ODB Editor protocol (aka 'external editor') support
[MacVim.git] / src / eval.c
blob11d700366a94b01b426828a0530b2efaf1d2ac6d
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},
350 /* shorthand */
351 #define vv_type vv_di.di_tv.v_type
352 #define vv_nr vv_di.di_tv.vval.v_number
353 #define vv_str vv_di.di_tv.vval.v_string
354 #define vv_tv vv_di.di_tv
357 * The v: variables are stored in dictionary "vimvardict".
358 * "vimvars_var" is the variable that is used for the "l:" scope.
360 static dict_T vimvardict;
361 static dictitem_T vimvars_var;
362 #define vimvarht vimvardict.dv_hashtab
364 static void prepare_vimvar __ARGS((int idx, typval_T *save_tv));
365 static void restore_vimvar __ARGS((int idx, typval_T *save_tv));
366 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
367 static int call_vim_function __ARGS((char_u *func, int argc, char_u **argv, int safe, typval_T *rettv));
368 #endif
369 static int ex_let_vars __ARGS((char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars));
370 static char_u *skip_var_list __ARGS((char_u *arg, int *var_count, int *semicolon));
371 static char_u *skip_var_one __ARGS((char_u *arg));
372 static void list_hashtable_vars __ARGS((hashtab_T *ht, char_u *prefix, int empty, int *first));
373 static void list_glob_vars __ARGS((int *first));
374 static void list_buf_vars __ARGS((int *first));
375 static void list_win_vars __ARGS((int *first));
376 #ifdef FEAT_WINDOWS
377 static void list_tab_vars __ARGS((int *first));
378 #endif
379 static void list_vim_vars __ARGS((int *first));
380 static void list_script_vars __ARGS((int *first));
381 static void list_func_vars __ARGS((int *first));
382 static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg, int *first));
383 static char_u *ex_let_one __ARGS((char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op));
384 static int check_changedtick __ARGS((char_u *arg));
385 static char_u *get_lval __ARGS((char_u *name, typval_T *rettv, lval_T *lp, int unlet, int skip, int quiet, int fne_flags));
386 static void clear_lval __ARGS((lval_T *lp));
387 static void set_var_lval __ARGS((lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op));
388 static int tv_op __ARGS((typval_T *tv1, typval_T *tv2, char_u *op));
389 static void list_add_watch __ARGS((list_T *l, listwatch_T *lw));
390 static void list_rem_watch __ARGS((list_T *l, listwatch_T *lwrem));
391 static void list_fix_watch __ARGS((list_T *l, listitem_T *item));
392 static void ex_unletlock __ARGS((exarg_T *eap, char_u *argstart, int deep));
393 static int do_unlet_var __ARGS((lval_T *lp, char_u *name_end, int forceit));
394 static int do_lock_var __ARGS((lval_T *lp, char_u *name_end, int deep, int lock));
395 static void item_lock __ARGS((typval_T *tv, int deep, int lock));
396 static int tv_islocked __ARGS((typval_T *tv));
398 static int eval0 __ARGS((char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate));
399 static int eval1 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
400 static int eval2 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
401 static int eval3 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
402 static int eval4 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
403 static int eval5 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
404 static int eval6 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
405 static int eval7 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
407 static int eval_index __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
408 static int get_option_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
409 static int get_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
410 static int get_lit_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
411 static int get_list_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
412 static int rettv_list_alloc __ARGS((typval_T *rettv));
413 static listitem_T *listitem_alloc __ARGS((void));
414 static void listitem_free __ARGS((listitem_T *item));
415 static void listitem_remove __ARGS((list_T *l, listitem_T *item));
416 static long list_len __ARGS((list_T *l));
417 static int list_equal __ARGS((list_T *l1, list_T *l2, int ic));
418 static int dict_equal __ARGS((dict_T *d1, dict_T *d2, int ic));
419 static int tv_equal __ARGS((typval_T *tv1, typval_T *tv2, int ic));
420 static listitem_T *list_find __ARGS((list_T *l, long n));
421 static long list_find_nr __ARGS((list_T *l, long idx, int *errorp));
422 static long list_idx_of_item __ARGS((list_T *l, listitem_T *item));
423 static void list_append __ARGS((list_T *l, listitem_T *item));
424 static int list_append_tv __ARGS((list_T *l, typval_T *tv));
425 static int list_append_string __ARGS((list_T *l, char_u *str, int len));
426 static int list_append_number __ARGS((list_T *l, varnumber_T n));
427 static int list_insert_tv __ARGS((list_T *l, typval_T *tv, listitem_T *item));
428 static int list_extend __ARGS((list_T *l1, list_T *l2, listitem_T *bef));
429 static int list_concat __ARGS((list_T *l1, list_T *l2, typval_T *tv));
430 static list_T *list_copy __ARGS((list_T *orig, int deep, int copyID));
431 static void list_remove __ARGS((list_T *l, listitem_T *item, listitem_T *item2));
432 static char_u *list2string __ARGS((typval_T *tv, int copyID));
433 static int list_join __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo, int copyID));
434 static void set_ref_in_ht __ARGS((hashtab_T *ht, int copyID));
435 static void set_ref_in_list __ARGS((list_T *l, int copyID));
436 static void set_ref_in_item __ARGS((typval_T *tv, int copyID));
437 static void dict_unref __ARGS((dict_T *d));
438 static void dict_free __ARGS((dict_T *d, int recurse));
439 static dictitem_T *dictitem_alloc __ARGS((char_u *key));
440 static dictitem_T *dictitem_copy __ARGS((dictitem_T *org));
441 static void dictitem_remove __ARGS((dict_T *dict, dictitem_T *item));
442 static void dictitem_free __ARGS((dictitem_T *item));
443 static dict_T *dict_copy __ARGS((dict_T *orig, int deep, int copyID));
444 static int dict_add __ARGS((dict_T *d, dictitem_T *item));
445 static long dict_len __ARGS((dict_T *d));
446 static dictitem_T *dict_find __ARGS((dict_T *d, char_u *key, int len));
447 static char_u *dict2string __ARGS((typval_T *tv, int copyID));
448 static int get_dict_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
449 static char_u *echo_string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
450 static char_u *tv2string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
451 static char_u *string_quote __ARGS((char_u *str, int function));
452 static int get_env_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
453 static int find_internal_func __ARGS((char_u *name));
454 static char_u *deref_func_name __ARGS((char_u *name, int *lenp));
455 static int get_func_tv __ARGS((char_u *name, int len, typval_T *rettv, char_u **arg, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
456 static int call_func __ARGS((char_u *name, int len, typval_T *rettv, int argcount, typval_T *argvars, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
457 static void emsg_funcname __ARGS((char *ermsg, char_u *name));
459 static void f_add __ARGS((typval_T *argvars, typval_T *rettv));
460 static void f_append __ARGS((typval_T *argvars, typval_T *rettv));
461 static void f_argc __ARGS((typval_T *argvars, typval_T *rettv));
462 static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv));
463 static void f_argv __ARGS((typval_T *argvars, typval_T *rettv));
464 static void f_browse __ARGS((typval_T *argvars, typval_T *rettv));
465 static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv));
466 static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv));
467 static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv));
468 static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv));
469 static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv));
470 static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv));
471 static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv));
472 static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv));
473 static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv));
474 static void f_call __ARGS((typval_T *argvars, typval_T *rettv));
475 static void f_changenr __ARGS((typval_T *argvars, typval_T *rettv));
476 static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv));
477 static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv));
478 static void f_clearmatches __ARGS((typval_T *argvars, typval_T *rettv));
479 static void f_col __ARGS((typval_T *argvars, typval_T *rettv));
480 #if defined(FEAT_INS_EXPAND)
481 static void f_complete __ARGS((typval_T *argvars, typval_T *rettv));
482 static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv));
483 static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv));
484 #endif
485 static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv));
486 static void f_copy __ARGS((typval_T *argvars, typval_T *rettv));
487 static void f_count __ARGS((typval_T *argvars, typval_T *rettv));
488 static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv));
489 static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv));
490 static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv));
491 static void f_delete __ARGS((typval_T *argvars, typval_T *rettv));
492 static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv));
493 static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv));
494 static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv));
495 static void f_empty __ARGS((typval_T *argvars, typval_T *rettv));
496 static void f_escape __ARGS((typval_T *argvars, typval_T *rettv));
497 static void f_eval __ARGS((typval_T *argvars, typval_T *rettv));
498 static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv));
499 static void f_executable __ARGS((typval_T *argvars, typval_T *rettv));
500 static void f_exists __ARGS((typval_T *argvars, typval_T *rettv));
501 static void f_expand __ARGS((typval_T *argvars, typval_T *rettv));
502 static void f_extend __ARGS((typval_T *argvars, typval_T *rettv));
503 static void f_feedkeys __ARGS((typval_T *argvars, typval_T *rettv));
504 static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv));
505 static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv));
506 static void f_filter __ARGS((typval_T *argvars, typval_T *rettv));
507 static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv));
508 static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv));
509 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
510 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
511 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
513 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
514 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
516 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
517 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
520 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
521 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
523 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
524 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
525 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
526 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
528 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
529 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
531 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
532 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
533 static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv));
534 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
535 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
536 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
537 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
542 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
546 static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv));
547 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
548 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
549 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
551 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
552 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
590 #ifdef vim_mkdir
591 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
592 #endif
593 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
594 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
595 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
596 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
603 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
604 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
605 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
606 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
607 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
608 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
609 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
610 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
611 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
618 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
619 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
620 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
621 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
622 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
623 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
624 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
625 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
626 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
627 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
628 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
629 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
630 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
631 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
632 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
633 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
634 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
635 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
636 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
637 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
638 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
639 #ifdef HAVE_STRFTIME
640 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
641 #endif
642 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
643 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
644 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
645 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
646 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
647 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
648 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
649 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
650 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
651 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
652 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
653 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
654 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
655 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
656 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
657 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
667 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
668 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
669 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
670 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
671 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
672 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
673 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
674 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
675 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
676 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
677 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
679 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
680 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
681 static int get_env_len __ARGS((char_u **arg));
682 static int get_id_len __ARGS((char_u **arg));
683 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
684 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
685 #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */
686 #define FNE_CHECK_START 2 /* find_name_end(): check name starts with
687 valid character */
688 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
689 static int eval_isnamec __ARGS((int c));
690 static int eval_isnamec1 __ARGS((int c));
691 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
692 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
693 static typval_T *alloc_tv __ARGS((void));
694 static typval_T *alloc_string_tv __ARGS((char_u *string));
695 static void init_tv __ARGS((typval_T *varp));
696 static long get_tv_number __ARGS((typval_T *varp));
697 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
698 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
699 static char_u *get_tv_string __ARGS((typval_T *varp));
700 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
701 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
702 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
703 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
704 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
705 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
706 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
707 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
708 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
709 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
710 static int var_check_ro __ARGS((int flags, char_u *name));
711 static int var_check_fixed __ARGS((int flags, char_u *name));
712 static int tv_check_lock __ARGS((int lock, char_u *name));
713 static void copy_tv __ARGS((typval_T *from, typval_T *to));
714 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
715 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
716 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
717 static int eval_fname_script __ARGS((char_u *p));
718 static int eval_fname_sid __ARGS((char_u *p));
719 static void list_func_head __ARGS((ufunc_T *fp, int indent));
720 static ufunc_T *find_func __ARGS((char_u *name));
721 static int function_exists __ARGS((char_u *name));
722 static int builtin_function __ARGS((char_u *name));
723 #ifdef FEAT_PROFILE
724 static void func_do_profile __ARGS((ufunc_T *fp));
725 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
726 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
727 static int
728 # ifdef __BORLANDC__
729 _RTLENTRYF
730 # endif
731 prof_total_cmp __ARGS((const void *s1, const void *s2));
732 static int
733 # ifdef __BORLANDC__
734 _RTLENTRYF
735 # endif
736 prof_self_cmp __ARGS((const void *s1, const void *s2));
737 #endif
738 static int script_autoload __ARGS((char_u *name, int reload));
739 static char_u *autoload_name __ARGS((char_u *name));
740 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
741 static void func_free __ARGS((ufunc_T *fp));
742 static void func_unref __ARGS((char_u *name));
743 static void func_ref __ARGS((char_u *name));
744 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));
745 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
746 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
747 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
748 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
749 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
750 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
752 /* Character used as separated in autoload function/variable names. */
753 #define AUTOLOAD_CHAR '#'
756 * Initialize the global and v: variables.
758 void
759 eval_init()
761 int i;
762 struct vimvar *p;
764 init_var_dict(&globvardict, &globvars_var);
765 init_var_dict(&vimvardict, &vimvars_var);
766 hash_init(&compat_hashtab);
767 hash_init(&func_hashtab);
769 for (i = 0; i < VV_LEN; ++i)
771 p = &vimvars[i];
772 STRCPY(p->vv_di.di_key, p->vv_name);
773 if (p->vv_flags & VV_RO)
774 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
775 else if (p->vv_flags & VV_RO_SBX)
776 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
777 else
778 p->vv_di.di_flags = DI_FLAGS_FIX;
780 /* add to v: scope dict, unless the value is not always available */
781 if (p->vv_type != VAR_UNKNOWN)
782 hash_add(&vimvarht, p->vv_di.di_key);
783 if (p->vv_flags & VV_COMPAT)
784 /* add to compat scope dict */
785 hash_add(&compat_hashtab, p->vv_di.di_key);
789 #if defined(EXITFREE) || defined(PROTO)
790 void
791 eval_clear()
793 int i;
794 struct vimvar *p;
796 for (i = 0; i < VV_LEN; ++i)
798 p = &vimvars[i];
799 if (p->vv_di.di_tv.v_type == VAR_STRING)
801 vim_free(p->vv_di.di_tv.vval.v_string);
802 p->vv_di.di_tv.vval.v_string = NULL;
805 hash_clear(&vimvarht);
806 hash_clear(&compat_hashtab);
808 /* script-local variables */
809 for (i = 1; i <= ga_scripts.ga_len; ++i)
810 vars_clear(&SCRIPT_VARS(i));
811 ga_clear(&ga_scripts);
812 free_scriptnames();
814 /* global variables */
815 vars_clear(&globvarht);
817 /* functions */
818 free_all_functions();
819 hash_clear(&func_hashtab);
821 /* autoloaded script names */
822 ga_clear_strings(&ga_loaded);
824 /* unreferenced lists and dicts */
825 (void)garbage_collect();
827 #endif
830 * Return the name of the executed function.
832 char_u *
833 func_name(cookie)
834 void *cookie;
836 return ((funccall_T *)cookie)->func->uf_name;
840 * Return the address holding the next breakpoint line for a funccall cookie.
842 linenr_T *
843 func_breakpoint(cookie)
844 void *cookie;
846 return &((funccall_T *)cookie)->breakpoint;
850 * Return the address holding the debug tick for a funccall cookie.
852 int *
853 func_dbg_tick(cookie)
854 void *cookie;
856 return &((funccall_T *)cookie)->dbg_tick;
860 * Return the nesting level for a funccall cookie.
863 func_level(cookie)
864 void *cookie;
866 return ((funccall_T *)cookie)->level;
869 /* pointer to funccal for currently active function */
870 funccall_T *current_funccal = NULL;
873 * Return TRUE when a function was ended by a ":return" command.
876 current_func_returned()
878 return current_funccal->returned;
883 * Set an internal variable to a string value. Creates the variable if it does
884 * not already exist.
886 void
887 set_internal_string_var(name, value)
888 char_u *name;
889 char_u *value;
891 char_u *val;
892 typval_T *tvp;
894 val = vim_strsave(value);
895 if (val != NULL)
897 tvp = alloc_string_tv(val);
898 if (tvp != NULL)
900 set_var(name, tvp, FALSE);
901 free_tv(tvp);
906 static lval_T *redir_lval = NULL;
907 static garray_T redir_ga; /* only valid when redir_lval is not NULL */
908 static char_u *redir_endp = NULL;
909 static char_u *redir_varname = NULL;
912 * Start recording command output to a variable
913 * Returns OK if successfully completed the setup. FAIL otherwise.
916 var_redir_start(name, append)
917 char_u *name;
918 int append; /* append to an existing variable */
920 int save_emsg;
921 int err;
922 typval_T tv;
924 /* Make sure a valid variable name is specified */
925 if (!eval_isnamec1(*name))
927 EMSG(_(e_invarg));
928 return FAIL;
931 redir_varname = vim_strsave(name);
932 if (redir_varname == NULL)
933 return FAIL;
935 redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
936 if (redir_lval == NULL)
938 var_redir_stop();
939 return FAIL;
942 /* The output is stored in growarray "redir_ga" until redirection ends. */
943 ga_init2(&redir_ga, (int)sizeof(char), 500);
945 /* Parse the variable name (can be a dict or list entry). */
946 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
947 FNE_CHECK_START);
948 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
950 if (redir_endp != NULL && *redir_endp != NUL)
951 /* Trailing characters are present after the variable name */
952 EMSG(_(e_trailing));
953 else
954 EMSG(_(e_invarg));
955 var_redir_stop();
956 return FAIL;
959 /* check if we can write to the variable: set it to or append an empty
960 * string */
961 save_emsg = did_emsg;
962 did_emsg = FALSE;
963 tv.v_type = VAR_STRING;
964 tv.vval.v_string = (char_u *)"";
965 if (append)
966 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
967 else
968 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
969 err = did_emsg;
970 did_emsg |= save_emsg;
971 if (err)
973 var_redir_stop();
974 return FAIL;
976 if (redir_lval->ll_newkey != NULL)
978 /* Dictionary item was created, don't do it again. */
979 vim_free(redir_lval->ll_newkey);
980 redir_lval->ll_newkey = NULL;
983 return OK;
987 * Append "value[value_len]" to the variable set by var_redir_start().
988 * The actual appending is postponed until redirection ends, because the value
989 * appended may in fact be the string we write to, changing it may cause freed
990 * memory to be used:
991 * :redir => foo
992 * :let foo
993 * :redir END
995 void
996 var_redir_str(value, value_len)
997 char_u *value;
998 int value_len;
1000 int len;
1002 if (redir_lval == NULL)
1003 return;
1005 if (value_len == -1)
1006 len = (int)STRLEN(value); /* Append the entire string */
1007 else
1008 len = value_len; /* Append only "value_len" characters */
1010 if (ga_grow(&redir_ga, len) == OK)
1012 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1013 redir_ga.ga_len += len;
1015 else
1016 var_redir_stop();
1020 * Stop redirecting command output to a variable.
1022 void
1023 var_redir_stop()
1025 typval_T tv;
1027 if (redir_lval != NULL)
1029 /* Append the trailing NUL. */
1030 ga_append(&redir_ga, NUL);
1032 /* Assign the text to the variable. */
1033 tv.v_type = VAR_STRING;
1034 tv.vval.v_string = redir_ga.ga_data;
1035 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1036 vim_free(tv.vval.v_string);
1038 clear_lval(redir_lval);
1039 vim_free(redir_lval);
1040 redir_lval = NULL;
1042 vim_free(redir_varname);
1043 redir_varname = NULL;
1046 # if defined(FEAT_MBYTE) || defined(PROTO)
1048 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1049 char_u *enc_from;
1050 char_u *enc_to;
1051 char_u *fname_from;
1052 char_u *fname_to;
1054 int err = FALSE;
1056 set_vim_var_string(VV_CC_FROM, enc_from, -1);
1057 set_vim_var_string(VV_CC_TO, enc_to, -1);
1058 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1059 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1060 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1061 err = TRUE;
1062 set_vim_var_string(VV_CC_FROM, NULL, -1);
1063 set_vim_var_string(VV_CC_TO, NULL, -1);
1064 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1065 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1067 if (err)
1068 return FAIL;
1069 return OK;
1071 # endif
1073 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1075 eval_printexpr(fname, args)
1076 char_u *fname;
1077 char_u *args;
1079 int err = FALSE;
1081 set_vim_var_string(VV_FNAME_IN, fname, -1);
1082 set_vim_var_string(VV_CMDARG, args, -1);
1083 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1084 err = TRUE;
1085 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1086 set_vim_var_string(VV_CMDARG, NULL, -1);
1088 if (err)
1090 mch_remove(fname);
1091 return FAIL;
1093 return OK;
1095 # endif
1097 # if defined(FEAT_DIFF) || defined(PROTO)
1098 void
1099 eval_diff(origfile, newfile, outfile)
1100 char_u *origfile;
1101 char_u *newfile;
1102 char_u *outfile;
1104 int err = FALSE;
1106 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1107 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1108 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1109 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1110 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1111 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1112 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1115 void
1116 eval_patch(origfile, difffile, outfile)
1117 char_u *origfile;
1118 char_u *difffile;
1119 char_u *outfile;
1121 int err;
1123 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1124 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1125 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1126 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1127 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1128 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1129 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1131 # endif
1134 * Top level evaluation function, returning a boolean.
1135 * Sets "error" to TRUE if there was an error.
1136 * Return TRUE or FALSE.
1139 eval_to_bool(arg, error, nextcmd, skip)
1140 char_u *arg;
1141 int *error;
1142 char_u **nextcmd;
1143 int skip; /* only parse, don't execute */
1145 typval_T tv;
1146 int retval = FALSE;
1148 if (skip)
1149 ++emsg_skip;
1150 if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1151 *error = TRUE;
1152 else
1154 *error = FALSE;
1155 if (!skip)
1157 retval = (get_tv_number_chk(&tv, error) != 0);
1158 clear_tv(&tv);
1161 if (skip)
1162 --emsg_skip;
1164 return retval;
1168 * Top level evaluation function, returning a string. If "skip" is TRUE,
1169 * only parsing to "nextcmd" is done, without reporting errors. Return
1170 * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1172 char_u *
1173 eval_to_string_skip(arg, nextcmd, skip)
1174 char_u *arg;
1175 char_u **nextcmd;
1176 int skip; /* only parse, don't execute */
1178 typval_T tv;
1179 char_u *retval;
1181 if (skip)
1182 ++emsg_skip;
1183 if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1184 retval = NULL;
1185 else
1187 retval = vim_strsave(get_tv_string(&tv));
1188 clear_tv(&tv);
1190 if (skip)
1191 --emsg_skip;
1193 return retval;
1197 * Skip over an expression at "*pp".
1198 * Return FAIL for an error, OK otherwise.
1201 skip_expr(pp)
1202 char_u **pp;
1204 typval_T rettv;
1206 *pp = skipwhite(*pp);
1207 return eval1(pp, &rettv, FALSE);
1211 * Top level evaluation function, returning a string.
1212 * Return pointer to allocated memory, or NULL for failure.
1214 char_u *
1215 eval_to_string(arg, nextcmd, dolist)
1216 char_u *arg;
1217 char_u **nextcmd;
1218 int dolist; /* turn List into sequence of lines */
1220 typval_T tv;
1221 char_u *retval;
1222 garray_T ga;
1224 if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1225 retval = NULL;
1226 else
1228 if (dolist && tv.v_type == VAR_LIST)
1230 ga_init2(&ga, (int)sizeof(char), 80);
1231 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1232 ga_append(&ga, NUL);
1233 retval = (char_u *)ga.ga_data;
1235 else
1236 retval = vim_strsave(get_tv_string(&tv));
1237 clear_tv(&tv);
1240 return retval;
1244 * Call eval_to_string() without using current local variables and using
1245 * textlock. When "use_sandbox" is TRUE use the sandbox.
1247 char_u *
1248 eval_to_string_safe(arg, nextcmd, use_sandbox)
1249 char_u *arg;
1250 char_u **nextcmd;
1251 int use_sandbox;
1253 char_u *retval;
1254 void *save_funccalp;
1256 save_funccalp = save_funccal();
1257 if (use_sandbox)
1258 ++sandbox;
1259 ++textlock;
1260 retval = eval_to_string(arg, nextcmd, FALSE);
1261 if (use_sandbox)
1262 --sandbox;
1263 --textlock;
1264 restore_funccal(save_funccalp);
1265 return retval;
1269 * Top level evaluation function, returning a number.
1270 * Evaluates "expr" silently.
1271 * Returns -1 for an error.
1274 eval_to_number(expr)
1275 char_u *expr;
1277 typval_T rettv;
1278 int retval;
1279 char_u *p = skipwhite(expr);
1281 ++emsg_off;
1283 if (eval1(&p, &rettv, TRUE) == FAIL)
1284 retval = -1;
1285 else
1287 retval = get_tv_number_chk(&rettv, NULL);
1288 clear_tv(&rettv);
1290 --emsg_off;
1292 return retval;
1296 * Prepare v: variable "idx" to be used.
1297 * Save the current typeval in "save_tv".
1298 * When not used yet add the variable to the v: hashtable.
1300 static void
1301 prepare_vimvar(idx, save_tv)
1302 int idx;
1303 typval_T *save_tv;
1305 *save_tv = vimvars[idx].vv_tv;
1306 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1307 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1311 * Restore v: variable "idx" to typeval "save_tv".
1312 * When no longer defined, remove the variable from the v: hashtable.
1314 static void
1315 restore_vimvar(idx, save_tv)
1316 int idx;
1317 typval_T *save_tv;
1319 hashitem_T *hi;
1321 vimvars[idx].vv_tv = *save_tv;
1322 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1324 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1325 if (HASHITEM_EMPTY(hi))
1326 EMSG2(_(e_intern2), "restore_vimvar()");
1327 else
1328 hash_remove(&vimvarht, hi);
1332 #if defined(FEAT_SPELL) || defined(PROTO)
1334 * Evaluate an expression to a list with suggestions.
1335 * For the "expr:" part of 'spellsuggest'.
1337 list_T *
1338 eval_spell_expr(badword, expr)
1339 char_u *badword;
1340 char_u *expr;
1342 typval_T save_val;
1343 typval_T rettv;
1344 list_T *list = NULL;
1345 char_u *p = skipwhite(expr);
1347 /* Set "v:val" to the bad word. */
1348 prepare_vimvar(VV_VAL, &save_val);
1349 vimvars[VV_VAL].vv_type = VAR_STRING;
1350 vimvars[VV_VAL].vv_str = badword;
1351 if (p_verbose == 0)
1352 ++emsg_off;
1354 if (eval1(&p, &rettv, TRUE) == OK)
1356 if (rettv.v_type != VAR_LIST)
1357 clear_tv(&rettv);
1358 else
1359 list = rettv.vval.v_list;
1362 if (p_verbose == 0)
1363 --emsg_off;
1364 restore_vimvar(VV_VAL, &save_val);
1366 return list;
1370 * "list" is supposed to contain two items: a word and a number. Return the
1371 * word in "pp" and the number as the return value.
1372 * Return -1 if anything isn't right.
1373 * Used to get the good word and score from the eval_spell_expr() result.
1376 get_spellword(list, pp)
1377 list_T *list;
1378 char_u **pp;
1380 listitem_T *li;
1382 li = list->lv_first;
1383 if (li == NULL)
1384 return -1;
1385 *pp = get_tv_string(&li->li_tv);
1387 li = li->li_next;
1388 if (li == NULL)
1389 return -1;
1390 return get_tv_number(&li->li_tv);
1392 #endif
1395 * Top level evaluation function.
1396 * Returns an allocated typval_T with the result.
1397 * Returns NULL when there is an error.
1399 typval_T *
1400 eval_expr(arg, nextcmd)
1401 char_u *arg;
1402 char_u **nextcmd;
1404 typval_T *tv;
1406 tv = (typval_T *)alloc(sizeof(typval_T));
1407 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1409 vim_free(tv);
1410 tv = NULL;
1413 return tv;
1417 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1418 || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1420 * Call some vimL function and return the result in "*rettv".
1421 * Uses argv[argc] for the function arguments.
1422 * Returns OK or FAIL.
1424 static int
1425 call_vim_function(func, argc, argv, safe, rettv)
1426 char_u *func;
1427 int argc;
1428 char_u **argv;
1429 int safe; /* use the sandbox */
1430 typval_T *rettv;
1432 typval_T *argvars;
1433 long n;
1434 int len;
1435 int i;
1436 int doesrange;
1437 void *save_funccalp = NULL;
1438 int ret;
1440 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1441 if (argvars == NULL)
1442 return FAIL;
1444 for (i = 0; i < argc; i++)
1446 /* Pass a NULL or empty argument as an empty string */
1447 if (argv[i] == NULL || *argv[i] == NUL)
1449 argvars[i].v_type = VAR_STRING;
1450 argvars[i].vval.v_string = (char_u *)"";
1451 continue;
1454 /* Recognize a number argument, the others must be strings. */
1455 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1456 if (len != 0 && len == (int)STRLEN(argv[i]))
1458 argvars[i].v_type = VAR_NUMBER;
1459 argvars[i].vval.v_number = n;
1461 else
1463 argvars[i].v_type = VAR_STRING;
1464 argvars[i].vval.v_string = argv[i];
1468 if (safe)
1470 save_funccalp = save_funccal();
1471 ++sandbox;
1474 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1475 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1476 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1477 &doesrange, TRUE, NULL);
1478 if (safe)
1480 --sandbox;
1481 restore_funccal(save_funccalp);
1483 vim_free(argvars);
1485 if (ret == FAIL)
1486 clear_tv(rettv);
1488 return ret;
1491 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1493 * Call vimL function "func" and return the result as a string.
1494 * Returns NULL when calling the function fails.
1495 * Uses argv[argc] for the function arguments.
1497 void *
1498 call_func_retstr(func, argc, argv, safe)
1499 char_u *func;
1500 int argc;
1501 char_u **argv;
1502 int safe; /* use the sandbox */
1504 typval_T rettv;
1505 char_u *retval;
1507 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1508 return NULL;
1510 retval = vim_strsave(get_tv_string(&rettv));
1511 clear_tv(&rettv);
1512 return retval;
1514 # endif
1516 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1518 * Call vimL function "func" and return the result as a number.
1519 * Returns -1 when calling the function fails.
1520 * Uses argv[argc] for the function arguments.
1522 long
1523 call_func_retnr(func, argc, argv, safe)
1524 char_u *func;
1525 int argc;
1526 char_u **argv;
1527 int safe; /* use the sandbox */
1529 typval_T rettv;
1530 long retval;
1532 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1533 return -1;
1535 retval = get_tv_number_chk(&rettv, NULL);
1536 clear_tv(&rettv);
1537 return retval;
1539 # endif
1542 * Call vimL function "func" and return the result as a list
1543 * Uses argv[argc] for the function arguments.
1545 void *
1546 call_func_retlist(func, argc, argv, safe)
1547 char_u *func;
1548 int argc;
1549 char_u **argv;
1550 int safe; /* use the sandbox */
1552 typval_T rettv;
1554 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1555 return NULL;
1557 if (rettv.v_type != VAR_LIST)
1559 clear_tv(&rettv);
1560 return NULL;
1563 return rettv.vval.v_list;
1565 #endif
1569 * Save the current function call pointer, and set it to NULL.
1570 * Used when executing autocommands and for ":source".
1572 void *
1573 save_funccal()
1575 funccall_T *fc = current_funccal;
1577 current_funccal = NULL;
1578 return (void *)fc;
1581 void
1582 restore_funccal(vfc)
1583 void *vfc;
1585 funccall_T *fc = (funccall_T *)vfc;
1587 current_funccal = fc;
1590 #if defined(FEAT_PROFILE) || defined(PROTO)
1592 * Prepare profiling for entering a child or something else that is not
1593 * counted for the script/function itself.
1594 * Should always be called in pair with prof_child_exit().
1596 void
1597 prof_child_enter(tm)
1598 proftime_T *tm; /* place to store waittime */
1600 funccall_T *fc = current_funccal;
1602 if (fc != NULL && fc->func->uf_profiling)
1603 profile_start(&fc->prof_child);
1604 script_prof_save(tm);
1608 * Take care of time spent in a child.
1609 * Should always be called after prof_child_enter().
1611 void
1612 prof_child_exit(tm)
1613 proftime_T *tm; /* where waittime was stored */
1615 funccall_T *fc = current_funccal;
1617 if (fc != NULL && fc->func->uf_profiling)
1619 profile_end(&fc->prof_child);
1620 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1621 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1622 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1624 script_prof_restore(tm);
1626 #endif
1629 #ifdef FEAT_FOLDING
1631 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1632 * it in "*cp". Doesn't give error messages.
1635 eval_foldexpr(arg, cp)
1636 char_u *arg;
1637 int *cp;
1639 typval_T tv;
1640 int retval;
1641 char_u *s;
1642 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1643 OPT_LOCAL);
1645 ++emsg_off;
1646 if (use_sandbox)
1647 ++sandbox;
1648 ++textlock;
1649 *cp = NUL;
1650 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1651 retval = 0;
1652 else
1654 /* If the result is a number, just return the number. */
1655 if (tv.v_type == VAR_NUMBER)
1656 retval = tv.vval.v_number;
1657 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1658 retval = 0;
1659 else
1661 /* If the result is a string, check if there is a non-digit before
1662 * the number. */
1663 s = tv.vval.v_string;
1664 if (!VIM_ISDIGIT(*s) && *s != '-')
1665 *cp = *s++;
1666 retval = atol((char *)s);
1668 clear_tv(&tv);
1670 --emsg_off;
1671 if (use_sandbox)
1672 --sandbox;
1673 --textlock;
1675 return retval;
1677 #endif
1680 * ":let" list all variable values
1681 * ":let var1 var2" list variable values
1682 * ":let var = expr" assignment command.
1683 * ":let var += expr" assignment command.
1684 * ":let var -= expr" assignment command.
1685 * ":let var .= expr" assignment command.
1686 * ":let [var1, var2] = expr" unpack list.
1688 void
1689 ex_let(eap)
1690 exarg_T *eap;
1692 char_u *arg = eap->arg;
1693 char_u *expr = NULL;
1694 typval_T rettv;
1695 int i;
1696 int var_count = 0;
1697 int semicolon = 0;
1698 char_u op[2];
1699 char_u *argend;
1700 int first = TRUE;
1702 argend = skip_var_list(arg, &var_count, &semicolon);
1703 if (argend == NULL)
1704 return;
1705 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1706 --argend;
1707 expr = vim_strchr(argend, '=');
1708 if (expr == NULL)
1711 * ":let" without "=": list variables
1713 if (*arg == '[')
1714 EMSG(_(e_invarg));
1715 else if (!ends_excmd(*arg))
1716 /* ":let var1 var2" */
1717 arg = list_arg_vars(eap, arg, &first);
1718 else if (!eap->skip)
1720 /* ":let" */
1721 list_glob_vars(&first);
1722 list_buf_vars(&first);
1723 list_win_vars(&first);
1724 #ifdef FEAT_WINDOWS
1725 list_tab_vars(&first);
1726 #endif
1727 list_script_vars(&first);
1728 list_func_vars(&first);
1729 list_vim_vars(&first);
1731 eap->nextcmd = check_nextcmd(arg);
1733 else
1735 op[0] = '=';
1736 op[1] = NUL;
1737 if (expr > argend)
1739 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1740 op[0] = expr[-1]; /* +=, -= or .= */
1742 expr = skipwhite(expr + 1);
1744 if (eap->skip)
1745 ++emsg_skip;
1746 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1747 if (eap->skip)
1749 if (i != FAIL)
1750 clear_tv(&rettv);
1751 --emsg_skip;
1753 else if (i != FAIL)
1755 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1756 op);
1757 clear_tv(&rettv);
1763 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1764 * Handles both "var" with any type and "[var, var; var]" with a list type.
1765 * When "nextchars" is not NULL it points to a string with characters that
1766 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1767 * or concatenate.
1768 * Returns OK or FAIL;
1770 static int
1771 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1772 char_u *arg_start;
1773 typval_T *tv;
1774 int copy; /* copy values from "tv", don't move */
1775 int semicolon; /* from skip_var_list() */
1776 int var_count; /* from skip_var_list() */
1777 char_u *nextchars;
1779 char_u *arg = arg_start;
1780 list_T *l;
1781 int i;
1782 listitem_T *item;
1783 typval_T ltv;
1785 if (*arg != '[')
1788 * ":let var = expr" or ":for var in list"
1790 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1791 return FAIL;
1792 return OK;
1796 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1798 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1800 EMSG(_(e_listreq));
1801 return FAIL;
1804 i = list_len(l);
1805 if (semicolon == 0 && var_count < i)
1807 EMSG(_("E687: Less targets than List items"));
1808 return FAIL;
1810 if (var_count - semicolon > i)
1812 EMSG(_("E688: More targets than List items"));
1813 return FAIL;
1816 item = l->lv_first;
1817 while (*arg != ']')
1819 arg = skipwhite(arg + 1);
1820 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1821 item = item->li_next;
1822 if (arg == NULL)
1823 return FAIL;
1825 arg = skipwhite(arg);
1826 if (*arg == ';')
1828 /* Put the rest of the list (may be empty) in the var after ';'.
1829 * Create a new list for this. */
1830 l = list_alloc();
1831 if (l == NULL)
1832 return FAIL;
1833 while (item != NULL)
1835 list_append_tv(l, &item->li_tv);
1836 item = item->li_next;
1839 ltv.v_type = VAR_LIST;
1840 ltv.v_lock = 0;
1841 ltv.vval.v_list = l;
1842 l->lv_refcount = 1;
1844 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1845 (char_u *)"]", nextchars);
1846 clear_tv(&ltv);
1847 if (arg == NULL)
1848 return FAIL;
1849 break;
1851 else if (*arg != ',' && *arg != ']')
1853 EMSG2(_(e_intern2), "ex_let_vars()");
1854 return FAIL;
1858 return OK;
1862 * Skip over assignable variable "var" or list of variables "[var, var]".
1863 * Used for ":let varvar = expr" and ":for varvar in expr".
1864 * For "[var, var]" increment "*var_count" for each variable.
1865 * for "[var, var; var]" set "semicolon".
1866 * Return NULL for an error.
1868 static char_u *
1869 skip_var_list(arg, var_count, semicolon)
1870 char_u *arg;
1871 int *var_count;
1872 int *semicolon;
1874 char_u *p, *s;
1876 if (*arg == '[')
1878 /* "[var, var]": find the matching ']'. */
1879 p = arg;
1880 for (;;)
1882 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
1883 s = skip_var_one(p);
1884 if (s == p)
1886 EMSG2(_(e_invarg2), p);
1887 return NULL;
1889 ++*var_count;
1891 p = skipwhite(s);
1892 if (*p == ']')
1893 break;
1894 else if (*p == ';')
1896 if (*semicolon == 1)
1898 EMSG(_("Double ; in list of variables"));
1899 return NULL;
1901 *semicolon = 1;
1903 else if (*p != ',')
1905 EMSG2(_(e_invarg2), p);
1906 return NULL;
1909 return p + 1;
1911 else
1912 return skip_var_one(arg);
1916 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
1917 * l[idx].
1919 static char_u *
1920 skip_var_one(arg)
1921 char_u *arg;
1923 if (*arg == '@' && arg[1] != NUL)
1924 return arg + 2;
1925 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
1926 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1930 * List variables for hashtab "ht" with prefix "prefix".
1931 * If "empty" is TRUE also list NULL strings as empty strings.
1933 static void
1934 list_hashtable_vars(ht, prefix, empty, first)
1935 hashtab_T *ht;
1936 char_u *prefix;
1937 int empty;
1938 int *first;
1940 hashitem_T *hi;
1941 dictitem_T *di;
1942 int todo;
1944 todo = (int)ht->ht_used;
1945 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
1947 if (!HASHITEM_EMPTY(hi))
1949 --todo;
1950 di = HI2DI(hi);
1951 if (empty || di->di_tv.v_type != VAR_STRING
1952 || di->di_tv.vval.v_string != NULL)
1953 list_one_var(di, prefix, first);
1959 * List global variables.
1961 static void
1962 list_glob_vars(first)
1963 int *first;
1965 list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
1969 * List buffer variables.
1971 static void
1972 list_buf_vars(first)
1973 int *first;
1975 char_u numbuf[NUMBUFLEN];
1977 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:",
1978 TRUE, first);
1980 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
1981 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
1982 numbuf, first);
1986 * List window variables.
1988 static void
1989 list_win_vars(first)
1990 int *first;
1992 list_hashtable_vars(&curwin->w_vars.dv_hashtab,
1993 (char_u *)"w:", TRUE, first);
1996 #ifdef FEAT_WINDOWS
1998 * List tab page variables.
2000 static void
2001 list_tab_vars(first)
2002 int *first;
2004 list_hashtable_vars(&curtab->tp_vars.dv_hashtab,
2005 (char_u *)"t:", TRUE, first);
2007 #endif
2010 * List Vim variables.
2012 static void
2013 list_vim_vars(first)
2014 int *first;
2016 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2020 * List script-local variables, if there is a script.
2022 static void
2023 list_script_vars(first)
2024 int *first;
2026 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2027 list_hashtable_vars(&SCRIPT_VARS(current_SID),
2028 (char_u *)"s:", FALSE, first);
2032 * List function variables, if there is a function.
2034 static void
2035 list_func_vars(first)
2036 int *first;
2038 if (current_funccal != NULL)
2039 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2040 (char_u *)"l:", FALSE, first);
2044 * List variables in "arg".
2046 static char_u *
2047 list_arg_vars(eap, arg, first)
2048 exarg_T *eap;
2049 char_u *arg;
2050 int *first;
2052 int error = FALSE;
2053 int len;
2054 char_u *name;
2055 char_u *name_start;
2056 char_u *arg_subsc;
2057 char_u *tofree;
2058 typval_T tv;
2060 while (!ends_excmd(*arg) && !got_int)
2062 if (error || eap->skip)
2064 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2065 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2067 emsg_severe = TRUE;
2068 EMSG(_(e_trailing));
2069 break;
2072 else
2074 /* get_name_len() takes care of expanding curly braces */
2075 name_start = name = arg;
2076 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2077 if (len <= 0)
2079 /* This is mainly to keep test 49 working: when expanding
2080 * curly braces fails overrule the exception error message. */
2081 if (len < 0 && !aborting())
2083 emsg_severe = TRUE;
2084 EMSG2(_(e_invarg2), arg);
2085 break;
2087 error = TRUE;
2089 else
2091 if (tofree != NULL)
2092 name = tofree;
2093 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2094 error = TRUE;
2095 else
2097 /* handle d.key, l[idx], f(expr) */
2098 arg_subsc = arg;
2099 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2100 error = TRUE;
2101 else
2103 if (arg == arg_subsc && len == 2 && name[1] == ':')
2105 switch (*name)
2107 case 'g': list_glob_vars(first); break;
2108 case 'b': list_buf_vars(first); break;
2109 case 'w': list_win_vars(first); break;
2110 #ifdef FEAT_WINDOWS
2111 case 't': list_tab_vars(first); break;
2112 #endif
2113 case 'v': list_vim_vars(first); break;
2114 case 's': list_script_vars(first); break;
2115 case 'l': list_func_vars(first); break;
2116 default:
2117 EMSG2(_("E738: Can't list variables for %s"), name);
2120 else
2122 char_u numbuf[NUMBUFLEN];
2123 char_u *tf;
2124 int c;
2125 char_u *s;
2127 s = echo_string(&tv, &tf, numbuf, 0);
2128 c = *arg;
2129 *arg = NUL;
2130 list_one_var_a((char_u *)"",
2131 arg == arg_subsc ? name : name_start,
2132 tv.v_type,
2133 s == NULL ? (char_u *)"" : s,
2134 first);
2135 *arg = c;
2136 vim_free(tf);
2138 clear_tv(&tv);
2143 vim_free(tofree);
2146 arg = skipwhite(arg);
2149 return arg;
2153 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2154 * Returns a pointer to the char just after the var name.
2155 * Returns NULL if there is an error.
2157 static char_u *
2158 ex_let_one(arg, tv, copy, endchars, op)
2159 char_u *arg; /* points to variable name */
2160 typval_T *tv; /* value to assign to variable */
2161 int copy; /* copy value from "tv" */
2162 char_u *endchars; /* valid chars after variable name or NULL */
2163 char_u *op; /* "+", "-", "." or NULL*/
2165 int c1;
2166 char_u *name;
2167 char_u *p;
2168 char_u *arg_end = NULL;
2169 int len;
2170 int opt_flags;
2171 char_u *tofree = NULL;
2174 * ":let $VAR = expr": Set environment variable.
2176 if (*arg == '$')
2178 /* Find the end of the name. */
2179 ++arg;
2180 name = arg;
2181 len = get_env_len(&arg);
2182 if (len == 0)
2183 EMSG2(_(e_invarg2), name - 1);
2184 else
2186 if (op != NULL && (*op == '+' || *op == '-'))
2187 EMSG2(_(e_letwrong), op);
2188 else if (endchars != NULL
2189 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2190 EMSG(_(e_letunexp));
2191 else
2193 c1 = name[len];
2194 name[len] = NUL;
2195 p = get_tv_string_chk(tv);
2196 if (p != NULL && op != NULL && *op == '.')
2198 int mustfree = FALSE;
2199 char_u *s = vim_getenv(name, &mustfree);
2201 if (s != NULL)
2203 p = tofree = concat_str(s, p);
2204 if (mustfree)
2205 vim_free(s);
2208 if (p != NULL)
2210 vim_setenv(name, p);
2211 if (STRICMP(name, "HOME") == 0)
2212 init_homedir();
2213 else if (didset_vim && STRICMP(name, "VIM") == 0)
2214 didset_vim = FALSE;
2215 else if (didset_vimruntime
2216 && STRICMP(name, "VIMRUNTIME") == 0)
2217 didset_vimruntime = FALSE;
2218 arg_end = arg;
2220 name[len] = c1;
2221 vim_free(tofree);
2227 * ":let &option = expr": Set option value.
2228 * ":let &l:option = expr": Set local option value.
2229 * ":let &g:option = expr": Set global option value.
2231 else if (*arg == '&')
2233 /* Find the end of the name. */
2234 p = find_option_end(&arg, &opt_flags);
2235 if (p == NULL || (endchars != NULL
2236 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2237 EMSG(_(e_letunexp));
2238 else
2240 long n;
2241 int opt_type;
2242 long numval;
2243 char_u *stringval = NULL;
2244 char_u *s;
2246 c1 = *p;
2247 *p = NUL;
2249 n = get_tv_number(tv);
2250 s = get_tv_string_chk(tv); /* != NULL if number or string */
2251 if (s != NULL && op != NULL && *op != '=')
2253 opt_type = get_option_value(arg, &numval,
2254 &stringval, opt_flags);
2255 if ((opt_type == 1 && *op == '.')
2256 || (opt_type == 0 && *op != '.'))
2257 EMSG2(_(e_letwrong), op);
2258 else
2260 if (opt_type == 1) /* number */
2262 if (*op == '+')
2263 n = numval + n;
2264 else
2265 n = numval - n;
2267 else if (opt_type == 0 && stringval != NULL) /* string */
2269 s = concat_str(stringval, s);
2270 vim_free(stringval);
2271 stringval = s;
2275 if (s != NULL)
2277 set_option_value(arg, n, s, opt_flags);
2278 arg_end = p;
2280 *p = c1;
2281 vim_free(stringval);
2286 * ":let @r = expr": Set register contents.
2288 else if (*arg == '@')
2290 ++arg;
2291 if (op != NULL && (*op == '+' || *op == '-'))
2292 EMSG2(_(e_letwrong), op);
2293 else if (endchars != NULL
2294 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2295 EMSG(_(e_letunexp));
2296 else
2298 char_u *ptofree = NULL;
2299 char_u *s;
2301 p = get_tv_string_chk(tv);
2302 if (p != NULL && op != NULL && *op == '.')
2304 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2305 if (s != NULL)
2307 p = ptofree = concat_str(s, p);
2308 vim_free(s);
2311 if (p != NULL)
2313 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2314 arg_end = arg + 1;
2316 vim_free(ptofree);
2321 * ":let var = expr": Set internal variable.
2322 * ":let {expr} = expr": Idem, name made with curly braces
2324 else if (eval_isnamec1(*arg) || *arg == '{')
2326 lval_T lv;
2328 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2329 if (p != NULL && lv.ll_name != NULL)
2331 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2332 EMSG(_(e_letunexp));
2333 else
2335 set_var_lval(&lv, p, tv, copy, op);
2336 arg_end = p;
2339 clear_lval(&lv);
2342 else
2343 EMSG2(_(e_invarg2), arg);
2345 return arg_end;
2349 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2351 static int
2352 check_changedtick(arg)
2353 char_u *arg;
2355 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2357 EMSG2(_(e_readonlyvar), arg);
2358 return TRUE;
2360 return FALSE;
2364 * Get an lval: variable, Dict item or List item that can be assigned a value
2365 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2366 * "name.key", "name.key[expr]" etc.
2367 * Indexing only works if "name" is an existing List or Dictionary.
2368 * "name" points to the start of the name.
2369 * If "rettv" is not NULL it points to the value to be assigned.
2370 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2371 * wrong; must end in space or cmd separator.
2373 * Returns a pointer to just after the name, including indexes.
2374 * When an evaluation error occurs "lp->ll_name" is NULL;
2375 * Returns NULL for a parsing error. Still need to free items in "lp"!
2377 static char_u *
2378 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2379 char_u *name;
2380 typval_T *rettv;
2381 lval_T *lp;
2382 int unlet;
2383 int skip;
2384 int quiet; /* don't give error messages */
2385 int fne_flags; /* flags for find_name_end() */
2387 char_u *p;
2388 char_u *expr_start, *expr_end;
2389 int cc;
2390 dictitem_T *v;
2391 typval_T var1;
2392 typval_T var2;
2393 int empty1 = FALSE;
2394 listitem_T *ni;
2395 char_u *key = NULL;
2396 int len;
2397 hashtab_T *ht;
2399 /* Clear everything in "lp". */
2400 vim_memset(lp, 0, sizeof(lval_T));
2402 if (skip)
2404 /* When skipping just find the end of the name. */
2405 lp->ll_name = name;
2406 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2409 /* Find the end of the name. */
2410 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2411 if (expr_start != NULL)
2413 /* Don't expand the name when we already know there is an error. */
2414 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2415 && *p != '[' && *p != '.')
2417 EMSG(_(e_trailing));
2418 return NULL;
2421 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2422 if (lp->ll_exp_name == NULL)
2424 /* Report an invalid expression in braces, unless the
2425 * expression evaluation has been cancelled due to an
2426 * aborting error, an interrupt, or an exception. */
2427 if (!aborting() && !quiet)
2429 emsg_severe = TRUE;
2430 EMSG2(_(e_invarg2), name);
2431 return NULL;
2434 lp->ll_name = lp->ll_exp_name;
2436 else
2437 lp->ll_name = name;
2439 /* Without [idx] or .key we are done. */
2440 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2441 return p;
2443 cc = *p;
2444 *p = NUL;
2445 v = find_var(lp->ll_name, &ht);
2446 if (v == NULL && !quiet)
2447 EMSG2(_(e_undefvar), lp->ll_name);
2448 *p = cc;
2449 if (v == NULL)
2450 return NULL;
2453 * Loop until no more [idx] or .key is following.
2455 lp->ll_tv = &v->di_tv;
2456 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2458 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2459 && !(lp->ll_tv->v_type == VAR_DICT
2460 && lp->ll_tv->vval.v_dict != NULL))
2462 if (!quiet)
2463 EMSG(_("E689: Can only index a List or Dictionary"));
2464 return NULL;
2466 if (lp->ll_range)
2468 if (!quiet)
2469 EMSG(_("E708: [:] must come last"));
2470 return NULL;
2473 len = -1;
2474 if (*p == '.')
2476 key = p + 1;
2477 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2479 if (len == 0)
2481 if (!quiet)
2482 EMSG(_(e_emptykey));
2483 return NULL;
2485 p = key + len;
2487 else
2489 /* Get the index [expr] or the first index [expr: ]. */
2490 p = skipwhite(p + 1);
2491 if (*p == ':')
2492 empty1 = TRUE;
2493 else
2495 empty1 = FALSE;
2496 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2497 return NULL;
2498 if (get_tv_string_chk(&var1) == NULL)
2500 /* not a number or string */
2501 clear_tv(&var1);
2502 return NULL;
2506 /* Optionally get the second index [ :expr]. */
2507 if (*p == ':')
2509 if (lp->ll_tv->v_type == VAR_DICT)
2511 if (!quiet)
2512 EMSG(_(e_dictrange));
2513 if (!empty1)
2514 clear_tv(&var1);
2515 return NULL;
2517 if (rettv != NULL && (rettv->v_type != VAR_LIST
2518 || rettv->vval.v_list == NULL))
2520 if (!quiet)
2521 EMSG(_("E709: [:] requires a List value"));
2522 if (!empty1)
2523 clear_tv(&var1);
2524 return NULL;
2526 p = skipwhite(p + 1);
2527 if (*p == ']')
2528 lp->ll_empty2 = TRUE;
2529 else
2531 lp->ll_empty2 = FALSE;
2532 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2534 if (!empty1)
2535 clear_tv(&var1);
2536 return NULL;
2538 if (get_tv_string_chk(&var2) == NULL)
2540 /* not a number or string */
2541 if (!empty1)
2542 clear_tv(&var1);
2543 clear_tv(&var2);
2544 return NULL;
2547 lp->ll_range = TRUE;
2549 else
2550 lp->ll_range = FALSE;
2552 if (*p != ']')
2554 if (!quiet)
2555 EMSG(_(e_missbrac));
2556 if (!empty1)
2557 clear_tv(&var1);
2558 if (lp->ll_range && !lp->ll_empty2)
2559 clear_tv(&var2);
2560 return NULL;
2563 /* Skip to past ']'. */
2564 ++p;
2567 if (lp->ll_tv->v_type == VAR_DICT)
2569 if (len == -1)
2571 /* "[key]": get key from "var1" */
2572 key = get_tv_string(&var1); /* is number or string */
2573 if (*key == NUL)
2575 if (!quiet)
2576 EMSG(_(e_emptykey));
2577 clear_tv(&var1);
2578 return NULL;
2581 lp->ll_list = NULL;
2582 lp->ll_dict = lp->ll_tv->vval.v_dict;
2583 lp->ll_di = dict_find(lp->ll_dict, key, len);
2584 if (lp->ll_di == NULL)
2586 /* Key does not exist in dict: may need to add it. */
2587 if (*p == '[' || *p == '.' || unlet)
2589 if (!quiet)
2590 EMSG2(_(e_dictkey), key);
2591 if (len == -1)
2592 clear_tv(&var1);
2593 return NULL;
2595 if (len == -1)
2596 lp->ll_newkey = vim_strsave(key);
2597 else
2598 lp->ll_newkey = vim_strnsave(key, len);
2599 if (len == -1)
2600 clear_tv(&var1);
2601 if (lp->ll_newkey == NULL)
2602 p = NULL;
2603 break;
2605 if (len == -1)
2606 clear_tv(&var1);
2607 lp->ll_tv = &lp->ll_di->di_tv;
2609 else
2612 * Get the number and item for the only or first index of the List.
2614 if (empty1)
2615 lp->ll_n1 = 0;
2616 else
2618 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2619 clear_tv(&var1);
2621 lp->ll_dict = NULL;
2622 lp->ll_list = lp->ll_tv->vval.v_list;
2623 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2624 if (lp->ll_li == NULL)
2626 if (lp->ll_n1 < 0)
2628 lp->ll_n1 = 0;
2629 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2632 if (lp->ll_li == NULL)
2634 if (lp->ll_range && !lp->ll_empty2)
2635 clear_tv(&var2);
2636 return NULL;
2640 * May need to find the item or absolute index for the second
2641 * index of a range.
2642 * When no index given: "lp->ll_empty2" is TRUE.
2643 * Otherwise "lp->ll_n2" is set to the second index.
2645 if (lp->ll_range && !lp->ll_empty2)
2647 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2648 clear_tv(&var2);
2649 if (lp->ll_n2 < 0)
2651 ni = list_find(lp->ll_list, lp->ll_n2);
2652 if (ni == NULL)
2653 return NULL;
2654 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2657 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2658 if (lp->ll_n1 < 0)
2659 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2660 if (lp->ll_n2 < lp->ll_n1)
2661 return NULL;
2664 lp->ll_tv = &lp->ll_li->li_tv;
2668 return p;
2672 * Clear lval "lp" that was filled by get_lval().
2674 static void
2675 clear_lval(lp)
2676 lval_T *lp;
2678 vim_free(lp->ll_exp_name);
2679 vim_free(lp->ll_newkey);
2683 * Set a variable that was parsed by get_lval() to "rettv".
2684 * "endp" points to just after the parsed name.
2685 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2687 static void
2688 set_var_lval(lp, endp, rettv, copy, op)
2689 lval_T *lp;
2690 char_u *endp;
2691 typval_T *rettv;
2692 int copy;
2693 char_u *op;
2695 int cc;
2696 listitem_T *ri;
2697 dictitem_T *di;
2699 if (lp->ll_tv == NULL)
2701 if (!check_changedtick(lp->ll_name))
2703 cc = *endp;
2704 *endp = NUL;
2705 if (op != NULL && *op != '=')
2707 typval_T tv;
2709 /* handle +=, -= and .= */
2710 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2711 &tv, TRUE) == OK)
2713 if (tv_op(&tv, rettv, op) == OK)
2714 set_var(lp->ll_name, &tv, FALSE);
2715 clear_tv(&tv);
2718 else
2719 set_var(lp->ll_name, rettv, copy);
2720 *endp = cc;
2723 else if (tv_check_lock(lp->ll_newkey == NULL
2724 ? lp->ll_tv->v_lock
2725 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2727 else if (lp->ll_range)
2730 * Assign the List values to the list items.
2732 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2734 if (op != NULL && *op != '=')
2735 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2736 else
2738 clear_tv(&lp->ll_li->li_tv);
2739 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2741 ri = ri->li_next;
2742 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2743 break;
2744 if (lp->ll_li->li_next == NULL)
2746 /* Need to add an empty item. */
2747 if (list_append_number(lp->ll_list, 0) == FAIL)
2749 ri = NULL;
2750 break;
2753 lp->ll_li = lp->ll_li->li_next;
2754 ++lp->ll_n1;
2756 if (ri != NULL)
2757 EMSG(_("E710: List value has more items than target"));
2758 else if (lp->ll_empty2
2759 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2760 : lp->ll_n1 != lp->ll_n2)
2761 EMSG(_("E711: List value has not enough items"));
2763 else
2766 * Assign to a List or Dictionary item.
2768 if (lp->ll_newkey != NULL)
2770 if (op != NULL && *op != '=')
2772 EMSG2(_(e_letwrong), op);
2773 return;
2776 /* Need to add an item to the Dictionary. */
2777 di = dictitem_alloc(lp->ll_newkey);
2778 if (di == NULL)
2779 return;
2780 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2782 vim_free(di);
2783 return;
2785 lp->ll_tv = &di->di_tv;
2787 else if (op != NULL && *op != '=')
2789 tv_op(lp->ll_tv, rettv, op);
2790 return;
2792 else
2793 clear_tv(lp->ll_tv);
2796 * Assign the value to the variable or list item.
2798 if (copy)
2799 copy_tv(rettv, lp->ll_tv);
2800 else
2802 *lp->ll_tv = *rettv;
2803 lp->ll_tv->v_lock = 0;
2804 init_tv(rettv);
2810 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2811 * Returns OK or FAIL.
2813 static int
2814 tv_op(tv1, tv2, op)
2815 typval_T *tv1;
2816 typval_T *tv2;
2817 char_u *op;
2819 long n;
2820 char_u numbuf[NUMBUFLEN];
2821 char_u *s;
2823 /* Can't do anything with a Funcref or a Dict on the right. */
2824 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2826 switch (tv1->v_type)
2828 case VAR_DICT:
2829 case VAR_FUNC:
2830 break;
2832 case VAR_LIST:
2833 if (*op != '+' || tv2->v_type != VAR_LIST)
2834 break;
2835 /* List += List */
2836 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2837 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2838 return OK;
2840 case VAR_NUMBER:
2841 case VAR_STRING:
2842 if (tv2->v_type == VAR_LIST)
2843 break;
2844 if (*op == '+' || *op == '-')
2846 /* nr += nr or nr -= nr*/
2847 n = get_tv_number(tv1);
2848 if (*op == '+')
2849 n += get_tv_number(tv2);
2850 else
2851 n -= get_tv_number(tv2);
2852 clear_tv(tv1);
2853 tv1->v_type = VAR_NUMBER;
2854 tv1->vval.v_number = n;
2856 else
2858 /* str .= str */
2859 s = get_tv_string(tv1);
2860 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2861 clear_tv(tv1);
2862 tv1->v_type = VAR_STRING;
2863 tv1->vval.v_string = s;
2865 return OK;
2869 EMSG2(_(e_letwrong), op);
2870 return FAIL;
2874 * Add a watcher to a list.
2876 static void
2877 list_add_watch(l, lw)
2878 list_T *l;
2879 listwatch_T *lw;
2881 lw->lw_next = l->lv_watch;
2882 l->lv_watch = lw;
2886 * Remove a watcher from a list.
2887 * No warning when it isn't found...
2889 static void
2890 list_rem_watch(l, lwrem)
2891 list_T *l;
2892 listwatch_T *lwrem;
2894 listwatch_T *lw, **lwp;
2896 lwp = &l->lv_watch;
2897 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2899 if (lw == lwrem)
2901 *lwp = lw->lw_next;
2902 break;
2904 lwp = &lw->lw_next;
2909 * Just before removing an item from a list: advance watchers to the next
2910 * item.
2912 static void
2913 list_fix_watch(l, item)
2914 list_T *l;
2915 listitem_T *item;
2917 listwatch_T *lw;
2919 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2920 if (lw->lw_item == item)
2921 lw->lw_item = item->li_next;
2925 * Evaluate the expression used in a ":for var in expr" command.
2926 * "arg" points to "var".
2927 * Set "*errp" to TRUE for an error, FALSE otherwise;
2928 * Return a pointer that holds the info. Null when there is an error.
2930 void *
2931 eval_for_line(arg, errp, nextcmdp, skip)
2932 char_u *arg;
2933 int *errp;
2934 char_u **nextcmdp;
2935 int skip;
2937 forinfo_T *fi;
2938 char_u *expr;
2939 typval_T tv;
2940 list_T *l;
2942 *errp = TRUE; /* default: there is an error */
2944 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
2945 if (fi == NULL)
2946 return NULL;
2948 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
2949 if (expr == NULL)
2950 return fi;
2952 expr = skipwhite(expr);
2953 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
2955 EMSG(_("E690: Missing \"in\" after :for"));
2956 return fi;
2959 if (skip)
2960 ++emsg_skip;
2961 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
2963 *errp = FALSE;
2964 if (!skip)
2966 l = tv.vval.v_list;
2967 if (tv.v_type != VAR_LIST || l == NULL)
2969 EMSG(_(e_listreq));
2970 clear_tv(&tv);
2972 else
2974 /* No need to increment the refcount, it's already set for the
2975 * list being used in "tv". */
2976 fi->fi_list = l;
2977 list_add_watch(l, &fi->fi_lw);
2978 fi->fi_lw.lw_item = l->lv_first;
2982 if (skip)
2983 --emsg_skip;
2985 return fi;
2989 * Use the first item in a ":for" list. Advance to the next.
2990 * Assign the values to the variable (list). "arg" points to the first one.
2991 * Return TRUE when a valid item was found, FALSE when at end of list or
2992 * something wrong.
2995 next_for_item(fi_void, arg)
2996 void *fi_void;
2997 char_u *arg;
2999 forinfo_T *fi = (forinfo_T *)fi_void;
3000 int result;
3001 listitem_T *item;
3003 item = fi->fi_lw.lw_item;
3004 if (item == NULL)
3005 result = FALSE;
3006 else
3008 fi->fi_lw.lw_item = item->li_next;
3009 result = (ex_let_vars(arg, &item->li_tv, TRUE,
3010 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3012 return result;
3016 * Free the structure used to store info used by ":for".
3018 void
3019 free_for_info(fi_void)
3020 void *fi_void;
3022 forinfo_T *fi = (forinfo_T *)fi_void;
3024 if (fi != NULL && fi->fi_list != NULL)
3026 list_rem_watch(fi->fi_list, &fi->fi_lw);
3027 list_unref(fi->fi_list);
3029 vim_free(fi);
3032 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3034 void
3035 set_context_for_expression(xp, arg, cmdidx)
3036 expand_T *xp;
3037 char_u *arg;
3038 cmdidx_T cmdidx;
3040 int got_eq = FALSE;
3041 int c;
3042 char_u *p;
3044 if (cmdidx == CMD_let)
3046 xp->xp_context = EXPAND_USER_VARS;
3047 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3049 /* ":let var1 var2 ...": find last space. */
3050 for (p = arg + STRLEN(arg); p >= arg; )
3052 xp->xp_pattern = p;
3053 mb_ptr_back(arg, p);
3054 if (vim_iswhite(*p))
3055 break;
3057 return;
3060 else
3061 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3062 : EXPAND_EXPRESSION;
3063 while ((xp->xp_pattern = vim_strpbrk(arg,
3064 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3066 c = *xp->xp_pattern;
3067 if (c == '&')
3069 c = xp->xp_pattern[1];
3070 if (c == '&')
3072 ++xp->xp_pattern;
3073 xp->xp_context = cmdidx != CMD_let || got_eq
3074 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3076 else if (c != ' ')
3078 xp->xp_context = EXPAND_SETTINGS;
3079 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3080 xp->xp_pattern += 2;
3084 else if (c == '$')
3086 /* environment variable */
3087 xp->xp_context = EXPAND_ENV_VARS;
3089 else if (c == '=')
3091 got_eq = TRUE;
3092 xp->xp_context = EXPAND_EXPRESSION;
3094 else if (c == '<'
3095 && xp->xp_context == EXPAND_FUNCTIONS
3096 && vim_strchr(xp->xp_pattern, '(') == NULL)
3098 /* Function name can start with "<SNR>" */
3099 break;
3101 else if (cmdidx != CMD_let || got_eq)
3103 if (c == '"') /* string */
3105 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3106 if (c == '\\' && xp->xp_pattern[1] != NUL)
3107 ++xp->xp_pattern;
3108 xp->xp_context = EXPAND_NOTHING;
3110 else if (c == '\'') /* literal string */
3112 /* Trick: '' is like stopping and starting a literal string. */
3113 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3114 /* skip */ ;
3115 xp->xp_context = EXPAND_NOTHING;
3117 else if (c == '|')
3119 if (xp->xp_pattern[1] == '|')
3121 ++xp->xp_pattern;
3122 xp->xp_context = EXPAND_EXPRESSION;
3124 else
3125 xp->xp_context = EXPAND_COMMANDS;
3127 else
3128 xp->xp_context = EXPAND_EXPRESSION;
3130 else
3131 /* Doesn't look like something valid, expand as an expression
3132 * anyway. */
3133 xp->xp_context = EXPAND_EXPRESSION;
3134 arg = xp->xp_pattern;
3135 if (*arg != NUL)
3136 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3137 /* skip */ ;
3139 xp->xp_pattern = arg;
3142 #endif /* FEAT_CMDL_COMPL */
3145 * ":1,25call func(arg1, arg2)" function call.
3147 void
3148 ex_call(eap)
3149 exarg_T *eap;
3151 char_u *arg = eap->arg;
3152 char_u *startarg;
3153 char_u *name;
3154 char_u *tofree;
3155 int len;
3156 typval_T rettv;
3157 linenr_T lnum;
3158 int doesrange;
3159 int failed = FALSE;
3160 funcdict_T fudi;
3162 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3163 if (fudi.fd_newkey != NULL)
3165 /* Still need to give an error message for missing key. */
3166 EMSG2(_(e_dictkey), fudi.fd_newkey);
3167 vim_free(fudi.fd_newkey);
3169 if (tofree == NULL)
3170 return;
3172 /* Increase refcount on dictionary, it could get deleted when evaluating
3173 * the arguments. */
3174 if (fudi.fd_dict != NULL)
3175 ++fudi.fd_dict->dv_refcount;
3177 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3178 len = (int)STRLEN(tofree);
3179 name = deref_func_name(tofree, &len);
3181 /* Skip white space to allow ":call func ()". Not good, but required for
3182 * backward compatibility. */
3183 startarg = skipwhite(arg);
3184 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3186 if (*startarg != '(')
3188 EMSG2(_("E107: Missing braces: %s"), eap->arg);
3189 goto end;
3193 * When skipping, evaluate the function once, to find the end of the
3194 * arguments.
3195 * When the function takes a range, this is discovered after the first
3196 * call, and the loop is broken.
3198 if (eap->skip)
3200 ++emsg_skip;
3201 lnum = eap->line2; /* do it once, also with an invalid range */
3203 else
3204 lnum = eap->line1;
3205 for ( ; lnum <= eap->line2; ++lnum)
3207 if (!eap->skip && eap->addr_count > 0)
3209 curwin->w_cursor.lnum = lnum;
3210 curwin->w_cursor.col = 0;
3212 arg = startarg;
3213 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3214 eap->line1, eap->line2, &doesrange,
3215 !eap->skip, fudi.fd_dict) == FAIL)
3217 failed = TRUE;
3218 break;
3221 /* Handle a function returning a Funcref, Dictionary or List. */
3222 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3224 failed = TRUE;
3225 break;
3228 clear_tv(&rettv);
3229 if (doesrange || eap->skip)
3230 break;
3232 /* Stop when immediately aborting on error, or when an interrupt
3233 * occurred or an exception was thrown but not caught.
3234 * get_func_tv() returned OK, so that the check for trailing
3235 * characters below is executed. */
3236 if (aborting())
3237 break;
3239 if (eap->skip)
3240 --emsg_skip;
3242 if (!failed)
3244 /* Check for trailing illegal characters and a following command. */
3245 if (!ends_excmd(*arg))
3247 emsg_severe = TRUE;
3248 EMSG(_(e_trailing));
3250 else
3251 eap->nextcmd = check_nextcmd(arg);
3254 end:
3255 dict_unref(fudi.fd_dict);
3256 vim_free(tofree);
3260 * ":unlet[!] var1 ... " command.
3262 void
3263 ex_unlet(eap)
3264 exarg_T *eap;
3266 ex_unletlock(eap, eap->arg, 0);
3270 * ":lockvar" and ":unlockvar" commands
3272 void
3273 ex_lockvar(eap)
3274 exarg_T *eap;
3276 char_u *arg = eap->arg;
3277 int deep = 2;
3279 if (eap->forceit)
3280 deep = -1;
3281 else if (vim_isdigit(*arg))
3283 deep = getdigits(&arg);
3284 arg = skipwhite(arg);
3287 ex_unletlock(eap, arg, deep);
3291 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3293 static void
3294 ex_unletlock(eap, argstart, deep)
3295 exarg_T *eap;
3296 char_u *argstart;
3297 int deep;
3299 char_u *arg = argstart;
3300 char_u *name_end;
3301 int error = FALSE;
3302 lval_T lv;
3306 /* Parse the name and find the end. */
3307 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3308 FNE_CHECK_START);
3309 if (lv.ll_name == NULL)
3310 error = TRUE; /* error but continue parsing */
3311 if (name_end == NULL || (!vim_iswhite(*name_end)
3312 && !ends_excmd(*name_end)))
3314 if (name_end != NULL)
3316 emsg_severe = TRUE;
3317 EMSG(_(e_trailing));
3319 if (!(eap->skip || error))
3320 clear_lval(&lv);
3321 break;
3324 if (!error && !eap->skip)
3326 if (eap->cmdidx == CMD_unlet)
3328 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3329 error = TRUE;
3331 else
3333 if (do_lock_var(&lv, name_end, deep,
3334 eap->cmdidx == CMD_lockvar) == FAIL)
3335 error = TRUE;
3339 if (!eap->skip)
3340 clear_lval(&lv);
3342 arg = skipwhite(name_end);
3343 } while (!ends_excmd(*arg));
3345 eap->nextcmd = check_nextcmd(arg);
3348 static int
3349 do_unlet_var(lp, name_end, forceit)
3350 lval_T *lp;
3351 char_u *name_end;
3352 int forceit;
3354 int ret = OK;
3355 int cc;
3357 if (lp->ll_tv == NULL)
3359 cc = *name_end;
3360 *name_end = NUL;
3362 /* Normal name or expanded name. */
3363 if (check_changedtick(lp->ll_name))
3364 ret = FAIL;
3365 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3366 ret = FAIL;
3367 *name_end = cc;
3369 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3370 return FAIL;
3371 else if (lp->ll_range)
3373 listitem_T *li;
3375 /* Delete a range of List items. */
3376 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3378 li = lp->ll_li->li_next;
3379 listitem_remove(lp->ll_list, lp->ll_li);
3380 lp->ll_li = li;
3381 ++lp->ll_n1;
3384 else
3386 if (lp->ll_list != NULL)
3387 /* unlet a List item. */
3388 listitem_remove(lp->ll_list, lp->ll_li);
3389 else
3390 /* unlet a Dictionary item. */
3391 dictitem_remove(lp->ll_dict, lp->ll_di);
3394 return ret;
3398 * "unlet" a variable. Return OK if it existed, FAIL if not.
3399 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3402 do_unlet(name, forceit)
3403 char_u *name;
3404 int forceit;
3406 hashtab_T *ht;
3407 hashitem_T *hi;
3408 char_u *varname;
3410 ht = find_var_ht(name, &varname);
3411 if (ht != NULL && *varname != NUL)
3413 hi = hash_find(ht, varname);
3414 if (!HASHITEM_EMPTY(hi))
3416 if (var_check_fixed(HI2DI(hi)->di_flags, name))
3417 return FAIL;
3418 if (var_check_ro(HI2DI(hi)->di_flags, name))
3419 return FAIL;
3420 delete_var(ht, hi);
3421 return OK;
3424 if (forceit)
3425 return OK;
3426 EMSG2(_("E108: No such variable: \"%s\""), name);
3427 return FAIL;
3431 * Lock or unlock variable indicated by "lp".
3432 * "deep" is the levels to go (-1 for unlimited);
3433 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3435 static int
3436 do_lock_var(lp, name_end, deep, lock)
3437 lval_T *lp;
3438 char_u *name_end;
3439 int deep;
3440 int lock;
3442 int ret = OK;
3443 int cc;
3444 dictitem_T *di;
3446 if (deep == 0) /* nothing to do */
3447 return OK;
3449 if (lp->ll_tv == NULL)
3451 cc = *name_end;
3452 *name_end = NUL;
3454 /* Normal name or expanded name. */
3455 if (check_changedtick(lp->ll_name))
3456 ret = FAIL;
3457 else
3459 di = find_var(lp->ll_name, NULL);
3460 if (di == NULL)
3461 ret = FAIL;
3462 else
3464 if (lock)
3465 di->di_flags |= DI_FLAGS_LOCK;
3466 else
3467 di->di_flags &= ~DI_FLAGS_LOCK;
3468 item_lock(&di->di_tv, deep, lock);
3471 *name_end = cc;
3473 else if (lp->ll_range)
3475 listitem_T *li = lp->ll_li;
3477 /* (un)lock a range of List items. */
3478 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3480 item_lock(&li->li_tv, deep, lock);
3481 li = li->li_next;
3482 ++lp->ll_n1;
3485 else if (lp->ll_list != NULL)
3486 /* (un)lock a List item. */
3487 item_lock(&lp->ll_li->li_tv, deep, lock);
3488 else
3489 /* un(lock) a Dictionary item. */
3490 item_lock(&lp->ll_di->di_tv, deep, lock);
3492 return ret;
3496 * Lock or unlock an item. "deep" is nr of levels to go.
3498 static void
3499 item_lock(tv, deep, lock)
3500 typval_T *tv;
3501 int deep;
3502 int lock;
3504 static int recurse = 0;
3505 list_T *l;
3506 listitem_T *li;
3507 dict_T *d;
3508 hashitem_T *hi;
3509 int todo;
3511 if (recurse >= DICT_MAXNEST)
3513 EMSG(_("E743: variable nested too deep for (un)lock"));
3514 return;
3516 if (deep == 0)
3517 return;
3518 ++recurse;
3520 /* lock/unlock the item itself */
3521 if (lock)
3522 tv->v_lock |= VAR_LOCKED;
3523 else
3524 tv->v_lock &= ~VAR_LOCKED;
3526 switch (tv->v_type)
3528 case VAR_LIST:
3529 if ((l = tv->vval.v_list) != NULL)
3531 if (lock)
3532 l->lv_lock |= VAR_LOCKED;
3533 else
3534 l->lv_lock &= ~VAR_LOCKED;
3535 if (deep < 0 || deep > 1)
3536 /* recursive: lock/unlock the items the List contains */
3537 for (li = l->lv_first; li != NULL; li = li->li_next)
3538 item_lock(&li->li_tv, deep - 1, lock);
3540 break;
3541 case VAR_DICT:
3542 if ((d = tv->vval.v_dict) != NULL)
3544 if (lock)
3545 d->dv_lock |= VAR_LOCKED;
3546 else
3547 d->dv_lock &= ~VAR_LOCKED;
3548 if (deep < 0 || deep > 1)
3550 /* recursive: lock/unlock the items the List contains */
3551 todo = (int)d->dv_hashtab.ht_used;
3552 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3554 if (!HASHITEM_EMPTY(hi))
3556 --todo;
3557 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3563 --recurse;
3567 * Return TRUE if typeval "tv" is locked: Either tha value is locked itself or
3568 * it refers to a List or Dictionary that is locked.
3570 static int
3571 tv_islocked(tv)
3572 typval_T *tv;
3574 return (tv->v_lock & VAR_LOCKED)
3575 || (tv->v_type == VAR_LIST
3576 && tv->vval.v_list != NULL
3577 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3578 || (tv->v_type == VAR_DICT
3579 && tv->vval.v_dict != NULL
3580 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3583 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3585 * Delete all "menutrans_" variables.
3587 void
3588 del_menutrans_vars()
3590 hashitem_T *hi;
3591 int todo;
3593 hash_lock(&globvarht);
3594 todo = (int)globvarht.ht_used;
3595 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3597 if (!HASHITEM_EMPTY(hi))
3599 --todo;
3600 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3601 delete_var(&globvarht, hi);
3604 hash_unlock(&globvarht);
3606 #endif
3608 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3611 * Local string buffer for the next two functions to store a variable name
3612 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3613 * get_user_var_name().
3616 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3618 static char_u *varnamebuf = NULL;
3619 static int varnamebuflen = 0;
3622 * Function to concatenate a prefix and a variable name.
3624 static char_u *
3625 cat_prefix_varname(prefix, name)
3626 int prefix;
3627 char_u *name;
3629 int len;
3631 len = (int)STRLEN(name) + 3;
3632 if (len > varnamebuflen)
3634 vim_free(varnamebuf);
3635 len += 10; /* some additional space */
3636 varnamebuf = alloc(len);
3637 if (varnamebuf == NULL)
3639 varnamebuflen = 0;
3640 return NULL;
3642 varnamebuflen = len;
3644 *varnamebuf = prefix;
3645 varnamebuf[1] = ':';
3646 STRCPY(varnamebuf + 2, name);
3647 return varnamebuf;
3651 * Function given to ExpandGeneric() to obtain the list of user defined
3652 * (global/buffer/window/built-in) variable names.
3654 /*ARGSUSED*/
3655 char_u *
3656 get_user_var_name(xp, idx)
3657 expand_T *xp;
3658 int idx;
3660 static long_u gdone;
3661 static long_u bdone;
3662 static long_u wdone;
3663 #ifdef FEAT_WINDOWS
3664 static long_u tdone;
3665 #endif
3666 static int vidx;
3667 static hashitem_T *hi;
3668 hashtab_T *ht;
3670 if (idx == 0)
3672 gdone = bdone = wdone = vidx = 0;
3673 #ifdef FEAT_WINDOWS
3674 tdone = 0;
3675 #endif
3678 /* Global variables */
3679 if (gdone < globvarht.ht_used)
3681 if (gdone++ == 0)
3682 hi = globvarht.ht_array;
3683 else
3684 ++hi;
3685 while (HASHITEM_EMPTY(hi))
3686 ++hi;
3687 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3688 return cat_prefix_varname('g', hi->hi_key);
3689 return hi->hi_key;
3692 /* b: variables */
3693 ht = &curbuf->b_vars.dv_hashtab;
3694 if (bdone < ht->ht_used)
3696 if (bdone++ == 0)
3697 hi = ht->ht_array;
3698 else
3699 ++hi;
3700 while (HASHITEM_EMPTY(hi))
3701 ++hi;
3702 return cat_prefix_varname('b', hi->hi_key);
3704 if (bdone == ht->ht_used)
3706 ++bdone;
3707 return (char_u *)"b:changedtick";
3710 /* w: variables */
3711 ht = &curwin->w_vars.dv_hashtab;
3712 if (wdone < ht->ht_used)
3714 if (wdone++ == 0)
3715 hi = ht->ht_array;
3716 else
3717 ++hi;
3718 while (HASHITEM_EMPTY(hi))
3719 ++hi;
3720 return cat_prefix_varname('w', hi->hi_key);
3723 #ifdef FEAT_WINDOWS
3724 /* t: variables */
3725 ht = &curtab->tp_vars.dv_hashtab;
3726 if (tdone < ht->ht_used)
3728 if (tdone++ == 0)
3729 hi = ht->ht_array;
3730 else
3731 ++hi;
3732 while (HASHITEM_EMPTY(hi))
3733 ++hi;
3734 return cat_prefix_varname('t', hi->hi_key);
3736 #endif
3738 /* v: variables */
3739 if (vidx < VV_LEN)
3740 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3742 vim_free(varnamebuf);
3743 varnamebuf = NULL;
3744 varnamebuflen = 0;
3745 return NULL;
3748 #endif /* FEAT_CMDL_COMPL */
3751 * types for expressions.
3753 typedef enum
3755 TYPE_UNKNOWN = 0
3756 , TYPE_EQUAL /* == */
3757 , TYPE_NEQUAL /* != */
3758 , TYPE_GREATER /* > */
3759 , TYPE_GEQUAL /* >= */
3760 , TYPE_SMALLER /* < */
3761 , TYPE_SEQUAL /* <= */
3762 , TYPE_MATCH /* =~ */
3763 , TYPE_NOMATCH /* !~ */
3764 } exptype_T;
3767 * The "evaluate" argument: When FALSE, the argument is only parsed but not
3768 * executed. The function may return OK, but the rettv will be of type
3769 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
3773 * Handle zero level expression.
3774 * This calls eval1() and handles error message and nextcmd.
3775 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3776 * Note: "rettv.v_lock" is not set.
3777 * Return OK or FAIL.
3779 static int
3780 eval0(arg, rettv, nextcmd, evaluate)
3781 char_u *arg;
3782 typval_T *rettv;
3783 char_u **nextcmd;
3784 int evaluate;
3786 int ret;
3787 char_u *p;
3789 p = skipwhite(arg);
3790 ret = eval1(&p, rettv, evaluate);
3791 if (ret == FAIL || !ends_excmd(*p))
3793 if (ret != FAIL)
3794 clear_tv(rettv);
3796 * Report the invalid expression unless the expression evaluation has
3797 * been cancelled due to an aborting error, an interrupt, or an
3798 * exception.
3800 if (!aborting())
3801 EMSG2(_(e_invexpr2), arg);
3802 ret = FAIL;
3804 if (nextcmd != NULL)
3805 *nextcmd = check_nextcmd(p);
3807 return ret;
3811 * Handle top level expression:
3812 * expr1 ? expr0 : expr0
3814 * "arg" must point to the first non-white of the expression.
3815 * "arg" is advanced to the next non-white after the recognized expression.
3817 * Note: "rettv.v_lock" is not set.
3819 * Return OK or FAIL.
3821 static int
3822 eval1(arg, rettv, evaluate)
3823 char_u **arg;
3824 typval_T *rettv;
3825 int evaluate;
3827 int result;
3828 typval_T var2;
3831 * Get the first variable.
3833 if (eval2(arg, rettv, evaluate) == FAIL)
3834 return FAIL;
3836 if ((*arg)[0] == '?')
3838 result = FALSE;
3839 if (evaluate)
3841 int error = FALSE;
3843 if (get_tv_number_chk(rettv, &error) != 0)
3844 result = TRUE;
3845 clear_tv(rettv);
3846 if (error)
3847 return FAIL;
3851 * Get the second variable.
3853 *arg = skipwhite(*arg + 1);
3854 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
3855 return FAIL;
3858 * Check for the ":".
3860 if ((*arg)[0] != ':')
3862 EMSG(_("E109: Missing ':' after '?'"));
3863 if (evaluate && result)
3864 clear_tv(rettv);
3865 return FAIL;
3869 * Get the third variable.
3871 *arg = skipwhite(*arg + 1);
3872 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
3874 if (evaluate && result)
3875 clear_tv(rettv);
3876 return FAIL;
3878 if (evaluate && !result)
3879 *rettv = var2;
3882 return OK;
3886 * Handle first level expression:
3887 * expr2 || expr2 || expr2 logical OR
3889 * "arg" must point to the first non-white of the expression.
3890 * "arg" is advanced to the next non-white after the recognized expression.
3892 * Return OK or FAIL.
3894 static int
3895 eval2(arg, rettv, evaluate)
3896 char_u **arg;
3897 typval_T *rettv;
3898 int evaluate;
3900 typval_T var2;
3901 long result;
3902 int first;
3903 int error = FALSE;
3906 * Get the first variable.
3908 if (eval3(arg, rettv, evaluate) == FAIL)
3909 return FAIL;
3912 * Repeat until there is no following "||".
3914 first = TRUE;
3915 result = FALSE;
3916 while ((*arg)[0] == '|' && (*arg)[1] == '|')
3918 if (evaluate && first)
3920 if (get_tv_number_chk(rettv, &error) != 0)
3921 result = TRUE;
3922 clear_tv(rettv);
3923 if (error)
3924 return FAIL;
3925 first = FALSE;
3929 * Get the second variable.
3931 *arg = skipwhite(*arg + 2);
3932 if (eval3(arg, &var2, evaluate && !result) == FAIL)
3933 return FAIL;
3936 * Compute the result.
3938 if (evaluate && !result)
3940 if (get_tv_number_chk(&var2, &error) != 0)
3941 result = TRUE;
3942 clear_tv(&var2);
3943 if (error)
3944 return FAIL;
3946 if (evaluate)
3948 rettv->v_type = VAR_NUMBER;
3949 rettv->vval.v_number = result;
3953 return OK;
3957 * Handle second level expression:
3958 * expr3 && expr3 && expr3 logical AND
3960 * "arg" must point to the first non-white of the expression.
3961 * "arg" is advanced to the next non-white after the recognized expression.
3963 * Return OK or FAIL.
3965 static int
3966 eval3(arg, rettv, evaluate)
3967 char_u **arg;
3968 typval_T *rettv;
3969 int evaluate;
3971 typval_T var2;
3972 long result;
3973 int first;
3974 int error = FALSE;
3977 * Get the first variable.
3979 if (eval4(arg, rettv, evaluate) == FAIL)
3980 return FAIL;
3983 * Repeat until there is no following "&&".
3985 first = TRUE;
3986 result = TRUE;
3987 while ((*arg)[0] == '&' && (*arg)[1] == '&')
3989 if (evaluate && first)
3991 if (get_tv_number_chk(rettv, &error) == 0)
3992 result = FALSE;
3993 clear_tv(rettv);
3994 if (error)
3995 return FAIL;
3996 first = FALSE;
4000 * Get the second variable.
4002 *arg = skipwhite(*arg + 2);
4003 if (eval4(arg, &var2, evaluate && result) == FAIL)
4004 return FAIL;
4007 * Compute the result.
4009 if (evaluate && result)
4011 if (get_tv_number_chk(&var2, &error) == 0)
4012 result = FALSE;
4013 clear_tv(&var2);
4014 if (error)
4015 return FAIL;
4017 if (evaluate)
4019 rettv->v_type = VAR_NUMBER;
4020 rettv->vval.v_number = result;
4024 return OK;
4028 * Handle third level expression:
4029 * var1 == var2
4030 * var1 =~ var2
4031 * var1 != var2
4032 * var1 !~ var2
4033 * var1 > var2
4034 * var1 >= var2
4035 * var1 < var2
4036 * var1 <= var2
4037 * var1 is var2
4038 * var1 isnot var2
4040 * "arg" must point to the first non-white of the expression.
4041 * "arg" is advanced to the next non-white after the recognized expression.
4043 * Return OK or FAIL.
4045 static int
4046 eval4(arg, rettv, evaluate)
4047 char_u **arg;
4048 typval_T *rettv;
4049 int evaluate;
4051 typval_T var2;
4052 char_u *p;
4053 int i;
4054 exptype_T type = TYPE_UNKNOWN;
4055 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4056 int len = 2;
4057 long n1, n2;
4058 char_u *s1, *s2;
4059 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4060 regmatch_T regmatch;
4061 int ic;
4062 char_u *save_cpo;
4065 * Get the first variable.
4067 if (eval5(arg, rettv, evaluate) == FAIL)
4068 return FAIL;
4070 p = *arg;
4071 switch (p[0])
4073 case '=': if (p[1] == '=')
4074 type = TYPE_EQUAL;
4075 else if (p[1] == '~')
4076 type = TYPE_MATCH;
4077 break;
4078 case '!': if (p[1] == '=')
4079 type = TYPE_NEQUAL;
4080 else if (p[1] == '~')
4081 type = TYPE_NOMATCH;
4082 break;
4083 case '>': if (p[1] != '=')
4085 type = TYPE_GREATER;
4086 len = 1;
4088 else
4089 type = TYPE_GEQUAL;
4090 break;
4091 case '<': if (p[1] != '=')
4093 type = TYPE_SMALLER;
4094 len = 1;
4096 else
4097 type = TYPE_SEQUAL;
4098 break;
4099 case 'i': if (p[1] == 's')
4101 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4102 len = 5;
4103 if (!vim_isIDc(p[len]))
4105 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4106 type_is = TRUE;
4109 break;
4113 * If there is a comparitive operator, use it.
4115 if (type != TYPE_UNKNOWN)
4117 /* extra question mark appended: ignore case */
4118 if (p[len] == '?')
4120 ic = TRUE;
4121 ++len;
4123 /* extra '#' appended: match case */
4124 else if (p[len] == '#')
4126 ic = FALSE;
4127 ++len;
4129 /* nothing appened: use 'ignorecase' */
4130 else
4131 ic = p_ic;
4134 * Get the second variable.
4136 *arg = skipwhite(p + len);
4137 if (eval5(arg, &var2, evaluate) == FAIL)
4139 clear_tv(rettv);
4140 return FAIL;
4143 if (evaluate)
4145 if (type_is && rettv->v_type != var2.v_type)
4147 /* For "is" a different type always means FALSE, for "notis"
4148 * it means TRUE. */
4149 n1 = (type == TYPE_NEQUAL);
4151 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4153 if (type_is)
4155 n1 = (rettv->v_type == var2.v_type
4156 && rettv->vval.v_list == var2.vval.v_list);
4157 if (type == TYPE_NEQUAL)
4158 n1 = !n1;
4160 else if (rettv->v_type != var2.v_type
4161 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4163 if (rettv->v_type != var2.v_type)
4164 EMSG(_("E691: Can only compare List with List"));
4165 else
4166 EMSG(_("E692: Invalid operation for Lists"));
4167 clear_tv(rettv);
4168 clear_tv(&var2);
4169 return FAIL;
4171 else
4173 /* Compare two Lists for being equal or unequal. */
4174 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
4175 if (type == TYPE_NEQUAL)
4176 n1 = !n1;
4180 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4182 if (type_is)
4184 n1 = (rettv->v_type == var2.v_type
4185 && rettv->vval.v_dict == var2.vval.v_dict);
4186 if (type == TYPE_NEQUAL)
4187 n1 = !n1;
4189 else if (rettv->v_type != var2.v_type
4190 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4192 if (rettv->v_type != var2.v_type)
4193 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4194 else
4195 EMSG(_("E736: Invalid operation for Dictionary"));
4196 clear_tv(rettv);
4197 clear_tv(&var2);
4198 return FAIL;
4200 else
4202 /* Compare two Dictionaries for being equal or unequal. */
4203 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4204 if (type == TYPE_NEQUAL)
4205 n1 = !n1;
4209 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4211 if (rettv->v_type != var2.v_type
4212 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4214 if (rettv->v_type != var2.v_type)
4215 EMSG(_("E693: Can only compare Funcref with Funcref"));
4216 else
4217 EMSG(_("E694: Invalid operation for Funcrefs"));
4218 clear_tv(rettv);
4219 clear_tv(&var2);
4220 return FAIL;
4222 else
4224 /* Compare two Funcrefs for being equal or unequal. */
4225 if (rettv->vval.v_string == NULL
4226 || var2.vval.v_string == NULL)
4227 n1 = FALSE;
4228 else
4229 n1 = STRCMP(rettv->vval.v_string,
4230 var2.vval.v_string) == 0;
4231 if (type == TYPE_NEQUAL)
4232 n1 = !n1;
4237 * If one of the two variables is a number, compare as a number.
4238 * When using "=~" or "!~", always compare as string.
4240 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4241 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4243 n1 = get_tv_number(rettv);
4244 n2 = get_tv_number(&var2);
4245 switch (type)
4247 case TYPE_EQUAL: n1 = (n1 == n2); break;
4248 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4249 case TYPE_GREATER: n1 = (n1 > n2); break;
4250 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4251 case TYPE_SMALLER: n1 = (n1 < n2); break;
4252 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4253 case TYPE_UNKNOWN:
4254 case TYPE_MATCH:
4255 case TYPE_NOMATCH: break; /* avoid gcc warning */
4258 else
4260 s1 = get_tv_string_buf(rettv, buf1);
4261 s2 = get_tv_string_buf(&var2, buf2);
4262 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4263 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4264 else
4265 i = 0;
4266 n1 = FALSE;
4267 switch (type)
4269 case TYPE_EQUAL: n1 = (i == 0); break;
4270 case TYPE_NEQUAL: n1 = (i != 0); break;
4271 case TYPE_GREATER: n1 = (i > 0); break;
4272 case TYPE_GEQUAL: n1 = (i >= 0); break;
4273 case TYPE_SMALLER: n1 = (i < 0); break;
4274 case TYPE_SEQUAL: n1 = (i <= 0); break;
4276 case TYPE_MATCH:
4277 case TYPE_NOMATCH:
4278 /* avoid 'l' flag in 'cpoptions' */
4279 save_cpo = p_cpo;
4280 p_cpo = (char_u *)"";
4281 regmatch.regprog = vim_regcomp(s2,
4282 RE_MAGIC + RE_STRING);
4283 regmatch.rm_ic = ic;
4284 if (regmatch.regprog != NULL)
4286 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4287 vim_free(regmatch.regprog);
4288 if (type == TYPE_NOMATCH)
4289 n1 = !n1;
4291 p_cpo = save_cpo;
4292 break;
4294 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4297 clear_tv(rettv);
4298 clear_tv(&var2);
4299 rettv->v_type = VAR_NUMBER;
4300 rettv->vval.v_number = n1;
4304 return OK;
4308 * Handle fourth level expression:
4309 * + number addition
4310 * - number subtraction
4311 * . string concatenation
4313 * "arg" must point to the first non-white of the expression.
4314 * "arg" is advanced to the next non-white after the recognized expression.
4316 * Return OK or FAIL.
4318 static int
4319 eval5(arg, rettv, evaluate)
4320 char_u **arg;
4321 typval_T *rettv;
4322 int evaluate;
4324 typval_T var2;
4325 typval_T var3;
4326 int op;
4327 long n1, n2;
4328 char_u *s1, *s2;
4329 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4330 char_u *p;
4333 * Get the first variable.
4335 if (eval6(arg, rettv, evaluate) == FAIL)
4336 return FAIL;
4339 * Repeat computing, until no '+', '-' or '.' is following.
4341 for (;;)
4343 op = **arg;
4344 if (op != '+' && op != '-' && op != '.')
4345 break;
4347 if (op != '+' || rettv->v_type != VAR_LIST)
4349 /* For "list + ...", an illegal use of the first operand as
4350 * a number cannot be determined before evaluating the 2nd
4351 * operand: if this is also a list, all is ok.
4352 * For "something . ...", "something - ..." or "non-list + ...",
4353 * we know that the first operand needs to be a string or number
4354 * without evaluating the 2nd operand. So check before to avoid
4355 * side effects after an error. */
4356 if (evaluate && get_tv_string_chk(rettv) == NULL)
4358 clear_tv(rettv);
4359 return FAIL;
4364 * Get the second variable.
4366 *arg = skipwhite(*arg + 1);
4367 if (eval6(arg, &var2, evaluate) == FAIL)
4369 clear_tv(rettv);
4370 return FAIL;
4373 if (evaluate)
4376 * Compute the result.
4378 if (op == '.')
4380 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4381 s2 = get_tv_string_buf_chk(&var2, buf2);
4382 if (s2 == NULL) /* type error ? */
4384 clear_tv(rettv);
4385 clear_tv(&var2);
4386 return FAIL;
4388 p = concat_str(s1, s2);
4389 clear_tv(rettv);
4390 rettv->v_type = VAR_STRING;
4391 rettv->vval.v_string = p;
4393 else if (op == '+' && rettv->v_type == VAR_LIST
4394 && var2.v_type == VAR_LIST)
4396 /* concatenate Lists */
4397 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4398 &var3) == FAIL)
4400 clear_tv(rettv);
4401 clear_tv(&var2);
4402 return FAIL;
4404 clear_tv(rettv);
4405 *rettv = var3;
4407 else
4409 int error = FALSE;
4411 n1 = get_tv_number_chk(rettv, &error);
4412 if (error)
4414 /* This can only happen for "list + non-list".
4415 * For "non-list + ..." or "something - ...", we returned
4416 * before evaluating the 2nd operand. */
4417 clear_tv(rettv);
4418 return FAIL;
4420 n2 = get_tv_number_chk(&var2, &error);
4421 if (error)
4423 clear_tv(rettv);
4424 clear_tv(&var2);
4425 return FAIL;
4427 clear_tv(rettv);
4428 if (op == '+')
4429 n1 = n1 + n2;
4430 else
4431 n1 = n1 - n2;
4432 rettv->v_type = VAR_NUMBER;
4433 rettv->vval.v_number = n1;
4435 clear_tv(&var2);
4438 return OK;
4442 * Handle fifth level expression:
4443 * * number multiplication
4444 * / number division
4445 * % number modulo
4447 * "arg" must point to the first non-white of the expression.
4448 * "arg" is advanced to the next non-white after the recognized expression.
4450 * Return OK or FAIL.
4452 static int
4453 eval6(arg, rettv, evaluate)
4454 char_u **arg;
4455 typval_T *rettv;
4456 int evaluate;
4458 typval_T var2;
4459 int op;
4460 long n1, n2;
4461 int error = FALSE;
4464 * Get the first variable.
4466 if (eval7(arg, rettv, evaluate) == FAIL)
4467 return FAIL;
4470 * Repeat computing, until no '*', '/' or '%' is following.
4472 for (;;)
4474 op = **arg;
4475 if (op != '*' && op != '/' && op != '%')
4476 break;
4478 if (evaluate)
4480 n1 = get_tv_number_chk(rettv, &error);
4481 clear_tv(rettv);
4482 if (error)
4483 return FAIL;
4485 else
4486 n1 = 0;
4489 * Get the second variable.
4491 *arg = skipwhite(*arg + 1);
4492 if (eval7(arg, &var2, evaluate) == FAIL)
4493 return FAIL;
4495 if (evaluate)
4497 n2 = get_tv_number_chk(&var2, &error);
4498 clear_tv(&var2);
4499 if (error)
4500 return FAIL;
4503 * Compute the result.
4505 if (op == '*')
4506 n1 = n1 * n2;
4507 else if (op == '/')
4509 if (n2 == 0) /* give an error message? */
4510 n1 = 0x7fffffffL;
4511 else
4512 n1 = n1 / n2;
4514 else
4516 if (n2 == 0) /* give an error message? */
4517 n1 = 0;
4518 else
4519 n1 = n1 % n2;
4521 rettv->v_type = VAR_NUMBER;
4522 rettv->vval.v_number = n1;
4526 return OK;
4530 * Handle sixth level expression:
4531 * number number constant
4532 * "string" string constant
4533 * 'string' literal string constant
4534 * &option-name option value
4535 * @r register contents
4536 * identifier variable value
4537 * function() function call
4538 * $VAR environment variable
4539 * (expression) nested expression
4540 * [expr, expr] List
4541 * {key: val, key: val} Dictionary
4543 * Also handle:
4544 * ! in front logical NOT
4545 * - in front unary minus
4546 * + in front unary plus (ignored)
4547 * trailing [] subscript in String or List
4548 * trailing .name entry in Dictionary
4550 * "arg" must point to the first non-white of the expression.
4551 * "arg" is advanced to the next non-white after the recognized expression.
4553 * Return OK or FAIL.
4555 static int
4556 eval7(arg, rettv, evaluate)
4557 char_u **arg;
4558 typval_T *rettv;
4559 int evaluate;
4561 long n;
4562 int len;
4563 char_u *s;
4564 int val;
4565 char_u *start_leader, *end_leader;
4566 int ret = OK;
4567 char_u *alias;
4570 * Initialise variable so that clear_tv() can't mistake this for a
4571 * string and free a string that isn't there.
4573 rettv->v_type = VAR_UNKNOWN;
4576 * Skip '!' and '-' characters. They are handled later.
4578 start_leader = *arg;
4579 while (**arg == '!' || **arg == '-' || **arg == '+')
4580 *arg = skipwhite(*arg + 1);
4581 end_leader = *arg;
4583 switch (**arg)
4586 * Number constant.
4588 case '0':
4589 case '1':
4590 case '2':
4591 case '3':
4592 case '4':
4593 case '5':
4594 case '6':
4595 case '7':
4596 case '8':
4597 case '9':
4598 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4599 *arg += len;
4600 if (evaluate)
4602 rettv->v_type = VAR_NUMBER;
4603 rettv->vval.v_number = n;
4605 break;
4608 * String constant: "string".
4610 case '"': ret = get_string_tv(arg, rettv, evaluate);
4611 break;
4614 * Literal string constant: 'str''ing'.
4616 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
4617 break;
4620 * List: [expr, expr]
4622 case '[': ret = get_list_tv(arg, rettv, evaluate);
4623 break;
4626 * Dictionary: {key: val, key: val}
4628 case '{': ret = get_dict_tv(arg, rettv, evaluate);
4629 break;
4632 * Option value: &name
4634 case '&': ret = get_option_tv(arg, rettv, evaluate);
4635 break;
4638 * Environment variable: $VAR.
4640 case '$': ret = get_env_tv(arg, rettv, evaluate);
4641 break;
4644 * Register contents: @r.
4646 case '@': ++*arg;
4647 if (evaluate)
4649 rettv->v_type = VAR_STRING;
4650 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4652 if (**arg != NUL)
4653 ++*arg;
4654 break;
4657 * nested expression: (expression).
4659 case '(': *arg = skipwhite(*arg + 1);
4660 ret = eval1(arg, rettv, evaluate); /* recursive! */
4661 if (**arg == ')')
4662 ++*arg;
4663 else if (ret == OK)
4665 EMSG(_("E110: Missing ')'"));
4666 clear_tv(rettv);
4667 ret = FAIL;
4669 break;
4671 default: ret = NOTDONE;
4672 break;
4675 if (ret == NOTDONE)
4678 * Must be a variable or function name.
4679 * Can also be a curly-braces kind of name: {expr}.
4681 s = *arg;
4682 len = get_name_len(arg, &alias, evaluate, TRUE);
4683 if (alias != NULL)
4684 s = alias;
4686 if (len <= 0)
4687 ret = FAIL;
4688 else
4690 if (**arg == '(') /* recursive! */
4692 /* If "s" is the name of a variable of type VAR_FUNC
4693 * use its contents. */
4694 s = deref_func_name(s, &len);
4696 /* Invoke the function. */
4697 ret = get_func_tv(s, len, rettv, arg,
4698 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
4699 &len, evaluate, NULL);
4700 /* Stop the expression evaluation when immediately
4701 * aborting on error, or when an interrupt occurred or
4702 * an exception was thrown but not caught. */
4703 if (aborting())
4705 if (ret == OK)
4706 clear_tv(rettv);
4707 ret = FAIL;
4710 else if (evaluate)
4711 ret = get_var_tv(s, len, rettv, TRUE);
4712 else
4713 ret = OK;
4716 if (alias != NULL)
4717 vim_free(alias);
4720 *arg = skipwhite(*arg);
4722 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
4723 * expr(expr). */
4724 if (ret == OK)
4725 ret = handle_subscript(arg, rettv, evaluate, TRUE);
4728 * Apply logical NOT and unary '-', from right to left, ignore '+'.
4730 if (ret == OK && evaluate && end_leader > start_leader)
4732 int error = FALSE;
4734 val = get_tv_number_chk(rettv, &error);
4735 if (error)
4737 clear_tv(rettv);
4738 ret = FAIL;
4740 else
4742 while (end_leader > start_leader)
4744 --end_leader;
4745 if (*end_leader == '!')
4746 val = !val;
4747 else if (*end_leader == '-')
4748 val = -val;
4750 clear_tv(rettv);
4751 rettv->v_type = VAR_NUMBER;
4752 rettv->vval.v_number = val;
4756 return ret;
4760 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
4761 * "*arg" points to the '[' or '.'.
4762 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
4764 static int
4765 eval_index(arg, rettv, evaluate, verbose)
4766 char_u **arg;
4767 typval_T *rettv;
4768 int evaluate;
4769 int verbose; /* give error messages */
4771 int empty1 = FALSE, empty2 = FALSE;
4772 typval_T var1, var2;
4773 long n1, n2 = 0;
4774 long len = -1;
4775 int range = FALSE;
4776 char_u *s;
4777 char_u *key = NULL;
4779 if (rettv->v_type == VAR_FUNC)
4781 if (verbose)
4782 EMSG(_("E695: Cannot index a Funcref"));
4783 return FAIL;
4786 if (**arg == '.')
4789 * dict.name
4791 key = *arg + 1;
4792 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
4794 if (len == 0)
4795 return FAIL;
4796 *arg = skipwhite(key + len);
4798 else
4801 * something[idx]
4803 * Get the (first) variable from inside the [].
4805 *arg = skipwhite(*arg + 1);
4806 if (**arg == ':')
4807 empty1 = TRUE;
4808 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
4809 return FAIL;
4810 else if (evaluate && get_tv_string_chk(&var1) == NULL)
4812 /* not a number or string */
4813 clear_tv(&var1);
4814 return FAIL;
4818 * Get the second variable from inside the [:].
4820 if (**arg == ':')
4822 range = TRUE;
4823 *arg = skipwhite(*arg + 1);
4824 if (**arg == ']')
4825 empty2 = TRUE;
4826 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
4828 if (!empty1)
4829 clear_tv(&var1);
4830 return FAIL;
4832 else if (evaluate && get_tv_string_chk(&var2) == NULL)
4834 /* not a number or string */
4835 if (!empty1)
4836 clear_tv(&var1);
4837 clear_tv(&var2);
4838 return FAIL;
4842 /* Check for the ']'. */
4843 if (**arg != ']')
4845 if (verbose)
4846 EMSG(_(e_missbrac));
4847 clear_tv(&var1);
4848 if (range)
4849 clear_tv(&var2);
4850 return FAIL;
4852 *arg = skipwhite(*arg + 1); /* skip the ']' */
4855 if (evaluate)
4857 n1 = 0;
4858 if (!empty1 && rettv->v_type != VAR_DICT)
4860 n1 = get_tv_number(&var1);
4861 clear_tv(&var1);
4863 if (range)
4865 if (empty2)
4866 n2 = -1;
4867 else
4869 n2 = get_tv_number(&var2);
4870 clear_tv(&var2);
4874 switch (rettv->v_type)
4876 case VAR_NUMBER:
4877 case VAR_STRING:
4878 s = get_tv_string(rettv);
4879 len = (long)STRLEN(s);
4880 if (range)
4882 /* The resulting variable is a substring. If the indexes
4883 * are out of range the result is empty. */
4884 if (n1 < 0)
4886 n1 = len + n1;
4887 if (n1 < 0)
4888 n1 = 0;
4890 if (n2 < 0)
4891 n2 = len + n2;
4892 else if (n2 >= len)
4893 n2 = len;
4894 if (n1 >= len || n2 < 0 || n1 > n2)
4895 s = NULL;
4896 else
4897 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
4899 else
4901 /* The resulting variable is a string of a single
4902 * character. If the index is too big or negative the
4903 * result is empty. */
4904 if (n1 >= len || n1 < 0)
4905 s = NULL;
4906 else
4907 s = vim_strnsave(s + n1, 1);
4909 clear_tv(rettv);
4910 rettv->v_type = VAR_STRING;
4911 rettv->vval.v_string = s;
4912 break;
4914 case VAR_LIST:
4915 len = list_len(rettv->vval.v_list);
4916 if (n1 < 0)
4917 n1 = len + n1;
4918 if (!empty1 && (n1 < 0 || n1 >= len))
4920 /* For a range we allow invalid values and return an empty
4921 * list. A list index out of range is an error. */
4922 if (!range)
4924 if (verbose)
4925 EMSGN(_(e_listidx), n1);
4926 return FAIL;
4928 n1 = len;
4930 if (range)
4932 list_T *l;
4933 listitem_T *item;
4935 if (n2 < 0)
4936 n2 = len + n2;
4937 else if (n2 >= len)
4938 n2 = len - 1;
4939 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
4940 n2 = -1;
4941 l = list_alloc();
4942 if (l == NULL)
4943 return FAIL;
4944 for (item = list_find(rettv->vval.v_list, n1);
4945 n1 <= n2; ++n1)
4947 if (list_append_tv(l, &item->li_tv) == FAIL)
4949 list_free(l, TRUE);
4950 return FAIL;
4952 item = item->li_next;
4954 clear_tv(rettv);
4955 rettv->v_type = VAR_LIST;
4956 rettv->vval.v_list = l;
4957 ++l->lv_refcount;
4959 else
4961 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
4962 clear_tv(rettv);
4963 *rettv = var1;
4965 break;
4967 case VAR_DICT:
4968 if (range)
4970 if (verbose)
4971 EMSG(_(e_dictrange));
4972 if (len == -1)
4973 clear_tv(&var1);
4974 return FAIL;
4977 dictitem_T *item;
4979 if (len == -1)
4981 key = get_tv_string(&var1);
4982 if (*key == NUL)
4984 if (verbose)
4985 EMSG(_(e_emptykey));
4986 clear_tv(&var1);
4987 return FAIL;
4991 item = dict_find(rettv->vval.v_dict, key, (int)len);
4993 if (item == NULL && verbose)
4994 EMSG2(_(e_dictkey), key);
4995 if (len == -1)
4996 clear_tv(&var1);
4997 if (item == NULL)
4998 return FAIL;
5000 copy_tv(&item->di_tv, &var1);
5001 clear_tv(rettv);
5002 *rettv = var1;
5004 break;
5008 return OK;
5012 * Get an option value.
5013 * "arg" points to the '&' or '+' before the option name.
5014 * "arg" is advanced to character after the option name.
5015 * Return OK or FAIL.
5017 static int
5018 get_option_tv(arg, rettv, evaluate)
5019 char_u **arg;
5020 typval_T *rettv; /* when NULL, only check if option exists */
5021 int evaluate;
5023 char_u *option_end;
5024 long numval;
5025 char_u *stringval;
5026 int opt_type;
5027 int c;
5028 int working = (**arg == '+'); /* has("+option") */
5029 int ret = OK;
5030 int opt_flags;
5033 * Isolate the option name and find its value.
5035 option_end = find_option_end(arg, &opt_flags);
5036 if (option_end == NULL)
5038 if (rettv != NULL)
5039 EMSG2(_("E112: Option name missing: %s"), *arg);
5040 return FAIL;
5043 if (!evaluate)
5045 *arg = option_end;
5046 return OK;
5049 c = *option_end;
5050 *option_end = NUL;
5051 opt_type = get_option_value(*arg, &numval,
5052 rettv == NULL ? NULL : &stringval, opt_flags);
5054 if (opt_type == -3) /* invalid name */
5056 if (rettv != NULL)
5057 EMSG2(_("E113: Unknown option: %s"), *arg);
5058 ret = FAIL;
5060 else if (rettv != NULL)
5062 if (opt_type == -2) /* hidden string option */
5064 rettv->v_type = VAR_STRING;
5065 rettv->vval.v_string = NULL;
5067 else if (opt_type == -1) /* hidden number option */
5069 rettv->v_type = VAR_NUMBER;
5070 rettv->vval.v_number = 0;
5072 else if (opt_type == 1) /* number option */
5074 rettv->v_type = VAR_NUMBER;
5075 rettv->vval.v_number = numval;
5077 else /* string option */
5079 rettv->v_type = VAR_STRING;
5080 rettv->vval.v_string = stringval;
5083 else if (working && (opt_type == -2 || opt_type == -1))
5084 ret = FAIL;
5086 *option_end = c; /* put back for error messages */
5087 *arg = option_end;
5089 return ret;
5093 * Allocate a variable for a string constant.
5094 * Return OK or FAIL.
5096 static int
5097 get_string_tv(arg, rettv, evaluate)
5098 char_u **arg;
5099 typval_T *rettv;
5100 int evaluate;
5102 char_u *p;
5103 char_u *name;
5104 int extra = 0;
5107 * Find the end of the string, skipping backslashed characters.
5109 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5111 if (*p == '\\' && p[1] != NUL)
5113 ++p;
5114 /* A "\<x>" form occupies at least 4 characters, and produces up
5115 * to 6 characters: reserve space for 2 extra */
5116 if (*p == '<')
5117 extra += 2;
5121 if (*p != '"')
5123 EMSG2(_("E114: Missing quote: %s"), *arg);
5124 return FAIL;
5127 /* If only parsing, set *arg and return here */
5128 if (!evaluate)
5130 *arg = p + 1;
5131 return OK;
5135 * Copy the string into allocated memory, handling backslashed
5136 * characters.
5138 name = alloc((unsigned)(p - *arg + extra));
5139 if (name == NULL)
5140 return FAIL;
5141 rettv->v_type = VAR_STRING;
5142 rettv->vval.v_string = name;
5144 for (p = *arg + 1; *p != NUL && *p != '"'; )
5146 if (*p == '\\')
5148 switch (*++p)
5150 case 'b': *name++ = BS; ++p; break;
5151 case 'e': *name++ = ESC; ++p; break;
5152 case 'f': *name++ = FF; ++p; break;
5153 case 'n': *name++ = NL; ++p; break;
5154 case 'r': *name++ = CAR; ++p; break;
5155 case 't': *name++ = TAB; ++p; break;
5157 case 'X': /* hex: "\x1", "\x12" */
5158 case 'x':
5159 case 'u': /* Unicode: "\u0023" */
5160 case 'U':
5161 if (vim_isxdigit(p[1]))
5163 int n, nr;
5164 int c = toupper(*p);
5166 if (c == 'X')
5167 n = 2;
5168 else
5169 n = 4;
5170 nr = 0;
5171 while (--n >= 0 && vim_isxdigit(p[1]))
5173 ++p;
5174 nr = (nr << 4) + hex2nr(*p);
5176 ++p;
5177 #ifdef FEAT_MBYTE
5178 /* For "\u" store the number according to
5179 * 'encoding'. */
5180 if (c != 'X')
5181 name += (*mb_char2bytes)(nr, name);
5182 else
5183 #endif
5184 *name++ = nr;
5186 break;
5188 /* octal: "\1", "\12", "\123" */
5189 case '0':
5190 case '1':
5191 case '2':
5192 case '3':
5193 case '4':
5194 case '5':
5195 case '6':
5196 case '7': *name = *p++ - '0';
5197 if (*p >= '0' && *p <= '7')
5199 *name = (*name << 3) + *p++ - '0';
5200 if (*p >= '0' && *p <= '7')
5201 *name = (*name << 3) + *p++ - '0';
5203 ++name;
5204 break;
5206 /* Special key, e.g.: "\<C-W>" */
5207 case '<': extra = trans_special(&p, name, TRUE);
5208 if (extra != 0)
5210 name += extra;
5211 break;
5213 /* FALLTHROUGH */
5215 default: MB_COPY_CHAR(p, name);
5216 break;
5219 else
5220 MB_COPY_CHAR(p, name);
5223 *name = NUL;
5224 *arg = p + 1;
5226 return OK;
5230 * Allocate a variable for a 'str''ing' constant.
5231 * Return OK or FAIL.
5233 static int
5234 get_lit_string_tv(arg, rettv, evaluate)
5235 char_u **arg;
5236 typval_T *rettv;
5237 int evaluate;
5239 char_u *p;
5240 char_u *str;
5241 int reduce = 0;
5244 * Find the end of the string, skipping ''.
5246 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5248 if (*p == '\'')
5250 if (p[1] != '\'')
5251 break;
5252 ++reduce;
5253 ++p;
5257 if (*p != '\'')
5259 EMSG2(_("E115: Missing quote: %s"), *arg);
5260 return FAIL;
5263 /* If only parsing return after setting "*arg" */
5264 if (!evaluate)
5266 *arg = p + 1;
5267 return OK;
5271 * Copy the string into allocated memory, handling '' to ' reduction.
5273 str = alloc((unsigned)((p - *arg) - reduce));
5274 if (str == NULL)
5275 return FAIL;
5276 rettv->v_type = VAR_STRING;
5277 rettv->vval.v_string = str;
5279 for (p = *arg + 1; *p != NUL; )
5281 if (*p == '\'')
5283 if (p[1] != '\'')
5284 break;
5285 ++p;
5287 MB_COPY_CHAR(p, str);
5289 *str = NUL;
5290 *arg = p + 1;
5292 return OK;
5296 * Allocate a variable for a List and fill it from "*arg".
5297 * Return OK or FAIL.
5299 static int
5300 get_list_tv(arg, rettv, evaluate)
5301 char_u **arg;
5302 typval_T *rettv;
5303 int evaluate;
5305 list_T *l = NULL;
5306 typval_T tv;
5307 listitem_T *item;
5309 if (evaluate)
5311 l = list_alloc();
5312 if (l == NULL)
5313 return FAIL;
5316 *arg = skipwhite(*arg + 1);
5317 while (**arg != ']' && **arg != NUL)
5319 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5320 goto failret;
5321 if (evaluate)
5323 item = listitem_alloc();
5324 if (item != NULL)
5326 item->li_tv = tv;
5327 item->li_tv.v_lock = 0;
5328 list_append(l, item);
5330 else
5331 clear_tv(&tv);
5334 if (**arg == ']')
5335 break;
5336 if (**arg != ',')
5338 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5339 goto failret;
5341 *arg = skipwhite(*arg + 1);
5344 if (**arg != ']')
5346 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5347 failret:
5348 if (evaluate)
5349 list_free(l, TRUE);
5350 return FAIL;
5353 *arg = skipwhite(*arg + 1);
5354 if (evaluate)
5356 rettv->v_type = VAR_LIST;
5357 rettv->vval.v_list = l;
5358 ++l->lv_refcount;
5361 return OK;
5365 * Allocate an empty header for a list.
5366 * Caller should take care of the reference count.
5368 list_T *
5369 list_alloc()
5371 list_T *l;
5373 l = (list_T *)alloc_clear(sizeof(list_T));
5374 if (l != NULL)
5376 /* Prepend the list to the list of lists for garbage collection. */
5377 if (first_list != NULL)
5378 first_list->lv_used_prev = l;
5379 l->lv_used_prev = NULL;
5380 l->lv_used_next = first_list;
5381 first_list = l;
5383 return l;
5387 * Allocate an empty list for a return value.
5388 * Returns OK or FAIL.
5390 static int
5391 rettv_list_alloc(rettv)
5392 typval_T *rettv;
5394 list_T *l = list_alloc();
5396 if (l == NULL)
5397 return FAIL;
5399 rettv->vval.v_list = l;
5400 rettv->v_type = VAR_LIST;
5401 ++l->lv_refcount;
5402 return OK;
5406 * Unreference a list: decrement the reference count and free it when it
5407 * becomes zero.
5409 void
5410 list_unref(l)
5411 list_T *l;
5413 if (l != NULL && --l->lv_refcount <= 0)
5414 list_free(l, TRUE);
5418 * Free a list, including all items it points to.
5419 * Ignores the reference count.
5421 void
5422 list_free(l, recurse)
5423 list_T *l;
5424 int recurse; /* Free Lists and Dictionaries recursively. */
5426 listitem_T *item;
5428 /* Remove the list from the list of lists for garbage collection. */
5429 if (l->lv_used_prev == NULL)
5430 first_list = l->lv_used_next;
5431 else
5432 l->lv_used_prev->lv_used_next = l->lv_used_next;
5433 if (l->lv_used_next != NULL)
5434 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5436 for (item = l->lv_first; item != NULL; item = l->lv_first)
5438 /* Remove the item before deleting it. */
5439 l->lv_first = item->li_next;
5440 if (recurse || (item->li_tv.v_type != VAR_LIST
5441 && item->li_tv.v_type != VAR_DICT))
5442 clear_tv(&item->li_tv);
5443 vim_free(item);
5445 vim_free(l);
5449 * Allocate a list item.
5451 static listitem_T *
5452 listitem_alloc()
5454 return (listitem_T *)alloc(sizeof(listitem_T));
5458 * Free a list item. Also clears the value. Does not notify watchers.
5460 static void
5461 listitem_free(item)
5462 listitem_T *item;
5464 clear_tv(&item->li_tv);
5465 vim_free(item);
5469 * Remove a list item from a List and free it. Also clears the value.
5471 static void
5472 listitem_remove(l, item)
5473 list_T *l;
5474 listitem_T *item;
5476 list_remove(l, item, item);
5477 listitem_free(item);
5481 * Get the number of items in a list.
5483 static long
5484 list_len(l)
5485 list_T *l;
5487 if (l == NULL)
5488 return 0L;
5489 return l->lv_len;
5493 * Return TRUE when two lists have exactly the same values.
5495 static int
5496 list_equal(l1, l2, ic)
5497 list_T *l1;
5498 list_T *l2;
5499 int ic; /* ignore case for strings */
5501 listitem_T *item1, *item2;
5503 if (l1 == l2)
5504 return TRUE;
5505 if (list_len(l1) != list_len(l2))
5506 return FALSE;
5508 for (item1 = l1->lv_first, item2 = l2->lv_first;
5509 item1 != NULL && item2 != NULL;
5510 item1 = item1->li_next, item2 = item2->li_next)
5511 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5512 return FALSE;
5513 return item1 == NULL && item2 == NULL;
5516 #if defined(FEAT_PYTHON) || defined(PROTO)
5518 * Return the dictitem that an entry in a hashtable points to.
5520 dictitem_T *
5521 dict_lookup(hi)
5522 hashitem_T *hi;
5524 return HI2DI(hi);
5526 #endif
5529 * Return TRUE when two dictionaries have exactly the same key/values.
5531 static int
5532 dict_equal(d1, d2, ic)
5533 dict_T *d1;
5534 dict_T *d2;
5535 int ic; /* ignore case for strings */
5537 hashitem_T *hi;
5538 dictitem_T *item2;
5539 int todo;
5541 if (d1 == d2)
5542 return TRUE;
5543 if (dict_len(d1) != dict_len(d2))
5544 return FALSE;
5546 todo = (int)d1->dv_hashtab.ht_used;
5547 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5549 if (!HASHITEM_EMPTY(hi))
5551 item2 = dict_find(d2, hi->hi_key, -1);
5552 if (item2 == NULL)
5553 return FALSE;
5554 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5555 return FALSE;
5556 --todo;
5559 return TRUE;
5563 * Return TRUE if "tv1" and "tv2" have the same value.
5564 * Compares the items just like "==" would compare them, but strings and
5565 * numbers are different.
5567 static int
5568 tv_equal(tv1, tv2, ic)
5569 typval_T *tv1;
5570 typval_T *tv2;
5571 int ic; /* ignore case */
5573 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5574 char_u *s1, *s2;
5575 static int recursive = 0; /* cach recursive loops */
5576 int r;
5578 if (tv1->v_type != tv2->v_type)
5579 return FALSE;
5580 /* Catch lists and dicts that have an endless loop by limiting
5581 * recursiveness to 1000. We guess they are equal then. */
5582 if (recursive >= 1000)
5583 return TRUE;
5585 switch (tv1->v_type)
5587 case VAR_LIST:
5588 ++recursive;
5589 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5590 --recursive;
5591 return r;
5593 case VAR_DICT:
5594 ++recursive;
5595 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5596 --recursive;
5597 return r;
5599 case VAR_FUNC:
5600 return (tv1->vval.v_string != NULL
5601 && tv2->vval.v_string != NULL
5602 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5604 case VAR_NUMBER:
5605 return tv1->vval.v_number == tv2->vval.v_number;
5607 case VAR_STRING:
5608 s1 = get_tv_string_buf(tv1, buf1);
5609 s2 = get_tv_string_buf(tv2, buf2);
5610 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5613 EMSG2(_(e_intern2), "tv_equal()");
5614 return TRUE;
5618 * Locate item with index "n" in list "l" and return it.
5619 * A negative index is counted from the end; -1 is the last item.
5620 * Returns NULL when "n" is out of range.
5622 static listitem_T *
5623 list_find(l, n)
5624 list_T *l;
5625 long n;
5627 listitem_T *item;
5628 long idx;
5630 if (l == NULL)
5631 return NULL;
5633 /* Negative index is relative to the end. */
5634 if (n < 0)
5635 n = l->lv_len + n;
5637 /* Check for index out of range. */
5638 if (n < 0 || n >= l->lv_len)
5639 return NULL;
5641 /* When there is a cached index may start search from there. */
5642 if (l->lv_idx_item != NULL)
5644 if (n < l->lv_idx / 2)
5646 /* closest to the start of the list */
5647 item = l->lv_first;
5648 idx = 0;
5650 else if (n > (l->lv_idx + l->lv_len) / 2)
5652 /* closest to the end of the list */
5653 item = l->lv_last;
5654 idx = l->lv_len - 1;
5656 else
5658 /* closest to the cached index */
5659 item = l->lv_idx_item;
5660 idx = l->lv_idx;
5663 else
5665 if (n < l->lv_len / 2)
5667 /* closest to the start of the list */
5668 item = l->lv_first;
5669 idx = 0;
5671 else
5673 /* closest to the end of the list */
5674 item = l->lv_last;
5675 idx = l->lv_len - 1;
5679 while (n > idx)
5681 /* search forward */
5682 item = item->li_next;
5683 ++idx;
5685 while (n < idx)
5687 /* search backward */
5688 item = item->li_prev;
5689 --idx;
5692 /* cache the used index */
5693 l->lv_idx = idx;
5694 l->lv_idx_item = item;
5696 return item;
5700 * Get list item "l[idx]" as a number.
5702 static long
5703 list_find_nr(l, idx, errorp)
5704 list_T *l;
5705 long idx;
5706 int *errorp; /* set to TRUE when something wrong */
5708 listitem_T *li;
5710 li = list_find(l, idx);
5711 if (li == NULL)
5713 if (errorp != NULL)
5714 *errorp = TRUE;
5715 return -1L;
5717 return get_tv_number_chk(&li->li_tv, errorp);
5721 * Locate "item" list "l" and return its index.
5722 * Returns -1 when "item" is not in the list.
5724 static long
5725 list_idx_of_item(l, item)
5726 list_T *l;
5727 listitem_T *item;
5729 long idx = 0;
5730 listitem_T *li;
5732 if (l == NULL)
5733 return -1;
5734 idx = 0;
5735 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
5736 ++idx;
5737 if (li == NULL)
5738 return -1;
5739 return idx;
5743 * Append item "item" to the end of list "l".
5745 static void
5746 list_append(l, item)
5747 list_T *l;
5748 listitem_T *item;
5750 if (l->lv_last == NULL)
5752 /* empty list */
5753 l->lv_first = item;
5754 l->lv_last = item;
5755 item->li_prev = NULL;
5757 else
5759 l->lv_last->li_next = item;
5760 item->li_prev = l->lv_last;
5761 l->lv_last = item;
5763 ++l->lv_len;
5764 item->li_next = NULL;
5768 * Append typval_T "tv" to the end of list "l".
5769 * Return FAIL when out of memory.
5771 static int
5772 list_append_tv(l, tv)
5773 list_T *l;
5774 typval_T *tv;
5776 listitem_T *li = listitem_alloc();
5778 if (li == NULL)
5779 return FAIL;
5780 copy_tv(tv, &li->li_tv);
5781 list_append(l, li);
5782 return OK;
5786 * Add a dictionary to a list. Used by getqflist().
5787 * Return FAIL when out of memory.
5790 list_append_dict(list, dict)
5791 list_T *list;
5792 dict_T *dict;
5794 listitem_T *li = listitem_alloc();
5796 if (li == NULL)
5797 return FAIL;
5798 li->li_tv.v_type = VAR_DICT;
5799 li->li_tv.v_lock = 0;
5800 li->li_tv.vval.v_dict = dict;
5801 list_append(list, li);
5802 ++dict->dv_refcount;
5803 return OK;
5807 * Make a copy of "str" and append it as an item to list "l".
5808 * When "len" >= 0 use "str[len]".
5809 * Returns FAIL when out of memory.
5811 static int
5812 list_append_string(l, str, len)
5813 list_T *l;
5814 char_u *str;
5815 int len;
5817 listitem_T *li = listitem_alloc();
5819 if (li == NULL)
5820 return FAIL;
5821 list_append(l, li);
5822 li->li_tv.v_type = VAR_STRING;
5823 li->li_tv.v_lock = 0;
5824 if (str == NULL)
5825 li->li_tv.vval.v_string = NULL;
5826 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
5827 : vim_strsave(str))) == NULL)
5828 return FAIL;
5829 return OK;
5833 * Append "n" to list "l".
5834 * Returns FAIL when out of memory.
5836 static int
5837 list_append_number(l, n)
5838 list_T *l;
5839 varnumber_T n;
5841 listitem_T *li;
5843 li = listitem_alloc();
5844 if (li == NULL)
5845 return FAIL;
5846 li->li_tv.v_type = VAR_NUMBER;
5847 li->li_tv.v_lock = 0;
5848 li->li_tv.vval.v_number = n;
5849 list_append(l, li);
5850 return OK;
5854 * Insert typval_T "tv" in list "l" before "item".
5855 * If "item" is NULL append at the end.
5856 * Return FAIL when out of memory.
5858 static int
5859 list_insert_tv(l, tv, item)
5860 list_T *l;
5861 typval_T *tv;
5862 listitem_T *item;
5864 listitem_T *ni = listitem_alloc();
5866 if (ni == NULL)
5867 return FAIL;
5868 copy_tv(tv, &ni->li_tv);
5869 if (item == NULL)
5870 /* Append new item at end of list. */
5871 list_append(l, ni);
5872 else
5874 /* Insert new item before existing item. */
5875 ni->li_prev = item->li_prev;
5876 ni->li_next = item;
5877 if (item->li_prev == NULL)
5879 l->lv_first = ni;
5880 ++l->lv_idx;
5882 else
5884 item->li_prev->li_next = ni;
5885 l->lv_idx_item = NULL;
5887 item->li_prev = ni;
5888 ++l->lv_len;
5890 return OK;
5894 * Extend "l1" with "l2".
5895 * If "bef" is NULL append at the end, otherwise insert before this item.
5896 * Returns FAIL when out of memory.
5898 static int
5899 list_extend(l1, l2, bef)
5900 list_T *l1;
5901 list_T *l2;
5902 listitem_T *bef;
5904 listitem_T *item;
5906 for (item = l2->lv_first; item != NULL; item = item->li_next)
5907 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
5908 return FAIL;
5909 return OK;
5913 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
5914 * Return FAIL when out of memory.
5916 static int
5917 list_concat(l1, l2, tv)
5918 list_T *l1;
5919 list_T *l2;
5920 typval_T *tv;
5922 list_T *l;
5924 /* make a copy of the first list. */
5925 l = list_copy(l1, FALSE, 0);
5926 if (l == NULL)
5927 return FAIL;
5928 tv->v_type = VAR_LIST;
5929 tv->vval.v_list = l;
5931 /* append all items from the second list */
5932 return list_extend(l, l2, NULL);
5936 * Make a copy of list "orig". Shallow if "deep" is FALSE.
5937 * The refcount of the new list is set to 1.
5938 * See item_copy() for "copyID".
5939 * Returns NULL when out of memory.
5941 static list_T *
5942 list_copy(orig, deep, copyID)
5943 list_T *orig;
5944 int deep;
5945 int copyID;
5947 list_T *copy;
5948 listitem_T *item;
5949 listitem_T *ni;
5951 if (orig == NULL)
5952 return NULL;
5954 copy = list_alloc();
5955 if (copy != NULL)
5957 if (copyID != 0)
5959 /* Do this before adding the items, because one of the items may
5960 * refer back to this list. */
5961 orig->lv_copyID = copyID;
5962 orig->lv_copylist = copy;
5964 for (item = orig->lv_first; item != NULL && !got_int;
5965 item = item->li_next)
5967 ni = listitem_alloc();
5968 if (ni == NULL)
5969 break;
5970 if (deep)
5972 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
5974 vim_free(ni);
5975 break;
5978 else
5979 copy_tv(&item->li_tv, &ni->li_tv);
5980 list_append(copy, ni);
5982 ++copy->lv_refcount;
5983 if (item != NULL)
5985 list_unref(copy);
5986 copy = NULL;
5990 return copy;
5994 * Remove items "item" to "item2" from list "l".
5995 * Does not free the listitem or the value!
5997 static void
5998 list_remove(l, item, item2)
5999 list_T *l;
6000 listitem_T *item;
6001 listitem_T *item2;
6003 listitem_T *ip;
6005 /* notify watchers */
6006 for (ip = item; ip != NULL; ip = ip->li_next)
6008 --l->lv_len;
6009 list_fix_watch(l, ip);
6010 if (ip == item2)
6011 break;
6014 if (item2->li_next == NULL)
6015 l->lv_last = item->li_prev;
6016 else
6017 item2->li_next->li_prev = item->li_prev;
6018 if (item->li_prev == NULL)
6019 l->lv_first = item2->li_next;
6020 else
6021 item->li_prev->li_next = item2->li_next;
6022 l->lv_idx_item = NULL;
6026 * Return an allocated string with the string representation of a list.
6027 * May return NULL.
6029 static char_u *
6030 list2string(tv, copyID)
6031 typval_T *tv;
6032 int copyID;
6034 garray_T ga;
6036 if (tv->vval.v_list == NULL)
6037 return NULL;
6038 ga_init2(&ga, (int)sizeof(char), 80);
6039 ga_append(&ga, '[');
6040 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6042 vim_free(ga.ga_data);
6043 return NULL;
6045 ga_append(&ga, ']');
6046 ga_append(&ga, NUL);
6047 return (char_u *)ga.ga_data;
6051 * Join list "l" into a string in "*gap", using separator "sep".
6052 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6053 * Return FAIL or OK.
6055 static int
6056 list_join(gap, l, sep, echo, copyID)
6057 garray_T *gap;
6058 list_T *l;
6059 char_u *sep;
6060 int echo;
6061 int copyID;
6063 int first = TRUE;
6064 char_u *tofree;
6065 char_u numbuf[NUMBUFLEN];
6066 listitem_T *item;
6067 char_u *s;
6069 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6071 if (first)
6072 first = FALSE;
6073 else
6074 ga_concat(gap, sep);
6076 if (echo)
6077 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6078 else
6079 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6080 if (s != NULL)
6081 ga_concat(gap, s);
6082 vim_free(tofree);
6083 if (s == NULL)
6084 return FAIL;
6086 return OK;
6090 * Garbage collection for lists and dictionaries.
6092 * We use reference counts to be able to free most items right away when they
6093 * are no longer used. But for composite items it's possible that it becomes
6094 * unused while the reference count is > 0: When there is a recursive
6095 * reference. Example:
6096 * :let l = [1, 2, 3]
6097 * :let d = {9: l}
6098 * :let l[1] = d
6100 * Since this is quite unusual we handle this with garbage collection: every
6101 * once in a while find out which lists and dicts are not referenced from any
6102 * variable.
6104 * Here is a good reference text about garbage collection (refers to Python
6105 * but it applies to all reference-counting mechanisms):
6106 * http://python.ca/nas/python/gc/
6110 * Do garbage collection for lists and dicts.
6111 * Return TRUE if some memory was freed.
6114 garbage_collect()
6116 dict_T *dd;
6117 list_T *ll;
6118 int copyID = ++current_copyID;
6119 buf_T *buf;
6120 win_T *wp;
6121 int i;
6122 funccall_T *fc;
6123 int did_free = FALSE;
6124 #ifdef FEAT_WINDOWS
6125 tabpage_T *tp;
6126 #endif
6128 /* Only do this once. */
6129 want_garbage_collect = FALSE;
6130 may_garbage_collect = FALSE;
6131 garbage_collect_at_exit = FALSE;
6134 * 1. Go through all accessible variables and mark all lists and dicts
6135 * with copyID.
6137 /* script-local variables */
6138 for (i = 1; i <= ga_scripts.ga_len; ++i)
6139 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6141 /* buffer-local variables */
6142 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6143 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6145 /* window-local variables */
6146 FOR_ALL_TAB_WINDOWS(tp, wp)
6147 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6149 #ifdef FEAT_WINDOWS
6150 /* tabpage-local variables */
6151 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6152 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6153 #endif
6155 /* global variables */
6156 set_ref_in_ht(&globvarht, copyID);
6158 /* function-local variables */
6159 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6161 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6162 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6166 * 2. Go through the list of dicts and free items without the copyID.
6168 for (dd = first_dict; dd != NULL; )
6169 if (dd->dv_copyID != copyID)
6171 /* Free the Dictionary and ordinary items it contains, but don't
6172 * recurse into Lists and Dictionaries, they will be in the list
6173 * of dicts or list of lists. */
6174 dict_free(dd, FALSE);
6175 did_free = TRUE;
6177 /* restart, next dict may also have been freed */
6178 dd = first_dict;
6180 else
6181 dd = dd->dv_used_next;
6184 * 3. Go through the list of lists and free items without the copyID.
6185 * But don't free a list that has a watcher (used in a for loop), these
6186 * are not referenced anywhere.
6188 for (ll = first_list; ll != NULL; )
6189 if (ll->lv_copyID != copyID && ll->lv_watch == NULL)
6191 /* Free the List and ordinary items it contains, but don't recurse
6192 * into Lists and Dictionaries, they will be in the list of dicts
6193 * or list of lists. */
6194 list_free(ll, FALSE);
6195 did_free = TRUE;
6197 /* restart, next list may also have been freed */
6198 ll = first_list;
6200 else
6201 ll = ll->lv_used_next;
6203 return did_free;
6207 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6209 static void
6210 set_ref_in_ht(ht, copyID)
6211 hashtab_T *ht;
6212 int copyID;
6214 int todo;
6215 hashitem_T *hi;
6217 todo = (int)ht->ht_used;
6218 for (hi = ht->ht_array; todo > 0; ++hi)
6219 if (!HASHITEM_EMPTY(hi))
6221 --todo;
6222 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6227 * Mark all lists and dicts referenced through list "l" with "copyID".
6229 static void
6230 set_ref_in_list(l, copyID)
6231 list_T *l;
6232 int copyID;
6234 listitem_T *li;
6236 for (li = l->lv_first; li != NULL; li = li->li_next)
6237 set_ref_in_item(&li->li_tv, copyID);
6241 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6243 static void
6244 set_ref_in_item(tv, copyID)
6245 typval_T *tv;
6246 int copyID;
6248 dict_T *dd;
6249 list_T *ll;
6251 switch (tv->v_type)
6253 case VAR_DICT:
6254 dd = tv->vval.v_dict;
6255 if (dd->dv_copyID != copyID)
6257 /* Didn't see this dict yet. */
6258 dd->dv_copyID = copyID;
6259 set_ref_in_ht(&dd->dv_hashtab, copyID);
6261 break;
6263 case VAR_LIST:
6264 ll = tv->vval.v_list;
6265 if (ll->lv_copyID != copyID)
6267 /* Didn't see this list yet. */
6268 ll->lv_copyID = copyID;
6269 set_ref_in_list(ll, copyID);
6271 break;
6273 return;
6277 * Allocate an empty header for a dictionary.
6279 dict_T *
6280 dict_alloc()
6282 dict_T *d;
6284 d = (dict_T *)alloc(sizeof(dict_T));
6285 if (d != NULL)
6287 /* Add the list to the list of dicts for garbage collection. */
6288 if (first_dict != NULL)
6289 first_dict->dv_used_prev = d;
6290 d->dv_used_next = first_dict;
6291 d->dv_used_prev = NULL;
6292 first_dict = d;
6294 hash_init(&d->dv_hashtab);
6295 d->dv_lock = 0;
6296 d->dv_refcount = 0;
6297 d->dv_copyID = 0;
6299 return d;
6303 * Unreference a Dictionary: decrement the reference count and free it when it
6304 * becomes zero.
6306 static void
6307 dict_unref(d)
6308 dict_T *d;
6310 if (d != NULL && --d->dv_refcount <= 0)
6311 dict_free(d, TRUE);
6315 * Free a Dictionary, including all items it contains.
6316 * Ignores the reference count.
6318 static void
6319 dict_free(d, recurse)
6320 dict_T *d;
6321 int recurse; /* Free Lists and Dictionaries recursively. */
6323 int todo;
6324 hashitem_T *hi;
6325 dictitem_T *di;
6327 /* Remove the dict from the list of dicts for garbage collection. */
6328 if (d->dv_used_prev == NULL)
6329 first_dict = d->dv_used_next;
6330 else
6331 d->dv_used_prev->dv_used_next = d->dv_used_next;
6332 if (d->dv_used_next != NULL)
6333 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6335 /* Lock the hashtab, we don't want it to resize while freeing items. */
6336 hash_lock(&d->dv_hashtab);
6337 todo = (int)d->dv_hashtab.ht_used;
6338 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6340 if (!HASHITEM_EMPTY(hi))
6342 /* Remove the item before deleting it, just in case there is
6343 * something recursive causing trouble. */
6344 di = HI2DI(hi);
6345 hash_remove(&d->dv_hashtab, hi);
6346 if (recurse || (di->di_tv.v_type != VAR_LIST
6347 && di->di_tv.v_type != VAR_DICT))
6348 clear_tv(&di->di_tv);
6349 vim_free(di);
6350 --todo;
6353 hash_clear(&d->dv_hashtab);
6354 vim_free(d);
6358 * Allocate a Dictionary item.
6359 * The "key" is copied to the new item.
6360 * Note that the value of the item "di_tv" still needs to be initialized!
6361 * Returns NULL when out of memory.
6363 static dictitem_T *
6364 dictitem_alloc(key)
6365 char_u *key;
6367 dictitem_T *di;
6369 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6370 if (di != NULL)
6372 STRCPY(di->di_key, key);
6373 di->di_flags = 0;
6375 return di;
6379 * Make a copy of a Dictionary item.
6381 static dictitem_T *
6382 dictitem_copy(org)
6383 dictitem_T *org;
6385 dictitem_T *di;
6387 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6388 + STRLEN(org->di_key)));
6389 if (di != NULL)
6391 STRCPY(di->di_key, org->di_key);
6392 di->di_flags = 0;
6393 copy_tv(&org->di_tv, &di->di_tv);
6395 return di;
6399 * Remove item "item" from Dictionary "dict" and free it.
6401 static void
6402 dictitem_remove(dict, item)
6403 dict_T *dict;
6404 dictitem_T *item;
6406 hashitem_T *hi;
6408 hi = hash_find(&dict->dv_hashtab, item->di_key);
6409 if (HASHITEM_EMPTY(hi))
6410 EMSG2(_(e_intern2), "dictitem_remove()");
6411 else
6412 hash_remove(&dict->dv_hashtab, hi);
6413 dictitem_free(item);
6417 * Free a dict item. Also clears the value.
6419 static void
6420 dictitem_free(item)
6421 dictitem_T *item;
6423 clear_tv(&item->di_tv);
6424 vim_free(item);
6428 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6429 * The refcount of the new dict is set to 1.
6430 * See item_copy() for "copyID".
6431 * Returns NULL when out of memory.
6433 static dict_T *
6434 dict_copy(orig, deep, copyID)
6435 dict_T *orig;
6436 int deep;
6437 int copyID;
6439 dict_T *copy;
6440 dictitem_T *di;
6441 int todo;
6442 hashitem_T *hi;
6444 if (orig == NULL)
6445 return NULL;
6447 copy = dict_alloc();
6448 if (copy != NULL)
6450 if (copyID != 0)
6452 orig->dv_copyID = copyID;
6453 orig->dv_copydict = copy;
6455 todo = (int)orig->dv_hashtab.ht_used;
6456 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6458 if (!HASHITEM_EMPTY(hi))
6460 --todo;
6462 di = dictitem_alloc(hi->hi_key);
6463 if (di == NULL)
6464 break;
6465 if (deep)
6467 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6468 copyID) == FAIL)
6470 vim_free(di);
6471 break;
6474 else
6475 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6476 if (dict_add(copy, di) == FAIL)
6478 dictitem_free(di);
6479 break;
6484 ++copy->dv_refcount;
6485 if (todo > 0)
6487 dict_unref(copy);
6488 copy = NULL;
6492 return copy;
6496 * Add item "item" to Dictionary "d".
6497 * Returns FAIL when out of memory and when key already existed.
6499 static int
6500 dict_add(d, item)
6501 dict_T *d;
6502 dictitem_T *item;
6504 return hash_add(&d->dv_hashtab, item->di_key);
6508 * Add a number or string entry to dictionary "d".
6509 * When "str" is NULL use number "nr", otherwise use "str".
6510 * Returns FAIL when out of memory and when key already exists.
6513 dict_add_nr_str(d, key, nr, str)
6514 dict_T *d;
6515 char *key;
6516 long nr;
6517 char_u *str;
6519 dictitem_T *item;
6521 item = dictitem_alloc((char_u *)key);
6522 if (item == NULL)
6523 return FAIL;
6524 item->di_tv.v_lock = 0;
6525 if (str == NULL)
6527 item->di_tv.v_type = VAR_NUMBER;
6528 item->di_tv.vval.v_number = nr;
6530 else
6532 item->di_tv.v_type = VAR_STRING;
6533 item->di_tv.vval.v_string = vim_strsave(str);
6535 if (dict_add(d, item) == FAIL)
6537 dictitem_free(item);
6538 return FAIL;
6540 return OK;
6544 * Get the number of items in a Dictionary.
6546 static long
6547 dict_len(d)
6548 dict_T *d;
6550 if (d == NULL)
6551 return 0L;
6552 return (long)d->dv_hashtab.ht_used;
6556 * Find item "key[len]" in Dictionary "d".
6557 * If "len" is negative use strlen(key).
6558 * Returns NULL when not found.
6560 static dictitem_T *
6561 dict_find(d, key, len)
6562 dict_T *d;
6563 char_u *key;
6564 int len;
6566 #define AKEYLEN 200
6567 char_u buf[AKEYLEN];
6568 char_u *akey;
6569 char_u *tofree = NULL;
6570 hashitem_T *hi;
6572 if (len < 0)
6573 akey = key;
6574 else if (len >= AKEYLEN)
6576 tofree = akey = vim_strnsave(key, len);
6577 if (akey == NULL)
6578 return NULL;
6580 else
6582 /* Avoid a malloc/free by using buf[]. */
6583 vim_strncpy(buf, key, len);
6584 akey = buf;
6587 hi = hash_find(&d->dv_hashtab, akey);
6588 vim_free(tofree);
6589 if (HASHITEM_EMPTY(hi))
6590 return NULL;
6591 return HI2DI(hi);
6595 * Get a string item from a dictionary.
6596 * When "save" is TRUE allocate memory for it.
6597 * Returns NULL if the entry doesn't exist or out of memory.
6599 char_u *
6600 get_dict_string(d, key, save)
6601 dict_T *d;
6602 char_u *key;
6603 int save;
6605 dictitem_T *di;
6606 char_u *s;
6608 di = dict_find(d, key, -1);
6609 if (di == NULL)
6610 return NULL;
6611 s = get_tv_string(&di->di_tv);
6612 if (save && s != NULL)
6613 s = vim_strsave(s);
6614 return s;
6618 * Get a number item from a dictionary.
6619 * Returns 0 if the entry doesn't exist or out of memory.
6621 long
6622 get_dict_number(d, key)
6623 dict_T *d;
6624 char_u *key;
6626 dictitem_T *di;
6628 di = dict_find(d, key, -1);
6629 if (di == NULL)
6630 return 0;
6631 return get_tv_number(&di->di_tv);
6635 * Return an allocated string with the string representation of a Dictionary.
6636 * May return NULL.
6638 static char_u *
6639 dict2string(tv, copyID)
6640 typval_T *tv;
6641 int copyID;
6643 garray_T ga;
6644 int first = TRUE;
6645 char_u *tofree;
6646 char_u numbuf[NUMBUFLEN];
6647 hashitem_T *hi;
6648 char_u *s;
6649 dict_T *d;
6650 int todo;
6652 if ((d = tv->vval.v_dict) == NULL)
6653 return NULL;
6654 ga_init2(&ga, (int)sizeof(char), 80);
6655 ga_append(&ga, '{');
6657 todo = (int)d->dv_hashtab.ht_used;
6658 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6660 if (!HASHITEM_EMPTY(hi))
6662 --todo;
6664 if (first)
6665 first = FALSE;
6666 else
6667 ga_concat(&ga, (char_u *)", ");
6669 tofree = string_quote(hi->hi_key, FALSE);
6670 if (tofree != NULL)
6672 ga_concat(&ga, tofree);
6673 vim_free(tofree);
6675 ga_concat(&ga, (char_u *)": ");
6676 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
6677 if (s != NULL)
6678 ga_concat(&ga, s);
6679 vim_free(tofree);
6680 if (s == NULL)
6681 break;
6684 if (todo > 0)
6686 vim_free(ga.ga_data);
6687 return NULL;
6690 ga_append(&ga, '}');
6691 ga_append(&ga, NUL);
6692 return (char_u *)ga.ga_data;
6696 * Allocate a variable for a Dictionary and fill it from "*arg".
6697 * Return OK or FAIL. Returns NOTDONE for {expr}.
6699 static int
6700 get_dict_tv(arg, rettv, evaluate)
6701 char_u **arg;
6702 typval_T *rettv;
6703 int evaluate;
6705 dict_T *d = NULL;
6706 typval_T tvkey;
6707 typval_T tv;
6708 char_u *key = NULL;
6709 dictitem_T *item;
6710 char_u *start = skipwhite(*arg + 1);
6711 char_u buf[NUMBUFLEN];
6714 * First check if it's not a curly-braces thing: {expr}.
6715 * Must do this without evaluating, otherwise a function may be called
6716 * twice. Unfortunately this means we need to call eval1() twice for the
6717 * first item.
6718 * But {} is an empty Dictionary.
6720 if (*start != '}')
6722 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
6723 return FAIL;
6724 if (*start == '}')
6725 return NOTDONE;
6728 if (evaluate)
6730 d = dict_alloc();
6731 if (d == NULL)
6732 return FAIL;
6734 tvkey.v_type = VAR_UNKNOWN;
6735 tv.v_type = VAR_UNKNOWN;
6737 *arg = skipwhite(*arg + 1);
6738 while (**arg != '}' && **arg != NUL)
6740 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
6741 goto failret;
6742 if (**arg != ':')
6744 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
6745 clear_tv(&tvkey);
6746 goto failret;
6748 if (evaluate)
6750 key = get_tv_string_buf_chk(&tvkey, buf);
6751 if (key == NULL || *key == NUL)
6753 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
6754 if (key != NULL)
6755 EMSG(_(e_emptykey));
6756 clear_tv(&tvkey);
6757 goto failret;
6761 *arg = skipwhite(*arg + 1);
6762 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
6764 if (evaluate)
6765 clear_tv(&tvkey);
6766 goto failret;
6768 if (evaluate)
6770 item = dict_find(d, key, -1);
6771 if (item != NULL)
6773 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
6774 clear_tv(&tvkey);
6775 clear_tv(&tv);
6776 goto failret;
6778 item = dictitem_alloc(key);
6779 clear_tv(&tvkey);
6780 if (item != NULL)
6782 item->di_tv = tv;
6783 item->di_tv.v_lock = 0;
6784 if (dict_add(d, item) == FAIL)
6785 dictitem_free(item);
6789 if (**arg == '}')
6790 break;
6791 if (**arg != ',')
6793 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
6794 goto failret;
6796 *arg = skipwhite(*arg + 1);
6799 if (**arg != '}')
6801 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
6802 failret:
6803 if (evaluate)
6804 dict_free(d, TRUE);
6805 return FAIL;
6808 *arg = skipwhite(*arg + 1);
6809 if (evaluate)
6811 rettv->v_type = VAR_DICT;
6812 rettv->vval.v_dict = d;
6813 ++d->dv_refcount;
6816 return OK;
6820 * Return a string with the string representation of a variable.
6821 * If the memory is allocated "tofree" is set to it, otherwise NULL.
6822 * "numbuf" is used for a number.
6823 * Does not put quotes around strings, as ":echo" displays values.
6824 * When "copyID" is not NULL replace recursive lists and dicts with "...".
6825 * May return NULL.
6827 static char_u *
6828 echo_string(tv, tofree, numbuf, copyID)
6829 typval_T *tv;
6830 char_u **tofree;
6831 char_u *numbuf;
6832 int copyID;
6834 static int recurse = 0;
6835 char_u *r = NULL;
6837 if (recurse >= DICT_MAXNEST)
6839 EMSG(_("E724: variable nested too deep for displaying"));
6840 *tofree = NULL;
6841 return NULL;
6843 ++recurse;
6845 switch (tv->v_type)
6847 case VAR_FUNC:
6848 *tofree = NULL;
6849 r = tv->vval.v_string;
6850 break;
6852 case VAR_LIST:
6853 if (tv->vval.v_list == NULL)
6855 *tofree = NULL;
6856 r = NULL;
6858 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
6860 *tofree = NULL;
6861 r = (char_u *)"[...]";
6863 else
6865 tv->vval.v_list->lv_copyID = copyID;
6866 *tofree = list2string(tv, copyID);
6867 r = *tofree;
6869 break;
6871 case VAR_DICT:
6872 if (tv->vval.v_dict == NULL)
6874 *tofree = NULL;
6875 r = NULL;
6877 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
6879 *tofree = NULL;
6880 r = (char_u *)"{...}";
6882 else
6884 tv->vval.v_dict->dv_copyID = copyID;
6885 *tofree = dict2string(tv, copyID);
6886 r = *tofree;
6888 break;
6890 case VAR_STRING:
6891 case VAR_NUMBER:
6892 *tofree = NULL;
6893 r = get_tv_string_buf(tv, numbuf);
6894 break;
6896 default:
6897 EMSG2(_(e_intern2), "echo_string()");
6898 *tofree = NULL;
6901 --recurse;
6902 return r;
6906 * Return a string with the string representation of a variable.
6907 * If the memory is allocated "tofree" is set to it, otherwise NULL.
6908 * "numbuf" is used for a number.
6909 * Puts quotes around strings, so that they can be parsed back by eval().
6910 * May return NULL.
6912 static char_u *
6913 tv2string(tv, tofree, numbuf, copyID)
6914 typval_T *tv;
6915 char_u **tofree;
6916 char_u *numbuf;
6917 int copyID;
6919 switch (tv->v_type)
6921 case VAR_FUNC:
6922 *tofree = string_quote(tv->vval.v_string, TRUE);
6923 return *tofree;
6924 case VAR_STRING:
6925 *tofree = string_quote(tv->vval.v_string, FALSE);
6926 return *tofree;
6927 case VAR_NUMBER:
6928 case VAR_LIST:
6929 case VAR_DICT:
6930 break;
6931 default:
6932 EMSG2(_(e_intern2), "tv2string()");
6934 return echo_string(tv, tofree, numbuf, copyID);
6938 * Return string "str" in ' quotes, doubling ' characters.
6939 * If "str" is NULL an empty string is assumed.
6940 * If "function" is TRUE make it function('string').
6942 static char_u *
6943 string_quote(str, function)
6944 char_u *str;
6945 int function;
6947 unsigned len;
6948 char_u *p, *r, *s;
6950 len = (function ? 13 : 3);
6951 if (str != NULL)
6953 len += (unsigned)STRLEN(str);
6954 for (p = str; *p != NUL; mb_ptr_adv(p))
6955 if (*p == '\'')
6956 ++len;
6958 s = r = alloc(len);
6959 if (r != NULL)
6961 if (function)
6963 STRCPY(r, "function('");
6964 r += 10;
6966 else
6967 *r++ = '\'';
6968 if (str != NULL)
6969 for (p = str; *p != NUL; )
6971 if (*p == '\'')
6972 *r++ = '\'';
6973 MB_COPY_CHAR(p, r);
6975 *r++ = '\'';
6976 if (function)
6977 *r++ = ')';
6978 *r++ = NUL;
6980 return s;
6984 * Get the value of an environment variable.
6985 * "arg" is pointing to the '$'. It is advanced to after the name.
6986 * If the environment variable was not set, silently assume it is empty.
6987 * Always return OK.
6989 static int
6990 get_env_tv(arg, rettv, evaluate)
6991 char_u **arg;
6992 typval_T *rettv;
6993 int evaluate;
6995 char_u *string = NULL;
6996 int len;
6997 int cc;
6998 char_u *name;
6999 int mustfree = FALSE;
7001 ++*arg;
7002 name = *arg;
7003 len = get_env_len(arg);
7004 if (evaluate)
7006 if (len != 0)
7008 cc = name[len];
7009 name[len] = NUL;
7010 /* first try vim_getenv(), fast for normal environment vars */
7011 string = vim_getenv(name, &mustfree);
7012 if (string != NULL && *string != NUL)
7014 if (!mustfree)
7015 string = vim_strsave(string);
7017 else
7019 if (mustfree)
7020 vim_free(string);
7022 /* next try expanding things like $VIM and ${HOME} */
7023 string = expand_env_save(name - 1);
7024 if (string != NULL && *string == '$')
7026 vim_free(string);
7027 string = NULL;
7030 name[len] = cc;
7032 rettv->v_type = VAR_STRING;
7033 rettv->vval.v_string = string;
7036 return OK;
7040 * Array with names and number of arguments of all internal functions
7041 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7043 static struct fst
7045 char *f_name; /* function name */
7046 char f_min_argc; /* minimal number of arguments */
7047 char f_max_argc; /* maximal number of arguments */
7048 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7049 /* implementation of function */
7050 } functions[] =
7052 {"add", 2, 2, f_add},
7053 {"append", 2, 2, f_append},
7054 {"argc", 0, 0, f_argc},
7055 {"argidx", 0, 0, f_argidx},
7056 {"argv", 0, 1, f_argv},
7057 {"browse", 4, 4, f_browse},
7058 {"browsedir", 2, 2, f_browsedir},
7059 {"bufexists", 1, 1, f_bufexists},
7060 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7061 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7062 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7063 {"buflisted", 1, 1, f_buflisted},
7064 {"bufloaded", 1, 1, f_bufloaded},
7065 {"bufname", 1, 1, f_bufname},
7066 {"bufnr", 1, 2, f_bufnr},
7067 {"bufwinnr", 1, 1, f_bufwinnr},
7068 {"byte2line", 1, 1, f_byte2line},
7069 {"byteidx", 2, 2, f_byteidx},
7070 {"call", 2, 3, f_call},
7071 {"changenr", 0, 0, f_changenr},
7072 {"char2nr", 1, 1, f_char2nr},
7073 {"cindent", 1, 1, f_cindent},
7074 {"clearmatches", 0, 0, f_clearmatches},
7075 {"col", 1, 1, f_col},
7076 #if defined(FEAT_INS_EXPAND)
7077 {"complete", 2, 2, f_complete},
7078 {"complete_add", 1, 1, f_complete_add},
7079 {"complete_check", 0, 0, f_complete_check},
7080 #endif
7081 {"confirm", 1, 4, f_confirm},
7082 {"copy", 1, 1, f_copy},
7083 {"count", 2, 4, f_count},
7084 {"cscope_connection",0,3, f_cscope_connection},
7085 {"cursor", 1, 3, f_cursor},
7086 {"deepcopy", 1, 2, f_deepcopy},
7087 {"delete", 1, 1, f_delete},
7088 {"did_filetype", 0, 0, f_did_filetype},
7089 {"diff_filler", 1, 1, f_diff_filler},
7090 {"diff_hlID", 2, 2, f_diff_hlID},
7091 {"empty", 1, 1, f_empty},
7092 {"escape", 2, 2, f_escape},
7093 {"eval", 1, 1, f_eval},
7094 {"eventhandler", 0, 0, f_eventhandler},
7095 {"executable", 1, 1, f_executable},
7096 {"exists", 1, 1, f_exists},
7097 {"expand", 1, 2, f_expand},
7098 {"extend", 2, 3, f_extend},
7099 {"feedkeys", 1, 2, f_feedkeys},
7100 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7101 {"filereadable", 1, 1, f_filereadable},
7102 {"filewritable", 1, 1, f_filewritable},
7103 {"filter", 2, 2, f_filter},
7104 {"finddir", 1, 3, f_finddir},
7105 {"findfile", 1, 3, f_findfile},
7106 {"fnamemodify", 2, 2, f_fnamemodify},
7107 {"foldclosed", 1, 1, f_foldclosed},
7108 {"foldclosedend", 1, 1, f_foldclosedend},
7109 {"foldlevel", 1, 1, f_foldlevel},
7110 {"foldtext", 0, 0, f_foldtext},
7111 {"foldtextresult", 1, 1, f_foldtextresult},
7112 {"foreground", 0, 0, f_foreground},
7113 {"function", 1, 1, f_function},
7114 {"garbagecollect", 0, 1, f_garbagecollect},
7115 {"get", 2, 3, f_get},
7116 {"getbufline", 2, 3, f_getbufline},
7117 {"getbufvar", 2, 2, f_getbufvar},
7118 {"getchar", 0, 1, f_getchar},
7119 {"getcharmod", 0, 0, f_getcharmod},
7120 {"getcmdline", 0, 0, f_getcmdline},
7121 {"getcmdpos", 0, 0, f_getcmdpos},
7122 {"getcmdtype", 0, 0, f_getcmdtype},
7123 {"getcwd", 0, 0, f_getcwd},
7124 {"getfontname", 0, 1, f_getfontname},
7125 {"getfperm", 1, 1, f_getfperm},
7126 {"getfsize", 1, 1, f_getfsize},
7127 {"getftime", 1, 1, f_getftime},
7128 {"getftype", 1, 1, f_getftype},
7129 {"getline", 1, 2, f_getline},
7130 {"getloclist", 1, 1, f_getqflist},
7131 {"getmatches", 0, 0, f_getmatches},
7132 {"getpos", 1, 1, f_getpos},
7133 {"getqflist", 0, 0, f_getqflist},
7134 {"getreg", 0, 2, f_getreg},
7135 {"getregtype", 0, 1, f_getregtype},
7136 {"gettabwinvar", 3, 3, f_gettabwinvar},
7137 {"getwinposx", 0, 0, f_getwinposx},
7138 {"getwinposy", 0, 0, f_getwinposy},
7139 {"getwinvar", 2, 2, f_getwinvar},
7140 {"glob", 1, 1, f_glob},
7141 {"globpath", 2, 2, f_globpath},
7142 {"has", 1, 1, f_has},
7143 {"has_key", 2, 2, f_has_key},
7144 {"haslocaldir", 0, 0, f_haslocaldir},
7145 {"hasmapto", 1, 3, f_hasmapto},
7146 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7147 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7148 {"histadd", 2, 2, f_histadd},
7149 {"histdel", 1, 2, f_histdel},
7150 {"histget", 1, 2, f_histget},
7151 {"histnr", 1, 1, f_histnr},
7152 {"hlID", 1, 1, f_hlID},
7153 {"hlexists", 1, 1, f_hlexists},
7154 {"hostname", 0, 0, f_hostname},
7155 {"iconv", 3, 3, f_iconv},
7156 {"indent", 1, 1, f_indent},
7157 {"index", 2, 4, f_index},
7158 {"input", 1, 3, f_input},
7159 {"inputdialog", 1, 3, f_inputdialog},
7160 {"inputlist", 1, 1, f_inputlist},
7161 {"inputrestore", 0, 0, f_inputrestore},
7162 {"inputsave", 0, 0, f_inputsave},
7163 {"inputsecret", 1, 2, f_inputsecret},
7164 {"insert", 2, 3, f_insert},
7165 {"isdirectory", 1, 1, f_isdirectory},
7166 {"islocked", 1, 1, f_islocked},
7167 {"items", 1, 1, f_items},
7168 {"join", 1, 2, f_join},
7169 {"keys", 1, 1, f_keys},
7170 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7171 {"len", 1, 1, f_len},
7172 {"libcall", 3, 3, f_libcall},
7173 {"libcallnr", 3, 3, f_libcallnr},
7174 {"line", 1, 1, f_line},
7175 {"line2byte", 1, 1, f_line2byte},
7176 {"lispindent", 1, 1, f_lispindent},
7177 {"localtime", 0, 0, f_localtime},
7178 {"map", 2, 2, f_map},
7179 {"maparg", 1, 3, f_maparg},
7180 {"mapcheck", 1, 3, f_mapcheck},
7181 {"match", 2, 4, f_match},
7182 {"matchadd", 2, 4, f_matchadd},
7183 {"matcharg", 1, 1, f_matcharg},
7184 {"matchdelete", 1, 1, f_matchdelete},
7185 {"matchend", 2, 4, f_matchend},
7186 {"matchlist", 2, 4, f_matchlist},
7187 {"matchstr", 2, 4, f_matchstr},
7188 {"max", 1, 1, f_max},
7189 {"min", 1, 1, f_min},
7190 #ifdef vim_mkdir
7191 {"mkdir", 1, 3, f_mkdir},
7192 #endif
7193 {"mode", 0, 0, f_mode},
7194 {"nextnonblank", 1, 1, f_nextnonblank},
7195 {"nr2char", 1, 1, f_nr2char},
7196 {"pathshorten", 1, 1, f_pathshorten},
7197 {"prevnonblank", 1, 1, f_prevnonblank},
7198 {"printf", 2, 19, f_printf},
7199 {"pumvisible", 0, 0, f_pumvisible},
7200 {"range", 1, 3, f_range},
7201 {"readfile", 1, 3, f_readfile},
7202 {"reltime", 0, 2, f_reltime},
7203 {"reltimestr", 1, 1, f_reltimestr},
7204 {"remote_expr", 2, 3, f_remote_expr},
7205 {"remote_foreground", 1, 1, f_remote_foreground},
7206 {"remote_peek", 1, 2, f_remote_peek},
7207 {"remote_read", 1, 1, f_remote_read},
7208 {"remote_send", 2, 3, f_remote_send},
7209 {"remove", 2, 3, f_remove},
7210 {"rename", 2, 2, f_rename},
7211 {"repeat", 2, 2, f_repeat},
7212 {"resolve", 1, 1, f_resolve},
7213 {"reverse", 1, 1, f_reverse},
7214 {"search", 1, 3, f_search},
7215 {"searchdecl", 1, 3, f_searchdecl},
7216 {"searchpair", 3, 6, f_searchpair},
7217 {"searchpairpos", 3, 6, f_searchpairpos},
7218 {"searchpos", 1, 3, f_searchpos},
7219 {"server2client", 2, 2, f_server2client},
7220 {"serverlist", 0, 0, f_serverlist},
7221 {"setbufvar", 3, 3, f_setbufvar},
7222 {"setcmdpos", 1, 1, f_setcmdpos},
7223 {"setline", 2, 2, f_setline},
7224 {"setloclist", 2, 3, f_setloclist},
7225 {"setmatches", 1, 1, f_setmatches},
7226 {"setpos", 2, 2, f_setpos},
7227 {"setqflist", 1, 2, f_setqflist},
7228 {"setreg", 2, 3, f_setreg},
7229 {"settabwinvar", 4, 4, f_settabwinvar},
7230 {"setwinvar", 3, 3, f_setwinvar},
7231 {"shellescape", 1, 1, f_shellescape},
7232 {"simplify", 1, 1, f_simplify},
7233 {"sort", 1, 2, f_sort},
7234 {"soundfold", 1, 1, f_soundfold},
7235 {"spellbadword", 0, 1, f_spellbadword},
7236 {"spellsuggest", 1, 3, f_spellsuggest},
7237 {"split", 1, 3, f_split},
7238 {"str2nr", 1, 2, f_str2nr},
7239 #ifdef HAVE_STRFTIME
7240 {"strftime", 1, 2, f_strftime},
7241 #endif
7242 {"stridx", 2, 3, f_stridx},
7243 {"string", 1, 1, f_string},
7244 {"strlen", 1, 1, f_strlen},
7245 {"strpart", 2, 3, f_strpart},
7246 {"strridx", 2, 3, f_strridx},
7247 {"strtrans", 1, 1, f_strtrans},
7248 {"submatch", 1, 1, f_submatch},
7249 {"substitute", 4, 4, f_substitute},
7250 {"synID", 3, 3, f_synID},
7251 {"synIDattr", 2, 3, f_synIDattr},
7252 {"synIDtrans", 1, 1, f_synIDtrans},
7253 {"system", 1, 2, f_system},
7254 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7255 {"tabpagenr", 0, 1, f_tabpagenr},
7256 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7257 {"tagfiles", 0, 0, f_tagfiles},
7258 {"taglist", 1, 1, f_taglist},
7259 {"tempname", 0, 0, f_tempname},
7260 {"test", 1, 1, f_test},
7261 {"tolower", 1, 1, f_tolower},
7262 {"toupper", 1, 1, f_toupper},
7263 {"tr", 3, 3, f_tr},
7264 {"type", 1, 1, f_type},
7265 {"values", 1, 1, f_values},
7266 {"virtcol", 1, 1, f_virtcol},
7267 {"visualmode", 0, 1, f_visualmode},
7268 {"winbufnr", 1, 1, f_winbufnr},
7269 {"wincol", 0, 0, f_wincol},
7270 {"winheight", 1, 1, f_winheight},
7271 {"winline", 0, 0, f_winline},
7272 {"winnr", 0, 1, f_winnr},
7273 {"winrestcmd", 0, 0, f_winrestcmd},
7274 {"winrestview", 1, 1, f_winrestview},
7275 {"winsaveview", 0, 0, f_winsaveview},
7276 {"winwidth", 1, 1, f_winwidth},
7277 {"writefile", 2, 3, f_writefile},
7280 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7283 * Function given to ExpandGeneric() to obtain the list of internal
7284 * or user defined function names.
7286 char_u *
7287 get_function_name(xp, idx)
7288 expand_T *xp;
7289 int idx;
7291 static int intidx = -1;
7292 char_u *name;
7294 if (idx == 0)
7295 intidx = -1;
7296 if (intidx < 0)
7298 name = get_user_func_name(xp, idx);
7299 if (name != NULL)
7300 return name;
7302 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7304 STRCPY(IObuff, functions[intidx].f_name);
7305 STRCAT(IObuff, "(");
7306 if (functions[intidx].f_max_argc == 0)
7307 STRCAT(IObuff, ")");
7308 return IObuff;
7311 return NULL;
7315 * Function given to ExpandGeneric() to obtain the list of internal or
7316 * user defined variable or function names.
7318 /*ARGSUSED*/
7319 char_u *
7320 get_expr_name(xp, idx)
7321 expand_T *xp;
7322 int idx;
7324 static int intidx = -1;
7325 char_u *name;
7327 if (idx == 0)
7328 intidx = -1;
7329 if (intidx < 0)
7331 name = get_function_name(xp, idx);
7332 if (name != NULL)
7333 return name;
7335 return get_user_var_name(xp, ++intidx);
7338 #endif /* FEAT_CMDL_COMPL */
7341 * Find internal function in table above.
7342 * Return index, or -1 if not found
7344 static int
7345 find_internal_func(name)
7346 char_u *name; /* name of the function */
7348 int first = 0;
7349 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7350 int cmp;
7351 int x;
7354 * Find the function name in the table. Binary search.
7356 while (first <= last)
7358 x = first + ((unsigned)(last - first) >> 1);
7359 cmp = STRCMP(name, functions[x].f_name);
7360 if (cmp < 0)
7361 last = x - 1;
7362 else if (cmp > 0)
7363 first = x + 1;
7364 else
7365 return x;
7367 return -1;
7371 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7372 * name it contains, otherwise return "name".
7374 static char_u *
7375 deref_func_name(name, lenp)
7376 char_u *name;
7377 int *lenp;
7379 dictitem_T *v;
7380 int cc;
7382 cc = name[*lenp];
7383 name[*lenp] = NUL;
7384 v = find_var(name, NULL);
7385 name[*lenp] = cc;
7386 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7388 if (v->di_tv.vval.v_string == NULL)
7390 *lenp = 0;
7391 return (char_u *)""; /* just in case */
7393 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7394 return v->di_tv.vval.v_string;
7397 return name;
7401 * Allocate a variable for the result of a function.
7402 * Return OK or FAIL.
7404 static int
7405 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7406 evaluate, selfdict)
7407 char_u *name; /* name of the function */
7408 int len; /* length of "name" */
7409 typval_T *rettv;
7410 char_u **arg; /* argument, pointing to the '(' */
7411 linenr_T firstline; /* first line of range */
7412 linenr_T lastline; /* last line of range */
7413 int *doesrange; /* return: function handled range */
7414 int evaluate;
7415 dict_T *selfdict; /* Dictionary for "self" */
7417 char_u *argp;
7418 int ret = OK;
7419 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7420 int argcount = 0; /* number of arguments found */
7423 * Get the arguments.
7425 argp = *arg;
7426 while (argcount < MAX_FUNC_ARGS)
7428 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7429 if (*argp == ')' || *argp == ',' || *argp == NUL)
7430 break;
7431 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7433 ret = FAIL;
7434 break;
7436 ++argcount;
7437 if (*argp != ',')
7438 break;
7440 if (*argp == ')')
7441 ++argp;
7442 else
7443 ret = FAIL;
7445 if (ret == OK)
7446 ret = call_func(name, len, rettv, argcount, argvars,
7447 firstline, lastline, doesrange, evaluate, selfdict);
7448 else if (!aborting())
7450 if (argcount == MAX_FUNC_ARGS)
7451 emsg_funcname("E740: Too many arguments for function %s", name);
7452 else
7453 emsg_funcname("E116: Invalid arguments for function %s", name);
7456 while (--argcount >= 0)
7457 clear_tv(&argvars[argcount]);
7459 *arg = skipwhite(argp);
7460 return ret;
7465 * Call a function with its resolved parameters
7466 * Return OK when the function can't be called, FAIL otherwise.
7467 * Also returns OK when an error was encountered while executing the function.
7469 static int
7470 call_func(name, len, rettv, argcount, argvars, firstline, lastline,
7471 doesrange, evaluate, selfdict)
7472 char_u *name; /* name of the function */
7473 int len; /* length of "name" */
7474 typval_T *rettv; /* return value goes here */
7475 int argcount; /* number of "argvars" */
7476 typval_T *argvars; /* vars for arguments, must have "argcount"
7477 PLUS ONE elements! */
7478 linenr_T firstline; /* first line of range */
7479 linenr_T lastline; /* last line of range */
7480 int *doesrange; /* return: function handled range */
7481 int evaluate;
7482 dict_T *selfdict; /* Dictionary for "self" */
7484 int ret = FAIL;
7485 #define ERROR_UNKNOWN 0
7486 #define ERROR_TOOMANY 1
7487 #define ERROR_TOOFEW 2
7488 #define ERROR_SCRIPT 3
7489 #define ERROR_DICT 4
7490 #define ERROR_NONE 5
7491 #define ERROR_OTHER 6
7492 int error = ERROR_NONE;
7493 int i;
7494 int llen;
7495 ufunc_T *fp;
7496 int cc;
7497 #define FLEN_FIXED 40
7498 char_u fname_buf[FLEN_FIXED + 1];
7499 char_u *fname;
7502 * In a script change <SID>name() and s:name() to K_SNR 123_name().
7503 * Change <SNR>123_name() to K_SNR 123_name().
7504 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
7506 cc = name[len];
7507 name[len] = NUL;
7508 llen = eval_fname_script(name);
7509 if (llen > 0)
7511 fname_buf[0] = K_SPECIAL;
7512 fname_buf[1] = KS_EXTRA;
7513 fname_buf[2] = (int)KE_SNR;
7514 i = 3;
7515 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
7517 if (current_SID <= 0)
7518 error = ERROR_SCRIPT;
7519 else
7521 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
7522 i = (int)STRLEN(fname_buf);
7525 if (i + STRLEN(name + llen) < FLEN_FIXED)
7527 STRCPY(fname_buf + i, name + llen);
7528 fname = fname_buf;
7530 else
7532 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
7533 if (fname == NULL)
7534 error = ERROR_OTHER;
7535 else
7537 mch_memmove(fname, fname_buf, (size_t)i);
7538 STRCPY(fname + i, name + llen);
7542 else
7543 fname = name;
7545 *doesrange = FALSE;
7548 /* execute the function if no errors detected and executing */
7549 if (evaluate && error == ERROR_NONE)
7551 rettv->v_type = VAR_NUMBER; /* default is number rettv */
7552 error = ERROR_UNKNOWN;
7554 if (!builtin_function(fname))
7557 * User defined function.
7559 fp = find_func(fname);
7561 #ifdef FEAT_AUTOCMD
7562 /* Trigger FuncUndefined event, may load the function. */
7563 if (fp == NULL
7564 && apply_autocmds(EVENT_FUNCUNDEFINED,
7565 fname, fname, TRUE, NULL)
7566 && !aborting())
7568 /* executed an autocommand, search for the function again */
7569 fp = find_func(fname);
7571 #endif
7572 /* Try loading a package. */
7573 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
7575 /* loaded a package, search for the function again */
7576 fp = find_func(fname);
7579 if (fp != NULL)
7581 if (fp->uf_flags & FC_RANGE)
7582 *doesrange = TRUE;
7583 if (argcount < fp->uf_args.ga_len)
7584 error = ERROR_TOOFEW;
7585 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
7586 error = ERROR_TOOMANY;
7587 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
7588 error = ERROR_DICT;
7589 else
7592 * Call the user function.
7593 * Save and restore search patterns, script variables and
7594 * redo buffer.
7596 save_search_patterns();
7597 saveRedobuff();
7598 ++fp->uf_calls;
7599 call_user_func(fp, argcount, argvars, rettv,
7600 firstline, lastline,
7601 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
7602 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
7603 && fp->uf_refcount <= 0)
7604 /* Function was unreferenced while being used, free it
7605 * now. */
7606 func_free(fp);
7607 restoreRedobuff();
7608 restore_search_patterns();
7609 error = ERROR_NONE;
7613 else
7616 * Find the function name in the table, call its implementation.
7618 i = find_internal_func(fname);
7619 if (i >= 0)
7621 if (argcount < functions[i].f_min_argc)
7622 error = ERROR_TOOFEW;
7623 else if (argcount > functions[i].f_max_argc)
7624 error = ERROR_TOOMANY;
7625 else
7627 argvars[argcount].v_type = VAR_UNKNOWN;
7628 functions[i].f_func(argvars, rettv);
7629 error = ERROR_NONE;
7634 * The function call (or "FuncUndefined" autocommand sequence) might
7635 * have been aborted by an error, an interrupt, or an explicitly thrown
7636 * exception that has not been caught so far. This situation can be
7637 * tested for by calling aborting(). For an error in an internal
7638 * function or for the "E132" error in call_user_func(), however, the
7639 * throw point at which the "force_abort" flag (temporarily reset by
7640 * emsg()) is normally updated has not been reached yet. We need to
7641 * update that flag first to make aborting() reliable.
7643 update_force_abort();
7645 if (error == ERROR_NONE)
7646 ret = OK;
7649 * Report an error unless the argument evaluation or function call has been
7650 * cancelled due to an aborting error, an interrupt, or an exception.
7652 if (!aborting())
7654 switch (error)
7656 case ERROR_UNKNOWN:
7657 emsg_funcname(N_("E117: Unknown function: %s"), name);
7658 break;
7659 case ERROR_TOOMANY:
7660 emsg_funcname(e_toomanyarg, name);
7661 break;
7662 case ERROR_TOOFEW:
7663 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
7664 name);
7665 break;
7666 case ERROR_SCRIPT:
7667 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
7668 name);
7669 break;
7670 case ERROR_DICT:
7671 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
7672 name);
7673 break;
7677 name[len] = cc;
7678 if (fname != name && fname != fname_buf)
7679 vim_free(fname);
7681 return ret;
7685 * Give an error message with a function name. Handle <SNR> things.
7687 static void
7688 emsg_funcname(ermsg, name)
7689 char *ermsg;
7690 char_u *name;
7692 char_u *p;
7694 if (*name == K_SPECIAL)
7695 p = concat_str((char_u *)"<SNR>", name + 3);
7696 else
7697 p = name;
7698 EMSG2(_(ermsg), p);
7699 if (p != name)
7700 vim_free(p);
7703 /*********************************************
7704 * Implementation of the built-in functions
7708 * "add(list, item)" function
7710 static void
7711 f_add(argvars, rettv)
7712 typval_T *argvars;
7713 typval_T *rettv;
7715 list_T *l;
7717 rettv->vval.v_number = 1; /* Default: Failed */
7718 if (argvars[0].v_type == VAR_LIST)
7720 if ((l = argvars[0].vval.v_list) != NULL
7721 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
7722 && list_append_tv(l, &argvars[1]) == OK)
7723 copy_tv(&argvars[0], rettv);
7725 else
7726 EMSG(_(e_listreq));
7730 * "append(lnum, string/list)" function
7732 static void
7733 f_append(argvars, rettv)
7734 typval_T *argvars;
7735 typval_T *rettv;
7737 long lnum;
7738 char_u *line;
7739 list_T *l = NULL;
7740 listitem_T *li = NULL;
7741 typval_T *tv;
7742 long added = 0;
7744 lnum = get_tv_lnum(argvars);
7745 if (lnum >= 0
7746 && lnum <= curbuf->b_ml.ml_line_count
7747 && u_save(lnum, lnum + 1) == OK)
7749 if (argvars[1].v_type == VAR_LIST)
7751 l = argvars[1].vval.v_list;
7752 if (l == NULL)
7753 return;
7754 li = l->lv_first;
7756 rettv->vval.v_number = 0; /* Default: Success */
7757 for (;;)
7759 if (l == NULL)
7760 tv = &argvars[1]; /* append a string */
7761 else if (li == NULL)
7762 break; /* end of list */
7763 else
7764 tv = &li->li_tv; /* append item from list */
7765 line = get_tv_string_chk(tv);
7766 if (line == NULL) /* type error */
7768 rettv->vval.v_number = 1; /* Failed */
7769 break;
7771 ml_append(lnum + added, line, (colnr_T)0, FALSE);
7772 ++added;
7773 if (l == NULL)
7774 break;
7775 li = li->li_next;
7778 appended_lines_mark(lnum, added);
7779 if (curwin->w_cursor.lnum > lnum)
7780 curwin->w_cursor.lnum += added;
7782 else
7783 rettv->vval.v_number = 1; /* Failed */
7787 * "argc()" function
7789 /* ARGSUSED */
7790 static void
7791 f_argc(argvars, rettv)
7792 typval_T *argvars;
7793 typval_T *rettv;
7795 rettv->vval.v_number = ARGCOUNT;
7799 * "argidx()" function
7801 /* ARGSUSED */
7802 static void
7803 f_argidx(argvars, rettv)
7804 typval_T *argvars;
7805 typval_T *rettv;
7807 rettv->vval.v_number = curwin->w_arg_idx;
7811 * "argv(nr)" function
7813 static void
7814 f_argv(argvars, rettv)
7815 typval_T *argvars;
7816 typval_T *rettv;
7818 int idx;
7820 if (argvars[0].v_type != VAR_UNKNOWN)
7822 idx = get_tv_number_chk(&argvars[0], NULL);
7823 if (idx >= 0 && idx < ARGCOUNT)
7824 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
7825 else
7826 rettv->vval.v_string = NULL;
7827 rettv->v_type = VAR_STRING;
7829 else if (rettv_list_alloc(rettv) == OK)
7830 for (idx = 0; idx < ARGCOUNT; ++idx)
7831 list_append_string(rettv->vval.v_list,
7832 alist_name(&ARGLIST[idx]), -1);
7836 * "browse(save, title, initdir, default)" function
7838 /* ARGSUSED */
7839 static void
7840 f_browse(argvars, rettv)
7841 typval_T *argvars;
7842 typval_T *rettv;
7844 #ifdef FEAT_BROWSE
7845 int save;
7846 char_u *title;
7847 char_u *initdir;
7848 char_u *defname;
7849 char_u buf[NUMBUFLEN];
7850 char_u buf2[NUMBUFLEN];
7851 int error = FALSE;
7853 save = get_tv_number_chk(&argvars[0], &error);
7854 title = get_tv_string_chk(&argvars[1]);
7855 initdir = get_tv_string_buf_chk(&argvars[2], buf);
7856 defname = get_tv_string_buf_chk(&argvars[3], buf2);
7858 if (error || title == NULL || initdir == NULL || defname == NULL)
7859 rettv->vval.v_string = NULL;
7860 else
7861 rettv->vval.v_string =
7862 do_browse(save ? BROWSE_SAVE : 0,
7863 title, defname, NULL, initdir, NULL, curbuf);
7864 #else
7865 rettv->vval.v_string = NULL;
7866 #endif
7867 rettv->v_type = VAR_STRING;
7871 * "browsedir(title, initdir)" function
7873 /* ARGSUSED */
7874 static void
7875 f_browsedir(argvars, rettv)
7876 typval_T *argvars;
7877 typval_T *rettv;
7879 #ifdef FEAT_BROWSE
7880 char_u *title;
7881 char_u *initdir;
7882 char_u buf[NUMBUFLEN];
7884 title = get_tv_string_chk(&argvars[0]);
7885 initdir = get_tv_string_buf_chk(&argvars[1], buf);
7887 if (title == NULL || initdir == NULL)
7888 rettv->vval.v_string = NULL;
7889 else
7890 rettv->vval.v_string = do_browse(BROWSE_DIR,
7891 title, NULL, NULL, initdir, NULL, curbuf);
7892 #else
7893 rettv->vval.v_string = NULL;
7894 #endif
7895 rettv->v_type = VAR_STRING;
7898 static buf_T *find_buffer __ARGS((typval_T *avar));
7901 * Find a buffer by number or exact name.
7903 static buf_T *
7904 find_buffer(avar)
7905 typval_T *avar;
7907 buf_T *buf = NULL;
7909 if (avar->v_type == VAR_NUMBER)
7910 buf = buflist_findnr((int)avar->vval.v_number);
7911 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
7913 buf = buflist_findname_exp(avar->vval.v_string);
7914 if (buf == NULL)
7916 /* No full path name match, try a match with a URL or a "nofile"
7917 * buffer, these don't use the full path. */
7918 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
7919 if (buf->b_fname != NULL
7920 && (path_with_url(buf->b_fname)
7921 #ifdef FEAT_QUICKFIX
7922 || bt_nofile(buf)
7923 #endif
7925 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
7926 break;
7929 return buf;
7933 * "bufexists(expr)" function
7935 static void
7936 f_bufexists(argvars, rettv)
7937 typval_T *argvars;
7938 typval_T *rettv;
7940 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
7944 * "buflisted(expr)" function
7946 static void
7947 f_buflisted(argvars, rettv)
7948 typval_T *argvars;
7949 typval_T *rettv;
7951 buf_T *buf;
7953 buf = find_buffer(&argvars[0]);
7954 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
7958 * "bufloaded(expr)" function
7960 static void
7961 f_bufloaded(argvars, rettv)
7962 typval_T *argvars;
7963 typval_T *rettv;
7965 buf_T *buf;
7967 buf = find_buffer(&argvars[0]);
7968 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
7971 static buf_T *get_buf_tv __ARGS((typval_T *tv));
7974 * Get buffer by number or pattern.
7976 static buf_T *
7977 get_buf_tv(tv)
7978 typval_T *tv;
7980 char_u *name = tv->vval.v_string;
7981 int save_magic;
7982 char_u *save_cpo;
7983 buf_T *buf;
7985 if (tv->v_type == VAR_NUMBER)
7986 return buflist_findnr((int)tv->vval.v_number);
7987 if (tv->v_type != VAR_STRING)
7988 return NULL;
7989 if (name == NULL || *name == NUL)
7990 return curbuf;
7991 if (name[0] == '$' && name[1] == NUL)
7992 return lastbuf;
7994 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
7995 save_magic = p_magic;
7996 p_magic = TRUE;
7997 save_cpo = p_cpo;
7998 p_cpo = (char_u *)"";
8000 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8001 TRUE, FALSE));
8003 p_magic = save_magic;
8004 p_cpo = save_cpo;
8006 /* If not found, try expanding the name, like done for bufexists(). */
8007 if (buf == NULL)
8008 buf = find_buffer(tv);
8010 return buf;
8014 * "bufname(expr)" function
8016 static void
8017 f_bufname(argvars, rettv)
8018 typval_T *argvars;
8019 typval_T *rettv;
8021 buf_T *buf;
8023 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8024 ++emsg_off;
8025 buf = get_buf_tv(&argvars[0]);
8026 rettv->v_type = VAR_STRING;
8027 if (buf != NULL && buf->b_fname != NULL)
8028 rettv->vval.v_string = vim_strsave(buf->b_fname);
8029 else
8030 rettv->vval.v_string = NULL;
8031 --emsg_off;
8035 * "bufnr(expr)" function
8037 static void
8038 f_bufnr(argvars, rettv)
8039 typval_T *argvars;
8040 typval_T *rettv;
8042 buf_T *buf;
8043 int error = FALSE;
8044 char_u *name;
8046 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8047 ++emsg_off;
8048 buf = get_buf_tv(&argvars[0]);
8049 --emsg_off;
8051 /* If the buffer isn't found and the second argument is not zero create a
8052 * new buffer. */
8053 if (buf == NULL
8054 && argvars[1].v_type != VAR_UNKNOWN
8055 && get_tv_number_chk(&argvars[1], &error) != 0
8056 && !error
8057 && (name = get_tv_string_chk(&argvars[0])) != NULL
8058 && !error)
8059 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8061 if (buf != NULL)
8062 rettv->vval.v_number = buf->b_fnum;
8063 else
8064 rettv->vval.v_number = -1;
8068 * "bufwinnr(nr)" function
8070 static void
8071 f_bufwinnr(argvars, rettv)
8072 typval_T *argvars;
8073 typval_T *rettv;
8075 #ifdef FEAT_WINDOWS
8076 win_T *wp;
8077 int winnr = 0;
8078 #endif
8079 buf_T *buf;
8081 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8082 ++emsg_off;
8083 buf = get_buf_tv(&argvars[0]);
8084 #ifdef FEAT_WINDOWS
8085 for (wp = firstwin; wp; wp = wp->w_next)
8087 ++winnr;
8088 if (wp->w_buffer == buf)
8089 break;
8091 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8092 #else
8093 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8094 #endif
8095 --emsg_off;
8099 * "byte2line(byte)" function
8101 /*ARGSUSED*/
8102 static void
8103 f_byte2line(argvars, rettv)
8104 typval_T *argvars;
8105 typval_T *rettv;
8107 #ifndef FEAT_BYTEOFF
8108 rettv->vval.v_number = -1;
8109 #else
8110 long boff = 0;
8112 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8113 if (boff < 0)
8114 rettv->vval.v_number = -1;
8115 else
8116 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8117 (linenr_T)0, &boff);
8118 #endif
8122 * "byteidx()" function
8124 /*ARGSUSED*/
8125 static void
8126 f_byteidx(argvars, rettv)
8127 typval_T *argvars;
8128 typval_T *rettv;
8130 #ifdef FEAT_MBYTE
8131 char_u *t;
8132 #endif
8133 char_u *str;
8134 long idx;
8136 str = get_tv_string_chk(&argvars[0]);
8137 idx = get_tv_number_chk(&argvars[1], NULL);
8138 rettv->vval.v_number = -1;
8139 if (str == NULL || idx < 0)
8140 return;
8142 #ifdef FEAT_MBYTE
8143 t = str;
8144 for ( ; idx > 0; idx--)
8146 if (*t == NUL) /* EOL reached */
8147 return;
8148 t += (*mb_ptr2len)(t);
8150 rettv->vval.v_number = (varnumber_T)(t - str);
8151 #else
8152 if (idx <= STRLEN(str))
8153 rettv->vval.v_number = idx;
8154 #endif
8158 * "call(func, arglist)" function
8160 static void
8161 f_call(argvars, rettv)
8162 typval_T *argvars;
8163 typval_T *rettv;
8165 char_u *func;
8166 typval_T argv[MAX_FUNC_ARGS + 1];
8167 int argc = 0;
8168 listitem_T *item;
8169 int dummy;
8170 dict_T *selfdict = NULL;
8172 rettv->vval.v_number = 0;
8173 if (argvars[1].v_type != VAR_LIST)
8175 EMSG(_(e_listreq));
8176 return;
8178 if (argvars[1].vval.v_list == NULL)
8179 return;
8181 if (argvars[0].v_type == VAR_FUNC)
8182 func = argvars[0].vval.v_string;
8183 else
8184 func = get_tv_string(&argvars[0]);
8185 if (*func == NUL)
8186 return; /* type error or empty name */
8188 if (argvars[2].v_type != VAR_UNKNOWN)
8190 if (argvars[2].v_type != VAR_DICT)
8192 EMSG(_(e_dictreq));
8193 return;
8195 selfdict = argvars[2].vval.v_dict;
8198 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
8199 item = item->li_next)
8201 if (argc == MAX_FUNC_ARGS)
8203 EMSG(_("E699: Too many arguments"));
8204 break;
8206 /* Make a copy of each argument. This is needed to be able to set
8207 * v_lock to VAR_FIXED in the copy without changing the original list.
8209 copy_tv(&item->li_tv, &argv[argc++]);
8212 if (item == NULL)
8213 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
8214 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
8215 &dummy, TRUE, selfdict);
8217 /* Free the arguments. */
8218 while (argc > 0)
8219 clear_tv(&argv[--argc]);
8223 * "changenr()" function
8225 /*ARGSUSED*/
8226 static void
8227 f_changenr(argvars, rettv)
8228 typval_T *argvars;
8229 typval_T *rettv;
8231 rettv->vval.v_number = curbuf->b_u_seq_cur;
8235 * "char2nr(string)" function
8237 static void
8238 f_char2nr(argvars, rettv)
8239 typval_T *argvars;
8240 typval_T *rettv;
8242 #ifdef FEAT_MBYTE
8243 if (has_mbyte)
8244 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
8245 else
8246 #endif
8247 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
8251 * "cindent(lnum)" function
8253 static void
8254 f_cindent(argvars, rettv)
8255 typval_T *argvars;
8256 typval_T *rettv;
8258 #ifdef FEAT_CINDENT
8259 pos_T pos;
8260 linenr_T lnum;
8262 pos = curwin->w_cursor;
8263 lnum = get_tv_lnum(argvars);
8264 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
8266 curwin->w_cursor.lnum = lnum;
8267 rettv->vval.v_number = get_c_indent();
8268 curwin->w_cursor = pos;
8270 else
8271 #endif
8272 rettv->vval.v_number = -1;
8276 * "clearmatches()" function
8278 /*ARGSUSED*/
8279 static void
8280 f_clearmatches(argvars, rettv)
8281 typval_T *argvars;
8282 typval_T *rettv;
8284 #ifdef FEAT_SEARCH_EXTRA
8285 clear_matches(curwin);
8286 #endif
8290 * "col(string)" function
8292 static void
8293 f_col(argvars, rettv)
8294 typval_T *argvars;
8295 typval_T *rettv;
8297 colnr_T col = 0;
8298 pos_T *fp;
8299 int fnum = curbuf->b_fnum;
8301 fp = var2fpos(&argvars[0], FALSE, &fnum);
8302 if (fp != NULL && fnum == curbuf->b_fnum)
8304 if (fp->col == MAXCOL)
8306 /* '> can be MAXCOL, get the length of the line then */
8307 if (fp->lnum <= curbuf->b_ml.ml_line_count)
8308 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
8309 else
8310 col = MAXCOL;
8312 else
8314 col = fp->col + 1;
8315 #ifdef FEAT_VIRTUALEDIT
8316 /* col(".") when the cursor is on the NUL at the end of the line
8317 * because of "coladd" can be seen as an extra column. */
8318 if (virtual_active() && fp == &curwin->w_cursor)
8320 char_u *p = ml_get_cursor();
8322 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
8323 curwin->w_virtcol - curwin->w_cursor.coladd))
8325 # ifdef FEAT_MBYTE
8326 int l;
8328 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
8329 col += l;
8330 # else
8331 if (*p != NUL && p[1] == NUL)
8332 ++col;
8333 # endif
8336 #endif
8339 rettv->vval.v_number = col;
8342 #if defined(FEAT_INS_EXPAND)
8344 * "complete()" function
8346 /*ARGSUSED*/
8347 static void
8348 f_complete(argvars, rettv)
8349 typval_T *argvars;
8350 typval_T *rettv;
8352 int startcol;
8354 if ((State & INSERT) == 0)
8356 EMSG(_("E785: complete() can only be used in Insert mode"));
8357 return;
8360 /* Check for undo allowed here, because if something was already inserted
8361 * the line was already saved for undo and this check isn't done. */
8362 if (!undo_allowed())
8363 return;
8365 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
8367 EMSG(_(e_invarg));
8368 return;
8371 startcol = get_tv_number_chk(&argvars[0], NULL);
8372 if (startcol <= 0)
8373 return;
8375 set_completion(startcol - 1, argvars[1].vval.v_list);
8379 * "complete_add()" function
8381 /*ARGSUSED*/
8382 static void
8383 f_complete_add(argvars, rettv)
8384 typval_T *argvars;
8385 typval_T *rettv;
8387 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
8391 * "complete_check()" function
8393 /*ARGSUSED*/
8394 static void
8395 f_complete_check(argvars, rettv)
8396 typval_T *argvars;
8397 typval_T *rettv;
8399 int saved = RedrawingDisabled;
8401 RedrawingDisabled = 0;
8402 ins_compl_check_keys(0);
8403 rettv->vval.v_number = compl_interrupted;
8404 RedrawingDisabled = saved;
8406 #endif
8409 * "confirm(message, buttons[, default [, type]])" function
8411 /*ARGSUSED*/
8412 static void
8413 f_confirm(argvars, rettv)
8414 typval_T *argvars;
8415 typval_T *rettv;
8417 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
8418 char_u *message;
8419 char_u *buttons = NULL;
8420 char_u buf[NUMBUFLEN];
8421 char_u buf2[NUMBUFLEN];
8422 int def = 1;
8423 int type = VIM_GENERIC;
8424 char_u *typestr;
8425 int error = FALSE;
8427 message = get_tv_string_chk(&argvars[0]);
8428 if (message == NULL)
8429 error = TRUE;
8430 if (argvars[1].v_type != VAR_UNKNOWN)
8432 buttons = get_tv_string_buf_chk(&argvars[1], buf);
8433 if (buttons == NULL)
8434 error = TRUE;
8435 if (argvars[2].v_type != VAR_UNKNOWN)
8437 def = get_tv_number_chk(&argvars[2], &error);
8438 if (argvars[3].v_type != VAR_UNKNOWN)
8440 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
8441 if (typestr == NULL)
8442 error = TRUE;
8443 else
8445 switch (TOUPPER_ASC(*typestr))
8447 case 'E': type = VIM_ERROR; break;
8448 case 'Q': type = VIM_QUESTION; break;
8449 case 'I': type = VIM_INFO; break;
8450 case 'W': type = VIM_WARNING; break;
8451 case 'G': type = VIM_GENERIC; break;
8458 if (buttons == NULL || *buttons == NUL)
8459 buttons = (char_u *)_("&Ok");
8461 if (error)
8462 rettv->vval.v_number = 0;
8463 else
8464 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
8465 def, NULL);
8466 #else
8467 rettv->vval.v_number = 0;
8468 #endif
8472 * "copy()" function
8474 static void
8475 f_copy(argvars, rettv)
8476 typval_T *argvars;
8477 typval_T *rettv;
8479 item_copy(&argvars[0], rettv, FALSE, 0);
8483 * "count()" function
8485 static void
8486 f_count(argvars, rettv)
8487 typval_T *argvars;
8488 typval_T *rettv;
8490 long n = 0;
8491 int ic = FALSE;
8493 if (argvars[0].v_type == VAR_LIST)
8495 listitem_T *li;
8496 list_T *l;
8497 long idx;
8499 if ((l = argvars[0].vval.v_list) != NULL)
8501 li = l->lv_first;
8502 if (argvars[2].v_type != VAR_UNKNOWN)
8504 int error = FALSE;
8506 ic = get_tv_number_chk(&argvars[2], &error);
8507 if (argvars[3].v_type != VAR_UNKNOWN)
8509 idx = get_tv_number_chk(&argvars[3], &error);
8510 if (!error)
8512 li = list_find(l, idx);
8513 if (li == NULL)
8514 EMSGN(_(e_listidx), idx);
8517 if (error)
8518 li = NULL;
8521 for ( ; li != NULL; li = li->li_next)
8522 if (tv_equal(&li->li_tv, &argvars[1], ic))
8523 ++n;
8526 else if (argvars[0].v_type == VAR_DICT)
8528 int todo;
8529 dict_T *d;
8530 hashitem_T *hi;
8532 if ((d = argvars[0].vval.v_dict) != NULL)
8534 int error = FALSE;
8536 if (argvars[2].v_type != VAR_UNKNOWN)
8538 ic = get_tv_number_chk(&argvars[2], &error);
8539 if (argvars[3].v_type != VAR_UNKNOWN)
8540 EMSG(_(e_invarg));
8543 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
8544 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
8546 if (!HASHITEM_EMPTY(hi))
8548 --todo;
8549 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
8550 ++n;
8555 else
8556 EMSG2(_(e_listdictarg), "count()");
8557 rettv->vval.v_number = n;
8561 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
8563 * Checks the existence of a cscope connection.
8565 /*ARGSUSED*/
8566 static void
8567 f_cscope_connection(argvars, rettv)
8568 typval_T *argvars;
8569 typval_T *rettv;
8571 #ifdef FEAT_CSCOPE
8572 int num = 0;
8573 char_u *dbpath = NULL;
8574 char_u *prepend = NULL;
8575 char_u buf[NUMBUFLEN];
8577 if (argvars[0].v_type != VAR_UNKNOWN
8578 && argvars[1].v_type != VAR_UNKNOWN)
8580 num = (int)get_tv_number(&argvars[0]);
8581 dbpath = get_tv_string(&argvars[1]);
8582 if (argvars[2].v_type != VAR_UNKNOWN)
8583 prepend = get_tv_string_buf(&argvars[2], buf);
8586 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
8587 #else
8588 rettv->vval.v_number = 0;
8589 #endif
8593 * "cursor(lnum, col)" function
8595 * Moves the cursor to the specified line and column
8597 /*ARGSUSED*/
8598 static void
8599 f_cursor(argvars, rettv)
8600 typval_T *argvars;
8601 typval_T *rettv;
8603 long line, col;
8604 #ifdef FEAT_VIRTUALEDIT
8605 long coladd = 0;
8606 #endif
8608 if (argvars[1].v_type == VAR_UNKNOWN)
8610 pos_T pos;
8612 if (list2fpos(argvars, &pos, NULL) == FAIL)
8613 return;
8614 line = pos.lnum;
8615 col = pos.col;
8616 #ifdef FEAT_VIRTUALEDIT
8617 coladd = pos.coladd;
8618 #endif
8620 else
8622 line = get_tv_lnum(argvars);
8623 col = get_tv_number_chk(&argvars[1], NULL);
8624 #ifdef FEAT_VIRTUALEDIT
8625 if (argvars[2].v_type != VAR_UNKNOWN)
8626 coladd = get_tv_number_chk(&argvars[2], NULL);
8627 #endif
8629 if (line < 0 || col < 0
8630 #ifdef FEAT_VIRTUALEDIT
8631 || coladd < 0
8632 #endif
8634 return; /* type error; errmsg already given */
8635 if (line > 0)
8636 curwin->w_cursor.lnum = line;
8637 if (col > 0)
8638 curwin->w_cursor.col = col - 1;
8639 #ifdef FEAT_VIRTUALEDIT
8640 curwin->w_cursor.coladd = coladd;
8641 #endif
8643 /* Make sure the cursor is in a valid position. */
8644 check_cursor();
8645 #ifdef FEAT_MBYTE
8646 /* Correct cursor for multi-byte character. */
8647 if (has_mbyte)
8648 mb_adjust_cursor();
8649 #endif
8651 curwin->w_set_curswant = TRUE;
8655 * "deepcopy()" function
8657 static void
8658 f_deepcopy(argvars, rettv)
8659 typval_T *argvars;
8660 typval_T *rettv;
8662 int noref = 0;
8664 if (argvars[1].v_type != VAR_UNKNOWN)
8665 noref = get_tv_number_chk(&argvars[1], NULL);
8666 if (noref < 0 || noref > 1)
8667 EMSG(_(e_invarg));
8668 else
8669 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? ++current_copyID : 0);
8673 * "delete()" function
8675 static void
8676 f_delete(argvars, rettv)
8677 typval_T *argvars;
8678 typval_T *rettv;
8680 if (check_restricted() || check_secure())
8681 rettv->vval.v_number = -1;
8682 else
8683 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
8687 * "did_filetype()" function
8689 /*ARGSUSED*/
8690 static void
8691 f_did_filetype(argvars, rettv)
8692 typval_T *argvars;
8693 typval_T *rettv;
8695 #ifdef FEAT_AUTOCMD
8696 rettv->vval.v_number = did_filetype;
8697 #else
8698 rettv->vval.v_number = 0;
8699 #endif
8703 * "diff_filler()" function
8705 /*ARGSUSED*/
8706 static void
8707 f_diff_filler(argvars, rettv)
8708 typval_T *argvars;
8709 typval_T *rettv;
8711 #ifdef FEAT_DIFF
8712 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
8713 #endif
8717 * "diff_hlID()" function
8719 /*ARGSUSED*/
8720 static void
8721 f_diff_hlID(argvars, rettv)
8722 typval_T *argvars;
8723 typval_T *rettv;
8725 #ifdef FEAT_DIFF
8726 linenr_T lnum = get_tv_lnum(argvars);
8727 static linenr_T prev_lnum = 0;
8728 static int changedtick = 0;
8729 static int fnum = 0;
8730 static int change_start = 0;
8731 static int change_end = 0;
8732 static hlf_T hlID = (hlf_T)0;
8733 int filler_lines;
8734 int col;
8736 if (lnum < 0) /* ignore type error in {lnum} arg */
8737 lnum = 0;
8738 if (lnum != prev_lnum
8739 || changedtick != curbuf->b_changedtick
8740 || fnum != curbuf->b_fnum)
8742 /* New line, buffer, change: need to get the values. */
8743 filler_lines = diff_check(curwin, lnum);
8744 if (filler_lines < 0)
8746 if (filler_lines == -1)
8748 change_start = MAXCOL;
8749 change_end = -1;
8750 if (diff_find_change(curwin, lnum, &change_start, &change_end))
8751 hlID = HLF_ADD; /* added line */
8752 else
8753 hlID = HLF_CHD; /* changed line */
8755 else
8756 hlID = HLF_ADD; /* added line */
8758 else
8759 hlID = (hlf_T)0;
8760 prev_lnum = lnum;
8761 changedtick = curbuf->b_changedtick;
8762 fnum = curbuf->b_fnum;
8765 if (hlID == HLF_CHD || hlID == HLF_TXD)
8767 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
8768 if (col >= change_start && col <= change_end)
8769 hlID = HLF_TXD; /* changed text */
8770 else
8771 hlID = HLF_CHD; /* changed line */
8773 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
8774 #endif
8778 * "empty({expr})" function
8780 static void
8781 f_empty(argvars, rettv)
8782 typval_T *argvars;
8783 typval_T *rettv;
8785 int n;
8787 switch (argvars[0].v_type)
8789 case VAR_STRING:
8790 case VAR_FUNC:
8791 n = argvars[0].vval.v_string == NULL
8792 || *argvars[0].vval.v_string == NUL;
8793 break;
8794 case VAR_NUMBER:
8795 n = argvars[0].vval.v_number == 0;
8796 break;
8797 case VAR_LIST:
8798 n = argvars[0].vval.v_list == NULL
8799 || argvars[0].vval.v_list->lv_first == NULL;
8800 break;
8801 case VAR_DICT:
8802 n = argvars[0].vval.v_dict == NULL
8803 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
8804 break;
8805 default:
8806 EMSG2(_(e_intern2), "f_empty()");
8807 n = 0;
8810 rettv->vval.v_number = n;
8814 * "escape({string}, {chars})" function
8816 static void
8817 f_escape(argvars, rettv)
8818 typval_T *argvars;
8819 typval_T *rettv;
8821 char_u buf[NUMBUFLEN];
8823 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
8824 get_tv_string_buf(&argvars[1], buf));
8825 rettv->v_type = VAR_STRING;
8829 * "eval()" function
8831 /*ARGSUSED*/
8832 static void
8833 f_eval(argvars, rettv)
8834 typval_T *argvars;
8835 typval_T *rettv;
8837 char_u *s;
8839 s = get_tv_string_chk(&argvars[0]);
8840 if (s != NULL)
8841 s = skipwhite(s);
8843 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
8845 rettv->v_type = VAR_NUMBER;
8846 rettv->vval.v_number = 0;
8848 else if (*s != NUL)
8849 EMSG(_(e_trailing));
8853 * "eventhandler()" function
8855 /*ARGSUSED*/
8856 static void
8857 f_eventhandler(argvars, rettv)
8858 typval_T *argvars;
8859 typval_T *rettv;
8861 rettv->vval.v_number = vgetc_busy;
8865 * "executable()" function
8867 static void
8868 f_executable(argvars, rettv)
8869 typval_T *argvars;
8870 typval_T *rettv;
8872 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
8876 * "exists()" function
8878 static void
8879 f_exists(argvars, rettv)
8880 typval_T *argvars;
8881 typval_T *rettv;
8883 char_u *p;
8884 char_u *name;
8885 int n = FALSE;
8886 int len = 0;
8888 p = get_tv_string(&argvars[0]);
8889 if (*p == '$') /* environment variable */
8891 /* first try "normal" environment variables (fast) */
8892 if (mch_getenv(p + 1) != NULL)
8893 n = TRUE;
8894 else
8896 /* try expanding things like $VIM and ${HOME} */
8897 p = expand_env_save(p);
8898 if (p != NULL && *p != '$')
8899 n = TRUE;
8900 vim_free(p);
8903 else if (*p == '&' || *p == '+') /* option */
8905 n = (get_option_tv(&p, NULL, TRUE) == OK);
8906 if (*skipwhite(p) != NUL)
8907 n = FALSE; /* trailing garbage */
8909 else if (*p == '*') /* internal or user defined function */
8911 n = function_exists(p + 1);
8913 else if (*p == ':')
8915 n = cmd_exists(p + 1);
8917 else if (*p == '#')
8919 #ifdef FEAT_AUTOCMD
8920 if (p[1] == '#')
8921 n = autocmd_supported(p + 2);
8922 else
8923 n = au_exists(p + 1);
8924 #endif
8926 else /* internal variable */
8928 char_u *tofree;
8929 typval_T tv;
8931 /* get_name_len() takes care of expanding curly braces */
8932 name = p;
8933 len = get_name_len(&p, &tofree, TRUE, FALSE);
8934 if (len > 0)
8936 if (tofree != NULL)
8937 name = tofree;
8938 n = (get_var_tv(name, len, &tv, FALSE) == OK);
8939 if (n)
8941 /* handle d.key, l[idx], f(expr) */
8942 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
8943 if (n)
8944 clear_tv(&tv);
8947 if (*p != NUL)
8948 n = FALSE;
8950 vim_free(tofree);
8953 rettv->vval.v_number = n;
8957 * "expand()" function
8959 static void
8960 f_expand(argvars, rettv)
8961 typval_T *argvars;
8962 typval_T *rettv;
8964 char_u *s;
8965 int len;
8966 char_u *errormsg;
8967 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
8968 expand_T xpc;
8969 int error = FALSE;
8971 rettv->v_type = VAR_STRING;
8972 s = get_tv_string(&argvars[0]);
8973 if (*s == '%' || *s == '#' || *s == '<')
8975 ++emsg_off;
8976 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
8977 --emsg_off;
8979 else
8981 /* When the optional second argument is non-zero, don't remove matches
8982 * for 'suffixes' and 'wildignore' */
8983 if (argvars[1].v_type != VAR_UNKNOWN
8984 && get_tv_number_chk(&argvars[1], &error))
8985 flags |= WILD_KEEP_ALL;
8986 if (!error)
8988 ExpandInit(&xpc);
8989 xpc.xp_context = EXPAND_FILES;
8990 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
8992 else
8993 rettv->vval.v_string = NULL;
8998 * "extend(list, list [, idx])" function
8999 * "extend(dict, dict [, action])" function
9001 static void
9002 f_extend(argvars, rettv)
9003 typval_T *argvars;
9004 typval_T *rettv;
9006 rettv->vval.v_number = 0;
9007 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9009 list_T *l1, *l2;
9010 listitem_T *item;
9011 long before;
9012 int error = FALSE;
9014 l1 = argvars[0].vval.v_list;
9015 l2 = argvars[1].vval.v_list;
9016 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9017 && l2 != NULL)
9019 if (argvars[2].v_type != VAR_UNKNOWN)
9021 before = get_tv_number_chk(&argvars[2], &error);
9022 if (error)
9023 return; /* type error; errmsg already given */
9025 if (before == l1->lv_len)
9026 item = NULL;
9027 else
9029 item = list_find(l1, before);
9030 if (item == NULL)
9032 EMSGN(_(e_listidx), before);
9033 return;
9037 else
9038 item = NULL;
9039 list_extend(l1, l2, item);
9041 copy_tv(&argvars[0], rettv);
9044 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9046 dict_T *d1, *d2;
9047 dictitem_T *di1;
9048 char_u *action;
9049 int i;
9050 hashitem_T *hi2;
9051 int todo;
9053 d1 = argvars[0].vval.v_dict;
9054 d2 = argvars[1].vval.v_dict;
9055 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9056 && d2 != NULL)
9058 /* Check the third argument. */
9059 if (argvars[2].v_type != VAR_UNKNOWN)
9061 static char *(av[]) = {"keep", "force", "error"};
9063 action = get_tv_string_chk(&argvars[2]);
9064 if (action == NULL)
9065 return; /* type error; errmsg already given */
9066 for (i = 0; i < 3; ++i)
9067 if (STRCMP(action, av[i]) == 0)
9068 break;
9069 if (i == 3)
9071 EMSG2(_(e_invarg2), action);
9072 return;
9075 else
9076 action = (char_u *)"force";
9078 /* Go over all entries in the second dict and add them to the
9079 * first dict. */
9080 todo = (int)d2->dv_hashtab.ht_used;
9081 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9083 if (!HASHITEM_EMPTY(hi2))
9085 --todo;
9086 di1 = dict_find(d1, hi2->hi_key, -1);
9087 if (di1 == NULL)
9089 di1 = dictitem_copy(HI2DI(hi2));
9090 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9091 dictitem_free(di1);
9093 else if (*action == 'e')
9095 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9096 break;
9098 else if (*action == 'f')
9100 clear_tv(&di1->di_tv);
9101 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9106 copy_tv(&argvars[0], rettv);
9109 else
9110 EMSG2(_(e_listdictarg), "extend()");
9114 * "feedkeys()" function
9116 /*ARGSUSED*/
9117 static void
9118 f_feedkeys(argvars, rettv)
9119 typval_T *argvars;
9120 typval_T *rettv;
9122 int remap = TRUE;
9123 char_u *keys, *flags;
9124 char_u nbuf[NUMBUFLEN];
9125 int typed = FALSE;
9126 char_u *keys_esc;
9128 /* This is not allowed in the sandbox. If the commands would still be
9129 * executed in the sandbox it would be OK, but it probably happens later,
9130 * when "sandbox" is no longer set. */
9131 if (check_secure())
9132 return;
9134 rettv->vval.v_number = 0;
9135 keys = get_tv_string(&argvars[0]);
9136 if (*keys != NUL)
9138 if (argvars[1].v_type != VAR_UNKNOWN)
9140 flags = get_tv_string_buf(&argvars[1], nbuf);
9141 for ( ; *flags != NUL; ++flags)
9143 switch (*flags)
9145 case 'n': remap = FALSE; break;
9146 case 'm': remap = TRUE; break;
9147 case 't': typed = TRUE; break;
9152 /* Need to escape K_SPECIAL and CSI before putting the string in the
9153 * typeahead buffer. */
9154 keys_esc = vim_strsave_escape_csi(keys);
9155 if (keys_esc != NULL)
9157 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
9158 typebuf.tb_len, !typed, FALSE);
9159 vim_free(keys_esc);
9160 if (vgetc_busy)
9161 typebuf_was_filled = TRUE;
9167 * "filereadable()" function
9169 static void
9170 f_filereadable(argvars, rettv)
9171 typval_T *argvars;
9172 typval_T *rettv;
9174 FILE *fd;
9175 char_u *p;
9176 int n;
9178 p = get_tv_string(&argvars[0]);
9179 if (*p && !mch_isdir(p) && (fd = mch_fopen((char *)p, "r")) != NULL)
9181 n = TRUE;
9182 fclose(fd);
9184 else
9185 n = FALSE;
9187 rettv->vval.v_number = n;
9191 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
9192 * rights to write into.
9194 static void
9195 f_filewritable(argvars, rettv)
9196 typval_T *argvars;
9197 typval_T *rettv;
9199 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
9202 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int dir));
9204 static void
9205 findfilendir(argvars, rettv, dir)
9206 typval_T *argvars;
9207 typval_T *rettv;
9208 int dir;
9210 #ifdef FEAT_SEARCHPATH
9211 char_u *fname;
9212 char_u *fresult = NULL;
9213 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
9214 char_u *p;
9215 char_u pathbuf[NUMBUFLEN];
9216 int count = 1;
9217 int first = TRUE;
9218 int error = FALSE;
9219 #endif
9221 rettv->vval.v_string = NULL;
9222 rettv->v_type = VAR_STRING;
9224 #ifdef FEAT_SEARCHPATH
9225 fname = get_tv_string(&argvars[0]);
9227 if (argvars[1].v_type != VAR_UNKNOWN)
9229 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
9230 if (p == NULL)
9231 error = TRUE;
9232 else
9234 if (*p != NUL)
9235 path = p;
9237 if (argvars[2].v_type != VAR_UNKNOWN)
9238 count = get_tv_number_chk(&argvars[2], &error);
9242 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
9243 error = TRUE;
9245 if (*fname != NUL && !error)
9249 if (rettv->v_type == VAR_STRING)
9250 vim_free(fresult);
9251 fresult = find_file_in_path_option(first ? fname : NULL,
9252 first ? (int)STRLEN(fname) : 0,
9253 0, first, path, dir, curbuf->b_ffname,
9254 dir ? (char_u *)"" : curbuf->b_p_sua);
9255 first = FALSE;
9257 if (fresult != NULL && rettv->v_type == VAR_LIST)
9258 list_append_string(rettv->vval.v_list, fresult, -1);
9260 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
9263 if (rettv->v_type == VAR_STRING)
9264 rettv->vval.v_string = fresult;
9265 #endif
9268 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
9269 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
9272 * Implementation of map() and filter().
9274 static void
9275 filter_map(argvars, rettv, map)
9276 typval_T *argvars;
9277 typval_T *rettv;
9278 int map;
9280 char_u buf[NUMBUFLEN];
9281 char_u *expr;
9282 listitem_T *li, *nli;
9283 list_T *l = NULL;
9284 dictitem_T *di;
9285 hashtab_T *ht;
9286 hashitem_T *hi;
9287 dict_T *d = NULL;
9288 typval_T save_val;
9289 typval_T save_key;
9290 int rem;
9291 int todo;
9292 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
9293 int save_did_emsg;
9295 rettv->vval.v_number = 0;
9296 if (argvars[0].v_type == VAR_LIST)
9298 if ((l = argvars[0].vval.v_list) == NULL
9299 || (map && tv_check_lock(l->lv_lock, ermsg)))
9300 return;
9302 else if (argvars[0].v_type == VAR_DICT)
9304 if ((d = argvars[0].vval.v_dict) == NULL
9305 || (map && tv_check_lock(d->dv_lock, ermsg)))
9306 return;
9308 else
9310 EMSG2(_(e_listdictarg), ermsg);
9311 return;
9314 expr = get_tv_string_buf_chk(&argvars[1], buf);
9315 /* On type errors, the preceding call has already displayed an error
9316 * message. Avoid a misleading error message for an empty string that
9317 * was not passed as argument. */
9318 if (expr != NULL)
9320 prepare_vimvar(VV_VAL, &save_val);
9321 expr = skipwhite(expr);
9323 /* We reset "did_emsg" to be able to detect whether an error
9324 * occurred during evaluation of the expression. */
9325 save_did_emsg = did_emsg;
9326 did_emsg = FALSE;
9328 if (argvars[0].v_type == VAR_DICT)
9330 prepare_vimvar(VV_KEY, &save_key);
9331 vimvars[VV_KEY].vv_type = VAR_STRING;
9333 ht = &d->dv_hashtab;
9334 hash_lock(ht);
9335 todo = (int)ht->ht_used;
9336 for (hi = ht->ht_array; todo > 0; ++hi)
9338 if (!HASHITEM_EMPTY(hi))
9340 --todo;
9341 di = HI2DI(hi);
9342 if (tv_check_lock(di->di_tv.v_lock, ermsg))
9343 break;
9344 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
9345 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
9346 || did_emsg)
9347 break;
9348 if (!map && rem)
9349 dictitem_remove(d, di);
9350 clear_tv(&vimvars[VV_KEY].vv_tv);
9353 hash_unlock(ht);
9355 restore_vimvar(VV_KEY, &save_key);
9357 else
9359 for (li = l->lv_first; li != NULL; li = nli)
9361 if (tv_check_lock(li->li_tv.v_lock, ermsg))
9362 break;
9363 nli = li->li_next;
9364 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
9365 || did_emsg)
9366 break;
9367 if (!map && rem)
9368 listitem_remove(l, li);
9372 restore_vimvar(VV_VAL, &save_val);
9374 did_emsg |= save_did_emsg;
9377 copy_tv(&argvars[0], rettv);
9380 static int
9381 filter_map_one(tv, expr, map, remp)
9382 typval_T *tv;
9383 char_u *expr;
9384 int map;
9385 int *remp;
9387 typval_T rettv;
9388 char_u *s;
9389 int retval = FAIL;
9391 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
9392 s = expr;
9393 if (eval1(&s, &rettv, TRUE) == FAIL)
9394 goto theend;
9395 if (*s != NUL) /* check for trailing chars after expr */
9397 EMSG2(_(e_invexpr2), s);
9398 goto theend;
9400 if (map)
9402 /* map(): replace the list item value */
9403 clear_tv(tv);
9404 rettv.v_lock = 0;
9405 *tv = rettv;
9407 else
9409 int error = FALSE;
9411 /* filter(): when expr is zero remove the item */
9412 *remp = (get_tv_number_chk(&rettv, &error) == 0);
9413 clear_tv(&rettv);
9414 /* On type error, nothing has been removed; return FAIL to stop the
9415 * loop. The error message was given by get_tv_number_chk(). */
9416 if (error)
9417 goto theend;
9419 retval = OK;
9420 theend:
9421 clear_tv(&vimvars[VV_VAL].vv_tv);
9422 return retval;
9426 * "filter()" function
9428 static void
9429 f_filter(argvars, rettv)
9430 typval_T *argvars;
9431 typval_T *rettv;
9433 filter_map(argvars, rettv, FALSE);
9437 * "finddir({fname}[, {path}[, {count}]])" function
9439 static void
9440 f_finddir(argvars, rettv)
9441 typval_T *argvars;
9442 typval_T *rettv;
9444 findfilendir(argvars, rettv, TRUE);
9448 * "findfile({fname}[, {path}[, {count}]])" function
9450 static void
9451 f_findfile(argvars, rettv)
9452 typval_T *argvars;
9453 typval_T *rettv;
9455 findfilendir(argvars, rettv, FALSE);
9459 * "fnamemodify({fname}, {mods})" function
9461 static void
9462 f_fnamemodify(argvars, rettv)
9463 typval_T *argvars;
9464 typval_T *rettv;
9466 char_u *fname;
9467 char_u *mods;
9468 int usedlen = 0;
9469 int len;
9470 char_u *fbuf = NULL;
9471 char_u buf[NUMBUFLEN];
9473 fname = get_tv_string_chk(&argvars[0]);
9474 mods = get_tv_string_buf_chk(&argvars[1], buf);
9475 if (fname == NULL || mods == NULL)
9476 fname = NULL;
9477 else
9479 len = (int)STRLEN(fname);
9480 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
9483 rettv->v_type = VAR_STRING;
9484 if (fname == NULL)
9485 rettv->vval.v_string = NULL;
9486 else
9487 rettv->vval.v_string = vim_strnsave(fname, len);
9488 vim_free(fbuf);
9491 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
9494 * "foldclosed()" function
9496 static void
9497 foldclosed_both(argvars, rettv, end)
9498 typval_T *argvars;
9499 typval_T *rettv;
9500 int end;
9502 #ifdef FEAT_FOLDING
9503 linenr_T lnum;
9504 linenr_T first, last;
9506 lnum = get_tv_lnum(argvars);
9507 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9509 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
9511 if (end)
9512 rettv->vval.v_number = (varnumber_T)last;
9513 else
9514 rettv->vval.v_number = (varnumber_T)first;
9515 return;
9518 #endif
9519 rettv->vval.v_number = -1;
9523 * "foldclosed()" function
9525 static void
9526 f_foldclosed(argvars, rettv)
9527 typval_T *argvars;
9528 typval_T *rettv;
9530 foldclosed_both(argvars, rettv, FALSE);
9534 * "foldclosedend()" function
9536 static void
9537 f_foldclosedend(argvars, rettv)
9538 typval_T *argvars;
9539 typval_T *rettv;
9541 foldclosed_both(argvars, rettv, TRUE);
9545 * "foldlevel()" function
9547 static void
9548 f_foldlevel(argvars, rettv)
9549 typval_T *argvars;
9550 typval_T *rettv;
9552 #ifdef FEAT_FOLDING
9553 linenr_T lnum;
9555 lnum = get_tv_lnum(argvars);
9556 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9557 rettv->vval.v_number = foldLevel(lnum);
9558 else
9559 #endif
9560 rettv->vval.v_number = 0;
9564 * "foldtext()" function
9566 /*ARGSUSED*/
9567 static void
9568 f_foldtext(argvars, rettv)
9569 typval_T *argvars;
9570 typval_T *rettv;
9572 #ifdef FEAT_FOLDING
9573 linenr_T lnum;
9574 char_u *s;
9575 char_u *r;
9576 int len;
9577 char *txt;
9578 #endif
9580 rettv->v_type = VAR_STRING;
9581 rettv->vval.v_string = NULL;
9582 #ifdef FEAT_FOLDING
9583 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
9584 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
9585 <= curbuf->b_ml.ml_line_count
9586 && vimvars[VV_FOLDDASHES].vv_str != NULL)
9588 /* Find first non-empty line in the fold. */
9589 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
9590 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
9592 if (!linewhite(lnum))
9593 break;
9594 ++lnum;
9597 /* Find interesting text in this line. */
9598 s = skipwhite(ml_get(lnum));
9599 /* skip C comment-start */
9600 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
9602 s = skipwhite(s + 2);
9603 if (*skipwhite(s) == NUL
9604 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
9606 s = skipwhite(ml_get(lnum + 1));
9607 if (*s == '*')
9608 s = skipwhite(s + 1);
9611 txt = _("+-%s%3ld lines: ");
9612 r = alloc((unsigned)(STRLEN(txt)
9613 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
9614 + 20 /* for %3ld */
9615 + STRLEN(s))); /* concatenated */
9616 if (r != NULL)
9618 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
9619 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
9620 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
9621 len = (int)STRLEN(r);
9622 STRCAT(r, s);
9623 /* remove 'foldmarker' and 'commentstring' */
9624 foldtext_cleanup(r + len);
9625 rettv->vval.v_string = r;
9628 #endif
9632 * "foldtextresult(lnum)" function
9634 /*ARGSUSED*/
9635 static void
9636 f_foldtextresult(argvars, rettv)
9637 typval_T *argvars;
9638 typval_T *rettv;
9640 #ifdef FEAT_FOLDING
9641 linenr_T lnum;
9642 char_u *text;
9643 char_u buf[51];
9644 foldinfo_T foldinfo;
9645 int fold_count;
9646 #endif
9648 rettv->v_type = VAR_STRING;
9649 rettv->vval.v_string = NULL;
9650 #ifdef FEAT_FOLDING
9651 lnum = get_tv_lnum(argvars);
9652 /* treat illegal types and illegal string values for {lnum} the same */
9653 if (lnum < 0)
9654 lnum = 0;
9655 fold_count = foldedCount(curwin, lnum, &foldinfo);
9656 if (fold_count > 0)
9658 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
9659 &foldinfo, buf);
9660 if (text == buf)
9661 text = vim_strsave(text);
9662 rettv->vval.v_string = text;
9664 #endif
9668 * "foreground()" function
9670 /*ARGSUSED*/
9671 static void
9672 f_foreground(argvars, rettv)
9673 typval_T *argvars;
9674 typval_T *rettv;
9676 rettv->vval.v_number = 0;
9677 #ifdef FEAT_GUI
9678 if (gui.in_use)
9679 gui_mch_set_foreground();
9680 #else
9681 # ifdef WIN32
9682 win32_set_foreground();
9683 # endif
9684 #endif
9688 * "function()" function
9690 /*ARGSUSED*/
9691 static void
9692 f_function(argvars, rettv)
9693 typval_T *argvars;
9694 typval_T *rettv;
9696 char_u *s;
9698 rettv->vval.v_number = 0;
9699 s = get_tv_string(&argvars[0]);
9700 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
9701 EMSG2(_(e_invarg2), s);
9702 else if (!function_exists(s))
9703 EMSG2(_("E700: Unknown function: %s"), s);
9704 else
9706 rettv->vval.v_string = vim_strsave(s);
9707 rettv->v_type = VAR_FUNC;
9712 * "garbagecollect()" function
9714 /*ARGSUSED*/
9715 static void
9716 f_garbagecollect(argvars, rettv)
9717 typval_T *argvars;
9718 typval_T *rettv;
9720 /* This is postponed until we are back at the toplevel, because we may be
9721 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
9722 want_garbage_collect = TRUE;
9724 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
9725 garbage_collect_at_exit = TRUE;
9729 * "get()" function
9731 static void
9732 f_get(argvars, rettv)
9733 typval_T *argvars;
9734 typval_T *rettv;
9736 listitem_T *li;
9737 list_T *l;
9738 dictitem_T *di;
9739 dict_T *d;
9740 typval_T *tv = NULL;
9742 if (argvars[0].v_type == VAR_LIST)
9744 if ((l = argvars[0].vval.v_list) != NULL)
9746 int error = FALSE;
9748 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
9749 if (!error && li != NULL)
9750 tv = &li->li_tv;
9753 else if (argvars[0].v_type == VAR_DICT)
9755 if ((d = argvars[0].vval.v_dict) != NULL)
9757 di = dict_find(d, get_tv_string(&argvars[1]), -1);
9758 if (di != NULL)
9759 tv = &di->di_tv;
9762 else
9763 EMSG2(_(e_listdictarg), "get()");
9765 if (tv == NULL)
9767 if (argvars[2].v_type == VAR_UNKNOWN)
9768 rettv->vval.v_number = 0;
9769 else
9770 copy_tv(&argvars[2], rettv);
9772 else
9773 copy_tv(tv, rettv);
9776 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
9779 * Get line or list of lines from buffer "buf" into "rettv".
9780 * Return a range (from start to end) of lines in rettv from the specified
9781 * buffer.
9782 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
9784 static void
9785 get_buffer_lines(buf, start, end, retlist, rettv)
9786 buf_T *buf;
9787 linenr_T start;
9788 linenr_T end;
9789 int retlist;
9790 typval_T *rettv;
9792 char_u *p;
9794 if (retlist)
9796 if (rettv_list_alloc(rettv) == FAIL)
9797 return;
9799 else
9800 rettv->vval.v_number = 0;
9802 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
9803 return;
9805 if (!retlist)
9807 if (start >= 1 && start <= buf->b_ml.ml_line_count)
9808 p = ml_get_buf(buf, start, FALSE);
9809 else
9810 p = (char_u *)"";
9812 rettv->v_type = VAR_STRING;
9813 rettv->vval.v_string = vim_strsave(p);
9815 else
9817 if (end < start)
9818 return;
9820 if (start < 1)
9821 start = 1;
9822 if (end > buf->b_ml.ml_line_count)
9823 end = buf->b_ml.ml_line_count;
9824 while (start <= end)
9825 if (list_append_string(rettv->vval.v_list,
9826 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
9827 break;
9832 * "getbufline()" function
9834 static void
9835 f_getbufline(argvars, rettv)
9836 typval_T *argvars;
9837 typval_T *rettv;
9839 linenr_T lnum;
9840 linenr_T end;
9841 buf_T *buf;
9843 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
9844 ++emsg_off;
9845 buf = get_buf_tv(&argvars[0]);
9846 --emsg_off;
9848 lnum = get_tv_lnum_buf(&argvars[1], buf);
9849 if (argvars[2].v_type == VAR_UNKNOWN)
9850 end = lnum;
9851 else
9852 end = get_tv_lnum_buf(&argvars[2], buf);
9854 get_buffer_lines(buf, lnum, end, TRUE, rettv);
9858 * "getbufvar()" function
9860 static void
9861 f_getbufvar(argvars, rettv)
9862 typval_T *argvars;
9863 typval_T *rettv;
9865 buf_T *buf;
9866 buf_T *save_curbuf;
9867 char_u *varname;
9868 dictitem_T *v;
9870 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
9871 varname = get_tv_string_chk(&argvars[1]);
9872 ++emsg_off;
9873 buf = get_buf_tv(&argvars[0]);
9875 rettv->v_type = VAR_STRING;
9876 rettv->vval.v_string = NULL;
9878 if (buf != NULL && varname != NULL)
9880 if (*varname == '&') /* buffer-local-option */
9882 /* set curbuf to be our buf, temporarily */
9883 save_curbuf = curbuf;
9884 curbuf = buf;
9886 get_option_tv(&varname, rettv, TRUE);
9888 /* restore previous notion of curbuf */
9889 curbuf = save_curbuf;
9891 else
9893 if (*varname == NUL)
9894 /* let getbufvar({nr}, "") return the "b:" dictionary. The
9895 * scope prefix before the NUL byte is required by
9896 * find_var_in_ht(). */
9897 varname = (char_u *)"b:" + 2;
9898 /* look up the variable */
9899 v = find_var_in_ht(&buf->b_vars.dv_hashtab, varname, FALSE);
9900 if (v != NULL)
9901 copy_tv(&v->di_tv, rettv);
9905 --emsg_off;
9909 * "getchar()" function
9911 static void
9912 f_getchar(argvars, rettv)
9913 typval_T *argvars;
9914 typval_T *rettv;
9916 varnumber_T n;
9917 int error = FALSE;
9919 /* Position the cursor. Needed after a message that ends in a space. */
9920 windgoto(msg_row, msg_col);
9922 ++no_mapping;
9923 ++allow_keys;
9924 for (;;)
9926 if (argvars[0].v_type == VAR_UNKNOWN)
9927 /* getchar(): blocking wait. */
9928 n = safe_vgetc();
9929 else if (get_tv_number_chk(&argvars[0], &error) == 1)
9930 /* getchar(1): only check if char avail */
9931 n = vpeekc();
9932 else if (error || vpeekc() == NUL)
9933 /* illegal argument or getchar(0) and no char avail: return zero */
9934 n = 0;
9935 else
9936 /* getchar(0) and char avail: return char */
9937 n = safe_vgetc();
9938 if (n == K_IGNORE)
9939 continue;
9940 break;
9942 --no_mapping;
9943 --allow_keys;
9945 vimvars[VV_MOUSE_WIN].vv_nr = 0;
9946 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
9947 vimvars[VV_MOUSE_COL].vv_nr = 0;
9949 rettv->vval.v_number = n;
9950 if (IS_SPECIAL(n) || mod_mask != 0)
9952 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
9953 int i = 0;
9955 /* Turn a special key into three bytes, plus modifier. */
9956 if (mod_mask != 0)
9958 temp[i++] = K_SPECIAL;
9959 temp[i++] = KS_MODIFIER;
9960 temp[i++] = mod_mask;
9962 if (IS_SPECIAL(n))
9964 temp[i++] = K_SPECIAL;
9965 temp[i++] = K_SECOND(n);
9966 temp[i++] = K_THIRD(n);
9968 #ifdef FEAT_MBYTE
9969 else if (has_mbyte)
9970 i += (*mb_char2bytes)(n, temp + i);
9971 #endif
9972 else
9973 temp[i++] = n;
9974 temp[i++] = NUL;
9975 rettv->v_type = VAR_STRING;
9976 rettv->vval.v_string = vim_strsave(temp);
9978 #ifdef FEAT_MOUSE
9979 if (n == K_LEFTMOUSE
9980 || n == K_LEFTMOUSE_NM
9981 || n == K_LEFTDRAG
9982 || n == K_LEFTRELEASE
9983 || n == K_LEFTRELEASE_NM
9984 || n == K_MIDDLEMOUSE
9985 || n == K_MIDDLEDRAG
9986 || n == K_MIDDLERELEASE
9987 || n == K_RIGHTMOUSE
9988 || n == K_RIGHTDRAG
9989 || n == K_RIGHTRELEASE
9990 || n == K_X1MOUSE
9991 || n == K_X1DRAG
9992 || n == K_X1RELEASE
9993 || n == K_X2MOUSE
9994 || n == K_X2DRAG
9995 || n == K_X2RELEASE
9996 || n == K_MOUSEDOWN
9997 || n == K_MOUSEUP)
9999 int row = mouse_row;
10000 int col = mouse_col;
10001 win_T *win;
10002 linenr_T lnum;
10003 # ifdef FEAT_WINDOWS
10004 win_T *wp;
10005 # endif
10006 int n = 1;
10008 if (row >= 0 && col >= 0)
10010 /* Find the window at the mouse coordinates and compute the
10011 * text position. */
10012 win = mouse_find_win(&row, &col);
10013 (void)mouse_comp_pos(win, &row, &col, &lnum);
10014 # ifdef FEAT_WINDOWS
10015 for (wp = firstwin; wp != win; wp = wp->w_next)
10016 ++n;
10017 # endif
10018 vimvars[VV_MOUSE_WIN].vv_nr = n;
10019 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
10020 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
10023 #endif
10028 * "getcharmod()" function
10030 /*ARGSUSED*/
10031 static void
10032 f_getcharmod(argvars, rettv)
10033 typval_T *argvars;
10034 typval_T *rettv;
10036 rettv->vval.v_number = mod_mask;
10040 * "getcmdline()" function
10042 /*ARGSUSED*/
10043 static void
10044 f_getcmdline(argvars, rettv)
10045 typval_T *argvars;
10046 typval_T *rettv;
10048 rettv->v_type = VAR_STRING;
10049 rettv->vval.v_string = get_cmdline_str();
10053 * "getcmdpos()" function
10055 /*ARGSUSED*/
10056 static void
10057 f_getcmdpos(argvars, rettv)
10058 typval_T *argvars;
10059 typval_T *rettv;
10061 rettv->vval.v_number = get_cmdline_pos() + 1;
10065 * "getcmdtype()" function
10067 /*ARGSUSED*/
10068 static void
10069 f_getcmdtype(argvars, rettv)
10070 typval_T *argvars;
10071 typval_T *rettv;
10073 rettv->v_type = VAR_STRING;
10074 rettv->vval.v_string = alloc(2);
10075 if (rettv->vval.v_string != NULL)
10077 rettv->vval.v_string[0] = get_cmdline_type();
10078 rettv->vval.v_string[1] = NUL;
10083 * "getcwd()" function
10085 /*ARGSUSED*/
10086 static void
10087 f_getcwd(argvars, rettv)
10088 typval_T *argvars;
10089 typval_T *rettv;
10091 char_u cwd[MAXPATHL];
10093 rettv->v_type = VAR_STRING;
10094 if (mch_dirname(cwd, MAXPATHL) == FAIL)
10095 rettv->vval.v_string = NULL;
10096 else
10098 rettv->vval.v_string = vim_strsave(cwd);
10099 #ifdef BACKSLASH_IN_FILENAME
10100 if (rettv->vval.v_string != NULL)
10101 slash_adjust(rettv->vval.v_string);
10102 #endif
10107 * "getfontname()" function
10109 /*ARGSUSED*/
10110 static void
10111 f_getfontname(argvars, rettv)
10112 typval_T *argvars;
10113 typval_T *rettv;
10115 rettv->v_type = VAR_STRING;
10116 rettv->vval.v_string = NULL;
10117 #ifdef FEAT_GUI
10118 if (gui.in_use)
10120 GuiFont font;
10121 char_u *name = NULL;
10123 if (argvars[0].v_type == VAR_UNKNOWN)
10125 /* Get the "Normal" font. Either the name saved by
10126 * hl_set_font_name() or from the font ID. */
10127 font = gui.norm_font;
10128 name = hl_get_font_name();
10130 else
10132 name = get_tv_string(&argvars[0]);
10133 if (STRCMP(name, "*") == 0) /* don't use font dialog */
10134 return;
10135 font = gui_mch_get_font(name, FALSE);
10136 if (font == NOFONT)
10137 return; /* Invalid font name, return empty string. */
10139 rettv->vval.v_string = gui_mch_get_fontname(font, name);
10140 if (argvars[0].v_type != VAR_UNKNOWN)
10141 gui_mch_free_font(font);
10143 #endif
10147 * "getfperm({fname})" function
10149 static void
10150 f_getfperm(argvars, rettv)
10151 typval_T *argvars;
10152 typval_T *rettv;
10154 char_u *fname;
10155 struct stat st;
10156 char_u *perm = NULL;
10157 char_u flags[] = "rwx";
10158 int i;
10160 fname = get_tv_string(&argvars[0]);
10162 rettv->v_type = VAR_STRING;
10163 if (mch_stat((char *)fname, &st) >= 0)
10165 perm = vim_strsave((char_u *)"---------");
10166 if (perm != NULL)
10168 for (i = 0; i < 9; i++)
10170 if (st.st_mode & (1 << (8 - i)))
10171 perm[i] = flags[i % 3];
10175 rettv->vval.v_string = perm;
10179 * "getfsize({fname})" function
10181 static void
10182 f_getfsize(argvars, rettv)
10183 typval_T *argvars;
10184 typval_T *rettv;
10186 char_u *fname;
10187 struct stat st;
10189 fname = get_tv_string(&argvars[0]);
10191 rettv->v_type = VAR_NUMBER;
10193 if (mch_stat((char *)fname, &st) >= 0)
10195 if (mch_isdir(fname))
10196 rettv->vval.v_number = 0;
10197 else
10199 rettv->vval.v_number = (varnumber_T)st.st_size;
10201 /* non-perfect check for overflow */
10202 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
10203 rettv->vval.v_number = -2;
10206 else
10207 rettv->vval.v_number = -1;
10211 * "getftime({fname})" function
10213 static void
10214 f_getftime(argvars, rettv)
10215 typval_T *argvars;
10216 typval_T *rettv;
10218 char_u *fname;
10219 struct stat st;
10221 fname = get_tv_string(&argvars[0]);
10223 if (mch_stat((char *)fname, &st) >= 0)
10224 rettv->vval.v_number = (varnumber_T)st.st_mtime;
10225 else
10226 rettv->vval.v_number = -1;
10230 * "getftype({fname})" function
10232 static void
10233 f_getftype(argvars, rettv)
10234 typval_T *argvars;
10235 typval_T *rettv;
10237 char_u *fname;
10238 struct stat st;
10239 char_u *type = NULL;
10240 char *t;
10242 fname = get_tv_string(&argvars[0]);
10244 rettv->v_type = VAR_STRING;
10245 if (mch_lstat((char *)fname, &st) >= 0)
10247 #ifdef S_ISREG
10248 if (S_ISREG(st.st_mode))
10249 t = "file";
10250 else if (S_ISDIR(st.st_mode))
10251 t = "dir";
10252 # ifdef S_ISLNK
10253 else if (S_ISLNK(st.st_mode))
10254 t = "link";
10255 # endif
10256 # ifdef S_ISBLK
10257 else if (S_ISBLK(st.st_mode))
10258 t = "bdev";
10259 # endif
10260 # ifdef S_ISCHR
10261 else if (S_ISCHR(st.st_mode))
10262 t = "cdev";
10263 # endif
10264 # ifdef S_ISFIFO
10265 else if (S_ISFIFO(st.st_mode))
10266 t = "fifo";
10267 # endif
10268 # ifdef S_ISSOCK
10269 else if (S_ISSOCK(st.st_mode))
10270 t = "fifo";
10271 # endif
10272 else
10273 t = "other";
10274 #else
10275 # ifdef S_IFMT
10276 switch (st.st_mode & S_IFMT)
10278 case S_IFREG: t = "file"; break;
10279 case S_IFDIR: t = "dir"; break;
10280 # ifdef S_IFLNK
10281 case S_IFLNK: t = "link"; break;
10282 # endif
10283 # ifdef S_IFBLK
10284 case S_IFBLK: t = "bdev"; break;
10285 # endif
10286 # ifdef S_IFCHR
10287 case S_IFCHR: t = "cdev"; break;
10288 # endif
10289 # ifdef S_IFIFO
10290 case S_IFIFO: t = "fifo"; break;
10291 # endif
10292 # ifdef S_IFSOCK
10293 case S_IFSOCK: t = "socket"; break;
10294 # endif
10295 default: t = "other";
10297 # else
10298 if (mch_isdir(fname))
10299 t = "dir";
10300 else
10301 t = "file";
10302 # endif
10303 #endif
10304 type = vim_strsave((char_u *)t);
10306 rettv->vval.v_string = type;
10310 * "getline(lnum, [end])" function
10312 static void
10313 f_getline(argvars, rettv)
10314 typval_T *argvars;
10315 typval_T *rettv;
10317 linenr_T lnum;
10318 linenr_T end;
10319 int retlist;
10321 lnum = get_tv_lnum(argvars);
10322 if (argvars[1].v_type == VAR_UNKNOWN)
10324 end = 0;
10325 retlist = FALSE;
10327 else
10329 end = get_tv_lnum(&argvars[1]);
10330 retlist = TRUE;
10333 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
10337 * "getmatches()" function
10339 /*ARGSUSED*/
10340 static void
10341 f_getmatches(argvars, rettv)
10342 typval_T *argvars;
10343 typval_T *rettv;
10345 #ifdef FEAT_SEARCH_EXTRA
10346 dict_T *dict;
10347 matchitem_T *cur = curwin->w_match_head;
10349 rettv->vval.v_number = 0;
10351 if (rettv_list_alloc(rettv) == OK)
10353 while (cur != NULL)
10355 dict = dict_alloc();
10356 if (dict == NULL)
10357 return;
10358 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
10359 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
10360 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
10361 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
10362 list_append_dict(rettv->vval.v_list, dict);
10363 cur = cur->next;
10366 #endif
10370 * "getpos(string)" function
10372 static void
10373 f_getpos(argvars, rettv)
10374 typval_T *argvars;
10375 typval_T *rettv;
10377 pos_T *fp;
10378 list_T *l;
10379 int fnum = -1;
10381 if (rettv_list_alloc(rettv) == OK)
10383 l = rettv->vval.v_list;
10384 fp = var2fpos(&argvars[0], TRUE, &fnum);
10385 if (fnum != -1)
10386 list_append_number(l, (varnumber_T)fnum);
10387 else
10388 list_append_number(l, (varnumber_T)0);
10389 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
10390 : (varnumber_T)0);
10391 list_append_number(l, (fp != NULL)
10392 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
10393 : (varnumber_T)0);
10394 list_append_number(l,
10395 #ifdef FEAT_VIRTUALEDIT
10396 (fp != NULL) ? (varnumber_T)fp->coladd :
10397 #endif
10398 (varnumber_T)0);
10400 else
10401 rettv->vval.v_number = FALSE;
10405 * "getqflist()" and "getloclist()" functions
10407 /*ARGSUSED*/
10408 static void
10409 f_getqflist(argvars, rettv)
10410 typval_T *argvars;
10411 typval_T *rettv;
10413 #ifdef FEAT_QUICKFIX
10414 win_T *wp;
10415 #endif
10417 rettv->vval.v_number = 0;
10418 #ifdef FEAT_QUICKFIX
10419 if (rettv_list_alloc(rettv) == OK)
10421 wp = NULL;
10422 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
10424 wp = find_win_by_nr(&argvars[0], NULL);
10425 if (wp == NULL)
10426 return;
10429 (void)get_errorlist(wp, rettv->vval.v_list);
10431 #endif
10435 * "getreg()" function
10437 static void
10438 f_getreg(argvars, rettv)
10439 typval_T *argvars;
10440 typval_T *rettv;
10442 char_u *strregname;
10443 int regname;
10444 int arg2 = FALSE;
10445 int error = FALSE;
10447 if (argvars[0].v_type != VAR_UNKNOWN)
10449 strregname = get_tv_string_chk(&argvars[0]);
10450 error = strregname == NULL;
10451 if (argvars[1].v_type != VAR_UNKNOWN)
10452 arg2 = get_tv_number_chk(&argvars[1], &error);
10454 else
10455 strregname = vimvars[VV_REG].vv_str;
10456 regname = (strregname == NULL ? '"' : *strregname);
10457 if (regname == 0)
10458 regname = '"';
10460 rettv->v_type = VAR_STRING;
10461 rettv->vval.v_string = error ? NULL :
10462 get_reg_contents(regname, TRUE, arg2);
10466 * "getregtype()" function
10468 static void
10469 f_getregtype(argvars, rettv)
10470 typval_T *argvars;
10471 typval_T *rettv;
10473 char_u *strregname;
10474 int regname;
10475 char_u buf[NUMBUFLEN + 2];
10476 long reglen = 0;
10478 if (argvars[0].v_type != VAR_UNKNOWN)
10480 strregname = get_tv_string_chk(&argvars[0]);
10481 if (strregname == NULL) /* type error; errmsg already given */
10483 rettv->v_type = VAR_STRING;
10484 rettv->vval.v_string = NULL;
10485 return;
10488 else
10489 /* Default to v:register */
10490 strregname = vimvars[VV_REG].vv_str;
10492 regname = (strregname == NULL ? '"' : *strregname);
10493 if (regname == 0)
10494 regname = '"';
10496 buf[0] = NUL;
10497 buf[1] = NUL;
10498 switch (get_reg_type(regname, &reglen))
10500 case MLINE: buf[0] = 'V'; break;
10501 case MCHAR: buf[0] = 'v'; break;
10502 #ifdef FEAT_VISUAL
10503 case MBLOCK:
10504 buf[0] = Ctrl_V;
10505 sprintf((char *)buf + 1, "%ld", reglen + 1);
10506 break;
10507 #endif
10509 rettv->v_type = VAR_STRING;
10510 rettv->vval.v_string = vim_strsave(buf);
10514 * "gettabwinvar()" function
10516 static void
10517 f_gettabwinvar(argvars, rettv)
10518 typval_T *argvars;
10519 typval_T *rettv;
10521 getwinvar(argvars, rettv, 1);
10525 * "getwinposx()" function
10527 /*ARGSUSED*/
10528 static void
10529 f_getwinposx(argvars, rettv)
10530 typval_T *argvars;
10531 typval_T *rettv;
10533 rettv->vval.v_number = -1;
10534 #ifdef FEAT_GUI
10535 if (gui.in_use)
10537 int x, y;
10539 if (gui_mch_get_winpos(&x, &y) == OK)
10540 rettv->vval.v_number = x;
10542 #endif
10546 * "getwinposy()" function
10548 /*ARGSUSED*/
10549 static void
10550 f_getwinposy(argvars, rettv)
10551 typval_T *argvars;
10552 typval_T *rettv;
10554 rettv->vval.v_number = -1;
10555 #ifdef FEAT_GUI
10556 if (gui.in_use)
10558 int x, y;
10560 if (gui_mch_get_winpos(&x, &y) == OK)
10561 rettv->vval.v_number = y;
10563 #endif
10567 * Find window specifed by "vp" in tabpage "tp".
10569 static win_T *
10570 find_win_by_nr(vp, tp)
10571 typval_T *vp;
10572 tabpage_T *tp; /* NULL for current tab page */
10574 #ifdef FEAT_WINDOWS
10575 win_T *wp;
10576 #endif
10577 int nr;
10579 nr = get_tv_number_chk(vp, NULL);
10581 #ifdef FEAT_WINDOWS
10582 if (nr < 0)
10583 return NULL;
10584 if (nr == 0)
10585 return curwin;
10587 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
10588 wp != NULL; wp = wp->w_next)
10589 if (--nr <= 0)
10590 break;
10591 return wp;
10592 #else
10593 if (nr == 0 || nr == 1)
10594 return curwin;
10595 return NULL;
10596 #endif
10600 * "getwinvar()" function
10602 static void
10603 f_getwinvar(argvars, rettv)
10604 typval_T *argvars;
10605 typval_T *rettv;
10607 getwinvar(argvars, rettv, 0);
10611 * getwinvar() and gettabwinvar()
10613 static void
10614 getwinvar(argvars, rettv, off)
10615 typval_T *argvars;
10616 typval_T *rettv;
10617 int off; /* 1 for gettabwinvar() */
10619 win_T *win, *oldcurwin;
10620 char_u *varname;
10621 dictitem_T *v;
10622 tabpage_T *tp;
10624 #ifdef FEAT_WINDOWS
10625 if (off == 1)
10626 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
10627 else
10628 tp = curtab;
10629 #endif
10630 win = find_win_by_nr(&argvars[off], tp);
10631 varname = get_tv_string_chk(&argvars[off + 1]);
10632 ++emsg_off;
10634 rettv->v_type = VAR_STRING;
10635 rettv->vval.v_string = NULL;
10637 if (win != NULL && varname != NULL)
10639 /* Set curwin to be our win, temporarily. Also set curbuf, so
10640 * that we can get buffer-local options. */
10641 oldcurwin = curwin;
10642 curwin = win;
10643 curbuf = win->w_buffer;
10645 if (*varname == '&') /* window-local-option */
10646 get_option_tv(&varname, rettv, 1);
10647 else
10649 if (*varname == NUL)
10650 /* let getwinvar({nr}, "") return the "w:" dictionary. The
10651 * scope prefix before the NUL byte is required by
10652 * find_var_in_ht(). */
10653 varname = (char_u *)"w:" + 2;
10654 /* look up the variable */
10655 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
10656 if (v != NULL)
10657 copy_tv(&v->di_tv, rettv);
10660 /* restore previous notion of curwin */
10661 curwin = oldcurwin;
10662 curbuf = curwin->w_buffer;
10665 --emsg_off;
10669 * "glob()" function
10671 static void
10672 f_glob(argvars, rettv)
10673 typval_T *argvars;
10674 typval_T *rettv;
10676 expand_T xpc;
10678 ExpandInit(&xpc);
10679 xpc.xp_context = EXPAND_FILES;
10680 rettv->v_type = VAR_STRING;
10681 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
10682 NULL, WILD_USE_NL|WILD_SILENT, WILD_ALL);
10686 * "globpath()" function
10688 static void
10689 f_globpath(argvars, rettv)
10690 typval_T *argvars;
10691 typval_T *rettv;
10693 char_u buf1[NUMBUFLEN];
10694 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
10696 rettv->v_type = VAR_STRING;
10697 if (file == NULL)
10698 rettv->vval.v_string = NULL;
10699 else
10700 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file);
10704 * "has()" function
10706 static void
10707 f_has(argvars, rettv)
10708 typval_T *argvars;
10709 typval_T *rettv;
10711 int i;
10712 char_u *name;
10713 int n = FALSE;
10714 static char *(has_list[]) =
10716 #ifdef AMIGA
10717 "amiga",
10718 # ifdef FEAT_ARP
10719 "arp",
10720 # endif
10721 #endif
10722 #ifdef __BEOS__
10723 "beos",
10724 #endif
10725 #ifdef MSDOS
10726 # ifdef DJGPP
10727 "dos32",
10728 # else
10729 "dos16",
10730 # endif
10731 #endif
10732 #ifdef MACOS
10733 "mac",
10734 #endif
10735 #if defined(MACOS_X_UNIX)
10736 "macunix",
10737 #endif
10738 #ifdef OS2
10739 "os2",
10740 #endif
10741 #ifdef __QNX__
10742 "qnx",
10743 #endif
10744 #ifdef RISCOS
10745 "riscos",
10746 #endif
10747 #ifdef UNIX
10748 "unix",
10749 #endif
10750 #ifdef VMS
10751 "vms",
10752 #endif
10753 #ifdef WIN16
10754 "win16",
10755 #endif
10756 #ifdef WIN32
10757 "win32",
10758 #endif
10759 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
10760 "win32unix",
10761 #endif
10762 #ifdef WIN64
10763 "win64",
10764 #endif
10765 #ifdef EBCDIC
10766 "ebcdic",
10767 #endif
10768 #ifndef CASE_INSENSITIVE_FILENAME
10769 "fname_case",
10770 #endif
10771 #ifdef FEAT_ARABIC
10772 "arabic",
10773 #endif
10774 #ifdef FEAT_AUTOCMD
10775 "autocmd",
10776 #endif
10777 #ifdef FEAT_BEVAL
10778 "balloon_eval",
10779 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
10780 "balloon_multiline",
10781 # endif
10782 #endif
10783 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
10784 "builtin_terms",
10785 # ifdef ALL_BUILTIN_TCAPS
10786 "all_builtin_terms",
10787 # endif
10788 #endif
10789 #ifdef FEAT_BYTEOFF
10790 "byte_offset",
10791 #endif
10792 #ifdef FEAT_CINDENT
10793 "cindent",
10794 #endif
10795 #ifdef FEAT_CLIENTSERVER
10796 "clientserver",
10797 #endif
10798 #ifdef FEAT_CLIPBOARD
10799 "clipboard",
10800 #endif
10801 #ifdef FEAT_CMDL_COMPL
10802 "cmdline_compl",
10803 #endif
10804 #ifdef FEAT_CMDHIST
10805 "cmdline_hist",
10806 #endif
10807 #ifdef FEAT_COMMENTS
10808 "comments",
10809 #endif
10810 #ifdef FEAT_CRYPT
10811 "cryptv",
10812 #endif
10813 #ifdef FEAT_CSCOPE
10814 "cscope",
10815 #endif
10816 #ifdef CURSOR_SHAPE
10817 "cursorshape",
10818 #endif
10819 #ifdef DEBUG
10820 "debug",
10821 #endif
10822 #ifdef FEAT_CON_DIALOG
10823 "dialog_con",
10824 #endif
10825 #ifdef FEAT_GUI_DIALOG
10826 "dialog_gui",
10827 #endif
10828 #ifdef FEAT_DIFF
10829 "diff",
10830 #endif
10831 #ifdef FEAT_DIGRAPHS
10832 "digraphs",
10833 #endif
10834 #ifdef FEAT_DND
10835 "dnd",
10836 #endif
10837 #ifdef FEAT_EMACS_TAGS
10838 "emacs_tags",
10839 #endif
10840 "eval", /* always present, of course! */
10841 #ifdef FEAT_EX_EXTRA
10842 "ex_extra",
10843 #endif
10844 #ifdef FEAT_SEARCH_EXTRA
10845 "extra_search",
10846 #endif
10847 #ifdef FEAT_FKMAP
10848 "farsi",
10849 #endif
10850 #ifdef FEAT_SEARCHPATH
10851 "file_in_path",
10852 #endif
10853 #if defined(UNIX) && !defined(USE_SYSTEM)
10854 "filterpipe",
10855 #endif
10856 #ifdef FEAT_FIND_ID
10857 "find_in_path",
10858 #endif
10859 #ifdef FEAT_FOLDING
10860 "folding",
10861 #endif
10862 #ifdef FEAT_FOOTER
10863 "footer",
10864 #endif
10865 #if !defined(USE_SYSTEM) && defined(UNIX)
10866 "fork",
10867 #endif
10868 #ifdef FEAT_FULLSCREEN
10869 "fullscreen",
10870 #endif
10871 #ifdef FEAT_GETTEXT
10872 "gettext",
10873 #endif
10874 #ifdef FEAT_GUI
10875 "gui",
10876 #endif
10877 #ifdef FEAT_GUI_ATHENA
10878 # ifdef FEAT_GUI_NEXTAW
10879 "gui_neXtaw",
10880 # else
10881 "gui_athena",
10882 # endif
10883 #endif
10884 #ifdef FEAT_GUI_GTK
10885 "gui_gtk",
10886 # ifdef HAVE_GTK2
10887 "gui_gtk2",
10888 # endif
10889 #endif
10890 #ifdef FEAT_GUI_GNOME
10891 "gui_gnome",
10892 #endif
10893 #ifdef FEAT_GUI_MAC
10894 "gui_mac",
10895 #endif
10896 #ifdef FEAT_GUI_MACVIM
10897 "gui_macvim",
10898 #endif
10899 #ifdef FEAT_GUI_MOTIF
10900 "gui_motif",
10901 #endif
10902 #ifdef FEAT_GUI_PHOTON
10903 "gui_photon",
10904 #endif
10905 #ifdef FEAT_GUI_W16
10906 "gui_win16",
10907 #endif
10908 #ifdef FEAT_GUI_W32
10909 "gui_win32",
10910 #endif
10911 #ifdef FEAT_HANGULIN
10912 "hangul_input",
10913 #endif
10914 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
10915 "iconv",
10916 #endif
10917 #ifdef FEAT_INS_EXPAND
10918 "insert_expand",
10919 #endif
10920 #ifdef FEAT_JUMPLIST
10921 "jumplist",
10922 #endif
10923 #ifdef FEAT_KEYMAP
10924 "keymap",
10925 #endif
10926 #ifdef FEAT_LANGMAP
10927 "langmap",
10928 #endif
10929 #ifdef FEAT_LIBCALL
10930 "libcall",
10931 #endif
10932 #ifdef FEAT_LINEBREAK
10933 "linebreak",
10934 #endif
10935 #ifdef FEAT_LISP
10936 "lispindent",
10937 #endif
10938 #ifdef FEAT_LISTCMDS
10939 "listcmds",
10940 #endif
10941 #ifdef FEAT_LOCALMAP
10942 "localmap",
10943 #endif
10944 #ifdef FEAT_MENU
10945 "menu",
10946 #endif
10947 #ifdef FEAT_SESSION
10948 "mksession",
10949 #endif
10950 #ifdef FEAT_MODIFY_FNAME
10951 "modify_fname",
10952 #endif
10953 #ifdef FEAT_MOUSE
10954 "mouse",
10955 #endif
10956 #ifdef FEAT_MOUSESHAPE
10957 "mouseshape",
10958 #endif
10959 #if defined(UNIX) || defined(VMS)
10960 # ifdef FEAT_MOUSE_DEC
10961 "mouse_dec",
10962 # endif
10963 # ifdef FEAT_MOUSE_GPM
10964 "mouse_gpm",
10965 # endif
10966 # ifdef FEAT_MOUSE_JSB
10967 "mouse_jsbterm",
10968 # endif
10969 # ifdef FEAT_MOUSE_NET
10970 "mouse_netterm",
10971 # endif
10972 # ifdef FEAT_MOUSE_PTERM
10973 "mouse_pterm",
10974 # endif
10975 # ifdef FEAT_MOUSE_XTERM
10976 "mouse_xterm",
10977 # endif
10978 #endif
10979 #ifdef FEAT_MBYTE
10980 "multi_byte",
10981 #endif
10982 #ifdef FEAT_MBYTE_IME
10983 "multi_byte_ime",
10984 #endif
10985 #ifdef FEAT_MULTI_LANG
10986 "multi_lang",
10987 #endif
10988 #ifdef FEAT_MZSCHEME
10989 #ifndef DYNAMIC_MZSCHEME
10990 "mzscheme",
10991 #endif
10992 #endif
10993 #ifdef FEAT_OLE
10994 "ole",
10995 #endif
10996 #ifdef FEAT_OSFILETYPE
10997 "osfiletype",
10998 #endif
10999 #ifdef FEAT_PATH_EXTRA
11000 "path_extra",
11001 #endif
11002 #ifdef FEAT_PERL
11003 #ifndef DYNAMIC_PERL
11004 "perl",
11005 #endif
11006 #endif
11007 #ifdef FEAT_PYTHON
11008 #ifndef DYNAMIC_PYTHON
11009 "python",
11010 #endif
11011 #endif
11012 #ifdef FEAT_POSTSCRIPT
11013 "postscript",
11014 #endif
11015 #ifdef FEAT_PRINTER
11016 "printer",
11017 #endif
11018 #ifdef FEAT_PROFILE
11019 "profile",
11020 #endif
11021 #ifdef FEAT_RELTIME
11022 "reltime",
11023 #endif
11024 #ifdef FEAT_QUICKFIX
11025 "quickfix",
11026 #endif
11027 #ifdef FEAT_RIGHTLEFT
11028 "rightleft",
11029 #endif
11030 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11031 "ruby",
11032 #endif
11033 #ifdef FEAT_SCROLLBIND
11034 "scrollbind",
11035 #endif
11036 #ifdef FEAT_CMDL_INFO
11037 "showcmd",
11038 "cmdline_info",
11039 #endif
11040 #ifdef FEAT_SIGNS
11041 "signs",
11042 #endif
11043 #ifdef FEAT_SMARTINDENT
11044 "smartindent",
11045 #endif
11046 #ifdef FEAT_SNIFF
11047 "sniff",
11048 #endif
11049 #ifdef FEAT_STL_OPT
11050 "statusline",
11051 #endif
11052 #ifdef FEAT_SUN_WORKSHOP
11053 "sun_workshop",
11054 #endif
11055 #ifdef FEAT_NETBEANS_INTG
11056 "netbeans_intg",
11057 #endif
11058 #ifdef FEAT_ODB_EDITOR
11059 "odbeditor",
11060 #endif
11061 #ifdef FEAT_SPELL
11062 "spell",
11063 #endif
11064 #ifdef FEAT_SYN_HL
11065 "syntax",
11066 #endif
11067 #if defined(USE_SYSTEM) || !defined(UNIX)
11068 "system",
11069 #endif
11070 #ifdef FEAT_TAG_BINS
11071 "tag_binary",
11072 #endif
11073 #ifdef FEAT_TAG_OLDSTATIC
11074 "tag_old_static",
11075 #endif
11076 #ifdef FEAT_TAG_ANYWHITE
11077 "tag_any_white",
11078 #endif
11079 #ifdef FEAT_TCL
11080 # ifndef DYNAMIC_TCL
11081 "tcl",
11082 # endif
11083 #endif
11084 #ifdef TERMINFO
11085 "terminfo",
11086 #endif
11087 #ifdef FEAT_TERMRESPONSE
11088 "termresponse",
11089 #endif
11090 #ifdef FEAT_TEXTOBJ
11091 "textobjects",
11092 #endif
11093 #ifdef HAVE_TGETENT
11094 "tgetent",
11095 #endif
11096 #ifdef FEAT_TITLE
11097 "title",
11098 #endif
11099 #ifdef FEAT_TOOLBAR
11100 "toolbar",
11101 #endif
11102 #ifdef FEAT_TRANSPARENCY
11103 "transparency",
11104 #endif
11105 #ifdef FEAT_USR_CMDS
11106 "user-commands", /* was accidentally included in 5.4 */
11107 "user_commands",
11108 #endif
11109 #ifdef FEAT_VIMINFO
11110 "viminfo",
11111 #endif
11112 #ifdef FEAT_VERTSPLIT
11113 "vertsplit",
11114 #endif
11115 #ifdef FEAT_VIRTUALEDIT
11116 "virtualedit",
11117 #endif
11118 #ifdef FEAT_VISUAL
11119 "visual",
11120 #endif
11121 #ifdef FEAT_VISUALEXTRA
11122 "visualextra",
11123 #endif
11124 #ifdef FEAT_VREPLACE
11125 "vreplace",
11126 #endif
11127 #ifdef FEAT_WILDIGN
11128 "wildignore",
11129 #endif
11130 #ifdef FEAT_WILDMENU
11131 "wildmenu",
11132 #endif
11133 #ifdef FEAT_WINDOWS
11134 "windows",
11135 #endif
11136 #ifdef FEAT_WAK
11137 "winaltkeys",
11138 #endif
11139 #ifdef FEAT_WRITEBACKUP
11140 "writebackup",
11141 #endif
11142 #ifdef FEAT_XIM
11143 "xim",
11144 #endif
11145 #ifdef FEAT_XFONTSET
11146 "xfontset",
11147 #endif
11148 #ifdef USE_XSMP
11149 "xsmp",
11150 #endif
11151 #ifdef USE_XSMP_INTERACT
11152 "xsmp_interact",
11153 #endif
11154 #ifdef FEAT_XCLIPBOARD
11155 "xterm_clipboard",
11156 #endif
11157 #ifdef FEAT_XTERM_SAVE
11158 "xterm_save",
11159 #endif
11160 #if defined(UNIX) && defined(FEAT_X11)
11161 "X11",
11162 #endif
11163 NULL
11166 name = get_tv_string(&argvars[0]);
11167 for (i = 0; has_list[i] != NULL; ++i)
11168 if (STRICMP(name, has_list[i]) == 0)
11170 n = TRUE;
11171 break;
11174 if (n == FALSE)
11176 if (STRNICMP(name, "patch", 5) == 0)
11177 n = has_patch(atoi((char *)name + 5));
11178 else if (STRICMP(name, "vim_starting") == 0)
11179 n = (starting != 0);
11180 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
11181 else if (STRICMP(name, "balloon_multiline") == 0)
11182 n = multiline_balloon_available();
11183 #endif
11184 #ifdef DYNAMIC_TCL
11185 else if (STRICMP(name, "tcl") == 0)
11186 n = tcl_enabled(FALSE);
11187 #endif
11188 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
11189 else if (STRICMP(name, "iconv") == 0)
11190 n = iconv_enabled(FALSE);
11191 #endif
11192 #ifdef DYNAMIC_MZSCHEME
11193 else if (STRICMP(name, "mzscheme") == 0)
11194 n = mzscheme_enabled(FALSE);
11195 #endif
11196 #ifdef DYNAMIC_RUBY
11197 else if (STRICMP(name, "ruby") == 0)
11198 n = ruby_enabled(FALSE);
11199 #endif
11200 #ifdef DYNAMIC_PYTHON
11201 else if (STRICMP(name, "python") == 0)
11202 n = python_enabled(FALSE);
11203 #endif
11204 #ifdef DYNAMIC_PERL
11205 else if (STRICMP(name, "perl") == 0)
11206 n = perl_enabled(FALSE);
11207 #endif
11208 #ifdef FEAT_GUI
11209 else if (STRICMP(name, "gui_running") == 0)
11210 n = (gui.in_use || gui.starting);
11211 # ifdef FEAT_GUI_W32
11212 else if (STRICMP(name, "gui_win32s") == 0)
11213 n = gui_is_win32s();
11214 # endif
11215 # ifdef FEAT_BROWSE
11216 else if (STRICMP(name, "browse") == 0)
11217 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
11218 # endif
11219 #endif
11220 #ifdef FEAT_SYN_HL
11221 else if (STRICMP(name, "syntax_items") == 0)
11222 n = syntax_present(curbuf);
11223 #endif
11224 #if defined(WIN3264)
11225 else if (STRICMP(name, "win95") == 0)
11226 n = mch_windows95();
11227 #endif
11228 #ifdef FEAT_NETBEANS_INTG
11229 else if (STRICMP(name, "netbeans_enabled") == 0)
11230 n = usingNetbeans;
11231 #endif
11234 rettv->vval.v_number = n;
11238 * "has_key()" function
11240 static void
11241 f_has_key(argvars, rettv)
11242 typval_T *argvars;
11243 typval_T *rettv;
11245 rettv->vval.v_number = 0;
11246 if (argvars[0].v_type != VAR_DICT)
11248 EMSG(_(e_dictreq));
11249 return;
11251 if (argvars[0].vval.v_dict == NULL)
11252 return;
11254 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
11255 get_tv_string(&argvars[1]), -1) != NULL;
11259 * "haslocaldir()" function
11261 /*ARGSUSED*/
11262 static void
11263 f_haslocaldir(argvars, rettv)
11264 typval_T *argvars;
11265 typval_T *rettv;
11267 rettv->vval.v_number = (curwin->w_localdir != NULL);
11271 * "hasmapto()" function
11273 static void
11274 f_hasmapto(argvars, rettv)
11275 typval_T *argvars;
11276 typval_T *rettv;
11278 char_u *name;
11279 char_u *mode;
11280 char_u buf[NUMBUFLEN];
11281 int abbr = FALSE;
11283 name = get_tv_string(&argvars[0]);
11284 if (argvars[1].v_type == VAR_UNKNOWN)
11285 mode = (char_u *)"nvo";
11286 else
11288 mode = get_tv_string_buf(&argvars[1], buf);
11289 if (argvars[2].v_type != VAR_UNKNOWN)
11290 abbr = get_tv_number(&argvars[2]);
11293 if (map_to_exists(name, mode, abbr))
11294 rettv->vval.v_number = TRUE;
11295 else
11296 rettv->vval.v_number = FALSE;
11300 * "histadd()" function
11302 /*ARGSUSED*/
11303 static void
11304 f_histadd(argvars, rettv)
11305 typval_T *argvars;
11306 typval_T *rettv;
11308 #ifdef FEAT_CMDHIST
11309 int histype;
11310 char_u *str;
11311 char_u buf[NUMBUFLEN];
11312 #endif
11314 rettv->vval.v_number = FALSE;
11315 if (check_restricted() || check_secure())
11316 return;
11317 #ifdef FEAT_CMDHIST
11318 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11319 histype = str != NULL ? get_histtype(str) : -1;
11320 if (histype >= 0)
11322 str = get_tv_string_buf(&argvars[1], buf);
11323 if (*str != NUL)
11325 add_to_history(histype, str, FALSE, NUL);
11326 rettv->vval.v_number = TRUE;
11327 return;
11330 #endif
11334 * "histdel()" function
11336 /*ARGSUSED*/
11337 static void
11338 f_histdel(argvars, rettv)
11339 typval_T *argvars;
11340 typval_T *rettv;
11342 #ifdef FEAT_CMDHIST
11343 int n;
11344 char_u buf[NUMBUFLEN];
11345 char_u *str;
11347 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11348 if (str == NULL)
11349 n = 0;
11350 else if (argvars[1].v_type == VAR_UNKNOWN)
11351 /* only one argument: clear entire history */
11352 n = clr_history(get_histtype(str));
11353 else if (argvars[1].v_type == VAR_NUMBER)
11354 /* index given: remove that entry */
11355 n = del_history_idx(get_histtype(str),
11356 (int)get_tv_number(&argvars[1]));
11357 else
11358 /* string given: remove all matching entries */
11359 n = del_history_entry(get_histtype(str),
11360 get_tv_string_buf(&argvars[1], buf));
11361 rettv->vval.v_number = n;
11362 #else
11363 rettv->vval.v_number = 0;
11364 #endif
11368 * "histget()" function
11370 /*ARGSUSED*/
11371 static void
11372 f_histget(argvars, rettv)
11373 typval_T *argvars;
11374 typval_T *rettv;
11376 #ifdef FEAT_CMDHIST
11377 int type;
11378 int idx;
11379 char_u *str;
11381 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11382 if (str == NULL)
11383 rettv->vval.v_string = NULL;
11384 else
11386 type = get_histtype(str);
11387 if (argvars[1].v_type == VAR_UNKNOWN)
11388 idx = get_history_idx(type);
11389 else
11390 idx = (int)get_tv_number_chk(&argvars[1], NULL);
11391 /* -1 on type error */
11392 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
11394 #else
11395 rettv->vval.v_string = NULL;
11396 #endif
11397 rettv->v_type = VAR_STRING;
11401 * "histnr()" function
11403 /*ARGSUSED*/
11404 static void
11405 f_histnr(argvars, rettv)
11406 typval_T *argvars;
11407 typval_T *rettv;
11409 int i;
11411 #ifdef FEAT_CMDHIST
11412 char_u *history = get_tv_string_chk(&argvars[0]);
11414 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
11415 if (i >= HIST_CMD && i < HIST_COUNT)
11416 i = get_history_idx(i);
11417 else
11418 #endif
11419 i = -1;
11420 rettv->vval.v_number = i;
11424 * "highlightID(name)" function
11426 static void
11427 f_hlID(argvars, rettv)
11428 typval_T *argvars;
11429 typval_T *rettv;
11431 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
11435 * "highlight_exists()" function
11437 static void
11438 f_hlexists(argvars, rettv)
11439 typval_T *argvars;
11440 typval_T *rettv;
11442 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
11446 * "hostname()" function
11448 /*ARGSUSED*/
11449 static void
11450 f_hostname(argvars, rettv)
11451 typval_T *argvars;
11452 typval_T *rettv;
11454 char_u hostname[256];
11456 mch_get_host_name(hostname, 256);
11457 rettv->v_type = VAR_STRING;
11458 rettv->vval.v_string = vim_strsave(hostname);
11462 * iconv() function
11464 /*ARGSUSED*/
11465 static void
11466 f_iconv(argvars, rettv)
11467 typval_T *argvars;
11468 typval_T *rettv;
11470 #ifdef FEAT_MBYTE
11471 char_u buf1[NUMBUFLEN];
11472 char_u buf2[NUMBUFLEN];
11473 char_u *from, *to, *str;
11474 vimconv_T vimconv;
11475 #endif
11477 rettv->v_type = VAR_STRING;
11478 rettv->vval.v_string = NULL;
11480 #ifdef FEAT_MBYTE
11481 str = get_tv_string(&argvars[0]);
11482 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
11483 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
11484 vimconv.vc_type = CONV_NONE;
11485 convert_setup(&vimconv, from, to);
11487 /* If the encodings are equal, no conversion needed. */
11488 if (vimconv.vc_type == CONV_NONE)
11489 rettv->vval.v_string = vim_strsave(str);
11490 else
11491 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
11493 convert_setup(&vimconv, NULL, NULL);
11494 vim_free(from);
11495 vim_free(to);
11496 #endif
11500 * "indent()" function
11502 static void
11503 f_indent(argvars, rettv)
11504 typval_T *argvars;
11505 typval_T *rettv;
11507 linenr_T lnum;
11509 lnum = get_tv_lnum(argvars);
11510 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
11511 rettv->vval.v_number = get_indent_lnum(lnum);
11512 else
11513 rettv->vval.v_number = -1;
11517 * "index()" function
11519 static void
11520 f_index(argvars, rettv)
11521 typval_T *argvars;
11522 typval_T *rettv;
11524 list_T *l;
11525 listitem_T *item;
11526 long idx = 0;
11527 int ic = FALSE;
11529 rettv->vval.v_number = -1;
11530 if (argvars[0].v_type != VAR_LIST)
11532 EMSG(_(e_listreq));
11533 return;
11535 l = argvars[0].vval.v_list;
11536 if (l != NULL)
11538 item = l->lv_first;
11539 if (argvars[2].v_type != VAR_UNKNOWN)
11541 int error = FALSE;
11543 /* Start at specified item. Use the cached index that list_find()
11544 * sets, so that a negative number also works. */
11545 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
11546 idx = l->lv_idx;
11547 if (argvars[3].v_type != VAR_UNKNOWN)
11548 ic = get_tv_number_chk(&argvars[3], &error);
11549 if (error)
11550 item = NULL;
11553 for ( ; item != NULL; item = item->li_next, ++idx)
11554 if (tv_equal(&item->li_tv, &argvars[1], ic))
11556 rettv->vval.v_number = idx;
11557 break;
11562 static int inputsecret_flag = 0;
11564 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
11567 * This function is used by f_input() and f_inputdialog() functions. The third
11568 * argument to f_input() specifies the type of completion to use at the
11569 * prompt. The third argument to f_inputdialog() specifies the value to return
11570 * when the user cancels the prompt.
11572 static void
11573 get_user_input(argvars, rettv, inputdialog)
11574 typval_T *argvars;
11575 typval_T *rettv;
11576 int inputdialog;
11578 char_u *prompt = get_tv_string_chk(&argvars[0]);
11579 char_u *p = NULL;
11580 int c;
11581 char_u buf[NUMBUFLEN];
11582 int cmd_silent_save = cmd_silent;
11583 char_u *defstr = (char_u *)"";
11584 int xp_type = EXPAND_NOTHING;
11585 char_u *xp_arg = NULL;
11587 rettv->v_type = VAR_STRING;
11588 rettv->vval.v_string = NULL;
11590 #ifdef NO_CONSOLE_INPUT
11591 /* While starting up, there is no place to enter text. */
11592 if (no_console_input())
11593 return;
11594 #endif
11596 cmd_silent = FALSE; /* Want to see the prompt. */
11597 if (prompt != NULL)
11599 /* Only the part of the message after the last NL is considered as
11600 * prompt for the command line */
11601 p = vim_strrchr(prompt, '\n');
11602 if (p == NULL)
11603 p = prompt;
11604 else
11606 ++p;
11607 c = *p;
11608 *p = NUL;
11609 msg_start();
11610 msg_clr_eos();
11611 msg_puts_attr(prompt, echo_attr);
11612 msg_didout = FALSE;
11613 msg_starthere();
11614 *p = c;
11616 cmdline_row = msg_row;
11618 if (argvars[1].v_type != VAR_UNKNOWN)
11620 defstr = get_tv_string_buf_chk(&argvars[1], buf);
11621 if (defstr != NULL)
11622 stuffReadbuffSpec(defstr);
11624 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
11626 char_u *xp_name;
11627 int xp_namelen;
11628 long argt;
11630 rettv->vval.v_string = NULL;
11632 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
11633 if (xp_name == NULL)
11634 return;
11636 xp_namelen = (int)STRLEN(xp_name);
11638 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
11639 &xp_arg) == FAIL)
11640 return;
11644 if (defstr != NULL)
11645 rettv->vval.v_string =
11646 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
11647 xp_type, xp_arg);
11649 vim_free(xp_arg);
11651 /* since the user typed this, no need to wait for return */
11652 need_wait_return = FALSE;
11653 msg_didout = FALSE;
11655 cmd_silent = cmd_silent_save;
11659 * "input()" function
11660 * Also handles inputsecret() when inputsecret is set.
11662 static void
11663 f_input(argvars, rettv)
11664 typval_T *argvars;
11665 typval_T *rettv;
11667 get_user_input(argvars, rettv, FALSE);
11671 * "inputdialog()" function
11673 static void
11674 f_inputdialog(argvars, rettv)
11675 typval_T *argvars;
11676 typval_T *rettv;
11678 #if defined(FEAT_GUI_TEXTDIALOG)
11679 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
11680 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
11682 char_u *message;
11683 char_u buf[NUMBUFLEN];
11684 char_u *defstr = (char_u *)"";
11686 message = get_tv_string_chk(&argvars[0]);
11687 if (argvars[1].v_type != VAR_UNKNOWN
11688 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
11689 vim_strncpy(IObuff, defstr, IOSIZE - 1);
11690 else
11691 IObuff[0] = NUL;
11692 if (message != NULL && defstr != NULL
11693 && do_dialog(VIM_QUESTION, NULL, message,
11694 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
11695 rettv->vval.v_string = vim_strsave(IObuff);
11696 else
11698 if (message != NULL && defstr != NULL
11699 && argvars[1].v_type != VAR_UNKNOWN
11700 && argvars[2].v_type != VAR_UNKNOWN)
11701 rettv->vval.v_string = vim_strsave(
11702 get_tv_string_buf(&argvars[2], buf));
11703 else
11704 rettv->vval.v_string = NULL;
11706 rettv->v_type = VAR_STRING;
11708 else
11709 #endif
11710 get_user_input(argvars, rettv, TRUE);
11714 * "inputlist()" function
11716 static void
11717 f_inputlist(argvars, rettv)
11718 typval_T *argvars;
11719 typval_T *rettv;
11721 listitem_T *li;
11722 int selected;
11723 int mouse_used;
11725 rettv->vval.v_number = 0;
11726 #ifdef NO_CONSOLE_INPUT
11727 /* While starting up, there is no place to enter text. */
11728 if (no_console_input())
11729 return;
11730 #endif
11731 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
11733 EMSG2(_(e_listarg), "inputlist()");
11734 return;
11737 msg_start();
11738 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
11739 lines_left = Rows; /* avoid more prompt */
11740 msg_scroll = TRUE;
11741 msg_clr_eos();
11743 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
11745 msg_puts(get_tv_string(&li->li_tv));
11746 msg_putchar('\n');
11749 /* Ask for choice. */
11750 selected = prompt_for_number(&mouse_used);
11751 if (mouse_used)
11752 selected -= lines_left;
11754 rettv->vval.v_number = selected;
11758 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
11761 * "inputrestore()" function
11763 /*ARGSUSED*/
11764 static void
11765 f_inputrestore(argvars, rettv)
11766 typval_T *argvars;
11767 typval_T *rettv;
11769 if (ga_userinput.ga_len > 0)
11771 --ga_userinput.ga_len;
11772 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
11773 + ga_userinput.ga_len);
11774 rettv->vval.v_number = 0; /* OK */
11776 else if (p_verbose > 1)
11778 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
11779 rettv->vval.v_number = 1; /* Failed */
11784 * "inputsave()" function
11786 /*ARGSUSED*/
11787 static void
11788 f_inputsave(argvars, rettv)
11789 typval_T *argvars;
11790 typval_T *rettv;
11792 /* Add an entry to the stack of typehead storage. */
11793 if (ga_grow(&ga_userinput, 1) == OK)
11795 save_typeahead((tasave_T *)(ga_userinput.ga_data)
11796 + ga_userinput.ga_len);
11797 ++ga_userinput.ga_len;
11798 rettv->vval.v_number = 0; /* OK */
11800 else
11801 rettv->vval.v_number = 1; /* Failed */
11805 * "inputsecret()" function
11807 static void
11808 f_inputsecret(argvars, rettv)
11809 typval_T *argvars;
11810 typval_T *rettv;
11812 ++cmdline_star;
11813 ++inputsecret_flag;
11814 f_input(argvars, rettv);
11815 --cmdline_star;
11816 --inputsecret_flag;
11820 * "insert()" function
11822 static void
11823 f_insert(argvars, rettv)
11824 typval_T *argvars;
11825 typval_T *rettv;
11827 long before = 0;
11828 listitem_T *item;
11829 list_T *l;
11830 int error = FALSE;
11832 rettv->vval.v_number = 0;
11833 if (argvars[0].v_type != VAR_LIST)
11834 EMSG2(_(e_listarg), "insert()");
11835 else if ((l = argvars[0].vval.v_list) != NULL
11836 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
11838 if (argvars[2].v_type != VAR_UNKNOWN)
11839 before = get_tv_number_chk(&argvars[2], &error);
11840 if (error)
11841 return; /* type error; errmsg already given */
11843 if (before == l->lv_len)
11844 item = NULL;
11845 else
11847 item = list_find(l, before);
11848 if (item == NULL)
11850 EMSGN(_(e_listidx), before);
11851 l = NULL;
11854 if (l != NULL)
11856 list_insert_tv(l, &argvars[1], item);
11857 copy_tv(&argvars[0], rettv);
11863 * "isdirectory()" function
11865 static void
11866 f_isdirectory(argvars, rettv)
11867 typval_T *argvars;
11868 typval_T *rettv;
11870 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
11874 * "islocked()" function
11876 static void
11877 f_islocked(argvars, rettv)
11878 typval_T *argvars;
11879 typval_T *rettv;
11881 lval_T lv;
11882 char_u *end;
11883 dictitem_T *di;
11885 rettv->vval.v_number = -1;
11886 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
11887 FNE_CHECK_START);
11888 if (end != NULL && lv.ll_name != NULL)
11890 if (*end != NUL)
11891 EMSG(_(e_trailing));
11892 else
11894 if (lv.ll_tv == NULL)
11896 if (check_changedtick(lv.ll_name))
11897 rettv->vval.v_number = 1; /* always locked */
11898 else
11900 di = find_var(lv.ll_name, NULL);
11901 if (di != NULL)
11903 /* Consider a variable locked when:
11904 * 1. the variable itself is locked
11905 * 2. the value of the variable is locked.
11906 * 3. the List or Dict value is locked.
11908 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
11909 || tv_islocked(&di->di_tv));
11913 else if (lv.ll_range)
11914 EMSG(_("E786: Range not allowed"));
11915 else if (lv.ll_newkey != NULL)
11916 EMSG2(_(e_dictkey), lv.ll_newkey);
11917 else if (lv.ll_list != NULL)
11918 /* List item. */
11919 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
11920 else
11921 /* Dictionary item. */
11922 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
11926 clear_lval(&lv);
11929 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
11932 * Turn a dict into a list:
11933 * "what" == 0: list of keys
11934 * "what" == 1: list of values
11935 * "what" == 2: list of items
11937 static void
11938 dict_list(argvars, rettv, what)
11939 typval_T *argvars;
11940 typval_T *rettv;
11941 int what;
11943 list_T *l2;
11944 dictitem_T *di;
11945 hashitem_T *hi;
11946 listitem_T *li;
11947 listitem_T *li2;
11948 dict_T *d;
11949 int todo;
11951 rettv->vval.v_number = 0;
11952 if (argvars[0].v_type != VAR_DICT)
11954 EMSG(_(e_dictreq));
11955 return;
11957 if ((d = argvars[0].vval.v_dict) == NULL)
11958 return;
11960 if (rettv_list_alloc(rettv) == FAIL)
11961 return;
11963 todo = (int)d->dv_hashtab.ht_used;
11964 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
11966 if (!HASHITEM_EMPTY(hi))
11968 --todo;
11969 di = HI2DI(hi);
11971 li = listitem_alloc();
11972 if (li == NULL)
11973 break;
11974 list_append(rettv->vval.v_list, li);
11976 if (what == 0)
11978 /* keys() */
11979 li->li_tv.v_type = VAR_STRING;
11980 li->li_tv.v_lock = 0;
11981 li->li_tv.vval.v_string = vim_strsave(di->di_key);
11983 else if (what == 1)
11985 /* values() */
11986 copy_tv(&di->di_tv, &li->li_tv);
11988 else
11990 /* items() */
11991 l2 = list_alloc();
11992 li->li_tv.v_type = VAR_LIST;
11993 li->li_tv.v_lock = 0;
11994 li->li_tv.vval.v_list = l2;
11995 if (l2 == NULL)
11996 break;
11997 ++l2->lv_refcount;
11999 li2 = listitem_alloc();
12000 if (li2 == NULL)
12001 break;
12002 list_append(l2, li2);
12003 li2->li_tv.v_type = VAR_STRING;
12004 li2->li_tv.v_lock = 0;
12005 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12007 li2 = listitem_alloc();
12008 if (li2 == NULL)
12009 break;
12010 list_append(l2, li2);
12011 copy_tv(&di->di_tv, &li2->li_tv);
12018 * "items(dict)" function
12020 static void
12021 f_items(argvars, rettv)
12022 typval_T *argvars;
12023 typval_T *rettv;
12025 dict_list(argvars, rettv, 2);
12029 * "join()" function
12031 static void
12032 f_join(argvars, rettv)
12033 typval_T *argvars;
12034 typval_T *rettv;
12036 garray_T ga;
12037 char_u *sep;
12039 rettv->vval.v_number = 0;
12040 if (argvars[0].v_type != VAR_LIST)
12042 EMSG(_(e_listreq));
12043 return;
12045 if (argvars[0].vval.v_list == NULL)
12046 return;
12047 if (argvars[1].v_type == VAR_UNKNOWN)
12048 sep = (char_u *)" ";
12049 else
12050 sep = get_tv_string_chk(&argvars[1]);
12052 rettv->v_type = VAR_STRING;
12054 if (sep != NULL)
12056 ga_init2(&ga, (int)sizeof(char), 80);
12057 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12058 ga_append(&ga, NUL);
12059 rettv->vval.v_string = (char_u *)ga.ga_data;
12061 else
12062 rettv->vval.v_string = NULL;
12066 * "keys()" function
12068 static void
12069 f_keys(argvars, rettv)
12070 typval_T *argvars;
12071 typval_T *rettv;
12073 dict_list(argvars, rettv, 0);
12077 * "last_buffer_nr()" function.
12079 /*ARGSUSED*/
12080 static void
12081 f_last_buffer_nr(argvars, rettv)
12082 typval_T *argvars;
12083 typval_T *rettv;
12085 int n = 0;
12086 buf_T *buf;
12088 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12089 if (n < buf->b_fnum)
12090 n = buf->b_fnum;
12092 rettv->vval.v_number = n;
12096 * "len()" function
12098 static void
12099 f_len(argvars, rettv)
12100 typval_T *argvars;
12101 typval_T *rettv;
12103 switch (argvars[0].v_type)
12105 case VAR_STRING:
12106 case VAR_NUMBER:
12107 rettv->vval.v_number = (varnumber_T)STRLEN(
12108 get_tv_string(&argvars[0]));
12109 break;
12110 case VAR_LIST:
12111 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
12112 break;
12113 case VAR_DICT:
12114 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
12115 break;
12116 default:
12117 EMSG(_("E701: Invalid type for len()"));
12118 break;
12122 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
12124 static void
12125 libcall_common(argvars, rettv, type)
12126 typval_T *argvars;
12127 typval_T *rettv;
12128 int type;
12130 #ifdef FEAT_LIBCALL
12131 char_u *string_in;
12132 char_u **string_result;
12133 int nr_result;
12134 #endif
12136 rettv->v_type = type;
12137 if (type == VAR_NUMBER)
12138 rettv->vval.v_number = 0;
12139 else
12140 rettv->vval.v_string = NULL;
12142 if (check_restricted() || check_secure())
12143 return;
12145 #ifdef FEAT_LIBCALL
12146 /* The first two args must be strings, otherwise its meaningless */
12147 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
12149 string_in = NULL;
12150 if (argvars[2].v_type == VAR_STRING)
12151 string_in = argvars[2].vval.v_string;
12152 if (type == VAR_NUMBER)
12153 string_result = NULL;
12154 else
12155 string_result = &rettv->vval.v_string;
12156 if (mch_libcall(argvars[0].vval.v_string,
12157 argvars[1].vval.v_string,
12158 string_in,
12159 argvars[2].vval.v_number,
12160 string_result,
12161 &nr_result) == OK
12162 && type == VAR_NUMBER)
12163 rettv->vval.v_number = nr_result;
12165 #endif
12169 * "libcall()" function
12171 static void
12172 f_libcall(argvars, rettv)
12173 typval_T *argvars;
12174 typval_T *rettv;
12176 libcall_common(argvars, rettv, VAR_STRING);
12180 * "libcallnr()" function
12182 static void
12183 f_libcallnr(argvars, rettv)
12184 typval_T *argvars;
12185 typval_T *rettv;
12187 libcall_common(argvars, rettv, VAR_NUMBER);
12191 * "line(string)" function
12193 static void
12194 f_line(argvars, rettv)
12195 typval_T *argvars;
12196 typval_T *rettv;
12198 linenr_T lnum = 0;
12199 pos_T *fp;
12200 int fnum;
12202 fp = var2fpos(&argvars[0], TRUE, &fnum);
12203 if (fp != NULL)
12204 lnum = fp->lnum;
12205 rettv->vval.v_number = lnum;
12209 * "line2byte(lnum)" function
12211 /*ARGSUSED*/
12212 static void
12213 f_line2byte(argvars, rettv)
12214 typval_T *argvars;
12215 typval_T *rettv;
12217 #ifndef FEAT_BYTEOFF
12218 rettv->vval.v_number = -1;
12219 #else
12220 linenr_T lnum;
12222 lnum = get_tv_lnum(argvars);
12223 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
12224 rettv->vval.v_number = -1;
12225 else
12226 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
12227 if (rettv->vval.v_number >= 0)
12228 ++rettv->vval.v_number;
12229 #endif
12233 * "lispindent(lnum)" function
12235 static void
12236 f_lispindent(argvars, rettv)
12237 typval_T *argvars;
12238 typval_T *rettv;
12240 #ifdef FEAT_LISP
12241 pos_T pos;
12242 linenr_T lnum;
12244 pos = curwin->w_cursor;
12245 lnum = get_tv_lnum(argvars);
12246 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12248 curwin->w_cursor.lnum = lnum;
12249 rettv->vval.v_number = get_lisp_indent();
12250 curwin->w_cursor = pos;
12252 else
12253 #endif
12254 rettv->vval.v_number = -1;
12258 * "localtime()" function
12260 /*ARGSUSED*/
12261 static void
12262 f_localtime(argvars, rettv)
12263 typval_T *argvars;
12264 typval_T *rettv;
12266 rettv->vval.v_number = (varnumber_T)time(NULL);
12269 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
12271 static void
12272 get_maparg(argvars, rettv, exact)
12273 typval_T *argvars;
12274 typval_T *rettv;
12275 int exact;
12277 char_u *keys;
12278 char_u *which;
12279 char_u buf[NUMBUFLEN];
12280 char_u *keys_buf = NULL;
12281 char_u *rhs;
12282 int mode;
12283 garray_T ga;
12284 int abbr = FALSE;
12286 /* return empty string for failure */
12287 rettv->v_type = VAR_STRING;
12288 rettv->vval.v_string = NULL;
12290 keys = get_tv_string(&argvars[0]);
12291 if (*keys == NUL)
12292 return;
12294 if (argvars[1].v_type != VAR_UNKNOWN)
12296 which = get_tv_string_buf_chk(&argvars[1], buf);
12297 if (argvars[2].v_type != VAR_UNKNOWN)
12298 abbr = get_tv_number(&argvars[2]);
12300 else
12301 which = (char_u *)"";
12302 if (which == NULL)
12303 return;
12305 mode = get_map_mode(&which, 0);
12307 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
12308 rhs = check_map(keys, mode, exact, FALSE, abbr);
12309 vim_free(keys_buf);
12310 if (rhs != NULL)
12312 ga_init(&ga);
12313 ga.ga_itemsize = 1;
12314 ga.ga_growsize = 40;
12316 while (*rhs != NUL)
12317 ga_concat(&ga, str2special(&rhs, FALSE));
12319 ga_append(&ga, NUL);
12320 rettv->vval.v_string = (char_u *)ga.ga_data;
12325 * "map()" function
12327 static void
12328 f_map(argvars, rettv)
12329 typval_T *argvars;
12330 typval_T *rettv;
12332 filter_map(argvars, rettv, TRUE);
12336 * "maparg()" function
12338 static void
12339 f_maparg(argvars, rettv)
12340 typval_T *argvars;
12341 typval_T *rettv;
12343 get_maparg(argvars, rettv, TRUE);
12347 * "mapcheck()" function
12349 static void
12350 f_mapcheck(argvars, rettv)
12351 typval_T *argvars;
12352 typval_T *rettv;
12354 get_maparg(argvars, rettv, FALSE);
12357 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
12359 static void
12360 find_some_match(argvars, rettv, type)
12361 typval_T *argvars;
12362 typval_T *rettv;
12363 int type;
12365 char_u *str = NULL;
12366 char_u *expr = NULL;
12367 char_u *pat;
12368 regmatch_T regmatch;
12369 char_u patbuf[NUMBUFLEN];
12370 char_u strbuf[NUMBUFLEN];
12371 char_u *save_cpo;
12372 long start = 0;
12373 long nth = 1;
12374 colnr_T startcol = 0;
12375 int match = 0;
12376 list_T *l = NULL;
12377 listitem_T *li = NULL;
12378 long idx = 0;
12379 char_u *tofree = NULL;
12381 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
12382 save_cpo = p_cpo;
12383 p_cpo = (char_u *)"";
12385 rettv->vval.v_number = -1;
12386 if (type == 3)
12388 /* return empty list when there are no matches */
12389 if (rettv_list_alloc(rettv) == FAIL)
12390 goto theend;
12392 else if (type == 2)
12394 rettv->v_type = VAR_STRING;
12395 rettv->vval.v_string = NULL;
12398 if (argvars[0].v_type == VAR_LIST)
12400 if ((l = argvars[0].vval.v_list) == NULL)
12401 goto theend;
12402 li = l->lv_first;
12404 else
12405 expr = str = get_tv_string(&argvars[0]);
12407 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
12408 if (pat == NULL)
12409 goto theend;
12411 if (argvars[2].v_type != VAR_UNKNOWN)
12413 int error = FALSE;
12415 start = get_tv_number_chk(&argvars[2], &error);
12416 if (error)
12417 goto theend;
12418 if (l != NULL)
12420 li = list_find(l, start);
12421 if (li == NULL)
12422 goto theend;
12423 idx = l->lv_idx; /* use the cached index */
12425 else
12427 if (start < 0)
12428 start = 0;
12429 if (start > (long)STRLEN(str))
12430 goto theend;
12431 /* When "count" argument is there ignore matches before "start",
12432 * otherwise skip part of the string. Differs when pattern is "^"
12433 * or "\<". */
12434 if (argvars[3].v_type != VAR_UNKNOWN)
12435 startcol = start;
12436 else
12437 str += start;
12440 if (argvars[3].v_type != VAR_UNKNOWN)
12441 nth = get_tv_number_chk(&argvars[3], &error);
12442 if (error)
12443 goto theend;
12446 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
12447 if (regmatch.regprog != NULL)
12449 regmatch.rm_ic = p_ic;
12451 for (;;)
12453 if (l != NULL)
12455 if (li == NULL)
12457 match = FALSE;
12458 break;
12460 vim_free(tofree);
12461 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
12462 if (str == NULL)
12463 break;
12466 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
12468 if (match && --nth <= 0)
12469 break;
12470 if (l == NULL && !match)
12471 break;
12473 /* Advance to just after the match. */
12474 if (l != NULL)
12476 li = li->li_next;
12477 ++idx;
12479 else
12481 #ifdef FEAT_MBYTE
12482 startcol = (colnr_T)(regmatch.startp[0]
12483 + (*mb_ptr2len)(regmatch.startp[0]) - str);
12484 #else
12485 startcol = regmatch.startp[0] + 1 - str;
12486 #endif
12490 if (match)
12492 if (type == 3)
12494 int i;
12496 /* return list with matched string and submatches */
12497 for (i = 0; i < NSUBEXP; ++i)
12499 if (regmatch.endp[i] == NULL)
12501 if (list_append_string(rettv->vval.v_list,
12502 (char_u *)"", 0) == FAIL)
12503 break;
12505 else if (list_append_string(rettv->vval.v_list,
12506 regmatch.startp[i],
12507 (int)(regmatch.endp[i] - regmatch.startp[i]))
12508 == FAIL)
12509 break;
12512 else if (type == 2)
12514 /* return matched string */
12515 if (l != NULL)
12516 copy_tv(&li->li_tv, rettv);
12517 else
12518 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
12519 (int)(regmatch.endp[0] - regmatch.startp[0]));
12521 else if (l != NULL)
12522 rettv->vval.v_number = idx;
12523 else
12525 if (type != 0)
12526 rettv->vval.v_number =
12527 (varnumber_T)(regmatch.startp[0] - str);
12528 else
12529 rettv->vval.v_number =
12530 (varnumber_T)(regmatch.endp[0] - str);
12531 rettv->vval.v_number += (varnumber_T)(str - expr);
12534 vim_free(regmatch.regprog);
12537 theend:
12538 vim_free(tofree);
12539 p_cpo = save_cpo;
12543 * "match()" function
12545 static void
12546 f_match(argvars, rettv)
12547 typval_T *argvars;
12548 typval_T *rettv;
12550 find_some_match(argvars, rettv, 1);
12554 * "matchadd()" function
12556 static void
12557 f_matchadd(argvars, rettv)
12558 typval_T *argvars;
12559 typval_T *rettv;
12561 #ifdef FEAT_SEARCH_EXTRA
12562 char_u buf[NUMBUFLEN];
12563 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
12564 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
12565 int prio = 10; /* default priority */
12566 int id = -1;
12567 int error = FALSE;
12569 rettv->vval.v_number = -1;
12571 if (grp == NULL || pat == NULL)
12572 return;
12573 if (argvars[2].v_type != VAR_UNKNOWN)
12575 prio = get_tv_number_chk(&argvars[2], &error);
12576 if (argvars[3].v_type != VAR_UNKNOWN)
12577 id = get_tv_number_chk(&argvars[3], &error);
12579 if (error == TRUE)
12580 return;
12581 if (id >= 1 && id <= 3)
12583 EMSGN("E798: ID is reserved for \":match\": %ld", id);
12584 return;
12587 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
12588 #endif
12592 * "matcharg()" function
12594 static void
12595 f_matcharg(argvars, rettv)
12596 typval_T *argvars;
12597 typval_T *rettv;
12599 if (rettv_list_alloc(rettv) == OK)
12601 #ifdef FEAT_SEARCH_EXTRA
12602 int id = get_tv_number(&argvars[0]);
12603 matchitem_T *m;
12605 if (id >= 1 && id <= 3)
12607 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
12609 list_append_string(rettv->vval.v_list,
12610 syn_id2name(m->hlg_id), -1);
12611 list_append_string(rettv->vval.v_list, m->pattern, -1);
12613 else
12615 list_append_string(rettv->vval.v_list, NUL, -1);
12616 list_append_string(rettv->vval.v_list, NUL, -1);
12619 #endif
12624 * "matchdelete()" function
12626 static void
12627 f_matchdelete(argvars, rettv)
12628 typval_T *argvars;
12629 typval_T *rettv;
12631 #ifdef FEAT_SEARCH_EXTRA
12632 rettv->vval.v_number = match_delete(curwin,
12633 (int)get_tv_number(&argvars[0]), TRUE);
12634 #endif
12638 * "matchend()" function
12640 static void
12641 f_matchend(argvars, rettv)
12642 typval_T *argvars;
12643 typval_T *rettv;
12645 find_some_match(argvars, rettv, 0);
12649 * "matchlist()" function
12651 static void
12652 f_matchlist(argvars, rettv)
12653 typval_T *argvars;
12654 typval_T *rettv;
12656 find_some_match(argvars, rettv, 3);
12660 * "matchstr()" function
12662 static void
12663 f_matchstr(argvars, rettv)
12664 typval_T *argvars;
12665 typval_T *rettv;
12667 find_some_match(argvars, rettv, 2);
12670 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
12672 static void
12673 max_min(argvars, rettv, domax)
12674 typval_T *argvars;
12675 typval_T *rettv;
12676 int domax;
12678 long n = 0;
12679 long i;
12680 int error = FALSE;
12682 if (argvars[0].v_type == VAR_LIST)
12684 list_T *l;
12685 listitem_T *li;
12687 l = argvars[0].vval.v_list;
12688 if (l != NULL)
12690 li = l->lv_first;
12691 if (li != NULL)
12693 n = get_tv_number_chk(&li->li_tv, &error);
12694 for (;;)
12696 li = li->li_next;
12697 if (li == NULL)
12698 break;
12699 i = get_tv_number_chk(&li->li_tv, &error);
12700 if (domax ? i > n : i < n)
12701 n = i;
12706 else if (argvars[0].v_type == VAR_DICT)
12708 dict_T *d;
12709 int first = TRUE;
12710 hashitem_T *hi;
12711 int todo;
12713 d = argvars[0].vval.v_dict;
12714 if (d != NULL)
12716 todo = (int)d->dv_hashtab.ht_used;
12717 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12719 if (!HASHITEM_EMPTY(hi))
12721 --todo;
12722 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
12723 if (first)
12725 n = i;
12726 first = FALSE;
12728 else if (domax ? i > n : i < n)
12729 n = i;
12734 else
12735 EMSG(_(e_listdictarg));
12736 rettv->vval.v_number = error ? 0 : n;
12740 * "max()" function
12742 static void
12743 f_max(argvars, rettv)
12744 typval_T *argvars;
12745 typval_T *rettv;
12747 max_min(argvars, rettv, TRUE);
12751 * "min()" function
12753 static void
12754 f_min(argvars, rettv)
12755 typval_T *argvars;
12756 typval_T *rettv;
12758 max_min(argvars, rettv, FALSE);
12761 static int mkdir_recurse __ARGS((char_u *dir, int prot));
12764 * Create the directory in which "dir" is located, and higher levels when
12765 * needed.
12767 static int
12768 mkdir_recurse(dir, prot)
12769 char_u *dir;
12770 int prot;
12772 char_u *p;
12773 char_u *updir;
12774 int r = FAIL;
12776 /* Get end of directory name in "dir".
12777 * We're done when it's "/" or "c:/". */
12778 p = gettail_sep(dir);
12779 if (p <= get_past_head(dir))
12780 return OK;
12782 /* If the directory exists we're done. Otherwise: create it.*/
12783 updir = vim_strnsave(dir, (int)(p - dir));
12784 if (updir == NULL)
12785 return FAIL;
12786 if (mch_isdir(updir))
12787 r = OK;
12788 else if (mkdir_recurse(updir, prot) == OK)
12789 r = vim_mkdir_emsg(updir, prot);
12790 vim_free(updir);
12791 return r;
12794 #ifdef vim_mkdir
12796 * "mkdir()" function
12798 static void
12799 f_mkdir(argvars, rettv)
12800 typval_T *argvars;
12801 typval_T *rettv;
12803 char_u *dir;
12804 char_u buf[NUMBUFLEN];
12805 int prot = 0755;
12807 rettv->vval.v_number = FAIL;
12808 if (check_restricted() || check_secure())
12809 return;
12811 dir = get_tv_string_buf(&argvars[0], buf);
12812 if (argvars[1].v_type != VAR_UNKNOWN)
12814 if (argvars[2].v_type != VAR_UNKNOWN)
12815 prot = get_tv_number_chk(&argvars[2], NULL);
12816 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
12817 mkdir_recurse(dir, prot);
12819 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
12821 #endif
12824 * "mode()" function
12826 /*ARGSUSED*/
12827 static void
12828 f_mode(argvars, rettv)
12829 typval_T *argvars;
12830 typval_T *rettv;
12832 char_u buf[2];
12834 #ifdef FEAT_VISUAL
12835 if (VIsual_active)
12837 if (VIsual_select)
12838 buf[0] = VIsual_mode + 's' - 'v';
12839 else
12840 buf[0] = VIsual_mode;
12842 else
12843 #endif
12844 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE)
12845 buf[0] = 'r';
12846 else if (State & INSERT)
12848 if (State & REPLACE_FLAG)
12849 buf[0] = 'R';
12850 else
12851 buf[0] = 'i';
12853 else if (State & CMDLINE)
12854 buf[0] = 'c';
12855 else
12856 buf[0] = 'n';
12858 buf[1] = NUL;
12859 rettv->vval.v_string = vim_strsave(buf);
12860 rettv->v_type = VAR_STRING;
12864 * "nextnonblank()" function
12866 static void
12867 f_nextnonblank(argvars, rettv)
12868 typval_T *argvars;
12869 typval_T *rettv;
12871 linenr_T lnum;
12873 for (lnum = get_tv_lnum(argvars); ; ++lnum)
12875 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
12877 lnum = 0;
12878 break;
12880 if (*skipwhite(ml_get(lnum)) != NUL)
12881 break;
12883 rettv->vval.v_number = lnum;
12887 * "nr2char()" function
12889 static void
12890 f_nr2char(argvars, rettv)
12891 typval_T *argvars;
12892 typval_T *rettv;
12894 char_u buf[NUMBUFLEN];
12896 #ifdef FEAT_MBYTE
12897 if (has_mbyte)
12898 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
12899 else
12900 #endif
12902 buf[0] = (char_u)get_tv_number(&argvars[0]);
12903 buf[1] = NUL;
12905 rettv->v_type = VAR_STRING;
12906 rettv->vval.v_string = vim_strsave(buf);
12910 * "pathshorten()" function
12912 static void
12913 f_pathshorten(argvars, rettv)
12914 typval_T *argvars;
12915 typval_T *rettv;
12917 char_u *p;
12919 rettv->v_type = VAR_STRING;
12920 p = get_tv_string_chk(&argvars[0]);
12921 if (p == NULL)
12922 rettv->vval.v_string = NULL;
12923 else
12925 p = vim_strsave(p);
12926 rettv->vval.v_string = p;
12927 if (p != NULL)
12928 shorten_dir(p);
12933 * "prevnonblank()" function
12935 static void
12936 f_prevnonblank(argvars, rettv)
12937 typval_T *argvars;
12938 typval_T *rettv;
12940 linenr_T lnum;
12942 lnum = get_tv_lnum(argvars);
12943 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
12944 lnum = 0;
12945 else
12946 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
12947 --lnum;
12948 rettv->vval.v_number = lnum;
12951 #ifdef HAVE_STDARG_H
12952 /* This dummy va_list is here because:
12953 * - passing a NULL pointer doesn't work when va_list isn't a pointer
12954 * - locally in the function results in a "used before set" warning
12955 * - using va_start() to initialize it gives "function with fixed args" error */
12956 static va_list ap;
12957 #endif
12960 * "printf()" function
12962 static void
12963 f_printf(argvars, rettv)
12964 typval_T *argvars;
12965 typval_T *rettv;
12967 rettv->v_type = VAR_STRING;
12968 rettv->vval.v_string = NULL;
12969 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
12971 char_u buf[NUMBUFLEN];
12972 int len;
12973 char_u *s;
12974 int saved_did_emsg = did_emsg;
12975 char *fmt;
12977 /* Get the required length, allocate the buffer and do it for real. */
12978 did_emsg = FALSE;
12979 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
12980 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
12981 if (!did_emsg)
12983 s = alloc(len + 1);
12984 if (s != NULL)
12986 rettv->vval.v_string = s;
12987 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
12990 did_emsg |= saved_did_emsg;
12992 #endif
12996 * "pumvisible()" function
12998 /*ARGSUSED*/
12999 static void
13000 f_pumvisible(argvars, rettv)
13001 typval_T *argvars;
13002 typval_T *rettv;
13004 rettv->vval.v_number = 0;
13005 #ifdef FEAT_INS_EXPAND
13006 if (pum_visible())
13007 rettv->vval.v_number = 1;
13008 #endif
13012 * "range()" function
13014 static void
13015 f_range(argvars, rettv)
13016 typval_T *argvars;
13017 typval_T *rettv;
13019 long start;
13020 long end;
13021 long stride = 1;
13022 long i;
13023 int error = FALSE;
13025 start = get_tv_number_chk(&argvars[0], &error);
13026 if (argvars[1].v_type == VAR_UNKNOWN)
13028 end = start - 1;
13029 start = 0;
13031 else
13033 end = get_tv_number_chk(&argvars[1], &error);
13034 if (argvars[2].v_type != VAR_UNKNOWN)
13035 stride = get_tv_number_chk(&argvars[2], &error);
13038 rettv->vval.v_number = 0;
13039 if (error)
13040 return; /* type error; errmsg already given */
13041 if (stride == 0)
13042 EMSG(_("E726: Stride is zero"));
13043 else if (stride > 0 ? end + 1 < start : end - 1 > start)
13044 EMSG(_("E727: Start past end"));
13045 else
13047 if (rettv_list_alloc(rettv) == OK)
13048 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
13049 if (list_append_number(rettv->vval.v_list,
13050 (varnumber_T)i) == FAIL)
13051 break;
13056 * "readfile()" function
13058 static void
13059 f_readfile(argvars, rettv)
13060 typval_T *argvars;
13061 typval_T *rettv;
13063 int binary = FALSE;
13064 char_u *fname;
13065 FILE *fd;
13066 listitem_T *li;
13067 #define FREAD_SIZE 200 /* optimized for text lines */
13068 char_u buf[FREAD_SIZE];
13069 int readlen; /* size of last fread() */
13070 int buflen; /* nr of valid chars in buf[] */
13071 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
13072 int tolist; /* first byte in buf[] still to be put in list */
13073 int chop; /* how many CR to chop off */
13074 char_u *prev = NULL; /* previously read bytes, if any */
13075 int prevlen = 0; /* length of "prev" if not NULL */
13076 char_u *s;
13077 int len;
13078 long maxline = MAXLNUM;
13079 long cnt = 0;
13081 if (argvars[1].v_type != VAR_UNKNOWN)
13083 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
13084 binary = TRUE;
13085 if (argvars[2].v_type != VAR_UNKNOWN)
13086 maxline = get_tv_number(&argvars[2]);
13089 if (rettv_list_alloc(rettv) == FAIL)
13090 return;
13092 /* Always open the file in binary mode, library functions have a mind of
13093 * their own about CR-LF conversion. */
13094 fname = get_tv_string(&argvars[0]);
13095 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
13097 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
13098 return;
13101 filtd = 0;
13102 while (cnt < maxline || maxline < 0)
13104 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
13105 buflen = filtd + readlen;
13106 tolist = 0;
13107 for ( ; filtd < buflen || readlen <= 0; ++filtd)
13109 if (buf[filtd] == '\n' || readlen <= 0)
13111 /* Only when in binary mode add an empty list item when the
13112 * last line ends in a '\n'. */
13113 if (!binary && readlen == 0 && filtd == 0)
13114 break;
13116 /* Found end-of-line or end-of-file: add a text line to the
13117 * list. */
13118 chop = 0;
13119 if (!binary)
13120 while (filtd - chop - 1 >= tolist
13121 && buf[filtd - chop - 1] == '\r')
13122 ++chop;
13123 len = filtd - tolist - chop;
13124 if (prev == NULL)
13125 s = vim_strnsave(buf + tolist, len);
13126 else
13128 s = alloc((unsigned)(prevlen + len + 1));
13129 if (s != NULL)
13131 mch_memmove(s, prev, prevlen);
13132 vim_free(prev);
13133 prev = NULL;
13134 mch_memmove(s + prevlen, buf + tolist, len);
13135 s[prevlen + len] = NUL;
13138 tolist = filtd + 1;
13140 li = listitem_alloc();
13141 if (li == NULL)
13143 vim_free(s);
13144 break;
13146 li->li_tv.v_type = VAR_STRING;
13147 li->li_tv.v_lock = 0;
13148 li->li_tv.vval.v_string = s;
13149 list_append(rettv->vval.v_list, li);
13151 if (++cnt >= maxline && maxline >= 0)
13152 break;
13153 if (readlen <= 0)
13154 break;
13156 else if (buf[filtd] == NUL)
13157 buf[filtd] = '\n';
13159 if (readlen <= 0)
13160 break;
13162 if (tolist == 0)
13164 /* "buf" is full, need to move text to an allocated buffer */
13165 if (prev == NULL)
13167 prev = vim_strnsave(buf, buflen);
13168 prevlen = buflen;
13170 else
13172 s = alloc((unsigned)(prevlen + buflen));
13173 if (s != NULL)
13175 mch_memmove(s, prev, prevlen);
13176 mch_memmove(s + prevlen, buf, buflen);
13177 vim_free(prev);
13178 prev = s;
13179 prevlen += buflen;
13182 filtd = 0;
13184 else
13186 mch_memmove(buf, buf + tolist, buflen - tolist);
13187 filtd -= tolist;
13192 * For a negative line count use only the lines at the end of the file,
13193 * free the rest.
13195 if (maxline < 0)
13196 while (cnt > -maxline)
13198 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
13199 --cnt;
13202 vim_free(prev);
13203 fclose(fd);
13206 #if defined(FEAT_RELTIME)
13207 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
13210 * Convert a List to proftime_T.
13211 * Return FAIL when there is something wrong.
13213 static int
13214 list2proftime(arg, tm)
13215 typval_T *arg;
13216 proftime_T *tm;
13218 long n1, n2;
13219 int error = FALSE;
13221 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
13222 || arg->vval.v_list->lv_len != 2)
13223 return FAIL;
13224 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
13225 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
13226 # ifdef WIN3264
13227 tm->HighPart = n1;
13228 tm->LowPart = n2;
13229 # else
13230 tm->tv_sec = n1;
13231 tm->tv_usec = n2;
13232 # endif
13233 return error ? FAIL : OK;
13235 #endif /* FEAT_RELTIME */
13238 * "reltime()" function
13240 static void
13241 f_reltime(argvars, rettv)
13242 typval_T *argvars;
13243 typval_T *rettv;
13245 #ifdef FEAT_RELTIME
13246 proftime_T res;
13247 proftime_T start;
13249 if (argvars[0].v_type == VAR_UNKNOWN)
13251 /* No arguments: get current time. */
13252 profile_start(&res);
13254 else if (argvars[1].v_type == VAR_UNKNOWN)
13256 if (list2proftime(&argvars[0], &res) == FAIL)
13257 return;
13258 profile_end(&res);
13260 else
13262 /* Two arguments: compute the difference. */
13263 if (list2proftime(&argvars[0], &start) == FAIL
13264 || list2proftime(&argvars[1], &res) == FAIL)
13265 return;
13266 profile_sub(&res, &start);
13269 if (rettv_list_alloc(rettv) == OK)
13271 long n1, n2;
13273 # ifdef WIN3264
13274 n1 = res.HighPart;
13275 n2 = res.LowPart;
13276 # else
13277 n1 = res.tv_sec;
13278 n2 = res.tv_usec;
13279 # endif
13280 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
13281 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
13283 #endif
13287 * "reltimestr()" function
13289 static void
13290 f_reltimestr(argvars, rettv)
13291 typval_T *argvars;
13292 typval_T *rettv;
13294 #ifdef FEAT_RELTIME
13295 proftime_T tm;
13296 #endif
13298 rettv->v_type = VAR_STRING;
13299 rettv->vval.v_string = NULL;
13300 #ifdef FEAT_RELTIME
13301 if (list2proftime(&argvars[0], &tm) == OK)
13302 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
13303 #endif
13306 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
13307 static void make_connection __ARGS((void));
13308 static int check_connection __ARGS((void));
13310 static void
13311 make_connection()
13313 if (X_DISPLAY == NULL
13314 # ifdef FEAT_GUI
13315 && !gui.in_use
13316 # endif
13319 x_force_connect = TRUE;
13320 setup_term_clip();
13321 x_force_connect = FALSE;
13325 static int
13326 check_connection()
13328 make_connection();
13329 if (X_DISPLAY == NULL)
13331 EMSG(_("E240: No connection to Vim server"));
13332 return FAIL;
13334 return OK;
13336 #endif
13338 #ifdef FEAT_CLIENTSERVER
13339 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
13341 static void
13342 remote_common(argvars, rettv, expr)
13343 typval_T *argvars;
13344 typval_T *rettv;
13345 int expr;
13347 char_u *server_name;
13348 char_u *keys;
13349 char_u *r = NULL;
13350 char_u buf[NUMBUFLEN];
13351 # ifdef WIN32
13352 HWND w;
13353 # elif defined(FEAT_X11)
13354 Window w;
13355 # elif defined(MAC_CLIENTSERVER)
13356 int w; // This is the port number ('w' is a bit confusing)
13357 # endif
13359 if (check_restricted() || check_secure())
13360 return;
13362 # ifdef FEAT_X11
13363 if (check_connection() == FAIL)
13364 return;
13365 # endif
13367 server_name = get_tv_string_chk(&argvars[0]);
13368 if (server_name == NULL)
13369 return; /* type error; errmsg already given */
13370 keys = get_tv_string_buf(&argvars[1], buf);
13371 # ifdef WIN32
13372 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
13373 # elif defined(FEAT_X11)
13374 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
13375 < 0)
13376 # elif defined(MAC_CLIENTSERVER)
13377 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
13378 # endif
13380 if (r != NULL)
13381 EMSG(r); /* sending worked but evaluation failed */
13382 else
13383 EMSG2(_("E241: Unable to send to %s"), server_name);
13384 return;
13387 rettv->vval.v_string = r;
13389 if (argvars[2].v_type != VAR_UNKNOWN)
13391 dictitem_T v;
13392 char_u str[30];
13393 char_u *idvar;
13395 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
13396 v.di_tv.v_type = VAR_STRING;
13397 v.di_tv.vval.v_string = vim_strsave(str);
13398 idvar = get_tv_string_chk(&argvars[2]);
13399 if (idvar != NULL)
13400 set_var(idvar, &v.di_tv, FALSE);
13401 vim_free(v.di_tv.vval.v_string);
13404 #endif
13407 * "remote_expr()" function
13409 /*ARGSUSED*/
13410 static void
13411 f_remote_expr(argvars, rettv)
13412 typval_T *argvars;
13413 typval_T *rettv;
13415 rettv->v_type = VAR_STRING;
13416 rettv->vval.v_string = NULL;
13417 #ifdef FEAT_CLIENTSERVER
13418 remote_common(argvars, rettv, TRUE);
13419 #endif
13423 * "remote_foreground()" function
13425 /*ARGSUSED*/
13426 static void
13427 f_remote_foreground(argvars, rettv)
13428 typval_T *argvars;
13429 typval_T *rettv;
13431 rettv->vval.v_number = 0;
13432 #ifdef FEAT_CLIENTSERVER
13433 # ifdef WIN32
13434 /* On Win32 it's done in this application. */
13436 char_u *server_name = get_tv_string_chk(&argvars[0]);
13438 if (server_name != NULL)
13439 serverForeground(server_name);
13441 # elif defined(FEAT_X11) || defined(MAC_CLIENTSERVER)
13442 /* Send a foreground() expression to the server. */
13443 argvars[1].v_type = VAR_STRING;
13444 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
13445 argvars[2].v_type = VAR_UNKNOWN;
13446 remote_common(argvars, rettv, TRUE);
13447 vim_free(argvars[1].vval.v_string);
13448 # endif
13449 #endif
13452 /*ARGSUSED*/
13453 static void
13454 f_remote_peek(argvars, rettv)
13455 typval_T *argvars;
13456 typval_T *rettv;
13458 #ifdef FEAT_CLIENTSERVER
13459 dictitem_T v;
13460 char_u *s = NULL;
13461 # ifdef WIN32
13462 long_u n = 0;
13463 # endif
13464 char_u *serverid;
13466 if (check_restricted() || check_secure())
13468 rettv->vval.v_number = -1;
13469 return;
13471 serverid = get_tv_string_chk(&argvars[0]);
13472 if (serverid == NULL)
13474 rettv->vval.v_number = -1;
13475 return; /* type error; errmsg already given */
13477 # ifdef WIN32
13478 sscanf(serverid, SCANF_HEX_LONG_U, &n);
13479 if (n == 0)
13480 rettv->vval.v_number = -1;
13481 else
13483 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
13484 rettv->vval.v_number = (s != NULL);
13486 # elif defined(FEAT_X11)
13487 rettv->vval.v_number = 0;
13488 if (check_connection() == FAIL)
13489 return;
13491 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
13492 serverStrToWin(serverid), &s);
13493 # elif defined(MAC_CLIENTSERVER)
13494 rettv->vval.v_number = serverPeekReply(serverStrToPort(serverid), &s);
13495 # endif
13497 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
13499 char_u *retvar;
13501 v.di_tv.v_type = VAR_STRING;
13502 v.di_tv.vval.v_string = vim_strsave(s);
13503 retvar = get_tv_string_chk(&argvars[1]);
13504 if (retvar != NULL)
13505 set_var(retvar, &v.di_tv, FALSE);
13506 vim_free(v.di_tv.vval.v_string);
13508 #else
13509 rettv->vval.v_number = -1;
13510 #endif
13513 /*ARGSUSED*/
13514 static void
13515 f_remote_read(argvars, rettv)
13516 typval_T *argvars;
13517 typval_T *rettv;
13519 char_u *r = NULL;
13521 #ifdef FEAT_CLIENTSERVER
13522 char_u *serverid = get_tv_string_chk(&argvars[0]);
13524 if (serverid != NULL && !check_restricted() && !check_secure())
13526 # ifdef WIN32
13527 /* The server's HWND is encoded in the 'id' parameter */
13528 long_u n = 0;
13530 sscanf(serverid, SCANF_HEX_LONG_U, &n);
13531 if (n != 0)
13532 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
13533 if (r == NULL)
13534 # elif defined(FEAT_X11)
13535 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
13536 serverStrToWin(serverid), &r, FALSE) < 0)
13537 # elif defined(MAC_CLIENTSERVER)
13538 if (serverReadReply(serverStrToPort(serverid), &r) < 0)
13539 # endif
13540 EMSG(_("E277: Unable to read a server reply"));
13542 #endif
13543 rettv->v_type = VAR_STRING;
13544 rettv->vval.v_string = r;
13548 * "remote_send()" function
13550 /*ARGSUSED*/
13551 static void
13552 f_remote_send(argvars, rettv)
13553 typval_T *argvars;
13554 typval_T *rettv;
13556 rettv->v_type = VAR_STRING;
13557 rettv->vval.v_string = NULL;
13558 #ifdef FEAT_CLIENTSERVER
13559 remote_common(argvars, rettv, FALSE);
13560 #endif
13564 * "remove()" function
13566 static void
13567 f_remove(argvars, rettv)
13568 typval_T *argvars;
13569 typval_T *rettv;
13571 list_T *l;
13572 listitem_T *item, *item2;
13573 listitem_T *li;
13574 long idx;
13575 long end;
13576 char_u *key;
13577 dict_T *d;
13578 dictitem_T *di;
13580 rettv->vval.v_number = 0;
13581 if (argvars[0].v_type == VAR_DICT)
13583 if (argvars[2].v_type != VAR_UNKNOWN)
13584 EMSG2(_(e_toomanyarg), "remove()");
13585 else if ((d = argvars[0].vval.v_dict) != NULL
13586 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
13588 key = get_tv_string_chk(&argvars[1]);
13589 if (key != NULL)
13591 di = dict_find(d, key, -1);
13592 if (di == NULL)
13593 EMSG2(_(e_dictkey), key);
13594 else
13596 *rettv = di->di_tv;
13597 init_tv(&di->di_tv);
13598 dictitem_remove(d, di);
13603 else if (argvars[0].v_type != VAR_LIST)
13604 EMSG2(_(e_listdictarg), "remove()");
13605 else if ((l = argvars[0].vval.v_list) != NULL
13606 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
13608 int error = FALSE;
13610 idx = get_tv_number_chk(&argvars[1], &error);
13611 if (error)
13612 ; /* type error: do nothing, errmsg already given */
13613 else if ((item = list_find(l, idx)) == NULL)
13614 EMSGN(_(e_listidx), idx);
13615 else
13617 if (argvars[2].v_type == VAR_UNKNOWN)
13619 /* Remove one item, return its value. */
13620 list_remove(l, item, item);
13621 *rettv = item->li_tv;
13622 vim_free(item);
13624 else
13626 /* Remove range of items, return list with values. */
13627 end = get_tv_number_chk(&argvars[2], &error);
13628 if (error)
13629 ; /* type error: do nothing */
13630 else if ((item2 = list_find(l, end)) == NULL)
13631 EMSGN(_(e_listidx), end);
13632 else
13634 int cnt = 0;
13636 for (li = item; li != NULL; li = li->li_next)
13638 ++cnt;
13639 if (li == item2)
13640 break;
13642 if (li == NULL) /* didn't find "item2" after "item" */
13643 EMSG(_(e_invrange));
13644 else
13646 list_remove(l, item, item2);
13647 if (rettv_list_alloc(rettv) == OK)
13649 l = rettv->vval.v_list;
13650 l->lv_first = item;
13651 l->lv_last = item2;
13652 item->li_prev = NULL;
13653 item2->li_next = NULL;
13654 l->lv_len = cnt;
13664 * "rename({from}, {to})" function
13666 static void
13667 f_rename(argvars, rettv)
13668 typval_T *argvars;
13669 typval_T *rettv;
13671 char_u buf[NUMBUFLEN];
13673 if (check_restricted() || check_secure())
13674 rettv->vval.v_number = -1;
13675 else
13676 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
13677 get_tv_string_buf(&argvars[1], buf));
13681 * "repeat()" function
13683 /*ARGSUSED*/
13684 static void
13685 f_repeat(argvars, rettv)
13686 typval_T *argvars;
13687 typval_T *rettv;
13689 char_u *p;
13690 int n;
13691 int slen;
13692 int len;
13693 char_u *r;
13694 int i;
13696 n = get_tv_number(&argvars[1]);
13697 if (argvars[0].v_type == VAR_LIST)
13699 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
13700 while (n-- > 0)
13701 if (list_extend(rettv->vval.v_list,
13702 argvars[0].vval.v_list, NULL) == FAIL)
13703 break;
13705 else
13707 p = get_tv_string(&argvars[0]);
13708 rettv->v_type = VAR_STRING;
13709 rettv->vval.v_string = NULL;
13711 slen = (int)STRLEN(p);
13712 len = slen * n;
13713 if (len <= 0)
13714 return;
13716 r = alloc(len + 1);
13717 if (r != NULL)
13719 for (i = 0; i < n; i++)
13720 mch_memmove(r + i * slen, p, (size_t)slen);
13721 r[len] = NUL;
13724 rettv->vval.v_string = r;
13729 * "resolve()" function
13731 static void
13732 f_resolve(argvars, rettv)
13733 typval_T *argvars;
13734 typval_T *rettv;
13736 char_u *p;
13738 p = get_tv_string(&argvars[0]);
13739 #ifdef FEAT_SHORTCUT
13741 char_u *v = NULL;
13743 v = mch_resolve_shortcut(p);
13744 if (v != NULL)
13745 rettv->vval.v_string = v;
13746 else
13747 rettv->vval.v_string = vim_strsave(p);
13749 #else
13750 # ifdef HAVE_READLINK
13752 char_u buf[MAXPATHL + 1];
13753 char_u *cpy;
13754 int len;
13755 char_u *remain = NULL;
13756 char_u *q;
13757 int is_relative_to_current = FALSE;
13758 int has_trailing_pathsep = FALSE;
13759 int limit = 100;
13761 p = vim_strsave(p);
13763 if (p[0] == '.' && (vim_ispathsep(p[1])
13764 || (p[1] == '.' && (vim_ispathsep(p[2])))))
13765 is_relative_to_current = TRUE;
13767 len = STRLEN(p);
13768 if (len > 0 && after_pathsep(p, p + len))
13769 has_trailing_pathsep = TRUE;
13771 q = getnextcomp(p);
13772 if (*q != NUL)
13774 /* Separate the first path component in "p", and keep the
13775 * remainder (beginning with the path separator). */
13776 remain = vim_strsave(q - 1);
13777 q[-1] = NUL;
13780 for (;;)
13782 for (;;)
13784 len = readlink((char *)p, (char *)buf, MAXPATHL);
13785 if (len <= 0)
13786 break;
13787 buf[len] = NUL;
13789 if (limit-- == 0)
13791 vim_free(p);
13792 vim_free(remain);
13793 EMSG(_("E655: Too many symbolic links (cycle?)"));
13794 rettv->vval.v_string = NULL;
13795 goto fail;
13798 /* Ensure that the result will have a trailing path separator
13799 * if the argument has one. */
13800 if (remain == NULL && has_trailing_pathsep)
13801 add_pathsep(buf);
13803 /* Separate the first path component in the link value and
13804 * concatenate the remainders. */
13805 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
13806 if (*q != NUL)
13808 if (remain == NULL)
13809 remain = vim_strsave(q - 1);
13810 else
13812 cpy = concat_str(q - 1, remain);
13813 if (cpy != NULL)
13815 vim_free(remain);
13816 remain = cpy;
13819 q[-1] = NUL;
13822 q = gettail(p);
13823 if (q > p && *q == NUL)
13825 /* Ignore trailing path separator. */
13826 q[-1] = NUL;
13827 q = gettail(p);
13829 if (q > p && !mch_isFullName(buf))
13831 /* symlink is relative to directory of argument */
13832 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
13833 if (cpy != NULL)
13835 STRCPY(cpy, p);
13836 STRCPY(gettail(cpy), buf);
13837 vim_free(p);
13838 p = cpy;
13841 else
13843 vim_free(p);
13844 p = vim_strsave(buf);
13848 if (remain == NULL)
13849 break;
13851 /* Append the first path component of "remain" to "p". */
13852 q = getnextcomp(remain + 1);
13853 len = q - remain - (*q != NUL);
13854 cpy = vim_strnsave(p, STRLEN(p) + len);
13855 if (cpy != NULL)
13857 STRNCAT(cpy, remain, len);
13858 vim_free(p);
13859 p = cpy;
13861 /* Shorten "remain". */
13862 if (*q != NUL)
13863 mch_memmove(remain, q - 1, STRLEN(q - 1) + 1);
13864 else
13866 vim_free(remain);
13867 remain = NULL;
13871 /* If the result is a relative path name, make it explicitly relative to
13872 * the current directory if and only if the argument had this form. */
13873 if (!vim_ispathsep(*p))
13875 if (is_relative_to_current
13876 && *p != NUL
13877 && !(p[0] == '.'
13878 && (p[1] == NUL
13879 || vim_ispathsep(p[1])
13880 || (p[1] == '.'
13881 && (p[2] == NUL
13882 || vim_ispathsep(p[2]))))))
13884 /* Prepend "./". */
13885 cpy = concat_str((char_u *)"./", p);
13886 if (cpy != NULL)
13888 vim_free(p);
13889 p = cpy;
13892 else if (!is_relative_to_current)
13894 /* Strip leading "./". */
13895 q = p;
13896 while (q[0] == '.' && vim_ispathsep(q[1]))
13897 q += 2;
13898 if (q > p)
13899 mch_memmove(p, p + 2, STRLEN(p + 2) + (size_t)1);
13903 /* Ensure that the result will have no trailing path separator
13904 * if the argument had none. But keep "/" or "//". */
13905 if (!has_trailing_pathsep)
13907 q = p + STRLEN(p);
13908 if (after_pathsep(p, q))
13909 *gettail_sep(p) = NUL;
13912 rettv->vval.v_string = p;
13914 # else
13915 rettv->vval.v_string = vim_strsave(p);
13916 # endif
13917 #endif
13919 simplify_filename(rettv->vval.v_string);
13921 #ifdef HAVE_READLINK
13922 fail:
13923 #endif
13924 rettv->v_type = VAR_STRING;
13928 * "reverse({list})" function
13930 static void
13931 f_reverse(argvars, rettv)
13932 typval_T *argvars;
13933 typval_T *rettv;
13935 list_T *l;
13936 listitem_T *li, *ni;
13938 rettv->vval.v_number = 0;
13939 if (argvars[0].v_type != VAR_LIST)
13940 EMSG2(_(e_listarg), "reverse()");
13941 else if ((l = argvars[0].vval.v_list) != NULL
13942 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
13944 li = l->lv_last;
13945 l->lv_first = l->lv_last = NULL;
13946 l->lv_len = 0;
13947 while (li != NULL)
13949 ni = li->li_prev;
13950 list_append(l, li);
13951 li = ni;
13953 rettv->vval.v_list = l;
13954 rettv->v_type = VAR_LIST;
13955 ++l->lv_refcount;
13959 #define SP_NOMOVE 0x01 /* don't move cursor */
13960 #define SP_REPEAT 0x02 /* repeat to find outer pair */
13961 #define SP_RETCOUNT 0x04 /* return matchcount */
13962 #define SP_SETPCMARK 0x08 /* set previous context mark */
13963 #define SP_START 0x10 /* accept match at start position */
13964 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
13965 #define SP_END 0x40 /* leave cursor at end of match */
13967 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
13970 * Get flags for a search function.
13971 * Possibly sets "p_ws".
13972 * Returns BACKWARD, FORWARD or zero (for an error).
13974 static int
13975 get_search_arg(varp, flagsp)
13976 typval_T *varp;
13977 int *flagsp;
13979 int dir = FORWARD;
13980 char_u *flags;
13981 char_u nbuf[NUMBUFLEN];
13982 int mask;
13984 if (varp->v_type != VAR_UNKNOWN)
13986 flags = get_tv_string_buf_chk(varp, nbuf);
13987 if (flags == NULL)
13988 return 0; /* type error; errmsg already given */
13989 while (*flags != NUL)
13991 switch (*flags)
13993 case 'b': dir = BACKWARD; break;
13994 case 'w': p_ws = TRUE; break;
13995 case 'W': p_ws = FALSE; break;
13996 default: mask = 0;
13997 if (flagsp != NULL)
13998 switch (*flags)
14000 case 'c': mask = SP_START; break;
14001 case 'e': mask = SP_END; break;
14002 case 'm': mask = SP_RETCOUNT; break;
14003 case 'n': mask = SP_NOMOVE; break;
14004 case 'p': mask = SP_SUBPAT; break;
14005 case 'r': mask = SP_REPEAT; break;
14006 case 's': mask = SP_SETPCMARK; break;
14008 if (mask == 0)
14010 EMSG2(_(e_invarg2), flags);
14011 dir = 0;
14013 else
14014 *flagsp |= mask;
14016 if (dir == 0)
14017 break;
14018 ++flags;
14021 return dir;
14025 * Shared by search() and searchpos() functions
14027 static int
14028 search_cmn(argvars, match_pos, flagsp)
14029 typval_T *argvars;
14030 pos_T *match_pos;
14031 int *flagsp;
14033 int flags;
14034 char_u *pat;
14035 pos_T pos;
14036 pos_T save_cursor;
14037 int save_p_ws = p_ws;
14038 int dir;
14039 int retval = 0; /* default: FAIL */
14040 long lnum_stop = 0;
14041 int options = SEARCH_KEEP;
14042 int subpatnum;
14044 pat = get_tv_string(&argvars[0]);
14045 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
14046 if (dir == 0)
14047 goto theend;
14048 flags = *flagsp;
14049 if (flags & SP_START)
14050 options |= SEARCH_START;
14051 if (flags & SP_END)
14052 options |= SEARCH_END;
14054 /* Optional extra argument: line number to stop searching. */
14055 if (argvars[1].v_type != VAR_UNKNOWN
14056 && argvars[2].v_type != VAR_UNKNOWN)
14058 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
14059 if (lnum_stop < 0)
14060 goto theend;
14064 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
14065 * Check to make sure only those flags are set.
14066 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
14067 * flags cannot be set. Check for that condition also.
14069 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
14070 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14072 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
14073 goto theend;
14076 pos = save_cursor = curwin->w_cursor;
14077 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14078 options, RE_SEARCH, (linenr_T)lnum_stop);
14079 if (subpatnum != FAIL)
14081 if (flags & SP_SUBPAT)
14082 retval = subpatnum;
14083 else
14084 retval = pos.lnum;
14085 if (flags & SP_SETPCMARK)
14086 setpcmark();
14087 curwin->w_cursor = pos;
14088 if (match_pos != NULL)
14090 /* Store the match cursor position */
14091 match_pos->lnum = pos.lnum;
14092 match_pos->col = pos.col + 1;
14094 /* "/$" will put the cursor after the end of the line, may need to
14095 * correct that here */
14096 check_cursor();
14099 /* If 'n' flag is used: restore cursor position. */
14100 if (flags & SP_NOMOVE)
14101 curwin->w_cursor = save_cursor;
14102 else
14103 curwin->w_set_curswant = TRUE;
14104 theend:
14105 p_ws = save_p_ws;
14107 return retval;
14111 * "search()" function
14113 static void
14114 f_search(argvars, rettv)
14115 typval_T *argvars;
14116 typval_T *rettv;
14118 int flags = 0;
14120 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
14124 * "searchdecl()" function
14126 static void
14127 f_searchdecl(argvars, rettv)
14128 typval_T *argvars;
14129 typval_T *rettv;
14131 int locally = 1;
14132 int thisblock = 0;
14133 int error = FALSE;
14134 char_u *name;
14136 rettv->vval.v_number = 1; /* default: FAIL */
14138 name = get_tv_string_chk(&argvars[0]);
14139 if (argvars[1].v_type != VAR_UNKNOWN)
14141 locally = get_tv_number_chk(&argvars[1], &error) == 0;
14142 if (!error && argvars[2].v_type != VAR_UNKNOWN)
14143 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
14145 if (!error && name != NULL)
14146 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
14147 locally, thisblock, SEARCH_KEEP) == FAIL;
14151 * Used by searchpair() and searchpairpos()
14153 static int
14154 searchpair_cmn(argvars, match_pos)
14155 typval_T *argvars;
14156 pos_T *match_pos;
14158 char_u *spat, *mpat, *epat;
14159 char_u *skip;
14160 int save_p_ws = p_ws;
14161 int dir;
14162 int flags = 0;
14163 char_u nbuf1[NUMBUFLEN];
14164 char_u nbuf2[NUMBUFLEN];
14165 char_u nbuf3[NUMBUFLEN];
14166 int retval = 0; /* default: FAIL */
14167 long lnum_stop = 0;
14169 /* Get the three pattern arguments: start, middle, end. */
14170 spat = get_tv_string_chk(&argvars[0]);
14171 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
14172 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
14173 if (spat == NULL || mpat == NULL || epat == NULL)
14174 goto theend; /* type error */
14176 /* Handle the optional fourth argument: flags */
14177 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
14178 if (dir == 0)
14179 goto theend;
14181 /* Don't accept SP_END or SP_SUBPAT.
14182 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
14184 if ((flags & (SP_END | SP_SUBPAT)) != 0
14185 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14187 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
14188 goto theend;
14191 /* Optional fifth argument: skip expression */
14192 if (argvars[3].v_type == VAR_UNKNOWN
14193 || argvars[4].v_type == VAR_UNKNOWN)
14194 skip = (char_u *)"";
14195 else
14197 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
14198 if (argvars[5].v_type != VAR_UNKNOWN)
14200 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
14201 if (lnum_stop < 0)
14202 goto theend;
14205 if (skip == NULL)
14206 goto theend; /* type error */
14208 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
14209 match_pos, lnum_stop);
14211 theend:
14212 p_ws = save_p_ws;
14214 return retval;
14218 * "searchpair()" function
14220 static void
14221 f_searchpair(argvars, rettv)
14222 typval_T *argvars;
14223 typval_T *rettv;
14225 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
14229 * "searchpairpos()" function
14231 static void
14232 f_searchpairpos(argvars, rettv)
14233 typval_T *argvars;
14234 typval_T *rettv;
14236 pos_T match_pos;
14237 int lnum = 0;
14238 int col = 0;
14240 rettv->vval.v_number = 0;
14242 if (rettv_list_alloc(rettv) == FAIL)
14243 return;
14245 if (searchpair_cmn(argvars, &match_pos) > 0)
14247 lnum = match_pos.lnum;
14248 col = match_pos.col;
14251 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14252 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14256 * Search for a start/middle/end thing.
14257 * Used by searchpair(), see its documentation for the details.
14258 * Returns 0 or -1 for no match,
14260 long
14261 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos, lnum_stop)
14262 char_u *spat; /* start pattern */
14263 char_u *mpat; /* middle pattern */
14264 char_u *epat; /* end pattern */
14265 int dir; /* BACKWARD or FORWARD */
14266 char_u *skip; /* skip expression */
14267 int flags; /* SP_SETPCMARK and other SP_ values */
14268 pos_T *match_pos;
14269 linenr_T lnum_stop; /* stop at this line if not zero */
14271 char_u *save_cpo;
14272 char_u *pat, *pat2 = NULL, *pat3 = NULL;
14273 long retval = 0;
14274 pos_T pos;
14275 pos_T firstpos;
14276 pos_T foundpos;
14277 pos_T save_cursor;
14278 pos_T save_pos;
14279 int n;
14280 int r;
14281 int nest = 1;
14282 int err;
14283 int options = SEARCH_KEEP;
14285 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
14286 save_cpo = p_cpo;
14287 p_cpo = (char_u *)"";
14289 /* Make two search patterns: start/end (pat2, for in nested pairs) and
14290 * start/middle/end (pat3, for the top pair). */
14291 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
14292 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
14293 if (pat2 == NULL || pat3 == NULL)
14294 goto theend;
14295 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
14296 if (*mpat == NUL)
14297 STRCPY(pat3, pat2);
14298 else
14299 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
14300 spat, epat, mpat);
14301 if (flags & SP_START)
14302 options |= SEARCH_START;
14304 save_cursor = curwin->w_cursor;
14305 pos = curwin->w_cursor;
14306 clearpos(&firstpos);
14307 clearpos(&foundpos);
14308 pat = pat3;
14309 for (;;)
14311 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14312 options, RE_SEARCH, lnum_stop);
14313 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
14314 /* didn't find it or found the first match again: FAIL */
14315 break;
14317 if (firstpos.lnum == 0)
14318 firstpos = pos;
14319 if (equalpos(pos, foundpos))
14321 /* Found the same position again. Can happen with a pattern that
14322 * has "\zs" at the end and searching backwards. Advance one
14323 * character and try again. */
14324 if (dir == BACKWARD)
14325 decl(&pos);
14326 else
14327 incl(&pos);
14329 foundpos = pos;
14331 /* If the skip pattern matches, ignore this match. */
14332 if (*skip != NUL)
14334 save_pos = curwin->w_cursor;
14335 curwin->w_cursor = pos;
14336 r = eval_to_bool(skip, &err, NULL, FALSE);
14337 curwin->w_cursor = save_pos;
14338 if (err)
14340 /* Evaluating {skip} caused an error, break here. */
14341 curwin->w_cursor = save_cursor;
14342 retval = -1;
14343 break;
14345 if (r)
14346 continue;
14349 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
14351 /* Found end when searching backwards or start when searching
14352 * forward: nested pair. */
14353 ++nest;
14354 pat = pat2; /* nested, don't search for middle */
14356 else
14358 /* Found end when searching forward or start when searching
14359 * backward: end of (nested) pair; or found middle in outer pair. */
14360 if (--nest == 1)
14361 pat = pat3; /* outer level, search for middle */
14364 if (nest == 0)
14366 /* Found the match: return matchcount or line number. */
14367 if (flags & SP_RETCOUNT)
14368 ++retval;
14369 else
14370 retval = pos.lnum;
14371 if (flags & SP_SETPCMARK)
14372 setpcmark();
14373 curwin->w_cursor = pos;
14374 if (!(flags & SP_REPEAT))
14375 break;
14376 nest = 1; /* search for next unmatched */
14380 if (match_pos != NULL)
14382 /* Store the match cursor position */
14383 match_pos->lnum = curwin->w_cursor.lnum;
14384 match_pos->col = curwin->w_cursor.col + 1;
14387 /* If 'n' flag is used or search failed: restore cursor position. */
14388 if ((flags & SP_NOMOVE) || retval == 0)
14389 curwin->w_cursor = save_cursor;
14391 theend:
14392 vim_free(pat2);
14393 vim_free(pat3);
14394 p_cpo = save_cpo;
14396 return retval;
14400 * "searchpos()" function
14402 static void
14403 f_searchpos(argvars, rettv)
14404 typval_T *argvars;
14405 typval_T *rettv;
14407 pos_T match_pos;
14408 int lnum = 0;
14409 int col = 0;
14410 int n;
14411 int flags = 0;
14413 rettv->vval.v_number = 0;
14415 if (rettv_list_alloc(rettv) == FAIL)
14416 return;
14418 n = search_cmn(argvars, &match_pos, &flags);
14419 if (n > 0)
14421 lnum = match_pos.lnum;
14422 col = match_pos.col;
14425 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14426 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14427 if (flags & SP_SUBPAT)
14428 list_append_number(rettv->vval.v_list, (varnumber_T)n);
14432 /*ARGSUSED*/
14433 static void
14434 f_server2client(argvars, rettv)
14435 typval_T *argvars;
14436 typval_T *rettv;
14438 #ifdef FEAT_CLIENTSERVER
14439 char_u buf[NUMBUFLEN];
14440 char_u *server = get_tv_string_chk(&argvars[0]);
14441 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
14443 rettv->vval.v_number = -1;
14444 if (server == NULL || reply == NULL)
14445 return;
14446 if (check_restricted() || check_secure())
14447 return;
14448 # ifdef FEAT_X11
14449 if (check_connection() == FAIL)
14450 return;
14451 # endif
14453 if (serverSendReply(server, reply) < 0)
14455 EMSG(_("E258: Unable to send to client"));
14456 return;
14458 rettv->vval.v_number = 0;
14459 #else
14460 rettv->vval.v_number = -1;
14461 #endif
14464 /*ARGSUSED*/
14465 static void
14466 f_serverlist(argvars, rettv)
14467 typval_T *argvars;
14468 typval_T *rettv;
14470 char_u *r = NULL;
14472 #ifdef FEAT_CLIENTSERVER
14473 # if defined(WIN32) || defined(MAC_CLIENTSERVER)
14474 r = serverGetVimNames();
14475 # elif defined(FEAT_X11)
14476 make_connection();
14477 if (X_DISPLAY != NULL)
14478 r = serverGetVimNames(X_DISPLAY);
14479 # endif
14480 #endif
14481 rettv->v_type = VAR_STRING;
14482 rettv->vval.v_string = r;
14486 * "setbufvar()" function
14488 /*ARGSUSED*/
14489 static void
14490 f_setbufvar(argvars, rettv)
14491 typval_T *argvars;
14492 typval_T *rettv;
14494 buf_T *buf;
14495 aco_save_T aco;
14496 char_u *varname, *bufvarname;
14497 typval_T *varp;
14498 char_u nbuf[NUMBUFLEN];
14500 rettv->vval.v_number = 0;
14502 if (check_restricted() || check_secure())
14503 return;
14504 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
14505 varname = get_tv_string_chk(&argvars[1]);
14506 buf = get_buf_tv(&argvars[0]);
14507 varp = &argvars[2];
14509 if (buf != NULL && varname != NULL && varp != NULL)
14511 /* set curbuf to be our buf, temporarily */
14512 aucmd_prepbuf(&aco, buf);
14514 if (*varname == '&')
14516 long numval;
14517 char_u *strval;
14518 int error = FALSE;
14520 ++varname;
14521 numval = get_tv_number_chk(varp, &error);
14522 strval = get_tv_string_buf_chk(varp, nbuf);
14523 if (!error && strval != NULL)
14524 set_option_value(varname, numval, strval, OPT_LOCAL);
14526 else
14528 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
14529 if (bufvarname != NULL)
14531 STRCPY(bufvarname, "b:");
14532 STRCPY(bufvarname + 2, varname);
14533 set_var(bufvarname, varp, TRUE);
14534 vim_free(bufvarname);
14538 /* reset notion of buffer */
14539 aucmd_restbuf(&aco);
14544 * "setcmdpos()" function
14546 static void
14547 f_setcmdpos(argvars, rettv)
14548 typval_T *argvars;
14549 typval_T *rettv;
14551 int pos = (int)get_tv_number(&argvars[0]) - 1;
14553 if (pos >= 0)
14554 rettv->vval.v_number = set_cmdline_pos(pos);
14558 * "setline()" function
14560 static void
14561 f_setline(argvars, rettv)
14562 typval_T *argvars;
14563 typval_T *rettv;
14565 linenr_T lnum;
14566 char_u *line = NULL;
14567 list_T *l = NULL;
14568 listitem_T *li = NULL;
14569 long added = 0;
14570 linenr_T lcount = curbuf->b_ml.ml_line_count;
14572 lnum = get_tv_lnum(&argvars[0]);
14573 if (argvars[1].v_type == VAR_LIST)
14575 l = argvars[1].vval.v_list;
14576 li = l->lv_first;
14578 else
14579 line = get_tv_string_chk(&argvars[1]);
14581 rettv->vval.v_number = 0; /* OK */
14582 for (;;)
14584 if (l != NULL)
14586 /* list argument, get next string */
14587 if (li == NULL)
14588 break;
14589 line = get_tv_string_chk(&li->li_tv);
14590 li = li->li_next;
14593 rettv->vval.v_number = 1; /* FAIL */
14594 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
14595 break;
14596 if (lnum <= curbuf->b_ml.ml_line_count)
14598 /* existing line, replace it */
14599 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
14601 changed_bytes(lnum, 0);
14602 if (lnum == curwin->w_cursor.lnum)
14603 check_cursor_col();
14604 rettv->vval.v_number = 0; /* OK */
14607 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
14609 /* lnum is one past the last line, append the line */
14610 ++added;
14611 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
14612 rettv->vval.v_number = 0; /* OK */
14615 if (l == NULL) /* only one string argument */
14616 break;
14617 ++lnum;
14620 if (added > 0)
14621 appended_lines_mark(lcount, added);
14625 * Used by "setqflist()" and "setloclist()" functions
14627 /*ARGSUSED*/
14628 static void
14629 set_qf_ll_list(wp, list_arg, action_arg, rettv)
14630 win_T *wp;
14631 typval_T *list_arg;
14632 typval_T *action_arg;
14633 typval_T *rettv;
14635 #ifdef FEAT_QUICKFIX
14636 char_u *act;
14637 int action = ' ';
14638 #endif
14640 rettv->vval.v_number = -1;
14642 #ifdef FEAT_QUICKFIX
14643 if (list_arg->v_type != VAR_LIST)
14644 EMSG(_(e_listreq));
14645 else
14647 list_T *l = list_arg->vval.v_list;
14649 if (action_arg->v_type == VAR_STRING)
14651 act = get_tv_string_chk(action_arg);
14652 if (act == NULL)
14653 return; /* type error; errmsg already given */
14654 if (*act == 'a' || *act == 'r')
14655 action = *act;
14658 if (l != NULL && set_errorlist(wp, l, action) == OK)
14659 rettv->vval.v_number = 0;
14661 #endif
14665 * "setloclist()" function
14667 /*ARGSUSED*/
14668 static void
14669 f_setloclist(argvars, rettv)
14670 typval_T *argvars;
14671 typval_T *rettv;
14673 win_T *win;
14675 rettv->vval.v_number = -1;
14677 win = find_win_by_nr(&argvars[0], NULL);
14678 if (win != NULL)
14679 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
14683 * "setmatches()" function
14685 static void
14686 f_setmatches(argvars, rettv)
14687 typval_T *argvars;
14688 typval_T *rettv;
14690 #ifdef FEAT_SEARCH_EXTRA
14691 list_T *l;
14692 listitem_T *li;
14693 dict_T *d;
14695 rettv->vval.v_number = -1;
14696 if (argvars[0].v_type != VAR_LIST)
14698 EMSG(_(e_listreq));
14699 return;
14701 if ((l = argvars[0].vval.v_list) != NULL)
14704 /* To some extent make sure that we are dealing with a list from
14705 * "getmatches()". */
14706 li = l->lv_first;
14707 while (li != NULL)
14709 if (li->li_tv.v_type != VAR_DICT
14710 || (d = li->li_tv.vval.v_dict) == NULL)
14712 EMSG(_(e_invarg));
14713 return;
14715 if (!(dict_find(d, (char_u *)"group", -1) != NULL
14716 && dict_find(d, (char_u *)"pattern", -1) != NULL
14717 && dict_find(d, (char_u *)"priority", -1) != NULL
14718 && dict_find(d, (char_u *)"id", -1) != NULL))
14720 EMSG(_(e_invarg));
14721 return;
14723 li = li->li_next;
14726 clear_matches(curwin);
14727 li = l->lv_first;
14728 while (li != NULL)
14730 d = li->li_tv.vval.v_dict;
14731 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
14732 get_dict_string(d, (char_u *)"pattern", FALSE),
14733 (int)get_dict_number(d, (char_u *)"priority"),
14734 (int)get_dict_number(d, (char_u *)"id"));
14735 li = li->li_next;
14737 rettv->vval.v_number = 0;
14739 #endif
14743 * "setpos()" function
14745 /*ARGSUSED*/
14746 static void
14747 f_setpos(argvars, rettv)
14748 typval_T *argvars;
14749 typval_T *rettv;
14751 pos_T pos;
14752 int fnum;
14753 char_u *name;
14755 name = get_tv_string_chk(argvars);
14756 if (name != NULL)
14758 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
14760 --pos.col;
14761 if (name[0] == '.') /* cursor */
14763 if (fnum == curbuf->b_fnum)
14765 curwin->w_cursor = pos;
14766 check_cursor();
14768 else
14769 EMSG(_(e_invarg));
14771 else if (name[0] == '\'') /* mark */
14772 (void)setmark_pos(name[1], &pos, fnum);
14773 else
14774 EMSG(_(e_invarg));
14780 * "setqflist()" function
14782 /*ARGSUSED*/
14783 static void
14784 f_setqflist(argvars, rettv)
14785 typval_T *argvars;
14786 typval_T *rettv;
14788 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
14792 * "setreg()" function
14794 static void
14795 f_setreg(argvars, rettv)
14796 typval_T *argvars;
14797 typval_T *rettv;
14799 int regname;
14800 char_u *strregname;
14801 char_u *stropt;
14802 char_u *strval;
14803 int append;
14804 char_u yank_type;
14805 long block_len;
14807 block_len = -1;
14808 yank_type = MAUTO;
14809 append = FALSE;
14811 strregname = get_tv_string_chk(argvars);
14812 rettv->vval.v_number = 1; /* FAIL is default */
14814 if (strregname == NULL)
14815 return; /* type error; errmsg already given */
14816 regname = *strregname;
14817 if (regname == 0 || regname == '@')
14818 regname = '"';
14819 else if (regname == '=')
14820 return;
14822 if (argvars[2].v_type != VAR_UNKNOWN)
14824 stropt = get_tv_string_chk(&argvars[2]);
14825 if (stropt == NULL)
14826 return; /* type error */
14827 for (; *stropt != NUL; ++stropt)
14828 switch (*stropt)
14830 case 'a': case 'A': /* append */
14831 append = TRUE;
14832 break;
14833 case 'v': case 'c': /* character-wise selection */
14834 yank_type = MCHAR;
14835 break;
14836 case 'V': case 'l': /* line-wise selection */
14837 yank_type = MLINE;
14838 break;
14839 #ifdef FEAT_VISUAL
14840 case 'b': case Ctrl_V: /* block-wise selection */
14841 yank_type = MBLOCK;
14842 if (VIM_ISDIGIT(stropt[1]))
14844 ++stropt;
14845 block_len = getdigits(&stropt) - 1;
14846 --stropt;
14848 break;
14849 #endif
14853 strval = get_tv_string_chk(&argvars[1]);
14854 if (strval != NULL)
14855 write_reg_contents_ex(regname, strval, -1,
14856 append, yank_type, block_len);
14857 rettv->vval.v_number = 0;
14861 * "settabwinvar()" function
14863 static void
14864 f_settabwinvar(argvars, rettv)
14865 typval_T *argvars;
14866 typval_T *rettv;
14868 setwinvar(argvars, rettv, 1);
14872 * "setwinvar()" function
14874 static void
14875 f_setwinvar(argvars, rettv)
14876 typval_T *argvars;
14877 typval_T *rettv;
14879 setwinvar(argvars, rettv, 0);
14883 * "setwinvar()" and "settabwinvar()" functions
14885 static void
14886 setwinvar(argvars, rettv, off)
14887 typval_T *argvars;
14888 typval_T *rettv;
14889 int off;
14891 win_T *win;
14892 #ifdef FEAT_WINDOWS
14893 win_T *save_curwin;
14894 tabpage_T *save_curtab;
14895 #endif
14896 char_u *varname, *winvarname;
14897 typval_T *varp;
14898 char_u nbuf[NUMBUFLEN];
14899 tabpage_T *tp;
14901 rettv->vval.v_number = 0;
14903 if (check_restricted() || check_secure())
14904 return;
14906 #ifdef FEAT_WINDOWS
14907 if (off == 1)
14908 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
14909 else
14910 tp = curtab;
14911 #endif
14912 win = find_win_by_nr(&argvars[off], tp);
14913 varname = get_tv_string_chk(&argvars[off + 1]);
14914 varp = &argvars[off + 2];
14916 if (win != NULL && varname != NULL && varp != NULL)
14918 #ifdef FEAT_WINDOWS
14919 /* set curwin to be our win, temporarily */
14920 save_curwin = curwin;
14921 save_curtab = curtab;
14922 goto_tabpage_tp(tp);
14923 if (!win_valid(win))
14924 return;
14925 curwin = win;
14926 curbuf = curwin->w_buffer;
14927 #endif
14929 if (*varname == '&')
14931 long numval;
14932 char_u *strval;
14933 int error = FALSE;
14935 ++varname;
14936 numval = get_tv_number_chk(varp, &error);
14937 strval = get_tv_string_buf_chk(varp, nbuf);
14938 if (!error && strval != NULL)
14939 set_option_value(varname, numval, strval, OPT_LOCAL);
14941 else
14943 winvarname = alloc((unsigned)STRLEN(varname) + 3);
14944 if (winvarname != NULL)
14946 STRCPY(winvarname, "w:");
14947 STRCPY(winvarname + 2, varname);
14948 set_var(winvarname, varp, TRUE);
14949 vim_free(winvarname);
14953 #ifdef FEAT_WINDOWS
14954 /* Restore current tabpage and window, if still valid (autocomands can
14955 * make them invalid). */
14956 if (valid_tabpage(save_curtab))
14957 goto_tabpage_tp(save_curtab);
14958 if (win_valid(save_curwin))
14960 curwin = save_curwin;
14961 curbuf = curwin->w_buffer;
14963 #endif
14968 * "shellescape({string})" function
14970 static void
14971 f_shellescape(argvars, rettv)
14972 typval_T *argvars;
14973 typval_T *rettv;
14975 rettv->vval.v_string = vim_strsave_shellescape(get_tv_string(&argvars[0]));
14976 rettv->v_type = VAR_STRING;
14980 * "simplify()" function
14982 static void
14983 f_simplify(argvars, rettv)
14984 typval_T *argvars;
14985 typval_T *rettv;
14987 char_u *p;
14989 p = get_tv_string(&argvars[0]);
14990 rettv->vval.v_string = vim_strsave(p);
14991 simplify_filename(rettv->vval.v_string); /* simplify in place */
14992 rettv->v_type = VAR_STRING;
14995 static int
14996 #ifdef __BORLANDC__
14997 _RTLENTRYF
14998 #endif
14999 item_compare __ARGS((const void *s1, const void *s2));
15000 static int
15001 #ifdef __BORLANDC__
15002 _RTLENTRYF
15003 #endif
15004 item_compare2 __ARGS((const void *s1, const void *s2));
15006 static int item_compare_ic;
15007 static char_u *item_compare_func;
15008 static int item_compare_func_err;
15009 #define ITEM_COMPARE_FAIL 999
15012 * Compare functions for f_sort() below.
15014 static int
15015 #ifdef __BORLANDC__
15016 _RTLENTRYF
15017 #endif
15018 item_compare(s1, s2)
15019 const void *s1;
15020 const void *s2;
15022 char_u *p1, *p2;
15023 char_u *tofree1, *tofree2;
15024 int res;
15025 char_u numbuf1[NUMBUFLEN];
15026 char_u numbuf2[NUMBUFLEN];
15028 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
15029 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
15030 if (p1 == NULL)
15031 p1 = (char_u *)"";
15032 if (p2 == NULL)
15033 p2 = (char_u *)"";
15034 if (item_compare_ic)
15035 res = STRICMP(p1, p2);
15036 else
15037 res = STRCMP(p1, p2);
15038 vim_free(tofree1);
15039 vim_free(tofree2);
15040 return res;
15043 static int
15044 #ifdef __BORLANDC__
15045 _RTLENTRYF
15046 #endif
15047 item_compare2(s1, s2)
15048 const void *s1;
15049 const void *s2;
15051 int res;
15052 typval_T rettv;
15053 typval_T argv[3];
15054 int dummy;
15056 /* shortcut after failure in previous call; compare all items equal */
15057 if (item_compare_func_err)
15058 return 0;
15060 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
15061 * in the copy without changing the original list items. */
15062 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
15063 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
15065 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
15066 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
15067 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
15068 clear_tv(&argv[0]);
15069 clear_tv(&argv[1]);
15071 if (res == FAIL)
15072 res = ITEM_COMPARE_FAIL;
15073 else
15074 /* return value has wrong type */
15075 res = get_tv_number_chk(&rettv, &item_compare_func_err);
15076 if (item_compare_func_err)
15077 res = ITEM_COMPARE_FAIL;
15078 clear_tv(&rettv);
15079 return res;
15083 * "sort({list})" function
15085 static void
15086 f_sort(argvars, rettv)
15087 typval_T *argvars;
15088 typval_T *rettv;
15090 list_T *l;
15091 listitem_T *li;
15092 listitem_T **ptrs;
15093 long len;
15094 long i;
15096 rettv->vval.v_number = 0;
15097 if (argvars[0].v_type != VAR_LIST)
15098 EMSG2(_(e_listarg), "sort()");
15099 else
15101 l = argvars[0].vval.v_list;
15102 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
15103 return;
15104 rettv->vval.v_list = l;
15105 rettv->v_type = VAR_LIST;
15106 ++l->lv_refcount;
15108 len = list_len(l);
15109 if (len <= 1)
15110 return; /* short list sorts pretty quickly */
15112 item_compare_ic = FALSE;
15113 item_compare_func = NULL;
15114 if (argvars[1].v_type != VAR_UNKNOWN)
15116 if (argvars[1].v_type == VAR_FUNC)
15117 item_compare_func = argvars[1].vval.v_string;
15118 else
15120 int error = FALSE;
15122 i = get_tv_number_chk(&argvars[1], &error);
15123 if (error)
15124 return; /* type error; errmsg already given */
15125 if (i == 1)
15126 item_compare_ic = TRUE;
15127 else
15128 item_compare_func = get_tv_string(&argvars[1]);
15132 /* Make an array with each entry pointing to an item in the List. */
15133 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
15134 if (ptrs == NULL)
15135 return;
15136 i = 0;
15137 for (li = l->lv_first; li != NULL; li = li->li_next)
15138 ptrs[i++] = li;
15140 item_compare_func_err = FALSE;
15141 /* test the compare function */
15142 if (item_compare_func != NULL
15143 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
15144 == ITEM_COMPARE_FAIL)
15145 EMSG(_("E702: Sort compare function failed"));
15146 else
15148 /* Sort the array with item pointers. */
15149 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
15150 item_compare_func == NULL ? item_compare : item_compare2);
15152 if (!item_compare_func_err)
15154 /* Clear the List and append the items in the sorted order. */
15155 l->lv_first = l->lv_last = NULL;
15156 l->lv_len = 0;
15157 for (i = 0; i < len; ++i)
15158 list_append(l, ptrs[i]);
15162 vim_free(ptrs);
15167 * "soundfold({word})" function
15169 static void
15170 f_soundfold(argvars, rettv)
15171 typval_T *argvars;
15172 typval_T *rettv;
15174 char_u *s;
15176 rettv->v_type = VAR_STRING;
15177 s = get_tv_string(&argvars[0]);
15178 #ifdef FEAT_SPELL
15179 rettv->vval.v_string = eval_soundfold(s);
15180 #else
15181 rettv->vval.v_string = vim_strsave(s);
15182 #endif
15186 * "spellbadword()" function
15188 /* ARGSUSED */
15189 static void
15190 f_spellbadword(argvars, rettv)
15191 typval_T *argvars;
15192 typval_T *rettv;
15194 char_u *word = (char_u *)"";
15195 hlf_T attr = HLF_COUNT;
15196 int len = 0;
15198 if (rettv_list_alloc(rettv) == FAIL)
15199 return;
15201 #ifdef FEAT_SPELL
15202 if (argvars[0].v_type == VAR_UNKNOWN)
15204 /* Find the start and length of the badly spelled word. */
15205 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
15206 if (len != 0)
15207 word = ml_get_cursor();
15209 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15211 char_u *str = get_tv_string_chk(&argvars[0]);
15212 int capcol = -1;
15214 if (str != NULL)
15216 /* Check the argument for spelling. */
15217 while (*str != NUL)
15219 len = spell_check(curwin, str, &attr, &capcol, FALSE);
15220 if (attr != HLF_COUNT)
15222 word = str;
15223 break;
15225 str += len;
15229 #endif
15231 list_append_string(rettv->vval.v_list, word, len);
15232 list_append_string(rettv->vval.v_list, (char_u *)(
15233 attr == HLF_SPB ? "bad" :
15234 attr == HLF_SPR ? "rare" :
15235 attr == HLF_SPL ? "local" :
15236 attr == HLF_SPC ? "caps" :
15237 ""), -1);
15241 * "spellsuggest()" function
15243 /*ARGSUSED*/
15244 static void
15245 f_spellsuggest(argvars, rettv)
15246 typval_T *argvars;
15247 typval_T *rettv;
15249 #ifdef FEAT_SPELL
15250 char_u *str;
15251 int typeerr = FALSE;
15252 int maxcount;
15253 garray_T ga;
15254 int i;
15255 listitem_T *li;
15256 int need_capital = FALSE;
15257 #endif
15259 if (rettv_list_alloc(rettv) == FAIL)
15260 return;
15262 #ifdef FEAT_SPELL
15263 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15265 str = get_tv_string(&argvars[0]);
15266 if (argvars[1].v_type != VAR_UNKNOWN)
15268 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
15269 if (maxcount <= 0)
15270 return;
15271 if (argvars[2].v_type != VAR_UNKNOWN)
15273 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
15274 if (typeerr)
15275 return;
15278 else
15279 maxcount = 25;
15281 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
15283 for (i = 0; i < ga.ga_len; ++i)
15285 str = ((char_u **)ga.ga_data)[i];
15287 li = listitem_alloc();
15288 if (li == NULL)
15289 vim_free(str);
15290 else
15292 li->li_tv.v_type = VAR_STRING;
15293 li->li_tv.v_lock = 0;
15294 li->li_tv.vval.v_string = str;
15295 list_append(rettv->vval.v_list, li);
15298 ga_clear(&ga);
15300 #endif
15303 static void
15304 f_split(argvars, rettv)
15305 typval_T *argvars;
15306 typval_T *rettv;
15308 char_u *str;
15309 char_u *end;
15310 char_u *pat = NULL;
15311 regmatch_T regmatch;
15312 char_u patbuf[NUMBUFLEN];
15313 char_u *save_cpo;
15314 int match;
15315 colnr_T col = 0;
15316 int keepempty = FALSE;
15317 int typeerr = FALSE;
15319 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15320 save_cpo = p_cpo;
15321 p_cpo = (char_u *)"";
15323 str = get_tv_string(&argvars[0]);
15324 if (argvars[1].v_type != VAR_UNKNOWN)
15326 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
15327 if (pat == NULL)
15328 typeerr = TRUE;
15329 if (argvars[2].v_type != VAR_UNKNOWN)
15330 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
15332 if (pat == NULL || *pat == NUL)
15333 pat = (char_u *)"[\\x01- ]\\+";
15335 if (rettv_list_alloc(rettv) == FAIL)
15336 return;
15337 if (typeerr)
15338 return;
15340 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
15341 if (regmatch.regprog != NULL)
15343 regmatch.rm_ic = FALSE;
15344 while (*str != NUL || keepempty)
15346 if (*str == NUL)
15347 match = FALSE; /* empty item at the end */
15348 else
15349 match = vim_regexec_nl(&regmatch, str, col);
15350 if (match)
15351 end = regmatch.startp[0];
15352 else
15353 end = str + STRLEN(str);
15354 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
15355 && *str != NUL && match && end < regmatch.endp[0]))
15357 if (list_append_string(rettv->vval.v_list, str,
15358 (int)(end - str)) == FAIL)
15359 break;
15361 if (!match)
15362 break;
15363 /* Advance to just after the match. */
15364 if (regmatch.endp[0] > str)
15365 col = 0;
15366 else
15368 /* Don't get stuck at the same match. */
15369 #ifdef FEAT_MBYTE
15370 col = (*mb_ptr2len)(regmatch.endp[0]);
15371 #else
15372 col = 1;
15373 #endif
15375 str = regmatch.endp[0];
15378 vim_free(regmatch.regprog);
15381 p_cpo = save_cpo;
15385 * "str2nr()" function
15387 static void
15388 f_str2nr(argvars, rettv)
15389 typval_T *argvars;
15390 typval_T *rettv;
15392 int base = 10;
15393 char_u *p;
15394 long n;
15396 if (argvars[1].v_type != VAR_UNKNOWN)
15398 base = get_tv_number(&argvars[1]);
15399 if (base != 8 && base != 10 && base != 16)
15401 EMSG(_(e_invarg));
15402 return;
15406 p = skipwhite(get_tv_string(&argvars[0]));
15407 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
15408 rettv->vval.v_number = n;
15411 #ifdef HAVE_STRFTIME
15413 * "strftime({format}[, {time}])" function
15415 static void
15416 f_strftime(argvars, rettv)
15417 typval_T *argvars;
15418 typval_T *rettv;
15420 char_u result_buf[256];
15421 struct tm *curtime;
15422 time_t seconds;
15423 char_u *p;
15425 rettv->v_type = VAR_STRING;
15427 p = get_tv_string(&argvars[0]);
15428 if (argvars[1].v_type == VAR_UNKNOWN)
15429 seconds = time(NULL);
15430 else
15431 seconds = (time_t)get_tv_number(&argvars[1]);
15432 curtime = localtime(&seconds);
15433 /* MSVC returns NULL for an invalid value of seconds. */
15434 if (curtime == NULL)
15435 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
15436 else
15438 # ifdef FEAT_MBYTE
15439 vimconv_T conv;
15440 char_u *enc;
15442 conv.vc_type = CONV_NONE;
15443 enc = enc_locale();
15444 convert_setup(&conv, p_enc, enc);
15445 if (conv.vc_type != CONV_NONE)
15446 p = string_convert(&conv, p, NULL);
15447 # endif
15448 if (p != NULL)
15449 (void)strftime((char *)result_buf, sizeof(result_buf),
15450 (char *)p, curtime);
15451 else
15452 result_buf[0] = NUL;
15454 # ifdef FEAT_MBYTE
15455 if (conv.vc_type != CONV_NONE)
15456 vim_free(p);
15457 convert_setup(&conv, enc, p_enc);
15458 if (conv.vc_type != CONV_NONE)
15459 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
15460 else
15461 # endif
15462 rettv->vval.v_string = vim_strsave(result_buf);
15464 # ifdef FEAT_MBYTE
15465 /* Release conversion descriptors */
15466 convert_setup(&conv, NULL, NULL);
15467 vim_free(enc);
15468 # endif
15471 #endif
15474 * "stridx()" function
15476 static void
15477 f_stridx(argvars, rettv)
15478 typval_T *argvars;
15479 typval_T *rettv;
15481 char_u buf[NUMBUFLEN];
15482 char_u *needle;
15483 char_u *haystack;
15484 char_u *save_haystack;
15485 char_u *pos;
15486 int start_idx;
15488 needle = get_tv_string_chk(&argvars[1]);
15489 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
15490 rettv->vval.v_number = -1;
15491 if (needle == NULL || haystack == NULL)
15492 return; /* type error; errmsg already given */
15494 if (argvars[2].v_type != VAR_UNKNOWN)
15496 int error = FALSE;
15498 start_idx = get_tv_number_chk(&argvars[2], &error);
15499 if (error || start_idx >= (int)STRLEN(haystack))
15500 return;
15501 if (start_idx >= 0)
15502 haystack += start_idx;
15505 pos = (char_u *)strstr((char *)haystack, (char *)needle);
15506 if (pos != NULL)
15507 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
15511 * "string()" function
15513 static void
15514 f_string(argvars, rettv)
15515 typval_T *argvars;
15516 typval_T *rettv;
15518 char_u *tofree;
15519 char_u numbuf[NUMBUFLEN];
15521 rettv->v_type = VAR_STRING;
15522 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
15523 /* Make a copy if we have a value but it's not in allocate memory. */
15524 if (rettv->vval.v_string != NULL && tofree == NULL)
15525 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
15529 * "strlen()" function
15531 static void
15532 f_strlen(argvars, rettv)
15533 typval_T *argvars;
15534 typval_T *rettv;
15536 rettv->vval.v_number = (varnumber_T)(STRLEN(
15537 get_tv_string(&argvars[0])));
15541 * "strpart()" function
15543 static void
15544 f_strpart(argvars, rettv)
15545 typval_T *argvars;
15546 typval_T *rettv;
15548 char_u *p;
15549 int n;
15550 int len;
15551 int slen;
15552 int error = FALSE;
15554 p = get_tv_string(&argvars[0]);
15555 slen = (int)STRLEN(p);
15557 n = get_tv_number_chk(&argvars[1], &error);
15558 if (error)
15559 len = 0;
15560 else if (argvars[2].v_type != VAR_UNKNOWN)
15561 len = get_tv_number(&argvars[2]);
15562 else
15563 len = slen - n; /* default len: all bytes that are available. */
15566 * Only return the overlap between the specified part and the actual
15567 * string.
15569 if (n < 0)
15571 len += n;
15572 n = 0;
15574 else if (n > slen)
15575 n = slen;
15576 if (len < 0)
15577 len = 0;
15578 else if (n + len > slen)
15579 len = slen - n;
15581 rettv->v_type = VAR_STRING;
15582 rettv->vval.v_string = vim_strnsave(p + n, len);
15586 * "strridx()" function
15588 static void
15589 f_strridx(argvars, rettv)
15590 typval_T *argvars;
15591 typval_T *rettv;
15593 char_u buf[NUMBUFLEN];
15594 char_u *needle;
15595 char_u *haystack;
15596 char_u *rest;
15597 char_u *lastmatch = NULL;
15598 int haystack_len, end_idx;
15600 needle = get_tv_string_chk(&argvars[1]);
15601 haystack = get_tv_string_buf_chk(&argvars[0], buf);
15603 rettv->vval.v_number = -1;
15604 if (needle == NULL || haystack == NULL)
15605 return; /* type error; errmsg already given */
15607 haystack_len = (int)STRLEN(haystack);
15608 if (argvars[2].v_type != VAR_UNKNOWN)
15610 /* Third argument: upper limit for index */
15611 end_idx = get_tv_number_chk(&argvars[2], NULL);
15612 if (end_idx < 0)
15613 return; /* can never find a match */
15615 else
15616 end_idx = haystack_len;
15618 if (*needle == NUL)
15620 /* Empty string matches past the end. */
15621 lastmatch = haystack + end_idx;
15623 else
15625 for (rest = haystack; *rest != '\0'; ++rest)
15627 rest = (char_u *)strstr((char *)rest, (char *)needle);
15628 if (rest == NULL || rest > haystack + end_idx)
15629 break;
15630 lastmatch = rest;
15634 if (lastmatch == NULL)
15635 rettv->vval.v_number = -1;
15636 else
15637 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
15641 * "strtrans()" function
15643 static void
15644 f_strtrans(argvars, rettv)
15645 typval_T *argvars;
15646 typval_T *rettv;
15648 rettv->v_type = VAR_STRING;
15649 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
15653 * "submatch()" function
15655 static void
15656 f_submatch(argvars, rettv)
15657 typval_T *argvars;
15658 typval_T *rettv;
15660 rettv->v_type = VAR_STRING;
15661 rettv->vval.v_string =
15662 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
15666 * "substitute()" function
15668 static void
15669 f_substitute(argvars, rettv)
15670 typval_T *argvars;
15671 typval_T *rettv;
15673 char_u patbuf[NUMBUFLEN];
15674 char_u subbuf[NUMBUFLEN];
15675 char_u flagsbuf[NUMBUFLEN];
15677 char_u *str = get_tv_string_chk(&argvars[0]);
15678 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
15679 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
15680 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
15682 rettv->v_type = VAR_STRING;
15683 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
15684 rettv->vval.v_string = NULL;
15685 else
15686 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
15690 * "synID(lnum, col, trans)" function
15692 /*ARGSUSED*/
15693 static void
15694 f_synID(argvars, rettv)
15695 typval_T *argvars;
15696 typval_T *rettv;
15698 int id = 0;
15699 #ifdef FEAT_SYN_HL
15700 long lnum;
15701 long col;
15702 int trans;
15703 int transerr = FALSE;
15705 lnum = get_tv_lnum(argvars); /* -1 on type error */
15706 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
15707 trans = get_tv_number_chk(&argvars[2], &transerr);
15709 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
15710 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
15711 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL);
15712 #endif
15714 rettv->vval.v_number = id;
15718 * "synIDattr(id, what [, mode])" function
15720 /*ARGSUSED*/
15721 static void
15722 f_synIDattr(argvars, rettv)
15723 typval_T *argvars;
15724 typval_T *rettv;
15726 char_u *p = NULL;
15727 #ifdef FEAT_SYN_HL
15728 int id;
15729 char_u *what;
15730 char_u *mode;
15731 char_u modebuf[NUMBUFLEN];
15732 int modec;
15734 id = get_tv_number(&argvars[0]);
15735 what = get_tv_string(&argvars[1]);
15736 if (argvars[2].v_type != VAR_UNKNOWN)
15738 mode = get_tv_string_buf(&argvars[2], modebuf);
15739 modec = TOLOWER_ASC(mode[0]);
15740 if (modec != 't' && modec != 'c'
15741 #ifdef FEAT_GUI
15742 && modec != 'g'
15743 #endif
15745 modec = 0; /* replace invalid with current */
15747 else
15749 #ifdef FEAT_GUI
15750 if (gui.in_use)
15751 modec = 'g';
15752 else
15753 #endif
15754 if (t_colors > 1)
15755 modec = 'c';
15756 else
15757 modec = 't';
15761 switch (TOLOWER_ASC(what[0]))
15763 case 'b':
15764 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
15765 p = highlight_color(id, what, modec);
15766 else /* bold */
15767 p = highlight_has_attr(id, HL_BOLD, modec);
15768 break;
15770 case 'f': /* fg[#] */
15771 p = highlight_color(id, what, modec);
15772 break;
15774 case 'i':
15775 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
15776 p = highlight_has_attr(id, HL_INVERSE, modec);
15777 else /* italic */
15778 p = highlight_has_attr(id, HL_ITALIC, modec);
15779 break;
15781 case 'n': /* name */
15782 p = get_highlight_name(NULL, id - 1);
15783 break;
15785 case 'r': /* reverse */
15786 p = highlight_has_attr(id, HL_INVERSE, modec);
15787 break;
15789 case 's': /* standout */
15790 p = highlight_has_attr(id, HL_STANDOUT, modec);
15791 break;
15793 case 'u':
15794 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
15795 /* underline */
15796 p = highlight_has_attr(id, HL_UNDERLINE, modec);
15797 else
15798 /* undercurl */
15799 p = highlight_has_attr(id, HL_UNDERCURL, modec);
15800 break;
15803 if (p != NULL)
15804 p = vim_strsave(p);
15805 #endif
15806 rettv->v_type = VAR_STRING;
15807 rettv->vval.v_string = p;
15811 * "synIDtrans(id)" function
15813 /*ARGSUSED*/
15814 static void
15815 f_synIDtrans(argvars, rettv)
15816 typval_T *argvars;
15817 typval_T *rettv;
15819 int id;
15821 #ifdef FEAT_SYN_HL
15822 id = get_tv_number(&argvars[0]);
15824 if (id > 0)
15825 id = syn_get_final_id(id);
15826 else
15827 #endif
15828 id = 0;
15830 rettv->vval.v_number = id;
15834 * "system()" function
15836 static void
15837 f_system(argvars, rettv)
15838 typval_T *argvars;
15839 typval_T *rettv;
15841 char_u *res = NULL;
15842 char_u *p;
15843 char_u *infile = NULL;
15844 char_u buf[NUMBUFLEN];
15845 int err = FALSE;
15846 FILE *fd;
15848 if (check_restricted() || check_secure())
15849 return;
15851 if (argvars[1].v_type != VAR_UNKNOWN)
15854 * Write the string to a temp file, to be used for input of the shell
15855 * command.
15857 if ((infile = vim_tempname('i')) == NULL)
15859 EMSG(_(e_notmp));
15860 return;
15863 fd = mch_fopen((char *)infile, WRITEBIN);
15864 if (fd == NULL)
15866 EMSG2(_(e_notopen), infile);
15867 goto done;
15869 p = get_tv_string_buf_chk(&argvars[1], buf);
15870 if (p == NULL)
15872 fclose(fd);
15873 goto done; /* type error; errmsg already given */
15875 if (fwrite(p, STRLEN(p), 1, fd) != 1)
15876 err = TRUE;
15877 if (fclose(fd) != 0)
15878 err = TRUE;
15879 if (err)
15881 EMSG(_("E677: Error writing temp file"));
15882 goto done;
15886 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
15887 SHELL_SILENT | SHELL_COOKED);
15889 #ifdef USE_CR
15890 /* translate <CR> into <NL> */
15891 if (res != NULL)
15893 char_u *s;
15895 for (s = res; *s; ++s)
15897 if (*s == CAR)
15898 *s = NL;
15901 #else
15902 # ifdef USE_CRNL
15903 /* translate <CR><NL> into <NL> */
15904 if (res != NULL)
15906 char_u *s, *d;
15908 d = res;
15909 for (s = res; *s; ++s)
15911 if (s[0] == CAR && s[1] == NL)
15912 ++s;
15913 *d++ = *s;
15915 *d = NUL;
15917 # endif
15918 #endif
15920 done:
15921 if (infile != NULL)
15923 mch_remove(infile);
15924 vim_free(infile);
15926 rettv->v_type = VAR_STRING;
15927 rettv->vval.v_string = res;
15931 * "tabpagebuflist()" function
15933 /* ARGSUSED */
15934 static void
15935 f_tabpagebuflist(argvars, rettv)
15936 typval_T *argvars;
15937 typval_T *rettv;
15939 #ifndef FEAT_WINDOWS
15940 rettv->vval.v_number = 0;
15941 #else
15942 tabpage_T *tp;
15943 win_T *wp = NULL;
15945 if (argvars[0].v_type == VAR_UNKNOWN)
15946 wp = firstwin;
15947 else
15949 tp = find_tabpage((int)get_tv_number(&argvars[0]));
15950 if (tp != NULL)
15951 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
15953 if (wp == NULL)
15954 rettv->vval.v_number = 0;
15955 else
15957 if (rettv_list_alloc(rettv) == FAIL)
15958 rettv->vval.v_number = 0;
15959 else
15961 for (; wp != NULL; wp = wp->w_next)
15962 if (list_append_number(rettv->vval.v_list,
15963 wp->w_buffer->b_fnum) == FAIL)
15964 break;
15967 #endif
15972 * "tabpagenr()" function
15974 /* ARGSUSED */
15975 static void
15976 f_tabpagenr(argvars, rettv)
15977 typval_T *argvars;
15978 typval_T *rettv;
15980 int nr = 1;
15981 #ifdef FEAT_WINDOWS
15982 char_u *arg;
15984 if (argvars[0].v_type != VAR_UNKNOWN)
15986 arg = get_tv_string_chk(&argvars[0]);
15987 nr = 0;
15988 if (arg != NULL)
15990 if (STRCMP(arg, "$") == 0)
15991 nr = tabpage_index(NULL) - 1;
15992 else
15993 EMSG2(_(e_invexpr2), arg);
15996 else
15997 nr = tabpage_index(curtab);
15998 #endif
15999 rettv->vval.v_number = nr;
16003 #ifdef FEAT_WINDOWS
16004 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
16007 * Common code for tabpagewinnr() and winnr().
16009 static int
16010 get_winnr(tp, argvar)
16011 tabpage_T *tp;
16012 typval_T *argvar;
16014 win_T *twin;
16015 int nr = 1;
16016 win_T *wp;
16017 char_u *arg;
16019 twin = (tp == curtab) ? curwin : tp->tp_curwin;
16020 if (argvar->v_type != VAR_UNKNOWN)
16022 arg = get_tv_string_chk(argvar);
16023 if (arg == NULL)
16024 nr = 0; /* type error; errmsg already given */
16025 else if (STRCMP(arg, "$") == 0)
16026 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
16027 else if (STRCMP(arg, "#") == 0)
16029 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
16030 if (twin == NULL)
16031 nr = 0;
16033 else
16035 EMSG2(_(e_invexpr2), arg);
16036 nr = 0;
16040 if (nr > 0)
16041 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16042 wp != twin; wp = wp->w_next)
16044 if (wp == NULL)
16046 /* didn't find it in this tabpage */
16047 nr = 0;
16048 break;
16050 ++nr;
16052 return nr;
16054 #endif
16057 * "tabpagewinnr()" function
16059 /* ARGSUSED */
16060 static void
16061 f_tabpagewinnr(argvars, rettv)
16062 typval_T *argvars;
16063 typval_T *rettv;
16065 int nr = 1;
16066 #ifdef FEAT_WINDOWS
16067 tabpage_T *tp;
16069 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16070 if (tp == NULL)
16071 nr = 0;
16072 else
16073 nr = get_winnr(tp, &argvars[1]);
16074 #endif
16075 rettv->vval.v_number = nr;
16080 * "tagfiles()" function
16082 /*ARGSUSED*/
16083 static void
16084 f_tagfiles(argvars, rettv)
16085 typval_T *argvars;
16086 typval_T *rettv;
16088 char_u fname[MAXPATHL + 1];
16089 tagname_T tn;
16090 int first;
16092 if (rettv_list_alloc(rettv) == FAIL)
16094 rettv->vval.v_number = 0;
16095 return;
16098 for (first = TRUE; ; first = FALSE)
16099 if (get_tagfname(&tn, first, fname) == FAIL
16100 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
16101 break;
16102 tagname_free(&tn);
16106 * "taglist()" function
16108 static void
16109 f_taglist(argvars, rettv)
16110 typval_T *argvars;
16111 typval_T *rettv;
16113 char_u *tag_pattern;
16115 tag_pattern = get_tv_string(&argvars[0]);
16117 rettv->vval.v_number = FALSE;
16118 if (*tag_pattern == NUL)
16119 return;
16121 if (rettv_list_alloc(rettv) == OK)
16122 (void)get_tags(rettv->vval.v_list, tag_pattern);
16126 * "tempname()" function
16128 /*ARGSUSED*/
16129 static void
16130 f_tempname(argvars, rettv)
16131 typval_T *argvars;
16132 typval_T *rettv;
16134 static int x = 'A';
16136 rettv->v_type = VAR_STRING;
16137 rettv->vval.v_string = vim_tempname(x);
16139 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
16140 * names. Skip 'I' and 'O', they are used for shell redirection. */
16143 if (x == 'Z')
16144 x = '0';
16145 else if (x == '9')
16146 x = 'A';
16147 else
16149 #ifdef EBCDIC
16150 if (x == 'I')
16151 x = 'J';
16152 else if (x == 'R')
16153 x = 'S';
16154 else
16155 #endif
16156 ++x;
16158 } while (x == 'I' || x == 'O');
16162 * "test(list)" function: Just checking the walls...
16164 /*ARGSUSED*/
16165 static void
16166 f_test(argvars, rettv)
16167 typval_T *argvars;
16168 typval_T *rettv;
16170 /* Used for unit testing. Change the code below to your liking. */
16171 #if 0
16172 listitem_T *li;
16173 list_T *l;
16174 char_u *bad, *good;
16176 if (argvars[0].v_type != VAR_LIST)
16177 return;
16178 l = argvars[0].vval.v_list;
16179 if (l == NULL)
16180 return;
16181 li = l->lv_first;
16182 if (li == NULL)
16183 return;
16184 bad = get_tv_string(&li->li_tv);
16185 li = li->li_next;
16186 if (li == NULL)
16187 return;
16188 good = get_tv_string(&li->li_tv);
16189 rettv->vval.v_number = test_edit_score(bad, good);
16190 #endif
16194 * "tolower(string)" function
16196 static void
16197 f_tolower(argvars, rettv)
16198 typval_T *argvars;
16199 typval_T *rettv;
16201 char_u *p;
16203 p = vim_strsave(get_tv_string(&argvars[0]));
16204 rettv->v_type = VAR_STRING;
16205 rettv->vval.v_string = p;
16207 if (p != NULL)
16208 while (*p != NUL)
16210 #ifdef FEAT_MBYTE
16211 int l;
16213 if (enc_utf8)
16215 int c, lc;
16217 c = utf_ptr2char(p);
16218 lc = utf_tolower(c);
16219 l = utf_ptr2len(p);
16220 /* TODO: reallocate string when byte count changes. */
16221 if (utf_char2len(lc) == l)
16222 utf_char2bytes(lc, p);
16223 p += l;
16225 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
16226 p += l; /* skip multi-byte character */
16227 else
16228 #endif
16230 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
16231 ++p;
16237 * "toupper(string)" function
16239 static void
16240 f_toupper(argvars, rettv)
16241 typval_T *argvars;
16242 typval_T *rettv;
16244 rettv->v_type = VAR_STRING;
16245 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
16249 * "tr(string, fromstr, tostr)" function
16251 static void
16252 f_tr(argvars, rettv)
16253 typval_T *argvars;
16254 typval_T *rettv;
16256 char_u *instr;
16257 char_u *fromstr;
16258 char_u *tostr;
16259 char_u *p;
16260 #ifdef FEAT_MBYTE
16261 int inlen;
16262 int fromlen;
16263 int tolen;
16264 int idx;
16265 char_u *cpstr;
16266 int cplen;
16267 int first = TRUE;
16268 #endif
16269 char_u buf[NUMBUFLEN];
16270 char_u buf2[NUMBUFLEN];
16271 garray_T ga;
16273 instr = get_tv_string(&argvars[0]);
16274 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
16275 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
16277 /* Default return value: empty string. */
16278 rettv->v_type = VAR_STRING;
16279 rettv->vval.v_string = NULL;
16280 if (fromstr == NULL || tostr == NULL)
16281 return; /* type error; errmsg already given */
16282 ga_init2(&ga, (int)sizeof(char), 80);
16284 #ifdef FEAT_MBYTE
16285 if (!has_mbyte)
16286 #endif
16287 /* not multi-byte: fromstr and tostr must be the same length */
16288 if (STRLEN(fromstr) != STRLEN(tostr))
16290 #ifdef FEAT_MBYTE
16291 error:
16292 #endif
16293 EMSG2(_(e_invarg2), fromstr);
16294 ga_clear(&ga);
16295 return;
16298 /* fromstr and tostr have to contain the same number of chars */
16299 while (*instr != NUL)
16301 #ifdef FEAT_MBYTE
16302 if (has_mbyte)
16304 inlen = (*mb_ptr2len)(instr);
16305 cpstr = instr;
16306 cplen = inlen;
16307 idx = 0;
16308 for (p = fromstr; *p != NUL; p += fromlen)
16310 fromlen = (*mb_ptr2len)(p);
16311 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
16313 for (p = tostr; *p != NUL; p += tolen)
16315 tolen = (*mb_ptr2len)(p);
16316 if (idx-- == 0)
16318 cplen = tolen;
16319 cpstr = p;
16320 break;
16323 if (*p == NUL) /* tostr is shorter than fromstr */
16324 goto error;
16325 break;
16327 ++idx;
16330 if (first && cpstr == instr)
16332 /* Check that fromstr and tostr have the same number of
16333 * (multi-byte) characters. Done only once when a character
16334 * of instr doesn't appear in fromstr. */
16335 first = FALSE;
16336 for (p = tostr; *p != NUL; p += tolen)
16338 tolen = (*mb_ptr2len)(p);
16339 --idx;
16341 if (idx != 0)
16342 goto error;
16345 ga_grow(&ga, cplen);
16346 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
16347 ga.ga_len += cplen;
16349 instr += inlen;
16351 else
16352 #endif
16354 /* When not using multi-byte chars we can do it faster. */
16355 p = vim_strchr(fromstr, *instr);
16356 if (p != NULL)
16357 ga_append(&ga, tostr[p - fromstr]);
16358 else
16359 ga_append(&ga, *instr);
16360 ++instr;
16364 /* add a terminating NUL */
16365 ga_grow(&ga, 1);
16366 ga_append(&ga, NUL);
16368 rettv->vval.v_string = ga.ga_data;
16372 * "type(expr)" function
16374 static void
16375 f_type(argvars, rettv)
16376 typval_T *argvars;
16377 typval_T *rettv;
16379 int n;
16381 switch (argvars[0].v_type)
16383 case VAR_NUMBER: n = 0; break;
16384 case VAR_STRING: n = 1; break;
16385 case VAR_FUNC: n = 2; break;
16386 case VAR_LIST: n = 3; break;
16387 case VAR_DICT: n = 4; break;
16388 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
16390 rettv->vval.v_number = n;
16394 * "values(dict)" function
16396 static void
16397 f_values(argvars, rettv)
16398 typval_T *argvars;
16399 typval_T *rettv;
16401 dict_list(argvars, rettv, 1);
16405 * "virtcol(string)" function
16407 static void
16408 f_virtcol(argvars, rettv)
16409 typval_T *argvars;
16410 typval_T *rettv;
16412 colnr_T vcol = 0;
16413 pos_T *fp;
16414 int fnum = curbuf->b_fnum;
16416 fp = var2fpos(&argvars[0], FALSE, &fnum);
16417 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
16418 && fnum == curbuf->b_fnum)
16420 getvvcol(curwin, fp, NULL, NULL, &vcol);
16421 ++vcol;
16424 rettv->vval.v_number = vcol;
16428 * "visualmode()" function
16430 /*ARGSUSED*/
16431 static void
16432 f_visualmode(argvars, rettv)
16433 typval_T *argvars;
16434 typval_T *rettv;
16436 #ifdef FEAT_VISUAL
16437 char_u str[2];
16439 rettv->v_type = VAR_STRING;
16440 str[0] = curbuf->b_visual_mode_eval;
16441 str[1] = NUL;
16442 rettv->vval.v_string = vim_strsave(str);
16444 /* A non-zero number or non-empty string argument: reset mode. */
16445 if ((argvars[0].v_type == VAR_NUMBER
16446 && argvars[0].vval.v_number != 0)
16447 || (argvars[0].v_type == VAR_STRING
16448 && *get_tv_string(&argvars[0]) != NUL))
16449 curbuf->b_visual_mode_eval = NUL;
16450 #else
16451 rettv->vval.v_number = 0; /* return anything, it won't work anyway */
16452 #endif
16456 * "winbufnr(nr)" function
16458 static void
16459 f_winbufnr(argvars, rettv)
16460 typval_T *argvars;
16461 typval_T *rettv;
16463 win_T *wp;
16465 wp = find_win_by_nr(&argvars[0], NULL);
16466 if (wp == NULL)
16467 rettv->vval.v_number = -1;
16468 else
16469 rettv->vval.v_number = wp->w_buffer->b_fnum;
16473 * "wincol()" function
16475 /*ARGSUSED*/
16476 static void
16477 f_wincol(argvars, rettv)
16478 typval_T *argvars;
16479 typval_T *rettv;
16481 validate_cursor();
16482 rettv->vval.v_number = curwin->w_wcol + 1;
16486 * "winheight(nr)" function
16488 static void
16489 f_winheight(argvars, rettv)
16490 typval_T *argvars;
16491 typval_T *rettv;
16493 win_T *wp;
16495 wp = find_win_by_nr(&argvars[0], NULL);
16496 if (wp == NULL)
16497 rettv->vval.v_number = -1;
16498 else
16499 rettv->vval.v_number = wp->w_height;
16503 * "winline()" function
16505 /*ARGSUSED*/
16506 static void
16507 f_winline(argvars, rettv)
16508 typval_T *argvars;
16509 typval_T *rettv;
16511 validate_cursor();
16512 rettv->vval.v_number = curwin->w_wrow + 1;
16516 * "winnr()" function
16518 /* ARGSUSED */
16519 static void
16520 f_winnr(argvars, rettv)
16521 typval_T *argvars;
16522 typval_T *rettv;
16524 int nr = 1;
16526 #ifdef FEAT_WINDOWS
16527 nr = get_winnr(curtab, &argvars[0]);
16528 #endif
16529 rettv->vval.v_number = nr;
16533 * "winrestcmd()" function
16535 /* ARGSUSED */
16536 static void
16537 f_winrestcmd(argvars, rettv)
16538 typval_T *argvars;
16539 typval_T *rettv;
16541 #ifdef FEAT_WINDOWS
16542 win_T *wp;
16543 int winnr = 1;
16544 garray_T ga;
16545 char_u buf[50];
16547 ga_init2(&ga, (int)sizeof(char), 70);
16548 for (wp = firstwin; wp != NULL; wp = wp->w_next)
16550 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
16551 ga_concat(&ga, buf);
16552 # ifdef FEAT_VERTSPLIT
16553 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
16554 ga_concat(&ga, buf);
16555 # endif
16556 ++winnr;
16558 ga_append(&ga, NUL);
16560 rettv->vval.v_string = ga.ga_data;
16561 #else
16562 rettv->vval.v_string = NULL;
16563 #endif
16564 rettv->v_type = VAR_STRING;
16568 * "winrestview()" function
16570 /* ARGSUSED */
16571 static void
16572 f_winrestview(argvars, rettv)
16573 typval_T *argvars;
16574 typval_T *rettv;
16576 dict_T *dict;
16578 if (argvars[0].v_type != VAR_DICT
16579 || (dict = argvars[0].vval.v_dict) == NULL)
16580 EMSG(_(e_invarg));
16581 else
16583 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
16584 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
16585 #ifdef FEAT_VIRTUALEDIT
16586 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
16587 #endif
16588 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
16589 curwin->w_set_curswant = FALSE;
16591 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
16592 #ifdef FEAT_DIFF
16593 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
16594 #endif
16595 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
16596 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
16598 check_cursor();
16599 changed_cline_bef_curs();
16600 invalidate_botline();
16601 redraw_later(VALID);
16603 if (curwin->w_topline == 0)
16604 curwin->w_topline = 1;
16605 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
16606 curwin->w_topline = curbuf->b_ml.ml_line_count;
16607 #ifdef FEAT_DIFF
16608 check_topfill(curwin, TRUE);
16609 #endif
16614 * "winsaveview()" function
16616 /* ARGSUSED */
16617 static void
16618 f_winsaveview(argvars, rettv)
16619 typval_T *argvars;
16620 typval_T *rettv;
16622 dict_T *dict;
16624 dict = dict_alloc();
16625 if (dict == NULL)
16626 return;
16627 rettv->v_type = VAR_DICT;
16628 rettv->vval.v_dict = dict;
16629 ++dict->dv_refcount;
16631 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
16632 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
16633 #ifdef FEAT_VIRTUALEDIT
16634 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
16635 #endif
16636 update_curswant();
16637 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
16639 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
16640 #ifdef FEAT_DIFF
16641 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
16642 #endif
16643 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
16644 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
16648 * "winwidth(nr)" function
16650 static void
16651 f_winwidth(argvars, rettv)
16652 typval_T *argvars;
16653 typval_T *rettv;
16655 win_T *wp;
16657 wp = find_win_by_nr(&argvars[0], NULL);
16658 if (wp == NULL)
16659 rettv->vval.v_number = -1;
16660 else
16661 #ifdef FEAT_VERTSPLIT
16662 rettv->vval.v_number = wp->w_width;
16663 #else
16664 rettv->vval.v_number = Columns;
16665 #endif
16669 * "writefile()" function
16671 static void
16672 f_writefile(argvars, rettv)
16673 typval_T *argvars;
16674 typval_T *rettv;
16676 int binary = FALSE;
16677 char_u *fname;
16678 FILE *fd;
16679 listitem_T *li;
16680 char_u *s;
16681 int ret = 0;
16682 int c;
16684 if (check_restricted() || check_secure())
16685 return;
16687 if (argvars[0].v_type != VAR_LIST)
16689 EMSG2(_(e_listarg), "writefile()");
16690 return;
16692 if (argvars[0].vval.v_list == NULL)
16693 return;
16695 if (argvars[2].v_type != VAR_UNKNOWN
16696 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
16697 binary = TRUE;
16699 /* Always open the file in binary mode, library functions have a mind of
16700 * their own about CR-LF conversion. */
16701 fname = get_tv_string(&argvars[1]);
16702 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
16704 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
16705 ret = -1;
16707 else
16709 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
16710 li = li->li_next)
16712 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
16714 if (*s == '\n')
16715 c = putc(NUL, fd);
16716 else
16717 c = putc(*s, fd);
16718 if (c == EOF)
16720 ret = -1;
16721 break;
16724 if (!binary || li->li_next != NULL)
16725 if (putc('\n', fd) == EOF)
16727 ret = -1;
16728 break;
16730 if (ret < 0)
16732 EMSG(_(e_write));
16733 break;
16736 fclose(fd);
16739 rettv->vval.v_number = ret;
16743 * Translate a String variable into a position.
16744 * Returns NULL when there is an error.
16746 static pos_T *
16747 var2fpos(varp, dollar_lnum, fnum)
16748 typval_T *varp;
16749 int dollar_lnum; /* TRUE when $ is last line */
16750 int *fnum; /* set to fnum for '0, 'A, etc. */
16752 char_u *name;
16753 static pos_T pos;
16754 pos_T *pp;
16756 /* Argument can be [lnum, col, coladd]. */
16757 if (varp->v_type == VAR_LIST)
16759 list_T *l;
16760 int len;
16761 int error = FALSE;
16762 listitem_T *li;
16764 l = varp->vval.v_list;
16765 if (l == NULL)
16766 return NULL;
16768 /* Get the line number */
16769 pos.lnum = list_find_nr(l, 0L, &error);
16770 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
16771 return NULL; /* invalid line number */
16773 /* Get the column number */
16774 pos.col = list_find_nr(l, 1L, &error);
16775 if (error)
16776 return NULL;
16777 len = (long)STRLEN(ml_get(pos.lnum));
16779 /* We accept "$" for the column number: last column. */
16780 li = list_find(l, 1L);
16781 if (li != NULL && li->li_tv.v_type == VAR_STRING
16782 && li->li_tv.vval.v_string != NULL
16783 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
16784 pos.col = len + 1;
16786 /* Accept a position up to the NUL after the line. */
16787 if (pos.col == 0 || (int)pos.col > len + 1)
16788 return NULL; /* invalid column number */
16789 --pos.col;
16791 #ifdef FEAT_VIRTUALEDIT
16792 /* Get the virtual offset. Defaults to zero. */
16793 pos.coladd = list_find_nr(l, 2L, &error);
16794 if (error)
16795 pos.coladd = 0;
16796 #endif
16798 return &pos;
16801 name = get_tv_string_chk(varp);
16802 if (name == NULL)
16803 return NULL;
16804 if (name[0] == '.') /* cursor */
16805 return &curwin->w_cursor;
16806 if (name[0] == '\'') /* mark */
16808 pp = getmark_fnum(name[1], FALSE, fnum);
16809 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
16810 return NULL;
16811 return pp;
16814 #ifdef FEAT_VIRTUALEDIT
16815 pos.coladd = 0;
16816 #endif
16818 if (name[0] == 'w' && dollar_lnum)
16820 pos.col = 0;
16821 if (name[1] == '0') /* "w0": first visible line */
16823 update_topline();
16824 pos.lnum = curwin->w_topline;
16825 return &pos;
16827 else if (name[1] == '$') /* "w$": last visible line */
16829 validate_botline();
16830 pos.lnum = curwin->w_botline - 1;
16831 return &pos;
16834 else if (name[0] == '$') /* last column or line */
16836 if (dollar_lnum)
16838 pos.lnum = curbuf->b_ml.ml_line_count;
16839 pos.col = 0;
16841 else
16843 pos.lnum = curwin->w_cursor.lnum;
16844 pos.col = (colnr_T)STRLEN(ml_get_curline());
16846 return &pos;
16848 return NULL;
16852 * Convert list in "arg" into a position and optional file number.
16853 * When "fnump" is NULL there is no file number, only 3 items.
16854 * Note that the column is passed on as-is, the caller may want to decrement
16855 * it to use 1 for the first column.
16856 * Return FAIL when conversion is not possible, doesn't check the position for
16857 * validity.
16859 static int
16860 list2fpos(arg, posp, fnump)
16861 typval_T *arg;
16862 pos_T *posp;
16863 int *fnump;
16865 list_T *l = arg->vval.v_list;
16866 long i = 0;
16867 long n;
16869 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
16870 * when "fnump" isn't NULL and "coladd" is optional. */
16871 if (arg->v_type != VAR_LIST
16872 || l == NULL
16873 || l->lv_len < (fnump == NULL ? 2 : 3)
16874 || l->lv_len > (fnump == NULL ? 3 : 4))
16875 return FAIL;
16877 if (fnump != NULL)
16879 n = list_find_nr(l, i++, NULL); /* fnum */
16880 if (n < 0)
16881 return FAIL;
16882 if (n == 0)
16883 n = curbuf->b_fnum; /* current buffer */
16884 *fnump = n;
16887 n = list_find_nr(l, i++, NULL); /* lnum */
16888 if (n < 0)
16889 return FAIL;
16890 posp->lnum = n;
16892 n = list_find_nr(l, i++, NULL); /* col */
16893 if (n < 0)
16894 return FAIL;
16895 posp->col = n;
16897 #ifdef FEAT_VIRTUALEDIT
16898 n = list_find_nr(l, i, NULL);
16899 if (n < 0)
16900 posp->coladd = 0;
16901 else
16902 posp->coladd = n;
16903 #endif
16905 return OK;
16909 * Get the length of an environment variable name.
16910 * Advance "arg" to the first character after the name.
16911 * Return 0 for error.
16913 static int
16914 get_env_len(arg)
16915 char_u **arg;
16917 char_u *p;
16918 int len;
16920 for (p = *arg; vim_isIDc(*p); ++p)
16922 if (p == *arg) /* no name found */
16923 return 0;
16925 len = (int)(p - *arg);
16926 *arg = p;
16927 return len;
16931 * Get the length of the name of a function or internal variable.
16932 * "arg" is advanced to the first non-white character after the name.
16933 * Return 0 if something is wrong.
16935 static int
16936 get_id_len(arg)
16937 char_u **arg;
16939 char_u *p;
16940 int len;
16942 /* Find the end of the name. */
16943 for (p = *arg; eval_isnamec(*p); ++p)
16945 if (p == *arg) /* no name found */
16946 return 0;
16948 len = (int)(p - *arg);
16949 *arg = skipwhite(p);
16951 return len;
16955 * Get the length of the name of a variable or function.
16956 * Only the name is recognized, does not handle ".key" or "[idx]".
16957 * "arg" is advanced to the first non-white character after the name.
16958 * Return -1 if curly braces expansion failed.
16959 * Return 0 if something else is wrong.
16960 * If the name contains 'magic' {}'s, expand them and return the
16961 * expanded name in an allocated string via 'alias' - caller must free.
16963 static int
16964 get_name_len(arg, alias, evaluate, verbose)
16965 char_u **arg;
16966 char_u **alias;
16967 int evaluate;
16968 int verbose;
16970 int len;
16971 char_u *p;
16972 char_u *expr_start;
16973 char_u *expr_end;
16975 *alias = NULL; /* default to no alias */
16977 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
16978 && (*arg)[2] == (int)KE_SNR)
16980 /* hard coded <SNR>, already translated */
16981 *arg += 3;
16982 return get_id_len(arg) + 3;
16984 len = eval_fname_script(*arg);
16985 if (len > 0)
16987 /* literal "<SID>", "s:" or "<SNR>" */
16988 *arg += len;
16992 * Find the end of the name; check for {} construction.
16994 p = find_name_end(*arg, &expr_start, &expr_end,
16995 len > 0 ? 0 : FNE_CHECK_START);
16996 if (expr_start != NULL)
16998 char_u *temp_string;
17000 if (!evaluate)
17002 len += (int)(p - *arg);
17003 *arg = skipwhite(p);
17004 return len;
17008 * Include any <SID> etc in the expanded string:
17009 * Thus the -len here.
17011 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
17012 if (temp_string == NULL)
17013 return -1;
17014 *alias = temp_string;
17015 *arg = skipwhite(p);
17016 return (int)STRLEN(temp_string);
17019 len += get_id_len(arg);
17020 if (len == 0 && verbose)
17021 EMSG2(_(e_invexpr2), *arg);
17023 return len;
17027 * Find the end of a variable or function name, taking care of magic braces.
17028 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
17029 * start and end of the first magic braces item.
17030 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
17031 * Return a pointer to just after the name. Equal to "arg" if there is no
17032 * valid name.
17034 static char_u *
17035 find_name_end(arg, expr_start, expr_end, flags)
17036 char_u *arg;
17037 char_u **expr_start;
17038 char_u **expr_end;
17039 int flags;
17041 int mb_nest = 0;
17042 int br_nest = 0;
17043 char_u *p;
17045 if (expr_start != NULL)
17047 *expr_start = NULL;
17048 *expr_end = NULL;
17051 /* Quick check for valid starting character. */
17052 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
17053 return arg;
17055 for (p = arg; *p != NUL
17056 && (eval_isnamec(*p)
17057 || *p == '{'
17058 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
17059 || mb_nest != 0
17060 || br_nest != 0); mb_ptr_adv(p))
17062 if (*p == '\'')
17064 /* skip over 'string' to avoid counting [ and ] inside it. */
17065 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
17067 if (*p == NUL)
17068 break;
17070 else if (*p == '"')
17072 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
17073 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
17074 if (*p == '\\' && p[1] != NUL)
17075 ++p;
17076 if (*p == NUL)
17077 break;
17080 if (mb_nest == 0)
17082 if (*p == '[')
17083 ++br_nest;
17084 else if (*p == ']')
17085 --br_nest;
17088 if (br_nest == 0)
17090 if (*p == '{')
17092 mb_nest++;
17093 if (expr_start != NULL && *expr_start == NULL)
17094 *expr_start = p;
17096 else if (*p == '}')
17098 mb_nest--;
17099 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
17100 *expr_end = p;
17105 return p;
17109 * Expands out the 'magic' {}'s in a variable/function name.
17110 * Note that this can call itself recursively, to deal with
17111 * constructs like foo{bar}{baz}{bam}
17112 * The four pointer arguments point to "foo{expre}ss{ion}bar"
17113 * "in_start" ^
17114 * "expr_start" ^
17115 * "expr_end" ^
17116 * "in_end" ^
17118 * Returns a new allocated string, which the caller must free.
17119 * Returns NULL for failure.
17121 static char_u *
17122 make_expanded_name(in_start, expr_start, expr_end, in_end)
17123 char_u *in_start;
17124 char_u *expr_start;
17125 char_u *expr_end;
17126 char_u *in_end;
17128 char_u c1;
17129 char_u *retval = NULL;
17130 char_u *temp_result;
17131 char_u *nextcmd = NULL;
17133 if (expr_end == NULL || in_end == NULL)
17134 return NULL;
17135 *expr_start = NUL;
17136 *expr_end = NUL;
17137 c1 = *in_end;
17138 *in_end = NUL;
17140 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
17141 if (temp_result != NULL && nextcmd == NULL)
17143 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
17144 + (in_end - expr_end) + 1));
17145 if (retval != NULL)
17147 STRCPY(retval, in_start);
17148 STRCAT(retval, temp_result);
17149 STRCAT(retval, expr_end + 1);
17152 vim_free(temp_result);
17154 *in_end = c1; /* put char back for error messages */
17155 *expr_start = '{';
17156 *expr_end = '}';
17158 if (retval != NULL)
17160 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
17161 if (expr_start != NULL)
17163 /* Further expansion! */
17164 temp_result = make_expanded_name(retval, expr_start,
17165 expr_end, temp_result);
17166 vim_free(retval);
17167 retval = temp_result;
17171 return retval;
17175 * Return TRUE if character "c" can be used in a variable or function name.
17176 * Does not include '{' or '}' for magic braces.
17178 static int
17179 eval_isnamec(c)
17180 int c;
17182 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
17186 * Return TRUE if character "c" can be used as the first character in a
17187 * variable or function name (excluding '{' and '}').
17189 static int
17190 eval_isnamec1(c)
17191 int c;
17193 return (ASCII_ISALPHA(c) || c == '_');
17197 * Set number v: variable to "val".
17199 void
17200 set_vim_var_nr(idx, val)
17201 int idx;
17202 long val;
17204 vimvars[idx].vv_nr = val;
17208 * Get number v: variable value.
17210 long
17211 get_vim_var_nr(idx)
17212 int idx;
17214 return vimvars[idx].vv_nr;
17217 #if defined(FEAT_AUTOCMD) || defined(PROTO)
17219 * Get string v: variable value. Uses a static buffer, can only be used once.
17221 char_u *
17222 get_vim_var_str(idx)
17223 int idx;
17225 return get_tv_string(&vimvars[idx].vv_tv);
17227 #endif
17230 * Set v:count, v:count1 and v:prevcount.
17232 void
17233 set_vcount(count, count1)
17234 long count;
17235 long count1;
17237 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
17238 vimvars[VV_COUNT].vv_nr = count;
17239 vimvars[VV_COUNT1].vv_nr = count1;
17243 * Set string v: variable to a copy of "val".
17245 void
17246 set_vim_var_string(idx, val, len)
17247 int idx;
17248 char_u *val;
17249 int len; /* length of "val" to use or -1 (whole string) */
17251 /* Need to do this (at least) once, since we can't initialize a union.
17252 * Will always be invoked when "v:progname" is set. */
17253 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
17255 vim_free(vimvars[idx].vv_str);
17256 if (val == NULL)
17257 vimvars[idx].vv_str = NULL;
17258 else if (len == -1)
17259 vimvars[idx].vv_str = vim_strsave(val);
17260 else
17261 vimvars[idx].vv_str = vim_strnsave(val, len);
17265 * Set v:register if needed.
17267 void
17268 set_reg_var(c)
17269 int c;
17271 char_u regname;
17273 if (c == 0 || c == ' ')
17274 regname = '"';
17275 else
17276 regname = c;
17277 /* Avoid free/alloc when the value is already right. */
17278 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
17279 set_vim_var_string(VV_REG, &regname, 1);
17283 * Get or set v:exception. If "oldval" == NULL, return the current value.
17284 * Otherwise, restore the value to "oldval" and return NULL.
17285 * Must always be called in pairs to save and restore v:exception! Does not
17286 * take care of memory allocations.
17288 char_u *
17289 v_exception(oldval)
17290 char_u *oldval;
17292 if (oldval == NULL)
17293 return vimvars[VV_EXCEPTION].vv_str;
17295 vimvars[VV_EXCEPTION].vv_str = oldval;
17296 return NULL;
17300 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
17301 * Otherwise, restore the value to "oldval" and return NULL.
17302 * Must always be called in pairs to save and restore v:throwpoint! Does not
17303 * take care of memory allocations.
17305 char_u *
17306 v_throwpoint(oldval)
17307 char_u *oldval;
17309 if (oldval == NULL)
17310 return vimvars[VV_THROWPOINT].vv_str;
17312 vimvars[VV_THROWPOINT].vv_str = oldval;
17313 return NULL;
17316 #if defined(FEAT_AUTOCMD) || defined(PROTO)
17318 * Set v:cmdarg.
17319 * If "eap" != NULL, use "eap" to generate the value and return the old value.
17320 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
17321 * Must always be called in pairs!
17323 char_u *
17324 set_cmdarg(eap, oldarg)
17325 exarg_T *eap;
17326 char_u *oldarg;
17328 char_u *oldval;
17329 char_u *newval;
17330 unsigned len;
17332 oldval = vimvars[VV_CMDARG].vv_str;
17333 if (eap == NULL)
17335 vim_free(oldval);
17336 vimvars[VV_CMDARG].vv_str = oldarg;
17337 return NULL;
17340 if (eap->force_bin == FORCE_BIN)
17341 len = 6;
17342 else if (eap->force_bin == FORCE_NOBIN)
17343 len = 8;
17344 else
17345 len = 0;
17347 if (eap->read_edit)
17348 len += 7;
17350 if (eap->force_ff != 0)
17351 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
17352 # ifdef FEAT_MBYTE
17353 if (eap->force_enc != 0)
17354 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
17355 if (eap->bad_char != 0)
17356 len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
17357 # endif
17359 newval = alloc(len + 1);
17360 if (newval == NULL)
17361 return NULL;
17363 if (eap->force_bin == FORCE_BIN)
17364 sprintf((char *)newval, " ++bin");
17365 else if (eap->force_bin == FORCE_NOBIN)
17366 sprintf((char *)newval, " ++nobin");
17367 else
17368 *newval = NUL;
17370 if (eap->read_edit)
17371 STRCAT(newval, " ++edit");
17373 if (eap->force_ff != 0)
17374 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
17375 eap->cmd + eap->force_ff);
17376 # ifdef FEAT_MBYTE
17377 if (eap->force_enc != 0)
17378 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
17379 eap->cmd + eap->force_enc);
17380 if (eap->bad_char != 0)
17381 sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
17382 eap->cmd + eap->bad_char);
17383 # endif
17384 vimvars[VV_CMDARG].vv_str = newval;
17385 return oldval;
17387 #endif
17390 * Get the value of internal variable "name".
17391 * Return OK or FAIL.
17393 static int
17394 get_var_tv(name, len, rettv, verbose)
17395 char_u *name;
17396 int len; /* length of "name" */
17397 typval_T *rettv; /* NULL when only checking existence */
17398 int verbose; /* may give error message */
17400 int ret = OK;
17401 typval_T *tv = NULL;
17402 typval_T atv;
17403 dictitem_T *v;
17404 int cc;
17406 /* truncate the name, so that we can use strcmp() */
17407 cc = name[len];
17408 name[len] = NUL;
17411 * Check for "b:changedtick".
17413 if (STRCMP(name, "b:changedtick") == 0)
17415 atv.v_type = VAR_NUMBER;
17416 atv.vval.v_number = curbuf->b_changedtick;
17417 tv = &atv;
17421 * Check for user-defined variables.
17423 else
17425 v = find_var(name, NULL);
17426 if (v != NULL)
17427 tv = &v->di_tv;
17430 if (tv == NULL)
17432 if (rettv != NULL && verbose)
17433 EMSG2(_(e_undefvar), name);
17434 ret = FAIL;
17436 else if (rettv != NULL)
17437 copy_tv(tv, rettv);
17439 name[len] = cc;
17441 return ret;
17445 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
17446 * Also handle function call with Funcref variable: func(expr)
17447 * Can all be combined: dict.func(expr)[idx]['func'](expr)
17449 static int
17450 handle_subscript(arg, rettv, evaluate, verbose)
17451 char_u **arg;
17452 typval_T *rettv;
17453 int evaluate; /* do more than finding the end */
17454 int verbose; /* give error messages */
17456 int ret = OK;
17457 dict_T *selfdict = NULL;
17458 char_u *s;
17459 int len;
17460 typval_T functv;
17462 while (ret == OK
17463 && (**arg == '['
17464 || (**arg == '.' && rettv->v_type == VAR_DICT)
17465 || (**arg == '(' && rettv->v_type == VAR_FUNC))
17466 && !vim_iswhite(*(*arg - 1)))
17468 if (**arg == '(')
17470 /* need to copy the funcref so that we can clear rettv */
17471 functv = *rettv;
17472 rettv->v_type = VAR_UNKNOWN;
17474 /* Invoke the function. Recursive! */
17475 s = functv.vval.v_string;
17476 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
17477 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
17478 &len, evaluate, selfdict);
17480 /* Clear the funcref afterwards, so that deleting it while
17481 * evaluating the arguments is possible (see test55). */
17482 clear_tv(&functv);
17484 /* Stop the expression evaluation when immediately aborting on
17485 * error, or when an interrupt occurred or an exception was thrown
17486 * but not caught. */
17487 if (aborting())
17489 if (ret == OK)
17490 clear_tv(rettv);
17491 ret = FAIL;
17493 dict_unref(selfdict);
17494 selfdict = NULL;
17496 else /* **arg == '[' || **arg == '.' */
17498 dict_unref(selfdict);
17499 if (rettv->v_type == VAR_DICT)
17501 selfdict = rettv->vval.v_dict;
17502 if (selfdict != NULL)
17503 ++selfdict->dv_refcount;
17505 else
17506 selfdict = NULL;
17507 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
17509 clear_tv(rettv);
17510 ret = FAIL;
17514 dict_unref(selfdict);
17515 return ret;
17519 * Allocate memory for a variable type-value, and make it emtpy (0 or NULL
17520 * value).
17522 static typval_T *
17523 alloc_tv()
17525 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
17529 * Allocate memory for a variable type-value, and assign a string to it.
17530 * The string "s" must have been allocated, it is consumed.
17531 * Return NULL for out of memory, the variable otherwise.
17533 static typval_T *
17534 alloc_string_tv(s)
17535 char_u *s;
17537 typval_T *rettv;
17539 rettv = alloc_tv();
17540 if (rettv != NULL)
17542 rettv->v_type = VAR_STRING;
17543 rettv->vval.v_string = s;
17545 else
17546 vim_free(s);
17547 return rettv;
17551 * Free the memory for a variable type-value.
17553 void
17554 free_tv(varp)
17555 typval_T *varp;
17557 if (varp != NULL)
17559 switch (varp->v_type)
17561 case VAR_FUNC:
17562 func_unref(varp->vval.v_string);
17563 /*FALLTHROUGH*/
17564 case VAR_STRING:
17565 vim_free(varp->vval.v_string);
17566 break;
17567 case VAR_LIST:
17568 list_unref(varp->vval.v_list);
17569 break;
17570 case VAR_DICT:
17571 dict_unref(varp->vval.v_dict);
17572 break;
17573 case VAR_NUMBER:
17574 case VAR_UNKNOWN:
17575 break;
17576 default:
17577 EMSG2(_(e_intern2), "free_tv()");
17578 break;
17580 vim_free(varp);
17585 * Free the memory for a variable value and set the value to NULL or 0.
17587 void
17588 clear_tv(varp)
17589 typval_T *varp;
17591 if (varp != NULL)
17593 switch (varp->v_type)
17595 case VAR_FUNC:
17596 func_unref(varp->vval.v_string);
17597 /*FALLTHROUGH*/
17598 case VAR_STRING:
17599 vim_free(varp->vval.v_string);
17600 varp->vval.v_string = NULL;
17601 break;
17602 case VAR_LIST:
17603 list_unref(varp->vval.v_list);
17604 varp->vval.v_list = NULL;
17605 break;
17606 case VAR_DICT:
17607 dict_unref(varp->vval.v_dict);
17608 varp->vval.v_dict = NULL;
17609 break;
17610 case VAR_NUMBER:
17611 varp->vval.v_number = 0;
17612 break;
17613 case VAR_UNKNOWN:
17614 break;
17615 default:
17616 EMSG2(_(e_intern2), "clear_tv()");
17618 varp->v_lock = 0;
17623 * Set the value of a variable to NULL without freeing items.
17625 static void
17626 init_tv(varp)
17627 typval_T *varp;
17629 if (varp != NULL)
17630 vim_memset(varp, 0, sizeof(typval_T));
17634 * Get the number value of a variable.
17635 * If it is a String variable, uses vim_str2nr().
17636 * For incompatible types, return 0.
17637 * get_tv_number_chk() is similar to get_tv_number(), but informs the
17638 * caller of incompatible types: it sets *denote to TRUE if "denote"
17639 * is not NULL or returns -1 otherwise.
17641 static long
17642 get_tv_number(varp)
17643 typval_T *varp;
17645 int error = FALSE;
17647 return get_tv_number_chk(varp, &error); /* return 0L on error */
17650 long
17651 get_tv_number_chk(varp, denote)
17652 typval_T *varp;
17653 int *denote;
17655 long n = 0L;
17657 switch (varp->v_type)
17659 case VAR_NUMBER:
17660 return (long)(varp->vval.v_number);
17661 case VAR_FUNC:
17662 EMSG(_("E703: Using a Funcref as a number"));
17663 break;
17664 case VAR_STRING:
17665 if (varp->vval.v_string != NULL)
17666 vim_str2nr(varp->vval.v_string, NULL, NULL,
17667 TRUE, TRUE, &n, NULL);
17668 return n;
17669 case VAR_LIST:
17670 EMSG(_("E745: Using a List as a number"));
17671 break;
17672 case VAR_DICT:
17673 EMSG(_("E728: Using a Dictionary as a number"));
17674 break;
17675 default:
17676 EMSG2(_(e_intern2), "get_tv_number()");
17677 break;
17679 if (denote == NULL) /* useful for values that must be unsigned */
17680 n = -1;
17681 else
17682 *denote = TRUE;
17683 return n;
17687 * Get the lnum from the first argument.
17688 * Also accepts ".", "$", etc., but that only works for the current buffer.
17689 * Returns -1 on error.
17691 static linenr_T
17692 get_tv_lnum(argvars)
17693 typval_T *argvars;
17695 typval_T rettv;
17696 linenr_T lnum;
17698 lnum = get_tv_number_chk(&argvars[0], NULL);
17699 if (lnum == 0) /* no valid number, try using line() */
17701 rettv.v_type = VAR_NUMBER;
17702 f_line(argvars, &rettv);
17703 lnum = rettv.vval.v_number;
17704 clear_tv(&rettv);
17706 return lnum;
17710 * Get the lnum from the first argument.
17711 * Also accepts "$", then "buf" is used.
17712 * Returns 0 on error.
17714 static linenr_T
17715 get_tv_lnum_buf(argvars, buf)
17716 typval_T *argvars;
17717 buf_T *buf;
17719 if (argvars[0].v_type == VAR_STRING
17720 && argvars[0].vval.v_string != NULL
17721 && argvars[0].vval.v_string[0] == '$'
17722 && buf != NULL)
17723 return buf->b_ml.ml_line_count;
17724 return get_tv_number_chk(&argvars[0], NULL);
17728 * Get the string value of a variable.
17729 * If it is a Number variable, the number is converted into a string.
17730 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
17731 * get_tv_string_buf() uses a given buffer.
17732 * If the String variable has never been set, return an empty string.
17733 * Never returns NULL;
17734 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
17735 * NULL on error.
17737 static char_u *
17738 get_tv_string(varp)
17739 typval_T *varp;
17741 static char_u mybuf[NUMBUFLEN];
17743 return get_tv_string_buf(varp, mybuf);
17746 static char_u *
17747 get_tv_string_buf(varp, buf)
17748 typval_T *varp;
17749 char_u *buf;
17751 char_u *res = get_tv_string_buf_chk(varp, buf);
17753 return res != NULL ? res : (char_u *)"";
17756 char_u *
17757 get_tv_string_chk(varp)
17758 typval_T *varp;
17760 static char_u mybuf[NUMBUFLEN];
17762 return get_tv_string_buf_chk(varp, mybuf);
17765 static char_u *
17766 get_tv_string_buf_chk(varp, buf)
17767 typval_T *varp;
17768 char_u *buf;
17770 switch (varp->v_type)
17772 case VAR_NUMBER:
17773 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
17774 return buf;
17775 case VAR_FUNC:
17776 EMSG(_("E729: using Funcref as a String"));
17777 break;
17778 case VAR_LIST:
17779 EMSG(_("E730: using List as a String"));
17780 break;
17781 case VAR_DICT:
17782 EMSG(_("E731: using Dictionary as a String"));
17783 break;
17784 case VAR_STRING:
17785 if (varp->vval.v_string != NULL)
17786 return varp->vval.v_string;
17787 return (char_u *)"";
17788 default:
17789 EMSG2(_(e_intern2), "get_tv_string_buf()");
17790 break;
17792 return NULL;
17796 * Find variable "name" in the list of variables.
17797 * Return a pointer to it if found, NULL if not found.
17798 * Careful: "a:0" variables don't have a name.
17799 * When "htp" is not NULL we are writing to the variable, set "htp" to the
17800 * hashtab_T used.
17802 static dictitem_T *
17803 find_var(name, htp)
17804 char_u *name;
17805 hashtab_T **htp;
17807 char_u *varname;
17808 hashtab_T *ht;
17810 ht = find_var_ht(name, &varname);
17811 if (htp != NULL)
17812 *htp = ht;
17813 if (ht == NULL)
17814 return NULL;
17815 return find_var_in_ht(ht, varname, htp != NULL);
17819 * Find variable "varname" in hashtab "ht".
17820 * Returns NULL if not found.
17822 static dictitem_T *
17823 find_var_in_ht(ht, varname, writing)
17824 hashtab_T *ht;
17825 char_u *varname;
17826 int writing;
17828 hashitem_T *hi;
17830 if (*varname == NUL)
17832 /* Must be something like "s:", otherwise "ht" would be NULL. */
17833 switch (varname[-2])
17835 case 's': return &SCRIPT_SV(current_SID).sv_var;
17836 case 'g': return &globvars_var;
17837 case 'v': return &vimvars_var;
17838 case 'b': return &curbuf->b_bufvar;
17839 case 'w': return &curwin->w_winvar;
17840 #ifdef FEAT_WINDOWS
17841 case 't': return &curtab->tp_winvar;
17842 #endif
17843 case 'l': return current_funccal == NULL
17844 ? NULL : &current_funccal->l_vars_var;
17845 case 'a': return current_funccal == NULL
17846 ? NULL : &current_funccal->l_avars_var;
17848 return NULL;
17851 hi = hash_find(ht, varname);
17852 if (HASHITEM_EMPTY(hi))
17854 /* For global variables we may try auto-loading the script. If it
17855 * worked find the variable again. Don't auto-load a script if it was
17856 * loaded already, otherwise it would be loaded every time when
17857 * checking if a function name is a Funcref variable. */
17858 if (ht == &globvarht && !writing
17859 && script_autoload(varname, FALSE) && !aborting())
17860 hi = hash_find(ht, varname);
17861 if (HASHITEM_EMPTY(hi))
17862 return NULL;
17864 return HI2DI(hi);
17868 * Find the hashtab used for a variable name.
17869 * Set "varname" to the start of name without ':'.
17871 static hashtab_T *
17872 find_var_ht(name, varname)
17873 char_u *name;
17874 char_u **varname;
17876 hashitem_T *hi;
17878 if (name[1] != ':')
17880 /* The name must not start with a colon or #. */
17881 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
17882 return NULL;
17883 *varname = name;
17885 /* "version" is "v:version" in all scopes */
17886 hi = hash_find(&compat_hashtab, name);
17887 if (!HASHITEM_EMPTY(hi))
17888 return &compat_hashtab;
17890 if (current_funccal == NULL)
17891 return &globvarht; /* global variable */
17892 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
17894 *varname = name + 2;
17895 if (*name == 'g') /* global variable */
17896 return &globvarht;
17897 /* There must be no ':' or '#' in the rest of the name, unless g: is used
17899 if (vim_strchr(name + 2, ':') != NULL
17900 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
17901 return NULL;
17902 if (*name == 'b') /* buffer variable */
17903 return &curbuf->b_vars.dv_hashtab;
17904 if (*name == 'w') /* window variable */
17905 return &curwin->w_vars.dv_hashtab;
17906 #ifdef FEAT_WINDOWS
17907 if (*name == 't') /* tab page variable */
17908 return &curtab->tp_vars.dv_hashtab;
17909 #endif
17910 if (*name == 'v') /* v: variable */
17911 return &vimvarht;
17912 if (*name == 'a' && current_funccal != NULL) /* function argument */
17913 return &current_funccal->l_avars.dv_hashtab;
17914 if (*name == 'l' && current_funccal != NULL) /* local function variable */
17915 return &current_funccal->l_vars.dv_hashtab;
17916 if (*name == 's' /* script variable */
17917 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
17918 return &SCRIPT_VARS(current_SID);
17919 return NULL;
17923 * Get the string value of a (global/local) variable.
17924 * Returns NULL when it doesn't exist.
17926 char_u *
17927 get_var_value(name)
17928 char_u *name;
17930 dictitem_T *v;
17932 v = find_var(name, NULL);
17933 if (v == NULL)
17934 return NULL;
17935 return get_tv_string(&v->di_tv);
17939 * Allocate a new hashtab for a sourced script. It will be used while
17940 * sourcing this script and when executing functions defined in the script.
17942 void
17943 new_script_vars(id)
17944 scid_T id;
17946 int i;
17947 hashtab_T *ht;
17948 scriptvar_T *sv;
17950 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
17952 /* Re-allocating ga_data means that an ht_array pointing to
17953 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
17954 * at its init value. Also reset "v_dict", it's always the same. */
17955 for (i = 1; i <= ga_scripts.ga_len; ++i)
17957 ht = &SCRIPT_VARS(i);
17958 if (ht->ht_mask == HT_INIT_SIZE - 1)
17959 ht->ht_array = ht->ht_smallarray;
17960 sv = &SCRIPT_SV(i);
17961 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
17964 while (ga_scripts.ga_len < id)
17966 sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
17967 init_var_dict(&sv->sv_dict, &sv->sv_var);
17968 ++ga_scripts.ga_len;
17974 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
17975 * point to it.
17977 void
17978 init_var_dict(dict, dict_var)
17979 dict_T *dict;
17980 dictitem_T *dict_var;
17982 hash_init(&dict->dv_hashtab);
17983 dict->dv_refcount = 99999;
17984 dict_var->di_tv.vval.v_dict = dict;
17985 dict_var->di_tv.v_type = VAR_DICT;
17986 dict_var->di_tv.v_lock = VAR_FIXED;
17987 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
17988 dict_var->di_key[0] = NUL;
17992 * Clean up a list of internal variables.
17993 * Frees all allocated variables and the value they contain.
17994 * Clears hashtab "ht", does not free it.
17996 void
17997 vars_clear(ht)
17998 hashtab_T *ht;
18000 vars_clear_ext(ht, TRUE);
18004 * Like vars_clear(), but only free the value if "free_val" is TRUE.
18006 static void
18007 vars_clear_ext(ht, free_val)
18008 hashtab_T *ht;
18009 int free_val;
18011 int todo;
18012 hashitem_T *hi;
18013 dictitem_T *v;
18015 hash_lock(ht);
18016 todo = (int)ht->ht_used;
18017 for (hi = ht->ht_array; todo > 0; ++hi)
18019 if (!HASHITEM_EMPTY(hi))
18021 --todo;
18023 /* Free the variable. Don't remove it from the hashtab,
18024 * ht_array might change then. hash_clear() takes care of it
18025 * later. */
18026 v = HI2DI(hi);
18027 if (free_val)
18028 clear_tv(&v->di_tv);
18029 if ((v->di_flags & DI_FLAGS_FIX) == 0)
18030 vim_free(v);
18033 hash_clear(ht);
18034 ht->ht_used = 0;
18038 * Delete a variable from hashtab "ht" at item "hi".
18039 * Clear the variable value and free the dictitem.
18041 static void
18042 delete_var(ht, hi)
18043 hashtab_T *ht;
18044 hashitem_T *hi;
18046 dictitem_T *di = HI2DI(hi);
18048 hash_remove(ht, hi);
18049 clear_tv(&di->di_tv);
18050 vim_free(di);
18054 * List the value of one internal variable.
18056 static void
18057 list_one_var(v, prefix, first)
18058 dictitem_T *v;
18059 char_u *prefix;
18060 int *first;
18062 char_u *tofree;
18063 char_u *s;
18064 char_u numbuf[NUMBUFLEN];
18066 s = echo_string(&v->di_tv, &tofree, numbuf, ++current_copyID);
18067 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
18068 s == NULL ? (char_u *)"" : s, first);
18069 vim_free(tofree);
18072 static void
18073 list_one_var_a(prefix, name, type, string, first)
18074 char_u *prefix;
18075 char_u *name;
18076 int type;
18077 char_u *string;
18078 int *first; /* when TRUE clear rest of screen and set to FALSE */
18080 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
18081 msg_start();
18082 msg_puts(prefix);
18083 if (name != NULL) /* "a:" vars don't have a name stored */
18084 msg_puts(name);
18085 msg_putchar(' ');
18086 msg_advance(22);
18087 if (type == VAR_NUMBER)
18088 msg_putchar('#');
18089 else if (type == VAR_FUNC)
18090 msg_putchar('*');
18091 else if (type == VAR_LIST)
18093 msg_putchar('[');
18094 if (*string == '[')
18095 ++string;
18097 else if (type == VAR_DICT)
18099 msg_putchar('{');
18100 if (*string == '{')
18101 ++string;
18103 else
18104 msg_putchar(' ');
18106 msg_outtrans(string);
18108 if (type == VAR_FUNC)
18109 msg_puts((char_u *)"()");
18110 if (*first)
18112 msg_clr_eos();
18113 *first = FALSE;
18118 * Set variable "name" to value in "tv".
18119 * If the variable already exists, the value is updated.
18120 * Otherwise the variable is created.
18122 static void
18123 set_var(name, tv, copy)
18124 char_u *name;
18125 typval_T *tv;
18126 int copy; /* make copy of value in "tv" */
18128 dictitem_T *v;
18129 char_u *varname;
18130 hashtab_T *ht;
18131 char_u *p;
18133 if (tv->v_type == VAR_FUNC)
18135 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
18136 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
18137 ? name[2] : name[0]))
18139 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
18140 return;
18142 if (function_exists(name))
18144 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
18145 name);
18146 return;
18150 ht = find_var_ht(name, &varname);
18151 if (ht == NULL || *varname == NUL)
18153 EMSG2(_(e_illvar), name);
18154 return;
18157 v = find_var_in_ht(ht, varname, TRUE);
18158 if (v != NULL)
18160 /* existing variable, need to clear the value */
18161 if (var_check_ro(v->di_flags, name)
18162 || tv_check_lock(v->di_tv.v_lock, name))
18163 return;
18164 if (v->di_tv.v_type != tv->v_type
18165 && !((v->di_tv.v_type == VAR_STRING
18166 || v->di_tv.v_type == VAR_NUMBER)
18167 && (tv->v_type == VAR_STRING
18168 || tv->v_type == VAR_NUMBER)))
18170 EMSG2(_("E706: Variable type mismatch for: %s"), name);
18171 return;
18175 * Handle setting internal v: variables separately: we don't change
18176 * the type.
18178 if (ht == &vimvarht)
18180 if (v->di_tv.v_type == VAR_STRING)
18182 vim_free(v->di_tv.vval.v_string);
18183 if (copy || tv->v_type != VAR_STRING)
18184 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
18185 else
18187 /* Take over the string to avoid an extra alloc/free. */
18188 v->di_tv.vval.v_string = tv->vval.v_string;
18189 tv->vval.v_string = NULL;
18192 else if (v->di_tv.v_type != VAR_NUMBER)
18193 EMSG2(_(e_intern2), "set_var()");
18194 else
18195 v->di_tv.vval.v_number = get_tv_number(tv);
18196 return;
18199 clear_tv(&v->di_tv);
18201 else /* add a new variable */
18203 /* Can't add "v:" variable. */
18204 if (ht == &vimvarht)
18206 EMSG2(_(e_illvar), name);
18207 return;
18210 /* Make sure the variable name is valid. */
18211 for (p = varname; *p != NUL; ++p)
18212 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
18213 && *p != AUTOLOAD_CHAR)
18215 EMSG2(_(e_illvar), varname);
18216 return;
18219 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
18220 + STRLEN(varname)));
18221 if (v == NULL)
18222 return;
18223 STRCPY(v->di_key, varname);
18224 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
18226 vim_free(v);
18227 return;
18229 v->di_flags = 0;
18232 if (copy || tv->v_type == VAR_NUMBER)
18233 copy_tv(tv, &v->di_tv);
18234 else
18236 v->di_tv = *tv;
18237 v->di_tv.v_lock = 0;
18238 init_tv(tv);
18243 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
18244 * Also give an error message.
18246 static int
18247 var_check_ro(flags, name)
18248 int flags;
18249 char_u *name;
18251 if (flags & DI_FLAGS_RO)
18253 EMSG2(_(e_readonlyvar), name);
18254 return TRUE;
18256 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
18258 EMSG2(_(e_readonlysbx), name);
18259 return TRUE;
18261 return FALSE;
18265 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
18266 * Also give an error message.
18268 static int
18269 var_check_fixed(flags, name)
18270 int flags;
18271 char_u *name;
18273 if (flags & DI_FLAGS_FIX)
18275 EMSG2(_("E795: Cannot delete variable %s"), name);
18276 return TRUE;
18278 return FALSE;
18282 * Return TRUE if typeval "tv" is set to be locked (immutable).
18283 * Also give an error message, using "name".
18285 static int
18286 tv_check_lock(lock, name)
18287 int lock;
18288 char_u *name;
18290 if (lock & VAR_LOCKED)
18292 EMSG2(_("E741: Value is locked: %s"),
18293 name == NULL ? (char_u *)_("Unknown") : name);
18294 return TRUE;
18296 if (lock & VAR_FIXED)
18298 EMSG2(_("E742: Cannot change value of %s"),
18299 name == NULL ? (char_u *)_("Unknown") : name);
18300 return TRUE;
18302 return FALSE;
18306 * Copy the values from typval_T "from" to typval_T "to".
18307 * When needed allocates string or increases reference count.
18308 * Does not make a copy of a list or dict but copies the reference!
18310 static void
18311 copy_tv(from, to)
18312 typval_T *from;
18313 typval_T *to;
18315 to->v_type = from->v_type;
18316 to->v_lock = 0;
18317 switch (from->v_type)
18319 case VAR_NUMBER:
18320 to->vval.v_number = from->vval.v_number;
18321 break;
18322 case VAR_STRING:
18323 case VAR_FUNC:
18324 if (from->vval.v_string == NULL)
18325 to->vval.v_string = NULL;
18326 else
18328 to->vval.v_string = vim_strsave(from->vval.v_string);
18329 if (from->v_type == VAR_FUNC)
18330 func_ref(to->vval.v_string);
18332 break;
18333 case VAR_LIST:
18334 if (from->vval.v_list == NULL)
18335 to->vval.v_list = NULL;
18336 else
18338 to->vval.v_list = from->vval.v_list;
18339 ++to->vval.v_list->lv_refcount;
18341 break;
18342 case VAR_DICT:
18343 if (from->vval.v_dict == NULL)
18344 to->vval.v_dict = NULL;
18345 else
18347 to->vval.v_dict = from->vval.v_dict;
18348 ++to->vval.v_dict->dv_refcount;
18350 break;
18351 default:
18352 EMSG2(_(e_intern2), "copy_tv()");
18353 break;
18358 * Make a copy of an item.
18359 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
18360 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
18361 * reference to an already copied list/dict can be used.
18362 * Returns FAIL or OK.
18364 static int
18365 item_copy(from, to, deep, copyID)
18366 typval_T *from;
18367 typval_T *to;
18368 int deep;
18369 int copyID;
18371 static int recurse = 0;
18372 int ret = OK;
18374 if (recurse >= DICT_MAXNEST)
18376 EMSG(_("E698: variable nested too deep for making a copy"));
18377 return FAIL;
18379 ++recurse;
18381 switch (from->v_type)
18383 case VAR_NUMBER:
18384 case VAR_STRING:
18385 case VAR_FUNC:
18386 copy_tv(from, to);
18387 break;
18388 case VAR_LIST:
18389 to->v_type = VAR_LIST;
18390 to->v_lock = 0;
18391 if (from->vval.v_list == NULL)
18392 to->vval.v_list = NULL;
18393 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
18395 /* use the copy made earlier */
18396 to->vval.v_list = from->vval.v_list->lv_copylist;
18397 ++to->vval.v_list->lv_refcount;
18399 else
18400 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
18401 if (to->vval.v_list == NULL)
18402 ret = FAIL;
18403 break;
18404 case VAR_DICT:
18405 to->v_type = VAR_DICT;
18406 to->v_lock = 0;
18407 if (from->vval.v_dict == NULL)
18408 to->vval.v_dict = NULL;
18409 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
18411 /* use the copy made earlier */
18412 to->vval.v_dict = from->vval.v_dict->dv_copydict;
18413 ++to->vval.v_dict->dv_refcount;
18415 else
18416 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
18417 if (to->vval.v_dict == NULL)
18418 ret = FAIL;
18419 break;
18420 default:
18421 EMSG2(_(e_intern2), "item_copy()");
18422 ret = FAIL;
18424 --recurse;
18425 return ret;
18429 * ":echo expr1 ..." print each argument separated with a space, add a
18430 * newline at the end.
18431 * ":echon expr1 ..." print each argument plain.
18433 void
18434 ex_echo(eap)
18435 exarg_T *eap;
18437 char_u *arg = eap->arg;
18438 typval_T rettv;
18439 char_u *tofree;
18440 char_u *p;
18441 int needclr = TRUE;
18442 int atstart = TRUE;
18443 char_u numbuf[NUMBUFLEN];
18445 if (eap->skip)
18446 ++emsg_skip;
18447 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
18449 p = arg;
18450 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
18453 * Report the invalid expression unless the expression evaluation
18454 * has been cancelled due to an aborting error, an interrupt, or an
18455 * exception.
18457 if (!aborting())
18458 EMSG2(_(e_invexpr2), p);
18459 break;
18461 if (!eap->skip)
18463 if (atstart)
18465 atstart = FALSE;
18466 /* Call msg_start() after eval1(), evaluating the expression
18467 * may cause a message to appear. */
18468 if (eap->cmdidx == CMD_echo)
18469 msg_start();
18471 else if (eap->cmdidx == CMD_echo)
18472 msg_puts_attr((char_u *)" ", echo_attr);
18473 p = echo_string(&rettv, &tofree, numbuf, ++current_copyID);
18474 if (p != NULL)
18475 for ( ; *p != NUL && !got_int; ++p)
18477 if (*p == '\n' || *p == '\r' || *p == TAB)
18479 if (*p != TAB && needclr)
18481 /* remove any text still there from the command */
18482 msg_clr_eos();
18483 needclr = FALSE;
18485 msg_putchar_attr(*p, echo_attr);
18487 else
18489 #ifdef FEAT_MBYTE
18490 if (has_mbyte)
18492 int i = (*mb_ptr2len)(p);
18494 (void)msg_outtrans_len_attr(p, i, echo_attr);
18495 p += i - 1;
18497 else
18498 #endif
18499 (void)msg_outtrans_len_attr(p, 1, echo_attr);
18502 vim_free(tofree);
18504 clear_tv(&rettv);
18505 arg = skipwhite(arg);
18507 eap->nextcmd = check_nextcmd(arg);
18509 if (eap->skip)
18510 --emsg_skip;
18511 else
18513 /* remove text that may still be there from the command */
18514 if (needclr)
18515 msg_clr_eos();
18516 if (eap->cmdidx == CMD_echo)
18517 msg_end();
18522 * ":echohl {name}".
18524 void
18525 ex_echohl(eap)
18526 exarg_T *eap;
18528 int id;
18530 id = syn_name2id(eap->arg);
18531 if (id == 0)
18532 echo_attr = 0;
18533 else
18534 echo_attr = syn_id2attr(id);
18538 * ":execute expr1 ..." execute the result of an expression.
18539 * ":echomsg expr1 ..." Print a message
18540 * ":echoerr expr1 ..." Print an error
18541 * Each gets spaces around each argument and a newline at the end for
18542 * echo commands
18544 void
18545 ex_execute(eap)
18546 exarg_T *eap;
18548 char_u *arg = eap->arg;
18549 typval_T rettv;
18550 int ret = OK;
18551 char_u *p;
18552 garray_T ga;
18553 int len;
18554 int save_did_emsg;
18556 ga_init2(&ga, 1, 80);
18558 if (eap->skip)
18559 ++emsg_skip;
18560 while (*arg != NUL && *arg != '|' && *arg != '\n')
18562 p = arg;
18563 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
18566 * Report the invalid expression unless the expression evaluation
18567 * has been cancelled due to an aborting error, an interrupt, or an
18568 * exception.
18570 if (!aborting())
18571 EMSG2(_(e_invexpr2), p);
18572 ret = FAIL;
18573 break;
18576 if (!eap->skip)
18578 p = get_tv_string(&rettv);
18579 len = (int)STRLEN(p);
18580 if (ga_grow(&ga, len + 2) == FAIL)
18582 clear_tv(&rettv);
18583 ret = FAIL;
18584 break;
18586 if (ga.ga_len)
18587 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
18588 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
18589 ga.ga_len += len;
18592 clear_tv(&rettv);
18593 arg = skipwhite(arg);
18596 if (ret != FAIL && ga.ga_data != NULL)
18598 if (eap->cmdidx == CMD_echomsg)
18600 MSG_ATTR(ga.ga_data, echo_attr);
18601 out_flush();
18603 else if (eap->cmdidx == CMD_echoerr)
18605 /* We don't want to abort following commands, restore did_emsg. */
18606 save_did_emsg = did_emsg;
18607 EMSG((char_u *)ga.ga_data);
18608 if (!force_abort)
18609 did_emsg = save_did_emsg;
18611 else if (eap->cmdidx == CMD_execute)
18612 do_cmdline((char_u *)ga.ga_data,
18613 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
18616 ga_clear(&ga);
18618 if (eap->skip)
18619 --emsg_skip;
18621 eap->nextcmd = check_nextcmd(arg);
18625 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
18626 * "arg" points to the "&" or '+' when called, to "option" when returning.
18627 * Returns NULL when no option name found. Otherwise pointer to the char
18628 * after the option name.
18630 static char_u *
18631 find_option_end(arg, opt_flags)
18632 char_u **arg;
18633 int *opt_flags;
18635 char_u *p = *arg;
18637 ++p;
18638 if (*p == 'g' && p[1] == ':')
18640 *opt_flags = OPT_GLOBAL;
18641 p += 2;
18643 else if (*p == 'l' && p[1] == ':')
18645 *opt_flags = OPT_LOCAL;
18646 p += 2;
18648 else
18649 *opt_flags = 0;
18651 if (!ASCII_ISALPHA(*p))
18652 return NULL;
18653 *arg = p;
18655 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
18656 p += 4; /* termcap option */
18657 else
18658 while (ASCII_ISALPHA(*p))
18659 ++p;
18660 return p;
18664 * ":function"
18666 void
18667 ex_function(eap)
18668 exarg_T *eap;
18670 char_u *theline;
18671 int j;
18672 int c;
18673 int saved_did_emsg;
18674 char_u *name = NULL;
18675 char_u *p;
18676 char_u *arg;
18677 char_u *line_arg = NULL;
18678 garray_T newargs;
18679 garray_T newlines;
18680 int varargs = FALSE;
18681 int mustend = FALSE;
18682 int flags = 0;
18683 ufunc_T *fp;
18684 int indent;
18685 int nesting;
18686 char_u *skip_until = NULL;
18687 dictitem_T *v;
18688 funcdict_T fudi;
18689 static int func_nr = 0; /* number for nameless function */
18690 int paren;
18691 hashtab_T *ht;
18692 int todo;
18693 hashitem_T *hi;
18694 int sourcing_lnum_off;
18697 * ":function" without argument: list functions.
18699 if (ends_excmd(*eap->arg))
18701 if (!eap->skip)
18703 todo = (int)func_hashtab.ht_used;
18704 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
18706 if (!HASHITEM_EMPTY(hi))
18708 --todo;
18709 fp = HI2UF(hi);
18710 if (!isdigit(*fp->uf_name))
18711 list_func_head(fp, FALSE);
18715 eap->nextcmd = check_nextcmd(eap->arg);
18716 return;
18720 * ":function /pat": list functions matching pattern.
18722 if (*eap->arg == '/')
18724 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
18725 if (!eap->skip)
18727 regmatch_T regmatch;
18729 c = *p;
18730 *p = NUL;
18731 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
18732 *p = c;
18733 if (regmatch.regprog != NULL)
18735 regmatch.rm_ic = p_ic;
18737 todo = (int)func_hashtab.ht_used;
18738 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
18740 if (!HASHITEM_EMPTY(hi))
18742 --todo;
18743 fp = HI2UF(hi);
18744 if (!isdigit(*fp->uf_name)
18745 && vim_regexec(&regmatch, fp->uf_name, 0))
18746 list_func_head(fp, FALSE);
18751 if (*p == '/')
18752 ++p;
18753 eap->nextcmd = check_nextcmd(p);
18754 return;
18758 * Get the function name. There are these situations:
18759 * func normal function name
18760 * "name" == func, "fudi.fd_dict" == NULL
18761 * dict.func new dictionary entry
18762 * "name" == NULL, "fudi.fd_dict" set,
18763 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
18764 * dict.func existing dict entry with a Funcref
18765 * "name" == func, "fudi.fd_dict" set,
18766 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
18767 * dict.func existing dict entry that's not a Funcref
18768 * "name" == NULL, "fudi.fd_dict" set,
18769 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
18771 p = eap->arg;
18772 name = trans_function_name(&p, eap->skip, 0, &fudi);
18773 paren = (vim_strchr(p, '(') != NULL);
18774 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
18777 * Return on an invalid expression in braces, unless the expression
18778 * evaluation has been cancelled due to an aborting error, an
18779 * interrupt, or an exception.
18781 if (!aborting())
18783 if (!eap->skip && fudi.fd_newkey != NULL)
18784 EMSG2(_(e_dictkey), fudi.fd_newkey);
18785 vim_free(fudi.fd_newkey);
18786 return;
18788 else
18789 eap->skip = TRUE;
18792 /* An error in a function call during evaluation of an expression in magic
18793 * braces should not cause the function not to be defined. */
18794 saved_did_emsg = did_emsg;
18795 did_emsg = FALSE;
18798 * ":function func" with only function name: list function.
18800 if (!paren)
18802 if (!ends_excmd(*skipwhite(p)))
18804 EMSG(_(e_trailing));
18805 goto ret_free;
18807 eap->nextcmd = check_nextcmd(p);
18808 if (eap->nextcmd != NULL)
18809 *p = NUL;
18810 if (!eap->skip && !got_int)
18812 fp = find_func(name);
18813 if (fp != NULL)
18815 list_func_head(fp, TRUE);
18816 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
18818 if (FUNCLINE(fp, j) == NULL)
18819 continue;
18820 msg_putchar('\n');
18821 msg_outnum((long)(j + 1));
18822 if (j < 9)
18823 msg_putchar(' ');
18824 if (j < 99)
18825 msg_putchar(' ');
18826 msg_prt_line(FUNCLINE(fp, j), FALSE);
18827 out_flush(); /* show a line at a time */
18828 ui_breakcheck();
18830 if (!got_int)
18832 msg_putchar('\n');
18833 msg_puts((char_u *)" endfunction");
18836 else
18837 emsg_funcname("E123: Undefined function: %s", name);
18839 goto ret_free;
18843 * ":function name(arg1, arg2)" Define function.
18845 p = skipwhite(p);
18846 if (*p != '(')
18848 if (!eap->skip)
18850 EMSG2(_("E124: Missing '(': %s"), eap->arg);
18851 goto ret_free;
18853 /* attempt to continue by skipping some text */
18854 if (vim_strchr(p, '(') != NULL)
18855 p = vim_strchr(p, '(');
18857 p = skipwhite(p + 1);
18859 ga_init2(&newargs, (int)sizeof(char_u *), 3);
18860 ga_init2(&newlines, (int)sizeof(char_u *), 3);
18862 if (!eap->skip)
18864 /* Check the name of the function. Unless it's a dictionary function
18865 * (that we are overwriting). */
18866 if (name != NULL)
18867 arg = name;
18868 else
18869 arg = fudi.fd_newkey;
18870 if (arg != NULL && (fudi.fd_di == NULL
18871 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
18873 if (*arg == K_SPECIAL)
18874 j = 3;
18875 else
18876 j = 0;
18877 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
18878 : eval_isnamec(arg[j])))
18879 ++j;
18880 if (arg[j] != NUL)
18881 emsg_funcname(_(e_invarg2), arg);
18886 * Isolate the arguments: "arg1, arg2, ...)"
18888 while (*p != ')')
18890 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
18892 varargs = TRUE;
18893 p += 3;
18894 mustend = TRUE;
18896 else
18898 arg = p;
18899 while (ASCII_ISALNUM(*p) || *p == '_')
18900 ++p;
18901 if (arg == p || isdigit(*arg)
18902 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
18903 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
18905 if (!eap->skip)
18906 EMSG2(_("E125: Illegal argument: %s"), arg);
18907 break;
18909 if (ga_grow(&newargs, 1) == FAIL)
18910 goto erret;
18911 c = *p;
18912 *p = NUL;
18913 arg = vim_strsave(arg);
18914 if (arg == NULL)
18915 goto erret;
18916 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
18917 *p = c;
18918 newargs.ga_len++;
18919 if (*p == ',')
18920 ++p;
18921 else
18922 mustend = TRUE;
18924 p = skipwhite(p);
18925 if (mustend && *p != ')')
18927 if (!eap->skip)
18928 EMSG2(_(e_invarg2), eap->arg);
18929 break;
18932 ++p; /* skip the ')' */
18934 /* find extra arguments "range", "dict" and "abort" */
18935 for (;;)
18937 p = skipwhite(p);
18938 if (STRNCMP(p, "range", 5) == 0)
18940 flags |= FC_RANGE;
18941 p += 5;
18943 else if (STRNCMP(p, "dict", 4) == 0)
18945 flags |= FC_DICT;
18946 p += 4;
18948 else if (STRNCMP(p, "abort", 5) == 0)
18950 flags |= FC_ABORT;
18951 p += 5;
18953 else
18954 break;
18957 /* When there is a line break use what follows for the function body.
18958 * Makes 'exe "func Test()\n...\nendfunc"' work. */
18959 if (*p == '\n')
18960 line_arg = p + 1;
18961 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
18962 EMSG(_(e_trailing));
18965 * Read the body of the function, until ":endfunction" is found.
18967 if (KeyTyped)
18969 /* Check if the function already exists, don't let the user type the
18970 * whole function before telling him it doesn't work! For a script we
18971 * need to skip the body to be able to find what follows. */
18972 if (!eap->skip && !eap->forceit)
18974 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
18975 EMSG(_(e_funcdict));
18976 else if (name != NULL && find_func(name) != NULL)
18977 emsg_funcname(e_funcexts, name);
18980 if (!eap->skip && did_emsg)
18981 goto erret;
18983 msg_putchar('\n'); /* don't overwrite the function name */
18984 cmdline_row = msg_row;
18987 indent = 2;
18988 nesting = 0;
18989 for (;;)
18991 msg_scroll = TRUE;
18992 need_wait_return = FALSE;
18993 sourcing_lnum_off = sourcing_lnum;
18995 if (line_arg != NULL)
18997 /* Use eap->arg, split up in parts by line breaks. */
18998 theline = line_arg;
18999 p = vim_strchr(theline, '\n');
19000 if (p == NULL)
19001 line_arg += STRLEN(line_arg);
19002 else
19004 *p = NUL;
19005 line_arg = p + 1;
19008 else if (eap->getline == NULL)
19009 theline = getcmdline(':', 0L, indent);
19010 else
19011 theline = eap->getline(':', eap->cookie, indent);
19012 if (KeyTyped)
19013 lines_left = Rows - 1;
19014 if (theline == NULL)
19016 EMSG(_("E126: Missing :endfunction"));
19017 goto erret;
19020 /* Detect line continuation: sourcing_lnum increased more than one. */
19021 if (sourcing_lnum > sourcing_lnum_off + 1)
19022 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
19023 else
19024 sourcing_lnum_off = 0;
19026 if (skip_until != NULL)
19028 /* between ":append" and "." and between ":python <<EOF" and "EOF"
19029 * don't check for ":endfunc". */
19030 if (STRCMP(theline, skip_until) == 0)
19032 vim_free(skip_until);
19033 skip_until = NULL;
19036 else
19038 /* skip ':' and blanks*/
19039 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
19042 /* Check for "endfunction". */
19043 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
19045 if (line_arg == NULL)
19046 vim_free(theline);
19047 break;
19050 /* Increase indent inside "if", "while", "for" and "try", decrease
19051 * at "end". */
19052 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
19053 indent -= 2;
19054 else if (STRNCMP(p, "if", 2) == 0
19055 || STRNCMP(p, "wh", 2) == 0
19056 || STRNCMP(p, "for", 3) == 0
19057 || STRNCMP(p, "try", 3) == 0)
19058 indent += 2;
19060 /* Check for defining a function inside this function. */
19061 if (checkforcmd(&p, "function", 2))
19063 if (*p == '!')
19064 p = skipwhite(p + 1);
19065 p += eval_fname_script(p);
19066 if (ASCII_ISALPHA(*p))
19068 vim_free(trans_function_name(&p, TRUE, 0, NULL));
19069 if (*skipwhite(p) == '(')
19071 ++nesting;
19072 indent += 2;
19077 /* Check for ":append" or ":insert". */
19078 p = skip_range(p, NULL);
19079 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
19080 || (p[0] == 'i'
19081 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
19082 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
19083 skip_until = vim_strsave((char_u *)".");
19085 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
19086 arg = skipwhite(skiptowhite(p));
19087 if (arg[0] == '<' && arg[1] =='<'
19088 && ((p[0] == 'p' && p[1] == 'y'
19089 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
19090 || (p[0] == 'p' && p[1] == 'e'
19091 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
19092 || (p[0] == 't' && p[1] == 'c'
19093 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
19094 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
19095 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
19096 || (p[0] == 'm' && p[1] == 'z'
19097 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
19100 /* ":python <<" continues until a dot, like ":append" */
19101 p = skipwhite(arg + 2);
19102 if (*p == NUL)
19103 skip_until = vim_strsave((char_u *)".");
19104 else
19105 skip_until = vim_strsave(p);
19109 /* Add the line to the function. */
19110 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
19112 if (line_arg == NULL)
19113 vim_free(theline);
19114 goto erret;
19117 /* Copy the line to newly allocated memory. get_one_sourceline()
19118 * allocates 250 bytes per line, this saves 80% on average. The cost
19119 * is an extra alloc/free. */
19120 p = vim_strsave(theline);
19121 if (p != NULL)
19123 if (line_arg == NULL)
19124 vim_free(theline);
19125 theline = p;
19128 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
19130 /* Add NULL lines for continuation lines, so that the line count is
19131 * equal to the index in the growarray. */
19132 while (sourcing_lnum_off-- > 0)
19133 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
19135 /* Check for end of eap->arg. */
19136 if (line_arg != NULL && *line_arg == NUL)
19137 line_arg = NULL;
19140 /* Don't define the function when skipping commands or when an error was
19141 * detected. */
19142 if (eap->skip || did_emsg)
19143 goto erret;
19146 * If there are no errors, add the function
19148 if (fudi.fd_dict == NULL)
19150 v = find_var(name, &ht);
19151 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
19153 emsg_funcname("E707: Function name conflicts with variable: %s",
19154 name);
19155 goto erret;
19158 fp = find_func(name);
19159 if (fp != NULL)
19161 if (!eap->forceit)
19163 emsg_funcname(e_funcexts, name);
19164 goto erret;
19166 if (fp->uf_calls > 0)
19168 emsg_funcname("E127: Cannot redefine function %s: It is in use",
19169 name);
19170 goto erret;
19172 /* redefine existing function */
19173 ga_clear_strings(&(fp->uf_args));
19174 ga_clear_strings(&(fp->uf_lines));
19175 vim_free(name);
19176 name = NULL;
19179 else
19181 char numbuf[20];
19183 fp = NULL;
19184 if (fudi.fd_newkey == NULL && !eap->forceit)
19186 EMSG(_(e_funcdict));
19187 goto erret;
19189 if (fudi.fd_di == NULL)
19191 /* Can't add a function to a locked dictionary */
19192 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
19193 goto erret;
19195 /* Can't change an existing function if it is locked */
19196 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
19197 goto erret;
19199 /* Give the function a sequential number. Can only be used with a
19200 * Funcref! */
19201 vim_free(name);
19202 sprintf(numbuf, "%d", ++func_nr);
19203 name = vim_strsave((char_u *)numbuf);
19204 if (name == NULL)
19205 goto erret;
19208 if (fp == NULL)
19210 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
19212 int slen, plen;
19213 char_u *scriptname;
19215 /* Check that the autoload name matches the script name. */
19216 j = FAIL;
19217 if (sourcing_name != NULL)
19219 scriptname = autoload_name(name);
19220 if (scriptname != NULL)
19222 p = vim_strchr(scriptname, '/');
19223 plen = (int)STRLEN(p);
19224 slen = (int)STRLEN(sourcing_name);
19225 if (slen > plen && fnamecmp(p,
19226 sourcing_name + slen - plen) == 0)
19227 j = OK;
19228 vim_free(scriptname);
19231 if (j == FAIL)
19233 EMSG2(_("E746: Function name does not match script file name: %s"), name);
19234 goto erret;
19238 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
19239 if (fp == NULL)
19240 goto erret;
19242 if (fudi.fd_dict != NULL)
19244 if (fudi.fd_di == NULL)
19246 /* add new dict entry */
19247 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
19248 if (fudi.fd_di == NULL)
19250 vim_free(fp);
19251 goto erret;
19253 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
19255 vim_free(fudi.fd_di);
19256 vim_free(fp);
19257 goto erret;
19260 else
19261 /* overwrite existing dict entry */
19262 clear_tv(&fudi.fd_di->di_tv);
19263 fudi.fd_di->di_tv.v_type = VAR_FUNC;
19264 fudi.fd_di->di_tv.v_lock = 0;
19265 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
19266 fp->uf_refcount = 1;
19268 /* behave like "dict" was used */
19269 flags |= FC_DICT;
19272 /* insert the new function in the function list */
19273 STRCPY(fp->uf_name, name);
19274 hash_add(&func_hashtab, UF2HIKEY(fp));
19276 fp->uf_args = newargs;
19277 fp->uf_lines = newlines;
19278 #ifdef FEAT_PROFILE
19279 fp->uf_tml_count = NULL;
19280 fp->uf_tml_total = NULL;
19281 fp->uf_tml_self = NULL;
19282 fp->uf_profiling = FALSE;
19283 if (prof_def_func())
19284 func_do_profile(fp);
19285 #endif
19286 fp->uf_varargs = varargs;
19287 fp->uf_flags = flags;
19288 fp->uf_calls = 0;
19289 fp->uf_script_ID = current_SID;
19290 goto ret_free;
19292 erret:
19293 ga_clear_strings(&newargs);
19294 ga_clear_strings(&newlines);
19295 ret_free:
19296 vim_free(skip_until);
19297 vim_free(fudi.fd_newkey);
19298 vim_free(name);
19299 did_emsg |= saved_did_emsg;
19303 * Get a function name, translating "<SID>" and "<SNR>".
19304 * Also handles a Funcref in a List or Dictionary.
19305 * Returns the function name in allocated memory, or NULL for failure.
19306 * flags:
19307 * TFN_INT: internal function name OK
19308 * TFN_QUIET: be quiet
19309 * Advances "pp" to just after the function name (if no error).
19311 static char_u *
19312 trans_function_name(pp, skip, flags, fdp)
19313 char_u **pp;
19314 int skip; /* only find the end, don't evaluate */
19315 int flags;
19316 funcdict_T *fdp; /* return: info about dictionary used */
19318 char_u *name = NULL;
19319 char_u *start;
19320 char_u *end;
19321 int lead;
19322 char_u sid_buf[20];
19323 int len;
19324 lval_T lv;
19326 if (fdp != NULL)
19327 vim_memset(fdp, 0, sizeof(funcdict_T));
19328 start = *pp;
19330 /* Check for hard coded <SNR>: already translated function ID (from a user
19331 * command). */
19332 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
19333 && (*pp)[2] == (int)KE_SNR)
19335 *pp += 3;
19336 len = get_id_len(pp) + 3;
19337 return vim_strnsave(start, len);
19340 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
19341 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
19342 lead = eval_fname_script(start);
19343 if (lead > 2)
19344 start += lead;
19346 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
19347 lead > 2 ? 0 : FNE_CHECK_START);
19348 if (end == start)
19350 if (!skip)
19351 EMSG(_("E129: Function name required"));
19352 goto theend;
19354 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
19357 * Report an invalid expression in braces, unless the expression
19358 * evaluation has been cancelled due to an aborting error, an
19359 * interrupt, or an exception.
19361 if (!aborting())
19363 if (end != NULL)
19364 EMSG2(_(e_invarg2), start);
19366 else
19367 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
19368 goto theend;
19371 if (lv.ll_tv != NULL)
19373 if (fdp != NULL)
19375 fdp->fd_dict = lv.ll_dict;
19376 fdp->fd_newkey = lv.ll_newkey;
19377 lv.ll_newkey = NULL;
19378 fdp->fd_di = lv.ll_di;
19380 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
19382 name = vim_strsave(lv.ll_tv->vval.v_string);
19383 *pp = end;
19385 else
19387 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
19388 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
19389 EMSG(_(e_funcref));
19390 else
19391 *pp = end;
19392 name = NULL;
19394 goto theend;
19397 if (lv.ll_name == NULL)
19399 /* Error found, but continue after the function name. */
19400 *pp = end;
19401 goto theend;
19404 /* Check if the name is a Funcref. If so, use the value. */
19405 if (lv.ll_exp_name != NULL)
19407 len = (int)STRLEN(lv.ll_exp_name);
19408 name = deref_func_name(lv.ll_exp_name, &len);
19409 if (name == lv.ll_exp_name)
19410 name = NULL;
19412 else
19414 len = (int)(end - *pp);
19415 name = deref_func_name(*pp, &len);
19416 if (name == *pp)
19417 name = NULL;
19419 if (name != NULL)
19421 name = vim_strsave(name);
19422 *pp = end;
19423 goto theend;
19426 if (lv.ll_exp_name != NULL)
19428 len = (int)STRLEN(lv.ll_exp_name);
19429 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
19430 && STRNCMP(lv.ll_name, "s:", 2) == 0)
19432 /* When there was "s:" already or the name expanded to get a
19433 * leading "s:" then remove it. */
19434 lv.ll_name += 2;
19435 len -= 2;
19436 lead = 2;
19439 else
19441 if (lead == 2) /* skip over "s:" */
19442 lv.ll_name += 2;
19443 len = (int)(end - lv.ll_name);
19447 * Copy the function name to allocated memory.
19448 * Accept <SID>name() inside a script, translate into <SNR>123_name().
19449 * Accept <SNR>123_name() outside a script.
19451 if (skip)
19452 lead = 0; /* do nothing */
19453 else if (lead > 0)
19455 lead = 3;
19456 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
19457 || eval_fname_sid(*pp))
19459 /* It's "s:" or "<SID>" */
19460 if (current_SID <= 0)
19462 EMSG(_(e_usingsid));
19463 goto theend;
19465 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
19466 lead += (int)STRLEN(sid_buf);
19469 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
19471 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
19472 goto theend;
19474 name = alloc((unsigned)(len + lead + 1));
19475 if (name != NULL)
19477 if (lead > 0)
19479 name[0] = K_SPECIAL;
19480 name[1] = KS_EXTRA;
19481 name[2] = (int)KE_SNR;
19482 if (lead > 3) /* If it's "<SID>" */
19483 STRCPY(name + 3, sid_buf);
19485 mch_memmove(name + lead, lv.ll_name, (size_t)len);
19486 name[len + lead] = NUL;
19488 *pp = end;
19490 theend:
19491 clear_lval(&lv);
19492 return name;
19496 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
19497 * Return 2 if "p" starts with "s:".
19498 * Return 0 otherwise.
19500 static int
19501 eval_fname_script(p)
19502 char_u *p;
19504 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
19505 || STRNICMP(p + 1, "SNR>", 4) == 0))
19506 return 5;
19507 if (p[0] == 's' && p[1] == ':')
19508 return 2;
19509 return 0;
19513 * Return TRUE if "p" starts with "<SID>" or "s:".
19514 * Only works if eval_fname_script() returned non-zero for "p"!
19516 static int
19517 eval_fname_sid(p)
19518 char_u *p;
19520 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
19524 * List the head of the function: "name(arg1, arg2)".
19526 static void
19527 list_func_head(fp, indent)
19528 ufunc_T *fp;
19529 int indent;
19531 int j;
19533 msg_start();
19534 if (indent)
19535 MSG_PUTS(" ");
19536 MSG_PUTS("function ");
19537 if (fp->uf_name[0] == K_SPECIAL)
19539 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
19540 msg_puts(fp->uf_name + 3);
19542 else
19543 msg_puts(fp->uf_name);
19544 msg_putchar('(');
19545 for (j = 0; j < fp->uf_args.ga_len; ++j)
19547 if (j)
19548 MSG_PUTS(", ");
19549 msg_puts(FUNCARG(fp, j));
19551 if (fp->uf_varargs)
19553 if (j)
19554 MSG_PUTS(", ");
19555 MSG_PUTS("...");
19557 msg_putchar(')');
19558 msg_clr_eos();
19559 if (p_verbose > 0)
19560 last_set_msg(fp->uf_script_ID);
19564 * Find a function by name, return pointer to it in ufuncs.
19565 * Return NULL for unknown function.
19567 static ufunc_T *
19568 find_func(name)
19569 char_u *name;
19571 hashitem_T *hi;
19573 hi = hash_find(&func_hashtab, name);
19574 if (!HASHITEM_EMPTY(hi))
19575 return HI2UF(hi);
19576 return NULL;
19579 #if defined(EXITFREE) || defined(PROTO)
19580 void
19581 free_all_functions()
19583 hashitem_T *hi;
19585 /* Need to start all over every time, because func_free() may change the
19586 * hash table. */
19587 while (func_hashtab.ht_used > 0)
19588 for (hi = func_hashtab.ht_array; ; ++hi)
19589 if (!HASHITEM_EMPTY(hi))
19591 func_free(HI2UF(hi));
19592 break;
19595 #endif
19598 * Return TRUE if a function "name" exists.
19600 static int
19601 function_exists(name)
19602 char_u *name;
19604 char_u *nm = name;
19605 char_u *p;
19606 int n = FALSE;
19608 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
19609 nm = skipwhite(nm);
19611 /* Only accept "funcname", "funcname ", "funcname (..." and
19612 * "funcname(...", not "funcname!...". */
19613 if (p != NULL && (*nm == NUL || *nm == '('))
19615 if (builtin_function(p))
19616 n = (find_internal_func(p) >= 0);
19617 else
19618 n = (find_func(p) != NULL);
19620 vim_free(p);
19621 return n;
19625 * Return TRUE if "name" looks like a builtin function name: starts with a
19626 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
19628 static int
19629 builtin_function(name)
19630 char_u *name;
19632 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
19633 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
19636 #if defined(FEAT_PROFILE) || defined(PROTO)
19638 * Start profiling function "fp".
19640 static void
19641 func_do_profile(fp)
19642 ufunc_T *fp;
19644 fp->uf_tm_count = 0;
19645 profile_zero(&fp->uf_tm_self);
19646 profile_zero(&fp->uf_tm_total);
19647 if (fp->uf_tml_count == NULL)
19648 fp->uf_tml_count = (int *)alloc_clear((unsigned)
19649 (sizeof(int) * fp->uf_lines.ga_len));
19650 if (fp->uf_tml_total == NULL)
19651 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
19652 (sizeof(proftime_T) * fp->uf_lines.ga_len));
19653 if (fp->uf_tml_self == NULL)
19654 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
19655 (sizeof(proftime_T) * fp->uf_lines.ga_len));
19656 fp->uf_tml_idx = -1;
19657 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
19658 || fp->uf_tml_self == NULL)
19659 return; /* out of memory */
19661 fp->uf_profiling = TRUE;
19665 * Dump the profiling results for all functions in file "fd".
19667 void
19668 func_dump_profile(fd)
19669 FILE *fd;
19671 hashitem_T *hi;
19672 int todo;
19673 ufunc_T *fp;
19674 int i;
19675 ufunc_T **sorttab;
19676 int st_len = 0;
19678 todo = (int)func_hashtab.ht_used;
19679 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
19681 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
19683 if (!HASHITEM_EMPTY(hi))
19685 --todo;
19686 fp = HI2UF(hi);
19687 if (fp->uf_profiling)
19689 if (sorttab != NULL)
19690 sorttab[st_len++] = fp;
19692 if (fp->uf_name[0] == K_SPECIAL)
19693 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
19694 else
19695 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
19696 if (fp->uf_tm_count == 1)
19697 fprintf(fd, "Called 1 time\n");
19698 else
19699 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
19700 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
19701 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
19702 fprintf(fd, "\n");
19703 fprintf(fd, "count total (s) self (s)\n");
19705 for (i = 0; i < fp->uf_lines.ga_len; ++i)
19707 if (FUNCLINE(fp, i) == NULL)
19708 continue;
19709 prof_func_line(fd, fp->uf_tml_count[i],
19710 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
19711 fprintf(fd, "%s\n", FUNCLINE(fp, i));
19713 fprintf(fd, "\n");
19718 if (sorttab != NULL && st_len > 0)
19720 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
19721 prof_total_cmp);
19722 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
19723 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
19724 prof_self_cmp);
19725 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
19729 static void
19730 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
19731 FILE *fd;
19732 ufunc_T **sorttab;
19733 int st_len;
19734 char *title;
19735 int prefer_self; /* when equal print only self time */
19737 int i;
19738 ufunc_T *fp;
19740 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
19741 fprintf(fd, "count total (s) self (s) function\n");
19742 for (i = 0; i < 20 && i < st_len; ++i)
19744 fp = sorttab[i];
19745 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
19746 prefer_self);
19747 if (fp->uf_name[0] == K_SPECIAL)
19748 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
19749 else
19750 fprintf(fd, " %s()\n", fp->uf_name);
19752 fprintf(fd, "\n");
19756 * Print the count and times for one function or function line.
19758 static void
19759 prof_func_line(fd, count, total, self, prefer_self)
19760 FILE *fd;
19761 int count;
19762 proftime_T *total;
19763 proftime_T *self;
19764 int prefer_self; /* when equal print only self time */
19766 if (count > 0)
19768 fprintf(fd, "%5d ", count);
19769 if (prefer_self && profile_equal(total, self))
19770 fprintf(fd, " ");
19771 else
19772 fprintf(fd, "%s ", profile_msg(total));
19773 if (!prefer_self && profile_equal(total, self))
19774 fprintf(fd, " ");
19775 else
19776 fprintf(fd, "%s ", profile_msg(self));
19778 else
19779 fprintf(fd, " ");
19783 * Compare function for total time sorting.
19785 static int
19786 #ifdef __BORLANDC__
19787 _RTLENTRYF
19788 #endif
19789 prof_total_cmp(s1, s2)
19790 const void *s1;
19791 const void *s2;
19793 ufunc_T *p1, *p2;
19795 p1 = *(ufunc_T **)s1;
19796 p2 = *(ufunc_T **)s2;
19797 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
19801 * Compare function for self time sorting.
19803 static int
19804 #ifdef __BORLANDC__
19805 _RTLENTRYF
19806 #endif
19807 prof_self_cmp(s1, s2)
19808 const void *s1;
19809 const void *s2;
19811 ufunc_T *p1, *p2;
19813 p1 = *(ufunc_T **)s1;
19814 p2 = *(ufunc_T **)s2;
19815 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
19818 #endif
19821 * If "name" has a package name try autoloading the script for it.
19822 * Return TRUE if a package was loaded.
19824 static int
19825 script_autoload(name, reload)
19826 char_u *name;
19827 int reload; /* load script again when already loaded */
19829 char_u *p;
19830 char_u *scriptname, *tofree;
19831 int ret = FALSE;
19832 int i;
19834 /* If there is no '#' after name[0] there is no package name. */
19835 p = vim_strchr(name, AUTOLOAD_CHAR);
19836 if (p == NULL || p == name)
19837 return FALSE;
19839 tofree = scriptname = autoload_name(name);
19841 /* Find the name in the list of previously loaded package names. Skip
19842 * "autoload/", it's always the same. */
19843 for (i = 0; i < ga_loaded.ga_len; ++i)
19844 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
19845 break;
19846 if (!reload && i < ga_loaded.ga_len)
19847 ret = FALSE; /* was loaded already */
19848 else
19850 /* Remember the name if it wasn't loaded already. */
19851 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
19853 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
19854 tofree = NULL;
19857 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
19858 if (source_runtime(scriptname, FALSE) == OK)
19859 ret = TRUE;
19862 vim_free(tofree);
19863 return ret;
19867 * Return the autoload script name for a function or variable name.
19868 * Returns NULL when out of memory.
19870 static char_u *
19871 autoload_name(name)
19872 char_u *name;
19874 char_u *p;
19875 char_u *scriptname;
19877 /* Get the script file name: replace '#' with '/', append ".vim". */
19878 scriptname = alloc((unsigned)(STRLEN(name) + 14));
19879 if (scriptname == NULL)
19880 return FALSE;
19881 STRCPY(scriptname, "autoload/");
19882 STRCAT(scriptname, name);
19883 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
19884 STRCAT(scriptname, ".vim");
19885 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
19886 *p = '/';
19887 return scriptname;
19890 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
19893 * Function given to ExpandGeneric() to obtain the list of user defined
19894 * function names.
19896 char_u *
19897 get_user_func_name(xp, idx)
19898 expand_T *xp;
19899 int idx;
19901 static long_u done;
19902 static hashitem_T *hi;
19903 ufunc_T *fp;
19905 if (idx == 0)
19907 done = 0;
19908 hi = func_hashtab.ht_array;
19910 if (done < func_hashtab.ht_used)
19912 if (done++ > 0)
19913 ++hi;
19914 while (HASHITEM_EMPTY(hi))
19915 ++hi;
19916 fp = HI2UF(hi);
19918 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
19919 return fp->uf_name; /* prevents overflow */
19921 cat_func_name(IObuff, fp);
19922 if (xp->xp_context != EXPAND_USER_FUNC)
19924 STRCAT(IObuff, "(");
19925 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
19926 STRCAT(IObuff, ")");
19928 return IObuff;
19930 return NULL;
19933 #endif /* FEAT_CMDL_COMPL */
19936 * Copy the function name of "fp" to buffer "buf".
19937 * "buf" must be able to hold the function name plus three bytes.
19938 * Takes care of script-local function names.
19940 static void
19941 cat_func_name(buf, fp)
19942 char_u *buf;
19943 ufunc_T *fp;
19945 if (fp->uf_name[0] == K_SPECIAL)
19947 STRCPY(buf, "<SNR>");
19948 STRCAT(buf, fp->uf_name + 3);
19950 else
19951 STRCPY(buf, fp->uf_name);
19955 * ":delfunction {name}"
19957 void
19958 ex_delfunction(eap)
19959 exarg_T *eap;
19961 ufunc_T *fp = NULL;
19962 char_u *p;
19963 char_u *name;
19964 funcdict_T fudi;
19966 p = eap->arg;
19967 name = trans_function_name(&p, eap->skip, 0, &fudi);
19968 vim_free(fudi.fd_newkey);
19969 if (name == NULL)
19971 if (fudi.fd_dict != NULL && !eap->skip)
19972 EMSG(_(e_funcref));
19973 return;
19975 if (!ends_excmd(*skipwhite(p)))
19977 vim_free(name);
19978 EMSG(_(e_trailing));
19979 return;
19981 eap->nextcmd = check_nextcmd(p);
19982 if (eap->nextcmd != NULL)
19983 *p = NUL;
19985 if (!eap->skip)
19986 fp = find_func(name);
19987 vim_free(name);
19989 if (!eap->skip)
19991 if (fp == NULL)
19993 EMSG2(_(e_nofunc), eap->arg);
19994 return;
19996 if (fp->uf_calls > 0)
19998 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
19999 return;
20002 if (fudi.fd_dict != NULL)
20004 /* Delete the dict item that refers to the function, it will
20005 * invoke func_unref() and possibly delete the function. */
20006 dictitem_remove(fudi.fd_dict, fudi.fd_di);
20008 else
20009 func_free(fp);
20014 * Free a function and remove it from the list of functions.
20016 static void
20017 func_free(fp)
20018 ufunc_T *fp;
20020 hashitem_T *hi;
20022 /* clear this function */
20023 ga_clear_strings(&(fp->uf_args));
20024 ga_clear_strings(&(fp->uf_lines));
20025 #ifdef FEAT_PROFILE
20026 vim_free(fp->uf_tml_count);
20027 vim_free(fp->uf_tml_total);
20028 vim_free(fp->uf_tml_self);
20029 #endif
20031 /* remove the function from the function hashtable */
20032 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
20033 if (HASHITEM_EMPTY(hi))
20034 EMSG2(_(e_intern2), "func_free()");
20035 else
20036 hash_remove(&func_hashtab, hi);
20038 vim_free(fp);
20042 * Unreference a Function: decrement the reference count and free it when it
20043 * becomes zero. Only for numbered functions.
20045 static void
20046 func_unref(name)
20047 char_u *name;
20049 ufunc_T *fp;
20051 if (name != NULL && isdigit(*name))
20053 fp = find_func(name);
20054 if (fp == NULL)
20055 EMSG2(_(e_intern2), "func_unref()");
20056 else if (--fp->uf_refcount <= 0)
20058 /* Only delete it when it's not being used. Otherwise it's done
20059 * when "uf_calls" becomes zero. */
20060 if (fp->uf_calls == 0)
20061 func_free(fp);
20067 * Count a reference to a Function.
20069 static void
20070 func_ref(name)
20071 char_u *name;
20073 ufunc_T *fp;
20075 if (name != NULL && isdigit(*name))
20077 fp = find_func(name);
20078 if (fp == NULL)
20079 EMSG2(_(e_intern2), "func_ref()");
20080 else
20081 ++fp->uf_refcount;
20086 * Call a user function.
20088 static void
20089 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
20090 ufunc_T *fp; /* pointer to function */
20091 int argcount; /* nr of args */
20092 typval_T *argvars; /* arguments */
20093 typval_T *rettv; /* return value */
20094 linenr_T firstline; /* first line of range */
20095 linenr_T lastline; /* last line of range */
20096 dict_T *selfdict; /* Dictionary for "self" */
20098 char_u *save_sourcing_name;
20099 linenr_T save_sourcing_lnum;
20100 scid_T save_current_SID;
20101 funccall_T fc;
20102 int save_did_emsg;
20103 static int depth = 0;
20104 dictitem_T *v;
20105 int fixvar_idx = 0; /* index in fixvar[] */
20106 int i;
20107 int ai;
20108 char_u numbuf[NUMBUFLEN];
20109 char_u *name;
20110 #ifdef FEAT_PROFILE
20111 proftime_T wait_start;
20112 proftime_T call_start;
20113 #endif
20115 /* If depth of calling is getting too high, don't execute the function */
20116 if (depth >= p_mfd)
20118 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
20119 rettv->v_type = VAR_NUMBER;
20120 rettv->vval.v_number = -1;
20121 return;
20123 ++depth;
20125 line_breakcheck(); /* check for CTRL-C hit */
20127 fc.caller = current_funccal;
20128 current_funccal = &fc;
20129 fc.func = fp;
20130 fc.rettv = rettv;
20131 rettv->vval.v_number = 0;
20132 fc.linenr = 0;
20133 fc.returned = FALSE;
20134 fc.level = ex_nesting_level;
20135 /* Check if this function has a breakpoint. */
20136 fc.breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
20137 fc.dbg_tick = debug_tick;
20140 * Note about using fc.fixvar[]: This is an array of FIXVAR_CNT variables
20141 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
20142 * each argument variable and saves a lot of time.
20145 * Init l: variables.
20147 init_var_dict(&fc.l_vars, &fc.l_vars_var);
20148 if (selfdict != NULL)
20150 /* Set l:self to "selfdict". Use "name" to avoid a warning from
20151 * some compiler that checks the destination size. */
20152 v = &fc.fixvar[fixvar_idx++].var;
20153 name = v->di_key;
20154 STRCPY(name, "self");
20155 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
20156 hash_add(&fc.l_vars.dv_hashtab, DI2HIKEY(v));
20157 v->di_tv.v_type = VAR_DICT;
20158 v->di_tv.v_lock = 0;
20159 v->di_tv.vval.v_dict = selfdict;
20160 ++selfdict->dv_refcount;
20164 * Init a: variables.
20165 * Set a:0 to "argcount".
20166 * Set a:000 to a list with room for the "..." arguments.
20168 init_var_dict(&fc.l_avars, &fc.l_avars_var);
20169 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "0",
20170 (varnumber_T)(argcount - fp->uf_args.ga_len));
20171 v = &fc.fixvar[fixvar_idx++].var;
20172 STRCPY(v->di_key, "000");
20173 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20174 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
20175 v->di_tv.v_type = VAR_LIST;
20176 v->di_tv.v_lock = VAR_FIXED;
20177 v->di_tv.vval.v_list = &fc.l_varlist;
20178 vim_memset(&fc.l_varlist, 0, sizeof(list_T));
20179 fc.l_varlist.lv_refcount = 99999;
20180 fc.l_varlist.lv_lock = VAR_FIXED;
20183 * Set a:firstline to "firstline" and a:lastline to "lastline".
20184 * Set a:name to named arguments.
20185 * Set a:N to the "..." arguments.
20187 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "firstline",
20188 (varnumber_T)firstline);
20189 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "lastline",
20190 (varnumber_T)lastline);
20191 for (i = 0; i < argcount; ++i)
20193 ai = i - fp->uf_args.ga_len;
20194 if (ai < 0)
20195 /* named argument a:name */
20196 name = FUNCARG(fp, i);
20197 else
20199 /* "..." argument a:1, a:2, etc. */
20200 sprintf((char *)numbuf, "%d", ai + 1);
20201 name = numbuf;
20203 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
20205 v = &fc.fixvar[fixvar_idx++].var;
20206 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20208 else
20210 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
20211 + STRLEN(name)));
20212 if (v == NULL)
20213 break;
20214 v->di_flags = DI_FLAGS_RO;
20216 STRCPY(v->di_key, name);
20217 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
20219 /* Note: the values are copied directly to avoid alloc/free.
20220 * "argvars" must have VAR_FIXED for v_lock. */
20221 v->di_tv = argvars[i];
20222 v->di_tv.v_lock = VAR_FIXED;
20224 if (ai >= 0 && ai < MAX_FUNC_ARGS)
20226 list_append(&fc.l_varlist, &fc.l_listitems[ai]);
20227 fc.l_listitems[ai].li_tv = argvars[i];
20228 fc.l_listitems[ai].li_tv.v_lock = VAR_FIXED;
20232 /* Don't redraw while executing the function. */
20233 ++RedrawingDisabled;
20234 save_sourcing_name = sourcing_name;
20235 save_sourcing_lnum = sourcing_lnum;
20236 sourcing_lnum = 1;
20237 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
20238 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
20239 if (sourcing_name != NULL)
20241 if (save_sourcing_name != NULL
20242 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
20243 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
20244 else
20245 STRCPY(sourcing_name, "function ");
20246 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
20248 if (p_verbose >= 12)
20250 ++no_wait_return;
20251 verbose_enter_scroll();
20253 smsg((char_u *)_("calling %s"), sourcing_name);
20254 if (p_verbose >= 14)
20256 char_u buf[MSG_BUF_LEN];
20257 char_u numbuf2[NUMBUFLEN];
20258 char_u *tofree;
20259 char_u *s;
20261 msg_puts((char_u *)"(");
20262 for (i = 0; i < argcount; ++i)
20264 if (i > 0)
20265 msg_puts((char_u *)", ");
20266 if (argvars[i].v_type == VAR_NUMBER)
20267 msg_outnum((long)argvars[i].vval.v_number);
20268 else
20270 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
20271 if (s != NULL)
20273 trunc_string(s, buf, MSG_BUF_CLEN);
20274 msg_puts(buf);
20275 vim_free(tofree);
20279 msg_puts((char_u *)")");
20281 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20283 verbose_leave_scroll();
20284 --no_wait_return;
20287 #ifdef FEAT_PROFILE
20288 if (do_profiling == PROF_YES)
20290 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
20291 func_do_profile(fp);
20292 if (fp->uf_profiling
20293 || (fc.caller != NULL && &fc.caller->func->uf_profiling))
20295 ++fp->uf_tm_count;
20296 profile_start(&call_start);
20297 profile_zero(&fp->uf_tm_children);
20299 script_prof_save(&wait_start);
20301 #endif
20303 save_current_SID = current_SID;
20304 current_SID = fp->uf_script_ID;
20305 save_did_emsg = did_emsg;
20306 did_emsg = FALSE;
20308 /* call do_cmdline() to execute the lines */
20309 do_cmdline(NULL, get_func_line, (void *)&fc,
20310 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
20312 --RedrawingDisabled;
20314 /* when the function was aborted because of an error, return -1 */
20315 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
20317 clear_tv(rettv);
20318 rettv->v_type = VAR_NUMBER;
20319 rettv->vval.v_number = -1;
20322 #ifdef FEAT_PROFILE
20323 if (do_profiling == PROF_YES && (fp->uf_profiling
20324 || (fc.caller != NULL && &fc.caller->func->uf_profiling)))
20326 profile_end(&call_start);
20327 profile_sub_wait(&wait_start, &call_start);
20328 profile_add(&fp->uf_tm_total, &call_start);
20329 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
20330 if (fc.caller != NULL && &fc.caller->func->uf_profiling)
20332 profile_add(&fc.caller->func->uf_tm_children, &call_start);
20333 profile_add(&fc.caller->func->uf_tml_children, &call_start);
20336 #endif
20338 /* when being verbose, mention the return value */
20339 if (p_verbose >= 12)
20341 ++no_wait_return;
20342 verbose_enter_scroll();
20344 if (aborting())
20345 smsg((char_u *)_("%s aborted"), sourcing_name);
20346 else if (fc.rettv->v_type == VAR_NUMBER)
20347 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
20348 (long)fc.rettv->vval.v_number);
20349 else
20351 char_u buf[MSG_BUF_LEN];
20352 char_u numbuf2[NUMBUFLEN];
20353 char_u *tofree;
20354 char_u *s;
20356 /* The value may be very long. Skip the middle part, so that we
20357 * have some idea how it starts and ends. smsg() would always
20358 * truncate it at the end. */
20359 s = tv2string(fc.rettv, &tofree, numbuf2, 0);
20360 if (s != NULL)
20362 trunc_string(s, buf, MSG_BUF_CLEN);
20363 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
20364 vim_free(tofree);
20367 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20369 verbose_leave_scroll();
20370 --no_wait_return;
20373 vim_free(sourcing_name);
20374 sourcing_name = save_sourcing_name;
20375 sourcing_lnum = save_sourcing_lnum;
20376 current_SID = save_current_SID;
20377 #ifdef FEAT_PROFILE
20378 if (do_profiling == PROF_YES)
20379 script_prof_restore(&wait_start);
20380 #endif
20382 if (p_verbose >= 12 && sourcing_name != NULL)
20384 ++no_wait_return;
20385 verbose_enter_scroll();
20387 smsg((char_u *)_("continuing in %s"), sourcing_name);
20388 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20390 verbose_leave_scroll();
20391 --no_wait_return;
20394 did_emsg |= save_did_emsg;
20395 current_funccal = fc.caller;
20397 /* The a: variables typevals were not alloced, only free the allocated
20398 * variables. */
20399 vars_clear_ext(&fc.l_avars.dv_hashtab, FALSE);
20401 vars_clear(&fc.l_vars.dv_hashtab); /* free all l: variables */
20402 --depth;
20406 * Add a number variable "name" to dict "dp" with value "nr".
20408 static void
20409 add_nr_var(dp, v, name, nr)
20410 dict_T *dp;
20411 dictitem_T *v;
20412 char *name;
20413 varnumber_T nr;
20415 STRCPY(v->di_key, name);
20416 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20417 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
20418 v->di_tv.v_type = VAR_NUMBER;
20419 v->di_tv.v_lock = VAR_FIXED;
20420 v->di_tv.vval.v_number = nr;
20424 * ":return [expr]"
20426 void
20427 ex_return(eap)
20428 exarg_T *eap;
20430 char_u *arg = eap->arg;
20431 typval_T rettv;
20432 int returning = FALSE;
20434 if (current_funccal == NULL)
20436 EMSG(_("E133: :return not inside a function"));
20437 return;
20440 if (eap->skip)
20441 ++emsg_skip;
20443 eap->nextcmd = NULL;
20444 if ((*arg != NUL && *arg != '|' && *arg != '\n')
20445 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
20447 if (!eap->skip)
20448 returning = do_return(eap, FALSE, TRUE, &rettv);
20449 else
20450 clear_tv(&rettv);
20452 /* It's safer to return also on error. */
20453 else if (!eap->skip)
20456 * Return unless the expression evaluation has been cancelled due to an
20457 * aborting error, an interrupt, or an exception.
20459 if (!aborting())
20460 returning = do_return(eap, FALSE, TRUE, NULL);
20463 /* When skipping or the return gets pending, advance to the next command
20464 * in this line (!returning). Otherwise, ignore the rest of the line.
20465 * Following lines will be ignored by get_func_line(). */
20466 if (returning)
20467 eap->nextcmd = NULL;
20468 else if (eap->nextcmd == NULL) /* no argument */
20469 eap->nextcmd = check_nextcmd(arg);
20471 if (eap->skip)
20472 --emsg_skip;
20476 * Return from a function. Possibly makes the return pending. Also called
20477 * for a pending return at the ":endtry" or after returning from an extra
20478 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
20479 * when called due to a ":return" command. "rettv" may point to a typval_T
20480 * with the return rettv. Returns TRUE when the return can be carried out,
20481 * FALSE when the return gets pending.
20484 do_return(eap, reanimate, is_cmd, rettv)
20485 exarg_T *eap;
20486 int reanimate;
20487 int is_cmd;
20488 void *rettv;
20490 int idx;
20491 struct condstack *cstack = eap->cstack;
20493 if (reanimate)
20494 /* Undo the return. */
20495 current_funccal->returned = FALSE;
20498 * Cleanup (and inactivate) conditionals, but stop when a try conditional
20499 * not in its finally clause (which then is to be executed next) is found.
20500 * In this case, make the ":return" pending for execution at the ":endtry".
20501 * Otherwise, return normally.
20503 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
20504 if (idx >= 0)
20506 cstack->cs_pending[idx] = CSTP_RETURN;
20508 if (!is_cmd && !reanimate)
20509 /* A pending return again gets pending. "rettv" points to an
20510 * allocated variable with the rettv of the original ":return"'s
20511 * argument if present or is NULL else. */
20512 cstack->cs_rettv[idx] = rettv;
20513 else
20515 /* When undoing a return in order to make it pending, get the stored
20516 * return rettv. */
20517 if (reanimate)
20518 rettv = current_funccal->rettv;
20520 if (rettv != NULL)
20522 /* Store the value of the pending return. */
20523 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
20524 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
20525 else
20526 EMSG(_(e_outofmem));
20528 else
20529 cstack->cs_rettv[idx] = NULL;
20531 if (reanimate)
20533 /* The pending return value could be overwritten by a ":return"
20534 * without argument in a finally clause; reset the default
20535 * return value. */
20536 current_funccal->rettv->v_type = VAR_NUMBER;
20537 current_funccal->rettv->vval.v_number = 0;
20540 report_make_pending(CSTP_RETURN, rettv);
20542 else
20544 current_funccal->returned = TRUE;
20546 /* If the return is carried out now, store the return value. For
20547 * a return immediately after reanimation, the value is already
20548 * there. */
20549 if (!reanimate && rettv != NULL)
20551 clear_tv(current_funccal->rettv);
20552 *current_funccal->rettv = *(typval_T *)rettv;
20553 if (!is_cmd)
20554 vim_free(rettv);
20558 return idx < 0;
20562 * Free the variable with a pending return value.
20564 void
20565 discard_pending_return(rettv)
20566 void *rettv;
20568 free_tv((typval_T *)rettv);
20572 * Generate a return command for producing the value of "rettv". The result
20573 * is an allocated string. Used by report_pending() for verbose messages.
20575 char_u *
20576 get_return_cmd(rettv)
20577 void *rettv;
20579 char_u *s = NULL;
20580 char_u *tofree = NULL;
20581 char_u numbuf[NUMBUFLEN];
20583 if (rettv != NULL)
20584 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
20585 if (s == NULL)
20586 s = (char_u *)"";
20588 STRCPY(IObuff, ":return ");
20589 STRNCPY(IObuff + 8, s, IOSIZE - 8);
20590 if (STRLEN(s) + 8 >= IOSIZE)
20591 STRCPY(IObuff + IOSIZE - 4, "...");
20592 vim_free(tofree);
20593 return vim_strsave(IObuff);
20597 * Get next function line.
20598 * Called by do_cmdline() to get the next line.
20599 * Returns allocated string, or NULL for end of function.
20601 /* ARGSUSED */
20602 char_u *
20603 get_func_line(c, cookie, indent)
20604 int c; /* not used */
20605 void *cookie;
20606 int indent; /* not used */
20608 funccall_T *fcp = (funccall_T *)cookie;
20609 ufunc_T *fp = fcp->func;
20610 char_u *retval;
20611 garray_T *gap; /* growarray with function lines */
20613 /* If breakpoints have been added/deleted need to check for it. */
20614 if (fcp->dbg_tick != debug_tick)
20616 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
20617 sourcing_lnum);
20618 fcp->dbg_tick = debug_tick;
20620 #ifdef FEAT_PROFILE
20621 if (do_profiling == PROF_YES)
20622 func_line_end(cookie);
20623 #endif
20625 gap = &fp->uf_lines;
20626 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
20627 || fcp->returned)
20628 retval = NULL;
20629 else
20631 /* Skip NULL lines (continuation lines). */
20632 while (fcp->linenr < gap->ga_len
20633 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
20634 ++fcp->linenr;
20635 if (fcp->linenr >= gap->ga_len)
20636 retval = NULL;
20637 else
20639 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
20640 sourcing_lnum = fcp->linenr;
20641 #ifdef FEAT_PROFILE
20642 if (do_profiling == PROF_YES)
20643 func_line_start(cookie);
20644 #endif
20648 /* Did we encounter a breakpoint? */
20649 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
20651 dbg_breakpoint(fp->uf_name, sourcing_lnum);
20652 /* Find next breakpoint. */
20653 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
20654 sourcing_lnum);
20655 fcp->dbg_tick = debug_tick;
20658 return retval;
20661 #if defined(FEAT_PROFILE) || defined(PROTO)
20663 * Called when starting to read a function line.
20664 * "sourcing_lnum" must be correct!
20665 * When skipping lines it may not actually be executed, but we won't find out
20666 * until later and we need to store the time now.
20668 void
20669 func_line_start(cookie)
20670 void *cookie;
20672 funccall_T *fcp = (funccall_T *)cookie;
20673 ufunc_T *fp = fcp->func;
20675 if (fp->uf_profiling && sourcing_lnum >= 1
20676 && sourcing_lnum <= fp->uf_lines.ga_len)
20678 fp->uf_tml_idx = sourcing_lnum - 1;
20679 /* Skip continuation lines. */
20680 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
20681 --fp->uf_tml_idx;
20682 fp->uf_tml_execed = FALSE;
20683 profile_start(&fp->uf_tml_start);
20684 profile_zero(&fp->uf_tml_children);
20685 profile_get_wait(&fp->uf_tml_wait);
20690 * Called when actually executing a function line.
20692 void
20693 func_line_exec(cookie)
20694 void *cookie;
20696 funccall_T *fcp = (funccall_T *)cookie;
20697 ufunc_T *fp = fcp->func;
20699 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
20700 fp->uf_tml_execed = TRUE;
20704 * Called when done with a function line.
20706 void
20707 func_line_end(cookie)
20708 void *cookie;
20710 funccall_T *fcp = (funccall_T *)cookie;
20711 ufunc_T *fp = fcp->func;
20713 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
20715 if (fp->uf_tml_execed)
20717 ++fp->uf_tml_count[fp->uf_tml_idx];
20718 profile_end(&fp->uf_tml_start);
20719 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
20720 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
20721 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
20722 &fp->uf_tml_children);
20724 fp->uf_tml_idx = -1;
20727 #endif
20730 * Return TRUE if the currently active function should be ended, because a
20731 * return was encountered or an error occured. Used inside a ":while".
20734 func_has_ended(cookie)
20735 void *cookie;
20737 funccall_T *fcp = (funccall_T *)cookie;
20739 /* Ignore the "abort" flag if the abortion behavior has been changed due to
20740 * an error inside a try conditional. */
20741 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
20742 || fcp->returned);
20746 * return TRUE if cookie indicates a function which "abort"s on errors.
20749 func_has_abort(cookie)
20750 void *cookie;
20752 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
20755 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
20756 typedef enum
20758 VAR_FLAVOUR_DEFAULT,
20759 VAR_FLAVOUR_SESSION,
20760 VAR_FLAVOUR_VIMINFO
20761 } var_flavour_T;
20763 static var_flavour_T var_flavour __ARGS((char_u *varname));
20765 static var_flavour_T
20766 var_flavour(varname)
20767 char_u *varname;
20769 char_u *p = varname;
20771 if (ASCII_ISUPPER(*p))
20773 while (*(++p))
20774 if (ASCII_ISLOWER(*p))
20775 return VAR_FLAVOUR_SESSION;
20776 return VAR_FLAVOUR_VIMINFO;
20778 else
20779 return VAR_FLAVOUR_DEFAULT;
20781 #endif
20783 #if defined(FEAT_VIMINFO) || defined(PROTO)
20785 * Restore global vars that start with a capital from the viminfo file
20788 read_viminfo_varlist(virp, writing)
20789 vir_T *virp;
20790 int writing;
20792 char_u *tab;
20793 int is_string = FALSE;
20794 typval_T tv;
20796 if (!writing && (find_viminfo_parameter('!') != NULL))
20798 tab = vim_strchr(virp->vir_line + 1, '\t');
20799 if (tab != NULL)
20801 *tab++ = '\0'; /* isolate the variable name */
20802 if (*tab == 'S') /* string var */
20803 is_string = TRUE;
20805 tab = vim_strchr(tab, '\t');
20806 if (tab != NULL)
20808 if (is_string)
20810 tv.v_type = VAR_STRING;
20811 tv.vval.v_string = viminfo_readstring(virp,
20812 (int)(tab - virp->vir_line + 1), TRUE);
20814 else
20816 tv.v_type = VAR_NUMBER;
20817 tv.vval.v_number = atol((char *)tab + 1);
20819 set_var(virp->vir_line + 1, &tv, FALSE);
20820 if (is_string)
20821 vim_free(tv.vval.v_string);
20826 return viminfo_readline(virp);
20830 * Write global vars that start with a capital to the viminfo file
20832 void
20833 write_viminfo_varlist(fp)
20834 FILE *fp;
20836 hashitem_T *hi;
20837 dictitem_T *this_var;
20838 int todo;
20839 char *s;
20840 char_u *p;
20841 char_u *tofree;
20842 char_u numbuf[NUMBUFLEN];
20844 if (find_viminfo_parameter('!') == NULL)
20845 return;
20847 fprintf(fp, _("\n# global variables:\n"));
20849 todo = (int)globvarht.ht_used;
20850 for (hi = globvarht.ht_array; todo > 0; ++hi)
20852 if (!HASHITEM_EMPTY(hi))
20854 --todo;
20855 this_var = HI2DI(hi);
20856 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
20858 switch (this_var->di_tv.v_type)
20860 case VAR_STRING: s = "STR"; break;
20861 case VAR_NUMBER: s = "NUM"; break;
20862 default: continue;
20864 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
20865 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
20866 if (p != NULL)
20867 viminfo_writestring(fp, p);
20868 vim_free(tofree);
20873 #endif
20875 #if defined(FEAT_SESSION) || defined(PROTO)
20877 store_session_globals(fd)
20878 FILE *fd;
20880 hashitem_T *hi;
20881 dictitem_T *this_var;
20882 int todo;
20883 char_u *p, *t;
20885 todo = (int)globvarht.ht_used;
20886 for (hi = globvarht.ht_array; todo > 0; ++hi)
20888 if (!HASHITEM_EMPTY(hi))
20890 --todo;
20891 this_var = HI2DI(hi);
20892 if ((this_var->di_tv.v_type == VAR_NUMBER
20893 || this_var->di_tv.v_type == VAR_STRING)
20894 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
20896 /* Escape special characters with a backslash. Turn a LF and
20897 * CR into \n and \r. */
20898 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
20899 (char_u *)"\\\"\n\r");
20900 if (p == NULL) /* out of memory */
20901 break;
20902 for (t = p; *t != NUL; ++t)
20903 if (*t == '\n')
20904 *t = 'n';
20905 else if (*t == '\r')
20906 *t = 'r';
20907 if ((fprintf(fd, "let %s = %c%s%c",
20908 this_var->di_key,
20909 (this_var->di_tv.v_type == VAR_STRING) ? '"'
20910 : ' ',
20912 (this_var->di_tv.v_type == VAR_STRING) ? '"'
20913 : ' ') < 0)
20914 || put_eol(fd) == FAIL)
20916 vim_free(p);
20917 return FAIL;
20919 vim_free(p);
20923 return OK;
20925 #endif
20928 * Display script name where an item was last set.
20929 * Should only be invoked when 'verbose' is non-zero.
20931 void
20932 last_set_msg(scriptID)
20933 scid_T scriptID;
20935 char_u *p;
20937 if (scriptID != 0)
20939 p = home_replace_save(NULL, get_scriptname(scriptID));
20940 if (p != NULL)
20942 verbose_enter();
20943 MSG_PUTS(_("\n\tLast set from "));
20944 MSG_PUTS(p);
20945 vim_free(p);
20946 verbose_leave();
20951 #endif /* FEAT_EVAL */
20953 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
20956 #ifdef WIN3264
20958 * Functions for ":8" filename modifier: get 8.3 version of a filename.
20960 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
20961 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
20962 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
20965 * Get the short pathname of a file.
20966 * Returns 1 on success. *fnamelen is 0 for nonexistent path.
20968 static int
20969 get_short_pathname(fnamep, bufp, fnamelen)
20970 char_u **fnamep;
20971 char_u **bufp;
20972 int *fnamelen;
20974 int l,len;
20975 char_u *newbuf;
20977 len = *fnamelen;
20979 l = GetShortPathName(*fnamep, *fnamep, len);
20980 if (l > len - 1)
20982 /* If that doesn't work (not enough space), then save the string
20983 * and try again with a new buffer big enough
20985 newbuf = vim_strnsave(*fnamep, l);
20986 if (newbuf == NULL)
20987 return 0;
20989 vim_free(*bufp);
20990 *fnamep = *bufp = newbuf;
20992 l = GetShortPathName(*fnamep,*fnamep,l+1);
20994 /* Really should always succeed, as the buffer is big enough */
20997 *fnamelen = l;
20998 return 1;
21002 * Create a short path name. Returns the length of the buffer it needs.
21003 * Doesn't copy over the end of the buffer passed in.
21005 static int
21006 shortpath_for_invalid_fname(fname, bufp, fnamelen)
21007 char_u **fname;
21008 char_u **bufp;
21009 int *fnamelen;
21011 char_u *s, *p, *pbuf2, *pbuf3;
21012 char_u ch;
21013 int len, len2, plen, slen;
21015 /* Make a copy */
21016 len2 = *fnamelen;
21017 pbuf2 = vim_strnsave(*fname, len2);
21018 pbuf3 = NULL;
21020 s = pbuf2 + len2 - 1; /* Find the end */
21021 slen = 1;
21022 plen = len2;
21024 if (after_pathsep(pbuf2, s + 1))
21026 --s;
21027 ++slen;
21028 --plen;
21033 /* Go back one path-separator */
21034 while (s > pbuf2 && !after_pathsep(pbuf2, s + 1))
21036 --s;
21037 ++slen;
21038 --plen;
21040 if (s <= pbuf2)
21041 break;
21043 /* Remember the character that is about to be splatted */
21044 ch = *s;
21045 *s = 0; /* get_short_pathname requires a null-terminated string */
21047 /* Try it in situ */
21048 p = pbuf2;
21049 if (!get_short_pathname(&p, &pbuf3, &plen))
21051 vim_free(pbuf2);
21052 return -1;
21054 *s = ch; /* Preserve the string */
21055 } while (plen == 0);
21057 if (plen > 0)
21059 /* Remember the length of the new string. */
21060 *fnamelen = len = plen + slen;
21061 vim_free(*bufp);
21062 if (len > len2)
21064 /* If there's not enough space in the currently allocated string,
21065 * then copy it to a buffer big enough.
21067 *fname= *bufp = vim_strnsave(p, len);
21068 if (*fname == NULL)
21069 return -1;
21071 else
21073 /* Transfer pbuf2 to being the main buffer (it's big enough) */
21074 *fname = *bufp = pbuf2;
21075 if (p != pbuf2)
21076 strncpy(*fname, p, plen);
21077 pbuf2 = NULL;
21079 /* Concat the next bit */
21080 strncpy(*fname + plen, s, slen);
21081 (*fname)[len] = '\0';
21083 vim_free(pbuf3);
21084 vim_free(pbuf2);
21085 return 0;
21089 * Get a pathname for a partial path.
21091 static int
21092 shortpath_for_partial(fnamep, bufp, fnamelen)
21093 char_u **fnamep;
21094 char_u **bufp;
21095 int *fnamelen;
21097 int sepcount, len, tflen;
21098 char_u *p;
21099 char_u *pbuf, *tfname;
21100 int hasTilde;
21102 /* Count up the path seperators from the RHS.. so we know which part
21103 * of the path to return.
21105 sepcount = 0;
21106 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
21107 if (vim_ispathsep(*p))
21108 ++sepcount;
21110 /* Need full path first (use expand_env() to remove a "~/") */
21111 hasTilde = (**fnamep == '~');
21112 if (hasTilde)
21113 pbuf = tfname = expand_env_save(*fnamep);
21114 else
21115 pbuf = tfname = FullName_save(*fnamep, FALSE);
21117 len = tflen = (int)STRLEN(tfname);
21119 if (!get_short_pathname(&tfname, &pbuf, &len))
21120 return -1;
21122 if (len == 0)
21124 /* Don't have a valid filename, so shorten the rest of the
21125 * path if we can. This CAN give us invalid 8.3 filenames, but
21126 * there's not a lot of point in guessing what it might be.
21128 len = tflen;
21129 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == -1)
21130 return -1;
21133 /* Count the paths backward to find the beginning of the desired string. */
21134 for (p = tfname + len - 1; p >= tfname; --p)
21136 #ifdef FEAT_MBYTE
21137 if (has_mbyte)
21138 p -= mb_head_off(tfname, p);
21139 #endif
21140 if (vim_ispathsep(*p))
21142 if (sepcount == 0 || (hasTilde && sepcount == 1))
21143 break;
21144 else
21145 sepcount --;
21148 if (hasTilde)
21150 --p;
21151 if (p >= tfname)
21152 *p = '~';
21153 else
21154 return -1;
21156 else
21157 ++p;
21159 /* Copy in the string - p indexes into tfname - allocated at pbuf */
21160 vim_free(*bufp);
21161 *fnamelen = (int)STRLEN(p);
21162 *bufp = pbuf;
21163 *fnamep = p;
21165 return 0;
21167 #endif /* WIN3264 */
21170 * Adjust a filename, according to a string of modifiers.
21171 * *fnamep must be NUL terminated when called. When returning, the length is
21172 * determined by *fnamelen.
21173 * Returns valid flags.
21174 * When there is an error, *fnamep is set to NULL.
21177 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
21178 char_u *src; /* string with modifiers */
21179 int *usedlen; /* characters after src that are used */
21180 char_u **fnamep; /* file name so far */
21181 char_u **bufp; /* buffer for allocated file name or NULL */
21182 int *fnamelen; /* length of fnamep */
21184 int valid = 0;
21185 char_u *tail;
21186 char_u *s, *p, *pbuf;
21187 char_u dirname[MAXPATHL];
21188 int c;
21189 int has_fullname = 0;
21190 #ifdef WIN3264
21191 int has_shortname = 0;
21192 #endif
21194 repeat:
21195 /* ":p" - full path/file_name */
21196 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
21198 has_fullname = 1;
21200 valid |= VALID_PATH;
21201 *usedlen += 2;
21203 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
21204 if ((*fnamep)[0] == '~'
21205 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
21206 && ((*fnamep)[1] == '/'
21207 # ifdef BACKSLASH_IN_FILENAME
21208 || (*fnamep)[1] == '\\'
21209 # endif
21210 || (*fnamep)[1] == NUL)
21212 #endif
21215 *fnamep = expand_env_save(*fnamep);
21216 vim_free(*bufp); /* free any allocated file name */
21217 *bufp = *fnamep;
21218 if (*fnamep == NULL)
21219 return -1;
21222 /* When "/." or "/.." is used: force expansion to get rid of it. */
21223 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
21225 if (vim_ispathsep(*p)
21226 && p[1] == '.'
21227 && (p[2] == NUL
21228 || vim_ispathsep(p[2])
21229 || (p[2] == '.'
21230 && (p[3] == NUL || vim_ispathsep(p[3])))))
21231 break;
21234 /* FullName_save() is slow, don't use it when not needed. */
21235 if (*p != NUL || !vim_isAbsName(*fnamep))
21237 *fnamep = FullName_save(*fnamep, *p != NUL);
21238 vim_free(*bufp); /* free any allocated file name */
21239 *bufp = *fnamep;
21240 if (*fnamep == NULL)
21241 return -1;
21244 /* Append a path separator to a directory. */
21245 if (mch_isdir(*fnamep))
21247 /* Make room for one or two extra characters. */
21248 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
21249 vim_free(*bufp); /* free any allocated file name */
21250 *bufp = *fnamep;
21251 if (*fnamep == NULL)
21252 return -1;
21253 add_pathsep(*fnamep);
21257 /* ":." - path relative to the current directory */
21258 /* ":~" - path relative to the home directory */
21259 /* ":8" - shortname path - postponed till after */
21260 while (src[*usedlen] == ':'
21261 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
21263 *usedlen += 2;
21264 if (c == '8')
21266 #ifdef WIN3264
21267 has_shortname = 1; /* Postpone this. */
21268 #endif
21269 continue;
21271 pbuf = NULL;
21272 /* Need full path first (use expand_env() to remove a "~/") */
21273 if (!has_fullname)
21275 if (c == '.' && **fnamep == '~')
21276 p = pbuf = expand_env_save(*fnamep);
21277 else
21278 p = pbuf = FullName_save(*fnamep, FALSE);
21280 else
21281 p = *fnamep;
21283 has_fullname = 0;
21285 if (p != NULL)
21287 if (c == '.')
21289 mch_dirname(dirname, MAXPATHL);
21290 s = shorten_fname(p, dirname);
21291 if (s != NULL)
21293 *fnamep = s;
21294 if (pbuf != NULL)
21296 vim_free(*bufp); /* free any allocated file name */
21297 *bufp = pbuf;
21298 pbuf = NULL;
21302 else
21304 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
21305 /* Only replace it when it starts with '~' */
21306 if (*dirname == '~')
21308 s = vim_strsave(dirname);
21309 if (s != NULL)
21311 *fnamep = s;
21312 vim_free(*bufp);
21313 *bufp = s;
21317 vim_free(pbuf);
21321 tail = gettail(*fnamep);
21322 *fnamelen = (int)STRLEN(*fnamep);
21324 /* ":h" - head, remove "/file_name", can be repeated */
21325 /* Don't remove the first "/" or "c:\" */
21326 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
21328 valid |= VALID_HEAD;
21329 *usedlen += 2;
21330 s = get_past_head(*fnamep);
21331 while (tail > s && after_pathsep(s, tail))
21332 mb_ptr_back(*fnamep, tail);
21333 *fnamelen = (int)(tail - *fnamep);
21334 #ifdef VMS
21335 if (*fnamelen > 0)
21336 *fnamelen += 1; /* the path separator is part of the path */
21337 #endif
21338 if (*fnamelen == 0)
21340 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
21341 p = vim_strsave((char_u *)".");
21342 if (p == NULL)
21343 return -1;
21344 vim_free(*bufp);
21345 *bufp = *fnamep = tail = p;
21346 *fnamelen = 1;
21348 else
21350 while (tail > s && !after_pathsep(s, tail))
21351 mb_ptr_back(*fnamep, tail);
21355 /* ":8" - shortname */
21356 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
21358 *usedlen += 2;
21359 #ifdef WIN3264
21360 has_shortname = 1;
21361 #endif
21364 #ifdef WIN3264
21365 /* Check shortname after we have done 'heads' and before we do 'tails'
21367 if (has_shortname)
21369 pbuf = NULL;
21370 /* Copy the string if it is shortened by :h */
21371 if (*fnamelen < (int)STRLEN(*fnamep))
21373 p = vim_strnsave(*fnamep, *fnamelen);
21374 if (p == 0)
21375 return -1;
21376 vim_free(*bufp);
21377 *bufp = *fnamep = p;
21380 /* Split into two implementations - makes it easier. First is where
21381 * there isn't a full name already, second is where there is.
21383 if (!has_fullname && !vim_isAbsName(*fnamep))
21385 if (shortpath_for_partial(fnamep, bufp, fnamelen) == -1)
21386 return -1;
21388 else
21390 int l;
21392 /* Simple case, already have the full-name
21393 * Nearly always shorter, so try first time. */
21394 l = *fnamelen;
21395 if (!get_short_pathname(fnamep, bufp, &l))
21396 return -1;
21398 if (l == 0)
21400 /* Couldn't find the filename.. search the paths.
21402 l = *fnamelen;
21403 if (shortpath_for_invalid_fname(fnamep, bufp, &l ) == -1)
21404 return -1;
21406 *fnamelen = l;
21409 #endif /* WIN3264 */
21411 /* ":t" - tail, just the basename */
21412 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
21414 *usedlen += 2;
21415 *fnamelen -= (int)(tail - *fnamep);
21416 *fnamep = tail;
21419 /* ":e" - extension, can be repeated */
21420 /* ":r" - root, without extension, can be repeated */
21421 while (src[*usedlen] == ':'
21422 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
21424 /* find a '.' in the tail:
21425 * - for second :e: before the current fname
21426 * - otherwise: The last '.'
21428 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
21429 s = *fnamep - 2;
21430 else
21431 s = *fnamep + *fnamelen - 1;
21432 for ( ; s > tail; --s)
21433 if (s[0] == '.')
21434 break;
21435 if (src[*usedlen + 1] == 'e') /* :e */
21437 if (s > tail)
21439 *fnamelen += (int)(*fnamep - (s + 1));
21440 *fnamep = s + 1;
21441 #ifdef VMS
21442 /* cut version from the extension */
21443 s = *fnamep + *fnamelen - 1;
21444 for ( ; s > *fnamep; --s)
21445 if (s[0] == ';')
21446 break;
21447 if (s > *fnamep)
21448 *fnamelen = s - *fnamep;
21449 #endif
21451 else if (*fnamep <= tail)
21452 *fnamelen = 0;
21454 else /* :r */
21456 if (s > tail) /* remove one extension */
21457 *fnamelen = (int)(s - *fnamep);
21459 *usedlen += 2;
21462 /* ":s?pat?foo?" - substitute */
21463 /* ":gs?pat?foo?" - global substitute */
21464 if (src[*usedlen] == ':'
21465 && (src[*usedlen + 1] == 's'
21466 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
21468 char_u *str;
21469 char_u *pat;
21470 char_u *sub;
21471 int sep;
21472 char_u *flags;
21473 int didit = FALSE;
21475 flags = (char_u *)"";
21476 s = src + *usedlen + 2;
21477 if (src[*usedlen + 1] == 'g')
21479 flags = (char_u *)"g";
21480 ++s;
21483 sep = *s++;
21484 if (sep)
21486 /* find end of pattern */
21487 p = vim_strchr(s, sep);
21488 if (p != NULL)
21490 pat = vim_strnsave(s, (int)(p - s));
21491 if (pat != NULL)
21493 s = p + 1;
21494 /* find end of substitution */
21495 p = vim_strchr(s, sep);
21496 if (p != NULL)
21498 sub = vim_strnsave(s, (int)(p - s));
21499 str = vim_strnsave(*fnamep, *fnamelen);
21500 if (sub != NULL && str != NULL)
21502 *usedlen = (int)(p + 1 - src);
21503 s = do_string_sub(str, pat, sub, flags);
21504 if (s != NULL)
21506 *fnamep = s;
21507 *fnamelen = (int)STRLEN(s);
21508 vim_free(*bufp);
21509 *bufp = s;
21510 didit = TRUE;
21513 vim_free(sub);
21514 vim_free(str);
21516 vim_free(pat);
21519 /* after using ":s", repeat all the modifiers */
21520 if (didit)
21521 goto repeat;
21525 return valid;
21529 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
21530 * "flags" can be "g" to do a global substitute.
21531 * Returns an allocated string, NULL for error.
21533 char_u *
21534 do_string_sub(str, pat, sub, flags)
21535 char_u *str;
21536 char_u *pat;
21537 char_u *sub;
21538 char_u *flags;
21540 int sublen;
21541 regmatch_T regmatch;
21542 int i;
21543 int do_all;
21544 char_u *tail;
21545 garray_T ga;
21546 char_u *ret;
21547 char_u *save_cpo;
21549 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
21550 save_cpo = p_cpo;
21551 p_cpo = (char_u *)"";
21553 ga_init2(&ga, 1, 200);
21555 do_all = (flags[0] == 'g');
21557 regmatch.rm_ic = p_ic;
21558 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
21559 if (regmatch.regprog != NULL)
21561 tail = str;
21562 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
21565 * Get some space for a temporary buffer to do the substitution
21566 * into. It will contain:
21567 * - The text up to where the match is.
21568 * - The substituted text.
21569 * - The text after the match.
21571 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
21572 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
21573 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
21575 ga_clear(&ga);
21576 break;
21579 /* copy the text up to where the match is */
21580 i = (int)(regmatch.startp[0] - tail);
21581 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
21582 /* add the substituted text */
21583 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
21584 + ga.ga_len + i, TRUE, TRUE, FALSE);
21585 ga.ga_len += i + sublen - 1;
21586 /* avoid getting stuck on a match with an empty string */
21587 if (tail == regmatch.endp[0])
21589 if (*tail == NUL)
21590 break;
21591 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
21592 ++ga.ga_len;
21594 else
21596 tail = regmatch.endp[0];
21597 if (*tail == NUL)
21598 break;
21600 if (!do_all)
21601 break;
21604 if (ga.ga_data != NULL)
21605 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
21607 vim_free(regmatch.regprog);
21610 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
21611 ga_clear(&ga);
21612 p_cpo = save_cpo;
21614 return ret;
21617 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */