Merged from the latest developing branch.
[MacVim/KaoriYa.git] / src / eval.c
blob34263544cb66bf7075efa6ea5c9ed6deda0dbfc0
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
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 */
11 * eval.c: Expression evaluation.
13 #if defined(MSDOS) || defined(MSWIN)
14 # include "vimio.h" /* for mch_open(), must be before vim.h */
15 #endif
17 #include "vim.h"
19 #ifdef AMIGA
20 # include <time.h> /* for strftime() */
21 #endif
23 #ifdef MACOS
24 # include <time.h> /* for time_t */
25 #endif
27 #ifdef HAVE_FCNTL_H
28 # include <fcntl.h>
29 #endif
31 #if defined(FEAT_EVAL) || defined(PROTO)
33 #define DICT_MAXNEST 100 /* maximum nesting of lists and dicts */
36 * In a hashtab item "hi_key" points to "di_key" in a dictitem.
37 * This avoids adding a pointer to the hashtab item.
38 * DI2HIKEY() converts a dictitem pointer to a hashitem key pointer.
39 * HIKEY2DI() converts a hashitem key pointer to a dictitem pointer.
40 * HI2DI() converts a hashitem pointer to a dictitem pointer.
42 static dictitem_T dumdi;
43 #define DI2HIKEY(di) ((di)->di_key)
44 #define HIKEY2DI(p) ((dictitem_T *)(p - (dumdi.di_key - (char_u *)&dumdi)))
45 #define HI2DI(hi) HIKEY2DI((hi)->hi_key)
48 * Structure returned by get_lval() and used by set_var_lval().
49 * For a plain name:
50 * "name" points to the variable name.
51 * "exp_name" is NULL.
52 * "tv" is NULL
53 * For a magic braces name:
54 * "name" points to the expanded variable name.
55 * "exp_name" is non-NULL, to be freed later.
56 * "tv" is NULL
57 * For an index in a list:
58 * "name" points to the (expanded) variable name.
59 * "exp_name" NULL or non-NULL, to be freed later.
60 * "tv" points to the (first) list item value
61 * "li" points to the (first) list item
62 * "range", "n1", "n2" and "empty2" indicate what items are used.
63 * For an existing Dict item:
64 * "name" points to the (expanded) variable name.
65 * "exp_name" NULL or non-NULL, to be freed later.
66 * "tv" points to the dict item value
67 * "newkey" is NULL
68 * For a non-existing Dict item:
69 * "name" points to the (expanded) variable name.
70 * "exp_name" NULL or non-NULL, to be freed later.
71 * "tv" points to the Dictionary typval_T
72 * "newkey" is the key for the new item.
74 typedef struct lval_S
76 char_u *ll_name; /* start of variable name (can be NULL) */
77 char_u *ll_exp_name; /* NULL or expanded name in allocated memory. */
78 typval_T *ll_tv; /* Typeval of item being used. If "newkey"
79 isn't NULL it's the Dict to which to add
80 the item. */
81 listitem_T *ll_li; /* The list item or NULL. */
82 list_T *ll_list; /* The list or NULL. */
83 int ll_range; /* TRUE when a [i:j] range was used */
84 long ll_n1; /* First index for list */
85 long ll_n2; /* Second index for list range */
86 int ll_empty2; /* Second index is empty: [i:] */
87 dict_T *ll_dict; /* The Dictionary or NULL */
88 dictitem_T *ll_di; /* The dictitem or NULL */
89 char_u *ll_newkey; /* New key for Dict in alloc. mem or NULL. */
90 } lval_T;
93 static char *e_letunexp = N_("E18: Unexpected characters in :let");
94 static char *e_listidx = N_("E684: list index out of range: %ld");
95 static char *e_undefvar = N_("E121: Undefined variable: %s");
96 static char *e_missbrac = N_("E111: Missing ']'");
97 static char *e_listarg = N_("E686: Argument of %s must be a List");
98 static char *e_listdictarg = N_("E712: Argument of %s must be a List or Dictionary");
99 static char *e_emptykey = N_("E713: Cannot use empty key for Dictionary");
100 static char *e_listreq = N_("E714: List required");
101 static char *e_dictreq = N_("E715: Dictionary required");
102 static char *e_toomanyarg = N_("E118: Too many arguments for function: %s");
103 static char *e_dictkey = N_("E716: Key not present in Dictionary: %s");
104 static char *e_funcexts = N_("E122: Function %s already exists, add ! to replace it");
105 static char *e_funcdict = N_("E717: Dictionary entry already exists");
106 static char *e_funcref = N_("E718: Funcref required");
107 static char *e_dictrange = N_("E719: Cannot use [:] with a Dictionary");
108 static char *e_letwrong = N_("E734: Wrong variable type for %s=");
109 static char *e_nofunc = N_("E130: Unknown function: %s");
110 static char *e_illvar = N_("E461: Illegal variable name: %s");
112 * All user-defined global variables are stored in dictionary "globvardict".
113 * "globvars_var" is the variable that is used for "g:".
115 static dict_T globvardict;
116 static dictitem_T globvars_var;
117 #define globvarht globvardict.dv_hashtab
120 * Old Vim variables such as "v:version" are also available without the "v:".
121 * Also in functions. We need a special hashtable for them.
123 static hashtab_T compat_hashtab;
126 * When recursively copying lists and dicts we need to remember which ones we
127 * have done to avoid endless recursiveness. This unique ID is used for that.
129 static int current_copyID = 0;
132 * Array to hold the hashtab with variables local to each sourced script.
133 * Each item holds a variable (nameless) that points to the dict_T.
135 typedef struct
137 dictitem_T sv_var;
138 dict_T sv_dict;
139 } scriptvar_T;
141 static garray_T ga_scripts = {0, 0, sizeof(scriptvar_T), 4, NULL};
142 #define SCRIPT_SV(id) (((scriptvar_T *)ga_scripts.ga_data)[(id) - 1])
143 #define SCRIPT_VARS(id) (SCRIPT_SV(id).sv_dict.dv_hashtab)
145 static int echo_attr = 0; /* attributes used for ":echo" */
147 /* Values for trans_function_name() argument: */
148 #define TFN_INT 1 /* internal function name OK */
149 #define TFN_QUIET 2 /* no error messages */
152 * Structure to hold info for a user function.
154 typedef struct ufunc ufunc_T;
156 struct ufunc
158 int uf_varargs; /* variable nr of arguments */
159 int uf_flags;
160 int uf_calls; /* nr of active calls */
161 garray_T uf_args; /* arguments */
162 garray_T uf_lines; /* function lines */
163 #ifdef FEAT_PROFILE
164 int uf_profiling; /* TRUE when func is being profiled */
165 /* profiling the function as a whole */
166 int uf_tm_count; /* nr of calls */
167 proftime_T uf_tm_total; /* time spend in function + children */
168 proftime_T uf_tm_self; /* time spend in function itself */
169 proftime_T uf_tm_children; /* time spent in children this call */
170 /* profiling the function per line */
171 int *uf_tml_count; /* nr of times line was executed */
172 proftime_T *uf_tml_total; /* time spend in a line + children */
173 proftime_T *uf_tml_self; /* time spend in a line itself */
174 proftime_T uf_tml_start; /* start time for current line */
175 proftime_T uf_tml_children; /* time spent in children for this line */
176 proftime_T uf_tml_wait; /* start wait time for current line */
177 int uf_tml_idx; /* index of line being timed; -1 if none */
178 int uf_tml_execed; /* line being timed was executed */
179 #endif
180 scid_T uf_script_ID; /* ID of script where function was defined,
181 used for s: variables */
182 int uf_refcount; /* for numbered function: reference count */
183 char_u uf_name[1]; /* name of function (actually longer); can
184 start with <SNR>123_ (<SNR> is K_SPECIAL
185 KS_EXTRA KE_SNR) */
188 /* function flags */
189 #define FC_ABORT 1 /* abort function on error */
190 #define FC_RANGE 2 /* function accepts range */
191 #define FC_DICT 4 /* Dict function, uses "self" */
194 * All user-defined functions are found in this hashtable.
196 static hashtab_T func_hashtab;
198 /* The names of packages that once were loaded are remembered. */
199 static garray_T ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
201 /* list heads for garbage collection */
202 static dict_T *first_dict = NULL; /* list of all dicts */
203 static list_T *first_list = NULL; /* list of all lists */
205 /* From user function to hashitem and back. */
206 static ufunc_T dumuf;
207 #define UF2HIKEY(fp) ((fp)->uf_name)
208 #define HIKEY2UF(p) ((ufunc_T *)(p - (dumuf.uf_name - (char_u *)&dumuf)))
209 #define HI2UF(hi) HIKEY2UF((hi)->hi_key)
211 #define FUNCARG(fp, j) ((char_u **)(fp->uf_args.ga_data))[j]
212 #define FUNCLINE(fp, j) ((char_u **)(fp->uf_lines.ga_data))[j]
214 #define MAX_FUNC_ARGS 20 /* maximum number of function arguments */
215 #define VAR_SHORT_LEN 20 /* short variable name length */
216 #define FIXVAR_CNT 12 /* number of fixed variables */
218 /* structure to hold info for a function that is currently being executed. */
219 typedef struct funccall_S funccall_T;
221 struct funccall_S
223 ufunc_T *func; /* function being called */
224 int linenr; /* next line to be executed */
225 int returned; /* ":return" used */
226 struct /* fixed variables for arguments */
228 dictitem_T var; /* variable (without room for name) */
229 char_u room[VAR_SHORT_LEN]; /* room for the name */
230 } fixvar[FIXVAR_CNT];
231 dict_T l_vars; /* l: local function variables */
232 dictitem_T l_vars_var; /* variable for l: scope */
233 dict_T l_avars; /* a: argument variables */
234 dictitem_T l_avars_var; /* variable for a: scope */
235 list_T l_varlist; /* list for a:000 */
236 listitem_T l_listitems[MAX_FUNC_ARGS]; /* listitems for a:000 */
237 typval_T *rettv; /* return value */
238 linenr_T breakpoint; /* next line with breakpoint or zero */
239 int dbg_tick; /* debug_tick when breakpoint was set */
240 int level; /* top nesting level of executed function */
241 #ifdef FEAT_PROFILE
242 proftime_T prof_child; /* time spent in a child */
243 #endif
244 funccall_T *caller; /* calling function or NULL */
248 * Info used by a ":for" loop.
250 typedef struct
252 int fi_semicolon; /* TRUE if ending in '; var]' */
253 int fi_varcount; /* nr of variables in the list */
254 listwatch_T fi_lw; /* keep an eye on the item used. */
255 list_T *fi_list; /* list being used */
256 } forinfo_T;
259 * Struct used by trans_function_name()
261 typedef struct
263 dict_T *fd_dict; /* Dictionary used */
264 char_u *fd_newkey; /* new key in "dict" in allocated memory */
265 dictitem_T *fd_di; /* Dictionary item used */
266 } funcdict_T;
270 * Array to hold the value of v: variables.
271 * The value is in a dictitem, so that it can also be used in the v: scope.
272 * The reason to use this table anyway is for very quick access to the
273 * variables with the VV_ defines.
275 #include "version.h"
277 /* values for vv_flags: */
278 #define VV_COMPAT 1 /* compatible, also used without "v:" */
279 #define VV_RO 2 /* read-only */
280 #define VV_RO_SBX 4 /* read-only in the sandbox */
282 #define VV_NAME(s, t) s, {{t}}, {0}
284 static struct vimvar
286 char *vv_name; /* name of variable, without v: */
287 dictitem_T vv_di; /* value and name for key */
288 char vv_filler[16]; /* space for LONGEST name below!!! */
289 char vv_flags; /* VV_COMPAT, VV_RO, VV_RO_SBX */
290 } vimvars[VV_LEN] =
293 * The order here must match the VV_ defines in vim.h!
294 * Initializing a union does not work, leave tv.vval empty to get zero's.
296 {VV_NAME("count", VAR_NUMBER), VV_COMPAT+VV_RO},
297 {VV_NAME("count1", VAR_NUMBER), VV_RO},
298 {VV_NAME("prevcount", VAR_NUMBER), VV_RO},
299 {VV_NAME("errmsg", VAR_STRING), VV_COMPAT},
300 {VV_NAME("warningmsg", VAR_STRING), 0},
301 {VV_NAME("statusmsg", VAR_STRING), 0},
302 {VV_NAME("shell_error", VAR_NUMBER), VV_COMPAT+VV_RO},
303 {VV_NAME("this_session", VAR_STRING), VV_COMPAT},
304 {VV_NAME("version", VAR_NUMBER), VV_COMPAT+VV_RO},
305 {VV_NAME("lnum", VAR_NUMBER), VV_RO_SBX},
306 {VV_NAME("termresponse", VAR_STRING), VV_RO},
307 {VV_NAME("fname", VAR_STRING), VV_RO},
308 {VV_NAME("lang", VAR_STRING), VV_RO},
309 {VV_NAME("lc_time", VAR_STRING), VV_RO},
310 {VV_NAME("ctype", VAR_STRING), VV_RO},
311 {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
312 {VV_NAME("charconvert_to", VAR_STRING), VV_RO},
313 {VV_NAME("fname_in", VAR_STRING), VV_RO},
314 {VV_NAME("fname_out", VAR_STRING), VV_RO},
315 {VV_NAME("fname_new", VAR_STRING), VV_RO},
316 {VV_NAME("fname_diff", VAR_STRING), VV_RO},
317 {VV_NAME("cmdarg", VAR_STRING), VV_RO},
318 {VV_NAME("foldstart", VAR_NUMBER), VV_RO_SBX},
319 {VV_NAME("foldend", VAR_NUMBER), VV_RO_SBX},
320 {VV_NAME("folddashes", VAR_STRING), VV_RO_SBX},
321 {VV_NAME("foldlevel", VAR_NUMBER), VV_RO_SBX},
322 {VV_NAME("progname", VAR_STRING), VV_RO},
323 {VV_NAME("servername", VAR_STRING), VV_RO},
324 {VV_NAME("dying", VAR_NUMBER), VV_RO},
325 {VV_NAME("exception", VAR_STRING), VV_RO},
326 {VV_NAME("throwpoint", VAR_STRING), VV_RO},
327 {VV_NAME("register", VAR_STRING), VV_RO},
328 {VV_NAME("cmdbang", VAR_NUMBER), VV_RO},
329 {VV_NAME("insertmode", VAR_STRING), VV_RO},
330 {VV_NAME("val", VAR_UNKNOWN), VV_RO},
331 {VV_NAME("key", VAR_UNKNOWN), VV_RO},
332 {VV_NAME("profiling", VAR_NUMBER), VV_RO},
333 {VV_NAME("fcs_reason", VAR_STRING), VV_RO},
334 {VV_NAME("fcs_choice", VAR_STRING), 0},
335 {VV_NAME("beval_bufnr", VAR_NUMBER), VV_RO},
336 {VV_NAME("beval_winnr", VAR_NUMBER), VV_RO},
337 {VV_NAME("beval_lnum", VAR_NUMBER), VV_RO},
338 {VV_NAME("beval_col", VAR_NUMBER), VV_RO},
339 {VV_NAME("beval_text", VAR_STRING), VV_RO},
340 {VV_NAME("scrollstart", VAR_STRING), 0},
341 {VV_NAME("swapname", VAR_STRING), VV_RO},
342 {VV_NAME("swapchoice", VAR_STRING), 0},
343 {VV_NAME("swapcommand", VAR_STRING), VV_RO},
344 {VV_NAME("char", VAR_STRING), VV_RO},
345 {VV_NAME("mouse_win", VAR_NUMBER), 0},
346 {VV_NAME("mouse_lnum", VAR_NUMBER), 0},
347 {VV_NAME("mouse_col", VAR_NUMBER), 0},
348 {VV_NAME("operator", VAR_STRING), VV_RO},
351 /* shorthand */
352 #define vv_type vv_di.di_tv.v_type
353 #define vv_nr vv_di.di_tv.vval.v_number
354 #define vv_str vv_di.di_tv.vval.v_string
355 #define vv_tv vv_di.di_tv
358 * The v: variables are stored in dictionary "vimvardict".
359 * "vimvars_var" is the variable that is used for the "l:" scope.
361 static dict_T vimvardict;
362 static dictitem_T vimvars_var;
363 #define vimvarht vimvardict.dv_hashtab
365 static void prepare_vimvar __ARGS((int idx, typval_T *save_tv));
366 static void restore_vimvar __ARGS((int idx, typval_T *save_tv));
367 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
368 static int call_vim_function __ARGS((char_u *func, int argc, char_u **argv, int safe, typval_T *rettv));
369 #endif
370 static int ex_let_vars __ARGS((char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars));
371 static char_u *skip_var_list __ARGS((char_u *arg, int *var_count, int *semicolon));
372 static char_u *skip_var_one __ARGS((char_u *arg));
373 static void list_hashtable_vars __ARGS((hashtab_T *ht, char_u *prefix, int empty, int *first));
374 static void list_glob_vars __ARGS((int *first));
375 static void list_buf_vars __ARGS((int *first));
376 static void list_win_vars __ARGS((int *first));
377 #ifdef FEAT_WINDOWS
378 static void list_tab_vars __ARGS((int *first));
379 #endif
380 static void list_vim_vars __ARGS((int *first));
381 static void list_script_vars __ARGS((int *first));
382 static void list_func_vars __ARGS((int *first));
383 static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg, int *first));
384 static char_u *ex_let_one __ARGS((char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op));
385 static int check_changedtick __ARGS((char_u *arg));
386 static char_u *get_lval __ARGS((char_u *name, typval_T *rettv, lval_T *lp, int unlet, int skip, int quiet, int fne_flags));
387 static void clear_lval __ARGS((lval_T *lp));
388 static void set_var_lval __ARGS((lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op));
389 static int tv_op __ARGS((typval_T *tv1, typval_T *tv2, char_u *op));
390 static void list_add_watch __ARGS((list_T *l, listwatch_T *lw));
391 static void list_rem_watch __ARGS((list_T *l, listwatch_T *lwrem));
392 static void list_fix_watch __ARGS((list_T *l, listitem_T *item));
393 static void ex_unletlock __ARGS((exarg_T *eap, char_u *argstart, int deep));
394 static int do_unlet_var __ARGS((lval_T *lp, char_u *name_end, int forceit));
395 static int do_lock_var __ARGS((lval_T *lp, char_u *name_end, int deep, int lock));
396 static void item_lock __ARGS((typval_T *tv, int deep, int lock));
397 static int tv_islocked __ARGS((typval_T *tv));
399 static int eval0 __ARGS((char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate));
400 static int eval1 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
401 static int eval2 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
402 static int eval3 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
403 static int eval4 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
404 static int eval5 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
405 static int eval6 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
406 static int eval7 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
408 static int eval_index __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
409 static int get_option_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
410 static int get_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
411 static int get_lit_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
412 static int get_list_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
413 static int rettv_list_alloc __ARGS((typval_T *rettv));
414 static listitem_T *listitem_alloc __ARGS((void));
415 static void listitem_free __ARGS((listitem_T *item));
416 static void listitem_remove __ARGS((list_T *l, listitem_T *item));
417 static long list_len __ARGS((list_T *l));
418 static int list_equal __ARGS((list_T *l1, list_T *l2, int ic));
419 static int dict_equal __ARGS((dict_T *d1, dict_T *d2, int ic));
420 static int tv_equal __ARGS((typval_T *tv1, typval_T *tv2, int ic));
421 static listitem_T *list_find __ARGS((list_T *l, long n));
422 static long list_find_nr __ARGS((list_T *l, long idx, int *errorp));
423 static long list_idx_of_item __ARGS((list_T *l, listitem_T *item));
424 static void list_append __ARGS((list_T *l, listitem_T *item));
425 static int list_append_tv __ARGS((list_T *l, typval_T *tv));
426 static int list_append_string __ARGS((list_T *l, char_u *str, int len));
427 static int list_append_number __ARGS((list_T *l, varnumber_T n));
428 static int list_insert_tv __ARGS((list_T *l, typval_T *tv, listitem_T *item));
429 static int list_extend __ARGS((list_T *l1, list_T *l2, listitem_T *bef));
430 static int list_concat __ARGS((list_T *l1, list_T *l2, typval_T *tv));
431 static list_T *list_copy __ARGS((list_T *orig, int deep, int copyID));
432 static void list_remove __ARGS((list_T *l, listitem_T *item, listitem_T *item2));
433 static char_u *list2string __ARGS((typval_T *tv, int copyID));
434 static int list_join __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo, int copyID));
435 static void set_ref_in_ht __ARGS((hashtab_T *ht, int copyID));
436 static void set_ref_in_list __ARGS((list_T *l, int copyID));
437 static void set_ref_in_item __ARGS((typval_T *tv, int copyID));
438 static void dict_unref __ARGS((dict_T *d));
439 static void dict_free __ARGS((dict_T *d, int recurse));
440 static dictitem_T *dictitem_alloc __ARGS((char_u *key));
441 static dictitem_T *dictitem_copy __ARGS((dictitem_T *org));
442 static void dictitem_remove __ARGS((dict_T *dict, dictitem_T *item));
443 static void dictitem_free __ARGS((dictitem_T *item));
444 static dict_T *dict_copy __ARGS((dict_T *orig, int deep, int copyID));
445 static int dict_add __ARGS((dict_T *d, dictitem_T *item));
446 static long dict_len __ARGS((dict_T *d));
447 static dictitem_T *dict_find __ARGS((dict_T *d, char_u *key, int len));
448 static char_u *dict2string __ARGS((typval_T *tv, int copyID));
449 static int get_dict_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
450 static char_u *echo_string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
451 static char_u *tv2string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
452 static char_u *string_quote __ARGS((char_u *str, int function));
453 static int get_env_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
454 static int find_internal_func __ARGS((char_u *name));
455 static char_u *deref_func_name __ARGS((char_u *name, int *lenp));
456 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));
457 static int call_func __ARGS((char_u *name, int len, typval_T *rettv, int argcount, typval_T *argvars, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
458 static void emsg_funcname __ARGS((char *ermsg, char_u *name));
460 static void f_add __ARGS((typval_T *argvars, typval_T *rettv));
461 static void f_append __ARGS((typval_T *argvars, typval_T *rettv));
462 static void f_argc __ARGS((typval_T *argvars, typval_T *rettv));
463 static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv));
464 static void f_argv __ARGS((typval_T *argvars, typval_T *rettv));
465 static void f_browse __ARGS((typval_T *argvars, typval_T *rettv));
466 static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv));
467 static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv));
468 static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv));
469 static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv));
470 static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv));
471 static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv));
472 static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv));
473 static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv));
474 static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv));
475 static void f_call __ARGS((typval_T *argvars, typval_T *rettv));
476 static void f_changenr __ARGS((typval_T *argvars, typval_T *rettv));
477 static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv));
478 static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv));
479 static void f_clearmatches __ARGS((typval_T *argvars, typval_T *rettv));
480 static void f_col __ARGS((typval_T *argvars, typval_T *rettv));
481 #if defined(FEAT_INS_EXPAND)
482 static void f_complete __ARGS((typval_T *argvars, typval_T *rettv));
483 static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv));
484 static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv));
485 #endif
486 static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv));
487 static void f_copy __ARGS((typval_T *argvars, typval_T *rettv));
488 static void f_count __ARGS((typval_T *argvars, typval_T *rettv));
489 static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv));
490 static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv));
491 static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv));
492 static void f_delete __ARGS((typval_T *argvars, typval_T *rettv));
493 static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv));
494 static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv));
495 static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv));
496 static void f_empty __ARGS((typval_T *argvars, typval_T *rettv));
497 static void f_escape __ARGS((typval_T *argvars, typval_T *rettv));
498 static void f_eval __ARGS((typval_T *argvars, typval_T *rettv));
499 static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv));
500 static void f_executable __ARGS((typval_T *argvars, typval_T *rettv));
501 static void f_exists __ARGS((typval_T *argvars, typval_T *rettv));
502 static void f_expand __ARGS((typval_T *argvars, typval_T *rettv));
503 static void f_extend __ARGS((typval_T *argvars, typval_T *rettv));
504 static void f_feedkeys __ARGS((typval_T *argvars, typval_T *rettv));
505 static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv));
506 static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv));
507 static void f_filter __ARGS((typval_T *argvars, typval_T *rettv));
508 static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv));
509 static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv));
510 static void f_fnameescape __ARGS((typval_T *argvars, typval_T *rettv));
511 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
513 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
514 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
516 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
517 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
520 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
521 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
523 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
524 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
525 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
526 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
528 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
529 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
531 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
532 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
533 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
534 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
535 static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv));
536 static void f_getpid __ARGS((typval_T *argvars, typval_T *rettv));
537 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
542 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
546 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
547 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
548 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
549 static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
551 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
552 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
590 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
591 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
592 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
593 #ifdef vim_mkdir
594 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
595 #endif
596 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
603 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
604 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
605 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
606 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
607 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
608 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
609 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
610 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
611 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
618 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
619 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
620 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
621 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
622 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
623 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
624 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
625 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
626 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
627 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
628 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
629 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
630 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
631 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
632 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
633 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
634 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
635 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
636 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
637 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
638 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
639 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
640 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
641 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
642 #ifdef HAVE_STRFTIME
643 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
644 #endif
645 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
646 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
647 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
648 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
649 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
650 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
651 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
652 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
653 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
654 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
655 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
656 static void f_synstack __ARGS((typval_T *argvars, typval_T *rettv));
657 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
667 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
668 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
669 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
670 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
671 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
672 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
673 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
674 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
675 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
676 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
677 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
678 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
679 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
680 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
681 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
683 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
684 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
685 static int get_env_len __ARGS((char_u **arg));
686 static int get_id_len __ARGS((char_u **arg));
687 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
688 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
689 #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */
690 #define FNE_CHECK_START 2 /* find_name_end(): check name starts with
691 valid character */
692 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
693 static int eval_isnamec __ARGS((int c));
694 static int eval_isnamec1 __ARGS((int c));
695 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
696 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
697 static typval_T *alloc_tv __ARGS((void));
698 static typval_T *alloc_string_tv __ARGS((char_u *string));
699 static void init_tv __ARGS((typval_T *varp));
700 static long get_tv_number __ARGS((typval_T *varp));
701 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
702 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
703 static char_u *get_tv_string __ARGS((typval_T *varp));
704 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
705 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
706 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
707 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
708 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
709 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
710 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
711 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
712 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
713 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
714 static int var_check_ro __ARGS((int flags, char_u *name));
715 static int var_check_fixed __ARGS((int flags, char_u *name));
716 static int tv_check_lock __ARGS((int lock, char_u *name));
717 static void copy_tv __ARGS((typval_T *from, typval_T *to));
718 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
719 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
720 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
721 static int eval_fname_script __ARGS((char_u *p));
722 static int eval_fname_sid __ARGS((char_u *p));
723 static void list_func_head __ARGS((ufunc_T *fp, int indent));
724 static ufunc_T *find_func __ARGS((char_u *name));
725 static int function_exists __ARGS((char_u *name));
726 static int builtin_function __ARGS((char_u *name));
727 #ifdef FEAT_PROFILE
728 static void func_do_profile __ARGS((ufunc_T *fp));
729 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
730 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
731 static int
732 # ifdef __BORLANDC__
733 _RTLENTRYF
734 # endif
735 prof_total_cmp __ARGS((const void *s1, const void *s2));
736 static int
737 # ifdef __BORLANDC__
738 _RTLENTRYF
739 # endif
740 prof_self_cmp __ARGS((const void *s1, const void *s2));
741 #endif
742 static int script_autoload __ARGS((char_u *name, int reload));
743 static char_u *autoload_name __ARGS((char_u *name));
744 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
745 static void func_free __ARGS((ufunc_T *fp));
746 static void func_unref __ARGS((char_u *name));
747 static void func_ref __ARGS((char_u *name));
748 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));
749 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
750 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
751 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
752 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
753 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
754 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
756 /* Character used as separated in autoload function/variable names. */
757 #define AUTOLOAD_CHAR '#'
760 * Initialize the global and v: variables.
762 void
763 eval_init()
765 int i;
766 struct vimvar *p;
768 init_var_dict(&globvardict, &globvars_var);
769 init_var_dict(&vimvardict, &vimvars_var);
770 hash_init(&compat_hashtab);
771 hash_init(&func_hashtab);
773 for (i = 0; i < VV_LEN; ++i)
775 p = &vimvars[i];
776 STRCPY(p->vv_di.di_key, p->vv_name);
777 if (p->vv_flags & VV_RO)
778 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
779 else if (p->vv_flags & VV_RO_SBX)
780 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
781 else
782 p->vv_di.di_flags = DI_FLAGS_FIX;
784 /* add to v: scope dict, unless the value is not always available */
785 if (p->vv_type != VAR_UNKNOWN)
786 hash_add(&vimvarht, p->vv_di.di_key);
787 if (p->vv_flags & VV_COMPAT)
788 /* add to compat scope dict */
789 hash_add(&compat_hashtab, p->vv_di.di_key);
793 #if defined(EXITFREE) || defined(PROTO)
794 void
795 eval_clear()
797 int i;
798 struct vimvar *p;
800 for (i = 0; i < VV_LEN; ++i)
802 p = &vimvars[i];
803 if (p->vv_di.di_tv.v_type == VAR_STRING)
805 vim_free(p->vv_di.di_tv.vval.v_string);
806 p->vv_di.di_tv.vval.v_string = NULL;
809 hash_clear(&vimvarht);
810 hash_clear(&compat_hashtab);
812 /* script-local variables */
813 for (i = 1; i <= ga_scripts.ga_len; ++i)
814 vars_clear(&SCRIPT_VARS(i));
815 ga_clear(&ga_scripts);
816 free_scriptnames();
818 /* global variables */
819 vars_clear(&globvarht);
821 /* functions */
822 free_all_functions();
823 hash_clear(&func_hashtab);
825 /* autoloaded script names */
826 ga_clear_strings(&ga_loaded);
828 /* unreferenced lists and dicts */
829 (void)garbage_collect();
831 #endif
834 * Return the name of the executed function.
836 char_u *
837 func_name(cookie)
838 void *cookie;
840 return ((funccall_T *)cookie)->func->uf_name;
844 * Return the address holding the next breakpoint line for a funccall cookie.
846 linenr_T *
847 func_breakpoint(cookie)
848 void *cookie;
850 return &((funccall_T *)cookie)->breakpoint;
854 * Return the address holding the debug tick for a funccall cookie.
856 int *
857 func_dbg_tick(cookie)
858 void *cookie;
860 return &((funccall_T *)cookie)->dbg_tick;
864 * Return the nesting level for a funccall cookie.
867 func_level(cookie)
868 void *cookie;
870 return ((funccall_T *)cookie)->level;
873 /* pointer to funccal for currently active function */
874 funccall_T *current_funccal = NULL;
877 * Return TRUE when a function was ended by a ":return" command.
880 current_func_returned()
882 return current_funccal->returned;
887 * Set an internal variable to a string value. Creates the variable if it does
888 * not already exist.
890 void
891 set_internal_string_var(name, value)
892 char_u *name;
893 char_u *value;
895 char_u *val;
896 typval_T *tvp;
898 val = vim_strsave(value);
899 if (val != NULL)
901 tvp = alloc_string_tv(val);
902 if (tvp != NULL)
904 set_var(name, tvp, FALSE);
905 free_tv(tvp);
910 static lval_T *redir_lval = NULL;
911 static garray_T redir_ga; /* only valid when redir_lval is not NULL */
912 static char_u *redir_endp = NULL;
913 static char_u *redir_varname = NULL;
916 * Start recording command output to a variable
917 * Returns OK if successfully completed the setup. FAIL otherwise.
920 var_redir_start(name, append)
921 char_u *name;
922 int append; /* append to an existing variable */
924 int save_emsg;
925 int err;
926 typval_T tv;
928 /* Make sure a valid variable name is specified */
929 if (!eval_isnamec1(*name))
931 EMSG(_(e_invarg));
932 return FAIL;
935 redir_varname = vim_strsave(name);
936 if (redir_varname == NULL)
937 return FAIL;
939 redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
940 if (redir_lval == NULL)
942 var_redir_stop();
943 return FAIL;
946 /* The output is stored in growarray "redir_ga" until redirection ends. */
947 ga_init2(&redir_ga, (int)sizeof(char), 500);
949 /* Parse the variable name (can be a dict or list entry). */
950 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
951 FNE_CHECK_START);
952 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
954 if (redir_endp != NULL && *redir_endp != NUL)
955 /* Trailing characters are present after the variable name */
956 EMSG(_(e_trailing));
957 else
958 EMSG(_(e_invarg));
959 var_redir_stop();
960 return FAIL;
963 /* check if we can write to the variable: set it to or append an empty
964 * string */
965 save_emsg = did_emsg;
966 did_emsg = FALSE;
967 tv.v_type = VAR_STRING;
968 tv.vval.v_string = (char_u *)"";
969 if (append)
970 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
971 else
972 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
973 err = did_emsg;
974 did_emsg |= save_emsg;
975 if (err)
977 var_redir_stop();
978 return FAIL;
980 if (redir_lval->ll_newkey != NULL)
982 /* Dictionary item was created, don't do it again. */
983 vim_free(redir_lval->ll_newkey);
984 redir_lval->ll_newkey = NULL;
987 return OK;
991 * Append "value[value_len]" to the variable set by var_redir_start().
992 * The actual appending is postponed until redirection ends, because the value
993 * appended may in fact be the string we write to, changing it may cause freed
994 * memory to be used:
995 * :redir => foo
996 * :let foo
997 * :redir END
999 void
1000 var_redir_str(value, value_len)
1001 char_u *value;
1002 int value_len;
1004 int len;
1006 if (redir_lval == NULL)
1007 return;
1009 if (value_len == -1)
1010 len = (int)STRLEN(value); /* Append the entire string */
1011 else
1012 len = value_len; /* Append only "value_len" characters */
1014 if (ga_grow(&redir_ga, len) == OK)
1016 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1017 redir_ga.ga_len += len;
1019 else
1020 var_redir_stop();
1024 * Stop redirecting command output to a variable.
1026 void
1027 var_redir_stop()
1029 typval_T tv;
1031 if (redir_lval != NULL)
1033 /* Append the trailing NUL. */
1034 ga_append(&redir_ga, NUL);
1036 /* Assign the text to the variable. */
1037 tv.v_type = VAR_STRING;
1038 tv.vval.v_string = redir_ga.ga_data;
1039 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1040 vim_free(tv.vval.v_string);
1042 clear_lval(redir_lval);
1043 vim_free(redir_lval);
1044 redir_lval = NULL;
1046 vim_free(redir_varname);
1047 redir_varname = NULL;
1050 # if defined(FEAT_MBYTE) || defined(PROTO)
1052 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1053 char_u *enc_from;
1054 char_u *enc_to;
1055 char_u *fname_from;
1056 char_u *fname_to;
1058 int err = FALSE;
1060 set_vim_var_string(VV_CC_FROM, enc_from, -1);
1061 set_vim_var_string(VV_CC_TO, enc_to, -1);
1062 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1063 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1064 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1065 err = TRUE;
1066 set_vim_var_string(VV_CC_FROM, NULL, -1);
1067 set_vim_var_string(VV_CC_TO, NULL, -1);
1068 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1069 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1071 if (err)
1072 return FAIL;
1073 return OK;
1075 # endif
1077 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1079 eval_printexpr(fname, args)
1080 char_u *fname;
1081 char_u *args;
1083 int err = FALSE;
1085 set_vim_var_string(VV_FNAME_IN, fname, -1);
1086 set_vim_var_string(VV_CMDARG, args, -1);
1087 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1088 err = TRUE;
1089 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1090 set_vim_var_string(VV_CMDARG, NULL, -1);
1092 if (err)
1094 mch_remove(fname);
1095 return FAIL;
1097 return OK;
1099 # endif
1101 # if defined(FEAT_DIFF) || defined(PROTO)
1102 void
1103 eval_diff(origfile, newfile, outfile)
1104 char_u *origfile;
1105 char_u *newfile;
1106 char_u *outfile;
1108 int err = FALSE;
1110 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1111 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1112 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1113 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1114 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1115 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1116 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1119 void
1120 eval_patch(origfile, difffile, outfile)
1121 char_u *origfile;
1122 char_u *difffile;
1123 char_u *outfile;
1125 int err;
1127 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1128 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1129 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1130 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1131 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1132 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1133 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1135 # endif
1138 * Top level evaluation function, returning a boolean.
1139 * Sets "error" to TRUE if there was an error.
1140 * Return TRUE or FALSE.
1143 eval_to_bool(arg, error, nextcmd, skip)
1144 char_u *arg;
1145 int *error;
1146 char_u **nextcmd;
1147 int skip; /* only parse, don't execute */
1149 typval_T tv;
1150 int retval = FALSE;
1152 if (skip)
1153 ++emsg_skip;
1154 if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1155 *error = TRUE;
1156 else
1158 *error = FALSE;
1159 if (!skip)
1161 retval = (get_tv_number_chk(&tv, error) != 0);
1162 clear_tv(&tv);
1165 if (skip)
1166 --emsg_skip;
1168 return retval;
1172 * Top level evaluation function, returning a string. If "skip" is TRUE,
1173 * only parsing to "nextcmd" is done, without reporting errors. Return
1174 * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1176 char_u *
1177 eval_to_string_skip(arg, nextcmd, skip)
1178 char_u *arg;
1179 char_u **nextcmd;
1180 int skip; /* only parse, don't execute */
1182 typval_T tv;
1183 char_u *retval;
1185 if (skip)
1186 ++emsg_skip;
1187 if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1188 retval = NULL;
1189 else
1191 retval = vim_strsave(get_tv_string(&tv));
1192 clear_tv(&tv);
1194 if (skip)
1195 --emsg_skip;
1197 return retval;
1201 * Skip over an expression at "*pp".
1202 * Return FAIL for an error, OK otherwise.
1205 skip_expr(pp)
1206 char_u **pp;
1208 typval_T rettv;
1210 *pp = skipwhite(*pp);
1211 return eval1(pp, &rettv, FALSE);
1215 * Top level evaluation function, returning a string.
1216 * Return pointer to allocated memory, or NULL for failure.
1218 char_u *
1219 eval_to_string(arg, nextcmd, dolist)
1220 char_u *arg;
1221 char_u **nextcmd;
1222 int dolist; /* turn List into sequence of lines */
1224 typval_T tv;
1225 char_u *retval;
1226 garray_T ga;
1228 if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1229 retval = NULL;
1230 else
1232 if (dolist && tv.v_type == VAR_LIST)
1234 ga_init2(&ga, (int)sizeof(char), 80);
1235 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1236 ga_append(&ga, NUL);
1237 retval = (char_u *)ga.ga_data;
1239 else
1240 retval = vim_strsave(get_tv_string(&tv));
1241 clear_tv(&tv);
1244 return retval;
1248 * Call eval_to_string() without using current local variables and using
1249 * textlock. When "use_sandbox" is TRUE use the sandbox.
1251 char_u *
1252 eval_to_string_safe(arg, nextcmd, use_sandbox)
1253 char_u *arg;
1254 char_u **nextcmd;
1255 int use_sandbox;
1257 char_u *retval;
1258 void *save_funccalp;
1260 save_funccalp = save_funccal();
1261 if (use_sandbox)
1262 ++sandbox;
1263 ++textlock;
1264 retval = eval_to_string(arg, nextcmd, FALSE);
1265 if (use_sandbox)
1266 --sandbox;
1267 --textlock;
1268 restore_funccal(save_funccalp);
1269 return retval;
1273 * Top level evaluation function, returning a number.
1274 * Evaluates "expr" silently.
1275 * Returns -1 for an error.
1278 eval_to_number(expr)
1279 char_u *expr;
1281 typval_T rettv;
1282 int retval;
1283 char_u *p = skipwhite(expr);
1285 ++emsg_off;
1287 if (eval1(&p, &rettv, TRUE) == FAIL)
1288 retval = -1;
1289 else
1291 retval = get_tv_number_chk(&rettv, NULL);
1292 clear_tv(&rettv);
1294 --emsg_off;
1296 return retval;
1300 * Prepare v: variable "idx" to be used.
1301 * Save the current typeval in "save_tv".
1302 * When not used yet add the variable to the v: hashtable.
1304 static void
1305 prepare_vimvar(idx, save_tv)
1306 int idx;
1307 typval_T *save_tv;
1309 *save_tv = vimvars[idx].vv_tv;
1310 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1311 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1315 * Restore v: variable "idx" to typeval "save_tv".
1316 * When no longer defined, remove the variable from the v: hashtable.
1318 static void
1319 restore_vimvar(idx, save_tv)
1320 int idx;
1321 typval_T *save_tv;
1323 hashitem_T *hi;
1325 vimvars[idx].vv_tv = *save_tv;
1326 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1328 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1329 if (HASHITEM_EMPTY(hi))
1330 EMSG2(_(e_intern2), "restore_vimvar()");
1331 else
1332 hash_remove(&vimvarht, hi);
1336 #if defined(FEAT_SPELL) || defined(PROTO)
1338 * Evaluate an expression to a list with suggestions.
1339 * For the "expr:" part of 'spellsuggest'.
1341 list_T *
1342 eval_spell_expr(badword, expr)
1343 char_u *badword;
1344 char_u *expr;
1346 typval_T save_val;
1347 typval_T rettv;
1348 list_T *list = NULL;
1349 char_u *p = skipwhite(expr);
1351 /* Set "v:val" to the bad word. */
1352 prepare_vimvar(VV_VAL, &save_val);
1353 vimvars[VV_VAL].vv_type = VAR_STRING;
1354 vimvars[VV_VAL].vv_str = badword;
1355 if (p_verbose == 0)
1356 ++emsg_off;
1358 if (eval1(&p, &rettv, TRUE) == OK)
1360 if (rettv.v_type != VAR_LIST)
1361 clear_tv(&rettv);
1362 else
1363 list = rettv.vval.v_list;
1366 if (p_verbose == 0)
1367 --emsg_off;
1368 restore_vimvar(VV_VAL, &save_val);
1370 return list;
1374 * "list" is supposed to contain two items: a word and a number. Return the
1375 * word in "pp" and the number as the return value.
1376 * Return -1 if anything isn't right.
1377 * Used to get the good word and score from the eval_spell_expr() result.
1380 get_spellword(list, pp)
1381 list_T *list;
1382 char_u **pp;
1384 listitem_T *li;
1386 li = list->lv_first;
1387 if (li == NULL)
1388 return -1;
1389 *pp = get_tv_string(&li->li_tv);
1391 li = li->li_next;
1392 if (li == NULL)
1393 return -1;
1394 return get_tv_number(&li->li_tv);
1396 #endif
1399 * Top level evaluation function.
1400 * Returns an allocated typval_T with the result.
1401 * Returns NULL when there is an error.
1403 typval_T *
1404 eval_expr(arg, nextcmd)
1405 char_u *arg;
1406 char_u **nextcmd;
1408 typval_T *tv;
1410 tv = (typval_T *)alloc(sizeof(typval_T));
1411 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1413 vim_free(tv);
1414 tv = NULL;
1417 return tv;
1421 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1422 || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1424 * Call some vimL function and return the result in "*rettv".
1425 * Uses argv[argc] for the function arguments.
1426 * Returns OK or FAIL.
1428 static int
1429 call_vim_function(func, argc, argv, safe, rettv)
1430 char_u *func;
1431 int argc;
1432 char_u **argv;
1433 int safe; /* use the sandbox */
1434 typval_T *rettv;
1436 typval_T *argvars;
1437 long n;
1438 int len;
1439 int i;
1440 int doesrange;
1441 void *save_funccalp = NULL;
1442 int ret;
1444 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1445 if (argvars == NULL)
1446 return FAIL;
1448 for (i = 0; i < argc; i++)
1450 /* Pass a NULL or empty argument as an empty string */
1451 if (argv[i] == NULL || *argv[i] == NUL)
1453 argvars[i].v_type = VAR_STRING;
1454 argvars[i].vval.v_string = (char_u *)"";
1455 continue;
1458 /* Recognize a number argument, the others must be strings. */
1459 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1460 if (len != 0 && len == (int)STRLEN(argv[i]))
1462 argvars[i].v_type = VAR_NUMBER;
1463 argvars[i].vval.v_number = n;
1465 else
1467 argvars[i].v_type = VAR_STRING;
1468 argvars[i].vval.v_string = argv[i];
1472 if (safe)
1474 save_funccalp = save_funccal();
1475 ++sandbox;
1478 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1479 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1480 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1481 &doesrange, TRUE, NULL);
1482 if (safe)
1484 --sandbox;
1485 restore_funccal(save_funccalp);
1487 vim_free(argvars);
1489 if (ret == FAIL)
1490 clear_tv(rettv);
1492 return ret;
1495 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1497 * Call vimL function "func" and return the result as a string.
1498 * Returns NULL when calling the function fails.
1499 * Uses argv[argc] for the function arguments.
1501 void *
1502 call_func_retstr(func, argc, argv, safe)
1503 char_u *func;
1504 int argc;
1505 char_u **argv;
1506 int safe; /* use the sandbox */
1508 typval_T rettv;
1509 char_u *retval;
1511 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1512 return NULL;
1514 retval = vim_strsave(get_tv_string(&rettv));
1515 clear_tv(&rettv);
1516 return retval;
1518 # endif
1520 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1522 * Call vimL function "func" and return the result as a number.
1523 * Returns -1 when calling the function fails.
1524 * Uses argv[argc] for the function arguments.
1526 long
1527 call_func_retnr(func, argc, argv, safe)
1528 char_u *func;
1529 int argc;
1530 char_u **argv;
1531 int safe; /* use the sandbox */
1533 typval_T rettv;
1534 long retval;
1536 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1537 return -1;
1539 retval = get_tv_number_chk(&rettv, NULL);
1540 clear_tv(&rettv);
1541 return retval;
1543 # endif
1546 * Call vimL function "func" and return the result as a list
1547 * Uses argv[argc] for the function arguments.
1549 void *
1550 call_func_retlist(func, argc, argv, safe)
1551 char_u *func;
1552 int argc;
1553 char_u **argv;
1554 int safe; /* use the sandbox */
1556 typval_T rettv;
1558 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1559 return NULL;
1561 if (rettv.v_type != VAR_LIST)
1563 clear_tv(&rettv);
1564 return NULL;
1567 return rettv.vval.v_list;
1569 #endif
1573 * Save the current function call pointer, and set it to NULL.
1574 * Used when executing autocommands and for ":source".
1576 void *
1577 save_funccal()
1579 funccall_T *fc = current_funccal;
1581 current_funccal = NULL;
1582 return (void *)fc;
1585 void
1586 restore_funccal(vfc)
1587 void *vfc;
1589 funccall_T *fc = (funccall_T *)vfc;
1591 current_funccal = fc;
1594 #if defined(FEAT_PROFILE) || defined(PROTO)
1596 * Prepare profiling for entering a child or something else that is not
1597 * counted for the script/function itself.
1598 * Should always be called in pair with prof_child_exit().
1600 void
1601 prof_child_enter(tm)
1602 proftime_T *tm; /* place to store waittime */
1604 funccall_T *fc = current_funccal;
1606 if (fc != NULL && fc->func->uf_profiling)
1607 profile_start(&fc->prof_child);
1608 script_prof_save(tm);
1612 * Take care of time spent in a child.
1613 * Should always be called after prof_child_enter().
1615 void
1616 prof_child_exit(tm)
1617 proftime_T *tm; /* where waittime was stored */
1619 funccall_T *fc = current_funccal;
1621 if (fc != NULL && fc->func->uf_profiling)
1623 profile_end(&fc->prof_child);
1624 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1625 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1626 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1628 script_prof_restore(tm);
1630 #endif
1633 #ifdef FEAT_FOLDING
1635 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1636 * it in "*cp". Doesn't give error messages.
1639 eval_foldexpr(arg, cp)
1640 char_u *arg;
1641 int *cp;
1643 typval_T tv;
1644 int retval;
1645 char_u *s;
1646 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1647 OPT_LOCAL);
1649 ++emsg_off;
1650 if (use_sandbox)
1651 ++sandbox;
1652 ++textlock;
1653 *cp = NUL;
1654 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1655 retval = 0;
1656 else
1658 /* If the result is a number, just return the number. */
1659 if (tv.v_type == VAR_NUMBER)
1660 retval = tv.vval.v_number;
1661 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1662 retval = 0;
1663 else
1665 /* If the result is a string, check if there is a non-digit before
1666 * the number. */
1667 s = tv.vval.v_string;
1668 if (!VIM_ISDIGIT(*s) && *s != '-')
1669 *cp = *s++;
1670 retval = atol((char *)s);
1672 clear_tv(&tv);
1674 --emsg_off;
1675 if (use_sandbox)
1676 --sandbox;
1677 --textlock;
1679 return retval;
1681 #endif
1684 * ":let" list all variable values
1685 * ":let var1 var2" list variable values
1686 * ":let var = expr" assignment command.
1687 * ":let var += expr" assignment command.
1688 * ":let var -= expr" assignment command.
1689 * ":let var .= expr" assignment command.
1690 * ":let [var1, var2] = expr" unpack list.
1692 void
1693 ex_let(eap)
1694 exarg_T *eap;
1696 char_u *arg = eap->arg;
1697 char_u *expr = NULL;
1698 typval_T rettv;
1699 int i;
1700 int var_count = 0;
1701 int semicolon = 0;
1702 char_u op[2];
1703 char_u *argend;
1704 int first = TRUE;
1706 argend = skip_var_list(arg, &var_count, &semicolon);
1707 if (argend == NULL)
1708 return;
1709 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1710 --argend;
1711 expr = vim_strchr(argend, '=');
1712 if (expr == NULL)
1715 * ":let" without "=": list variables
1717 if (*arg == '[')
1718 EMSG(_(e_invarg));
1719 else if (!ends_excmd(*arg))
1720 /* ":let var1 var2" */
1721 arg = list_arg_vars(eap, arg, &first);
1722 else if (!eap->skip)
1724 /* ":let" */
1725 list_glob_vars(&first);
1726 list_buf_vars(&first);
1727 list_win_vars(&first);
1728 #ifdef FEAT_WINDOWS
1729 list_tab_vars(&first);
1730 #endif
1731 list_script_vars(&first);
1732 list_func_vars(&first);
1733 list_vim_vars(&first);
1735 eap->nextcmd = check_nextcmd(arg);
1737 else
1739 op[0] = '=';
1740 op[1] = NUL;
1741 if (expr > argend)
1743 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1744 op[0] = expr[-1]; /* +=, -= or .= */
1746 expr = skipwhite(expr + 1);
1748 if (eap->skip)
1749 ++emsg_skip;
1750 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1751 if (eap->skip)
1753 if (i != FAIL)
1754 clear_tv(&rettv);
1755 --emsg_skip;
1757 else if (i != FAIL)
1759 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1760 op);
1761 clear_tv(&rettv);
1767 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1768 * Handles both "var" with any type and "[var, var; var]" with a list type.
1769 * When "nextchars" is not NULL it points to a string with characters that
1770 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1771 * or concatenate.
1772 * Returns OK or FAIL;
1774 static int
1775 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1776 char_u *arg_start;
1777 typval_T *tv;
1778 int copy; /* copy values from "tv", don't move */
1779 int semicolon; /* from skip_var_list() */
1780 int var_count; /* from skip_var_list() */
1781 char_u *nextchars;
1783 char_u *arg = arg_start;
1784 list_T *l;
1785 int i;
1786 listitem_T *item;
1787 typval_T ltv;
1789 if (*arg != '[')
1792 * ":let var = expr" or ":for var in list"
1794 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1795 return FAIL;
1796 return OK;
1800 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1802 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1804 EMSG(_(e_listreq));
1805 return FAIL;
1808 i = list_len(l);
1809 if (semicolon == 0 && var_count < i)
1811 EMSG(_("E687: Less targets than List items"));
1812 return FAIL;
1814 if (var_count - semicolon > i)
1816 EMSG(_("E688: More targets than List items"));
1817 return FAIL;
1820 item = l->lv_first;
1821 while (*arg != ']')
1823 arg = skipwhite(arg + 1);
1824 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1825 item = item->li_next;
1826 if (arg == NULL)
1827 return FAIL;
1829 arg = skipwhite(arg);
1830 if (*arg == ';')
1832 /* Put the rest of the list (may be empty) in the var after ';'.
1833 * Create a new list for this. */
1834 l = list_alloc();
1835 if (l == NULL)
1836 return FAIL;
1837 while (item != NULL)
1839 list_append_tv(l, &item->li_tv);
1840 item = item->li_next;
1843 ltv.v_type = VAR_LIST;
1844 ltv.v_lock = 0;
1845 ltv.vval.v_list = l;
1846 l->lv_refcount = 1;
1848 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1849 (char_u *)"]", nextchars);
1850 clear_tv(&ltv);
1851 if (arg == NULL)
1852 return FAIL;
1853 break;
1855 else if (*arg != ',' && *arg != ']')
1857 EMSG2(_(e_intern2), "ex_let_vars()");
1858 return FAIL;
1862 return OK;
1866 * Skip over assignable variable "var" or list of variables "[var, var]".
1867 * Used for ":let varvar = expr" and ":for varvar in expr".
1868 * For "[var, var]" increment "*var_count" for each variable.
1869 * for "[var, var; var]" set "semicolon".
1870 * Return NULL for an error.
1872 static char_u *
1873 skip_var_list(arg, var_count, semicolon)
1874 char_u *arg;
1875 int *var_count;
1876 int *semicolon;
1878 char_u *p, *s;
1880 if (*arg == '[')
1882 /* "[var, var]": find the matching ']'. */
1883 p = arg;
1884 for (;;)
1886 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
1887 s = skip_var_one(p);
1888 if (s == p)
1890 EMSG2(_(e_invarg2), p);
1891 return NULL;
1893 ++*var_count;
1895 p = skipwhite(s);
1896 if (*p == ']')
1897 break;
1898 else if (*p == ';')
1900 if (*semicolon == 1)
1902 EMSG(_("Double ; in list of variables"));
1903 return NULL;
1905 *semicolon = 1;
1907 else if (*p != ',')
1909 EMSG2(_(e_invarg2), p);
1910 return NULL;
1913 return p + 1;
1915 else
1916 return skip_var_one(arg);
1920 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
1921 * l[idx].
1923 static char_u *
1924 skip_var_one(arg)
1925 char_u *arg;
1927 if (*arg == '@' && arg[1] != NUL)
1928 return arg + 2;
1929 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
1930 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1934 * List variables for hashtab "ht" with prefix "prefix".
1935 * If "empty" is TRUE also list NULL strings as empty strings.
1937 static void
1938 list_hashtable_vars(ht, prefix, empty, first)
1939 hashtab_T *ht;
1940 char_u *prefix;
1941 int empty;
1942 int *first;
1944 hashitem_T *hi;
1945 dictitem_T *di;
1946 int todo;
1948 todo = (int)ht->ht_used;
1949 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
1951 if (!HASHITEM_EMPTY(hi))
1953 --todo;
1954 di = HI2DI(hi);
1955 if (empty || di->di_tv.v_type != VAR_STRING
1956 || di->di_tv.vval.v_string != NULL)
1957 list_one_var(di, prefix, first);
1963 * List global variables.
1965 static void
1966 list_glob_vars(first)
1967 int *first;
1969 list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
1973 * List buffer variables.
1975 static void
1976 list_buf_vars(first)
1977 int *first;
1979 char_u numbuf[NUMBUFLEN];
1981 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:",
1982 TRUE, first);
1984 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
1985 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
1986 numbuf, first);
1990 * List window variables.
1992 static void
1993 list_win_vars(first)
1994 int *first;
1996 list_hashtable_vars(&curwin->w_vars.dv_hashtab,
1997 (char_u *)"w:", TRUE, first);
2000 #ifdef FEAT_WINDOWS
2002 * List tab page variables.
2004 static void
2005 list_tab_vars(first)
2006 int *first;
2008 list_hashtable_vars(&curtab->tp_vars.dv_hashtab,
2009 (char_u *)"t:", TRUE, first);
2011 #endif
2014 * List Vim variables.
2016 static void
2017 list_vim_vars(first)
2018 int *first;
2020 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2024 * List script-local variables, if there is a script.
2026 static void
2027 list_script_vars(first)
2028 int *first;
2030 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2031 list_hashtable_vars(&SCRIPT_VARS(current_SID),
2032 (char_u *)"s:", FALSE, first);
2036 * List function variables, if there is a function.
2038 static void
2039 list_func_vars(first)
2040 int *first;
2042 if (current_funccal != NULL)
2043 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2044 (char_u *)"l:", FALSE, first);
2048 * List variables in "arg".
2050 static char_u *
2051 list_arg_vars(eap, arg, first)
2052 exarg_T *eap;
2053 char_u *arg;
2054 int *first;
2056 int error = FALSE;
2057 int len;
2058 char_u *name;
2059 char_u *name_start;
2060 char_u *arg_subsc;
2061 char_u *tofree;
2062 typval_T tv;
2064 while (!ends_excmd(*arg) && !got_int)
2066 if (error || eap->skip)
2068 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2069 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2071 emsg_severe = TRUE;
2072 EMSG(_(e_trailing));
2073 break;
2076 else
2078 /* get_name_len() takes care of expanding curly braces */
2079 name_start = name = arg;
2080 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2081 if (len <= 0)
2083 /* This is mainly to keep test 49 working: when expanding
2084 * curly braces fails overrule the exception error message. */
2085 if (len < 0 && !aborting())
2087 emsg_severe = TRUE;
2088 EMSG2(_(e_invarg2), arg);
2089 break;
2091 error = TRUE;
2093 else
2095 if (tofree != NULL)
2096 name = tofree;
2097 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2098 error = TRUE;
2099 else
2101 /* handle d.key, l[idx], f(expr) */
2102 arg_subsc = arg;
2103 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2104 error = TRUE;
2105 else
2107 if (arg == arg_subsc && len == 2 && name[1] == ':')
2109 switch (*name)
2111 case 'g': list_glob_vars(first); break;
2112 case 'b': list_buf_vars(first); break;
2113 case 'w': list_win_vars(first); break;
2114 #ifdef FEAT_WINDOWS
2115 case 't': list_tab_vars(first); break;
2116 #endif
2117 case 'v': list_vim_vars(first); break;
2118 case 's': list_script_vars(first); break;
2119 case 'l': list_func_vars(first); break;
2120 default:
2121 EMSG2(_("E738: Can't list variables for %s"), name);
2124 else
2126 char_u numbuf[NUMBUFLEN];
2127 char_u *tf;
2128 int c;
2129 char_u *s;
2131 s = echo_string(&tv, &tf, numbuf, 0);
2132 c = *arg;
2133 *arg = NUL;
2134 list_one_var_a((char_u *)"",
2135 arg == arg_subsc ? name : name_start,
2136 tv.v_type,
2137 s == NULL ? (char_u *)"" : s,
2138 first);
2139 *arg = c;
2140 vim_free(tf);
2142 clear_tv(&tv);
2147 vim_free(tofree);
2150 arg = skipwhite(arg);
2153 return arg;
2157 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2158 * Returns a pointer to the char just after the var name.
2159 * Returns NULL if there is an error.
2161 static char_u *
2162 ex_let_one(arg, tv, copy, endchars, op)
2163 char_u *arg; /* points to variable name */
2164 typval_T *tv; /* value to assign to variable */
2165 int copy; /* copy value from "tv" */
2166 char_u *endchars; /* valid chars after variable name or NULL */
2167 char_u *op; /* "+", "-", "." or NULL*/
2169 int c1;
2170 char_u *name;
2171 char_u *p;
2172 char_u *arg_end = NULL;
2173 int len;
2174 int opt_flags;
2175 char_u *tofree = NULL;
2178 * ":let $VAR = expr": Set environment variable.
2180 if (*arg == '$')
2182 /* Find the end of the name. */
2183 ++arg;
2184 name = arg;
2185 len = get_env_len(&arg);
2186 if (len == 0)
2187 EMSG2(_(e_invarg2), name - 1);
2188 else
2190 if (op != NULL && (*op == '+' || *op == '-'))
2191 EMSG2(_(e_letwrong), op);
2192 else if (endchars != NULL
2193 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2194 EMSG(_(e_letunexp));
2195 else
2197 c1 = name[len];
2198 name[len] = NUL;
2199 p = get_tv_string_chk(tv);
2200 if (p != NULL && op != NULL && *op == '.')
2202 int mustfree = FALSE;
2203 char_u *s = vim_getenv(name, &mustfree);
2205 if (s != NULL)
2207 p = tofree = concat_str(s, p);
2208 if (mustfree)
2209 vim_free(s);
2212 if (p != NULL)
2214 vim_setenv(name, p);
2215 if (STRICMP(name, "HOME") == 0)
2216 init_homedir();
2217 else if (didset_vim && STRICMP(name, "VIM") == 0)
2218 didset_vim = FALSE;
2219 else if (didset_vimruntime
2220 && STRICMP(name, "VIMRUNTIME") == 0)
2221 didset_vimruntime = FALSE;
2222 arg_end = arg;
2224 name[len] = c1;
2225 vim_free(tofree);
2231 * ":let &option = expr": Set option value.
2232 * ":let &l:option = expr": Set local option value.
2233 * ":let &g:option = expr": Set global option value.
2235 else if (*arg == '&')
2237 /* Find the end of the name. */
2238 p = find_option_end(&arg, &opt_flags);
2239 if (p == NULL || (endchars != NULL
2240 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2241 EMSG(_(e_letunexp));
2242 else
2244 long n;
2245 int opt_type;
2246 long numval;
2247 char_u *stringval = NULL;
2248 char_u *s;
2250 c1 = *p;
2251 *p = NUL;
2253 n = get_tv_number(tv);
2254 s = get_tv_string_chk(tv); /* != NULL if number or string */
2255 if (s != NULL && op != NULL && *op != '=')
2257 opt_type = get_option_value(arg, &numval,
2258 &stringval, opt_flags);
2259 if ((opt_type == 1 && *op == '.')
2260 || (opt_type == 0 && *op != '.'))
2261 EMSG2(_(e_letwrong), op);
2262 else
2264 if (opt_type == 1) /* number */
2266 if (*op == '+')
2267 n = numval + n;
2268 else
2269 n = numval - n;
2271 else if (opt_type == 0 && stringval != NULL) /* string */
2273 s = concat_str(stringval, s);
2274 vim_free(stringval);
2275 stringval = s;
2279 if (s != NULL)
2281 set_option_value(arg, n, s, opt_flags);
2282 arg_end = p;
2284 *p = c1;
2285 vim_free(stringval);
2290 * ":let @r = expr": Set register contents.
2292 else if (*arg == '@')
2294 ++arg;
2295 if (op != NULL && (*op == '+' || *op == '-'))
2296 EMSG2(_(e_letwrong), op);
2297 else if (endchars != NULL
2298 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2299 EMSG(_(e_letunexp));
2300 else
2302 char_u *ptofree = NULL;
2303 char_u *s;
2305 p = get_tv_string_chk(tv);
2306 if (p != NULL && op != NULL && *op == '.')
2308 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2309 if (s != NULL)
2311 p = ptofree = concat_str(s, p);
2312 vim_free(s);
2315 if (p != NULL)
2317 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2318 arg_end = arg + 1;
2320 vim_free(ptofree);
2325 * ":let var = expr": Set internal variable.
2326 * ":let {expr} = expr": Idem, name made with curly braces
2328 else if (eval_isnamec1(*arg) || *arg == '{')
2330 lval_T lv;
2332 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2333 if (p != NULL && lv.ll_name != NULL)
2335 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2336 EMSG(_(e_letunexp));
2337 else
2339 set_var_lval(&lv, p, tv, copy, op);
2340 arg_end = p;
2343 clear_lval(&lv);
2346 else
2347 EMSG2(_(e_invarg2), arg);
2349 return arg_end;
2353 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2355 static int
2356 check_changedtick(arg)
2357 char_u *arg;
2359 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2361 EMSG2(_(e_readonlyvar), arg);
2362 return TRUE;
2364 return FALSE;
2368 * Get an lval: variable, Dict item or List item that can be assigned a value
2369 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2370 * "name.key", "name.key[expr]" etc.
2371 * Indexing only works if "name" is an existing List or Dictionary.
2372 * "name" points to the start of the name.
2373 * If "rettv" is not NULL it points to the value to be assigned.
2374 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2375 * wrong; must end in space or cmd separator.
2377 * Returns a pointer to just after the name, including indexes.
2378 * When an evaluation error occurs "lp->ll_name" is NULL;
2379 * Returns NULL for a parsing error. Still need to free items in "lp"!
2381 static char_u *
2382 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2383 char_u *name;
2384 typval_T *rettv;
2385 lval_T *lp;
2386 int unlet;
2387 int skip;
2388 int quiet; /* don't give error messages */
2389 int fne_flags; /* flags for find_name_end() */
2391 char_u *p;
2392 char_u *expr_start, *expr_end;
2393 int cc;
2394 dictitem_T *v;
2395 typval_T var1;
2396 typval_T var2;
2397 int empty1 = FALSE;
2398 listitem_T *ni;
2399 char_u *key = NULL;
2400 int len;
2401 hashtab_T *ht;
2403 /* Clear everything in "lp". */
2404 vim_memset(lp, 0, sizeof(lval_T));
2406 if (skip)
2408 /* When skipping just find the end of the name. */
2409 lp->ll_name = name;
2410 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2413 /* Find the end of the name. */
2414 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2415 if (expr_start != NULL)
2417 /* Don't expand the name when we already know there is an error. */
2418 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2419 && *p != '[' && *p != '.')
2421 EMSG(_(e_trailing));
2422 return NULL;
2425 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2426 if (lp->ll_exp_name == NULL)
2428 /* Report an invalid expression in braces, unless the
2429 * expression evaluation has been cancelled due to an
2430 * aborting error, an interrupt, or an exception. */
2431 if (!aborting() && !quiet)
2433 emsg_severe = TRUE;
2434 EMSG2(_(e_invarg2), name);
2435 return NULL;
2438 lp->ll_name = lp->ll_exp_name;
2440 else
2441 lp->ll_name = name;
2443 /* Without [idx] or .key we are done. */
2444 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2445 return p;
2447 cc = *p;
2448 *p = NUL;
2449 v = find_var(lp->ll_name, &ht);
2450 if (v == NULL && !quiet)
2451 EMSG2(_(e_undefvar), lp->ll_name);
2452 *p = cc;
2453 if (v == NULL)
2454 return NULL;
2457 * Loop until no more [idx] or .key is following.
2459 lp->ll_tv = &v->di_tv;
2460 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2462 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2463 && !(lp->ll_tv->v_type == VAR_DICT
2464 && lp->ll_tv->vval.v_dict != NULL))
2466 if (!quiet)
2467 EMSG(_("E689: Can only index a List or Dictionary"));
2468 return NULL;
2470 if (lp->ll_range)
2472 if (!quiet)
2473 EMSG(_("E708: [:] must come last"));
2474 return NULL;
2477 len = -1;
2478 if (*p == '.')
2480 key = p + 1;
2481 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2483 if (len == 0)
2485 if (!quiet)
2486 EMSG(_(e_emptykey));
2487 return NULL;
2489 p = key + len;
2491 else
2493 /* Get the index [expr] or the first index [expr: ]. */
2494 p = skipwhite(p + 1);
2495 if (*p == ':')
2496 empty1 = TRUE;
2497 else
2499 empty1 = FALSE;
2500 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2501 return NULL;
2502 if (get_tv_string_chk(&var1) == NULL)
2504 /* not a number or string */
2505 clear_tv(&var1);
2506 return NULL;
2510 /* Optionally get the second index [ :expr]. */
2511 if (*p == ':')
2513 if (lp->ll_tv->v_type == VAR_DICT)
2515 if (!quiet)
2516 EMSG(_(e_dictrange));
2517 if (!empty1)
2518 clear_tv(&var1);
2519 return NULL;
2521 if (rettv != NULL && (rettv->v_type != VAR_LIST
2522 || rettv->vval.v_list == NULL))
2524 if (!quiet)
2525 EMSG(_("E709: [:] requires a List value"));
2526 if (!empty1)
2527 clear_tv(&var1);
2528 return NULL;
2530 p = skipwhite(p + 1);
2531 if (*p == ']')
2532 lp->ll_empty2 = TRUE;
2533 else
2535 lp->ll_empty2 = FALSE;
2536 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2538 if (!empty1)
2539 clear_tv(&var1);
2540 return NULL;
2542 if (get_tv_string_chk(&var2) == NULL)
2544 /* not a number or string */
2545 if (!empty1)
2546 clear_tv(&var1);
2547 clear_tv(&var2);
2548 return NULL;
2551 lp->ll_range = TRUE;
2553 else
2554 lp->ll_range = FALSE;
2556 if (*p != ']')
2558 if (!quiet)
2559 EMSG(_(e_missbrac));
2560 if (!empty1)
2561 clear_tv(&var1);
2562 if (lp->ll_range && !lp->ll_empty2)
2563 clear_tv(&var2);
2564 return NULL;
2567 /* Skip to past ']'. */
2568 ++p;
2571 if (lp->ll_tv->v_type == VAR_DICT)
2573 if (len == -1)
2575 /* "[key]": get key from "var1" */
2576 key = get_tv_string(&var1); /* is number or string */
2577 if (*key == NUL)
2579 if (!quiet)
2580 EMSG(_(e_emptykey));
2581 clear_tv(&var1);
2582 return NULL;
2585 lp->ll_list = NULL;
2586 lp->ll_dict = lp->ll_tv->vval.v_dict;
2587 lp->ll_di = dict_find(lp->ll_dict, key, len);
2588 if (lp->ll_di == NULL)
2590 /* Key does not exist in dict: may need to add it. */
2591 if (*p == '[' || *p == '.' || unlet)
2593 if (!quiet)
2594 EMSG2(_(e_dictkey), key);
2595 if (len == -1)
2596 clear_tv(&var1);
2597 return NULL;
2599 if (len == -1)
2600 lp->ll_newkey = vim_strsave(key);
2601 else
2602 lp->ll_newkey = vim_strnsave(key, len);
2603 if (len == -1)
2604 clear_tv(&var1);
2605 if (lp->ll_newkey == NULL)
2606 p = NULL;
2607 break;
2609 if (len == -1)
2610 clear_tv(&var1);
2611 lp->ll_tv = &lp->ll_di->di_tv;
2613 else
2616 * Get the number and item for the only or first index of the List.
2618 if (empty1)
2619 lp->ll_n1 = 0;
2620 else
2622 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2623 clear_tv(&var1);
2625 lp->ll_dict = NULL;
2626 lp->ll_list = lp->ll_tv->vval.v_list;
2627 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2628 if (lp->ll_li == NULL)
2630 if (lp->ll_n1 < 0)
2632 lp->ll_n1 = 0;
2633 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2636 if (lp->ll_li == NULL)
2638 if (lp->ll_range && !lp->ll_empty2)
2639 clear_tv(&var2);
2640 return NULL;
2644 * May need to find the item or absolute index for the second
2645 * index of a range.
2646 * When no index given: "lp->ll_empty2" is TRUE.
2647 * Otherwise "lp->ll_n2" is set to the second index.
2649 if (lp->ll_range && !lp->ll_empty2)
2651 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2652 clear_tv(&var2);
2653 if (lp->ll_n2 < 0)
2655 ni = list_find(lp->ll_list, lp->ll_n2);
2656 if (ni == NULL)
2657 return NULL;
2658 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2661 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2662 if (lp->ll_n1 < 0)
2663 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2664 if (lp->ll_n2 < lp->ll_n1)
2665 return NULL;
2668 lp->ll_tv = &lp->ll_li->li_tv;
2672 return p;
2676 * Clear lval "lp" that was filled by get_lval().
2678 static void
2679 clear_lval(lp)
2680 lval_T *lp;
2682 vim_free(lp->ll_exp_name);
2683 vim_free(lp->ll_newkey);
2687 * Set a variable that was parsed by get_lval() to "rettv".
2688 * "endp" points to just after the parsed name.
2689 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2691 static void
2692 set_var_lval(lp, endp, rettv, copy, op)
2693 lval_T *lp;
2694 char_u *endp;
2695 typval_T *rettv;
2696 int copy;
2697 char_u *op;
2699 int cc;
2700 listitem_T *ri;
2701 dictitem_T *di;
2703 if (lp->ll_tv == NULL)
2705 if (!check_changedtick(lp->ll_name))
2707 cc = *endp;
2708 *endp = NUL;
2709 if (op != NULL && *op != '=')
2711 typval_T tv;
2713 /* handle +=, -= and .= */
2714 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2715 &tv, TRUE) == OK)
2717 if (tv_op(&tv, rettv, op) == OK)
2718 set_var(lp->ll_name, &tv, FALSE);
2719 clear_tv(&tv);
2722 else
2723 set_var(lp->ll_name, rettv, copy);
2724 *endp = cc;
2727 else if (tv_check_lock(lp->ll_newkey == NULL
2728 ? lp->ll_tv->v_lock
2729 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2731 else if (lp->ll_range)
2734 * Assign the List values to the list items.
2736 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2738 if (op != NULL && *op != '=')
2739 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2740 else
2742 clear_tv(&lp->ll_li->li_tv);
2743 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2745 ri = ri->li_next;
2746 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2747 break;
2748 if (lp->ll_li->li_next == NULL)
2750 /* Need to add an empty item. */
2751 if (list_append_number(lp->ll_list, 0) == FAIL)
2753 ri = NULL;
2754 break;
2757 lp->ll_li = lp->ll_li->li_next;
2758 ++lp->ll_n1;
2760 if (ri != NULL)
2761 EMSG(_("E710: List value has more items than target"));
2762 else if (lp->ll_empty2
2763 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2764 : lp->ll_n1 != lp->ll_n2)
2765 EMSG(_("E711: List value has not enough items"));
2767 else
2770 * Assign to a List or Dictionary item.
2772 if (lp->ll_newkey != NULL)
2774 if (op != NULL && *op != '=')
2776 EMSG2(_(e_letwrong), op);
2777 return;
2780 /* Need to add an item to the Dictionary. */
2781 di = dictitem_alloc(lp->ll_newkey);
2782 if (di == NULL)
2783 return;
2784 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2786 vim_free(di);
2787 return;
2789 lp->ll_tv = &di->di_tv;
2791 else if (op != NULL && *op != '=')
2793 tv_op(lp->ll_tv, rettv, op);
2794 return;
2796 else
2797 clear_tv(lp->ll_tv);
2800 * Assign the value to the variable or list item.
2802 if (copy)
2803 copy_tv(rettv, lp->ll_tv);
2804 else
2806 *lp->ll_tv = *rettv;
2807 lp->ll_tv->v_lock = 0;
2808 init_tv(rettv);
2814 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2815 * Returns OK or FAIL.
2817 static int
2818 tv_op(tv1, tv2, op)
2819 typval_T *tv1;
2820 typval_T *tv2;
2821 char_u *op;
2823 long n;
2824 char_u numbuf[NUMBUFLEN];
2825 char_u *s;
2827 /* Can't do anything with a Funcref or a Dict on the right. */
2828 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2830 switch (tv1->v_type)
2832 case VAR_DICT:
2833 case VAR_FUNC:
2834 break;
2836 case VAR_LIST:
2837 if (*op != '+' || tv2->v_type != VAR_LIST)
2838 break;
2839 /* List += List */
2840 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2841 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2842 return OK;
2844 case VAR_NUMBER:
2845 case VAR_STRING:
2846 if (tv2->v_type == VAR_LIST)
2847 break;
2848 if (*op == '+' || *op == '-')
2850 /* nr += nr or nr -= nr*/
2851 n = get_tv_number(tv1);
2852 if (*op == '+')
2853 n += get_tv_number(tv2);
2854 else
2855 n -= get_tv_number(tv2);
2856 clear_tv(tv1);
2857 tv1->v_type = VAR_NUMBER;
2858 tv1->vval.v_number = n;
2860 else
2862 /* str .= str */
2863 s = get_tv_string(tv1);
2864 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2865 clear_tv(tv1);
2866 tv1->v_type = VAR_STRING;
2867 tv1->vval.v_string = s;
2869 return OK;
2873 EMSG2(_(e_letwrong), op);
2874 return FAIL;
2878 * Add a watcher to a list.
2880 static void
2881 list_add_watch(l, lw)
2882 list_T *l;
2883 listwatch_T *lw;
2885 lw->lw_next = l->lv_watch;
2886 l->lv_watch = lw;
2890 * Remove a watcher from a list.
2891 * No warning when it isn't found...
2893 static void
2894 list_rem_watch(l, lwrem)
2895 list_T *l;
2896 listwatch_T *lwrem;
2898 listwatch_T *lw, **lwp;
2900 lwp = &l->lv_watch;
2901 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2903 if (lw == lwrem)
2905 *lwp = lw->lw_next;
2906 break;
2908 lwp = &lw->lw_next;
2913 * Just before removing an item from a list: advance watchers to the next
2914 * item.
2916 static void
2917 list_fix_watch(l, item)
2918 list_T *l;
2919 listitem_T *item;
2921 listwatch_T *lw;
2923 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2924 if (lw->lw_item == item)
2925 lw->lw_item = item->li_next;
2929 * Evaluate the expression used in a ":for var in expr" command.
2930 * "arg" points to "var".
2931 * Set "*errp" to TRUE for an error, FALSE otherwise;
2932 * Return a pointer that holds the info. Null when there is an error.
2934 void *
2935 eval_for_line(arg, errp, nextcmdp, skip)
2936 char_u *arg;
2937 int *errp;
2938 char_u **nextcmdp;
2939 int skip;
2941 forinfo_T *fi;
2942 char_u *expr;
2943 typval_T tv;
2944 list_T *l;
2946 *errp = TRUE; /* default: there is an error */
2948 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
2949 if (fi == NULL)
2950 return NULL;
2952 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
2953 if (expr == NULL)
2954 return fi;
2956 expr = skipwhite(expr);
2957 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
2959 EMSG(_("E690: Missing \"in\" after :for"));
2960 return fi;
2963 if (skip)
2964 ++emsg_skip;
2965 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
2967 *errp = FALSE;
2968 if (!skip)
2970 l = tv.vval.v_list;
2971 if (tv.v_type != VAR_LIST || l == NULL)
2973 EMSG(_(e_listreq));
2974 clear_tv(&tv);
2976 else
2978 /* No need to increment the refcount, it's already set for the
2979 * list being used in "tv". */
2980 fi->fi_list = l;
2981 list_add_watch(l, &fi->fi_lw);
2982 fi->fi_lw.lw_item = l->lv_first;
2986 if (skip)
2987 --emsg_skip;
2989 return fi;
2993 * Use the first item in a ":for" list. Advance to the next.
2994 * Assign the values to the variable (list). "arg" points to the first one.
2995 * Return TRUE when a valid item was found, FALSE when at end of list or
2996 * something wrong.
2999 next_for_item(fi_void, arg)
3000 void *fi_void;
3001 char_u *arg;
3003 forinfo_T *fi = (forinfo_T *)fi_void;
3004 int result;
3005 listitem_T *item;
3007 item = fi->fi_lw.lw_item;
3008 if (item == NULL)
3009 result = FALSE;
3010 else
3012 fi->fi_lw.lw_item = item->li_next;
3013 result = (ex_let_vars(arg, &item->li_tv, TRUE,
3014 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3016 return result;
3020 * Free the structure used to store info used by ":for".
3022 void
3023 free_for_info(fi_void)
3024 void *fi_void;
3026 forinfo_T *fi = (forinfo_T *)fi_void;
3028 if (fi != NULL && fi->fi_list != NULL)
3030 list_rem_watch(fi->fi_list, &fi->fi_lw);
3031 list_unref(fi->fi_list);
3033 vim_free(fi);
3036 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3038 void
3039 set_context_for_expression(xp, arg, cmdidx)
3040 expand_T *xp;
3041 char_u *arg;
3042 cmdidx_T cmdidx;
3044 int got_eq = FALSE;
3045 int c;
3046 char_u *p;
3048 if (cmdidx == CMD_let)
3050 xp->xp_context = EXPAND_USER_VARS;
3051 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3053 /* ":let var1 var2 ...": find last space. */
3054 for (p = arg + STRLEN(arg); p >= arg; )
3056 xp->xp_pattern = p;
3057 mb_ptr_back(arg, p);
3058 if (vim_iswhite(*p))
3059 break;
3061 return;
3064 else
3065 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3066 : EXPAND_EXPRESSION;
3067 while ((xp->xp_pattern = vim_strpbrk(arg,
3068 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3070 c = *xp->xp_pattern;
3071 if (c == '&')
3073 c = xp->xp_pattern[1];
3074 if (c == '&')
3076 ++xp->xp_pattern;
3077 xp->xp_context = cmdidx != CMD_let || got_eq
3078 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3080 else if (c != ' ')
3082 xp->xp_context = EXPAND_SETTINGS;
3083 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3084 xp->xp_pattern += 2;
3088 else if (c == '$')
3090 /* environment variable */
3091 xp->xp_context = EXPAND_ENV_VARS;
3093 else if (c == '=')
3095 got_eq = TRUE;
3096 xp->xp_context = EXPAND_EXPRESSION;
3098 else if (c == '<'
3099 && xp->xp_context == EXPAND_FUNCTIONS
3100 && vim_strchr(xp->xp_pattern, '(') == NULL)
3102 /* Function name can start with "<SNR>" */
3103 break;
3105 else if (cmdidx != CMD_let || got_eq)
3107 if (c == '"') /* string */
3109 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3110 if (c == '\\' && xp->xp_pattern[1] != NUL)
3111 ++xp->xp_pattern;
3112 xp->xp_context = EXPAND_NOTHING;
3114 else if (c == '\'') /* literal string */
3116 /* Trick: '' is like stopping and starting a literal string. */
3117 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3118 /* skip */ ;
3119 xp->xp_context = EXPAND_NOTHING;
3121 else if (c == '|')
3123 if (xp->xp_pattern[1] == '|')
3125 ++xp->xp_pattern;
3126 xp->xp_context = EXPAND_EXPRESSION;
3128 else
3129 xp->xp_context = EXPAND_COMMANDS;
3131 else
3132 xp->xp_context = EXPAND_EXPRESSION;
3134 else
3135 /* Doesn't look like something valid, expand as an expression
3136 * anyway. */
3137 xp->xp_context = EXPAND_EXPRESSION;
3138 arg = xp->xp_pattern;
3139 if (*arg != NUL)
3140 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3141 /* skip */ ;
3143 xp->xp_pattern = arg;
3146 #endif /* FEAT_CMDL_COMPL */
3149 * ":1,25call func(arg1, arg2)" function call.
3151 void
3152 ex_call(eap)
3153 exarg_T *eap;
3155 char_u *arg = eap->arg;
3156 char_u *startarg;
3157 char_u *name;
3158 char_u *tofree;
3159 int len;
3160 typval_T rettv;
3161 linenr_T lnum;
3162 int doesrange;
3163 int failed = FALSE;
3164 funcdict_T fudi;
3166 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3167 if (fudi.fd_newkey != NULL)
3169 /* Still need to give an error message for missing key. */
3170 EMSG2(_(e_dictkey), fudi.fd_newkey);
3171 vim_free(fudi.fd_newkey);
3173 if (tofree == NULL)
3174 return;
3176 /* Increase refcount on dictionary, it could get deleted when evaluating
3177 * the arguments. */
3178 if (fudi.fd_dict != NULL)
3179 ++fudi.fd_dict->dv_refcount;
3181 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3182 len = (int)STRLEN(tofree);
3183 name = deref_func_name(tofree, &len);
3185 /* Skip white space to allow ":call func ()". Not good, but required for
3186 * backward compatibility. */
3187 startarg = skipwhite(arg);
3188 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3190 if (*startarg != '(')
3192 EMSG2(_("E107: Missing braces: %s"), eap->arg);
3193 goto end;
3197 * When skipping, evaluate the function once, to find the end of the
3198 * arguments.
3199 * When the function takes a range, this is discovered after the first
3200 * call, and the loop is broken.
3202 if (eap->skip)
3204 ++emsg_skip;
3205 lnum = eap->line2; /* do it once, also with an invalid range */
3207 else
3208 lnum = eap->line1;
3209 for ( ; lnum <= eap->line2; ++lnum)
3211 if (!eap->skip && eap->addr_count > 0)
3213 curwin->w_cursor.lnum = lnum;
3214 curwin->w_cursor.col = 0;
3216 arg = startarg;
3217 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3218 eap->line1, eap->line2, &doesrange,
3219 !eap->skip, fudi.fd_dict) == FAIL)
3221 failed = TRUE;
3222 break;
3225 /* Handle a function returning a Funcref, Dictionary or List. */
3226 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3228 failed = TRUE;
3229 break;
3232 clear_tv(&rettv);
3233 if (doesrange || eap->skip)
3234 break;
3236 /* Stop when immediately aborting on error, or when an interrupt
3237 * occurred or an exception was thrown but not caught.
3238 * get_func_tv() returned OK, so that the check for trailing
3239 * characters below is executed. */
3240 if (aborting())
3241 break;
3243 if (eap->skip)
3244 --emsg_skip;
3246 if (!failed)
3248 /* Check for trailing illegal characters and a following command. */
3249 if (!ends_excmd(*arg))
3251 emsg_severe = TRUE;
3252 EMSG(_(e_trailing));
3254 else
3255 eap->nextcmd = check_nextcmd(arg);
3258 end:
3259 dict_unref(fudi.fd_dict);
3260 vim_free(tofree);
3264 * ":unlet[!] var1 ... " command.
3266 void
3267 ex_unlet(eap)
3268 exarg_T *eap;
3270 ex_unletlock(eap, eap->arg, 0);
3274 * ":lockvar" and ":unlockvar" commands
3276 void
3277 ex_lockvar(eap)
3278 exarg_T *eap;
3280 char_u *arg = eap->arg;
3281 int deep = 2;
3283 if (eap->forceit)
3284 deep = -1;
3285 else if (vim_isdigit(*arg))
3287 deep = getdigits(&arg);
3288 arg = skipwhite(arg);
3291 ex_unletlock(eap, arg, deep);
3295 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3297 static void
3298 ex_unletlock(eap, argstart, deep)
3299 exarg_T *eap;
3300 char_u *argstart;
3301 int deep;
3303 char_u *arg = argstart;
3304 char_u *name_end;
3305 int error = FALSE;
3306 lval_T lv;
3310 /* Parse the name and find the end. */
3311 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3312 FNE_CHECK_START);
3313 if (lv.ll_name == NULL)
3314 error = TRUE; /* error but continue parsing */
3315 if (name_end == NULL || (!vim_iswhite(*name_end)
3316 && !ends_excmd(*name_end)))
3318 if (name_end != NULL)
3320 emsg_severe = TRUE;
3321 EMSG(_(e_trailing));
3323 if (!(eap->skip || error))
3324 clear_lval(&lv);
3325 break;
3328 if (!error && !eap->skip)
3330 if (eap->cmdidx == CMD_unlet)
3332 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3333 error = TRUE;
3335 else
3337 if (do_lock_var(&lv, name_end, deep,
3338 eap->cmdidx == CMD_lockvar) == FAIL)
3339 error = TRUE;
3343 if (!eap->skip)
3344 clear_lval(&lv);
3346 arg = skipwhite(name_end);
3347 } while (!ends_excmd(*arg));
3349 eap->nextcmd = check_nextcmd(arg);
3352 static int
3353 do_unlet_var(lp, name_end, forceit)
3354 lval_T *lp;
3355 char_u *name_end;
3356 int forceit;
3358 int ret = OK;
3359 int cc;
3361 if (lp->ll_tv == NULL)
3363 cc = *name_end;
3364 *name_end = NUL;
3366 /* Normal name or expanded name. */
3367 if (check_changedtick(lp->ll_name))
3368 ret = FAIL;
3369 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3370 ret = FAIL;
3371 *name_end = cc;
3373 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3374 return FAIL;
3375 else if (lp->ll_range)
3377 listitem_T *li;
3379 /* Delete a range of List items. */
3380 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3382 li = lp->ll_li->li_next;
3383 listitem_remove(lp->ll_list, lp->ll_li);
3384 lp->ll_li = li;
3385 ++lp->ll_n1;
3388 else
3390 if (lp->ll_list != NULL)
3391 /* unlet a List item. */
3392 listitem_remove(lp->ll_list, lp->ll_li);
3393 else
3394 /* unlet a Dictionary item. */
3395 dictitem_remove(lp->ll_dict, lp->ll_di);
3398 return ret;
3402 * "unlet" a variable. Return OK if it existed, FAIL if not.
3403 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3406 do_unlet(name, forceit)
3407 char_u *name;
3408 int forceit;
3410 hashtab_T *ht;
3411 hashitem_T *hi;
3412 char_u *varname;
3413 dictitem_T *di;
3415 ht = find_var_ht(name, &varname);
3416 if (ht != NULL && *varname != NUL)
3418 hi = hash_find(ht, varname);
3419 if (!HASHITEM_EMPTY(hi))
3421 di = HI2DI(hi);
3422 if (var_check_fixed(di->di_flags, name)
3423 || var_check_ro(di->di_flags, name))
3424 return FAIL;
3425 delete_var(ht, hi);
3426 return OK;
3429 if (forceit)
3430 return OK;
3431 EMSG2(_("E108: No such variable: \"%s\""), name);
3432 return FAIL;
3436 * Lock or unlock variable indicated by "lp".
3437 * "deep" is the levels to go (-1 for unlimited);
3438 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3440 static int
3441 do_lock_var(lp, name_end, deep, lock)
3442 lval_T *lp;
3443 char_u *name_end;
3444 int deep;
3445 int lock;
3447 int ret = OK;
3448 int cc;
3449 dictitem_T *di;
3451 if (deep == 0) /* nothing to do */
3452 return OK;
3454 if (lp->ll_tv == NULL)
3456 cc = *name_end;
3457 *name_end = NUL;
3459 /* Normal name or expanded name. */
3460 if (check_changedtick(lp->ll_name))
3461 ret = FAIL;
3462 else
3464 di = find_var(lp->ll_name, NULL);
3465 if (di == NULL)
3466 ret = FAIL;
3467 else
3469 if (lock)
3470 di->di_flags |= DI_FLAGS_LOCK;
3471 else
3472 di->di_flags &= ~DI_FLAGS_LOCK;
3473 item_lock(&di->di_tv, deep, lock);
3476 *name_end = cc;
3478 else if (lp->ll_range)
3480 listitem_T *li = lp->ll_li;
3482 /* (un)lock a range of List items. */
3483 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3485 item_lock(&li->li_tv, deep, lock);
3486 li = li->li_next;
3487 ++lp->ll_n1;
3490 else if (lp->ll_list != NULL)
3491 /* (un)lock a List item. */
3492 item_lock(&lp->ll_li->li_tv, deep, lock);
3493 else
3494 /* un(lock) a Dictionary item. */
3495 item_lock(&lp->ll_di->di_tv, deep, lock);
3497 return ret;
3501 * Lock or unlock an item. "deep" is nr of levels to go.
3503 static void
3504 item_lock(tv, deep, lock)
3505 typval_T *tv;
3506 int deep;
3507 int lock;
3509 static int recurse = 0;
3510 list_T *l;
3511 listitem_T *li;
3512 dict_T *d;
3513 hashitem_T *hi;
3514 int todo;
3516 if (recurse >= DICT_MAXNEST)
3518 EMSG(_("E743: variable nested too deep for (un)lock"));
3519 return;
3521 if (deep == 0)
3522 return;
3523 ++recurse;
3525 /* lock/unlock the item itself */
3526 if (lock)
3527 tv->v_lock |= VAR_LOCKED;
3528 else
3529 tv->v_lock &= ~VAR_LOCKED;
3531 switch (tv->v_type)
3533 case VAR_LIST:
3534 if ((l = tv->vval.v_list) != NULL)
3536 if (lock)
3537 l->lv_lock |= VAR_LOCKED;
3538 else
3539 l->lv_lock &= ~VAR_LOCKED;
3540 if (deep < 0 || deep > 1)
3541 /* recursive: lock/unlock the items the List contains */
3542 for (li = l->lv_first; li != NULL; li = li->li_next)
3543 item_lock(&li->li_tv, deep - 1, lock);
3545 break;
3546 case VAR_DICT:
3547 if ((d = tv->vval.v_dict) != NULL)
3549 if (lock)
3550 d->dv_lock |= VAR_LOCKED;
3551 else
3552 d->dv_lock &= ~VAR_LOCKED;
3553 if (deep < 0 || deep > 1)
3555 /* recursive: lock/unlock the items the List contains */
3556 todo = (int)d->dv_hashtab.ht_used;
3557 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3559 if (!HASHITEM_EMPTY(hi))
3561 --todo;
3562 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3568 --recurse;
3572 * Return TRUE if typeval "tv" is locked: Either tha value is locked itself or
3573 * it refers to a List or Dictionary that is locked.
3575 static int
3576 tv_islocked(tv)
3577 typval_T *tv;
3579 return (tv->v_lock & VAR_LOCKED)
3580 || (tv->v_type == VAR_LIST
3581 && tv->vval.v_list != NULL
3582 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3583 || (tv->v_type == VAR_DICT
3584 && tv->vval.v_dict != NULL
3585 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3588 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3590 * Delete all "menutrans_" variables.
3592 void
3593 del_menutrans_vars()
3595 hashitem_T *hi;
3596 int todo;
3598 hash_lock(&globvarht);
3599 todo = (int)globvarht.ht_used;
3600 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3602 if (!HASHITEM_EMPTY(hi))
3604 --todo;
3605 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3606 delete_var(&globvarht, hi);
3609 hash_unlock(&globvarht);
3611 #endif
3613 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3616 * Local string buffer for the next two functions to store a variable name
3617 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3618 * get_user_var_name().
3621 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3623 static char_u *varnamebuf = NULL;
3624 static int varnamebuflen = 0;
3627 * Function to concatenate a prefix and a variable name.
3629 static char_u *
3630 cat_prefix_varname(prefix, name)
3631 int prefix;
3632 char_u *name;
3634 int len;
3636 len = (int)STRLEN(name) + 3;
3637 if (len > varnamebuflen)
3639 vim_free(varnamebuf);
3640 len += 10; /* some additional space */
3641 varnamebuf = alloc(len);
3642 if (varnamebuf == NULL)
3644 varnamebuflen = 0;
3645 return NULL;
3647 varnamebuflen = len;
3649 *varnamebuf = prefix;
3650 varnamebuf[1] = ':';
3651 STRCPY(varnamebuf + 2, name);
3652 return varnamebuf;
3656 * Function given to ExpandGeneric() to obtain the list of user defined
3657 * (global/buffer/window/built-in) variable names.
3659 /*ARGSUSED*/
3660 char_u *
3661 get_user_var_name(xp, idx)
3662 expand_T *xp;
3663 int idx;
3665 static long_u gdone;
3666 static long_u bdone;
3667 static long_u wdone;
3668 #ifdef FEAT_WINDOWS
3669 static long_u tdone;
3670 #endif
3671 static int vidx;
3672 static hashitem_T *hi;
3673 hashtab_T *ht;
3675 if (idx == 0)
3677 gdone = bdone = wdone = vidx = 0;
3678 #ifdef FEAT_WINDOWS
3679 tdone = 0;
3680 #endif
3683 /* Global variables */
3684 if (gdone < globvarht.ht_used)
3686 if (gdone++ == 0)
3687 hi = globvarht.ht_array;
3688 else
3689 ++hi;
3690 while (HASHITEM_EMPTY(hi))
3691 ++hi;
3692 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3693 return cat_prefix_varname('g', hi->hi_key);
3694 return hi->hi_key;
3697 /* b: variables */
3698 ht = &curbuf->b_vars.dv_hashtab;
3699 if (bdone < ht->ht_used)
3701 if (bdone++ == 0)
3702 hi = ht->ht_array;
3703 else
3704 ++hi;
3705 while (HASHITEM_EMPTY(hi))
3706 ++hi;
3707 return cat_prefix_varname('b', hi->hi_key);
3709 if (bdone == ht->ht_used)
3711 ++bdone;
3712 return (char_u *)"b:changedtick";
3715 /* w: variables */
3716 ht = &curwin->w_vars.dv_hashtab;
3717 if (wdone < ht->ht_used)
3719 if (wdone++ == 0)
3720 hi = ht->ht_array;
3721 else
3722 ++hi;
3723 while (HASHITEM_EMPTY(hi))
3724 ++hi;
3725 return cat_prefix_varname('w', hi->hi_key);
3728 #ifdef FEAT_WINDOWS
3729 /* t: variables */
3730 ht = &curtab->tp_vars.dv_hashtab;
3731 if (tdone < ht->ht_used)
3733 if (tdone++ == 0)
3734 hi = ht->ht_array;
3735 else
3736 ++hi;
3737 while (HASHITEM_EMPTY(hi))
3738 ++hi;
3739 return cat_prefix_varname('t', hi->hi_key);
3741 #endif
3743 /* v: variables */
3744 if (vidx < VV_LEN)
3745 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3747 vim_free(varnamebuf);
3748 varnamebuf = NULL;
3749 varnamebuflen = 0;
3750 return NULL;
3753 #endif /* FEAT_CMDL_COMPL */
3756 * types for expressions.
3758 typedef enum
3760 TYPE_UNKNOWN = 0
3761 , TYPE_EQUAL /* == */
3762 , TYPE_NEQUAL /* != */
3763 , TYPE_GREATER /* > */
3764 , TYPE_GEQUAL /* >= */
3765 , TYPE_SMALLER /* < */
3766 , TYPE_SEQUAL /* <= */
3767 , TYPE_MATCH /* =~ */
3768 , TYPE_NOMATCH /* !~ */
3769 } exptype_T;
3772 * The "evaluate" argument: When FALSE, the argument is only parsed but not
3773 * executed. The function may return OK, but the rettv will be of type
3774 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
3778 * Handle zero level expression.
3779 * This calls eval1() and handles error message and nextcmd.
3780 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3781 * Note: "rettv.v_lock" is not set.
3782 * Return OK or FAIL.
3784 static int
3785 eval0(arg, rettv, nextcmd, evaluate)
3786 char_u *arg;
3787 typval_T *rettv;
3788 char_u **nextcmd;
3789 int evaluate;
3791 int ret;
3792 char_u *p;
3794 p = skipwhite(arg);
3795 ret = eval1(&p, rettv, evaluate);
3796 if (ret == FAIL || !ends_excmd(*p))
3798 if (ret != FAIL)
3799 clear_tv(rettv);
3801 * Report the invalid expression unless the expression evaluation has
3802 * been cancelled due to an aborting error, an interrupt, or an
3803 * exception.
3805 if (!aborting())
3806 EMSG2(_(e_invexpr2), arg);
3807 ret = FAIL;
3809 if (nextcmd != NULL)
3810 *nextcmd = check_nextcmd(p);
3812 return ret;
3816 * Handle top level expression:
3817 * expr1 ? expr0 : expr0
3819 * "arg" must point to the first non-white of the expression.
3820 * "arg" is advanced to the next non-white after the recognized expression.
3822 * Note: "rettv.v_lock" is not set.
3824 * Return OK or FAIL.
3826 static int
3827 eval1(arg, rettv, evaluate)
3828 char_u **arg;
3829 typval_T *rettv;
3830 int evaluate;
3832 int result;
3833 typval_T var2;
3836 * Get the first variable.
3838 if (eval2(arg, rettv, evaluate) == FAIL)
3839 return FAIL;
3841 if ((*arg)[0] == '?')
3843 result = FALSE;
3844 if (evaluate)
3846 int error = FALSE;
3848 if (get_tv_number_chk(rettv, &error) != 0)
3849 result = TRUE;
3850 clear_tv(rettv);
3851 if (error)
3852 return FAIL;
3856 * Get the second variable.
3858 *arg = skipwhite(*arg + 1);
3859 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
3860 return FAIL;
3863 * Check for the ":".
3865 if ((*arg)[0] != ':')
3867 EMSG(_("E109: Missing ':' after '?'"));
3868 if (evaluate && result)
3869 clear_tv(rettv);
3870 return FAIL;
3874 * Get the third variable.
3876 *arg = skipwhite(*arg + 1);
3877 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
3879 if (evaluate && result)
3880 clear_tv(rettv);
3881 return FAIL;
3883 if (evaluate && !result)
3884 *rettv = var2;
3887 return OK;
3891 * Handle first level expression:
3892 * expr2 || expr2 || expr2 logical OR
3894 * "arg" must point to the first non-white of the expression.
3895 * "arg" is advanced to the next non-white after the recognized expression.
3897 * Return OK or FAIL.
3899 static int
3900 eval2(arg, rettv, evaluate)
3901 char_u **arg;
3902 typval_T *rettv;
3903 int evaluate;
3905 typval_T var2;
3906 long result;
3907 int first;
3908 int error = FALSE;
3911 * Get the first variable.
3913 if (eval3(arg, rettv, evaluate) == FAIL)
3914 return FAIL;
3917 * Repeat until there is no following "||".
3919 first = TRUE;
3920 result = FALSE;
3921 while ((*arg)[0] == '|' && (*arg)[1] == '|')
3923 if (evaluate && first)
3925 if (get_tv_number_chk(rettv, &error) != 0)
3926 result = TRUE;
3927 clear_tv(rettv);
3928 if (error)
3929 return FAIL;
3930 first = FALSE;
3934 * Get the second variable.
3936 *arg = skipwhite(*arg + 2);
3937 if (eval3(arg, &var2, evaluate && !result) == FAIL)
3938 return FAIL;
3941 * Compute the result.
3943 if (evaluate && !result)
3945 if (get_tv_number_chk(&var2, &error) != 0)
3946 result = TRUE;
3947 clear_tv(&var2);
3948 if (error)
3949 return FAIL;
3951 if (evaluate)
3953 rettv->v_type = VAR_NUMBER;
3954 rettv->vval.v_number = result;
3958 return OK;
3962 * Handle second level expression:
3963 * expr3 && expr3 && expr3 logical AND
3965 * "arg" must point to the first non-white of the expression.
3966 * "arg" is advanced to the next non-white after the recognized expression.
3968 * Return OK or FAIL.
3970 static int
3971 eval3(arg, rettv, evaluate)
3972 char_u **arg;
3973 typval_T *rettv;
3974 int evaluate;
3976 typval_T var2;
3977 long result;
3978 int first;
3979 int error = FALSE;
3982 * Get the first variable.
3984 if (eval4(arg, rettv, evaluate) == FAIL)
3985 return FAIL;
3988 * Repeat until there is no following "&&".
3990 first = TRUE;
3991 result = TRUE;
3992 while ((*arg)[0] == '&' && (*arg)[1] == '&')
3994 if (evaluate && first)
3996 if (get_tv_number_chk(rettv, &error) == 0)
3997 result = FALSE;
3998 clear_tv(rettv);
3999 if (error)
4000 return FAIL;
4001 first = FALSE;
4005 * Get the second variable.
4007 *arg = skipwhite(*arg + 2);
4008 if (eval4(arg, &var2, evaluate && result) == FAIL)
4009 return FAIL;
4012 * Compute the result.
4014 if (evaluate && result)
4016 if (get_tv_number_chk(&var2, &error) == 0)
4017 result = FALSE;
4018 clear_tv(&var2);
4019 if (error)
4020 return FAIL;
4022 if (evaluate)
4024 rettv->v_type = VAR_NUMBER;
4025 rettv->vval.v_number = result;
4029 return OK;
4033 * Handle third level expression:
4034 * var1 == var2
4035 * var1 =~ var2
4036 * var1 != var2
4037 * var1 !~ var2
4038 * var1 > var2
4039 * var1 >= var2
4040 * var1 < var2
4041 * var1 <= var2
4042 * var1 is var2
4043 * var1 isnot var2
4045 * "arg" must point to the first non-white of the expression.
4046 * "arg" is advanced to the next non-white after the recognized expression.
4048 * Return OK or FAIL.
4050 static int
4051 eval4(arg, rettv, evaluate)
4052 char_u **arg;
4053 typval_T *rettv;
4054 int evaluate;
4056 typval_T var2;
4057 char_u *p;
4058 int i;
4059 exptype_T type = TYPE_UNKNOWN;
4060 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4061 int len = 2;
4062 long n1, n2;
4063 char_u *s1, *s2;
4064 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4065 regmatch_T regmatch;
4066 int ic;
4067 char_u *save_cpo;
4070 * Get the first variable.
4072 if (eval5(arg, rettv, evaluate) == FAIL)
4073 return FAIL;
4075 p = *arg;
4076 switch (p[0])
4078 case '=': if (p[1] == '=')
4079 type = TYPE_EQUAL;
4080 else if (p[1] == '~')
4081 type = TYPE_MATCH;
4082 break;
4083 case '!': if (p[1] == '=')
4084 type = TYPE_NEQUAL;
4085 else if (p[1] == '~')
4086 type = TYPE_NOMATCH;
4087 break;
4088 case '>': if (p[1] != '=')
4090 type = TYPE_GREATER;
4091 len = 1;
4093 else
4094 type = TYPE_GEQUAL;
4095 break;
4096 case '<': if (p[1] != '=')
4098 type = TYPE_SMALLER;
4099 len = 1;
4101 else
4102 type = TYPE_SEQUAL;
4103 break;
4104 case 'i': if (p[1] == 's')
4106 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4107 len = 5;
4108 if (!vim_isIDc(p[len]))
4110 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4111 type_is = TRUE;
4114 break;
4118 * If there is a comparitive operator, use it.
4120 if (type != TYPE_UNKNOWN)
4122 /* extra question mark appended: ignore case */
4123 if (p[len] == '?')
4125 ic = TRUE;
4126 ++len;
4128 /* extra '#' appended: match case */
4129 else if (p[len] == '#')
4131 ic = FALSE;
4132 ++len;
4134 /* nothing appened: use 'ignorecase' */
4135 else
4136 ic = p_ic;
4139 * Get the second variable.
4141 *arg = skipwhite(p + len);
4142 if (eval5(arg, &var2, evaluate) == FAIL)
4144 clear_tv(rettv);
4145 return FAIL;
4148 if (evaluate)
4150 if (type_is && rettv->v_type != var2.v_type)
4152 /* For "is" a different type always means FALSE, for "notis"
4153 * it means TRUE. */
4154 n1 = (type == TYPE_NEQUAL);
4156 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4158 if (type_is)
4160 n1 = (rettv->v_type == var2.v_type
4161 && rettv->vval.v_list == var2.vval.v_list);
4162 if (type == TYPE_NEQUAL)
4163 n1 = !n1;
4165 else if (rettv->v_type != var2.v_type
4166 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4168 if (rettv->v_type != var2.v_type)
4169 EMSG(_("E691: Can only compare List with List"));
4170 else
4171 EMSG(_("E692: Invalid operation for Lists"));
4172 clear_tv(rettv);
4173 clear_tv(&var2);
4174 return FAIL;
4176 else
4178 /* Compare two Lists for being equal or unequal. */
4179 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
4180 if (type == TYPE_NEQUAL)
4181 n1 = !n1;
4185 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4187 if (type_is)
4189 n1 = (rettv->v_type == var2.v_type
4190 && rettv->vval.v_dict == var2.vval.v_dict);
4191 if (type == TYPE_NEQUAL)
4192 n1 = !n1;
4194 else if (rettv->v_type != var2.v_type
4195 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4197 if (rettv->v_type != var2.v_type)
4198 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4199 else
4200 EMSG(_("E736: Invalid operation for Dictionary"));
4201 clear_tv(rettv);
4202 clear_tv(&var2);
4203 return FAIL;
4205 else
4207 /* Compare two Dictionaries for being equal or unequal. */
4208 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4209 if (type == TYPE_NEQUAL)
4210 n1 = !n1;
4214 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4216 if (rettv->v_type != var2.v_type
4217 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4219 if (rettv->v_type != var2.v_type)
4220 EMSG(_("E693: Can only compare Funcref with Funcref"));
4221 else
4222 EMSG(_("E694: Invalid operation for Funcrefs"));
4223 clear_tv(rettv);
4224 clear_tv(&var2);
4225 return FAIL;
4227 else
4229 /* Compare two Funcrefs for being equal or unequal. */
4230 if (rettv->vval.v_string == NULL
4231 || var2.vval.v_string == NULL)
4232 n1 = FALSE;
4233 else
4234 n1 = STRCMP(rettv->vval.v_string,
4235 var2.vval.v_string) == 0;
4236 if (type == TYPE_NEQUAL)
4237 n1 = !n1;
4242 * If one of the two variables is a number, compare as a number.
4243 * When using "=~" or "!~", always compare as string.
4245 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4246 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4248 n1 = get_tv_number(rettv);
4249 n2 = get_tv_number(&var2);
4250 switch (type)
4252 case TYPE_EQUAL: n1 = (n1 == n2); break;
4253 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4254 case TYPE_GREATER: n1 = (n1 > n2); break;
4255 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4256 case TYPE_SMALLER: n1 = (n1 < n2); break;
4257 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4258 case TYPE_UNKNOWN:
4259 case TYPE_MATCH:
4260 case TYPE_NOMATCH: break; /* avoid gcc warning */
4263 else
4265 s1 = get_tv_string_buf(rettv, buf1);
4266 s2 = get_tv_string_buf(&var2, buf2);
4267 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4268 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4269 else
4270 i = 0;
4271 n1 = FALSE;
4272 switch (type)
4274 case TYPE_EQUAL: n1 = (i == 0); break;
4275 case TYPE_NEQUAL: n1 = (i != 0); break;
4276 case TYPE_GREATER: n1 = (i > 0); break;
4277 case TYPE_GEQUAL: n1 = (i >= 0); break;
4278 case TYPE_SMALLER: n1 = (i < 0); break;
4279 case TYPE_SEQUAL: n1 = (i <= 0); break;
4281 case TYPE_MATCH:
4282 case TYPE_NOMATCH:
4283 /* avoid 'l' flag in 'cpoptions' */
4284 save_cpo = p_cpo;
4285 p_cpo = (char_u *)"";
4286 regmatch.regprog = vim_regcomp(s2,
4287 RE_MAGIC + RE_STRING);
4288 regmatch.rm_ic = ic;
4289 if (regmatch.regprog != NULL)
4291 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4292 vim_free(regmatch.regprog);
4293 if (type == TYPE_NOMATCH)
4294 n1 = !n1;
4296 p_cpo = save_cpo;
4297 break;
4299 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4302 clear_tv(rettv);
4303 clear_tv(&var2);
4304 rettv->v_type = VAR_NUMBER;
4305 rettv->vval.v_number = n1;
4309 return OK;
4313 * Handle fourth level expression:
4314 * + number addition
4315 * - number subtraction
4316 * . string concatenation
4318 * "arg" must point to the first non-white of the expression.
4319 * "arg" is advanced to the next non-white after the recognized expression.
4321 * Return OK or FAIL.
4323 static int
4324 eval5(arg, rettv, evaluate)
4325 char_u **arg;
4326 typval_T *rettv;
4327 int evaluate;
4329 typval_T var2;
4330 typval_T var3;
4331 int op;
4332 long n1, n2;
4333 char_u *s1, *s2;
4334 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4335 char_u *p;
4338 * Get the first variable.
4340 if (eval6(arg, rettv, evaluate) == FAIL)
4341 return FAIL;
4344 * Repeat computing, until no '+', '-' or '.' is following.
4346 for (;;)
4348 op = **arg;
4349 if (op != '+' && op != '-' && op != '.')
4350 break;
4352 if (op != '+' || rettv->v_type != VAR_LIST)
4354 /* For "list + ...", an illegal use of the first operand as
4355 * a number cannot be determined before evaluating the 2nd
4356 * operand: if this is also a list, all is ok.
4357 * For "something . ...", "something - ..." or "non-list + ...",
4358 * we know that the first operand needs to be a string or number
4359 * without evaluating the 2nd operand. So check before to avoid
4360 * side effects after an error. */
4361 if (evaluate && get_tv_string_chk(rettv) == NULL)
4363 clear_tv(rettv);
4364 return FAIL;
4369 * Get the second variable.
4371 *arg = skipwhite(*arg + 1);
4372 if (eval6(arg, &var2, evaluate) == FAIL)
4374 clear_tv(rettv);
4375 return FAIL;
4378 if (evaluate)
4381 * Compute the result.
4383 if (op == '.')
4385 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4386 s2 = get_tv_string_buf_chk(&var2, buf2);
4387 if (s2 == NULL) /* type error ? */
4389 clear_tv(rettv);
4390 clear_tv(&var2);
4391 return FAIL;
4393 p = concat_str(s1, s2);
4394 clear_tv(rettv);
4395 rettv->v_type = VAR_STRING;
4396 rettv->vval.v_string = p;
4398 else if (op == '+' && rettv->v_type == VAR_LIST
4399 && var2.v_type == VAR_LIST)
4401 /* concatenate Lists */
4402 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4403 &var3) == FAIL)
4405 clear_tv(rettv);
4406 clear_tv(&var2);
4407 return FAIL;
4409 clear_tv(rettv);
4410 *rettv = var3;
4412 else
4414 int error = FALSE;
4416 n1 = get_tv_number_chk(rettv, &error);
4417 if (error)
4419 /* This can only happen for "list + non-list".
4420 * For "non-list + ..." or "something - ...", we returned
4421 * before evaluating the 2nd operand. */
4422 clear_tv(rettv);
4423 return FAIL;
4425 n2 = get_tv_number_chk(&var2, &error);
4426 if (error)
4428 clear_tv(rettv);
4429 clear_tv(&var2);
4430 return FAIL;
4432 clear_tv(rettv);
4433 if (op == '+')
4434 n1 = n1 + n2;
4435 else
4436 n1 = n1 - n2;
4437 rettv->v_type = VAR_NUMBER;
4438 rettv->vval.v_number = n1;
4440 clear_tv(&var2);
4443 return OK;
4447 * Handle fifth level expression:
4448 * * number multiplication
4449 * / number division
4450 * % number modulo
4452 * "arg" must point to the first non-white of the expression.
4453 * "arg" is advanced to the next non-white after the recognized expression.
4455 * Return OK or FAIL.
4457 static int
4458 eval6(arg, rettv, evaluate)
4459 char_u **arg;
4460 typval_T *rettv;
4461 int evaluate;
4463 typval_T var2;
4464 int op;
4465 long n1, n2;
4466 int error = FALSE;
4469 * Get the first variable.
4471 if (eval7(arg, rettv, evaluate) == FAIL)
4472 return FAIL;
4475 * Repeat computing, until no '*', '/' or '%' is following.
4477 for (;;)
4479 op = **arg;
4480 if (op != '*' && op != '/' && op != '%')
4481 break;
4483 if (evaluate)
4485 n1 = get_tv_number_chk(rettv, &error);
4486 clear_tv(rettv);
4487 if (error)
4488 return FAIL;
4490 else
4491 n1 = 0;
4494 * Get the second variable.
4496 *arg = skipwhite(*arg + 1);
4497 if (eval7(arg, &var2, evaluate) == FAIL)
4498 return FAIL;
4500 if (evaluate)
4502 n2 = get_tv_number_chk(&var2, &error);
4503 clear_tv(&var2);
4504 if (error)
4505 return FAIL;
4508 * Compute the result.
4510 if (op == '*')
4511 n1 = n1 * n2;
4512 else if (op == '/')
4514 if (n2 == 0) /* give an error message? */
4515 n1 = 0x7fffffffL;
4516 else
4517 n1 = n1 / n2;
4519 else
4521 if (n2 == 0) /* give an error message? */
4522 n1 = 0;
4523 else
4524 n1 = n1 % n2;
4526 rettv->v_type = VAR_NUMBER;
4527 rettv->vval.v_number = n1;
4531 return OK;
4535 * Handle sixth level expression:
4536 * number number constant
4537 * "string" string constant
4538 * 'string' literal string constant
4539 * &option-name option value
4540 * @r register contents
4541 * identifier variable value
4542 * function() function call
4543 * $VAR environment variable
4544 * (expression) nested expression
4545 * [expr, expr] List
4546 * {key: val, key: val} Dictionary
4548 * Also handle:
4549 * ! in front logical NOT
4550 * - in front unary minus
4551 * + in front unary plus (ignored)
4552 * trailing [] subscript in String or List
4553 * trailing .name entry in Dictionary
4555 * "arg" must point to the first non-white of the expression.
4556 * "arg" is advanced to the next non-white after the recognized expression.
4558 * Return OK or FAIL.
4560 static int
4561 eval7(arg, rettv, evaluate)
4562 char_u **arg;
4563 typval_T *rettv;
4564 int evaluate;
4566 long n;
4567 int len;
4568 char_u *s;
4569 int val;
4570 char_u *start_leader, *end_leader;
4571 int ret = OK;
4572 char_u *alias;
4575 * Initialise variable so that clear_tv() can't mistake this for a
4576 * string and free a string that isn't there.
4578 rettv->v_type = VAR_UNKNOWN;
4581 * Skip '!' and '-' characters. They are handled later.
4583 start_leader = *arg;
4584 while (**arg == '!' || **arg == '-' || **arg == '+')
4585 *arg = skipwhite(*arg + 1);
4586 end_leader = *arg;
4588 switch (**arg)
4591 * Number constant.
4593 case '0':
4594 case '1':
4595 case '2':
4596 case '3':
4597 case '4':
4598 case '5':
4599 case '6':
4600 case '7':
4601 case '8':
4602 case '9':
4603 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4604 *arg += len;
4605 if (evaluate)
4607 rettv->v_type = VAR_NUMBER;
4608 rettv->vval.v_number = n;
4610 break;
4613 * String constant: "string".
4615 case '"': ret = get_string_tv(arg, rettv, evaluate);
4616 break;
4619 * Literal string constant: 'str''ing'.
4621 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
4622 break;
4625 * List: [expr, expr]
4627 case '[': ret = get_list_tv(arg, rettv, evaluate);
4628 break;
4631 * Dictionary: {key: val, key: val}
4633 case '{': ret = get_dict_tv(arg, rettv, evaluate);
4634 break;
4637 * Option value: &name
4639 case '&': ret = get_option_tv(arg, rettv, evaluate);
4640 break;
4643 * Environment variable: $VAR.
4645 case '$': ret = get_env_tv(arg, rettv, evaluate);
4646 break;
4649 * Register contents: @r.
4651 case '@': ++*arg;
4652 if (evaluate)
4654 rettv->v_type = VAR_STRING;
4655 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4657 if (**arg != NUL)
4658 ++*arg;
4659 break;
4662 * nested expression: (expression).
4664 case '(': *arg = skipwhite(*arg + 1);
4665 ret = eval1(arg, rettv, evaluate); /* recursive! */
4666 if (**arg == ')')
4667 ++*arg;
4668 else if (ret == OK)
4670 EMSG(_("E110: Missing ')'"));
4671 clear_tv(rettv);
4672 ret = FAIL;
4674 break;
4676 default: ret = NOTDONE;
4677 break;
4680 if (ret == NOTDONE)
4683 * Must be a variable or function name.
4684 * Can also be a curly-braces kind of name: {expr}.
4686 s = *arg;
4687 len = get_name_len(arg, &alias, evaluate, TRUE);
4688 if (alias != NULL)
4689 s = alias;
4691 if (len <= 0)
4692 ret = FAIL;
4693 else
4695 if (**arg == '(') /* recursive! */
4697 /* If "s" is the name of a variable of type VAR_FUNC
4698 * use its contents. */
4699 s = deref_func_name(s, &len);
4701 /* Invoke the function. */
4702 ret = get_func_tv(s, len, rettv, arg,
4703 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
4704 &len, evaluate, NULL);
4705 /* Stop the expression evaluation when immediately
4706 * aborting on error, or when an interrupt occurred or
4707 * an exception was thrown but not caught. */
4708 if (aborting())
4710 if (ret == OK)
4711 clear_tv(rettv);
4712 ret = FAIL;
4715 else if (evaluate)
4716 ret = get_var_tv(s, len, rettv, TRUE);
4717 else
4718 ret = OK;
4721 if (alias != NULL)
4722 vim_free(alias);
4725 *arg = skipwhite(*arg);
4727 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
4728 * expr(expr). */
4729 if (ret == OK)
4730 ret = handle_subscript(arg, rettv, evaluate, TRUE);
4733 * Apply logical NOT and unary '-', from right to left, ignore '+'.
4735 if (ret == OK && evaluate && end_leader > start_leader)
4737 int error = FALSE;
4739 val = get_tv_number_chk(rettv, &error);
4740 if (error)
4742 clear_tv(rettv);
4743 ret = FAIL;
4745 else
4747 while (end_leader > start_leader)
4749 --end_leader;
4750 if (*end_leader == '!')
4751 val = !val;
4752 else if (*end_leader == '-')
4753 val = -val;
4755 clear_tv(rettv);
4756 rettv->v_type = VAR_NUMBER;
4757 rettv->vval.v_number = val;
4761 return ret;
4765 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
4766 * "*arg" points to the '[' or '.'.
4767 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
4769 static int
4770 eval_index(arg, rettv, evaluate, verbose)
4771 char_u **arg;
4772 typval_T *rettv;
4773 int evaluate;
4774 int verbose; /* give error messages */
4776 int empty1 = FALSE, empty2 = FALSE;
4777 typval_T var1, var2;
4778 long n1, n2 = 0;
4779 long len = -1;
4780 int range = FALSE;
4781 char_u *s;
4782 char_u *key = NULL;
4784 if (rettv->v_type == VAR_FUNC)
4786 if (verbose)
4787 EMSG(_("E695: Cannot index a Funcref"));
4788 return FAIL;
4791 if (**arg == '.')
4794 * dict.name
4796 key = *arg + 1;
4797 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
4799 if (len == 0)
4800 return FAIL;
4801 *arg = skipwhite(key + len);
4803 else
4806 * something[idx]
4808 * Get the (first) variable from inside the [].
4810 *arg = skipwhite(*arg + 1);
4811 if (**arg == ':')
4812 empty1 = TRUE;
4813 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
4814 return FAIL;
4815 else if (evaluate && get_tv_string_chk(&var1) == NULL)
4817 /* not a number or string */
4818 clear_tv(&var1);
4819 return FAIL;
4823 * Get the second variable from inside the [:].
4825 if (**arg == ':')
4827 range = TRUE;
4828 *arg = skipwhite(*arg + 1);
4829 if (**arg == ']')
4830 empty2 = TRUE;
4831 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
4833 if (!empty1)
4834 clear_tv(&var1);
4835 return FAIL;
4837 else if (evaluate && get_tv_string_chk(&var2) == NULL)
4839 /* not a number or string */
4840 if (!empty1)
4841 clear_tv(&var1);
4842 clear_tv(&var2);
4843 return FAIL;
4847 /* Check for the ']'. */
4848 if (**arg != ']')
4850 if (verbose)
4851 EMSG(_(e_missbrac));
4852 clear_tv(&var1);
4853 if (range)
4854 clear_tv(&var2);
4855 return FAIL;
4857 *arg = skipwhite(*arg + 1); /* skip the ']' */
4860 if (evaluate)
4862 n1 = 0;
4863 if (!empty1 && rettv->v_type != VAR_DICT)
4865 n1 = get_tv_number(&var1);
4866 clear_tv(&var1);
4868 if (range)
4870 if (empty2)
4871 n2 = -1;
4872 else
4874 n2 = get_tv_number(&var2);
4875 clear_tv(&var2);
4879 switch (rettv->v_type)
4881 case VAR_NUMBER:
4882 case VAR_STRING:
4883 s = get_tv_string(rettv);
4884 len = (long)STRLEN(s);
4885 if (range)
4887 /* The resulting variable is a substring. If the indexes
4888 * are out of range the result is empty. */
4889 if (n1 < 0)
4891 n1 = len + n1;
4892 if (n1 < 0)
4893 n1 = 0;
4895 if (n2 < 0)
4896 n2 = len + n2;
4897 else if (n2 >= len)
4898 n2 = len;
4899 if (n1 >= len || n2 < 0 || n1 > n2)
4900 s = NULL;
4901 else
4902 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
4904 else
4906 /* The resulting variable is a string of a single
4907 * character. If the index is too big or negative the
4908 * result is empty. */
4909 if (n1 >= len || n1 < 0)
4910 s = NULL;
4911 else
4912 s = vim_strnsave(s + n1, 1);
4914 clear_tv(rettv);
4915 rettv->v_type = VAR_STRING;
4916 rettv->vval.v_string = s;
4917 break;
4919 case VAR_LIST:
4920 len = list_len(rettv->vval.v_list);
4921 if (n1 < 0)
4922 n1 = len + n1;
4923 if (!empty1 && (n1 < 0 || n1 >= len))
4925 /* For a range we allow invalid values and return an empty
4926 * list. A list index out of range is an error. */
4927 if (!range)
4929 if (verbose)
4930 EMSGN(_(e_listidx), n1);
4931 return FAIL;
4933 n1 = len;
4935 if (range)
4937 list_T *l;
4938 listitem_T *item;
4940 if (n2 < 0)
4941 n2 = len + n2;
4942 else if (n2 >= len)
4943 n2 = len - 1;
4944 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
4945 n2 = -1;
4946 l = list_alloc();
4947 if (l == NULL)
4948 return FAIL;
4949 for (item = list_find(rettv->vval.v_list, n1);
4950 n1 <= n2; ++n1)
4952 if (list_append_tv(l, &item->li_tv) == FAIL)
4954 list_free(l, TRUE);
4955 return FAIL;
4957 item = item->li_next;
4959 clear_tv(rettv);
4960 rettv->v_type = VAR_LIST;
4961 rettv->vval.v_list = l;
4962 ++l->lv_refcount;
4964 else
4966 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
4967 clear_tv(rettv);
4968 *rettv = var1;
4970 break;
4972 case VAR_DICT:
4973 if (range)
4975 if (verbose)
4976 EMSG(_(e_dictrange));
4977 if (len == -1)
4978 clear_tv(&var1);
4979 return FAIL;
4982 dictitem_T *item;
4984 if (len == -1)
4986 key = get_tv_string(&var1);
4987 if (*key == NUL)
4989 if (verbose)
4990 EMSG(_(e_emptykey));
4991 clear_tv(&var1);
4992 return FAIL;
4996 item = dict_find(rettv->vval.v_dict, key, (int)len);
4998 if (item == NULL && verbose)
4999 EMSG2(_(e_dictkey), key);
5000 if (len == -1)
5001 clear_tv(&var1);
5002 if (item == NULL)
5003 return FAIL;
5005 copy_tv(&item->di_tv, &var1);
5006 clear_tv(rettv);
5007 *rettv = var1;
5009 break;
5013 return OK;
5017 * Get an option value.
5018 * "arg" points to the '&' or '+' before the option name.
5019 * "arg" is advanced to character after the option name.
5020 * Return OK or FAIL.
5022 static int
5023 get_option_tv(arg, rettv, evaluate)
5024 char_u **arg;
5025 typval_T *rettv; /* when NULL, only check if option exists */
5026 int evaluate;
5028 char_u *option_end;
5029 long numval;
5030 char_u *stringval;
5031 int opt_type;
5032 int c;
5033 int working = (**arg == '+'); /* has("+option") */
5034 int ret = OK;
5035 int opt_flags;
5038 * Isolate the option name and find its value.
5040 option_end = find_option_end(arg, &opt_flags);
5041 if (option_end == NULL)
5043 if (rettv != NULL)
5044 EMSG2(_("E112: Option name missing: %s"), *arg);
5045 return FAIL;
5048 if (!evaluate)
5050 *arg = option_end;
5051 return OK;
5054 c = *option_end;
5055 *option_end = NUL;
5056 opt_type = get_option_value(*arg, &numval,
5057 rettv == NULL ? NULL : &stringval, opt_flags);
5059 if (opt_type == -3) /* invalid name */
5061 if (rettv != NULL)
5062 EMSG2(_("E113: Unknown option: %s"), *arg);
5063 ret = FAIL;
5065 else if (rettv != NULL)
5067 if (opt_type == -2) /* hidden string option */
5069 rettv->v_type = VAR_STRING;
5070 rettv->vval.v_string = NULL;
5072 else if (opt_type == -1) /* hidden number option */
5074 rettv->v_type = VAR_NUMBER;
5075 rettv->vval.v_number = 0;
5077 else if (opt_type == 1) /* number option */
5079 rettv->v_type = VAR_NUMBER;
5080 rettv->vval.v_number = numval;
5082 else /* string option */
5084 rettv->v_type = VAR_STRING;
5085 rettv->vval.v_string = stringval;
5088 else if (working && (opt_type == -2 || opt_type == -1))
5089 ret = FAIL;
5091 *option_end = c; /* put back for error messages */
5092 *arg = option_end;
5094 return ret;
5098 * Allocate a variable for a string constant.
5099 * Return OK or FAIL.
5101 static int
5102 get_string_tv(arg, rettv, evaluate)
5103 char_u **arg;
5104 typval_T *rettv;
5105 int evaluate;
5107 char_u *p;
5108 char_u *name;
5109 int extra = 0;
5112 * Find the end of the string, skipping backslashed characters.
5114 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5116 if (*p == '\\' && p[1] != NUL)
5118 ++p;
5119 /* A "\<x>" form occupies at least 4 characters, and produces up
5120 * to 6 characters: reserve space for 2 extra */
5121 if (*p == '<')
5122 extra += 2;
5126 if (*p != '"')
5128 EMSG2(_("E114: Missing quote: %s"), *arg);
5129 return FAIL;
5132 /* If only parsing, set *arg and return here */
5133 if (!evaluate)
5135 *arg = p + 1;
5136 return OK;
5140 * Copy the string into allocated memory, handling backslashed
5141 * characters.
5143 name = alloc((unsigned)(p - *arg + extra));
5144 if (name == NULL)
5145 return FAIL;
5146 rettv->v_type = VAR_STRING;
5147 rettv->vval.v_string = name;
5149 for (p = *arg + 1; *p != NUL && *p != '"'; )
5151 if (*p == '\\')
5153 switch (*++p)
5155 case 'b': *name++ = BS; ++p; break;
5156 case 'e': *name++ = ESC; ++p; break;
5157 case 'f': *name++ = FF; ++p; break;
5158 case 'n': *name++ = NL; ++p; break;
5159 case 'r': *name++ = CAR; ++p; break;
5160 case 't': *name++ = TAB; ++p; break;
5162 case 'X': /* hex: "\x1", "\x12" */
5163 case 'x':
5164 case 'u': /* Unicode: "\u0023" */
5165 case 'U':
5166 if (vim_isxdigit(p[1]))
5168 int n, nr;
5169 int c = toupper(*p);
5171 if (c == 'X')
5172 n = 2;
5173 else
5174 n = 4;
5175 nr = 0;
5176 while (--n >= 0 && vim_isxdigit(p[1]))
5178 ++p;
5179 nr = (nr << 4) + hex2nr(*p);
5181 ++p;
5182 #ifdef FEAT_MBYTE
5183 /* For "\u" store the number according to
5184 * 'encoding'. */
5185 if (c != 'X')
5186 name += (*mb_char2bytes)(nr, name);
5187 else
5188 #endif
5189 *name++ = nr;
5191 break;
5193 /* octal: "\1", "\12", "\123" */
5194 case '0':
5195 case '1':
5196 case '2':
5197 case '3':
5198 case '4':
5199 case '5':
5200 case '6':
5201 case '7': *name = *p++ - '0';
5202 if (*p >= '0' && *p <= '7')
5204 *name = (*name << 3) + *p++ - '0';
5205 if (*p >= '0' && *p <= '7')
5206 *name = (*name << 3) + *p++ - '0';
5208 ++name;
5209 break;
5211 /* Special key, e.g.: "\<C-W>" */
5212 case '<': extra = trans_special(&p, name, TRUE);
5213 if (extra != 0)
5215 name += extra;
5216 break;
5218 /* FALLTHROUGH */
5220 default: MB_COPY_CHAR(p, name);
5221 break;
5224 else
5225 MB_COPY_CHAR(p, name);
5228 *name = NUL;
5229 *arg = p + 1;
5231 return OK;
5235 * Allocate a variable for a 'str''ing' constant.
5236 * Return OK or FAIL.
5238 static int
5239 get_lit_string_tv(arg, rettv, evaluate)
5240 char_u **arg;
5241 typval_T *rettv;
5242 int evaluate;
5244 char_u *p;
5245 char_u *str;
5246 int reduce = 0;
5249 * Find the end of the string, skipping ''.
5251 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5253 if (*p == '\'')
5255 if (p[1] != '\'')
5256 break;
5257 ++reduce;
5258 ++p;
5262 if (*p != '\'')
5264 EMSG2(_("E115: Missing quote: %s"), *arg);
5265 return FAIL;
5268 /* If only parsing return after setting "*arg" */
5269 if (!evaluate)
5271 *arg = p + 1;
5272 return OK;
5276 * Copy the string into allocated memory, handling '' to ' reduction.
5278 str = alloc((unsigned)((p - *arg) - reduce));
5279 if (str == NULL)
5280 return FAIL;
5281 rettv->v_type = VAR_STRING;
5282 rettv->vval.v_string = str;
5284 for (p = *arg + 1; *p != NUL; )
5286 if (*p == '\'')
5288 if (p[1] != '\'')
5289 break;
5290 ++p;
5292 MB_COPY_CHAR(p, str);
5294 *str = NUL;
5295 *arg = p + 1;
5297 return OK;
5301 * Allocate a variable for a List and fill it from "*arg".
5302 * Return OK or FAIL.
5304 static int
5305 get_list_tv(arg, rettv, evaluate)
5306 char_u **arg;
5307 typval_T *rettv;
5308 int evaluate;
5310 list_T *l = NULL;
5311 typval_T tv;
5312 listitem_T *item;
5314 if (evaluate)
5316 l = list_alloc();
5317 if (l == NULL)
5318 return FAIL;
5321 *arg = skipwhite(*arg + 1);
5322 while (**arg != ']' && **arg != NUL)
5324 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5325 goto failret;
5326 if (evaluate)
5328 item = listitem_alloc();
5329 if (item != NULL)
5331 item->li_tv = tv;
5332 item->li_tv.v_lock = 0;
5333 list_append(l, item);
5335 else
5336 clear_tv(&tv);
5339 if (**arg == ']')
5340 break;
5341 if (**arg != ',')
5343 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5344 goto failret;
5346 *arg = skipwhite(*arg + 1);
5349 if (**arg != ']')
5351 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5352 failret:
5353 if (evaluate)
5354 list_free(l, TRUE);
5355 return FAIL;
5358 *arg = skipwhite(*arg + 1);
5359 if (evaluate)
5361 rettv->v_type = VAR_LIST;
5362 rettv->vval.v_list = l;
5363 ++l->lv_refcount;
5366 return OK;
5370 * Allocate an empty header for a list.
5371 * Caller should take care of the reference count.
5373 list_T *
5374 list_alloc()
5376 list_T *l;
5378 l = (list_T *)alloc_clear(sizeof(list_T));
5379 if (l != NULL)
5381 /* Prepend the list to the list of lists for garbage collection. */
5382 if (first_list != NULL)
5383 first_list->lv_used_prev = l;
5384 l->lv_used_prev = NULL;
5385 l->lv_used_next = first_list;
5386 first_list = l;
5388 return l;
5392 * Allocate an empty list for a return value.
5393 * Returns OK or FAIL.
5395 static int
5396 rettv_list_alloc(rettv)
5397 typval_T *rettv;
5399 list_T *l = list_alloc();
5401 if (l == NULL)
5402 return FAIL;
5404 rettv->vval.v_list = l;
5405 rettv->v_type = VAR_LIST;
5406 ++l->lv_refcount;
5407 return OK;
5411 * Unreference a list: decrement the reference count and free it when it
5412 * becomes zero.
5414 void
5415 list_unref(l)
5416 list_T *l;
5418 if (l != NULL && --l->lv_refcount <= 0)
5419 list_free(l, TRUE);
5423 * Free a list, including all items it points to.
5424 * Ignores the reference count.
5426 void
5427 list_free(l, recurse)
5428 list_T *l;
5429 int recurse; /* Free Lists and Dictionaries recursively. */
5431 listitem_T *item;
5433 /* Remove the list from the list of lists for garbage collection. */
5434 if (l->lv_used_prev == NULL)
5435 first_list = l->lv_used_next;
5436 else
5437 l->lv_used_prev->lv_used_next = l->lv_used_next;
5438 if (l->lv_used_next != NULL)
5439 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5441 for (item = l->lv_first; item != NULL; item = l->lv_first)
5443 /* Remove the item before deleting it. */
5444 l->lv_first = item->li_next;
5445 if (recurse || (item->li_tv.v_type != VAR_LIST
5446 && item->li_tv.v_type != VAR_DICT))
5447 clear_tv(&item->li_tv);
5448 vim_free(item);
5450 vim_free(l);
5454 * Allocate a list item.
5456 static listitem_T *
5457 listitem_alloc()
5459 return (listitem_T *)alloc(sizeof(listitem_T));
5463 * Free a list item. Also clears the value. Does not notify watchers.
5465 static void
5466 listitem_free(item)
5467 listitem_T *item;
5469 clear_tv(&item->li_tv);
5470 vim_free(item);
5474 * Remove a list item from a List and free it. Also clears the value.
5476 static void
5477 listitem_remove(l, item)
5478 list_T *l;
5479 listitem_T *item;
5481 list_remove(l, item, item);
5482 listitem_free(item);
5486 * Get the number of items in a list.
5488 static long
5489 list_len(l)
5490 list_T *l;
5492 if (l == NULL)
5493 return 0L;
5494 return l->lv_len;
5498 * Return TRUE when two lists have exactly the same values.
5500 static int
5501 list_equal(l1, l2, ic)
5502 list_T *l1;
5503 list_T *l2;
5504 int ic; /* ignore case for strings */
5506 listitem_T *item1, *item2;
5508 if (l1 == l2)
5509 return TRUE;
5510 if (list_len(l1) != list_len(l2))
5511 return FALSE;
5513 for (item1 = l1->lv_first, item2 = l2->lv_first;
5514 item1 != NULL && item2 != NULL;
5515 item1 = item1->li_next, item2 = item2->li_next)
5516 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5517 return FALSE;
5518 return item1 == NULL && item2 == NULL;
5521 #if defined(FEAT_PYTHON) || defined(PROTO)
5523 * Return the dictitem that an entry in a hashtable points to.
5525 dictitem_T *
5526 dict_lookup(hi)
5527 hashitem_T *hi;
5529 return HI2DI(hi);
5531 #endif
5534 * Return TRUE when two dictionaries have exactly the same key/values.
5536 static int
5537 dict_equal(d1, d2, ic)
5538 dict_T *d1;
5539 dict_T *d2;
5540 int ic; /* ignore case for strings */
5542 hashitem_T *hi;
5543 dictitem_T *item2;
5544 int todo;
5546 if (d1 == d2)
5547 return TRUE;
5548 if (dict_len(d1) != dict_len(d2))
5549 return FALSE;
5551 todo = (int)d1->dv_hashtab.ht_used;
5552 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5554 if (!HASHITEM_EMPTY(hi))
5556 item2 = dict_find(d2, hi->hi_key, -1);
5557 if (item2 == NULL)
5558 return FALSE;
5559 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5560 return FALSE;
5561 --todo;
5564 return TRUE;
5568 * Return TRUE if "tv1" and "tv2" have the same value.
5569 * Compares the items just like "==" would compare them, but strings and
5570 * numbers are different.
5572 static int
5573 tv_equal(tv1, tv2, ic)
5574 typval_T *tv1;
5575 typval_T *tv2;
5576 int ic; /* ignore case */
5578 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5579 char_u *s1, *s2;
5580 static int recursive = 0; /* cach recursive loops */
5581 int r;
5583 if (tv1->v_type != tv2->v_type)
5584 return FALSE;
5585 /* Catch lists and dicts that have an endless loop by limiting
5586 * recursiveness to 1000. We guess they are equal then. */
5587 if (recursive >= 1000)
5588 return TRUE;
5590 switch (tv1->v_type)
5592 case VAR_LIST:
5593 ++recursive;
5594 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5595 --recursive;
5596 return r;
5598 case VAR_DICT:
5599 ++recursive;
5600 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5601 --recursive;
5602 return r;
5604 case VAR_FUNC:
5605 return (tv1->vval.v_string != NULL
5606 && tv2->vval.v_string != NULL
5607 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5609 case VAR_NUMBER:
5610 return tv1->vval.v_number == tv2->vval.v_number;
5612 case VAR_STRING:
5613 s1 = get_tv_string_buf(tv1, buf1);
5614 s2 = get_tv_string_buf(tv2, buf2);
5615 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5618 EMSG2(_(e_intern2), "tv_equal()");
5619 return TRUE;
5623 * Locate item with index "n" in list "l" and return it.
5624 * A negative index is counted from the end; -1 is the last item.
5625 * Returns NULL when "n" is out of range.
5627 static listitem_T *
5628 list_find(l, n)
5629 list_T *l;
5630 long n;
5632 listitem_T *item;
5633 long idx;
5635 if (l == NULL)
5636 return NULL;
5638 /* Negative index is relative to the end. */
5639 if (n < 0)
5640 n = l->lv_len + n;
5642 /* Check for index out of range. */
5643 if (n < 0 || n >= l->lv_len)
5644 return NULL;
5646 /* When there is a cached index may start search from there. */
5647 if (l->lv_idx_item != NULL)
5649 if (n < l->lv_idx / 2)
5651 /* closest to the start of the list */
5652 item = l->lv_first;
5653 idx = 0;
5655 else if (n > (l->lv_idx + l->lv_len) / 2)
5657 /* closest to the end of the list */
5658 item = l->lv_last;
5659 idx = l->lv_len - 1;
5661 else
5663 /* closest to the cached index */
5664 item = l->lv_idx_item;
5665 idx = l->lv_idx;
5668 else
5670 if (n < l->lv_len / 2)
5672 /* closest to the start of the list */
5673 item = l->lv_first;
5674 idx = 0;
5676 else
5678 /* closest to the end of the list */
5679 item = l->lv_last;
5680 idx = l->lv_len - 1;
5684 while (n > idx)
5686 /* search forward */
5687 item = item->li_next;
5688 ++idx;
5690 while (n < idx)
5692 /* search backward */
5693 item = item->li_prev;
5694 --idx;
5697 /* cache the used index */
5698 l->lv_idx = idx;
5699 l->lv_idx_item = item;
5701 return item;
5705 * Get list item "l[idx]" as a number.
5707 static long
5708 list_find_nr(l, idx, errorp)
5709 list_T *l;
5710 long idx;
5711 int *errorp; /* set to TRUE when something wrong */
5713 listitem_T *li;
5715 li = list_find(l, idx);
5716 if (li == NULL)
5718 if (errorp != NULL)
5719 *errorp = TRUE;
5720 return -1L;
5722 return get_tv_number_chk(&li->li_tv, errorp);
5726 * Locate "item" list "l" and return its index.
5727 * Returns -1 when "item" is not in the list.
5729 static long
5730 list_idx_of_item(l, item)
5731 list_T *l;
5732 listitem_T *item;
5734 long idx = 0;
5735 listitem_T *li;
5737 if (l == NULL)
5738 return -1;
5739 idx = 0;
5740 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
5741 ++idx;
5742 if (li == NULL)
5743 return -1;
5744 return idx;
5748 * Append item "item" to the end of list "l".
5750 static void
5751 list_append(l, item)
5752 list_T *l;
5753 listitem_T *item;
5755 if (l->lv_last == NULL)
5757 /* empty list */
5758 l->lv_first = item;
5759 l->lv_last = item;
5760 item->li_prev = NULL;
5762 else
5764 l->lv_last->li_next = item;
5765 item->li_prev = l->lv_last;
5766 l->lv_last = item;
5768 ++l->lv_len;
5769 item->li_next = NULL;
5773 * Append typval_T "tv" to the end of list "l".
5774 * Return FAIL when out of memory.
5776 static int
5777 list_append_tv(l, tv)
5778 list_T *l;
5779 typval_T *tv;
5781 listitem_T *li = listitem_alloc();
5783 if (li == NULL)
5784 return FAIL;
5785 copy_tv(tv, &li->li_tv);
5786 list_append(l, li);
5787 return OK;
5791 * Add a dictionary to a list. Used by getqflist().
5792 * Return FAIL when out of memory.
5795 list_append_dict(list, dict)
5796 list_T *list;
5797 dict_T *dict;
5799 listitem_T *li = listitem_alloc();
5801 if (li == NULL)
5802 return FAIL;
5803 li->li_tv.v_type = VAR_DICT;
5804 li->li_tv.v_lock = 0;
5805 li->li_tv.vval.v_dict = dict;
5806 list_append(list, li);
5807 ++dict->dv_refcount;
5808 return OK;
5812 * Make a copy of "str" and append it as an item to list "l".
5813 * When "len" >= 0 use "str[len]".
5814 * Returns FAIL when out of memory.
5816 static int
5817 list_append_string(l, str, len)
5818 list_T *l;
5819 char_u *str;
5820 int len;
5822 listitem_T *li = listitem_alloc();
5824 if (li == NULL)
5825 return FAIL;
5826 list_append(l, li);
5827 li->li_tv.v_type = VAR_STRING;
5828 li->li_tv.v_lock = 0;
5829 if (str == NULL)
5830 li->li_tv.vval.v_string = NULL;
5831 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
5832 : vim_strsave(str))) == NULL)
5833 return FAIL;
5834 return OK;
5838 * Append "n" to list "l".
5839 * Returns FAIL when out of memory.
5841 static int
5842 list_append_number(l, n)
5843 list_T *l;
5844 varnumber_T n;
5846 listitem_T *li;
5848 li = listitem_alloc();
5849 if (li == NULL)
5850 return FAIL;
5851 li->li_tv.v_type = VAR_NUMBER;
5852 li->li_tv.v_lock = 0;
5853 li->li_tv.vval.v_number = n;
5854 list_append(l, li);
5855 return OK;
5859 * Insert typval_T "tv" in list "l" before "item".
5860 * If "item" is NULL append at the end.
5861 * Return FAIL when out of memory.
5863 static int
5864 list_insert_tv(l, tv, item)
5865 list_T *l;
5866 typval_T *tv;
5867 listitem_T *item;
5869 listitem_T *ni = listitem_alloc();
5871 if (ni == NULL)
5872 return FAIL;
5873 copy_tv(tv, &ni->li_tv);
5874 if (item == NULL)
5875 /* Append new item at end of list. */
5876 list_append(l, ni);
5877 else
5879 /* Insert new item before existing item. */
5880 ni->li_prev = item->li_prev;
5881 ni->li_next = item;
5882 if (item->li_prev == NULL)
5884 l->lv_first = ni;
5885 ++l->lv_idx;
5887 else
5889 item->li_prev->li_next = ni;
5890 l->lv_idx_item = NULL;
5892 item->li_prev = ni;
5893 ++l->lv_len;
5895 return OK;
5899 * Extend "l1" with "l2".
5900 * If "bef" is NULL append at the end, otherwise insert before this item.
5901 * Returns FAIL when out of memory.
5903 static int
5904 list_extend(l1, l2, bef)
5905 list_T *l1;
5906 list_T *l2;
5907 listitem_T *bef;
5909 listitem_T *item;
5911 for (item = l2->lv_first; item != NULL; item = item->li_next)
5912 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
5913 return FAIL;
5914 return OK;
5918 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
5919 * Return FAIL when out of memory.
5921 static int
5922 list_concat(l1, l2, tv)
5923 list_T *l1;
5924 list_T *l2;
5925 typval_T *tv;
5927 list_T *l;
5929 /* make a copy of the first list. */
5930 l = list_copy(l1, FALSE, 0);
5931 if (l == NULL)
5932 return FAIL;
5933 tv->v_type = VAR_LIST;
5934 tv->vval.v_list = l;
5936 /* append all items from the second list */
5937 return list_extend(l, l2, NULL);
5941 * Make a copy of list "orig". Shallow if "deep" is FALSE.
5942 * The refcount of the new list is set to 1.
5943 * See item_copy() for "copyID".
5944 * Returns NULL when out of memory.
5946 static list_T *
5947 list_copy(orig, deep, copyID)
5948 list_T *orig;
5949 int deep;
5950 int copyID;
5952 list_T *copy;
5953 listitem_T *item;
5954 listitem_T *ni;
5956 if (orig == NULL)
5957 return NULL;
5959 copy = list_alloc();
5960 if (copy != NULL)
5962 if (copyID != 0)
5964 /* Do this before adding the items, because one of the items may
5965 * refer back to this list. */
5966 orig->lv_copyID = copyID;
5967 orig->lv_copylist = copy;
5969 for (item = orig->lv_first; item != NULL && !got_int;
5970 item = item->li_next)
5972 ni = listitem_alloc();
5973 if (ni == NULL)
5974 break;
5975 if (deep)
5977 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
5979 vim_free(ni);
5980 break;
5983 else
5984 copy_tv(&item->li_tv, &ni->li_tv);
5985 list_append(copy, ni);
5987 ++copy->lv_refcount;
5988 if (item != NULL)
5990 list_unref(copy);
5991 copy = NULL;
5995 return copy;
5999 * Remove items "item" to "item2" from list "l".
6000 * Does not free the listitem or the value!
6002 static void
6003 list_remove(l, item, item2)
6004 list_T *l;
6005 listitem_T *item;
6006 listitem_T *item2;
6008 listitem_T *ip;
6010 /* notify watchers */
6011 for (ip = item; ip != NULL; ip = ip->li_next)
6013 --l->lv_len;
6014 list_fix_watch(l, ip);
6015 if (ip == item2)
6016 break;
6019 if (item2->li_next == NULL)
6020 l->lv_last = item->li_prev;
6021 else
6022 item2->li_next->li_prev = item->li_prev;
6023 if (item->li_prev == NULL)
6024 l->lv_first = item2->li_next;
6025 else
6026 item->li_prev->li_next = item2->li_next;
6027 l->lv_idx_item = NULL;
6031 * Return an allocated string with the string representation of a list.
6032 * May return NULL.
6034 static char_u *
6035 list2string(tv, copyID)
6036 typval_T *tv;
6037 int copyID;
6039 garray_T ga;
6041 if (tv->vval.v_list == NULL)
6042 return NULL;
6043 ga_init2(&ga, (int)sizeof(char), 80);
6044 ga_append(&ga, '[');
6045 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6047 vim_free(ga.ga_data);
6048 return NULL;
6050 ga_append(&ga, ']');
6051 ga_append(&ga, NUL);
6052 return (char_u *)ga.ga_data;
6056 * Join list "l" into a string in "*gap", using separator "sep".
6057 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6058 * Return FAIL or OK.
6060 static int
6061 list_join(gap, l, sep, echo, copyID)
6062 garray_T *gap;
6063 list_T *l;
6064 char_u *sep;
6065 int echo;
6066 int copyID;
6068 int first = TRUE;
6069 char_u *tofree;
6070 char_u numbuf[NUMBUFLEN];
6071 listitem_T *item;
6072 char_u *s;
6074 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6076 if (first)
6077 first = FALSE;
6078 else
6079 ga_concat(gap, sep);
6081 if (echo)
6082 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6083 else
6084 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6085 if (s != NULL)
6086 ga_concat(gap, s);
6087 vim_free(tofree);
6088 if (s == NULL)
6089 return FAIL;
6091 return OK;
6095 * Garbage collection for lists and dictionaries.
6097 * We use reference counts to be able to free most items right away when they
6098 * are no longer used. But for composite items it's possible that it becomes
6099 * unused while the reference count is > 0: When there is a recursive
6100 * reference. Example:
6101 * :let l = [1, 2, 3]
6102 * :let d = {9: l}
6103 * :let l[1] = d
6105 * Since this is quite unusual we handle this with garbage collection: every
6106 * once in a while find out which lists and dicts are not referenced from any
6107 * variable.
6109 * Here is a good reference text about garbage collection (refers to Python
6110 * but it applies to all reference-counting mechanisms):
6111 * http://python.ca/nas/python/gc/
6115 * Do garbage collection for lists and dicts.
6116 * Return TRUE if some memory was freed.
6119 garbage_collect()
6121 dict_T *dd;
6122 list_T *ll;
6123 int copyID = ++current_copyID;
6124 buf_T *buf;
6125 win_T *wp;
6126 int i;
6127 funccall_T *fc;
6128 int did_free = FALSE;
6129 #ifdef FEAT_WINDOWS
6130 tabpage_T *tp;
6131 #endif
6133 /* Only do this once. */
6134 want_garbage_collect = FALSE;
6135 may_garbage_collect = FALSE;
6136 garbage_collect_at_exit = FALSE;
6139 * 1. Go through all accessible variables and mark all lists and dicts
6140 * with copyID.
6142 /* script-local variables */
6143 for (i = 1; i <= ga_scripts.ga_len; ++i)
6144 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6146 /* buffer-local variables */
6147 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6148 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6150 /* window-local variables */
6151 FOR_ALL_TAB_WINDOWS(tp, wp)
6152 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6154 #ifdef FEAT_WINDOWS
6155 /* tabpage-local variables */
6156 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6157 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6158 #endif
6160 /* global variables */
6161 set_ref_in_ht(&globvarht, copyID);
6163 /* function-local variables */
6164 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6166 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6167 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6171 * 2. Go through the list of dicts and free items without the copyID.
6173 for (dd = first_dict; dd != NULL; )
6174 if (dd->dv_copyID != copyID)
6176 /* Free the Dictionary and ordinary items it contains, but don't
6177 * recurse into Lists and Dictionaries, they will be in the list
6178 * of dicts or list of lists. */
6179 dict_free(dd, FALSE);
6180 did_free = TRUE;
6182 /* restart, next dict may also have been freed */
6183 dd = first_dict;
6185 else
6186 dd = dd->dv_used_next;
6189 * 3. Go through the list of lists and free items without the copyID.
6190 * But don't free a list that has a watcher (used in a for loop), these
6191 * are not referenced anywhere.
6193 for (ll = first_list; ll != NULL; )
6194 if (ll->lv_copyID != copyID && ll->lv_watch == NULL)
6196 /* Free the List and ordinary items it contains, but don't recurse
6197 * into Lists and Dictionaries, they will be in the list of dicts
6198 * or list of lists. */
6199 list_free(ll, FALSE);
6200 did_free = TRUE;
6202 /* restart, next list may also have been freed */
6203 ll = first_list;
6205 else
6206 ll = ll->lv_used_next;
6208 return did_free;
6212 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6214 static void
6215 set_ref_in_ht(ht, copyID)
6216 hashtab_T *ht;
6217 int copyID;
6219 int todo;
6220 hashitem_T *hi;
6222 todo = (int)ht->ht_used;
6223 for (hi = ht->ht_array; todo > 0; ++hi)
6224 if (!HASHITEM_EMPTY(hi))
6226 --todo;
6227 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6232 * Mark all lists and dicts referenced through list "l" with "copyID".
6234 static void
6235 set_ref_in_list(l, copyID)
6236 list_T *l;
6237 int copyID;
6239 listitem_T *li;
6241 for (li = l->lv_first; li != NULL; li = li->li_next)
6242 set_ref_in_item(&li->li_tv, copyID);
6246 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6248 static void
6249 set_ref_in_item(tv, copyID)
6250 typval_T *tv;
6251 int copyID;
6253 dict_T *dd;
6254 list_T *ll;
6256 switch (tv->v_type)
6258 case VAR_DICT:
6259 dd = tv->vval.v_dict;
6260 if (dd->dv_copyID != copyID)
6262 /* Didn't see this dict yet. */
6263 dd->dv_copyID = copyID;
6264 set_ref_in_ht(&dd->dv_hashtab, copyID);
6266 break;
6268 case VAR_LIST:
6269 ll = tv->vval.v_list;
6270 if (ll->lv_copyID != copyID)
6272 /* Didn't see this list yet. */
6273 ll->lv_copyID = copyID;
6274 set_ref_in_list(ll, copyID);
6276 break;
6278 return;
6282 * Allocate an empty header for a dictionary.
6284 dict_T *
6285 dict_alloc()
6287 dict_T *d;
6289 d = (dict_T *)alloc(sizeof(dict_T));
6290 if (d != NULL)
6292 /* Add the list to the list of dicts for garbage collection. */
6293 if (first_dict != NULL)
6294 first_dict->dv_used_prev = d;
6295 d->dv_used_next = first_dict;
6296 d->dv_used_prev = NULL;
6297 first_dict = d;
6299 hash_init(&d->dv_hashtab);
6300 d->dv_lock = 0;
6301 d->dv_refcount = 0;
6302 d->dv_copyID = 0;
6304 return d;
6308 * Unreference a Dictionary: decrement the reference count and free it when it
6309 * becomes zero.
6311 static void
6312 dict_unref(d)
6313 dict_T *d;
6315 if (d != NULL && --d->dv_refcount <= 0)
6316 dict_free(d, TRUE);
6320 * Free a Dictionary, including all items it contains.
6321 * Ignores the reference count.
6323 static void
6324 dict_free(d, recurse)
6325 dict_T *d;
6326 int recurse; /* Free Lists and Dictionaries recursively. */
6328 int todo;
6329 hashitem_T *hi;
6330 dictitem_T *di;
6332 /* Remove the dict from the list of dicts for garbage collection. */
6333 if (d->dv_used_prev == NULL)
6334 first_dict = d->dv_used_next;
6335 else
6336 d->dv_used_prev->dv_used_next = d->dv_used_next;
6337 if (d->dv_used_next != NULL)
6338 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6340 /* Lock the hashtab, we don't want it to resize while freeing items. */
6341 hash_lock(&d->dv_hashtab);
6342 todo = (int)d->dv_hashtab.ht_used;
6343 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6345 if (!HASHITEM_EMPTY(hi))
6347 /* Remove the item before deleting it, just in case there is
6348 * something recursive causing trouble. */
6349 di = HI2DI(hi);
6350 hash_remove(&d->dv_hashtab, hi);
6351 if (recurse || (di->di_tv.v_type != VAR_LIST
6352 && di->di_tv.v_type != VAR_DICT))
6353 clear_tv(&di->di_tv);
6354 vim_free(di);
6355 --todo;
6358 hash_clear(&d->dv_hashtab);
6359 vim_free(d);
6363 * Allocate a Dictionary item.
6364 * The "key" is copied to the new item.
6365 * Note that the value of the item "di_tv" still needs to be initialized!
6366 * Returns NULL when out of memory.
6368 static dictitem_T *
6369 dictitem_alloc(key)
6370 char_u *key;
6372 dictitem_T *di;
6374 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6375 if (di != NULL)
6377 STRCPY(di->di_key, key);
6378 di->di_flags = 0;
6380 return di;
6384 * Make a copy of a Dictionary item.
6386 static dictitem_T *
6387 dictitem_copy(org)
6388 dictitem_T *org;
6390 dictitem_T *di;
6392 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6393 + STRLEN(org->di_key)));
6394 if (di != NULL)
6396 STRCPY(di->di_key, org->di_key);
6397 di->di_flags = 0;
6398 copy_tv(&org->di_tv, &di->di_tv);
6400 return di;
6404 * Remove item "item" from Dictionary "dict" and free it.
6406 static void
6407 dictitem_remove(dict, item)
6408 dict_T *dict;
6409 dictitem_T *item;
6411 hashitem_T *hi;
6413 hi = hash_find(&dict->dv_hashtab, item->di_key);
6414 if (HASHITEM_EMPTY(hi))
6415 EMSG2(_(e_intern2), "dictitem_remove()");
6416 else
6417 hash_remove(&dict->dv_hashtab, hi);
6418 dictitem_free(item);
6422 * Free a dict item. Also clears the value.
6424 static void
6425 dictitem_free(item)
6426 dictitem_T *item;
6428 clear_tv(&item->di_tv);
6429 vim_free(item);
6433 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6434 * The refcount of the new dict is set to 1.
6435 * See item_copy() for "copyID".
6436 * Returns NULL when out of memory.
6438 static dict_T *
6439 dict_copy(orig, deep, copyID)
6440 dict_T *orig;
6441 int deep;
6442 int copyID;
6444 dict_T *copy;
6445 dictitem_T *di;
6446 int todo;
6447 hashitem_T *hi;
6449 if (orig == NULL)
6450 return NULL;
6452 copy = dict_alloc();
6453 if (copy != NULL)
6455 if (copyID != 0)
6457 orig->dv_copyID = copyID;
6458 orig->dv_copydict = copy;
6460 todo = (int)orig->dv_hashtab.ht_used;
6461 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6463 if (!HASHITEM_EMPTY(hi))
6465 --todo;
6467 di = dictitem_alloc(hi->hi_key);
6468 if (di == NULL)
6469 break;
6470 if (deep)
6472 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6473 copyID) == FAIL)
6475 vim_free(di);
6476 break;
6479 else
6480 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6481 if (dict_add(copy, di) == FAIL)
6483 dictitem_free(di);
6484 break;
6489 ++copy->dv_refcount;
6490 if (todo > 0)
6492 dict_unref(copy);
6493 copy = NULL;
6497 return copy;
6501 * Add item "item" to Dictionary "d".
6502 * Returns FAIL when out of memory and when key already existed.
6504 static int
6505 dict_add(d, item)
6506 dict_T *d;
6507 dictitem_T *item;
6509 return hash_add(&d->dv_hashtab, item->di_key);
6513 * Add a number or string entry to dictionary "d".
6514 * When "str" is NULL use number "nr", otherwise use "str".
6515 * Returns FAIL when out of memory and when key already exists.
6518 dict_add_nr_str(d, key, nr, str)
6519 dict_T *d;
6520 char *key;
6521 long nr;
6522 char_u *str;
6524 dictitem_T *item;
6526 item = dictitem_alloc((char_u *)key);
6527 if (item == NULL)
6528 return FAIL;
6529 item->di_tv.v_lock = 0;
6530 if (str == NULL)
6532 item->di_tv.v_type = VAR_NUMBER;
6533 item->di_tv.vval.v_number = nr;
6535 else
6537 item->di_tv.v_type = VAR_STRING;
6538 item->di_tv.vval.v_string = vim_strsave(str);
6540 if (dict_add(d, item) == FAIL)
6542 dictitem_free(item);
6543 return FAIL;
6545 return OK;
6549 * Get the number of items in a Dictionary.
6551 static long
6552 dict_len(d)
6553 dict_T *d;
6555 if (d == NULL)
6556 return 0L;
6557 return (long)d->dv_hashtab.ht_used;
6561 * Find item "key[len]" in Dictionary "d".
6562 * If "len" is negative use strlen(key).
6563 * Returns NULL when not found.
6565 static dictitem_T *
6566 dict_find(d, key, len)
6567 dict_T *d;
6568 char_u *key;
6569 int len;
6571 #define AKEYLEN 200
6572 char_u buf[AKEYLEN];
6573 char_u *akey;
6574 char_u *tofree = NULL;
6575 hashitem_T *hi;
6577 if (len < 0)
6578 akey = key;
6579 else if (len >= AKEYLEN)
6581 tofree = akey = vim_strnsave(key, len);
6582 if (akey == NULL)
6583 return NULL;
6585 else
6587 /* Avoid a malloc/free by using buf[]. */
6588 vim_strncpy(buf, key, len);
6589 akey = buf;
6592 hi = hash_find(&d->dv_hashtab, akey);
6593 vim_free(tofree);
6594 if (HASHITEM_EMPTY(hi))
6595 return NULL;
6596 return HI2DI(hi);
6600 * Get a string item from a dictionary.
6601 * When "save" is TRUE allocate memory for it.
6602 * Returns NULL if the entry doesn't exist or out of memory.
6604 char_u *
6605 get_dict_string(d, key, save)
6606 dict_T *d;
6607 char_u *key;
6608 int save;
6610 dictitem_T *di;
6611 char_u *s;
6613 di = dict_find(d, key, -1);
6614 if (di == NULL)
6615 return NULL;
6616 s = get_tv_string(&di->di_tv);
6617 if (save && s != NULL)
6618 s = vim_strsave(s);
6619 return s;
6623 * Get a number item from a dictionary.
6624 * Returns 0 if the entry doesn't exist or out of memory.
6626 long
6627 get_dict_number(d, key)
6628 dict_T *d;
6629 char_u *key;
6631 dictitem_T *di;
6633 di = dict_find(d, key, -1);
6634 if (di == NULL)
6635 return 0;
6636 return get_tv_number(&di->di_tv);
6640 * Return an allocated string with the string representation of a Dictionary.
6641 * May return NULL.
6643 static char_u *
6644 dict2string(tv, copyID)
6645 typval_T *tv;
6646 int copyID;
6648 garray_T ga;
6649 int first = TRUE;
6650 char_u *tofree;
6651 char_u numbuf[NUMBUFLEN];
6652 hashitem_T *hi;
6653 char_u *s;
6654 dict_T *d;
6655 int todo;
6657 if ((d = tv->vval.v_dict) == NULL)
6658 return NULL;
6659 ga_init2(&ga, (int)sizeof(char), 80);
6660 ga_append(&ga, '{');
6662 todo = (int)d->dv_hashtab.ht_used;
6663 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6665 if (!HASHITEM_EMPTY(hi))
6667 --todo;
6669 if (first)
6670 first = FALSE;
6671 else
6672 ga_concat(&ga, (char_u *)", ");
6674 tofree = string_quote(hi->hi_key, FALSE);
6675 if (tofree != NULL)
6677 ga_concat(&ga, tofree);
6678 vim_free(tofree);
6680 ga_concat(&ga, (char_u *)": ");
6681 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
6682 if (s != NULL)
6683 ga_concat(&ga, s);
6684 vim_free(tofree);
6685 if (s == NULL)
6686 break;
6689 if (todo > 0)
6691 vim_free(ga.ga_data);
6692 return NULL;
6695 ga_append(&ga, '}');
6696 ga_append(&ga, NUL);
6697 return (char_u *)ga.ga_data;
6701 * Allocate a variable for a Dictionary and fill it from "*arg".
6702 * Return OK or FAIL. Returns NOTDONE for {expr}.
6704 static int
6705 get_dict_tv(arg, rettv, evaluate)
6706 char_u **arg;
6707 typval_T *rettv;
6708 int evaluate;
6710 dict_T *d = NULL;
6711 typval_T tvkey;
6712 typval_T tv;
6713 char_u *key = NULL;
6714 dictitem_T *item;
6715 char_u *start = skipwhite(*arg + 1);
6716 char_u buf[NUMBUFLEN];
6719 * First check if it's not a curly-braces thing: {expr}.
6720 * Must do this without evaluating, otherwise a function may be called
6721 * twice. Unfortunately this means we need to call eval1() twice for the
6722 * first item.
6723 * But {} is an empty Dictionary.
6725 if (*start != '}')
6727 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
6728 return FAIL;
6729 if (*start == '}')
6730 return NOTDONE;
6733 if (evaluate)
6735 d = dict_alloc();
6736 if (d == NULL)
6737 return FAIL;
6739 tvkey.v_type = VAR_UNKNOWN;
6740 tv.v_type = VAR_UNKNOWN;
6742 *arg = skipwhite(*arg + 1);
6743 while (**arg != '}' && **arg != NUL)
6745 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
6746 goto failret;
6747 if (**arg != ':')
6749 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
6750 clear_tv(&tvkey);
6751 goto failret;
6753 if (evaluate)
6755 key = get_tv_string_buf_chk(&tvkey, buf);
6756 if (key == NULL || *key == NUL)
6758 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
6759 if (key != NULL)
6760 EMSG(_(e_emptykey));
6761 clear_tv(&tvkey);
6762 goto failret;
6766 *arg = skipwhite(*arg + 1);
6767 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
6769 if (evaluate)
6770 clear_tv(&tvkey);
6771 goto failret;
6773 if (evaluate)
6775 item = dict_find(d, key, -1);
6776 if (item != NULL)
6778 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
6779 clear_tv(&tvkey);
6780 clear_tv(&tv);
6781 goto failret;
6783 item = dictitem_alloc(key);
6784 clear_tv(&tvkey);
6785 if (item != NULL)
6787 item->di_tv = tv;
6788 item->di_tv.v_lock = 0;
6789 if (dict_add(d, item) == FAIL)
6790 dictitem_free(item);
6794 if (**arg == '}')
6795 break;
6796 if (**arg != ',')
6798 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
6799 goto failret;
6801 *arg = skipwhite(*arg + 1);
6804 if (**arg != '}')
6806 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
6807 failret:
6808 if (evaluate)
6809 dict_free(d, TRUE);
6810 return FAIL;
6813 *arg = skipwhite(*arg + 1);
6814 if (evaluate)
6816 rettv->v_type = VAR_DICT;
6817 rettv->vval.v_dict = d;
6818 ++d->dv_refcount;
6821 return OK;
6825 * Return a string with the string representation of a variable.
6826 * If the memory is allocated "tofree" is set to it, otherwise NULL.
6827 * "numbuf" is used for a number.
6828 * Does not put quotes around strings, as ":echo" displays values.
6829 * When "copyID" is not NULL replace recursive lists and dicts with "...".
6830 * May return NULL.
6832 static char_u *
6833 echo_string(tv, tofree, numbuf, copyID)
6834 typval_T *tv;
6835 char_u **tofree;
6836 char_u *numbuf;
6837 int copyID;
6839 static int recurse = 0;
6840 char_u *r = NULL;
6842 if (recurse >= DICT_MAXNEST)
6844 EMSG(_("E724: variable nested too deep for displaying"));
6845 *tofree = NULL;
6846 return NULL;
6848 ++recurse;
6850 switch (tv->v_type)
6852 case VAR_FUNC:
6853 *tofree = NULL;
6854 r = tv->vval.v_string;
6855 break;
6857 case VAR_LIST:
6858 if (tv->vval.v_list == NULL)
6860 *tofree = NULL;
6861 r = NULL;
6863 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
6865 *tofree = NULL;
6866 r = (char_u *)"[...]";
6868 else
6870 tv->vval.v_list->lv_copyID = copyID;
6871 *tofree = list2string(tv, copyID);
6872 r = *tofree;
6874 break;
6876 case VAR_DICT:
6877 if (tv->vval.v_dict == NULL)
6879 *tofree = NULL;
6880 r = NULL;
6882 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
6884 *tofree = NULL;
6885 r = (char_u *)"{...}";
6887 else
6889 tv->vval.v_dict->dv_copyID = copyID;
6890 *tofree = dict2string(tv, copyID);
6891 r = *tofree;
6893 break;
6895 case VAR_STRING:
6896 case VAR_NUMBER:
6897 *tofree = NULL;
6898 r = get_tv_string_buf(tv, numbuf);
6899 break;
6901 default:
6902 EMSG2(_(e_intern2), "echo_string()");
6903 *tofree = NULL;
6906 --recurse;
6907 return r;
6911 * Return a string with the string representation of a variable.
6912 * If the memory is allocated "tofree" is set to it, otherwise NULL.
6913 * "numbuf" is used for a number.
6914 * Puts quotes around strings, so that they can be parsed back by eval().
6915 * May return NULL.
6917 static char_u *
6918 tv2string(tv, tofree, numbuf, copyID)
6919 typval_T *tv;
6920 char_u **tofree;
6921 char_u *numbuf;
6922 int copyID;
6924 switch (tv->v_type)
6926 case VAR_FUNC:
6927 *tofree = string_quote(tv->vval.v_string, TRUE);
6928 return *tofree;
6929 case VAR_STRING:
6930 *tofree = string_quote(tv->vval.v_string, FALSE);
6931 return *tofree;
6932 case VAR_NUMBER:
6933 case VAR_LIST:
6934 case VAR_DICT:
6935 break;
6936 default:
6937 EMSG2(_(e_intern2), "tv2string()");
6939 return echo_string(tv, tofree, numbuf, copyID);
6943 * Return string "str" in ' quotes, doubling ' characters.
6944 * If "str" is NULL an empty string is assumed.
6945 * If "function" is TRUE make it function('string').
6947 static char_u *
6948 string_quote(str, function)
6949 char_u *str;
6950 int function;
6952 unsigned len;
6953 char_u *p, *r, *s;
6955 len = (function ? 13 : 3);
6956 if (str != NULL)
6958 len += (unsigned)STRLEN(str);
6959 for (p = str; *p != NUL; mb_ptr_adv(p))
6960 if (*p == '\'')
6961 ++len;
6963 s = r = alloc(len);
6964 if (r != NULL)
6966 if (function)
6968 STRCPY(r, "function('");
6969 r += 10;
6971 else
6972 *r++ = '\'';
6973 if (str != NULL)
6974 for (p = str; *p != NUL; )
6976 if (*p == '\'')
6977 *r++ = '\'';
6978 MB_COPY_CHAR(p, r);
6980 *r++ = '\'';
6981 if (function)
6982 *r++ = ')';
6983 *r++ = NUL;
6985 return s;
6989 * Get the value of an environment variable.
6990 * "arg" is pointing to the '$'. It is advanced to after the name.
6991 * If the environment variable was not set, silently assume it is empty.
6992 * Always return OK.
6994 static int
6995 get_env_tv(arg, rettv, evaluate)
6996 char_u **arg;
6997 typval_T *rettv;
6998 int evaluate;
7000 char_u *string = NULL;
7001 int len;
7002 int cc;
7003 char_u *name;
7004 int mustfree = FALSE;
7006 ++*arg;
7007 name = *arg;
7008 len = get_env_len(arg);
7009 if (evaluate)
7011 if (len != 0)
7013 cc = name[len];
7014 name[len] = NUL;
7015 /* first try vim_getenv(), fast for normal environment vars */
7016 string = vim_getenv(name, &mustfree);
7017 if (string != NULL && *string != NUL)
7019 if (!mustfree)
7020 string = vim_strsave(string);
7022 else
7024 if (mustfree)
7025 vim_free(string);
7027 /* next try expanding things like $VIM and ${HOME} */
7028 string = expand_env_save(name - 1);
7029 if (string != NULL && *string == '$')
7031 vim_free(string);
7032 string = NULL;
7035 name[len] = cc;
7037 rettv->v_type = VAR_STRING;
7038 rettv->vval.v_string = string;
7041 return OK;
7045 * Array with names and number of arguments of all internal functions
7046 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7048 static struct fst
7050 char *f_name; /* function name */
7051 char f_min_argc; /* minimal number of arguments */
7052 char f_max_argc; /* maximal number of arguments */
7053 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7054 /* implementation of function */
7055 } functions[] =
7057 {"add", 2, 2, f_add},
7058 {"append", 2, 2, f_append},
7059 {"argc", 0, 0, f_argc},
7060 {"argidx", 0, 0, f_argidx},
7061 {"argv", 0, 1, f_argv},
7062 {"browse", 4, 4, f_browse},
7063 {"browsedir", 2, 2, f_browsedir},
7064 {"bufexists", 1, 1, f_bufexists},
7065 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7066 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7067 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7068 {"buflisted", 1, 1, f_buflisted},
7069 {"bufloaded", 1, 1, f_bufloaded},
7070 {"bufname", 1, 1, f_bufname},
7071 {"bufnr", 1, 2, f_bufnr},
7072 {"bufwinnr", 1, 1, f_bufwinnr},
7073 {"byte2line", 1, 1, f_byte2line},
7074 {"byteidx", 2, 2, f_byteidx},
7075 {"call", 2, 3, f_call},
7076 {"changenr", 0, 0, f_changenr},
7077 {"char2nr", 1, 1, f_char2nr},
7078 {"cindent", 1, 1, f_cindent},
7079 {"clearmatches", 0, 0, f_clearmatches},
7080 {"col", 1, 1, f_col},
7081 #if defined(FEAT_INS_EXPAND)
7082 {"complete", 2, 2, f_complete},
7083 {"complete_add", 1, 1, f_complete_add},
7084 {"complete_check", 0, 0, f_complete_check},
7085 #endif
7086 {"confirm", 1, 4, f_confirm},
7087 {"copy", 1, 1, f_copy},
7088 {"count", 2, 4, f_count},
7089 {"cscope_connection",0,3, f_cscope_connection},
7090 {"cursor", 1, 3, f_cursor},
7091 {"deepcopy", 1, 2, f_deepcopy},
7092 {"delete", 1, 1, f_delete},
7093 {"did_filetype", 0, 0, f_did_filetype},
7094 {"diff_filler", 1, 1, f_diff_filler},
7095 {"diff_hlID", 2, 2, f_diff_hlID},
7096 {"empty", 1, 1, f_empty},
7097 {"escape", 2, 2, f_escape},
7098 {"eval", 1, 1, f_eval},
7099 {"eventhandler", 0, 0, f_eventhandler},
7100 {"executable", 1, 1, f_executable},
7101 {"exists", 1, 1, f_exists},
7102 {"expand", 1, 2, f_expand},
7103 {"extend", 2, 3, f_extend},
7104 {"feedkeys", 1, 2, f_feedkeys},
7105 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7106 {"filereadable", 1, 1, f_filereadable},
7107 {"filewritable", 1, 1, f_filewritable},
7108 {"filter", 2, 2, f_filter},
7109 {"finddir", 1, 3, f_finddir},
7110 {"findfile", 1, 3, f_findfile},
7111 {"fnameescape", 1, 1, f_fnameescape},
7112 {"fnamemodify", 2, 2, f_fnamemodify},
7113 {"foldclosed", 1, 1, f_foldclosed},
7114 {"foldclosedend", 1, 1, f_foldclosedend},
7115 {"foldlevel", 1, 1, f_foldlevel},
7116 {"foldtext", 0, 0, f_foldtext},
7117 {"foldtextresult", 1, 1, f_foldtextresult},
7118 {"foreground", 0, 0, f_foreground},
7119 {"function", 1, 1, f_function},
7120 {"garbagecollect", 0, 1, f_garbagecollect},
7121 {"get", 2, 3, f_get},
7122 {"getbufline", 2, 3, f_getbufline},
7123 {"getbufvar", 2, 2, f_getbufvar},
7124 {"getchar", 0, 1, f_getchar},
7125 {"getcharmod", 0, 0, f_getcharmod},
7126 {"getcmdline", 0, 0, f_getcmdline},
7127 {"getcmdpos", 0, 0, f_getcmdpos},
7128 {"getcmdtype", 0, 0, f_getcmdtype},
7129 {"getcwd", 0, 0, f_getcwd},
7130 {"getfontname", 0, 1, f_getfontname},
7131 {"getfperm", 1, 1, f_getfperm},
7132 {"getfsize", 1, 1, f_getfsize},
7133 {"getftime", 1, 1, f_getftime},
7134 {"getftype", 1, 1, f_getftype},
7135 {"getline", 1, 2, f_getline},
7136 {"getloclist", 1, 1, f_getqflist},
7137 {"getmatches", 0, 0, f_getmatches},
7138 {"getpid", 0, 0, f_getpid},
7139 {"getpos", 1, 1, f_getpos},
7140 {"getqflist", 0, 0, f_getqflist},
7141 {"getreg", 0, 2, f_getreg},
7142 {"getregtype", 0, 1, f_getregtype},
7143 {"gettabwinvar", 3, 3, f_gettabwinvar},
7144 {"getwinposx", 0, 0, f_getwinposx},
7145 {"getwinposy", 0, 0, f_getwinposy},
7146 {"getwinvar", 2, 2, f_getwinvar},
7147 {"glob", 1, 1, f_glob},
7148 {"globpath", 2, 2, f_globpath},
7149 {"has", 1, 1, f_has},
7150 {"has_key", 2, 2, f_has_key},
7151 {"haslocaldir", 0, 0, f_haslocaldir},
7152 {"hasmapto", 1, 3, f_hasmapto},
7153 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7154 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7155 {"histadd", 2, 2, f_histadd},
7156 {"histdel", 1, 2, f_histdel},
7157 {"histget", 1, 2, f_histget},
7158 {"histnr", 1, 1, f_histnr},
7159 {"hlID", 1, 1, f_hlID},
7160 {"hlexists", 1, 1, f_hlexists},
7161 {"hostname", 0, 0, f_hostname},
7162 {"iconv", 3, 3, f_iconv},
7163 {"indent", 1, 1, f_indent},
7164 {"index", 2, 4, f_index},
7165 {"input", 1, 3, f_input},
7166 {"inputdialog", 1, 3, f_inputdialog},
7167 {"inputlist", 1, 1, f_inputlist},
7168 {"inputrestore", 0, 0, f_inputrestore},
7169 {"inputsave", 0, 0, f_inputsave},
7170 {"inputsecret", 1, 2, f_inputsecret},
7171 {"insert", 2, 3, f_insert},
7172 {"isdirectory", 1, 1, f_isdirectory},
7173 {"islocked", 1, 1, f_islocked},
7174 {"items", 1, 1, f_items},
7175 {"join", 1, 2, f_join},
7176 {"keys", 1, 1, f_keys},
7177 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7178 {"len", 1, 1, f_len},
7179 {"libcall", 3, 3, f_libcall},
7180 {"libcallnr", 3, 3, f_libcallnr},
7181 {"line", 1, 1, f_line},
7182 {"line2byte", 1, 1, f_line2byte},
7183 {"lispindent", 1, 1, f_lispindent},
7184 {"localtime", 0, 0, f_localtime},
7185 {"map", 2, 2, f_map},
7186 {"maparg", 1, 3, f_maparg},
7187 {"mapcheck", 1, 3, f_mapcheck},
7188 {"match", 2, 4, f_match},
7189 {"matchadd", 2, 4, f_matchadd},
7190 {"matcharg", 1, 1, f_matcharg},
7191 {"matchdelete", 1, 1, f_matchdelete},
7192 {"matchend", 2, 4, f_matchend},
7193 {"matchlist", 2, 4, f_matchlist},
7194 {"matchstr", 2, 4, f_matchstr},
7195 {"max", 1, 1, f_max},
7196 {"min", 1, 1, f_min},
7197 #ifdef vim_mkdir
7198 {"mkdir", 1, 3, f_mkdir},
7199 #endif
7200 {"mode", 0, 0, f_mode},
7201 {"nextnonblank", 1, 1, f_nextnonblank},
7202 {"nr2char", 1, 1, f_nr2char},
7203 {"pathshorten", 1, 1, f_pathshorten},
7204 {"prevnonblank", 1, 1, f_prevnonblank},
7205 {"printf", 2, 19, f_printf},
7206 {"pumvisible", 0, 0, f_pumvisible},
7207 {"range", 1, 3, f_range},
7208 {"readfile", 1, 3, f_readfile},
7209 {"reltime", 0, 2, f_reltime},
7210 {"reltimestr", 1, 1, f_reltimestr},
7211 {"remote_expr", 2, 3, f_remote_expr},
7212 {"remote_foreground", 1, 1, f_remote_foreground},
7213 {"remote_peek", 1, 2, f_remote_peek},
7214 {"remote_read", 1, 1, f_remote_read},
7215 {"remote_send", 2, 3, f_remote_send},
7216 {"remove", 2, 3, f_remove},
7217 {"rename", 2, 2, f_rename},
7218 {"repeat", 2, 2, f_repeat},
7219 {"resolve", 1, 1, f_resolve},
7220 {"reverse", 1, 1, f_reverse},
7221 {"search", 1, 4, f_search},
7222 {"searchdecl", 1, 3, f_searchdecl},
7223 {"searchpair", 3, 7, f_searchpair},
7224 {"searchpairpos", 3, 7, f_searchpairpos},
7225 {"searchpos", 1, 4, f_searchpos},
7226 {"server2client", 2, 2, f_server2client},
7227 {"serverlist", 0, 0, f_serverlist},
7228 {"setbufvar", 3, 3, f_setbufvar},
7229 {"setcmdpos", 1, 1, f_setcmdpos},
7230 {"setline", 2, 2, f_setline},
7231 {"setloclist", 2, 3, f_setloclist},
7232 {"setmatches", 1, 1, f_setmatches},
7233 {"setpos", 2, 2, f_setpos},
7234 {"setqflist", 1, 2, f_setqflist},
7235 {"setreg", 2, 3, f_setreg},
7236 {"settabwinvar", 4, 4, f_settabwinvar},
7237 {"setwinvar", 3, 3, f_setwinvar},
7238 {"shellescape", 1, 1, f_shellescape},
7239 {"simplify", 1, 1, f_simplify},
7240 {"sort", 1, 2, f_sort},
7241 {"soundfold", 1, 1, f_soundfold},
7242 {"spellbadword", 0, 1, f_spellbadword},
7243 {"spellsuggest", 1, 3, f_spellsuggest},
7244 {"split", 1, 3, f_split},
7245 {"str2nr", 1, 2, f_str2nr},
7246 #ifdef HAVE_STRFTIME
7247 {"strftime", 1, 2, f_strftime},
7248 #endif
7249 {"stridx", 2, 3, f_stridx},
7250 {"string", 1, 1, f_string},
7251 {"strlen", 1, 1, f_strlen},
7252 {"strpart", 2, 3, f_strpart},
7253 {"strridx", 2, 3, f_strridx},
7254 {"strtrans", 1, 1, f_strtrans},
7255 {"submatch", 1, 1, f_submatch},
7256 {"substitute", 4, 4, f_substitute},
7257 {"synID", 3, 3, f_synID},
7258 {"synIDattr", 2, 3, f_synIDattr},
7259 {"synIDtrans", 1, 1, f_synIDtrans},
7260 {"synstack", 2, 2, f_synstack},
7261 {"system", 1, 2, f_system},
7262 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7263 {"tabpagenr", 0, 1, f_tabpagenr},
7264 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7265 {"tagfiles", 0, 0, f_tagfiles},
7266 {"taglist", 1, 1, f_taglist},
7267 {"tempname", 0, 0, f_tempname},
7268 {"test", 1, 1, f_test},
7269 {"tolower", 1, 1, f_tolower},
7270 {"toupper", 1, 1, f_toupper},
7271 {"tr", 3, 3, f_tr},
7272 {"type", 1, 1, f_type},
7273 {"values", 1, 1, f_values},
7274 {"virtcol", 1, 1, f_virtcol},
7275 {"visualmode", 0, 1, f_visualmode},
7276 {"winbufnr", 1, 1, f_winbufnr},
7277 {"wincol", 0, 0, f_wincol},
7278 {"winheight", 1, 1, f_winheight},
7279 {"winline", 0, 0, f_winline},
7280 {"winnr", 0, 1, f_winnr},
7281 {"winrestcmd", 0, 0, f_winrestcmd},
7282 {"winrestview", 1, 1, f_winrestview},
7283 {"winsaveview", 0, 0, f_winsaveview},
7284 {"winwidth", 1, 1, f_winwidth},
7285 {"writefile", 2, 3, f_writefile},
7288 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7291 * Function given to ExpandGeneric() to obtain the list of internal
7292 * or user defined function names.
7294 char_u *
7295 get_function_name(xp, idx)
7296 expand_T *xp;
7297 int idx;
7299 static int intidx = -1;
7300 char_u *name;
7302 if (idx == 0)
7303 intidx = -1;
7304 if (intidx < 0)
7306 name = get_user_func_name(xp, idx);
7307 if (name != NULL)
7308 return name;
7310 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7312 STRCPY(IObuff, functions[intidx].f_name);
7313 STRCAT(IObuff, "(");
7314 if (functions[intidx].f_max_argc == 0)
7315 STRCAT(IObuff, ")");
7316 return IObuff;
7319 return NULL;
7323 * Function given to ExpandGeneric() to obtain the list of internal or
7324 * user defined variable or function names.
7326 /*ARGSUSED*/
7327 char_u *
7328 get_expr_name(xp, idx)
7329 expand_T *xp;
7330 int idx;
7332 static int intidx = -1;
7333 char_u *name;
7335 if (idx == 0)
7336 intidx = -1;
7337 if (intidx < 0)
7339 name = get_function_name(xp, idx);
7340 if (name != NULL)
7341 return name;
7343 return get_user_var_name(xp, ++intidx);
7346 #endif /* FEAT_CMDL_COMPL */
7349 * Find internal function in table above.
7350 * Return index, or -1 if not found
7352 static int
7353 find_internal_func(name)
7354 char_u *name; /* name of the function */
7356 int first = 0;
7357 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7358 int cmp;
7359 int x;
7362 * Find the function name in the table. Binary search.
7364 while (first <= last)
7366 x = first + ((unsigned)(last - first) >> 1);
7367 cmp = STRCMP(name, functions[x].f_name);
7368 if (cmp < 0)
7369 last = x - 1;
7370 else if (cmp > 0)
7371 first = x + 1;
7372 else
7373 return x;
7375 return -1;
7379 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7380 * name it contains, otherwise return "name".
7382 static char_u *
7383 deref_func_name(name, lenp)
7384 char_u *name;
7385 int *lenp;
7387 dictitem_T *v;
7388 int cc;
7390 cc = name[*lenp];
7391 name[*lenp] = NUL;
7392 v = find_var(name, NULL);
7393 name[*lenp] = cc;
7394 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7396 if (v->di_tv.vval.v_string == NULL)
7398 *lenp = 0;
7399 return (char_u *)""; /* just in case */
7401 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7402 return v->di_tv.vval.v_string;
7405 return name;
7409 * Allocate a variable for the result of a function.
7410 * Return OK or FAIL.
7412 static int
7413 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7414 evaluate, selfdict)
7415 char_u *name; /* name of the function */
7416 int len; /* length of "name" */
7417 typval_T *rettv;
7418 char_u **arg; /* argument, pointing to the '(' */
7419 linenr_T firstline; /* first line of range */
7420 linenr_T lastline; /* last line of range */
7421 int *doesrange; /* return: function handled range */
7422 int evaluate;
7423 dict_T *selfdict; /* Dictionary for "self" */
7425 char_u *argp;
7426 int ret = OK;
7427 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7428 int argcount = 0; /* number of arguments found */
7431 * Get the arguments.
7433 argp = *arg;
7434 while (argcount < MAX_FUNC_ARGS)
7436 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7437 if (*argp == ')' || *argp == ',' || *argp == NUL)
7438 break;
7439 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7441 ret = FAIL;
7442 break;
7444 ++argcount;
7445 if (*argp != ',')
7446 break;
7448 if (*argp == ')')
7449 ++argp;
7450 else
7451 ret = FAIL;
7453 if (ret == OK)
7454 ret = call_func(name, len, rettv, argcount, argvars,
7455 firstline, lastline, doesrange, evaluate, selfdict);
7456 else if (!aborting())
7458 if (argcount == MAX_FUNC_ARGS)
7459 emsg_funcname("E740: Too many arguments for function %s", name);
7460 else
7461 emsg_funcname("E116: Invalid arguments for function %s", name);
7464 while (--argcount >= 0)
7465 clear_tv(&argvars[argcount]);
7467 *arg = skipwhite(argp);
7468 return ret;
7473 * Call a function with its resolved parameters
7474 * Return OK when the function can't be called, FAIL otherwise.
7475 * Also returns OK when an error was encountered while executing the function.
7477 static int
7478 call_func(name, len, rettv, argcount, argvars, firstline, lastline,
7479 doesrange, evaluate, selfdict)
7480 char_u *name; /* name of the function */
7481 int len; /* length of "name" */
7482 typval_T *rettv; /* return value goes here */
7483 int argcount; /* number of "argvars" */
7484 typval_T *argvars; /* vars for arguments, must have "argcount"
7485 PLUS ONE elements! */
7486 linenr_T firstline; /* first line of range */
7487 linenr_T lastline; /* last line of range */
7488 int *doesrange; /* return: function handled range */
7489 int evaluate;
7490 dict_T *selfdict; /* Dictionary for "self" */
7492 int ret = FAIL;
7493 #define ERROR_UNKNOWN 0
7494 #define ERROR_TOOMANY 1
7495 #define ERROR_TOOFEW 2
7496 #define ERROR_SCRIPT 3
7497 #define ERROR_DICT 4
7498 #define ERROR_NONE 5
7499 #define ERROR_OTHER 6
7500 int error = ERROR_NONE;
7501 int i;
7502 int llen;
7503 ufunc_T *fp;
7504 int cc;
7505 #define FLEN_FIXED 40
7506 char_u fname_buf[FLEN_FIXED + 1];
7507 char_u *fname;
7510 * In a script change <SID>name() and s:name() to K_SNR 123_name().
7511 * Change <SNR>123_name() to K_SNR 123_name().
7512 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
7514 cc = name[len];
7515 name[len] = NUL;
7516 llen = eval_fname_script(name);
7517 if (llen > 0)
7519 fname_buf[0] = K_SPECIAL;
7520 fname_buf[1] = KS_EXTRA;
7521 fname_buf[2] = (int)KE_SNR;
7522 i = 3;
7523 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
7525 if (current_SID <= 0)
7526 error = ERROR_SCRIPT;
7527 else
7529 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
7530 i = (int)STRLEN(fname_buf);
7533 if (i + STRLEN(name + llen) < FLEN_FIXED)
7535 STRCPY(fname_buf + i, name + llen);
7536 fname = fname_buf;
7538 else
7540 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
7541 if (fname == NULL)
7542 error = ERROR_OTHER;
7543 else
7545 mch_memmove(fname, fname_buf, (size_t)i);
7546 STRCPY(fname + i, name + llen);
7550 else
7551 fname = name;
7553 *doesrange = FALSE;
7556 /* execute the function if no errors detected and executing */
7557 if (evaluate && error == ERROR_NONE)
7559 rettv->v_type = VAR_NUMBER; /* default is number rettv */
7560 error = ERROR_UNKNOWN;
7562 if (!builtin_function(fname))
7565 * User defined function.
7567 fp = find_func(fname);
7569 #ifdef FEAT_AUTOCMD
7570 /* Trigger FuncUndefined event, may load the function. */
7571 if (fp == NULL
7572 && apply_autocmds(EVENT_FUNCUNDEFINED,
7573 fname, fname, TRUE, NULL)
7574 && !aborting())
7576 /* executed an autocommand, search for the function again */
7577 fp = find_func(fname);
7579 #endif
7580 /* Try loading a package. */
7581 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
7583 /* loaded a package, search for the function again */
7584 fp = find_func(fname);
7587 if (fp != NULL)
7589 if (fp->uf_flags & FC_RANGE)
7590 *doesrange = TRUE;
7591 if (argcount < fp->uf_args.ga_len)
7592 error = ERROR_TOOFEW;
7593 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
7594 error = ERROR_TOOMANY;
7595 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
7596 error = ERROR_DICT;
7597 else
7600 * Call the user function.
7601 * Save and restore search patterns, script variables and
7602 * redo buffer.
7604 save_search_patterns();
7605 saveRedobuff();
7606 ++fp->uf_calls;
7607 call_user_func(fp, argcount, argvars, rettv,
7608 firstline, lastline,
7609 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
7610 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
7611 && fp->uf_refcount <= 0)
7612 /* Function was unreferenced while being used, free it
7613 * now. */
7614 func_free(fp);
7615 restoreRedobuff();
7616 restore_search_patterns();
7617 error = ERROR_NONE;
7621 else
7624 * Find the function name in the table, call its implementation.
7626 i = find_internal_func(fname);
7627 if (i >= 0)
7629 if (argcount < functions[i].f_min_argc)
7630 error = ERROR_TOOFEW;
7631 else if (argcount > functions[i].f_max_argc)
7632 error = ERROR_TOOMANY;
7633 else
7635 argvars[argcount].v_type = VAR_UNKNOWN;
7636 functions[i].f_func(argvars, rettv);
7637 error = ERROR_NONE;
7642 * The function call (or "FuncUndefined" autocommand sequence) might
7643 * have been aborted by an error, an interrupt, or an explicitly thrown
7644 * exception that has not been caught so far. This situation can be
7645 * tested for by calling aborting(). For an error in an internal
7646 * function or for the "E132" error in call_user_func(), however, the
7647 * throw point at which the "force_abort" flag (temporarily reset by
7648 * emsg()) is normally updated has not been reached yet. We need to
7649 * update that flag first to make aborting() reliable.
7651 update_force_abort();
7653 if (error == ERROR_NONE)
7654 ret = OK;
7657 * Report an error unless the argument evaluation or function call has been
7658 * cancelled due to an aborting error, an interrupt, or an exception.
7660 if (!aborting())
7662 switch (error)
7664 case ERROR_UNKNOWN:
7665 emsg_funcname(N_("E117: Unknown function: %s"), name);
7666 break;
7667 case ERROR_TOOMANY:
7668 emsg_funcname(e_toomanyarg, name);
7669 break;
7670 case ERROR_TOOFEW:
7671 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
7672 name);
7673 break;
7674 case ERROR_SCRIPT:
7675 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
7676 name);
7677 break;
7678 case ERROR_DICT:
7679 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
7680 name);
7681 break;
7685 name[len] = cc;
7686 if (fname != name && fname != fname_buf)
7687 vim_free(fname);
7689 return ret;
7693 * Give an error message with a function name. Handle <SNR> things.
7695 static void
7696 emsg_funcname(ermsg, name)
7697 char *ermsg;
7698 char_u *name;
7700 char_u *p;
7702 if (*name == K_SPECIAL)
7703 p = concat_str((char_u *)"<SNR>", name + 3);
7704 else
7705 p = name;
7706 EMSG2(_(ermsg), p);
7707 if (p != name)
7708 vim_free(p);
7711 /*********************************************
7712 * Implementation of the built-in functions
7716 * "add(list, item)" function
7718 static void
7719 f_add(argvars, rettv)
7720 typval_T *argvars;
7721 typval_T *rettv;
7723 list_T *l;
7725 rettv->vval.v_number = 1; /* Default: Failed */
7726 if (argvars[0].v_type == VAR_LIST)
7728 if ((l = argvars[0].vval.v_list) != NULL
7729 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
7730 && list_append_tv(l, &argvars[1]) == OK)
7731 copy_tv(&argvars[0], rettv);
7733 else
7734 EMSG(_(e_listreq));
7738 * "append(lnum, string/list)" function
7740 static void
7741 f_append(argvars, rettv)
7742 typval_T *argvars;
7743 typval_T *rettv;
7745 long lnum;
7746 char_u *line;
7747 list_T *l = NULL;
7748 listitem_T *li = NULL;
7749 typval_T *tv;
7750 long added = 0;
7752 lnum = get_tv_lnum(argvars);
7753 if (lnum >= 0
7754 && lnum <= curbuf->b_ml.ml_line_count
7755 && u_save(lnum, lnum + 1) == OK)
7757 if (argvars[1].v_type == VAR_LIST)
7759 l = argvars[1].vval.v_list;
7760 if (l == NULL)
7761 return;
7762 li = l->lv_first;
7764 rettv->vval.v_number = 0; /* Default: Success */
7765 for (;;)
7767 if (l == NULL)
7768 tv = &argvars[1]; /* append a string */
7769 else if (li == NULL)
7770 break; /* end of list */
7771 else
7772 tv = &li->li_tv; /* append item from list */
7773 line = get_tv_string_chk(tv);
7774 if (line == NULL) /* type error */
7776 rettv->vval.v_number = 1; /* Failed */
7777 break;
7779 ml_append(lnum + added, line, (colnr_T)0, FALSE);
7780 ++added;
7781 if (l == NULL)
7782 break;
7783 li = li->li_next;
7786 appended_lines_mark(lnum, added);
7787 if (curwin->w_cursor.lnum > lnum)
7788 curwin->w_cursor.lnum += added;
7790 else
7791 rettv->vval.v_number = 1; /* Failed */
7795 * "argc()" function
7797 /* ARGSUSED */
7798 static void
7799 f_argc(argvars, rettv)
7800 typval_T *argvars;
7801 typval_T *rettv;
7803 rettv->vval.v_number = ARGCOUNT;
7807 * "argidx()" function
7809 /* ARGSUSED */
7810 static void
7811 f_argidx(argvars, rettv)
7812 typval_T *argvars;
7813 typval_T *rettv;
7815 rettv->vval.v_number = curwin->w_arg_idx;
7819 * "argv(nr)" function
7821 static void
7822 f_argv(argvars, rettv)
7823 typval_T *argvars;
7824 typval_T *rettv;
7826 int idx;
7828 if (argvars[0].v_type != VAR_UNKNOWN)
7830 idx = get_tv_number_chk(&argvars[0], NULL);
7831 if (idx >= 0 && idx < ARGCOUNT)
7832 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
7833 else
7834 rettv->vval.v_string = NULL;
7835 rettv->v_type = VAR_STRING;
7837 else if (rettv_list_alloc(rettv) == OK)
7838 for (idx = 0; idx < ARGCOUNT; ++idx)
7839 list_append_string(rettv->vval.v_list,
7840 alist_name(&ARGLIST[idx]), -1);
7844 * "browse(save, title, initdir, default)" function
7846 /* ARGSUSED */
7847 static void
7848 f_browse(argvars, rettv)
7849 typval_T *argvars;
7850 typval_T *rettv;
7852 #ifdef FEAT_BROWSE
7853 int save;
7854 char_u *title;
7855 char_u *initdir;
7856 char_u *defname;
7857 char_u buf[NUMBUFLEN];
7858 char_u buf2[NUMBUFLEN];
7859 int error = FALSE;
7861 save = get_tv_number_chk(&argvars[0], &error);
7862 title = get_tv_string_chk(&argvars[1]);
7863 initdir = get_tv_string_buf_chk(&argvars[2], buf);
7864 defname = get_tv_string_buf_chk(&argvars[3], buf2);
7866 if (error || title == NULL || initdir == NULL || defname == NULL)
7867 rettv->vval.v_string = NULL;
7868 else
7869 rettv->vval.v_string =
7870 do_browse(save ? BROWSE_SAVE : 0,
7871 title, defname, NULL, initdir, NULL, curbuf);
7872 #else
7873 rettv->vval.v_string = NULL;
7874 #endif
7875 rettv->v_type = VAR_STRING;
7879 * "browsedir(title, initdir)" function
7881 /* ARGSUSED */
7882 static void
7883 f_browsedir(argvars, rettv)
7884 typval_T *argvars;
7885 typval_T *rettv;
7887 #ifdef FEAT_BROWSE
7888 char_u *title;
7889 char_u *initdir;
7890 char_u buf[NUMBUFLEN];
7892 title = get_tv_string_chk(&argvars[0]);
7893 initdir = get_tv_string_buf_chk(&argvars[1], buf);
7895 if (title == NULL || initdir == NULL)
7896 rettv->vval.v_string = NULL;
7897 else
7898 rettv->vval.v_string = do_browse(BROWSE_DIR,
7899 title, NULL, NULL, initdir, NULL, curbuf);
7900 #else
7901 rettv->vval.v_string = NULL;
7902 #endif
7903 rettv->v_type = VAR_STRING;
7906 static buf_T *find_buffer __ARGS((typval_T *avar));
7909 * Find a buffer by number or exact name.
7911 static buf_T *
7912 find_buffer(avar)
7913 typval_T *avar;
7915 buf_T *buf = NULL;
7917 if (avar->v_type == VAR_NUMBER)
7918 buf = buflist_findnr((int)avar->vval.v_number);
7919 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
7921 buf = buflist_findname_exp(avar->vval.v_string);
7922 if (buf == NULL)
7924 /* No full path name match, try a match with a URL or a "nofile"
7925 * buffer, these don't use the full path. */
7926 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
7927 if (buf->b_fname != NULL
7928 && (path_with_url(buf->b_fname)
7929 #ifdef FEAT_QUICKFIX
7930 || bt_nofile(buf)
7931 #endif
7933 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
7934 break;
7937 return buf;
7941 * "bufexists(expr)" function
7943 static void
7944 f_bufexists(argvars, rettv)
7945 typval_T *argvars;
7946 typval_T *rettv;
7948 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
7952 * "buflisted(expr)" function
7954 static void
7955 f_buflisted(argvars, rettv)
7956 typval_T *argvars;
7957 typval_T *rettv;
7959 buf_T *buf;
7961 buf = find_buffer(&argvars[0]);
7962 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
7966 * "bufloaded(expr)" function
7968 static void
7969 f_bufloaded(argvars, rettv)
7970 typval_T *argvars;
7971 typval_T *rettv;
7973 buf_T *buf;
7975 buf = find_buffer(&argvars[0]);
7976 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
7979 static buf_T *get_buf_tv __ARGS((typval_T *tv));
7982 * Get buffer by number or pattern.
7984 static buf_T *
7985 get_buf_tv(tv)
7986 typval_T *tv;
7988 char_u *name = tv->vval.v_string;
7989 int save_magic;
7990 char_u *save_cpo;
7991 buf_T *buf;
7993 if (tv->v_type == VAR_NUMBER)
7994 return buflist_findnr((int)tv->vval.v_number);
7995 if (tv->v_type != VAR_STRING)
7996 return NULL;
7997 if (name == NULL || *name == NUL)
7998 return curbuf;
7999 if (name[0] == '$' && name[1] == NUL)
8000 return lastbuf;
8002 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
8003 save_magic = p_magic;
8004 p_magic = TRUE;
8005 save_cpo = p_cpo;
8006 p_cpo = (char_u *)"";
8008 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8009 TRUE, FALSE));
8011 p_magic = save_magic;
8012 p_cpo = save_cpo;
8014 /* If not found, try expanding the name, like done for bufexists(). */
8015 if (buf == NULL)
8016 buf = find_buffer(tv);
8018 return buf;
8022 * "bufname(expr)" function
8024 static void
8025 f_bufname(argvars, rettv)
8026 typval_T *argvars;
8027 typval_T *rettv;
8029 buf_T *buf;
8031 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8032 ++emsg_off;
8033 buf = get_buf_tv(&argvars[0]);
8034 rettv->v_type = VAR_STRING;
8035 if (buf != NULL && buf->b_fname != NULL)
8036 rettv->vval.v_string = vim_strsave(buf->b_fname);
8037 else
8038 rettv->vval.v_string = NULL;
8039 --emsg_off;
8043 * "bufnr(expr)" function
8045 static void
8046 f_bufnr(argvars, rettv)
8047 typval_T *argvars;
8048 typval_T *rettv;
8050 buf_T *buf;
8051 int error = FALSE;
8052 char_u *name;
8054 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8055 ++emsg_off;
8056 buf = get_buf_tv(&argvars[0]);
8057 --emsg_off;
8059 /* If the buffer isn't found and the second argument is not zero create a
8060 * new buffer. */
8061 if (buf == NULL
8062 && argvars[1].v_type != VAR_UNKNOWN
8063 && get_tv_number_chk(&argvars[1], &error) != 0
8064 && !error
8065 && (name = get_tv_string_chk(&argvars[0])) != NULL
8066 && !error)
8067 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8069 if (buf != NULL)
8070 rettv->vval.v_number = buf->b_fnum;
8071 else
8072 rettv->vval.v_number = -1;
8076 * "bufwinnr(nr)" function
8078 static void
8079 f_bufwinnr(argvars, rettv)
8080 typval_T *argvars;
8081 typval_T *rettv;
8083 #ifdef FEAT_WINDOWS
8084 win_T *wp;
8085 int winnr = 0;
8086 #endif
8087 buf_T *buf;
8089 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8090 ++emsg_off;
8091 buf = get_buf_tv(&argvars[0]);
8092 #ifdef FEAT_WINDOWS
8093 for (wp = firstwin; wp; wp = wp->w_next)
8095 ++winnr;
8096 if (wp->w_buffer == buf)
8097 break;
8099 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8100 #else
8101 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8102 #endif
8103 --emsg_off;
8107 * "byte2line(byte)" function
8109 /*ARGSUSED*/
8110 static void
8111 f_byte2line(argvars, rettv)
8112 typval_T *argvars;
8113 typval_T *rettv;
8115 #ifndef FEAT_BYTEOFF
8116 rettv->vval.v_number = -1;
8117 #else
8118 long boff = 0;
8120 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8121 if (boff < 0)
8122 rettv->vval.v_number = -1;
8123 else
8124 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8125 (linenr_T)0, &boff);
8126 #endif
8130 * "byteidx()" function
8132 /*ARGSUSED*/
8133 static void
8134 f_byteidx(argvars, rettv)
8135 typval_T *argvars;
8136 typval_T *rettv;
8138 #ifdef FEAT_MBYTE
8139 char_u *t;
8140 #endif
8141 char_u *str;
8142 long idx;
8144 str = get_tv_string_chk(&argvars[0]);
8145 idx = get_tv_number_chk(&argvars[1], NULL);
8146 rettv->vval.v_number = -1;
8147 if (str == NULL || idx < 0)
8148 return;
8150 #ifdef FEAT_MBYTE
8151 t = str;
8152 for ( ; idx > 0; idx--)
8154 if (*t == NUL) /* EOL reached */
8155 return;
8156 t += (*mb_ptr2len)(t);
8158 rettv->vval.v_number = (varnumber_T)(t - str);
8159 #else
8160 if (idx <= STRLEN(str))
8161 rettv->vval.v_number = idx;
8162 #endif
8166 * "call(func, arglist)" function
8168 static void
8169 f_call(argvars, rettv)
8170 typval_T *argvars;
8171 typval_T *rettv;
8173 char_u *func;
8174 typval_T argv[MAX_FUNC_ARGS + 1];
8175 int argc = 0;
8176 listitem_T *item;
8177 int dummy;
8178 dict_T *selfdict = NULL;
8180 rettv->vval.v_number = 0;
8181 if (argvars[1].v_type != VAR_LIST)
8183 EMSG(_(e_listreq));
8184 return;
8186 if (argvars[1].vval.v_list == NULL)
8187 return;
8189 if (argvars[0].v_type == VAR_FUNC)
8190 func = argvars[0].vval.v_string;
8191 else
8192 func = get_tv_string(&argvars[0]);
8193 if (*func == NUL)
8194 return; /* type error or empty name */
8196 if (argvars[2].v_type != VAR_UNKNOWN)
8198 if (argvars[2].v_type != VAR_DICT)
8200 EMSG(_(e_dictreq));
8201 return;
8203 selfdict = argvars[2].vval.v_dict;
8206 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
8207 item = item->li_next)
8209 if (argc == MAX_FUNC_ARGS)
8211 EMSG(_("E699: Too many arguments"));
8212 break;
8214 /* Make a copy of each argument. This is needed to be able to set
8215 * v_lock to VAR_FIXED in the copy without changing the original list.
8217 copy_tv(&item->li_tv, &argv[argc++]);
8220 if (item == NULL)
8221 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
8222 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
8223 &dummy, TRUE, selfdict);
8225 /* Free the arguments. */
8226 while (argc > 0)
8227 clear_tv(&argv[--argc]);
8231 * "changenr()" function
8233 /*ARGSUSED*/
8234 static void
8235 f_changenr(argvars, rettv)
8236 typval_T *argvars;
8237 typval_T *rettv;
8239 rettv->vval.v_number = curbuf->b_u_seq_cur;
8243 * "char2nr(string)" function
8245 static void
8246 f_char2nr(argvars, rettv)
8247 typval_T *argvars;
8248 typval_T *rettv;
8250 #ifdef FEAT_MBYTE
8251 if (has_mbyte)
8252 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
8253 else
8254 #endif
8255 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
8259 * "cindent(lnum)" function
8261 static void
8262 f_cindent(argvars, rettv)
8263 typval_T *argvars;
8264 typval_T *rettv;
8266 #ifdef FEAT_CINDENT
8267 pos_T pos;
8268 linenr_T lnum;
8270 pos = curwin->w_cursor;
8271 lnum = get_tv_lnum(argvars);
8272 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
8274 curwin->w_cursor.lnum = lnum;
8275 rettv->vval.v_number = get_c_indent();
8276 curwin->w_cursor = pos;
8278 else
8279 #endif
8280 rettv->vval.v_number = -1;
8284 * "clearmatches()" function
8286 /*ARGSUSED*/
8287 static void
8288 f_clearmatches(argvars, rettv)
8289 typval_T *argvars;
8290 typval_T *rettv;
8292 #ifdef FEAT_SEARCH_EXTRA
8293 clear_matches(curwin);
8294 #endif
8298 * "col(string)" function
8300 static void
8301 f_col(argvars, rettv)
8302 typval_T *argvars;
8303 typval_T *rettv;
8305 colnr_T col = 0;
8306 pos_T *fp;
8307 int fnum = curbuf->b_fnum;
8309 fp = var2fpos(&argvars[0], FALSE, &fnum);
8310 if (fp != NULL && fnum == curbuf->b_fnum)
8312 if (fp->col == MAXCOL)
8314 /* '> can be MAXCOL, get the length of the line then */
8315 if (fp->lnum <= curbuf->b_ml.ml_line_count)
8316 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
8317 else
8318 col = MAXCOL;
8320 else
8322 col = fp->col + 1;
8323 #ifdef FEAT_VIRTUALEDIT
8324 /* col(".") when the cursor is on the NUL at the end of the line
8325 * because of "coladd" can be seen as an extra column. */
8326 if (virtual_active() && fp == &curwin->w_cursor)
8328 char_u *p = ml_get_cursor();
8330 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
8331 curwin->w_virtcol - curwin->w_cursor.coladd))
8333 # ifdef FEAT_MBYTE
8334 int l;
8336 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
8337 col += l;
8338 # else
8339 if (*p != NUL && p[1] == NUL)
8340 ++col;
8341 # endif
8344 #endif
8347 rettv->vval.v_number = col;
8350 #if defined(FEAT_INS_EXPAND)
8352 * "complete()" function
8354 /*ARGSUSED*/
8355 static void
8356 f_complete(argvars, rettv)
8357 typval_T *argvars;
8358 typval_T *rettv;
8360 int startcol;
8362 if ((State & INSERT) == 0)
8364 EMSG(_("E785: complete() can only be used in Insert mode"));
8365 return;
8368 /* Check for undo allowed here, because if something was already inserted
8369 * the line was already saved for undo and this check isn't done. */
8370 if (!undo_allowed())
8371 return;
8373 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
8375 EMSG(_(e_invarg));
8376 return;
8379 startcol = get_tv_number_chk(&argvars[0], NULL);
8380 if (startcol <= 0)
8381 return;
8383 set_completion(startcol - 1, argvars[1].vval.v_list);
8387 * "complete_add()" function
8389 /*ARGSUSED*/
8390 static void
8391 f_complete_add(argvars, rettv)
8392 typval_T *argvars;
8393 typval_T *rettv;
8395 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
8399 * "complete_check()" function
8401 /*ARGSUSED*/
8402 static void
8403 f_complete_check(argvars, rettv)
8404 typval_T *argvars;
8405 typval_T *rettv;
8407 int saved = RedrawingDisabled;
8409 RedrawingDisabled = 0;
8410 ins_compl_check_keys(0);
8411 rettv->vval.v_number = compl_interrupted;
8412 RedrawingDisabled = saved;
8414 #endif
8417 * "confirm(message, buttons[, default [, type]])" function
8419 /*ARGSUSED*/
8420 static void
8421 f_confirm(argvars, rettv)
8422 typval_T *argvars;
8423 typval_T *rettv;
8425 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
8426 char_u *message;
8427 char_u *buttons = NULL;
8428 char_u buf[NUMBUFLEN];
8429 char_u buf2[NUMBUFLEN];
8430 int def = 1;
8431 int type = VIM_GENERIC;
8432 char_u *typestr;
8433 int error = FALSE;
8435 message = get_tv_string_chk(&argvars[0]);
8436 if (message == NULL)
8437 error = TRUE;
8438 if (argvars[1].v_type != VAR_UNKNOWN)
8440 buttons = get_tv_string_buf_chk(&argvars[1], buf);
8441 if (buttons == NULL)
8442 error = TRUE;
8443 if (argvars[2].v_type != VAR_UNKNOWN)
8445 def = get_tv_number_chk(&argvars[2], &error);
8446 if (argvars[3].v_type != VAR_UNKNOWN)
8448 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
8449 if (typestr == NULL)
8450 error = TRUE;
8451 else
8453 switch (TOUPPER_ASC(*typestr))
8455 case 'E': type = VIM_ERROR; break;
8456 case 'Q': type = VIM_QUESTION; break;
8457 case 'I': type = VIM_INFO; break;
8458 case 'W': type = VIM_WARNING; break;
8459 case 'G': type = VIM_GENERIC; break;
8466 if (buttons == NULL || *buttons == NUL)
8467 buttons = (char_u *)_("&Ok");
8469 if (error)
8470 rettv->vval.v_number = 0;
8471 else
8472 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
8473 def, NULL);
8474 #else
8475 rettv->vval.v_number = 0;
8476 #endif
8480 * "copy()" function
8482 static void
8483 f_copy(argvars, rettv)
8484 typval_T *argvars;
8485 typval_T *rettv;
8487 item_copy(&argvars[0], rettv, FALSE, 0);
8491 * "count()" function
8493 static void
8494 f_count(argvars, rettv)
8495 typval_T *argvars;
8496 typval_T *rettv;
8498 long n = 0;
8499 int ic = FALSE;
8501 if (argvars[0].v_type == VAR_LIST)
8503 listitem_T *li;
8504 list_T *l;
8505 long idx;
8507 if ((l = argvars[0].vval.v_list) != NULL)
8509 li = l->lv_first;
8510 if (argvars[2].v_type != VAR_UNKNOWN)
8512 int error = FALSE;
8514 ic = get_tv_number_chk(&argvars[2], &error);
8515 if (argvars[3].v_type != VAR_UNKNOWN)
8517 idx = get_tv_number_chk(&argvars[3], &error);
8518 if (!error)
8520 li = list_find(l, idx);
8521 if (li == NULL)
8522 EMSGN(_(e_listidx), idx);
8525 if (error)
8526 li = NULL;
8529 for ( ; li != NULL; li = li->li_next)
8530 if (tv_equal(&li->li_tv, &argvars[1], ic))
8531 ++n;
8534 else if (argvars[0].v_type == VAR_DICT)
8536 int todo;
8537 dict_T *d;
8538 hashitem_T *hi;
8540 if ((d = argvars[0].vval.v_dict) != NULL)
8542 int error = FALSE;
8544 if (argvars[2].v_type != VAR_UNKNOWN)
8546 ic = get_tv_number_chk(&argvars[2], &error);
8547 if (argvars[3].v_type != VAR_UNKNOWN)
8548 EMSG(_(e_invarg));
8551 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
8552 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
8554 if (!HASHITEM_EMPTY(hi))
8556 --todo;
8557 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
8558 ++n;
8563 else
8564 EMSG2(_(e_listdictarg), "count()");
8565 rettv->vval.v_number = n;
8569 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
8571 * Checks the existence of a cscope connection.
8573 /*ARGSUSED*/
8574 static void
8575 f_cscope_connection(argvars, rettv)
8576 typval_T *argvars;
8577 typval_T *rettv;
8579 #ifdef FEAT_CSCOPE
8580 int num = 0;
8581 char_u *dbpath = NULL;
8582 char_u *prepend = NULL;
8583 char_u buf[NUMBUFLEN];
8585 if (argvars[0].v_type != VAR_UNKNOWN
8586 && argvars[1].v_type != VAR_UNKNOWN)
8588 num = (int)get_tv_number(&argvars[0]);
8589 dbpath = get_tv_string(&argvars[1]);
8590 if (argvars[2].v_type != VAR_UNKNOWN)
8591 prepend = get_tv_string_buf(&argvars[2], buf);
8594 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
8595 #else
8596 rettv->vval.v_number = 0;
8597 #endif
8601 * "cursor(lnum, col)" function
8603 * Moves the cursor to the specified line and column
8605 /*ARGSUSED*/
8606 static void
8607 f_cursor(argvars, rettv)
8608 typval_T *argvars;
8609 typval_T *rettv;
8611 long line, col;
8612 #ifdef FEAT_VIRTUALEDIT
8613 long coladd = 0;
8614 #endif
8616 if (argvars[1].v_type == VAR_UNKNOWN)
8618 pos_T pos;
8620 if (list2fpos(argvars, &pos, NULL) == FAIL)
8621 return;
8622 line = pos.lnum;
8623 col = pos.col;
8624 #ifdef FEAT_VIRTUALEDIT
8625 coladd = pos.coladd;
8626 #endif
8628 else
8630 line = get_tv_lnum(argvars);
8631 col = get_tv_number_chk(&argvars[1], NULL);
8632 #ifdef FEAT_VIRTUALEDIT
8633 if (argvars[2].v_type != VAR_UNKNOWN)
8634 coladd = get_tv_number_chk(&argvars[2], NULL);
8635 #endif
8637 if (line < 0 || col < 0
8638 #ifdef FEAT_VIRTUALEDIT
8639 || coladd < 0
8640 #endif
8642 return; /* type error; errmsg already given */
8643 if (line > 0)
8644 curwin->w_cursor.lnum = line;
8645 if (col > 0)
8646 curwin->w_cursor.col = col - 1;
8647 #ifdef FEAT_VIRTUALEDIT
8648 curwin->w_cursor.coladd = coladd;
8649 #endif
8651 /* Make sure the cursor is in a valid position. */
8652 check_cursor();
8653 #ifdef FEAT_MBYTE
8654 /* Correct cursor for multi-byte character. */
8655 if (has_mbyte)
8656 mb_adjust_cursor();
8657 #endif
8659 curwin->w_set_curswant = TRUE;
8663 * "deepcopy()" function
8665 static void
8666 f_deepcopy(argvars, rettv)
8667 typval_T *argvars;
8668 typval_T *rettv;
8670 int noref = 0;
8672 if (argvars[1].v_type != VAR_UNKNOWN)
8673 noref = get_tv_number_chk(&argvars[1], NULL);
8674 if (noref < 0 || noref > 1)
8675 EMSG(_(e_invarg));
8676 else
8677 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? ++current_copyID : 0);
8681 * "delete()" function
8683 static void
8684 f_delete(argvars, rettv)
8685 typval_T *argvars;
8686 typval_T *rettv;
8688 if (check_restricted() || check_secure())
8689 rettv->vval.v_number = -1;
8690 else
8691 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
8695 * "did_filetype()" function
8697 /*ARGSUSED*/
8698 static void
8699 f_did_filetype(argvars, rettv)
8700 typval_T *argvars;
8701 typval_T *rettv;
8703 #ifdef FEAT_AUTOCMD
8704 rettv->vval.v_number = did_filetype;
8705 #else
8706 rettv->vval.v_number = 0;
8707 #endif
8711 * "diff_filler()" function
8713 /*ARGSUSED*/
8714 static void
8715 f_diff_filler(argvars, rettv)
8716 typval_T *argvars;
8717 typval_T *rettv;
8719 #ifdef FEAT_DIFF
8720 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
8721 #endif
8725 * "diff_hlID()" function
8727 /*ARGSUSED*/
8728 static void
8729 f_diff_hlID(argvars, rettv)
8730 typval_T *argvars;
8731 typval_T *rettv;
8733 #ifdef FEAT_DIFF
8734 linenr_T lnum = get_tv_lnum(argvars);
8735 static linenr_T prev_lnum = 0;
8736 static int changedtick = 0;
8737 static int fnum = 0;
8738 static int change_start = 0;
8739 static int change_end = 0;
8740 static hlf_T hlID = (hlf_T)0;
8741 int filler_lines;
8742 int col;
8744 if (lnum < 0) /* ignore type error in {lnum} arg */
8745 lnum = 0;
8746 if (lnum != prev_lnum
8747 || changedtick != curbuf->b_changedtick
8748 || fnum != curbuf->b_fnum)
8750 /* New line, buffer, change: need to get the values. */
8751 filler_lines = diff_check(curwin, lnum);
8752 if (filler_lines < 0)
8754 if (filler_lines == -1)
8756 change_start = MAXCOL;
8757 change_end = -1;
8758 if (diff_find_change(curwin, lnum, &change_start, &change_end))
8759 hlID = HLF_ADD; /* added line */
8760 else
8761 hlID = HLF_CHD; /* changed line */
8763 else
8764 hlID = HLF_ADD; /* added line */
8766 else
8767 hlID = (hlf_T)0;
8768 prev_lnum = lnum;
8769 changedtick = curbuf->b_changedtick;
8770 fnum = curbuf->b_fnum;
8773 if (hlID == HLF_CHD || hlID == HLF_TXD)
8775 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
8776 if (col >= change_start && col <= change_end)
8777 hlID = HLF_TXD; /* changed text */
8778 else
8779 hlID = HLF_CHD; /* changed line */
8781 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
8782 #endif
8786 * "empty({expr})" function
8788 static void
8789 f_empty(argvars, rettv)
8790 typval_T *argvars;
8791 typval_T *rettv;
8793 int n;
8795 switch (argvars[0].v_type)
8797 case VAR_STRING:
8798 case VAR_FUNC:
8799 n = argvars[0].vval.v_string == NULL
8800 || *argvars[0].vval.v_string == NUL;
8801 break;
8802 case VAR_NUMBER:
8803 n = argvars[0].vval.v_number == 0;
8804 break;
8805 case VAR_LIST:
8806 n = argvars[0].vval.v_list == NULL
8807 || argvars[0].vval.v_list->lv_first == NULL;
8808 break;
8809 case VAR_DICT:
8810 n = argvars[0].vval.v_dict == NULL
8811 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
8812 break;
8813 default:
8814 EMSG2(_(e_intern2), "f_empty()");
8815 n = 0;
8818 rettv->vval.v_number = n;
8822 * "escape({string}, {chars})" function
8824 static void
8825 f_escape(argvars, rettv)
8826 typval_T *argvars;
8827 typval_T *rettv;
8829 char_u buf[NUMBUFLEN];
8831 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
8832 get_tv_string_buf(&argvars[1], buf));
8833 rettv->v_type = VAR_STRING;
8837 * "eval()" function
8839 /*ARGSUSED*/
8840 static void
8841 f_eval(argvars, rettv)
8842 typval_T *argvars;
8843 typval_T *rettv;
8845 char_u *s;
8847 s = get_tv_string_chk(&argvars[0]);
8848 if (s != NULL)
8849 s = skipwhite(s);
8851 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
8853 rettv->v_type = VAR_NUMBER;
8854 rettv->vval.v_number = 0;
8856 else if (*s != NUL)
8857 EMSG(_(e_trailing));
8861 * "eventhandler()" function
8863 /*ARGSUSED*/
8864 static void
8865 f_eventhandler(argvars, rettv)
8866 typval_T *argvars;
8867 typval_T *rettv;
8869 rettv->vval.v_number = vgetc_busy;
8873 * "executable()" function
8875 static void
8876 f_executable(argvars, rettv)
8877 typval_T *argvars;
8878 typval_T *rettv;
8880 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
8884 * "exists()" function
8886 static void
8887 f_exists(argvars, rettv)
8888 typval_T *argvars;
8889 typval_T *rettv;
8891 char_u *p;
8892 char_u *name;
8893 int n = FALSE;
8894 int len = 0;
8896 p = get_tv_string(&argvars[0]);
8897 if (*p == '$') /* environment variable */
8899 /* first try "normal" environment variables (fast) */
8900 if (mch_getenv(p + 1) != NULL)
8901 n = TRUE;
8902 else
8904 /* try expanding things like $VIM and ${HOME} */
8905 p = expand_env_save(p);
8906 if (p != NULL && *p != '$')
8907 n = TRUE;
8908 vim_free(p);
8911 else if (*p == '&' || *p == '+') /* option */
8913 n = (get_option_tv(&p, NULL, TRUE) == OK);
8914 if (*skipwhite(p) != NUL)
8915 n = FALSE; /* trailing garbage */
8917 else if (*p == '*') /* internal or user defined function */
8919 n = function_exists(p + 1);
8921 else if (*p == ':')
8923 n = cmd_exists(p + 1);
8925 else if (*p == '#')
8927 #ifdef FEAT_AUTOCMD
8928 if (p[1] == '#')
8929 n = autocmd_supported(p + 2);
8930 else
8931 n = au_exists(p + 1);
8932 #endif
8934 else /* internal variable */
8936 char_u *tofree;
8937 typval_T tv;
8939 /* get_name_len() takes care of expanding curly braces */
8940 name = p;
8941 len = get_name_len(&p, &tofree, TRUE, FALSE);
8942 if (len > 0)
8944 if (tofree != NULL)
8945 name = tofree;
8946 n = (get_var_tv(name, len, &tv, FALSE) == OK);
8947 if (n)
8949 /* handle d.key, l[idx], f(expr) */
8950 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
8951 if (n)
8952 clear_tv(&tv);
8955 if (*p != NUL)
8956 n = FALSE;
8958 vim_free(tofree);
8961 rettv->vval.v_number = n;
8965 * "expand()" function
8967 static void
8968 f_expand(argvars, rettv)
8969 typval_T *argvars;
8970 typval_T *rettv;
8972 char_u *s;
8973 int len;
8974 char_u *errormsg;
8975 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
8976 expand_T xpc;
8977 int error = FALSE;
8979 rettv->v_type = VAR_STRING;
8980 s = get_tv_string(&argvars[0]);
8981 if (*s == '%' || *s == '#' || *s == '<')
8983 ++emsg_off;
8984 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
8985 --emsg_off;
8987 else
8989 /* When the optional second argument is non-zero, don't remove matches
8990 * for 'suffixes' and 'wildignore' */
8991 if (argvars[1].v_type != VAR_UNKNOWN
8992 && get_tv_number_chk(&argvars[1], &error))
8993 flags |= WILD_KEEP_ALL;
8994 if (!error)
8996 ExpandInit(&xpc);
8997 xpc.xp_context = EXPAND_FILES;
8998 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
9000 else
9001 rettv->vval.v_string = NULL;
9006 * "extend(list, list [, idx])" function
9007 * "extend(dict, dict [, action])" function
9009 static void
9010 f_extend(argvars, rettv)
9011 typval_T *argvars;
9012 typval_T *rettv;
9014 rettv->vval.v_number = 0;
9015 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9017 list_T *l1, *l2;
9018 listitem_T *item;
9019 long before;
9020 int error = FALSE;
9022 l1 = argvars[0].vval.v_list;
9023 l2 = argvars[1].vval.v_list;
9024 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9025 && l2 != NULL)
9027 if (argvars[2].v_type != VAR_UNKNOWN)
9029 before = get_tv_number_chk(&argvars[2], &error);
9030 if (error)
9031 return; /* type error; errmsg already given */
9033 if (before == l1->lv_len)
9034 item = NULL;
9035 else
9037 item = list_find(l1, before);
9038 if (item == NULL)
9040 EMSGN(_(e_listidx), before);
9041 return;
9045 else
9046 item = NULL;
9047 list_extend(l1, l2, item);
9049 copy_tv(&argvars[0], rettv);
9052 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9054 dict_T *d1, *d2;
9055 dictitem_T *di1;
9056 char_u *action;
9057 int i;
9058 hashitem_T *hi2;
9059 int todo;
9061 d1 = argvars[0].vval.v_dict;
9062 d2 = argvars[1].vval.v_dict;
9063 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9064 && d2 != NULL)
9066 /* Check the third argument. */
9067 if (argvars[2].v_type != VAR_UNKNOWN)
9069 static char *(av[]) = {"keep", "force", "error"};
9071 action = get_tv_string_chk(&argvars[2]);
9072 if (action == NULL)
9073 return; /* type error; errmsg already given */
9074 for (i = 0; i < 3; ++i)
9075 if (STRCMP(action, av[i]) == 0)
9076 break;
9077 if (i == 3)
9079 EMSG2(_(e_invarg2), action);
9080 return;
9083 else
9084 action = (char_u *)"force";
9086 /* Go over all entries in the second dict and add them to the
9087 * first dict. */
9088 todo = (int)d2->dv_hashtab.ht_used;
9089 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9091 if (!HASHITEM_EMPTY(hi2))
9093 --todo;
9094 di1 = dict_find(d1, hi2->hi_key, -1);
9095 if (di1 == NULL)
9097 di1 = dictitem_copy(HI2DI(hi2));
9098 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9099 dictitem_free(di1);
9101 else if (*action == 'e')
9103 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9104 break;
9106 else if (*action == 'f')
9108 clear_tv(&di1->di_tv);
9109 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9114 copy_tv(&argvars[0], rettv);
9117 else
9118 EMSG2(_(e_listdictarg), "extend()");
9122 * "feedkeys()" function
9124 /*ARGSUSED*/
9125 static void
9126 f_feedkeys(argvars, rettv)
9127 typval_T *argvars;
9128 typval_T *rettv;
9130 int remap = TRUE;
9131 char_u *keys, *flags;
9132 char_u nbuf[NUMBUFLEN];
9133 int typed = FALSE;
9134 char_u *keys_esc;
9136 /* This is not allowed in the sandbox. If the commands would still be
9137 * executed in the sandbox it would be OK, but it probably happens later,
9138 * when "sandbox" is no longer set. */
9139 if (check_secure())
9140 return;
9142 rettv->vval.v_number = 0;
9143 keys = get_tv_string(&argvars[0]);
9144 if (*keys != NUL)
9146 if (argvars[1].v_type != VAR_UNKNOWN)
9148 flags = get_tv_string_buf(&argvars[1], nbuf);
9149 for ( ; *flags != NUL; ++flags)
9151 switch (*flags)
9153 case 'n': remap = FALSE; break;
9154 case 'm': remap = TRUE; break;
9155 case 't': typed = TRUE; break;
9160 /* Need to escape K_SPECIAL and CSI before putting the string in the
9161 * typeahead buffer. */
9162 keys_esc = vim_strsave_escape_csi(keys);
9163 if (keys_esc != NULL)
9165 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
9166 typebuf.tb_len, !typed, FALSE);
9167 vim_free(keys_esc);
9168 if (vgetc_busy)
9169 typebuf_was_filled = TRUE;
9175 * "filereadable()" function
9177 static void
9178 f_filereadable(argvars, rettv)
9179 typval_T *argvars;
9180 typval_T *rettv;
9182 FILE *fd;
9183 char_u *p;
9184 int n;
9186 p = get_tv_string(&argvars[0]);
9187 if (*p && !mch_isdir(p) && (fd = mch_fopen((char *)p, "r")) != NULL)
9189 n = TRUE;
9190 fclose(fd);
9192 else
9193 n = FALSE;
9195 rettv->vval.v_number = n;
9199 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
9200 * rights to write into.
9202 static void
9203 f_filewritable(argvars, rettv)
9204 typval_T *argvars;
9205 typval_T *rettv;
9207 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
9210 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
9212 static void
9213 findfilendir(argvars, rettv, find_what)
9214 typval_T *argvars;
9215 typval_T *rettv;
9216 int find_what;
9218 #ifdef FEAT_SEARCHPATH
9219 char_u *fname;
9220 char_u *fresult = NULL;
9221 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
9222 char_u *p;
9223 char_u pathbuf[NUMBUFLEN];
9224 int count = 1;
9225 int first = TRUE;
9226 int error = FALSE;
9227 #endif
9229 rettv->vval.v_string = NULL;
9230 rettv->v_type = VAR_STRING;
9232 #ifdef FEAT_SEARCHPATH
9233 fname = get_tv_string(&argvars[0]);
9235 if (argvars[1].v_type != VAR_UNKNOWN)
9237 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
9238 if (p == NULL)
9239 error = TRUE;
9240 else
9242 if (*p != NUL)
9243 path = p;
9245 if (argvars[2].v_type != VAR_UNKNOWN)
9246 count = get_tv_number_chk(&argvars[2], &error);
9250 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
9251 error = TRUE;
9253 if (*fname != NUL && !error)
9257 if (rettv->v_type == VAR_STRING)
9258 vim_free(fresult);
9259 fresult = find_file_in_path_option(first ? fname : NULL,
9260 first ? (int)STRLEN(fname) : 0,
9261 0, first, path,
9262 find_what,
9263 curbuf->b_ffname,
9264 find_what == FINDFILE_DIR
9265 ? (char_u *)"" : curbuf->b_p_sua);
9266 first = FALSE;
9268 if (fresult != NULL && rettv->v_type == VAR_LIST)
9269 list_append_string(rettv->vval.v_list, fresult, -1);
9271 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
9274 if (rettv->v_type == VAR_STRING)
9275 rettv->vval.v_string = fresult;
9276 #endif
9279 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
9280 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
9283 * Implementation of map() and filter().
9285 static void
9286 filter_map(argvars, rettv, map)
9287 typval_T *argvars;
9288 typval_T *rettv;
9289 int map;
9291 char_u buf[NUMBUFLEN];
9292 char_u *expr;
9293 listitem_T *li, *nli;
9294 list_T *l = NULL;
9295 dictitem_T *di;
9296 hashtab_T *ht;
9297 hashitem_T *hi;
9298 dict_T *d = NULL;
9299 typval_T save_val;
9300 typval_T save_key;
9301 int rem;
9302 int todo;
9303 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
9304 int save_did_emsg;
9306 rettv->vval.v_number = 0;
9307 if (argvars[0].v_type == VAR_LIST)
9309 if ((l = argvars[0].vval.v_list) == NULL
9310 || (map && tv_check_lock(l->lv_lock, ermsg)))
9311 return;
9313 else if (argvars[0].v_type == VAR_DICT)
9315 if ((d = argvars[0].vval.v_dict) == NULL
9316 || (map && tv_check_lock(d->dv_lock, ermsg)))
9317 return;
9319 else
9321 EMSG2(_(e_listdictarg), ermsg);
9322 return;
9325 expr = get_tv_string_buf_chk(&argvars[1], buf);
9326 /* On type errors, the preceding call has already displayed an error
9327 * message. Avoid a misleading error message for an empty string that
9328 * was not passed as argument. */
9329 if (expr != NULL)
9331 prepare_vimvar(VV_VAL, &save_val);
9332 expr = skipwhite(expr);
9334 /* We reset "did_emsg" to be able to detect whether an error
9335 * occurred during evaluation of the expression. */
9336 save_did_emsg = did_emsg;
9337 did_emsg = FALSE;
9339 if (argvars[0].v_type == VAR_DICT)
9341 prepare_vimvar(VV_KEY, &save_key);
9342 vimvars[VV_KEY].vv_type = VAR_STRING;
9344 ht = &d->dv_hashtab;
9345 hash_lock(ht);
9346 todo = (int)ht->ht_used;
9347 for (hi = ht->ht_array; todo > 0; ++hi)
9349 if (!HASHITEM_EMPTY(hi))
9351 --todo;
9352 di = HI2DI(hi);
9353 if (tv_check_lock(di->di_tv.v_lock, ermsg))
9354 break;
9355 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
9356 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
9357 || did_emsg)
9358 break;
9359 if (!map && rem)
9360 dictitem_remove(d, di);
9361 clear_tv(&vimvars[VV_KEY].vv_tv);
9364 hash_unlock(ht);
9366 restore_vimvar(VV_KEY, &save_key);
9368 else
9370 for (li = l->lv_first; li != NULL; li = nli)
9372 if (tv_check_lock(li->li_tv.v_lock, ermsg))
9373 break;
9374 nli = li->li_next;
9375 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
9376 || did_emsg)
9377 break;
9378 if (!map && rem)
9379 listitem_remove(l, li);
9383 restore_vimvar(VV_VAL, &save_val);
9385 did_emsg |= save_did_emsg;
9388 copy_tv(&argvars[0], rettv);
9391 static int
9392 filter_map_one(tv, expr, map, remp)
9393 typval_T *tv;
9394 char_u *expr;
9395 int map;
9396 int *remp;
9398 typval_T rettv;
9399 char_u *s;
9400 int retval = FAIL;
9402 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
9403 s = expr;
9404 if (eval1(&s, &rettv, TRUE) == FAIL)
9405 goto theend;
9406 if (*s != NUL) /* check for trailing chars after expr */
9408 EMSG2(_(e_invexpr2), s);
9409 goto theend;
9411 if (map)
9413 /* map(): replace the list item value */
9414 clear_tv(tv);
9415 rettv.v_lock = 0;
9416 *tv = rettv;
9418 else
9420 int error = FALSE;
9422 /* filter(): when expr is zero remove the item */
9423 *remp = (get_tv_number_chk(&rettv, &error) == 0);
9424 clear_tv(&rettv);
9425 /* On type error, nothing has been removed; return FAIL to stop the
9426 * loop. The error message was given by get_tv_number_chk(). */
9427 if (error)
9428 goto theend;
9430 retval = OK;
9431 theend:
9432 clear_tv(&vimvars[VV_VAL].vv_tv);
9433 return retval;
9437 * "filter()" function
9439 static void
9440 f_filter(argvars, rettv)
9441 typval_T *argvars;
9442 typval_T *rettv;
9444 filter_map(argvars, rettv, FALSE);
9448 * "finddir({fname}[, {path}[, {count}]])" function
9450 static void
9451 f_finddir(argvars, rettv)
9452 typval_T *argvars;
9453 typval_T *rettv;
9455 findfilendir(argvars, rettv, FINDFILE_DIR);
9459 * "findfile({fname}[, {path}[, {count}]])" function
9461 static void
9462 f_findfile(argvars, rettv)
9463 typval_T *argvars;
9464 typval_T *rettv;
9466 findfilendir(argvars, rettv, FINDFILE_FILE);
9470 * "fnameescape({string})" function
9472 static void
9473 f_fnameescape(argvars, rettv)
9474 typval_T *argvars;
9475 typval_T *rettv;
9477 rettv->vval.v_string = vim_strsave_fnameescape(
9478 get_tv_string(&argvars[0]), FALSE);
9479 rettv->v_type = VAR_STRING;
9483 * "fnamemodify({fname}, {mods})" function
9485 static void
9486 f_fnamemodify(argvars, rettv)
9487 typval_T *argvars;
9488 typval_T *rettv;
9490 char_u *fname;
9491 char_u *mods;
9492 int usedlen = 0;
9493 int len;
9494 char_u *fbuf = NULL;
9495 char_u buf[NUMBUFLEN];
9497 fname = get_tv_string_chk(&argvars[0]);
9498 mods = get_tv_string_buf_chk(&argvars[1], buf);
9499 if (fname == NULL || mods == NULL)
9500 fname = NULL;
9501 else
9503 len = (int)STRLEN(fname);
9504 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
9507 rettv->v_type = VAR_STRING;
9508 if (fname == NULL)
9509 rettv->vval.v_string = NULL;
9510 else
9511 rettv->vval.v_string = vim_strnsave(fname, len);
9512 vim_free(fbuf);
9515 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
9518 * "foldclosed()" function
9520 static void
9521 foldclosed_both(argvars, rettv, end)
9522 typval_T *argvars;
9523 typval_T *rettv;
9524 int end;
9526 #ifdef FEAT_FOLDING
9527 linenr_T lnum;
9528 linenr_T first, last;
9530 lnum = get_tv_lnum(argvars);
9531 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9533 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
9535 if (end)
9536 rettv->vval.v_number = (varnumber_T)last;
9537 else
9538 rettv->vval.v_number = (varnumber_T)first;
9539 return;
9542 #endif
9543 rettv->vval.v_number = -1;
9547 * "foldclosed()" function
9549 static void
9550 f_foldclosed(argvars, rettv)
9551 typval_T *argvars;
9552 typval_T *rettv;
9554 foldclosed_both(argvars, rettv, FALSE);
9558 * "foldclosedend()" function
9560 static void
9561 f_foldclosedend(argvars, rettv)
9562 typval_T *argvars;
9563 typval_T *rettv;
9565 foldclosed_both(argvars, rettv, TRUE);
9569 * "foldlevel()" function
9571 static void
9572 f_foldlevel(argvars, rettv)
9573 typval_T *argvars;
9574 typval_T *rettv;
9576 #ifdef FEAT_FOLDING
9577 linenr_T lnum;
9579 lnum = get_tv_lnum(argvars);
9580 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9581 rettv->vval.v_number = foldLevel(lnum);
9582 else
9583 #endif
9584 rettv->vval.v_number = 0;
9588 * "foldtext()" function
9590 /*ARGSUSED*/
9591 static void
9592 f_foldtext(argvars, rettv)
9593 typval_T *argvars;
9594 typval_T *rettv;
9596 #ifdef FEAT_FOLDING
9597 linenr_T lnum;
9598 char_u *s;
9599 char_u *r;
9600 int len;
9601 char *txt;
9602 #endif
9604 rettv->v_type = VAR_STRING;
9605 rettv->vval.v_string = NULL;
9606 #ifdef FEAT_FOLDING
9607 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
9608 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
9609 <= curbuf->b_ml.ml_line_count
9610 && vimvars[VV_FOLDDASHES].vv_str != NULL)
9612 /* Find first non-empty line in the fold. */
9613 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
9614 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
9616 if (!linewhite(lnum))
9617 break;
9618 ++lnum;
9621 /* Find interesting text in this line. */
9622 s = skipwhite(ml_get(lnum));
9623 /* skip C comment-start */
9624 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
9626 s = skipwhite(s + 2);
9627 if (*skipwhite(s) == NUL
9628 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
9630 s = skipwhite(ml_get(lnum + 1));
9631 if (*s == '*')
9632 s = skipwhite(s + 1);
9635 txt = _("+-%s%3ld lines: ");
9636 r = alloc((unsigned)(STRLEN(txt)
9637 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
9638 + 20 /* for %3ld */
9639 + STRLEN(s))); /* concatenated */
9640 if (r != NULL)
9642 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
9643 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
9644 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
9645 len = (int)STRLEN(r);
9646 STRCAT(r, s);
9647 /* remove 'foldmarker' and 'commentstring' */
9648 foldtext_cleanup(r + len);
9649 rettv->vval.v_string = r;
9652 #endif
9656 * "foldtextresult(lnum)" function
9658 /*ARGSUSED*/
9659 static void
9660 f_foldtextresult(argvars, rettv)
9661 typval_T *argvars;
9662 typval_T *rettv;
9664 #ifdef FEAT_FOLDING
9665 linenr_T lnum;
9666 char_u *text;
9667 char_u buf[51];
9668 foldinfo_T foldinfo;
9669 int fold_count;
9670 #endif
9672 rettv->v_type = VAR_STRING;
9673 rettv->vval.v_string = NULL;
9674 #ifdef FEAT_FOLDING
9675 lnum = get_tv_lnum(argvars);
9676 /* treat illegal types and illegal string values for {lnum} the same */
9677 if (lnum < 0)
9678 lnum = 0;
9679 fold_count = foldedCount(curwin, lnum, &foldinfo);
9680 if (fold_count > 0)
9682 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
9683 &foldinfo, buf);
9684 if (text == buf)
9685 text = vim_strsave(text);
9686 rettv->vval.v_string = text;
9688 #endif
9692 * "foreground()" function
9694 /*ARGSUSED*/
9695 static void
9696 f_foreground(argvars, rettv)
9697 typval_T *argvars;
9698 typval_T *rettv;
9700 rettv->vval.v_number = 0;
9701 #ifdef FEAT_GUI
9702 if (gui.in_use)
9703 gui_mch_set_foreground();
9704 #else
9705 # ifdef WIN32
9706 win32_set_foreground();
9707 # endif
9708 #endif
9712 * "function()" function
9714 /*ARGSUSED*/
9715 static void
9716 f_function(argvars, rettv)
9717 typval_T *argvars;
9718 typval_T *rettv;
9720 char_u *s;
9722 rettv->vval.v_number = 0;
9723 s = get_tv_string(&argvars[0]);
9724 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
9725 EMSG2(_(e_invarg2), s);
9726 else if (!function_exists(s))
9727 EMSG2(_("E700: Unknown function: %s"), s);
9728 else
9730 rettv->vval.v_string = vim_strsave(s);
9731 rettv->v_type = VAR_FUNC;
9736 * "garbagecollect()" function
9738 /*ARGSUSED*/
9739 static void
9740 f_garbagecollect(argvars, rettv)
9741 typval_T *argvars;
9742 typval_T *rettv;
9744 /* This is postponed until we are back at the toplevel, because we may be
9745 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
9746 want_garbage_collect = TRUE;
9748 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
9749 garbage_collect_at_exit = TRUE;
9753 * "get()" function
9755 static void
9756 f_get(argvars, rettv)
9757 typval_T *argvars;
9758 typval_T *rettv;
9760 listitem_T *li;
9761 list_T *l;
9762 dictitem_T *di;
9763 dict_T *d;
9764 typval_T *tv = NULL;
9766 if (argvars[0].v_type == VAR_LIST)
9768 if ((l = argvars[0].vval.v_list) != NULL)
9770 int error = FALSE;
9772 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
9773 if (!error && li != NULL)
9774 tv = &li->li_tv;
9777 else if (argvars[0].v_type == VAR_DICT)
9779 if ((d = argvars[0].vval.v_dict) != NULL)
9781 di = dict_find(d, get_tv_string(&argvars[1]), -1);
9782 if (di != NULL)
9783 tv = &di->di_tv;
9786 else
9787 EMSG2(_(e_listdictarg), "get()");
9789 if (tv == NULL)
9791 if (argvars[2].v_type == VAR_UNKNOWN)
9792 rettv->vval.v_number = 0;
9793 else
9794 copy_tv(&argvars[2], rettv);
9796 else
9797 copy_tv(tv, rettv);
9800 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
9803 * Get line or list of lines from buffer "buf" into "rettv".
9804 * Return a range (from start to end) of lines in rettv from the specified
9805 * buffer.
9806 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
9808 static void
9809 get_buffer_lines(buf, start, end, retlist, rettv)
9810 buf_T *buf;
9811 linenr_T start;
9812 linenr_T end;
9813 int retlist;
9814 typval_T *rettv;
9816 char_u *p;
9818 if (retlist)
9820 if (rettv_list_alloc(rettv) == FAIL)
9821 return;
9823 else
9824 rettv->vval.v_number = 0;
9826 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
9827 return;
9829 if (!retlist)
9831 if (start >= 1 && start <= buf->b_ml.ml_line_count)
9832 p = ml_get_buf(buf, start, FALSE);
9833 else
9834 p = (char_u *)"";
9836 rettv->v_type = VAR_STRING;
9837 rettv->vval.v_string = vim_strsave(p);
9839 else
9841 if (end < start)
9842 return;
9844 if (start < 1)
9845 start = 1;
9846 if (end > buf->b_ml.ml_line_count)
9847 end = buf->b_ml.ml_line_count;
9848 while (start <= end)
9849 if (list_append_string(rettv->vval.v_list,
9850 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
9851 break;
9856 * "getbufline()" function
9858 static void
9859 f_getbufline(argvars, rettv)
9860 typval_T *argvars;
9861 typval_T *rettv;
9863 linenr_T lnum;
9864 linenr_T end;
9865 buf_T *buf;
9867 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
9868 ++emsg_off;
9869 buf = get_buf_tv(&argvars[0]);
9870 --emsg_off;
9872 lnum = get_tv_lnum_buf(&argvars[1], buf);
9873 if (argvars[2].v_type == VAR_UNKNOWN)
9874 end = lnum;
9875 else
9876 end = get_tv_lnum_buf(&argvars[2], buf);
9878 get_buffer_lines(buf, lnum, end, TRUE, rettv);
9882 * "getbufvar()" function
9884 static void
9885 f_getbufvar(argvars, rettv)
9886 typval_T *argvars;
9887 typval_T *rettv;
9889 buf_T *buf;
9890 buf_T *save_curbuf;
9891 char_u *varname;
9892 dictitem_T *v;
9894 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
9895 varname = get_tv_string_chk(&argvars[1]);
9896 ++emsg_off;
9897 buf = get_buf_tv(&argvars[0]);
9899 rettv->v_type = VAR_STRING;
9900 rettv->vval.v_string = NULL;
9902 if (buf != NULL && varname != NULL)
9904 if (*varname == '&') /* buffer-local-option */
9906 /* set curbuf to be our buf, temporarily */
9907 save_curbuf = curbuf;
9908 curbuf = buf;
9910 get_option_tv(&varname, rettv, TRUE);
9912 /* restore previous notion of curbuf */
9913 curbuf = save_curbuf;
9915 else
9917 if (*varname == NUL)
9918 /* let getbufvar({nr}, "") return the "b:" dictionary. The
9919 * scope prefix before the NUL byte is required by
9920 * find_var_in_ht(). */
9921 varname = (char_u *)"b:" + 2;
9922 /* look up the variable */
9923 v = find_var_in_ht(&buf->b_vars.dv_hashtab, varname, FALSE);
9924 if (v != NULL)
9925 copy_tv(&v->di_tv, rettv);
9929 --emsg_off;
9933 * "getchar()" function
9935 static void
9936 f_getchar(argvars, rettv)
9937 typval_T *argvars;
9938 typval_T *rettv;
9940 varnumber_T n;
9941 int error = FALSE;
9943 /* Position the cursor. Needed after a message that ends in a space. */
9944 windgoto(msg_row, msg_col);
9946 ++no_mapping;
9947 ++allow_keys;
9948 for (;;)
9950 if (argvars[0].v_type == VAR_UNKNOWN)
9951 /* getchar(): blocking wait. */
9952 n = safe_vgetc();
9953 else if (get_tv_number_chk(&argvars[0], &error) == 1)
9954 /* getchar(1): only check if char avail */
9955 n = vpeekc();
9956 else if (error || vpeekc() == NUL)
9957 /* illegal argument or getchar(0) and no char avail: return zero */
9958 n = 0;
9959 else
9960 /* getchar(0) and char avail: return char */
9961 n = safe_vgetc();
9962 if (n == K_IGNORE)
9963 continue;
9964 break;
9966 --no_mapping;
9967 --allow_keys;
9969 vimvars[VV_MOUSE_WIN].vv_nr = 0;
9970 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
9971 vimvars[VV_MOUSE_COL].vv_nr = 0;
9973 rettv->vval.v_number = n;
9974 if (IS_SPECIAL(n) || mod_mask != 0)
9976 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
9977 int i = 0;
9979 /* Turn a special key into three bytes, plus modifier. */
9980 if (mod_mask != 0)
9982 temp[i++] = K_SPECIAL;
9983 temp[i++] = KS_MODIFIER;
9984 temp[i++] = mod_mask;
9986 if (IS_SPECIAL(n))
9988 temp[i++] = K_SPECIAL;
9989 temp[i++] = K_SECOND(n);
9990 temp[i++] = K_THIRD(n);
9992 #ifdef FEAT_MBYTE
9993 else if (has_mbyte)
9994 i += (*mb_char2bytes)(n, temp + i);
9995 #endif
9996 else
9997 temp[i++] = n;
9998 temp[i++] = NUL;
9999 rettv->v_type = VAR_STRING;
10000 rettv->vval.v_string = vim_strsave(temp);
10002 #ifdef FEAT_MOUSE
10003 if (n == K_LEFTMOUSE
10004 || n == K_LEFTMOUSE_NM
10005 || n == K_LEFTDRAG
10006 || n == K_LEFTRELEASE
10007 || n == K_LEFTRELEASE_NM
10008 || n == K_MIDDLEMOUSE
10009 || n == K_MIDDLEDRAG
10010 || n == K_MIDDLERELEASE
10011 || n == K_RIGHTMOUSE
10012 || n == K_RIGHTDRAG
10013 || n == K_RIGHTRELEASE
10014 || n == K_X1MOUSE
10015 || n == K_X1DRAG
10016 || n == K_X1RELEASE
10017 || n == K_X2MOUSE
10018 || n == K_X2DRAG
10019 || n == K_X2RELEASE
10020 || n == K_MOUSEDOWN
10021 || n == K_MOUSEUP)
10023 int row = mouse_row;
10024 int col = mouse_col;
10025 win_T *win;
10026 linenr_T lnum;
10027 # ifdef FEAT_WINDOWS
10028 win_T *wp;
10029 # endif
10030 int n = 1;
10032 if (row >= 0 && col >= 0)
10034 /* Find the window at the mouse coordinates and compute the
10035 * text position. */
10036 win = mouse_find_win(&row, &col);
10037 (void)mouse_comp_pos(win, &row, &col, &lnum);
10038 # ifdef FEAT_WINDOWS
10039 for (wp = firstwin; wp != win; wp = wp->w_next)
10040 ++n;
10041 # endif
10042 vimvars[VV_MOUSE_WIN].vv_nr = n;
10043 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
10044 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
10047 #endif
10052 * "getcharmod()" function
10054 /*ARGSUSED*/
10055 static void
10056 f_getcharmod(argvars, rettv)
10057 typval_T *argvars;
10058 typval_T *rettv;
10060 rettv->vval.v_number = mod_mask;
10064 * "getcmdline()" function
10066 /*ARGSUSED*/
10067 static void
10068 f_getcmdline(argvars, rettv)
10069 typval_T *argvars;
10070 typval_T *rettv;
10072 rettv->v_type = VAR_STRING;
10073 rettv->vval.v_string = get_cmdline_str();
10077 * "getcmdpos()" function
10079 /*ARGSUSED*/
10080 static void
10081 f_getcmdpos(argvars, rettv)
10082 typval_T *argvars;
10083 typval_T *rettv;
10085 rettv->vval.v_number = get_cmdline_pos() + 1;
10089 * "getcmdtype()" function
10091 /*ARGSUSED*/
10092 static void
10093 f_getcmdtype(argvars, rettv)
10094 typval_T *argvars;
10095 typval_T *rettv;
10097 rettv->v_type = VAR_STRING;
10098 rettv->vval.v_string = alloc(2);
10099 if (rettv->vval.v_string != NULL)
10101 rettv->vval.v_string[0] = get_cmdline_type();
10102 rettv->vval.v_string[1] = NUL;
10107 * "getcwd()" function
10109 /*ARGSUSED*/
10110 static void
10111 f_getcwd(argvars, rettv)
10112 typval_T *argvars;
10113 typval_T *rettv;
10115 char_u cwd[MAXPATHL];
10117 rettv->v_type = VAR_STRING;
10118 if (mch_dirname(cwd, MAXPATHL) == FAIL)
10119 rettv->vval.v_string = NULL;
10120 else
10122 rettv->vval.v_string = vim_strsave(cwd);
10123 #ifdef BACKSLASH_IN_FILENAME
10124 if (rettv->vval.v_string != NULL)
10125 slash_adjust(rettv->vval.v_string);
10126 #endif
10131 * "getfontname()" function
10133 /*ARGSUSED*/
10134 static void
10135 f_getfontname(argvars, rettv)
10136 typval_T *argvars;
10137 typval_T *rettv;
10139 rettv->v_type = VAR_STRING;
10140 rettv->vval.v_string = NULL;
10141 #ifdef FEAT_GUI
10142 if (gui.in_use)
10144 GuiFont font;
10145 char_u *name = NULL;
10147 if (argvars[0].v_type == VAR_UNKNOWN)
10149 /* Get the "Normal" font. Either the name saved by
10150 * hl_set_font_name() or from the font ID. */
10151 font = gui.norm_font;
10152 name = hl_get_font_name();
10154 else
10156 name = get_tv_string(&argvars[0]);
10157 if (STRCMP(name, "*") == 0) /* don't use font dialog */
10158 return;
10159 font = gui_mch_get_font(name, FALSE);
10160 if (font == NOFONT)
10161 return; /* Invalid font name, return empty string. */
10163 rettv->vval.v_string = gui_mch_get_fontname(font, name);
10164 if (argvars[0].v_type != VAR_UNKNOWN)
10165 gui_mch_free_font(font);
10167 #endif
10171 * "getfperm({fname})" function
10173 static void
10174 f_getfperm(argvars, rettv)
10175 typval_T *argvars;
10176 typval_T *rettv;
10178 char_u *fname;
10179 struct stat st;
10180 char_u *perm = NULL;
10181 char_u flags[] = "rwx";
10182 int i;
10184 fname = get_tv_string(&argvars[0]);
10186 rettv->v_type = VAR_STRING;
10187 if (mch_stat((char *)fname, &st) >= 0)
10189 perm = vim_strsave((char_u *)"---------");
10190 if (perm != NULL)
10192 for (i = 0; i < 9; i++)
10194 if (st.st_mode & (1 << (8 - i)))
10195 perm[i] = flags[i % 3];
10199 rettv->vval.v_string = perm;
10203 * "getfsize({fname})" function
10205 static void
10206 f_getfsize(argvars, rettv)
10207 typval_T *argvars;
10208 typval_T *rettv;
10210 char_u *fname;
10211 struct stat st;
10213 fname = get_tv_string(&argvars[0]);
10215 rettv->v_type = VAR_NUMBER;
10217 if (mch_stat((char *)fname, &st) >= 0)
10219 if (mch_isdir(fname))
10220 rettv->vval.v_number = 0;
10221 else
10223 rettv->vval.v_number = (varnumber_T)st.st_size;
10225 /* non-perfect check for overflow */
10226 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
10227 rettv->vval.v_number = -2;
10230 else
10231 rettv->vval.v_number = -1;
10235 * "getftime({fname})" function
10237 static void
10238 f_getftime(argvars, rettv)
10239 typval_T *argvars;
10240 typval_T *rettv;
10242 char_u *fname;
10243 struct stat st;
10245 fname = get_tv_string(&argvars[0]);
10247 if (mch_stat((char *)fname, &st) >= 0)
10248 rettv->vval.v_number = (varnumber_T)st.st_mtime;
10249 else
10250 rettv->vval.v_number = -1;
10254 * "getftype({fname})" function
10256 static void
10257 f_getftype(argvars, rettv)
10258 typval_T *argvars;
10259 typval_T *rettv;
10261 char_u *fname;
10262 struct stat st;
10263 char_u *type = NULL;
10264 char *t;
10266 fname = get_tv_string(&argvars[0]);
10268 rettv->v_type = VAR_STRING;
10269 if (mch_lstat((char *)fname, &st) >= 0)
10271 #ifdef S_ISREG
10272 if (S_ISREG(st.st_mode))
10273 t = "file";
10274 else if (S_ISDIR(st.st_mode))
10275 t = "dir";
10276 # ifdef S_ISLNK
10277 else if (S_ISLNK(st.st_mode))
10278 t = "link";
10279 # endif
10280 # ifdef S_ISBLK
10281 else if (S_ISBLK(st.st_mode))
10282 t = "bdev";
10283 # endif
10284 # ifdef S_ISCHR
10285 else if (S_ISCHR(st.st_mode))
10286 t = "cdev";
10287 # endif
10288 # ifdef S_ISFIFO
10289 else if (S_ISFIFO(st.st_mode))
10290 t = "fifo";
10291 # endif
10292 # ifdef S_ISSOCK
10293 else if (S_ISSOCK(st.st_mode))
10294 t = "fifo";
10295 # endif
10296 else
10297 t = "other";
10298 #else
10299 # ifdef S_IFMT
10300 switch (st.st_mode & S_IFMT)
10302 case S_IFREG: t = "file"; break;
10303 case S_IFDIR: t = "dir"; break;
10304 # ifdef S_IFLNK
10305 case S_IFLNK: t = "link"; break;
10306 # endif
10307 # ifdef S_IFBLK
10308 case S_IFBLK: t = "bdev"; break;
10309 # endif
10310 # ifdef S_IFCHR
10311 case S_IFCHR: t = "cdev"; break;
10312 # endif
10313 # ifdef S_IFIFO
10314 case S_IFIFO: t = "fifo"; break;
10315 # endif
10316 # ifdef S_IFSOCK
10317 case S_IFSOCK: t = "socket"; break;
10318 # endif
10319 default: t = "other";
10321 # else
10322 if (mch_isdir(fname))
10323 t = "dir";
10324 else
10325 t = "file";
10326 # endif
10327 #endif
10328 type = vim_strsave((char_u *)t);
10330 rettv->vval.v_string = type;
10334 * "getline(lnum, [end])" function
10336 static void
10337 f_getline(argvars, rettv)
10338 typval_T *argvars;
10339 typval_T *rettv;
10341 linenr_T lnum;
10342 linenr_T end;
10343 int retlist;
10345 lnum = get_tv_lnum(argvars);
10346 if (argvars[1].v_type == VAR_UNKNOWN)
10348 end = 0;
10349 retlist = FALSE;
10351 else
10353 end = get_tv_lnum(&argvars[1]);
10354 retlist = TRUE;
10357 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
10361 * "getmatches()" function
10363 /*ARGSUSED*/
10364 static void
10365 f_getmatches(argvars, rettv)
10366 typval_T *argvars;
10367 typval_T *rettv;
10369 #ifdef FEAT_SEARCH_EXTRA
10370 dict_T *dict;
10371 matchitem_T *cur = curwin->w_match_head;
10373 rettv->vval.v_number = 0;
10375 if (rettv_list_alloc(rettv) == OK)
10377 while (cur != NULL)
10379 dict = dict_alloc();
10380 if (dict == NULL)
10381 return;
10382 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
10383 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
10384 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
10385 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
10386 list_append_dict(rettv->vval.v_list, dict);
10387 cur = cur->next;
10390 #endif
10394 * "getpid()" function
10396 /*ARGSUSED*/
10397 static void
10398 f_getpid(argvars, rettv)
10399 typval_T *argvars;
10400 typval_T *rettv;
10402 rettv->vval.v_number = mch_get_pid();
10406 * "getpos(string)" function
10408 static void
10409 f_getpos(argvars, rettv)
10410 typval_T *argvars;
10411 typval_T *rettv;
10413 pos_T *fp;
10414 list_T *l;
10415 int fnum = -1;
10417 if (rettv_list_alloc(rettv) == OK)
10419 l = rettv->vval.v_list;
10420 fp = var2fpos(&argvars[0], TRUE, &fnum);
10421 if (fnum != -1)
10422 list_append_number(l, (varnumber_T)fnum);
10423 else
10424 list_append_number(l, (varnumber_T)0);
10425 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
10426 : (varnumber_T)0);
10427 list_append_number(l, (fp != NULL)
10428 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
10429 : (varnumber_T)0);
10430 list_append_number(l,
10431 #ifdef FEAT_VIRTUALEDIT
10432 (fp != NULL) ? (varnumber_T)fp->coladd :
10433 #endif
10434 (varnumber_T)0);
10436 else
10437 rettv->vval.v_number = FALSE;
10441 * "getqflist()" and "getloclist()" functions
10443 /*ARGSUSED*/
10444 static void
10445 f_getqflist(argvars, rettv)
10446 typval_T *argvars;
10447 typval_T *rettv;
10449 #ifdef FEAT_QUICKFIX
10450 win_T *wp;
10451 #endif
10453 rettv->vval.v_number = 0;
10454 #ifdef FEAT_QUICKFIX
10455 if (rettv_list_alloc(rettv) == OK)
10457 wp = NULL;
10458 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
10460 wp = find_win_by_nr(&argvars[0], NULL);
10461 if (wp == NULL)
10462 return;
10465 (void)get_errorlist(wp, rettv->vval.v_list);
10467 #endif
10471 * "getreg()" function
10473 static void
10474 f_getreg(argvars, rettv)
10475 typval_T *argvars;
10476 typval_T *rettv;
10478 char_u *strregname;
10479 int regname;
10480 int arg2 = FALSE;
10481 int error = FALSE;
10483 if (argvars[0].v_type != VAR_UNKNOWN)
10485 strregname = get_tv_string_chk(&argvars[0]);
10486 error = strregname == NULL;
10487 if (argvars[1].v_type != VAR_UNKNOWN)
10488 arg2 = get_tv_number_chk(&argvars[1], &error);
10490 else
10491 strregname = vimvars[VV_REG].vv_str;
10492 regname = (strregname == NULL ? '"' : *strregname);
10493 if (regname == 0)
10494 regname = '"';
10496 rettv->v_type = VAR_STRING;
10497 rettv->vval.v_string = error ? NULL :
10498 get_reg_contents(regname, TRUE, arg2);
10502 * "getregtype()" function
10504 static void
10505 f_getregtype(argvars, rettv)
10506 typval_T *argvars;
10507 typval_T *rettv;
10509 char_u *strregname;
10510 int regname;
10511 char_u buf[NUMBUFLEN + 2];
10512 long reglen = 0;
10514 if (argvars[0].v_type != VAR_UNKNOWN)
10516 strregname = get_tv_string_chk(&argvars[0]);
10517 if (strregname == NULL) /* type error; errmsg already given */
10519 rettv->v_type = VAR_STRING;
10520 rettv->vval.v_string = NULL;
10521 return;
10524 else
10525 /* Default to v:register */
10526 strregname = vimvars[VV_REG].vv_str;
10528 regname = (strregname == NULL ? '"' : *strregname);
10529 if (regname == 0)
10530 regname = '"';
10532 buf[0] = NUL;
10533 buf[1] = NUL;
10534 switch (get_reg_type(regname, &reglen))
10536 case MLINE: buf[0] = 'V'; break;
10537 case MCHAR: buf[0] = 'v'; break;
10538 #ifdef FEAT_VISUAL
10539 case MBLOCK:
10540 buf[0] = Ctrl_V;
10541 sprintf((char *)buf + 1, "%ld", reglen + 1);
10542 break;
10543 #endif
10545 rettv->v_type = VAR_STRING;
10546 rettv->vval.v_string = vim_strsave(buf);
10550 * "gettabwinvar()" function
10552 static void
10553 f_gettabwinvar(argvars, rettv)
10554 typval_T *argvars;
10555 typval_T *rettv;
10557 getwinvar(argvars, rettv, 1);
10561 * "getwinposx()" function
10563 /*ARGSUSED*/
10564 static void
10565 f_getwinposx(argvars, rettv)
10566 typval_T *argvars;
10567 typval_T *rettv;
10569 rettv->vval.v_number = -1;
10570 #ifdef FEAT_GUI
10571 if (gui.in_use)
10573 int x, y;
10575 if (gui_mch_get_winpos(&x, &y) == OK)
10576 rettv->vval.v_number = x;
10578 #endif
10582 * "getwinposy()" function
10584 /*ARGSUSED*/
10585 static void
10586 f_getwinposy(argvars, rettv)
10587 typval_T *argvars;
10588 typval_T *rettv;
10590 rettv->vval.v_number = -1;
10591 #ifdef FEAT_GUI
10592 if (gui.in_use)
10594 int x, y;
10596 if (gui_mch_get_winpos(&x, &y) == OK)
10597 rettv->vval.v_number = y;
10599 #endif
10603 * Find window specifed by "vp" in tabpage "tp".
10605 static win_T *
10606 find_win_by_nr(vp, tp)
10607 typval_T *vp;
10608 tabpage_T *tp; /* NULL for current tab page */
10610 #ifdef FEAT_WINDOWS
10611 win_T *wp;
10612 #endif
10613 int nr;
10615 nr = get_tv_number_chk(vp, NULL);
10617 #ifdef FEAT_WINDOWS
10618 if (nr < 0)
10619 return NULL;
10620 if (nr == 0)
10621 return curwin;
10623 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
10624 wp != NULL; wp = wp->w_next)
10625 if (--nr <= 0)
10626 break;
10627 return wp;
10628 #else
10629 if (nr == 0 || nr == 1)
10630 return curwin;
10631 return NULL;
10632 #endif
10636 * "getwinvar()" function
10638 static void
10639 f_getwinvar(argvars, rettv)
10640 typval_T *argvars;
10641 typval_T *rettv;
10643 getwinvar(argvars, rettv, 0);
10647 * getwinvar() and gettabwinvar()
10649 static void
10650 getwinvar(argvars, rettv, off)
10651 typval_T *argvars;
10652 typval_T *rettv;
10653 int off; /* 1 for gettabwinvar() */
10655 win_T *win, *oldcurwin;
10656 char_u *varname;
10657 dictitem_T *v;
10658 tabpage_T *tp;
10660 #ifdef FEAT_WINDOWS
10661 if (off == 1)
10662 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
10663 else
10664 tp = curtab;
10665 #endif
10666 win = find_win_by_nr(&argvars[off], tp);
10667 varname = get_tv_string_chk(&argvars[off + 1]);
10668 ++emsg_off;
10670 rettv->v_type = VAR_STRING;
10671 rettv->vval.v_string = NULL;
10673 if (win != NULL && varname != NULL)
10675 /* Set curwin to be our win, temporarily. Also set curbuf, so
10676 * that we can get buffer-local options. */
10677 oldcurwin = curwin;
10678 curwin = win;
10679 curbuf = win->w_buffer;
10681 if (*varname == '&') /* window-local-option */
10682 get_option_tv(&varname, rettv, 1);
10683 else
10685 if (*varname == NUL)
10686 /* let getwinvar({nr}, "") return the "w:" dictionary. The
10687 * scope prefix before the NUL byte is required by
10688 * find_var_in_ht(). */
10689 varname = (char_u *)"w:" + 2;
10690 /* look up the variable */
10691 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
10692 if (v != NULL)
10693 copy_tv(&v->di_tv, rettv);
10696 /* restore previous notion of curwin */
10697 curwin = oldcurwin;
10698 curbuf = curwin->w_buffer;
10701 --emsg_off;
10705 * "glob()" function
10707 static void
10708 f_glob(argvars, rettv)
10709 typval_T *argvars;
10710 typval_T *rettv;
10712 expand_T xpc;
10714 ExpandInit(&xpc);
10715 xpc.xp_context = EXPAND_FILES;
10716 rettv->v_type = VAR_STRING;
10717 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
10718 NULL, WILD_USE_NL|WILD_SILENT, WILD_ALL);
10722 * "globpath()" function
10724 static void
10725 f_globpath(argvars, rettv)
10726 typval_T *argvars;
10727 typval_T *rettv;
10729 char_u buf1[NUMBUFLEN];
10730 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
10732 rettv->v_type = VAR_STRING;
10733 if (file == NULL)
10734 rettv->vval.v_string = NULL;
10735 else
10736 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file);
10740 * "has()" function
10742 static void
10743 f_has(argvars, rettv)
10744 typval_T *argvars;
10745 typval_T *rettv;
10747 int i;
10748 char_u *name;
10749 int n = FALSE;
10750 static char *(has_list[]) =
10752 #ifdef AMIGA
10753 "amiga",
10754 # ifdef FEAT_ARP
10755 "arp",
10756 # endif
10757 #endif
10758 #ifdef __BEOS__
10759 "beos",
10760 #endif
10761 #ifdef MSDOS
10762 # ifdef DJGPP
10763 "dos32",
10764 # else
10765 "dos16",
10766 # endif
10767 #endif
10768 #ifdef MACOS
10769 "mac",
10770 #endif
10771 #if defined(MACOS_X_UNIX)
10772 "macunix",
10773 #endif
10774 #ifdef OS2
10775 "os2",
10776 #endif
10777 #ifdef __QNX__
10778 "qnx",
10779 #endif
10780 #ifdef RISCOS
10781 "riscos",
10782 #endif
10783 #ifdef UNIX
10784 "unix",
10785 #endif
10786 #ifdef VMS
10787 "vms",
10788 #endif
10789 #ifdef WIN16
10790 "win16",
10791 #endif
10792 #ifdef WIN32
10793 "win32",
10794 #endif
10795 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
10796 "win32unix",
10797 #endif
10798 #ifdef WIN64
10799 "win64",
10800 #endif
10801 #ifdef EBCDIC
10802 "ebcdic",
10803 #endif
10804 #ifndef CASE_INSENSITIVE_FILENAME
10805 "fname_case",
10806 #endif
10807 #ifdef FEAT_ARABIC
10808 "arabic",
10809 #endif
10810 #ifdef FEAT_AUTOCMD
10811 "autocmd",
10812 #endif
10813 #ifdef FEAT_BEVAL
10814 "balloon_eval",
10815 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
10816 "balloon_multiline",
10817 # endif
10818 #endif
10819 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
10820 "builtin_terms",
10821 # ifdef ALL_BUILTIN_TCAPS
10822 "all_builtin_terms",
10823 # endif
10824 #endif
10825 #ifdef FEAT_BYTEOFF
10826 "byte_offset",
10827 #endif
10828 #ifdef FEAT_CINDENT
10829 "cindent",
10830 #endif
10831 #ifdef FEAT_CLIENTSERVER
10832 "clientserver",
10833 #endif
10834 #ifdef FEAT_CLIPBOARD
10835 "clipboard",
10836 #endif
10837 #ifdef FEAT_CMDL_COMPL
10838 "cmdline_compl",
10839 #endif
10840 #ifdef FEAT_CMDHIST
10841 "cmdline_hist",
10842 #endif
10843 #ifdef FEAT_COMMENTS
10844 "comments",
10845 #endif
10846 #ifdef FEAT_CRYPT
10847 "cryptv",
10848 #endif
10849 #ifdef FEAT_CSCOPE
10850 "cscope",
10851 #endif
10852 #ifdef CURSOR_SHAPE
10853 "cursorshape",
10854 #endif
10855 #ifdef DEBUG
10856 "debug",
10857 #endif
10858 #ifdef FEAT_CON_DIALOG
10859 "dialog_con",
10860 #endif
10861 #ifdef FEAT_GUI_DIALOG
10862 "dialog_gui",
10863 #endif
10864 #ifdef FEAT_DIFF
10865 "diff",
10866 #endif
10867 #ifdef FEAT_DIGRAPHS
10868 "digraphs",
10869 #endif
10870 #ifdef FEAT_DND
10871 "dnd",
10872 #endif
10873 #ifdef FEAT_EMACS_TAGS
10874 "emacs_tags",
10875 #endif
10876 "eval", /* always present, of course! */
10877 #ifdef FEAT_EX_EXTRA
10878 "ex_extra",
10879 #endif
10880 #ifdef FEAT_SEARCH_EXTRA
10881 "extra_search",
10882 #endif
10883 #ifdef FEAT_FKMAP
10884 "farsi",
10885 #endif
10886 #ifdef FEAT_SEARCHPATH
10887 "file_in_path",
10888 #endif
10889 #if defined(UNIX) && !defined(USE_SYSTEM)
10890 "filterpipe",
10891 #endif
10892 #ifdef FEAT_FIND_ID
10893 "find_in_path",
10894 #endif
10895 #ifdef FEAT_FOLDING
10896 "folding",
10897 #endif
10898 #ifdef FEAT_FOOTER
10899 "footer",
10900 #endif
10901 #if !defined(USE_SYSTEM) && defined(UNIX)
10902 "fork",
10903 #endif
10904 #ifdef FEAT_GETTEXT
10905 "gettext",
10906 #endif
10907 #ifdef FEAT_GUI
10908 "gui",
10909 #endif
10910 #ifdef FEAT_GUI_ATHENA
10911 # ifdef FEAT_GUI_NEXTAW
10912 "gui_neXtaw",
10913 # else
10914 "gui_athena",
10915 # endif
10916 #endif
10917 #ifdef FEAT_GUI_GTK
10918 "gui_gtk",
10919 # ifdef HAVE_GTK2
10920 "gui_gtk2",
10921 # endif
10922 #endif
10923 #ifdef FEAT_GUI_GNOME
10924 "gui_gnome",
10925 #endif
10926 #ifdef FEAT_GUI_MAC
10927 "gui_mac",
10928 #endif
10929 #ifdef FEAT_GUI_MOTIF
10930 "gui_motif",
10931 #endif
10932 #ifdef FEAT_GUI_PHOTON
10933 "gui_photon",
10934 #endif
10935 #ifdef FEAT_GUI_W16
10936 "gui_win16",
10937 #endif
10938 #ifdef FEAT_GUI_W32
10939 "gui_win32",
10940 #endif
10941 #ifdef FEAT_HANGULIN
10942 "hangul_input",
10943 #endif
10944 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
10945 "iconv",
10946 #endif
10947 #ifdef FEAT_INS_EXPAND
10948 "insert_expand",
10949 #endif
10950 #ifdef FEAT_JUMPLIST
10951 "jumplist",
10952 #endif
10953 #ifdef FEAT_KEYMAP
10954 "keymap",
10955 #endif
10956 #ifdef FEAT_LANGMAP
10957 "langmap",
10958 #endif
10959 #ifdef FEAT_LIBCALL
10960 "libcall",
10961 #endif
10962 #ifdef FEAT_LINEBREAK
10963 "linebreak",
10964 #endif
10965 #ifdef FEAT_LISP
10966 "lispindent",
10967 #endif
10968 #ifdef FEAT_LISTCMDS
10969 "listcmds",
10970 #endif
10971 #ifdef FEAT_LOCALMAP
10972 "localmap",
10973 #endif
10974 #ifdef FEAT_MENU
10975 "menu",
10976 #endif
10977 #ifdef FEAT_SESSION
10978 "mksession",
10979 #endif
10980 #ifdef FEAT_MODIFY_FNAME
10981 "modify_fname",
10982 #endif
10983 #ifdef FEAT_MOUSE
10984 "mouse",
10985 #endif
10986 #ifdef FEAT_MOUSESHAPE
10987 "mouseshape",
10988 #endif
10989 #if defined(UNIX) || defined(VMS)
10990 # ifdef FEAT_MOUSE_DEC
10991 "mouse_dec",
10992 # endif
10993 # ifdef FEAT_MOUSE_GPM
10994 "mouse_gpm",
10995 # endif
10996 # ifdef FEAT_MOUSE_JSB
10997 "mouse_jsbterm",
10998 # endif
10999 # ifdef FEAT_MOUSE_NET
11000 "mouse_netterm",
11001 # endif
11002 # ifdef FEAT_MOUSE_PTERM
11003 "mouse_pterm",
11004 # endif
11005 # ifdef FEAT_MOUSE_XTERM
11006 "mouse_xterm",
11007 # endif
11008 #endif
11009 #ifdef FEAT_MBYTE
11010 "multi_byte",
11011 #endif
11012 #ifdef FEAT_MBYTE_IME
11013 "multi_byte_ime",
11014 #endif
11015 #ifdef FEAT_MULTI_LANG
11016 "multi_lang",
11017 #endif
11018 #ifdef FEAT_MZSCHEME
11019 #ifndef DYNAMIC_MZSCHEME
11020 "mzscheme",
11021 #endif
11022 #endif
11023 #ifdef FEAT_OLE
11024 "ole",
11025 #endif
11026 #ifdef FEAT_OSFILETYPE
11027 "osfiletype",
11028 #endif
11029 #ifdef FEAT_PATH_EXTRA
11030 "path_extra",
11031 #endif
11032 #ifdef FEAT_PERL
11033 #ifndef DYNAMIC_PERL
11034 "perl",
11035 #endif
11036 #endif
11037 #ifdef FEAT_PYTHON
11038 #ifndef DYNAMIC_PYTHON
11039 "python",
11040 #endif
11041 #endif
11042 #ifdef FEAT_POSTSCRIPT
11043 "postscript",
11044 #endif
11045 #ifdef FEAT_PRINTER
11046 "printer",
11047 #endif
11048 #ifdef FEAT_PROFILE
11049 "profile",
11050 #endif
11051 #ifdef FEAT_RELTIME
11052 "reltime",
11053 #endif
11054 #ifdef FEAT_QUICKFIX
11055 "quickfix",
11056 #endif
11057 #ifdef FEAT_RIGHTLEFT
11058 "rightleft",
11059 #endif
11060 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11061 "ruby",
11062 #endif
11063 #ifdef FEAT_SCROLLBIND
11064 "scrollbind",
11065 #endif
11066 #ifdef FEAT_CMDL_INFO
11067 "showcmd",
11068 "cmdline_info",
11069 #endif
11070 #ifdef FEAT_SIGNS
11071 "signs",
11072 #endif
11073 #ifdef FEAT_SMARTINDENT
11074 "smartindent",
11075 #endif
11076 #ifdef FEAT_SNIFF
11077 "sniff",
11078 #endif
11079 #ifdef FEAT_STL_OPT
11080 "statusline",
11081 #endif
11082 #ifdef FEAT_SUN_WORKSHOP
11083 "sun_workshop",
11084 #endif
11085 #ifdef FEAT_NETBEANS_INTG
11086 "netbeans_intg",
11087 #endif
11088 #ifdef FEAT_SPELL
11089 "spell",
11090 #endif
11091 #ifdef FEAT_SYN_HL
11092 "syntax",
11093 #endif
11094 #if defined(USE_SYSTEM) || !defined(UNIX)
11095 "system",
11096 #endif
11097 #ifdef FEAT_TAG_BINS
11098 "tag_binary",
11099 #endif
11100 #ifdef FEAT_TAG_OLDSTATIC
11101 "tag_old_static",
11102 #endif
11103 #ifdef FEAT_TAG_ANYWHITE
11104 "tag_any_white",
11105 #endif
11106 #ifdef FEAT_TCL
11107 # ifndef DYNAMIC_TCL
11108 "tcl",
11109 # endif
11110 #endif
11111 #ifdef TERMINFO
11112 "terminfo",
11113 #endif
11114 #ifdef FEAT_TERMRESPONSE
11115 "termresponse",
11116 #endif
11117 #ifdef FEAT_TEXTOBJ
11118 "textobjects",
11119 #endif
11120 #ifdef HAVE_TGETENT
11121 "tgetent",
11122 #endif
11123 #ifdef FEAT_TITLE
11124 "title",
11125 #endif
11126 #ifdef FEAT_TOOLBAR
11127 "toolbar",
11128 #endif
11129 #ifdef FEAT_USR_CMDS
11130 "user-commands", /* was accidentally included in 5.4 */
11131 "user_commands",
11132 #endif
11133 #ifdef FEAT_VIMINFO
11134 "viminfo",
11135 #endif
11136 #ifdef FEAT_VERTSPLIT
11137 "vertsplit",
11138 #endif
11139 #ifdef FEAT_VIRTUALEDIT
11140 "virtualedit",
11141 #endif
11142 #ifdef FEAT_VISUAL
11143 "visual",
11144 #endif
11145 #ifdef FEAT_VISUALEXTRA
11146 "visualextra",
11147 #endif
11148 #ifdef FEAT_VREPLACE
11149 "vreplace",
11150 #endif
11151 #ifdef FEAT_WILDIGN
11152 "wildignore",
11153 #endif
11154 #ifdef FEAT_WILDMENU
11155 "wildmenu",
11156 #endif
11157 #ifdef FEAT_WINDOWS
11158 "windows",
11159 #endif
11160 #ifdef FEAT_WAK
11161 "winaltkeys",
11162 #endif
11163 #ifdef FEAT_WRITEBACKUP
11164 "writebackup",
11165 #endif
11166 #ifdef FEAT_XIM
11167 "xim",
11168 #endif
11169 #ifdef FEAT_XFONTSET
11170 "xfontset",
11171 #endif
11172 #ifdef USE_XSMP
11173 "xsmp",
11174 #endif
11175 #ifdef USE_XSMP_INTERACT
11176 "xsmp_interact",
11177 #endif
11178 #ifdef FEAT_XCLIPBOARD
11179 "xterm_clipboard",
11180 #endif
11181 #ifdef FEAT_XTERM_SAVE
11182 "xterm_save",
11183 #endif
11184 #if defined(UNIX) && defined(FEAT_X11)
11185 "X11",
11186 #endif
11187 NULL
11190 name = get_tv_string(&argvars[0]);
11191 for (i = 0; has_list[i] != NULL; ++i)
11192 if (STRICMP(name, has_list[i]) == 0)
11194 n = TRUE;
11195 break;
11198 if (n == FALSE)
11200 if (STRNICMP(name, "patch", 5) == 0)
11201 n = has_patch(atoi((char *)name + 5));
11202 else if (STRICMP(name, "vim_starting") == 0)
11203 n = (starting != 0);
11204 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
11205 else if (STRICMP(name, "balloon_multiline") == 0)
11206 n = multiline_balloon_available();
11207 #endif
11208 #ifdef DYNAMIC_TCL
11209 else if (STRICMP(name, "tcl") == 0)
11210 n = tcl_enabled(FALSE);
11211 #endif
11212 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
11213 else if (STRICMP(name, "iconv") == 0)
11214 n = iconv_enabled(FALSE);
11215 #endif
11216 #ifdef DYNAMIC_MZSCHEME
11217 else if (STRICMP(name, "mzscheme") == 0)
11218 n = mzscheme_enabled(FALSE);
11219 #endif
11220 #ifdef DYNAMIC_RUBY
11221 else if (STRICMP(name, "ruby") == 0)
11222 n = ruby_enabled(FALSE);
11223 #endif
11224 #ifdef DYNAMIC_PYTHON
11225 else if (STRICMP(name, "python") == 0)
11226 n = python_enabled(FALSE);
11227 #endif
11228 #ifdef DYNAMIC_PERL
11229 else if (STRICMP(name, "perl") == 0)
11230 n = perl_enabled(FALSE);
11231 #endif
11232 #ifdef FEAT_GUI
11233 else if (STRICMP(name, "gui_running") == 0)
11234 n = (gui.in_use || gui.starting);
11235 # ifdef FEAT_GUI_W32
11236 else if (STRICMP(name, "gui_win32s") == 0)
11237 n = gui_is_win32s();
11238 # endif
11239 # ifdef FEAT_BROWSE
11240 else if (STRICMP(name, "browse") == 0)
11241 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
11242 # endif
11243 #endif
11244 #ifdef FEAT_SYN_HL
11245 else if (STRICMP(name, "syntax_items") == 0)
11246 n = syntax_present(curbuf);
11247 #endif
11248 #if defined(WIN3264)
11249 else if (STRICMP(name, "win95") == 0)
11250 n = mch_windows95();
11251 #endif
11252 #ifdef FEAT_NETBEANS_INTG
11253 else if (STRICMP(name, "netbeans_enabled") == 0)
11254 n = usingNetbeans;
11255 #endif
11258 rettv->vval.v_number = n;
11262 * "has_key()" function
11264 static void
11265 f_has_key(argvars, rettv)
11266 typval_T *argvars;
11267 typval_T *rettv;
11269 rettv->vval.v_number = 0;
11270 if (argvars[0].v_type != VAR_DICT)
11272 EMSG(_(e_dictreq));
11273 return;
11275 if (argvars[0].vval.v_dict == NULL)
11276 return;
11278 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
11279 get_tv_string(&argvars[1]), -1) != NULL;
11283 * "haslocaldir()" function
11285 /*ARGSUSED*/
11286 static void
11287 f_haslocaldir(argvars, rettv)
11288 typval_T *argvars;
11289 typval_T *rettv;
11291 rettv->vval.v_number = (curwin->w_localdir != NULL);
11295 * "hasmapto()" function
11297 static void
11298 f_hasmapto(argvars, rettv)
11299 typval_T *argvars;
11300 typval_T *rettv;
11302 char_u *name;
11303 char_u *mode;
11304 char_u buf[NUMBUFLEN];
11305 int abbr = FALSE;
11307 name = get_tv_string(&argvars[0]);
11308 if (argvars[1].v_type == VAR_UNKNOWN)
11309 mode = (char_u *)"nvo";
11310 else
11312 mode = get_tv_string_buf(&argvars[1], buf);
11313 if (argvars[2].v_type != VAR_UNKNOWN)
11314 abbr = get_tv_number(&argvars[2]);
11317 if (map_to_exists(name, mode, abbr))
11318 rettv->vval.v_number = TRUE;
11319 else
11320 rettv->vval.v_number = FALSE;
11324 * "histadd()" function
11326 /*ARGSUSED*/
11327 static void
11328 f_histadd(argvars, rettv)
11329 typval_T *argvars;
11330 typval_T *rettv;
11332 #ifdef FEAT_CMDHIST
11333 int histype;
11334 char_u *str;
11335 char_u buf[NUMBUFLEN];
11336 #endif
11338 rettv->vval.v_number = FALSE;
11339 if (check_restricted() || check_secure())
11340 return;
11341 #ifdef FEAT_CMDHIST
11342 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11343 histype = str != NULL ? get_histtype(str) : -1;
11344 if (histype >= 0)
11346 str = get_tv_string_buf(&argvars[1], buf);
11347 if (*str != NUL)
11349 add_to_history(histype, str, FALSE, NUL);
11350 rettv->vval.v_number = TRUE;
11351 return;
11354 #endif
11358 * "histdel()" function
11360 /*ARGSUSED*/
11361 static void
11362 f_histdel(argvars, rettv)
11363 typval_T *argvars;
11364 typval_T *rettv;
11366 #ifdef FEAT_CMDHIST
11367 int n;
11368 char_u buf[NUMBUFLEN];
11369 char_u *str;
11371 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11372 if (str == NULL)
11373 n = 0;
11374 else if (argvars[1].v_type == VAR_UNKNOWN)
11375 /* only one argument: clear entire history */
11376 n = clr_history(get_histtype(str));
11377 else if (argvars[1].v_type == VAR_NUMBER)
11378 /* index given: remove that entry */
11379 n = del_history_idx(get_histtype(str),
11380 (int)get_tv_number(&argvars[1]));
11381 else
11382 /* string given: remove all matching entries */
11383 n = del_history_entry(get_histtype(str),
11384 get_tv_string_buf(&argvars[1], buf));
11385 rettv->vval.v_number = n;
11386 #else
11387 rettv->vval.v_number = 0;
11388 #endif
11392 * "histget()" function
11394 /*ARGSUSED*/
11395 static void
11396 f_histget(argvars, rettv)
11397 typval_T *argvars;
11398 typval_T *rettv;
11400 #ifdef FEAT_CMDHIST
11401 int type;
11402 int idx;
11403 char_u *str;
11405 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11406 if (str == NULL)
11407 rettv->vval.v_string = NULL;
11408 else
11410 type = get_histtype(str);
11411 if (argvars[1].v_type == VAR_UNKNOWN)
11412 idx = get_history_idx(type);
11413 else
11414 idx = (int)get_tv_number_chk(&argvars[1], NULL);
11415 /* -1 on type error */
11416 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
11418 #else
11419 rettv->vval.v_string = NULL;
11420 #endif
11421 rettv->v_type = VAR_STRING;
11425 * "histnr()" function
11427 /*ARGSUSED*/
11428 static void
11429 f_histnr(argvars, rettv)
11430 typval_T *argvars;
11431 typval_T *rettv;
11433 int i;
11435 #ifdef FEAT_CMDHIST
11436 char_u *history = get_tv_string_chk(&argvars[0]);
11438 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
11439 if (i >= HIST_CMD && i < HIST_COUNT)
11440 i = get_history_idx(i);
11441 else
11442 #endif
11443 i = -1;
11444 rettv->vval.v_number = i;
11448 * "highlightID(name)" function
11450 static void
11451 f_hlID(argvars, rettv)
11452 typval_T *argvars;
11453 typval_T *rettv;
11455 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
11459 * "highlight_exists()" function
11461 static void
11462 f_hlexists(argvars, rettv)
11463 typval_T *argvars;
11464 typval_T *rettv;
11466 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
11470 * "hostname()" function
11472 /*ARGSUSED*/
11473 static void
11474 f_hostname(argvars, rettv)
11475 typval_T *argvars;
11476 typval_T *rettv;
11478 char_u hostname[256];
11480 mch_get_host_name(hostname, 256);
11481 rettv->v_type = VAR_STRING;
11482 rettv->vval.v_string = vim_strsave(hostname);
11486 * iconv() function
11488 /*ARGSUSED*/
11489 static void
11490 f_iconv(argvars, rettv)
11491 typval_T *argvars;
11492 typval_T *rettv;
11494 #ifdef FEAT_MBYTE
11495 char_u buf1[NUMBUFLEN];
11496 char_u buf2[NUMBUFLEN];
11497 char_u *from, *to, *str;
11498 vimconv_T vimconv;
11499 #endif
11501 rettv->v_type = VAR_STRING;
11502 rettv->vval.v_string = NULL;
11504 #ifdef FEAT_MBYTE
11505 str = get_tv_string(&argvars[0]);
11506 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
11507 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
11508 vimconv.vc_type = CONV_NONE;
11509 convert_setup(&vimconv, from, to);
11511 /* If the encodings are equal, no conversion needed. */
11512 if (vimconv.vc_type == CONV_NONE)
11513 rettv->vval.v_string = vim_strsave(str);
11514 else
11515 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
11517 convert_setup(&vimconv, NULL, NULL);
11518 vim_free(from);
11519 vim_free(to);
11520 #endif
11524 * "indent()" function
11526 static void
11527 f_indent(argvars, rettv)
11528 typval_T *argvars;
11529 typval_T *rettv;
11531 linenr_T lnum;
11533 lnum = get_tv_lnum(argvars);
11534 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
11535 rettv->vval.v_number = get_indent_lnum(lnum);
11536 else
11537 rettv->vval.v_number = -1;
11541 * "index()" function
11543 static void
11544 f_index(argvars, rettv)
11545 typval_T *argvars;
11546 typval_T *rettv;
11548 list_T *l;
11549 listitem_T *item;
11550 long idx = 0;
11551 int ic = FALSE;
11553 rettv->vval.v_number = -1;
11554 if (argvars[0].v_type != VAR_LIST)
11556 EMSG(_(e_listreq));
11557 return;
11559 l = argvars[0].vval.v_list;
11560 if (l != NULL)
11562 item = l->lv_first;
11563 if (argvars[2].v_type != VAR_UNKNOWN)
11565 int error = FALSE;
11567 /* Start at specified item. Use the cached index that list_find()
11568 * sets, so that a negative number also works. */
11569 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
11570 idx = l->lv_idx;
11571 if (argvars[3].v_type != VAR_UNKNOWN)
11572 ic = get_tv_number_chk(&argvars[3], &error);
11573 if (error)
11574 item = NULL;
11577 for ( ; item != NULL; item = item->li_next, ++idx)
11578 if (tv_equal(&item->li_tv, &argvars[1], ic))
11580 rettv->vval.v_number = idx;
11581 break;
11586 static int inputsecret_flag = 0;
11588 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
11591 * This function is used by f_input() and f_inputdialog() functions. The third
11592 * argument to f_input() specifies the type of completion to use at the
11593 * prompt. The third argument to f_inputdialog() specifies the value to return
11594 * when the user cancels the prompt.
11596 static void
11597 get_user_input(argvars, rettv, inputdialog)
11598 typval_T *argvars;
11599 typval_T *rettv;
11600 int inputdialog;
11602 char_u *prompt = get_tv_string_chk(&argvars[0]);
11603 char_u *p = NULL;
11604 int c;
11605 char_u buf[NUMBUFLEN];
11606 int cmd_silent_save = cmd_silent;
11607 char_u *defstr = (char_u *)"";
11608 int xp_type = EXPAND_NOTHING;
11609 char_u *xp_arg = NULL;
11611 rettv->v_type = VAR_STRING;
11612 rettv->vval.v_string = NULL;
11614 #ifdef NO_CONSOLE_INPUT
11615 /* While starting up, there is no place to enter text. */
11616 if (no_console_input())
11617 return;
11618 #endif
11620 cmd_silent = FALSE; /* Want to see the prompt. */
11621 if (prompt != NULL)
11623 /* Only the part of the message after the last NL is considered as
11624 * prompt for the command line */
11625 p = vim_strrchr(prompt, '\n');
11626 if (p == NULL)
11627 p = prompt;
11628 else
11630 ++p;
11631 c = *p;
11632 *p = NUL;
11633 msg_start();
11634 msg_clr_eos();
11635 msg_puts_attr(prompt, echo_attr);
11636 msg_didout = FALSE;
11637 msg_starthere();
11638 *p = c;
11640 cmdline_row = msg_row;
11642 if (argvars[1].v_type != VAR_UNKNOWN)
11644 defstr = get_tv_string_buf_chk(&argvars[1], buf);
11645 if (defstr != NULL)
11646 stuffReadbuffSpec(defstr);
11648 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
11650 char_u *xp_name;
11651 int xp_namelen;
11652 long argt;
11654 rettv->vval.v_string = NULL;
11656 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
11657 if (xp_name == NULL)
11658 return;
11660 xp_namelen = (int)STRLEN(xp_name);
11662 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
11663 &xp_arg) == FAIL)
11664 return;
11668 if (defstr != NULL)
11669 rettv->vval.v_string =
11670 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
11671 xp_type, xp_arg);
11673 vim_free(xp_arg);
11675 /* since the user typed this, no need to wait for return */
11676 need_wait_return = FALSE;
11677 msg_didout = FALSE;
11679 cmd_silent = cmd_silent_save;
11683 * "input()" function
11684 * Also handles inputsecret() when inputsecret is set.
11686 static void
11687 f_input(argvars, rettv)
11688 typval_T *argvars;
11689 typval_T *rettv;
11691 get_user_input(argvars, rettv, FALSE);
11695 * "inputdialog()" function
11697 static void
11698 f_inputdialog(argvars, rettv)
11699 typval_T *argvars;
11700 typval_T *rettv;
11702 #if defined(FEAT_GUI_TEXTDIALOG)
11703 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
11704 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
11706 char_u *message;
11707 char_u buf[NUMBUFLEN];
11708 char_u *defstr = (char_u *)"";
11710 message = get_tv_string_chk(&argvars[0]);
11711 if (argvars[1].v_type != VAR_UNKNOWN
11712 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
11713 vim_strncpy(IObuff, defstr, IOSIZE - 1);
11714 else
11715 IObuff[0] = NUL;
11716 if (message != NULL && defstr != NULL
11717 && do_dialog(VIM_QUESTION, NULL, message,
11718 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
11719 rettv->vval.v_string = vim_strsave(IObuff);
11720 else
11722 if (message != NULL && defstr != NULL
11723 && argvars[1].v_type != VAR_UNKNOWN
11724 && argvars[2].v_type != VAR_UNKNOWN)
11725 rettv->vval.v_string = vim_strsave(
11726 get_tv_string_buf(&argvars[2], buf));
11727 else
11728 rettv->vval.v_string = NULL;
11730 rettv->v_type = VAR_STRING;
11732 else
11733 #endif
11734 get_user_input(argvars, rettv, TRUE);
11738 * "inputlist()" function
11740 static void
11741 f_inputlist(argvars, rettv)
11742 typval_T *argvars;
11743 typval_T *rettv;
11745 listitem_T *li;
11746 int selected;
11747 int mouse_used;
11749 rettv->vval.v_number = 0;
11750 #ifdef NO_CONSOLE_INPUT
11751 /* While starting up, there is no place to enter text. */
11752 if (no_console_input())
11753 return;
11754 #endif
11755 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
11757 EMSG2(_(e_listarg), "inputlist()");
11758 return;
11761 msg_start();
11762 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
11763 lines_left = Rows; /* avoid more prompt */
11764 msg_scroll = TRUE;
11765 msg_clr_eos();
11767 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
11769 msg_puts(get_tv_string(&li->li_tv));
11770 msg_putchar('\n');
11773 /* Ask for choice. */
11774 selected = prompt_for_number(&mouse_used);
11775 if (mouse_used)
11776 selected -= lines_left;
11778 rettv->vval.v_number = selected;
11782 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
11785 * "inputrestore()" function
11787 /*ARGSUSED*/
11788 static void
11789 f_inputrestore(argvars, rettv)
11790 typval_T *argvars;
11791 typval_T *rettv;
11793 if (ga_userinput.ga_len > 0)
11795 --ga_userinput.ga_len;
11796 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
11797 + ga_userinput.ga_len);
11798 rettv->vval.v_number = 0; /* OK */
11800 else if (p_verbose > 1)
11802 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
11803 rettv->vval.v_number = 1; /* Failed */
11808 * "inputsave()" function
11810 /*ARGSUSED*/
11811 static void
11812 f_inputsave(argvars, rettv)
11813 typval_T *argvars;
11814 typval_T *rettv;
11816 /* Add an entry to the stack of typehead storage. */
11817 if (ga_grow(&ga_userinput, 1) == OK)
11819 save_typeahead((tasave_T *)(ga_userinput.ga_data)
11820 + ga_userinput.ga_len);
11821 ++ga_userinput.ga_len;
11822 rettv->vval.v_number = 0; /* OK */
11824 else
11825 rettv->vval.v_number = 1; /* Failed */
11829 * "inputsecret()" function
11831 static void
11832 f_inputsecret(argvars, rettv)
11833 typval_T *argvars;
11834 typval_T *rettv;
11836 ++cmdline_star;
11837 ++inputsecret_flag;
11838 f_input(argvars, rettv);
11839 --cmdline_star;
11840 --inputsecret_flag;
11844 * "insert()" function
11846 static void
11847 f_insert(argvars, rettv)
11848 typval_T *argvars;
11849 typval_T *rettv;
11851 long before = 0;
11852 listitem_T *item;
11853 list_T *l;
11854 int error = FALSE;
11856 rettv->vval.v_number = 0;
11857 if (argvars[0].v_type != VAR_LIST)
11858 EMSG2(_(e_listarg), "insert()");
11859 else if ((l = argvars[0].vval.v_list) != NULL
11860 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
11862 if (argvars[2].v_type != VAR_UNKNOWN)
11863 before = get_tv_number_chk(&argvars[2], &error);
11864 if (error)
11865 return; /* type error; errmsg already given */
11867 if (before == l->lv_len)
11868 item = NULL;
11869 else
11871 item = list_find(l, before);
11872 if (item == NULL)
11874 EMSGN(_(e_listidx), before);
11875 l = NULL;
11878 if (l != NULL)
11880 list_insert_tv(l, &argvars[1], item);
11881 copy_tv(&argvars[0], rettv);
11887 * "isdirectory()" function
11889 static void
11890 f_isdirectory(argvars, rettv)
11891 typval_T *argvars;
11892 typval_T *rettv;
11894 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
11898 * "islocked()" function
11900 static void
11901 f_islocked(argvars, rettv)
11902 typval_T *argvars;
11903 typval_T *rettv;
11905 lval_T lv;
11906 char_u *end;
11907 dictitem_T *di;
11909 rettv->vval.v_number = -1;
11910 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
11911 FNE_CHECK_START);
11912 if (end != NULL && lv.ll_name != NULL)
11914 if (*end != NUL)
11915 EMSG(_(e_trailing));
11916 else
11918 if (lv.ll_tv == NULL)
11920 if (check_changedtick(lv.ll_name))
11921 rettv->vval.v_number = 1; /* always locked */
11922 else
11924 di = find_var(lv.ll_name, NULL);
11925 if (di != NULL)
11927 /* Consider a variable locked when:
11928 * 1. the variable itself is locked
11929 * 2. the value of the variable is locked.
11930 * 3. the List or Dict value is locked.
11932 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
11933 || tv_islocked(&di->di_tv));
11937 else if (lv.ll_range)
11938 EMSG(_("E786: Range not allowed"));
11939 else if (lv.ll_newkey != NULL)
11940 EMSG2(_(e_dictkey), lv.ll_newkey);
11941 else if (lv.ll_list != NULL)
11942 /* List item. */
11943 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
11944 else
11945 /* Dictionary item. */
11946 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
11950 clear_lval(&lv);
11953 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
11956 * Turn a dict into a list:
11957 * "what" == 0: list of keys
11958 * "what" == 1: list of values
11959 * "what" == 2: list of items
11961 static void
11962 dict_list(argvars, rettv, what)
11963 typval_T *argvars;
11964 typval_T *rettv;
11965 int what;
11967 list_T *l2;
11968 dictitem_T *di;
11969 hashitem_T *hi;
11970 listitem_T *li;
11971 listitem_T *li2;
11972 dict_T *d;
11973 int todo;
11975 rettv->vval.v_number = 0;
11976 if (argvars[0].v_type != VAR_DICT)
11978 EMSG(_(e_dictreq));
11979 return;
11981 if ((d = argvars[0].vval.v_dict) == NULL)
11982 return;
11984 if (rettv_list_alloc(rettv) == FAIL)
11985 return;
11987 todo = (int)d->dv_hashtab.ht_used;
11988 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
11990 if (!HASHITEM_EMPTY(hi))
11992 --todo;
11993 di = HI2DI(hi);
11995 li = listitem_alloc();
11996 if (li == NULL)
11997 break;
11998 list_append(rettv->vval.v_list, li);
12000 if (what == 0)
12002 /* keys() */
12003 li->li_tv.v_type = VAR_STRING;
12004 li->li_tv.v_lock = 0;
12005 li->li_tv.vval.v_string = vim_strsave(di->di_key);
12007 else if (what == 1)
12009 /* values() */
12010 copy_tv(&di->di_tv, &li->li_tv);
12012 else
12014 /* items() */
12015 l2 = list_alloc();
12016 li->li_tv.v_type = VAR_LIST;
12017 li->li_tv.v_lock = 0;
12018 li->li_tv.vval.v_list = l2;
12019 if (l2 == NULL)
12020 break;
12021 ++l2->lv_refcount;
12023 li2 = listitem_alloc();
12024 if (li2 == NULL)
12025 break;
12026 list_append(l2, li2);
12027 li2->li_tv.v_type = VAR_STRING;
12028 li2->li_tv.v_lock = 0;
12029 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12031 li2 = listitem_alloc();
12032 if (li2 == NULL)
12033 break;
12034 list_append(l2, li2);
12035 copy_tv(&di->di_tv, &li2->li_tv);
12042 * "items(dict)" function
12044 static void
12045 f_items(argvars, rettv)
12046 typval_T *argvars;
12047 typval_T *rettv;
12049 dict_list(argvars, rettv, 2);
12053 * "join()" function
12055 static void
12056 f_join(argvars, rettv)
12057 typval_T *argvars;
12058 typval_T *rettv;
12060 garray_T ga;
12061 char_u *sep;
12063 rettv->vval.v_number = 0;
12064 if (argvars[0].v_type != VAR_LIST)
12066 EMSG(_(e_listreq));
12067 return;
12069 if (argvars[0].vval.v_list == NULL)
12070 return;
12071 if (argvars[1].v_type == VAR_UNKNOWN)
12072 sep = (char_u *)" ";
12073 else
12074 sep = get_tv_string_chk(&argvars[1]);
12076 rettv->v_type = VAR_STRING;
12078 if (sep != NULL)
12080 ga_init2(&ga, (int)sizeof(char), 80);
12081 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12082 ga_append(&ga, NUL);
12083 rettv->vval.v_string = (char_u *)ga.ga_data;
12085 else
12086 rettv->vval.v_string = NULL;
12090 * "keys()" function
12092 static void
12093 f_keys(argvars, rettv)
12094 typval_T *argvars;
12095 typval_T *rettv;
12097 dict_list(argvars, rettv, 0);
12101 * "last_buffer_nr()" function.
12103 /*ARGSUSED*/
12104 static void
12105 f_last_buffer_nr(argvars, rettv)
12106 typval_T *argvars;
12107 typval_T *rettv;
12109 int n = 0;
12110 buf_T *buf;
12112 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12113 if (n < buf->b_fnum)
12114 n = buf->b_fnum;
12116 rettv->vval.v_number = n;
12120 * "len()" function
12122 static void
12123 f_len(argvars, rettv)
12124 typval_T *argvars;
12125 typval_T *rettv;
12127 switch (argvars[0].v_type)
12129 case VAR_STRING:
12130 case VAR_NUMBER:
12131 rettv->vval.v_number = (varnumber_T)STRLEN(
12132 get_tv_string(&argvars[0]));
12133 break;
12134 case VAR_LIST:
12135 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
12136 break;
12137 case VAR_DICT:
12138 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
12139 break;
12140 default:
12141 EMSG(_("E701: Invalid type for len()"));
12142 break;
12146 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
12148 static void
12149 libcall_common(argvars, rettv, type)
12150 typval_T *argvars;
12151 typval_T *rettv;
12152 int type;
12154 #ifdef FEAT_LIBCALL
12155 char_u *string_in;
12156 char_u **string_result;
12157 int nr_result;
12158 #endif
12160 rettv->v_type = type;
12161 if (type == VAR_NUMBER)
12162 rettv->vval.v_number = 0;
12163 else
12164 rettv->vval.v_string = NULL;
12166 if (check_restricted() || check_secure())
12167 return;
12169 #ifdef FEAT_LIBCALL
12170 /* The first two args must be strings, otherwise its meaningless */
12171 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
12173 string_in = NULL;
12174 if (argvars[2].v_type == VAR_STRING)
12175 string_in = argvars[2].vval.v_string;
12176 if (type == VAR_NUMBER)
12177 string_result = NULL;
12178 else
12179 string_result = &rettv->vval.v_string;
12180 if (mch_libcall(argvars[0].vval.v_string,
12181 argvars[1].vval.v_string,
12182 string_in,
12183 argvars[2].vval.v_number,
12184 string_result,
12185 &nr_result) == OK
12186 && type == VAR_NUMBER)
12187 rettv->vval.v_number = nr_result;
12189 #endif
12193 * "libcall()" function
12195 static void
12196 f_libcall(argvars, rettv)
12197 typval_T *argvars;
12198 typval_T *rettv;
12200 libcall_common(argvars, rettv, VAR_STRING);
12204 * "libcallnr()" function
12206 static void
12207 f_libcallnr(argvars, rettv)
12208 typval_T *argvars;
12209 typval_T *rettv;
12211 libcall_common(argvars, rettv, VAR_NUMBER);
12215 * "line(string)" function
12217 static void
12218 f_line(argvars, rettv)
12219 typval_T *argvars;
12220 typval_T *rettv;
12222 linenr_T lnum = 0;
12223 pos_T *fp;
12224 int fnum;
12226 fp = var2fpos(&argvars[0], TRUE, &fnum);
12227 if (fp != NULL)
12228 lnum = fp->lnum;
12229 rettv->vval.v_number = lnum;
12233 * "line2byte(lnum)" function
12235 /*ARGSUSED*/
12236 static void
12237 f_line2byte(argvars, rettv)
12238 typval_T *argvars;
12239 typval_T *rettv;
12241 #ifndef FEAT_BYTEOFF
12242 rettv->vval.v_number = -1;
12243 #else
12244 linenr_T lnum;
12246 lnum = get_tv_lnum(argvars);
12247 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
12248 rettv->vval.v_number = -1;
12249 else
12250 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
12251 if (rettv->vval.v_number >= 0)
12252 ++rettv->vval.v_number;
12253 #endif
12257 * "lispindent(lnum)" function
12259 static void
12260 f_lispindent(argvars, rettv)
12261 typval_T *argvars;
12262 typval_T *rettv;
12264 #ifdef FEAT_LISP
12265 pos_T pos;
12266 linenr_T lnum;
12268 pos = curwin->w_cursor;
12269 lnum = get_tv_lnum(argvars);
12270 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12272 curwin->w_cursor.lnum = lnum;
12273 rettv->vval.v_number = get_lisp_indent();
12274 curwin->w_cursor = pos;
12276 else
12277 #endif
12278 rettv->vval.v_number = -1;
12282 * "localtime()" function
12284 /*ARGSUSED*/
12285 static void
12286 f_localtime(argvars, rettv)
12287 typval_T *argvars;
12288 typval_T *rettv;
12290 rettv->vval.v_number = (varnumber_T)time(NULL);
12293 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
12295 static void
12296 get_maparg(argvars, rettv, exact)
12297 typval_T *argvars;
12298 typval_T *rettv;
12299 int exact;
12301 char_u *keys;
12302 char_u *which;
12303 char_u buf[NUMBUFLEN];
12304 char_u *keys_buf = NULL;
12305 char_u *rhs;
12306 int mode;
12307 garray_T ga;
12308 int abbr = FALSE;
12310 /* return empty string for failure */
12311 rettv->v_type = VAR_STRING;
12312 rettv->vval.v_string = NULL;
12314 keys = get_tv_string(&argvars[0]);
12315 if (*keys == NUL)
12316 return;
12318 if (argvars[1].v_type != VAR_UNKNOWN)
12320 which = get_tv_string_buf_chk(&argvars[1], buf);
12321 if (argvars[2].v_type != VAR_UNKNOWN)
12322 abbr = get_tv_number(&argvars[2]);
12324 else
12325 which = (char_u *)"";
12326 if (which == NULL)
12327 return;
12329 mode = get_map_mode(&which, 0);
12331 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
12332 rhs = check_map(keys, mode, exact, FALSE, abbr);
12333 vim_free(keys_buf);
12334 if (rhs != NULL)
12336 ga_init(&ga);
12337 ga.ga_itemsize = 1;
12338 ga.ga_growsize = 40;
12340 while (*rhs != NUL)
12341 ga_concat(&ga, str2special(&rhs, FALSE));
12343 ga_append(&ga, NUL);
12344 rettv->vval.v_string = (char_u *)ga.ga_data;
12349 * "map()" function
12351 static void
12352 f_map(argvars, rettv)
12353 typval_T *argvars;
12354 typval_T *rettv;
12356 filter_map(argvars, rettv, TRUE);
12360 * "maparg()" function
12362 static void
12363 f_maparg(argvars, rettv)
12364 typval_T *argvars;
12365 typval_T *rettv;
12367 get_maparg(argvars, rettv, TRUE);
12371 * "mapcheck()" function
12373 static void
12374 f_mapcheck(argvars, rettv)
12375 typval_T *argvars;
12376 typval_T *rettv;
12378 get_maparg(argvars, rettv, FALSE);
12381 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
12383 static void
12384 find_some_match(argvars, rettv, type)
12385 typval_T *argvars;
12386 typval_T *rettv;
12387 int type;
12389 char_u *str = NULL;
12390 char_u *expr = NULL;
12391 char_u *pat;
12392 regmatch_T regmatch;
12393 char_u patbuf[NUMBUFLEN];
12394 char_u strbuf[NUMBUFLEN];
12395 char_u *save_cpo;
12396 long start = 0;
12397 long nth = 1;
12398 colnr_T startcol = 0;
12399 int match = 0;
12400 list_T *l = NULL;
12401 listitem_T *li = NULL;
12402 long idx = 0;
12403 char_u *tofree = NULL;
12405 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
12406 save_cpo = p_cpo;
12407 p_cpo = (char_u *)"";
12409 rettv->vval.v_number = -1;
12410 if (type == 3)
12412 /* return empty list when there are no matches */
12413 if (rettv_list_alloc(rettv) == FAIL)
12414 goto theend;
12416 else if (type == 2)
12418 rettv->v_type = VAR_STRING;
12419 rettv->vval.v_string = NULL;
12422 if (argvars[0].v_type == VAR_LIST)
12424 if ((l = argvars[0].vval.v_list) == NULL)
12425 goto theend;
12426 li = l->lv_first;
12428 else
12429 expr = str = get_tv_string(&argvars[0]);
12431 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
12432 if (pat == NULL)
12433 goto theend;
12435 if (argvars[2].v_type != VAR_UNKNOWN)
12437 int error = FALSE;
12439 start = get_tv_number_chk(&argvars[2], &error);
12440 if (error)
12441 goto theend;
12442 if (l != NULL)
12444 li = list_find(l, start);
12445 if (li == NULL)
12446 goto theend;
12447 idx = l->lv_idx; /* use the cached index */
12449 else
12451 if (start < 0)
12452 start = 0;
12453 if (start > (long)STRLEN(str))
12454 goto theend;
12455 /* When "count" argument is there ignore matches before "start",
12456 * otherwise skip part of the string. Differs when pattern is "^"
12457 * or "\<". */
12458 if (argvars[3].v_type != VAR_UNKNOWN)
12459 startcol = start;
12460 else
12461 str += start;
12464 if (argvars[3].v_type != VAR_UNKNOWN)
12465 nth = get_tv_number_chk(&argvars[3], &error);
12466 if (error)
12467 goto theend;
12470 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
12471 if (regmatch.regprog != NULL)
12473 regmatch.rm_ic = p_ic;
12475 for (;;)
12477 if (l != NULL)
12479 if (li == NULL)
12481 match = FALSE;
12482 break;
12484 vim_free(tofree);
12485 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
12486 if (str == NULL)
12487 break;
12490 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
12492 if (match && --nth <= 0)
12493 break;
12494 if (l == NULL && !match)
12495 break;
12497 /* Advance to just after the match. */
12498 if (l != NULL)
12500 li = li->li_next;
12501 ++idx;
12503 else
12505 #ifdef FEAT_MBYTE
12506 startcol = (colnr_T)(regmatch.startp[0]
12507 + (*mb_ptr2len)(regmatch.startp[0]) - str);
12508 #else
12509 startcol = regmatch.startp[0] + 1 - str;
12510 #endif
12514 if (match)
12516 if (type == 3)
12518 int i;
12520 /* return list with matched string and submatches */
12521 for (i = 0; i < NSUBEXP; ++i)
12523 if (regmatch.endp[i] == NULL)
12525 if (list_append_string(rettv->vval.v_list,
12526 (char_u *)"", 0) == FAIL)
12527 break;
12529 else if (list_append_string(rettv->vval.v_list,
12530 regmatch.startp[i],
12531 (int)(regmatch.endp[i] - regmatch.startp[i]))
12532 == FAIL)
12533 break;
12536 else if (type == 2)
12538 /* return matched string */
12539 if (l != NULL)
12540 copy_tv(&li->li_tv, rettv);
12541 else
12542 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
12543 (int)(regmatch.endp[0] - regmatch.startp[0]));
12545 else if (l != NULL)
12546 rettv->vval.v_number = idx;
12547 else
12549 if (type != 0)
12550 rettv->vval.v_number =
12551 (varnumber_T)(regmatch.startp[0] - str);
12552 else
12553 rettv->vval.v_number =
12554 (varnumber_T)(regmatch.endp[0] - str);
12555 rettv->vval.v_number += (varnumber_T)(str - expr);
12558 vim_free(regmatch.regprog);
12561 theend:
12562 vim_free(tofree);
12563 p_cpo = save_cpo;
12567 * "match()" function
12569 static void
12570 f_match(argvars, rettv)
12571 typval_T *argvars;
12572 typval_T *rettv;
12574 find_some_match(argvars, rettv, 1);
12578 * "matchadd()" function
12580 static void
12581 f_matchadd(argvars, rettv)
12582 typval_T *argvars;
12583 typval_T *rettv;
12585 #ifdef FEAT_SEARCH_EXTRA
12586 char_u buf[NUMBUFLEN];
12587 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
12588 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
12589 int prio = 10; /* default priority */
12590 int id = -1;
12591 int error = FALSE;
12593 rettv->vval.v_number = -1;
12595 if (grp == NULL || pat == NULL)
12596 return;
12597 if (argvars[2].v_type != VAR_UNKNOWN)
12599 prio = get_tv_number_chk(&argvars[2], &error);
12600 if (argvars[3].v_type != VAR_UNKNOWN)
12601 id = get_tv_number_chk(&argvars[3], &error);
12603 if (error == TRUE)
12604 return;
12605 if (id >= 1 && id <= 3)
12607 EMSGN("E798: ID is reserved for \":match\": %ld", id);
12608 return;
12611 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
12612 #endif
12616 * "matcharg()" function
12618 static void
12619 f_matcharg(argvars, rettv)
12620 typval_T *argvars;
12621 typval_T *rettv;
12623 if (rettv_list_alloc(rettv) == OK)
12625 #ifdef FEAT_SEARCH_EXTRA
12626 int id = get_tv_number(&argvars[0]);
12627 matchitem_T *m;
12629 if (id >= 1 && id <= 3)
12631 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
12633 list_append_string(rettv->vval.v_list,
12634 syn_id2name(m->hlg_id), -1);
12635 list_append_string(rettv->vval.v_list, m->pattern, -1);
12637 else
12639 list_append_string(rettv->vval.v_list, NUL, -1);
12640 list_append_string(rettv->vval.v_list, NUL, -1);
12643 #endif
12648 * "matchdelete()" function
12650 static void
12651 f_matchdelete(argvars, rettv)
12652 typval_T *argvars;
12653 typval_T *rettv;
12655 #ifdef FEAT_SEARCH_EXTRA
12656 rettv->vval.v_number = match_delete(curwin,
12657 (int)get_tv_number(&argvars[0]), TRUE);
12658 #endif
12662 * "matchend()" function
12664 static void
12665 f_matchend(argvars, rettv)
12666 typval_T *argvars;
12667 typval_T *rettv;
12669 find_some_match(argvars, rettv, 0);
12673 * "matchlist()" function
12675 static void
12676 f_matchlist(argvars, rettv)
12677 typval_T *argvars;
12678 typval_T *rettv;
12680 find_some_match(argvars, rettv, 3);
12684 * "matchstr()" function
12686 static void
12687 f_matchstr(argvars, rettv)
12688 typval_T *argvars;
12689 typval_T *rettv;
12691 find_some_match(argvars, rettv, 2);
12694 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
12696 static void
12697 max_min(argvars, rettv, domax)
12698 typval_T *argvars;
12699 typval_T *rettv;
12700 int domax;
12702 long n = 0;
12703 long i;
12704 int error = FALSE;
12706 if (argvars[0].v_type == VAR_LIST)
12708 list_T *l;
12709 listitem_T *li;
12711 l = argvars[0].vval.v_list;
12712 if (l != NULL)
12714 li = l->lv_first;
12715 if (li != NULL)
12717 n = get_tv_number_chk(&li->li_tv, &error);
12718 for (;;)
12720 li = li->li_next;
12721 if (li == NULL)
12722 break;
12723 i = get_tv_number_chk(&li->li_tv, &error);
12724 if (domax ? i > n : i < n)
12725 n = i;
12730 else if (argvars[0].v_type == VAR_DICT)
12732 dict_T *d;
12733 int first = TRUE;
12734 hashitem_T *hi;
12735 int todo;
12737 d = argvars[0].vval.v_dict;
12738 if (d != NULL)
12740 todo = (int)d->dv_hashtab.ht_used;
12741 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12743 if (!HASHITEM_EMPTY(hi))
12745 --todo;
12746 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
12747 if (first)
12749 n = i;
12750 first = FALSE;
12752 else if (domax ? i > n : i < n)
12753 n = i;
12758 else
12759 EMSG(_(e_listdictarg));
12760 rettv->vval.v_number = error ? 0 : n;
12764 * "max()" function
12766 static void
12767 f_max(argvars, rettv)
12768 typval_T *argvars;
12769 typval_T *rettv;
12771 max_min(argvars, rettv, TRUE);
12775 * "min()" function
12777 static void
12778 f_min(argvars, rettv)
12779 typval_T *argvars;
12780 typval_T *rettv;
12782 max_min(argvars, rettv, FALSE);
12785 static int mkdir_recurse __ARGS((char_u *dir, int prot));
12788 * Create the directory in which "dir" is located, and higher levels when
12789 * needed.
12791 static int
12792 mkdir_recurse(dir, prot)
12793 char_u *dir;
12794 int prot;
12796 char_u *p;
12797 char_u *updir;
12798 int r = FAIL;
12800 /* Get end of directory name in "dir".
12801 * We're done when it's "/" or "c:/". */
12802 p = gettail_sep(dir);
12803 if (p <= get_past_head(dir))
12804 return OK;
12806 /* If the directory exists we're done. Otherwise: create it.*/
12807 updir = vim_strnsave(dir, (int)(p - dir));
12808 if (updir == NULL)
12809 return FAIL;
12810 if (mch_isdir(updir))
12811 r = OK;
12812 else if (mkdir_recurse(updir, prot) == OK)
12813 r = vim_mkdir_emsg(updir, prot);
12814 vim_free(updir);
12815 return r;
12818 #ifdef vim_mkdir
12820 * "mkdir()" function
12822 static void
12823 f_mkdir(argvars, rettv)
12824 typval_T *argvars;
12825 typval_T *rettv;
12827 char_u *dir;
12828 char_u buf[NUMBUFLEN];
12829 int prot = 0755;
12831 rettv->vval.v_number = FAIL;
12832 if (check_restricted() || check_secure())
12833 return;
12835 dir = get_tv_string_buf(&argvars[0], buf);
12836 if (argvars[1].v_type != VAR_UNKNOWN)
12838 if (argvars[2].v_type != VAR_UNKNOWN)
12839 prot = get_tv_number_chk(&argvars[2], NULL);
12840 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
12841 mkdir_recurse(dir, prot);
12843 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
12845 #endif
12848 * "mode()" function
12850 /*ARGSUSED*/
12851 static void
12852 f_mode(argvars, rettv)
12853 typval_T *argvars;
12854 typval_T *rettv;
12856 char_u buf[2];
12858 #ifdef FEAT_VISUAL
12859 if (VIsual_active)
12861 if (VIsual_select)
12862 buf[0] = VIsual_mode + 's' - 'v';
12863 else
12864 buf[0] = VIsual_mode;
12866 else
12867 #endif
12868 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE)
12869 buf[0] = 'r';
12870 else if (State & INSERT)
12872 if (State & REPLACE_FLAG)
12873 buf[0] = 'R';
12874 else
12875 buf[0] = 'i';
12877 else if (State & CMDLINE)
12878 buf[0] = 'c';
12879 else
12880 buf[0] = 'n';
12882 buf[1] = NUL;
12883 rettv->vval.v_string = vim_strsave(buf);
12884 rettv->v_type = VAR_STRING;
12888 * "nextnonblank()" function
12890 static void
12891 f_nextnonblank(argvars, rettv)
12892 typval_T *argvars;
12893 typval_T *rettv;
12895 linenr_T lnum;
12897 for (lnum = get_tv_lnum(argvars); ; ++lnum)
12899 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
12901 lnum = 0;
12902 break;
12904 if (*skipwhite(ml_get(lnum)) != NUL)
12905 break;
12907 rettv->vval.v_number = lnum;
12911 * "nr2char()" function
12913 static void
12914 f_nr2char(argvars, rettv)
12915 typval_T *argvars;
12916 typval_T *rettv;
12918 char_u buf[NUMBUFLEN];
12920 #ifdef FEAT_MBYTE
12921 if (has_mbyte)
12922 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
12923 else
12924 #endif
12926 buf[0] = (char_u)get_tv_number(&argvars[0]);
12927 buf[1] = NUL;
12929 rettv->v_type = VAR_STRING;
12930 rettv->vval.v_string = vim_strsave(buf);
12934 * "pathshorten()" function
12936 static void
12937 f_pathshorten(argvars, rettv)
12938 typval_T *argvars;
12939 typval_T *rettv;
12941 char_u *p;
12943 rettv->v_type = VAR_STRING;
12944 p = get_tv_string_chk(&argvars[0]);
12945 if (p == NULL)
12946 rettv->vval.v_string = NULL;
12947 else
12949 p = vim_strsave(p);
12950 rettv->vval.v_string = p;
12951 if (p != NULL)
12952 shorten_dir(p);
12957 * "prevnonblank()" function
12959 static void
12960 f_prevnonblank(argvars, rettv)
12961 typval_T *argvars;
12962 typval_T *rettv;
12964 linenr_T lnum;
12966 lnum = get_tv_lnum(argvars);
12967 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
12968 lnum = 0;
12969 else
12970 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
12971 --lnum;
12972 rettv->vval.v_number = lnum;
12975 #ifdef HAVE_STDARG_H
12976 /* This dummy va_list is here because:
12977 * - passing a NULL pointer doesn't work when va_list isn't a pointer
12978 * - locally in the function results in a "used before set" warning
12979 * - using va_start() to initialize it gives "function with fixed args" error */
12980 static va_list ap;
12981 #endif
12984 * "printf()" function
12986 static void
12987 f_printf(argvars, rettv)
12988 typval_T *argvars;
12989 typval_T *rettv;
12991 rettv->v_type = VAR_STRING;
12992 rettv->vval.v_string = NULL;
12993 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
12995 char_u buf[NUMBUFLEN];
12996 int len;
12997 char_u *s;
12998 int saved_did_emsg = did_emsg;
12999 char *fmt;
13001 /* Get the required length, allocate the buffer and do it for real. */
13002 did_emsg = FALSE;
13003 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
13004 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
13005 if (!did_emsg)
13007 s = alloc(len + 1);
13008 if (s != NULL)
13010 rettv->vval.v_string = s;
13011 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
13014 did_emsg |= saved_did_emsg;
13016 #endif
13020 * "pumvisible()" function
13022 /*ARGSUSED*/
13023 static void
13024 f_pumvisible(argvars, rettv)
13025 typval_T *argvars;
13026 typval_T *rettv;
13028 rettv->vval.v_number = 0;
13029 #ifdef FEAT_INS_EXPAND
13030 if (pum_visible())
13031 rettv->vval.v_number = 1;
13032 #endif
13036 * "range()" function
13038 static void
13039 f_range(argvars, rettv)
13040 typval_T *argvars;
13041 typval_T *rettv;
13043 long start;
13044 long end;
13045 long stride = 1;
13046 long i;
13047 int error = FALSE;
13049 start = get_tv_number_chk(&argvars[0], &error);
13050 if (argvars[1].v_type == VAR_UNKNOWN)
13052 end = start - 1;
13053 start = 0;
13055 else
13057 end = get_tv_number_chk(&argvars[1], &error);
13058 if (argvars[2].v_type != VAR_UNKNOWN)
13059 stride = get_tv_number_chk(&argvars[2], &error);
13062 rettv->vval.v_number = 0;
13063 if (error)
13064 return; /* type error; errmsg already given */
13065 if (stride == 0)
13066 EMSG(_("E726: Stride is zero"));
13067 else if (stride > 0 ? end + 1 < start : end - 1 > start)
13068 EMSG(_("E727: Start past end"));
13069 else
13071 if (rettv_list_alloc(rettv) == OK)
13072 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
13073 if (list_append_number(rettv->vval.v_list,
13074 (varnumber_T)i) == FAIL)
13075 break;
13080 * "readfile()" function
13082 static void
13083 f_readfile(argvars, rettv)
13084 typval_T *argvars;
13085 typval_T *rettv;
13087 int binary = FALSE;
13088 char_u *fname;
13089 FILE *fd;
13090 listitem_T *li;
13091 #define FREAD_SIZE 200 /* optimized for text lines */
13092 char_u buf[FREAD_SIZE];
13093 int readlen; /* size of last fread() */
13094 int buflen; /* nr of valid chars in buf[] */
13095 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
13096 int tolist; /* first byte in buf[] still to be put in list */
13097 int chop; /* how many CR to chop off */
13098 char_u *prev = NULL; /* previously read bytes, if any */
13099 int prevlen = 0; /* length of "prev" if not NULL */
13100 char_u *s;
13101 int len;
13102 long maxline = MAXLNUM;
13103 long cnt = 0;
13105 if (argvars[1].v_type != VAR_UNKNOWN)
13107 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
13108 binary = TRUE;
13109 if (argvars[2].v_type != VAR_UNKNOWN)
13110 maxline = get_tv_number(&argvars[2]);
13113 if (rettv_list_alloc(rettv) == FAIL)
13114 return;
13116 /* Always open the file in binary mode, library functions have a mind of
13117 * their own about CR-LF conversion. */
13118 fname = get_tv_string(&argvars[0]);
13119 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
13121 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
13122 return;
13125 filtd = 0;
13126 while (cnt < maxline || maxline < 0)
13128 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
13129 buflen = filtd + readlen;
13130 tolist = 0;
13131 for ( ; filtd < buflen || readlen <= 0; ++filtd)
13133 if (buf[filtd] == '\n' || readlen <= 0)
13135 /* Only when in binary mode add an empty list item when the
13136 * last line ends in a '\n'. */
13137 if (!binary && readlen == 0 && filtd == 0)
13138 break;
13140 /* Found end-of-line or end-of-file: add a text line to the
13141 * list. */
13142 chop = 0;
13143 if (!binary)
13144 while (filtd - chop - 1 >= tolist
13145 && buf[filtd - chop - 1] == '\r')
13146 ++chop;
13147 len = filtd - tolist - chop;
13148 if (prev == NULL)
13149 s = vim_strnsave(buf + tolist, len);
13150 else
13152 s = alloc((unsigned)(prevlen + len + 1));
13153 if (s != NULL)
13155 mch_memmove(s, prev, prevlen);
13156 vim_free(prev);
13157 prev = NULL;
13158 mch_memmove(s + prevlen, buf + tolist, len);
13159 s[prevlen + len] = NUL;
13162 tolist = filtd + 1;
13164 li = listitem_alloc();
13165 if (li == NULL)
13167 vim_free(s);
13168 break;
13170 li->li_tv.v_type = VAR_STRING;
13171 li->li_tv.v_lock = 0;
13172 li->li_tv.vval.v_string = s;
13173 list_append(rettv->vval.v_list, li);
13175 if (++cnt >= maxline && maxline >= 0)
13176 break;
13177 if (readlen <= 0)
13178 break;
13180 else if (buf[filtd] == NUL)
13181 buf[filtd] = '\n';
13183 if (readlen <= 0)
13184 break;
13186 if (tolist == 0)
13188 /* "buf" is full, need to move text to an allocated buffer */
13189 if (prev == NULL)
13191 prev = vim_strnsave(buf, buflen);
13192 prevlen = buflen;
13194 else
13196 s = alloc((unsigned)(prevlen + buflen));
13197 if (s != NULL)
13199 mch_memmove(s, prev, prevlen);
13200 mch_memmove(s + prevlen, buf, buflen);
13201 vim_free(prev);
13202 prev = s;
13203 prevlen += buflen;
13206 filtd = 0;
13208 else
13210 mch_memmove(buf, buf + tolist, buflen - tolist);
13211 filtd -= tolist;
13216 * For a negative line count use only the lines at the end of the file,
13217 * free the rest.
13219 if (maxline < 0)
13220 while (cnt > -maxline)
13222 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
13223 --cnt;
13226 vim_free(prev);
13227 fclose(fd);
13230 #if defined(FEAT_RELTIME)
13231 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
13234 * Convert a List to proftime_T.
13235 * Return FAIL when there is something wrong.
13237 static int
13238 list2proftime(arg, tm)
13239 typval_T *arg;
13240 proftime_T *tm;
13242 long n1, n2;
13243 int error = FALSE;
13245 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
13246 || arg->vval.v_list->lv_len != 2)
13247 return FAIL;
13248 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
13249 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
13250 # ifdef WIN3264
13251 tm->HighPart = n1;
13252 tm->LowPart = n2;
13253 # else
13254 tm->tv_sec = n1;
13255 tm->tv_usec = n2;
13256 # endif
13257 return error ? FAIL : OK;
13259 #endif /* FEAT_RELTIME */
13262 * "reltime()" function
13264 static void
13265 f_reltime(argvars, rettv)
13266 typval_T *argvars;
13267 typval_T *rettv;
13269 #ifdef FEAT_RELTIME
13270 proftime_T res;
13271 proftime_T start;
13273 if (argvars[0].v_type == VAR_UNKNOWN)
13275 /* No arguments: get current time. */
13276 profile_start(&res);
13278 else if (argvars[1].v_type == VAR_UNKNOWN)
13280 if (list2proftime(&argvars[0], &res) == FAIL)
13281 return;
13282 profile_end(&res);
13284 else
13286 /* Two arguments: compute the difference. */
13287 if (list2proftime(&argvars[0], &start) == FAIL
13288 || list2proftime(&argvars[1], &res) == FAIL)
13289 return;
13290 profile_sub(&res, &start);
13293 if (rettv_list_alloc(rettv) == OK)
13295 long n1, n2;
13297 # ifdef WIN3264
13298 n1 = res.HighPart;
13299 n2 = res.LowPart;
13300 # else
13301 n1 = res.tv_sec;
13302 n2 = res.tv_usec;
13303 # endif
13304 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
13305 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
13307 #endif
13311 * "reltimestr()" function
13313 static void
13314 f_reltimestr(argvars, rettv)
13315 typval_T *argvars;
13316 typval_T *rettv;
13318 #ifdef FEAT_RELTIME
13319 proftime_T tm;
13320 #endif
13322 rettv->v_type = VAR_STRING;
13323 rettv->vval.v_string = NULL;
13324 #ifdef FEAT_RELTIME
13325 if (list2proftime(&argvars[0], &tm) == OK)
13326 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
13327 #endif
13330 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
13331 static void make_connection __ARGS((void));
13332 static int check_connection __ARGS((void));
13334 static void
13335 make_connection()
13337 if (X_DISPLAY == NULL
13338 # ifdef FEAT_GUI
13339 && !gui.in_use
13340 # endif
13343 x_force_connect = TRUE;
13344 setup_term_clip();
13345 x_force_connect = FALSE;
13349 static int
13350 check_connection()
13352 make_connection();
13353 if (X_DISPLAY == NULL)
13355 EMSG(_("E240: No connection to Vim server"));
13356 return FAIL;
13358 return OK;
13360 #endif
13362 #ifdef FEAT_CLIENTSERVER
13363 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
13365 static void
13366 remote_common(argvars, rettv, expr)
13367 typval_T *argvars;
13368 typval_T *rettv;
13369 int expr;
13371 char_u *server_name;
13372 char_u *keys;
13373 char_u *r = NULL;
13374 char_u buf[NUMBUFLEN];
13375 # ifdef WIN32
13376 HWND w;
13377 # else
13378 Window w;
13379 # endif
13381 if (check_restricted() || check_secure())
13382 return;
13384 # ifdef FEAT_X11
13385 if (check_connection() == FAIL)
13386 return;
13387 # endif
13389 server_name = get_tv_string_chk(&argvars[0]);
13390 if (server_name == NULL)
13391 return; /* type error; errmsg already given */
13392 keys = get_tv_string_buf(&argvars[1], buf);
13393 # ifdef WIN32
13394 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
13395 # else
13396 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
13397 < 0)
13398 # endif
13400 if (r != NULL)
13401 EMSG(r); /* sending worked but evaluation failed */
13402 else
13403 EMSG2(_("E241: Unable to send to %s"), server_name);
13404 return;
13407 rettv->vval.v_string = r;
13409 if (argvars[2].v_type != VAR_UNKNOWN)
13411 dictitem_T v;
13412 char_u str[30];
13413 char_u *idvar;
13415 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
13416 v.di_tv.v_type = VAR_STRING;
13417 v.di_tv.vval.v_string = vim_strsave(str);
13418 idvar = get_tv_string_chk(&argvars[2]);
13419 if (idvar != NULL)
13420 set_var(idvar, &v.di_tv, FALSE);
13421 vim_free(v.di_tv.vval.v_string);
13424 #endif
13427 * "remote_expr()" function
13429 /*ARGSUSED*/
13430 static void
13431 f_remote_expr(argvars, rettv)
13432 typval_T *argvars;
13433 typval_T *rettv;
13435 rettv->v_type = VAR_STRING;
13436 rettv->vval.v_string = NULL;
13437 #ifdef FEAT_CLIENTSERVER
13438 remote_common(argvars, rettv, TRUE);
13439 #endif
13443 * "remote_foreground()" function
13445 /*ARGSUSED*/
13446 static void
13447 f_remote_foreground(argvars, rettv)
13448 typval_T *argvars;
13449 typval_T *rettv;
13451 rettv->vval.v_number = 0;
13452 #ifdef FEAT_CLIENTSERVER
13453 # ifdef WIN32
13454 /* On Win32 it's done in this application. */
13456 char_u *server_name = get_tv_string_chk(&argvars[0]);
13458 if (server_name != NULL)
13459 serverForeground(server_name);
13461 # else
13462 /* Send a foreground() expression to the server. */
13463 argvars[1].v_type = VAR_STRING;
13464 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
13465 argvars[2].v_type = VAR_UNKNOWN;
13466 remote_common(argvars, rettv, TRUE);
13467 vim_free(argvars[1].vval.v_string);
13468 # endif
13469 #endif
13472 /*ARGSUSED*/
13473 static void
13474 f_remote_peek(argvars, rettv)
13475 typval_T *argvars;
13476 typval_T *rettv;
13478 #ifdef FEAT_CLIENTSERVER
13479 dictitem_T v;
13480 char_u *s = NULL;
13481 # ifdef WIN32
13482 long_u n = 0;
13483 # endif
13484 char_u *serverid;
13486 if (check_restricted() || check_secure())
13488 rettv->vval.v_number = -1;
13489 return;
13491 serverid = get_tv_string_chk(&argvars[0]);
13492 if (serverid == NULL)
13494 rettv->vval.v_number = -1;
13495 return; /* type error; errmsg already given */
13497 # ifdef WIN32
13498 sscanf(serverid, SCANF_HEX_LONG_U, &n);
13499 if (n == 0)
13500 rettv->vval.v_number = -1;
13501 else
13503 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
13504 rettv->vval.v_number = (s != NULL);
13506 # else
13507 rettv->vval.v_number = 0;
13508 if (check_connection() == FAIL)
13509 return;
13511 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
13512 serverStrToWin(serverid), &s);
13513 # endif
13515 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
13517 char_u *retvar;
13519 v.di_tv.v_type = VAR_STRING;
13520 v.di_tv.vval.v_string = vim_strsave(s);
13521 retvar = get_tv_string_chk(&argvars[1]);
13522 if (retvar != NULL)
13523 set_var(retvar, &v.di_tv, FALSE);
13524 vim_free(v.di_tv.vval.v_string);
13526 #else
13527 rettv->vval.v_number = -1;
13528 #endif
13531 /*ARGSUSED*/
13532 static void
13533 f_remote_read(argvars, rettv)
13534 typval_T *argvars;
13535 typval_T *rettv;
13537 char_u *r = NULL;
13539 #ifdef FEAT_CLIENTSERVER
13540 char_u *serverid = get_tv_string_chk(&argvars[0]);
13542 if (serverid != NULL && !check_restricted() && !check_secure())
13544 # ifdef WIN32
13545 /* The server's HWND is encoded in the 'id' parameter */
13546 long_u n = 0;
13548 sscanf(serverid, SCANF_HEX_LONG_U, &n);
13549 if (n != 0)
13550 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
13551 if (r == NULL)
13552 # else
13553 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
13554 serverStrToWin(serverid), &r, FALSE) < 0)
13555 # endif
13556 EMSG(_("E277: Unable to read a server reply"));
13558 #endif
13559 rettv->v_type = VAR_STRING;
13560 rettv->vval.v_string = r;
13564 * "remote_send()" function
13566 /*ARGSUSED*/
13567 static void
13568 f_remote_send(argvars, rettv)
13569 typval_T *argvars;
13570 typval_T *rettv;
13572 rettv->v_type = VAR_STRING;
13573 rettv->vval.v_string = NULL;
13574 #ifdef FEAT_CLIENTSERVER
13575 remote_common(argvars, rettv, FALSE);
13576 #endif
13580 * "remove()" function
13582 static void
13583 f_remove(argvars, rettv)
13584 typval_T *argvars;
13585 typval_T *rettv;
13587 list_T *l;
13588 listitem_T *item, *item2;
13589 listitem_T *li;
13590 long idx;
13591 long end;
13592 char_u *key;
13593 dict_T *d;
13594 dictitem_T *di;
13596 rettv->vval.v_number = 0;
13597 if (argvars[0].v_type == VAR_DICT)
13599 if (argvars[2].v_type != VAR_UNKNOWN)
13600 EMSG2(_(e_toomanyarg), "remove()");
13601 else if ((d = argvars[0].vval.v_dict) != NULL
13602 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
13604 key = get_tv_string_chk(&argvars[1]);
13605 if (key != NULL)
13607 di = dict_find(d, key, -1);
13608 if (di == NULL)
13609 EMSG2(_(e_dictkey), key);
13610 else
13612 *rettv = di->di_tv;
13613 init_tv(&di->di_tv);
13614 dictitem_remove(d, di);
13619 else if (argvars[0].v_type != VAR_LIST)
13620 EMSG2(_(e_listdictarg), "remove()");
13621 else if ((l = argvars[0].vval.v_list) != NULL
13622 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
13624 int error = FALSE;
13626 idx = get_tv_number_chk(&argvars[1], &error);
13627 if (error)
13628 ; /* type error: do nothing, errmsg already given */
13629 else if ((item = list_find(l, idx)) == NULL)
13630 EMSGN(_(e_listidx), idx);
13631 else
13633 if (argvars[2].v_type == VAR_UNKNOWN)
13635 /* Remove one item, return its value. */
13636 list_remove(l, item, item);
13637 *rettv = item->li_tv;
13638 vim_free(item);
13640 else
13642 /* Remove range of items, return list with values. */
13643 end = get_tv_number_chk(&argvars[2], &error);
13644 if (error)
13645 ; /* type error: do nothing */
13646 else if ((item2 = list_find(l, end)) == NULL)
13647 EMSGN(_(e_listidx), end);
13648 else
13650 int cnt = 0;
13652 for (li = item; li != NULL; li = li->li_next)
13654 ++cnt;
13655 if (li == item2)
13656 break;
13658 if (li == NULL) /* didn't find "item2" after "item" */
13659 EMSG(_(e_invrange));
13660 else
13662 list_remove(l, item, item2);
13663 if (rettv_list_alloc(rettv) == OK)
13665 l = rettv->vval.v_list;
13666 l->lv_first = item;
13667 l->lv_last = item2;
13668 item->li_prev = NULL;
13669 item2->li_next = NULL;
13670 l->lv_len = cnt;
13680 * "rename({from}, {to})" function
13682 static void
13683 f_rename(argvars, rettv)
13684 typval_T *argvars;
13685 typval_T *rettv;
13687 char_u buf[NUMBUFLEN];
13689 if (check_restricted() || check_secure())
13690 rettv->vval.v_number = -1;
13691 else
13692 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
13693 get_tv_string_buf(&argvars[1], buf));
13697 * "repeat()" function
13699 /*ARGSUSED*/
13700 static void
13701 f_repeat(argvars, rettv)
13702 typval_T *argvars;
13703 typval_T *rettv;
13705 char_u *p;
13706 int n;
13707 int slen;
13708 int len;
13709 char_u *r;
13710 int i;
13712 n = get_tv_number(&argvars[1]);
13713 if (argvars[0].v_type == VAR_LIST)
13715 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
13716 while (n-- > 0)
13717 if (list_extend(rettv->vval.v_list,
13718 argvars[0].vval.v_list, NULL) == FAIL)
13719 break;
13721 else
13723 p = get_tv_string(&argvars[0]);
13724 rettv->v_type = VAR_STRING;
13725 rettv->vval.v_string = NULL;
13727 slen = (int)STRLEN(p);
13728 len = slen * n;
13729 if (len <= 0)
13730 return;
13732 r = alloc(len + 1);
13733 if (r != NULL)
13735 for (i = 0; i < n; i++)
13736 mch_memmove(r + i * slen, p, (size_t)slen);
13737 r[len] = NUL;
13740 rettv->vval.v_string = r;
13745 * "resolve()" function
13747 static void
13748 f_resolve(argvars, rettv)
13749 typval_T *argvars;
13750 typval_T *rettv;
13752 char_u *p;
13754 p = get_tv_string(&argvars[0]);
13755 #ifdef FEAT_SHORTCUT
13757 char_u *v = NULL;
13759 v = mch_resolve_shortcut(p);
13760 if (v != NULL)
13761 rettv->vval.v_string = v;
13762 else
13763 rettv->vval.v_string = vim_strsave(p);
13765 #else
13766 # ifdef HAVE_READLINK
13768 char_u buf[MAXPATHL + 1];
13769 char_u *cpy;
13770 int len;
13771 char_u *remain = NULL;
13772 char_u *q;
13773 int is_relative_to_current = FALSE;
13774 int has_trailing_pathsep = FALSE;
13775 int limit = 100;
13777 p = vim_strsave(p);
13779 if (p[0] == '.' && (vim_ispathsep(p[1])
13780 || (p[1] == '.' && (vim_ispathsep(p[2])))))
13781 is_relative_to_current = TRUE;
13783 len = STRLEN(p);
13784 if (len > 0 && after_pathsep(p, p + len))
13785 has_trailing_pathsep = TRUE;
13787 q = getnextcomp(p);
13788 if (*q != NUL)
13790 /* Separate the first path component in "p", and keep the
13791 * remainder (beginning with the path separator). */
13792 remain = vim_strsave(q - 1);
13793 q[-1] = NUL;
13796 for (;;)
13798 for (;;)
13800 len = readlink((char *)p, (char *)buf, MAXPATHL);
13801 if (len <= 0)
13802 break;
13803 buf[len] = NUL;
13805 if (limit-- == 0)
13807 vim_free(p);
13808 vim_free(remain);
13809 EMSG(_("E655: Too many symbolic links (cycle?)"));
13810 rettv->vval.v_string = NULL;
13811 goto fail;
13814 /* Ensure that the result will have a trailing path separator
13815 * if the argument has one. */
13816 if (remain == NULL && has_trailing_pathsep)
13817 add_pathsep(buf);
13819 /* Separate the first path component in the link value and
13820 * concatenate the remainders. */
13821 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
13822 if (*q != NUL)
13824 if (remain == NULL)
13825 remain = vim_strsave(q - 1);
13826 else
13828 cpy = concat_str(q - 1, remain);
13829 if (cpy != NULL)
13831 vim_free(remain);
13832 remain = cpy;
13835 q[-1] = NUL;
13838 q = gettail(p);
13839 if (q > p && *q == NUL)
13841 /* Ignore trailing path separator. */
13842 q[-1] = NUL;
13843 q = gettail(p);
13845 if (q > p && !mch_isFullName(buf))
13847 /* symlink is relative to directory of argument */
13848 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
13849 if (cpy != NULL)
13851 STRCPY(cpy, p);
13852 STRCPY(gettail(cpy), buf);
13853 vim_free(p);
13854 p = cpy;
13857 else
13859 vim_free(p);
13860 p = vim_strsave(buf);
13864 if (remain == NULL)
13865 break;
13867 /* Append the first path component of "remain" to "p". */
13868 q = getnextcomp(remain + 1);
13869 len = q - remain - (*q != NUL);
13870 cpy = vim_strnsave(p, STRLEN(p) + len);
13871 if (cpy != NULL)
13873 STRNCAT(cpy, remain, len);
13874 vim_free(p);
13875 p = cpy;
13877 /* Shorten "remain". */
13878 if (*q != NUL)
13879 mch_memmove(remain, q - 1, STRLEN(q - 1) + 1);
13880 else
13882 vim_free(remain);
13883 remain = NULL;
13887 /* If the result is a relative path name, make it explicitly relative to
13888 * the current directory if and only if the argument had this form. */
13889 if (!vim_ispathsep(*p))
13891 if (is_relative_to_current
13892 && *p != NUL
13893 && !(p[0] == '.'
13894 && (p[1] == NUL
13895 || vim_ispathsep(p[1])
13896 || (p[1] == '.'
13897 && (p[2] == NUL
13898 || vim_ispathsep(p[2]))))))
13900 /* Prepend "./". */
13901 cpy = concat_str((char_u *)"./", p);
13902 if (cpy != NULL)
13904 vim_free(p);
13905 p = cpy;
13908 else if (!is_relative_to_current)
13910 /* Strip leading "./". */
13911 q = p;
13912 while (q[0] == '.' && vim_ispathsep(q[1]))
13913 q += 2;
13914 if (q > p)
13915 mch_memmove(p, p + 2, STRLEN(p + 2) + (size_t)1);
13919 /* Ensure that the result will have no trailing path separator
13920 * if the argument had none. But keep "/" or "//". */
13921 if (!has_trailing_pathsep)
13923 q = p + STRLEN(p);
13924 if (after_pathsep(p, q))
13925 *gettail_sep(p) = NUL;
13928 rettv->vval.v_string = p;
13930 # else
13931 rettv->vval.v_string = vim_strsave(p);
13932 # endif
13933 #endif
13935 simplify_filename(rettv->vval.v_string);
13937 #ifdef HAVE_READLINK
13938 fail:
13939 #endif
13940 rettv->v_type = VAR_STRING;
13944 * "reverse({list})" function
13946 static void
13947 f_reverse(argvars, rettv)
13948 typval_T *argvars;
13949 typval_T *rettv;
13951 list_T *l;
13952 listitem_T *li, *ni;
13954 rettv->vval.v_number = 0;
13955 if (argvars[0].v_type != VAR_LIST)
13956 EMSG2(_(e_listarg), "reverse()");
13957 else if ((l = argvars[0].vval.v_list) != NULL
13958 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
13960 li = l->lv_last;
13961 l->lv_first = l->lv_last = NULL;
13962 l->lv_len = 0;
13963 while (li != NULL)
13965 ni = li->li_prev;
13966 list_append(l, li);
13967 li = ni;
13969 rettv->vval.v_list = l;
13970 rettv->v_type = VAR_LIST;
13971 ++l->lv_refcount;
13972 l->lv_idx = l->lv_len - l->lv_idx - 1;
13976 #define SP_NOMOVE 0x01 /* don't move cursor */
13977 #define SP_REPEAT 0x02 /* repeat to find outer pair */
13978 #define SP_RETCOUNT 0x04 /* return matchcount */
13979 #define SP_SETPCMARK 0x08 /* set previous context mark */
13980 #define SP_START 0x10 /* accept match at start position */
13981 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
13982 #define SP_END 0x40 /* leave cursor at end of match */
13984 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
13987 * Get flags for a search function.
13988 * Possibly sets "p_ws".
13989 * Returns BACKWARD, FORWARD or zero (for an error).
13991 static int
13992 get_search_arg(varp, flagsp)
13993 typval_T *varp;
13994 int *flagsp;
13996 int dir = FORWARD;
13997 char_u *flags;
13998 char_u nbuf[NUMBUFLEN];
13999 int mask;
14001 if (varp->v_type != VAR_UNKNOWN)
14003 flags = get_tv_string_buf_chk(varp, nbuf);
14004 if (flags == NULL)
14005 return 0; /* type error; errmsg already given */
14006 while (*flags != NUL)
14008 switch (*flags)
14010 case 'b': dir = BACKWARD; break;
14011 case 'w': p_ws = TRUE; break;
14012 case 'W': p_ws = FALSE; break;
14013 default: mask = 0;
14014 if (flagsp != NULL)
14015 switch (*flags)
14017 case 'c': mask = SP_START; break;
14018 case 'e': mask = SP_END; break;
14019 case 'm': mask = SP_RETCOUNT; break;
14020 case 'n': mask = SP_NOMOVE; break;
14021 case 'p': mask = SP_SUBPAT; break;
14022 case 'r': mask = SP_REPEAT; break;
14023 case 's': mask = SP_SETPCMARK; break;
14025 if (mask == 0)
14027 EMSG2(_(e_invarg2), flags);
14028 dir = 0;
14030 else
14031 *flagsp |= mask;
14033 if (dir == 0)
14034 break;
14035 ++flags;
14038 return dir;
14042 * Shared by search() and searchpos() functions
14044 static int
14045 search_cmn(argvars, match_pos, flagsp)
14046 typval_T *argvars;
14047 pos_T *match_pos;
14048 int *flagsp;
14050 int flags;
14051 char_u *pat;
14052 pos_T pos;
14053 pos_T save_cursor;
14054 int save_p_ws = p_ws;
14055 int dir;
14056 int retval = 0; /* default: FAIL */
14057 long lnum_stop = 0;
14058 proftime_T tm;
14059 #ifdef FEAT_RELTIME
14060 long time_limit = 0;
14061 #endif
14062 int options = SEARCH_KEEP;
14063 int subpatnum;
14065 pat = get_tv_string(&argvars[0]);
14066 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
14067 if (dir == 0)
14068 goto theend;
14069 flags = *flagsp;
14070 if (flags & SP_START)
14071 options |= SEARCH_START;
14072 if (flags & SP_END)
14073 options |= SEARCH_END;
14075 /* Optional arguments: line number to stop searching and timeout. */
14076 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
14078 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
14079 if (lnum_stop < 0)
14080 goto theend;
14081 #ifdef FEAT_RELTIME
14082 if (argvars[3].v_type != VAR_UNKNOWN)
14084 time_limit = get_tv_number_chk(&argvars[3], NULL);
14085 if (time_limit < 0)
14086 goto theend;
14088 #endif
14091 #ifdef FEAT_RELTIME
14092 /* Set the time limit, if there is one. */
14093 profile_setlimit(time_limit, &tm);
14094 #endif
14097 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
14098 * Check to make sure only those flags are set.
14099 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
14100 * flags cannot be set. Check for that condition also.
14102 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
14103 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14105 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
14106 goto theend;
14109 pos = save_cursor = curwin->w_cursor;
14110 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14111 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
14112 if (subpatnum != FAIL)
14114 if (flags & SP_SUBPAT)
14115 retval = subpatnum;
14116 else
14117 retval = pos.lnum;
14118 if (flags & SP_SETPCMARK)
14119 setpcmark();
14120 curwin->w_cursor = pos;
14121 if (match_pos != NULL)
14123 /* Store the match cursor position */
14124 match_pos->lnum = pos.lnum;
14125 match_pos->col = pos.col + 1;
14127 /* "/$" will put the cursor after the end of the line, may need to
14128 * correct that here */
14129 check_cursor();
14132 /* If 'n' flag is used: restore cursor position. */
14133 if (flags & SP_NOMOVE)
14134 curwin->w_cursor = save_cursor;
14135 else
14136 curwin->w_set_curswant = TRUE;
14137 theend:
14138 p_ws = save_p_ws;
14140 return retval;
14144 * "search()" function
14146 static void
14147 f_search(argvars, rettv)
14148 typval_T *argvars;
14149 typval_T *rettv;
14151 int flags = 0;
14153 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
14157 * "searchdecl()" function
14159 static void
14160 f_searchdecl(argvars, rettv)
14161 typval_T *argvars;
14162 typval_T *rettv;
14164 int locally = 1;
14165 int thisblock = 0;
14166 int error = FALSE;
14167 char_u *name;
14169 rettv->vval.v_number = 1; /* default: FAIL */
14171 name = get_tv_string_chk(&argvars[0]);
14172 if (argvars[1].v_type != VAR_UNKNOWN)
14174 locally = get_tv_number_chk(&argvars[1], &error) == 0;
14175 if (!error && argvars[2].v_type != VAR_UNKNOWN)
14176 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
14178 if (!error && name != NULL)
14179 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
14180 locally, thisblock, SEARCH_KEEP) == FAIL;
14184 * Used by searchpair() and searchpairpos()
14186 static int
14187 searchpair_cmn(argvars, match_pos)
14188 typval_T *argvars;
14189 pos_T *match_pos;
14191 char_u *spat, *mpat, *epat;
14192 char_u *skip;
14193 int save_p_ws = p_ws;
14194 int dir;
14195 int flags = 0;
14196 char_u nbuf1[NUMBUFLEN];
14197 char_u nbuf2[NUMBUFLEN];
14198 char_u nbuf3[NUMBUFLEN];
14199 int retval = 0; /* default: FAIL */
14200 long lnum_stop = 0;
14201 long time_limit = 0;
14203 /* Get the three pattern arguments: start, middle, end. */
14204 spat = get_tv_string_chk(&argvars[0]);
14205 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
14206 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
14207 if (spat == NULL || mpat == NULL || epat == NULL)
14208 goto theend; /* type error */
14210 /* Handle the optional fourth argument: flags */
14211 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
14212 if (dir == 0)
14213 goto theend;
14215 /* Don't accept SP_END or SP_SUBPAT.
14216 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
14218 if ((flags & (SP_END | SP_SUBPAT)) != 0
14219 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14221 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
14222 goto theend;
14225 /* Using 'r' implies 'W', otherwise it doesn't work. */
14226 if (flags & SP_REPEAT)
14227 p_ws = FALSE;
14229 /* Optional fifth argument: skip expression */
14230 if (argvars[3].v_type == VAR_UNKNOWN
14231 || argvars[4].v_type == VAR_UNKNOWN)
14232 skip = (char_u *)"";
14233 else
14235 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
14236 if (argvars[5].v_type != VAR_UNKNOWN)
14238 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
14239 if (lnum_stop < 0)
14240 goto theend;
14241 #ifdef FEAT_RELTIME
14242 if (argvars[6].v_type != VAR_UNKNOWN)
14244 time_limit = get_tv_number_chk(&argvars[6], NULL);
14245 if (time_limit < 0)
14246 goto theend;
14248 #endif
14251 if (skip == NULL)
14252 goto theend; /* type error */
14254 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
14255 match_pos, lnum_stop, time_limit);
14257 theend:
14258 p_ws = save_p_ws;
14260 return retval;
14264 * "searchpair()" function
14266 static void
14267 f_searchpair(argvars, rettv)
14268 typval_T *argvars;
14269 typval_T *rettv;
14271 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
14275 * "searchpairpos()" function
14277 static void
14278 f_searchpairpos(argvars, rettv)
14279 typval_T *argvars;
14280 typval_T *rettv;
14282 pos_T match_pos;
14283 int lnum = 0;
14284 int col = 0;
14286 rettv->vval.v_number = 0;
14288 if (rettv_list_alloc(rettv) == FAIL)
14289 return;
14291 if (searchpair_cmn(argvars, &match_pos) > 0)
14293 lnum = match_pos.lnum;
14294 col = match_pos.col;
14297 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14298 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14302 * Search for a start/middle/end thing.
14303 * Used by searchpair(), see its documentation for the details.
14304 * Returns 0 or -1 for no match,
14306 long
14307 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
14308 lnum_stop, time_limit)
14309 char_u *spat; /* start pattern */
14310 char_u *mpat; /* middle pattern */
14311 char_u *epat; /* end pattern */
14312 int dir; /* BACKWARD or FORWARD */
14313 char_u *skip; /* skip expression */
14314 int flags; /* SP_SETPCMARK and other SP_ values */
14315 pos_T *match_pos;
14316 linenr_T lnum_stop; /* stop at this line if not zero */
14317 long time_limit; /* stop after this many msec */
14319 char_u *save_cpo;
14320 char_u *pat, *pat2 = NULL, *pat3 = NULL;
14321 long retval = 0;
14322 pos_T pos;
14323 pos_T firstpos;
14324 pos_T foundpos;
14325 pos_T save_cursor;
14326 pos_T save_pos;
14327 int n;
14328 int r;
14329 int nest = 1;
14330 int err;
14331 int options = SEARCH_KEEP;
14332 proftime_T tm;
14334 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
14335 save_cpo = p_cpo;
14336 p_cpo = (char_u *)"";
14338 #ifdef FEAT_RELTIME
14339 /* Set the time limit, if there is one. */
14340 profile_setlimit(time_limit, &tm);
14341 #endif
14343 /* Make two search patterns: start/end (pat2, for in nested pairs) and
14344 * start/middle/end (pat3, for the top pair). */
14345 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
14346 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
14347 if (pat2 == NULL || pat3 == NULL)
14348 goto theend;
14349 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
14350 if (*mpat == NUL)
14351 STRCPY(pat3, pat2);
14352 else
14353 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
14354 spat, epat, mpat);
14355 if (flags & SP_START)
14356 options |= SEARCH_START;
14358 save_cursor = curwin->w_cursor;
14359 pos = curwin->w_cursor;
14360 clearpos(&firstpos);
14361 clearpos(&foundpos);
14362 pat = pat3;
14363 for (;;)
14365 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14366 options, RE_SEARCH, lnum_stop, &tm);
14367 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
14368 /* didn't find it or found the first match again: FAIL */
14369 break;
14371 if (firstpos.lnum == 0)
14372 firstpos = pos;
14373 if (equalpos(pos, foundpos))
14375 /* Found the same position again. Can happen with a pattern that
14376 * has "\zs" at the end and searching backwards. Advance one
14377 * character and try again. */
14378 if (dir == BACKWARD)
14379 decl(&pos);
14380 else
14381 incl(&pos);
14383 foundpos = pos;
14385 /* clear the start flag to avoid getting stuck here */
14386 options &= ~SEARCH_START;
14388 /* If the skip pattern matches, ignore this match. */
14389 if (*skip != NUL)
14391 save_pos = curwin->w_cursor;
14392 curwin->w_cursor = pos;
14393 r = eval_to_bool(skip, &err, NULL, FALSE);
14394 curwin->w_cursor = save_pos;
14395 if (err)
14397 /* Evaluating {skip} caused an error, break here. */
14398 curwin->w_cursor = save_cursor;
14399 retval = -1;
14400 break;
14402 if (r)
14403 continue;
14406 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
14408 /* Found end when searching backwards or start when searching
14409 * forward: nested pair. */
14410 ++nest;
14411 pat = pat2; /* nested, don't search for middle */
14413 else
14415 /* Found end when searching forward or start when searching
14416 * backward: end of (nested) pair; or found middle in outer pair. */
14417 if (--nest == 1)
14418 pat = pat3; /* outer level, search for middle */
14421 if (nest == 0)
14423 /* Found the match: return matchcount or line number. */
14424 if (flags & SP_RETCOUNT)
14425 ++retval;
14426 else
14427 retval = pos.lnum;
14428 if (flags & SP_SETPCMARK)
14429 setpcmark();
14430 curwin->w_cursor = pos;
14431 if (!(flags & SP_REPEAT))
14432 break;
14433 nest = 1; /* search for next unmatched */
14437 if (match_pos != NULL)
14439 /* Store the match cursor position */
14440 match_pos->lnum = curwin->w_cursor.lnum;
14441 match_pos->col = curwin->w_cursor.col + 1;
14444 /* If 'n' flag is used or search failed: restore cursor position. */
14445 if ((flags & SP_NOMOVE) || retval == 0)
14446 curwin->w_cursor = save_cursor;
14448 theend:
14449 vim_free(pat2);
14450 vim_free(pat3);
14451 p_cpo = save_cpo;
14453 return retval;
14457 * "searchpos()" function
14459 static void
14460 f_searchpos(argvars, rettv)
14461 typval_T *argvars;
14462 typval_T *rettv;
14464 pos_T match_pos;
14465 int lnum = 0;
14466 int col = 0;
14467 int n;
14468 int flags = 0;
14470 rettv->vval.v_number = 0;
14472 if (rettv_list_alloc(rettv) == FAIL)
14473 return;
14475 n = search_cmn(argvars, &match_pos, &flags);
14476 if (n > 0)
14478 lnum = match_pos.lnum;
14479 col = match_pos.col;
14482 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14483 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14484 if (flags & SP_SUBPAT)
14485 list_append_number(rettv->vval.v_list, (varnumber_T)n);
14489 /*ARGSUSED*/
14490 static void
14491 f_server2client(argvars, rettv)
14492 typval_T *argvars;
14493 typval_T *rettv;
14495 #ifdef FEAT_CLIENTSERVER
14496 char_u buf[NUMBUFLEN];
14497 char_u *server = get_tv_string_chk(&argvars[0]);
14498 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
14500 rettv->vval.v_number = -1;
14501 if (server == NULL || reply == NULL)
14502 return;
14503 if (check_restricted() || check_secure())
14504 return;
14505 # ifdef FEAT_X11
14506 if (check_connection() == FAIL)
14507 return;
14508 # endif
14510 if (serverSendReply(server, reply) < 0)
14512 EMSG(_("E258: Unable to send to client"));
14513 return;
14515 rettv->vval.v_number = 0;
14516 #else
14517 rettv->vval.v_number = -1;
14518 #endif
14521 /*ARGSUSED*/
14522 static void
14523 f_serverlist(argvars, rettv)
14524 typval_T *argvars;
14525 typval_T *rettv;
14527 char_u *r = NULL;
14529 #ifdef FEAT_CLIENTSERVER
14530 # ifdef WIN32
14531 r = serverGetVimNames();
14532 # else
14533 make_connection();
14534 if (X_DISPLAY != NULL)
14535 r = serverGetVimNames(X_DISPLAY);
14536 # endif
14537 #endif
14538 rettv->v_type = VAR_STRING;
14539 rettv->vval.v_string = r;
14543 * "setbufvar()" function
14545 /*ARGSUSED*/
14546 static void
14547 f_setbufvar(argvars, rettv)
14548 typval_T *argvars;
14549 typval_T *rettv;
14551 buf_T *buf;
14552 aco_save_T aco;
14553 char_u *varname, *bufvarname;
14554 typval_T *varp;
14555 char_u nbuf[NUMBUFLEN];
14557 rettv->vval.v_number = 0;
14559 if (check_restricted() || check_secure())
14560 return;
14561 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
14562 varname = get_tv_string_chk(&argvars[1]);
14563 buf = get_buf_tv(&argvars[0]);
14564 varp = &argvars[2];
14566 if (buf != NULL && varname != NULL && varp != NULL)
14568 /* set curbuf to be our buf, temporarily */
14569 aucmd_prepbuf(&aco, buf);
14571 if (*varname == '&')
14573 long numval;
14574 char_u *strval;
14575 int error = FALSE;
14577 ++varname;
14578 numval = get_tv_number_chk(varp, &error);
14579 strval = get_tv_string_buf_chk(varp, nbuf);
14580 if (!error && strval != NULL)
14581 set_option_value(varname, numval, strval, OPT_LOCAL);
14583 else
14585 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
14586 if (bufvarname != NULL)
14588 STRCPY(bufvarname, "b:");
14589 STRCPY(bufvarname + 2, varname);
14590 set_var(bufvarname, varp, TRUE);
14591 vim_free(bufvarname);
14595 /* reset notion of buffer */
14596 aucmd_restbuf(&aco);
14601 * "setcmdpos()" function
14603 static void
14604 f_setcmdpos(argvars, rettv)
14605 typval_T *argvars;
14606 typval_T *rettv;
14608 int pos = (int)get_tv_number(&argvars[0]) - 1;
14610 if (pos >= 0)
14611 rettv->vval.v_number = set_cmdline_pos(pos);
14615 * "setline()" function
14617 static void
14618 f_setline(argvars, rettv)
14619 typval_T *argvars;
14620 typval_T *rettv;
14622 linenr_T lnum;
14623 char_u *line = NULL;
14624 list_T *l = NULL;
14625 listitem_T *li = NULL;
14626 long added = 0;
14627 linenr_T lcount = curbuf->b_ml.ml_line_count;
14629 lnum = get_tv_lnum(&argvars[0]);
14630 if (argvars[1].v_type == VAR_LIST)
14632 l = argvars[1].vval.v_list;
14633 li = l->lv_first;
14635 else
14636 line = get_tv_string_chk(&argvars[1]);
14638 rettv->vval.v_number = 0; /* OK */
14639 for (;;)
14641 if (l != NULL)
14643 /* list argument, get next string */
14644 if (li == NULL)
14645 break;
14646 line = get_tv_string_chk(&li->li_tv);
14647 li = li->li_next;
14650 rettv->vval.v_number = 1; /* FAIL */
14651 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
14652 break;
14653 if (lnum <= curbuf->b_ml.ml_line_count)
14655 /* existing line, replace it */
14656 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
14658 changed_bytes(lnum, 0);
14659 if (lnum == curwin->w_cursor.lnum)
14660 check_cursor_col();
14661 rettv->vval.v_number = 0; /* OK */
14664 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
14666 /* lnum is one past the last line, append the line */
14667 ++added;
14668 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
14669 rettv->vval.v_number = 0; /* OK */
14672 if (l == NULL) /* only one string argument */
14673 break;
14674 ++lnum;
14677 if (added > 0)
14678 appended_lines_mark(lcount, added);
14681 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
14684 * Used by "setqflist()" and "setloclist()" functions
14686 /*ARGSUSED*/
14687 static void
14688 set_qf_ll_list(wp, list_arg, action_arg, rettv)
14689 win_T *wp;
14690 typval_T *list_arg;
14691 typval_T *action_arg;
14692 typval_T *rettv;
14694 #ifdef FEAT_QUICKFIX
14695 char_u *act;
14696 int action = ' ';
14697 #endif
14699 rettv->vval.v_number = -1;
14701 #ifdef FEAT_QUICKFIX
14702 if (list_arg->v_type != VAR_LIST)
14703 EMSG(_(e_listreq));
14704 else
14706 list_T *l = list_arg->vval.v_list;
14708 if (action_arg->v_type == VAR_STRING)
14710 act = get_tv_string_chk(action_arg);
14711 if (act == NULL)
14712 return; /* type error; errmsg already given */
14713 if (*act == 'a' || *act == 'r')
14714 action = *act;
14717 if (l != NULL && set_errorlist(wp, l, action) == OK)
14718 rettv->vval.v_number = 0;
14720 #endif
14724 * "setloclist()" function
14726 /*ARGSUSED*/
14727 static void
14728 f_setloclist(argvars, rettv)
14729 typval_T *argvars;
14730 typval_T *rettv;
14732 win_T *win;
14734 rettv->vval.v_number = -1;
14736 win = find_win_by_nr(&argvars[0], NULL);
14737 if (win != NULL)
14738 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
14742 * "setmatches()" function
14744 static void
14745 f_setmatches(argvars, rettv)
14746 typval_T *argvars;
14747 typval_T *rettv;
14749 #ifdef FEAT_SEARCH_EXTRA
14750 list_T *l;
14751 listitem_T *li;
14752 dict_T *d;
14754 rettv->vval.v_number = -1;
14755 if (argvars[0].v_type != VAR_LIST)
14757 EMSG(_(e_listreq));
14758 return;
14760 if ((l = argvars[0].vval.v_list) != NULL)
14763 /* To some extent make sure that we are dealing with a list from
14764 * "getmatches()". */
14765 li = l->lv_first;
14766 while (li != NULL)
14768 if (li->li_tv.v_type != VAR_DICT
14769 || (d = li->li_tv.vval.v_dict) == NULL)
14771 EMSG(_(e_invarg));
14772 return;
14774 if (!(dict_find(d, (char_u *)"group", -1) != NULL
14775 && dict_find(d, (char_u *)"pattern", -1) != NULL
14776 && dict_find(d, (char_u *)"priority", -1) != NULL
14777 && dict_find(d, (char_u *)"id", -1) != NULL))
14779 EMSG(_(e_invarg));
14780 return;
14782 li = li->li_next;
14785 clear_matches(curwin);
14786 li = l->lv_first;
14787 while (li != NULL)
14789 d = li->li_tv.vval.v_dict;
14790 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
14791 get_dict_string(d, (char_u *)"pattern", FALSE),
14792 (int)get_dict_number(d, (char_u *)"priority"),
14793 (int)get_dict_number(d, (char_u *)"id"));
14794 li = li->li_next;
14796 rettv->vval.v_number = 0;
14798 #endif
14802 * "setpos()" function
14804 /*ARGSUSED*/
14805 static void
14806 f_setpos(argvars, rettv)
14807 typval_T *argvars;
14808 typval_T *rettv;
14810 pos_T pos;
14811 int fnum;
14812 char_u *name;
14814 rettv->vval.v_number = -1;
14815 name = get_tv_string_chk(argvars);
14816 if (name != NULL)
14818 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
14820 --pos.col;
14821 if (name[0] == '.' && name[1] == NUL)
14823 /* set cursor */
14824 if (fnum == curbuf->b_fnum)
14826 curwin->w_cursor = pos;
14827 check_cursor();
14828 rettv->vval.v_number = 0;
14830 else
14831 EMSG(_(e_invarg));
14833 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
14835 /* set mark */
14836 if (setmark_pos(name[1], &pos, fnum) == OK)
14837 rettv->vval.v_number = 0;
14839 else
14840 EMSG(_(e_invarg));
14846 * "setqflist()" function
14848 /*ARGSUSED*/
14849 static void
14850 f_setqflist(argvars, rettv)
14851 typval_T *argvars;
14852 typval_T *rettv;
14854 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
14858 * "setreg()" function
14860 static void
14861 f_setreg(argvars, rettv)
14862 typval_T *argvars;
14863 typval_T *rettv;
14865 int regname;
14866 char_u *strregname;
14867 char_u *stropt;
14868 char_u *strval;
14869 int append;
14870 char_u yank_type;
14871 long block_len;
14873 block_len = -1;
14874 yank_type = MAUTO;
14875 append = FALSE;
14877 strregname = get_tv_string_chk(argvars);
14878 rettv->vval.v_number = 1; /* FAIL is default */
14880 if (strregname == NULL)
14881 return; /* type error; errmsg already given */
14882 regname = *strregname;
14883 if (regname == 0 || regname == '@')
14884 regname = '"';
14885 else if (regname == '=')
14886 return;
14888 if (argvars[2].v_type != VAR_UNKNOWN)
14890 stropt = get_tv_string_chk(&argvars[2]);
14891 if (stropt == NULL)
14892 return; /* type error */
14893 for (; *stropt != NUL; ++stropt)
14894 switch (*stropt)
14896 case 'a': case 'A': /* append */
14897 append = TRUE;
14898 break;
14899 case 'v': case 'c': /* character-wise selection */
14900 yank_type = MCHAR;
14901 break;
14902 case 'V': case 'l': /* line-wise selection */
14903 yank_type = MLINE;
14904 break;
14905 #ifdef FEAT_VISUAL
14906 case 'b': case Ctrl_V: /* block-wise selection */
14907 yank_type = MBLOCK;
14908 if (VIM_ISDIGIT(stropt[1]))
14910 ++stropt;
14911 block_len = getdigits(&stropt) - 1;
14912 --stropt;
14914 break;
14915 #endif
14919 strval = get_tv_string_chk(&argvars[1]);
14920 if (strval != NULL)
14921 write_reg_contents_ex(regname, strval, -1,
14922 append, yank_type, block_len);
14923 rettv->vval.v_number = 0;
14927 * "settabwinvar()" function
14929 static void
14930 f_settabwinvar(argvars, rettv)
14931 typval_T *argvars;
14932 typval_T *rettv;
14934 setwinvar(argvars, rettv, 1);
14938 * "setwinvar()" function
14940 static void
14941 f_setwinvar(argvars, rettv)
14942 typval_T *argvars;
14943 typval_T *rettv;
14945 setwinvar(argvars, rettv, 0);
14949 * "setwinvar()" and "settabwinvar()" functions
14951 static void
14952 setwinvar(argvars, rettv, off)
14953 typval_T *argvars;
14954 typval_T *rettv;
14955 int off;
14957 win_T *win;
14958 #ifdef FEAT_WINDOWS
14959 win_T *save_curwin;
14960 tabpage_T *save_curtab;
14961 #endif
14962 char_u *varname, *winvarname;
14963 typval_T *varp;
14964 char_u nbuf[NUMBUFLEN];
14965 tabpage_T *tp;
14967 rettv->vval.v_number = 0;
14969 if (check_restricted() || check_secure())
14970 return;
14972 #ifdef FEAT_WINDOWS
14973 if (off == 1)
14974 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
14975 else
14976 tp = curtab;
14977 #endif
14978 win = find_win_by_nr(&argvars[off], tp);
14979 varname = get_tv_string_chk(&argvars[off + 1]);
14980 varp = &argvars[off + 2];
14982 if (win != NULL && varname != NULL && varp != NULL)
14984 #ifdef FEAT_WINDOWS
14985 /* set curwin to be our win, temporarily */
14986 save_curwin = curwin;
14987 save_curtab = curtab;
14988 goto_tabpage_tp(tp);
14989 if (!win_valid(win))
14990 return;
14991 curwin = win;
14992 curbuf = curwin->w_buffer;
14993 #endif
14995 if (*varname == '&')
14997 long numval;
14998 char_u *strval;
14999 int error = FALSE;
15001 ++varname;
15002 numval = get_tv_number_chk(varp, &error);
15003 strval = get_tv_string_buf_chk(varp, nbuf);
15004 if (!error && strval != NULL)
15005 set_option_value(varname, numval, strval, OPT_LOCAL);
15007 else
15009 winvarname = alloc((unsigned)STRLEN(varname) + 3);
15010 if (winvarname != NULL)
15012 STRCPY(winvarname, "w:");
15013 STRCPY(winvarname + 2, varname);
15014 set_var(winvarname, varp, TRUE);
15015 vim_free(winvarname);
15019 #ifdef FEAT_WINDOWS
15020 /* Restore current tabpage and window, if still valid (autocomands can
15021 * make them invalid). */
15022 if (valid_tabpage(save_curtab))
15023 goto_tabpage_tp(save_curtab);
15024 if (win_valid(save_curwin))
15026 curwin = save_curwin;
15027 curbuf = curwin->w_buffer;
15029 #endif
15034 * "shellescape({string})" function
15036 static void
15037 f_shellescape(argvars, rettv)
15038 typval_T *argvars;
15039 typval_T *rettv;
15041 rettv->vval.v_string = vim_strsave_shellescape(get_tv_string(&argvars[0]));
15042 rettv->v_type = VAR_STRING;
15046 * "simplify()" function
15048 static void
15049 f_simplify(argvars, rettv)
15050 typval_T *argvars;
15051 typval_T *rettv;
15053 char_u *p;
15055 p = get_tv_string(&argvars[0]);
15056 rettv->vval.v_string = vim_strsave(p);
15057 simplify_filename(rettv->vval.v_string); /* simplify in place */
15058 rettv->v_type = VAR_STRING;
15061 static int
15062 #ifdef __BORLANDC__
15063 _RTLENTRYF
15064 #endif
15065 item_compare __ARGS((const void *s1, const void *s2));
15066 static int
15067 #ifdef __BORLANDC__
15068 _RTLENTRYF
15069 #endif
15070 item_compare2 __ARGS((const void *s1, const void *s2));
15072 static int item_compare_ic;
15073 static char_u *item_compare_func;
15074 static int item_compare_func_err;
15075 #define ITEM_COMPARE_FAIL 999
15078 * Compare functions for f_sort() below.
15080 static int
15081 #ifdef __BORLANDC__
15082 _RTLENTRYF
15083 #endif
15084 item_compare(s1, s2)
15085 const void *s1;
15086 const void *s2;
15088 char_u *p1, *p2;
15089 char_u *tofree1, *tofree2;
15090 int res;
15091 char_u numbuf1[NUMBUFLEN];
15092 char_u numbuf2[NUMBUFLEN];
15094 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
15095 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
15096 if (p1 == NULL)
15097 p1 = (char_u *)"";
15098 if (p2 == NULL)
15099 p2 = (char_u *)"";
15100 if (item_compare_ic)
15101 res = STRICMP(p1, p2);
15102 else
15103 res = STRCMP(p1, p2);
15104 vim_free(tofree1);
15105 vim_free(tofree2);
15106 return res;
15109 static int
15110 #ifdef __BORLANDC__
15111 _RTLENTRYF
15112 #endif
15113 item_compare2(s1, s2)
15114 const void *s1;
15115 const void *s2;
15117 int res;
15118 typval_T rettv;
15119 typval_T argv[3];
15120 int dummy;
15122 /* shortcut after failure in previous call; compare all items equal */
15123 if (item_compare_func_err)
15124 return 0;
15126 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
15127 * in the copy without changing the original list items. */
15128 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
15129 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
15131 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
15132 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
15133 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
15134 clear_tv(&argv[0]);
15135 clear_tv(&argv[1]);
15137 if (res == FAIL)
15138 res = ITEM_COMPARE_FAIL;
15139 else
15140 /* return value has wrong type */
15141 res = get_tv_number_chk(&rettv, &item_compare_func_err);
15142 if (item_compare_func_err)
15143 res = ITEM_COMPARE_FAIL;
15144 clear_tv(&rettv);
15145 return res;
15149 * "sort({list})" function
15151 static void
15152 f_sort(argvars, rettv)
15153 typval_T *argvars;
15154 typval_T *rettv;
15156 list_T *l;
15157 listitem_T *li;
15158 listitem_T **ptrs;
15159 long len;
15160 long i;
15162 rettv->vval.v_number = 0;
15163 if (argvars[0].v_type != VAR_LIST)
15164 EMSG2(_(e_listarg), "sort()");
15165 else
15167 l = argvars[0].vval.v_list;
15168 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
15169 return;
15170 rettv->vval.v_list = l;
15171 rettv->v_type = VAR_LIST;
15172 ++l->lv_refcount;
15174 len = list_len(l);
15175 if (len <= 1)
15176 return; /* short list sorts pretty quickly */
15178 item_compare_ic = FALSE;
15179 item_compare_func = NULL;
15180 if (argvars[1].v_type != VAR_UNKNOWN)
15182 if (argvars[1].v_type == VAR_FUNC)
15183 item_compare_func = argvars[1].vval.v_string;
15184 else
15186 int error = FALSE;
15188 i = get_tv_number_chk(&argvars[1], &error);
15189 if (error)
15190 return; /* type error; errmsg already given */
15191 if (i == 1)
15192 item_compare_ic = TRUE;
15193 else
15194 item_compare_func = get_tv_string(&argvars[1]);
15198 /* Make an array with each entry pointing to an item in the List. */
15199 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
15200 if (ptrs == NULL)
15201 return;
15202 i = 0;
15203 for (li = l->lv_first; li != NULL; li = li->li_next)
15204 ptrs[i++] = li;
15206 item_compare_func_err = FALSE;
15207 /* test the compare function */
15208 if (item_compare_func != NULL
15209 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
15210 == ITEM_COMPARE_FAIL)
15211 EMSG(_("E702: Sort compare function failed"));
15212 else
15214 /* Sort the array with item pointers. */
15215 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
15216 item_compare_func == NULL ? item_compare : item_compare2);
15218 if (!item_compare_func_err)
15220 /* Clear the List and append the items in the sorted order. */
15221 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
15222 l->lv_len = 0;
15223 for (i = 0; i < len; ++i)
15224 list_append(l, ptrs[i]);
15228 vim_free(ptrs);
15233 * "soundfold({word})" function
15235 static void
15236 f_soundfold(argvars, rettv)
15237 typval_T *argvars;
15238 typval_T *rettv;
15240 char_u *s;
15242 rettv->v_type = VAR_STRING;
15243 s = get_tv_string(&argvars[0]);
15244 #ifdef FEAT_SPELL
15245 rettv->vval.v_string = eval_soundfold(s);
15246 #else
15247 rettv->vval.v_string = vim_strsave(s);
15248 #endif
15252 * "spellbadword()" function
15254 /* ARGSUSED */
15255 static void
15256 f_spellbadword(argvars, rettv)
15257 typval_T *argvars;
15258 typval_T *rettv;
15260 char_u *word = (char_u *)"";
15261 hlf_T attr = HLF_COUNT;
15262 int len = 0;
15264 if (rettv_list_alloc(rettv) == FAIL)
15265 return;
15267 #ifdef FEAT_SPELL
15268 if (argvars[0].v_type == VAR_UNKNOWN)
15270 /* Find the start and length of the badly spelled word. */
15271 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
15272 if (len != 0)
15273 word = ml_get_cursor();
15275 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15277 char_u *str = get_tv_string_chk(&argvars[0]);
15278 int capcol = -1;
15280 if (str != NULL)
15282 /* Check the argument for spelling. */
15283 while (*str != NUL)
15285 len = spell_check(curwin, str, &attr, &capcol, FALSE);
15286 if (attr != HLF_COUNT)
15288 word = str;
15289 break;
15291 str += len;
15295 #endif
15297 list_append_string(rettv->vval.v_list, word, len);
15298 list_append_string(rettv->vval.v_list, (char_u *)(
15299 attr == HLF_SPB ? "bad" :
15300 attr == HLF_SPR ? "rare" :
15301 attr == HLF_SPL ? "local" :
15302 attr == HLF_SPC ? "caps" :
15303 ""), -1);
15307 * "spellsuggest()" function
15309 /*ARGSUSED*/
15310 static void
15311 f_spellsuggest(argvars, rettv)
15312 typval_T *argvars;
15313 typval_T *rettv;
15315 #ifdef FEAT_SPELL
15316 char_u *str;
15317 int typeerr = FALSE;
15318 int maxcount;
15319 garray_T ga;
15320 int i;
15321 listitem_T *li;
15322 int need_capital = FALSE;
15323 #endif
15325 if (rettv_list_alloc(rettv) == FAIL)
15326 return;
15328 #ifdef FEAT_SPELL
15329 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15331 str = get_tv_string(&argvars[0]);
15332 if (argvars[1].v_type != VAR_UNKNOWN)
15334 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
15335 if (maxcount <= 0)
15336 return;
15337 if (argvars[2].v_type != VAR_UNKNOWN)
15339 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
15340 if (typeerr)
15341 return;
15344 else
15345 maxcount = 25;
15347 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
15349 for (i = 0; i < ga.ga_len; ++i)
15351 str = ((char_u **)ga.ga_data)[i];
15353 li = listitem_alloc();
15354 if (li == NULL)
15355 vim_free(str);
15356 else
15358 li->li_tv.v_type = VAR_STRING;
15359 li->li_tv.v_lock = 0;
15360 li->li_tv.vval.v_string = str;
15361 list_append(rettv->vval.v_list, li);
15364 ga_clear(&ga);
15366 #endif
15369 static void
15370 f_split(argvars, rettv)
15371 typval_T *argvars;
15372 typval_T *rettv;
15374 char_u *str;
15375 char_u *end;
15376 char_u *pat = NULL;
15377 regmatch_T regmatch;
15378 char_u patbuf[NUMBUFLEN];
15379 char_u *save_cpo;
15380 int match;
15381 colnr_T col = 0;
15382 int keepempty = FALSE;
15383 int typeerr = FALSE;
15385 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15386 save_cpo = p_cpo;
15387 p_cpo = (char_u *)"";
15389 str = get_tv_string(&argvars[0]);
15390 if (argvars[1].v_type != VAR_UNKNOWN)
15392 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
15393 if (pat == NULL)
15394 typeerr = TRUE;
15395 if (argvars[2].v_type != VAR_UNKNOWN)
15396 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
15398 if (pat == NULL || *pat == NUL)
15399 pat = (char_u *)"[\\x01- ]\\+";
15401 if (rettv_list_alloc(rettv) == FAIL)
15402 return;
15403 if (typeerr)
15404 return;
15406 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
15407 if (regmatch.regprog != NULL)
15409 regmatch.rm_ic = FALSE;
15410 while (*str != NUL || keepempty)
15412 if (*str == NUL)
15413 match = FALSE; /* empty item at the end */
15414 else
15415 match = vim_regexec_nl(&regmatch, str, col);
15416 if (match)
15417 end = regmatch.startp[0];
15418 else
15419 end = str + STRLEN(str);
15420 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
15421 && *str != NUL && match && end < regmatch.endp[0]))
15423 if (list_append_string(rettv->vval.v_list, str,
15424 (int)(end - str)) == FAIL)
15425 break;
15427 if (!match)
15428 break;
15429 /* Advance to just after the match. */
15430 if (regmatch.endp[0] > str)
15431 col = 0;
15432 else
15434 /* Don't get stuck at the same match. */
15435 #ifdef FEAT_MBYTE
15436 col = (*mb_ptr2len)(regmatch.endp[0]);
15437 #else
15438 col = 1;
15439 #endif
15441 str = regmatch.endp[0];
15444 vim_free(regmatch.regprog);
15447 p_cpo = save_cpo;
15451 * "str2nr()" function
15453 static void
15454 f_str2nr(argvars, rettv)
15455 typval_T *argvars;
15456 typval_T *rettv;
15458 int base = 10;
15459 char_u *p;
15460 long n;
15462 if (argvars[1].v_type != VAR_UNKNOWN)
15464 base = get_tv_number(&argvars[1]);
15465 if (base != 8 && base != 10 && base != 16)
15467 EMSG(_(e_invarg));
15468 return;
15472 p = skipwhite(get_tv_string(&argvars[0]));
15473 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
15474 rettv->vval.v_number = n;
15477 #ifdef HAVE_STRFTIME
15479 * "strftime({format}[, {time}])" function
15481 static void
15482 f_strftime(argvars, rettv)
15483 typval_T *argvars;
15484 typval_T *rettv;
15486 char_u result_buf[256];
15487 struct tm *curtime;
15488 time_t seconds;
15489 char_u *p;
15491 rettv->v_type = VAR_STRING;
15493 p = get_tv_string(&argvars[0]);
15494 if (argvars[1].v_type == VAR_UNKNOWN)
15495 seconds = time(NULL);
15496 else
15497 seconds = (time_t)get_tv_number(&argvars[1]);
15498 curtime = localtime(&seconds);
15499 /* MSVC returns NULL for an invalid value of seconds. */
15500 if (curtime == NULL)
15501 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
15502 else
15504 # ifdef FEAT_MBYTE
15505 vimconv_T conv;
15506 char_u *enc;
15508 conv.vc_type = CONV_NONE;
15509 enc = enc_locale();
15510 convert_setup(&conv, p_enc, enc);
15511 if (conv.vc_type != CONV_NONE)
15512 p = string_convert(&conv, p, NULL);
15513 # endif
15514 if (p != NULL)
15515 (void)strftime((char *)result_buf, sizeof(result_buf),
15516 (char *)p, curtime);
15517 else
15518 result_buf[0] = NUL;
15520 # ifdef FEAT_MBYTE
15521 if (conv.vc_type != CONV_NONE)
15522 vim_free(p);
15523 convert_setup(&conv, enc, p_enc);
15524 if (conv.vc_type != CONV_NONE)
15525 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
15526 else
15527 # endif
15528 rettv->vval.v_string = vim_strsave(result_buf);
15530 # ifdef FEAT_MBYTE
15531 /* Release conversion descriptors */
15532 convert_setup(&conv, NULL, NULL);
15533 vim_free(enc);
15534 # endif
15537 #endif
15540 * "stridx()" function
15542 static void
15543 f_stridx(argvars, rettv)
15544 typval_T *argvars;
15545 typval_T *rettv;
15547 char_u buf[NUMBUFLEN];
15548 char_u *needle;
15549 char_u *haystack;
15550 char_u *save_haystack;
15551 char_u *pos;
15552 int start_idx;
15554 needle = get_tv_string_chk(&argvars[1]);
15555 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
15556 rettv->vval.v_number = -1;
15557 if (needle == NULL || haystack == NULL)
15558 return; /* type error; errmsg already given */
15560 if (argvars[2].v_type != VAR_UNKNOWN)
15562 int error = FALSE;
15564 start_idx = get_tv_number_chk(&argvars[2], &error);
15565 if (error || start_idx >= (int)STRLEN(haystack))
15566 return;
15567 if (start_idx >= 0)
15568 haystack += start_idx;
15571 pos = (char_u *)strstr((char *)haystack, (char *)needle);
15572 if (pos != NULL)
15573 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
15577 * "string()" function
15579 static void
15580 f_string(argvars, rettv)
15581 typval_T *argvars;
15582 typval_T *rettv;
15584 char_u *tofree;
15585 char_u numbuf[NUMBUFLEN];
15587 rettv->v_type = VAR_STRING;
15588 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
15589 /* Make a copy if we have a value but it's not in allocate memory. */
15590 if (rettv->vval.v_string != NULL && tofree == NULL)
15591 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
15595 * "strlen()" function
15597 static void
15598 f_strlen(argvars, rettv)
15599 typval_T *argvars;
15600 typval_T *rettv;
15602 rettv->vval.v_number = (varnumber_T)(STRLEN(
15603 get_tv_string(&argvars[0])));
15607 * "strpart()" function
15609 static void
15610 f_strpart(argvars, rettv)
15611 typval_T *argvars;
15612 typval_T *rettv;
15614 char_u *p;
15615 int n;
15616 int len;
15617 int slen;
15618 int error = FALSE;
15620 p = get_tv_string(&argvars[0]);
15621 slen = (int)STRLEN(p);
15623 n = get_tv_number_chk(&argvars[1], &error);
15624 if (error)
15625 len = 0;
15626 else if (argvars[2].v_type != VAR_UNKNOWN)
15627 len = get_tv_number(&argvars[2]);
15628 else
15629 len = slen - n; /* default len: all bytes that are available. */
15632 * Only return the overlap between the specified part and the actual
15633 * string.
15635 if (n < 0)
15637 len += n;
15638 n = 0;
15640 else if (n > slen)
15641 n = slen;
15642 if (len < 0)
15643 len = 0;
15644 else if (n + len > slen)
15645 len = slen - n;
15647 rettv->v_type = VAR_STRING;
15648 rettv->vval.v_string = vim_strnsave(p + n, len);
15652 * "strridx()" function
15654 static void
15655 f_strridx(argvars, rettv)
15656 typval_T *argvars;
15657 typval_T *rettv;
15659 char_u buf[NUMBUFLEN];
15660 char_u *needle;
15661 char_u *haystack;
15662 char_u *rest;
15663 char_u *lastmatch = NULL;
15664 int haystack_len, end_idx;
15666 needle = get_tv_string_chk(&argvars[1]);
15667 haystack = get_tv_string_buf_chk(&argvars[0], buf);
15669 rettv->vval.v_number = -1;
15670 if (needle == NULL || haystack == NULL)
15671 return; /* type error; errmsg already given */
15673 haystack_len = (int)STRLEN(haystack);
15674 if (argvars[2].v_type != VAR_UNKNOWN)
15676 /* Third argument: upper limit for index */
15677 end_idx = get_tv_number_chk(&argvars[2], NULL);
15678 if (end_idx < 0)
15679 return; /* can never find a match */
15681 else
15682 end_idx = haystack_len;
15684 if (*needle == NUL)
15686 /* Empty string matches past the end. */
15687 lastmatch = haystack + end_idx;
15689 else
15691 for (rest = haystack; *rest != '\0'; ++rest)
15693 rest = (char_u *)strstr((char *)rest, (char *)needle);
15694 if (rest == NULL || rest > haystack + end_idx)
15695 break;
15696 lastmatch = rest;
15700 if (lastmatch == NULL)
15701 rettv->vval.v_number = -1;
15702 else
15703 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
15707 * "strtrans()" function
15709 static void
15710 f_strtrans(argvars, rettv)
15711 typval_T *argvars;
15712 typval_T *rettv;
15714 rettv->v_type = VAR_STRING;
15715 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
15719 * "submatch()" function
15721 static void
15722 f_submatch(argvars, rettv)
15723 typval_T *argvars;
15724 typval_T *rettv;
15726 rettv->v_type = VAR_STRING;
15727 rettv->vval.v_string =
15728 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
15732 * "substitute()" function
15734 static void
15735 f_substitute(argvars, rettv)
15736 typval_T *argvars;
15737 typval_T *rettv;
15739 char_u patbuf[NUMBUFLEN];
15740 char_u subbuf[NUMBUFLEN];
15741 char_u flagsbuf[NUMBUFLEN];
15743 char_u *str = get_tv_string_chk(&argvars[0]);
15744 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
15745 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
15746 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
15748 rettv->v_type = VAR_STRING;
15749 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
15750 rettv->vval.v_string = NULL;
15751 else
15752 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
15756 * "synID(lnum, col, trans)" function
15758 /*ARGSUSED*/
15759 static void
15760 f_synID(argvars, rettv)
15761 typval_T *argvars;
15762 typval_T *rettv;
15764 int id = 0;
15765 #ifdef FEAT_SYN_HL
15766 long lnum;
15767 long col;
15768 int trans;
15769 int transerr = FALSE;
15771 lnum = get_tv_lnum(argvars); /* -1 on type error */
15772 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
15773 trans = get_tv_number_chk(&argvars[2], &transerr);
15775 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
15776 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
15777 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
15778 #endif
15780 rettv->vval.v_number = id;
15784 * "synIDattr(id, what [, mode])" function
15786 /*ARGSUSED*/
15787 static void
15788 f_synIDattr(argvars, rettv)
15789 typval_T *argvars;
15790 typval_T *rettv;
15792 char_u *p = NULL;
15793 #ifdef FEAT_SYN_HL
15794 int id;
15795 char_u *what;
15796 char_u *mode;
15797 char_u modebuf[NUMBUFLEN];
15798 int modec;
15800 id = get_tv_number(&argvars[0]);
15801 what = get_tv_string(&argvars[1]);
15802 if (argvars[2].v_type != VAR_UNKNOWN)
15804 mode = get_tv_string_buf(&argvars[2], modebuf);
15805 modec = TOLOWER_ASC(mode[0]);
15806 if (modec != 't' && modec != 'c'
15807 #ifdef FEAT_GUI
15808 && modec != 'g'
15809 #endif
15811 modec = 0; /* replace invalid with current */
15813 else
15815 #ifdef FEAT_GUI
15816 if (gui.in_use)
15817 modec = 'g';
15818 else
15819 #endif
15820 if (t_colors > 1)
15821 modec = 'c';
15822 else
15823 modec = 't';
15827 switch (TOLOWER_ASC(what[0]))
15829 case 'b':
15830 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
15831 p = highlight_color(id, what, modec);
15832 else /* bold */
15833 p = highlight_has_attr(id, HL_BOLD, modec);
15834 break;
15836 case 'f': /* fg[#] */
15837 p = highlight_color(id, what, modec);
15838 break;
15840 case 'i':
15841 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
15842 p = highlight_has_attr(id, HL_INVERSE, modec);
15843 else /* italic */
15844 p = highlight_has_attr(id, HL_ITALIC, modec);
15845 break;
15847 case 'n': /* name */
15848 p = get_highlight_name(NULL, id - 1);
15849 break;
15851 case 'r': /* reverse */
15852 p = highlight_has_attr(id, HL_INVERSE, modec);
15853 break;
15855 case 's': /* standout */
15856 p = highlight_has_attr(id, HL_STANDOUT, modec);
15857 break;
15859 case 'u':
15860 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
15861 /* underline */
15862 p = highlight_has_attr(id, HL_UNDERLINE, modec);
15863 else
15864 /* undercurl */
15865 p = highlight_has_attr(id, HL_UNDERCURL, modec);
15866 break;
15869 if (p != NULL)
15870 p = vim_strsave(p);
15871 #endif
15872 rettv->v_type = VAR_STRING;
15873 rettv->vval.v_string = p;
15877 * "synIDtrans(id)" function
15879 /*ARGSUSED*/
15880 static void
15881 f_synIDtrans(argvars, rettv)
15882 typval_T *argvars;
15883 typval_T *rettv;
15885 int id;
15887 #ifdef FEAT_SYN_HL
15888 id = get_tv_number(&argvars[0]);
15890 if (id > 0)
15891 id = syn_get_final_id(id);
15892 else
15893 #endif
15894 id = 0;
15896 rettv->vval.v_number = id;
15900 * "synstack(lnum, col)" function
15902 /*ARGSUSED*/
15903 static void
15904 f_synstack(argvars, rettv)
15905 typval_T *argvars;
15906 typval_T *rettv;
15908 #ifdef FEAT_SYN_HL
15909 long lnum;
15910 long col;
15911 int i;
15912 int id;
15913 #endif
15915 rettv->v_type = VAR_LIST;
15916 rettv->vval.v_list = NULL;
15918 #ifdef FEAT_SYN_HL
15919 lnum = get_tv_lnum(argvars); /* -1 on type error */
15920 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
15922 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
15923 && col >= 0 && col < (long)STRLEN(ml_get(lnum))
15924 && rettv_list_alloc(rettv) != FAIL)
15926 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
15927 for (i = 0; ; ++i)
15929 id = syn_get_stack_item(i);
15930 if (id < 0)
15931 break;
15932 if (list_append_number(rettv->vval.v_list, id) == FAIL)
15933 break;
15936 #endif
15940 * "system()" function
15942 static void
15943 f_system(argvars, rettv)
15944 typval_T *argvars;
15945 typval_T *rettv;
15947 char_u *res = NULL;
15948 char_u *p;
15949 char_u *infile = NULL;
15950 char_u buf[NUMBUFLEN];
15951 int err = FALSE;
15952 FILE *fd;
15954 if (check_restricted() || check_secure())
15955 goto done;
15957 if (argvars[1].v_type != VAR_UNKNOWN)
15960 * Write the string to a temp file, to be used for input of the shell
15961 * command.
15963 if ((infile = vim_tempname('i')) == NULL)
15965 EMSG(_(e_notmp));
15966 goto done;
15969 fd = mch_fopen((char *)infile, WRITEBIN);
15970 if (fd == NULL)
15972 EMSG2(_(e_notopen), infile);
15973 goto done;
15975 p = get_tv_string_buf_chk(&argvars[1], buf);
15976 if (p == NULL)
15978 fclose(fd);
15979 goto done; /* type error; errmsg already given */
15981 if (fwrite(p, STRLEN(p), 1, fd) != 1)
15982 err = TRUE;
15983 if (fclose(fd) != 0)
15984 err = TRUE;
15985 if (err)
15987 EMSG(_("E677: Error writing temp file"));
15988 goto done;
15992 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
15993 SHELL_SILENT | SHELL_COOKED);
15995 #ifdef USE_CR
15996 /* translate <CR> into <NL> */
15997 if (res != NULL)
15999 char_u *s;
16001 for (s = res; *s; ++s)
16003 if (*s == CAR)
16004 *s = NL;
16007 #else
16008 # ifdef USE_CRNL
16009 /* translate <CR><NL> into <NL> */
16010 if (res != NULL)
16012 char_u *s, *d;
16014 d = res;
16015 for (s = res; *s; ++s)
16017 if (s[0] == CAR && s[1] == NL)
16018 ++s;
16019 *d++ = *s;
16021 *d = NUL;
16023 # endif
16024 #endif
16026 done:
16027 if (infile != NULL)
16029 mch_remove(infile);
16030 vim_free(infile);
16032 rettv->v_type = VAR_STRING;
16033 rettv->vval.v_string = res;
16037 * "tabpagebuflist()" function
16039 /* ARGSUSED */
16040 static void
16041 f_tabpagebuflist(argvars, rettv)
16042 typval_T *argvars;
16043 typval_T *rettv;
16045 #ifndef FEAT_WINDOWS
16046 rettv->vval.v_number = 0;
16047 #else
16048 tabpage_T *tp;
16049 win_T *wp = NULL;
16051 if (argvars[0].v_type == VAR_UNKNOWN)
16052 wp = firstwin;
16053 else
16055 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16056 if (tp != NULL)
16057 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16059 if (wp == NULL)
16060 rettv->vval.v_number = 0;
16061 else
16063 if (rettv_list_alloc(rettv) == FAIL)
16064 rettv->vval.v_number = 0;
16065 else
16067 for (; wp != NULL; wp = wp->w_next)
16068 if (list_append_number(rettv->vval.v_list,
16069 wp->w_buffer->b_fnum) == FAIL)
16070 break;
16073 #endif
16078 * "tabpagenr()" function
16080 /* ARGSUSED */
16081 static void
16082 f_tabpagenr(argvars, rettv)
16083 typval_T *argvars;
16084 typval_T *rettv;
16086 int nr = 1;
16087 #ifdef FEAT_WINDOWS
16088 char_u *arg;
16090 if (argvars[0].v_type != VAR_UNKNOWN)
16092 arg = get_tv_string_chk(&argvars[0]);
16093 nr = 0;
16094 if (arg != NULL)
16096 if (STRCMP(arg, "$") == 0)
16097 nr = tabpage_index(NULL) - 1;
16098 else
16099 EMSG2(_(e_invexpr2), arg);
16102 else
16103 nr = tabpage_index(curtab);
16104 #endif
16105 rettv->vval.v_number = nr;
16109 #ifdef FEAT_WINDOWS
16110 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
16113 * Common code for tabpagewinnr() and winnr().
16115 static int
16116 get_winnr(tp, argvar)
16117 tabpage_T *tp;
16118 typval_T *argvar;
16120 win_T *twin;
16121 int nr = 1;
16122 win_T *wp;
16123 char_u *arg;
16125 twin = (tp == curtab) ? curwin : tp->tp_curwin;
16126 if (argvar->v_type != VAR_UNKNOWN)
16128 arg = get_tv_string_chk(argvar);
16129 if (arg == NULL)
16130 nr = 0; /* type error; errmsg already given */
16131 else if (STRCMP(arg, "$") == 0)
16132 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
16133 else if (STRCMP(arg, "#") == 0)
16135 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
16136 if (twin == NULL)
16137 nr = 0;
16139 else
16141 EMSG2(_(e_invexpr2), arg);
16142 nr = 0;
16146 if (nr > 0)
16147 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16148 wp != twin; wp = wp->w_next)
16150 if (wp == NULL)
16152 /* didn't find it in this tabpage */
16153 nr = 0;
16154 break;
16156 ++nr;
16158 return nr;
16160 #endif
16163 * "tabpagewinnr()" function
16165 /* ARGSUSED */
16166 static void
16167 f_tabpagewinnr(argvars, rettv)
16168 typval_T *argvars;
16169 typval_T *rettv;
16171 int nr = 1;
16172 #ifdef FEAT_WINDOWS
16173 tabpage_T *tp;
16175 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16176 if (tp == NULL)
16177 nr = 0;
16178 else
16179 nr = get_winnr(tp, &argvars[1]);
16180 #endif
16181 rettv->vval.v_number = nr;
16186 * "tagfiles()" function
16188 /*ARGSUSED*/
16189 static void
16190 f_tagfiles(argvars, rettv)
16191 typval_T *argvars;
16192 typval_T *rettv;
16194 char_u fname[MAXPATHL + 1];
16195 tagname_T tn;
16196 int first;
16198 if (rettv_list_alloc(rettv) == FAIL)
16200 rettv->vval.v_number = 0;
16201 return;
16204 for (first = TRUE; ; first = FALSE)
16205 if (get_tagfname(&tn, first, fname) == FAIL
16206 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
16207 break;
16208 tagname_free(&tn);
16212 * "taglist()" function
16214 static void
16215 f_taglist(argvars, rettv)
16216 typval_T *argvars;
16217 typval_T *rettv;
16219 char_u *tag_pattern;
16221 tag_pattern = get_tv_string(&argvars[0]);
16223 rettv->vval.v_number = FALSE;
16224 if (*tag_pattern == NUL)
16225 return;
16227 if (rettv_list_alloc(rettv) == OK)
16228 (void)get_tags(rettv->vval.v_list, tag_pattern);
16232 * "tempname()" function
16234 /*ARGSUSED*/
16235 static void
16236 f_tempname(argvars, rettv)
16237 typval_T *argvars;
16238 typval_T *rettv;
16240 static int x = 'A';
16242 rettv->v_type = VAR_STRING;
16243 rettv->vval.v_string = vim_tempname(x);
16245 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
16246 * names. Skip 'I' and 'O', they are used for shell redirection. */
16249 if (x == 'Z')
16250 x = '0';
16251 else if (x == '9')
16252 x = 'A';
16253 else
16255 #ifdef EBCDIC
16256 if (x == 'I')
16257 x = 'J';
16258 else if (x == 'R')
16259 x = 'S';
16260 else
16261 #endif
16262 ++x;
16264 } while (x == 'I' || x == 'O');
16268 * "test(list)" function: Just checking the walls...
16270 /*ARGSUSED*/
16271 static void
16272 f_test(argvars, rettv)
16273 typval_T *argvars;
16274 typval_T *rettv;
16276 /* Used for unit testing. Change the code below to your liking. */
16277 #if 0
16278 listitem_T *li;
16279 list_T *l;
16280 char_u *bad, *good;
16282 if (argvars[0].v_type != VAR_LIST)
16283 return;
16284 l = argvars[0].vval.v_list;
16285 if (l == NULL)
16286 return;
16287 li = l->lv_first;
16288 if (li == NULL)
16289 return;
16290 bad = get_tv_string(&li->li_tv);
16291 li = li->li_next;
16292 if (li == NULL)
16293 return;
16294 good = get_tv_string(&li->li_tv);
16295 rettv->vval.v_number = test_edit_score(bad, good);
16296 #endif
16300 * "tolower(string)" function
16302 static void
16303 f_tolower(argvars, rettv)
16304 typval_T *argvars;
16305 typval_T *rettv;
16307 char_u *p;
16309 p = vim_strsave(get_tv_string(&argvars[0]));
16310 rettv->v_type = VAR_STRING;
16311 rettv->vval.v_string = p;
16313 if (p != NULL)
16314 while (*p != NUL)
16316 #ifdef FEAT_MBYTE
16317 int l;
16319 if (enc_utf8)
16321 int c, lc;
16323 c = utf_ptr2char(p);
16324 lc = utf_tolower(c);
16325 l = utf_ptr2len(p);
16326 /* TODO: reallocate string when byte count changes. */
16327 if (utf_char2len(lc) == l)
16328 utf_char2bytes(lc, p);
16329 p += l;
16331 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
16332 p += l; /* skip multi-byte character */
16333 else
16334 #endif
16336 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
16337 ++p;
16343 * "toupper(string)" function
16345 static void
16346 f_toupper(argvars, rettv)
16347 typval_T *argvars;
16348 typval_T *rettv;
16350 rettv->v_type = VAR_STRING;
16351 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
16355 * "tr(string, fromstr, tostr)" function
16357 static void
16358 f_tr(argvars, rettv)
16359 typval_T *argvars;
16360 typval_T *rettv;
16362 char_u *instr;
16363 char_u *fromstr;
16364 char_u *tostr;
16365 char_u *p;
16366 #ifdef FEAT_MBYTE
16367 int inlen;
16368 int fromlen;
16369 int tolen;
16370 int idx;
16371 char_u *cpstr;
16372 int cplen;
16373 int first = TRUE;
16374 #endif
16375 char_u buf[NUMBUFLEN];
16376 char_u buf2[NUMBUFLEN];
16377 garray_T ga;
16379 instr = get_tv_string(&argvars[0]);
16380 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
16381 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
16383 /* Default return value: empty string. */
16384 rettv->v_type = VAR_STRING;
16385 rettv->vval.v_string = NULL;
16386 if (fromstr == NULL || tostr == NULL)
16387 return; /* type error; errmsg already given */
16388 ga_init2(&ga, (int)sizeof(char), 80);
16390 #ifdef FEAT_MBYTE
16391 if (!has_mbyte)
16392 #endif
16393 /* not multi-byte: fromstr and tostr must be the same length */
16394 if (STRLEN(fromstr) != STRLEN(tostr))
16396 #ifdef FEAT_MBYTE
16397 error:
16398 #endif
16399 EMSG2(_(e_invarg2), fromstr);
16400 ga_clear(&ga);
16401 return;
16404 /* fromstr and tostr have to contain the same number of chars */
16405 while (*instr != NUL)
16407 #ifdef FEAT_MBYTE
16408 if (has_mbyte)
16410 inlen = (*mb_ptr2len)(instr);
16411 cpstr = instr;
16412 cplen = inlen;
16413 idx = 0;
16414 for (p = fromstr; *p != NUL; p += fromlen)
16416 fromlen = (*mb_ptr2len)(p);
16417 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
16419 for (p = tostr; *p != NUL; p += tolen)
16421 tolen = (*mb_ptr2len)(p);
16422 if (idx-- == 0)
16424 cplen = tolen;
16425 cpstr = p;
16426 break;
16429 if (*p == NUL) /* tostr is shorter than fromstr */
16430 goto error;
16431 break;
16433 ++idx;
16436 if (first && cpstr == instr)
16438 /* Check that fromstr and tostr have the same number of
16439 * (multi-byte) characters. Done only once when a character
16440 * of instr doesn't appear in fromstr. */
16441 first = FALSE;
16442 for (p = tostr; *p != NUL; p += tolen)
16444 tolen = (*mb_ptr2len)(p);
16445 --idx;
16447 if (idx != 0)
16448 goto error;
16451 ga_grow(&ga, cplen);
16452 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
16453 ga.ga_len += cplen;
16455 instr += inlen;
16457 else
16458 #endif
16460 /* When not using multi-byte chars we can do it faster. */
16461 p = vim_strchr(fromstr, *instr);
16462 if (p != NULL)
16463 ga_append(&ga, tostr[p - fromstr]);
16464 else
16465 ga_append(&ga, *instr);
16466 ++instr;
16470 /* add a terminating NUL */
16471 ga_grow(&ga, 1);
16472 ga_append(&ga, NUL);
16474 rettv->vval.v_string = ga.ga_data;
16478 * "type(expr)" function
16480 static void
16481 f_type(argvars, rettv)
16482 typval_T *argvars;
16483 typval_T *rettv;
16485 int n;
16487 switch (argvars[0].v_type)
16489 case VAR_NUMBER: n = 0; break;
16490 case VAR_STRING: n = 1; break;
16491 case VAR_FUNC: n = 2; break;
16492 case VAR_LIST: n = 3; break;
16493 case VAR_DICT: n = 4; break;
16494 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
16496 rettv->vval.v_number = n;
16500 * "values(dict)" function
16502 static void
16503 f_values(argvars, rettv)
16504 typval_T *argvars;
16505 typval_T *rettv;
16507 dict_list(argvars, rettv, 1);
16511 * "virtcol(string)" function
16513 static void
16514 f_virtcol(argvars, rettv)
16515 typval_T *argvars;
16516 typval_T *rettv;
16518 colnr_T vcol = 0;
16519 pos_T *fp;
16520 int fnum = curbuf->b_fnum;
16522 fp = var2fpos(&argvars[0], FALSE, &fnum);
16523 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
16524 && fnum == curbuf->b_fnum)
16526 getvvcol(curwin, fp, NULL, NULL, &vcol);
16527 ++vcol;
16530 rettv->vval.v_number = vcol;
16534 * "visualmode()" function
16536 /*ARGSUSED*/
16537 static void
16538 f_visualmode(argvars, rettv)
16539 typval_T *argvars;
16540 typval_T *rettv;
16542 #ifdef FEAT_VISUAL
16543 char_u str[2];
16545 rettv->v_type = VAR_STRING;
16546 str[0] = curbuf->b_visual_mode_eval;
16547 str[1] = NUL;
16548 rettv->vval.v_string = vim_strsave(str);
16550 /* A non-zero number or non-empty string argument: reset mode. */
16551 if ((argvars[0].v_type == VAR_NUMBER
16552 && argvars[0].vval.v_number != 0)
16553 || (argvars[0].v_type == VAR_STRING
16554 && *get_tv_string(&argvars[0]) != NUL))
16555 curbuf->b_visual_mode_eval = NUL;
16556 #else
16557 rettv->vval.v_number = 0; /* return anything, it won't work anyway */
16558 #endif
16562 * "winbufnr(nr)" function
16564 static void
16565 f_winbufnr(argvars, rettv)
16566 typval_T *argvars;
16567 typval_T *rettv;
16569 win_T *wp;
16571 wp = find_win_by_nr(&argvars[0], NULL);
16572 if (wp == NULL)
16573 rettv->vval.v_number = -1;
16574 else
16575 rettv->vval.v_number = wp->w_buffer->b_fnum;
16579 * "wincol()" function
16581 /*ARGSUSED*/
16582 static void
16583 f_wincol(argvars, rettv)
16584 typval_T *argvars;
16585 typval_T *rettv;
16587 validate_cursor();
16588 rettv->vval.v_number = curwin->w_wcol + 1;
16592 * "winheight(nr)" function
16594 static void
16595 f_winheight(argvars, rettv)
16596 typval_T *argvars;
16597 typval_T *rettv;
16599 win_T *wp;
16601 wp = find_win_by_nr(&argvars[0], NULL);
16602 if (wp == NULL)
16603 rettv->vval.v_number = -1;
16604 else
16605 rettv->vval.v_number = wp->w_height;
16609 * "winline()" function
16611 /*ARGSUSED*/
16612 static void
16613 f_winline(argvars, rettv)
16614 typval_T *argvars;
16615 typval_T *rettv;
16617 validate_cursor();
16618 rettv->vval.v_number = curwin->w_wrow + 1;
16622 * "winnr()" function
16624 /* ARGSUSED */
16625 static void
16626 f_winnr(argvars, rettv)
16627 typval_T *argvars;
16628 typval_T *rettv;
16630 int nr = 1;
16632 #ifdef FEAT_WINDOWS
16633 nr = get_winnr(curtab, &argvars[0]);
16634 #endif
16635 rettv->vval.v_number = nr;
16639 * "winrestcmd()" function
16641 /* ARGSUSED */
16642 static void
16643 f_winrestcmd(argvars, rettv)
16644 typval_T *argvars;
16645 typval_T *rettv;
16647 #ifdef FEAT_WINDOWS
16648 win_T *wp;
16649 int winnr = 1;
16650 garray_T ga;
16651 char_u buf[50];
16653 ga_init2(&ga, (int)sizeof(char), 70);
16654 for (wp = firstwin; wp != NULL; wp = wp->w_next)
16656 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
16657 ga_concat(&ga, buf);
16658 # ifdef FEAT_VERTSPLIT
16659 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
16660 ga_concat(&ga, buf);
16661 # endif
16662 ++winnr;
16664 ga_append(&ga, NUL);
16666 rettv->vval.v_string = ga.ga_data;
16667 #else
16668 rettv->vval.v_string = NULL;
16669 #endif
16670 rettv->v_type = VAR_STRING;
16674 * "winrestview()" function
16676 /* ARGSUSED */
16677 static void
16678 f_winrestview(argvars, rettv)
16679 typval_T *argvars;
16680 typval_T *rettv;
16682 dict_T *dict;
16684 if (argvars[0].v_type != VAR_DICT
16685 || (dict = argvars[0].vval.v_dict) == NULL)
16686 EMSG(_(e_invarg));
16687 else
16689 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
16690 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
16691 #ifdef FEAT_VIRTUALEDIT
16692 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
16693 #endif
16694 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
16695 curwin->w_set_curswant = FALSE;
16697 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
16698 #ifdef FEAT_DIFF
16699 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
16700 #endif
16701 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
16702 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
16704 check_cursor();
16705 changed_cline_bef_curs();
16706 invalidate_botline();
16707 redraw_later(VALID);
16709 if (curwin->w_topline == 0)
16710 curwin->w_topline = 1;
16711 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
16712 curwin->w_topline = curbuf->b_ml.ml_line_count;
16713 #ifdef FEAT_DIFF
16714 check_topfill(curwin, TRUE);
16715 #endif
16720 * "winsaveview()" function
16722 /* ARGSUSED */
16723 static void
16724 f_winsaveview(argvars, rettv)
16725 typval_T *argvars;
16726 typval_T *rettv;
16728 dict_T *dict;
16730 dict = dict_alloc();
16731 if (dict == NULL)
16732 return;
16733 rettv->v_type = VAR_DICT;
16734 rettv->vval.v_dict = dict;
16735 ++dict->dv_refcount;
16737 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
16738 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
16739 #ifdef FEAT_VIRTUALEDIT
16740 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
16741 #endif
16742 update_curswant();
16743 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
16745 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
16746 #ifdef FEAT_DIFF
16747 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
16748 #endif
16749 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
16750 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
16754 * "winwidth(nr)" function
16756 static void
16757 f_winwidth(argvars, rettv)
16758 typval_T *argvars;
16759 typval_T *rettv;
16761 win_T *wp;
16763 wp = find_win_by_nr(&argvars[0], NULL);
16764 if (wp == NULL)
16765 rettv->vval.v_number = -1;
16766 else
16767 #ifdef FEAT_VERTSPLIT
16768 rettv->vval.v_number = wp->w_width;
16769 #else
16770 rettv->vval.v_number = Columns;
16771 #endif
16775 * "writefile()" function
16777 static void
16778 f_writefile(argvars, rettv)
16779 typval_T *argvars;
16780 typval_T *rettv;
16782 int binary = FALSE;
16783 char_u *fname;
16784 FILE *fd;
16785 listitem_T *li;
16786 char_u *s;
16787 int ret = 0;
16788 int c;
16790 if (check_restricted() || check_secure())
16791 return;
16793 if (argvars[0].v_type != VAR_LIST)
16795 EMSG2(_(e_listarg), "writefile()");
16796 return;
16798 if (argvars[0].vval.v_list == NULL)
16799 return;
16801 if (argvars[2].v_type != VAR_UNKNOWN
16802 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
16803 binary = TRUE;
16805 /* Always open the file in binary mode, library functions have a mind of
16806 * their own about CR-LF conversion. */
16807 fname = get_tv_string(&argvars[1]);
16808 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
16810 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
16811 ret = -1;
16813 else
16815 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
16816 li = li->li_next)
16818 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
16820 if (*s == '\n')
16821 c = putc(NUL, fd);
16822 else
16823 c = putc(*s, fd);
16824 if (c == EOF)
16826 ret = -1;
16827 break;
16830 if (!binary || li->li_next != NULL)
16831 if (putc('\n', fd) == EOF)
16833 ret = -1;
16834 break;
16836 if (ret < 0)
16838 EMSG(_(e_write));
16839 break;
16842 fclose(fd);
16845 rettv->vval.v_number = ret;
16849 * Translate a String variable into a position.
16850 * Returns NULL when there is an error.
16852 static pos_T *
16853 var2fpos(varp, dollar_lnum, fnum)
16854 typval_T *varp;
16855 int dollar_lnum; /* TRUE when $ is last line */
16856 int *fnum; /* set to fnum for '0, 'A, etc. */
16858 char_u *name;
16859 static pos_T pos;
16860 pos_T *pp;
16862 /* Argument can be [lnum, col, coladd]. */
16863 if (varp->v_type == VAR_LIST)
16865 list_T *l;
16866 int len;
16867 int error = FALSE;
16868 listitem_T *li;
16870 l = varp->vval.v_list;
16871 if (l == NULL)
16872 return NULL;
16874 /* Get the line number */
16875 pos.lnum = list_find_nr(l, 0L, &error);
16876 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
16877 return NULL; /* invalid line number */
16879 /* Get the column number */
16880 pos.col = list_find_nr(l, 1L, &error);
16881 if (error)
16882 return NULL;
16883 len = (long)STRLEN(ml_get(pos.lnum));
16885 /* We accept "$" for the column number: last column. */
16886 li = list_find(l, 1L);
16887 if (li != NULL && li->li_tv.v_type == VAR_STRING
16888 && li->li_tv.vval.v_string != NULL
16889 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
16890 pos.col = len + 1;
16892 /* Accept a position up to the NUL after the line. */
16893 if (pos.col == 0 || (int)pos.col > len + 1)
16894 return NULL; /* invalid column number */
16895 --pos.col;
16897 #ifdef FEAT_VIRTUALEDIT
16898 /* Get the virtual offset. Defaults to zero. */
16899 pos.coladd = list_find_nr(l, 2L, &error);
16900 if (error)
16901 pos.coladd = 0;
16902 #endif
16904 return &pos;
16907 name = get_tv_string_chk(varp);
16908 if (name == NULL)
16909 return NULL;
16910 if (name[0] == '.') /* cursor */
16911 return &curwin->w_cursor;
16912 if (name[0] == '\'') /* mark */
16914 pp = getmark_fnum(name[1], FALSE, fnum);
16915 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
16916 return NULL;
16917 return pp;
16920 #ifdef FEAT_VIRTUALEDIT
16921 pos.coladd = 0;
16922 #endif
16924 if (name[0] == 'w' && dollar_lnum)
16926 pos.col = 0;
16927 if (name[1] == '0') /* "w0": first visible line */
16929 update_topline();
16930 pos.lnum = curwin->w_topline;
16931 return &pos;
16933 else if (name[1] == '$') /* "w$": last visible line */
16935 validate_botline();
16936 pos.lnum = curwin->w_botline - 1;
16937 return &pos;
16940 else if (name[0] == '$') /* last column or line */
16942 if (dollar_lnum)
16944 pos.lnum = curbuf->b_ml.ml_line_count;
16945 pos.col = 0;
16947 else
16949 pos.lnum = curwin->w_cursor.lnum;
16950 pos.col = (colnr_T)STRLEN(ml_get_curline());
16952 return &pos;
16954 return NULL;
16958 * Convert list in "arg" into a position and optional file number.
16959 * When "fnump" is NULL there is no file number, only 3 items.
16960 * Note that the column is passed on as-is, the caller may want to decrement
16961 * it to use 1 for the first column.
16962 * Return FAIL when conversion is not possible, doesn't check the position for
16963 * validity.
16965 static int
16966 list2fpos(arg, posp, fnump)
16967 typval_T *arg;
16968 pos_T *posp;
16969 int *fnump;
16971 list_T *l = arg->vval.v_list;
16972 long i = 0;
16973 long n;
16975 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
16976 * when "fnump" isn't NULL and "coladd" is optional. */
16977 if (arg->v_type != VAR_LIST
16978 || l == NULL
16979 || l->lv_len < (fnump == NULL ? 2 : 3)
16980 || l->lv_len > (fnump == NULL ? 3 : 4))
16981 return FAIL;
16983 if (fnump != NULL)
16985 n = list_find_nr(l, i++, NULL); /* fnum */
16986 if (n < 0)
16987 return FAIL;
16988 if (n == 0)
16989 n = curbuf->b_fnum; /* current buffer */
16990 *fnump = n;
16993 n = list_find_nr(l, i++, NULL); /* lnum */
16994 if (n < 0)
16995 return FAIL;
16996 posp->lnum = n;
16998 n = list_find_nr(l, i++, NULL); /* col */
16999 if (n < 0)
17000 return FAIL;
17001 posp->col = n;
17003 #ifdef FEAT_VIRTUALEDIT
17004 n = list_find_nr(l, i, NULL);
17005 if (n < 0)
17006 posp->coladd = 0;
17007 else
17008 posp->coladd = n;
17009 #endif
17011 return OK;
17015 * Get the length of an environment variable name.
17016 * Advance "arg" to the first character after the name.
17017 * Return 0 for error.
17019 static int
17020 get_env_len(arg)
17021 char_u **arg;
17023 char_u *p;
17024 int len;
17026 for (p = *arg; vim_isIDc(*p); ++p)
17028 if (p == *arg) /* no name found */
17029 return 0;
17031 len = (int)(p - *arg);
17032 *arg = p;
17033 return len;
17037 * Get the length of the name of a function or internal variable.
17038 * "arg" is advanced to the first non-white character after the name.
17039 * Return 0 if something is wrong.
17041 static int
17042 get_id_len(arg)
17043 char_u **arg;
17045 char_u *p;
17046 int len;
17048 /* Find the end of the name. */
17049 for (p = *arg; eval_isnamec(*p); ++p)
17051 if (p == *arg) /* no name found */
17052 return 0;
17054 len = (int)(p - *arg);
17055 *arg = skipwhite(p);
17057 return len;
17061 * Get the length of the name of a variable or function.
17062 * Only the name is recognized, does not handle ".key" or "[idx]".
17063 * "arg" is advanced to the first non-white character after the name.
17064 * Return -1 if curly braces expansion failed.
17065 * Return 0 if something else is wrong.
17066 * If the name contains 'magic' {}'s, expand them and return the
17067 * expanded name in an allocated string via 'alias' - caller must free.
17069 static int
17070 get_name_len(arg, alias, evaluate, verbose)
17071 char_u **arg;
17072 char_u **alias;
17073 int evaluate;
17074 int verbose;
17076 int len;
17077 char_u *p;
17078 char_u *expr_start;
17079 char_u *expr_end;
17081 *alias = NULL; /* default to no alias */
17083 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
17084 && (*arg)[2] == (int)KE_SNR)
17086 /* hard coded <SNR>, already translated */
17087 *arg += 3;
17088 return get_id_len(arg) + 3;
17090 len = eval_fname_script(*arg);
17091 if (len > 0)
17093 /* literal "<SID>", "s:" or "<SNR>" */
17094 *arg += len;
17098 * Find the end of the name; check for {} construction.
17100 p = find_name_end(*arg, &expr_start, &expr_end,
17101 len > 0 ? 0 : FNE_CHECK_START);
17102 if (expr_start != NULL)
17104 char_u *temp_string;
17106 if (!evaluate)
17108 len += (int)(p - *arg);
17109 *arg = skipwhite(p);
17110 return len;
17114 * Include any <SID> etc in the expanded string:
17115 * Thus the -len here.
17117 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
17118 if (temp_string == NULL)
17119 return -1;
17120 *alias = temp_string;
17121 *arg = skipwhite(p);
17122 return (int)STRLEN(temp_string);
17125 len += get_id_len(arg);
17126 if (len == 0 && verbose)
17127 EMSG2(_(e_invexpr2), *arg);
17129 return len;
17133 * Find the end of a variable or function name, taking care of magic braces.
17134 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
17135 * start and end of the first magic braces item.
17136 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
17137 * Return a pointer to just after the name. Equal to "arg" if there is no
17138 * valid name.
17140 static char_u *
17141 find_name_end(arg, expr_start, expr_end, flags)
17142 char_u *arg;
17143 char_u **expr_start;
17144 char_u **expr_end;
17145 int flags;
17147 int mb_nest = 0;
17148 int br_nest = 0;
17149 char_u *p;
17151 if (expr_start != NULL)
17153 *expr_start = NULL;
17154 *expr_end = NULL;
17157 /* Quick check for valid starting character. */
17158 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
17159 return arg;
17161 for (p = arg; *p != NUL
17162 && (eval_isnamec(*p)
17163 || *p == '{'
17164 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
17165 || mb_nest != 0
17166 || br_nest != 0); mb_ptr_adv(p))
17168 if (*p == '\'')
17170 /* skip over 'string' to avoid counting [ and ] inside it. */
17171 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
17173 if (*p == NUL)
17174 break;
17176 else if (*p == '"')
17178 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
17179 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
17180 if (*p == '\\' && p[1] != NUL)
17181 ++p;
17182 if (*p == NUL)
17183 break;
17186 if (mb_nest == 0)
17188 if (*p == '[')
17189 ++br_nest;
17190 else if (*p == ']')
17191 --br_nest;
17194 if (br_nest == 0)
17196 if (*p == '{')
17198 mb_nest++;
17199 if (expr_start != NULL && *expr_start == NULL)
17200 *expr_start = p;
17202 else if (*p == '}')
17204 mb_nest--;
17205 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
17206 *expr_end = p;
17211 return p;
17215 * Expands out the 'magic' {}'s in a variable/function name.
17216 * Note that this can call itself recursively, to deal with
17217 * constructs like foo{bar}{baz}{bam}
17218 * The four pointer arguments point to "foo{expre}ss{ion}bar"
17219 * "in_start" ^
17220 * "expr_start" ^
17221 * "expr_end" ^
17222 * "in_end" ^
17224 * Returns a new allocated string, which the caller must free.
17225 * Returns NULL for failure.
17227 static char_u *
17228 make_expanded_name(in_start, expr_start, expr_end, in_end)
17229 char_u *in_start;
17230 char_u *expr_start;
17231 char_u *expr_end;
17232 char_u *in_end;
17234 char_u c1;
17235 char_u *retval = NULL;
17236 char_u *temp_result;
17237 char_u *nextcmd = NULL;
17239 if (expr_end == NULL || in_end == NULL)
17240 return NULL;
17241 *expr_start = NUL;
17242 *expr_end = NUL;
17243 c1 = *in_end;
17244 *in_end = NUL;
17246 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
17247 if (temp_result != NULL && nextcmd == NULL)
17249 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
17250 + (in_end - expr_end) + 1));
17251 if (retval != NULL)
17253 STRCPY(retval, in_start);
17254 STRCAT(retval, temp_result);
17255 STRCAT(retval, expr_end + 1);
17258 vim_free(temp_result);
17260 *in_end = c1; /* put char back for error messages */
17261 *expr_start = '{';
17262 *expr_end = '}';
17264 if (retval != NULL)
17266 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
17267 if (expr_start != NULL)
17269 /* Further expansion! */
17270 temp_result = make_expanded_name(retval, expr_start,
17271 expr_end, temp_result);
17272 vim_free(retval);
17273 retval = temp_result;
17277 return retval;
17281 * Return TRUE if character "c" can be used in a variable or function name.
17282 * Does not include '{' or '}' for magic braces.
17284 static int
17285 eval_isnamec(c)
17286 int c;
17288 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
17292 * Return TRUE if character "c" can be used as the first character in a
17293 * variable or function name (excluding '{' and '}').
17295 static int
17296 eval_isnamec1(c)
17297 int c;
17299 return (ASCII_ISALPHA(c) || c == '_');
17303 * Set number v: variable to "val".
17305 void
17306 set_vim_var_nr(idx, val)
17307 int idx;
17308 long val;
17310 vimvars[idx].vv_nr = val;
17314 * Get number v: variable value.
17316 long
17317 get_vim_var_nr(idx)
17318 int idx;
17320 return vimvars[idx].vv_nr;
17323 #if defined(FEAT_AUTOCMD) || defined(PROTO)
17325 * Get string v: variable value. Uses a static buffer, can only be used once.
17327 char_u *
17328 get_vim_var_str(idx)
17329 int idx;
17331 return get_tv_string(&vimvars[idx].vv_tv);
17333 #endif
17336 * Set v:count, v:count1 and v:prevcount.
17338 void
17339 set_vcount(count, count1)
17340 long count;
17341 long count1;
17343 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
17344 vimvars[VV_COUNT].vv_nr = count;
17345 vimvars[VV_COUNT1].vv_nr = count1;
17349 * Set string v: variable to a copy of "val".
17351 void
17352 set_vim_var_string(idx, val, len)
17353 int idx;
17354 char_u *val;
17355 int len; /* length of "val" to use or -1 (whole string) */
17357 /* Need to do this (at least) once, since we can't initialize a union.
17358 * Will always be invoked when "v:progname" is set. */
17359 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
17361 vim_free(vimvars[idx].vv_str);
17362 if (val == NULL)
17363 vimvars[idx].vv_str = NULL;
17364 else if (len == -1)
17365 vimvars[idx].vv_str = vim_strsave(val);
17366 else
17367 vimvars[idx].vv_str = vim_strnsave(val, len);
17371 * Set v:register if needed.
17373 void
17374 set_reg_var(c)
17375 int c;
17377 char_u regname;
17379 if (c == 0 || c == ' ')
17380 regname = '"';
17381 else
17382 regname = c;
17383 /* Avoid free/alloc when the value is already right. */
17384 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
17385 set_vim_var_string(VV_REG, &regname, 1);
17389 * Get or set v:exception. If "oldval" == NULL, return the current value.
17390 * Otherwise, restore the value to "oldval" and return NULL.
17391 * Must always be called in pairs to save and restore v:exception! Does not
17392 * take care of memory allocations.
17394 char_u *
17395 v_exception(oldval)
17396 char_u *oldval;
17398 if (oldval == NULL)
17399 return vimvars[VV_EXCEPTION].vv_str;
17401 vimvars[VV_EXCEPTION].vv_str = oldval;
17402 return NULL;
17406 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
17407 * Otherwise, restore the value to "oldval" and return NULL.
17408 * Must always be called in pairs to save and restore v:throwpoint! Does not
17409 * take care of memory allocations.
17411 char_u *
17412 v_throwpoint(oldval)
17413 char_u *oldval;
17415 if (oldval == NULL)
17416 return vimvars[VV_THROWPOINT].vv_str;
17418 vimvars[VV_THROWPOINT].vv_str = oldval;
17419 return NULL;
17422 #if defined(FEAT_AUTOCMD) || defined(PROTO)
17424 * Set v:cmdarg.
17425 * If "eap" != NULL, use "eap" to generate the value and return the old value.
17426 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
17427 * Must always be called in pairs!
17429 char_u *
17430 set_cmdarg(eap, oldarg)
17431 exarg_T *eap;
17432 char_u *oldarg;
17434 char_u *oldval;
17435 char_u *newval;
17436 unsigned len;
17438 oldval = vimvars[VV_CMDARG].vv_str;
17439 if (eap == NULL)
17441 vim_free(oldval);
17442 vimvars[VV_CMDARG].vv_str = oldarg;
17443 return NULL;
17446 if (eap->force_bin == FORCE_BIN)
17447 len = 6;
17448 else if (eap->force_bin == FORCE_NOBIN)
17449 len = 8;
17450 else
17451 len = 0;
17453 if (eap->read_edit)
17454 len += 7;
17456 if (eap->force_ff != 0)
17457 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
17458 # ifdef FEAT_MBYTE
17459 if (eap->force_enc != 0)
17460 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
17461 if (eap->bad_char != 0)
17462 len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
17463 # endif
17465 newval = alloc(len + 1);
17466 if (newval == NULL)
17467 return NULL;
17469 if (eap->force_bin == FORCE_BIN)
17470 sprintf((char *)newval, " ++bin");
17471 else if (eap->force_bin == FORCE_NOBIN)
17472 sprintf((char *)newval, " ++nobin");
17473 else
17474 *newval = NUL;
17476 if (eap->read_edit)
17477 STRCAT(newval, " ++edit");
17479 if (eap->force_ff != 0)
17480 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
17481 eap->cmd + eap->force_ff);
17482 # ifdef FEAT_MBYTE
17483 if (eap->force_enc != 0)
17484 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
17485 eap->cmd + eap->force_enc);
17486 if (eap->bad_char != 0)
17487 sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
17488 eap->cmd + eap->bad_char);
17489 # endif
17490 vimvars[VV_CMDARG].vv_str = newval;
17491 return oldval;
17493 #endif
17496 * Get the value of internal variable "name".
17497 * Return OK or FAIL.
17499 static int
17500 get_var_tv(name, len, rettv, verbose)
17501 char_u *name;
17502 int len; /* length of "name" */
17503 typval_T *rettv; /* NULL when only checking existence */
17504 int verbose; /* may give error message */
17506 int ret = OK;
17507 typval_T *tv = NULL;
17508 typval_T atv;
17509 dictitem_T *v;
17510 int cc;
17512 /* truncate the name, so that we can use strcmp() */
17513 cc = name[len];
17514 name[len] = NUL;
17517 * Check for "b:changedtick".
17519 if (STRCMP(name, "b:changedtick") == 0)
17521 atv.v_type = VAR_NUMBER;
17522 atv.vval.v_number = curbuf->b_changedtick;
17523 tv = &atv;
17527 * Check for user-defined variables.
17529 else
17531 v = find_var(name, NULL);
17532 if (v != NULL)
17533 tv = &v->di_tv;
17536 if (tv == NULL)
17538 if (rettv != NULL && verbose)
17539 EMSG2(_(e_undefvar), name);
17540 ret = FAIL;
17542 else if (rettv != NULL)
17543 copy_tv(tv, rettv);
17545 name[len] = cc;
17547 return ret;
17551 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
17552 * Also handle function call with Funcref variable: func(expr)
17553 * Can all be combined: dict.func(expr)[idx]['func'](expr)
17555 static int
17556 handle_subscript(arg, rettv, evaluate, verbose)
17557 char_u **arg;
17558 typval_T *rettv;
17559 int evaluate; /* do more than finding the end */
17560 int verbose; /* give error messages */
17562 int ret = OK;
17563 dict_T *selfdict = NULL;
17564 char_u *s;
17565 int len;
17566 typval_T functv;
17568 while (ret == OK
17569 && (**arg == '['
17570 || (**arg == '.' && rettv->v_type == VAR_DICT)
17571 || (**arg == '(' && rettv->v_type == VAR_FUNC))
17572 && !vim_iswhite(*(*arg - 1)))
17574 if (**arg == '(')
17576 /* need to copy the funcref so that we can clear rettv */
17577 functv = *rettv;
17578 rettv->v_type = VAR_UNKNOWN;
17580 /* Invoke the function. Recursive! */
17581 s = functv.vval.v_string;
17582 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
17583 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
17584 &len, evaluate, selfdict);
17586 /* Clear the funcref afterwards, so that deleting it while
17587 * evaluating the arguments is possible (see test55). */
17588 clear_tv(&functv);
17590 /* Stop the expression evaluation when immediately aborting on
17591 * error, or when an interrupt occurred or an exception was thrown
17592 * but not caught. */
17593 if (aborting())
17595 if (ret == OK)
17596 clear_tv(rettv);
17597 ret = FAIL;
17599 dict_unref(selfdict);
17600 selfdict = NULL;
17602 else /* **arg == '[' || **arg == '.' */
17604 dict_unref(selfdict);
17605 if (rettv->v_type == VAR_DICT)
17607 selfdict = rettv->vval.v_dict;
17608 if (selfdict != NULL)
17609 ++selfdict->dv_refcount;
17611 else
17612 selfdict = NULL;
17613 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
17615 clear_tv(rettv);
17616 ret = FAIL;
17620 dict_unref(selfdict);
17621 return ret;
17625 * Allocate memory for a variable type-value, and make it emtpy (0 or NULL
17626 * value).
17628 static typval_T *
17629 alloc_tv()
17631 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
17635 * Allocate memory for a variable type-value, and assign a string to it.
17636 * The string "s" must have been allocated, it is consumed.
17637 * Return NULL for out of memory, the variable otherwise.
17639 static typval_T *
17640 alloc_string_tv(s)
17641 char_u *s;
17643 typval_T *rettv;
17645 rettv = alloc_tv();
17646 if (rettv != NULL)
17648 rettv->v_type = VAR_STRING;
17649 rettv->vval.v_string = s;
17651 else
17652 vim_free(s);
17653 return rettv;
17657 * Free the memory for a variable type-value.
17659 void
17660 free_tv(varp)
17661 typval_T *varp;
17663 if (varp != NULL)
17665 switch (varp->v_type)
17667 case VAR_FUNC:
17668 func_unref(varp->vval.v_string);
17669 /*FALLTHROUGH*/
17670 case VAR_STRING:
17671 vim_free(varp->vval.v_string);
17672 break;
17673 case VAR_LIST:
17674 list_unref(varp->vval.v_list);
17675 break;
17676 case VAR_DICT:
17677 dict_unref(varp->vval.v_dict);
17678 break;
17679 case VAR_NUMBER:
17680 case VAR_UNKNOWN:
17681 break;
17682 default:
17683 EMSG2(_(e_intern2), "free_tv()");
17684 break;
17686 vim_free(varp);
17691 * Free the memory for a variable value and set the value to NULL or 0.
17693 void
17694 clear_tv(varp)
17695 typval_T *varp;
17697 if (varp != NULL)
17699 switch (varp->v_type)
17701 case VAR_FUNC:
17702 func_unref(varp->vval.v_string);
17703 /*FALLTHROUGH*/
17704 case VAR_STRING:
17705 vim_free(varp->vval.v_string);
17706 varp->vval.v_string = NULL;
17707 break;
17708 case VAR_LIST:
17709 list_unref(varp->vval.v_list);
17710 varp->vval.v_list = NULL;
17711 break;
17712 case VAR_DICT:
17713 dict_unref(varp->vval.v_dict);
17714 varp->vval.v_dict = NULL;
17715 break;
17716 case VAR_NUMBER:
17717 varp->vval.v_number = 0;
17718 break;
17719 case VAR_UNKNOWN:
17720 break;
17721 default:
17722 EMSG2(_(e_intern2), "clear_tv()");
17724 varp->v_lock = 0;
17729 * Set the value of a variable to NULL without freeing items.
17731 static void
17732 init_tv(varp)
17733 typval_T *varp;
17735 if (varp != NULL)
17736 vim_memset(varp, 0, sizeof(typval_T));
17740 * Get the number value of a variable.
17741 * If it is a String variable, uses vim_str2nr().
17742 * For incompatible types, return 0.
17743 * get_tv_number_chk() is similar to get_tv_number(), but informs the
17744 * caller of incompatible types: it sets *denote to TRUE if "denote"
17745 * is not NULL or returns -1 otherwise.
17747 static long
17748 get_tv_number(varp)
17749 typval_T *varp;
17751 int error = FALSE;
17753 return get_tv_number_chk(varp, &error); /* return 0L on error */
17756 long
17757 get_tv_number_chk(varp, denote)
17758 typval_T *varp;
17759 int *denote;
17761 long n = 0L;
17763 switch (varp->v_type)
17765 case VAR_NUMBER:
17766 return (long)(varp->vval.v_number);
17767 case VAR_FUNC:
17768 EMSG(_("E703: Using a Funcref as a number"));
17769 break;
17770 case VAR_STRING:
17771 if (varp->vval.v_string != NULL)
17772 vim_str2nr(varp->vval.v_string, NULL, NULL,
17773 TRUE, TRUE, &n, NULL);
17774 return n;
17775 case VAR_LIST:
17776 EMSG(_("E745: Using a List as a number"));
17777 break;
17778 case VAR_DICT:
17779 EMSG(_("E728: Using a Dictionary as a number"));
17780 break;
17781 default:
17782 EMSG2(_(e_intern2), "get_tv_number()");
17783 break;
17785 if (denote == NULL) /* useful for values that must be unsigned */
17786 n = -1;
17787 else
17788 *denote = TRUE;
17789 return n;
17793 * Get the lnum from the first argument.
17794 * Also accepts ".", "$", etc., but that only works for the current buffer.
17795 * Returns -1 on error.
17797 static linenr_T
17798 get_tv_lnum(argvars)
17799 typval_T *argvars;
17801 typval_T rettv;
17802 linenr_T lnum;
17804 lnum = get_tv_number_chk(&argvars[0], NULL);
17805 if (lnum == 0) /* no valid number, try using line() */
17807 rettv.v_type = VAR_NUMBER;
17808 f_line(argvars, &rettv);
17809 lnum = rettv.vval.v_number;
17810 clear_tv(&rettv);
17812 return lnum;
17816 * Get the lnum from the first argument.
17817 * Also accepts "$", then "buf" is used.
17818 * Returns 0 on error.
17820 static linenr_T
17821 get_tv_lnum_buf(argvars, buf)
17822 typval_T *argvars;
17823 buf_T *buf;
17825 if (argvars[0].v_type == VAR_STRING
17826 && argvars[0].vval.v_string != NULL
17827 && argvars[0].vval.v_string[0] == '$'
17828 && buf != NULL)
17829 return buf->b_ml.ml_line_count;
17830 return get_tv_number_chk(&argvars[0], NULL);
17834 * Get the string value of a variable.
17835 * If it is a Number variable, the number is converted into a string.
17836 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
17837 * get_tv_string_buf() uses a given buffer.
17838 * If the String variable has never been set, return an empty string.
17839 * Never returns NULL;
17840 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
17841 * NULL on error.
17843 static char_u *
17844 get_tv_string(varp)
17845 typval_T *varp;
17847 static char_u mybuf[NUMBUFLEN];
17849 return get_tv_string_buf(varp, mybuf);
17852 static char_u *
17853 get_tv_string_buf(varp, buf)
17854 typval_T *varp;
17855 char_u *buf;
17857 char_u *res = get_tv_string_buf_chk(varp, buf);
17859 return res != NULL ? res : (char_u *)"";
17862 char_u *
17863 get_tv_string_chk(varp)
17864 typval_T *varp;
17866 static char_u mybuf[NUMBUFLEN];
17868 return get_tv_string_buf_chk(varp, mybuf);
17871 static char_u *
17872 get_tv_string_buf_chk(varp, buf)
17873 typval_T *varp;
17874 char_u *buf;
17876 switch (varp->v_type)
17878 case VAR_NUMBER:
17879 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
17880 return buf;
17881 case VAR_FUNC:
17882 EMSG(_("E729: using Funcref as a String"));
17883 break;
17884 case VAR_LIST:
17885 EMSG(_("E730: using List as a String"));
17886 break;
17887 case VAR_DICT:
17888 EMSG(_("E731: using Dictionary as a String"));
17889 break;
17890 case VAR_STRING:
17891 if (varp->vval.v_string != NULL)
17892 return varp->vval.v_string;
17893 return (char_u *)"";
17894 default:
17895 EMSG2(_(e_intern2), "get_tv_string_buf()");
17896 break;
17898 return NULL;
17902 * Find variable "name" in the list of variables.
17903 * Return a pointer to it if found, NULL if not found.
17904 * Careful: "a:0" variables don't have a name.
17905 * When "htp" is not NULL we are writing to the variable, set "htp" to the
17906 * hashtab_T used.
17908 static dictitem_T *
17909 find_var(name, htp)
17910 char_u *name;
17911 hashtab_T **htp;
17913 char_u *varname;
17914 hashtab_T *ht;
17916 ht = find_var_ht(name, &varname);
17917 if (htp != NULL)
17918 *htp = ht;
17919 if (ht == NULL)
17920 return NULL;
17921 return find_var_in_ht(ht, varname, htp != NULL);
17925 * Find variable "varname" in hashtab "ht".
17926 * Returns NULL if not found.
17928 static dictitem_T *
17929 find_var_in_ht(ht, varname, writing)
17930 hashtab_T *ht;
17931 char_u *varname;
17932 int writing;
17934 hashitem_T *hi;
17936 if (*varname == NUL)
17938 /* Must be something like "s:", otherwise "ht" would be NULL. */
17939 switch (varname[-2])
17941 case 's': return &SCRIPT_SV(current_SID).sv_var;
17942 case 'g': return &globvars_var;
17943 case 'v': return &vimvars_var;
17944 case 'b': return &curbuf->b_bufvar;
17945 case 'w': return &curwin->w_winvar;
17946 #ifdef FEAT_WINDOWS
17947 case 't': return &curtab->tp_winvar;
17948 #endif
17949 case 'l': return current_funccal == NULL
17950 ? NULL : &current_funccal->l_vars_var;
17951 case 'a': return current_funccal == NULL
17952 ? NULL : &current_funccal->l_avars_var;
17954 return NULL;
17957 hi = hash_find(ht, varname);
17958 if (HASHITEM_EMPTY(hi))
17960 /* For global variables we may try auto-loading the script. If it
17961 * worked find the variable again. Don't auto-load a script if it was
17962 * loaded already, otherwise it would be loaded every time when
17963 * checking if a function name is a Funcref variable. */
17964 if (ht == &globvarht && !writing
17965 && script_autoload(varname, FALSE) && !aborting())
17966 hi = hash_find(ht, varname);
17967 if (HASHITEM_EMPTY(hi))
17968 return NULL;
17970 return HI2DI(hi);
17974 * Find the hashtab used for a variable name.
17975 * Set "varname" to the start of name without ':'.
17977 static hashtab_T *
17978 find_var_ht(name, varname)
17979 char_u *name;
17980 char_u **varname;
17982 hashitem_T *hi;
17984 if (name[1] != ':')
17986 /* The name must not start with a colon or #. */
17987 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
17988 return NULL;
17989 *varname = name;
17991 /* "version" is "v:version" in all scopes */
17992 hi = hash_find(&compat_hashtab, name);
17993 if (!HASHITEM_EMPTY(hi))
17994 return &compat_hashtab;
17996 if (current_funccal == NULL)
17997 return &globvarht; /* global variable */
17998 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
18000 *varname = name + 2;
18001 if (*name == 'g') /* global variable */
18002 return &globvarht;
18003 /* There must be no ':' or '#' in the rest of the name, unless g: is used
18005 if (vim_strchr(name + 2, ':') != NULL
18006 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
18007 return NULL;
18008 if (*name == 'b') /* buffer variable */
18009 return &curbuf->b_vars.dv_hashtab;
18010 if (*name == 'w') /* window variable */
18011 return &curwin->w_vars.dv_hashtab;
18012 #ifdef FEAT_WINDOWS
18013 if (*name == 't') /* tab page variable */
18014 return &curtab->tp_vars.dv_hashtab;
18015 #endif
18016 if (*name == 'v') /* v: variable */
18017 return &vimvarht;
18018 if (*name == 'a' && current_funccal != NULL) /* function argument */
18019 return &current_funccal->l_avars.dv_hashtab;
18020 if (*name == 'l' && current_funccal != NULL) /* local function variable */
18021 return &current_funccal->l_vars.dv_hashtab;
18022 if (*name == 's' /* script variable */
18023 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
18024 return &SCRIPT_VARS(current_SID);
18025 return NULL;
18029 * Get the string value of a (global/local) variable.
18030 * Returns NULL when it doesn't exist.
18032 char_u *
18033 get_var_value(name)
18034 char_u *name;
18036 dictitem_T *v;
18038 v = find_var(name, NULL);
18039 if (v == NULL)
18040 return NULL;
18041 return get_tv_string(&v->di_tv);
18045 * Allocate a new hashtab for a sourced script. It will be used while
18046 * sourcing this script and when executing functions defined in the script.
18048 void
18049 new_script_vars(id)
18050 scid_T id;
18052 int i;
18053 hashtab_T *ht;
18054 scriptvar_T *sv;
18056 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
18058 /* Re-allocating ga_data means that an ht_array pointing to
18059 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
18060 * at its init value. Also reset "v_dict", it's always the same. */
18061 for (i = 1; i <= ga_scripts.ga_len; ++i)
18063 ht = &SCRIPT_VARS(i);
18064 if (ht->ht_mask == HT_INIT_SIZE - 1)
18065 ht->ht_array = ht->ht_smallarray;
18066 sv = &SCRIPT_SV(i);
18067 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
18070 while (ga_scripts.ga_len < id)
18072 sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
18073 init_var_dict(&sv->sv_dict, &sv->sv_var);
18074 ++ga_scripts.ga_len;
18080 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
18081 * point to it.
18083 void
18084 init_var_dict(dict, dict_var)
18085 dict_T *dict;
18086 dictitem_T *dict_var;
18088 hash_init(&dict->dv_hashtab);
18089 dict->dv_refcount = 99999;
18090 dict_var->di_tv.vval.v_dict = dict;
18091 dict_var->di_tv.v_type = VAR_DICT;
18092 dict_var->di_tv.v_lock = VAR_FIXED;
18093 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
18094 dict_var->di_key[0] = NUL;
18098 * Clean up a list of internal variables.
18099 * Frees all allocated variables and the value they contain.
18100 * Clears hashtab "ht", does not free it.
18102 void
18103 vars_clear(ht)
18104 hashtab_T *ht;
18106 vars_clear_ext(ht, TRUE);
18110 * Like vars_clear(), but only free the value if "free_val" is TRUE.
18112 static void
18113 vars_clear_ext(ht, free_val)
18114 hashtab_T *ht;
18115 int free_val;
18117 int todo;
18118 hashitem_T *hi;
18119 dictitem_T *v;
18121 hash_lock(ht);
18122 todo = (int)ht->ht_used;
18123 for (hi = ht->ht_array; todo > 0; ++hi)
18125 if (!HASHITEM_EMPTY(hi))
18127 --todo;
18129 /* Free the variable. Don't remove it from the hashtab,
18130 * ht_array might change then. hash_clear() takes care of it
18131 * later. */
18132 v = HI2DI(hi);
18133 if (free_val)
18134 clear_tv(&v->di_tv);
18135 if ((v->di_flags & DI_FLAGS_FIX) == 0)
18136 vim_free(v);
18139 hash_clear(ht);
18140 ht->ht_used = 0;
18144 * Delete a variable from hashtab "ht" at item "hi".
18145 * Clear the variable value and free the dictitem.
18147 static void
18148 delete_var(ht, hi)
18149 hashtab_T *ht;
18150 hashitem_T *hi;
18152 dictitem_T *di = HI2DI(hi);
18154 hash_remove(ht, hi);
18155 clear_tv(&di->di_tv);
18156 vim_free(di);
18160 * List the value of one internal variable.
18162 static void
18163 list_one_var(v, prefix, first)
18164 dictitem_T *v;
18165 char_u *prefix;
18166 int *first;
18168 char_u *tofree;
18169 char_u *s;
18170 char_u numbuf[NUMBUFLEN];
18172 s = echo_string(&v->di_tv, &tofree, numbuf, ++current_copyID);
18173 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
18174 s == NULL ? (char_u *)"" : s, first);
18175 vim_free(tofree);
18178 static void
18179 list_one_var_a(prefix, name, type, string, first)
18180 char_u *prefix;
18181 char_u *name;
18182 int type;
18183 char_u *string;
18184 int *first; /* when TRUE clear rest of screen and set to FALSE */
18186 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
18187 msg_start();
18188 msg_puts(prefix);
18189 if (name != NULL) /* "a:" vars don't have a name stored */
18190 msg_puts(name);
18191 msg_putchar(' ');
18192 msg_advance(22);
18193 if (type == VAR_NUMBER)
18194 msg_putchar('#');
18195 else if (type == VAR_FUNC)
18196 msg_putchar('*');
18197 else if (type == VAR_LIST)
18199 msg_putchar('[');
18200 if (*string == '[')
18201 ++string;
18203 else if (type == VAR_DICT)
18205 msg_putchar('{');
18206 if (*string == '{')
18207 ++string;
18209 else
18210 msg_putchar(' ');
18212 msg_outtrans(string);
18214 if (type == VAR_FUNC)
18215 msg_puts((char_u *)"()");
18216 if (*first)
18218 msg_clr_eos();
18219 *first = FALSE;
18224 * Set variable "name" to value in "tv".
18225 * If the variable already exists, the value is updated.
18226 * Otherwise the variable is created.
18228 static void
18229 set_var(name, tv, copy)
18230 char_u *name;
18231 typval_T *tv;
18232 int copy; /* make copy of value in "tv" */
18234 dictitem_T *v;
18235 char_u *varname;
18236 hashtab_T *ht;
18237 char_u *p;
18239 if (tv->v_type == VAR_FUNC)
18241 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
18242 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
18243 ? name[2] : name[0]))
18245 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
18246 return;
18248 if (function_exists(name))
18250 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
18251 name);
18252 return;
18256 ht = find_var_ht(name, &varname);
18257 if (ht == NULL || *varname == NUL)
18259 EMSG2(_(e_illvar), name);
18260 return;
18263 v = find_var_in_ht(ht, varname, TRUE);
18264 if (v != NULL)
18266 /* existing variable, need to clear the value */
18267 if (var_check_ro(v->di_flags, name)
18268 || tv_check_lock(v->di_tv.v_lock, name))
18269 return;
18270 if (v->di_tv.v_type != tv->v_type
18271 && !((v->di_tv.v_type == VAR_STRING
18272 || v->di_tv.v_type == VAR_NUMBER)
18273 && (tv->v_type == VAR_STRING
18274 || tv->v_type == VAR_NUMBER)))
18276 EMSG2(_("E706: Variable type mismatch for: %s"), name);
18277 return;
18281 * Handle setting internal v: variables separately: we don't change
18282 * the type.
18284 if (ht == &vimvarht)
18286 if (v->di_tv.v_type == VAR_STRING)
18288 vim_free(v->di_tv.vval.v_string);
18289 if (copy || tv->v_type != VAR_STRING)
18290 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
18291 else
18293 /* Take over the string to avoid an extra alloc/free. */
18294 v->di_tv.vval.v_string = tv->vval.v_string;
18295 tv->vval.v_string = NULL;
18298 else if (v->di_tv.v_type != VAR_NUMBER)
18299 EMSG2(_(e_intern2), "set_var()");
18300 else
18301 v->di_tv.vval.v_number = get_tv_number(tv);
18302 return;
18305 clear_tv(&v->di_tv);
18307 else /* add a new variable */
18309 /* Can't add "v:" variable. */
18310 if (ht == &vimvarht)
18312 EMSG2(_(e_illvar), name);
18313 return;
18316 /* Make sure the variable name is valid. */
18317 for (p = varname; *p != NUL; ++p)
18318 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
18319 && *p != AUTOLOAD_CHAR)
18321 EMSG2(_(e_illvar), varname);
18322 return;
18325 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
18326 + STRLEN(varname)));
18327 if (v == NULL)
18328 return;
18329 STRCPY(v->di_key, varname);
18330 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
18332 vim_free(v);
18333 return;
18335 v->di_flags = 0;
18338 if (copy || tv->v_type == VAR_NUMBER)
18339 copy_tv(tv, &v->di_tv);
18340 else
18342 v->di_tv = *tv;
18343 v->di_tv.v_lock = 0;
18344 init_tv(tv);
18349 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
18350 * Also give an error message.
18352 static int
18353 var_check_ro(flags, name)
18354 int flags;
18355 char_u *name;
18357 if (flags & DI_FLAGS_RO)
18359 EMSG2(_(e_readonlyvar), name);
18360 return TRUE;
18362 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
18364 EMSG2(_(e_readonlysbx), name);
18365 return TRUE;
18367 return FALSE;
18371 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
18372 * Also give an error message.
18374 static int
18375 var_check_fixed(flags, name)
18376 int flags;
18377 char_u *name;
18379 if (flags & DI_FLAGS_FIX)
18381 EMSG2(_("E795: Cannot delete variable %s"), name);
18382 return TRUE;
18384 return FALSE;
18388 * Return TRUE if typeval "tv" is set to be locked (immutable).
18389 * Also give an error message, using "name".
18391 static int
18392 tv_check_lock(lock, name)
18393 int lock;
18394 char_u *name;
18396 if (lock & VAR_LOCKED)
18398 EMSG2(_("E741: Value is locked: %s"),
18399 name == NULL ? (char_u *)_("Unknown") : name);
18400 return TRUE;
18402 if (lock & VAR_FIXED)
18404 EMSG2(_("E742: Cannot change value of %s"),
18405 name == NULL ? (char_u *)_("Unknown") : name);
18406 return TRUE;
18408 return FALSE;
18412 * Copy the values from typval_T "from" to typval_T "to".
18413 * When needed allocates string or increases reference count.
18414 * Does not make a copy of a list or dict but copies the reference!
18416 static void
18417 copy_tv(from, to)
18418 typval_T *from;
18419 typval_T *to;
18421 to->v_type = from->v_type;
18422 to->v_lock = 0;
18423 switch (from->v_type)
18425 case VAR_NUMBER:
18426 to->vval.v_number = from->vval.v_number;
18427 break;
18428 case VAR_STRING:
18429 case VAR_FUNC:
18430 if (from->vval.v_string == NULL)
18431 to->vval.v_string = NULL;
18432 else
18434 to->vval.v_string = vim_strsave(from->vval.v_string);
18435 if (from->v_type == VAR_FUNC)
18436 func_ref(to->vval.v_string);
18438 break;
18439 case VAR_LIST:
18440 if (from->vval.v_list == NULL)
18441 to->vval.v_list = NULL;
18442 else
18444 to->vval.v_list = from->vval.v_list;
18445 ++to->vval.v_list->lv_refcount;
18447 break;
18448 case VAR_DICT:
18449 if (from->vval.v_dict == NULL)
18450 to->vval.v_dict = NULL;
18451 else
18453 to->vval.v_dict = from->vval.v_dict;
18454 ++to->vval.v_dict->dv_refcount;
18456 break;
18457 default:
18458 EMSG2(_(e_intern2), "copy_tv()");
18459 break;
18464 * Make a copy of an item.
18465 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
18466 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
18467 * reference to an already copied list/dict can be used.
18468 * Returns FAIL or OK.
18470 static int
18471 item_copy(from, to, deep, copyID)
18472 typval_T *from;
18473 typval_T *to;
18474 int deep;
18475 int copyID;
18477 static int recurse = 0;
18478 int ret = OK;
18480 if (recurse >= DICT_MAXNEST)
18482 EMSG(_("E698: variable nested too deep for making a copy"));
18483 return FAIL;
18485 ++recurse;
18487 switch (from->v_type)
18489 case VAR_NUMBER:
18490 case VAR_STRING:
18491 case VAR_FUNC:
18492 copy_tv(from, to);
18493 break;
18494 case VAR_LIST:
18495 to->v_type = VAR_LIST;
18496 to->v_lock = 0;
18497 if (from->vval.v_list == NULL)
18498 to->vval.v_list = NULL;
18499 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
18501 /* use the copy made earlier */
18502 to->vval.v_list = from->vval.v_list->lv_copylist;
18503 ++to->vval.v_list->lv_refcount;
18505 else
18506 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
18507 if (to->vval.v_list == NULL)
18508 ret = FAIL;
18509 break;
18510 case VAR_DICT:
18511 to->v_type = VAR_DICT;
18512 to->v_lock = 0;
18513 if (from->vval.v_dict == NULL)
18514 to->vval.v_dict = NULL;
18515 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
18517 /* use the copy made earlier */
18518 to->vval.v_dict = from->vval.v_dict->dv_copydict;
18519 ++to->vval.v_dict->dv_refcount;
18521 else
18522 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
18523 if (to->vval.v_dict == NULL)
18524 ret = FAIL;
18525 break;
18526 default:
18527 EMSG2(_(e_intern2), "item_copy()");
18528 ret = FAIL;
18530 --recurse;
18531 return ret;
18535 * ":echo expr1 ..." print each argument separated with a space, add a
18536 * newline at the end.
18537 * ":echon expr1 ..." print each argument plain.
18539 void
18540 ex_echo(eap)
18541 exarg_T *eap;
18543 char_u *arg = eap->arg;
18544 typval_T rettv;
18545 char_u *tofree;
18546 char_u *p;
18547 int needclr = TRUE;
18548 int atstart = TRUE;
18549 char_u numbuf[NUMBUFLEN];
18551 if (eap->skip)
18552 ++emsg_skip;
18553 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
18555 p = arg;
18556 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
18559 * Report the invalid expression unless the expression evaluation
18560 * has been cancelled due to an aborting error, an interrupt, or an
18561 * exception.
18563 if (!aborting())
18564 EMSG2(_(e_invexpr2), p);
18565 break;
18567 if (!eap->skip)
18569 if (atstart)
18571 atstart = FALSE;
18572 /* Call msg_start() after eval1(), evaluating the expression
18573 * may cause a message to appear. */
18574 if (eap->cmdidx == CMD_echo)
18575 msg_start();
18577 else if (eap->cmdidx == CMD_echo)
18578 msg_puts_attr((char_u *)" ", echo_attr);
18579 p = echo_string(&rettv, &tofree, numbuf, ++current_copyID);
18580 if (p != NULL)
18581 for ( ; *p != NUL && !got_int; ++p)
18583 if (*p == '\n' || *p == '\r' || *p == TAB)
18585 if (*p != TAB && needclr)
18587 /* remove any text still there from the command */
18588 msg_clr_eos();
18589 needclr = FALSE;
18591 msg_putchar_attr(*p, echo_attr);
18593 else
18595 #ifdef FEAT_MBYTE
18596 if (has_mbyte)
18598 int i = (*mb_ptr2len)(p);
18600 (void)msg_outtrans_len_attr(p, i, echo_attr);
18601 p += i - 1;
18603 else
18604 #endif
18605 (void)msg_outtrans_len_attr(p, 1, echo_attr);
18608 vim_free(tofree);
18610 clear_tv(&rettv);
18611 arg = skipwhite(arg);
18613 eap->nextcmd = check_nextcmd(arg);
18615 if (eap->skip)
18616 --emsg_skip;
18617 else
18619 /* remove text that may still be there from the command */
18620 if (needclr)
18621 msg_clr_eos();
18622 if (eap->cmdidx == CMD_echo)
18623 msg_end();
18628 * ":echohl {name}".
18630 void
18631 ex_echohl(eap)
18632 exarg_T *eap;
18634 int id;
18636 id = syn_name2id(eap->arg);
18637 if (id == 0)
18638 echo_attr = 0;
18639 else
18640 echo_attr = syn_id2attr(id);
18644 * ":execute expr1 ..." execute the result of an expression.
18645 * ":echomsg expr1 ..." Print a message
18646 * ":echoerr expr1 ..." Print an error
18647 * Each gets spaces around each argument and a newline at the end for
18648 * echo commands
18650 void
18651 ex_execute(eap)
18652 exarg_T *eap;
18654 char_u *arg = eap->arg;
18655 typval_T rettv;
18656 int ret = OK;
18657 char_u *p;
18658 garray_T ga;
18659 int len;
18660 int save_did_emsg;
18662 ga_init2(&ga, 1, 80);
18664 if (eap->skip)
18665 ++emsg_skip;
18666 while (*arg != NUL && *arg != '|' && *arg != '\n')
18668 p = arg;
18669 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
18672 * Report the invalid expression unless the expression evaluation
18673 * has been cancelled due to an aborting error, an interrupt, or an
18674 * exception.
18676 if (!aborting())
18677 EMSG2(_(e_invexpr2), p);
18678 ret = FAIL;
18679 break;
18682 if (!eap->skip)
18684 p = get_tv_string(&rettv);
18685 len = (int)STRLEN(p);
18686 if (ga_grow(&ga, len + 2) == FAIL)
18688 clear_tv(&rettv);
18689 ret = FAIL;
18690 break;
18692 if (ga.ga_len)
18693 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
18694 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
18695 ga.ga_len += len;
18698 clear_tv(&rettv);
18699 arg = skipwhite(arg);
18702 if (ret != FAIL && ga.ga_data != NULL)
18704 if (eap->cmdidx == CMD_echomsg)
18706 MSG_ATTR(ga.ga_data, echo_attr);
18707 out_flush();
18709 else if (eap->cmdidx == CMD_echoerr)
18711 /* We don't want to abort following commands, restore did_emsg. */
18712 save_did_emsg = did_emsg;
18713 EMSG((char_u *)ga.ga_data);
18714 if (!force_abort)
18715 did_emsg = save_did_emsg;
18717 else if (eap->cmdidx == CMD_execute)
18718 do_cmdline((char_u *)ga.ga_data,
18719 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
18722 ga_clear(&ga);
18724 if (eap->skip)
18725 --emsg_skip;
18727 eap->nextcmd = check_nextcmd(arg);
18731 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
18732 * "arg" points to the "&" or '+' when called, to "option" when returning.
18733 * Returns NULL when no option name found. Otherwise pointer to the char
18734 * after the option name.
18736 static char_u *
18737 find_option_end(arg, opt_flags)
18738 char_u **arg;
18739 int *opt_flags;
18741 char_u *p = *arg;
18743 ++p;
18744 if (*p == 'g' && p[1] == ':')
18746 *opt_flags = OPT_GLOBAL;
18747 p += 2;
18749 else if (*p == 'l' && p[1] == ':')
18751 *opt_flags = OPT_LOCAL;
18752 p += 2;
18754 else
18755 *opt_flags = 0;
18757 if (!ASCII_ISALPHA(*p))
18758 return NULL;
18759 *arg = p;
18761 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
18762 p += 4; /* termcap option */
18763 else
18764 while (ASCII_ISALPHA(*p))
18765 ++p;
18766 return p;
18770 * ":function"
18772 void
18773 ex_function(eap)
18774 exarg_T *eap;
18776 char_u *theline;
18777 int j;
18778 int c;
18779 int saved_did_emsg;
18780 char_u *name = NULL;
18781 char_u *p;
18782 char_u *arg;
18783 char_u *line_arg = NULL;
18784 garray_T newargs;
18785 garray_T newlines;
18786 int varargs = FALSE;
18787 int mustend = FALSE;
18788 int flags = 0;
18789 ufunc_T *fp;
18790 int indent;
18791 int nesting;
18792 char_u *skip_until = NULL;
18793 dictitem_T *v;
18794 funcdict_T fudi;
18795 static int func_nr = 0; /* number for nameless function */
18796 int paren;
18797 hashtab_T *ht;
18798 int todo;
18799 hashitem_T *hi;
18800 int sourcing_lnum_off;
18803 * ":function" without argument: list functions.
18805 if (ends_excmd(*eap->arg))
18807 if (!eap->skip)
18809 todo = (int)func_hashtab.ht_used;
18810 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
18812 if (!HASHITEM_EMPTY(hi))
18814 --todo;
18815 fp = HI2UF(hi);
18816 if (!isdigit(*fp->uf_name))
18817 list_func_head(fp, FALSE);
18821 eap->nextcmd = check_nextcmd(eap->arg);
18822 return;
18826 * ":function /pat": list functions matching pattern.
18828 if (*eap->arg == '/')
18830 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
18831 if (!eap->skip)
18833 regmatch_T regmatch;
18835 c = *p;
18836 *p = NUL;
18837 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
18838 *p = c;
18839 if (regmatch.regprog != NULL)
18841 regmatch.rm_ic = p_ic;
18843 todo = (int)func_hashtab.ht_used;
18844 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
18846 if (!HASHITEM_EMPTY(hi))
18848 --todo;
18849 fp = HI2UF(hi);
18850 if (!isdigit(*fp->uf_name)
18851 && vim_regexec(&regmatch, fp->uf_name, 0))
18852 list_func_head(fp, FALSE);
18857 if (*p == '/')
18858 ++p;
18859 eap->nextcmd = check_nextcmd(p);
18860 return;
18864 * Get the function name. There are these situations:
18865 * func normal function name
18866 * "name" == func, "fudi.fd_dict" == NULL
18867 * dict.func new dictionary entry
18868 * "name" == NULL, "fudi.fd_dict" set,
18869 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
18870 * dict.func existing dict entry with a Funcref
18871 * "name" == func, "fudi.fd_dict" set,
18872 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
18873 * dict.func existing dict entry that's not a Funcref
18874 * "name" == NULL, "fudi.fd_dict" set,
18875 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
18877 p = eap->arg;
18878 name = trans_function_name(&p, eap->skip, 0, &fudi);
18879 paren = (vim_strchr(p, '(') != NULL);
18880 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
18883 * Return on an invalid expression in braces, unless the expression
18884 * evaluation has been cancelled due to an aborting error, an
18885 * interrupt, or an exception.
18887 if (!aborting())
18889 if (!eap->skip && fudi.fd_newkey != NULL)
18890 EMSG2(_(e_dictkey), fudi.fd_newkey);
18891 vim_free(fudi.fd_newkey);
18892 return;
18894 else
18895 eap->skip = TRUE;
18898 /* An error in a function call during evaluation of an expression in magic
18899 * braces should not cause the function not to be defined. */
18900 saved_did_emsg = did_emsg;
18901 did_emsg = FALSE;
18904 * ":function func" with only function name: list function.
18906 if (!paren)
18908 if (!ends_excmd(*skipwhite(p)))
18910 EMSG(_(e_trailing));
18911 goto ret_free;
18913 eap->nextcmd = check_nextcmd(p);
18914 if (eap->nextcmd != NULL)
18915 *p = NUL;
18916 if (!eap->skip && !got_int)
18918 fp = find_func(name);
18919 if (fp != NULL)
18921 list_func_head(fp, TRUE);
18922 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
18924 if (FUNCLINE(fp, j) == NULL)
18925 continue;
18926 msg_putchar('\n');
18927 msg_outnum((long)(j + 1));
18928 if (j < 9)
18929 msg_putchar(' ');
18930 if (j < 99)
18931 msg_putchar(' ');
18932 msg_prt_line(FUNCLINE(fp, j), FALSE);
18933 out_flush(); /* show a line at a time */
18934 ui_breakcheck();
18936 if (!got_int)
18938 msg_putchar('\n');
18939 msg_puts((char_u *)" endfunction");
18942 else
18943 emsg_funcname("E123: Undefined function: %s", name);
18945 goto ret_free;
18949 * ":function name(arg1, arg2)" Define function.
18951 p = skipwhite(p);
18952 if (*p != '(')
18954 if (!eap->skip)
18956 EMSG2(_("E124: Missing '(': %s"), eap->arg);
18957 goto ret_free;
18959 /* attempt to continue by skipping some text */
18960 if (vim_strchr(p, '(') != NULL)
18961 p = vim_strchr(p, '(');
18963 p = skipwhite(p + 1);
18965 ga_init2(&newargs, (int)sizeof(char_u *), 3);
18966 ga_init2(&newlines, (int)sizeof(char_u *), 3);
18968 if (!eap->skip)
18970 /* Check the name of the function. Unless it's a dictionary function
18971 * (that we are overwriting). */
18972 if (name != NULL)
18973 arg = name;
18974 else
18975 arg = fudi.fd_newkey;
18976 if (arg != NULL && (fudi.fd_di == NULL
18977 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
18979 if (*arg == K_SPECIAL)
18980 j = 3;
18981 else
18982 j = 0;
18983 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
18984 : eval_isnamec(arg[j])))
18985 ++j;
18986 if (arg[j] != NUL)
18987 emsg_funcname(_(e_invarg2), arg);
18992 * Isolate the arguments: "arg1, arg2, ...)"
18994 while (*p != ')')
18996 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
18998 varargs = TRUE;
18999 p += 3;
19000 mustend = TRUE;
19002 else
19004 arg = p;
19005 while (ASCII_ISALNUM(*p) || *p == '_')
19006 ++p;
19007 if (arg == p || isdigit(*arg)
19008 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
19009 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
19011 if (!eap->skip)
19012 EMSG2(_("E125: Illegal argument: %s"), arg);
19013 break;
19015 if (ga_grow(&newargs, 1) == FAIL)
19016 goto erret;
19017 c = *p;
19018 *p = NUL;
19019 arg = vim_strsave(arg);
19020 if (arg == NULL)
19021 goto erret;
19022 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
19023 *p = c;
19024 newargs.ga_len++;
19025 if (*p == ',')
19026 ++p;
19027 else
19028 mustend = TRUE;
19030 p = skipwhite(p);
19031 if (mustend && *p != ')')
19033 if (!eap->skip)
19034 EMSG2(_(e_invarg2), eap->arg);
19035 break;
19038 ++p; /* skip the ')' */
19040 /* find extra arguments "range", "dict" and "abort" */
19041 for (;;)
19043 p = skipwhite(p);
19044 if (STRNCMP(p, "range", 5) == 0)
19046 flags |= FC_RANGE;
19047 p += 5;
19049 else if (STRNCMP(p, "dict", 4) == 0)
19051 flags |= FC_DICT;
19052 p += 4;
19054 else if (STRNCMP(p, "abort", 5) == 0)
19056 flags |= FC_ABORT;
19057 p += 5;
19059 else
19060 break;
19063 /* When there is a line break use what follows for the function body.
19064 * Makes 'exe "func Test()\n...\nendfunc"' work. */
19065 if (*p == '\n')
19066 line_arg = p + 1;
19067 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
19068 EMSG(_(e_trailing));
19071 * Read the body of the function, until ":endfunction" is found.
19073 if (KeyTyped)
19075 /* Check if the function already exists, don't let the user type the
19076 * whole function before telling him it doesn't work! For a script we
19077 * need to skip the body to be able to find what follows. */
19078 if (!eap->skip && !eap->forceit)
19080 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
19081 EMSG(_(e_funcdict));
19082 else if (name != NULL && find_func(name) != NULL)
19083 emsg_funcname(e_funcexts, name);
19086 if (!eap->skip && did_emsg)
19087 goto erret;
19089 msg_putchar('\n'); /* don't overwrite the function name */
19090 cmdline_row = msg_row;
19093 indent = 2;
19094 nesting = 0;
19095 for (;;)
19097 msg_scroll = TRUE;
19098 need_wait_return = FALSE;
19099 sourcing_lnum_off = sourcing_lnum;
19101 if (line_arg != NULL)
19103 /* Use eap->arg, split up in parts by line breaks. */
19104 theline = line_arg;
19105 p = vim_strchr(theline, '\n');
19106 if (p == NULL)
19107 line_arg += STRLEN(line_arg);
19108 else
19110 *p = NUL;
19111 line_arg = p + 1;
19114 else if (eap->getline == NULL)
19115 theline = getcmdline(':', 0L, indent);
19116 else
19117 theline = eap->getline(':', eap->cookie, indent);
19118 if (KeyTyped)
19119 lines_left = Rows - 1;
19120 if (theline == NULL)
19122 EMSG(_("E126: Missing :endfunction"));
19123 goto erret;
19126 /* Detect line continuation: sourcing_lnum increased more than one. */
19127 if (sourcing_lnum > sourcing_lnum_off + 1)
19128 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
19129 else
19130 sourcing_lnum_off = 0;
19132 if (skip_until != NULL)
19134 /* between ":append" and "." and between ":python <<EOF" and "EOF"
19135 * don't check for ":endfunc". */
19136 if (STRCMP(theline, skip_until) == 0)
19138 vim_free(skip_until);
19139 skip_until = NULL;
19142 else
19144 /* skip ':' and blanks*/
19145 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
19148 /* Check for "endfunction". */
19149 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
19151 if (line_arg == NULL)
19152 vim_free(theline);
19153 break;
19156 /* Increase indent inside "if", "while", "for" and "try", decrease
19157 * at "end". */
19158 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
19159 indent -= 2;
19160 else if (STRNCMP(p, "if", 2) == 0
19161 || STRNCMP(p, "wh", 2) == 0
19162 || STRNCMP(p, "for", 3) == 0
19163 || STRNCMP(p, "try", 3) == 0)
19164 indent += 2;
19166 /* Check for defining a function inside this function. */
19167 if (checkforcmd(&p, "function", 2))
19169 if (*p == '!')
19170 p = skipwhite(p + 1);
19171 p += eval_fname_script(p);
19172 if (ASCII_ISALPHA(*p))
19174 vim_free(trans_function_name(&p, TRUE, 0, NULL));
19175 if (*skipwhite(p) == '(')
19177 ++nesting;
19178 indent += 2;
19183 /* Check for ":append" or ":insert". */
19184 p = skip_range(p, NULL);
19185 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
19186 || (p[0] == 'i'
19187 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
19188 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
19189 skip_until = vim_strsave((char_u *)".");
19191 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
19192 arg = skipwhite(skiptowhite(p));
19193 if (arg[0] == '<' && arg[1] =='<'
19194 && ((p[0] == 'p' && p[1] == 'y'
19195 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
19196 || (p[0] == 'p' && p[1] == 'e'
19197 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
19198 || (p[0] == 't' && p[1] == 'c'
19199 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
19200 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
19201 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
19202 || (p[0] == 'm' && p[1] == 'z'
19203 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
19206 /* ":python <<" continues until a dot, like ":append" */
19207 p = skipwhite(arg + 2);
19208 if (*p == NUL)
19209 skip_until = vim_strsave((char_u *)".");
19210 else
19211 skip_until = vim_strsave(p);
19215 /* Add the line to the function. */
19216 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
19218 if (line_arg == NULL)
19219 vim_free(theline);
19220 goto erret;
19223 /* Copy the line to newly allocated memory. get_one_sourceline()
19224 * allocates 250 bytes per line, this saves 80% on average. The cost
19225 * is an extra alloc/free. */
19226 p = vim_strsave(theline);
19227 if (p != NULL)
19229 if (line_arg == NULL)
19230 vim_free(theline);
19231 theline = p;
19234 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
19236 /* Add NULL lines for continuation lines, so that the line count is
19237 * equal to the index in the growarray. */
19238 while (sourcing_lnum_off-- > 0)
19239 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
19241 /* Check for end of eap->arg. */
19242 if (line_arg != NULL && *line_arg == NUL)
19243 line_arg = NULL;
19246 /* Don't define the function when skipping commands or when an error was
19247 * detected. */
19248 if (eap->skip || did_emsg)
19249 goto erret;
19252 * If there are no errors, add the function
19254 if (fudi.fd_dict == NULL)
19256 v = find_var(name, &ht);
19257 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
19259 emsg_funcname("E707: Function name conflicts with variable: %s",
19260 name);
19261 goto erret;
19264 fp = find_func(name);
19265 if (fp != NULL)
19267 if (!eap->forceit)
19269 emsg_funcname(e_funcexts, name);
19270 goto erret;
19272 if (fp->uf_calls > 0)
19274 emsg_funcname("E127: Cannot redefine function %s: It is in use",
19275 name);
19276 goto erret;
19278 /* redefine existing function */
19279 ga_clear_strings(&(fp->uf_args));
19280 ga_clear_strings(&(fp->uf_lines));
19281 vim_free(name);
19282 name = NULL;
19285 else
19287 char numbuf[20];
19289 fp = NULL;
19290 if (fudi.fd_newkey == NULL && !eap->forceit)
19292 EMSG(_(e_funcdict));
19293 goto erret;
19295 if (fudi.fd_di == NULL)
19297 /* Can't add a function to a locked dictionary */
19298 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
19299 goto erret;
19301 /* Can't change an existing function if it is locked */
19302 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
19303 goto erret;
19305 /* Give the function a sequential number. Can only be used with a
19306 * Funcref! */
19307 vim_free(name);
19308 sprintf(numbuf, "%d", ++func_nr);
19309 name = vim_strsave((char_u *)numbuf);
19310 if (name == NULL)
19311 goto erret;
19314 if (fp == NULL)
19316 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
19318 int slen, plen;
19319 char_u *scriptname;
19321 /* Check that the autoload name matches the script name. */
19322 j = FAIL;
19323 if (sourcing_name != NULL)
19325 scriptname = autoload_name(name);
19326 if (scriptname != NULL)
19328 p = vim_strchr(scriptname, '/');
19329 plen = (int)STRLEN(p);
19330 slen = (int)STRLEN(sourcing_name);
19331 if (slen > plen && fnamecmp(p,
19332 sourcing_name + slen - plen) == 0)
19333 j = OK;
19334 vim_free(scriptname);
19337 if (j == FAIL)
19339 EMSG2(_("E746: Function name does not match script file name: %s"), name);
19340 goto erret;
19344 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
19345 if (fp == NULL)
19346 goto erret;
19348 if (fudi.fd_dict != NULL)
19350 if (fudi.fd_di == NULL)
19352 /* add new dict entry */
19353 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
19354 if (fudi.fd_di == NULL)
19356 vim_free(fp);
19357 goto erret;
19359 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
19361 vim_free(fudi.fd_di);
19362 vim_free(fp);
19363 goto erret;
19366 else
19367 /* overwrite existing dict entry */
19368 clear_tv(&fudi.fd_di->di_tv);
19369 fudi.fd_di->di_tv.v_type = VAR_FUNC;
19370 fudi.fd_di->di_tv.v_lock = 0;
19371 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
19372 fp->uf_refcount = 1;
19374 /* behave like "dict" was used */
19375 flags |= FC_DICT;
19378 /* insert the new function in the function list */
19379 STRCPY(fp->uf_name, name);
19380 hash_add(&func_hashtab, UF2HIKEY(fp));
19382 fp->uf_args = newargs;
19383 fp->uf_lines = newlines;
19384 #ifdef FEAT_PROFILE
19385 fp->uf_tml_count = NULL;
19386 fp->uf_tml_total = NULL;
19387 fp->uf_tml_self = NULL;
19388 fp->uf_profiling = FALSE;
19389 if (prof_def_func())
19390 func_do_profile(fp);
19391 #endif
19392 fp->uf_varargs = varargs;
19393 fp->uf_flags = flags;
19394 fp->uf_calls = 0;
19395 fp->uf_script_ID = current_SID;
19396 goto ret_free;
19398 erret:
19399 ga_clear_strings(&newargs);
19400 ga_clear_strings(&newlines);
19401 ret_free:
19402 vim_free(skip_until);
19403 vim_free(fudi.fd_newkey);
19404 vim_free(name);
19405 did_emsg |= saved_did_emsg;
19409 * Get a function name, translating "<SID>" and "<SNR>".
19410 * Also handles a Funcref in a List or Dictionary.
19411 * Returns the function name in allocated memory, or NULL for failure.
19412 * flags:
19413 * TFN_INT: internal function name OK
19414 * TFN_QUIET: be quiet
19415 * Advances "pp" to just after the function name (if no error).
19417 static char_u *
19418 trans_function_name(pp, skip, flags, fdp)
19419 char_u **pp;
19420 int skip; /* only find the end, don't evaluate */
19421 int flags;
19422 funcdict_T *fdp; /* return: info about dictionary used */
19424 char_u *name = NULL;
19425 char_u *start;
19426 char_u *end;
19427 int lead;
19428 char_u sid_buf[20];
19429 int len;
19430 lval_T lv;
19432 if (fdp != NULL)
19433 vim_memset(fdp, 0, sizeof(funcdict_T));
19434 start = *pp;
19436 /* Check for hard coded <SNR>: already translated function ID (from a user
19437 * command). */
19438 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
19439 && (*pp)[2] == (int)KE_SNR)
19441 *pp += 3;
19442 len = get_id_len(pp) + 3;
19443 return vim_strnsave(start, len);
19446 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
19447 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
19448 lead = eval_fname_script(start);
19449 if (lead > 2)
19450 start += lead;
19452 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
19453 lead > 2 ? 0 : FNE_CHECK_START);
19454 if (end == start)
19456 if (!skip)
19457 EMSG(_("E129: Function name required"));
19458 goto theend;
19460 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
19463 * Report an invalid expression in braces, unless the expression
19464 * evaluation has been cancelled due to an aborting error, an
19465 * interrupt, or an exception.
19467 if (!aborting())
19469 if (end != NULL)
19470 EMSG2(_(e_invarg2), start);
19472 else
19473 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
19474 goto theend;
19477 if (lv.ll_tv != NULL)
19479 if (fdp != NULL)
19481 fdp->fd_dict = lv.ll_dict;
19482 fdp->fd_newkey = lv.ll_newkey;
19483 lv.ll_newkey = NULL;
19484 fdp->fd_di = lv.ll_di;
19486 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
19488 name = vim_strsave(lv.ll_tv->vval.v_string);
19489 *pp = end;
19491 else
19493 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
19494 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
19495 EMSG(_(e_funcref));
19496 else
19497 *pp = end;
19498 name = NULL;
19500 goto theend;
19503 if (lv.ll_name == NULL)
19505 /* Error found, but continue after the function name. */
19506 *pp = end;
19507 goto theend;
19510 /* Check if the name is a Funcref. If so, use the value. */
19511 if (lv.ll_exp_name != NULL)
19513 len = (int)STRLEN(lv.ll_exp_name);
19514 name = deref_func_name(lv.ll_exp_name, &len);
19515 if (name == lv.ll_exp_name)
19516 name = NULL;
19518 else
19520 len = (int)(end - *pp);
19521 name = deref_func_name(*pp, &len);
19522 if (name == *pp)
19523 name = NULL;
19525 if (name != NULL)
19527 name = vim_strsave(name);
19528 *pp = end;
19529 goto theend;
19532 if (lv.ll_exp_name != NULL)
19534 len = (int)STRLEN(lv.ll_exp_name);
19535 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
19536 && STRNCMP(lv.ll_name, "s:", 2) == 0)
19538 /* When there was "s:" already or the name expanded to get a
19539 * leading "s:" then remove it. */
19540 lv.ll_name += 2;
19541 len -= 2;
19542 lead = 2;
19545 else
19547 if (lead == 2) /* skip over "s:" */
19548 lv.ll_name += 2;
19549 len = (int)(end - lv.ll_name);
19553 * Copy the function name to allocated memory.
19554 * Accept <SID>name() inside a script, translate into <SNR>123_name().
19555 * Accept <SNR>123_name() outside a script.
19557 if (skip)
19558 lead = 0; /* do nothing */
19559 else if (lead > 0)
19561 lead = 3;
19562 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
19563 || eval_fname_sid(*pp))
19565 /* It's "s:" or "<SID>" */
19566 if (current_SID <= 0)
19568 EMSG(_(e_usingsid));
19569 goto theend;
19571 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
19572 lead += (int)STRLEN(sid_buf);
19575 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
19577 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
19578 goto theend;
19580 name = alloc((unsigned)(len + lead + 1));
19581 if (name != NULL)
19583 if (lead > 0)
19585 name[0] = K_SPECIAL;
19586 name[1] = KS_EXTRA;
19587 name[2] = (int)KE_SNR;
19588 if (lead > 3) /* If it's "<SID>" */
19589 STRCPY(name + 3, sid_buf);
19591 mch_memmove(name + lead, lv.ll_name, (size_t)len);
19592 name[len + lead] = NUL;
19594 *pp = end;
19596 theend:
19597 clear_lval(&lv);
19598 return name;
19602 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
19603 * Return 2 if "p" starts with "s:".
19604 * Return 0 otherwise.
19606 static int
19607 eval_fname_script(p)
19608 char_u *p;
19610 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
19611 || STRNICMP(p + 1, "SNR>", 4) == 0))
19612 return 5;
19613 if (p[0] == 's' && p[1] == ':')
19614 return 2;
19615 return 0;
19619 * Return TRUE if "p" starts with "<SID>" or "s:".
19620 * Only works if eval_fname_script() returned non-zero for "p"!
19622 static int
19623 eval_fname_sid(p)
19624 char_u *p;
19626 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
19630 * List the head of the function: "name(arg1, arg2)".
19632 static void
19633 list_func_head(fp, indent)
19634 ufunc_T *fp;
19635 int indent;
19637 int j;
19639 msg_start();
19640 if (indent)
19641 MSG_PUTS(" ");
19642 MSG_PUTS("function ");
19643 if (fp->uf_name[0] == K_SPECIAL)
19645 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
19646 msg_puts(fp->uf_name + 3);
19648 else
19649 msg_puts(fp->uf_name);
19650 msg_putchar('(');
19651 for (j = 0; j < fp->uf_args.ga_len; ++j)
19653 if (j)
19654 MSG_PUTS(", ");
19655 msg_puts(FUNCARG(fp, j));
19657 if (fp->uf_varargs)
19659 if (j)
19660 MSG_PUTS(", ");
19661 MSG_PUTS("...");
19663 msg_putchar(')');
19664 msg_clr_eos();
19665 if (p_verbose > 0)
19666 last_set_msg(fp->uf_script_ID);
19670 * Find a function by name, return pointer to it in ufuncs.
19671 * Return NULL for unknown function.
19673 static ufunc_T *
19674 find_func(name)
19675 char_u *name;
19677 hashitem_T *hi;
19679 hi = hash_find(&func_hashtab, name);
19680 if (!HASHITEM_EMPTY(hi))
19681 return HI2UF(hi);
19682 return NULL;
19685 #if defined(EXITFREE) || defined(PROTO)
19686 void
19687 free_all_functions()
19689 hashitem_T *hi;
19691 /* Need to start all over every time, because func_free() may change the
19692 * hash table. */
19693 while (func_hashtab.ht_used > 0)
19694 for (hi = func_hashtab.ht_array; ; ++hi)
19695 if (!HASHITEM_EMPTY(hi))
19697 func_free(HI2UF(hi));
19698 break;
19701 #endif
19704 * Return TRUE if a function "name" exists.
19706 static int
19707 function_exists(name)
19708 char_u *name;
19710 char_u *nm = name;
19711 char_u *p;
19712 int n = FALSE;
19714 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
19715 nm = skipwhite(nm);
19717 /* Only accept "funcname", "funcname ", "funcname (..." and
19718 * "funcname(...", not "funcname!...". */
19719 if (p != NULL && (*nm == NUL || *nm == '('))
19721 if (builtin_function(p))
19722 n = (find_internal_func(p) >= 0);
19723 else
19724 n = (find_func(p) != NULL);
19726 vim_free(p);
19727 return n;
19731 * Return TRUE if "name" looks like a builtin function name: starts with a
19732 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
19734 static int
19735 builtin_function(name)
19736 char_u *name;
19738 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
19739 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
19742 #if defined(FEAT_PROFILE) || defined(PROTO)
19744 * Start profiling function "fp".
19746 static void
19747 func_do_profile(fp)
19748 ufunc_T *fp;
19750 fp->uf_tm_count = 0;
19751 profile_zero(&fp->uf_tm_self);
19752 profile_zero(&fp->uf_tm_total);
19753 if (fp->uf_tml_count == NULL)
19754 fp->uf_tml_count = (int *)alloc_clear((unsigned)
19755 (sizeof(int) * fp->uf_lines.ga_len));
19756 if (fp->uf_tml_total == NULL)
19757 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
19758 (sizeof(proftime_T) * fp->uf_lines.ga_len));
19759 if (fp->uf_tml_self == NULL)
19760 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
19761 (sizeof(proftime_T) * fp->uf_lines.ga_len));
19762 fp->uf_tml_idx = -1;
19763 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
19764 || fp->uf_tml_self == NULL)
19765 return; /* out of memory */
19767 fp->uf_profiling = TRUE;
19771 * Dump the profiling results for all functions in file "fd".
19773 void
19774 func_dump_profile(fd)
19775 FILE *fd;
19777 hashitem_T *hi;
19778 int todo;
19779 ufunc_T *fp;
19780 int i;
19781 ufunc_T **sorttab;
19782 int st_len = 0;
19784 todo = (int)func_hashtab.ht_used;
19785 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
19787 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
19789 if (!HASHITEM_EMPTY(hi))
19791 --todo;
19792 fp = HI2UF(hi);
19793 if (fp->uf_profiling)
19795 if (sorttab != NULL)
19796 sorttab[st_len++] = fp;
19798 if (fp->uf_name[0] == K_SPECIAL)
19799 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
19800 else
19801 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
19802 if (fp->uf_tm_count == 1)
19803 fprintf(fd, "Called 1 time\n");
19804 else
19805 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
19806 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
19807 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
19808 fprintf(fd, "\n");
19809 fprintf(fd, "count total (s) self (s)\n");
19811 for (i = 0; i < fp->uf_lines.ga_len; ++i)
19813 if (FUNCLINE(fp, i) == NULL)
19814 continue;
19815 prof_func_line(fd, fp->uf_tml_count[i],
19816 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
19817 fprintf(fd, "%s\n", FUNCLINE(fp, i));
19819 fprintf(fd, "\n");
19824 if (sorttab != NULL && st_len > 0)
19826 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
19827 prof_total_cmp);
19828 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
19829 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
19830 prof_self_cmp);
19831 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
19835 static void
19836 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
19837 FILE *fd;
19838 ufunc_T **sorttab;
19839 int st_len;
19840 char *title;
19841 int prefer_self; /* when equal print only self time */
19843 int i;
19844 ufunc_T *fp;
19846 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
19847 fprintf(fd, "count total (s) self (s) function\n");
19848 for (i = 0; i < 20 && i < st_len; ++i)
19850 fp = sorttab[i];
19851 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
19852 prefer_self);
19853 if (fp->uf_name[0] == K_SPECIAL)
19854 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
19855 else
19856 fprintf(fd, " %s()\n", fp->uf_name);
19858 fprintf(fd, "\n");
19862 * Print the count and times for one function or function line.
19864 static void
19865 prof_func_line(fd, count, total, self, prefer_self)
19866 FILE *fd;
19867 int count;
19868 proftime_T *total;
19869 proftime_T *self;
19870 int prefer_self; /* when equal print only self time */
19872 if (count > 0)
19874 fprintf(fd, "%5d ", count);
19875 if (prefer_self && profile_equal(total, self))
19876 fprintf(fd, " ");
19877 else
19878 fprintf(fd, "%s ", profile_msg(total));
19879 if (!prefer_self && profile_equal(total, self))
19880 fprintf(fd, " ");
19881 else
19882 fprintf(fd, "%s ", profile_msg(self));
19884 else
19885 fprintf(fd, " ");
19889 * Compare function for total time sorting.
19891 static int
19892 #ifdef __BORLANDC__
19893 _RTLENTRYF
19894 #endif
19895 prof_total_cmp(s1, s2)
19896 const void *s1;
19897 const void *s2;
19899 ufunc_T *p1, *p2;
19901 p1 = *(ufunc_T **)s1;
19902 p2 = *(ufunc_T **)s2;
19903 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
19907 * Compare function for self time sorting.
19909 static int
19910 #ifdef __BORLANDC__
19911 _RTLENTRYF
19912 #endif
19913 prof_self_cmp(s1, s2)
19914 const void *s1;
19915 const void *s2;
19917 ufunc_T *p1, *p2;
19919 p1 = *(ufunc_T **)s1;
19920 p2 = *(ufunc_T **)s2;
19921 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
19924 #endif
19927 * If "name" has a package name try autoloading the script for it.
19928 * Return TRUE if a package was loaded.
19930 static int
19931 script_autoload(name, reload)
19932 char_u *name;
19933 int reload; /* load script again when already loaded */
19935 char_u *p;
19936 char_u *scriptname, *tofree;
19937 int ret = FALSE;
19938 int i;
19940 /* If there is no '#' after name[0] there is no package name. */
19941 p = vim_strchr(name, AUTOLOAD_CHAR);
19942 if (p == NULL || p == name)
19943 return FALSE;
19945 tofree = scriptname = autoload_name(name);
19947 /* Find the name in the list of previously loaded package names. Skip
19948 * "autoload/", it's always the same. */
19949 for (i = 0; i < ga_loaded.ga_len; ++i)
19950 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
19951 break;
19952 if (!reload && i < ga_loaded.ga_len)
19953 ret = FALSE; /* was loaded already */
19954 else
19956 /* Remember the name if it wasn't loaded already. */
19957 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
19959 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
19960 tofree = NULL;
19963 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
19964 if (source_runtime(scriptname, FALSE) == OK)
19965 ret = TRUE;
19968 vim_free(tofree);
19969 return ret;
19973 * Return the autoload script name for a function or variable name.
19974 * Returns NULL when out of memory.
19976 static char_u *
19977 autoload_name(name)
19978 char_u *name;
19980 char_u *p;
19981 char_u *scriptname;
19983 /* Get the script file name: replace '#' with '/', append ".vim". */
19984 scriptname = alloc((unsigned)(STRLEN(name) + 14));
19985 if (scriptname == NULL)
19986 return FALSE;
19987 STRCPY(scriptname, "autoload/");
19988 STRCAT(scriptname, name);
19989 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
19990 STRCAT(scriptname, ".vim");
19991 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
19992 *p = '/';
19993 return scriptname;
19996 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
19999 * Function given to ExpandGeneric() to obtain the list of user defined
20000 * function names.
20002 char_u *
20003 get_user_func_name(xp, idx)
20004 expand_T *xp;
20005 int idx;
20007 static long_u done;
20008 static hashitem_T *hi;
20009 ufunc_T *fp;
20011 if (idx == 0)
20013 done = 0;
20014 hi = func_hashtab.ht_array;
20016 if (done < func_hashtab.ht_used)
20018 if (done++ > 0)
20019 ++hi;
20020 while (HASHITEM_EMPTY(hi))
20021 ++hi;
20022 fp = HI2UF(hi);
20024 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
20025 return fp->uf_name; /* prevents overflow */
20027 cat_func_name(IObuff, fp);
20028 if (xp->xp_context != EXPAND_USER_FUNC)
20030 STRCAT(IObuff, "(");
20031 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
20032 STRCAT(IObuff, ")");
20034 return IObuff;
20036 return NULL;
20039 #endif /* FEAT_CMDL_COMPL */
20042 * Copy the function name of "fp" to buffer "buf".
20043 * "buf" must be able to hold the function name plus three bytes.
20044 * Takes care of script-local function names.
20046 static void
20047 cat_func_name(buf, fp)
20048 char_u *buf;
20049 ufunc_T *fp;
20051 if (fp->uf_name[0] == K_SPECIAL)
20053 STRCPY(buf, "<SNR>");
20054 STRCAT(buf, fp->uf_name + 3);
20056 else
20057 STRCPY(buf, fp->uf_name);
20061 * ":delfunction {name}"
20063 void
20064 ex_delfunction(eap)
20065 exarg_T *eap;
20067 ufunc_T *fp = NULL;
20068 char_u *p;
20069 char_u *name;
20070 funcdict_T fudi;
20072 p = eap->arg;
20073 name = trans_function_name(&p, eap->skip, 0, &fudi);
20074 vim_free(fudi.fd_newkey);
20075 if (name == NULL)
20077 if (fudi.fd_dict != NULL && !eap->skip)
20078 EMSG(_(e_funcref));
20079 return;
20081 if (!ends_excmd(*skipwhite(p)))
20083 vim_free(name);
20084 EMSG(_(e_trailing));
20085 return;
20087 eap->nextcmd = check_nextcmd(p);
20088 if (eap->nextcmd != NULL)
20089 *p = NUL;
20091 if (!eap->skip)
20092 fp = find_func(name);
20093 vim_free(name);
20095 if (!eap->skip)
20097 if (fp == NULL)
20099 EMSG2(_(e_nofunc), eap->arg);
20100 return;
20102 if (fp->uf_calls > 0)
20104 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
20105 return;
20108 if (fudi.fd_dict != NULL)
20110 /* Delete the dict item that refers to the function, it will
20111 * invoke func_unref() and possibly delete the function. */
20112 dictitem_remove(fudi.fd_dict, fudi.fd_di);
20114 else
20115 func_free(fp);
20120 * Free a function and remove it from the list of functions.
20122 static void
20123 func_free(fp)
20124 ufunc_T *fp;
20126 hashitem_T *hi;
20128 /* clear this function */
20129 ga_clear_strings(&(fp->uf_args));
20130 ga_clear_strings(&(fp->uf_lines));
20131 #ifdef FEAT_PROFILE
20132 vim_free(fp->uf_tml_count);
20133 vim_free(fp->uf_tml_total);
20134 vim_free(fp->uf_tml_self);
20135 #endif
20137 /* remove the function from the function hashtable */
20138 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
20139 if (HASHITEM_EMPTY(hi))
20140 EMSG2(_(e_intern2), "func_free()");
20141 else
20142 hash_remove(&func_hashtab, hi);
20144 vim_free(fp);
20148 * Unreference a Function: decrement the reference count and free it when it
20149 * becomes zero. Only for numbered functions.
20151 static void
20152 func_unref(name)
20153 char_u *name;
20155 ufunc_T *fp;
20157 if (name != NULL && isdigit(*name))
20159 fp = find_func(name);
20160 if (fp == NULL)
20161 EMSG2(_(e_intern2), "func_unref()");
20162 else if (--fp->uf_refcount <= 0)
20164 /* Only delete it when it's not being used. Otherwise it's done
20165 * when "uf_calls" becomes zero. */
20166 if (fp->uf_calls == 0)
20167 func_free(fp);
20173 * Count a reference to a Function.
20175 static void
20176 func_ref(name)
20177 char_u *name;
20179 ufunc_T *fp;
20181 if (name != NULL && isdigit(*name))
20183 fp = find_func(name);
20184 if (fp == NULL)
20185 EMSG2(_(e_intern2), "func_ref()");
20186 else
20187 ++fp->uf_refcount;
20192 * Call a user function.
20194 static void
20195 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
20196 ufunc_T *fp; /* pointer to function */
20197 int argcount; /* nr of args */
20198 typval_T *argvars; /* arguments */
20199 typval_T *rettv; /* return value */
20200 linenr_T firstline; /* first line of range */
20201 linenr_T lastline; /* last line of range */
20202 dict_T *selfdict; /* Dictionary for "self" */
20204 char_u *save_sourcing_name;
20205 linenr_T save_sourcing_lnum;
20206 scid_T save_current_SID;
20207 funccall_T fc;
20208 int save_did_emsg;
20209 static int depth = 0;
20210 dictitem_T *v;
20211 int fixvar_idx = 0; /* index in fixvar[] */
20212 int i;
20213 int ai;
20214 char_u numbuf[NUMBUFLEN];
20215 char_u *name;
20216 #ifdef FEAT_PROFILE
20217 proftime_T wait_start;
20218 proftime_T call_start;
20219 #endif
20221 /* If depth of calling is getting too high, don't execute the function */
20222 if (depth >= p_mfd)
20224 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
20225 rettv->v_type = VAR_NUMBER;
20226 rettv->vval.v_number = -1;
20227 return;
20229 ++depth;
20231 line_breakcheck(); /* check for CTRL-C hit */
20233 fc.caller = current_funccal;
20234 current_funccal = &fc;
20235 fc.func = fp;
20236 fc.rettv = rettv;
20237 rettv->vval.v_number = 0;
20238 fc.linenr = 0;
20239 fc.returned = FALSE;
20240 fc.level = ex_nesting_level;
20241 /* Check if this function has a breakpoint. */
20242 fc.breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
20243 fc.dbg_tick = debug_tick;
20246 * Note about using fc.fixvar[]: This is an array of FIXVAR_CNT variables
20247 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
20248 * each argument variable and saves a lot of time.
20251 * Init l: variables.
20253 init_var_dict(&fc.l_vars, &fc.l_vars_var);
20254 if (selfdict != NULL)
20256 /* Set l:self to "selfdict". Use "name" to avoid a warning from
20257 * some compiler that checks the destination size. */
20258 v = &fc.fixvar[fixvar_idx++].var;
20259 name = v->di_key;
20260 STRCPY(name, "self");
20261 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
20262 hash_add(&fc.l_vars.dv_hashtab, DI2HIKEY(v));
20263 v->di_tv.v_type = VAR_DICT;
20264 v->di_tv.v_lock = 0;
20265 v->di_tv.vval.v_dict = selfdict;
20266 ++selfdict->dv_refcount;
20270 * Init a: variables.
20271 * Set a:0 to "argcount".
20272 * Set a:000 to a list with room for the "..." arguments.
20274 init_var_dict(&fc.l_avars, &fc.l_avars_var);
20275 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "0",
20276 (varnumber_T)(argcount - fp->uf_args.ga_len));
20277 v = &fc.fixvar[fixvar_idx++].var;
20278 STRCPY(v->di_key, "000");
20279 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20280 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
20281 v->di_tv.v_type = VAR_LIST;
20282 v->di_tv.v_lock = VAR_FIXED;
20283 v->di_tv.vval.v_list = &fc.l_varlist;
20284 vim_memset(&fc.l_varlist, 0, sizeof(list_T));
20285 fc.l_varlist.lv_refcount = 99999;
20286 fc.l_varlist.lv_lock = VAR_FIXED;
20289 * Set a:firstline to "firstline" and a:lastline to "lastline".
20290 * Set a:name to named arguments.
20291 * Set a:N to the "..." arguments.
20293 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "firstline",
20294 (varnumber_T)firstline);
20295 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "lastline",
20296 (varnumber_T)lastline);
20297 for (i = 0; i < argcount; ++i)
20299 ai = i - fp->uf_args.ga_len;
20300 if (ai < 0)
20301 /* named argument a:name */
20302 name = FUNCARG(fp, i);
20303 else
20305 /* "..." argument a:1, a:2, etc. */
20306 sprintf((char *)numbuf, "%d", ai + 1);
20307 name = numbuf;
20309 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
20311 v = &fc.fixvar[fixvar_idx++].var;
20312 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20314 else
20316 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
20317 + STRLEN(name)));
20318 if (v == NULL)
20319 break;
20320 v->di_flags = DI_FLAGS_RO;
20322 STRCPY(v->di_key, name);
20323 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
20325 /* Note: the values are copied directly to avoid alloc/free.
20326 * "argvars" must have VAR_FIXED for v_lock. */
20327 v->di_tv = argvars[i];
20328 v->di_tv.v_lock = VAR_FIXED;
20330 if (ai >= 0 && ai < MAX_FUNC_ARGS)
20332 list_append(&fc.l_varlist, &fc.l_listitems[ai]);
20333 fc.l_listitems[ai].li_tv = argvars[i];
20334 fc.l_listitems[ai].li_tv.v_lock = VAR_FIXED;
20338 /* Don't redraw while executing the function. */
20339 ++RedrawingDisabled;
20340 save_sourcing_name = sourcing_name;
20341 save_sourcing_lnum = sourcing_lnum;
20342 sourcing_lnum = 1;
20343 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
20344 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
20345 if (sourcing_name != NULL)
20347 if (save_sourcing_name != NULL
20348 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
20349 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
20350 else
20351 STRCPY(sourcing_name, "function ");
20352 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
20354 if (p_verbose >= 12)
20356 ++no_wait_return;
20357 verbose_enter_scroll();
20359 smsg((char_u *)_("calling %s"), sourcing_name);
20360 if (p_verbose >= 14)
20362 char_u buf[MSG_BUF_LEN];
20363 char_u numbuf2[NUMBUFLEN];
20364 char_u *tofree;
20365 char_u *s;
20367 msg_puts((char_u *)"(");
20368 for (i = 0; i < argcount; ++i)
20370 if (i > 0)
20371 msg_puts((char_u *)", ");
20372 if (argvars[i].v_type == VAR_NUMBER)
20373 msg_outnum((long)argvars[i].vval.v_number);
20374 else
20376 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
20377 if (s != NULL)
20379 trunc_string(s, buf, MSG_BUF_CLEN);
20380 msg_puts(buf);
20381 vim_free(tofree);
20385 msg_puts((char_u *)")");
20387 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20389 verbose_leave_scroll();
20390 --no_wait_return;
20393 #ifdef FEAT_PROFILE
20394 if (do_profiling == PROF_YES)
20396 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
20397 func_do_profile(fp);
20398 if (fp->uf_profiling
20399 || (fc.caller != NULL && &fc.caller->func->uf_profiling))
20401 ++fp->uf_tm_count;
20402 profile_start(&call_start);
20403 profile_zero(&fp->uf_tm_children);
20405 script_prof_save(&wait_start);
20407 #endif
20409 save_current_SID = current_SID;
20410 current_SID = fp->uf_script_ID;
20411 save_did_emsg = did_emsg;
20412 did_emsg = FALSE;
20414 /* call do_cmdline() to execute the lines */
20415 do_cmdline(NULL, get_func_line, (void *)&fc,
20416 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
20418 --RedrawingDisabled;
20420 /* when the function was aborted because of an error, return -1 */
20421 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
20423 clear_tv(rettv);
20424 rettv->v_type = VAR_NUMBER;
20425 rettv->vval.v_number = -1;
20428 #ifdef FEAT_PROFILE
20429 if (do_profiling == PROF_YES && (fp->uf_profiling
20430 || (fc.caller != NULL && &fc.caller->func->uf_profiling)))
20432 profile_end(&call_start);
20433 profile_sub_wait(&wait_start, &call_start);
20434 profile_add(&fp->uf_tm_total, &call_start);
20435 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
20436 if (fc.caller != NULL && &fc.caller->func->uf_profiling)
20438 profile_add(&fc.caller->func->uf_tm_children, &call_start);
20439 profile_add(&fc.caller->func->uf_tml_children, &call_start);
20442 #endif
20444 /* when being verbose, mention the return value */
20445 if (p_verbose >= 12)
20447 ++no_wait_return;
20448 verbose_enter_scroll();
20450 if (aborting())
20451 smsg((char_u *)_("%s aborted"), sourcing_name);
20452 else if (fc.rettv->v_type == VAR_NUMBER)
20453 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
20454 (long)fc.rettv->vval.v_number);
20455 else
20457 char_u buf[MSG_BUF_LEN];
20458 char_u numbuf2[NUMBUFLEN];
20459 char_u *tofree;
20460 char_u *s;
20462 /* The value may be very long. Skip the middle part, so that we
20463 * have some idea how it starts and ends. smsg() would always
20464 * truncate it at the end. */
20465 s = tv2string(fc.rettv, &tofree, numbuf2, 0);
20466 if (s != NULL)
20468 trunc_string(s, buf, MSG_BUF_CLEN);
20469 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
20470 vim_free(tofree);
20473 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20475 verbose_leave_scroll();
20476 --no_wait_return;
20479 vim_free(sourcing_name);
20480 sourcing_name = save_sourcing_name;
20481 sourcing_lnum = save_sourcing_lnum;
20482 current_SID = save_current_SID;
20483 #ifdef FEAT_PROFILE
20484 if (do_profiling == PROF_YES)
20485 script_prof_restore(&wait_start);
20486 #endif
20488 if (p_verbose >= 12 && sourcing_name != NULL)
20490 ++no_wait_return;
20491 verbose_enter_scroll();
20493 smsg((char_u *)_("continuing in %s"), sourcing_name);
20494 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20496 verbose_leave_scroll();
20497 --no_wait_return;
20500 did_emsg |= save_did_emsg;
20501 current_funccal = fc.caller;
20503 /* The a: variables typevals were not alloced, only free the allocated
20504 * variables. */
20505 vars_clear_ext(&fc.l_avars.dv_hashtab, FALSE);
20507 vars_clear(&fc.l_vars.dv_hashtab); /* free all l: variables */
20508 --depth;
20512 * Add a number variable "name" to dict "dp" with value "nr".
20514 static void
20515 add_nr_var(dp, v, name, nr)
20516 dict_T *dp;
20517 dictitem_T *v;
20518 char *name;
20519 varnumber_T nr;
20521 STRCPY(v->di_key, name);
20522 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20523 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
20524 v->di_tv.v_type = VAR_NUMBER;
20525 v->di_tv.v_lock = VAR_FIXED;
20526 v->di_tv.vval.v_number = nr;
20530 * ":return [expr]"
20532 void
20533 ex_return(eap)
20534 exarg_T *eap;
20536 char_u *arg = eap->arg;
20537 typval_T rettv;
20538 int returning = FALSE;
20540 if (current_funccal == NULL)
20542 EMSG(_("E133: :return not inside a function"));
20543 return;
20546 if (eap->skip)
20547 ++emsg_skip;
20549 eap->nextcmd = NULL;
20550 if ((*arg != NUL && *arg != '|' && *arg != '\n')
20551 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
20553 if (!eap->skip)
20554 returning = do_return(eap, FALSE, TRUE, &rettv);
20555 else
20556 clear_tv(&rettv);
20558 /* It's safer to return also on error. */
20559 else if (!eap->skip)
20562 * Return unless the expression evaluation has been cancelled due to an
20563 * aborting error, an interrupt, or an exception.
20565 if (!aborting())
20566 returning = do_return(eap, FALSE, TRUE, NULL);
20569 /* When skipping or the return gets pending, advance to the next command
20570 * in this line (!returning). Otherwise, ignore the rest of the line.
20571 * Following lines will be ignored by get_func_line(). */
20572 if (returning)
20573 eap->nextcmd = NULL;
20574 else if (eap->nextcmd == NULL) /* no argument */
20575 eap->nextcmd = check_nextcmd(arg);
20577 if (eap->skip)
20578 --emsg_skip;
20582 * Return from a function. Possibly makes the return pending. Also called
20583 * for a pending return at the ":endtry" or after returning from an extra
20584 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
20585 * when called due to a ":return" command. "rettv" may point to a typval_T
20586 * with the return rettv. Returns TRUE when the return can be carried out,
20587 * FALSE when the return gets pending.
20590 do_return(eap, reanimate, is_cmd, rettv)
20591 exarg_T *eap;
20592 int reanimate;
20593 int is_cmd;
20594 void *rettv;
20596 int idx;
20597 struct condstack *cstack = eap->cstack;
20599 if (reanimate)
20600 /* Undo the return. */
20601 current_funccal->returned = FALSE;
20604 * Cleanup (and inactivate) conditionals, but stop when a try conditional
20605 * not in its finally clause (which then is to be executed next) is found.
20606 * In this case, make the ":return" pending for execution at the ":endtry".
20607 * Otherwise, return normally.
20609 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
20610 if (idx >= 0)
20612 cstack->cs_pending[idx] = CSTP_RETURN;
20614 if (!is_cmd && !reanimate)
20615 /* A pending return again gets pending. "rettv" points to an
20616 * allocated variable with the rettv of the original ":return"'s
20617 * argument if present or is NULL else. */
20618 cstack->cs_rettv[idx] = rettv;
20619 else
20621 /* When undoing a return in order to make it pending, get the stored
20622 * return rettv. */
20623 if (reanimate)
20624 rettv = current_funccal->rettv;
20626 if (rettv != NULL)
20628 /* Store the value of the pending return. */
20629 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
20630 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
20631 else
20632 EMSG(_(e_outofmem));
20634 else
20635 cstack->cs_rettv[idx] = NULL;
20637 if (reanimate)
20639 /* The pending return value could be overwritten by a ":return"
20640 * without argument in a finally clause; reset the default
20641 * return value. */
20642 current_funccal->rettv->v_type = VAR_NUMBER;
20643 current_funccal->rettv->vval.v_number = 0;
20646 report_make_pending(CSTP_RETURN, rettv);
20648 else
20650 current_funccal->returned = TRUE;
20652 /* If the return is carried out now, store the return value. For
20653 * a return immediately after reanimation, the value is already
20654 * there. */
20655 if (!reanimate && rettv != NULL)
20657 clear_tv(current_funccal->rettv);
20658 *current_funccal->rettv = *(typval_T *)rettv;
20659 if (!is_cmd)
20660 vim_free(rettv);
20664 return idx < 0;
20668 * Free the variable with a pending return value.
20670 void
20671 discard_pending_return(rettv)
20672 void *rettv;
20674 free_tv((typval_T *)rettv);
20678 * Generate a return command for producing the value of "rettv". The result
20679 * is an allocated string. Used by report_pending() for verbose messages.
20681 char_u *
20682 get_return_cmd(rettv)
20683 void *rettv;
20685 char_u *s = NULL;
20686 char_u *tofree = NULL;
20687 char_u numbuf[NUMBUFLEN];
20689 if (rettv != NULL)
20690 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
20691 if (s == NULL)
20692 s = (char_u *)"";
20694 STRCPY(IObuff, ":return ");
20695 STRNCPY(IObuff + 8, s, IOSIZE - 8);
20696 if (STRLEN(s) + 8 >= IOSIZE)
20697 STRCPY(IObuff + IOSIZE - 4, "...");
20698 vim_free(tofree);
20699 return vim_strsave(IObuff);
20703 * Get next function line.
20704 * Called by do_cmdline() to get the next line.
20705 * Returns allocated string, or NULL for end of function.
20707 /* ARGSUSED */
20708 char_u *
20709 get_func_line(c, cookie, indent)
20710 int c; /* not used */
20711 void *cookie;
20712 int indent; /* not used */
20714 funccall_T *fcp = (funccall_T *)cookie;
20715 ufunc_T *fp = fcp->func;
20716 char_u *retval;
20717 garray_T *gap; /* growarray with function lines */
20719 /* If breakpoints have been added/deleted need to check for it. */
20720 if (fcp->dbg_tick != debug_tick)
20722 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
20723 sourcing_lnum);
20724 fcp->dbg_tick = debug_tick;
20726 #ifdef FEAT_PROFILE
20727 if (do_profiling == PROF_YES)
20728 func_line_end(cookie);
20729 #endif
20731 gap = &fp->uf_lines;
20732 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
20733 || fcp->returned)
20734 retval = NULL;
20735 else
20737 /* Skip NULL lines (continuation lines). */
20738 while (fcp->linenr < gap->ga_len
20739 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
20740 ++fcp->linenr;
20741 if (fcp->linenr >= gap->ga_len)
20742 retval = NULL;
20743 else
20745 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
20746 sourcing_lnum = fcp->linenr;
20747 #ifdef FEAT_PROFILE
20748 if (do_profiling == PROF_YES)
20749 func_line_start(cookie);
20750 #endif
20754 /* Did we encounter a breakpoint? */
20755 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
20757 dbg_breakpoint(fp->uf_name, sourcing_lnum);
20758 /* Find next breakpoint. */
20759 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
20760 sourcing_lnum);
20761 fcp->dbg_tick = debug_tick;
20764 return retval;
20767 #if defined(FEAT_PROFILE) || defined(PROTO)
20769 * Called when starting to read a function line.
20770 * "sourcing_lnum" must be correct!
20771 * When skipping lines it may not actually be executed, but we won't find out
20772 * until later and we need to store the time now.
20774 void
20775 func_line_start(cookie)
20776 void *cookie;
20778 funccall_T *fcp = (funccall_T *)cookie;
20779 ufunc_T *fp = fcp->func;
20781 if (fp->uf_profiling && sourcing_lnum >= 1
20782 && sourcing_lnum <= fp->uf_lines.ga_len)
20784 fp->uf_tml_idx = sourcing_lnum - 1;
20785 /* Skip continuation lines. */
20786 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
20787 --fp->uf_tml_idx;
20788 fp->uf_tml_execed = FALSE;
20789 profile_start(&fp->uf_tml_start);
20790 profile_zero(&fp->uf_tml_children);
20791 profile_get_wait(&fp->uf_tml_wait);
20796 * Called when actually executing a function line.
20798 void
20799 func_line_exec(cookie)
20800 void *cookie;
20802 funccall_T *fcp = (funccall_T *)cookie;
20803 ufunc_T *fp = fcp->func;
20805 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
20806 fp->uf_tml_execed = TRUE;
20810 * Called when done with a function line.
20812 void
20813 func_line_end(cookie)
20814 void *cookie;
20816 funccall_T *fcp = (funccall_T *)cookie;
20817 ufunc_T *fp = fcp->func;
20819 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
20821 if (fp->uf_tml_execed)
20823 ++fp->uf_tml_count[fp->uf_tml_idx];
20824 profile_end(&fp->uf_tml_start);
20825 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
20826 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
20827 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
20828 &fp->uf_tml_children);
20830 fp->uf_tml_idx = -1;
20833 #endif
20836 * Return TRUE if the currently active function should be ended, because a
20837 * return was encountered or an error occured. Used inside a ":while".
20840 func_has_ended(cookie)
20841 void *cookie;
20843 funccall_T *fcp = (funccall_T *)cookie;
20845 /* Ignore the "abort" flag if the abortion behavior has been changed due to
20846 * an error inside a try conditional. */
20847 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
20848 || fcp->returned);
20852 * return TRUE if cookie indicates a function which "abort"s on errors.
20855 func_has_abort(cookie)
20856 void *cookie;
20858 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
20861 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
20862 typedef enum
20864 VAR_FLAVOUR_DEFAULT,
20865 VAR_FLAVOUR_SESSION,
20866 VAR_FLAVOUR_VIMINFO
20867 } var_flavour_T;
20869 static var_flavour_T var_flavour __ARGS((char_u *varname));
20871 static var_flavour_T
20872 var_flavour(varname)
20873 char_u *varname;
20875 char_u *p = varname;
20877 if (ASCII_ISUPPER(*p))
20879 while (*(++p))
20880 if (ASCII_ISLOWER(*p))
20881 return VAR_FLAVOUR_SESSION;
20882 return VAR_FLAVOUR_VIMINFO;
20884 else
20885 return VAR_FLAVOUR_DEFAULT;
20887 #endif
20889 #if defined(FEAT_VIMINFO) || defined(PROTO)
20891 * Restore global vars that start with a capital from the viminfo file
20894 read_viminfo_varlist(virp, writing)
20895 vir_T *virp;
20896 int writing;
20898 char_u *tab;
20899 int is_string = FALSE;
20900 typval_T tv;
20902 if (!writing && (find_viminfo_parameter('!') != NULL))
20904 tab = vim_strchr(virp->vir_line + 1, '\t');
20905 if (tab != NULL)
20907 *tab++ = '\0'; /* isolate the variable name */
20908 if (*tab == 'S') /* string var */
20909 is_string = TRUE;
20911 tab = vim_strchr(tab, '\t');
20912 if (tab != NULL)
20914 if (is_string)
20916 tv.v_type = VAR_STRING;
20917 tv.vval.v_string = viminfo_readstring(virp,
20918 (int)(tab - virp->vir_line + 1), TRUE);
20920 else
20922 tv.v_type = VAR_NUMBER;
20923 tv.vval.v_number = atol((char *)tab + 1);
20925 set_var(virp->vir_line + 1, &tv, FALSE);
20926 if (is_string)
20927 vim_free(tv.vval.v_string);
20932 return viminfo_readline(virp);
20936 * Write global vars that start with a capital to the viminfo file
20938 void
20939 write_viminfo_varlist(fp)
20940 FILE *fp;
20942 hashitem_T *hi;
20943 dictitem_T *this_var;
20944 int todo;
20945 char *s;
20946 char_u *p;
20947 char_u *tofree;
20948 char_u numbuf[NUMBUFLEN];
20950 if (find_viminfo_parameter('!') == NULL)
20951 return;
20953 fprintf(fp, _("\n# global variables:\n"));
20955 todo = (int)globvarht.ht_used;
20956 for (hi = globvarht.ht_array; todo > 0; ++hi)
20958 if (!HASHITEM_EMPTY(hi))
20960 --todo;
20961 this_var = HI2DI(hi);
20962 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
20964 switch (this_var->di_tv.v_type)
20966 case VAR_STRING: s = "STR"; break;
20967 case VAR_NUMBER: s = "NUM"; break;
20968 default: continue;
20970 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
20971 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
20972 if (p != NULL)
20973 viminfo_writestring(fp, p);
20974 vim_free(tofree);
20979 #endif
20981 #if defined(FEAT_SESSION) || defined(PROTO)
20983 store_session_globals(fd)
20984 FILE *fd;
20986 hashitem_T *hi;
20987 dictitem_T *this_var;
20988 int todo;
20989 char_u *p, *t;
20991 todo = (int)globvarht.ht_used;
20992 for (hi = globvarht.ht_array; todo > 0; ++hi)
20994 if (!HASHITEM_EMPTY(hi))
20996 --todo;
20997 this_var = HI2DI(hi);
20998 if ((this_var->di_tv.v_type == VAR_NUMBER
20999 || this_var->di_tv.v_type == VAR_STRING)
21000 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
21002 /* Escape special characters with a backslash. Turn a LF and
21003 * CR into \n and \r. */
21004 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
21005 (char_u *)"\\\"\n\r");
21006 if (p == NULL) /* out of memory */
21007 break;
21008 for (t = p; *t != NUL; ++t)
21009 if (*t == '\n')
21010 *t = 'n';
21011 else if (*t == '\r')
21012 *t = 'r';
21013 if ((fprintf(fd, "let %s = %c%s%c",
21014 this_var->di_key,
21015 (this_var->di_tv.v_type == VAR_STRING) ? '"'
21016 : ' ',
21018 (this_var->di_tv.v_type == VAR_STRING) ? '"'
21019 : ' ') < 0)
21020 || put_eol(fd) == FAIL)
21022 vim_free(p);
21023 return FAIL;
21025 vim_free(p);
21029 return OK;
21031 #endif
21034 * Display script name where an item was last set.
21035 * Should only be invoked when 'verbose' is non-zero.
21037 void
21038 last_set_msg(scriptID)
21039 scid_T scriptID;
21041 char_u *p;
21043 if (scriptID != 0)
21045 p = home_replace_save(NULL, get_scriptname(scriptID));
21046 if (p != NULL)
21048 verbose_enter();
21049 MSG_PUTS(_("\n\tLast set from "));
21050 MSG_PUTS(p);
21051 vim_free(p);
21052 verbose_leave();
21057 #endif /* FEAT_EVAL */
21059 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
21062 #ifdef WIN3264
21064 * Functions for ":8" filename modifier: get 8.3 version of a filename.
21066 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
21067 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
21068 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
21071 * Get the short pathname of a file.
21072 * Returns 1 on success. *fnamelen is 0 for nonexistent path.
21074 static int
21075 get_short_pathname(fnamep, bufp, fnamelen)
21076 char_u **fnamep;
21077 char_u **bufp;
21078 int *fnamelen;
21080 int l,len;
21081 char_u *newbuf;
21083 len = *fnamelen;
21085 l = GetShortPathName(*fnamep, *fnamep, len);
21086 if (l > len - 1)
21088 /* If that doesn't work (not enough space), then save the string
21089 * and try again with a new buffer big enough
21091 newbuf = vim_strnsave(*fnamep, l);
21092 if (newbuf == NULL)
21093 return 0;
21095 vim_free(*bufp);
21096 *fnamep = *bufp = newbuf;
21098 l = GetShortPathName(*fnamep,*fnamep,l+1);
21100 /* Really should always succeed, as the buffer is big enough */
21103 *fnamelen = l;
21104 return 1;
21108 * Create a short path name. Returns the length of the buffer it needs.
21109 * Doesn't copy over the end of the buffer passed in.
21111 static int
21112 shortpath_for_invalid_fname(fname, bufp, fnamelen)
21113 char_u **fname;
21114 char_u **bufp;
21115 int *fnamelen;
21117 char_u *s, *p, *pbuf2, *pbuf3;
21118 char_u ch;
21119 int len, len2, plen, slen;
21121 /* Make a copy */
21122 len2 = *fnamelen;
21123 pbuf2 = vim_strnsave(*fname, len2);
21124 pbuf3 = NULL;
21126 s = pbuf2 + len2 - 1; /* Find the end */
21127 slen = 1;
21128 plen = len2;
21130 if (after_pathsep(pbuf2, s + 1))
21132 --s;
21133 ++slen;
21134 --plen;
21139 /* Go back one path-separator */
21140 while (s > pbuf2 && !after_pathsep(pbuf2, s + 1))
21142 --s;
21143 ++slen;
21144 --plen;
21146 if (s <= pbuf2)
21147 break;
21149 /* Remember the character that is about to be splatted */
21150 ch = *s;
21151 *s = 0; /* get_short_pathname requires a null-terminated string */
21153 /* Try it in situ */
21154 p = pbuf2;
21155 if (!get_short_pathname(&p, &pbuf3, &plen))
21157 vim_free(pbuf2);
21158 return -1;
21160 *s = ch; /* Preserve the string */
21161 } while (plen == 0);
21163 if (plen > 0)
21165 /* Remember the length of the new string. */
21166 *fnamelen = len = plen + slen;
21167 vim_free(*bufp);
21168 if (len > len2)
21170 /* If there's not enough space in the currently allocated string,
21171 * then copy it to a buffer big enough.
21173 *fname= *bufp = vim_strnsave(p, len);
21174 if (*fname == NULL)
21175 return -1;
21177 else
21179 /* Transfer pbuf2 to being the main buffer (it's big enough) */
21180 *fname = *bufp = pbuf2;
21181 if (p != pbuf2)
21182 strncpy(*fname, p, plen);
21183 pbuf2 = NULL;
21185 /* Concat the next bit */
21186 strncpy(*fname + plen, s, slen);
21187 (*fname)[len] = '\0';
21189 vim_free(pbuf3);
21190 vim_free(pbuf2);
21191 return 0;
21195 * Get a pathname for a partial path.
21197 static int
21198 shortpath_for_partial(fnamep, bufp, fnamelen)
21199 char_u **fnamep;
21200 char_u **bufp;
21201 int *fnamelen;
21203 int sepcount, len, tflen;
21204 char_u *p;
21205 char_u *pbuf, *tfname;
21206 int hasTilde;
21208 /* Count up the path seperators from the RHS.. so we know which part
21209 * of the path to return.
21211 sepcount = 0;
21212 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
21213 if (vim_ispathsep(*p))
21214 ++sepcount;
21216 /* Need full path first (use expand_env() to remove a "~/") */
21217 hasTilde = (**fnamep == '~');
21218 if (hasTilde)
21219 pbuf = tfname = expand_env_save(*fnamep);
21220 else
21221 pbuf = tfname = FullName_save(*fnamep, FALSE);
21223 len = tflen = (int)STRLEN(tfname);
21225 if (!get_short_pathname(&tfname, &pbuf, &len))
21226 return -1;
21228 if (len == 0)
21230 /* Don't have a valid filename, so shorten the rest of the
21231 * path if we can. This CAN give us invalid 8.3 filenames, but
21232 * there's not a lot of point in guessing what it might be.
21234 len = tflen;
21235 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == -1)
21236 return -1;
21239 /* Count the paths backward to find the beginning of the desired string. */
21240 for (p = tfname + len - 1; p >= tfname; --p)
21242 #ifdef FEAT_MBYTE
21243 if (has_mbyte)
21244 p -= mb_head_off(tfname, p);
21245 #endif
21246 if (vim_ispathsep(*p))
21248 if (sepcount == 0 || (hasTilde && sepcount == 1))
21249 break;
21250 else
21251 sepcount --;
21254 if (hasTilde)
21256 --p;
21257 if (p >= tfname)
21258 *p = '~';
21259 else
21260 return -1;
21262 else
21263 ++p;
21265 /* Copy in the string - p indexes into tfname - allocated at pbuf */
21266 vim_free(*bufp);
21267 *fnamelen = (int)STRLEN(p);
21268 *bufp = pbuf;
21269 *fnamep = p;
21271 return 0;
21273 #endif /* WIN3264 */
21276 * Adjust a filename, according to a string of modifiers.
21277 * *fnamep must be NUL terminated when called. When returning, the length is
21278 * determined by *fnamelen.
21279 * Returns valid flags.
21280 * When there is an error, *fnamep is set to NULL.
21283 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
21284 char_u *src; /* string with modifiers */
21285 int *usedlen; /* characters after src that are used */
21286 char_u **fnamep; /* file name so far */
21287 char_u **bufp; /* buffer for allocated file name or NULL */
21288 int *fnamelen; /* length of fnamep */
21290 int valid = 0;
21291 char_u *tail;
21292 char_u *s, *p, *pbuf;
21293 char_u dirname[MAXPATHL];
21294 int c;
21295 int has_fullname = 0;
21296 #ifdef WIN3264
21297 int has_shortname = 0;
21298 #endif
21300 repeat:
21301 /* ":p" - full path/file_name */
21302 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
21304 has_fullname = 1;
21306 valid |= VALID_PATH;
21307 *usedlen += 2;
21309 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
21310 if ((*fnamep)[0] == '~'
21311 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
21312 && ((*fnamep)[1] == '/'
21313 # ifdef BACKSLASH_IN_FILENAME
21314 || (*fnamep)[1] == '\\'
21315 # endif
21316 || (*fnamep)[1] == NUL)
21318 #endif
21321 *fnamep = expand_env_save(*fnamep);
21322 vim_free(*bufp); /* free any allocated file name */
21323 *bufp = *fnamep;
21324 if (*fnamep == NULL)
21325 return -1;
21328 /* When "/." or "/.." is used: force expansion to get rid of it. */
21329 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
21331 if (vim_ispathsep(*p)
21332 && p[1] == '.'
21333 && (p[2] == NUL
21334 || vim_ispathsep(p[2])
21335 || (p[2] == '.'
21336 && (p[3] == NUL || vim_ispathsep(p[3])))))
21337 break;
21340 /* FullName_save() is slow, don't use it when not needed. */
21341 if (*p != NUL || !vim_isAbsName(*fnamep))
21343 *fnamep = FullName_save(*fnamep, *p != NUL);
21344 vim_free(*bufp); /* free any allocated file name */
21345 *bufp = *fnamep;
21346 if (*fnamep == NULL)
21347 return -1;
21350 /* Append a path separator to a directory. */
21351 if (mch_isdir(*fnamep))
21353 /* Make room for one or two extra characters. */
21354 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
21355 vim_free(*bufp); /* free any allocated file name */
21356 *bufp = *fnamep;
21357 if (*fnamep == NULL)
21358 return -1;
21359 add_pathsep(*fnamep);
21363 /* ":." - path relative to the current directory */
21364 /* ":~" - path relative to the home directory */
21365 /* ":8" - shortname path - postponed till after */
21366 while (src[*usedlen] == ':'
21367 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
21369 *usedlen += 2;
21370 if (c == '8')
21372 #ifdef WIN3264
21373 has_shortname = 1; /* Postpone this. */
21374 #endif
21375 continue;
21377 pbuf = NULL;
21378 /* Need full path first (use expand_env() to remove a "~/") */
21379 if (!has_fullname)
21381 if (c == '.' && **fnamep == '~')
21382 p = pbuf = expand_env_save(*fnamep);
21383 else
21384 p = pbuf = FullName_save(*fnamep, FALSE);
21386 else
21387 p = *fnamep;
21389 has_fullname = 0;
21391 if (p != NULL)
21393 if (c == '.')
21395 mch_dirname(dirname, MAXPATHL);
21396 s = shorten_fname(p, dirname);
21397 if (s != NULL)
21399 *fnamep = s;
21400 if (pbuf != NULL)
21402 vim_free(*bufp); /* free any allocated file name */
21403 *bufp = pbuf;
21404 pbuf = NULL;
21408 else
21410 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
21411 /* Only replace it when it starts with '~' */
21412 if (*dirname == '~')
21414 s = vim_strsave(dirname);
21415 if (s != NULL)
21417 *fnamep = s;
21418 vim_free(*bufp);
21419 *bufp = s;
21423 vim_free(pbuf);
21427 tail = gettail(*fnamep);
21428 *fnamelen = (int)STRLEN(*fnamep);
21430 /* ":h" - head, remove "/file_name", can be repeated */
21431 /* Don't remove the first "/" or "c:\" */
21432 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
21434 valid |= VALID_HEAD;
21435 *usedlen += 2;
21436 s = get_past_head(*fnamep);
21437 while (tail > s && after_pathsep(s, tail))
21438 mb_ptr_back(*fnamep, tail);
21439 *fnamelen = (int)(tail - *fnamep);
21440 #ifdef VMS
21441 if (*fnamelen > 0)
21442 *fnamelen += 1; /* the path separator is part of the path */
21443 #endif
21444 if (*fnamelen == 0)
21446 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
21447 p = vim_strsave((char_u *)".");
21448 if (p == NULL)
21449 return -1;
21450 vim_free(*bufp);
21451 *bufp = *fnamep = tail = p;
21452 *fnamelen = 1;
21454 else
21456 while (tail > s && !after_pathsep(s, tail))
21457 mb_ptr_back(*fnamep, tail);
21461 /* ":8" - shortname */
21462 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
21464 *usedlen += 2;
21465 #ifdef WIN3264
21466 has_shortname = 1;
21467 #endif
21470 #ifdef WIN3264
21471 /* Check shortname after we have done 'heads' and before we do 'tails'
21473 if (has_shortname)
21475 pbuf = NULL;
21476 /* Copy the string if it is shortened by :h */
21477 if (*fnamelen < (int)STRLEN(*fnamep))
21479 p = vim_strnsave(*fnamep, *fnamelen);
21480 if (p == 0)
21481 return -1;
21482 vim_free(*bufp);
21483 *bufp = *fnamep = p;
21486 /* Split into two implementations - makes it easier. First is where
21487 * there isn't a full name already, second is where there is.
21489 if (!has_fullname && !vim_isAbsName(*fnamep))
21491 if (shortpath_for_partial(fnamep, bufp, fnamelen) == -1)
21492 return -1;
21494 else
21496 int l;
21498 /* Simple case, already have the full-name
21499 * Nearly always shorter, so try first time. */
21500 l = *fnamelen;
21501 if (!get_short_pathname(fnamep, bufp, &l))
21502 return -1;
21504 if (l == 0)
21506 /* Couldn't find the filename.. search the paths.
21508 l = *fnamelen;
21509 if (shortpath_for_invalid_fname(fnamep, bufp, &l ) == -1)
21510 return -1;
21512 *fnamelen = l;
21515 #endif /* WIN3264 */
21517 /* ":t" - tail, just the basename */
21518 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
21520 *usedlen += 2;
21521 *fnamelen -= (int)(tail - *fnamep);
21522 *fnamep = tail;
21525 /* ":e" - extension, can be repeated */
21526 /* ":r" - root, without extension, can be repeated */
21527 while (src[*usedlen] == ':'
21528 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
21530 /* find a '.' in the tail:
21531 * - for second :e: before the current fname
21532 * - otherwise: The last '.'
21534 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
21535 s = *fnamep - 2;
21536 else
21537 s = *fnamep + *fnamelen - 1;
21538 for ( ; s > tail; --s)
21539 if (s[0] == '.')
21540 break;
21541 if (src[*usedlen + 1] == 'e') /* :e */
21543 if (s > tail)
21545 *fnamelen += (int)(*fnamep - (s + 1));
21546 *fnamep = s + 1;
21547 #ifdef VMS
21548 /* cut version from the extension */
21549 s = *fnamep + *fnamelen - 1;
21550 for ( ; s > *fnamep; --s)
21551 if (s[0] == ';')
21552 break;
21553 if (s > *fnamep)
21554 *fnamelen = s - *fnamep;
21555 #endif
21557 else if (*fnamep <= tail)
21558 *fnamelen = 0;
21560 else /* :r */
21562 if (s > tail) /* remove one extension */
21563 *fnamelen = (int)(s - *fnamep);
21565 *usedlen += 2;
21568 /* ":s?pat?foo?" - substitute */
21569 /* ":gs?pat?foo?" - global substitute */
21570 if (src[*usedlen] == ':'
21571 && (src[*usedlen + 1] == 's'
21572 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
21574 char_u *str;
21575 char_u *pat;
21576 char_u *sub;
21577 int sep;
21578 char_u *flags;
21579 int didit = FALSE;
21581 flags = (char_u *)"";
21582 s = src + *usedlen + 2;
21583 if (src[*usedlen + 1] == 'g')
21585 flags = (char_u *)"g";
21586 ++s;
21589 sep = *s++;
21590 if (sep)
21592 /* find end of pattern */
21593 p = vim_strchr(s, sep);
21594 if (p != NULL)
21596 pat = vim_strnsave(s, (int)(p - s));
21597 if (pat != NULL)
21599 s = p + 1;
21600 /* find end of substitution */
21601 p = vim_strchr(s, sep);
21602 if (p != NULL)
21604 sub = vim_strnsave(s, (int)(p - s));
21605 str = vim_strnsave(*fnamep, *fnamelen);
21606 if (sub != NULL && str != NULL)
21608 *usedlen = (int)(p + 1 - src);
21609 s = do_string_sub(str, pat, sub, flags);
21610 if (s != NULL)
21612 *fnamep = s;
21613 *fnamelen = (int)STRLEN(s);
21614 vim_free(*bufp);
21615 *bufp = s;
21616 didit = TRUE;
21619 vim_free(sub);
21620 vim_free(str);
21622 vim_free(pat);
21625 /* after using ":s", repeat all the modifiers */
21626 if (didit)
21627 goto repeat;
21631 return valid;
21635 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
21636 * "flags" can be "g" to do a global substitute.
21637 * Returns an allocated string, NULL for error.
21639 char_u *
21640 do_string_sub(str, pat, sub, flags)
21641 char_u *str;
21642 char_u *pat;
21643 char_u *sub;
21644 char_u *flags;
21646 int sublen;
21647 regmatch_T regmatch;
21648 int i;
21649 int do_all;
21650 char_u *tail;
21651 garray_T ga;
21652 char_u *ret;
21653 char_u *save_cpo;
21655 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
21656 save_cpo = p_cpo;
21657 p_cpo = (char_u *)"";
21659 ga_init2(&ga, 1, 200);
21661 do_all = (flags[0] == 'g');
21663 regmatch.rm_ic = p_ic;
21664 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
21665 if (regmatch.regprog != NULL)
21667 tail = str;
21668 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
21671 * Get some space for a temporary buffer to do the substitution
21672 * into. It will contain:
21673 * - The text up to where the match is.
21674 * - The substituted text.
21675 * - The text after the match.
21677 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
21678 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
21679 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
21681 ga_clear(&ga);
21682 break;
21685 /* copy the text up to where the match is */
21686 i = (int)(regmatch.startp[0] - tail);
21687 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
21688 /* add the substituted text */
21689 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
21690 + ga.ga_len + i, TRUE, TRUE, FALSE);
21691 ga.ga_len += i + sublen - 1;
21692 /* avoid getting stuck on a match with an empty string */
21693 if (tail == regmatch.endp[0])
21695 if (*tail == NUL)
21696 break;
21697 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
21698 ++ga.ga_len;
21700 else
21702 tail = regmatch.endp[0];
21703 if (*tail == NUL)
21704 break;
21706 if (!do_all)
21707 break;
21710 if (ga.ga_data != NULL)
21711 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
21713 vim_free(regmatch.regprog);
21716 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
21717 ga_clear(&ga);
21718 p_cpo = save_cpo;
21720 return ret;
21723 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */