Merge commit 'svn-vim'
[MacVim.git] / src / eval.c
blob194157494c74abb0605218f26f1b04a70bb424eb
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_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
511 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
513 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
514 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
516 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
517 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
520 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
521 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
523 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
524 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
525 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
526 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
528 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
529 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
531 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
532 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
533 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
534 static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv));
535 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
536 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
537 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
542 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
546 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
547 static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv));
548 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
549 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
551 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
552 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
590 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
591 #ifdef vim_mkdir
592 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
593 #endif
594 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
595 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
596 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
603 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
604 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
605 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
606 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
607 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
608 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
609 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
610 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
611 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
618 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
619 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
620 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
621 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
622 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
623 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
624 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
625 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
626 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
627 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
628 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
629 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
630 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
631 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
632 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
633 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
634 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
635 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
636 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
637 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
638 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
639 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
640 #ifdef HAVE_STRFTIME
641 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
642 #endif
643 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
644 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
645 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
646 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
647 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
648 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
649 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
650 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
651 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
652 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
653 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
654 static void f_synstack __ARGS((typval_T *argvars, typval_T *rettv));
655 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
656 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
657 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
667 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
668 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
669 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
670 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
671 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
672 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
673 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
674 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
675 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
676 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
677 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
678 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
679 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
681 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
682 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
683 static int get_env_len __ARGS((char_u **arg));
684 static int get_id_len __ARGS((char_u **arg));
685 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
686 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
687 #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */
688 #define FNE_CHECK_START 2 /* find_name_end(): check name starts with
689 valid character */
690 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
691 static int eval_isnamec __ARGS((int c));
692 static int eval_isnamec1 __ARGS((int c));
693 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
694 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
695 static typval_T *alloc_tv __ARGS((void));
696 static typval_T *alloc_string_tv __ARGS((char_u *string));
697 static void init_tv __ARGS((typval_T *varp));
698 static long get_tv_number __ARGS((typval_T *varp));
699 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
700 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
701 static char_u *get_tv_string __ARGS((typval_T *varp));
702 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
703 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
704 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
705 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
706 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
707 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
708 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
709 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
710 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
711 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
712 static int var_check_ro __ARGS((int flags, char_u *name));
713 static int var_check_fixed __ARGS((int flags, char_u *name));
714 static int tv_check_lock __ARGS((int lock, char_u *name));
715 static void copy_tv __ARGS((typval_T *from, typval_T *to));
716 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
717 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
718 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
719 static int eval_fname_script __ARGS((char_u *p));
720 static int eval_fname_sid __ARGS((char_u *p));
721 static void list_func_head __ARGS((ufunc_T *fp, int indent));
722 static ufunc_T *find_func __ARGS((char_u *name));
723 static int function_exists __ARGS((char_u *name));
724 static int builtin_function __ARGS((char_u *name));
725 #ifdef FEAT_PROFILE
726 static void func_do_profile __ARGS((ufunc_T *fp));
727 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
728 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
729 static int
730 # ifdef __BORLANDC__
731 _RTLENTRYF
732 # endif
733 prof_total_cmp __ARGS((const void *s1, const void *s2));
734 static int
735 # ifdef __BORLANDC__
736 _RTLENTRYF
737 # endif
738 prof_self_cmp __ARGS((const void *s1, const void *s2));
739 #endif
740 static int script_autoload __ARGS((char_u *name, int reload));
741 static char_u *autoload_name __ARGS((char_u *name));
742 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
743 static void func_free __ARGS((ufunc_T *fp));
744 static void func_unref __ARGS((char_u *name));
745 static void func_ref __ARGS((char_u *name));
746 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));
747 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
748 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
749 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
750 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
751 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
752 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
754 /* Character used as separated in autoload function/variable names. */
755 #define AUTOLOAD_CHAR '#'
758 * Initialize the global and v: variables.
760 void
761 eval_init()
763 int i;
764 struct vimvar *p;
766 init_var_dict(&globvardict, &globvars_var);
767 init_var_dict(&vimvardict, &vimvars_var);
768 hash_init(&compat_hashtab);
769 hash_init(&func_hashtab);
771 for (i = 0; i < VV_LEN; ++i)
773 p = &vimvars[i];
774 STRCPY(p->vv_di.di_key, p->vv_name);
775 if (p->vv_flags & VV_RO)
776 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
777 else if (p->vv_flags & VV_RO_SBX)
778 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
779 else
780 p->vv_di.di_flags = DI_FLAGS_FIX;
782 /* add to v: scope dict, unless the value is not always available */
783 if (p->vv_type != VAR_UNKNOWN)
784 hash_add(&vimvarht, p->vv_di.di_key);
785 if (p->vv_flags & VV_COMPAT)
786 /* add to compat scope dict */
787 hash_add(&compat_hashtab, p->vv_di.di_key);
791 #if defined(EXITFREE) || defined(PROTO)
792 void
793 eval_clear()
795 int i;
796 struct vimvar *p;
798 for (i = 0; i < VV_LEN; ++i)
800 p = &vimvars[i];
801 if (p->vv_di.di_tv.v_type == VAR_STRING)
803 vim_free(p->vv_di.di_tv.vval.v_string);
804 p->vv_di.di_tv.vval.v_string = NULL;
807 hash_clear(&vimvarht);
808 hash_clear(&compat_hashtab);
810 /* script-local variables */
811 for (i = 1; i <= ga_scripts.ga_len; ++i)
812 vars_clear(&SCRIPT_VARS(i));
813 ga_clear(&ga_scripts);
814 free_scriptnames();
816 /* global variables */
817 vars_clear(&globvarht);
819 /* functions */
820 free_all_functions();
821 hash_clear(&func_hashtab);
823 /* autoloaded script names */
824 ga_clear_strings(&ga_loaded);
826 /* unreferenced lists and dicts */
827 (void)garbage_collect();
829 #endif
832 * Return the name of the executed function.
834 char_u *
835 func_name(cookie)
836 void *cookie;
838 return ((funccall_T *)cookie)->func->uf_name;
842 * Return the address holding the next breakpoint line for a funccall cookie.
844 linenr_T *
845 func_breakpoint(cookie)
846 void *cookie;
848 return &((funccall_T *)cookie)->breakpoint;
852 * Return the address holding the debug tick for a funccall cookie.
854 int *
855 func_dbg_tick(cookie)
856 void *cookie;
858 return &((funccall_T *)cookie)->dbg_tick;
862 * Return the nesting level for a funccall cookie.
865 func_level(cookie)
866 void *cookie;
868 return ((funccall_T *)cookie)->level;
871 /* pointer to funccal for currently active function */
872 funccall_T *current_funccal = NULL;
875 * Return TRUE when a function was ended by a ":return" command.
878 current_func_returned()
880 return current_funccal->returned;
885 * Set an internal variable to a string value. Creates the variable if it does
886 * not already exist.
888 void
889 set_internal_string_var(name, value)
890 char_u *name;
891 char_u *value;
893 char_u *val;
894 typval_T *tvp;
896 val = vim_strsave(value);
897 if (val != NULL)
899 tvp = alloc_string_tv(val);
900 if (tvp != NULL)
902 set_var(name, tvp, FALSE);
903 free_tv(tvp);
908 static lval_T *redir_lval = NULL;
909 static garray_T redir_ga; /* only valid when redir_lval is not NULL */
910 static char_u *redir_endp = NULL;
911 static char_u *redir_varname = NULL;
914 * Start recording command output to a variable
915 * Returns OK if successfully completed the setup. FAIL otherwise.
918 var_redir_start(name, append)
919 char_u *name;
920 int append; /* append to an existing variable */
922 int save_emsg;
923 int err;
924 typval_T tv;
926 /* Make sure a valid variable name is specified */
927 if (!eval_isnamec1(*name))
929 EMSG(_(e_invarg));
930 return FAIL;
933 redir_varname = vim_strsave(name);
934 if (redir_varname == NULL)
935 return FAIL;
937 redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
938 if (redir_lval == NULL)
940 var_redir_stop();
941 return FAIL;
944 /* The output is stored in growarray "redir_ga" until redirection ends. */
945 ga_init2(&redir_ga, (int)sizeof(char), 500);
947 /* Parse the variable name (can be a dict or list entry). */
948 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
949 FNE_CHECK_START);
950 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
952 if (redir_endp != NULL && *redir_endp != NUL)
953 /* Trailing characters are present after the variable name */
954 EMSG(_(e_trailing));
955 else
956 EMSG(_(e_invarg));
957 var_redir_stop();
958 return FAIL;
961 /* check if we can write to the variable: set it to or append an empty
962 * string */
963 save_emsg = did_emsg;
964 did_emsg = FALSE;
965 tv.v_type = VAR_STRING;
966 tv.vval.v_string = (char_u *)"";
967 if (append)
968 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
969 else
970 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
971 err = did_emsg;
972 did_emsg |= save_emsg;
973 if (err)
975 var_redir_stop();
976 return FAIL;
978 if (redir_lval->ll_newkey != NULL)
980 /* Dictionary item was created, don't do it again. */
981 vim_free(redir_lval->ll_newkey);
982 redir_lval->ll_newkey = NULL;
985 return OK;
989 * Append "value[value_len]" to the variable set by var_redir_start().
990 * The actual appending is postponed until redirection ends, because the value
991 * appended may in fact be the string we write to, changing it may cause freed
992 * memory to be used:
993 * :redir => foo
994 * :let foo
995 * :redir END
997 void
998 var_redir_str(value, value_len)
999 char_u *value;
1000 int value_len;
1002 int len;
1004 if (redir_lval == NULL)
1005 return;
1007 if (value_len == -1)
1008 len = (int)STRLEN(value); /* Append the entire string */
1009 else
1010 len = value_len; /* Append only "value_len" characters */
1012 if (ga_grow(&redir_ga, len) == OK)
1014 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1015 redir_ga.ga_len += len;
1017 else
1018 var_redir_stop();
1022 * Stop redirecting command output to a variable.
1024 void
1025 var_redir_stop()
1027 typval_T tv;
1029 if (redir_lval != NULL)
1031 /* Append the trailing NUL. */
1032 ga_append(&redir_ga, NUL);
1034 /* Assign the text to the variable. */
1035 tv.v_type = VAR_STRING;
1036 tv.vval.v_string = redir_ga.ga_data;
1037 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1038 vim_free(tv.vval.v_string);
1040 clear_lval(redir_lval);
1041 vim_free(redir_lval);
1042 redir_lval = NULL;
1044 vim_free(redir_varname);
1045 redir_varname = NULL;
1048 # if defined(FEAT_MBYTE) || defined(PROTO)
1050 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1051 char_u *enc_from;
1052 char_u *enc_to;
1053 char_u *fname_from;
1054 char_u *fname_to;
1056 int err = FALSE;
1058 set_vim_var_string(VV_CC_FROM, enc_from, -1);
1059 set_vim_var_string(VV_CC_TO, enc_to, -1);
1060 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1061 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1062 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1063 err = TRUE;
1064 set_vim_var_string(VV_CC_FROM, NULL, -1);
1065 set_vim_var_string(VV_CC_TO, NULL, -1);
1066 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1067 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1069 if (err)
1070 return FAIL;
1071 return OK;
1073 # endif
1075 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1077 eval_printexpr(fname, args)
1078 char_u *fname;
1079 char_u *args;
1081 int err = FALSE;
1083 set_vim_var_string(VV_FNAME_IN, fname, -1);
1084 set_vim_var_string(VV_CMDARG, args, -1);
1085 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1086 err = TRUE;
1087 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1088 set_vim_var_string(VV_CMDARG, NULL, -1);
1090 if (err)
1092 mch_remove(fname);
1093 return FAIL;
1095 return OK;
1097 # endif
1099 # if defined(FEAT_DIFF) || defined(PROTO)
1100 void
1101 eval_diff(origfile, newfile, outfile)
1102 char_u *origfile;
1103 char_u *newfile;
1104 char_u *outfile;
1106 int err = FALSE;
1108 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1109 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1110 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1111 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1112 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1113 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1114 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1117 void
1118 eval_patch(origfile, difffile, outfile)
1119 char_u *origfile;
1120 char_u *difffile;
1121 char_u *outfile;
1123 int err;
1125 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1126 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1127 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1128 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1129 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1130 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1131 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1133 # endif
1136 * Top level evaluation function, returning a boolean.
1137 * Sets "error" to TRUE if there was an error.
1138 * Return TRUE or FALSE.
1141 eval_to_bool(arg, error, nextcmd, skip)
1142 char_u *arg;
1143 int *error;
1144 char_u **nextcmd;
1145 int skip; /* only parse, don't execute */
1147 typval_T tv;
1148 int retval = FALSE;
1150 if (skip)
1151 ++emsg_skip;
1152 if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1153 *error = TRUE;
1154 else
1156 *error = FALSE;
1157 if (!skip)
1159 retval = (get_tv_number_chk(&tv, error) != 0);
1160 clear_tv(&tv);
1163 if (skip)
1164 --emsg_skip;
1166 return retval;
1170 * Top level evaluation function, returning a string. If "skip" is TRUE,
1171 * only parsing to "nextcmd" is done, without reporting errors. Return
1172 * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1174 char_u *
1175 eval_to_string_skip(arg, nextcmd, skip)
1176 char_u *arg;
1177 char_u **nextcmd;
1178 int skip; /* only parse, don't execute */
1180 typval_T tv;
1181 char_u *retval;
1183 if (skip)
1184 ++emsg_skip;
1185 if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1186 retval = NULL;
1187 else
1189 retval = vim_strsave(get_tv_string(&tv));
1190 clear_tv(&tv);
1192 if (skip)
1193 --emsg_skip;
1195 return retval;
1199 * Skip over an expression at "*pp".
1200 * Return FAIL for an error, OK otherwise.
1203 skip_expr(pp)
1204 char_u **pp;
1206 typval_T rettv;
1208 *pp = skipwhite(*pp);
1209 return eval1(pp, &rettv, FALSE);
1213 * Top level evaluation function, returning a string.
1214 * Return pointer to allocated memory, or NULL for failure.
1216 char_u *
1217 eval_to_string(arg, nextcmd, dolist)
1218 char_u *arg;
1219 char_u **nextcmd;
1220 int dolist; /* turn List into sequence of lines */
1222 typval_T tv;
1223 char_u *retval;
1224 garray_T ga;
1226 if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1227 retval = NULL;
1228 else
1230 if (dolist && tv.v_type == VAR_LIST)
1232 ga_init2(&ga, (int)sizeof(char), 80);
1233 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1234 ga_append(&ga, NUL);
1235 retval = (char_u *)ga.ga_data;
1237 else
1238 retval = vim_strsave(get_tv_string(&tv));
1239 clear_tv(&tv);
1242 return retval;
1246 * Call eval_to_string() without using current local variables and using
1247 * textlock. When "use_sandbox" is TRUE use the sandbox.
1249 char_u *
1250 eval_to_string_safe(arg, nextcmd, use_sandbox)
1251 char_u *arg;
1252 char_u **nextcmd;
1253 int use_sandbox;
1255 char_u *retval;
1256 void *save_funccalp;
1258 save_funccalp = save_funccal();
1259 if (use_sandbox)
1260 ++sandbox;
1261 ++textlock;
1262 retval = eval_to_string(arg, nextcmd, FALSE);
1263 if (use_sandbox)
1264 --sandbox;
1265 --textlock;
1266 restore_funccal(save_funccalp);
1267 return retval;
1271 * Top level evaluation function, returning a number.
1272 * Evaluates "expr" silently.
1273 * Returns -1 for an error.
1276 eval_to_number(expr)
1277 char_u *expr;
1279 typval_T rettv;
1280 int retval;
1281 char_u *p = skipwhite(expr);
1283 ++emsg_off;
1285 if (eval1(&p, &rettv, TRUE) == FAIL)
1286 retval = -1;
1287 else
1289 retval = get_tv_number_chk(&rettv, NULL);
1290 clear_tv(&rettv);
1292 --emsg_off;
1294 return retval;
1298 * Prepare v: variable "idx" to be used.
1299 * Save the current typeval in "save_tv".
1300 * When not used yet add the variable to the v: hashtable.
1302 static void
1303 prepare_vimvar(idx, save_tv)
1304 int idx;
1305 typval_T *save_tv;
1307 *save_tv = vimvars[idx].vv_tv;
1308 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1309 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1313 * Restore v: variable "idx" to typeval "save_tv".
1314 * When no longer defined, remove the variable from the v: hashtable.
1316 static void
1317 restore_vimvar(idx, save_tv)
1318 int idx;
1319 typval_T *save_tv;
1321 hashitem_T *hi;
1323 vimvars[idx].vv_tv = *save_tv;
1324 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1326 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1327 if (HASHITEM_EMPTY(hi))
1328 EMSG2(_(e_intern2), "restore_vimvar()");
1329 else
1330 hash_remove(&vimvarht, hi);
1334 #if defined(FEAT_SPELL) || defined(PROTO)
1336 * Evaluate an expression to a list with suggestions.
1337 * For the "expr:" part of 'spellsuggest'.
1339 list_T *
1340 eval_spell_expr(badword, expr)
1341 char_u *badword;
1342 char_u *expr;
1344 typval_T save_val;
1345 typval_T rettv;
1346 list_T *list = NULL;
1347 char_u *p = skipwhite(expr);
1349 /* Set "v:val" to the bad word. */
1350 prepare_vimvar(VV_VAL, &save_val);
1351 vimvars[VV_VAL].vv_type = VAR_STRING;
1352 vimvars[VV_VAL].vv_str = badword;
1353 if (p_verbose == 0)
1354 ++emsg_off;
1356 if (eval1(&p, &rettv, TRUE) == OK)
1358 if (rettv.v_type != VAR_LIST)
1359 clear_tv(&rettv);
1360 else
1361 list = rettv.vval.v_list;
1364 if (p_verbose == 0)
1365 --emsg_off;
1366 restore_vimvar(VV_VAL, &save_val);
1368 return list;
1372 * "list" is supposed to contain two items: a word and a number. Return the
1373 * word in "pp" and the number as the return value.
1374 * Return -1 if anything isn't right.
1375 * Used to get the good word and score from the eval_spell_expr() result.
1378 get_spellword(list, pp)
1379 list_T *list;
1380 char_u **pp;
1382 listitem_T *li;
1384 li = list->lv_first;
1385 if (li == NULL)
1386 return -1;
1387 *pp = get_tv_string(&li->li_tv);
1389 li = li->li_next;
1390 if (li == NULL)
1391 return -1;
1392 return get_tv_number(&li->li_tv);
1394 #endif
1397 * Top level evaluation function.
1398 * Returns an allocated typval_T with the result.
1399 * Returns NULL when there is an error.
1401 typval_T *
1402 eval_expr(arg, nextcmd)
1403 char_u *arg;
1404 char_u **nextcmd;
1406 typval_T *tv;
1408 tv = (typval_T *)alloc(sizeof(typval_T));
1409 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1411 vim_free(tv);
1412 tv = NULL;
1415 return tv;
1419 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1420 || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1422 * Call some vimL function and return the result in "*rettv".
1423 * Uses argv[argc] for the function arguments.
1424 * Returns OK or FAIL.
1426 static int
1427 call_vim_function(func, argc, argv, safe, rettv)
1428 char_u *func;
1429 int argc;
1430 char_u **argv;
1431 int safe; /* use the sandbox */
1432 typval_T *rettv;
1434 typval_T *argvars;
1435 long n;
1436 int len;
1437 int i;
1438 int doesrange;
1439 void *save_funccalp = NULL;
1440 int ret;
1442 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1443 if (argvars == NULL)
1444 return FAIL;
1446 for (i = 0; i < argc; i++)
1448 /* Pass a NULL or empty argument as an empty string */
1449 if (argv[i] == NULL || *argv[i] == NUL)
1451 argvars[i].v_type = VAR_STRING;
1452 argvars[i].vval.v_string = (char_u *)"";
1453 continue;
1456 /* Recognize a number argument, the others must be strings. */
1457 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1458 if (len != 0 && len == (int)STRLEN(argv[i]))
1460 argvars[i].v_type = VAR_NUMBER;
1461 argvars[i].vval.v_number = n;
1463 else
1465 argvars[i].v_type = VAR_STRING;
1466 argvars[i].vval.v_string = argv[i];
1470 if (safe)
1472 save_funccalp = save_funccal();
1473 ++sandbox;
1476 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1477 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1478 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1479 &doesrange, TRUE, NULL);
1480 if (safe)
1482 --sandbox;
1483 restore_funccal(save_funccalp);
1485 vim_free(argvars);
1487 if (ret == FAIL)
1488 clear_tv(rettv);
1490 return ret;
1493 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1495 * Call vimL function "func" and return the result as a string.
1496 * Returns NULL when calling the function fails.
1497 * Uses argv[argc] for the function arguments.
1499 void *
1500 call_func_retstr(func, argc, argv, safe)
1501 char_u *func;
1502 int argc;
1503 char_u **argv;
1504 int safe; /* use the sandbox */
1506 typval_T rettv;
1507 char_u *retval;
1509 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1510 return NULL;
1512 retval = vim_strsave(get_tv_string(&rettv));
1513 clear_tv(&rettv);
1514 return retval;
1516 # endif
1518 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1520 * Call vimL function "func" and return the result as a number.
1521 * Returns -1 when calling the function fails.
1522 * Uses argv[argc] for the function arguments.
1524 long
1525 call_func_retnr(func, argc, argv, safe)
1526 char_u *func;
1527 int argc;
1528 char_u **argv;
1529 int safe; /* use the sandbox */
1531 typval_T rettv;
1532 long retval;
1534 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1535 return -1;
1537 retval = get_tv_number_chk(&rettv, NULL);
1538 clear_tv(&rettv);
1539 return retval;
1541 # endif
1544 * Call vimL function "func" and return the result as a list
1545 * Uses argv[argc] for the function arguments.
1547 void *
1548 call_func_retlist(func, argc, argv, safe)
1549 char_u *func;
1550 int argc;
1551 char_u **argv;
1552 int safe; /* use the sandbox */
1554 typval_T rettv;
1556 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1557 return NULL;
1559 if (rettv.v_type != VAR_LIST)
1561 clear_tv(&rettv);
1562 return NULL;
1565 return rettv.vval.v_list;
1567 #endif
1571 * Save the current function call pointer, and set it to NULL.
1572 * Used when executing autocommands and for ":source".
1574 void *
1575 save_funccal()
1577 funccall_T *fc = current_funccal;
1579 current_funccal = NULL;
1580 return (void *)fc;
1583 void
1584 restore_funccal(vfc)
1585 void *vfc;
1587 funccall_T *fc = (funccall_T *)vfc;
1589 current_funccal = fc;
1592 #if defined(FEAT_PROFILE) || defined(PROTO)
1594 * Prepare profiling for entering a child or something else that is not
1595 * counted for the script/function itself.
1596 * Should always be called in pair with prof_child_exit().
1598 void
1599 prof_child_enter(tm)
1600 proftime_T *tm; /* place to store waittime */
1602 funccall_T *fc = current_funccal;
1604 if (fc != NULL && fc->func->uf_profiling)
1605 profile_start(&fc->prof_child);
1606 script_prof_save(tm);
1610 * Take care of time spent in a child.
1611 * Should always be called after prof_child_enter().
1613 void
1614 prof_child_exit(tm)
1615 proftime_T *tm; /* where waittime was stored */
1617 funccall_T *fc = current_funccal;
1619 if (fc != NULL && fc->func->uf_profiling)
1621 profile_end(&fc->prof_child);
1622 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1623 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1624 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1626 script_prof_restore(tm);
1628 #endif
1631 #ifdef FEAT_FOLDING
1633 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1634 * it in "*cp". Doesn't give error messages.
1637 eval_foldexpr(arg, cp)
1638 char_u *arg;
1639 int *cp;
1641 typval_T tv;
1642 int retval;
1643 char_u *s;
1644 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1645 OPT_LOCAL);
1647 ++emsg_off;
1648 if (use_sandbox)
1649 ++sandbox;
1650 ++textlock;
1651 *cp = NUL;
1652 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1653 retval = 0;
1654 else
1656 /* If the result is a number, just return the number. */
1657 if (tv.v_type == VAR_NUMBER)
1658 retval = tv.vval.v_number;
1659 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1660 retval = 0;
1661 else
1663 /* If the result is a string, check if there is a non-digit before
1664 * the number. */
1665 s = tv.vval.v_string;
1666 if (!VIM_ISDIGIT(*s) && *s != '-')
1667 *cp = *s++;
1668 retval = atol((char *)s);
1670 clear_tv(&tv);
1672 --emsg_off;
1673 if (use_sandbox)
1674 --sandbox;
1675 --textlock;
1677 return retval;
1679 #endif
1682 * ":let" list all variable values
1683 * ":let var1 var2" list variable values
1684 * ":let var = expr" assignment command.
1685 * ":let var += expr" assignment command.
1686 * ":let var -= expr" assignment command.
1687 * ":let var .= expr" assignment command.
1688 * ":let [var1, var2] = expr" unpack list.
1690 void
1691 ex_let(eap)
1692 exarg_T *eap;
1694 char_u *arg = eap->arg;
1695 char_u *expr = NULL;
1696 typval_T rettv;
1697 int i;
1698 int var_count = 0;
1699 int semicolon = 0;
1700 char_u op[2];
1701 char_u *argend;
1702 int first = TRUE;
1704 argend = skip_var_list(arg, &var_count, &semicolon);
1705 if (argend == NULL)
1706 return;
1707 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1708 --argend;
1709 expr = vim_strchr(argend, '=');
1710 if (expr == NULL)
1713 * ":let" without "=": list variables
1715 if (*arg == '[')
1716 EMSG(_(e_invarg));
1717 else if (!ends_excmd(*arg))
1718 /* ":let var1 var2" */
1719 arg = list_arg_vars(eap, arg, &first);
1720 else if (!eap->skip)
1722 /* ":let" */
1723 list_glob_vars(&first);
1724 list_buf_vars(&first);
1725 list_win_vars(&first);
1726 #ifdef FEAT_WINDOWS
1727 list_tab_vars(&first);
1728 #endif
1729 list_script_vars(&first);
1730 list_func_vars(&first);
1731 list_vim_vars(&first);
1733 eap->nextcmd = check_nextcmd(arg);
1735 else
1737 op[0] = '=';
1738 op[1] = NUL;
1739 if (expr > argend)
1741 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1742 op[0] = expr[-1]; /* +=, -= or .= */
1744 expr = skipwhite(expr + 1);
1746 if (eap->skip)
1747 ++emsg_skip;
1748 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1749 if (eap->skip)
1751 if (i != FAIL)
1752 clear_tv(&rettv);
1753 --emsg_skip;
1755 else if (i != FAIL)
1757 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1758 op);
1759 clear_tv(&rettv);
1765 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1766 * Handles both "var" with any type and "[var, var; var]" with a list type.
1767 * When "nextchars" is not NULL it points to a string with characters that
1768 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1769 * or concatenate.
1770 * Returns OK or FAIL;
1772 static int
1773 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1774 char_u *arg_start;
1775 typval_T *tv;
1776 int copy; /* copy values from "tv", don't move */
1777 int semicolon; /* from skip_var_list() */
1778 int var_count; /* from skip_var_list() */
1779 char_u *nextchars;
1781 char_u *arg = arg_start;
1782 list_T *l;
1783 int i;
1784 listitem_T *item;
1785 typval_T ltv;
1787 if (*arg != '[')
1790 * ":let var = expr" or ":for var in list"
1792 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1793 return FAIL;
1794 return OK;
1798 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1800 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1802 EMSG(_(e_listreq));
1803 return FAIL;
1806 i = list_len(l);
1807 if (semicolon == 0 && var_count < i)
1809 EMSG(_("E687: Less targets than List items"));
1810 return FAIL;
1812 if (var_count - semicolon > i)
1814 EMSG(_("E688: More targets than List items"));
1815 return FAIL;
1818 item = l->lv_first;
1819 while (*arg != ']')
1821 arg = skipwhite(arg + 1);
1822 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1823 item = item->li_next;
1824 if (arg == NULL)
1825 return FAIL;
1827 arg = skipwhite(arg);
1828 if (*arg == ';')
1830 /* Put the rest of the list (may be empty) in the var after ';'.
1831 * Create a new list for this. */
1832 l = list_alloc();
1833 if (l == NULL)
1834 return FAIL;
1835 while (item != NULL)
1837 list_append_tv(l, &item->li_tv);
1838 item = item->li_next;
1841 ltv.v_type = VAR_LIST;
1842 ltv.v_lock = 0;
1843 ltv.vval.v_list = l;
1844 l->lv_refcount = 1;
1846 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1847 (char_u *)"]", nextchars);
1848 clear_tv(&ltv);
1849 if (arg == NULL)
1850 return FAIL;
1851 break;
1853 else if (*arg != ',' && *arg != ']')
1855 EMSG2(_(e_intern2), "ex_let_vars()");
1856 return FAIL;
1860 return OK;
1864 * Skip over assignable variable "var" or list of variables "[var, var]".
1865 * Used for ":let varvar = expr" and ":for varvar in expr".
1866 * For "[var, var]" increment "*var_count" for each variable.
1867 * for "[var, var; var]" set "semicolon".
1868 * Return NULL for an error.
1870 static char_u *
1871 skip_var_list(arg, var_count, semicolon)
1872 char_u *arg;
1873 int *var_count;
1874 int *semicolon;
1876 char_u *p, *s;
1878 if (*arg == '[')
1880 /* "[var, var]": find the matching ']'. */
1881 p = arg;
1882 for (;;)
1884 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
1885 s = skip_var_one(p);
1886 if (s == p)
1888 EMSG2(_(e_invarg2), p);
1889 return NULL;
1891 ++*var_count;
1893 p = skipwhite(s);
1894 if (*p == ']')
1895 break;
1896 else if (*p == ';')
1898 if (*semicolon == 1)
1900 EMSG(_("Double ; in list of variables"));
1901 return NULL;
1903 *semicolon = 1;
1905 else if (*p != ',')
1907 EMSG2(_(e_invarg2), p);
1908 return NULL;
1911 return p + 1;
1913 else
1914 return skip_var_one(arg);
1918 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
1919 * l[idx].
1921 static char_u *
1922 skip_var_one(arg)
1923 char_u *arg;
1925 if (*arg == '@' && arg[1] != NUL)
1926 return arg + 2;
1927 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
1928 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1932 * List variables for hashtab "ht" with prefix "prefix".
1933 * If "empty" is TRUE also list NULL strings as empty strings.
1935 static void
1936 list_hashtable_vars(ht, prefix, empty, first)
1937 hashtab_T *ht;
1938 char_u *prefix;
1939 int empty;
1940 int *first;
1942 hashitem_T *hi;
1943 dictitem_T *di;
1944 int todo;
1946 todo = (int)ht->ht_used;
1947 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
1949 if (!HASHITEM_EMPTY(hi))
1951 --todo;
1952 di = HI2DI(hi);
1953 if (empty || di->di_tv.v_type != VAR_STRING
1954 || di->di_tv.vval.v_string != NULL)
1955 list_one_var(di, prefix, first);
1961 * List global variables.
1963 static void
1964 list_glob_vars(first)
1965 int *first;
1967 list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
1971 * List buffer variables.
1973 static void
1974 list_buf_vars(first)
1975 int *first;
1977 char_u numbuf[NUMBUFLEN];
1979 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:",
1980 TRUE, first);
1982 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
1983 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
1984 numbuf, first);
1988 * List window variables.
1990 static void
1991 list_win_vars(first)
1992 int *first;
1994 list_hashtable_vars(&curwin->w_vars.dv_hashtab,
1995 (char_u *)"w:", TRUE, first);
1998 #ifdef FEAT_WINDOWS
2000 * List tab page variables.
2002 static void
2003 list_tab_vars(first)
2004 int *first;
2006 list_hashtable_vars(&curtab->tp_vars.dv_hashtab,
2007 (char_u *)"t:", TRUE, first);
2009 #endif
2012 * List Vim variables.
2014 static void
2015 list_vim_vars(first)
2016 int *first;
2018 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2022 * List script-local variables, if there is a script.
2024 static void
2025 list_script_vars(first)
2026 int *first;
2028 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2029 list_hashtable_vars(&SCRIPT_VARS(current_SID),
2030 (char_u *)"s:", FALSE, first);
2034 * List function variables, if there is a function.
2036 static void
2037 list_func_vars(first)
2038 int *first;
2040 if (current_funccal != NULL)
2041 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2042 (char_u *)"l:", FALSE, first);
2046 * List variables in "arg".
2048 static char_u *
2049 list_arg_vars(eap, arg, first)
2050 exarg_T *eap;
2051 char_u *arg;
2052 int *first;
2054 int error = FALSE;
2055 int len;
2056 char_u *name;
2057 char_u *name_start;
2058 char_u *arg_subsc;
2059 char_u *tofree;
2060 typval_T tv;
2062 while (!ends_excmd(*arg) && !got_int)
2064 if (error || eap->skip)
2066 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2067 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2069 emsg_severe = TRUE;
2070 EMSG(_(e_trailing));
2071 break;
2074 else
2076 /* get_name_len() takes care of expanding curly braces */
2077 name_start = name = arg;
2078 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2079 if (len <= 0)
2081 /* This is mainly to keep test 49 working: when expanding
2082 * curly braces fails overrule the exception error message. */
2083 if (len < 0 && !aborting())
2085 emsg_severe = TRUE;
2086 EMSG2(_(e_invarg2), arg);
2087 break;
2089 error = TRUE;
2091 else
2093 if (tofree != NULL)
2094 name = tofree;
2095 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2096 error = TRUE;
2097 else
2099 /* handle d.key, l[idx], f(expr) */
2100 arg_subsc = arg;
2101 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2102 error = TRUE;
2103 else
2105 if (arg == arg_subsc && len == 2 && name[1] == ':')
2107 switch (*name)
2109 case 'g': list_glob_vars(first); break;
2110 case 'b': list_buf_vars(first); break;
2111 case 'w': list_win_vars(first); break;
2112 #ifdef FEAT_WINDOWS
2113 case 't': list_tab_vars(first); break;
2114 #endif
2115 case 'v': list_vim_vars(first); break;
2116 case 's': list_script_vars(first); break;
2117 case 'l': list_func_vars(first); break;
2118 default:
2119 EMSG2(_("E738: Can't list variables for %s"), name);
2122 else
2124 char_u numbuf[NUMBUFLEN];
2125 char_u *tf;
2126 int c;
2127 char_u *s;
2129 s = echo_string(&tv, &tf, numbuf, 0);
2130 c = *arg;
2131 *arg = NUL;
2132 list_one_var_a((char_u *)"",
2133 arg == arg_subsc ? name : name_start,
2134 tv.v_type,
2135 s == NULL ? (char_u *)"" : s,
2136 first);
2137 *arg = c;
2138 vim_free(tf);
2140 clear_tv(&tv);
2145 vim_free(tofree);
2148 arg = skipwhite(arg);
2151 return arg;
2155 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2156 * Returns a pointer to the char just after the var name.
2157 * Returns NULL if there is an error.
2159 static char_u *
2160 ex_let_one(arg, tv, copy, endchars, op)
2161 char_u *arg; /* points to variable name */
2162 typval_T *tv; /* value to assign to variable */
2163 int copy; /* copy value from "tv" */
2164 char_u *endchars; /* valid chars after variable name or NULL */
2165 char_u *op; /* "+", "-", "." or NULL*/
2167 int c1;
2168 char_u *name;
2169 char_u *p;
2170 char_u *arg_end = NULL;
2171 int len;
2172 int opt_flags;
2173 char_u *tofree = NULL;
2176 * ":let $VAR = expr": Set environment variable.
2178 if (*arg == '$')
2180 /* Find the end of the name. */
2181 ++arg;
2182 name = arg;
2183 len = get_env_len(&arg);
2184 if (len == 0)
2185 EMSG2(_(e_invarg2), name - 1);
2186 else
2188 if (op != NULL && (*op == '+' || *op == '-'))
2189 EMSG2(_(e_letwrong), op);
2190 else if (endchars != NULL
2191 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2192 EMSG(_(e_letunexp));
2193 else
2195 c1 = name[len];
2196 name[len] = NUL;
2197 p = get_tv_string_chk(tv);
2198 if (p != NULL && op != NULL && *op == '.')
2200 int mustfree = FALSE;
2201 char_u *s = vim_getenv(name, &mustfree);
2203 if (s != NULL)
2205 p = tofree = concat_str(s, p);
2206 if (mustfree)
2207 vim_free(s);
2210 if (p != NULL)
2212 vim_setenv(name, p);
2213 if (STRICMP(name, "HOME") == 0)
2214 init_homedir();
2215 else if (didset_vim && STRICMP(name, "VIM") == 0)
2216 didset_vim = FALSE;
2217 else if (didset_vimruntime
2218 && STRICMP(name, "VIMRUNTIME") == 0)
2219 didset_vimruntime = FALSE;
2220 arg_end = arg;
2222 name[len] = c1;
2223 vim_free(tofree);
2229 * ":let &option = expr": Set option value.
2230 * ":let &l:option = expr": Set local option value.
2231 * ":let &g:option = expr": Set global option value.
2233 else if (*arg == '&')
2235 /* Find the end of the name. */
2236 p = find_option_end(&arg, &opt_flags);
2237 if (p == NULL || (endchars != NULL
2238 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2239 EMSG(_(e_letunexp));
2240 else
2242 long n;
2243 int opt_type;
2244 long numval;
2245 char_u *stringval = NULL;
2246 char_u *s;
2248 c1 = *p;
2249 *p = NUL;
2251 n = get_tv_number(tv);
2252 s = get_tv_string_chk(tv); /* != NULL if number or string */
2253 if (s != NULL && op != NULL && *op != '=')
2255 opt_type = get_option_value(arg, &numval,
2256 &stringval, opt_flags);
2257 if ((opt_type == 1 && *op == '.')
2258 || (opt_type == 0 && *op != '.'))
2259 EMSG2(_(e_letwrong), op);
2260 else
2262 if (opt_type == 1) /* number */
2264 if (*op == '+')
2265 n = numval + n;
2266 else
2267 n = numval - n;
2269 else if (opt_type == 0 && stringval != NULL) /* string */
2271 s = concat_str(stringval, s);
2272 vim_free(stringval);
2273 stringval = s;
2277 if (s != NULL)
2279 set_option_value(arg, n, s, opt_flags);
2280 arg_end = p;
2282 *p = c1;
2283 vim_free(stringval);
2288 * ":let @r = expr": Set register contents.
2290 else if (*arg == '@')
2292 ++arg;
2293 if (op != NULL && (*op == '+' || *op == '-'))
2294 EMSG2(_(e_letwrong), op);
2295 else if (endchars != NULL
2296 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2297 EMSG(_(e_letunexp));
2298 else
2300 char_u *ptofree = NULL;
2301 char_u *s;
2303 p = get_tv_string_chk(tv);
2304 if (p != NULL && op != NULL && *op == '.')
2306 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2307 if (s != NULL)
2309 p = ptofree = concat_str(s, p);
2310 vim_free(s);
2313 if (p != NULL)
2315 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2316 arg_end = arg + 1;
2318 vim_free(ptofree);
2323 * ":let var = expr": Set internal variable.
2324 * ":let {expr} = expr": Idem, name made with curly braces
2326 else if (eval_isnamec1(*arg) || *arg == '{')
2328 lval_T lv;
2330 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2331 if (p != NULL && lv.ll_name != NULL)
2333 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2334 EMSG(_(e_letunexp));
2335 else
2337 set_var_lval(&lv, p, tv, copy, op);
2338 arg_end = p;
2341 clear_lval(&lv);
2344 else
2345 EMSG2(_(e_invarg2), arg);
2347 return arg_end;
2351 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2353 static int
2354 check_changedtick(arg)
2355 char_u *arg;
2357 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2359 EMSG2(_(e_readonlyvar), arg);
2360 return TRUE;
2362 return FALSE;
2366 * Get an lval: variable, Dict item or List item that can be assigned a value
2367 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2368 * "name.key", "name.key[expr]" etc.
2369 * Indexing only works if "name" is an existing List or Dictionary.
2370 * "name" points to the start of the name.
2371 * If "rettv" is not NULL it points to the value to be assigned.
2372 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2373 * wrong; must end in space or cmd separator.
2375 * Returns a pointer to just after the name, including indexes.
2376 * When an evaluation error occurs "lp->ll_name" is NULL;
2377 * Returns NULL for a parsing error. Still need to free items in "lp"!
2379 static char_u *
2380 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2381 char_u *name;
2382 typval_T *rettv;
2383 lval_T *lp;
2384 int unlet;
2385 int skip;
2386 int quiet; /* don't give error messages */
2387 int fne_flags; /* flags for find_name_end() */
2389 char_u *p;
2390 char_u *expr_start, *expr_end;
2391 int cc;
2392 dictitem_T *v;
2393 typval_T var1;
2394 typval_T var2;
2395 int empty1 = FALSE;
2396 listitem_T *ni;
2397 char_u *key = NULL;
2398 int len;
2399 hashtab_T *ht;
2401 /* Clear everything in "lp". */
2402 vim_memset(lp, 0, sizeof(lval_T));
2404 if (skip)
2406 /* When skipping just find the end of the name. */
2407 lp->ll_name = name;
2408 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2411 /* Find the end of the name. */
2412 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2413 if (expr_start != NULL)
2415 /* Don't expand the name when we already know there is an error. */
2416 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2417 && *p != '[' && *p != '.')
2419 EMSG(_(e_trailing));
2420 return NULL;
2423 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2424 if (lp->ll_exp_name == NULL)
2426 /* Report an invalid expression in braces, unless the
2427 * expression evaluation has been cancelled due to an
2428 * aborting error, an interrupt, or an exception. */
2429 if (!aborting() && !quiet)
2431 emsg_severe = TRUE;
2432 EMSG2(_(e_invarg2), name);
2433 return NULL;
2436 lp->ll_name = lp->ll_exp_name;
2438 else
2439 lp->ll_name = name;
2441 /* Without [idx] or .key we are done. */
2442 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2443 return p;
2445 cc = *p;
2446 *p = NUL;
2447 v = find_var(lp->ll_name, &ht);
2448 if (v == NULL && !quiet)
2449 EMSG2(_(e_undefvar), lp->ll_name);
2450 *p = cc;
2451 if (v == NULL)
2452 return NULL;
2455 * Loop until no more [idx] or .key is following.
2457 lp->ll_tv = &v->di_tv;
2458 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2460 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2461 && !(lp->ll_tv->v_type == VAR_DICT
2462 && lp->ll_tv->vval.v_dict != NULL))
2464 if (!quiet)
2465 EMSG(_("E689: Can only index a List or Dictionary"));
2466 return NULL;
2468 if (lp->ll_range)
2470 if (!quiet)
2471 EMSG(_("E708: [:] must come last"));
2472 return NULL;
2475 len = -1;
2476 if (*p == '.')
2478 key = p + 1;
2479 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2481 if (len == 0)
2483 if (!quiet)
2484 EMSG(_(e_emptykey));
2485 return NULL;
2487 p = key + len;
2489 else
2491 /* Get the index [expr] or the first index [expr: ]. */
2492 p = skipwhite(p + 1);
2493 if (*p == ':')
2494 empty1 = TRUE;
2495 else
2497 empty1 = FALSE;
2498 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2499 return NULL;
2500 if (get_tv_string_chk(&var1) == NULL)
2502 /* not a number or string */
2503 clear_tv(&var1);
2504 return NULL;
2508 /* Optionally get the second index [ :expr]. */
2509 if (*p == ':')
2511 if (lp->ll_tv->v_type == VAR_DICT)
2513 if (!quiet)
2514 EMSG(_(e_dictrange));
2515 if (!empty1)
2516 clear_tv(&var1);
2517 return NULL;
2519 if (rettv != NULL && (rettv->v_type != VAR_LIST
2520 || rettv->vval.v_list == NULL))
2522 if (!quiet)
2523 EMSG(_("E709: [:] requires a List value"));
2524 if (!empty1)
2525 clear_tv(&var1);
2526 return NULL;
2528 p = skipwhite(p + 1);
2529 if (*p == ']')
2530 lp->ll_empty2 = TRUE;
2531 else
2533 lp->ll_empty2 = FALSE;
2534 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2536 if (!empty1)
2537 clear_tv(&var1);
2538 return NULL;
2540 if (get_tv_string_chk(&var2) == NULL)
2542 /* not a number or string */
2543 if (!empty1)
2544 clear_tv(&var1);
2545 clear_tv(&var2);
2546 return NULL;
2549 lp->ll_range = TRUE;
2551 else
2552 lp->ll_range = FALSE;
2554 if (*p != ']')
2556 if (!quiet)
2557 EMSG(_(e_missbrac));
2558 if (!empty1)
2559 clear_tv(&var1);
2560 if (lp->ll_range && !lp->ll_empty2)
2561 clear_tv(&var2);
2562 return NULL;
2565 /* Skip to past ']'. */
2566 ++p;
2569 if (lp->ll_tv->v_type == VAR_DICT)
2571 if (len == -1)
2573 /* "[key]": get key from "var1" */
2574 key = get_tv_string(&var1); /* is number or string */
2575 if (*key == NUL)
2577 if (!quiet)
2578 EMSG(_(e_emptykey));
2579 clear_tv(&var1);
2580 return NULL;
2583 lp->ll_list = NULL;
2584 lp->ll_dict = lp->ll_tv->vval.v_dict;
2585 lp->ll_di = dict_find(lp->ll_dict, key, len);
2586 if (lp->ll_di == NULL)
2588 /* Key does not exist in dict: may need to add it. */
2589 if (*p == '[' || *p == '.' || unlet)
2591 if (!quiet)
2592 EMSG2(_(e_dictkey), key);
2593 if (len == -1)
2594 clear_tv(&var1);
2595 return NULL;
2597 if (len == -1)
2598 lp->ll_newkey = vim_strsave(key);
2599 else
2600 lp->ll_newkey = vim_strnsave(key, len);
2601 if (len == -1)
2602 clear_tv(&var1);
2603 if (lp->ll_newkey == NULL)
2604 p = NULL;
2605 break;
2607 if (len == -1)
2608 clear_tv(&var1);
2609 lp->ll_tv = &lp->ll_di->di_tv;
2611 else
2614 * Get the number and item for the only or first index of the List.
2616 if (empty1)
2617 lp->ll_n1 = 0;
2618 else
2620 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2621 clear_tv(&var1);
2623 lp->ll_dict = NULL;
2624 lp->ll_list = lp->ll_tv->vval.v_list;
2625 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2626 if (lp->ll_li == NULL)
2628 if (lp->ll_n1 < 0)
2630 lp->ll_n1 = 0;
2631 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2634 if (lp->ll_li == NULL)
2636 if (lp->ll_range && !lp->ll_empty2)
2637 clear_tv(&var2);
2638 return NULL;
2642 * May need to find the item or absolute index for the second
2643 * index of a range.
2644 * When no index given: "lp->ll_empty2" is TRUE.
2645 * Otherwise "lp->ll_n2" is set to the second index.
2647 if (lp->ll_range && !lp->ll_empty2)
2649 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2650 clear_tv(&var2);
2651 if (lp->ll_n2 < 0)
2653 ni = list_find(lp->ll_list, lp->ll_n2);
2654 if (ni == NULL)
2655 return NULL;
2656 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2659 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2660 if (lp->ll_n1 < 0)
2661 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2662 if (lp->ll_n2 < lp->ll_n1)
2663 return NULL;
2666 lp->ll_tv = &lp->ll_li->li_tv;
2670 return p;
2674 * Clear lval "lp" that was filled by get_lval().
2676 static void
2677 clear_lval(lp)
2678 lval_T *lp;
2680 vim_free(lp->ll_exp_name);
2681 vim_free(lp->ll_newkey);
2685 * Set a variable that was parsed by get_lval() to "rettv".
2686 * "endp" points to just after the parsed name.
2687 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2689 static void
2690 set_var_lval(lp, endp, rettv, copy, op)
2691 lval_T *lp;
2692 char_u *endp;
2693 typval_T *rettv;
2694 int copy;
2695 char_u *op;
2697 int cc;
2698 listitem_T *ri;
2699 dictitem_T *di;
2701 if (lp->ll_tv == NULL)
2703 if (!check_changedtick(lp->ll_name))
2705 cc = *endp;
2706 *endp = NUL;
2707 if (op != NULL && *op != '=')
2709 typval_T tv;
2711 /* handle +=, -= and .= */
2712 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2713 &tv, TRUE) == OK)
2715 if (tv_op(&tv, rettv, op) == OK)
2716 set_var(lp->ll_name, &tv, FALSE);
2717 clear_tv(&tv);
2720 else
2721 set_var(lp->ll_name, rettv, copy);
2722 *endp = cc;
2725 else if (tv_check_lock(lp->ll_newkey == NULL
2726 ? lp->ll_tv->v_lock
2727 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2729 else if (lp->ll_range)
2732 * Assign the List values to the list items.
2734 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2736 if (op != NULL && *op != '=')
2737 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2738 else
2740 clear_tv(&lp->ll_li->li_tv);
2741 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2743 ri = ri->li_next;
2744 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2745 break;
2746 if (lp->ll_li->li_next == NULL)
2748 /* Need to add an empty item. */
2749 if (list_append_number(lp->ll_list, 0) == FAIL)
2751 ri = NULL;
2752 break;
2755 lp->ll_li = lp->ll_li->li_next;
2756 ++lp->ll_n1;
2758 if (ri != NULL)
2759 EMSG(_("E710: List value has more items than target"));
2760 else if (lp->ll_empty2
2761 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2762 : lp->ll_n1 != lp->ll_n2)
2763 EMSG(_("E711: List value has not enough items"));
2765 else
2768 * Assign to a List or Dictionary item.
2770 if (lp->ll_newkey != NULL)
2772 if (op != NULL && *op != '=')
2774 EMSG2(_(e_letwrong), op);
2775 return;
2778 /* Need to add an item to the Dictionary. */
2779 di = dictitem_alloc(lp->ll_newkey);
2780 if (di == NULL)
2781 return;
2782 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2784 vim_free(di);
2785 return;
2787 lp->ll_tv = &di->di_tv;
2789 else if (op != NULL && *op != '=')
2791 tv_op(lp->ll_tv, rettv, op);
2792 return;
2794 else
2795 clear_tv(lp->ll_tv);
2798 * Assign the value to the variable or list item.
2800 if (copy)
2801 copy_tv(rettv, lp->ll_tv);
2802 else
2804 *lp->ll_tv = *rettv;
2805 lp->ll_tv->v_lock = 0;
2806 init_tv(rettv);
2812 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2813 * Returns OK or FAIL.
2815 static int
2816 tv_op(tv1, tv2, op)
2817 typval_T *tv1;
2818 typval_T *tv2;
2819 char_u *op;
2821 long n;
2822 char_u numbuf[NUMBUFLEN];
2823 char_u *s;
2825 /* Can't do anything with a Funcref or a Dict on the right. */
2826 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2828 switch (tv1->v_type)
2830 case VAR_DICT:
2831 case VAR_FUNC:
2832 break;
2834 case VAR_LIST:
2835 if (*op != '+' || tv2->v_type != VAR_LIST)
2836 break;
2837 /* List += List */
2838 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2839 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2840 return OK;
2842 case VAR_NUMBER:
2843 case VAR_STRING:
2844 if (tv2->v_type == VAR_LIST)
2845 break;
2846 if (*op == '+' || *op == '-')
2848 /* nr += nr or nr -= nr*/
2849 n = get_tv_number(tv1);
2850 if (*op == '+')
2851 n += get_tv_number(tv2);
2852 else
2853 n -= get_tv_number(tv2);
2854 clear_tv(tv1);
2855 tv1->v_type = VAR_NUMBER;
2856 tv1->vval.v_number = n;
2858 else
2860 /* str .= str */
2861 s = get_tv_string(tv1);
2862 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2863 clear_tv(tv1);
2864 tv1->v_type = VAR_STRING;
2865 tv1->vval.v_string = s;
2867 return OK;
2871 EMSG2(_(e_letwrong), op);
2872 return FAIL;
2876 * Add a watcher to a list.
2878 static void
2879 list_add_watch(l, lw)
2880 list_T *l;
2881 listwatch_T *lw;
2883 lw->lw_next = l->lv_watch;
2884 l->lv_watch = lw;
2888 * Remove a watcher from a list.
2889 * No warning when it isn't found...
2891 static void
2892 list_rem_watch(l, lwrem)
2893 list_T *l;
2894 listwatch_T *lwrem;
2896 listwatch_T *lw, **lwp;
2898 lwp = &l->lv_watch;
2899 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2901 if (lw == lwrem)
2903 *lwp = lw->lw_next;
2904 break;
2906 lwp = &lw->lw_next;
2911 * Just before removing an item from a list: advance watchers to the next
2912 * item.
2914 static void
2915 list_fix_watch(l, item)
2916 list_T *l;
2917 listitem_T *item;
2919 listwatch_T *lw;
2921 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2922 if (lw->lw_item == item)
2923 lw->lw_item = item->li_next;
2927 * Evaluate the expression used in a ":for var in expr" command.
2928 * "arg" points to "var".
2929 * Set "*errp" to TRUE for an error, FALSE otherwise;
2930 * Return a pointer that holds the info. Null when there is an error.
2932 void *
2933 eval_for_line(arg, errp, nextcmdp, skip)
2934 char_u *arg;
2935 int *errp;
2936 char_u **nextcmdp;
2937 int skip;
2939 forinfo_T *fi;
2940 char_u *expr;
2941 typval_T tv;
2942 list_T *l;
2944 *errp = TRUE; /* default: there is an error */
2946 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
2947 if (fi == NULL)
2948 return NULL;
2950 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
2951 if (expr == NULL)
2952 return fi;
2954 expr = skipwhite(expr);
2955 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
2957 EMSG(_("E690: Missing \"in\" after :for"));
2958 return fi;
2961 if (skip)
2962 ++emsg_skip;
2963 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
2965 *errp = FALSE;
2966 if (!skip)
2968 l = tv.vval.v_list;
2969 if (tv.v_type != VAR_LIST || l == NULL)
2971 EMSG(_(e_listreq));
2972 clear_tv(&tv);
2974 else
2976 /* No need to increment the refcount, it's already set for the
2977 * list being used in "tv". */
2978 fi->fi_list = l;
2979 list_add_watch(l, &fi->fi_lw);
2980 fi->fi_lw.lw_item = l->lv_first;
2984 if (skip)
2985 --emsg_skip;
2987 return fi;
2991 * Use the first item in a ":for" list. Advance to the next.
2992 * Assign the values to the variable (list). "arg" points to the first one.
2993 * Return TRUE when a valid item was found, FALSE when at end of list or
2994 * something wrong.
2997 next_for_item(fi_void, arg)
2998 void *fi_void;
2999 char_u *arg;
3001 forinfo_T *fi = (forinfo_T *)fi_void;
3002 int result;
3003 listitem_T *item;
3005 item = fi->fi_lw.lw_item;
3006 if (item == NULL)
3007 result = FALSE;
3008 else
3010 fi->fi_lw.lw_item = item->li_next;
3011 result = (ex_let_vars(arg, &item->li_tv, TRUE,
3012 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3014 return result;
3018 * Free the structure used to store info used by ":for".
3020 void
3021 free_for_info(fi_void)
3022 void *fi_void;
3024 forinfo_T *fi = (forinfo_T *)fi_void;
3026 if (fi != NULL && fi->fi_list != NULL)
3028 list_rem_watch(fi->fi_list, &fi->fi_lw);
3029 list_unref(fi->fi_list);
3031 vim_free(fi);
3034 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3036 void
3037 set_context_for_expression(xp, arg, cmdidx)
3038 expand_T *xp;
3039 char_u *arg;
3040 cmdidx_T cmdidx;
3042 int got_eq = FALSE;
3043 int c;
3044 char_u *p;
3046 if (cmdidx == CMD_let)
3048 xp->xp_context = EXPAND_USER_VARS;
3049 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3051 /* ":let var1 var2 ...": find last space. */
3052 for (p = arg + STRLEN(arg); p >= arg; )
3054 xp->xp_pattern = p;
3055 mb_ptr_back(arg, p);
3056 if (vim_iswhite(*p))
3057 break;
3059 return;
3062 else
3063 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3064 : EXPAND_EXPRESSION;
3065 while ((xp->xp_pattern = vim_strpbrk(arg,
3066 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3068 c = *xp->xp_pattern;
3069 if (c == '&')
3071 c = xp->xp_pattern[1];
3072 if (c == '&')
3074 ++xp->xp_pattern;
3075 xp->xp_context = cmdidx != CMD_let || got_eq
3076 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3078 else if (c != ' ')
3080 xp->xp_context = EXPAND_SETTINGS;
3081 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3082 xp->xp_pattern += 2;
3086 else if (c == '$')
3088 /* environment variable */
3089 xp->xp_context = EXPAND_ENV_VARS;
3091 else if (c == '=')
3093 got_eq = TRUE;
3094 xp->xp_context = EXPAND_EXPRESSION;
3096 else if (c == '<'
3097 && xp->xp_context == EXPAND_FUNCTIONS
3098 && vim_strchr(xp->xp_pattern, '(') == NULL)
3100 /* Function name can start with "<SNR>" */
3101 break;
3103 else if (cmdidx != CMD_let || got_eq)
3105 if (c == '"') /* string */
3107 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3108 if (c == '\\' && xp->xp_pattern[1] != NUL)
3109 ++xp->xp_pattern;
3110 xp->xp_context = EXPAND_NOTHING;
3112 else if (c == '\'') /* literal string */
3114 /* Trick: '' is like stopping and starting a literal string. */
3115 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3116 /* skip */ ;
3117 xp->xp_context = EXPAND_NOTHING;
3119 else if (c == '|')
3121 if (xp->xp_pattern[1] == '|')
3123 ++xp->xp_pattern;
3124 xp->xp_context = EXPAND_EXPRESSION;
3126 else
3127 xp->xp_context = EXPAND_COMMANDS;
3129 else
3130 xp->xp_context = EXPAND_EXPRESSION;
3132 else
3133 /* Doesn't look like something valid, expand as an expression
3134 * anyway. */
3135 xp->xp_context = EXPAND_EXPRESSION;
3136 arg = xp->xp_pattern;
3137 if (*arg != NUL)
3138 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3139 /* skip */ ;
3141 xp->xp_pattern = arg;
3144 #endif /* FEAT_CMDL_COMPL */
3147 * ":1,25call func(arg1, arg2)" function call.
3149 void
3150 ex_call(eap)
3151 exarg_T *eap;
3153 char_u *arg = eap->arg;
3154 char_u *startarg;
3155 char_u *name;
3156 char_u *tofree;
3157 int len;
3158 typval_T rettv;
3159 linenr_T lnum;
3160 int doesrange;
3161 int failed = FALSE;
3162 funcdict_T fudi;
3164 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3165 if (fudi.fd_newkey != NULL)
3167 /* Still need to give an error message for missing key. */
3168 EMSG2(_(e_dictkey), fudi.fd_newkey);
3169 vim_free(fudi.fd_newkey);
3171 if (tofree == NULL)
3172 return;
3174 /* Increase refcount on dictionary, it could get deleted when evaluating
3175 * the arguments. */
3176 if (fudi.fd_dict != NULL)
3177 ++fudi.fd_dict->dv_refcount;
3179 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3180 len = (int)STRLEN(tofree);
3181 name = deref_func_name(tofree, &len);
3183 /* Skip white space to allow ":call func ()". Not good, but required for
3184 * backward compatibility. */
3185 startarg = skipwhite(arg);
3186 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3188 if (*startarg != '(')
3190 EMSG2(_("E107: Missing braces: %s"), eap->arg);
3191 goto end;
3195 * When skipping, evaluate the function once, to find the end of the
3196 * arguments.
3197 * When the function takes a range, this is discovered after the first
3198 * call, and the loop is broken.
3200 if (eap->skip)
3202 ++emsg_skip;
3203 lnum = eap->line2; /* do it once, also with an invalid range */
3205 else
3206 lnum = eap->line1;
3207 for ( ; lnum <= eap->line2; ++lnum)
3209 if (!eap->skip && eap->addr_count > 0)
3211 curwin->w_cursor.lnum = lnum;
3212 curwin->w_cursor.col = 0;
3214 arg = startarg;
3215 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3216 eap->line1, eap->line2, &doesrange,
3217 !eap->skip, fudi.fd_dict) == FAIL)
3219 failed = TRUE;
3220 break;
3223 /* Handle a function returning a Funcref, Dictionary or List. */
3224 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3226 failed = TRUE;
3227 break;
3230 clear_tv(&rettv);
3231 if (doesrange || eap->skip)
3232 break;
3234 /* Stop when immediately aborting on error, or when an interrupt
3235 * occurred or an exception was thrown but not caught.
3236 * get_func_tv() returned OK, so that the check for trailing
3237 * characters below is executed. */
3238 if (aborting())
3239 break;
3241 if (eap->skip)
3242 --emsg_skip;
3244 if (!failed)
3246 /* Check for trailing illegal characters and a following command. */
3247 if (!ends_excmd(*arg))
3249 emsg_severe = TRUE;
3250 EMSG(_(e_trailing));
3252 else
3253 eap->nextcmd = check_nextcmd(arg);
3256 end:
3257 dict_unref(fudi.fd_dict);
3258 vim_free(tofree);
3262 * ":unlet[!] var1 ... " command.
3264 void
3265 ex_unlet(eap)
3266 exarg_T *eap;
3268 ex_unletlock(eap, eap->arg, 0);
3272 * ":lockvar" and ":unlockvar" commands
3274 void
3275 ex_lockvar(eap)
3276 exarg_T *eap;
3278 char_u *arg = eap->arg;
3279 int deep = 2;
3281 if (eap->forceit)
3282 deep = -1;
3283 else if (vim_isdigit(*arg))
3285 deep = getdigits(&arg);
3286 arg = skipwhite(arg);
3289 ex_unletlock(eap, arg, deep);
3293 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3295 static void
3296 ex_unletlock(eap, argstart, deep)
3297 exarg_T *eap;
3298 char_u *argstart;
3299 int deep;
3301 char_u *arg = argstart;
3302 char_u *name_end;
3303 int error = FALSE;
3304 lval_T lv;
3308 /* Parse the name and find the end. */
3309 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3310 FNE_CHECK_START);
3311 if (lv.ll_name == NULL)
3312 error = TRUE; /* error but continue parsing */
3313 if (name_end == NULL || (!vim_iswhite(*name_end)
3314 && !ends_excmd(*name_end)))
3316 if (name_end != NULL)
3318 emsg_severe = TRUE;
3319 EMSG(_(e_trailing));
3321 if (!(eap->skip || error))
3322 clear_lval(&lv);
3323 break;
3326 if (!error && !eap->skip)
3328 if (eap->cmdidx == CMD_unlet)
3330 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3331 error = TRUE;
3333 else
3335 if (do_lock_var(&lv, name_end, deep,
3336 eap->cmdidx == CMD_lockvar) == FAIL)
3337 error = TRUE;
3341 if (!eap->skip)
3342 clear_lval(&lv);
3344 arg = skipwhite(name_end);
3345 } while (!ends_excmd(*arg));
3347 eap->nextcmd = check_nextcmd(arg);
3350 static int
3351 do_unlet_var(lp, name_end, forceit)
3352 lval_T *lp;
3353 char_u *name_end;
3354 int forceit;
3356 int ret = OK;
3357 int cc;
3359 if (lp->ll_tv == NULL)
3361 cc = *name_end;
3362 *name_end = NUL;
3364 /* Normal name or expanded name. */
3365 if (check_changedtick(lp->ll_name))
3366 ret = FAIL;
3367 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3368 ret = FAIL;
3369 *name_end = cc;
3371 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3372 return FAIL;
3373 else if (lp->ll_range)
3375 listitem_T *li;
3377 /* Delete a range of List items. */
3378 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3380 li = lp->ll_li->li_next;
3381 listitem_remove(lp->ll_list, lp->ll_li);
3382 lp->ll_li = li;
3383 ++lp->ll_n1;
3386 else
3388 if (lp->ll_list != NULL)
3389 /* unlet a List item. */
3390 listitem_remove(lp->ll_list, lp->ll_li);
3391 else
3392 /* unlet a Dictionary item. */
3393 dictitem_remove(lp->ll_dict, lp->ll_di);
3396 return ret;
3400 * "unlet" a variable. Return OK if it existed, FAIL if not.
3401 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3404 do_unlet(name, forceit)
3405 char_u *name;
3406 int forceit;
3408 hashtab_T *ht;
3409 hashitem_T *hi;
3410 char_u *varname;
3411 dictitem_T *di;
3413 ht = find_var_ht(name, &varname);
3414 if (ht != NULL && *varname != NUL)
3416 hi = hash_find(ht, varname);
3417 if (!HASHITEM_EMPTY(hi))
3419 di = HI2DI(hi);
3420 if (var_check_fixed(di->di_flags, name)
3421 || var_check_ro(di->di_flags, name))
3422 return FAIL;
3423 delete_var(ht, hi);
3424 return OK;
3427 if (forceit)
3428 return OK;
3429 EMSG2(_("E108: No such variable: \"%s\""), name);
3430 return FAIL;
3434 * Lock or unlock variable indicated by "lp".
3435 * "deep" is the levels to go (-1 for unlimited);
3436 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3438 static int
3439 do_lock_var(lp, name_end, deep, lock)
3440 lval_T *lp;
3441 char_u *name_end;
3442 int deep;
3443 int lock;
3445 int ret = OK;
3446 int cc;
3447 dictitem_T *di;
3449 if (deep == 0) /* nothing to do */
3450 return OK;
3452 if (lp->ll_tv == NULL)
3454 cc = *name_end;
3455 *name_end = NUL;
3457 /* Normal name or expanded name. */
3458 if (check_changedtick(lp->ll_name))
3459 ret = FAIL;
3460 else
3462 di = find_var(lp->ll_name, NULL);
3463 if (di == NULL)
3464 ret = FAIL;
3465 else
3467 if (lock)
3468 di->di_flags |= DI_FLAGS_LOCK;
3469 else
3470 di->di_flags &= ~DI_FLAGS_LOCK;
3471 item_lock(&di->di_tv, deep, lock);
3474 *name_end = cc;
3476 else if (lp->ll_range)
3478 listitem_T *li = lp->ll_li;
3480 /* (un)lock a range of List items. */
3481 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3483 item_lock(&li->li_tv, deep, lock);
3484 li = li->li_next;
3485 ++lp->ll_n1;
3488 else if (lp->ll_list != NULL)
3489 /* (un)lock a List item. */
3490 item_lock(&lp->ll_li->li_tv, deep, lock);
3491 else
3492 /* un(lock) a Dictionary item. */
3493 item_lock(&lp->ll_di->di_tv, deep, lock);
3495 return ret;
3499 * Lock or unlock an item. "deep" is nr of levels to go.
3501 static void
3502 item_lock(tv, deep, lock)
3503 typval_T *tv;
3504 int deep;
3505 int lock;
3507 static int recurse = 0;
3508 list_T *l;
3509 listitem_T *li;
3510 dict_T *d;
3511 hashitem_T *hi;
3512 int todo;
3514 if (recurse >= DICT_MAXNEST)
3516 EMSG(_("E743: variable nested too deep for (un)lock"));
3517 return;
3519 if (deep == 0)
3520 return;
3521 ++recurse;
3523 /* lock/unlock the item itself */
3524 if (lock)
3525 tv->v_lock |= VAR_LOCKED;
3526 else
3527 tv->v_lock &= ~VAR_LOCKED;
3529 switch (tv->v_type)
3531 case VAR_LIST:
3532 if ((l = tv->vval.v_list) != NULL)
3534 if (lock)
3535 l->lv_lock |= VAR_LOCKED;
3536 else
3537 l->lv_lock &= ~VAR_LOCKED;
3538 if (deep < 0 || deep > 1)
3539 /* recursive: lock/unlock the items the List contains */
3540 for (li = l->lv_first; li != NULL; li = li->li_next)
3541 item_lock(&li->li_tv, deep - 1, lock);
3543 break;
3544 case VAR_DICT:
3545 if ((d = tv->vval.v_dict) != NULL)
3547 if (lock)
3548 d->dv_lock |= VAR_LOCKED;
3549 else
3550 d->dv_lock &= ~VAR_LOCKED;
3551 if (deep < 0 || deep > 1)
3553 /* recursive: lock/unlock the items the List contains */
3554 todo = (int)d->dv_hashtab.ht_used;
3555 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3557 if (!HASHITEM_EMPTY(hi))
3559 --todo;
3560 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3566 --recurse;
3570 * Return TRUE if typeval "tv" is locked: Either tha value is locked itself or
3571 * it refers to a List or Dictionary that is locked.
3573 static int
3574 tv_islocked(tv)
3575 typval_T *tv;
3577 return (tv->v_lock & VAR_LOCKED)
3578 || (tv->v_type == VAR_LIST
3579 && tv->vval.v_list != NULL
3580 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3581 || (tv->v_type == VAR_DICT
3582 && tv->vval.v_dict != NULL
3583 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3586 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3588 * Delete all "menutrans_" variables.
3590 void
3591 del_menutrans_vars()
3593 hashitem_T *hi;
3594 int todo;
3596 hash_lock(&globvarht);
3597 todo = (int)globvarht.ht_used;
3598 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3600 if (!HASHITEM_EMPTY(hi))
3602 --todo;
3603 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3604 delete_var(&globvarht, hi);
3607 hash_unlock(&globvarht);
3609 #endif
3611 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3614 * Local string buffer for the next two functions to store a variable name
3615 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3616 * get_user_var_name().
3619 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3621 static char_u *varnamebuf = NULL;
3622 static int varnamebuflen = 0;
3625 * Function to concatenate a prefix and a variable name.
3627 static char_u *
3628 cat_prefix_varname(prefix, name)
3629 int prefix;
3630 char_u *name;
3632 int len;
3634 len = (int)STRLEN(name) + 3;
3635 if (len > varnamebuflen)
3637 vim_free(varnamebuf);
3638 len += 10; /* some additional space */
3639 varnamebuf = alloc(len);
3640 if (varnamebuf == NULL)
3642 varnamebuflen = 0;
3643 return NULL;
3645 varnamebuflen = len;
3647 *varnamebuf = prefix;
3648 varnamebuf[1] = ':';
3649 STRCPY(varnamebuf + 2, name);
3650 return varnamebuf;
3654 * Function given to ExpandGeneric() to obtain the list of user defined
3655 * (global/buffer/window/built-in) variable names.
3657 /*ARGSUSED*/
3658 char_u *
3659 get_user_var_name(xp, idx)
3660 expand_T *xp;
3661 int idx;
3663 static long_u gdone;
3664 static long_u bdone;
3665 static long_u wdone;
3666 #ifdef FEAT_WINDOWS
3667 static long_u tdone;
3668 #endif
3669 static int vidx;
3670 static hashitem_T *hi;
3671 hashtab_T *ht;
3673 if (idx == 0)
3675 gdone = bdone = wdone = vidx = 0;
3676 #ifdef FEAT_WINDOWS
3677 tdone = 0;
3678 #endif
3681 /* Global variables */
3682 if (gdone < globvarht.ht_used)
3684 if (gdone++ == 0)
3685 hi = globvarht.ht_array;
3686 else
3687 ++hi;
3688 while (HASHITEM_EMPTY(hi))
3689 ++hi;
3690 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3691 return cat_prefix_varname('g', hi->hi_key);
3692 return hi->hi_key;
3695 /* b: variables */
3696 ht = &curbuf->b_vars.dv_hashtab;
3697 if (bdone < ht->ht_used)
3699 if (bdone++ == 0)
3700 hi = ht->ht_array;
3701 else
3702 ++hi;
3703 while (HASHITEM_EMPTY(hi))
3704 ++hi;
3705 return cat_prefix_varname('b', hi->hi_key);
3707 if (bdone == ht->ht_used)
3709 ++bdone;
3710 return (char_u *)"b:changedtick";
3713 /* w: variables */
3714 ht = &curwin->w_vars.dv_hashtab;
3715 if (wdone < ht->ht_used)
3717 if (wdone++ == 0)
3718 hi = ht->ht_array;
3719 else
3720 ++hi;
3721 while (HASHITEM_EMPTY(hi))
3722 ++hi;
3723 return cat_prefix_varname('w', hi->hi_key);
3726 #ifdef FEAT_WINDOWS
3727 /* t: variables */
3728 ht = &curtab->tp_vars.dv_hashtab;
3729 if (tdone < ht->ht_used)
3731 if (tdone++ == 0)
3732 hi = ht->ht_array;
3733 else
3734 ++hi;
3735 while (HASHITEM_EMPTY(hi))
3736 ++hi;
3737 return cat_prefix_varname('t', hi->hi_key);
3739 #endif
3741 /* v: variables */
3742 if (vidx < VV_LEN)
3743 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3745 vim_free(varnamebuf);
3746 varnamebuf = NULL;
3747 varnamebuflen = 0;
3748 return NULL;
3751 #endif /* FEAT_CMDL_COMPL */
3754 * types for expressions.
3756 typedef enum
3758 TYPE_UNKNOWN = 0
3759 , TYPE_EQUAL /* == */
3760 , TYPE_NEQUAL /* != */
3761 , TYPE_GREATER /* > */
3762 , TYPE_GEQUAL /* >= */
3763 , TYPE_SMALLER /* < */
3764 , TYPE_SEQUAL /* <= */
3765 , TYPE_MATCH /* =~ */
3766 , TYPE_NOMATCH /* !~ */
3767 } exptype_T;
3770 * The "evaluate" argument: When FALSE, the argument is only parsed but not
3771 * executed. The function may return OK, but the rettv will be of type
3772 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
3776 * Handle zero level expression.
3777 * This calls eval1() and handles error message and nextcmd.
3778 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3779 * Note: "rettv.v_lock" is not set.
3780 * Return OK or FAIL.
3782 static int
3783 eval0(arg, rettv, nextcmd, evaluate)
3784 char_u *arg;
3785 typval_T *rettv;
3786 char_u **nextcmd;
3787 int evaluate;
3789 int ret;
3790 char_u *p;
3792 p = skipwhite(arg);
3793 ret = eval1(&p, rettv, evaluate);
3794 if (ret == FAIL || !ends_excmd(*p))
3796 if (ret != FAIL)
3797 clear_tv(rettv);
3799 * Report the invalid expression unless the expression evaluation has
3800 * been cancelled due to an aborting error, an interrupt, or an
3801 * exception.
3803 if (!aborting())
3804 EMSG2(_(e_invexpr2), arg);
3805 ret = FAIL;
3807 if (nextcmd != NULL)
3808 *nextcmd = check_nextcmd(p);
3810 return ret;
3814 * Handle top level expression:
3815 * expr1 ? expr0 : expr0
3817 * "arg" must point to the first non-white of the expression.
3818 * "arg" is advanced to the next non-white after the recognized expression.
3820 * Note: "rettv.v_lock" is not set.
3822 * Return OK or FAIL.
3824 static int
3825 eval1(arg, rettv, evaluate)
3826 char_u **arg;
3827 typval_T *rettv;
3828 int evaluate;
3830 int result;
3831 typval_T var2;
3834 * Get the first variable.
3836 if (eval2(arg, rettv, evaluate) == FAIL)
3837 return FAIL;
3839 if ((*arg)[0] == '?')
3841 result = FALSE;
3842 if (evaluate)
3844 int error = FALSE;
3846 if (get_tv_number_chk(rettv, &error) != 0)
3847 result = TRUE;
3848 clear_tv(rettv);
3849 if (error)
3850 return FAIL;
3854 * Get the second variable.
3856 *arg = skipwhite(*arg + 1);
3857 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
3858 return FAIL;
3861 * Check for the ":".
3863 if ((*arg)[0] != ':')
3865 EMSG(_("E109: Missing ':' after '?'"));
3866 if (evaluate && result)
3867 clear_tv(rettv);
3868 return FAIL;
3872 * Get the third variable.
3874 *arg = skipwhite(*arg + 1);
3875 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
3877 if (evaluate && result)
3878 clear_tv(rettv);
3879 return FAIL;
3881 if (evaluate && !result)
3882 *rettv = var2;
3885 return OK;
3889 * Handle first level expression:
3890 * expr2 || expr2 || expr2 logical OR
3892 * "arg" must point to the first non-white of the expression.
3893 * "arg" is advanced to the next non-white after the recognized expression.
3895 * Return OK or FAIL.
3897 static int
3898 eval2(arg, rettv, evaluate)
3899 char_u **arg;
3900 typval_T *rettv;
3901 int evaluate;
3903 typval_T var2;
3904 long result;
3905 int first;
3906 int error = FALSE;
3909 * Get the first variable.
3911 if (eval3(arg, rettv, evaluate) == FAIL)
3912 return FAIL;
3915 * Repeat until there is no following "||".
3917 first = TRUE;
3918 result = FALSE;
3919 while ((*arg)[0] == '|' && (*arg)[1] == '|')
3921 if (evaluate && first)
3923 if (get_tv_number_chk(rettv, &error) != 0)
3924 result = TRUE;
3925 clear_tv(rettv);
3926 if (error)
3927 return FAIL;
3928 first = FALSE;
3932 * Get the second variable.
3934 *arg = skipwhite(*arg + 2);
3935 if (eval3(arg, &var2, evaluate && !result) == FAIL)
3936 return FAIL;
3939 * Compute the result.
3941 if (evaluate && !result)
3943 if (get_tv_number_chk(&var2, &error) != 0)
3944 result = TRUE;
3945 clear_tv(&var2);
3946 if (error)
3947 return FAIL;
3949 if (evaluate)
3951 rettv->v_type = VAR_NUMBER;
3952 rettv->vval.v_number = result;
3956 return OK;
3960 * Handle second level expression:
3961 * expr3 && expr3 && expr3 logical AND
3963 * "arg" must point to the first non-white of the expression.
3964 * "arg" is advanced to the next non-white after the recognized expression.
3966 * Return OK or FAIL.
3968 static int
3969 eval3(arg, rettv, evaluate)
3970 char_u **arg;
3971 typval_T *rettv;
3972 int evaluate;
3974 typval_T var2;
3975 long result;
3976 int first;
3977 int error = FALSE;
3980 * Get the first variable.
3982 if (eval4(arg, rettv, evaluate) == FAIL)
3983 return FAIL;
3986 * Repeat until there is no following "&&".
3988 first = TRUE;
3989 result = TRUE;
3990 while ((*arg)[0] == '&' && (*arg)[1] == '&')
3992 if (evaluate && first)
3994 if (get_tv_number_chk(rettv, &error) == 0)
3995 result = FALSE;
3996 clear_tv(rettv);
3997 if (error)
3998 return FAIL;
3999 first = FALSE;
4003 * Get the second variable.
4005 *arg = skipwhite(*arg + 2);
4006 if (eval4(arg, &var2, evaluate && result) == FAIL)
4007 return FAIL;
4010 * Compute the result.
4012 if (evaluate && result)
4014 if (get_tv_number_chk(&var2, &error) == 0)
4015 result = FALSE;
4016 clear_tv(&var2);
4017 if (error)
4018 return FAIL;
4020 if (evaluate)
4022 rettv->v_type = VAR_NUMBER;
4023 rettv->vval.v_number = result;
4027 return OK;
4031 * Handle third level expression:
4032 * var1 == var2
4033 * var1 =~ var2
4034 * var1 != var2
4035 * var1 !~ var2
4036 * var1 > var2
4037 * var1 >= var2
4038 * var1 < var2
4039 * var1 <= var2
4040 * var1 is var2
4041 * var1 isnot var2
4043 * "arg" must point to the first non-white of the expression.
4044 * "arg" is advanced to the next non-white after the recognized expression.
4046 * Return OK or FAIL.
4048 static int
4049 eval4(arg, rettv, evaluate)
4050 char_u **arg;
4051 typval_T *rettv;
4052 int evaluate;
4054 typval_T var2;
4055 char_u *p;
4056 int i;
4057 exptype_T type = TYPE_UNKNOWN;
4058 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4059 int len = 2;
4060 long n1, n2;
4061 char_u *s1, *s2;
4062 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4063 regmatch_T regmatch;
4064 int ic;
4065 char_u *save_cpo;
4068 * Get the first variable.
4070 if (eval5(arg, rettv, evaluate) == FAIL)
4071 return FAIL;
4073 p = *arg;
4074 switch (p[0])
4076 case '=': if (p[1] == '=')
4077 type = TYPE_EQUAL;
4078 else if (p[1] == '~')
4079 type = TYPE_MATCH;
4080 break;
4081 case '!': if (p[1] == '=')
4082 type = TYPE_NEQUAL;
4083 else if (p[1] == '~')
4084 type = TYPE_NOMATCH;
4085 break;
4086 case '>': if (p[1] != '=')
4088 type = TYPE_GREATER;
4089 len = 1;
4091 else
4092 type = TYPE_GEQUAL;
4093 break;
4094 case '<': if (p[1] != '=')
4096 type = TYPE_SMALLER;
4097 len = 1;
4099 else
4100 type = TYPE_SEQUAL;
4101 break;
4102 case 'i': if (p[1] == 's')
4104 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4105 len = 5;
4106 if (!vim_isIDc(p[len]))
4108 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4109 type_is = TRUE;
4112 break;
4116 * If there is a comparitive operator, use it.
4118 if (type != TYPE_UNKNOWN)
4120 /* extra question mark appended: ignore case */
4121 if (p[len] == '?')
4123 ic = TRUE;
4124 ++len;
4126 /* extra '#' appended: match case */
4127 else if (p[len] == '#')
4129 ic = FALSE;
4130 ++len;
4132 /* nothing appened: use 'ignorecase' */
4133 else
4134 ic = p_ic;
4137 * Get the second variable.
4139 *arg = skipwhite(p + len);
4140 if (eval5(arg, &var2, evaluate) == FAIL)
4142 clear_tv(rettv);
4143 return FAIL;
4146 if (evaluate)
4148 if (type_is && rettv->v_type != var2.v_type)
4150 /* For "is" a different type always means FALSE, for "notis"
4151 * it means TRUE. */
4152 n1 = (type == TYPE_NEQUAL);
4154 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4156 if (type_is)
4158 n1 = (rettv->v_type == var2.v_type
4159 && rettv->vval.v_list == var2.vval.v_list);
4160 if (type == TYPE_NEQUAL)
4161 n1 = !n1;
4163 else if (rettv->v_type != var2.v_type
4164 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4166 if (rettv->v_type != var2.v_type)
4167 EMSG(_("E691: Can only compare List with List"));
4168 else
4169 EMSG(_("E692: Invalid operation for Lists"));
4170 clear_tv(rettv);
4171 clear_tv(&var2);
4172 return FAIL;
4174 else
4176 /* Compare two Lists for being equal or unequal. */
4177 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
4178 if (type == TYPE_NEQUAL)
4179 n1 = !n1;
4183 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4185 if (type_is)
4187 n1 = (rettv->v_type == var2.v_type
4188 && rettv->vval.v_dict == var2.vval.v_dict);
4189 if (type == TYPE_NEQUAL)
4190 n1 = !n1;
4192 else if (rettv->v_type != var2.v_type
4193 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4195 if (rettv->v_type != var2.v_type)
4196 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4197 else
4198 EMSG(_("E736: Invalid operation for Dictionary"));
4199 clear_tv(rettv);
4200 clear_tv(&var2);
4201 return FAIL;
4203 else
4205 /* Compare two Dictionaries for being equal or unequal. */
4206 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4207 if (type == TYPE_NEQUAL)
4208 n1 = !n1;
4212 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4214 if (rettv->v_type != var2.v_type
4215 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4217 if (rettv->v_type != var2.v_type)
4218 EMSG(_("E693: Can only compare Funcref with Funcref"));
4219 else
4220 EMSG(_("E694: Invalid operation for Funcrefs"));
4221 clear_tv(rettv);
4222 clear_tv(&var2);
4223 return FAIL;
4225 else
4227 /* Compare two Funcrefs for being equal or unequal. */
4228 if (rettv->vval.v_string == NULL
4229 || var2.vval.v_string == NULL)
4230 n1 = FALSE;
4231 else
4232 n1 = STRCMP(rettv->vval.v_string,
4233 var2.vval.v_string) == 0;
4234 if (type == TYPE_NEQUAL)
4235 n1 = !n1;
4240 * If one of the two variables is a number, compare as a number.
4241 * When using "=~" or "!~", always compare as string.
4243 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4244 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4246 n1 = get_tv_number(rettv);
4247 n2 = get_tv_number(&var2);
4248 switch (type)
4250 case TYPE_EQUAL: n1 = (n1 == n2); break;
4251 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4252 case TYPE_GREATER: n1 = (n1 > n2); break;
4253 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4254 case TYPE_SMALLER: n1 = (n1 < n2); break;
4255 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4256 case TYPE_UNKNOWN:
4257 case TYPE_MATCH:
4258 case TYPE_NOMATCH: break; /* avoid gcc warning */
4261 else
4263 s1 = get_tv_string_buf(rettv, buf1);
4264 s2 = get_tv_string_buf(&var2, buf2);
4265 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4266 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4267 else
4268 i = 0;
4269 n1 = FALSE;
4270 switch (type)
4272 case TYPE_EQUAL: n1 = (i == 0); break;
4273 case TYPE_NEQUAL: n1 = (i != 0); break;
4274 case TYPE_GREATER: n1 = (i > 0); break;
4275 case TYPE_GEQUAL: n1 = (i >= 0); break;
4276 case TYPE_SMALLER: n1 = (i < 0); break;
4277 case TYPE_SEQUAL: n1 = (i <= 0); break;
4279 case TYPE_MATCH:
4280 case TYPE_NOMATCH:
4281 /* avoid 'l' flag in 'cpoptions' */
4282 save_cpo = p_cpo;
4283 p_cpo = (char_u *)"";
4284 regmatch.regprog = vim_regcomp(s2,
4285 RE_MAGIC + RE_STRING);
4286 regmatch.rm_ic = ic;
4287 if (regmatch.regprog != NULL)
4289 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4290 vim_free(regmatch.regprog);
4291 if (type == TYPE_NOMATCH)
4292 n1 = !n1;
4294 p_cpo = save_cpo;
4295 break;
4297 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4300 clear_tv(rettv);
4301 clear_tv(&var2);
4302 rettv->v_type = VAR_NUMBER;
4303 rettv->vval.v_number = n1;
4307 return OK;
4311 * Handle fourth level expression:
4312 * + number addition
4313 * - number subtraction
4314 * . string concatenation
4316 * "arg" must point to the first non-white of the expression.
4317 * "arg" is advanced to the next non-white after the recognized expression.
4319 * Return OK or FAIL.
4321 static int
4322 eval5(arg, rettv, evaluate)
4323 char_u **arg;
4324 typval_T *rettv;
4325 int evaluate;
4327 typval_T var2;
4328 typval_T var3;
4329 int op;
4330 long n1, n2;
4331 char_u *s1, *s2;
4332 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4333 char_u *p;
4336 * Get the first variable.
4338 if (eval6(arg, rettv, evaluate) == FAIL)
4339 return FAIL;
4342 * Repeat computing, until no '+', '-' or '.' is following.
4344 for (;;)
4346 op = **arg;
4347 if (op != '+' && op != '-' && op != '.')
4348 break;
4350 if (op != '+' || rettv->v_type != VAR_LIST)
4352 /* For "list + ...", an illegal use of the first operand as
4353 * a number cannot be determined before evaluating the 2nd
4354 * operand: if this is also a list, all is ok.
4355 * For "something . ...", "something - ..." or "non-list + ...",
4356 * we know that the first operand needs to be a string or number
4357 * without evaluating the 2nd operand. So check before to avoid
4358 * side effects after an error. */
4359 if (evaluate && get_tv_string_chk(rettv) == NULL)
4361 clear_tv(rettv);
4362 return FAIL;
4367 * Get the second variable.
4369 *arg = skipwhite(*arg + 1);
4370 if (eval6(arg, &var2, evaluate) == FAIL)
4372 clear_tv(rettv);
4373 return FAIL;
4376 if (evaluate)
4379 * Compute the result.
4381 if (op == '.')
4383 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4384 s2 = get_tv_string_buf_chk(&var2, buf2);
4385 if (s2 == NULL) /* type error ? */
4387 clear_tv(rettv);
4388 clear_tv(&var2);
4389 return FAIL;
4391 p = concat_str(s1, s2);
4392 clear_tv(rettv);
4393 rettv->v_type = VAR_STRING;
4394 rettv->vval.v_string = p;
4396 else if (op == '+' && rettv->v_type == VAR_LIST
4397 && var2.v_type == VAR_LIST)
4399 /* concatenate Lists */
4400 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4401 &var3) == FAIL)
4403 clear_tv(rettv);
4404 clear_tv(&var2);
4405 return FAIL;
4407 clear_tv(rettv);
4408 *rettv = var3;
4410 else
4412 int error = FALSE;
4414 n1 = get_tv_number_chk(rettv, &error);
4415 if (error)
4417 /* This can only happen for "list + non-list".
4418 * For "non-list + ..." or "something - ...", we returned
4419 * before evaluating the 2nd operand. */
4420 clear_tv(rettv);
4421 return FAIL;
4423 n2 = get_tv_number_chk(&var2, &error);
4424 if (error)
4426 clear_tv(rettv);
4427 clear_tv(&var2);
4428 return FAIL;
4430 clear_tv(rettv);
4431 if (op == '+')
4432 n1 = n1 + n2;
4433 else
4434 n1 = n1 - n2;
4435 rettv->v_type = VAR_NUMBER;
4436 rettv->vval.v_number = n1;
4438 clear_tv(&var2);
4441 return OK;
4445 * Handle fifth level expression:
4446 * * number multiplication
4447 * / number division
4448 * % number modulo
4450 * "arg" must point to the first non-white of the expression.
4451 * "arg" is advanced to the next non-white after the recognized expression.
4453 * Return OK or FAIL.
4455 static int
4456 eval6(arg, rettv, evaluate)
4457 char_u **arg;
4458 typval_T *rettv;
4459 int evaluate;
4461 typval_T var2;
4462 int op;
4463 long n1, n2;
4464 int error = FALSE;
4467 * Get the first variable.
4469 if (eval7(arg, rettv, evaluate) == FAIL)
4470 return FAIL;
4473 * Repeat computing, until no '*', '/' or '%' is following.
4475 for (;;)
4477 op = **arg;
4478 if (op != '*' && op != '/' && op != '%')
4479 break;
4481 if (evaluate)
4483 n1 = get_tv_number_chk(rettv, &error);
4484 clear_tv(rettv);
4485 if (error)
4486 return FAIL;
4488 else
4489 n1 = 0;
4492 * Get the second variable.
4494 *arg = skipwhite(*arg + 1);
4495 if (eval7(arg, &var2, evaluate) == FAIL)
4496 return FAIL;
4498 if (evaluate)
4500 n2 = get_tv_number_chk(&var2, &error);
4501 clear_tv(&var2);
4502 if (error)
4503 return FAIL;
4506 * Compute the result.
4508 if (op == '*')
4509 n1 = n1 * n2;
4510 else if (op == '/')
4512 if (n2 == 0) /* give an error message? */
4513 n1 = 0x7fffffffL;
4514 else
4515 n1 = n1 / n2;
4517 else
4519 if (n2 == 0) /* give an error message? */
4520 n1 = 0;
4521 else
4522 n1 = n1 % n2;
4524 rettv->v_type = VAR_NUMBER;
4525 rettv->vval.v_number = n1;
4529 return OK;
4533 * Handle sixth level expression:
4534 * number number constant
4535 * "string" string constant
4536 * 'string' literal string constant
4537 * &option-name option value
4538 * @r register contents
4539 * identifier variable value
4540 * function() function call
4541 * $VAR environment variable
4542 * (expression) nested expression
4543 * [expr, expr] List
4544 * {key: val, key: val} Dictionary
4546 * Also handle:
4547 * ! in front logical NOT
4548 * - in front unary minus
4549 * + in front unary plus (ignored)
4550 * trailing [] subscript in String or List
4551 * trailing .name entry in Dictionary
4553 * "arg" must point to the first non-white of the expression.
4554 * "arg" is advanced to the next non-white after the recognized expression.
4556 * Return OK or FAIL.
4558 static int
4559 eval7(arg, rettv, evaluate)
4560 char_u **arg;
4561 typval_T *rettv;
4562 int evaluate;
4564 long n;
4565 int len;
4566 char_u *s;
4567 int val;
4568 char_u *start_leader, *end_leader;
4569 int ret = OK;
4570 char_u *alias;
4573 * Initialise variable so that clear_tv() can't mistake this for a
4574 * string and free a string that isn't there.
4576 rettv->v_type = VAR_UNKNOWN;
4579 * Skip '!' and '-' characters. They are handled later.
4581 start_leader = *arg;
4582 while (**arg == '!' || **arg == '-' || **arg == '+')
4583 *arg = skipwhite(*arg + 1);
4584 end_leader = *arg;
4586 switch (**arg)
4589 * Number constant.
4591 case '0':
4592 case '1':
4593 case '2':
4594 case '3':
4595 case '4':
4596 case '5':
4597 case '6':
4598 case '7':
4599 case '8':
4600 case '9':
4601 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4602 *arg += len;
4603 if (evaluate)
4605 rettv->v_type = VAR_NUMBER;
4606 rettv->vval.v_number = n;
4608 break;
4611 * String constant: "string".
4613 case '"': ret = get_string_tv(arg, rettv, evaluate);
4614 break;
4617 * Literal string constant: 'str''ing'.
4619 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
4620 break;
4623 * List: [expr, expr]
4625 case '[': ret = get_list_tv(arg, rettv, evaluate);
4626 break;
4629 * Dictionary: {key: val, key: val}
4631 case '{': ret = get_dict_tv(arg, rettv, evaluate);
4632 break;
4635 * Option value: &name
4637 case '&': ret = get_option_tv(arg, rettv, evaluate);
4638 break;
4641 * Environment variable: $VAR.
4643 case '$': ret = get_env_tv(arg, rettv, evaluate);
4644 break;
4647 * Register contents: @r.
4649 case '@': ++*arg;
4650 if (evaluate)
4652 rettv->v_type = VAR_STRING;
4653 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4655 if (**arg != NUL)
4656 ++*arg;
4657 break;
4660 * nested expression: (expression).
4662 case '(': *arg = skipwhite(*arg + 1);
4663 ret = eval1(arg, rettv, evaluate); /* recursive! */
4664 if (**arg == ')')
4665 ++*arg;
4666 else if (ret == OK)
4668 EMSG(_("E110: Missing ')'"));
4669 clear_tv(rettv);
4670 ret = FAIL;
4672 break;
4674 default: ret = NOTDONE;
4675 break;
4678 if (ret == NOTDONE)
4681 * Must be a variable or function name.
4682 * Can also be a curly-braces kind of name: {expr}.
4684 s = *arg;
4685 len = get_name_len(arg, &alias, evaluate, TRUE);
4686 if (alias != NULL)
4687 s = alias;
4689 if (len <= 0)
4690 ret = FAIL;
4691 else
4693 if (**arg == '(') /* recursive! */
4695 /* If "s" is the name of a variable of type VAR_FUNC
4696 * use its contents. */
4697 s = deref_func_name(s, &len);
4699 /* Invoke the function. */
4700 ret = get_func_tv(s, len, rettv, arg,
4701 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
4702 &len, evaluate, NULL);
4703 /* Stop the expression evaluation when immediately
4704 * aborting on error, or when an interrupt occurred or
4705 * an exception was thrown but not caught. */
4706 if (aborting())
4708 if (ret == OK)
4709 clear_tv(rettv);
4710 ret = FAIL;
4713 else if (evaluate)
4714 ret = get_var_tv(s, len, rettv, TRUE);
4715 else
4716 ret = OK;
4719 if (alias != NULL)
4720 vim_free(alias);
4723 *arg = skipwhite(*arg);
4725 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
4726 * expr(expr). */
4727 if (ret == OK)
4728 ret = handle_subscript(arg, rettv, evaluate, TRUE);
4731 * Apply logical NOT and unary '-', from right to left, ignore '+'.
4733 if (ret == OK && evaluate && end_leader > start_leader)
4735 int error = FALSE;
4737 val = get_tv_number_chk(rettv, &error);
4738 if (error)
4740 clear_tv(rettv);
4741 ret = FAIL;
4743 else
4745 while (end_leader > start_leader)
4747 --end_leader;
4748 if (*end_leader == '!')
4749 val = !val;
4750 else if (*end_leader == '-')
4751 val = -val;
4753 clear_tv(rettv);
4754 rettv->v_type = VAR_NUMBER;
4755 rettv->vval.v_number = val;
4759 return ret;
4763 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
4764 * "*arg" points to the '[' or '.'.
4765 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
4767 static int
4768 eval_index(arg, rettv, evaluate, verbose)
4769 char_u **arg;
4770 typval_T *rettv;
4771 int evaluate;
4772 int verbose; /* give error messages */
4774 int empty1 = FALSE, empty2 = FALSE;
4775 typval_T var1, var2;
4776 long n1, n2 = 0;
4777 long len = -1;
4778 int range = FALSE;
4779 char_u *s;
4780 char_u *key = NULL;
4782 if (rettv->v_type == VAR_FUNC)
4784 if (verbose)
4785 EMSG(_("E695: Cannot index a Funcref"));
4786 return FAIL;
4789 if (**arg == '.')
4792 * dict.name
4794 key = *arg + 1;
4795 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
4797 if (len == 0)
4798 return FAIL;
4799 *arg = skipwhite(key + len);
4801 else
4804 * something[idx]
4806 * Get the (first) variable from inside the [].
4808 *arg = skipwhite(*arg + 1);
4809 if (**arg == ':')
4810 empty1 = TRUE;
4811 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
4812 return FAIL;
4813 else if (evaluate && get_tv_string_chk(&var1) == NULL)
4815 /* not a number or string */
4816 clear_tv(&var1);
4817 return FAIL;
4821 * Get the second variable from inside the [:].
4823 if (**arg == ':')
4825 range = TRUE;
4826 *arg = skipwhite(*arg + 1);
4827 if (**arg == ']')
4828 empty2 = TRUE;
4829 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
4831 if (!empty1)
4832 clear_tv(&var1);
4833 return FAIL;
4835 else if (evaluate && get_tv_string_chk(&var2) == NULL)
4837 /* not a number or string */
4838 if (!empty1)
4839 clear_tv(&var1);
4840 clear_tv(&var2);
4841 return FAIL;
4845 /* Check for the ']'. */
4846 if (**arg != ']')
4848 if (verbose)
4849 EMSG(_(e_missbrac));
4850 clear_tv(&var1);
4851 if (range)
4852 clear_tv(&var2);
4853 return FAIL;
4855 *arg = skipwhite(*arg + 1); /* skip the ']' */
4858 if (evaluate)
4860 n1 = 0;
4861 if (!empty1 && rettv->v_type != VAR_DICT)
4863 n1 = get_tv_number(&var1);
4864 clear_tv(&var1);
4866 if (range)
4868 if (empty2)
4869 n2 = -1;
4870 else
4872 n2 = get_tv_number(&var2);
4873 clear_tv(&var2);
4877 switch (rettv->v_type)
4879 case VAR_NUMBER:
4880 case VAR_STRING:
4881 s = get_tv_string(rettv);
4882 len = (long)STRLEN(s);
4883 if (range)
4885 /* The resulting variable is a substring. If the indexes
4886 * are out of range the result is empty. */
4887 if (n1 < 0)
4889 n1 = len + n1;
4890 if (n1 < 0)
4891 n1 = 0;
4893 if (n2 < 0)
4894 n2 = len + n2;
4895 else if (n2 >= len)
4896 n2 = len;
4897 if (n1 >= len || n2 < 0 || n1 > n2)
4898 s = NULL;
4899 else
4900 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
4902 else
4904 /* The resulting variable is a string of a single
4905 * character. If the index is too big or negative the
4906 * result is empty. */
4907 if (n1 >= len || n1 < 0)
4908 s = NULL;
4909 else
4910 s = vim_strnsave(s + n1, 1);
4912 clear_tv(rettv);
4913 rettv->v_type = VAR_STRING;
4914 rettv->vval.v_string = s;
4915 break;
4917 case VAR_LIST:
4918 len = list_len(rettv->vval.v_list);
4919 if (n1 < 0)
4920 n1 = len + n1;
4921 if (!empty1 && (n1 < 0 || n1 >= len))
4923 /* For a range we allow invalid values and return an empty
4924 * list. A list index out of range is an error. */
4925 if (!range)
4927 if (verbose)
4928 EMSGN(_(e_listidx), n1);
4929 return FAIL;
4931 n1 = len;
4933 if (range)
4935 list_T *l;
4936 listitem_T *item;
4938 if (n2 < 0)
4939 n2 = len + n2;
4940 else if (n2 >= len)
4941 n2 = len - 1;
4942 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
4943 n2 = -1;
4944 l = list_alloc();
4945 if (l == NULL)
4946 return FAIL;
4947 for (item = list_find(rettv->vval.v_list, n1);
4948 n1 <= n2; ++n1)
4950 if (list_append_tv(l, &item->li_tv) == FAIL)
4952 list_free(l, TRUE);
4953 return FAIL;
4955 item = item->li_next;
4957 clear_tv(rettv);
4958 rettv->v_type = VAR_LIST;
4959 rettv->vval.v_list = l;
4960 ++l->lv_refcount;
4962 else
4964 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
4965 clear_tv(rettv);
4966 *rettv = var1;
4968 break;
4970 case VAR_DICT:
4971 if (range)
4973 if (verbose)
4974 EMSG(_(e_dictrange));
4975 if (len == -1)
4976 clear_tv(&var1);
4977 return FAIL;
4980 dictitem_T *item;
4982 if (len == -1)
4984 key = get_tv_string(&var1);
4985 if (*key == NUL)
4987 if (verbose)
4988 EMSG(_(e_emptykey));
4989 clear_tv(&var1);
4990 return FAIL;
4994 item = dict_find(rettv->vval.v_dict, key, (int)len);
4996 if (item == NULL && verbose)
4997 EMSG2(_(e_dictkey), key);
4998 if (len == -1)
4999 clear_tv(&var1);
5000 if (item == NULL)
5001 return FAIL;
5003 copy_tv(&item->di_tv, &var1);
5004 clear_tv(rettv);
5005 *rettv = var1;
5007 break;
5011 return OK;
5015 * Get an option value.
5016 * "arg" points to the '&' or '+' before the option name.
5017 * "arg" is advanced to character after the option name.
5018 * Return OK or FAIL.
5020 static int
5021 get_option_tv(arg, rettv, evaluate)
5022 char_u **arg;
5023 typval_T *rettv; /* when NULL, only check if option exists */
5024 int evaluate;
5026 char_u *option_end;
5027 long numval;
5028 char_u *stringval;
5029 int opt_type;
5030 int c;
5031 int working = (**arg == '+'); /* has("+option") */
5032 int ret = OK;
5033 int opt_flags;
5036 * Isolate the option name and find its value.
5038 option_end = find_option_end(arg, &opt_flags);
5039 if (option_end == NULL)
5041 if (rettv != NULL)
5042 EMSG2(_("E112: Option name missing: %s"), *arg);
5043 return FAIL;
5046 if (!evaluate)
5048 *arg = option_end;
5049 return OK;
5052 c = *option_end;
5053 *option_end = NUL;
5054 opt_type = get_option_value(*arg, &numval,
5055 rettv == NULL ? NULL : &stringval, opt_flags);
5057 if (opt_type == -3) /* invalid name */
5059 if (rettv != NULL)
5060 EMSG2(_("E113: Unknown option: %s"), *arg);
5061 ret = FAIL;
5063 else if (rettv != NULL)
5065 if (opt_type == -2) /* hidden string option */
5067 rettv->v_type = VAR_STRING;
5068 rettv->vval.v_string = NULL;
5070 else if (opt_type == -1) /* hidden number option */
5072 rettv->v_type = VAR_NUMBER;
5073 rettv->vval.v_number = 0;
5075 else if (opt_type == 1) /* number option */
5077 rettv->v_type = VAR_NUMBER;
5078 rettv->vval.v_number = numval;
5080 else /* string option */
5082 rettv->v_type = VAR_STRING;
5083 rettv->vval.v_string = stringval;
5086 else if (working && (opt_type == -2 || opt_type == -1))
5087 ret = FAIL;
5089 *option_end = c; /* put back for error messages */
5090 *arg = option_end;
5092 return ret;
5096 * Allocate a variable for a string constant.
5097 * Return OK or FAIL.
5099 static int
5100 get_string_tv(arg, rettv, evaluate)
5101 char_u **arg;
5102 typval_T *rettv;
5103 int evaluate;
5105 char_u *p;
5106 char_u *name;
5107 int extra = 0;
5110 * Find the end of the string, skipping backslashed characters.
5112 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5114 if (*p == '\\' && p[1] != NUL)
5116 ++p;
5117 /* A "\<x>" form occupies at least 4 characters, and produces up
5118 * to 6 characters: reserve space for 2 extra */
5119 if (*p == '<')
5120 extra += 2;
5124 if (*p != '"')
5126 EMSG2(_("E114: Missing quote: %s"), *arg);
5127 return FAIL;
5130 /* If only parsing, set *arg and return here */
5131 if (!evaluate)
5133 *arg = p + 1;
5134 return OK;
5138 * Copy the string into allocated memory, handling backslashed
5139 * characters.
5141 name = alloc((unsigned)(p - *arg + extra));
5142 if (name == NULL)
5143 return FAIL;
5144 rettv->v_type = VAR_STRING;
5145 rettv->vval.v_string = name;
5147 for (p = *arg + 1; *p != NUL && *p != '"'; )
5149 if (*p == '\\')
5151 switch (*++p)
5153 case 'b': *name++ = BS; ++p; break;
5154 case 'e': *name++ = ESC; ++p; break;
5155 case 'f': *name++ = FF; ++p; break;
5156 case 'n': *name++ = NL; ++p; break;
5157 case 'r': *name++ = CAR; ++p; break;
5158 case 't': *name++ = TAB; ++p; break;
5160 case 'X': /* hex: "\x1", "\x12" */
5161 case 'x':
5162 case 'u': /* Unicode: "\u0023" */
5163 case 'U':
5164 if (vim_isxdigit(p[1]))
5166 int n, nr;
5167 int c = toupper(*p);
5169 if (c == 'X')
5170 n = 2;
5171 else
5172 n = 4;
5173 nr = 0;
5174 while (--n >= 0 && vim_isxdigit(p[1]))
5176 ++p;
5177 nr = (nr << 4) + hex2nr(*p);
5179 ++p;
5180 #ifdef FEAT_MBYTE
5181 /* For "\u" store the number according to
5182 * 'encoding'. */
5183 if (c != 'X')
5184 name += (*mb_char2bytes)(nr, name);
5185 else
5186 #endif
5187 *name++ = nr;
5189 break;
5191 /* octal: "\1", "\12", "\123" */
5192 case '0':
5193 case '1':
5194 case '2':
5195 case '3':
5196 case '4':
5197 case '5':
5198 case '6':
5199 case '7': *name = *p++ - '0';
5200 if (*p >= '0' && *p <= '7')
5202 *name = (*name << 3) + *p++ - '0';
5203 if (*p >= '0' && *p <= '7')
5204 *name = (*name << 3) + *p++ - '0';
5206 ++name;
5207 break;
5209 /* Special key, e.g.: "\<C-W>" */
5210 case '<': extra = trans_special(&p, name, TRUE);
5211 if (extra != 0)
5213 name += extra;
5214 break;
5216 /* FALLTHROUGH */
5218 default: MB_COPY_CHAR(p, name);
5219 break;
5222 else
5223 MB_COPY_CHAR(p, name);
5226 *name = NUL;
5227 *arg = p + 1;
5229 return OK;
5233 * Allocate a variable for a 'str''ing' constant.
5234 * Return OK or FAIL.
5236 static int
5237 get_lit_string_tv(arg, rettv, evaluate)
5238 char_u **arg;
5239 typval_T *rettv;
5240 int evaluate;
5242 char_u *p;
5243 char_u *str;
5244 int reduce = 0;
5247 * Find the end of the string, skipping ''.
5249 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5251 if (*p == '\'')
5253 if (p[1] != '\'')
5254 break;
5255 ++reduce;
5256 ++p;
5260 if (*p != '\'')
5262 EMSG2(_("E115: Missing quote: %s"), *arg);
5263 return FAIL;
5266 /* If only parsing return after setting "*arg" */
5267 if (!evaluate)
5269 *arg = p + 1;
5270 return OK;
5274 * Copy the string into allocated memory, handling '' to ' reduction.
5276 str = alloc((unsigned)((p - *arg) - reduce));
5277 if (str == NULL)
5278 return FAIL;
5279 rettv->v_type = VAR_STRING;
5280 rettv->vval.v_string = str;
5282 for (p = *arg + 1; *p != NUL; )
5284 if (*p == '\'')
5286 if (p[1] != '\'')
5287 break;
5288 ++p;
5290 MB_COPY_CHAR(p, str);
5292 *str = NUL;
5293 *arg = p + 1;
5295 return OK;
5299 * Allocate a variable for a List and fill it from "*arg".
5300 * Return OK or FAIL.
5302 static int
5303 get_list_tv(arg, rettv, evaluate)
5304 char_u **arg;
5305 typval_T *rettv;
5306 int evaluate;
5308 list_T *l = NULL;
5309 typval_T tv;
5310 listitem_T *item;
5312 if (evaluate)
5314 l = list_alloc();
5315 if (l == NULL)
5316 return FAIL;
5319 *arg = skipwhite(*arg + 1);
5320 while (**arg != ']' && **arg != NUL)
5322 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5323 goto failret;
5324 if (evaluate)
5326 item = listitem_alloc();
5327 if (item != NULL)
5329 item->li_tv = tv;
5330 item->li_tv.v_lock = 0;
5331 list_append(l, item);
5333 else
5334 clear_tv(&tv);
5337 if (**arg == ']')
5338 break;
5339 if (**arg != ',')
5341 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5342 goto failret;
5344 *arg = skipwhite(*arg + 1);
5347 if (**arg != ']')
5349 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5350 failret:
5351 if (evaluate)
5352 list_free(l, TRUE);
5353 return FAIL;
5356 *arg = skipwhite(*arg + 1);
5357 if (evaluate)
5359 rettv->v_type = VAR_LIST;
5360 rettv->vval.v_list = l;
5361 ++l->lv_refcount;
5364 return OK;
5368 * Allocate an empty header for a list.
5369 * Caller should take care of the reference count.
5371 list_T *
5372 list_alloc()
5374 list_T *l;
5376 l = (list_T *)alloc_clear(sizeof(list_T));
5377 if (l != NULL)
5379 /* Prepend the list to the list of lists for garbage collection. */
5380 if (first_list != NULL)
5381 first_list->lv_used_prev = l;
5382 l->lv_used_prev = NULL;
5383 l->lv_used_next = first_list;
5384 first_list = l;
5386 return l;
5390 * Allocate an empty list for a return value.
5391 * Returns OK or FAIL.
5393 static int
5394 rettv_list_alloc(rettv)
5395 typval_T *rettv;
5397 list_T *l = list_alloc();
5399 if (l == NULL)
5400 return FAIL;
5402 rettv->vval.v_list = l;
5403 rettv->v_type = VAR_LIST;
5404 ++l->lv_refcount;
5405 return OK;
5409 * Unreference a list: decrement the reference count and free it when it
5410 * becomes zero.
5412 void
5413 list_unref(l)
5414 list_T *l;
5416 if (l != NULL && --l->lv_refcount <= 0)
5417 list_free(l, TRUE);
5421 * Free a list, including all items it points to.
5422 * Ignores the reference count.
5424 void
5425 list_free(l, recurse)
5426 list_T *l;
5427 int recurse; /* Free Lists and Dictionaries recursively. */
5429 listitem_T *item;
5431 /* Remove the list from the list of lists for garbage collection. */
5432 if (l->lv_used_prev == NULL)
5433 first_list = l->lv_used_next;
5434 else
5435 l->lv_used_prev->lv_used_next = l->lv_used_next;
5436 if (l->lv_used_next != NULL)
5437 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5439 for (item = l->lv_first; item != NULL; item = l->lv_first)
5441 /* Remove the item before deleting it. */
5442 l->lv_first = item->li_next;
5443 if (recurse || (item->li_tv.v_type != VAR_LIST
5444 && item->li_tv.v_type != VAR_DICT))
5445 clear_tv(&item->li_tv);
5446 vim_free(item);
5448 vim_free(l);
5452 * Allocate a list item.
5454 static listitem_T *
5455 listitem_alloc()
5457 return (listitem_T *)alloc(sizeof(listitem_T));
5461 * Free a list item. Also clears the value. Does not notify watchers.
5463 static void
5464 listitem_free(item)
5465 listitem_T *item;
5467 clear_tv(&item->li_tv);
5468 vim_free(item);
5472 * Remove a list item from a List and free it. Also clears the value.
5474 static void
5475 listitem_remove(l, item)
5476 list_T *l;
5477 listitem_T *item;
5479 list_remove(l, item, item);
5480 listitem_free(item);
5484 * Get the number of items in a list.
5486 static long
5487 list_len(l)
5488 list_T *l;
5490 if (l == NULL)
5491 return 0L;
5492 return l->lv_len;
5496 * Return TRUE when two lists have exactly the same values.
5498 static int
5499 list_equal(l1, l2, ic)
5500 list_T *l1;
5501 list_T *l2;
5502 int ic; /* ignore case for strings */
5504 listitem_T *item1, *item2;
5506 if (l1 == l2)
5507 return TRUE;
5508 if (list_len(l1) != list_len(l2))
5509 return FALSE;
5511 for (item1 = l1->lv_first, item2 = l2->lv_first;
5512 item1 != NULL && item2 != NULL;
5513 item1 = item1->li_next, item2 = item2->li_next)
5514 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5515 return FALSE;
5516 return item1 == NULL && item2 == NULL;
5519 #if defined(FEAT_PYTHON) || defined(PROTO)
5521 * Return the dictitem that an entry in a hashtable points to.
5523 dictitem_T *
5524 dict_lookup(hi)
5525 hashitem_T *hi;
5527 return HI2DI(hi);
5529 #endif
5532 * Return TRUE when two dictionaries have exactly the same key/values.
5534 static int
5535 dict_equal(d1, d2, ic)
5536 dict_T *d1;
5537 dict_T *d2;
5538 int ic; /* ignore case for strings */
5540 hashitem_T *hi;
5541 dictitem_T *item2;
5542 int todo;
5544 if (d1 == d2)
5545 return TRUE;
5546 if (dict_len(d1) != dict_len(d2))
5547 return FALSE;
5549 todo = (int)d1->dv_hashtab.ht_used;
5550 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5552 if (!HASHITEM_EMPTY(hi))
5554 item2 = dict_find(d2, hi->hi_key, -1);
5555 if (item2 == NULL)
5556 return FALSE;
5557 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5558 return FALSE;
5559 --todo;
5562 return TRUE;
5566 * Return TRUE if "tv1" and "tv2" have the same value.
5567 * Compares the items just like "==" would compare them, but strings and
5568 * numbers are different.
5570 static int
5571 tv_equal(tv1, tv2, ic)
5572 typval_T *tv1;
5573 typval_T *tv2;
5574 int ic; /* ignore case */
5576 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5577 char_u *s1, *s2;
5578 static int recursive = 0; /* cach recursive loops */
5579 int r;
5581 if (tv1->v_type != tv2->v_type)
5582 return FALSE;
5583 /* Catch lists and dicts that have an endless loop by limiting
5584 * recursiveness to 1000. We guess they are equal then. */
5585 if (recursive >= 1000)
5586 return TRUE;
5588 switch (tv1->v_type)
5590 case VAR_LIST:
5591 ++recursive;
5592 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5593 --recursive;
5594 return r;
5596 case VAR_DICT:
5597 ++recursive;
5598 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5599 --recursive;
5600 return r;
5602 case VAR_FUNC:
5603 return (tv1->vval.v_string != NULL
5604 && tv2->vval.v_string != NULL
5605 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5607 case VAR_NUMBER:
5608 return tv1->vval.v_number == tv2->vval.v_number;
5610 case VAR_STRING:
5611 s1 = get_tv_string_buf(tv1, buf1);
5612 s2 = get_tv_string_buf(tv2, buf2);
5613 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5616 EMSG2(_(e_intern2), "tv_equal()");
5617 return TRUE;
5621 * Locate item with index "n" in list "l" and return it.
5622 * A negative index is counted from the end; -1 is the last item.
5623 * Returns NULL when "n" is out of range.
5625 static listitem_T *
5626 list_find(l, n)
5627 list_T *l;
5628 long n;
5630 listitem_T *item;
5631 long idx;
5633 if (l == NULL)
5634 return NULL;
5636 /* Negative index is relative to the end. */
5637 if (n < 0)
5638 n = l->lv_len + n;
5640 /* Check for index out of range. */
5641 if (n < 0 || n >= l->lv_len)
5642 return NULL;
5644 /* When there is a cached index may start search from there. */
5645 if (l->lv_idx_item != NULL)
5647 if (n < l->lv_idx / 2)
5649 /* closest to the start of the list */
5650 item = l->lv_first;
5651 idx = 0;
5653 else if (n > (l->lv_idx + l->lv_len) / 2)
5655 /* closest to the end of the list */
5656 item = l->lv_last;
5657 idx = l->lv_len - 1;
5659 else
5661 /* closest to the cached index */
5662 item = l->lv_idx_item;
5663 idx = l->lv_idx;
5666 else
5668 if (n < l->lv_len / 2)
5670 /* closest to the start of the list */
5671 item = l->lv_first;
5672 idx = 0;
5674 else
5676 /* closest to the end of the list */
5677 item = l->lv_last;
5678 idx = l->lv_len - 1;
5682 while (n > idx)
5684 /* search forward */
5685 item = item->li_next;
5686 ++idx;
5688 while (n < idx)
5690 /* search backward */
5691 item = item->li_prev;
5692 --idx;
5695 /* cache the used index */
5696 l->lv_idx = idx;
5697 l->lv_idx_item = item;
5699 return item;
5703 * Get list item "l[idx]" as a number.
5705 static long
5706 list_find_nr(l, idx, errorp)
5707 list_T *l;
5708 long idx;
5709 int *errorp; /* set to TRUE when something wrong */
5711 listitem_T *li;
5713 li = list_find(l, idx);
5714 if (li == NULL)
5716 if (errorp != NULL)
5717 *errorp = TRUE;
5718 return -1L;
5720 return get_tv_number_chk(&li->li_tv, errorp);
5724 * Locate "item" list "l" and return its index.
5725 * Returns -1 when "item" is not in the list.
5727 static long
5728 list_idx_of_item(l, item)
5729 list_T *l;
5730 listitem_T *item;
5732 long idx = 0;
5733 listitem_T *li;
5735 if (l == NULL)
5736 return -1;
5737 idx = 0;
5738 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
5739 ++idx;
5740 if (li == NULL)
5741 return -1;
5742 return idx;
5746 * Append item "item" to the end of list "l".
5748 static void
5749 list_append(l, item)
5750 list_T *l;
5751 listitem_T *item;
5753 if (l->lv_last == NULL)
5755 /* empty list */
5756 l->lv_first = item;
5757 l->lv_last = item;
5758 item->li_prev = NULL;
5760 else
5762 l->lv_last->li_next = item;
5763 item->li_prev = l->lv_last;
5764 l->lv_last = item;
5766 ++l->lv_len;
5767 item->li_next = NULL;
5771 * Append typval_T "tv" to the end of list "l".
5772 * Return FAIL when out of memory.
5774 static int
5775 list_append_tv(l, tv)
5776 list_T *l;
5777 typval_T *tv;
5779 listitem_T *li = listitem_alloc();
5781 if (li == NULL)
5782 return FAIL;
5783 copy_tv(tv, &li->li_tv);
5784 list_append(l, li);
5785 return OK;
5789 * Add a dictionary to a list. Used by getqflist().
5790 * Return FAIL when out of memory.
5793 list_append_dict(list, dict)
5794 list_T *list;
5795 dict_T *dict;
5797 listitem_T *li = listitem_alloc();
5799 if (li == NULL)
5800 return FAIL;
5801 li->li_tv.v_type = VAR_DICT;
5802 li->li_tv.v_lock = 0;
5803 li->li_tv.vval.v_dict = dict;
5804 list_append(list, li);
5805 ++dict->dv_refcount;
5806 return OK;
5810 * Make a copy of "str" and append it as an item to list "l".
5811 * When "len" >= 0 use "str[len]".
5812 * Returns FAIL when out of memory.
5814 static int
5815 list_append_string(l, str, len)
5816 list_T *l;
5817 char_u *str;
5818 int len;
5820 listitem_T *li = listitem_alloc();
5822 if (li == NULL)
5823 return FAIL;
5824 list_append(l, li);
5825 li->li_tv.v_type = VAR_STRING;
5826 li->li_tv.v_lock = 0;
5827 if (str == NULL)
5828 li->li_tv.vval.v_string = NULL;
5829 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
5830 : vim_strsave(str))) == NULL)
5831 return FAIL;
5832 return OK;
5836 * Append "n" to list "l".
5837 * Returns FAIL when out of memory.
5839 static int
5840 list_append_number(l, n)
5841 list_T *l;
5842 varnumber_T n;
5844 listitem_T *li;
5846 li = listitem_alloc();
5847 if (li == NULL)
5848 return FAIL;
5849 li->li_tv.v_type = VAR_NUMBER;
5850 li->li_tv.v_lock = 0;
5851 li->li_tv.vval.v_number = n;
5852 list_append(l, li);
5853 return OK;
5857 * Insert typval_T "tv" in list "l" before "item".
5858 * If "item" is NULL append at the end.
5859 * Return FAIL when out of memory.
5861 static int
5862 list_insert_tv(l, tv, item)
5863 list_T *l;
5864 typval_T *tv;
5865 listitem_T *item;
5867 listitem_T *ni = listitem_alloc();
5869 if (ni == NULL)
5870 return FAIL;
5871 copy_tv(tv, &ni->li_tv);
5872 if (item == NULL)
5873 /* Append new item at end of list. */
5874 list_append(l, ni);
5875 else
5877 /* Insert new item before existing item. */
5878 ni->li_prev = item->li_prev;
5879 ni->li_next = item;
5880 if (item->li_prev == NULL)
5882 l->lv_first = ni;
5883 ++l->lv_idx;
5885 else
5887 item->li_prev->li_next = ni;
5888 l->lv_idx_item = NULL;
5890 item->li_prev = ni;
5891 ++l->lv_len;
5893 return OK;
5897 * Extend "l1" with "l2".
5898 * If "bef" is NULL append at the end, otherwise insert before this item.
5899 * Returns FAIL when out of memory.
5901 static int
5902 list_extend(l1, l2, bef)
5903 list_T *l1;
5904 list_T *l2;
5905 listitem_T *bef;
5907 listitem_T *item;
5909 for (item = l2->lv_first; item != NULL; item = item->li_next)
5910 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
5911 return FAIL;
5912 return OK;
5916 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
5917 * Return FAIL when out of memory.
5919 static int
5920 list_concat(l1, l2, tv)
5921 list_T *l1;
5922 list_T *l2;
5923 typval_T *tv;
5925 list_T *l;
5927 /* make a copy of the first list. */
5928 l = list_copy(l1, FALSE, 0);
5929 if (l == NULL)
5930 return FAIL;
5931 tv->v_type = VAR_LIST;
5932 tv->vval.v_list = l;
5934 /* append all items from the second list */
5935 return list_extend(l, l2, NULL);
5939 * Make a copy of list "orig". Shallow if "deep" is FALSE.
5940 * The refcount of the new list is set to 1.
5941 * See item_copy() for "copyID".
5942 * Returns NULL when out of memory.
5944 static list_T *
5945 list_copy(orig, deep, copyID)
5946 list_T *orig;
5947 int deep;
5948 int copyID;
5950 list_T *copy;
5951 listitem_T *item;
5952 listitem_T *ni;
5954 if (orig == NULL)
5955 return NULL;
5957 copy = list_alloc();
5958 if (copy != NULL)
5960 if (copyID != 0)
5962 /* Do this before adding the items, because one of the items may
5963 * refer back to this list. */
5964 orig->lv_copyID = copyID;
5965 orig->lv_copylist = copy;
5967 for (item = orig->lv_first; item != NULL && !got_int;
5968 item = item->li_next)
5970 ni = listitem_alloc();
5971 if (ni == NULL)
5972 break;
5973 if (deep)
5975 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
5977 vim_free(ni);
5978 break;
5981 else
5982 copy_tv(&item->li_tv, &ni->li_tv);
5983 list_append(copy, ni);
5985 ++copy->lv_refcount;
5986 if (item != NULL)
5988 list_unref(copy);
5989 copy = NULL;
5993 return copy;
5997 * Remove items "item" to "item2" from list "l".
5998 * Does not free the listitem or the value!
6000 static void
6001 list_remove(l, item, item2)
6002 list_T *l;
6003 listitem_T *item;
6004 listitem_T *item2;
6006 listitem_T *ip;
6008 /* notify watchers */
6009 for (ip = item; ip != NULL; ip = ip->li_next)
6011 --l->lv_len;
6012 list_fix_watch(l, ip);
6013 if (ip == item2)
6014 break;
6017 if (item2->li_next == NULL)
6018 l->lv_last = item->li_prev;
6019 else
6020 item2->li_next->li_prev = item->li_prev;
6021 if (item->li_prev == NULL)
6022 l->lv_first = item2->li_next;
6023 else
6024 item->li_prev->li_next = item2->li_next;
6025 l->lv_idx_item = NULL;
6029 * Return an allocated string with the string representation of a list.
6030 * May return NULL.
6032 static char_u *
6033 list2string(tv, copyID)
6034 typval_T *tv;
6035 int copyID;
6037 garray_T ga;
6039 if (tv->vval.v_list == NULL)
6040 return NULL;
6041 ga_init2(&ga, (int)sizeof(char), 80);
6042 ga_append(&ga, '[');
6043 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6045 vim_free(ga.ga_data);
6046 return NULL;
6048 ga_append(&ga, ']');
6049 ga_append(&ga, NUL);
6050 return (char_u *)ga.ga_data;
6054 * Join list "l" into a string in "*gap", using separator "sep".
6055 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6056 * Return FAIL or OK.
6058 static int
6059 list_join(gap, l, sep, echo, copyID)
6060 garray_T *gap;
6061 list_T *l;
6062 char_u *sep;
6063 int echo;
6064 int copyID;
6066 int first = TRUE;
6067 char_u *tofree;
6068 char_u numbuf[NUMBUFLEN];
6069 listitem_T *item;
6070 char_u *s;
6072 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6074 if (first)
6075 first = FALSE;
6076 else
6077 ga_concat(gap, sep);
6079 if (echo)
6080 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6081 else
6082 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6083 if (s != NULL)
6084 ga_concat(gap, s);
6085 vim_free(tofree);
6086 if (s == NULL)
6087 return FAIL;
6089 return OK;
6093 * Garbage collection for lists and dictionaries.
6095 * We use reference counts to be able to free most items right away when they
6096 * are no longer used. But for composite items it's possible that it becomes
6097 * unused while the reference count is > 0: When there is a recursive
6098 * reference. Example:
6099 * :let l = [1, 2, 3]
6100 * :let d = {9: l}
6101 * :let l[1] = d
6103 * Since this is quite unusual we handle this with garbage collection: every
6104 * once in a while find out which lists and dicts are not referenced from any
6105 * variable.
6107 * Here is a good reference text about garbage collection (refers to Python
6108 * but it applies to all reference-counting mechanisms):
6109 * http://python.ca/nas/python/gc/
6113 * Do garbage collection for lists and dicts.
6114 * Return TRUE if some memory was freed.
6117 garbage_collect()
6119 dict_T *dd;
6120 list_T *ll;
6121 int copyID = ++current_copyID;
6122 buf_T *buf;
6123 win_T *wp;
6124 int i;
6125 funccall_T *fc;
6126 int did_free = FALSE;
6127 #ifdef FEAT_WINDOWS
6128 tabpage_T *tp;
6129 #endif
6131 /* Only do this once. */
6132 want_garbage_collect = FALSE;
6133 may_garbage_collect = FALSE;
6134 garbage_collect_at_exit = FALSE;
6137 * 1. Go through all accessible variables and mark all lists and dicts
6138 * with copyID.
6140 /* script-local variables */
6141 for (i = 1; i <= ga_scripts.ga_len; ++i)
6142 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6144 /* buffer-local variables */
6145 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6146 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6148 /* window-local variables */
6149 FOR_ALL_TAB_WINDOWS(tp, wp)
6150 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6152 #ifdef FEAT_WINDOWS
6153 /* tabpage-local variables */
6154 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6155 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6156 #endif
6158 /* global variables */
6159 set_ref_in_ht(&globvarht, copyID);
6161 /* function-local variables */
6162 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6164 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6165 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6169 * 2. Go through the list of dicts and free items without the copyID.
6171 for (dd = first_dict; dd != NULL; )
6172 if (dd->dv_copyID != copyID)
6174 /* Free the Dictionary and ordinary items it contains, but don't
6175 * recurse into Lists and Dictionaries, they will be in the list
6176 * of dicts or list of lists. */
6177 dict_free(dd, FALSE);
6178 did_free = TRUE;
6180 /* restart, next dict may also have been freed */
6181 dd = first_dict;
6183 else
6184 dd = dd->dv_used_next;
6187 * 3. Go through the list of lists and free items without the copyID.
6188 * But don't free a list that has a watcher (used in a for loop), these
6189 * are not referenced anywhere.
6191 for (ll = first_list; ll != NULL; )
6192 if (ll->lv_copyID != copyID && ll->lv_watch == NULL)
6194 /* Free the List and ordinary items it contains, but don't recurse
6195 * into Lists and Dictionaries, they will be in the list of dicts
6196 * or list of lists. */
6197 list_free(ll, FALSE);
6198 did_free = TRUE;
6200 /* restart, next list may also have been freed */
6201 ll = first_list;
6203 else
6204 ll = ll->lv_used_next;
6206 return did_free;
6210 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6212 static void
6213 set_ref_in_ht(ht, copyID)
6214 hashtab_T *ht;
6215 int copyID;
6217 int todo;
6218 hashitem_T *hi;
6220 todo = (int)ht->ht_used;
6221 for (hi = ht->ht_array; todo > 0; ++hi)
6222 if (!HASHITEM_EMPTY(hi))
6224 --todo;
6225 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6230 * Mark all lists and dicts referenced through list "l" with "copyID".
6232 static void
6233 set_ref_in_list(l, copyID)
6234 list_T *l;
6235 int copyID;
6237 listitem_T *li;
6239 for (li = l->lv_first; li != NULL; li = li->li_next)
6240 set_ref_in_item(&li->li_tv, copyID);
6244 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6246 static void
6247 set_ref_in_item(tv, copyID)
6248 typval_T *tv;
6249 int copyID;
6251 dict_T *dd;
6252 list_T *ll;
6254 switch (tv->v_type)
6256 case VAR_DICT:
6257 dd = tv->vval.v_dict;
6258 if (dd->dv_copyID != copyID)
6260 /* Didn't see this dict yet. */
6261 dd->dv_copyID = copyID;
6262 set_ref_in_ht(&dd->dv_hashtab, copyID);
6264 break;
6266 case VAR_LIST:
6267 ll = tv->vval.v_list;
6268 if (ll->lv_copyID != copyID)
6270 /* Didn't see this list yet. */
6271 ll->lv_copyID = copyID;
6272 set_ref_in_list(ll, copyID);
6274 break;
6276 return;
6280 * Allocate an empty header for a dictionary.
6282 dict_T *
6283 dict_alloc()
6285 dict_T *d;
6287 d = (dict_T *)alloc(sizeof(dict_T));
6288 if (d != NULL)
6290 /* Add the list to the list of dicts for garbage collection. */
6291 if (first_dict != NULL)
6292 first_dict->dv_used_prev = d;
6293 d->dv_used_next = first_dict;
6294 d->dv_used_prev = NULL;
6295 first_dict = d;
6297 hash_init(&d->dv_hashtab);
6298 d->dv_lock = 0;
6299 d->dv_refcount = 0;
6300 d->dv_copyID = 0;
6302 return d;
6306 * Unreference a Dictionary: decrement the reference count and free it when it
6307 * becomes zero.
6309 static void
6310 dict_unref(d)
6311 dict_T *d;
6313 if (d != NULL && --d->dv_refcount <= 0)
6314 dict_free(d, TRUE);
6318 * Free a Dictionary, including all items it contains.
6319 * Ignores the reference count.
6321 static void
6322 dict_free(d, recurse)
6323 dict_T *d;
6324 int recurse; /* Free Lists and Dictionaries recursively. */
6326 int todo;
6327 hashitem_T *hi;
6328 dictitem_T *di;
6330 /* Remove the dict from the list of dicts for garbage collection. */
6331 if (d->dv_used_prev == NULL)
6332 first_dict = d->dv_used_next;
6333 else
6334 d->dv_used_prev->dv_used_next = d->dv_used_next;
6335 if (d->dv_used_next != NULL)
6336 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6338 /* Lock the hashtab, we don't want it to resize while freeing items. */
6339 hash_lock(&d->dv_hashtab);
6340 todo = (int)d->dv_hashtab.ht_used;
6341 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6343 if (!HASHITEM_EMPTY(hi))
6345 /* Remove the item before deleting it, just in case there is
6346 * something recursive causing trouble. */
6347 di = HI2DI(hi);
6348 hash_remove(&d->dv_hashtab, hi);
6349 if (recurse || (di->di_tv.v_type != VAR_LIST
6350 && di->di_tv.v_type != VAR_DICT))
6351 clear_tv(&di->di_tv);
6352 vim_free(di);
6353 --todo;
6356 hash_clear(&d->dv_hashtab);
6357 vim_free(d);
6361 * Allocate a Dictionary item.
6362 * The "key" is copied to the new item.
6363 * Note that the value of the item "di_tv" still needs to be initialized!
6364 * Returns NULL when out of memory.
6366 static dictitem_T *
6367 dictitem_alloc(key)
6368 char_u *key;
6370 dictitem_T *di;
6372 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6373 if (di != NULL)
6375 STRCPY(di->di_key, key);
6376 di->di_flags = 0;
6378 return di;
6382 * Make a copy of a Dictionary item.
6384 static dictitem_T *
6385 dictitem_copy(org)
6386 dictitem_T *org;
6388 dictitem_T *di;
6390 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6391 + STRLEN(org->di_key)));
6392 if (di != NULL)
6394 STRCPY(di->di_key, org->di_key);
6395 di->di_flags = 0;
6396 copy_tv(&org->di_tv, &di->di_tv);
6398 return di;
6402 * Remove item "item" from Dictionary "dict" and free it.
6404 static void
6405 dictitem_remove(dict, item)
6406 dict_T *dict;
6407 dictitem_T *item;
6409 hashitem_T *hi;
6411 hi = hash_find(&dict->dv_hashtab, item->di_key);
6412 if (HASHITEM_EMPTY(hi))
6413 EMSG2(_(e_intern2), "dictitem_remove()");
6414 else
6415 hash_remove(&dict->dv_hashtab, hi);
6416 dictitem_free(item);
6420 * Free a dict item. Also clears the value.
6422 static void
6423 dictitem_free(item)
6424 dictitem_T *item;
6426 clear_tv(&item->di_tv);
6427 vim_free(item);
6431 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6432 * The refcount of the new dict is set to 1.
6433 * See item_copy() for "copyID".
6434 * Returns NULL when out of memory.
6436 static dict_T *
6437 dict_copy(orig, deep, copyID)
6438 dict_T *orig;
6439 int deep;
6440 int copyID;
6442 dict_T *copy;
6443 dictitem_T *di;
6444 int todo;
6445 hashitem_T *hi;
6447 if (orig == NULL)
6448 return NULL;
6450 copy = dict_alloc();
6451 if (copy != NULL)
6453 if (copyID != 0)
6455 orig->dv_copyID = copyID;
6456 orig->dv_copydict = copy;
6458 todo = (int)orig->dv_hashtab.ht_used;
6459 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6461 if (!HASHITEM_EMPTY(hi))
6463 --todo;
6465 di = dictitem_alloc(hi->hi_key);
6466 if (di == NULL)
6467 break;
6468 if (deep)
6470 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6471 copyID) == FAIL)
6473 vim_free(di);
6474 break;
6477 else
6478 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6479 if (dict_add(copy, di) == FAIL)
6481 dictitem_free(di);
6482 break;
6487 ++copy->dv_refcount;
6488 if (todo > 0)
6490 dict_unref(copy);
6491 copy = NULL;
6495 return copy;
6499 * Add item "item" to Dictionary "d".
6500 * Returns FAIL when out of memory and when key already existed.
6502 static int
6503 dict_add(d, item)
6504 dict_T *d;
6505 dictitem_T *item;
6507 return hash_add(&d->dv_hashtab, item->di_key);
6511 * Add a number or string entry to dictionary "d".
6512 * When "str" is NULL use number "nr", otherwise use "str".
6513 * Returns FAIL when out of memory and when key already exists.
6516 dict_add_nr_str(d, key, nr, str)
6517 dict_T *d;
6518 char *key;
6519 long nr;
6520 char_u *str;
6522 dictitem_T *item;
6524 item = dictitem_alloc((char_u *)key);
6525 if (item == NULL)
6526 return FAIL;
6527 item->di_tv.v_lock = 0;
6528 if (str == NULL)
6530 item->di_tv.v_type = VAR_NUMBER;
6531 item->di_tv.vval.v_number = nr;
6533 else
6535 item->di_tv.v_type = VAR_STRING;
6536 item->di_tv.vval.v_string = vim_strsave(str);
6538 if (dict_add(d, item) == FAIL)
6540 dictitem_free(item);
6541 return FAIL;
6543 return OK;
6547 * Get the number of items in a Dictionary.
6549 static long
6550 dict_len(d)
6551 dict_T *d;
6553 if (d == NULL)
6554 return 0L;
6555 return (long)d->dv_hashtab.ht_used;
6559 * Find item "key[len]" in Dictionary "d".
6560 * If "len" is negative use strlen(key).
6561 * Returns NULL when not found.
6563 static dictitem_T *
6564 dict_find(d, key, len)
6565 dict_T *d;
6566 char_u *key;
6567 int len;
6569 #define AKEYLEN 200
6570 char_u buf[AKEYLEN];
6571 char_u *akey;
6572 char_u *tofree = NULL;
6573 hashitem_T *hi;
6575 if (len < 0)
6576 akey = key;
6577 else if (len >= AKEYLEN)
6579 tofree = akey = vim_strnsave(key, len);
6580 if (akey == NULL)
6581 return NULL;
6583 else
6585 /* Avoid a malloc/free by using buf[]. */
6586 vim_strncpy(buf, key, len);
6587 akey = buf;
6590 hi = hash_find(&d->dv_hashtab, akey);
6591 vim_free(tofree);
6592 if (HASHITEM_EMPTY(hi))
6593 return NULL;
6594 return HI2DI(hi);
6598 * Get a string item from a dictionary.
6599 * When "save" is TRUE allocate memory for it.
6600 * Returns NULL if the entry doesn't exist or out of memory.
6602 char_u *
6603 get_dict_string(d, key, save)
6604 dict_T *d;
6605 char_u *key;
6606 int save;
6608 dictitem_T *di;
6609 char_u *s;
6611 di = dict_find(d, key, -1);
6612 if (di == NULL)
6613 return NULL;
6614 s = get_tv_string(&di->di_tv);
6615 if (save && s != NULL)
6616 s = vim_strsave(s);
6617 return s;
6621 * Get a number item from a dictionary.
6622 * Returns 0 if the entry doesn't exist or out of memory.
6624 long
6625 get_dict_number(d, key)
6626 dict_T *d;
6627 char_u *key;
6629 dictitem_T *di;
6631 di = dict_find(d, key, -1);
6632 if (di == NULL)
6633 return 0;
6634 return get_tv_number(&di->di_tv);
6638 * Return an allocated string with the string representation of a Dictionary.
6639 * May return NULL.
6641 static char_u *
6642 dict2string(tv, copyID)
6643 typval_T *tv;
6644 int copyID;
6646 garray_T ga;
6647 int first = TRUE;
6648 char_u *tofree;
6649 char_u numbuf[NUMBUFLEN];
6650 hashitem_T *hi;
6651 char_u *s;
6652 dict_T *d;
6653 int todo;
6655 if ((d = tv->vval.v_dict) == NULL)
6656 return NULL;
6657 ga_init2(&ga, (int)sizeof(char), 80);
6658 ga_append(&ga, '{');
6660 todo = (int)d->dv_hashtab.ht_used;
6661 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6663 if (!HASHITEM_EMPTY(hi))
6665 --todo;
6667 if (first)
6668 first = FALSE;
6669 else
6670 ga_concat(&ga, (char_u *)", ");
6672 tofree = string_quote(hi->hi_key, FALSE);
6673 if (tofree != NULL)
6675 ga_concat(&ga, tofree);
6676 vim_free(tofree);
6678 ga_concat(&ga, (char_u *)": ");
6679 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
6680 if (s != NULL)
6681 ga_concat(&ga, s);
6682 vim_free(tofree);
6683 if (s == NULL)
6684 break;
6687 if (todo > 0)
6689 vim_free(ga.ga_data);
6690 return NULL;
6693 ga_append(&ga, '}');
6694 ga_append(&ga, NUL);
6695 return (char_u *)ga.ga_data;
6699 * Allocate a variable for a Dictionary and fill it from "*arg".
6700 * Return OK or FAIL. Returns NOTDONE for {expr}.
6702 static int
6703 get_dict_tv(arg, rettv, evaluate)
6704 char_u **arg;
6705 typval_T *rettv;
6706 int evaluate;
6708 dict_T *d = NULL;
6709 typval_T tvkey;
6710 typval_T tv;
6711 char_u *key = NULL;
6712 dictitem_T *item;
6713 char_u *start = skipwhite(*arg + 1);
6714 char_u buf[NUMBUFLEN];
6717 * First check if it's not a curly-braces thing: {expr}.
6718 * Must do this without evaluating, otherwise a function may be called
6719 * twice. Unfortunately this means we need to call eval1() twice for the
6720 * first item.
6721 * But {} is an empty Dictionary.
6723 if (*start != '}')
6725 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
6726 return FAIL;
6727 if (*start == '}')
6728 return NOTDONE;
6731 if (evaluate)
6733 d = dict_alloc();
6734 if (d == NULL)
6735 return FAIL;
6737 tvkey.v_type = VAR_UNKNOWN;
6738 tv.v_type = VAR_UNKNOWN;
6740 *arg = skipwhite(*arg + 1);
6741 while (**arg != '}' && **arg != NUL)
6743 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
6744 goto failret;
6745 if (**arg != ':')
6747 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
6748 clear_tv(&tvkey);
6749 goto failret;
6751 if (evaluate)
6753 key = get_tv_string_buf_chk(&tvkey, buf);
6754 if (key == NULL || *key == NUL)
6756 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
6757 if (key != NULL)
6758 EMSG(_(e_emptykey));
6759 clear_tv(&tvkey);
6760 goto failret;
6764 *arg = skipwhite(*arg + 1);
6765 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
6767 if (evaluate)
6768 clear_tv(&tvkey);
6769 goto failret;
6771 if (evaluate)
6773 item = dict_find(d, key, -1);
6774 if (item != NULL)
6776 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
6777 clear_tv(&tvkey);
6778 clear_tv(&tv);
6779 goto failret;
6781 item = dictitem_alloc(key);
6782 clear_tv(&tvkey);
6783 if (item != NULL)
6785 item->di_tv = tv;
6786 item->di_tv.v_lock = 0;
6787 if (dict_add(d, item) == FAIL)
6788 dictitem_free(item);
6792 if (**arg == '}')
6793 break;
6794 if (**arg != ',')
6796 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
6797 goto failret;
6799 *arg = skipwhite(*arg + 1);
6802 if (**arg != '}')
6804 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
6805 failret:
6806 if (evaluate)
6807 dict_free(d, TRUE);
6808 return FAIL;
6811 *arg = skipwhite(*arg + 1);
6812 if (evaluate)
6814 rettv->v_type = VAR_DICT;
6815 rettv->vval.v_dict = d;
6816 ++d->dv_refcount;
6819 return OK;
6823 * Return a string with the string representation of a variable.
6824 * If the memory is allocated "tofree" is set to it, otherwise NULL.
6825 * "numbuf" is used for a number.
6826 * Does not put quotes around strings, as ":echo" displays values.
6827 * When "copyID" is not NULL replace recursive lists and dicts with "...".
6828 * May return NULL.
6830 static char_u *
6831 echo_string(tv, tofree, numbuf, copyID)
6832 typval_T *tv;
6833 char_u **tofree;
6834 char_u *numbuf;
6835 int copyID;
6837 static int recurse = 0;
6838 char_u *r = NULL;
6840 if (recurse >= DICT_MAXNEST)
6842 EMSG(_("E724: variable nested too deep for displaying"));
6843 *tofree = NULL;
6844 return NULL;
6846 ++recurse;
6848 switch (tv->v_type)
6850 case VAR_FUNC:
6851 *tofree = NULL;
6852 r = tv->vval.v_string;
6853 break;
6855 case VAR_LIST:
6856 if (tv->vval.v_list == NULL)
6858 *tofree = NULL;
6859 r = NULL;
6861 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
6863 *tofree = NULL;
6864 r = (char_u *)"[...]";
6866 else
6868 tv->vval.v_list->lv_copyID = copyID;
6869 *tofree = list2string(tv, copyID);
6870 r = *tofree;
6872 break;
6874 case VAR_DICT:
6875 if (tv->vval.v_dict == NULL)
6877 *tofree = NULL;
6878 r = NULL;
6880 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
6882 *tofree = NULL;
6883 r = (char_u *)"{...}";
6885 else
6887 tv->vval.v_dict->dv_copyID = copyID;
6888 *tofree = dict2string(tv, copyID);
6889 r = *tofree;
6891 break;
6893 case VAR_STRING:
6894 case VAR_NUMBER:
6895 *tofree = NULL;
6896 r = get_tv_string_buf(tv, numbuf);
6897 break;
6899 default:
6900 EMSG2(_(e_intern2), "echo_string()");
6901 *tofree = NULL;
6904 --recurse;
6905 return r;
6909 * Return a string with the string representation of a variable.
6910 * If the memory is allocated "tofree" is set to it, otherwise NULL.
6911 * "numbuf" is used for a number.
6912 * Puts quotes around strings, so that they can be parsed back by eval().
6913 * May return NULL.
6915 static char_u *
6916 tv2string(tv, tofree, numbuf, copyID)
6917 typval_T *tv;
6918 char_u **tofree;
6919 char_u *numbuf;
6920 int copyID;
6922 switch (tv->v_type)
6924 case VAR_FUNC:
6925 *tofree = string_quote(tv->vval.v_string, TRUE);
6926 return *tofree;
6927 case VAR_STRING:
6928 *tofree = string_quote(tv->vval.v_string, FALSE);
6929 return *tofree;
6930 case VAR_NUMBER:
6931 case VAR_LIST:
6932 case VAR_DICT:
6933 break;
6934 default:
6935 EMSG2(_(e_intern2), "tv2string()");
6937 return echo_string(tv, tofree, numbuf, copyID);
6941 * Return string "str" in ' quotes, doubling ' characters.
6942 * If "str" is NULL an empty string is assumed.
6943 * If "function" is TRUE make it function('string').
6945 static char_u *
6946 string_quote(str, function)
6947 char_u *str;
6948 int function;
6950 unsigned len;
6951 char_u *p, *r, *s;
6953 len = (function ? 13 : 3);
6954 if (str != NULL)
6956 len += (unsigned)STRLEN(str);
6957 for (p = str; *p != NUL; mb_ptr_adv(p))
6958 if (*p == '\'')
6959 ++len;
6961 s = r = alloc(len);
6962 if (r != NULL)
6964 if (function)
6966 STRCPY(r, "function('");
6967 r += 10;
6969 else
6970 *r++ = '\'';
6971 if (str != NULL)
6972 for (p = str; *p != NUL; )
6974 if (*p == '\'')
6975 *r++ = '\'';
6976 MB_COPY_CHAR(p, r);
6978 *r++ = '\'';
6979 if (function)
6980 *r++ = ')';
6981 *r++ = NUL;
6983 return s;
6987 * Get the value of an environment variable.
6988 * "arg" is pointing to the '$'. It is advanced to after the name.
6989 * If the environment variable was not set, silently assume it is empty.
6990 * Always return OK.
6992 static int
6993 get_env_tv(arg, rettv, evaluate)
6994 char_u **arg;
6995 typval_T *rettv;
6996 int evaluate;
6998 char_u *string = NULL;
6999 int len;
7000 int cc;
7001 char_u *name;
7002 int mustfree = FALSE;
7004 ++*arg;
7005 name = *arg;
7006 len = get_env_len(arg);
7007 if (evaluate)
7009 if (len != 0)
7011 cc = name[len];
7012 name[len] = NUL;
7013 /* first try vim_getenv(), fast for normal environment vars */
7014 string = vim_getenv(name, &mustfree);
7015 if (string != NULL && *string != NUL)
7017 if (!mustfree)
7018 string = vim_strsave(string);
7020 else
7022 if (mustfree)
7023 vim_free(string);
7025 /* next try expanding things like $VIM and ${HOME} */
7026 string = expand_env_save(name - 1);
7027 if (string != NULL && *string == '$')
7029 vim_free(string);
7030 string = NULL;
7033 name[len] = cc;
7035 rettv->v_type = VAR_STRING;
7036 rettv->vval.v_string = string;
7039 return OK;
7043 * Array with names and number of arguments of all internal functions
7044 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7046 static struct fst
7048 char *f_name; /* function name */
7049 char f_min_argc; /* minimal number of arguments */
7050 char f_max_argc; /* maximal number of arguments */
7051 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7052 /* implementation of function */
7053 } functions[] =
7055 {"add", 2, 2, f_add},
7056 {"append", 2, 2, f_append},
7057 {"argc", 0, 0, f_argc},
7058 {"argidx", 0, 0, f_argidx},
7059 {"argv", 0, 1, f_argv},
7060 {"browse", 4, 4, f_browse},
7061 {"browsedir", 2, 2, f_browsedir},
7062 {"bufexists", 1, 1, f_bufexists},
7063 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7064 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7065 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7066 {"buflisted", 1, 1, f_buflisted},
7067 {"bufloaded", 1, 1, f_bufloaded},
7068 {"bufname", 1, 1, f_bufname},
7069 {"bufnr", 1, 2, f_bufnr},
7070 {"bufwinnr", 1, 1, f_bufwinnr},
7071 {"byte2line", 1, 1, f_byte2line},
7072 {"byteidx", 2, 2, f_byteidx},
7073 {"call", 2, 3, f_call},
7074 {"changenr", 0, 0, f_changenr},
7075 {"char2nr", 1, 1, f_char2nr},
7076 {"cindent", 1, 1, f_cindent},
7077 {"clearmatches", 0, 0, f_clearmatches},
7078 {"col", 1, 1, f_col},
7079 #if defined(FEAT_INS_EXPAND)
7080 {"complete", 2, 2, f_complete},
7081 {"complete_add", 1, 1, f_complete_add},
7082 {"complete_check", 0, 0, f_complete_check},
7083 #endif
7084 {"confirm", 1, 4, f_confirm},
7085 {"copy", 1, 1, f_copy},
7086 {"count", 2, 4, f_count},
7087 {"cscope_connection",0,3, f_cscope_connection},
7088 {"cursor", 1, 3, f_cursor},
7089 {"deepcopy", 1, 2, f_deepcopy},
7090 {"delete", 1, 1, f_delete},
7091 {"did_filetype", 0, 0, f_did_filetype},
7092 {"diff_filler", 1, 1, f_diff_filler},
7093 {"diff_hlID", 2, 2, f_diff_hlID},
7094 {"empty", 1, 1, f_empty},
7095 {"escape", 2, 2, f_escape},
7096 {"eval", 1, 1, f_eval},
7097 {"eventhandler", 0, 0, f_eventhandler},
7098 {"executable", 1, 1, f_executable},
7099 {"exists", 1, 1, f_exists},
7100 {"expand", 1, 2, f_expand},
7101 {"extend", 2, 3, f_extend},
7102 {"feedkeys", 1, 2, f_feedkeys},
7103 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7104 {"filereadable", 1, 1, f_filereadable},
7105 {"filewritable", 1, 1, f_filewritable},
7106 {"filter", 2, 2, f_filter},
7107 {"finddir", 1, 3, f_finddir},
7108 {"findfile", 1, 3, f_findfile},
7109 {"fnamemodify", 2, 2, f_fnamemodify},
7110 {"foldclosed", 1, 1, f_foldclosed},
7111 {"foldclosedend", 1, 1, f_foldclosedend},
7112 {"foldlevel", 1, 1, f_foldlevel},
7113 {"foldtext", 0, 0, f_foldtext},
7114 {"foldtextresult", 1, 1, f_foldtextresult},
7115 {"foreground", 0, 0, f_foreground},
7116 {"function", 1, 1, f_function},
7117 {"garbagecollect", 0, 1, f_garbagecollect},
7118 {"get", 2, 3, f_get},
7119 {"getbufline", 2, 3, f_getbufline},
7120 {"getbufvar", 2, 2, f_getbufvar},
7121 {"getchar", 0, 1, f_getchar},
7122 {"getcharmod", 0, 0, f_getcharmod},
7123 {"getcmdline", 0, 0, f_getcmdline},
7124 {"getcmdpos", 0, 0, f_getcmdpos},
7125 {"getcmdtype", 0, 0, f_getcmdtype},
7126 {"getcwd", 0, 0, f_getcwd},
7127 {"getfontname", 0, 1, f_getfontname},
7128 {"getfperm", 1, 1, f_getfperm},
7129 {"getfsize", 1, 1, f_getfsize},
7130 {"getftime", 1, 1, f_getftime},
7131 {"getftype", 1, 1, f_getftype},
7132 {"getline", 1, 2, f_getline},
7133 {"getloclist", 1, 1, f_getqflist},
7134 {"getmatches", 0, 0, f_getmatches},
7135 {"getpos", 1, 1, f_getpos},
7136 {"getqflist", 0, 0, f_getqflist},
7137 {"getreg", 0, 2, f_getreg},
7138 {"getregtype", 0, 1, f_getregtype},
7139 {"gettabwinvar", 3, 3, f_gettabwinvar},
7140 {"getwinposx", 0, 0, f_getwinposx},
7141 {"getwinposy", 0, 0, f_getwinposy},
7142 {"getwinvar", 2, 2, f_getwinvar},
7143 {"glob", 1, 1, f_glob},
7144 {"globpath", 2, 2, f_globpath},
7145 {"has", 1, 1, f_has},
7146 {"has_key", 2, 2, f_has_key},
7147 {"haslocaldir", 0, 0, f_haslocaldir},
7148 {"hasmapto", 1, 3, f_hasmapto},
7149 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7150 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7151 {"histadd", 2, 2, f_histadd},
7152 {"histdel", 1, 2, f_histdel},
7153 {"histget", 1, 2, f_histget},
7154 {"histnr", 1, 1, f_histnr},
7155 {"hlID", 1, 1, f_hlID},
7156 {"hlexists", 1, 1, f_hlexists},
7157 {"hostname", 0, 0, f_hostname},
7158 {"iconv", 3, 3, f_iconv},
7159 {"indent", 1, 1, f_indent},
7160 {"index", 2, 4, f_index},
7161 {"input", 1, 3, f_input},
7162 {"inputdialog", 1, 3, f_inputdialog},
7163 {"inputlist", 1, 1, f_inputlist},
7164 {"inputrestore", 0, 0, f_inputrestore},
7165 {"inputsave", 0, 0, f_inputsave},
7166 {"inputsecret", 1, 2, f_inputsecret},
7167 {"insert", 2, 3, f_insert},
7168 {"isdirectory", 1, 1, f_isdirectory},
7169 {"islocked", 1, 1, f_islocked},
7170 {"items", 1, 1, f_items},
7171 {"join", 1, 2, f_join},
7172 {"keys", 1, 1, f_keys},
7173 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7174 {"len", 1, 1, f_len},
7175 {"libcall", 3, 3, f_libcall},
7176 {"libcallnr", 3, 3, f_libcallnr},
7177 {"line", 1, 1, f_line},
7178 {"line2byte", 1, 1, f_line2byte},
7179 {"lispindent", 1, 1, f_lispindent},
7180 {"localtime", 0, 0, f_localtime},
7181 {"map", 2, 2, f_map},
7182 {"maparg", 1, 3, f_maparg},
7183 {"mapcheck", 1, 3, f_mapcheck},
7184 {"match", 2, 4, f_match},
7185 {"matchadd", 2, 4, f_matchadd},
7186 {"matcharg", 1, 1, f_matcharg},
7187 {"matchdelete", 1, 1, f_matchdelete},
7188 {"matchend", 2, 4, f_matchend},
7189 {"matchlist", 2, 4, f_matchlist},
7190 {"matchstr", 2, 4, f_matchstr},
7191 {"max", 1, 1, f_max},
7192 {"min", 1, 1, f_min},
7193 #ifdef vim_mkdir
7194 {"mkdir", 1, 3, f_mkdir},
7195 #endif
7196 {"mode", 0, 0, f_mode},
7197 {"nextnonblank", 1, 1, f_nextnonblank},
7198 {"nr2char", 1, 1, f_nr2char},
7199 {"pathshorten", 1, 1, f_pathshorten},
7200 {"prevnonblank", 1, 1, f_prevnonblank},
7201 {"printf", 2, 19, f_printf},
7202 {"pumvisible", 0, 0, f_pumvisible},
7203 {"range", 1, 3, f_range},
7204 {"readfile", 1, 3, f_readfile},
7205 {"reltime", 0, 2, f_reltime},
7206 {"reltimestr", 1, 1, f_reltimestr},
7207 {"remote_expr", 2, 3, f_remote_expr},
7208 {"remote_foreground", 1, 1, f_remote_foreground},
7209 {"remote_peek", 1, 2, f_remote_peek},
7210 {"remote_read", 1, 1, f_remote_read},
7211 {"remote_send", 2, 3, f_remote_send},
7212 {"remove", 2, 3, f_remove},
7213 {"rename", 2, 2, f_rename},
7214 {"repeat", 2, 2, f_repeat},
7215 {"resolve", 1, 1, f_resolve},
7216 {"reverse", 1, 1, f_reverse},
7217 {"search", 1, 4, f_search},
7218 {"searchdecl", 1, 3, f_searchdecl},
7219 {"searchpair", 3, 7, f_searchpair},
7220 {"searchpairpos", 3, 7, f_searchpairpos},
7221 {"searchpos", 1, 4, f_searchpos},
7222 {"server2client", 2, 2, f_server2client},
7223 {"serverlist", 0, 0, f_serverlist},
7224 {"setbufvar", 3, 3, f_setbufvar},
7225 {"setcmdpos", 1, 1, f_setcmdpos},
7226 {"setline", 2, 2, f_setline},
7227 {"setloclist", 2, 3, f_setloclist},
7228 {"setmatches", 1, 1, f_setmatches},
7229 {"setpos", 2, 2, f_setpos},
7230 {"setqflist", 1, 2, f_setqflist},
7231 {"setreg", 2, 3, f_setreg},
7232 {"settabwinvar", 4, 4, f_settabwinvar},
7233 {"setwinvar", 3, 3, f_setwinvar},
7234 {"shellescape", 1, 1, f_shellescape},
7235 {"simplify", 1, 1, f_simplify},
7236 {"sort", 1, 2, f_sort},
7237 {"soundfold", 1, 1, f_soundfold},
7238 {"spellbadword", 0, 1, f_spellbadword},
7239 {"spellsuggest", 1, 3, f_spellsuggest},
7240 {"split", 1, 3, f_split},
7241 {"str2nr", 1, 2, f_str2nr},
7242 #ifdef HAVE_STRFTIME
7243 {"strftime", 1, 2, f_strftime},
7244 #endif
7245 {"stridx", 2, 3, f_stridx},
7246 {"string", 1, 1, f_string},
7247 {"strlen", 1, 1, f_strlen},
7248 {"strpart", 2, 3, f_strpart},
7249 {"strridx", 2, 3, f_strridx},
7250 {"strtrans", 1, 1, f_strtrans},
7251 {"submatch", 1, 1, f_submatch},
7252 {"substitute", 4, 4, f_substitute},
7253 {"synID", 3, 3, f_synID},
7254 {"synIDattr", 2, 3, f_synIDattr},
7255 {"synIDtrans", 1, 1, f_synIDtrans},
7256 {"synstack", 2, 2, f_synstack},
7257 {"system", 1, 2, f_system},
7258 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7259 {"tabpagenr", 0, 1, f_tabpagenr},
7260 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7261 {"tagfiles", 0, 0, f_tagfiles},
7262 {"taglist", 1, 1, f_taglist},
7263 {"tempname", 0, 0, f_tempname},
7264 {"test", 1, 1, f_test},
7265 {"tolower", 1, 1, f_tolower},
7266 {"toupper", 1, 1, f_toupper},
7267 {"tr", 3, 3, f_tr},
7268 {"type", 1, 1, f_type},
7269 {"values", 1, 1, f_values},
7270 {"virtcol", 1, 1, f_virtcol},
7271 {"visualmode", 0, 1, f_visualmode},
7272 {"winbufnr", 1, 1, f_winbufnr},
7273 {"wincol", 0, 0, f_wincol},
7274 {"winheight", 1, 1, f_winheight},
7275 {"winline", 0, 0, f_winline},
7276 {"winnr", 0, 1, f_winnr},
7277 {"winrestcmd", 0, 0, f_winrestcmd},
7278 {"winrestview", 1, 1, f_winrestview},
7279 {"winsaveview", 0, 0, f_winsaveview},
7280 {"winwidth", 1, 1, f_winwidth},
7281 {"writefile", 2, 3, f_writefile},
7284 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7287 * Function given to ExpandGeneric() to obtain the list of internal
7288 * or user defined function names.
7290 char_u *
7291 get_function_name(xp, idx)
7292 expand_T *xp;
7293 int idx;
7295 static int intidx = -1;
7296 char_u *name;
7298 if (idx == 0)
7299 intidx = -1;
7300 if (intidx < 0)
7302 name = get_user_func_name(xp, idx);
7303 if (name != NULL)
7304 return name;
7306 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7308 STRCPY(IObuff, functions[intidx].f_name);
7309 STRCAT(IObuff, "(");
7310 if (functions[intidx].f_max_argc == 0)
7311 STRCAT(IObuff, ")");
7312 return IObuff;
7315 return NULL;
7319 * Function given to ExpandGeneric() to obtain the list of internal or
7320 * user defined variable or function names.
7322 /*ARGSUSED*/
7323 char_u *
7324 get_expr_name(xp, idx)
7325 expand_T *xp;
7326 int idx;
7328 static int intidx = -1;
7329 char_u *name;
7331 if (idx == 0)
7332 intidx = -1;
7333 if (intidx < 0)
7335 name = get_function_name(xp, idx);
7336 if (name != NULL)
7337 return name;
7339 return get_user_var_name(xp, ++intidx);
7342 #endif /* FEAT_CMDL_COMPL */
7345 * Find internal function in table above.
7346 * Return index, or -1 if not found
7348 static int
7349 find_internal_func(name)
7350 char_u *name; /* name of the function */
7352 int first = 0;
7353 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7354 int cmp;
7355 int x;
7358 * Find the function name in the table. Binary search.
7360 while (first <= last)
7362 x = first + ((unsigned)(last - first) >> 1);
7363 cmp = STRCMP(name, functions[x].f_name);
7364 if (cmp < 0)
7365 last = x - 1;
7366 else if (cmp > 0)
7367 first = x + 1;
7368 else
7369 return x;
7371 return -1;
7375 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7376 * name it contains, otherwise return "name".
7378 static char_u *
7379 deref_func_name(name, lenp)
7380 char_u *name;
7381 int *lenp;
7383 dictitem_T *v;
7384 int cc;
7386 cc = name[*lenp];
7387 name[*lenp] = NUL;
7388 v = find_var(name, NULL);
7389 name[*lenp] = cc;
7390 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7392 if (v->di_tv.vval.v_string == NULL)
7394 *lenp = 0;
7395 return (char_u *)""; /* just in case */
7397 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7398 return v->di_tv.vval.v_string;
7401 return name;
7405 * Allocate a variable for the result of a function.
7406 * Return OK or FAIL.
7408 static int
7409 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7410 evaluate, selfdict)
7411 char_u *name; /* name of the function */
7412 int len; /* length of "name" */
7413 typval_T *rettv;
7414 char_u **arg; /* argument, pointing to the '(' */
7415 linenr_T firstline; /* first line of range */
7416 linenr_T lastline; /* last line of range */
7417 int *doesrange; /* return: function handled range */
7418 int evaluate;
7419 dict_T *selfdict; /* Dictionary for "self" */
7421 char_u *argp;
7422 int ret = OK;
7423 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7424 int argcount = 0; /* number of arguments found */
7427 * Get the arguments.
7429 argp = *arg;
7430 while (argcount < MAX_FUNC_ARGS)
7432 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7433 if (*argp == ')' || *argp == ',' || *argp == NUL)
7434 break;
7435 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7437 ret = FAIL;
7438 break;
7440 ++argcount;
7441 if (*argp != ',')
7442 break;
7444 if (*argp == ')')
7445 ++argp;
7446 else
7447 ret = FAIL;
7449 if (ret == OK)
7450 ret = call_func(name, len, rettv, argcount, argvars,
7451 firstline, lastline, doesrange, evaluate, selfdict);
7452 else if (!aborting())
7454 if (argcount == MAX_FUNC_ARGS)
7455 emsg_funcname("E740: Too many arguments for function %s", name);
7456 else
7457 emsg_funcname("E116: Invalid arguments for function %s", name);
7460 while (--argcount >= 0)
7461 clear_tv(&argvars[argcount]);
7463 *arg = skipwhite(argp);
7464 return ret;
7469 * Call a function with its resolved parameters
7470 * Return OK when the function can't be called, FAIL otherwise.
7471 * Also returns OK when an error was encountered while executing the function.
7473 static int
7474 call_func(name, len, rettv, argcount, argvars, firstline, lastline,
7475 doesrange, evaluate, selfdict)
7476 char_u *name; /* name of the function */
7477 int len; /* length of "name" */
7478 typval_T *rettv; /* return value goes here */
7479 int argcount; /* number of "argvars" */
7480 typval_T *argvars; /* vars for arguments, must have "argcount"
7481 PLUS ONE elements! */
7482 linenr_T firstline; /* first line of range */
7483 linenr_T lastline; /* last line of range */
7484 int *doesrange; /* return: function handled range */
7485 int evaluate;
7486 dict_T *selfdict; /* Dictionary for "self" */
7488 int ret = FAIL;
7489 #define ERROR_UNKNOWN 0
7490 #define ERROR_TOOMANY 1
7491 #define ERROR_TOOFEW 2
7492 #define ERROR_SCRIPT 3
7493 #define ERROR_DICT 4
7494 #define ERROR_NONE 5
7495 #define ERROR_OTHER 6
7496 int error = ERROR_NONE;
7497 int i;
7498 int llen;
7499 ufunc_T *fp;
7500 int cc;
7501 #define FLEN_FIXED 40
7502 char_u fname_buf[FLEN_FIXED + 1];
7503 char_u *fname;
7506 * In a script change <SID>name() and s:name() to K_SNR 123_name().
7507 * Change <SNR>123_name() to K_SNR 123_name().
7508 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
7510 cc = name[len];
7511 name[len] = NUL;
7512 llen = eval_fname_script(name);
7513 if (llen > 0)
7515 fname_buf[0] = K_SPECIAL;
7516 fname_buf[1] = KS_EXTRA;
7517 fname_buf[2] = (int)KE_SNR;
7518 i = 3;
7519 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
7521 if (current_SID <= 0)
7522 error = ERROR_SCRIPT;
7523 else
7525 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
7526 i = (int)STRLEN(fname_buf);
7529 if (i + STRLEN(name + llen) < FLEN_FIXED)
7531 STRCPY(fname_buf + i, name + llen);
7532 fname = fname_buf;
7534 else
7536 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
7537 if (fname == NULL)
7538 error = ERROR_OTHER;
7539 else
7541 mch_memmove(fname, fname_buf, (size_t)i);
7542 STRCPY(fname + i, name + llen);
7546 else
7547 fname = name;
7549 *doesrange = FALSE;
7552 /* execute the function if no errors detected and executing */
7553 if (evaluate && error == ERROR_NONE)
7555 rettv->v_type = VAR_NUMBER; /* default is number rettv */
7556 error = ERROR_UNKNOWN;
7558 if (!builtin_function(fname))
7561 * User defined function.
7563 fp = find_func(fname);
7565 #ifdef FEAT_AUTOCMD
7566 /* Trigger FuncUndefined event, may load the function. */
7567 if (fp == NULL
7568 && apply_autocmds(EVENT_FUNCUNDEFINED,
7569 fname, fname, TRUE, NULL)
7570 && !aborting())
7572 /* executed an autocommand, search for the function again */
7573 fp = find_func(fname);
7575 #endif
7576 /* Try loading a package. */
7577 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
7579 /* loaded a package, search for the function again */
7580 fp = find_func(fname);
7583 if (fp != NULL)
7585 if (fp->uf_flags & FC_RANGE)
7586 *doesrange = TRUE;
7587 if (argcount < fp->uf_args.ga_len)
7588 error = ERROR_TOOFEW;
7589 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
7590 error = ERROR_TOOMANY;
7591 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
7592 error = ERROR_DICT;
7593 else
7596 * Call the user function.
7597 * Save and restore search patterns, script variables and
7598 * redo buffer.
7600 save_search_patterns();
7601 saveRedobuff();
7602 ++fp->uf_calls;
7603 call_user_func(fp, argcount, argvars, rettv,
7604 firstline, lastline,
7605 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
7606 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
7607 && fp->uf_refcount <= 0)
7608 /* Function was unreferenced while being used, free it
7609 * now. */
7610 func_free(fp);
7611 restoreRedobuff();
7612 restore_search_patterns();
7613 error = ERROR_NONE;
7617 else
7620 * Find the function name in the table, call its implementation.
7622 i = find_internal_func(fname);
7623 if (i >= 0)
7625 if (argcount < functions[i].f_min_argc)
7626 error = ERROR_TOOFEW;
7627 else if (argcount > functions[i].f_max_argc)
7628 error = ERROR_TOOMANY;
7629 else
7631 argvars[argcount].v_type = VAR_UNKNOWN;
7632 functions[i].f_func(argvars, rettv);
7633 error = ERROR_NONE;
7638 * The function call (or "FuncUndefined" autocommand sequence) might
7639 * have been aborted by an error, an interrupt, or an explicitly thrown
7640 * exception that has not been caught so far. This situation can be
7641 * tested for by calling aborting(). For an error in an internal
7642 * function or for the "E132" error in call_user_func(), however, the
7643 * throw point at which the "force_abort" flag (temporarily reset by
7644 * emsg()) is normally updated has not been reached yet. We need to
7645 * update that flag first to make aborting() reliable.
7647 update_force_abort();
7649 if (error == ERROR_NONE)
7650 ret = OK;
7653 * Report an error unless the argument evaluation or function call has been
7654 * cancelled due to an aborting error, an interrupt, or an exception.
7656 if (!aborting())
7658 switch (error)
7660 case ERROR_UNKNOWN:
7661 emsg_funcname(N_("E117: Unknown function: %s"), name);
7662 break;
7663 case ERROR_TOOMANY:
7664 emsg_funcname(e_toomanyarg, name);
7665 break;
7666 case ERROR_TOOFEW:
7667 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
7668 name);
7669 break;
7670 case ERROR_SCRIPT:
7671 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
7672 name);
7673 break;
7674 case ERROR_DICT:
7675 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
7676 name);
7677 break;
7681 name[len] = cc;
7682 if (fname != name && fname != fname_buf)
7683 vim_free(fname);
7685 return ret;
7689 * Give an error message with a function name. Handle <SNR> things.
7691 static void
7692 emsg_funcname(ermsg, name)
7693 char *ermsg;
7694 char_u *name;
7696 char_u *p;
7698 if (*name == K_SPECIAL)
7699 p = concat_str((char_u *)"<SNR>", name + 3);
7700 else
7701 p = name;
7702 EMSG2(_(ermsg), p);
7703 if (p != name)
7704 vim_free(p);
7707 /*********************************************
7708 * Implementation of the built-in functions
7712 * "add(list, item)" function
7714 static void
7715 f_add(argvars, rettv)
7716 typval_T *argvars;
7717 typval_T *rettv;
7719 list_T *l;
7721 rettv->vval.v_number = 1; /* Default: Failed */
7722 if (argvars[0].v_type == VAR_LIST)
7724 if ((l = argvars[0].vval.v_list) != NULL
7725 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
7726 && list_append_tv(l, &argvars[1]) == OK)
7727 copy_tv(&argvars[0], rettv);
7729 else
7730 EMSG(_(e_listreq));
7734 * "append(lnum, string/list)" function
7736 static void
7737 f_append(argvars, rettv)
7738 typval_T *argvars;
7739 typval_T *rettv;
7741 long lnum;
7742 char_u *line;
7743 list_T *l = NULL;
7744 listitem_T *li = NULL;
7745 typval_T *tv;
7746 long added = 0;
7748 lnum = get_tv_lnum(argvars);
7749 if (lnum >= 0
7750 && lnum <= curbuf->b_ml.ml_line_count
7751 && u_save(lnum, lnum + 1) == OK)
7753 if (argvars[1].v_type == VAR_LIST)
7755 l = argvars[1].vval.v_list;
7756 if (l == NULL)
7757 return;
7758 li = l->lv_first;
7760 rettv->vval.v_number = 0; /* Default: Success */
7761 for (;;)
7763 if (l == NULL)
7764 tv = &argvars[1]; /* append a string */
7765 else if (li == NULL)
7766 break; /* end of list */
7767 else
7768 tv = &li->li_tv; /* append item from list */
7769 line = get_tv_string_chk(tv);
7770 if (line == NULL) /* type error */
7772 rettv->vval.v_number = 1; /* Failed */
7773 break;
7775 ml_append(lnum + added, line, (colnr_T)0, FALSE);
7776 ++added;
7777 if (l == NULL)
7778 break;
7779 li = li->li_next;
7782 appended_lines_mark(lnum, added);
7783 if (curwin->w_cursor.lnum > lnum)
7784 curwin->w_cursor.lnum += added;
7786 else
7787 rettv->vval.v_number = 1; /* Failed */
7791 * "argc()" function
7793 /* ARGSUSED */
7794 static void
7795 f_argc(argvars, rettv)
7796 typval_T *argvars;
7797 typval_T *rettv;
7799 rettv->vval.v_number = ARGCOUNT;
7803 * "argidx()" function
7805 /* ARGSUSED */
7806 static void
7807 f_argidx(argvars, rettv)
7808 typval_T *argvars;
7809 typval_T *rettv;
7811 rettv->vval.v_number = curwin->w_arg_idx;
7815 * "argv(nr)" function
7817 static void
7818 f_argv(argvars, rettv)
7819 typval_T *argvars;
7820 typval_T *rettv;
7822 int idx;
7824 if (argvars[0].v_type != VAR_UNKNOWN)
7826 idx = get_tv_number_chk(&argvars[0], NULL);
7827 if (idx >= 0 && idx < ARGCOUNT)
7828 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
7829 else
7830 rettv->vval.v_string = NULL;
7831 rettv->v_type = VAR_STRING;
7833 else if (rettv_list_alloc(rettv) == OK)
7834 for (idx = 0; idx < ARGCOUNT; ++idx)
7835 list_append_string(rettv->vval.v_list,
7836 alist_name(&ARGLIST[idx]), -1);
7840 * "browse(save, title, initdir, default)" function
7842 /* ARGSUSED */
7843 static void
7844 f_browse(argvars, rettv)
7845 typval_T *argvars;
7846 typval_T *rettv;
7848 #ifdef FEAT_BROWSE
7849 int save;
7850 char_u *title;
7851 char_u *initdir;
7852 char_u *defname;
7853 char_u buf[NUMBUFLEN];
7854 char_u buf2[NUMBUFLEN];
7855 int error = FALSE;
7857 save = get_tv_number_chk(&argvars[0], &error);
7858 title = get_tv_string_chk(&argvars[1]);
7859 initdir = get_tv_string_buf_chk(&argvars[2], buf);
7860 defname = get_tv_string_buf_chk(&argvars[3], buf2);
7862 if (error || title == NULL || initdir == NULL || defname == NULL)
7863 rettv->vval.v_string = NULL;
7864 else
7865 rettv->vval.v_string =
7866 do_browse(save ? BROWSE_SAVE : 0,
7867 title, defname, NULL, initdir, NULL, curbuf);
7868 #else
7869 rettv->vval.v_string = NULL;
7870 #endif
7871 rettv->v_type = VAR_STRING;
7875 * "browsedir(title, initdir)" function
7877 /* ARGSUSED */
7878 static void
7879 f_browsedir(argvars, rettv)
7880 typval_T *argvars;
7881 typval_T *rettv;
7883 #ifdef FEAT_BROWSE
7884 char_u *title;
7885 char_u *initdir;
7886 char_u buf[NUMBUFLEN];
7888 title = get_tv_string_chk(&argvars[0]);
7889 initdir = get_tv_string_buf_chk(&argvars[1], buf);
7891 if (title == NULL || initdir == NULL)
7892 rettv->vval.v_string = NULL;
7893 else
7894 rettv->vval.v_string = do_browse(BROWSE_DIR,
7895 title, NULL, NULL, initdir, NULL, curbuf);
7896 #else
7897 rettv->vval.v_string = NULL;
7898 #endif
7899 rettv->v_type = VAR_STRING;
7902 static buf_T *find_buffer __ARGS((typval_T *avar));
7905 * Find a buffer by number or exact name.
7907 static buf_T *
7908 find_buffer(avar)
7909 typval_T *avar;
7911 buf_T *buf = NULL;
7913 if (avar->v_type == VAR_NUMBER)
7914 buf = buflist_findnr((int)avar->vval.v_number);
7915 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
7917 buf = buflist_findname_exp(avar->vval.v_string);
7918 if (buf == NULL)
7920 /* No full path name match, try a match with a URL or a "nofile"
7921 * buffer, these don't use the full path. */
7922 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
7923 if (buf->b_fname != NULL
7924 && (path_with_url(buf->b_fname)
7925 #ifdef FEAT_QUICKFIX
7926 || bt_nofile(buf)
7927 #endif
7929 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
7930 break;
7933 return buf;
7937 * "bufexists(expr)" function
7939 static void
7940 f_bufexists(argvars, rettv)
7941 typval_T *argvars;
7942 typval_T *rettv;
7944 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
7948 * "buflisted(expr)" function
7950 static void
7951 f_buflisted(argvars, rettv)
7952 typval_T *argvars;
7953 typval_T *rettv;
7955 buf_T *buf;
7957 buf = find_buffer(&argvars[0]);
7958 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
7962 * "bufloaded(expr)" function
7964 static void
7965 f_bufloaded(argvars, rettv)
7966 typval_T *argvars;
7967 typval_T *rettv;
7969 buf_T *buf;
7971 buf = find_buffer(&argvars[0]);
7972 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
7975 static buf_T *get_buf_tv __ARGS((typval_T *tv));
7978 * Get buffer by number or pattern.
7980 static buf_T *
7981 get_buf_tv(tv)
7982 typval_T *tv;
7984 char_u *name = tv->vval.v_string;
7985 int save_magic;
7986 char_u *save_cpo;
7987 buf_T *buf;
7989 if (tv->v_type == VAR_NUMBER)
7990 return buflist_findnr((int)tv->vval.v_number);
7991 if (tv->v_type != VAR_STRING)
7992 return NULL;
7993 if (name == NULL || *name == NUL)
7994 return curbuf;
7995 if (name[0] == '$' && name[1] == NUL)
7996 return lastbuf;
7998 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
7999 save_magic = p_magic;
8000 p_magic = TRUE;
8001 save_cpo = p_cpo;
8002 p_cpo = (char_u *)"";
8004 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8005 TRUE, FALSE));
8007 p_magic = save_magic;
8008 p_cpo = save_cpo;
8010 /* If not found, try expanding the name, like done for bufexists(). */
8011 if (buf == NULL)
8012 buf = find_buffer(tv);
8014 return buf;
8018 * "bufname(expr)" function
8020 static void
8021 f_bufname(argvars, rettv)
8022 typval_T *argvars;
8023 typval_T *rettv;
8025 buf_T *buf;
8027 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8028 ++emsg_off;
8029 buf = get_buf_tv(&argvars[0]);
8030 rettv->v_type = VAR_STRING;
8031 if (buf != NULL && buf->b_fname != NULL)
8032 rettv->vval.v_string = vim_strsave(buf->b_fname);
8033 else
8034 rettv->vval.v_string = NULL;
8035 --emsg_off;
8039 * "bufnr(expr)" function
8041 static void
8042 f_bufnr(argvars, rettv)
8043 typval_T *argvars;
8044 typval_T *rettv;
8046 buf_T *buf;
8047 int error = FALSE;
8048 char_u *name;
8050 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8051 ++emsg_off;
8052 buf = get_buf_tv(&argvars[0]);
8053 --emsg_off;
8055 /* If the buffer isn't found and the second argument is not zero create a
8056 * new buffer. */
8057 if (buf == NULL
8058 && argvars[1].v_type != VAR_UNKNOWN
8059 && get_tv_number_chk(&argvars[1], &error) != 0
8060 && !error
8061 && (name = get_tv_string_chk(&argvars[0])) != NULL
8062 && !error)
8063 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8065 if (buf != NULL)
8066 rettv->vval.v_number = buf->b_fnum;
8067 else
8068 rettv->vval.v_number = -1;
8072 * "bufwinnr(nr)" function
8074 static void
8075 f_bufwinnr(argvars, rettv)
8076 typval_T *argvars;
8077 typval_T *rettv;
8079 #ifdef FEAT_WINDOWS
8080 win_T *wp;
8081 int winnr = 0;
8082 #endif
8083 buf_T *buf;
8085 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8086 ++emsg_off;
8087 buf = get_buf_tv(&argvars[0]);
8088 #ifdef FEAT_WINDOWS
8089 for (wp = firstwin; wp; wp = wp->w_next)
8091 ++winnr;
8092 if (wp->w_buffer == buf)
8093 break;
8095 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8096 #else
8097 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8098 #endif
8099 --emsg_off;
8103 * "byte2line(byte)" function
8105 /*ARGSUSED*/
8106 static void
8107 f_byte2line(argvars, rettv)
8108 typval_T *argvars;
8109 typval_T *rettv;
8111 #ifndef FEAT_BYTEOFF
8112 rettv->vval.v_number = -1;
8113 #else
8114 long boff = 0;
8116 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8117 if (boff < 0)
8118 rettv->vval.v_number = -1;
8119 else
8120 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8121 (linenr_T)0, &boff);
8122 #endif
8126 * "byteidx()" function
8128 /*ARGSUSED*/
8129 static void
8130 f_byteidx(argvars, rettv)
8131 typval_T *argvars;
8132 typval_T *rettv;
8134 #ifdef FEAT_MBYTE
8135 char_u *t;
8136 #endif
8137 char_u *str;
8138 long idx;
8140 str = get_tv_string_chk(&argvars[0]);
8141 idx = get_tv_number_chk(&argvars[1], NULL);
8142 rettv->vval.v_number = -1;
8143 if (str == NULL || idx < 0)
8144 return;
8146 #ifdef FEAT_MBYTE
8147 t = str;
8148 for ( ; idx > 0; idx--)
8150 if (*t == NUL) /* EOL reached */
8151 return;
8152 t += (*mb_ptr2len)(t);
8154 rettv->vval.v_number = (varnumber_T)(t - str);
8155 #else
8156 if (idx <= STRLEN(str))
8157 rettv->vval.v_number = idx;
8158 #endif
8162 * "call(func, arglist)" function
8164 static void
8165 f_call(argvars, rettv)
8166 typval_T *argvars;
8167 typval_T *rettv;
8169 char_u *func;
8170 typval_T argv[MAX_FUNC_ARGS + 1];
8171 int argc = 0;
8172 listitem_T *item;
8173 int dummy;
8174 dict_T *selfdict = NULL;
8176 rettv->vval.v_number = 0;
8177 if (argvars[1].v_type != VAR_LIST)
8179 EMSG(_(e_listreq));
8180 return;
8182 if (argvars[1].vval.v_list == NULL)
8183 return;
8185 if (argvars[0].v_type == VAR_FUNC)
8186 func = argvars[0].vval.v_string;
8187 else
8188 func = get_tv_string(&argvars[0]);
8189 if (*func == NUL)
8190 return; /* type error or empty name */
8192 if (argvars[2].v_type != VAR_UNKNOWN)
8194 if (argvars[2].v_type != VAR_DICT)
8196 EMSG(_(e_dictreq));
8197 return;
8199 selfdict = argvars[2].vval.v_dict;
8202 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
8203 item = item->li_next)
8205 if (argc == MAX_FUNC_ARGS)
8207 EMSG(_("E699: Too many arguments"));
8208 break;
8210 /* Make a copy of each argument. This is needed to be able to set
8211 * v_lock to VAR_FIXED in the copy without changing the original list.
8213 copy_tv(&item->li_tv, &argv[argc++]);
8216 if (item == NULL)
8217 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
8218 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
8219 &dummy, TRUE, selfdict);
8221 /* Free the arguments. */
8222 while (argc > 0)
8223 clear_tv(&argv[--argc]);
8227 * "changenr()" function
8229 /*ARGSUSED*/
8230 static void
8231 f_changenr(argvars, rettv)
8232 typval_T *argvars;
8233 typval_T *rettv;
8235 rettv->vval.v_number = curbuf->b_u_seq_cur;
8239 * "char2nr(string)" function
8241 static void
8242 f_char2nr(argvars, rettv)
8243 typval_T *argvars;
8244 typval_T *rettv;
8246 #ifdef FEAT_MBYTE
8247 if (has_mbyte)
8248 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
8249 else
8250 #endif
8251 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
8255 * "cindent(lnum)" function
8257 static void
8258 f_cindent(argvars, rettv)
8259 typval_T *argvars;
8260 typval_T *rettv;
8262 #ifdef FEAT_CINDENT
8263 pos_T pos;
8264 linenr_T lnum;
8266 pos = curwin->w_cursor;
8267 lnum = get_tv_lnum(argvars);
8268 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
8270 curwin->w_cursor.lnum = lnum;
8271 rettv->vval.v_number = get_c_indent();
8272 curwin->w_cursor = pos;
8274 else
8275 #endif
8276 rettv->vval.v_number = -1;
8280 * "clearmatches()" function
8282 /*ARGSUSED*/
8283 static void
8284 f_clearmatches(argvars, rettv)
8285 typval_T *argvars;
8286 typval_T *rettv;
8288 #ifdef FEAT_SEARCH_EXTRA
8289 clear_matches(curwin);
8290 #endif
8294 * "col(string)" function
8296 static void
8297 f_col(argvars, rettv)
8298 typval_T *argvars;
8299 typval_T *rettv;
8301 colnr_T col = 0;
8302 pos_T *fp;
8303 int fnum = curbuf->b_fnum;
8305 fp = var2fpos(&argvars[0], FALSE, &fnum);
8306 if (fp != NULL && fnum == curbuf->b_fnum)
8308 if (fp->col == MAXCOL)
8310 /* '> can be MAXCOL, get the length of the line then */
8311 if (fp->lnum <= curbuf->b_ml.ml_line_count)
8312 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
8313 else
8314 col = MAXCOL;
8316 else
8318 col = fp->col + 1;
8319 #ifdef FEAT_VIRTUALEDIT
8320 /* col(".") when the cursor is on the NUL at the end of the line
8321 * because of "coladd" can be seen as an extra column. */
8322 if (virtual_active() && fp == &curwin->w_cursor)
8324 char_u *p = ml_get_cursor();
8326 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
8327 curwin->w_virtcol - curwin->w_cursor.coladd))
8329 # ifdef FEAT_MBYTE
8330 int l;
8332 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
8333 col += l;
8334 # else
8335 if (*p != NUL && p[1] == NUL)
8336 ++col;
8337 # endif
8340 #endif
8343 rettv->vval.v_number = col;
8346 #if defined(FEAT_INS_EXPAND)
8348 * "complete()" function
8350 /*ARGSUSED*/
8351 static void
8352 f_complete(argvars, rettv)
8353 typval_T *argvars;
8354 typval_T *rettv;
8356 int startcol;
8358 if ((State & INSERT) == 0)
8360 EMSG(_("E785: complete() can only be used in Insert mode"));
8361 return;
8364 /* Check for undo allowed here, because if something was already inserted
8365 * the line was already saved for undo and this check isn't done. */
8366 if (!undo_allowed())
8367 return;
8369 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
8371 EMSG(_(e_invarg));
8372 return;
8375 startcol = get_tv_number_chk(&argvars[0], NULL);
8376 if (startcol <= 0)
8377 return;
8379 set_completion(startcol - 1, argvars[1].vval.v_list);
8383 * "complete_add()" function
8385 /*ARGSUSED*/
8386 static void
8387 f_complete_add(argvars, rettv)
8388 typval_T *argvars;
8389 typval_T *rettv;
8391 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
8395 * "complete_check()" function
8397 /*ARGSUSED*/
8398 static void
8399 f_complete_check(argvars, rettv)
8400 typval_T *argvars;
8401 typval_T *rettv;
8403 int saved = RedrawingDisabled;
8405 RedrawingDisabled = 0;
8406 ins_compl_check_keys(0);
8407 rettv->vval.v_number = compl_interrupted;
8408 RedrawingDisabled = saved;
8410 #endif
8413 * "confirm(message, buttons[, default [, type]])" function
8415 /*ARGSUSED*/
8416 static void
8417 f_confirm(argvars, rettv)
8418 typval_T *argvars;
8419 typval_T *rettv;
8421 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
8422 char_u *message;
8423 char_u *buttons = NULL;
8424 char_u buf[NUMBUFLEN];
8425 char_u buf2[NUMBUFLEN];
8426 int def = 1;
8427 int type = VIM_GENERIC;
8428 char_u *typestr;
8429 int error = FALSE;
8431 message = get_tv_string_chk(&argvars[0]);
8432 if (message == NULL)
8433 error = TRUE;
8434 if (argvars[1].v_type != VAR_UNKNOWN)
8436 buttons = get_tv_string_buf_chk(&argvars[1], buf);
8437 if (buttons == NULL)
8438 error = TRUE;
8439 if (argvars[2].v_type != VAR_UNKNOWN)
8441 def = get_tv_number_chk(&argvars[2], &error);
8442 if (argvars[3].v_type != VAR_UNKNOWN)
8444 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
8445 if (typestr == NULL)
8446 error = TRUE;
8447 else
8449 switch (TOUPPER_ASC(*typestr))
8451 case 'E': type = VIM_ERROR; break;
8452 case 'Q': type = VIM_QUESTION; break;
8453 case 'I': type = VIM_INFO; break;
8454 case 'W': type = VIM_WARNING; break;
8455 case 'G': type = VIM_GENERIC; break;
8462 if (buttons == NULL || *buttons == NUL)
8463 buttons = (char_u *)_("&Ok");
8465 if (error)
8466 rettv->vval.v_number = 0;
8467 else
8468 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
8469 def, NULL);
8470 #else
8471 rettv->vval.v_number = 0;
8472 #endif
8476 * "copy()" function
8478 static void
8479 f_copy(argvars, rettv)
8480 typval_T *argvars;
8481 typval_T *rettv;
8483 item_copy(&argvars[0], rettv, FALSE, 0);
8487 * "count()" function
8489 static void
8490 f_count(argvars, rettv)
8491 typval_T *argvars;
8492 typval_T *rettv;
8494 long n = 0;
8495 int ic = FALSE;
8497 if (argvars[0].v_type == VAR_LIST)
8499 listitem_T *li;
8500 list_T *l;
8501 long idx;
8503 if ((l = argvars[0].vval.v_list) != NULL)
8505 li = l->lv_first;
8506 if (argvars[2].v_type != VAR_UNKNOWN)
8508 int error = FALSE;
8510 ic = get_tv_number_chk(&argvars[2], &error);
8511 if (argvars[3].v_type != VAR_UNKNOWN)
8513 idx = get_tv_number_chk(&argvars[3], &error);
8514 if (!error)
8516 li = list_find(l, idx);
8517 if (li == NULL)
8518 EMSGN(_(e_listidx), idx);
8521 if (error)
8522 li = NULL;
8525 for ( ; li != NULL; li = li->li_next)
8526 if (tv_equal(&li->li_tv, &argvars[1], ic))
8527 ++n;
8530 else if (argvars[0].v_type == VAR_DICT)
8532 int todo;
8533 dict_T *d;
8534 hashitem_T *hi;
8536 if ((d = argvars[0].vval.v_dict) != NULL)
8538 int error = FALSE;
8540 if (argvars[2].v_type != VAR_UNKNOWN)
8542 ic = get_tv_number_chk(&argvars[2], &error);
8543 if (argvars[3].v_type != VAR_UNKNOWN)
8544 EMSG(_(e_invarg));
8547 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
8548 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
8550 if (!HASHITEM_EMPTY(hi))
8552 --todo;
8553 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
8554 ++n;
8559 else
8560 EMSG2(_(e_listdictarg), "count()");
8561 rettv->vval.v_number = n;
8565 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
8567 * Checks the existence of a cscope connection.
8569 /*ARGSUSED*/
8570 static void
8571 f_cscope_connection(argvars, rettv)
8572 typval_T *argvars;
8573 typval_T *rettv;
8575 #ifdef FEAT_CSCOPE
8576 int num = 0;
8577 char_u *dbpath = NULL;
8578 char_u *prepend = NULL;
8579 char_u buf[NUMBUFLEN];
8581 if (argvars[0].v_type != VAR_UNKNOWN
8582 && argvars[1].v_type != VAR_UNKNOWN)
8584 num = (int)get_tv_number(&argvars[0]);
8585 dbpath = get_tv_string(&argvars[1]);
8586 if (argvars[2].v_type != VAR_UNKNOWN)
8587 prepend = get_tv_string_buf(&argvars[2], buf);
8590 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
8591 #else
8592 rettv->vval.v_number = 0;
8593 #endif
8597 * "cursor(lnum, col)" function
8599 * Moves the cursor to the specified line and column
8601 /*ARGSUSED*/
8602 static void
8603 f_cursor(argvars, rettv)
8604 typval_T *argvars;
8605 typval_T *rettv;
8607 long line, col;
8608 #ifdef FEAT_VIRTUALEDIT
8609 long coladd = 0;
8610 #endif
8612 if (argvars[1].v_type == VAR_UNKNOWN)
8614 pos_T pos;
8616 if (list2fpos(argvars, &pos, NULL) == FAIL)
8617 return;
8618 line = pos.lnum;
8619 col = pos.col;
8620 #ifdef FEAT_VIRTUALEDIT
8621 coladd = pos.coladd;
8622 #endif
8624 else
8626 line = get_tv_lnum(argvars);
8627 col = get_tv_number_chk(&argvars[1], NULL);
8628 #ifdef FEAT_VIRTUALEDIT
8629 if (argvars[2].v_type != VAR_UNKNOWN)
8630 coladd = get_tv_number_chk(&argvars[2], NULL);
8631 #endif
8633 if (line < 0 || col < 0
8634 #ifdef FEAT_VIRTUALEDIT
8635 || coladd < 0
8636 #endif
8638 return; /* type error; errmsg already given */
8639 if (line > 0)
8640 curwin->w_cursor.lnum = line;
8641 if (col > 0)
8642 curwin->w_cursor.col = col - 1;
8643 #ifdef FEAT_VIRTUALEDIT
8644 curwin->w_cursor.coladd = coladd;
8645 #endif
8647 /* Make sure the cursor is in a valid position. */
8648 check_cursor();
8649 #ifdef FEAT_MBYTE
8650 /* Correct cursor for multi-byte character. */
8651 if (has_mbyte)
8652 mb_adjust_cursor();
8653 #endif
8655 curwin->w_set_curswant = TRUE;
8659 * "deepcopy()" function
8661 static void
8662 f_deepcopy(argvars, rettv)
8663 typval_T *argvars;
8664 typval_T *rettv;
8666 int noref = 0;
8668 if (argvars[1].v_type != VAR_UNKNOWN)
8669 noref = get_tv_number_chk(&argvars[1], NULL);
8670 if (noref < 0 || noref > 1)
8671 EMSG(_(e_invarg));
8672 else
8673 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? ++current_copyID : 0);
8677 * "delete()" function
8679 static void
8680 f_delete(argvars, rettv)
8681 typval_T *argvars;
8682 typval_T *rettv;
8684 if (check_restricted() || check_secure())
8685 rettv->vval.v_number = -1;
8686 else
8687 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
8691 * "did_filetype()" function
8693 /*ARGSUSED*/
8694 static void
8695 f_did_filetype(argvars, rettv)
8696 typval_T *argvars;
8697 typval_T *rettv;
8699 #ifdef FEAT_AUTOCMD
8700 rettv->vval.v_number = did_filetype;
8701 #else
8702 rettv->vval.v_number = 0;
8703 #endif
8707 * "diff_filler()" function
8709 /*ARGSUSED*/
8710 static void
8711 f_diff_filler(argvars, rettv)
8712 typval_T *argvars;
8713 typval_T *rettv;
8715 #ifdef FEAT_DIFF
8716 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
8717 #endif
8721 * "diff_hlID()" function
8723 /*ARGSUSED*/
8724 static void
8725 f_diff_hlID(argvars, rettv)
8726 typval_T *argvars;
8727 typval_T *rettv;
8729 #ifdef FEAT_DIFF
8730 linenr_T lnum = get_tv_lnum(argvars);
8731 static linenr_T prev_lnum = 0;
8732 static int changedtick = 0;
8733 static int fnum = 0;
8734 static int change_start = 0;
8735 static int change_end = 0;
8736 static hlf_T hlID = (hlf_T)0;
8737 int filler_lines;
8738 int col;
8740 if (lnum < 0) /* ignore type error in {lnum} arg */
8741 lnum = 0;
8742 if (lnum != prev_lnum
8743 || changedtick != curbuf->b_changedtick
8744 || fnum != curbuf->b_fnum)
8746 /* New line, buffer, change: need to get the values. */
8747 filler_lines = diff_check(curwin, lnum);
8748 if (filler_lines < 0)
8750 if (filler_lines == -1)
8752 change_start = MAXCOL;
8753 change_end = -1;
8754 if (diff_find_change(curwin, lnum, &change_start, &change_end))
8755 hlID = HLF_ADD; /* added line */
8756 else
8757 hlID = HLF_CHD; /* changed line */
8759 else
8760 hlID = HLF_ADD; /* added line */
8762 else
8763 hlID = (hlf_T)0;
8764 prev_lnum = lnum;
8765 changedtick = curbuf->b_changedtick;
8766 fnum = curbuf->b_fnum;
8769 if (hlID == HLF_CHD || hlID == HLF_TXD)
8771 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
8772 if (col >= change_start && col <= change_end)
8773 hlID = HLF_TXD; /* changed text */
8774 else
8775 hlID = HLF_CHD; /* changed line */
8777 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
8778 #endif
8782 * "empty({expr})" function
8784 static void
8785 f_empty(argvars, rettv)
8786 typval_T *argvars;
8787 typval_T *rettv;
8789 int n;
8791 switch (argvars[0].v_type)
8793 case VAR_STRING:
8794 case VAR_FUNC:
8795 n = argvars[0].vval.v_string == NULL
8796 || *argvars[0].vval.v_string == NUL;
8797 break;
8798 case VAR_NUMBER:
8799 n = argvars[0].vval.v_number == 0;
8800 break;
8801 case VAR_LIST:
8802 n = argvars[0].vval.v_list == NULL
8803 || argvars[0].vval.v_list->lv_first == NULL;
8804 break;
8805 case VAR_DICT:
8806 n = argvars[0].vval.v_dict == NULL
8807 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
8808 break;
8809 default:
8810 EMSG2(_(e_intern2), "f_empty()");
8811 n = 0;
8814 rettv->vval.v_number = n;
8818 * "escape({string}, {chars})" function
8820 static void
8821 f_escape(argvars, rettv)
8822 typval_T *argvars;
8823 typval_T *rettv;
8825 char_u buf[NUMBUFLEN];
8827 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
8828 get_tv_string_buf(&argvars[1], buf));
8829 rettv->v_type = VAR_STRING;
8833 * "eval()" function
8835 /*ARGSUSED*/
8836 static void
8837 f_eval(argvars, rettv)
8838 typval_T *argvars;
8839 typval_T *rettv;
8841 char_u *s;
8843 s = get_tv_string_chk(&argvars[0]);
8844 if (s != NULL)
8845 s = skipwhite(s);
8847 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
8849 rettv->v_type = VAR_NUMBER;
8850 rettv->vval.v_number = 0;
8852 else if (*s != NUL)
8853 EMSG(_(e_trailing));
8857 * "eventhandler()" function
8859 /*ARGSUSED*/
8860 static void
8861 f_eventhandler(argvars, rettv)
8862 typval_T *argvars;
8863 typval_T *rettv;
8865 rettv->vval.v_number = vgetc_busy;
8869 * "executable()" function
8871 static void
8872 f_executable(argvars, rettv)
8873 typval_T *argvars;
8874 typval_T *rettv;
8876 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
8880 * "exists()" function
8882 static void
8883 f_exists(argvars, rettv)
8884 typval_T *argvars;
8885 typval_T *rettv;
8887 char_u *p;
8888 char_u *name;
8889 int n = FALSE;
8890 int len = 0;
8892 p = get_tv_string(&argvars[0]);
8893 if (*p == '$') /* environment variable */
8895 /* first try "normal" environment variables (fast) */
8896 if (mch_getenv(p + 1) != NULL)
8897 n = TRUE;
8898 else
8900 /* try expanding things like $VIM and ${HOME} */
8901 p = expand_env_save(p);
8902 if (p != NULL && *p != '$')
8903 n = TRUE;
8904 vim_free(p);
8907 else if (*p == '&' || *p == '+') /* option */
8909 n = (get_option_tv(&p, NULL, TRUE) == OK);
8910 if (*skipwhite(p) != NUL)
8911 n = FALSE; /* trailing garbage */
8913 else if (*p == '*') /* internal or user defined function */
8915 n = function_exists(p + 1);
8917 else if (*p == ':')
8919 n = cmd_exists(p + 1);
8921 else if (*p == '#')
8923 #ifdef FEAT_AUTOCMD
8924 if (p[1] == '#')
8925 n = autocmd_supported(p + 2);
8926 else
8927 n = au_exists(p + 1);
8928 #endif
8930 else /* internal variable */
8932 char_u *tofree;
8933 typval_T tv;
8935 /* get_name_len() takes care of expanding curly braces */
8936 name = p;
8937 len = get_name_len(&p, &tofree, TRUE, FALSE);
8938 if (len > 0)
8940 if (tofree != NULL)
8941 name = tofree;
8942 n = (get_var_tv(name, len, &tv, FALSE) == OK);
8943 if (n)
8945 /* handle d.key, l[idx], f(expr) */
8946 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
8947 if (n)
8948 clear_tv(&tv);
8951 if (*p != NUL)
8952 n = FALSE;
8954 vim_free(tofree);
8957 rettv->vval.v_number = n;
8961 * "expand()" function
8963 static void
8964 f_expand(argvars, rettv)
8965 typval_T *argvars;
8966 typval_T *rettv;
8968 char_u *s;
8969 int len;
8970 char_u *errormsg;
8971 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
8972 expand_T xpc;
8973 int error = FALSE;
8975 rettv->v_type = VAR_STRING;
8976 s = get_tv_string(&argvars[0]);
8977 if (*s == '%' || *s == '#' || *s == '<')
8979 ++emsg_off;
8980 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
8981 --emsg_off;
8983 else
8985 /* When the optional second argument is non-zero, don't remove matches
8986 * for 'suffixes' and 'wildignore' */
8987 if (argvars[1].v_type != VAR_UNKNOWN
8988 && get_tv_number_chk(&argvars[1], &error))
8989 flags |= WILD_KEEP_ALL;
8990 if (!error)
8992 ExpandInit(&xpc);
8993 xpc.xp_context = EXPAND_FILES;
8994 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
8996 else
8997 rettv->vval.v_string = NULL;
9002 * "extend(list, list [, idx])" function
9003 * "extend(dict, dict [, action])" function
9005 static void
9006 f_extend(argvars, rettv)
9007 typval_T *argvars;
9008 typval_T *rettv;
9010 rettv->vval.v_number = 0;
9011 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9013 list_T *l1, *l2;
9014 listitem_T *item;
9015 long before;
9016 int error = FALSE;
9018 l1 = argvars[0].vval.v_list;
9019 l2 = argvars[1].vval.v_list;
9020 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9021 && l2 != NULL)
9023 if (argvars[2].v_type != VAR_UNKNOWN)
9025 before = get_tv_number_chk(&argvars[2], &error);
9026 if (error)
9027 return; /* type error; errmsg already given */
9029 if (before == l1->lv_len)
9030 item = NULL;
9031 else
9033 item = list_find(l1, before);
9034 if (item == NULL)
9036 EMSGN(_(e_listidx), before);
9037 return;
9041 else
9042 item = NULL;
9043 list_extend(l1, l2, item);
9045 copy_tv(&argvars[0], rettv);
9048 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9050 dict_T *d1, *d2;
9051 dictitem_T *di1;
9052 char_u *action;
9053 int i;
9054 hashitem_T *hi2;
9055 int todo;
9057 d1 = argvars[0].vval.v_dict;
9058 d2 = argvars[1].vval.v_dict;
9059 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9060 && d2 != NULL)
9062 /* Check the third argument. */
9063 if (argvars[2].v_type != VAR_UNKNOWN)
9065 static char *(av[]) = {"keep", "force", "error"};
9067 action = get_tv_string_chk(&argvars[2]);
9068 if (action == NULL)
9069 return; /* type error; errmsg already given */
9070 for (i = 0; i < 3; ++i)
9071 if (STRCMP(action, av[i]) == 0)
9072 break;
9073 if (i == 3)
9075 EMSG2(_(e_invarg2), action);
9076 return;
9079 else
9080 action = (char_u *)"force";
9082 /* Go over all entries in the second dict and add them to the
9083 * first dict. */
9084 todo = (int)d2->dv_hashtab.ht_used;
9085 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9087 if (!HASHITEM_EMPTY(hi2))
9089 --todo;
9090 di1 = dict_find(d1, hi2->hi_key, -1);
9091 if (di1 == NULL)
9093 di1 = dictitem_copy(HI2DI(hi2));
9094 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9095 dictitem_free(di1);
9097 else if (*action == 'e')
9099 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9100 break;
9102 else if (*action == 'f')
9104 clear_tv(&di1->di_tv);
9105 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9110 copy_tv(&argvars[0], rettv);
9113 else
9114 EMSG2(_(e_listdictarg), "extend()");
9118 * "feedkeys()" function
9120 /*ARGSUSED*/
9121 static void
9122 f_feedkeys(argvars, rettv)
9123 typval_T *argvars;
9124 typval_T *rettv;
9126 int remap = TRUE;
9127 char_u *keys, *flags;
9128 char_u nbuf[NUMBUFLEN];
9129 int typed = FALSE;
9130 char_u *keys_esc;
9132 /* This is not allowed in the sandbox. If the commands would still be
9133 * executed in the sandbox it would be OK, but it probably happens later,
9134 * when "sandbox" is no longer set. */
9135 if (check_secure())
9136 return;
9138 rettv->vval.v_number = 0;
9139 keys = get_tv_string(&argvars[0]);
9140 if (*keys != NUL)
9142 if (argvars[1].v_type != VAR_UNKNOWN)
9144 flags = get_tv_string_buf(&argvars[1], nbuf);
9145 for ( ; *flags != NUL; ++flags)
9147 switch (*flags)
9149 case 'n': remap = FALSE; break;
9150 case 'm': remap = TRUE; break;
9151 case 't': typed = TRUE; break;
9156 /* Need to escape K_SPECIAL and CSI before putting the string in the
9157 * typeahead buffer. */
9158 keys_esc = vim_strsave_escape_csi(keys);
9159 if (keys_esc != NULL)
9161 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
9162 typebuf.tb_len, !typed, FALSE);
9163 vim_free(keys_esc);
9164 if (vgetc_busy)
9165 typebuf_was_filled = TRUE;
9171 * "filereadable()" function
9173 static void
9174 f_filereadable(argvars, rettv)
9175 typval_T *argvars;
9176 typval_T *rettv;
9178 FILE *fd;
9179 char_u *p;
9180 int n;
9182 p = get_tv_string(&argvars[0]);
9183 if (*p && !mch_isdir(p) && (fd = mch_fopen((char *)p, "r")) != NULL)
9185 n = TRUE;
9186 fclose(fd);
9188 else
9189 n = FALSE;
9191 rettv->vval.v_number = n;
9195 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
9196 * rights to write into.
9198 static void
9199 f_filewritable(argvars, rettv)
9200 typval_T *argvars;
9201 typval_T *rettv;
9203 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
9206 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int dir));
9208 static void
9209 findfilendir(argvars, rettv, dir)
9210 typval_T *argvars;
9211 typval_T *rettv;
9212 int dir;
9214 #ifdef FEAT_SEARCHPATH
9215 char_u *fname;
9216 char_u *fresult = NULL;
9217 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
9218 char_u *p;
9219 char_u pathbuf[NUMBUFLEN];
9220 int count = 1;
9221 int first = TRUE;
9222 int error = FALSE;
9223 #endif
9225 rettv->vval.v_string = NULL;
9226 rettv->v_type = VAR_STRING;
9228 #ifdef FEAT_SEARCHPATH
9229 fname = get_tv_string(&argvars[0]);
9231 if (argvars[1].v_type != VAR_UNKNOWN)
9233 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
9234 if (p == NULL)
9235 error = TRUE;
9236 else
9238 if (*p != NUL)
9239 path = p;
9241 if (argvars[2].v_type != VAR_UNKNOWN)
9242 count = get_tv_number_chk(&argvars[2], &error);
9246 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
9247 error = TRUE;
9249 if (*fname != NUL && !error)
9253 if (rettv->v_type == VAR_STRING)
9254 vim_free(fresult);
9255 fresult = find_file_in_path_option(first ? fname : NULL,
9256 first ? (int)STRLEN(fname) : 0,
9257 0, first, path, dir, curbuf->b_ffname,
9258 dir ? (char_u *)"" : curbuf->b_p_sua);
9259 first = FALSE;
9261 if (fresult != NULL && rettv->v_type == VAR_LIST)
9262 list_append_string(rettv->vval.v_list, fresult, -1);
9264 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
9267 if (rettv->v_type == VAR_STRING)
9268 rettv->vval.v_string = fresult;
9269 #endif
9272 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
9273 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
9276 * Implementation of map() and filter().
9278 static void
9279 filter_map(argvars, rettv, map)
9280 typval_T *argvars;
9281 typval_T *rettv;
9282 int map;
9284 char_u buf[NUMBUFLEN];
9285 char_u *expr;
9286 listitem_T *li, *nli;
9287 list_T *l = NULL;
9288 dictitem_T *di;
9289 hashtab_T *ht;
9290 hashitem_T *hi;
9291 dict_T *d = NULL;
9292 typval_T save_val;
9293 typval_T save_key;
9294 int rem;
9295 int todo;
9296 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
9297 int save_did_emsg;
9299 rettv->vval.v_number = 0;
9300 if (argvars[0].v_type == VAR_LIST)
9302 if ((l = argvars[0].vval.v_list) == NULL
9303 || (map && tv_check_lock(l->lv_lock, ermsg)))
9304 return;
9306 else if (argvars[0].v_type == VAR_DICT)
9308 if ((d = argvars[0].vval.v_dict) == NULL
9309 || (map && tv_check_lock(d->dv_lock, ermsg)))
9310 return;
9312 else
9314 EMSG2(_(e_listdictarg), ermsg);
9315 return;
9318 expr = get_tv_string_buf_chk(&argvars[1], buf);
9319 /* On type errors, the preceding call has already displayed an error
9320 * message. Avoid a misleading error message for an empty string that
9321 * was not passed as argument. */
9322 if (expr != NULL)
9324 prepare_vimvar(VV_VAL, &save_val);
9325 expr = skipwhite(expr);
9327 /* We reset "did_emsg" to be able to detect whether an error
9328 * occurred during evaluation of the expression. */
9329 save_did_emsg = did_emsg;
9330 did_emsg = FALSE;
9332 if (argvars[0].v_type == VAR_DICT)
9334 prepare_vimvar(VV_KEY, &save_key);
9335 vimvars[VV_KEY].vv_type = VAR_STRING;
9337 ht = &d->dv_hashtab;
9338 hash_lock(ht);
9339 todo = (int)ht->ht_used;
9340 for (hi = ht->ht_array; todo > 0; ++hi)
9342 if (!HASHITEM_EMPTY(hi))
9344 --todo;
9345 di = HI2DI(hi);
9346 if (tv_check_lock(di->di_tv.v_lock, ermsg))
9347 break;
9348 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
9349 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
9350 || did_emsg)
9351 break;
9352 if (!map && rem)
9353 dictitem_remove(d, di);
9354 clear_tv(&vimvars[VV_KEY].vv_tv);
9357 hash_unlock(ht);
9359 restore_vimvar(VV_KEY, &save_key);
9361 else
9363 for (li = l->lv_first; li != NULL; li = nli)
9365 if (tv_check_lock(li->li_tv.v_lock, ermsg))
9366 break;
9367 nli = li->li_next;
9368 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
9369 || did_emsg)
9370 break;
9371 if (!map && rem)
9372 listitem_remove(l, li);
9376 restore_vimvar(VV_VAL, &save_val);
9378 did_emsg |= save_did_emsg;
9381 copy_tv(&argvars[0], rettv);
9384 static int
9385 filter_map_one(tv, expr, map, remp)
9386 typval_T *tv;
9387 char_u *expr;
9388 int map;
9389 int *remp;
9391 typval_T rettv;
9392 char_u *s;
9393 int retval = FAIL;
9395 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
9396 s = expr;
9397 if (eval1(&s, &rettv, TRUE) == FAIL)
9398 goto theend;
9399 if (*s != NUL) /* check for trailing chars after expr */
9401 EMSG2(_(e_invexpr2), s);
9402 goto theend;
9404 if (map)
9406 /* map(): replace the list item value */
9407 clear_tv(tv);
9408 rettv.v_lock = 0;
9409 *tv = rettv;
9411 else
9413 int error = FALSE;
9415 /* filter(): when expr is zero remove the item */
9416 *remp = (get_tv_number_chk(&rettv, &error) == 0);
9417 clear_tv(&rettv);
9418 /* On type error, nothing has been removed; return FAIL to stop the
9419 * loop. The error message was given by get_tv_number_chk(). */
9420 if (error)
9421 goto theend;
9423 retval = OK;
9424 theend:
9425 clear_tv(&vimvars[VV_VAL].vv_tv);
9426 return retval;
9430 * "filter()" function
9432 static void
9433 f_filter(argvars, rettv)
9434 typval_T *argvars;
9435 typval_T *rettv;
9437 filter_map(argvars, rettv, FALSE);
9441 * "finddir({fname}[, {path}[, {count}]])" function
9443 static void
9444 f_finddir(argvars, rettv)
9445 typval_T *argvars;
9446 typval_T *rettv;
9448 findfilendir(argvars, rettv, TRUE);
9452 * "findfile({fname}[, {path}[, {count}]])" function
9454 static void
9455 f_findfile(argvars, rettv)
9456 typval_T *argvars;
9457 typval_T *rettv;
9459 findfilendir(argvars, rettv, FALSE);
9463 * "fnamemodify({fname}, {mods})" function
9465 static void
9466 f_fnamemodify(argvars, rettv)
9467 typval_T *argvars;
9468 typval_T *rettv;
9470 char_u *fname;
9471 char_u *mods;
9472 int usedlen = 0;
9473 int len;
9474 char_u *fbuf = NULL;
9475 char_u buf[NUMBUFLEN];
9477 fname = get_tv_string_chk(&argvars[0]);
9478 mods = get_tv_string_buf_chk(&argvars[1], buf);
9479 if (fname == NULL || mods == NULL)
9480 fname = NULL;
9481 else
9483 len = (int)STRLEN(fname);
9484 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
9487 rettv->v_type = VAR_STRING;
9488 if (fname == NULL)
9489 rettv->vval.v_string = NULL;
9490 else
9491 rettv->vval.v_string = vim_strnsave(fname, len);
9492 vim_free(fbuf);
9495 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
9498 * "foldclosed()" function
9500 static void
9501 foldclosed_both(argvars, rettv, end)
9502 typval_T *argvars;
9503 typval_T *rettv;
9504 int end;
9506 #ifdef FEAT_FOLDING
9507 linenr_T lnum;
9508 linenr_T first, last;
9510 lnum = get_tv_lnum(argvars);
9511 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9513 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
9515 if (end)
9516 rettv->vval.v_number = (varnumber_T)last;
9517 else
9518 rettv->vval.v_number = (varnumber_T)first;
9519 return;
9522 #endif
9523 rettv->vval.v_number = -1;
9527 * "foldclosed()" function
9529 static void
9530 f_foldclosed(argvars, rettv)
9531 typval_T *argvars;
9532 typval_T *rettv;
9534 foldclosed_both(argvars, rettv, FALSE);
9538 * "foldclosedend()" function
9540 static void
9541 f_foldclosedend(argvars, rettv)
9542 typval_T *argvars;
9543 typval_T *rettv;
9545 foldclosed_both(argvars, rettv, TRUE);
9549 * "foldlevel()" function
9551 static void
9552 f_foldlevel(argvars, rettv)
9553 typval_T *argvars;
9554 typval_T *rettv;
9556 #ifdef FEAT_FOLDING
9557 linenr_T lnum;
9559 lnum = get_tv_lnum(argvars);
9560 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9561 rettv->vval.v_number = foldLevel(lnum);
9562 else
9563 #endif
9564 rettv->vval.v_number = 0;
9568 * "foldtext()" function
9570 /*ARGSUSED*/
9571 static void
9572 f_foldtext(argvars, rettv)
9573 typval_T *argvars;
9574 typval_T *rettv;
9576 #ifdef FEAT_FOLDING
9577 linenr_T lnum;
9578 char_u *s;
9579 char_u *r;
9580 int len;
9581 char *txt;
9582 #endif
9584 rettv->v_type = VAR_STRING;
9585 rettv->vval.v_string = NULL;
9586 #ifdef FEAT_FOLDING
9587 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
9588 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
9589 <= curbuf->b_ml.ml_line_count
9590 && vimvars[VV_FOLDDASHES].vv_str != NULL)
9592 /* Find first non-empty line in the fold. */
9593 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
9594 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
9596 if (!linewhite(lnum))
9597 break;
9598 ++lnum;
9601 /* Find interesting text in this line. */
9602 s = skipwhite(ml_get(lnum));
9603 /* skip C comment-start */
9604 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
9606 s = skipwhite(s + 2);
9607 if (*skipwhite(s) == NUL
9608 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
9610 s = skipwhite(ml_get(lnum + 1));
9611 if (*s == '*')
9612 s = skipwhite(s + 1);
9615 txt = _("+-%s%3ld lines: ");
9616 r = alloc((unsigned)(STRLEN(txt)
9617 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
9618 + 20 /* for %3ld */
9619 + STRLEN(s))); /* concatenated */
9620 if (r != NULL)
9622 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
9623 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
9624 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
9625 len = (int)STRLEN(r);
9626 STRCAT(r, s);
9627 /* remove 'foldmarker' and 'commentstring' */
9628 foldtext_cleanup(r + len);
9629 rettv->vval.v_string = r;
9632 #endif
9636 * "foldtextresult(lnum)" function
9638 /*ARGSUSED*/
9639 static void
9640 f_foldtextresult(argvars, rettv)
9641 typval_T *argvars;
9642 typval_T *rettv;
9644 #ifdef FEAT_FOLDING
9645 linenr_T lnum;
9646 char_u *text;
9647 char_u buf[51];
9648 foldinfo_T foldinfo;
9649 int fold_count;
9650 #endif
9652 rettv->v_type = VAR_STRING;
9653 rettv->vval.v_string = NULL;
9654 #ifdef FEAT_FOLDING
9655 lnum = get_tv_lnum(argvars);
9656 /* treat illegal types and illegal string values for {lnum} the same */
9657 if (lnum < 0)
9658 lnum = 0;
9659 fold_count = foldedCount(curwin, lnum, &foldinfo);
9660 if (fold_count > 0)
9662 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
9663 &foldinfo, buf);
9664 if (text == buf)
9665 text = vim_strsave(text);
9666 rettv->vval.v_string = text;
9668 #endif
9672 * "foreground()" function
9674 /*ARGSUSED*/
9675 static void
9676 f_foreground(argvars, rettv)
9677 typval_T *argvars;
9678 typval_T *rettv;
9680 rettv->vval.v_number = 0;
9681 #ifdef FEAT_GUI
9682 if (gui.in_use)
9683 gui_mch_set_foreground();
9684 #else
9685 # ifdef WIN32
9686 win32_set_foreground();
9687 # endif
9688 #endif
9692 * "function()" function
9694 /*ARGSUSED*/
9695 static void
9696 f_function(argvars, rettv)
9697 typval_T *argvars;
9698 typval_T *rettv;
9700 char_u *s;
9702 rettv->vval.v_number = 0;
9703 s = get_tv_string(&argvars[0]);
9704 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
9705 EMSG2(_(e_invarg2), s);
9706 else if (!function_exists(s))
9707 EMSG2(_("E700: Unknown function: %s"), s);
9708 else
9710 rettv->vval.v_string = vim_strsave(s);
9711 rettv->v_type = VAR_FUNC;
9716 * "garbagecollect()" function
9718 /*ARGSUSED*/
9719 static void
9720 f_garbagecollect(argvars, rettv)
9721 typval_T *argvars;
9722 typval_T *rettv;
9724 /* This is postponed until we are back at the toplevel, because we may be
9725 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
9726 want_garbage_collect = TRUE;
9728 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
9729 garbage_collect_at_exit = TRUE;
9733 * "get()" function
9735 static void
9736 f_get(argvars, rettv)
9737 typval_T *argvars;
9738 typval_T *rettv;
9740 listitem_T *li;
9741 list_T *l;
9742 dictitem_T *di;
9743 dict_T *d;
9744 typval_T *tv = NULL;
9746 if (argvars[0].v_type == VAR_LIST)
9748 if ((l = argvars[0].vval.v_list) != NULL)
9750 int error = FALSE;
9752 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
9753 if (!error && li != NULL)
9754 tv = &li->li_tv;
9757 else if (argvars[0].v_type == VAR_DICT)
9759 if ((d = argvars[0].vval.v_dict) != NULL)
9761 di = dict_find(d, get_tv_string(&argvars[1]), -1);
9762 if (di != NULL)
9763 tv = &di->di_tv;
9766 else
9767 EMSG2(_(e_listdictarg), "get()");
9769 if (tv == NULL)
9771 if (argvars[2].v_type == VAR_UNKNOWN)
9772 rettv->vval.v_number = 0;
9773 else
9774 copy_tv(&argvars[2], rettv);
9776 else
9777 copy_tv(tv, rettv);
9780 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
9783 * Get line or list of lines from buffer "buf" into "rettv".
9784 * Return a range (from start to end) of lines in rettv from the specified
9785 * buffer.
9786 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
9788 static void
9789 get_buffer_lines(buf, start, end, retlist, rettv)
9790 buf_T *buf;
9791 linenr_T start;
9792 linenr_T end;
9793 int retlist;
9794 typval_T *rettv;
9796 char_u *p;
9798 if (retlist)
9800 if (rettv_list_alloc(rettv) == FAIL)
9801 return;
9803 else
9804 rettv->vval.v_number = 0;
9806 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
9807 return;
9809 if (!retlist)
9811 if (start >= 1 && start <= buf->b_ml.ml_line_count)
9812 p = ml_get_buf(buf, start, FALSE);
9813 else
9814 p = (char_u *)"";
9816 rettv->v_type = VAR_STRING;
9817 rettv->vval.v_string = vim_strsave(p);
9819 else
9821 if (end < start)
9822 return;
9824 if (start < 1)
9825 start = 1;
9826 if (end > buf->b_ml.ml_line_count)
9827 end = buf->b_ml.ml_line_count;
9828 while (start <= end)
9829 if (list_append_string(rettv->vval.v_list,
9830 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
9831 break;
9836 * "getbufline()" function
9838 static void
9839 f_getbufline(argvars, rettv)
9840 typval_T *argvars;
9841 typval_T *rettv;
9843 linenr_T lnum;
9844 linenr_T end;
9845 buf_T *buf;
9847 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
9848 ++emsg_off;
9849 buf = get_buf_tv(&argvars[0]);
9850 --emsg_off;
9852 lnum = get_tv_lnum_buf(&argvars[1], buf);
9853 if (argvars[2].v_type == VAR_UNKNOWN)
9854 end = lnum;
9855 else
9856 end = get_tv_lnum_buf(&argvars[2], buf);
9858 get_buffer_lines(buf, lnum, end, TRUE, rettv);
9862 * "getbufvar()" function
9864 static void
9865 f_getbufvar(argvars, rettv)
9866 typval_T *argvars;
9867 typval_T *rettv;
9869 buf_T *buf;
9870 buf_T *save_curbuf;
9871 char_u *varname;
9872 dictitem_T *v;
9874 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
9875 varname = get_tv_string_chk(&argvars[1]);
9876 ++emsg_off;
9877 buf = get_buf_tv(&argvars[0]);
9879 rettv->v_type = VAR_STRING;
9880 rettv->vval.v_string = NULL;
9882 if (buf != NULL && varname != NULL)
9884 if (*varname == '&') /* buffer-local-option */
9886 /* set curbuf to be our buf, temporarily */
9887 save_curbuf = curbuf;
9888 curbuf = buf;
9890 get_option_tv(&varname, rettv, TRUE);
9892 /* restore previous notion of curbuf */
9893 curbuf = save_curbuf;
9895 else
9897 if (*varname == NUL)
9898 /* let getbufvar({nr}, "") return the "b:" dictionary. The
9899 * scope prefix before the NUL byte is required by
9900 * find_var_in_ht(). */
9901 varname = (char_u *)"b:" + 2;
9902 /* look up the variable */
9903 v = find_var_in_ht(&buf->b_vars.dv_hashtab, varname, FALSE);
9904 if (v != NULL)
9905 copy_tv(&v->di_tv, rettv);
9909 --emsg_off;
9913 * "getchar()" function
9915 static void
9916 f_getchar(argvars, rettv)
9917 typval_T *argvars;
9918 typval_T *rettv;
9920 varnumber_T n;
9921 int error = FALSE;
9923 /* Position the cursor. Needed after a message that ends in a space. */
9924 windgoto(msg_row, msg_col);
9926 ++no_mapping;
9927 ++allow_keys;
9928 for (;;)
9930 if (argvars[0].v_type == VAR_UNKNOWN)
9931 /* getchar(): blocking wait. */
9932 n = safe_vgetc();
9933 else if (get_tv_number_chk(&argvars[0], &error) == 1)
9934 /* getchar(1): only check if char avail */
9935 n = vpeekc();
9936 else if (error || vpeekc() == NUL)
9937 /* illegal argument or getchar(0) and no char avail: return zero */
9938 n = 0;
9939 else
9940 /* getchar(0) and char avail: return char */
9941 n = safe_vgetc();
9942 if (n == K_IGNORE)
9943 continue;
9944 break;
9946 --no_mapping;
9947 --allow_keys;
9949 vimvars[VV_MOUSE_WIN].vv_nr = 0;
9950 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
9951 vimvars[VV_MOUSE_COL].vv_nr = 0;
9953 rettv->vval.v_number = n;
9954 if (IS_SPECIAL(n) || mod_mask != 0)
9956 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
9957 int i = 0;
9959 /* Turn a special key into three bytes, plus modifier. */
9960 if (mod_mask != 0)
9962 temp[i++] = K_SPECIAL;
9963 temp[i++] = KS_MODIFIER;
9964 temp[i++] = mod_mask;
9966 if (IS_SPECIAL(n))
9968 temp[i++] = K_SPECIAL;
9969 temp[i++] = K_SECOND(n);
9970 temp[i++] = K_THIRD(n);
9972 #ifdef FEAT_MBYTE
9973 else if (has_mbyte)
9974 i += (*mb_char2bytes)(n, temp + i);
9975 #endif
9976 else
9977 temp[i++] = n;
9978 temp[i++] = NUL;
9979 rettv->v_type = VAR_STRING;
9980 rettv->vval.v_string = vim_strsave(temp);
9982 #ifdef FEAT_MOUSE
9983 if (n == K_LEFTMOUSE
9984 || n == K_LEFTMOUSE_NM
9985 || n == K_LEFTDRAG
9986 || n == K_LEFTRELEASE
9987 || n == K_LEFTRELEASE_NM
9988 || n == K_MIDDLEMOUSE
9989 || n == K_MIDDLEDRAG
9990 || n == K_MIDDLERELEASE
9991 || n == K_RIGHTMOUSE
9992 || n == K_RIGHTDRAG
9993 || n == K_RIGHTRELEASE
9994 || n == K_X1MOUSE
9995 || n == K_X1DRAG
9996 || n == K_X1RELEASE
9997 || n == K_X2MOUSE
9998 || n == K_X2DRAG
9999 || n == K_X2RELEASE
10000 || n == K_MOUSEDOWN
10001 || n == K_MOUSEUP)
10003 int row = mouse_row;
10004 int col = mouse_col;
10005 win_T *win;
10006 linenr_T lnum;
10007 # ifdef FEAT_WINDOWS
10008 win_T *wp;
10009 # endif
10010 int n = 1;
10012 if (row >= 0 && col >= 0)
10014 /* Find the window at the mouse coordinates and compute the
10015 * text position. */
10016 win = mouse_find_win(&row, &col);
10017 (void)mouse_comp_pos(win, &row, &col, &lnum);
10018 # ifdef FEAT_WINDOWS
10019 for (wp = firstwin; wp != win; wp = wp->w_next)
10020 ++n;
10021 # endif
10022 vimvars[VV_MOUSE_WIN].vv_nr = n;
10023 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
10024 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
10027 #endif
10032 * "getcharmod()" function
10034 /*ARGSUSED*/
10035 static void
10036 f_getcharmod(argvars, rettv)
10037 typval_T *argvars;
10038 typval_T *rettv;
10040 rettv->vval.v_number = mod_mask;
10044 * "getcmdline()" function
10046 /*ARGSUSED*/
10047 static void
10048 f_getcmdline(argvars, rettv)
10049 typval_T *argvars;
10050 typval_T *rettv;
10052 rettv->v_type = VAR_STRING;
10053 rettv->vval.v_string = get_cmdline_str();
10057 * "getcmdpos()" function
10059 /*ARGSUSED*/
10060 static void
10061 f_getcmdpos(argvars, rettv)
10062 typval_T *argvars;
10063 typval_T *rettv;
10065 rettv->vval.v_number = get_cmdline_pos() + 1;
10069 * "getcmdtype()" function
10071 /*ARGSUSED*/
10072 static void
10073 f_getcmdtype(argvars, rettv)
10074 typval_T *argvars;
10075 typval_T *rettv;
10077 rettv->v_type = VAR_STRING;
10078 rettv->vval.v_string = alloc(2);
10079 if (rettv->vval.v_string != NULL)
10081 rettv->vval.v_string[0] = get_cmdline_type();
10082 rettv->vval.v_string[1] = NUL;
10087 * "getcwd()" function
10089 /*ARGSUSED*/
10090 static void
10091 f_getcwd(argvars, rettv)
10092 typval_T *argvars;
10093 typval_T *rettv;
10095 char_u cwd[MAXPATHL];
10097 rettv->v_type = VAR_STRING;
10098 if (mch_dirname(cwd, MAXPATHL) == FAIL)
10099 rettv->vval.v_string = NULL;
10100 else
10102 rettv->vval.v_string = vim_strsave(cwd);
10103 #ifdef BACKSLASH_IN_FILENAME
10104 if (rettv->vval.v_string != NULL)
10105 slash_adjust(rettv->vval.v_string);
10106 #endif
10111 * "getfontname()" function
10113 /*ARGSUSED*/
10114 static void
10115 f_getfontname(argvars, rettv)
10116 typval_T *argvars;
10117 typval_T *rettv;
10119 rettv->v_type = VAR_STRING;
10120 rettv->vval.v_string = NULL;
10121 #ifdef FEAT_GUI
10122 if (gui.in_use)
10124 GuiFont font;
10125 char_u *name = NULL;
10127 if (argvars[0].v_type == VAR_UNKNOWN)
10129 /* Get the "Normal" font. Either the name saved by
10130 * hl_set_font_name() or from the font ID. */
10131 font = gui.norm_font;
10132 name = hl_get_font_name();
10134 else
10136 name = get_tv_string(&argvars[0]);
10137 if (STRCMP(name, "*") == 0) /* don't use font dialog */
10138 return;
10139 font = gui_mch_get_font(name, FALSE);
10140 if (font == NOFONT)
10141 return; /* Invalid font name, return empty string. */
10143 rettv->vval.v_string = gui_mch_get_fontname(font, name);
10144 if (argvars[0].v_type != VAR_UNKNOWN)
10145 gui_mch_free_font(font);
10147 #endif
10151 * "getfperm({fname})" function
10153 static void
10154 f_getfperm(argvars, rettv)
10155 typval_T *argvars;
10156 typval_T *rettv;
10158 char_u *fname;
10159 struct stat st;
10160 char_u *perm = NULL;
10161 char_u flags[] = "rwx";
10162 int i;
10164 fname = get_tv_string(&argvars[0]);
10166 rettv->v_type = VAR_STRING;
10167 if (mch_stat((char *)fname, &st) >= 0)
10169 perm = vim_strsave((char_u *)"---------");
10170 if (perm != NULL)
10172 for (i = 0; i < 9; i++)
10174 if (st.st_mode & (1 << (8 - i)))
10175 perm[i] = flags[i % 3];
10179 rettv->vval.v_string = perm;
10183 * "getfsize({fname})" function
10185 static void
10186 f_getfsize(argvars, rettv)
10187 typval_T *argvars;
10188 typval_T *rettv;
10190 char_u *fname;
10191 struct stat st;
10193 fname = get_tv_string(&argvars[0]);
10195 rettv->v_type = VAR_NUMBER;
10197 if (mch_stat((char *)fname, &st) >= 0)
10199 if (mch_isdir(fname))
10200 rettv->vval.v_number = 0;
10201 else
10203 rettv->vval.v_number = (varnumber_T)st.st_size;
10205 /* non-perfect check for overflow */
10206 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
10207 rettv->vval.v_number = -2;
10210 else
10211 rettv->vval.v_number = -1;
10215 * "getftime({fname})" function
10217 static void
10218 f_getftime(argvars, rettv)
10219 typval_T *argvars;
10220 typval_T *rettv;
10222 char_u *fname;
10223 struct stat st;
10225 fname = get_tv_string(&argvars[0]);
10227 if (mch_stat((char *)fname, &st) >= 0)
10228 rettv->vval.v_number = (varnumber_T)st.st_mtime;
10229 else
10230 rettv->vval.v_number = -1;
10234 * "getftype({fname})" function
10236 static void
10237 f_getftype(argvars, rettv)
10238 typval_T *argvars;
10239 typval_T *rettv;
10241 char_u *fname;
10242 struct stat st;
10243 char_u *type = NULL;
10244 char *t;
10246 fname = get_tv_string(&argvars[0]);
10248 rettv->v_type = VAR_STRING;
10249 if (mch_lstat((char *)fname, &st) >= 0)
10251 #ifdef S_ISREG
10252 if (S_ISREG(st.st_mode))
10253 t = "file";
10254 else if (S_ISDIR(st.st_mode))
10255 t = "dir";
10256 # ifdef S_ISLNK
10257 else if (S_ISLNK(st.st_mode))
10258 t = "link";
10259 # endif
10260 # ifdef S_ISBLK
10261 else if (S_ISBLK(st.st_mode))
10262 t = "bdev";
10263 # endif
10264 # ifdef S_ISCHR
10265 else if (S_ISCHR(st.st_mode))
10266 t = "cdev";
10267 # endif
10268 # ifdef S_ISFIFO
10269 else if (S_ISFIFO(st.st_mode))
10270 t = "fifo";
10271 # endif
10272 # ifdef S_ISSOCK
10273 else if (S_ISSOCK(st.st_mode))
10274 t = "fifo";
10275 # endif
10276 else
10277 t = "other";
10278 #else
10279 # ifdef S_IFMT
10280 switch (st.st_mode & S_IFMT)
10282 case S_IFREG: t = "file"; break;
10283 case S_IFDIR: t = "dir"; break;
10284 # ifdef S_IFLNK
10285 case S_IFLNK: t = "link"; break;
10286 # endif
10287 # ifdef S_IFBLK
10288 case S_IFBLK: t = "bdev"; break;
10289 # endif
10290 # ifdef S_IFCHR
10291 case S_IFCHR: t = "cdev"; break;
10292 # endif
10293 # ifdef S_IFIFO
10294 case S_IFIFO: t = "fifo"; break;
10295 # endif
10296 # ifdef S_IFSOCK
10297 case S_IFSOCK: t = "socket"; break;
10298 # endif
10299 default: t = "other";
10301 # else
10302 if (mch_isdir(fname))
10303 t = "dir";
10304 else
10305 t = "file";
10306 # endif
10307 #endif
10308 type = vim_strsave((char_u *)t);
10310 rettv->vval.v_string = type;
10314 * "getline(lnum, [end])" function
10316 static void
10317 f_getline(argvars, rettv)
10318 typval_T *argvars;
10319 typval_T *rettv;
10321 linenr_T lnum;
10322 linenr_T end;
10323 int retlist;
10325 lnum = get_tv_lnum(argvars);
10326 if (argvars[1].v_type == VAR_UNKNOWN)
10328 end = 0;
10329 retlist = FALSE;
10331 else
10333 end = get_tv_lnum(&argvars[1]);
10334 retlist = TRUE;
10337 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
10341 * "getmatches()" function
10343 /*ARGSUSED*/
10344 static void
10345 f_getmatches(argvars, rettv)
10346 typval_T *argvars;
10347 typval_T *rettv;
10349 #ifdef FEAT_SEARCH_EXTRA
10350 dict_T *dict;
10351 matchitem_T *cur = curwin->w_match_head;
10353 rettv->vval.v_number = 0;
10355 if (rettv_list_alloc(rettv) == OK)
10357 while (cur != NULL)
10359 dict = dict_alloc();
10360 if (dict == NULL)
10361 return;
10362 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
10363 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
10364 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
10365 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
10366 list_append_dict(rettv->vval.v_list, dict);
10367 cur = cur->next;
10370 #endif
10374 * "getpos(string)" function
10376 static void
10377 f_getpos(argvars, rettv)
10378 typval_T *argvars;
10379 typval_T *rettv;
10381 pos_T *fp;
10382 list_T *l;
10383 int fnum = -1;
10385 if (rettv_list_alloc(rettv) == OK)
10387 l = rettv->vval.v_list;
10388 fp = var2fpos(&argvars[0], TRUE, &fnum);
10389 if (fnum != -1)
10390 list_append_number(l, (varnumber_T)fnum);
10391 else
10392 list_append_number(l, (varnumber_T)0);
10393 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
10394 : (varnumber_T)0);
10395 list_append_number(l, (fp != NULL)
10396 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
10397 : (varnumber_T)0);
10398 list_append_number(l,
10399 #ifdef FEAT_VIRTUALEDIT
10400 (fp != NULL) ? (varnumber_T)fp->coladd :
10401 #endif
10402 (varnumber_T)0);
10404 else
10405 rettv->vval.v_number = FALSE;
10409 * "getqflist()" and "getloclist()" functions
10411 /*ARGSUSED*/
10412 static void
10413 f_getqflist(argvars, rettv)
10414 typval_T *argvars;
10415 typval_T *rettv;
10417 #ifdef FEAT_QUICKFIX
10418 win_T *wp;
10419 #endif
10421 rettv->vval.v_number = 0;
10422 #ifdef FEAT_QUICKFIX
10423 if (rettv_list_alloc(rettv) == OK)
10425 wp = NULL;
10426 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
10428 wp = find_win_by_nr(&argvars[0], NULL);
10429 if (wp == NULL)
10430 return;
10433 (void)get_errorlist(wp, rettv->vval.v_list);
10435 #endif
10439 * "getreg()" function
10441 static void
10442 f_getreg(argvars, rettv)
10443 typval_T *argvars;
10444 typval_T *rettv;
10446 char_u *strregname;
10447 int regname;
10448 int arg2 = FALSE;
10449 int error = FALSE;
10451 if (argvars[0].v_type != VAR_UNKNOWN)
10453 strregname = get_tv_string_chk(&argvars[0]);
10454 error = strregname == NULL;
10455 if (argvars[1].v_type != VAR_UNKNOWN)
10456 arg2 = get_tv_number_chk(&argvars[1], &error);
10458 else
10459 strregname = vimvars[VV_REG].vv_str;
10460 regname = (strregname == NULL ? '"' : *strregname);
10461 if (regname == 0)
10462 regname = '"';
10464 rettv->v_type = VAR_STRING;
10465 rettv->vval.v_string = error ? NULL :
10466 get_reg_contents(regname, TRUE, arg2);
10470 * "getregtype()" function
10472 static void
10473 f_getregtype(argvars, rettv)
10474 typval_T *argvars;
10475 typval_T *rettv;
10477 char_u *strregname;
10478 int regname;
10479 char_u buf[NUMBUFLEN + 2];
10480 long reglen = 0;
10482 if (argvars[0].v_type != VAR_UNKNOWN)
10484 strregname = get_tv_string_chk(&argvars[0]);
10485 if (strregname == NULL) /* type error; errmsg already given */
10487 rettv->v_type = VAR_STRING;
10488 rettv->vval.v_string = NULL;
10489 return;
10492 else
10493 /* Default to v:register */
10494 strregname = vimvars[VV_REG].vv_str;
10496 regname = (strregname == NULL ? '"' : *strregname);
10497 if (regname == 0)
10498 regname = '"';
10500 buf[0] = NUL;
10501 buf[1] = NUL;
10502 switch (get_reg_type(regname, &reglen))
10504 case MLINE: buf[0] = 'V'; break;
10505 case MCHAR: buf[0] = 'v'; break;
10506 #ifdef FEAT_VISUAL
10507 case MBLOCK:
10508 buf[0] = Ctrl_V;
10509 sprintf((char *)buf + 1, "%ld", reglen + 1);
10510 break;
10511 #endif
10513 rettv->v_type = VAR_STRING;
10514 rettv->vval.v_string = vim_strsave(buf);
10518 * "gettabwinvar()" function
10520 static void
10521 f_gettabwinvar(argvars, rettv)
10522 typval_T *argvars;
10523 typval_T *rettv;
10525 getwinvar(argvars, rettv, 1);
10529 * "getwinposx()" function
10531 /*ARGSUSED*/
10532 static void
10533 f_getwinposx(argvars, rettv)
10534 typval_T *argvars;
10535 typval_T *rettv;
10537 rettv->vval.v_number = -1;
10538 #ifdef FEAT_GUI
10539 if (gui.in_use)
10541 int x, y;
10543 if (gui_mch_get_winpos(&x, &y) == OK)
10544 rettv->vval.v_number = x;
10546 #endif
10550 * "getwinposy()" function
10552 /*ARGSUSED*/
10553 static void
10554 f_getwinposy(argvars, rettv)
10555 typval_T *argvars;
10556 typval_T *rettv;
10558 rettv->vval.v_number = -1;
10559 #ifdef FEAT_GUI
10560 if (gui.in_use)
10562 int x, y;
10564 if (gui_mch_get_winpos(&x, &y) == OK)
10565 rettv->vval.v_number = y;
10567 #endif
10571 * Find window specifed by "vp" in tabpage "tp".
10573 static win_T *
10574 find_win_by_nr(vp, tp)
10575 typval_T *vp;
10576 tabpage_T *tp; /* NULL for current tab page */
10578 #ifdef FEAT_WINDOWS
10579 win_T *wp;
10580 #endif
10581 int nr;
10583 nr = get_tv_number_chk(vp, NULL);
10585 #ifdef FEAT_WINDOWS
10586 if (nr < 0)
10587 return NULL;
10588 if (nr == 0)
10589 return curwin;
10591 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
10592 wp != NULL; wp = wp->w_next)
10593 if (--nr <= 0)
10594 break;
10595 return wp;
10596 #else
10597 if (nr == 0 || nr == 1)
10598 return curwin;
10599 return NULL;
10600 #endif
10604 * "getwinvar()" function
10606 static void
10607 f_getwinvar(argvars, rettv)
10608 typval_T *argvars;
10609 typval_T *rettv;
10611 getwinvar(argvars, rettv, 0);
10615 * getwinvar() and gettabwinvar()
10617 static void
10618 getwinvar(argvars, rettv, off)
10619 typval_T *argvars;
10620 typval_T *rettv;
10621 int off; /* 1 for gettabwinvar() */
10623 win_T *win, *oldcurwin;
10624 char_u *varname;
10625 dictitem_T *v;
10626 tabpage_T *tp;
10628 #ifdef FEAT_WINDOWS
10629 if (off == 1)
10630 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
10631 else
10632 tp = curtab;
10633 #endif
10634 win = find_win_by_nr(&argvars[off], tp);
10635 varname = get_tv_string_chk(&argvars[off + 1]);
10636 ++emsg_off;
10638 rettv->v_type = VAR_STRING;
10639 rettv->vval.v_string = NULL;
10641 if (win != NULL && varname != NULL)
10643 /* Set curwin to be our win, temporarily. Also set curbuf, so
10644 * that we can get buffer-local options. */
10645 oldcurwin = curwin;
10646 curwin = win;
10647 curbuf = win->w_buffer;
10649 if (*varname == '&') /* window-local-option */
10650 get_option_tv(&varname, rettv, 1);
10651 else
10653 if (*varname == NUL)
10654 /* let getwinvar({nr}, "") return the "w:" dictionary. The
10655 * scope prefix before the NUL byte is required by
10656 * find_var_in_ht(). */
10657 varname = (char_u *)"w:" + 2;
10658 /* look up the variable */
10659 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
10660 if (v != NULL)
10661 copy_tv(&v->di_tv, rettv);
10664 /* restore previous notion of curwin */
10665 curwin = oldcurwin;
10666 curbuf = curwin->w_buffer;
10669 --emsg_off;
10673 * "glob()" function
10675 static void
10676 f_glob(argvars, rettv)
10677 typval_T *argvars;
10678 typval_T *rettv;
10680 expand_T xpc;
10682 ExpandInit(&xpc);
10683 xpc.xp_context = EXPAND_FILES;
10684 rettv->v_type = VAR_STRING;
10685 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
10686 NULL, WILD_USE_NL|WILD_SILENT, WILD_ALL);
10690 * "globpath()" function
10692 static void
10693 f_globpath(argvars, rettv)
10694 typval_T *argvars;
10695 typval_T *rettv;
10697 char_u buf1[NUMBUFLEN];
10698 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
10700 rettv->v_type = VAR_STRING;
10701 if (file == NULL)
10702 rettv->vval.v_string = NULL;
10703 else
10704 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file);
10708 * "has()" function
10710 static void
10711 f_has(argvars, rettv)
10712 typval_T *argvars;
10713 typval_T *rettv;
10715 int i;
10716 char_u *name;
10717 int n = FALSE;
10718 static char *(has_list[]) =
10720 #ifdef AMIGA
10721 "amiga",
10722 # ifdef FEAT_ARP
10723 "arp",
10724 # endif
10725 #endif
10726 #ifdef __BEOS__
10727 "beos",
10728 #endif
10729 #ifdef MSDOS
10730 # ifdef DJGPP
10731 "dos32",
10732 # else
10733 "dos16",
10734 # endif
10735 #endif
10736 #ifdef MACOS
10737 "mac",
10738 #endif
10739 #if defined(MACOS_X_UNIX)
10740 "macunix",
10741 #endif
10742 #ifdef OS2
10743 "os2",
10744 #endif
10745 #ifdef __QNX__
10746 "qnx",
10747 #endif
10748 #ifdef RISCOS
10749 "riscos",
10750 #endif
10751 #ifdef UNIX
10752 "unix",
10753 #endif
10754 #ifdef VMS
10755 "vms",
10756 #endif
10757 #ifdef WIN16
10758 "win16",
10759 #endif
10760 #ifdef WIN32
10761 "win32",
10762 #endif
10763 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
10764 "win32unix",
10765 #endif
10766 #ifdef WIN64
10767 "win64",
10768 #endif
10769 #ifdef EBCDIC
10770 "ebcdic",
10771 #endif
10772 #ifndef CASE_INSENSITIVE_FILENAME
10773 "fname_case",
10774 #endif
10775 #ifdef FEAT_ARABIC
10776 "arabic",
10777 #endif
10778 #ifdef FEAT_AUTOCMD
10779 "autocmd",
10780 #endif
10781 #ifdef FEAT_BEVAL
10782 "balloon_eval",
10783 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
10784 "balloon_multiline",
10785 # endif
10786 #endif
10787 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
10788 "builtin_terms",
10789 # ifdef ALL_BUILTIN_TCAPS
10790 "all_builtin_terms",
10791 # endif
10792 #endif
10793 #ifdef FEAT_BYTEOFF
10794 "byte_offset",
10795 #endif
10796 #ifdef FEAT_CINDENT
10797 "cindent",
10798 #endif
10799 #ifdef FEAT_CLIENTSERVER
10800 "clientserver",
10801 #endif
10802 #ifdef FEAT_CLIPBOARD
10803 "clipboard",
10804 #endif
10805 #ifdef FEAT_CMDL_COMPL
10806 "cmdline_compl",
10807 #endif
10808 #ifdef FEAT_CMDHIST
10809 "cmdline_hist",
10810 #endif
10811 #ifdef FEAT_COMMENTS
10812 "comments",
10813 #endif
10814 #ifdef FEAT_CRYPT
10815 "cryptv",
10816 #endif
10817 #ifdef FEAT_CSCOPE
10818 "cscope",
10819 #endif
10820 #ifdef CURSOR_SHAPE
10821 "cursorshape",
10822 #endif
10823 #ifdef DEBUG
10824 "debug",
10825 #endif
10826 #ifdef FEAT_CON_DIALOG
10827 "dialog_con",
10828 #endif
10829 #ifdef FEAT_GUI_DIALOG
10830 "dialog_gui",
10831 #endif
10832 #ifdef FEAT_DIFF
10833 "diff",
10834 #endif
10835 #ifdef FEAT_DIGRAPHS
10836 "digraphs",
10837 #endif
10838 #ifdef FEAT_DND
10839 "dnd",
10840 #endif
10841 #ifdef FEAT_EMACS_TAGS
10842 "emacs_tags",
10843 #endif
10844 "eval", /* always present, of course! */
10845 #ifdef FEAT_EX_EXTRA
10846 "ex_extra",
10847 #endif
10848 #ifdef FEAT_SEARCH_EXTRA
10849 "extra_search",
10850 #endif
10851 #ifdef FEAT_FKMAP
10852 "farsi",
10853 #endif
10854 #ifdef FEAT_SEARCHPATH
10855 "file_in_path",
10856 #endif
10857 #if defined(UNIX) && !defined(USE_SYSTEM)
10858 "filterpipe",
10859 #endif
10860 #ifdef FEAT_FIND_ID
10861 "find_in_path",
10862 #endif
10863 #ifdef FEAT_FOLDING
10864 "folding",
10865 #endif
10866 #ifdef FEAT_FOOTER
10867 "footer",
10868 #endif
10869 #if !defined(USE_SYSTEM) && defined(UNIX)
10870 "fork",
10871 #endif
10872 #ifdef FEAT_FULLSCREEN
10873 "fullscreen",
10874 #endif
10875 #ifdef FEAT_GETTEXT
10876 "gettext",
10877 #endif
10878 #ifdef FEAT_GUI
10879 "gui",
10880 #endif
10881 #ifdef FEAT_GUI_ATHENA
10882 # ifdef FEAT_GUI_NEXTAW
10883 "gui_neXtaw",
10884 # else
10885 "gui_athena",
10886 # endif
10887 #endif
10888 #ifdef FEAT_GUI_GTK
10889 "gui_gtk",
10890 # ifdef HAVE_GTK2
10891 "gui_gtk2",
10892 # endif
10893 #endif
10894 #ifdef FEAT_GUI_GNOME
10895 "gui_gnome",
10896 #endif
10897 #ifdef FEAT_GUI_MAC
10898 "gui_mac",
10899 #endif
10900 #ifdef FEAT_GUI_MACVIM
10901 "gui_macvim",
10902 #endif
10903 #ifdef FEAT_GUI_MOTIF
10904 "gui_motif",
10905 #endif
10906 #ifdef FEAT_GUI_PHOTON
10907 "gui_photon",
10908 #endif
10909 #ifdef FEAT_GUI_W16
10910 "gui_win16",
10911 #endif
10912 #ifdef FEAT_GUI_W32
10913 "gui_win32",
10914 #endif
10915 #ifdef FEAT_HANGULIN
10916 "hangul_input",
10917 #endif
10918 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
10919 "iconv",
10920 #endif
10921 #ifdef FEAT_INS_EXPAND
10922 "insert_expand",
10923 #endif
10924 #ifdef FEAT_JUMPLIST
10925 "jumplist",
10926 #endif
10927 #ifdef FEAT_KEYMAP
10928 "keymap",
10929 #endif
10930 #ifdef FEAT_LANGMAP
10931 "langmap",
10932 #endif
10933 #ifdef FEAT_LIBCALL
10934 "libcall",
10935 #endif
10936 #ifdef FEAT_LINEBREAK
10937 "linebreak",
10938 #endif
10939 #ifdef FEAT_LISP
10940 "lispindent",
10941 #endif
10942 #ifdef FEAT_LISTCMDS
10943 "listcmds",
10944 #endif
10945 #ifdef FEAT_LOCALMAP
10946 "localmap",
10947 #endif
10948 #ifdef FEAT_MENU
10949 "menu",
10950 #endif
10951 #ifdef FEAT_SESSION
10952 "mksession",
10953 #endif
10954 #ifdef FEAT_MODIFY_FNAME
10955 "modify_fname",
10956 #endif
10957 #ifdef FEAT_MOUSE
10958 "mouse",
10959 #endif
10960 #ifdef FEAT_MOUSESHAPE
10961 "mouseshape",
10962 #endif
10963 #if defined(UNIX) || defined(VMS)
10964 # ifdef FEAT_MOUSE_DEC
10965 "mouse_dec",
10966 # endif
10967 # ifdef FEAT_MOUSE_GPM
10968 "mouse_gpm",
10969 # endif
10970 # ifdef FEAT_MOUSE_JSB
10971 "mouse_jsbterm",
10972 # endif
10973 # ifdef FEAT_MOUSE_NET
10974 "mouse_netterm",
10975 # endif
10976 # ifdef FEAT_MOUSE_PTERM
10977 "mouse_pterm",
10978 # endif
10979 # ifdef FEAT_MOUSE_XTERM
10980 "mouse_xterm",
10981 # endif
10982 #endif
10983 #ifdef FEAT_MBYTE
10984 "multi_byte",
10985 #endif
10986 #ifdef FEAT_MBYTE_IME
10987 "multi_byte_ime",
10988 #endif
10989 #ifdef FEAT_MULTI_LANG
10990 "multi_lang",
10991 #endif
10992 #ifdef FEAT_MZSCHEME
10993 #ifndef DYNAMIC_MZSCHEME
10994 "mzscheme",
10995 #endif
10996 #endif
10997 #ifdef FEAT_OLE
10998 "ole",
10999 #endif
11000 #ifdef FEAT_OSFILETYPE
11001 "osfiletype",
11002 #endif
11003 #ifdef FEAT_PATH_EXTRA
11004 "path_extra",
11005 #endif
11006 #ifdef FEAT_PERL
11007 #ifndef DYNAMIC_PERL
11008 "perl",
11009 #endif
11010 #endif
11011 #ifdef FEAT_PYTHON
11012 #ifndef DYNAMIC_PYTHON
11013 "python",
11014 #endif
11015 #endif
11016 #ifdef FEAT_POSTSCRIPT
11017 "postscript",
11018 #endif
11019 #ifdef FEAT_PRINTER
11020 "printer",
11021 #endif
11022 #ifdef FEAT_PROFILE
11023 "profile",
11024 #endif
11025 #ifdef FEAT_RELTIME
11026 "reltime",
11027 #endif
11028 #ifdef FEAT_QUICKFIX
11029 "quickfix",
11030 #endif
11031 #ifdef FEAT_RIGHTLEFT
11032 "rightleft",
11033 #endif
11034 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11035 "ruby",
11036 #endif
11037 #ifdef FEAT_SCROLLBIND
11038 "scrollbind",
11039 #endif
11040 #ifdef FEAT_CMDL_INFO
11041 "showcmd",
11042 "cmdline_info",
11043 #endif
11044 #ifdef FEAT_SIGNS
11045 "signs",
11046 #endif
11047 #ifdef FEAT_SMARTINDENT
11048 "smartindent",
11049 #endif
11050 #ifdef FEAT_SNIFF
11051 "sniff",
11052 #endif
11053 #ifdef FEAT_STL_OPT
11054 "statusline",
11055 #endif
11056 #ifdef FEAT_SUN_WORKSHOP
11057 "sun_workshop",
11058 #endif
11059 #ifdef FEAT_NETBEANS_INTG
11060 "netbeans_intg",
11061 #endif
11062 #ifdef FEAT_ODB_EDITOR
11063 "odbeditor",
11064 #endif
11065 #ifdef FEAT_SPELL
11066 "spell",
11067 #endif
11068 #ifdef FEAT_SYN_HL
11069 "syntax",
11070 #endif
11071 #if defined(USE_SYSTEM) || !defined(UNIX)
11072 "system",
11073 #endif
11074 #ifdef FEAT_TAG_BINS
11075 "tag_binary",
11076 #endif
11077 #ifdef FEAT_TAG_OLDSTATIC
11078 "tag_old_static",
11079 #endif
11080 #ifdef FEAT_TAG_ANYWHITE
11081 "tag_any_white",
11082 #endif
11083 #ifdef FEAT_TCL
11084 # ifndef DYNAMIC_TCL
11085 "tcl",
11086 # endif
11087 #endif
11088 #ifdef TERMINFO
11089 "terminfo",
11090 #endif
11091 #ifdef FEAT_TERMRESPONSE
11092 "termresponse",
11093 #endif
11094 #ifdef FEAT_TEXTOBJ
11095 "textobjects",
11096 #endif
11097 #ifdef HAVE_TGETENT
11098 "tgetent",
11099 #endif
11100 #ifdef FEAT_TITLE
11101 "title",
11102 #endif
11103 #ifdef FEAT_TOOLBAR
11104 "toolbar",
11105 #endif
11106 #ifdef FEAT_TRANSPARENCY
11107 "transparency",
11108 #endif
11109 #ifdef FEAT_USR_CMDS
11110 "user-commands", /* was accidentally included in 5.4 */
11111 "user_commands",
11112 #endif
11113 #ifdef FEAT_VIMINFO
11114 "viminfo",
11115 #endif
11116 #ifdef FEAT_VERTSPLIT
11117 "vertsplit",
11118 #endif
11119 #ifdef FEAT_VIRTUALEDIT
11120 "virtualedit",
11121 #endif
11122 #ifdef FEAT_VISUAL
11123 "visual",
11124 #endif
11125 #ifdef FEAT_VISUALEXTRA
11126 "visualextra",
11127 #endif
11128 #ifdef FEAT_VREPLACE
11129 "vreplace",
11130 #endif
11131 #ifdef FEAT_WILDIGN
11132 "wildignore",
11133 #endif
11134 #ifdef FEAT_WILDMENU
11135 "wildmenu",
11136 #endif
11137 #ifdef FEAT_WINDOWS
11138 "windows",
11139 #endif
11140 #ifdef FEAT_WAK
11141 "winaltkeys",
11142 #endif
11143 #ifdef FEAT_WRITEBACKUP
11144 "writebackup",
11145 #endif
11146 #ifdef FEAT_XIM
11147 "xim",
11148 #endif
11149 #ifdef FEAT_XFONTSET
11150 "xfontset",
11151 #endif
11152 #ifdef USE_XSMP
11153 "xsmp",
11154 #endif
11155 #ifdef USE_XSMP_INTERACT
11156 "xsmp_interact",
11157 #endif
11158 #ifdef FEAT_XCLIPBOARD
11159 "xterm_clipboard",
11160 #endif
11161 #ifdef FEAT_XTERM_SAVE
11162 "xterm_save",
11163 #endif
11164 #if defined(UNIX) && defined(FEAT_X11)
11165 "X11",
11166 #endif
11167 NULL
11170 name = get_tv_string(&argvars[0]);
11171 for (i = 0; has_list[i] != NULL; ++i)
11172 if (STRICMP(name, has_list[i]) == 0)
11174 n = TRUE;
11175 break;
11178 if (n == FALSE)
11180 if (STRNICMP(name, "patch", 5) == 0)
11181 n = has_patch(atoi((char *)name + 5));
11182 else if (STRICMP(name, "vim_starting") == 0)
11183 n = (starting != 0);
11184 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
11185 else if (STRICMP(name, "balloon_multiline") == 0)
11186 n = multiline_balloon_available();
11187 #endif
11188 #ifdef DYNAMIC_TCL
11189 else if (STRICMP(name, "tcl") == 0)
11190 n = tcl_enabled(FALSE);
11191 #endif
11192 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
11193 else if (STRICMP(name, "iconv") == 0)
11194 n = iconv_enabled(FALSE);
11195 #endif
11196 #ifdef DYNAMIC_MZSCHEME
11197 else if (STRICMP(name, "mzscheme") == 0)
11198 n = mzscheme_enabled(FALSE);
11199 #endif
11200 #ifdef DYNAMIC_RUBY
11201 else if (STRICMP(name, "ruby") == 0)
11202 n = ruby_enabled(FALSE);
11203 #endif
11204 #ifdef DYNAMIC_PYTHON
11205 else if (STRICMP(name, "python") == 0)
11206 n = python_enabled(FALSE);
11207 #endif
11208 #ifdef DYNAMIC_PERL
11209 else if (STRICMP(name, "perl") == 0)
11210 n = perl_enabled(FALSE);
11211 #endif
11212 #ifdef FEAT_GUI
11213 else if (STRICMP(name, "gui_running") == 0)
11214 n = (gui.in_use || gui.starting);
11215 # ifdef FEAT_GUI_W32
11216 else if (STRICMP(name, "gui_win32s") == 0)
11217 n = gui_is_win32s();
11218 # endif
11219 # ifdef FEAT_BROWSE
11220 else if (STRICMP(name, "browse") == 0)
11221 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
11222 # endif
11223 #endif
11224 #ifdef FEAT_SYN_HL
11225 else if (STRICMP(name, "syntax_items") == 0)
11226 n = syntax_present(curbuf);
11227 #endif
11228 #if defined(WIN3264)
11229 else if (STRICMP(name, "win95") == 0)
11230 n = mch_windows95();
11231 #endif
11232 #ifdef FEAT_NETBEANS_INTG
11233 else if (STRICMP(name, "netbeans_enabled") == 0)
11234 n = usingNetbeans;
11235 #endif
11238 rettv->vval.v_number = n;
11242 * "has_key()" function
11244 static void
11245 f_has_key(argvars, rettv)
11246 typval_T *argvars;
11247 typval_T *rettv;
11249 rettv->vval.v_number = 0;
11250 if (argvars[0].v_type != VAR_DICT)
11252 EMSG(_(e_dictreq));
11253 return;
11255 if (argvars[0].vval.v_dict == NULL)
11256 return;
11258 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
11259 get_tv_string(&argvars[1]), -1) != NULL;
11263 * "haslocaldir()" function
11265 /*ARGSUSED*/
11266 static void
11267 f_haslocaldir(argvars, rettv)
11268 typval_T *argvars;
11269 typval_T *rettv;
11271 rettv->vval.v_number = (curwin->w_localdir != NULL);
11275 * "hasmapto()" function
11277 static void
11278 f_hasmapto(argvars, rettv)
11279 typval_T *argvars;
11280 typval_T *rettv;
11282 char_u *name;
11283 char_u *mode;
11284 char_u buf[NUMBUFLEN];
11285 int abbr = FALSE;
11287 name = get_tv_string(&argvars[0]);
11288 if (argvars[1].v_type == VAR_UNKNOWN)
11289 mode = (char_u *)"nvo";
11290 else
11292 mode = get_tv_string_buf(&argvars[1], buf);
11293 if (argvars[2].v_type != VAR_UNKNOWN)
11294 abbr = get_tv_number(&argvars[2]);
11297 if (map_to_exists(name, mode, abbr))
11298 rettv->vval.v_number = TRUE;
11299 else
11300 rettv->vval.v_number = FALSE;
11304 * "histadd()" function
11306 /*ARGSUSED*/
11307 static void
11308 f_histadd(argvars, rettv)
11309 typval_T *argvars;
11310 typval_T *rettv;
11312 #ifdef FEAT_CMDHIST
11313 int histype;
11314 char_u *str;
11315 char_u buf[NUMBUFLEN];
11316 #endif
11318 rettv->vval.v_number = FALSE;
11319 if (check_restricted() || check_secure())
11320 return;
11321 #ifdef FEAT_CMDHIST
11322 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11323 histype = str != NULL ? get_histtype(str) : -1;
11324 if (histype >= 0)
11326 str = get_tv_string_buf(&argvars[1], buf);
11327 if (*str != NUL)
11329 add_to_history(histype, str, FALSE, NUL);
11330 rettv->vval.v_number = TRUE;
11331 return;
11334 #endif
11338 * "histdel()" function
11340 /*ARGSUSED*/
11341 static void
11342 f_histdel(argvars, rettv)
11343 typval_T *argvars;
11344 typval_T *rettv;
11346 #ifdef FEAT_CMDHIST
11347 int n;
11348 char_u buf[NUMBUFLEN];
11349 char_u *str;
11351 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11352 if (str == NULL)
11353 n = 0;
11354 else if (argvars[1].v_type == VAR_UNKNOWN)
11355 /* only one argument: clear entire history */
11356 n = clr_history(get_histtype(str));
11357 else if (argvars[1].v_type == VAR_NUMBER)
11358 /* index given: remove that entry */
11359 n = del_history_idx(get_histtype(str),
11360 (int)get_tv_number(&argvars[1]));
11361 else
11362 /* string given: remove all matching entries */
11363 n = del_history_entry(get_histtype(str),
11364 get_tv_string_buf(&argvars[1], buf));
11365 rettv->vval.v_number = n;
11366 #else
11367 rettv->vval.v_number = 0;
11368 #endif
11372 * "histget()" function
11374 /*ARGSUSED*/
11375 static void
11376 f_histget(argvars, rettv)
11377 typval_T *argvars;
11378 typval_T *rettv;
11380 #ifdef FEAT_CMDHIST
11381 int type;
11382 int idx;
11383 char_u *str;
11385 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11386 if (str == NULL)
11387 rettv->vval.v_string = NULL;
11388 else
11390 type = get_histtype(str);
11391 if (argvars[1].v_type == VAR_UNKNOWN)
11392 idx = get_history_idx(type);
11393 else
11394 idx = (int)get_tv_number_chk(&argvars[1], NULL);
11395 /* -1 on type error */
11396 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
11398 #else
11399 rettv->vval.v_string = NULL;
11400 #endif
11401 rettv->v_type = VAR_STRING;
11405 * "histnr()" function
11407 /*ARGSUSED*/
11408 static void
11409 f_histnr(argvars, rettv)
11410 typval_T *argvars;
11411 typval_T *rettv;
11413 int i;
11415 #ifdef FEAT_CMDHIST
11416 char_u *history = get_tv_string_chk(&argvars[0]);
11418 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
11419 if (i >= HIST_CMD && i < HIST_COUNT)
11420 i = get_history_idx(i);
11421 else
11422 #endif
11423 i = -1;
11424 rettv->vval.v_number = i;
11428 * "highlightID(name)" function
11430 static void
11431 f_hlID(argvars, rettv)
11432 typval_T *argvars;
11433 typval_T *rettv;
11435 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
11439 * "highlight_exists()" function
11441 static void
11442 f_hlexists(argvars, rettv)
11443 typval_T *argvars;
11444 typval_T *rettv;
11446 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
11450 * "hostname()" function
11452 /*ARGSUSED*/
11453 static void
11454 f_hostname(argvars, rettv)
11455 typval_T *argvars;
11456 typval_T *rettv;
11458 char_u hostname[256];
11460 mch_get_host_name(hostname, 256);
11461 rettv->v_type = VAR_STRING;
11462 rettv->vval.v_string = vim_strsave(hostname);
11466 * iconv() function
11468 /*ARGSUSED*/
11469 static void
11470 f_iconv(argvars, rettv)
11471 typval_T *argvars;
11472 typval_T *rettv;
11474 #ifdef FEAT_MBYTE
11475 char_u buf1[NUMBUFLEN];
11476 char_u buf2[NUMBUFLEN];
11477 char_u *from, *to, *str;
11478 vimconv_T vimconv;
11479 #endif
11481 rettv->v_type = VAR_STRING;
11482 rettv->vval.v_string = NULL;
11484 #ifdef FEAT_MBYTE
11485 str = get_tv_string(&argvars[0]);
11486 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
11487 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
11488 vimconv.vc_type = CONV_NONE;
11489 convert_setup(&vimconv, from, to);
11491 /* If the encodings are equal, no conversion needed. */
11492 if (vimconv.vc_type == CONV_NONE)
11493 rettv->vval.v_string = vim_strsave(str);
11494 else
11495 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
11497 convert_setup(&vimconv, NULL, NULL);
11498 vim_free(from);
11499 vim_free(to);
11500 #endif
11504 * "indent()" function
11506 static void
11507 f_indent(argvars, rettv)
11508 typval_T *argvars;
11509 typval_T *rettv;
11511 linenr_T lnum;
11513 lnum = get_tv_lnum(argvars);
11514 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
11515 rettv->vval.v_number = get_indent_lnum(lnum);
11516 else
11517 rettv->vval.v_number = -1;
11521 * "index()" function
11523 static void
11524 f_index(argvars, rettv)
11525 typval_T *argvars;
11526 typval_T *rettv;
11528 list_T *l;
11529 listitem_T *item;
11530 long idx = 0;
11531 int ic = FALSE;
11533 rettv->vval.v_number = -1;
11534 if (argvars[0].v_type != VAR_LIST)
11536 EMSG(_(e_listreq));
11537 return;
11539 l = argvars[0].vval.v_list;
11540 if (l != NULL)
11542 item = l->lv_first;
11543 if (argvars[2].v_type != VAR_UNKNOWN)
11545 int error = FALSE;
11547 /* Start at specified item. Use the cached index that list_find()
11548 * sets, so that a negative number also works. */
11549 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
11550 idx = l->lv_idx;
11551 if (argvars[3].v_type != VAR_UNKNOWN)
11552 ic = get_tv_number_chk(&argvars[3], &error);
11553 if (error)
11554 item = NULL;
11557 for ( ; item != NULL; item = item->li_next, ++idx)
11558 if (tv_equal(&item->li_tv, &argvars[1], ic))
11560 rettv->vval.v_number = idx;
11561 break;
11566 static int inputsecret_flag = 0;
11568 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
11571 * This function is used by f_input() and f_inputdialog() functions. The third
11572 * argument to f_input() specifies the type of completion to use at the
11573 * prompt. The third argument to f_inputdialog() specifies the value to return
11574 * when the user cancels the prompt.
11576 static void
11577 get_user_input(argvars, rettv, inputdialog)
11578 typval_T *argvars;
11579 typval_T *rettv;
11580 int inputdialog;
11582 char_u *prompt = get_tv_string_chk(&argvars[0]);
11583 char_u *p = NULL;
11584 int c;
11585 char_u buf[NUMBUFLEN];
11586 int cmd_silent_save = cmd_silent;
11587 char_u *defstr = (char_u *)"";
11588 int xp_type = EXPAND_NOTHING;
11589 char_u *xp_arg = NULL;
11591 rettv->v_type = VAR_STRING;
11592 rettv->vval.v_string = NULL;
11594 #ifdef NO_CONSOLE_INPUT
11595 /* While starting up, there is no place to enter text. */
11596 if (no_console_input())
11597 return;
11598 #endif
11600 cmd_silent = FALSE; /* Want to see the prompt. */
11601 if (prompt != NULL)
11603 /* Only the part of the message after the last NL is considered as
11604 * prompt for the command line */
11605 p = vim_strrchr(prompt, '\n');
11606 if (p == NULL)
11607 p = prompt;
11608 else
11610 ++p;
11611 c = *p;
11612 *p = NUL;
11613 msg_start();
11614 msg_clr_eos();
11615 msg_puts_attr(prompt, echo_attr);
11616 msg_didout = FALSE;
11617 msg_starthere();
11618 *p = c;
11620 cmdline_row = msg_row;
11622 if (argvars[1].v_type != VAR_UNKNOWN)
11624 defstr = get_tv_string_buf_chk(&argvars[1], buf);
11625 if (defstr != NULL)
11626 stuffReadbuffSpec(defstr);
11628 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
11630 char_u *xp_name;
11631 int xp_namelen;
11632 long argt;
11634 rettv->vval.v_string = NULL;
11636 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
11637 if (xp_name == NULL)
11638 return;
11640 xp_namelen = (int)STRLEN(xp_name);
11642 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
11643 &xp_arg) == FAIL)
11644 return;
11648 if (defstr != NULL)
11649 rettv->vval.v_string =
11650 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
11651 xp_type, xp_arg);
11653 vim_free(xp_arg);
11655 /* since the user typed this, no need to wait for return */
11656 need_wait_return = FALSE;
11657 msg_didout = FALSE;
11659 cmd_silent = cmd_silent_save;
11663 * "input()" function
11664 * Also handles inputsecret() when inputsecret is set.
11666 static void
11667 f_input(argvars, rettv)
11668 typval_T *argvars;
11669 typval_T *rettv;
11671 get_user_input(argvars, rettv, FALSE);
11675 * "inputdialog()" function
11677 static void
11678 f_inputdialog(argvars, rettv)
11679 typval_T *argvars;
11680 typval_T *rettv;
11682 #if defined(FEAT_GUI_TEXTDIALOG)
11683 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
11684 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
11686 char_u *message;
11687 char_u buf[NUMBUFLEN];
11688 char_u *defstr = (char_u *)"";
11690 message = get_tv_string_chk(&argvars[0]);
11691 if (argvars[1].v_type != VAR_UNKNOWN
11692 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
11693 vim_strncpy(IObuff, defstr, IOSIZE - 1);
11694 else
11695 IObuff[0] = NUL;
11696 if (message != NULL && defstr != NULL
11697 && do_dialog(VIM_QUESTION, NULL, message,
11698 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
11699 rettv->vval.v_string = vim_strsave(IObuff);
11700 else
11702 if (message != NULL && defstr != NULL
11703 && argvars[1].v_type != VAR_UNKNOWN
11704 && argvars[2].v_type != VAR_UNKNOWN)
11705 rettv->vval.v_string = vim_strsave(
11706 get_tv_string_buf(&argvars[2], buf));
11707 else
11708 rettv->vval.v_string = NULL;
11710 rettv->v_type = VAR_STRING;
11712 else
11713 #endif
11714 get_user_input(argvars, rettv, TRUE);
11718 * "inputlist()" function
11720 static void
11721 f_inputlist(argvars, rettv)
11722 typval_T *argvars;
11723 typval_T *rettv;
11725 listitem_T *li;
11726 int selected;
11727 int mouse_used;
11729 rettv->vval.v_number = 0;
11730 #ifdef NO_CONSOLE_INPUT
11731 /* While starting up, there is no place to enter text. */
11732 if (no_console_input())
11733 return;
11734 #endif
11735 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
11737 EMSG2(_(e_listarg), "inputlist()");
11738 return;
11741 msg_start();
11742 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
11743 lines_left = Rows; /* avoid more prompt */
11744 msg_scroll = TRUE;
11745 msg_clr_eos();
11747 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
11749 msg_puts(get_tv_string(&li->li_tv));
11750 msg_putchar('\n');
11753 /* Ask for choice. */
11754 selected = prompt_for_number(&mouse_used);
11755 if (mouse_used)
11756 selected -= lines_left;
11758 rettv->vval.v_number = selected;
11762 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
11765 * "inputrestore()" function
11767 /*ARGSUSED*/
11768 static void
11769 f_inputrestore(argvars, rettv)
11770 typval_T *argvars;
11771 typval_T *rettv;
11773 if (ga_userinput.ga_len > 0)
11775 --ga_userinput.ga_len;
11776 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
11777 + ga_userinput.ga_len);
11778 rettv->vval.v_number = 0; /* OK */
11780 else if (p_verbose > 1)
11782 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
11783 rettv->vval.v_number = 1; /* Failed */
11788 * "inputsave()" function
11790 /*ARGSUSED*/
11791 static void
11792 f_inputsave(argvars, rettv)
11793 typval_T *argvars;
11794 typval_T *rettv;
11796 /* Add an entry to the stack of typehead storage. */
11797 if (ga_grow(&ga_userinput, 1) == OK)
11799 save_typeahead((tasave_T *)(ga_userinput.ga_data)
11800 + ga_userinput.ga_len);
11801 ++ga_userinput.ga_len;
11802 rettv->vval.v_number = 0; /* OK */
11804 else
11805 rettv->vval.v_number = 1; /* Failed */
11809 * "inputsecret()" function
11811 static void
11812 f_inputsecret(argvars, rettv)
11813 typval_T *argvars;
11814 typval_T *rettv;
11816 ++cmdline_star;
11817 ++inputsecret_flag;
11818 f_input(argvars, rettv);
11819 --cmdline_star;
11820 --inputsecret_flag;
11824 * "insert()" function
11826 static void
11827 f_insert(argvars, rettv)
11828 typval_T *argvars;
11829 typval_T *rettv;
11831 long before = 0;
11832 listitem_T *item;
11833 list_T *l;
11834 int error = FALSE;
11836 rettv->vval.v_number = 0;
11837 if (argvars[0].v_type != VAR_LIST)
11838 EMSG2(_(e_listarg), "insert()");
11839 else if ((l = argvars[0].vval.v_list) != NULL
11840 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
11842 if (argvars[2].v_type != VAR_UNKNOWN)
11843 before = get_tv_number_chk(&argvars[2], &error);
11844 if (error)
11845 return; /* type error; errmsg already given */
11847 if (before == l->lv_len)
11848 item = NULL;
11849 else
11851 item = list_find(l, before);
11852 if (item == NULL)
11854 EMSGN(_(e_listidx), before);
11855 l = NULL;
11858 if (l != NULL)
11860 list_insert_tv(l, &argvars[1], item);
11861 copy_tv(&argvars[0], rettv);
11867 * "isdirectory()" function
11869 static void
11870 f_isdirectory(argvars, rettv)
11871 typval_T *argvars;
11872 typval_T *rettv;
11874 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
11878 * "islocked()" function
11880 static void
11881 f_islocked(argvars, rettv)
11882 typval_T *argvars;
11883 typval_T *rettv;
11885 lval_T lv;
11886 char_u *end;
11887 dictitem_T *di;
11889 rettv->vval.v_number = -1;
11890 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
11891 FNE_CHECK_START);
11892 if (end != NULL && lv.ll_name != NULL)
11894 if (*end != NUL)
11895 EMSG(_(e_trailing));
11896 else
11898 if (lv.ll_tv == NULL)
11900 if (check_changedtick(lv.ll_name))
11901 rettv->vval.v_number = 1; /* always locked */
11902 else
11904 di = find_var(lv.ll_name, NULL);
11905 if (di != NULL)
11907 /* Consider a variable locked when:
11908 * 1. the variable itself is locked
11909 * 2. the value of the variable is locked.
11910 * 3. the List or Dict value is locked.
11912 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
11913 || tv_islocked(&di->di_tv));
11917 else if (lv.ll_range)
11918 EMSG(_("E786: Range not allowed"));
11919 else if (lv.ll_newkey != NULL)
11920 EMSG2(_(e_dictkey), lv.ll_newkey);
11921 else if (lv.ll_list != NULL)
11922 /* List item. */
11923 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
11924 else
11925 /* Dictionary item. */
11926 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
11930 clear_lval(&lv);
11933 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
11936 * Turn a dict into a list:
11937 * "what" == 0: list of keys
11938 * "what" == 1: list of values
11939 * "what" == 2: list of items
11941 static void
11942 dict_list(argvars, rettv, what)
11943 typval_T *argvars;
11944 typval_T *rettv;
11945 int what;
11947 list_T *l2;
11948 dictitem_T *di;
11949 hashitem_T *hi;
11950 listitem_T *li;
11951 listitem_T *li2;
11952 dict_T *d;
11953 int todo;
11955 rettv->vval.v_number = 0;
11956 if (argvars[0].v_type != VAR_DICT)
11958 EMSG(_(e_dictreq));
11959 return;
11961 if ((d = argvars[0].vval.v_dict) == NULL)
11962 return;
11964 if (rettv_list_alloc(rettv) == FAIL)
11965 return;
11967 todo = (int)d->dv_hashtab.ht_used;
11968 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
11970 if (!HASHITEM_EMPTY(hi))
11972 --todo;
11973 di = HI2DI(hi);
11975 li = listitem_alloc();
11976 if (li == NULL)
11977 break;
11978 list_append(rettv->vval.v_list, li);
11980 if (what == 0)
11982 /* keys() */
11983 li->li_tv.v_type = VAR_STRING;
11984 li->li_tv.v_lock = 0;
11985 li->li_tv.vval.v_string = vim_strsave(di->di_key);
11987 else if (what == 1)
11989 /* values() */
11990 copy_tv(&di->di_tv, &li->li_tv);
11992 else
11994 /* items() */
11995 l2 = list_alloc();
11996 li->li_tv.v_type = VAR_LIST;
11997 li->li_tv.v_lock = 0;
11998 li->li_tv.vval.v_list = l2;
11999 if (l2 == NULL)
12000 break;
12001 ++l2->lv_refcount;
12003 li2 = listitem_alloc();
12004 if (li2 == NULL)
12005 break;
12006 list_append(l2, li2);
12007 li2->li_tv.v_type = VAR_STRING;
12008 li2->li_tv.v_lock = 0;
12009 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12011 li2 = listitem_alloc();
12012 if (li2 == NULL)
12013 break;
12014 list_append(l2, li2);
12015 copy_tv(&di->di_tv, &li2->li_tv);
12022 * "items(dict)" function
12024 static void
12025 f_items(argvars, rettv)
12026 typval_T *argvars;
12027 typval_T *rettv;
12029 dict_list(argvars, rettv, 2);
12033 * "join()" function
12035 static void
12036 f_join(argvars, rettv)
12037 typval_T *argvars;
12038 typval_T *rettv;
12040 garray_T ga;
12041 char_u *sep;
12043 rettv->vval.v_number = 0;
12044 if (argvars[0].v_type != VAR_LIST)
12046 EMSG(_(e_listreq));
12047 return;
12049 if (argvars[0].vval.v_list == NULL)
12050 return;
12051 if (argvars[1].v_type == VAR_UNKNOWN)
12052 sep = (char_u *)" ";
12053 else
12054 sep = get_tv_string_chk(&argvars[1]);
12056 rettv->v_type = VAR_STRING;
12058 if (sep != NULL)
12060 ga_init2(&ga, (int)sizeof(char), 80);
12061 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12062 ga_append(&ga, NUL);
12063 rettv->vval.v_string = (char_u *)ga.ga_data;
12065 else
12066 rettv->vval.v_string = NULL;
12070 * "keys()" function
12072 static void
12073 f_keys(argvars, rettv)
12074 typval_T *argvars;
12075 typval_T *rettv;
12077 dict_list(argvars, rettv, 0);
12081 * "last_buffer_nr()" function.
12083 /*ARGSUSED*/
12084 static void
12085 f_last_buffer_nr(argvars, rettv)
12086 typval_T *argvars;
12087 typval_T *rettv;
12089 int n = 0;
12090 buf_T *buf;
12092 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12093 if (n < buf->b_fnum)
12094 n = buf->b_fnum;
12096 rettv->vval.v_number = n;
12100 * "len()" function
12102 static void
12103 f_len(argvars, rettv)
12104 typval_T *argvars;
12105 typval_T *rettv;
12107 switch (argvars[0].v_type)
12109 case VAR_STRING:
12110 case VAR_NUMBER:
12111 rettv->vval.v_number = (varnumber_T)STRLEN(
12112 get_tv_string(&argvars[0]));
12113 break;
12114 case VAR_LIST:
12115 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
12116 break;
12117 case VAR_DICT:
12118 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
12119 break;
12120 default:
12121 EMSG(_("E701: Invalid type for len()"));
12122 break;
12126 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
12128 static void
12129 libcall_common(argvars, rettv, type)
12130 typval_T *argvars;
12131 typval_T *rettv;
12132 int type;
12134 #ifdef FEAT_LIBCALL
12135 char_u *string_in;
12136 char_u **string_result;
12137 int nr_result;
12138 #endif
12140 rettv->v_type = type;
12141 if (type == VAR_NUMBER)
12142 rettv->vval.v_number = 0;
12143 else
12144 rettv->vval.v_string = NULL;
12146 if (check_restricted() || check_secure())
12147 return;
12149 #ifdef FEAT_LIBCALL
12150 /* The first two args must be strings, otherwise its meaningless */
12151 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
12153 string_in = NULL;
12154 if (argvars[2].v_type == VAR_STRING)
12155 string_in = argvars[2].vval.v_string;
12156 if (type == VAR_NUMBER)
12157 string_result = NULL;
12158 else
12159 string_result = &rettv->vval.v_string;
12160 if (mch_libcall(argvars[0].vval.v_string,
12161 argvars[1].vval.v_string,
12162 string_in,
12163 argvars[2].vval.v_number,
12164 string_result,
12165 &nr_result) == OK
12166 && type == VAR_NUMBER)
12167 rettv->vval.v_number = nr_result;
12169 #endif
12173 * "libcall()" function
12175 static void
12176 f_libcall(argvars, rettv)
12177 typval_T *argvars;
12178 typval_T *rettv;
12180 libcall_common(argvars, rettv, VAR_STRING);
12184 * "libcallnr()" function
12186 static void
12187 f_libcallnr(argvars, rettv)
12188 typval_T *argvars;
12189 typval_T *rettv;
12191 libcall_common(argvars, rettv, VAR_NUMBER);
12195 * "line(string)" function
12197 static void
12198 f_line(argvars, rettv)
12199 typval_T *argvars;
12200 typval_T *rettv;
12202 linenr_T lnum = 0;
12203 pos_T *fp;
12204 int fnum;
12206 fp = var2fpos(&argvars[0], TRUE, &fnum);
12207 if (fp != NULL)
12208 lnum = fp->lnum;
12209 rettv->vval.v_number = lnum;
12213 * "line2byte(lnum)" function
12215 /*ARGSUSED*/
12216 static void
12217 f_line2byte(argvars, rettv)
12218 typval_T *argvars;
12219 typval_T *rettv;
12221 #ifndef FEAT_BYTEOFF
12222 rettv->vval.v_number = -1;
12223 #else
12224 linenr_T lnum;
12226 lnum = get_tv_lnum(argvars);
12227 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
12228 rettv->vval.v_number = -1;
12229 else
12230 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
12231 if (rettv->vval.v_number >= 0)
12232 ++rettv->vval.v_number;
12233 #endif
12237 * "lispindent(lnum)" function
12239 static void
12240 f_lispindent(argvars, rettv)
12241 typval_T *argvars;
12242 typval_T *rettv;
12244 #ifdef FEAT_LISP
12245 pos_T pos;
12246 linenr_T lnum;
12248 pos = curwin->w_cursor;
12249 lnum = get_tv_lnum(argvars);
12250 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12252 curwin->w_cursor.lnum = lnum;
12253 rettv->vval.v_number = get_lisp_indent();
12254 curwin->w_cursor = pos;
12256 else
12257 #endif
12258 rettv->vval.v_number = -1;
12262 * "localtime()" function
12264 /*ARGSUSED*/
12265 static void
12266 f_localtime(argvars, rettv)
12267 typval_T *argvars;
12268 typval_T *rettv;
12270 rettv->vval.v_number = (varnumber_T)time(NULL);
12273 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
12275 static void
12276 get_maparg(argvars, rettv, exact)
12277 typval_T *argvars;
12278 typval_T *rettv;
12279 int exact;
12281 char_u *keys;
12282 char_u *which;
12283 char_u buf[NUMBUFLEN];
12284 char_u *keys_buf = NULL;
12285 char_u *rhs;
12286 int mode;
12287 garray_T ga;
12288 int abbr = FALSE;
12290 /* return empty string for failure */
12291 rettv->v_type = VAR_STRING;
12292 rettv->vval.v_string = NULL;
12294 keys = get_tv_string(&argvars[0]);
12295 if (*keys == NUL)
12296 return;
12298 if (argvars[1].v_type != VAR_UNKNOWN)
12300 which = get_tv_string_buf_chk(&argvars[1], buf);
12301 if (argvars[2].v_type != VAR_UNKNOWN)
12302 abbr = get_tv_number(&argvars[2]);
12304 else
12305 which = (char_u *)"";
12306 if (which == NULL)
12307 return;
12309 mode = get_map_mode(&which, 0);
12311 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
12312 rhs = check_map(keys, mode, exact, FALSE, abbr);
12313 vim_free(keys_buf);
12314 if (rhs != NULL)
12316 ga_init(&ga);
12317 ga.ga_itemsize = 1;
12318 ga.ga_growsize = 40;
12320 while (*rhs != NUL)
12321 ga_concat(&ga, str2special(&rhs, FALSE));
12323 ga_append(&ga, NUL);
12324 rettv->vval.v_string = (char_u *)ga.ga_data;
12329 * "map()" function
12331 static void
12332 f_map(argvars, rettv)
12333 typval_T *argvars;
12334 typval_T *rettv;
12336 filter_map(argvars, rettv, TRUE);
12340 * "maparg()" function
12342 static void
12343 f_maparg(argvars, rettv)
12344 typval_T *argvars;
12345 typval_T *rettv;
12347 get_maparg(argvars, rettv, TRUE);
12351 * "mapcheck()" function
12353 static void
12354 f_mapcheck(argvars, rettv)
12355 typval_T *argvars;
12356 typval_T *rettv;
12358 get_maparg(argvars, rettv, FALSE);
12361 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
12363 static void
12364 find_some_match(argvars, rettv, type)
12365 typval_T *argvars;
12366 typval_T *rettv;
12367 int type;
12369 char_u *str = NULL;
12370 char_u *expr = NULL;
12371 char_u *pat;
12372 regmatch_T regmatch;
12373 char_u patbuf[NUMBUFLEN];
12374 char_u strbuf[NUMBUFLEN];
12375 char_u *save_cpo;
12376 long start = 0;
12377 long nth = 1;
12378 colnr_T startcol = 0;
12379 int match = 0;
12380 list_T *l = NULL;
12381 listitem_T *li = NULL;
12382 long idx = 0;
12383 char_u *tofree = NULL;
12385 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
12386 save_cpo = p_cpo;
12387 p_cpo = (char_u *)"";
12389 rettv->vval.v_number = -1;
12390 if (type == 3)
12392 /* return empty list when there are no matches */
12393 if (rettv_list_alloc(rettv) == FAIL)
12394 goto theend;
12396 else if (type == 2)
12398 rettv->v_type = VAR_STRING;
12399 rettv->vval.v_string = NULL;
12402 if (argvars[0].v_type == VAR_LIST)
12404 if ((l = argvars[0].vval.v_list) == NULL)
12405 goto theend;
12406 li = l->lv_first;
12408 else
12409 expr = str = get_tv_string(&argvars[0]);
12411 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
12412 if (pat == NULL)
12413 goto theend;
12415 if (argvars[2].v_type != VAR_UNKNOWN)
12417 int error = FALSE;
12419 start = get_tv_number_chk(&argvars[2], &error);
12420 if (error)
12421 goto theend;
12422 if (l != NULL)
12424 li = list_find(l, start);
12425 if (li == NULL)
12426 goto theend;
12427 idx = l->lv_idx; /* use the cached index */
12429 else
12431 if (start < 0)
12432 start = 0;
12433 if (start > (long)STRLEN(str))
12434 goto theend;
12435 /* When "count" argument is there ignore matches before "start",
12436 * otherwise skip part of the string. Differs when pattern is "^"
12437 * or "\<". */
12438 if (argvars[3].v_type != VAR_UNKNOWN)
12439 startcol = start;
12440 else
12441 str += start;
12444 if (argvars[3].v_type != VAR_UNKNOWN)
12445 nth = get_tv_number_chk(&argvars[3], &error);
12446 if (error)
12447 goto theend;
12450 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
12451 if (regmatch.regprog != NULL)
12453 regmatch.rm_ic = p_ic;
12455 for (;;)
12457 if (l != NULL)
12459 if (li == NULL)
12461 match = FALSE;
12462 break;
12464 vim_free(tofree);
12465 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
12466 if (str == NULL)
12467 break;
12470 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
12472 if (match && --nth <= 0)
12473 break;
12474 if (l == NULL && !match)
12475 break;
12477 /* Advance to just after the match. */
12478 if (l != NULL)
12480 li = li->li_next;
12481 ++idx;
12483 else
12485 #ifdef FEAT_MBYTE
12486 startcol = (colnr_T)(regmatch.startp[0]
12487 + (*mb_ptr2len)(regmatch.startp[0]) - str);
12488 #else
12489 startcol = regmatch.startp[0] + 1 - str;
12490 #endif
12494 if (match)
12496 if (type == 3)
12498 int i;
12500 /* return list with matched string and submatches */
12501 for (i = 0; i < NSUBEXP; ++i)
12503 if (regmatch.endp[i] == NULL)
12505 if (list_append_string(rettv->vval.v_list,
12506 (char_u *)"", 0) == FAIL)
12507 break;
12509 else if (list_append_string(rettv->vval.v_list,
12510 regmatch.startp[i],
12511 (int)(regmatch.endp[i] - regmatch.startp[i]))
12512 == FAIL)
12513 break;
12516 else if (type == 2)
12518 /* return matched string */
12519 if (l != NULL)
12520 copy_tv(&li->li_tv, rettv);
12521 else
12522 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
12523 (int)(regmatch.endp[0] - regmatch.startp[0]));
12525 else if (l != NULL)
12526 rettv->vval.v_number = idx;
12527 else
12529 if (type != 0)
12530 rettv->vval.v_number =
12531 (varnumber_T)(regmatch.startp[0] - str);
12532 else
12533 rettv->vval.v_number =
12534 (varnumber_T)(regmatch.endp[0] - str);
12535 rettv->vval.v_number += (varnumber_T)(str - expr);
12538 vim_free(regmatch.regprog);
12541 theend:
12542 vim_free(tofree);
12543 p_cpo = save_cpo;
12547 * "match()" function
12549 static void
12550 f_match(argvars, rettv)
12551 typval_T *argvars;
12552 typval_T *rettv;
12554 find_some_match(argvars, rettv, 1);
12558 * "matchadd()" function
12560 static void
12561 f_matchadd(argvars, rettv)
12562 typval_T *argvars;
12563 typval_T *rettv;
12565 #ifdef FEAT_SEARCH_EXTRA
12566 char_u buf[NUMBUFLEN];
12567 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
12568 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
12569 int prio = 10; /* default priority */
12570 int id = -1;
12571 int error = FALSE;
12573 rettv->vval.v_number = -1;
12575 if (grp == NULL || pat == NULL)
12576 return;
12577 if (argvars[2].v_type != VAR_UNKNOWN)
12579 prio = get_tv_number_chk(&argvars[2], &error);
12580 if (argvars[3].v_type != VAR_UNKNOWN)
12581 id = get_tv_number_chk(&argvars[3], &error);
12583 if (error == TRUE)
12584 return;
12585 if (id >= 1 && id <= 3)
12587 EMSGN("E798: ID is reserved for \":match\": %ld", id);
12588 return;
12591 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
12592 #endif
12596 * "matcharg()" function
12598 static void
12599 f_matcharg(argvars, rettv)
12600 typval_T *argvars;
12601 typval_T *rettv;
12603 if (rettv_list_alloc(rettv) == OK)
12605 #ifdef FEAT_SEARCH_EXTRA
12606 int id = get_tv_number(&argvars[0]);
12607 matchitem_T *m;
12609 if (id >= 1 && id <= 3)
12611 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
12613 list_append_string(rettv->vval.v_list,
12614 syn_id2name(m->hlg_id), -1);
12615 list_append_string(rettv->vval.v_list, m->pattern, -1);
12617 else
12619 list_append_string(rettv->vval.v_list, NUL, -1);
12620 list_append_string(rettv->vval.v_list, NUL, -1);
12623 #endif
12628 * "matchdelete()" function
12630 static void
12631 f_matchdelete(argvars, rettv)
12632 typval_T *argvars;
12633 typval_T *rettv;
12635 #ifdef FEAT_SEARCH_EXTRA
12636 rettv->vval.v_number = match_delete(curwin,
12637 (int)get_tv_number(&argvars[0]), TRUE);
12638 #endif
12642 * "matchend()" function
12644 static void
12645 f_matchend(argvars, rettv)
12646 typval_T *argvars;
12647 typval_T *rettv;
12649 find_some_match(argvars, rettv, 0);
12653 * "matchlist()" function
12655 static void
12656 f_matchlist(argvars, rettv)
12657 typval_T *argvars;
12658 typval_T *rettv;
12660 find_some_match(argvars, rettv, 3);
12664 * "matchstr()" function
12666 static void
12667 f_matchstr(argvars, rettv)
12668 typval_T *argvars;
12669 typval_T *rettv;
12671 find_some_match(argvars, rettv, 2);
12674 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
12676 static void
12677 max_min(argvars, rettv, domax)
12678 typval_T *argvars;
12679 typval_T *rettv;
12680 int domax;
12682 long n = 0;
12683 long i;
12684 int error = FALSE;
12686 if (argvars[0].v_type == VAR_LIST)
12688 list_T *l;
12689 listitem_T *li;
12691 l = argvars[0].vval.v_list;
12692 if (l != NULL)
12694 li = l->lv_first;
12695 if (li != NULL)
12697 n = get_tv_number_chk(&li->li_tv, &error);
12698 for (;;)
12700 li = li->li_next;
12701 if (li == NULL)
12702 break;
12703 i = get_tv_number_chk(&li->li_tv, &error);
12704 if (domax ? i > n : i < n)
12705 n = i;
12710 else if (argvars[0].v_type == VAR_DICT)
12712 dict_T *d;
12713 int first = TRUE;
12714 hashitem_T *hi;
12715 int todo;
12717 d = argvars[0].vval.v_dict;
12718 if (d != NULL)
12720 todo = (int)d->dv_hashtab.ht_used;
12721 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12723 if (!HASHITEM_EMPTY(hi))
12725 --todo;
12726 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
12727 if (first)
12729 n = i;
12730 first = FALSE;
12732 else if (domax ? i > n : i < n)
12733 n = i;
12738 else
12739 EMSG(_(e_listdictarg));
12740 rettv->vval.v_number = error ? 0 : n;
12744 * "max()" function
12746 static void
12747 f_max(argvars, rettv)
12748 typval_T *argvars;
12749 typval_T *rettv;
12751 max_min(argvars, rettv, TRUE);
12755 * "min()" function
12757 static void
12758 f_min(argvars, rettv)
12759 typval_T *argvars;
12760 typval_T *rettv;
12762 max_min(argvars, rettv, FALSE);
12765 static int mkdir_recurse __ARGS((char_u *dir, int prot));
12768 * Create the directory in which "dir" is located, and higher levels when
12769 * needed.
12771 static int
12772 mkdir_recurse(dir, prot)
12773 char_u *dir;
12774 int prot;
12776 char_u *p;
12777 char_u *updir;
12778 int r = FAIL;
12780 /* Get end of directory name in "dir".
12781 * We're done when it's "/" or "c:/". */
12782 p = gettail_sep(dir);
12783 if (p <= get_past_head(dir))
12784 return OK;
12786 /* If the directory exists we're done. Otherwise: create it.*/
12787 updir = vim_strnsave(dir, (int)(p - dir));
12788 if (updir == NULL)
12789 return FAIL;
12790 if (mch_isdir(updir))
12791 r = OK;
12792 else if (mkdir_recurse(updir, prot) == OK)
12793 r = vim_mkdir_emsg(updir, prot);
12794 vim_free(updir);
12795 return r;
12798 #ifdef vim_mkdir
12800 * "mkdir()" function
12802 static void
12803 f_mkdir(argvars, rettv)
12804 typval_T *argvars;
12805 typval_T *rettv;
12807 char_u *dir;
12808 char_u buf[NUMBUFLEN];
12809 int prot = 0755;
12811 rettv->vval.v_number = FAIL;
12812 if (check_restricted() || check_secure())
12813 return;
12815 dir = get_tv_string_buf(&argvars[0], buf);
12816 if (argvars[1].v_type != VAR_UNKNOWN)
12818 if (argvars[2].v_type != VAR_UNKNOWN)
12819 prot = get_tv_number_chk(&argvars[2], NULL);
12820 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
12821 mkdir_recurse(dir, prot);
12823 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
12825 #endif
12828 * "mode()" function
12830 /*ARGSUSED*/
12831 static void
12832 f_mode(argvars, rettv)
12833 typval_T *argvars;
12834 typval_T *rettv;
12836 char_u buf[2];
12838 #ifdef FEAT_VISUAL
12839 if (VIsual_active)
12841 if (VIsual_select)
12842 buf[0] = VIsual_mode + 's' - 'v';
12843 else
12844 buf[0] = VIsual_mode;
12846 else
12847 #endif
12848 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE)
12849 buf[0] = 'r';
12850 else if (State & INSERT)
12852 if (State & REPLACE_FLAG)
12853 buf[0] = 'R';
12854 else
12855 buf[0] = 'i';
12857 else if (State & CMDLINE)
12858 buf[0] = 'c';
12859 else
12860 buf[0] = 'n';
12862 buf[1] = NUL;
12863 rettv->vval.v_string = vim_strsave(buf);
12864 rettv->v_type = VAR_STRING;
12868 * "nextnonblank()" function
12870 static void
12871 f_nextnonblank(argvars, rettv)
12872 typval_T *argvars;
12873 typval_T *rettv;
12875 linenr_T lnum;
12877 for (lnum = get_tv_lnum(argvars); ; ++lnum)
12879 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
12881 lnum = 0;
12882 break;
12884 if (*skipwhite(ml_get(lnum)) != NUL)
12885 break;
12887 rettv->vval.v_number = lnum;
12891 * "nr2char()" function
12893 static void
12894 f_nr2char(argvars, rettv)
12895 typval_T *argvars;
12896 typval_T *rettv;
12898 char_u buf[NUMBUFLEN];
12900 #ifdef FEAT_MBYTE
12901 if (has_mbyte)
12902 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
12903 else
12904 #endif
12906 buf[0] = (char_u)get_tv_number(&argvars[0]);
12907 buf[1] = NUL;
12909 rettv->v_type = VAR_STRING;
12910 rettv->vval.v_string = vim_strsave(buf);
12914 * "pathshorten()" function
12916 static void
12917 f_pathshorten(argvars, rettv)
12918 typval_T *argvars;
12919 typval_T *rettv;
12921 char_u *p;
12923 rettv->v_type = VAR_STRING;
12924 p = get_tv_string_chk(&argvars[0]);
12925 if (p == NULL)
12926 rettv->vval.v_string = NULL;
12927 else
12929 p = vim_strsave(p);
12930 rettv->vval.v_string = p;
12931 if (p != NULL)
12932 shorten_dir(p);
12937 * "prevnonblank()" function
12939 static void
12940 f_prevnonblank(argvars, rettv)
12941 typval_T *argvars;
12942 typval_T *rettv;
12944 linenr_T lnum;
12946 lnum = get_tv_lnum(argvars);
12947 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
12948 lnum = 0;
12949 else
12950 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
12951 --lnum;
12952 rettv->vval.v_number = lnum;
12955 #ifdef HAVE_STDARG_H
12956 /* This dummy va_list is here because:
12957 * - passing a NULL pointer doesn't work when va_list isn't a pointer
12958 * - locally in the function results in a "used before set" warning
12959 * - using va_start() to initialize it gives "function with fixed args" error */
12960 static va_list ap;
12961 #endif
12964 * "printf()" function
12966 static void
12967 f_printf(argvars, rettv)
12968 typval_T *argvars;
12969 typval_T *rettv;
12971 rettv->v_type = VAR_STRING;
12972 rettv->vval.v_string = NULL;
12973 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
12975 char_u buf[NUMBUFLEN];
12976 int len;
12977 char_u *s;
12978 int saved_did_emsg = did_emsg;
12979 char *fmt;
12981 /* Get the required length, allocate the buffer and do it for real. */
12982 did_emsg = FALSE;
12983 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
12984 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
12985 if (!did_emsg)
12987 s = alloc(len + 1);
12988 if (s != NULL)
12990 rettv->vval.v_string = s;
12991 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
12994 did_emsg |= saved_did_emsg;
12996 #endif
13000 * "pumvisible()" function
13002 /*ARGSUSED*/
13003 static void
13004 f_pumvisible(argvars, rettv)
13005 typval_T *argvars;
13006 typval_T *rettv;
13008 rettv->vval.v_number = 0;
13009 #ifdef FEAT_INS_EXPAND
13010 if (pum_visible())
13011 rettv->vval.v_number = 1;
13012 #endif
13016 * "range()" function
13018 static void
13019 f_range(argvars, rettv)
13020 typval_T *argvars;
13021 typval_T *rettv;
13023 long start;
13024 long end;
13025 long stride = 1;
13026 long i;
13027 int error = FALSE;
13029 start = get_tv_number_chk(&argvars[0], &error);
13030 if (argvars[1].v_type == VAR_UNKNOWN)
13032 end = start - 1;
13033 start = 0;
13035 else
13037 end = get_tv_number_chk(&argvars[1], &error);
13038 if (argvars[2].v_type != VAR_UNKNOWN)
13039 stride = get_tv_number_chk(&argvars[2], &error);
13042 rettv->vval.v_number = 0;
13043 if (error)
13044 return; /* type error; errmsg already given */
13045 if (stride == 0)
13046 EMSG(_("E726: Stride is zero"));
13047 else if (stride > 0 ? end + 1 < start : end - 1 > start)
13048 EMSG(_("E727: Start past end"));
13049 else
13051 if (rettv_list_alloc(rettv) == OK)
13052 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
13053 if (list_append_number(rettv->vval.v_list,
13054 (varnumber_T)i) == FAIL)
13055 break;
13060 * "readfile()" function
13062 static void
13063 f_readfile(argvars, rettv)
13064 typval_T *argvars;
13065 typval_T *rettv;
13067 int binary = FALSE;
13068 char_u *fname;
13069 FILE *fd;
13070 listitem_T *li;
13071 #define FREAD_SIZE 200 /* optimized for text lines */
13072 char_u buf[FREAD_SIZE];
13073 int readlen; /* size of last fread() */
13074 int buflen; /* nr of valid chars in buf[] */
13075 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
13076 int tolist; /* first byte in buf[] still to be put in list */
13077 int chop; /* how many CR to chop off */
13078 char_u *prev = NULL; /* previously read bytes, if any */
13079 int prevlen = 0; /* length of "prev" if not NULL */
13080 char_u *s;
13081 int len;
13082 long maxline = MAXLNUM;
13083 long cnt = 0;
13085 if (argvars[1].v_type != VAR_UNKNOWN)
13087 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
13088 binary = TRUE;
13089 if (argvars[2].v_type != VAR_UNKNOWN)
13090 maxline = get_tv_number(&argvars[2]);
13093 if (rettv_list_alloc(rettv) == FAIL)
13094 return;
13096 /* Always open the file in binary mode, library functions have a mind of
13097 * their own about CR-LF conversion. */
13098 fname = get_tv_string(&argvars[0]);
13099 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
13101 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
13102 return;
13105 filtd = 0;
13106 while (cnt < maxline || maxline < 0)
13108 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
13109 buflen = filtd + readlen;
13110 tolist = 0;
13111 for ( ; filtd < buflen || readlen <= 0; ++filtd)
13113 if (buf[filtd] == '\n' || readlen <= 0)
13115 /* Only when in binary mode add an empty list item when the
13116 * last line ends in a '\n'. */
13117 if (!binary && readlen == 0 && filtd == 0)
13118 break;
13120 /* Found end-of-line or end-of-file: add a text line to the
13121 * list. */
13122 chop = 0;
13123 if (!binary)
13124 while (filtd - chop - 1 >= tolist
13125 && buf[filtd - chop - 1] == '\r')
13126 ++chop;
13127 len = filtd - tolist - chop;
13128 if (prev == NULL)
13129 s = vim_strnsave(buf + tolist, len);
13130 else
13132 s = alloc((unsigned)(prevlen + len + 1));
13133 if (s != NULL)
13135 mch_memmove(s, prev, prevlen);
13136 vim_free(prev);
13137 prev = NULL;
13138 mch_memmove(s + prevlen, buf + tolist, len);
13139 s[prevlen + len] = NUL;
13142 tolist = filtd + 1;
13144 li = listitem_alloc();
13145 if (li == NULL)
13147 vim_free(s);
13148 break;
13150 li->li_tv.v_type = VAR_STRING;
13151 li->li_tv.v_lock = 0;
13152 li->li_tv.vval.v_string = s;
13153 list_append(rettv->vval.v_list, li);
13155 if (++cnt >= maxline && maxline >= 0)
13156 break;
13157 if (readlen <= 0)
13158 break;
13160 else if (buf[filtd] == NUL)
13161 buf[filtd] = '\n';
13163 if (readlen <= 0)
13164 break;
13166 if (tolist == 0)
13168 /* "buf" is full, need to move text to an allocated buffer */
13169 if (prev == NULL)
13171 prev = vim_strnsave(buf, buflen);
13172 prevlen = buflen;
13174 else
13176 s = alloc((unsigned)(prevlen + buflen));
13177 if (s != NULL)
13179 mch_memmove(s, prev, prevlen);
13180 mch_memmove(s + prevlen, buf, buflen);
13181 vim_free(prev);
13182 prev = s;
13183 prevlen += buflen;
13186 filtd = 0;
13188 else
13190 mch_memmove(buf, buf + tolist, buflen - tolist);
13191 filtd -= tolist;
13196 * For a negative line count use only the lines at the end of the file,
13197 * free the rest.
13199 if (maxline < 0)
13200 while (cnt > -maxline)
13202 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
13203 --cnt;
13206 vim_free(prev);
13207 fclose(fd);
13210 #if defined(FEAT_RELTIME)
13211 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
13214 * Convert a List to proftime_T.
13215 * Return FAIL when there is something wrong.
13217 static int
13218 list2proftime(arg, tm)
13219 typval_T *arg;
13220 proftime_T *tm;
13222 long n1, n2;
13223 int error = FALSE;
13225 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
13226 || arg->vval.v_list->lv_len != 2)
13227 return FAIL;
13228 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
13229 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
13230 # ifdef WIN3264
13231 tm->HighPart = n1;
13232 tm->LowPart = n2;
13233 # else
13234 tm->tv_sec = n1;
13235 tm->tv_usec = n2;
13236 # endif
13237 return error ? FAIL : OK;
13239 #endif /* FEAT_RELTIME */
13242 * "reltime()" function
13244 static void
13245 f_reltime(argvars, rettv)
13246 typval_T *argvars;
13247 typval_T *rettv;
13249 #ifdef FEAT_RELTIME
13250 proftime_T res;
13251 proftime_T start;
13253 if (argvars[0].v_type == VAR_UNKNOWN)
13255 /* No arguments: get current time. */
13256 profile_start(&res);
13258 else if (argvars[1].v_type == VAR_UNKNOWN)
13260 if (list2proftime(&argvars[0], &res) == FAIL)
13261 return;
13262 profile_end(&res);
13264 else
13266 /* Two arguments: compute the difference. */
13267 if (list2proftime(&argvars[0], &start) == FAIL
13268 || list2proftime(&argvars[1], &res) == FAIL)
13269 return;
13270 profile_sub(&res, &start);
13273 if (rettv_list_alloc(rettv) == OK)
13275 long n1, n2;
13277 # ifdef WIN3264
13278 n1 = res.HighPart;
13279 n2 = res.LowPart;
13280 # else
13281 n1 = res.tv_sec;
13282 n2 = res.tv_usec;
13283 # endif
13284 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
13285 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
13287 #endif
13291 * "reltimestr()" function
13293 static void
13294 f_reltimestr(argvars, rettv)
13295 typval_T *argvars;
13296 typval_T *rettv;
13298 #ifdef FEAT_RELTIME
13299 proftime_T tm;
13300 #endif
13302 rettv->v_type = VAR_STRING;
13303 rettv->vval.v_string = NULL;
13304 #ifdef FEAT_RELTIME
13305 if (list2proftime(&argvars[0], &tm) == OK)
13306 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
13307 #endif
13310 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
13311 static void make_connection __ARGS((void));
13312 static int check_connection __ARGS((void));
13314 static void
13315 make_connection()
13317 if (X_DISPLAY == NULL
13318 # ifdef FEAT_GUI
13319 && !gui.in_use
13320 # endif
13323 x_force_connect = TRUE;
13324 setup_term_clip();
13325 x_force_connect = FALSE;
13329 static int
13330 check_connection()
13332 make_connection();
13333 if (X_DISPLAY == NULL)
13335 EMSG(_("E240: No connection to Vim server"));
13336 return FAIL;
13338 return OK;
13340 #endif
13342 #ifdef FEAT_CLIENTSERVER
13343 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
13345 static void
13346 remote_common(argvars, rettv, expr)
13347 typval_T *argvars;
13348 typval_T *rettv;
13349 int expr;
13351 char_u *server_name;
13352 char_u *keys;
13353 char_u *r = NULL;
13354 char_u buf[NUMBUFLEN];
13355 # ifdef WIN32
13356 HWND w;
13357 # elif defined(FEAT_X11)
13358 Window w;
13359 # elif defined(MAC_CLIENTSERVER)
13360 int w; // This is the port number ('w' is a bit confusing)
13361 # endif
13363 if (check_restricted() || check_secure())
13364 return;
13366 # ifdef FEAT_X11
13367 if (check_connection() == FAIL)
13368 return;
13369 # endif
13371 server_name = get_tv_string_chk(&argvars[0]);
13372 if (server_name == NULL)
13373 return; /* type error; errmsg already given */
13374 keys = get_tv_string_buf(&argvars[1], buf);
13375 # ifdef WIN32
13376 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
13377 # elif defined(FEAT_X11)
13378 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
13379 < 0)
13380 # elif defined(MAC_CLIENTSERVER)
13381 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
13382 # endif
13384 if (r != NULL)
13385 EMSG(r); /* sending worked but evaluation failed */
13386 else
13387 EMSG2(_("E241: Unable to send to %s"), server_name);
13388 return;
13391 rettv->vval.v_string = r;
13393 if (argvars[2].v_type != VAR_UNKNOWN)
13395 dictitem_T v;
13396 char_u str[30];
13397 char_u *idvar;
13399 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
13400 v.di_tv.v_type = VAR_STRING;
13401 v.di_tv.vval.v_string = vim_strsave(str);
13402 idvar = get_tv_string_chk(&argvars[2]);
13403 if (idvar != NULL)
13404 set_var(idvar, &v.di_tv, FALSE);
13405 vim_free(v.di_tv.vval.v_string);
13408 #endif
13411 * "remote_expr()" function
13413 /*ARGSUSED*/
13414 static void
13415 f_remote_expr(argvars, rettv)
13416 typval_T *argvars;
13417 typval_T *rettv;
13419 rettv->v_type = VAR_STRING;
13420 rettv->vval.v_string = NULL;
13421 #ifdef FEAT_CLIENTSERVER
13422 remote_common(argvars, rettv, TRUE);
13423 #endif
13427 * "remote_foreground()" function
13429 /*ARGSUSED*/
13430 static void
13431 f_remote_foreground(argvars, rettv)
13432 typval_T *argvars;
13433 typval_T *rettv;
13435 rettv->vval.v_number = 0;
13436 #ifdef FEAT_CLIENTSERVER
13437 # ifdef WIN32
13438 /* On Win32 it's done in this application. */
13440 char_u *server_name = get_tv_string_chk(&argvars[0]);
13442 if (server_name != NULL)
13443 serverForeground(server_name);
13445 # elif defined(FEAT_X11) || defined(MAC_CLIENTSERVER)
13446 /* Send a foreground() expression to the server. */
13447 argvars[1].v_type = VAR_STRING;
13448 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
13449 argvars[2].v_type = VAR_UNKNOWN;
13450 remote_common(argvars, rettv, TRUE);
13451 vim_free(argvars[1].vval.v_string);
13452 # endif
13453 #endif
13456 /*ARGSUSED*/
13457 static void
13458 f_remote_peek(argvars, rettv)
13459 typval_T *argvars;
13460 typval_T *rettv;
13462 #ifdef FEAT_CLIENTSERVER
13463 dictitem_T v;
13464 char_u *s = NULL;
13465 # ifdef WIN32
13466 long_u n = 0;
13467 # endif
13468 char_u *serverid;
13470 if (check_restricted() || check_secure())
13472 rettv->vval.v_number = -1;
13473 return;
13475 serverid = get_tv_string_chk(&argvars[0]);
13476 if (serverid == NULL)
13478 rettv->vval.v_number = -1;
13479 return; /* type error; errmsg already given */
13481 # ifdef WIN32
13482 sscanf(serverid, SCANF_HEX_LONG_U, &n);
13483 if (n == 0)
13484 rettv->vval.v_number = -1;
13485 else
13487 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
13488 rettv->vval.v_number = (s != NULL);
13490 # elif defined(FEAT_X11)
13491 rettv->vval.v_number = 0;
13492 if (check_connection() == FAIL)
13493 return;
13495 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
13496 serverStrToWin(serverid), &s);
13497 # elif defined(MAC_CLIENTSERVER)
13498 rettv->vval.v_number = serverPeekReply(serverStrToPort(serverid), &s);
13499 # endif
13501 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
13503 char_u *retvar;
13505 v.di_tv.v_type = VAR_STRING;
13506 v.di_tv.vval.v_string = vim_strsave(s);
13507 retvar = get_tv_string_chk(&argvars[1]);
13508 if (retvar != NULL)
13509 set_var(retvar, &v.di_tv, FALSE);
13510 vim_free(v.di_tv.vval.v_string);
13512 #else
13513 rettv->vval.v_number = -1;
13514 #endif
13517 /*ARGSUSED*/
13518 static void
13519 f_remote_read(argvars, rettv)
13520 typval_T *argvars;
13521 typval_T *rettv;
13523 char_u *r = NULL;
13525 #ifdef FEAT_CLIENTSERVER
13526 char_u *serverid = get_tv_string_chk(&argvars[0]);
13528 if (serverid != NULL && !check_restricted() && !check_secure())
13530 # ifdef WIN32
13531 /* The server's HWND is encoded in the 'id' parameter */
13532 long_u n = 0;
13534 sscanf(serverid, SCANF_HEX_LONG_U, &n);
13535 if (n != 0)
13536 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
13537 if (r == NULL)
13538 # elif defined(FEAT_X11)
13539 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
13540 serverStrToWin(serverid), &r, FALSE) < 0)
13541 # elif defined(MAC_CLIENTSERVER)
13542 if (serverReadReply(serverStrToPort(serverid), &r) < 0)
13543 # endif
13544 EMSG(_("E277: Unable to read a server reply"));
13546 #endif
13547 rettv->v_type = VAR_STRING;
13548 rettv->vval.v_string = r;
13552 * "remote_send()" function
13554 /*ARGSUSED*/
13555 static void
13556 f_remote_send(argvars, rettv)
13557 typval_T *argvars;
13558 typval_T *rettv;
13560 rettv->v_type = VAR_STRING;
13561 rettv->vval.v_string = NULL;
13562 #ifdef FEAT_CLIENTSERVER
13563 remote_common(argvars, rettv, FALSE);
13564 #endif
13568 * "remove()" function
13570 static void
13571 f_remove(argvars, rettv)
13572 typval_T *argvars;
13573 typval_T *rettv;
13575 list_T *l;
13576 listitem_T *item, *item2;
13577 listitem_T *li;
13578 long idx;
13579 long end;
13580 char_u *key;
13581 dict_T *d;
13582 dictitem_T *di;
13584 rettv->vval.v_number = 0;
13585 if (argvars[0].v_type == VAR_DICT)
13587 if (argvars[2].v_type != VAR_UNKNOWN)
13588 EMSG2(_(e_toomanyarg), "remove()");
13589 else if ((d = argvars[0].vval.v_dict) != NULL
13590 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
13592 key = get_tv_string_chk(&argvars[1]);
13593 if (key != NULL)
13595 di = dict_find(d, key, -1);
13596 if (di == NULL)
13597 EMSG2(_(e_dictkey), key);
13598 else
13600 *rettv = di->di_tv;
13601 init_tv(&di->di_tv);
13602 dictitem_remove(d, di);
13607 else if (argvars[0].v_type != VAR_LIST)
13608 EMSG2(_(e_listdictarg), "remove()");
13609 else if ((l = argvars[0].vval.v_list) != NULL
13610 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
13612 int error = FALSE;
13614 idx = get_tv_number_chk(&argvars[1], &error);
13615 if (error)
13616 ; /* type error: do nothing, errmsg already given */
13617 else if ((item = list_find(l, idx)) == NULL)
13618 EMSGN(_(e_listidx), idx);
13619 else
13621 if (argvars[2].v_type == VAR_UNKNOWN)
13623 /* Remove one item, return its value. */
13624 list_remove(l, item, item);
13625 *rettv = item->li_tv;
13626 vim_free(item);
13628 else
13630 /* Remove range of items, return list with values. */
13631 end = get_tv_number_chk(&argvars[2], &error);
13632 if (error)
13633 ; /* type error: do nothing */
13634 else if ((item2 = list_find(l, end)) == NULL)
13635 EMSGN(_(e_listidx), end);
13636 else
13638 int cnt = 0;
13640 for (li = item; li != NULL; li = li->li_next)
13642 ++cnt;
13643 if (li == item2)
13644 break;
13646 if (li == NULL) /* didn't find "item2" after "item" */
13647 EMSG(_(e_invrange));
13648 else
13650 list_remove(l, item, item2);
13651 if (rettv_list_alloc(rettv) == OK)
13653 l = rettv->vval.v_list;
13654 l->lv_first = item;
13655 l->lv_last = item2;
13656 item->li_prev = NULL;
13657 item2->li_next = NULL;
13658 l->lv_len = cnt;
13668 * "rename({from}, {to})" function
13670 static void
13671 f_rename(argvars, rettv)
13672 typval_T *argvars;
13673 typval_T *rettv;
13675 char_u buf[NUMBUFLEN];
13677 if (check_restricted() || check_secure())
13678 rettv->vval.v_number = -1;
13679 else
13680 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
13681 get_tv_string_buf(&argvars[1], buf));
13685 * "repeat()" function
13687 /*ARGSUSED*/
13688 static void
13689 f_repeat(argvars, rettv)
13690 typval_T *argvars;
13691 typval_T *rettv;
13693 char_u *p;
13694 int n;
13695 int slen;
13696 int len;
13697 char_u *r;
13698 int i;
13700 n = get_tv_number(&argvars[1]);
13701 if (argvars[0].v_type == VAR_LIST)
13703 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
13704 while (n-- > 0)
13705 if (list_extend(rettv->vval.v_list,
13706 argvars[0].vval.v_list, NULL) == FAIL)
13707 break;
13709 else
13711 p = get_tv_string(&argvars[0]);
13712 rettv->v_type = VAR_STRING;
13713 rettv->vval.v_string = NULL;
13715 slen = (int)STRLEN(p);
13716 len = slen * n;
13717 if (len <= 0)
13718 return;
13720 r = alloc(len + 1);
13721 if (r != NULL)
13723 for (i = 0; i < n; i++)
13724 mch_memmove(r + i * slen, p, (size_t)slen);
13725 r[len] = NUL;
13728 rettv->vval.v_string = r;
13733 * "resolve()" function
13735 static void
13736 f_resolve(argvars, rettv)
13737 typval_T *argvars;
13738 typval_T *rettv;
13740 char_u *p;
13742 p = get_tv_string(&argvars[0]);
13743 #ifdef FEAT_SHORTCUT
13745 char_u *v = NULL;
13747 v = mch_resolve_shortcut(p);
13748 if (v != NULL)
13749 rettv->vval.v_string = v;
13750 else
13751 rettv->vval.v_string = vim_strsave(p);
13753 #else
13754 # ifdef HAVE_READLINK
13756 char_u buf[MAXPATHL + 1];
13757 char_u *cpy;
13758 int len;
13759 char_u *remain = NULL;
13760 char_u *q;
13761 int is_relative_to_current = FALSE;
13762 int has_trailing_pathsep = FALSE;
13763 int limit = 100;
13765 p = vim_strsave(p);
13767 if (p[0] == '.' && (vim_ispathsep(p[1])
13768 || (p[1] == '.' && (vim_ispathsep(p[2])))))
13769 is_relative_to_current = TRUE;
13771 len = STRLEN(p);
13772 if (len > 0 && after_pathsep(p, p + len))
13773 has_trailing_pathsep = TRUE;
13775 q = getnextcomp(p);
13776 if (*q != NUL)
13778 /* Separate the first path component in "p", and keep the
13779 * remainder (beginning with the path separator). */
13780 remain = vim_strsave(q - 1);
13781 q[-1] = NUL;
13784 for (;;)
13786 for (;;)
13788 len = readlink((char *)p, (char *)buf, MAXPATHL);
13789 if (len <= 0)
13790 break;
13791 buf[len] = NUL;
13793 if (limit-- == 0)
13795 vim_free(p);
13796 vim_free(remain);
13797 EMSG(_("E655: Too many symbolic links (cycle?)"));
13798 rettv->vval.v_string = NULL;
13799 goto fail;
13802 /* Ensure that the result will have a trailing path separator
13803 * if the argument has one. */
13804 if (remain == NULL && has_trailing_pathsep)
13805 add_pathsep(buf);
13807 /* Separate the first path component in the link value and
13808 * concatenate the remainders. */
13809 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
13810 if (*q != NUL)
13812 if (remain == NULL)
13813 remain = vim_strsave(q - 1);
13814 else
13816 cpy = concat_str(q - 1, remain);
13817 if (cpy != NULL)
13819 vim_free(remain);
13820 remain = cpy;
13823 q[-1] = NUL;
13826 q = gettail(p);
13827 if (q > p && *q == NUL)
13829 /* Ignore trailing path separator. */
13830 q[-1] = NUL;
13831 q = gettail(p);
13833 if (q > p && !mch_isFullName(buf))
13835 /* symlink is relative to directory of argument */
13836 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
13837 if (cpy != NULL)
13839 STRCPY(cpy, p);
13840 STRCPY(gettail(cpy), buf);
13841 vim_free(p);
13842 p = cpy;
13845 else
13847 vim_free(p);
13848 p = vim_strsave(buf);
13852 if (remain == NULL)
13853 break;
13855 /* Append the first path component of "remain" to "p". */
13856 q = getnextcomp(remain + 1);
13857 len = q - remain - (*q != NUL);
13858 cpy = vim_strnsave(p, STRLEN(p) + len);
13859 if (cpy != NULL)
13861 STRNCAT(cpy, remain, len);
13862 vim_free(p);
13863 p = cpy;
13865 /* Shorten "remain". */
13866 if (*q != NUL)
13867 mch_memmove(remain, q - 1, STRLEN(q - 1) + 1);
13868 else
13870 vim_free(remain);
13871 remain = NULL;
13875 /* If the result is a relative path name, make it explicitly relative to
13876 * the current directory if and only if the argument had this form. */
13877 if (!vim_ispathsep(*p))
13879 if (is_relative_to_current
13880 && *p != NUL
13881 && !(p[0] == '.'
13882 && (p[1] == NUL
13883 || vim_ispathsep(p[1])
13884 || (p[1] == '.'
13885 && (p[2] == NUL
13886 || vim_ispathsep(p[2]))))))
13888 /* Prepend "./". */
13889 cpy = concat_str((char_u *)"./", p);
13890 if (cpy != NULL)
13892 vim_free(p);
13893 p = cpy;
13896 else if (!is_relative_to_current)
13898 /* Strip leading "./". */
13899 q = p;
13900 while (q[0] == '.' && vim_ispathsep(q[1]))
13901 q += 2;
13902 if (q > p)
13903 mch_memmove(p, p + 2, STRLEN(p + 2) + (size_t)1);
13907 /* Ensure that the result will have no trailing path separator
13908 * if the argument had none. But keep "/" or "//". */
13909 if (!has_trailing_pathsep)
13911 q = p + STRLEN(p);
13912 if (after_pathsep(p, q))
13913 *gettail_sep(p) = NUL;
13916 rettv->vval.v_string = p;
13918 # else
13919 rettv->vval.v_string = vim_strsave(p);
13920 # endif
13921 #endif
13923 simplify_filename(rettv->vval.v_string);
13925 #ifdef HAVE_READLINK
13926 fail:
13927 #endif
13928 rettv->v_type = VAR_STRING;
13932 * "reverse({list})" function
13934 static void
13935 f_reverse(argvars, rettv)
13936 typval_T *argvars;
13937 typval_T *rettv;
13939 list_T *l;
13940 listitem_T *li, *ni;
13942 rettv->vval.v_number = 0;
13943 if (argvars[0].v_type != VAR_LIST)
13944 EMSG2(_(e_listarg), "reverse()");
13945 else if ((l = argvars[0].vval.v_list) != NULL
13946 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
13948 li = l->lv_last;
13949 l->lv_first = l->lv_last = NULL;
13950 l->lv_len = 0;
13951 while (li != NULL)
13953 ni = li->li_prev;
13954 list_append(l, li);
13955 li = ni;
13957 rettv->vval.v_list = l;
13958 rettv->v_type = VAR_LIST;
13959 ++l->lv_refcount;
13963 #define SP_NOMOVE 0x01 /* don't move cursor */
13964 #define SP_REPEAT 0x02 /* repeat to find outer pair */
13965 #define SP_RETCOUNT 0x04 /* return matchcount */
13966 #define SP_SETPCMARK 0x08 /* set previous context mark */
13967 #define SP_START 0x10 /* accept match at start position */
13968 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
13969 #define SP_END 0x40 /* leave cursor at end of match */
13971 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
13974 * Get flags for a search function.
13975 * Possibly sets "p_ws".
13976 * Returns BACKWARD, FORWARD or zero (for an error).
13978 static int
13979 get_search_arg(varp, flagsp)
13980 typval_T *varp;
13981 int *flagsp;
13983 int dir = FORWARD;
13984 char_u *flags;
13985 char_u nbuf[NUMBUFLEN];
13986 int mask;
13988 if (varp->v_type != VAR_UNKNOWN)
13990 flags = get_tv_string_buf_chk(varp, nbuf);
13991 if (flags == NULL)
13992 return 0; /* type error; errmsg already given */
13993 while (*flags != NUL)
13995 switch (*flags)
13997 case 'b': dir = BACKWARD; break;
13998 case 'w': p_ws = TRUE; break;
13999 case 'W': p_ws = FALSE; break;
14000 default: mask = 0;
14001 if (flagsp != NULL)
14002 switch (*flags)
14004 case 'c': mask = SP_START; break;
14005 case 'e': mask = SP_END; break;
14006 case 'm': mask = SP_RETCOUNT; break;
14007 case 'n': mask = SP_NOMOVE; break;
14008 case 'p': mask = SP_SUBPAT; break;
14009 case 'r': mask = SP_REPEAT; break;
14010 case 's': mask = SP_SETPCMARK; break;
14012 if (mask == 0)
14014 EMSG2(_(e_invarg2), flags);
14015 dir = 0;
14017 else
14018 *flagsp |= mask;
14020 if (dir == 0)
14021 break;
14022 ++flags;
14025 return dir;
14029 * Shared by search() and searchpos() functions
14031 static int
14032 search_cmn(argvars, match_pos, flagsp)
14033 typval_T *argvars;
14034 pos_T *match_pos;
14035 int *flagsp;
14037 int flags;
14038 char_u *pat;
14039 pos_T pos;
14040 pos_T save_cursor;
14041 int save_p_ws = p_ws;
14042 int dir;
14043 int retval = 0; /* default: FAIL */
14044 long lnum_stop = 0;
14045 proftime_T tm;
14046 #ifdef FEAT_RELTIME
14047 long time_limit = 0;
14048 #endif
14049 int options = SEARCH_KEEP;
14050 int subpatnum;
14052 pat = get_tv_string(&argvars[0]);
14053 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
14054 if (dir == 0)
14055 goto theend;
14056 flags = *flagsp;
14057 if (flags & SP_START)
14058 options |= SEARCH_START;
14059 if (flags & SP_END)
14060 options |= SEARCH_END;
14062 /* Optional arguments: line number to stop searching and timeout. */
14063 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
14065 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
14066 if (lnum_stop < 0)
14067 goto theend;
14068 #ifdef FEAT_RELTIME
14069 if (argvars[3].v_type != VAR_UNKNOWN)
14071 time_limit = get_tv_number_chk(&argvars[3], NULL);
14072 if (time_limit < 0)
14073 goto theend;
14075 #endif
14078 #ifdef FEAT_RELTIME
14079 /* Set the time limit, if there is one. */
14080 profile_setlimit(time_limit, &tm);
14081 #endif
14084 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
14085 * Check to make sure only those flags are set.
14086 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
14087 * flags cannot be set. Check for that condition also.
14089 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
14090 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14092 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
14093 goto theend;
14096 pos = save_cursor = curwin->w_cursor;
14097 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14098 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
14099 if (subpatnum != FAIL)
14101 if (flags & SP_SUBPAT)
14102 retval = subpatnum;
14103 else
14104 retval = pos.lnum;
14105 if (flags & SP_SETPCMARK)
14106 setpcmark();
14107 curwin->w_cursor = pos;
14108 if (match_pos != NULL)
14110 /* Store the match cursor position */
14111 match_pos->lnum = pos.lnum;
14112 match_pos->col = pos.col + 1;
14114 /* "/$" will put the cursor after the end of the line, may need to
14115 * correct that here */
14116 check_cursor();
14119 /* If 'n' flag is used: restore cursor position. */
14120 if (flags & SP_NOMOVE)
14121 curwin->w_cursor = save_cursor;
14122 else
14123 curwin->w_set_curswant = TRUE;
14124 theend:
14125 p_ws = save_p_ws;
14127 return retval;
14131 * "search()" function
14133 static void
14134 f_search(argvars, rettv)
14135 typval_T *argvars;
14136 typval_T *rettv;
14138 int flags = 0;
14140 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
14144 * "searchdecl()" function
14146 static void
14147 f_searchdecl(argvars, rettv)
14148 typval_T *argvars;
14149 typval_T *rettv;
14151 int locally = 1;
14152 int thisblock = 0;
14153 int error = FALSE;
14154 char_u *name;
14156 rettv->vval.v_number = 1; /* default: FAIL */
14158 name = get_tv_string_chk(&argvars[0]);
14159 if (argvars[1].v_type != VAR_UNKNOWN)
14161 locally = get_tv_number_chk(&argvars[1], &error) == 0;
14162 if (!error && argvars[2].v_type != VAR_UNKNOWN)
14163 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
14165 if (!error && name != NULL)
14166 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
14167 locally, thisblock, SEARCH_KEEP) == FAIL;
14171 * Used by searchpair() and searchpairpos()
14173 static int
14174 searchpair_cmn(argvars, match_pos)
14175 typval_T *argvars;
14176 pos_T *match_pos;
14178 char_u *spat, *mpat, *epat;
14179 char_u *skip;
14180 int save_p_ws = p_ws;
14181 int dir;
14182 int flags = 0;
14183 char_u nbuf1[NUMBUFLEN];
14184 char_u nbuf2[NUMBUFLEN];
14185 char_u nbuf3[NUMBUFLEN];
14186 int retval = 0; /* default: FAIL */
14187 long lnum_stop = 0;
14188 long time_limit = 0;
14190 /* Get the three pattern arguments: start, middle, end. */
14191 spat = get_tv_string_chk(&argvars[0]);
14192 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
14193 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
14194 if (spat == NULL || mpat == NULL || epat == NULL)
14195 goto theend; /* type error */
14197 /* Handle the optional fourth argument: flags */
14198 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
14199 if (dir == 0)
14200 goto theend;
14202 /* Don't accept SP_END or SP_SUBPAT.
14203 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
14205 if ((flags & (SP_END | SP_SUBPAT)) != 0
14206 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14208 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
14209 goto theend;
14212 /* Using 'r' implies 'W', otherwise it doesn't work. */
14213 if (flags & SP_REPEAT)
14214 p_ws = FALSE;
14216 /* Optional fifth argument: skip expression */
14217 if (argvars[3].v_type == VAR_UNKNOWN
14218 || argvars[4].v_type == VAR_UNKNOWN)
14219 skip = (char_u *)"";
14220 else
14222 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
14223 if (argvars[5].v_type != VAR_UNKNOWN)
14225 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
14226 if (lnum_stop < 0)
14227 goto theend;
14228 #ifdef FEAT_RELTIME
14229 if (argvars[6].v_type != VAR_UNKNOWN)
14231 time_limit = get_tv_number_chk(&argvars[6], NULL);
14232 if (time_limit < 0)
14233 goto theend;
14235 #endif
14238 if (skip == NULL)
14239 goto theend; /* type error */
14241 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
14242 match_pos, lnum_stop, time_limit);
14244 theend:
14245 p_ws = save_p_ws;
14247 return retval;
14251 * "searchpair()" function
14253 static void
14254 f_searchpair(argvars, rettv)
14255 typval_T *argvars;
14256 typval_T *rettv;
14258 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
14262 * "searchpairpos()" function
14264 static void
14265 f_searchpairpos(argvars, rettv)
14266 typval_T *argvars;
14267 typval_T *rettv;
14269 pos_T match_pos;
14270 int lnum = 0;
14271 int col = 0;
14273 rettv->vval.v_number = 0;
14275 if (rettv_list_alloc(rettv) == FAIL)
14276 return;
14278 if (searchpair_cmn(argvars, &match_pos) > 0)
14280 lnum = match_pos.lnum;
14281 col = match_pos.col;
14284 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14285 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14289 * Search for a start/middle/end thing.
14290 * Used by searchpair(), see its documentation for the details.
14291 * Returns 0 or -1 for no match,
14293 long
14294 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
14295 lnum_stop, time_limit)
14296 char_u *spat; /* start pattern */
14297 char_u *mpat; /* middle pattern */
14298 char_u *epat; /* end pattern */
14299 int dir; /* BACKWARD or FORWARD */
14300 char_u *skip; /* skip expression */
14301 int flags; /* SP_SETPCMARK and other SP_ values */
14302 pos_T *match_pos;
14303 linenr_T lnum_stop; /* stop at this line if not zero */
14304 long time_limit; /* stop after this many msec */
14306 char_u *save_cpo;
14307 char_u *pat, *pat2 = NULL, *pat3 = NULL;
14308 long retval = 0;
14309 pos_T pos;
14310 pos_T firstpos;
14311 pos_T foundpos;
14312 pos_T save_cursor;
14313 pos_T save_pos;
14314 int n;
14315 int r;
14316 int nest = 1;
14317 int err;
14318 int options = SEARCH_KEEP;
14319 proftime_T tm;
14321 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
14322 save_cpo = p_cpo;
14323 p_cpo = (char_u *)"";
14325 #ifdef FEAT_RELTIME
14326 /* Set the time limit, if there is one. */
14327 profile_setlimit(time_limit, &tm);
14328 #endif
14330 /* Make two search patterns: start/end (pat2, for in nested pairs) and
14331 * start/middle/end (pat3, for the top pair). */
14332 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
14333 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
14334 if (pat2 == NULL || pat3 == NULL)
14335 goto theend;
14336 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
14337 if (*mpat == NUL)
14338 STRCPY(pat3, pat2);
14339 else
14340 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
14341 spat, epat, mpat);
14342 if (flags & SP_START)
14343 options |= SEARCH_START;
14345 save_cursor = curwin->w_cursor;
14346 pos = curwin->w_cursor;
14347 clearpos(&firstpos);
14348 clearpos(&foundpos);
14349 pat = pat3;
14350 for (;;)
14352 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14353 options, RE_SEARCH, lnum_stop, &tm);
14354 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
14355 /* didn't find it or found the first match again: FAIL */
14356 break;
14358 if (firstpos.lnum == 0)
14359 firstpos = pos;
14360 if (equalpos(pos, foundpos))
14362 /* Found the same position again. Can happen with a pattern that
14363 * has "\zs" at the end and searching backwards. Advance one
14364 * character and try again. */
14365 if (dir == BACKWARD)
14366 decl(&pos);
14367 else
14368 incl(&pos);
14370 foundpos = pos;
14372 /* clear the start flag to avoid getting stuck here */
14373 options &= ~SEARCH_START;
14375 /* If the skip pattern matches, ignore this match. */
14376 if (*skip != NUL)
14378 save_pos = curwin->w_cursor;
14379 curwin->w_cursor = pos;
14380 r = eval_to_bool(skip, &err, NULL, FALSE);
14381 curwin->w_cursor = save_pos;
14382 if (err)
14384 /* Evaluating {skip} caused an error, break here. */
14385 curwin->w_cursor = save_cursor;
14386 retval = -1;
14387 break;
14389 if (r)
14390 continue;
14393 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
14395 /* Found end when searching backwards or start when searching
14396 * forward: nested pair. */
14397 ++nest;
14398 pat = pat2; /* nested, don't search for middle */
14400 else
14402 /* Found end when searching forward or start when searching
14403 * backward: end of (nested) pair; or found middle in outer pair. */
14404 if (--nest == 1)
14405 pat = pat3; /* outer level, search for middle */
14408 if (nest == 0)
14410 /* Found the match: return matchcount or line number. */
14411 if (flags & SP_RETCOUNT)
14412 ++retval;
14413 else
14414 retval = pos.lnum;
14415 if (flags & SP_SETPCMARK)
14416 setpcmark();
14417 curwin->w_cursor = pos;
14418 if (!(flags & SP_REPEAT))
14419 break;
14420 nest = 1; /* search for next unmatched */
14424 if (match_pos != NULL)
14426 /* Store the match cursor position */
14427 match_pos->lnum = curwin->w_cursor.lnum;
14428 match_pos->col = curwin->w_cursor.col + 1;
14431 /* If 'n' flag is used or search failed: restore cursor position. */
14432 if ((flags & SP_NOMOVE) || retval == 0)
14433 curwin->w_cursor = save_cursor;
14435 theend:
14436 vim_free(pat2);
14437 vim_free(pat3);
14438 p_cpo = save_cpo;
14440 return retval;
14444 * "searchpos()" function
14446 static void
14447 f_searchpos(argvars, rettv)
14448 typval_T *argvars;
14449 typval_T *rettv;
14451 pos_T match_pos;
14452 int lnum = 0;
14453 int col = 0;
14454 int n;
14455 int flags = 0;
14457 rettv->vval.v_number = 0;
14459 if (rettv_list_alloc(rettv) == FAIL)
14460 return;
14462 n = search_cmn(argvars, &match_pos, &flags);
14463 if (n > 0)
14465 lnum = match_pos.lnum;
14466 col = match_pos.col;
14469 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14470 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14471 if (flags & SP_SUBPAT)
14472 list_append_number(rettv->vval.v_list, (varnumber_T)n);
14476 /*ARGSUSED*/
14477 static void
14478 f_server2client(argvars, rettv)
14479 typval_T *argvars;
14480 typval_T *rettv;
14482 #ifdef FEAT_CLIENTSERVER
14483 char_u buf[NUMBUFLEN];
14484 char_u *server = get_tv_string_chk(&argvars[0]);
14485 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
14487 rettv->vval.v_number = -1;
14488 if (server == NULL || reply == NULL)
14489 return;
14490 if (check_restricted() || check_secure())
14491 return;
14492 # ifdef FEAT_X11
14493 if (check_connection() == FAIL)
14494 return;
14495 # endif
14497 if (serverSendReply(server, reply) < 0)
14499 EMSG(_("E258: Unable to send to client"));
14500 return;
14502 rettv->vval.v_number = 0;
14503 #else
14504 rettv->vval.v_number = -1;
14505 #endif
14508 /*ARGSUSED*/
14509 static void
14510 f_serverlist(argvars, rettv)
14511 typval_T *argvars;
14512 typval_T *rettv;
14514 char_u *r = NULL;
14516 #ifdef FEAT_CLIENTSERVER
14517 # if defined(WIN32) || defined(MAC_CLIENTSERVER)
14518 r = serverGetVimNames();
14519 # elif defined(FEAT_X11)
14520 make_connection();
14521 if (X_DISPLAY != NULL)
14522 r = serverGetVimNames(X_DISPLAY);
14523 # endif
14524 #endif
14525 rettv->v_type = VAR_STRING;
14526 rettv->vval.v_string = r;
14530 * "setbufvar()" function
14532 /*ARGSUSED*/
14533 static void
14534 f_setbufvar(argvars, rettv)
14535 typval_T *argvars;
14536 typval_T *rettv;
14538 buf_T *buf;
14539 aco_save_T aco;
14540 char_u *varname, *bufvarname;
14541 typval_T *varp;
14542 char_u nbuf[NUMBUFLEN];
14544 rettv->vval.v_number = 0;
14546 if (check_restricted() || check_secure())
14547 return;
14548 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
14549 varname = get_tv_string_chk(&argvars[1]);
14550 buf = get_buf_tv(&argvars[0]);
14551 varp = &argvars[2];
14553 if (buf != NULL && varname != NULL && varp != NULL)
14555 /* set curbuf to be our buf, temporarily */
14556 aucmd_prepbuf(&aco, buf);
14558 if (*varname == '&')
14560 long numval;
14561 char_u *strval;
14562 int error = FALSE;
14564 ++varname;
14565 numval = get_tv_number_chk(varp, &error);
14566 strval = get_tv_string_buf_chk(varp, nbuf);
14567 if (!error && strval != NULL)
14568 set_option_value(varname, numval, strval, OPT_LOCAL);
14570 else
14572 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
14573 if (bufvarname != NULL)
14575 STRCPY(bufvarname, "b:");
14576 STRCPY(bufvarname + 2, varname);
14577 set_var(bufvarname, varp, TRUE);
14578 vim_free(bufvarname);
14582 /* reset notion of buffer */
14583 aucmd_restbuf(&aco);
14588 * "setcmdpos()" function
14590 static void
14591 f_setcmdpos(argvars, rettv)
14592 typval_T *argvars;
14593 typval_T *rettv;
14595 int pos = (int)get_tv_number(&argvars[0]) - 1;
14597 if (pos >= 0)
14598 rettv->vval.v_number = set_cmdline_pos(pos);
14602 * "setline()" function
14604 static void
14605 f_setline(argvars, rettv)
14606 typval_T *argvars;
14607 typval_T *rettv;
14609 linenr_T lnum;
14610 char_u *line = NULL;
14611 list_T *l = NULL;
14612 listitem_T *li = NULL;
14613 long added = 0;
14614 linenr_T lcount = curbuf->b_ml.ml_line_count;
14616 lnum = get_tv_lnum(&argvars[0]);
14617 if (argvars[1].v_type == VAR_LIST)
14619 l = argvars[1].vval.v_list;
14620 li = l->lv_first;
14622 else
14623 line = get_tv_string_chk(&argvars[1]);
14625 rettv->vval.v_number = 0; /* OK */
14626 for (;;)
14628 if (l != NULL)
14630 /* list argument, get next string */
14631 if (li == NULL)
14632 break;
14633 line = get_tv_string_chk(&li->li_tv);
14634 li = li->li_next;
14637 rettv->vval.v_number = 1; /* FAIL */
14638 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
14639 break;
14640 if (lnum <= curbuf->b_ml.ml_line_count)
14642 /* existing line, replace it */
14643 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
14645 changed_bytes(lnum, 0);
14646 if (lnum == curwin->w_cursor.lnum)
14647 check_cursor_col();
14648 rettv->vval.v_number = 0; /* OK */
14651 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
14653 /* lnum is one past the last line, append the line */
14654 ++added;
14655 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
14656 rettv->vval.v_number = 0; /* OK */
14659 if (l == NULL) /* only one string argument */
14660 break;
14661 ++lnum;
14664 if (added > 0)
14665 appended_lines_mark(lcount, added);
14669 * Used by "setqflist()" and "setloclist()" functions
14671 /*ARGSUSED*/
14672 static void
14673 set_qf_ll_list(wp, list_arg, action_arg, rettv)
14674 win_T *wp;
14675 typval_T *list_arg;
14676 typval_T *action_arg;
14677 typval_T *rettv;
14679 #ifdef FEAT_QUICKFIX
14680 char_u *act;
14681 int action = ' ';
14682 #endif
14684 rettv->vval.v_number = -1;
14686 #ifdef FEAT_QUICKFIX
14687 if (list_arg->v_type != VAR_LIST)
14688 EMSG(_(e_listreq));
14689 else
14691 list_T *l = list_arg->vval.v_list;
14693 if (action_arg->v_type == VAR_STRING)
14695 act = get_tv_string_chk(action_arg);
14696 if (act == NULL)
14697 return; /* type error; errmsg already given */
14698 if (*act == 'a' || *act == 'r')
14699 action = *act;
14702 if (l != NULL && set_errorlist(wp, l, action) == OK)
14703 rettv->vval.v_number = 0;
14705 #endif
14709 * "setloclist()" function
14711 /*ARGSUSED*/
14712 static void
14713 f_setloclist(argvars, rettv)
14714 typval_T *argvars;
14715 typval_T *rettv;
14717 win_T *win;
14719 rettv->vval.v_number = -1;
14721 win = find_win_by_nr(&argvars[0], NULL);
14722 if (win != NULL)
14723 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
14727 * "setmatches()" function
14729 static void
14730 f_setmatches(argvars, rettv)
14731 typval_T *argvars;
14732 typval_T *rettv;
14734 #ifdef FEAT_SEARCH_EXTRA
14735 list_T *l;
14736 listitem_T *li;
14737 dict_T *d;
14739 rettv->vval.v_number = -1;
14740 if (argvars[0].v_type != VAR_LIST)
14742 EMSG(_(e_listreq));
14743 return;
14745 if ((l = argvars[0].vval.v_list) != NULL)
14748 /* To some extent make sure that we are dealing with a list from
14749 * "getmatches()". */
14750 li = l->lv_first;
14751 while (li != NULL)
14753 if (li->li_tv.v_type != VAR_DICT
14754 || (d = li->li_tv.vval.v_dict) == NULL)
14756 EMSG(_(e_invarg));
14757 return;
14759 if (!(dict_find(d, (char_u *)"group", -1) != NULL
14760 && dict_find(d, (char_u *)"pattern", -1) != NULL
14761 && dict_find(d, (char_u *)"priority", -1) != NULL
14762 && dict_find(d, (char_u *)"id", -1) != NULL))
14764 EMSG(_(e_invarg));
14765 return;
14767 li = li->li_next;
14770 clear_matches(curwin);
14771 li = l->lv_first;
14772 while (li != NULL)
14774 d = li->li_tv.vval.v_dict;
14775 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
14776 get_dict_string(d, (char_u *)"pattern", FALSE),
14777 (int)get_dict_number(d, (char_u *)"priority"),
14778 (int)get_dict_number(d, (char_u *)"id"));
14779 li = li->li_next;
14781 rettv->vval.v_number = 0;
14783 #endif
14787 * "setpos()" function
14789 /*ARGSUSED*/
14790 static void
14791 f_setpos(argvars, rettv)
14792 typval_T *argvars;
14793 typval_T *rettv;
14795 pos_T pos;
14796 int fnum;
14797 char_u *name;
14799 name = get_tv_string_chk(argvars);
14800 if (name != NULL)
14802 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
14804 --pos.col;
14805 if (name[0] == '.') /* cursor */
14807 if (fnum == curbuf->b_fnum)
14809 curwin->w_cursor = pos;
14810 check_cursor();
14812 else
14813 EMSG(_(e_invarg));
14815 else if (name[0] == '\'') /* mark */
14816 (void)setmark_pos(name[1], &pos, fnum);
14817 else
14818 EMSG(_(e_invarg));
14824 * "setqflist()" function
14826 /*ARGSUSED*/
14827 static void
14828 f_setqflist(argvars, rettv)
14829 typval_T *argvars;
14830 typval_T *rettv;
14832 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
14836 * "setreg()" function
14838 static void
14839 f_setreg(argvars, rettv)
14840 typval_T *argvars;
14841 typval_T *rettv;
14843 int regname;
14844 char_u *strregname;
14845 char_u *stropt;
14846 char_u *strval;
14847 int append;
14848 char_u yank_type;
14849 long block_len;
14851 block_len = -1;
14852 yank_type = MAUTO;
14853 append = FALSE;
14855 strregname = get_tv_string_chk(argvars);
14856 rettv->vval.v_number = 1; /* FAIL is default */
14858 if (strregname == NULL)
14859 return; /* type error; errmsg already given */
14860 regname = *strregname;
14861 if (regname == 0 || regname == '@')
14862 regname = '"';
14863 else if (regname == '=')
14864 return;
14866 if (argvars[2].v_type != VAR_UNKNOWN)
14868 stropt = get_tv_string_chk(&argvars[2]);
14869 if (stropt == NULL)
14870 return; /* type error */
14871 for (; *stropt != NUL; ++stropt)
14872 switch (*stropt)
14874 case 'a': case 'A': /* append */
14875 append = TRUE;
14876 break;
14877 case 'v': case 'c': /* character-wise selection */
14878 yank_type = MCHAR;
14879 break;
14880 case 'V': case 'l': /* line-wise selection */
14881 yank_type = MLINE;
14882 break;
14883 #ifdef FEAT_VISUAL
14884 case 'b': case Ctrl_V: /* block-wise selection */
14885 yank_type = MBLOCK;
14886 if (VIM_ISDIGIT(stropt[1]))
14888 ++stropt;
14889 block_len = getdigits(&stropt) - 1;
14890 --stropt;
14892 break;
14893 #endif
14897 strval = get_tv_string_chk(&argvars[1]);
14898 if (strval != NULL)
14899 write_reg_contents_ex(regname, strval, -1,
14900 append, yank_type, block_len);
14901 rettv->vval.v_number = 0;
14905 * "settabwinvar()" function
14907 static void
14908 f_settabwinvar(argvars, rettv)
14909 typval_T *argvars;
14910 typval_T *rettv;
14912 setwinvar(argvars, rettv, 1);
14916 * "setwinvar()" function
14918 static void
14919 f_setwinvar(argvars, rettv)
14920 typval_T *argvars;
14921 typval_T *rettv;
14923 setwinvar(argvars, rettv, 0);
14927 * "setwinvar()" and "settabwinvar()" functions
14929 static void
14930 setwinvar(argvars, rettv, off)
14931 typval_T *argvars;
14932 typval_T *rettv;
14933 int off;
14935 win_T *win;
14936 #ifdef FEAT_WINDOWS
14937 win_T *save_curwin;
14938 tabpage_T *save_curtab;
14939 #endif
14940 char_u *varname, *winvarname;
14941 typval_T *varp;
14942 char_u nbuf[NUMBUFLEN];
14943 tabpage_T *tp;
14945 rettv->vval.v_number = 0;
14947 if (check_restricted() || check_secure())
14948 return;
14950 #ifdef FEAT_WINDOWS
14951 if (off == 1)
14952 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
14953 else
14954 tp = curtab;
14955 #endif
14956 win = find_win_by_nr(&argvars[off], tp);
14957 varname = get_tv_string_chk(&argvars[off + 1]);
14958 varp = &argvars[off + 2];
14960 if (win != NULL && varname != NULL && varp != NULL)
14962 #ifdef FEAT_WINDOWS
14963 /* set curwin to be our win, temporarily */
14964 save_curwin = curwin;
14965 save_curtab = curtab;
14966 goto_tabpage_tp(tp);
14967 if (!win_valid(win))
14968 return;
14969 curwin = win;
14970 curbuf = curwin->w_buffer;
14971 #endif
14973 if (*varname == '&')
14975 long numval;
14976 char_u *strval;
14977 int error = FALSE;
14979 ++varname;
14980 numval = get_tv_number_chk(varp, &error);
14981 strval = get_tv_string_buf_chk(varp, nbuf);
14982 if (!error && strval != NULL)
14983 set_option_value(varname, numval, strval, OPT_LOCAL);
14985 else
14987 winvarname = alloc((unsigned)STRLEN(varname) + 3);
14988 if (winvarname != NULL)
14990 STRCPY(winvarname, "w:");
14991 STRCPY(winvarname + 2, varname);
14992 set_var(winvarname, varp, TRUE);
14993 vim_free(winvarname);
14997 #ifdef FEAT_WINDOWS
14998 /* Restore current tabpage and window, if still valid (autocomands can
14999 * make them invalid). */
15000 if (valid_tabpage(save_curtab))
15001 goto_tabpage_tp(save_curtab);
15002 if (win_valid(save_curwin))
15004 curwin = save_curwin;
15005 curbuf = curwin->w_buffer;
15007 #endif
15012 * "shellescape({string})" function
15014 static void
15015 f_shellescape(argvars, rettv)
15016 typval_T *argvars;
15017 typval_T *rettv;
15019 rettv->vval.v_string = vim_strsave_shellescape(get_tv_string(&argvars[0]));
15020 rettv->v_type = VAR_STRING;
15024 * "simplify()" function
15026 static void
15027 f_simplify(argvars, rettv)
15028 typval_T *argvars;
15029 typval_T *rettv;
15031 char_u *p;
15033 p = get_tv_string(&argvars[0]);
15034 rettv->vval.v_string = vim_strsave(p);
15035 simplify_filename(rettv->vval.v_string); /* simplify in place */
15036 rettv->v_type = VAR_STRING;
15039 static int
15040 #ifdef __BORLANDC__
15041 _RTLENTRYF
15042 #endif
15043 item_compare __ARGS((const void *s1, const void *s2));
15044 static int
15045 #ifdef __BORLANDC__
15046 _RTLENTRYF
15047 #endif
15048 item_compare2 __ARGS((const void *s1, const void *s2));
15050 static int item_compare_ic;
15051 static char_u *item_compare_func;
15052 static int item_compare_func_err;
15053 #define ITEM_COMPARE_FAIL 999
15056 * Compare functions for f_sort() below.
15058 static int
15059 #ifdef __BORLANDC__
15060 _RTLENTRYF
15061 #endif
15062 item_compare(s1, s2)
15063 const void *s1;
15064 const void *s2;
15066 char_u *p1, *p2;
15067 char_u *tofree1, *tofree2;
15068 int res;
15069 char_u numbuf1[NUMBUFLEN];
15070 char_u numbuf2[NUMBUFLEN];
15072 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
15073 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
15074 if (p1 == NULL)
15075 p1 = (char_u *)"";
15076 if (p2 == NULL)
15077 p2 = (char_u *)"";
15078 if (item_compare_ic)
15079 res = STRICMP(p1, p2);
15080 else
15081 res = STRCMP(p1, p2);
15082 vim_free(tofree1);
15083 vim_free(tofree2);
15084 return res;
15087 static int
15088 #ifdef __BORLANDC__
15089 _RTLENTRYF
15090 #endif
15091 item_compare2(s1, s2)
15092 const void *s1;
15093 const void *s2;
15095 int res;
15096 typval_T rettv;
15097 typval_T argv[3];
15098 int dummy;
15100 /* shortcut after failure in previous call; compare all items equal */
15101 if (item_compare_func_err)
15102 return 0;
15104 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
15105 * in the copy without changing the original list items. */
15106 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
15107 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
15109 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
15110 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
15111 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
15112 clear_tv(&argv[0]);
15113 clear_tv(&argv[1]);
15115 if (res == FAIL)
15116 res = ITEM_COMPARE_FAIL;
15117 else
15118 /* return value has wrong type */
15119 res = get_tv_number_chk(&rettv, &item_compare_func_err);
15120 if (item_compare_func_err)
15121 res = ITEM_COMPARE_FAIL;
15122 clear_tv(&rettv);
15123 return res;
15127 * "sort({list})" function
15129 static void
15130 f_sort(argvars, rettv)
15131 typval_T *argvars;
15132 typval_T *rettv;
15134 list_T *l;
15135 listitem_T *li;
15136 listitem_T **ptrs;
15137 long len;
15138 long i;
15140 rettv->vval.v_number = 0;
15141 if (argvars[0].v_type != VAR_LIST)
15142 EMSG2(_(e_listarg), "sort()");
15143 else
15145 l = argvars[0].vval.v_list;
15146 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
15147 return;
15148 rettv->vval.v_list = l;
15149 rettv->v_type = VAR_LIST;
15150 ++l->lv_refcount;
15152 len = list_len(l);
15153 if (len <= 1)
15154 return; /* short list sorts pretty quickly */
15156 item_compare_ic = FALSE;
15157 item_compare_func = NULL;
15158 if (argvars[1].v_type != VAR_UNKNOWN)
15160 if (argvars[1].v_type == VAR_FUNC)
15161 item_compare_func = argvars[1].vval.v_string;
15162 else
15164 int error = FALSE;
15166 i = get_tv_number_chk(&argvars[1], &error);
15167 if (error)
15168 return; /* type error; errmsg already given */
15169 if (i == 1)
15170 item_compare_ic = TRUE;
15171 else
15172 item_compare_func = get_tv_string(&argvars[1]);
15176 /* Make an array with each entry pointing to an item in the List. */
15177 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
15178 if (ptrs == NULL)
15179 return;
15180 i = 0;
15181 for (li = l->lv_first; li != NULL; li = li->li_next)
15182 ptrs[i++] = li;
15184 item_compare_func_err = FALSE;
15185 /* test the compare function */
15186 if (item_compare_func != NULL
15187 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
15188 == ITEM_COMPARE_FAIL)
15189 EMSG(_("E702: Sort compare function failed"));
15190 else
15192 /* Sort the array with item pointers. */
15193 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
15194 item_compare_func == NULL ? item_compare : item_compare2);
15196 if (!item_compare_func_err)
15198 /* Clear the List and append the items in the sorted order. */
15199 l->lv_first = l->lv_last = NULL;
15200 l->lv_len = 0;
15201 for (i = 0; i < len; ++i)
15202 list_append(l, ptrs[i]);
15206 vim_free(ptrs);
15211 * "soundfold({word})" function
15213 static void
15214 f_soundfold(argvars, rettv)
15215 typval_T *argvars;
15216 typval_T *rettv;
15218 char_u *s;
15220 rettv->v_type = VAR_STRING;
15221 s = get_tv_string(&argvars[0]);
15222 #ifdef FEAT_SPELL
15223 rettv->vval.v_string = eval_soundfold(s);
15224 #else
15225 rettv->vval.v_string = vim_strsave(s);
15226 #endif
15230 * "spellbadword()" function
15232 /* ARGSUSED */
15233 static void
15234 f_spellbadword(argvars, rettv)
15235 typval_T *argvars;
15236 typval_T *rettv;
15238 char_u *word = (char_u *)"";
15239 hlf_T attr = HLF_COUNT;
15240 int len = 0;
15242 if (rettv_list_alloc(rettv) == FAIL)
15243 return;
15245 #ifdef FEAT_SPELL
15246 if (argvars[0].v_type == VAR_UNKNOWN)
15248 /* Find the start and length of the badly spelled word. */
15249 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
15250 if (len != 0)
15251 word = ml_get_cursor();
15253 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15255 char_u *str = get_tv_string_chk(&argvars[0]);
15256 int capcol = -1;
15258 if (str != NULL)
15260 /* Check the argument for spelling. */
15261 while (*str != NUL)
15263 len = spell_check(curwin, str, &attr, &capcol, FALSE);
15264 if (attr != HLF_COUNT)
15266 word = str;
15267 break;
15269 str += len;
15273 #endif
15275 list_append_string(rettv->vval.v_list, word, len);
15276 list_append_string(rettv->vval.v_list, (char_u *)(
15277 attr == HLF_SPB ? "bad" :
15278 attr == HLF_SPR ? "rare" :
15279 attr == HLF_SPL ? "local" :
15280 attr == HLF_SPC ? "caps" :
15281 ""), -1);
15285 * "spellsuggest()" function
15287 /*ARGSUSED*/
15288 static void
15289 f_spellsuggest(argvars, rettv)
15290 typval_T *argvars;
15291 typval_T *rettv;
15293 #ifdef FEAT_SPELL
15294 char_u *str;
15295 int typeerr = FALSE;
15296 int maxcount;
15297 garray_T ga;
15298 int i;
15299 listitem_T *li;
15300 int need_capital = FALSE;
15301 #endif
15303 if (rettv_list_alloc(rettv) == FAIL)
15304 return;
15306 #ifdef FEAT_SPELL
15307 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15309 str = get_tv_string(&argvars[0]);
15310 if (argvars[1].v_type != VAR_UNKNOWN)
15312 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
15313 if (maxcount <= 0)
15314 return;
15315 if (argvars[2].v_type != VAR_UNKNOWN)
15317 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
15318 if (typeerr)
15319 return;
15322 else
15323 maxcount = 25;
15325 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
15327 for (i = 0; i < ga.ga_len; ++i)
15329 str = ((char_u **)ga.ga_data)[i];
15331 li = listitem_alloc();
15332 if (li == NULL)
15333 vim_free(str);
15334 else
15336 li->li_tv.v_type = VAR_STRING;
15337 li->li_tv.v_lock = 0;
15338 li->li_tv.vval.v_string = str;
15339 list_append(rettv->vval.v_list, li);
15342 ga_clear(&ga);
15344 #endif
15347 static void
15348 f_split(argvars, rettv)
15349 typval_T *argvars;
15350 typval_T *rettv;
15352 char_u *str;
15353 char_u *end;
15354 char_u *pat = NULL;
15355 regmatch_T regmatch;
15356 char_u patbuf[NUMBUFLEN];
15357 char_u *save_cpo;
15358 int match;
15359 colnr_T col = 0;
15360 int keepempty = FALSE;
15361 int typeerr = FALSE;
15363 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15364 save_cpo = p_cpo;
15365 p_cpo = (char_u *)"";
15367 str = get_tv_string(&argvars[0]);
15368 if (argvars[1].v_type != VAR_UNKNOWN)
15370 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
15371 if (pat == NULL)
15372 typeerr = TRUE;
15373 if (argvars[2].v_type != VAR_UNKNOWN)
15374 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
15376 if (pat == NULL || *pat == NUL)
15377 pat = (char_u *)"[\\x01- ]\\+";
15379 if (rettv_list_alloc(rettv) == FAIL)
15380 return;
15381 if (typeerr)
15382 return;
15384 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
15385 if (regmatch.regprog != NULL)
15387 regmatch.rm_ic = FALSE;
15388 while (*str != NUL || keepempty)
15390 if (*str == NUL)
15391 match = FALSE; /* empty item at the end */
15392 else
15393 match = vim_regexec_nl(&regmatch, str, col);
15394 if (match)
15395 end = regmatch.startp[0];
15396 else
15397 end = str + STRLEN(str);
15398 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
15399 && *str != NUL && match && end < regmatch.endp[0]))
15401 if (list_append_string(rettv->vval.v_list, str,
15402 (int)(end - str)) == FAIL)
15403 break;
15405 if (!match)
15406 break;
15407 /* Advance to just after the match. */
15408 if (regmatch.endp[0] > str)
15409 col = 0;
15410 else
15412 /* Don't get stuck at the same match. */
15413 #ifdef FEAT_MBYTE
15414 col = (*mb_ptr2len)(regmatch.endp[0]);
15415 #else
15416 col = 1;
15417 #endif
15419 str = regmatch.endp[0];
15422 vim_free(regmatch.regprog);
15425 p_cpo = save_cpo;
15429 * "str2nr()" function
15431 static void
15432 f_str2nr(argvars, rettv)
15433 typval_T *argvars;
15434 typval_T *rettv;
15436 int base = 10;
15437 char_u *p;
15438 long n;
15440 if (argvars[1].v_type != VAR_UNKNOWN)
15442 base = get_tv_number(&argvars[1]);
15443 if (base != 8 && base != 10 && base != 16)
15445 EMSG(_(e_invarg));
15446 return;
15450 p = skipwhite(get_tv_string(&argvars[0]));
15451 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
15452 rettv->vval.v_number = n;
15455 #ifdef HAVE_STRFTIME
15457 * "strftime({format}[, {time}])" function
15459 static void
15460 f_strftime(argvars, rettv)
15461 typval_T *argvars;
15462 typval_T *rettv;
15464 char_u result_buf[256];
15465 struct tm *curtime;
15466 time_t seconds;
15467 char_u *p;
15469 rettv->v_type = VAR_STRING;
15471 p = get_tv_string(&argvars[0]);
15472 if (argvars[1].v_type == VAR_UNKNOWN)
15473 seconds = time(NULL);
15474 else
15475 seconds = (time_t)get_tv_number(&argvars[1]);
15476 curtime = localtime(&seconds);
15477 /* MSVC returns NULL for an invalid value of seconds. */
15478 if (curtime == NULL)
15479 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
15480 else
15482 # ifdef FEAT_MBYTE
15483 vimconv_T conv;
15484 char_u *enc;
15486 conv.vc_type = CONV_NONE;
15487 enc = enc_locale();
15488 convert_setup(&conv, p_enc, enc);
15489 if (conv.vc_type != CONV_NONE)
15490 p = string_convert(&conv, p, NULL);
15491 # endif
15492 if (p != NULL)
15493 (void)strftime((char *)result_buf, sizeof(result_buf),
15494 (char *)p, curtime);
15495 else
15496 result_buf[0] = NUL;
15498 # ifdef FEAT_MBYTE
15499 if (conv.vc_type != CONV_NONE)
15500 vim_free(p);
15501 convert_setup(&conv, enc, p_enc);
15502 if (conv.vc_type != CONV_NONE)
15503 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
15504 else
15505 # endif
15506 rettv->vval.v_string = vim_strsave(result_buf);
15508 # ifdef FEAT_MBYTE
15509 /* Release conversion descriptors */
15510 convert_setup(&conv, NULL, NULL);
15511 vim_free(enc);
15512 # endif
15515 #endif
15518 * "stridx()" function
15520 static void
15521 f_stridx(argvars, rettv)
15522 typval_T *argvars;
15523 typval_T *rettv;
15525 char_u buf[NUMBUFLEN];
15526 char_u *needle;
15527 char_u *haystack;
15528 char_u *save_haystack;
15529 char_u *pos;
15530 int start_idx;
15532 needle = get_tv_string_chk(&argvars[1]);
15533 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
15534 rettv->vval.v_number = -1;
15535 if (needle == NULL || haystack == NULL)
15536 return; /* type error; errmsg already given */
15538 if (argvars[2].v_type != VAR_UNKNOWN)
15540 int error = FALSE;
15542 start_idx = get_tv_number_chk(&argvars[2], &error);
15543 if (error || start_idx >= (int)STRLEN(haystack))
15544 return;
15545 if (start_idx >= 0)
15546 haystack += start_idx;
15549 pos = (char_u *)strstr((char *)haystack, (char *)needle);
15550 if (pos != NULL)
15551 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
15555 * "string()" function
15557 static void
15558 f_string(argvars, rettv)
15559 typval_T *argvars;
15560 typval_T *rettv;
15562 char_u *tofree;
15563 char_u numbuf[NUMBUFLEN];
15565 rettv->v_type = VAR_STRING;
15566 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
15567 /* Make a copy if we have a value but it's not in allocate memory. */
15568 if (rettv->vval.v_string != NULL && tofree == NULL)
15569 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
15573 * "strlen()" function
15575 static void
15576 f_strlen(argvars, rettv)
15577 typval_T *argvars;
15578 typval_T *rettv;
15580 rettv->vval.v_number = (varnumber_T)(STRLEN(
15581 get_tv_string(&argvars[0])));
15585 * "strpart()" function
15587 static void
15588 f_strpart(argvars, rettv)
15589 typval_T *argvars;
15590 typval_T *rettv;
15592 char_u *p;
15593 int n;
15594 int len;
15595 int slen;
15596 int error = FALSE;
15598 p = get_tv_string(&argvars[0]);
15599 slen = (int)STRLEN(p);
15601 n = get_tv_number_chk(&argvars[1], &error);
15602 if (error)
15603 len = 0;
15604 else if (argvars[2].v_type != VAR_UNKNOWN)
15605 len = get_tv_number(&argvars[2]);
15606 else
15607 len = slen - n; /* default len: all bytes that are available. */
15610 * Only return the overlap between the specified part and the actual
15611 * string.
15613 if (n < 0)
15615 len += n;
15616 n = 0;
15618 else if (n > slen)
15619 n = slen;
15620 if (len < 0)
15621 len = 0;
15622 else if (n + len > slen)
15623 len = slen - n;
15625 rettv->v_type = VAR_STRING;
15626 rettv->vval.v_string = vim_strnsave(p + n, len);
15630 * "strridx()" function
15632 static void
15633 f_strridx(argvars, rettv)
15634 typval_T *argvars;
15635 typval_T *rettv;
15637 char_u buf[NUMBUFLEN];
15638 char_u *needle;
15639 char_u *haystack;
15640 char_u *rest;
15641 char_u *lastmatch = NULL;
15642 int haystack_len, end_idx;
15644 needle = get_tv_string_chk(&argvars[1]);
15645 haystack = get_tv_string_buf_chk(&argvars[0], buf);
15647 rettv->vval.v_number = -1;
15648 if (needle == NULL || haystack == NULL)
15649 return; /* type error; errmsg already given */
15651 haystack_len = (int)STRLEN(haystack);
15652 if (argvars[2].v_type != VAR_UNKNOWN)
15654 /* Third argument: upper limit for index */
15655 end_idx = get_tv_number_chk(&argvars[2], NULL);
15656 if (end_idx < 0)
15657 return; /* can never find a match */
15659 else
15660 end_idx = haystack_len;
15662 if (*needle == NUL)
15664 /* Empty string matches past the end. */
15665 lastmatch = haystack + end_idx;
15667 else
15669 for (rest = haystack; *rest != '\0'; ++rest)
15671 rest = (char_u *)strstr((char *)rest, (char *)needle);
15672 if (rest == NULL || rest > haystack + end_idx)
15673 break;
15674 lastmatch = rest;
15678 if (lastmatch == NULL)
15679 rettv->vval.v_number = -1;
15680 else
15681 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
15685 * "strtrans()" function
15687 static void
15688 f_strtrans(argvars, rettv)
15689 typval_T *argvars;
15690 typval_T *rettv;
15692 rettv->v_type = VAR_STRING;
15693 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
15697 * "submatch()" function
15699 static void
15700 f_submatch(argvars, rettv)
15701 typval_T *argvars;
15702 typval_T *rettv;
15704 rettv->v_type = VAR_STRING;
15705 rettv->vval.v_string =
15706 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
15710 * "substitute()" function
15712 static void
15713 f_substitute(argvars, rettv)
15714 typval_T *argvars;
15715 typval_T *rettv;
15717 char_u patbuf[NUMBUFLEN];
15718 char_u subbuf[NUMBUFLEN];
15719 char_u flagsbuf[NUMBUFLEN];
15721 char_u *str = get_tv_string_chk(&argvars[0]);
15722 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
15723 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
15724 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
15726 rettv->v_type = VAR_STRING;
15727 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
15728 rettv->vval.v_string = NULL;
15729 else
15730 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
15734 * "synID(lnum, col, trans)" function
15736 /*ARGSUSED*/
15737 static void
15738 f_synID(argvars, rettv)
15739 typval_T *argvars;
15740 typval_T *rettv;
15742 int id = 0;
15743 #ifdef FEAT_SYN_HL
15744 long lnum;
15745 long col;
15746 int trans;
15747 int transerr = FALSE;
15749 lnum = get_tv_lnum(argvars); /* -1 on type error */
15750 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
15751 trans = get_tv_number_chk(&argvars[2], &transerr);
15753 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
15754 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
15755 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
15756 #endif
15758 rettv->vval.v_number = id;
15762 * "synIDattr(id, what [, mode])" function
15764 /*ARGSUSED*/
15765 static void
15766 f_synIDattr(argvars, rettv)
15767 typval_T *argvars;
15768 typval_T *rettv;
15770 char_u *p = NULL;
15771 #ifdef FEAT_SYN_HL
15772 int id;
15773 char_u *what;
15774 char_u *mode;
15775 char_u modebuf[NUMBUFLEN];
15776 int modec;
15778 id = get_tv_number(&argvars[0]);
15779 what = get_tv_string(&argvars[1]);
15780 if (argvars[2].v_type != VAR_UNKNOWN)
15782 mode = get_tv_string_buf(&argvars[2], modebuf);
15783 modec = TOLOWER_ASC(mode[0]);
15784 if (modec != 't' && modec != 'c'
15785 #ifdef FEAT_GUI
15786 && modec != 'g'
15787 #endif
15789 modec = 0; /* replace invalid with current */
15791 else
15793 #ifdef FEAT_GUI
15794 if (gui.in_use)
15795 modec = 'g';
15796 else
15797 #endif
15798 if (t_colors > 1)
15799 modec = 'c';
15800 else
15801 modec = 't';
15805 switch (TOLOWER_ASC(what[0]))
15807 case 'b':
15808 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
15809 p = highlight_color(id, what, modec);
15810 else /* bold */
15811 p = highlight_has_attr(id, HL_BOLD, modec);
15812 break;
15814 case 'f': /* fg[#] */
15815 p = highlight_color(id, what, modec);
15816 break;
15818 case 'i':
15819 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
15820 p = highlight_has_attr(id, HL_INVERSE, modec);
15821 else /* italic */
15822 p = highlight_has_attr(id, HL_ITALIC, modec);
15823 break;
15825 case 'n': /* name */
15826 p = get_highlight_name(NULL, id - 1);
15827 break;
15829 case 'r': /* reverse */
15830 p = highlight_has_attr(id, HL_INVERSE, modec);
15831 break;
15833 case 's': /* standout */
15834 p = highlight_has_attr(id, HL_STANDOUT, modec);
15835 break;
15837 case 'u':
15838 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
15839 /* underline */
15840 p = highlight_has_attr(id, HL_UNDERLINE, modec);
15841 else
15842 /* undercurl */
15843 p = highlight_has_attr(id, HL_UNDERCURL, modec);
15844 break;
15847 if (p != NULL)
15848 p = vim_strsave(p);
15849 #endif
15850 rettv->v_type = VAR_STRING;
15851 rettv->vval.v_string = p;
15855 * "synIDtrans(id)" function
15857 /*ARGSUSED*/
15858 static void
15859 f_synIDtrans(argvars, rettv)
15860 typval_T *argvars;
15861 typval_T *rettv;
15863 int id;
15865 #ifdef FEAT_SYN_HL
15866 id = get_tv_number(&argvars[0]);
15868 if (id > 0)
15869 id = syn_get_final_id(id);
15870 else
15871 #endif
15872 id = 0;
15874 rettv->vval.v_number = id;
15878 * "synstack(lnum, col)" function
15880 /*ARGSUSED*/
15881 static void
15882 f_synstack(argvars, rettv)
15883 typval_T *argvars;
15884 typval_T *rettv;
15886 #ifdef FEAT_SYN_HL
15887 long lnum;
15888 long col;
15889 int i;
15890 int id;
15891 #endif
15893 rettv->v_type = VAR_LIST;
15894 rettv->vval.v_list = NULL;
15896 #ifdef FEAT_SYN_HL
15897 lnum = get_tv_lnum(argvars); /* -1 on type error */
15898 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
15900 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
15901 && col >= 0 && col < (long)STRLEN(ml_get(lnum))
15902 && rettv_list_alloc(rettv) != FAIL)
15904 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
15905 for (i = 0; ; ++i)
15907 id = syn_get_stack_item(i);
15908 if (id < 0)
15909 break;
15910 if (list_append_number(rettv->vval.v_list, id) == FAIL)
15911 break;
15914 #endif
15918 * "system()" function
15920 static void
15921 f_system(argvars, rettv)
15922 typval_T *argvars;
15923 typval_T *rettv;
15925 char_u *res = NULL;
15926 char_u *p;
15927 char_u *infile = NULL;
15928 char_u buf[NUMBUFLEN];
15929 int err = FALSE;
15930 FILE *fd;
15932 if (check_restricted() || check_secure())
15933 goto done;
15935 if (argvars[1].v_type != VAR_UNKNOWN)
15938 * Write the string to a temp file, to be used for input of the shell
15939 * command.
15941 if ((infile = vim_tempname('i')) == NULL)
15943 EMSG(_(e_notmp));
15944 goto done;
15947 fd = mch_fopen((char *)infile, WRITEBIN);
15948 if (fd == NULL)
15950 EMSG2(_(e_notopen), infile);
15951 goto done;
15953 p = get_tv_string_buf_chk(&argvars[1], buf);
15954 if (p == NULL)
15956 fclose(fd);
15957 goto done; /* type error; errmsg already given */
15959 if (fwrite(p, STRLEN(p), 1, fd) != 1)
15960 err = TRUE;
15961 if (fclose(fd) != 0)
15962 err = TRUE;
15963 if (err)
15965 EMSG(_("E677: Error writing temp file"));
15966 goto done;
15970 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
15971 SHELL_SILENT | SHELL_COOKED);
15973 #ifdef USE_CR
15974 /* translate <CR> into <NL> */
15975 if (res != NULL)
15977 char_u *s;
15979 for (s = res; *s; ++s)
15981 if (*s == CAR)
15982 *s = NL;
15985 #else
15986 # ifdef USE_CRNL
15987 /* translate <CR><NL> into <NL> */
15988 if (res != NULL)
15990 char_u *s, *d;
15992 d = res;
15993 for (s = res; *s; ++s)
15995 if (s[0] == CAR && s[1] == NL)
15996 ++s;
15997 *d++ = *s;
15999 *d = NUL;
16001 # endif
16002 #endif
16004 done:
16005 if (infile != NULL)
16007 mch_remove(infile);
16008 vim_free(infile);
16010 rettv->v_type = VAR_STRING;
16011 rettv->vval.v_string = res;
16015 * "tabpagebuflist()" function
16017 /* ARGSUSED */
16018 static void
16019 f_tabpagebuflist(argvars, rettv)
16020 typval_T *argvars;
16021 typval_T *rettv;
16023 #ifndef FEAT_WINDOWS
16024 rettv->vval.v_number = 0;
16025 #else
16026 tabpage_T *tp;
16027 win_T *wp = NULL;
16029 if (argvars[0].v_type == VAR_UNKNOWN)
16030 wp = firstwin;
16031 else
16033 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16034 if (tp != NULL)
16035 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16037 if (wp == NULL)
16038 rettv->vval.v_number = 0;
16039 else
16041 if (rettv_list_alloc(rettv) == FAIL)
16042 rettv->vval.v_number = 0;
16043 else
16045 for (; wp != NULL; wp = wp->w_next)
16046 if (list_append_number(rettv->vval.v_list,
16047 wp->w_buffer->b_fnum) == FAIL)
16048 break;
16051 #endif
16056 * "tabpagenr()" function
16058 /* ARGSUSED */
16059 static void
16060 f_tabpagenr(argvars, rettv)
16061 typval_T *argvars;
16062 typval_T *rettv;
16064 int nr = 1;
16065 #ifdef FEAT_WINDOWS
16066 char_u *arg;
16068 if (argvars[0].v_type != VAR_UNKNOWN)
16070 arg = get_tv_string_chk(&argvars[0]);
16071 nr = 0;
16072 if (arg != NULL)
16074 if (STRCMP(arg, "$") == 0)
16075 nr = tabpage_index(NULL) - 1;
16076 else
16077 EMSG2(_(e_invexpr2), arg);
16080 else
16081 nr = tabpage_index(curtab);
16082 #endif
16083 rettv->vval.v_number = nr;
16087 #ifdef FEAT_WINDOWS
16088 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
16091 * Common code for tabpagewinnr() and winnr().
16093 static int
16094 get_winnr(tp, argvar)
16095 tabpage_T *tp;
16096 typval_T *argvar;
16098 win_T *twin;
16099 int nr = 1;
16100 win_T *wp;
16101 char_u *arg;
16103 twin = (tp == curtab) ? curwin : tp->tp_curwin;
16104 if (argvar->v_type != VAR_UNKNOWN)
16106 arg = get_tv_string_chk(argvar);
16107 if (arg == NULL)
16108 nr = 0; /* type error; errmsg already given */
16109 else if (STRCMP(arg, "$") == 0)
16110 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
16111 else if (STRCMP(arg, "#") == 0)
16113 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
16114 if (twin == NULL)
16115 nr = 0;
16117 else
16119 EMSG2(_(e_invexpr2), arg);
16120 nr = 0;
16124 if (nr > 0)
16125 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16126 wp != twin; wp = wp->w_next)
16128 if (wp == NULL)
16130 /* didn't find it in this tabpage */
16131 nr = 0;
16132 break;
16134 ++nr;
16136 return nr;
16138 #endif
16141 * "tabpagewinnr()" function
16143 /* ARGSUSED */
16144 static void
16145 f_tabpagewinnr(argvars, rettv)
16146 typval_T *argvars;
16147 typval_T *rettv;
16149 int nr = 1;
16150 #ifdef FEAT_WINDOWS
16151 tabpage_T *tp;
16153 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16154 if (tp == NULL)
16155 nr = 0;
16156 else
16157 nr = get_winnr(tp, &argvars[1]);
16158 #endif
16159 rettv->vval.v_number = nr;
16164 * "tagfiles()" function
16166 /*ARGSUSED*/
16167 static void
16168 f_tagfiles(argvars, rettv)
16169 typval_T *argvars;
16170 typval_T *rettv;
16172 char_u fname[MAXPATHL + 1];
16173 tagname_T tn;
16174 int first;
16176 if (rettv_list_alloc(rettv) == FAIL)
16178 rettv->vval.v_number = 0;
16179 return;
16182 for (first = TRUE; ; first = FALSE)
16183 if (get_tagfname(&tn, first, fname) == FAIL
16184 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
16185 break;
16186 tagname_free(&tn);
16190 * "taglist()" function
16192 static void
16193 f_taglist(argvars, rettv)
16194 typval_T *argvars;
16195 typval_T *rettv;
16197 char_u *tag_pattern;
16199 tag_pattern = get_tv_string(&argvars[0]);
16201 rettv->vval.v_number = FALSE;
16202 if (*tag_pattern == NUL)
16203 return;
16205 if (rettv_list_alloc(rettv) == OK)
16206 (void)get_tags(rettv->vval.v_list, tag_pattern);
16210 * "tempname()" function
16212 /*ARGSUSED*/
16213 static void
16214 f_tempname(argvars, rettv)
16215 typval_T *argvars;
16216 typval_T *rettv;
16218 static int x = 'A';
16220 rettv->v_type = VAR_STRING;
16221 rettv->vval.v_string = vim_tempname(x);
16223 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
16224 * names. Skip 'I' and 'O', they are used for shell redirection. */
16227 if (x == 'Z')
16228 x = '0';
16229 else if (x == '9')
16230 x = 'A';
16231 else
16233 #ifdef EBCDIC
16234 if (x == 'I')
16235 x = 'J';
16236 else if (x == 'R')
16237 x = 'S';
16238 else
16239 #endif
16240 ++x;
16242 } while (x == 'I' || x == 'O');
16246 * "test(list)" function: Just checking the walls...
16248 /*ARGSUSED*/
16249 static void
16250 f_test(argvars, rettv)
16251 typval_T *argvars;
16252 typval_T *rettv;
16254 /* Used for unit testing. Change the code below to your liking. */
16255 #if 0
16256 listitem_T *li;
16257 list_T *l;
16258 char_u *bad, *good;
16260 if (argvars[0].v_type != VAR_LIST)
16261 return;
16262 l = argvars[0].vval.v_list;
16263 if (l == NULL)
16264 return;
16265 li = l->lv_first;
16266 if (li == NULL)
16267 return;
16268 bad = get_tv_string(&li->li_tv);
16269 li = li->li_next;
16270 if (li == NULL)
16271 return;
16272 good = get_tv_string(&li->li_tv);
16273 rettv->vval.v_number = test_edit_score(bad, good);
16274 #endif
16278 * "tolower(string)" function
16280 static void
16281 f_tolower(argvars, rettv)
16282 typval_T *argvars;
16283 typval_T *rettv;
16285 char_u *p;
16287 p = vim_strsave(get_tv_string(&argvars[0]));
16288 rettv->v_type = VAR_STRING;
16289 rettv->vval.v_string = p;
16291 if (p != NULL)
16292 while (*p != NUL)
16294 #ifdef FEAT_MBYTE
16295 int l;
16297 if (enc_utf8)
16299 int c, lc;
16301 c = utf_ptr2char(p);
16302 lc = utf_tolower(c);
16303 l = utf_ptr2len(p);
16304 /* TODO: reallocate string when byte count changes. */
16305 if (utf_char2len(lc) == l)
16306 utf_char2bytes(lc, p);
16307 p += l;
16309 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
16310 p += l; /* skip multi-byte character */
16311 else
16312 #endif
16314 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
16315 ++p;
16321 * "toupper(string)" function
16323 static void
16324 f_toupper(argvars, rettv)
16325 typval_T *argvars;
16326 typval_T *rettv;
16328 rettv->v_type = VAR_STRING;
16329 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
16333 * "tr(string, fromstr, tostr)" function
16335 static void
16336 f_tr(argvars, rettv)
16337 typval_T *argvars;
16338 typval_T *rettv;
16340 char_u *instr;
16341 char_u *fromstr;
16342 char_u *tostr;
16343 char_u *p;
16344 #ifdef FEAT_MBYTE
16345 int inlen;
16346 int fromlen;
16347 int tolen;
16348 int idx;
16349 char_u *cpstr;
16350 int cplen;
16351 int first = TRUE;
16352 #endif
16353 char_u buf[NUMBUFLEN];
16354 char_u buf2[NUMBUFLEN];
16355 garray_T ga;
16357 instr = get_tv_string(&argvars[0]);
16358 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
16359 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
16361 /* Default return value: empty string. */
16362 rettv->v_type = VAR_STRING;
16363 rettv->vval.v_string = NULL;
16364 if (fromstr == NULL || tostr == NULL)
16365 return; /* type error; errmsg already given */
16366 ga_init2(&ga, (int)sizeof(char), 80);
16368 #ifdef FEAT_MBYTE
16369 if (!has_mbyte)
16370 #endif
16371 /* not multi-byte: fromstr and tostr must be the same length */
16372 if (STRLEN(fromstr) != STRLEN(tostr))
16374 #ifdef FEAT_MBYTE
16375 error:
16376 #endif
16377 EMSG2(_(e_invarg2), fromstr);
16378 ga_clear(&ga);
16379 return;
16382 /* fromstr and tostr have to contain the same number of chars */
16383 while (*instr != NUL)
16385 #ifdef FEAT_MBYTE
16386 if (has_mbyte)
16388 inlen = (*mb_ptr2len)(instr);
16389 cpstr = instr;
16390 cplen = inlen;
16391 idx = 0;
16392 for (p = fromstr; *p != NUL; p += fromlen)
16394 fromlen = (*mb_ptr2len)(p);
16395 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
16397 for (p = tostr; *p != NUL; p += tolen)
16399 tolen = (*mb_ptr2len)(p);
16400 if (idx-- == 0)
16402 cplen = tolen;
16403 cpstr = p;
16404 break;
16407 if (*p == NUL) /* tostr is shorter than fromstr */
16408 goto error;
16409 break;
16411 ++idx;
16414 if (first && cpstr == instr)
16416 /* Check that fromstr and tostr have the same number of
16417 * (multi-byte) characters. Done only once when a character
16418 * of instr doesn't appear in fromstr. */
16419 first = FALSE;
16420 for (p = tostr; *p != NUL; p += tolen)
16422 tolen = (*mb_ptr2len)(p);
16423 --idx;
16425 if (idx != 0)
16426 goto error;
16429 ga_grow(&ga, cplen);
16430 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
16431 ga.ga_len += cplen;
16433 instr += inlen;
16435 else
16436 #endif
16438 /* When not using multi-byte chars we can do it faster. */
16439 p = vim_strchr(fromstr, *instr);
16440 if (p != NULL)
16441 ga_append(&ga, tostr[p - fromstr]);
16442 else
16443 ga_append(&ga, *instr);
16444 ++instr;
16448 /* add a terminating NUL */
16449 ga_grow(&ga, 1);
16450 ga_append(&ga, NUL);
16452 rettv->vval.v_string = ga.ga_data;
16456 * "type(expr)" function
16458 static void
16459 f_type(argvars, rettv)
16460 typval_T *argvars;
16461 typval_T *rettv;
16463 int n;
16465 switch (argvars[0].v_type)
16467 case VAR_NUMBER: n = 0; break;
16468 case VAR_STRING: n = 1; break;
16469 case VAR_FUNC: n = 2; break;
16470 case VAR_LIST: n = 3; break;
16471 case VAR_DICT: n = 4; break;
16472 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
16474 rettv->vval.v_number = n;
16478 * "values(dict)" function
16480 static void
16481 f_values(argvars, rettv)
16482 typval_T *argvars;
16483 typval_T *rettv;
16485 dict_list(argvars, rettv, 1);
16489 * "virtcol(string)" function
16491 static void
16492 f_virtcol(argvars, rettv)
16493 typval_T *argvars;
16494 typval_T *rettv;
16496 colnr_T vcol = 0;
16497 pos_T *fp;
16498 int fnum = curbuf->b_fnum;
16500 fp = var2fpos(&argvars[0], FALSE, &fnum);
16501 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
16502 && fnum == curbuf->b_fnum)
16504 getvvcol(curwin, fp, NULL, NULL, &vcol);
16505 ++vcol;
16508 rettv->vval.v_number = vcol;
16512 * "visualmode()" function
16514 /*ARGSUSED*/
16515 static void
16516 f_visualmode(argvars, rettv)
16517 typval_T *argvars;
16518 typval_T *rettv;
16520 #ifdef FEAT_VISUAL
16521 char_u str[2];
16523 rettv->v_type = VAR_STRING;
16524 str[0] = curbuf->b_visual_mode_eval;
16525 str[1] = NUL;
16526 rettv->vval.v_string = vim_strsave(str);
16528 /* A non-zero number or non-empty string argument: reset mode. */
16529 if ((argvars[0].v_type == VAR_NUMBER
16530 && argvars[0].vval.v_number != 0)
16531 || (argvars[0].v_type == VAR_STRING
16532 && *get_tv_string(&argvars[0]) != NUL))
16533 curbuf->b_visual_mode_eval = NUL;
16534 #else
16535 rettv->vval.v_number = 0; /* return anything, it won't work anyway */
16536 #endif
16540 * "winbufnr(nr)" function
16542 static void
16543 f_winbufnr(argvars, rettv)
16544 typval_T *argvars;
16545 typval_T *rettv;
16547 win_T *wp;
16549 wp = find_win_by_nr(&argvars[0], NULL);
16550 if (wp == NULL)
16551 rettv->vval.v_number = -1;
16552 else
16553 rettv->vval.v_number = wp->w_buffer->b_fnum;
16557 * "wincol()" function
16559 /*ARGSUSED*/
16560 static void
16561 f_wincol(argvars, rettv)
16562 typval_T *argvars;
16563 typval_T *rettv;
16565 validate_cursor();
16566 rettv->vval.v_number = curwin->w_wcol + 1;
16570 * "winheight(nr)" function
16572 static void
16573 f_winheight(argvars, rettv)
16574 typval_T *argvars;
16575 typval_T *rettv;
16577 win_T *wp;
16579 wp = find_win_by_nr(&argvars[0], NULL);
16580 if (wp == NULL)
16581 rettv->vval.v_number = -1;
16582 else
16583 rettv->vval.v_number = wp->w_height;
16587 * "winline()" function
16589 /*ARGSUSED*/
16590 static void
16591 f_winline(argvars, rettv)
16592 typval_T *argvars;
16593 typval_T *rettv;
16595 validate_cursor();
16596 rettv->vval.v_number = curwin->w_wrow + 1;
16600 * "winnr()" function
16602 /* ARGSUSED */
16603 static void
16604 f_winnr(argvars, rettv)
16605 typval_T *argvars;
16606 typval_T *rettv;
16608 int nr = 1;
16610 #ifdef FEAT_WINDOWS
16611 nr = get_winnr(curtab, &argvars[0]);
16612 #endif
16613 rettv->vval.v_number = nr;
16617 * "winrestcmd()" function
16619 /* ARGSUSED */
16620 static void
16621 f_winrestcmd(argvars, rettv)
16622 typval_T *argvars;
16623 typval_T *rettv;
16625 #ifdef FEAT_WINDOWS
16626 win_T *wp;
16627 int winnr = 1;
16628 garray_T ga;
16629 char_u buf[50];
16631 ga_init2(&ga, (int)sizeof(char), 70);
16632 for (wp = firstwin; wp != NULL; wp = wp->w_next)
16634 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
16635 ga_concat(&ga, buf);
16636 # ifdef FEAT_VERTSPLIT
16637 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
16638 ga_concat(&ga, buf);
16639 # endif
16640 ++winnr;
16642 ga_append(&ga, NUL);
16644 rettv->vval.v_string = ga.ga_data;
16645 #else
16646 rettv->vval.v_string = NULL;
16647 #endif
16648 rettv->v_type = VAR_STRING;
16652 * "winrestview()" function
16654 /* ARGSUSED */
16655 static void
16656 f_winrestview(argvars, rettv)
16657 typval_T *argvars;
16658 typval_T *rettv;
16660 dict_T *dict;
16662 if (argvars[0].v_type != VAR_DICT
16663 || (dict = argvars[0].vval.v_dict) == NULL)
16664 EMSG(_(e_invarg));
16665 else
16667 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
16668 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
16669 #ifdef FEAT_VIRTUALEDIT
16670 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
16671 #endif
16672 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
16673 curwin->w_set_curswant = FALSE;
16675 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
16676 #ifdef FEAT_DIFF
16677 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
16678 #endif
16679 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
16680 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
16682 check_cursor();
16683 changed_cline_bef_curs();
16684 invalidate_botline();
16685 redraw_later(VALID);
16687 if (curwin->w_topline == 0)
16688 curwin->w_topline = 1;
16689 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
16690 curwin->w_topline = curbuf->b_ml.ml_line_count;
16691 #ifdef FEAT_DIFF
16692 check_topfill(curwin, TRUE);
16693 #endif
16698 * "winsaveview()" function
16700 /* ARGSUSED */
16701 static void
16702 f_winsaveview(argvars, rettv)
16703 typval_T *argvars;
16704 typval_T *rettv;
16706 dict_T *dict;
16708 dict = dict_alloc();
16709 if (dict == NULL)
16710 return;
16711 rettv->v_type = VAR_DICT;
16712 rettv->vval.v_dict = dict;
16713 ++dict->dv_refcount;
16715 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
16716 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
16717 #ifdef FEAT_VIRTUALEDIT
16718 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
16719 #endif
16720 update_curswant();
16721 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
16723 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
16724 #ifdef FEAT_DIFF
16725 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
16726 #endif
16727 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
16728 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
16732 * "winwidth(nr)" function
16734 static void
16735 f_winwidth(argvars, rettv)
16736 typval_T *argvars;
16737 typval_T *rettv;
16739 win_T *wp;
16741 wp = find_win_by_nr(&argvars[0], NULL);
16742 if (wp == NULL)
16743 rettv->vval.v_number = -1;
16744 else
16745 #ifdef FEAT_VERTSPLIT
16746 rettv->vval.v_number = wp->w_width;
16747 #else
16748 rettv->vval.v_number = Columns;
16749 #endif
16753 * "writefile()" function
16755 static void
16756 f_writefile(argvars, rettv)
16757 typval_T *argvars;
16758 typval_T *rettv;
16760 int binary = FALSE;
16761 char_u *fname;
16762 FILE *fd;
16763 listitem_T *li;
16764 char_u *s;
16765 int ret = 0;
16766 int c;
16768 if (check_restricted() || check_secure())
16769 return;
16771 if (argvars[0].v_type != VAR_LIST)
16773 EMSG2(_(e_listarg), "writefile()");
16774 return;
16776 if (argvars[0].vval.v_list == NULL)
16777 return;
16779 if (argvars[2].v_type != VAR_UNKNOWN
16780 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
16781 binary = TRUE;
16783 /* Always open the file in binary mode, library functions have a mind of
16784 * their own about CR-LF conversion. */
16785 fname = get_tv_string(&argvars[1]);
16786 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
16788 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
16789 ret = -1;
16791 else
16793 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
16794 li = li->li_next)
16796 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
16798 if (*s == '\n')
16799 c = putc(NUL, fd);
16800 else
16801 c = putc(*s, fd);
16802 if (c == EOF)
16804 ret = -1;
16805 break;
16808 if (!binary || li->li_next != NULL)
16809 if (putc('\n', fd) == EOF)
16811 ret = -1;
16812 break;
16814 if (ret < 0)
16816 EMSG(_(e_write));
16817 break;
16820 fclose(fd);
16823 rettv->vval.v_number = ret;
16827 * Translate a String variable into a position.
16828 * Returns NULL when there is an error.
16830 static pos_T *
16831 var2fpos(varp, dollar_lnum, fnum)
16832 typval_T *varp;
16833 int dollar_lnum; /* TRUE when $ is last line */
16834 int *fnum; /* set to fnum for '0, 'A, etc. */
16836 char_u *name;
16837 static pos_T pos;
16838 pos_T *pp;
16840 /* Argument can be [lnum, col, coladd]. */
16841 if (varp->v_type == VAR_LIST)
16843 list_T *l;
16844 int len;
16845 int error = FALSE;
16846 listitem_T *li;
16848 l = varp->vval.v_list;
16849 if (l == NULL)
16850 return NULL;
16852 /* Get the line number */
16853 pos.lnum = list_find_nr(l, 0L, &error);
16854 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
16855 return NULL; /* invalid line number */
16857 /* Get the column number */
16858 pos.col = list_find_nr(l, 1L, &error);
16859 if (error)
16860 return NULL;
16861 len = (long)STRLEN(ml_get(pos.lnum));
16863 /* We accept "$" for the column number: last column. */
16864 li = list_find(l, 1L);
16865 if (li != NULL && li->li_tv.v_type == VAR_STRING
16866 && li->li_tv.vval.v_string != NULL
16867 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
16868 pos.col = len + 1;
16870 /* Accept a position up to the NUL after the line. */
16871 if (pos.col == 0 || (int)pos.col > len + 1)
16872 return NULL; /* invalid column number */
16873 --pos.col;
16875 #ifdef FEAT_VIRTUALEDIT
16876 /* Get the virtual offset. Defaults to zero. */
16877 pos.coladd = list_find_nr(l, 2L, &error);
16878 if (error)
16879 pos.coladd = 0;
16880 #endif
16882 return &pos;
16885 name = get_tv_string_chk(varp);
16886 if (name == NULL)
16887 return NULL;
16888 if (name[0] == '.') /* cursor */
16889 return &curwin->w_cursor;
16890 if (name[0] == '\'') /* mark */
16892 pp = getmark_fnum(name[1], FALSE, fnum);
16893 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
16894 return NULL;
16895 return pp;
16898 #ifdef FEAT_VIRTUALEDIT
16899 pos.coladd = 0;
16900 #endif
16902 if (name[0] == 'w' && dollar_lnum)
16904 pos.col = 0;
16905 if (name[1] == '0') /* "w0": first visible line */
16907 update_topline();
16908 pos.lnum = curwin->w_topline;
16909 return &pos;
16911 else if (name[1] == '$') /* "w$": last visible line */
16913 validate_botline();
16914 pos.lnum = curwin->w_botline - 1;
16915 return &pos;
16918 else if (name[0] == '$') /* last column or line */
16920 if (dollar_lnum)
16922 pos.lnum = curbuf->b_ml.ml_line_count;
16923 pos.col = 0;
16925 else
16927 pos.lnum = curwin->w_cursor.lnum;
16928 pos.col = (colnr_T)STRLEN(ml_get_curline());
16930 return &pos;
16932 return NULL;
16936 * Convert list in "arg" into a position and optional file number.
16937 * When "fnump" is NULL there is no file number, only 3 items.
16938 * Note that the column is passed on as-is, the caller may want to decrement
16939 * it to use 1 for the first column.
16940 * Return FAIL when conversion is not possible, doesn't check the position for
16941 * validity.
16943 static int
16944 list2fpos(arg, posp, fnump)
16945 typval_T *arg;
16946 pos_T *posp;
16947 int *fnump;
16949 list_T *l = arg->vval.v_list;
16950 long i = 0;
16951 long n;
16953 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
16954 * when "fnump" isn't NULL and "coladd" is optional. */
16955 if (arg->v_type != VAR_LIST
16956 || l == NULL
16957 || l->lv_len < (fnump == NULL ? 2 : 3)
16958 || l->lv_len > (fnump == NULL ? 3 : 4))
16959 return FAIL;
16961 if (fnump != NULL)
16963 n = list_find_nr(l, i++, NULL); /* fnum */
16964 if (n < 0)
16965 return FAIL;
16966 if (n == 0)
16967 n = curbuf->b_fnum; /* current buffer */
16968 *fnump = n;
16971 n = list_find_nr(l, i++, NULL); /* lnum */
16972 if (n < 0)
16973 return FAIL;
16974 posp->lnum = n;
16976 n = list_find_nr(l, i++, NULL); /* col */
16977 if (n < 0)
16978 return FAIL;
16979 posp->col = n;
16981 #ifdef FEAT_VIRTUALEDIT
16982 n = list_find_nr(l, i, NULL);
16983 if (n < 0)
16984 posp->coladd = 0;
16985 else
16986 posp->coladd = n;
16987 #endif
16989 return OK;
16993 * Get the length of an environment variable name.
16994 * Advance "arg" to the first character after the name.
16995 * Return 0 for error.
16997 static int
16998 get_env_len(arg)
16999 char_u **arg;
17001 char_u *p;
17002 int len;
17004 for (p = *arg; vim_isIDc(*p); ++p)
17006 if (p == *arg) /* no name found */
17007 return 0;
17009 len = (int)(p - *arg);
17010 *arg = p;
17011 return len;
17015 * Get the length of the name of a function or internal variable.
17016 * "arg" is advanced to the first non-white character after the name.
17017 * Return 0 if something is wrong.
17019 static int
17020 get_id_len(arg)
17021 char_u **arg;
17023 char_u *p;
17024 int len;
17026 /* Find the end of the name. */
17027 for (p = *arg; eval_isnamec(*p); ++p)
17029 if (p == *arg) /* no name found */
17030 return 0;
17032 len = (int)(p - *arg);
17033 *arg = skipwhite(p);
17035 return len;
17039 * Get the length of the name of a variable or function.
17040 * Only the name is recognized, does not handle ".key" or "[idx]".
17041 * "arg" is advanced to the first non-white character after the name.
17042 * Return -1 if curly braces expansion failed.
17043 * Return 0 if something else is wrong.
17044 * If the name contains 'magic' {}'s, expand them and return the
17045 * expanded name in an allocated string via 'alias' - caller must free.
17047 static int
17048 get_name_len(arg, alias, evaluate, verbose)
17049 char_u **arg;
17050 char_u **alias;
17051 int evaluate;
17052 int verbose;
17054 int len;
17055 char_u *p;
17056 char_u *expr_start;
17057 char_u *expr_end;
17059 *alias = NULL; /* default to no alias */
17061 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
17062 && (*arg)[2] == (int)KE_SNR)
17064 /* hard coded <SNR>, already translated */
17065 *arg += 3;
17066 return get_id_len(arg) + 3;
17068 len = eval_fname_script(*arg);
17069 if (len > 0)
17071 /* literal "<SID>", "s:" or "<SNR>" */
17072 *arg += len;
17076 * Find the end of the name; check for {} construction.
17078 p = find_name_end(*arg, &expr_start, &expr_end,
17079 len > 0 ? 0 : FNE_CHECK_START);
17080 if (expr_start != NULL)
17082 char_u *temp_string;
17084 if (!evaluate)
17086 len += (int)(p - *arg);
17087 *arg = skipwhite(p);
17088 return len;
17092 * Include any <SID> etc in the expanded string:
17093 * Thus the -len here.
17095 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
17096 if (temp_string == NULL)
17097 return -1;
17098 *alias = temp_string;
17099 *arg = skipwhite(p);
17100 return (int)STRLEN(temp_string);
17103 len += get_id_len(arg);
17104 if (len == 0 && verbose)
17105 EMSG2(_(e_invexpr2), *arg);
17107 return len;
17111 * Find the end of a variable or function name, taking care of magic braces.
17112 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
17113 * start and end of the first magic braces item.
17114 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
17115 * Return a pointer to just after the name. Equal to "arg" if there is no
17116 * valid name.
17118 static char_u *
17119 find_name_end(arg, expr_start, expr_end, flags)
17120 char_u *arg;
17121 char_u **expr_start;
17122 char_u **expr_end;
17123 int flags;
17125 int mb_nest = 0;
17126 int br_nest = 0;
17127 char_u *p;
17129 if (expr_start != NULL)
17131 *expr_start = NULL;
17132 *expr_end = NULL;
17135 /* Quick check for valid starting character. */
17136 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
17137 return arg;
17139 for (p = arg; *p != NUL
17140 && (eval_isnamec(*p)
17141 || *p == '{'
17142 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
17143 || mb_nest != 0
17144 || br_nest != 0); mb_ptr_adv(p))
17146 if (*p == '\'')
17148 /* skip over 'string' to avoid counting [ and ] inside it. */
17149 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
17151 if (*p == NUL)
17152 break;
17154 else if (*p == '"')
17156 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
17157 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
17158 if (*p == '\\' && p[1] != NUL)
17159 ++p;
17160 if (*p == NUL)
17161 break;
17164 if (mb_nest == 0)
17166 if (*p == '[')
17167 ++br_nest;
17168 else if (*p == ']')
17169 --br_nest;
17172 if (br_nest == 0)
17174 if (*p == '{')
17176 mb_nest++;
17177 if (expr_start != NULL && *expr_start == NULL)
17178 *expr_start = p;
17180 else if (*p == '}')
17182 mb_nest--;
17183 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
17184 *expr_end = p;
17189 return p;
17193 * Expands out the 'magic' {}'s in a variable/function name.
17194 * Note that this can call itself recursively, to deal with
17195 * constructs like foo{bar}{baz}{bam}
17196 * The four pointer arguments point to "foo{expre}ss{ion}bar"
17197 * "in_start" ^
17198 * "expr_start" ^
17199 * "expr_end" ^
17200 * "in_end" ^
17202 * Returns a new allocated string, which the caller must free.
17203 * Returns NULL for failure.
17205 static char_u *
17206 make_expanded_name(in_start, expr_start, expr_end, in_end)
17207 char_u *in_start;
17208 char_u *expr_start;
17209 char_u *expr_end;
17210 char_u *in_end;
17212 char_u c1;
17213 char_u *retval = NULL;
17214 char_u *temp_result;
17215 char_u *nextcmd = NULL;
17217 if (expr_end == NULL || in_end == NULL)
17218 return NULL;
17219 *expr_start = NUL;
17220 *expr_end = NUL;
17221 c1 = *in_end;
17222 *in_end = NUL;
17224 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
17225 if (temp_result != NULL && nextcmd == NULL)
17227 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
17228 + (in_end - expr_end) + 1));
17229 if (retval != NULL)
17231 STRCPY(retval, in_start);
17232 STRCAT(retval, temp_result);
17233 STRCAT(retval, expr_end + 1);
17236 vim_free(temp_result);
17238 *in_end = c1; /* put char back for error messages */
17239 *expr_start = '{';
17240 *expr_end = '}';
17242 if (retval != NULL)
17244 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
17245 if (expr_start != NULL)
17247 /* Further expansion! */
17248 temp_result = make_expanded_name(retval, expr_start,
17249 expr_end, temp_result);
17250 vim_free(retval);
17251 retval = temp_result;
17255 return retval;
17259 * Return TRUE if character "c" can be used in a variable or function name.
17260 * Does not include '{' or '}' for magic braces.
17262 static int
17263 eval_isnamec(c)
17264 int c;
17266 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
17270 * Return TRUE if character "c" can be used as the first character in a
17271 * variable or function name (excluding '{' and '}').
17273 static int
17274 eval_isnamec1(c)
17275 int c;
17277 return (ASCII_ISALPHA(c) || c == '_');
17281 * Set number v: variable to "val".
17283 void
17284 set_vim_var_nr(idx, val)
17285 int idx;
17286 long val;
17288 vimvars[idx].vv_nr = val;
17292 * Get number v: variable value.
17294 long
17295 get_vim_var_nr(idx)
17296 int idx;
17298 return vimvars[idx].vv_nr;
17301 #if defined(FEAT_AUTOCMD) || defined(PROTO)
17303 * Get string v: variable value. Uses a static buffer, can only be used once.
17305 char_u *
17306 get_vim_var_str(idx)
17307 int idx;
17309 return get_tv_string(&vimvars[idx].vv_tv);
17311 #endif
17314 * Set v:count, v:count1 and v:prevcount.
17316 void
17317 set_vcount(count, count1)
17318 long count;
17319 long count1;
17321 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
17322 vimvars[VV_COUNT].vv_nr = count;
17323 vimvars[VV_COUNT1].vv_nr = count1;
17327 * Set string v: variable to a copy of "val".
17329 void
17330 set_vim_var_string(idx, val, len)
17331 int idx;
17332 char_u *val;
17333 int len; /* length of "val" to use or -1 (whole string) */
17335 /* Need to do this (at least) once, since we can't initialize a union.
17336 * Will always be invoked when "v:progname" is set. */
17337 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
17339 vim_free(vimvars[idx].vv_str);
17340 if (val == NULL)
17341 vimvars[idx].vv_str = NULL;
17342 else if (len == -1)
17343 vimvars[idx].vv_str = vim_strsave(val);
17344 else
17345 vimvars[idx].vv_str = vim_strnsave(val, len);
17349 * Set v:register if needed.
17351 void
17352 set_reg_var(c)
17353 int c;
17355 char_u regname;
17357 if (c == 0 || c == ' ')
17358 regname = '"';
17359 else
17360 regname = c;
17361 /* Avoid free/alloc when the value is already right. */
17362 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
17363 set_vim_var_string(VV_REG, &regname, 1);
17367 * Get or set v:exception. If "oldval" == NULL, return the current value.
17368 * Otherwise, restore the value to "oldval" and return NULL.
17369 * Must always be called in pairs to save and restore v:exception! Does not
17370 * take care of memory allocations.
17372 char_u *
17373 v_exception(oldval)
17374 char_u *oldval;
17376 if (oldval == NULL)
17377 return vimvars[VV_EXCEPTION].vv_str;
17379 vimvars[VV_EXCEPTION].vv_str = oldval;
17380 return NULL;
17384 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
17385 * Otherwise, restore the value to "oldval" and return NULL.
17386 * Must always be called in pairs to save and restore v:throwpoint! Does not
17387 * take care of memory allocations.
17389 char_u *
17390 v_throwpoint(oldval)
17391 char_u *oldval;
17393 if (oldval == NULL)
17394 return vimvars[VV_THROWPOINT].vv_str;
17396 vimvars[VV_THROWPOINT].vv_str = oldval;
17397 return NULL;
17400 #if defined(FEAT_AUTOCMD) || defined(PROTO)
17402 * Set v:cmdarg.
17403 * If "eap" != NULL, use "eap" to generate the value and return the old value.
17404 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
17405 * Must always be called in pairs!
17407 char_u *
17408 set_cmdarg(eap, oldarg)
17409 exarg_T *eap;
17410 char_u *oldarg;
17412 char_u *oldval;
17413 char_u *newval;
17414 unsigned len;
17416 oldval = vimvars[VV_CMDARG].vv_str;
17417 if (eap == NULL)
17419 vim_free(oldval);
17420 vimvars[VV_CMDARG].vv_str = oldarg;
17421 return NULL;
17424 if (eap->force_bin == FORCE_BIN)
17425 len = 6;
17426 else if (eap->force_bin == FORCE_NOBIN)
17427 len = 8;
17428 else
17429 len = 0;
17431 if (eap->read_edit)
17432 len += 7;
17434 if (eap->force_ff != 0)
17435 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
17436 # ifdef FEAT_MBYTE
17437 if (eap->force_enc != 0)
17438 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
17439 if (eap->bad_char != 0)
17440 len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
17441 # endif
17443 newval = alloc(len + 1);
17444 if (newval == NULL)
17445 return NULL;
17447 if (eap->force_bin == FORCE_BIN)
17448 sprintf((char *)newval, " ++bin");
17449 else if (eap->force_bin == FORCE_NOBIN)
17450 sprintf((char *)newval, " ++nobin");
17451 else
17452 *newval = NUL;
17454 if (eap->read_edit)
17455 STRCAT(newval, " ++edit");
17457 if (eap->force_ff != 0)
17458 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
17459 eap->cmd + eap->force_ff);
17460 # ifdef FEAT_MBYTE
17461 if (eap->force_enc != 0)
17462 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
17463 eap->cmd + eap->force_enc);
17464 if (eap->bad_char != 0)
17465 sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
17466 eap->cmd + eap->bad_char);
17467 # endif
17468 vimvars[VV_CMDARG].vv_str = newval;
17469 return oldval;
17471 #endif
17474 * Get the value of internal variable "name".
17475 * Return OK or FAIL.
17477 static int
17478 get_var_tv(name, len, rettv, verbose)
17479 char_u *name;
17480 int len; /* length of "name" */
17481 typval_T *rettv; /* NULL when only checking existence */
17482 int verbose; /* may give error message */
17484 int ret = OK;
17485 typval_T *tv = NULL;
17486 typval_T atv;
17487 dictitem_T *v;
17488 int cc;
17490 /* truncate the name, so that we can use strcmp() */
17491 cc = name[len];
17492 name[len] = NUL;
17495 * Check for "b:changedtick".
17497 if (STRCMP(name, "b:changedtick") == 0)
17499 atv.v_type = VAR_NUMBER;
17500 atv.vval.v_number = curbuf->b_changedtick;
17501 tv = &atv;
17505 * Check for user-defined variables.
17507 else
17509 v = find_var(name, NULL);
17510 if (v != NULL)
17511 tv = &v->di_tv;
17514 if (tv == NULL)
17516 if (rettv != NULL && verbose)
17517 EMSG2(_(e_undefvar), name);
17518 ret = FAIL;
17520 else if (rettv != NULL)
17521 copy_tv(tv, rettv);
17523 name[len] = cc;
17525 return ret;
17529 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
17530 * Also handle function call with Funcref variable: func(expr)
17531 * Can all be combined: dict.func(expr)[idx]['func'](expr)
17533 static int
17534 handle_subscript(arg, rettv, evaluate, verbose)
17535 char_u **arg;
17536 typval_T *rettv;
17537 int evaluate; /* do more than finding the end */
17538 int verbose; /* give error messages */
17540 int ret = OK;
17541 dict_T *selfdict = NULL;
17542 char_u *s;
17543 int len;
17544 typval_T functv;
17546 while (ret == OK
17547 && (**arg == '['
17548 || (**arg == '.' && rettv->v_type == VAR_DICT)
17549 || (**arg == '(' && rettv->v_type == VAR_FUNC))
17550 && !vim_iswhite(*(*arg - 1)))
17552 if (**arg == '(')
17554 /* need to copy the funcref so that we can clear rettv */
17555 functv = *rettv;
17556 rettv->v_type = VAR_UNKNOWN;
17558 /* Invoke the function. Recursive! */
17559 s = functv.vval.v_string;
17560 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
17561 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
17562 &len, evaluate, selfdict);
17564 /* Clear the funcref afterwards, so that deleting it while
17565 * evaluating the arguments is possible (see test55). */
17566 clear_tv(&functv);
17568 /* Stop the expression evaluation when immediately aborting on
17569 * error, or when an interrupt occurred or an exception was thrown
17570 * but not caught. */
17571 if (aborting())
17573 if (ret == OK)
17574 clear_tv(rettv);
17575 ret = FAIL;
17577 dict_unref(selfdict);
17578 selfdict = NULL;
17580 else /* **arg == '[' || **arg == '.' */
17582 dict_unref(selfdict);
17583 if (rettv->v_type == VAR_DICT)
17585 selfdict = rettv->vval.v_dict;
17586 if (selfdict != NULL)
17587 ++selfdict->dv_refcount;
17589 else
17590 selfdict = NULL;
17591 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
17593 clear_tv(rettv);
17594 ret = FAIL;
17598 dict_unref(selfdict);
17599 return ret;
17603 * Allocate memory for a variable type-value, and make it emtpy (0 or NULL
17604 * value).
17606 static typval_T *
17607 alloc_tv()
17609 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
17613 * Allocate memory for a variable type-value, and assign a string to it.
17614 * The string "s" must have been allocated, it is consumed.
17615 * Return NULL for out of memory, the variable otherwise.
17617 static typval_T *
17618 alloc_string_tv(s)
17619 char_u *s;
17621 typval_T *rettv;
17623 rettv = alloc_tv();
17624 if (rettv != NULL)
17626 rettv->v_type = VAR_STRING;
17627 rettv->vval.v_string = s;
17629 else
17630 vim_free(s);
17631 return rettv;
17635 * Free the memory for a variable type-value.
17637 void
17638 free_tv(varp)
17639 typval_T *varp;
17641 if (varp != NULL)
17643 switch (varp->v_type)
17645 case VAR_FUNC:
17646 func_unref(varp->vval.v_string);
17647 /*FALLTHROUGH*/
17648 case VAR_STRING:
17649 vim_free(varp->vval.v_string);
17650 break;
17651 case VAR_LIST:
17652 list_unref(varp->vval.v_list);
17653 break;
17654 case VAR_DICT:
17655 dict_unref(varp->vval.v_dict);
17656 break;
17657 case VAR_NUMBER:
17658 case VAR_UNKNOWN:
17659 break;
17660 default:
17661 EMSG2(_(e_intern2), "free_tv()");
17662 break;
17664 vim_free(varp);
17669 * Free the memory for a variable value and set the value to NULL or 0.
17671 void
17672 clear_tv(varp)
17673 typval_T *varp;
17675 if (varp != NULL)
17677 switch (varp->v_type)
17679 case VAR_FUNC:
17680 func_unref(varp->vval.v_string);
17681 /*FALLTHROUGH*/
17682 case VAR_STRING:
17683 vim_free(varp->vval.v_string);
17684 varp->vval.v_string = NULL;
17685 break;
17686 case VAR_LIST:
17687 list_unref(varp->vval.v_list);
17688 varp->vval.v_list = NULL;
17689 break;
17690 case VAR_DICT:
17691 dict_unref(varp->vval.v_dict);
17692 varp->vval.v_dict = NULL;
17693 break;
17694 case VAR_NUMBER:
17695 varp->vval.v_number = 0;
17696 break;
17697 case VAR_UNKNOWN:
17698 break;
17699 default:
17700 EMSG2(_(e_intern2), "clear_tv()");
17702 varp->v_lock = 0;
17707 * Set the value of a variable to NULL without freeing items.
17709 static void
17710 init_tv(varp)
17711 typval_T *varp;
17713 if (varp != NULL)
17714 vim_memset(varp, 0, sizeof(typval_T));
17718 * Get the number value of a variable.
17719 * If it is a String variable, uses vim_str2nr().
17720 * For incompatible types, return 0.
17721 * get_tv_number_chk() is similar to get_tv_number(), but informs the
17722 * caller of incompatible types: it sets *denote to TRUE if "denote"
17723 * is not NULL or returns -1 otherwise.
17725 static long
17726 get_tv_number(varp)
17727 typval_T *varp;
17729 int error = FALSE;
17731 return get_tv_number_chk(varp, &error); /* return 0L on error */
17734 long
17735 get_tv_number_chk(varp, denote)
17736 typval_T *varp;
17737 int *denote;
17739 long n = 0L;
17741 switch (varp->v_type)
17743 case VAR_NUMBER:
17744 return (long)(varp->vval.v_number);
17745 case VAR_FUNC:
17746 EMSG(_("E703: Using a Funcref as a number"));
17747 break;
17748 case VAR_STRING:
17749 if (varp->vval.v_string != NULL)
17750 vim_str2nr(varp->vval.v_string, NULL, NULL,
17751 TRUE, TRUE, &n, NULL);
17752 return n;
17753 case VAR_LIST:
17754 EMSG(_("E745: Using a List as a number"));
17755 break;
17756 case VAR_DICT:
17757 EMSG(_("E728: Using a Dictionary as a number"));
17758 break;
17759 default:
17760 EMSG2(_(e_intern2), "get_tv_number()");
17761 break;
17763 if (denote == NULL) /* useful for values that must be unsigned */
17764 n = -1;
17765 else
17766 *denote = TRUE;
17767 return n;
17771 * Get the lnum from the first argument.
17772 * Also accepts ".", "$", etc., but that only works for the current buffer.
17773 * Returns -1 on error.
17775 static linenr_T
17776 get_tv_lnum(argvars)
17777 typval_T *argvars;
17779 typval_T rettv;
17780 linenr_T lnum;
17782 lnum = get_tv_number_chk(&argvars[0], NULL);
17783 if (lnum == 0) /* no valid number, try using line() */
17785 rettv.v_type = VAR_NUMBER;
17786 f_line(argvars, &rettv);
17787 lnum = rettv.vval.v_number;
17788 clear_tv(&rettv);
17790 return lnum;
17794 * Get the lnum from the first argument.
17795 * Also accepts "$", then "buf" is used.
17796 * Returns 0 on error.
17798 static linenr_T
17799 get_tv_lnum_buf(argvars, buf)
17800 typval_T *argvars;
17801 buf_T *buf;
17803 if (argvars[0].v_type == VAR_STRING
17804 && argvars[0].vval.v_string != NULL
17805 && argvars[0].vval.v_string[0] == '$'
17806 && buf != NULL)
17807 return buf->b_ml.ml_line_count;
17808 return get_tv_number_chk(&argvars[0], NULL);
17812 * Get the string value of a variable.
17813 * If it is a Number variable, the number is converted into a string.
17814 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
17815 * get_tv_string_buf() uses a given buffer.
17816 * If the String variable has never been set, return an empty string.
17817 * Never returns NULL;
17818 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
17819 * NULL on error.
17821 static char_u *
17822 get_tv_string(varp)
17823 typval_T *varp;
17825 static char_u mybuf[NUMBUFLEN];
17827 return get_tv_string_buf(varp, mybuf);
17830 static char_u *
17831 get_tv_string_buf(varp, buf)
17832 typval_T *varp;
17833 char_u *buf;
17835 char_u *res = get_tv_string_buf_chk(varp, buf);
17837 return res != NULL ? res : (char_u *)"";
17840 char_u *
17841 get_tv_string_chk(varp)
17842 typval_T *varp;
17844 static char_u mybuf[NUMBUFLEN];
17846 return get_tv_string_buf_chk(varp, mybuf);
17849 static char_u *
17850 get_tv_string_buf_chk(varp, buf)
17851 typval_T *varp;
17852 char_u *buf;
17854 switch (varp->v_type)
17856 case VAR_NUMBER:
17857 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
17858 return buf;
17859 case VAR_FUNC:
17860 EMSG(_("E729: using Funcref as a String"));
17861 break;
17862 case VAR_LIST:
17863 EMSG(_("E730: using List as a String"));
17864 break;
17865 case VAR_DICT:
17866 EMSG(_("E731: using Dictionary as a String"));
17867 break;
17868 case VAR_STRING:
17869 if (varp->vval.v_string != NULL)
17870 return varp->vval.v_string;
17871 return (char_u *)"";
17872 default:
17873 EMSG2(_(e_intern2), "get_tv_string_buf()");
17874 break;
17876 return NULL;
17880 * Find variable "name" in the list of variables.
17881 * Return a pointer to it if found, NULL if not found.
17882 * Careful: "a:0" variables don't have a name.
17883 * When "htp" is not NULL we are writing to the variable, set "htp" to the
17884 * hashtab_T used.
17886 static dictitem_T *
17887 find_var(name, htp)
17888 char_u *name;
17889 hashtab_T **htp;
17891 char_u *varname;
17892 hashtab_T *ht;
17894 ht = find_var_ht(name, &varname);
17895 if (htp != NULL)
17896 *htp = ht;
17897 if (ht == NULL)
17898 return NULL;
17899 return find_var_in_ht(ht, varname, htp != NULL);
17903 * Find variable "varname" in hashtab "ht".
17904 * Returns NULL if not found.
17906 static dictitem_T *
17907 find_var_in_ht(ht, varname, writing)
17908 hashtab_T *ht;
17909 char_u *varname;
17910 int writing;
17912 hashitem_T *hi;
17914 if (*varname == NUL)
17916 /* Must be something like "s:", otherwise "ht" would be NULL. */
17917 switch (varname[-2])
17919 case 's': return &SCRIPT_SV(current_SID).sv_var;
17920 case 'g': return &globvars_var;
17921 case 'v': return &vimvars_var;
17922 case 'b': return &curbuf->b_bufvar;
17923 case 'w': return &curwin->w_winvar;
17924 #ifdef FEAT_WINDOWS
17925 case 't': return &curtab->tp_winvar;
17926 #endif
17927 case 'l': return current_funccal == NULL
17928 ? NULL : &current_funccal->l_vars_var;
17929 case 'a': return current_funccal == NULL
17930 ? NULL : &current_funccal->l_avars_var;
17932 return NULL;
17935 hi = hash_find(ht, varname);
17936 if (HASHITEM_EMPTY(hi))
17938 /* For global variables we may try auto-loading the script. If it
17939 * worked find the variable again. Don't auto-load a script if it was
17940 * loaded already, otherwise it would be loaded every time when
17941 * checking if a function name is a Funcref variable. */
17942 if (ht == &globvarht && !writing
17943 && script_autoload(varname, FALSE) && !aborting())
17944 hi = hash_find(ht, varname);
17945 if (HASHITEM_EMPTY(hi))
17946 return NULL;
17948 return HI2DI(hi);
17952 * Find the hashtab used for a variable name.
17953 * Set "varname" to the start of name without ':'.
17955 static hashtab_T *
17956 find_var_ht(name, varname)
17957 char_u *name;
17958 char_u **varname;
17960 hashitem_T *hi;
17962 if (name[1] != ':')
17964 /* The name must not start with a colon or #. */
17965 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
17966 return NULL;
17967 *varname = name;
17969 /* "version" is "v:version" in all scopes */
17970 hi = hash_find(&compat_hashtab, name);
17971 if (!HASHITEM_EMPTY(hi))
17972 return &compat_hashtab;
17974 if (current_funccal == NULL)
17975 return &globvarht; /* global variable */
17976 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
17978 *varname = name + 2;
17979 if (*name == 'g') /* global variable */
17980 return &globvarht;
17981 /* There must be no ':' or '#' in the rest of the name, unless g: is used
17983 if (vim_strchr(name + 2, ':') != NULL
17984 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
17985 return NULL;
17986 if (*name == 'b') /* buffer variable */
17987 return &curbuf->b_vars.dv_hashtab;
17988 if (*name == 'w') /* window variable */
17989 return &curwin->w_vars.dv_hashtab;
17990 #ifdef FEAT_WINDOWS
17991 if (*name == 't') /* tab page variable */
17992 return &curtab->tp_vars.dv_hashtab;
17993 #endif
17994 if (*name == 'v') /* v: variable */
17995 return &vimvarht;
17996 if (*name == 'a' && current_funccal != NULL) /* function argument */
17997 return &current_funccal->l_avars.dv_hashtab;
17998 if (*name == 'l' && current_funccal != NULL) /* local function variable */
17999 return &current_funccal->l_vars.dv_hashtab;
18000 if (*name == 's' /* script variable */
18001 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
18002 return &SCRIPT_VARS(current_SID);
18003 return NULL;
18007 * Get the string value of a (global/local) variable.
18008 * Returns NULL when it doesn't exist.
18010 char_u *
18011 get_var_value(name)
18012 char_u *name;
18014 dictitem_T *v;
18016 v = find_var(name, NULL);
18017 if (v == NULL)
18018 return NULL;
18019 return get_tv_string(&v->di_tv);
18023 * Allocate a new hashtab for a sourced script. It will be used while
18024 * sourcing this script and when executing functions defined in the script.
18026 void
18027 new_script_vars(id)
18028 scid_T id;
18030 int i;
18031 hashtab_T *ht;
18032 scriptvar_T *sv;
18034 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
18036 /* Re-allocating ga_data means that an ht_array pointing to
18037 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
18038 * at its init value. Also reset "v_dict", it's always the same. */
18039 for (i = 1; i <= ga_scripts.ga_len; ++i)
18041 ht = &SCRIPT_VARS(i);
18042 if (ht->ht_mask == HT_INIT_SIZE - 1)
18043 ht->ht_array = ht->ht_smallarray;
18044 sv = &SCRIPT_SV(i);
18045 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
18048 while (ga_scripts.ga_len < id)
18050 sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
18051 init_var_dict(&sv->sv_dict, &sv->sv_var);
18052 ++ga_scripts.ga_len;
18058 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
18059 * point to it.
18061 void
18062 init_var_dict(dict, dict_var)
18063 dict_T *dict;
18064 dictitem_T *dict_var;
18066 hash_init(&dict->dv_hashtab);
18067 dict->dv_refcount = 99999;
18068 dict_var->di_tv.vval.v_dict = dict;
18069 dict_var->di_tv.v_type = VAR_DICT;
18070 dict_var->di_tv.v_lock = VAR_FIXED;
18071 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
18072 dict_var->di_key[0] = NUL;
18076 * Clean up a list of internal variables.
18077 * Frees all allocated variables and the value they contain.
18078 * Clears hashtab "ht", does not free it.
18080 void
18081 vars_clear(ht)
18082 hashtab_T *ht;
18084 vars_clear_ext(ht, TRUE);
18088 * Like vars_clear(), but only free the value if "free_val" is TRUE.
18090 static void
18091 vars_clear_ext(ht, free_val)
18092 hashtab_T *ht;
18093 int free_val;
18095 int todo;
18096 hashitem_T *hi;
18097 dictitem_T *v;
18099 hash_lock(ht);
18100 todo = (int)ht->ht_used;
18101 for (hi = ht->ht_array; todo > 0; ++hi)
18103 if (!HASHITEM_EMPTY(hi))
18105 --todo;
18107 /* Free the variable. Don't remove it from the hashtab,
18108 * ht_array might change then. hash_clear() takes care of it
18109 * later. */
18110 v = HI2DI(hi);
18111 if (free_val)
18112 clear_tv(&v->di_tv);
18113 if ((v->di_flags & DI_FLAGS_FIX) == 0)
18114 vim_free(v);
18117 hash_clear(ht);
18118 ht->ht_used = 0;
18122 * Delete a variable from hashtab "ht" at item "hi".
18123 * Clear the variable value and free the dictitem.
18125 static void
18126 delete_var(ht, hi)
18127 hashtab_T *ht;
18128 hashitem_T *hi;
18130 dictitem_T *di = HI2DI(hi);
18132 hash_remove(ht, hi);
18133 clear_tv(&di->di_tv);
18134 vim_free(di);
18138 * List the value of one internal variable.
18140 static void
18141 list_one_var(v, prefix, first)
18142 dictitem_T *v;
18143 char_u *prefix;
18144 int *first;
18146 char_u *tofree;
18147 char_u *s;
18148 char_u numbuf[NUMBUFLEN];
18150 s = echo_string(&v->di_tv, &tofree, numbuf, ++current_copyID);
18151 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
18152 s == NULL ? (char_u *)"" : s, first);
18153 vim_free(tofree);
18156 static void
18157 list_one_var_a(prefix, name, type, string, first)
18158 char_u *prefix;
18159 char_u *name;
18160 int type;
18161 char_u *string;
18162 int *first; /* when TRUE clear rest of screen and set to FALSE */
18164 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
18165 msg_start();
18166 msg_puts(prefix);
18167 if (name != NULL) /* "a:" vars don't have a name stored */
18168 msg_puts(name);
18169 msg_putchar(' ');
18170 msg_advance(22);
18171 if (type == VAR_NUMBER)
18172 msg_putchar('#');
18173 else if (type == VAR_FUNC)
18174 msg_putchar('*');
18175 else if (type == VAR_LIST)
18177 msg_putchar('[');
18178 if (*string == '[')
18179 ++string;
18181 else if (type == VAR_DICT)
18183 msg_putchar('{');
18184 if (*string == '{')
18185 ++string;
18187 else
18188 msg_putchar(' ');
18190 msg_outtrans(string);
18192 if (type == VAR_FUNC)
18193 msg_puts((char_u *)"()");
18194 if (*first)
18196 msg_clr_eos();
18197 *first = FALSE;
18202 * Set variable "name" to value in "tv".
18203 * If the variable already exists, the value is updated.
18204 * Otherwise the variable is created.
18206 static void
18207 set_var(name, tv, copy)
18208 char_u *name;
18209 typval_T *tv;
18210 int copy; /* make copy of value in "tv" */
18212 dictitem_T *v;
18213 char_u *varname;
18214 hashtab_T *ht;
18215 char_u *p;
18217 if (tv->v_type == VAR_FUNC)
18219 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
18220 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
18221 ? name[2] : name[0]))
18223 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
18224 return;
18226 if (function_exists(name))
18228 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
18229 name);
18230 return;
18234 ht = find_var_ht(name, &varname);
18235 if (ht == NULL || *varname == NUL)
18237 EMSG2(_(e_illvar), name);
18238 return;
18241 v = find_var_in_ht(ht, varname, TRUE);
18242 if (v != NULL)
18244 /* existing variable, need to clear the value */
18245 if (var_check_ro(v->di_flags, name)
18246 || tv_check_lock(v->di_tv.v_lock, name))
18247 return;
18248 if (v->di_tv.v_type != tv->v_type
18249 && !((v->di_tv.v_type == VAR_STRING
18250 || v->di_tv.v_type == VAR_NUMBER)
18251 && (tv->v_type == VAR_STRING
18252 || tv->v_type == VAR_NUMBER)))
18254 EMSG2(_("E706: Variable type mismatch for: %s"), name);
18255 return;
18259 * Handle setting internal v: variables separately: we don't change
18260 * the type.
18262 if (ht == &vimvarht)
18264 if (v->di_tv.v_type == VAR_STRING)
18266 vim_free(v->di_tv.vval.v_string);
18267 if (copy || tv->v_type != VAR_STRING)
18268 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
18269 else
18271 /* Take over the string to avoid an extra alloc/free. */
18272 v->di_tv.vval.v_string = tv->vval.v_string;
18273 tv->vval.v_string = NULL;
18276 else if (v->di_tv.v_type != VAR_NUMBER)
18277 EMSG2(_(e_intern2), "set_var()");
18278 else
18279 v->di_tv.vval.v_number = get_tv_number(tv);
18280 return;
18283 clear_tv(&v->di_tv);
18285 else /* add a new variable */
18287 /* Can't add "v:" variable. */
18288 if (ht == &vimvarht)
18290 EMSG2(_(e_illvar), name);
18291 return;
18294 /* Make sure the variable name is valid. */
18295 for (p = varname; *p != NUL; ++p)
18296 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
18297 && *p != AUTOLOAD_CHAR)
18299 EMSG2(_(e_illvar), varname);
18300 return;
18303 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
18304 + STRLEN(varname)));
18305 if (v == NULL)
18306 return;
18307 STRCPY(v->di_key, varname);
18308 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
18310 vim_free(v);
18311 return;
18313 v->di_flags = 0;
18316 if (copy || tv->v_type == VAR_NUMBER)
18317 copy_tv(tv, &v->di_tv);
18318 else
18320 v->di_tv = *tv;
18321 v->di_tv.v_lock = 0;
18322 init_tv(tv);
18327 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
18328 * Also give an error message.
18330 static int
18331 var_check_ro(flags, name)
18332 int flags;
18333 char_u *name;
18335 if (flags & DI_FLAGS_RO)
18337 EMSG2(_(e_readonlyvar), name);
18338 return TRUE;
18340 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
18342 EMSG2(_(e_readonlysbx), name);
18343 return TRUE;
18345 return FALSE;
18349 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
18350 * Also give an error message.
18352 static int
18353 var_check_fixed(flags, name)
18354 int flags;
18355 char_u *name;
18357 if (flags & DI_FLAGS_FIX)
18359 EMSG2(_("E795: Cannot delete variable %s"), name);
18360 return TRUE;
18362 return FALSE;
18366 * Return TRUE if typeval "tv" is set to be locked (immutable).
18367 * Also give an error message, using "name".
18369 static int
18370 tv_check_lock(lock, name)
18371 int lock;
18372 char_u *name;
18374 if (lock & VAR_LOCKED)
18376 EMSG2(_("E741: Value is locked: %s"),
18377 name == NULL ? (char_u *)_("Unknown") : name);
18378 return TRUE;
18380 if (lock & VAR_FIXED)
18382 EMSG2(_("E742: Cannot change value of %s"),
18383 name == NULL ? (char_u *)_("Unknown") : name);
18384 return TRUE;
18386 return FALSE;
18390 * Copy the values from typval_T "from" to typval_T "to".
18391 * When needed allocates string or increases reference count.
18392 * Does not make a copy of a list or dict but copies the reference!
18394 static void
18395 copy_tv(from, to)
18396 typval_T *from;
18397 typval_T *to;
18399 to->v_type = from->v_type;
18400 to->v_lock = 0;
18401 switch (from->v_type)
18403 case VAR_NUMBER:
18404 to->vval.v_number = from->vval.v_number;
18405 break;
18406 case VAR_STRING:
18407 case VAR_FUNC:
18408 if (from->vval.v_string == NULL)
18409 to->vval.v_string = NULL;
18410 else
18412 to->vval.v_string = vim_strsave(from->vval.v_string);
18413 if (from->v_type == VAR_FUNC)
18414 func_ref(to->vval.v_string);
18416 break;
18417 case VAR_LIST:
18418 if (from->vval.v_list == NULL)
18419 to->vval.v_list = NULL;
18420 else
18422 to->vval.v_list = from->vval.v_list;
18423 ++to->vval.v_list->lv_refcount;
18425 break;
18426 case VAR_DICT:
18427 if (from->vval.v_dict == NULL)
18428 to->vval.v_dict = NULL;
18429 else
18431 to->vval.v_dict = from->vval.v_dict;
18432 ++to->vval.v_dict->dv_refcount;
18434 break;
18435 default:
18436 EMSG2(_(e_intern2), "copy_tv()");
18437 break;
18442 * Make a copy of an item.
18443 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
18444 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
18445 * reference to an already copied list/dict can be used.
18446 * Returns FAIL or OK.
18448 static int
18449 item_copy(from, to, deep, copyID)
18450 typval_T *from;
18451 typval_T *to;
18452 int deep;
18453 int copyID;
18455 static int recurse = 0;
18456 int ret = OK;
18458 if (recurse >= DICT_MAXNEST)
18460 EMSG(_("E698: variable nested too deep for making a copy"));
18461 return FAIL;
18463 ++recurse;
18465 switch (from->v_type)
18467 case VAR_NUMBER:
18468 case VAR_STRING:
18469 case VAR_FUNC:
18470 copy_tv(from, to);
18471 break;
18472 case VAR_LIST:
18473 to->v_type = VAR_LIST;
18474 to->v_lock = 0;
18475 if (from->vval.v_list == NULL)
18476 to->vval.v_list = NULL;
18477 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
18479 /* use the copy made earlier */
18480 to->vval.v_list = from->vval.v_list->lv_copylist;
18481 ++to->vval.v_list->lv_refcount;
18483 else
18484 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
18485 if (to->vval.v_list == NULL)
18486 ret = FAIL;
18487 break;
18488 case VAR_DICT:
18489 to->v_type = VAR_DICT;
18490 to->v_lock = 0;
18491 if (from->vval.v_dict == NULL)
18492 to->vval.v_dict = NULL;
18493 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
18495 /* use the copy made earlier */
18496 to->vval.v_dict = from->vval.v_dict->dv_copydict;
18497 ++to->vval.v_dict->dv_refcount;
18499 else
18500 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
18501 if (to->vval.v_dict == NULL)
18502 ret = FAIL;
18503 break;
18504 default:
18505 EMSG2(_(e_intern2), "item_copy()");
18506 ret = FAIL;
18508 --recurse;
18509 return ret;
18513 * ":echo expr1 ..." print each argument separated with a space, add a
18514 * newline at the end.
18515 * ":echon expr1 ..." print each argument plain.
18517 void
18518 ex_echo(eap)
18519 exarg_T *eap;
18521 char_u *arg = eap->arg;
18522 typval_T rettv;
18523 char_u *tofree;
18524 char_u *p;
18525 int needclr = TRUE;
18526 int atstart = TRUE;
18527 char_u numbuf[NUMBUFLEN];
18529 if (eap->skip)
18530 ++emsg_skip;
18531 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
18533 p = arg;
18534 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
18537 * Report the invalid expression unless the expression evaluation
18538 * has been cancelled due to an aborting error, an interrupt, or an
18539 * exception.
18541 if (!aborting())
18542 EMSG2(_(e_invexpr2), p);
18543 break;
18545 if (!eap->skip)
18547 if (atstart)
18549 atstart = FALSE;
18550 /* Call msg_start() after eval1(), evaluating the expression
18551 * may cause a message to appear. */
18552 if (eap->cmdidx == CMD_echo)
18553 msg_start();
18555 else if (eap->cmdidx == CMD_echo)
18556 msg_puts_attr((char_u *)" ", echo_attr);
18557 p = echo_string(&rettv, &tofree, numbuf, ++current_copyID);
18558 if (p != NULL)
18559 for ( ; *p != NUL && !got_int; ++p)
18561 if (*p == '\n' || *p == '\r' || *p == TAB)
18563 if (*p != TAB && needclr)
18565 /* remove any text still there from the command */
18566 msg_clr_eos();
18567 needclr = FALSE;
18569 msg_putchar_attr(*p, echo_attr);
18571 else
18573 #ifdef FEAT_MBYTE
18574 if (has_mbyte)
18576 int i = (*mb_ptr2len)(p);
18578 (void)msg_outtrans_len_attr(p, i, echo_attr);
18579 p += i - 1;
18581 else
18582 #endif
18583 (void)msg_outtrans_len_attr(p, 1, echo_attr);
18586 vim_free(tofree);
18588 clear_tv(&rettv);
18589 arg = skipwhite(arg);
18591 eap->nextcmd = check_nextcmd(arg);
18593 if (eap->skip)
18594 --emsg_skip;
18595 else
18597 /* remove text that may still be there from the command */
18598 if (needclr)
18599 msg_clr_eos();
18600 if (eap->cmdidx == CMD_echo)
18601 msg_end();
18606 * ":echohl {name}".
18608 void
18609 ex_echohl(eap)
18610 exarg_T *eap;
18612 int id;
18614 id = syn_name2id(eap->arg);
18615 if (id == 0)
18616 echo_attr = 0;
18617 else
18618 echo_attr = syn_id2attr(id);
18622 * ":execute expr1 ..." execute the result of an expression.
18623 * ":echomsg expr1 ..." Print a message
18624 * ":echoerr expr1 ..." Print an error
18625 * Each gets spaces around each argument and a newline at the end for
18626 * echo commands
18628 void
18629 ex_execute(eap)
18630 exarg_T *eap;
18632 char_u *arg = eap->arg;
18633 typval_T rettv;
18634 int ret = OK;
18635 char_u *p;
18636 garray_T ga;
18637 int len;
18638 int save_did_emsg;
18640 ga_init2(&ga, 1, 80);
18642 if (eap->skip)
18643 ++emsg_skip;
18644 while (*arg != NUL && *arg != '|' && *arg != '\n')
18646 p = arg;
18647 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
18650 * Report the invalid expression unless the expression evaluation
18651 * has been cancelled due to an aborting error, an interrupt, or an
18652 * exception.
18654 if (!aborting())
18655 EMSG2(_(e_invexpr2), p);
18656 ret = FAIL;
18657 break;
18660 if (!eap->skip)
18662 p = get_tv_string(&rettv);
18663 len = (int)STRLEN(p);
18664 if (ga_grow(&ga, len + 2) == FAIL)
18666 clear_tv(&rettv);
18667 ret = FAIL;
18668 break;
18670 if (ga.ga_len)
18671 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
18672 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
18673 ga.ga_len += len;
18676 clear_tv(&rettv);
18677 arg = skipwhite(arg);
18680 if (ret != FAIL && ga.ga_data != NULL)
18682 if (eap->cmdidx == CMD_echomsg)
18684 MSG_ATTR(ga.ga_data, echo_attr);
18685 out_flush();
18687 else if (eap->cmdidx == CMD_echoerr)
18689 /* We don't want to abort following commands, restore did_emsg. */
18690 save_did_emsg = did_emsg;
18691 EMSG((char_u *)ga.ga_data);
18692 if (!force_abort)
18693 did_emsg = save_did_emsg;
18695 else if (eap->cmdidx == CMD_execute)
18696 do_cmdline((char_u *)ga.ga_data,
18697 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
18700 ga_clear(&ga);
18702 if (eap->skip)
18703 --emsg_skip;
18705 eap->nextcmd = check_nextcmd(arg);
18709 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
18710 * "arg" points to the "&" or '+' when called, to "option" when returning.
18711 * Returns NULL when no option name found. Otherwise pointer to the char
18712 * after the option name.
18714 static char_u *
18715 find_option_end(arg, opt_flags)
18716 char_u **arg;
18717 int *opt_flags;
18719 char_u *p = *arg;
18721 ++p;
18722 if (*p == 'g' && p[1] == ':')
18724 *opt_flags = OPT_GLOBAL;
18725 p += 2;
18727 else if (*p == 'l' && p[1] == ':')
18729 *opt_flags = OPT_LOCAL;
18730 p += 2;
18732 else
18733 *opt_flags = 0;
18735 if (!ASCII_ISALPHA(*p))
18736 return NULL;
18737 *arg = p;
18739 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
18740 p += 4; /* termcap option */
18741 else
18742 while (ASCII_ISALPHA(*p))
18743 ++p;
18744 return p;
18748 * ":function"
18750 void
18751 ex_function(eap)
18752 exarg_T *eap;
18754 char_u *theline;
18755 int j;
18756 int c;
18757 int saved_did_emsg;
18758 char_u *name = NULL;
18759 char_u *p;
18760 char_u *arg;
18761 char_u *line_arg = NULL;
18762 garray_T newargs;
18763 garray_T newlines;
18764 int varargs = FALSE;
18765 int mustend = FALSE;
18766 int flags = 0;
18767 ufunc_T *fp;
18768 int indent;
18769 int nesting;
18770 char_u *skip_until = NULL;
18771 dictitem_T *v;
18772 funcdict_T fudi;
18773 static int func_nr = 0; /* number for nameless function */
18774 int paren;
18775 hashtab_T *ht;
18776 int todo;
18777 hashitem_T *hi;
18778 int sourcing_lnum_off;
18781 * ":function" without argument: list functions.
18783 if (ends_excmd(*eap->arg))
18785 if (!eap->skip)
18787 todo = (int)func_hashtab.ht_used;
18788 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
18790 if (!HASHITEM_EMPTY(hi))
18792 --todo;
18793 fp = HI2UF(hi);
18794 if (!isdigit(*fp->uf_name))
18795 list_func_head(fp, FALSE);
18799 eap->nextcmd = check_nextcmd(eap->arg);
18800 return;
18804 * ":function /pat": list functions matching pattern.
18806 if (*eap->arg == '/')
18808 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
18809 if (!eap->skip)
18811 regmatch_T regmatch;
18813 c = *p;
18814 *p = NUL;
18815 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
18816 *p = c;
18817 if (regmatch.regprog != NULL)
18819 regmatch.rm_ic = p_ic;
18821 todo = (int)func_hashtab.ht_used;
18822 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
18824 if (!HASHITEM_EMPTY(hi))
18826 --todo;
18827 fp = HI2UF(hi);
18828 if (!isdigit(*fp->uf_name)
18829 && vim_regexec(&regmatch, fp->uf_name, 0))
18830 list_func_head(fp, FALSE);
18835 if (*p == '/')
18836 ++p;
18837 eap->nextcmd = check_nextcmd(p);
18838 return;
18842 * Get the function name. There are these situations:
18843 * func normal function name
18844 * "name" == func, "fudi.fd_dict" == NULL
18845 * dict.func new dictionary entry
18846 * "name" == NULL, "fudi.fd_dict" set,
18847 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
18848 * dict.func existing dict entry with a Funcref
18849 * "name" == func, "fudi.fd_dict" set,
18850 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
18851 * dict.func existing dict entry that's not a Funcref
18852 * "name" == NULL, "fudi.fd_dict" set,
18853 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
18855 p = eap->arg;
18856 name = trans_function_name(&p, eap->skip, 0, &fudi);
18857 paren = (vim_strchr(p, '(') != NULL);
18858 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
18861 * Return on an invalid expression in braces, unless the expression
18862 * evaluation has been cancelled due to an aborting error, an
18863 * interrupt, or an exception.
18865 if (!aborting())
18867 if (!eap->skip && fudi.fd_newkey != NULL)
18868 EMSG2(_(e_dictkey), fudi.fd_newkey);
18869 vim_free(fudi.fd_newkey);
18870 return;
18872 else
18873 eap->skip = TRUE;
18876 /* An error in a function call during evaluation of an expression in magic
18877 * braces should not cause the function not to be defined. */
18878 saved_did_emsg = did_emsg;
18879 did_emsg = FALSE;
18882 * ":function func" with only function name: list function.
18884 if (!paren)
18886 if (!ends_excmd(*skipwhite(p)))
18888 EMSG(_(e_trailing));
18889 goto ret_free;
18891 eap->nextcmd = check_nextcmd(p);
18892 if (eap->nextcmd != NULL)
18893 *p = NUL;
18894 if (!eap->skip && !got_int)
18896 fp = find_func(name);
18897 if (fp != NULL)
18899 list_func_head(fp, TRUE);
18900 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
18902 if (FUNCLINE(fp, j) == NULL)
18903 continue;
18904 msg_putchar('\n');
18905 msg_outnum((long)(j + 1));
18906 if (j < 9)
18907 msg_putchar(' ');
18908 if (j < 99)
18909 msg_putchar(' ');
18910 msg_prt_line(FUNCLINE(fp, j), FALSE);
18911 out_flush(); /* show a line at a time */
18912 ui_breakcheck();
18914 if (!got_int)
18916 msg_putchar('\n');
18917 msg_puts((char_u *)" endfunction");
18920 else
18921 emsg_funcname("E123: Undefined function: %s", name);
18923 goto ret_free;
18927 * ":function name(arg1, arg2)" Define function.
18929 p = skipwhite(p);
18930 if (*p != '(')
18932 if (!eap->skip)
18934 EMSG2(_("E124: Missing '(': %s"), eap->arg);
18935 goto ret_free;
18937 /* attempt to continue by skipping some text */
18938 if (vim_strchr(p, '(') != NULL)
18939 p = vim_strchr(p, '(');
18941 p = skipwhite(p + 1);
18943 ga_init2(&newargs, (int)sizeof(char_u *), 3);
18944 ga_init2(&newlines, (int)sizeof(char_u *), 3);
18946 if (!eap->skip)
18948 /* Check the name of the function. Unless it's a dictionary function
18949 * (that we are overwriting). */
18950 if (name != NULL)
18951 arg = name;
18952 else
18953 arg = fudi.fd_newkey;
18954 if (arg != NULL && (fudi.fd_di == NULL
18955 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
18957 if (*arg == K_SPECIAL)
18958 j = 3;
18959 else
18960 j = 0;
18961 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
18962 : eval_isnamec(arg[j])))
18963 ++j;
18964 if (arg[j] != NUL)
18965 emsg_funcname(_(e_invarg2), arg);
18970 * Isolate the arguments: "arg1, arg2, ...)"
18972 while (*p != ')')
18974 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
18976 varargs = TRUE;
18977 p += 3;
18978 mustend = TRUE;
18980 else
18982 arg = p;
18983 while (ASCII_ISALNUM(*p) || *p == '_')
18984 ++p;
18985 if (arg == p || isdigit(*arg)
18986 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
18987 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
18989 if (!eap->skip)
18990 EMSG2(_("E125: Illegal argument: %s"), arg);
18991 break;
18993 if (ga_grow(&newargs, 1) == FAIL)
18994 goto erret;
18995 c = *p;
18996 *p = NUL;
18997 arg = vim_strsave(arg);
18998 if (arg == NULL)
18999 goto erret;
19000 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
19001 *p = c;
19002 newargs.ga_len++;
19003 if (*p == ',')
19004 ++p;
19005 else
19006 mustend = TRUE;
19008 p = skipwhite(p);
19009 if (mustend && *p != ')')
19011 if (!eap->skip)
19012 EMSG2(_(e_invarg2), eap->arg);
19013 break;
19016 ++p; /* skip the ')' */
19018 /* find extra arguments "range", "dict" and "abort" */
19019 for (;;)
19021 p = skipwhite(p);
19022 if (STRNCMP(p, "range", 5) == 0)
19024 flags |= FC_RANGE;
19025 p += 5;
19027 else if (STRNCMP(p, "dict", 4) == 0)
19029 flags |= FC_DICT;
19030 p += 4;
19032 else if (STRNCMP(p, "abort", 5) == 0)
19034 flags |= FC_ABORT;
19035 p += 5;
19037 else
19038 break;
19041 /* When there is a line break use what follows for the function body.
19042 * Makes 'exe "func Test()\n...\nendfunc"' work. */
19043 if (*p == '\n')
19044 line_arg = p + 1;
19045 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
19046 EMSG(_(e_trailing));
19049 * Read the body of the function, until ":endfunction" is found.
19051 if (KeyTyped)
19053 /* Check if the function already exists, don't let the user type the
19054 * whole function before telling him it doesn't work! For a script we
19055 * need to skip the body to be able to find what follows. */
19056 if (!eap->skip && !eap->forceit)
19058 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
19059 EMSG(_(e_funcdict));
19060 else if (name != NULL && find_func(name) != NULL)
19061 emsg_funcname(e_funcexts, name);
19064 if (!eap->skip && did_emsg)
19065 goto erret;
19067 msg_putchar('\n'); /* don't overwrite the function name */
19068 cmdline_row = msg_row;
19071 indent = 2;
19072 nesting = 0;
19073 for (;;)
19075 msg_scroll = TRUE;
19076 need_wait_return = FALSE;
19077 sourcing_lnum_off = sourcing_lnum;
19079 if (line_arg != NULL)
19081 /* Use eap->arg, split up in parts by line breaks. */
19082 theline = line_arg;
19083 p = vim_strchr(theline, '\n');
19084 if (p == NULL)
19085 line_arg += STRLEN(line_arg);
19086 else
19088 *p = NUL;
19089 line_arg = p + 1;
19092 else if (eap->getline == NULL)
19093 theline = getcmdline(':', 0L, indent);
19094 else
19095 theline = eap->getline(':', eap->cookie, indent);
19096 if (KeyTyped)
19097 lines_left = Rows - 1;
19098 if (theline == NULL)
19100 EMSG(_("E126: Missing :endfunction"));
19101 goto erret;
19104 /* Detect line continuation: sourcing_lnum increased more than one. */
19105 if (sourcing_lnum > sourcing_lnum_off + 1)
19106 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
19107 else
19108 sourcing_lnum_off = 0;
19110 if (skip_until != NULL)
19112 /* between ":append" and "." and between ":python <<EOF" and "EOF"
19113 * don't check for ":endfunc". */
19114 if (STRCMP(theline, skip_until) == 0)
19116 vim_free(skip_until);
19117 skip_until = NULL;
19120 else
19122 /* skip ':' and blanks*/
19123 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
19126 /* Check for "endfunction". */
19127 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
19129 if (line_arg == NULL)
19130 vim_free(theline);
19131 break;
19134 /* Increase indent inside "if", "while", "for" and "try", decrease
19135 * at "end". */
19136 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
19137 indent -= 2;
19138 else if (STRNCMP(p, "if", 2) == 0
19139 || STRNCMP(p, "wh", 2) == 0
19140 || STRNCMP(p, "for", 3) == 0
19141 || STRNCMP(p, "try", 3) == 0)
19142 indent += 2;
19144 /* Check for defining a function inside this function. */
19145 if (checkforcmd(&p, "function", 2))
19147 if (*p == '!')
19148 p = skipwhite(p + 1);
19149 p += eval_fname_script(p);
19150 if (ASCII_ISALPHA(*p))
19152 vim_free(trans_function_name(&p, TRUE, 0, NULL));
19153 if (*skipwhite(p) == '(')
19155 ++nesting;
19156 indent += 2;
19161 /* Check for ":append" or ":insert". */
19162 p = skip_range(p, NULL);
19163 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
19164 || (p[0] == 'i'
19165 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
19166 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
19167 skip_until = vim_strsave((char_u *)".");
19169 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
19170 arg = skipwhite(skiptowhite(p));
19171 if (arg[0] == '<' && arg[1] =='<'
19172 && ((p[0] == 'p' && p[1] == 'y'
19173 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
19174 || (p[0] == 'p' && p[1] == 'e'
19175 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
19176 || (p[0] == 't' && p[1] == 'c'
19177 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
19178 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
19179 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
19180 || (p[0] == 'm' && p[1] == 'z'
19181 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
19184 /* ":python <<" continues until a dot, like ":append" */
19185 p = skipwhite(arg + 2);
19186 if (*p == NUL)
19187 skip_until = vim_strsave((char_u *)".");
19188 else
19189 skip_until = vim_strsave(p);
19193 /* Add the line to the function. */
19194 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
19196 if (line_arg == NULL)
19197 vim_free(theline);
19198 goto erret;
19201 /* Copy the line to newly allocated memory. get_one_sourceline()
19202 * allocates 250 bytes per line, this saves 80% on average. The cost
19203 * is an extra alloc/free. */
19204 p = vim_strsave(theline);
19205 if (p != NULL)
19207 if (line_arg == NULL)
19208 vim_free(theline);
19209 theline = p;
19212 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
19214 /* Add NULL lines for continuation lines, so that the line count is
19215 * equal to the index in the growarray. */
19216 while (sourcing_lnum_off-- > 0)
19217 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
19219 /* Check for end of eap->arg. */
19220 if (line_arg != NULL && *line_arg == NUL)
19221 line_arg = NULL;
19224 /* Don't define the function when skipping commands or when an error was
19225 * detected. */
19226 if (eap->skip || did_emsg)
19227 goto erret;
19230 * If there are no errors, add the function
19232 if (fudi.fd_dict == NULL)
19234 v = find_var(name, &ht);
19235 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
19237 emsg_funcname("E707: Function name conflicts with variable: %s",
19238 name);
19239 goto erret;
19242 fp = find_func(name);
19243 if (fp != NULL)
19245 if (!eap->forceit)
19247 emsg_funcname(e_funcexts, name);
19248 goto erret;
19250 if (fp->uf_calls > 0)
19252 emsg_funcname("E127: Cannot redefine function %s: It is in use",
19253 name);
19254 goto erret;
19256 /* redefine existing function */
19257 ga_clear_strings(&(fp->uf_args));
19258 ga_clear_strings(&(fp->uf_lines));
19259 vim_free(name);
19260 name = NULL;
19263 else
19265 char numbuf[20];
19267 fp = NULL;
19268 if (fudi.fd_newkey == NULL && !eap->forceit)
19270 EMSG(_(e_funcdict));
19271 goto erret;
19273 if (fudi.fd_di == NULL)
19275 /* Can't add a function to a locked dictionary */
19276 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
19277 goto erret;
19279 /* Can't change an existing function if it is locked */
19280 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
19281 goto erret;
19283 /* Give the function a sequential number. Can only be used with a
19284 * Funcref! */
19285 vim_free(name);
19286 sprintf(numbuf, "%d", ++func_nr);
19287 name = vim_strsave((char_u *)numbuf);
19288 if (name == NULL)
19289 goto erret;
19292 if (fp == NULL)
19294 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
19296 int slen, plen;
19297 char_u *scriptname;
19299 /* Check that the autoload name matches the script name. */
19300 j = FAIL;
19301 if (sourcing_name != NULL)
19303 scriptname = autoload_name(name);
19304 if (scriptname != NULL)
19306 p = vim_strchr(scriptname, '/');
19307 plen = (int)STRLEN(p);
19308 slen = (int)STRLEN(sourcing_name);
19309 if (slen > plen && fnamecmp(p,
19310 sourcing_name + slen - plen) == 0)
19311 j = OK;
19312 vim_free(scriptname);
19315 if (j == FAIL)
19317 EMSG2(_("E746: Function name does not match script file name: %s"), name);
19318 goto erret;
19322 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
19323 if (fp == NULL)
19324 goto erret;
19326 if (fudi.fd_dict != NULL)
19328 if (fudi.fd_di == NULL)
19330 /* add new dict entry */
19331 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
19332 if (fudi.fd_di == NULL)
19334 vim_free(fp);
19335 goto erret;
19337 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
19339 vim_free(fudi.fd_di);
19340 vim_free(fp);
19341 goto erret;
19344 else
19345 /* overwrite existing dict entry */
19346 clear_tv(&fudi.fd_di->di_tv);
19347 fudi.fd_di->di_tv.v_type = VAR_FUNC;
19348 fudi.fd_di->di_tv.v_lock = 0;
19349 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
19350 fp->uf_refcount = 1;
19352 /* behave like "dict" was used */
19353 flags |= FC_DICT;
19356 /* insert the new function in the function list */
19357 STRCPY(fp->uf_name, name);
19358 hash_add(&func_hashtab, UF2HIKEY(fp));
19360 fp->uf_args = newargs;
19361 fp->uf_lines = newlines;
19362 #ifdef FEAT_PROFILE
19363 fp->uf_tml_count = NULL;
19364 fp->uf_tml_total = NULL;
19365 fp->uf_tml_self = NULL;
19366 fp->uf_profiling = FALSE;
19367 if (prof_def_func())
19368 func_do_profile(fp);
19369 #endif
19370 fp->uf_varargs = varargs;
19371 fp->uf_flags = flags;
19372 fp->uf_calls = 0;
19373 fp->uf_script_ID = current_SID;
19374 goto ret_free;
19376 erret:
19377 ga_clear_strings(&newargs);
19378 ga_clear_strings(&newlines);
19379 ret_free:
19380 vim_free(skip_until);
19381 vim_free(fudi.fd_newkey);
19382 vim_free(name);
19383 did_emsg |= saved_did_emsg;
19387 * Get a function name, translating "<SID>" and "<SNR>".
19388 * Also handles a Funcref in a List or Dictionary.
19389 * Returns the function name in allocated memory, or NULL for failure.
19390 * flags:
19391 * TFN_INT: internal function name OK
19392 * TFN_QUIET: be quiet
19393 * Advances "pp" to just after the function name (if no error).
19395 static char_u *
19396 trans_function_name(pp, skip, flags, fdp)
19397 char_u **pp;
19398 int skip; /* only find the end, don't evaluate */
19399 int flags;
19400 funcdict_T *fdp; /* return: info about dictionary used */
19402 char_u *name = NULL;
19403 char_u *start;
19404 char_u *end;
19405 int lead;
19406 char_u sid_buf[20];
19407 int len;
19408 lval_T lv;
19410 if (fdp != NULL)
19411 vim_memset(fdp, 0, sizeof(funcdict_T));
19412 start = *pp;
19414 /* Check for hard coded <SNR>: already translated function ID (from a user
19415 * command). */
19416 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
19417 && (*pp)[2] == (int)KE_SNR)
19419 *pp += 3;
19420 len = get_id_len(pp) + 3;
19421 return vim_strnsave(start, len);
19424 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
19425 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
19426 lead = eval_fname_script(start);
19427 if (lead > 2)
19428 start += lead;
19430 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
19431 lead > 2 ? 0 : FNE_CHECK_START);
19432 if (end == start)
19434 if (!skip)
19435 EMSG(_("E129: Function name required"));
19436 goto theend;
19438 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
19441 * Report an invalid expression in braces, unless the expression
19442 * evaluation has been cancelled due to an aborting error, an
19443 * interrupt, or an exception.
19445 if (!aborting())
19447 if (end != NULL)
19448 EMSG2(_(e_invarg2), start);
19450 else
19451 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
19452 goto theend;
19455 if (lv.ll_tv != NULL)
19457 if (fdp != NULL)
19459 fdp->fd_dict = lv.ll_dict;
19460 fdp->fd_newkey = lv.ll_newkey;
19461 lv.ll_newkey = NULL;
19462 fdp->fd_di = lv.ll_di;
19464 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
19466 name = vim_strsave(lv.ll_tv->vval.v_string);
19467 *pp = end;
19469 else
19471 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
19472 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
19473 EMSG(_(e_funcref));
19474 else
19475 *pp = end;
19476 name = NULL;
19478 goto theend;
19481 if (lv.ll_name == NULL)
19483 /* Error found, but continue after the function name. */
19484 *pp = end;
19485 goto theend;
19488 /* Check if the name is a Funcref. If so, use the value. */
19489 if (lv.ll_exp_name != NULL)
19491 len = (int)STRLEN(lv.ll_exp_name);
19492 name = deref_func_name(lv.ll_exp_name, &len);
19493 if (name == lv.ll_exp_name)
19494 name = NULL;
19496 else
19498 len = (int)(end - *pp);
19499 name = deref_func_name(*pp, &len);
19500 if (name == *pp)
19501 name = NULL;
19503 if (name != NULL)
19505 name = vim_strsave(name);
19506 *pp = end;
19507 goto theend;
19510 if (lv.ll_exp_name != NULL)
19512 len = (int)STRLEN(lv.ll_exp_name);
19513 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
19514 && STRNCMP(lv.ll_name, "s:", 2) == 0)
19516 /* When there was "s:" already or the name expanded to get a
19517 * leading "s:" then remove it. */
19518 lv.ll_name += 2;
19519 len -= 2;
19520 lead = 2;
19523 else
19525 if (lead == 2) /* skip over "s:" */
19526 lv.ll_name += 2;
19527 len = (int)(end - lv.ll_name);
19531 * Copy the function name to allocated memory.
19532 * Accept <SID>name() inside a script, translate into <SNR>123_name().
19533 * Accept <SNR>123_name() outside a script.
19535 if (skip)
19536 lead = 0; /* do nothing */
19537 else if (lead > 0)
19539 lead = 3;
19540 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
19541 || eval_fname_sid(*pp))
19543 /* It's "s:" or "<SID>" */
19544 if (current_SID <= 0)
19546 EMSG(_(e_usingsid));
19547 goto theend;
19549 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
19550 lead += (int)STRLEN(sid_buf);
19553 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
19555 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
19556 goto theend;
19558 name = alloc((unsigned)(len + lead + 1));
19559 if (name != NULL)
19561 if (lead > 0)
19563 name[0] = K_SPECIAL;
19564 name[1] = KS_EXTRA;
19565 name[2] = (int)KE_SNR;
19566 if (lead > 3) /* If it's "<SID>" */
19567 STRCPY(name + 3, sid_buf);
19569 mch_memmove(name + lead, lv.ll_name, (size_t)len);
19570 name[len + lead] = NUL;
19572 *pp = end;
19574 theend:
19575 clear_lval(&lv);
19576 return name;
19580 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
19581 * Return 2 if "p" starts with "s:".
19582 * Return 0 otherwise.
19584 static int
19585 eval_fname_script(p)
19586 char_u *p;
19588 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
19589 || STRNICMP(p + 1, "SNR>", 4) == 0))
19590 return 5;
19591 if (p[0] == 's' && p[1] == ':')
19592 return 2;
19593 return 0;
19597 * Return TRUE if "p" starts with "<SID>" or "s:".
19598 * Only works if eval_fname_script() returned non-zero for "p"!
19600 static int
19601 eval_fname_sid(p)
19602 char_u *p;
19604 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
19608 * List the head of the function: "name(arg1, arg2)".
19610 static void
19611 list_func_head(fp, indent)
19612 ufunc_T *fp;
19613 int indent;
19615 int j;
19617 msg_start();
19618 if (indent)
19619 MSG_PUTS(" ");
19620 MSG_PUTS("function ");
19621 if (fp->uf_name[0] == K_SPECIAL)
19623 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
19624 msg_puts(fp->uf_name + 3);
19626 else
19627 msg_puts(fp->uf_name);
19628 msg_putchar('(');
19629 for (j = 0; j < fp->uf_args.ga_len; ++j)
19631 if (j)
19632 MSG_PUTS(", ");
19633 msg_puts(FUNCARG(fp, j));
19635 if (fp->uf_varargs)
19637 if (j)
19638 MSG_PUTS(", ");
19639 MSG_PUTS("...");
19641 msg_putchar(')');
19642 msg_clr_eos();
19643 if (p_verbose > 0)
19644 last_set_msg(fp->uf_script_ID);
19648 * Find a function by name, return pointer to it in ufuncs.
19649 * Return NULL for unknown function.
19651 static ufunc_T *
19652 find_func(name)
19653 char_u *name;
19655 hashitem_T *hi;
19657 hi = hash_find(&func_hashtab, name);
19658 if (!HASHITEM_EMPTY(hi))
19659 return HI2UF(hi);
19660 return NULL;
19663 #if defined(EXITFREE) || defined(PROTO)
19664 void
19665 free_all_functions()
19667 hashitem_T *hi;
19669 /* Need to start all over every time, because func_free() may change the
19670 * hash table. */
19671 while (func_hashtab.ht_used > 0)
19672 for (hi = func_hashtab.ht_array; ; ++hi)
19673 if (!HASHITEM_EMPTY(hi))
19675 func_free(HI2UF(hi));
19676 break;
19679 #endif
19682 * Return TRUE if a function "name" exists.
19684 static int
19685 function_exists(name)
19686 char_u *name;
19688 char_u *nm = name;
19689 char_u *p;
19690 int n = FALSE;
19692 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
19693 nm = skipwhite(nm);
19695 /* Only accept "funcname", "funcname ", "funcname (..." and
19696 * "funcname(...", not "funcname!...". */
19697 if (p != NULL && (*nm == NUL || *nm == '('))
19699 if (builtin_function(p))
19700 n = (find_internal_func(p) >= 0);
19701 else
19702 n = (find_func(p) != NULL);
19704 vim_free(p);
19705 return n;
19709 * Return TRUE if "name" looks like a builtin function name: starts with a
19710 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
19712 static int
19713 builtin_function(name)
19714 char_u *name;
19716 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
19717 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
19720 #if defined(FEAT_PROFILE) || defined(PROTO)
19722 * Start profiling function "fp".
19724 static void
19725 func_do_profile(fp)
19726 ufunc_T *fp;
19728 fp->uf_tm_count = 0;
19729 profile_zero(&fp->uf_tm_self);
19730 profile_zero(&fp->uf_tm_total);
19731 if (fp->uf_tml_count == NULL)
19732 fp->uf_tml_count = (int *)alloc_clear((unsigned)
19733 (sizeof(int) * fp->uf_lines.ga_len));
19734 if (fp->uf_tml_total == NULL)
19735 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
19736 (sizeof(proftime_T) * fp->uf_lines.ga_len));
19737 if (fp->uf_tml_self == NULL)
19738 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
19739 (sizeof(proftime_T) * fp->uf_lines.ga_len));
19740 fp->uf_tml_idx = -1;
19741 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
19742 || fp->uf_tml_self == NULL)
19743 return; /* out of memory */
19745 fp->uf_profiling = TRUE;
19749 * Dump the profiling results for all functions in file "fd".
19751 void
19752 func_dump_profile(fd)
19753 FILE *fd;
19755 hashitem_T *hi;
19756 int todo;
19757 ufunc_T *fp;
19758 int i;
19759 ufunc_T **sorttab;
19760 int st_len = 0;
19762 todo = (int)func_hashtab.ht_used;
19763 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
19765 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
19767 if (!HASHITEM_EMPTY(hi))
19769 --todo;
19770 fp = HI2UF(hi);
19771 if (fp->uf_profiling)
19773 if (sorttab != NULL)
19774 sorttab[st_len++] = fp;
19776 if (fp->uf_name[0] == K_SPECIAL)
19777 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
19778 else
19779 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
19780 if (fp->uf_tm_count == 1)
19781 fprintf(fd, "Called 1 time\n");
19782 else
19783 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
19784 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
19785 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
19786 fprintf(fd, "\n");
19787 fprintf(fd, "count total (s) self (s)\n");
19789 for (i = 0; i < fp->uf_lines.ga_len; ++i)
19791 if (FUNCLINE(fp, i) == NULL)
19792 continue;
19793 prof_func_line(fd, fp->uf_tml_count[i],
19794 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
19795 fprintf(fd, "%s\n", FUNCLINE(fp, i));
19797 fprintf(fd, "\n");
19802 if (sorttab != NULL && st_len > 0)
19804 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
19805 prof_total_cmp);
19806 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
19807 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
19808 prof_self_cmp);
19809 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
19813 static void
19814 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
19815 FILE *fd;
19816 ufunc_T **sorttab;
19817 int st_len;
19818 char *title;
19819 int prefer_self; /* when equal print only self time */
19821 int i;
19822 ufunc_T *fp;
19824 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
19825 fprintf(fd, "count total (s) self (s) function\n");
19826 for (i = 0; i < 20 && i < st_len; ++i)
19828 fp = sorttab[i];
19829 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
19830 prefer_self);
19831 if (fp->uf_name[0] == K_SPECIAL)
19832 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
19833 else
19834 fprintf(fd, " %s()\n", fp->uf_name);
19836 fprintf(fd, "\n");
19840 * Print the count and times for one function or function line.
19842 static void
19843 prof_func_line(fd, count, total, self, prefer_self)
19844 FILE *fd;
19845 int count;
19846 proftime_T *total;
19847 proftime_T *self;
19848 int prefer_self; /* when equal print only self time */
19850 if (count > 0)
19852 fprintf(fd, "%5d ", count);
19853 if (prefer_self && profile_equal(total, self))
19854 fprintf(fd, " ");
19855 else
19856 fprintf(fd, "%s ", profile_msg(total));
19857 if (!prefer_self && profile_equal(total, self))
19858 fprintf(fd, " ");
19859 else
19860 fprintf(fd, "%s ", profile_msg(self));
19862 else
19863 fprintf(fd, " ");
19867 * Compare function for total time sorting.
19869 static int
19870 #ifdef __BORLANDC__
19871 _RTLENTRYF
19872 #endif
19873 prof_total_cmp(s1, s2)
19874 const void *s1;
19875 const void *s2;
19877 ufunc_T *p1, *p2;
19879 p1 = *(ufunc_T **)s1;
19880 p2 = *(ufunc_T **)s2;
19881 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
19885 * Compare function for self time sorting.
19887 static int
19888 #ifdef __BORLANDC__
19889 _RTLENTRYF
19890 #endif
19891 prof_self_cmp(s1, s2)
19892 const void *s1;
19893 const void *s2;
19895 ufunc_T *p1, *p2;
19897 p1 = *(ufunc_T **)s1;
19898 p2 = *(ufunc_T **)s2;
19899 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
19902 #endif
19905 * If "name" has a package name try autoloading the script for it.
19906 * Return TRUE if a package was loaded.
19908 static int
19909 script_autoload(name, reload)
19910 char_u *name;
19911 int reload; /* load script again when already loaded */
19913 char_u *p;
19914 char_u *scriptname, *tofree;
19915 int ret = FALSE;
19916 int i;
19918 /* If there is no '#' after name[0] there is no package name. */
19919 p = vim_strchr(name, AUTOLOAD_CHAR);
19920 if (p == NULL || p == name)
19921 return FALSE;
19923 tofree = scriptname = autoload_name(name);
19925 /* Find the name in the list of previously loaded package names. Skip
19926 * "autoload/", it's always the same. */
19927 for (i = 0; i < ga_loaded.ga_len; ++i)
19928 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
19929 break;
19930 if (!reload && i < ga_loaded.ga_len)
19931 ret = FALSE; /* was loaded already */
19932 else
19934 /* Remember the name if it wasn't loaded already. */
19935 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
19937 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
19938 tofree = NULL;
19941 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
19942 if (source_runtime(scriptname, FALSE) == OK)
19943 ret = TRUE;
19946 vim_free(tofree);
19947 return ret;
19951 * Return the autoload script name for a function or variable name.
19952 * Returns NULL when out of memory.
19954 static char_u *
19955 autoload_name(name)
19956 char_u *name;
19958 char_u *p;
19959 char_u *scriptname;
19961 /* Get the script file name: replace '#' with '/', append ".vim". */
19962 scriptname = alloc((unsigned)(STRLEN(name) + 14));
19963 if (scriptname == NULL)
19964 return FALSE;
19965 STRCPY(scriptname, "autoload/");
19966 STRCAT(scriptname, name);
19967 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
19968 STRCAT(scriptname, ".vim");
19969 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
19970 *p = '/';
19971 return scriptname;
19974 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
19977 * Function given to ExpandGeneric() to obtain the list of user defined
19978 * function names.
19980 char_u *
19981 get_user_func_name(xp, idx)
19982 expand_T *xp;
19983 int idx;
19985 static long_u done;
19986 static hashitem_T *hi;
19987 ufunc_T *fp;
19989 if (idx == 0)
19991 done = 0;
19992 hi = func_hashtab.ht_array;
19994 if (done < func_hashtab.ht_used)
19996 if (done++ > 0)
19997 ++hi;
19998 while (HASHITEM_EMPTY(hi))
19999 ++hi;
20000 fp = HI2UF(hi);
20002 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
20003 return fp->uf_name; /* prevents overflow */
20005 cat_func_name(IObuff, fp);
20006 if (xp->xp_context != EXPAND_USER_FUNC)
20008 STRCAT(IObuff, "(");
20009 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
20010 STRCAT(IObuff, ")");
20012 return IObuff;
20014 return NULL;
20017 #endif /* FEAT_CMDL_COMPL */
20020 * Copy the function name of "fp" to buffer "buf".
20021 * "buf" must be able to hold the function name plus three bytes.
20022 * Takes care of script-local function names.
20024 static void
20025 cat_func_name(buf, fp)
20026 char_u *buf;
20027 ufunc_T *fp;
20029 if (fp->uf_name[0] == K_SPECIAL)
20031 STRCPY(buf, "<SNR>");
20032 STRCAT(buf, fp->uf_name + 3);
20034 else
20035 STRCPY(buf, fp->uf_name);
20039 * ":delfunction {name}"
20041 void
20042 ex_delfunction(eap)
20043 exarg_T *eap;
20045 ufunc_T *fp = NULL;
20046 char_u *p;
20047 char_u *name;
20048 funcdict_T fudi;
20050 p = eap->arg;
20051 name = trans_function_name(&p, eap->skip, 0, &fudi);
20052 vim_free(fudi.fd_newkey);
20053 if (name == NULL)
20055 if (fudi.fd_dict != NULL && !eap->skip)
20056 EMSG(_(e_funcref));
20057 return;
20059 if (!ends_excmd(*skipwhite(p)))
20061 vim_free(name);
20062 EMSG(_(e_trailing));
20063 return;
20065 eap->nextcmd = check_nextcmd(p);
20066 if (eap->nextcmd != NULL)
20067 *p = NUL;
20069 if (!eap->skip)
20070 fp = find_func(name);
20071 vim_free(name);
20073 if (!eap->skip)
20075 if (fp == NULL)
20077 EMSG2(_(e_nofunc), eap->arg);
20078 return;
20080 if (fp->uf_calls > 0)
20082 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
20083 return;
20086 if (fudi.fd_dict != NULL)
20088 /* Delete the dict item that refers to the function, it will
20089 * invoke func_unref() and possibly delete the function. */
20090 dictitem_remove(fudi.fd_dict, fudi.fd_di);
20092 else
20093 func_free(fp);
20098 * Free a function and remove it from the list of functions.
20100 static void
20101 func_free(fp)
20102 ufunc_T *fp;
20104 hashitem_T *hi;
20106 /* clear this function */
20107 ga_clear_strings(&(fp->uf_args));
20108 ga_clear_strings(&(fp->uf_lines));
20109 #ifdef FEAT_PROFILE
20110 vim_free(fp->uf_tml_count);
20111 vim_free(fp->uf_tml_total);
20112 vim_free(fp->uf_tml_self);
20113 #endif
20115 /* remove the function from the function hashtable */
20116 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
20117 if (HASHITEM_EMPTY(hi))
20118 EMSG2(_(e_intern2), "func_free()");
20119 else
20120 hash_remove(&func_hashtab, hi);
20122 vim_free(fp);
20126 * Unreference a Function: decrement the reference count and free it when it
20127 * becomes zero. Only for numbered functions.
20129 static void
20130 func_unref(name)
20131 char_u *name;
20133 ufunc_T *fp;
20135 if (name != NULL && isdigit(*name))
20137 fp = find_func(name);
20138 if (fp == NULL)
20139 EMSG2(_(e_intern2), "func_unref()");
20140 else if (--fp->uf_refcount <= 0)
20142 /* Only delete it when it's not being used. Otherwise it's done
20143 * when "uf_calls" becomes zero. */
20144 if (fp->uf_calls == 0)
20145 func_free(fp);
20151 * Count a reference to a Function.
20153 static void
20154 func_ref(name)
20155 char_u *name;
20157 ufunc_T *fp;
20159 if (name != NULL && isdigit(*name))
20161 fp = find_func(name);
20162 if (fp == NULL)
20163 EMSG2(_(e_intern2), "func_ref()");
20164 else
20165 ++fp->uf_refcount;
20170 * Call a user function.
20172 static void
20173 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
20174 ufunc_T *fp; /* pointer to function */
20175 int argcount; /* nr of args */
20176 typval_T *argvars; /* arguments */
20177 typval_T *rettv; /* return value */
20178 linenr_T firstline; /* first line of range */
20179 linenr_T lastline; /* last line of range */
20180 dict_T *selfdict; /* Dictionary for "self" */
20182 char_u *save_sourcing_name;
20183 linenr_T save_sourcing_lnum;
20184 scid_T save_current_SID;
20185 funccall_T fc;
20186 int save_did_emsg;
20187 static int depth = 0;
20188 dictitem_T *v;
20189 int fixvar_idx = 0; /* index in fixvar[] */
20190 int i;
20191 int ai;
20192 char_u numbuf[NUMBUFLEN];
20193 char_u *name;
20194 #ifdef FEAT_PROFILE
20195 proftime_T wait_start;
20196 proftime_T call_start;
20197 #endif
20199 /* If depth of calling is getting too high, don't execute the function */
20200 if (depth >= p_mfd)
20202 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
20203 rettv->v_type = VAR_NUMBER;
20204 rettv->vval.v_number = -1;
20205 return;
20207 ++depth;
20209 line_breakcheck(); /* check for CTRL-C hit */
20211 fc.caller = current_funccal;
20212 current_funccal = &fc;
20213 fc.func = fp;
20214 fc.rettv = rettv;
20215 rettv->vval.v_number = 0;
20216 fc.linenr = 0;
20217 fc.returned = FALSE;
20218 fc.level = ex_nesting_level;
20219 /* Check if this function has a breakpoint. */
20220 fc.breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
20221 fc.dbg_tick = debug_tick;
20224 * Note about using fc.fixvar[]: This is an array of FIXVAR_CNT variables
20225 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
20226 * each argument variable and saves a lot of time.
20229 * Init l: variables.
20231 init_var_dict(&fc.l_vars, &fc.l_vars_var);
20232 if (selfdict != NULL)
20234 /* Set l:self to "selfdict". Use "name" to avoid a warning from
20235 * some compiler that checks the destination size. */
20236 v = &fc.fixvar[fixvar_idx++].var;
20237 name = v->di_key;
20238 STRCPY(name, "self");
20239 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
20240 hash_add(&fc.l_vars.dv_hashtab, DI2HIKEY(v));
20241 v->di_tv.v_type = VAR_DICT;
20242 v->di_tv.v_lock = 0;
20243 v->di_tv.vval.v_dict = selfdict;
20244 ++selfdict->dv_refcount;
20248 * Init a: variables.
20249 * Set a:0 to "argcount".
20250 * Set a:000 to a list with room for the "..." arguments.
20252 init_var_dict(&fc.l_avars, &fc.l_avars_var);
20253 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "0",
20254 (varnumber_T)(argcount - fp->uf_args.ga_len));
20255 v = &fc.fixvar[fixvar_idx++].var;
20256 STRCPY(v->di_key, "000");
20257 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20258 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
20259 v->di_tv.v_type = VAR_LIST;
20260 v->di_tv.v_lock = VAR_FIXED;
20261 v->di_tv.vval.v_list = &fc.l_varlist;
20262 vim_memset(&fc.l_varlist, 0, sizeof(list_T));
20263 fc.l_varlist.lv_refcount = 99999;
20264 fc.l_varlist.lv_lock = VAR_FIXED;
20267 * Set a:firstline to "firstline" and a:lastline to "lastline".
20268 * Set a:name to named arguments.
20269 * Set a:N to the "..." arguments.
20271 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "firstline",
20272 (varnumber_T)firstline);
20273 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "lastline",
20274 (varnumber_T)lastline);
20275 for (i = 0; i < argcount; ++i)
20277 ai = i - fp->uf_args.ga_len;
20278 if (ai < 0)
20279 /* named argument a:name */
20280 name = FUNCARG(fp, i);
20281 else
20283 /* "..." argument a:1, a:2, etc. */
20284 sprintf((char *)numbuf, "%d", ai + 1);
20285 name = numbuf;
20287 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
20289 v = &fc.fixvar[fixvar_idx++].var;
20290 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20292 else
20294 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
20295 + STRLEN(name)));
20296 if (v == NULL)
20297 break;
20298 v->di_flags = DI_FLAGS_RO;
20300 STRCPY(v->di_key, name);
20301 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
20303 /* Note: the values are copied directly to avoid alloc/free.
20304 * "argvars" must have VAR_FIXED for v_lock. */
20305 v->di_tv = argvars[i];
20306 v->di_tv.v_lock = VAR_FIXED;
20308 if (ai >= 0 && ai < MAX_FUNC_ARGS)
20310 list_append(&fc.l_varlist, &fc.l_listitems[ai]);
20311 fc.l_listitems[ai].li_tv = argvars[i];
20312 fc.l_listitems[ai].li_tv.v_lock = VAR_FIXED;
20316 /* Don't redraw while executing the function. */
20317 ++RedrawingDisabled;
20318 save_sourcing_name = sourcing_name;
20319 save_sourcing_lnum = sourcing_lnum;
20320 sourcing_lnum = 1;
20321 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
20322 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
20323 if (sourcing_name != NULL)
20325 if (save_sourcing_name != NULL
20326 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
20327 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
20328 else
20329 STRCPY(sourcing_name, "function ");
20330 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
20332 if (p_verbose >= 12)
20334 ++no_wait_return;
20335 verbose_enter_scroll();
20337 smsg((char_u *)_("calling %s"), sourcing_name);
20338 if (p_verbose >= 14)
20340 char_u buf[MSG_BUF_LEN];
20341 char_u numbuf2[NUMBUFLEN];
20342 char_u *tofree;
20343 char_u *s;
20345 msg_puts((char_u *)"(");
20346 for (i = 0; i < argcount; ++i)
20348 if (i > 0)
20349 msg_puts((char_u *)", ");
20350 if (argvars[i].v_type == VAR_NUMBER)
20351 msg_outnum((long)argvars[i].vval.v_number);
20352 else
20354 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
20355 if (s != NULL)
20357 trunc_string(s, buf, MSG_BUF_CLEN);
20358 msg_puts(buf);
20359 vim_free(tofree);
20363 msg_puts((char_u *)")");
20365 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20367 verbose_leave_scroll();
20368 --no_wait_return;
20371 #ifdef FEAT_PROFILE
20372 if (do_profiling == PROF_YES)
20374 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
20375 func_do_profile(fp);
20376 if (fp->uf_profiling
20377 || (fc.caller != NULL && &fc.caller->func->uf_profiling))
20379 ++fp->uf_tm_count;
20380 profile_start(&call_start);
20381 profile_zero(&fp->uf_tm_children);
20383 script_prof_save(&wait_start);
20385 #endif
20387 save_current_SID = current_SID;
20388 current_SID = fp->uf_script_ID;
20389 save_did_emsg = did_emsg;
20390 did_emsg = FALSE;
20392 /* call do_cmdline() to execute the lines */
20393 do_cmdline(NULL, get_func_line, (void *)&fc,
20394 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
20396 --RedrawingDisabled;
20398 /* when the function was aborted because of an error, return -1 */
20399 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
20401 clear_tv(rettv);
20402 rettv->v_type = VAR_NUMBER;
20403 rettv->vval.v_number = -1;
20406 #ifdef FEAT_PROFILE
20407 if (do_profiling == PROF_YES && (fp->uf_profiling
20408 || (fc.caller != NULL && &fc.caller->func->uf_profiling)))
20410 profile_end(&call_start);
20411 profile_sub_wait(&wait_start, &call_start);
20412 profile_add(&fp->uf_tm_total, &call_start);
20413 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
20414 if (fc.caller != NULL && &fc.caller->func->uf_profiling)
20416 profile_add(&fc.caller->func->uf_tm_children, &call_start);
20417 profile_add(&fc.caller->func->uf_tml_children, &call_start);
20420 #endif
20422 /* when being verbose, mention the return value */
20423 if (p_verbose >= 12)
20425 ++no_wait_return;
20426 verbose_enter_scroll();
20428 if (aborting())
20429 smsg((char_u *)_("%s aborted"), sourcing_name);
20430 else if (fc.rettv->v_type == VAR_NUMBER)
20431 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
20432 (long)fc.rettv->vval.v_number);
20433 else
20435 char_u buf[MSG_BUF_LEN];
20436 char_u numbuf2[NUMBUFLEN];
20437 char_u *tofree;
20438 char_u *s;
20440 /* The value may be very long. Skip the middle part, so that we
20441 * have some idea how it starts and ends. smsg() would always
20442 * truncate it at the end. */
20443 s = tv2string(fc.rettv, &tofree, numbuf2, 0);
20444 if (s != NULL)
20446 trunc_string(s, buf, MSG_BUF_CLEN);
20447 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
20448 vim_free(tofree);
20451 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20453 verbose_leave_scroll();
20454 --no_wait_return;
20457 vim_free(sourcing_name);
20458 sourcing_name = save_sourcing_name;
20459 sourcing_lnum = save_sourcing_lnum;
20460 current_SID = save_current_SID;
20461 #ifdef FEAT_PROFILE
20462 if (do_profiling == PROF_YES)
20463 script_prof_restore(&wait_start);
20464 #endif
20466 if (p_verbose >= 12 && sourcing_name != NULL)
20468 ++no_wait_return;
20469 verbose_enter_scroll();
20471 smsg((char_u *)_("continuing in %s"), sourcing_name);
20472 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20474 verbose_leave_scroll();
20475 --no_wait_return;
20478 did_emsg |= save_did_emsg;
20479 current_funccal = fc.caller;
20481 /* The a: variables typevals were not alloced, only free the allocated
20482 * variables. */
20483 vars_clear_ext(&fc.l_avars.dv_hashtab, FALSE);
20485 vars_clear(&fc.l_vars.dv_hashtab); /* free all l: variables */
20486 --depth;
20490 * Add a number variable "name" to dict "dp" with value "nr".
20492 static void
20493 add_nr_var(dp, v, name, nr)
20494 dict_T *dp;
20495 dictitem_T *v;
20496 char *name;
20497 varnumber_T nr;
20499 STRCPY(v->di_key, name);
20500 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20501 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
20502 v->di_tv.v_type = VAR_NUMBER;
20503 v->di_tv.v_lock = VAR_FIXED;
20504 v->di_tv.vval.v_number = nr;
20508 * ":return [expr]"
20510 void
20511 ex_return(eap)
20512 exarg_T *eap;
20514 char_u *arg = eap->arg;
20515 typval_T rettv;
20516 int returning = FALSE;
20518 if (current_funccal == NULL)
20520 EMSG(_("E133: :return not inside a function"));
20521 return;
20524 if (eap->skip)
20525 ++emsg_skip;
20527 eap->nextcmd = NULL;
20528 if ((*arg != NUL && *arg != '|' && *arg != '\n')
20529 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
20531 if (!eap->skip)
20532 returning = do_return(eap, FALSE, TRUE, &rettv);
20533 else
20534 clear_tv(&rettv);
20536 /* It's safer to return also on error. */
20537 else if (!eap->skip)
20540 * Return unless the expression evaluation has been cancelled due to an
20541 * aborting error, an interrupt, or an exception.
20543 if (!aborting())
20544 returning = do_return(eap, FALSE, TRUE, NULL);
20547 /* When skipping or the return gets pending, advance to the next command
20548 * in this line (!returning). Otherwise, ignore the rest of the line.
20549 * Following lines will be ignored by get_func_line(). */
20550 if (returning)
20551 eap->nextcmd = NULL;
20552 else if (eap->nextcmd == NULL) /* no argument */
20553 eap->nextcmd = check_nextcmd(arg);
20555 if (eap->skip)
20556 --emsg_skip;
20560 * Return from a function. Possibly makes the return pending. Also called
20561 * for a pending return at the ":endtry" or after returning from an extra
20562 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
20563 * when called due to a ":return" command. "rettv" may point to a typval_T
20564 * with the return rettv. Returns TRUE when the return can be carried out,
20565 * FALSE when the return gets pending.
20568 do_return(eap, reanimate, is_cmd, rettv)
20569 exarg_T *eap;
20570 int reanimate;
20571 int is_cmd;
20572 void *rettv;
20574 int idx;
20575 struct condstack *cstack = eap->cstack;
20577 if (reanimate)
20578 /* Undo the return. */
20579 current_funccal->returned = FALSE;
20582 * Cleanup (and inactivate) conditionals, but stop when a try conditional
20583 * not in its finally clause (which then is to be executed next) is found.
20584 * In this case, make the ":return" pending for execution at the ":endtry".
20585 * Otherwise, return normally.
20587 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
20588 if (idx >= 0)
20590 cstack->cs_pending[idx] = CSTP_RETURN;
20592 if (!is_cmd && !reanimate)
20593 /* A pending return again gets pending. "rettv" points to an
20594 * allocated variable with the rettv of the original ":return"'s
20595 * argument if present or is NULL else. */
20596 cstack->cs_rettv[idx] = rettv;
20597 else
20599 /* When undoing a return in order to make it pending, get the stored
20600 * return rettv. */
20601 if (reanimate)
20602 rettv = current_funccal->rettv;
20604 if (rettv != NULL)
20606 /* Store the value of the pending return. */
20607 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
20608 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
20609 else
20610 EMSG(_(e_outofmem));
20612 else
20613 cstack->cs_rettv[idx] = NULL;
20615 if (reanimate)
20617 /* The pending return value could be overwritten by a ":return"
20618 * without argument in a finally clause; reset the default
20619 * return value. */
20620 current_funccal->rettv->v_type = VAR_NUMBER;
20621 current_funccal->rettv->vval.v_number = 0;
20624 report_make_pending(CSTP_RETURN, rettv);
20626 else
20628 current_funccal->returned = TRUE;
20630 /* If the return is carried out now, store the return value. For
20631 * a return immediately after reanimation, the value is already
20632 * there. */
20633 if (!reanimate && rettv != NULL)
20635 clear_tv(current_funccal->rettv);
20636 *current_funccal->rettv = *(typval_T *)rettv;
20637 if (!is_cmd)
20638 vim_free(rettv);
20642 return idx < 0;
20646 * Free the variable with a pending return value.
20648 void
20649 discard_pending_return(rettv)
20650 void *rettv;
20652 free_tv((typval_T *)rettv);
20656 * Generate a return command for producing the value of "rettv". The result
20657 * is an allocated string. Used by report_pending() for verbose messages.
20659 char_u *
20660 get_return_cmd(rettv)
20661 void *rettv;
20663 char_u *s = NULL;
20664 char_u *tofree = NULL;
20665 char_u numbuf[NUMBUFLEN];
20667 if (rettv != NULL)
20668 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
20669 if (s == NULL)
20670 s = (char_u *)"";
20672 STRCPY(IObuff, ":return ");
20673 STRNCPY(IObuff + 8, s, IOSIZE - 8);
20674 if (STRLEN(s) + 8 >= IOSIZE)
20675 STRCPY(IObuff + IOSIZE - 4, "...");
20676 vim_free(tofree);
20677 return vim_strsave(IObuff);
20681 * Get next function line.
20682 * Called by do_cmdline() to get the next line.
20683 * Returns allocated string, or NULL for end of function.
20685 /* ARGSUSED */
20686 char_u *
20687 get_func_line(c, cookie, indent)
20688 int c; /* not used */
20689 void *cookie;
20690 int indent; /* not used */
20692 funccall_T *fcp = (funccall_T *)cookie;
20693 ufunc_T *fp = fcp->func;
20694 char_u *retval;
20695 garray_T *gap; /* growarray with function lines */
20697 /* If breakpoints have been added/deleted need to check for it. */
20698 if (fcp->dbg_tick != debug_tick)
20700 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
20701 sourcing_lnum);
20702 fcp->dbg_tick = debug_tick;
20704 #ifdef FEAT_PROFILE
20705 if (do_profiling == PROF_YES)
20706 func_line_end(cookie);
20707 #endif
20709 gap = &fp->uf_lines;
20710 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
20711 || fcp->returned)
20712 retval = NULL;
20713 else
20715 /* Skip NULL lines (continuation lines). */
20716 while (fcp->linenr < gap->ga_len
20717 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
20718 ++fcp->linenr;
20719 if (fcp->linenr >= gap->ga_len)
20720 retval = NULL;
20721 else
20723 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
20724 sourcing_lnum = fcp->linenr;
20725 #ifdef FEAT_PROFILE
20726 if (do_profiling == PROF_YES)
20727 func_line_start(cookie);
20728 #endif
20732 /* Did we encounter a breakpoint? */
20733 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
20735 dbg_breakpoint(fp->uf_name, sourcing_lnum);
20736 /* Find next breakpoint. */
20737 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
20738 sourcing_lnum);
20739 fcp->dbg_tick = debug_tick;
20742 return retval;
20745 #if defined(FEAT_PROFILE) || defined(PROTO)
20747 * Called when starting to read a function line.
20748 * "sourcing_lnum" must be correct!
20749 * When skipping lines it may not actually be executed, but we won't find out
20750 * until later and we need to store the time now.
20752 void
20753 func_line_start(cookie)
20754 void *cookie;
20756 funccall_T *fcp = (funccall_T *)cookie;
20757 ufunc_T *fp = fcp->func;
20759 if (fp->uf_profiling && sourcing_lnum >= 1
20760 && sourcing_lnum <= fp->uf_lines.ga_len)
20762 fp->uf_tml_idx = sourcing_lnum - 1;
20763 /* Skip continuation lines. */
20764 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
20765 --fp->uf_tml_idx;
20766 fp->uf_tml_execed = FALSE;
20767 profile_start(&fp->uf_tml_start);
20768 profile_zero(&fp->uf_tml_children);
20769 profile_get_wait(&fp->uf_tml_wait);
20774 * Called when actually executing a function line.
20776 void
20777 func_line_exec(cookie)
20778 void *cookie;
20780 funccall_T *fcp = (funccall_T *)cookie;
20781 ufunc_T *fp = fcp->func;
20783 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
20784 fp->uf_tml_execed = TRUE;
20788 * Called when done with a function line.
20790 void
20791 func_line_end(cookie)
20792 void *cookie;
20794 funccall_T *fcp = (funccall_T *)cookie;
20795 ufunc_T *fp = fcp->func;
20797 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
20799 if (fp->uf_tml_execed)
20801 ++fp->uf_tml_count[fp->uf_tml_idx];
20802 profile_end(&fp->uf_tml_start);
20803 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
20804 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
20805 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
20806 &fp->uf_tml_children);
20808 fp->uf_tml_idx = -1;
20811 #endif
20814 * Return TRUE if the currently active function should be ended, because a
20815 * return was encountered or an error occured. Used inside a ":while".
20818 func_has_ended(cookie)
20819 void *cookie;
20821 funccall_T *fcp = (funccall_T *)cookie;
20823 /* Ignore the "abort" flag if the abortion behavior has been changed due to
20824 * an error inside a try conditional. */
20825 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
20826 || fcp->returned);
20830 * return TRUE if cookie indicates a function which "abort"s on errors.
20833 func_has_abort(cookie)
20834 void *cookie;
20836 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
20839 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
20840 typedef enum
20842 VAR_FLAVOUR_DEFAULT,
20843 VAR_FLAVOUR_SESSION,
20844 VAR_FLAVOUR_VIMINFO
20845 } var_flavour_T;
20847 static var_flavour_T var_flavour __ARGS((char_u *varname));
20849 static var_flavour_T
20850 var_flavour(varname)
20851 char_u *varname;
20853 char_u *p = varname;
20855 if (ASCII_ISUPPER(*p))
20857 while (*(++p))
20858 if (ASCII_ISLOWER(*p))
20859 return VAR_FLAVOUR_SESSION;
20860 return VAR_FLAVOUR_VIMINFO;
20862 else
20863 return VAR_FLAVOUR_DEFAULT;
20865 #endif
20867 #if defined(FEAT_VIMINFO) || defined(PROTO)
20869 * Restore global vars that start with a capital from the viminfo file
20872 read_viminfo_varlist(virp, writing)
20873 vir_T *virp;
20874 int writing;
20876 char_u *tab;
20877 int is_string = FALSE;
20878 typval_T tv;
20880 if (!writing && (find_viminfo_parameter('!') != NULL))
20882 tab = vim_strchr(virp->vir_line + 1, '\t');
20883 if (tab != NULL)
20885 *tab++ = '\0'; /* isolate the variable name */
20886 if (*tab == 'S') /* string var */
20887 is_string = TRUE;
20889 tab = vim_strchr(tab, '\t');
20890 if (tab != NULL)
20892 if (is_string)
20894 tv.v_type = VAR_STRING;
20895 tv.vval.v_string = viminfo_readstring(virp,
20896 (int)(tab - virp->vir_line + 1), TRUE);
20898 else
20900 tv.v_type = VAR_NUMBER;
20901 tv.vval.v_number = atol((char *)tab + 1);
20903 set_var(virp->vir_line + 1, &tv, FALSE);
20904 if (is_string)
20905 vim_free(tv.vval.v_string);
20910 return viminfo_readline(virp);
20914 * Write global vars that start with a capital to the viminfo file
20916 void
20917 write_viminfo_varlist(fp)
20918 FILE *fp;
20920 hashitem_T *hi;
20921 dictitem_T *this_var;
20922 int todo;
20923 char *s;
20924 char_u *p;
20925 char_u *tofree;
20926 char_u numbuf[NUMBUFLEN];
20928 if (find_viminfo_parameter('!') == NULL)
20929 return;
20931 fprintf(fp, _("\n# global variables:\n"));
20933 todo = (int)globvarht.ht_used;
20934 for (hi = globvarht.ht_array; todo > 0; ++hi)
20936 if (!HASHITEM_EMPTY(hi))
20938 --todo;
20939 this_var = HI2DI(hi);
20940 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
20942 switch (this_var->di_tv.v_type)
20944 case VAR_STRING: s = "STR"; break;
20945 case VAR_NUMBER: s = "NUM"; break;
20946 default: continue;
20948 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
20949 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
20950 if (p != NULL)
20951 viminfo_writestring(fp, p);
20952 vim_free(tofree);
20957 #endif
20959 #if defined(FEAT_SESSION) || defined(PROTO)
20961 store_session_globals(fd)
20962 FILE *fd;
20964 hashitem_T *hi;
20965 dictitem_T *this_var;
20966 int todo;
20967 char_u *p, *t;
20969 todo = (int)globvarht.ht_used;
20970 for (hi = globvarht.ht_array; todo > 0; ++hi)
20972 if (!HASHITEM_EMPTY(hi))
20974 --todo;
20975 this_var = HI2DI(hi);
20976 if ((this_var->di_tv.v_type == VAR_NUMBER
20977 || this_var->di_tv.v_type == VAR_STRING)
20978 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
20980 /* Escape special characters with a backslash. Turn a LF and
20981 * CR into \n and \r. */
20982 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
20983 (char_u *)"\\\"\n\r");
20984 if (p == NULL) /* out of memory */
20985 break;
20986 for (t = p; *t != NUL; ++t)
20987 if (*t == '\n')
20988 *t = 'n';
20989 else if (*t == '\r')
20990 *t = 'r';
20991 if ((fprintf(fd, "let %s = %c%s%c",
20992 this_var->di_key,
20993 (this_var->di_tv.v_type == VAR_STRING) ? '"'
20994 : ' ',
20996 (this_var->di_tv.v_type == VAR_STRING) ? '"'
20997 : ' ') < 0)
20998 || put_eol(fd) == FAIL)
21000 vim_free(p);
21001 return FAIL;
21003 vim_free(p);
21007 return OK;
21009 #endif
21012 * Display script name where an item was last set.
21013 * Should only be invoked when 'verbose' is non-zero.
21015 void
21016 last_set_msg(scriptID)
21017 scid_T scriptID;
21019 char_u *p;
21021 if (scriptID != 0)
21023 p = home_replace_save(NULL, get_scriptname(scriptID));
21024 if (p != NULL)
21026 verbose_enter();
21027 MSG_PUTS(_("\n\tLast set from "));
21028 MSG_PUTS(p);
21029 vim_free(p);
21030 verbose_leave();
21035 #endif /* FEAT_EVAL */
21037 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
21040 #ifdef WIN3264
21042 * Functions for ":8" filename modifier: get 8.3 version of a filename.
21044 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
21045 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
21046 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
21049 * Get the short pathname of a file.
21050 * Returns 1 on success. *fnamelen is 0 for nonexistent path.
21052 static int
21053 get_short_pathname(fnamep, bufp, fnamelen)
21054 char_u **fnamep;
21055 char_u **bufp;
21056 int *fnamelen;
21058 int l,len;
21059 char_u *newbuf;
21061 len = *fnamelen;
21063 l = GetShortPathName(*fnamep, *fnamep, len);
21064 if (l > len - 1)
21066 /* If that doesn't work (not enough space), then save the string
21067 * and try again with a new buffer big enough
21069 newbuf = vim_strnsave(*fnamep, l);
21070 if (newbuf == NULL)
21071 return 0;
21073 vim_free(*bufp);
21074 *fnamep = *bufp = newbuf;
21076 l = GetShortPathName(*fnamep,*fnamep,l+1);
21078 /* Really should always succeed, as the buffer is big enough */
21081 *fnamelen = l;
21082 return 1;
21086 * Create a short path name. Returns the length of the buffer it needs.
21087 * Doesn't copy over the end of the buffer passed in.
21089 static int
21090 shortpath_for_invalid_fname(fname, bufp, fnamelen)
21091 char_u **fname;
21092 char_u **bufp;
21093 int *fnamelen;
21095 char_u *s, *p, *pbuf2, *pbuf3;
21096 char_u ch;
21097 int len, len2, plen, slen;
21099 /* Make a copy */
21100 len2 = *fnamelen;
21101 pbuf2 = vim_strnsave(*fname, len2);
21102 pbuf3 = NULL;
21104 s = pbuf2 + len2 - 1; /* Find the end */
21105 slen = 1;
21106 plen = len2;
21108 if (after_pathsep(pbuf2, s + 1))
21110 --s;
21111 ++slen;
21112 --plen;
21117 /* Go back one path-separator */
21118 while (s > pbuf2 && !after_pathsep(pbuf2, s + 1))
21120 --s;
21121 ++slen;
21122 --plen;
21124 if (s <= pbuf2)
21125 break;
21127 /* Remember the character that is about to be splatted */
21128 ch = *s;
21129 *s = 0; /* get_short_pathname requires a null-terminated string */
21131 /* Try it in situ */
21132 p = pbuf2;
21133 if (!get_short_pathname(&p, &pbuf3, &plen))
21135 vim_free(pbuf2);
21136 return -1;
21138 *s = ch; /* Preserve the string */
21139 } while (plen == 0);
21141 if (plen > 0)
21143 /* Remember the length of the new string. */
21144 *fnamelen = len = plen + slen;
21145 vim_free(*bufp);
21146 if (len > len2)
21148 /* If there's not enough space in the currently allocated string,
21149 * then copy it to a buffer big enough.
21151 *fname= *bufp = vim_strnsave(p, len);
21152 if (*fname == NULL)
21153 return -1;
21155 else
21157 /* Transfer pbuf2 to being the main buffer (it's big enough) */
21158 *fname = *bufp = pbuf2;
21159 if (p != pbuf2)
21160 strncpy(*fname, p, plen);
21161 pbuf2 = NULL;
21163 /* Concat the next bit */
21164 strncpy(*fname + plen, s, slen);
21165 (*fname)[len] = '\0';
21167 vim_free(pbuf3);
21168 vim_free(pbuf2);
21169 return 0;
21173 * Get a pathname for a partial path.
21175 static int
21176 shortpath_for_partial(fnamep, bufp, fnamelen)
21177 char_u **fnamep;
21178 char_u **bufp;
21179 int *fnamelen;
21181 int sepcount, len, tflen;
21182 char_u *p;
21183 char_u *pbuf, *tfname;
21184 int hasTilde;
21186 /* Count up the path seperators from the RHS.. so we know which part
21187 * of the path to return.
21189 sepcount = 0;
21190 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
21191 if (vim_ispathsep(*p))
21192 ++sepcount;
21194 /* Need full path first (use expand_env() to remove a "~/") */
21195 hasTilde = (**fnamep == '~');
21196 if (hasTilde)
21197 pbuf = tfname = expand_env_save(*fnamep);
21198 else
21199 pbuf = tfname = FullName_save(*fnamep, FALSE);
21201 len = tflen = (int)STRLEN(tfname);
21203 if (!get_short_pathname(&tfname, &pbuf, &len))
21204 return -1;
21206 if (len == 0)
21208 /* Don't have a valid filename, so shorten the rest of the
21209 * path if we can. This CAN give us invalid 8.3 filenames, but
21210 * there's not a lot of point in guessing what it might be.
21212 len = tflen;
21213 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == -1)
21214 return -1;
21217 /* Count the paths backward to find the beginning of the desired string. */
21218 for (p = tfname + len - 1; p >= tfname; --p)
21220 #ifdef FEAT_MBYTE
21221 if (has_mbyte)
21222 p -= mb_head_off(tfname, p);
21223 #endif
21224 if (vim_ispathsep(*p))
21226 if (sepcount == 0 || (hasTilde && sepcount == 1))
21227 break;
21228 else
21229 sepcount --;
21232 if (hasTilde)
21234 --p;
21235 if (p >= tfname)
21236 *p = '~';
21237 else
21238 return -1;
21240 else
21241 ++p;
21243 /* Copy in the string - p indexes into tfname - allocated at pbuf */
21244 vim_free(*bufp);
21245 *fnamelen = (int)STRLEN(p);
21246 *bufp = pbuf;
21247 *fnamep = p;
21249 return 0;
21251 #endif /* WIN3264 */
21254 * Adjust a filename, according to a string of modifiers.
21255 * *fnamep must be NUL terminated when called. When returning, the length is
21256 * determined by *fnamelen.
21257 * Returns valid flags.
21258 * When there is an error, *fnamep is set to NULL.
21261 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
21262 char_u *src; /* string with modifiers */
21263 int *usedlen; /* characters after src that are used */
21264 char_u **fnamep; /* file name so far */
21265 char_u **bufp; /* buffer for allocated file name or NULL */
21266 int *fnamelen; /* length of fnamep */
21268 int valid = 0;
21269 char_u *tail;
21270 char_u *s, *p, *pbuf;
21271 char_u dirname[MAXPATHL];
21272 int c;
21273 int has_fullname = 0;
21274 #ifdef WIN3264
21275 int has_shortname = 0;
21276 #endif
21278 repeat:
21279 /* ":p" - full path/file_name */
21280 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
21282 has_fullname = 1;
21284 valid |= VALID_PATH;
21285 *usedlen += 2;
21287 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
21288 if ((*fnamep)[0] == '~'
21289 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
21290 && ((*fnamep)[1] == '/'
21291 # ifdef BACKSLASH_IN_FILENAME
21292 || (*fnamep)[1] == '\\'
21293 # endif
21294 || (*fnamep)[1] == NUL)
21296 #endif
21299 *fnamep = expand_env_save(*fnamep);
21300 vim_free(*bufp); /* free any allocated file name */
21301 *bufp = *fnamep;
21302 if (*fnamep == NULL)
21303 return -1;
21306 /* When "/." or "/.." is used: force expansion to get rid of it. */
21307 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
21309 if (vim_ispathsep(*p)
21310 && p[1] == '.'
21311 && (p[2] == NUL
21312 || vim_ispathsep(p[2])
21313 || (p[2] == '.'
21314 && (p[3] == NUL || vim_ispathsep(p[3])))))
21315 break;
21318 /* FullName_save() is slow, don't use it when not needed. */
21319 if (*p != NUL || !vim_isAbsName(*fnamep))
21321 *fnamep = FullName_save(*fnamep, *p != NUL);
21322 vim_free(*bufp); /* free any allocated file name */
21323 *bufp = *fnamep;
21324 if (*fnamep == NULL)
21325 return -1;
21328 /* Append a path separator to a directory. */
21329 if (mch_isdir(*fnamep))
21331 /* Make room for one or two extra characters. */
21332 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
21333 vim_free(*bufp); /* free any allocated file name */
21334 *bufp = *fnamep;
21335 if (*fnamep == NULL)
21336 return -1;
21337 add_pathsep(*fnamep);
21341 /* ":." - path relative to the current directory */
21342 /* ":~" - path relative to the home directory */
21343 /* ":8" - shortname path - postponed till after */
21344 while (src[*usedlen] == ':'
21345 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
21347 *usedlen += 2;
21348 if (c == '8')
21350 #ifdef WIN3264
21351 has_shortname = 1; /* Postpone this. */
21352 #endif
21353 continue;
21355 pbuf = NULL;
21356 /* Need full path first (use expand_env() to remove a "~/") */
21357 if (!has_fullname)
21359 if (c == '.' && **fnamep == '~')
21360 p = pbuf = expand_env_save(*fnamep);
21361 else
21362 p = pbuf = FullName_save(*fnamep, FALSE);
21364 else
21365 p = *fnamep;
21367 has_fullname = 0;
21369 if (p != NULL)
21371 if (c == '.')
21373 mch_dirname(dirname, MAXPATHL);
21374 s = shorten_fname(p, dirname);
21375 if (s != NULL)
21377 *fnamep = s;
21378 if (pbuf != NULL)
21380 vim_free(*bufp); /* free any allocated file name */
21381 *bufp = pbuf;
21382 pbuf = NULL;
21386 else
21388 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
21389 /* Only replace it when it starts with '~' */
21390 if (*dirname == '~')
21392 s = vim_strsave(dirname);
21393 if (s != NULL)
21395 *fnamep = s;
21396 vim_free(*bufp);
21397 *bufp = s;
21401 vim_free(pbuf);
21405 tail = gettail(*fnamep);
21406 *fnamelen = (int)STRLEN(*fnamep);
21408 /* ":h" - head, remove "/file_name", can be repeated */
21409 /* Don't remove the first "/" or "c:\" */
21410 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
21412 valid |= VALID_HEAD;
21413 *usedlen += 2;
21414 s = get_past_head(*fnamep);
21415 while (tail > s && after_pathsep(s, tail))
21416 mb_ptr_back(*fnamep, tail);
21417 *fnamelen = (int)(tail - *fnamep);
21418 #ifdef VMS
21419 if (*fnamelen > 0)
21420 *fnamelen += 1; /* the path separator is part of the path */
21421 #endif
21422 if (*fnamelen == 0)
21424 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
21425 p = vim_strsave((char_u *)".");
21426 if (p == NULL)
21427 return -1;
21428 vim_free(*bufp);
21429 *bufp = *fnamep = tail = p;
21430 *fnamelen = 1;
21432 else
21434 while (tail > s && !after_pathsep(s, tail))
21435 mb_ptr_back(*fnamep, tail);
21439 /* ":8" - shortname */
21440 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
21442 *usedlen += 2;
21443 #ifdef WIN3264
21444 has_shortname = 1;
21445 #endif
21448 #ifdef WIN3264
21449 /* Check shortname after we have done 'heads' and before we do 'tails'
21451 if (has_shortname)
21453 pbuf = NULL;
21454 /* Copy the string if it is shortened by :h */
21455 if (*fnamelen < (int)STRLEN(*fnamep))
21457 p = vim_strnsave(*fnamep, *fnamelen);
21458 if (p == 0)
21459 return -1;
21460 vim_free(*bufp);
21461 *bufp = *fnamep = p;
21464 /* Split into two implementations - makes it easier. First is where
21465 * there isn't a full name already, second is where there is.
21467 if (!has_fullname && !vim_isAbsName(*fnamep))
21469 if (shortpath_for_partial(fnamep, bufp, fnamelen) == -1)
21470 return -1;
21472 else
21474 int l;
21476 /* Simple case, already have the full-name
21477 * Nearly always shorter, so try first time. */
21478 l = *fnamelen;
21479 if (!get_short_pathname(fnamep, bufp, &l))
21480 return -1;
21482 if (l == 0)
21484 /* Couldn't find the filename.. search the paths.
21486 l = *fnamelen;
21487 if (shortpath_for_invalid_fname(fnamep, bufp, &l ) == -1)
21488 return -1;
21490 *fnamelen = l;
21493 #endif /* WIN3264 */
21495 /* ":t" - tail, just the basename */
21496 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
21498 *usedlen += 2;
21499 *fnamelen -= (int)(tail - *fnamep);
21500 *fnamep = tail;
21503 /* ":e" - extension, can be repeated */
21504 /* ":r" - root, without extension, can be repeated */
21505 while (src[*usedlen] == ':'
21506 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
21508 /* find a '.' in the tail:
21509 * - for second :e: before the current fname
21510 * - otherwise: The last '.'
21512 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
21513 s = *fnamep - 2;
21514 else
21515 s = *fnamep + *fnamelen - 1;
21516 for ( ; s > tail; --s)
21517 if (s[0] == '.')
21518 break;
21519 if (src[*usedlen + 1] == 'e') /* :e */
21521 if (s > tail)
21523 *fnamelen += (int)(*fnamep - (s + 1));
21524 *fnamep = s + 1;
21525 #ifdef VMS
21526 /* cut version from the extension */
21527 s = *fnamep + *fnamelen - 1;
21528 for ( ; s > *fnamep; --s)
21529 if (s[0] == ';')
21530 break;
21531 if (s > *fnamep)
21532 *fnamelen = s - *fnamep;
21533 #endif
21535 else if (*fnamep <= tail)
21536 *fnamelen = 0;
21538 else /* :r */
21540 if (s > tail) /* remove one extension */
21541 *fnamelen = (int)(s - *fnamep);
21543 *usedlen += 2;
21546 /* ":s?pat?foo?" - substitute */
21547 /* ":gs?pat?foo?" - global substitute */
21548 if (src[*usedlen] == ':'
21549 && (src[*usedlen + 1] == 's'
21550 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
21552 char_u *str;
21553 char_u *pat;
21554 char_u *sub;
21555 int sep;
21556 char_u *flags;
21557 int didit = FALSE;
21559 flags = (char_u *)"";
21560 s = src + *usedlen + 2;
21561 if (src[*usedlen + 1] == 'g')
21563 flags = (char_u *)"g";
21564 ++s;
21567 sep = *s++;
21568 if (sep)
21570 /* find end of pattern */
21571 p = vim_strchr(s, sep);
21572 if (p != NULL)
21574 pat = vim_strnsave(s, (int)(p - s));
21575 if (pat != NULL)
21577 s = p + 1;
21578 /* find end of substitution */
21579 p = vim_strchr(s, sep);
21580 if (p != NULL)
21582 sub = vim_strnsave(s, (int)(p - s));
21583 str = vim_strnsave(*fnamep, *fnamelen);
21584 if (sub != NULL && str != NULL)
21586 *usedlen = (int)(p + 1 - src);
21587 s = do_string_sub(str, pat, sub, flags);
21588 if (s != NULL)
21590 *fnamep = s;
21591 *fnamelen = (int)STRLEN(s);
21592 vim_free(*bufp);
21593 *bufp = s;
21594 didit = TRUE;
21597 vim_free(sub);
21598 vim_free(str);
21600 vim_free(pat);
21603 /* after using ":s", repeat all the modifiers */
21604 if (didit)
21605 goto repeat;
21609 return valid;
21613 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
21614 * "flags" can be "g" to do a global substitute.
21615 * Returns an allocated string, NULL for error.
21617 char_u *
21618 do_string_sub(str, pat, sub, flags)
21619 char_u *str;
21620 char_u *pat;
21621 char_u *sub;
21622 char_u *flags;
21624 int sublen;
21625 regmatch_T regmatch;
21626 int i;
21627 int do_all;
21628 char_u *tail;
21629 garray_T ga;
21630 char_u *ret;
21631 char_u *save_cpo;
21633 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
21634 save_cpo = p_cpo;
21635 p_cpo = (char_u *)"";
21637 ga_init2(&ga, 1, 200);
21639 do_all = (flags[0] == 'g');
21641 regmatch.rm_ic = p_ic;
21642 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
21643 if (regmatch.regprog != NULL)
21645 tail = str;
21646 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
21649 * Get some space for a temporary buffer to do the substitution
21650 * into. It will contain:
21651 * - The text up to where the match is.
21652 * - The substituted text.
21653 * - The text after the match.
21655 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
21656 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
21657 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
21659 ga_clear(&ga);
21660 break;
21663 /* copy the text up to where the match is */
21664 i = (int)(regmatch.startp[0] - tail);
21665 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
21666 /* add the substituted text */
21667 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
21668 + ga.ga_len + i, TRUE, TRUE, FALSE);
21669 ga.ga_len += i + sublen - 1;
21670 /* avoid getting stuck on a match with an empty string */
21671 if (tail == regmatch.endp[0])
21673 if (*tail == NUL)
21674 break;
21675 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
21676 ++ga.ga_len;
21678 else
21680 tail = regmatch.endp[0];
21681 if (*tail == NUL)
21682 break;
21684 if (!do_all)
21685 break;
21688 if (ga.ga_data != NULL)
21689 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
21691 vim_free(regmatch.regprog);
21694 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
21695 ga_clear(&ga);
21696 p_cpo = save_cpo;
21698 return ret;
21701 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */