fork for IVI
[profile/ivi/vim.git] / src / eval.c
1 /* vi:set ts=8 sts=4 sw=4:
2  *
3  * VIM - Vi IMproved    by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9
10 /*
11  * eval.c: Expression evaluation.
12  */
13
14 #include "vim.h"
15
16 #if defined(FEAT_EVAL) || defined(PROTO)
17
18 #ifdef AMIGA
19 # include <time.h>      /* for strftime() */
20 #endif
21
22 #ifdef VMS
23 # include <float.h>
24 #endif
25
26 #ifdef MACOS
27 # include <time.h>      /* for time_t */
28 #endif
29
30 #if defined(FEAT_FLOAT) && defined(HAVE_MATH_H)
31 # include <math.h>
32 #endif
33
34 #define DICT_MAXNEST 100        /* maximum nesting of lists and dicts */
35
36 #define DO_NOT_FREE_CNT 99999   /* refcount for dict or list that should not
37                                    be freed. */
38
39 /*
40  * In a hashtab item "hi_key" points to "di_key" in a dictitem.
41  * This avoids adding a pointer to the hashtab item.
42  * DI2HIKEY() converts a dictitem pointer to a hashitem key pointer.
43  * HIKEY2DI() converts a hashitem key pointer to a dictitem pointer.
44  * HI2DI() converts a hashitem pointer to a dictitem pointer.
45  */
46 static dictitem_T dumdi;
47 #define DI2HIKEY(di) ((di)->di_key)
48 #define HIKEY2DI(p)  ((dictitem_T *)(p - (dumdi.di_key - (char_u *)&dumdi)))
49 #define HI2DI(hi)     HIKEY2DI((hi)->hi_key)
50
51 /*
52  * Structure returned by get_lval() and used by set_var_lval().
53  * For a plain name:
54  *      "name"      points to the variable name.
55  *      "exp_name"  is NULL.
56  *      "tv"        is NULL
57  * For a magic braces name:
58  *      "name"      points to the expanded variable name.
59  *      "exp_name"  is non-NULL, to be freed later.
60  *      "tv"        is NULL
61  * For an index in a list:
62  *      "name"      points to the (expanded) variable name.
63  *      "exp_name"  NULL or non-NULL, to be freed later.
64  *      "tv"        points to the (first) list item value
65  *      "li"        points to the (first) list item
66  *      "range", "n1", "n2" and "empty2" indicate what items are used.
67  * For an existing Dict item:
68  *      "name"      points to the (expanded) variable name.
69  *      "exp_name"  NULL or non-NULL, to be freed later.
70  *      "tv"        points to the dict item value
71  *      "newkey"    is NULL
72  * For a non-existing Dict item:
73  *      "name"      points to the (expanded) variable name.
74  *      "exp_name"  NULL or non-NULL, to be freed later.
75  *      "tv"        points to the Dictionary typval_T
76  *      "newkey"    is the key for the new item.
77  */
78 typedef struct lval_S
79 {
80     char_u      *ll_name;       /* start of variable name (can be NULL) */
81     char_u      *ll_exp_name;   /* NULL or expanded name in allocated memory. */
82     typval_T    *ll_tv;         /* Typeval of item being used.  If "newkey"
83                                    isn't NULL it's the Dict to which to add
84                                    the item. */
85     listitem_T  *ll_li;         /* The list item or NULL. */
86     list_T      *ll_list;       /* The list or NULL. */
87     int         ll_range;       /* TRUE when a [i:j] range was used */
88     long        ll_n1;          /* First index for list */
89     long        ll_n2;          /* Second index for list range */
90     int         ll_empty2;      /* Second index is empty: [i:] */
91     dict_T      *ll_dict;       /* The Dictionary or NULL */
92     dictitem_T  *ll_di;         /* The dictitem or NULL */
93     char_u      *ll_newkey;     /* New key for Dict in alloc. mem or NULL. */
94 } lval_T;
95
96
97 static char *e_letunexp = N_("E18: Unexpected characters in :let");
98 static char *e_listidx = N_("E684: list index out of range: %ld");
99 static char *e_undefvar = N_("E121: Undefined variable: %s");
100 static char *e_missbrac = N_("E111: Missing ']'");
101 static char *e_listarg = N_("E686: Argument of %s must be a List");
102 static char *e_listdictarg = N_("E712: Argument of %s must be a List or Dictionary");
103 static char *e_emptykey = N_("E713: Cannot use empty key for Dictionary");
104 static char *e_listreq = N_("E714: List required");
105 static char *e_dictreq = N_("E715: Dictionary required");
106 static char *e_toomanyarg = N_("E118: Too many arguments for function: %s");
107 static char *e_dictkey = N_("E716: Key not present in Dictionary: %s");
108 static char *e_funcexts = N_("E122: Function %s already exists, add ! to replace it");
109 static char *e_funcdict = N_("E717: Dictionary entry already exists");
110 static char *e_funcref = N_("E718: Funcref required");
111 static char *e_dictrange = N_("E719: Cannot use [:] with a Dictionary");
112 static char *e_letwrong = N_("E734: Wrong variable type for %s=");
113 static char *e_nofunc = N_("E130: Unknown function: %s");
114 static char *e_illvar = N_("E461: Illegal variable name: %s");
115
116 /*
117  * All user-defined global variables are stored in dictionary "globvardict".
118  * "globvars_var" is the variable that is used for "g:".
119  */
120 static dict_T           globvardict;
121 static dictitem_T       globvars_var;
122 #define globvarht globvardict.dv_hashtab
123
124 /*
125  * Old Vim variables such as "v:version" are also available without the "v:".
126  * Also in functions.  We need a special hashtable for them.
127  */
128 static hashtab_T        compat_hashtab;
129
130 /* When using exists() don't auto-load a script. */
131 static int              no_autoload = FALSE;
132
133 /*
134  * When recursively copying lists and dicts we need to remember which ones we
135  * have done to avoid endless recursiveness.  This unique ID is used for that.
136  * The last bit is used for previous_funccal, ignored when comparing.
137  */
138 static int current_copyID = 0;
139 #define COPYID_INC 2
140 #define COPYID_MASK (~0x1)
141
142 /*
143  * Array to hold the hashtab with variables local to each sourced script.
144  * Each item holds a variable (nameless) that points to the dict_T.
145  */
146 typedef struct
147 {
148     dictitem_T  sv_var;
149     dict_T      sv_dict;
150 } scriptvar_T;
151
152 static garray_T     ga_scripts = {0, 0, sizeof(scriptvar_T *), 4, NULL};
153 #define SCRIPT_SV(id) (((scriptvar_T **)ga_scripts.ga_data)[(id) - 1])
154 #define SCRIPT_VARS(id) (SCRIPT_SV(id)->sv_dict.dv_hashtab)
155
156 static int echo_attr = 0;   /* attributes used for ":echo" */
157
158 /* Values for trans_function_name() argument: */
159 #define TFN_INT         1       /* internal function name OK */
160 #define TFN_QUIET       2       /* no error messages */
161
162 /*
163  * Structure to hold info for a user function.
164  */
165 typedef struct ufunc ufunc_T;
166
167 struct ufunc
168 {
169     int         uf_varargs;     /* variable nr of arguments */
170     int         uf_flags;
171     int         uf_calls;       /* nr of active calls */
172     garray_T    uf_args;        /* arguments */
173     garray_T    uf_lines;       /* function lines */
174 #ifdef FEAT_PROFILE
175     int         uf_profiling;   /* TRUE when func is being profiled */
176     /* profiling the function as a whole */
177     int         uf_tm_count;    /* nr of calls */
178     proftime_T  uf_tm_total;    /* time spent in function + children */
179     proftime_T  uf_tm_self;     /* time spent in function itself */
180     proftime_T  uf_tm_children; /* time spent in children this call */
181     /* profiling the function per line */
182     int         *uf_tml_count;  /* nr of times line was executed */
183     proftime_T  *uf_tml_total;  /* time spent in a line + children */
184     proftime_T  *uf_tml_self;   /* time spent in a line itself */
185     proftime_T  uf_tml_start;   /* start time for current line */
186     proftime_T  uf_tml_children; /* time spent in children for this line */
187     proftime_T  uf_tml_wait;    /* start wait time for current line */
188     int         uf_tml_idx;     /* index of line being timed; -1 if none */
189     int         uf_tml_execed;  /* line being timed was executed */
190 #endif
191     scid_T      uf_script_ID;   /* ID of script where function was defined,
192                                    used for s: variables */
193     int         uf_refcount;    /* for numbered function: reference count */
194     char_u      uf_name[1];     /* name of function (actually longer); can
195                                    start with <SNR>123_ (<SNR> is K_SPECIAL
196                                    KS_EXTRA KE_SNR) */
197 };
198
199 /* function flags */
200 #define FC_ABORT    1           /* abort function on error */
201 #define FC_RANGE    2           /* function accepts range */
202 #define FC_DICT     4           /* Dict function, uses "self" */
203
204 /*
205  * All user-defined functions are found in this hashtable.
206  */
207 static hashtab_T        func_hashtab;
208
209 /* The names of packages that once were loaded are remembered. */
210 static garray_T         ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
211
212 /* list heads for garbage collection */
213 static dict_T           *first_dict = NULL;     /* list of all dicts */
214 static list_T           *first_list = NULL;     /* list of all lists */
215
216 /* From user function to hashitem and back. */
217 static ufunc_T dumuf;
218 #define UF2HIKEY(fp) ((fp)->uf_name)
219 #define HIKEY2UF(p)  ((ufunc_T *)(p - (dumuf.uf_name - (char_u *)&dumuf)))
220 #define HI2UF(hi)     HIKEY2UF((hi)->hi_key)
221
222 #define FUNCARG(fp, j)  ((char_u **)(fp->uf_args.ga_data))[j]
223 #define FUNCLINE(fp, j) ((char_u **)(fp->uf_lines.ga_data))[j]
224
225 #define MAX_FUNC_ARGS   20      /* maximum number of function arguments */
226 #define VAR_SHORT_LEN   20      /* short variable name length */
227 #define FIXVAR_CNT      12      /* number of fixed variables */
228
229 /* structure to hold info for a function that is currently being executed. */
230 typedef struct funccall_S funccall_T;
231
232 struct funccall_S
233 {
234     ufunc_T     *func;          /* function being called */
235     int         linenr;         /* next line to be executed */
236     int         returned;       /* ":return" used */
237     struct                      /* fixed variables for arguments */
238     {
239         dictitem_T      var;            /* variable (without room for name) */
240         char_u  room[VAR_SHORT_LEN];    /* room for the name */
241     } fixvar[FIXVAR_CNT];
242     dict_T      l_vars;         /* l: local function variables */
243     dictitem_T  l_vars_var;     /* variable for l: scope */
244     dict_T      l_avars;        /* a: argument variables */
245     dictitem_T  l_avars_var;    /* variable for a: scope */
246     list_T      l_varlist;      /* list for a:000 */
247     listitem_T  l_listitems[MAX_FUNC_ARGS];     /* listitems for a:000 */
248     typval_T    *rettv;         /* return value */
249     linenr_T    breakpoint;     /* next line with breakpoint or zero */
250     int         dbg_tick;       /* debug_tick when breakpoint was set */
251     int         level;          /* top nesting level of executed function */
252 #ifdef FEAT_PROFILE
253     proftime_T  prof_child;     /* time spent in a child */
254 #endif
255     funccall_T  *caller;        /* calling function or NULL */
256 };
257
258 /*
259  * Info used by a ":for" loop.
260  */
261 typedef struct
262 {
263     int         fi_semicolon;   /* TRUE if ending in '; var]' */
264     int         fi_varcount;    /* nr of variables in the list */
265     listwatch_T fi_lw;          /* keep an eye on the item used. */
266     list_T      *fi_list;       /* list being used */
267 } forinfo_T;
268
269 /*
270  * Struct used by trans_function_name()
271  */
272 typedef struct
273 {
274     dict_T      *fd_dict;       /* Dictionary used */
275     char_u      *fd_newkey;     /* new key in "dict" in allocated memory */
276     dictitem_T  *fd_di;         /* Dictionary item used */
277 } funcdict_T;
278
279
280 /*
281  * Array to hold the value of v: variables.
282  * The value is in a dictitem, so that it can also be used in the v: scope.
283  * The reason to use this table anyway is for very quick access to the
284  * variables with the VV_ defines.
285  */
286 #include "version.h"
287
288 /* values for vv_flags: */
289 #define VV_COMPAT       1       /* compatible, also used without "v:" */
290 #define VV_RO           2       /* read-only */
291 #define VV_RO_SBX       4       /* read-only in the sandbox */
292
293 #define VV_NAME(s, t)   s, {{t, 0, {0}}, 0, {0}}, {0}
294
295 static struct vimvar
296 {
297     char        *vv_name;       /* name of variable, without v: */
298     dictitem_T  vv_di;          /* value and name for key */
299     char        vv_filler[16];  /* space for LONGEST name below!!! */
300     char        vv_flags;       /* VV_COMPAT, VV_RO, VV_RO_SBX */
301 } vimvars[VV_LEN] =
302 {
303     /*
304      * The order here must match the VV_ defines in vim.h!
305      * Initializing a union does not work, leave tv.vval empty to get zero's.
306      */
307     {VV_NAME("count",            VAR_NUMBER), VV_COMPAT+VV_RO},
308     {VV_NAME("count1",           VAR_NUMBER), VV_RO},
309     {VV_NAME("prevcount",        VAR_NUMBER), VV_RO},
310     {VV_NAME("errmsg",           VAR_STRING), VV_COMPAT},
311     {VV_NAME("warningmsg",       VAR_STRING), 0},
312     {VV_NAME("statusmsg",        VAR_STRING), 0},
313     {VV_NAME("shell_error",      VAR_NUMBER), VV_COMPAT+VV_RO},
314     {VV_NAME("this_session",     VAR_STRING), VV_COMPAT},
315     {VV_NAME("version",          VAR_NUMBER), VV_COMPAT+VV_RO},
316     {VV_NAME("lnum",             VAR_NUMBER), VV_RO_SBX},
317     {VV_NAME("termresponse",     VAR_STRING), VV_RO},
318     {VV_NAME("fname",            VAR_STRING), VV_RO},
319     {VV_NAME("lang",             VAR_STRING), VV_RO},
320     {VV_NAME("lc_time",          VAR_STRING), VV_RO},
321     {VV_NAME("ctype",            VAR_STRING), VV_RO},
322     {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
323     {VV_NAME("charconvert_to",   VAR_STRING), VV_RO},
324     {VV_NAME("fname_in",         VAR_STRING), VV_RO},
325     {VV_NAME("fname_out",        VAR_STRING), VV_RO},
326     {VV_NAME("fname_new",        VAR_STRING), VV_RO},
327     {VV_NAME("fname_diff",       VAR_STRING), VV_RO},
328     {VV_NAME("cmdarg",           VAR_STRING), VV_RO},
329     {VV_NAME("foldstart",        VAR_NUMBER), VV_RO_SBX},
330     {VV_NAME("foldend",          VAR_NUMBER), VV_RO_SBX},
331     {VV_NAME("folddashes",       VAR_STRING), VV_RO_SBX},
332     {VV_NAME("foldlevel",        VAR_NUMBER), VV_RO_SBX},
333     {VV_NAME("progname",         VAR_STRING), VV_RO},
334     {VV_NAME("servername",       VAR_STRING), VV_RO},
335     {VV_NAME("dying",            VAR_NUMBER), VV_RO},
336     {VV_NAME("exception",        VAR_STRING), VV_RO},
337     {VV_NAME("throwpoint",       VAR_STRING), VV_RO},
338     {VV_NAME("register",         VAR_STRING), VV_RO},
339     {VV_NAME("cmdbang",          VAR_NUMBER), VV_RO},
340     {VV_NAME("insertmode",       VAR_STRING), VV_RO},
341     {VV_NAME("val",              VAR_UNKNOWN), VV_RO},
342     {VV_NAME("key",              VAR_UNKNOWN), VV_RO},
343     {VV_NAME("profiling",        VAR_NUMBER), VV_RO},
344     {VV_NAME("fcs_reason",       VAR_STRING), VV_RO},
345     {VV_NAME("fcs_choice",       VAR_STRING), 0},
346     {VV_NAME("beval_bufnr",      VAR_NUMBER), VV_RO},
347     {VV_NAME("beval_winnr",      VAR_NUMBER), VV_RO},
348     {VV_NAME("beval_lnum",       VAR_NUMBER), VV_RO},
349     {VV_NAME("beval_col",        VAR_NUMBER), VV_RO},
350     {VV_NAME("beval_text",       VAR_STRING), VV_RO},
351     {VV_NAME("scrollstart",      VAR_STRING), 0},
352     {VV_NAME("swapname",         VAR_STRING), VV_RO},
353     {VV_NAME("swapchoice",       VAR_STRING), 0},
354     {VV_NAME("swapcommand",      VAR_STRING), VV_RO},
355     {VV_NAME("char",             VAR_STRING), 0},
356     {VV_NAME("mouse_win",        VAR_NUMBER), 0},
357     {VV_NAME("mouse_lnum",       VAR_NUMBER), 0},
358     {VV_NAME("mouse_col",        VAR_NUMBER), 0},
359     {VV_NAME("operator",         VAR_STRING), VV_RO},
360     {VV_NAME("searchforward",    VAR_NUMBER), 0},
361     {VV_NAME("oldfiles",         VAR_LIST), 0},
362     {VV_NAME("windowid",         VAR_NUMBER), VV_RO},
363 };
364
365 /* shorthand */
366 #define vv_type         vv_di.di_tv.v_type
367 #define vv_nr           vv_di.di_tv.vval.v_number
368 #define vv_float        vv_di.di_tv.vval.v_float
369 #define vv_str          vv_di.di_tv.vval.v_string
370 #define vv_list         vv_di.di_tv.vval.v_list
371 #define vv_tv           vv_di.di_tv
372
373 /*
374  * The v: variables are stored in dictionary "vimvardict".
375  * "vimvars_var" is the variable that is used for the "l:" scope.
376  */
377 static dict_T           vimvardict;
378 static dictitem_T       vimvars_var;
379 #define vimvarht  vimvardict.dv_hashtab
380
381 static void prepare_vimvar __ARGS((int idx, typval_T *save_tv));
382 static void restore_vimvar __ARGS((int idx, typval_T *save_tv));
383 static int ex_let_vars __ARGS((char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars));
384 static char_u *skip_var_list __ARGS((char_u *arg, int *var_count, int *semicolon));
385 static char_u *skip_var_one __ARGS((char_u *arg));
386 static void list_hashtable_vars __ARGS((hashtab_T *ht, char_u *prefix, int empty, int *first));
387 static void list_glob_vars __ARGS((int *first));
388 static void list_buf_vars __ARGS((int *first));
389 static void list_win_vars __ARGS((int *first));
390 #ifdef FEAT_WINDOWS
391 static void list_tab_vars __ARGS((int *first));
392 #endif
393 static void list_vim_vars __ARGS((int *first));
394 static void list_script_vars __ARGS((int *first));
395 static void list_func_vars __ARGS((int *first));
396 static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg, int *first));
397 static char_u *ex_let_one __ARGS((char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op));
398 static int check_changedtick __ARGS((char_u *arg));
399 static char_u *get_lval __ARGS((char_u *name, typval_T *rettv, lval_T *lp, int unlet, int skip, int quiet, int fne_flags));
400 static void clear_lval __ARGS((lval_T *lp));
401 static void set_var_lval __ARGS((lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op));
402 static int tv_op __ARGS((typval_T *tv1, typval_T *tv2, char_u  *op));
403 static void list_add_watch __ARGS((list_T *l, listwatch_T *lw));
404 static void list_rem_watch __ARGS((list_T *l, listwatch_T *lwrem));
405 static void list_fix_watch __ARGS((list_T *l, listitem_T *item));
406 static void ex_unletlock __ARGS((exarg_T *eap, char_u *argstart, int deep));
407 static int do_unlet_var __ARGS((lval_T *lp, char_u *name_end, int forceit));
408 static int do_lock_var __ARGS((lval_T *lp, char_u *name_end, int deep, int lock));
409 static void item_lock __ARGS((typval_T *tv, int deep, int lock));
410 static int tv_islocked __ARGS((typval_T *tv));
411
412 static int eval0 __ARGS((char_u *arg,  typval_T *rettv, char_u **nextcmd, int evaluate));
413 static int eval1 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
414 static int eval2 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
415 static int eval3 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
416 static int eval4 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
417 static int eval5 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
418 static int eval6 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
419 static int eval7 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
420
421 static int eval_index __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
422 static int get_option_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
423 static int get_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
424 static int get_lit_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
425 static int get_list_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
426 static int rettv_list_alloc __ARGS((typval_T *rettv));
427 static listitem_T *listitem_alloc __ARGS((void));
428 static void listitem_free __ARGS((listitem_T *item));
429 static void listitem_remove __ARGS((list_T *l, listitem_T *item));
430 static long list_len __ARGS((list_T *l));
431 static int list_equal __ARGS((list_T *l1, list_T *l2, int ic, int recursive));
432 static int dict_equal __ARGS((dict_T *d1, dict_T *d2, int ic, int recursive));
433 static int tv_equal __ARGS((typval_T *tv1, typval_T *tv2, int ic, int recursive));
434 static listitem_T *list_find __ARGS((list_T *l, long n));
435 static long list_find_nr __ARGS((list_T *l, long idx, int *errorp));
436 static long list_idx_of_item __ARGS((list_T *l, listitem_T *item));
437 static void list_append __ARGS((list_T *l, listitem_T *item));
438 static int list_append_number __ARGS((list_T *l, varnumber_T n));
439 static int list_insert_tv __ARGS((list_T *l, typval_T *tv, listitem_T *item));
440 static int list_extend __ARGS((list_T   *l1, list_T *l2, listitem_T *bef));
441 static int list_concat __ARGS((list_T *l1, list_T *l2, typval_T *tv));
442 static list_T *list_copy __ARGS((list_T *orig, int deep, int copyID));
443 static void list_remove __ARGS((list_T *l, listitem_T *item, listitem_T *item2));
444 static char_u *list2string __ARGS((typval_T *tv, int copyID));
445 static int list_join __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo, int copyID));
446 static int free_unref_items __ARGS((int copyID));
447 static void set_ref_in_ht __ARGS((hashtab_T *ht, int copyID));
448 static void set_ref_in_list __ARGS((list_T *l, int copyID));
449 static void set_ref_in_item __ARGS((typval_T *tv, int copyID));
450 static int rettv_dict_alloc __ARGS((typval_T *rettv));
451 static void dict_free __ARGS((dict_T *d, int recurse));
452 static dictitem_T *dictitem_copy __ARGS((dictitem_T *org));
453 static void dictitem_remove __ARGS((dict_T *dict, dictitem_T *item));
454 static dict_T *dict_copy __ARGS((dict_T *orig, int deep, int copyID));
455 static long dict_len __ARGS((dict_T *d));
456 static char_u *dict2string __ARGS((typval_T *tv, int copyID));
457 static int get_dict_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
458 static char_u *echo_string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
459 static char_u *tv2string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
460 static char_u *string_quote __ARGS((char_u *str, int function));
461 #ifdef FEAT_FLOAT
462 static int string2float __ARGS((char_u *text, float_T *value));
463 #endif
464 static int get_env_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
465 static int find_internal_func __ARGS((char_u *name));
466 static char_u *deref_func_name __ARGS((char_u *name, int *lenp));
467 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));
468 static int call_func __ARGS((char_u *funcname, int len, typval_T *rettv, int argcount, typval_T *argvars, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
469 static void emsg_funcname __ARGS((char *ermsg, char_u *name));
470 static int non_zero_arg __ARGS((typval_T *argvars));
471
472 #ifdef FEAT_FLOAT
473 static void f_abs __ARGS((typval_T *argvars, typval_T *rettv));
474 static void f_acos __ARGS((typval_T *argvars, typval_T *rettv));
475 #endif
476 static void f_add __ARGS((typval_T *argvars, typval_T *rettv));
477 static void f_and __ARGS((typval_T *argvars, typval_T *rettv));
478 static void f_append __ARGS((typval_T *argvars, typval_T *rettv));
479 static void f_argc __ARGS((typval_T *argvars, typval_T *rettv));
480 static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv));
481 static void f_argv __ARGS((typval_T *argvars, typval_T *rettv));
482 #ifdef FEAT_FLOAT
483 static void f_asin __ARGS((typval_T *argvars, typval_T *rettv));
484 static void f_atan __ARGS((typval_T *argvars, typval_T *rettv));
485 static void f_atan2 __ARGS((typval_T *argvars, typval_T *rettv));
486 #endif
487 static void f_browse __ARGS((typval_T *argvars, typval_T *rettv));
488 static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv));
489 static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv));
490 static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv));
491 static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv));
492 static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv));
493 static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv));
494 static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv));
495 static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv));
496 static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv));
497 static void f_call __ARGS((typval_T *argvars, typval_T *rettv));
498 #ifdef FEAT_FLOAT
499 static void f_ceil __ARGS((typval_T *argvars, typval_T *rettv));
500 #endif
501 static void f_changenr __ARGS((typval_T *argvars, typval_T *rettv));
502 static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv));
503 static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv));
504 static void f_clearmatches __ARGS((typval_T *argvars, typval_T *rettv));
505 static void f_col __ARGS((typval_T *argvars, typval_T *rettv));
506 #if defined(FEAT_INS_EXPAND)
507 static void f_complete __ARGS((typval_T *argvars, typval_T *rettv));
508 static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv));
509 static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv));
510 #endif
511 static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_copy __ARGS((typval_T *argvars, typval_T *rettv));
513 #ifdef FEAT_FLOAT
514 static void f_cos __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_cosh __ARGS((typval_T *argvars, typval_T *rettv));
516 #endif
517 static void f_count __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv));
520 static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv));
521 static void f_delete __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv));
523 static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv));
524 static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv));
525 static void f_empty __ARGS((typval_T *argvars, typval_T *rettv));
526 static void f_escape __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_eval __ARGS((typval_T *argvars, typval_T *rettv));
528 static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv));
529 static void f_executable __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_exists __ARGS((typval_T *argvars, typval_T *rettv));
531 #ifdef FEAT_FLOAT
532 static void f_exp __ARGS((typval_T *argvars, typval_T *rettv));
533 #endif
534 static void f_expand __ARGS((typval_T *argvars, typval_T *rettv));
535 static void f_extend __ARGS((typval_T *argvars, typval_T *rettv));
536 static void f_feedkeys __ARGS((typval_T *argvars, typval_T *rettv));
537 static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_filter __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv));
542 #ifdef FEAT_FLOAT
543 static void f_float2nr __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_floor __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_fmod __ARGS((typval_T *argvars, typval_T *rettv));
546 #endif
547 static void f_fnameescape __ARGS((typval_T *argvars, typval_T *rettv));
548 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
549 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
551 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
552 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_getpid __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_gettabvar __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
590 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
591 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
592 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
593 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
594 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
595 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
596 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
603 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
604 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
605 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
606 static void f_invert __ARGS((typval_T *argvars, typval_T *rettv));
607 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
608 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
609 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
610 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
611 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
618 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
619 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
620 #ifdef FEAT_FLOAT
621 static void f_log __ARGS((typval_T *argvars, typval_T *rettv));
622 static void f_log10 __ARGS((typval_T *argvars, typval_T *rettv));
623 #endif
624 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
625 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
626 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
627 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
628 static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv));
629 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
630 static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv));
631 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
632 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
633 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
634 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
635 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
636 #ifdef vim_mkdir
637 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
638 #endif
639 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
640 #ifdef FEAT_MZSCHEME
641 static void f_mzeval __ARGS((typval_T *argvars, typval_T *rettv));
642 #endif
643 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
644 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
645 static void f_or __ARGS((typval_T *argvars, typval_T *rettv));
646 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
647 #ifdef FEAT_FLOAT
648 static void f_pow __ARGS((typval_T *argvars, typval_T *rettv));
649 #endif
650 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
651 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
652 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
653 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
654 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
655 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
656 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
657 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
667 #ifdef FEAT_FLOAT
668 static void f_round __ARGS((typval_T *argvars, typval_T *rettv));
669 #endif
670 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
671 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
672 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
673 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
674 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
675 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
676 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
677 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
678 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
679 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
680 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
681 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
682 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
683 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
684 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
685 static void f_settabvar __ARGS((typval_T *argvars, typval_T *rettv));
686 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
687 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
688 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
689 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
690 #ifdef FEAT_FLOAT
691 static void f_sin __ARGS((typval_T *argvars, typval_T *rettv));
692 static void f_sinh __ARGS((typval_T *argvars, typval_T *rettv));
693 #endif
694 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
695 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
696 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
697 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
698 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
699 #ifdef FEAT_FLOAT
700 static void f_sqrt __ARGS((typval_T *argvars, typval_T *rettv));
701 static void f_str2float __ARGS((typval_T *argvars, typval_T *rettv));
702 #endif
703 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
704 static void f_strchars __ARGS((typval_T *argvars, typval_T *rettv));
705 #ifdef HAVE_STRFTIME
706 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
707 #endif
708 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
709 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
710 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
711 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
712 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
713 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
714 static void f_strdisplaywidth __ARGS((typval_T *argvars, typval_T *rettv));
715 static void f_strwidth __ARGS((typval_T *argvars, typval_T *rettv));
716 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
717 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
718 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
719 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
720 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
721 static void f_synstack __ARGS((typval_T *argvars, typval_T *rettv));
722 static void f_synconcealed __ARGS((typval_T *argvars, typval_T *rettv));
723 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
724 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
725 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
726 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
727 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
728 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
729 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
730 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
731 #ifdef FEAT_FLOAT
732 static void f_tan __ARGS((typval_T *argvars, typval_T *rettv));
733 static void f_tanh __ARGS((typval_T *argvars, typval_T *rettv));
734 #endif
735 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
736 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
737 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
738 #ifdef FEAT_FLOAT
739 static void f_trunc __ARGS((typval_T *argvars, typval_T *rettv));
740 #endif
741 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
742 static void f_undofile __ARGS((typval_T *argvars, typval_T *rettv));
743 static void f_undotree __ARGS((typval_T *argvars, typval_T *rettv));
744 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
745 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
746 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
747 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
748 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
749 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
750 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
751 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
752 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
753 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
754 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
755 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
756 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
757 static void f_xor __ARGS((typval_T *argvars, typval_T *rettv));
758
759 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
760 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
761 static int get_env_len __ARGS((char_u **arg));
762 static int get_id_len __ARGS((char_u **arg));
763 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
764 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
765 #define FNE_INCL_BR     1       /* find_name_end(): include [] in name */
766 #define FNE_CHECK_START 2       /* find_name_end(): check name starts with
767                                    valid character */
768 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
769 static int eval_isnamec __ARGS((int c));
770 static int eval_isnamec1 __ARGS((int c));
771 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
772 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
773 static typval_T *alloc_tv __ARGS((void));
774 static typval_T *alloc_string_tv __ARGS((char_u *string));
775 static void init_tv __ARGS((typval_T *varp));
776 static long get_tv_number __ARGS((typval_T *varp));
777 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
778 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
779 static char_u *get_tv_string __ARGS((typval_T *varp));
780 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
781 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
782 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
783 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
784 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
785 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
786 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
787 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
788 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
789 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
790 static int var_check_ro __ARGS((int flags, char_u *name));
791 static int var_check_fixed __ARGS((int flags, char_u *name));
792 static int var_check_func_name __ARGS((char_u *name, int new_var));
793 static int valid_varname __ARGS((char_u *varname));
794 static int tv_check_lock __ARGS((int lock, char_u *name));
795 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
796 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
797 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
798 static int eval_fname_script __ARGS((char_u *p));
799 static int eval_fname_sid __ARGS((char_u *p));
800 static void list_func_head __ARGS((ufunc_T *fp, int indent));
801 static ufunc_T *find_func __ARGS((char_u *name));
802 static int function_exists __ARGS((char_u *name));
803 static int builtin_function __ARGS((char_u *name));
804 #ifdef FEAT_PROFILE
805 static void func_do_profile __ARGS((ufunc_T *fp));
806 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
807 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
808 static int
809 # ifdef __BORLANDC__
810     _RTLENTRYF
811 # endif
812         prof_total_cmp __ARGS((const void *s1, const void *s2));
813 static int
814 # ifdef __BORLANDC__
815     _RTLENTRYF
816 # endif
817         prof_self_cmp __ARGS((const void *s1, const void *s2));
818 #endif
819 static int script_autoload __ARGS((char_u *name, int reload));
820 static char_u *autoload_name __ARGS((char_u *name));
821 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
822 static void func_free __ARGS((ufunc_T *fp));
823 static void func_unref __ARGS((char_u *name));
824 static void func_ref __ARGS((char_u *name));
825 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));
826 static int can_free_funccal __ARGS((funccall_T *fc, int copyID)) ;
827 static void free_funccal __ARGS((funccall_T *fc, int free_val));
828 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
829 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
830 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
831 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
832 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
833 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
834
835
836 #ifdef EBCDIC
837 static int compare_func_name __ARGS((const void *s1, const void *s2));
838 static void sortFunctions __ARGS(());
839 #endif
840
841
842 /* Character used as separated in autoload function/variable names. */
843 #define AUTOLOAD_CHAR '#'
844
845 /*
846  * Initialize the global and v: variables.
847  */
848     void
849 eval_init()
850 {
851     int             i;
852     struct vimvar   *p;
853
854     init_var_dict(&globvardict, &globvars_var);
855     init_var_dict(&vimvardict, &vimvars_var);
856     vimvardict.dv_lock = VAR_FIXED;
857     hash_init(&compat_hashtab);
858     hash_init(&func_hashtab);
859
860     for (i = 0; i < VV_LEN; ++i)
861     {
862         p = &vimvars[i];
863         STRCPY(p->vv_di.di_key, p->vv_name);
864         if (p->vv_flags & VV_RO)
865             p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
866         else if (p->vv_flags & VV_RO_SBX)
867             p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
868         else
869             p->vv_di.di_flags = DI_FLAGS_FIX;
870
871         /* add to v: scope dict, unless the value is not always available */
872         if (p->vv_type != VAR_UNKNOWN)
873             hash_add(&vimvarht, p->vv_di.di_key);
874         if (p->vv_flags & VV_COMPAT)
875             /* add to compat scope dict */
876             hash_add(&compat_hashtab, p->vv_di.di_key);
877     }
878     set_vim_var_nr(VV_SEARCHFORWARD, 1L);
879
880 #ifdef EBCDIC
881     /*
882      * Sort the function table, to enable binary search.
883      */
884     sortFunctions();
885 #endif
886 }
887
888 #if defined(EXITFREE) || defined(PROTO)
889     void
890 eval_clear()
891 {
892     int             i;
893     struct vimvar   *p;
894
895     for (i = 0; i < VV_LEN; ++i)
896     {
897         p = &vimvars[i];
898         if (p->vv_di.di_tv.v_type == VAR_STRING)
899         {
900             vim_free(p->vv_str);
901             p->vv_str = NULL;
902         }
903         else if (p->vv_di.di_tv.v_type == VAR_LIST)
904         {
905             list_unref(p->vv_list);
906             p->vv_list = NULL;
907         }
908     }
909     hash_clear(&vimvarht);
910     hash_init(&vimvarht);  /* garbage_collect() will access it */
911     hash_clear(&compat_hashtab);
912
913     free_scriptnames();
914     free_locales();
915
916     /* global variables */
917     vars_clear(&globvarht);
918
919     /* autoloaded script names */
920     ga_clear_strings(&ga_loaded);
921
922     /* script-local variables */
923     for (i = 1; i <= ga_scripts.ga_len; ++i)
924     {
925         vars_clear(&SCRIPT_VARS(i));
926         vim_free(SCRIPT_SV(i));
927     }
928     ga_clear(&ga_scripts);
929
930     /* unreferenced lists and dicts */
931     (void)garbage_collect();
932
933     /* functions */
934     free_all_functions();
935     hash_clear(&func_hashtab);
936 }
937 #endif
938
939 /*
940  * Return the name of the executed function.
941  */
942     char_u *
943 func_name(cookie)
944     void *cookie;
945 {
946     return ((funccall_T *)cookie)->func->uf_name;
947 }
948
949 /*
950  * Return the address holding the next breakpoint line for a funccall cookie.
951  */
952     linenr_T *
953 func_breakpoint(cookie)
954     void *cookie;
955 {
956     return &((funccall_T *)cookie)->breakpoint;
957 }
958
959 /*
960  * Return the address holding the debug tick for a funccall cookie.
961  */
962     int *
963 func_dbg_tick(cookie)
964     void *cookie;
965 {
966     return &((funccall_T *)cookie)->dbg_tick;
967 }
968
969 /*
970  * Return the nesting level for a funccall cookie.
971  */
972     int
973 func_level(cookie)
974     void *cookie;
975 {
976     return ((funccall_T *)cookie)->level;
977 }
978
979 /* pointer to funccal for currently active function */
980 funccall_T *current_funccal = NULL;
981
982 /* pointer to list of previously used funccal, still around because some
983  * item in it is still being used. */
984 funccall_T *previous_funccal = NULL;
985
986 /*
987  * Return TRUE when a function was ended by a ":return" command.
988  */
989     int
990 current_func_returned()
991 {
992     return current_funccal->returned;
993 }
994
995
996 /*
997  * Set an internal variable to a string value. Creates the variable if it does
998  * not already exist.
999  */
1000     void
1001 set_internal_string_var(name, value)
1002     char_u      *name;
1003     char_u      *value;
1004 {
1005     char_u      *val;
1006     typval_T    *tvp;
1007
1008     val = vim_strsave(value);
1009     if (val != NULL)
1010     {
1011         tvp = alloc_string_tv(val);
1012         if (tvp != NULL)
1013         {
1014             set_var(name, tvp, FALSE);
1015             free_tv(tvp);
1016         }
1017     }
1018 }
1019
1020 static lval_T   *redir_lval = NULL;
1021 static garray_T redir_ga;       /* only valid when redir_lval is not NULL */
1022 static char_u   *redir_endp = NULL;
1023 static char_u   *redir_varname = NULL;
1024
1025 /*
1026  * Start recording command output to a variable
1027  * Returns OK if successfully completed the setup.  FAIL otherwise.
1028  */
1029     int
1030 var_redir_start(name, append)
1031     char_u      *name;
1032     int         append;         /* append to an existing variable */
1033 {
1034     int         save_emsg;
1035     int         err;
1036     typval_T    tv;
1037
1038     /* Catch a bad name early. */
1039     if (!eval_isnamec1(*name))
1040     {
1041         EMSG(_(e_invarg));
1042         return FAIL;
1043     }
1044
1045     /* Make a copy of the name, it is used in redir_lval until redir ends. */
1046     redir_varname = vim_strsave(name);
1047     if (redir_varname == NULL)
1048         return FAIL;
1049
1050     redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
1051     if (redir_lval == NULL)
1052     {
1053         var_redir_stop();
1054         return FAIL;
1055     }
1056
1057     /* The output is stored in growarray "redir_ga" until redirection ends. */
1058     ga_init2(&redir_ga, (int)sizeof(char), 500);
1059
1060     /* Parse the variable name (can be a dict or list entry). */
1061     redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
1062                                                              FNE_CHECK_START);
1063     if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
1064     {
1065         clear_lval(redir_lval);
1066         if (redir_endp != NULL && *redir_endp != NUL)
1067             /* Trailing characters are present after the variable name */
1068             EMSG(_(e_trailing));
1069         else
1070             EMSG(_(e_invarg));
1071         redir_endp = NULL;  /* don't store a value, only cleanup */
1072         var_redir_stop();
1073         return FAIL;
1074     }
1075
1076     /* check if we can write to the variable: set it to or append an empty
1077      * string */
1078     save_emsg = did_emsg;
1079     did_emsg = FALSE;
1080     tv.v_type = VAR_STRING;
1081     tv.vval.v_string = (char_u *)"";
1082     if (append)
1083         set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
1084     else
1085         set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
1086     clear_lval(redir_lval);
1087     err = did_emsg;
1088     did_emsg |= save_emsg;
1089     if (err)
1090     {
1091         redir_endp = NULL;  /* don't store a value, only cleanup */
1092         var_redir_stop();
1093         return FAIL;
1094     }
1095
1096     return OK;
1097 }
1098
1099 /*
1100  * Append "value[value_len]" to the variable set by var_redir_start().
1101  * The actual appending is postponed until redirection ends, because the value
1102  * appended may in fact be the string we write to, changing it may cause freed
1103  * memory to be used:
1104  *   :redir => foo
1105  *   :let foo
1106  *   :redir END
1107  */
1108     void
1109 var_redir_str(value, value_len)
1110     char_u      *value;
1111     int         value_len;
1112 {
1113     int         len;
1114
1115     if (redir_lval == NULL)
1116         return;
1117
1118     if (value_len == -1)
1119         len = (int)STRLEN(value);       /* Append the entire string */
1120     else
1121         len = value_len;                /* Append only "value_len" characters */
1122
1123     if (ga_grow(&redir_ga, len) == OK)
1124     {
1125         mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1126         redir_ga.ga_len += len;
1127     }
1128     else
1129         var_redir_stop();
1130 }
1131
1132 /*
1133  * Stop redirecting command output to a variable.
1134  * Frees the allocated memory.
1135  */
1136     void
1137 var_redir_stop()
1138 {
1139     typval_T    tv;
1140
1141     if (redir_lval != NULL)
1142     {
1143         /* If there was no error: assign the text to the variable. */
1144         if (redir_endp != NULL)
1145         {
1146             ga_append(&redir_ga, NUL);  /* Append the trailing NUL. */
1147             tv.v_type = VAR_STRING;
1148             tv.vval.v_string = redir_ga.ga_data;
1149             /* Call get_lval() again, if it's inside a Dict or List it may
1150              * have changed. */
1151             redir_endp = get_lval(redir_varname, NULL, redir_lval,
1152                                         FALSE, FALSE, FALSE, FNE_CHECK_START);
1153             if (redir_endp != NULL && redir_lval->ll_name != NULL)
1154                 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1155             clear_lval(redir_lval);
1156         }
1157
1158         /* free the collected output */
1159         vim_free(redir_ga.ga_data);
1160         redir_ga.ga_data = NULL;
1161
1162         vim_free(redir_lval);
1163         redir_lval = NULL;
1164     }
1165     vim_free(redir_varname);
1166     redir_varname = NULL;
1167 }
1168
1169 # if defined(FEAT_MBYTE) || defined(PROTO)
1170     int
1171 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1172     char_u      *enc_from;
1173     char_u      *enc_to;
1174     char_u      *fname_from;
1175     char_u      *fname_to;
1176 {
1177     int         err = FALSE;
1178
1179     set_vim_var_string(VV_CC_FROM, enc_from, -1);
1180     set_vim_var_string(VV_CC_TO, enc_to, -1);
1181     set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1182     set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1183     if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1184         err = TRUE;
1185     set_vim_var_string(VV_CC_FROM, NULL, -1);
1186     set_vim_var_string(VV_CC_TO, NULL, -1);
1187     set_vim_var_string(VV_FNAME_IN, NULL, -1);
1188     set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1189
1190     if (err)
1191         return FAIL;
1192     return OK;
1193 }
1194 # endif
1195
1196 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1197     int
1198 eval_printexpr(fname, args)
1199     char_u      *fname;
1200     char_u      *args;
1201 {
1202     int         err = FALSE;
1203
1204     set_vim_var_string(VV_FNAME_IN, fname, -1);
1205     set_vim_var_string(VV_CMDARG, args, -1);
1206     if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1207         err = TRUE;
1208     set_vim_var_string(VV_FNAME_IN, NULL, -1);
1209     set_vim_var_string(VV_CMDARG, NULL, -1);
1210
1211     if (err)
1212     {
1213         mch_remove(fname);
1214         return FAIL;
1215     }
1216     return OK;
1217 }
1218 # endif
1219
1220 # if defined(FEAT_DIFF) || defined(PROTO)
1221     void
1222 eval_diff(origfile, newfile, outfile)
1223     char_u      *origfile;
1224     char_u      *newfile;
1225     char_u      *outfile;
1226 {
1227     int         err = FALSE;
1228
1229     set_vim_var_string(VV_FNAME_IN, origfile, -1);
1230     set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1231     set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1232     (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1233     set_vim_var_string(VV_FNAME_IN, NULL, -1);
1234     set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1235     set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1236 }
1237
1238     void
1239 eval_patch(origfile, difffile, outfile)
1240     char_u      *origfile;
1241     char_u      *difffile;
1242     char_u      *outfile;
1243 {
1244     int         err;
1245
1246     set_vim_var_string(VV_FNAME_IN, origfile, -1);
1247     set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1248     set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1249     (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1250     set_vim_var_string(VV_FNAME_IN, NULL, -1);
1251     set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1252     set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1253 }
1254 # endif
1255
1256 /*
1257  * Top level evaluation function, returning a boolean.
1258  * Sets "error" to TRUE if there was an error.
1259  * Return TRUE or FALSE.
1260  */
1261     int
1262 eval_to_bool(arg, error, nextcmd, skip)
1263     char_u      *arg;
1264     int         *error;
1265     char_u      **nextcmd;
1266     int         skip;       /* only parse, don't execute */
1267 {
1268     typval_T    tv;
1269     int         retval = FALSE;
1270
1271     if (skip)
1272         ++emsg_skip;
1273     if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1274         *error = TRUE;
1275     else
1276     {
1277         *error = FALSE;
1278         if (!skip)
1279         {
1280             retval = (get_tv_number_chk(&tv, error) != 0);
1281             clear_tv(&tv);
1282         }
1283     }
1284     if (skip)
1285         --emsg_skip;
1286
1287     return retval;
1288 }
1289
1290 /*
1291  * Top level evaluation function, returning a string.  If "skip" is TRUE,
1292  * only parsing to "nextcmd" is done, without reporting errors.  Return
1293  * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1294  */
1295     char_u *
1296 eval_to_string_skip(arg, nextcmd, skip)
1297     char_u      *arg;
1298     char_u      **nextcmd;
1299     int         skip;       /* only parse, don't execute */
1300 {
1301     typval_T    tv;
1302     char_u      *retval;
1303
1304     if (skip)
1305         ++emsg_skip;
1306     if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1307         retval = NULL;
1308     else
1309     {
1310         retval = vim_strsave(get_tv_string(&tv));
1311         clear_tv(&tv);
1312     }
1313     if (skip)
1314         --emsg_skip;
1315
1316     return retval;
1317 }
1318
1319 /*
1320  * Skip over an expression at "*pp".
1321  * Return FAIL for an error, OK otherwise.
1322  */
1323     int
1324 skip_expr(pp)
1325     char_u      **pp;
1326 {
1327     typval_T    rettv;
1328
1329     *pp = skipwhite(*pp);
1330     return eval1(pp, &rettv, FALSE);
1331 }
1332
1333 /*
1334  * Top level evaluation function, returning a string.
1335  * When "convert" is TRUE convert a List into a sequence of lines and convert
1336  * a Float to a String.
1337  * Return pointer to allocated memory, or NULL for failure.
1338  */
1339     char_u *
1340 eval_to_string(arg, nextcmd, convert)
1341     char_u      *arg;
1342     char_u      **nextcmd;
1343     int         convert;
1344 {
1345     typval_T    tv;
1346     char_u      *retval;
1347     garray_T    ga;
1348 #ifdef FEAT_FLOAT
1349     char_u      numbuf[NUMBUFLEN];
1350 #endif
1351
1352     if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1353         retval = NULL;
1354     else
1355     {
1356         if (convert && tv.v_type == VAR_LIST)
1357         {
1358             ga_init2(&ga, (int)sizeof(char), 80);
1359             if (tv.vval.v_list != NULL)
1360             {
1361                 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1362                 if (tv.vval.v_list->lv_len > 0)
1363                     ga_append(&ga, NL);
1364             }
1365             ga_append(&ga, NUL);
1366             retval = (char_u *)ga.ga_data;
1367         }
1368 #ifdef FEAT_FLOAT
1369         else if (convert && tv.v_type == VAR_FLOAT)
1370         {
1371             vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv.vval.v_float);
1372             retval = vim_strsave(numbuf);
1373         }
1374 #endif
1375         else
1376             retval = vim_strsave(get_tv_string(&tv));
1377         clear_tv(&tv);
1378     }
1379
1380     return retval;
1381 }
1382
1383 /*
1384  * Call eval_to_string() without using current local variables and using
1385  * textlock.  When "use_sandbox" is TRUE use the sandbox.
1386  */
1387     char_u *
1388 eval_to_string_safe(arg, nextcmd, use_sandbox)
1389     char_u      *arg;
1390     char_u      **nextcmd;
1391     int         use_sandbox;
1392 {
1393     char_u      *retval;
1394     void        *save_funccalp;
1395
1396     save_funccalp = save_funccal();
1397     if (use_sandbox)
1398         ++sandbox;
1399     ++textlock;
1400     retval = eval_to_string(arg, nextcmd, FALSE);
1401     if (use_sandbox)
1402         --sandbox;
1403     --textlock;
1404     restore_funccal(save_funccalp);
1405     return retval;
1406 }
1407
1408 /*
1409  * Top level evaluation function, returning a number.
1410  * Evaluates "expr" silently.
1411  * Returns -1 for an error.
1412  */
1413     int
1414 eval_to_number(expr)
1415     char_u      *expr;
1416 {
1417     typval_T    rettv;
1418     int         retval;
1419     char_u      *p = skipwhite(expr);
1420
1421     ++emsg_off;
1422
1423     if (eval1(&p, &rettv, TRUE) == FAIL)
1424         retval = -1;
1425     else
1426     {
1427         retval = get_tv_number_chk(&rettv, NULL);
1428         clear_tv(&rettv);
1429     }
1430     --emsg_off;
1431
1432     return retval;
1433 }
1434
1435 /*
1436  * Prepare v: variable "idx" to be used.
1437  * Save the current typeval in "save_tv".
1438  * When not used yet add the variable to the v: hashtable.
1439  */
1440     static void
1441 prepare_vimvar(idx, save_tv)
1442     int         idx;
1443     typval_T    *save_tv;
1444 {
1445     *save_tv = vimvars[idx].vv_tv;
1446     if (vimvars[idx].vv_type == VAR_UNKNOWN)
1447         hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1448 }
1449
1450 /*
1451  * Restore v: variable "idx" to typeval "save_tv".
1452  * When no longer defined, remove the variable from the v: hashtable.
1453  */
1454     static void
1455 restore_vimvar(idx, save_tv)
1456     int         idx;
1457     typval_T    *save_tv;
1458 {
1459     hashitem_T  *hi;
1460
1461     vimvars[idx].vv_tv = *save_tv;
1462     if (vimvars[idx].vv_type == VAR_UNKNOWN)
1463     {
1464         hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1465         if (HASHITEM_EMPTY(hi))
1466             EMSG2(_(e_intern2), "restore_vimvar()");
1467         else
1468             hash_remove(&vimvarht, hi);
1469     }
1470 }
1471
1472 #if defined(FEAT_SPELL) || defined(PROTO)
1473 /*
1474  * Evaluate an expression to a list with suggestions.
1475  * For the "expr:" part of 'spellsuggest'.
1476  * Returns NULL when there is an error.
1477  */
1478     list_T *
1479 eval_spell_expr(badword, expr)
1480     char_u      *badword;
1481     char_u      *expr;
1482 {
1483     typval_T    save_val;
1484     typval_T    rettv;
1485     list_T      *list = NULL;
1486     char_u      *p = skipwhite(expr);
1487
1488     /* Set "v:val" to the bad word. */
1489     prepare_vimvar(VV_VAL, &save_val);
1490     vimvars[VV_VAL].vv_type = VAR_STRING;
1491     vimvars[VV_VAL].vv_str = badword;
1492     if (p_verbose == 0)
1493         ++emsg_off;
1494
1495     if (eval1(&p, &rettv, TRUE) == OK)
1496     {
1497         if (rettv.v_type != VAR_LIST)
1498             clear_tv(&rettv);
1499         else
1500             list = rettv.vval.v_list;
1501     }
1502
1503     if (p_verbose == 0)
1504         --emsg_off;
1505     restore_vimvar(VV_VAL, &save_val);
1506
1507     return list;
1508 }
1509
1510 /*
1511  * "list" is supposed to contain two items: a word and a number.  Return the
1512  * word in "pp" and the number as the return value.
1513  * Return -1 if anything isn't right.
1514  * Used to get the good word and score from the eval_spell_expr() result.
1515  */
1516     int
1517 get_spellword(list, pp)
1518     list_T      *list;
1519     char_u      **pp;
1520 {
1521     listitem_T  *li;
1522
1523     li = list->lv_first;
1524     if (li == NULL)
1525         return -1;
1526     *pp = get_tv_string(&li->li_tv);
1527
1528     li = li->li_next;
1529     if (li == NULL)
1530         return -1;
1531     return get_tv_number(&li->li_tv);
1532 }
1533 #endif
1534
1535 /*
1536  * Top level evaluation function.
1537  * Returns an allocated typval_T with the result.
1538  * Returns NULL when there is an error.
1539  */
1540     typval_T *
1541 eval_expr(arg, nextcmd)
1542     char_u      *arg;
1543     char_u      **nextcmd;
1544 {
1545     typval_T    *tv;
1546
1547     tv = (typval_T *)alloc(sizeof(typval_T));
1548     if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1549     {
1550         vim_free(tv);
1551         tv = NULL;
1552     }
1553
1554     return tv;
1555 }
1556
1557
1558 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1559         || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1560 /*
1561  * Call some vimL function and return the result in "*rettv".
1562  * Uses argv[argc] for the function arguments.  Only Number and String
1563  * arguments are currently supported.
1564  * Returns OK or FAIL.
1565  */
1566     int
1567 call_vim_function(func, argc, argv, safe, rettv)
1568     char_u      *func;
1569     int         argc;
1570     char_u      **argv;
1571     int         safe;           /* use the sandbox */
1572     typval_T    *rettv;
1573 {
1574     typval_T    *argvars;
1575     long        n;
1576     int         len;
1577     int         i;
1578     int         doesrange;
1579     void        *save_funccalp = NULL;
1580     int         ret;
1581
1582     argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1583     if (argvars == NULL)
1584         return FAIL;
1585
1586     for (i = 0; i < argc; i++)
1587     {
1588         /* Pass a NULL or empty argument as an empty string */
1589         if (argv[i] == NULL || *argv[i] == NUL)
1590         {
1591             argvars[i].v_type = VAR_STRING;
1592             argvars[i].vval.v_string = (char_u *)"";
1593             continue;
1594         }
1595
1596         /* Recognize a number argument, the others must be strings. */
1597         vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1598         if (len != 0 && len == (int)STRLEN(argv[i]))
1599         {
1600             argvars[i].v_type = VAR_NUMBER;
1601             argvars[i].vval.v_number = n;
1602         }
1603         else
1604         {
1605             argvars[i].v_type = VAR_STRING;
1606             argvars[i].vval.v_string = argv[i];
1607         }
1608     }
1609
1610     if (safe)
1611     {
1612         save_funccalp = save_funccal();
1613         ++sandbox;
1614     }
1615
1616     rettv->v_type = VAR_UNKNOWN;                /* clear_tv() uses this */
1617     ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1618                     curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1619                     &doesrange, TRUE, NULL);
1620     if (safe)
1621     {
1622         --sandbox;
1623         restore_funccal(save_funccalp);
1624     }
1625     vim_free(argvars);
1626
1627     if (ret == FAIL)
1628         clear_tv(rettv);
1629
1630     return ret;
1631 }
1632
1633 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1634 /*
1635  * Call vimL function "func" and return the result as a string.
1636  * Returns NULL when calling the function fails.
1637  * Uses argv[argc] for the function arguments.
1638  */
1639     void *
1640 call_func_retstr(func, argc, argv, safe)
1641     char_u      *func;
1642     int         argc;
1643     char_u      **argv;
1644     int         safe;           /* use the sandbox */
1645 {
1646     typval_T    rettv;
1647     char_u      *retval;
1648
1649     if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1650         return NULL;
1651
1652     retval = vim_strsave(get_tv_string(&rettv));
1653     clear_tv(&rettv);
1654     return retval;
1655 }
1656 # endif
1657
1658 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1659 /*
1660  * Call vimL function "func" and return the result as a number.
1661  * Returns -1 when calling the function fails.
1662  * Uses argv[argc] for the function arguments.
1663  */
1664     long
1665 call_func_retnr(func, argc, argv, safe)
1666     char_u      *func;
1667     int         argc;
1668     char_u      **argv;
1669     int         safe;           /* use the sandbox */
1670 {
1671     typval_T    rettv;
1672     long        retval;
1673
1674     if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1675         return -1;
1676
1677     retval = get_tv_number_chk(&rettv, NULL);
1678     clear_tv(&rettv);
1679     return retval;
1680 }
1681 # endif
1682
1683 /*
1684  * Call vimL function "func" and return the result as a List.
1685  * Uses argv[argc] for the function arguments.
1686  * Returns NULL when there is something wrong.
1687  */
1688     void *
1689 call_func_retlist(func, argc, argv, safe)
1690     char_u      *func;
1691     int         argc;
1692     char_u      **argv;
1693     int         safe;           /* use the sandbox */
1694 {
1695     typval_T    rettv;
1696
1697     if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1698         return NULL;
1699
1700     if (rettv.v_type != VAR_LIST)
1701     {
1702         clear_tv(&rettv);
1703         return NULL;
1704     }
1705
1706     return rettv.vval.v_list;
1707 }
1708 #endif
1709
1710
1711 /*
1712  * Save the current function call pointer, and set it to NULL.
1713  * Used when executing autocommands and for ":source".
1714  */
1715     void *
1716 save_funccal()
1717 {
1718     funccall_T *fc = current_funccal;
1719
1720     current_funccal = NULL;
1721     return (void *)fc;
1722 }
1723
1724     void
1725 restore_funccal(vfc)
1726     void *vfc;
1727 {
1728     funccall_T *fc = (funccall_T *)vfc;
1729
1730     current_funccal = fc;
1731 }
1732
1733 #if defined(FEAT_PROFILE) || defined(PROTO)
1734 /*
1735  * Prepare profiling for entering a child or something else that is not
1736  * counted for the script/function itself.
1737  * Should always be called in pair with prof_child_exit().
1738  */
1739     void
1740 prof_child_enter(tm)
1741     proftime_T *tm;     /* place to store waittime */
1742 {
1743     funccall_T *fc = current_funccal;
1744
1745     if (fc != NULL && fc->func->uf_profiling)
1746         profile_start(&fc->prof_child);
1747     script_prof_save(tm);
1748 }
1749
1750 /*
1751  * Take care of time spent in a child.
1752  * Should always be called after prof_child_enter().
1753  */
1754     void
1755 prof_child_exit(tm)
1756     proftime_T *tm;     /* where waittime was stored */
1757 {
1758     funccall_T *fc = current_funccal;
1759
1760     if (fc != NULL && fc->func->uf_profiling)
1761     {
1762         profile_end(&fc->prof_child);
1763         profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1764         profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1765         profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1766     }
1767     script_prof_restore(tm);
1768 }
1769 #endif
1770
1771
1772 #ifdef FEAT_FOLDING
1773 /*
1774  * Evaluate 'foldexpr'.  Returns the foldlevel, and any character preceding
1775  * it in "*cp".  Doesn't give error messages.
1776  */
1777     int
1778 eval_foldexpr(arg, cp)
1779     char_u      *arg;
1780     int         *cp;
1781 {
1782     typval_T    tv;
1783     int         retval;
1784     char_u      *s;
1785     int         use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1786                                                                    OPT_LOCAL);
1787
1788     ++emsg_off;
1789     if (use_sandbox)
1790         ++sandbox;
1791     ++textlock;
1792     *cp = NUL;
1793     if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1794         retval = 0;
1795     else
1796     {
1797         /* If the result is a number, just return the number. */
1798         if (tv.v_type == VAR_NUMBER)
1799             retval = tv.vval.v_number;
1800         else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1801             retval = 0;
1802         else
1803         {
1804             /* If the result is a string, check if there is a non-digit before
1805              * the number. */
1806             s = tv.vval.v_string;
1807             if (!VIM_ISDIGIT(*s) && *s != '-')
1808                 *cp = *s++;
1809             retval = atol((char *)s);
1810         }
1811         clear_tv(&tv);
1812     }
1813     --emsg_off;
1814     if (use_sandbox)
1815         --sandbox;
1816     --textlock;
1817
1818     return retval;
1819 }
1820 #endif
1821
1822 /*
1823  * ":let"                       list all variable values
1824  * ":let var1 var2"             list variable values
1825  * ":let var = expr"            assignment command.
1826  * ":let var += expr"           assignment command.
1827  * ":let var -= expr"           assignment command.
1828  * ":let var .= expr"           assignment command.
1829  * ":let [var1, var2] = expr"   unpack list.
1830  */
1831     void
1832 ex_let(eap)
1833     exarg_T     *eap;
1834 {
1835     char_u      *arg = eap->arg;
1836     char_u      *expr = NULL;
1837     typval_T    rettv;
1838     int         i;
1839     int         var_count = 0;
1840     int         semicolon = 0;
1841     char_u      op[2];
1842     char_u      *argend;
1843     int         first = TRUE;
1844
1845     argend = skip_var_list(arg, &var_count, &semicolon);
1846     if (argend == NULL)
1847         return;
1848     if (argend > arg && argend[-1] == '.')  /* for var.='str' */
1849         --argend;
1850     expr = vim_strchr(argend, '=');
1851     if (expr == NULL)
1852     {
1853         /*
1854          * ":let" without "=": list variables
1855          */
1856         if (*arg == '[')
1857             EMSG(_(e_invarg));
1858         else if (!ends_excmd(*arg))
1859             /* ":let var1 var2" */
1860             arg = list_arg_vars(eap, arg, &first);
1861         else if (!eap->skip)
1862         {
1863             /* ":let" */
1864             list_glob_vars(&first);
1865             list_buf_vars(&first);
1866             list_win_vars(&first);
1867 #ifdef FEAT_WINDOWS
1868             list_tab_vars(&first);
1869 #endif
1870             list_script_vars(&first);
1871             list_func_vars(&first);
1872             list_vim_vars(&first);
1873         }
1874         eap->nextcmd = check_nextcmd(arg);
1875     }
1876     else
1877     {
1878         op[0] = '=';
1879         op[1] = NUL;
1880         if (expr > argend)
1881         {
1882             if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1883                 op[0] = expr[-1];   /* +=, -= or .= */
1884         }
1885         expr = skipwhite(expr + 1);
1886
1887         if (eap->skip)
1888             ++emsg_skip;
1889         i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1890         if (eap->skip)
1891         {
1892             if (i != FAIL)
1893                 clear_tv(&rettv);
1894             --emsg_skip;
1895         }
1896         else if (i != FAIL)
1897         {
1898             (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1899                                                                           op);
1900             clear_tv(&rettv);
1901         }
1902     }
1903 }
1904
1905 /*
1906  * Assign the typevalue "tv" to the variable or variables at "arg_start".
1907  * Handles both "var" with any type and "[var, var; var]" with a list type.
1908  * When "nextchars" is not NULL it points to a string with characters that
1909  * must appear after the variable(s).  Use "+", "-" or "." for add, subtract
1910  * or concatenate.
1911  * Returns OK or FAIL;
1912  */
1913     static int
1914 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1915     char_u      *arg_start;
1916     typval_T    *tv;
1917     int         copy;           /* copy values from "tv", don't move */
1918     int         semicolon;      /* from skip_var_list() */
1919     int         var_count;      /* from skip_var_list() */
1920     char_u      *nextchars;
1921 {
1922     char_u      *arg = arg_start;
1923     list_T      *l;
1924     int         i;
1925     listitem_T  *item;
1926     typval_T    ltv;
1927
1928     if (*arg != '[')
1929     {
1930         /*
1931          * ":let var = expr" or ":for var in list"
1932          */
1933         if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1934             return FAIL;
1935         return OK;
1936     }
1937
1938     /*
1939      * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1940      */
1941     if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1942     {
1943         EMSG(_(e_listreq));
1944         return FAIL;
1945     }
1946
1947     i = list_len(l);
1948     if (semicolon == 0 && var_count < i)
1949     {
1950         EMSG(_("E687: Less targets than List items"));
1951         return FAIL;
1952     }
1953     if (var_count - semicolon > i)
1954     {
1955         EMSG(_("E688: More targets than List items"));
1956         return FAIL;
1957     }
1958
1959     item = l->lv_first;
1960     while (*arg != ']')
1961     {
1962         arg = skipwhite(arg + 1);
1963         arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1964         item = item->li_next;
1965         if (arg == NULL)
1966             return FAIL;
1967
1968         arg = skipwhite(arg);
1969         if (*arg == ';')
1970         {
1971             /* Put the rest of the list (may be empty) in the var after ';'.
1972              * Create a new list for this. */
1973             l = list_alloc();
1974             if (l == NULL)
1975                 return FAIL;
1976             while (item != NULL)
1977             {
1978                 list_append_tv(l, &item->li_tv);
1979                 item = item->li_next;
1980             }
1981
1982             ltv.v_type = VAR_LIST;
1983             ltv.v_lock = 0;
1984             ltv.vval.v_list = l;
1985             l->lv_refcount = 1;
1986
1987             arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1988                                                     (char_u *)"]", nextchars);
1989             clear_tv(&ltv);
1990             if (arg == NULL)
1991                 return FAIL;
1992             break;
1993         }
1994         else if (*arg != ',' && *arg != ']')
1995         {
1996             EMSG2(_(e_intern2), "ex_let_vars()");
1997             return FAIL;
1998         }
1999     }
2000
2001     return OK;
2002 }
2003
2004 /*
2005  * Skip over assignable variable "var" or list of variables "[var, var]".
2006  * Used for ":let varvar = expr" and ":for varvar in expr".
2007  * For "[var, var]" increment "*var_count" for each variable.
2008  * for "[var, var; var]" set "semicolon".
2009  * Return NULL for an error.
2010  */
2011     static char_u *
2012 skip_var_list(arg, var_count, semicolon)
2013     char_u      *arg;
2014     int         *var_count;
2015     int         *semicolon;
2016 {
2017     char_u      *p, *s;
2018
2019     if (*arg == '[')
2020     {
2021         /* "[var, var]": find the matching ']'. */
2022         p = arg;
2023         for (;;)
2024         {
2025             p = skipwhite(p + 1);       /* skip whites after '[', ';' or ',' */
2026             s = skip_var_one(p);
2027             if (s == p)
2028             {
2029                 EMSG2(_(e_invarg2), p);
2030                 return NULL;
2031             }
2032             ++*var_count;
2033
2034             p = skipwhite(s);
2035             if (*p == ']')
2036                 break;
2037             else if (*p == ';')
2038             {
2039                 if (*semicolon == 1)
2040                 {
2041                     EMSG(_("Double ; in list of variables"));
2042                     return NULL;
2043                 }
2044                 *semicolon = 1;
2045             }
2046             else if (*p != ',')
2047             {
2048                 EMSG2(_(e_invarg2), p);
2049                 return NULL;
2050             }
2051         }
2052         return p + 1;
2053     }
2054     else
2055         return skip_var_one(arg);
2056 }
2057
2058 /*
2059  * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
2060  * l[idx].
2061  */
2062     static char_u *
2063 skip_var_one(arg)
2064     char_u      *arg;
2065 {
2066     if (*arg == '@' && arg[1] != NUL)
2067         return arg + 2;
2068     return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
2069                                    NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2070 }
2071
2072 /*
2073  * List variables for hashtab "ht" with prefix "prefix".
2074  * If "empty" is TRUE also list NULL strings as empty strings.
2075  */
2076     static void
2077 list_hashtable_vars(ht, prefix, empty, first)
2078     hashtab_T   *ht;
2079     char_u      *prefix;
2080     int         empty;
2081     int         *first;
2082 {
2083     hashitem_T  *hi;
2084     dictitem_T  *di;
2085     int         todo;
2086
2087     todo = (int)ht->ht_used;
2088     for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
2089     {
2090         if (!HASHITEM_EMPTY(hi))
2091         {
2092             --todo;
2093             di = HI2DI(hi);
2094             if (empty || di->di_tv.v_type != VAR_STRING
2095                                            || di->di_tv.vval.v_string != NULL)
2096                 list_one_var(di, prefix, first);
2097         }
2098     }
2099 }
2100
2101 /*
2102  * List global variables.
2103  */
2104     static void
2105 list_glob_vars(first)
2106     int *first;
2107 {
2108     list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
2109 }
2110
2111 /*
2112  * List buffer variables.
2113  */
2114     static void
2115 list_buf_vars(first)
2116     int *first;
2117 {
2118     char_u      numbuf[NUMBUFLEN];
2119
2120     list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:",
2121                                                                  TRUE, first);
2122
2123     sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
2124     list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
2125                                                                numbuf, first);
2126 }
2127
2128 /*
2129  * List window variables.
2130  */
2131     static void
2132 list_win_vars(first)
2133     int *first;
2134 {
2135     list_hashtable_vars(&curwin->w_vars.dv_hashtab,
2136                                                  (char_u *)"w:", TRUE, first);
2137 }
2138
2139 #ifdef FEAT_WINDOWS
2140 /*
2141  * List tab page variables.
2142  */
2143     static void
2144 list_tab_vars(first)
2145     int *first;
2146 {
2147     list_hashtable_vars(&curtab->tp_vars.dv_hashtab,
2148                                                  (char_u *)"t:", TRUE, first);
2149 }
2150 #endif
2151
2152 /*
2153  * List Vim variables.
2154  */
2155     static void
2156 list_vim_vars(first)
2157     int *first;
2158 {
2159     list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2160 }
2161
2162 /*
2163  * List script-local variables, if there is a script.
2164  */
2165     static void
2166 list_script_vars(first)
2167     int *first;
2168 {
2169     if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2170         list_hashtable_vars(&SCRIPT_VARS(current_SID),
2171                                                 (char_u *)"s:", FALSE, first);
2172 }
2173
2174 /*
2175  * List function variables, if there is a function.
2176  */
2177     static void
2178 list_func_vars(first)
2179     int *first;
2180 {
2181     if (current_funccal != NULL)
2182         list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2183                                                 (char_u *)"l:", FALSE, first);
2184 }
2185
2186 /*
2187  * List variables in "arg".
2188  */
2189     static char_u *
2190 list_arg_vars(eap, arg, first)
2191     exarg_T     *eap;
2192     char_u      *arg;
2193     int         *first;
2194 {
2195     int         error = FALSE;
2196     int         len;
2197     char_u      *name;
2198     char_u      *name_start;
2199     char_u      *arg_subsc;
2200     char_u      *tofree;
2201     typval_T    tv;
2202
2203     while (!ends_excmd(*arg) && !got_int)
2204     {
2205         if (error || eap->skip)
2206         {
2207             arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2208             if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2209             {
2210                 emsg_severe = TRUE;
2211                 EMSG(_(e_trailing));
2212                 break;
2213             }
2214         }
2215         else
2216         {
2217             /* get_name_len() takes care of expanding curly braces */
2218             name_start = name = arg;
2219             len = get_name_len(&arg, &tofree, TRUE, TRUE);
2220             if (len <= 0)
2221             {
2222                 /* This is mainly to keep test 49 working: when expanding
2223                  * curly braces fails overrule the exception error message. */
2224                 if (len < 0 && !aborting())
2225                 {
2226                     emsg_severe = TRUE;
2227                     EMSG2(_(e_invarg2), arg);
2228                     break;
2229                 }
2230                 error = TRUE;
2231             }
2232             else
2233             {
2234                 if (tofree != NULL)
2235                     name = tofree;
2236                 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2237                     error = TRUE;
2238                 else
2239                 {
2240                     /* handle d.key, l[idx], f(expr) */
2241                     arg_subsc = arg;
2242                     if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2243                         error = TRUE;
2244                     else
2245                     {
2246                         if (arg == arg_subsc && len == 2 && name[1] == ':')
2247                         {
2248                             switch (*name)
2249                             {
2250                                 case 'g': list_glob_vars(first); break;
2251                                 case 'b': list_buf_vars(first); break;
2252                                 case 'w': list_win_vars(first); break;
2253 #ifdef FEAT_WINDOWS
2254                                 case 't': list_tab_vars(first); break;
2255 #endif
2256                                 case 'v': list_vim_vars(first); break;
2257                                 case 's': list_script_vars(first); break;
2258                                 case 'l': list_func_vars(first); break;
2259                                 default:
2260                                           EMSG2(_("E738: Can't list variables for %s"), name);
2261                             }
2262                         }
2263                         else
2264                         {
2265                             char_u      numbuf[NUMBUFLEN];
2266                             char_u      *tf;
2267                             int         c;
2268                             char_u      *s;
2269
2270                             s = echo_string(&tv, &tf, numbuf, 0);
2271                             c = *arg;
2272                             *arg = NUL;
2273                             list_one_var_a((char_u *)"",
2274                                     arg == arg_subsc ? name : name_start,
2275                                     tv.v_type,
2276                                     s == NULL ? (char_u *)"" : s,
2277                                     first);
2278                             *arg = c;
2279                             vim_free(tf);
2280                         }
2281                         clear_tv(&tv);
2282                     }
2283                 }
2284             }
2285
2286             vim_free(tofree);
2287         }
2288
2289         arg = skipwhite(arg);
2290     }
2291
2292     return arg;
2293 }
2294
2295 /*
2296  * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2297  * Returns a pointer to the char just after the var name.
2298  * Returns NULL if there is an error.
2299  */
2300     static char_u *
2301 ex_let_one(arg, tv, copy, endchars, op)
2302     char_u      *arg;           /* points to variable name */
2303     typval_T    *tv;            /* value to assign to variable */
2304     int         copy;           /* copy value from "tv" */
2305     char_u      *endchars;      /* valid chars after variable name  or NULL */
2306     char_u      *op;            /* "+", "-", "."  or NULL*/
2307 {
2308     int         c1;
2309     char_u      *name;
2310     char_u      *p;
2311     char_u      *arg_end = NULL;
2312     int         len;
2313     int         opt_flags;
2314     char_u      *tofree = NULL;
2315
2316     /*
2317      * ":let $VAR = expr": Set environment variable.
2318      */
2319     if (*arg == '$')
2320     {
2321         /* Find the end of the name. */
2322         ++arg;
2323         name = arg;
2324         len = get_env_len(&arg);
2325         if (len == 0)
2326             EMSG2(_(e_invarg2), name - 1);
2327         else
2328         {
2329             if (op != NULL && (*op == '+' || *op == '-'))
2330                 EMSG2(_(e_letwrong), op);
2331             else if (endchars != NULL
2332                              && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2333                 EMSG(_(e_letunexp));
2334             else if (!check_secure())
2335             {
2336                 c1 = name[len];
2337                 name[len] = NUL;
2338                 p = get_tv_string_chk(tv);
2339                 if (p != NULL && op != NULL && *op == '.')
2340                 {
2341                     int     mustfree = FALSE;
2342                     char_u  *s = vim_getenv(name, &mustfree);
2343
2344                     if (s != NULL)
2345                     {
2346                         p = tofree = concat_str(s, p);
2347                         if (mustfree)
2348                             vim_free(s);
2349                     }
2350                 }
2351                 if (p != NULL)
2352                 {
2353                     vim_setenv(name, p);
2354                     if (STRICMP(name, "HOME") == 0)
2355                         init_homedir();
2356                     else if (didset_vim && STRICMP(name, "VIM") == 0)
2357                         didset_vim = FALSE;
2358                     else if (didset_vimruntime
2359                                         && STRICMP(name, "VIMRUNTIME") == 0)
2360                         didset_vimruntime = FALSE;
2361                     arg_end = arg;
2362                 }
2363                 name[len] = c1;
2364                 vim_free(tofree);
2365             }
2366         }
2367     }
2368
2369     /*
2370      * ":let &option = expr": Set option value.
2371      * ":let &l:option = expr": Set local option value.
2372      * ":let &g:option = expr": Set global option value.
2373      */
2374     else if (*arg == '&')
2375     {
2376         /* Find the end of the name. */
2377         p = find_option_end(&arg, &opt_flags);
2378         if (p == NULL || (endchars != NULL
2379                               && vim_strchr(endchars, *skipwhite(p)) == NULL))
2380             EMSG(_(e_letunexp));
2381         else
2382         {
2383             long        n;
2384             int         opt_type;
2385             long        numval;
2386             char_u      *stringval = NULL;
2387             char_u      *s;
2388
2389             c1 = *p;
2390             *p = NUL;
2391
2392             n = get_tv_number(tv);
2393             s = get_tv_string_chk(tv);      /* != NULL if number or string */
2394             if (s != NULL && op != NULL && *op != '=')
2395             {
2396                 opt_type = get_option_value(arg, &numval,
2397                                                        &stringval, opt_flags);
2398                 if ((opt_type == 1 && *op == '.')
2399                         || (opt_type == 0 && *op != '.'))
2400                     EMSG2(_(e_letwrong), op);
2401                 else
2402                 {
2403                     if (opt_type == 1)  /* number */
2404                     {
2405                         if (*op == '+')
2406                             n = numval + n;
2407                         else
2408                             n = numval - n;
2409                     }
2410                     else if (opt_type == 0 && stringval != NULL) /* string */
2411                     {
2412                         s = concat_str(stringval, s);
2413                         vim_free(stringval);
2414                         stringval = s;
2415                     }
2416                 }
2417             }
2418             if (s != NULL)
2419             {
2420                 set_option_value(arg, n, s, opt_flags);
2421                 arg_end = p;
2422             }
2423             *p = c1;
2424             vim_free(stringval);
2425         }
2426     }
2427
2428     /*
2429      * ":let @r = expr": Set register contents.
2430      */
2431     else if (*arg == '@')
2432     {
2433         ++arg;
2434         if (op != NULL && (*op == '+' || *op == '-'))
2435             EMSG2(_(e_letwrong), op);
2436         else if (endchars != NULL
2437                          && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2438             EMSG(_(e_letunexp));
2439         else
2440         {
2441             char_u      *ptofree = NULL;
2442             char_u      *s;
2443
2444             p = get_tv_string_chk(tv);
2445             if (p != NULL && op != NULL && *op == '.')
2446             {
2447                 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2448                 if (s != NULL)
2449                 {
2450                     p = ptofree = concat_str(s, p);
2451                     vim_free(s);
2452                 }
2453             }
2454             if (p != NULL)
2455             {
2456                 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2457                 arg_end = arg + 1;
2458             }
2459             vim_free(ptofree);
2460         }
2461     }
2462
2463     /*
2464      * ":let var = expr": Set internal variable.
2465      * ":let {expr} = expr": Idem, name made with curly braces
2466      */
2467     else if (eval_isnamec1(*arg) || *arg == '{')
2468     {
2469         lval_T  lv;
2470
2471         p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2472         if (p != NULL && lv.ll_name != NULL)
2473         {
2474             if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2475                 EMSG(_(e_letunexp));
2476             else
2477             {
2478                 set_var_lval(&lv, p, tv, copy, op);
2479                 arg_end = p;
2480             }
2481         }
2482         clear_lval(&lv);
2483     }
2484
2485     else
2486         EMSG2(_(e_invarg2), arg);
2487
2488     return arg_end;
2489 }
2490
2491 /*
2492  * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2493  */
2494     static int
2495 check_changedtick(arg)
2496     char_u      *arg;
2497 {
2498     if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2499     {
2500         EMSG2(_(e_readonlyvar), arg);
2501         return TRUE;
2502     }
2503     return FALSE;
2504 }
2505
2506 /*
2507  * Get an lval: variable, Dict item or List item that can be assigned a value
2508  * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2509  * "name.key", "name.key[expr]" etc.
2510  * Indexing only works if "name" is an existing List or Dictionary.
2511  * "name" points to the start of the name.
2512  * If "rettv" is not NULL it points to the value to be assigned.
2513  * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2514  * wrong; must end in space or cmd separator.
2515  *
2516  * Returns a pointer to just after the name, including indexes.
2517  * When an evaluation error occurs "lp->ll_name" is NULL;
2518  * Returns NULL for a parsing error.  Still need to free items in "lp"!
2519  */
2520     static char_u *
2521 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2522     char_u      *name;
2523     typval_T    *rettv;
2524     lval_T      *lp;
2525     int         unlet;
2526     int         skip;
2527     int         quiet;      /* don't give error messages */
2528     int         fne_flags;  /* flags for find_name_end() */
2529 {
2530     char_u      *p;
2531     char_u      *expr_start, *expr_end;
2532     int         cc;
2533     dictitem_T  *v;
2534     typval_T    var1;
2535     typval_T    var2;
2536     int         empty1 = FALSE;
2537     listitem_T  *ni;
2538     char_u      *key = NULL;
2539     int         len;
2540     hashtab_T   *ht;
2541
2542     /* Clear everything in "lp". */
2543     vim_memset(lp, 0, sizeof(lval_T));
2544
2545     if (skip)
2546     {
2547         /* When skipping just find the end of the name. */
2548         lp->ll_name = name;
2549         return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2550     }
2551
2552     /* Find the end of the name. */
2553     p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2554     if (expr_start != NULL)
2555     {
2556         /* Don't expand the name when we already know there is an error. */
2557         if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2558                                                     && *p != '[' && *p != '.')
2559         {
2560             EMSG(_(e_trailing));
2561             return NULL;
2562         }
2563
2564         lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2565         if (lp->ll_exp_name == NULL)
2566         {
2567             /* Report an invalid expression in braces, unless the
2568              * expression evaluation has been cancelled due to an
2569              * aborting error, an interrupt, or an exception. */
2570             if (!aborting() && !quiet)
2571             {
2572                 emsg_severe = TRUE;
2573                 EMSG2(_(e_invarg2), name);
2574                 return NULL;
2575             }
2576         }
2577         lp->ll_name = lp->ll_exp_name;
2578     }
2579     else
2580         lp->ll_name = name;
2581
2582     /* Without [idx] or .key we are done. */
2583     if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2584         return p;
2585
2586     cc = *p;
2587     *p = NUL;
2588     v = find_var(lp->ll_name, &ht);
2589     if (v == NULL && !quiet)
2590         EMSG2(_(e_undefvar), lp->ll_name);
2591     *p = cc;
2592     if (v == NULL)
2593         return NULL;
2594
2595     /*
2596      * Loop until no more [idx] or .key is following.
2597      */
2598     lp->ll_tv = &v->di_tv;
2599     while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2600     {
2601         if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2602                 && !(lp->ll_tv->v_type == VAR_DICT
2603                                            && lp->ll_tv->vval.v_dict != NULL))
2604         {
2605             if (!quiet)
2606                 EMSG(_("E689: Can only index a List or Dictionary"));
2607             return NULL;
2608         }
2609         if (lp->ll_range)
2610         {
2611             if (!quiet)
2612                 EMSG(_("E708: [:] must come last"));
2613             return NULL;
2614         }
2615
2616         len = -1;
2617         if (*p == '.')
2618         {
2619             key = p + 1;
2620             for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2621                 ;
2622             if (len == 0)
2623             {
2624                 if (!quiet)
2625                     EMSG(_(e_emptykey));
2626                 return NULL;
2627             }
2628             p = key + len;
2629         }
2630         else
2631         {
2632             /* Get the index [expr] or the first index [expr: ]. */
2633             p = skipwhite(p + 1);
2634             if (*p == ':')
2635                 empty1 = TRUE;
2636             else
2637             {
2638                 empty1 = FALSE;
2639                 if (eval1(&p, &var1, TRUE) == FAIL)     /* recursive! */
2640                     return NULL;
2641                 if (get_tv_string_chk(&var1) == NULL)
2642                 {
2643                     /* not a number or string */
2644                     clear_tv(&var1);
2645                     return NULL;
2646                 }
2647             }
2648
2649             /* Optionally get the second index [ :expr]. */
2650             if (*p == ':')
2651             {
2652                 if (lp->ll_tv->v_type == VAR_DICT)
2653                 {
2654                     if (!quiet)
2655                         EMSG(_(e_dictrange));
2656                     if (!empty1)
2657                         clear_tv(&var1);
2658                     return NULL;
2659                 }
2660                 if (rettv != NULL && (rettv->v_type != VAR_LIST
2661                                                || rettv->vval.v_list == NULL))
2662                 {
2663                     if (!quiet)
2664                         EMSG(_("E709: [:] requires a List value"));
2665                     if (!empty1)
2666                         clear_tv(&var1);
2667                     return NULL;
2668                 }
2669                 p = skipwhite(p + 1);
2670                 if (*p == ']')
2671                     lp->ll_empty2 = TRUE;
2672                 else
2673                 {
2674                     lp->ll_empty2 = FALSE;
2675                     if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2676                     {
2677                         if (!empty1)
2678                             clear_tv(&var1);
2679                         return NULL;
2680                     }
2681                     if (get_tv_string_chk(&var2) == NULL)
2682                     {
2683                         /* not a number or string */
2684                         if (!empty1)
2685                             clear_tv(&var1);
2686                         clear_tv(&var2);
2687                         return NULL;
2688                     }
2689                 }
2690                 lp->ll_range = TRUE;
2691             }
2692             else
2693                 lp->ll_range = FALSE;
2694
2695             if (*p != ']')
2696             {
2697                 if (!quiet)
2698                     EMSG(_(e_missbrac));
2699                 if (!empty1)
2700                     clear_tv(&var1);
2701                 if (lp->ll_range && !lp->ll_empty2)
2702                     clear_tv(&var2);
2703                 return NULL;
2704             }
2705
2706             /* Skip to past ']'. */
2707             ++p;
2708         }
2709
2710         if (lp->ll_tv->v_type == VAR_DICT)
2711         {
2712             if (len == -1)
2713             {
2714                 /* "[key]": get key from "var1" */
2715                 key = get_tv_string(&var1);     /* is number or string */
2716                 if (*key == NUL)
2717                 {
2718                     if (!quiet)
2719                         EMSG(_(e_emptykey));
2720                     clear_tv(&var1);
2721                     return NULL;
2722                 }
2723             }
2724             lp->ll_list = NULL;
2725             lp->ll_dict = lp->ll_tv->vval.v_dict;
2726             lp->ll_di = dict_find(lp->ll_dict, key, len);
2727
2728             /* When assigning to g: check that a function and variable name is
2729              * valid. */
2730             if (rettv != NULL && lp->ll_dict == &globvardict)
2731             {
2732                 if (rettv->v_type == VAR_FUNC
2733                                && var_check_func_name(key, lp->ll_di == NULL))
2734                     return NULL;
2735                 if (!valid_varname(key))
2736                     return NULL;
2737             }
2738
2739             if (lp->ll_di == NULL)
2740             {
2741                 /* Can't add "v:" variable. */
2742                 if (lp->ll_dict == &vimvardict)
2743                 {
2744                     EMSG2(_(e_illvar), name);
2745                     return NULL;
2746                 }
2747
2748                 /* Key does not exist in dict: may need to add it. */
2749                 if (*p == '[' || *p == '.' || unlet)
2750                 {
2751                     if (!quiet)
2752                         EMSG2(_(e_dictkey), key);
2753                     if (len == -1)
2754                         clear_tv(&var1);
2755                     return NULL;
2756                 }
2757                 if (len == -1)
2758                     lp->ll_newkey = vim_strsave(key);
2759                 else
2760                     lp->ll_newkey = vim_strnsave(key, len);
2761                 if (len == -1)
2762                     clear_tv(&var1);
2763                 if (lp->ll_newkey == NULL)
2764                     p = NULL;
2765                 break;
2766             }
2767             /* existing variable, need to check if it can be changed */
2768             else if (var_check_ro(lp->ll_di->di_flags, name))
2769                 return NULL;
2770
2771             if (len == -1)
2772                 clear_tv(&var1);
2773             lp->ll_tv = &lp->ll_di->di_tv;
2774         }
2775         else
2776         {
2777             /*
2778              * Get the number and item for the only or first index of the List.
2779              */
2780             if (empty1)
2781                 lp->ll_n1 = 0;
2782             else
2783             {
2784                 lp->ll_n1 = get_tv_number(&var1);   /* is number or string */
2785                 clear_tv(&var1);
2786             }
2787             lp->ll_dict = NULL;
2788             lp->ll_list = lp->ll_tv->vval.v_list;
2789             lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2790             if (lp->ll_li == NULL)
2791             {
2792                 if (lp->ll_n1 < 0)
2793                 {
2794                     lp->ll_n1 = 0;
2795                     lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2796                 }
2797             }
2798             if (lp->ll_li == NULL)
2799             {
2800                 if (lp->ll_range && !lp->ll_empty2)
2801                     clear_tv(&var2);
2802                 if (!quiet)
2803                     EMSGN(_(e_listidx), lp->ll_n1);
2804                 return NULL;
2805             }
2806
2807             /*
2808              * May need to find the item or absolute index for the second
2809              * index of a range.
2810              * When no index given: "lp->ll_empty2" is TRUE.
2811              * Otherwise "lp->ll_n2" is set to the second index.
2812              */
2813             if (lp->ll_range && !lp->ll_empty2)
2814             {
2815                 lp->ll_n2 = get_tv_number(&var2);   /* is number or string */
2816                 clear_tv(&var2);
2817                 if (lp->ll_n2 < 0)
2818                 {
2819                     ni = list_find(lp->ll_list, lp->ll_n2);
2820                     if (ni == NULL)
2821                     {
2822                         if (!quiet)
2823                             EMSGN(_(e_listidx), lp->ll_n2);
2824                         return NULL;
2825                     }
2826                     lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2827                 }
2828
2829                 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2830                 if (lp->ll_n1 < 0)
2831                     lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2832                 if (lp->ll_n2 < lp->ll_n1)
2833                 {
2834                     if (!quiet)
2835                         EMSGN(_(e_listidx), lp->ll_n2);
2836                     return NULL;
2837                 }
2838             }
2839
2840             lp->ll_tv = &lp->ll_li->li_tv;
2841         }
2842     }
2843
2844     return p;
2845 }
2846
2847 /*
2848  * Clear lval "lp" that was filled by get_lval().
2849  */
2850     static void
2851 clear_lval(lp)
2852     lval_T      *lp;
2853 {
2854     vim_free(lp->ll_exp_name);
2855     vim_free(lp->ll_newkey);
2856 }
2857
2858 /*
2859  * Set a variable that was parsed by get_lval() to "rettv".
2860  * "endp" points to just after the parsed name.
2861  * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2862  */
2863     static void
2864 set_var_lval(lp, endp, rettv, copy, op)
2865     lval_T      *lp;
2866     char_u      *endp;
2867     typval_T    *rettv;
2868     int         copy;
2869     char_u      *op;
2870 {
2871     int         cc;
2872     listitem_T  *ri;
2873     dictitem_T  *di;
2874
2875     if (lp->ll_tv == NULL)
2876     {
2877         if (!check_changedtick(lp->ll_name))
2878         {
2879             cc = *endp;
2880             *endp = NUL;
2881             if (op != NULL && *op != '=')
2882             {
2883                 typval_T tv;
2884
2885                 /* handle +=, -= and .= */
2886                 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2887                                                              &tv, TRUE) == OK)
2888                 {
2889                     if (tv_op(&tv, rettv, op) == OK)
2890                         set_var(lp->ll_name, &tv, FALSE);
2891                     clear_tv(&tv);
2892                 }
2893             }
2894             else
2895                 set_var(lp->ll_name, rettv, copy);
2896             *endp = cc;
2897         }
2898     }
2899     else if (tv_check_lock(lp->ll_newkey == NULL
2900                 ? lp->ll_tv->v_lock
2901                 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2902         ;
2903     else if (lp->ll_range)
2904     {
2905         /*
2906          * Assign the List values to the list items.
2907          */
2908         for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2909         {
2910             if (op != NULL && *op != '=')
2911                 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2912             else
2913             {
2914                 clear_tv(&lp->ll_li->li_tv);
2915                 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2916             }
2917             ri = ri->li_next;
2918             if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2919                 break;
2920             if (lp->ll_li->li_next == NULL)
2921             {
2922                 /* Need to add an empty item. */
2923                 if (list_append_number(lp->ll_list, 0) == FAIL)
2924                 {
2925                     ri = NULL;
2926                     break;
2927                 }
2928             }
2929             lp->ll_li = lp->ll_li->li_next;
2930             ++lp->ll_n1;
2931         }
2932         if (ri != NULL)
2933             EMSG(_("E710: List value has more items than target"));
2934         else if (lp->ll_empty2
2935                 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2936                 : lp->ll_n1 != lp->ll_n2)
2937             EMSG(_("E711: List value has not enough items"));
2938     }
2939     else
2940     {
2941         /*
2942          * Assign to a List or Dictionary item.
2943          */
2944         if (lp->ll_newkey != NULL)
2945         {
2946             if (op != NULL && *op != '=')
2947             {
2948                 EMSG2(_(e_letwrong), op);
2949                 return;
2950             }
2951
2952             /* Need to add an item to the Dictionary. */
2953             di = dictitem_alloc(lp->ll_newkey);
2954             if (di == NULL)
2955                 return;
2956             if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2957             {
2958                 vim_free(di);
2959                 return;
2960             }
2961             lp->ll_tv = &di->di_tv;
2962         }
2963         else if (op != NULL && *op != '=')
2964         {
2965             tv_op(lp->ll_tv, rettv, op);
2966             return;
2967         }
2968         else
2969             clear_tv(lp->ll_tv);
2970
2971         /*
2972          * Assign the value to the variable or list item.
2973          */
2974         if (copy)
2975             copy_tv(rettv, lp->ll_tv);
2976         else
2977         {
2978             *lp->ll_tv = *rettv;
2979             lp->ll_tv->v_lock = 0;
2980             init_tv(rettv);
2981         }
2982     }
2983 }
2984
2985 /*
2986  * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2987  * Returns OK or FAIL.
2988  */
2989     static int
2990 tv_op(tv1, tv2, op)
2991     typval_T *tv1;
2992     typval_T *tv2;
2993     char_u  *op;
2994 {
2995     long        n;
2996     char_u      numbuf[NUMBUFLEN];
2997     char_u      *s;
2998
2999     /* Can't do anything with a Funcref or a Dict on the right. */
3000     if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
3001     {
3002         switch (tv1->v_type)
3003         {
3004             case VAR_DICT:
3005             case VAR_FUNC:
3006                 break;
3007
3008             case VAR_LIST:
3009                 if (*op != '+' || tv2->v_type != VAR_LIST)
3010                     break;
3011                 /* List += List */
3012                 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
3013                     list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
3014                 return OK;
3015
3016             case VAR_NUMBER:
3017             case VAR_STRING:
3018                 if (tv2->v_type == VAR_LIST)
3019                     break;
3020                 if (*op == '+' || *op == '-')
3021                 {
3022                     /* nr += nr  or  nr -= nr*/
3023                     n = get_tv_number(tv1);
3024 #ifdef FEAT_FLOAT
3025                     if (tv2->v_type == VAR_FLOAT)
3026                     {
3027                         float_T f = n;
3028
3029                         if (*op == '+')
3030                             f += tv2->vval.v_float;
3031                         else
3032                             f -= tv2->vval.v_float;
3033                         clear_tv(tv1);
3034                         tv1->v_type = VAR_FLOAT;
3035                         tv1->vval.v_float = f;
3036                     }
3037                     else
3038 #endif
3039                     {
3040                         if (*op == '+')
3041                             n += get_tv_number(tv2);
3042                         else
3043                             n -= get_tv_number(tv2);
3044                         clear_tv(tv1);
3045                         tv1->v_type = VAR_NUMBER;
3046                         tv1->vval.v_number = n;
3047                     }
3048                 }
3049                 else
3050                 {
3051                     if (tv2->v_type == VAR_FLOAT)
3052                         break;
3053
3054                     /* str .= str */
3055                     s = get_tv_string(tv1);
3056                     s = concat_str(s, get_tv_string_buf(tv2, numbuf));
3057                     clear_tv(tv1);
3058                     tv1->v_type = VAR_STRING;
3059                     tv1->vval.v_string = s;
3060                 }
3061                 return OK;
3062
3063 #ifdef FEAT_FLOAT
3064             case VAR_FLOAT:
3065                 {
3066                     float_T f;
3067
3068                     if (*op == '.' || (tv2->v_type != VAR_FLOAT
3069                                     && tv2->v_type != VAR_NUMBER
3070                                     && tv2->v_type != VAR_STRING))
3071                         break;
3072                     if (tv2->v_type == VAR_FLOAT)
3073                         f = tv2->vval.v_float;
3074                     else
3075                         f = get_tv_number(tv2);
3076                     if (*op == '+')
3077                         tv1->vval.v_float += f;
3078                     else
3079                         tv1->vval.v_float -= f;
3080                 }
3081                 return OK;
3082 #endif
3083         }
3084     }
3085
3086     EMSG2(_(e_letwrong), op);
3087     return FAIL;
3088 }
3089
3090 /*
3091  * Add a watcher to a list.
3092  */
3093     static void
3094 list_add_watch(l, lw)
3095     list_T      *l;
3096     listwatch_T *lw;
3097 {
3098     lw->lw_next = l->lv_watch;
3099     l->lv_watch = lw;
3100 }
3101
3102 /*
3103  * Remove a watcher from a list.
3104  * No warning when it isn't found...
3105  */
3106     static void
3107 list_rem_watch(l, lwrem)
3108     list_T      *l;
3109     listwatch_T *lwrem;
3110 {
3111     listwatch_T *lw, **lwp;
3112
3113     lwp = &l->lv_watch;
3114     for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3115     {
3116         if (lw == lwrem)
3117         {
3118             *lwp = lw->lw_next;
3119             break;
3120         }
3121         lwp = &lw->lw_next;
3122     }
3123 }
3124
3125 /*
3126  * Just before removing an item from a list: advance watchers to the next
3127  * item.
3128  */
3129     static void
3130 list_fix_watch(l, item)
3131     list_T      *l;
3132     listitem_T  *item;
3133 {
3134     listwatch_T *lw;
3135
3136     for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3137         if (lw->lw_item == item)
3138             lw->lw_item = item->li_next;
3139 }
3140
3141 /*
3142  * Evaluate the expression used in a ":for var in expr" command.
3143  * "arg" points to "var".
3144  * Set "*errp" to TRUE for an error, FALSE otherwise;
3145  * Return a pointer that holds the info.  Null when there is an error.
3146  */
3147     void *
3148 eval_for_line(arg, errp, nextcmdp, skip)
3149     char_u      *arg;
3150     int         *errp;
3151     char_u      **nextcmdp;
3152     int         skip;
3153 {
3154     forinfo_T   *fi;
3155     char_u      *expr;
3156     typval_T    tv;
3157     list_T      *l;
3158
3159     *errp = TRUE;       /* default: there is an error */
3160
3161     fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
3162     if (fi == NULL)
3163         return NULL;
3164
3165     expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
3166     if (expr == NULL)
3167         return fi;
3168
3169     expr = skipwhite(expr);
3170     if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
3171     {
3172         EMSG(_("E690: Missing \"in\" after :for"));
3173         return fi;
3174     }
3175
3176     if (skip)
3177         ++emsg_skip;
3178     if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
3179     {
3180         *errp = FALSE;
3181         if (!skip)
3182         {
3183             l = tv.vval.v_list;
3184             if (tv.v_type != VAR_LIST || l == NULL)
3185             {
3186                 EMSG(_(e_listreq));
3187                 clear_tv(&tv);
3188             }
3189             else
3190             {
3191                 /* No need to increment the refcount, it's already set for the
3192                  * list being used in "tv". */
3193                 fi->fi_list = l;
3194                 list_add_watch(l, &fi->fi_lw);
3195                 fi->fi_lw.lw_item = l->lv_first;
3196             }
3197         }
3198     }
3199     if (skip)
3200         --emsg_skip;
3201
3202     return fi;
3203 }
3204
3205 /*
3206  * Use the first item in a ":for" list.  Advance to the next.
3207  * Assign the values to the variable (list).  "arg" points to the first one.
3208  * Return TRUE when a valid item was found, FALSE when at end of list or
3209  * something wrong.
3210  */
3211     int
3212 next_for_item(fi_void, arg)
3213     void        *fi_void;
3214     char_u      *arg;
3215 {
3216     forinfo_T    *fi = (forinfo_T *)fi_void;
3217     int         result;
3218     listitem_T  *item;
3219
3220     item = fi->fi_lw.lw_item;
3221     if (item == NULL)
3222         result = FALSE;
3223     else
3224     {
3225         fi->fi_lw.lw_item = item->li_next;
3226         result = (ex_let_vars(arg, &item->li_tv, TRUE,
3227                               fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3228     }
3229     return result;
3230 }
3231
3232 /*
3233  * Free the structure used to store info used by ":for".
3234  */
3235     void
3236 free_for_info(fi_void)
3237     void *fi_void;
3238 {
3239     forinfo_T    *fi = (forinfo_T *)fi_void;
3240
3241     if (fi != NULL && fi->fi_list != NULL)
3242     {
3243         list_rem_watch(fi->fi_list, &fi->fi_lw);
3244         list_unref(fi->fi_list);
3245     }
3246     vim_free(fi);
3247 }
3248
3249 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3250
3251     void
3252 set_context_for_expression(xp, arg, cmdidx)
3253     expand_T    *xp;
3254     char_u      *arg;
3255     cmdidx_T    cmdidx;
3256 {
3257     int         got_eq = FALSE;
3258     int         c;
3259     char_u      *p;
3260
3261     if (cmdidx == CMD_let)
3262     {
3263         xp->xp_context = EXPAND_USER_VARS;
3264         if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3265         {
3266             /* ":let var1 var2 ...": find last space. */
3267             for (p = arg + STRLEN(arg); p >= arg; )
3268             {
3269                 xp->xp_pattern = p;
3270                 mb_ptr_back(arg, p);
3271                 if (vim_iswhite(*p))
3272                     break;
3273             }
3274             return;
3275         }
3276     }
3277     else
3278         xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3279                                                           : EXPAND_EXPRESSION;
3280     while ((xp->xp_pattern = vim_strpbrk(arg,
3281                                   (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3282     {
3283         c = *xp->xp_pattern;
3284         if (c == '&')
3285         {
3286             c = xp->xp_pattern[1];
3287             if (c == '&')
3288             {
3289                 ++xp->xp_pattern;
3290                 xp->xp_context = cmdidx != CMD_let || got_eq
3291                                          ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3292             }
3293             else if (c != ' ')
3294             {
3295                 xp->xp_context = EXPAND_SETTINGS;
3296                 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3297                     xp->xp_pattern += 2;
3298
3299             }
3300         }
3301         else if (c == '$')
3302         {
3303             /* environment variable */
3304             xp->xp_context = EXPAND_ENV_VARS;
3305         }
3306         else if (c == '=')
3307         {
3308             got_eq = TRUE;
3309             xp->xp_context = EXPAND_EXPRESSION;
3310         }
3311         else if (c == '<'
3312                 && xp->xp_context == EXPAND_FUNCTIONS
3313                 && vim_strchr(xp->xp_pattern, '(') == NULL)
3314         {
3315             /* Function name can start with "<SNR>" */
3316             break;
3317         }
3318         else if (cmdidx != CMD_let || got_eq)
3319         {
3320             if (c == '"')           /* string */
3321             {
3322                 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3323                     if (c == '\\' && xp->xp_pattern[1] != NUL)
3324                         ++xp->xp_pattern;
3325                 xp->xp_context = EXPAND_NOTHING;
3326             }
3327             else if (c == '\'')     /* literal string */
3328             {
3329                 /* Trick: '' is like stopping and starting a literal string. */
3330                 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3331                     /* skip */ ;
3332                 xp->xp_context = EXPAND_NOTHING;
3333             }
3334             else if (c == '|')
3335             {
3336                 if (xp->xp_pattern[1] == '|')
3337                 {
3338                     ++xp->xp_pattern;
3339                     xp->xp_context = EXPAND_EXPRESSION;
3340                 }
3341                 else
3342                     xp->xp_context = EXPAND_COMMANDS;
3343             }
3344             else
3345                 xp->xp_context = EXPAND_EXPRESSION;
3346         }
3347         else
3348             /* Doesn't look like something valid, expand as an expression
3349              * anyway. */
3350             xp->xp_context = EXPAND_EXPRESSION;
3351         arg = xp->xp_pattern;
3352         if (*arg != NUL)
3353             while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3354                 /* skip */ ;
3355     }
3356     xp->xp_pattern = arg;
3357 }
3358
3359 #endif /* FEAT_CMDL_COMPL */
3360
3361 /*
3362  * ":1,25call func(arg1, arg2)" function call.
3363  */
3364     void
3365 ex_call(eap)
3366     exarg_T     *eap;
3367 {
3368     char_u      *arg = eap->arg;
3369     char_u      *startarg;
3370     char_u      *name;
3371     char_u      *tofree;
3372     int         len;
3373     typval_T    rettv;
3374     linenr_T    lnum;
3375     int         doesrange;
3376     int         failed = FALSE;
3377     funcdict_T  fudi;
3378
3379     if (eap->skip)
3380     {
3381         /* trans_function_name() doesn't work well when skipping, use eval0()
3382          * instead to skip to any following command, e.g. for:
3383          *   :if 0 | call dict.foo().bar() | endif  */
3384         ++emsg_skip;
3385         if (eval0(eap->arg, &rettv, &eap->nextcmd, FALSE) != FAIL)
3386             clear_tv(&rettv);
3387         --emsg_skip;
3388         return;
3389     }
3390
3391     tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3392     if (fudi.fd_newkey != NULL)
3393     {
3394         /* Still need to give an error message for missing key. */
3395         EMSG2(_(e_dictkey), fudi.fd_newkey);
3396         vim_free(fudi.fd_newkey);
3397     }
3398     if (tofree == NULL)
3399         return;
3400
3401     /* Increase refcount on dictionary, it could get deleted when evaluating
3402      * the arguments. */
3403     if (fudi.fd_dict != NULL)
3404         ++fudi.fd_dict->dv_refcount;
3405
3406     /* If it is the name of a variable of type VAR_FUNC use its contents. */
3407     len = (int)STRLEN(tofree);
3408     name = deref_func_name(tofree, &len);
3409
3410     /* Skip white space to allow ":call func ()".  Not good, but required for
3411      * backward compatibility. */
3412     startarg = skipwhite(arg);
3413     rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3414
3415     if (*startarg != '(')
3416     {
3417         EMSG2(_("E107: Missing parentheses: %s"), eap->arg);
3418         goto end;
3419     }
3420
3421     /*
3422      * When skipping, evaluate the function once, to find the end of the
3423      * arguments.
3424      * When the function takes a range, this is discovered after the first
3425      * call, and the loop is broken.
3426      */
3427     if (eap->skip)
3428     {
3429         ++emsg_skip;
3430         lnum = eap->line2;      /* do it once, also with an invalid range */
3431     }
3432     else
3433         lnum = eap->line1;
3434     for ( ; lnum <= eap->line2; ++lnum)
3435     {
3436         if (!eap->skip && eap->addr_count > 0)
3437         {
3438             curwin->w_cursor.lnum = lnum;
3439             curwin->w_cursor.col = 0;
3440 #ifdef FEAT_VIRTUALEDIT
3441             curwin->w_cursor.coladd = 0;
3442 #endif
3443         }
3444         arg = startarg;
3445         if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3446                     eap->line1, eap->line2, &doesrange,
3447                                             !eap->skip, fudi.fd_dict) == FAIL)
3448         {
3449             failed = TRUE;
3450             break;
3451         }
3452
3453         /* Handle a function returning a Funcref, Dictionary or List. */
3454         if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3455         {
3456             failed = TRUE;
3457             break;
3458         }
3459
3460         clear_tv(&rettv);
3461         if (doesrange || eap->skip)
3462             break;
3463
3464         /* Stop when immediately aborting on error, or when an interrupt
3465          * occurred or an exception was thrown but not caught.
3466          * get_func_tv() returned OK, so that the check for trailing
3467          * characters below is executed. */
3468         if (aborting())
3469             break;
3470     }
3471     if (eap->skip)
3472         --emsg_skip;
3473
3474     if (!failed)
3475     {
3476         /* Check for trailing illegal characters and a following command. */
3477         if (!ends_excmd(*arg))
3478         {
3479             emsg_severe = TRUE;
3480             EMSG(_(e_trailing));
3481         }
3482         else
3483             eap->nextcmd = check_nextcmd(arg);
3484     }
3485
3486 end:
3487     dict_unref(fudi.fd_dict);
3488     vim_free(tofree);
3489 }
3490
3491 /*
3492  * ":unlet[!] var1 ... " command.
3493  */
3494     void
3495 ex_unlet(eap)
3496     exarg_T     *eap;
3497 {
3498     ex_unletlock(eap, eap->arg, 0);
3499 }
3500
3501 /*
3502  * ":lockvar" and ":unlockvar" commands
3503  */
3504     void
3505 ex_lockvar(eap)
3506     exarg_T     *eap;
3507 {
3508     char_u      *arg = eap->arg;
3509     int         deep = 2;
3510
3511     if (eap->forceit)
3512         deep = -1;
3513     else if (vim_isdigit(*arg))
3514     {
3515         deep = getdigits(&arg);
3516         arg = skipwhite(arg);
3517     }
3518
3519     ex_unletlock(eap, arg, deep);
3520 }
3521
3522 /*
3523  * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3524  */
3525     static void
3526 ex_unletlock(eap, argstart, deep)
3527     exarg_T     *eap;
3528     char_u      *argstart;
3529     int         deep;
3530 {
3531     char_u      *arg = argstart;
3532     char_u      *name_end;
3533     int         error = FALSE;
3534     lval_T      lv;
3535
3536     do
3537     {
3538         /* Parse the name and find the end. */
3539         name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3540                                                              FNE_CHECK_START);
3541         if (lv.ll_name == NULL)
3542             error = TRUE;           /* error but continue parsing */
3543         if (name_end == NULL || (!vim_iswhite(*name_end)
3544                                                    && !ends_excmd(*name_end)))
3545         {
3546             if (name_end != NULL)
3547             {
3548                 emsg_severe = TRUE;
3549                 EMSG(_(e_trailing));
3550             }
3551             if (!(eap->skip || error))
3552                 clear_lval(&lv);
3553             break;
3554         }
3555
3556         if (!error && !eap->skip)
3557         {
3558             if (eap->cmdidx == CMD_unlet)
3559             {
3560                 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3561                     error = TRUE;
3562             }
3563             else
3564             {
3565                 if (do_lock_var(&lv, name_end, deep,
3566                                           eap->cmdidx == CMD_lockvar) == FAIL)
3567                     error = TRUE;
3568             }
3569         }
3570
3571         if (!eap->skip)
3572             clear_lval(&lv);
3573
3574         arg = skipwhite(name_end);
3575     } while (!ends_excmd(*arg));
3576
3577     eap->nextcmd = check_nextcmd(arg);
3578 }
3579
3580     static int
3581 do_unlet_var(lp, name_end, forceit)
3582     lval_T      *lp;
3583     char_u      *name_end;
3584     int         forceit;
3585 {
3586     int         ret = OK;
3587     int         cc;
3588
3589     if (lp->ll_tv == NULL)
3590     {
3591         cc = *name_end;
3592         *name_end = NUL;
3593
3594         /* Normal name or expanded name. */
3595         if (check_changedtick(lp->ll_name))
3596             ret = FAIL;
3597         else if (do_unlet(lp->ll_name, forceit) == FAIL)
3598             ret = FAIL;
3599         *name_end = cc;
3600     }
3601     else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3602         return FAIL;
3603     else if (lp->ll_range)
3604     {
3605         listitem_T    *li;
3606
3607         /* Delete a range of List items. */
3608         while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3609         {
3610             li = lp->ll_li->li_next;
3611             listitem_remove(lp->ll_list, lp->ll_li);
3612             lp->ll_li = li;
3613             ++lp->ll_n1;
3614         }
3615     }
3616     else
3617     {
3618         if (lp->ll_list != NULL)
3619             /* unlet a List item. */
3620             listitem_remove(lp->ll_list, lp->ll_li);
3621         else
3622             /* unlet a Dictionary item. */
3623             dictitem_remove(lp->ll_dict, lp->ll_di);
3624     }
3625
3626     return ret;
3627 }
3628
3629 /*
3630  * "unlet" a variable.  Return OK if it existed, FAIL if not.
3631  * When "forceit" is TRUE don't complain if the variable doesn't exist.
3632  */
3633     int
3634 do_unlet(name, forceit)
3635     char_u      *name;
3636     int         forceit;
3637 {
3638     hashtab_T   *ht;
3639     hashitem_T  *hi;
3640     char_u      *varname;
3641     dictitem_T  *di;
3642
3643     ht = find_var_ht(name, &varname);
3644     if (ht != NULL && *varname != NUL)
3645     {
3646         hi = hash_find(ht, varname);
3647         if (!HASHITEM_EMPTY(hi))
3648         {
3649             di = HI2DI(hi);
3650             if (var_check_fixed(di->di_flags, name)
3651                     || var_check_ro(di->di_flags, name))
3652                 return FAIL;
3653             delete_var(ht, hi);
3654             return OK;
3655         }
3656     }
3657     if (forceit)
3658         return OK;
3659     EMSG2(_("E108: No such variable: \"%s\""), name);
3660     return FAIL;
3661 }
3662
3663 /*
3664  * Lock or unlock variable indicated by "lp".
3665  * "deep" is the levels to go (-1 for unlimited);
3666  * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3667  */
3668     static int
3669 do_lock_var(lp, name_end, deep, lock)
3670     lval_T      *lp;
3671     char_u      *name_end;
3672     int         deep;
3673     int         lock;
3674 {
3675     int         ret = OK;
3676     int         cc;
3677     dictitem_T  *di;
3678
3679     if (deep == 0)      /* nothing to do */
3680         return OK;
3681
3682     if (lp->ll_tv == NULL)
3683     {
3684         cc = *name_end;
3685         *name_end = NUL;
3686
3687         /* Normal name or expanded name. */
3688         if (check_changedtick(lp->ll_name))
3689             ret = FAIL;
3690         else
3691         {
3692             di = find_var(lp->ll_name, NULL);
3693             if (di == NULL)
3694                 ret = FAIL;
3695             else
3696             {
3697                 if (lock)
3698                     di->di_flags |= DI_FLAGS_LOCK;
3699                 else
3700                     di->di_flags &= ~DI_FLAGS_LOCK;
3701                 item_lock(&di->di_tv, deep, lock);
3702             }
3703         }
3704         *name_end = cc;
3705     }
3706     else if (lp->ll_range)
3707     {
3708         listitem_T    *li = lp->ll_li;
3709
3710         /* (un)lock a range of List items. */
3711         while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3712         {
3713             item_lock(&li->li_tv, deep, lock);
3714             li = li->li_next;
3715             ++lp->ll_n1;
3716         }
3717     }
3718     else if (lp->ll_list != NULL)
3719         /* (un)lock a List item. */
3720         item_lock(&lp->ll_li->li_tv, deep, lock);
3721     else
3722         /* un(lock) a Dictionary item. */
3723         item_lock(&lp->ll_di->di_tv, deep, lock);
3724
3725     return ret;
3726 }
3727
3728 /*
3729  * Lock or unlock an item.  "deep" is nr of levels to go.
3730  */
3731     static void
3732 item_lock(tv, deep, lock)
3733     typval_T    *tv;
3734     int         deep;
3735     int         lock;
3736 {
3737     static int  recurse = 0;
3738     list_T      *l;
3739     listitem_T  *li;
3740     dict_T      *d;
3741     hashitem_T  *hi;
3742     int         todo;
3743
3744     if (recurse >= DICT_MAXNEST)
3745     {
3746         EMSG(_("E743: variable nested too deep for (un)lock"));
3747         return;
3748     }
3749     if (deep == 0)
3750         return;
3751     ++recurse;
3752
3753     /* lock/unlock the item itself */
3754     if (lock)
3755         tv->v_lock |= VAR_LOCKED;
3756     else
3757         tv->v_lock &= ~VAR_LOCKED;
3758
3759     switch (tv->v_type)
3760     {
3761         case VAR_LIST:
3762             if ((l = tv->vval.v_list) != NULL)
3763             {
3764                 if (lock)
3765                     l->lv_lock |= VAR_LOCKED;
3766                 else
3767                     l->lv_lock &= ~VAR_LOCKED;
3768                 if (deep < 0 || deep > 1)
3769                     /* recursive: lock/unlock the items the List contains */
3770                     for (li = l->lv_first; li != NULL; li = li->li_next)
3771                         item_lock(&li->li_tv, deep - 1, lock);
3772             }
3773             break;
3774         case VAR_DICT:
3775             if ((d = tv->vval.v_dict) != NULL)
3776             {
3777                 if (lock)
3778                     d->dv_lock |= VAR_LOCKED;
3779                 else
3780                     d->dv_lock &= ~VAR_LOCKED;
3781                 if (deep < 0 || deep > 1)
3782                 {
3783                     /* recursive: lock/unlock the items the List contains */
3784                     todo = (int)d->dv_hashtab.ht_used;
3785                     for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3786                     {
3787                         if (!HASHITEM_EMPTY(hi))
3788                         {
3789                             --todo;
3790                             item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3791                         }
3792                     }
3793                 }
3794             }
3795     }
3796     --recurse;
3797 }
3798
3799 /*
3800  * Return TRUE if typeval "tv" is locked: Either that value is locked itself
3801  * or it refers to a List or Dictionary that is locked.
3802  */
3803     static int
3804 tv_islocked(tv)
3805     typval_T    *tv;
3806 {
3807     return (tv->v_lock & VAR_LOCKED)
3808         || (tv->v_type == VAR_LIST
3809                 && tv->vval.v_list != NULL
3810                 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3811         || (tv->v_type == VAR_DICT
3812                 && tv->vval.v_dict != NULL
3813                 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3814 }
3815
3816 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3817 /*
3818  * Delete all "menutrans_" variables.
3819  */
3820     void
3821 del_menutrans_vars()
3822 {
3823     hashitem_T  *hi;
3824     int         todo;
3825
3826     hash_lock(&globvarht);
3827     todo = (int)globvarht.ht_used;
3828     for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3829     {
3830         if (!HASHITEM_EMPTY(hi))
3831         {
3832             --todo;
3833             if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3834                 delete_var(&globvarht, hi);
3835         }
3836     }
3837     hash_unlock(&globvarht);
3838 }
3839 #endif
3840
3841 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3842
3843 /*
3844  * Local string buffer for the next two functions to store a variable name
3845  * with its prefix. Allocated in cat_prefix_varname(), freed later in
3846  * get_user_var_name().
3847  */
3848
3849 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3850
3851 static char_u   *varnamebuf = NULL;
3852 static int      varnamebuflen = 0;
3853
3854 /*
3855  * Function to concatenate a prefix and a variable name.
3856  */
3857     static char_u *
3858 cat_prefix_varname(prefix, name)
3859     int         prefix;
3860     char_u      *name;
3861 {
3862     int         len;
3863
3864     len = (int)STRLEN(name) + 3;
3865     if (len > varnamebuflen)
3866     {
3867         vim_free(varnamebuf);
3868         len += 10;                      /* some additional space */
3869         varnamebuf = alloc(len);
3870         if (varnamebuf == NULL)
3871         {
3872             varnamebuflen = 0;
3873             return NULL;
3874         }
3875         varnamebuflen = len;
3876     }
3877     *varnamebuf = prefix;
3878     varnamebuf[1] = ':';
3879     STRCPY(varnamebuf + 2, name);
3880     return varnamebuf;
3881 }
3882
3883 /*
3884  * Function given to ExpandGeneric() to obtain the list of user defined
3885  * (global/buffer/window/built-in) variable names.
3886  */
3887     char_u *
3888 get_user_var_name(xp, idx)
3889     expand_T    *xp;
3890     int         idx;
3891 {
3892     static long_u       gdone;
3893     static long_u       bdone;
3894     static long_u       wdone;
3895 #ifdef FEAT_WINDOWS
3896     static long_u       tdone;
3897 #endif
3898     static int          vidx;
3899     static hashitem_T   *hi;
3900     hashtab_T           *ht;
3901
3902     if (idx == 0)
3903     {
3904         gdone = bdone = wdone = vidx = 0;
3905 #ifdef FEAT_WINDOWS
3906         tdone = 0;
3907 #endif
3908     }
3909
3910     /* Global variables */
3911     if (gdone < globvarht.ht_used)
3912     {
3913         if (gdone++ == 0)
3914             hi = globvarht.ht_array;
3915         else
3916             ++hi;
3917         while (HASHITEM_EMPTY(hi))
3918             ++hi;
3919         if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3920             return cat_prefix_varname('g', hi->hi_key);
3921         return hi->hi_key;
3922     }
3923
3924     /* b: variables */
3925     ht = &curbuf->b_vars.dv_hashtab;
3926     if (bdone < ht->ht_used)
3927     {
3928         if (bdone++ == 0)
3929             hi = ht->ht_array;
3930         else
3931             ++hi;
3932         while (HASHITEM_EMPTY(hi))
3933             ++hi;
3934         return cat_prefix_varname('b', hi->hi_key);
3935     }
3936     if (bdone == ht->ht_used)
3937     {
3938         ++bdone;
3939         return (char_u *)"b:changedtick";
3940     }
3941
3942     /* w: variables */
3943     ht = &curwin->w_vars.dv_hashtab;
3944     if (wdone < ht->ht_used)
3945     {
3946         if (wdone++ == 0)
3947             hi = ht->ht_array;
3948         else
3949             ++hi;
3950         while (HASHITEM_EMPTY(hi))
3951             ++hi;
3952         return cat_prefix_varname('w', hi->hi_key);
3953     }
3954
3955 #ifdef FEAT_WINDOWS
3956     /* t: variables */
3957     ht = &curtab->tp_vars.dv_hashtab;
3958     if (tdone < ht->ht_used)
3959     {
3960         if (tdone++ == 0)
3961             hi = ht->ht_array;
3962         else
3963             ++hi;
3964         while (HASHITEM_EMPTY(hi))
3965             ++hi;
3966         return cat_prefix_varname('t', hi->hi_key);
3967     }
3968 #endif
3969
3970     /* v: variables */
3971     if (vidx < VV_LEN)
3972         return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3973
3974     vim_free(varnamebuf);
3975     varnamebuf = NULL;
3976     varnamebuflen = 0;
3977     return NULL;
3978 }
3979
3980 #endif /* FEAT_CMDL_COMPL */
3981
3982 /*
3983  * types for expressions.
3984  */
3985 typedef enum
3986 {
3987     TYPE_UNKNOWN = 0
3988     , TYPE_EQUAL        /* == */
3989     , TYPE_NEQUAL       /* != */
3990     , TYPE_GREATER      /* >  */
3991     , TYPE_GEQUAL       /* >= */
3992     , TYPE_SMALLER      /* <  */
3993     , TYPE_SEQUAL       /* <= */
3994     , TYPE_MATCH        /* =~ */
3995     , TYPE_NOMATCH      /* !~ */
3996 } exptype_T;
3997
3998 /*
3999  * The "evaluate" argument: When FALSE, the argument is only parsed but not
4000  * executed.  The function may return OK, but the rettv will be of type
4001  * VAR_UNKNOWN.  The function still returns FAIL for a syntax error.
4002  */
4003
4004 /*
4005  * Handle zero level expression.
4006  * This calls eval1() and handles error message and nextcmd.
4007  * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
4008  * Note: "rettv.v_lock" is not set.
4009  * Return OK or FAIL.
4010  */
4011     static int
4012 eval0(arg, rettv, nextcmd, evaluate)
4013     char_u      *arg;
4014     typval_T    *rettv;
4015     char_u      **nextcmd;
4016     int         evaluate;
4017 {
4018     int         ret;
4019     char_u      *p;
4020
4021     p = skipwhite(arg);
4022     ret = eval1(&p, rettv, evaluate);
4023     if (ret == FAIL || !ends_excmd(*p))
4024     {
4025         if (ret != FAIL)
4026             clear_tv(rettv);
4027         /*
4028          * Report the invalid expression unless the expression evaluation has
4029          * been cancelled due to an aborting error, an interrupt, or an
4030          * exception.
4031          */
4032         if (!aborting())
4033             EMSG2(_(e_invexpr2), arg);
4034         ret = FAIL;
4035     }
4036     if (nextcmd != NULL)
4037         *nextcmd = check_nextcmd(p);
4038
4039     return ret;
4040 }
4041
4042 /*
4043  * Handle top level expression:
4044  *      expr2 ? expr1 : expr1
4045  *
4046  * "arg" must point to the first non-white of the expression.
4047  * "arg" is advanced to the next non-white after the recognized expression.
4048  *
4049  * Note: "rettv.v_lock" is not set.
4050  *
4051  * Return OK or FAIL.
4052  */
4053     static int
4054 eval1(arg, rettv, evaluate)
4055     char_u      **arg;
4056     typval_T    *rettv;
4057     int         evaluate;
4058 {
4059     int         result;
4060     typval_T    var2;
4061
4062     /*
4063      * Get the first variable.
4064      */
4065     if (eval2(arg, rettv, evaluate) == FAIL)
4066         return FAIL;
4067
4068     if ((*arg)[0] == '?')
4069     {
4070         result = FALSE;
4071         if (evaluate)
4072         {
4073             int         error = FALSE;
4074
4075             if (get_tv_number_chk(rettv, &error) != 0)
4076                 result = TRUE;
4077             clear_tv(rettv);
4078             if (error)
4079                 return FAIL;
4080         }
4081
4082         /*
4083          * Get the second variable.
4084          */
4085         *arg = skipwhite(*arg + 1);
4086         if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
4087             return FAIL;
4088
4089         /*
4090          * Check for the ":".
4091          */
4092         if ((*arg)[0] != ':')
4093         {
4094             EMSG(_("E109: Missing ':' after '?'"));
4095             if (evaluate && result)
4096                 clear_tv(rettv);
4097             return FAIL;
4098         }
4099
4100         /*
4101          * Get the third variable.
4102          */
4103         *arg = skipwhite(*arg + 1);
4104         if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
4105         {
4106             if (evaluate && result)
4107                 clear_tv(rettv);
4108             return FAIL;
4109         }
4110         if (evaluate && !result)
4111             *rettv = var2;
4112     }
4113
4114     return OK;
4115 }
4116
4117 /*
4118  * Handle first level expression:
4119  *      expr2 || expr2 || expr2     logical OR
4120  *
4121  * "arg" must point to the first non-white of the expression.
4122  * "arg" is advanced to the next non-white after the recognized expression.
4123  *
4124  * Return OK or FAIL.
4125  */
4126     static int
4127 eval2(arg, rettv, evaluate)
4128     char_u      **arg;
4129     typval_T    *rettv;
4130     int         evaluate;
4131 {
4132     typval_T    var2;
4133     long        result;
4134     int         first;
4135     int         error = FALSE;
4136
4137     /*
4138      * Get the first variable.
4139      */
4140     if (eval3(arg, rettv, evaluate) == FAIL)
4141         return FAIL;
4142
4143     /*
4144      * Repeat until there is no following "||".
4145      */
4146     first = TRUE;
4147     result = FALSE;
4148     while ((*arg)[0] == '|' && (*arg)[1] == '|')
4149     {
4150         if (evaluate && first)
4151         {
4152             if (get_tv_number_chk(rettv, &error) != 0)
4153                 result = TRUE;
4154             clear_tv(rettv);
4155             if (error)
4156                 return FAIL;
4157             first = FALSE;
4158         }
4159
4160         /*
4161          * Get the second variable.
4162          */
4163         *arg = skipwhite(*arg + 2);
4164         if (eval3(arg, &var2, evaluate && !result) == FAIL)
4165             return FAIL;
4166
4167         /*
4168          * Compute the result.
4169          */
4170         if (evaluate && !result)
4171         {
4172             if (get_tv_number_chk(&var2, &error) != 0)
4173                 result = TRUE;
4174             clear_tv(&var2);
4175             if (error)
4176                 return FAIL;
4177         }
4178         if (evaluate)
4179         {
4180             rettv->v_type = VAR_NUMBER;
4181             rettv->vval.v_number = result;
4182         }
4183     }
4184
4185     return OK;
4186 }
4187
4188 /*
4189  * Handle second level expression:
4190  *      expr3 && expr3 && expr3     logical AND
4191  *
4192  * "arg" must point to the first non-white of the expression.
4193  * "arg" is advanced to the next non-white after the recognized expression.
4194  *
4195  * Return OK or FAIL.
4196  */
4197     static int
4198 eval3(arg, rettv, evaluate)
4199     char_u      **arg;
4200     typval_T    *rettv;
4201     int         evaluate;
4202 {
4203     typval_T    var2;
4204     long        result;
4205     int         first;
4206     int         error = FALSE;
4207
4208     /*
4209      * Get the first variable.
4210      */
4211     if (eval4(arg, rettv, evaluate) == FAIL)
4212         return FAIL;
4213
4214     /*
4215      * Repeat until there is no following "&&".
4216      */
4217     first = TRUE;
4218     result = TRUE;
4219     while ((*arg)[0] == '&' && (*arg)[1] == '&')
4220     {
4221         if (evaluate && first)
4222         {
4223             if (get_tv_number_chk(rettv, &error) == 0)
4224                 result = FALSE;
4225             clear_tv(rettv);
4226             if (error)
4227                 return FAIL;
4228             first = FALSE;
4229         }
4230
4231         /*
4232          * Get the second variable.
4233          */
4234         *arg = skipwhite(*arg + 2);
4235         if (eval4(arg, &var2, evaluate && result) == FAIL)
4236             return FAIL;
4237
4238         /*
4239          * Compute the result.
4240          */
4241         if (evaluate && result)
4242         {
4243             if (get_tv_number_chk(&var2, &error) == 0)
4244                 result = FALSE;
4245             clear_tv(&var2);
4246             if (error)
4247                 return FAIL;
4248         }
4249         if (evaluate)
4250         {
4251             rettv->v_type = VAR_NUMBER;
4252             rettv->vval.v_number = result;
4253         }
4254     }
4255
4256     return OK;
4257 }
4258
4259 /*
4260  * Handle third level expression:
4261  *      var1 == var2
4262  *      var1 =~ var2
4263  *      var1 != var2
4264  *      var1 !~ var2
4265  *      var1 > var2
4266  *      var1 >= var2
4267  *      var1 < var2
4268  *      var1 <= var2
4269  *      var1 is var2
4270  *      var1 isnot var2
4271  *
4272  * "arg" must point to the first non-white of the expression.
4273  * "arg" is advanced to the next non-white after the recognized expression.
4274  *
4275  * Return OK or FAIL.
4276  */
4277     static int
4278 eval4(arg, rettv, evaluate)
4279     char_u      **arg;
4280     typval_T    *rettv;
4281     int         evaluate;
4282 {
4283     typval_T    var2;
4284     char_u      *p;
4285     int         i;
4286     exptype_T   type = TYPE_UNKNOWN;
4287     int         type_is = FALSE;    /* TRUE for "is" and "isnot" */
4288     int         len = 2;
4289     long        n1, n2;
4290     char_u      *s1, *s2;
4291     char_u      buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4292     regmatch_T  regmatch;
4293     int         ic;
4294     char_u      *save_cpo;
4295
4296     /*
4297      * Get the first variable.
4298      */
4299     if (eval5(arg, rettv, evaluate) == FAIL)
4300         return FAIL;
4301
4302     p = *arg;
4303     switch (p[0])
4304     {
4305         case '=':   if (p[1] == '=')
4306                         type = TYPE_EQUAL;
4307                     else if (p[1] == '~')
4308                         type = TYPE_MATCH;
4309                     break;
4310         case '!':   if (p[1] == '=')
4311                         type = TYPE_NEQUAL;
4312                     else if (p[1] == '~')
4313                         type = TYPE_NOMATCH;
4314                     break;
4315         case '>':   if (p[1] != '=')
4316                     {
4317                         type = TYPE_GREATER;
4318                         len = 1;
4319                     }
4320                     else
4321                         type = TYPE_GEQUAL;
4322                     break;
4323         case '<':   if (p[1] != '=')
4324                     {
4325                         type = TYPE_SMALLER;
4326                         len = 1;
4327                     }
4328                     else
4329                         type = TYPE_SEQUAL;
4330                     break;
4331         case 'i':   if (p[1] == 's')
4332                     {
4333                         if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4334                             len = 5;
4335                         if (!vim_isIDc(p[len]))
4336                         {
4337                             type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4338                             type_is = TRUE;
4339                         }
4340                     }
4341                     break;
4342     }
4343
4344     /*
4345      * If there is a comparative operator, use it.
4346      */
4347     if (type != TYPE_UNKNOWN)
4348     {
4349         /* extra question mark appended: ignore case */
4350         if (p[len] == '?')
4351         {
4352             ic = TRUE;
4353             ++len;
4354         }
4355         /* extra '#' appended: match case */
4356         else if (p[len] == '#')
4357         {
4358             ic = FALSE;
4359             ++len;
4360         }
4361         /* nothing appended: use 'ignorecase' */
4362         else
4363             ic = p_ic;
4364
4365         /*
4366          * Get the second variable.
4367          */
4368         *arg = skipwhite(p + len);
4369         if (eval5(arg, &var2, evaluate) == FAIL)
4370         {
4371             clear_tv(rettv);
4372             return FAIL;
4373         }
4374
4375         if (evaluate)
4376         {
4377             if (type_is && rettv->v_type != var2.v_type)
4378             {
4379                 /* For "is" a different type always means FALSE, for "notis"
4380                  * it means TRUE. */
4381                 n1 = (type == TYPE_NEQUAL);
4382             }
4383             else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4384             {
4385                 if (type_is)
4386                 {
4387                     n1 = (rettv->v_type == var2.v_type
4388                                    && rettv->vval.v_list == var2.vval.v_list);
4389                     if (type == TYPE_NEQUAL)
4390                         n1 = !n1;
4391                 }
4392                 else if (rettv->v_type != var2.v_type
4393                         || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4394                 {
4395                     if (rettv->v_type != var2.v_type)
4396                         EMSG(_("E691: Can only compare List with List"));
4397                     else
4398                         EMSG(_("E692: Invalid operation for Lists"));
4399                     clear_tv(rettv);
4400                     clear_tv(&var2);
4401                     return FAIL;
4402                 }
4403                 else
4404                 {
4405                     /* Compare two Lists for being equal or unequal. */
4406                     n1 = list_equal(rettv->vval.v_list, var2.vval.v_list,
4407                                                                    ic, FALSE);
4408                     if (type == TYPE_NEQUAL)
4409                         n1 = !n1;
4410                 }
4411             }
4412
4413             else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4414             {
4415                 if (type_is)
4416                 {
4417                     n1 = (rettv->v_type == var2.v_type
4418                                    && rettv->vval.v_dict == var2.vval.v_dict);
4419                     if (type == TYPE_NEQUAL)
4420                         n1 = !n1;
4421                 }
4422                 else if (rettv->v_type != var2.v_type
4423                         || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4424                 {
4425                     if (rettv->v_type != var2.v_type)
4426                         EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4427                     else
4428                         EMSG(_("E736: Invalid operation for Dictionary"));
4429                     clear_tv(rettv);
4430                     clear_tv(&var2);
4431                     return FAIL;
4432                 }
4433                 else
4434                 {
4435                     /* Compare two Dictionaries for being equal or unequal. */
4436                     n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict,
4437                                                                    ic, FALSE);
4438                     if (type == TYPE_NEQUAL)
4439                         n1 = !n1;
4440                 }
4441             }
4442
4443             else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4444             {
4445                 if (rettv->v_type != var2.v_type
4446                         || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4447                 {
4448                     if (rettv->v_type != var2.v_type)
4449                         EMSG(_("E693: Can only compare Funcref with Funcref"));
4450                     else
4451                         EMSG(_("E694: Invalid operation for Funcrefs"));
4452                     clear_tv(rettv);
4453                     clear_tv(&var2);
4454                     return FAIL;
4455                 }
4456                 else
4457                 {
4458                     /* Compare two Funcrefs for being equal or unequal. */
4459                     if (rettv->vval.v_string == NULL
4460                                                 || var2.vval.v_string == NULL)
4461                         n1 = FALSE;
4462                     else
4463                         n1 = STRCMP(rettv->vval.v_string,
4464                                                      var2.vval.v_string) == 0;
4465                     if (type == TYPE_NEQUAL)
4466                         n1 = !n1;
4467                 }
4468             }
4469
4470 #ifdef FEAT_FLOAT
4471             /*
4472              * If one of the two variables is a float, compare as a float.
4473              * When using "=~" or "!~", always compare as string.
4474              */
4475             else if ((rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4476                     && type != TYPE_MATCH && type != TYPE_NOMATCH)
4477             {
4478                 float_T f1, f2;
4479
4480                 if (rettv->v_type == VAR_FLOAT)
4481                     f1 = rettv->vval.v_float;
4482                 else
4483                     f1 = get_tv_number(rettv);
4484                 if (var2.v_type == VAR_FLOAT)
4485                     f2 = var2.vval.v_float;
4486                 else
4487                     f2 = get_tv_number(&var2);
4488                 n1 = FALSE;
4489                 switch (type)
4490                 {
4491                     case TYPE_EQUAL:    n1 = (f1 == f2); break;
4492                     case TYPE_NEQUAL:   n1 = (f1 != f2); break;
4493                     case TYPE_GREATER:  n1 = (f1 > f2); break;
4494                     case TYPE_GEQUAL:   n1 = (f1 >= f2); break;
4495                     case TYPE_SMALLER:  n1 = (f1 < f2); break;
4496                     case TYPE_SEQUAL:   n1 = (f1 <= f2); break;
4497                     case TYPE_UNKNOWN:
4498                     case TYPE_MATCH:
4499                     case TYPE_NOMATCH:  break;  /* avoid gcc warning */
4500                 }
4501             }
4502 #endif
4503
4504             /*
4505              * If one of the two variables is a number, compare as a number.
4506              * When using "=~" or "!~", always compare as string.
4507              */
4508             else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4509                     && type != TYPE_MATCH && type != TYPE_NOMATCH)
4510             {
4511                 n1 = get_tv_number(rettv);
4512                 n2 = get_tv_number(&var2);
4513                 switch (type)
4514                 {
4515                     case TYPE_EQUAL:    n1 = (n1 == n2); break;
4516                     case TYPE_NEQUAL:   n1 = (n1 != n2); break;
4517                     case TYPE_GREATER:  n1 = (n1 > n2); break;
4518                     case TYPE_GEQUAL:   n1 = (n1 >= n2); break;
4519                     case TYPE_SMALLER:  n1 = (n1 < n2); break;
4520                     case TYPE_SEQUAL:   n1 = (n1 <= n2); break;
4521                     case TYPE_UNKNOWN:
4522                     case TYPE_MATCH:
4523                     case TYPE_NOMATCH:  break;  /* avoid gcc warning */
4524                 }
4525             }
4526             else
4527             {
4528                 s1 = get_tv_string_buf(rettv, buf1);
4529                 s2 = get_tv_string_buf(&var2, buf2);
4530                 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4531                     i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4532                 else
4533                     i = 0;
4534                 n1 = FALSE;
4535                 switch (type)
4536                 {
4537                     case TYPE_EQUAL:    n1 = (i == 0); break;
4538                     case TYPE_NEQUAL:   n1 = (i != 0); break;
4539                     case TYPE_GREATER:  n1 = (i > 0); break;
4540                     case TYPE_GEQUAL:   n1 = (i >= 0); break;
4541                     case TYPE_SMALLER:  n1 = (i < 0); break;
4542                     case TYPE_SEQUAL:   n1 = (i <= 0); break;
4543
4544                     case TYPE_MATCH:
4545                     case TYPE_NOMATCH:
4546                             /* avoid 'l' flag in 'cpoptions' */
4547                             save_cpo = p_cpo;
4548                             p_cpo = (char_u *)"";
4549                             regmatch.regprog = vim_regcomp(s2,
4550                                                         RE_MAGIC + RE_STRING);
4551                             regmatch.rm_ic = ic;
4552                             if (regmatch.regprog != NULL)
4553                             {
4554                                 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4555                                 vim_free(regmatch.regprog);
4556                                 if (type == TYPE_NOMATCH)
4557                                     n1 = !n1;
4558                             }
4559                             p_cpo = save_cpo;
4560                             break;
4561
4562                     case TYPE_UNKNOWN:  break;  /* avoid gcc warning */
4563                 }
4564             }
4565             clear_tv(rettv);
4566             clear_tv(&var2);
4567             rettv->v_type = VAR_NUMBER;
4568             rettv->vval.v_number = n1;
4569         }
4570     }
4571
4572     return OK;
4573 }
4574
4575 /*
4576  * Handle fourth level expression:
4577  *      +       number addition
4578  *      -       number subtraction
4579  *      .       string concatenation
4580  *
4581  * "arg" must point to the first non-white of the expression.
4582  * "arg" is advanced to the next non-white after the recognized expression.
4583  *
4584  * Return OK or FAIL.
4585  */
4586     static int
4587 eval5(arg, rettv, evaluate)
4588     char_u      **arg;
4589     typval_T    *rettv;
4590     int         evaluate;
4591 {
4592     typval_T    var2;
4593     typval_T    var3;
4594     int         op;
4595     long        n1, n2;
4596 #ifdef FEAT_FLOAT
4597     float_T     f1 = 0, f2 = 0;
4598 #endif
4599     char_u      *s1, *s2;
4600     char_u      buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4601     char_u      *p;
4602
4603     /*
4604      * Get the first variable.
4605      */
4606     if (eval6(arg, rettv, evaluate, FALSE) == FAIL)
4607         return FAIL;
4608
4609     /*
4610      * Repeat computing, until no '+', '-' or '.' is following.
4611      */
4612     for (;;)
4613     {
4614         op = **arg;
4615         if (op != '+' && op != '-' && op != '.')
4616             break;
4617
4618         if ((op != '+' || rettv->v_type != VAR_LIST)
4619 #ifdef FEAT_FLOAT
4620                 && (op == '.' || rettv->v_type != VAR_FLOAT)
4621 #endif
4622                 )
4623         {
4624             /* For "list + ...", an illegal use of the first operand as
4625              * a number cannot be determined before evaluating the 2nd
4626              * operand: if this is also a list, all is ok.
4627              * For "something . ...", "something - ..." or "non-list + ...",
4628              * we know that the first operand needs to be a string or number
4629              * without evaluating the 2nd operand.  So check before to avoid
4630              * side effects after an error. */
4631             if (evaluate && get_tv_string_chk(rettv) == NULL)
4632             {
4633                 clear_tv(rettv);
4634                 return FAIL;
4635             }
4636         }
4637
4638         /*
4639          * Get the second variable.
4640          */
4641         *arg = skipwhite(*arg + 1);
4642         if (eval6(arg, &var2, evaluate, op == '.') == FAIL)
4643         {
4644             clear_tv(rettv);
4645             return FAIL;
4646         }
4647
4648         if (evaluate)
4649         {
4650             /*
4651              * Compute the result.
4652              */
4653             if (op == '.')
4654             {
4655                 s1 = get_tv_string_buf(rettv, buf1);    /* already checked */
4656                 s2 = get_tv_string_buf_chk(&var2, buf2);
4657                 if (s2 == NULL)         /* type error ? */
4658                 {
4659                     clear_tv(rettv);
4660                     clear_tv(&var2);
4661                     return FAIL;
4662                 }
4663                 p = concat_str(s1, s2);
4664                 clear_tv(rettv);
4665                 rettv->v_type = VAR_STRING;
4666                 rettv->vval.v_string = p;
4667             }
4668             else if (op == '+' && rettv->v_type == VAR_LIST
4669                                                    && var2.v_type == VAR_LIST)
4670             {
4671                 /* concatenate Lists */
4672                 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4673                                                                &var3) == FAIL)
4674                 {
4675                     clear_tv(rettv);
4676                     clear_tv(&var2);
4677                     return FAIL;
4678                 }
4679                 clear_tv(rettv);
4680                 *rettv = var3;
4681             }
4682             else
4683             {
4684                 int         error = FALSE;
4685
4686 #ifdef FEAT_FLOAT
4687                 if (rettv->v_type == VAR_FLOAT)
4688                 {
4689                     f1 = rettv->vval.v_float;
4690                     n1 = 0;
4691                 }
4692                 else
4693 #endif
4694                 {
4695                     n1 = get_tv_number_chk(rettv, &error);
4696                     if (error)
4697                     {
4698                         /* This can only happen for "list + non-list".  For
4699                          * "non-list + ..." or "something - ...", we returned
4700                          * before evaluating the 2nd operand. */
4701                         clear_tv(rettv);
4702                         return FAIL;
4703                     }
4704 #ifdef FEAT_FLOAT
4705                     if (var2.v_type == VAR_FLOAT)
4706                         f1 = n1;
4707 #endif
4708                 }
4709 #ifdef FEAT_FLOAT
4710                 if (var2.v_type == VAR_FLOAT)
4711                 {
4712                     f2 = var2.vval.v_float;
4713                     n2 = 0;
4714                 }
4715                 else
4716 #endif
4717                 {
4718                     n2 = get_tv_number_chk(&var2, &error);
4719                     if (error)
4720                     {
4721                         clear_tv(rettv);
4722                         clear_tv(&var2);
4723                         return FAIL;
4724                     }
4725 #ifdef FEAT_FLOAT
4726                     if (rettv->v_type == VAR_FLOAT)
4727                         f2 = n2;
4728 #endif
4729                 }
4730                 clear_tv(rettv);
4731
4732 #ifdef FEAT_FLOAT
4733                 /* If there is a float on either side the result is a float. */
4734                 if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4735                 {
4736                     if (op == '+')
4737                         f1 = f1 + f2;
4738                     else
4739                         f1 = f1 - f2;
4740                     rettv->v_type = VAR_FLOAT;
4741                     rettv->vval.v_float = f1;
4742                 }
4743                 else
4744 #endif
4745                 {
4746                     if (op == '+')
4747                         n1 = n1 + n2;
4748                     else
4749                         n1 = n1 - n2;
4750                     rettv->v_type = VAR_NUMBER;
4751                     rettv->vval.v_number = n1;
4752                 }
4753             }
4754             clear_tv(&var2);
4755         }
4756     }
4757     return OK;
4758 }
4759
4760 /*
4761  * Handle fifth level expression:
4762  *      *       number multiplication
4763  *      /       number division
4764  *      %       number modulo
4765  *
4766  * "arg" must point to the first non-white of the expression.
4767  * "arg" is advanced to the next non-white after the recognized expression.
4768  *
4769  * Return OK or FAIL.
4770  */
4771     static int
4772 eval6(arg, rettv, evaluate, want_string)
4773     char_u      **arg;
4774     typval_T    *rettv;
4775     int         evaluate;
4776     int         want_string;  /* after "." operator */
4777 {
4778     typval_T    var2;
4779     int         op;
4780     long        n1, n2;
4781 #ifdef FEAT_FLOAT
4782     int         use_float = FALSE;
4783     float_T     f1 = 0, f2;
4784 #endif
4785     int         error = FALSE;
4786
4787     /*
4788      * Get the first variable.
4789      */
4790     if (eval7(arg, rettv, evaluate, want_string) == FAIL)
4791         return FAIL;
4792
4793     /*
4794      * Repeat computing, until no '*', '/' or '%' is following.
4795      */
4796     for (;;)
4797     {
4798         op = **arg;
4799         if (op != '*' && op != '/' && op != '%')
4800             break;
4801
4802         if (evaluate)
4803         {
4804 #ifdef FEAT_FLOAT
4805             if (rettv->v_type == VAR_FLOAT)
4806             {
4807                 f1 = rettv->vval.v_float;
4808                 use_float = TRUE;
4809                 n1 = 0;
4810             }
4811             else
4812 #endif
4813                 n1 = get_tv_number_chk(rettv, &error);
4814             clear_tv(rettv);
4815             if (error)
4816                 return FAIL;
4817         }
4818         else
4819             n1 = 0;
4820
4821         /*
4822          * Get the second variable.
4823          */
4824         *arg = skipwhite(*arg + 1);
4825         if (eval7(arg, &var2, evaluate, FALSE) == FAIL)
4826             return FAIL;
4827
4828         if (evaluate)
4829         {
4830 #ifdef FEAT_FLOAT
4831             if (var2.v_type == VAR_FLOAT)
4832             {
4833                 if (!use_float)
4834                 {
4835                     f1 = n1;
4836                     use_float = TRUE;
4837                 }
4838                 f2 = var2.vval.v_float;
4839                 n2 = 0;
4840             }
4841             else
4842 #endif
4843             {
4844                 n2 = get_tv_number_chk(&var2, &error);
4845                 clear_tv(&var2);
4846                 if (error)
4847                     return FAIL;
4848 #ifdef FEAT_FLOAT
4849                 if (use_float)
4850                     f2 = n2;
4851 #endif
4852             }
4853
4854             /*
4855              * Compute the result.
4856              * When either side is a float the result is a float.
4857              */
4858 #ifdef FEAT_FLOAT
4859             if (use_float)
4860             {
4861                 if (op == '*')
4862                     f1 = f1 * f2;
4863                 else if (op == '/')
4864                 {
4865 # ifdef VMS
4866                     /* VMS crashes on divide by zero, work around it */
4867                     if (f2 == 0.0)
4868                     {
4869                         if (f1 == 0)
4870                             f1 = -1 * __F_FLT_MAX - 1L;   /* similar to NaN */
4871                         else if (f1 < 0)
4872                             f1 = -1 * __F_FLT_MAX;
4873                         else
4874                             f1 = __F_FLT_MAX;
4875                     }
4876                     else
4877                         f1 = f1 / f2;
4878 # else
4879                     /* We rely on the floating point library to handle divide
4880                      * by zero to result in "inf" and not a crash. */
4881                     f1 = f1 / f2;
4882 # endif
4883                 }
4884                 else
4885                 {
4886                     EMSG(_("E804: Cannot use '%' with Float"));
4887                     return FAIL;
4888                 }
4889                 rettv->v_type = VAR_FLOAT;
4890                 rettv->vval.v_float = f1;
4891             }
4892             else
4893 #endif
4894             {
4895                 if (op == '*')
4896                     n1 = n1 * n2;
4897                 else if (op == '/')
4898                 {
4899                     if (n2 == 0)        /* give an error message? */
4900                     {
4901                         if (n1 == 0)
4902                             n1 = -0x7fffffffL - 1L;     /* similar to NaN */
4903                         else if (n1 < 0)
4904                             n1 = -0x7fffffffL;
4905                         else
4906                             n1 = 0x7fffffffL;
4907                     }
4908                     else
4909                         n1 = n1 / n2;
4910                 }
4911                 else
4912                 {
4913                     if (n2 == 0)        /* give an error message? */
4914                         n1 = 0;
4915                     else
4916                         n1 = n1 % n2;
4917                 }
4918                 rettv->v_type = VAR_NUMBER;
4919                 rettv->vval.v_number = n1;
4920             }
4921         }
4922     }
4923
4924     return OK;
4925 }
4926
4927 /*
4928  * Handle sixth level expression:
4929  *  number              number constant
4930  *  "string"            string constant
4931  *  'string'            literal string constant
4932  *  &option-name        option value
4933  *  @r                  register contents
4934  *  identifier          variable value
4935  *  function()          function call
4936  *  $VAR                environment variable
4937  *  (expression)        nested expression
4938  *  [expr, expr]        List
4939  *  {key: val, key: val}  Dictionary
4940  *
4941  *  Also handle:
4942  *  ! in front          logical NOT
4943  *  - in front          unary minus
4944  *  + in front          unary plus (ignored)
4945  *  trailing []         subscript in String or List
4946  *  trailing .name      entry in Dictionary
4947  *
4948  * "arg" must point to the first non-white of the expression.
4949  * "arg" is advanced to the next non-white after the recognized expression.
4950  *
4951  * Return OK or FAIL.
4952  */
4953     static int
4954 eval7(arg, rettv, evaluate, want_string)
4955     char_u      **arg;
4956     typval_T    *rettv;
4957     int         evaluate;
4958     int         want_string UNUSED;     /* after "." operator */
4959 {
4960     long        n;
4961     int         len;
4962     char_u      *s;
4963     char_u      *start_leader, *end_leader;
4964     int         ret = OK;
4965     char_u      *alias;
4966
4967     /*
4968      * Initialise variable so that clear_tv() can't mistake this for a
4969      * string and free a string that isn't there.
4970      */
4971     rettv->v_type = VAR_UNKNOWN;
4972
4973     /*
4974      * Skip '!' and '-' characters.  They are handled later.
4975      */
4976     start_leader = *arg;
4977     while (**arg == '!' || **arg == '-' || **arg == '+')
4978         *arg = skipwhite(*arg + 1);
4979     end_leader = *arg;
4980
4981     switch (**arg)
4982     {
4983     /*
4984      * Number constant.
4985      */
4986     case '0':
4987     case '1':
4988     case '2':
4989     case '3':
4990     case '4':
4991     case '5':
4992     case '6':
4993     case '7':
4994     case '8':
4995     case '9':
4996         {
4997 #ifdef FEAT_FLOAT
4998                 char_u *p = skipdigits(*arg + 1);
4999                 int    get_float = FALSE;
5000
5001                 /* We accept a float when the format matches
5002                  * "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?".  This is very
5003                  * strict to avoid backwards compatibility problems.
5004                  * Don't look for a float after the "." operator, so that
5005                  * ":let vers = 1.2.3" doesn't fail. */
5006                 if (!want_string && p[0] == '.' && vim_isdigit(p[1]))
5007                 {
5008                     get_float = TRUE;
5009                     p = skipdigits(p + 2);
5010                     if (*p == 'e' || *p == 'E')
5011                     {
5012                         ++p;
5013                         if (*p == '-' || *p == '+')
5014                             ++p;
5015                         if (!vim_isdigit(*p))
5016                             get_float = FALSE;
5017                         else
5018                             p = skipdigits(p + 1);
5019                     }
5020                     if (ASCII_ISALPHA(*p) || *p == '.')
5021                         get_float = FALSE;
5022                 }
5023                 if (get_float)
5024                 {
5025                     float_T     f;
5026
5027                     *arg += string2float(*arg, &f);
5028                     if (evaluate)
5029                     {
5030                         rettv->v_type = VAR_FLOAT;
5031                         rettv->vval.v_float = f;
5032                     }
5033                 }
5034                 else
5035 #endif
5036                 {
5037                     vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
5038                     *arg += len;
5039                     if (evaluate)
5040                     {
5041                         rettv->v_type = VAR_NUMBER;
5042                         rettv->vval.v_number = n;
5043                     }
5044                 }
5045                 break;
5046         }
5047
5048     /*
5049      * String constant: "string".
5050      */
5051     case '"':   ret = get_string_tv(arg, rettv, evaluate);
5052                 break;
5053
5054     /*
5055      * Literal string constant: 'str''ing'.
5056      */
5057     case '\'':  ret = get_lit_string_tv(arg, rettv, evaluate);
5058                 break;
5059
5060     /*
5061      * List: [expr, expr]
5062      */
5063     case '[':   ret = get_list_tv(arg, rettv, evaluate);
5064                 break;
5065
5066     /*
5067      * Dictionary: {key: val, key: val}
5068      */
5069     case '{':   ret = get_dict_tv(arg, rettv, evaluate);
5070                 break;
5071
5072     /*
5073      * Option value: &name
5074      */
5075     case '&':   ret = get_option_tv(arg, rettv, evaluate);
5076                 break;
5077
5078     /*
5079      * Environment variable: $VAR.
5080      */
5081     case '$':   ret = get_env_tv(arg, rettv, evaluate);
5082                 break;
5083
5084     /*
5085      * Register contents: @r.
5086      */
5087     case '@':   ++*arg;
5088                 if (evaluate)
5089                 {
5090                     rettv->v_type = VAR_STRING;
5091                     rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
5092                 }
5093                 if (**arg != NUL)
5094                     ++*arg;
5095                 break;
5096
5097     /*
5098      * nested expression: (expression).
5099      */
5100     case '(':   *arg = skipwhite(*arg + 1);
5101                 ret = eval1(arg, rettv, evaluate);      /* recursive! */
5102                 if (**arg == ')')
5103                     ++*arg;
5104                 else if (ret == OK)
5105                 {
5106                     EMSG(_("E110: Missing ')'"));
5107                     clear_tv(rettv);
5108                     ret = FAIL;
5109                 }
5110                 break;
5111
5112     default:    ret = NOTDONE;
5113                 break;
5114     }
5115
5116     if (ret == NOTDONE)
5117     {
5118         /*
5119          * Must be a variable or function name.
5120          * Can also be a curly-braces kind of name: {expr}.
5121          */
5122         s = *arg;
5123         len = get_name_len(arg, &alias, evaluate, TRUE);
5124         if (alias != NULL)
5125             s = alias;
5126
5127         if (len <= 0)
5128             ret = FAIL;
5129         else
5130         {
5131             if (**arg == '(')           /* recursive! */
5132             {
5133                 /* If "s" is the name of a variable of type VAR_FUNC
5134                  * use its contents. */
5135                 s = deref_func_name(s, &len);
5136
5137                 /* Invoke the function. */
5138                 ret = get_func_tv(s, len, rettv, arg,
5139                           curwin->w_cursor.lnum, curwin->w_cursor.lnum,
5140                           &len, evaluate, NULL);
5141                 /* Stop the expression evaluation when immediately
5142                  * aborting on error, or when an interrupt occurred or
5143                  * an exception was thrown but not caught. */
5144                 if (aborting())
5145                 {
5146                     if (ret == OK)
5147                         clear_tv(rettv);
5148                     ret = FAIL;
5149                 }
5150             }
5151             else if (evaluate)
5152                 ret = get_var_tv(s, len, rettv, TRUE);
5153             else
5154                 ret = OK;
5155         }
5156         vim_free(alias);
5157     }
5158
5159     *arg = skipwhite(*arg);
5160
5161     /* Handle following '[', '(' and '.' for expr[expr], expr.name,
5162      * expr(expr). */
5163     if (ret == OK)
5164         ret = handle_subscript(arg, rettv, evaluate, TRUE);
5165
5166     /*
5167      * Apply logical NOT and unary '-', from right to left, ignore '+'.
5168      */
5169     if (ret == OK && evaluate && end_leader > start_leader)
5170     {
5171         int         error = FALSE;
5172         int         val = 0;
5173 #ifdef FEAT_FLOAT
5174         float_T     f = 0.0;
5175
5176         if (rettv->v_type == VAR_FLOAT)
5177             f = rettv->vval.v_float;
5178         else
5179 #endif
5180             val = get_tv_number_chk(rettv, &error);
5181         if (error)
5182         {
5183             clear_tv(rettv);
5184             ret = FAIL;
5185         }
5186         else
5187         {
5188             while (end_leader > start_leader)
5189             {
5190                 --end_leader;
5191                 if (*end_leader == '!')
5192                 {
5193 #ifdef FEAT_FLOAT
5194                     if (rettv->v_type == VAR_FLOAT)
5195                         f = !f;
5196                     else
5197 #endif
5198                         val = !val;
5199                 }
5200                 else if (*end_leader == '-')
5201                 {
5202 #ifdef FEAT_FLOAT
5203                     if (rettv->v_type == VAR_FLOAT)
5204                         f = -f;
5205                     else
5206 #endif
5207                         val = -val;
5208                 }
5209             }
5210 #ifdef FEAT_FLOAT
5211             if (rettv->v_type == VAR_FLOAT)
5212             {
5213                 clear_tv(rettv);
5214                 rettv->vval.v_float = f;
5215             }
5216             else
5217 #endif
5218             {
5219                 clear_tv(rettv);
5220                 rettv->v_type = VAR_NUMBER;
5221                 rettv->vval.v_number = val;
5222             }
5223         }
5224     }
5225
5226     return ret;
5227 }
5228
5229 /*
5230  * Evaluate an "[expr]" or "[expr:expr]" index.  Also "dict.key".
5231  * "*arg" points to the '[' or '.'.
5232  * Returns FAIL or OK. "*arg" is advanced to after the ']'.
5233  */
5234     static int
5235 eval_index(arg, rettv, evaluate, verbose)
5236     char_u      **arg;
5237     typval_T    *rettv;
5238     int         evaluate;
5239     int         verbose;        /* give error messages */
5240 {
5241     int         empty1 = FALSE, empty2 = FALSE;
5242     typval_T    var1, var2;
5243     long        n1, n2 = 0;
5244     long        len = -1;
5245     int         range = FALSE;
5246     char_u      *s;
5247     char_u      *key = NULL;
5248
5249     if (rettv->v_type == VAR_FUNC
5250 #ifdef FEAT_FLOAT
5251             || rettv->v_type == VAR_FLOAT
5252 #endif
5253             )
5254     {
5255         if (verbose)
5256             EMSG(_("E695: Cannot index a Funcref"));
5257         return FAIL;
5258     }
5259
5260     if (**arg == '.')
5261     {
5262         /*
5263          * dict.name
5264          */
5265         key = *arg + 1;
5266         for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
5267             ;
5268         if (len == 0)
5269             return FAIL;
5270         *arg = skipwhite(key + len);
5271     }
5272     else
5273     {
5274         /*
5275          * something[idx]
5276          *
5277          * Get the (first) variable from inside the [].
5278          */
5279         *arg = skipwhite(*arg + 1);
5280         if (**arg == ':')
5281             empty1 = TRUE;
5282         else if (eval1(arg, &var1, evaluate) == FAIL)   /* recursive! */
5283             return FAIL;
5284         else if (evaluate && get_tv_string_chk(&var1) == NULL)
5285         {
5286             /* not a number or string */
5287             clear_tv(&var1);
5288             return FAIL;
5289         }
5290
5291         /*
5292          * Get the second variable from inside the [:].
5293          */
5294         if (**arg == ':')
5295         {
5296             range = TRUE;
5297             *arg = skipwhite(*arg + 1);
5298             if (**arg == ']')
5299                 empty2 = TRUE;
5300             else if (eval1(arg, &var2, evaluate) == FAIL)       /* recursive! */
5301             {
5302                 if (!empty1)
5303                     clear_tv(&var1);
5304                 return FAIL;
5305             }
5306             else if (evaluate && get_tv_string_chk(&var2) == NULL)
5307             {
5308                 /* not a number or string */
5309                 if (!empty1)
5310                     clear_tv(&var1);
5311                 clear_tv(&var2);
5312                 return FAIL;
5313             }
5314         }
5315
5316         /* Check for the ']'. */
5317         if (**arg != ']')
5318         {
5319             if (verbose)
5320                 EMSG(_(e_missbrac));
5321             clear_tv(&var1);
5322             if (range)
5323                 clear_tv(&var2);
5324             return FAIL;
5325         }
5326         *arg = skipwhite(*arg + 1);     /* skip the ']' */
5327     }
5328
5329     if (evaluate)
5330     {
5331         n1 = 0;
5332         if (!empty1 && rettv->v_type != VAR_DICT)
5333         {
5334             n1 = get_tv_number(&var1);
5335             clear_tv(&var1);
5336         }
5337         if (range)
5338         {
5339             if (empty2)
5340                 n2 = -1;
5341             else
5342             {
5343                 n2 = get_tv_number(&var2);
5344                 clear_tv(&var2);
5345             }
5346         }
5347
5348         switch (rettv->v_type)
5349         {
5350             case VAR_NUMBER:
5351             case VAR_STRING:
5352                 s = get_tv_string(rettv);
5353                 len = (long)STRLEN(s);
5354                 if (range)
5355                 {
5356                     /* The resulting variable is a substring.  If the indexes
5357                      * are out of range the result is empty. */
5358                     if (n1 < 0)
5359                     {
5360                         n1 = len + n1;
5361                         if (n1 < 0)
5362                             n1 = 0;
5363                     }
5364                     if (n2 < 0)
5365                         n2 = len + n2;
5366                     else if (n2 >= len)
5367                         n2 = len;
5368                     if (n1 >= len || n2 < 0 || n1 > n2)
5369                         s = NULL;
5370                     else
5371                         s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
5372                 }
5373                 else
5374                 {
5375                     /* The resulting variable is a string of a single
5376                      * character.  If the index is too big or negative the
5377                      * result is empty. */
5378                     if (n1 >= len || n1 < 0)
5379                         s = NULL;
5380                     else
5381                         s = vim_strnsave(s + n1, 1);
5382                 }
5383                 clear_tv(rettv);
5384                 rettv->v_type = VAR_STRING;
5385                 rettv->vval.v_string = s;
5386                 break;
5387
5388             case VAR_LIST:
5389                 len = list_len(rettv->vval.v_list);
5390                 if (n1 < 0)
5391                     n1 = len + n1;
5392                 if (!empty1 && (n1 < 0 || n1 >= len))
5393                 {
5394                     /* For a range we allow invalid values and return an empty
5395                      * list.  A list index out of range is an error. */
5396                     if (!range)
5397                     {
5398                         if (verbose)
5399                             EMSGN(_(e_listidx), n1);
5400                         return FAIL;
5401                     }
5402                     n1 = len;
5403                 }
5404                 if (range)
5405                 {
5406                     list_T      *l;
5407                     listitem_T  *item;
5408
5409                     if (n2 < 0)
5410                         n2 = len + n2;
5411                     else if (n2 >= len)
5412                         n2 = len - 1;
5413                     if (!empty2 && (n2 < 0 || n2 + 1 < n1))
5414                         n2 = -1;
5415                     l = list_alloc();
5416                     if (l == NULL)
5417                         return FAIL;
5418                     for (item = list_find(rettv->vval.v_list, n1);
5419                                                                n1 <= n2; ++n1)
5420                     {
5421                         if (list_append_tv(l, &item->li_tv) == FAIL)
5422                         {
5423                             list_free(l, TRUE);
5424                             return FAIL;
5425                         }
5426                         item = item->li_next;
5427                     }
5428                     clear_tv(rettv);
5429                     rettv->v_type = VAR_LIST;
5430                     rettv->vval.v_list = l;
5431                     ++l->lv_refcount;
5432                 }
5433                 else
5434                 {
5435                     copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
5436                     clear_tv(rettv);
5437                     *rettv = var1;
5438                 }
5439                 break;
5440
5441             case VAR_DICT:
5442                 if (range)
5443                 {
5444                     if (verbose)
5445                         EMSG(_(e_dictrange));
5446                     if (len == -1)
5447                         clear_tv(&var1);
5448                     return FAIL;
5449                 }
5450                 {
5451                     dictitem_T  *item;
5452
5453                     if (len == -1)
5454                     {
5455                         key = get_tv_string(&var1);
5456                         if (*key == NUL)
5457                         {
5458                             if (verbose)
5459                                 EMSG(_(e_emptykey));
5460                             clear_tv(&var1);
5461                             return FAIL;
5462                         }
5463                     }
5464
5465                     item = dict_find(rettv->vval.v_dict, key, (int)len);
5466
5467                     if (item == NULL && verbose)
5468                         EMSG2(_(e_dictkey), key);
5469                     if (len == -1)
5470                         clear_tv(&var1);
5471                     if (item == NULL)
5472                         return FAIL;
5473
5474                     copy_tv(&item->di_tv, &var1);
5475                     clear_tv(rettv);
5476                     *rettv = var1;
5477                 }
5478                 break;
5479         }
5480     }
5481
5482     return OK;
5483 }
5484
5485 /*
5486  * Get an option value.
5487  * "arg" points to the '&' or '+' before the option name.
5488  * "arg" is advanced to character after the option name.
5489  * Return OK or FAIL.
5490  */
5491     static int
5492 get_option_tv(arg, rettv, evaluate)
5493     char_u      **arg;
5494     typval_T    *rettv; /* when NULL, only check if option exists */
5495     int         evaluate;
5496 {
5497     char_u      *option_end;
5498     long        numval;
5499     char_u      *stringval;
5500     int         opt_type;
5501     int         c;
5502     int         working = (**arg == '+');    /* has("+option") */
5503     int         ret = OK;
5504     int         opt_flags;
5505
5506     /*
5507      * Isolate the option name and find its value.
5508      */
5509     option_end = find_option_end(arg, &opt_flags);
5510     if (option_end == NULL)
5511     {
5512         if (rettv != NULL)
5513             EMSG2(_("E112: Option name missing: %s"), *arg);
5514         return FAIL;
5515     }
5516
5517     if (!evaluate)
5518     {
5519         *arg = option_end;
5520         return OK;
5521     }
5522
5523     c = *option_end;
5524     *option_end = NUL;
5525     opt_type = get_option_value(*arg, &numval,
5526                                rettv == NULL ? NULL : &stringval, opt_flags);
5527
5528     if (opt_type == -3)                 /* invalid name */
5529     {
5530         if (rettv != NULL)
5531             EMSG2(_("E113: Unknown option: %s"), *arg);
5532         ret = FAIL;
5533     }
5534     else if (rettv != NULL)
5535     {
5536         if (opt_type == -2)             /* hidden string option */
5537         {
5538             rettv->v_type = VAR_STRING;
5539             rettv->vval.v_string = NULL;
5540         }
5541         else if (opt_type == -1)        /* hidden number option */
5542         {
5543             rettv->v_type = VAR_NUMBER;
5544             rettv->vval.v_number = 0;
5545         }
5546         else if (opt_type == 1)         /* number option */
5547         {
5548             rettv->v_type = VAR_NUMBER;
5549             rettv->vval.v_number = numval;
5550         }
5551         else                            /* string option */
5552         {
5553             rettv->v_type = VAR_STRING;
5554             rettv->vval.v_string = stringval;
5555         }
5556     }
5557     else if (working && (opt_type == -2 || opt_type == -1))
5558         ret = FAIL;
5559
5560     *option_end = c;                /* put back for error messages */
5561     *arg = option_end;
5562
5563     return ret;
5564 }
5565
5566 /*
5567  * Allocate a variable for a string constant.
5568  * Return OK or FAIL.
5569  */
5570     static int
5571 get_string_tv(arg, rettv, evaluate)
5572     char_u      **arg;
5573     typval_T    *rettv;
5574     int         evaluate;
5575 {
5576     char_u      *p;
5577     char_u      *name;
5578     int         extra = 0;
5579
5580     /*
5581      * Find the end of the string, skipping backslashed characters.
5582      */
5583     for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5584     {
5585         if (*p == '\\' && p[1] != NUL)
5586         {
5587             ++p;
5588             /* A "\<x>" form occupies at least 4 characters, and produces up
5589              * to 6 characters: reserve space for 2 extra */
5590             if (*p == '<')
5591                 extra += 2;
5592         }
5593     }
5594
5595     if (*p != '"')
5596     {
5597         EMSG2(_("E114: Missing quote: %s"), *arg);
5598         return FAIL;
5599     }
5600
5601     /* If only parsing, set *arg and return here */
5602     if (!evaluate)
5603     {
5604         *arg = p + 1;
5605         return OK;
5606     }
5607
5608     /*
5609      * Copy the string into allocated memory, handling backslashed
5610      * characters.
5611      */
5612     name = alloc((unsigned)(p - *arg + extra));
5613     if (name == NULL)
5614         return FAIL;
5615     rettv->v_type = VAR_STRING;
5616     rettv->vval.v_string = name;
5617
5618     for (p = *arg + 1; *p != NUL && *p != '"'; )
5619     {
5620         if (*p == '\\')
5621         {
5622             switch (*++p)
5623             {
5624                 case 'b': *name++ = BS; ++p; break;
5625                 case 'e': *name++ = ESC; ++p; break;
5626                 case 'f': *name++ = FF; ++p; break;
5627                 case 'n': *name++ = NL; ++p; break;
5628                 case 'r': *name++ = CAR; ++p; break;
5629                 case 't': *name++ = TAB; ++p; break;
5630
5631                 case 'X': /* hex: "\x1", "\x12" */
5632                 case 'x':
5633                 case 'u': /* Unicode: "\u0023" */
5634                 case 'U':
5635                           if (vim_isxdigit(p[1]))
5636                           {
5637                               int       n, nr;
5638                               int       c = toupper(*p);
5639
5640                               if (c == 'X')
5641                                   n = 2;
5642                               else
5643                                   n = 4;
5644                               nr = 0;
5645                               while (--n >= 0 && vim_isxdigit(p[1]))
5646                               {
5647                                   ++p;
5648                                   nr = (nr << 4) + hex2nr(*p);
5649                               }
5650                               ++p;
5651 #ifdef FEAT_MBYTE
5652                               /* For "\u" store the number according to
5653                                * 'encoding'. */
5654                               if (c != 'X')
5655                                   name += (*mb_char2bytes)(nr, name);
5656                               else
5657 #endif
5658                                   *name++ = nr;
5659                           }
5660                           break;
5661
5662                           /* octal: "\1", "\12", "\123" */
5663                 case '0':
5664                 case '1':
5665                 case '2':
5666                 case '3':
5667                 case '4':
5668                 case '5':
5669                 case '6':
5670                 case '7': *name = *p++ - '0';
5671                           if (*p >= '0' && *p <= '7')
5672                           {
5673                               *name = (*name << 3) + *p++ - '0';
5674                               if (*p >= '0' && *p <= '7')
5675                                   *name = (*name << 3) + *p++ - '0';
5676                           }
5677                           ++name;
5678                           break;
5679
5680                             /* Special key, e.g.: "\<C-W>" */
5681                 case '<': extra = trans_special(&p, name, TRUE);
5682                           if (extra != 0)
5683                           {
5684                               name += extra;
5685                               break;
5686                           }
5687                           /* FALLTHROUGH */
5688
5689                 default:  MB_COPY_CHAR(p, name);
5690                           break;
5691             }
5692         }
5693         else
5694             MB_COPY_CHAR(p, name);
5695
5696     }
5697     *name = NUL;
5698     *arg = p + 1;
5699
5700     return OK;
5701 }
5702
5703 /*
5704  * Allocate a variable for a 'str''ing' constant.
5705  * Return OK or FAIL.
5706  */
5707     static int
5708 get_lit_string_tv(arg, rettv, evaluate)
5709     char_u      **arg;
5710     typval_T    *rettv;
5711     int         evaluate;
5712 {
5713     char_u      *p;
5714     char_u      *str;
5715     int         reduce = 0;
5716
5717     /*
5718      * Find the end of the string, skipping ''.
5719      */
5720     for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5721     {
5722         if (*p == '\'')
5723         {
5724             if (p[1] != '\'')
5725                 break;
5726             ++reduce;
5727             ++p;
5728         }
5729     }
5730
5731     if (*p != '\'')
5732     {
5733         EMSG2(_("E115: Missing quote: %s"), *arg);
5734         return FAIL;
5735     }
5736
5737     /* If only parsing return after setting "*arg" */
5738     if (!evaluate)
5739     {
5740         *arg = p + 1;
5741         return OK;
5742     }
5743
5744     /*
5745      * Copy the string into allocated memory, handling '' to ' reduction.
5746      */
5747     str = alloc((unsigned)((p - *arg) - reduce));
5748     if (str == NULL)
5749         return FAIL;
5750     rettv->v_type = VAR_STRING;
5751     rettv->vval.v_string = str;
5752
5753     for (p = *arg + 1; *p != NUL; )
5754     {
5755         if (*p == '\'')
5756         {
5757             if (p[1] != '\'')
5758                 break;
5759             ++p;
5760         }
5761         MB_COPY_CHAR(p, str);
5762     }
5763     *str = NUL;
5764     *arg = p + 1;
5765
5766     return OK;
5767 }
5768
5769 /*
5770  * Allocate a variable for a List and fill it from "*arg".
5771  * Return OK or FAIL.
5772  */
5773     static int
5774 get_list_tv(arg, rettv, evaluate)
5775     char_u      **arg;
5776     typval_T    *rettv;
5777     int         evaluate;
5778 {
5779     list_T      *l = NULL;
5780     typval_T    tv;
5781     listitem_T  *item;
5782
5783     if (evaluate)
5784     {
5785         l = list_alloc();
5786         if (l == NULL)
5787             return FAIL;
5788     }
5789
5790     *arg = skipwhite(*arg + 1);
5791     while (**arg != ']' && **arg != NUL)
5792     {
5793         if (eval1(arg, &tv, evaluate) == FAIL)  /* recursive! */
5794             goto failret;
5795         if (evaluate)
5796         {
5797             item = listitem_alloc();
5798             if (item != NULL)
5799             {
5800                 item->li_tv = tv;
5801                 item->li_tv.v_lock = 0;
5802                 list_append(l, item);
5803             }
5804             else
5805                 clear_tv(&tv);
5806         }
5807
5808         if (**arg == ']')
5809             break;
5810         if (**arg != ',')
5811         {
5812             EMSG2(_("E696: Missing comma in List: %s"), *arg);
5813             goto failret;
5814         }
5815         *arg = skipwhite(*arg + 1);
5816     }
5817
5818     if (**arg != ']')
5819     {
5820         EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5821 failret:
5822         if (evaluate)
5823             list_free(l, TRUE);
5824         return FAIL;
5825     }
5826
5827     *arg = skipwhite(*arg + 1);
5828     if (evaluate)
5829     {
5830         rettv->v_type = VAR_LIST;
5831         rettv->vval.v_list = l;
5832         ++l->lv_refcount;
5833     }
5834
5835     return OK;
5836 }
5837
5838 /*
5839  * Allocate an empty header for a list.
5840  * Caller should take care of the reference count.
5841  */
5842     list_T *
5843 list_alloc()
5844 {
5845     list_T  *l;
5846
5847     l = (list_T *)alloc_clear(sizeof(list_T));
5848     if (l != NULL)
5849     {
5850         /* Prepend the list to the list of lists for garbage collection. */
5851         if (first_list != NULL)
5852             first_list->lv_used_prev = l;
5853         l->lv_used_prev = NULL;
5854         l->lv_used_next = first_list;
5855         first_list = l;
5856     }
5857     return l;
5858 }
5859
5860 /*
5861  * Allocate an empty list for a return value.
5862  * Returns OK or FAIL.
5863  */
5864     static int
5865 rettv_list_alloc(rettv)
5866     typval_T    *rettv;
5867 {
5868     list_T      *l = list_alloc();
5869
5870     if (l == NULL)
5871         return FAIL;
5872
5873     rettv->vval.v_list = l;
5874     rettv->v_type = VAR_LIST;
5875     ++l->lv_refcount;
5876     return OK;
5877 }
5878
5879 /*
5880  * Unreference a list: decrement the reference count and free it when it
5881  * becomes zero.
5882  */
5883     void
5884 list_unref(l)
5885     list_T *l;
5886 {
5887     if (l != NULL && --l->lv_refcount <= 0)
5888         list_free(l, TRUE);
5889 }
5890
5891 /*
5892  * Free a list, including all items it points to.
5893  * Ignores the reference count.
5894  */
5895     void
5896 list_free(l, recurse)
5897     list_T  *l;
5898     int     recurse;    /* Free Lists and Dictionaries recursively. */
5899 {
5900     listitem_T *item;
5901
5902     /* Remove the list from the list of lists for garbage collection. */
5903     if (l->lv_used_prev == NULL)
5904         first_list = l->lv_used_next;
5905     else
5906         l->lv_used_prev->lv_used_next = l->lv_used_next;
5907     if (l->lv_used_next != NULL)
5908         l->lv_used_next->lv_used_prev = l->lv_used_prev;
5909
5910     for (item = l->lv_first; item != NULL; item = l->lv_first)
5911     {
5912         /* Remove the item before deleting it. */
5913         l->lv_first = item->li_next;
5914         if (recurse || (item->li_tv.v_type != VAR_LIST
5915                                            && item->li_tv.v_type != VAR_DICT))
5916             clear_tv(&item->li_tv);
5917         vim_free(item);
5918     }
5919     vim_free(l);
5920 }
5921
5922 /*
5923  * Allocate a list item.
5924  */
5925     static listitem_T *
5926 listitem_alloc()
5927 {
5928     return (listitem_T *)alloc(sizeof(listitem_T));
5929 }
5930
5931 /*
5932  * Free a list item.  Also clears the value.  Does not notify watchers.
5933  */
5934     static void
5935 listitem_free(item)
5936     listitem_T *item;
5937 {
5938     clear_tv(&item->li_tv);
5939     vim_free(item);
5940 }
5941
5942 /*
5943  * Remove a list item from a List and free it.  Also clears the value.
5944  */
5945     static void
5946 listitem_remove(l, item)
5947     list_T  *l;
5948     listitem_T *item;
5949 {
5950     list_remove(l, item, item);
5951     listitem_free(item);
5952 }
5953
5954 /*
5955  * Get the number of items in a list.
5956  */
5957     static long
5958 list_len(l)
5959     list_T      *l;
5960 {
5961     if (l == NULL)
5962         return 0L;
5963     return l->lv_len;
5964 }
5965
5966 /*
5967  * Return TRUE when two lists have exactly the same values.
5968  */
5969     static int
5970 list_equal(l1, l2, ic, recursive)
5971     list_T      *l1;
5972     list_T      *l2;
5973     int         ic;     /* ignore case for strings */
5974     int         recursive;  /* TRUE when used recursively */
5975 {
5976     listitem_T  *item1, *item2;
5977
5978     if (l1 == NULL || l2 == NULL)
5979         return FALSE;
5980     if (l1 == l2)
5981         return TRUE;
5982     if (list_len(l1) != list_len(l2))
5983         return FALSE;
5984
5985     for (item1 = l1->lv_first, item2 = l2->lv_first;
5986             item1 != NULL && item2 != NULL;
5987                                item1 = item1->li_next, item2 = item2->li_next)
5988         if (!tv_equal(&item1->li_tv, &item2->li_tv, ic, recursive))
5989             return FALSE;
5990     return item1 == NULL && item2 == NULL;
5991 }
5992
5993 #if defined(FEAT_RUBY) || defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) \
5994         || defined(FEAT_MZSCHEME) || defined(FEAT_LUA) || defined(PROTO)
5995 /*
5996  * Return the dictitem that an entry in a hashtable points to.
5997  */
5998     dictitem_T *
5999 dict_lookup(hi)
6000     hashitem_T *hi;
6001 {
6002     return HI2DI(hi);
6003 }
6004 #endif
6005
6006 /*
6007  * Return TRUE when two dictionaries have exactly the same key/values.
6008  */
6009     static int
6010 dict_equal(d1, d2, ic, recursive)
6011     dict_T      *d1;
6012     dict_T      *d2;
6013     int         ic;     /* ignore case for strings */
6014     int         recursive; /* TRUE when used recursively */
6015 {
6016     hashitem_T  *hi;
6017     dictitem_T  *item2;
6018     int         todo;
6019
6020     if (d1 == NULL || d2 == NULL)
6021         return FALSE;
6022     if (d1 == d2)
6023         return TRUE;
6024     if (dict_len(d1) != dict_len(d2))
6025         return FALSE;
6026
6027     todo = (int)d1->dv_hashtab.ht_used;
6028     for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
6029     {
6030         if (!HASHITEM_EMPTY(hi))
6031         {
6032             item2 = dict_find(d2, hi->hi_key, -1);
6033             if (item2 == NULL)
6034                 return FALSE;
6035             if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic, recursive))
6036                 return FALSE;
6037             --todo;
6038         }
6039     }
6040     return TRUE;
6041 }
6042
6043 static int tv_equal_recurse_limit;
6044
6045 /*
6046  * Return TRUE if "tv1" and "tv2" have the same value.
6047  * Compares the items just like "==" would compare them, but strings and
6048  * numbers are different.  Floats and numbers are also different.
6049  */
6050     static int
6051 tv_equal(tv1, tv2, ic, recursive)
6052     typval_T *tv1;
6053     typval_T *tv2;
6054     int      ic;            /* ignore case */
6055     int      recursive;     /* TRUE when used recursively */
6056 {
6057     char_u      buf1[NUMBUFLEN], buf2[NUMBUFLEN];
6058     char_u      *s1, *s2;
6059     static int  recursive_cnt = 0;          /* catch recursive loops */
6060     int         r;
6061
6062     if (tv1->v_type != tv2->v_type)
6063         return FALSE;
6064
6065     /* Catch lists and dicts that have an endless loop by limiting
6066      * recursiveness to a limit.  We guess they are equal then.
6067      * A fixed limit has the problem of still taking an awful long time.
6068      * Reduce the limit every time running into it. That should work fine for
6069      * deeply linked structures that are not recursively linked and catch
6070      * recursiveness quickly. */
6071     if (!recursive)
6072         tv_equal_recurse_limit = 1000;
6073     if (recursive_cnt >= tv_equal_recurse_limit)
6074     {
6075         --tv_equal_recurse_limit;
6076         return TRUE;
6077     }
6078
6079     switch (tv1->v_type)
6080     {
6081         case VAR_LIST:
6082             ++recursive_cnt;
6083             r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic, TRUE);
6084             --recursive_cnt;
6085             return r;
6086
6087         case VAR_DICT:
6088             ++recursive_cnt;
6089             r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic, TRUE);
6090             --recursive_cnt;
6091             return r;
6092
6093         case VAR_FUNC:
6094             return (tv1->vval.v_string != NULL
6095                     && tv2->vval.v_string != NULL
6096                     && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
6097
6098         case VAR_NUMBER:
6099             return tv1->vval.v_number == tv2->vval.v_number;
6100
6101 #ifdef FEAT_FLOAT
6102         case VAR_FLOAT:
6103             return tv1->vval.v_float == tv2->vval.v_float;
6104 #endif
6105
6106         case VAR_STRING:
6107             s1 = get_tv_string_buf(tv1, buf1);
6108             s2 = get_tv_string_buf(tv2, buf2);
6109             return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
6110     }
6111
6112     EMSG2(_(e_intern2), "tv_equal()");
6113     return TRUE;
6114 }
6115
6116 /*
6117  * Locate item with index "n" in list "l" and return it.
6118  * A negative index is counted from the end; -1 is the last item.
6119  * Returns NULL when "n" is out of range.
6120  */
6121     static listitem_T *
6122 list_find(l, n)
6123     list_T      *l;
6124     long        n;
6125 {
6126     listitem_T  *item;
6127     long        idx;
6128
6129     if (l == NULL)
6130         return NULL;
6131
6132     /* Negative index is relative to the end. */
6133     if (n < 0)
6134         n = l->lv_len + n;
6135
6136     /* Check for index out of range. */
6137     if (n < 0 || n >= l->lv_len)
6138         return NULL;
6139
6140     /* When there is a cached index may start search from there. */
6141     if (l->lv_idx_item != NULL)
6142     {
6143         if (n < l->lv_idx / 2)
6144         {
6145             /* closest to the start of the list */
6146             item = l->lv_first;
6147             idx = 0;
6148         }
6149         else if (n > (l->lv_idx + l->lv_len) / 2)
6150         {
6151             /* closest to the end of the list */
6152             item = l->lv_last;
6153             idx = l->lv_len - 1;
6154         }
6155         else
6156         {
6157             /* closest to the cached index */
6158             item = l->lv_idx_item;
6159             idx = l->lv_idx;
6160         }
6161     }
6162     else
6163     {
6164         if (n < l->lv_len / 2)
6165         {
6166             /* closest to the start of the list */
6167             item = l->lv_first;
6168             idx = 0;
6169         }
6170         else
6171         {
6172             /* closest to the end of the list */
6173             item = l->lv_last;
6174             idx = l->lv_len - 1;
6175         }
6176     }
6177
6178     while (n > idx)
6179     {
6180         /* search forward */
6181         item = item->li_next;
6182         ++idx;
6183     }
6184     while (n < idx)
6185     {
6186         /* search backward */
6187         item = item->li_prev;
6188         --idx;
6189     }
6190
6191     /* cache the used index */
6192     l->lv_idx = idx;
6193     l->lv_idx_item = item;
6194
6195     return item;
6196 }
6197
6198 /*
6199  * Get list item "l[idx]" as a number.
6200  */
6201     static long
6202 list_find_nr(l, idx, errorp)
6203     list_T      *l;
6204     long        idx;
6205     int         *errorp;        /* set to TRUE when something wrong */
6206 {
6207     listitem_T  *li;
6208
6209     li = list_find(l, idx);
6210     if (li == NULL)
6211     {
6212         if (errorp != NULL)
6213             *errorp = TRUE;
6214         return -1L;
6215     }
6216     return get_tv_number_chk(&li->li_tv, errorp);
6217 }
6218
6219 /*
6220  * Get list item "l[idx - 1]" as a string.  Returns NULL for failure.
6221  */
6222     char_u *
6223 list_find_str(l, idx)
6224     list_T      *l;
6225     long        idx;
6226 {
6227     listitem_T  *li;
6228
6229     li = list_find(l, idx - 1);
6230     if (li == NULL)
6231     {
6232         EMSGN(_(e_listidx), idx);
6233         return NULL;
6234     }
6235     return get_tv_string(&li->li_tv);
6236 }
6237
6238 /*
6239  * Locate "item" list "l" and return its index.
6240  * Returns -1 when "item" is not in the list.
6241  */
6242     static long
6243 list_idx_of_item(l, item)
6244     list_T      *l;
6245     listitem_T  *item;
6246 {
6247     long        idx = 0;
6248     listitem_T  *li;
6249
6250     if (l == NULL)
6251         return -1;
6252     idx = 0;
6253     for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
6254         ++idx;
6255     if (li == NULL)
6256         return -1;
6257     return idx;
6258 }
6259
6260 /*
6261  * Append item "item" to the end of list "l".
6262  */
6263     static void
6264 list_append(l, item)
6265     list_T      *l;
6266     listitem_T  *item;
6267 {
6268     if (l->lv_last == NULL)
6269     {
6270         /* empty list */
6271         l->lv_first = item;
6272         l->lv_last = item;
6273         item->li_prev = NULL;
6274     }
6275     else
6276     {
6277         l->lv_last->li_next = item;
6278         item->li_prev = l->lv_last;
6279         l->lv_last = item;
6280     }
6281     ++l->lv_len;
6282     item->li_next = NULL;
6283 }
6284
6285 /*
6286  * Append typval_T "tv" to the end of list "l".
6287  * Return FAIL when out of memory.
6288  */
6289     int
6290 list_append_tv(l, tv)
6291     list_T      *l;
6292     typval_T    *tv;
6293 {
6294     listitem_T  *li = listitem_alloc();
6295
6296     if (li == NULL)
6297         return FAIL;
6298     copy_tv(tv, &li->li_tv);
6299     list_append(l, li);
6300     return OK;
6301 }
6302
6303 /*
6304  * Add a dictionary to a list.  Used by getqflist().
6305  * Return FAIL when out of memory.
6306  */
6307     int
6308 list_append_dict(list, dict)
6309     list_T      *list;
6310     dict_T      *dict;
6311 {
6312     listitem_T  *li = listitem_alloc();
6313
6314     if (li == NULL)
6315         return FAIL;
6316     li->li_tv.v_type = VAR_DICT;
6317     li->li_tv.v_lock = 0;
6318     li->li_tv.vval.v_dict = dict;
6319     list_append(list, li);
6320     ++dict->dv_refcount;
6321     return OK;
6322 }
6323
6324 /*
6325  * Make a copy of "str" and append it as an item to list "l".
6326  * When "len" >= 0 use "str[len]".
6327  * Returns FAIL when out of memory.
6328  */
6329     int
6330 list_append_string(l, str, len)
6331     list_T      *l;
6332     char_u      *str;
6333     int         len;
6334 {
6335     listitem_T *li = listitem_alloc();
6336
6337     if (li == NULL)
6338         return FAIL;
6339     list_append(l, li);
6340     li->li_tv.v_type = VAR_STRING;
6341     li->li_tv.v_lock = 0;
6342     if (str == NULL)
6343         li->li_tv.vval.v_string = NULL;
6344     else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
6345                                                  : vim_strsave(str))) == NULL)
6346         return FAIL;
6347     return OK;
6348 }
6349
6350 /*
6351  * Append "n" to list "l".
6352  * Returns FAIL when out of memory.
6353  */
6354     static int
6355 list_append_number(l, n)
6356     list_T      *l;
6357     varnumber_T n;
6358 {
6359     listitem_T  *li;
6360
6361     li = listitem_alloc();
6362     if (li == NULL)
6363         return FAIL;
6364     li->li_tv.v_type = VAR_NUMBER;
6365     li->li_tv.v_lock = 0;
6366     li->li_tv.vval.v_number = n;
6367     list_append(l, li);
6368     return OK;
6369 }
6370
6371 /*
6372  * Insert typval_T "tv" in list "l" before "item".
6373  * If "item" is NULL append at the end.
6374  * Return FAIL when out of memory.
6375  */
6376     static int
6377 list_insert_tv(l, tv, item)
6378     list_T      *l;
6379     typval_T    *tv;
6380     listitem_T  *item;
6381 {
6382     listitem_T  *ni = listitem_alloc();
6383
6384     if (ni == NULL)
6385         return FAIL;
6386     copy_tv(tv, &ni->li_tv);
6387     if (item == NULL)
6388         /* Append new item at end of list. */
6389         list_append(l, ni);
6390     else
6391     {
6392         /* Insert new item before existing item. */
6393         ni->li_prev = item->li_prev;
6394         ni->li_next = item;
6395         if (item->li_prev == NULL)
6396         {
6397             l->lv_first = ni;
6398             ++l->lv_idx;
6399         }
6400         else
6401         {
6402             item->li_prev->li_next = ni;
6403             l->lv_idx_item = NULL;
6404         }
6405         item->li_prev = ni;
6406         ++l->lv_len;
6407     }
6408     return OK;
6409 }
6410
6411 /*
6412  * Extend "l1" with "l2".
6413  * If "bef" is NULL append at the end, otherwise insert before this item.
6414  * Returns FAIL when out of memory.
6415  */
6416     static int
6417 list_extend(l1, l2, bef)
6418     list_T      *l1;
6419     list_T      *l2;
6420     listitem_T  *bef;
6421 {
6422     listitem_T  *item;
6423     int         todo = l2->lv_len;
6424
6425     /* We also quit the loop when we have inserted the original item count of
6426      * the list, avoid a hang when we extend a list with itself. */
6427     for (item = l2->lv_first; item != NULL && --todo >= 0; item = item->li_next)
6428         if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
6429             return FAIL;
6430     return OK;
6431 }
6432
6433 /*
6434  * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
6435  * Return FAIL when out of memory.
6436  */
6437     static int
6438 list_concat(l1, l2, tv)
6439     list_T      *l1;
6440     list_T      *l2;
6441     typval_T    *tv;
6442 {
6443     list_T      *l;
6444
6445     if (l1 == NULL || l2 == NULL)
6446         return FAIL;
6447
6448     /* make a copy of the first list. */
6449     l = list_copy(l1, FALSE, 0);
6450     if (l == NULL)
6451         return FAIL;
6452     tv->v_type = VAR_LIST;
6453     tv->vval.v_list = l;
6454
6455     /* append all items from the second list */
6456     return list_extend(l, l2, NULL);
6457 }
6458
6459 /*
6460  * Make a copy of list "orig".  Shallow if "deep" is FALSE.
6461  * The refcount of the new list is set to 1.
6462  * See item_copy() for "copyID".
6463  * Returns NULL when out of memory.
6464  */
6465     static list_T *
6466 list_copy(orig, deep, copyID)
6467     list_T      *orig;
6468     int         deep;
6469     int         copyID;
6470 {
6471     list_T      *copy;
6472     listitem_T  *item;
6473     listitem_T  *ni;
6474
6475     if (orig == NULL)
6476         return NULL;
6477
6478     copy = list_alloc();
6479     if (copy != NULL)
6480     {
6481         if (copyID != 0)
6482         {
6483             /* Do this before adding the items, because one of the items may
6484              * refer back to this list. */
6485             orig->lv_copyID = copyID;
6486             orig->lv_copylist = copy;
6487         }
6488         for (item = orig->lv_first; item != NULL && !got_int;
6489                                                          item = item->li_next)
6490         {
6491             ni = listitem_alloc();
6492             if (ni == NULL)
6493                 break;
6494             if (deep)
6495             {
6496                 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
6497                 {
6498                     vim_free(ni);
6499                     break;
6500                 }
6501             }
6502             else
6503                 copy_tv(&item->li_tv, &ni->li_tv);
6504             list_append(copy, ni);
6505         }
6506         ++copy->lv_refcount;
6507         if (item != NULL)
6508         {
6509             list_unref(copy);
6510             copy = NULL;
6511         }
6512     }
6513
6514     return copy;
6515 }
6516
6517 /*
6518  * Remove items "item" to "item2" from list "l".
6519  * Does not free the listitem or the value!
6520  */
6521     static void
6522 list_remove(l, item, item2)
6523     list_T      *l;
6524     listitem_T  *item;
6525     listitem_T  *item2;
6526 {
6527     listitem_T  *ip;
6528
6529     /* notify watchers */
6530     for (ip = item; ip != NULL; ip = ip->li_next)
6531     {
6532         --l->lv_len;
6533         list_fix_watch(l, ip);
6534         if (ip == item2)
6535             break;
6536     }
6537
6538     if (item2->li_next == NULL)
6539         l->lv_last = item->li_prev;
6540     else
6541         item2->li_next->li_prev = item->li_prev;
6542     if (item->li_prev == NULL)
6543         l->lv_first = item2->li_next;
6544     else
6545         item->li_prev->li_next = item2->li_next;
6546     l->lv_idx_item = NULL;
6547 }
6548
6549 /*
6550  * Return an allocated string with the string representation of a list.
6551  * May return NULL.
6552  */
6553     static char_u *
6554 list2string(tv, copyID)
6555     typval_T    *tv;
6556     int         copyID;
6557 {
6558     garray_T    ga;
6559
6560     if (tv->vval.v_list == NULL)
6561         return NULL;
6562     ga_init2(&ga, (int)sizeof(char), 80);
6563     ga_append(&ga, '[');
6564     if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6565     {
6566         vim_free(ga.ga_data);
6567         return NULL;
6568     }
6569     ga_append(&ga, ']');
6570     ga_append(&ga, NUL);
6571     return (char_u *)ga.ga_data;
6572 }
6573
6574 /*
6575  * Join list "l" into a string in "*gap", using separator "sep".
6576  * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6577  * Return FAIL or OK.
6578  */
6579     static int
6580 list_join(gap, l, sep, echo, copyID)
6581     garray_T    *gap;
6582     list_T      *l;
6583     char_u      *sep;
6584     int         echo;
6585     int         copyID;
6586 {
6587     int         first = TRUE;
6588     char_u      *tofree;
6589     char_u      numbuf[NUMBUFLEN];
6590     listitem_T  *item;
6591     char_u      *s;
6592
6593     for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6594     {
6595         if (first)
6596             first = FALSE;
6597         else
6598             ga_concat(gap, sep);
6599
6600         if (echo)
6601             s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6602         else
6603             s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6604         if (s != NULL)
6605             ga_concat(gap, s);
6606         vim_free(tofree);
6607         if (s == NULL)
6608             return FAIL;
6609         line_breakcheck();
6610     }
6611     return OK;
6612 }
6613
6614 /*
6615  * Garbage collection for lists and dictionaries.
6616  *
6617  * We use reference counts to be able to free most items right away when they
6618  * are no longer used.  But for composite items it's possible that it becomes
6619  * unused while the reference count is > 0: When there is a recursive
6620  * reference.  Example:
6621  *      :let l = [1, 2, 3]
6622  *      :let d = {9: l}
6623  *      :let l[1] = d
6624  *
6625  * Since this is quite unusual we handle this with garbage collection: every
6626  * once in a while find out which lists and dicts are not referenced from any
6627  * variable.
6628  *
6629  * Here is a good reference text about garbage collection (refers to Python
6630  * but it applies to all reference-counting mechanisms):
6631  *      http://python.ca/nas/python/gc/
6632  */
6633
6634 /*
6635  * Do garbage collection for lists and dicts.
6636  * Return TRUE if some memory was freed.
6637  */
6638     int
6639 garbage_collect()
6640 {
6641     int         copyID;
6642     buf_T       *buf;
6643     win_T       *wp;
6644     int         i;
6645     funccall_T  *fc, **pfc;
6646     int         did_free;
6647     int         did_free_funccal = FALSE;
6648 #ifdef FEAT_WINDOWS
6649     tabpage_T   *tp;
6650 #endif
6651
6652     /* Only do this once. */
6653     want_garbage_collect = FALSE;
6654     may_garbage_collect = FALSE;
6655     garbage_collect_at_exit = FALSE;
6656
6657     /* We advance by two because we add one for items referenced through
6658      * previous_funccal. */
6659     current_copyID += COPYID_INC;
6660     copyID = current_copyID;
6661
6662     /*
6663      * 1. Go through all accessible variables and mark all lists and dicts
6664      *    with copyID.
6665      */
6666
6667     /* Don't free variables in the previous_funccal list unless they are only
6668      * referenced through previous_funccal.  This must be first, because if
6669      * the item is referenced elsewhere the funccal must not be freed. */
6670     for (fc = previous_funccal; fc != NULL; fc = fc->caller)
6671     {
6672         set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1);
6673         set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1);
6674     }
6675
6676     /* script-local variables */
6677     for (i = 1; i <= ga_scripts.ga_len; ++i)
6678         set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6679
6680     /* buffer-local variables */
6681     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6682         set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6683
6684     /* window-local variables */
6685     FOR_ALL_TAB_WINDOWS(tp, wp)
6686         set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6687
6688 #ifdef FEAT_WINDOWS
6689     /* tabpage-local variables */
6690     for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6691         set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6692 #endif
6693
6694     /* global variables */
6695     set_ref_in_ht(&globvarht, copyID);
6696
6697     /* function-local variables */
6698     for (fc = current_funccal; fc != NULL; fc = fc->caller)
6699     {
6700         set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6701         set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6702     }
6703
6704     /* v: vars */
6705     set_ref_in_ht(&vimvarht, copyID);
6706
6707     /*
6708      * 2. Free lists and dictionaries that are not referenced.
6709      */
6710     did_free = free_unref_items(copyID);
6711
6712     /*
6713      * 3. Check if any funccal can be freed now.
6714      */
6715     for (pfc = &previous_funccal; *pfc != NULL; )
6716     {
6717         if (can_free_funccal(*pfc, copyID))
6718         {
6719             fc = *pfc;
6720             *pfc = fc->caller;
6721             free_funccal(fc, TRUE);
6722             did_free = TRUE;
6723             did_free_funccal = TRUE;
6724         }
6725         else
6726             pfc = &(*pfc)->caller;
6727     }
6728     if (did_free_funccal)
6729         /* When a funccal was freed some more items might be garbage
6730          * collected, so run again. */
6731         (void)garbage_collect();
6732
6733     return did_free;
6734 }
6735
6736 /*
6737  * Free lists and dictionaries that are no longer referenced.
6738  */
6739     static int
6740 free_unref_items(copyID)
6741     int copyID;
6742 {
6743     dict_T      *dd;
6744     list_T      *ll;
6745     int         did_free = FALSE;
6746
6747     /*
6748      * Go through the list of dicts and free items without the copyID.
6749      */
6750     for (dd = first_dict; dd != NULL; )
6751         if ((dd->dv_copyID & COPYID_MASK) != (copyID & COPYID_MASK))
6752         {
6753             /* Free the Dictionary and ordinary items it contains, but don't
6754              * recurse into Lists and Dictionaries, they will be in the list
6755              * of dicts or list of lists. */
6756             dict_free(dd, FALSE);
6757             did_free = TRUE;
6758
6759             /* restart, next dict may also have been freed */
6760             dd = first_dict;
6761         }
6762         else
6763             dd = dd->dv_used_next;
6764
6765     /*
6766      * Go through the list of lists and free items without the copyID.
6767      * But don't free a list that has a watcher (used in a for loop), these
6768      * are not referenced anywhere.
6769      */
6770     for (ll = first_list; ll != NULL; )
6771         if ((ll->lv_copyID & COPYID_MASK) != (copyID & COPYID_MASK)
6772                                                       && ll->lv_watch == NULL)
6773         {
6774             /* Free the List and ordinary items it contains, but don't recurse
6775              * into Lists and Dictionaries, they will be in the list of dicts
6776              * or list of lists. */
6777             list_free(ll, FALSE);
6778             did_free = TRUE;
6779
6780             /* restart, next list may also have been freed */
6781             ll = first_list;
6782         }
6783         else
6784             ll = ll->lv_used_next;
6785
6786     return did_free;
6787 }
6788
6789 /*
6790  * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6791  */
6792     static void
6793 set_ref_in_ht(ht, copyID)
6794     hashtab_T   *ht;
6795     int         copyID;
6796 {
6797     int         todo;
6798     hashitem_T  *hi;
6799
6800     todo = (int)ht->ht_used;
6801     for (hi = ht->ht_array; todo > 0; ++hi)
6802         if (!HASHITEM_EMPTY(hi))
6803         {
6804             --todo;
6805             set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6806         }
6807 }
6808
6809 /*
6810  * Mark all lists and dicts referenced through list "l" with "copyID".
6811  */
6812     static void
6813 set_ref_in_list(l, copyID)
6814     list_T      *l;
6815     int         copyID;
6816 {
6817     listitem_T *li;
6818
6819     for (li = l->lv_first; li != NULL; li = li->li_next)
6820         set_ref_in_item(&li->li_tv, copyID);
6821 }
6822
6823 /*
6824  * Mark all lists and dicts referenced through typval "tv" with "copyID".
6825  */
6826     static void
6827 set_ref_in_item(tv, copyID)
6828     typval_T    *tv;
6829     int         copyID;
6830 {
6831     dict_T      *dd;
6832     list_T      *ll;
6833
6834     switch (tv->v_type)
6835     {
6836         case VAR_DICT:
6837             dd = tv->vval.v_dict;
6838             if (dd != NULL && dd->dv_copyID != copyID)
6839             {
6840                 /* Didn't see this dict yet. */
6841                 dd->dv_copyID = copyID;
6842                 set_ref_in_ht(&dd->dv_hashtab, copyID);
6843             }
6844             break;
6845
6846         case VAR_LIST:
6847             ll = tv->vval.v_list;
6848             if (ll != NULL && ll->lv_copyID != copyID)
6849             {
6850                 /* Didn't see this list yet. */
6851                 ll->lv_copyID = copyID;
6852                 set_ref_in_list(ll, copyID);
6853             }
6854             break;
6855     }
6856     return;
6857 }
6858
6859 /*
6860  * Allocate an empty header for a dictionary.
6861  */
6862     dict_T *
6863 dict_alloc()
6864 {
6865     dict_T *d;
6866
6867     d = (dict_T *)alloc(sizeof(dict_T));
6868     if (d != NULL)
6869     {
6870         /* Add the list to the list of dicts for garbage collection. */
6871         if (first_dict != NULL)
6872             first_dict->dv_used_prev = d;
6873         d->dv_used_next = first_dict;
6874         d->dv_used_prev = NULL;
6875         first_dict = d;
6876
6877         hash_init(&d->dv_hashtab);
6878         d->dv_lock = 0;
6879         d->dv_refcount = 0;
6880         d->dv_copyID = 0;
6881     }
6882     return d;
6883 }
6884
6885 /*
6886  * Allocate an empty dict for a return value.
6887  * Returns OK or FAIL.
6888  */
6889     static int
6890 rettv_dict_alloc(rettv)
6891     typval_T    *rettv;
6892 {
6893     dict_T      *d = dict_alloc();
6894
6895     if (d == NULL)
6896         return FAIL;
6897
6898     rettv->vval.v_dict = d;
6899     rettv->v_type = VAR_DICT;
6900     ++d->dv_refcount;
6901     return OK;
6902 }
6903
6904
6905 /*
6906  * Unreference a Dictionary: decrement the reference count and free it when it
6907  * becomes zero.
6908  */
6909     void
6910 dict_unref(d)
6911     dict_T *d;
6912 {
6913     if (d != NULL && --d->dv_refcount <= 0)
6914         dict_free(d, TRUE);
6915 }
6916
6917 /*
6918  * Free a Dictionary, including all items it contains.
6919  * Ignores the reference count.
6920  */
6921     static void
6922 dict_free(d, recurse)
6923     dict_T  *d;
6924     int     recurse;    /* Free Lists and Dictionaries recursively. */
6925 {
6926     int         todo;
6927     hashitem_T  *hi;
6928     dictitem_T  *di;
6929
6930     /* Remove the dict from the list of dicts for garbage collection. */
6931     if (d->dv_used_prev == NULL)
6932         first_dict = d->dv_used_next;
6933     else
6934         d->dv_used_prev->dv_used_next = d->dv_used_next;
6935     if (d->dv_used_next != NULL)
6936         d->dv_used_next->dv_used_prev = d->dv_used_prev;
6937
6938     /* Lock the hashtab, we don't want it to resize while freeing items. */
6939     hash_lock(&d->dv_hashtab);
6940     todo = (int)d->dv_hashtab.ht_used;
6941     for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6942     {
6943         if (!HASHITEM_EMPTY(hi))
6944         {
6945             /* Remove the item before deleting it, just in case there is
6946              * something recursive causing trouble. */
6947             di = HI2DI(hi);
6948             hash_remove(&d->dv_hashtab, hi);
6949             if (recurse || (di->di_tv.v_type != VAR_LIST
6950                                              && di->di_tv.v_type != VAR_DICT))
6951                 clear_tv(&di->di_tv);
6952             vim_free(di);
6953             --todo;
6954         }
6955     }
6956     hash_clear(&d->dv_hashtab);
6957     vim_free(d);
6958 }
6959
6960 /*
6961  * Allocate a Dictionary item.
6962  * The "key" is copied to the new item.
6963  * Note that the value of the item "di_tv" still needs to be initialized!
6964  * Returns NULL when out of memory.
6965  */
6966     dictitem_T *
6967 dictitem_alloc(key)
6968     char_u      *key;
6969 {
6970     dictitem_T *di;
6971
6972     di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6973     if (di != NULL)
6974     {
6975         STRCPY(di->di_key, key);
6976         di->di_flags = 0;
6977     }
6978     return di;
6979 }
6980
6981 /*
6982  * Make a copy of a Dictionary item.
6983  */
6984     static dictitem_T *
6985 dictitem_copy(org)
6986     dictitem_T *org;
6987 {
6988     dictitem_T *di;
6989
6990     di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6991                                                       + STRLEN(org->di_key)));
6992     if (di != NULL)
6993     {
6994         STRCPY(di->di_key, org->di_key);
6995         di->di_flags = 0;
6996         copy_tv(&org->di_tv, &di->di_tv);
6997     }
6998     return di;
6999 }
7000
7001 /*
7002  * Remove item "item" from Dictionary "dict" and free it.
7003  */
7004     static void
7005 dictitem_remove(dict, item)
7006     dict_T      *dict;
7007     dictitem_T  *item;
7008 {
7009     hashitem_T  *hi;
7010
7011     hi = hash_find(&dict->dv_hashtab, item->di_key);
7012     if (HASHITEM_EMPTY(hi))
7013         EMSG2(_(e_intern2), "dictitem_remove()");
7014     else
7015         hash_remove(&dict->dv_hashtab, hi);
7016     dictitem_free(item);
7017 }
7018
7019 /*
7020  * Free a dict item.  Also clears the value.
7021  */
7022     void
7023 dictitem_free(item)
7024     dictitem_T *item;
7025 {
7026     clear_tv(&item->di_tv);
7027     vim_free(item);
7028 }
7029
7030 /*
7031  * Make a copy of dict "d".  Shallow if "deep" is FALSE.
7032  * The refcount of the new dict is set to 1.
7033  * See item_copy() for "copyID".
7034  * Returns NULL when out of memory.
7035  */
7036     static dict_T *
7037 dict_copy(orig, deep, copyID)
7038     dict_T      *orig;
7039     int         deep;
7040     int         copyID;
7041 {
7042     dict_T      *copy;
7043     dictitem_T  *di;
7044     int         todo;
7045     hashitem_T  *hi;
7046
7047     if (orig == NULL)
7048         return NULL;
7049
7050     copy = dict_alloc();
7051     if (copy != NULL)
7052     {
7053         if (copyID != 0)
7054         {
7055             orig->dv_copyID = copyID;
7056             orig->dv_copydict = copy;
7057         }
7058         todo = (int)orig->dv_hashtab.ht_used;
7059         for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
7060         {
7061             if (!HASHITEM_EMPTY(hi))
7062             {
7063                 --todo;
7064
7065                 di = dictitem_alloc(hi->hi_key);
7066                 if (di == NULL)
7067                     break;
7068                 if (deep)
7069                 {
7070                     if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
7071                                                               copyID) == FAIL)
7072                     {
7073                         vim_free(di);
7074                         break;
7075                     }
7076                 }
7077                 else
7078                     copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
7079                 if (dict_add(copy, di) == FAIL)
7080                 {
7081                     dictitem_free(di);
7082                     break;
7083                 }
7084             }
7085         }
7086
7087         ++copy->dv_refcount;
7088         if (todo > 0)
7089         {
7090             dict_unref(copy);
7091             copy = NULL;
7092         }
7093     }
7094
7095     return copy;
7096 }
7097
7098 /*
7099  * Add item "item" to Dictionary "d".
7100  * Returns FAIL when out of memory and when key already exists.
7101  */
7102     int
7103 dict_add(d, item)
7104     dict_T      *d;
7105     dictitem_T  *item;
7106 {
7107     return hash_add(&d->dv_hashtab, item->di_key);
7108 }
7109
7110 /*
7111  * Add a number or string entry to dictionary "d".
7112  * When "str" is NULL use number "nr", otherwise use "str".
7113  * Returns FAIL when out of memory and when key already exists.
7114  */
7115     int
7116 dict_add_nr_str(d, key, nr, str)
7117     dict_T      *d;
7118     char        *key;
7119     long        nr;
7120     char_u      *str;
7121 {
7122     dictitem_T  *item;
7123
7124     item = dictitem_alloc((char_u *)key);
7125     if (item == NULL)
7126         return FAIL;
7127     item->di_tv.v_lock = 0;
7128     if (str == NULL)
7129     {
7130         item->di_tv.v_type = VAR_NUMBER;
7131         item->di_tv.vval.v_number = nr;
7132     }
7133     else
7134     {
7135         item->di_tv.v_type = VAR_STRING;
7136         item->di_tv.vval.v_string = vim_strsave(str);
7137     }
7138     if (dict_add(d, item) == FAIL)
7139     {
7140         dictitem_free(item);
7141         return FAIL;
7142     }
7143     return OK;
7144 }
7145
7146 /*
7147  * Add a list entry to dictionary "d".
7148  * Returns FAIL when out of memory and when key already exists.
7149  */
7150     int
7151 dict_add_list(d, key, list)
7152     dict_T      *d;
7153     char        *key;
7154     list_T      *list;
7155 {
7156     dictitem_T  *item;
7157
7158     item = dictitem_alloc((char_u *)key);
7159     if (item == NULL)
7160         return FAIL;
7161     item->di_tv.v_lock = 0;
7162     item->di_tv.v_type = VAR_LIST;
7163     item->di_tv.vval.v_list = list;
7164     if (dict_add(d, item) == FAIL)
7165     {
7166         dictitem_free(item);
7167         return FAIL;
7168     }
7169     ++list->lv_refcount;
7170     return OK;
7171 }
7172
7173 /*
7174  * Get the number of items in a Dictionary.
7175  */
7176     static long
7177 dict_len(d)
7178     dict_T      *d;
7179 {
7180     if (d == NULL)
7181         return 0L;
7182     return (long)d->dv_hashtab.ht_used;
7183 }
7184
7185 /*
7186  * Find item "key[len]" in Dictionary "d".
7187  * If "len" is negative use strlen(key).
7188  * Returns NULL when not found.
7189  */
7190     dictitem_T *
7191 dict_find(d, key, len)
7192     dict_T      *d;
7193     char_u      *key;
7194     int         len;
7195 {
7196 #define AKEYLEN 200
7197     char_u      buf[AKEYLEN];
7198     char_u      *akey;
7199     char_u      *tofree = NULL;
7200     hashitem_T  *hi;
7201
7202     if (len < 0)
7203         akey = key;
7204     else if (len >= AKEYLEN)
7205     {
7206         tofree = akey = vim_strnsave(key, len);
7207         if (akey == NULL)
7208             return NULL;
7209     }
7210     else
7211     {
7212         /* Avoid a malloc/free by using buf[]. */
7213         vim_strncpy(buf, key, len);
7214         akey = buf;
7215     }
7216
7217     hi = hash_find(&d->dv_hashtab, akey);
7218     vim_free(tofree);
7219     if (HASHITEM_EMPTY(hi))
7220         return NULL;
7221     return HI2DI(hi);
7222 }
7223
7224 /*
7225  * Get a string item from a dictionary.
7226  * When "save" is TRUE allocate memory for it.
7227  * Returns NULL if the entry doesn't exist or out of memory.
7228  */
7229     char_u *
7230 get_dict_string(d, key, save)
7231     dict_T      *d;
7232     char_u      *key;
7233     int         save;
7234 {
7235     dictitem_T  *di;
7236     char_u      *s;
7237
7238     di = dict_find(d, key, -1);
7239     if (di == NULL)
7240         return NULL;
7241     s = get_tv_string(&di->di_tv);
7242     if (save && s != NULL)
7243         s = vim_strsave(s);
7244     return s;
7245 }
7246
7247 /*
7248  * Get a number item from a dictionary.
7249  * Returns 0 if the entry doesn't exist or out of memory.
7250  */
7251     long
7252 get_dict_number(d, key)
7253     dict_T      *d;
7254     char_u      *key;
7255 {
7256     dictitem_T  *di;
7257
7258     di = dict_find(d, key, -1);
7259     if (di == NULL)
7260         return 0;
7261     return get_tv_number(&di->di_tv);
7262 }
7263
7264 /*
7265  * Return an allocated string with the string representation of a Dictionary.
7266  * May return NULL.
7267  */
7268     static char_u *
7269 dict2string(tv, copyID)
7270     typval_T    *tv;
7271     int         copyID;
7272 {
7273     garray_T    ga;
7274     int         first = TRUE;
7275     char_u      *tofree;
7276     char_u      numbuf[NUMBUFLEN];
7277     hashitem_T  *hi;
7278     char_u      *s;
7279     dict_T      *d;
7280     int         todo;
7281
7282     if ((d = tv->vval.v_dict) == NULL)
7283         return NULL;
7284     ga_init2(&ga, (int)sizeof(char), 80);
7285     ga_append(&ga, '{');
7286
7287     todo = (int)d->dv_hashtab.ht_used;
7288     for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
7289     {
7290         if (!HASHITEM_EMPTY(hi))
7291         {
7292             --todo;
7293
7294             if (first)
7295                 first = FALSE;
7296             else
7297                 ga_concat(&ga, (char_u *)", ");
7298
7299             tofree = string_quote(hi->hi_key, FALSE);
7300             if (tofree != NULL)
7301             {
7302                 ga_concat(&ga, tofree);
7303                 vim_free(tofree);
7304             }
7305             ga_concat(&ga, (char_u *)": ");
7306             s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
7307             if (s != NULL)
7308                 ga_concat(&ga, s);
7309             vim_free(tofree);
7310             if (s == NULL)
7311                 break;
7312         }
7313     }
7314     if (todo > 0)
7315     {
7316         vim_free(ga.ga_data);
7317         return NULL;
7318     }
7319
7320     ga_append(&ga, '}');
7321     ga_append(&ga, NUL);
7322     return (char_u *)ga.ga_data;
7323 }
7324
7325 /*
7326  * Allocate a variable for a Dictionary and fill it from "*arg".
7327  * Return OK or FAIL.  Returns NOTDONE for {expr}.
7328  */
7329     static int
7330 get_dict_tv(arg, rettv, evaluate)
7331     char_u      **arg;
7332     typval_T    *rettv;
7333     int         evaluate;
7334 {
7335     dict_T      *d = NULL;
7336     typval_T    tvkey;
7337     typval_T    tv;
7338     char_u      *key = NULL;
7339     dictitem_T  *item;
7340     char_u      *start = skipwhite(*arg + 1);
7341     char_u      buf[NUMBUFLEN];
7342
7343     /*
7344      * First check if it's not a curly-braces thing: {expr}.
7345      * Must do this without evaluating, otherwise a function may be called
7346      * twice.  Unfortunately this means we need to call eval1() twice for the
7347      * first item.
7348      * But {} is an empty Dictionary.
7349      */
7350     if (*start != '}')
7351     {
7352         if (eval1(&start, &tv, FALSE) == FAIL)  /* recursive! */
7353             return FAIL;
7354         if (*start == '}')
7355             return NOTDONE;
7356     }
7357
7358     if (evaluate)
7359     {
7360         d = dict_alloc();
7361         if (d == NULL)
7362             return FAIL;
7363     }
7364     tvkey.v_type = VAR_UNKNOWN;
7365     tv.v_type = VAR_UNKNOWN;
7366
7367     *arg = skipwhite(*arg + 1);
7368     while (**arg != '}' && **arg != NUL)
7369     {
7370         if (eval1(arg, &tvkey, evaluate) == FAIL)       /* recursive! */
7371             goto failret;
7372         if (**arg != ':')
7373         {
7374             EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
7375             clear_tv(&tvkey);
7376             goto failret;
7377         }
7378         if (evaluate)
7379         {
7380             key = get_tv_string_buf_chk(&tvkey, buf);
7381             if (key == NULL || *key == NUL)
7382             {
7383                 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
7384                 if (key != NULL)
7385                     EMSG(_(e_emptykey));
7386                 clear_tv(&tvkey);
7387                 goto failret;
7388             }
7389         }
7390
7391         *arg = skipwhite(*arg + 1);
7392         if (eval1(arg, &tv, evaluate) == FAIL)  /* recursive! */
7393         {
7394             if (evaluate)
7395                 clear_tv(&tvkey);
7396             goto failret;
7397         }
7398         if (evaluate)
7399         {
7400             item = dict_find(d, key, -1);
7401             if (item != NULL)
7402             {
7403                 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
7404                 clear_tv(&tvkey);
7405                 clear_tv(&tv);
7406                 goto failret;
7407             }
7408             item = dictitem_alloc(key);
7409             clear_tv(&tvkey);
7410             if (item != NULL)
7411             {
7412                 item->di_tv = tv;
7413                 item->di_tv.v_lock = 0;
7414                 if (dict_add(d, item) == FAIL)
7415                     dictitem_free(item);
7416             }
7417         }
7418
7419         if (**arg == '}')
7420             break;
7421         if (**arg != ',')
7422         {
7423             EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
7424             goto failret;
7425         }
7426         *arg = skipwhite(*arg + 1);
7427     }
7428
7429     if (**arg != '}')
7430     {
7431         EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
7432 failret:
7433         if (evaluate)
7434             dict_free(d, TRUE);
7435         return FAIL;
7436     }
7437
7438     *arg = skipwhite(*arg + 1);
7439     if (evaluate)
7440     {
7441         rettv->v_type = VAR_DICT;
7442         rettv->vval.v_dict = d;
7443         ++d->dv_refcount;
7444     }
7445
7446     return OK;
7447 }
7448
7449 /*
7450  * Return a string with the string representation of a variable.
7451  * If the memory is allocated "tofree" is set to it, otherwise NULL.
7452  * "numbuf" is used for a number.
7453  * Does not put quotes around strings, as ":echo" displays values.
7454  * When "copyID" is not NULL replace recursive lists and dicts with "...".
7455  * May return NULL.
7456  */
7457     static char_u *
7458 echo_string(tv, tofree, numbuf, copyID)
7459     typval_T    *tv;
7460     char_u      **tofree;
7461     char_u      *numbuf;
7462     int         copyID;
7463 {
7464     static int  recurse = 0;
7465     char_u      *r = NULL;
7466
7467     if (recurse >= DICT_MAXNEST)
7468     {
7469         EMSG(_("E724: variable nested too deep for displaying"));
7470         *tofree = NULL;
7471         return NULL;
7472     }
7473     ++recurse;
7474
7475     switch (tv->v_type)
7476     {
7477         case VAR_FUNC:
7478             *tofree = NULL;
7479             r = tv->vval.v_string;
7480             break;
7481
7482         case VAR_LIST:
7483             if (tv->vval.v_list == NULL)
7484             {
7485                 *tofree = NULL;
7486                 r = NULL;
7487             }
7488             else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
7489             {
7490                 *tofree = NULL;
7491                 r = (char_u *)"[...]";
7492             }
7493             else
7494             {
7495                 tv->vval.v_list->lv_copyID = copyID;
7496                 *tofree = list2string(tv, copyID);
7497                 r = *tofree;
7498             }
7499             break;
7500
7501         case VAR_DICT:
7502             if (tv->vval.v_dict == NULL)
7503             {
7504                 *tofree = NULL;
7505                 r = NULL;
7506             }
7507             else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
7508             {
7509                 *tofree = NULL;
7510                 r = (char_u *)"{...}";
7511             }
7512             else
7513             {
7514                 tv->vval.v_dict->dv_copyID = copyID;
7515                 *tofree = dict2string(tv, copyID);
7516                 r = *tofree;
7517             }
7518             break;
7519
7520         case VAR_STRING:
7521         case VAR_NUMBER:
7522             *tofree = NULL;
7523             r = get_tv_string_buf(tv, numbuf);
7524             break;
7525
7526 #ifdef FEAT_FLOAT
7527         case VAR_FLOAT:
7528             *tofree = NULL;
7529             vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
7530             r = numbuf;
7531             break;
7532 #endif
7533
7534         default:
7535             EMSG2(_(e_intern2), "echo_string()");
7536             *tofree = NULL;
7537     }
7538
7539     --recurse;
7540     return r;
7541 }
7542
7543 /*
7544  * Return a string with the string representation of a variable.
7545  * If the memory is allocated "tofree" is set to it, otherwise NULL.
7546  * "numbuf" is used for a number.
7547  * Puts quotes around strings, so that they can be parsed back by eval().
7548  * May return NULL.
7549  */
7550     static char_u *
7551 tv2string(tv, tofree, numbuf, copyID)
7552     typval_T    *tv;
7553     char_u      **tofree;
7554     char_u      *numbuf;
7555     int         copyID;
7556 {
7557     switch (tv->v_type)
7558     {
7559         case VAR_FUNC:
7560             *tofree = string_quote(tv->vval.v_string, TRUE);
7561             return *tofree;
7562         case VAR_STRING:
7563             *tofree = string_quote(tv->vval.v_string, FALSE);
7564             return *tofree;
7565 #ifdef FEAT_FLOAT
7566         case VAR_FLOAT:
7567             *tofree = NULL;
7568             vim_snprintf((char *)numbuf, NUMBUFLEN - 1, "%g", tv->vval.v_float);
7569             return numbuf;
7570 #endif
7571         case VAR_NUMBER:
7572         case VAR_LIST:
7573         case VAR_DICT:
7574             break;
7575         default:
7576             EMSG2(_(e_intern2), "tv2string()");
7577     }
7578     return echo_string(tv, tofree, numbuf, copyID);
7579 }
7580
7581 /*
7582  * Return string "str" in ' quotes, doubling ' characters.
7583  * If "str" is NULL an empty string is assumed.
7584  * If "function" is TRUE make it function('string').
7585  */
7586     static char_u *
7587 string_quote(str, function)
7588     char_u      *str;
7589     int         function;
7590 {
7591     unsigned    len;
7592     char_u      *p, *r, *s;
7593
7594     len = (function ? 13 : 3);
7595     if (str != NULL)
7596     {
7597         len += (unsigned)STRLEN(str);
7598         for (p = str; *p != NUL; mb_ptr_adv(p))
7599             if (*p == '\'')
7600                 ++len;
7601     }
7602     s = r = alloc(len);
7603     if (r != NULL)
7604     {
7605         if (function)
7606         {
7607             STRCPY(r, "function('");
7608             r += 10;
7609         }
7610         else
7611             *r++ = '\'';
7612         if (str != NULL)
7613             for (p = str; *p != NUL; )
7614             {
7615                 if (*p == '\'')
7616                     *r++ = '\'';
7617                 MB_COPY_CHAR(p, r);
7618             }
7619         *r++ = '\'';
7620         if (function)
7621             *r++ = ')';
7622         *r++ = NUL;
7623     }
7624     return s;
7625 }
7626
7627 #ifdef FEAT_FLOAT
7628 /*
7629  * Convert the string "text" to a floating point number.
7630  * This uses strtod().  setlocale(LC_NUMERIC, "C") has been used to make sure
7631  * this always uses a decimal point.
7632  * Returns the length of the text that was consumed.
7633  */
7634     static int
7635 string2float(text, value)
7636     char_u      *text;
7637     float_T     *value;     /* result stored here */
7638 {
7639     char        *s = (char *)text;
7640     float_T     f;
7641
7642     f = strtod(s, &s);
7643     *value = f;
7644     return (int)((char_u *)s - text);
7645 }
7646 #endif
7647
7648 /*
7649  * Get the value of an environment variable.
7650  * "arg" is pointing to the '$'.  It is advanced to after the name.
7651  * If the environment variable was not set, silently assume it is empty.
7652  * Always return OK.
7653  */
7654     static int
7655 get_env_tv(arg, rettv, evaluate)
7656     char_u      **arg;
7657     typval_T    *rettv;
7658     int         evaluate;
7659 {
7660     char_u      *string = NULL;
7661     int         len;
7662     int         cc;
7663     char_u      *name;
7664     int         mustfree = FALSE;
7665
7666     ++*arg;
7667     name = *arg;
7668     len = get_env_len(arg);
7669     if (evaluate)
7670     {
7671         if (len != 0)
7672         {
7673             cc = name[len];
7674             name[len] = NUL;
7675             /* first try vim_getenv(), fast for normal environment vars */
7676             string = vim_getenv(name, &mustfree);
7677             if (string != NULL && *string != NUL)
7678             {
7679                 if (!mustfree)
7680                     string = vim_strsave(string);
7681             }
7682             else
7683             {
7684                 if (mustfree)
7685                     vim_free(string);
7686
7687                 /* next try expanding things like $VIM and ${HOME} */
7688                 string = expand_env_save(name - 1);
7689                 if (string != NULL && *string == '$')
7690                 {
7691                     vim_free(string);
7692                     string = NULL;
7693                 }
7694             }
7695             name[len] = cc;
7696         }
7697         rettv->v_type = VAR_STRING;
7698         rettv->vval.v_string = string;
7699     }
7700
7701     return OK;
7702 }
7703
7704 /*
7705  * Array with names and number of arguments of all internal functions
7706  * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7707  */
7708 static struct fst
7709 {
7710     char        *f_name;        /* function name */
7711     char        f_min_argc;     /* minimal number of arguments */
7712     char        f_max_argc;     /* maximal number of arguments */
7713     void        (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7714                                 /* implementation of function */
7715 } functions[] =
7716 {
7717 #ifdef FEAT_FLOAT
7718     {"abs",             1, 1, f_abs},
7719     {"acos",            1, 1, f_acos},  /* WJMc */
7720 #endif
7721     {"add",             2, 2, f_add},
7722     {"and",             2, 2, f_and},
7723     {"append",          2, 2, f_append},
7724     {"argc",            0, 0, f_argc},
7725     {"argidx",          0, 0, f_argidx},
7726     {"argv",            0, 1, f_argv},
7727 #ifdef FEAT_FLOAT
7728     {"asin",            1, 1, f_asin},  /* WJMc */
7729     {"atan",            1, 1, f_atan},
7730     {"atan2",           2, 2, f_atan2},
7731 #endif
7732     {"browse",          4, 4, f_browse},
7733     {"browsedir",       2, 2, f_browsedir},
7734     {"bufexists",       1, 1, f_bufexists},
7735     {"buffer_exists",   1, 1, f_bufexists},     /* obsolete */
7736     {"buffer_name",     1, 1, f_bufname},       /* obsolete */
7737     {"buffer_number",   1, 1, f_bufnr},         /* obsolete */
7738     {"buflisted",       1, 1, f_buflisted},
7739     {"bufloaded",       1, 1, f_bufloaded},
7740     {"bufname",         1, 1, f_bufname},
7741     {"bufnr",           1, 2, f_bufnr},
7742     {"bufwinnr",        1, 1, f_bufwinnr},
7743     {"byte2line",       1, 1, f_byte2line},
7744     {"byteidx",         2, 2, f_byteidx},
7745     {"call",            2, 3, f_call},
7746 #ifdef FEAT_FLOAT
7747     {"ceil",            1, 1, f_ceil},
7748 #endif
7749     {"changenr",        0, 0, f_changenr},
7750     {"char2nr",         1, 1, f_char2nr},
7751     {"cindent",         1, 1, f_cindent},
7752     {"clearmatches",    0, 0, f_clearmatches},
7753     {"col",             1, 1, f_col},
7754 #if defined(FEAT_INS_EXPAND)
7755     {"complete",        2, 2, f_complete},
7756     {"complete_add",    1, 1, f_complete_add},
7757     {"complete_check",  0, 0, f_complete_check},
7758 #endif
7759     {"confirm",         1, 4, f_confirm},
7760     {"copy",            1, 1, f_copy},
7761 #ifdef FEAT_FLOAT
7762     {"cos",             1, 1, f_cos},
7763     {"cosh",            1, 1, f_cosh},
7764 #endif
7765     {"count",           2, 4, f_count},
7766     {"cscope_connection",0,3, f_cscope_connection},
7767     {"cursor",          1, 3, f_cursor},
7768     {"deepcopy",        1, 2, f_deepcopy},
7769     {"delete",          1, 1, f_delete},
7770     {"did_filetype",    0, 0, f_did_filetype},
7771     {"diff_filler",     1, 1, f_diff_filler},
7772     {"diff_hlID",       2, 2, f_diff_hlID},
7773     {"empty",           1, 1, f_empty},
7774     {"escape",          2, 2, f_escape},
7775     {"eval",            1, 1, f_eval},
7776     {"eventhandler",    0, 0, f_eventhandler},
7777     {"executable",      1, 1, f_executable},
7778     {"exists",          1, 1, f_exists},
7779 #ifdef FEAT_FLOAT
7780     {"exp",             1, 1, f_exp},
7781 #endif
7782     {"expand",          1, 2, f_expand},
7783     {"extend",          2, 3, f_extend},
7784     {"feedkeys",        1, 2, f_feedkeys},
7785     {"file_readable",   1, 1, f_filereadable},  /* obsolete */
7786     {"filereadable",    1, 1, f_filereadable},
7787     {"filewritable",    1, 1, f_filewritable},
7788     {"filter",          2, 2, f_filter},
7789     {"finddir",         1, 3, f_finddir},
7790     {"findfile",        1, 3, f_findfile},
7791 #ifdef FEAT_FLOAT
7792     {"float2nr",        1, 1, f_float2nr},
7793     {"floor",           1, 1, f_floor},
7794     {"fmod",            2, 2, f_fmod},
7795 #endif
7796     {"fnameescape",     1, 1, f_fnameescape},
7797     {"fnamemodify",     2, 2, f_fnamemodify},
7798     {"foldclosed",      1, 1, f_foldclosed},
7799     {"foldclosedend",   1, 1, f_foldclosedend},
7800     {"foldlevel",       1, 1, f_foldlevel},
7801     {"foldtext",        0, 0, f_foldtext},
7802     {"foldtextresult",  1, 1, f_foldtextresult},
7803     {"foreground",      0, 0, f_foreground},
7804     {"function",        1, 1, f_function},
7805     {"garbagecollect",  0, 1, f_garbagecollect},
7806     {"get",             2, 3, f_get},
7807     {"getbufline",      2, 3, f_getbufline},
7808     {"getbufvar",       2, 2, f_getbufvar},
7809     {"getchar",         0, 1, f_getchar},
7810     {"getcharmod",      0, 0, f_getcharmod},
7811     {"getcmdline",      0, 0, f_getcmdline},
7812     {"getcmdpos",       0, 0, f_getcmdpos},
7813     {"getcmdtype",      0, 0, f_getcmdtype},
7814     {"getcwd",          0, 0, f_getcwd},
7815     {"getfontname",     0, 1, f_getfontname},
7816     {"getfperm",        1, 1, f_getfperm},
7817     {"getfsize",        1, 1, f_getfsize},
7818     {"getftime",        1, 1, f_getftime},
7819     {"getftype",        1, 1, f_getftype},
7820     {"getline",         1, 2, f_getline},
7821     {"getloclist",      1, 1, f_getqflist},
7822     {"getmatches",      0, 0, f_getmatches},
7823     {"getpid",          0, 0, f_getpid},
7824     {"getpos",          1, 1, f_getpos},
7825     {"getqflist",       0, 0, f_getqflist},
7826     {"getreg",          0, 2, f_getreg},
7827     {"getregtype",      0, 1, f_getregtype},
7828     {"gettabvar",       2, 2, f_gettabvar},
7829     {"gettabwinvar",    3, 3, f_gettabwinvar},
7830     {"getwinposx",      0, 0, f_getwinposx},
7831     {"getwinposy",      0, 0, f_getwinposy},
7832     {"getwinvar",       2, 2, f_getwinvar},
7833     {"glob",            1, 2, f_glob},
7834     {"globpath",        2, 3, f_globpath},
7835     {"has",             1, 1, f_has},
7836     {"has_key",         2, 2, f_has_key},
7837     {"haslocaldir",     0, 0, f_haslocaldir},
7838     {"hasmapto",        1, 3, f_hasmapto},
7839     {"highlightID",     1, 1, f_hlID},          /* obsolete */
7840     {"highlight_exists",1, 1, f_hlexists},      /* obsolete */
7841     {"histadd",         2, 2, f_histadd},
7842     {"histdel",         1, 2, f_histdel},
7843     {"histget",         1, 2, f_histget},
7844     {"histnr",          1, 1, f_histnr},
7845     {"hlID",            1, 1, f_hlID},
7846     {"hlexists",        1, 1, f_hlexists},
7847     {"hostname",        0, 0, f_hostname},
7848     {"iconv",           3, 3, f_iconv},
7849     {"indent",          1, 1, f_indent},
7850     {"index",           2, 4, f_index},
7851     {"input",           1, 3, f_input},
7852     {"inputdialog",     1, 3, f_inputdialog},
7853     {"inputlist",       1, 1, f_inputlist},
7854     {"inputrestore",    0, 0, f_inputrestore},
7855     {"inputsave",       0, 0, f_inputsave},
7856     {"inputsecret",     1, 2, f_inputsecret},
7857     {"insert",          2, 3, f_insert},
7858     {"invert",          1, 1, f_invert},
7859     {"isdirectory",     1, 1, f_isdirectory},
7860     {"islocked",        1, 1, f_islocked},
7861     {"items",           1, 1, f_items},
7862     {"join",            1, 2, f_join},
7863     {"keys",            1, 1, f_keys},
7864     {"last_buffer_nr",  0, 0, f_last_buffer_nr},/* obsolete */
7865     {"len",             1, 1, f_len},
7866     {"libcall",         3, 3, f_libcall},
7867     {"libcallnr",       3, 3, f_libcallnr},
7868     {"line",            1, 1, f_line},
7869     {"line2byte",       1, 1, f_line2byte},
7870     {"lispindent",      1, 1, f_lispindent},
7871     {"localtime",       0, 0, f_localtime},
7872 #ifdef FEAT_FLOAT
7873     {"log",             1, 1, f_log},
7874     {"log10",           1, 1, f_log10},
7875 #endif
7876     {"map",             2, 2, f_map},
7877     {"maparg",          1, 4, f_maparg},
7878     {"mapcheck",        1, 3, f_mapcheck},
7879     {"match",           2, 4, f_match},
7880     {"matchadd",        2, 4, f_matchadd},
7881     {"matcharg",        1, 1, f_matcharg},
7882     {"matchdelete",     1, 1, f_matchdelete},
7883     {"matchend",        2, 4, f_matchend},
7884     {"matchlist",       2, 4, f_matchlist},
7885     {"matchstr",        2, 4, f_matchstr},
7886     {"max",             1, 1, f_max},
7887     {"min",             1, 1, f_min},
7888 #ifdef vim_mkdir
7889     {"mkdir",           1, 3, f_mkdir},
7890 #endif
7891     {"mode",            0, 1, f_mode},
7892 #ifdef FEAT_MZSCHEME
7893     {"mzeval",          1, 1, f_mzeval},
7894 #endif
7895     {"nextnonblank",    1, 1, f_nextnonblank},
7896     {"nr2char",         1, 1, f_nr2char},
7897     {"or",              2, 2, f_or},
7898     {"pathshorten",     1, 1, f_pathshorten},
7899 #ifdef FEAT_FLOAT
7900     {"pow",             2, 2, f_pow},
7901 #endif
7902     {"prevnonblank",    1, 1, f_prevnonblank},
7903     {"printf",          2, 19, f_printf},
7904     {"pumvisible",      0, 0, f_pumvisible},
7905     {"range",           1, 3, f_range},
7906     {"readfile",        1, 3, f_readfile},
7907     {"reltime",         0, 2, f_reltime},
7908     {"reltimestr",      1, 1, f_reltimestr},
7909     {"remote_expr",     2, 3, f_remote_expr},
7910     {"remote_foreground", 1, 1, f_remote_foreground},
7911     {"remote_peek",     1, 2, f_remote_peek},
7912     {"remote_read",     1, 1, f_remote_read},
7913     {"remote_send",     2, 3, f_remote_send},
7914     {"remove",          2, 3, f_remove},
7915     {"rename",          2, 2, f_rename},
7916     {"repeat",          2, 2, f_repeat},
7917     {"resolve",         1, 1, f_resolve},
7918     {"reverse",         1, 1, f_reverse},
7919 #ifdef FEAT_FLOAT
7920     {"round",           1, 1, f_round},
7921 #endif
7922     {"search",          1, 4, f_search},
7923     {"searchdecl",      1, 3, f_searchdecl},
7924     {"searchpair",      3, 7, f_searchpair},
7925     {"searchpairpos",   3, 7, f_searchpairpos},
7926     {"searchpos",       1, 4, f_searchpos},
7927     {"server2client",   2, 2, f_server2client},
7928     {"serverlist",      0, 0, f_serverlist},
7929     {"setbufvar",       3, 3, f_setbufvar},
7930     {"setcmdpos",       1, 1, f_setcmdpos},
7931     {"setline",         2, 2, f_setline},
7932     {"setloclist",      2, 3, f_setloclist},
7933     {"setmatches",      1, 1, f_setmatches},
7934     {"setpos",          2, 2, f_setpos},
7935     {"setqflist",       1, 2, f_setqflist},
7936     {"setreg",          2, 3, f_setreg},
7937     {"settabvar",       3, 3, f_settabvar},
7938     {"settabwinvar",    4, 4, f_settabwinvar},
7939     {"setwinvar",       3, 3, f_setwinvar},
7940     {"shellescape",     1, 2, f_shellescape},
7941     {"simplify",        1, 1, f_simplify},
7942 #ifdef FEAT_FLOAT
7943     {"sin",             1, 1, f_sin},
7944     {"sinh",            1, 1, f_sinh},
7945 #endif
7946     {"sort",            1, 3, f_sort},
7947     {"soundfold",       1, 1, f_soundfold},
7948     {"spellbadword",    0, 1, f_spellbadword},
7949     {"spellsuggest",    1, 3, f_spellsuggest},
7950     {"split",           1, 3, f_split},
7951 #ifdef FEAT_FLOAT
7952     {"sqrt",            1, 1, f_sqrt},
7953     {"str2float",       1, 1, f_str2float},
7954 #endif
7955     {"str2nr",          1, 2, f_str2nr},
7956     {"strchars",        1, 1, f_strchars},
7957     {"strdisplaywidth", 1, 2, f_strdisplaywidth},
7958 #ifdef HAVE_STRFTIME
7959     {"strftime",        1, 2, f_strftime},
7960 #endif
7961     {"stridx",          2, 3, f_stridx},
7962     {"string",          1, 1, f_string},
7963     {"strlen",          1, 1, f_strlen},
7964     {"strpart",         2, 3, f_strpart},
7965     {"strridx",         2, 3, f_strridx},
7966     {"strtrans",        1, 1, f_strtrans},
7967     {"strwidth",        1, 1, f_strwidth},
7968     {"submatch",        1, 1, f_submatch},
7969     {"substitute",      4, 4, f_substitute},
7970     {"synID",           3, 3, f_synID},
7971     {"synIDattr",       2, 3, f_synIDattr},
7972     {"synIDtrans",      1, 1, f_synIDtrans},
7973     {"synconcealed",    2, 2, f_synconcealed},
7974     {"synstack",        2, 2, f_synstack},
7975     {"system",          1, 2, f_system},
7976     {"tabpagebuflist",  0, 1, f_tabpagebuflist},
7977     {"tabpagenr",       0, 1, f_tabpagenr},
7978     {"tabpagewinnr",    1, 2, f_tabpagewinnr},
7979     {"tagfiles",        0, 0, f_tagfiles},
7980     {"taglist",         1, 1, f_taglist},
7981 #ifdef FEAT_FLOAT
7982     {"tan",             1, 1, f_tan},
7983     {"tanh",            1, 1, f_tanh},
7984 #endif
7985     {"tempname",        0, 0, f_tempname},
7986     {"test",            1, 1, f_test},
7987     {"tolower",         1, 1, f_tolower},
7988     {"toupper",         1, 1, f_toupper},
7989     {"tr",              3, 3, f_tr},
7990 #ifdef FEAT_FLOAT
7991     {"trunc",           1, 1, f_trunc},
7992 #endif
7993     {"type",            1, 1, f_type},
7994     {"undofile",        1, 1, f_undofile},
7995     {"undotree",        0, 0, f_undotree},
7996     {"values",          1, 1, f_values},
7997     {"virtcol",         1, 1, f_virtcol},
7998     {"visualmode",      0, 1, f_visualmode},
7999     {"winbufnr",        1, 1, f_winbufnr},
8000     {"wincol",          0, 0, f_wincol},
8001     {"winheight",       1, 1, f_winheight},
8002     {"winline",         0, 0, f_winline},
8003     {"winnr",           0, 1, f_winnr},
8004     {"winrestcmd",      0, 0, f_winrestcmd},
8005     {"winrestview",     1, 1, f_winrestview},
8006     {"winsaveview",     0, 0, f_winsaveview},
8007     {"winwidth",        1, 1, f_winwidth},
8008     {"writefile",       2, 3, f_writefile},
8009     {"xor",             2, 2, f_xor},
8010 };
8011
8012 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
8013
8014 /*
8015  * Function given to ExpandGeneric() to obtain the list of internal
8016  * or user defined function names.
8017  */
8018     char_u *
8019 get_function_name(xp, idx)
8020     expand_T    *xp;
8021     int         idx;
8022 {
8023     static int  intidx = -1;
8024     char_u      *name;
8025
8026     if (idx == 0)
8027         intidx = -1;
8028     if (intidx < 0)
8029     {
8030         name = get_user_func_name(xp, idx);
8031         if (name != NULL)
8032             return name;
8033     }
8034     if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
8035     {
8036         STRCPY(IObuff, functions[intidx].f_name);
8037         STRCAT(IObuff, "(");
8038         if (functions[intidx].f_max_argc == 0)
8039             STRCAT(IObuff, ")");
8040         return IObuff;
8041     }
8042
8043     return NULL;
8044 }
8045
8046 /*
8047  * Function given to ExpandGeneric() to obtain the list of internal or
8048  * user defined variable or function names.
8049  */
8050     char_u *
8051 get_expr_name(xp, idx)
8052     expand_T    *xp;
8053     int         idx;
8054 {
8055     static int  intidx = -1;
8056     char_u      *name;
8057
8058     if (idx == 0)
8059         intidx = -1;
8060     if (intidx < 0)
8061     {
8062         name = get_function_name(xp, idx);
8063         if (name != NULL)
8064             return name;
8065     }
8066     return get_user_var_name(xp, ++intidx);
8067 }
8068
8069 #endif /* FEAT_CMDL_COMPL */
8070
8071 #if defined(EBCDIC) || defined(PROTO)
8072 /*
8073  * Compare struct fst by function name.
8074  */
8075     static int
8076 compare_func_name(s1, s2)
8077     const void *s1;
8078     const void *s2;
8079 {
8080     struct fst *p1 = (struct fst *)s1;
8081     struct fst *p2 = (struct fst *)s2;
8082
8083     return STRCMP(p1->f_name, p2->f_name);
8084 }
8085
8086 /*
8087  * Sort the function table by function name.
8088  * The sorting of the table above is ASCII dependant.
8089  * On machines using EBCDIC we have to sort it.
8090  */
8091     static void
8092 sortFunctions()
8093 {
8094     int         funcCnt = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
8095
8096     qsort(functions, (size_t)funcCnt, sizeof(struct fst), compare_func_name);
8097 }
8098 #endif
8099
8100
8101 /*
8102  * Find internal function in table above.
8103  * Return index, or -1 if not found
8104  */
8105     static int
8106 find_internal_func(name)
8107     char_u      *name;          /* name of the function */
8108 {
8109     int         first = 0;
8110     int         last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
8111     int         cmp;
8112     int         x;
8113
8114     /*
8115      * Find the function name in the table. Binary search.
8116      */
8117     while (first <= last)
8118     {
8119         x = first + ((unsigned)(last - first) >> 1);
8120         cmp = STRCMP(name, functions[x].f_name);
8121         if (cmp < 0)
8122             last = x - 1;
8123         else if (cmp > 0)
8124             first = x + 1;
8125         else
8126             return x;
8127     }
8128     return -1;
8129 }
8130
8131 /*
8132  * Check if "name" is a variable of type VAR_FUNC.  If so, return the function
8133  * name it contains, otherwise return "name".
8134  */
8135     static char_u *
8136 deref_func_name(name, lenp)
8137     char_u      *name;
8138     int         *lenp;
8139 {
8140     dictitem_T  *v;
8141     int         cc;
8142
8143     cc = name[*lenp];
8144     name[*lenp] = NUL;
8145     v = find_var(name, NULL);
8146     name[*lenp] = cc;
8147     if (v != NULL && v->di_tv.v_type == VAR_FUNC)
8148     {
8149         if (v->di_tv.vval.v_string == NULL)
8150         {
8151             *lenp = 0;
8152             return (char_u *)"";        /* just in case */
8153         }
8154         *lenp = (int)STRLEN(v->di_tv.vval.v_string);
8155         return v->di_tv.vval.v_string;
8156     }
8157
8158     return name;
8159 }
8160
8161 /*
8162  * Allocate a variable for the result of a function.
8163  * Return OK or FAIL.
8164  */
8165     static int
8166 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
8167                                                            evaluate, selfdict)
8168     char_u      *name;          /* name of the function */
8169     int         len;            /* length of "name" */
8170     typval_T    *rettv;
8171     char_u      **arg;          /* argument, pointing to the '(' */
8172     linenr_T    firstline;      /* first line of range */
8173     linenr_T    lastline;       /* last line of range */
8174     int         *doesrange;     /* return: function handled range */
8175     int         evaluate;
8176     dict_T      *selfdict;      /* Dictionary for "self" */
8177 {
8178     char_u      *argp;
8179     int         ret = OK;
8180     typval_T    argvars[MAX_FUNC_ARGS + 1];     /* vars for arguments */
8181     int         argcount = 0;           /* number of arguments found */
8182
8183     /*
8184      * Get the arguments.
8185      */
8186     argp = *arg;
8187     while (argcount < MAX_FUNC_ARGS)
8188     {
8189         argp = skipwhite(argp + 1);         /* skip the '(' or ',' */
8190         if (*argp == ')' || *argp == ',' || *argp == NUL)
8191             break;
8192         if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
8193         {
8194             ret = FAIL;
8195             break;
8196         }
8197         ++argcount;
8198         if (*argp != ',')
8199             break;
8200     }
8201     if (*argp == ')')
8202         ++argp;
8203     else
8204         ret = FAIL;
8205
8206     if (ret == OK)
8207         ret = call_func(name, len, rettv, argcount, argvars,
8208                           firstline, lastline, doesrange, evaluate, selfdict);
8209     else if (!aborting())
8210     {
8211         if (argcount == MAX_FUNC_ARGS)
8212             emsg_funcname(N_("E740: Too many arguments for function %s"), name);
8213         else
8214             emsg_funcname(N_("E116: Invalid arguments for function %s"), name);
8215     }
8216
8217     while (--argcount >= 0)
8218         clear_tv(&argvars[argcount]);
8219
8220     *arg = skipwhite(argp);
8221     return ret;
8222 }
8223
8224
8225 /*
8226  * Call a function with its resolved parameters
8227  * Return OK when the function can't be called,  FAIL otherwise.
8228  * Also returns OK when an error was encountered while executing the function.
8229  */
8230     static int
8231 call_func(funcname, len, rettv, argcount, argvars, firstline, lastline,
8232                                                 doesrange, evaluate, selfdict)
8233     char_u      *funcname;      /* name of the function */
8234     int         len;            /* length of "name" */
8235     typval_T    *rettv;         /* return value goes here */
8236     int         argcount;       /* number of "argvars" */
8237     typval_T    *argvars;       /* vars for arguments, must have "argcount"
8238                                    PLUS ONE elements! */
8239     linenr_T    firstline;      /* first line of range */
8240     linenr_T    lastline;       /* last line of range */
8241     int         *doesrange;     /* return: function handled range */
8242     int         evaluate;
8243     dict_T      *selfdict;      /* Dictionary for "self" */
8244 {
8245     int         ret = FAIL;
8246 #define ERROR_UNKNOWN   0
8247 #define ERROR_TOOMANY   1
8248 #define ERROR_TOOFEW    2
8249 #define ERROR_SCRIPT    3
8250 #define ERROR_DICT      4
8251 #define ERROR_NONE      5
8252 #define ERROR_OTHER     6
8253     int         error = ERROR_NONE;
8254     int         i;
8255     int         llen;
8256     ufunc_T     *fp;
8257 #define FLEN_FIXED 40
8258     char_u      fname_buf[FLEN_FIXED + 1];
8259     char_u      *fname;
8260     char_u      *name;
8261
8262     /* Make a copy of the name, if it comes from a funcref variable it could
8263      * be changed or deleted in the called function. */
8264     name = vim_strnsave(funcname, len);
8265     if (name == NULL)
8266         return ret;
8267
8268     /*
8269      * In a script change <SID>name() and s:name() to K_SNR 123_name().
8270      * Change <SNR>123_name() to K_SNR 123_name().
8271      * Use fname_buf[] when it fits, otherwise allocate memory (slow).
8272      */
8273     llen = eval_fname_script(name);
8274     if (llen > 0)
8275     {
8276         fname_buf[0] = K_SPECIAL;
8277         fname_buf[1] = KS_EXTRA;
8278         fname_buf[2] = (int)KE_SNR;
8279         i = 3;
8280         if (eval_fname_sid(name))       /* "<SID>" or "s:" */
8281         {
8282             if (current_SID <= 0)
8283                 error = ERROR_SCRIPT;
8284             else
8285             {
8286                 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
8287                 i = (int)STRLEN(fname_buf);
8288             }
8289         }
8290         if (i + STRLEN(name + llen) < FLEN_FIXED)
8291         {
8292             STRCPY(fname_buf + i, name + llen);
8293             fname = fname_buf;
8294         }
8295         else
8296         {
8297             fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
8298             if (fname == NULL)
8299                 error = ERROR_OTHER;
8300             else
8301             {
8302                 mch_memmove(fname, fname_buf, (size_t)i);
8303                 STRCPY(fname + i, name + llen);
8304             }
8305         }
8306     }
8307     else
8308         fname = name;
8309
8310     *doesrange = FALSE;
8311
8312
8313     /* execute the function if no errors detected and executing */
8314     if (evaluate && error == ERROR_NONE)
8315     {
8316         rettv->v_type = VAR_NUMBER;     /* default rettv is number zero */
8317         rettv->vval.v_number = 0;
8318         error = ERROR_UNKNOWN;
8319
8320         if (!builtin_function(fname))
8321         {
8322             /*
8323              * User defined function.
8324              */
8325             fp = find_func(fname);
8326
8327 #ifdef FEAT_AUTOCMD
8328             /* Trigger FuncUndefined event, may load the function. */
8329             if (fp == NULL
8330                     && apply_autocmds(EVENT_FUNCUNDEFINED,
8331                                                      fname, fname, TRUE, NULL)
8332                     && !aborting())
8333             {
8334                 /* executed an autocommand, search for the function again */
8335                 fp = find_func(fname);
8336             }
8337 #endif
8338             /* Try loading a package. */
8339             if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
8340             {
8341                 /* loaded a package, search for the function again */
8342                 fp = find_func(fname);
8343             }
8344
8345             if (fp != NULL)
8346             {
8347                 if (fp->uf_flags & FC_RANGE)
8348                     *doesrange = TRUE;
8349                 if (argcount < fp->uf_args.ga_len)
8350                     error = ERROR_TOOFEW;
8351                 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
8352                     error = ERROR_TOOMANY;
8353                 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
8354                     error = ERROR_DICT;
8355                 else
8356                 {
8357                     /*
8358                      * Call the user function.
8359                      * Save and restore search patterns, script variables and
8360                      * redo buffer.
8361                      */
8362                     save_search_patterns();
8363                     saveRedobuff();
8364                     ++fp->uf_calls;
8365                     call_user_func(fp, argcount, argvars, rettv,
8366                                                firstline, lastline,
8367                                   (fp->uf_flags & FC_DICT) ? selfdict : NULL);
8368                     if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
8369                                                       && fp->uf_refcount <= 0)
8370                         /* Function was unreferenced while being used, free it
8371                          * now. */
8372                         func_free(fp);
8373                     restoreRedobuff();
8374                     restore_search_patterns();
8375                     error = ERROR_NONE;
8376                 }
8377             }
8378         }
8379         else
8380         {
8381             /*
8382              * Find the function name in the table, call its implementation.
8383              */
8384             i = find_internal_func(fname);
8385             if (i >= 0)
8386             {
8387                 if (argcount < functions[i].f_min_argc)
8388                     error = ERROR_TOOFEW;
8389                 else if (argcount > functions[i].f_max_argc)
8390                     error = ERROR_TOOMANY;
8391                 else
8392                 {
8393                     argvars[argcount].v_type = VAR_UNKNOWN;
8394                     functions[i].f_func(argvars, rettv);
8395                     error = ERROR_NONE;
8396                 }
8397             }
8398         }
8399         /*
8400          * The function call (or "FuncUndefined" autocommand sequence) might
8401          * have been aborted by an error, an interrupt, or an explicitly thrown
8402          * exception that has not been caught so far.  This situation can be
8403          * tested for by calling aborting().  For an error in an internal
8404          * function or for the "E132" error in call_user_func(), however, the
8405          * throw point at which the "force_abort" flag (temporarily reset by
8406          * emsg()) is normally updated has not been reached yet. We need to
8407          * update that flag first to make aborting() reliable.
8408          */
8409         update_force_abort();
8410     }
8411     if (error == ERROR_NONE)
8412         ret = OK;
8413
8414     /*
8415      * Report an error unless the argument evaluation or function call has been
8416      * cancelled due to an aborting error, an interrupt, or an exception.
8417      */
8418     if (!aborting())
8419     {
8420         switch (error)
8421         {
8422             case ERROR_UNKNOWN:
8423                     emsg_funcname(N_("E117: Unknown function: %s"), name);
8424                     break;
8425             case ERROR_TOOMANY:
8426                     emsg_funcname(e_toomanyarg, name);
8427                     break;
8428             case ERROR_TOOFEW:
8429                     emsg_funcname(N_("E119: Not enough arguments for function: %s"),
8430                                                                         name);
8431                     break;
8432             case ERROR_SCRIPT:
8433                     emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
8434                                                                         name);
8435                     break;
8436             case ERROR_DICT:
8437                     emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
8438                                                                         name);
8439                     break;
8440         }
8441     }
8442
8443     if (fname != name && fname != fname_buf)
8444         vim_free(fname);
8445     vim_free(name);
8446
8447     return ret;
8448 }
8449
8450 /*
8451  * Give an error message with a function name.  Handle <SNR> things.
8452  * "ermsg" is to be passed without translation, use N_() instead of _().
8453  */
8454     static void
8455 emsg_funcname(ermsg, name)
8456     char        *ermsg;
8457     char_u      *name;
8458 {
8459     char_u      *p;
8460
8461     if (*name == K_SPECIAL)
8462         p = concat_str((char_u *)"<SNR>", name + 3);
8463     else
8464         p = name;
8465     EMSG2(_(ermsg), p);
8466     if (p != name)
8467         vim_free(p);
8468 }
8469
8470 /*
8471  * Return TRUE for a non-zero Number and a non-empty String.
8472  */
8473     static int
8474 non_zero_arg(argvars)
8475     typval_T    *argvars;
8476 {
8477     return ((argvars[0].v_type == VAR_NUMBER
8478                 && argvars[0].vval.v_number != 0)
8479             || (argvars[0].v_type == VAR_STRING
8480                 && argvars[0].vval.v_string != NULL
8481                 && *argvars[0].vval.v_string != NUL));
8482 }
8483
8484 /*********************************************
8485  * Implementation of the built-in functions
8486  */
8487
8488 #ifdef FEAT_FLOAT
8489 static int get_float_arg __ARGS((typval_T *argvars, float_T *f));
8490
8491 /*
8492  * Get the float value of "argvars[0]" into "f".
8493  * Returns FAIL when the argument is not a Number or Float.
8494  */
8495     static int
8496 get_float_arg(argvars, f)
8497     typval_T    *argvars;
8498     float_T     *f;
8499 {
8500     if (argvars[0].v_type == VAR_FLOAT)
8501     {
8502         *f = argvars[0].vval.v_float;
8503         return OK;
8504     }
8505     if (argvars[0].v_type == VAR_NUMBER)
8506     {
8507         *f = (float_T)argvars[0].vval.v_number;
8508         return OK;
8509     }
8510     EMSG(_("E808: Number or Float required"));
8511     return FAIL;
8512 }
8513
8514 /*
8515  * "abs(expr)" function
8516  */
8517     static void
8518 f_abs(argvars, rettv)
8519     typval_T    *argvars;
8520     typval_T    *rettv;
8521 {
8522     if (argvars[0].v_type == VAR_FLOAT)
8523     {
8524         rettv->v_type = VAR_FLOAT;
8525         rettv->vval.v_float = fabs(argvars[0].vval.v_float);
8526     }
8527     else
8528     {
8529         varnumber_T     n;
8530         int             error = FALSE;
8531
8532         n = get_tv_number_chk(&argvars[0], &error);
8533         if (error)
8534             rettv->vval.v_number = -1;
8535         else if (n > 0)
8536             rettv->vval.v_number = n;
8537         else
8538             rettv->vval.v_number = -n;
8539     }
8540 }
8541
8542 /*
8543  * "acos()" function
8544  */
8545     static void
8546 f_acos(argvars, rettv)
8547     typval_T    *argvars;
8548     typval_T    *rettv;
8549 {
8550     float_T     f;
8551
8552     rettv->v_type = VAR_FLOAT;
8553     if (get_float_arg(argvars, &f) == OK)
8554         rettv->vval.v_float = acos(f);
8555     else
8556         rettv->vval.v_float = 0.0;
8557 }
8558 #endif
8559
8560 /*
8561  * "add(list, item)" function
8562  */
8563     static void
8564 f_add(argvars, rettv)
8565     typval_T    *argvars;
8566     typval_T    *rettv;
8567 {
8568     list_T      *l;
8569
8570     rettv->vval.v_number = 1; /* Default: Failed */
8571     if (argvars[0].v_type == VAR_LIST)
8572     {
8573         if ((l = argvars[0].vval.v_list) != NULL
8574                 && !tv_check_lock(l->lv_lock, (char_u *)_("add() argument"))
8575                 && list_append_tv(l, &argvars[1]) == OK)
8576             copy_tv(&argvars[0], rettv);
8577     }
8578     else
8579         EMSG(_(e_listreq));
8580 }
8581
8582 /*
8583  * "and(expr, expr)" function
8584  */
8585     static void
8586 f_and(argvars, rettv)
8587     typval_T    *argvars;
8588     typval_T    *rettv;
8589 {
8590     rettv->vval.v_number = get_tv_number_chk(&argvars[0], NULL)
8591                                         & get_tv_number_chk(&argvars[1], NULL);
8592 }
8593
8594 /*
8595  * "append(lnum, string/list)" function
8596  */
8597     static void
8598 f_append(argvars, rettv)
8599     typval_T    *argvars;
8600     typval_T    *rettv;
8601 {
8602     long        lnum;
8603     char_u      *line;
8604     list_T      *l = NULL;
8605     listitem_T  *li = NULL;
8606     typval_T    *tv;
8607     long        added = 0;
8608
8609     lnum = get_tv_lnum(argvars);
8610     if (lnum >= 0
8611             && lnum <= curbuf->b_ml.ml_line_count
8612             && u_save(lnum, lnum + 1) == OK)
8613     {
8614         if (argvars[1].v_type == VAR_LIST)
8615         {
8616             l = argvars[1].vval.v_list;
8617             if (l == NULL)
8618                 return;
8619             li = l->lv_first;
8620         }
8621         for (;;)
8622         {
8623             if (l == NULL)
8624                 tv = &argvars[1];       /* append a string */
8625             else if (li == NULL)
8626                 break;                  /* end of list */
8627             else
8628                 tv = &li->li_tv;        /* append item from list */
8629             line = get_tv_string_chk(tv);
8630             if (line == NULL)           /* type error */
8631             {
8632                 rettv->vval.v_number = 1;       /* Failed */
8633                 break;
8634             }
8635             ml_append(lnum + added, line, (colnr_T)0, FALSE);
8636             ++added;
8637             if (l == NULL)
8638                 break;
8639             li = li->li_next;
8640         }
8641
8642         appended_lines_mark(lnum, added);
8643         if (curwin->w_cursor.lnum > lnum)
8644             curwin->w_cursor.lnum += added;
8645     }
8646     else
8647         rettv->vval.v_number = 1;       /* Failed */
8648 }
8649
8650 /*
8651  * "argc()" function
8652  */
8653     static void
8654 f_argc(argvars, rettv)
8655     typval_T    *argvars UNUSED;
8656     typval_T    *rettv;
8657 {
8658     rettv->vval.v_number = ARGCOUNT;
8659 }
8660
8661 /*
8662  * "argidx()" function
8663  */
8664     static void
8665 f_argidx(argvars, rettv)
8666     typval_T    *argvars UNUSED;
8667     typval_T    *rettv;
8668 {
8669     rettv->vval.v_number = curwin->w_arg_idx;
8670 }
8671
8672 /*
8673  * "argv(nr)" function
8674  */
8675     static void
8676 f_argv(argvars, rettv)
8677     typval_T    *argvars;
8678     typval_T    *rettv;
8679 {
8680     int         idx;
8681
8682     if (argvars[0].v_type != VAR_UNKNOWN)
8683     {
8684         idx = get_tv_number_chk(&argvars[0], NULL);
8685         if (idx >= 0 && idx < ARGCOUNT)
8686             rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
8687         else
8688             rettv->vval.v_string = NULL;
8689         rettv->v_type = VAR_STRING;
8690     }
8691     else if (rettv_list_alloc(rettv) == OK)
8692         for (idx = 0; idx < ARGCOUNT; ++idx)
8693             list_append_string(rettv->vval.v_list,
8694                                                alist_name(&ARGLIST[idx]), -1);
8695 }
8696
8697 #ifdef FEAT_FLOAT
8698 /*
8699  * "asin()" function
8700  */
8701     static void
8702 f_asin(argvars, rettv)
8703     typval_T    *argvars;
8704     typval_T    *rettv;
8705 {
8706     float_T     f;
8707
8708     rettv->v_type = VAR_FLOAT;
8709     if (get_float_arg(argvars, &f) == OK)
8710         rettv->vval.v_float = asin(f);
8711     else
8712         rettv->vval.v_float = 0.0;
8713 }
8714
8715 /*
8716  * "atan()" function
8717  */
8718     static void
8719 f_atan(argvars, rettv)
8720     typval_T    *argvars;
8721     typval_T    *rettv;
8722 {
8723     float_T     f;
8724
8725     rettv->v_type = VAR_FLOAT;
8726     if (get_float_arg(argvars, &f) == OK)
8727         rettv->vval.v_float = atan(f);
8728     else
8729         rettv->vval.v_float = 0.0;
8730 }
8731
8732 /*
8733  * "atan2()" function
8734  */
8735     static void
8736 f_atan2(argvars, rettv)
8737     typval_T    *argvars;
8738     typval_T    *rettv;
8739 {
8740     float_T     fx, fy;
8741
8742     rettv->v_type = VAR_FLOAT;
8743     if (get_float_arg(argvars, &fx) == OK
8744                                      && get_float_arg(&argvars[1], &fy) == OK)
8745         rettv->vval.v_float = atan2(fx, fy);
8746     else
8747         rettv->vval.v_float = 0.0;
8748 }
8749 #endif
8750
8751 /*
8752  * "browse(save, title, initdir, default)" function
8753  */
8754     static void
8755 f_browse(argvars, rettv)
8756     typval_T    *argvars UNUSED;
8757     typval_T    *rettv;
8758 {
8759 #ifdef FEAT_BROWSE
8760     int         save;
8761     char_u      *title;
8762     char_u      *initdir;
8763     char_u      *defname;
8764     char_u      buf[NUMBUFLEN];
8765     char_u      buf2[NUMBUFLEN];
8766     int         error = FALSE;
8767
8768     save = get_tv_number_chk(&argvars[0], &error);
8769     title = get_tv_string_chk(&argvars[1]);
8770     initdir = get_tv_string_buf_chk(&argvars[2], buf);
8771     defname = get_tv_string_buf_chk(&argvars[3], buf2);
8772
8773     if (error || title == NULL || initdir == NULL || defname == NULL)
8774         rettv->vval.v_string = NULL;
8775     else
8776         rettv->vval.v_string =
8777                  do_browse(save ? BROWSE_SAVE : 0,
8778                                  title, defname, NULL, initdir, NULL, curbuf);
8779 #else
8780     rettv->vval.v_string = NULL;
8781 #endif
8782     rettv->v_type = VAR_STRING;
8783 }
8784
8785 /*
8786  * "browsedir(title, initdir)" function
8787  */
8788     static void
8789 f_browsedir(argvars, rettv)
8790     typval_T    *argvars UNUSED;
8791     typval_T    *rettv;
8792 {
8793 #ifdef FEAT_BROWSE
8794     char_u      *title;
8795     char_u      *initdir;
8796     char_u      buf[NUMBUFLEN];
8797
8798     title = get_tv_string_chk(&argvars[0]);
8799     initdir = get_tv_string_buf_chk(&argvars[1], buf);
8800
8801     if (title == NULL || initdir == NULL)
8802         rettv->vval.v_string = NULL;
8803     else
8804         rettv->vval.v_string = do_browse(BROWSE_DIR,
8805                                     title, NULL, NULL, initdir, NULL, curbuf);
8806 #else
8807     rettv->vval.v_string = NULL;
8808 #endif
8809     rettv->v_type = VAR_STRING;
8810 }
8811
8812 static buf_T *find_buffer __ARGS((typval_T *avar));
8813
8814 /*
8815  * Find a buffer by number or exact name.
8816  */
8817     static buf_T *
8818 find_buffer(avar)
8819     typval_T    *avar;
8820 {
8821     buf_T       *buf = NULL;
8822
8823     if (avar->v_type == VAR_NUMBER)
8824         buf = buflist_findnr((int)avar->vval.v_number);
8825     else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
8826     {
8827         buf = buflist_findname_exp(avar->vval.v_string);
8828         if (buf == NULL)
8829         {
8830             /* No full path name match, try a match with a URL or a "nofile"
8831              * buffer, these don't use the full path. */
8832             for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8833                 if (buf->b_fname != NULL
8834                         && (path_with_url(buf->b_fname)
8835 #ifdef FEAT_QUICKFIX
8836                             || bt_nofile(buf)
8837 #endif
8838                            )
8839                         && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
8840                     break;
8841         }
8842     }
8843     return buf;
8844 }
8845
8846 /*
8847  * "bufexists(expr)" function
8848  */
8849     static void
8850 f_bufexists(argvars, rettv)
8851     typval_T    *argvars;
8852     typval_T    *rettv;
8853 {
8854     rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
8855 }
8856
8857 /*
8858  * "buflisted(expr)" function
8859  */
8860     static void
8861 f_buflisted(argvars, rettv)
8862     typval_T    *argvars;
8863     typval_T    *rettv;
8864 {
8865     buf_T       *buf;
8866
8867     buf = find_buffer(&argvars[0]);
8868     rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
8869 }
8870
8871 /*
8872  * "bufloaded(expr)" function
8873  */
8874     static void
8875 f_bufloaded(argvars, rettv)
8876     typval_T    *argvars;
8877     typval_T    *rettv;
8878 {
8879     buf_T       *buf;
8880
8881     buf = find_buffer(&argvars[0]);
8882     rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
8883 }
8884
8885 static buf_T *get_buf_tv __ARGS((typval_T *tv));
8886
8887 /*
8888  * Get buffer by number or pattern.
8889  */
8890     static buf_T *
8891 get_buf_tv(tv)
8892     typval_T    *tv;
8893 {
8894     char_u      *name = tv->vval.v_string;
8895     int         save_magic;
8896     char_u      *save_cpo;
8897     buf_T       *buf;
8898
8899     if (tv->v_type == VAR_NUMBER)
8900         return buflist_findnr((int)tv->vval.v_number);
8901     if (tv->v_type != VAR_STRING)
8902         return NULL;
8903     if (name == NULL || *name == NUL)
8904         return curbuf;
8905     if (name[0] == '$' && name[1] == NUL)
8906         return lastbuf;
8907
8908     /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
8909     save_magic = p_magic;
8910     p_magic = TRUE;
8911     save_cpo = p_cpo;
8912     p_cpo = (char_u *)"";
8913
8914     buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8915                                                                 TRUE, FALSE));
8916
8917     p_magic = save_magic;
8918     p_cpo = save_cpo;
8919
8920     /* If not found, try expanding the name, like done for bufexists(). */
8921     if (buf == NULL)
8922         buf = find_buffer(tv);
8923
8924     return buf;
8925 }
8926
8927 /*
8928  * "bufname(expr)" function
8929  */
8930     static void
8931 f_bufname(argvars, rettv)
8932     typval_T    *argvars;
8933     typval_T    *rettv;
8934 {
8935     buf_T       *buf;
8936
8937     (void)get_tv_number(&argvars[0]);       /* issue errmsg if type error */
8938     ++emsg_off;
8939     buf = get_buf_tv(&argvars[0]);
8940     rettv->v_type = VAR_STRING;
8941     if (buf != NULL && buf->b_fname != NULL)
8942         rettv->vval.v_string = vim_strsave(buf->b_fname);
8943     else
8944         rettv->vval.v_string = NULL;
8945     --emsg_off;
8946 }
8947
8948 /*
8949  * "bufnr(expr)" function
8950  */
8951     static void
8952 f_bufnr(argvars, rettv)
8953     typval_T    *argvars;
8954     typval_T    *rettv;
8955 {
8956     buf_T       *buf;
8957     int         error = FALSE;
8958     char_u      *name;
8959
8960     (void)get_tv_number(&argvars[0]);       /* issue errmsg if type error */
8961     ++emsg_off;
8962     buf = get_buf_tv(&argvars[0]);
8963     --emsg_off;
8964
8965     /* If the buffer isn't found and the second argument is not zero create a
8966      * new buffer. */
8967     if (buf == NULL
8968             && argvars[1].v_type != VAR_UNKNOWN
8969             && get_tv_number_chk(&argvars[1], &error) != 0
8970             && !error
8971             && (name = get_tv_string_chk(&argvars[0])) != NULL
8972             && !error)
8973         buf = buflist_new(name, NULL, (linenr_T)1, 0);
8974
8975     if (buf != NULL)
8976         rettv->vval.v_number = buf->b_fnum;
8977     else
8978         rettv->vval.v_number = -1;
8979 }
8980
8981 /*
8982  * "bufwinnr(nr)" function
8983  */
8984     static void
8985 f_bufwinnr(argvars, rettv)
8986     typval_T    *argvars;
8987     typval_T    *rettv;
8988 {
8989 #ifdef FEAT_WINDOWS
8990     win_T       *wp;
8991     int         winnr = 0;
8992 #endif
8993     buf_T       *buf;
8994
8995     (void)get_tv_number(&argvars[0]);       /* issue errmsg if type error */
8996     ++emsg_off;
8997     buf = get_buf_tv(&argvars[0]);
8998 #ifdef FEAT_WINDOWS
8999     for (wp = firstwin; wp; wp = wp->w_next)
9000     {
9001         ++winnr;
9002         if (wp->w_buffer == buf)
9003             break;
9004     }
9005     rettv->vval.v_number = (wp != NULL ? winnr : -1);
9006 #else
9007     rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
9008 #endif
9009     --emsg_off;
9010 }
9011
9012 /*
9013  * "byte2line(byte)" function
9014  */
9015     static void
9016 f_byte2line(argvars, rettv)
9017     typval_T    *argvars UNUSED;
9018     typval_T    *rettv;
9019 {
9020 #ifndef FEAT_BYTEOFF
9021     rettv->vval.v_number = -1;
9022 #else
9023     long        boff = 0;
9024
9025     boff = get_tv_number(&argvars[0]) - 1;  /* boff gets -1 on type error */
9026     if (boff < 0)
9027         rettv->vval.v_number = -1;
9028     else
9029         rettv->vval.v_number = ml_find_line_or_offset(curbuf,
9030                                                           (linenr_T)0, &boff);
9031 #endif
9032 }
9033
9034 /*
9035  * "byteidx()" function
9036  */
9037     static void
9038 f_byteidx(argvars, rettv)
9039     typval_T    *argvars;
9040     typval_T    *rettv;
9041 {
9042 #ifdef FEAT_MBYTE
9043     char_u      *t;
9044 #endif
9045     char_u      *str;
9046     long        idx;
9047
9048     str = get_tv_string_chk(&argvars[0]);
9049     idx = get_tv_number_chk(&argvars[1], NULL);
9050     rettv->vval.v_number = -1;
9051     if (str == NULL || idx < 0)
9052         return;
9053
9054 #ifdef FEAT_MBYTE
9055     t = str;
9056     for ( ; idx > 0; idx--)
9057     {
9058         if (*t == NUL)          /* EOL reached */
9059             return;
9060         t += (*mb_ptr2len)(t);
9061     }
9062     rettv->vval.v_number = (varnumber_T)(t - str);
9063 #else
9064     if ((size_t)idx <= STRLEN(str))
9065         rettv->vval.v_number = idx;
9066 #endif
9067 }
9068
9069 /*
9070  * "call(func, arglist)" function
9071  */
9072     static void
9073 f_call(argvars, rettv)
9074     typval_T    *argvars;
9075     typval_T    *rettv;
9076 {
9077     char_u      *func;
9078     typval_T    argv[MAX_FUNC_ARGS + 1];
9079     int         argc = 0;
9080     listitem_T  *item;
9081     int         dummy;
9082     dict_T      *selfdict = NULL;
9083
9084     if (argvars[1].v_type != VAR_LIST)
9085     {
9086         EMSG(_(e_listreq));
9087         return;
9088     }
9089     if (argvars[1].vval.v_list == NULL)
9090         return;
9091
9092     if (argvars[0].v_type == VAR_FUNC)
9093         func = argvars[0].vval.v_string;
9094     else
9095         func = get_tv_string(&argvars[0]);
9096     if (*func == NUL)
9097         return;         /* type error or empty name */
9098
9099     if (argvars[2].v_type != VAR_UNKNOWN)
9100     {
9101         if (argvars[2].v_type != VAR_DICT)
9102         {
9103             EMSG(_(e_dictreq));
9104             return;
9105         }
9106         selfdict = argvars[2].vval.v_dict;
9107     }
9108
9109     for (item = argvars[1].vval.v_list->lv_first; item != NULL;
9110                                                          item = item->li_next)
9111     {
9112         if (argc == MAX_FUNC_ARGS)
9113         {
9114             EMSG(_("E699: Too many arguments"));
9115             break;
9116         }
9117         /* Make a copy of each argument.  This is needed to be able to set
9118          * v_lock to VAR_FIXED in the copy without changing the original list.
9119          */
9120         copy_tv(&item->li_tv, &argv[argc++]);
9121     }
9122
9123     if (item == NULL)
9124         (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
9125                                  curwin->w_cursor.lnum, curwin->w_cursor.lnum,
9126                                                       &dummy, TRUE, selfdict);
9127
9128     /* Free the arguments. */
9129     while (argc > 0)
9130         clear_tv(&argv[--argc]);
9131 }
9132
9133 #ifdef FEAT_FLOAT
9134 /*
9135  * "ceil({float})" function
9136  */
9137     static void
9138 f_ceil(argvars, rettv)
9139     typval_T    *argvars;
9140     typval_T    *rettv;
9141 {
9142     float_T     f;
9143
9144     rettv->v_type = VAR_FLOAT;
9145     if (get_float_arg(argvars, &f) == OK)
9146         rettv->vval.v_float = ceil(f);
9147     else
9148         rettv->vval.v_float = 0.0;
9149 }
9150 #endif
9151
9152 /*
9153  * "changenr()" function
9154  */
9155     static void
9156 f_changenr(argvars, rettv)
9157     typval_T    *argvars UNUSED;
9158     typval_T    *rettv;
9159 {
9160     rettv->vval.v_number = curbuf->b_u_seq_cur;
9161 }
9162
9163 /*
9164  * "char2nr(string)" function
9165  */
9166     static void
9167 f_char2nr(argvars, rettv)
9168     typval_T    *argvars;
9169     typval_T    *rettv;
9170 {
9171 #ifdef FEAT_MBYTE
9172     if (has_mbyte)
9173         rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
9174     else
9175 #endif
9176     rettv->vval.v_number = get_tv_string(&argvars[0])[0];
9177 }
9178
9179 /*
9180  * "cindent(lnum)" function
9181  */
9182     static void
9183 f_cindent(argvars, rettv)
9184     typval_T    *argvars;
9185     typval_T    *rettv;
9186 {
9187 #ifdef FEAT_CINDENT
9188     pos_T       pos;
9189     linenr_T    lnum;
9190
9191     pos = curwin->w_cursor;
9192     lnum = get_tv_lnum(argvars);
9193     if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9194     {
9195         curwin->w_cursor.lnum = lnum;
9196         rettv->vval.v_number = get_c_indent();
9197         curwin->w_cursor = pos;
9198     }
9199     else
9200 #endif
9201         rettv->vval.v_number = -1;
9202 }
9203
9204 /*
9205  * "clearmatches()" function
9206  */
9207     static void
9208 f_clearmatches(argvars, rettv)
9209     typval_T    *argvars UNUSED;
9210     typval_T    *rettv UNUSED;
9211 {
9212 #ifdef FEAT_SEARCH_EXTRA
9213     clear_matches(curwin);
9214 #endif
9215 }
9216
9217 /*
9218  * "col(string)" function
9219  */
9220     static void
9221 f_col(argvars, rettv)
9222     typval_T    *argvars;
9223     typval_T    *rettv;
9224 {
9225     colnr_T     col = 0;
9226     pos_T       *fp;
9227     int         fnum = curbuf->b_fnum;
9228
9229     fp = var2fpos(&argvars[0], FALSE, &fnum);
9230     if (fp != NULL && fnum == curbuf->b_fnum)
9231     {
9232         if (fp->col == MAXCOL)
9233         {
9234             /* '> can be MAXCOL, get the length of the line then */
9235             if (fp->lnum <= curbuf->b_ml.ml_line_count)
9236                 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
9237             else
9238                 col = MAXCOL;
9239         }
9240         else
9241         {
9242             col = fp->col + 1;
9243 #ifdef FEAT_VIRTUALEDIT
9244             /* col(".") when the cursor is on the NUL at the end of the line
9245              * because of "coladd" can be seen as an extra column. */
9246             if (virtual_active() && fp == &curwin->w_cursor)
9247             {
9248                 char_u  *p = ml_get_cursor();
9249
9250                 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
9251                                  curwin->w_virtcol - curwin->w_cursor.coladd))
9252                 {
9253 # ifdef FEAT_MBYTE
9254                     int         l;
9255
9256                     if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
9257                         col += l;
9258 # else
9259                     if (*p != NUL && p[1] == NUL)
9260                         ++col;
9261 # endif
9262                 }
9263             }
9264 #endif
9265         }
9266     }
9267     rettv->vval.v_number = col;
9268 }
9269
9270 #if defined(FEAT_INS_EXPAND)
9271 /*
9272  * "complete()" function
9273  */
9274     static void
9275 f_complete(argvars, rettv)
9276     typval_T    *argvars;
9277     typval_T    *rettv UNUSED;
9278 {
9279     int     startcol;
9280
9281     if ((State & INSERT) == 0)
9282     {
9283         EMSG(_("E785: complete() can only be used in Insert mode"));
9284         return;
9285     }
9286
9287     /* Check for undo allowed here, because if something was already inserted
9288      * the line was already saved for undo and this check isn't done. */
9289     if (!undo_allowed())
9290         return;
9291
9292     if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
9293     {
9294         EMSG(_(e_invarg));
9295         return;
9296     }
9297
9298     startcol = get_tv_number_chk(&argvars[0], NULL);
9299     if (startcol <= 0)
9300         return;
9301
9302     set_completion(startcol - 1, argvars[1].vval.v_list);
9303 }
9304
9305 /*
9306  * "complete_add()" function
9307  */
9308     static void
9309 f_complete_add(argvars, rettv)
9310     typval_T    *argvars;
9311     typval_T    *rettv;
9312 {
9313     rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
9314 }
9315
9316 /*
9317  * "complete_check()" function
9318  */
9319     static void
9320 f_complete_check(argvars, rettv)
9321     typval_T    *argvars UNUSED;
9322     typval_T    *rettv;
9323 {
9324     int         saved = RedrawingDisabled;
9325
9326     RedrawingDisabled = 0;
9327     ins_compl_check_keys(0);
9328     rettv->vval.v_number = compl_interrupted;
9329     RedrawingDisabled = saved;
9330 }
9331 #endif
9332
9333 /*
9334  * "confirm(message, buttons[, default [, type]])" function
9335  */
9336     static void
9337 f_confirm(argvars, rettv)
9338     typval_T    *argvars UNUSED;
9339     typval_T    *rettv UNUSED;
9340 {
9341 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
9342     char_u      *message;
9343     char_u      *buttons = NULL;
9344     char_u      buf[NUMBUFLEN];
9345     char_u      buf2[NUMBUFLEN];
9346     int         def = 1;
9347     int         type = VIM_GENERIC;
9348     char_u      *typestr;
9349     int         error = FALSE;
9350
9351     message = get_tv_string_chk(&argvars[0]);
9352     if (message == NULL)
9353         error = TRUE;
9354     if (argvars[1].v_type != VAR_UNKNOWN)
9355     {
9356         buttons = get_tv_string_buf_chk(&argvars[1], buf);
9357         if (buttons == NULL)
9358             error = TRUE;
9359         if (argvars[2].v_type != VAR_UNKNOWN)
9360         {
9361             def = get_tv_number_chk(&argvars[2], &error);
9362             if (argvars[3].v_type != VAR_UNKNOWN)
9363             {
9364                 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
9365                 if (typestr == NULL)
9366                     error = TRUE;
9367                 else
9368                 {
9369                     switch (TOUPPER_ASC(*typestr))
9370                     {
9371                         case 'E': type = VIM_ERROR; break;
9372                         case 'Q': type = VIM_QUESTION; break;
9373                         case 'I': type = VIM_INFO; break;
9374                         case 'W': type = VIM_WARNING; break;
9375                         case 'G': type = VIM_GENERIC; break;
9376                     }
9377                 }
9378             }
9379         }
9380     }
9381
9382     if (buttons == NULL || *buttons == NUL)
9383         buttons = (char_u *)_("&Ok");
9384
9385     if (!error)
9386         rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
9387                                                             def, NULL, FALSE);
9388 #endif
9389 }
9390
9391 /*
9392  * "copy()" function
9393  */
9394     static void
9395 f_copy(argvars, rettv)
9396     typval_T    *argvars;
9397     typval_T    *rettv;
9398 {
9399     item_copy(&argvars[0], rettv, FALSE, 0);
9400 }
9401
9402 #ifdef FEAT_FLOAT
9403 /*
9404  * "cos()" function
9405  */
9406     static void
9407 f_cos(argvars, rettv)
9408     typval_T    *argvars;
9409     typval_T    *rettv;
9410 {
9411     float_T     f;
9412
9413     rettv->v_type = VAR_FLOAT;
9414     if (get_float_arg(argvars, &f) == OK)
9415         rettv->vval.v_float = cos(f);
9416     else
9417         rettv->vval.v_float = 0.0;
9418 }
9419
9420 /*
9421  * "cosh()" function
9422  */
9423     static void
9424 f_cosh(argvars, rettv)
9425     typval_T    *argvars;
9426     typval_T    *rettv;
9427 {
9428     float_T     f;
9429
9430     rettv->v_type = VAR_FLOAT;
9431     if (get_float_arg(argvars, &f) == OK)
9432         rettv->vval.v_float = cosh(f);
9433     else
9434         rettv->vval.v_float = 0.0;
9435 }
9436 #endif
9437
9438 /*
9439  * "count()" function
9440  */
9441     static void
9442 f_count(argvars, rettv)
9443     typval_T    *argvars;
9444     typval_T    *rettv;
9445 {
9446     long        n = 0;
9447     int         ic = FALSE;
9448
9449     if (argvars[0].v_type == VAR_LIST)
9450     {
9451         listitem_T      *li;
9452         list_T          *l;
9453         long            idx;
9454
9455         if ((l = argvars[0].vval.v_list) != NULL)
9456         {
9457             li = l->lv_first;
9458             if (argvars[2].v_type != VAR_UNKNOWN)
9459             {
9460                 int error = FALSE;
9461
9462                 ic = get_tv_number_chk(&argvars[2], &error);
9463                 if (argvars[3].v_type != VAR_UNKNOWN)
9464                 {
9465                     idx = get_tv_number_chk(&argvars[3], &error);
9466                     if (!error)
9467                     {
9468                         li = list_find(l, idx);
9469                         if (li == NULL)
9470                             EMSGN(_(e_listidx), idx);
9471                     }
9472                 }
9473                 if (error)
9474                     li = NULL;
9475             }
9476
9477             for ( ; li != NULL; li = li->li_next)
9478                 if (tv_equal(&li->li_tv, &argvars[1], ic, FALSE))
9479                     ++n;
9480         }
9481     }
9482     else if (argvars[0].v_type == VAR_DICT)
9483     {
9484         int             todo;
9485         dict_T          *d;
9486         hashitem_T      *hi;
9487
9488         if ((d = argvars[0].vval.v_dict) != NULL)
9489         {
9490             int error = FALSE;
9491
9492             if (argvars[2].v_type != VAR_UNKNOWN)
9493             {
9494                 ic = get_tv_number_chk(&argvars[2], &error);
9495                 if (argvars[3].v_type != VAR_UNKNOWN)
9496                     EMSG(_(e_invarg));
9497             }
9498
9499             todo = error ? 0 : (int)d->dv_hashtab.ht_used;
9500             for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
9501             {
9502                 if (!HASHITEM_EMPTY(hi))
9503                 {
9504                     --todo;
9505                     if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic, FALSE))
9506                         ++n;
9507                 }
9508             }
9509         }
9510     }
9511     else
9512         EMSG2(_(e_listdictarg), "count()");
9513     rettv->vval.v_number = n;
9514 }
9515
9516 /*
9517  * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
9518  *
9519  * Checks the existence of a cscope connection.
9520  */
9521     static void
9522 f_cscope_connection(argvars, rettv)
9523     typval_T    *argvars UNUSED;
9524     typval_T    *rettv UNUSED;
9525 {
9526 #ifdef FEAT_CSCOPE
9527     int         num = 0;
9528     char_u      *dbpath = NULL;
9529     char_u      *prepend = NULL;
9530     char_u      buf[NUMBUFLEN];
9531
9532     if (argvars[0].v_type != VAR_UNKNOWN
9533             && argvars[1].v_type != VAR_UNKNOWN)
9534     {
9535         num = (int)get_tv_number(&argvars[0]);
9536         dbpath = get_tv_string(&argvars[1]);
9537         if (argvars[2].v_type != VAR_UNKNOWN)
9538             prepend = get_tv_string_buf(&argvars[2], buf);
9539     }
9540
9541     rettv->vval.v_number = cs_connection(num, dbpath, prepend);
9542 #endif
9543 }
9544
9545 /*
9546  * "cursor(lnum, col)" function
9547  *
9548  * Moves the cursor to the specified line and column.
9549  * Returns 0 when the position could be set, -1 otherwise.
9550  */
9551     static void
9552 f_cursor(argvars, rettv)
9553     typval_T    *argvars;
9554     typval_T    *rettv;
9555 {
9556     long        line, col;
9557 #ifdef FEAT_VIRTUALEDIT
9558     long        coladd = 0;
9559 #endif
9560
9561     rettv->vval.v_number = -1;
9562     if (argvars[1].v_type == VAR_UNKNOWN)
9563     {
9564         pos_T       pos;
9565
9566         if (list2fpos(argvars, &pos, NULL) == FAIL)
9567             return;
9568         line = pos.lnum;
9569         col = pos.col;
9570 #ifdef FEAT_VIRTUALEDIT
9571         coladd = pos.coladd;
9572 #endif
9573     }
9574     else
9575     {
9576         line = get_tv_lnum(argvars);
9577         col = get_tv_number_chk(&argvars[1], NULL);
9578 #ifdef FEAT_VIRTUALEDIT
9579         if (argvars[2].v_type != VAR_UNKNOWN)
9580             coladd = get_tv_number_chk(&argvars[2], NULL);
9581 #endif
9582     }
9583     if (line < 0 || col < 0
9584 #ifdef FEAT_VIRTUALEDIT
9585                             || coladd < 0
9586 #endif
9587             )
9588         return;         /* type error; errmsg already given */
9589     if (line > 0)
9590         curwin->w_cursor.lnum = line;
9591     if (col > 0)
9592         curwin->w_cursor.col = col - 1;
9593 #ifdef FEAT_VIRTUALEDIT
9594     curwin->w_cursor.coladd = coladd;
9595 #endif
9596
9597     /* Make sure the cursor is in a valid position. */
9598     check_cursor();
9599 #ifdef FEAT_MBYTE
9600     /* Correct cursor for multi-byte character. */
9601     if (has_mbyte)
9602         mb_adjust_cursor();
9603 #endif
9604
9605     curwin->w_set_curswant = TRUE;
9606     rettv->vval.v_number = 0;
9607 }
9608
9609 /*
9610  * "deepcopy()" function
9611  */
9612     static void
9613 f_deepcopy(argvars, rettv)
9614     typval_T    *argvars;
9615     typval_T    *rettv;
9616 {
9617     int         noref = 0;
9618
9619     if (argvars[1].v_type != VAR_UNKNOWN)
9620         noref = get_tv_number_chk(&argvars[1], NULL);
9621     if (noref < 0 || noref > 1)
9622         EMSG(_(e_invarg));
9623     else
9624     {
9625         current_copyID += COPYID_INC;
9626         item_copy(&argvars[0], rettv, TRUE, noref == 0 ? current_copyID : 0);
9627     }
9628 }
9629
9630 /*
9631  * "delete()" function
9632  */
9633     static void
9634 f_delete(argvars, rettv)
9635     typval_T    *argvars;
9636     typval_T    *rettv;
9637 {
9638     if (check_restricted() || check_secure())
9639         rettv->vval.v_number = -1;
9640     else
9641         rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
9642 }
9643
9644 /*
9645  * "did_filetype()" function
9646  */
9647     static void
9648 f_did_filetype(argvars, rettv)
9649     typval_T    *argvars UNUSED;
9650     typval_T    *rettv UNUSED;
9651 {
9652 #ifdef FEAT_AUTOCMD
9653     rettv->vval.v_number = did_filetype;
9654 #endif
9655 }
9656
9657 /*
9658  * "diff_filler()" function
9659  */
9660     static void
9661 f_diff_filler(argvars, rettv)
9662     typval_T    *argvars UNUSED;
9663     typval_T    *rettv UNUSED;
9664 {
9665 #ifdef FEAT_DIFF
9666     rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
9667 #endif
9668 }
9669
9670 /*
9671  * "diff_hlID()" function
9672  */
9673     static void
9674 f_diff_hlID(argvars, rettv)
9675     typval_T    *argvars UNUSED;
9676     typval_T    *rettv UNUSED;
9677 {
9678 #ifdef FEAT_DIFF
9679     linenr_T            lnum = get_tv_lnum(argvars);
9680     static linenr_T     prev_lnum = 0;
9681     static int          changedtick = 0;
9682     static int          fnum = 0;
9683     static int          change_start = 0;
9684     static int          change_end = 0;
9685     static hlf_T        hlID = (hlf_T)0;
9686     int                 filler_lines;
9687     int                 col;
9688
9689     if (lnum < 0)       /* ignore type error in {lnum} arg */
9690         lnum = 0;
9691     if (lnum != prev_lnum
9692             || changedtick != curbuf->b_changedtick
9693             || fnum != curbuf->b_fnum)
9694     {
9695         /* New line, buffer, change: need to get the values. */
9696         filler_lines = diff_check(curwin, lnum);
9697         if (filler_lines < 0)
9698         {
9699             if (filler_lines == -1)
9700             {
9701                 change_start = MAXCOL;
9702                 change_end = -1;
9703                 if (diff_find_change(curwin, lnum, &change_start, &change_end))
9704                     hlID = HLF_ADD;     /* added line */
9705                 else
9706                     hlID = HLF_CHD;     /* changed line */
9707             }
9708             else
9709                 hlID = HLF_ADD; /* added line */
9710         }
9711         else
9712             hlID = (hlf_T)0;
9713         prev_lnum = lnum;
9714         changedtick = curbuf->b_changedtick;
9715         fnum = curbuf->b_fnum;
9716     }
9717
9718     if (hlID == HLF_CHD || hlID == HLF_TXD)
9719     {
9720         col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
9721         if (col >= change_start && col <= change_end)
9722             hlID = HLF_TXD;                     /* changed text */
9723         else
9724             hlID = HLF_CHD;                     /* changed line */
9725     }
9726     rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
9727 #endif
9728 }
9729
9730 /*
9731  * "empty({expr})" function
9732  */
9733     static void
9734 f_empty(argvars, rettv)
9735     typval_T    *argvars;
9736     typval_T    *rettv;
9737 {
9738     int         n;
9739
9740     switch (argvars[0].v_type)
9741     {
9742         case VAR_STRING:
9743         case VAR_FUNC:
9744             n = argvars[0].vval.v_string == NULL
9745                                           || *argvars[0].vval.v_string == NUL;
9746             break;
9747         case VAR_NUMBER:
9748             n = argvars[0].vval.v_number == 0;
9749             break;
9750 #ifdef FEAT_FLOAT
9751         case VAR_FLOAT:
9752             n = argvars[0].vval.v_float == 0.0;
9753             break;
9754 #endif
9755         case VAR_LIST:
9756             n = argvars[0].vval.v_list == NULL
9757                                   || argvars[0].vval.v_list->lv_first == NULL;
9758             break;
9759         case VAR_DICT:
9760             n = argvars[0].vval.v_dict == NULL
9761                         || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
9762             break;
9763         default:
9764             EMSG2(_(e_intern2), "f_empty()");
9765             n = 0;
9766     }
9767
9768     rettv->vval.v_number = n;
9769 }
9770
9771 /*
9772  * "escape({string}, {chars})" function
9773  */
9774     static void
9775 f_escape(argvars, rettv)
9776     typval_T    *argvars;
9777     typval_T    *rettv;
9778 {
9779     char_u      buf[NUMBUFLEN];
9780
9781     rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
9782                                          get_tv_string_buf(&argvars[1], buf));
9783     rettv->v_type = VAR_STRING;
9784 }
9785
9786 /*
9787  * "eval()" function
9788  */
9789     static void
9790 f_eval(argvars, rettv)
9791     typval_T    *argvars;
9792     typval_T    *rettv;
9793 {
9794     char_u      *s;
9795
9796     s = get_tv_string_chk(&argvars[0]);
9797     if (s != NULL)
9798         s = skipwhite(s);
9799
9800     if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
9801     {
9802         rettv->v_type = VAR_NUMBER;
9803         rettv->vval.v_number = 0;
9804     }
9805     else if (*s != NUL)
9806         EMSG(_(e_trailing));
9807 }
9808
9809 /*
9810  * "eventhandler()" function
9811  */
9812     static void
9813 f_eventhandler(argvars, rettv)
9814     typval_T    *argvars UNUSED;
9815     typval_T    *rettv;
9816 {
9817     rettv->vval.v_number = vgetc_busy;
9818 }
9819
9820 /*
9821  * "executable()" function
9822  */
9823     static void
9824 f_executable(argvars, rettv)
9825     typval_T    *argvars;
9826     typval_T    *rettv;
9827 {
9828     rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
9829 }
9830
9831 /*
9832  * "exists()" function
9833  */
9834     static void
9835 f_exists(argvars, rettv)
9836     typval_T    *argvars;
9837     typval_T    *rettv;
9838 {
9839     char_u      *p;
9840     char_u      *name;
9841     int         n = FALSE;
9842     int         len = 0;
9843
9844     no_autoload = TRUE;
9845
9846     p = get_tv_string(&argvars[0]);
9847     if (*p == '$')                      /* environment variable */
9848     {
9849         /* first try "normal" environment variables (fast) */
9850         if (mch_getenv(p + 1) != NULL)
9851             n = TRUE;
9852         else
9853         {
9854             /* try expanding things like $VIM and ${HOME} */
9855             p = expand_env_save(p);
9856             if (p != NULL && *p != '$')
9857                 n = TRUE;
9858             vim_free(p);
9859         }
9860     }
9861     else if (*p == '&' || *p == '+')                    /* option */
9862     {
9863         n = (get_option_tv(&p, NULL, TRUE) == OK);
9864         if (*skipwhite(p) != NUL)
9865             n = FALSE;                  /* trailing garbage */
9866     }
9867     else if (*p == '*')                 /* internal or user defined function */
9868     {
9869         n = function_exists(p + 1);
9870     }
9871     else if (*p == ':')
9872     {
9873         n = cmd_exists(p + 1);
9874     }
9875     else if (*p == '#')
9876     {
9877 #ifdef FEAT_AUTOCMD
9878         if (p[1] == '#')
9879             n = autocmd_supported(p + 2);
9880         else
9881             n = au_exists(p + 1);
9882 #endif
9883     }
9884     else                                /* internal variable */
9885     {
9886         char_u      *tofree;
9887         typval_T    tv;
9888
9889         /* get_name_len() takes care of expanding curly braces */
9890         name = p;
9891         len = get_name_len(&p, &tofree, TRUE, FALSE);
9892         if (len > 0)
9893         {
9894             if (tofree != NULL)
9895                 name = tofree;
9896             n = (get_var_tv(name, len, &tv, FALSE) == OK);
9897             if (n)
9898             {
9899                 /* handle d.key, l[idx], f(expr) */
9900                 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
9901                 if (n)
9902                     clear_tv(&tv);
9903             }
9904         }
9905         if (*p != NUL)
9906             n = FALSE;
9907
9908         vim_free(tofree);
9909     }
9910
9911     rettv->vval.v_number = n;
9912
9913     no_autoload = FALSE;
9914 }
9915
9916 #ifdef FEAT_FLOAT
9917 /*
9918  * "exp()" function
9919  */
9920     static void
9921 f_exp(argvars, rettv)
9922     typval_T    *argvars;
9923     typval_T    *rettv;
9924 {
9925     float_T     f;
9926
9927     rettv->v_type = VAR_FLOAT;
9928     if (get_float_arg(argvars, &f) == OK)
9929         rettv->vval.v_float = exp(f);
9930     else
9931         rettv->vval.v_float = 0.0;
9932 }
9933 #endif
9934
9935 /*
9936  * "expand()" function
9937  */
9938     static void
9939 f_expand(argvars, rettv)
9940     typval_T    *argvars;
9941     typval_T    *rettv;
9942 {
9943     char_u      *s;
9944     int         len;
9945     char_u      *errormsg;
9946     int         options = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
9947     expand_T    xpc;
9948     int         error = FALSE;
9949
9950     rettv->v_type = VAR_STRING;
9951     s = get_tv_string(&argvars[0]);
9952     if (*s == '%' || *s == '#' || *s == '<')
9953     {
9954         ++emsg_off;
9955         rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
9956         --emsg_off;
9957     }
9958     else
9959     {
9960         /* When the optional second argument is non-zero, don't remove matches
9961          * for 'wildignore' and don't put matches for 'suffixes' at the end. */
9962         if (argvars[1].v_type != VAR_UNKNOWN
9963                                     && get_tv_number_chk(&argvars[1], &error))
9964             options |= WILD_KEEP_ALL;
9965         if (!error)
9966         {
9967             ExpandInit(&xpc);
9968             xpc.xp_context = EXPAND_FILES;
9969             if (p_wic)
9970                 options += WILD_ICASE;
9971             rettv->vval.v_string = ExpandOne(&xpc, s, NULL, options, WILD_ALL);
9972         }
9973         else
9974             rettv->vval.v_string = NULL;
9975     }
9976 }
9977
9978 /*
9979  * "extend(list, list [, idx])" function
9980  * "extend(dict, dict [, action])" function
9981  */
9982     static void
9983 f_extend(argvars, rettv)
9984     typval_T    *argvars;
9985     typval_T    *rettv;
9986 {
9987     char      *arg_errmsg = N_("extend() argument");
9988
9989     if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9990     {
9991         list_T          *l1, *l2;
9992         listitem_T      *item;
9993         long            before;
9994         int             error = FALSE;
9995
9996         l1 = argvars[0].vval.v_list;
9997         l2 = argvars[1].vval.v_list;
9998         if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)_(arg_errmsg))
9999                 && l2 != NULL)
10000         {
10001             if (argvars[2].v_type != VAR_UNKNOWN)
10002             {
10003                 before = get_tv_number_chk(&argvars[2], &error);
10004                 if (error)
10005                     return;             /* type error; errmsg already given */
10006
10007                 if (before == l1->lv_len)
10008                     item = NULL;
10009                 else
10010                 {
10011                     item = list_find(l1, before);
10012                     if (item == NULL)
10013                     {
10014                         EMSGN(_(e_listidx), before);
10015                         return;
10016                     }
10017                 }
10018             }
10019             else
10020                 item = NULL;
10021             list_extend(l1, l2, item);
10022
10023             copy_tv(&argvars[0], rettv);
10024         }
10025     }
10026     else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
10027     {
10028         dict_T          *d1, *d2;
10029         dictitem_T      *di1;
10030         char_u          *action;
10031         int             i;
10032         hashitem_T      *hi2;
10033         int             todo;
10034
10035         d1 = argvars[0].vval.v_dict;
10036         d2 = argvars[1].vval.v_dict;
10037         if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)_(arg_errmsg))
10038                 && d2 != NULL)
10039         {
10040             /* Check the third argument. */
10041             if (argvars[2].v_type != VAR_UNKNOWN)
10042             {
10043                 static char *(av[]) = {"keep", "force", "error"};
10044
10045                 action = get_tv_string_chk(&argvars[2]);
10046                 if (action == NULL)
10047                     return;             /* type error; errmsg already given */
10048                 for (i = 0; i < 3; ++i)
10049                     if (STRCMP(action, av[i]) == 0)
10050                         break;
10051                 if (i == 3)
10052                 {
10053                     EMSG2(_(e_invarg2), action);
10054                     return;
10055                 }
10056             }
10057             else
10058                 action = (char_u *)"force";
10059
10060             /* Go over all entries in the second dict and add them to the
10061              * first dict. */
10062             todo = (int)d2->dv_hashtab.ht_used;
10063             for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
10064             {
10065                 if (!HASHITEM_EMPTY(hi2))
10066                 {
10067                     --todo;
10068                     di1 = dict_find(d1, hi2->hi_key, -1);
10069                     if (di1 == NULL)
10070                     {
10071                         di1 = dictitem_copy(HI2DI(hi2));
10072                         if (di1 != NULL && dict_add(d1, di1) == FAIL)
10073                             dictitem_free(di1);
10074                     }
10075                     else if (*action == 'e')
10076                     {
10077                         EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
10078                         break;
10079                     }
10080                     else if (*action == 'f')
10081                     {
10082                         clear_tv(&di1->di_tv);
10083                         copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
10084                     }
10085                 }
10086             }
10087
10088             copy_tv(&argvars[0], rettv);
10089         }
10090     }
10091     else
10092         EMSG2(_(e_listdictarg), "extend()");
10093 }
10094
10095 /*
10096  * "feedkeys()" function
10097  */
10098     static void
10099 f_feedkeys(argvars, rettv)
10100     typval_T    *argvars;
10101     typval_T    *rettv UNUSED;
10102 {
10103     int         remap = TRUE;
10104     char_u      *keys, *flags;
10105     char_u      nbuf[NUMBUFLEN];
10106     int         typed = FALSE;
10107     char_u      *keys_esc;
10108
10109     /* This is not allowed in the sandbox.  If the commands would still be
10110      * executed in the sandbox it would be OK, but it probably happens later,
10111      * when "sandbox" is no longer set. */
10112     if (check_secure())
10113         return;
10114
10115     keys = get_tv_string(&argvars[0]);
10116     if (*keys != NUL)
10117     {
10118         if (argvars[1].v_type != VAR_UNKNOWN)
10119         {
10120             flags = get_tv_string_buf(&argvars[1], nbuf);
10121             for ( ; *flags != NUL; ++flags)
10122             {
10123                 switch (*flags)
10124                 {
10125                     case 'n': remap = FALSE; break;
10126                     case 'm': remap = TRUE; break;
10127                     case 't': typed = TRUE; break;
10128                 }
10129             }
10130         }
10131
10132         /* Need to escape K_SPECIAL and CSI before putting the string in the
10133          * typeahead buffer. */
10134         keys_esc = vim_strsave_escape_csi(keys);
10135         if (keys_esc != NULL)
10136         {
10137             ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
10138                                                typebuf.tb_len, !typed, FALSE);
10139             vim_free(keys_esc);
10140             if (vgetc_busy)
10141                 typebuf_was_filled = TRUE;
10142         }
10143     }
10144 }
10145
10146 /*
10147  * "filereadable()" function
10148  */
10149     static void
10150 f_filereadable(argvars, rettv)
10151     typval_T    *argvars;
10152     typval_T    *rettv;
10153 {
10154     int         fd;
10155     char_u      *p;
10156     int         n;
10157
10158 #ifndef O_NONBLOCK
10159 # define O_NONBLOCK 0
10160 #endif
10161     p = get_tv_string(&argvars[0]);
10162     if (*p && !mch_isdir(p) && (fd = mch_open((char *)p,
10163                                               O_RDONLY | O_NONBLOCK, 0)) >= 0)
10164     {
10165         n = TRUE;
10166         close(fd);
10167     }
10168     else
10169         n = FALSE;
10170
10171     rettv->vval.v_number = n;
10172 }
10173
10174 /*
10175  * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
10176  * rights to write into.
10177  */
10178     static void
10179 f_filewritable(argvars, rettv)
10180     typval_T    *argvars;
10181     typval_T    *rettv;
10182 {
10183     rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
10184 }
10185
10186 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
10187
10188     static void
10189 findfilendir(argvars, rettv, find_what)
10190     typval_T    *argvars;
10191     typval_T    *rettv;
10192     int         find_what;
10193 {
10194 #ifdef FEAT_SEARCHPATH
10195     char_u      *fname;
10196     char_u      *fresult = NULL;
10197     char_u      *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
10198     char_u      *p;
10199     char_u      pathbuf[NUMBUFLEN];
10200     int         count = 1;
10201     int         first = TRUE;
10202     int         error = FALSE;
10203 #endif
10204
10205     rettv->vval.v_string = NULL;
10206     rettv->v_type = VAR_STRING;
10207
10208 #ifdef FEAT_SEARCHPATH
10209     fname = get_tv_string(&argvars[0]);
10210
10211     if (argvars[1].v_type != VAR_UNKNOWN)
10212     {
10213         p = get_tv_string_buf_chk(&argvars[1], pathbuf);
10214         if (p == NULL)
10215             error = TRUE;
10216         else
10217         {
10218             if (*p != NUL)
10219                 path = p;
10220
10221             if (argvars[2].v_type != VAR_UNKNOWN)
10222                 count = get_tv_number_chk(&argvars[2], &error);
10223         }
10224     }
10225
10226     if (count < 0 && rettv_list_alloc(rettv) == FAIL)
10227         error = TRUE;
10228
10229     if (*fname != NUL && !error)
10230     {
10231         do
10232         {
10233             if (rettv->v_type == VAR_STRING)
10234                 vim_free(fresult);
10235             fresult = find_file_in_path_option(first ? fname : NULL,
10236                                                first ? (int)STRLEN(fname) : 0,
10237                                         0, first, path,
10238                                         find_what,
10239                                         curbuf->b_ffname,
10240                                         find_what == FINDFILE_DIR
10241                                             ? (char_u *)"" : curbuf->b_p_sua);
10242             first = FALSE;
10243
10244             if (fresult != NULL && rettv->v_type == VAR_LIST)
10245                 list_append_string(rettv->vval.v_list, fresult, -1);
10246
10247         } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
10248     }
10249
10250     if (rettv->v_type == VAR_STRING)
10251         rettv->vval.v_string = fresult;
10252 #endif
10253 }
10254
10255 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
10256 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
10257
10258 /*
10259  * Implementation of map() and filter().
10260  */
10261     static void
10262 filter_map(argvars, rettv, map)
10263     typval_T    *argvars;
10264     typval_T    *rettv;
10265     int         map;
10266 {
10267     char_u      buf[NUMBUFLEN];
10268     char_u      *expr;
10269     listitem_T  *li, *nli;
10270     list_T      *l = NULL;
10271     dictitem_T  *di;
10272     hashtab_T   *ht;
10273     hashitem_T  *hi;
10274     dict_T      *d = NULL;
10275     typval_T    save_val;
10276     typval_T    save_key;
10277     int         rem;
10278     int         todo;
10279     char_u      *ermsg = (char_u *)(map ? "map()" : "filter()");
10280     char        *arg_errmsg = (map ? N_("map() argument")
10281                                    : N_("filter() argument"));
10282     int         save_did_emsg;
10283     int         idx = 0;
10284
10285     if (argvars[0].v_type == VAR_LIST)
10286     {
10287         if ((l = argvars[0].vval.v_list) == NULL
10288                 || tv_check_lock(l->lv_lock, (char_u *)_(arg_errmsg)))
10289             return;
10290     }
10291     else if (argvars[0].v_type == VAR_DICT)
10292     {
10293         if ((d = argvars[0].vval.v_dict) == NULL
10294                 || tv_check_lock(d->dv_lock, (char_u *)_(arg_errmsg)))
10295             return;
10296     }
10297     else
10298     {
10299         EMSG2(_(e_listdictarg), ermsg);
10300         return;
10301     }
10302
10303     expr = get_tv_string_buf_chk(&argvars[1], buf);
10304     /* On type errors, the preceding call has already displayed an error
10305      * message.  Avoid a misleading error message for an empty string that
10306      * was not passed as argument. */
10307     if (expr != NULL)
10308     {
10309         prepare_vimvar(VV_VAL, &save_val);
10310         expr = skipwhite(expr);
10311
10312         /* We reset "did_emsg" to be able to detect whether an error
10313          * occurred during evaluation of the expression. */
10314         save_did_emsg = did_emsg;
10315         did_emsg = FALSE;
10316
10317         prepare_vimvar(VV_KEY, &save_key);
10318         if (argvars[0].v_type == VAR_DICT)
10319         {
10320             vimvars[VV_KEY].vv_type = VAR_STRING;
10321
10322             ht = &d->dv_hashtab;
10323             hash_lock(ht);
10324             todo = (int)ht->ht_used;
10325             for (hi = ht->ht_array; todo > 0; ++hi)
10326             {
10327                 if (!HASHITEM_EMPTY(hi))
10328                 {
10329                     --todo;
10330                     di = HI2DI(hi);
10331                     if (tv_check_lock(di->di_tv.v_lock,
10332                                                      (char_u *)_(arg_errmsg)))
10333                         break;
10334                     vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
10335                     if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
10336                                                                   || did_emsg)
10337                         break;
10338                     if (!map && rem)
10339                         dictitem_remove(d, di);
10340                     clear_tv(&vimvars[VV_KEY].vv_tv);
10341                 }
10342             }
10343             hash_unlock(ht);
10344         }
10345         else
10346         {
10347             vimvars[VV_KEY].vv_type = VAR_NUMBER;
10348
10349             for (li = l->lv_first; li != NULL; li = nli)
10350             {
10351                 if (tv_check_lock(li->li_tv.v_lock, (char_u *)_(arg_errmsg)))
10352                     break;
10353                 nli = li->li_next;
10354                 vimvars[VV_KEY].vv_nr = idx;
10355                 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
10356                                                                   || did_emsg)
10357                     break;
10358                 if (!map && rem)
10359                     listitem_remove(l, li);
10360                 ++idx;
10361             }
10362         }
10363
10364         restore_vimvar(VV_KEY, &save_key);
10365         restore_vimvar(VV_VAL, &save_val);
10366
10367         did_emsg |= save_did_emsg;
10368     }
10369
10370     copy_tv(&argvars[0], rettv);
10371 }
10372
10373     static int
10374 filter_map_one(tv, expr, map, remp)
10375     typval_T    *tv;
10376     char_u      *expr;
10377     int         map;
10378     int         *remp;
10379 {
10380     typval_T    rettv;
10381     char_u      *s;
10382     int         retval = FAIL;
10383
10384     copy_tv(tv, &vimvars[VV_VAL].vv_tv);
10385     s = expr;
10386     if (eval1(&s, &rettv, TRUE) == FAIL)
10387         goto theend;
10388     if (*s != NUL)  /* check for trailing chars after expr */
10389     {
10390         EMSG2(_(e_invexpr2), s);
10391         goto theend;
10392     }
10393     if (map)
10394     {
10395         /* map(): replace the list item value */
10396         clear_tv(tv);
10397         rettv.v_lock = 0;
10398         *tv = rettv;
10399     }
10400     else
10401     {
10402         int         error = FALSE;
10403
10404         /* filter(): when expr is zero remove the item */
10405         *remp = (get_tv_number_chk(&rettv, &error) == 0);
10406         clear_tv(&rettv);
10407         /* On type error, nothing has been removed; return FAIL to stop the
10408          * loop.  The error message was given by get_tv_number_chk(). */
10409         if (error)
10410             goto theend;
10411     }
10412     retval = OK;
10413 theend:
10414     clear_tv(&vimvars[VV_VAL].vv_tv);
10415     return retval;
10416 }
10417
10418 /*
10419  * "filter()" function
10420  */
10421     static void
10422 f_filter(argvars, rettv)
10423     typval_T    *argvars;
10424     typval_T    *rettv;
10425 {
10426     filter_map(argvars, rettv, FALSE);
10427 }
10428
10429 /*
10430  * "finddir({fname}[, {path}[, {count}]])" function
10431  */
10432     static void
10433 f_finddir(argvars, rettv)
10434     typval_T    *argvars;
10435     typval_T    *rettv;
10436 {
10437     findfilendir(argvars, rettv, FINDFILE_DIR);
10438 }
10439
10440 /*
10441  * "findfile({fname}[, {path}[, {count}]])" function
10442  */
10443     static void
10444 f_findfile(argvars, rettv)
10445     typval_T    *argvars;
10446     typval_T    *rettv;
10447 {
10448     findfilendir(argvars, rettv, FINDFILE_FILE);
10449 }
10450
10451 #ifdef FEAT_FLOAT
10452 /*
10453  * "float2nr({float})" function
10454  */
10455     static void
10456 f_float2nr(argvars, rettv)
10457     typval_T    *argvars;
10458     typval_T    *rettv;
10459 {
10460     float_T     f;
10461
10462     if (get_float_arg(argvars, &f) == OK)
10463     {
10464         if (f < -0x7fffffff)
10465             rettv->vval.v_number = -0x7fffffff;
10466         else if (f > 0x7fffffff)
10467             rettv->vval.v_number = 0x7fffffff;
10468         else
10469             rettv->vval.v_number = (varnumber_T)f;
10470     }
10471 }
10472
10473 /*
10474  * "floor({float})" function
10475  */
10476     static void
10477 f_floor(argvars, rettv)
10478     typval_T    *argvars;
10479     typval_T    *rettv;
10480 {
10481     float_T     f;
10482
10483     rettv->v_type = VAR_FLOAT;
10484     if (get_float_arg(argvars, &f) == OK)
10485         rettv->vval.v_float = floor(f);
10486     else
10487         rettv->vval.v_float = 0.0;
10488 }
10489
10490 /*
10491  * "fmod()" function
10492  */
10493     static void
10494 f_fmod(argvars, rettv)
10495     typval_T    *argvars;
10496     typval_T    *rettv;
10497 {
10498     float_T     fx, fy;
10499
10500     rettv->v_type = VAR_FLOAT;
10501     if (get_float_arg(argvars, &fx) == OK
10502                                      && get_float_arg(&argvars[1], &fy) == OK)
10503         rettv->vval.v_float = fmod(fx, fy);
10504     else
10505         rettv->vval.v_float = 0.0;
10506 }
10507 #endif
10508
10509 /*
10510  * "fnameescape({string})" function
10511  */
10512     static void
10513 f_fnameescape(argvars, rettv)
10514     typval_T    *argvars;
10515     typval_T    *rettv;
10516 {
10517     rettv->vval.v_string = vim_strsave_fnameescape(
10518                                            get_tv_string(&argvars[0]), FALSE);
10519     rettv->v_type = VAR_STRING;
10520 }
10521
10522 /*
10523  * "fnamemodify({fname}, {mods})" function
10524  */
10525     static void
10526 f_fnamemodify(argvars, rettv)
10527     typval_T    *argvars;
10528     typval_T    *rettv;
10529 {
10530     char_u      *fname;
10531     char_u      *mods;
10532     int         usedlen = 0;
10533     int         len;
10534     char_u      *fbuf = NULL;
10535     char_u      buf[NUMBUFLEN];
10536
10537     fname = get_tv_string_chk(&argvars[0]);
10538     mods = get_tv_string_buf_chk(&argvars[1], buf);
10539     if (fname == NULL || mods == NULL)
10540         fname = NULL;
10541     else
10542     {
10543         len = (int)STRLEN(fname);
10544         (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
10545     }
10546
10547     rettv->v_type = VAR_STRING;
10548     if (fname == NULL)
10549         rettv->vval.v_string = NULL;
10550     else
10551         rettv->vval.v_string = vim_strnsave(fname, len);
10552     vim_free(fbuf);
10553 }
10554
10555 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
10556
10557 /*
10558  * "foldclosed()" function
10559  */
10560     static void
10561 foldclosed_both(argvars, rettv, end)
10562     typval_T    *argvars;
10563     typval_T    *rettv;
10564     int         end;
10565 {
10566 #ifdef FEAT_FOLDING
10567     linenr_T    lnum;
10568     linenr_T    first, last;
10569
10570     lnum = get_tv_lnum(argvars);
10571     if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10572     {
10573         if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
10574         {
10575             if (end)
10576                 rettv->vval.v_number = (varnumber_T)last;
10577             else
10578                 rettv->vval.v_number = (varnumber_T)first;
10579             return;
10580         }
10581     }
10582 #endif
10583     rettv->vval.v_number = -1;
10584 }
10585
10586 /*
10587  * "foldclosed()" function
10588  */
10589     static void
10590 f_foldclosed(argvars, rettv)
10591     typval_T    *argvars;
10592     typval_T    *rettv;
10593 {
10594     foldclosed_both(argvars, rettv, FALSE);
10595 }
10596
10597 /*
10598  * "foldclosedend()" function
10599  */
10600     static void
10601 f_foldclosedend(argvars, rettv)
10602     typval_T    *argvars;
10603     typval_T    *rettv;
10604 {
10605     foldclosed_both(argvars, rettv, TRUE);
10606 }
10607
10608 /*
10609  * "foldlevel()" function
10610  */
10611     static void
10612 f_foldlevel(argvars, rettv)
10613     typval_T    *argvars;
10614     typval_T    *rettv;
10615 {
10616 #ifdef FEAT_FOLDING
10617     linenr_T    lnum;
10618
10619     lnum = get_tv_lnum(argvars);
10620     if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10621         rettv->vval.v_number = foldLevel(lnum);
10622 #endif
10623 }
10624
10625 /*
10626  * "foldtext()" function
10627  */
10628     static void
10629 f_foldtext(argvars, rettv)
10630     typval_T    *argvars UNUSED;
10631     typval_T    *rettv;
10632 {
10633 #ifdef FEAT_FOLDING
10634     linenr_T    lnum;
10635     char_u      *s;
10636     char_u      *r;
10637     int         len;
10638     char        *txt;
10639 #endif
10640
10641     rettv->v_type = VAR_STRING;
10642     rettv->vval.v_string = NULL;
10643 #ifdef FEAT_FOLDING
10644     if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
10645             && (linenr_T)vimvars[VV_FOLDEND].vv_nr
10646                                                  <= curbuf->b_ml.ml_line_count
10647             && vimvars[VV_FOLDDASHES].vv_str != NULL)
10648     {
10649         /* Find first non-empty line in the fold. */
10650         lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
10651         while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10652         {
10653             if (!linewhite(lnum))
10654                 break;
10655             ++lnum;
10656         }
10657
10658         /* Find interesting text in this line. */
10659         s = skipwhite(ml_get(lnum));
10660         /* skip C comment-start */
10661         if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
10662         {
10663             s = skipwhite(s + 2);
10664             if (*skipwhite(s) == NUL
10665                             && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10666             {
10667                 s = skipwhite(ml_get(lnum + 1));
10668                 if (*s == '*')
10669                     s = skipwhite(s + 1);
10670             }
10671         }
10672         txt = _("+-%s%3ld lines: ");
10673         r = alloc((unsigned)(STRLEN(txt)
10674                     + STRLEN(vimvars[VV_FOLDDASHES].vv_str)    /* for %s */
10675                     + 20                                    /* for %3ld */
10676                     + STRLEN(s)));                          /* concatenated */
10677         if (r != NULL)
10678         {
10679             sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
10680                     (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
10681                                 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
10682             len = (int)STRLEN(r);
10683             STRCAT(r, s);
10684             /* remove 'foldmarker' and 'commentstring' */
10685             foldtext_cleanup(r + len);
10686             rettv->vval.v_string = r;
10687         }
10688     }
10689 #endif
10690 }
10691
10692 /*
10693  * "foldtextresult(lnum)" function
10694  */
10695     static void
10696 f_foldtextresult(argvars, rettv)
10697     typval_T    *argvars UNUSED;
10698     typval_T    *rettv;
10699 {
10700 #ifdef FEAT_FOLDING
10701     linenr_T    lnum;
10702     char_u      *text;
10703     char_u      buf[51];
10704     foldinfo_T  foldinfo;
10705     int         fold_count;
10706 #endif
10707
10708     rettv->v_type = VAR_STRING;
10709     rettv->vval.v_string = NULL;
10710 #ifdef FEAT_FOLDING
10711     lnum = get_tv_lnum(argvars);
10712     /* treat illegal types and illegal string values for {lnum} the same */
10713     if (lnum < 0)
10714         lnum = 0;
10715     fold_count = foldedCount(curwin, lnum, &foldinfo);
10716     if (fold_count > 0)
10717     {
10718         text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
10719                                                               &foldinfo, buf);
10720         if (text == buf)
10721             text = vim_strsave(text);
10722         rettv->vval.v_string = text;
10723     }
10724 #endif
10725 }
10726
10727 /*
10728  * "foreground()" function
10729  */
10730     static void
10731 f_foreground(argvars, rettv)
10732     typval_T    *argvars UNUSED;
10733     typval_T    *rettv UNUSED;
10734 {
10735 #ifdef FEAT_GUI
10736     if (gui.in_use)
10737         gui_mch_set_foreground();
10738 #else
10739 # ifdef WIN32
10740     win32_set_foreground();
10741 # endif
10742 #endif
10743 }
10744
10745 /*
10746  * "function()" function
10747  */
10748     static void
10749 f_function(argvars, rettv)
10750     typval_T    *argvars;
10751     typval_T    *rettv;
10752 {
10753     char_u      *s;
10754
10755     s = get_tv_string(&argvars[0]);
10756     if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
10757         EMSG2(_(e_invarg2), s);
10758     /* Don't check an autoload name for existence here. */
10759     else if (vim_strchr(s, AUTOLOAD_CHAR) == NULL && !function_exists(s))
10760         EMSG2(_("E700: Unknown function: %s"), s);
10761     else
10762     {
10763         rettv->vval.v_string = vim_strsave(s);
10764         rettv->v_type = VAR_FUNC;
10765     }
10766 }
10767
10768 /*
10769  * "garbagecollect()" function
10770  */
10771     static void
10772 f_garbagecollect(argvars, rettv)
10773     typval_T    *argvars;
10774     typval_T    *rettv UNUSED;
10775 {
10776     /* This is postponed until we are back at the toplevel, because we may be
10777      * using Lists and Dicts internally.  E.g.: ":echo [garbagecollect()]". */
10778     want_garbage_collect = TRUE;
10779
10780     if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
10781         garbage_collect_at_exit = TRUE;
10782 }
10783
10784 /*
10785  * "get()" function
10786  */
10787     static void
10788 f_get(argvars, rettv)
10789     typval_T    *argvars;
10790     typval_T    *rettv;
10791 {
10792     listitem_T  *li;
10793     list_T      *l;
10794     dictitem_T  *di;
10795     dict_T      *d;
10796     typval_T    *tv = NULL;
10797
10798     if (argvars[0].v_type == VAR_LIST)
10799     {
10800         if ((l = argvars[0].vval.v_list) != NULL)
10801         {
10802             int         error = FALSE;
10803
10804             li = list_find(l, get_tv_number_chk(&argvars[1], &error));
10805             if (!error && li != NULL)
10806                 tv = &li->li_tv;
10807         }
10808     }
10809     else if (argvars[0].v_type == VAR_DICT)
10810     {
10811         if ((d = argvars[0].vval.v_dict) != NULL)
10812         {
10813             di = dict_find(d, get_tv_string(&argvars[1]), -1);
10814             if (di != NULL)
10815                 tv = &di->di_tv;
10816         }
10817     }
10818     else
10819         EMSG2(_(e_listdictarg), "get()");
10820
10821     if (tv == NULL)
10822     {
10823         if (argvars[2].v_type != VAR_UNKNOWN)
10824             copy_tv(&argvars[2], rettv);
10825     }
10826     else
10827         copy_tv(tv, rettv);
10828 }
10829
10830 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
10831
10832 /*
10833  * Get line or list of lines from buffer "buf" into "rettv".
10834  * Return a range (from start to end) of lines in rettv from the specified
10835  * buffer.
10836  * If 'retlist' is TRUE, then the lines are returned as a Vim List.
10837  */
10838     static void
10839 get_buffer_lines(buf, start, end, retlist, rettv)
10840     buf_T       *buf;
10841     linenr_T    start;
10842     linenr_T    end;
10843     int         retlist;
10844     typval_T    *rettv;
10845 {
10846     char_u      *p;
10847
10848     if (retlist && rettv_list_alloc(rettv) == FAIL)
10849         return;
10850
10851     if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
10852         return;
10853
10854     if (!retlist)
10855     {
10856         if (start >= 1 && start <= buf->b_ml.ml_line_count)
10857             p = ml_get_buf(buf, start, FALSE);
10858         else
10859             p = (char_u *)"";
10860
10861         rettv->v_type = VAR_STRING;
10862         rettv->vval.v_string = vim_strsave(p);
10863     }
10864     else
10865     {
10866         if (end < start)
10867             return;
10868
10869         if (start < 1)
10870             start = 1;
10871         if (end > buf->b_ml.ml_line_count)
10872             end = buf->b_ml.ml_line_count;
10873         while (start <= end)
10874             if (list_append_string(rettv->vval.v_list,
10875                                  ml_get_buf(buf, start++, FALSE), -1) == FAIL)
10876                 break;
10877     }
10878 }
10879
10880 /*
10881  * "getbufline()" function
10882  */
10883     static void
10884 f_getbufline(argvars, rettv)
10885     typval_T    *argvars;
10886     typval_T    *rettv;
10887 {
10888     linenr_T    lnum;
10889     linenr_T    end;
10890     buf_T       *buf;
10891
10892     (void)get_tv_number(&argvars[0]);       /* issue errmsg if type error */
10893     ++emsg_off;
10894     buf = get_buf_tv(&argvars[0]);
10895     --emsg_off;
10896
10897     lnum = get_tv_lnum_buf(&argvars[1], buf);
10898     if (argvars[2].v_type == VAR_UNKNOWN)
10899         end = lnum;
10900     else
10901         end = get_tv_lnum_buf(&argvars[2], buf);
10902
10903     get_buffer_lines(buf, lnum, end, TRUE, rettv);
10904 }
10905
10906 /*
10907  * "getbufvar()" function
10908  */
10909     static void
10910 f_getbufvar(argvars, rettv)
10911     typval_T    *argvars;
10912     typval_T    *rettv;
10913 {
10914     buf_T       *buf;
10915     buf_T       *save_curbuf;
10916     char_u      *varname;
10917     dictitem_T  *v;
10918
10919     (void)get_tv_number(&argvars[0]);       /* issue errmsg if type error */
10920     varname = get_tv_string_chk(&argvars[1]);
10921     ++emsg_off;
10922     buf = get_buf_tv(&argvars[0]);
10923
10924     rettv->v_type = VAR_STRING;
10925     rettv->vval.v_string = NULL;
10926
10927     if (buf != NULL && varname != NULL)
10928     {
10929         /* set curbuf to be our buf, temporarily */
10930         save_curbuf = curbuf;
10931         curbuf = buf;
10932
10933         if (*varname == '&')    /* buffer-local-option */
10934             get_option_tv(&varname, rettv, TRUE);
10935         else if (STRCMP(varname, "changedtick") == 0)
10936         {
10937             rettv->v_type = VAR_NUMBER;
10938             rettv->vval.v_number = curbuf->b_changedtick;
10939         }
10940         else
10941         {
10942             if (*varname == NUL)
10943                 /* let getbufvar({nr}, "") return the "b:" dictionary.  The
10944                  * scope prefix before the NUL byte is required by
10945                  * find_var_in_ht(). */
10946                 varname = (char_u *)"b:" + 2;
10947             /* look up the variable */
10948             v = find_var_in_ht(&curbuf->b_vars.dv_hashtab, varname, FALSE);
10949             if (v != NULL)
10950                 copy_tv(&v->di_tv, rettv);
10951         }
10952
10953         /* restore previous notion of curbuf */
10954         curbuf = save_curbuf;
10955     }
10956
10957     --emsg_off;
10958 }
10959
10960 /*
10961  * "getchar()" function
10962  */
10963     static void
10964 f_getchar(argvars, rettv)
10965     typval_T    *argvars;
10966     typval_T    *rettv;
10967 {
10968     varnumber_T         n;
10969     int                 error = FALSE;
10970
10971     /* Position the cursor.  Needed after a message that ends in a space. */
10972     windgoto(msg_row, msg_col);
10973
10974     ++no_mapping;
10975     ++allow_keys;
10976     for (;;)
10977     {
10978         if (argvars[0].v_type == VAR_UNKNOWN)
10979             /* getchar(): blocking wait. */
10980             n = safe_vgetc();
10981         else if (get_tv_number_chk(&argvars[0], &error) == 1)
10982             /* getchar(1): only check if char avail */
10983             n = vpeekc();
10984         else if (error || vpeekc() == NUL)
10985             /* illegal argument or getchar(0) and no char avail: return zero */
10986             n = 0;
10987         else
10988             /* getchar(0) and char avail: return char */
10989             n = safe_vgetc();
10990         if (n == K_IGNORE)
10991             continue;
10992         break;
10993     }
10994     --no_mapping;
10995     --allow_keys;
10996
10997     vimvars[VV_MOUSE_WIN].vv_nr = 0;
10998     vimvars[VV_MOUSE_LNUM].vv_nr = 0;
10999     vimvars[VV_MOUSE_COL].vv_nr = 0;
11000
11001     rettv->vval.v_number = n;
11002     if (IS_SPECIAL(n) || mod_mask != 0)
11003     {
11004         char_u          temp[10];   /* modifier: 3, mbyte-char: 6, NUL: 1 */
11005         int             i = 0;
11006
11007         /* Turn a special key into three bytes, plus modifier. */
11008         if (mod_mask != 0)
11009         {
11010             temp[i++] = K_SPECIAL;
11011             temp[i++] = KS_MODIFIER;
11012             temp[i++] = mod_mask;
11013         }
11014         if (IS_SPECIAL(n))
11015         {
11016             temp[i++] = K_SPECIAL;
11017             temp[i++] = K_SECOND(n);
11018             temp[i++] = K_THIRD(n);
11019         }
11020 #ifdef FEAT_MBYTE
11021         else if (has_mbyte)
11022             i += (*mb_char2bytes)(n, temp + i);
11023 #endif
11024         else
11025             temp[i++] = n;
11026         temp[i++] = NUL;
11027         rettv->v_type = VAR_STRING;
11028         rettv->vval.v_string = vim_strsave(temp);
11029
11030 #ifdef FEAT_MOUSE
11031         if (n == K_LEFTMOUSE
11032                 || n == K_LEFTMOUSE_NM
11033                 || n == K_LEFTDRAG
11034                 || n == K_LEFTRELEASE
11035                 || n == K_LEFTRELEASE_NM
11036                 || n == K_MIDDLEMOUSE
11037                 || n == K_MIDDLEDRAG
11038                 || n == K_MIDDLERELEASE
11039                 || n == K_RIGHTMOUSE
11040                 || n == K_RIGHTDRAG
11041                 || n == K_RIGHTRELEASE
11042                 || n == K_X1MOUSE
11043                 || n == K_X1DRAG
11044                 || n == K_X1RELEASE
11045                 || n == K_X2MOUSE
11046                 || n == K_X2DRAG
11047                 || n == K_X2RELEASE
11048                 || n == K_MOUSELEFT
11049                 || n == K_MOUSERIGHT
11050                 || n == K_MOUSEDOWN
11051                 || n == K_MOUSEUP)
11052         {
11053             int         row = mouse_row;
11054             int         col = mouse_col;
11055             win_T       *win;
11056             linenr_T    lnum;
11057 # ifdef FEAT_WINDOWS
11058             win_T       *wp;
11059 # endif
11060             int         winnr = 1;
11061
11062             if (row >= 0 && col >= 0)
11063             {
11064                 /* Find the window at the mouse coordinates and compute the
11065                  * text position. */
11066                 win = mouse_find_win(&row, &col);
11067                 (void)mouse_comp_pos(win, &row, &col, &lnum);
11068 # ifdef FEAT_WINDOWS
11069                 for (wp = firstwin; wp != win; wp = wp->w_next)
11070                     ++winnr;
11071 # endif
11072                 vimvars[VV_MOUSE_WIN].vv_nr = winnr;
11073                 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
11074                 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
11075             }
11076         }
11077 #endif
11078     }
11079 }
11080
11081 /*
11082  * "getcharmod()" function
11083  */
11084     static void
11085 f_getcharmod(argvars, rettv)
11086     typval_T    *argvars UNUSED;
11087     typval_T    *rettv;
11088 {
11089     rettv->vval.v_number = mod_mask;
11090 }
11091
11092 /*
11093  * "getcmdline()" function
11094  */
11095     static void
11096 f_getcmdline(argvars, rettv)
11097     typval_T    *argvars UNUSED;
11098     typval_T    *rettv;
11099 {
11100     rettv->v_type = VAR_STRING;
11101     rettv->vval.v_string = get_cmdline_str();
11102 }
11103
11104 /*
11105  * "getcmdpos()" function
11106  */
11107     static void
11108 f_getcmdpos(argvars, rettv)
11109     typval_T    *argvars UNUSED;
11110     typval_T    *rettv;
11111 {
11112     rettv->vval.v_number = get_cmdline_pos() + 1;
11113 }
11114
11115 /*
11116  * "getcmdtype()" function
11117  */
11118     static void
11119 f_getcmdtype(argvars, rettv)
11120     typval_T    *argvars UNUSED;
11121     typval_T    *rettv;
11122 {
11123     rettv->v_type = VAR_STRING;
11124     rettv->vval.v_string = alloc(2);
11125     if (rettv->vval.v_string != NULL)
11126     {
11127         rettv->vval.v_string[0] = get_cmdline_type();
11128         rettv->vval.v_string[1] = NUL;
11129     }
11130 }
11131
11132 /*
11133  * "getcwd()" function
11134  */
11135     static void
11136 f_getcwd(argvars, rettv)
11137     typval_T    *argvars UNUSED;
11138     typval_T    *rettv;
11139 {
11140     char_u      *cwd;
11141
11142     rettv->v_type = VAR_STRING;
11143     rettv->vval.v_string = NULL;
11144     cwd = alloc(MAXPATHL);
11145     if (cwd != NULL)
11146     {
11147         if (mch_dirname(cwd, MAXPATHL) != FAIL)
11148         {
11149             rettv->vval.v_string = vim_strsave(cwd);
11150 #ifdef BACKSLASH_IN_FILENAME
11151             if (rettv->vval.v_string != NULL)
11152                 slash_adjust(rettv->vval.v_string);
11153 #endif
11154         }
11155         vim_free(cwd);
11156     }
11157 }
11158
11159 /*
11160  * "getfontname()" function
11161  */
11162     static void
11163 f_getfontname(argvars, rettv)
11164     typval_T    *argvars UNUSED;
11165     typval_T    *rettv;
11166 {
11167     rettv->v_type = VAR_STRING;
11168     rettv->vval.v_string = NULL;
11169 #ifdef FEAT_GUI
11170     if (gui.in_use)
11171     {
11172         GuiFont font;
11173         char_u  *name = NULL;
11174
11175         if (argvars[0].v_type == VAR_UNKNOWN)
11176         {
11177             /* Get the "Normal" font.  Either the name saved by
11178              * hl_set_font_name() or from the font ID. */
11179             font = gui.norm_font;
11180             name = hl_get_font_name();
11181         }
11182         else
11183         {
11184             name = get_tv_string(&argvars[0]);
11185             if (STRCMP(name, "*") == 0)     /* don't use font dialog */
11186                 return;
11187             font = gui_mch_get_font(name, FALSE);
11188             if (font == NOFONT)
11189                 return;     /* Invalid font name, return empty string. */
11190         }
11191         rettv->vval.v_string = gui_mch_get_fontname(font, name);
11192         if (argvars[0].v_type != VAR_UNKNOWN)
11193             gui_mch_free_font(font);
11194     }
11195 #endif
11196 }
11197
11198 /*
11199  * "getfperm({fname})" function
11200  */
11201     static void
11202 f_getfperm(argvars, rettv)
11203     typval_T    *argvars;
11204     typval_T    *rettv;
11205 {
11206     char_u      *fname;
11207     struct stat st;
11208     char_u      *perm = NULL;
11209     char_u      flags[] = "rwx";
11210     int         i;
11211
11212     fname = get_tv_string(&argvars[0]);
11213
11214     rettv->v_type = VAR_STRING;
11215     if (mch_stat((char *)fname, &st) >= 0)
11216     {
11217         perm = vim_strsave((char_u *)"---------");
11218         if (perm != NULL)
11219         {
11220             for (i = 0; i < 9; i++)
11221             {
11222                 if (st.st_mode & (1 << (8 - i)))
11223                     perm[i] = flags[i % 3];
11224             }
11225         }
11226     }
11227     rettv->vval.v_string = perm;
11228 }
11229
11230 /*
11231  * "getfsize({fname})" function
11232  */
11233     static void
11234 f_getfsize(argvars, rettv)
11235     typval_T    *argvars;
11236     typval_T    *rettv;
11237 {
11238     char_u      *fname;
11239     struct stat st;
11240
11241     fname = get_tv_string(&argvars[0]);
11242
11243     rettv->v_type = VAR_NUMBER;
11244
11245     if (mch_stat((char *)fname, &st) >= 0)
11246     {
11247         if (mch_isdir(fname))
11248             rettv->vval.v_number = 0;
11249         else
11250         {
11251             rettv->vval.v_number = (varnumber_T)st.st_size;
11252
11253             /* non-perfect check for overflow */
11254             if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
11255                 rettv->vval.v_number = -2;
11256         }
11257     }
11258     else
11259           rettv->vval.v_number = -1;
11260 }
11261
11262 /*
11263  * "getftime({fname})" function
11264  */
11265     static void
11266 f_getftime(argvars, rettv)
11267     typval_T    *argvars;
11268     typval_T    *rettv;
11269 {
11270     char_u      *fname;
11271     struct stat st;
11272
11273     fname = get_tv_string(&argvars[0]);
11274
11275     if (mch_stat((char *)fname, &st) >= 0)
11276         rettv->vval.v_number = (varnumber_T)st.st_mtime;
11277     else
11278         rettv->vval.v_number = -1;
11279 }
11280
11281 /*
11282  * "getftype({fname})" function
11283  */
11284     static void
11285 f_getftype(argvars, rettv)
11286     typval_T    *argvars;
11287     typval_T    *rettv;
11288 {
11289     char_u      *fname;
11290     struct stat st;
11291     char_u      *type = NULL;
11292     char        *t;
11293
11294     fname = get_tv_string(&argvars[0]);
11295
11296     rettv->v_type = VAR_STRING;
11297     if (mch_lstat((char *)fname, &st) >= 0)
11298     {
11299 #ifdef S_ISREG
11300         if (S_ISREG(st.st_mode))
11301             t = "file";
11302         else if (S_ISDIR(st.st_mode))
11303             t = "dir";
11304 # ifdef S_ISLNK
11305         else if (S_ISLNK(st.st_mode))
11306             t = "link";
11307 # endif
11308 # ifdef S_ISBLK
11309         else if (S_ISBLK(st.st_mode))
11310             t = "bdev";
11311 # endif
11312 # ifdef S_ISCHR
11313         else if (S_ISCHR(st.st_mode))
11314             t = "cdev";
11315 # endif
11316 # ifdef S_ISFIFO
11317         else if (S_ISFIFO(st.st_mode))
11318             t = "fifo";
11319 # endif
11320 # ifdef S_ISSOCK
11321         else if (S_ISSOCK(st.st_mode))
11322             t = "fifo";
11323 # endif
11324         else
11325             t = "other";
11326 #else
11327 # ifdef S_IFMT
11328         switch (st.st_mode & S_IFMT)
11329         {
11330             case S_IFREG: t = "file"; break;
11331             case S_IFDIR: t = "dir"; break;
11332 #  ifdef S_IFLNK
11333             case S_IFLNK: t = "link"; break;
11334 #  endif
11335 #  ifdef S_IFBLK
11336             case S_IFBLK: t = "bdev"; break;
11337 #  endif
11338 #  ifdef S_IFCHR
11339             case S_IFCHR: t = "cdev"; break;
11340 #  endif
11341 #  ifdef S_IFIFO
11342             case S_IFIFO: t = "fifo"; break;
11343 #  endif
11344 #  ifdef S_IFSOCK
11345             case S_IFSOCK: t = "socket"; break;
11346 #  endif
11347             default: t = "other";
11348         }
11349 # else
11350         if (mch_isdir(fname))
11351             t = "dir";
11352         else
11353             t = "file";
11354 # endif
11355 #endif
11356         type = vim_strsave((char_u *)t);
11357     }
11358     rettv->vval.v_string = type;
11359 }
11360
11361 /*
11362  * "getline(lnum, [end])" function
11363  */
11364     static void
11365 f_getline(argvars, rettv)
11366     typval_T    *argvars;
11367     typval_T    *rettv;
11368 {
11369     linenr_T    lnum;
11370     linenr_T    end;
11371     int         retlist;
11372
11373     lnum = get_tv_lnum(argvars);
11374     if (argvars[1].v_type == VAR_UNKNOWN)
11375     {
11376         end = 0;
11377         retlist = FALSE;
11378     }
11379     else
11380     {
11381         end = get_tv_lnum(&argvars[1]);
11382         retlist = TRUE;
11383     }
11384
11385     get_buffer_lines(curbuf, lnum, end, retlist, rettv);
11386 }
11387
11388 /*
11389  * "getmatches()" function
11390  */
11391     static void
11392 f_getmatches(argvars, rettv)
11393     typval_T    *argvars UNUSED;
11394     typval_T    *rettv;
11395 {
11396 #ifdef FEAT_SEARCH_EXTRA
11397     dict_T      *dict;
11398     matchitem_T *cur = curwin->w_match_head;
11399
11400     if (rettv_list_alloc(rettv) == OK)
11401     {
11402         while (cur != NULL)
11403         {
11404             dict = dict_alloc();
11405             if (dict == NULL)
11406                 return;
11407             dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
11408             dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
11409             dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
11410             dict_add_nr_str(dict, "id", (long)cur->id, NULL);
11411             list_append_dict(rettv->vval.v_list, dict);
11412             cur = cur->next;
11413         }
11414     }
11415 #endif
11416 }
11417
11418 /*
11419  * "getpid()" function
11420  */
11421     static void
11422 f_getpid(argvars, rettv)
11423     typval_T    *argvars UNUSED;
11424     typval_T    *rettv;
11425 {
11426     rettv->vval.v_number = mch_get_pid();
11427 }
11428
11429 /*
11430  * "getpos(string)" function
11431  */
11432     static void
11433 f_getpos(argvars, rettv)
11434     typval_T    *argvars;
11435     typval_T    *rettv;
11436 {
11437     pos_T       *fp;
11438     list_T      *l;
11439     int         fnum = -1;
11440
11441     if (rettv_list_alloc(rettv) == OK)
11442     {
11443         l = rettv->vval.v_list;
11444         fp = var2fpos(&argvars[0], TRUE, &fnum);
11445         if (fnum != -1)
11446             list_append_number(l, (varnumber_T)fnum);
11447         else
11448             list_append_number(l, (varnumber_T)0);
11449         list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
11450                                                             : (varnumber_T)0);
11451         list_append_number(l, (fp != NULL)
11452                      ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
11453                                                             : (varnumber_T)0);
11454         list_append_number(l,
11455 #ifdef FEAT_VIRTUALEDIT
11456                                 (fp != NULL) ? (varnumber_T)fp->coladd :
11457 #endif
11458                                                               (varnumber_T)0);
11459     }
11460     else
11461         rettv->vval.v_number = FALSE;
11462 }
11463
11464 /*
11465  * "getqflist()" and "getloclist()" functions
11466  */
11467     static void
11468 f_getqflist(argvars, rettv)
11469     typval_T    *argvars UNUSED;
11470     typval_T    *rettv UNUSED;
11471 {
11472 #ifdef FEAT_QUICKFIX
11473     win_T       *wp;
11474 #endif
11475
11476 #ifdef FEAT_QUICKFIX
11477     if (rettv_list_alloc(rettv) == OK)
11478     {
11479         wp = NULL;
11480         if (argvars[0].v_type != VAR_UNKNOWN)   /* getloclist() */
11481         {
11482             wp = find_win_by_nr(&argvars[0], NULL);
11483             if (wp == NULL)
11484                 return;
11485         }
11486
11487         (void)get_errorlist(wp, rettv->vval.v_list);
11488     }
11489 #endif
11490 }
11491
11492 /*
11493  * "getreg()" function
11494  */
11495     static void
11496 f_getreg(argvars, rettv)
11497     typval_T    *argvars;
11498     typval_T    *rettv;
11499 {
11500     char_u      *strregname;
11501     int         regname;
11502     int         arg2 = FALSE;
11503     int         error = FALSE;
11504
11505     if (argvars[0].v_type != VAR_UNKNOWN)
11506     {
11507         strregname = get_tv_string_chk(&argvars[0]);
11508         error = strregname == NULL;
11509         if (argvars[1].v_type != VAR_UNKNOWN)
11510             arg2 = get_tv_number_chk(&argvars[1], &error);
11511     }
11512     else
11513         strregname = vimvars[VV_REG].vv_str;
11514     regname = (strregname == NULL ? '"' : *strregname);
11515     if (regname == 0)
11516         regname = '"';
11517
11518     rettv->v_type = VAR_STRING;
11519     rettv->vval.v_string = error ? NULL :
11520                                     get_reg_contents(regname, TRUE, arg2);
11521 }
11522
11523 /*
11524  * "getregtype()" function
11525  */
11526     static void
11527 f_getregtype(argvars, rettv)
11528     typval_T    *argvars;
11529     typval_T    *rettv;
11530 {
11531     char_u      *strregname;
11532     int         regname;
11533     char_u      buf[NUMBUFLEN + 2];
11534     long        reglen = 0;
11535
11536     if (argvars[0].v_type != VAR_UNKNOWN)
11537     {
11538         strregname = get_tv_string_chk(&argvars[0]);
11539         if (strregname == NULL)     /* type error; errmsg already given */
11540         {
11541             rettv->v_type = VAR_STRING;
11542             rettv->vval.v_string = NULL;
11543             return;
11544         }
11545     }
11546     else
11547         /* Default to v:register */
11548         strregname = vimvars[VV_REG].vv_str;
11549
11550     regname = (strregname == NULL ? '"' : *strregname);
11551     if (regname == 0)
11552         regname = '"';
11553
11554     buf[0] = NUL;
11555     buf[1] = NUL;
11556     switch (get_reg_type(regname, &reglen))
11557     {
11558         case MLINE: buf[0] = 'V'; break;
11559         case MCHAR: buf[0] = 'v'; break;
11560 #ifdef FEAT_VISUAL
11561         case MBLOCK:
11562                 buf[0] = Ctrl_V;
11563                 sprintf((char *)buf + 1, "%ld", reglen + 1);
11564                 break;
11565 #endif
11566     }
11567     rettv->v_type = VAR_STRING;
11568     rettv->vval.v_string = vim_strsave(buf);
11569 }
11570
11571 /*
11572  * "gettabvar()" function
11573  */
11574     static void
11575 f_gettabvar(argvars, rettv)
11576     typval_T    *argvars;
11577     typval_T    *rettv;
11578 {
11579     tabpage_T   *tp;
11580     dictitem_T  *v;
11581     char_u      *varname;
11582
11583     rettv->v_type = VAR_STRING;
11584     rettv->vval.v_string = NULL;
11585
11586     varname = get_tv_string_chk(&argvars[1]);
11587     tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
11588     if (tp != NULL && varname != NULL)
11589     {
11590         /* look up the variable */
11591         v = find_var_in_ht(&tp->tp_vars.dv_hashtab, varname, FALSE);
11592         if (v != NULL)
11593             copy_tv(&v->di_tv, rettv);
11594     }
11595 }
11596
11597 /*
11598  * "gettabwinvar()" function
11599  */
11600     static void
11601 f_gettabwinvar(argvars, rettv)
11602     typval_T    *argvars;
11603     typval_T    *rettv;
11604 {
11605     getwinvar(argvars, rettv, 1);
11606 }
11607
11608 /*
11609  * "getwinposx()" function
11610  */
11611     static void
11612 f_getwinposx(argvars, rettv)
11613     typval_T    *argvars UNUSED;
11614     typval_T    *rettv;
11615 {
11616     rettv->vval.v_number = -1;
11617 #ifdef FEAT_GUI
11618     if (gui.in_use)
11619     {
11620         int         x, y;
11621
11622         if (gui_mch_get_winpos(&x, &y) == OK)
11623             rettv->vval.v_number = x;
11624     }
11625 #endif
11626 }
11627
11628 /*
11629  * "getwinposy()" function
11630  */
11631     static void
11632 f_getwinposy(argvars, rettv)
11633     typval_T    *argvars UNUSED;
11634     typval_T    *rettv;
11635 {
11636     rettv->vval.v_number = -1;
11637 #ifdef FEAT_GUI
11638     if (gui.in_use)
11639     {
11640         int         x, y;
11641
11642         if (gui_mch_get_winpos(&x, &y) == OK)
11643             rettv->vval.v_number = y;
11644     }
11645 #endif
11646 }
11647
11648 /*
11649  * Find window specified by "vp" in tabpage "tp".
11650  */
11651     static win_T *
11652 find_win_by_nr(vp, tp)
11653     typval_T    *vp;
11654     tabpage_T   *tp;        /* NULL for current tab page */
11655 {
11656 #ifdef FEAT_WINDOWS
11657     win_T       *wp;
11658 #endif
11659     int         nr;
11660
11661     nr = get_tv_number_chk(vp, NULL);
11662
11663 #ifdef FEAT_WINDOWS
11664     if (nr < 0)
11665         return NULL;
11666     if (nr == 0)
11667         return curwin;
11668
11669     for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
11670                                                   wp != NULL; wp = wp->w_next)
11671         if (--nr <= 0)
11672             break;
11673     return wp;
11674 #else
11675     if (nr == 0 || nr == 1)
11676         return curwin;
11677     return NULL;
11678 #endif
11679 }
11680
11681 /*
11682  * "getwinvar()" function
11683  */
11684     static void
11685 f_getwinvar(argvars, rettv)
11686     typval_T    *argvars;
11687     typval_T    *rettv;
11688 {
11689     getwinvar(argvars, rettv, 0);
11690 }
11691
11692 /*
11693  * getwinvar() and gettabwinvar()
11694  */
11695     static void
11696 getwinvar(argvars, rettv, off)
11697     typval_T    *argvars;
11698     typval_T    *rettv;
11699     int         off;        /* 1 for gettabwinvar() */
11700 {
11701     win_T       *win, *oldcurwin;
11702     char_u      *varname;
11703     dictitem_T  *v;
11704     tabpage_T   *tp;
11705
11706 #ifdef FEAT_WINDOWS
11707     if (off == 1)
11708         tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
11709     else
11710         tp = curtab;
11711 #endif
11712     win = find_win_by_nr(&argvars[off], tp);
11713     varname = get_tv_string_chk(&argvars[off + 1]);
11714     ++emsg_off;
11715
11716     rettv->v_type = VAR_STRING;
11717     rettv->vval.v_string = NULL;
11718
11719     if (win != NULL && varname != NULL)
11720     {
11721         /* Set curwin to be our win, temporarily.  Also set curbuf, so
11722          * that we can get buffer-local options. */
11723         oldcurwin = curwin;
11724         curwin = win;
11725         curbuf = win->w_buffer;
11726
11727         if (*varname == '&')    /* window-local-option */
11728             get_option_tv(&varname, rettv, 1);
11729         else
11730         {
11731             if (*varname == NUL)
11732                 /* let getwinvar({nr}, "") return the "w:" dictionary.  The
11733                  * scope prefix before the NUL byte is required by
11734                  * find_var_in_ht(). */
11735                 varname = (char_u *)"w:" + 2;
11736             /* look up the variable */
11737             v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
11738             if (v != NULL)
11739                 copy_tv(&v->di_tv, rettv);
11740         }
11741
11742         /* restore previous notion of curwin */
11743         curwin = oldcurwin;
11744         curbuf = curwin->w_buffer;
11745     }
11746
11747     --emsg_off;
11748 }
11749
11750 /*
11751  * "glob()" function
11752  */
11753     static void
11754 f_glob(argvars, rettv)
11755     typval_T    *argvars;
11756     typval_T    *rettv;
11757 {
11758     int         options = WILD_SILENT|WILD_USE_NL;
11759     expand_T    xpc;
11760     int         error = FALSE;
11761
11762     /* When the optional second argument is non-zero, don't remove matches
11763     * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11764     if (argvars[1].v_type != VAR_UNKNOWN
11765                                 && get_tv_number_chk(&argvars[1], &error))
11766         options |= WILD_KEEP_ALL;
11767     rettv->v_type = VAR_STRING;
11768     if (!error)
11769     {
11770         ExpandInit(&xpc);
11771         xpc.xp_context = EXPAND_FILES;
11772         if (p_wic)
11773             options += WILD_ICASE;
11774         rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
11775                                                      NULL, options, WILD_ALL);
11776     }
11777     else
11778         rettv->vval.v_string = NULL;
11779 }
11780
11781 /*
11782  * "globpath()" function
11783  */
11784     static void
11785 f_globpath(argvars, rettv)
11786     typval_T    *argvars;
11787     typval_T    *rettv;
11788 {
11789     int         flags = 0;
11790     char_u      buf1[NUMBUFLEN];
11791     char_u      *file = get_tv_string_buf_chk(&argvars[1], buf1);
11792     int         error = FALSE;
11793
11794     /* When the optional second argument is non-zero, don't remove matches
11795     * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11796     if (argvars[2].v_type != VAR_UNKNOWN
11797                                 && get_tv_number_chk(&argvars[2], &error))
11798         flags |= WILD_KEEP_ALL;
11799     rettv->v_type = VAR_STRING;
11800     if (file == NULL || error)
11801         rettv->vval.v_string = NULL;
11802     else
11803         rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file,
11804                                                                        flags);
11805 }
11806
11807 /*
11808  * "has()" function
11809  */
11810     static void
11811 f_has(argvars, rettv)
11812     typval_T    *argvars;
11813     typval_T    *rettv;
11814 {
11815     int         i;
11816     char_u      *name;
11817     int         n = FALSE;
11818     static char *(has_list[]) =
11819     {
11820 #ifdef AMIGA
11821         "amiga",
11822 # ifdef FEAT_ARP
11823         "arp",
11824 # endif
11825 #endif
11826 #ifdef __BEOS__
11827         "beos",
11828 #endif
11829 #ifdef MSDOS
11830 # ifdef DJGPP
11831         "dos32",
11832 # else
11833         "dos16",
11834 # endif
11835 #endif
11836 #ifdef MACOS
11837         "mac",
11838 #endif
11839 #if defined(MACOS_X_UNIX)
11840         "macunix",
11841 #endif
11842 #ifdef OS2
11843         "os2",
11844 #endif
11845 #ifdef __QNX__
11846         "qnx",
11847 #endif
11848 #ifdef UNIX
11849         "unix",
11850 #endif
11851 #ifdef VMS
11852         "vms",
11853 #endif
11854 #ifdef WIN16
11855         "win16",
11856 #endif
11857 #ifdef WIN32
11858         "win32",
11859 #endif
11860 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
11861         "win32unix",
11862 #endif
11863 #if defined(WIN64) || defined(_WIN64)
11864         "win64",
11865 #endif
11866 #ifdef EBCDIC
11867         "ebcdic",
11868 #endif
11869 #ifndef CASE_INSENSITIVE_FILENAME
11870         "fname_case",
11871 #endif
11872 #ifdef FEAT_ARABIC
11873         "arabic",
11874 #endif
11875 #ifdef FEAT_AUTOCMD
11876         "autocmd",
11877 #endif
11878 #ifdef FEAT_BEVAL
11879         "balloon_eval",
11880 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
11881         "balloon_multiline",
11882 # endif
11883 #endif
11884 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
11885         "builtin_terms",
11886 # ifdef ALL_BUILTIN_TCAPS
11887         "all_builtin_terms",
11888 # endif
11889 #endif
11890 #ifdef FEAT_BYTEOFF
11891         "byte_offset",
11892 #endif
11893 #ifdef FEAT_CINDENT
11894         "cindent",
11895 #endif
11896 #ifdef FEAT_CLIENTSERVER
11897         "clientserver",
11898 #endif
11899 #ifdef FEAT_CLIPBOARD
11900         "clipboard",
11901 #endif
11902 #ifdef FEAT_CMDL_COMPL
11903         "cmdline_compl",
11904 #endif
11905 #ifdef FEAT_CMDHIST
11906         "cmdline_hist",
11907 #endif
11908 #ifdef FEAT_COMMENTS
11909         "comments",
11910 #endif
11911 #ifdef FEAT_CONCEAL
11912         "conceal",
11913 #endif
11914 #ifdef FEAT_CRYPT
11915         "cryptv",
11916 #endif
11917 #ifdef FEAT_CSCOPE
11918         "cscope",
11919 #endif
11920 #ifdef FEAT_CURSORBIND
11921         "cursorbind",
11922 #endif
11923 #ifdef CURSOR_SHAPE
11924         "cursorshape",
11925 #endif
11926 #ifdef DEBUG
11927         "debug",
11928 #endif
11929 #ifdef FEAT_CON_DIALOG
11930         "dialog_con",
11931 #endif
11932 #ifdef FEAT_GUI_DIALOG
11933         "dialog_gui",
11934 #endif
11935 #ifdef FEAT_DIFF
11936         "diff",
11937 #endif
11938 #ifdef FEAT_DIGRAPHS
11939         "digraphs",
11940 #endif
11941 #ifdef FEAT_DND
11942         "dnd",
11943 #endif
11944 #ifdef FEAT_EMACS_TAGS
11945         "emacs_tags",
11946 #endif
11947         "eval",     /* always present, of course! */
11948 #ifdef FEAT_EX_EXTRA
11949         "ex_extra",
11950 #endif
11951 #ifdef FEAT_SEARCH_EXTRA
11952         "extra_search",
11953 #endif
11954 #ifdef FEAT_FKMAP
11955         "farsi",
11956 #endif
11957 #ifdef FEAT_SEARCHPATH
11958         "file_in_path",
11959 #endif
11960 #if (defined(UNIX) && !defined(USE_SYSTEM)) || defined(WIN3264)
11961         "filterpipe",
11962 #endif
11963 #ifdef FEAT_FIND_ID
11964         "find_in_path",
11965 #endif
11966 #ifdef FEAT_FLOAT
11967         "float",
11968 #endif
11969 #ifdef FEAT_FOLDING
11970         "folding",
11971 #endif
11972 #ifdef FEAT_FOOTER
11973         "footer",
11974 #endif
11975 #if !defined(USE_SYSTEM) && defined(UNIX)
11976         "fork",
11977 #endif
11978 #ifdef FEAT_GETTEXT
11979         "gettext",
11980 #endif
11981 #ifdef FEAT_GUI
11982         "gui",
11983 #endif
11984 #ifdef FEAT_GUI_ATHENA
11985 # ifdef FEAT_GUI_NEXTAW
11986         "gui_neXtaw",
11987 # else
11988         "gui_athena",
11989 # endif
11990 #endif
11991 #ifdef FEAT_GUI_GTK
11992         "gui_gtk",
11993         "gui_gtk2",
11994 #endif
11995 #ifdef FEAT_GUI_GNOME
11996         "gui_gnome",
11997 #endif
11998 #ifdef FEAT_GUI_MAC
11999         "gui_mac",
12000 #endif
12001 #ifdef FEAT_GUI_MOTIF
12002         "gui_motif",
12003 #endif
12004 #ifdef FEAT_GUI_PHOTON
12005         "gui_photon",
12006 #endif
12007 #ifdef FEAT_GUI_W16
12008         "gui_win16",
12009 #endif
12010 #ifdef FEAT_GUI_W32
12011         "gui_win32",
12012 #endif
12013 #ifdef FEAT_HANGULIN
12014         "hangul_input",
12015 #endif
12016 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
12017         "iconv",
12018 #endif
12019 #ifdef FEAT_INS_EXPAND
12020         "insert_expand",
12021 #endif
12022 #ifdef FEAT_JUMPLIST
12023         "jumplist",
12024 #endif
12025 #ifdef FEAT_KEYMAP
12026         "keymap",
12027 #endif
12028 #ifdef FEAT_LANGMAP
12029         "langmap",
12030 #endif
12031 #ifdef FEAT_LIBCALL
12032         "libcall",
12033 #endif
12034 #ifdef FEAT_LINEBREAK
12035         "linebreak",
12036 #endif
12037 #ifdef FEAT_LISP
12038         "lispindent",
12039 #endif
12040 #ifdef FEAT_LISTCMDS
12041         "listcmds",
12042 #endif
12043 #ifdef FEAT_LOCALMAP
12044         "localmap",
12045 #endif
12046 #ifdef FEAT_LUA
12047 # ifndef DYNAMIC_LUA
12048         "lua",
12049 # endif
12050 #endif
12051 #ifdef FEAT_MENU
12052         "menu",
12053 #endif
12054 #ifdef FEAT_SESSION
12055         "mksession",
12056 #endif
12057 #ifdef FEAT_MODIFY_FNAME
12058         "modify_fname",
12059 #endif
12060 #ifdef FEAT_MOUSE
12061         "mouse",
12062 #endif
12063 #ifdef FEAT_MOUSESHAPE
12064         "mouseshape",
12065 #endif
12066 #if defined(UNIX) || defined(VMS)
12067 # ifdef FEAT_MOUSE_DEC
12068         "mouse_dec",
12069 # endif
12070 # ifdef FEAT_MOUSE_GPM
12071         "mouse_gpm",
12072 # endif
12073 # ifdef FEAT_MOUSE_JSB
12074         "mouse_jsbterm",
12075 # endif
12076 # ifdef FEAT_MOUSE_NET
12077         "mouse_netterm",
12078 # endif
12079 # ifdef FEAT_MOUSE_PTERM
12080         "mouse_pterm",
12081 # endif
12082 # ifdef FEAT_SYSMOUSE
12083         "mouse_sysmouse",
12084 # endif
12085 # ifdef FEAT_MOUSE_XTERM
12086         "mouse_xterm",
12087 # endif
12088 #endif
12089 #ifdef FEAT_MBYTE
12090         "multi_byte",
12091 #endif
12092 #ifdef FEAT_MBYTE_IME
12093         "multi_byte_ime",
12094 #endif
12095 #ifdef FEAT_MULTI_LANG
12096         "multi_lang",
12097 #endif
12098 #ifdef FEAT_MZSCHEME
12099 #ifndef DYNAMIC_MZSCHEME
12100         "mzscheme",
12101 #endif
12102 #endif
12103 #ifdef FEAT_OLE
12104         "ole",
12105 #endif
12106 #ifdef FEAT_PATH_EXTRA
12107         "path_extra",
12108 #endif
12109 #ifdef FEAT_PERL
12110 #ifndef DYNAMIC_PERL
12111         "perl",
12112 #endif
12113 #endif
12114 #ifdef FEAT_PERSISTENT_UNDO
12115         "persistent_undo",
12116 #endif
12117 #ifdef FEAT_PYTHON
12118 #ifndef DYNAMIC_PYTHON
12119         "python",
12120 #endif
12121 #endif
12122 #ifdef FEAT_PYTHON3
12123 #ifndef DYNAMIC_PYTHON3
12124         "python3",
12125 #endif
12126 #endif
12127 #ifdef FEAT_POSTSCRIPT
12128         "postscript",
12129 #endif
12130 #ifdef FEAT_PRINTER
12131         "printer",
12132 #endif
12133 #ifdef FEAT_PROFILE
12134         "profile",
12135 #endif
12136 #ifdef FEAT_RELTIME
12137         "reltime",
12138 #endif
12139 #ifdef FEAT_QUICKFIX
12140         "quickfix",
12141 #endif
12142 #ifdef FEAT_RIGHTLEFT
12143         "rightleft",
12144 #endif
12145 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
12146         "ruby",
12147 #endif
12148 #ifdef FEAT_SCROLLBIND
12149         "scrollbind",
12150 #endif
12151 #ifdef FEAT_CMDL_INFO
12152         "showcmd",
12153         "cmdline_info",
12154 #endif
12155 #ifdef FEAT_SIGNS
12156         "signs",
12157 #endif
12158 #ifdef FEAT_SMARTINDENT
12159         "smartindent",
12160 #endif
12161 #ifdef FEAT_SNIFF
12162         "sniff",
12163 #endif
12164 #ifdef STARTUPTIME
12165         "startuptime",
12166 #endif
12167 #ifdef FEAT_STL_OPT
12168         "statusline",
12169 #endif
12170 #ifdef FEAT_SUN_WORKSHOP
12171         "sun_workshop",
12172 #endif
12173 #ifdef FEAT_NETBEANS_INTG
12174         "netbeans_intg",
12175 #endif
12176 #ifdef FEAT_SPELL
12177         "spell",
12178 #endif
12179 #ifdef FEAT_SYN_HL
12180         "syntax",
12181 #endif
12182 #if defined(USE_SYSTEM) || !defined(UNIX)
12183         "system",
12184 #endif
12185 #ifdef FEAT_TAG_BINS
12186         "tag_binary",
12187 #endif
12188 #ifdef FEAT_TAG_OLDSTATIC
12189         "tag_old_static",
12190 #endif
12191 #ifdef FEAT_TAG_ANYWHITE
12192         "tag_any_white",
12193 #endif
12194 #ifdef FEAT_TCL
12195 # ifndef DYNAMIC_TCL
12196         "tcl",
12197 # endif
12198 #endif
12199 #ifdef TERMINFO
12200         "terminfo",
12201 #endif
12202 #ifdef FEAT_TERMRESPONSE
12203         "termresponse",
12204 #endif
12205 #ifdef FEAT_TEXTOBJ
12206         "textobjects",
12207 #endif
12208 #ifdef HAVE_TGETENT
12209         "tgetent",
12210 #endif
12211 #ifdef FEAT_TITLE
12212         "title",
12213 #endif
12214 #ifdef FEAT_TOOLBAR
12215         "toolbar",
12216 #endif
12217 #if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
12218         "unnamedplus",
12219 #endif
12220 #ifdef FEAT_USR_CMDS
12221         "user-commands",    /* was accidentally included in 5.4 */
12222         "user_commands",
12223 #endif
12224 #ifdef FEAT_VIMINFO
12225         "viminfo",
12226 #endif
12227 #ifdef FEAT_VERTSPLIT
12228         "vertsplit",
12229 #endif
12230 #ifdef FEAT_VIRTUALEDIT
12231         "virtualedit",
12232 #endif
12233 #ifdef FEAT_VISUAL
12234         "visual",
12235 #endif
12236 #ifdef FEAT_VISUALEXTRA
12237         "visualextra",
12238 #endif
12239 #ifdef FEAT_VREPLACE
12240         "vreplace",
12241 #endif
12242 #ifdef FEAT_WILDIGN
12243         "wildignore",
12244 #endif
12245 #ifdef FEAT_WILDMENU
12246         "wildmenu",
12247 #endif
12248 #ifdef FEAT_WINDOWS
12249         "windows",
12250 #endif
12251 #ifdef FEAT_WAK
12252         "winaltkeys",
12253 #endif
12254 #ifdef FEAT_WRITEBACKUP
12255         "writebackup",
12256 #endif
12257 #ifdef FEAT_XIM
12258         "xim",
12259 #endif
12260 #ifdef FEAT_XFONTSET
12261         "xfontset",
12262 #endif
12263 #ifdef USE_XSMP
12264         "xsmp",
12265 #endif
12266 #ifdef USE_XSMP_INTERACT
12267         "xsmp_interact",
12268 #endif
12269 #ifdef FEAT_XCLIPBOARD
12270         "xterm_clipboard",
12271 #endif
12272 #ifdef FEAT_XTERM_SAVE
12273         "xterm_save",
12274 #endif
12275 #if defined(UNIX) && defined(FEAT_X11)
12276         "X11",
12277 #endif
12278         NULL
12279     };
12280
12281     name = get_tv_string(&argvars[0]);
12282     for (i = 0; has_list[i] != NULL; ++i)
12283         if (STRICMP(name, has_list[i]) == 0)
12284         {
12285             n = TRUE;
12286             break;
12287         }
12288
12289     if (n == FALSE)
12290     {
12291         if (STRNICMP(name, "patch", 5) == 0)
12292             n = has_patch(atoi((char *)name + 5));
12293         else if (STRICMP(name, "vim_starting") == 0)
12294             n = (starting != 0);
12295 #ifdef FEAT_MBYTE
12296         else if (STRICMP(name, "multi_byte_encoding") == 0)
12297             n = has_mbyte;
12298 #endif
12299 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
12300         else if (STRICMP(name, "balloon_multiline") == 0)
12301             n = multiline_balloon_available();
12302 #endif
12303 #ifdef DYNAMIC_TCL
12304         else if (STRICMP(name, "tcl") == 0)
12305             n = tcl_enabled(FALSE);
12306 #endif
12307 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
12308         else if (STRICMP(name, "iconv") == 0)
12309             n = iconv_enabled(FALSE);
12310 #endif
12311 #ifdef DYNAMIC_LUA
12312         else if (STRICMP(name, "lua") == 0)
12313             n = lua_enabled(FALSE);
12314 #endif
12315 #ifdef DYNAMIC_MZSCHEME
12316         else if (STRICMP(name, "mzscheme") == 0)
12317             n = mzscheme_enabled(FALSE);
12318 #endif
12319 #ifdef DYNAMIC_RUBY
12320         else if (STRICMP(name, "ruby") == 0)
12321             n = ruby_enabled(FALSE);
12322 #endif
12323 #ifdef FEAT_PYTHON
12324 #ifdef DYNAMIC_PYTHON
12325         else if (STRICMP(name, "python") == 0)
12326             n = python_enabled(FALSE);
12327 #endif
12328 #endif
12329 #ifdef FEAT_PYTHON3
12330 #ifdef DYNAMIC_PYTHON3
12331         else if (STRICMP(name, "python3") == 0)
12332             n = python3_enabled(FALSE);
12333 #endif
12334 #endif
12335 #ifdef DYNAMIC_PERL
12336         else if (STRICMP(name, "perl") == 0)
12337             n = perl_enabled(FALSE);
12338 #endif
12339 #ifdef FEAT_GUI
12340         else if (STRICMP(name, "gui_running") == 0)
12341             n = (gui.in_use || gui.starting);
12342 # ifdef FEAT_GUI_W32
12343         else if (STRICMP(name, "gui_win32s") == 0)
12344             n = gui_is_win32s();
12345 # endif
12346 # ifdef FEAT_BROWSE
12347         else if (STRICMP(name, "browse") == 0)
12348             n = gui.in_use;     /* gui_mch_browse() works when GUI is running */
12349 # endif
12350 #endif
12351 #ifdef FEAT_SYN_HL
12352         else if (STRICMP(name, "syntax_items") == 0)
12353             n = syntax_present(curwin);
12354 #endif
12355 #if defined(WIN3264)
12356         else if (STRICMP(name, "win95") == 0)
12357             n = mch_windows95();
12358 #endif
12359 #ifdef FEAT_NETBEANS_INTG
12360         else if (STRICMP(name, "netbeans_enabled") == 0)
12361             n = netbeans_active();
12362 #endif
12363     }
12364
12365     rettv->vval.v_number = n;
12366 }
12367
12368 /*
12369  * "has_key()" function
12370  */
12371     static void
12372 f_has_key(argvars, rettv)
12373     typval_T    *argvars;
12374     typval_T    *rettv;
12375 {
12376     if (argvars[0].v_type != VAR_DICT)
12377     {
12378         EMSG(_(e_dictreq));
12379         return;
12380     }
12381     if (argvars[0].vval.v_dict == NULL)
12382         return;
12383
12384     rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
12385                                       get_tv_string(&argvars[1]), -1) != NULL;
12386 }
12387
12388 /*
12389  * "haslocaldir()" function
12390  */
12391     static void
12392 f_haslocaldir(argvars, rettv)
12393     typval_T    *argvars UNUSED;
12394     typval_T    *rettv;
12395 {
12396     rettv->vval.v_number = (curwin->w_localdir != NULL);
12397 }
12398
12399 /*
12400  * "hasmapto()" function
12401  */
12402     static void
12403 f_hasmapto(argvars, rettv)
12404     typval_T    *argvars;
12405     typval_T    *rettv;
12406 {
12407     char_u      *name;
12408     char_u      *mode;
12409     char_u      buf[NUMBUFLEN];
12410     int         abbr = FALSE;
12411
12412     name = get_tv_string(&argvars[0]);
12413     if (argvars[1].v_type == VAR_UNKNOWN)
12414         mode = (char_u *)"nvo";
12415     else
12416     {
12417         mode = get_tv_string_buf(&argvars[1], buf);
12418         if (argvars[2].v_type != VAR_UNKNOWN)
12419             abbr = get_tv_number(&argvars[2]);
12420     }
12421
12422     if (map_to_exists(name, mode, abbr))
12423         rettv->vval.v_number = TRUE;
12424     else
12425         rettv->vval.v_number = FALSE;
12426 }
12427
12428 /*
12429  * "histadd()" function
12430  */
12431     static void
12432 f_histadd(argvars, rettv)
12433     typval_T    *argvars UNUSED;
12434     typval_T    *rettv;
12435 {
12436 #ifdef FEAT_CMDHIST
12437     int         histype;
12438     char_u      *str;
12439     char_u      buf[NUMBUFLEN];
12440 #endif
12441
12442     rettv->vval.v_number = FALSE;
12443     if (check_restricted() || check_secure())
12444         return;
12445 #ifdef FEAT_CMDHIST
12446     str = get_tv_string_chk(&argvars[0]);       /* NULL on type error */
12447     histype = str != NULL ? get_histtype(str) : -1;
12448     if (histype >= 0)
12449     {
12450         str = get_tv_string_buf(&argvars[1], buf);
12451         if (*str != NUL)
12452         {
12453             init_history();
12454             add_to_history(histype, str, FALSE, NUL);
12455             rettv->vval.v_number = TRUE;
12456             return;
12457         }
12458     }
12459 #endif
12460 }
12461
12462 /*
12463  * "histdel()" function
12464  */
12465     static void
12466 f_histdel(argvars, rettv)
12467     typval_T    *argvars UNUSED;
12468     typval_T    *rettv UNUSED;
12469 {
12470 #ifdef FEAT_CMDHIST
12471     int         n;
12472     char_u      buf[NUMBUFLEN];
12473     char_u      *str;
12474
12475     str = get_tv_string_chk(&argvars[0]);       /* NULL on type error */
12476     if (str == NULL)
12477         n = 0;
12478     else if (argvars[1].v_type == VAR_UNKNOWN)
12479         /* only one argument: clear entire history */
12480         n = clr_history(get_histtype(str));
12481     else if (argvars[1].v_type == VAR_NUMBER)
12482         /* index given: remove that entry */
12483         n = del_history_idx(get_histtype(str),
12484                                           (int)get_tv_number(&argvars[1]));
12485     else
12486         /* string given: remove all matching entries */
12487         n = del_history_entry(get_histtype(str),
12488                                       get_tv_string_buf(&argvars[1], buf));
12489     rettv->vval.v_number = n;
12490 #endif
12491 }
12492
12493 /*
12494  * "histget()" function
12495  */
12496     static void
12497 f_histget(argvars, rettv)
12498     typval_T    *argvars UNUSED;
12499     typval_T    *rettv;
12500 {
12501 #ifdef FEAT_CMDHIST
12502     int         type;
12503     int         idx;
12504     char_u      *str;
12505
12506     str = get_tv_string_chk(&argvars[0]);       /* NULL on type error */
12507     if (str == NULL)
12508         rettv->vval.v_string = NULL;
12509     else
12510     {
12511         type = get_histtype(str);
12512         if (argvars[1].v_type == VAR_UNKNOWN)
12513             idx = get_history_idx(type);
12514         else
12515             idx = (int)get_tv_number_chk(&argvars[1], NULL);
12516                                                     /* -1 on type error */
12517         rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
12518     }
12519 #else
12520     rettv->vval.v_string = NULL;
12521 #endif
12522     rettv->v_type = VAR_STRING;
12523 }
12524
12525 /*
12526  * "histnr()" function
12527  */
12528     static void
12529 f_histnr(argvars, rettv)
12530     typval_T    *argvars UNUSED;
12531     typval_T    *rettv;
12532 {
12533     int         i;
12534
12535 #ifdef FEAT_CMDHIST
12536     char_u      *history = get_tv_string_chk(&argvars[0]);
12537
12538     i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
12539     if (i >= HIST_CMD && i < HIST_COUNT)
12540         i = get_history_idx(i);
12541     else
12542 #endif
12543         i = -1;
12544     rettv->vval.v_number = i;
12545 }
12546
12547 /*
12548  * "highlightID(name)" function
12549  */
12550     static void
12551 f_hlID(argvars, rettv)
12552     typval_T    *argvars;
12553     typval_T    *rettv;
12554 {
12555     rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
12556 }
12557
12558 /*
12559  * "highlight_exists()" function
12560  */
12561     static void
12562 f_hlexists(argvars, rettv)
12563     typval_T    *argvars;
12564     typval_T    *rettv;
12565 {
12566     rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
12567 }
12568
12569 /*
12570  * "hostname()" function
12571  */
12572     static void
12573 f_hostname(argvars, rettv)
12574     typval_T    *argvars UNUSED;
12575     typval_T    *rettv;
12576 {
12577     char_u hostname[256];
12578
12579     mch_get_host_name(hostname, 256);
12580     rettv->v_type = VAR_STRING;
12581     rettv->vval.v_string = vim_strsave(hostname);
12582 }
12583
12584 /*
12585  * iconv() function
12586  */
12587     static void
12588 f_iconv(argvars, rettv)
12589     typval_T    *argvars UNUSED;
12590     typval_T    *rettv;
12591 {
12592 #ifdef FEAT_MBYTE
12593     char_u      buf1[NUMBUFLEN];
12594     char_u      buf2[NUMBUFLEN];
12595     char_u      *from, *to, *str;
12596     vimconv_T   vimconv;
12597 #endif
12598
12599     rettv->v_type = VAR_STRING;
12600     rettv->vval.v_string = NULL;
12601
12602 #ifdef FEAT_MBYTE
12603     str = get_tv_string(&argvars[0]);
12604     from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
12605     to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
12606     vimconv.vc_type = CONV_NONE;
12607     convert_setup(&vimconv, from, to);
12608
12609     /* If the encodings are equal, no conversion needed. */
12610     if (vimconv.vc_type == CONV_NONE)
12611         rettv->vval.v_string = vim_strsave(str);
12612     else
12613         rettv->vval.v_string = string_convert(&vimconv, str, NULL);
12614
12615     convert_setup(&vimconv, NULL, NULL);
12616     vim_free(from);
12617     vim_free(to);
12618 #endif
12619 }
12620
12621 /*
12622  * "indent()" function
12623  */
12624     static void
12625 f_indent(argvars, rettv)
12626     typval_T    *argvars;
12627     typval_T    *rettv;
12628 {
12629     linenr_T    lnum;
12630
12631     lnum = get_tv_lnum(argvars);
12632     if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12633         rettv->vval.v_number = get_indent_lnum(lnum);
12634     else
12635         rettv->vval.v_number = -1;
12636 }
12637
12638 /*
12639  * "index()" function
12640  */
12641     static void
12642 f_index(argvars, rettv)
12643     typval_T    *argvars;
12644     typval_T    *rettv;
12645 {
12646     list_T      *l;
12647     listitem_T  *item;
12648     long        idx = 0;
12649     int         ic = FALSE;
12650
12651     rettv->vval.v_number = -1;
12652     if (argvars[0].v_type != VAR_LIST)
12653     {
12654         EMSG(_(e_listreq));
12655         return;
12656     }
12657     l = argvars[0].vval.v_list;
12658     if (l != NULL)
12659     {
12660         item = l->lv_first;
12661         if (argvars[2].v_type != VAR_UNKNOWN)
12662         {
12663             int         error = FALSE;
12664
12665             /* Start at specified item.  Use the cached index that list_find()
12666              * sets, so that a negative number also works. */
12667             item = list_find(l, get_tv_number_chk(&argvars[2], &error));
12668             idx = l->lv_idx;
12669             if (argvars[3].v_type != VAR_UNKNOWN)
12670                 ic = get_tv_number_chk(&argvars[3], &error);
12671             if (error)
12672                 item = NULL;
12673         }
12674
12675         for ( ; item != NULL; item = item->li_next, ++idx)
12676             if (tv_equal(&item->li_tv, &argvars[1], ic, FALSE))
12677             {
12678                 rettv->vval.v_number = idx;
12679                 break;
12680             }
12681     }
12682 }
12683
12684 static int inputsecret_flag = 0;
12685
12686 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
12687
12688 /*
12689  * This function is used by f_input() and f_inputdialog() functions. The third
12690  * argument to f_input() specifies the type of completion to use at the
12691  * prompt. The third argument to f_inputdialog() specifies the value to return
12692  * when the user cancels the prompt.
12693  */
12694     static void
12695 get_user_input(argvars, rettv, inputdialog)
12696     typval_T    *argvars;
12697     typval_T    *rettv;
12698     int         inputdialog;
12699 {
12700     char_u      *prompt = get_tv_string_chk(&argvars[0]);
12701     char_u      *p = NULL;
12702     int         c;
12703     char_u      buf[NUMBUFLEN];
12704     int         cmd_silent_save = cmd_silent;
12705     char_u      *defstr = (char_u *)"";
12706     int         xp_type = EXPAND_NOTHING;
12707     char_u      *xp_arg = NULL;
12708
12709     rettv->v_type = VAR_STRING;
12710     rettv->vval.v_string = NULL;
12711
12712 #ifdef NO_CONSOLE_INPUT
12713     /* While starting up, there is no place to enter text. */
12714     if (no_console_input())
12715         return;
12716 #endif
12717
12718     cmd_silent = FALSE;         /* Want to see the prompt. */
12719     if (prompt != NULL)
12720     {
12721         /* Only the part of the message after the last NL is considered as
12722          * prompt for the command line */
12723         p = vim_strrchr(prompt, '\n');
12724         if (p == NULL)
12725             p = prompt;
12726         else
12727         {
12728             ++p;
12729             c = *p;
12730             *p = NUL;
12731             msg_start();
12732             msg_clr_eos();
12733             msg_puts_attr(prompt, echo_attr);
12734             msg_didout = FALSE;
12735             msg_starthere();
12736             *p = c;
12737         }
12738         cmdline_row = msg_row;
12739
12740         if (argvars[1].v_type != VAR_UNKNOWN)
12741         {
12742             defstr = get_tv_string_buf_chk(&argvars[1], buf);
12743             if (defstr != NULL)
12744                 stuffReadbuffSpec(defstr);
12745
12746             if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
12747             {
12748                 char_u  *xp_name;
12749                 int     xp_namelen;
12750                 long    argt;
12751
12752                 rettv->vval.v_string = NULL;
12753
12754                 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
12755                 if (xp_name == NULL)
12756                     return;
12757
12758                 xp_namelen = (int)STRLEN(xp_name);
12759
12760                 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
12761                                                              &xp_arg) == FAIL)
12762                     return;
12763             }
12764         }
12765
12766         if (defstr != NULL)
12767             rettv->vval.v_string =
12768                 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
12769                                   xp_type, xp_arg);
12770
12771         vim_free(xp_arg);
12772
12773         /* since the user typed this, no need to wait for return */
12774         need_wait_return = FALSE;
12775         msg_didout = FALSE;
12776     }
12777     cmd_silent = cmd_silent_save;
12778 }
12779
12780 /*
12781  * "input()" function
12782  *     Also handles inputsecret() when inputsecret is set.
12783  */
12784     static void
12785 f_input(argvars, rettv)
12786     typval_T    *argvars;
12787     typval_T    *rettv;
12788 {
12789     get_user_input(argvars, rettv, FALSE);
12790 }
12791
12792 /*
12793  * "inputdialog()" function
12794  */
12795     static void
12796 f_inputdialog(argvars, rettv)
12797     typval_T    *argvars;
12798     typval_T    *rettv;
12799 {
12800 #if defined(FEAT_GUI_TEXTDIALOG)
12801     /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
12802     if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
12803     {
12804         char_u  *message;
12805         char_u  buf[NUMBUFLEN];
12806         char_u  *defstr = (char_u *)"";
12807
12808         message = get_tv_string_chk(&argvars[0]);
12809         if (argvars[1].v_type != VAR_UNKNOWN
12810                 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
12811             vim_strncpy(IObuff, defstr, IOSIZE - 1);
12812         else
12813             IObuff[0] = NUL;
12814         if (message != NULL && defstr != NULL
12815                 && do_dialog(VIM_QUESTION, NULL, message,
12816                           (char_u *)_("&OK\n&Cancel"), 1, IObuff, FALSE) == 1)
12817             rettv->vval.v_string = vim_strsave(IObuff);
12818         else
12819         {
12820             if (message != NULL && defstr != NULL
12821                                         && argvars[1].v_type != VAR_UNKNOWN
12822                                         && argvars[2].v_type != VAR_UNKNOWN)
12823                 rettv->vval.v_string = vim_strsave(
12824                                       get_tv_string_buf(&argvars[2], buf));
12825             else
12826                 rettv->vval.v_string = NULL;
12827         }
12828         rettv->v_type = VAR_STRING;
12829     }
12830     else
12831 #endif
12832         get_user_input(argvars, rettv, TRUE);
12833 }
12834
12835 /*
12836  * "inputlist()" function
12837  */
12838     static void
12839 f_inputlist(argvars, rettv)
12840     typval_T    *argvars;
12841     typval_T    *rettv;
12842 {
12843     listitem_T  *li;
12844     int         selected;
12845     int         mouse_used;
12846
12847 #ifdef NO_CONSOLE_INPUT
12848     /* While starting up, there is no place to enter text. */
12849     if (no_console_input())
12850         return;
12851 #endif
12852     if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
12853     {
12854         EMSG2(_(e_listarg), "inputlist()");
12855         return;
12856     }
12857
12858     msg_start();
12859     msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
12860     lines_left = Rows;  /* avoid more prompt */
12861     msg_scroll = TRUE;
12862     msg_clr_eos();
12863
12864     for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
12865     {
12866         msg_puts(get_tv_string(&li->li_tv));
12867         msg_putchar('\n');
12868     }
12869
12870     /* Ask for choice. */
12871     selected = prompt_for_number(&mouse_used);
12872     if (mouse_used)
12873         selected -= lines_left;
12874
12875     rettv->vval.v_number = selected;
12876 }
12877
12878
12879 static garray_T     ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
12880
12881 /*
12882  * "inputrestore()" function
12883  */
12884     static void
12885 f_inputrestore(argvars, rettv)
12886     typval_T    *argvars UNUSED;
12887     typval_T    *rettv;
12888 {
12889     if (ga_userinput.ga_len > 0)
12890     {
12891         --ga_userinput.ga_len;
12892         restore_typeahead((tasave_T *)(ga_userinput.ga_data)
12893                                                        + ga_userinput.ga_len);
12894         /* default return is zero == OK */
12895     }
12896     else if (p_verbose > 1)
12897     {
12898         verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
12899         rettv->vval.v_number = 1; /* Failed */
12900     }
12901 }
12902
12903 /*
12904  * "inputsave()" function
12905  */
12906     static void
12907 f_inputsave(argvars, rettv)
12908     typval_T    *argvars UNUSED;
12909     typval_T    *rettv;
12910 {
12911     /* Add an entry to the stack of typeahead storage. */
12912     if (ga_grow(&ga_userinput, 1) == OK)
12913     {
12914         save_typeahead((tasave_T *)(ga_userinput.ga_data)
12915                                                        + ga_userinput.ga_len);
12916         ++ga_userinput.ga_len;
12917         /* default return is zero == OK */
12918     }
12919     else
12920         rettv->vval.v_number = 1; /* Failed */
12921 }
12922
12923 /*
12924  * "inputsecret()" function
12925  */
12926     static void
12927 f_inputsecret(argvars, rettv)
12928     typval_T    *argvars;
12929     typval_T    *rettv;
12930 {
12931     ++cmdline_star;
12932     ++inputsecret_flag;
12933     f_input(argvars, rettv);
12934     --cmdline_star;
12935     --inputsecret_flag;
12936 }
12937
12938 /*
12939  * "insert()" function
12940  */
12941     static void
12942 f_insert(argvars, rettv)
12943     typval_T    *argvars;
12944     typval_T    *rettv;
12945 {
12946     long        before = 0;
12947     listitem_T  *item;
12948     list_T      *l;
12949     int         error = FALSE;
12950
12951     if (argvars[0].v_type != VAR_LIST)
12952         EMSG2(_(e_listarg), "insert()");
12953     else if ((l = argvars[0].vval.v_list) != NULL
12954             && !tv_check_lock(l->lv_lock, (char_u *)_("insert() argument")))
12955     {
12956         if (argvars[2].v_type != VAR_UNKNOWN)
12957             before = get_tv_number_chk(&argvars[2], &error);
12958         if (error)
12959             return;             /* type error; errmsg already given */
12960
12961         if (before == l->lv_len)
12962             item = NULL;
12963         else
12964         {
12965             item = list_find(l, before);
12966             if (item == NULL)
12967             {
12968                 EMSGN(_(e_listidx), before);
12969                 l = NULL;
12970             }
12971         }
12972         if (l != NULL)
12973         {
12974             list_insert_tv(l, &argvars[1], item);
12975             copy_tv(&argvars[0], rettv);
12976         }
12977     }
12978 }
12979
12980 /*
12981  * "invert(expr)" function
12982  */
12983     static void
12984 f_invert(argvars, rettv)
12985     typval_T    *argvars;
12986     typval_T    *rettv;
12987 {
12988     rettv->vval.v_number = ~get_tv_number_chk(&argvars[0], NULL);
12989 }
12990
12991 /*
12992  * "isdirectory()" function
12993  */
12994     static void
12995 f_isdirectory(argvars, rettv)
12996     typval_T    *argvars;
12997     typval_T    *rettv;
12998 {
12999     rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
13000 }
13001
13002 /*
13003  * "islocked()" function
13004  */
13005     static void
13006 f_islocked(argvars, rettv)
13007     typval_T    *argvars;
13008     typval_T    *rettv;
13009 {
13010     lval_T      lv;
13011     char_u      *end;
13012     dictitem_T  *di;
13013
13014     rettv->vval.v_number = -1;
13015     end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
13016                                                              FNE_CHECK_START);
13017     if (end != NULL && lv.ll_name != NULL)
13018     {
13019         if (*end != NUL)
13020             EMSG(_(e_trailing));
13021         else
13022         {
13023             if (lv.ll_tv == NULL)
13024             {
13025                 if (check_changedtick(lv.ll_name))
13026                     rettv->vval.v_number = 1;       /* always locked */
13027                 else
13028                 {
13029                     di = find_var(lv.ll_name, NULL);
13030                     if (di != NULL)
13031                     {
13032                         /* Consider a variable locked when:
13033                          * 1. the variable itself is locked
13034                          * 2. the value of the variable is locked.
13035                          * 3. the List or Dict value is locked.
13036                          */
13037                         rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
13038                                                   || tv_islocked(&di->di_tv));
13039                     }
13040                 }
13041             }
13042             else if (lv.ll_range)
13043                 EMSG(_("E786: Range not allowed"));
13044             else if (lv.ll_newkey != NULL)
13045                 EMSG2(_(e_dictkey), lv.ll_newkey);
13046             else if (lv.ll_list != NULL)
13047                 /* List item. */
13048                 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
13049             else
13050                 /* Dictionary item. */
13051                 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
13052         }
13053     }
13054
13055     clear_lval(&lv);
13056 }
13057
13058 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
13059
13060 /*
13061  * Turn a dict into a list:
13062  * "what" == 0: list of keys
13063  * "what" == 1: list of values
13064  * "what" == 2: list of items
13065  */
13066     static void
13067 dict_list(argvars, rettv, what)
13068     typval_T    *argvars;
13069     typval_T    *rettv;
13070     int         what;
13071 {
13072     list_T      *l2;
13073     dictitem_T  *di;
13074     hashitem_T  *hi;
13075     listitem_T  *li;
13076     listitem_T  *li2;
13077     dict_T      *d;
13078     int         todo;
13079
13080     if (argvars[0].v_type != VAR_DICT)
13081     {
13082         EMSG(_(e_dictreq));
13083         return;
13084     }
13085     if ((d = argvars[0].vval.v_dict) == NULL)
13086         return;
13087
13088     if (rettv_list_alloc(rettv) == FAIL)
13089         return;
13090
13091     todo = (int)d->dv_hashtab.ht_used;
13092     for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13093     {
13094         if (!HASHITEM_EMPTY(hi))
13095         {
13096             --todo;
13097             di = HI2DI(hi);
13098
13099             li = listitem_alloc();
13100             if (li == NULL)
13101                 break;
13102             list_append(rettv->vval.v_list, li);
13103
13104             if (what == 0)
13105             {
13106                 /* keys() */
13107                 li->li_tv.v_type = VAR_STRING;
13108                 li->li_tv.v_lock = 0;
13109                 li->li_tv.vval.v_string = vim_strsave(di->di_key);
13110             }
13111             else if (what == 1)
13112             {
13113                 /* values() */
13114                 copy_tv(&di->di_tv, &li->li_tv);
13115             }
13116             else
13117             {
13118                 /* items() */
13119                 l2 = list_alloc();
13120                 li->li_tv.v_type = VAR_LIST;
13121                 li->li_tv.v_lock = 0;
13122                 li->li_tv.vval.v_list = l2;
13123                 if (l2 == NULL)
13124                     break;
13125                 ++l2->lv_refcount;
13126
13127                 li2 = listitem_alloc();
13128                 if (li2 == NULL)
13129                     break;
13130                 list_append(l2, li2);
13131                 li2->li_tv.v_type = VAR_STRING;
13132                 li2->li_tv.v_lock = 0;
13133                 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
13134
13135                 li2 = listitem_alloc();
13136                 if (li2 == NULL)
13137                     break;
13138                 list_append(l2, li2);
13139                 copy_tv(&di->di_tv, &li2->li_tv);
13140             }
13141         }
13142     }
13143 }
13144
13145 /*
13146  * "items(dict)" function
13147  */
13148     static void
13149 f_items(argvars, rettv)
13150     typval_T    *argvars;
13151     typval_T    *rettv;
13152 {
13153     dict_list(argvars, rettv, 2);
13154 }
13155
13156 /*
13157  * "join()" function
13158  */
13159     static void
13160 f_join(argvars, rettv)
13161     typval_T    *argvars;
13162     typval_T    *rettv;
13163 {
13164     garray_T    ga;
13165     char_u      *sep;
13166
13167     if (argvars[0].v_type != VAR_LIST)
13168     {
13169         EMSG(_(e_listreq));
13170         return;
13171     }
13172     if (argvars[0].vval.v_list == NULL)
13173         return;
13174     if (argvars[1].v_type == VAR_UNKNOWN)
13175         sep = (char_u *)" ";
13176     else
13177         sep = get_tv_string_chk(&argvars[1]);
13178
13179     rettv->v_type = VAR_STRING;
13180
13181     if (sep != NULL)
13182     {
13183         ga_init2(&ga, (int)sizeof(char), 80);
13184         list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
13185         ga_append(&ga, NUL);
13186         rettv->vval.v_string = (char_u *)ga.ga_data;
13187     }
13188     else
13189         rettv->vval.v_string = NULL;
13190 }
13191
13192 /*
13193  * "keys()" function
13194  */
13195     static void
13196 f_keys(argvars, rettv)
13197     typval_T    *argvars;
13198     typval_T    *rettv;
13199 {
13200     dict_list(argvars, rettv, 0);
13201 }
13202
13203 /*
13204  * "last_buffer_nr()" function.
13205  */
13206     static void
13207 f_last_buffer_nr(argvars, rettv)
13208     typval_T    *argvars UNUSED;
13209     typval_T    *rettv;
13210 {
13211     int         n = 0;
13212     buf_T       *buf;
13213
13214     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
13215         if (n < buf->b_fnum)
13216             n = buf->b_fnum;
13217
13218     rettv->vval.v_number = n;
13219 }
13220
13221 /*
13222  * "len()" function
13223  */
13224     static void
13225 f_len(argvars, rettv)
13226     typval_T    *argvars;
13227     typval_T    *rettv;
13228 {
13229     switch (argvars[0].v_type)
13230     {
13231         case VAR_STRING:
13232         case VAR_NUMBER:
13233             rettv->vval.v_number = (varnumber_T)STRLEN(
13234                                                get_tv_string(&argvars[0]));
13235             break;
13236         case VAR_LIST:
13237             rettv->vval.v_number = list_len(argvars[0].vval.v_list);
13238             break;
13239         case VAR_DICT:
13240             rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
13241             break;
13242         default:
13243             EMSG(_("E701: Invalid type for len()"));
13244             break;
13245     }
13246 }
13247
13248 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
13249
13250     static void
13251 libcall_common(argvars, rettv, type)
13252     typval_T    *argvars;
13253     typval_T    *rettv;
13254     int         type;
13255 {
13256 #ifdef FEAT_LIBCALL
13257     char_u              *string_in;
13258     char_u              **string_result;
13259     int                 nr_result;
13260 #endif
13261
13262     rettv->v_type = type;
13263     if (type != VAR_NUMBER)
13264         rettv->vval.v_string = NULL;
13265
13266     if (check_restricted() || check_secure())
13267         return;
13268
13269 #ifdef FEAT_LIBCALL
13270     /* The first two args must be strings, otherwise its meaningless */
13271     if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
13272     {
13273         string_in = NULL;
13274         if (argvars[2].v_type == VAR_STRING)
13275             string_in = argvars[2].vval.v_string;
13276         if (type == VAR_NUMBER)
13277             string_result = NULL;
13278         else
13279             string_result = &rettv->vval.v_string;
13280         if (mch_libcall(argvars[0].vval.v_string,
13281                              argvars[1].vval.v_string,
13282                              string_in,
13283                              argvars[2].vval.v_number,
13284                              string_result,
13285                              &nr_result) == OK
13286                 && type == VAR_NUMBER)
13287             rettv->vval.v_number = nr_result;
13288     }
13289 #endif
13290 }
13291
13292 /*
13293  * "libcall()" function
13294  */
13295     static void
13296 f_libcall(argvars, rettv)
13297     typval_T    *argvars;
13298     typval_T    *rettv;
13299 {
13300     libcall_common(argvars, rettv, VAR_STRING);
13301 }
13302
13303 /*
13304  * "libcallnr()" function
13305  */
13306     static void
13307 f_libcallnr(argvars, rettv)
13308     typval_T    *argvars;
13309     typval_T    *rettv;
13310 {
13311     libcall_common(argvars, rettv, VAR_NUMBER);
13312 }
13313
13314 /*
13315  * "line(string)" function
13316  */
13317     static void
13318 f_line(argvars, rettv)
13319     typval_T    *argvars;
13320     typval_T    *rettv;
13321 {
13322     linenr_T    lnum = 0;
13323     pos_T       *fp;
13324     int         fnum;
13325
13326     fp = var2fpos(&argvars[0], TRUE, &fnum);
13327     if (fp != NULL)
13328         lnum = fp->lnum;
13329     rettv->vval.v_number = lnum;
13330 }
13331
13332 /*
13333  * "line2byte(lnum)" function
13334  */
13335     static void
13336 f_line2byte(argvars, rettv)
13337     typval_T    *argvars UNUSED;
13338     typval_T    *rettv;
13339 {
13340 #ifndef FEAT_BYTEOFF
13341     rettv->vval.v_number = -1;
13342 #else
13343     linenr_T    lnum;
13344
13345     lnum = get_tv_lnum(argvars);
13346     if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
13347         rettv->vval.v_number = -1;
13348     else
13349         rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
13350     if (rettv->vval.v_number >= 0)
13351         ++rettv->vval.v_number;
13352 #endif
13353 }
13354
13355 /*
13356  * "lispindent(lnum)" function
13357  */
13358     static void
13359 f_lispindent(argvars, rettv)
13360     typval_T    *argvars;
13361     typval_T    *rettv;
13362 {
13363 #ifdef FEAT_LISP
13364     pos_T       pos;
13365     linenr_T    lnum;
13366
13367     pos = curwin->w_cursor;
13368     lnum = get_tv_lnum(argvars);
13369     if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
13370     {
13371         curwin->w_cursor.lnum = lnum;
13372         rettv->vval.v_number = get_lisp_indent();
13373         curwin->w_cursor = pos;
13374     }
13375     else
13376 #endif
13377         rettv->vval.v_number = -1;
13378 }
13379
13380 /*
13381  * "localtime()" function
13382  */
13383     static void
13384 f_localtime(argvars, rettv)
13385     typval_T    *argvars UNUSED;
13386     typval_T    *rettv;
13387 {
13388     rettv->vval.v_number = (varnumber_T)time(NULL);
13389 }
13390
13391 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
13392
13393     static void
13394 get_maparg(argvars, rettv, exact)
13395     typval_T    *argvars;
13396     typval_T    *rettv;
13397     int         exact;
13398 {
13399     char_u      *keys;
13400     char_u      *which;
13401     char_u      buf[NUMBUFLEN];
13402     char_u      *keys_buf = NULL;
13403     char_u      *rhs;
13404     int         mode;
13405     int         abbr = FALSE;
13406     int         get_dict = FALSE;
13407     mapblock_T  *mp;
13408     int         buffer_local;
13409
13410     /* return empty string for failure */
13411     rettv->v_type = VAR_STRING;
13412     rettv->vval.v_string = NULL;
13413
13414     keys = get_tv_string(&argvars[0]);
13415     if (*keys == NUL)
13416         return;
13417
13418     if (argvars[1].v_type != VAR_UNKNOWN)
13419     {
13420         which = get_tv_string_buf_chk(&argvars[1], buf);
13421         if (argvars[2].v_type != VAR_UNKNOWN)
13422         {
13423             abbr = get_tv_number(&argvars[2]);
13424             if (argvars[3].v_type != VAR_UNKNOWN)
13425                 get_dict = get_tv_number(&argvars[3]);
13426         }
13427     }
13428     else
13429         which = (char_u *)"";
13430     if (which == NULL)
13431         return;
13432
13433     mode = get_map_mode(&which, 0);
13434
13435     keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
13436     rhs = check_map(keys, mode, exact, FALSE, abbr, &mp, &buffer_local);
13437     vim_free(keys_buf);
13438
13439     if (!get_dict)
13440     {
13441         /* Return a string. */
13442         if (rhs != NULL)
13443             rettv->vval.v_string = str2special_save(rhs, FALSE);
13444
13445     }
13446     else if (rettv_dict_alloc(rettv) != FAIL && rhs != NULL)
13447     {
13448         /* Return a dictionary. */
13449         char_u      *lhs = str2special_save(mp->m_keys, TRUE);
13450         char_u      *mapmode = map_mode_to_chars(mp->m_mode);
13451         dict_T      *dict = rettv->vval.v_dict;
13452
13453         dict_add_nr_str(dict, "lhs",     0L, lhs);
13454         dict_add_nr_str(dict, "rhs",     0L, mp->m_orig_str);
13455         dict_add_nr_str(dict, "noremap", mp->m_noremap ? 1L : 0L , NULL);
13456         dict_add_nr_str(dict, "expr",    mp->m_expr    ? 1L : 0L, NULL);
13457         dict_add_nr_str(dict, "silent",  mp->m_silent  ? 1L : 0L, NULL);
13458         dict_add_nr_str(dict, "sid",     (long)mp->m_script_ID, NULL);
13459         dict_add_nr_str(dict, "buffer",  (long)buffer_local, NULL);
13460         dict_add_nr_str(dict, "mode",    0L, mapmode);
13461
13462         vim_free(lhs);
13463         vim_free(mapmode);
13464     }
13465 }
13466
13467 #ifdef FEAT_FLOAT
13468 /*
13469  * "log()" function
13470  */
13471     static void
13472 f_log(argvars, rettv)
13473     typval_T    *argvars;
13474     typval_T    *rettv;
13475 {
13476     float_T     f;
13477
13478     rettv->v_type = VAR_FLOAT;
13479     if (get_float_arg(argvars, &f) == OK)
13480         rettv->vval.v_float = log(f);
13481     else
13482         rettv->vval.v_float = 0.0;
13483 }
13484
13485 /*
13486  * "log10()" function
13487  */
13488     static void
13489 f_log10(argvars, rettv)
13490     typval_T    *argvars;
13491     typval_T    *rettv;
13492 {
13493     float_T     f;
13494
13495     rettv->v_type = VAR_FLOAT;
13496     if (get_float_arg(argvars, &f) == OK)
13497         rettv->vval.v_float = log10(f);
13498     else
13499         rettv->vval.v_float = 0.0;
13500 }
13501 #endif
13502
13503 /*
13504  * "map()" function
13505  */
13506     static void
13507 f_map(argvars, rettv)
13508     typval_T    *argvars;
13509     typval_T    *rettv;
13510 {
13511     filter_map(argvars, rettv, TRUE);
13512 }
13513
13514 /*
13515  * "maparg()" function
13516  */
13517     static void
13518 f_maparg(argvars, rettv)
13519     typval_T    *argvars;
13520     typval_T    *rettv;
13521 {
13522     get_maparg(argvars, rettv, TRUE);
13523 }
13524
13525 /*
13526  * "mapcheck()" function
13527  */
13528     static void
13529 f_mapcheck(argvars, rettv)
13530     typval_T    *argvars;
13531     typval_T    *rettv;
13532 {
13533     get_maparg(argvars, rettv, FALSE);
13534 }
13535
13536 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
13537
13538     static void
13539 find_some_match(argvars, rettv, type)
13540     typval_T    *argvars;
13541     typval_T    *rettv;
13542     int         type;
13543 {
13544     char_u      *str = NULL;
13545     char_u      *expr = NULL;
13546     char_u      *pat;
13547     regmatch_T  regmatch;
13548     char_u      patbuf[NUMBUFLEN];
13549     char_u      strbuf[NUMBUFLEN];
13550     char_u      *save_cpo;
13551     long        start = 0;
13552     long        nth = 1;
13553     colnr_T     startcol = 0;
13554     int         match = 0;
13555     list_T      *l = NULL;
13556     listitem_T  *li = NULL;
13557     long        idx = 0;
13558     char_u      *tofree = NULL;
13559
13560     /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
13561     save_cpo = p_cpo;
13562     p_cpo = (char_u *)"";
13563
13564     rettv->vval.v_number = -1;
13565     if (type == 3)
13566     {
13567         /* return empty list when there are no matches */
13568         if (rettv_list_alloc(rettv) == FAIL)
13569             goto theend;
13570     }
13571     else if (type == 2)
13572     {
13573         rettv->v_type = VAR_STRING;
13574         rettv->vval.v_string = NULL;
13575     }
13576
13577     if (argvars[0].v_type == VAR_LIST)
13578     {
13579         if ((l = argvars[0].vval.v_list) == NULL)
13580             goto theend;
13581         li = l->lv_first;
13582     }
13583     else
13584         expr = str = get_tv_string(&argvars[0]);
13585
13586     pat = get_tv_string_buf_chk(&argvars[1], patbuf);
13587     if (pat == NULL)
13588         goto theend;
13589
13590     if (argvars[2].v_type != VAR_UNKNOWN)
13591     {
13592         int         error = FALSE;
13593
13594         start = get_tv_number_chk(&argvars[2], &error);
13595         if (error)
13596             goto theend;
13597         if (l != NULL)
13598         {
13599             li = list_find(l, start);
13600             if (li == NULL)
13601                 goto theend;
13602             idx = l->lv_idx;    /* use the cached index */
13603         }
13604         else
13605         {
13606             if (start < 0)
13607                 start = 0;
13608             if (start > (long)STRLEN(str))
13609                 goto theend;
13610             /* When "count" argument is there ignore matches before "start",
13611              * otherwise skip part of the string.  Differs when pattern is "^"
13612              * or "\<". */
13613             if (argvars[3].v_type != VAR_UNKNOWN)
13614                 startcol = start;
13615             else
13616                 str += start;
13617         }
13618
13619         if (argvars[3].v_type != VAR_UNKNOWN)
13620             nth = get_tv_number_chk(&argvars[3], &error);
13621         if (error)
13622             goto theend;
13623     }
13624
13625     regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
13626     if (regmatch.regprog != NULL)
13627     {
13628         regmatch.rm_ic = p_ic;
13629
13630         for (;;)
13631         {
13632             if (l != NULL)
13633             {
13634                 if (li == NULL)
13635                 {
13636                     match = FALSE;
13637                     break;
13638                 }
13639                 vim_free(tofree);
13640                 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
13641                 if (str == NULL)
13642                     break;
13643             }
13644
13645             match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
13646
13647             if (match && --nth <= 0)
13648                 break;
13649             if (l == NULL && !match)
13650                 break;
13651
13652             /* Advance to just after the match. */
13653             if (l != NULL)
13654             {
13655                 li = li->li_next;
13656                 ++idx;
13657             }
13658             else
13659             {
13660 #ifdef FEAT_MBYTE
13661                 startcol = (colnr_T)(regmatch.startp[0]
13662                                     + (*mb_ptr2len)(regmatch.startp[0]) - str);
13663 #else
13664                 startcol = (colnr_T)(regmatch.startp[0] + 1 - str);
13665 #endif
13666             }
13667         }
13668
13669         if (match)
13670         {
13671             if (type == 3)
13672             {
13673                 int i;
13674
13675                 /* return list with matched string and submatches */
13676                 for (i = 0; i < NSUBEXP; ++i)
13677                 {
13678                     if (regmatch.endp[i] == NULL)
13679                     {
13680                         if (list_append_string(rettv->vval.v_list,
13681                                                      (char_u *)"", 0) == FAIL)
13682                             break;
13683                     }
13684                     else if (list_append_string(rettv->vval.v_list,
13685                                 regmatch.startp[i],
13686                                 (int)(regmatch.endp[i] - regmatch.startp[i]))
13687                             == FAIL)
13688                         break;
13689                 }
13690             }
13691             else if (type == 2)
13692             {
13693                 /* return matched string */
13694                 if (l != NULL)
13695                     copy_tv(&li->li_tv, rettv);
13696                 else
13697                     rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
13698                                 (int)(regmatch.endp[0] - regmatch.startp[0]));
13699             }
13700             else if (l != NULL)
13701                 rettv->vval.v_number = idx;
13702             else
13703             {
13704                 if (type != 0)
13705                     rettv->vval.v_number =
13706                                       (varnumber_T)(regmatch.startp[0] - str);
13707                 else
13708                     rettv->vval.v_number =
13709                                         (varnumber_T)(regmatch.endp[0] - str);
13710                 rettv->vval.v_number += (varnumber_T)(str - expr);
13711             }
13712         }
13713         vim_free(regmatch.regprog);
13714     }
13715
13716 theend:
13717     vim_free(tofree);
13718     p_cpo = save_cpo;
13719 }
13720
13721 /*
13722  * "match()" function
13723  */
13724     static void
13725 f_match(argvars, rettv)
13726     typval_T    *argvars;
13727     typval_T    *rettv;
13728 {
13729     find_some_match(argvars, rettv, 1);
13730 }
13731
13732 /*
13733  * "matchadd()" function
13734  */
13735     static void
13736 f_matchadd(argvars, rettv)
13737     typval_T    *argvars;
13738     typval_T    *rettv;
13739 {
13740 #ifdef FEAT_SEARCH_EXTRA
13741     char_u      buf[NUMBUFLEN];
13742     char_u      *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
13743     char_u      *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
13744     int         prio = 10;      /* default priority */
13745     int         id = -1;
13746     int         error = FALSE;
13747
13748     rettv->vval.v_number = -1;
13749
13750     if (grp == NULL || pat == NULL)
13751         return;
13752     if (argvars[2].v_type != VAR_UNKNOWN)
13753     {
13754         prio = get_tv_number_chk(&argvars[2], &error);
13755         if (argvars[3].v_type != VAR_UNKNOWN)
13756             id = get_tv_number_chk(&argvars[3], &error);
13757     }
13758     if (error == TRUE)
13759         return;
13760     if (id >= 1 && id <= 3)
13761     {
13762         EMSGN("E798: ID is reserved for \":match\": %ld", id);
13763         return;
13764     }
13765
13766     rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
13767 #endif
13768 }
13769
13770 /*
13771  * "matcharg()" function
13772  */
13773     static void
13774 f_matcharg(argvars, rettv)
13775     typval_T    *argvars;
13776     typval_T    *rettv;
13777 {
13778     if (rettv_list_alloc(rettv) == OK)
13779     {
13780 #ifdef FEAT_SEARCH_EXTRA
13781         int         id = get_tv_number(&argvars[0]);
13782         matchitem_T *m;
13783
13784         if (id >= 1 && id <= 3)
13785         {
13786             if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
13787             {
13788                 list_append_string(rettv->vval.v_list,
13789                                                 syn_id2name(m->hlg_id), -1);
13790                 list_append_string(rettv->vval.v_list, m->pattern, -1);
13791             }
13792             else
13793             {
13794                 list_append_string(rettv->vval.v_list, NUL, -1);
13795                 list_append_string(rettv->vval.v_list, NUL, -1);
13796             }
13797         }
13798 #endif
13799     }
13800 }
13801
13802 /*
13803  * "matchdelete()" function
13804  */
13805     static void
13806 f_matchdelete(argvars, rettv)
13807     typval_T    *argvars;
13808     typval_T    *rettv;
13809 {
13810 #ifdef FEAT_SEARCH_EXTRA
13811     rettv->vval.v_number = match_delete(curwin,
13812                                        (int)get_tv_number(&argvars[0]), TRUE);
13813 #endif
13814 }
13815
13816 /*
13817  * "matchend()" function
13818  */
13819     static void
13820 f_matchend(argvars, rettv)
13821     typval_T    *argvars;
13822     typval_T    *rettv;
13823 {
13824     find_some_match(argvars, rettv, 0);
13825 }
13826
13827 /*
13828  * "matchlist()" function
13829  */
13830     static void
13831 f_matchlist(argvars, rettv)
13832     typval_T    *argvars;
13833     typval_T    *rettv;
13834 {
13835     find_some_match(argvars, rettv, 3);
13836 }
13837
13838 /*
13839  * "matchstr()" function
13840  */
13841     static void
13842 f_matchstr(argvars, rettv)
13843     typval_T    *argvars;
13844     typval_T    *rettv;
13845 {
13846     find_some_match(argvars, rettv, 2);
13847 }
13848
13849 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
13850
13851     static void
13852 max_min(argvars, rettv, domax)
13853     typval_T    *argvars;
13854     typval_T    *rettv;
13855     int         domax;
13856 {
13857     long        n = 0;
13858     long        i;
13859     int         error = FALSE;
13860
13861     if (argvars[0].v_type == VAR_LIST)
13862     {
13863         list_T          *l;
13864         listitem_T      *li;
13865
13866         l = argvars[0].vval.v_list;
13867         if (l != NULL)
13868         {
13869             li = l->lv_first;
13870             if (li != NULL)
13871             {
13872                 n = get_tv_number_chk(&li->li_tv, &error);
13873                 for (;;)
13874                 {
13875                     li = li->li_next;
13876                     if (li == NULL)
13877                         break;
13878                     i = get_tv_number_chk(&li->li_tv, &error);
13879                     if (domax ? i > n : i < n)
13880                         n = i;
13881                 }
13882             }
13883         }
13884     }
13885     else if (argvars[0].v_type == VAR_DICT)
13886     {
13887         dict_T          *d;
13888         int             first = TRUE;
13889         hashitem_T      *hi;
13890         int             todo;
13891
13892         d = argvars[0].vval.v_dict;
13893         if (d != NULL)
13894         {
13895             todo = (int)d->dv_hashtab.ht_used;
13896             for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13897             {
13898                 if (!HASHITEM_EMPTY(hi))
13899                 {
13900                     --todo;
13901                     i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
13902                     if (first)
13903                     {
13904                         n = i;
13905                         first = FALSE;
13906                     }
13907                     else if (domax ? i > n : i < n)
13908                         n = i;
13909                 }
13910             }
13911         }
13912     }
13913     else
13914         EMSG(_(e_listdictarg));
13915     rettv->vval.v_number = error ? 0 : n;
13916 }
13917
13918 /*
13919  * "max()" function
13920  */
13921     static void
13922 f_max(argvars, rettv)
13923     typval_T    *argvars;
13924     typval_T    *rettv;
13925 {
13926     max_min(argvars, rettv, TRUE);
13927 }
13928
13929 /*
13930  * "min()" function
13931  */
13932     static void
13933 f_min(argvars, rettv)
13934     typval_T    *argvars;
13935     typval_T    *rettv;
13936 {
13937     max_min(argvars, rettv, FALSE);
13938 }
13939
13940 static int mkdir_recurse __ARGS((char_u *dir, int prot));
13941
13942 /*
13943  * Create the directory in which "dir" is located, and higher levels when
13944  * needed.
13945  */
13946     static int
13947 mkdir_recurse(dir, prot)
13948     char_u      *dir;
13949     int         prot;
13950 {
13951     char_u      *p;
13952     char_u      *updir;
13953     int         r = FAIL;
13954
13955     /* Get end of directory name in "dir".
13956      * We're done when it's "/" or "c:/". */
13957     p = gettail_sep(dir);
13958     if (p <= get_past_head(dir))
13959         return OK;
13960
13961     /* If the directory exists we're done.  Otherwise: create it.*/
13962     updir = vim_strnsave(dir, (int)(p - dir));
13963     if (updir == NULL)
13964         return FAIL;
13965     if (mch_isdir(updir))
13966         r = OK;
13967     else if (mkdir_recurse(updir, prot) == OK)
13968         r = vim_mkdir_emsg(updir, prot);
13969     vim_free(updir);
13970     return r;
13971 }
13972
13973 #ifdef vim_mkdir
13974 /*
13975  * "mkdir()" function
13976  */
13977     static void
13978 f_mkdir(argvars, rettv)
13979     typval_T    *argvars;
13980     typval_T    *rettv;
13981 {
13982     char_u      *dir;
13983     char_u      buf[NUMBUFLEN];
13984     int         prot = 0755;
13985
13986     rettv->vval.v_number = FAIL;
13987     if (check_restricted() || check_secure())
13988         return;
13989
13990     dir = get_tv_string_buf(&argvars[0], buf);
13991     if (argvars[1].v_type != VAR_UNKNOWN)
13992     {
13993         if (argvars[2].v_type != VAR_UNKNOWN)
13994             prot = get_tv_number_chk(&argvars[2], NULL);
13995         if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
13996             mkdir_recurse(dir, prot);
13997     }
13998     rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
13999 }
14000 #endif
14001
14002 /*
14003  * "mode()" function
14004  */
14005     static void
14006 f_mode(argvars, rettv)
14007     typval_T    *argvars;
14008     typval_T    *rettv;
14009 {
14010     char_u      buf[3];
14011
14012     buf[1] = NUL;
14013     buf[2] = NUL;
14014
14015 #ifdef FEAT_VISUAL
14016     if (VIsual_active)
14017     {
14018         if (VIsual_select)
14019             buf[0] = VIsual_mode + 's' - 'v';
14020         else
14021             buf[0] = VIsual_mode;
14022     }
14023     else
14024 #endif
14025         if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
14026                 || State == CONFIRM)
14027     {
14028         buf[0] = 'r';
14029         if (State == ASKMORE)
14030             buf[1] = 'm';
14031         else if (State == CONFIRM)
14032             buf[1] = '?';
14033     }
14034     else if (State == EXTERNCMD)
14035         buf[0] = '!';
14036     else if (State & INSERT)
14037     {
14038 #ifdef FEAT_VREPLACE
14039         if (State & VREPLACE_FLAG)
14040         {
14041             buf[0] = 'R';
14042             buf[1] = 'v';
14043         }
14044         else
14045 #endif
14046         if (State & REPLACE_FLAG)
14047             buf[0] = 'R';
14048         else
14049             buf[0] = 'i';
14050     }
14051     else if (State & CMDLINE)
14052     {
14053         buf[0] = 'c';
14054         if (exmode_active)
14055             buf[1] = 'v';
14056     }
14057     else if (exmode_active)
14058     {
14059         buf[0] = 'c';
14060         buf[1] = 'e';
14061     }
14062     else
14063     {
14064         buf[0] = 'n';
14065         if (finish_op)
14066             buf[1] = 'o';
14067     }
14068
14069     /* Clear out the minor mode when the argument is not a non-zero number or
14070      * non-empty string.  */
14071     if (!non_zero_arg(&argvars[0]))
14072         buf[1] = NUL;
14073
14074     rettv->vval.v_string = vim_strsave(buf);
14075     rettv->v_type = VAR_STRING;
14076 }
14077
14078 #ifdef FEAT_MZSCHEME
14079 /*
14080  * "mzeval()" function
14081  */
14082     static void
14083 f_mzeval(argvars, rettv)
14084     typval_T    *argvars;
14085     typval_T    *rettv;
14086 {
14087     char_u      *str;
14088     char_u      buf[NUMBUFLEN];
14089
14090     str = get_tv_string_buf(&argvars[0], buf);
14091     do_mzeval(str, rettv);
14092 }
14093 #endif
14094
14095 /*
14096  * "nextnonblank()" function
14097  */
14098     static void
14099 f_nextnonblank(argvars, rettv)
14100     typval_T    *argvars;
14101     typval_T    *rettv;
14102 {
14103     linenr_T    lnum;
14104
14105     for (lnum = get_tv_lnum(argvars); ; ++lnum)
14106     {
14107         if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
14108         {
14109             lnum = 0;
14110             break;
14111         }
14112         if (*skipwhite(ml_get(lnum)) != NUL)
14113             break;
14114     }
14115     rettv->vval.v_number = lnum;
14116 }
14117
14118 /*
14119  * "nr2char()" function
14120  */
14121     static void
14122 f_nr2char(argvars, rettv)
14123     typval_T    *argvars;
14124     typval_T    *rettv;
14125 {
14126     char_u      buf[NUMBUFLEN];
14127
14128 #ifdef FEAT_MBYTE
14129     if (has_mbyte)
14130         buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
14131     else
14132 #endif
14133     {
14134         buf[0] = (char_u)get_tv_number(&argvars[0]);
14135         buf[1] = NUL;
14136     }
14137     rettv->v_type = VAR_STRING;
14138     rettv->vval.v_string = vim_strsave(buf);
14139 }
14140
14141 /*
14142  * "or(expr, expr)" function
14143  */
14144     static void
14145 f_or(argvars, rettv)
14146     typval_T    *argvars;
14147     typval_T    *rettv;
14148 {
14149     rettv->vval.v_number = get_tv_number_chk(&argvars[0], NULL)
14150                                         | get_tv_number_chk(&argvars[1], NULL);
14151 }
14152
14153 /*
14154  * "pathshorten()" function
14155  */
14156     static void
14157 f_pathshorten(argvars, rettv)
14158     typval_T    *argvars;
14159     typval_T    *rettv;
14160 {
14161     char_u      *p;
14162
14163     rettv->v_type = VAR_STRING;
14164     p = get_tv_string_chk(&argvars[0]);
14165     if (p == NULL)
14166         rettv->vval.v_string = NULL;
14167     else
14168     {
14169         p = vim_strsave(p);
14170         rettv->vval.v_string = p;
14171         if (p != NULL)
14172             shorten_dir(p);
14173     }
14174 }
14175
14176 #ifdef FEAT_FLOAT
14177 /*
14178  * "pow()" function
14179  */
14180     static void
14181 f_pow(argvars, rettv)
14182     typval_T    *argvars;
14183     typval_T    *rettv;
14184 {
14185     float_T     fx, fy;
14186
14187     rettv->v_type = VAR_FLOAT;
14188     if (get_float_arg(argvars, &fx) == OK
14189                                      && get_float_arg(&argvars[1], &fy) == OK)
14190         rettv->vval.v_float = pow(fx, fy);
14191     else
14192         rettv->vval.v_float = 0.0;
14193 }
14194 #endif
14195
14196 /*
14197  * "prevnonblank()" function
14198  */
14199     static void
14200 f_prevnonblank(argvars, rettv)
14201     typval_T    *argvars;
14202     typval_T    *rettv;
14203 {
14204     linenr_T    lnum;
14205
14206     lnum = get_tv_lnum(argvars);
14207     if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
14208         lnum = 0;
14209     else
14210         while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
14211             --lnum;
14212     rettv->vval.v_number = lnum;
14213 }
14214
14215 #ifdef HAVE_STDARG_H
14216 /* This dummy va_list is here because:
14217  * - passing a NULL pointer doesn't work when va_list isn't a pointer
14218  * - locally in the function results in a "used before set" warning
14219  * - using va_start() to initialize it gives "function with fixed args" error */
14220 static va_list  ap;
14221 #endif
14222
14223 /*
14224  * "printf()" function
14225  */
14226     static void
14227 f_printf(argvars, rettv)
14228     typval_T    *argvars;
14229     typval_T    *rettv;
14230 {
14231     rettv->v_type = VAR_STRING;
14232     rettv->vval.v_string = NULL;
14233 #ifdef HAVE_STDARG_H        /* only very old compilers can't do this */
14234     {
14235         char_u  buf[NUMBUFLEN];
14236         int     len;
14237         char_u  *s;
14238         int     saved_did_emsg = did_emsg;
14239         char    *fmt;
14240
14241         /* Get the required length, allocate the buffer and do it for real. */
14242         did_emsg = FALSE;
14243         fmt = (char *)get_tv_string_buf(&argvars[0], buf);
14244         len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
14245         if (!did_emsg)
14246         {
14247             s = alloc(len + 1);
14248             if (s != NULL)
14249             {
14250                 rettv->vval.v_string = s;
14251                 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
14252             }
14253         }
14254         did_emsg |= saved_did_emsg;
14255     }
14256 #endif
14257 }
14258
14259 /*
14260  * "pumvisible()" function
14261  */
14262     static void
14263 f_pumvisible(argvars, rettv)
14264     typval_T    *argvars UNUSED;
14265     typval_T    *rettv UNUSED;
14266 {
14267 #ifdef FEAT_INS_EXPAND
14268     if (pum_visible())
14269         rettv->vval.v_number = 1;
14270 #endif
14271 }
14272
14273 /*
14274  * "range()" function
14275  */
14276     static void
14277 f_range(argvars, rettv)
14278     typval_T    *argvars;
14279     typval_T    *rettv;
14280 {
14281     long        start;
14282     long        end;
14283     long        stride = 1;
14284     long        i;
14285     int         error = FALSE;
14286
14287     start = get_tv_number_chk(&argvars[0], &error);
14288     if (argvars[1].v_type == VAR_UNKNOWN)
14289     {
14290         end = start - 1;
14291         start = 0;
14292     }
14293     else
14294     {
14295         end = get_tv_number_chk(&argvars[1], &error);
14296         if (argvars[2].v_type != VAR_UNKNOWN)
14297             stride = get_tv_number_chk(&argvars[2], &error);
14298     }
14299
14300     if (error)
14301         return;         /* type error; errmsg already given */
14302     if (stride == 0)
14303         EMSG(_("E726: Stride is zero"));
14304     else if (stride > 0 ? end + 1 < start : end - 1 > start)
14305         EMSG(_("E727: Start past end"));
14306     else
14307     {
14308         if (rettv_list_alloc(rettv) == OK)
14309             for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
14310                 if (list_append_number(rettv->vval.v_list,
14311                                                       (varnumber_T)i) == FAIL)
14312                     break;
14313     }
14314 }
14315
14316 /*
14317  * "readfile()" function
14318  */
14319     static void
14320 f_readfile(argvars, rettv)
14321     typval_T    *argvars;
14322     typval_T    *rettv;
14323 {
14324     int         binary = FALSE;
14325     char_u      *fname;
14326     FILE        *fd;
14327     listitem_T  *li;
14328 #define FREAD_SIZE 200      /* optimized for text lines */
14329     char_u      buf[FREAD_SIZE];
14330     int         readlen;    /* size of last fread() */
14331     int         buflen;     /* nr of valid chars in buf[] */
14332     int         filtd;      /* how much in buf[] was NUL -> '\n' filtered */
14333     int         tolist;     /* first byte in buf[] still to be put in list */
14334     int         chop;       /* how many CR to chop off */
14335     char_u      *prev = NULL;   /* previously read bytes, if any */
14336     int         prevlen = 0;    /* length of "prev" if not NULL */
14337     char_u      *s;
14338     int         len;
14339     long        maxline = MAXLNUM;
14340     long        cnt = 0;
14341
14342     if (argvars[1].v_type != VAR_UNKNOWN)
14343     {
14344         if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
14345             binary = TRUE;
14346         if (argvars[2].v_type != VAR_UNKNOWN)
14347             maxline = get_tv_number(&argvars[2]);
14348     }
14349
14350     if (rettv_list_alloc(rettv) == FAIL)
14351         return;
14352
14353     /* Always open the file in binary mode, library functions have a mind of
14354      * their own about CR-LF conversion. */
14355     fname = get_tv_string(&argvars[0]);
14356     if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
14357     {
14358         EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
14359         return;
14360     }
14361
14362     filtd = 0;
14363     while (cnt < maxline || maxline < 0)
14364     {
14365         readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
14366         buflen = filtd + readlen;
14367         tolist = 0;
14368         for ( ; filtd < buflen || readlen <= 0; ++filtd)
14369         {
14370             if (readlen <= 0 || buf[filtd] == '\n')
14371             {
14372                 /* In binary mode add an empty list item when the last
14373                  * non-empty line ends in a '\n'. */
14374                 if (!binary && readlen == 0 && filtd == 0 && prev == NULL)
14375                     break;
14376
14377                 /* Found end-of-line or end-of-file: add a text line to the
14378                  * list. */
14379                 chop = 0;
14380                 if (!binary)
14381                     while (filtd - chop - 1 >= tolist
14382                                           && buf[filtd - chop - 1] == '\r')
14383                         ++chop;
14384                 len = filtd - tolist - chop;
14385                 if (prev == NULL)
14386                     s = vim_strnsave(buf + tolist, len);
14387                 else
14388                 {
14389                     s = alloc((unsigned)(prevlen + len + 1));
14390                     if (s != NULL)
14391                     {
14392                         mch_memmove(s, prev, prevlen);
14393                         vim_free(prev);
14394                         prev = NULL;
14395                         mch_memmove(s + prevlen, buf + tolist, len);
14396                         s[prevlen + len] = NUL;
14397                     }
14398                 }
14399                 tolist = filtd + 1;
14400
14401                 li = listitem_alloc();
14402                 if (li == NULL)
14403                 {
14404                     vim_free(s);
14405                     break;
14406                 }
14407                 li->li_tv.v_type = VAR_STRING;
14408                 li->li_tv.v_lock = 0;
14409                 li->li_tv.vval.v_string = s;
14410                 list_append(rettv->vval.v_list, li);
14411
14412                 if (++cnt >= maxline && maxline >= 0)
14413                     break;
14414                 if (readlen <= 0)
14415                     break;
14416             }
14417             else if (buf[filtd] == NUL)
14418                 buf[filtd] = '\n';
14419 #ifdef FEAT_MBYTE
14420             else if (buf[filtd] == 0xef
14421                     && enc_utf8
14422                     && filtd + 2 < buflen
14423                     && !binary
14424                     && buf[filtd + 1] == 0xbb
14425                     && buf[filtd + 2] == 0xbf)
14426             {
14427                 /* remove utf-8 byte order mark */
14428                 mch_memmove(buf + filtd, buf + filtd + 3, buflen - filtd - 3);
14429                 --filtd;
14430                 buflen -= 3;
14431             }
14432 #endif
14433         }
14434         if (readlen <= 0)
14435             break;
14436
14437         if (tolist == 0)
14438         {
14439             if (buflen >= FREAD_SIZE / 2)
14440             {
14441                 /* "buf" is full, need to move text to an allocated buffer */
14442                 if (prev == NULL)
14443                 {
14444                     prev = vim_strnsave(buf, buflen);
14445                     prevlen = buflen;
14446                 }
14447                 else
14448                 {
14449                     s = alloc((unsigned)(prevlen + buflen));
14450                     if (s != NULL)
14451                     {
14452                         mch_memmove(s, prev, prevlen);
14453                         mch_memmove(s + prevlen, buf, buflen);
14454                         vim_free(prev);
14455                         prev = s;
14456                         prevlen += buflen;
14457                     }
14458                 }
14459                 filtd = 0;
14460             }
14461         }
14462         else
14463         {
14464             mch_memmove(buf, buf + tolist, buflen - tolist);
14465             filtd -= tolist;
14466         }
14467     }
14468
14469     /*
14470      * For a negative line count use only the lines at the end of the file,
14471      * free the rest.
14472      */
14473     if (maxline < 0)
14474         while (cnt > -maxline)
14475         {
14476             listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
14477             --cnt;
14478         }
14479
14480     vim_free(prev);
14481     fclose(fd);
14482 }
14483
14484 #if defined(FEAT_RELTIME)
14485 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
14486
14487 /*
14488  * Convert a List to proftime_T.
14489  * Return FAIL when there is something wrong.
14490  */
14491     static int
14492 list2proftime(arg, tm)
14493     typval_T    *arg;
14494     proftime_T  *tm;
14495 {
14496     long        n1, n2;
14497     int error = FALSE;
14498
14499     if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
14500                                              || arg->vval.v_list->lv_len != 2)
14501         return FAIL;
14502     n1 = list_find_nr(arg->vval.v_list, 0L, &error);
14503     n2 = list_find_nr(arg->vval.v_list, 1L, &error);
14504 # ifdef WIN3264
14505     tm->HighPart = n1;
14506     tm->LowPart = n2;
14507 # else
14508     tm->tv_sec = n1;
14509     tm->tv_usec = n2;
14510 # endif
14511     return error ? FAIL : OK;
14512 }
14513 #endif /* FEAT_RELTIME */
14514
14515 /*
14516  * "reltime()" function
14517  */
14518     static void
14519 f_reltime(argvars, rettv)
14520     typval_T    *argvars;
14521     typval_T    *rettv;
14522 {
14523 #ifdef FEAT_RELTIME
14524     proftime_T  res;
14525     proftime_T  start;
14526
14527     if (argvars[0].v_type == VAR_UNKNOWN)
14528     {
14529         /* No arguments: get current time. */
14530         profile_start(&res);
14531     }
14532     else if (argvars[1].v_type == VAR_UNKNOWN)
14533     {
14534         if (list2proftime(&argvars[0], &res) == FAIL)
14535             return;
14536         profile_end(&res);
14537     }
14538     else
14539     {
14540         /* Two arguments: compute the difference. */
14541         if (list2proftime(&argvars[0], &start) == FAIL
14542                 || list2proftime(&argvars[1], &res) == FAIL)
14543             return;
14544         profile_sub(&res, &start);
14545     }
14546
14547     if (rettv_list_alloc(rettv) == OK)
14548     {
14549         long    n1, n2;
14550
14551 # ifdef WIN3264
14552         n1 = res.HighPart;
14553         n2 = res.LowPart;
14554 # else
14555         n1 = res.tv_sec;
14556         n2 = res.tv_usec;
14557 # endif
14558         list_append_number(rettv->vval.v_list, (varnumber_T)n1);
14559         list_append_number(rettv->vval.v_list, (varnumber_T)n2);
14560     }
14561 #endif
14562 }
14563
14564 /*
14565  * "reltimestr()" function
14566  */
14567     static void
14568 f_reltimestr(argvars, rettv)
14569     typval_T    *argvars;
14570     typval_T    *rettv;
14571 {
14572 #ifdef FEAT_RELTIME
14573     proftime_T  tm;
14574 #endif
14575
14576     rettv->v_type = VAR_STRING;
14577     rettv->vval.v_string = NULL;
14578 #ifdef FEAT_RELTIME
14579     if (list2proftime(&argvars[0], &tm) == OK)
14580         rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
14581 #endif
14582 }
14583
14584 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
14585 static void make_connection __ARGS((void));
14586 static int check_connection __ARGS((void));
14587
14588     static void
14589 make_connection()
14590 {
14591     if (X_DISPLAY == NULL
14592 # ifdef FEAT_GUI
14593             && !gui.in_use
14594 # endif
14595             )
14596     {
14597         x_force_connect = TRUE;
14598         setup_term_clip();
14599         x_force_connect = FALSE;
14600     }
14601 }
14602
14603     static int
14604 check_connection()
14605 {
14606     make_connection();
14607     if (X_DISPLAY == NULL)
14608     {
14609         EMSG(_("E240: No connection to Vim server"));
14610         return FAIL;
14611     }
14612     return OK;
14613 }
14614 #endif
14615
14616 #ifdef FEAT_CLIENTSERVER
14617 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
14618
14619     static void
14620 remote_common(argvars, rettv, expr)
14621     typval_T    *argvars;
14622     typval_T    *rettv;
14623     int         expr;
14624 {
14625     char_u      *server_name;
14626     char_u      *keys;
14627     char_u      *r = NULL;
14628     char_u      buf[NUMBUFLEN];
14629 # ifdef WIN32
14630     HWND        w;
14631 # else
14632     Window      w;
14633 # endif
14634
14635     if (check_restricted() || check_secure())
14636         return;
14637
14638 # ifdef FEAT_X11
14639     if (check_connection() == FAIL)
14640         return;
14641 # endif
14642
14643     server_name = get_tv_string_chk(&argvars[0]);
14644     if (server_name == NULL)
14645         return;         /* type error; errmsg already given */
14646     keys = get_tv_string_buf(&argvars[1], buf);
14647 # ifdef WIN32
14648     if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14649 # else
14650     if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
14651                                                                           < 0)
14652 # endif
14653     {
14654         if (r != NULL)
14655             EMSG(r);            /* sending worked but evaluation failed */
14656         else
14657             EMSG2(_("E241: Unable to send to %s"), server_name);
14658         return;
14659     }
14660
14661     rettv->vval.v_string = r;
14662
14663     if (argvars[2].v_type != VAR_UNKNOWN)
14664     {
14665         dictitem_T      v;
14666         char_u          str[30];
14667         char_u          *idvar;
14668
14669         sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
14670         v.di_tv.v_type = VAR_STRING;
14671         v.di_tv.vval.v_string = vim_strsave(str);
14672         idvar = get_tv_string_chk(&argvars[2]);
14673         if (idvar != NULL)
14674             set_var(idvar, &v.di_tv, FALSE);
14675         vim_free(v.di_tv.vval.v_string);
14676     }
14677 }
14678 #endif
14679
14680 /*
14681  * "remote_expr()" function
14682  */
14683     static void
14684 f_remote_expr(argvars, rettv)
14685     typval_T    *argvars UNUSED;
14686     typval_T    *rettv;
14687 {
14688     rettv->v_type = VAR_STRING;
14689     rettv->vval.v_string = NULL;
14690 #ifdef FEAT_CLIENTSERVER
14691     remote_common(argvars, rettv, TRUE);
14692 #endif
14693 }
14694
14695 /*
14696  * "remote_foreground()" function
14697  */
14698     static void
14699 f_remote_foreground(argvars, rettv)
14700     typval_T    *argvars UNUSED;
14701     typval_T    *rettv UNUSED;
14702 {
14703 #ifdef FEAT_CLIENTSERVER
14704 # ifdef WIN32
14705     /* On Win32 it's done in this application. */
14706     {
14707         char_u  *server_name = get_tv_string_chk(&argvars[0]);
14708
14709         if (server_name != NULL)
14710             serverForeground(server_name);
14711     }
14712 # else
14713     /* Send a foreground() expression to the server. */
14714     argvars[1].v_type = VAR_STRING;
14715     argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
14716     argvars[2].v_type = VAR_UNKNOWN;
14717     remote_common(argvars, rettv, TRUE);
14718     vim_free(argvars[1].vval.v_string);
14719 # endif
14720 #endif
14721 }
14722
14723     static void
14724 f_remote_peek(argvars, rettv)
14725     typval_T    *argvars UNUSED;
14726     typval_T    *rettv;
14727 {
14728 #ifdef FEAT_CLIENTSERVER
14729     dictitem_T  v;
14730     char_u      *s = NULL;
14731 # ifdef WIN32
14732     long_u      n = 0;
14733 # endif
14734     char_u      *serverid;
14735
14736     if (check_restricted() || check_secure())
14737     {
14738         rettv->vval.v_number = -1;
14739         return;
14740     }
14741     serverid = get_tv_string_chk(&argvars[0]);
14742     if (serverid == NULL)
14743     {
14744         rettv->vval.v_number = -1;
14745         return;         /* type error; errmsg already given */
14746     }
14747 # ifdef WIN32
14748     sscanf(serverid, SCANF_HEX_LONG_U, &n);
14749     if (n == 0)
14750         rettv->vval.v_number = -1;
14751     else
14752     {
14753         s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
14754         rettv->vval.v_number = (s != NULL);
14755     }
14756 # else
14757     if (check_connection() == FAIL)
14758         return;
14759
14760     rettv->vval.v_number = serverPeekReply(X_DISPLAY,
14761                                                 serverStrToWin(serverid), &s);
14762 # endif
14763
14764     if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
14765     {
14766         char_u          *retvar;
14767
14768         v.di_tv.v_type = VAR_STRING;
14769         v.di_tv.vval.v_string = vim_strsave(s);
14770         retvar = get_tv_string_chk(&argvars[1]);
14771         if (retvar != NULL)
14772             set_var(retvar, &v.di_tv, FALSE);
14773         vim_free(v.di_tv.vval.v_string);
14774     }
14775 #else
14776     rettv->vval.v_number = -1;
14777 #endif
14778 }
14779
14780     static void
14781 f_remote_read(argvars, rettv)
14782     typval_T    *argvars UNUSED;
14783     typval_T    *rettv;
14784 {
14785     char_u      *r = NULL;
14786
14787 #ifdef FEAT_CLIENTSERVER
14788     char_u      *serverid = get_tv_string_chk(&argvars[0]);
14789
14790     if (serverid != NULL && !check_restricted() && !check_secure())
14791     {
14792 # ifdef WIN32
14793         /* The server's HWND is encoded in the 'id' parameter */
14794         long_u          n = 0;
14795
14796         sscanf(serverid, SCANF_HEX_LONG_U, &n);
14797         if (n != 0)
14798             r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
14799         if (r == NULL)
14800 # else
14801         if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
14802                 serverStrToWin(serverid), &r, FALSE) < 0)
14803 # endif
14804             EMSG(_("E277: Unable to read a server reply"));
14805     }
14806 #endif
14807     rettv->v_type = VAR_STRING;
14808     rettv->vval.v_string = r;
14809 }
14810
14811 /*
14812  * "remote_send()" function
14813  */
14814     static void
14815 f_remote_send(argvars, rettv)
14816     typval_T    *argvars UNUSED;
14817     typval_T    *rettv;
14818 {
14819     rettv->v_type = VAR_STRING;
14820     rettv->vval.v_string = NULL;
14821 #ifdef FEAT_CLIENTSERVER
14822     remote_common(argvars, rettv, FALSE);
14823 #endif
14824 }
14825
14826 /*
14827  * "remove()" function
14828  */
14829     static void
14830 f_remove(argvars, rettv)
14831     typval_T    *argvars;
14832     typval_T    *rettv;
14833 {
14834     list_T      *l;
14835     listitem_T  *item, *item2;
14836     listitem_T  *li;
14837     long        idx;
14838     long        end;
14839     char_u      *key;
14840     dict_T      *d;
14841     dictitem_T  *di;
14842     char        *arg_errmsg = N_("remove() argument");
14843
14844     if (argvars[0].v_type == VAR_DICT)
14845     {
14846         if (argvars[2].v_type != VAR_UNKNOWN)
14847             EMSG2(_(e_toomanyarg), "remove()");
14848         else if ((d = argvars[0].vval.v_dict) != NULL
14849                 && !tv_check_lock(d->dv_lock, (char_u *)_(arg_errmsg)))
14850         {
14851             key = get_tv_string_chk(&argvars[1]);
14852             if (key != NULL)
14853             {
14854                 di = dict_find(d, key, -1);
14855                 if (di == NULL)
14856                     EMSG2(_(e_dictkey), key);
14857                 else
14858                 {
14859                     *rettv = di->di_tv;
14860                     init_tv(&di->di_tv);
14861                     dictitem_remove(d, di);
14862                 }
14863             }
14864         }
14865     }
14866     else if (argvars[0].v_type != VAR_LIST)
14867         EMSG2(_(e_listdictarg), "remove()");
14868     else if ((l = argvars[0].vval.v_list) != NULL
14869             && !tv_check_lock(l->lv_lock, (char_u *)_(arg_errmsg)))
14870     {
14871         int         error = FALSE;
14872
14873         idx = get_tv_number_chk(&argvars[1], &error);
14874         if (error)
14875             ;           /* type error: do nothing, errmsg already given */
14876         else if ((item = list_find(l, idx)) == NULL)
14877             EMSGN(_(e_listidx), idx);
14878         else
14879         {
14880             if (argvars[2].v_type == VAR_UNKNOWN)
14881             {
14882                 /* Remove one item, return its value. */
14883                 list_remove(l, item, item);
14884                 *rettv = item->li_tv;
14885                 vim_free(item);
14886             }
14887             else
14888             {
14889                 /* Remove range of items, return list with values. */
14890                 end = get_tv_number_chk(&argvars[2], &error);
14891                 if (error)
14892                     ;           /* type error: do nothing */
14893                 else if ((item2 = list_find(l, end)) == NULL)
14894                     EMSGN(_(e_listidx), end);
14895                 else
14896                 {
14897                     int     cnt = 0;
14898
14899                     for (li = item; li != NULL; li = li->li_next)
14900                     {
14901                         ++cnt;
14902                         if (li == item2)
14903                             break;
14904                     }
14905                     if (li == NULL)  /* didn't find "item2" after "item" */
14906                         EMSG(_(e_invrange));
14907                     else
14908                     {
14909                         list_remove(l, item, item2);
14910                         if (rettv_list_alloc(rettv) == OK)
14911                         {
14912                             l = rettv->vval.v_list;
14913                             l->lv_first = item;
14914                             l->lv_last = item2;
14915                             item->li_prev = NULL;
14916                             item2->li_next = NULL;
14917                             l->lv_len = cnt;
14918                         }
14919                     }
14920                 }
14921             }
14922         }
14923     }
14924 }
14925
14926 /*
14927  * "rename({from}, {to})" function
14928  */
14929     static void
14930 f_rename(argvars, rettv)
14931     typval_T    *argvars;
14932     typval_T    *rettv;
14933 {
14934     char_u      buf[NUMBUFLEN];
14935
14936     if (check_restricted() || check_secure())
14937         rettv->vval.v_number = -1;
14938     else
14939         rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
14940                                       get_tv_string_buf(&argvars[1], buf));
14941 }
14942
14943 /*
14944  * "repeat()" function
14945  */
14946     static void
14947 f_repeat(argvars, rettv)
14948     typval_T    *argvars;
14949     typval_T    *rettv;
14950 {
14951     char_u      *p;
14952     int         n;
14953     int         slen;
14954     int         len;
14955     char_u      *r;
14956     int         i;
14957
14958     n = get_tv_number(&argvars[1]);
14959     if (argvars[0].v_type == VAR_LIST)
14960     {
14961         if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
14962             while (n-- > 0)
14963                 if (list_extend(rettv->vval.v_list,
14964                                         argvars[0].vval.v_list, NULL) == FAIL)
14965                     break;
14966     }
14967     else
14968     {
14969         p = get_tv_string(&argvars[0]);
14970         rettv->v_type = VAR_STRING;
14971         rettv->vval.v_string = NULL;
14972
14973         slen = (int)STRLEN(p);
14974         len = slen * n;
14975         if (len <= 0)
14976             return;
14977
14978         r = alloc(len + 1);
14979         if (r != NULL)
14980         {
14981             for (i = 0; i < n; i++)
14982                 mch_memmove(r + i * slen, p, (size_t)slen);
14983             r[len] = NUL;
14984         }
14985
14986         rettv->vval.v_string = r;
14987     }
14988 }
14989
14990 /*
14991  * "resolve()" function
14992  */
14993     static void
14994 f_resolve(argvars, rettv)
14995     typval_T    *argvars;
14996     typval_T    *rettv;
14997 {
14998     char_u      *p;
14999 #ifdef HAVE_READLINK
15000     char_u      *buf = NULL;
15001 #endif
15002
15003     p = get_tv_string(&argvars[0]);
15004 #ifdef FEAT_SHORTCUT
15005     {
15006         char_u  *v = NULL;
15007
15008         v = mch_resolve_shortcut(p);
15009         if (v != NULL)
15010             rettv->vval.v_string = v;
15011         else
15012             rettv->vval.v_string = vim_strsave(p);
15013     }
15014 #else
15015 # ifdef HAVE_READLINK
15016     {
15017         char_u  *cpy;
15018         int     len;
15019         char_u  *remain = NULL;
15020         char_u  *q;
15021         int     is_relative_to_current = FALSE;
15022         int     has_trailing_pathsep = FALSE;
15023         int     limit = 100;
15024
15025         p = vim_strsave(p);
15026
15027         if (p[0] == '.' && (vim_ispathsep(p[1])
15028                                    || (p[1] == '.' && (vim_ispathsep(p[2])))))
15029             is_relative_to_current = TRUE;
15030
15031         len = STRLEN(p);
15032         if (len > 0 && after_pathsep(p, p + len))
15033         {
15034             has_trailing_pathsep = TRUE;
15035             p[len - 1] = NUL; /* the trailing slash breaks readlink() */
15036         }
15037
15038         q = getnextcomp(p);
15039         if (*q != NUL)
15040         {
15041             /* Separate the first path component in "p", and keep the
15042              * remainder (beginning with the path separator). */
15043             remain = vim_strsave(q - 1);
15044             q[-1] = NUL;
15045         }
15046
15047         buf = alloc(MAXPATHL + 1);
15048         if (buf == NULL)
15049             goto fail;
15050
15051         for (;;)
15052         {
15053             for (;;)
15054             {
15055                 len = readlink((char *)p, (char *)buf, MAXPATHL);
15056                 if (len <= 0)
15057                     break;
15058                 buf[len] = NUL;
15059
15060                 if (limit-- == 0)
15061                 {
15062                     vim_free(p);
15063                     vim_free(remain);
15064                     EMSG(_("E655: Too many symbolic links (cycle?)"));
15065                     rettv->vval.v_string = NULL;
15066                     goto fail;
15067                 }
15068
15069                 /* Ensure that the result will have a trailing path separator
15070                  * if the argument has one. */
15071                 if (remain == NULL && has_trailing_pathsep)
15072                     add_pathsep(buf);
15073
15074                 /* Separate the first path component in the link value and
15075                  * concatenate the remainders. */
15076                 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
15077                 if (*q != NUL)
15078                 {
15079                     if (remain == NULL)
15080                         remain = vim_strsave(q - 1);
15081                     else
15082                     {
15083                         cpy = concat_str(q - 1, remain);
15084                         if (cpy != NULL)
15085                         {
15086                             vim_free(remain);
15087                             remain = cpy;
15088                         }
15089                     }
15090                     q[-1] = NUL;
15091                 }
15092
15093                 q = gettail(p);
15094                 if (q > p && *q == NUL)
15095                 {
15096                     /* Ignore trailing path separator. */
15097                     q[-1] = NUL;
15098                     q = gettail(p);
15099                 }
15100                 if (q > p && !mch_isFullName(buf))
15101                 {
15102                     /* symlink is relative to directory of argument */
15103                     cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
15104                     if (cpy != NULL)
15105                     {
15106                         STRCPY(cpy, p);
15107                         STRCPY(gettail(cpy), buf);
15108                         vim_free(p);
15109                         p = cpy;
15110                     }
15111                 }
15112                 else
15113                 {
15114                     vim_free(p);
15115                     p = vim_strsave(buf);
15116                 }
15117             }
15118
15119             if (remain == NULL)
15120                 break;
15121
15122             /* Append the first path component of "remain" to "p". */
15123             q = getnextcomp(remain + 1);
15124             len = q - remain - (*q != NUL);
15125             cpy = vim_strnsave(p, STRLEN(p) + len);
15126             if (cpy != NULL)
15127             {
15128                 STRNCAT(cpy, remain, len);
15129                 vim_free(p);
15130                 p = cpy;
15131             }
15132             /* Shorten "remain". */
15133             if (*q != NUL)
15134                 STRMOVE(remain, q - 1);
15135             else
15136             {
15137                 vim_free(remain);
15138                 remain = NULL;
15139             }
15140         }
15141
15142         /* If the result is a relative path name, make it explicitly relative to
15143          * the current directory if and only if the argument had this form. */
15144         if (!vim_ispathsep(*p))
15145         {
15146             if (is_relative_to_current
15147                     && *p != NUL
15148                     && !(p[0] == '.'
15149                         && (p[1] == NUL
15150                             || vim_ispathsep(p[1])
15151                             || (p[1] == '.'
15152                                 && (p[2] == NUL
15153                                     || vim_ispathsep(p[2]))))))
15154             {
15155                 /* Prepend "./". */
15156                 cpy = concat_str((char_u *)"./", p);
15157                 if (cpy != NULL)
15158                 {
15159                     vim_free(p);
15160                     p = cpy;
15161                 }
15162             }
15163             else if (!is_relative_to_current)
15164             {
15165                 /* Strip leading "./". */
15166                 q = p;
15167                 while (q[0] == '.' && vim_ispathsep(q[1]))
15168                     q += 2;
15169                 if (q > p)
15170                     STRMOVE(p, p + 2);
15171             }
15172         }
15173
15174         /* Ensure that the result will have no trailing path separator
15175          * if the argument had none.  But keep "/" or "//". */
15176         if (!has_trailing_pathsep)
15177         {
15178             q = p + STRLEN(p);
15179             if (after_pathsep(p, q))
15180                 *gettail_sep(p) = NUL;
15181         }
15182
15183         rettv->vval.v_string = p;
15184     }
15185 # else
15186     rettv->vval.v_string = vim_strsave(p);
15187 # endif
15188 #endif
15189
15190     simplify_filename(rettv->vval.v_string);
15191
15192 #ifdef HAVE_READLINK
15193 fail:
15194     vim_free(buf);
15195 #endif
15196     rettv->v_type = VAR_STRING;
15197 }
15198
15199 /*
15200  * "reverse({list})" function
15201  */
15202     static void
15203 f_reverse(argvars, rettv)
15204     typval_T    *argvars;
15205     typval_T    *rettv;
15206 {
15207     list_T      *l;
15208     listitem_T  *li, *ni;
15209
15210     if (argvars[0].v_type != VAR_LIST)
15211         EMSG2(_(e_listarg), "reverse()");
15212     else if ((l = argvars[0].vval.v_list) != NULL
15213             && !tv_check_lock(l->lv_lock, (char_u *)_("reverse() argument")))
15214     {
15215         li = l->lv_last;
15216         l->lv_first = l->lv_last = NULL;
15217         l->lv_len = 0;
15218         while (li != NULL)
15219         {
15220             ni = li->li_prev;
15221             list_append(l, li);
15222             li = ni;
15223         }
15224         rettv->vval.v_list = l;
15225         rettv->v_type = VAR_LIST;
15226         ++l->lv_refcount;
15227         l->lv_idx = l->lv_len - l->lv_idx - 1;
15228     }
15229 }
15230
15231 #define SP_NOMOVE       0x01        /* don't move cursor */
15232 #define SP_REPEAT       0x02        /* repeat to find outer pair */
15233 #define SP_RETCOUNT     0x04        /* return matchcount */
15234 #define SP_SETPCMARK    0x08        /* set previous context mark */
15235 #define SP_START        0x10        /* accept match at start position */
15236 #define SP_SUBPAT       0x20        /* return nr of matching sub-pattern */
15237 #define SP_END          0x40        /* leave cursor at end of match */
15238
15239 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
15240
15241 /*
15242  * Get flags for a search function.
15243  * Possibly sets "p_ws".
15244  * Returns BACKWARD, FORWARD or zero (for an error).
15245  */
15246     static int
15247 get_search_arg(varp, flagsp)
15248     typval_T    *varp;
15249     int         *flagsp;
15250 {
15251     int         dir = FORWARD;
15252     char_u      *flags;
15253     char_u      nbuf[NUMBUFLEN];
15254     int         mask;
15255
15256     if (varp->v_type != VAR_UNKNOWN)
15257     {
15258         flags = get_tv_string_buf_chk(varp, nbuf);
15259         if (flags == NULL)
15260             return 0;           /* type error; errmsg already given */
15261         while (*flags != NUL)
15262         {
15263             switch (*flags)
15264             {
15265                 case 'b': dir = BACKWARD; break;
15266                 case 'w': p_ws = TRUE; break;
15267                 case 'W': p_ws = FALSE; break;
15268                 default:  mask = 0;
15269                           if (flagsp != NULL)
15270                              switch (*flags)
15271                              {
15272                                  case 'c': mask = SP_START; break;
15273                                  case 'e': mask = SP_END; break;
15274                                  case 'm': mask = SP_RETCOUNT; break;
15275                                  case 'n': mask = SP_NOMOVE; break;
15276                                  case 'p': mask = SP_SUBPAT; break;
15277                                  case 'r': mask = SP_REPEAT; break;
15278                                  case 's': mask = SP_SETPCMARK; break;
15279                              }
15280                           if (mask == 0)
15281                           {
15282                               EMSG2(_(e_invarg2), flags);
15283                               dir = 0;
15284                           }
15285                           else
15286                               *flagsp |= mask;
15287             }
15288             if (dir == 0)
15289                 break;
15290             ++flags;
15291         }
15292     }
15293     return dir;
15294 }
15295
15296 /*
15297  * Shared by search() and searchpos() functions
15298  */
15299     static int
15300 search_cmn(argvars, match_pos, flagsp)
15301     typval_T    *argvars;
15302     pos_T       *match_pos;
15303     int         *flagsp;
15304 {
15305     int         flags;
15306     char_u      *pat;
15307     pos_T       pos;
15308     pos_T       save_cursor;
15309     int         save_p_ws = p_ws;
15310     int         dir;
15311     int         retval = 0;     /* default: FAIL */
15312     long        lnum_stop = 0;
15313     proftime_T  tm;
15314 #ifdef FEAT_RELTIME
15315     long        time_limit = 0;
15316 #endif
15317     int         options = SEARCH_KEEP;
15318     int         subpatnum;
15319
15320     pat = get_tv_string(&argvars[0]);
15321     dir = get_search_arg(&argvars[1], flagsp);  /* may set p_ws */
15322     if (dir == 0)
15323         goto theend;
15324     flags = *flagsp;
15325     if (flags & SP_START)
15326         options |= SEARCH_START;
15327     if (flags & SP_END)
15328         options |= SEARCH_END;
15329
15330     /* Optional arguments: line number to stop searching and timeout. */
15331     if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
15332     {
15333         lnum_stop = get_tv_number_chk(&argvars[2], NULL);
15334         if (lnum_stop < 0)
15335             goto theend;
15336 #ifdef FEAT_RELTIME
15337         if (argvars[3].v_type != VAR_UNKNOWN)
15338         {
15339             time_limit = get_tv_number_chk(&argvars[3], NULL);
15340             if (time_limit < 0)
15341                 goto theend;
15342         }
15343 #endif
15344     }
15345
15346 #ifdef FEAT_RELTIME
15347     /* Set the time limit, if there is one. */
15348     profile_setlimit(time_limit, &tm);
15349 #endif
15350
15351     /*
15352      * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
15353      * Check to make sure only those flags are set.
15354      * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
15355      * flags cannot be set. Check for that condition also.
15356      */
15357     if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
15358             || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
15359     {
15360         EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
15361         goto theend;
15362     }
15363
15364     pos = save_cursor = curwin->w_cursor;
15365     subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15366                                 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
15367     if (subpatnum != FAIL)
15368     {
15369         if (flags & SP_SUBPAT)
15370             retval = subpatnum;
15371         else
15372             retval = pos.lnum;
15373         if (flags & SP_SETPCMARK)
15374             setpcmark();
15375         curwin->w_cursor = pos;
15376         if (match_pos != NULL)
15377         {
15378             /* Store the match cursor position */
15379             match_pos->lnum = pos.lnum;
15380             match_pos->col = pos.col + 1;
15381         }
15382         /* "/$" will put the cursor after the end of the line, may need to
15383          * correct that here */
15384         check_cursor();
15385     }
15386
15387     /* If 'n' flag is used: restore cursor position. */
15388     if (flags & SP_NOMOVE)
15389         curwin->w_cursor = save_cursor;
15390     else
15391         curwin->w_set_curswant = TRUE;
15392 theend:
15393     p_ws = save_p_ws;
15394
15395     return retval;
15396 }
15397
15398 #ifdef FEAT_FLOAT
15399 /*
15400  * "round({float})" function
15401  */
15402     static void
15403 f_round(argvars, rettv)
15404     typval_T    *argvars;
15405     typval_T    *rettv;
15406 {
15407     float_T     f;
15408
15409     rettv->v_type = VAR_FLOAT;
15410     if (get_float_arg(argvars, &f) == OK)
15411         /* round() is not in C90, use ceil() or floor() instead. */
15412         rettv->vval.v_float = f > 0 ? floor(f + 0.5) : ceil(f - 0.5);
15413     else
15414         rettv->vval.v_float = 0.0;
15415 }
15416 #endif
15417
15418 /*
15419  * "search()" function
15420  */
15421     static void
15422 f_search(argvars, rettv)
15423     typval_T    *argvars;
15424     typval_T    *rettv;
15425 {
15426     int         flags = 0;
15427
15428     rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
15429 }
15430
15431 /*
15432  * "searchdecl()" function
15433  */
15434     static void
15435 f_searchdecl(argvars, rettv)
15436     typval_T    *argvars;
15437     typval_T    *rettv;
15438 {
15439     int         locally = 1;
15440     int         thisblock = 0;
15441     int         error = FALSE;
15442     char_u      *name;
15443
15444     rettv->vval.v_number = 1;   /* default: FAIL */
15445
15446     name = get_tv_string_chk(&argvars[0]);
15447     if (argvars[1].v_type != VAR_UNKNOWN)
15448     {
15449         locally = get_tv_number_chk(&argvars[1], &error) == 0;
15450         if (!error && argvars[2].v_type != VAR_UNKNOWN)
15451             thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
15452     }
15453     if (!error && name != NULL)
15454         rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
15455                                      locally, thisblock, SEARCH_KEEP) == FAIL;
15456 }
15457
15458 /*
15459  * Used by searchpair() and searchpairpos()
15460  */
15461     static int
15462 searchpair_cmn(argvars, match_pos)
15463     typval_T    *argvars;
15464     pos_T       *match_pos;
15465 {
15466     char_u      *spat, *mpat, *epat;
15467     char_u      *skip;
15468     int         save_p_ws = p_ws;
15469     int         dir;
15470     int         flags = 0;
15471     char_u      nbuf1[NUMBUFLEN];
15472     char_u      nbuf2[NUMBUFLEN];
15473     char_u      nbuf3[NUMBUFLEN];
15474     int         retval = 0;             /* default: FAIL */
15475     long        lnum_stop = 0;
15476     long        time_limit = 0;
15477
15478     /* Get the three pattern arguments: start, middle, end. */
15479     spat = get_tv_string_chk(&argvars[0]);
15480     mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
15481     epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
15482     if (spat == NULL || mpat == NULL || epat == NULL)
15483         goto theend;        /* type error */
15484
15485     /* Handle the optional fourth argument: flags */
15486     dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
15487     if (dir == 0)
15488         goto theend;
15489
15490     /* Don't accept SP_END or SP_SUBPAT.
15491      * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
15492      */
15493     if ((flags & (SP_END | SP_SUBPAT)) != 0
15494             || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
15495     {
15496         EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
15497         goto theend;
15498     }
15499
15500     /* Using 'r' implies 'W', otherwise it doesn't work. */
15501     if (flags & SP_REPEAT)
15502         p_ws = FALSE;
15503
15504     /* Optional fifth argument: skip expression */
15505     if (argvars[3].v_type == VAR_UNKNOWN
15506             || argvars[4].v_type == VAR_UNKNOWN)
15507         skip = (char_u *)"";
15508     else
15509     {
15510         skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
15511         if (argvars[5].v_type != VAR_UNKNOWN)
15512         {
15513             lnum_stop = get_tv_number_chk(&argvars[5], NULL);
15514             if (lnum_stop < 0)
15515                 goto theend;
15516 #ifdef FEAT_RELTIME
15517             if (argvars[6].v_type != VAR_UNKNOWN)
15518             {
15519                 time_limit = get_tv_number_chk(&argvars[6], NULL);
15520                 if (time_limit < 0)
15521                     goto theend;
15522             }
15523 #endif
15524         }
15525     }
15526     if (skip == NULL)
15527         goto theend;        /* type error */
15528
15529     retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
15530                                             match_pos, lnum_stop, time_limit);
15531
15532 theend:
15533     p_ws = save_p_ws;
15534
15535     return retval;
15536 }
15537
15538 /*
15539  * "searchpair()" function
15540  */
15541     static void
15542 f_searchpair(argvars, rettv)
15543     typval_T    *argvars;
15544     typval_T    *rettv;
15545 {
15546     rettv->vval.v_number = searchpair_cmn(argvars, NULL);
15547 }
15548
15549 /*
15550  * "searchpairpos()" function
15551  */
15552     static void
15553 f_searchpairpos(argvars, rettv)
15554     typval_T    *argvars;
15555     typval_T    *rettv;
15556 {
15557     pos_T       match_pos;
15558     int         lnum = 0;
15559     int         col = 0;
15560
15561     if (rettv_list_alloc(rettv) == FAIL)
15562         return;
15563
15564     if (searchpair_cmn(argvars, &match_pos) > 0)
15565     {
15566         lnum = match_pos.lnum;
15567         col = match_pos.col;
15568     }
15569
15570     list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15571     list_append_number(rettv->vval.v_list, (varnumber_T)col);
15572 }
15573
15574 /*
15575  * Search for a start/middle/end thing.
15576  * Used by searchpair(), see its documentation for the details.
15577  * Returns 0 or -1 for no match,
15578  */
15579     long
15580 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
15581                                                         lnum_stop, time_limit)
15582     char_u      *spat;      /* start pattern */
15583     char_u      *mpat;      /* middle pattern */
15584     char_u      *epat;      /* end pattern */
15585     int         dir;        /* BACKWARD or FORWARD */
15586     char_u      *skip;      /* skip expression */
15587     int         flags;      /* SP_SETPCMARK and other SP_ values */
15588     pos_T       *match_pos;
15589     linenr_T    lnum_stop;  /* stop at this line if not zero */
15590     long        time_limit; /* stop after this many msec */
15591 {
15592     char_u      *save_cpo;
15593     char_u      *pat, *pat2 = NULL, *pat3 = NULL;
15594     long        retval = 0;
15595     pos_T       pos;
15596     pos_T       firstpos;
15597     pos_T       foundpos;
15598     pos_T       save_cursor;
15599     pos_T       save_pos;
15600     int         n;
15601     int         r;
15602     int         nest = 1;
15603     int         err;
15604     int         options = SEARCH_KEEP;
15605     proftime_T  tm;
15606
15607     /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15608     save_cpo = p_cpo;
15609     p_cpo = empty_option;
15610
15611 #ifdef FEAT_RELTIME
15612     /* Set the time limit, if there is one. */
15613     profile_setlimit(time_limit, &tm);
15614 #endif
15615
15616     /* Make two search patterns: start/end (pat2, for in nested pairs) and
15617      * start/middle/end (pat3, for the top pair). */
15618     pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
15619     pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
15620     if (pat2 == NULL || pat3 == NULL)
15621         goto theend;
15622     sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
15623     if (*mpat == NUL)
15624         STRCPY(pat3, pat2);
15625     else
15626         sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
15627                                                             spat, epat, mpat);
15628     if (flags & SP_START)
15629         options |= SEARCH_START;
15630
15631     save_cursor = curwin->w_cursor;
15632     pos = curwin->w_cursor;
15633     clearpos(&firstpos);
15634     clearpos(&foundpos);
15635     pat = pat3;
15636     for (;;)
15637     {
15638         n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15639                                            options, RE_SEARCH, lnum_stop, &tm);
15640         if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
15641             /* didn't find it or found the first match again: FAIL */
15642             break;
15643
15644         if (firstpos.lnum == 0)
15645             firstpos = pos;
15646         if (equalpos(pos, foundpos))
15647         {
15648             /* Found the same position again.  Can happen with a pattern that
15649              * has "\zs" at the end and searching backwards.  Advance one
15650              * character and try again. */
15651             if (dir == BACKWARD)
15652                 decl(&pos);
15653             else
15654                 incl(&pos);
15655         }
15656         foundpos = pos;
15657
15658         /* clear the start flag to avoid getting stuck here */
15659         options &= ~SEARCH_START;
15660
15661         /* If the skip pattern matches, ignore this match. */
15662         if (*skip != NUL)
15663         {
15664             save_pos = curwin->w_cursor;
15665             curwin->w_cursor = pos;
15666             r = eval_to_bool(skip, &err, NULL, FALSE);
15667             curwin->w_cursor = save_pos;
15668             if (err)
15669             {
15670                 /* Evaluating {skip} caused an error, break here. */
15671                 curwin->w_cursor = save_cursor;
15672                 retval = -1;
15673                 break;
15674             }
15675             if (r)
15676                 continue;
15677         }
15678
15679         if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
15680         {
15681             /* Found end when searching backwards or start when searching
15682              * forward: nested pair. */
15683             ++nest;
15684             pat = pat2;         /* nested, don't search for middle */
15685         }
15686         else
15687         {
15688             /* Found end when searching forward or start when searching
15689              * backward: end of (nested) pair; or found middle in outer pair. */
15690             if (--nest == 1)
15691                 pat = pat3;     /* outer level, search for middle */
15692         }
15693
15694         if (nest == 0)
15695         {
15696             /* Found the match: return matchcount or line number. */
15697             if (flags & SP_RETCOUNT)
15698                 ++retval;
15699             else
15700                 retval = pos.lnum;
15701             if (flags & SP_SETPCMARK)
15702                 setpcmark();
15703             curwin->w_cursor = pos;
15704             if (!(flags & SP_REPEAT))
15705                 break;
15706             nest = 1;       /* search for next unmatched */
15707         }
15708     }
15709
15710     if (match_pos != NULL)
15711     {
15712         /* Store the match cursor position */
15713         match_pos->lnum = curwin->w_cursor.lnum;
15714         match_pos->col = curwin->w_cursor.col + 1;
15715     }
15716
15717     /* If 'n' flag is used or search failed: restore cursor position. */
15718     if ((flags & SP_NOMOVE) || retval == 0)
15719         curwin->w_cursor = save_cursor;
15720
15721 theend:
15722     vim_free(pat2);
15723     vim_free(pat3);
15724     if (p_cpo == empty_option)
15725         p_cpo = save_cpo;
15726     else
15727         /* Darn, evaluating the {skip} expression changed the value. */
15728         free_string_option(save_cpo);
15729
15730     return retval;
15731 }
15732
15733 /*
15734  * "searchpos()" function
15735  */
15736     static void
15737 f_searchpos(argvars, rettv)
15738     typval_T    *argvars;
15739     typval_T    *rettv;
15740 {
15741     pos_T       match_pos;
15742     int         lnum = 0;
15743     int         col = 0;
15744     int         n;
15745     int         flags = 0;
15746
15747     if (rettv_list_alloc(rettv) == FAIL)
15748         return;
15749
15750     n = search_cmn(argvars, &match_pos, &flags);
15751     if (n > 0)
15752     {
15753         lnum = match_pos.lnum;
15754         col = match_pos.col;
15755     }
15756
15757     list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15758     list_append_number(rettv->vval.v_list, (varnumber_T)col);
15759     if (flags & SP_SUBPAT)
15760         list_append_number(rettv->vval.v_list, (varnumber_T)n);
15761 }
15762
15763
15764     static void
15765 f_server2client(argvars, rettv)
15766     typval_T    *argvars UNUSED;
15767     typval_T    *rettv;
15768 {
15769 #ifdef FEAT_CLIENTSERVER
15770     char_u      buf[NUMBUFLEN];
15771     char_u      *server = get_tv_string_chk(&argvars[0]);
15772     char_u      *reply = get_tv_string_buf_chk(&argvars[1], buf);
15773
15774     rettv->vval.v_number = -1;
15775     if (server == NULL || reply == NULL)
15776         return;
15777     if (check_restricted() || check_secure())
15778         return;
15779 # ifdef FEAT_X11
15780     if (check_connection() == FAIL)
15781         return;
15782 # endif
15783
15784     if (serverSendReply(server, reply) < 0)
15785     {
15786         EMSG(_("E258: Unable to send to client"));
15787         return;
15788     }
15789     rettv->vval.v_number = 0;
15790 #else
15791     rettv->vval.v_number = -1;
15792 #endif
15793 }
15794
15795     static void
15796 f_serverlist(argvars, rettv)
15797     typval_T    *argvars UNUSED;
15798     typval_T    *rettv;
15799 {
15800     char_u      *r = NULL;
15801
15802 #ifdef FEAT_CLIENTSERVER
15803 # ifdef WIN32
15804     r = serverGetVimNames();
15805 # else
15806     make_connection();
15807     if (X_DISPLAY != NULL)
15808         r = serverGetVimNames(X_DISPLAY);
15809 # endif
15810 #endif
15811     rettv->v_type = VAR_STRING;
15812     rettv->vval.v_string = r;
15813 }
15814
15815 /*
15816  * "setbufvar()" function
15817  */
15818     static void
15819 f_setbufvar(argvars, rettv)
15820     typval_T    *argvars;
15821     typval_T    *rettv UNUSED;
15822 {
15823     buf_T       *buf;
15824     aco_save_T  aco;
15825     char_u      *varname, *bufvarname;
15826     typval_T    *varp;
15827     char_u      nbuf[NUMBUFLEN];
15828
15829     if (check_restricted() || check_secure())
15830         return;
15831     (void)get_tv_number(&argvars[0]);       /* issue errmsg if type error */
15832     varname = get_tv_string_chk(&argvars[1]);
15833     buf = get_buf_tv(&argvars[0]);
15834     varp = &argvars[2];
15835
15836     if (buf != NULL && varname != NULL && varp != NULL)
15837     {
15838         /* set curbuf to be our buf, temporarily */
15839         aucmd_prepbuf(&aco, buf);
15840
15841         if (*varname == '&')
15842         {
15843             long        numval;
15844             char_u      *strval;
15845             int         error = FALSE;
15846
15847             ++varname;
15848             numval = get_tv_number_chk(varp, &error);
15849             strval = get_tv_string_buf_chk(varp, nbuf);
15850             if (!error && strval != NULL)
15851                 set_option_value(varname, numval, strval, OPT_LOCAL);
15852         }
15853         else
15854         {
15855             bufvarname = alloc((unsigned)STRLEN(varname) + 3);
15856             if (bufvarname != NULL)
15857             {
15858                 STRCPY(bufvarname, "b:");
15859                 STRCPY(bufvarname + 2, varname);
15860                 set_var(bufvarname, varp, TRUE);
15861                 vim_free(bufvarname);
15862             }
15863         }
15864
15865         /* reset notion of buffer */
15866         aucmd_restbuf(&aco);
15867     }
15868 }
15869
15870 /*
15871  * "setcmdpos()" function
15872  */
15873     static void
15874 f_setcmdpos(argvars, rettv)
15875     typval_T    *argvars;
15876     typval_T    *rettv;
15877 {
15878     int         pos = (int)get_tv_number(&argvars[0]) - 1;
15879
15880     if (pos >= 0)
15881         rettv->vval.v_number = set_cmdline_pos(pos);
15882 }
15883
15884 /*
15885  * "setline()" function
15886  */
15887     static void
15888 f_setline(argvars, rettv)
15889     typval_T    *argvars;
15890     typval_T    *rettv;
15891 {
15892     linenr_T    lnum;
15893     char_u      *line = NULL;
15894     list_T      *l = NULL;
15895     listitem_T  *li = NULL;
15896     long        added = 0;
15897     linenr_T    lcount = curbuf->b_ml.ml_line_count;
15898
15899     lnum = get_tv_lnum(&argvars[0]);
15900     if (argvars[1].v_type == VAR_LIST)
15901     {
15902         l = argvars[1].vval.v_list;
15903         li = l->lv_first;
15904     }
15905     else
15906         line = get_tv_string_chk(&argvars[1]);
15907
15908     /* default result is zero == OK */
15909     for (;;)
15910     {
15911         if (l != NULL)
15912         {
15913             /* list argument, get next string */
15914             if (li == NULL)
15915                 break;
15916             line = get_tv_string_chk(&li->li_tv);
15917             li = li->li_next;
15918         }
15919
15920         rettv->vval.v_number = 1;       /* FAIL */
15921         if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
15922             break;
15923         if (lnum <= curbuf->b_ml.ml_line_count)
15924         {
15925             /* existing line, replace it */
15926             if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
15927             {
15928                 changed_bytes(lnum, 0);
15929                 if (lnum == curwin->w_cursor.lnum)
15930                     check_cursor_col();
15931                 rettv->vval.v_number = 0;       /* OK */
15932             }
15933         }
15934         else if (added > 0 || u_save(lnum - 1, lnum) == OK)
15935         {
15936             /* lnum is one past the last line, append the line */
15937             ++added;
15938             if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
15939                 rettv->vval.v_number = 0;       /* OK */
15940         }
15941
15942         if (l == NULL)                  /* only one string argument */
15943             break;
15944         ++lnum;
15945     }
15946
15947     if (added > 0)
15948         appended_lines_mark(lcount, added);
15949 }
15950
15951 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
15952
15953 /*
15954  * Used by "setqflist()" and "setloclist()" functions
15955  */
15956     static void
15957 set_qf_ll_list(wp, list_arg, action_arg, rettv)
15958     win_T       *wp UNUSED;
15959     typval_T    *list_arg UNUSED;
15960     typval_T    *action_arg UNUSED;
15961     typval_T    *rettv;
15962 {
15963 #ifdef FEAT_QUICKFIX
15964     char_u      *act;
15965     int         action = ' ';
15966 #endif
15967
15968     rettv->vval.v_number = -1;
15969
15970 #ifdef FEAT_QUICKFIX
15971     if (list_arg->v_type != VAR_LIST)
15972         EMSG(_(e_listreq));
15973     else
15974     {
15975         list_T  *l = list_arg->vval.v_list;
15976
15977         if (action_arg->v_type == VAR_STRING)
15978         {
15979             act = get_tv_string_chk(action_arg);
15980             if (act == NULL)
15981                 return;         /* type error; errmsg already given */
15982             if (*act == 'a' || *act == 'r')
15983                 action = *act;
15984         }
15985
15986         if (l != NULL && set_errorlist(wp, l, action, NULL) == OK)
15987             rettv->vval.v_number = 0;
15988     }
15989 #endif
15990 }
15991
15992 /*
15993  * "setloclist()" function
15994  */
15995     static void
15996 f_setloclist(argvars, rettv)
15997     typval_T    *argvars;
15998     typval_T    *rettv;
15999 {
16000     win_T       *win;
16001
16002     rettv->vval.v_number = -1;
16003
16004     win = find_win_by_nr(&argvars[0], NULL);
16005     if (win != NULL)
16006         set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
16007 }
16008
16009 /*
16010  * "setmatches()" function
16011  */
16012     static void
16013 f_setmatches(argvars, rettv)
16014     typval_T    *argvars;
16015     typval_T    *rettv;
16016 {
16017 #ifdef FEAT_SEARCH_EXTRA
16018     list_T      *l;
16019     listitem_T  *li;
16020     dict_T      *d;
16021
16022     rettv->vval.v_number = -1;
16023     if (argvars[0].v_type != VAR_LIST)
16024     {
16025         EMSG(_(e_listreq));
16026         return;
16027     }
16028     if ((l = argvars[0].vval.v_list) != NULL)
16029     {
16030
16031         /* To some extent make sure that we are dealing with a list from
16032          * "getmatches()". */
16033         li = l->lv_first;
16034         while (li != NULL)
16035         {
16036             if (li->li_tv.v_type != VAR_DICT
16037                     || (d = li->li_tv.vval.v_dict) == NULL)
16038             {
16039                 EMSG(_(e_invarg));
16040                 return;
16041             }
16042             if (!(dict_find(d, (char_u *)"group", -1) != NULL
16043                         && dict_find(d, (char_u *)"pattern", -1) != NULL
16044                         && dict_find(d, (char_u *)"priority", -1) != NULL
16045                         && dict_find(d, (char_u *)"id", -1) != NULL))
16046             {
16047                 EMSG(_(e_invarg));
16048                 return;
16049             }
16050             li = li->li_next;
16051         }
16052
16053         clear_matches(curwin);
16054         li = l->lv_first;
16055         while (li != NULL)
16056         {
16057             d = li->li_tv.vval.v_dict;
16058             match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
16059                     get_dict_string(d, (char_u *)"pattern", FALSE),
16060                     (int)get_dict_number(d, (char_u *)"priority"),
16061                     (int)get_dict_number(d, (char_u *)"id"));
16062             li = li->li_next;
16063         }
16064         rettv->vval.v_number = 0;
16065     }
16066 #endif
16067 }
16068
16069 /*
16070  * "setpos()" function
16071  */
16072     static void
16073 f_setpos(argvars, rettv)
16074     typval_T    *argvars;
16075     typval_T    *rettv;
16076 {
16077     pos_T       pos;
16078     int         fnum;
16079     char_u      *name;
16080
16081     rettv->vval.v_number = -1;
16082     name = get_tv_string_chk(argvars);
16083     if (name != NULL)
16084     {
16085         if (list2fpos(&argvars[1], &pos, &fnum) == OK)
16086         {
16087             if (--pos.col < 0)
16088                 pos.col = 0;
16089             if (name[0] == '.' && name[1] == NUL)
16090             {
16091                 /* set cursor */
16092                 if (fnum == curbuf->b_fnum)
16093                 {
16094                     curwin->w_cursor = pos;
16095                     check_cursor();
16096                     rettv->vval.v_number = 0;
16097                 }
16098                 else
16099                     EMSG(_(e_invarg));
16100             }
16101             else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
16102             {
16103                 /* set mark */
16104                 if (setmark_pos(name[1], &pos, fnum) == OK)
16105                     rettv->vval.v_number = 0;
16106             }
16107             else
16108                 EMSG(_(e_invarg));
16109         }
16110     }
16111 }
16112
16113 /*
16114  * "setqflist()" function
16115  */
16116     static void
16117 f_setqflist(argvars, rettv)
16118     typval_T    *argvars;
16119     typval_T    *rettv;
16120 {
16121     set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
16122 }
16123
16124 /*
16125  * "setreg()" function
16126  */
16127     static void
16128 f_setreg(argvars, rettv)
16129     typval_T    *argvars;
16130     typval_T    *rettv;
16131 {
16132     int         regname;
16133     char_u      *strregname;
16134     char_u      *stropt;
16135     char_u      *strval;
16136     int         append;
16137     char_u      yank_type;
16138     long        block_len;
16139
16140     block_len = -1;
16141     yank_type = MAUTO;
16142     append = FALSE;
16143
16144     strregname = get_tv_string_chk(argvars);
16145     rettv->vval.v_number = 1;           /* FAIL is default */
16146
16147     if (strregname == NULL)
16148         return;         /* type error; errmsg already given */
16149     regname = *strregname;
16150     if (regname == 0 || regname == '@')
16151         regname = '"';
16152     else if (regname == '=')
16153         return;
16154
16155     if (argvars[2].v_type != VAR_UNKNOWN)
16156     {
16157         stropt = get_tv_string_chk(&argvars[2]);
16158         if (stropt == NULL)
16159             return;             /* type error */
16160         for (; *stropt != NUL; ++stropt)
16161             switch (*stropt)
16162             {
16163                 case 'a': case 'A':     /* append */
16164                     append = TRUE;
16165                     break;
16166                 case 'v': case 'c':     /* character-wise selection */
16167                     yank_type = MCHAR;
16168                     break;
16169                 case 'V': case 'l':     /* line-wise selection */
16170                     yank_type = MLINE;
16171                     break;
16172 #ifdef FEAT_VISUAL
16173                 case 'b': case Ctrl_V:  /* block-wise selection */
16174                     yank_type = MBLOCK;
16175                     if (VIM_ISDIGIT(stropt[1]))
16176                     {
16177                         ++stropt;
16178                         block_len = getdigits(&stropt) - 1;
16179                         --stropt;
16180                     }
16181                     break;
16182 #endif
16183             }
16184     }
16185
16186     strval = get_tv_string_chk(&argvars[1]);
16187     if (strval != NULL)
16188         write_reg_contents_ex(regname, strval, -1,
16189                                                 append, yank_type, block_len);
16190     rettv->vval.v_number = 0;
16191 }
16192
16193 /*
16194  * "settabvar()" function
16195  */
16196     static void
16197 f_settabvar(argvars, rettv)
16198     typval_T    *argvars;
16199     typval_T    *rettv;
16200 {
16201     tabpage_T   *save_curtab;
16202     char_u      *varname, *tabvarname;
16203     typval_T    *varp;
16204     tabpage_T   *tp;
16205
16206     rettv->vval.v_number = 0;
16207
16208     if (check_restricted() || check_secure())
16209         return;
16210
16211     tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
16212     varname = get_tv_string_chk(&argvars[1]);
16213     varp = &argvars[2];
16214
16215     if (tp != NULL && varname != NULL && varp != NULL)
16216     {
16217         save_curtab = curtab;
16218         goto_tabpage_tp(tp);
16219
16220         tabvarname = alloc((unsigned)STRLEN(varname) + 3);
16221         if (tabvarname != NULL)
16222         {
16223             STRCPY(tabvarname, "t:");
16224             STRCPY(tabvarname + 2, varname);
16225             set_var(tabvarname, varp, TRUE);
16226             vim_free(tabvarname);
16227         }
16228
16229         /* Restore current tabpage */
16230         if (valid_tabpage(save_curtab))
16231             goto_tabpage_tp(save_curtab);
16232     }
16233 }
16234
16235 /*
16236  * "settabwinvar()" function
16237  */
16238     static void
16239 f_settabwinvar(argvars, rettv)
16240     typval_T    *argvars;
16241     typval_T    *rettv;
16242 {
16243     setwinvar(argvars, rettv, 1);
16244 }
16245
16246 /*
16247  * "setwinvar()" function
16248  */
16249     static void
16250 f_setwinvar(argvars, rettv)
16251     typval_T    *argvars;
16252     typval_T    *rettv;
16253 {
16254     setwinvar(argvars, rettv, 0);
16255 }
16256
16257 /*
16258  * "setwinvar()" and "settabwinvar()" functions
16259  */
16260     static void
16261 setwinvar(argvars, rettv, off)
16262     typval_T    *argvars;
16263     typval_T    *rettv UNUSED;
16264     int         off;
16265 {
16266     win_T       *win;
16267 #ifdef FEAT_WINDOWS
16268     win_T       *save_curwin;
16269     tabpage_T   *save_curtab;
16270 #endif
16271     char_u      *varname, *winvarname;
16272     typval_T    *varp;
16273     char_u      nbuf[NUMBUFLEN];
16274     tabpage_T   *tp;
16275
16276     if (check_restricted() || check_secure())
16277         return;
16278
16279 #ifdef FEAT_WINDOWS
16280     if (off == 1)
16281         tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
16282     else
16283         tp = curtab;
16284 #endif
16285     win = find_win_by_nr(&argvars[off], tp);
16286     varname = get_tv_string_chk(&argvars[off + 1]);
16287     varp = &argvars[off + 2];
16288
16289     if (win != NULL && varname != NULL && varp != NULL)
16290     {
16291 #ifdef FEAT_WINDOWS
16292         /* set curwin to be our win, temporarily */
16293         save_curwin = curwin;
16294         save_curtab = curtab;
16295         goto_tabpage_tp(tp);
16296         if (!win_valid(win))
16297             return;
16298         curwin = win;
16299         curbuf = curwin->w_buffer;
16300 #endif
16301
16302         if (*varname == '&')
16303         {
16304             long        numval;
16305             char_u      *strval;
16306             int         error = FALSE;
16307
16308             ++varname;
16309             numval = get_tv_number_chk(varp, &error);
16310             strval = get_tv_string_buf_chk(varp, nbuf);
16311             if (!error && strval != NULL)
16312                 set_option_value(varname, numval, strval, OPT_LOCAL);
16313         }
16314         else
16315         {
16316             winvarname = alloc((unsigned)STRLEN(varname) + 3);
16317             if (winvarname != NULL)
16318             {
16319                 STRCPY(winvarname, "w:");
16320                 STRCPY(winvarname + 2, varname);
16321                 set_var(winvarname, varp, TRUE);
16322                 vim_free(winvarname);
16323             }
16324         }
16325
16326 #ifdef FEAT_WINDOWS
16327         /* Restore current tabpage and window, if still valid (autocomands can
16328          * make them invalid). */
16329         if (valid_tabpage(save_curtab))
16330             goto_tabpage_tp(save_curtab);
16331         if (win_valid(save_curwin))
16332         {
16333             curwin = save_curwin;
16334             curbuf = curwin->w_buffer;
16335         }
16336 #endif
16337     }
16338 }
16339
16340 /*
16341  * "shellescape({string})" function
16342  */
16343     static void
16344 f_shellescape(argvars, rettv)
16345     typval_T    *argvars;
16346     typval_T    *rettv;
16347 {
16348     rettv->vval.v_string = vim_strsave_shellescape(
16349                        get_tv_string(&argvars[0]), non_zero_arg(&argvars[1]));
16350     rettv->v_type = VAR_STRING;
16351 }
16352
16353 /*
16354  * "simplify()" function
16355  */
16356     static void
16357 f_simplify(argvars, rettv)
16358     typval_T    *argvars;
16359     typval_T    *rettv;
16360 {
16361     char_u      *p;
16362
16363     p = get_tv_string(&argvars[0]);
16364     rettv->vval.v_string = vim_strsave(p);
16365     simplify_filename(rettv->vval.v_string);    /* simplify in place */
16366     rettv->v_type = VAR_STRING;
16367 }
16368
16369 #ifdef FEAT_FLOAT
16370 /*
16371  * "sin()" function
16372  */
16373     static void
16374 f_sin(argvars, rettv)
16375     typval_T    *argvars;
16376     typval_T    *rettv;
16377 {
16378     float_T     f;
16379
16380     rettv->v_type = VAR_FLOAT;
16381     if (get_float_arg(argvars, &f) == OK)
16382         rettv->vval.v_float = sin(f);
16383     else
16384         rettv->vval.v_float = 0.0;
16385 }
16386
16387 /*
16388  * "sinh()" function
16389  */
16390     static void
16391 f_sinh(argvars, rettv)
16392     typval_T    *argvars;
16393     typval_T    *rettv;
16394 {
16395     float_T     f;
16396
16397     rettv->v_type = VAR_FLOAT;
16398     if (get_float_arg(argvars, &f) == OK)
16399         rettv->vval.v_float = sinh(f);
16400     else
16401         rettv->vval.v_float = 0.0;
16402 }
16403 #endif
16404
16405 static int
16406 #ifdef __BORLANDC__
16407     _RTLENTRYF
16408 #endif
16409         item_compare __ARGS((const void *s1, const void *s2));
16410 static int
16411 #ifdef __BORLANDC__
16412     _RTLENTRYF
16413 #endif
16414         item_compare2 __ARGS((const void *s1, const void *s2));
16415
16416 static int      item_compare_ic;
16417 static char_u   *item_compare_func;
16418 static dict_T   *item_compare_selfdict;
16419 static int      item_compare_func_err;
16420 #define ITEM_COMPARE_FAIL 999
16421
16422 /*
16423  * Compare functions for f_sort() below.
16424  */
16425     static int
16426 #ifdef __BORLANDC__
16427 _RTLENTRYF
16428 #endif
16429 item_compare(s1, s2)
16430     const void  *s1;
16431     const void  *s2;
16432 {
16433     char_u      *p1, *p2;
16434     char_u      *tofree1, *tofree2;
16435     int         res;
16436     char_u      numbuf1[NUMBUFLEN];
16437     char_u      numbuf2[NUMBUFLEN];
16438
16439     p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
16440     p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
16441     if (p1 == NULL)
16442         p1 = (char_u *)"";
16443     if (p2 == NULL)
16444         p2 = (char_u *)"";
16445     if (item_compare_ic)
16446         res = STRICMP(p1, p2);
16447     else
16448         res = STRCMP(p1, p2);
16449     vim_free(tofree1);
16450     vim_free(tofree2);
16451     return res;
16452 }
16453
16454     static int
16455 #ifdef __BORLANDC__
16456 _RTLENTRYF
16457 #endif
16458 item_compare2(s1, s2)
16459     const void  *s1;
16460     const void  *s2;
16461 {
16462     int         res;
16463     typval_T    rettv;
16464     typval_T    argv[3];
16465     int         dummy;
16466
16467     /* shortcut after failure in previous call; compare all items equal */
16468     if (item_compare_func_err)
16469         return 0;
16470
16471     /* copy the values.  This is needed to be able to set v_lock to VAR_FIXED
16472      * in the copy without changing the original list items. */
16473     copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
16474     copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
16475
16476     rettv.v_type = VAR_UNKNOWN;         /* clear_tv() uses this */
16477     res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
16478                                  &rettv, 2, argv, 0L, 0L, &dummy, TRUE,
16479                                  item_compare_selfdict);
16480     clear_tv(&argv[0]);
16481     clear_tv(&argv[1]);
16482
16483     if (res == FAIL)
16484         res = ITEM_COMPARE_FAIL;
16485     else
16486         res = get_tv_number_chk(&rettv, &item_compare_func_err);
16487     if (item_compare_func_err)
16488         res = ITEM_COMPARE_FAIL;  /* return value has wrong type */
16489     clear_tv(&rettv);
16490     return res;
16491 }
16492
16493 /*
16494  * "sort({list})" function
16495  */
16496     static void
16497 f_sort(argvars, rettv)
16498     typval_T    *argvars;
16499     typval_T    *rettv;
16500 {
16501     list_T      *l;
16502     listitem_T  *li;
16503     listitem_T  **ptrs;
16504     long        len;
16505     long        i;
16506
16507     if (argvars[0].v_type != VAR_LIST)
16508         EMSG2(_(e_listarg), "sort()");
16509     else
16510     {
16511         l = argvars[0].vval.v_list;
16512         if (l == NULL || tv_check_lock(l->lv_lock,
16513                                              (char_u *)_("sort() argument")))
16514             return;
16515         rettv->vval.v_list = l;
16516         rettv->v_type = VAR_LIST;
16517         ++l->lv_refcount;
16518
16519         len = list_len(l);
16520         if (len <= 1)
16521             return;     /* short list sorts pretty quickly */
16522
16523         item_compare_ic = FALSE;
16524         item_compare_func = NULL;
16525         item_compare_selfdict = NULL;
16526         if (argvars[1].v_type != VAR_UNKNOWN)
16527         {
16528             /* optional second argument: {func} */
16529             if (argvars[1].v_type == VAR_FUNC)
16530                 item_compare_func = argvars[1].vval.v_string;
16531             else
16532             {
16533                 int         error = FALSE;
16534
16535                 i = get_tv_number_chk(&argvars[1], &error);
16536                 if (error)
16537                     return;             /* type error; errmsg already given */
16538                 if (i == 1)
16539                     item_compare_ic = TRUE;
16540                 else
16541                     item_compare_func = get_tv_string(&argvars[1]);
16542             }
16543
16544             if (argvars[2].v_type != VAR_UNKNOWN)
16545             {
16546                 /* optional third argument: {dict} */
16547                 if (argvars[2].v_type != VAR_DICT)
16548                 {
16549                     EMSG(_(e_dictreq));
16550                     return;
16551                 }
16552                 item_compare_selfdict = argvars[2].vval.v_dict;
16553             }
16554         }
16555
16556         /* Make an array with each entry pointing to an item in the List. */
16557         ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
16558         if (ptrs == NULL)
16559             return;
16560         i = 0;
16561         for (li = l->lv_first; li != NULL; li = li->li_next)
16562             ptrs[i++] = li;
16563
16564         item_compare_func_err = FALSE;
16565         /* test the compare function */
16566         if (item_compare_func != NULL
16567                 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
16568                                                          == ITEM_COMPARE_FAIL)
16569             EMSG(_("E702: Sort compare function failed"));
16570         else
16571         {
16572             /* Sort the array with item pointers. */
16573             qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
16574                     item_compare_func == NULL ? item_compare : item_compare2);
16575
16576             if (!item_compare_func_err)
16577             {
16578                 /* Clear the List and append the items in the sorted order. */
16579                 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
16580                 l->lv_len = 0;
16581                 for (i = 0; i < len; ++i)
16582                     list_append(l, ptrs[i]);
16583             }
16584         }
16585
16586         vim_free(ptrs);
16587     }
16588 }
16589
16590 /*
16591  * "soundfold({word})" function
16592  */
16593     static void
16594 f_soundfold(argvars, rettv)
16595     typval_T    *argvars;
16596     typval_T    *rettv;
16597 {
16598     char_u      *s;
16599
16600     rettv->v_type = VAR_STRING;
16601     s = get_tv_string(&argvars[0]);
16602 #ifdef FEAT_SPELL
16603     rettv->vval.v_string = eval_soundfold(s);
16604 #else
16605     rettv->vval.v_string = vim_strsave(s);
16606 #endif
16607 }
16608
16609 /*
16610  * "spellbadword()" function
16611  */
16612     static void
16613 f_spellbadword(argvars, rettv)
16614     typval_T    *argvars UNUSED;
16615     typval_T    *rettv;
16616 {
16617     char_u      *word = (char_u *)"";
16618     hlf_T       attr = HLF_COUNT;
16619     int         len = 0;
16620
16621     if (rettv_list_alloc(rettv) == FAIL)
16622         return;
16623
16624 #ifdef FEAT_SPELL
16625     if (argvars[0].v_type == VAR_UNKNOWN)
16626     {
16627         /* Find the start and length of the badly spelled word. */
16628         len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
16629         if (len != 0)
16630             word = ml_get_cursor();
16631     }
16632     else if (curwin->w_p_spell && *curbuf->b_s.b_p_spl != NUL)
16633     {
16634         char_u  *str = get_tv_string_chk(&argvars[0]);
16635         int     capcol = -1;
16636
16637         if (str != NULL)
16638         {
16639             /* Check the argument for spelling. */
16640             while (*str != NUL)
16641             {
16642                 len = spell_check(curwin, str, &attr, &capcol, FALSE);
16643                 if (attr != HLF_COUNT)
16644                 {
16645                     word = str;
16646                     break;
16647                 }
16648                 str += len;
16649             }
16650         }
16651     }
16652 #endif
16653
16654     list_append_string(rettv->vval.v_list, word, len);
16655     list_append_string(rettv->vval.v_list, (char_u *)(
16656                         attr == HLF_SPB ? "bad" :
16657                         attr == HLF_SPR ? "rare" :
16658                         attr == HLF_SPL ? "local" :
16659                         attr == HLF_SPC ? "caps" :
16660                         ""), -1);
16661 }
16662
16663 /*
16664  * "spellsuggest()" function
16665  */
16666     static void
16667 f_spellsuggest(argvars, rettv)
16668     typval_T    *argvars UNUSED;
16669     typval_T    *rettv;
16670 {
16671 #ifdef FEAT_SPELL
16672     char_u      *str;
16673     int         typeerr = FALSE;
16674     int         maxcount;
16675     garray_T    ga;
16676     int         i;
16677     listitem_T  *li;
16678     int         need_capital = FALSE;
16679 #endif
16680
16681     if (rettv_list_alloc(rettv) == FAIL)
16682         return;
16683
16684 #ifdef FEAT_SPELL
16685     if (curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL)
16686     {
16687         str = get_tv_string(&argvars[0]);
16688         if (argvars[1].v_type != VAR_UNKNOWN)
16689         {
16690             maxcount = get_tv_number_chk(&argvars[1], &typeerr);
16691             if (maxcount <= 0)
16692                 return;
16693             if (argvars[2].v_type != VAR_UNKNOWN)
16694             {
16695                 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
16696                 if (typeerr)
16697                     return;
16698             }
16699         }
16700         else
16701             maxcount = 25;
16702
16703         spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
16704
16705         for (i = 0; i < ga.ga_len; ++i)
16706         {
16707             str = ((char_u **)ga.ga_data)[i];
16708
16709             li = listitem_alloc();
16710             if (li == NULL)
16711                 vim_free(str);
16712             else
16713             {
16714                 li->li_tv.v_type = VAR_STRING;
16715                 li->li_tv.v_lock = 0;
16716                 li->li_tv.vval.v_string = str;
16717                 list_append(rettv->vval.v_list, li);
16718             }
16719         }
16720         ga_clear(&ga);
16721     }
16722 #endif
16723 }
16724
16725     static void
16726 f_split(argvars, rettv)
16727     typval_T    *argvars;
16728     typval_T    *rettv;
16729 {
16730     char_u      *str;
16731     char_u      *end;
16732     char_u      *pat = NULL;
16733     regmatch_T  regmatch;
16734     char_u      patbuf[NUMBUFLEN];
16735     char_u      *save_cpo;
16736     int         match;
16737     colnr_T     col = 0;
16738     int         keepempty = FALSE;
16739     int         typeerr = FALSE;
16740
16741     /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
16742     save_cpo = p_cpo;
16743     p_cpo = (char_u *)"";
16744
16745     str = get_tv_string(&argvars[0]);
16746     if (argvars[1].v_type != VAR_UNKNOWN)
16747     {
16748         pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16749         if (pat == NULL)
16750             typeerr = TRUE;
16751         if (argvars[2].v_type != VAR_UNKNOWN)
16752             keepempty = get_tv_number_chk(&argvars[2], &typeerr);
16753     }
16754     if (pat == NULL || *pat == NUL)
16755         pat = (char_u *)"[\\x01- ]\\+";
16756
16757     if (rettv_list_alloc(rettv) == FAIL)
16758         return;
16759     if (typeerr)
16760         return;
16761
16762     regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
16763     if (regmatch.regprog != NULL)
16764     {
16765         regmatch.rm_ic = FALSE;
16766         while (*str != NUL || keepempty)
16767         {
16768             if (*str == NUL)
16769                 match = FALSE;  /* empty item at the end */
16770             else
16771                 match = vim_regexec_nl(&regmatch, str, col);
16772             if (match)
16773                 end = regmatch.startp[0];
16774             else
16775                 end = str + STRLEN(str);
16776             if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
16777                            && *str != NUL && match && end < regmatch.endp[0]))
16778             {
16779                 if (list_append_string(rettv->vval.v_list, str,
16780                                                     (int)(end - str)) == FAIL)
16781                     break;
16782             }
16783             if (!match)
16784                 break;
16785             /* Advance to just after the match. */
16786             if (regmatch.endp[0] > str)
16787                 col = 0;
16788             else
16789             {
16790                 /* Don't get stuck at the same match. */
16791 #ifdef FEAT_MBYTE
16792                 col = (*mb_ptr2len)(regmatch.endp[0]);
16793 #else
16794                 col = 1;
16795 #endif
16796             }
16797             str = regmatch.endp[0];
16798         }
16799
16800         vim_free(regmatch.regprog);
16801     }
16802
16803     p_cpo = save_cpo;
16804 }
16805
16806 #ifdef FEAT_FLOAT
16807 /*
16808  * "sqrt()" function
16809  */
16810     static void
16811 f_sqrt(argvars, rettv)
16812     typval_T    *argvars;
16813     typval_T    *rettv;
16814 {
16815     float_T     f;
16816
16817     rettv->v_type = VAR_FLOAT;
16818     if (get_float_arg(argvars, &f) == OK)
16819         rettv->vval.v_float = sqrt(f);
16820     else
16821         rettv->vval.v_float = 0.0;
16822 }
16823
16824 /*
16825  * "str2float()" function
16826  */
16827     static void
16828 f_str2float(argvars, rettv)
16829     typval_T    *argvars;
16830     typval_T    *rettv;
16831 {
16832     char_u *p = skipwhite(get_tv_string(&argvars[0]));
16833
16834     if (*p == '+')
16835         p = skipwhite(p + 1);
16836     (void)string2float(p, &rettv->vval.v_float);
16837     rettv->v_type = VAR_FLOAT;
16838 }
16839 #endif
16840
16841 /*
16842  * "str2nr()" function
16843  */
16844     static void
16845 f_str2nr(argvars, rettv)
16846     typval_T    *argvars;
16847     typval_T    *rettv;
16848 {
16849     int         base = 10;
16850     char_u      *p;
16851     long        n;
16852
16853     if (argvars[1].v_type != VAR_UNKNOWN)
16854     {
16855         base = get_tv_number(&argvars[1]);
16856         if (base != 8 && base != 10 && base != 16)
16857         {
16858             EMSG(_(e_invarg));
16859             return;
16860         }
16861     }
16862
16863     p = skipwhite(get_tv_string(&argvars[0]));
16864     if (*p == '+')
16865         p = skipwhite(p + 1);
16866     vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
16867     rettv->vval.v_number = n;
16868 }
16869
16870 #ifdef HAVE_STRFTIME
16871 /*
16872  * "strftime({format}[, {time}])" function
16873  */
16874     static void
16875 f_strftime(argvars, rettv)
16876     typval_T    *argvars;
16877     typval_T    *rettv;
16878 {
16879     char_u      result_buf[256];
16880     struct tm   *curtime;
16881     time_t      seconds;
16882     char_u      *p;
16883
16884     rettv->v_type = VAR_STRING;
16885
16886     p = get_tv_string(&argvars[0]);
16887     if (argvars[1].v_type == VAR_UNKNOWN)
16888         seconds = time(NULL);
16889     else
16890         seconds = (time_t)get_tv_number(&argvars[1]);
16891     curtime = localtime(&seconds);
16892     /* MSVC returns NULL for an invalid value of seconds. */
16893     if (curtime == NULL)
16894         rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
16895     else
16896     {
16897 # ifdef FEAT_MBYTE
16898         vimconv_T   conv;
16899         char_u      *enc;
16900
16901         conv.vc_type = CONV_NONE;
16902         enc = enc_locale();
16903         convert_setup(&conv, p_enc, enc);
16904         if (conv.vc_type != CONV_NONE)
16905             p = string_convert(&conv, p, NULL);
16906 # endif
16907         if (p != NULL)
16908             (void)strftime((char *)result_buf, sizeof(result_buf),
16909                                                           (char *)p, curtime);
16910         else
16911             result_buf[0] = NUL;
16912
16913 # ifdef FEAT_MBYTE
16914         if (conv.vc_type != CONV_NONE)
16915             vim_free(p);
16916         convert_setup(&conv, enc, p_enc);
16917         if (conv.vc_type != CONV_NONE)
16918             rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
16919         else
16920 # endif
16921             rettv->vval.v_string = vim_strsave(result_buf);
16922
16923 # ifdef FEAT_MBYTE
16924         /* Release conversion descriptors */
16925         convert_setup(&conv, NULL, NULL);
16926         vim_free(enc);
16927 # endif
16928     }
16929 }
16930 #endif
16931
16932 /*
16933  * "stridx()" function
16934  */
16935     static void
16936 f_stridx(argvars, rettv)
16937     typval_T    *argvars;
16938     typval_T    *rettv;
16939 {
16940     char_u      buf[NUMBUFLEN];
16941     char_u      *needle;
16942     char_u      *haystack;
16943     char_u      *save_haystack;
16944     char_u      *pos;
16945     int         start_idx;
16946
16947     needle = get_tv_string_chk(&argvars[1]);
16948     save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
16949     rettv->vval.v_number = -1;
16950     if (needle == NULL || haystack == NULL)
16951         return;         /* type error; errmsg already given */
16952
16953     if (argvars[2].v_type != VAR_UNKNOWN)
16954     {
16955         int         error = FALSE;
16956
16957         start_idx = get_tv_number_chk(&argvars[2], &error);
16958         if (error || start_idx >= (int)STRLEN(haystack))
16959             return;
16960         if (start_idx >= 0)
16961             haystack += start_idx;
16962     }
16963
16964     pos = (char_u *)strstr((char *)haystack, (char *)needle);
16965     if (pos != NULL)
16966         rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
16967 }
16968
16969 /*
16970  * "string()" function
16971  */
16972     static void
16973 f_string(argvars, rettv)
16974     typval_T    *argvars;
16975     typval_T    *rettv;
16976 {
16977     char_u      *tofree;
16978     char_u      numbuf[NUMBUFLEN];
16979
16980     rettv->v_type = VAR_STRING;
16981     rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
16982     /* Make a copy if we have a value but it's not in allocated memory. */
16983     if (rettv->vval.v_string != NULL && tofree == NULL)
16984         rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
16985 }
16986
16987 /*
16988  * "strlen()" function
16989  */
16990     static void
16991 f_strlen(argvars, rettv)
16992     typval_T    *argvars;
16993     typval_T    *rettv;
16994 {
16995     rettv->vval.v_number = (varnumber_T)(STRLEN(
16996                                               get_tv_string(&argvars[0])));
16997 }
16998
16999 /*
17000  * "strchars()" function
17001  */
17002     static void
17003 f_strchars(argvars, rettv)
17004     typval_T    *argvars;
17005     typval_T    *rettv;
17006 {
17007     char_u              *s = get_tv_string(&argvars[0]);
17008 #ifdef FEAT_MBYTE
17009     varnumber_T         len = 0;
17010
17011     while (*s != NUL)
17012     {
17013         mb_cptr2char_adv(&s);
17014         ++len;
17015     }
17016     rettv->vval.v_number = len;
17017 #else
17018     rettv->vval.v_number = (varnumber_T)(STRLEN(s));
17019 #endif
17020 }
17021
17022 /*
17023  * "strdisplaywidth()" function
17024  */
17025     static void
17026 f_strdisplaywidth(argvars, rettv)
17027     typval_T    *argvars;
17028     typval_T    *rettv;
17029 {
17030     char_u      *s = get_tv_string(&argvars[0]);
17031     int         col = 0;
17032
17033     if (argvars[1].v_type != VAR_UNKNOWN)
17034         col = get_tv_number(&argvars[1]);
17035
17036     rettv->vval.v_number = (varnumber_T)(linetabsize_col(col, s) - col);
17037 }
17038
17039 /*
17040  * "strwidth()" function
17041  */
17042     static void
17043 f_strwidth(argvars, rettv)
17044     typval_T    *argvars;
17045     typval_T    *rettv;
17046 {
17047     char_u      *s = get_tv_string(&argvars[0]);
17048
17049     rettv->vval.v_number = (varnumber_T)(
17050 #ifdef FEAT_MBYTE
17051             mb_string2cells(s, -1)
17052 #else
17053             STRLEN(s)
17054 #endif
17055             );
17056 }
17057
17058 /*
17059  * "strpart()" function
17060  */
17061     static void
17062 f_strpart(argvars, rettv)
17063     typval_T    *argvars;
17064     typval_T    *rettv;
17065 {
17066     char_u      *p;
17067     int         n;
17068     int         len;
17069     int         slen;
17070     int         error = FALSE;
17071
17072     p = get_tv_string(&argvars[0]);
17073     slen = (int)STRLEN(p);
17074
17075     n = get_tv_number_chk(&argvars[1], &error);
17076     if (error)
17077         len = 0;
17078     else if (argvars[2].v_type != VAR_UNKNOWN)
17079         len = get_tv_number(&argvars[2]);
17080     else
17081         len = slen - n;     /* default len: all bytes that are available. */
17082
17083     /*
17084      * Only return the overlap between the specified part and the actual
17085      * string.
17086      */
17087     if (n < 0)
17088     {
17089         len += n;
17090         n = 0;
17091     }
17092     else if (n > slen)
17093         n = slen;
17094     if (len < 0)
17095         len = 0;
17096     else if (n + len > slen)
17097         len = slen - n;
17098
17099     rettv->v_type = VAR_STRING;
17100     rettv->vval.v_string = vim_strnsave(p + n, len);
17101 }
17102
17103 /*
17104  * "strridx()" function
17105  */
17106     static void
17107 f_strridx(argvars, rettv)
17108     typval_T    *argvars;
17109     typval_T    *rettv;
17110 {
17111     char_u      buf[NUMBUFLEN];
17112     char_u      *needle;
17113     char_u      *haystack;
17114     char_u      *rest;
17115     char_u      *lastmatch = NULL;
17116     int         haystack_len, end_idx;
17117
17118     needle = get_tv_string_chk(&argvars[1]);
17119     haystack = get_tv_string_buf_chk(&argvars[0], buf);
17120
17121     rettv->vval.v_number = -1;
17122     if (needle == NULL || haystack == NULL)
17123         return;         /* type error; errmsg already given */
17124
17125     haystack_len = (int)STRLEN(haystack);
17126     if (argvars[2].v_type != VAR_UNKNOWN)
17127     {
17128         /* Third argument: upper limit for index */
17129         end_idx = get_tv_number_chk(&argvars[2], NULL);
17130         if (end_idx < 0)
17131             return;     /* can never find a match */
17132     }
17133     else
17134         end_idx = haystack_len;
17135
17136     if (*needle == NUL)
17137     {
17138         /* Empty string matches past the end. */
17139         lastmatch = haystack + end_idx;
17140     }
17141     else
17142     {
17143         for (rest = haystack; *rest != '\0'; ++rest)
17144         {
17145             rest = (char_u *)strstr((char *)rest, (char *)needle);
17146             if (rest == NULL || rest > haystack + end_idx)
17147                 break;
17148             lastmatch = rest;
17149         }
17150     }
17151
17152     if (lastmatch == NULL)
17153         rettv->vval.v_number = -1;
17154     else
17155         rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
17156 }
17157
17158 /*
17159  * "strtrans()" function
17160  */
17161     static void
17162 f_strtrans(argvars, rettv)
17163     typval_T    *argvars;
17164     typval_T    *rettv;
17165 {
17166     rettv->v_type = VAR_STRING;
17167     rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
17168 }
17169
17170 /*
17171  * "submatch()" function
17172  */
17173     static void
17174 f_submatch(argvars, rettv)
17175     typval_T    *argvars;
17176     typval_T    *rettv;
17177 {
17178     rettv->v_type = VAR_STRING;
17179     rettv->vval.v_string =
17180                     reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
17181 }
17182
17183 /*
17184  * "substitute()" function
17185  */
17186     static void
17187 f_substitute(argvars, rettv)
17188     typval_T    *argvars;
17189     typval_T    *rettv;
17190 {
17191     char_u      patbuf[NUMBUFLEN];
17192     char_u      subbuf[NUMBUFLEN];
17193     char_u      flagsbuf[NUMBUFLEN];
17194
17195     char_u      *str = get_tv_string_chk(&argvars[0]);
17196     char_u      *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
17197     char_u      *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
17198     char_u      *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
17199
17200     rettv->v_type = VAR_STRING;
17201     if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
17202         rettv->vval.v_string = NULL;
17203     else
17204         rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
17205 }
17206
17207 /*
17208  * "synID(lnum, col, trans)" function
17209  */
17210     static void
17211 f_synID(argvars, rettv)
17212     typval_T    *argvars UNUSED;
17213     typval_T    *rettv;
17214 {
17215     int         id = 0;
17216 #ifdef FEAT_SYN_HL
17217     long        lnum;
17218     long        col;
17219     int         trans;
17220     int         transerr = FALSE;
17221
17222     lnum = get_tv_lnum(argvars);                /* -1 on type error */
17223     col = get_tv_number(&argvars[1]) - 1;       /* -1 on type error */
17224     trans = get_tv_number_chk(&argvars[2], &transerr);
17225
17226     if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
17227             && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
17228         id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
17229 #endif
17230
17231     rettv->vval.v_number = id;
17232 }
17233
17234 /*
17235  * "synIDattr(id, what [, mode])" function
17236  */
17237     static void
17238 f_synIDattr(argvars, rettv)
17239     typval_T    *argvars UNUSED;
17240     typval_T    *rettv;
17241 {
17242     char_u      *p = NULL;
17243 #ifdef FEAT_SYN_HL
17244     int         id;
17245     char_u      *what;
17246     char_u      *mode;
17247     char_u      modebuf[NUMBUFLEN];
17248     int         modec;
17249
17250     id = get_tv_number(&argvars[0]);
17251     what = get_tv_string(&argvars[1]);
17252     if (argvars[2].v_type != VAR_UNKNOWN)
17253     {
17254         mode = get_tv_string_buf(&argvars[2], modebuf);
17255         modec = TOLOWER_ASC(mode[0]);
17256         if (modec != 't' && modec != 'c' && modec != 'g')
17257             modec = 0;  /* replace invalid with current */
17258     }
17259     else
17260     {
17261 #ifdef FEAT_GUI
17262         if (gui.in_use)
17263             modec = 'g';
17264         else
17265 #endif
17266             if (t_colors > 1)
17267             modec = 'c';
17268         else
17269             modec = 't';
17270     }
17271
17272
17273     switch (TOLOWER_ASC(what[0]))
17274     {
17275         case 'b':
17276                 if (TOLOWER_ASC(what[1]) == 'g')        /* bg[#] */
17277                     p = highlight_color(id, what, modec);
17278                 else                                    /* bold */
17279                     p = highlight_has_attr(id, HL_BOLD, modec);
17280                 break;
17281
17282         case 'f':                                       /* fg[#] or font */
17283                 p = highlight_color(id, what, modec);
17284                 break;
17285
17286         case 'i':
17287                 if (TOLOWER_ASC(what[1]) == 'n')        /* inverse */
17288                     p = highlight_has_attr(id, HL_INVERSE, modec);
17289                 else                                    /* italic */
17290                     p = highlight_has_attr(id, HL_ITALIC, modec);
17291                 break;
17292
17293         case 'n':                                       /* name */
17294                 p = get_highlight_name(NULL, id - 1);
17295                 break;
17296
17297         case 'r':                                       /* reverse */
17298                 p = highlight_has_attr(id, HL_INVERSE, modec);
17299                 break;
17300
17301         case 's':
17302                 if (TOLOWER_ASC(what[1]) == 'p')        /* sp[#] */
17303                     p = highlight_color(id, what, modec);
17304                 else                                    /* standout */
17305                     p = highlight_has_attr(id, HL_STANDOUT, modec);
17306                 break;
17307
17308         case 'u':
17309                 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
17310                                                         /* underline */
17311                     p = highlight_has_attr(id, HL_UNDERLINE, modec);
17312                 else
17313                                                         /* undercurl */
17314                     p = highlight_has_attr(id, HL_UNDERCURL, modec);
17315                 break;
17316     }
17317
17318     if (p != NULL)
17319         p = vim_strsave(p);
17320 #endif
17321     rettv->v_type = VAR_STRING;
17322     rettv->vval.v_string = p;
17323 }
17324
17325 /*
17326  * "synIDtrans(id)" function
17327  */
17328     static void
17329 f_synIDtrans(argvars, rettv)
17330     typval_T    *argvars UNUSED;
17331     typval_T    *rettv;
17332 {
17333     int         id;
17334
17335 #ifdef FEAT_SYN_HL
17336     id = get_tv_number(&argvars[0]);
17337
17338     if (id > 0)
17339         id = syn_get_final_id(id);
17340     else
17341 #endif
17342         id = 0;
17343
17344     rettv->vval.v_number = id;
17345 }
17346
17347 /*
17348  * "synconcealed(lnum, col)" function
17349  */
17350     static void
17351 f_synconcealed(argvars, rettv)
17352     typval_T    *argvars UNUSED;
17353     typval_T    *rettv;
17354 {
17355 #if defined(FEAT_SYN_HL) && defined(FEAT_CONCEAL)
17356     long        lnum;
17357     long        col;
17358     int         syntax_flags = 0;
17359     int         cchar;
17360     int         matchid = 0;
17361     char_u      str[NUMBUFLEN];
17362 #endif
17363
17364     rettv->v_type = VAR_LIST;
17365     rettv->vval.v_list = NULL;
17366
17367 #if defined(FEAT_SYN_HL) && defined(FEAT_CONCEAL)
17368     lnum = get_tv_lnum(argvars);                /* -1 on type error */
17369     col = get_tv_number(&argvars[1]) - 1;       /* -1 on type error */
17370
17371     vim_memset(str, NUL, sizeof(str));
17372
17373     if (rettv_list_alloc(rettv) != FAIL)
17374     {
17375         if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
17376             && col >= 0 && col <= (long)STRLEN(ml_get(lnum))
17377             && curwin->w_p_cole > 0)
17378         {
17379             (void)syn_get_id(curwin, lnum, col, FALSE, NULL, FALSE);
17380             syntax_flags = get_syntax_info(&matchid);
17381
17382             /* get the conceal character */
17383             if ((syntax_flags & HL_CONCEAL) && curwin->w_p_cole < 3)
17384             {
17385                 cchar = syn_get_sub_char();
17386                 if (cchar == NUL && curwin->w_p_cole == 1 && lcs_conceal != NUL)
17387                     cchar = lcs_conceal;
17388                 if (cchar != NUL)
17389                 {
17390 # ifdef FEAT_MBYTE
17391                     if (has_mbyte)
17392                         (*mb_char2bytes)(cchar, str);
17393                     else
17394 # endif
17395                         str[0] = cchar;
17396                 }
17397             }
17398         }
17399
17400         list_append_number(rettv->vval.v_list,
17401                                             (syntax_flags & HL_CONCEAL) != 0);
17402         /* -1 to auto-determine strlen */
17403         list_append_string(rettv->vval.v_list, str, -1);
17404         list_append_number(rettv->vval.v_list, matchid);
17405     }
17406 #endif
17407 }
17408
17409 /*
17410  * "synstack(lnum, col)" function
17411  */
17412     static void
17413 f_synstack(argvars, rettv)
17414     typval_T    *argvars UNUSED;
17415     typval_T    *rettv;
17416 {
17417 #ifdef FEAT_SYN_HL
17418     long        lnum;
17419     long        col;
17420     int         i;
17421     int         id;
17422 #endif
17423
17424     rettv->v_type = VAR_LIST;
17425     rettv->vval.v_list = NULL;
17426
17427 #ifdef FEAT_SYN_HL
17428     lnum = get_tv_lnum(argvars);                /* -1 on type error */
17429     col = get_tv_number(&argvars[1]) - 1;       /* -1 on type error */
17430
17431     if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
17432             && col >= 0 && col <= (long)STRLEN(ml_get(lnum))
17433             && rettv_list_alloc(rettv) != FAIL)
17434     {
17435         (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
17436         for (i = 0; ; ++i)
17437         {
17438             id = syn_get_stack_item(i);
17439             if (id < 0)
17440                 break;
17441             if (list_append_number(rettv->vval.v_list, id) == FAIL)
17442                 break;
17443         }
17444     }
17445 #endif
17446 }
17447
17448 /*
17449  * "system()" function
17450  */
17451     static void
17452 f_system(argvars, rettv)
17453     typval_T    *argvars;
17454     typval_T    *rettv;
17455 {
17456     char_u      *res = NULL;
17457     char_u      *p;
17458     char_u      *infile = NULL;
17459     char_u      buf[NUMBUFLEN];
17460     int         err = FALSE;
17461     FILE        *fd;
17462
17463     if (check_restricted() || check_secure())
17464         goto done;
17465
17466     if (argvars[1].v_type != VAR_UNKNOWN)
17467     {
17468         /*
17469          * Write the string to a temp file, to be used for input of the shell
17470          * command.
17471          */
17472         if ((infile = vim_tempname('i')) == NULL)
17473         {
17474             EMSG(_(e_notmp));
17475             goto done;
17476         }
17477
17478         fd = mch_fopen((char *)infile, WRITEBIN);
17479         if (fd == NULL)
17480         {
17481             EMSG2(_(e_notopen), infile);
17482             goto done;
17483         }
17484         p = get_tv_string_buf_chk(&argvars[1], buf);
17485         if (p == NULL)
17486         {
17487             fclose(fd);
17488             goto done;          /* type error; errmsg already given */
17489         }
17490         if (fwrite(p, STRLEN(p), 1, fd) != 1)
17491             err = TRUE;
17492         if (fclose(fd) != 0)
17493             err = TRUE;
17494         if (err)
17495         {
17496             EMSG(_("E677: Error writing temp file"));
17497             goto done;
17498         }
17499     }
17500
17501     res = get_cmd_output(get_tv_string(&argvars[0]), infile,
17502                                                  SHELL_SILENT | SHELL_COOKED);
17503
17504 #ifdef USE_CR
17505     /* translate <CR> into <NL> */
17506     if (res != NULL)
17507     {
17508         char_u  *s;
17509
17510         for (s = res; *s; ++s)
17511         {
17512             if (*s == CAR)
17513                 *s = NL;
17514         }
17515     }
17516 #else
17517 # ifdef USE_CRNL
17518     /* translate <CR><NL> into <NL> */
17519     if (res != NULL)
17520     {
17521         char_u  *s, *d;
17522
17523         d = res;
17524         for (s = res; *s; ++s)
17525         {
17526             if (s[0] == CAR && s[1] == NL)
17527                 ++s;
17528             *d++ = *s;
17529         }
17530         *d = NUL;
17531     }
17532 # endif
17533 #endif
17534
17535 done:
17536     if (infile != NULL)
17537     {
17538         mch_remove(infile);
17539         vim_free(infile);
17540     }
17541     rettv->v_type = VAR_STRING;
17542     rettv->vval.v_string = res;
17543 }
17544
17545 /*
17546  * "tabpagebuflist()" function
17547  */
17548     static void
17549 f_tabpagebuflist(argvars, rettv)
17550     typval_T    *argvars UNUSED;
17551     typval_T    *rettv UNUSED;
17552 {
17553 #ifdef FEAT_WINDOWS
17554     tabpage_T   *tp;
17555     win_T       *wp = NULL;
17556
17557     if (argvars[0].v_type == VAR_UNKNOWN)
17558         wp = firstwin;
17559     else
17560     {
17561         tp = find_tabpage((int)get_tv_number(&argvars[0]));
17562         if (tp != NULL)
17563             wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
17564     }
17565     if (wp != NULL && rettv_list_alloc(rettv) != FAIL)
17566     {
17567         for (; wp != NULL; wp = wp->w_next)
17568             if (list_append_number(rettv->vval.v_list,
17569                                                 wp->w_buffer->b_fnum) == FAIL)
17570                 break;
17571     }
17572 #endif
17573 }
17574
17575
17576 /*
17577  * "tabpagenr()" function
17578  */
17579     static void
17580 f_tabpagenr(argvars, rettv)
17581     typval_T    *argvars UNUSED;
17582     typval_T    *rettv;
17583 {
17584     int         nr = 1;
17585 #ifdef FEAT_WINDOWS
17586     char_u      *arg;
17587
17588     if (argvars[0].v_type != VAR_UNKNOWN)
17589     {
17590         arg = get_tv_string_chk(&argvars[0]);
17591         nr = 0;
17592         if (arg != NULL)
17593         {
17594             if (STRCMP(arg, "$") == 0)
17595                 nr = tabpage_index(NULL) - 1;
17596             else
17597                 EMSG2(_(e_invexpr2), arg);
17598         }
17599     }
17600     else
17601         nr = tabpage_index(curtab);
17602 #endif
17603     rettv->vval.v_number = nr;
17604 }
17605
17606
17607 #ifdef FEAT_WINDOWS
17608 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
17609
17610 /*
17611  * Common code for tabpagewinnr() and winnr().
17612  */
17613     static int
17614 get_winnr(tp, argvar)
17615     tabpage_T   *tp;
17616     typval_T    *argvar;
17617 {
17618     win_T       *twin;
17619     int         nr = 1;
17620     win_T       *wp;
17621     char_u      *arg;
17622
17623     twin = (tp == curtab) ? curwin : tp->tp_curwin;
17624     if (argvar->v_type != VAR_UNKNOWN)
17625     {
17626         arg = get_tv_string_chk(argvar);
17627         if (arg == NULL)
17628             nr = 0;             /* type error; errmsg already given */
17629         else if (STRCMP(arg, "$") == 0)
17630             twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
17631         else if (STRCMP(arg, "#") == 0)
17632         {
17633             twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
17634             if (twin == NULL)
17635                 nr = 0;
17636         }
17637         else
17638         {
17639             EMSG2(_(e_invexpr2), arg);
17640             nr = 0;
17641         }
17642     }
17643
17644     if (nr > 0)
17645         for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
17646                                               wp != twin; wp = wp->w_next)
17647         {
17648             if (wp == NULL)
17649             {
17650                 /* didn't find it in this tabpage */
17651                 nr = 0;
17652                 break;
17653             }
17654             ++nr;
17655         }
17656     return nr;
17657 }
17658 #endif
17659
17660 /*
17661  * "tabpagewinnr()" function
17662  */
17663     static void
17664 f_tabpagewinnr(argvars, rettv)
17665     typval_T    *argvars UNUSED;
17666     typval_T    *rettv;
17667 {
17668     int         nr = 1;
17669 #ifdef FEAT_WINDOWS
17670     tabpage_T   *tp;
17671
17672     tp = find_tabpage((int)get_tv_number(&argvars[0]));
17673     if (tp == NULL)
17674         nr = 0;
17675     else
17676         nr = get_winnr(tp, &argvars[1]);
17677 #endif
17678     rettv->vval.v_number = nr;
17679 }
17680
17681
17682 /*
17683  * "tagfiles()" function
17684  */
17685     static void
17686 f_tagfiles(argvars, rettv)
17687     typval_T    *argvars UNUSED;
17688     typval_T    *rettv;
17689 {
17690     char_u      *fname;
17691     tagname_T   tn;
17692     int         first;
17693
17694     if (rettv_list_alloc(rettv) == FAIL)
17695         return;
17696     fname = alloc(MAXPATHL);
17697     if (fname == NULL)
17698         return;
17699
17700     for (first = TRUE; ; first = FALSE)
17701         if (get_tagfname(&tn, first, fname) == FAIL
17702                 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
17703             break;
17704     tagname_free(&tn);
17705     vim_free(fname);
17706 }
17707
17708 /*
17709  * "taglist()" function
17710  */
17711     static void
17712 f_taglist(argvars, rettv)
17713     typval_T  *argvars;
17714     typval_T  *rettv;
17715 {
17716     char_u  *tag_pattern;
17717
17718     tag_pattern = get_tv_string(&argvars[0]);
17719
17720     rettv->vval.v_number = FALSE;
17721     if (*tag_pattern == NUL)
17722         return;
17723
17724     if (rettv_list_alloc(rettv) == OK)
17725         (void)get_tags(rettv->vval.v_list, tag_pattern);
17726 }
17727
17728 /*
17729  * "tempname()" function
17730  */
17731     static void
17732 f_tempname(argvars, rettv)
17733     typval_T    *argvars UNUSED;
17734     typval_T    *rettv;
17735 {
17736     static int  x = 'A';
17737
17738     rettv->v_type = VAR_STRING;
17739     rettv->vval.v_string = vim_tempname(x);
17740
17741     /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
17742      * names.  Skip 'I' and 'O', they are used for shell redirection. */
17743     do
17744     {
17745         if (x == 'Z')
17746             x = '0';
17747         else if (x == '9')
17748             x = 'A';
17749         else
17750         {
17751 #ifdef EBCDIC
17752             if (x == 'I')
17753                 x = 'J';
17754             else if (x == 'R')
17755                 x = 'S';
17756             else
17757 #endif
17758                 ++x;
17759         }
17760     } while (x == 'I' || x == 'O');
17761 }
17762
17763 /*
17764  * "test(list)" function: Just checking the walls...
17765  */
17766     static void
17767 f_test(argvars, rettv)
17768     typval_T    *argvars UNUSED;
17769     typval_T    *rettv UNUSED;
17770 {
17771     /* Used for unit testing.  Change the code below to your liking. */
17772 #if 0
17773     listitem_T  *li;
17774     list_T      *l;
17775     char_u      *bad, *good;
17776
17777     if (argvars[0].v_type != VAR_LIST)
17778         return;
17779     l = argvars[0].vval.v_list;
17780     if (l == NULL)
17781         return;
17782     li = l->lv_first;
17783     if (li == NULL)
17784         return;
17785     bad = get_tv_string(&li->li_tv);
17786     li = li->li_next;
17787     if (li == NULL)
17788         return;
17789     good = get_tv_string(&li->li_tv);
17790     rettv->vval.v_number = test_edit_score(bad, good);
17791 #endif
17792 }
17793
17794 #ifdef FEAT_FLOAT
17795 /*
17796  * "tan()" function
17797  */
17798     static void
17799 f_tan(argvars, rettv)
17800     typval_T    *argvars;
17801     typval_T    *rettv;
17802 {
17803     float_T     f;
17804
17805     rettv->v_type = VAR_FLOAT;
17806     if (get_float_arg(argvars, &f) == OK)
17807         rettv->vval.v_float = tan(f);
17808     else
17809         rettv->vval.v_float = 0.0;
17810 }
17811
17812 /*
17813  * "tanh()" function
17814  */
17815     static void
17816 f_tanh(argvars, rettv)
17817     typval_T    *argvars;
17818     typval_T    *rettv;
17819 {
17820     float_T     f;
17821
17822     rettv->v_type = VAR_FLOAT;
17823     if (get_float_arg(argvars, &f) == OK)
17824         rettv->vval.v_float = tanh(f);
17825     else
17826         rettv->vval.v_float = 0.0;
17827 }
17828 #endif
17829
17830 /*
17831  * "tolower(string)" function
17832  */
17833     static void
17834 f_tolower(argvars, rettv)
17835     typval_T    *argvars;
17836     typval_T    *rettv;
17837 {
17838     char_u      *p;
17839
17840     p = vim_strsave(get_tv_string(&argvars[0]));
17841     rettv->v_type = VAR_STRING;
17842     rettv->vval.v_string = p;
17843
17844     if (p != NULL)
17845         while (*p != NUL)
17846         {
17847 #ifdef FEAT_MBYTE
17848             int         l;
17849
17850             if (enc_utf8)
17851             {
17852                 int c, lc;
17853
17854                 c = utf_ptr2char(p);
17855                 lc = utf_tolower(c);
17856                 l = utf_ptr2len(p);
17857                 /* TODO: reallocate string when byte count changes. */
17858                 if (utf_char2len(lc) == l)
17859                     utf_char2bytes(lc, p);
17860                 p += l;
17861             }
17862             else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
17863                 p += l;         /* skip multi-byte character */
17864             else
17865 #endif
17866             {
17867                 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
17868                 ++p;
17869             }
17870         }
17871 }
17872
17873 /*
17874  * "toupper(string)" function
17875  */
17876     static void
17877 f_toupper(argvars, rettv)
17878     typval_T    *argvars;
17879     typval_T    *rettv;
17880 {
17881     rettv->v_type = VAR_STRING;
17882     rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
17883 }
17884
17885 /*
17886  * "tr(string, fromstr, tostr)" function
17887  */
17888     static void
17889 f_tr(argvars, rettv)
17890     typval_T    *argvars;
17891     typval_T    *rettv;
17892 {
17893     char_u      *instr;
17894     char_u      *fromstr;
17895     char_u      *tostr;
17896     char_u      *p;
17897 #ifdef FEAT_MBYTE
17898     int         inlen;
17899     int         fromlen;
17900     int         tolen;
17901     int         idx;
17902     char_u      *cpstr;
17903     int         cplen;
17904     int         first = TRUE;
17905 #endif
17906     char_u      buf[NUMBUFLEN];
17907     char_u      buf2[NUMBUFLEN];
17908     garray_T    ga;
17909
17910     instr = get_tv_string(&argvars[0]);
17911     fromstr = get_tv_string_buf_chk(&argvars[1], buf);
17912     tostr = get_tv_string_buf_chk(&argvars[2], buf2);
17913
17914     /* Default return value: empty string. */
17915     rettv->v_type = VAR_STRING;
17916     rettv->vval.v_string = NULL;
17917     if (fromstr == NULL || tostr == NULL)
17918             return;             /* type error; errmsg already given */
17919     ga_init2(&ga, (int)sizeof(char), 80);
17920
17921 #ifdef FEAT_MBYTE
17922     if (!has_mbyte)
17923 #endif
17924         /* not multi-byte: fromstr and tostr must be the same length */
17925         if (STRLEN(fromstr) != STRLEN(tostr))
17926         {
17927 #ifdef FEAT_MBYTE
17928 error:
17929 #endif
17930             EMSG2(_(e_invarg2), fromstr);
17931             ga_clear(&ga);
17932             return;
17933         }
17934
17935     /* fromstr and tostr have to contain the same number of chars */
17936     while (*instr != NUL)
17937     {
17938 #ifdef FEAT_MBYTE
17939         if (has_mbyte)
17940         {
17941             inlen = (*mb_ptr2len)(instr);
17942             cpstr = instr;
17943             cplen = inlen;
17944             idx = 0;
17945             for (p = fromstr; *p != NUL; p += fromlen)
17946             {
17947                 fromlen = (*mb_ptr2len)(p);
17948                 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
17949                 {
17950                     for (p = tostr; *p != NUL; p += tolen)
17951                     {
17952                         tolen = (*mb_ptr2len)(p);
17953                         if (idx-- == 0)
17954                         {
17955                             cplen = tolen;
17956                             cpstr = p;
17957                             break;
17958                         }
17959                     }
17960                     if (*p == NUL)      /* tostr is shorter than fromstr */
17961                         goto error;
17962                     break;
17963                 }
17964                 ++idx;
17965             }
17966
17967             if (first && cpstr == instr)
17968             {
17969                 /* Check that fromstr and tostr have the same number of
17970                  * (multi-byte) characters.  Done only once when a character
17971                  * of instr doesn't appear in fromstr. */
17972                 first = FALSE;
17973                 for (p = tostr; *p != NUL; p += tolen)
17974                 {
17975                     tolen = (*mb_ptr2len)(p);
17976                     --idx;
17977                 }
17978                 if (idx != 0)
17979                     goto error;
17980             }
17981
17982             ga_grow(&ga, cplen);
17983             mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
17984             ga.ga_len += cplen;
17985
17986             instr += inlen;
17987         }
17988         else
17989 #endif
17990         {
17991             /* When not using multi-byte chars we can do it faster. */
17992             p = vim_strchr(fromstr, *instr);
17993             if (p != NULL)
17994                 ga_append(&ga, tostr[p - fromstr]);
17995             else
17996                 ga_append(&ga, *instr);
17997             ++instr;
17998         }
17999     }
18000
18001     /* add a terminating NUL */
18002     ga_grow(&ga, 1);
18003     ga_append(&ga, NUL);
18004
18005     rettv->vval.v_string = ga.ga_data;
18006 }
18007
18008 #ifdef FEAT_FLOAT
18009 /*
18010  * "trunc({float})" function
18011  */
18012     static void
18013 f_trunc(argvars, rettv)
18014     typval_T    *argvars;
18015     typval_T    *rettv;
18016 {
18017     float_T     f;
18018
18019     rettv->v_type = VAR_FLOAT;
18020     if (get_float_arg(argvars, &f) == OK)
18021         /* trunc() is not in C90, use floor() or ceil() instead. */
18022         rettv->vval.v_float = f > 0 ? floor(f) : ceil(f);
18023     else
18024         rettv->vval.v_float = 0.0;
18025 }
18026 #endif
18027
18028 /*
18029  * "type(expr)" function
18030  */
18031     static void
18032 f_type(argvars, rettv)
18033     typval_T    *argvars;
18034     typval_T    *rettv;
18035 {
18036     int n;
18037
18038     switch (argvars[0].v_type)
18039     {
18040         case VAR_NUMBER: n = 0; break;
18041         case VAR_STRING: n = 1; break;
18042         case VAR_FUNC:   n = 2; break;
18043         case VAR_LIST:   n = 3; break;
18044         case VAR_DICT:   n = 4; break;
18045 #ifdef FEAT_FLOAT
18046         case VAR_FLOAT:  n = 5; break;
18047 #endif
18048         default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
18049     }
18050     rettv->vval.v_number = n;
18051 }
18052
18053 /*
18054  * "undofile(name)" function
18055  */
18056     static void
18057 f_undofile(argvars, rettv)
18058     typval_T    *argvars;
18059     typval_T    *rettv;
18060 {
18061     rettv->v_type = VAR_STRING;
18062 #ifdef FEAT_PERSISTENT_UNDO
18063     {
18064         char_u *ffname = FullName_save(get_tv_string(&argvars[0]), FALSE);
18065
18066         if (ffname != NULL)
18067             rettv->vval.v_string = u_get_undo_file_name(ffname, FALSE);
18068         vim_free(ffname);
18069     }
18070 #else
18071     rettv->vval.v_string = NULL;
18072 #endif
18073 }
18074
18075 /*
18076  * "undotree()" function
18077  */
18078     static void
18079 f_undotree(argvars, rettv)
18080     typval_T    *argvars UNUSED;
18081     typval_T    *rettv;
18082 {
18083     if (rettv_dict_alloc(rettv) == OK)
18084     {
18085         dict_T *dict = rettv->vval.v_dict;
18086         list_T *list;
18087
18088         dict_add_nr_str(dict, "synced", (long)curbuf->b_u_synced, NULL);
18089         dict_add_nr_str(dict, "seq_last", curbuf->b_u_seq_last, NULL);
18090         dict_add_nr_str(dict, "save_last",
18091                                         (long)curbuf->b_u_save_nr_last, NULL);
18092         dict_add_nr_str(dict, "seq_cur", curbuf->b_u_seq_cur, NULL);
18093         dict_add_nr_str(dict, "time_cur", (long)curbuf->b_u_time_cur, NULL);
18094         dict_add_nr_str(dict, "save_cur", (long)curbuf->b_u_save_nr_cur, NULL);
18095
18096         list = list_alloc();
18097         if (list != NULL)
18098         {
18099             u_eval_tree(curbuf->b_u_oldhead, list);
18100             dict_add_list(dict, "entries", list);
18101         }
18102     }
18103 }
18104
18105 /*
18106  * "values(dict)" function
18107  */
18108     static void
18109 f_values(argvars, rettv)
18110     typval_T    *argvars;
18111     typval_T    *rettv;
18112 {
18113     dict_list(argvars, rettv, 1);
18114 }
18115
18116 /*
18117  * "virtcol(string)" function
18118  */
18119     static void
18120 f_virtcol(argvars, rettv)
18121     typval_T    *argvars;
18122     typval_T    *rettv;
18123 {
18124     colnr_T     vcol = 0;
18125     pos_T       *fp;
18126     int         fnum = curbuf->b_fnum;
18127
18128     fp = var2fpos(&argvars[0], FALSE, &fnum);
18129     if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
18130                                                     && fnum == curbuf->b_fnum)
18131     {
18132         getvvcol(curwin, fp, NULL, NULL, &vcol);
18133         ++vcol;
18134     }
18135
18136     rettv->vval.v_number = vcol;
18137 }
18138
18139 /*
18140  * "visualmode()" function
18141  */
18142     static void
18143 f_visualmode(argvars, rettv)
18144     typval_T    *argvars UNUSED;
18145     typval_T    *rettv UNUSED;
18146 {
18147 #ifdef FEAT_VISUAL
18148     char_u      str[2];
18149
18150     rettv->v_type = VAR_STRING;
18151     str[0] = curbuf->b_visual_mode_eval;
18152     str[1] = NUL;
18153     rettv->vval.v_string = vim_strsave(str);
18154
18155     /* A non-zero number or non-empty string argument: reset mode. */
18156     if (non_zero_arg(&argvars[0]))
18157         curbuf->b_visual_mode_eval = NUL;
18158 #endif
18159 }
18160
18161 /*
18162  * "winbufnr(nr)" function
18163  */
18164     static void
18165 f_winbufnr(argvars, rettv)
18166     typval_T    *argvars;
18167     typval_T    *rettv;
18168 {
18169     win_T       *wp;
18170
18171     wp = find_win_by_nr(&argvars[0], NULL);
18172     if (wp == NULL)
18173         rettv->vval.v_number = -1;
18174     else
18175         rettv->vval.v_number = wp->w_buffer->b_fnum;
18176 }
18177
18178 /*
18179  * "wincol()" function
18180  */
18181     static void
18182 f_wincol(argvars, rettv)
18183     typval_T    *argvars UNUSED;
18184     typval_T    *rettv;
18185 {
18186     validate_cursor();
18187     rettv->vval.v_number = curwin->w_wcol + 1;
18188 }
18189
18190 /*
18191  * "winheight(nr)" function
18192  */
18193     static void
18194 f_winheight(argvars, rettv)
18195     typval_T    *argvars;
18196     typval_T    *rettv;
18197 {
18198     win_T       *wp;
18199
18200     wp = find_win_by_nr(&argvars[0], NULL);
18201     if (wp == NULL)
18202         rettv->vval.v_number = -1;
18203     else
18204         rettv->vval.v_number = wp->w_height;
18205 }
18206
18207 /*
18208  * "winline()" function
18209  */
18210     static void
18211 f_winline(argvars, rettv)
18212     typval_T    *argvars UNUSED;
18213     typval_T    *rettv;
18214 {
18215     validate_cursor();
18216     rettv->vval.v_number = curwin->w_wrow + 1;
18217 }
18218
18219 /*
18220  * "winnr()" function
18221  */
18222     static void
18223 f_winnr(argvars, rettv)
18224     typval_T    *argvars UNUSED;
18225     typval_T    *rettv;
18226 {
18227     int         nr = 1;
18228
18229 #ifdef FEAT_WINDOWS
18230     nr = get_winnr(curtab, &argvars[0]);
18231 #endif
18232     rettv->vval.v_number = nr;
18233 }
18234
18235 /*
18236  * "winrestcmd()" function
18237  */
18238     static void
18239 f_winrestcmd(argvars, rettv)
18240     typval_T    *argvars UNUSED;
18241     typval_T    *rettv;
18242 {
18243 #ifdef FEAT_WINDOWS
18244     win_T       *wp;
18245     int         winnr = 1;
18246     garray_T    ga;
18247     char_u      buf[50];
18248
18249     ga_init2(&ga, (int)sizeof(char), 70);
18250     for (wp = firstwin; wp != NULL; wp = wp->w_next)
18251     {
18252         sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
18253         ga_concat(&ga, buf);
18254 # ifdef FEAT_VERTSPLIT
18255         sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
18256         ga_concat(&ga, buf);
18257 # endif
18258         ++winnr;
18259     }
18260     ga_append(&ga, NUL);
18261
18262     rettv->vval.v_string = ga.ga_data;
18263 #else
18264     rettv->vval.v_string = NULL;
18265 #endif
18266     rettv->v_type = VAR_STRING;
18267 }
18268
18269 /*
18270  * "winrestview()" function
18271  */
18272     static void
18273 f_winrestview(argvars, rettv)
18274     typval_T    *argvars;
18275     typval_T    *rettv UNUSED;
18276 {
18277     dict_T      *dict;
18278
18279     if (argvars[0].v_type != VAR_DICT
18280             || (dict = argvars[0].vval.v_dict) == NULL)
18281         EMSG(_(e_invarg));
18282     else
18283     {
18284         curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
18285         curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
18286 #ifdef FEAT_VIRTUALEDIT
18287         curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
18288 #endif
18289         curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
18290         curwin->w_set_curswant = FALSE;
18291
18292         set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
18293 #ifdef FEAT_DIFF
18294         curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
18295 #endif
18296         curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
18297         curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
18298
18299         check_cursor();
18300         changed_cline_bef_curs();
18301         invalidate_botline();
18302         redraw_later(VALID);
18303
18304         if (curwin->w_topline == 0)
18305             curwin->w_topline = 1;
18306         if (curwin->w_topline > curbuf->b_ml.ml_line_count)
18307             curwin->w_topline = curbuf->b_ml.ml_line_count;
18308 #ifdef FEAT_DIFF
18309         check_topfill(curwin, TRUE);
18310 #endif
18311     }
18312 }
18313
18314 /*
18315  * "winsaveview()" function
18316  */
18317     static void
18318 f_winsaveview(argvars, rettv)
18319     typval_T    *argvars UNUSED;
18320     typval_T    *rettv;
18321 {
18322     dict_T      *dict;
18323
18324     if (rettv_dict_alloc(rettv) == FAIL)
18325         return;
18326     dict = rettv->vval.v_dict;
18327
18328     dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
18329     dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
18330 #ifdef FEAT_VIRTUALEDIT
18331     dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
18332 #endif
18333     update_curswant();
18334     dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
18335
18336     dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
18337 #ifdef FEAT_DIFF
18338     dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
18339 #endif
18340     dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
18341     dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
18342 }
18343
18344 /*
18345  * "winwidth(nr)" function
18346  */
18347     static void
18348 f_winwidth(argvars, rettv)
18349     typval_T    *argvars;
18350     typval_T    *rettv;
18351 {
18352     win_T       *wp;
18353
18354     wp = find_win_by_nr(&argvars[0], NULL);
18355     if (wp == NULL)
18356         rettv->vval.v_number = -1;
18357     else
18358 #ifdef FEAT_VERTSPLIT
18359         rettv->vval.v_number = wp->w_width;
18360 #else
18361         rettv->vval.v_number = Columns;
18362 #endif
18363 }
18364
18365 /*
18366  * "writefile()" function
18367  */
18368     static void
18369 f_writefile(argvars, rettv)
18370     typval_T    *argvars;
18371     typval_T    *rettv;
18372 {
18373     int         binary = FALSE;
18374     char_u      *fname;
18375     FILE        *fd;
18376     listitem_T  *li;
18377     char_u      *s;
18378     int         ret = 0;
18379     int         c;
18380
18381     if (check_restricted() || check_secure())
18382         return;
18383
18384     if (argvars[0].v_type != VAR_LIST)
18385     {
18386         EMSG2(_(e_listarg), "writefile()");
18387         return;
18388     }
18389     if (argvars[0].vval.v_list == NULL)
18390         return;
18391
18392     if (argvars[2].v_type != VAR_UNKNOWN
18393                               && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
18394         binary = TRUE;
18395
18396     /* Always open the file in binary mode, library functions have a mind of
18397      * their own about CR-LF conversion. */
18398     fname = get_tv_string(&argvars[1]);
18399     if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
18400     {
18401         EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
18402         ret = -1;
18403     }
18404     else
18405     {
18406         for (li = argvars[0].vval.v_list->lv_first; li != NULL;
18407                                                              li = li->li_next)
18408         {
18409             for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
18410             {
18411                 if (*s == '\n')
18412                     c = putc(NUL, fd);
18413                 else
18414                     c = putc(*s, fd);
18415                 if (c == EOF)
18416                 {
18417                     ret = -1;
18418                     break;
18419                 }
18420             }
18421             if (!binary || li->li_next != NULL)
18422                 if (putc('\n', fd) == EOF)
18423                 {
18424                     ret = -1;
18425                     break;
18426                 }
18427             if (ret < 0)
18428             {
18429                 EMSG(_(e_write));
18430                 break;
18431             }
18432         }
18433         fclose(fd);
18434     }
18435
18436     rettv->vval.v_number = ret;
18437 }
18438
18439 /*
18440  * "xor(expr, expr)" function
18441  */
18442     static void
18443 f_xor(argvars, rettv)
18444     typval_T    *argvars;
18445     typval_T    *rettv;
18446 {
18447     rettv->vval.v_number = get_tv_number_chk(&argvars[0], NULL)
18448                                         ^ get_tv_number_chk(&argvars[1], NULL);
18449 }
18450
18451
18452 /*
18453  * Translate a String variable into a position.
18454  * Returns NULL when there is an error.
18455  */
18456     static pos_T *
18457 var2fpos(varp, dollar_lnum, fnum)
18458     typval_T    *varp;
18459     int         dollar_lnum;    /* TRUE when $ is last line */
18460     int         *fnum;          /* set to fnum for '0, 'A, etc. */
18461 {
18462     char_u              *name;
18463     static pos_T        pos;
18464     pos_T               *pp;
18465
18466     /* Argument can be [lnum, col, coladd]. */
18467     if (varp->v_type == VAR_LIST)
18468     {
18469         list_T          *l;
18470         int             len;
18471         int             error = FALSE;
18472         listitem_T      *li;
18473
18474         l = varp->vval.v_list;
18475         if (l == NULL)
18476             return NULL;
18477
18478         /* Get the line number */
18479         pos.lnum = list_find_nr(l, 0L, &error);
18480         if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
18481             return NULL;        /* invalid line number */
18482
18483         /* Get the column number */
18484         pos.col = list_find_nr(l, 1L, &error);
18485         if (error)
18486             return NULL;
18487         len = (long)STRLEN(ml_get(pos.lnum));
18488
18489         /* We accept "$" for the column number: last column. */
18490         li = list_find(l, 1L);
18491         if (li != NULL && li->li_tv.v_type == VAR_STRING
18492                 && li->li_tv.vval.v_string != NULL
18493                 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
18494             pos.col = len + 1;
18495
18496         /* Accept a position up to the NUL after the line. */
18497         if (pos.col == 0 || (int)pos.col > len + 1)
18498             return NULL;        /* invalid column number */
18499         --pos.col;
18500
18501 #ifdef FEAT_VIRTUALEDIT
18502         /* Get the virtual offset.  Defaults to zero. */
18503         pos.coladd = list_find_nr(l, 2L, &error);
18504         if (error)
18505             pos.coladd = 0;
18506 #endif
18507
18508         return &pos;
18509     }
18510
18511     name = get_tv_string_chk(varp);
18512     if (name == NULL)
18513         return NULL;
18514     if (name[0] == '.')                         /* cursor */
18515         return &curwin->w_cursor;
18516 #ifdef FEAT_VISUAL
18517     if (name[0] == 'v' && name[1] == NUL)       /* Visual start */
18518     {
18519         if (VIsual_active)
18520             return &VIsual;
18521         return &curwin->w_cursor;
18522     }
18523 #endif
18524     if (name[0] == '\'')                        /* mark */
18525     {
18526         pp = getmark_fnum(name[1], FALSE, fnum);
18527         if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
18528             return NULL;
18529         return pp;
18530     }
18531
18532 #ifdef FEAT_VIRTUALEDIT
18533     pos.coladd = 0;
18534 #endif
18535
18536     if (name[0] == 'w' && dollar_lnum)
18537     {
18538         pos.col = 0;
18539         if (name[1] == '0')             /* "w0": first visible line */
18540         {
18541             update_topline();
18542             pos.lnum = curwin->w_topline;
18543             return &pos;
18544         }
18545         else if (name[1] == '$')        /* "w$": last visible line */
18546         {
18547             validate_botline();
18548             pos.lnum = curwin->w_botline - 1;
18549             return &pos;
18550         }
18551     }
18552     else if (name[0] == '$')            /* last column or line */
18553     {
18554         if (dollar_lnum)
18555         {
18556             pos.lnum = curbuf->b_ml.ml_line_count;
18557             pos.col = 0;
18558         }
18559         else
18560         {
18561             pos.lnum = curwin->w_cursor.lnum;
18562             pos.col = (colnr_T)STRLEN(ml_get_curline());
18563         }
18564         return &pos;
18565     }
18566     return NULL;
18567 }
18568
18569 /*
18570  * Convert list in "arg" into a position and optional file number.
18571  * When "fnump" is NULL there is no file number, only 3 items.
18572  * Note that the column is passed on as-is, the caller may want to decrement
18573  * it to use 1 for the first column.
18574  * Return FAIL when conversion is not possible, doesn't check the position for
18575  * validity.
18576  */
18577     static int
18578 list2fpos(arg, posp, fnump)
18579     typval_T    *arg;
18580     pos_T       *posp;
18581     int         *fnump;
18582 {
18583     list_T      *l = arg->vval.v_list;
18584     long        i = 0;
18585     long        n;
18586
18587     /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
18588      * when "fnump" isn't NULL and "coladd" is optional. */
18589     if (arg->v_type != VAR_LIST
18590             || l == NULL
18591             || l->lv_len < (fnump == NULL ? 2 : 3)
18592             || l->lv_len > (fnump == NULL ? 3 : 4))
18593         return FAIL;
18594
18595     if (fnump != NULL)
18596     {
18597         n = list_find_nr(l, i++, NULL); /* fnum */
18598         if (n < 0)
18599             return FAIL;
18600         if (n == 0)
18601             n = curbuf->b_fnum;         /* current buffer */
18602         *fnump = n;
18603     }
18604
18605     n = list_find_nr(l, i++, NULL);     /* lnum */
18606     if (n < 0)
18607         return FAIL;
18608     posp->lnum = n;
18609
18610     n = list_find_nr(l, i++, NULL);     /* col */
18611     if (n < 0)
18612         return FAIL;
18613     posp->col = n;
18614
18615 #ifdef FEAT_VIRTUALEDIT
18616     n = list_find_nr(l, i, NULL);
18617     if (n < 0)
18618         posp->coladd = 0;
18619     else
18620         posp->coladd = n;
18621 #endif
18622
18623     return OK;
18624 }
18625
18626 /*
18627  * Get the length of an environment variable name.
18628  * Advance "arg" to the first character after the name.
18629  * Return 0 for error.
18630  */
18631     static int
18632 get_env_len(arg)
18633     char_u      **arg;
18634 {
18635     char_u      *p;
18636     int         len;
18637
18638     for (p = *arg; vim_isIDc(*p); ++p)
18639         ;
18640     if (p == *arg)          /* no name found */
18641         return 0;
18642
18643     len = (int)(p - *arg);
18644     *arg = p;
18645     return len;
18646 }
18647
18648 /*
18649  * Get the length of the name of a function or internal variable.
18650  * "arg" is advanced to the first non-white character after the name.
18651  * Return 0 if something is wrong.
18652  */
18653     static int
18654 get_id_len(arg)
18655     char_u      **arg;
18656 {
18657     char_u      *p;
18658     int         len;
18659
18660     /* Find the end of the name. */
18661     for (p = *arg; eval_isnamec(*p); ++p)
18662         ;
18663     if (p == *arg)          /* no name found */
18664         return 0;
18665
18666     len = (int)(p - *arg);
18667     *arg = skipwhite(p);
18668
18669     return len;
18670 }
18671
18672 /*
18673  * Get the length of the name of a variable or function.
18674  * Only the name is recognized, does not handle ".key" or "[idx]".
18675  * "arg" is advanced to the first non-white character after the name.
18676  * Return -1 if curly braces expansion failed.
18677  * Return 0 if something else is wrong.
18678  * If the name contains 'magic' {}'s, expand them and return the
18679  * expanded name in an allocated string via 'alias' - caller must free.
18680  */
18681     static int
18682 get_name_len(arg, alias, evaluate, verbose)
18683     char_u      **arg;
18684     char_u      **alias;
18685     int         evaluate;
18686     int         verbose;
18687 {
18688     int         len;
18689     char_u      *p;
18690     char_u      *expr_start;
18691     char_u      *expr_end;
18692
18693     *alias = NULL;  /* default to no alias */
18694
18695     if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
18696                                                   && (*arg)[2] == (int)KE_SNR)
18697     {
18698         /* hard coded <SNR>, already translated */
18699         *arg += 3;
18700         return get_id_len(arg) + 3;
18701     }
18702     len = eval_fname_script(*arg);
18703     if (len > 0)
18704     {
18705         /* literal "<SID>", "s:" or "<SNR>" */
18706         *arg += len;
18707     }
18708
18709     /*
18710      * Find the end of the name; check for {} construction.
18711      */
18712     p = find_name_end(*arg, &expr_start, &expr_end,
18713                                                len > 0 ? 0 : FNE_CHECK_START);
18714     if (expr_start != NULL)
18715     {
18716         char_u  *temp_string;
18717
18718         if (!evaluate)
18719         {
18720             len += (int)(p - *arg);
18721             *arg = skipwhite(p);
18722             return len;
18723         }
18724
18725         /*
18726          * Include any <SID> etc in the expanded string:
18727          * Thus the -len here.
18728          */
18729         temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
18730         if (temp_string == NULL)
18731             return -1;
18732         *alias = temp_string;
18733         *arg = skipwhite(p);
18734         return (int)STRLEN(temp_string);
18735     }
18736
18737     len += get_id_len(arg);
18738     if (len == 0 && verbose)
18739         EMSG2(_(e_invexpr2), *arg);
18740
18741     return len;
18742 }
18743
18744 /*
18745  * Find the end of a variable or function name, taking care of magic braces.
18746  * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
18747  * start and end of the first magic braces item.
18748  * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
18749  * Return a pointer to just after the name.  Equal to "arg" if there is no
18750  * valid name.
18751  */
18752     static char_u *
18753 find_name_end(arg, expr_start, expr_end, flags)
18754     char_u      *arg;
18755     char_u      **expr_start;
18756     char_u      **expr_end;
18757     int         flags;
18758 {
18759     int         mb_nest = 0;
18760     int         br_nest = 0;
18761     char_u      *p;
18762
18763     if (expr_start != NULL)
18764     {
18765         *expr_start = NULL;
18766         *expr_end = NULL;
18767     }
18768
18769     /* Quick check for valid starting character. */
18770     if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
18771         return arg;
18772
18773     for (p = arg; *p != NUL
18774                     && (eval_isnamec(*p)
18775                         || *p == '{'
18776                         || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
18777                         || mb_nest != 0
18778                         || br_nest != 0); mb_ptr_adv(p))
18779     {
18780         if (*p == '\'')
18781         {
18782             /* skip over 'string' to avoid counting [ and ] inside it. */
18783             for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
18784                 ;
18785             if (*p == NUL)
18786                 break;
18787         }
18788         else if (*p == '"')
18789         {
18790             /* skip over "str\"ing" to avoid counting [ and ] inside it. */
18791             for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
18792                 if (*p == '\\' && p[1] != NUL)
18793                     ++p;
18794             if (*p == NUL)
18795                 break;
18796         }
18797
18798         if (mb_nest == 0)
18799         {
18800             if (*p == '[')
18801                 ++br_nest;
18802             else if (*p == ']')
18803                 --br_nest;
18804         }
18805
18806         if (br_nest == 0)
18807         {
18808             if (*p == '{')
18809             {
18810                 mb_nest++;
18811                 if (expr_start != NULL && *expr_start == NULL)
18812                     *expr_start = p;
18813             }
18814             else if (*p == '}')
18815             {
18816                 mb_nest--;
18817                 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
18818                     *expr_end = p;
18819             }
18820         }
18821     }
18822
18823     return p;
18824 }
18825
18826 /*
18827  * Expands out the 'magic' {}'s in a variable/function name.
18828  * Note that this can call itself recursively, to deal with
18829  * constructs like foo{bar}{baz}{bam}
18830  * The four pointer arguments point to "foo{expre}ss{ion}bar"
18831  *                      "in_start"      ^
18832  *                      "expr_start"       ^
18833  *                      "expr_end"               ^
18834  *                      "in_end"                            ^
18835  *
18836  * Returns a new allocated string, which the caller must free.
18837  * Returns NULL for failure.
18838  */
18839     static char_u *
18840 make_expanded_name(in_start, expr_start, expr_end, in_end)
18841     char_u      *in_start;
18842     char_u      *expr_start;
18843     char_u      *expr_end;
18844     char_u      *in_end;
18845 {
18846     char_u      c1;
18847     char_u      *retval = NULL;
18848     char_u      *temp_result;
18849     char_u      *nextcmd = NULL;
18850
18851     if (expr_end == NULL || in_end == NULL)
18852         return NULL;
18853     *expr_start = NUL;
18854     *expr_end = NUL;
18855     c1 = *in_end;
18856     *in_end = NUL;
18857
18858     temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
18859     if (temp_result != NULL && nextcmd == NULL)
18860     {
18861         retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
18862                                                    + (in_end - expr_end) + 1));
18863         if (retval != NULL)
18864         {
18865             STRCPY(retval, in_start);
18866             STRCAT(retval, temp_result);
18867             STRCAT(retval, expr_end + 1);
18868         }
18869     }
18870     vim_free(temp_result);
18871
18872     *in_end = c1;               /* put char back for error messages */
18873     *expr_start = '{';
18874     *expr_end = '}';
18875
18876     if (retval != NULL)
18877     {
18878         temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
18879         if (expr_start != NULL)
18880         {
18881             /* Further expansion! */
18882             temp_result = make_expanded_name(retval, expr_start,
18883                                                        expr_end, temp_result);
18884             vim_free(retval);
18885             retval = temp_result;
18886         }
18887     }
18888
18889     return retval;
18890 }
18891
18892 /*
18893  * Return TRUE if character "c" can be used in a variable or function name.
18894  * Does not include '{' or '}' for magic braces.
18895  */
18896     static int
18897 eval_isnamec(c)
18898     int     c;
18899 {
18900     return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
18901 }
18902
18903 /*
18904  * Return TRUE if character "c" can be used as the first character in a
18905  * variable or function name (excluding '{' and '}').
18906  */
18907     static int
18908 eval_isnamec1(c)
18909     int     c;
18910 {
18911     return (ASCII_ISALPHA(c) || c == '_');
18912 }
18913
18914 /*
18915  * Set number v: variable to "val".
18916  */
18917     void
18918 set_vim_var_nr(idx, val)
18919     int         idx;
18920     long        val;
18921 {
18922     vimvars[idx].vv_nr = val;
18923 }
18924
18925 /*
18926  * Get number v: variable value.
18927  */
18928     long
18929 get_vim_var_nr(idx)
18930     int         idx;
18931 {
18932     return vimvars[idx].vv_nr;
18933 }
18934
18935 /*
18936  * Get string v: variable value.  Uses a static buffer, can only be used once.
18937  */
18938     char_u *
18939 get_vim_var_str(idx)
18940     int         idx;
18941 {
18942     return get_tv_string(&vimvars[idx].vv_tv);
18943 }
18944
18945 /*
18946  * Get List v: variable value.  Caller must take care of reference count when
18947  * needed.
18948  */
18949     list_T *
18950 get_vim_var_list(idx)
18951     int         idx;
18952 {
18953     return vimvars[idx].vv_list;
18954 }
18955
18956 /*
18957  * Set v:char to character "c".
18958  */
18959     void
18960 set_vim_var_char(c)
18961     int c;
18962 {
18963 #ifdef FEAT_MBYTE
18964     char_u      buf[MB_MAXBYTES];
18965 #else
18966     char_u      buf[2];
18967 #endif
18968
18969 #ifdef FEAT_MBYTE
18970     if (has_mbyte)
18971         buf[(*mb_char2bytes)(c, buf)] = NUL;
18972     else
18973 #endif
18974     {
18975         buf[0] = c;
18976         buf[1] = NUL;
18977     }
18978     set_vim_var_string(VV_CHAR, buf, -1);
18979 }
18980
18981 /*
18982  * Set v:count to "count" and v:count1 to "count1".
18983  * When "set_prevcount" is TRUE first set v:prevcount from v:count.
18984  */
18985     void
18986 set_vcount(count, count1, set_prevcount)
18987     long        count;
18988     long        count1;
18989     int         set_prevcount;
18990 {
18991     if (set_prevcount)
18992         vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
18993     vimvars[VV_COUNT].vv_nr = count;
18994     vimvars[VV_COUNT1].vv_nr = count1;
18995 }
18996
18997 /*
18998  * Set string v: variable to a copy of "val".
18999  */
19000     void
19001 set_vim_var_string(idx, val, len)
19002     int         idx;
19003     char_u      *val;
19004     int         len;        /* length of "val" to use or -1 (whole string) */
19005 {
19006     /* Need to do this (at least) once, since we can't initialize a union.
19007      * Will always be invoked when "v:progname" is set. */
19008     vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
19009
19010     vim_free(vimvars[idx].vv_str);
19011     if (val == NULL)
19012         vimvars[idx].vv_str = NULL;
19013     else if (len == -1)
19014         vimvars[idx].vv_str = vim_strsave(val);
19015     else
19016         vimvars[idx].vv_str = vim_strnsave(val, len);
19017 }
19018
19019 /*
19020  * Set List v: variable to "val".
19021  */
19022     void
19023 set_vim_var_list(idx, val)
19024     int         idx;
19025     list_T      *val;
19026 {
19027     list_unref(vimvars[idx].vv_list);
19028     vimvars[idx].vv_list = val;
19029     if (val != NULL)
19030         ++val->lv_refcount;
19031 }
19032
19033 /*
19034  * Set v:register if needed.
19035  */
19036     void
19037 set_reg_var(c)
19038     int         c;
19039 {
19040     char_u      regname;
19041
19042     if (c == 0 || c == ' ')
19043         regname = '"';
19044     else
19045         regname = c;
19046     /* Avoid free/alloc when the value is already right. */
19047     if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
19048         set_vim_var_string(VV_REG, &regname, 1);
19049 }
19050
19051 /*
19052  * Get or set v:exception.  If "oldval" == NULL, return the current value.
19053  * Otherwise, restore the value to "oldval" and return NULL.
19054  * Must always be called in pairs to save and restore v:exception!  Does not
19055  * take care of memory allocations.
19056  */
19057     char_u *
19058 v_exception(oldval)
19059     char_u      *oldval;
19060 {
19061     if (oldval == NULL)
19062         return vimvars[VV_EXCEPTION].vv_str;
19063
19064     vimvars[VV_EXCEPTION].vv_str = oldval;
19065     return NULL;
19066 }
19067
19068 /*
19069  * Get or set v:throwpoint.  If "oldval" == NULL, return the current value.
19070  * Otherwise, restore the value to "oldval" and return NULL.
19071  * Must always be called in pairs to save and restore v:throwpoint!  Does not
19072  * take care of memory allocations.
19073  */
19074     char_u *
19075 v_throwpoint(oldval)
19076     char_u      *oldval;
19077 {
19078     if (oldval == NULL)
19079         return vimvars[VV_THROWPOINT].vv_str;
19080
19081     vimvars[VV_THROWPOINT].vv_str = oldval;
19082     return NULL;
19083 }
19084
19085 #if defined(FEAT_AUTOCMD) || defined(PROTO)
19086 /*
19087  * Set v:cmdarg.
19088  * If "eap" != NULL, use "eap" to generate the value and return the old value.
19089  * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
19090  * Must always be called in pairs!
19091  */
19092     char_u *
19093 set_cmdarg(eap, oldarg)
19094     exarg_T     *eap;
19095     char_u      *oldarg;
19096 {
19097     char_u      *oldval;
19098     char_u      *newval;
19099     unsigned    len;
19100
19101     oldval = vimvars[VV_CMDARG].vv_str;
19102     if (eap == NULL)
19103     {
19104         vim_free(oldval);
19105         vimvars[VV_CMDARG].vv_str = oldarg;
19106         return NULL;
19107     }
19108
19109     if (eap->force_bin == FORCE_BIN)
19110         len = 6;
19111     else if (eap->force_bin == FORCE_NOBIN)
19112         len = 8;
19113     else
19114         len = 0;
19115
19116     if (eap->read_edit)
19117         len += 7;
19118
19119     if (eap->force_ff != 0)
19120         len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
19121 # ifdef FEAT_MBYTE
19122     if (eap->force_enc != 0)
19123         len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
19124     if (eap->bad_char != 0)
19125         len += 7 + 4;  /* " ++bad=" + "keep" or "drop" */
19126 # endif
19127
19128     newval = alloc(len + 1);
19129     if (newval == NULL)
19130         return NULL;
19131
19132     if (eap->force_bin == FORCE_BIN)
19133         sprintf((char *)newval, " ++bin");
19134     else if (eap->force_bin == FORCE_NOBIN)
19135         sprintf((char *)newval, " ++nobin");
19136     else
19137         *newval = NUL;
19138
19139     if (eap->read_edit)
19140         STRCAT(newval, " ++edit");
19141
19142     if (eap->force_ff != 0)
19143         sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
19144                                                 eap->cmd + eap->force_ff);
19145 # ifdef FEAT_MBYTE
19146     if (eap->force_enc != 0)
19147         sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
19148                                                eap->cmd + eap->force_enc);
19149     if (eap->bad_char == BAD_KEEP)
19150         STRCPY(newval + STRLEN(newval), " ++bad=keep");
19151     else if (eap->bad_char == BAD_DROP)
19152         STRCPY(newval + STRLEN(newval), " ++bad=drop");
19153     else if (eap->bad_char != 0)
19154         sprintf((char *)newval + STRLEN(newval), " ++bad=%c", eap->bad_char);
19155 # endif
19156     vimvars[VV_CMDARG].vv_str = newval;
19157     return oldval;
19158 }
19159 #endif
19160
19161 /*
19162  * Get the value of internal variable "name".
19163  * Return OK or FAIL.
19164  */
19165     static int
19166 get_var_tv(name, len, rettv, verbose)
19167     char_u      *name;
19168     int         len;            /* length of "name" */
19169     typval_T    *rettv;         /* NULL when only checking existence */
19170     int         verbose;        /* may give error message */
19171 {
19172     int         ret = OK;
19173     typval_T    *tv = NULL;
19174     typval_T    atv;
19175     dictitem_T  *v;
19176     int         cc;
19177
19178     /* truncate the name, so that we can use strcmp() */
19179     cc = name[len];
19180     name[len] = NUL;
19181
19182     /*
19183      * Check for "b:changedtick".
19184      */
19185     if (STRCMP(name, "b:changedtick") == 0)
19186     {
19187         atv.v_type = VAR_NUMBER;
19188         atv.vval.v_number = curbuf->b_changedtick;
19189         tv = &atv;
19190     }
19191
19192     /*
19193      * Check for user-defined variables.
19194      */
19195     else
19196     {
19197         v = find_var(name, NULL);
19198         if (v != NULL)
19199             tv = &v->di_tv;
19200     }
19201
19202     if (tv == NULL)
19203     {
19204         if (rettv != NULL && verbose)
19205             EMSG2(_(e_undefvar), name);
19206         ret = FAIL;
19207     }
19208     else if (rettv != NULL)
19209         copy_tv(tv, rettv);
19210
19211     name[len] = cc;
19212
19213     return ret;
19214 }
19215
19216 /*
19217  * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
19218  * Also handle function call with Funcref variable: func(expr)
19219  * Can all be combined: dict.func(expr)[idx]['func'](expr)
19220  */
19221     static int
19222 handle_subscript(arg, rettv, evaluate, verbose)
19223     char_u      **arg;
19224     typval_T    *rettv;
19225     int         evaluate;       /* do more than finding the end */
19226     int         verbose;        /* give error messages */
19227 {
19228     int         ret = OK;
19229     dict_T      *selfdict = NULL;
19230     char_u      *s;
19231     int         len;
19232     typval_T    functv;
19233
19234     while (ret == OK
19235             && (**arg == '['
19236                 || (**arg == '.' && rettv->v_type == VAR_DICT)
19237                 || (**arg == '(' && rettv->v_type == VAR_FUNC))
19238             && !vim_iswhite(*(*arg - 1)))
19239     {
19240         if (**arg == '(')
19241         {
19242             /* need to copy the funcref so that we can clear rettv */
19243             functv = *rettv;
19244             rettv->v_type = VAR_UNKNOWN;
19245
19246             /* Invoke the function.  Recursive! */
19247             s = functv.vval.v_string;
19248             ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
19249                         curwin->w_cursor.lnum, curwin->w_cursor.lnum,
19250                         &len, evaluate, selfdict);
19251
19252             /* Clear the funcref afterwards, so that deleting it while
19253              * evaluating the arguments is possible (see test55). */
19254             clear_tv(&functv);
19255
19256             /* Stop the expression evaluation when immediately aborting on
19257              * error, or when an interrupt occurred or an exception was thrown
19258              * but not caught. */
19259             if (aborting())
19260             {
19261                 if (ret == OK)
19262                     clear_tv(rettv);
19263                 ret = FAIL;
19264             }
19265             dict_unref(selfdict);
19266             selfdict = NULL;
19267         }
19268         else /* **arg == '[' || **arg == '.' */
19269         {
19270             dict_unref(selfdict);
19271             if (rettv->v_type == VAR_DICT)
19272             {
19273                 selfdict = rettv->vval.v_dict;
19274                 if (selfdict != NULL)
19275                     ++selfdict->dv_refcount;
19276             }
19277             else
19278                 selfdict = NULL;
19279             if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
19280             {
19281                 clear_tv(rettv);
19282                 ret = FAIL;
19283             }
19284         }
19285     }
19286     dict_unref(selfdict);
19287     return ret;
19288 }
19289
19290 /*
19291  * Allocate memory for a variable type-value, and make it empty (0 or NULL
19292  * value).
19293  */
19294     static typval_T *
19295 alloc_tv()
19296 {
19297     return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
19298 }
19299
19300 /*
19301  * Allocate memory for a variable type-value, and assign a string to it.
19302  * The string "s" must have been allocated, it is consumed.
19303  * Return NULL for out of memory, the variable otherwise.
19304  */
19305     static typval_T *
19306 alloc_string_tv(s)
19307     char_u      *s;
19308 {
19309     typval_T    *rettv;
19310
19311     rettv = alloc_tv();
19312     if (rettv != NULL)
19313     {
19314         rettv->v_type = VAR_STRING;
19315         rettv->vval.v_string = s;
19316     }
19317     else
19318         vim_free(s);
19319     return rettv;
19320 }
19321
19322 /*
19323  * Free the memory for a variable type-value.
19324  */
19325     void
19326 free_tv(varp)
19327     typval_T *varp;
19328 {
19329     if (varp != NULL)
19330     {
19331         switch (varp->v_type)
19332         {
19333             case VAR_FUNC:
19334                 func_unref(varp->vval.v_string);
19335                 /*FALLTHROUGH*/
19336             case VAR_STRING:
19337                 vim_free(varp->vval.v_string);
19338                 break;
19339             case VAR_LIST:
19340                 list_unref(varp->vval.v_list);
19341                 break;
19342             case VAR_DICT:
19343                 dict_unref(varp->vval.v_dict);
19344                 break;
19345             case VAR_NUMBER:
19346 #ifdef FEAT_FLOAT
19347             case VAR_FLOAT:
19348 #endif
19349             case VAR_UNKNOWN:
19350                 break;
19351             default:
19352                 EMSG2(_(e_intern2), "free_tv()");
19353                 break;
19354         }
19355         vim_free(varp);
19356     }
19357 }
19358
19359 /*
19360  * Free the memory for a variable value and set the value to NULL or 0.
19361  */
19362     void
19363 clear_tv(varp)
19364     typval_T *varp;
19365 {
19366     if (varp != NULL)
19367     {
19368         switch (varp->v_type)
19369         {
19370             case VAR_FUNC:
19371                 func_unref(varp->vval.v_string);
19372                 /*FALLTHROUGH*/
19373             case VAR_STRING:
19374                 vim_free(varp->vval.v_string);
19375                 varp->vval.v_string = NULL;
19376                 break;
19377             case VAR_LIST:
19378                 list_unref(varp->vval.v_list);
19379                 varp->vval.v_list = NULL;
19380                 break;
19381             case VAR_DICT:
19382                 dict_unref(varp->vval.v_dict);
19383                 varp->vval.v_dict = NULL;
19384                 break;
19385             case VAR_NUMBER:
19386                 varp->vval.v_number = 0;
19387                 break;
19388 #ifdef FEAT_FLOAT
19389             case VAR_FLOAT:
19390                 varp->vval.v_float = 0.0;
19391                 break;
19392 #endif
19393             case VAR_UNKNOWN:
19394                 break;
19395             default:
19396                 EMSG2(_(e_intern2), "clear_tv()");
19397         }
19398         varp->v_lock = 0;
19399     }
19400 }
19401
19402 /*
19403  * Set the value of a variable to NULL without freeing items.
19404  */
19405     static void
19406 init_tv(varp)
19407     typval_T *varp;
19408 {
19409     if (varp != NULL)
19410         vim_memset(varp, 0, sizeof(typval_T));
19411 }
19412
19413 /*
19414  * Get the number value of a variable.
19415  * If it is a String variable, uses vim_str2nr().
19416  * For incompatible types, return 0.
19417  * get_tv_number_chk() is similar to get_tv_number(), but informs the
19418  * caller of incompatible types: it sets *denote to TRUE if "denote"
19419  * is not NULL or returns -1 otherwise.
19420  */
19421     static long
19422 get_tv_number(varp)
19423     typval_T    *varp;
19424 {
19425     int         error = FALSE;
19426
19427     return get_tv_number_chk(varp, &error);     /* return 0L on error */
19428 }
19429
19430     long
19431 get_tv_number_chk(varp, denote)
19432     typval_T    *varp;
19433     int         *denote;
19434 {
19435     long        n = 0L;
19436
19437     switch (varp->v_type)
19438     {
19439         case VAR_NUMBER:
19440             return (long)(varp->vval.v_number);
19441 #ifdef FEAT_FLOAT
19442         case VAR_FLOAT:
19443             EMSG(_("E805: Using a Float as a Number"));
19444             break;
19445 #endif
19446         case VAR_FUNC:
19447             EMSG(_("E703: Using a Funcref as a Number"));
19448             break;
19449         case VAR_STRING:
19450             if (varp->vval.v_string != NULL)
19451                 vim_str2nr(varp->vval.v_string, NULL, NULL,
19452                                                         TRUE, TRUE, &n, NULL);
19453             return n;
19454         case VAR_LIST:
19455             EMSG(_("E745: Using a List as a Number"));
19456             break;
19457         case VAR_DICT:
19458             EMSG(_("E728: Using a Dictionary as a Number"));
19459             break;
19460         default:
19461             EMSG2(_(e_intern2), "get_tv_number()");
19462             break;
19463     }
19464     if (denote == NULL)         /* useful for values that must be unsigned */
19465         n = -1;
19466     else
19467         *denote = TRUE;
19468     return n;
19469 }
19470
19471 /*
19472  * Get the lnum from the first argument.
19473  * Also accepts ".", "$", etc., but that only works for the current buffer.
19474  * Returns -1 on error.
19475  */
19476     static linenr_T
19477 get_tv_lnum(argvars)
19478     typval_T    *argvars;
19479 {
19480     typval_T    rettv;
19481     linenr_T    lnum;
19482
19483     lnum = get_tv_number_chk(&argvars[0], NULL);
19484     if (lnum == 0)  /* no valid number, try using line() */
19485     {
19486         rettv.v_type = VAR_NUMBER;
19487         f_line(argvars, &rettv);
19488         lnum = rettv.vval.v_number;
19489         clear_tv(&rettv);
19490     }
19491     return lnum;
19492 }
19493
19494 /*
19495  * Get the lnum from the first argument.
19496  * Also accepts "$", then "buf" is used.
19497  * Returns 0 on error.
19498  */
19499     static linenr_T
19500 get_tv_lnum_buf(argvars, buf)
19501     typval_T    *argvars;
19502     buf_T       *buf;
19503 {
19504     if (argvars[0].v_type == VAR_STRING
19505             && argvars[0].vval.v_string != NULL
19506             && argvars[0].vval.v_string[0] == '$'
19507             && buf != NULL)
19508         return buf->b_ml.ml_line_count;
19509     return get_tv_number_chk(&argvars[0], NULL);
19510 }
19511
19512 /*
19513  * Get the string value of a variable.
19514  * If it is a Number variable, the number is converted into a string.
19515  * get_tv_string() uses a single, static buffer.  YOU CAN ONLY USE IT ONCE!
19516  * get_tv_string_buf() uses a given buffer.
19517  * If the String variable has never been set, return an empty string.
19518  * Never returns NULL;
19519  * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
19520  * NULL on error.
19521  */
19522     static char_u *
19523 get_tv_string(varp)
19524     typval_T    *varp;
19525 {
19526     static char_u   mybuf[NUMBUFLEN];
19527
19528     return get_tv_string_buf(varp, mybuf);
19529 }
19530
19531     static char_u *
19532 get_tv_string_buf(varp, buf)
19533     typval_T    *varp;
19534     char_u      *buf;
19535 {
19536     char_u      *res =  get_tv_string_buf_chk(varp, buf);
19537
19538     return res != NULL ? res : (char_u *)"";
19539 }
19540
19541     char_u *
19542 get_tv_string_chk(varp)
19543     typval_T    *varp;
19544 {
19545     static char_u   mybuf[NUMBUFLEN];
19546
19547     return get_tv_string_buf_chk(varp, mybuf);
19548 }
19549
19550     static char_u *
19551 get_tv_string_buf_chk(varp, buf)
19552     typval_T    *varp;
19553     char_u      *buf;
19554 {
19555     switch (varp->v_type)
19556     {
19557         case VAR_NUMBER:
19558             sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
19559             return buf;
19560         case VAR_FUNC:
19561             EMSG(_("E729: using Funcref as a String"));
19562             break;
19563         case VAR_LIST:
19564             EMSG(_("E730: using List as a String"));
19565             break;
19566         case VAR_DICT:
19567             EMSG(_("E731: using Dictionary as a String"));
19568             break;
19569 #ifdef FEAT_FLOAT
19570         case VAR_FLOAT:
19571             EMSG(_("E806: using Float as a String"));
19572             break;
19573 #endif
19574         case VAR_STRING:
19575             if (varp->vval.v_string != NULL)
19576                 return varp->vval.v_string;
19577             return (char_u *)"";
19578         default:
19579             EMSG2(_(e_intern2), "get_tv_string_buf()");
19580             break;
19581     }
19582     return NULL;
19583 }
19584
19585 /*
19586  * Find variable "name" in the list of variables.
19587  * Return a pointer to it if found, NULL if not found.
19588  * Careful: "a:0" variables don't have a name.
19589  * When "htp" is not NULL we are writing to the variable, set "htp" to the
19590  * hashtab_T used.
19591  */
19592     static dictitem_T *
19593 find_var(name, htp)
19594     char_u      *name;
19595     hashtab_T   **htp;
19596 {
19597     char_u      *varname;
19598     hashtab_T   *ht;
19599
19600     ht = find_var_ht(name, &varname);
19601     if (htp != NULL)
19602         *htp = ht;
19603     if (ht == NULL)
19604         return NULL;
19605     return find_var_in_ht(ht, varname, htp != NULL);
19606 }
19607
19608 /*
19609  * Find variable "varname" in hashtab "ht".
19610  * Returns NULL if not found.
19611  */
19612     static dictitem_T *
19613 find_var_in_ht(ht, varname, writing)
19614     hashtab_T   *ht;
19615     char_u      *varname;
19616     int         writing;
19617 {
19618     hashitem_T  *hi;
19619
19620     if (*varname == NUL)
19621     {
19622         /* Must be something like "s:", otherwise "ht" would be NULL. */
19623         switch (varname[-2])
19624         {
19625             case 's': return &SCRIPT_SV(current_SID)->sv_var;
19626             case 'g': return &globvars_var;
19627             case 'v': return &vimvars_var;
19628             case 'b': return &curbuf->b_bufvar;
19629             case 'w': return &curwin->w_winvar;
19630 #ifdef FEAT_WINDOWS
19631             case 't': return &curtab->tp_winvar;
19632 #endif
19633             case 'l': return current_funccal == NULL
19634                                         ? NULL : &current_funccal->l_vars_var;
19635             case 'a': return current_funccal == NULL
19636                                        ? NULL : &current_funccal->l_avars_var;
19637         }
19638         return NULL;
19639     }
19640
19641     hi = hash_find(ht, varname);
19642     if (HASHITEM_EMPTY(hi))
19643     {
19644         /* For global variables we may try auto-loading the script.  If it
19645          * worked find the variable again.  Don't auto-load a script if it was
19646          * loaded already, otherwise it would be loaded every time when
19647          * checking if a function name is a Funcref variable. */
19648         if (ht == &globvarht && !writing)
19649         {
19650             /* Note: script_autoload() may make "hi" invalid. It must either
19651              * be obtained again or not used. */
19652             if (!script_autoload(varname, FALSE) || aborting())
19653                 return NULL;
19654             hi = hash_find(ht, varname);
19655         }
19656         if (HASHITEM_EMPTY(hi))
19657             return NULL;
19658     }
19659     return HI2DI(hi);
19660 }
19661
19662 /*
19663  * Find the hashtab used for a variable name.
19664  * Set "varname" to the start of name without ':'.
19665  */
19666     static hashtab_T *
19667 find_var_ht(name, varname)
19668     char_u  *name;
19669     char_u  **varname;
19670 {
19671     hashitem_T  *hi;
19672
19673     if (name[1] != ':')
19674     {
19675         /* The name must not start with a colon or #. */
19676         if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
19677             return NULL;
19678         *varname = name;
19679
19680         /* "version" is "v:version" in all scopes */
19681         hi = hash_find(&compat_hashtab, name);
19682         if (!HASHITEM_EMPTY(hi))
19683             return &compat_hashtab;
19684
19685         if (current_funccal == NULL)
19686             return &globvarht;                  /* global variable */
19687         return &current_funccal->l_vars.dv_hashtab; /* l: variable */
19688     }
19689     *varname = name + 2;
19690     if (*name == 'g')                           /* global variable */
19691         return &globvarht;
19692     /* There must be no ':' or '#' in the rest of the name, unless g: is used
19693      */
19694     if (vim_strchr(name + 2, ':') != NULL
19695                                || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
19696         return NULL;
19697     if (*name == 'b')                           /* buffer variable */
19698         return &curbuf->b_vars.dv_hashtab;
19699     if (*name == 'w')                           /* window variable */
19700         return &curwin->w_vars.dv_hashtab;
19701 #ifdef FEAT_WINDOWS
19702     if (*name == 't')                           /* tab page variable */
19703         return &curtab->tp_vars.dv_hashtab;
19704 #endif
19705     if (*name == 'v')                           /* v: variable */
19706         return &vimvarht;
19707     if (*name == 'a' && current_funccal != NULL) /* function argument */
19708         return &current_funccal->l_avars.dv_hashtab;
19709     if (*name == 'l' && current_funccal != NULL) /* local function variable */
19710         return &current_funccal->l_vars.dv_hashtab;
19711     if (*name == 's'                            /* script variable */
19712             && current_SID > 0 && current_SID <= ga_scripts.ga_len)
19713         return &SCRIPT_VARS(current_SID);
19714     return NULL;
19715 }
19716
19717 /*
19718  * Get the string value of a (global/local) variable.
19719  * Note: see get_tv_string() for how long the pointer remains valid.
19720  * Returns NULL when it doesn't exist.
19721  */
19722     char_u *
19723 get_var_value(name)
19724     char_u      *name;
19725 {
19726     dictitem_T  *v;
19727
19728     v = find_var(name, NULL);
19729     if (v == NULL)
19730         return NULL;
19731     return get_tv_string(&v->di_tv);
19732 }
19733
19734 /*
19735  * Allocate a new hashtab for a sourced script.  It will be used while
19736  * sourcing this script and when executing functions defined in the script.
19737  */
19738     void
19739 new_script_vars(id)
19740     scid_T id;
19741 {
19742     int         i;
19743     hashtab_T   *ht;
19744     scriptvar_T *sv;
19745
19746     if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
19747     {
19748         /* Re-allocating ga_data means that an ht_array pointing to
19749          * ht_smallarray becomes invalid.  We can recognize this: ht_mask is
19750          * at its init value.  Also reset "v_dict", it's always the same. */
19751         for (i = 1; i <= ga_scripts.ga_len; ++i)
19752         {
19753             ht = &SCRIPT_VARS(i);
19754             if (ht->ht_mask == HT_INIT_SIZE - 1)
19755                 ht->ht_array = ht->ht_smallarray;
19756             sv = SCRIPT_SV(i);
19757             sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
19758         }
19759
19760         while (ga_scripts.ga_len < id)
19761         {
19762             sv = SCRIPT_SV(ga_scripts.ga_len + 1) =
19763                 (scriptvar_T *)alloc_clear(sizeof(scriptvar_T));
19764             init_var_dict(&sv->sv_dict, &sv->sv_var);
19765             ++ga_scripts.ga_len;
19766         }
19767     }
19768 }
19769
19770 /*
19771  * Initialize dictionary "dict" as a scope and set variable "dict_var" to
19772  * point to it.
19773  */
19774     void
19775 init_var_dict(dict, dict_var)
19776     dict_T      *dict;
19777     dictitem_T  *dict_var;
19778 {
19779     hash_init(&dict->dv_hashtab);
19780     dict->dv_refcount = DO_NOT_FREE_CNT;
19781     dict->dv_copyID = 0;
19782     dict_var->di_tv.vval.v_dict = dict;
19783     dict_var->di_tv.v_type = VAR_DICT;
19784     dict_var->di_tv.v_lock = VAR_FIXED;
19785     dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
19786     dict_var->di_key[0] = NUL;
19787 }
19788
19789 /*
19790  * Clean up a list of internal variables.
19791  * Frees all allocated variables and the value they contain.
19792  * Clears hashtab "ht", does not free it.
19793  */
19794     void
19795 vars_clear(ht)
19796     hashtab_T *ht;
19797 {
19798     vars_clear_ext(ht, TRUE);
19799 }
19800
19801 /*
19802  * Like vars_clear(), but only free the value if "free_val" is TRUE.
19803  */
19804     static void
19805 vars_clear_ext(ht, free_val)
19806     hashtab_T   *ht;
19807     int         free_val;
19808 {
19809     int         todo;
19810     hashitem_T  *hi;
19811     dictitem_T  *v;
19812
19813     hash_lock(ht);
19814     todo = (int)ht->ht_used;
19815     for (hi = ht->ht_array; todo > 0; ++hi)
19816     {
19817         if (!HASHITEM_EMPTY(hi))
19818         {
19819             --todo;
19820
19821             /* Free the variable.  Don't remove it from the hashtab,
19822              * ht_array might change then.  hash_clear() takes care of it
19823              * later. */
19824             v = HI2DI(hi);
19825             if (free_val)
19826                 clear_tv(&v->di_tv);
19827             if ((v->di_flags & DI_FLAGS_FIX) == 0)
19828                 vim_free(v);
19829         }
19830     }
19831     hash_clear(ht);
19832     ht->ht_used = 0;
19833 }
19834
19835 /*
19836  * Delete a variable from hashtab "ht" at item "hi".
19837  * Clear the variable value and free the dictitem.
19838  */
19839     static void
19840 delete_var(ht, hi)
19841     hashtab_T   *ht;
19842     hashitem_T  *hi;
19843 {
19844     dictitem_T  *di = HI2DI(hi);
19845
19846     hash_remove(ht, hi);
19847     clear_tv(&di->di_tv);
19848     vim_free(di);
19849 }
19850
19851 /*
19852  * List the value of one internal variable.
19853  */
19854     static void
19855 list_one_var(v, prefix, first)
19856     dictitem_T  *v;
19857     char_u      *prefix;
19858     int         *first;
19859 {
19860     char_u      *tofree;
19861     char_u      *s;
19862     char_u      numbuf[NUMBUFLEN];
19863
19864     current_copyID += COPYID_INC;
19865     s = echo_string(&v->di_tv, &tofree, numbuf, current_copyID);
19866     list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
19867                                          s == NULL ? (char_u *)"" : s, first);
19868     vim_free(tofree);
19869 }
19870
19871     static void
19872 list_one_var_a(prefix, name, type, string, first)
19873     char_u      *prefix;
19874     char_u      *name;
19875     int         type;
19876     char_u      *string;
19877     int         *first;  /* when TRUE clear rest of screen and set to FALSE */
19878 {
19879     /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
19880     msg_start();
19881     msg_puts(prefix);
19882     if (name != NULL)   /* "a:" vars don't have a name stored */
19883         msg_puts(name);
19884     msg_putchar(' ');
19885     msg_advance(22);
19886     if (type == VAR_NUMBER)
19887         msg_putchar('#');
19888     else if (type == VAR_FUNC)
19889         msg_putchar('*');
19890     else if (type == VAR_LIST)
19891     {
19892         msg_putchar('[');
19893         if (*string == '[')
19894             ++string;
19895     }
19896     else if (type == VAR_DICT)
19897     {
19898         msg_putchar('{');
19899         if (*string == '{')
19900             ++string;
19901     }
19902     else
19903         msg_putchar(' ');
19904
19905     msg_outtrans(string);
19906
19907     if (type == VAR_FUNC)
19908         msg_puts((char_u *)"()");
19909     if (*first)
19910     {
19911         msg_clr_eos();
19912         *first = FALSE;
19913     }
19914 }
19915
19916 /*
19917  * Set variable "name" to value in "tv".
19918  * If the variable already exists, the value is updated.
19919  * Otherwise the variable is created.
19920  */
19921     static void
19922 set_var(name, tv, copy)
19923     char_u      *name;
19924     typval_T    *tv;
19925     int         copy;       /* make copy of value in "tv" */
19926 {
19927     dictitem_T  *v;
19928     char_u      *varname;
19929     hashtab_T   *ht;
19930
19931     ht = find_var_ht(name, &varname);
19932     if (ht == NULL || *varname == NUL)
19933     {
19934         EMSG2(_(e_illvar), name);
19935         return;
19936     }
19937     v = find_var_in_ht(ht, varname, TRUE);
19938
19939     if (tv->v_type == VAR_FUNC && var_check_func_name(name, v == NULL))
19940         return;
19941
19942     if (v != NULL)
19943     {
19944         /* existing variable, need to clear the value */
19945         if (var_check_ro(v->di_flags, name)
19946                                       || tv_check_lock(v->di_tv.v_lock, name))
19947             return;
19948         if (v->di_tv.v_type != tv->v_type
19949                 && !((v->di_tv.v_type == VAR_STRING
19950                         || v->di_tv.v_type == VAR_NUMBER)
19951                     && (tv->v_type == VAR_STRING
19952                         || tv->v_type == VAR_NUMBER))
19953 #ifdef FEAT_FLOAT
19954                 && !((v->di_tv.v_type == VAR_NUMBER
19955                         || v->di_tv.v_type == VAR_FLOAT)
19956                     && (tv->v_type == VAR_NUMBER
19957                         || tv->v_type == VAR_FLOAT))
19958 #endif
19959                 )
19960         {
19961             EMSG2(_("E706: Variable type mismatch for: %s"), name);
19962             return;
19963         }
19964
19965         /*
19966          * Handle setting internal v: variables separately: we don't change
19967          * the type.
19968          */
19969         if (ht == &vimvarht)
19970         {
19971             if (v->di_tv.v_type == VAR_STRING)
19972             {
19973                 vim_free(v->di_tv.vval.v_string);
19974                 if (copy || tv->v_type != VAR_STRING)
19975                     v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
19976                 else
19977                 {
19978                     /* Take over the string to avoid an extra alloc/free. */
19979                     v->di_tv.vval.v_string = tv->vval.v_string;
19980                     tv->vval.v_string = NULL;
19981                 }
19982             }
19983             else if (v->di_tv.v_type != VAR_NUMBER)
19984                 EMSG2(_(e_intern2), "set_var()");
19985             else
19986             {
19987                 v->di_tv.vval.v_number = get_tv_number(tv);
19988                 if (STRCMP(varname, "searchforward") == 0)
19989                     set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
19990             }
19991             return;
19992         }
19993
19994         clear_tv(&v->di_tv);
19995     }
19996     else                    /* add a new variable */
19997     {
19998         /* Can't add "v:" variable. */
19999         if (ht == &vimvarht)
20000         {
20001             EMSG2(_(e_illvar), name);
20002             return;
20003         }
20004
20005         /* Make sure the variable name is valid. */
20006         if (!valid_varname(varname))
20007             return;
20008
20009         v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
20010                                                           + STRLEN(varname)));
20011         if (v == NULL)
20012             return;
20013         STRCPY(v->di_key, varname);
20014         if (hash_add(ht, DI2HIKEY(v)) == FAIL)
20015         {
20016             vim_free(v);
20017             return;
20018         }
20019         v->di_flags = 0;
20020     }
20021
20022     if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
20023         copy_tv(tv, &v->di_tv);
20024     else
20025     {
20026         v->di_tv = *tv;
20027         v->di_tv.v_lock = 0;
20028         init_tv(tv);
20029     }
20030 }
20031
20032 /*
20033  * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
20034  * Also give an error message.
20035  */
20036     static int
20037 var_check_ro(flags, name)
20038     int         flags;
20039     char_u      *name;
20040 {
20041     if (flags & DI_FLAGS_RO)
20042     {
20043         EMSG2(_(e_readonlyvar), name);
20044         return TRUE;
20045     }
20046     if ((flags & DI_FLAGS_RO_SBX) && sandbox)
20047     {
20048         EMSG2(_(e_readonlysbx), name);
20049         return TRUE;
20050     }
20051     return FALSE;
20052 }
20053
20054 /*
20055  * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
20056  * Also give an error message.
20057  */
20058     static int
20059 var_check_fixed(flags, name)
20060     int         flags;
20061     char_u      *name;
20062 {
20063     if (flags & DI_FLAGS_FIX)
20064     {
20065         EMSG2(_("E795: Cannot delete variable %s"), name);
20066         return TRUE;
20067     }
20068     return FALSE;
20069 }
20070
20071 /*
20072  * Check if a funcref is assigned to a valid variable name.
20073  * Return TRUE and give an error if not.
20074  */
20075     static int
20076 var_check_func_name(name, new_var)
20077     char_u *name;    /* points to start of variable name */
20078     int    new_var;  /* TRUE when creating the variable */
20079 {
20080     if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
20081             && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
20082                                                      ? name[2] : name[0]))
20083     {
20084         EMSG2(_("E704: Funcref variable name must start with a capital: %s"),
20085                                                                         name);
20086         return TRUE;
20087     }
20088     /* Don't allow hiding a function.  When "v" is not NULL we might be
20089      * assigning another function to the same var, the type is checked
20090      * below. */
20091     if (new_var && function_exists(name))
20092     {
20093         EMSG2(_("E705: Variable name conflicts with existing function: %s"),
20094                                                                     name);
20095         return TRUE;
20096     }
20097     return FALSE;
20098 }
20099
20100 /*
20101  * Check if a variable name is valid.
20102  * Return FALSE and give an error if not.
20103  */
20104     static int
20105 valid_varname(varname)
20106     char_u *varname;
20107 {
20108     char_u *p;
20109
20110     for (p = varname; *p != NUL; ++p)
20111         if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
20112                                                    && *p != AUTOLOAD_CHAR)
20113         {
20114             EMSG2(_(e_illvar), varname);
20115             return FALSE;
20116         }
20117     return TRUE;
20118 }
20119
20120 /*
20121  * Return TRUE if typeval "tv" is set to be locked (immutable).
20122  * Also give an error message, using "name".
20123  */
20124     static int
20125 tv_check_lock(lock, name)
20126     int         lock;
20127     char_u      *name;
20128 {
20129     if (lock & VAR_LOCKED)
20130     {
20131         EMSG2(_("E741: Value is locked: %s"),
20132                                 name == NULL ? (char_u *)_("Unknown") : name);
20133         return TRUE;
20134     }
20135     if (lock & VAR_FIXED)
20136     {
20137         EMSG2(_("E742: Cannot change value of %s"),
20138                                 name == NULL ? (char_u *)_("Unknown") : name);
20139         return TRUE;
20140     }
20141     return FALSE;
20142 }
20143
20144 /*
20145  * Copy the values from typval_T "from" to typval_T "to".
20146  * When needed allocates string or increases reference count.
20147  * Does not make a copy of a list or dict but copies the reference!
20148  * It is OK for "from" and "to" to point to the same item.  This is used to
20149  * make a copy later.
20150  */
20151     void
20152 copy_tv(from, to)
20153     typval_T *from;
20154     typval_T *to;
20155 {
20156     to->v_type = from->v_type;
20157     to->v_lock = 0;
20158     switch (from->v_type)
20159     {
20160         case VAR_NUMBER:
20161             to->vval.v_number = from->vval.v_number;
20162             break;
20163 #ifdef FEAT_FLOAT
20164         case VAR_FLOAT:
20165             to->vval.v_float = from->vval.v_float;
20166             break;
20167 #endif
20168         case VAR_STRING:
20169         case VAR_FUNC:
20170             if (from->vval.v_string == NULL)
20171                 to->vval.v_string = NULL;
20172             else
20173             {
20174                 to->vval.v_string = vim_strsave(from->vval.v_string);
20175                 if (from->v_type == VAR_FUNC)
20176                     func_ref(to->vval.v_string);
20177             }
20178             break;
20179         case VAR_LIST:
20180             if (from->vval.v_list == NULL)
20181                 to->vval.v_list = NULL;
20182             else
20183             {
20184                 to->vval.v_list = from->vval.v_list;
20185                 ++to->vval.v_list->lv_refcount;
20186             }
20187             break;
20188         case VAR_DICT:
20189             if (from->vval.v_dict == NULL)
20190                 to->vval.v_dict = NULL;
20191             else
20192             {
20193                 to->vval.v_dict = from->vval.v_dict;
20194                 ++to->vval.v_dict->dv_refcount;
20195             }
20196             break;
20197         default:
20198             EMSG2(_(e_intern2), "copy_tv()");
20199             break;
20200     }
20201 }
20202
20203 /*
20204  * Make a copy of an item.
20205  * Lists and Dictionaries are also copied.  A deep copy if "deep" is set.
20206  * For deepcopy() "copyID" is zero for a full copy or the ID for when a
20207  * reference to an already copied list/dict can be used.
20208  * Returns FAIL or OK.
20209  */
20210     static int
20211 item_copy(from, to, deep, copyID)
20212     typval_T    *from;
20213     typval_T    *to;
20214     int         deep;
20215     int         copyID;
20216 {
20217     static int  recurse = 0;
20218     int         ret = OK;
20219
20220     if (recurse >= DICT_MAXNEST)
20221     {
20222         EMSG(_("E698: variable nested too deep for making a copy"));
20223         return FAIL;
20224     }
20225     ++recurse;
20226
20227     switch (from->v_type)
20228     {
20229         case VAR_NUMBER:
20230 #ifdef FEAT_FLOAT
20231         case VAR_FLOAT:
20232 #endif
20233         case VAR_STRING:
20234         case VAR_FUNC:
20235             copy_tv(from, to);
20236             break;
20237         case VAR_LIST:
20238             to->v_type = VAR_LIST;
20239             to->v_lock = 0;
20240             if (from->vval.v_list == NULL)
20241                 to->vval.v_list = NULL;
20242             else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
20243             {
20244                 /* use the copy made earlier */
20245                 to->vval.v_list = from->vval.v_list->lv_copylist;
20246                 ++to->vval.v_list->lv_refcount;
20247             }
20248             else
20249                 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
20250             if (to->vval.v_list == NULL)
20251                 ret = FAIL;
20252             break;
20253         case VAR_DICT:
20254             to->v_type = VAR_DICT;
20255             to->v_lock = 0;
20256             if (from->vval.v_dict == NULL)
20257                 to->vval.v_dict = NULL;
20258             else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
20259             {
20260                 /* use the copy made earlier */
20261                 to->vval.v_dict = from->vval.v_dict->dv_copydict;
20262                 ++to->vval.v_dict->dv_refcount;
20263             }
20264             else
20265                 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
20266             if (to->vval.v_dict == NULL)
20267                 ret = FAIL;
20268             break;
20269         default:
20270             EMSG2(_(e_intern2), "item_copy()");
20271             ret = FAIL;
20272     }
20273     --recurse;
20274     return ret;
20275 }
20276
20277 /*
20278  * ":echo expr1 ..."    print each argument separated with a space, add a
20279  *                      newline at the end.
20280  * ":echon expr1 ..."   print each argument plain.
20281  */
20282     void
20283 ex_echo(eap)
20284     exarg_T     *eap;
20285 {
20286     char_u      *arg = eap->arg;
20287     typval_T    rettv;
20288     char_u      *tofree;
20289     char_u      *p;
20290     int         needclr = TRUE;
20291     int         atstart = TRUE;
20292     char_u      numbuf[NUMBUFLEN];
20293
20294     if (eap->skip)
20295         ++emsg_skip;
20296     while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
20297     {
20298         /* If eval1() causes an error message the text from the command may
20299          * still need to be cleared. E.g., "echo 22,44". */
20300         need_clr_eos = needclr;
20301
20302         p = arg;
20303         if (eval1(&arg, &rettv, !eap->skip) == FAIL)
20304         {
20305             /*
20306              * Report the invalid expression unless the expression evaluation
20307              * has been cancelled due to an aborting error, an interrupt, or an
20308              * exception.
20309              */
20310             if (!aborting())
20311                 EMSG2(_(e_invexpr2), p);
20312             need_clr_eos = FALSE;
20313             break;
20314         }
20315         need_clr_eos = FALSE;
20316
20317         if (!eap->skip)
20318         {
20319             if (atstart)
20320             {
20321                 atstart = FALSE;
20322                 /* Call msg_start() after eval1(), evaluating the expression
20323                  * may cause a message to appear. */
20324                 if (eap->cmdidx == CMD_echo)
20325                     msg_start();
20326             }
20327             else if (eap->cmdidx == CMD_echo)
20328                 msg_puts_attr((char_u *)" ", echo_attr);
20329             current_copyID += COPYID_INC;
20330             p = echo_string(&rettv, &tofree, numbuf, current_copyID);
20331             if (p != NULL)
20332                 for ( ; *p != NUL && !got_int; ++p)
20333                 {
20334                     if (*p == '\n' || *p == '\r' || *p == TAB)
20335                     {
20336                         if (*p != TAB && needclr)
20337                         {
20338                             /* remove any text still there from the command */
20339                             msg_clr_eos();
20340                             needclr = FALSE;
20341                         }
20342                         msg_putchar_attr(*p, echo_attr);
20343                     }
20344                     else
20345                     {
20346 #ifdef FEAT_MBYTE
20347                         if (has_mbyte)
20348                         {
20349                             int i = (*mb_ptr2len)(p);
20350
20351                             (void)msg_outtrans_len_attr(p, i, echo_attr);
20352                             p += i - 1;
20353                         }
20354                         else
20355 #endif
20356                             (void)msg_outtrans_len_attr(p, 1, echo_attr);
20357                     }
20358                 }
20359             vim_free(tofree);
20360         }
20361         clear_tv(&rettv);
20362         arg = skipwhite(arg);
20363     }
20364     eap->nextcmd = check_nextcmd(arg);
20365
20366     if (eap->skip)
20367         --emsg_skip;
20368     else
20369     {
20370         /* remove text that may still be there from the command */
20371         if (needclr)
20372             msg_clr_eos();
20373         if (eap->cmdidx == CMD_echo)
20374             msg_end();
20375     }
20376 }
20377
20378 /*
20379  * ":echohl {name}".
20380  */
20381     void
20382 ex_echohl(eap)
20383     exarg_T     *eap;
20384 {
20385     int         id;
20386
20387     id = syn_name2id(eap->arg);
20388     if (id == 0)
20389         echo_attr = 0;
20390     else
20391         echo_attr = syn_id2attr(id);
20392 }
20393
20394 /*
20395  * ":execute expr1 ..." execute the result of an expression.
20396  * ":echomsg expr1 ..." Print a message
20397  * ":echoerr expr1 ..." Print an error
20398  * Each gets spaces around each argument and a newline at the end for
20399  * echo commands
20400  */
20401     void
20402 ex_execute(eap)
20403     exarg_T     *eap;
20404 {
20405     char_u      *arg = eap->arg;
20406     typval_T    rettv;
20407     int         ret = OK;
20408     char_u      *p;
20409     garray_T    ga;
20410     int         len;
20411     int         save_did_emsg;
20412
20413     ga_init2(&ga, 1, 80);
20414
20415     if (eap->skip)
20416         ++emsg_skip;
20417     while (*arg != NUL && *arg != '|' && *arg != '\n')
20418     {
20419         p = arg;
20420         if (eval1(&arg, &rettv, !eap->skip) == FAIL)
20421         {
20422             /*
20423              * Report the invalid expression unless the expression evaluation
20424              * has been cancelled due to an aborting error, an interrupt, or an
20425              * exception.
20426              */
20427             if (!aborting())
20428                 EMSG2(_(e_invexpr2), p);
20429             ret = FAIL;
20430             break;
20431         }
20432
20433         if (!eap->skip)
20434         {
20435             p = get_tv_string(&rettv);
20436             len = (int)STRLEN(p);
20437             if (ga_grow(&ga, len + 2) == FAIL)
20438             {
20439                 clear_tv(&rettv);
20440                 ret = FAIL;
20441                 break;
20442             }
20443             if (ga.ga_len)
20444                 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
20445             STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
20446             ga.ga_len += len;
20447         }
20448
20449         clear_tv(&rettv);
20450         arg = skipwhite(arg);
20451     }
20452
20453     if (ret != FAIL && ga.ga_data != NULL)
20454     {
20455         if (eap->cmdidx == CMD_echomsg)
20456         {
20457             MSG_ATTR(ga.ga_data, echo_attr);
20458             out_flush();
20459         }
20460         else if (eap->cmdidx == CMD_echoerr)
20461         {
20462             /* We don't want to abort following commands, restore did_emsg. */
20463             save_did_emsg = did_emsg;
20464             EMSG((char_u *)ga.ga_data);
20465             if (!force_abort)
20466                 did_emsg = save_did_emsg;
20467         }
20468         else if (eap->cmdidx == CMD_execute)
20469             do_cmdline((char_u *)ga.ga_data,
20470                        eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
20471     }
20472
20473     ga_clear(&ga);
20474
20475     if (eap->skip)
20476         --emsg_skip;
20477
20478     eap->nextcmd = check_nextcmd(arg);
20479 }
20480
20481 /*
20482  * Skip over the name of an option: "&option", "&g:option" or "&l:option".
20483  * "arg" points to the "&" or '+' when called, to "option" when returning.
20484  * Returns NULL when no option name found.  Otherwise pointer to the char
20485  * after the option name.
20486  */
20487     static char_u *
20488 find_option_end(arg, opt_flags)
20489     char_u      **arg;
20490     int         *opt_flags;
20491 {
20492     char_u      *p = *arg;
20493
20494     ++p;
20495     if (*p == 'g' && p[1] == ':')
20496     {
20497         *opt_flags = OPT_GLOBAL;
20498         p += 2;
20499     }
20500     else if (*p == 'l' && p[1] == ':')
20501     {
20502         *opt_flags = OPT_LOCAL;
20503         p += 2;
20504     }
20505     else
20506         *opt_flags = 0;
20507
20508     if (!ASCII_ISALPHA(*p))
20509         return NULL;
20510     *arg = p;
20511
20512     if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
20513         p += 4;     /* termcap option */
20514     else
20515         while (ASCII_ISALPHA(*p))
20516             ++p;
20517     return p;
20518 }
20519
20520 /*
20521  * ":function"
20522  */
20523     void
20524 ex_function(eap)
20525     exarg_T     *eap;
20526 {
20527     char_u      *theline;
20528     int         i;
20529     int         j;
20530     int         c;
20531     int         saved_did_emsg;
20532     char_u      *name = NULL;
20533     char_u      *p;
20534     char_u      *arg;
20535     char_u      *line_arg = NULL;
20536     garray_T    newargs;
20537     garray_T    newlines;
20538     int         varargs = FALSE;
20539     int         mustend = FALSE;
20540     int         flags = 0;
20541     ufunc_T     *fp;
20542     int         indent;
20543     int         nesting;
20544     char_u      *skip_until = NULL;
20545     dictitem_T  *v;
20546     funcdict_T  fudi;
20547     static int  func_nr = 0;        /* number for nameless function */
20548     int         paren;
20549     hashtab_T   *ht;
20550     int         todo;
20551     hashitem_T  *hi;
20552     int         sourcing_lnum_off;
20553
20554     /*
20555      * ":function" without argument: list functions.
20556      */
20557     if (ends_excmd(*eap->arg))
20558     {
20559         if (!eap->skip)
20560         {
20561             todo = (int)func_hashtab.ht_used;
20562             for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
20563             {
20564                 if (!HASHITEM_EMPTY(hi))
20565                 {
20566                     --todo;
20567                     fp = HI2UF(hi);
20568                     if (!isdigit(*fp->uf_name))
20569                         list_func_head(fp, FALSE);
20570                 }
20571             }
20572         }
20573         eap->nextcmd = check_nextcmd(eap->arg);
20574         return;
20575     }
20576
20577     /*
20578      * ":function /pat": list functions matching pattern.
20579      */
20580     if (*eap->arg == '/')
20581     {
20582         p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
20583         if (!eap->skip)
20584         {
20585             regmatch_T  regmatch;
20586
20587             c = *p;
20588             *p = NUL;
20589             regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
20590             *p = c;
20591             if (regmatch.regprog != NULL)
20592             {
20593                 regmatch.rm_ic = p_ic;
20594
20595                 todo = (int)func_hashtab.ht_used;
20596                 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
20597                 {
20598                     if (!HASHITEM_EMPTY(hi))
20599                     {
20600                         --todo;
20601                         fp = HI2UF(hi);
20602                         if (!isdigit(*fp->uf_name)
20603                                     && vim_regexec(&regmatch, fp->uf_name, 0))
20604                             list_func_head(fp, FALSE);
20605                     }
20606                 }
20607                 vim_free(regmatch.regprog);
20608             }
20609         }
20610         if (*p == '/')
20611             ++p;
20612         eap->nextcmd = check_nextcmd(p);
20613         return;
20614     }
20615
20616     /*
20617      * Get the function name.  There are these situations:
20618      * func         normal function name
20619      *              "name" == func, "fudi.fd_dict" == NULL
20620      * dict.func    new dictionary entry
20621      *              "name" == NULL, "fudi.fd_dict" set,
20622      *              "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
20623      * dict.func    existing dict entry with a Funcref
20624      *              "name" == func, "fudi.fd_dict" set,
20625      *              "fudi.fd_di" set, "fudi.fd_newkey" == NULL
20626      * dict.func    existing dict entry that's not a Funcref
20627      *              "name" == NULL, "fudi.fd_dict" set,
20628      *              "fudi.fd_di" set, "fudi.fd_newkey" == NULL
20629      */
20630     p = eap->arg;
20631     name = trans_function_name(&p, eap->skip, 0, &fudi);
20632     paren = (vim_strchr(p, '(') != NULL);
20633     if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
20634     {
20635         /*
20636          * Return on an invalid expression in braces, unless the expression
20637          * evaluation has been cancelled due to an aborting error, an
20638          * interrupt, or an exception.
20639          */
20640         if (!aborting())
20641         {
20642             if (!eap->skip && fudi.fd_newkey != NULL)
20643                 EMSG2(_(e_dictkey), fudi.fd_newkey);
20644             vim_free(fudi.fd_newkey);
20645             return;
20646         }
20647         else
20648             eap->skip = TRUE;
20649     }
20650
20651     /* An error in a function call during evaluation of an expression in magic
20652      * braces should not cause the function not to be defined. */
20653     saved_did_emsg = did_emsg;
20654     did_emsg = FALSE;
20655
20656     /*
20657      * ":function func" with only function name: list function.
20658      */
20659     if (!paren)
20660     {
20661         if (!ends_excmd(*skipwhite(p)))
20662         {
20663             EMSG(_(e_trailing));
20664             goto ret_free;
20665         }
20666         eap->nextcmd = check_nextcmd(p);
20667         if (eap->nextcmd != NULL)
20668             *p = NUL;
20669         if (!eap->skip && !got_int)
20670         {
20671             fp = find_func(name);
20672             if (fp != NULL)
20673             {
20674                 list_func_head(fp, TRUE);
20675                 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
20676                 {
20677                     if (FUNCLINE(fp, j) == NULL)
20678                         continue;
20679                     msg_putchar('\n');
20680                     msg_outnum((long)(j + 1));
20681                     if (j < 9)
20682                         msg_putchar(' ');
20683                     if (j < 99)
20684                         msg_putchar(' ');
20685                     msg_prt_line(FUNCLINE(fp, j), FALSE);
20686                     out_flush();        /* show a line at a time */
20687                     ui_breakcheck();
20688                 }
20689                 if (!got_int)
20690                 {
20691                     msg_putchar('\n');
20692                     msg_puts((char_u *)"   endfunction");
20693                 }
20694             }
20695             else
20696                 emsg_funcname(N_("E123: Undefined function: %s"), name);
20697         }
20698         goto ret_free;
20699     }
20700
20701     /*
20702      * ":function name(arg1, arg2)" Define function.
20703      */
20704     p = skipwhite(p);
20705     if (*p != '(')
20706     {
20707         if (!eap->skip)
20708         {
20709             EMSG2(_("E124: Missing '(': %s"), eap->arg);
20710             goto ret_free;
20711         }
20712         /* attempt to continue by skipping some text */
20713         if (vim_strchr(p, '(') != NULL)
20714             p = vim_strchr(p, '(');
20715     }
20716     p = skipwhite(p + 1);
20717
20718     ga_init2(&newargs, (int)sizeof(char_u *), 3);
20719     ga_init2(&newlines, (int)sizeof(char_u *), 3);
20720
20721     if (!eap->skip)
20722     {
20723         /* Check the name of the function.  Unless it's a dictionary function
20724          * (that we are overwriting). */
20725         if (name != NULL)
20726             arg = name;
20727         else
20728             arg = fudi.fd_newkey;
20729         if (arg != NULL && (fudi.fd_di == NULL
20730                                      || fudi.fd_di->di_tv.v_type != VAR_FUNC))
20731         {
20732             if (*arg == K_SPECIAL)
20733                 j = 3;
20734             else
20735                 j = 0;
20736             while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
20737                                                       : eval_isnamec(arg[j])))
20738                 ++j;
20739             if (arg[j] != NUL)
20740                 emsg_funcname((char *)e_invarg2, arg);
20741         }
20742     }
20743
20744     /*
20745      * Isolate the arguments: "arg1, arg2, ...)"
20746      */
20747     while (*p != ')')
20748     {
20749         if (p[0] == '.' && p[1] == '.' && p[2] == '.')
20750         {
20751             varargs = TRUE;
20752             p += 3;
20753             mustend = TRUE;
20754         }
20755         else
20756         {
20757             arg = p;
20758             while (ASCII_ISALNUM(*p) || *p == '_')
20759                 ++p;
20760             if (arg == p || isdigit(*arg)
20761                     || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
20762                     || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
20763             {
20764                 if (!eap->skip)
20765                     EMSG2(_("E125: Illegal argument: %s"), arg);
20766                 break;
20767             }
20768             if (ga_grow(&newargs, 1) == FAIL)
20769                 goto erret;
20770             c = *p;
20771             *p = NUL;
20772             arg = vim_strsave(arg);
20773             if (arg == NULL)
20774                 goto erret;
20775
20776             /* Check for duplicate argument name. */
20777             for (i = 0; i < newargs.ga_len; ++i)
20778                 if (STRCMP(((char_u **)(newargs.ga_data))[i], arg) == 0)
20779                 {
20780                     EMSG2(_("E853: Duplicate argument name: %s"), arg);
20781                     goto erret;
20782                 }
20783
20784             ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
20785             *p = c;
20786             newargs.ga_len++;
20787             if (*p == ',')
20788                 ++p;
20789             else
20790                 mustend = TRUE;
20791         }
20792         p = skipwhite(p);
20793         if (mustend && *p != ')')
20794         {
20795             if (!eap->skip)
20796                 EMSG2(_(e_invarg2), eap->arg);
20797             break;
20798         }
20799     }
20800     ++p;        /* skip the ')' */
20801
20802     /* find extra arguments "range", "dict" and "abort" */
20803     for (;;)
20804     {
20805         p = skipwhite(p);
20806         if (STRNCMP(p, "range", 5) == 0)
20807         {
20808             flags |= FC_RANGE;
20809             p += 5;
20810         }
20811         else if (STRNCMP(p, "dict", 4) == 0)
20812         {
20813             flags |= FC_DICT;
20814             p += 4;
20815         }
20816         else if (STRNCMP(p, "abort", 5) == 0)
20817         {
20818             flags |= FC_ABORT;
20819             p += 5;
20820         }
20821         else
20822             break;
20823     }
20824
20825     /* When there is a line break use what follows for the function body.
20826      * Makes 'exe "func Test()\n...\nendfunc"' work. */
20827     if (*p == '\n')
20828         line_arg = p + 1;
20829     else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
20830         EMSG(_(e_trailing));
20831
20832     /*
20833      * Read the body of the function, until ":endfunction" is found.
20834      */
20835     if (KeyTyped)
20836     {
20837         /* Check if the function already exists, don't let the user type the
20838          * whole function before telling him it doesn't work!  For a script we
20839          * need to skip the body to be able to find what follows. */
20840         if (!eap->skip && !eap->forceit)
20841         {
20842             if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
20843                 EMSG(_(e_funcdict));
20844             else if (name != NULL && find_func(name) != NULL)
20845                 emsg_funcname(e_funcexts, name);
20846         }
20847
20848         if (!eap->skip && did_emsg)
20849             goto erret;
20850
20851         msg_putchar('\n');          /* don't overwrite the function name */
20852         cmdline_row = msg_row;
20853     }
20854
20855     indent = 2;
20856     nesting = 0;
20857     for (;;)
20858     {
20859         if (KeyTyped)
20860             msg_scroll = TRUE;
20861         need_wait_return = FALSE;
20862         sourcing_lnum_off = sourcing_lnum;
20863
20864         if (line_arg != NULL)
20865         {
20866             /* Use eap->arg, split up in parts by line breaks. */
20867             theline = line_arg;
20868             p = vim_strchr(theline, '\n');
20869             if (p == NULL)
20870                 line_arg += STRLEN(line_arg);
20871             else
20872             {
20873                 *p = NUL;
20874                 line_arg = p + 1;
20875             }
20876         }
20877         else if (eap->getline == NULL)
20878             theline = getcmdline(':', 0L, indent);
20879         else
20880             theline = eap->getline(':', eap->cookie, indent);
20881         if (KeyTyped)
20882             lines_left = Rows - 1;
20883         if (theline == NULL)
20884         {
20885             EMSG(_("E126: Missing :endfunction"));
20886             goto erret;
20887         }
20888
20889         /* Detect line continuation: sourcing_lnum increased more than one. */
20890         if (sourcing_lnum > sourcing_lnum_off + 1)
20891             sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
20892         else
20893             sourcing_lnum_off = 0;
20894
20895         if (skip_until != NULL)
20896         {
20897             /* between ":append" and "." and between ":python <<EOF" and "EOF"
20898              * don't check for ":endfunc". */
20899             if (STRCMP(theline, skip_until) == 0)
20900             {
20901                 vim_free(skip_until);
20902                 skip_until = NULL;
20903             }
20904         }
20905         else
20906         {
20907             /* skip ':' and blanks*/
20908             for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
20909                 ;
20910
20911             /* Check for "endfunction". */
20912             if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
20913             {
20914                 if (line_arg == NULL)
20915                     vim_free(theline);
20916                 break;
20917             }
20918
20919             /* Increase indent inside "if", "while", "for" and "try", decrease
20920              * at "end". */
20921             if (indent > 2 && STRNCMP(p, "end", 3) == 0)
20922                 indent -= 2;
20923             else if (STRNCMP(p, "if", 2) == 0
20924                     || STRNCMP(p, "wh", 2) == 0
20925                     || STRNCMP(p, "for", 3) == 0
20926                     || STRNCMP(p, "try", 3) == 0)
20927                 indent += 2;
20928
20929             /* Check for defining a function inside this function. */
20930             if (checkforcmd(&p, "function", 2))
20931             {
20932                 if (*p == '!')
20933                     p = skipwhite(p + 1);
20934                 p += eval_fname_script(p);
20935                 if (ASCII_ISALPHA(*p))
20936                 {
20937                     vim_free(trans_function_name(&p, TRUE, 0, NULL));
20938                     if (*skipwhite(p) == '(')
20939                     {
20940                         ++nesting;
20941                         indent += 2;
20942                     }
20943                 }
20944             }
20945
20946             /* Check for ":append" or ":insert". */
20947             p = skip_range(p, NULL);
20948             if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
20949                     || (p[0] == 'i'
20950                         && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
20951                                 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
20952                 skip_until = vim_strsave((char_u *)".");
20953
20954             /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
20955             arg = skipwhite(skiptowhite(p));
20956             if (arg[0] == '<' && arg[1] =='<'
20957                     && ((p[0] == 'p' && p[1] == 'y'
20958                                     && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
20959                         || (p[0] == 'p' && p[1] == 'e'
20960                                     && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
20961                         || (p[0] == 't' && p[1] == 'c'
20962                                     && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
20963                         || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a'
20964                                     && !ASCII_ISALPHA(p[3]))
20965                         || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
20966                                     && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
20967                         || (p[0] == 'm' && p[1] == 'z'
20968                                     && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
20969                         ))
20970             {
20971                 /* ":python <<" continues until a dot, like ":append" */
20972                 p = skipwhite(arg + 2);
20973                 if (*p == NUL)
20974                     skip_until = vim_strsave((char_u *)".");
20975                 else
20976                     skip_until = vim_strsave(p);
20977             }
20978         }
20979
20980         /* Add the line to the function. */
20981         if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
20982         {
20983             if (line_arg == NULL)
20984                 vim_free(theline);
20985             goto erret;
20986         }
20987
20988         /* Copy the line to newly allocated memory.  get_one_sourceline()
20989          * allocates 250 bytes per line, this saves 80% on average.  The cost
20990          * is an extra alloc/free. */
20991         p = vim_strsave(theline);
20992         if (p != NULL)
20993         {
20994             if (line_arg == NULL)
20995                 vim_free(theline);
20996             theline = p;
20997         }
20998
20999         ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
21000
21001         /* Add NULL lines for continuation lines, so that the line count is
21002          * equal to the index in the growarray.   */
21003         while (sourcing_lnum_off-- > 0)
21004             ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
21005
21006         /* Check for end of eap->arg. */
21007         if (line_arg != NULL && *line_arg == NUL)
21008             line_arg = NULL;
21009     }
21010
21011     /* Don't define the function when skipping commands or when an error was
21012      * detected. */
21013     if (eap->skip || did_emsg)
21014         goto erret;
21015
21016     /*
21017      * If there are no errors, add the function
21018      */
21019     if (fudi.fd_dict == NULL)
21020     {
21021         v = find_var(name, &ht);
21022         if (v != NULL && v->di_tv.v_type == VAR_FUNC)
21023         {
21024             emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
21025                                                                         name);
21026             goto erret;
21027         }
21028
21029         fp = find_func(name);
21030         if (fp != NULL)
21031         {
21032             if (!eap->forceit)
21033             {
21034                 emsg_funcname(e_funcexts, name);
21035                 goto erret;
21036             }
21037             if (fp->uf_calls > 0)
21038             {
21039                 emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"),
21040                                                                         name);
21041                 goto erret;
21042             }
21043             /* redefine existing function */
21044             ga_clear_strings(&(fp->uf_args));
21045             ga_clear_strings(&(fp->uf_lines));
21046             vim_free(name);
21047             name = NULL;
21048         }
21049     }
21050     else
21051     {
21052         char    numbuf[20];
21053
21054         fp = NULL;
21055         if (fudi.fd_newkey == NULL && !eap->forceit)
21056         {
21057             EMSG(_(e_funcdict));
21058             goto erret;
21059         }
21060         if (fudi.fd_di == NULL)
21061         {
21062             /* Can't add a function to a locked dictionary */
21063             if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
21064                 goto erret;
21065         }
21066             /* Can't change an existing function if it is locked */
21067         else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
21068             goto erret;
21069
21070         /* Give the function a sequential number.  Can only be used with a
21071          * Funcref! */
21072         vim_free(name);
21073         sprintf(numbuf, "%d", ++func_nr);
21074         name = vim_strsave((char_u *)numbuf);
21075         if (name == NULL)
21076             goto erret;
21077     }
21078
21079     if (fp == NULL)
21080     {
21081         if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
21082         {
21083             int     slen, plen;
21084             char_u  *scriptname;
21085
21086             /* Check that the autoload name matches the script name. */
21087             j = FAIL;
21088             if (sourcing_name != NULL)
21089             {
21090                 scriptname = autoload_name(name);
21091                 if (scriptname != NULL)
21092                 {
21093                     p = vim_strchr(scriptname, '/');
21094                     plen = (int)STRLEN(p);
21095                     slen = (int)STRLEN(sourcing_name);
21096                     if (slen > plen && fnamecmp(p,
21097                                             sourcing_name + slen - plen) == 0)
21098                         j = OK;
21099                     vim_free(scriptname);
21100                 }
21101             }
21102             if (j == FAIL)
21103             {
21104                 EMSG2(_("E746: Function name does not match script file name: %s"), name);
21105                 goto erret;
21106             }
21107         }
21108
21109         fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
21110         if (fp == NULL)
21111             goto erret;
21112
21113         if (fudi.fd_dict != NULL)
21114         {
21115             if (fudi.fd_di == NULL)
21116             {
21117                 /* add new dict entry */
21118                 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
21119                 if (fudi.fd_di == NULL)
21120                 {
21121                     vim_free(fp);
21122                     goto erret;
21123                 }
21124                 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
21125                 {
21126                     vim_free(fudi.fd_di);
21127                     vim_free(fp);
21128                     goto erret;
21129                 }
21130             }
21131             else
21132                 /* overwrite existing dict entry */
21133                 clear_tv(&fudi.fd_di->di_tv);
21134             fudi.fd_di->di_tv.v_type = VAR_FUNC;
21135             fudi.fd_di->di_tv.v_lock = 0;
21136             fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
21137             fp->uf_refcount = 1;
21138
21139             /* behave like "dict" was used */
21140             flags |= FC_DICT;
21141         }
21142
21143         /* insert the new function in the function list */
21144         STRCPY(fp->uf_name, name);
21145         hash_add(&func_hashtab, UF2HIKEY(fp));
21146     }
21147     fp->uf_args = newargs;
21148     fp->uf_lines = newlines;
21149 #ifdef FEAT_PROFILE
21150     fp->uf_tml_count = NULL;
21151     fp->uf_tml_total = NULL;
21152     fp->uf_tml_self = NULL;
21153     fp->uf_profiling = FALSE;
21154     if (prof_def_func())
21155         func_do_profile(fp);
21156 #endif
21157     fp->uf_varargs = varargs;
21158     fp->uf_flags = flags;
21159     fp->uf_calls = 0;
21160     fp->uf_script_ID = current_SID;
21161     goto ret_free;
21162
21163 erret:
21164     ga_clear_strings(&newargs);
21165     ga_clear_strings(&newlines);
21166 ret_free:
21167     vim_free(skip_until);
21168     vim_free(fudi.fd_newkey);
21169     vim_free(name);
21170     did_emsg |= saved_did_emsg;
21171 }
21172
21173 /*
21174  * Get a function name, translating "<SID>" and "<SNR>".
21175  * Also handles a Funcref in a List or Dictionary.
21176  * Returns the function name in allocated memory, or NULL for failure.
21177  * flags:
21178  * TFN_INT:   internal function name OK
21179  * TFN_QUIET: be quiet
21180  * Advances "pp" to just after the function name (if no error).
21181  */
21182     static char_u *
21183 trans_function_name(pp, skip, flags, fdp)
21184     char_u      **pp;
21185     int         skip;           /* only find the end, don't evaluate */
21186     int         flags;
21187     funcdict_T  *fdp;           /* return: info about dictionary used */
21188 {
21189     char_u      *name = NULL;
21190     char_u      *start;
21191     char_u      *end;
21192     int         lead;
21193     char_u      sid_buf[20];
21194     int         len;
21195     lval_T      lv;
21196
21197     if (fdp != NULL)
21198         vim_memset(fdp, 0, sizeof(funcdict_T));
21199     start = *pp;
21200
21201     /* Check for hard coded <SNR>: already translated function ID (from a user
21202      * command). */
21203     if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
21204                                                    && (*pp)[2] == (int)KE_SNR)
21205     {
21206         *pp += 3;
21207         len = get_id_len(pp) + 3;
21208         return vim_strnsave(start, len);
21209     }
21210
21211     /* A name starting with "<SID>" or "<SNR>" is local to a script.  But
21212      * don't skip over "s:", get_lval() needs it for "s:dict.func". */
21213     lead = eval_fname_script(start);
21214     if (lead > 2)
21215         start += lead;
21216
21217     end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
21218                                               lead > 2 ? 0 : FNE_CHECK_START);
21219     if (end == start)
21220     {
21221         if (!skip)
21222             EMSG(_("E129: Function name required"));
21223         goto theend;
21224     }
21225     if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
21226     {
21227         /*
21228          * Report an invalid expression in braces, unless the expression
21229          * evaluation has been cancelled due to an aborting error, an
21230          * interrupt, or an exception.
21231          */
21232         if (!aborting())
21233         {
21234             if (end != NULL)
21235                 EMSG2(_(e_invarg2), start);
21236         }
21237         else
21238             *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
21239         goto theend;
21240     }
21241
21242     if (lv.ll_tv != NULL)
21243     {
21244         if (fdp != NULL)
21245         {
21246             fdp->fd_dict = lv.ll_dict;
21247             fdp->fd_newkey = lv.ll_newkey;
21248             lv.ll_newkey = NULL;
21249             fdp->fd_di = lv.ll_di;
21250         }
21251         if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
21252         {
21253             name = vim_strsave(lv.ll_tv->vval.v_string);
21254             *pp = end;
21255         }
21256         else
21257         {
21258             if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
21259                              || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
21260                 EMSG(_(e_funcref));
21261             else
21262                 *pp = end;
21263             name = NULL;
21264         }
21265         goto theend;
21266     }
21267
21268     if (lv.ll_name == NULL)
21269     {
21270         /* Error found, but continue after the function name. */
21271         *pp = end;
21272         goto theend;
21273     }
21274
21275     /* Check if the name is a Funcref.  If so, use the value. */
21276     if (lv.ll_exp_name != NULL)
21277     {
21278         len = (int)STRLEN(lv.ll_exp_name);
21279         name = deref_func_name(lv.ll_exp_name, &len);
21280         if (name == lv.ll_exp_name)
21281             name = NULL;
21282     }
21283     else
21284     {
21285         len = (int)(end - *pp);
21286         name = deref_func_name(*pp, &len);
21287         if (name == *pp)
21288             name = NULL;
21289     }
21290     if (name != NULL)
21291     {
21292         name = vim_strsave(name);
21293         *pp = end;
21294         goto theend;
21295     }
21296
21297     if (lv.ll_exp_name != NULL)
21298     {
21299         len = (int)STRLEN(lv.ll_exp_name);
21300         if (lead <= 2 && lv.ll_name == lv.ll_exp_name
21301                                          && STRNCMP(lv.ll_name, "s:", 2) == 0)
21302         {
21303             /* When there was "s:" already or the name expanded to get a
21304              * leading "s:" then remove it. */
21305             lv.ll_name += 2;
21306             len -= 2;
21307             lead = 2;
21308         }
21309     }
21310     else
21311     {
21312         if (lead == 2)  /* skip over "s:" */
21313             lv.ll_name += 2;
21314         len = (int)(end - lv.ll_name);
21315     }
21316
21317     /*
21318      * Copy the function name to allocated memory.
21319      * Accept <SID>name() inside a script, translate into <SNR>123_name().
21320      * Accept <SNR>123_name() outside a script.
21321      */
21322     if (skip)
21323         lead = 0;       /* do nothing */
21324     else if (lead > 0)
21325     {
21326         lead = 3;
21327         if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
21328                                                        || eval_fname_sid(*pp))
21329         {
21330             /* It's "s:" or "<SID>" */
21331             if (current_SID <= 0)
21332             {
21333                 EMSG(_(e_usingsid));
21334                 goto theend;
21335             }
21336             sprintf((char *)sid_buf, "%ld_", (long)current_SID);
21337             lead += (int)STRLEN(sid_buf);
21338         }
21339     }
21340     else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
21341     {
21342         EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
21343         goto theend;
21344     }
21345     name = alloc((unsigned)(len + lead + 1));
21346     if (name != NULL)
21347     {
21348         if (lead > 0)
21349         {
21350             name[0] = K_SPECIAL;
21351             name[1] = KS_EXTRA;
21352             name[2] = (int)KE_SNR;
21353             if (lead > 3)       /* If it's "<SID>" */
21354                 STRCPY(name + 3, sid_buf);
21355         }
21356         mch_memmove(name + lead, lv.ll_name, (size_t)len);
21357         name[len + lead] = NUL;
21358     }
21359     *pp = end;
21360
21361 theend:
21362     clear_lval(&lv);
21363     return name;
21364 }
21365
21366 /*
21367  * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
21368  * Return 2 if "p" starts with "s:".
21369  * Return 0 otherwise.
21370  */
21371     static int
21372 eval_fname_script(p)
21373     char_u      *p;
21374 {
21375     if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
21376                                           || STRNICMP(p + 1, "SNR>", 4) == 0))
21377         return 5;
21378     if (p[0] == 's' && p[1] == ':')
21379         return 2;
21380     return 0;
21381 }
21382
21383 /*
21384  * Return TRUE if "p" starts with "<SID>" or "s:".
21385  * Only works if eval_fname_script() returned non-zero for "p"!
21386  */
21387     static int
21388 eval_fname_sid(p)
21389     char_u      *p;
21390 {
21391     return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
21392 }
21393
21394 /*
21395  * List the head of the function: "name(arg1, arg2)".
21396  */
21397     static void
21398 list_func_head(fp, indent)
21399     ufunc_T     *fp;
21400     int         indent;
21401 {
21402     int         j;
21403
21404     msg_start();
21405     if (indent)
21406         MSG_PUTS("   ");
21407     MSG_PUTS("function ");
21408     if (fp->uf_name[0] == K_SPECIAL)
21409     {
21410         MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
21411         msg_puts(fp->uf_name + 3);
21412     }
21413     else
21414         msg_puts(fp->uf_name);
21415     msg_putchar('(');
21416     for (j = 0; j < fp->uf_args.ga_len; ++j)
21417     {
21418         if (j)
21419             MSG_PUTS(", ");
21420         msg_puts(FUNCARG(fp, j));
21421     }
21422     if (fp->uf_varargs)
21423     {
21424         if (j)
21425             MSG_PUTS(", ");
21426         MSG_PUTS("...");
21427     }
21428     msg_putchar(')');
21429     msg_clr_eos();
21430     if (p_verbose > 0)
21431         last_set_msg(fp->uf_script_ID);
21432 }
21433
21434 /*
21435  * Find a function by name, return pointer to it in ufuncs.
21436  * Return NULL for unknown function.
21437  */
21438     static ufunc_T *
21439 find_func(name)
21440     char_u      *name;
21441 {
21442     hashitem_T  *hi;
21443
21444     hi = hash_find(&func_hashtab, name);
21445     if (!HASHITEM_EMPTY(hi))
21446         return HI2UF(hi);
21447     return NULL;
21448 }
21449
21450 #if defined(EXITFREE) || defined(PROTO)
21451     void
21452 free_all_functions()
21453 {
21454     hashitem_T  *hi;
21455
21456     /* Need to start all over every time, because func_free() may change the
21457      * hash table. */
21458     while (func_hashtab.ht_used > 0)
21459         for (hi = func_hashtab.ht_array; ; ++hi)
21460             if (!HASHITEM_EMPTY(hi))
21461             {
21462                 func_free(HI2UF(hi));
21463                 break;
21464             }
21465 }
21466 #endif
21467
21468 /*
21469  * Return TRUE if a function "name" exists.
21470  */
21471     static int
21472 function_exists(name)
21473     char_u *name;
21474 {
21475     char_u  *nm = name;
21476     char_u  *p;
21477     int     n = FALSE;
21478
21479     p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
21480     nm = skipwhite(nm);
21481
21482     /* Only accept "funcname", "funcname ", "funcname (..." and
21483      * "funcname(...", not "funcname!...". */
21484     if (p != NULL && (*nm == NUL || *nm == '('))
21485     {
21486         if (builtin_function(p))
21487             n = (find_internal_func(p) >= 0);
21488         else
21489             n = (find_func(p) != NULL);
21490     }
21491     vim_free(p);
21492     return n;
21493 }
21494
21495 /*
21496  * Return TRUE if "name" looks like a builtin function name: starts with a
21497  * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
21498  */
21499     static int
21500 builtin_function(name)
21501     char_u *name;
21502 {
21503     return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
21504                                    && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
21505 }
21506
21507 #if defined(FEAT_PROFILE) || defined(PROTO)
21508 /*
21509  * Start profiling function "fp".
21510  */
21511     static void
21512 func_do_profile(fp)
21513     ufunc_T     *fp;
21514 {
21515     int         len = fp->uf_lines.ga_len;
21516
21517     if (len == 0)
21518         len = 1;  /* avoid getting error for allocating zero bytes */
21519     fp->uf_tm_count = 0;
21520     profile_zero(&fp->uf_tm_self);
21521     profile_zero(&fp->uf_tm_total);
21522     if (fp->uf_tml_count == NULL)
21523         fp->uf_tml_count = (int *)alloc_clear((unsigned) (sizeof(int) * len));
21524     if (fp->uf_tml_total == NULL)
21525         fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
21526                                                   (sizeof(proftime_T) * len));
21527     if (fp->uf_tml_self == NULL)
21528         fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
21529                                                   (sizeof(proftime_T) * len));
21530     fp->uf_tml_idx = -1;
21531     if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
21532                                                    || fp->uf_tml_self == NULL)
21533         return;     /* out of memory */
21534
21535     fp->uf_profiling = TRUE;
21536 }
21537
21538 /*
21539  * Dump the profiling results for all functions in file "fd".
21540  */
21541     void
21542 func_dump_profile(fd)
21543     FILE    *fd;
21544 {
21545     hashitem_T  *hi;
21546     int         todo;
21547     ufunc_T     *fp;
21548     int         i;
21549     ufunc_T     **sorttab;
21550     int         st_len = 0;
21551
21552     todo = (int)func_hashtab.ht_used;
21553     if (todo == 0)
21554         return;     /* nothing to dump */
21555
21556     sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
21557
21558     for (hi = func_hashtab.ht_array; todo > 0; ++hi)
21559     {
21560         if (!HASHITEM_EMPTY(hi))
21561         {
21562             --todo;
21563             fp = HI2UF(hi);
21564             if (fp->uf_profiling)
21565             {
21566                 if (sorttab != NULL)
21567                     sorttab[st_len++] = fp;
21568
21569                 if (fp->uf_name[0] == K_SPECIAL)
21570                     fprintf(fd, "FUNCTION  <SNR>%s()\n", fp->uf_name + 3);
21571                 else
21572                     fprintf(fd, "FUNCTION  %s()\n", fp->uf_name);
21573                 if (fp->uf_tm_count == 1)
21574                     fprintf(fd, "Called 1 time\n");
21575                 else
21576                     fprintf(fd, "Called %d times\n", fp->uf_tm_count);
21577                 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
21578                 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
21579                 fprintf(fd, "\n");
21580                 fprintf(fd, "count  total (s)   self (s)\n");
21581
21582                 for (i = 0; i < fp->uf_lines.ga_len; ++i)
21583                 {
21584                     if (FUNCLINE(fp, i) == NULL)
21585                         continue;
21586                     prof_func_line(fd, fp->uf_tml_count[i],
21587                              &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
21588                     fprintf(fd, "%s\n", FUNCLINE(fp, i));
21589                 }
21590                 fprintf(fd, "\n");
21591             }
21592         }
21593     }
21594
21595     if (sorttab != NULL && st_len > 0)
21596     {
21597         qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
21598                                                               prof_total_cmp);
21599         prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
21600         qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
21601                                                               prof_self_cmp);
21602         prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
21603     }
21604
21605     vim_free(sorttab);
21606 }
21607
21608     static void
21609 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
21610     FILE        *fd;
21611     ufunc_T     **sorttab;
21612     int         st_len;
21613     char        *title;
21614     int         prefer_self;    /* when equal print only self time */
21615 {
21616     int         i;
21617     ufunc_T     *fp;
21618
21619     fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
21620     fprintf(fd, "count  total (s)   self (s)  function\n");
21621     for (i = 0; i < 20 && i < st_len; ++i)
21622     {
21623         fp = sorttab[i];
21624         prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
21625                                                                  prefer_self);
21626         if (fp->uf_name[0] == K_SPECIAL)
21627             fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
21628         else
21629             fprintf(fd, " %s()\n", fp->uf_name);
21630     }
21631     fprintf(fd, "\n");
21632 }
21633
21634 /*
21635  * Print the count and times for one function or function line.
21636  */
21637     static void
21638 prof_func_line(fd, count, total, self, prefer_self)
21639     FILE        *fd;
21640     int         count;
21641     proftime_T  *total;
21642     proftime_T  *self;
21643     int         prefer_self;    /* when equal print only self time */
21644 {
21645     if (count > 0)
21646     {
21647         fprintf(fd, "%5d ", count);
21648         if (prefer_self && profile_equal(total, self))
21649             fprintf(fd, "           ");
21650         else
21651             fprintf(fd, "%s ", profile_msg(total));
21652         if (!prefer_self && profile_equal(total, self))
21653             fprintf(fd, "           ");
21654         else
21655             fprintf(fd, "%s ", profile_msg(self));
21656     }
21657     else
21658         fprintf(fd, "                            ");
21659 }
21660
21661 /*
21662  * Compare function for total time sorting.
21663  */
21664     static int
21665 #ifdef __BORLANDC__
21666 _RTLENTRYF
21667 #endif
21668 prof_total_cmp(s1, s2)
21669     const void  *s1;
21670     const void  *s2;
21671 {
21672     ufunc_T     *p1, *p2;
21673
21674     p1 = *(ufunc_T **)s1;
21675     p2 = *(ufunc_T **)s2;
21676     return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
21677 }
21678
21679 /*
21680  * Compare function for self time sorting.
21681  */
21682     static int
21683 #ifdef __BORLANDC__
21684 _RTLENTRYF
21685 #endif
21686 prof_self_cmp(s1, s2)
21687     const void  *s1;
21688     const void  *s2;
21689 {
21690     ufunc_T     *p1, *p2;
21691
21692     p1 = *(ufunc_T **)s1;
21693     p2 = *(ufunc_T **)s2;
21694     return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
21695 }
21696
21697 #endif
21698
21699 /*
21700  * If "name" has a package name try autoloading the script for it.
21701  * Return TRUE if a package was loaded.
21702  */
21703     static int
21704 script_autoload(name, reload)
21705     char_u      *name;
21706     int         reload;     /* load script again when already loaded */
21707 {
21708     char_u      *p;
21709     char_u      *scriptname, *tofree;
21710     int         ret = FALSE;
21711     int         i;
21712
21713     /* Return quickly when autoload disabled. */
21714     if (no_autoload)
21715         return FALSE;
21716
21717     /* If there is no '#' after name[0] there is no package name. */
21718     p = vim_strchr(name, AUTOLOAD_CHAR);
21719     if (p == NULL || p == name)
21720         return FALSE;
21721
21722     tofree = scriptname = autoload_name(name);
21723
21724     /* Find the name in the list of previously loaded package names.  Skip
21725      * "autoload/", it's always the same. */
21726     for (i = 0; i < ga_loaded.ga_len; ++i)
21727         if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
21728             break;
21729     if (!reload && i < ga_loaded.ga_len)
21730         ret = FALSE;        /* was loaded already */
21731     else
21732     {
21733         /* Remember the name if it wasn't loaded already. */
21734         if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
21735         {
21736             ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
21737             tofree = NULL;
21738         }
21739
21740         /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
21741         if (source_runtime(scriptname, FALSE) == OK)
21742             ret = TRUE;
21743     }
21744
21745     vim_free(tofree);
21746     return ret;
21747 }
21748
21749 /*
21750  * Return the autoload script name for a function or variable name.
21751  * Returns NULL when out of memory.
21752  */
21753     static char_u *
21754 autoload_name(name)
21755     char_u      *name;
21756 {
21757     char_u      *p;
21758     char_u      *scriptname;
21759
21760     /* Get the script file name: replace '#' with '/', append ".vim". */
21761     scriptname = alloc((unsigned)(STRLEN(name) + 14));
21762     if (scriptname == NULL)
21763         return FALSE;
21764     STRCPY(scriptname, "autoload/");
21765     STRCAT(scriptname, name);
21766     *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
21767     STRCAT(scriptname, ".vim");
21768     while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
21769         *p = '/';
21770     return scriptname;
21771 }
21772
21773 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
21774
21775 /*
21776  * Function given to ExpandGeneric() to obtain the list of user defined
21777  * function names.
21778  */
21779     char_u *
21780 get_user_func_name(xp, idx)
21781     expand_T    *xp;
21782     int         idx;
21783 {
21784     static long_u       done;
21785     static hashitem_T   *hi;
21786     ufunc_T             *fp;
21787
21788     if (idx == 0)
21789     {
21790         done = 0;
21791         hi = func_hashtab.ht_array;
21792     }
21793     if (done < func_hashtab.ht_used)
21794     {
21795         if (done++ > 0)
21796             ++hi;
21797         while (HASHITEM_EMPTY(hi))
21798             ++hi;
21799         fp = HI2UF(hi);
21800
21801         if (fp->uf_flags & FC_DICT)
21802             return NULL; /* don't show dict functions */
21803
21804         if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
21805             return fp->uf_name; /* prevents overflow */
21806
21807         cat_func_name(IObuff, fp);
21808         if (xp->xp_context != EXPAND_USER_FUNC)
21809         {
21810             STRCAT(IObuff, "(");
21811             if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
21812                 STRCAT(IObuff, ")");
21813         }
21814         return IObuff;
21815     }
21816     return NULL;
21817 }
21818
21819 #endif /* FEAT_CMDL_COMPL */
21820
21821 /*
21822  * Copy the function name of "fp" to buffer "buf".
21823  * "buf" must be able to hold the function name plus three bytes.
21824  * Takes care of script-local function names.
21825  */
21826     static void
21827 cat_func_name(buf, fp)
21828     char_u      *buf;
21829     ufunc_T     *fp;
21830 {
21831     if (fp->uf_name[0] == K_SPECIAL)
21832     {
21833         STRCPY(buf, "<SNR>");
21834         STRCAT(buf, fp->uf_name + 3);
21835     }
21836     else
21837         STRCPY(buf, fp->uf_name);
21838 }
21839
21840 /*
21841  * ":delfunction {name}"
21842  */
21843     void
21844 ex_delfunction(eap)
21845     exarg_T     *eap;
21846 {
21847     ufunc_T     *fp = NULL;
21848     char_u      *p;
21849     char_u      *name;
21850     funcdict_T  fudi;
21851
21852     p = eap->arg;
21853     name = trans_function_name(&p, eap->skip, 0, &fudi);
21854     vim_free(fudi.fd_newkey);
21855     if (name == NULL)
21856     {
21857         if (fudi.fd_dict != NULL && !eap->skip)
21858             EMSG(_(e_funcref));
21859         return;
21860     }
21861     if (!ends_excmd(*skipwhite(p)))
21862     {
21863         vim_free(name);
21864         EMSG(_(e_trailing));
21865         return;
21866     }
21867     eap->nextcmd = check_nextcmd(p);
21868     if (eap->nextcmd != NULL)
21869         *p = NUL;
21870
21871     if (!eap->skip)
21872         fp = find_func(name);
21873     vim_free(name);
21874
21875     if (!eap->skip)
21876     {
21877         if (fp == NULL)
21878         {
21879             EMSG2(_(e_nofunc), eap->arg);
21880             return;
21881         }
21882         if (fp->uf_calls > 0)
21883         {
21884             EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
21885             return;
21886         }
21887
21888         if (fudi.fd_dict != NULL)
21889         {
21890             /* Delete the dict item that refers to the function, it will
21891              * invoke func_unref() and possibly delete the function. */
21892             dictitem_remove(fudi.fd_dict, fudi.fd_di);
21893         }
21894         else
21895             func_free(fp);
21896     }
21897 }
21898
21899 /*
21900  * Free a function and remove it from the list of functions.
21901  */
21902     static void
21903 func_free(fp)
21904     ufunc_T *fp;
21905 {
21906     hashitem_T  *hi;
21907
21908     /* clear this function */
21909     ga_clear_strings(&(fp->uf_args));
21910     ga_clear_strings(&(fp->uf_lines));
21911 #ifdef FEAT_PROFILE
21912     vim_free(fp->uf_tml_count);
21913     vim_free(fp->uf_tml_total);
21914     vim_free(fp->uf_tml_self);
21915 #endif
21916
21917     /* remove the function from the function hashtable */
21918     hi = hash_find(&func_hashtab, UF2HIKEY(fp));
21919     if (HASHITEM_EMPTY(hi))
21920         EMSG2(_(e_intern2), "func_free()");
21921     else
21922         hash_remove(&func_hashtab, hi);
21923
21924     vim_free(fp);
21925 }
21926
21927 /*
21928  * Unreference a Function: decrement the reference count and free it when it
21929  * becomes zero.  Only for numbered functions.
21930  */
21931     static void
21932 func_unref(name)
21933     char_u      *name;
21934 {
21935     ufunc_T *fp;
21936
21937     if (name != NULL && isdigit(*name))
21938     {
21939         fp = find_func(name);
21940         if (fp == NULL)
21941             EMSG2(_(e_intern2), "func_unref()");
21942         else if (--fp->uf_refcount <= 0)
21943         {
21944             /* Only delete it when it's not being used.  Otherwise it's done
21945              * when "uf_calls" becomes zero. */
21946             if (fp->uf_calls == 0)
21947                 func_free(fp);
21948         }
21949     }
21950 }
21951
21952 /*
21953  * Count a reference to a Function.
21954  */
21955     static void
21956 func_ref(name)
21957     char_u      *name;
21958 {
21959     ufunc_T *fp;
21960
21961     if (name != NULL && isdigit(*name))
21962     {
21963         fp = find_func(name);
21964         if (fp == NULL)
21965             EMSG2(_(e_intern2), "func_ref()");
21966         else
21967             ++fp->uf_refcount;
21968     }
21969 }
21970
21971 /*
21972  * Call a user function.
21973  */
21974     static void
21975 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
21976     ufunc_T     *fp;            /* pointer to function */
21977     int         argcount;       /* nr of args */
21978     typval_T    *argvars;       /* arguments */
21979     typval_T    *rettv;         /* return value */
21980     linenr_T    firstline;      /* first line of range */
21981     linenr_T    lastline;       /* last line of range */
21982     dict_T      *selfdict;      /* Dictionary for "self" */
21983 {
21984     char_u      *save_sourcing_name;
21985     linenr_T    save_sourcing_lnum;
21986     scid_T      save_current_SID;
21987     funccall_T  *fc;
21988     int         save_did_emsg;
21989     static int  depth = 0;
21990     dictitem_T  *v;
21991     int         fixvar_idx = 0; /* index in fixvar[] */
21992     int         i;
21993     int         ai;
21994     char_u      numbuf[NUMBUFLEN];
21995     char_u      *name;
21996 #ifdef FEAT_PROFILE
21997     proftime_T  wait_start;
21998     proftime_T  call_start;
21999 #endif
22000
22001     /* If depth of calling is getting too high, don't execute the function */
22002     if (depth >= p_mfd)
22003     {
22004         EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
22005         rettv->v_type = VAR_NUMBER;
22006         rettv->vval.v_number = -1;
22007         return;
22008     }
22009     ++depth;
22010
22011     line_breakcheck();          /* check for CTRL-C hit */
22012
22013     fc = (funccall_T *)alloc(sizeof(funccall_T));
22014     fc->caller = current_funccal;
22015     current_funccal = fc;
22016     fc->func = fp;
22017     fc->rettv = rettv;
22018     rettv->vval.v_number = 0;
22019     fc->linenr = 0;
22020     fc->returned = FALSE;
22021     fc->level = ex_nesting_level;
22022     /* Check if this function has a breakpoint. */
22023     fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
22024     fc->dbg_tick = debug_tick;
22025
22026     /*
22027      * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables
22028      * with names up to VAR_SHORT_LEN long.  This avoids having to alloc/free
22029      * each argument variable and saves a lot of time.
22030      */
22031     /*
22032      * Init l: variables.
22033      */
22034     init_var_dict(&fc->l_vars, &fc->l_vars_var);
22035     if (selfdict != NULL)
22036     {
22037         /* Set l:self to "selfdict".  Use "name" to avoid a warning from
22038          * some compiler that checks the destination size. */
22039         v = &fc->fixvar[fixvar_idx++].var;
22040         name = v->di_key;
22041         STRCPY(name, "self");
22042         v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
22043         hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
22044         v->di_tv.v_type = VAR_DICT;
22045         v->di_tv.v_lock = 0;
22046         v->di_tv.vval.v_dict = selfdict;
22047         ++selfdict->dv_refcount;
22048     }
22049
22050     /*
22051      * Init a: variables.
22052      * Set a:0 to "argcount".
22053      * Set a:000 to a list with room for the "..." arguments.
22054      */
22055     init_var_dict(&fc->l_avars, &fc->l_avars_var);
22056     add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0",
22057                                 (varnumber_T)(argcount - fp->uf_args.ga_len));
22058     /* Use "name" to avoid a warning from some compiler that checks the
22059      * destination size. */
22060     v = &fc->fixvar[fixvar_idx++].var;
22061     name = v->di_key;
22062     STRCPY(name, "000");
22063     v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
22064     hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
22065     v->di_tv.v_type = VAR_LIST;
22066     v->di_tv.v_lock = VAR_FIXED;
22067     v->di_tv.vval.v_list = &fc->l_varlist;
22068     vim_memset(&fc->l_varlist, 0, sizeof(list_T));
22069     fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT;
22070     fc->l_varlist.lv_lock = VAR_FIXED;
22071
22072     /*
22073      * Set a:firstline to "firstline" and a:lastline to "lastline".
22074      * Set a:name to named arguments.
22075      * Set a:N to the "..." arguments.
22076      */
22077     add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline",
22078                                                       (varnumber_T)firstline);
22079     add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline",
22080                                                        (varnumber_T)lastline);
22081     for (i = 0; i < argcount; ++i)
22082     {
22083         ai = i - fp->uf_args.ga_len;
22084         if (ai < 0)
22085             /* named argument a:name */
22086             name = FUNCARG(fp, i);
22087         else
22088         {
22089             /* "..." argument a:1, a:2, etc. */
22090             sprintf((char *)numbuf, "%d", ai + 1);
22091             name = numbuf;
22092         }
22093         if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
22094         {
22095             v = &fc->fixvar[fixvar_idx++].var;
22096             v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
22097         }
22098         else
22099         {
22100             v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
22101                                                              + STRLEN(name)));
22102             if (v == NULL)
22103                 break;
22104             v->di_flags = DI_FLAGS_RO;
22105         }
22106         STRCPY(v->di_key, name);
22107         hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
22108
22109         /* Note: the values are copied directly to avoid alloc/free.
22110          * "argvars" must have VAR_FIXED for v_lock. */
22111         v->di_tv = argvars[i];
22112         v->di_tv.v_lock = VAR_FIXED;
22113
22114         if (ai >= 0 && ai < MAX_FUNC_ARGS)
22115         {
22116             list_append(&fc->l_varlist, &fc->l_listitems[ai]);
22117             fc->l_listitems[ai].li_tv = argvars[i];
22118             fc->l_listitems[ai].li_tv.v_lock = VAR_FIXED;
22119         }
22120     }
22121
22122     /* Don't redraw while executing the function. */
22123     ++RedrawingDisabled;
22124     save_sourcing_name = sourcing_name;
22125     save_sourcing_lnum = sourcing_lnum;
22126     sourcing_lnum = 1;
22127     sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
22128                 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
22129     if (sourcing_name != NULL)
22130     {
22131         if (save_sourcing_name != NULL
22132                           && STRNCMP(save_sourcing_name, "function ", 9) == 0)
22133             sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
22134         else
22135             STRCPY(sourcing_name, "function ");
22136         cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
22137
22138         if (p_verbose >= 12)
22139         {
22140             ++no_wait_return;
22141             verbose_enter_scroll();
22142
22143             smsg((char_u *)_("calling %s"), sourcing_name);
22144             if (p_verbose >= 14)
22145             {
22146                 char_u  buf[MSG_BUF_LEN];
22147                 char_u  numbuf2[NUMBUFLEN];
22148                 char_u  *tofree;
22149                 char_u  *s;
22150
22151                 msg_puts((char_u *)"(");
22152                 for (i = 0; i < argcount; ++i)
22153                 {
22154                     if (i > 0)
22155                         msg_puts((char_u *)", ");
22156                     if (argvars[i].v_type == VAR_NUMBER)
22157                         msg_outnum((long)argvars[i].vval.v_number);
22158                     else
22159                     {
22160                         s = tv2string(&argvars[i], &tofree, numbuf2, 0);
22161                         if (s != NULL)
22162                         {
22163                             trunc_string(s, buf, MSG_BUF_CLEN);
22164                             msg_puts(buf);
22165                             vim_free(tofree);
22166                         }
22167                     }
22168                 }
22169                 msg_puts((char_u *)")");
22170             }
22171             msg_puts((char_u *)"\n");   /* don't overwrite this either */
22172
22173             verbose_leave_scroll();
22174             --no_wait_return;
22175         }
22176     }
22177 #ifdef FEAT_PROFILE
22178     if (do_profiling == PROF_YES)
22179     {
22180         if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
22181             func_do_profile(fp);
22182         if (fp->uf_profiling
22183                     || (fc->caller != NULL && fc->caller->func->uf_profiling))
22184         {
22185             ++fp->uf_tm_count;
22186             profile_start(&call_start);
22187             profile_zero(&fp->uf_tm_children);
22188         }
22189         script_prof_save(&wait_start);
22190     }
22191 #endif
22192
22193     save_current_SID = current_SID;
22194     current_SID = fp->uf_script_ID;
22195     save_did_emsg = did_emsg;
22196     did_emsg = FALSE;
22197
22198     /* call do_cmdline() to execute the lines */
22199     do_cmdline(NULL, get_func_line, (void *)fc,
22200                                      DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
22201
22202     --RedrawingDisabled;
22203
22204     /* when the function was aborted because of an error, return -1 */
22205     if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
22206     {
22207         clear_tv(rettv);
22208         rettv->v_type = VAR_NUMBER;
22209         rettv->vval.v_number = -1;
22210     }
22211
22212 #ifdef FEAT_PROFILE
22213     if (do_profiling == PROF_YES && (fp->uf_profiling
22214                     || (fc->caller != NULL && fc->caller->func->uf_profiling)))
22215     {
22216         profile_end(&call_start);
22217         profile_sub_wait(&wait_start, &call_start);
22218         profile_add(&fp->uf_tm_total, &call_start);
22219         profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
22220         if (fc->caller != NULL && fc->caller->func->uf_profiling)
22221         {
22222             profile_add(&fc->caller->func->uf_tm_children, &call_start);
22223             profile_add(&fc->caller->func->uf_tml_children, &call_start);
22224         }
22225     }
22226 #endif
22227
22228     /* when being verbose, mention the return value */
22229     if (p_verbose >= 12)
22230     {
22231         ++no_wait_return;
22232         verbose_enter_scroll();
22233
22234         if (aborting())
22235             smsg((char_u *)_("%s aborted"), sourcing_name);
22236         else if (fc->rettv->v_type == VAR_NUMBER)
22237             smsg((char_u *)_("%s returning #%ld"), sourcing_name,
22238                                                (long)fc->rettv->vval.v_number);
22239         else
22240         {
22241             char_u      buf[MSG_BUF_LEN];
22242             char_u      numbuf2[NUMBUFLEN];
22243             char_u      *tofree;
22244             char_u      *s;
22245
22246             /* The value may be very long.  Skip the middle part, so that we
22247              * have some idea how it starts and ends. smsg() would always
22248              * truncate it at the end. */
22249             s = tv2string(fc->rettv, &tofree, numbuf2, 0);
22250             if (s != NULL)
22251             {
22252                 trunc_string(s, buf, MSG_BUF_CLEN);
22253                 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
22254                 vim_free(tofree);
22255             }
22256         }
22257         msg_puts((char_u *)"\n");   /* don't overwrite this either */
22258
22259         verbose_leave_scroll();
22260         --no_wait_return;
22261     }
22262
22263     vim_free(sourcing_name);
22264     sourcing_name = save_sourcing_name;
22265     sourcing_lnum = save_sourcing_lnum;
22266     current_SID = save_current_SID;
22267 #ifdef FEAT_PROFILE
22268     if (do_profiling == PROF_YES)
22269         script_prof_restore(&wait_start);
22270 #endif
22271
22272     if (p_verbose >= 12 && sourcing_name != NULL)
22273     {
22274         ++no_wait_return;
22275         verbose_enter_scroll();
22276
22277         smsg((char_u *)_("continuing in %s"), sourcing_name);
22278         msg_puts((char_u *)"\n");   /* don't overwrite this either */
22279
22280         verbose_leave_scroll();
22281         --no_wait_return;
22282     }
22283
22284     did_emsg |= save_did_emsg;
22285     current_funccal = fc->caller;
22286     --depth;
22287
22288     /* If the a:000 list and the l: and a: dicts are not referenced we can
22289      * free the funccall_T and what's in it. */
22290     if (fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
22291             && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
22292             && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT)
22293     {
22294         free_funccal(fc, FALSE);
22295     }
22296     else
22297     {
22298         hashitem_T      *hi;
22299         listitem_T      *li;
22300         int             todo;
22301
22302         /* "fc" is still in use.  This can happen when returning "a:000" or
22303          * assigning "l:" to a global variable.
22304          * Link "fc" in the list for garbage collection later. */
22305         fc->caller = previous_funccal;
22306         previous_funccal = fc;
22307
22308         /* Make a copy of the a: variables, since we didn't do that above. */
22309         todo = (int)fc->l_avars.dv_hashtab.ht_used;
22310         for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi)
22311         {
22312             if (!HASHITEM_EMPTY(hi))
22313             {
22314                 --todo;
22315                 v = HI2DI(hi);
22316                 copy_tv(&v->di_tv, &v->di_tv);
22317             }
22318         }
22319
22320         /* Make a copy of the a:000 items, since we didn't do that above. */
22321         for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
22322             copy_tv(&li->li_tv, &li->li_tv);
22323     }
22324 }
22325
22326 /*
22327  * Return TRUE if items in "fc" do not have "copyID".  That means they are not
22328  * referenced from anywhere that is in use.
22329  */
22330     static int
22331 can_free_funccal(fc, copyID)
22332     funccall_T  *fc;
22333     int         copyID;
22334 {
22335     return (fc->l_varlist.lv_copyID != copyID
22336             && fc->l_vars.dv_copyID != copyID
22337             && fc->l_avars.dv_copyID != copyID);
22338 }
22339
22340 /*
22341  * Free "fc" and what it contains.
22342  */
22343    static void
22344 free_funccal(fc, free_val)
22345     funccall_T  *fc;
22346     int         free_val;  /* a: vars were allocated */
22347 {
22348     listitem_T  *li;
22349
22350     /* The a: variables typevals may not have been allocated, only free the
22351      * allocated variables. */
22352     vars_clear_ext(&fc->l_avars.dv_hashtab, free_val);
22353
22354     /* free all l: variables */
22355     vars_clear(&fc->l_vars.dv_hashtab);
22356
22357     /* Free the a:000 variables if they were allocated. */
22358     if (free_val)
22359         for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
22360             clear_tv(&li->li_tv);
22361
22362     vim_free(fc);
22363 }
22364
22365 /*
22366  * Add a number variable "name" to dict "dp" with value "nr".
22367  */
22368     static void
22369 add_nr_var(dp, v, name, nr)
22370     dict_T      *dp;
22371     dictitem_T  *v;
22372     char        *name;
22373     varnumber_T nr;
22374 {
22375     STRCPY(v->di_key, name);
22376     v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
22377     hash_add(&dp->dv_hashtab, DI2HIKEY(v));
22378     v->di_tv.v_type = VAR_NUMBER;
22379     v->di_tv.v_lock = VAR_FIXED;
22380     v->di_tv.vval.v_number = nr;
22381 }
22382
22383 /*
22384  * ":return [expr]"
22385  */
22386     void
22387 ex_return(eap)
22388     exarg_T     *eap;
22389 {
22390     char_u      *arg = eap->arg;
22391     typval_T    rettv;
22392     int         returning = FALSE;
22393
22394     if (current_funccal == NULL)
22395     {
22396         EMSG(_("E133: :return not inside a function"));
22397         return;
22398     }
22399
22400     if (eap->skip)
22401         ++emsg_skip;
22402
22403     eap->nextcmd = NULL;
22404     if ((*arg != NUL && *arg != '|' && *arg != '\n')
22405             && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
22406     {
22407         if (!eap->skip)
22408             returning = do_return(eap, FALSE, TRUE, &rettv);
22409         else
22410             clear_tv(&rettv);
22411     }
22412     /* It's safer to return also on error. */
22413     else if (!eap->skip)
22414     {
22415         /*
22416          * Return unless the expression evaluation has been cancelled due to an
22417          * aborting error, an interrupt, or an exception.
22418          */
22419         if (!aborting())
22420             returning = do_return(eap, FALSE, TRUE, NULL);
22421     }
22422
22423     /* When skipping or the return gets pending, advance to the next command
22424      * in this line (!returning).  Otherwise, ignore the rest of the line.
22425      * Following lines will be ignored by get_func_line(). */
22426     if (returning)
22427         eap->nextcmd = NULL;
22428     else if (eap->nextcmd == NULL)          /* no argument */
22429         eap->nextcmd = check_nextcmd(arg);
22430
22431     if (eap->skip)
22432         --emsg_skip;
22433 }
22434
22435 /*
22436  * Return from a function.  Possibly makes the return pending.  Also called
22437  * for a pending return at the ":endtry" or after returning from an extra
22438  * do_cmdline().  "reanimate" is used in the latter case.  "is_cmd" is set
22439  * when called due to a ":return" command.  "rettv" may point to a typval_T
22440  * with the return rettv.  Returns TRUE when the return can be carried out,
22441  * FALSE when the return gets pending.
22442  */
22443     int
22444 do_return(eap, reanimate, is_cmd, rettv)
22445     exarg_T     *eap;
22446     int         reanimate;
22447     int         is_cmd;
22448     void        *rettv;
22449 {
22450     int         idx;
22451     struct condstack *cstack = eap->cstack;
22452
22453     if (reanimate)
22454         /* Undo the return. */
22455         current_funccal->returned = FALSE;
22456
22457     /*
22458      * Cleanup (and inactivate) conditionals, but stop when a try conditional
22459      * not in its finally clause (which then is to be executed next) is found.
22460      * In this case, make the ":return" pending for execution at the ":endtry".
22461      * Otherwise, return normally.
22462      */
22463     idx = cleanup_conditionals(eap->cstack, 0, TRUE);
22464     if (idx >= 0)
22465     {
22466         cstack->cs_pending[idx] = CSTP_RETURN;
22467
22468         if (!is_cmd && !reanimate)
22469             /* A pending return again gets pending.  "rettv" points to an
22470              * allocated variable with the rettv of the original ":return"'s
22471              * argument if present or is NULL else. */
22472             cstack->cs_rettv[idx] = rettv;
22473         else
22474         {
22475             /* When undoing a return in order to make it pending, get the stored
22476              * return rettv. */
22477             if (reanimate)
22478                 rettv = current_funccal->rettv;
22479
22480             if (rettv != NULL)
22481             {
22482                 /* Store the value of the pending return. */
22483                 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
22484                     *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
22485                 else
22486                     EMSG(_(e_outofmem));
22487             }
22488             else
22489                 cstack->cs_rettv[idx] = NULL;
22490
22491             if (reanimate)
22492             {
22493                 /* The pending return value could be overwritten by a ":return"
22494                  * without argument in a finally clause; reset the default
22495                  * return value. */
22496                 current_funccal->rettv->v_type = VAR_NUMBER;
22497                 current_funccal->rettv->vval.v_number = 0;
22498             }
22499         }
22500         report_make_pending(CSTP_RETURN, rettv);
22501     }
22502     else
22503     {
22504         current_funccal->returned = TRUE;
22505
22506         /* If the return is carried out now, store the return value.  For
22507          * a return immediately after reanimation, the value is already
22508          * there. */
22509         if (!reanimate && rettv != NULL)
22510         {
22511             clear_tv(current_funccal->rettv);
22512             *current_funccal->rettv = *(typval_T *)rettv;
22513             if (!is_cmd)
22514                 vim_free(rettv);
22515         }
22516     }
22517
22518     return idx < 0;
22519 }
22520
22521 /*
22522  * Free the variable with a pending return value.
22523  */
22524     void
22525 discard_pending_return(rettv)
22526     void        *rettv;
22527 {
22528     free_tv((typval_T *)rettv);
22529 }
22530
22531 /*
22532  * Generate a return command for producing the value of "rettv".  The result
22533  * is an allocated string.  Used by report_pending() for verbose messages.
22534  */
22535     char_u *
22536 get_return_cmd(rettv)
22537     void        *rettv;
22538 {
22539     char_u      *s = NULL;
22540     char_u      *tofree = NULL;
22541     char_u      numbuf[NUMBUFLEN];
22542
22543     if (rettv != NULL)
22544         s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
22545     if (s == NULL)
22546         s = (char_u *)"";
22547
22548     STRCPY(IObuff, ":return ");
22549     STRNCPY(IObuff + 8, s, IOSIZE - 8);
22550     if (STRLEN(s) + 8 >= IOSIZE)
22551         STRCPY(IObuff + IOSIZE - 4, "...");
22552     vim_free(tofree);
22553     return vim_strsave(IObuff);
22554 }
22555
22556 /*
22557  * Get next function line.
22558  * Called by do_cmdline() to get the next line.
22559  * Returns allocated string, or NULL for end of function.
22560  */
22561     char_u *
22562 get_func_line(c, cookie, indent)
22563     int     c UNUSED;
22564     void    *cookie;
22565     int     indent UNUSED;
22566 {
22567     funccall_T  *fcp = (funccall_T *)cookie;
22568     ufunc_T     *fp = fcp->func;
22569     char_u      *retval;
22570     garray_T    *gap;  /* growarray with function lines */
22571
22572     /* If breakpoints have been added/deleted need to check for it. */
22573     if (fcp->dbg_tick != debug_tick)
22574     {
22575         fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
22576                                                                sourcing_lnum);
22577         fcp->dbg_tick = debug_tick;
22578     }
22579 #ifdef FEAT_PROFILE
22580     if (do_profiling == PROF_YES)
22581         func_line_end(cookie);
22582 #endif
22583
22584     gap = &fp->uf_lines;
22585     if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
22586             || fcp->returned)
22587         retval = NULL;
22588     else
22589     {
22590         /* Skip NULL lines (continuation lines). */
22591         while (fcp->linenr < gap->ga_len
22592                           && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
22593             ++fcp->linenr;
22594         if (fcp->linenr >= gap->ga_len)
22595             retval = NULL;
22596         else
22597         {
22598             retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
22599             sourcing_lnum = fcp->linenr;
22600 #ifdef FEAT_PROFILE
22601             if (do_profiling == PROF_YES)
22602                 func_line_start(cookie);
22603 #endif
22604         }
22605     }
22606
22607     /* Did we encounter a breakpoint? */
22608     if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
22609     {
22610         dbg_breakpoint(fp->uf_name, sourcing_lnum);
22611         /* Find next breakpoint. */
22612         fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
22613                                                                sourcing_lnum);
22614         fcp->dbg_tick = debug_tick;
22615     }
22616
22617     return retval;
22618 }
22619
22620 #if defined(FEAT_PROFILE) || defined(PROTO)
22621 /*
22622  * Called when starting to read a function line.
22623  * "sourcing_lnum" must be correct!
22624  * When skipping lines it may not actually be executed, but we won't find out
22625  * until later and we need to store the time now.
22626  */
22627     void
22628 func_line_start(cookie)
22629     void    *cookie;
22630 {
22631     funccall_T  *fcp = (funccall_T *)cookie;
22632     ufunc_T     *fp = fcp->func;
22633
22634     if (fp->uf_profiling && sourcing_lnum >= 1
22635                                       && sourcing_lnum <= fp->uf_lines.ga_len)
22636     {
22637         fp->uf_tml_idx = sourcing_lnum - 1;
22638         /* Skip continuation lines. */
22639         while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
22640             --fp->uf_tml_idx;
22641         fp->uf_tml_execed = FALSE;
22642         profile_start(&fp->uf_tml_start);
22643         profile_zero(&fp->uf_tml_children);
22644         profile_get_wait(&fp->uf_tml_wait);
22645     }
22646 }
22647
22648 /*
22649  * Called when actually executing a function line.
22650  */
22651     void
22652 func_line_exec(cookie)
22653     void    *cookie;
22654 {
22655     funccall_T  *fcp = (funccall_T *)cookie;
22656     ufunc_T     *fp = fcp->func;
22657
22658     if (fp->uf_profiling && fp->uf_tml_idx >= 0)
22659         fp->uf_tml_execed = TRUE;
22660 }
22661
22662 /*
22663  * Called when done with a function line.
22664  */
22665     void
22666 func_line_end(cookie)
22667     void    *cookie;
22668 {
22669     funccall_T  *fcp = (funccall_T *)cookie;
22670     ufunc_T     *fp = fcp->func;
22671
22672     if (fp->uf_profiling && fp->uf_tml_idx >= 0)
22673     {
22674         if (fp->uf_tml_execed)
22675         {
22676             ++fp->uf_tml_count[fp->uf_tml_idx];
22677             profile_end(&fp->uf_tml_start);
22678             profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
22679             profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
22680             profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
22681                                                         &fp->uf_tml_children);
22682         }
22683         fp->uf_tml_idx = -1;
22684     }
22685 }
22686 #endif
22687
22688 /*
22689  * Return TRUE if the currently active function should be ended, because a
22690  * return was encountered or an error occurred.  Used inside a ":while".
22691  */
22692     int
22693 func_has_ended(cookie)
22694     void    *cookie;
22695 {
22696     funccall_T  *fcp = (funccall_T *)cookie;
22697
22698     /* Ignore the "abort" flag if the abortion behavior has been changed due to
22699      * an error inside a try conditional. */
22700     return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
22701             || fcp->returned);
22702 }
22703
22704 /*
22705  * return TRUE if cookie indicates a function which "abort"s on errors.
22706  */
22707     int
22708 func_has_abort(cookie)
22709     void    *cookie;
22710 {
22711     return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
22712 }
22713
22714 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
22715 typedef enum
22716 {
22717     VAR_FLAVOUR_DEFAULT,        /* doesn't start with uppercase */
22718     VAR_FLAVOUR_SESSION,        /* starts with uppercase, some lower */
22719     VAR_FLAVOUR_VIMINFO         /* all uppercase */
22720 } var_flavour_T;
22721
22722 static var_flavour_T var_flavour __ARGS((char_u *varname));
22723
22724     static var_flavour_T
22725 var_flavour(varname)
22726     char_u *varname;
22727 {
22728     char_u *p = varname;
22729
22730     if (ASCII_ISUPPER(*p))
22731     {
22732         while (*(++p))
22733             if (ASCII_ISLOWER(*p))
22734                 return VAR_FLAVOUR_SESSION;
22735         return VAR_FLAVOUR_VIMINFO;
22736     }
22737     else
22738         return VAR_FLAVOUR_DEFAULT;
22739 }
22740 #endif
22741
22742 #if defined(FEAT_VIMINFO) || defined(PROTO)
22743 /*
22744  * Restore global vars that start with a capital from the viminfo file
22745  */
22746     int
22747 read_viminfo_varlist(virp, writing)
22748     vir_T       *virp;
22749     int         writing;
22750 {
22751     char_u      *tab;
22752     int         type = VAR_NUMBER;
22753     typval_T    tv;
22754
22755     if (!writing && (find_viminfo_parameter('!') != NULL))
22756     {
22757         tab = vim_strchr(virp->vir_line + 1, '\t');
22758         if (tab != NULL)
22759         {
22760             *tab++ = '\0';      /* isolate the variable name */
22761             switch (*tab)
22762             {
22763                 case 'S': type = VAR_STRING; break;
22764 #ifdef FEAT_FLOAT
22765                 case 'F': type = VAR_FLOAT; break;
22766 #endif
22767                 case 'D': type = VAR_DICT; break;
22768                 case 'L': type = VAR_LIST; break;
22769             }
22770
22771             tab = vim_strchr(tab, '\t');
22772             if (tab != NULL)
22773             {
22774                 tv.v_type = type;
22775                 if (type == VAR_STRING || type == VAR_DICT || type == VAR_LIST)
22776                     tv.vval.v_string = viminfo_readstring(virp,
22777                                        (int)(tab - virp->vir_line + 1), TRUE);
22778 #ifdef FEAT_FLOAT
22779                 else if (type == VAR_FLOAT)
22780                     (void)string2float(tab + 1, &tv.vval.v_float);
22781 #endif
22782                 else
22783                     tv.vval.v_number = atol((char *)tab + 1);
22784                 if (type == VAR_DICT || type == VAR_LIST)
22785                 {
22786                     typval_T *etv = eval_expr(tv.vval.v_string, NULL);
22787
22788                     if (etv == NULL)
22789                         /* Failed to parse back the dict or list, use it as a
22790                          * string. */
22791                         tv.v_type = VAR_STRING;
22792                     else
22793                     {
22794                         vim_free(tv.vval.v_string);
22795                         tv = *etv;
22796                     }
22797                 }
22798
22799                 set_var(virp->vir_line + 1, &tv, FALSE);
22800
22801                 if (tv.v_type == VAR_STRING)
22802                     vim_free(tv.vval.v_string);
22803                 else if (tv.v_type == VAR_DICT || tv.v_type == VAR_LIST)
22804                     clear_tv(&tv);
22805             }
22806         }
22807     }
22808
22809     return viminfo_readline(virp);
22810 }
22811
22812 /*
22813  * Write global vars that start with a capital to the viminfo file
22814  */
22815     void
22816 write_viminfo_varlist(fp)
22817     FILE    *fp;
22818 {
22819     hashitem_T  *hi;
22820     dictitem_T  *this_var;
22821     int         todo;
22822     char        *s;
22823     char_u      *p;
22824     char_u      *tofree;
22825     char_u      numbuf[NUMBUFLEN];
22826
22827     if (find_viminfo_parameter('!') == NULL)
22828         return;
22829
22830     fputs(_("\n# global variables:\n"), fp);
22831
22832     todo = (int)globvarht.ht_used;
22833     for (hi = globvarht.ht_array; todo > 0; ++hi)
22834     {
22835         if (!HASHITEM_EMPTY(hi))
22836         {
22837             --todo;
22838             this_var = HI2DI(hi);
22839             if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
22840             {
22841                 switch (this_var->di_tv.v_type)
22842                 {
22843                     case VAR_STRING: s = "STR"; break;
22844                     case VAR_NUMBER: s = "NUM"; break;
22845 #ifdef FEAT_FLOAT
22846                     case VAR_FLOAT:  s = "FLO"; break;
22847 #endif
22848                     case VAR_DICT:   s = "DIC"; break;
22849                     case VAR_LIST:   s = "LIS"; break;
22850                     default: continue;
22851                 }
22852                 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
22853                 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
22854                 if (p != NULL)
22855                     viminfo_writestring(fp, p);
22856                 vim_free(tofree);
22857             }
22858         }
22859     }
22860 }
22861 #endif
22862
22863 #if defined(FEAT_SESSION) || defined(PROTO)
22864     int
22865 store_session_globals(fd)
22866     FILE        *fd;
22867 {
22868     hashitem_T  *hi;
22869     dictitem_T  *this_var;
22870     int         todo;
22871     char_u      *p, *t;
22872
22873     todo = (int)globvarht.ht_used;
22874     for (hi = globvarht.ht_array; todo > 0; ++hi)
22875     {
22876         if (!HASHITEM_EMPTY(hi))
22877         {
22878             --todo;
22879             this_var = HI2DI(hi);
22880             if ((this_var->di_tv.v_type == VAR_NUMBER
22881                         || this_var->di_tv.v_type == VAR_STRING)
22882                     && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22883             {
22884                 /* Escape special characters with a backslash.  Turn a LF and
22885                  * CR into \n and \r. */
22886                 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
22887                                                         (char_u *)"\\\"\n\r");
22888                 if (p == NULL)      /* out of memory */
22889                     break;
22890                 for (t = p; *t != NUL; ++t)
22891                     if (*t == '\n')
22892                         *t = 'n';
22893                     else if (*t == '\r')
22894                         *t = 'r';
22895                 if ((fprintf(fd, "let %s = %c%s%c",
22896                                 this_var->di_key,
22897                                 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22898                                                                         : ' ',
22899                                 p,
22900                                 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22901                                                                    : ' ') < 0)
22902                         || put_eol(fd) == FAIL)
22903                 {
22904                     vim_free(p);
22905                     return FAIL;
22906                 }
22907                 vim_free(p);
22908             }
22909 #ifdef FEAT_FLOAT
22910             else if (this_var->di_tv.v_type == VAR_FLOAT
22911                     && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22912             {
22913                 float_T f = this_var->di_tv.vval.v_float;
22914                 int sign = ' ';
22915
22916                 if (f < 0)
22917                 {
22918                     f = -f;
22919                     sign = '-';
22920                 }
22921                 if ((fprintf(fd, "let %s = %c&%f",
22922                                                this_var->di_key, sign, f) < 0)
22923                         || put_eol(fd) == FAIL)
22924                     return FAIL;
22925             }
22926 #endif
22927         }
22928     }
22929     return OK;
22930 }
22931 #endif
22932
22933 /*
22934  * Display script name where an item was last set.
22935  * Should only be invoked when 'verbose' is non-zero.
22936  */
22937     void
22938 last_set_msg(scriptID)
22939     scid_T scriptID;
22940 {
22941     char_u *p;
22942
22943     if (scriptID != 0)
22944     {
22945         p = home_replace_save(NULL, get_scriptname(scriptID));
22946         if (p != NULL)
22947         {
22948             verbose_enter();
22949             MSG_PUTS(_("\n\tLast set from "));
22950             MSG_PUTS(p);
22951             vim_free(p);
22952             verbose_leave();
22953         }
22954     }
22955 }
22956
22957 /*
22958  * List v:oldfiles in a nice way.
22959  */
22960     void
22961 ex_oldfiles(eap)
22962     exarg_T     *eap UNUSED;
22963 {
22964     list_T      *l = vimvars[VV_OLDFILES].vv_list;
22965     listitem_T  *li;
22966     int         nr = 0;
22967
22968     if (l == NULL)
22969         msg((char_u *)_("No old files"));
22970     else
22971     {
22972         msg_start();
22973         msg_scroll = TRUE;
22974         for (li = l->lv_first; li != NULL && !got_int; li = li->li_next)
22975         {
22976             msg_outnum((long)++nr);
22977             MSG_PUTS(": ");
22978             msg_outtrans(get_tv_string(&li->li_tv));
22979             msg_putchar('\n');
22980             out_flush();            /* output one line at a time */
22981             ui_breakcheck();
22982         }
22983         /* Assume "got_int" was set to truncate the listing. */
22984         got_int = FALSE;
22985
22986 #ifdef FEAT_BROWSE_CMD
22987         if (cmdmod.browse)
22988         {
22989             quit_more = FALSE;
22990             nr = prompt_for_number(FALSE);
22991             msg_starthere();
22992             if (nr > 0)
22993             {
22994                 char_u *p = list_find_str(get_vim_var_list(VV_OLDFILES),
22995                                                                     (long)nr);
22996
22997                 if (p != NULL)
22998                 {
22999                     p = expand_env_save(p);
23000                     eap->arg = p;
23001                     eap->cmdidx = CMD_edit;
23002                     cmdmod.browse = FALSE;
23003                     do_exedit(eap, NULL);
23004                     vim_free(p);
23005                 }
23006             }
23007         }
23008 #endif
23009     }
23010 }
23011
23012 #endif /* FEAT_EVAL */
23013
23014
23015 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
23016
23017 #ifdef WIN3264
23018 /*
23019  * Functions for ":8" filename modifier: get 8.3 version of a filename.
23020  */
23021 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
23022 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
23023 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
23024
23025 /*
23026  * Get the short path (8.3) for the filename in "fnamep".
23027  * Only works for a valid file name.
23028  * When the path gets longer "fnamep" is changed and the allocated buffer
23029  * is put in "bufp".
23030  * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
23031  * Returns OK on success, FAIL on failure.
23032  */
23033     static int
23034 get_short_pathname(fnamep, bufp, fnamelen)
23035     char_u      **fnamep;
23036     char_u      **bufp;
23037     int         *fnamelen;
23038 {
23039     int         l, len;
23040     char_u      *newbuf;
23041
23042     len = *fnamelen;
23043     l = GetShortPathName(*fnamep, *fnamep, len);
23044     if (l > len - 1)
23045     {
23046         /* If that doesn't work (not enough space), then save the string
23047          * and try again with a new buffer big enough. */
23048         newbuf = vim_strnsave(*fnamep, l);
23049         if (newbuf == NULL)
23050             return FAIL;
23051
23052         vim_free(*bufp);
23053         *fnamep = *bufp = newbuf;
23054
23055         /* Really should always succeed, as the buffer is big enough. */
23056         l = GetShortPathName(*fnamep, *fnamep, l+1);
23057     }
23058
23059     *fnamelen = l;
23060     return OK;
23061 }
23062
23063 /*
23064  * Get the short path (8.3) for the filename in "fname". The converted
23065  * path is returned in "bufp".
23066  *
23067  * Some of the directories specified in "fname" may not exist. This function
23068  * will shorten the existing directories at the beginning of the path and then
23069  * append the remaining non-existing path.
23070  *
23071  * fname - Pointer to the filename to shorten.  On return, contains the
23072  *         pointer to the shortened pathname
23073  * bufp -  Pointer to an allocated buffer for the filename.
23074  * fnamelen - Length of the filename pointed to by fname
23075  *
23076  * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
23077  */
23078     static int
23079 shortpath_for_invalid_fname(fname, bufp, fnamelen)
23080     char_u      **fname;
23081     char_u      **bufp;
23082     int         *fnamelen;
23083 {
23084     char_u      *short_fname, *save_fname, *pbuf_unused;
23085     char_u      *endp, *save_endp;
23086     char_u      ch;
23087     int         old_len, len;
23088     int         new_len, sfx_len;
23089     int         retval = OK;
23090
23091     /* Make a copy */
23092     old_len = *fnamelen;
23093     save_fname = vim_strnsave(*fname, old_len);
23094     pbuf_unused = NULL;
23095     short_fname = NULL;
23096
23097     endp = save_fname + old_len - 1; /* Find the end of the copy */
23098     save_endp = endp;
23099
23100     /*
23101      * Try shortening the supplied path till it succeeds by removing one
23102      * directory at a time from the tail of the path.
23103      */
23104     len = 0;
23105     for (;;)
23106     {
23107         /* go back one path-separator */
23108         while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
23109             --endp;
23110         if (endp <= save_fname)
23111             break;              /* processed the complete path */
23112
23113         /*
23114          * Replace the path separator with a NUL and try to shorten the
23115          * resulting path.
23116          */
23117         ch = *endp;
23118         *endp = 0;
23119         short_fname = save_fname;
23120         len = (int)STRLEN(short_fname) + 1;
23121         if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
23122         {
23123             retval = FAIL;
23124             goto theend;
23125         }
23126         *endp = ch;     /* preserve the string */
23127
23128         if (len > 0)
23129             break;      /* successfully shortened the path */
23130
23131         /* failed to shorten the path. Skip the path separator */
23132         --endp;
23133     }
23134
23135     if (len > 0)
23136     {
23137         /*
23138          * Succeeded in shortening the path. Now concatenate the shortened
23139          * path with the remaining path at the tail.
23140          */
23141
23142         /* Compute the length of the new path. */
23143         sfx_len = (int)(save_endp - endp) + 1;
23144         new_len = len + sfx_len;
23145
23146         *fnamelen = new_len;
23147         vim_free(*bufp);
23148         if (new_len > old_len)
23149         {
23150             /* There is not enough space in the currently allocated string,
23151              * copy it to a buffer big enough. */
23152             *fname = *bufp = vim_strnsave(short_fname, new_len);
23153             if (*fname == NULL)
23154             {
23155                 retval = FAIL;
23156                 goto theend;
23157             }
23158         }
23159         else
23160         {
23161             /* Transfer short_fname to the main buffer (it's big enough),
23162              * unless get_short_pathname() did its work in-place. */
23163             *fname = *bufp = save_fname;
23164             if (short_fname != save_fname)
23165                 vim_strncpy(save_fname, short_fname, len);
23166             save_fname = NULL;
23167         }
23168
23169         /* concat the not-shortened part of the path */
23170         vim_strncpy(*fname + len, endp, sfx_len);
23171         (*fname)[new_len] = NUL;
23172     }
23173
23174 theend:
23175     vim_free(pbuf_unused);
23176     vim_free(save_fname);
23177
23178     return retval;
23179 }
23180
23181 /*
23182  * Get a pathname for a partial path.
23183  * Returns OK for success, FAIL for failure.
23184  */
23185     static int
23186 shortpath_for_partial(fnamep, bufp, fnamelen)
23187     char_u      **fnamep;
23188     char_u      **bufp;
23189     int         *fnamelen;
23190 {
23191     int         sepcount, len, tflen;
23192     char_u      *p;
23193     char_u      *pbuf, *tfname;
23194     int         hasTilde;
23195
23196     /* Count up the path separators from the RHS.. so we know which part
23197      * of the path to return. */
23198     sepcount = 0;
23199     for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
23200         if (vim_ispathsep(*p))
23201             ++sepcount;
23202
23203     /* Need full path first (use expand_env() to remove a "~/") */
23204     hasTilde = (**fnamep == '~');
23205     if (hasTilde)
23206         pbuf = tfname = expand_env_save(*fnamep);
23207     else
23208         pbuf = tfname = FullName_save(*fnamep, FALSE);
23209
23210     len = tflen = (int)STRLEN(tfname);
23211
23212     if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
23213         return FAIL;
23214
23215     if (len == 0)
23216     {
23217         /* Don't have a valid filename, so shorten the rest of the
23218          * path if we can. This CAN give us invalid 8.3 filenames, but
23219          * there's not a lot of point in guessing what it might be.
23220          */
23221         len = tflen;
23222         if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
23223             return FAIL;
23224     }
23225
23226     /* Count the paths backward to find the beginning of the desired string. */
23227     for (p = tfname + len - 1; p >= tfname; --p)
23228     {
23229 #ifdef FEAT_MBYTE
23230         if (has_mbyte)
23231             p -= mb_head_off(tfname, p);
23232 #endif
23233         if (vim_ispathsep(*p))
23234         {
23235             if (sepcount == 0 || (hasTilde && sepcount == 1))
23236                 break;
23237             else
23238                 sepcount --;
23239         }
23240     }
23241     if (hasTilde)
23242     {
23243         --p;
23244         if (p >= tfname)
23245             *p = '~';
23246         else
23247             return FAIL;
23248     }
23249     else
23250         ++p;
23251
23252     /* Copy in the string - p indexes into tfname - allocated at pbuf */
23253     vim_free(*bufp);
23254     *fnamelen = (int)STRLEN(p);
23255     *bufp = pbuf;
23256     *fnamep = p;
23257
23258     return OK;
23259 }
23260 #endif /* WIN3264 */
23261
23262 /*
23263  * Adjust a filename, according to a string of modifiers.
23264  * *fnamep must be NUL terminated when called.  When returning, the length is
23265  * determined by *fnamelen.
23266  * Returns VALID_ flags or -1 for failure.
23267  * When there is an error, *fnamep is set to NULL.
23268  */
23269     int
23270 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
23271     char_u      *src;           /* string with modifiers */
23272     int         *usedlen;       /* characters after src that are used */
23273     char_u      **fnamep;       /* file name so far */
23274     char_u      **bufp;         /* buffer for allocated file name or NULL */
23275     int         *fnamelen;      /* length of fnamep */
23276 {
23277     int         valid = 0;
23278     char_u      *tail;
23279     char_u      *s, *p, *pbuf;
23280     char_u      dirname[MAXPATHL];
23281     int         c;
23282     int         has_fullname = 0;
23283 #ifdef WIN3264
23284     char_u      *fname_start = *fnamep;
23285     int         has_shortname = 0;
23286 #endif
23287
23288 repeat:
23289     /* ":p" - full path/file_name */
23290     if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
23291     {
23292         has_fullname = 1;
23293
23294         valid |= VALID_PATH;
23295         *usedlen += 2;
23296
23297         /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
23298         if ((*fnamep)[0] == '~'
23299 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
23300                 && ((*fnamep)[1] == '/'
23301 # ifdef BACKSLASH_IN_FILENAME
23302                     || (*fnamep)[1] == '\\'
23303 # endif
23304                     || (*fnamep)[1] == NUL)
23305
23306 #endif
23307            )
23308         {
23309             *fnamep = expand_env_save(*fnamep);
23310             vim_free(*bufp);    /* free any allocated file name */
23311             *bufp = *fnamep;
23312             if (*fnamep == NULL)
23313                 return -1;
23314         }
23315
23316         /* When "/." or "/.." is used: force expansion to get rid of it. */
23317         for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
23318         {
23319             if (vim_ispathsep(*p)
23320                     && p[1] == '.'
23321                     && (p[2] == NUL
23322                         || vim_ispathsep(p[2])
23323                         || (p[2] == '.'
23324                             && (p[3] == NUL || vim_ispathsep(p[3])))))
23325                 break;
23326         }
23327
23328         /* FullName_save() is slow, don't use it when not needed. */
23329         if (*p != NUL || !vim_isAbsName(*fnamep))
23330         {
23331             *fnamep = FullName_save(*fnamep, *p != NUL);
23332             vim_free(*bufp);    /* free any allocated file name */
23333             *bufp = *fnamep;
23334             if (*fnamep == NULL)
23335                 return -1;
23336         }
23337
23338         /* Append a path separator to a directory. */
23339         if (mch_isdir(*fnamep))
23340         {
23341             /* Make room for one or two extra characters. */
23342             *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
23343             vim_free(*bufp);    /* free any allocated file name */
23344             *bufp = *fnamep;
23345             if (*fnamep == NULL)
23346                 return -1;
23347             add_pathsep(*fnamep);
23348         }
23349     }
23350
23351     /* ":." - path relative to the current directory */
23352     /* ":~" - path relative to the home directory */
23353     /* ":8" - shortname path - postponed till after */
23354     while (src[*usedlen] == ':'
23355                   && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
23356     {
23357         *usedlen += 2;
23358         if (c == '8')
23359         {
23360 #ifdef WIN3264
23361             has_shortname = 1; /* Postpone this. */
23362 #endif
23363             continue;
23364         }
23365         pbuf = NULL;
23366         /* Need full path first (use expand_env() to remove a "~/") */
23367         if (!has_fullname)
23368         {
23369             if (c == '.' && **fnamep == '~')
23370                 p = pbuf = expand_env_save(*fnamep);
23371             else
23372                 p = pbuf = FullName_save(*fnamep, FALSE);
23373         }
23374         else
23375             p = *fnamep;
23376
23377         has_fullname = 0;
23378
23379         if (p != NULL)
23380         {
23381             if (c == '.')
23382             {
23383                 mch_dirname(dirname, MAXPATHL);
23384                 s = shorten_fname(p, dirname);
23385                 if (s != NULL)
23386                 {
23387                     *fnamep = s;
23388                     if (pbuf != NULL)
23389                     {
23390                         vim_free(*bufp);   /* free any allocated file name */
23391                         *bufp = pbuf;
23392                         pbuf = NULL;
23393                     }
23394                 }
23395             }
23396             else
23397             {
23398                 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
23399                 /* Only replace it when it starts with '~' */
23400                 if (*dirname == '~')
23401                 {
23402                     s = vim_strsave(dirname);
23403                     if (s != NULL)
23404                     {
23405                         *fnamep = s;
23406                         vim_free(*bufp);
23407                         *bufp = s;
23408                     }
23409                 }
23410             }
23411             vim_free(pbuf);
23412         }
23413     }
23414
23415     tail = gettail(*fnamep);
23416     *fnamelen = (int)STRLEN(*fnamep);
23417
23418     /* ":h" - head, remove "/file_name", can be repeated  */
23419     /* Don't remove the first "/" or "c:\" */
23420     while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
23421     {
23422         valid |= VALID_HEAD;
23423         *usedlen += 2;
23424         s = get_past_head(*fnamep);
23425         while (tail > s && after_pathsep(s, tail))
23426             mb_ptr_back(*fnamep, tail);
23427         *fnamelen = (int)(tail - *fnamep);
23428 #ifdef VMS
23429         if (*fnamelen > 0)
23430             *fnamelen += 1; /* the path separator is part of the path */
23431 #endif
23432         if (*fnamelen == 0)
23433         {
23434             /* Result is empty.  Turn it into "." to make ":cd %:h" work. */
23435             p = vim_strsave((char_u *)".");
23436             if (p == NULL)
23437                 return -1;
23438             vim_free(*bufp);
23439             *bufp = *fnamep = tail = p;
23440             *fnamelen = 1;
23441         }
23442         else
23443         {
23444             while (tail > s && !after_pathsep(s, tail))
23445                 mb_ptr_back(*fnamep, tail);
23446         }
23447     }
23448
23449     /* ":8" - shortname  */
23450     if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
23451     {
23452         *usedlen += 2;
23453 #ifdef WIN3264
23454         has_shortname = 1;
23455 #endif
23456     }
23457
23458 #ifdef WIN3264
23459     /*
23460      * Handle ":8" after we have done 'heads' and before we do 'tails'.
23461      */
23462     if (has_shortname)
23463     {
23464         /* Copy the string if it is shortened by :h and when it wasn't copied
23465          * yet, because we are going to change it in place.  Avoids changing
23466          * the buffer name for "%:8". */
23467         if (*fnamelen < (int)STRLEN(*fnamep) || *fnamep == fname_start)
23468         {
23469             p = vim_strnsave(*fnamep, *fnamelen);
23470             if (p == NULL)
23471                 return -1;
23472             vim_free(*bufp);
23473             *bufp = *fnamep = p;
23474         }
23475
23476         /* Split into two implementations - makes it easier.  First is where
23477          * there isn't a full name already, second is where there is. */
23478         if (!has_fullname && !vim_isAbsName(*fnamep))
23479         {
23480             if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
23481                 return -1;
23482         }
23483         else
23484         {
23485             int         l = *fnamelen;
23486
23487             /* Simple case, already have the full-name.
23488              * Nearly always shorter, so try first time. */
23489             if (get_short_pathname(fnamep, bufp, &l) == FAIL)
23490                 return -1;
23491
23492             if (l == 0)
23493             {
23494                 /* Couldn't find the filename, search the paths. */
23495                 l = *fnamelen;
23496                 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
23497                     return -1;
23498             }
23499             *fnamelen = l;
23500         }
23501     }
23502 #endif /* WIN3264 */
23503
23504     /* ":t" - tail, just the basename */
23505     if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
23506     {
23507         *usedlen += 2;
23508         *fnamelen -= (int)(tail - *fnamep);
23509         *fnamep = tail;
23510     }
23511
23512     /* ":e" - extension, can be repeated */
23513     /* ":r" - root, without extension, can be repeated */
23514     while (src[*usedlen] == ':'
23515             && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
23516     {
23517         /* find a '.' in the tail:
23518          * - for second :e: before the current fname
23519          * - otherwise: The last '.'
23520          */
23521         if (src[*usedlen + 1] == 'e' && *fnamep > tail)
23522             s = *fnamep - 2;
23523         else
23524             s = *fnamep + *fnamelen - 1;
23525         for ( ; s > tail; --s)
23526             if (s[0] == '.')
23527                 break;
23528         if (src[*usedlen + 1] == 'e')           /* :e */
23529         {
23530             if (s > tail)
23531             {
23532                 *fnamelen += (int)(*fnamep - (s + 1));
23533                 *fnamep = s + 1;
23534 #ifdef VMS
23535                 /* cut version from the extension */
23536                 s = *fnamep + *fnamelen - 1;
23537                 for ( ; s > *fnamep; --s)
23538                     if (s[0] == ';')
23539                         break;
23540                 if (s > *fnamep)
23541                     *fnamelen = s - *fnamep;
23542 #endif
23543             }
23544             else if (*fnamep <= tail)
23545                 *fnamelen = 0;
23546         }
23547         else                            /* :r */
23548         {
23549             if (s > tail)       /* remove one extension */
23550                 *fnamelen = (int)(s - *fnamep);
23551         }
23552         *usedlen += 2;
23553     }
23554
23555     /* ":s?pat?foo?" - substitute */
23556     /* ":gs?pat?foo?" - global substitute */
23557     if (src[*usedlen] == ':'
23558             && (src[*usedlen + 1] == 's'
23559                 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
23560     {
23561         char_u      *str;
23562         char_u      *pat;
23563         char_u      *sub;
23564         int         sep;
23565         char_u      *flags;
23566         int         didit = FALSE;
23567
23568         flags = (char_u *)"";
23569         s = src + *usedlen + 2;
23570         if (src[*usedlen + 1] == 'g')
23571         {
23572             flags = (char_u *)"g";
23573             ++s;
23574         }
23575
23576         sep = *s++;
23577         if (sep)
23578         {
23579             /* find end of pattern */
23580             p = vim_strchr(s, sep);
23581             if (p != NULL)
23582             {
23583                 pat = vim_strnsave(s, (int)(p - s));
23584                 if (pat != NULL)
23585                 {
23586                     s = p + 1;
23587                     /* find end of substitution */
23588                     p = vim_strchr(s, sep);
23589                     if (p != NULL)
23590                     {
23591                         sub = vim_strnsave(s, (int)(p - s));
23592                         str = vim_strnsave(*fnamep, *fnamelen);
23593                         if (sub != NULL && str != NULL)
23594                         {
23595                             *usedlen = (int)(p + 1 - src);
23596                             s = do_string_sub(str, pat, sub, flags);
23597                             if (s != NULL)
23598                             {
23599                                 *fnamep = s;
23600                                 *fnamelen = (int)STRLEN(s);
23601                                 vim_free(*bufp);
23602                                 *bufp = s;
23603                                 didit = TRUE;
23604                             }
23605                         }
23606                         vim_free(sub);
23607                         vim_free(str);
23608                     }
23609                     vim_free(pat);
23610                 }
23611             }
23612             /* after using ":s", repeat all the modifiers */
23613             if (didit)
23614                 goto repeat;
23615         }
23616     }
23617
23618     return valid;
23619 }
23620
23621 /*
23622  * Perform a substitution on "str" with pattern "pat" and substitute "sub".
23623  * "flags" can be "g" to do a global substitute.
23624  * Returns an allocated string, NULL for error.
23625  */
23626     char_u *
23627 do_string_sub(str, pat, sub, flags)
23628     char_u      *str;
23629     char_u      *pat;
23630     char_u      *sub;
23631     char_u      *flags;
23632 {
23633     int         sublen;
23634     regmatch_T  regmatch;
23635     int         i;
23636     int         do_all;
23637     char_u      *tail;
23638     garray_T    ga;
23639     char_u      *ret;
23640     char_u      *save_cpo;
23641
23642     /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
23643     save_cpo = p_cpo;
23644     p_cpo = empty_option;
23645
23646     ga_init2(&ga, 1, 200);
23647
23648     do_all = (flags[0] == 'g');
23649
23650     regmatch.rm_ic = p_ic;
23651     regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
23652     if (regmatch.regprog != NULL)
23653     {
23654         tail = str;
23655         while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
23656         {
23657             /*
23658              * Get some space for a temporary buffer to do the substitution
23659              * into.  It will contain:
23660              * - The text up to where the match is.
23661              * - The substituted text.
23662              * - The text after the match.
23663              */
23664             sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
23665             if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
23666                             (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
23667             {
23668                 ga_clear(&ga);
23669                 break;
23670             }
23671
23672             /* copy the text up to where the match is */
23673             i = (int)(regmatch.startp[0] - tail);
23674             mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
23675             /* add the substituted text */
23676             (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
23677                                           + ga.ga_len + i, TRUE, TRUE, FALSE);
23678             ga.ga_len += i + sublen - 1;
23679             /* avoid getting stuck on a match with an empty string */
23680             if (tail == regmatch.endp[0])
23681             {
23682                 if (*tail == NUL)
23683                     break;
23684                 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
23685                 ++ga.ga_len;
23686             }
23687             else
23688             {
23689                 tail = regmatch.endp[0];
23690                 if (*tail == NUL)
23691                     break;
23692             }
23693             if (!do_all)
23694                 break;
23695         }
23696
23697         if (ga.ga_data != NULL)
23698             STRCPY((char *)ga.ga_data + ga.ga_len, tail);
23699
23700         vim_free(regmatch.regprog);
23701     }
23702
23703     ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
23704     ga_clear(&ga);
23705     if (p_cpo == empty_option)
23706         p_cpo = save_cpo;
23707     else
23708         /* Darn, evaluating {sub} expression changed the value. */
23709         free_string_option(save_cpo);
23710
23711     return ret;
23712 }
23713
23714 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */