Deleted junk files.
[MacVim/jjgod.git] / src / eval.c
blob8b239f3b204907017e6954c85afeb52f1465cf46
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));
373 static void list_glob_vars __ARGS((void));
374 static void list_buf_vars __ARGS((void));
375 static void list_win_vars __ARGS((void));
376 #ifdef FEAT_WINDOWS
377 static void list_tab_vars __ARGS((void));
378 #endif
379 static void list_vim_vars __ARGS((void));
380 static void list_script_vars __ARGS((void));
381 static void list_func_vars __ARGS((void));
382 static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg));
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));
708 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string));
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 clear_tv(&vimvars[idx].vv_tv);
1322 vimvars[idx].vv_tv = *save_tv;
1323 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1325 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1326 if (HASHITEM_EMPTY(hi))
1327 EMSG2(_(e_intern2), "restore_vimvar()");
1328 else
1329 hash_remove(&vimvarht, hi);
1333 #if defined(FEAT_SPELL) || defined(PROTO)
1335 * Evaluate an expression to a list with suggestions.
1336 * For the "expr:" part of 'spellsuggest'.
1338 list_T *
1339 eval_spell_expr(badword, expr)
1340 char_u *badword;
1341 char_u *expr;
1343 typval_T save_val;
1344 typval_T rettv;
1345 list_T *list = NULL;
1346 char_u *p = skipwhite(expr);
1348 /* Set "v:val" to the bad word. */
1349 prepare_vimvar(VV_VAL, &save_val);
1350 vimvars[VV_VAL].vv_type = VAR_STRING;
1351 vimvars[VV_VAL].vv_str = badword;
1352 if (p_verbose == 0)
1353 ++emsg_off;
1355 if (eval1(&p, &rettv, TRUE) == OK)
1357 if (rettv.v_type != VAR_LIST)
1358 clear_tv(&rettv);
1359 else
1360 list = rettv.vval.v_list;
1363 if (p_verbose == 0)
1364 --emsg_off;
1365 vimvars[VV_VAL].vv_str = NULL;
1366 restore_vimvar(VV_VAL, &save_val);
1368 return list;
1372 * "list" is supposed to contain two items: a word and a number. Return the
1373 * word in "pp" and the number as the return value.
1374 * Return -1 if anything isn't right.
1375 * Used to get the good word and score from the eval_spell_expr() result.
1378 get_spellword(list, pp)
1379 list_T *list;
1380 char_u **pp;
1382 listitem_T *li;
1384 li = list->lv_first;
1385 if (li == NULL)
1386 return -1;
1387 *pp = get_tv_string(&li->li_tv);
1389 li = li->li_next;
1390 if (li == NULL)
1391 return -1;
1392 return get_tv_number(&li->li_tv);
1394 #endif
1397 * Top level evaluation function.
1398 * Returns an allocated typval_T with the result.
1399 * Returns NULL when there is an error.
1401 typval_T *
1402 eval_expr(arg, nextcmd)
1403 char_u *arg;
1404 char_u **nextcmd;
1406 typval_T *tv;
1408 tv = (typval_T *)alloc(sizeof(typval_T));
1409 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1411 vim_free(tv);
1412 tv = NULL;
1415 return tv;
1419 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1420 || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1422 * Call some vimL function and return the result in "*rettv".
1423 * Uses argv[argc] for the function arguments.
1424 * Returns OK or FAIL.
1426 static int
1427 call_vim_function(func, argc, argv, safe, rettv)
1428 char_u *func;
1429 int argc;
1430 char_u **argv;
1431 int safe; /* use the sandbox */
1432 typval_T *rettv;
1434 typval_T *argvars;
1435 long n;
1436 int len;
1437 int i;
1438 int doesrange;
1439 void *save_funccalp = NULL;
1440 int ret;
1442 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1443 if (argvars == NULL)
1444 return FAIL;
1446 for (i = 0; i < argc; i++)
1448 /* Pass a NULL or empty argument as an empty string */
1449 if (argv[i] == NULL || *argv[i] == NUL)
1451 argvars[i].v_type = VAR_STRING;
1452 argvars[i].vval.v_string = (char_u *)"";
1453 continue;
1456 /* Recognize a number argument, the others must be strings. */
1457 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1458 if (len != 0 && len == (int)STRLEN(argv[i]))
1460 argvars[i].v_type = VAR_NUMBER;
1461 argvars[i].vval.v_number = n;
1463 else
1465 argvars[i].v_type = VAR_STRING;
1466 argvars[i].vval.v_string = argv[i];
1470 if (safe)
1472 save_funccalp = save_funccal();
1473 ++sandbox;
1476 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1477 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1478 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1479 &doesrange, TRUE, NULL);
1480 if (safe)
1482 --sandbox;
1483 restore_funccal(save_funccalp);
1485 vim_free(argvars);
1487 if (ret == FAIL)
1488 clear_tv(rettv);
1490 return ret;
1493 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1495 * Call vimL function "func" and return the result as a string.
1496 * Returns NULL when calling the function fails.
1497 * Uses argv[argc] for the function arguments.
1499 void *
1500 call_func_retstr(func, argc, argv, safe)
1501 char_u *func;
1502 int argc;
1503 char_u **argv;
1504 int safe; /* use the sandbox */
1506 typval_T rettv;
1507 char_u *retval;
1509 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1510 return NULL;
1512 retval = vim_strsave(get_tv_string(&rettv));
1513 clear_tv(&rettv);
1514 return retval;
1516 # endif
1518 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1520 * Call vimL function "func" and return the result as a number.
1521 * Returns -1 when calling the function fails.
1522 * Uses argv[argc] for the function arguments.
1524 long
1525 call_func_retnr(func, argc, argv, safe)
1526 char_u *func;
1527 int argc;
1528 char_u **argv;
1529 int safe; /* use the sandbox */
1531 typval_T rettv;
1532 long retval;
1534 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1535 return -1;
1537 retval = get_tv_number_chk(&rettv, NULL);
1538 clear_tv(&rettv);
1539 return retval;
1541 # endif
1544 * Call vimL function "func" and return the result as a list
1545 * Uses argv[argc] for the function arguments.
1547 void *
1548 call_func_retlist(func, argc, argv, safe)
1549 char_u *func;
1550 int argc;
1551 char_u **argv;
1552 int safe; /* use the sandbox */
1554 typval_T rettv;
1556 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1557 return NULL;
1559 if (rettv.v_type != VAR_LIST)
1561 clear_tv(&rettv);
1562 return NULL;
1565 return rettv.vval.v_list;
1567 #endif
1571 * Save the current function call pointer, and set it to NULL.
1572 * Used when executing autocommands and for ":source".
1574 void *
1575 save_funccal()
1577 funccall_T *fc = current_funccal;
1579 current_funccal = NULL;
1580 return (void *)fc;
1583 void
1584 restore_funccal(vfc)
1585 void *vfc;
1587 funccall_T *fc = (funccall_T *)vfc;
1589 current_funccal = fc;
1592 #if defined(FEAT_PROFILE) || defined(PROTO)
1594 * Prepare profiling for entering a child or something else that is not
1595 * counted for the script/function itself.
1596 * Should always be called in pair with prof_child_exit().
1598 void
1599 prof_child_enter(tm)
1600 proftime_T *tm; /* place to store waittime */
1602 funccall_T *fc = current_funccal;
1604 if (fc != NULL && fc->func->uf_profiling)
1605 profile_start(&fc->prof_child);
1606 script_prof_save(tm);
1610 * Take care of time spent in a child.
1611 * Should always be called after prof_child_enter().
1613 void
1614 prof_child_exit(tm)
1615 proftime_T *tm; /* where waittime was stored */
1617 funccall_T *fc = current_funccal;
1619 if (fc != NULL && fc->func->uf_profiling)
1621 profile_end(&fc->prof_child);
1622 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1623 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1624 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1626 script_prof_restore(tm);
1628 #endif
1631 #ifdef FEAT_FOLDING
1633 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1634 * it in "*cp". Doesn't give error messages.
1637 eval_foldexpr(arg, cp)
1638 char_u *arg;
1639 int *cp;
1641 typval_T tv;
1642 int retval;
1643 char_u *s;
1644 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1645 OPT_LOCAL);
1647 ++emsg_off;
1648 if (use_sandbox)
1649 ++sandbox;
1650 ++textlock;
1651 *cp = NUL;
1652 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1653 retval = 0;
1654 else
1656 /* If the result is a number, just return the number. */
1657 if (tv.v_type == VAR_NUMBER)
1658 retval = tv.vval.v_number;
1659 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1660 retval = 0;
1661 else
1663 /* If the result is a string, check if there is a non-digit before
1664 * the number. */
1665 s = tv.vval.v_string;
1666 if (!VIM_ISDIGIT(*s) && *s != '-')
1667 *cp = *s++;
1668 retval = atol((char *)s);
1670 clear_tv(&tv);
1672 --emsg_off;
1673 if (use_sandbox)
1674 --sandbox;
1675 --textlock;
1677 return retval;
1679 #endif
1682 * ":let" list all variable values
1683 * ":let var1 var2" list variable values
1684 * ":let var = expr" assignment command.
1685 * ":let var += expr" assignment command.
1686 * ":let var -= expr" assignment command.
1687 * ":let var .= expr" assignment command.
1688 * ":let [var1, var2] = expr" unpack list.
1690 void
1691 ex_let(eap)
1692 exarg_T *eap;
1694 char_u *arg = eap->arg;
1695 char_u *expr = NULL;
1696 typval_T rettv;
1697 int i;
1698 int var_count = 0;
1699 int semicolon = 0;
1700 char_u op[2];
1701 char_u *argend;
1703 argend = skip_var_list(arg, &var_count, &semicolon);
1704 if (argend == NULL)
1705 return;
1706 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1707 --argend;
1708 expr = vim_strchr(argend, '=');
1709 if (expr == NULL)
1712 * ":let" without "=": list variables
1714 if (*arg == '[')
1715 EMSG(_(e_invarg));
1716 else if (!ends_excmd(*arg))
1717 /* ":let var1 var2" */
1718 arg = list_arg_vars(eap, arg);
1719 else if (!eap->skip)
1721 /* ":let" */
1722 list_glob_vars();
1723 list_buf_vars();
1724 list_win_vars();
1725 #ifdef FEAT_WINDOWS
1726 list_tab_vars();
1727 #endif
1728 list_script_vars();
1729 list_func_vars();
1730 list_vim_vars();
1732 eap->nextcmd = check_nextcmd(arg);
1734 else
1736 op[0] = '=';
1737 op[1] = NUL;
1738 if (expr > argend)
1740 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1741 op[0] = expr[-1]; /* +=, -= or .= */
1743 expr = skipwhite(expr + 1);
1745 if (eap->skip)
1746 ++emsg_skip;
1747 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1748 if (eap->skip)
1750 if (i != FAIL)
1751 clear_tv(&rettv);
1752 --emsg_skip;
1754 else if (i != FAIL)
1756 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1757 op);
1758 clear_tv(&rettv);
1764 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1765 * Handles both "var" with any type and "[var, var; var]" with a list type.
1766 * When "nextchars" is not NULL it points to a string with characters that
1767 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1768 * or concatenate.
1769 * Returns OK or FAIL;
1771 static int
1772 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1773 char_u *arg_start;
1774 typval_T *tv;
1775 int copy; /* copy values from "tv", don't move */
1776 int semicolon; /* from skip_var_list() */
1777 int var_count; /* from skip_var_list() */
1778 char_u *nextchars;
1780 char_u *arg = arg_start;
1781 list_T *l;
1782 int i;
1783 listitem_T *item;
1784 typval_T ltv;
1786 if (*arg != '[')
1789 * ":let var = expr" or ":for var in list"
1791 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1792 return FAIL;
1793 return OK;
1797 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1799 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1801 EMSG(_(e_listreq));
1802 return FAIL;
1805 i = list_len(l);
1806 if (semicolon == 0 && var_count < i)
1808 EMSG(_("E687: Less targets than List items"));
1809 return FAIL;
1811 if (var_count - semicolon > i)
1813 EMSG(_("E688: More targets than List items"));
1814 return FAIL;
1817 item = l->lv_first;
1818 while (*arg != ']')
1820 arg = skipwhite(arg + 1);
1821 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1822 item = item->li_next;
1823 if (arg == NULL)
1824 return FAIL;
1826 arg = skipwhite(arg);
1827 if (*arg == ';')
1829 /* Put the rest of the list (may be empty) in the var after ';'.
1830 * Create a new list for this. */
1831 l = list_alloc();
1832 if (l == NULL)
1833 return FAIL;
1834 while (item != NULL)
1836 list_append_tv(l, &item->li_tv);
1837 item = item->li_next;
1840 ltv.v_type = VAR_LIST;
1841 ltv.v_lock = 0;
1842 ltv.vval.v_list = l;
1843 l->lv_refcount = 1;
1845 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1846 (char_u *)"]", nextchars);
1847 clear_tv(&ltv);
1848 if (arg == NULL)
1849 return FAIL;
1850 break;
1852 else if (*arg != ',' && *arg != ']')
1854 EMSG2(_(e_intern2), "ex_let_vars()");
1855 return FAIL;
1859 return OK;
1863 * Skip over assignable variable "var" or list of variables "[var, var]".
1864 * Used for ":let varvar = expr" and ":for varvar in expr".
1865 * For "[var, var]" increment "*var_count" for each variable.
1866 * for "[var, var; var]" set "semicolon".
1867 * Return NULL for an error.
1869 static char_u *
1870 skip_var_list(arg, var_count, semicolon)
1871 char_u *arg;
1872 int *var_count;
1873 int *semicolon;
1875 char_u *p, *s;
1877 if (*arg == '[')
1879 /* "[var, var]": find the matching ']'. */
1880 p = arg;
1881 for (;;)
1883 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
1884 s = skip_var_one(p);
1885 if (s == p)
1887 EMSG2(_(e_invarg2), p);
1888 return NULL;
1890 ++*var_count;
1892 p = skipwhite(s);
1893 if (*p == ']')
1894 break;
1895 else if (*p == ';')
1897 if (*semicolon == 1)
1899 EMSG(_("Double ; in list of variables"));
1900 return NULL;
1902 *semicolon = 1;
1904 else if (*p != ',')
1906 EMSG2(_(e_invarg2), p);
1907 return NULL;
1910 return p + 1;
1912 else
1913 return skip_var_one(arg);
1917 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
1918 * l[idx].
1920 static char_u *
1921 skip_var_one(arg)
1922 char_u *arg;
1924 if (*arg == '@' && arg[1] != NUL)
1925 return arg + 2;
1926 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
1927 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1931 * List variables for hashtab "ht" with prefix "prefix".
1932 * If "empty" is TRUE also list NULL strings as empty strings.
1934 static void
1935 list_hashtable_vars(ht, prefix, empty)
1936 hashtab_T *ht;
1937 char_u *prefix;
1938 int empty;
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);
1959 * List global variables.
1961 static void
1962 list_glob_vars()
1964 list_hashtable_vars(&globvarht, (char_u *)"", TRUE);
1968 * List buffer variables.
1970 static void
1971 list_buf_vars()
1973 char_u numbuf[NUMBUFLEN];
1975 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:", TRUE);
1977 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
1978 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER, numbuf);
1982 * List window variables.
1984 static void
1985 list_win_vars()
1987 list_hashtable_vars(&curwin->w_vars.dv_hashtab, (char_u *)"w:", TRUE);
1990 #ifdef FEAT_WINDOWS
1992 * List tab page variables.
1994 static void
1995 list_tab_vars()
1997 list_hashtable_vars(&curtab->tp_vars.dv_hashtab, (char_u *)"t:", TRUE);
1999 #endif
2002 * List Vim variables.
2004 static void
2005 list_vim_vars()
2007 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE);
2011 * List script-local variables, if there is a script.
2013 static void
2014 list_script_vars()
2016 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2017 list_hashtable_vars(&SCRIPT_VARS(current_SID), (char_u *)"s:", FALSE);
2021 * List function variables, if there is a function.
2023 static void
2024 list_func_vars()
2026 if (current_funccal != NULL)
2027 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2028 (char_u *)"l:", FALSE);
2032 * List variables in "arg".
2034 static char_u *
2035 list_arg_vars(eap, arg)
2036 exarg_T *eap;
2037 char_u *arg;
2039 int error = FALSE;
2040 int len;
2041 char_u *name;
2042 char_u *name_start;
2043 char_u *arg_subsc;
2044 char_u *tofree;
2045 typval_T tv;
2047 while (!ends_excmd(*arg) && !got_int)
2049 if (error || eap->skip)
2051 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2052 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2054 emsg_severe = TRUE;
2055 EMSG(_(e_trailing));
2056 break;
2059 else
2061 /* get_name_len() takes care of expanding curly braces */
2062 name_start = name = arg;
2063 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2064 if (len <= 0)
2066 /* This is mainly to keep test 49 working: when expanding
2067 * curly braces fails overrule the exception error message. */
2068 if (len < 0 && !aborting())
2070 emsg_severe = TRUE;
2071 EMSG2(_(e_invarg2), arg);
2072 break;
2074 error = TRUE;
2076 else
2078 if (tofree != NULL)
2079 name = tofree;
2080 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2081 error = TRUE;
2082 else
2084 /* handle d.key, l[idx], f(expr) */
2085 arg_subsc = arg;
2086 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2087 error = TRUE;
2088 else
2090 if (arg == arg_subsc && len == 2 && name[1] == ':')
2092 switch (*name)
2094 case 'g': list_glob_vars(); break;
2095 case 'b': list_buf_vars(); break;
2096 case 'w': list_win_vars(); break;
2097 #ifdef FEAT_WINDOWS
2098 case 't': list_tab_vars(); break;
2099 #endif
2100 case 'v': list_vim_vars(); break;
2101 case 's': list_script_vars(); break;
2102 case 'l': list_func_vars(); break;
2103 default:
2104 EMSG2(_("E738: Can't list variables for %s"), name);
2107 else
2109 char_u numbuf[NUMBUFLEN];
2110 char_u *tf;
2111 int c;
2112 char_u *s;
2114 s = echo_string(&tv, &tf, numbuf, 0);
2115 c = *arg;
2116 *arg = NUL;
2117 list_one_var_a((char_u *)"",
2118 arg == arg_subsc ? name : name_start,
2119 tv.v_type, s == NULL ? (char_u *)"" : s);
2120 *arg = c;
2121 vim_free(tf);
2123 clear_tv(&tv);
2128 vim_free(tofree);
2131 arg = skipwhite(arg);
2134 return arg;
2138 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2139 * Returns a pointer to the char just after the var name.
2140 * Returns NULL if there is an error.
2142 static char_u *
2143 ex_let_one(arg, tv, copy, endchars, op)
2144 char_u *arg; /* points to variable name */
2145 typval_T *tv; /* value to assign to variable */
2146 int copy; /* copy value from "tv" */
2147 char_u *endchars; /* valid chars after variable name or NULL */
2148 char_u *op; /* "+", "-", "." or NULL*/
2150 int c1;
2151 char_u *name;
2152 char_u *p;
2153 char_u *arg_end = NULL;
2154 int len;
2155 int opt_flags;
2156 char_u *tofree = NULL;
2159 * ":let $VAR = expr": Set environment variable.
2161 if (*arg == '$')
2163 /* Find the end of the name. */
2164 ++arg;
2165 name = arg;
2166 len = get_env_len(&arg);
2167 if (len == 0)
2168 EMSG2(_(e_invarg2), name - 1);
2169 else
2171 if (op != NULL && (*op == '+' || *op == '-'))
2172 EMSG2(_(e_letwrong), op);
2173 else if (endchars != NULL
2174 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2175 EMSG(_(e_letunexp));
2176 else
2178 c1 = name[len];
2179 name[len] = NUL;
2180 p = get_tv_string_chk(tv);
2181 if (p != NULL && op != NULL && *op == '.')
2183 int mustfree = FALSE;
2184 char_u *s = vim_getenv(name, &mustfree);
2186 if (s != NULL)
2188 p = tofree = concat_str(s, p);
2189 if (mustfree)
2190 vim_free(s);
2193 if (p != NULL)
2195 vim_setenv(name, p);
2196 if (STRICMP(name, "HOME") == 0)
2197 init_homedir();
2198 else if (didset_vim && STRICMP(name, "VIM") == 0)
2199 didset_vim = FALSE;
2200 else if (didset_vimruntime
2201 && STRICMP(name, "VIMRUNTIME") == 0)
2202 didset_vimruntime = FALSE;
2203 arg_end = arg;
2205 name[len] = c1;
2206 vim_free(tofree);
2212 * ":let &option = expr": Set option value.
2213 * ":let &l:option = expr": Set local option value.
2214 * ":let &g:option = expr": Set global option value.
2216 else if (*arg == '&')
2218 /* Find the end of the name. */
2219 p = find_option_end(&arg, &opt_flags);
2220 if (p == NULL || (endchars != NULL
2221 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2222 EMSG(_(e_letunexp));
2223 else
2225 long n;
2226 int opt_type;
2227 long numval;
2228 char_u *stringval = NULL;
2229 char_u *s;
2231 c1 = *p;
2232 *p = NUL;
2234 n = get_tv_number(tv);
2235 s = get_tv_string_chk(tv); /* != NULL if number or string */
2236 if (s != NULL && op != NULL && *op != '=')
2238 opt_type = get_option_value(arg, &numval,
2239 &stringval, opt_flags);
2240 if ((opt_type == 1 && *op == '.')
2241 || (opt_type == 0 && *op != '.'))
2242 EMSG2(_(e_letwrong), op);
2243 else
2245 if (opt_type == 1) /* number */
2247 if (*op == '+')
2248 n = numval + n;
2249 else
2250 n = numval - n;
2252 else if (opt_type == 0 && stringval != NULL) /* string */
2254 s = concat_str(stringval, s);
2255 vim_free(stringval);
2256 stringval = s;
2260 if (s != NULL)
2262 set_option_value(arg, n, s, opt_flags);
2263 arg_end = p;
2265 *p = c1;
2266 vim_free(stringval);
2271 * ":let @r = expr": Set register contents.
2273 else if (*arg == '@')
2275 ++arg;
2276 if (op != NULL && (*op == '+' || *op == '-'))
2277 EMSG2(_(e_letwrong), op);
2278 else if (endchars != NULL
2279 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2280 EMSG(_(e_letunexp));
2281 else
2283 char_u *ptofree = NULL;
2284 char_u *s;
2286 p = get_tv_string_chk(tv);
2287 if (p != NULL && op != NULL && *op == '.')
2289 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2290 if (s != NULL)
2292 p = ptofree = concat_str(s, p);
2293 vim_free(s);
2296 if (p != NULL)
2298 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2299 arg_end = arg + 1;
2301 vim_free(ptofree);
2306 * ":let var = expr": Set internal variable.
2307 * ":let {expr} = expr": Idem, name made with curly braces
2309 else if (eval_isnamec1(*arg) || *arg == '{')
2311 lval_T lv;
2313 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2314 if (p != NULL && lv.ll_name != NULL)
2316 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2317 EMSG(_(e_letunexp));
2318 else
2320 set_var_lval(&lv, p, tv, copy, op);
2321 arg_end = p;
2324 clear_lval(&lv);
2327 else
2328 EMSG2(_(e_invarg2), arg);
2330 return arg_end;
2334 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2336 static int
2337 check_changedtick(arg)
2338 char_u *arg;
2340 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2342 EMSG2(_(e_readonlyvar), arg);
2343 return TRUE;
2345 return FALSE;
2349 * Get an lval: variable, Dict item or List item that can be assigned a value
2350 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2351 * "name.key", "name.key[expr]" etc.
2352 * Indexing only works if "name" is an existing List or Dictionary.
2353 * "name" points to the start of the name.
2354 * If "rettv" is not NULL it points to the value to be assigned.
2355 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2356 * wrong; must end in space or cmd separator.
2358 * Returns a pointer to just after the name, including indexes.
2359 * When an evaluation error occurs "lp->ll_name" is NULL;
2360 * Returns NULL for a parsing error. Still need to free items in "lp"!
2362 static char_u *
2363 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2364 char_u *name;
2365 typval_T *rettv;
2366 lval_T *lp;
2367 int unlet;
2368 int skip;
2369 int quiet; /* don't give error messages */
2370 int fne_flags; /* flags for find_name_end() */
2372 char_u *p;
2373 char_u *expr_start, *expr_end;
2374 int cc;
2375 dictitem_T *v;
2376 typval_T var1;
2377 typval_T var2;
2378 int empty1 = FALSE;
2379 listitem_T *ni;
2380 char_u *key = NULL;
2381 int len;
2382 hashtab_T *ht;
2384 /* Clear everything in "lp". */
2385 vim_memset(lp, 0, sizeof(lval_T));
2387 if (skip)
2389 /* When skipping just find the end of the name. */
2390 lp->ll_name = name;
2391 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2394 /* Find the end of the name. */
2395 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2396 if (expr_start != NULL)
2398 /* Don't expand the name when we already know there is an error. */
2399 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2400 && *p != '[' && *p != '.')
2402 EMSG(_(e_trailing));
2403 return NULL;
2406 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2407 if (lp->ll_exp_name == NULL)
2409 /* Report an invalid expression in braces, unless the
2410 * expression evaluation has been cancelled due to an
2411 * aborting error, an interrupt, or an exception. */
2412 if (!aborting() && !quiet)
2414 emsg_severe = TRUE;
2415 EMSG2(_(e_invarg2), name);
2416 return NULL;
2419 lp->ll_name = lp->ll_exp_name;
2421 else
2422 lp->ll_name = name;
2424 /* Without [idx] or .key we are done. */
2425 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2426 return p;
2428 cc = *p;
2429 *p = NUL;
2430 v = find_var(lp->ll_name, &ht);
2431 if (v == NULL && !quiet)
2432 EMSG2(_(e_undefvar), lp->ll_name);
2433 *p = cc;
2434 if (v == NULL)
2435 return NULL;
2438 * Loop until no more [idx] or .key is following.
2440 lp->ll_tv = &v->di_tv;
2441 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2443 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2444 && !(lp->ll_tv->v_type == VAR_DICT
2445 && lp->ll_tv->vval.v_dict != NULL))
2447 if (!quiet)
2448 EMSG(_("E689: Can only index a List or Dictionary"));
2449 return NULL;
2451 if (lp->ll_range)
2453 if (!quiet)
2454 EMSG(_("E708: [:] must come last"));
2455 return NULL;
2458 len = -1;
2459 if (*p == '.')
2461 key = p + 1;
2462 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2464 if (len == 0)
2466 if (!quiet)
2467 EMSG(_(e_emptykey));
2468 return NULL;
2470 p = key + len;
2472 else
2474 /* Get the index [expr] or the first index [expr: ]. */
2475 p = skipwhite(p + 1);
2476 if (*p == ':')
2477 empty1 = TRUE;
2478 else
2480 empty1 = FALSE;
2481 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2482 return NULL;
2483 if (get_tv_string_chk(&var1) == NULL)
2485 /* not a number or string */
2486 clear_tv(&var1);
2487 return NULL;
2491 /* Optionally get the second index [ :expr]. */
2492 if (*p == ':')
2494 if (lp->ll_tv->v_type == VAR_DICT)
2496 if (!quiet)
2497 EMSG(_(e_dictrange));
2498 if (!empty1)
2499 clear_tv(&var1);
2500 return NULL;
2502 if (rettv != NULL && (rettv->v_type != VAR_LIST
2503 || rettv->vval.v_list == NULL))
2505 if (!quiet)
2506 EMSG(_("E709: [:] requires a List value"));
2507 if (!empty1)
2508 clear_tv(&var1);
2509 return NULL;
2511 p = skipwhite(p + 1);
2512 if (*p == ']')
2513 lp->ll_empty2 = TRUE;
2514 else
2516 lp->ll_empty2 = FALSE;
2517 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2519 if (!empty1)
2520 clear_tv(&var1);
2521 return NULL;
2523 if (get_tv_string_chk(&var2) == NULL)
2525 /* not a number or string */
2526 if (!empty1)
2527 clear_tv(&var1);
2528 clear_tv(&var2);
2529 return NULL;
2532 lp->ll_range = TRUE;
2534 else
2535 lp->ll_range = FALSE;
2537 if (*p != ']')
2539 if (!quiet)
2540 EMSG(_(e_missbrac));
2541 if (!empty1)
2542 clear_tv(&var1);
2543 if (lp->ll_range && !lp->ll_empty2)
2544 clear_tv(&var2);
2545 return NULL;
2548 /* Skip to past ']'. */
2549 ++p;
2552 if (lp->ll_tv->v_type == VAR_DICT)
2554 if (len == -1)
2556 /* "[key]": get key from "var1" */
2557 key = get_tv_string(&var1); /* is number or string */
2558 if (*key == NUL)
2560 if (!quiet)
2561 EMSG(_(e_emptykey));
2562 clear_tv(&var1);
2563 return NULL;
2566 lp->ll_list = NULL;
2567 lp->ll_dict = lp->ll_tv->vval.v_dict;
2568 lp->ll_di = dict_find(lp->ll_dict, key, len);
2569 if (lp->ll_di == NULL)
2571 /* Key does not exist in dict: may need to add it. */
2572 if (*p == '[' || *p == '.' || unlet)
2574 if (!quiet)
2575 EMSG2(_(e_dictkey), key);
2576 if (len == -1)
2577 clear_tv(&var1);
2578 return NULL;
2580 if (len == -1)
2581 lp->ll_newkey = vim_strsave(key);
2582 else
2583 lp->ll_newkey = vim_strnsave(key, len);
2584 if (len == -1)
2585 clear_tv(&var1);
2586 if (lp->ll_newkey == NULL)
2587 p = NULL;
2588 break;
2590 if (len == -1)
2591 clear_tv(&var1);
2592 lp->ll_tv = &lp->ll_di->di_tv;
2594 else
2597 * Get the number and item for the only or first index of the List.
2599 if (empty1)
2600 lp->ll_n1 = 0;
2601 else
2603 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2604 clear_tv(&var1);
2606 lp->ll_dict = NULL;
2607 lp->ll_list = lp->ll_tv->vval.v_list;
2608 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2609 if (lp->ll_li == NULL)
2611 if (lp->ll_n1 < 0)
2613 lp->ll_n1 = 0;
2614 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2617 if (lp->ll_li == NULL)
2619 if (lp->ll_range && !lp->ll_empty2)
2620 clear_tv(&var2);
2621 return NULL;
2625 * May need to find the item or absolute index for the second
2626 * index of a range.
2627 * When no index given: "lp->ll_empty2" is TRUE.
2628 * Otherwise "lp->ll_n2" is set to the second index.
2630 if (lp->ll_range && !lp->ll_empty2)
2632 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2633 clear_tv(&var2);
2634 if (lp->ll_n2 < 0)
2636 ni = list_find(lp->ll_list, lp->ll_n2);
2637 if (ni == NULL)
2638 return NULL;
2639 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2642 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2643 if (lp->ll_n1 < 0)
2644 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2645 if (lp->ll_n2 < lp->ll_n1)
2646 return NULL;
2649 lp->ll_tv = &lp->ll_li->li_tv;
2653 return p;
2657 * Clear lval "lp" that was filled by get_lval().
2659 static void
2660 clear_lval(lp)
2661 lval_T *lp;
2663 vim_free(lp->ll_exp_name);
2664 vim_free(lp->ll_newkey);
2668 * Set a variable that was parsed by get_lval() to "rettv".
2669 * "endp" points to just after the parsed name.
2670 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2672 static void
2673 set_var_lval(lp, endp, rettv, copy, op)
2674 lval_T *lp;
2675 char_u *endp;
2676 typval_T *rettv;
2677 int copy;
2678 char_u *op;
2680 int cc;
2681 listitem_T *ri;
2682 dictitem_T *di;
2684 if (lp->ll_tv == NULL)
2686 if (!check_changedtick(lp->ll_name))
2688 cc = *endp;
2689 *endp = NUL;
2690 if (op != NULL && *op != '=')
2692 typval_T tv;
2694 /* handle +=, -= and .= */
2695 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2696 &tv, TRUE) == OK)
2698 if (tv_op(&tv, rettv, op) == OK)
2699 set_var(lp->ll_name, &tv, FALSE);
2700 clear_tv(&tv);
2703 else
2704 set_var(lp->ll_name, rettv, copy);
2705 *endp = cc;
2708 else if (tv_check_lock(lp->ll_newkey == NULL
2709 ? lp->ll_tv->v_lock
2710 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2712 else if (lp->ll_range)
2715 * Assign the List values to the list items.
2717 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2719 if (op != NULL && *op != '=')
2720 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2721 else
2723 clear_tv(&lp->ll_li->li_tv);
2724 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2726 ri = ri->li_next;
2727 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2728 break;
2729 if (lp->ll_li->li_next == NULL)
2731 /* Need to add an empty item. */
2732 if (list_append_number(lp->ll_list, 0) == FAIL)
2734 ri = NULL;
2735 break;
2738 lp->ll_li = lp->ll_li->li_next;
2739 ++lp->ll_n1;
2741 if (ri != NULL)
2742 EMSG(_("E710: List value has more items than target"));
2743 else if (lp->ll_empty2
2744 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2745 : lp->ll_n1 != lp->ll_n2)
2746 EMSG(_("E711: List value has not enough items"));
2748 else
2751 * Assign to a List or Dictionary item.
2753 if (lp->ll_newkey != NULL)
2755 if (op != NULL && *op != '=')
2757 EMSG2(_(e_letwrong), op);
2758 return;
2761 /* Need to add an item to the Dictionary. */
2762 di = dictitem_alloc(lp->ll_newkey);
2763 if (di == NULL)
2764 return;
2765 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2767 vim_free(di);
2768 return;
2770 lp->ll_tv = &di->di_tv;
2772 else if (op != NULL && *op != '=')
2774 tv_op(lp->ll_tv, rettv, op);
2775 return;
2777 else
2778 clear_tv(lp->ll_tv);
2781 * Assign the value to the variable or list item.
2783 if (copy)
2784 copy_tv(rettv, lp->ll_tv);
2785 else
2787 *lp->ll_tv = *rettv;
2788 lp->ll_tv->v_lock = 0;
2789 init_tv(rettv);
2795 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2796 * Returns OK or FAIL.
2798 static int
2799 tv_op(tv1, tv2, op)
2800 typval_T *tv1;
2801 typval_T *tv2;
2802 char_u *op;
2804 long n;
2805 char_u numbuf[NUMBUFLEN];
2806 char_u *s;
2808 /* Can't do anything with a Funcref or a Dict on the right. */
2809 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2811 switch (tv1->v_type)
2813 case VAR_DICT:
2814 case VAR_FUNC:
2815 break;
2817 case VAR_LIST:
2818 if (*op != '+' || tv2->v_type != VAR_LIST)
2819 break;
2820 /* List += List */
2821 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2822 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2823 return OK;
2825 case VAR_NUMBER:
2826 case VAR_STRING:
2827 if (tv2->v_type == VAR_LIST)
2828 break;
2829 if (*op == '+' || *op == '-')
2831 /* nr += nr or nr -= nr*/
2832 n = get_tv_number(tv1);
2833 if (*op == '+')
2834 n += get_tv_number(tv2);
2835 else
2836 n -= get_tv_number(tv2);
2837 clear_tv(tv1);
2838 tv1->v_type = VAR_NUMBER;
2839 tv1->vval.v_number = n;
2841 else
2843 /* str .= str */
2844 s = get_tv_string(tv1);
2845 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2846 clear_tv(tv1);
2847 tv1->v_type = VAR_STRING;
2848 tv1->vval.v_string = s;
2850 return OK;
2854 EMSG2(_(e_letwrong), op);
2855 return FAIL;
2859 * Add a watcher to a list.
2861 static void
2862 list_add_watch(l, lw)
2863 list_T *l;
2864 listwatch_T *lw;
2866 lw->lw_next = l->lv_watch;
2867 l->lv_watch = lw;
2871 * Remove a watcher from a list.
2872 * No warning when it isn't found...
2874 static void
2875 list_rem_watch(l, lwrem)
2876 list_T *l;
2877 listwatch_T *lwrem;
2879 listwatch_T *lw, **lwp;
2881 lwp = &l->lv_watch;
2882 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2884 if (lw == lwrem)
2886 *lwp = lw->lw_next;
2887 break;
2889 lwp = &lw->lw_next;
2894 * Just before removing an item from a list: advance watchers to the next
2895 * item.
2897 static void
2898 list_fix_watch(l, item)
2899 list_T *l;
2900 listitem_T *item;
2902 listwatch_T *lw;
2904 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2905 if (lw->lw_item == item)
2906 lw->lw_item = item->li_next;
2910 * Evaluate the expression used in a ":for var in expr" command.
2911 * "arg" points to "var".
2912 * Set "*errp" to TRUE for an error, FALSE otherwise;
2913 * Return a pointer that holds the info. Null when there is an error.
2915 void *
2916 eval_for_line(arg, errp, nextcmdp, skip)
2917 char_u *arg;
2918 int *errp;
2919 char_u **nextcmdp;
2920 int skip;
2922 forinfo_T *fi;
2923 char_u *expr;
2924 typval_T tv;
2925 list_T *l;
2927 *errp = TRUE; /* default: there is an error */
2929 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
2930 if (fi == NULL)
2931 return NULL;
2933 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
2934 if (expr == NULL)
2935 return fi;
2937 expr = skipwhite(expr);
2938 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
2940 EMSG(_("E690: Missing \"in\" after :for"));
2941 return fi;
2944 if (skip)
2945 ++emsg_skip;
2946 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
2948 *errp = FALSE;
2949 if (!skip)
2951 l = tv.vval.v_list;
2952 if (tv.v_type != VAR_LIST || l == NULL)
2954 EMSG(_(e_listreq));
2955 clear_tv(&tv);
2957 else
2959 /* No need to increment the refcount, it's already set for the
2960 * list being used in "tv". */
2961 fi->fi_list = l;
2962 list_add_watch(l, &fi->fi_lw);
2963 fi->fi_lw.lw_item = l->lv_first;
2967 if (skip)
2968 --emsg_skip;
2970 return fi;
2974 * Use the first item in a ":for" list. Advance to the next.
2975 * Assign the values to the variable (list). "arg" points to the first one.
2976 * Return TRUE when a valid item was found, FALSE when at end of list or
2977 * something wrong.
2980 next_for_item(fi_void, arg)
2981 void *fi_void;
2982 char_u *arg;
2984 forinfo_T *fi = (forinfo_T *)fi_void;
2985 int result;
2986 listitem_T *item;
2988 item = fi->fi_lw.lw_item;
2989 if (item == NULL)
2990 result = FALSE;
2991 else
2993 fi->fi_lw.lw_item = item->li_next;
2994 result = (ex_let_vars(arg, &item->li_tv, TRUE,
2995 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
2997 return result;
3001 * Free the structure used to store info used by ":for".
3003 void
3004 free_for_info(fi_void)
3005 void *fi_void;
3007 forinfo_T *fi = (forinfo_T *)fi_void;
3009 if (fi != NULL && fi->fi_list != NULL)
3011 list_rem_watch(fi->fi_list, &fi->fi_lw);
3012 list_unref(fi->fi_list);
3014 vim_free(fi);
3017 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3019 void
3020 set_context_for_expression(xp, arg, cmdidx)
3021 expand_T *xp;
3022 char_u *arg;
3023 cmdidx_T cmdidx;
3025 int got_eq = FALSE;
3026 int c;
3027 char_u *p;
3029 if (cmdidx == CMD_let)
3031 xp->xp_context = EXPAND_USER_VARS;
3032 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3034 /* ":let var1 var2 ...": find last space. */
3035 for (p = arg + STRLEN(arg); p >= arg; )
3037 xp->xp_pattern = p;
3038 mb_ptr_back(arg, p);
3039 if (vim_iswhite(*p))
3040 break;
3042 return;
3045 else
3046 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3047 : EXPAND_EXPRESSION;
3048 while ((xp->xp_pattern = vim_strpbrk(arg,
3049 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3051 c = *xp->xp_pattern;
3052 if (c == '&')
3054 c = xp->xp_pattern[1];
3055 if (c == '&')
3057 ++xp->xp_pattern;
3058 xp->xp_context = cmdidx != CMD_let || got_eq
3059 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3061 else if (c != ' ')
3063 xp->xp_context = EXPAND_SETTINGS;
3064 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3065 xp->xp_pattern += 2;
3069 else if (c == '$')
3071 /* environment variable */
3072 xp->xp_context = EXPAND_ENV_VARS;
3074 else if (c == '=')
3076 got_eq = TRUE;
3077 xp->xp_context = EXPAND_EXPRESSION;
3079 else if (c == '<'
3080 && xp->xp_context == EXPAND_FUNCTIONS
3081 && vim_strchr(xp->xp_pattern, '(') == NULL)
3083 /* Function name can start with "<SNR>" */
3084 break;
3086 else if (cmdidx != CMD_let || got_eq)
3088 if (c == '"') /* string */
3090 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3091 if (c == '\\' && xp->xp_pattern[1] != NUL)
3092 ++xp->xp_pattern;
3093 xp->xp_context = EXPAND_NOTHING;
3095 else if (c == '\'') /* literal string */
3097 /* Trick: '' is like stopping and starting a literal string. */
3098 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3099 /* skip */ ;
3100 xp->xp_context = EXPAND_NOTHING;
3102 else if (c == '|')
3104 if (xp->xp_pattern[1] == '|')
3106 ++xp->xp_pattern;
3107 xp->xp_context = EXPAND_EXPRESSION;
3109 else
3110 xp->xp_context = EXPAND_COMMANDS;
3112 else
3113 xp->xp_context = EXPAND_EXPRESSION;
3115 else
3116 /* Doesn't look like something valid, expand as an expression
3117 * anyway. */
3118 xp->xp_context = EXPAND_EXPRESSION;
3119 arg = xp->xp_pattern;
3120 if (*arg != NUL)
3121 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3122 /* skip */ ;
3124 xp->xp_pattern = arg;
3127 #endif /* FEAT_CMDL_COMPL */
3130 * ":1,25call func(arg1, arg2)" function call.
3132 void
3133 ex_call(eap)
3134 exarg_T *eap;
3136 char_u *arg = eap->arg;
3137 char_u *startarg;
3138 char_u *name;
3139 char_u *tofree;
3140 int len;
3141 typval_T rettv;
3142 linenr_T lnum;
3143 int doesrange;
3144 int failed = FALSE;
3145 funcdict_T fudi;
3147 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3148 if (fudi.fd_newkey != NULL)
3150 /* Still need to give an error message for missing key. */
3151 EMSG2(_(e_dictkey), fudi.fd_newkey);
3152 vim_free(fudi.fd_newkey);
3154 if (tofree == NULL)
3155 return;
3157 /* Increase refcount on dictionary, it could get deleted when evaluating
3158 * the arguments. */
3159 if (fudi.fd_dict != NULL)
3160 ++fudi.fd_dict->dv_refcount;
3162 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3163 len = (int)STRLEN(tofree);
3164 name = deref_func_name(tofree, &len);
3166 /* Skip white space to allow ":call func ()". Not good, but required for
3167 * backward compatibility. */
3168 startarg = skipwhite(arg);
3169 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3171 if (*startarg != '(')
3173 EMSG2(_("E107: Missing braces: %s"), eap->arg);
3174 goto end;
3178 * When skipping, evaluate the function once, to find the end of the
3179 * arguments.
3180 * When the function takes a range, this is discovered after the first
3181 * call, and the loop is broken.
3183 if (eap->skip)
3185 ++emsg_skip;
3186 lnum = eap->line2; /* do it once, also with an invalid range */
3188 else
3189 lnum = eap->line1;
3190 for ( ; lnum <= eap->line2; ++lnum)
3192 if (!eap->skip && eap->addr_count > 0)
3194 curwin->w_cursor.lnum = lnum;
3195 curwin->w_cursor.col = 0;
3197 arg = startarg;
3198 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3199 eap->line1, eap->line2, &doesrange,
3200 !eap->skip, fudi.fd_dict) == FAIL)
3202 failed = TRUE;
3203 break;
3206 /* Handle a function returning a Funcref, Dictionary or List. */
3207 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3209 failed = TRUE;
3210 break;
3213 clear_tv(&rettv);
3214 if (doesrange || eap->skip)
3215 break;
3217 /* Stop when immediately aborting on error, or when an interrupt
3218 * occurred or an exception was thrown but not caught.
3219 * get_func_tv() returned OK, so that the check for trailing
3220 * characters below is executed. */
3221 if (aborting())
3222 break;
3224 if (eap->skip)
3225 --emsg_skip;
3227 if (!failed)
3229 /* Check for trailing illegal characters and a following command. */
3230 if (!ends_excmd(*arg))
3232 emsg_severe = TRUE;
3233 EMSG(_(e_trailing));
3235 else
3236 eap->nextcmd = check_nextcmd(arg);
3239 end:
3240 dict_unref(fudi.fd_dict);
3241 vim_free(tofree);
3245 * ":unlet[!] var1 ... " command.
3247 void
3248 ex_unlet(eap)
3249 exarg_T *eap;
3251 ex_unletlock(eap, eap->arg, 0);
3255 * ":lockvar" and ":unlockvar" commands
3257 void
3258 ex_lockvar(eap)
3259 exarg_T *eap;
3261 char_u *arg = eap->arg;
3262 int deep = 2;
3264 if (eap->forceit)
3265 deep = -1;
3266 else if (vim_isdigit(*arg))
3268 deep = getdigits(&arg);
3269 arg = skipwhite(arg);
3272 ex_unletlock(eap, arg, deep);
3276 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3278 static void
3279 ex_unletlock(eap, argstart, deep)
3280 exarg_T *eap;
3281 char_u *argstart;
3282 int deep;
3284 char_u *arg = argstart;
3285 char_u *name_end;
3286 int error = FALSE;
3287 lval_T lv;
3291 /* Parse the name and find the end. */
3292 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3293 FNE_CHECK_START);
3294 if (lv.ll_name == NULL)
3295 error = TRUE; /* error but continue parsing */
3296 if (name_end == NULL || (!vim_iswhite(*name_end)
3297 && !ends_excmd(*name_end)))
3299 if (name_end != NULL)
3301 emsg_severe = TRUE;
3302 EMSG(_(e_trailing));
3304 if (!(eap->skip || error))
3305 clear_lval(&lv);
3306 break;
3309 if (!error && !eap->skip)
3311 if (eap->cmdidx == CMD_unlet)
3313 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3314 error = TRUE;
3316 else
3318 if (do_lock_var(&lv, name_end, deep,
3319 eap->cmdidx == CMD_lockvar) == FAIL)
3320 error = TRUE;
3324 if (!eap->skip)
3325 clear_lval(&lv);
3327 arg = skipwhite(name_end);
3328 } while (!ends_excmd(*arg));
3330 eap->nextcmd = check_nextcmd(arg);
3333 static int
3334 do_unlet_var(lp, name_end, forceit)
3335 lval_T *lp;
3336 char_u *name_end;
3337 int forceit;
3339 int ret = OK;
3340 int cc;
3342 if (lp->ll_tv == NULL)
3344 cc = *name_end;
3345 *name_end = NUL;
3347 /* Normal name or expanded name. */
3348 if (check_changedtick(lp->ll_name))
3349 ret = FAIL;
3350 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3351 ret = FAIL;
3352 *name_end = cc;
3354 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3355 return FAIL;
3356 else if (lp->ll_range)
3358 listitem_T *li;
3360 /* Delete a range of List items. */
3361 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3363 li = lp->ll_li->li_next;
3364 listitem_remove(lp->ll_list, lp->ll_li);
3365 lp->ll_li = li;
3366 ++lp->ll_n1;
3369 else
3371 if (lp->ll_list != NULL)
3372 /* unlet a List item. */
3373 listitem_remove(lp->ll_list, lp->ll_li);
3374 else
3375 /* unlet a Dictionary item. */
3376 dictitem_remove(lp->ll_dict, lp->ll_di);
3379 return ret;
3383 * "unlet" a variable. Return OK if it existed, FAIL if not.
3384 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3387 do_unlet(name, forceit)
3388 char_u *name;
3389 int forceit;
3391 hashtab_T *ht;
3392 hashitem_T *hi;
3393 char_u *varname;
3395 ht = find_var_ht(name, &varname);
3396 if (ht != NULL && *varname != NUL)
3398 hi = hash_find(ht, varname);
3399 if (!HASHITEM_EMPTY(hi))
3401 if (var_check_fixed(HI2DI(hi)->di_flags, name))
3402 return FAIL;
3403 if (var_check_ro(HI2DI(hi)->di_flags, name))
3404 return FAIL;
3405 delete_var(ht, hi);
3406 return OK;
3409 if (forceit)
3410 return OK;
3411 EMSG2(_("E108: No such variable: \"%s\""), name);
3412 return FAIL;
3416 * Lock or unlock variable indicated by "lp".
3417 * "deep" is the levels to go (-1 for unlimited);
3418 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3420 static int
3421 do_lock_var(lp, name_end, deep, lock)
3422 lval_T *lp;
3423 char_u *name_end;
3424 int deep;
3425 int lock;
3427 int ret = OK;
3428 int cc;
3429 dictitem_T *di;
3431 if (deep == 0) /* nothing to do */
3432 return OK;
3434 if (lp->ll_tv == NULL)
3436 cc = *name_end;
3437 *name_end = NUL;
3439 /* Normal name or expanded name. */
3440 if (check_changedtick(lp->ll_name))
3441 ret = FAIL;
3442 else
3444 di = find_var(lp->ll_name, NULL);
3445 if (di == NULL)
3446 ret = FAIL;
3447 else
3449 if (lock)
3450 di->di_flags |= DI_FLAGS_LOCK;
3451 else
3452 di->di_flags &= ~DI_FLAGS_LOCK;
3453 item_lock(&di->di_tv, deep, lock);
3456 *name_end = cc;
3458 else if (lp->ll_range)
3460 listitem_T *li = lp->ll_li;
3462 /* (un)lock a range of List items. */
3463 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3465 item_lock(&li->li_tv, deep, lock);
3466 li = li->li_next;
3467 ++lp->ll_n1;
3470 else if (lp->ll_list != NULL)
3471 /* (un)lock a List item. */
3472 item_lock(&lp->ll_li->li_tv, deep, lock);
3473 else
3474 /* un(lock) a Dictionary item. */
3475 item_lock(&lp->ll_di->di_tv, deep, lock);
3477 return ret;
3481 * Lock or unlock an item. "deep" is nr of levels to go.
3483 static void
3484 item_lock(tv, deep, lock)
3485 typval_T *tv;
3486 int deep;
3487 int lock;
3489 static int recurse = 0;
3490 list_T *l;
3491 listitem_T *li;
3492 dict_T *d;
3493 hashitem_T *hi;
3494 int todo;
3496 if (recurse >= DICT_MAXNEST)
3498 EMSG(_("E743: variable nested too deep for (un)lock"));
3499 return;
3501 if (deep == 0)
3502 return;
3503 ++recurse;
3505 /* lock/unlock the item itself */
3506 if (lock)
3507 tv->v_lock |= VAR_LOCKED;
3508 else
3509 tv->v_lock &= ~VAR_LOCKED;
3511 switch (tv->v_type)
3513 case VAR_LIST:
3514 if ((l = tv->vval.v_list) != NULL)
3516 if (lock)
3517 l->lv_lock |= VAR_LOCKED;
3518 else
3519 l->lv_lock &= ~VAR_LOCKED;
3520 if (deep < 0 || deep > 1)
3521 /* recursive: lock/unlock the items the List contains */
3522 for (li = l->lv_first; li != NULL; li = li->li_next)
3523 item_lock(&li->li_tv, deep - 1, lock);
3525 break;
3526 case VAR_DICT:
3527 if ((d = tv->vval.v_dict) != NULL)
3529 if (lock)
3530 d->dv_lock |= VAR_LOCKED;
3531 else
3532 d->dv_lock &= ~VAR_LOCKED;
3533 if (deep < 0 || deep > 1)
3535 /* recursive: lock/unlock the items the List contains */
3536 todo = (int)d->dv_hashtab.ht_used;
3537 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3539 if (!HASHITEM_EMPTY(hi))
3541 --todo;
3542 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3548 --recurse;
3552 * Return TRUE if typeval "tv" is locked: Either tha value is locked itself or
3553 * it refers to a List or Dictionary that is locked.
3555 static int
3556 tv_islocked(tv)
3557 typval_T *tv;
3559 return (tv->v_lock & VAR_LOCKED)
3560 || (tv->v_type == VAR_LIST
3561 && tv->vval.v_list != NULL
3562 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3563 || (tv->v_type == VAR_DICT
3564 && tv->vval.v_dict != NULL
3565 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3568 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3570 * Delete all "menutrans_" variables.
3572 void
3573 del_menutrans_vars()
3575 hashitem_T *hi;
3576 int todo;
3578 hash_lock(&globvarht);
3579 todo = (int)globvarht.ht_used;
3580 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3582 if (!HASHITEM_EMPTY(hi))
3584 --todo;
3585 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3586 delete_var(&globvarht, hi);
3589 hash_unlock(&globvarht);
3591 #endif
3593 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3596 * Local string buffer for the next two functions to store a variable name
3597 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3598 * get_user_var_name().
3601 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3603 static char_u *varnamebuf = NULL;
3604 static int varnamebuflen = 0;
3607 * Function to concatenate a prefix and a variable name.
3609 static char_u *
3610 cat_prefix_varname(prefix, name)
3611 int prefix;
3612 char_u *name;
3614 int len;
3616 len = (int)STRLEN(name) + 3;
3617 if (len > varnamebuflen)
3619 vim_free(varnamebuf);
3620 len += 10; /* some additional space */
3621 varnamebuf = alloc(len);
3622 if (varnamebuf == NULL)
3624 varnamebuflen = 0;
3625 return NULL;
3627 varnamebuflen = len;
3629 *varnamebuf = prefix;
3630 varnamebuf[1] = ':';
3631 STRCPY(varnamebuf + 2, name);
3632 return varnamebuf;
3636 * Function given to ExpandGeneric() to obtain the list of user defined
3637 * (global/buffer/window/built-in) variable names.
3639 /*ARGSUSED*/
3640 char_u *
3641 get_user_var_name(xp, idx)
3642 expand_T *xp;
3643 int idx;
3645 static long_u gdone;
3646 static long_u bdone;
3647 static long_u wdone;
3648 #ifdef FEAT_WINDOWS
3649 static long_u tdone;
3650 #endif
3651 static int vidx;
3652 static hashitem_T *hi;
3653 hashtab_T *ht;
3655 if (idx == 0)
3657 gdone = bdone = wdone = vidx = 0;
3658 #ifdef FEAT_WINDOWS
3659 tdone = 0;
3660 #endif
3663 /* Global variables */
3664 if (gdone < globvarht.ht_used)
3666 if (gdone++ == 0)
3667 hi = globvarht.ht_array;
3668 else
3669 ++hi;
3670 while (HASHITEM_EMPTY(hi))
3671 ++hi;
3672 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3673 return cat_prefix_varname('g', hi->hi_key);
3674 return hi->hi_key;
3677 /* b: variables */
3678 ht = &curbuf->b_vars.dv_hashtab;
3679 if (bdone < ht->ht_used)
3681 if (bdone++ == 0)
3682 hi = ht->ht_array;
3683 else
3684 ++hi;
3685 while (HASHITEM_EMPTY(hi))
3686 ++hi;
3687 return cat_prefix_varname('b', hi->hi_key);
3689 if (bdone == ht->ht_used)
3691 ++bdone;
3692 return (char_u *)"b:changedtick";
3695 /* w: variables */
3696 ht = &curwin->w_vars.dv_hashtab;
3697 if (wdone < ht->ht_used)
3699 if (wdone++ == 0)
3700 hi = ht->ht_array;
3701 else
3702 ++hi;
3703 while (HASHITEM_EMPTY(hi))
3704 ++hi;
3705 return cat_prefix_varname('w', hi->hi_key);
3708 #ifdef FEAT_WINDOWS
3709 /* t: variables */
3710 ht = &curtab->tp_vars.dv_hashtab;
3711 if (tdone < ht->ht_used)
3713 if (tdone++ == 0)
3714 hi = ht->ht_array;
3715 else
3716 ++hi;
3717 while (HASHITEM_EMPTY(hi))
3718 ++hi;
3719 return cat_prefix_varname('t', hi->hi_key);
3721 #endif
3723 /* v: variables */
3724 if (vidx < VV_LEN)
3725 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3727 vim_free(varnamebuf);
3728 varnamebuf = NULL;
3729 varnamebuflen = 0;
3730 return NULL;
3733 #endif /* FEAT_CMDL_COMPL */
3736 * types for expressions.
3738 typedef enum
3740 TYPE_UNKNOWN = 0
3741 , TYPE_EQUAL /* == */
3742 , TYPE_NEQUAL /* != */
3743 , TYPE_GREATER /* > */
3744 , TYPE_GEQUAL /* >= */
3745 , TYPE_SMALLER /* < */
3746 , TYPE_SEQUAL /* <= */
3747 , TYPE_MATCH /* =~ */
3748 , TYPE_NOMATCH /* !~ */
3749 } exptype_T;
3752 * The "evaluate" argument: When FALSE, the argument is only parsed but not
3753 * executed. The function may return OK, but the rettv will be of type
3754 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
3758 * Handle zero level expression.
3759 * This calls eval1() and handles error message and nextcmd.
3760 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3761 * Note: "rettv.v_lock" is not set.
3762 * Return OK or FAIL.
3764 static int
3765 eval0(arg, rettv, nextcmd, evaluate)
3766 char_u *arg;
3767 typval_T *rettv;
3768 char_u **nextcmd;
3769 int evaluate;
3771 int ret;
3772 char_u *p;
3774 p = skipwhite(arg);
3775 ret = eval1(&p, rettv, evaluate);
3776 if (ret == FAIL || !ends_excmd(*p))
3778 if (ret != FAIL)
3779 clear_tv(rettv);
3781 * Report the invalid expression unless the expression evaluation has
3782 * been cancelled due to an aborting error, an interrupt, or an
3783 * exception.
3785 if (!aborting())
3786 EMSG2(_(e_invexpr2), arg);
3787 ret = FAIL;
3789 if (nextcmd != NULL)
3790 *nextcmd = check_nextcmd(p);
3792 return ret;
3796 * Handle top level expression:
3797 * expr1 ? expr0 : expr0
3799 * "arg" must point to the first non-white of the expression.
3800 * "arg" is advanced to the next non-white after the recognized expression.
3802 * Note: "rettv.v_lock" is not set.
3804 * Return OK or FAIL.
3806 static int
3807 eval1(arg, rettv, evaluate)
3808 char_u **arg;
3809 typval_T *rettv;
3810 int evaluate;
3812 int result;
3813 typval_T var2;
3816 * Get the first variable.
3818 if (eval2(arg, rettv, evaluate) == FAIL)
3819 return FAIL;
3821 if ((*arg)[0] == '?')
3823 result = FALSE;
3824 if (evaluate)
3826 int error = FALSE;
3828 if (get_tv_number_chk(rettv, &error) != 0)
3829 result = TRUE;
3830 clear_tv(rettv);
3831 if (error)
3832 return FAIL;
3836 * Get the second variable.
3838 *arg = skipwhite(*arg + 1);
3839 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
3840 return FAIL;
3843 * Check for the ":".
3845 if ((*arg)[0] != ':')
3847 EMSG(_("E109: Missing ':' after '?'"));
3848 if (evaluate && result)
3849 clear_tv(rettv);
3850 return FAIL;
3854 * Get the third variable.
3856 *arg = skipwhite(*arg + 1);
3857 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
3859 if (evaluate && result)
3860 clear_tv(rettv);
3861 return FAIL;
3863 if (evaluate && !result)
3864 *rettv = var2;
3867 return OK;
3871 * Handle first level expression:
3872 * expr2 || expr2 || expr2 logical OR
3874 * "arg" must point to the first non-white of the expression.
3875 * "arg" is advanced to the next non-white after the recognized expression.
3877 * Return OK or FAIL.
3879 static int
3880 eval2(arg, rettv, evaluate)
3881 char_u **arg;
3882 typval_T *rettv;
3883 int evaluate;
3885 typval_T var2;
3886 long result;
3887 int first;
3888 int error = FALSE;
3891 * Get the first variable.
3893 if (eval3(arg, rettv, evaluate) == FAIL)
3894 return FAIL;
3897 * Repeat until there is no following "||".
3899 first = TRUE;
3900 result = FALSE;
3901 while ((*arg)[0] == '|' && (*arg)[1] == '|')
3903 if (evaluate && first)
3905 if (get_tv_number_chk(rettv, &error) != 0)
3906 result = TRUE;
3907 clear_tv(rettv);
3908 if (error)
3909 return FAIL;
3910 first = FALSE;
3914 * Get the second variable.
3916 *arg = skipwhite(*arg + 2);
3917 if (eval3(arg, &var2, evaluate && !result) == FAIL)
3918 return FAIL;
3921 * Compute the result.
3923 if (evaluate && !result)
3925 if (get_tv_number_chk(&var2, &error) != 0)
3926 result = TRUE;
3927 clear_tv(&var2);
3928 if (error)
3929 return FAIL;
3931 if (evaluate)
3933 rettv->v_type = VAR_NUMBER;
3934 rettv->vval.v_number = result;
3938 return OK;
3942 * Handle second level expression:
3943 * expr3 && expr3 && expr3 logical AND
3945 * "arg" must point to the first non-white of the expression.
3946 * "arg" is advanced to the next non-white after the recognized expression.
3948 * Return OK or FAIL.
3950 static int
3951 eval3(arg, rettv, evaluate)
3952 char_u **arg;
3953 typval_T *rettv;
3954 int evaluate;
3956 typval_T var2;
3957 long result;
3958 int first;
3959 int error = FALSE;
3962 * Get the first variable.
3964 if (eval4(arg, rettv, evaluate) == FAIL)
3965 return FAIL;
3968 * Repeat until there is no following "&&".
3970 first = TRUE;
3971 result = TRUE;
3972 while ((*arg)[0] == '&' && (*arg)[1] == '&')
3974 if (evaluate && first)
3976 if (get_tv_number_chk(rettv, &error) == 0)
3977 result = FALSE;
3978 clear_tv(rettv);
3979 if (error)
3980 return FAIL;
3981 first = FALSE;
3985 * Get the second variable.
3987 *arg = skipwhite(*arg + 2);
3988 if (eval4(arg, &var2, evaluate && result) == FAIL)
3989 return FAIL;
3992 * Compute the result.
3994 if (evaluate && result)
3996 if (get_tv_number_chk(&var2, &error) == 0)
3997 result = FALSE;
3998 clear_tv(&var2);
3999 if (error)
4000 return FAIL;
4002 if (evaluate)
4004 rettv->v_type = VAR_NUMBER;
4005 rettv->vval.v_number = result;
4009 return OK;
4013 * Handle third level expression:
4014 * var1 == var2
4015 * var1 =~ var2
4016 * var1 != var2
4017 * var1 !~ var2
4018 * var1 > var2
4019 * var1 >= var2
4020 * var1 < var2
4021 * var1 <= var2
4022 * var1 is var2
4023 * var1 isnot var2
4025 * "arg" must point to the first non-white of the expression.
4026 * "arg" is advanced to the next non-white after the recognized expression.
4028 * Return OK or FAIL.
4030 static int
4031 eval4(arg, rettv, evaluate)
4032 char_u **arg;
4033 typval_T *rettv;
4034 int evaluate;
4036 typval_T var2;
4037 char_u *p;
4038 int i;
4039 exptype_T type = TYPE_UNKNOWN;
4040 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4041 int len = 2;
4042 long n1, n2;
4043 char_u *s1, *s2;
4044 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4045 regmatch_T regmatch;
4046 int ic;
4047 char_u *save_cpo;
4050 * Get the first variable.
4052 if (eval5(arg, rettv, evaluate) == FAIL)
4053 return FAIL;
4055 p = *arg;
4056 switch (p[0])
4058 case '=': if (p[1] == '=')
4059 type = TYPE_EQUAL;
4060 else if (p[1] == '~')
4061 type = TYPE_MATCH;
4062 break;
4063 case '!': if (p[1] == '=')
4064 type = TYPE_NEQUAL;
4065 else if (p[1] == '~')
4066 type = TYPE_NOMATCH;
4067 break;
4068 case '>': if (p[1] != '=')
4070 type = TYPE_GREATER;
4071 len = 1;
4073 else
4074 type = TYPE_GEQUAL;
4075 break;
4076 case '<': if (p[1] != '=')
4078 type = TYPE_SMALLER;
4079 len = 1;
4081 else
4082 type = TYPE_SEQUAL;
4083 break;
4084 case 'i': if (p[1] == 's')
4086 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4087 len = 5;
4088 if (!vim_isIDc(p[len]))
4090 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4091 type_is = TRUE;
4094 break;
4098 * If there is a comparitive operator, use it.
4100 if (type != TYPE_UNKNOWN)
4102 /* extra question mark appended: ignore case */
4103 if (p[len] == '?')
4105 ic = TRUE;
4106 ++len;
4108 /* extra '#' appended: match case */
4109 else if (p[len] == '#')
4111 ic = FALSE;
4112 ++len;
4114 /* nothing appened: use 'ignorecase' */
4115 else
4116 ic = p_ic;
4119 * Get the second variable.
4121 *arg = skipwhite(p + len);
4122 if (eval5(arg, &var2, evaluate) == FAIL)
4124 clear_tv(rettv);
4125 return FAIL;
4128 if (evaluate)
4130 if (type_is && rettv->v_type != var2.v_type)
4132 /* For "is" a different type always means FALSE, for "notis"
4133 * it means TRUE. */
4134 n1 = (type == TYPE_NEQUAL);
4136 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4138 if (type_is)
4140 n1 = (rettv->v_type == var2.v_type
4141 && rettv->vval.v_list == var2.vval.v_list);
4142 if (type == TYPE_NEQUAL)
4143 n1 = !n1;
4145 else if (rettv->v_type != var2.v_type
4146 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4148 if (rettv->v_type != var2.v_type)
4149 EMSG(_("E691: Can only compare List with List"));
4150 else
4151 EMSG(_("E692: Invalid operation for Lists"));
4152 clear_tv(rettv);
4153 clear_tv(&var2);
4154 return FAIL;
4156 else
4158 /* Compare two Lists for being equal or unequal. */
4159 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
4160 if (type == TYPE_NEQUAL)
4161 n1 = !n1;
4165 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4167 if (type_is)
4169 n1 = (rettv->v_type == var2.v_type
4170 && rettv->vval.v_dict == var2.vval.v_dict);
4171 if (type == TYPE_NEQUAL)
4172 n1 = !n1;
4174 else if (rettv->v_type != var2.v_type
4175 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4177 if (rettv->v_type != var2.v_type)
4178 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4179 else
4180 EMSG(_("E736: Invalid operation for Dictionary"));
4181 clear_tv(rettv);
4182 clear_tv(&var2);
4183 return FAIL;
4185 else
4187 /* Compare two Dictionaries for being equal or unequal. */
4188 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4189 if (type == TYPE_NEQUAL)
4190 n1 = !n1;
4194 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4196 if (rettv->v_type != var2.v_type
4197 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4199 if (rettv->v_type != var2.v_type)
4200 EMSG(_("E693: Can only compare Funcref with Funcref"));
4201 else
4202 EMSG(_("E694: Invalid operation for Funcrefs"));
4203 clear_tv(rettv);
4204 clear_tv(&var2);
4205 return FAIL;
4207 else
4209 /* Compare two Funcrefs for being equal or unequal. */
4210 if (rettv->vval.v_string == NULL
4211 || var2.vval.v_string == NULL)
4212 n1 = FALSE;
4213 else
4214 n1 = STRCMP(rettv->vval.v_string,
4215 var2.vval.v_string) == 0;
4216 if (type == TYPE_NEQUAL)
4217 n1 = !n1;
4222 * If one of the two variables is a number, compare as a number.
4223 * When using "=~" or "!~", always compare as string.
4225 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4226 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4228 n1 = get_tv_number(rettv);
4229 n2 = get_tv_number(&var2);
4230 switch (type)
4232 case TYPE_EQUAL: n1 = (n1 == n2); break;
4233 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4234 case TYPE_GREATER: n1 = (n1 > n2); break;
4235 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4236 case TYPE_SMALLER: n1 = (n1 < n2); break;
4237 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4238 case TYPE_UNKNOWN:
4239 case TYPE_MATCH:
4240 case TYPE_NOMATCH: break; /* avoid gcc warning */
4243 else
4245 s1 = get_tv_string_buf(rettv, buf1);
4246 s2 = get_tv_string_buf(&var2, buf2);
4247 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4248 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4249 else
4250 i = 0;
4251 n1 = FALSE;
4252 switch (type)
4254 case TYPE_EQUAL: n1 = (i == 0); break;
4255 case TYPE_NEQUAL: n1 = (i != 0); break;
4256 case TYPE_GREATER: n1 = (i > 0); break;
4257 case TYPE_GEQUAL: n1 = (i >= 0); break;
4258 case TYPE_SMALLER: n1 = (i < 0); break;
4259 case TYPE_SEQUAL: n1 = (i <= 0); break;
4261 case TYPE_MATCH:
4262 case TYPE_NOMATCH:
4263 /* avoid 'l' flag in 'cpoptions' */
4264 save_cpo = p_cpo;
4265 p_cpo = (char_u *)"";
4266 regmatch.regprog = vim_regcomp(s2,
4267 RE_MAGIC + RE_STRING);
4268 regmatch.rm_ic = ic;
4269 if (regmatch.regprog != NULL)
4271 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4272 vim_free(regmatch.regprog);
4273 if (type == TYPE_NOMATCH)
4274 n1 = !n1;
4276 p_cpo = save_cpo;
4277 break;
4279 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4282 clear_tv(rettv);
4283 clear_tv(&var2);
4284 rettv->v_type = VAR_NUMBER;
4285 rettv->vval.v_number = n1;
4289 return OK;
4293 * Handle fourth level expression:
4294 * + number addition
4295 * - number subtraction
4296 * . string concatenation
4298 * "arg" must point to the first non-white of the expression.
4299 * "arg" is advanced to the next non-white after the recognized expression.
4301 * Return OK or FAIL.
4303 static int
4304 eval5(arg, rettv, evaluate)
4305 char_u **arg;
4306 typval_T *rettv;
4307 int evaluate;
4309 typval_T var2;
4310 typval_T var3;
4311 int op;
4312 long n1, n2;
4313 char_u *s1, *s2;
4314 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4315 char_u *p;
4318 * Get the first variable.
4320 if (eval6(arg, rettv, evaluate) == FAIL)
4321 return FAIL;
4324 * Repeat computing, until no '+', '-' or '.' is following.
4326 for (;;)
4328 op = **arg;
4329 if (op != '+' && op != '-' && op != '.')
4330 break;
4332 if (op != '+' || rettv->v_type != VAR_LIST)
4334 /* For "list + ...", an illegal use of the first operand as
4335 * a number cannot be determined before evaluating the 2nd
4336 * operand: if this is also a list, all is ok.
4337 * For "something . ...", "something - ..." or "non-list + ...",
4338 * we know that the first operand needs to be a string or number
4339 * without evaluating the 2nd operand. So check before to avoid
4340 * side effects after an error. */
4341 if (evaluate && get_tv_string_chk(rettv) == NULL)
4343 clear_tv(rettv);
4344 return FAIL;
4349 * Get the second variable.
4351 *arg = skipwhite(*arg + 1);
4352 if (eval6(arg, &var2, evaluate) == FAIL)
4354 clear_tv(rettv);
4355 return FAIL;
4358 if (evaluate)
4361 * Compute the result.
4363 if (op == '.')
4365 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4366 s2 = get_tv_string_buf_chk(&var2, buf2);
4367 if (s2 == NULL) /* type error ? */
4369 clear_tv(rettv);
4370 clear_tv(&var2);
4371 return FAIL;
4373 p = concat_str(s1, s2);
4374 clear_tv(rettv);
4375 rettv->v_type = VAR_STRING;
4376 rettv->vval.v_string = p;
4378 else if (op == '+' && rettv->v_type == VAR_LIST
4379 && var2.v_type == VAR_LIST)
4381 /* concatenate Lists */
4382 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4383 &var3) == FAIL)
4385 clear_tv(rettv);
4386 clear_tv(&var2);
4387 return FAIL;
4389 clear_tv(rettv);
4390 *rettv = var3;
4392 else
4394 int error = FALSE;
4396 n1 = get_tv_number_chk(rettv, &error);
4397 if (error)
4399 /* This can only happen for "list + non-list".
4400 * For "non-list + ..." or "something - ...", we returned
4401 * before evaluating the 2nd operand. */
4402 clear_tv(rettv);
4403 return FAIL;
4405 n2 = get_tv_number_chk(&var2, &error);
4406 if (error)
4408 clear_tv(rettv);
4409 clear_tv(&var2);
4410 return FAIL;
4412 clear_tv(rettv);
4413 if (op == '+')
4414 n1 = n1 + n2;
4415 else
4416 n1 = n1 - n2;
4417 rettv->v_type = VAR_NUMBER;
4418 rettv->vval.v_number = n1;
4420 clear_tv(&var2);
4423 return OK;
4427 * Handle fifth level expression:
4428 * * number multiplication
4429 * / number division
4430 * % number modulo
4432 * "arg" must point to the first non-white of the expression.
4433 * "arg" is advanced to the next non-white after the recognized expression.
4435 * Return OK or FAIL.
4437 static int
4438 eval6(arg, rettv, evaluate)
4439 char_u **arg;
4440 typval_T *rettv;
4441 int evaluate;
4443 typval_T var2;
4444 int op;
4445 long n1, n2;
4446 int error = FALSE;
4449 * Get the first variable.
4451 if (eval7(arg, rettv, evaluate) == FAIL)
4452 return FAIL;
4455 * Repeat computing, until no '*', '/' or '%' is following.
4457 for (;;)
4459 op = **arg;
4460 if (op != '*' && op != '/' && op != '%')
4461 break;
4463 if (evaluate)
4465 n1 = get_tv_number_chk(rettv, &error);
4466 clear_tv(rettv);
4467 if (error)
4468 return FAIL;
4470 else
4471 n1 = 0;
4474 * Get the second variable.
4476 *arg = skipwhite(*arg + 1);
4477 if (eval7(arg, &var2, evaluate) == FAIL)
4478 return FAIL;
4480 if (evaluate)
4482 n2 = get_tv_number_chk(&var2, &error);
4483 clear_tv(&var2);
4484 if (error)
4485 return FAIL;
4488 * Compute the result.
4490 if (op == '*')
4491 n1 = n1 * n2;
4492 else if (op == '/')
4494 if (n2 == 0) /* give an error message? */
4495 n1 = 0x7fffffffL;
4496 else
4497 n1 = n1 / n2;
4499 else
4501 if (n2 == 0) /* give an error message? */
4502 n1 = 0;
4503 else
4504 n1 = n1 % n2;
4506 rettv->v_type = VAR_NUMBER;
4507 rettv->vval.v_number = n1;
4511 return OK;
4515 * Handle sixth level expression:
4516 * number number constant
4517 * "string" string constant
4518 * 'string' literal string constant
4519 * &option-name option value
4520 * @r register contents
4521 * identifier variable value
4522 * function() function call
4523 * $VAR environment variable
4524 * (expression) nested expression
4525 * [expr, expr] List
4526 * {key: val, key: val} Dictionary
4528 * Also handle:
4529 * ! in front logical NOT
4530 * - in front unary minus
4531 * + in front unary plus (ignored)
4532 * trailing [] subscript in String or List
4533 * trailing .name entry in Dictionary
4535 * "arg" must point to the first non-white of the expression.
4536 * "arg" is advanced to the next non-white after the recognized expression.
4538 * Return OK or FAIL.
4540 static int
4541 eval7(arg, rettv, evaluate)
4542 char_u **arg;
4543 typval_T *rettv;
4544 int evaluate;
4546 long n;
4547 int len;
4548 char_u *s;
4549 int val;
4550 char_u *start_leader, *end_leader;
4551 int ret = OK;
4552 char_u *alias;
4555 * Initialise variable so that clear_tv() can't mistake this for a
4556 * string and free a string that isn't there.
4558 rettv->v_type = VAR_UNKNOWN;
4561 * Skip '!' and '-' characters. They are handled later.
4563 start_leader = *arg;
4564 while (**arg == '!' || **arg == '-' || **arg == '+')
4565 *arg = skipwhite(*arg + 1);
4566 end_leader = *arg;
4568 switch (**arg)
4571 * Number constant.
4573 case '0':
4574 case '1':
4575 case '2':
4576 case '3':
4577 case '4':
4578 case '5':
4579 case '6':
4580 case '7':
4581 case '8':
4582 case '9':
4583 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4584 *arg += len;
4585 if (evaluate)
4587 rettv->v_type = VAR_NUMBER;
4588 rettv->vval.v_number = n;
4590 break;
4593 * String constant: "string".
4595 case '"': ret = get_string_tv(arg, rettv, evaluate);
4596 break;
4599 * Literal string constant: 'str''ing'.
4601 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
4602 break;
4605 * List: [expr, expr]
4607 case '[': ret = get_list_tv(arg, rettv, evaluate);
4608 break;
4611 * Dictionary: {key: val, key: val}
4613 case '{': ret = get_dict_tv(arg, rettv, evaluate);
4614 break;
4617 * Option value: &name
4619 case '&': ret = get_option_tv(arg, rettv, evaluate);
4620 break;
4623 * Environment variable: $VAR.
4625 case '$': ret = get_env_tv(arg, rettv, evaluate);
4626 break;
4629 * Register contents: @r.
4631 case '@': ++*arg;
4632 if (evaluate)
4634 rettv->v_type = VAR_STRING;
4635 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4637 if (**arg != NUL)
4638 ++*arg;
4639 break;
4642 * nested expression: (expression).
4644 case '(': *arg = skipwhite(*arg + 1);
4645 ret = eval1(arg, rettv, evaluate); /* recursive! */
4646 if (**arg == ')')
4647 ++*arg;
4648 else if (ret == OK)
4650 EMSG(_("E110: Missing ')'"));
4651 clear_tv(rettv);
4652 ret = FAIL;
4654 break;
4656 default: ret = NOTDONE;
4657 break;
4660 if (ret == NOTDONE)
4663 * Must be a variable or function name.
4664 * Can also be a curly-braces kind of name: {expr}.
4666 s = *arg;
4667 len = get_name_len(arg, &alias, evaluate, TRUE);
4668 if (alias != NULL)
4669 s = alias;
4671 if (len <= 0)
4672 ret = FAIL;
4673 else
4675 if (**arg == '(') /* recursive! */
4677 /* If "s" is the name of a variable of type VAR_FUNC
4678 * use its contents. */
4679 s = deref_func_name(s, &len);
4681 /* Invoke the function. */
4682 ret = get_func_tv(s, len, rettv, arg,
4683 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
4684 &len, evaluate, NULL);
4685 /* Stop the expression evaluation when immediately
4686 * aborting on error, or when an interrupt occurred or
4687 * an exception was thrown but not caught. */
4688 if (aborting())
4690 if (ret == OK)
4691 clear_tv(rettv);
4692 ret = FAIL;
4695 else if (evaluate)
4696 ret = get_var_tv(s, len, rettv, TRUE);
4697 else
4698 ret = OK;
4701 if (alias != NULL)
4702 vim_free(alias);
4705 *arg = skipwhite(*arg);
4707 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
4708 * expr(expr). */
4709 if (ret == OK)
4710 ret = handle_subscript(arg, rettv, evaluate, TRUE);
4713 * Apply logical NOT and unary '-', from right to left, ignore '+'.
4715 if (ret == OK && evaluate && end_leader > start_leader)
4717 int error = FALSE;
4719 val = get_tv_number_chk(rettv, &error);
4720 if (error)
4722 clear_tv(rettv);
4723 ret = FAIL;
4725 else
4727 while (end_leader > start_leader)
4729 --end_leader;
4730 if (*end_leader == '!')
4731 val = !val;
4732 else if (*end_leader == '-')
4733 val = -val;
4735 clear_tv(rettv);
4736 rettv->v_type = VAR_NUMBER;
4737 rettv->vval.v_number = val;
4741 return ret;
4745 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
4746 * "*arg" points to the '[' or '.'.
4747 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
4749 static int
4750 eval_index(arg, rettv, evaluate, verbose)
4751 char_u **arg;
4752 typval_T *rettv;
4753 int evaluate;
4754 int verbose; /* give error messages */
4756 int empty1 = FALSE, empty2 = FALSE;
4757 typval_T var1, var2;
4758 long n1, n2 = 0;
4759 long len = -1;
4760 int range = FALSE;
4761 char_u *s;
4762 char_u *key = NULL;
4764 if (rettv->v_type == VAR_FUNC)
4766 if (verbose)
4767 EMSG(_("E695: Cannot index a Funcref"));
4768 return FAIL;
4771 if (**arg == '.')
4774 * dict.name
4776 key = *arg + 1;
4777 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
4779 if (len == 0)
4780 return FAIL;
4781 *arg = skipwhite(key + len);
4783 else
4786 * something[idx]
4788 * Get the (first) variable from inside the [].
4790 *arg = skipwhite(*arg + 1);
4791 if (**arg == ':')
4792 empty1 = TRUE;
4793 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
4794 return FAIL;
4795 else if (evaluate && get_tv_string_chk(&var1) == NULL)
4797 /* not a number or string */
4798 clear_tv(&var1);
4799 return FAIL;
4803 * Get the second variable from inside the [:].
4805 if (**arg == ':')
4807 range = TRUE;
4808 *arg = skipwhite(*arg + 1);
4809 if (**arg == ']')
4810 empty2 = TRUE;
4811 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
4813 if (!empty1)
4814 clear_tv(&var1);
4815 return FAIL;
4817 else if (evaluate && get_tv_string_chk(&var2) == NULL)
4819 /* not a number or string */
4820 if (!empty1)
4821 clear_tv(&var1);
4822 clear_tv(&var2);
4823 return FAIL;
4827 /* Check for the ']'. */
4828 if (**arg != ']')
4830 if (verbose)
4831 EMSG(_(e_missbrac));
4832 clear_tv(&var1);
4833 if (range)
4834 clear_tv(&var2);
4835 return FAIL;
4837 *arg = skipwhite(*arg + 1); /* skip the ']' */
4840 if (evaluate)
4842 n1 = 0;
4843 if (!empty1 && rettv->v_type != VAR_DICT)
4845 n1 = get_tv_number(&var1);
4846 clear_tv(&var1);
4848 if (range)
4850 if (empty2)
4851 n2 = -1;
4852 else
4854 n2 = get_tv_number(&var2);
4855 clear_tv(&var2);
4859 switch (rettv->v_type)
4861 case VAR_NUMBER:
4862 case VAR_STRING:
4863 s = get_tv_string(rettv);
4864 len = (long)STRLEN(s);
4865 if (range)
4867 /* The resulting variable is a substring. If the indexes
4868 * are out of range the result is empty. */
4869 if (n1 < 0)
4871 n1 = len + n1;
4872 if (n1 < 0)
4873 n1 = 0;
4875 if (n2 < 0)
4876 n2 = len + n2;
4877 else if (n2 >= len)
4878 n2 = len;
4879 if (n1 >= len || n2 < 0 || n1 > n2)
4880 s = NULL;
4881 else
4882 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
4884 else
4886 /* The resulting variable is a string of a single
4887 * character. If the index is too big or negative the
4888 * result is empty. */
4889 if (n1 >= len || n1 < 0)
4890 s = NULL;
4891 else
4892 s = vim_strnsave(s + n1, 1);
4894 clear_tv(rettv);
4895 rettv->v_type = VAR_STRING;
4896 rettv->vval.v_string = s;
4897 break;
4899 case VAR_LIST:
4900 len = list_len(rettv->vval.v_list);
4901 if (n1 < 0)
4902 n1 = len + n1;
4903 if (!empty1 && (n1 < 0 || n1 >= len))
4905 /* For a range we allow invalid values and return an empty
4906 * list. A list index out of range is an error. */
4907 if (!range)
4909 if (verbose)
4910 EMSGN(_(e_listidx), n1);
4911 return FAIL;
4913 n1 = len;
4915 if (range)
4917 list_T *l;
4918 listitem_T *item;
4920 if (n2 < 0)
4921 n2 = len + n2;
4922 else if (n2 >= len)
4923 n2 = len - 1;
4924 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
4925 n2 = -1;
4926 l = list_alloc();
4927 if (l == NULL)
4928 return FAIL;
4929 for (item = list_find(rettv->vval.v_list, n1);
4930 n1 <= n2; ++n1)
4932 if (list_append_tv(l, &item->li_tv) == FAIL)
4934 list_free(l, TRUE);
4935 return FAIL;
4937 item = item->li_next;
4939 clear_tv(rettv);
4940 rettv->v_type = VAR_LIST;
4941 rettv->vval.v_list = l;
4942 ++l->lv_refcount;
4944 else
4946 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
4947 clear_tv(rettv);
4948 *rettv = var1;
4950 break;
4952 case VAR_DICT:
4953 if (range)
4955 if (verbose)
4956 EMSG(_(e_dictrange));
4957 if (len == -1)
4958 clear_tv(&var1);
4959 return FAIL;
4962 dictitem_T *item;
4964 if (len == -1)
4966 key = get_tv_string(&var1);
4967 if (*key == NUL)
4969 if (verbose)
4970 EMSG(_(e_emptykey));
4971 clear_tv(&var1);
4972 return FAIL;
4976 item = dict_find(rettv->vval.v_dict, key, (int)len);
4978 if (item == NULL && verbose)
4979 EMSG2(_(e_dictkey), key);
4980 if (len == -1)
4981 clear_tv(&var1);
4982 if (item == NULL)
4983 return FAIL;
4985 copy_tv(&item->di_tv, &var1);
4986 clear_tv(rettv);
4987 *rettv = var1;
4989 break;
4993 return OK;
4997 * Get an option value.
4998 * "arg" points to the '&' or '+' before the option name.
4999 * "arg" is advanced to character after the option name.
5000 * Return OK or FAIL.
5002 static int
5003 get_option_tv(arg, rettv, evaluate)
5004 char_u **arg;
5005 typval_T *rettv; /* when NULL, only check if option exists */
5006 int evaluate;
5008 char_u *option_end;
5009 long numval;
5010 char_u *stringval;
5011 int opt_type;
5012 int c;
5013 int working = (**arg == '+'); /* has("+option") */
5014 int ret = OK;
5015 int opt_flags;
5018 * Isolate the option name and find its value.
5020 option_end = find_option_end(arg, &opt_flags);
5021 if (option_end == NULL)
5023 if (rettv != NULL)
5024 EMSG2(_("E112: Option name missing: %s"), *arg);
5025 return FAIL;
5028 if (!evaluate)
5030 *arg = option_end;
5031 return OK;
5034 c = *option_end;
5035 *option_end = NUL;
5036 opt_type = get_option_value(*arg, &numval,
5037 rettv == NULL ? NULL : &stringval, opt_flags);
5039 if (opt_type == -3) /* invalid name */
5041 if (rettv != NULL)
5042 EMSG2(_("E113: Unknown option: %s"), *arg);
5043 ret = FAIL;
5045 else if (rettv != NULL)
5047 if (opt_type == -2) /* hidden string option */
5049 rettv->v_type = VAR_STRING;
5050 rettv->vval.v_string = NULL;
5052 else if (opt_type == -1) /* hidden number option */
5054 rettv->v_type = VAR_NUMBER;
5055 rettv->vval.v_number = 0;
5057 else if (opt_type == 1) /* number option */
5059 rettv->v_type = VAR_NUMBER;
5060 rettv->vval.v_number = numval;
5062 else /* string option */
5064 rettv->v_type = VAR_STRING;
5065 rettv->vval.v_string = stringval;
5068 else if (working && (opt_type == -2 || opt_type == -1))
5069 ret = FAIL;
5071 *option_end = c; /* put back for error messages */
5072 *arg = option_end;
5074 return ret;
5078 * Allocate a variable for a string constant.
5079 * Return OK or FAIL.
5081 static int
5082 get_string_tv(arg, rettv, evaluate)
5083 char_u **arg;
5084 typval_T *rettv;
5085 int evaluate;
5087 char_u *p;
5088 char_u *name;
5089 int extra = 0;
5092 * Find the end of the string, skipping backslashed characters.
5094 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5096 if (*p == '\\' && p[1] != NUL)
5098 ++p;
5099 /* A "\<x>" form occupies at least 4 characters, and produces up
5100 * to 6 characters: reserve space for 2 extra */
5101 if (*p == '<')
5102 extra += 2;
5106 if (*p != '"')
5108 EMSG2(_("E114: Missing quote: %s"), *arg);
5109 return FAIL;
5112 /* If only parsing, set *arg and return here */
5113 if (!evaluate)
5115 *arg = p + 1;
5116 return OK;
5120 * Copy the string into allocated memory, handling backslashed
5121 * characters.
5123 name = alloc((unsigned)(p - *arg + extra));
5124 if (name == NULL)
5125 return FAIL;
5126 rettv->v_type = VAR_STRING;
5127 rettv->vval.v_string = name;
5129 for (p = *arg + 1; *p != NUL && *p != '"'; )
5131 if (*p == '\\')
5133 switch (*++p)
5135 case 'b': *name++ = BS; ++p; break;
5136 case 'e': *name++ = ESC; ++p; break;
5137 case 'f': *name++ = FF; ++p; break;
5138 case 'n': *name++ = NL; ++p; break;
5139 case 'r': *name++ = CAR; ++p; break;
5140 case 't': *name++ = TAB; ++p; break;
5142 case 'X': /* hex: "\x1", "\x12" */
5143 case 'x':
5144 case 'u': /* Unicode: "\u0023" */
5145 case 'U':
5146 if (vim_isxdigit(p[1]))
5148 int n, nr;
5149 int c = toupper(*p);
5151 if (c == 'X')
5152 n = 2;
5153 else
5154 n = 4;
5155 nr = 0;
5156 while (--n >= 0 && vim_isxdigit(p[1]))
5158 ++p;
5159 nr = (nr << 4) + hex2nr(*p);
5161 ++p;
5162 #ifdef FEAT_MBYTE
5163 /* For "\u" store the number according to
5164 * 'encoding'. */
5165 if (c != 'X')
5166 name += (*mb_char2bytes)(nr, name);
5167 else
5168 #endif
5169 *name++ = nr;
5171 break;
5173 /* octal: "\1", "\12", "\123" */
5174 case '0':
5175 case '1':
5176 case '2':
5177 case '3':
5178 case '4':
5179 case '5':
5180 case '6':
5181 case '7': *name = *p++ - '0';
5182 if (*p >= '0' && *p <= '7')
5184 *name = (*name << 3) + *p++ - '0';
5185 if (*p >= '0' && *p <= '7')
5186 *name = (*name << 3) + *p++ - '0';
5188 ++name;
5189 break;
5191 /* Special key, e.g.: "\<C-W>" */
5192 case '<': extra = trans_special(&p, name, TRUE);
5193 if (extra != 0)
5195 name += extra;
5196 break;
5198 /* FALLTHROUGH */
5200 default: MB_COPY_CHAR(p, name);
5201 break;
5204 else
5205 MB_COPY_CHAR(p, name);
5208 *name = NUL;
5209 *arg = p + 1;
5211 return OK;
5215 * Allocate a variable for a 'str''ing' constant.
5216 * Return OK or FAIL.
5218 static int
5219 get_lit_string_tv(arg, rettv, evaluate)
5220 char_u **arg;
5221 typval_T *rettv;
5222 int evaluate;
5224 char_u *p;
5225 char_u *str;
5226 int reduce = 0;
5229 * Find the end of the string, skipping ''.
5231 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5233 if (*p == '\'')
5235 if (p[1] != '\'')
5236 break;
5237 ++reduce;
5238 ++p;
5242 if (*p != '\'')
5244 EMSG2(_("E115: Missing quote: %s"), *arg);
5245 return FAIL;
5248 /* If only parsing return after setting "*arg" */
5249 if (!evaluate)
5251 *arg = p + 1;
5252 return OK;
5256 * Copy the string into allocated memory, handling '' to ' reduction.
5258 str = alloc((unsigned)((p - *arg) - reduce));
5259 if (str == NULL)
5260 return FAIL;
5261 rettv->v_type = VAR_STRING;
5262 rettv->vval.v_string = str;
5264 for (p = *arg + 1; *p != NUL; )
5266 if (*p == '\'')
5268 if (p[1] != '\'')
5269 break;
5270 ++p;
5272 MB_COPY_CHAR(p, str);
5274 *str = NUL;
5275 *arg = p + 1;
5277 return OK;
5281 * Allocate a variable for a List and fill it from "*arg".
5282 * Return OK or FAIL.
5284 static int
5285 get_list_tv(arg, rettv, evaluate)
5286 char_u **arg;
5287 typval_T *rettv;
5288 int evaluate;
5290 list_T *l = NULL;
5291 typval_T tv;
5292 listitem_T *item;
5294 if (evaluate)
5296 l = list_alloc();
5297 if (l == NULL)
5298 return FAIL;
5301 *arg = skipwhite(*arg + 1);
5302 while (**arg != ']' && **arg != NUL)
5304 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5305 goto failret;
5306 if (evaluate)
5308 item = listitem_alloc();
5309 if (item != NULL)
5311 item->li_tv = tv;
5312 item->li_tv.v_lock = 0;
5313 list_append(l, item);
5315 else
5316 clear_tv(&tv);
5319 if (**arg == ']')
5320 break;
5321 if (**arg != ',')
5323 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5324 goto failret;
5326 *arg = skipwhite(*arg + 1);
5329 if (**arg != ']')
5331 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5332 failret:
5333 if (evaluate)
5334 list_free(l, TRUE);
5335 return FAIL;
5338 *arg = skipwhite(*arg + 1);
5339 if (evaluate)
5341 rettv->v_type = VAR_LIST;
5342 rettv->vval.v_list = l;
5343 ++l->lv_refcount;
5346 return OK;
5350 * Allocate an empty header for a list.
5351 * Caller should take care of the reference count.
5353 list_T *
5354 list_alloc()
5356 list_T *l;
5358 l = (list_T *)alloc_clear(sizeof(list_T));
5359 if (l != NULL)
5361 /* Prepend the list to the list of lists for garbage collection. */
5362 if (first_list != NULL)
5363 first_list->lv_used_prev = l;
5364 l->lv_used_prev = NULL;
5365 l->lv_used_next = first_list;
5366 first_list = l;
5368 return l;
5372 * Allocate an empty list for a return value.
5373 * Returns OK or FAIL.
5375 static int
5376 rettv_list_alloc(rettv)
5377 typval_T *rettv;
5379 list_T *l = list_alloc();
5381 if (l == NULL)
5382 return FAIL;
5384 rettv->vval.v_list = l;
5385 rettv->v_type = VAR_LIST;
5386 ++l->lv_refcount;
5387 return OK;
5391 * Unreference a list: decrement the reference count and free it when it
5392 * becomes zero.
5394 void
5395 list_unref(l)
5396 list_T *l;
5398 if (l != NULL && --l->lv_refcount <= 0)
5399 list_free(l, TRUE);
5403 * Free a list, including all items it points to.
5404 * Ignores the reference count.
5406 void
5407 list_free(l, recurse)
5408 list_T *l;
5409 int recurse; /* Free Lists and Dictionaries recursively. */
5411 listitem_T *item;
5413 /* Remove the list from the list of lists for garbage collection. */
5414 if (l->lv_used_prev == NULL)
5415 first_list = l->lv_used_next;
5416 else
5417 l->lv_used_prev->lv_used_next = l->lv_used_next;
5418 if (l->lv_used_next != NULL)
5419 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5421 for (item = l->lv_first; item != NULL; item = l->lv_first)
5423 /* Remove the item before deleting it. */
5424 l->lv_first = item->li_next;
5425 if (recurse || (item->li_tv.v_type != VAR_LIST
5426 && item->li_tv.v_type != VAR_DICT))
5427 clear_tv(&item->li_tv);
5428 vim_free(item);
5430 vim_free(l);
5434 * Allocate a list item.
5436 static listitem_T *
5437 listitem_alloc()
5439 return (listitem_T *)alloc(sizeof(listitem_T));
5443 * Free a list item. Also clears the value. Does not notify watchers.
5445 static void
5446 listitem_free(item)
5447 listitem_T *item;
5449 clear_tv(&item->li_tv);
5450 vim_free(item);
5454 * Remove a list item from a List and free it. Also clears the value.
5456 static void
5457 listitem_remove(l, item)
5458 list_T *l;
5459 listitem_T *item;
5461 list_remove(l, item, item);
5462 listitem_free(item);
5466 * Get the number of items in a list.
5468 static long
5469 list_len(l)
5470 list_T *l;
5472 if (l == NULL)
5473 return 0L;
5474 return l->lv_len;
5478 * Return TRUE when two lists have exactly the same values.
5480 static int
5481 list_equal(l1, l2, ic)
5482 list_T *l1;
5483 list_T *l2;
5484 int ic; /* ignore case for strings */
5486 listitem_T *item1, *item2;
5488 if (l1 == l2)
5489 return TRUE;
5490 if (list_len(l1) != list_len(l2))
5491 return FALSE;
5493 for (item1 = l1->lv_first, item2 = l2->lv_first;
5494 item1 != NULL && item2 != NULL;
5495 item1 = item1->li_next, item2 = item2->li_next)
5496 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5497 return FALSE;
5498 return item1 == NULL && item2 == NULL;
5501 #if defined(FEAT_PYTHON) || defined(PROTO)
5503 * Return the dictitem that an entry in a hashtable points to.
5505 dictitem_T *
5506 dict_lookup(hi)
5507 hashitem_T *hi;
5509 return HI2DI(hi);
5511 #endif
5514 * Return TRUE when two dictionaries have exactly the same key/values.
5516 static int
5517 dict_equal(d1, d2, ic)
5518 dict_T *d1;
5519 dict_T *d2;
5520 int ic; /* ignore case for strings */
5522 hashitem_T *hi;
5523 dictitem_T *item2;
5524 int todo;
5526 if (d1 == d2)
5527 return TRUE;
5528 if (dict_len(d1) != dict_len(d2))
5529 return FALSE;
5531 todo = (int)d1->dv_hashtab.ht_used;
5532 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5534 if (!HASHITEM_EMPTY(hi))
5536 item2 = dict_find(d2, hi->hi_key, -1);
5537 if (item2 == NULL)
5538 return FALSE;
5539 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5540 return FALSE;
5541 --todo;
5544 return TRUE;
5548 * Return TRUE if "tv1" and "tv2" have the same value.
5549 * Compares the items just like "==" would compare them, but strings and
5550 * numbers are different.
5552 static int
5553 tv_equal(tv1, tv2, ic)
5554 typval_T *tv1;
5555 typval_T *tv2;
5556 int ic; /* ignore case */
5558 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5559 char_u *s1, *s2;
5560 static int recursive = 0; /* cach recursive loops */
5561 int r;
5563 if (tv1->v_type != tv2->v_type)
5564 return FALSE;
5565 /* Catch lists and dicts that have an endless loop by limiting
5566 * recursiveness to 1000. We guess they are equal then. */
5567 if (recursive >= 1000)
5568 return TRUE;
5570 switch (tv1->v_type)
5572 case VAR_LIST:
5573 ++recursive;
5574 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5575 --recursive;
5576 return r;
5578 case VAR_DICT:
5579 ++recursive;
5580 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5581 --recursive;
5582 return r;
5584 case VAR_FUNC:
5585 return (tv1->vval.v_string != NULL
5586 && tv2->vval.v_string != NULL
5587 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5589 case VAR_NUMBER:
5590 return tv1->vval.v_number == tv2->vval.v_number;
5592 case VAR_STRING:
5593 s1 = get_tv_string_buf(tv1, buf1);
5594 s2 = get_tv_string_buf(tv2, buf2);
5595 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5598 EMSG2(_(e_intern2), "tv_equal()");
5599 return TRUE;
5603 * Locate item with index "n" in list "l" and return it.
5604 * A negative index is counted from the end; -1 is the last item.
5605 * Returns NULL when "n" is out of range.
5607 static listitem_T *
5608 list_find(l, n)
5609 list_T *l;
5610 long n;
5612 listitem_T *item;
5613 long idx;
5615 if (l == NULL)
5616 return NULL;
5618 /* Negative index is relative to the end. */
5619 if (n < 0)
5620 n = l->lv_len + n;
5622 /* Check for index out of range. */
5623 if (n < 0 || n >= l->lv_len)
5624 return NULL;
5626 /* When there is a cached index may start search from there. */
5627 if (l->lv_idx_item != NULL)
5629 if (n < l->lv_idx / 2)
5631 /* closest to the start of the list */
5632 item = l->lv_first;
5633 idx = 0;
5635 else if (n > (l->lv_idx + l->lv_len) / 2)
5637 /* closest to the end of the list */
5638 item = l->lv_last;
5639 idx = l->lv_len - 1;
5641 else
5643 /* closest to the cached index */
5644 item = l->lv_idx_item;
5645 idx = l->lv_idx;
5648 else
5650 if (n < l->lv_len / 2)
5652 /* closest to the start of the list */
5653 item = l->lv_first;
5654 idx = 0;
5656 else
5658 /* closest to the end of the list */
5659 item = l->lv_last;
5660 idx = l->lv_len - 1;
5664 while (n > idx)
5666 /* search forward */
5667 item = item->li_next;
5668 ++idx;
5670 while (n < idx)
5672 /* search backward */
5673 item = item->li_prev;
5674 --idx;
5677 /* cache the used index */
5678 l->lv_idx = idx;
5679 l->lv_idx_item = item;
5681 return item;
5685 * Get list item "l[idx]" as a number.
5687 static long
5688 list_find_nr(l, idx, errorp)
5689 list_T *l;
5690 long idx;
5691 int *errorp; /* set to TRUE when something wrong */
5693 listitem_T *li;
5695 li = list_find(l, idx);
5696 if (li == NULL)
5698 if (errorp != NULL)
5699 *errorp = TRUE;
5700 return -1L;
5702 return get_tv_number_chk(&li->li_tv, errorp);
5706 * Locate "item" list "l" and return its index.
5707 * Returns -1 when "item" is not in the list.
5709 static long
5710 list_idx_of_item(l, item)
5711 list_T *l;
5712 listitem_T *item;
5714 long idx = 0;
5715 listitem_T *li;
5717 if (l == NULL)
5718 return -1;
5719 idx = 0;
5720 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
5721 ++idx;
5722 if (li == NULL)
5723 return -1;
5724 return idx;
5728 * Append item "item" to the end of list "l".
5730 static void
5731 list_append(l, item)
5732 list_T *l;
5733 listitem_T *item;
5735 if (l->lv_last == NULL)
5737 /* empty list */
5738 l->lv_first = item;
5739 l->lv_last = item;
5740 item->li_prev = NULL;
5742 else
5744 l->lv_last->li_next = item;
5745 item->li_prev = l->lv_last;
5746 l->lv_last = item;
5748 ++l->lv_len;
5749 item->li_next = NULL;
5753 * Append typval_T "tv" to the end of list "l".
5754 * Return FAIL when out of memory.
5756 static int
5757 list_append_tv(l, tv)
5758 list_T *l;
5759 typval_T *tv;
5761 listitem_T *li = listitem_alloc();
5763 if (li == NULL)
5764 return FAIL;
5765 copy_tv(tv, &li->li_tv);
5766 list_append(l, li);
5767 return OK;
5771 * Add a dictionary to a list. Used by getqflist().
5772 * Return FAIL when out of memory.
5775 list_append_dict(list, dict)
5776 list_T *list;
5777 dict_T *dict;
5779 listitem_T *li = listitem_alloc();
5781 if (li == NULL)
5782 return FAIL;
5783 li->li_tv.v_type = VAR_DICT;
5784 li->li_tv.v_lock = 0;
5785 li->li_tv.vval.v_dict = dict;
5786 list_append(list, li);
5787 ++dict->dv_refcount;
5788 return OK;
5792 * Make a copy of "str" and append it as an item to list "l".
5793 * When "len" >= 0 use "str[len]".
5794 * Returns FAIL when out of memory.
5796 static int
5797 list_append_string(l, str, len)
5798 list_T *l;
5799 char_u *str;
5800 int len;
5802 listitem_T *li = listitem_alloc();
5804 if (li == NULL)
5805 return FAIL;
5806 list_append(l, li);
5807 li->li_tv.v_type = VAR_STRING;
5808 li->li_tv.v_lock = 0;
5809 if (str == NULL)
5810 li->li_tv.vval.v_string = NULL;
5811 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
5812 : vim_strsave(str))) == NULL)
5813 return FAIL;
5814 return OK;
5818 * Append "n" to list "l".
5819 * Returns FAIL when out of memory.
5821 static int
5822 list_append_number(l, n)
5823 list_T *l;
5824 varnumber_T n;
5826 listitem_T *li;
5828 li = listitem_alloc();
5829 if (li == NULL)
5830 return FAIL;
5831 li->li_tv.v_type = VAR_NUMBER;
5832 li->li_tv.v_lock = 0;
5833 li->li_tv.vval.v_number = n;
5834 list_append(l, li);
5835 return OK;
5839 * Insert typval_T "tv" in list "l" before "item".
5840 * If "item" is NULL append at the end.
5841 * Return FAIL when out of memory.
5843 static int
5844 list_insert_tv(l, tv, item)
5845 list_T *l;
5846 typval_T *tv;
5847 listitem_T *item;
5849 listitem_T *ni = listitem_alloc();
5851 if (ni == NULL)
5852 return FAIL;
5853 copy_tv(tv, &ni->li_tv);
5854 if (item == NULL)
5855 /* Append new item at end of list. */
5856 list_append(l, ni);
5857 else
5859 /* Insert new item before existing item. */
5860 ni->li_prev = item->li_prev;
5861 ni->li_next = item;
5862 if (item->li_prev == NULL)
5864 l->lv_first = ni;
5865 ++l->lv_idx;
5867 else
5869 item->li_prev->li_next = ni;
5870 l->lv_idx_item = NULL;
5872 item->li_prev = ni;
5873 ++l->lv_len;
5875 return OK;
5879 * Extend "l1" with "l2".
5880 * If "bef" is NULL append at the end, otherwise insert before this item.
5881 * Returns FAIL when out of memory.
5883 static int
5884 list_extend(l1, l2, bef)
5885 list_T *l1;
5886 list_T *l2;
5887 listitem_T *bef;
5889 listitem_T *item;
5891 for (item = l2->lv_first; item != NULL; item = item->li_next)
5892 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
5893 return FAIL;
5894 return OK;
5898 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
5899 * Return FAIL when out of memory.
5901 static int
5902 list_concat(l1, l2, tv)
5903 list_T *l1;
5904 list_T *l2;
5905 typval_T *tv;
5907 list_T *l;
5909 /* make a copy of the first list. */
5910 l = list_copy(l1, FALSE, 0);
5911 if (l == NULL)
5912 return FAIL;
5913 tv->v_type = VAR_LIST;
5914 tv->vval.v_list = l;
5916 /* append all items from the second list */
5917 return list_extend(l, l2, NULL);
5921 * Make a copy of list "orig". Shallow if "deep" is FALSE.
5922 * The refcount of the new list is set to 1.
5923 * See item_copy() for "copyID".
5924 * Returns NULL when out of memory.
5926 static list_T *
5927 list_copy(orig, deep, copyID)
5928 list_T *orig;
5929 int deep;
5930 int copyID;
5932 list_T *copy;
5933 listitem_T *item;
5934 listitem_T *ni;
5936 if (orig == NULL)
5937 return NULL;
5939 copy = list_alloc();
5940 if (copy != NULL)
5942 if (copyID != 0)
5944 /* Do this before adding the items, because one of the items may
5945 * refer back to this list. */
5946 orig->lv_copyID = copyID;
5947 orig->lv_copylist = copy;
5949 for (item = orig->lv_first; item != NULL && !got_int;
5950 item = item->li_next)
5952 ni = listitem_alloc();
5953 if (ni == NULL)
5954 break;
5955 if (deep)
5957 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
5959 vim_free(ni);
5960 break;
5963 else
5964 copy_tv(&item->li_tv, &ni->li_tv);
5965 list_append(copy, ni);
5967 ++copy->lv_refcount;
5968 if (item != NULL)
5970 list_unref(copy);
5971 copy = NULL;
5975 return copy;
5979 * Remove items "item" to "item2" from list "l".
5980 * Does not free the listitem or the value!
5982 static void
5983 list_remove(l, item, item2)
5984 list_T *l;
5985 listitem_T *item;
5986 listitem_T *item2;
5988 listitem_T *ip;
5990 /* notify watchers */
5991 for (ip = item; ip != NULL; ip = ip->li_next)
5993 --l->lv_len;
5994 list_fix_watch(l, ip);
5995 if (ip == item2)
5996 break;
5999 if (item2->li_next == NULL)
6000 l->lv_last = item->li_prev;
6001 else
6002 item2->li_next->li_prev = item->li_prev;
6003 if (item->li_prev == NULL)
6004 l->lv_first = item2->li_next;
6005 else
6006 item->li_prev->li_next = item2->li_next;
6007 l->lv_idx_item = NULL;
6011 * Return an allocated string with the string representation of a list.
6012 * May return NULL.
6014 static char_u *
6015 list2string(tv, copyID)
6016 typval_T *tv;
6017 int copyID;
6019 garray_T ga;
6021 if (tv->vval.v_list == NULL)
6022 return NULL;
6023 ga_init2(&ga, (int)sizeof(char), 80);
6024 ga_append(&ga, '[');
6025 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6027 vim_free(ga.ga_data);
6028 return NULL;
6030 ga_append(&ga, ']');
6031 ga_append(&ga, NUL);
6032 return (char_u *)ga.ga_data;
6036 * Join list "l" into a string in "*gap", using separator "sep".
6037 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6038 * Return FAIL or OK.
6040 static int
6041 list_join(gap, l, sep, echo, copyID)
6042 garray_T *gap;
6043 list_T *l;
6044 char_u *sep;
6045 int echo;
6046 int copyID;
6048 int first = TRUE;
6049 char_u *tofree;
6050 char_u numbuf[NUMBUFLEN];
6051 listitem_T *item;
6052 char_u *s;
6054 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6056 if (first)
6057 first = FALSE;
6058 else
6059 ga_concat(gap, sep);
6061 if (echo)
6062 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6063 else
6064 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6065 if (s != NULL)
6066 ga_concat(gap, s);
6067 vim_free(tofree);
6068 if (s == NULL)
6069 return FAIL;
6071 return OK;
6075 * Garbage collection for lists and dictionaries.
6077 * We use reference counts to be able to free most items right away when they
6078 * are no longer used. But for composite items it's possible that it becomes
6079 * unused while the reference count is > 0: When there is a recursive
6080 * reference. Example:
6081 * :let l = [1, 2, 3]
6082 * :let d = {9: l}
6083 * :let l[1] = d
6085 * Since this is quite unusual we handle this with garbage collection: every
6086 * once in a while find out which lists and dicts are not referenced from any
6087 * variable.
6089 * Here is a good reference text about garbage collection (refers to Python
6090 * but it applies to all reference-counting mechanisms):
6091 * http://python.ca/nas/python/gc/
6095 * Do garbage collection for lists and dicts.
6096 * Return TRUE if some memory was freed.
6099 garbage_collect()
6101 dict_T *dd;
6102 list_T *ll;
6103 int copyID = ++current_copyID;
6104 buf_T *buf;
6105 win_T *wp;
6106 int i;
6107 funccall_T *fc;
6108 int did_free = FALSE;
6109 #ifdef FEAT_WINDOWS
6110 tabpage_T *tp;
6111 #endif
6113 /* Only do this once. */
6114 want_garbage_collect = FALSE;
6115 may_garbage_collect = FALSE;
6118 * 1. Go through all accessible variables and mark all lists and dicts
6119 * with copyID.
6121 /* script-local variables */
6122 for (i = 1; i <= ga_scripts.ga_len; ++i)
6123 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6125 /* buffer-local variables */
6126 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6127 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6129 /* window-local variables */
6130 FOR_ALL_TAB_WINDOWS(tp, wp)
6131 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6133 #ifdef FEAT_WINDOWS
6134 /* tabpage-local variables */
6135 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6136 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6137 #endif
6139 /* global variables */
6140 set_ref_in_ht(&globvarht, copyID);
6142 /* function-local variables */
6143 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6145 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6146 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6150 * 2. Go through the list of dicts and free items without the copyID.
6152 for (dd = first_dict; dd != NULL; )
6153 if (dd->dv_copyID != copyID)
6155 /* Free the Dictionary and ordinary items it contains, but don't
6156 * recurse into Lists and Dictionaries, they will be in the list
6157 * of dicts or list of lists. */
6158 dict_free(dd, FALSE);
6159 did_free = TRUE;
6161 /* restart, next dict may also have been freed */
6162 dd = first_dict;
6164 else
6165 dd = dd->dv_used_next;
6168 * 3. Go through the list of lists and free items without the copyID.
6169 * But don't free a list that has a watcher (used in a for loop), these
6170 * are not referenced anywhere.
6172 for (ll = first_list; ll != NULL; )
6173 if (ll->lv_copyID != copyID && ll->lv_watch == NULL)
6175 /* Free the List and ordinary items it contains, but don't recurse
6176 * into Lists and Dictionaries, they will be in the list of dicts
6177 * or list of lists. */
6178 list_free(ll, FALSE);
6179 did_free = TRUE;
6181 /* restart, next list may also have been freed */
6182 ll = first_list;
6184 else
6185 ll = ll->lv_used_next;
6187 return did_free;
6191 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6193 static void
6194 set_ref_in_ht(ht, copyID)
6195 hashtab_T *ht;
6196 int copyID;
6198 int todo;
6199 hashitem_T *hi;
6201 todo = (int)ht->ht_used;
6202 for (hi = ht->ht_array; todo > 0; ++hi)
6203 if (!HASHITEM_EMPTY(hi))
6205 --todo;
6206 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6211 * Mark all lists and dicts referenced through list "l" with "copyID".
6213 static void
6214 set_ref_in_list(l, copyID)
6215 list_T *l;
6216 int copyID;
6218 listitem_T *li;
6220 for (li = l->lv_first; li != NULL; li = li->li_next)
6221 set_ref_in_item(&li->li_tv, copyID);
6225 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6227 static void
6228 set_ref_in_item(tv, copyID)
6229 typval_T *tv;
6230 int copyID;
6232 dict_T *dd;
6233 list_T *ll;
6235 switch (tv->v_type)
6237 case VAR_DICT:
6238 dd = tv->vval.v_dict;
6239 if (dd->dv_copyID != copyID)
6241 /* Didn't see this dict yet. */
6242 dd->dv_copyID = copyID;
6243 set_ref_in_ht(&dd->dv_hashtab, copyID);
6245 break;
6247 case VAR_LIST:
6248 ll = tv->vval.v_list;
6249 if (ll->lv_copyID != copyID)
6251 /* Didn't see this list yet. */
6252 ll->lv_copyID = copyID;
6253 set_ref_in_list(ll, copyID);
6255 break;
6257 return;
6261 * Allocate an empty header for a dictionary.
6263 dict_T *
6264 dict_alloc()
6266 dict_T *d;
6268 d = (dict_T *)alloc(sizeof(dict_T));
6269 if (d != NULL)
6271 /* Add the list to the list of dicts for garbage collection. */
6272 if (first_dict != NULL)
6273 first_dict->dv_used_prev = d;
6274 d->dv_used_next = first_dict;
6275 d->dv_used_prev = NULL;
6276 first_dict = d;
6278 hash_init(&d->dv_hashtab);
6279 d->dv_lock = 0;
6280 d->dv_refcount = 0;
6281 d->dv_copyID = 0;
6283 return d;
6287 * Unreference a Dictionary: decrement the reference count and free it when it
6288 * becomes zero.
6290 static void
6291 dict_unref(d)
6292 dict_T *d;
6294 if (d != NULL && --d->dv_refcount <= 0)
6295 dict_free(d, TRUE);
6299 * Free a Dictionary, including all items it contains.
6300 * Ignores the reference count.
6302 static void
6303 dict_free(d, recurse)
6304 dict_T *d;
6305 int recurse; /* Free Lists and Dictionaries recursively. */
6307 int todo;
6308 hashitem_T *hi;
6309 dictitem_T *di;
6311 /* Remove the dict from the list of dicts for garbage collection. */
6312 if (d->dv_used_prev == NULL)
6313 first_dict = d->dv_used_next;
6314 else
6315 d->dv_used_prev->dv_used_next = d->dv_used_next;
6316 if (d->dv_used_next != NULL)
6317 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6319 /* Lock the hashtab, we don't want it to resize while freeing items. */
6320 hash_lock(&d->dv_hashtab);
6321 todo = (int)d->dv_hashtab.ht_used;
6322 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6324 if (!HASHITEM_EMPTY(hi))
6326 /* Remove the item before deleting it, just in case there is
6327 * something recursive causing trouble. */
6328 di = HI2DI(hi);
6329 hash_remove(&d->dv_hashtab, hi);
6330 if (recurse || (di->di_tv.v_type != VAR_LIST
6331 && di->di_tv.v_type != VAR_DICT))
6332 clear_tv(&di->di_tv);
6333 vim_free(di);
6334 --todo;
6337 hash_clear(&d->dv_hashtab);
6338 vim_free(d);
6342 * Allocate a Dictionary item.
6343 * The "key" is copied to the new item.
6344 * Note that the value of the item "di_tv" still needs to be initialized!
6345 * Returns NULL when out of memory.
6347 static dictitem_T *
6348 dictitem_alloc(key)
6349 char_u *key;
6351 dictitem_T *di;
6353 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6354 if (di != NULL)
6356 STRCPY(di->di_key, key);
6357 di->di_flags = 0;
6359 return di;
6363 * Make a copy of a Dictionary item.
6365 static dictitem_T *
6366 dictitem_copy(org)
6367 dictitem_T *org;
6369 dictitem_T *di;
6371 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6372 + STRLEN(org->di_key)));
6373 if (di != NULL)
6375 STRCPY(di->di_key, org->di_key);
6376 di->di_flags = 0;
6377 copy_tv(&org->di_tv, &di->di_tv);
6379 return di;
6383 * Remove item "item" from Dictionary "dict" and free it.
6385 static void
6386 dictitem_remove(dict, item)
6387 dict_T *dict;
6388 dictitem_T *item;
6390 hashitem_T *hi;
6392 hi = hash_find(&dict->dv_hashtab, item->di_key);
6393 if (HASHITEM_EMPTY(hi))
6394 EMSG2(_(e_intern2), "dictitem_remove()");
6395 else
6396 hash_remove(&dict->dv_hashtab, hi);
6397 dictitem_free(item);
6401 * Free a dict item. Also clears the value.
6403 static void
6404 dictitem_free(item)
6405 dictitem_T *item;
6407 clear_tv(&item->di_tv);
6408 vim_free(item);
6412 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6413 * The refcount of the new dict is set to 1.
6414 * See item_copy() for "copyID".
6415 * Returns NULL when out of memory.
6417 static dict_T *
6418 dict_copy(orig, deep, copyID)
6419 dict_T *orig;
6420 int deep;
6421 int copyID;
6423 dict_T *copy;
6424 dictitem_T *di;
6425 int todo;
6426 hashitem_T *hi;
6428 if (orig == NULL)
6429 return NULL;
6431 copy = dict_alloc();
6432 if (copy != NULL)
6434 if (copyID != 0)
6436 orig->dv_copyID = copyID;
6437 orig->dv_copydict = copy;
6439 todo = (int)orig->dv_hashtab.ht_used;
6440 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6442 if (!HASHITEM_EMPTY(hi))
6444 --todo;
6446 di = dictitem_alloc(hi->hi_key);
6447 if (di == NULL)
6448 break;
6449 if (deep)
6451 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6452 copyID) == FAIL)
6454 vim_free(di);
6455 break;
6458 else
6459 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6460 if (dict_add(copy, di) == FAIL)
6462 dictitem_free(di);
6463 break;
6468 ++copy->dv_refcount;
6469 if (todo > 0)
6471 dict_unref(copy);
6472 copy = NULL;
6476 return copy;
6480 * Add item "item" to Dictionary "d".
6481 * Returns FAIL when out of memory and when key already existed.
6483 static int
6484 dict_add(d, item)
6485 dict_T *d;
6486 dictitem_T *item;
6488 return hash_add(&d->dv_hashtab, item->di_key);
6492 * Add a number or string entry to dictionary "d".
6493 * When "str" is NULL use number "nr", otherwise use "str".
6494 * Returns FAIL when out of memory and when key already exists.
6497 dict_add_nr_str(d, key, nr, str)
6498 dict_T *d;
6499 char *key;
6500 long nr;
6501 char_u *str;
6503 dictitem_T *item;
6505 item = dictitem_alloc((char_u *)key);
6506 if (item == NULL)
6507 return FAIL;
6508 item->di_tv.v_lock = 0;
6509 if (str == NULL)
6511 item->di_tv.v_type = VAR_NUMBER;
6512 item->di_tv.vval.v_number = nr;
6514 else
6516 item->di_tv.v_type = VAR_STRING;
6517 item->di_tv.vval.v_string = vim_strsave(str);
6519 if (dict_add(d, item) == FAIL)
6521 dictitem_free(item);
6522 return FAIL;
6524 return OK;
6528 * Get the number of items in a Dictionary.
6530 static long
6531 dict_len(d)
6532 dict_T *d;
6534 if (d == NULL)
6535 return 0L;
6536 return (long)d->dv_hashtab.ht_used;
6540 * Find item "key[len]" in Dictionary "d".
6541 * If "len" is negative use strlen(key).
6542 * Returns NULL when not found.
6544 static dictitem_T *
6545 dict_find(d, key, len)
6546 dict_T *d;
6547 char_u *key;
6548 int len;
6550 #define AKEYLEN 200
6551 char_u buf[AKEYLEN];
6552 char_u *akey;
6553 char_u *tofree = NULL;
6554 hashitem_T *hi;
6556 if (len < 0)
6557 akey = key;
6558 else if (len >= AKEYLEN)
6560 tofree = akey = vim_strnsave(key, len);
6561 if (akey == NULL)
6562 return NULL;
6564 else
6566 /* Avoid a malloc/free by using buf[]. */
6567 vim_strncpy(buf, key, len);
6568 akey = buf;
6571 hi = hash_find(&d->dv_hashtab, akey);
6572 vim_free(tofree);
6573 if (HASHITEM_EMPTY(hi))
6574 return NULL;
6575 return HI2DI(hi);
6579 * Get a string item from a dictionary.
6580 * When "save" is TRUE allocate memory for it.
6581 * Returns NULL if the entry doesn't exist or out of memory.
6583 char_u *
6584 get_dict_string(d, key, save)
6585 dict_T *d;
6586 char_u *key;
6587 int save;
6589 dictitem_T *di;
6590 char_u *s;
6592 di = dict_find(d, key, -1);
6593 if (di == NULL)
6594 return NULL;
6595 s = get_tv_string(&di->di_tv);
6596 if (save && s != NULL)
6597 s = vim_strsave(s);
6598 return s;
6602 * Get a number item from a dictionary.
6603 * Returns 0 if the entry doesn't exist or out of memory.
6605 long
6606 get_dict_number(d, key)
6607 dict_T *d;
6608 char_u *key;
6610 dictitem_T *di;
6612 di = dict_find(d, key, -1);
6613 if (di == NULL)
6614 return 0;
6615 return get_tv_number(&di->di_tv);
6619 * Return an allocated string with the string representation of a Dictionary.
6620 * May return NULL.
6622 static char_u *
6623 dict2string(tv, copyID)
6624 typval_T *tv;
6625 int copyID;
6627 garray_T ga;
6628 int first = TRUE;
6629 char_u *tofree;
6630 char_u numbuf[NUMBUFLEN];
6631 hashitem_T *hi;
6632 char_u *s;
6633 dict_T *d;
6634 int todo;
6636 if ((d = tv->vval.v_dict) == NULL)
6637 return NULL;
6638 ga_init2(&ga, (int)sizeof(char), 80);
6639 ga_append(&ga, '{');
6641 todo = (int)d->dv_hashtab.ht_used;
6642 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6644 if (!HASHITEM_EMPTY(hi))
6646 --todo;
6648 if (first)
6649 first = FALSE;
6650 else
6651 ga_concat(&ga, (char_u *)", ");
6653 tofree = string_quote(hi->hi_key, FALSE);
6654 if (tofree != NULL)
6656 ga_concat(&ga, tofree);
6657 vim_free(tofree);
6659 ga_concat(&ga, (char_u *)": ");
6660 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
6661 if (s != NULL)
6662 ga_concat(&ga, s);
6663 vim_free(tofree);
6664 if (s == NULL)
6665 break;
6668 if (todo > 0)
6670 vim_free(ga.ga_data);
6671 return NULL;
6674 ga_append(&ga, '}');
6675 ga_append(&ga, NUL);
6676 return (char_u *)ga.ga_data;
6680 * Allocate a variable for a Dictionary and fill it from "*arg".
6681 * Return OK or FAIL. Returns NOTDONE for {expr}.
6683 static int
6684 get_dict_tv(arg, rettv, evaluate)
6685 char_u **arg;
6686 typval_T *rettv;
6687 int evaluate;
6689 dict_T *d = NULL;
6690 typval_T tvkey;
6691 typval_T tv;
6692 char_u *key;
6693 dictitem_T *item;
6694 char_u *start = skipwhite(*arg + 1);
6695 char_u buf[NUMBUFLEN];
6698 * First check if it's not a curly-braces thing: {expr}.
6699 * Must do this without evaluating, otherwise a function may be called
6700 * twice. Unfortunately this means we need to call eval1() twice for the
6701 * first item.
6702 * But {} is an empty Dictionary.
6704 if (*start != '}')
6706 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
6707 return FAIL;
6708 if (*start == '}')
6709 return NOTDONE;
6712 if (evaluate)
6714 d = dict_alloc();
6715 if (d == NULL)
6716 return FAIL;
6718 tvkey.v_type = VAR_UNKNOWN;
6719 tv.v_type = VAR_UNKNOWN;
6721 *arg = skipwhite(*arg + 1);
6722 while (**arg != '}' && **arg != NUL)
6724 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
6725 goto failret;
6726 if (**arg != ':')
6728 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
6729 clear_tv(&tvkey);
6730 goto failret;
6732 key = get_tv_string_buf_chk(&tvkey, buf);
6733 if (key == NULL || *key == NUL)
6735 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
6736 if (key != NULL)
6737 EMSG(_(e_emptykey));
6738 clear_tv(&tvkey);
6739 goto failret;
6742 *arg = skipwhite(*arg + 1);
6743 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
6745 clear_tv(&tvkey);
6746 goto failret;
6748 if (evaluate)
6750 item = dict_find(d, key, -1);
6751 if (item != NULL)
6753 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
6754 clear_tv(&tvkey);
6755 clear_tv(&tv);
6756 goto failret;
6758 item = dictitem_alloc(key);
6759 clear_tv(&tvkey);
6760 if (item != NULL)
6762 item->di_tv = tv;
6763 item->di_tv.v_lock = 0;
6764 if (dict_add(d, item) == FAIL)
6765 dictitem_free(item);
6769 if (**arg == '}')
6770 break;
6771 if (**arg != ',')
6773 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
6774 goto failret;
6776 *arg = skipwhite(*arg + 1);
6779 if (**arg != '}')
6781 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
6782 failret:
6783 if (evaluate)
6784 dict_free(d, TRUE);
6785 return FAIL;
6788 *arg = skipwhite(*arg + 1);
6789 if (evaluate)
6791 rettv->v_type = VAR_DICT;
6792 rettv->vval.v_dict = d;
6793 ++d->dv_refcount;
6796 return OK;
6800 * Return a string with the string representation of a variable.
6801 * If the memory is allocated "tofree" is set to it, otherwise NULL.
6802 * "numbuf" is used for a number.
6803 * Does not put quotes around strings, as ":echo" displays values.
6804 * When "copyID" is not NULL replace recursive lists and dicts with "...".
6805 * May return NULL.
6807 static char_u *
6808 echo_string(tv, tofree, numbuf, copyID)
6809 typval_T *tv;
6810 char_u **tofree;
6811 char_u *numbuf;
6812 int copyID;
6814 static int recurse = 0;
6815 char_u *r = NULL;
6817 if (recurse >= DICT_MAXNEST)
6819 EMSG(_("E724: variable nested too deep for displaying"));
6820 *tofree = NULL;
6821 return NULL;
6823 ++recurse;
6825 switch (tv->v_type)
6827 case VAR_FUNC:
6828 *tofree = NULL;
6829 r = tv->vval.v_string;
6830 break;
6832 case VAR_LIST:
6833 if (tv->vval.v_list == NULL)
6835 *tofree = NULL;
6836 r = NULL;
6838 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
6840 *tofree = NULL;
6841 r = (char_u *)"[...]";
6843 else
6845 tv->vval.v_list->lv_copyID = copyID;
6846 *tofree = list2string(tv, copyID);
6847 r = *tofree;
6849 break;
6851 case VAR_DICT:
6852 if (tv->vval.v_dict == NULL)
6854 *tofree = NULL;
6855 r = NULL;
6857 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
6859 *tofree = NULL;
6860 r = (char_u *)"{...}";
6862 else
6864 tv->vval.v_dict->dv_copyID = copyID;
6865 *tofree = dict2string(tv, copyID);
6866 r = *tofree;
6868 break;
6870 case VAR_STRING:
6871 case VAR_NUMBER:
6872 *tofree = NULL;
6873 r = get_tv_string_buf(tv, numbuf);
6874 break;
6876 default:
6877 EMSG2(_(e_intern2), "echo_string()");
6878 *tofree = NULL;
6881 --recurse;
6882 return r;
6886 * Return a string with the string representation of a variable.
6887 * If the memory is allocated "tofree" is set to it, otherwise NULL.
6888 * "numbuf" is used for a number.
6889 * Puts quotes around strings, so that they can be parsed back by eval().
6890 * May return NULL.
6892 static char_u *
6893 tv2string(tv, tofree, numbuf, copyID)
6894 typval_T *tv;
6895 char_u **tofree;
6896 char_u *numbuf;
6897 int copyID;
6899 switch (tv->v_type)
6901 case VAR_FUNC:
6902 *tofree = string_quote(tv->vval.v_string, TRUE);
6903 return *tofree;
6904 case VAR_STRING:
6905 *tofree = string_quote(tv->vval.v_string, FALSE);
6906 return *tofree;
6907 case VAR_NUMBER:
6908 case VAR_LIST:
6909 case VAR_DICT:
6910 break;
6911 default:
6912 EMSG2(_(e_intern2), "tv2string()");
6914 return echo_string(tv, tofree, numbuf, copyID);
6918 * Return string "str" in ' quotes, doubling ' characters.
6919 * If "str" is NULL an empty string is assumed.
6920 * If "function" is TRUE make it function('string').
6922 static char_u *
6923 string_quote(str, function)
6924 char_u *str;
6925 int function;
6927 unsigned len;
6928 char_u *p, *r, *s;
6930 len = (function ? 13 : 3);
6931 if (str != NULL)
6933 len += (unsigned)STRLEN(str);
6934 for (p = str; *p != NUL; mb_ptr_adv(p))
6935 if (*p == '\'')
6936 ++len;
6938 s = r = alloc(len);
6939 if (r != NULL)
6941 if (function)
6943 STRCPY(r, "function('");
6944 r += 10;
6946 else
6947 *r++ = '\'';
6948 if (str != NULL)
6949 for (p = str; *p != NUL; )
6951 if (*p == '\'')
6952 *r++ = '\'';
6953 MB_COPY_CHAR(p, r);
6955 *r++ = '\'';
6956 if (function)
6957 *r++ = ')';
6958 *r++ = NUL;
6960 return s;
6964 * Get the value of an environment variable.
6965 * "arg" is pointing to the '$'. It is advanced to after the name.
6966 * If the environment variable was not set, silently assume it is empty.
6967 * Always return OK.
6969 static int
6970 get_env_tv(arg, rettv, evaluate)
6971 char_u **arg;
6972 typval_T *rettv;
6973 int evaluate;
6975 char_u *string = NULL;
6976 int len;
6977 int cc;
6978 char_u *name;
6979 int mustfree = FALSE;
6981 ++*arg;
6982 name = *arg;
6983 len = get_env_len(arg);
6984 if (evaluate)
6986 if (len != 0)
6988 cc = name[len];
6989 name[len] = NUL;
6990 /* first try vim_getenv(), fast for normal environment vars */
6991 string = vim_getenv(name, &mustfree);
6992 if (string != NULL && *string != NUL)
6994 if (!mustfree)
6995 string = vim_strsave(string);
6997 else
6999 if (mustfree)
7000 vim_free(string);
7002 /* next try expanding things like $VIM and ${HOME} */
7003 string = expand_env_save(name - 1);
7004 if (string != NULL && *string == '$')
7006 vim_free(string);
7007 string = NULL;
7010 name[len] = cc;
7012 rettv->v_type = VAR_STRING;
7013 rettv->vval.v_string = string;
7016 return OK;
7020 * Array with names and number of arguments of all internal functions
7021 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7023 static struct fst
7025 char *f_name; /* function name */
7026 char f_min_argc; /* minimal number of arguments */
7027 char f_max_argc; /* maximal number of arguments */
7028 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7029 /* implementation of function */
7030 } functions[] =
7032 {"add", 2, 2, f_add},
7033 {"append", 2, 2, f_append},
7034 {"argc", 0, 0, f_argc},
7035 {"argidx", 0, 0, f_argidx},
7036 {"argv", 0, 1, f_argv},
7037 {"browse", 4, 4, f_browse},
7038 {"browsedir", 2, 2, f_browsedir},
7039 {"bufexists", 1, 1, f_bufexists},
7040 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7041 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7042 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7043 {"buflisted", 1, 1, f_buflisted},
7044 {"bufloaded", 1, 1, f_bufloaded},
7045 {"bufname", 1, 1, f_bufname},
7046 {"bufnr", 1, 2, f_bufnr},
7047 {"bufwinnr", 1, 1, f_bufwinnr},
7048 {"byte2line", 1, 1, f_byte2line},
7049 {"byteidx", 2, 2, f_byteidx},
7050 {"call", 2, 3, f_call},
7051 {"changenr", 0, 0, f_changenr},
7052 {"char2nr", 1, 1, f_char2nr},
7053 {"cindent", 1, 1, f_cindent},
7054 {"clearmatches", 0, 0, f_clearmatches},
7055 {"col", 1, 1, f_col},
7056 #if defined(FEAT_INS_EXPAND)
7057 {"complete", 2, 2, f_complete},
7058 {"complete_add", 1, 1, f_complete_add},
7059 {"complete_check", 0, 0, f_complete_check},
7060 #endif
7061 {"confirm", 1, 4, f_confirm},
7062 {"copy", 1, 1, f_copy},
7063 {"count", 2, 4, f_count},
7064 {"cscope_connection",0,3, f_cscope_connection},
7065 {"cursor", 1, 3, f_cursor},
7066 {"deepcopy", 1, 2, f_deepcopy},
7067 {"delete", 1, 1, f_delete},
7068 {"did_filetype", 0, 0, f_did_filetype},
7069 {"diff_filler", 1, 1, f_diff_filler},
7070 {"diff_hlID", 2, 2, f_diff_hlID},
7071 {"empty", 1, 1, f_empty},
7072 {"escape", 2, 2, f_escape},
7073 {"eval", 1, 1, f_eval},
7074 {"eventhandler", 0, 0, f_eventhandler},
7075 {"executable", 1, 1, f_executable},
7076 {"exists", 1, 1, f_exists},
7077 {"expand", 1, 2, f_expand},
7078 {"extend", 2, 3, f_extend},
7079 {"feedkeys", 1, 2, f_feedkeys},
7080 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7081 {"filereadable", 1, 1, f_filereadable},
7082 {"filewritable", 1, 1, f_filewritable},
7083 {"filter", 2, 2, f_filter},
7084 {"finddir", 1, 3, f_finddir},
7085 {"findfile", 1, 3, f_findfile},
7086 {"fnamemodify", 2, 2, f_fnamemodify},
7087 {"foldclosed", 1, 1, f_foldclosed},
7088 {"foldclosedend", 1, 1, f_foldclosedend},
7089 {"foldlevel", 1, 1, f_foldlevel},
7090 {"foldtext", 0, 0, f_foldtext},
7091 {"foldtextresult", 1, 1, f_foldtextresult},
7092 {"foreground", 0, 0, f_foreground},
7093 {"function", 1, 1, f_function},
7094 {"garbagecollect", 0, 0, f_garbagecollect},
7095 {"get", 2, 3, f_get},
7096 {"getbufline", 2, 3, f_getbufline},
7097 {"getbufvar", 2, 2, f_getbufvar},
7098 {"getchar", 0, 1, f_getchar},
7099 {"getcharmod", 0, 0, f_getcharmod},
7100 {"getcmdline", 0, 0, f_getcmdline},
7101 {"getcmdpos", 0, 0, f_getcmdpos},
7102 {"getcmdtype", 0, 0, f_getcmdtype},
7103 {"getcwd", 0, 0, f_getcwd},
7104 {"getfontname", 0, 1, f_getfontname},
7105 {"getfperm", 1, 1, f_getfperm},
7106 {"getfsize", 1, 1, f_getfsize},
7107 {"getftime", 1, 1, f_getftime},
7108 {"getftype", 1, 1, f_getftype},
7109 {"getline", 1, 2, f_getline},
7110 {"getloclist", 1, 1, f_getqflist},
7111 {"getmatches", 0, 0, f_getmatches},
7112 {"getpos", 1, 1, f_getpos},
7113 {"getqflist", 0, 0, f_getqflist},
7114 {"getreg", 0, 2, f_getreg},
7115 {"getregtype", 0, 1, f_getregtype},
7116 {"gettabwinvar", 3, 3, f_gettabwinvar},
7117 {"getwinposx", 0, 0, f_getwinposx},
7118 {"getwinposy", 0, 0, f_getwinposy},
7119 {"getwinvar", 2, 2, f_getwinvar},
7120 {"glob", 1, 1, f_glob},
7121 {"globpath", 2, 2, f_globpath},
7122 {"has", 1, 1, f_has},
7123 {"has_key", 2, 2, f_has_key},
7124 {"haslocaldir", 0, 0, f_haslocaldir},
7125 {"hasmapto", 1, 3, f_hasmapto},
7126 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7127 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7128 {"histadd", 2, 2, f_histadd},
7129 {"histdel", 1, 2, f_histdel},
7130 {"histget", 1, 2, f_histget},
7131 {"histnr", 1, 1, f_histnr},
7132 {"hlID", 1, 1, f_hlID},
7133 {"hlexists", 1, 1, f_hlexists},
7134 {"hostname", 0, 0, f_hostname},
7135 {"iconv", 3, 3, f_iconv},
7136 {"indent", 1, 1, f_indent},
7137 {"index", 2, 4, f_index},
7138 {"input", 1, 3, f_input},
7139 {"inputdialog", 1, 3, f_inputdialog},
7140 {"inputlist", 1, 1, f_inputlist},
7141 {"inputrestore", 0, 0, f_inputrestore},
7142 {"inputsave", 0, 0, f_inputsave},
7143 {"inputsecret", 1, 2, f_inputsecret},
7144 {"insert", 2, 3, f_insert},
7145 {"isdirectory", 1, 1, f_isdirectory},
7146 {"islocked", 1, 1, f_islocked},
7147 {"items", 1, 1, f_items},
7148 {"join", 1, 2, f_join},
7149 {"keys", 1, 1, f_keys},
7150 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7151 {"len", 1, 1, f_len},
7152 {"libcall", 3, 3, f_libcall},
7153 {"libcallnr", 3, 3, f_libcallnr},
7154 {"line", 1, 1, f_line},
7155 {"line2byte", 1, 1, f_line2byte},
7156 {"lispindent", 1, 1, f_lispindent},
7157 {"localtime", 0, 0, f_localtime},
7158 {"map", 2, 2, f_map},
7159 {"maparg", 1, 3, f_maparg},
7160 {"mapcheck", 1, 3, f_mapcheck},
7161 {"match", 2, 4, f_match},
7162 {"matchadd", 2, 4, f_matchadd},
7163 {"matcharg", 1, 1, f_matcharg},
7164 {"matchdelete", 1, 1, f_matchdelete},
7165 {"matchend", 2, 4, f_matchend},
7166 {"matchlist", 2, 4, f_matchlist},
7167 {"matchstr", 2, 4, f_matchstr},
7168 {"max", 1, 1, f_max},
7169 {"min", 1, 1, f_min},
7170 #ifdef vim_mkdir
7171 {"mkdir", 1, 3, f_mkdir},
7172 #endif
7173 {"mode", 0, 0, f_mode},
7174 {"nextnonblank", 1, 1, f_nextnonblank},
7175 {"nr2char", 1, 1, f_nr2char},
7176 {"pathshorten", 1, 1, f_pathshorten},
7177 {"prevnonblank", 1, 1, f_prevnonblank},
7178 {"printf", 2, 19, f_printf},
7179 {"pumvisible", 0, 0, f_pumvisible},
7180 {"range", 1, 3, f_range},
7181 {"readfile", 1, 3, f_readfile},
7182 {"reltime", 0, 2, f_reltime},
7183 {"reltimestr", 1, 1, f_reltimestr},
7184 {"remote_expr", 2, 3, f_remote_expr},
7185 {"remote_foreground", 1, 1, f_remote_foreground},
7186 {"remote_peek", 1, 2, f_remote_peek},
7187 {"remote_read", 1, 1, f_remote_read},
7188 {"remote_send", 2, 3, f_remote_send},
7189 {"remove", 2, 3, f_remove},
7190 {"rename", 2, 2, f_rename},
7191 {"repeat", 2, 2, f_repeat},
7192 {"resolve", 1, 1, f_resolve},
7193 {"reverse", 1, 1, f_reverse},
7194 {"search", 1, 3, f_search},
7195 {"searchdecl", 1, 3, f_searchdecl},
7196 {"searchpair", 3, 6, f_searchpair},
7197 {"searchpairpos", 3, 6, f_searchpairpos},
7198 {"searchpos", 1, 3, f_searchpos},
7199 {"server2client", 2, 2, f_server2client},
7200 {"serverlist", 0, 0, f_serverlist},
7201 {"setbufvar", 3, 3, f_setbufvar},
7202 {"setcmdpos", 1, 1, f_setcmdpos},
7203 {"setline", 2, 2, f_setline},
7204 {"setloclist", 2, 3, f_setloclist},
7205 {"setmatches", 1, 1, f_setmatches},
7206 {"setpos", 2, 2, f_setpos},
7207 {"setqflist", 1, 2, f_setqflist},
7208 {"setreg", 2, 3, f_setreg},
7209 {"settabwinvar", 4, 4, f_settabwinvar},
7210 {"setwinvar", 3, 3, f_setwinvar},
7211 {"shellescape", 1, 1, f_shellescape},
7212 {"simplify", 1, 1, f_simplify},
7213 {"sort", 1, 2, f_sort},
7214 {"soundfold", 1, 1, f_soundfold},
7215 {"spellbadword", 0, 1, f_spellbadword},
7216 {"spellsuggest", 1, 3, f_spellsuggest},
7217 {"split", 1, 3, f_split},
7218 {"str2nr", 1, 2, f_str2nr},
7219 #ifdef HAVE_STRFTIME
7220 {"strftime", 1, 2, f_strftime},
7221 #endif
7222 {"stridx", 2, 3, f_stridx},
7223 {"string", 1, 1, f_string},
7224 {"strlen", 1, 1, f_strlen},
7225 {"strpart", 2, 3, f_strpart},
7226 {"strridx", 2, 3, f_strridx},
7227 {"strtrans", 1, 1, f_strtrans},
7228 {"submatch", 1, 1, f_submatch},
7229 {"substitute", 4, 4, f_substitute},
7230 {"synID", 3, 3, f_synID},
7231 {"synIDattr", 2, 3, f_synIDattr},
7232 {"synIDtrans", 1, 1, f_synIDtrans},
7233 {"system", 1, 2, f_system},
7234 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7235 {"tabpagenr", 0, 1, f_tabpagenr},
7236 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7237 {"tagfiles", 0, 0, f_tagfiles},
7238 {"taglist", 1, 1, f_taglist},
7239 {"tempname", 0, 0, f_tempname},
7240 {"test", 1, 1, f_test},
7241 {"tolower", 1, 1, f_tolower},
7242 {"toupper", 1, 1, f_toupper},
7243 {"tr", 3, 3, f_tr},
7244 {"type", 1, 1, f_type},
7245 {"values", 1, 1, f_values},
7246 {"virtcol", 1, 1, f_virtcol},
7247 {"visualmode", 0, 1, f_visualmode},
7248 {"winbufnr", 1, 1, f_winbufnr},
7249 {"wincol", 0, 0, f_wincol},
7250 {"winheight", 1, 1, f_winheight},
7251 {"winline", 0, 0, f_winline},
7252 {"winnr", 0, 1, f_winnr},
7253 {"winrestcmd", 0, 0, f_winrestcmd},
7254 {"winrestview", 1, 1, f_winrestview},
7255 {"winsaveview", 0, 0, f_winsaveview},
7256 {"winwidth", 1, 1, f_winwidth},
7257 {"writefile", 2, 3, f_writefile},
7260 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7263 * Function given to ExpandGeneric() to obtain the list of internal
7264 * or user defined function names.
7266 char_u *
7267 get_function_name(xp, idx)
7268 expand_T *xp;
7269 int idx;
7271 static int intidx = -1;
7272 char_u *name;
7274 if (idx == 0)
7275 intidx = -1;
7276 if (intidx < 0)
7278 name = get_user_func_name(xp, idx);
7279 if (name != NULL)
7280 return name;
7282 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7284 STRCPY(IObuff, functions[intidx].f_name);
7285 STRCAT(IObuff, "(");
7286 if (functions[intidx].f_max_argc == 0)
7287 STRCAT(IObuff, ")");
7288 return IObuff;
7291 return NULL;
7295 * Function given to ExpandGeneric() to obtain the list of internal or
7296 * user defined variable or function names.
7298 /*ARGSUSED*/
7299 char_u *
7300 get_expr_name(xp, idx)
7301 expand_T *xp;
7302 int idx;
7304 static int intidx = -1;
7305 char_u *name;
7307 if (idx == 0)
7308 intidx = -1;
7309 if (intidx < 0)
7311 name = get_function_name(xp, idx);
7312 if (name != NULL)
7313 return name;
7315 return get_user_var_name(xp, ++intidx);
7318 #endif /* FEAT_CMDL_COMPL */
7321 * Find internal function in table above.
7322 * Return index, or -1 if not found
7324 static int
7325 find_internal_func(name)
7326 char_u *name; /* name of the function */
7328 int first = 0;
7329 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7330 int cmp;
7331 int x;
7334 * Find the function name in the table. Binary search.
7336 while (first <= last)
7338 x = first + ((unsigned)(last - first) >> 1);
7339 cmp = STRCMP(name, functions[x].f_name);
7340 if (cmp < 0)
7341 last = x - 1;
7342 else if (cmp > 0)
7343 first = x + 1;
7344 else
7345 return x;
7347 return -1;
7351 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7352 * name it contains, otherwise return "name".
7354 static char_u *
7355 deref_func_name(name, lenp)
7356 char_u *name;
7357 int *lenp;
7359 dictitem_T *v;
7360 int cc;
7362 cc = name[*lenp];
7363 name[*lenp] = NUL;
7364 v = find_var(name, NULL);
7365 name[*lenp] = cc;
7366 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7368 if (v->di_tv.vval.v_string == NULL)
7370 *lenp = 0;
7371 return (char_u *)""; /* just in case */
7373 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7374 return v->di_tv.vval.v_string;
7377 return name;
7381 * Allocate a variable for the result of a function.
7382 * Return OK or FAIL.
7384 static int
7385 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7386 evaluate, selfdict)
7387 char_u *name; /* name of the function */
7388 int len; /* length of "name" */
7389 typval_T *rettv;
7390 char_u **arg; /* argument, pointing to the '(' */
7391 linenr_T firstline; /* first line of range */
7392 linenr_T lastline; /* last line of range */
7393 int *doesrange; /* return: function handled range */
7394 int evaluate;
7395 dict_T *selfdict; /* Dictionary for "self" */
7397 char_u *argp;
7398 int ret = OK;
7399 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7400 int argcount = 0; /* number of arguments found */
7403 * Get the arguments.
7405 argp = *arg;
7406 while (argcount < MAX_FUNC_ARGS)
7408 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7409 if (*argp == ')' || *argp == ',' || *argp == NUL)
7410 break;
7411 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7413 ret = FAIL;
7414 break;
7416 ++argcount;
7417 if (*argp != ',')
7418 break;
7420 if (*argp == ')')
7421 ++argp;
7422 else
7423 ret = FAIL;
7425 if (ret == OK)
7426 ret = call_func(name, len, rettv, argcount, argvars,
7427 firstline, lastline, doesrange, evaluate, selfdict);
7428 else if (!aborting())
7430 if (argcount == MAX_FUNC_ARGS)
7431 emsg_funcname("E740: Too many arguments for function %s", name);
7432 else
7433 emsg_funcname("E116: Invalid arguments for function %s", name);
7436 while (--argcount >= 0)
7437 clear_tv(&argvars[argcount]);
7439 *arg = skipwhite(argp);
7440 return ret;
7445 * Call a function with its resolved parameters
7446 * Return OK when the function can't be called, FAIL otherwise.
7447 * Also returns OK when an error was encountered while executing the function.
7449 static int
7450 call_func(name, len, rettv, argcount, argvars, firstline, lastline,
7451 doesrange, evaluate, selfdict)
7452 char_u *name; /* name of the function */
7453 int len; /* length of "name" */
7454 typval_T *rettv; /* return value goes here */
7455 int argcount; /* number of "argvars" */
7456 typval_T *argvars; /* vars for arguments, must have "argcount"
7457 PLUS ONE elements! */
7458 linenr_T firstline; /* first line of range */
7459 linenr_T lastline; /* last line of range */
7460 int *doesrange; /* return: function handled range */
7461 int evaluate;
7462 dict_T *selfdict; /* Dictionary for "self" */
7464 int ret = FAIL;
7465 #define ERROR_UNKNOWN 0
7466 #define ERROR_TOOMANY 1
7467 #define ERROR_TOOFEW 2
7468 #define ERROR_SCRIPT 3
7469 #define ERROR_DICT 4
7470 #define ERROR_NONE 5
7471 #define ERROR_OTHER 6
7472 int error = ERROR_NONE;
7473 int i;
7474 int llen;
7475 ufunc_T *fp;
7476 int cc;
7477 #define FLEN_FIXED 40
7478 char_u fname_buf[FLEN_FIXED + 1];
7479 char_u *fname;
7482 * In a script change <SID>name() and s:name() to K_SNR 123_name().
7483 * Change <SNR>123_name() to K_SNR 123_name().
7484 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
7486 cc = name[len];
7487 name[len] = NUL;
7488 llen = eval_fname_script(name);
7489 if (llen > 0)
7491 fname_buf[0] = K_SPECIAL;
7492 fname_buf[1] = KS_EXTRA;
7493 fname_buf[2] = (int)KE_SNR;
7494 i = 3;
7495 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
7497 if (current_SID <= 0)
7498 error = ERROR_SCRIPT;
7499 else
7501 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
7502 i = (int)STRLEN(fname_buf);
7505 if (i + STRLEN(name + llen) < FLEN_FIXED)
7507 STRCPY(fname_buf + i, name + llen);
7508 fname = fname_buf;
7510 else
7512 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
7513 if (fname == NULL)
7514 error = ERROR_OTHER;
7515 else
7517 mch_memmove(fname, fname_buf, (size_t)i);
7518 STRCPY(fname + i, name + llen);
7522 else
7523 fname = name;
7525 *doesrange = FALSE;
7528 /* execute the function if no errors detected and executing */
7529 if (evaluate && error == ERROR_NONE)
7531 rettv->v_type = VAR_NUMBER; /* default is number rettv */
7532 error = ERROR_UNKNOWN;
7534 if (!builtin_function(fname))
7537 * User defined function.
7539 fp = find_func(fname);
7541 #ifdef FEAT_AUTOCMD
7542 /* Trigger FuncUndefined event, may load the function. */
7543 if (fp == NULL
7544 && apply_autocmds(EVENT_FUNCUNDEFINED,
7545 fname, fname, TRUE, NULL)
7546 && !aborting())
7548 /* executed an autocommand, search for the function again */
7549 fp = find_func(fname);
7551 #endif
7552 /* Try loading a package. */
7553 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
7555 /* loaded a package, search for the function again */
7556 fp = find_func(fname);
7559 if (fp != NULL)
7561 if (fp->uf_flags & FC_RANGE)
7562 *doesrange = TRUE;
7563 if (argcount < fp->uf_args.ga_len)
7564 error = ERROR_TOOFEW;
7565 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
7566 error = ERROR_TOOMANY;
7567 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
7568 error = ERROR_DICT;
7569 else
7572 * Call the user function.
7573 * Save and restore search patterns, script variables and
7574 * redo buffer.
7576 save_search_patterns();
7577 saveRedobuff();
7578 ++fp->uf_calls;
7579 call_user_func(fp, argcount, argvars, rettv,
7580 firstline, lastline,
7581 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
7582 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
7583 && fp->uf_refcount <= 0)
7584 /* Function was unreferenced while being used, free it
7585 * now. */
7586 func_free(fp);
7587 restoreRedobuff();
7588 restore_search_patterns();
7589 error = ERROR_NONE;
7593 else
7596 * Find the function name in the table, call its implementation.
7598 i = find_internal_func(fname);
7599 if (i >= 0)
7601 if (argcount < functions[i].f_min_argc)
7602 error = ERROR_TOOFEW;
7603 else if (argcount > functions[i].f_max_argc)
7604 error = ERROR_TOOMANY;
7605 else
7607 argvars[argcount].v_type = VAR_UNKNOWN;
7608 functions[i].f_func(argvars, rettv);
7609 error = ERROR_NONE;
7614 * The function call (or "FuncUndefined" autocommand sequence) might
7615 * have been aborted by an error, an interrupt, or an explicitly thrown
7616 * exception that has not been caught so far. This situation can be
7617 * tested for by calling aborting(). For an error in an internal
7618 * function or for the "E132" error in call_user_func(), however, the
7619 * throw point at which the "force_abort" flag (temporarily reset by
7620 * emsg()) is normally updated has not been reached yet. We need to
7621 * update that flag first to make aborting() reliable.
7623 update_force_abort();
7625 if (error == ERROR_NONE)
7626 ret = OK;
7629 * Report an error unless the argument evaluation or function call has been
7630 * cancelled due to an aborting error, an interrupt, or an exception.
7632 if (!aborting())
7634 switch (error)
7636 case ERROR_UNKNOWN:
7637 emsg_funcname(N_("E117: Unknown function: %s"), name);
7638 break;
7639 case ERROR_TOOMANY:
7640 emsg_funcname(e_toomanyarg, name);
7641 break;
7642 case ERROR_TOOFEW:
7643 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
7644 name);
7645 break;
7646 case ERROR_SCRIPT:
7647 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
7648 name);
7649 break;
7650 case ERROR_DICT:
7651 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
7652 name);
7653 break;
7657 name[len] = cc;
7658 if (fname != name && fname != fname_buf)
7659 vim_free(fname);
7661 return ret;
7665 * Give an error message with a function name. Handle <SNR> things.
7667 static void
7668 emsg_funcname(ermsg, name)
7669 char *ermsg;
7670 char_u *name;
7672 char_u *p;
7674 if (*name == K_SPECIAL)
7675 p = concat_str((char_u *)"<SNR>", name + 3);
7676 else
7677 p = name;
7678 EMSG2(_(ermsg), p);
7679 if (p != name)
7680 vim_free(p);
7683 /*********************************************
7684 * Implementation of the built-in functions
7688 * "add(list, item)" function
7690 static void
7691 f_add(argvars, rettv)
7692 typval_T *argvars;
7693 typval_T *rettv;
7695 list_T *l;
7697 rettv->vval.v_number = 1; /* Default: Failed */
7698 if (argvars[0].v_type == VAR_LIST)
7700 if ((l = argvars[0].vval.v_list) != NULL
7701 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
7702 && list_append_tv(l, &argvars[1]) == OK)
7703 copy_tv(&argvars[0], rettv);
7705 else
7706 EMSG(_(e_listreq));
7710 * "append(lnum, string/list)" function
7712 static void
7713 f_append(argvars, rettv)
7714 typval_T *argvars;
7715 typval_T *rettv;
7717 long lnum;
7718 char_u *line;
7719 list_T *l = NULL;
7720 listitem_T *li = NULL;
7721 typval_T *tv;
7722 long added = 0;
7724 lnum = get_tv_lnum(argvars);
7725 if (lnum >= 0
7726 && lnum <= curbuf->b_ml.ml_line_count
7727 && u_save(lnum, lnum + 1) == OK)
7729 if (argvars[1].v_type == VAR_LIST)
7731 l = argvars[1].vval.v_list;
7732 if (l == NULL)
7733 return;
7734 li = l->lv_first;
7736 rettv->vval.v_number = 0; /* Default: Success */
7737 for (;;)
7739 if (l == NULL)
7740 tv = &argvars[1]; /* append a string */
7741 else if (li == NULL)
7742 break; /* end of list */
7743 else
7744 tv = &li->li_tv; /* append item from list */
7745 line = get_tv_string_chk(tv);
7746 if (line == NULL) /* type error */
7748 rettv->vval.v_number = 1; /* Failed */
7749 break;
7751 ml_append(lnum + added, line, (colnr_T)0, FALSE);
7752 ++added;
7753 if (l == NULL)
7754 break;
7755 li = li->li_next;
7758 appended_lines_mark(lnum, added);
7759 if (curwin->w_cursor.lnum > lnum)
7760 curwin->w_cursor.lnum += added;
7762 else
7763 rettv->vval.v_number = 1; /* Failed */
7767 * "argc()" function
7769 /* ARGSUSED */
7770 static void
7771 f_argc(argvars, rettv)
7772 typval_T *argvars;
7773 typval_T *rettv;
7775 rettv->vval.v_number = ARGCOUNT;
7779 * "argidx()" function
7781 /* ARGSUSED */
7782 static void
7783 f_argidx(argvars, rettv)
7784 typval_T *argvars;
7785 typval_T *rettv;
7787 rettv->vval.v_number = curwin->w_arg_idx;
7791 * "argv(nr)" function
7793 static void
7794 f_argv(argvars, rettv)
7795 typval_T *argvars;
7796 typval_T *rettv;
7798 int idx;
7800 if (argvars[0].v_type != VAR_UNKNOWN)
7802 idx = get_tv_number_chk(&argvars[0], NULL);
7803 if (idx >= 0 && idx < ARGCOUNT)
7804 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
7805 else
7806 rettv->vval.v_string = NULL;
7807 rettv->v_type = VAR_STRING;
7809 else if (rettv_list_alloc(rettv) == OK)
7810 for (idx = 0; idx < ARGCOUNT; ++idx)
7811 list_append_string(rettv->vval.v_list,
7812 alist_name(&ARGLIST[idx]), -1);
7816 * "browse(save, title, initdir, default)" function
7818 /* ARGSUSED */
7819 static void
7820 f_browse(argvars, rettv)
7821 typval_T *argvars;
7822 typval_T *rettv;
7824 #ifdef FEAT_BROWSE
7825 int save;
7826 char_u *title;
7827 char_u *initdir;
7828 char_u *defname;
7829 char_u buf[NUMBUFLEN];
7830 char_u buf2[NUMBUFLEN];
7831 int error = FALSE;
7833 save = get_tv_number_chk(&argvars[0], &error);
7834 title = get_tv_string_chk(&argvars[1]);
7835 initdir = get_tv_string_buf_chk(&argvars[2], buf);
7836 defname = get_tv_string_buf_chk(&argvars[3], buf2);
7838 if (error || title == NULL || initdir == NULL || defname == NULL)
7839 rettv->vval.v_string = NULL;
7840 else
7841 rettv->vval.v_string =
7842 do_browse(save ? BROWSE_SAVE : 0,
7843 title, defname, NULL, initdir, NULL, curbuf);
7844 #else
7845 rettv->vval.v_string = NULL;
7846 #endif
7847 rettv->v_type = VAR_STRING;
7851 * "browsedir(title, initdir)" function
7853 /* ARGSUSED */
7854 static void
7855 f_browsedir(argvars, rettv)
7856 typval_T *argvars;
7857 typval_T *rettv;
7859 #ifdef FEAT_BROWSE
7860 char_u *title;
7861 char_u *initdir;
7862 char_u buf[NUMBUFLEN];
7864 title = get_tv_string_chk(&argvars[0]);
7865 initdir = get_tv_string_buf_chk(&argvars[1], buf);
7867 if (title == NULL || initdir == NULL)
7868 rettv->vval.v_string = NULL;
7869 else
7870 rettv->vval.v_string = do_browse(BROWSE_DIR,
7871 title, NULL, NULL, initdir, NULL, curbuf);
7872 #else
7873 rettv->vval.v_string = NULL;
7874 #endif
7875 rettv->v_type = VAR_STRING;
7878 static buf_T *find_buffer __ARGS((typval_T *avar));
7881 * Find a buffer by number or exact name.
7883 static buf_T *
7884 find_buffer(avar)
7885 typval_T *avar;
7887 buf_T *buf = NULL;
7889 if (avar->v_type == VAR_NUMBER)
7890 buf = buflist_findnr((int)avar->vval.v_number);
7891 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
7893 buf = buflist_findname_exp(avar->vval.v_string);
7894 if (buf == NULL)
7896 /* No full path name match, try a match with a URL or a "nofile"
7897 * buffer, these don't use the full path. */
7898 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
7899 if (buf->b_fname != NULL
7900 && (path_with_url(buf->b_fname)
7901 #ifdef FEAT_QUICKFIX
7902 || bt_nofile(buf)
7903 #endif
7905 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
7906 break;
7909 return buf;
7913 * "bufexists(expr)" function
7915 static void
7916 f_bufexists(argvars, rettv)
7917 typval_T *argvars;
7918 typval_T *rettv;
7920 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
7924 * "buflisted(expr)" function
7926 static void
7927 f_buflisted(argvars, rettv)
7928 typval_T *argvars;
7929 typval_T *rettv;
7931 buf_T *buf;
7933 buf = find_buffer(&argvars[0]);
7934 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
7938 * "bufloaded(expr)" function
7940 static void
7941 f_bufloaded(argvars, rettv)
7942 typval_T *argvars;
7943 typval_T *rettv;
7945 buf_T *buf;
7947 buf = find_buffer(&argvars[0]);
7948 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
7951 static buf_T *get_buf_tv __ARGS((typval_T *tv));
7954 * Get buffer by number or pattern.
7956 static buf_T *
7957 get_buf_tv(tv)
7958 typval_T *tv;
7960 char_u *name = tv->vval.v_string;
7961 int save_magic;
7962 char_u *save_cpo;
7963 buf_T *buf;
7965 if (tv->v_type == VAR_NUMBER)
7966 return buflist_findnr((int)tv->vval.v_number);
7967 if (tv->v_type != VAR_STRING)
7968 return NULL;
7969 if (name == NULL || *name == NUL)
7970 return curbuf;
7971 if (name[0] == '$' && name[1] == NUL)
7972 return lastbuf;
7974 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
7975 save_magic = p_magic;
7976 p_magic = TRUE;
7977 save_cpo = p_cpo;
7978 p_cpo = (char_u *)"";
7980 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
7981 TRUE, FALSE));
7983 p_magic = save_magic;
7984 p_cpo = save_cpo;
7986 /* If not found, try expanding the name, like done for bufexists(). */
7987 if (buf == NULL)
7988 buf = find_buffer(tv);
7990 return buf;
7994 * "bufname(expr)" function
7996 static void
7997 f_bufname(argvars, rettv)
7998 typval_T *argvars;
7999 typval_T *rettv;
8001 buf_T *buf;
8003 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8004 ++emsg_off;
8005 buf = get_buf_tv(&argvars[0]);
8006 rettv->v_type = VAR_STRING;
8007 if (buf != NULL && buf->b_fname != NULL)
8008 rettv->vval.v_string = vim_strsave(buf->b_fname);
8009 else
8010 rettv->vval.v_string = NULL;
8011 --emsg_off;
8015 * "bufnr(expr)" function
8017 static void
8018 f_bufnr(argvars, rettv)
8019 typval_T *argvars;
8020 typval_T *rettv;
8022 buf_T *buf;
8023 int error = FALSE;
8024 char_u *name;
8026 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8027 ++emsg_off;
8028 buf = get_buf_tv(&argvars[0]);
8029 --emsg_off;
8031 /* If the buffer isn't found and the second argument is not zero create a
8032 * new buffer. */
8033 if (buf == NULL
8034 && argvars[1].v_type != VAR_UNKNOWN
8035 && get_tv_number_chk(&argvars[1], &error) != 0
8036 && !error
8037 && (name = get_tv_string_chk(&argvars[0])) != NULL
8038 && !error)
8039 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8041 if (buf != NULL)
8042 rettv->vval.v_number = buf->b_fnum;
8043 else
8044 rettv->vval.v_number = -1;
8048 * "bufwinnr(nr)" function
8050 static void
8051 f_bufwinnr(argvars, rettv)
8052 typval_T *argvars;
8053 typval_T *rettv;
8055 #ifdef FEAT_WINDOWS
8056 win_T *wp;
8057 int winnr = 0;
8058 #endif
8059 buf_T *buf;
8061 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8062 ++emsg_off;
8063 buf = get_buf_tv(&argvars[0]);
8064 #ifdef FEAT_WINDOWS
8065 for (wp = firstwin; wp; wp = wp->w_next)
8067 ++winnr;
8068 if (wp->w_buffer == buf)
8069 break;
8071 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8072 #else
8073 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8074 #endif
8075 --emsg_off;
8079 * "byte2line(byte)" function
8081 /*ARGSUSED*/
8082 static void
8083 f_byte2line(argvars, rettv)
8084 typval_T *argvars;
8085 typval_T *rettv;
8087 #ifndef FEAT_BYTEOFF
8088 rettv->vval.v_number = -1;
8089 #else
8090 long boff = 0;
8092 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8093 if (boff < 0)
8094 rettv->vval.v_number = -1;
8095 else
8096 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8097 (linenr_T)0, &boff);
8098 #endif
8102 * "byteidx()" function
8104 /*ARGSUSED*/
8105 static void
8106 f_byteidx(argvars, rettv)
8107 typval_T *argvars;
8108 typval_T *rettv;
8110 #ifdef FEAT_MBYTE
8111 char_u *t;
8112 #endif
8113 char_u *str;
8114 long idx;
8116 str = get_tv_string_chk(&argvars[0]);
8117 idx = get_tv_number_chk(&argvars[1], NULL);
8118 rettv->vval.v_number = -1;
8119 if (str == NULL || idx < 0)
8120 return;
8122 #ifdef FEAT_MBYTE
8123 t = str;
8124 for ( ; idx > 0; idx--)
8126 if (*t == NUL) /* EOL reached */
8127 return;
8128 t += (*mb_ptr2len)(t);
8130 rettv->vval.v_number = (varnumber_T)(t - str);
8131 #else
8132 if (idx <= STRLEN(str))
8133 rettv->vval.v_number = idx;
8134 #endif
8138 * "call(func, arglist)" function
8140 static void
8141 f_call(argvars, rettv)
8142 typval_T *argvars;
8143 typval_T *rettv;
8145 char_u *func;
8146 typval_T argv[MAX_FUNC_ARGS + 1];
8147 int argc = 0;
8148 listitem_T *item;
8149 int dummy;
8150 dict_T *selfdict = NULL;
8152 rettv->vval.v_number = 0;
8153 if (argvars[1].v_type != VAR_LIST)
8155 EMSG(_(e_listreq));
8156 return;
8158 if (argvars[1].vval.v_list == NULL)
8159 return;
8161 if (argvars[0].v_type == VAR_FUNC)
8162 func = argvars[0].vval.v_string;
8163 else
8164 func = get_tv_string(&argvars[0]);
8165 if (*func == NUL)
8166 return; /* type error or empty name */
8168 if (argvars[2].v_type != VAR_UNKNOWN)
8170 if (argvars[2].v_type != VAR_DICT)
8172 EMSG(_(e_dictreq));
8173 return;
8175 selfdict = argvars[2].vval.v_dict;
8178 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
8179 item = item->li_next)
8181 if (argc == MAX_FUNC_ARGS)
8183 EMSG(_("E699: Too many arguments"));
8184 break;
8186 /* Make a copy of each argument. This is needed to be able to set
8187 * v_lock to VAR_FIXED in the copy without changing the original list.
8189 copy_tv(&item->li_tv, &argv[argc++]);
8192 if (item == NULL)
8193 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
8194 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
8195 &dummy, TRUE, selfdict);
8197 /* Free the arguments. */
8198 while (argc > 0)
8199 clear_tv(&argv[--argc]);
8203 * "changenr()" function
8205 /*ARGSUSED*/
8206 static void
8207 f_changenr(argvars, rettv)
8208 typval_T *argvars;
8209 typval_T *rettv;
8211 rettv->vval.v_number = curbuf->b_u_seq_cur;
8215 * "char2nr(string)" function
8217 static void
8218 f_char2nr(argvars, rettv)
8219 typval_T *argvars;
8220 typval_T *rettv;
8222 #ifdef FEAT_MBYTE
8223 if (has_mbyte)
8224 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
8225 else
8226 #endif
8227 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
8231 * "cindent(lnum)" function
8233 static void
8234 f_cindent(argvars, rettv)
8235 typval_T *argvars;
8236 typval_T *rettv;
8238 #ifdef FEAT_CINDENT
8239 pos_T pos;
8240 linenr_T lnum;
8242 pos = curwin->w_cursor;
8243 lnum = get_tv_lnum(argvars);
8244 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
8246 curwin->w_cursor.lnum = lnum;
8247 rettv->vval.v_number = get_c_indent();
8248 curwin->w_cursor = pos;
8250 else
8251 #endif
8252 rettv->vval.v_number = -1;
8256 * "clearmatches()" function
8258 /*ARGSUSED*/
8259 static void
8260 f_clearmatches(argvars, rettv)
8261 typval_T *argvars;
8262 typval_T *rettv;
8264 #ifdef FEAT_SEARCH_EXTRA
8265 clear_matches(curwin);
8266 #endif
8270 * "col(string)" function
8272 static void
8273 f_col(argvars, rettv)
8274 typval_T *argvars;
8275 typval_T *rettv;
8277 colnr_T col = 0;
8278 pos_T *fp;
8279 int fnum = curbuf->b_fnum;
8281 fp = var2fpos(&argvars[0], FALSE, &fnum);
8282 if (fp != NULL && fnum == curbuf->b_fnum)
8284 if (fp->col == MAXCOL)
8286 /* '> can be MAXCOL, get the length of the line then */
8287 if (fp->lnum <= curbuf->b_ml.ml_line_count)
8288 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
8289 else
8290 col = MAXCOL;
8292 else
8294 col = fp->col + 1;
8295 #ifdef FEAT_VIRTUALEDIT
8296 /* col(".") when the cursor is on the NUL at the end of the line
8297 * because of "coladd" can be seen as an extra column. */
8298 if (virtual_active() && fp == &curwin->w_cursor)
8300 char_u *p = ml_get_cursor();
8302 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
8303 curwin->w_virtcol - curwin->w_cursor.coladd))
8305 # ifdef FEAT_MBYTE
8306 int l;
8308 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
8309 col += l;
8310 # else
8311 if (*p != NUL && p[1] == NUL)
8312 ++col;
8313 # endif
8316 #endif
8319 rettv->vval.v_number = col;
8322 #if defined(FEAT_INS_EXPAND)
8324 * "complete()" function
8326 /*ARGSUSED*/
8327 static void
8328 f_complete(argvars, rettv)
8329 typval_T *argvars;
8330 typval_T *rettv;
8332 int startcol;
8334 if ((State & INSERT) == 0)
8336 EMSG(_("E785: complete() can only be used in Insert mode"));
8337 return;
8340 /* Check for undo allowed here, because if something was already inserted
8341 * the line was already saved for undo and this check isn't done. */
8342 if (!undo_allowed())
8343 return;
8345 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
8347 EMSG(_(e_invarg));
8348 return;
8351 startcol = get_tv_number_chk(&argvars[0], NULL);
8352 if (startcol <= 0)
8353 return;
8355 set_completion(startcol - 1, argvars[1].vval.v_list);
8359 * "complete_add()" function
8361 /*ARGSUSED*/
8362 static void
8363 f_complete_add(argvars, rettv)
8364 typval_T *argvars;
8365 typval_T *rettv;
8367 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
8371 * "complete_check()" function
8373 /*ARGSUSED*/
8374 static void
8375 f_complete_check(argvars, rettv)
8376 typval_T *argvars;
8377 typval_T *rettv;
8379 int saved = RedrawingDisabled;
8381 RedrawingDisabled = 0;
8382 ins_compl_check_keys(0);
8383 rettv->vval.v_number = compl_interrupted;
8384 RedrawingDisabled = saved;
8386 #endif
8389 * "confirm(message, buttons[, default [, type]])" function
8391 /*ARGSUSED*/
8392 static void
8393 f_confirm(argvars, rettv)
8394 typval_T *argvars;
8395 typval_T *rettv;
8397 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
8398 char_u *message;
8399 char_u *buttons = NULL;
8400 char_u buf[NUMBUFLEN];
8401 char_u buf2[NUMBUFLEN];
8402 int def = 1;
8403 int type = VIM_GENERIC;
8404 char_u *typestr;
8405 int error = FALSE;
8407 message = get_tv_string_chk(&argvars[0]);
8408 if (message == NULL)
8409 error = TRUE;
8410 if (argvars[1].v_type != VAR_UNKNOWN)
8412 buttons = get_tv_string_buf_chk(&argvars[1], buf);
8413 if (buttons == NULL)
8414 error = TRUE;
8415 if (argvars[2].v_type != VAR_UNKNOWN)
8417 def = get_tv_number_chk(&argvars[2], &error);
8418 if (argvars[3].v_type != VAR_UNKNOWN)
8420 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
8421 if (typestr == NULL)
8422 error = TRUE;
8423 else
8425 switch (TOUPPER_ASC(*typestr))
8427 case 'E': type = VIM_ERROR; break;
8428 case 'Q': type = VIM_QUESTION; break;
8429 case 'I': type = VIM_INFO; break;
8430 case 'W': type = VIM_WARNING; break;
8431 case 'G': type = VIM_GENERIC; break;
8438 if (buttons == NULL || *buttons == NUL)
8439 buttons = (char_u *)_("&Ok");
8441 if (error)
8442 rettv->vval.v_number = 0;
8443 else
8444 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
8445 def, NULL);
8446 #else
8447 rettv->vval.v_number = 0;
8448 #endif
8452 * "copy()" function
8454 static void
8455 f_copy(argvars, rettv)
8456 typval_T *argvars;
8457 typval_T *rettv;
8459 item_copy(&argvars[0], rettv, FALSE, 0);
8463 * "count()" function
8465 static void
8466 f_count(argvars, rettv)
8467 typval_T *argvars;
8468 typval_T *rettv;
8470 long n = 0;
8471 int ic = FALSE;
8473 if (argvars[0].v_type == VAR_LIST)
8475 listitem_T *li;
8476 list_T *l;
8477 long idx;
8479 if ((l = argvars[0].vval.v_list) != NULL)
8481 li = l->lv_first;
8482 if (argvars[2].v_type != VAR_UNKNOWN)
8484 int error = FALSE;
8486 ic = get_tv_number_chk(&argvars[2], &error);
8487 if (argvars[3].v_type != VAR_UNKNOWN)
8489 idx = get_tv_number_chk(&argvars[3], &error);
8490 if (!error)
8492 li = list_find(l, idx);
8493 if (li == NULL)
8494 EMSGN(_(e_listidx), idx);
8497 if (error)
8498 li = NULL;
8501 for ( ; li != NULL; li = li->li_next)
8502 if (tv_equal(&li->li_tv, &argvars[1], ic))
8503 ++n;
8506 else if (argvars[0].v_type == VAR_DICT)
8508 int todo;
8509 dict_T *d;
8510 hashitem_T *hi;
8512 if ((d = argvars[0].vval.v_dict) != NULL)
8514 int error = FALSE;
8516 if (argvars[2].v_type != VAR_UNKNOWN)
8518 ic = get_tv_number_chk(&argvars[2], &error);
8519 if (argvars[3].v_type != VAR_UNKNOWN)
8520 EMSG(_(e_invarg));
8523 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
8524 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
8526 if (!HASHITEM_EMPTY(hi))
8528 --todo;
8529 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
8530 ++n;
8535 else
8536 EMSG2(_(e_listdictarg), "count()");
8537 rettv->vval.v_number = n;
8541 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
8543 * Checks the existence of a cscope connection.
8545 /*ARGSUSED*/
8546 static void
8547 f_cscope_connection(argvars, rettv)
8548 typval_T *argvars;
8549 typval_T *rettv;
8551 #ifdef FEAT_CSCOPE
8552 int num = 0;
8553 char_u *dbpath = NULL;
8554 char_u *prepend = NULL;
8555 char_u buf[NUMBUFLEN];
8557 if (argvars[0].v_type != VAR_UNKNOWN
8558 && argvars[1].v_type != VAR_UNKNOWN)
8560 num = (int)get_tv_number(&argvars[0]);
8561 dbpath = get_tv_string(&argvars[1]);
8562 if (argvars[2].v_type != VAR_UNKNOWN)
8563 prepend = get_tv_string_buf(&argvars[2], buf);
8566 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
8567 #else
8568 rettv->vval.v_number = 0;
8569 #endif
8573 * "cursor(lnum, col)" function
8575 * Moves the cursor to the specified line and column
8577 /*ARGSUSED*/
8578 static void
8579 f_cursor(argvars, rettv)
8580 typval_T *argvars;
8581 typval_T *rettv;
8583 long line, col;
8584 #ifdef FEAT_VIRTUALEDIT
8585 long coladd = 0;
8586 #endif
8588 if (argvars[1].v_type == VAR_UNKNOWN)
8590 pos_T pos;
8592 if (list2fpos(argvars, &pos, NULL) == FAIL)
8593 return;
8594 line = pos.lnum;
8595 col = pos.col;
8596 #ifdef FEAT_VIRTUALEDIT
8597 coladd = pos.coladd;
8598 #endif
8600 else
8602 line = get_tv_lnum(argvars);
8603 col = get_tv_number_chk(&argvars[1], NULL);
8604 #ifdef FEAT_VIRTUALEDIT
8605 if (argvars[2].v_type != VAR_UNKNOWN)
8606 coladd = get_tv_number_chk(&argvars[2], NULL);
8607 #endif
8609 if (line < 0 || col < 0
8610 #ifdef FEAT_VIRTUALEDIT
8611 || coladd < 0
8612 #endif
8614 return; /* type error; errmsg already given */
8615 if (line > 0)
8616 curwin->w_cursor.lnum = line;
8617 if (col > 0)
8618 curwin->w_cursor.col = col - 1;
8619 #ifdef FEAT_VIRTUALEDIT
8620 curwin->w_cursor.coladd = coladd;
8621 #endif
8623 /* Make sure the cursor is in a valid position. */
8624 check_cursor();
8625 #ifdef FEAT_MBYTE
8626 /* Correct cursor for multi-byte character. */
8627 if (has_mbyte)
8628 mb_adjust_cursor();
8629 #endif
8631 curwin->w_set_curswant = TRUE;
8635 * "deepcopy()" function
8637 static void
8638 f_deepcopy(argvars, rettv)
8639 typval_T *argvars;
8640 typval_T *rettv;
8642 int noref = 0;
8644 if (argvars[1].v_type != VAR_UNKNOWN)
8645 noref = get_tv_number_chk(&argvars[1], NULL);
8646 if (noref < 0 || noref > 1)
8647 EMSG(_(e_invarg));
8648 else
8649 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? ++current_copyID : 0);
8653 * "delete()" function
8655 static void
8656 f_delete(argvars, rettv)
8657 typval_T *argvars;
8658 typval_T *rettv;
8660 if (check_restricted() || check_secure())
8661 rettv->vval.v_number = -1;
8662 else
8663 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
8667 * "did_filetype()" function
8669 /*ARGSUSED*/
8670 static void
8671 f_did_filetype(argvars, rettv)
8672 typval_T *argvars;
8673 typval_T *rettv;
8675 #ifdef FEAT_AUTOCMD
8676 rettv->vval.v_number = did_filetype;
8677 #else
8678 rettv->vval.v_number = 0;
8679 #endif
8683 * "diff_filler()" function
8685 /*ARGSUSED*/
8686 static void
8687 f_diff_filler(argvars, rettv)
8688 typval_T *argvars;
8689 typval_T *rettv;
8691 #ifdef FEAT_DIFF
8692 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
8693 #endif
8697 * "diff_hlID()" function
8699 /*ARGSUSED*/
8700 static void
8701 f_diff_hlID(argvars, rettv)
8702 typval_T *argvars;
8703 typval_T *rettv;
8705 #ifdef FEAT_DIFF
8706 linenr_T lnum = get_tv_lnum(argvars);
8707 static linenr_T prev_lnum = 0;
8708 static int changedtick = 0;
8709 static int fnum = 0;
8710 static int change_start = 0;
8711 static int change_end = 0;
8712 static hlf_T hlID = 0;
8713 int filler_lines;
8714 int col;
8716 if (lnum < 0) /* ignore type error in {lnum} arg */
8717 lnum = 0;
8718 if (lnum != prev_lnum
8719 || changedtick != curbuf->b_changedtick
8720 || fnum != curbuf->b_fnum)
8722 /* New line, buffer, change: need to get the values. */
8723 filler_lines = diff_check(curwin, lnum);
8724 if (filler_lines < 0)
8726 if (filler_lines == -1)
8728 change_start = MAXCOL;
8729 change_end = -1;
8730 if (diff_find_change(curwin, lnum, &change_start, &change_end))
8731 hlID = HLF_ADD; /* added line */
8732 else
8733 hlID = HLF_CHD; /* changed line */
8735 else
8736 hlID = HLF_ADD; /* added line */
8738 else
8739 hlID = (hlf_T)0;
8740 prev_lnum = lnum;
8741 changedtick = curbuf->b_changedtick;
8742 fnum = curbuf->b_fnum;
8745 if (hlID == HLF_CHD || hlID == HLF_TXD)
8747 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
8748 if (col >= change_start && col <= change_end)
8749 hlID = HLF_TXD; /* changed text */
8750 else
8751 hlID = HLF_CHD; /* changed line */
8753 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
8754 #endif
8758 * "empty({expr})" function
8760 static void
8761 f_empty(argvars, rettv)
8762 typval_T *argvars;
8763 typval_T *rettv;
8765 int n;
8767 switch (argvars[0].v_type)
8769 case VAR_STRING:
8770 case VAR_FUNC:
8771 n = argvars[0].vval.v_string == NULL
8772 || *argvars[0].vval.v_string == NUL;
8773 break;
8774 case VAR_NUMBER:
8775 n = argvars[0].vval.v_number == 0;
8776 break;
8777 case VAR_LIST:
8778 n = argvars[0].vval.v_list == NULL
8779 || argvars[0].vval.v_list->lv_first == NULL;
8780 break;
8781 case VAR_DICT:
8782 n = argvars[0].vval.v_dict == NULL
8783 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
8784 break;
8785 default:
8786 EMSG2(_(e_intern2), "f_empty()");
8787 n = 0;
8790 rettv->vval.v_number = n;
8794 * "escape({string}, {chars})" function
8796 static void
8797 f_escape(argvars, rettv)
8798 typval_T *argvars;
8799 typval_T *rettv;
8801 char_u buf[NUMBUFLEN];
8803 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
8804 get_tv_string_buf(&argvars[1], buf));
8805 rettv->v_type = VAR_STRING;
8809 * "eval()" function
8811 /*ARGSUSED*/
8812 static void
8813 f_eval(argvars, rettv)
8814 typval_T *argvars;
8815 typval_T *rettv;
8817 char_u *s;
8819 s = get_tv_string_chk(&argvars[0]);
8820 if (s != NULL)
8821 s = skipwhite(s);
8823 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
8825 rettv->v_type = VAR_NUMBER;
8826 rettv->vval.v_number = 0;
8828 else if (*s != NUL)
8829 EMSG(_(e_trailing));
8833 * "eventhandler()" function
8835 /*ARGSUSED*/
8836 static void
8837 f_eventhandler(argvars, rettv)
8838 typval_T *argvars;
8839 typval_T *rettv;
8841 rettv->vval.v_number = vgetc_busy;
8845 * "executable()" function
8847 static void
8848 f_executable(argvars, rettv)
8849 typval_T *argvars;
8850 typval_T *rettv;
8852 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
8856 * "exists()" function
8858 static void
8859 f_exists(argvars, rettv)
8860 typval_T *argvars;
8861 typval_T *rettv;
8863 char_u *p;
8864 char_u *name;
8865 int n = FALSE;
8866 int len = 0;
8868 p = get_tv_string(&argvars[0]);
8869 if (*p == '$') /* environment variable */
8871 /* first try "normal" environment variables (fast) */
8872 if (mch_getenv(p + 1) != NULL)
8873 n = TRUE;
8874 else
8876 /* try expanding things like $VIM and ${HOME} */
8877 p = expand_env_save(p);
8878 if (p != NULL && *p != '$')
8879 n = TRUE;
8880 vim_free(p);
8883 else if (*p == '&' || *p == '+') /* option */
8885 n = (get_option_tv(&p, NULL, TRUE) == OK);
8886 if (*skipwhite(p) != NUL)
8887 n = FALSE; /* trailing garbage */
8889 else if (*p == '*') /* internal or user defined function */
8891 n = function_exists(p + 1);
8893 else if (*p == ':')
8895 n = cmd_exists(p + 1);
8897 else if (*p == '#')
8899 #ifdef FEAT_AUTOCMD
8900 if (p[1] == '#')
8901 n = autocmd_supported(p + 2);
8902 else
8903 n = au_exists(p + 1);
8904 #endif
8906 else /* internal variable */
8908 char_u *tofree;
8909 typval_T tv;
8911 /* get_name_len() takes care of expanding curly braces */
8912 name = p;
8913 len = get_name_len(&p, &tofree, TRUE, FALSE);
8914 if (len > 0)
8916 if (tofree != NULL)
8917 name = tofree;
8918 n = (get_var_tv(name, len, &tv, FALSE) == OK);
8919 if (n)
8921 /* handle d.key, l[idx], f(expr) */
8922 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
8923 if (n)
8924 clear_tv(&tv);
8927 if (*p != NUL)
8928 n = FALSE;
8930 vim_free(tofree);
8933 rettv->vval.v_number = n;
8937 * "expand()" function
8939 static void
8940 f_expand(argvars, rettv)
8941 typval_T *argvars;
8942 typval_T *rettv;
8944 char_u *s;
8945 int len;
8946 char_u *errormsg;
8947 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
8948 expand_T xpc;
8949 int error = FALSE;
8951 rettv->v_type = VAR_STRING;
8952 s = get_tv_string(&argvars[0]);
8953 if (*s == '%' || *s == '#' || *s == '<')
8955 ++emsg_off;
8956 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
8957 --emsg_off;
8959 else
8961 /* When the optional second argument is non-zero, don't remove matches
8962 * for 'suffixes' and 'wildignore' */
8963 if (argvars[1].v_type != VAR_UNKNOWN
8964 && get_tv_number_chk(&argvars[1], &error))
8965 flags |= WILD_KEEP_ALL;
8966 if (!error)
8968 ExpandInit(&xpc);
8969 xpc.xp_context = EXPAND_FILES;
8970 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
8972 else
8973 rettv->vval.v_string = NULL;
8978 * "extend(list, list [, idx])" function
8979 * "extend(dict, dict [, action])" function
8981 static void
8982 f_extend(argvars, rettv)
8983 typval_T *argvars;
8984 typval_T *rettv;
8986 rettv->vval.v_number = 0;
8987 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
8989 list_T *l1, *l2;
8990 listitem_T *item;
8991 long before;
8992 int error = FALSE;
8994 l1 = argvars[0].vval.v_list;
8995 l2 = argvars[1].vval.v_list;
8996 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
8997 && l2 != NULL)
8999 if (argvars[2].v_type != VAR_UNKNOWN)
9001 before = get_tv_number_chk(&argvars[2], &error);
9002 if (error)
9003 return; /* type error; errmsg already given */
9005 if (before == l1->lv_len)
9006 item = NULL;
9007 else
9009 item = list_find(l1, before);
9010 if (item == NULL)
9012 EMSGN(_(e_listidx), before);
9013 return;
9017 else
9018 item = NULL;
9019 list_extend(l1, l2, item);
9021 copy_tv(&argvars[0], rettv);
9024 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9026 dict_T *d1, *d2;
9027 dictitem_T *di1;
9028 char_u *action;
9029 int i;
9030 hashitem_T *hi2;
9031 int todo;
9033 d1 = argvars[0].vval.v_dict;
9034 d2 = argvars[1].vval.v_dict;
9035 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9036 && d2 != NULL)
9038 /* Check the third argument. */
9039 if (argvars[2].v_type != VAR_UNKNOWN)
9041 static char *(av[]) = {"keep", "force", "error"};
9043 action = get_tv_string_chk(&argvars[2]);
9044 if (action == NULL)
9045 return; /* type error; errmsg already given */
9046 for (i = 0; i < 3; ++i)
9047 if (STRCMP(action, av[i]) == 0)
9048 break;
9049 if (i == 3)
9051 EMSG2(_(e_invarg2), action);
9052 return;
9055 else
9056 action = (char_u *)"force";
9058 /* Go over all entries in the second dict and add them to the
9059 * first dict. */
9060 todo = (int)d2->dv_hashtab.ht_used;
9061 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9063 if (!HASHITEM_EMPTY(hi2))
9065 --todo;
9066 di1 = dict_find(d1, hi2->hi_key, -1);
9067 if (di1 == NULL)
9069 di1 = dictitem_copy(HI2DI(hi2));
9070 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9071 dictitem_free(di1);
9073 else if (*action == 'e')
9075 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9076 break;
9078 else if (*action == 'f')
9080 clear_tv(&di1->di_tv);
9081 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9086 copy_tv(&argvars[0], rettv);
9089 else
9090 EMSG2(_(e_listdictarg), "extend()");
9094 * "feedkeys()" function
9096 /*ARGSUSED*/
9097 static void
9098 f_feedkeys(argvars, rettv)
9099 typval_T *argvars;
9100 typval_T *rettv;
9102 int remap = TRUE;
9103 char_u *keys, *flags;
9104 char_u nbuf[NUMBUFLEN];
9105 int typed = FALSE;
9106 char_u *keys_esc;
9108 /* This is not allowed in the sandbox. If the commands would still be
9109 * executed in the sandbox it would be OK, but it probably happens later,
9110 * when "sandbox" is no longer set. */
9111 if (check_secure())
9112 return;
9114 rettv->vval.v_number = 0;
9115 keys = get_tv_string(&argvars[0]);
9116 if (*keys != NUL)
9118 if (argvars[1].v_type != VAR_UNKNOWN)
9120 flags = get_tv_string_buf(&argvars[1], nbuf);
9121 for ( ; *flags != NUL; ++flags)
9123 switch (*flags)
9125 case 'n': remap = FALSE; break;
9126 case 'm': remap = TRUE; break;
9127 case 't': typed = TRUE; break;
9132 /* Need to escape K_SPECIAL and CSI before putting the string in the
9133 * typeahead buffer. */
9134 keys_esc = vim_strsave_escape_csi(keys);
9135 if (keys_esc != NULL)
9137 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
9138 typebuf.tb_len, !typed, FALSE);
9139 vim_free(keys_esc);
9140 if (vgetc_busy)
9141 typebuf_was_filled = TRUE;
9147 * "filereadable()" function
9149 static void
9150 f_filereadable(argvars, rettv)
9151 typval_T *argvars;
9152 typval_T *rettv;
9154 FILE *fd;
9155 char_u *p;
9156 int n;
9158 p = get_tv_string(&argvars[0]);
9159 if (*p && !mch_isdir(p) && (fd = mch_fopen((char *)p, "r")) != NULL)
9161 n = TRUE;
9162 fclose(fd);
9164 else
9165 n = FALSE;
9167 rettv->vval.v_number = n;
9171 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
9172 * rights to write into.
9174 static void
9175 f_filewritable(argvars, rettv)
9176 typval_T *argvars;
9177 typval_T *rettv;
9179 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
9182 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int dir));
9184 static void
9185 findfilendir(argvars, rettv, dir)
9186 typval_T *argvars;
9187 typval_T *rettv;
9188 int dir;
9190 #ifdef FEAT_SEARCHPATH
9191 char_u *fname;
9192 char_u *fresult = NULL;
9193 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
9194 char_u *p;
9195 char_u pathbuf[NUMBUFLEN];
9196 int count = 1;
9197 int first = TRUE;
9198 int error = FALSE;
9199 #endif
9201 rettv->vval.v_string = NULL;
9202 rettv->v_type = VAR_STRING;
9204 #ifdef FEAT_SEARCHPATH
9205 fname = get_tv_string(&argvars[0]);
9207 if (argvars[1].v_type != VAR_UNKNOWN)
9209 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
9210 if (p == NULL)
9211 error = TRUE;
9212 else
9214 if (*p != NUL)
9215 path = p;
9217 if (argvars[2].v_type != VAR_UNKNOWN)
9218 count = get_tv_number_chk(&argvars[2], &error);
9222 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
9223 error = TRUE;
9225 if (*fname != NUL && !error)
9229 if (rettv->v_type == VAR_STRING)
9230 vim_free(fresult);
9231 fresult = find_file_in_path_option(first ? fname : NULL,
9232 first ? (int)STRLEN(fname) : 0,
9233 0, first, path, dir, curbuf->b_ffname,
9234 dir ? (char_u *)"" : curbuf->b_p_sua);
9235 first = FALSE;
9237 if (fresult != NULL && rettv->v_type == VAR_LIST)
9238 list_append_string(rettv->vval.v_list, fresult, -1);
9240 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
9243 if (rettv->v_type == VAR_STRING)
9244 rettv->vval.v_string = fresult;
9245 #endif
9248 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
9249 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
9252 * Implementation of map() and filter().
9254 static void
9255 filter_map(argvars, rettv, map)
9256 typval_T *argvars;
9257 typval_T *rettv;
9258 int map;
9260 char_u buf[NUMBUFLEN];
9261 char_u *expr;
9262 listitem_T *li, *nli;
9263 list_T *l = NULL;
9264 dictitem_T *di;
9265 hashtab_T *ht;
9266 hashitem_T *hi;
9267 dict_T *d = NULL;
9268 typval_T save_val;
9269 typval_T save_key;
9270 int rem;
9271 int todo;
9272 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
9273 int save_did_emsg;
9275 rettv->vval.v_number = 0;
9276 if (argvars[0].v_type == VAR_LIST)
9278 if ((l = argvars[0].vval.v_list) == NULL
9279 || (map && tv_check_lock(l->lv_lock, ermsg)))
9280 return;
9282 else if (argvars[0].v_type == VAR_DICT)
9284 if ((d = argvars[0].vval.v_dict) == NULL
9285 || (map && tv_check_lock(d->dv_lock, ermsg)))
9286 return;
9288 else
9290 EMSG2(_(e_listdictarg), ermsg);
9291 return;
9294 expr = get_tv_string_buf_chk(&argvars[1], buf);
9295 /* On type errors, the preceding call has already displayed an error
9296 * message. Avoid a misleading error message for an empty string that
9297 * was not passed as argument. */
9298 if (expr != NULL)
9300 prepare_vimvar(VV_VAL, &save_val);
9301 expr = skipwhite(expr);
9303 /* We reset "did_emsg" to be able to detect whether an error
9304 * occurred during evaluation of the expression. */
9305 save_did_emsg = did_emsg;
9306 did_emsg = FALSE;
9308 if (argvars[0].v_type == VAR_DICT)
9310 prepare_vimvar(VV_KEY, &save_key);
9311 vimvars[VV_KEY].vv_type = VAR_STRING;
9313 ht = &d->dv_hashtab;
9314 hash_lock(ht);
9315 todo = (int)ht->ht_used;
9316 for (hi = ht->ht_array; todo > 0; ++hi)
9318 if (!HASHITEM_EMPTY(hi))
9320 --todo;
9321 di = HI2DI(hi);
9322 if (tv_check_lock(di->di_tv.v_lock, ermsg))
9323 break;
9324 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
9325 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
9326 || did_emsg)
9327 break;
9328 if (!map && rem)
9329 dictitem_remove(d, di);
9330 clear_tv(&vimvars[VV_KEY].vv_tv);
9333 hash_unlock(ht);
9335 restore_vimvar(VV_KEY, &save_key);
9337 else
9339 for (li = l->lv_first; li != NULL; li = nli)
9341 if (tv_check_lock(li->li_tv.v_lock, ermsg))
9342 break;
9343 nli = li->li_next;
9344 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
9345 || did_emsg)
9346 break;
9347 if (!map && rem)
9348 listitem_remove(l, li);
9352 restore_vimvar(VV_VAL, &save_val);
9354 did_emsg |= save_did_emsg;
9357 copy_tv(&argvars[0], rettv);
9360 static int
9361 filter_map_one(tv, expr, map, remp)
9362 typval_T *tv;
9363 char_u *expr;
9364 int map;
9365 int *remp;
9367 typval_T rettv;
9368 char_u *s;
9370 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
9371 s = expr;
9372 if (eval1(&s, &rettv, TRUE) == FAIL)
9373 return FAIL;
9374 if (*s != NUL) /* check for trailing chars after expr */
9376 EMSG2(_(e_invexpr2), s);
9377 return FAIL;
9379 if (map)
9381 /* map(): replace the list item value */
9382 clear_tv(tv);
9383 rettv.v_lock = 0;
9384 *tv = rettv;
9386 else
9388 int error = FALSE;
9390 /* filter(): when expr is zero remove the item */
9391 *remp = (get_tv_number_chk(&rettv, &error) == 0);
9392 clear_tv(&rettv);
9393 /* On type error, nothing has been removed; return FAIL to stop the
9394 * loop. The error message was given by get_tv_number_chk(). */
9395 if (error)
9396 return FAIL;
9398 clear_tv(&vimvars[VV_VAL].vv_tv);
9399 return OK;
9403 * "filter()" function
9405 static void
9406 f_filter(argvars, rettv)
9407 typval_T *argvars;
9408 typval_T *rettv;
9410 filter_map(argvars, rettv, FALSE);
9414 * "finddir({fname}[, {path}[, {count}]])" function
9416 static void
9417 f_finddir(argvars, rettv)
9418 typval_T *argvars;
9419 typval_T *rettv;
9421 findfilendir(argvars, rettv, TRUE);
9425 * "findfile({fname}[, {path}[, {count}]])" function
9427 static void
9428 f_findfile(argvars, rettv)
9429 typval_T *argvars;
9430 typval_T *rettv;
9432 findfilendir(argvars, rettv, FALSE);
9436 * "fnamemodify({fname}, {mods})" function
9438 static void
9439 f_fnamemodify(argvars, rettv)
9440 typval_T *argvars;
9441 typval_T *rettv;
9443 char_u *fname;
9444 char_u *mods;
9445 int usedlen = 0;
9446 int len;
9447 char_u *fbuf = NULL;
9448 char_u buf[NUMBUFLEN];
9450 fname = get_tv_string_chk(&argvars[0]);
9451 mods = get_tv_string_buf_chk(&argvars[1], buf);
9452 if (fname == NULL || mods == NULL)
9453 fname = NULL;
9454 else
9456 len = (int)STRLEN(fname);
9457 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
9460 rettv->v_type = VAR_STRING;
9461 if (fname == NULL)
9462 rettv->vval.v_string = NULL;
9463 else
9464 rettv->vval.v_string = vim_strnsave(fname, len);
9465 vim_free(fbuf);
9468 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
9471 * "foldclosed()" function
9473 static void
9474 foldclosed_both(argvars, rettv, end)
9475 typval_T *argvars;
9476 typval_T *rettv;
9477 int end;
9479 #ifdef FEAT_FOLDING
9480 linenr_T lnum;
9481 linenr_T first, last;
9483 lnum = get_tv_lnum(argvars);
9484 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9486 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
9488 if (end)
9489 rettv->vval.v_number = (varnumber_T)last;
9490 else
9491 rettv->vval.v_number = (varnumber_T)first;
9492 return;
9495 #endif
9496 rettv->vval.v_number = -1;
9500 * "foldclosed()" function
9502 static void
9503 f_foldclosed(argvars, rettv)
9504 typval_T *argvars;
9505 typval_T *rettv;
9507 foldclosed_both(argvars, rettv, FALSE);
9511 * "foldclosedend()" function
9513 static void
9514 f_foldclosedend(argvars, rettv)
9515 typval_T *argvars;
9516 typval_T *rettv;
9518 foldclosed_both(argvars, rettv, TRUE);
9522 * "foldlevel()" function
9524 static void
9525 f_foldlevel(argvars, rettv)
9526 typval_T *argvars;
9527 typval_T *rettv;
9529 #ifdef FEAT_FOLDING
9530 linenr_T lnum;
9532 lnum = get_tv_lnum(argvars);
9533 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9534 rettv->vval.v_number = foldLevel(lnum);
9535 else
9536 #endif
9537 rettv->vval.v_number = 0;
9541 * "foldtext()" function
9543 /*ARGSUSED*/
9544 static void
9545 f_foldtext(argvars, rettv)
9546 typval_T *argvars;
9547 typval_T *rettv;
9549 #ifdef FEAT_FOLDING
9550 linenr_T lnum;
9551 char_u *s;
9552 char_u *r;
9553 int len;
9554 char *txt;
9555 #endif
9557 rettv->v_type = VAR_STRING;
9558 rettv->vval.v_string = NULL;
9559 #ifdef FEAT_FOLDING
9560 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
9561 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
9562 <= curbuf->b_ml.ml_line_count
9563 && vimvars[VV_FOLDDASHES].vv_str != NULL)
9565 /* Find first non-empty line in the fold. */
9566 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
9567 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
9569 if (!linewhite(lnum))
9570 break;
9571 ++lnum;
9574 /* Find interesting text in this line. */
9575 s = skipwhite(ml_get(lnum));
9576 /* skip C comment-start */
9577 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
9579 s = skipwhite(s + 2);
9580 if (*skipwhite(s) == NUL
9581 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
9583 s = skipwhite(ml_get(lnum + 1));
9584 if (*s == '*')
9585 s = skipwhite(s + 1);
9588 txt = _("+-%s%3ld lines: ");
9589 r = alloc((unsigned)(STRLEN(txt)
9590 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
9591 + 20 /* for %3ld */
9592 + STRLEN(s))); /* concatenated */
9593 if (r != NULL)
9595 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
9596 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
9597 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
9598 len = (int)STRLEN(r);
9599 STRCAT(r, s);
9600 /* remove 'foldmarker' and 'commentstring' */
9601 foldtext_cleanup(r + len);
9602 rettv->vval.v_string = r;
9605 #endif
9609 * "foldtextresult(lnum)" function
9611 /*ARGSUSED*/
9612 static void
9613 f_foldtextresult(argvars, rettv)
9614 typval_T *argvars;
9615 typval_T *rettv;
9617 #ifdef FEAT_FOLDING
9618 linenr_T lnum;
9619 char_u *text;
9620 char_u buf[51];
9621 foldinfo_T foldinfo;
9622 int fold_count;
9623 #endif
9625 rettv->v_type = VAR_STRING;
9626 rettv->vval.v_string = NULL;
9627 #ifdef FEAT_FOLDING
9628 lnum = get_tv_lnum(argvars);
9629 /* treat illegal types and illegal string values for {lnum} the same */
9630 if (lnum < 0)
9631 lnum = 0;
9632 fold_count = foldedCount(curwin, lnum, &foldinfo);
9633 if (fold_count > 0)
9635 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
9636 &foldinfo, buf);
9637 if (text == buf)
9638 text = vim_strsave(text);
9639 rettv->vval.v_string = text;
9641 #endif
9645 * "foreground()" function
9647 /*ARGSUSED*/
9648 static void
9649 f_foreground(argvars, rettv)
9650 typval_T *argvars;
9651 typval_T *rettv;
9653 rettv->vval.v_number = 0;
9654 #ifdef FEAT_GUI
9655 if (gui.in_use)
9656 gui_mch_set_foreground();
9657 #else
9658 # ifdef WIN32
9659 win32_set_foreground();
9660 # endif
9661 #endif
9665 * "function()" function
9667 /*ARGSUSED*/
9668 static void
9669 f_function(argvars, rettv)
9670 typval_T *argvars;
9671 typval_T *rettv;
9673 char_u *s;
9675 rettv->vval.v_number = 0;
9676 s = get_tv_string(&argvars[0]);
9677 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
9678 EMSG2(_(e_invarg2), s);
9679 else if (!function_exists(s))
9680 EMSG2(_("E700: Unknown function: %s"), s);
9681 else
9683 rettv->vval.v_string = vim_strsave(s);
9684 rettv->v_type = VAR_FUNC;
9689 * "garbagecollect()" function
9691 /*ARGSUSED*/
9692 static void
9693 f_garbagecollect(argvars, rettv)
9694 typval_T *argvars;
9695 typval_T *rettv;
9697 /* This is postponed until we are back at the toplevel, because we may be
9698 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
9699 want_garbage_collect = TRUE;
9703 * "get()" function
9705 static void
9706 f_get(argvars, rettv)
9707 typval_T *argvars;
9708 typval_T *rettv;
9710 listitem_T *li;
9711 list_T *l;
9712 dictitem_T *di;
9713 dict_T *d;
9714 typval_T *tv = NULL;
9716 if (argvars[0].v_type == VAR_LIST)
9718 if ((l = argvars[0].vval.v_list) != NULL)
9720 int error = FALSE;
9722 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
9723 if (!error && li != NULL)
9724 tv = &li->li_tv;
9727 else if (argvars[0].v_type == VAR_DICT)
9729 if ((d = argvars[0].vval.v_dict) != NULL)
9731 di = dict_find(d, get_tv_string(&argvars[1]), -1);
9732 if (di != NULL)
9733 tv = &di->di_tv;
9736 else
9737 EMSG2(_(e_listdictarg), "get()");
9739 if (tv == NULL)
9741 if (argvars[2].v_type == VAR_UNKNOWN)
9742 rettv->vval.v_number = 0;
9743 else
9744 copy_tv(&argvars[2], rettv);
9746 else
9747 copy_tv(tv, rettv);
9750 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
9753 * Get line or list of lines from buffer "buf" into "rettv".
9754 * Return a range (from start to end) of lines in rettv from the specified
9755 * buffer.
9756 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
9758 static void
9759 get_buffer_lines(buf, start, end, retlist, rettv)
9760 buf_T *buf;
9761 linenr_T start;
9762 linenr_T end;
9763 int retlist;
9764 typval_T *rettv;
9766 char_u *p;
9768 if (retlist)
9770 if (rettv_list_alloc(rettv) == FAIL)
9771 return;
9773 else
9774 rettv->vval.v_number = 0;
9776 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
9777 return;
9779 if (!retlist)
9781 if (start >= 1 && start <= buf->b_ml.ml_line_count)
9782 p = ml_get_buf(buf, start, FALSE);
9783 else
9784 p = (char_u *)"";
9786 rettv->v_type = VAR_STRING;
9787 rettv->vval.v_string = vim_strsave(p);
9789 else
9791 if (end < start)
9792 return;
9794 if (start < 1)
9795 start = 1;
9796 if (end > buf->b_ml.ml_line_count)
9797 end = buf->b_ml.ml_line_count;
9798 while (start <= end)
9799 if (list_append_string(rettv->vval.v_list,
9800 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
9801 break;
9806 * "getbufline()" function
9808 static void
9809 f_getbufline(argvars, rettv)
9810 typval_T *argvars;
9811 typval_T *rettv;
9813 linenr_T lnum;
9814 linenr_T end;
9815 buf_T *buf;
9817 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
9818 ++emsg_off;
9819 buf = get_buf_tv(&argvars[0]);
9820 --emsg_off;
9822 lnum = get_tv_lnum_buf(&argvars[1], buf);
9823 if (argvars[2].v_type == VAR_UNKNOWN)
9824 end = lnum;
9825 else
9826 end = get_tv_lnum_buf(&argvars[2], buf);
9828 get_buffer_lines(buf, lnum, end, TRUE, rettv);
9832 * "getbufvar()" function
9834 static void
9835 f_getbufvar(argvars, rettv)
9836 typval_T *argvars;
9837 typval_T *rettv;
9839 buf_T *buf;
9840 buf_T *save_curbuf;
9841 char_u *varname;
9842 dictitem_T *v;
9844 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
9845 varname = get_tv_string_chk(&argvars[1]);
9846 ++emsg_off;
9847 buf = get_buf_tv(&argvars[0]);
9849 rettv->v_type = VAR_STRING;
9850 rettv->vval.v_string = NULL;
9852 if (buf != NULL && varname != NULL)
9854 if (*varname == '&') /* buffer-local-option */
9856 /* set curbuf to be our buf, temporarily */
9857 save_curbuf = curbuf;
9858 curbuf = buf;
9860 get_option_tv(&varname, rettv, TRUE);
9862 /* restore previous notion of curbuf */
9863 curbuf = save_curbuf;
9865 else
9867 if (*varname == NUL)
9868 /* let getbufvar({nr}, "") return the "b:" dictionary. The
9869 * scope prefix before the NUL byte is required by
9870 * find_var_in_ht(). */
9871 varname = (char_u *)"b:" + 2;
9872 /* look up the variable */
9873 v = find_var_in_ht(&buf->b_vars.dv_hashtab, varname, FALSE);
9874 if (v != NULL)
9875 copy_tv(&v->di_tv, rettv);
9879 --emsg_off;
9883 * "getchar()" function
9885 static void
9886 f_getchar(argvars, rettv)
9887 typval_T *argvars;
9888 typval_T *rettv;
9890 varnumber_T n;
9891 int error = FALSE;
9893 /* Position the cursor. Needed after a message that ends in a space. */
9894 windgoto(msg_row, msg_col);
9896 ++no_mapping;
9897 ++allow_keys;
9898 if (argvars[0].v_type == VAR_UNKNOWN)
9899 /* getchar(): blocking wait. */
9900 n = safe_vgetc();
9901 else if (get_tv_number_chk(&argvars[0], &error) == 1)
9902 /* getchar(1): only check if char avail */
9903 n = vpeekc();
9904 else if (error || vpeekc() == NUL)
9905 /* illegal argument or getchar(0) and no char avail: return zero */
9906 n = 0;
9907 else
9908 /* getchar(0) and char avail: return char */
9909 n = safe_vgetc();
9910 --no_mapping;
9911 --allow_keys;
9913 vimvars[VV_MOUSE_WIN].vv_nr = 0;
9914 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
9915 vimvars[VV_MOUSE_COL].vv_nr = 0;
9917 rettv->vval.v_number = n;
9918 if (IS_SPECIAL(n) || mod_mask != 0)
9920 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
9921 int i = 0;
9923 /* Turn a special key into three bytes, plus modifier. */
9924 if (mod_mask != 0)
9926 temp[i++] = K_SPECIAL;
9927 temp[i++] = KS_MODIFIER;
9928 temp[i++] = mod_mask;
9930 if (IS_SPECIAL(n))
9932 temp[i++] = K_SPECIAL;
9933 temp[i++] = K_SECOND(n);
9934 temp[i++] = K_THIRD(n);
9936 #ifdef FEAT_MBYTE
9937 else if (has_mbyte)
9938 i += (*mb_char2bytes)(n, temp + i);
9939 #endif
9940 else
9941 temp[i++] = n;
9942 temp[i++] = NUL;
9943 rettv->v_type = VAR_STRING;
9944 rettv->vval.v_string = vim_strsave(temp);
9946 #ifdef FEAT_MOUSE
9947 if (n == K_LEFTMOUSE
9948 || n == K_LEFTMOUSE_NM
9949 || n == K_LEFTDRAG
9950 || n == K_LEFTRELEASE
9951 || n == K_LEFTRELEASE_NM
9952 || n == K_MIDDLEMOUSE
9953 || n == K_MIDDLEDRAG
9954 || n == K_MIDDLERELEASE
9955 || n == K_RIGHTMOUSE
9956 || n == K_RIGHTDRAG
9957 || n == K_RIGHTRELEASE
9958 || n == K_X1MOUSE
9959 || n == K_X1DRAG
9960 || n == K_X1RELEASE
9961 || n == K_X2MOUSE
9962 || n == K_X2DRAG
9963 || n == K_X2RELEASE
9964 || n == K_MOUSEDOWN
9965 || n == K_MOUSEUP)
9967 int row = mouse_row;
9968 int col = mouse_col;
9969 win_T *win;
9970 linenr_T lnum;
9971 # ifdef FEAT_WINDOWS
9972 win_T *wp;
9973 # endif
9974 int n = 1;
9976 if (row >= 0 && col >= 0)
9978 /* Find the window at the mouse coordinates and compute the
9979 * text position. */
9980 win = mouse_find_win(&row, &col);
9981 (void)mouse_comp_pos(win, &row, &col, &lnum);
9982 # ifdef FEAT_WINDOWS
9983 for (wp = firstwin; wp != win; wp = wp->w_next)
9984 ++n;
9985 # endif
9986 vimvars[VV_MOUSE_WIN].vv_nr = n;
9987 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
9988 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
9991 #endif
9996 * "getcharmod()" function
9998 /*ARGSUSED*/
9999 static void
10000 f_getcharmod(argvars, rettv)
10001 typval_T *argvars;
10002 typval_T *rettv;
10004 rettv->vval.v_number = mod_mask;
10008 * "getcmdline()" function
10010 /*ARGSUSED*/
10011 static void
10012 f_getcmdline(argvars, rettv)
10013 typval_T *argvars;
10014 typval_T *rettv;
10016 rettv->v_type = VAR_STRING;
10017 rettv->vval.v_string = get_cmdline_str();
10021 * "getcmdpos()" function
10023 /*ARGSUSED*/
10024 static void
10025 f_getcmdpos(argvars, rettv)
10026 typval_T *argvars;
10027 typval_T *rettv;
10029 rettv->vval.v_number = get_cmdline_pos() + 1;
10033 * "getcmdtype()" function
10035 /*ARGSUSED*/
10036 static void
10037 f_getcmdtype(argvars, rettv)
10038 typval_T *argvars;
10039 typval_T *rettv;
10041 rettv->v_type = VAR_STRING;
10042 rettv->vval.v_string = alloc(2);
10043 if (rettv->vval.v_string != NULL)
10045 rettv->vval.v_string[0] = get_cmdline_type();
10046 rettv->vval.v_string[1] = NUL;
10051 * "getcwd()" function
10053 /*ARGSUSED*/
10054 static void
10055 f_getcwd(argvars, rettv)
10056 typval_T *argvars;
10057 typval_T *rettv;
10059 char_u cwd[MAXPATHL];
10061 rettv->v_type = VAR_STRING;
10062 if (mch_dirname(cwd, MAXPATHL) == FAIL)
10063 rettv->vval.v_string = NULL;
10064 else
10066 rettv->vval.v_string = vim_strsave(cwd);
10067 #ifdef BACKSLASH_IN_FILENAME
10068 if (rettv->vval.v_string != NULL)
10069 slash_adjust(rettv->vval.v_string);
10070 #endif
10075 * "getfontname()" function
10077 /*ARGSUSED*/
10078 static void
10079 f_getfontname(argvars, rettv)
10080 typval_T *argvars;
10081 typval_T *rettv;
10083 rettv->v_type = VAR_STRING;
10084 rettv->vval.v_string = NULL;
10085 #ifdef FEAT_GUI
10086 if (gui.in_use)
10088 GuiFont font;
10089 char_u *name = NULL;
10091 if (argvars[0].v_type == VAR_UNKNOWN)
10093 /* Get the "Normal" font. Either the name saved by
10094 * hl_set_font_name() or from the font ID. */
10095 font = gui.norm_font;
10096 name = hl_get_font_name();
10098 else
10100 name = get_tv_string(&argvars[0]);
10101 if (STRCMP(name, "*") == 0) /* don't use font dialog */
10102 return;
10103 font = gui_mch_get_font(name, FALSE);
10104 if (font == NOFONT)
10105 return; /* Invalid font name, return empty string. */
10107 rettv->vval.v_string = gui_mch_get_fontname(font, name);
10108 if (argvars[0].v_type != VAR_UNKNOWN)
10109 gui_mch_free_font(font);
10111 #endif
10115 * "getfperm({fname})" function
10117 static void
10118 f_getfperm(argvars, rettv)
10119 typval_T *argvars;
10120 typval_T *rettv;
10122 char_u *fname;
10123 struct stat st;
10124 char_u *perm = NULL;
10125 char_u flags[] = "rwx";
10126 int i;
10128 fname = get_tv_string(&argvars[0]);
10130 rettv->v_type = VAR_STRING;
10131 if (mch_stat((char *)fname, &st) >= 0)
10133 perm = vim_strsave((char_u *)"---------");
10134 if (perm != NULL)
10136 for (i = 0; i < 9; i++)
10138 if (st.st_mode & (1 << (8 - i)))
10139 perm[i] = flags[i % 3];
10143 rettv->vval.v_string = perm;
10147 * "getfsize({fname})" function
10149 static void
10150 f_getfsize(argvars, rettv)
10151 typval_T *argvars;
10152 typval_T *rettv;
10154 char_u *fname;
10155 struct stat st;
10157 fname = get_tv_string(&argvars[0]);
10159 rettv->v_type = VAR_NUMBER;
10161 if (mch_stat((char *)fname, &st) >= 0)
10163 if (mch_isdir(fname))
10164 rettv->vval.v_number = 0;
10165 else
10167 rettv->vval.v_number = (varnumber_T)st.st_size;
10169 /* non-perfect check for overflow */
10170 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
10171 rettv->vval.v_number = -2;
10174 else
10175 rettv->vval.v_number = -1;
10179 * "getftime({fname})" function
10181 static void
10182 f_getftime(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 if (mch_stat((char *)fname, &st) >= 0)
10192 rettv->vval.v_number = (varnumber_T)st.st_mtime;
10193 else
10194 rettv->vval.v_number = -1;
10198 * "getftype({fname})" function
10200 static void
10201 f_getftype(argvars, rettv)
10202 typval_T *argvars;
10203 typval_T *rettv;
10205 char_u *fname;
10206 struct stat st;
10207 char_u *type = NULL;
10208 char *t;
10210 fname = get_tv_string(&argvars[0]);
10212 rettv->v_type = VAR_STRING;
10213 if (mch_lstat((char *)fname, &st) >= 0)
10215 #ifdef S_ISREG
10216 if (S_ISREG(st.st_mode))
10217 t = "file";
10218 else if (S_ISDIR(st.st_mode))
10219 t = "dir";
10220 # ifdef S_ISLNK
10221 else if (S_ISLNK(st.st_mode))
10222 t = "link";
10223 # endif
10224 # ifdef S_ISBLK
10225 else if (S_ISBLK(st.st_mode))
10226 t = "bdev";
10227 # endif
10228 # ifdef S_ISCHR
10229 else if (S_ISCHR(st.st_mode))
10230 t = "cdev";
10231 # endif
10232 # ifdef S_ISFIFO
10233 else if (S_ISFIFO(st.st_mode))
10234 t = "fifo";
10235 # endif
10236 # ifdef S_ISSOCK
10237 else if (S_ISSOCK(st.st_mode))
10238 t = "fifo";
10239 # endif
10240 else
10241 t = "other";
10242 #else
10243 # ifdef S_IFMT
10244 switch (st.st_mode & S_IFMT)
10246 case S_IFREG: t = "file"; break;
10247 case S_IFDIR: t = "dir"; break;
10248 # ifdef S_IFLNK
10249 case S_IFLNK: t = "link"; break;
10250 # endif
10251 # ifdef S_IFBLK
10252 case S_IFBLK: t = "bdev"; break;
10253 # endif
10254 # ifdef S_IFCHR
10255 case S_IFCHR: t = "cdev"; break;
10256 # endif
10257 # ifdef S_IFIFO
10258 case S_IFIFO: t = "fifo"; break;
10259 # endif
10260 # ifdef S_IFSOCK
10261 case S_IFSOCK: t = "socket"; break;
10262 # endif
10263 default: t = "other";
10265 # else
10266 if (mch_isdir(fname))
10267 t = "dir";
10268 else
10269 t = "file";
10270 # endif
10271 #endif
10272 type = vim_strsave((char_u *)t);
10274 rettv->vval.v_string = type;
10278 * "getline(lnum, [end])" function
10280 static void
10281 f_getline(argvars, rettv)
10282 typval_T *argvars;
10283 typval_T *rettv;
10285 linenr_T lnum;
10286 linenr_T end;
10287 int retlist;
10289 lnum = get_tv_lnum(argvars);
10290 if (argvars[1].v_type == VAR_UNKNOWN)
10292 end = 0;
10293 retlist = FALSE;
10295 else
10297 end = get_tv_lnum(&argvars[1]);
10298 retlist = TRUE;
10301 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
10305 * "getmatches()" function
10307 /*ARGSUSED*/
10308 static void
10309 f_getmatches(argvars, rettv)
10310 typval_T *argvars;
10311 typval_T *rettv;
10313 #ifdef FEAT_SEARCH_EXTRA
10314 dict_T *dict;
10315 matchitem_T *cur = curwin->w_match_head;
10317 rettv->vval.v_number = 0;
10319 if (rettv_list_alloc(rettv) == OK)
10321 while (cur != NULL)
10323 dict = dict_alloc();
10324 if (dict == NULL)
10325 return;
10326 ++dict->dv_refcount;
10327 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
10328 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
10329 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
10330 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
10331 list_append_dict(rettv->vval.v_list, dict);
10332 cur = cur->next;
10335 #endif
10339 * "getpos(string)" function
10341 static void
10342 f_getpos(argvars, rettv)
10343 typval_T *argvars;
10344 typval_T *rettv;
10346 pos_T *fp;
10347 list_T *l;
10348 int fnum = -1;
10350 if (rettv_list_alloc(rettv) == OK)
10352 l = rettv->vval.v_list;
10353 fp = var2fpos(&argvars[0], TRUE, &fnum);
10354 if (fnum != -1)
10355 list_append_number(l, (varnumber_T)fnum);
10356 else
10357 list_append_number(l, (varnumber_T)0);
10358 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
10359 : (varnumber_T)0);
10360 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->col + 1
10361 : (varnumber_T)0);
10362 list_append_number(l,
10363 #ifdef FEAT_VIRTUALEDIT
10364 (fp != NULL) ? (varnumber_T)fp->coladd :
10365 #endif
10366 (varnumber_T)0);
10368 else
10369 rettv->vval.v_number = FALSE;
10373 * "getqflist()" and "getloclist()" functions
10375 /*ARGSUSED*/
10376 static void
10377 f_getqflist(argvars, rettv)
10378 typval_T *argvars;
10379 typval_T *rettv;
10381 #ifdef FEAT_QUICKFIX
10382 win_T *wp;
10383 #endif
10385 rettv->vval.v_number = 0;
10386 #ifdef FEAT_QUICKFIX
10387 if (rettv_list_alloc(rettv) == OK)
10389 wp = NULL;
10390 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
10392 wp = find_win_by_nr(&argvars[0], NULL);
10393 if (wp == NULL)
10394 return;
10397 (void)get_errorlist(wp, rettv->vval.v_list);
10399 #endif
10403 * "getreg()" function
10405 static void
10406 f_getreg(argvars, rettv)
10407 typval_T *argvars;
10408 typval_T *rettv;
10410 char_u *strregname;
10411 int regname;
10412 int arg2 = FALSE;
10413 int error = FALSE;
10415 if (argvars[0].v_type != VAR_UNKNOWN)
10417 strregname = get_tv_string_chk(&argvars[0]);
10418 error = strregname == NULL;
10419 if (argvars[1].v_type != VAR_UNKNOWN)
10420 arg2 = get_tv_number_chk(&argvars[1], &error);
10422 else
10423 strregname = vimvars[VV_REG].vv_str;
10424 regname = (strregname == NULL ? '"' : *strregname);
10425 if (regname == 0)
10426 regname = '"';
10428 rettv->v_type = VAR_STRING;
10429 rettv->vval.v_string = error ? NULL :
10430 get_reg_contents(regname, TRUE, arg2);
10434 * "getregtype()" function
10436 static void
10437 f_getregtype(argvars, rettv)
10438 typval_T *argvars;
10439 typval_T *rettv;
10441 char_u *strregname;
10442 int regname;
10443 char_u buf[NUMBUFLEN + 2];
10444 long reglen = 0;
10446 if (argvars[0].v_type != VAR_UNKNOWN)
10448 strregname = get_tv_string_chk(&argvars[0]);
10449 if (strregname == NULL) /* type error; errmsg already given */
10451 rettv->v_type = VAR_STRING;
10452 rettv->vval.v_string = NULL;
10453 return;
10456 else
10457 /* Default to v:register */
10458 strregname = vimvars[VV_REG].vv_str;
10460 regname = (strregname == NULL ? '"' : *strregname);
10461 if (regname == 0)
10462 regname = '"';
10464 buf[0] = NUL;
10465 buf[1] = NUL;
10466 switch (get_reg_type(regname, &reglen))
10468 case MLINE: buf[0] = 'V'; break;
10469 case MCHAR: buf[0] = 'v'; break;
10470 #ifdef FEAT_VISUAL
10471 case MBLOCK:
10472 buf[0] = Ctrl_V;
10473 sprintf((char *)buf + 1, "%ld", reglen + 1);
10474 break;
10475 #endif
10477 rettv->v_type = VAR_STRING;
10478 rettv->vval.v_string = vim_strsave(buf);
10482 * "gettabwinvar()" function
10484 static void
10485 f_gettabwinvar(argvars, rettv)
10486 typval_T *argvars;
10487 typval_T *rettv;
10489 getwinvar(argvars, rettv, 1);
10493 * "getwinposx()" function
10495 /*ARGSUSED*/
10496 static void
10497 f_getwinposx(argvars, rettv)
10498 typval_T *argvars;
10499 typval_T *rettv;
10501 rettv->vval.v_number = -1;
10502 #ifdef FEAT_GUI
10503 if (gui.in_use)
10505 int x, y;
10507 if (gui_mch_get_winpos(&x, &y) == OK)
10508 rettv->vval.v_number = x;
10510 #endif
10514 * "getwinposy()" function
10516 /*ARGSUSED*/
10517 static void
10518 f_getwinposy(argvars, rettv)
10519 typval_T *argvars;
10520 typval_T *rettv;
10522 rettv->vval.v_number = -1;
10523 #ifdef FEAT_GUI
10524 if (gui.in_use)
10526 int x, y;
10528 if (gui_mch_get_winpos(&x, &y) == OK)
10529 rettv->vval.v_number = y;
10531 #endif
10535 * Find window specifed by "vp" in tabpage "tp".
10537 static win_T *
10538 find_win_by_nr(vp, tp)
10539 typval_T *vp;
10540 tabpage_T *tp; /* NULL for current tab page */
10542 #ifdef FEAT_WINDOWS
10543 win_T *wp;
10544 #endif
10545 int nr;
10547 nr = get_tv_number_chk(vp, NULL);
10549 #ifdef FEAT_WINDOWS
10550 if (nr < 0)
10551 return NULL;
10552 if (nr == 0)
10553 return curwin;
10555 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
10556 wp != NULL; wp = wp->w_next)
10557 if (--nr <= 0)
10558 break;
10559 return wp;
10560 #else
10561 if (nr == 0 || nr == 1)
10562 return curwin;
10563 return NULL;
10564 #endif
10568 * "getwinvar()" function
10570 static void
10571 f_getwinvar(argvars, rettv)
10572 typval_T *argvars;
10573 typval_T *rettv;
10575 getwinvar(argvars, rettv, 0);
10579 * getwinvar() and gettabwinvar()
10581 static void
10582 getwinvar(argvars, rettv, off)
10583 typval_T *argvars;
10584 typval_T *rettv;
10585 int off; /* 1 for gettabwinvar() */
10587 win_T *win, *oldcurwin;
10588 char_u *varname;
10589 dictitem_T *v;
10590 tabpage_T *tp;
10592 #ifdef FEAT_WINDOWS
10593 if (off == 1)
10594 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
10595 else
10596 tp = curtab;
10597 #endif
10598 win = find_win_by_nr(&argvars[off], tp);
10599 varname = get_tv_string_chk(&argvars[off + 1]);
10600 ++emsg_off;
10602 rettv->v_type = VAR_STRING;
10603 rettv->vval.v_string = NULL;
10605 if (win != NULL && varname != NULL)
10607 /* Set curwin to be our win, temporarily. Also set curbuf, so
10608 * that we can get buffer-local options. */
10609 oldcurwin = curwin;
10610 curwin = win;
10611 curbuf = win->w_buffer;
10613 if (*varname == '&') /* window-local-option */
10614 get_option_tv(&varname, rettv, 1);
10615 else
10617 if (*varname == NUL)
10618 /* let getwinvar({nr}, "") return the "w:" dictionary. The
10619 * scope prefix before the NUL byte is required by
10620 * find_var_in_ht(). */
10621 varname = (char_u *)"w:" + 2;
10622 /* look up the variable */
10623 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
10624 if (v != NULL)
10625 copy_tv(&v->di_tv, rettv);
10628 /* restore previous notion of curwin */
10629 curwin = oldcurwin;
10630 curbuf = curwin->w_buffer;
10633 --emsg_off;
10637 * "glob()" function
10639 static void
10640 f_glob(argvars, rettv)
10641 typval_T *argvars;
10642 typval_T *rettv;
10644 expand_T xpc;
10646 ExpandInit(&xpc);
10647 xpc.xp_context = EXPAND_FILES;
10648 rettv->v_type = VAR_STRING;
10649 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
10650 NULL, WILD_USE_NL|WILD_SILENT, WILD_ALL);
10654 * "globpath()" function
10656 static void
10657 f_globpath(argvars, rettv)
10658 typval_T *argvars;
10659 typval_T *rettv;
10661 char_u buf1[NUMBUFLEN];
10662 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
10664 rettv->v_type = VAR_STRING;
10665 if (file == NULL)
10666 rettv->vval.v_string = NULL;
10667 else
10668 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file);
10672 * "has()" function
10674 static void
10675 f_has(argvars, rettv)
10676 typval_T *argvars;
10677 typval_T *rettv;
10679 int i;
10680 char_u *name;
10681 int n = FALSE;
10682 static char *(has_list[]) =
10684 #ifdef AMIGA
10685 "amiga",
10686 # ifdef FEAT_ARP
10687 "arp",
10688 # endif
10689 #endif
10690 #ifdef __BEOS__
10691 "beos",
10692 #endif
10693 #ifdef MSDOS
10694 # ifdef DJGPP
10695 "dos32",
10696 # else
10697 "dos16",
10698 # endif
10699 #endif
10700 #ifdef MACOS
10701 "mac",
10702 #endif
10703 #if defined(MACOS_X_UNIX)
10704 "macunix",
10705 #endif
10706 #ifdef OS2
10707 "os2",
10708 #endif
10709 #ifdef __QNX__
10710 "qnx",
10711 #endif
10712 #ifdef RISCOS
10713 "riscos",
10714 #endif
10715 #ifdef UNIX
10716 "unix",
10717 #endif
10718 #ifdef VMS
10719 "vms",
10720 #endif
10721 #ifdef WIN16
10722 "win16",
10723 #endif
10724 #ifdef WIN32
10725 "win32",
10726 #endif
10727 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
10728 "win32unix",
10729 #endif
10730 #ifdef WIN64
10731 "win64",
10732 #endif
10733 #ifdef EBCDIC
10734 "ebcdic",
10735 #endif
10736 #ifndef CASE_INSENSITIVE_FILENAME
10737 "fname_case",
10738 #endif
10739 #ifdef FEAT_ARABIC
10740 "arabic",
10741 #endif
10742 #ifdef FEAT_AUTOCMD
10743 "autocmd",
10744 #endif
10745 #ifdef FEAT_BEVAL
10746 "balloon_eval",
10747 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
10748 "balloon_multiline",
10749 # endif
10750 #endif
10751 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
10752 "builtin_terms",
10753 # ifdef ALL_BUILTIN_TCAPS
10754 "all_builtin_terms",
10755 # endif
10756 #endif
10757 #ifdef FEAT_BYTEOFF
10758 "byte_offset",
10759 #endif
10760 #ifdef FEAT_CINDENT
10761 "cindent",
10762 #endif
10763 #ifdef FEAT_CLIENTSERVER
10764 "clientserver",
10765 #endif
10766 #ifdef FEAT_CLIPBOARD
10767 "clipboard",
10768 #endif
10769 #ifdef FEAT_CMDL_COMPL
10770 "cmdline_compl",
10771 #endif
10772 #ifdef FEAT_CMDHIST
10773 "cmdline_hist",
10774 #endif
10775 #ifdef FEAT_COMMENTS
10776 "comments",
10777 #endif
10778 #ifdef FEAT_CRYPT
10779 "cryptv",
10780 #endif
10781 #ifdef FEAT_CSCOPE
10782 "cscope",
10783 #endif
10784 #ifdef CURSOR_SHAPE
10785 "cursorshape",
10786 #endif
10787 #ifdef DEBUG
10788 "debug",
10789 #endif
10790 #ifdef FEAT_CON_DIALOG
10791 "dialog_con",
10792 #endif
10793 #ifdef FEAT_GUI_DIALOG
10794 "dialog_gui",
10795 #endif
10796 #ifdef FEAT_DIFF
10797 "diff",
10798 #endif
10799 #ifdef FEAT_DIGRAPHS
10800 "digraphs",
10801 #endif
10802 #ifdef FEAT_DND
10803 "dnd",
10804 #endif
10805 #ifdef FEAT_EMACS_TAGS
10806 "emacs_tags",
10807 #endif
10808 "eval", /* always present, of course! */
10809 #ifdef FEAT_EX_EXTRA
10810 "ex_extra",
10811 #endif
10812 #ifdef FEAT_SEARCH_EXTRA
10813 "extra_search",
10814 #endif
10815 #ifdef FEAT_FKMAP
10816 "farsi",
10817 #endif
10818 #ifdef FEAT_SEARCHPATH
10819 "file_in_path",
10820 #endif
10821 #if defined(UNIX) && !defined(USE_SYSTEM)
10822 "filterpipe",
10823 #endif
10824 #ifdef FEAT_FIND_ID
10825 "find_in_path",
10826 #endif
10827 #ifdef FEAT_FOLDING
10828 "folding",
10829 #endif
10830 #ifdef FEAT_FOOTER
10831 "footer",
10832 #endif
10833 #if !defined(USE_SYSTEM) && defined(UNIX)
10834 "fork",
10835 #endif
10836 #ifdef FEAT_GETTEXT
10837 "gettext",
10838 #endif
10839 #ifdef FEAT_GUI
10840 "gui",
10841 #endif
10842 #ifdef FEAT_GUI_ATHENA
10843 # ifdef FEAT_GUI_NEXTAW
10844 "gui_neXtaw",
10845 # else
10846 "gui_athena",
10847 # endif
10848 #endif
10849 #ifdef FEAT_GUI_GTK
10850 "gui_gtk",
10851 # ifdef HAVE_GTK2
10852 "gui_gtk2",
10853 # endif
10854 #endif
10855 #ifdef FEAT_GUI_MAC
10856 "gui_mac",
10857 #endif
10858 #ifdef FEAT_GUI_MOTIF
10859 "gui_motif",
10860 #endif
10861 #ifdef FEAT_GUI_PHOTON
10862 "gui_photon",
10863 #endif
10864 #ifdef FEAT_GUI_W16
10865 "gui_win16",
10866 #endif
10867 #ifdef FEAT_GUI_W32
10868 "gui_win32",
10869 #endif
10870 #ifdef FEAT_HANGULIN
10871 "hangul_input",
10872 #endif
10873 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
10874 "iconv",
10875 #endif
10876 #ifdef FEAT_INS_EXPAND
10877 "insert_expand",
10878 #endif
10879 #ifdef FEAT_JUMPLIST
10880 "jumplist",
10881 #endif
10882 #ifdef FEAT_KEYMAP
10883 "keymap",
10884 #endif
10885 #ifdef FEAT_LANGMAP
10886 "langmap",
10887 #endif
10888 #ifdef FEAT_LIBCALL
10889 "libcall",
10890 #endif
10891 #ifdef FEAT_LINEBREAK
10892 "linebreak",
10893 #endif
10894 #ifdef FEAT_LISP
10895 "lispindent",
10896 #endif
10897 #ifdef FEAT_LISTCMDS
10898 "listcmds",
10899 #endif
10900 #ifdef FEAT_LOCALMAP
10901 "localmap",
10902 #endif
10903 #ifdef FEAT_MENU
10904 "menu",
10905 #endif
10906 #ifdef FEAT_SESSION
10907 "mksession",
10908 #endif
10909 #ifdef FEAT_MODIFY_FNAME
10910 "modify_fname",
10911 #endif
10912 #ifdef FEAT_MOUSE
10913 "mouse",
10914 #endif
10915 #ifdef FEAT_MOUSESHAPE
10916 "mouseshape",
10917 #endif
10918 #if defined(UNIX) || defined(VMS)
10919 # ifdef FEAT_MOUSE_DEC
10920 "mouse_dec",
10921 # endif
10922 # ifdef FEAT_MOUSE_GPM
10923 "mouse_gpm",
10924 # endif
10925 # ifdef FEAT_MOUSE_JSB
10926 "mouse_jsbterm",
10927 # endif
10928 # ifdef FEAT_MOUSE_NET
10929 "mouse_netterm",
10930 # endif
10931 # ifdef FEAT_MOUSE_PTERM
10932 "mouse_pterm",
10933 # endif
10934 # ifdef FEAT_MOUSE_XTERM
10935 "mouse_xterm",
10936 # endif
10937 #endif
10938 #ifdef FEAT_MBYTE
10939 "multi_byte",
10940 #endif
10941 #ifdef FEAT_MBYTE_IME
10942 "multi_byte_ime",
10943 #endif
10944 #ifdef FEAT_MULTI_LANG
10945 "multi_lang",
10946 #endif
10947 #ifdef FEAT_MZSCHEME
10948 #ifndef DYNAMIC_MZSCHEME
10949 "mzscheme",
10950 #endif
10951 #endif
10952 #ifdef FEAT_OLE
10953 "ole",
10954 #endif
10955 #ifdef FEAT_OSFILETYPE
10956 "osfiletype",
10957 #endif
10958 #ifdef FEAT_PATH_EXTRA
10959 "path_extra",
10960 #endif
10961 #ifdef FEAT_PERL
10962 #ifndef DYNAMIC_PERL
10963 "perl",
10964 #endif
10965 #endif
10966 #ifdef FEAT_PYTHON
10967 #ifndef DYNAMIC_PYTHON
10968 "python",
10969 #endif
10970 #endif
10971 #ifdef FEAT_POSTSCRIPT
10972 "postscript",
10973 #endif
10974 #ifdef FEAT_PRINTER
10975 "printer",
10976 #endif
10977 #ifdef FEAT_PROFILE
10978 "profile",
10979 #endif
10980 #ifdef FEAT_RELTIME
10981 "reltime",
10982 #endif
10983 #ifdef FEAT_QUICKFIX
10984 "quickfix",
10985 #endif
10986 #ifdef FEAT_RIGHTLEFT
10987 "rightleft",
10988 #endif
10989 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
10990 "ruby",
10991 #endif
10992 #ifdef FEAT_SCROLLBIND
10993 "scrollbind",
10994 #endif
10995 #ifdef FEAT_CMDL_INFO
10996 "showcmd",
10997 "cmdline_info",
10998 #endif
10999 #ifdef FEAT_SIGNS
11000 "signs",
11001 #endif
11002 #ifdef FEAT_SMARTINDENT
11003 "smartindent",
11004 #endif
11005 #ifdef FEAT_SNIFF
11006 "sniff",
11007 #endif
11008 #ifdef FEAT_STL_OPT
11009 "statusline",
11010 #endif
11011 #ifdef FEAT_SUN_WORKSHOP
11012 "sun_workshop",
11013 #endif
11014 #ifdef FEAT_NETBEANS_INTG
11015 "netbeans_intg",
11016 #endif
11017 #ifdef FEAT_SPELL
11018 "spell",
11019 #endif
11020 #ifdef FEAT_SYN_HL
11021 "syntax",
11022 #endif
11023 #if defined(USE_SYSTEM) || !defined(UNIX)
11024 "system",
11025 #endif
11026 #ifdef FEAT_TAG_BINS
11027 "tag_binary",
11028 #endif
11029 #ifdef FEAT_TAG_OLDSTATIC
11030 "tag_old_static",
11031 #endif
11032 #ifdef FEAT_TAG_ANYWHITE
11033 "tag_any_white",
11034 #endif
11035 #ifdef FEAT_TCL
11036 # ifndef DYNAMIC_TCL
11037 "tcl",
11038 # endif
11039 #endif
11040 #ifdef TERMINFO
11041 "terminfo",
11042 #endif
11043 #ifdef FEAT_TERMRESPONSE
11044 "termresponse",
11045 #endif
11046 #ifdef FEAT_TEXTOBJ
11047 "textobjects",
11048 #endif
11049 #ifdef HAVE_TGETENT
11050 "tgetent",
11051 #endif
11052 #ifdef FEAT_TITLE
11053 "title",
11054 #endif
11055 #ifdef FEAT_TOOLBAR
11056 "toolbar",
11057 #endif
11058 #ifdef FEAT_USR_CMDS
11059 "user-commands", /* was accidentally included in 5.4 */
11060 "user_commands",
11061 #endif
11062 #ifdef FEAT_VIMINFO
11063 "viminfo",
11064 #endif
11065 #ifdef FEAT_VERTSPLIT
11066 "vertsplit",
11067 #endif
11068 #ifdef FEAT_VIRTUALEDIT
11069 "virtualedit",
11070 #endif
11071 #ifdef FEAT_VISUAL
11072 "visual",
11073 #endif
11074 #ifdef FEAT_VISUALEXTRA
11075 "visualextra",
11076 #endif
11077 #ifdef FEAT_VREPLACE
11078 "vreplace",
11079 #endif
11080 #ifdef FEAT_WILDIGN
11081 "wildignore",
11082 #endif
11083 #ifdef FEAT_WILDMENU
11084 "wildmenu",
11085 #endif
11086 #ifdef FEAT_WINDOWS
11087 "windows",
11088 #endif
11089 #ifdef FEAT_WAK
11090 "winaltkeys",
11091 #endif
11092 #ifdef FEAT_WRITEBACKUP
11093 "writebackup",
11094 #endif
11095 #ifdef FEAT_XIM
11096 "xim",
11097 #endif
11098 #ifdef FEAT_XFONTSET
11099 "xfontset",
11100 #endif
11101 #ifdef USE_XSMP
11102 "xsmp",
11103 #endif
11104 #ifdef USE_XSMP_INTERACT
11105 "xsmp_interact",
11106 #endif
11107 #ifdef FEAT_XCLIPBOARD
11108 "xterm_clipboard",
11109 #endif
11110 #ifdef FEAT_XTERM_SAVE
11111 "xterm_save",
11112 #endif
11113 #if defined(UNIX) && defined(FEAT_X11)
11114 "X11",
11115 #endif
11116 NULL
11119 name = get_tv_string(&argvars[0]);
11120 for (i = 0; has_list[i] != NULL; ++i)
11121 if (STRICMP(name, has_list[i]) == 0)
11123 n = TRUE;
11124 break;
11127 if (n == FALSE)
11129 if (STRNICMP(name, "patch", 5) == 0)
11130 n = has_patch(atoi((char *)name + 5));
11131 else if (STRICMP(name, "vim_starting") == 0)
11132 n = (starting != 0);
11133 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
11134 else if (STRICMP(name, "balloon_multiline") == 0)
11135 n = multiline_balloon_available();
11136 #endif
11137 #ifdef DYNAMIC_TCL
11138 else if (STRICMP(name, "tcl") == 0)
11139 n = tcl_enabled(FALSE);
11140 #endif
11141 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
11142 else if (STRICMP(name, "iconv") == 0)
11143 n = iconv_enabled(FALSE);
11144 #endif
11145 #ifdef DYNAMIC_MZSCHEME
11146 else if (STRICMP(name, "mzscheme") == 0)
11147 n = mzscheme_enabled(FALSE);
11148 #endif
11149 #ifdef DYNAMIC_RUBY
11150 else if (STRICMP(name, "ruby") == 0)
11151 n = ruby_enabled(FALSE);
11152 #endif
11153 #ifdef DYNAMIC_PYTHON
11154 else if (STRICMP(name, "python") == 0)
11155 n = python_enabled(FALSE);
11156 #endif
11157 #ifdef DYNAMIC_PERL
11158 else if (STRICMP(name, "perl") == 0)
11159 n = perl_enabled(FALSE);
11160 #endif
11161 #ifdef FEAT_GUI
11162 else if (STRICMP(name, "gui_running") == 0)
11163 n = (gui.in_use || gui.starting);
11164 # ifdef FEAT_GUI_W32
11165 else if (STRICMP(name, "gui_win32s") == 0)
11166 n = gui_is_win32s();
11167 # endif
11168 # ifdef FEAT_BROWSE
11169 else if (STRICMP(name, "browse") == 0)
11170 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
11171 # endif
11172 #endif
11173 #ifdef FEAT_SYN_HL
11174 else if (STRICMP(name, "syntax_items") == 0)
11175 n = syntax_present(curbuf);
11176 #endif
11177 #if defined(WIN3264)
11178 else if (STRICMP(name, "win95") == 0)
11179 n = mch_windows95();
11180 #endif
11181 #ifdef FEAT_NETBEANS_INTG
11182 else if (STRICMP(name, "netbeans_enabled") == 0)
11183 n = usingNetbeans;
11184 #endif
11187 rettv->vval.v_number = n;
11191 * "has_key()" function
11193 static void
11194 f_has_key(argvars, rettv)
11195 typval_T *argvars;
11196 typval_T *rettv;
11198 rettv->vval.v_number = 0;
11199 if (argvars[0].v_type != VAR_DICT)
11201 EMSG(_(e_dictreq));
11202 return;
11204 if (argvars[0].vval.v_dict == NULL)
11205 return;
11207 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
11208 get_tv_string(&argvars[1]), -1) != NULL;
11212 * "haslocaldir()" function
11214 /*ARGSUSED*/
11215 static void
11216 f_haslocaldir(argvars, rettv)
11217 typval_T *argvars;
11218 typval_T *rettv;
11220 rettv->vval.v_number = (curwin->w_localdir != NULL);
11224 * "hasmapto()" function
11226 static void
11227 f_hasmapto(argvars, rettv)
11228 typval_T *argvars;
11229 typval_T *rettv;
11231 char_u *name;
11232 char_u *mode;
11233 char_u buf[NUMBUFLEN];
11234 int abbr = FALSE;
11236 name = get_tv_string(&argvars[0]);
11237 if (argvars[1].v_type == VAR_UNKNOWN)
11238 mode = (char_u *)"nvo";
11239 else
11241 mode = get_tv_string_buf(&argvars[1], buf);
11242 if (argvars[2].v_type != VAR_UNKNOWN)
11243 abbr = get_tv_number(&argvars[2]);
11246 if (map_to_exists(name, mode, abbr))
11247 rettv->vval.v_number = TRUE;
11248 else
11249 rettv->vval.v_number = FALSE;
11253 * "histadd()" function
11255 /*ARGSUSED*/
11256 static void
11257 f_histadd(argvars, rettv)
11258 typval_T *argvars;
11259 typval_T *rettv;
11261 #ifdef FEAT_CMDHIST
11262 int histype;
11263 char_u *str;
11264 char_u buf[NUMBUFLEN];
11265 #endif
11267 rettv->vval.v_number = FALSE;
11268 if (check_restricted() || check_secure())
11269 return;
11270 #ifdef FEAT_CMDHIST
11271 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11272 histype = str != NULL ? get_histtype(str) : -1;
11273 if (histype >= 0)
11275 str = get_tv_string_buf(&argvars[1], buf);
11276 if (*str != NUL)
11278 add_to_history(histype, str, FALSE, NUL);
11279 rettv->vval.v_number = TRUE;
11280 return;
11283 #endif
11287 * "histdel()" function
11289 /*ARGSUSED*/
11290 static void
11291 f_histdel(argvars, rettv)
11292 typval_T *argvars;
11293 typval_T *rettv;
11295 #ifdef FEAT_CMDHIST
11296 int n;
11297 char_u buf[NUMBUFLEN];
11298 char_u *str;
11300 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11301 if (str == NULL)
11302 n = 0;
11303 else if (argvars[1].v_type == VAR_UNKNOWN)
11304 /* only one argument: clear entire history */
11305 n = clr_history(get_histtype(str));
11306 else if (argvars[1].v_type == VAR_NUMBER)
11307 /* index given: remove that entry */
11308 n = del_history_idx(get_histtype(str),
11309 (int)get_tv_number(&argvars[1]));
11310 else
11311 /* string given: remove all matching entries */
11312 n = del_history_entry(get_histtype(str),
11313 get_tv_string_buf(&argvars[1], buf));
11314 rettv->vval.v_number = n;
11315 #else
11316 rettv->vval.v_number = 0;
11317 #endif
11321 * "histget()" function
11323 /*ARGSUSED*/
11324 static void
11325 f_histget(argvars, rettv)
11326 typval_T *argvars;
11327 typval_T *rettv;
11329 #ifdef FEAT_CMDHIST
11330 int type;
11331 int idx;
11332 char_u *str;
11334 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11335 if (str == NULL)
11336 rettv->vval.v_string = NULL;
11337 else
11339 type = get_histtype(str);
11340 if (argvars[1].v_type == VAR_UNKNOWN)
11341 idx = get_history_idx(type);
11342 else
11343 idx = (int)get_tv_number_chk(&argvars[1], NULL);
11344 /* -1 on type error */
11345 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
11347 #else
11348 rettv->vval.v_string = NULL;
11349 #endif
11350 rettv->v_type = VAR_STRING;
11354 * "histnr()" function
11356 /*ARGSUSED*/
11357 static void
11358 f_histnr(argvars, rettv)
11359 typval_T *argvars;
11360 typval_T *rettv;
11362 int i;
11364 #ifdef FEAT_CMDHIST
11365 char_u *history = get_tv_string_chk(&argvars[0]);
11367 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
11368 if (i >= HIST_CMD && i < HIST_COUNT)
11369 i = get_history_idx(i);
11370 else
11371 #endif
11372 i = -1;
11373 rettv->vval.v_number = i;
11377 * "highlightID(name)" function
11379 static void
11380 f_hlID(argvars, rettv)
11381 typval_T *argvars;
11382 typval_T *rettv;
11384 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
11388 * "highlight_exists()" function
11390 static void
11391 f_hlexists(argvars, rettv)
11392 typval_T *argvars;
11393 typval_T *rettv;
11395 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
11399 * "hostname()" function
11401 /*ARGSUSED*/
11402 static void
11403 f_hostname(argvars, rettv)
11404 typval_T *argvars;
11405 typval_T *rettv;
11407 char_u hostname[256];
11409 mch_get_host_name(hostname, 256);
11410 rettv->v_type = VAR_STRING;
11411 rettv->vval.v_string = vim_strsave(hostname);
11415 * iconv() function
11417 /*ARGSUSED*/
11418 static void
11419 f_iconv(argvars, rettv)
11420 typval_T *argvars;
11421 typval_T *rettv;
11423 #ifdef FEAT_MBYTE
11424 char_u buf1[NUMBUFLEN];
11425 char_u buf2[NUMBUFLEN];
11426 char_u *from, *to, *str;
11427 vimconv_T vimconv;
11428 #endif
11430 rettv->v_type = VAR_STRING;
11431 rettv->vval.v_string = NULL;
11433 #ifdef FEAT_MBYTE
11434 str = get_tv_string(&argvars[0]);
11435 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
11436 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
11437 vimconv.vc_type = CONV_NONE;
11438 convert_setup(&vimconv, from, to);
11440 /* If the encodings are equal, no conversion needed. */
11441 if (vimconv.vc_type == CONV_NONE)
11442 rettv->vval.v_string = vim_strsave(str);
11443 else
11444 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
11446 convert_setup(&vimconv, NULL, NULL);
11447 vim_free(from);
11448 vim_free(to);
11449 #endif
11453 * "indent()" function
11455 static void
11456 f_indent(argvars, rettv)
11457 typval_T *argvars;
11458 typval_T *rettv;
11460 linenr_T lnum;
11462 lnum = get_tv_lnum(argvars);
11463 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
11464 rettv->vval.v_number = get_indent_lnum(lnum);
11465 else
11466 rettv->vval.v_number = -1;
11470 * "index()" function
11472 static void
11473 f_index(argvars, rettv)
11474 typval_T *argvars;
11475 typval_T *rettv;
11477 list_T *l;
11478 listitem_T *item;
11479 long idx = 0;
11480 int ic = FALSE;
11482 rettv->vval.v_number = -1;
11483 if (argvars[0].v_type != VAR_LIST)
11485 EMSG(_(e_listreq));
11486 return;
11488 l = argvars[0].vval.v_list;
11489 if (l != NULL)
11491 item = l->lv_first;
11492 if (argvars[2].v_type != VAR_UNKNOWN)
11494 int error = FALSE;
11496 /* Start at specified item. Use the cached index that list_find()
11497 * sets, so that a negative number also works. */
11498 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
11499 idx = l->lv_idx;
11500 if (argvars[3].v_type != VAR_UNKNOWN)
11501 ic = get_tv_number_chk(&argvars[3], &error);
11502 if (error)
11503 item = NULL;
11506 for ( ; item != NULL; item = item->li_next, ++idx)
11507 if (tv_equal(&item->li_tv, &argvars[1], ic))
11509 rettv->vval.v_number = idx;
11510 break;
11515 static int inputsecret_flag = 0;
11517 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
11520 * This function is used by f_input() and f_inputdialog() functions. The third
11521 * argument to f_input() specifies the type of completion to use at the
11522 * prompt. The third argument to f_inputdialog() specifies the value to return
11523 * when the user cancels the prompt.
11525 static void
11526 get_user_input(argvars, rettv, inputdialog)
11527 typval_T *argvars;
11528 typval_T *rettv;
11529 int inputdialog;
11531 char_u *prompt = get_tv_string_chk(&argvars[0]);
11532 char_u *p = NULL;
11533 int c;
11534 char_u buf[NUMBUFLEN];
11535 int cmd_silent_save = cmd_silent;
11536 char_u *defstr = (char_u *)"";
11537 int xp_type = EXPAND_NOTHING;
11538 char_u *xp_arg = NULL;
11540 rettv->v_type = VAR_STRING;
11542 #ifdef NO_CONSOLE_INPUT
11543 /* While starting up, there is no place to enter text. */
11544 if (no_console_input())
11546 rettv->vval.v_string = NULL;
11547 return;
11549 #endif
11551 cmd_silent = FALSE; /* Want to see the prompt. */
11552 if (prompt != NULL)
11554 /* Only the part of the message after the last NL is considered as
11555 * prompt for the command line */
11556 p = vim_strrchr(prompt, '\n');
11557 if (p == NULL)
11558 p = prompt;
11559 else
11561 ++p;
11562 c = *p;
11563 *p = NUL;
11564 msg_start();
11565 msg_clr_eos();
11566 msg_puts_attr(prompt, echo_attr);
11567 msg_didout = FALSE;
11568 msg_starthere();
11569 *p = c;
11571 cmdline_row = msg_row;
11573 if (argvars[1].v_type != VAR_UNKNOWN)
11575 defstr = get_tv_string_buf_chk(&argvars[1], buf);
11576 if (defstr != NULL)
11577 stuffReadbuffSpec(defstr);
11579 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
11581 char_u *xp_name;
11582 int xp_namelen;
11583 long argt;
11585 rettv->vval.v_string = NULL;
11587 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
11588 if (xp_name == NULL)
11589 return;
11591 xp_namelen = (int)STRLEN(xp_name);
11593 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
11594 &xp_arg) == FAIL)
11595 return;
11599 if (defstr != NULL)
11600 rettv->vval.v_string =
11601 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
11602 xp_type, xp_arg);
11604 vim_free(xp_arg);
11606 /* since the user typed this, no need to wait for return */
11607 need_wait_return = FALSE;
11608 msg_didout = FALSE;
11610 cmd_silent = cmd_silent_save;
11614 * "input()" function
11615 * Also handles inputsecret() when inputsecret is set.
11617 static void
11618 f_input(argvars, rettv)
11619 typval_T *argvars;
11620 typval_T *rettv;
11622 get_user_input(argvars, rettv, FALSE);
11626 * "inputdialog()" function
11628 static void
11629 f_inputdialog(argvars, rettv)
11630 typval_T *argvars;
11631 typval_T *rettv;
11633 #if defined(FEAT_GUI_TEXTDIALOG)
11634 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
11635 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
11637 char_u *message;
11638 char_u buf[NUMBUFLEN];
11639 char_u *defstr = (char_u *)"";
11641 message = get_tv_string_chk(&argvars[0]);
11642 if (argvars[1].v_type != VAR_UNKNOWN
11643 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
11644 vim_strncpy(IObuff, defstr, IOSIZE - 1);
11645 else
11646 IObuff[0] = NUL;
11647 if (message != NULL && defstr != NULL
11648 && do_dialog(VIM_QUESTION, NULL, message,
11649 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
11650 rettv->vval.v_string = vim_strsave(IObuff);
11651 else
11653 if (message != NULL && defstr != NULL
11654 && argvars[1].v_type != VAR_UNKNOWN
11655 && argvars[2].v_type != VAR_UNKNOWN)
11656 rettv->vval.v_string = vim_strsave(
11657 get_tv_string_buf(&argvars[2], buf));
11658 else
11659 rettv->vval.v_string = NULL;
11661 rettv->v_type = VAR_STRING;
11663 else
11664 #endif
11665 get_user_input(argvars, rettv, TRUE);
11669 * "inputlist()" function
11671 static void
11672 f_inputlist(argvars, rettv)
11673 typval_T *argvars;
11674 typval_T *rettv;
11676 listitem_T *li;
11677 int selected;
11678 int mouse_used;
11680 rettv->vval.v_number = 0;
11681 #ifdef NO_CONSOLE_INPUT
11682 /* While starting up, there is no place to enter text. */
11683 if (no_console_input())
11684 return;
11685 #endif
11686 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
11688 EMSG2(_(e_listarg), "inputlist()");
11689 return;
11692 msg_start();
11693 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
11694 lines_left = Rows; /* avoid more prompt */
11695 msg_scroll = TRUE;
11696 msg_clr_eos();
11698 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
11700 msg_puts(get_tv_string(&li->li_tv));
11701 msg_putchar('\n');
11704 /* Ask for choice. */
11705 selected = prompt_for_number(&mouse_used);
11706 if (mouse_used)
11707 selected -= lines_left;
11709 rettv->vval.v_number = selected;
11713 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
11716 * "inputrestore()" function
11718 /*ARGSUSED*/
11719 static void
11720 f_inputrestore(argvars, rettv)
11721 typval_T *argvars;
11722 typval_T *rettv;
11724 if (ga_userinput.ga_len > 0)
11726 --ga_userinput.ga_len;
11727 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
11728 + ga_userinput.ga_len);
11729 rettv->vval.v_number = 0; /* OK */
11731 else if (p_verbose > 1)
11733 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
11734 rettv->vval.v_number = 1; /* Failed */
11739 * "inputsave()" function
11741 /*ARGSUSED*/
11742 static void
11743 f_inputsave(argvars, rettv)
11744 typval_T *argvars;
11745 typval_T *rettv;
11747 /* Add an entry to the stack of typehead storage. */
11748 if (ga_grow(&ga_userinput, 1) == OK)
11750 save_typeahead((tasave_T *)(ga_userinput.ga_data)
11751 + ga_userinput.ga_len);
11752 ++ga_userinput.ga_len;
11753 rettv->vval.v_number = 0; /* OK */
11755 else
11756 rettv->vval.v_number = 1; /* Failed */
11760 * "inputsecret()" function
11762 static void
11763 f_inputsecret(argvars, rettv)
11764 typval_T *argvars;
11765 typval_T *rettv;
11767 ++cmdline_star;
11768 ++inputsecret_flag;
11769 f_input(argvars, rettv);
11770 --cmdline_star;
11771 --inputsecret_flag;
11775 * "insert()" function
11777 static void
11778 f_insert(argvars, rettv)
11779 typval_T *argvars;
11780 typval_T *rettv;
11782 long before = 0;
11783 listitem_T *item;
11784 list_T *l;
11785 int error = FALSE;
11787 rettv->vval.v_number = 0;
11788 if (argvars[0].v_type != VAR_LIST)
11789 EMSG2(_(e_listarg), "insert()");
11790 else if ((l = argvars[0].vval.v_list) != NULL
11791 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
11793 if (argvars[2].v_type != VAR_UNKNOWN)
11794 before = get_tv_number_chk(&argvars[2], &error);
11795 if (error)
11796 return; /* type error; errmsg already given */
11798 if (before == l->lv_len)
11799 item = NULL;
11800 else
11802 item = list_find(l, before);
11803 if (item == NULL)
11805 EMSGN(_(e_listidx), before);
11806 l = NULL;
11809 if (l != NULL)
11811 list_insert_tv(l, &argvars[1], item);
11812 copy_tv(&argvars[0], rettv);
11818 * "isdirectory()" function
11820 static void
11821 f_isdirectory(argvars, rettv)
11822 typval_T *argvars;
11823 typval_T *rettv;
11825 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
11829 * "islocked()" function
11831 static void
11832 f_islocked(argvars, rettv)
11833 typval_T *argvars;
11834 typval_T *rettv;
11836 lval_T lv;
11837 char_u *end;
11838 dictitem_T *di;
11840 rettv->vval.v_number = -1;
11841 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
11842 FNE_CHECK_START);
11843 if (end != NULL && lv.ll_name != NULL)
11845 if (*end != NUL)
11846 EMSG(_(e_trailing));
11847 else
11849 if (lv.ll_tv == NULL)
11851 if (check_changedtick(lv.ll_name))
11852 rettv->vval.v_number = 1; /* always locked */
11853 else
11855 di = find_var(lv.ll_name, NULL);
11856 if (di != NULL)
11858 /* Consider a variable locked when:
11859 * 1. the variable itself is locked
11860 * 2. the value of the variable is locked.
11861 * 3. the List or Dict value is locked.
11863 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
11864 || tv_islocked(&di->di_tv));
11868 else if (lv.ll_range)
11869 EMSG(_("E786: Range not allowed"));
11870 else if (lv.ll_newkey != NULL)
11871 EMSG2(_(e_dictkey), lv.ll_newkey);
11872 else if (lv.ll_list != NULL)
11873 /* List item. */
11874 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
11875 else
11876 /* Dictionary item. */
11877 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
11881 clear_lval(&lv);
11884 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
11887 * Turn a dict into a list:
11888 * "what" == 0: list of keys
11889 * "what" == 1: list of values
11890 * "what" == 2: list of items
11892 static void
11893 dict_list(argvars, rettv, what)
11894 typval_T *argvars;
11895 typval_T *rettv;
11896 int what;
11898 list_T *l2;
11899 dictitem_T *di;
11900 hashitem_T *hi;
11901 listitem_T *li;
11902 listitem_T *li2;
11903 dict_T *d;
11904 int todo;
11906 rettv->vval.v_number = 0;
11907 if (argvars[0].v_type != VAR_DICT)
11909 EMSG(_(e_dictreq));
11910 return;
11912 if ((d = argvars[0].vval.v_dict) == NULL)
11913 return;
11915 if (rettv_list_alloc(rettv) == FAIL)
11916 return;
11918 todo = (int)d->dv_hashtab.ht_used;
11919 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
11921 if (!HASHITEM_EMPTY(hi))
11923 --todo;
11924 di = HI2DI(hi);
11926 li = listitem_alloc();
11927 if (li == NULL)
11928 break;
11929 list_append(rettv->vval.v_list, li);
11931 if (what == 0)
11933 /* keys() */
11934 li->li_tv.v_type = VAR_STRING;
11935 li->li_tv.v_lock = 0;
11936 li->li_tv.vval.v_string = vim_strsave(di->di_key);
11938 else if (what == 1)
11940 /* values() */
11941 copy_tv(&di->di_tv, &li->li_tv);
11943 else
11945 /* items() */
11946 l2 = list_alloc();
11947 li->li_tv.v_type = VAR_LIST;
11948 li->li_tv.v_lock = 0;
11949 li->li_tv.vval.v_list = l2;
11950 if (l2 == NULL)
11951 break;
11952 ++l2->lv_refcount;
11954 li2 = listitem_alloc();
11955 if (li2 == NULL)
11956 break;
11957 list_append(l2, li2);
11958 li2->li_tv.v_type = VAR_STRING;
11959 li2->li_tv.v_lock = 0;
11960 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
11962 li2 = listitem_alloc();
11963 if (li2 == NULL)
11964 break;
11965 list_append(l2, li2);
11966 copy_tv(&di->di_tv, &li2->li_tv);
11973 * "items(dict)" function
11975 static void
11976 f_items(argvars, rettv)
11977 typval_T *argvars;
11978 typval_T *rettv;
11980 dict_list(argvars, rettv, 2);
11984 * "join()" function
11986 static void
11987 f_join(argvars, rettv)
11988 typval_T *argvars;
11989 typval_T *rettv;
11991 garray_T ga;
11992 char_u *sep;
11994 rettv->vval.v_number = 0;
11995 if (argvars[0].v_type != VAR_LIST)
11997 EMSG(_(e_listreq));
11998 return;
12000 if (argvars[0].vval.v_list == NULL)
12001 return;
12002 if (argvars[1].v_type == VAR_UNKNOWN)
12003 sep = (char_u *)" ";
12004 else
12005 sep = get_tv_string_chk(&argvars[1]);
12007 rettv->v_type = VAR_STRING;
12009 if (sep != NULL)
12011 ga_init2(&ga, (int)sizeof(char), 80);
12012 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12013 ga_append(&ga, NUL);
12014 rettv->vval.v_string = (char_u *)ga.ga_data;
12016 else
12017 rettv->vval.v_string = NULL;
12021 * "keys()" function
12023 static void
12024 f_keys(argvars, rettv)
12025 typval_T *argvars;
12026 typval_T *rettv;
12028 dict_list(argvars, rettv, 0);
12032 * "last_buffer_nr()" function.
12034 /*ARGSUSED*/
12035 static void
12036 f_last_buffer_nr(argvars, rettv)
12037 typval_T *argvars;
12038 typval_T *rettv;
12040 int n = 0;
12041 buf_T *buf;
12043 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12044 if (n < buf->b_fnum)
12045 n = buf->b_fnum;
12047 rettv->vval.v_number = n;
12051 * "len()" function
12053 static void
12054 f_len(argvars, rettv)
12055 typval_T *argvars;
12056 typval_T *rettv;
12058 switch (argvars[0].v_type)
12060 case VAR_STRING:
12061 case VAR_NUMBER:
12062 rettv->vval.v_number = (varnumber_T)STRLEN(
12063 get_tv_string(&argvars[0]));
12064 break;
12065 case VAR_LIST:
12066 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
12067 break;
12068 case VAR_DICT:
12069 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
12070 break;
12071 default:
12072 EMSG(_("E701: Invalid type for len()"));
12073 break;
12077 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
12079 static void
12080 libcall_common(argvars, rettv, type)
12081 typval_T *argvars;
12082 typval_T *rettv;
12083 int type;
12085 #ifdef FEAT_LIBCALL
12086 char_u *string_in;
12087 char_u **string_result;
12088 int nr_result;
12089 #endif
12091 rettv->v_type = type;
12092 if (type == VAR_NUMBER)
12093 rettv->vval.v_number = 0;
12094 else
12095 rettv->vval.v_string = NULL;
12097 if (check_restricted() || check_secure())
12098 return;
12100 #ifdef FEAT_LIBCALL
12101 /* The first two args must be strings, otherwise its meaningless */
12102 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
12104 string_in = NULL;
12105 if (argvars[2].v_type == VAR_STRING)
12106 string_in = argvars[2].vval.v_string;
12107 if (type == VAR_NUMBER)
12108 string_result = NULL;
12109 else
12110 string_result = &rettv->vval.v_string;
12111 if (mch_libcall(argvars[0].vval.v_string,
12112 argvars[1].vval.v_string,
12113 string_in,
12114 argvars[2].vval.v_number,
12115 string_result,
12116 &nr_result) == OK
12117 && type == VAR_NUMBER)
12118 rettv->vval.v_number = nr_result;
12120 #endif
12124 * "libcall()" function
12126 static void
12127 f_libcall(argvars, rettv)
12128 typval_T *argvars;
12129 typval_T *rettv;
12131 libcall_common(argvars, rettv, VAR_STRING);
12135 * "libcallnr()" function
12137 static void
12138 f_libcallnr(argvars, rettv)
12139 typval_T *argvars;
12140 typval_T *rettv;
12142 libcall_common(argvars, rettv, VAR_NUMBER);
12146 * "line(string)" function
12148 static void
12149 f_line(argvars, rettv)
12150 typval_T *argvars;
12151 typval_T *rettv;
12153 linenr_T lnum = 0;
12154 pos_T *fp;
12155 int fnum;
12157 fp = var2fpos(&argvars[0], TRUE, &fnum);
12158 if (fp != NULL)
12159 lnum = fp->lnum;
12160 rettv->vval.v_number = lnum;
12164 * "line2byte(lnum)" function
12166 /*ARGSUSED*/
12167 static void
12168 f_line2byte(argvars, rettv)
12169 typval_T *argvars;
12170 typval_T *rettv;
12172 #ifndef FEAT_BYTEOFF
12173 rettv->vval.v_number = -1;
12174 #else
12175 linenr_T lnum;
12177 lnum = get_tv_lnum(argvars);
12178 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
12179 rettv->vval.v_number = -1;
12180 else
12181 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
12182 if (rettv->vval.v_number >= 0)
12183 ++rettv->vval.v_number;
12184 #endif
12188 * "lispindent(lnum)" function
12190 static void
12191 f_lispindent(argvars, rettv)
12192 typval_T *argvars;
12193 typval_T *rettv;
12195 #ifdef FEAT_LISP
12196 pos_T pos;
12197 linenr_T lnum;
12199 pos = curwin->w_cursor;
12200 lnum = get_tv_lnum(argvars);
12201 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12203 curwin->w_cursor.lnum = lnum;
12204 rettv->vval.v_number = get_lisp_indent();
12205 curwin->w_cursor = pos;
12207 else
12208 #endif
12209 rettv->vval.v_number = -1;
12213 * "localtime()" function
12215 /*ARGSUSED*/
12216 static void
12217 f_localtime(argvars, rettv)
12218 typval_T *argvars;
12219 typval_T *rettv;
12221 rettv->vval.v_number = (varnumber_T)time(NULL);
12224 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
12226 static void
12227 get_maparg(argvars, rettv, exact)
12228 typval_T *argvars;
12229 typval_T *rettv;
12230 int exact;
12232 char_u *keys;
12233 char_u *which;
12234 char_u buf[NUMBUFLEN];
12235 char_u *keys_buf = NULL;
12236 char_u *rhs;
12237 int mode;
12238 garray_T ga;
12239 int abbr = FALSE;
12241 /* return empty string for failure */
12242 rettv->v_type = VAR_STRING;
12243 rettv->vval.v_string = NULL;
12245 keys = get_tv_string(&argvars[0]);
12246 if (*keys == NUL)
12247 return;
12249 if (argvars[1].v_type != VAR_UNKNOWN)
12251 which = get_tv_string_buf_chk(&argvars[1], buf);
12252 if (argvars[2].v_type != VAR_UNKNOWN)
12253 abbr = get_tv_number(&argvars[2]);
12255 else
12256 which = (char_u *)"";
12257 if (which == NULL)
12258 return;
12260 mode = get_map_mode(&which, 0);
12262 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
12263 rhs = check_map(keys, mode, exact, FALSE, abbr);
12264 vim_free(keys_buf);
12265 if (rhs != NULL)
12267 ga_init(&ga);
12268 ga.ga_itemsize = 1;
12269 ga.ga_growsize = 40;
12271 while (*rhs != NUL)
12272 ga_concat(&ga, str2special(&rhs, FALSE));
12274 ga_append(&ga, NUL);
12275 rettv->vval.v_string = (char_u *)ga.ga_data;
12280 * "map()" function
12282 static void
12283 f_map(argvars, rettv)
12284 typval_T *argvars;
12285 typval_T *rettv;
12287 filter_map(argvars, rettv, TRUE);
12291 * "maparg()" function
12293 static void
12294 f_maparg(argvars, rettv)
12295 typval_T *argvars;
12296 typval_T *rettv;
12298 get_maparg(argvars, rettv, TRUE);
12302 * "mapcheck()" function
12304 static void
12305 f_mapcheck(argvars, rettv)
12306 typval_T *argvars;
12307 typval_T *rettv;
12309 get_maparg(argvars, rettv, FALSE);
12312 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
12314 static void
12315 find_some_match(argvars, rettv, type)
12316 typval_T *argvars;
12317 typval_T *rettv;
12318 int type;
12320 char_u *str = NULL;
12321 char_u *expr = NULL;
12322 char_u *pat;
12323 regmatch_T regmatch;
12324 char_u patbuf[NUMBUFLEN];
12325 char_u strbuf[NUMBUFLEN];
12326 char_u *save_cpo;
12327 long start = 0;
12328 long nth = 1;
12329 colnr_T startcol = 0;
12330 int match = 0;
12331 list_T *l = NULL;
12332 listitem_T *li = NULL;
12333 long idx = 0;
12334 char_u *tofree = NULL;
12336 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
12337 save_cpo = p_cpo;
12338 p_cpo = (char_u *)"";
12340 rettv->vval.v_number = -1;
12341 if (type == 3)
12343 /* return empty list when there are no matches */
12344 if (rettv_list_alloc(rettv) == FAIL)
12345 goto theend;
12347 else if (type == 2)
12349 rettv->v_type = VAR_STRING;
12350 rettv->vval.v_string = NULL;
12353 if (argvars[0].v_type == VAR_LIST)
12355 if ((l = argvars[0].vval.v_list) == NULL)
12356 goto theend;
12357 li = l->lv_first;
12359 else
12360 expr = str = get_tv_string(&argvars[0]);
12362 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
12363 if (pat == NULL)
12364 goto theend;
12366 if (argvars[2].v_type != VAR_UNKNOWN)
12368 int error = FALSE;
12370 start = get_tv_number_chk(&argvars[2], &error);
12371 if (error)
12372 goto theend;
12373 if (l != NULL)
12375 li = list_find(l, start);
12376 if (li == NULL)
12377 goto theend;
12378 idx = l->lv_idx; /* use the cached index */
12380 else
12382 if (start < 0)
12383 start = 0;
12384 if (start > (long)STRLEN(str))
12385 goto theend;
12386 /* When "count" argument is there ignore matches before "start",
12387 * otherwise skip part of the string. Differs when pattern is "^"
12388 * or "\<". */
12389 if (argvars[3].v_type != VAR_UNKNOWN)
12390 startcol = start;
12391 else
12392 str += start;
12395 if (argvars[3].v_type != VAR_UNKNOWN)
12396 nth = get_tv_number_chk(&argvars[3], &error);
12397 if (error)
12398 goto theend;
12401 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
12402 if (regmatch.regprog != NULL)
12404 regmatch.rm_ic = p_ic;
12406 for (;;)
12408 if (l != NULL)
12410 if (li == NULL)
12412 match = FALSE;
12413 break;
12415 vim_free(tofree);
12416 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
12417 if (str == NULL)
12418 break;
12421 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
12423 if (match && --nth <= 0)
12424 break;
12425 if (l == NULL && !match)
12426 break;
12428 /* Advance to just after the match. */
12429 if (l != NULL)
12431 li = li->li_next;
12432 ++idx;
12434 else
12436 #ifdef FEAT_MBYTE
12437 startcol = (colnr_T)(regmatch.startp[0]
12438 + (*mb_ptr2len)(regmatch.startp[0]) - str);
12439 #else
12440 startcol = regmatch.startp[0] + 1 - str;
12441 #endif
12445 if (match)
12447 if (type == 3)
12449 int i;
12451 /* return list with matched string and submatches */
12452 for (i = 0; i < NSUBEXP; ++i)
12454 if (regmatch.endp[i] == NULL)
12456 if (list_append_string(rettv->vval.v_list,
12457 (char_u *)"", 0) == FAIL)
12458 break;
12460 else if (list_append_string(rettv->vval.v_list,
12461 regmatch.startp[i],
12462 (int)(regmatch.endp[i] - regmatch.startp[i]))
12463 == FAIL)
12464 break;
12467 else if (type == 2)
12469 /* return matched string */
12470 if (l != NULL)
12471 copy_tv(&li->li_tv, rettv);
12472 else
12473 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
12474 (int)(regmatch.endp[0] - regmatch.startp[0]));
12476 else if (l != NULL)
12477 rettv->vval.v_number = idx;
12478 else
12480 if (type != 0)
12481 rettv->vval.v_number =
12482 (varnumber_T)(regmatch.startp[0] - str);
12483 else
12484 rettv->vval.v_number =
12485 (varnumber_T)(regmatch.endp[0] - str);
12486 rettv->vval.v_number += (varnumber_T)(str - expr);
12489 vim_free(regmatch.regprog);
12492 theend:
12493 vim_free(tofree);
12494 p_cpo = save_cpo;
12498 * "match()" function
12500 static void
12501 f_match(argvars, rettv)
12502 typval_T *argvars;
12503 typval_T *rettv;
12505 find_some_match(argvars, rettv, 1);
12509 * "matchadd()" function
12511 static void
12512 f_matchadd(argvars, rettv)
12513 typval_T *argvars;
12514 typval_T *rettv;
12516 #ifdef FEAT_SEARCH_EXTRA
12517 char_u buf[NUMBUFLEN];
12518 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
12519 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
12520 int prio = 10; /* default priority */
12521 int id = -1;
12522 int error = FALSE;
12524 rettv->vval.v_number = -1;
12526 if (grp == NULL || pat == NULL)
12527 return;
12528 if (argvars[2].v_type != VAR_UNKNOWN)
12530 prio = get_tv_number_chk(&argvars[2], &error);
12531 if (argvars[3].v_type != VAR_UNKNOWN)
12532 id = get_tv_number_chk(&argvars[3], &error);
12534 if (error == TRUE)
12535 return;
12536 if (id >= 1 && id <= 3)
12538 EMSGN("E798: ID is reserved for \":match\": %ld", id);
12539 return;
12542 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
12543 #endif
12547 * "matcharg()" function
12549 static void
12550 f_matcharg(argvars, rettv)
12551 typval_T *argvars;
12552 typval_T *rettv;
12554 if (rettv_list_alloc(rettv) == OK)
12556 #ifdef FEAT_SEARCH_EXTRA
12557 int id = get_tv_number(&argvars[0]);
12558 matchitem_T *m;
12560 if (id >= 1 && id <= 3)
12562 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
12564 list_append_string(rettv->vval.v_list,
12565 syn_id2name(m->hlg_id), -1);
12566 list_append_string(rettv->vval.v_list, m->pattern, -1);
12568 else
12570 list_append_string(rettv->vval.v_list, NUL, -1);
12571 list_append_string(rettv->vval.v_list, NUL, -1);
12574 #endif
12579 * "matchdelete()" function
12581 static void
12582 f_matchdelete(argvars, rettv)
12583 typval_T *argvars;
12584 typval_T *rettv;
12586 #ifdef FEAT_SEARCH_EXTRA
12587 rettv->vval.v_number = match_delete(curwin,
12588 (int)get_tv_number(&argvars[0]), TRUE);
12589 #endif
12593 * "matchend()" function
12595 static void
12596 f_matchend(argvars, rettv)
12597 typval_T *argvars;
12598 typval_T *rettv;
12600 find_some_match(argvars, rettv, 0);
12604 * "matchlist()" function
12606 static void
12607 f_matchlist(argvars, rettv)
12608 typval_T *argvars;
12609 typval_T *rettv;
12611 find_some_match(argvars, rettv, 3);
12615 * "matchstr()" function
12617 static void
12618 f_matchstr(argvars, rettv)
12619 typval_T *argvars;
12620 typval_T *rettv;
12622 find_some_match(argvars, rettv, 2);
12625 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
12627 static void
12628 max_min(argvars, rettv, domax)
12629 typval_T *argvars;
12630 typval_T *rettv;
12631 int domax;
12633 long n = 0;
12634 long i;
12635 int error = FALSE;
12637 if (argvars[0].v_type == VAR_LIST)
12639 list_T *l;
12640 listitem_T *li;
12642 l = argvars[0].vval.v_list;
12643 if (l != NULL)
12645 li = l->lv_first;
12646 if (li != NULL)
12648 n = get_tv_number_chk(&li->li_tv, &error);
12649 for (;;)
12651 li = li->li_next;
12652 if (li == NULL)
12653 break;
12654 i = get_tv_number_chk(&li->li_tv, &error);
12655 if (domax ? i > n : i < n)
12656 n = i;
12661 else if (argvars[0].v_type == VAR_DICT)
12663 dict_T *d;
12664 int first = TRUE;
12665 hashitem_T *hi;
12666 int todo;
12668 d = argvars[0].vval.v_dict;
12669 if (d != NULL)
12671 todo = (int)d->dv_hashtab.ht_used;
12672 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12674 if (!HASHITEM_EMPTY(hi))
12676 --todo;
12677 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
12678 if (first)
12680 n = i;
12681 first = FALSE;
12683 else if (domax ? i > n : i < n)
12684 n = i;
12689 else
12690 EMSG(_(e_listdictarg));
12691 rettv->vval.v_number = error ? 0 : n;
12695 * "max()" function
12697 static void
12698 f_max(argvars, rettv)
12699 typval_T *argvars;
12700 typval_T *rettv;
12702 max_min(argvars, rettv, TRUE);
12706 * "min()" function
12708 static void
12709 f_min(argvars, rettv)
12710 typval_T *argvars;
12711 typval_T *rettv;
12713 max_min(argvars, rettv, FALSE);
12716 static int mkdir_recurse __ARGS((char_u *dir, int prot));
12719 * Create the directory in which "dir" is located, and higher levels when
12720 * needed.
12722 static int
12723 mkdir_recurse(dir, prot)
12724 char_u *dir;
12725 int prot;
12727 char_u *p;
12728 char_u *updir;
12729 int r = FAIL;
12731 /* Get end of directory name in "dir".
12732 * We're done when it's "/" or "c:/". */
12733 p = gettail_sep(dir);
12734 if (p <= get_past_head(dir))
12735 return OK;
12737 /* If the directory exists we're done. Otherwise: create it.*/
12738 updir = vim_strnsave(dir, (int)(p - dir));
12739 if (updir == NULL)
12740 return FAIL;
12741 if (mch_isdir(updir))
12742 r = OK;
12743 else if (mkdir_recurse(updir, prot) == OK)
12744 r = vim_mkdir_emsg(updir, prot);
12745 vim_free(updir);
12746 return r;
12749 #ifdef vim_mkdir
12751 * "mkdir()" function
12753 static void
12754 f_mkdir(argvars, rettv)
12755 typval_T *argvars;
12756 typval_T *rettv;
12758 char_u *dir;
12759 char_u buf[NUMBUFLEN];
12760 int prot = 0755;
12762 rettv->vval.v_number = FAIL;
12763 if (check_restricted() || check_secure())
12764 return;
12766 dir = get_tv_string_buf(&argvars[0], buf);
12767 if (argvars[1].v_type != VAR_UNKNOWN)
12769 if (argvars[2].v_type != VAR_UNKNOWN)
12770 prot = get_tv_number_chk(&argvars[2], NULL);
12771 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
12772 mkdir_recurse(dir, prot);
12774 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
12776 #endif
12779 * "mode()" function
12781 /*ARGSUSED*/
12782 static void
12783 f_mode(argvars, rettv)
12784 typval_T *argvars;
12785 typval_T *rettv;
12787 char_u buf[2];
12789 #ifdef FEAT_VISUAL
12790 if (VIsual_active)
12792 if (VIsual_select)
12793 buf[0] = VIsual_mode + 's' - 'v';
12794 else
12795 buf[0] = VIsual_mode;
12797 else
12798 #endif
12799 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE)
12800 buf[0] = 'r';
12801 else if (State & INSERT)
12803 if (State & REPLACE_FLAG)
12804 buf[0] = 'R';
12805 else
12806 buf[0] = 'i';
12808 else if (State & CMDLINE)
12809 buf[0] = 'c';
12810 else
12811 buf[0] = 'n';
12813 buf[1] = NUL;
12814 rettv->vval.v_string = vim_strsave(buf);
12815 rettv->v_type = VAR_STRING;
12819 * "nextnonblank()" function
12821 static void
12822 f_nextnonblank(argvars, rettv)
12823 typval_T *argvars;
12824 typval_T *rettv;
12826 linenr_T lnum;
12828 for (lnum = get_tv_lnum(argvars); ; ++lnum)
12830 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
12832 lnum = 0;
12833 break;
12835 if (*skipwhite(ml_get(lnum)) != NUL)
12836 break;
12838 rettv->vval.v_number = lnum;
12842 * "nr2char()" function
12844 static void
12845 f_nr2char(argvars, rettv)
12846 typval_T *argvars;
12847 typval_T *rettv;
12849 char_u buf[NUMBUFLEN];
12851 #ifdef FEAT_MBYTE
12852 if (has_mbyte)
12853 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
12854 else
12855 #endif
12857 buf[0] = (char_u)get_tv_number(&argvars[0]);
12858 buf[1] = NUL;
12860 rettv->v_type = VAR_STRING;
12861 rettv->vval.v_string = vim_strsave(buf);
12865 * "pathshorten()" function
12867 static void
12868 f_pathshorten(argvars, rettv)
12869 typval_T *argvars;
12870 typval_T *rettv;
12872 char_u *p;
12874 rettv->v_type = VAR_STRING;
12875 p = get_tv_string_chk(&argvars[0]);
12876 if (p == NULL)
12877 rettv->vval.v_string = NULL;
12878 else
12880 p = vim_strsave(p);
12881 rettv->vval.v_string = p;
12882 if (p != NULL)
12883 shorten_dir(p);
12888 * "prevnonblank()" function
12890 static void
12891 f_prevnonblank(argvars, rettv)
12892 typval_T *argvars;
12893 typval_T *rettv;
12895 linenr_T lnum;
12897 lnum = get_tv_lnum(argvars);
12898 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
12899 lnum = 0;
12900 else
12901 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
12902 --lnum;
12903 rettv->vval.v_number = lnum;
12906 #ifdef HAVE_STDARG_H
12907 /* This dummy va_list is here because:
12908 * - passing a NULL pointer doesn't work when va_list isn't a pointer
12909 * - locally in the function results in a "used before set" warning
12910 * - using va_start() to initialize it gives "function with fixed args" error */
12911 static va_list ap;
12912 #endif
12915 * "printf()" function
12917 static void
12918 f_printf(argvars, rettv)
12919 typval_T *argvars;
12920 typval_T *rettv;
12922 rettv->v_type = VAR_STRING;
12923 rettv->vval.v_string = NULL;
12924 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
12926 char_u buf[NUMBUFLEN];
12927 int len;
12928 char_u *s;
12929 int saved_did_emsg = did_emsg;
12930 char *fmt;
12932 /* Get the required length, allocate the buffer and do it for real. */
12933 did_emsg = FALSE;
12934 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
12935 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
12936 if (!did_emsg)
12938 s = alloc(len + 1);
12939 if (s != NULL)
12941 rettv->vval.v_string = s;
12942 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
12945 did_emsg |= saved_did_emsg;
12947 #endif
12951 * "pumvisible()" function
12953 /*ARGSUSED*/
12954 static void
12955 f_pumvisible(argvars, rettv)
12956 typval_T *argvars;
12957 typval_T *rettv;
12959 rettv->vval.v_number = 0;
12960 #ifdef FEAT_INS_EXPAND
12961 if (pum_visible())
12962 rettv->vval.v_number = 1;
12963 #endif
12967 * "range()" function
12969 static void
12970 f_range(argvars, rettv)
12971 typval_T *argvars;
12972 typval_T *rettv;
12974 long start;
12975 long end;
12976 long stride = 1;
12977 long i;
12978 int error = FALSE;
12980 start = get_tv_number_chk(&argvars[0], &error);
12981 if (argvars[1].v_type == VAR_UNKNOWN)
12983 end = start - 1;
12984 start = 0;
12986 else
12988 end = get_tv_number_chk(&argvars[1], &error);
12989 if (argvars[2].v_type != VAR_UNKNOWN)
12990 stride = get_tv_number_chk(&argvars[2], &error);
12993 rettv->vval.v_number = 0;
12994 if (error)
12995 return; /* type error; errmsg already given */
12996 if (stride == 0)
12997 EMSG(_("E726: Stride is zero"));
12998 else if (stride > 0 ? end + 1 < start : end - 1 > start)
12999 EMSG(_("E727: Start past end"));
13000 else
13002 if (rettv_list_alloc(rettv) == OK)
13003 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
13004 if (list_append_number(rettv->vval.v_list,
13005 (varnumber_T)i) == FAIL)
13006 break;
13011 * "readfile()" function
13013 static void
13014 f_readfile(argvars, rettv)
13015 typval_T *argvars;
13016 typval_T *rettv;
13018 int binary = FALSE;
13019 char_u *fname;
13020 FILE *fd;
13021 listitem_T *li;
13022 #define FREAD_SIZE 200 /* optimized for text lines */
13023 char_u buf[FREAD_SIZE];
13024 int readlen; /* size of last fread() */
13025 int buflen; /* nr of valid chars in buf[] */
13026 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
13027 int tolist; /* first byte in buf[] still to be put in list */
13028 int chop; /* how many CR to chop off */
13029 char_u *prev = NULL; /* previously read bytes, if any */
13030 int prevlen = 0; /* length of "prev" if not NULL */
13031 char_u *s;
13032 int len;
13033 long maxline = MAXLNUM;
13034 long cnt = 0;
13036 if (argvars[1].v_type != VAR_UNKNOWN)
13038 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
13039 binary = TRUE;
13040 if (argvars[2].v_type != VAR_UNKNOWN)
13041 maxline = get_tv_number(&argvars[2]);
13044 if (rettv_list_alloc(rettv) == FAIL)
13045 return;
13047 /* Always open the file in binary mode, library functions have a mind of
13048 * their own about CR-LF conversion. */
13049 fname = get_tv_string(&argvars[0]);
13050 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
13052 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
13053 return;
13056 filtd = 0;
13057 while (cnt < maxline || maxline < 0)
13059 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
13060 buflen = filtd + readlen;
13061 tolist = 0;
13062 for ( ; filtd < buflen || readlen <= 0; ++filtd)
13064 if (buf[filtd] == '\n' || readlen <= 0)
13066 /* Only when in binary mode add an empty list item when the
13067 * last line ends in a '\n'. */
13068 if (!binary && readlen == 0 && filtd == 0)
13069 break;
13071 /* Found end-of-line or end-of-file: add a text line to the
13072 * list. */
13073 chop = 0;
13074 if (!binary)
13075 while (filtd - chop - 1 >= tolist
13076 && buf[filtd - chop - 1] == '\r')
13077 ++chop;
13078 len = filtd - tolist - chop;
13079 if (prev == NULL)
13080 s = vim_strnsave(buf + tolist, len);
13081 else
13083 s = alloc((unsigned)(prevlen + len + 1));
13084 if (s != NULL)
13086 mch_memmove(s, prev, prevlen);
13087 vim_free(prev);
13088 prev = NULL;
13089 mch_memmove(s + prevlen, buf + tolist, len);
13090 s[prevlen + len] = NUL;
13093 tolist = filtd + 1;
13095 li = listitem_alloc();
13096 if (li == NULL)
13098 vim_free(s);
13099 break;
13101 li->li_tv.v_type = VAR_STRING;
13102 li->li_tv.v_lock = 0;
13103 li->li_tv.vval.v_string = s;
13104 list_append(rettv->vval.v_list, li);
13106 if (++cnt >= maxline && maxline >= 0)
13107 break;
13108 if (readlen <= 0)
13109 break;
13111 else if (buf[filtd] == NUL)
13112 buf[filtd] = '\n';
13114 if (readlen <= 0)
13115 break;
13117 if (tolist == 0)
13119 /* "buf" is full, need to move text to an allocated buffer */
13120 if (prev == NULL)
13122 prev = vim_strnsave(buf, buflen);
13123 prevlen = buflen;
13125 else
13127 s = alloc((unsigned)(prevlen + buflen));
13128 if (s != NULL)
13130 mch_memmove(s, prev, prevlen);
13131 mch_memmove(s + prevlen, buf, buflen);
13132 vim_free(prev);
13133 prev = s;
13134 prevlen += buflen;
13137 filtd = 0;
13139 else
13141 mch_memmove(buf, buf + tolist, buflen - tolist);
13142 filtd -= tolist;
13147 * For a negative line count use only the lines at the end of the file,
13148 * free the rest.
13150 if (maxline < 0)
13151 while (cnt > -maxline)
13153 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
13154 --cnt;
13157 vim_free(prev);
13158 fclose(fd);
13161 #if defined(FEAT_RELTIME)
13162 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
13165 * Convert a List to proftime_T.
13166 * Return FAIL when there is something wrong.
13168 static int
13169 list2proftime(arg, tm)
13170 typval_T *arg;
13171 proftime_T *tm;
13173 long n1, n2;
13174 int error = FALSE;
13176 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
13177 || arg->vval.v_list->lv_len != 2)
13178 return FAIL;
13179 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
13180 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
13181 # ifdef WIN3264
13182 tm->HighPart = n1;
13183 tm->LowPart = n2;
13184 # else
13185 tm->tv_sec = n1;
13186 tm->tv_usec = n2;
13187 # endif
13188 return error ? FAIL : OK;
13190 #endif /* FEAT_RELTIME */
13193 * "reltime()" function
13195 static void
13196 f_reltime(argvars, rettv)
13197 typval_T *argvars;
13198 typval_T *rettv;
13200 #ifdef FEAT_RELTIME
13201 proftime_T res;
13202 proftime_T start;
13204 if (argvars[0].v_type == VAR_UNKNOWN)
13206 /* No arguments: get current time. */
13207 profile_start(&res);
13209 else if (argvars[1].v_type == VAR_UNKNOWN)
13211 if (list2proftime(&argvars[0], &res) == FAIL)
13212 return;
13213 profile_end(&res);
13215 else
13217 /* Two arguments: compute the difference. */
13218 if (list2proftime(&argvars[0], &start) == FAIL
13219 || list2proftime(&argvars[1], &res) == FAIL)
13220 return;
13221 profile_sub(&res, &start);
13224 if (rettv_list_alloc(rettv) == OK)
13226 long n1, n2;
13228 # ifdef WIN3264
13229 n1 = res.HighPart;
13230 n2 = res.LowPart;
13231 # else
13232 n1 = res.tv_sec;
13233 n2 = res.tv_usec;
13234 # endif
13235 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
13236 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
13238 #endif
13242 * "reltimestr()" function
13244 static void
13245 f_reltimestr(argvars, rettv)
13246 typval_T *argvars;
13247 typval_T *rettv;
13249 #ifdef FEAT_RELTIME
13250 proftime_T tm;
13251 #endif
13253 rettv->v_type = VAR_STRING;
13254 rettv->vval.v_string = NULL;
13255 #ifdef FEAT_RELTIME
13256 if (list2proftime(&argvars[0], &tm) == OK)
13257 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
13258 #endif
13261 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
13262 static void make_connection __ARGS((void));
13263 static int check_connection __ARGS((void));
13265 static void
13266 make_connection()
13268 if (X_DISPLAY == NULL
13269 # ifdef FEAT_GUI
13270 && !gui.in_use
13271 # endif
13274 x_force_connect = TRUE;
13275 setup_term_clip();
13276 x_force_connect = FALSE;
13280 static int
13281 check_connection()
13283 make_connection();
13284 if (X_DISPLAY == NULL)
13286 EMSG(_("E240: No connection to Vim server"));
13287 return FAIL;
13289 return OK;
13291 #endif
13293 #ifdef FEAT_CLIENTSERVER
13294 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
13296 static void
13297 remote_common(argvars, rettv, expr)
13298 typval_T *argvars;
13299 typval_T *rettv;
13300 int expr;
13302 char_u *server_name;
13303 char_u *keys;
13304 char_u *r = NULL;
13305 char_u buf[NUMBUFLEN];
13306 # ifdef WIN32
13307 HWND w;
13308 # else
13309 Window w;
13310 # endif
13312 if (check_restricted() || check_secure())
13313 return;
13315 # ifdef FEAT_X11
13316 if (check_connection() == FAIL)
13317 return;
13318 # endif
13320 server_name = get_tv_string_chk(&argvars[0]);
13321 if (server_name == NULL)
13322 return; /* type error; errmsg already given */
13323 keys = get_tv_string_buf(&argvars[1], buf);
13324 # ifdef WIN32
13325 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
13326 # else
13327 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
13328 < 0)
13329 # endif
13331 if (r != NULL)
13332 EMSG(r); /* sending worked but evaluation failed */
13333 else
13334 EMSG2(_("E241: Unable to send to %s"), server_name);
13335 return;
13338 rettv->vval.v_string = r;
13340 if (argvars[2].v_type != VAR_UNKNOWN)
13342 dictitem_T v;
13343 char_u str[30];
13344 char_u *idvar;
13346 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
13347 v.di_tv.v_type = VAR_STRING;
13348 v.di_tv.vval.v_string = vim_strsave(str);
13349 idvar = get_tv_string_chk(&argvars[2]);
13350 if (idvar != NULL)
13351 set_var(idvar, &v.di_tv, FALSE);
13352 vim_free(v.di_tv.vval.v_string);
13355 #endif
13358 * "remote_expr()" function
13360 /*ARGSUSED*/
13361 static void
13362 f_remote_expr(argvars, rettv)
13363 typval_T *argvars;
13364 typval_T *rettv;
13366 rettv->v_type = VAR_STRING;
13367 rettv->vval.v_string = NULL;
13368 #ifdef FEAT_CLIENTSERVER
13369 remote_common(argvars, rettv, TRUE);
13370 #endif
13374 * "remote_foreground()" function
13376 /*ARGSUSED*/
13377 static void
13378 f_remote_foreground(argvars, rettv)
13379 typval_T *argvars;
13380 typval_T *rettv;
13382 rettv->vval.v_number = 0;
13383 #ifdef FEAT_CLIENTSERVER
13384 # ifdef WIN32
13385 /* On Win32 it's done in this application. */
13387 char_u *server_name = get_tv_string_chk(&argvars[0]);
13389 if (server_name != NULL)
13390 serverForeground(server_name);
13392 # else
13393 /* Send a foreground() expression to the server. */
13394 argvars[1].v_type = VAR_STRING;
13395 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
13396 argvars[2].v_type = VAR_UNKNOWN;
13397 remote_common(argvars, rettv, TRUE);
13398 vim_free(argvars[1].vval.v_string);
13399 # endif
13400 #endif
13403 /*ARGSUSED*/
13404 static void
13405 f_remote_peek(argvars, rettv)
13406 typval_T *argvars;
13407 typval_T *rettv;
13409 #ifdef FEAT_CLIENTSERVER
13410 dictitem_T v;
13411 char_u *s = NULL;
13412 # ifdef WIN32
13413 long_u n = 0;
13414 # endif
13415 char_u *serverid;
13417 if (check_restricted() || check_secure())
13419 rettv->vval.v_number = -1;
13420 return;
13422 serverid = get_tv_string_chk(&argvars[0]);
13423 if (serverid == NULL)
13425 rettv->vval.v_number = -1;
13426 return; /* type error; errmsg already given */
13428 # ifdef WIN32
13429 sscanf(serverid, SCANF_HEX_LONG_U, &n);
13430 if (n == 0)
13431 rettv->vval.v_number = -1;
13432 else
13434 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
13435 rettv->vval.v_number = (s != NULL);
13437 # else
13438 rettv->vval.v_number = 0;
13439 if (check_connection() == FAIL)
13440 return;
13442 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
13443 serverStrToWin(serverid), &s);
13444 # endif
13446 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
13448 char_u *retvar;
13450 v.di_tv.v_type = VAR_STRING;
13451 v.di_tv.vval.v_string = vim_strsave(s);
13452 retvar = get_tv_string_chk(&argvars[1]);
13453 if (retvar != NULL)
13454 set_var(retvar, &v.di_tv, FALSE);
13455 vim_free(v.di_tv.vval.v_string);
13457 #else
13458 rettv->vval.v_number = -1;
13459 #endif
13462 /*ARGSUSED*/
13463 static void
13464 f_remote_read(argvars, rettv)
13465 typval_T *argvars;
13466 typval_T *rettv;
13468 char_u *r = NULL;
13470 #ifdef FEAT_CLIENTSERVER
13471 char_u *serverid = get_tv_string_chk(&argvars[0]);
13473 if (serverid != NULL && !check_restricted() && !check_secure())
13475 # ifdef WIN32
13476 /* The server's HWND is encoded in the 'id' parameter */
13477 long_u n = 0;
13479 sscanf(serverid, SCANF_HEX_LONG_U, &n);
13480 if (n != 0)
13481 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
13482 if (r == NULL)
13483 # else
13484 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
13485 serverStrToWin(serverid), &r, FALSE) < 0)
13486 # endif
13487 EMSG(_("E277: Unable to read a server reply"));
13489 #endif
13490 rettv->v_type = VAR_STRING;
13491 rettv->vval.v_string = r;
13495 * "remote_send()" function
13497 /*ARGSUSED*/
13498 static void
13499 f_remote_send(argvars, rettv)
13500 typval_T *argvars;
13501 typval_T *rettv;
13503 rettv->v_type = VAR_STRING;
13504 rettv->vval.v_string = NULL;
13505 #ifdef FEAT_CLIENTSERVER
13506 remote_common(argvars, rettv, FALSE);
13507 #endif
13511 * "remove()" function
13513 static void
13514 f_remove(argvars, rettv)
13515 typval_T *argvars;
13516 typval_T *rettv;
13518 list_T *l;
13519 listitem_T *item, *item2;
13520 listitem_T *li;
13521 long idx;
13522 long end;
13523 char_u *key;
13524 dict_T *d;
13525 dictitem_T *di;
13527 rettv->vval.v_number = 0;
13528 if (argvars[0].v_type == VAR_DICT)
13530 if (argvars[2].v_type != VAR_UNKNOWN)
13531 EMSG2(_(e_toomanyarg), "remove()");
13532 else if ((d = argvars[0].vval.v_dict) != NULL
13533 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
13535 key = get_tv_string_chk(&argvars[1]);
13536 if (key != NULL)
13538 di = dict_find(d, key, -1);
13539 if (di == NULL)
13540 EMSG2(_(e_dictkey), key);
13541 else
13543 *rettv = di->di_tv;
13544 init_tv(&di->di_tv);
13545 dictitem_remove(d, di);
13550 else if (argvars[0].v_type != VAR_LIST)
13551 EMSG2(_(e_listdictarg), "remove()");
13552 else if ((l = argvars[0].vval.v_list) != NULL
13553 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
13555 int error = FALSE;
13557 idx = get_tv_number_chk(&argvars[1], &error);
13558 if (error)
13559 ; /* type error: do nothing, errmsg already given */
13560 else if ((item = list_find(l, idx)) == NULL)
13561 EMSGN(_(e_listidx), idx);
13562 else
13564 if (argvars[2].v_type == VAR_UNKNOWN)
13566 /* Remove one item, return its value. */
13567 list_remove(l, item, item);
13568 *rettv = item->li_tv;
13569 vim_free(item);
13571 else
13573 /* Remove range of items, return list with values. */
13574 end = get_tv_number_chk(&argvars[2], &error);
13575 if (error)
13576 ; /* type error: do nothing */
13577 else if ((item2 = list_find(l, end)) == NULL)
13578 EMSGN(_(e_listidx), end);
13579 else
13581 int cnt = 0;
13583 for (li = item; li != NULL; li = li->li_next)
13585 ++cnt;
13586 if (li == item2)
13587 break;
13589 if (li == NULL) /* didn't find "item2" after "item" */
13590 EMSG(_(e_invrange));
13591 else
13593 list_remove(l, item, item2);
13594 if (rettv_list_alloc(rettv) == OK)
13596 l = rettv->vval.v_list;
13597 l->lv_first = item;
13598 l->lv_last = item2;
13599 item->li_prev = NULL;
13600 item2->li_next = NULL;
13601 l->lv_len = cnt;
13611 * "rename({from}, {to})" function
13613 static void
13614 f_rename(argvars, rettv)
13615 typval_T *argvars;
13616 typval_T *rettv;
13618 char_u buf[NUMBUFLEN];
13620 if (check_restricted() || check_secure())
13621 rettv->vval.v_number = -1;
13622 else
13623 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
13624 get_tv_string_buf(&argvars[1], buf));
13628 * "repeat()" function
13630 /*ARGSUSED*/
13631 static void
13632 f_repeat(argvars, rettv)
13633 typval_T *argvars;
13634 typval_T *rettv;
13636 char_u *p;
13637 int n;
13638 int slen;
13639 int len;
13640 char_u *r;
13641 int i;
13643 n = get_tv_number(&argvars[1]);
13644 if (argvars[0].v_type == VAR_LIST)
13646 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
13647 while (n-- > 0)
13648 if (list_extend(rettv->vval.v_list,
13649 argvars[0].vval.v_list, NULL) == FAIL)
13650 break;
13652 else
13654 p = get_tv_string(&argvars[0]);
13655 rettv->v_type = VAR_STRING;
13656 rettv->vval.v_string = NULL;
13658 slen = (int)STRLEN(p);
13659 len = slen * n;
13660 if (len <= 0)
13661 return;
13663 r = alloc(len + 1);
13664 if (r != NULL)
13666 for (i = 0; i < n; i++)
13667 mch_memmove(r + i * slen, p, (size_t)slen);
13668 r[len] = NUL;
13671 rettv->vval.v_string = r;
13676 * "resolve()" function
13678 static void
13679 f_resolve(argvars, rettv)
13680 typval_T *argvars;
13681 typval_T *rettv;
13683 char_u *p;
13685 p = get_tv_string(&argvars[0]);
13686 #ifdef FEAT_SHORTCUT
13688 char_u *v = NULL;
13690 v = mch_resolve_shortcut(p);
13691 if (v != NULL)
13692 rettv->vval.v_string = v;
13693 else
13694 rettv->vval.v_string = vim_strsave(p);
13696 #else
13697 # ifdef HAVE_READLINK
13699 char_u buf[MAXPATHL + 1];
13700 char_u *cpy;
13701 int len;
13702 char_u *remain = NULL;
13703 char_u *q;
13704 int is_relative_to_current = FALSE;
13705 int has_trailing_pathsep = FALSE;
13706 int limit = 100;
13708 p = vim_strsave(p);
13710 if (p[0] == '.' && (vim_ispathsep(p[1])
13711 || (p[1] == '.' && (vim_ispathsep(p[2])))))
13712 is_relative_to_current = TRUE;
13714 len = STRLEN(p);
13715 if (len > 0 && after_pathsep(p, p + len))
13716 has_trailing_pathsep = TRUE;
13718 q = getnextcomp(p);
13719 if (*q != NUL)
13721 /* Separate the first path component in "p", and keep the
13722 * remainder (beginning with the path separator). */
13723 remain = vim_strsave(q - 1);
13724 q[-1] = NUL;
13727 for (;;)
13729 for (;;)
13731 len = readlink((char *)p, (char *)buf, MAXPATHL);
13732 if (len <= 0)
13733 break;
13734 buf[len] = NUL;
13736 if (limit-- == 0)
13738 vim_free(p);
13739 vim_free(remain);
13740 EMSG(_("E655: Too many symbolic links (cycle?)"));
13741 rettv->vval.v_string = NULL;
13742 goto fail;
13745 /* Ensure that the result will have a trailing path separator
13746 * if the argument has one. */
13747 if (remain == NULL && has_trailing_pathsep)
13748 add_pathsep(buf);
13750 /* Separate the first path component in the link value and
13751 * concatenate the remainders. */
13752 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
13753 if (*q != NUL)
13755 if (remain == NULL)
13756 remain = vim_strsave(q - 1);
13757 else
13759 cpy = concat_str(q - 1, remain);
13760 if (cpy != NULL)
13762 vim_free(remain);
13763 remain = cpy;
13766 q[-1] = NUL;
13769 q = gettail(p);
13770 if (q > p && *q == NUL)
13772 /* Ignore trailing path separator. */
13773 q[-1] = NUL;
13774 q = gettail(p);
13776 if (q > p && !mch_isFullName(buf))
13778 /* symlink is relative to directory of argument */
13779 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
13780 if (cpy != NULL)
13782 STRCPY(cpy, p);
13783 STRCPY(gettail(cpy), buf);
13784 vim_free(p);
13785 p = cpy;
13788 else
13790 vim_free(p);
13791 p = vim_strsave(buf);
13795 if (remain == NULL)
13796 break;
13798 /* Append the first path component of "remain" to "p". */
13799 q = getnextcomp(remain + 1);
13800 len = q - remain - (*q != NUL);
13801 cpy = vim_strnsave(p, STRLEN(p) + len);
13802 if (cpy != NULL)
13804 STRNCAT(cpy, remain, len);
13805 vim_free(p);
13806 p = cpy;
13808 /* Shorten "remain". */
13809 if (*q != NUL)
13810 mch_memmove(remain, q - 1, STRLEN(q - 1) + 1);
13811 else
13813 vim_free(remain);
13814 remain = NULL;
13818 /* If the result is a relative path name, make it explicitly relative to
13819 * the current directory if and only if the argument had this form. */
13820 if (!vim_ispathsep(*p))
13822 if (is_relative_to_current
13823 && *p != NUL
13824 && !(p[0] == '.'
13825 && (p[1] == NUL
13826 || vim_ispathsep(p[1])
13827 || (p[1] == '.'
13828 && (p[2] == NUL
13829 || vim_ispathsep(p[2]))))))
13831 /* Prepend "./". */
13832 cpy = concat_str((char_u *)"./", p);
13833 if (cpy != NULL)
13835 vim_free(p);
13836 p = cpy;
13839 else if (!is_relative_to_current)
13841 /* Strip leading "./". */
13842 q = p;
13843 while (q[0] == '.' && vim_ispathsep(q[1]))
13844 q += 2;
13845 if (q > p)
13846 mch_memmove(p, p + 2, STRLEN(p + 2) + (size_t)1);
13850 /* Ensure that the result will have no trailing path separator
13851 * if the argument had none. But keep "/" or "//". */
13852 if (!has_trailing_pathsep)
13854 q = p + STRLEN(p);
13855 if (after_pathsep(p, q))
13856 *gettail_sep(p) = NUL;
13859 rettv->vval.v_string = p;
13861 # else
13862 rettv->vval.v_string = vim_strsave(p);
13863 # endif
13864 #endif
13866 simplify_filename(rettv->vval.v_string);
13868 #ifdef HAVE_READLINK
13869 fail:
13870 #endif
13871 rettv->v_type = VAR_STRING;
13875 * "reverse({list})" function
13877 static void
13878 f_reverse(argvars, rettv)
13879 typval_T *argvars;
13880 typval_T *rettv;
13882 list_T *l;
13883 listitem_T *li, *ni;
13885 rettv->vval.v_number = 0;
13886 if (argvars[0].v_type != VAR_LIST)
13887 EMSG2(_(e_listarg), "reverse()");
13888 else if ((l = argvars[0].vval.v_list) != NULL
13889 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
13891 li = l->lv_last;
13892 l->lv_first = l->lv_last = NULL;
13893 l->lv_len = 0;
13894 while (li != NULL)
13896 ni = li->li_prev;
13897 list_append(l, li);
13898 li = ni;
13900 rettv->vval.v_list = l;
13901 rettv->v_type = VAR_LIST;
13902 ++l->lv_refcount;
13906 #define SP_NOMOVE 0x01 /* don't move cursor */
13907 #define SP_REPEAT 0x02 /* repeat to find outer pair */
13908 #define SP_RETCOUNT 0x04 /* return matchcount */
13909 #define SP_SETPCMARK 0x08 /* set previous context mark */
13910 #define SP_START 0x10 /* accept match at start position */
13911 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
13912 #define SP_END 0x40 /* leave cursor at end of match */
13914 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
13917 * Get flags for a search function.
13918 * Possibly sets "p_ws".
13919 * Returns BACKWARD, FORWARD or zero (for an error).
13921 static int
13922 get_search_arg(varp, flagsp)
13923 typval_T *varp;
13924 int *flagsp;
13926 int dir = FORWARD;
13927 char_u *flags;
13928 char_u nbuf[NUMBUFLEN];
13929 int mask;
13931 if (varp->v_type != VAR_UNKNOWN)
13933 flags = get_tv_string_buf_chk(varp, nbuf);
13934 if (flags == NULL)
13935 return 0; /* type error; errmsg already given */
13936 while (*flags != NUL)
13938 switch (*flags)
13940 case 'b': dir = BACKWARD; break;
13941 case 'w': p_ws = TRUE; break;
13942 case 'W': p_ws = FALSE; break;
13943 default: mask = 0;
13944 if (flagsp != NULL)
13945 switch (*flags)
13947 case 'c': mask = SP_START; break;
13948 case 'e': mask = SP_END; break;
13949 case 'm': mask = SP_RETCOUNT; break;
13950 case 'n': mask = SP_NOMOVE; break;
13951 case 'p': mask = SP_SUBPAT; break;
13952 case 'r': mask = SP_REPEAT; break;
13953 case 's': mask = SP_SETPCMARK; break;
13955 if (mask == 0)
13957 EMSG2(_(e_invarg2), flags);
13958 dir = 0;
13960 else
13961 *flagsp |= mask;
13963 if (dir == 0)
13964 break;
13965 ++flags;
13968 return dir;
13972 * Shared by search() and searchpos() functions
13974 static int
13975 search_cmn(argvars, match_pos, flagsp)
13976 typval_T *argvars;
13977 pos_T *match_pos;
13978 int *flagsp;
13980 int flags;
13981 char_u *pat;
13982 pos_T pos;
13983 pos_T save_cursor;
13984 int save_p_ws = p_ws;
13985 int dir;
13986 int retval = 0; /* default: FAIL */
13987 long lnum_stop = 0;
13988 int options = SEARCH_KEEP;
13989 int subpatnum;
13991 pat = get_tv_string(&argvars[0]);
13992 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
13993 if (dir == 0)
13994 goto theend;
13995 flags = *flagsp;
13996 if (flags & SP_START)
13997 options |= SEARCH_START;
13998 if (flags & SP_END)
13999 options |= SEARCH_END;
14001 /* Optional extra argument: line number to stop searching. */
14002 if (argvars[1].v_type != VAR_UNKNOWN
14003 && argvars[2].v_type != VAR_UNKNOWN)
14005 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
14006 if (lnum_stop < 0)
14007 goto theend;
14011 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
14012 * Check to make sure only those flags are set.
14013 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
14014 * flags cannot be set. Check for that condition also.
14016 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
14017 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14019 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
14020 goto theend;
14023 pos = save_cursor = curwin->w_cursor;
14024 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14025 options, RE_SEARCH, (linenr_T)lnum_stop);
14026 if (subpatnum != FAIL)
14028 if (flags & SP_SUBPAT)
14029 retval = subpatnum;
14030 else
14031 retval = pos.lnum;
14032 if (flags & SP_SETPCMARK)
14033 setpcmark();
14034 curwin->w_cursor = pos;
14035 if (match_pos != NULL)
14037 /* Store the match cursor position */
14038 match_pos->lnum = pos.lnum;
14039 match_pos->col = pos.col + 1;
14041 /* "/$" will put the cursor after the end of the line, may need to
14042 * correct that here */
14043 check_cursor();
14046 /* If 'n' flag is used: restore cursor position. */
14047 if (flags & SP_NOMOVE)
14048 curwin->w_cursor = save_cursor;
14049 else
14050 curwin->w_set_curswant = TRUE;
14051 theend:
14052 p_ws = save_p_ws;
14054 return retval;
14058 * "search()" function
14060 static void
14061 f_search(argvars, rettv)
14062 typval_T *argvars;
14063 typval_T *rettv;
14065 int flags = 0;
14067 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
14071 * "searchdecl()" function
14073 static void
14074 f_searchdecl(argvars, rettv)
14075 typval_T *argvars;
14076 typval_T *rettv;
14078 int locally = 1;
14079 int thisblock = 0;
14080 int error = FALSE;
14081 char_u *name;
14083 rettv->vval.v_number = 1; /* default: FAIL */
14085 name = get_tv_string_chk(&argvars[0]);
14086 if (argvars[1].v_type != VAR_UNKNOWN)
14088 locally = get_tv_number_chk(&argvars[1], &error) == 0;
14089 if (!error && argvars[2].v_type != VAR_UNKNOWN)
14090 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
14092 if (!error && name != NULL)
14093 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
14094 locally, thisblock, SEARCH_KEEP) == FAIL;
14098 * Used by searchpair() and searchpairpos()
14100 static int
14101 searchpair_cmn(argvars, match_pos)
14102 typval_T *argvars;
14103 pos_T *match_pos;
14105 char_u *spat, *mpat, *epat;
14106 char_u *skip;
14107 int save_p_ws = p_ws;
14108 int dir;
14109 int flags = 0;
14110 char_u nbuf1[NUMBUFLEN];
14111 char_u nbuf2[NUMBUFLEN];
14112 char_u nbuf3[NUMBUFLEN];
14113 int retval = 0; /* default: FAIL */
14114 long lnum_stop = 0;
14116 /* Get the three pattern arguments: start, middle, end. */
14117 spat = get_tv_string_chk(&argvars[0]);
14118 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
14119 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
14120 if (spat == NULL || mpat == NULL || epat == NULL)
14121 goto theend; /* type error */
14123 /* Handle the optional fourth argument: flags */
14124 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
14125 if (dir == 0)
14126 goto theend;
14128 /* Don't accept SP_END or SP_SUBPAT.
14129 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
14131 if ((flags & (SP_END | SP_SUBPAT)) != 0
14132 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14134 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
14135 goto theend;
14138 /* Optional fifth argument: skip expression */
14139 if (argvars[3].v_type == VAR_UNKNOWN
14140 || argvars[4].v_type == VAR_UNKNOWN)
14141 skip = (char_u *)"";
14142 else
14144 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
14145 if (argvars[5].v_type != VAR_UNKNOWN)
14147 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
14148 if (lnum_stop < 0)
14149 goto theend;
14152 if (skip == NULL)
14153 goto theend; /* type error */
14155 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
14156 match_pos, lnum_stop);
14158 theend:
14159 p_ws = save_p_ws;
14161 return retval;
14165 * "searchpair()" function
14167 static void
14168 f_searchpair(argvars, rettv)
14169 typval_T *argvars;
14170 typval_T *rettv;
14172 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
14176 * "searchpairpos()" function
14178 static void
14179 f_searchpairpos(argvars, rettv)
14180 typval_T *argvars;
14181 typval_T *rettv;
14183 pos_T match_pos;
14184 int lnum = 0;
14185 int col = 0;
14187 rettv->vval.v_number = 0;
14189 if (rettv_list_alloc(rettv) == FAIL)
14190 return;
14192 if (searchpair_cmn(argvars, &match_pos) > 0)
14194 lnum = match_pos.lnum;
14195 col = match_pos.col;
14198 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14199 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14203 * Search for a start/middle/end thing.
14204 * Used by searchpair(), see its documentation for the details.
14205 * Returns 0 or -1 for no match,
14207 long
14208 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos, lnum_stop)
14209 char_u *spat; /* start pattern */
14210 char_u *mpat; /* middle pattern */
14211 char_u *epat; /* end pattern */
14212 int dir; /* BACKWARD or FORWARD */
14213 char_u *skip; /* skip expression */
14214 int flags; /* SP_SETPCMARK and other SP_ values */
14215 pos_T *match_pos;
14216 linenr_T lnum_stop; /* stop at this line if not zero */
14218 char_u *save_cpo;
14219 char_u *pat, *pat2 = NULL, *pat3 = NULL;
14220 long retval = 0;
14221 pos_T pos;
14222 pos_T firstpos;
14223 pos_T foundpos;
14224 pos_T save_cursor;
14225 pos_T save_pos;
14226 int n;
14227 int r;
14228 int nest = 1;
14229 int err;
14230 int options = SEARCH_KEEP;
14232 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
14233 save_cpo = p_cpo;
14234 p_cpo = (char_u *)"";
14236 /* Make two search patterns: start/end (pat2, for in nested pairs) and
14237 * start/middle/end (pat3, for the top pair). */
14238 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
14239 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
14240 if (pat2 == NULL || pat3 == NULL)
14241 goto theend;
14242 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
14243 if (*mpat == NUL)
14244 STRCPY(pat3, pat2);
14245 else
14246 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
14247 spat, epat, mpat);
14248 if (flags & SP_START)
14249 options |= SEARCH_START;
14251 save_cursor = curwin->w_cursor;
14252 pos = curwin->w_cursor;
14253 clearpos(&firstpos);
14254 clearpos(&foundpos);
14255 pat = pat3;
14256 for (;;)
14258 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14259 options, RE_SEARCH, lnum_stop);
14260 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
14261 /* didn't find it or found the first match again: FAIL */
14262 break;
14264 if (firstpos.lnum == 0)
14265 firstpos = pos;
14266 if (equalpos(pos, foundpos))
14268 /* Found the same position again. Can happen with a pattern that
14269 * has "\zs" at the end and searching backwards. Advance one
14270 * character and try again. */
14271 if (dir == BACKWARD)
14272 decl(&pos);
14273 else
14274 incl(&pos);
14276 foundpos = pos;
14278 /* If the skip pattern matches, ignore this match. */
14279 if (*skip != NUL)
14281 save_pos = curwin->w_cursor;
14282 curwin->w_cursor = pos;
14283 r = eval_to_bool(skip, &err, NULL, FALSE);
14284 curwin->w_cursor = save_pos;
14285 if (err)
14287 /* Evaluating {skip} caused an error, break here. */
14288 curwin->w_cursor = save_cursor;
14289 retval = -1;
14290 break;
14292 if (r)
14293 continue;
14296 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
14298 /* Found end when searching backwards or start when searching
14299 * forward: nested pair. */
14300 ++nest;
14301 pat = pat2; /* nested, don't search for middle */
14303 else
14305 /* Found end when searching forward or start when searching
14306 * backward: end of (nested) pair; or found middle in outer pair. */
14307 if (--nest == 1)
14308 pat = pat3; /* outer level, search for middle */
14311 if (nest == 0)
14313 /* Found the match: return matchcount or line number. */
14314 if (flags & SP_RETCOUNT)
14315 ++retval;
14316 else
14317 retval = pos.lnum;
14318 if (flags & SP_SETPCMARK)
14319 setpcmark();
14320 curwin->w_cursor = pos;
14321 if (!(flags & SP_REPEAT))
14322 break;
14323 nest = 1; /* search for next unmatched */
14327 if (match_pos != NULL)
14329 /* Store the match cursor position */
14330 match_pos->lnum = curwin->w_cursor.lnum;
14331 match_pos->col = curwin->w_cursor.col + 1;
14334 /* If 'n' flag is used or search failed: restore cursor position. */
14335 if ((flags & SP_NOMOVE) || retval == 0)
14336 curwin->w_cursor = save_cursor;
14338 theend:
14339 vim_free(pat2);
14340 vim_free(pat3);
14341 p_cpo = save_cpo;
14343 return retval;
14347 * "searchpos()" function
14349 static void
14350 f_searchpos(argvars, rettv)
14351 typval_T *argvars;
14352 typval_T *rettv;
14354 pos_T match_pos;
14355 int lnum = 0;
14356 int col = 0;
14357 int n;
14358 int flags = 0;
14360 rettv->vval.v_number = 0;
14362 if (rettv_list_alloc(rettv) == FAIL)
14363 return;
14365 n = search_cmn(argvars, &match_pos, &flags);
14366 if (n > 0)
14368 lnum = match_pos.lnum;
14369 col = match_pos.col;
14372 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14373 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14374 if (flags & SP_SUBPAT)
14375 list_append_number(rettv->vval.v_list, (varnumber_T)n);
14379 /*ARGSUSED*/
14380 static void
14381 f_server2client(argvars, rettv)
14382 typval_T *argvars;
14383 typval_T *rettv;
14385 #ifdef FEAT_CLIENTSERVER
14386 char_u buf[NUMBUFLEN];
14387 char_u *server = get_tv_string_chk(&argvars[0]);
14388 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
14390 rettv->vval.v_number = -1;
14391 if (server == NULL || reply == NULL)
14392 return;
14393 if (check_restricted() || check_secure())
14394 return;
14395 # ifdef FEAT_X11
14396 if (check_connection() == FAIL)
14397 return;
14398 # endif
14400 if (serverSendReply(server, reply) < 0)
14402 EMSG(_("E258: Unable to send to client"));
14403 return;
14405 rettv->vval.v_number = 0;
14406 #else
14407 rettv->vval.v_number = -1;
14408 #endif
14411 /*ARGSUSED*/
14412 static void
14413 f_serverlist(argvars, rettv)
14414 typval_T *argvars;
14415 typval_T *rettv;
14417 char_u *r = NULL;
14419 #ifdef FEAT_CLIENTSERVER
14420 # ifdef WIN32
14421 r = serverGetVimNames();
14422 # else
14423 make_connection();
14424 if (X_DISPLAY != NULL)
14425 r = serverGetVimNames(X_DISPLAY);
14426 # endif
14427 #endif
14428 rettv->v_type = VAR_STRING;
14429 rettv->vval.v_string = r;
14433 * "setbufvar()" function
14435 /*ARGSUSED*/
14436 static void
14437 f_setbufvar(argvars, rettv)
14438 typval_T *argvars;
14439 typval_T *rettv;
14441 buf_T *buf;
14442 aco_save_T aco;
14443 char_u *varname, *bufvarname;
14444 typval_T *varp;
14445 char_u nbuf[NUMBUFLEN];
14447 rettv->vval.v_number = 0;
14449 if (check_restricted() || check_secure())
14450 return;
14451 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
14452 varname = get_tv_string_chk(&argvars[1]);
14453 buf = get_buf_tv(&argvars[0]);
14454 varp = &argvars[2];
14456 if (buf != NULL && varname != NULL && varp != NULL)
14458 /* set curbuf to be our buf, temporarily */
14459 aucmd_prepbuf(&aco, buf);
14461 if (*varname == '&')
14463 long numval;
14464 char_u *strval;
14465 int error = FALSE;
14467 ++varname;
14468 numval = get_tv_number_chk(varp, &error);
14469 strval = get_tv_string_buf_chk(varp, nbuf);
14470 if (!error && strval != NULL)
14471 set_option_value(varname, numval, strval, OPT_LOCAL);
14473 else
14475 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
14476 if (bufvarname != NULL)
14478 STRCPY(bufvarname, "b:");
14479 STRCPY(bufvarname + 2, varname);
14480 set_var(bufvarname, varp, TRUE);
14481 vim_free(bufvarname);
14485 /* reset notion of buffer */
14486 aucmd_restbuf(&aco);
14491 * "setcmdpos()" function
14493 static void
14494 f_setcmdpos(argvars, rettv)
14495 typval_T *argvars;
14496 typval_T *rettv;
14498 int pos = (int)get_tv_number(&argvars[0]) - 1;
14500 if (pos >= 0)
14501 rettv->vval.v_number = set_cmdline_pos(pos);
14505 * "setline()" function
14507 static void
14508 f_setline(argvars, rettv)
14509 typval_T *argvars;
14510 typval_T *rettv;
14512 linenr_T lnum;
14513 char_u *line = NULL;
14514 list_T *l = NULL;
14515 listitem_T *li = NULL;
14516 long added = 0;
14517 linenr_T lcount = curbuf->b_ml.ml_line_count;
14519 lnum = get_tv_lnum(&argvars[0]);
14520 if (argvars[1].v_type == VAR_LIST)
14522 l = argvars[1].vval.v_list;
14523 li = l->lv_first;
14525 else
14526 line = get_tv_string_chk(&argvars[1]);
14528 rettv->vval.v_number = 0; /* OK */
14529 for (;;)
14531 if (l != NULL)
14533 /* list argument, get next string */
14534 if (li == NULL)
14535 break;
14536 line = get_tv_string_chk(&li->li_tv);
14537 li = li->li_next;
14540 rettv->vval.v_number = 1; /* FAIL */
14541 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
14542 break;
14543 if (lnum <= curbuf->b_ml.ml_line_count)
14545 /* existing line, replace it */
14546 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
14548 changed_bytes(lnum, 0);
14549 if (lnum == curwin->w_cursor.lnum)
14550 check_cursor_col();
14551 rettv->vval.v_number = 0; /* OK */
14554 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
14556 /* lnum is one past the last line, append the line */
14557 ++added;
14558 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
14559 rettv->vval.v_number = 0; /* OK */
14562 if (l == NULL) /* only one string argument */
14563 break;
14564 ++lnum;
14567 if (added > 0)
14568 appended_lines_mark(lcount, added);
14572 * Used by "setqflist()" and "setloclist()" functions
14574 /*ARGSUSED*/
14575 static void
14576 set_qf_ll_list(wp, list_arg, action_arg, rettv)
14577 win_T *wp;
14578 typval_T *list_arg;
14579 typval_T *action_arg;
14580 typval_T *rettv;
14582 #ifdef FEAT_QUICKFIX
14583 char_u *act;
14584 int action = ' ';
14585 #endif
14587 rettv->vval.v_number = -1;
14589 #ifdef FEAT_QUICKFIX
14590 if (list_arg->v_type != VAR_LIST)
14591 EMSG(_(e_listreq));
14592 else
14594 list_T *l = list_arg->vval.v_list;
14596 if (action_arg->v_type == VAR_STRING)
14598 act = get_tv_string_chk(action_arg);
14599 if (act == NULL)
14600 return; /* type error; errmsg already given */
14601 if (*act == 'a' || *act == 'r')
14602 action = *act;
14605 if (l != NULL && set_errorlist(wp, l, action) == OK)
14606 rettv->vval.v_number = 0;
14608 #endif
14612 * "setloclist()" function
14614 /*ARGSUSED*/
14615 static void
14616 f_setloclist(argvars, rettv)
14617 typval_T *argvars;
14618 typval_T *rettv;
14620 win_T *win;
14622 rettv->vval.v_number = -1;
14624 win = find_win_by_nr(&argvars[0], NULL);
14625 if (win != NULL)
14626 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
14630 * "setmatches()" function
14632 static void
14633 f_setmatches(argvars, rettv)
14634 typval_T *argvars;
14635 typval_T *rettv;
14637 #ifdef FEAT_SEARCH_EXTRA
14638 list_T *l;
14639 listitem_T *li;
14640 dict_T *d;
14642 rettv->vval.v_number = -1;
14643 if (argvars[0].v_type != VAR_LIST)
14645 EMSG(_(e_listreq));
14646 return;
14648 if ((l = argvars[0].vval.v_list) != NULL)
14651 /* To some extent make sure that we are dealing with a list from
14652 * "getmatches()". */
14653 li = l->lv_first;
14654 while (li != NULL)
14656 if (li->li_tv.v_type != VAR_DICT
14657 || (d = li->li_tv.vval.v_dict) == NULL)
14659 EMSG(_(e_invarg));
14660 return;
14662 if (!(dict_find(d, (char_u *)"group", -1) != NULL
14663 && dict_find(d, (char_u *)"pattern", -1) != NULL
14664 && dict_find(d, (char_u *)"priority", -1) != NULL
14665 && dict_find(d, (char_u *)"id", -1) != NULL))
14667 EMSG(_(e_invarg));
14668 return;
14670 li = li->li_next;
14673 clear_matches(curwin);
14674 li = l->lv_first;
14675 while (li != NULL)
14677 d = li->li_tv.vval.v_dict;
14678 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
14679 get_dict_string(d, (char_u *)"pattern", FALSE),
14680 (int)get_dict_number(d, (char_u *)"priority"),
14681 (int)get_dict_number(d, (char_u *)"id"));
14682 li = li->li_next;
14684 rettv->vval.v_number = 0;
14686 #endif
14690 * "setpos()" function
14692 /*ARGSUSED*/
14693 static void
14694 f_setpos(argvars, rettv)
14695 typval_T *argvars;
14696 typval_T *rettv;
14698 pos_T pos;
14699 int fnum;
14700 char_u *name;
14702 name = get_tv_string_chk(argvars);
14703 if (name != NULL)
14705 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
14707 --pos.col;
14708 if (name[0] == '.') /* cursor */
14710 if (fnum == curbuf->b_fnum)
14712 curwin->w_cursor = pos;
14713 check_cursor();
14715 else
14716 EMSG(_(e_invarg));
14718 else if (name[0] == '\'') /* mark */
14719 (void)setmark_pos(name[1], &pos, fnum);
14720 else
14721 EMSG(_(e_invarg));
14727 * "setqflist()" function
14729 /*ARGSUSED*/
14730 static void
14731 f_setqflist(argvars, rettv)
14732 typval_T *argvars;
14733 typval_T *rettv;
14735 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
14739 * "setreg()" function
14741 static void
14742 f_setreg(argvars, rettv)
14743 typval_T *argvars;
14744 typval_T *rettv;
14746 int regname;
14747 char_u *strregname;
14748 char_u *stropt;
14749 char_u *strval;
14750 int append;
14751 char_u yank_type;
14752 long block_len;
14754 block_len = -1;
14755 yank_type = MAUTO;
14756 append = FALSE;
14758 strregname = get_tv_string_chk(argvars);
14759 rettv->vval.v_number = 1; /* FAIL is default */
14761 if (strregname == NULL)
14762 return; /* type error; errmsg already given */
14763 regname = *strregname;
14764 if (regname == 0 || regname == '@')
14765 regname = '"';
14766 else if (regname == '=')
14767 return;
14769 if (argvars[2].v_type != VAR_UNKNOWN)
14771 stropt = get_tv_string_chk(&argvars[2]);
14772 if (stropt == NULL)
14773 return; /* type error */
14774 for (; *stropt != NUL; ++stropt)
14775 switch (*stropt)
14777 case 'a': case 'A': /* append */
14778 append = TRUE;
14779 break;
14780 case 'v': case 'c': /* character-wise selection */
14781 yank_type = MCHAR;
14782 break;
14783 case 'V': case 'l': /* line-wise selection */
14784 yank_type = MLINE;
14785 break;
14786 #ifdef FEAT_VISUAL
14787 case 'b': case Ctrl_V: /* block-wise selection */
14788 yank_type = MBLOCK;
14789 if (VIM_ISDIGIT(stropt[1]))
14791 ++stropt;
14792 block_len = getdigits(&stropt) - 1;
14793 --stropt;
14795 break;
14796 #endif
14800 strval = get_tv_string_chk(&argvars[1]);
14801 if (strval != NULL)
14802 write_reg_contents_ex(regname, strval, -1,
14803 append, yank_type, block_len);
14804 rettv->vval.v_number = 0;
14808 * "settabwinvar()" function
14810 static void
14811 f_settabwinvar(argvars, rettv)
14812 typval_T *argvars;
14813 typval_T *rettv;
14815 setwinvar(argvars, rettv, 1);
14819 * "setwinvar()" function
14821 static void
14822 f_setwinvar(argvars, rettv)
14823 typval_T *argvars;
14824 typval_T *rettv;
14826 setwinvar(argvars, rettv, 0);
14830 * "setwinvar()" and "settabwinvar()" functions
14832 static void
14833 setwinvar(argvars, rettv, off)
14834 typval_T *argvars;
14835 typval_T *rettv;
14836 int off;
14838 win_T *win;
14839 #ifdef FEAT_WINDOWS
14840 win_T *save_curwin;
14841 tabpage_T *save_curtab;
14842 #endif
14843 char_u *varname, *winvarname;
14844 typval_T *varp;
14845 char_u nbuf[NUMBUFLEN];
14846 tabpage_T *tp;
14848 rettv->vval.v_number = 0;
14850 if (check_restricted() || check_secure())
14851 return;
14853 #ifdef FEAT_WINDOWS
14854 if (off == 1)
14855 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
14856 else
14857 tp = curtab;
14858 #endif
14859 win = find_win_by_nr(&argvars[off], tp);
14860 varname = get_tv_string_chk(&argvars[off + 1]);
14861 varp = &argvars[off + 2];
14863 if (win != NULL && varname != NULL && varp != NULL)
14865 #ifdef FEAT_WINDOWS
14866 /* set curwin to be our win, temporarily */
14867 save_curwin = curwin;
14868 save_curtab = curtab;
14869 goto_tabpage_tp(tp);
14870 if (!win_valid(win))
14871 return;
14872 curwin = win;
14873 curbuf = curwin->w_buffer;
14874 #endif
14876 if (*varname == '&')
14878 long numval;
14879 char_u *strval;
14880 int error = FALSE;
14882 ++varname;
14883 numval = get_tv_number_chk(varp, &error);
14884 strval = get_tv_string_buf_chk(varp, nbuf);
14885 if (!error && strval != NULL)
14886 set_option_value(varname, numval, strval, OPT_LOCAL);
14888 else
14890 winvarname = alloc((unsigned)STRLEN(varname) + 3);
14891 if (winvarname != NULL)
14893 STRCPY(winvarname, "w:");
14894 STRCPY(winvarname + 2, varname);
14895 set_var(winvarname, varp, TRUE);
14896 vim_free(winvarname);
14900 #ifdef FEAT_WINDOWS
14901 /* Restore current tabpage and window, if still valid (autocomands can
14902 * make them invalid). */
14903 if (valid_tabpage(save_curtab))
14904 goto_tabpage_tp(save_curtab);
14905 if (win_valid(save_curwin))
14907 curwin = save_curwin;
14908 curbuf = curwin->w_buffer;
14910 #endif
14915 * "shellescape({string})" function
14917 static void
14918 f_shellescape(argvars, rettv)
14919 typval_T *argvars;
14920 typval_T *rettv;
14922 rettv->vval.v_string = vim_strsave_shellescape(get_tv_string(&argvars[0]));
14923 rettv->v_type = VAR_STRING;
14927 * "simplify()" function
14929 static void
14930 f_simplify(argvars, rettv)
14931 typval_T *argvars;
14932 typval_T *rettv;
14934 char_u *p;
14936 p = get_tv_string(&argvars[0]);
14937 rettv->vval.v_string = vim_strsave(p);
14938 simplify_filename(rettv->vval.v_string); /* simplify in place */
14939 rettv->v_type = VAR_STRING;
14942 static int
14943 #ifdef __BORLANDC__
14944 _RTLENTRYF
14945 #endif
14946 item_compare __ARGS((const void *s1, const void *s2));
14947 static int
14948 #ifdef __BORLANDC__
14949 _RTLENTRYF
14950 #endif
14951 item_compare2 __ARGS((const void *s1, const void *s2));
14953 static int item_compare_ic;
14954 static char_u *item_compare_func;
14955 static int item_compare_func_err;
14956 #define ITEM_COMPARE_FAIL 999
14959 * Compare functions for f_sort() below.
14961 static int
14962 #ifdef __BORLANDC__
14963 _RTLENTRYF
14964 #endif
14965 item_compare(s1, s2)
14966 const void *s1;
14967 const void *s2;
14969 char_u *p1, *p2;
14970 char_u *tofree1, *tofree2;
14971 int res;
14972 char_u numbuf1[NUMBUFLEN];
14973 char_u numbuf2[NUMBUFLEN];
14975 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
14976 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
14977 if (p1 == NULL)
14978 p1 = (char_u *)"";
14979 if (p2 == NULL)
14980 p2 = (char_u *)"";
14981 if (item_compare_ic)
14982 res = STRICMP(p1, p2);
14983 else
14984 res = STRCMP(p1, p2);
14985 vim_free(tofree1);
14986 vim_free(tofree2);
14987 return res;
14990 static int
14991 #ifdef __BORLANDC__
14992 _RTLENTRYF
14993 #endif
14994 item_compare2(s1, s2)
14995 const void *s1;
14996 const void *s2;
14998 int res;
14999 typval_T rettv;
15000 typval_T argv[3];
15001 int dummy;
15003 /* shortcut after failure in previous call; compare all items equal */
15004 if (item_compare_func_err)
15005 return 0;
15007 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
15008 * in the copy without changing the original list items. */
15009 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
15010 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
15012 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
15013 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
15014 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
15015 clear_tv(&argv[0]);
15016 clear_tv(&argv[1]);
15018 if (res == FAIL)
15019 res = ITEM_COMPARE_FAIL;
15020 else
15021 /* return value has wrong type */
15022 res = get_tv_number_chk(&rettv, &item_compare_func_err);
15023 if (item_compare_func_err)
15024 res = ITEM_COMPARE_FAIL;
15025 clear_tv(&rettv);
15026 return res;
15030 * "sort({list})" function
15032 static void
15033 f_sort(argvars, rettv)
15034 typval_T *argvars;
15035 typval_T *rettv;
15037 list_T *l;
15038 listitem_T *li;
15039 listitem_T **ptrs;
15040 long len;
15041 long i;
15043 rettv->vval.v_number = 0;
15044 if (argvars[0].v_type != VAR_LIST)
15045 EMSG2(_(e_listarg), "sort()");
15046 else
15048 l = argvars[0].vval.v_list;
15049 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
15050 return;
15051 rettv->vval.v_list = l;
15052 rettv->v_type = VAR_LIST;
15053 ++l->lv_refcount;
15055 len = list_len(l);
15056 if (len <= 1)
15057 return; /* short list sorts pretty quickly */
15059 item_compare_ic = FALSE;
15060 item_compare_func = NULL;
15061 if (argvars[1].v_type != VAR_UNKNOWN)
15063 if (argvars[1].v_type == VAR_FUNC)
15064 item_compare_func = argvars[1].vval.v_string;
15065 else
15067 int error = FALSE;
15069 i = get_tv_number_chk(&argvars[1], &error);
15070 if (error)
15071 return; /* type error; errmsg already given */
15072 if (i == 1)
15073 item_compare_ic = TRUE;
15074 else
15075 item_compare_func = get_tv_string(&argvars[1]);
15079 /* Make an array with each entry pointing to an item in the List. */
15080 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
15081 if (ptrs == NULL)
15082 return;
15083 i = 0;
15084 for (li = l->lv_first; li != NULL; li = li->li_next)
15085 ptrs[i++] = li;
15087 item_compare_func_err = FALSE;
15088 /* test the compare function */
15089 if (item_compare_func != NULL
15090 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
15091 == ITEM_COMPARE_FAIL)
15092 EMSG(_("E702: Sort compare function failed"));
15093 else
15095 /* Sort the array with item pointers. */
15096 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
15097 item_compare_func == NULL ? item_compare : item_compare2);
15099 if (!item_compare_func_err)
15101 /* Clear the List and append the items in the sorted order. */
15102 l->lv_first = l->lv_last = NULL;
15103 l->lv_len = 0;
15104 for (i = 0; i < len; ++i)
15105 list_append(l, ptrs[i]);
15109 vim_free(ptrs);
15114 * "soundfold({word})" function
15116 static void
15117 f_soundfold(argvars, rettv)
15118 typval_T *argvars;
15119 typval_T *rettv;
15121 char_u *s;
15123 rettv->v_type = VAR_STRING;
15124 s = get_tv_string(&argvars[0]);
15125 #ifdef FEAT_SPELL
15126 rettv->vval.v_string = eval_soundfold(s);
15127 #else
15128 rettv->vval.v_string = vim_strsave(s);
15129 #endif
15133 * "spellbadword()" function
15135 /* ARGSUSED */
15136 static void
15137 f_spellbadword(argvars, rettv)
15138 typval_T *argvars;
15139 typval_T *rettv;
15141 char_u *word = (char_u *)"";
15142 hlf_T attr = HLF_COUNT;
15143 int len = 0;
15145 if (rettv_list_alloc(rettv) == FAIL)
15146 return;
15148 #ifdef FEAT_SPELL
15149 if (argvars[0].v_type == VAR_UNKNOWN)
15151 /* Find the start and length of the badly spelled word. */
15152 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
15153 if (len != 0)
15154 word = ml_get_cursor();
15156 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15158 char_u *str = get_tv_string_chk(&argvars[0]);
15159 int capcol = -1;
15161 if (str != NULL)
15163 /* Check the argument for spelling. */
15164 while (*str != NUL)
15166 len = spell_check(curwin, str, &attr, &capcol, FALSE);
15167 if (attr != HLF_COUNT)
15169 word = str;
15170 break;
15172 str += len;
15176 #endif
15178 list_append_string(rettv->vval.v_list, word, len);
15179 list_append_string(rettv->vval.v_list, (char_u *)(
15180 attr == HLF_SPB ? "bad" :
15181 attr == HLF_SPR ? "rare" :
15182 attr == HLF_SPL ? "local" :
15183 attr == HLF_SPC ? "caps" :
15184 ""), -1);
15188 * "spellsuggest()" function
15190 /*ARGSUSED*/
15191 static void
15192 f_spellsuggest(argvars, rettv)
15193 typval_T *argvars;
15194 typval_T *rettv;
15196 #ifdef FEAT_SPELL
15197 char_u *str;
15198 int typeerr = FALSE;
15199 int maxcount;
15200 garray_T ga;
15201 int i;
15202 listitem_T *li;
15203 int need_capital = FALSE;
15204 #endif
15206 if (rettv_list_alloc(rettv) == FAIL)
15207 return;
15209 #ifdef FEAT_SPELL
15210 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15212 str = get_tv_string(&argvars[0]);
15213 if (argvars[1].v_type != VAR_UNKNOWN)
15215 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
15216 if (maxcount <= 0)
15217 return;
15218 if (argvars[2].v_type != VAR_UNKNOWN)
15220 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
15221 if (typeerr)
15222 return;
15225 else
15226 maxcount = 25;
15228 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
15230 for (i = 0; i < ga.ga_len; ++i)
15232 str = ((char_u **)ga.ga_data)[i];
15234 li = listitem_alloc();
15235 if (li == NULL)
15236 vim_free(str);
15237 else
15239 li->li_tv.v_type = VAR_STRING;
15240 li->li_tv.v_lock = 0;
15241 li->li_tv.vval.v_string = str;
15242 list_append(rettv->vval.v_list, li);
15245 ga_clear(&ga);
15247 #endif
15250 static void
15251 f_split(argvars, rettv)
15252 typval_T *argvars;
15253 typval_T *rettv;
15255 char_u *str;
15256 char_u *end;
15257 char_u *pat = NULL;
15258 regmatch_T regmatch;
15259 char_u patbuf[NUMBUFLEN];
15260 char_u *save_cpo;
15261 int match;
15262 colnr_T col = 0;
15263 int keepempty = FALSE;
15264 int typeerr = FALSE;
15266 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15267 save_cpo = p_cpo;
15268 p_cpo = (char_u *)"";
15270 str = get_tv_string(&argvars[0]);
15271 if (argvars[1].v_type != VAR_UNKNOWN)
15273 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
15274 if (pat == NULL)
15275 typeerr = TRUE;
15276 if (argvars[2].v_type != VAR_UNKNOWN)
15277 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
15279 if (pat == NULL || *pat == NUL)
15280 pat = (char_u *)"[\\x01- ]\\+";
15282 if (rettv_list_alloc(rettv) == FAIL)
15283 return;
15284 if (typeerr)
15285 return;
15287 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
15288 if (regmatch.regprog != NULL)
15290 regmatch.rm_ic = FALSE;
15291 while (*str != NUL || keepempty)
15293 if (*str == NUL)
15294 match = FALSE; /* empty item at the end */
15295 else
15296 match = vim_regexec_nl(&regmatch, str, col);
15297 if (match)
15298 end = regmatch.startp[0];
15299 else
15300 end = str + STRLEN(str);
15301 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
15302 && *str != NUL && match && end < regmatch.endp[0]))
15304 if (list_append_string(rettv->vval.v_list, str,
15305 (int)(end - str)) == FAIL)
15306 break;
15308 if (!match)
15309 break;
15310 /* Advance to just after the match. */
15311 if (regmatch.endp[0] > str)
15312 col = 0;
15313 else
15315 /* Don't get stuck at the same match. */
15316 #ifdef FEAT_MBYTE
15317 col = (*mb_ptr2len)(regmatch.endp[0]);
15318 #else
15319 col = 1;
15320 #endif
15322 str = regmatch.endp[0];
15325 vim_free(regmatch.regprog);
15328 p_cpo = save_cpo;
15332 * "str2nr()" function
15334 static void
15335 f_str2nr(argvars, rettv)
15336 typval_T *argvars;
15337 typval_T *rettv;
15339 int base = 10;
15340 char_u *p;
15341 long n;
15343 if (argvars[1].v_type != VAR_UNKNOWN)
15345 base = get_tv_number(&argvars[1]);
15346 if (base != 8 && base != 10 && base != 16)
15348 EMSG(_(e_invarg));
15349 return;
15353 p = skipwhite(get_tv_string(&argvars[0]));
15354 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
15355 rettv->vval.v_number = n;
15358 #ifdef HAVE_STRFTIME
15360 * "strftime({format}[, {time}])" function
15362 static void
15363 f_strftime(argvars, rettv)
15364 typval_T *argvars;
15365 typval_T *rettv;
15367 char_u result_buf[256];
15368 struct tm *curtime;
15369 time_t seconds;
15370 char_u *p;
15372 rettv->v_type = VAR_STRING;
15374 p = get_tv_string(&argvars[0]);
15375 if (argvars[1].v_type == VAR_UNKNOWN)
15376 seconds = time(NULL);
15377 else
15378 seconds = (time_t)get_tv_number(&argvars[1]);
15379 curtime = localtime(&seconds);
15380 /* MSVC returns NULL for an invalid value of seconds. */
15381 if (curtime == NULL)
15382 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
15383 else
15385 # ifdef FEAT_MBYTE
15386 vimconv_T conv;
15387 char_u *enc;
15389 conv.vc_type = CONV_NONE;
15390 enc = enc_locale();
15391 convert_setup(&conv, p_enc, enc);
15392 if (conv.vc_type != CONV_NONE)
15393 p = string_convert(&conv, p, NULL);
15394 # endif
15395 if (p != NULL)
15396 (void)strftime((char *)result_buf, sizeof(result_buf),
15397 (char *)p, curtime);
15398 else
15399 result_buf[0] = NUL;
15401 # ifdef FEAT_MBYTE
15402 if (conv.vc_type != CONV_NONE)
15403 vim_free(p);
15404 convert_setup(&conv, enc, p_enc);
15405 if (conv.vc_type != CONV_NONE)
15406 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
15407 else
15408 # endif
15409 rettv->vval.v_string = vim_strsave(result_buf);
15411 # ifdef FEAT_MBYTE
15412 /* Release conversion descriptors */
15413 convert_setup(&conv, NULL, NULL);
15414 vim_free(enc);
15415 # endif
15418 #endif
15421 * "stridx()" function
15423 static void
15424 f_stridx(argvars, rettv)
15425 typval_T *argvars;
15426 typval_T *rettv;
15428 char_u buf[NUMBUFLEN];
15429 char_u *needle;
15430 char_u *haystack;
15431 char_u *save_haystack;
15432 char_u *pos;
15433 int start_idx;
15435 needle = get_tv_string_chk(&argvars[1]);
15436 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
15437 rettv->vval.v_number = -1;
15438 if (needle == NULL || haystack == NULL)
15439 return; /* type error; errmsg already given */
15441 if (argvars[2].v_type != VAR_UNKNOWN)
15443 int error = FALSE;
15445 start_idx = get_tv_number_chk(&argvars[2], &error);
15446 if (error || start_idx >= (int)STRLEN(haystack))
15447 return;
15448 if (start_idx >= 0)
15449 haystack += start_idx;
15452 pos = (char_u *)strstr((char *)haystack, (char *)needle);
15453 if (pos != NULL)
15454 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
15458 * "string()" function
15460 static void
15461 f_string(argvars, rettv)
15462 typval_T *argvars;
15463 typval_T *rettv;
15465 char_u *tofree;
15466 char_u numbuf[NUMBUFLEN];
15468 rettv->v_type = VAR_STRING;
15469 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
15470 /* Make a copy if we have a value but it's not in allocate memory. */
15471 if (rettv->vval.v_string != NULL && tofree == NULL)
15472 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
15476 * "strlen()" function
15478 static void
15479 f_strlen(argvars, rettv)
15480 typval_T *argvars;
15481 typval_T *rettv;
15483 rettv->vval.v_number = (varnumber_T)(STRLEN(
15484 get_tv_string(&argvars[0])));
15488 * "strpart()" function
15490 static void
15491 f_strpart(argvars, rettv)
15492 typval_T *argvars;
15493 typval_T *rettv;
15495 char_u *p;
15496 int n;
15497 int len;
15498 int slen;
15499 int error = FALSE;
15501 p = get_tv_string(&argvars[0]);
15502 slen = (int)STRLEN(p);
15504 n = get_tv_number_chk(&argvars[1], &error);
15505 if (error)
15506 len = 0;
15507 else if (argvars[2].v_type != VAR_UNKNOWN)
15508 len = get_tv_number(&argvars[2]);
15509 else
15510 len = slen - n; /* default len: all bytes that are available. */
15513 * Only return the overlap between the specified part and the actual
15514 * string.
15516 if (n < 0)
15518 len += n;
15519 n = 0;
15521 else if (n > slen)
15522 n = slen;
15523 if (len < 0)
15524 len = 0;
15525 else if (n + len > slen)
15526 len = slen - n;
15528 rettv->v_type = VAR_STRING;
15529 rettv->vval.v_string = vim_strnsave(p + n, len);
15533 * "strridx()" function
15535 static void
15536 f_strridx(argvars, rettv)
15537 typval_T *argvars;
15538 typval_T *rettv;
15540 char_u buf[NUMBUFLEN];
15541 char_u *needle;
15542 char_u *haystack;
15543 char_u *rest;
15544 char_u *lastmatch = NULL;
15545 int haystack_len, end_idx;
15547 needle = get_tv_string_chk(&argvars[1]);
15548 haystack = get_tv_string_buf_chk(&argvars[0], buf);
15550 rettv->vval.v_number = -1;
15551 if (needle == NULL || haystack == NULL)
15552 return; /* type error; errmsg already given */
15554 haystack_len = (int)STRLEN(haystack);
15555 if (argvars[2].v_type != VAR_UNKNOWN)
15557 /* Third argument: upper limit for index */
15558 end_idx = get_tv_number_chk(&argvars[2], NULL);
15559 if (end_idx < 0)
15560 return; /* can never find a match */
15562 else
15563 end_idx = haystack_len;
15565 if (*needle == NUL)
15567 /* Empty string matches past the end. */
15568 lastmatch = haystack + end_idx;
15570 else
15572 for (rest = haystack; *rest != '\0'; ++rest)
15574 rest = (char_u *)strstr((char *)rest, (char *)needle);
15575 if (rest == NULL || rest > haystack + end_idx)
15576 break;
15577 lastmatch = rest;
15581 if (lastmatch == NULL)
15582 rettv->vval.v_number = -1;
15583 else
15584 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
15588 * "strtrans()" function
15590 static void
15591 f_strtrans(argvars, rettv)
15592 typval_T *argvars;
15593 typval_T *rettv;
15595 rettv->v_type = VAR_STRING;
15596 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
15600 * "submatch()" function
15602 static void
15603 f_submatch(argvars, rettv)
15604 typval_T *argvars;
15605 typval_T *rettv;
15607 rettv->v_type = VAR_STRING;
15608 rettv->vval.v_string =
15609 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
15613 * "substitute()" function
15615 static void
15616 f_substitute(argvars, rettv)
15617 typval_T *argvars;
15618 typval_T *rettv;
15620 char_u patbuf[NUMBUFLEN];
15621 char_u subbuf[NUMBUFLEN];
15622 char_u flagsbuf[NUMBUFLEN];
15624 char_u *str = get_tv_string_chk(&argvars[0]);
15625 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
15626 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
15627 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
15629 rettv->v_type = VAR_STRING;
15630 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
15631 rettv->vval.v_string = NULL;
15632 else
15633 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
15637 * "synID(lnum, col, trans)" function
15639 /*ARGSUSED*/
15640 static void
15641 f_synID(argvars, rettv)
15642 typval_T *argvars;
15643 typval_T *rettv;
15645 int id = 0;
15646 #ifdef FEAT_SYN_HL
15647 long lnum;
15648 long col;
15649 int trans;
15650 int transerr = FALSE;
15652 lnum = get_tv_lnum(argvars); /* -1 on type error */
15653 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
15654 trans = get_tv_number_chk(&argvars[2], &transerr);
15656 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
15657 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
15658 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL);
15659 #endif
15661 rettv->vval.v_number = id;
15665 * "synIDattr(id, what [, mode])" function
15667 /*ARGSUSED*/
15668 static void
15669 f_synIDattr(argvars, rettv)
15670 typval_T *argvars;
15671 typval_T *rettv;
15673 char_u *p = NULL;
15674 #ifdef FEAT_SYN_HL
15675 int id;
15676 char_u *what;
15677 char_u *mode;
15678 char_u modebuf[NUMBUFLEN];
15679 int modec;
15681 id = get_tv_number(&argvars[0]);
15682 what = get_tv_string(&argvars[1]);
15683 if (argvars[2].v_type != VAR_UNKNOWN)
15685 mode = get_tv_string_buf(&argvars[2], modebuf);
15686 modec = TOLOWER_ASC(mode[0]);
15687 if (modec != 't' && modec != 'c'
15688 #ifdef FEAT_GUI
15689 && modec != 'g'
15690 #endif
15692 modec = 0; /* replace invalid with current */
15694 else
15696 #ifdef FEAT_GUI
15697 if (gui.in_use)
15698 modec = 'g';
15699 else
15700 #endif
15701 if (t_colors > 1)
15702 modec = 'c';
15703 else
15704 modec = 't';
15708 switch (TOLOWER_ASC(what[0]))
15710 case 'b':
15711 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
15712 p = highlight_color(id, what, modec);
15713 else /* bold */
15714 p = highlight_has_attr(id, HL_BOLD, modec);
15715 break;
15717 case 'f': /* fg[#] */
15718 p = highlight_color(id, what, modec);
15719 break;
15721 case 'i':
15722 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
15723 p = highlight_has_attr(id, HL_INVERSE, modec);
15724 else /* italic */
15725 p = highlight_has_attr(id, HL_ITALIC, modec);
15726 break;
15728 case 'n': /* name */
15729 p = get_highlight_name(NULL, id - 1);
15730 break;
15732 case 'r': /* reverse */
15733 p = highlight_has_attr(id, HL_INVERSE, modec);
15734 break;
15736 case 's': /* standout */
15737 p = highlight_has_attr(id, HL_STANDOUT, modec);
15738 break;
15740 case 'u':
15741 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
15742 /* underline */
15743 p = highlight_has_attr(id, HL_UNDERLINE, modec);
15744 else
15745 /* undercurl */
15746 p = highlight_has_attr(id, HL_UNDERCURL, modec);
15747 break;
15750 if (p != NULL)
15751 p = vim_strsave(p);
15752 #endif
15753 rettv->v_type = VAR_STRING;
15754 rettv->vval.v_string = p;
15758 * "synIDtrans(id)" function
15760 /*ARGSUSED*/
15761 static void
15762 f_synIDtrans(argvars, rettv)
15763 typval_T *argvars;
15764 typval_T *rettv;
15766 int id;
15768 #ifdef FEAT_SYN_HL
15769 id = get_tv_number(&argvars[0]);
15771 if (id > 0)
15772 id = syn_get_final_id(id);
15773 else
15774 #endif
15775 id = 0;
15777 rettv->vval.v_number = id;
15781 * "system()" function
15783 static void
15784 f_system(argvars, rettv)
15785 typval_T *argvars;
15786 typval_T *rettv;
15788 char_u *res = NULL;
15789 char_u *p;
15790 char_u *infile = NULL;
15791 char_u buf[NUMBUFLEN];
15792 int err = FALSE;
15793 FILE *fd;
15795 if (check_restricted() || check_secure())
15796 return;
15798 if (argvars[1].v_type != VAR_UNKNOWN)
15801 * Write the string to a temp file, to be used for input of the shell
15802 * command.
15804 if ((infile = vim_tempname('i')) == NULL)
15806 EMSG(_(e_notmp));
15807 return;
15810 fd = mch_fopen((char *)infile, WRITEBIN);
15811 if (fd == NULL)
15813 EMSG2(_(e_notopen), infile);
15814 goto done;
15816 p = get_tv_string_buf_chk(&argvars[1], buf);
15817 if (p == NULL)
15819 fclose(fd);
15820 goto done; /* type error; errmsg already given */
15822 if (fwrite(p, STRLEN(p), 1, fd) != 1)
15823 err = TRUE;
15824 if (fclose(fd) != 0)
15825 err = TRUE;
15826 if (err)
15828 EMSG(_("E677: Error writing temp file"));
15829 goto done;
15833 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
15834 SHELL_SILENT | SHELL_COOKED);
15836 #ifdef USE_CR
15837 /* translate <CR> into <NL> */
15838 if (res != NULL)
15840 char_u *s;
15842 for (s = res; *s; ++s)
15844 if (*s == CAR)
15845 *s = NL;
15848 #else
15849 # ifdef USE_CRNL
15850 /* translate <CR><NL> into <NL> */
15851 if (res != NULL)
15853 char_u *s, *d;
15855 d = res;
15856 for (s = res; *s; ++s)
15858 if (s[0] == CAR && s[1] == NL)
15859 ++s;
15860 *d++ = *s;
15862 *d = NUL;
15864 # endif
15865 #endif
15867 done:
15868 if (infile != NULL)
15870 mch_remove(infile);
15871 vim_free(infile);
15873 rettv->v_type = VAR_STRING;
15874 rettv->vval.v_string = res;
15878 * "tabpagebuflist()" function
15880 /* ARGSUSED */
15881 static void
15882 f_tabpagebuflist(argvars, rettv)
15883 typval_T *argvars;
15884 typval_T *rettv;
15886 #ifndef FEAT_WINDOWS
15887 rettv->vval.v_number = 0;
15888 #else
15889 tabpage_T *tp;
15890 win_T *wp = NULL;
15892 if (argvars[0].v_type == VAR_UNKNOWN)
15893 wp = firstwin;
15894 else
15896 tp = find_tabpage((int)get_tv_number(&argvars[0]));
15897 if (tp != NULL)
15898 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
15900 if (wp == NULL)
15901 rettv->vval.v_number = 0;
15902 else
15904 if (rettv_list_alloc(rettv) == FAIL)
15905 rettv->vval.v_number = 0;
15906 else
15908 for (; wp != NULL; wp = wp->w_next)
15909 if (list_append_number(rettv->vval.v_list,
15910 wp->w_buffer->b_fnum) == FAIL)
15911 break;
15914 #endif
15919 * "tabpagenr()" function
15921 /* ARGSUSED */
15922 static void
15923 f_tabpagenr(argvars, rettv)
15924 typval_T *argvars;
15925 typval_T *rettv;
15927 int nr = 1;
15928 #ifdef FEAT_WINDOWS
15929 char_u *arg;
15931 if (argvars[0].v_type != VAR_UNKNOWN)
15933 arg = get_tv_string_chk(&argvars[0]);
15934 nr = 0;
15935 if (arg != NULL)
15937 if (STRCMP(arg, "$") == 0)
15938 nr = tabpage_index(NULL) - 1;
15939 else
15940 EMSG2(_(e_invexpr2), arg);
15943 else
15944 nr = tabpage_index(curtab);
15945 #endif
15946 rettv->vval.v_number = nr;
15950 #ifdef FEAT_WINDOWS
15951 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
15954 * Common code for tabpagewinnr() and winnr().
15956 static int
15957 get_winnr(tp, argvar)
15958 tabpage_T *tp;
15959 typval_T *argvar;
15961 win_T *twin;
15962 int nr = 1;
15963 win_T *wp;
15964 char_u *arg;
15966 twin = (tp == curtab) ? curwin : tp->tp_curwin;
15967 if (argvar->v_type != VAR_UNKNOWN)
15969 arg = get_tv_string_chk(argvar);
15970 if (arg == NULL)
15971 nr = 0; /* type error; errmsg already given */
15972 else if (STRCMP(arg, "$") == 0)
15973 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
15974 else if (STRCMP(arg, "#") == 0)
15976 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
15977 if (twin == NULL)
15978 nr = 0;
15980 else
15982 EMSG2(_(e_invexpr2), arg);
15983 nr = 0;
15987 if (nr > 0)
15988 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
15989 wp != twin; wp = wp->w_next)
15991 if (wp == NULL)
15993 /* didn't find it in this tabpage */
15994 nr = 0;
15995 break;
15997 ++nr;
15999 return nr;
16001 #endif
16004 * "tabpagewinnr()" function
16006 /* ARGSUSED */
16007 static void
16008 f_tabpagewinnr(argvars, rettv)
16009 typval_T *argvars;
16010 typval_T *rettv;
16012 int nr = 1;
16013 #ifdef FEAT_WINDOWS
16014 tabpage_T *tp;
16016 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16017 if (tp == NULL)
16018 nr = 0;
16019 else
16020 nr = get_winnr(tp, &argvars[1]);
16021 #endif
16022 rettv->vval.v_number = nr;
16027 * "tagfiles()" function
16029 /*ARGSUSED*/
16030 static void
16031 f_tagfiles(argvars, rettv)
16032 typval_T *argvars;
16033 typval_T *rettv;
16035 char_u fname[MAXPATHL + 1];
16036 tagname_T tn;
16037 int first;
16039 if (rettv_list_alloc(rettv) == FAIL)
16041 rettv->vval.v_number = 0;
16042 return;
16045 for (first = TRUE; ; first = FALSE)
16046 if (get_tagfname(&tn, first, fname) == FAIL
16047 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
16048 break;
16049 tagname_free(&tn);
16053 * "taglist()" function
16055 static void
16056 f_taglist(argvars, rettv)
16057 typval_T *argvars;
16058 typval_T *rettv;
16060 char_u *tag_pattern;
16062 tag_pattern = get_tv_string(&argvars[0]);
16064 rettv->vval.v_number = FALSE;
16065 if (*tag_pattern == NUL)
16066 return;
16068 if (rettv_list_alloc(rettv) == OK)
16069 (void)get_tags(rettv->vval.v_list, tag_pattern);
16073 * "tempname()" function
16075 /*ARGSUSED*/
16076 static void
16077 f_tempname(argvars, rettv)
16078 typval_T *argvars;
16079 typval_T *rettv;
16081 static int x = 'A';
16083 rettv->v_type = VAR_STRING;
16084 rettv->vval.v_string = vim_tempname(x);
16086 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
16087 * names. Skip 'I' and 'O', they are used for shell redirection. */
16090 if (x == 'Z')
16091 x = '0';
16092 else if (x == '9')
16093 x = 'A';
16094 else
16096 #ifdef EBCDIC
16097 if (x == 'I')
16098 x = 'J';
16099 else if (x == 'R')
16100 x = 'S';
16101 else
16102 #endif
16103 ++x;
16105 } while (x == 'I' || x == 'O');
16109 * "test(list)" function: Just checking the walls...
16111 /*ARGSUSED*/
16112 static void
16113 f_test(argvars, rettv)
16114 typval_T *argvars;
16115 typval_T *rettv;
16117 /* Used for unit testing. Change the code below to your liking. */
16118 #if 0
16119 listitem_T *li;
16120 list_T *l;
16121 char_u *bad, *good;
16123 if (argvars[0].v_type != VAR_LIST)
16124 return;
16125 l = argvars[0].vval.v_list;
16126 if (l == NULL)
16127 return;
16128 li = l->lv_first;
16129 if (li == NULL)
16130 return;
16131 bad = get_tv_string(&li->li_tv);
16132 li = li->li_next;
16133 if (li == NULL)
16134 return;
16135 good = get_tv_string(&li->li_tv);
16136 rettv->vval.v_number = test_edit_score(bad, good);
16137 #endif
16141 * "tolower(string)" function
16143 static void
16144 f_tolower(argvars, rettv)
16145 typval_T *argvars;
16146 typval_T *rettv;
16148 char_u *p;
16150 p = vim_strsave(get_tv_string(&argvars[0]));
16151 rettv->v_type = VAR_STRING;
16152 rettv->vval.v_string = p;
16154 if (p != NULL)
16155 while (*p != NUL)
16157 #ifdef FEAT_MBYTE
16158 int l;
16160 if (enc_utf8)
16162 int c, lc;
16164 c = utf_ptr2char(p);
16165 lc = utf_tolower(c);
16166 l = utf_ptr2len(p);
16167 /* TODO: reallocate string when byte count changes. */
16168 if (utf_char2len(lc) == l)
16169 utf_char2bytes(lc, p);
16170 p += l;
16172 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
16173 p += l; /* skip multi-byte character */
16174 else
16175 #endif
16177 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
16178 ++p;
16184 * "toupper(string)" function
16186 static void
16187 f_toupper(argvars, rettv)
16188 typval_T *argvars;
16189 typval_T *rettv;
16191 rettv->v_type = VAR_STRING;
16192 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
16196 * "tr(string, fromstr, tostr)" function
16198 static void
16199 f_tr(argvars, rettv)
16200 typval_T *argvars;
16201 typval_T *rettv;
16203 char_u *instr;
16204 char_u *fromstr;
16205 char_u *tostr;
16206 char_u *p;
16207 #ifdef FEAT_MBYTE
16208 int inlen;
16209 int fromlen;
16210 int tolen;
16211 int idx;
16212 char_u *cpstr;
16213 int cplen;
16214 int first = TRUE;
16215 #endif
16216 char_u buf[NUMBUFLEN];
16217 char_u buf2[NUMBUFLEN];
16218 garray_T ga;
16220 instr = get_tv_string(&argvars[0]);
16221 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
16222 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
16224 /* Default return value: empty string. */
16225 rettv->v_type = VAR_STRING;
16226 rettv->vval.v_string = NULL;
16227 if (fromstr == NULL || tostr == NULL)
16228 return; /* type error; errmsg already given */
16229 ga_init2(&ga, (int)sizeof(char), 80);
16231 #ifdef FEAT_MBYTE
16232 if (!has_mbyte)
16233 #endif
16234 /* not multi-byte: fromstr and tostr must be the same length */
16235 if (STRLEN(fromstr) != STRLEN(tostr))
16237 #ifdef FEAT_MBYTE
16238 error:
16239 #endif
16240 EMSG2(_(e_invarg2), fromstr);
16241 ga_clear(&ga);
16242 return;
16245 /* fromstr and tostr have to contain the same number of chars */
16246 while (*instr != NUL)
16248 #ifdef FEAT_MBYTE
16249 if (has_mbyte)
16251 inlen = (*mb_ptr2len)(instr);
16252 cpstr = instr;
16253 cplen = inlen;
16254 idx = 0;
16255 for (p = fromstr; *p != NUL; p += fromlen)
16257 fromlen = (*mb_ptr2len)(p);
16258 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
16260 for (p = tostr; *p != NUL; p += tolen)
16262 tolen = (*mb_ptr2len)(p);
16263 if (idx-- == 0)
16265 cplen = tolen;
16266 cpstr = p;
16267 break;
16270 if (*p == NUL) /* tostr is shorter than fromstr */
16271 goto error;
16272 break;
16274 ++idx;
16277 if (first && cpstr == instr)
16279 /* Check that fromstr and tostr have the same number of
16280 * (multi-byte) characters. Done only once when a character
16281 * of instr doesn't appear in fromstr. */
16282 first = FALSE;
16283 for (p = tostr; *p != NUL; p += tolen)
16285 tolen = (*mb_ptr2len)(p);
16286 --idx;
16288 if (idx != 0)
16289 goto error;
16292 ga_grow(&ga, cplen);
16293 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
16294 ga.ga_len += cplen;
16296 instr += inlen;
16298 else
16299 #endif
16301 /* When not using multi-byte chars we can do it faster. */
16302 p = vim_strchr(fromstr, *instr);
16303 if (p != NULL)
16304 ga_append(&ga, tostr[p - fromstr]);
16305 else
16306 ga_append(&ga, *instr);
16307 ++instr;
16311 /* add a terminating NUL */
16312 ga_grow(&ga, 1);
16313 ga_append(&ga, NUL);
16315 rettv->vval.v_string = ga.ga_data;
16319 * "type(expr)" function
16321 static void
16322 f_type(argvars, rettv)
16323 typval_T *argvars;
16324 typval_T *rettv;
16326 int n;
16328 switch (argvars[0].v_type)
16330 case VAR_NUMBER: n = 0; break;
16331 case VAR_STRING: n = 1; break;
16332 case VAR_FUNC: n = 2; break;
16333 case VAR_LIST: n = 3; break;
16334 case VAR_DICT: n = 4; break;
16335 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
16337 rettv->vval.v_number = n;
16341 * "values(dict)" function
16343 static void
16344 f_values(argvars, rettv)
16345 typval_T *argvars;
16346 typval_T *rettv;
16348 dict_list(argvars, rettv, 1);
16352 * "virtcol(string)" function
16354 static void
16355 f_virtcol(argvars, rettv)
16356 typval_T *argvars;
16357 typval_T *rettv;
16359 colnr_T vcol = 0;
16360 pos_T *fp;
16361 int fnum = curbuf->b_fnum;
16363 fp = var2fpos(&argvars[0], FALSE, &fnum);
16364 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
16365 && fnum == curbuf->b_fnum)
16367 getvvcol(curwin, fp, NULL, NULL, &vcol);
16368 ++vcol;
16371 rettv->vval.v_number = vcol;
16375 * "visualmode()" function
16377 /*ARGSUSED*/
16378 static void
16379 f_visualmode(argvars, rettv)
16380 typval_T *argvars;
16381 typval_T *rettv;
16383 #ifdef FEAT_VISUAL
16384 char_u str[2];
16386 rettv->v_type = VAR_STRING;
16387 str[0] = curbuf->b_visual_mode_eval;
16388 str[1] = NUL;
16389 rettv->vval.v_string = vim_strsave(str);
16391 /* A non-zero number or non-empty string argument: reset mode. */
16392 if ((argvars[0].v_type == VAR_NUMBER
16393 && argvars[0].vval.v_number != 0)
16394 || (argvars[0].v_type == VAR_STRING
16395 && *get_tv_string(&argvars[0]) != NUL))
16396 curbuf->b_visual_mode_eval = NUL;
16397 #else
16398 rettv->vval.v_number = 0; /* return anything, it won't work anyway */
16399 #endif
16403 * "winbufnr(nr)" function
16405 static void
16406 f_winbufnr(argvars, rettv)
16407 typval_T *argvars;
16408 typval_T *rettv;
16410 win_T *wp;
16412 wp = find_win_by_nr(&argvars[0], NULL);
16413 if (wp == NULL)
16414 rettv->vval.v_number = -1;
16415 else
16416 rettv->vval.v_number = wp->w_buffer->b_fnum;
16420 * "wincol()" function
16422 /*ARGSUSED*/
16423 static void
16424 f_wincol(argvars, rettv)
16425 typval_T *argvars;
16426 typval_T *rettv;
16428 validate_cursor();
16429 rettv->vval.v_number = curwin->w_wcol + 1;
16433 * "winheight(nr)" function
16435 static void
16436 f_winheight(argvars, rettv)
16437 typval_T *argvars;
16438 typval_T *rettv;
16440 win_T *wp;
16442 wp = find_win_by_nr(&argvars[0], NULL);
16443 if (wp == NULL)
16444 rettv->vval.v_number = -1;
16445 else
16446 rettv->vval.v_number = wp->w_height;
16450 * "winline()" function
16452 /*ARGSUSED*/
16453 static void
16454 f_winline(argvars, rettv)
16455 typval_T *argvars;
16456 typval_T *rettv;
16458 validate_cursor();
16459 rettv->vval.v_number = curwin->w_wrow + 1;
16463 * "winnr()" function
16465 /* ARGSUSED */
16466 static void
16467 f_winnr(argvars, rettv)
16468 typval_T *argvars;
16469 typval_T *rettv;
16471 int nr = 1;
16473 #ifdef FEAT_WINDOWS
16474 nr = get_winnr(curtab, &argvars[0]);
16475 #endif
16476 rettv->vval.v_number = nr;
16480 * "winrestcmd()" function
16482 /* ARGSUSED */
16483 static void
16484 f_winrestcmd(argvars, rettv)
16485 typval_T *argvars;
16486 typval_T *rettv;
16488 #ifdef FEAT_WINDOWS
16489 win_T *wp;
16490 int winnr = 1;
16491 garray_T ga;
16492 char_u buf[50];
16494 ga_init2(&ga, (int)sizeof(char), 70);
16495 for (wp = firstwin; wp != NULL; wp = wp->w_next)
16497 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
16498 ga_concat(&ga, buf);
16499 # ifdef FEAT_VERTSPLIT
16500 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
16501 ga_concat(&ga, buf);
16502 # endif
16503 ++winnr;
16505 ga_append(&ga, NUL);
16507 rettv->vval.v_string = ga.ga_data;
16508 #else
16509 rettv->vval.v_string = NULL;
16510 #endif
16511 rettv->v_type = VAR_STRING;
16515 * "winrestview()" function
16517 /* ARGSUSED */
16518 static void
16519 f_winrestview(argvars, rettv)
16520 typval_T *argvars;
16521 typval_T *rettv;
16523 dict_T *dict;
16525 if (argvars[0].v_type != VAR_DICT
16526 || (dict = argvars[0].vval.v_dict) == NULL)
16527 EMSG(_(e_invarg));
16528 else
16530 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
16531 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
16532 #ifdef FEAT_VIRTUALEDIT
16533 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
16534 #endif
16535 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
16536 curwin->w_set_curswant = FALSE;
16538 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
16539 #ifdef FEAT_DIFF
16540 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
16541 #endif
16542 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
16543 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
16545 check_cursor();
16546 changed_cline_bef_curs();
16547 invalidate_botline();
16548 redraw_later(VALID);
16550 if (curwin->w_topline == 0)
16551 curwin->w_topline = 1;
16552 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
16553 curwin->w_topline = curbuf->b_ml.ml_line_count;
16554 #ifdef FEAT_DIFF
16555 check_topfill(curwin, TRUE);
16556 #endif
16561 * "winsaveview()" function
16563 /* ARGSUSED */
16564 static void
16565 f_winsaveview(argvars, rettv)
16566 typval_T *argvars;
16567 typval_T *rettv;
16569 dict_T *dict;
16571 dict = dict_alloc();
16572 if (dict == NULL)
16573 return;
16574 rettv->v_type = VAR_DICT;
16575 rettv->vval.v_dict = dict;
16576 ++dict->dv_refcount;
16578 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
16579 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
16580 #ifdef FEAT_VIRTUALEDIT
16581 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
16582 #endif
16583 update_curswant();
16584 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
16586 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
16587 #ifdef FEAT_DIFF
16588 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
16589 #endif
16590 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
16591 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
16595 * "winwidth(nr)" function
16597 static void
16598 f_winwidth(argvars, rettv)
16599 typval_T *argvars;
16600 typval_T *rettv;
16602 win_T *wp;
16604 wp = find_win_by_nr(&argvars[0], NULL);
16605 if (wp == NULL)
16606 rettv->vval.v_number = -1;
16607 else
16608 #ifdef FEAT_VERTSPLIT
16609 rettv->vval.v_number = wp->w_width;
16610 #else
16611 rettv->vval.v_number = Columns;
16612 #endif
16616 * "writefile()" function
16618 static void
16619 f_writefile(argvars, rettv)
16620 typval_T *argvars;
16621 typval_T *rettv;
16623 int binary = FALSE;
16624 char_u *fname;
16625 FILE *fd;
16626 listitem_T *li;
16627 char_u *s;
16628 int ret = 0;
16629 int c;
16631 if (check_restricted() || check_secure())
16632 return;
16634 if (argvars[0].v_type != VAR_LIST)
16636 EMSG2(_(e_listarg), "writefile()");
16637 return;
16639 if (argvars[0].vval.v_list == NULL)
16640 return;
16642 if (argvars[2].v_type != VAR_UNKNOWN
16643 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
16644 binary = TRUE;
16646 /* Always open the file in binary mode, library functions have a mind of
16647 * their own about CR-LF conversion. */
16648 fname = get_tv_string(&argvars[1]);
16649 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
16651 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
16652 ret = -1;
16654 else
16656 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
16657 li = li->li_next)
16659 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
16661 if (*s == '\n')
16662 c = putc(NUL, fd);
16663 else
16664 c = putc(*s, fd);
16665 if (c == EOF)
16667 ret = -1;
16668 break;
16671 if (!binary || li->li_next != NULL)
16672 if (putc('\n', fd) == EOF)
16674 ret = -1;
16675 break;
16677 if (ret < 0)
16679 EMSG(_(e_write));
16680 break;
16683 fclose(fd);
16686 rettv->vval.v_number = ret;
16690 * Translate a String variable into a position.
16691 * Returns NULL when there is an error.
16693 static pos_T *
16694 var2fpos(varp, dollar_lnum, fnum)
16695 typval_T *varp;
16696 int dollar_lnum; /* TRUE when $ is last line */
16697 int *fnum; /* set to fnum for '0, 'A, etc. */
16699 char_u *name;
16700 static pos_T pos;
16701 pos_T *pp;
16703 /* Argument can be [lnum, col, coladd]. */
16704 if (varp->v_type == VAR_LIST)
16706 list_T *l;
16707 int len;
16708 int error = FALSE;
16709 listitem_T *li;
16711 l = varp->vval.v_list;
16712 if (l == NULL)
16713 return NULL;
16715 /* Get the line number */
16716 pos.lnum = list_find_nr(l, 0L, &error);
16717 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
16718 return NULL; /* invalid line number */
16720 /* Get the column number */
16721 pos.col = list_find_nr(l, 1L, &error);
16722 if (error)
16723 return NULL;
16724 len = (long)STRLEN(ml_get(pos.lnum));
16726 /* We accept "$" for the column number: last column. */
16727 li = list_find(l, 1L);
16728 if (li != NULL && li->li_tv.v_type == VAR_STRING
16729 && li->li_tv.vval.v_string != NULL
16730 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
16731 pos.col = len + 1;
16733 /* Accept a position up to the NUL after the line. */
16734 if (pos.col == 0 || (int)pos.col > len + 1)
16735 return NULL; /* invalid column number */
16736 --pos.col;
16738 #ifdef FEAT_VIRTUALEDIT
16739 /* Get the virtual offset. Defaults to zero. */
16740 pos.coladd = list_find_nr(l, 2L, &error);
16741 if (error)
16742 pos.coladd = 0;
16743 #endif
16745 return &pos;
16748 name = get_tv_string_chk(varp);
16749 if (name == NULL)
16750 return NULL;
16751 if (name[0] == '.') /* cursor */
16752 return &curwin->w_cursor;
16753 if (name[0] == '\'') /* mark */
16755 pp = getmark_fnum(name[1], FALSE, fnum);
16756 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
16757 return NULL;
16758 return pp;
16761 #ifdef FEAT_VIRTUALEDIT
16762 pos.coladd = 0;
16763 #endif
16765 if (name[0] == 'w' && dollar_lnum)
16767 pos.col = 0;
16768 if (name[1] == '0') /* "w0": first visible line */
16770 update_topline();
16771 pos.lnum = curwin->w_topline;
16772 return &pos;
16774 else if (name[1] == '$') /* "w$": last visible line */
16776 validate_botline();
16777 pos.lnum = curwin->w_botline - 1;
16778 return &pos;
16781 else if (name[0] == '$') /* last column or line */
16783 if (dollar_lnum)
16785 pos.lnum = curbuf->b_ml.ml_line_count;
16786 pos.col = 0;
16788 else
16790 pos.lnum = curwin->w_cursor.lnum;
16791 pos.col = (colnr_T)STRLEN(ml_get_curline());
16793 return &pos;
16795 return NULL;
16799 * Convert list in "arg" into a position and optional file number.
16800 * When "fnump" is NULL there is no file number, only 3 items.
16801 * Note that the column is passed on as-is, the caller may want to decrement
16802 * it to use 1 for the first column.
16803 * Return FAIL when conversion is not possible, doesn't check the position for
16804 * validity.
16806 static int
16807 list2fpos(arg, posp, fnump)
16808 typval_T *arg;
16809 pos_T *posp;
16810 int *fnump;
16812 list_T *l = arg->vval.v_list;
16813 long i = 0;
16814 long n;
16816 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
16817 * when "fnump" isn't NULL and "coladd" is optional. */
16818 if (arg->v_type != VAR_LIST
16819 || l == NULL
16820 || l->lv_len < (fnump == NULL ? 2 : 3)
16821 || l->lv_len > (fnump == NULL ? 3 : 4))
16822 return FAIL;
16824 if (fnump != NULL)
16826 n = list_find_nr(l, i++, NULL); /* fnum */
16827 if (n < 0)
16828 return FAIL;
16829 if (n == 0)
16830 n = curbuf->b_fnum; /* current buffer */
16831 *fnump = n;
16834 n = list_find_nr(l, i++, NULL); /* lnum */
16835 if (n < 0)
16836 return FAIL;
16837 posp->lnum = n;
16839 n = list_find_nr(l, i++, NULL); /* col */
16840 if (n < 0)
16841 return FAIL;
16842 posp->col = n;
16844 #ifdef FEAT_VIRTUALEDIT
16845 n = list_find_nr(l, i, NULL);
16846 if (n < 0)
16847 posp->coladd = 0;
16848 else
16849 posp->coladd = n;
16850 #endif
16852 return OK;
16856 * Get the length of an environment variable name.
16857 * Advance "arg" to the first character after the name.
16858 * Return 0 for error.
16860 static int
16861 get_env_len(arg)
16862 char_u **arg;
16864 char_u *p;
16865 int len;
16867 for (p = *arg; vim_isIDc(*p); ++p)
16869 if (p == *arg) /* no name found */
16870 return 0;
16872 len = (int)(p - *arg);
16873 *arg = p;
16874 return len;
16878 * Get the length of the name of a function or internal variable.
16879 * "arg" is advanced to the first non-white character after the name.
16880 * Return 0 if something is wrong.
16882 static int
16883 get_id_len(arg)
16884 char_u **arg;
16886 char_u *p;
16887 int len;
16889 /* Find the end of the name. */
16890 for (p = *arg; eval_isnamec(*p); ++p)
16892 if (p == *arg) /* no name found */
16893 return 0;
16895 len = (int)(p - *arg);
16896 *arg = skipwhite(p);
16898 return len;
16902 * Get the length of the name of a variable or function.
16903 * Only the name is recognized, does not handle ".key" or "[idx]".
16904 * "arg" is advanced to the first non-white character after the name.
16905 * Return -1 if curly braces expansion failed.
16906 * Return 0 if something else is wrong.
16907 * If the name contains 'magic' {}'s, expand them and return the
16908 * expanded name in an allocated string via 'alias' - caller must free.
16910 static int
16911 get_name_len(arg, alias, evaluate, verbose)
16912 char_u **arg;
16913 char_u **alias;
16914 int evaluate;
16915 int verbose;
16917 int len;
16918 char_u *p;
16919 char_u *expr_start;
16920 char_u *expr_end;
16922 *alias = NULL; /* default to no alias */
16924 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
16925 && (*arg)[2] == (int)KE_SNR)
16927 /* hard coded <SNR>, already translated */
16928 *arg += 3;
16929 return get_id_len(arg) + 3;
16931 len = eval_fname_script(*arg);
16932 if (len > 0)
16934 /* literal "<SID>", "s:" or "<SNR>" */
16935 *arg += len;
16939 * Find the end of the name; check for {} construction.
16941 p = find_name_end(*arg, &expr_start, &expr_end,
16942 len > 0 ? 0 : FNE_CHECK_START);
16943 if (expr_start != NULL)
16945 char_u *temp_string;
16947 if (!evaluate)
16949 len += (int)(p - *arg);
16950 *arg = skipwhite(p);
16951 return len;
16955 * Include any <SID> etc in the expanded string:
16956 * Thus the -len here.
16958 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
16959 if (temp_string == NULL)
16960 return -1;
16961 *alias = temp_string;
16962 *arg = skipwhite(p);
16963 return (int)STRLEN(temp_string);
16966 len += get_id_len(arg);
16967 if (len == 0 && verbose)
16968 EMSG2(_(e_invexpr2), *arg);
16970 return len;
16974 * Find the end of a variable or function name, taking care of magic braces.
16975 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
16976 * start and end of the first magic braces item.
16977 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
16978 * Return a pointer to just after the name. Equal to "arg" if there is no
16979 * valid name.
16981 static char_u *
16982 find_name_end(arg, expr_start, expr_end, flags)
16983 char_u *arg;
16984 char_u **expr_start;
16985 char_u **expr_end;
16986 int flags;
16988 int mb_nest = 0;
16989 int br_nest = 0;
16990 char_u *p;
16992 if (expr_start != NULL)
16994 *expr_start = NULL;
16995 *expr_end = NULL;
16998 /* Quick check for valid starting character. */
16999 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
17000 return arg;
17002 for (p = arg; *p != NUL
17003 && (eval_isnamec(*p)
17004 || *p == '{'
17005 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
17006 || mb_nest != 0
17007 || br_nest != 0); mb_ptr_adv(p))
17009 if (*p == '\'')
17011 /* skip over 'string' to avoid counting [ and ] inside it. */
17012 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
17014 if (*p == NUL)
17015 break;
17017 else if (*p == '"')
17019 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
17020 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
17021 if (*p == '\\' && p[1] != NUL)
17022 ++p;
17023 if (*p == NUL)
17024 break;
17027 if (mb_nest == 0)
17029 if (*p == '[')
17030 ++br_nest;
17031 else if (*p == ']')
17032 --br_nest;
17035 if (br_nest == 0)
17037 if (*p == '{')
17039 mb_nest++;
17040 if (expr_start != NULL && *expr_start == NULL)
17041 *expr_start = p;
17043 else if (*p == '}')
17045 mb_nest--;
17046 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
17047 *expr_end = p;
17052 return p;
17056 * Expands out the 'magic' {}'s in a variable/function name.
17057 * Note that this can call itself recursively, to deal with
17058 * constructs like foo{bar}{baz}{bam}
17059 * The four pointer arguments point to "foo{expre}ss{ion}bar"
17060 * "in_start" ^
17061 * "expr_start" ^
17062 * "expr_end" ^
17063 * "in_end" ^
17065 * Returns a new allocated string, which the caller must free.
17066 * Returns NULL for failure.
17068 static char_u *
17069 make_expanded_name(in_start, expr_start, expr_end, in_end)
17070 char_u *in_start;
17071 char_u *expr_start;
17072 char_u *expr_end;
17073 char_u *in_end;
17075 char_u c1;
17076 char_u *retval = NULL;
17077 char_u *temp_result;
17078 char_u *nextcmd = NULL;
17080 if (expr_end == NULL || in_end == NULL)
17081 return NULL;
17082 *expr_start = NUL;
17083 *expr_end = NUL;
17084 c1 = *in_end;
17085 *in_end = NUL;
17087 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
17088 if (temp_result != NULL && nextcmd == NULL)
17090 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
17091 + (in_end - expr_end) + 1));
17092 if (retval != NULL)
17094 STRCPY(retval, in_start);
17095 STRCAT(retval, temp_result);
17096 STRCAT(retval, expr_end + 1);
17099 vim_free(temp_result);
17101 *in_end = c1; /* put char back for error messages */
17102 *expr_start = '{';
17103 *expr_end = '}';
17105 if (retval != NULL)
17107 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
17108 if (expr_start != NULL)
17110 /* Further expansion! */
17111 temp_result = make_expanded_name(retval, expr_start,
17112 expr_end, temp_result);
17113 vim_free(retval);
17114 retval = temp_result;
17118 return retval;
17122 * Return TRUE if character "c" can be used in a variable or function name.
17123 * Does not include '{' or '}' for magic braces.
17125 static int
17126 eval_isnamec(c)
17127 int c;
17129 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
17133 * Return TRUE if character "c" can be used as the first character in a
17134 * variable or function name (excluding '{' and '}').
17136 static int
17137 eval_isnamec1(c)
17138 int c;
17140 return (ASCII_ISALPHA(c) || c == '_');
17144 * Set number v: variable to "val".
17146 void
17147 set_vim_var_nr(idx, val)
17148 int idx;
17149 long val;
17151 vimvars[idx].vv_nr = val;
17155 * Get number v: variable value.
17157 long
17158 get_vim_var_nr(idx)
17159 int idx;
17161 return vimvars[idx].vv_nr;
17164 #if defined(FEAT_AUTOCMD) || defined(PROTO)
17166 * Get string v: variable value. Uses a static buffer, can only be used once.
17168 char_u *
17169 get_vim_var_str(idx)
17170 int idx;
17172 return get_tv_string(&vimvars[idx].vv_tv);
17174 #endif
17177 * Set v:count, v:count1 and v:prevcount.
17179 void
17180 set_vcount(count, count1)
17181 long count;
17182 long count1;
17184 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
17185 vimvars[VV_COUNT].vv_nr = count;
17186 vimvars[VV_COUNT1].vv_nr = count1;
17190 * Set string v: variable to a copy of "val".
17192 void
17193 set_vim_var_string(idx, val, len)
17194 int idx;
17195 char_u *val;
17196 int len; /* length of "val" to use or -1 (whole string) */
17198 /* Need to do this (at least) once, since we can't initialize a union.
17199 * Will always be invoked when "v:progname" is set. */
17200 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
17202 vim_free(vimvars[idx].vv_str);
17203 if (val == NULL)
17204 vimvars[idx].vv_str = NULL;
17205 else if (len == -1)
17206 vimvars[idx].vv_str = vim_strsave(val);
17207 else
17208 vimvars[idx].vv_str = vim_strnsave(val, len);
17212 * Set v:register if needed.
17214 void
17215 set_reg_var(c)
17216 int c;
17218 char_u regname;
17220 if (c == 0 || c == ' ')
17221 regname = '"';
17222 else
17223 regname = c;
17224 /* Avoid free/alloc when the value is already right. */
17225 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
17226 set_vim_var_string(VV_REG, &regname, 1);
17230 * Get or set v:exception. If "oldval" == NULL, return the current value.
17231 * Otherwise, restore the value to "oldval" and return NULL.
17232 * Must always be called in pairs to save and restore v:exception! Does not
17233 * take care of memory allocations.
17235 char_u *
17236 v_exception(oldval)
17237 char_u *oldval;
17239 if (oldval == NULL)
17240 return vimvars[VV_EXCEPTION].vv_str;
17242 vimvars[VV_EXCEPTION].vv_str = oldval;
17243 return NULL;
17247 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
17248 * Otherwise, restore the value to "oldval" and return NULL.
17249 * Must always be called in pairs to save and restore v:throwpoint! Does not
17250 * take care of memory allocations.
17252 char_u *
17253 v_throwpoint(oldval)
17254 char_u *oldval;
17256 if (oldval == NULL)
17257 return vimvars[VV_THROWPOINT].vv_str;
17259 vimvars[VV_THROWPOINT].vv_str = oldval;
17260 return NULL;
17263 #if defined(FEAT_AUTOCMD) || defined(PROTO)
17265 * Set v:cmdarg.
17266 * If "eap" != NULL, use "eap" to generate the value and return the old value.
17267 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
17268 * Must always be called in pairs!
17270 char_u *
17271 set_cmdarg(eap, oldarg)
17272 exarg_T *eap;
17273 char_u *oldarg;
17275 char_u *oldval;
17276 char_u *newval;
17277 unsigned len;
17279 oldval = vimvars[VV_CMDARG].vv_str;
17280 if (eap == NULL)
17282 vim_free(oldval);
17283 vimvars[VV_CMDARG].vv_str = oldarg;
17284 return NULL;
17287 if (eap->force_bin == FORCE_BIN)
17288 len = 6;
17289 else if (eap->force_bin == FORCE_NOBIN)
17290 len = 8;
17291 else
17292 len = 0;
17294 if (eap->read_edit)
17295 len += 7;
17297 if (eap->force_ff != 0)
17298 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
17299 # ifdef FEAT_MBYTE
17300 if (eap->force_enc != 0)
17301 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
17302 if (eap->bad_char != 0)
17303 len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
17304 # endif
17306 newval = alloc(len + 1);
17307 if (newval == NULL)
17308 return NULL;
17310 if (eap->force_bin == FORCE_BIN)
17311 sprintf((char *)newval, " ++bin");
17312 else if (eap->force_bin == FORCE_NOBIN)
17313 sprintf((char *)newval, " ++nobin");
17314 else
17315 *newval = NUL;
17317 if (eap->read_edit)
17318 STRCAT(newval, " ++edit");
17320 if (eap->force_ff != 0)
17321 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
17322 eap->cmd + eap->force_ff);
17323 # ifdef FEAT_MBYTE
17324 if (eap->force_enc != 0)
17325 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
17326 eap->cmd + eap->force_enc);
17327 if (eap->bad_char != 0)
17328 sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
17329 eap->cmd + eap->bad_char);
17330 # endif
17331 vimvars[VV_CMDARG].vv_str = newval;
17332 return oldval;
17334 #endif
17337 * Get the value of internal variable "name".
17338 * Return OK or FAIL.
17340 static int
17341 get_var_tv(name, len, rettv, verbose)
17342 char_u *name;
17343 int len; /* length of "name" */
17344 typval_T *rettv; /* NULL when only checking existence */
17345 int verbose; /* may give error message */
17347 int ret = OK;
17348 typval_T *tv = NULL;
17349 typval_T atv;
17350 dictitem_T *v;
17351 int cc;
17353 /* truncate the name, so that we can use strcmp() */
17354 cc = name[len];
17355 name[len] = NUL;
17358 * Check for "b:changedtick".
17360 if (STRCMP(name, "b:changedtick") == 0)
17362 atv.v_type = VAR_NUMBER;
17363 atv.vval.v_number = curbuf->b_changedtick;
17364 tv = &atv;
17368 * Check for user-defined variables.
17370 else
17372 v = find_var(name, NULL);
17373 if (v != NULL)
17374 tv = &v->di_tv;
17377 if (tv == NULL)
17379 if (rettv != NULL && verbose)
17380 EMSG2(_(e_undefvar), name);
17381 ret = FAIL;
17383 else if (rettv != NULL)
17384 copy_tv(tv, rettv);
17386 name[len] = cc;
17388 return ret;
17392 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
17393 * Also handle function call with Funcref variable: func(expr)
17394 * Can all be combined: dict.func(expr)[idx]['func'](expr)
17396 static int
17397 handle_subscript(arg, rettv, evaluate, verbose)
17398 char_u **arg;
17399 typval_T *rettv;
17400 int evaluate; /* do more than finding the end */
17401 int verbose; /* give error messages */
17403 int ret = OK;
17404 dict_T *selfdict = NULL;
17405 char_u *s;
17406 int len;
17407 typval_T functv;
17409 while (ret == OK
17410 && (**arg == '['
17411 || (**arg == '.' && rettv->v_type == VAR_DICT)
17412 || (**arg == '(' && rettv->v_type == VAR_FUNC))
17413 && !vim_iswhite(*(*arg - 1)))
17415 if (**arg == '(')
17417 /* need to copy the funcref so that we can clear rettv */
17418 functv = *rettv;
17419 rettv->v_type = VAR_UNKNOWN;
17421 /* Invoke the function. Recursive! */
17422 s = functv.vval.v_string;
17423 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
17424 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
17425 &len, evaluate, selfdict);
17427 /* Clear the funcref afterwards, so that deleting it while
17428 * evaluating the arguments is possible (see test55). */
17429 clear_tv(&functv);
17431 /* Stop the expression evaluation when immediately aborting on
17432 * error, or when an interrupt occurred or an exception was thrown
17433 * but not caught. */
17434 if (aborting())
17436 if (ret == OK)
17437 clear_tv(rettv);
17438 ret = FAIL;
17440 dict_unref(selfdict);
17441 selfdict = NULL;
17443 else /* **arg == '[' || **arg == '.' */
17445 dict_unref(selfdict);
17446 if (rettv->v_type == VAR_DICT)
17448 selfdict = rettv->vval.v_dict;
17449 if (selfdict != NULL)
17450 ++selfdict->dv_refcount;
17452 else
17453 selfdict = NULL;
17454 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
17456 clear_tv(rettv);
17457 ret = FAIL;
17461 dict_unref(selfdict);
17462 return ret;
17466 * Allocate memory for a variable type-value, and make it emtpy (0 or NULL
17467 * value).
17469 static typval_T *
17470 alloc_tv()
17472 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
17476 * Allocate memory for a variable type-value, and assign a string to it.
17477 * The string "s" must have been allocated, it is consumed.
17478 * Return NULL for out of memory, the variable otherwise.
17480 static typval_T *
17481 alloc_string_tv(s)
17482 char_u *s;
17484 typval_T *rettv;
17486 rettv = alloc_tv();
17487 if (rettv != NULL)
17489 rettv->v_type = VAR_STRING;
17490 rettv->vval.v_string = s;
17492 else
17493 vim_free(s);
17494 return rettv;
17498 * Free the memory for a variable type-value.
17500 void
17501 free_tv(varp)
17502 typval_T *varp;
17504 if (varp != NULL)
17506 switch (varp->v_type)
17508 case VAR_FUNC:
17509 func_unref(varp->vval.v_string);
17510 /*FALLTHROUGH*/
17511 case VAR_STRING:
17512 vim_free(varp->vval.v_string);
17513 break;
17514 case VAR_LIST:
17515 list_unref(varp->vval.v_list);
17516 break;
17517 case VAR_DICT:
17518 dict_unref(varp->vval.v_dict);
17519 break;
17520 case VAR_NUMBER:
17521 case VAR_UNKNOWN:
17522 break;
17523 default:
17524 EMSG2(_(e_intern2), "free_tv()");
17525 break;
17527 vim_free(varp);
17532 * Free the memory for a variable value and set the value to NULL or 0.
17534 void
17535 clear_tv(varp)
17536 typval_T *varp;
17538 if (varp != NULL)
17540 switch (varp->v_type)
17542 case VAR_FUNC:
17543 func_unref(varp->vval.v_string);
17544 /*FALLTHROUGH*/
17545 case VAR_STRING:
17546 vim_free(varp->vval.v_string);
17547 varp->vval.v_string = NULL;
17548 break;
17549 case VAR_LIST:
17550 list_unref(varp->vval.v_list);
17551 varp->vval.v_list = NULL;
17552 break;
17553 case VAR_DICT:
17554 dict_unref(varp->vval.v_dict);
17555 varp->vval.v_dict = NULL;
17556 break;
17557 case VAR_NUMBER:
17558 varp->vval.v_number = 0;
17559 break;
17560 case VAR_UNKNOWN:
17561 break;
17562 default:
17563 EMSG2(_(e_intern2), "clear_tv()");
17565 varp->v_lock = 0;
17570 * Set the value of a variable to NULL without freeing items.
17572 static void
17573 init_tv(varp)
17574 typval_T *varp;
17576 if (varp != NULL)
17577 vim_memset(varp, 0, sizeof(typval_T));
17581 * Get the number value of a variable.
17582 * If it is a String variable, uses vim_str2nr().
17583 * For incompatible types, return 0.
17584 * get_tv_number_chk() is similar to get_tv_number(), but informs the
17585 * caller of incompatible types: it sets *denote to TRUE if "denote"
17586 * is not NULL or returns -1 otherwise.
17588 static long
17589 get_tv_number(varp)
17590 typval_T *varp;
17592 int error = FALSE;
17594 return get_tv_number_chk(varp, &error); /* return 0L on error */
17597 long
17598 get_tv_number_chk(varp, denote)
17599 typval_T *varp;
17600 int *denote;
17602 long n = 0L;
17604 switch (varp->v_type)
17606 case VAR_NUMBER:
17607 return (long)(varp->vval.v_number);
17608 case VAR_FUNC:
17609 EMSG(_("E703: Using a Funcref as a number"));
17610 break;
17611 case VAR_STRING:
17612 if (varp->vval.v_string != NULL)
17613 vim_str2nr(varp->vval.v_string, NULL, NULL,
17614 TRUE, TRUE, &n, NULL);
17615 return n;
17616 case VAR_LIST:
17617 EMSG(_("E745: Using a List as a number"));
17618 break;
17619 case VAR_DICT:
17620 EMSG(_("E728: Using a Dictionary as a number"));
17621 break;
17622 default:
17623 EMSG2(_(e_intern2), "get_tv_number()");
17624 break;
17626 if (denote == NULL) /* useful for values that must be unsigned */
17627 n = -1;
17628 else
17629 *denote = TRUE;
17630 return n;
17634 * Get the lnum from the first argument.
17635 * Also accepts ".", "$", etc., but that only works for the current buffer.
17636 * Returns -1 on error.
17638 static linenr_T
17639 get_tv_lnum(argvars)
17640 typval_T *argvars;
17642 typval_T rettv;
17643 linenr_T lnum;
17645 lnum = get_tv_number_chk(&argvars[0], NULL);
17646 if (lnum == 0) /* no valid number, try using line() */
17648 rettv.v_type = VAR_NUMBER;
17649 f_line(argvars, &rettv);
17650 lnum = rettv.vval.v_number;
17651 clear_tv(&rettv);
17653 return lnum;
17657 * Get the lnum from the first argument.
17658 * Also accepts "$", then "buf" is used.
17659 * Returns 0 on error.
17661 static linenr_T
17662 get_tv_lnum_buf(argvars, buf)
17663 typval_T *argvars;
17664 buf_T *buf;
17666 if (argvars[0].v_type == VAR_STRING
17667 && argvars[0].vval.v_string != NULL
17668 && argvars[0].vval.v_string[0] == '$'
17669 && buf != NULL)
17670 return buf->b_ml.ml_line_count;
17671 return get_tv_number_chk(&argvars[0], NULL);
17675 * Get the string value of a variable.
17676 * If it is a Number variable, the number is converted into a string.
17677 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
17678 * get_tv_string_buf() uses a given buffer.
17679 * If the String variable has never been set, return an empty string.
17680 * Never returns NULL;
17681 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
17682 * NULL on error.
17684 static char_u *
17685 get_tv_string(varp)
17686 typval_T *varp;
17688 static char_u mybuf[NUMBUFLEN];
17690 return get_tv_string_buf(varp, mybuf);
17693 static char_u *
17694 get_tv_string_buf(varp, buf)
17695 typval_T *varp;
17696 char_u *buf;
17698 char_u *res = get_tv_string_buf_chk(varp, buf);
17700 return res != NULL ? res : (char_u *)"";
17703 char_u *
17704 get_tv_string_chk(varp)
17705 typval_T *varp;
17707 static char_u mybuf[NUMBUFLEN];
17709 return get_tv_string_buf_chk(varp, mybuf);
17712 static char_u *
17713 get_tv_string_buf_chk(varp, buf)
17714 typval_T *varp;
17715 char_u *buf;
17717 switch (varp->v_type)
17719 case VAR_NUMBER:
17720 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
17721 return buf;
17722 case VAR_FUNC:
17723 EMSG(_("E729: using Funcref as a String"));
17724 break;
17725 case VAR_LIST:
17726 EMSG(_("E730: using List as a String"));
17727 break;
17728 case VAR_DICT:
17729 EMSG(_("E731: using Dictionary as a String"));
17730 break;
17731 case VAR_STRING:
17732 if (varp->vval.v_string != NULL)
17733 return varp->vval.v_string;
17734 return (char_u *)"";
17735 default:
17736 EMSG2(_(e_intern2), "get_tv_string_buf()");
17737 break;
17739 return NULL;
17743 * Find variable "name" in the list of variables.
17744 * Return a pointer to it if found, NULL if not found.
17745 * Careful: "a:0" variables don't have a name.
17746 * When "htp" is not NULL we are writing to the variable, set "htp" to the
17747 * hashtab_T used.
17749 static dictitem_T *
17750 find_var(name, htp)
17751 char_u *name;
17752 hashtab_T **htp;
17754 char_u *varname;
17755 hashtab_T *ht;
17757 ht = find_var_ht(name, &varname);
17758 if (htp != NULL)
17759 *htp = ht;
17760 if (ht == NULL)
17761 return NULL;
17762 return find_var_in_ht(ht, varname, htp != NULL);
17766 * Find variable "varname" in hashtab "ht".
17767 * Returns NULL if not found.
17769 static dictitem_T *
17770 find_var_in_ht(ht, varname, writing)
17771 hashtab_T *ht;
17772 char_u *varname;
17773 int writing;
17775 hashitem_T *hi;
17777 if (*varname == NUL)
17779 /* Must be something like "s:", otherwise "ht" would be NULL. */
17780 switch (varname[-2])
17782 case 's': return &SCRIPT_SV(current_SID).sv_var;
17783 case 'g': return &globvars_var;
17784 case 'v': return &vimvars_var;
17785 case 'b': return &curbuf->b_bufvar;
17786 case 'w': return &curwin->w_winvar;
17787 #ifdef FEAT_WINDOWS
17788 case 't': return &curtab->tp_winvar;
17789 #endif
17790 case 'l': return current_funccal == NULL
17791 ? NULL : &current_funccal->l_vars_var;
17792 case 'a': return current_funccal == NULL
17793 ? NULL : &current_funccal->l_avars_var;
17795 return NULL;
17798 hi = hash_find(ht, varname);
17799 if (HASHITEM_EMPTY(hi))
17801 /* For global variables we may try auto-loading the script. If it
17802 * worked find the variable again. Don't auto-load a script if it was
17803 * loaded already, otherwise it would be loaded every time when
17804 * checking if a function name is a Funcref variable. */
17805 if (ht == &globvarht && !writing
17806 && script_autoload(varname, FALSE) && !aborting())
17807 hi = hash_find(ht, varname);
17808 if (HASHITEM_EMPTY(hi))
17809 return NULL;
17811 return HI2DI(hi);
17815 * Find the hashtab used for a variable name.
17816 * Set "varname" to the start of name without ':'.
17818 static hashtab_T *
17819 find_var_ht(name, varname)
17820 char_u *name;
17821 char_u **varname;
17823 hashitem_T *hi;
17825 if (name[1] != ':')
17827 /* The name must not start with a colon or #. */
17828 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
17829 return NULL;
17830 *varname = name;
17832 /* "version" is "v:version" in all scopes */
17833 hi = hash_find(&compat_hashtab, name);
17834 if (!HASHITEM_EMPTY(hi))
17835 return &compat_hashtab;
17837 if (current_funccal == NULL)
17838 return &globvarht; /* global variable */
17839 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
17841 *varname = name + 2;
17842 if (*name == 'g') /* global variable */
17843 return &globvarht;
17844 /* There must be no ':' or '#' in the rest of the name, unless g: is used
17846 if (vim_strchr(name + 2, ':') != NULL
17847 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
17848 return NULL;
17849 if (*name == 'b') /* buffer variable */
17850 return &curbuf->b_vars.dv_hashtab;
17851 if (*name == 'w') /* window variable */
17852 return &curwin->w_vars.dv_hashtab;
17853 #ifdef FEAT_WINDOWS
17854 if (*name == 't') /* tab page variable */
17855 return &curtab->tp_vars.dv_hashtab;
17856 #endif
17857 if (*name == 'v') /* v: variable */
17858 return &vimvarht;
17859 if (*name == 'a' && current_funccal != NULL) /* function argument */
17860 return &current_funccal->l_avars.dv_hashtab;
17861 if (*name == 'l' && current_funccal != NULL) /* local function variable */
17862 return &current_funccal->l_vars.dv_hashtab;
17863 if (*name == 's' /* script variable */
17864 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
17865 return &SCRIPT_VARS(current_SID);
17866 return NULL;
17870 * Get the string value of a (global/local) variable.
17871 * Returns NULL when it doesn't exist.
17873 char_u *
17874 get_var_value(name)
17875 char_u *name;
17877 dictitem_T *v;
17879 v = find_var(name, NULL);
17880 if (v == NULL)
17881 return NULL;
17882 return get_tv_string(&v->di_tv);
17886 * Allocate a new hashtab for a sourced script. It will be used while
17887 * sourcing this script and when executing functions defined in the script.
17889 void
17890 new_script_vars(id)
17891 scid_T id;
17893 int i;
17894 hashtab_T *ht;
17895 scriptvar_T *sv;
17897 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
17899 /* Re-allocating ga_data means that an ht_array pointing to
17900 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
17901 * at its init value. Also reset "v_dict", it's always the same. */
17902 for (i = 1; i <= ga_scripts.ga_len; ++i)
17904 ht = &SCRIPT_VARS(i);
17905 if (ht->ht_mask == HT_INIT_SIZE - 1)
17906 ht->ht_array = ht->ht_smallarray;
17907 sv = &SCRIPT_SV(i);
17908 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
17911 while (ga_scripts.ga_len < id)
17913 sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
17914 init_var_dict(&sv->sv_dict, &sv->sv_var);
17915 ++ga_scripts.ga_len;
17921 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
17922 * point to it.
17924 void
17925 init_var_dict(dict, dict_var)
17926 dict_T *dict;
17927 dictitem_T *dict_var;
17929 hash_init(&dict->dv_hashtab);
17930 dict->dv_refcount = 99999;
17931 dict_var->di_tv.vval.v_dict = dict;
17932 dict_var->di_tv.v_type = VAR_DICT;
17933 dict_var->di_tv.v_lock = VAR_FIXED;
17934 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
17935 dict_var->di_key[0] = NUL;
17939 * Clean up a list of internal variables.
17940 * Frees all allocated variables and the value they contain.
17941 * Clears hashtab "ht", does not free it.
17943 void
17944 vars_clear(ht)
17945 hashtab_T *ht;
17947 vars_clear_ext(ht, TRUE);
17951 * Like vars_clear(), but only free the value if "free_val" is TRUE.
17953 static void
17954 vars_clear_ext(ht, free_val)
17955 hashtab_T *ht;
17956 int free_val;
17958 int todo;
17959 hashitem_T *hi;
17960 dictitem_T *v;
17962 hash_lock(ht);
17963 todo = (int)ht->ht_used;
17964 for (hi = ht->ht_array; todo > 0; ++hi)
17966 if (!HASHITEM_EMPTY(hi))
17968 --todo;
17970 /* Free the variable. Don't remove it from the hashtab,
17971 * ht_array might change then. hash_clear() takes care of it
17972 * later. */
17973 v = HI2DI(hi);
17974 if (free_val)
17975 clear_tv(&v->di_tv);
17976 if ((v->di_flags & DI_FLAGS_FIX) == 0)
17977 vim_free(v);
17980 hash_clear(ht);
17981 ht->ht_used = 0;
17985 * Delete a variable from hashtab "ht" at item "hi".
17986 * Clear the variable value and free the dictitem.
17988 static void
17989 delete_var(ht, hi)
17990 hashtab_T *ht;
17991 hashitem_T *hi;
17993 dictitem_T *di = HI2DI(hi);
17995 hash_remove(ht, hi);
17996 clear_tv(&di->di_tv);
17997 vim_free(di);
18001 * List the value of one internal variable.
18003 static void
18004 list_one_var(v, prefix)
18005 dictitem_T *v;
18006 char_u *prefix;
18008 char_u *tofree;
18009 char_u *s;
18010 char_u numbuf[NUMBUFLEN];
18012 s = echo_string(&v->di_tv, &tofree, numbuf, ++current_copyID);
18013 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
18014 s == NULL ? (char_u *)"" : s);
18015 vim_free(tofree);
18018 static void
18019 list_one_var_a(prefix, name, type, string)
18020 char_u *prefix;
18021 char_u *name;
18022 int type;
18023 char_u *string;
18025 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
18026 msg_start();
18027 msg_puts(prefix);
18028 if (name != NULL) /* "a:" vars don't have a name stored */
18029 msg_puts(name);
18030 msg_putchar(' ');
18031 msg_advance(22);
18032 if (type == VAR_NUMBER)
18033 msg_putchar('#');
18034 else if (type == VAR_FUNC)
18035 msg_putchar('*');
18036 else if (type == VAR_LIST)
18038 msg_putchar('[');
18039 if (*string == '[')
18040 ++string;
18042 else if (type == VAR_DICT)
18044 msg_putchar('{');
18045 if (*string == '{')
18046 ++string;
18048 else
18049 msg_putchar(' ');
18051 msg_outtrans(string);
18053 if (type == VAR_FUNC)
18054 msg_puts((char_u *)"()");
18058 * Set variable "name" to value in "tv".
18059 * If the variable already exists, the value is updated.
18060 * Otherwise the variable is created.
18062 static void
18063 set_var(name, tv, copy)
18064 char_u *name;
18065 typval_T *tv;
18066 int copy; /* make copy of value in "tv" */
18068 dictitem_T *v;
18069 char_u *varname;
18070 hashtab_T *ht;
18071 char_u *p;
18073 if (tv->v_type == VAR_FUNC)
18075 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
18076 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
18077 ? name[2] : name[0]))
18079 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
18080 return;
18082 if (function_exists(name))
18084 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
18085 name);
18086 return;
18090 ht = find_var_ht(name, &varname);
18091 if (ht == NULL || *varname == NUL)
18093 EMSG2(_(e_illvar), name);
18094 return;
18097 v = find_var_in_ht(ht, varname, TRUE);
18098 if (v != NULL)
18100 /* existing variable, need to clear the value */
18101 if (var_check_ro(v->di_flags, name)
18102 || tv_check_lock(v->di_tv.v_lock, name))
18103 return;
18104 if (v->di_tv.v_type != tv->v_type
18105 && !((v->di_tv.v_type == VAR_STRING
18106 || v->di_tv.v_type == VAR_NUMBER)
18107 && (tv->v_type == VAR_STRING
18108 || tv->v_type == VAR_NUMBER)))
18110 EMSG2(_("E706: Variable type mismatch for: %s"), name);
18111 return;
18115 * Handle setting internal v: variables separately: we don't change
18116 * the type.
18118 if (ht == &vimvarht)
18120 if (v->di_tv.v_type == VAR_STRING)
18122 vim_free(v->di_tv.vval.v_string);
18123 if (copy || tv->v_type != VAR_STRING)
18124 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
18125 else
18127 /* Take over the string to avoid an extra alloc/free. */
18128 v->di_tv.vval.v_string = tv->vval.v_string;
18129 tv->vval.v_string = NULL;
18132 else if (v->di_tv.v_type != VAR_NUMBER)
18133 EMSG2(_(e_intern2), "set_var()");
18134 else
18135 v->di_tv.vval.v_number = get_tv_number(tv);
18136 return;
18139 clear_tv(&v->di_tv);
18141 else /* add a new variable */
18143 /* Can't add "v:" variable. */
18144 if (ht == &vimvarht)
18146 EMSG2(_(e_illvar), name);
18147 return;
18150 /* Make sure the variable name is valid. */
18151 for (p = varname; *p != NUL; ++p)
18152 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
18153 && *p != AUTOLOAD_CHAR)
18155 EMSG2(_(e_illvar), varname);
18156 return;
18159 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
18160 + STRLEN(varname)));
18161 if (v == NULL)
18162 return;
18163 STRCPY(v->di_key, varname);
18164 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
18166 vim_free(v);
18167 return;
18169 v->di_flags = 0;
18172 if (copy || tv->v_type == VAR_NUMBER)
18173 copy_tv(tv, &v->di_tv);
18174 else
18176 v->di_tv = *tv;
18177 v->di_tv.v_lock = 0;
18178 init_tv(tv);
18183 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
18184 * Also give an error message.
18186 static int
18187 var_check_ro(flags, name)
18188 int flags;
18189 char_u *name;
18191 if (flags & DI_FLAGS_RO)
18193 EMSG2(_(e_readonlyvar), name);
18194 return TRUE;
18196 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
18198 EMSG2(_(e_readonlysbx), name);
18199 return TRUE;
18201 return FALSE;
18205 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
18206 * Also give an error message.
18208 static int
18209 var_check_fixed(flags, name)
18210 int flags;
18211 char_u *name;
18213 if (flags & DI_FLAGS_FIX)
18215 EMSG2(_("E795: Cannot delete variable %s"), name);
18216 return TRUE;
18218 return FALSE;
18222 * Return TRUE if typeval "tv" is set to be locked (immutable).
18223 * Also give an error message, using "name".
18225 static int
18226 tv_check_lock(lock, name)
18227 int lock;
18228 char_u *name;
18230 if (lock & VAR_LOCKED)
18232 EMSG2(_("E741: Value is locked: %s"),
18233 name == NULL ? (char_u *)_("Unknown") : name);
18234 return TRUE;
18236 if (lock & VAR_FIXED)
18238 EMSG2(_("E742: Cannot change value of %s"),
18239 name == NULL ? (char_u *)_("Unknown") : name);
18240 return TRUE;
18242 return FALSE;
18246 * Copy the values from typval_T "from" to typval_T "to".
18247 * When needed allocates string or increases reference count.
18248 * Does not make a copy of a list or dict but copies the reference!
18250 static void
18251 copy_tv(from, to)
18252 typval_T *from;
18253 typval_T *to;
18255 to->v_type = from->v_type;
18256 to->v_lock = 0;
18257 switch (from->v_type)
18259 case VAR_NUMBER:
18260 to->vval.v_number = from->vval.v_number;
18261 break;
18262 case VAR_STRING:
18263 case VAR_FUNC:
18264 if (from->vval.v_string == NULL)
18265 to->vval.v_string = NULL;
18266 else
18268 to->vval.v_string = vim_strsave(from->vval.v_string);
18269 if (from->v_type == VAR_FUNC)
18270 func_ref(to->vval.v_string);
18272 break;
18273 case VAR_LIST:
18274 if (from->vval.v_list == NULL)
18275 to->vval.v_list = NULL;
18276 else
18278 to->vval.v_list = from->vval.v_list;
18279 ++to->vval.v_list->lv_refcount;
18281 break;
18282 case VAR_DICT:
18283 if (from->vval.v_dict == NULL)
18284 to->vval.v_dict = NULL;
18285 else
18287 to->vval.v_dict = from->vval.v_dict;
18288 ++to->vval.v_dict->dv_refcount;
18290 break;
18291 default:
18292 EMSG2(_(e_intern2), "copy_tv()");
18293 break;
18298 * Make a copy of an item.
18299 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
18300 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
18301 * reference to an already copied list/dict can be used.
18302 * Returns FAIL or OK.
18304 static int
18305 item_copy(from, to, deep, copyID)
18306 typval_T *from;
18307 typval_T *to;
18308 int deep;
18309 int copyID;
18311 static int recurse = 0;
18312 int ret = OK;
18314 if (recurse >= DICT_MAXNEST)
18316 EMSG(_("E698: variable nested too deep for making a copy"));
18317 return FAIL;
18319 ++recurse;
18321 switch (from->v_type)
18323 case VAR_NUMBER:
18324 case VAR_STRING:
18325 case VAR_FUNC:
18326 copy_tv(from, to);
18327 break;
18328 case VAR_LIST:
18329 to->v_type = VAR_LIST;
18330 to->v_lock = 0;
18331 if (from->vval.v_list == NULL)
18332 to->vval.v_list = NULL;
18333 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
18335 /* use the copy made earlier */
18336 to->vval.v_list = from->vval.v_list->lv_copylist;
18337 ++to->vval.v_list->lv_refcount;
18339 else
18340 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
18341 if (to->vval.v_list == NULL)
18342 ret = FAIL;
18343 break;
18344 case VAR_DICT:
18345 to->v_type = VAR_DICT;
18346 to->v_lock = 0;
18347 if (from->vval.v_dict == NULL)
18348 to->vval.v_dict = NULL;
18349 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
18351 /* use the copy made earlier */
18352 to->vval.v_dict = from->vval.v_dict->dv_copydict;
18353 ++to->vval.v_dict->dv_refcount;
18355 else
18356 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
18357 if (to->vval.v_dict == NULL)
18358 ret = FAIL;
18359 break;
18360 default:
18361 EMSG2(_(e_intern2), "item_copy()");
18362 ret = FAIL;
18364 --recurse;
18365 return ret;
18369 * ":echo expr1 ..." print each argument separated with a space, add a
18370 * newline at the end.
18371 * ":echon expr1 ..." print each argument plain.
18373 void
18374 ex_echo(eap)
18375 exarg_T *eap;
18377 char_u *arg = eap->arg;
18378 typval_T rettv;
18379 char_u *tofree;
18380 char_u *p;
18381 int needclr = TRUE;
18382 int atstart = TRUE;
18383 char_u numbuf[NUMBUFLEN];
18385 if (eap->skip)
18386 ++emsg_skip;
18387 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
18389 p = arg;
18390 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
18393 * Report the invalid expression unless the expression evaluation
18394 * has been cancelled due to an aborting error, an interrupt, or an
18395 * exception.
18397 if (!aborting())
18398 EMSG2(_(e_invexpr2), p);
18399 break;
18401 if (!eap->skip)
18403 if (atstart)
18405 atstart = FALSE;
18406 /* Call msg_start() after eval1(), evaluating the expression
18407 * may cause a message to appear. */
18408 if (eap->cmdidx == CMD_echo)
18409 msg_start();
18411 else if (eap->cmdidx == CMD_echo)
18412 msg_puts_attr((char_u *)" ", echo_attr);
18413 p = echo_string(&rettv, &tofree, numbuf, ++current_copyID);
18414 if (p != NULL)
18415 for ( ; *p != NUL && !got_int; ++p)
18417 if (*p == '\n' || *p == '\r' || *p == TAB)
18419 if (*p != TAB && needclr)
18421 /* remove any text still there from the command */
18422 msg_clr_eos();
18423 needclr = FALSE;
18425 msg_putchar_attr(*p, echo_attr);
18427 else
18429 #ifdef FEAT_MBYTE
18430 if (has_mbyte)
18432 int i = (*mb_ptr2len)(p);
18434 (void)msg_outtrans_len_attr(p, i, echo_attr);
18435 p += i - 1;
18437 else
18438 #endif
18439 (void)msg_outtrans_len_attr(p, 1, echo_attr);
18442 vim_free(tofree);
18444 clear_tv(&rettv);
18445 arg = skipwhite(arg);
18447 eap->nextcmd = check_nextcmd(arg);
18449 if (eap->skip)
18450 --emsg_skip;
18451 else
18453 /* remove text that may still be there from the command */
18454 if (needclr)
18455 msg_clr_eos();
18456 if (eap->cmdidx == CMD_echo)
18457 msg_end();
18462 * ":echohl {name}".
18464 void
18465 ex_echohl(eap)
18466 exarg_T *eap;
18468 int id;
18470 id = syn_name2id(eap->arg);
18471 if (id == 0)
18472 echo_attr = 0;
18473 else
18474 echo_attr = syn_id2attr(id);
18478 * ":execute expr1 ..." execute the result of an expression.
18479 * ":echomsg expr1 ..." Print a message
18480 * ":echoerr expr1 ..." Print an error
18481 * Each gets spaces around each argument and a newline at the end for
18482 * echo commands
18484 void
18485 ex_execute(eap)
18486 exarg_T *eap;
18488 char_u *arg = eap->arg;
18489 typval_T rettv;
18490 int ret = OK;
18491 char_u *p;
18492 garray_T ga;
18493 int len;
18494 int save_did_emsg;
18496 ga_init2(&ga, 1, 80);
18498 if (eap->skip)
18499 ++emsg_skip;
18500 while (*arg != NUL && *arg != '|' && *arg != '\n')
18502 p = arg;
18503 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
18506 * Report the invalid expression unless the expression evaluation
18507 * has been cancelled due to an aborting error, an interrupt, or an
18508 * exception.
18510 if (!aborting())
18511 EMSG2(_(e_invexpr2), p);
18512 ret = FAIL;
18513 break;
18516 if (!eap->skip)
18518 p = get_tv_string(&rettv);
18519 len = (int)STRLEN(p);
18520 if (ga_grow(&ga, len + 2) == FAIL)
18522 clear_tv(&rettv);
18523 ret = FAIL;
18524 break;
18526 if (ga.ga_len)
18527 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
18528 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
18529 ga.ga_len += len;
18532 clear_tv(&rettv);
18533 arg = skipwhite(arg);
18536 if (ret != FAIL && ga.ga_data != NULL)
18538 if (eap->cmdidx == CMD_echomsg)
18540 MSG_ATTR(ga.ga_data, echo_attr);
18541 out_flush();
18543 else if (eap->cmdidx == CMD_echoerr)
18545 /* We don't want to abort following commands, restore did_emsg. */
18546 save_did_emsg = did_emsg;
18547 EMSG((char_u *)ga.ga_data);
18548 if (!force_abort)
18549 did_emsg = save_did_emsg;
18551 else if (eap->cmdidx == CMD_execute)
18552 do_cmdline((char_u *)ga.ga_data,
18553 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
18556 ga_clear(&ga);
18558 if (eap->skip)
18559 --emsg_skip;
18561 eap->nextcmd = check_nextcmd(arg);
18565 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
18566 * "arg" points to the "&" or '+' when called, to "option" when returning.
18567 * Returns NULL when no option name found. Otherwise pointer to the char
18568 * after the option name.
18570 static char_u *
18571 find_option_end(arg, opt_flags)
18572 char_u **arg;
18573 int *opt_flags;
18575 char_u *p = *arg;
18577 ++p;
18578 if (*p == 'g' && p[1] == ':')
18580 *opt_flags = OPT_GLOBAL;
18581 p += 2;
18583 else if (*p == 'l' && p[1] == ':')
18585 *opt_flags = OPT_LOCAL;
18586 p += 2;
18588 else
18589 *opt_flags = 0;
18591 if (!ASCII_ISALPHA(*p))
18592 return NULL;
18593 *arg = p;
18595 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
18596 p += 4; /* termcap option */
18597 else
18598 while (ASCII_ISALPHA(*p))
18599 ++p;
18600 return p;
18604 * ":function"
18606 void
18607 ex_function(eap)
18608 exarg_T *eap;
18610 char_u *theline;
18611 int j;
18612 int c;
18613 int saved_did_emsg;
18614 char_u *name = NULL;
18615 char_u *p;
18616 char_u *arg;
18617 char_u *line_arg = NULL;
18618 garray_T newargs;
18619 garray_T newlines;
18620 int varargs = FALSE;
18621 int mustend = FALSE;
18622 int flags = 0;
18623 ufunc_T *fp;
18624 int indent;
18625 int nesting;
18626 char_u *skip_until = NULL;
18627 dictitem_T *v;
18628 funcdict_T fudi;
18629 static int func_nr = 0; /* number for nameless function */
18630 int paren;
18631 hashtab_T *ht;
18632 int todo;
18633 hashitem_T *hi;
18634 int sourcing_lnum_off;
18637 * ":function" without argument: list functions.
18639 if (ends_excmd(*eap->arg))
18641 if (!eap->skip)
18643 todo = (int)func_hashtab.ht_used;
18644 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
18646 if (!HASHITEM_EMPTY(hi))
18648 --todo;
18649 fp = HI2UF(hi);
18650 if (!isdigit(*fp->uf_name))
18651 list_func_head(fp, FALSE);
18655 eap->nextcmd = check_nextcmd(eap->arg);
18656 return;
18660 * ":function /pat": list functions matching pattern.
18662 if (*eap->arg == '/')
18664 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
18665 if (!eap->skip)
18667 regmatch_T regmatch;
18669 c = *p;
18670 *p = NUL;
18671 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
18672 *p = c;
18673 if (regmatch.regprog != NULL)
18675 regmatch.rm_ic = p_ic;
18677 todo = (int)func_hashtab.ht_used;
18678 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
18680 if (!HASHITEM_EMPTY(hi))
18682 --todo;
18683 fp = HI2UF(hi);
18684 if (!isdigit(*fp->uf_name)
18685 && vim_regexec(&regmatch, fp->uf_name, 0))
18686 list_func_head(fp, FALSE);
18691 if (*p == '/')
18692 ++p;
18693 eap->nextcmd = check_nextcmd(p);
18694 return;
18698 * Get the function name. There are these situations:
18699 * func normal function name
18700 * "name" == func, "fudi.fd_dict" == NULL
18701 * dict.func new dictionary entry
18702 * "name" == NULL, "fudi.fd_dict" set,
18703 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
18704 * dict.func existing dict entry with a Funcref
18705 * "name" == func, "fudi.fd_dict" set,
18706 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
18707 * dict.func existing dict entry that's not a Funcref
18708 * "name" == NULL, "fudi.fd_dict" set,
18709 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
18711 p = eap->arg;
18712 name = trans_function_name(&p, eap->skip, 0, &fudi);
18713 paren = (vim_strchr(p, '(') != NULL);
18714 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
18717 * Return on an invalid expression in braces, unless the expression
18718 * evaluation has been cancelled due to an aborting error, an
18719 * interrupt, or an exception.
18721 if (!aborting())
18723 if (!eap->skip && fudi.fd_newkey != NULL)
18724 EMSG2(_(e_dictkey), fudi.fd_newkey);
18725 vim_free(fudi.fd_newkey);
18726 return;
18728 else
18729 eap->skip = TRUE;
18732 /* An error in a function call during evaluation of an expression in magic
18733 * braces should not cause the function not to be defined. */
18734 saved_did_emsg = did_emsg;
18735 did_emsg = FALSE;
18738 * ":function func" with only function name: list function.
18740 if (!paren)
18742 if (!ends_excmd(*skipwhite(p)))
18744 EMSG(_(e_trailing));
18745 goto ret_free;
18747 eap->nextcmd = check_nextcmd(p);
18748 if (eap->nextcmd != NULL)
18749 *p = NUL;
18750 if (!eap->skip && !got_int)
18752 fp = find_func(name);
18753 if (fp != NULL)
18755 list_func_head(fp, TRUE);
18756 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
18758 if (FUNCLINE(fp, j) == NULL)
18759 continue;
18760 msg_putchar('\n');
18761 msg_outnum((long)(j + 1));
18762 if (j < 9)
18763 msg_putchar(' ');
18764 if (j < 99)
18765 msg_putchar(' ');
18766 msg_prt_line(FUNCLINE(fp, j), FALSE);
18767 out_flush(); /* show a line at a time */
18768 ui_breakcheck();
18770 if (!got_int)
18772 msg_putchar('\n');
18773 msg_puts((char_u *)" endfunction");
18776 else
18777 emsg_funcname("E123: Undefined function: %s", name);
18779 goto ret_free;
18783 * ":function name(arg1, arg2)" Define function.
18785 p = skipwhite(p);
18786 if (*p != '(')
18788 if (!eap->skip)
18790 EMSG2(_("E124: Missing '(': %s"), eap->arg);
18791 goto ret_free;
18793 /* attempt to continue by skipping some text */
18794 if (vim_strchr(p, '(') != NULL)
18795 p = vim_strchr(p, '(');
18797 p = skipwhite(p + 1);
18799 ga_init2(&newargs, (int)sizeof(char_u *), 3);
18800 ga_init2(&newlines, (int)sizeof(char_u *), 3);
18802 if (!eap->skip)
18804 /* Check the name of the function. Unless it's a dictionary function
18805 * (that we are overwriting). */
18806 if (name != NULL)
18807 arg = name;
18808 else
18809 arg = fudi.fd_newkey;
18810 if (arg != NULL && (fudi.fd_di == NULL
18811 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
18813 if (*arg == K_SPECIAL)
18814 j = 3;
18815 else
18816 j = 0;
18817 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
18818 : eval_isnamec(arg[j])))
18819 ++j;
18820 if (arg[j] != NUL)
18821 emsg_funcname(_(e_invarg2), arg);
18826 * Isolate the arguments: "arg1, arg2, ...)"
18828 while (*p != ')')
18830 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
18832 varargs = TRUE;
18833 p += 3;
18834 mustend = TRUE;
18836 else
18838 arg = p;
18839 while (ASCII_ISALNUM(*p) || *p == '_')
18840 ++p;
18841 if (arg == p || isdigit(*arg)
18842 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
18843 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
18845 if (!eap->skip)
18846 EMSG2(_("E125: Illegal argument: %s"), arg);
18847 break;
18849 if (ga_grow(&newargs, 1) == FAIL)
18850 goto erret;
18851 c = *p;
18852 *p = NUL;
18853 arg = vim_strsave(arg);
18854 if (arg == NULL)
18855 goto erret;
18856 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
18857 *p = c;
18858 newargs.ga_len++;
18859 if (*p == ',')
18860 ++p;
18861 else
18862 mustend = TRUE;
18864 p = skipwhite(p);
18865 if (mustend && *p != ')')
18867 if (!eap->skip)
18868 EMSG2(_(e_invarg2), eap->arg);
18869 break;
18872 ++p; /* skip the ')' */
18874 /* find extra arguments "range", "dict" and "abort" */
18875 for (;;)
18877 p = skipwhite(p);
18878 if (STRNCMP(p, "range", 5) == 0)
18880 flags |= FC_RANGE;
18881 p += 5;
18883 else if (STRNCMP(p, "dict", 4) == 0)
18885 flags |= FC_DICT;
18886 p += 4;
18888 else if (STRNCMP(p, "abort", 5) == 0)
18890 flags |= FC_ABORT;
18891 p += 5;
18893 else
18894 break;
18897 /* When there is a line break use what follows for the function body.
18898 * Makes 'exe "func Test()\n...\nendfunc"' work. */
18899 if (*p == '\n')
18900 line_arg = p + 1;
18901 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
18902 EMSG(_(e_trailing));
18905 * Read the body of the function, until ":endfunction" is found.
18907 if (KeyTyped)
18909 /* Check if the function already exists, don't let the user type the
18910 * whole function before telling him it doesn't work! For a script we
18911 * need to skip the body to be able to find what follows. */
18912 if (!eap->skip && !eap->forceit)
18914 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
18915 EMSG(_(e_funcdict));
18916 else if (name != NULL && find_func(name) != NULL)
18917 emsg_funcname(e_funcexts, name);
18920 if (!eap->skip && did_emsg)
18921 goto erret;
18923 msg_putchar('\n'); /* don't overwrite the function name */
18924 cmdline_row = msg_row;
18927 indent = 2;
18928 nesting = 0;
18929 for (;;)
18931 msg_scroll = TRUE;
18932 need_wait_return = FALSE;
18933 sourcing_lnum_off = sourcing_lnum;
18935 if (line_arg != NULL)
18937 /* Use eap->arg, split up in parts by line breaks. */
18938 theline = line_arg;
18939 p = vim_strchr(theline, '\n');
18940 if (p == NULL)
18941 line_arg += STRLEN(line_arg);
18942 else
18944 *p = NUL;
18945 line_arg = p + 1;
18948 else if (eap->getline == NULL)
18949 theline = getcmdline(':', 0L, indent);
18950 else
18951 theline = eap->getline(':', eap->cookie, indent);
18952 if (KeyTyped)
18953 lines_left = Rows - 1;
18954 if (theline == NULL)
18956 EMSG(_("E126: Missing :endfunction"));
18957 goto erret;
18960 /* Detect line continuation: sourcing_lnum increased more than one. */
18961 if (sourcing_lnum > sourcing_lnum_off + 1)
18962 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
18963 else
18964 sourcing_lnum_off = 0;
18966 if (skip_until != NULL)
18968 /* between ":append" and "." and between ":python <<EOF" and "EOF"
18969 * don't check for ":endfunc". */
18970 if (STRCMP(theline, skip_until) == 0)
18972 vim_free(skip_until);
18973 skip_until = NULL;
18976 else
18978 /* skip ':' and blanks*/
18979 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
18982 /* Check for "endfunction". */
18983 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
18985 if (line_arg == NULL)
18986 vim_free(theline);
18987 break;
18990 /* Increase indent inside "if", "while", "for" and "try", decrease
18991 * at "end". */
18992 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
18993 indent -= 2;
18994 else if (STRNCMP(p, "if", 2) == 0
18995 || STRNCMP(p, "wh", 2) == 0
18996 || STRNCMP(p, "for", 3) == 0
18997 || STRNCMP(p, "try", 3) == 0)
18998 indent += 2;
19000 /* Check for defining a function inside this function. */
19001 if (checkforcmd(&p, "function", 2))
19003 if (*p == '!')
19004 p = skipwhite(p + 1);
19005 p += eval_fname_script(p);
19006 if (ASCII_ISALPHA(*p))
19008 vim_free(trans_function_name(&p, TRUE, 0, NULL));
19009 if (*skipwhite(p) == '(')
19011 ++nesting;
19012 indent += 2;
19017 /* Check for ":append" or ":insert". */
19018 p = skip_range(p, NULL);
19019 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
19020 || (p[0] == 'i'
19021 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
19022 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
19023 skip_until = vim_strsave((char_u *)".");
19025 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
19026 arg = skipwhite(skiptowhite(p));
19027 if (arg[0] == '<' && arg[1] =='<'
19028 && ((p[0] == 'p' && p[1] == 'y'
19029 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
19030 || (p[0] == 'p' && p[1] == 'e'
19031 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
19032 || (p[0] == 't' && p[1] == 'c'
19033 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
19034 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
19035 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
19036 || (p[0] == 'm' && p[1] == 'z'
19037 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
19040 /* ":python <<" continues until a dot, like ":append" */
19041 p = skipwhite(arg + 2);
19042 if (*p == NUL)
19043 skip_until = vim_strsave((char_u *)".");
19044 else
19045 skip_until = vim_strsave(p);
19049 /* Add the line to the function. */
19050 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
19052 if (line_arg == NULL)
19053 vim_free(theline);
19054 goto erret;
19057 /* Copy the line to newly allocated memory. get_one_sourceline()
19058 * allocates 250 bytes per line, this saves 80% on average. The cost
19059 * is an extra alloc/free. */
19060 p = vim_strsave(theline);
19061 if (p != NULL)
19063 if (line_arg == NULL)
19064 vim_free(theline);
19065 theline = p;
19068 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
19070 /* Add NULL lines for continuation lines, so that the line count is
19071 * equal to the index in the growarray. */
19072 while (sourcing_lnum_off-- > 0)
19073 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
19075 /* Check for end of eap->arg. */
19076 if (line_arg != NULL && *line_arg == NUL)
19077 line_arg = NULL;
19080 /* Don't define the function when skipping commands or when an error was
19081 * detected. */
19082 if (eap->skip || did_emsg)
19083 goto erret;
19086 * If there are no errors, add the function
19088 if (fudi.fd_dict == NULL)
19090 v = find_var(name, &ht);
19091 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
19093 emsg_funcname("E707: Function name conflicts with variable: %s",
19094 name);
19095 goto erret;
19098 fp = find_func(name);
19099 if (fp != NULL)
19101 if (!eap->forceit)
19103 emsg_funcname(e_funcexts, name);
19104 goto erret;
19106 if (fp->uf_calls > 0)
19108 emsg_funcname("E127: Cannot redefine function %s: It is in use",
19109 name);
19110 goto erret;
19112 /* redefine existing function */
19113 ga_clear_strings(&(fp->uf_args));
19114 ga_clear_strings(&(fp->uf_lines));
19115 vim_free(name);
19116 name = NULL;
19119 else
19121 char numbuf[20];
19123 fp = NULL;
19124 if (fudi.fd_newkey == NULL && !eap->forceit)
19126 EMSG(_(e_funcdict));
19127 goto erret;
19129 if (fudi.fd_di == NULL)
19131 /* Can't add a function to a locked dictionary */
19132 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
19133 goto erret;
19135 /* Can't change an existing function if it is locked */
19136 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
19137 goto erret;
19139 /* Give the function a sequential number. Can only be used with a
19140 * Funcref! */
19141 vim_free(name);
19142 sprintf(numbuf, "%d", ++func_nr);
19143 name = vim_strsave((char_u *)numbuf);
19144 if (name == NULL)
19145 goto erret;
19148 if (fp == NULL)
19150 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
19152 int slen, plen;
19153 char_u *scriptname;
19155 /* Check that the autoload name matches the script name. */
19156 j = FAIL;
19157 if (sourcing_name != NULL)
19159 scriptname = autoload_name(name);
19160 if (scriptname != NULL)
19162 p = vim_strchr(scriptname, '/');
19163 plen = (int)STRLEN(p);
19164 slen = (int)STRLEN(sourcing_name);
19165 if (slen > plen && fnamecmp(p,
19166 sourcing_name + slen - plen) == 0)
19167 j = OK;
19168 vim_free(scriptname);
19171 if (j == FAIL)
19173 EMSG2(_("E746: Function name does not match script file name: %s"), name);
19174 goto erret;
19178 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
19179 if (fp == NULL)
19180 goto erret;
19182 if (fudi.fd_dict != NULL)
19184 if (fudi.fd_di == NULL)
19186 /* add new dict entry */
19187 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
19188 if (fudi.fd_di == NULL)
19190 vim_free(fp);
19191 goto erret;
19193 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
19195 vim_free(fudi.fd_di);
19196 vim_free(fp);
19197 goto erret;
19200 else
19201 /* overwrite existing dict entry */
19202 clear_tv(&fudi.fd_di->di_tv);
19203 fudi.fd_di->di_tv.v_type = VAR_FUNC;
19204 fudi.fd_di->di_tv.v_lock = 0;
19205 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
19206 fp->uf_refcount = 1;
19208 /* behave like "dict" was used */
19209 flags |= FC_DICT;
19212 /* insert the new function in the function list */
19213 STRCPY(fp->uf_name, name);
19214 hash_add(&func_hashtab, UF2HIKEY(fp));
19216 fp->uf_args = newargs;
19217 fp->uf_lines = newlines;
19218 #ifdef FEAT_PROFILE
19219 fp->uf_tml_count = NULL;
19220 fp->uf_tml_total = NULL;
19221 fp->uf_tml_self = NULL;
19222 fp->uf_profiling = FALSE;
19223 if (prof_def_func())
19224 func_do_profile(fp);
19225 #endif
19226 fp->uf_varargs = varargs;
19227 fp->uf_flags = flags;
19228 fp->uf_calls = 0;
19229 fp->uf_script_ID = current_SID;
19230 goto ret_free;
19232 erret:
19233 ga_clear_strings(&newargs);
19234 ga_clear_strings(&newlines);
19235 ret_free:
19236 vim_free(skip_until);
19237 vim_free(fudi.fd_newkey);
19238 vim_free(name);
19239 did_emsg |= saved_did_emsg;
19243 * Get a function name, translating "<SID>" and "<SNR>".
19244 * Also handles a Funcref in a List or Dictionary.
19245 * Returns the function name in allocated memory, or NULL for failure.
19246 * flags:
19247 * TFN_INT: internal function name OK
19248 * TFN_QUIET: be quiet
19249 * Advances "pp" to just after the function name (if no error).
19251 static char_u *
19252 trans_function_name(pp, skip, flags, fdp)
19253 char_u **pp;
19254 int skip; /* only find the end, don't evaluate */
19255 int flags;
19256 funcdict_T *fdp; /* return: info about dictionary used */
19258 char_u *name = NULL;
19259 char_u *start;
19260 char_u *end;
19261 int lead;
19262 char_u sid_buf[20];
19263 int len;
19264 lval_T lv;
19266 if (fdp != NULL)
19267 vim_memset(fdp, 0, sizeof(funcdict_T));
19268 start = *pp;
19270 /* Check for hard coded <SNR>: already translated function ID (from a user
19271 * command). */
19272 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
19273 && (*pp)[2] == (int)KE_SNR)
19275 *pp += 3;
19276 len = get_id_len(pp) + 3;
19277 return vim_strnsave(start, len);
19280 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
19281 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
19282 lead = eval_fname_script(start);
19283 if (lead > 2)
19284 start += lead;
19286 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
19287 lead > 2 ? 0 : FNE_CHECK_START);
19288 if (end == start)
19290 if (!skip)
19291 EMSG(_("E129: Function name required"));
19292 goto theend;
19294 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
19297 * Report an invalid expression in braces, unless the expression
19298 * evaluation has been cancelled due to an aborting error, an
19299 * interrupt, or an exception.
19301 if (!aborting())
19303 if (end != NULL)
19304 EMSG2(_(e_invarg2), start);
19306 else
19307 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
19308 goto theend;
19311 if (lv.ll_tv != NULL)
19313 if (fdp != NULL)
19315 fdp->fd_dict = lv.ll_dict;
19316 fdp->fd_newkey = lv.ll_newkey;
19317 lv.ll_newkey = NULL;
19318 fdp->fd_di = lv.ll_di;
19320 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
19322 name = vim_strsave(lv.ll_tv->vval.v_string);
19323 *pp = end;
19325 else
19327 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
19328 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
19329 EMSG(_(e_funcref));
19330 else
19331 *pp = end;
19332 name = NULL;
19334 goto theend;
19337 if (lv.ll_name == NULL)
19339 /* Error found, but continue after the function name. */
19340 *pp = end;
19341 goto theend;
19344 if (lv.ll_exp_name != NULL)
19346 len = (int)STRLEN(lv.ll_exp_name);
19347 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
19348 && STRNCMP(lv.ll_name, "s:", 2) == 0)
19350 /* When there was "s:" already or the name expanded to get a
19351 * leading "s:" then remove it. */
19352 lv.ll_name += 2;
19353 len -= 2;
19354 lead = 2;
19357 else
19359 if (lead == 2) /* skip over "s:" */
19360 lv.ll_name += 2;
19361 len = (int)(end - lv.ll_name);
19365 * Copy the function name to allocated memory.
19366 * Accept <SID>name() inside a script, translate into <SNR>123_name().
19367 * Accept <SNR>123_name() outside a script.
19369 if (skip)
19370 lead = 0; /* do nothing */
19371 else if (lead > 0)
19373 lead = 3;
19374 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
19375 || eval_fname_sid(*pp))
19377 /* It's "s:" or "<SID>" */
19378 if (current_SID <= 0)
19380 EMSG(_(e_usingsid));
19381 goto theend;
19383 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
19384 lead += (int)STRLEN(sid_buf);
19387 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
19389 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
19390 goto theend;
19392 name = alloc((unsigned)(len + lead + 1));
19393 if (name != NULL)
19395 if (lead > 0)
19397 name[0] = K_SPECIAL;
19398 name[1] = KS_EXTRA;
19399 name[2] = (int)KE_SNR;
19400 if (lead > 3) /* If it's "<SID>" */
19401 STRCPY(name + 3, sid_buf);
19403 mch_memmove(name + lead, lv.ll_name, (size_t)len);
19404 name[len + lead] = NUL;
19406 *pp = end;
19408 theend:
19409 clear_lval(&lv);
19410 return name;
19414 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
19415 * Return 2 if "p" starts with "s:".
19416 * Return 0 otherwise.
19418 static int
19419 eval_fname_script(p)
19420 char_u *p;
19422 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
19423 || STRNICMP(p + 1, "SNR>", 4) == 0))
19424 return 5;
19425 if (p[0] == 's' && p[1] == ':')
19426 return 2;
19427 return 0;
19431 * Return TRUE if "p" starts with "<SID>" or "s:".
19432 * Only works if eval_fname_script() returned non-zero for "p"!
19434 static int
19435 eval_fname_sid(p)
19436 char_u *p;
19438 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
19442 * List the head of the function: "name(arg1, arg2)".
19444 static void
19445 list_func_head(fp, indent)
19446 ufunc_T *fp;
19447 int indent;
19449 int j;
19451 msg_start();
19452 if (indent)
19453 MSG_PUTS(" ");
19454 MSG_PUTS("function ");
19455 if (fp->uf_name[0] == K_SPECIAL)
19457 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
19458 msg_puts(fp->uf_name + 3);
19460 else
19461 msg_puts(fp->uf_name);
19462 msg_putchar('(');
19463 for (j = 0; j < fp->uf_args.ga_len; ++j)
19465 if (j)
19466 MSG_PUTS(", ");
19467 msg_puts(FUNCARG(fp, j));
19469 if (fp->uf_varargs)
19471 if (j)
19472 MSG_PUTS(", ");
19473 MSG_PUTS("...");
19475 msg_putchar(')');
19476 msg_clr_eos();
19477 if (p_verbose > 0)
19478 last_set_msg(fp->uf_script_ID);
19482 * Find a function by name, return pointer to it in ufuncs.
19483 * Return NULL for unknown function.
19485 static ufunc_T *
19486 find_func(name)
19487 char_u *name;
19489 hashitem_T *hi;
19491 hi = hash_find(&func_hashtab, name);
19492 if (!HASHITEM_EMPTY(hi))
19493 return HI2UF(hi);
19494 return NULL;
19497 #if defined(EXITFREE) || defined(PROTO)
19498 void
19499 free_all_functions()
19501 hashitem_T *hi;
19503 /* Need to start all over every time, because func_free() may change the
19504 * hash table. */
19505 while (func_hashtab.ht_used > 0)
19506 for (hi = func_hashtab.ht_array; ; ++hi)
19507 if (!HASHITEM_EMPTY(hi))
19509 func_free(HI2UF(hi));
19510 break;
19513 #endif
19516 * Return TRUE if a function "name" exists.
19518 static int
19519 function_exists(name)
19520 char_u *name;
19522 char_u *nm = name;
19523 char_u *p;
19524 int n = FALSE;
19526 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
19527 nm = skipwhite(nm);
19529 /* Only accept "funcname", "funcname ", "funcname (..." and
19530 * "funcname(...", not "funcname!...". */
19531 if (p != NULL && (*nm == NUL || *nm == '('))
19533 if (builtin_function(p))
19534 n = (find_internal_func(p) >= 0);
19535 else
19536 n = (find_func(p) != NULL);
19538 vim_free(p);
19539 return n;
19543 * Return TRUE if "name" looks like a builtin function name: starts with a
19544 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
19546 static int
19547 builtin_function(name)
19548 char_u *name;
19550 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
19551 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
19554 #if defined(FEAT_PROFILE) || defined(PROTO)
19556 * Start profiling function "fp".
19558 static void
19559 func_do_profile(fp)
19560 ufunc_T *fp;
19562 fp->uf_tm_count = 0;
19563 profile_zero(&fp->uf_tm_self);
19564 profile_zero(&fp->uf_tm_total);
19565 if (fp->uf_tml_count == NULL)
19566 fp->uf_tml_count = (int *)alloc_clear((unsigned)
19567 (sizeof(int) * fp->uf_lines.ga_len));
19568 if (fp->uf_tml_total == NULL)
19569 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
19570 (sizeof(proftime_T) * fp->uf_lines.ga_len));
19571 if (fp->uf_tml_self == NULL)
19572 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
19573 (sizeof(proftime_T) * fp->uf_lines.ga_len));
19574 fp->uf_tml_idx = -1;
19575 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
19576 || fp->uf_tml_self == NULL)
19577 return; /* out of memory */
19579 fp->uf_profiling = TRUE;
19583 * Dump the profiling results for all functions in file "fd".
19585 void
19586 func_dump_profile(fd)
19587 FILE *fd;
19589 hashitem_T *hi;
19590 int todo;
19591 ufunc_T *fp;
19592 int i;
19593 ufunc_T **sorttab;
19594 int st_len = 0;
19596 todo = (int)func_hashtab.ht_used;
19597 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
19599 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
19601 if (!HASHITEM_EMPTY(hi))
19603 --todo;
19604 fp = HI2UF(hi);
19605 if (fp->uf_profiling)
19607 if (sorttab != NULL)
19608 sorttab[st_len++] = fp;
19610 if (fp->uf_name[0] == K_SPECIAL)
19611 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
19612 else
19613 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
19614 if (fp->uf_tm_count == 1)
19615 fprintf(fd, "Called 1 time\n");
19616 else
19617 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
19618 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
19619 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
19620 fprintf(fd, "\n");
19621 fprintf(fd, "count total (s) self (s)\n");
19623 for (i = 0; i < fp->uf_lines.ga_len; ++i)
19625 if (FUNCLINE(fp, i) == NULL)
19626 continue;
19627 prof_func_line(fd, fp->uf_tml_count[i],
19628 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
19629 fprintf(fd, "%s\n", FUNCLINE(fp, i));
19631 fprintf(fd, "\n");
19636 if (sorttab != NULL && st_len > 0)
19638 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
19639 prof_total_cmp);
19640 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
19641 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
19642 prof_self_cmp);
19643 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
19647 static void
19648 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
19649 FILE *fd;
19650 ufunc_T **sorttab;
19651 int st_len;
19652 char *title;
19653 int prefer_self; /* when equal print only self time */
19655 int i;
19656 ufunc_T *fp;
19658 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
19659 fprintf(fd, "count total (s) self (s) function\n");
19660 for (i = 0; i < 20 && i < st_len; ++i)
19662 fp = sorttab[i];
19663 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
19664 prefer_self);
19665 if (fp->uf_name[0] == K_SPECIAL)
19666 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
19667 else
19668 fprintf(fd, " %s()\n", fp->uf_name);
19670 fprintf(fd, "\n");
19674 * Print the count and times for one function or function line.
19676 static void
19677 prof_func_line(fd, count, total, self, prefer_self)
19678 FILE *fd;
19679 int count;
19680 proftime_T *total;
19681 proftime_T *self;
19682 int prefer_self; /* when equal print only self time */
19684 if (count > 0)
19686 fprintf(fd, "%5d ", count);
19687 if (prefer_self && profile_equal(total, self))
19688 fprintf(fd, " ");
19689 else
19690 fprintf(fd, "%s ", profile_msg(total));
19691 if (!prefer_self && profile_equal(total, self))
19692 fprintf(fd, " ");
19693 else
19694 fprintf(fd, "%s ", profile_msg(self));
19696 else
19697 fprintf(fd, " ");
19701 * Compare function for total time sorting.
19703 static int
19704 #ifdef __BORLANDC__
19705 _RTLENTRYF
19706 #endif
19707 prof_total_cmp(s1, s2)
19708 const void *s1;
19709 const void *s2;
19711 ufunc_T *p1, *p2;
19713 p1 = *(ufunc_T **)s1;
19714 p2 = *(ufunc_T **)s2;
19715 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
19719 * Compare function for self time sorting.
19721 static int
19722 #ifdef __BORLANDC__
19723 _RTLENTRYF
19724 #endif
19725 prof_self_cmp(s1, s2)
19726 const void *s1;
19727 const void *s2;
19729 ufunc_T *p1, *p2;
19731 p1 = *(ufunc_T **)s1;
19732 p2 = *(ufunc_T **)s2;
19733 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
19736 #endif
19739 * If "name" has a package name try autoloading the script for it.
19740 * Return TRUE if a package was loaded.
19742 static int
19743 script_autoload(name, reload)
19744 char_u *name;
19745 int reload; /* load script again when already loaded */
19747 char_u *p;
19748 char_u *scriptname, *tofree;
19749 int ret = FALSE;
19750 int i;
19752 /* If there is no '#' after name[0] there is no package name. */
19753 p = vim_strchr(name, AUTOLOAD_CHAR);
19754 if (p == NULL || p == name)
19755 return FALSE;
19757 tofree = scriptname = autoload_name(name);
19759 /* Find the name in the list of previously loaded package names. Skip
19760 * "autoload/", it's always the same. */
19761 for (i = 0; i < ga_loaded.ga_len; ++i)
19762 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
19763 break;
19764 if (!reload && i < ga_loaded.ga_len)
19765 ret = FALSE; /* was loaded already */
19766 else
19768 /* Remember the name if it wasn't loaded already. */
19769 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
19771 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
19772 tofree = NULL;
19775 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
19776 if (source_runtime(scriptname, FALSE) == OK)
19777 ret = TRUE;
19780 vim_free(tofree);
19781 return ret;
19785 * Return the autoload script name for a function or variable name.
19786 * Returns NULL when out of memory.
19788 static char_u *
19789 autoload_name(name)
19790 char_u *name;
19792 char_u *p;
19793 char_u *scriptname;
19795 /* Get the script file name: replace '#' with '/', append ".vim". */
19796 scriptname = alloc((unsigned)(STRLEN(name) + 14));
19797 if (scriptname == NULL)
19798 return FALSE;
19799 STRCPY(scriptname, "autoload/");
19800 STRCAT(scriptname, name);
19801 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
19802 STRCAT(scriptname, ".vim");
19803 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
19804 *p = '/';
19805 return scriptname;
19808 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
19811 * Function given to ExpandGeneric() to obtain the list of user defined
19812 * function names.
19814 char_u *
19815 get_user_func_name(xp, idx)
19816 expand_T *xp;
19817 int idx;
19819 static long_u done;
19820 static hashitem_T *hi;
19821 ufunc_T *fp;
19823 if (idx == 0)
19825 done = 0;
19826 hi = func_hashtab.ht_array;
19828 if (done < func_hashtab.ht_used)
19830 if (done++ > 0)
19831 ++hi;
19832 while (HASHITEM_EMPTY(hi))
19833 ++hi;
19834 fp = HI2UF(hi);
19836 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
19837 return fp->uf_name; /* prevents overflow */
19839 cat_func_name(IObuff, fp);
19840 if (xp->xp_context != EXPAND_USER_FUNC)
19842 STRCAT(IObuff, "(");
19843 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
19844 STRCAT(IObuff, ")");
19846 return IObuff;
19848 return NULL;
19851 #endif /* FEAT_CMDL_COMPL */
19854 * Copy the function name of "fp" to buffer "buf".
19855 * "buf" must be able to hold the function name plus three bytes.
19856 * Takes care of script-local function names.
19858 static void
19859 cat_func_name(buf, fp)
19860 char_u *buf;
19861 ufunc_T *fp;
19863 if (fp->uf_name[0] == K_SPECIAL)
19865 STRCPY(buf, "<SNR>");
19866 STRCAT(buf, fp->uf_name + 3);
19868 else
19869 STRCPY(buf, fp->uf_name);
19873 * ":delfunction {name}"
19875 void
19876 ex_delfunction(eap)
19877 exarg_T *eap;
19879 ufunc_T *fp = NULL;
19880 char_u *p;
19881 char_u *name;
19882 funcdict_T fudi;
19884 p = eap->arg;
19885 name = trans_function_name(&p, eap->skip, 0, &fudi);
19886 vim_free(fudi.fd_newkey);
19887 if (name == NULL)
19889 if (fudi.fd_dict != NULL && !eap->skip)
19890 EMSG(_(e_funcref));
19891 return;
19893 if (!ends_excmd(*skipwhite(p)))
19895 vim_free(name);
19896 EMSG(_(e_trailing));
19897 return;
19899 eap->nextcmd = check_nextcmd(p);
19900 if (eap->nextcmd != NULL)
19901 *p = NUL;
19903 if (!eap->skip)
19904 fp = find_func(name);
19905 vim_free(name);
19907 if (!eap->skip)
19909 if (fp == NULL)
19911 EMSG2(_(e_nofunc), eap->arg);
19912 return;
19914 if (fp->uf_calls > 0)
19916 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
19917 return;
19920 if (fudi.fd_dict != NULL)
19922 /* Delete the dict item that refers to the function, it will
19923 * invoke func_unref() and possibly delete the function. */
19924 dictitem_remove(fudi.fd_dict, fudi.fd_di);
19926 else
19927 func_free(fp);
19932 * Free a function and remove it from the list of functions.
19934 static void
19935 func_free(fp)
19936 ufunc_T *fp;
19938 hashitem_T *hi;
19940 /* clear this function */
19941 ga_clear_strings(&(fp->uf_args));
19942 ga_clear_strings(&(fp->uf_lines));
19943 #ifdef FEAT_PROFILE
19944 vim_free(fp->uf_tml_count);
19945 vim_free(fp->uf_tml_total);
19946 vim_free(fp->uf_tml_self);
19947 #endif
19949 /* remove the function from the function hashtable */
19950 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
19951 if (HASHITEM_EMPTY(hi))
19952 EMSG2(_(e_intern2), "func_free()");
19953 else
19954 hash_remove(&func_hashtab, hi);
19956 vim_free(fp);
19960 * Unreference a Function: decrement the reference count and free it when it
19961 * becomes zero. Only for numbered functions.
19963 static void
19964 func_unref(name)
19965 char_u *name;
19967 ufunc_T *fp;
19969 if (name != NULL && isdigit(*name))
19971 fp = find_func(name);
19972 if (fp == NULL)
19973 EMSG2(_(e_intern2), "func_unref()");
19974 else if (--fp->uf_refcount <= 0)
19976 /* Only delete it when it's not being used. Otherwise it's done
19977 * when "uf_calls" becomes zero. */
19978 if (fp->uf_calls == 0)
19979 func_free(fp);
19985 * Count a reference to a Function.
19987 static void
19988 func_ref(name)
19989 char_u *name;
19991 ufunc_T *fp;
19993 if (name != NULL && isdigit(*name))
19995 fp = find_func(name);
19996 if (fp == NULL)
19997 EMSG2(_(e_intern2), "func_ref()");
19998 else
19999 ++fp->uf_refcount;
20004 * Call a user function.
20006 static void
20007 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
20008 ufunc_T *fp; /* pointer to function */
20009 int argcount; /* nr of args */
20010 typval_T *argvars; /* arguments */
20011 typval_T *rettv; /* return value */
20012 linenr_T firstline; /* first line of range */
20013 linenr_T lastline; /* last line of range */
20014 dict_T *selfdict; /* Dictionary for "self" */
20016 char_u *save_sourcing_name;
20017 linenr_T save_sourcing_lnum;
20018 scid_T save_current_SID;
20019 funccall_T fc;
20020 int save_did_emsg;
20021 static int depth = 0;
20022 dictitem_T *v;
20023 int fixvar_idx = 0; /* index in fixvar[] */
20024 int i;
20025 int ai;
20026 char_u numbuf[NUMBUFLEN];
20027 char_u *name;
20028 #ifdef FEAT_PROFILE
20029 proftime_T wait_start;
20030 proftime_T call_start;
20031 #endif
20033 /* If depth of calling is getting too high, don't execute the function */
20034 if (depth >= p_mfd)
20036 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
20037 rettv->v_type = VAR_NUMBER;
20038 rettv->vval.v_number = -1;
20039 return;
20041 ++depth;
20043 line_breakcheck(); /* check for CTRL-C hit */
20045 fc.caller = current_funccal;
20046 current_funccal = &fc;
20047 fc.func = fp;
20048 fc.rettv = rettv;
20049 rettv->vval.v_number = 0;
20050 fc.linenr = 0;
20051 fc.returned = FALSE;
20052 fc.level = ex_nesting_level;
20053 /* Check if this function has a breakpoint. */
20054 fc.breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
20055 fc.dbg_tick = debug_tick;
20058 * Note about using fc.fixvar[]: This is an array of FIXVAR_CNT variables
20059 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
20060 * each argument variable and saves a lot of time.
20063 * Init l: variables.
20065 init_var_dict(&fc.l_vars, &fc.l_vars_var);
20066 if (selfdict != NULL)
20068 /* Set l:self to "selfdict". Use "name" to avoid a warning from
20069 * some compiler that checks the destination size. */
20070 v = &fc.fixvar[fixvar_idx++].var;
20071 name = v->di_key;
20072 STRCPY(name, "self");
20073 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
20074 hash_add(&fc.l_vars.dv_hashtab, DI2HIKEY(v));
20075 v->di_tv.v_type = VAR_DICT;
20076 v->di_tv.v_lock = 0;
20077 v->di_tv.vval.v_dict = selfdict;
20078 ++selfdict->dv_refcount;
20082 * Init a: variables.
20083 * Set a:0 to "argcount".
20084 * Set a:000 to a list with room for the "..." arguments.
20086 init_var_dict(&fc.l_avars, &fc.l_avars_var);
20087 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "0",
20088 (varnumber_T)(argcount - fp->uf_args.ga_len));
20089 v = &fc.fixvar[fixvar_idx++].var;
20090 STRCPY(v->di_key, "000");
20091 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20092 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
20093 v->di_tv.v_type = VAR_LIST;
20094 v->di_tv.v_lock = VAR_FIXED;
20095 v->di_tv.vval.v_list = &fc.l_varlist;
20096 vim_memset(&fc.l_varlist, 0, sizeof(list_T));
20097 fc.l_varlist.lv_refcount = 99999;
20098 fc.l_varlist.lv_lock = VAR_FIXED;
20101 * Set a:firstline to "firstline" and a:lastline to "lastline".
20102 * Set a:name to named arguments.
20103 * Set a:N to the "..." arguments.
20105 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "firstline",
20106 (varnumber_T)firstline);
20107 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "lastline",
20108 (varnumber_T)lastline);
20109 for (i = 0; i < argcount; ++i)
20111 ai = i - fp->uf_args.ga_len;
20112 if (ai < 0)
20113 /* named argument a:name */
20114 name = FUNCARG(fp, i);
20115 else
20117 /* "..." argument a:1, a:2, etc. */
20118 sprintf((char *)numbuf, "%d", ai + 1);
20119 name = numbuf;
20121 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
20123 v = &fc.fixvar[fixvar_idx++].var;
20124 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20126 else
20128 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
20129 + STRLEN(name)));
20130 if (v == NULL)
20131 break;
20132 v->di_flags = DI_FLAGS_RO;
20134 STRCPY(v->di_key, name);
20135 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
20137 /* Note: the values are copied directly to avoid alloc/free.
20138 * "argvars" must have VAR_FIXED for v_lock. */
20139 v->di_tv = argvars[i];
20140 v->di_tv.v_lock = VAR_FIXED;
20142 if (ai >= 0 && ai < MAX_FUNC_ARGS)
20144 list_append(&fc.l_varlist, &fc.l_listitems[ai]);
20145 fc.l_listitems[ai].li_tv = argvars[i];
20146 fc.l_listitems[ai].li_tv.v_lock = VAR_FIXED;
20150 /* Don't redraw while executing the function. */
20151 ++RedrawingDisabled;
20152 save_sourcing_name = sourcing_name;
20153 save_sourcing_lnum = sourcing_lnum;
20154 sourcing_lnum = 1;
20155 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
20156 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
20157 if (sourcing_name != NULL)
20159 if (save_sourcing_name != NULL
20160 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
20161 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
20162 else
20163 STRCPY(sourcing_name, "function ");
20164 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
20166 if (p_verbose >= 12)
20168 ++no_wait_return;
20169 verbose_enter_scroll();
20171 smsg((char_u *)_("calling %s"), sourcing_name);
20172 if (p_verbose >= 14)
20174 char_u buf[MSG_BUF_LEN];
20175 char_u numbuf2[NUMBUFLEN];
20176 char_u *tofree;
20177 char_u *s;
20179 msg_puts((char_u *)"(");
20180 for (i = 0; i < argcount; ++i)
20182 if (i > 0)
20183 msg_puts((char_u *)", ");
20184 if (argvars[i].v_type == VAR_NUMBER)
20185 msg_outnum((long)argvars[i].vval.v_number);
20186 else
20188 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
20189 if (s != NULL)
20191 trunc_string(s, buf, MSG_BUF_CLEN);
20192 msg_puts(buf);
20193 vim_free(tofree);
20197 msg_puts((char_u *)")");
20199 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20201 verbose_leave_scroll();
20202 --no_wait_return;
20205 #ifdef FEAT_PROFILE
20206 if (do_profiling == PROF_YES)
20208 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
20209 func_do_profile(fp);
20210 if (fp->uf_profiling
20211 || (fc.caller != NULL && &fc.caller->func->uf_profiling))
20213 ++fp->uf_tm_count;
20214 profile_start(&call_start);
20215 profile_zero(&fp->uf_tm_children);
20217 script_prof_save(&wait_start);
20219 #endif
20221 save_current_SID = current_SID;
20222 current_SID = fp->uf_script_ID;
20223 save_did_emsg = did_emsg;
20224 did_emsg = FALSE;
20226 /* call do_cmdline() to execute the lines */
20227 do_cmdline(NULL, get_func_line, (void *)&fc,
20228 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
20230 --RedrawingDisabled;
20232 /* when the function was aborted because of an error, return -1 */
20233 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
20235 clear_tv(rettv);
20236 rettv->v_type = VAR_NUMBER;
20237 rettv->vval.v_number = -1;
20240 #ifdef FEAT_PROFILE
20241 if (do_profiling == PROF_YES && (fp->uf_profiling
20242 || (fc.caller != NULL && &fc.caller->func->uf_profiling)))
20244 profile_end(&call_start);
20245 profile_sub_wait(&wait_start, &call_start);
20246 profile_add(&fp->uf_tm_total, &call_start);
20247 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
20248 if (fc.caller != NULL && &fc.caller->func->uf_profiling)
20250 profile_add(&fc.caller->func->uf_tm_children, &call_start);
20251 profile_add(&fc.caller->func->uf_tml_children, &call_start);
20254 #endif
20256 /* when being verbose, mention the return value */
20257 if (p_verbose >= 12)
20259 ++no_wait_return;
20260 verbose_enter_scroll();
20262 if (aborting())
20263 smsg((char_u *)_("%s aborted"), sourcing_name);
20264 else if (fc.rettv->v_type == VAR_NUMBER)
20265 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
20266 (long)fc.rettv->vval.v_number);
20267 else
20269 char_u buf[MSG_BUF_LEN];
20270 char_u numbuf2[NUMBUFLEN];
20271 char_u *tofree;
20272 char_u *s;
20274 /* The value may be very long. Skip the middle part, so that we
20275 * have some idea how it starts and ends. smsg() would always
20276 * truncate it at the end. */
20277 s = tv2string(fc.rettv, &tofree, numbuf2, 0);
20278 if (s != NULL)
20280 trunc_string(s, buf, MSG_BUF_CLEN);
20281 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
20282 vim_free(tofree);
20285 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20287 verbose_leave_scroll();
20288 --no_wait_return;
20291 vim_free(sourcing_name);
20292 sourcing_name = save_sourcing_name;
20293 sourcing_lnum = save_sourcing_lnum;
20294 current_SID = save_current_SID;
20295 #ifdef FEAT_PROFILE
20296 if (do_profiling == PROF_YES)
20297 script_prof_restore(&wait_start);
20298 #endif
20300 if (p_verbose >= 12 && sourcing_name != NULL)
20302 ++no_wait_return;
20303 verbose_enter_scroll();
20305 smsg((char_u *)_("continuing in %s"), sourcing_name);
20306 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20308 verbose_leave_scroll();
20309 --no_wait_return;
20312 did_emsg |= save_did_emsg;
20313 current_funccal = fc.caller;
20315 /* The a: variables typevals were not alloced, only free the allocated
20316 * variables. */
20317 vars_clear_ext(&fc.l_avars.dv_hashtab, FALSE);
20319 vars_clear(&fc.l_vars.dv_hashtab); /* free all l: variables */
20320 --depth;
20324 * Add a number variable "name" to dict "dp" with value "nr".
20326 static void
20327 add_nr_var(dp, v, name, nr)
20328 dict_T *dp;
20329 dictitem_T *v;
20330 char *name;
20331 varnumber_T nr;
20333 STRCPY(v->di_key, name);
20334 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20335 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
20336 v->di_tv.v_type = VAR_NUMBER;
20337 v->di_tv.v_lock = VAR_FIXED;
20338 v->di_tv.vval.v_number = nr;
20342 * ":return [expr]"
20344 void
20345 ex_return(eap)
20346 exarg_T *eap;
20348 char_u *arg = eap->arg;
20349 typval_T rettv;
20350 int returning = FALSE;
20352 if (current_funccal == NULL)
20354 EMSG(_("E133: :return not inside a function"));
20355 return;
20358 if (eap->skip)
20359 ++emsg_skip;
20361 eap->nextcmd = NULL;
20362 if ((*arg != NUL && *arg != '|' && *arg != '\n')
20363 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
20365 if (!eap->skip)
20366 returning = do_return(eap, FALSE, TRUE, &rettv);
20367 else
20368 clear_tv(&rettv);
20370 /* It's safer to return also on error. */
20371 else if (!eap->skip)
20374 * Return unless the expression evaluation has been cancelled due to an
20375 * aborting error, an interrupt, or an exception.
20377 if (!aborting())
20378 returning = do_return(eap, FALSE, TRUE, NULL);
20381 /* When skipping or the return gets pending, advance to the next command
20382 * in this line (!returning). Otherwise, ignore the rest of the line.
20383 * Following lines will be ignored by get_func_line(). */
20384 if (returning)
20385 eap->nextcmd = NULL;
20386 else if (eap->nextcmd == NULL) /* no argument */
20387 eap->nextcmd = check_nextcmd(arg);
20389 if (eap->skip)
20390 --emsg_skip;
20394 * Return from a function. Possibly makes the return pending. Also called
20395 * for a pending return at the ":endtry" or after returning from an extra
20396 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
20397 * when called due to a ":return" command. "rettv" may point to a typval_T
20398 * with the return rettv. Returns TRUE when the return can be carried out,
20399 * FALSE when the return gets pending.
20402 do_return(eap, reanimate, is_cmd, rettv)
20403 exarg_T *eap;
20404 int reanimate;
20405 int is_cmd;
20406 void *rettv;
20408 int idx;
20409 struct condstack *cstack = eap->cstack;
20411 if (reanimate)
20412 /* Undo the return. */
20413 current_funccal->returned = FALSE;
20416 * Cleanup (and inactivate) conditionals, but stop when a try conditional
20417 * not in its finally clause (which then is to be executed next) is found.
20418 * In this case, make the ":return" pending for execution at the ":endtry".
20419 * Otherwise, return normally.
20421 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
20422 if (idx >= 0)
20424 cstack->cs_pending[idx] = CSTP_RETURN;
20426 if (!is_cmd && !reanimate)
20427 /* A pending return again gets pending. "rettv" points to an
20428 * allocated variable with the rettv of the original ":return"'s
20429 * argument if present or is NULL else. */
20430 cstack->cs_rettv[idx] = rettv;
20431 else
20433 /* When undoing a return in order to make it pending, get the stored
20434 * return rettv. */
20435 if (reanimate)
20436 rettv = current_funccal->rettv;
20438 if (rettv != NULL)
20440 /* Store the value of the pending return. */
20441 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
20442 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
20443 else
20444 EMSG(_(e_outofmem));
20446 else
20447 cstack->cs_rettv[idx] = NULL;
20449 if (reanimate)
20451 /* The pending return value could be overwritten by a ":return"
20452 * without argument in a finally clause; reset the default
20453 * return value. */
20454 current_funccal->rettv->v_type = VAR_NUMBER;
20455 current_funccal->rettv->vval.v_number = 0;
20458 report_make_pending(CSTP_RETURN, rettv);
20460 else
20462 current_funccal->returned = TRUE;
20464 /* If the return is carried out now, store the return value. For
20465 * a return immediately after reanimation, the value is already
20466 * there. */
20467 if (!reanimate && rettv != NULL)
20469 clear_tv(current_funccal->rettv);
20470 *current_funccal->rettv = *(typval_T *)rettv;
20471 if (!is_cmd)
20472 vim_free(rettv);
20476 return idx < 0;
20480 * Free the variable with a pending return value.
20482 void
20483 discard_pending_return(rettv)
20484 void *rettv;
20486 free_tv((typval_T *)rettv);
20490 * Generate a return command for producing the value of "rettv". The result
20491 * is an allocated string. Used by report_pending() for verbose messages.
20493 char_u *
20494 get_return_cmd(rettv)
20495 void *rettv;
20497 char_u *s = NULL;
20498 char_u *tofree = NULL;
20499 char_u numbuf[NUMBUFLEN];
20501 if (rettv != NULL)
20502 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
20503 if (s == NULL)
20504 s = (char_u *)"";
20506 STRCPY(IObuff, ":return ");
20507 STRNCPY(IObuff + 8, s, IOSIZE - 8);
20508 if (STRLEN(s) + 8 >= IOSIZE)
20509 STRCPY(IObuff + IOSIZE - 4, "...");
20510 vim_free(tofree);
20511 return vim_strsave(IObuff);
20515 * Get next function line.
20516 * Called by do_cmdline() to get the next line.
20517 * Returns allocated string, or NULL for end of function.
20519 /* ARGSUSED */
20520 char_u *
20521 get_func_line(c, cookie, indent)
20522 int c; /* not used */
20523 void *cookie;
20524 int indent; /* not used */
20526 funccall_T *fcp = (funccall_T *)cookie;
20527 ufunc_T *fp = fcp->func;
20528 char_u *retval;
20529 garray_T *gap; /* growarray with function lines */
20531 /* If breakpoints have been added/deleted need to check for it. */
20532 if (fcp->dbg_tick != debug_tick)
20534 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
20535 sourcing_lnum);
20536 fcp->dbg_tick = debug_tick;
20538 #ifdef FEAT_PROFILE
20539 if (do_profiling == PROF_YES)
20540 func_line_end(cookie);
20541 #endif
20543 gap = &fp->uf_lines;
20544 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
20545 || fcp->returned)
20546 retval = NULL;
20547 else
20549 /* Skip NULL lines (continuation lines). */
20550 while (fcp->linenr < gap->ga_len
20551 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
20552 ++fcp->linenr;
20553 if (fcp->linenr >= gap->ga_len)
20554 retval = NULL;
20555 else
20557 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
20558 sourcing_lnum = fcp->linenr;
20559 #ifdef FEAT_PROFILE
20560 if (do_profiling == PROF_YES)
20561 func_line_start(cookie);
20562 #endif
20566 /* Did we encounter a breakpoint? */
20567 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
20569 dbg_breakpoint(fp->uf_name, sourcing_lnum);
20570 /* Find next breakpoint. */
20571 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
20572 sourcing_lnum);
20573 fcp->dbg_tick = debug_tick;
20576 return retval;
20579 #if defined(FEAT_PROFILE) || defined(PROTO)
20581 * Called when starting to read a function line.
20582 * "sourcing_lnum" must be correct!
20583 * When skipping lines it may not actually be executed, but we won't find out
20584 * until later and we need to store the time now.
20586 void
20587 func_line_start(cookie)
20588 void *cookie;
20590 funccall_T *fcp = (funccall_T *)cookie;
20591 ufunc_T *fp = fcp->func;
20593 if (fp->uf_profiling && sourcing_lnum >= 1
20594 && sourcing_lnum <= fp->uf_lines.ga_len)
20596 fp->uf_tml_idx = sourcing_lnum - 1;
20597 /* Skip continuation lines. */
20598 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
20599 --fp->uf_tml_idx;
20600 fp->uf_tml_execed = FALSE;
20601 profile_start(&fp->uf_tml_start);
20602 profile_zero(&fp->uf_tml_children);
20603 profile_get_wait(&fp->uf_tml_wait);
20608 * Called when actually executing a function line.
20610 void
20611 func_line_exec(cookie)
20612 void *cookie;
20614 funccall_T *fcp = (funccall_T *)cookie;
20615 ufunc_T *fp = fcp->func;
20617 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
20618 fp->uf_tml_execed = TRUE;
20622 * Called when done with a function line.
20624 void
20625 func_line_end(cookie)
20626 void *cookie;
20628 funccall_T *fcp = (funccall_T *)cookie;
20629 ufunc_T *fp = fcp->func;
20631 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
20633 if (fp->uf_tml_execed)
20635 ++fp->uf_tml_count[fp->uf_tml_idx];
20636 profile_end(&fp->uf_tml_start);
20637 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
20638 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
20639 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
20640 &fp->uf_tml_children);
20642 fp->uf_tml_idx = -1;
20645 #endif
20648 * Return TRUE if the currently active function should be ended, because a
20649 * return was encountered or an error occured. Used inside a ":while".
20652 func_has_ended(cookie)
20653 void *cookie;
20655 funccall_T *fcp = (funccall_T *)cookie;
20657 /* Ignore the "abort" flag if the abortion behavior has been changed due to
20658 * an error inside a try conditional. */
20659 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
20660 || fcp->returned);
20664 * return TRUE if cookie indicates a function which "abort"s on errors.
20667 func_has_abort(cookie)
20668 void *cookie;
20670 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
20673 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
20674 typedef enum
20676 VAR_FLAVOUR_DEFAULT,
20677 VAR_FLAVOUR_SESSION,
20678 VAR_FLAVOUR_VIMINFO
20679 } var_flavour_T;
20681 static var_flavour_T var_flavour __ARGS((char_u *varname));
20683 static var_flavour_T
20684 var_flavour(varname)
20685 char_u *varname;
20687 char_u *p = varname;
20689 if (ASCII_ISUPPER(*p))
20691 while (*(++p))
20692 if (ASCII_ISLOWER(*p))
20693 return VAR_FLAVOUR_SESSION;
20694 return VAR_FLAVOUR_VIMINFO;
20696 else
20697 return VAR_FLAVOUR_DEFAULT;
20699 #endif
20701 #if defined(FEAT_VIMINFO) || defined(PROTO)
20703 * Restore global vars that start with a capital from the viminfo file
20706 read_viminfo_varlist(virp, writing)
20707 vir_T *virp;
20708 int writing;
20710 char_u *tab;
20711 int is_string = FALSE;
20712 typval_T tv;
20714 if (!writing && (find_viminfo_parameter('!') != NULL))
20716 tab = vim_strchr(virp->vir_line + 1, '\t');
20717 if (tab != NULL)
20719 *tab++ = '\0'; /* isolate the variable name */
20720 if (*tab == 'S') /* string var */
20721 is_string = TRUE;
20723 tab = vim_strchr(tab, '\t');
20724 if (tab != NULL)
20726 if (is_string)
20728 tv.v_type = VAR_STRING;
20729 tv.vval.v_string = viminfo_readstring(virp,
20730 (int)(tab - virp->vir_line + 1), TRUE);
20732 else
20734 tv.v_type = VAR_NUMBER;
20735 tv.vval.v_number = atol((char *)tab + 1);
20737 set_var(virp->vir_line + 1, &tv, FALSE);
20738 if (is_string)
20739 vim_free(tv.vval.v_string);
20744 return viminfo_readline(virp);
20748 * Write global vars that start with a capital to the viminfo file
20750 void
20751 write_viminfo_varlist(fp)
20752 FILE *fp;
20754 hashitem_T *hi;
20755 dictitem_T *this_var;
20756 int todo;
20757 char *s;
20758 char_u *p;
20759 char_u *tofree;
20760 char_u numbuf[NUMBUFLEN];
20762 if (find_viminfo_parameter('!') == NULL)
20763 return;
20765 fprintf(fp, _("\n# global variables:\n"));
20767 todo = (int)globvarht.ht_used;
20768 for (hi = globvarht.ht_array; todo > 0; ++hi)
20770 if (!HASHITEM_EMPTY(hi))
20772 --todo;
20773 this_var = HI2DI(hi);
20774 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
20776 switch (this_var->di_tv.v_type)
20778 case VAR_STRING: s = "STR"; break;
20779 case VAR_NUMBER: s = "NUM"; break;
20780 default: continue;
20782 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
20783 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
20784 if (p != NULL)
20785 viminfo_writestring(fp, p);
20786 vim_free(tofree);
20791 #endif
20793 #if defined(FEAT_SESSION) || defined(PROTO)
20795 store_session_globals(fd)
20796 FILE *fd;
20798 hashitem_T *hi;
20799 dictitem_T *this_var;
20800 int todo;
20801 char_u *p, *t;
20803 todo = (int)globvarht.ht_used;
20804 for (hi = globvarht.ht_array; todo > 0; ++hi)
20806 if (!HASHITEM_EMPTY(hi))
20808 --todo;
20809 this_var = HI2DI(hi);
20810 if ((this_var->di_tv.v_type == VAR_NUMBER
20811 || this_var->di_tv.v_type == VAR_STRING)
20812 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
20814 /* Escape special characters with a backslash. Turn a LF and
20815 * CR into \n and \r. */
20816 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
20817 (char_u *)"\\\"\n\r");
20818 if (p == NULL) /* out of memory */
20819 break;
20820 for (t = p; *t != NUL; ++t)
20821 if (*t == '\n')
20822 *t = 'n';
20823 else if (*t == '\r')
20824 *t = 'r';
20825 if ((fprintf(fd, "let %s = %c%s%c",
20826 this_var->di_key,
20827 (this_var->di_tv.v_type == VAR_STRING) ? '"'
20828 : ' ',
20830 (this_var->di_tv.v_type == VAR_STRING) ? '"'
20831 : ' ') < 0)
20832 || put_eol(fd) == FAIL)
20834 vim_free(p);
20835 return FAIL;
20837 vim_free(p);
20841 return OK;
20843 #endif
20846 * Display script name where an item was last set.
20847 * Should only be invoked when 'verbose' is non-zero.
20849 void
20850 last_set_msg(scriptID)
20851 scid_T scriptID;
20853 char_u *p;
20855 if (scriptID != 0)
20857 p = home_replace_save(NULL, get_scriptname(scriptID));
20858 if (p != NULL)
20860 verbose_enter();
20861 MSG_PUTS(_("\n\tLast set from "));
20862 MSG_PUTS(p);
20863 vim_free(p);
20864 verbose_leave();
20869 #endif /* FEAT_EVAL */
20871 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
20874 #ifdef WIN3264
20876 * Functions for ":8" filename modifier: get 8.3 version of a filename.
20878 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
20879 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
20880 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
20883 * Get the short pathname of a file.
20884 * Returns 1 on success. *fnamelen is 0 for nonexistent path.
20886 static int
20887 get_short_pathname(fnamep, bufp, fnamelen)
20888 char_u **fnamep;
20889 char_u **bufp;
20890 int *fnamelen;
20892 int l,len;
20893 char_u *newbuf;
20895 len = *fnamelen;
20897 l = GetShortPathName(*fnamep, *fnamep, len);
20898 if (l > len - 1)
20900 /* If that doesn't work (not enough space), then save the string
20901 * and try again with a new buffer big enough
20903 newbuf = vim_strnsave(*fnamep, l);
20904 if (newbuf == NULL)
20905 return 0;
20907 vim_free(*bufp);
20908 *fnamep = *bufp = newbuf;
20910 l = GetShortPathName(*fnamep,*fnamep,l+1);
20912 /* Really should always succeed, as the buffer is big enough */
20915 *fnamelen = l;
20916 return 1;
20920 * Create a short path name. Returns the length of the buffer it needs.
20921 * Doesn't copy over the end of the buffer passed in.
20923 static int
20924 shortpath_for_invalid_fname(fname, bufp, fnamelen)
20925 char_u **fname;
20926 char_u **bufp;
20927 int *fnamelen;
20929 char_u *s, *p, *pbuf2, *pbuf3;
20930 char_u ch;
20931 int len, len2, plen, slen;
20933 /* Make a copy */
20934 len2 = *fnamelen;
20935 pbuf2 = vim_strnsave(*fname, len2);
20936 pbuf3 = NULL;
20938 s = pbuf2 + len2 - 1; /* Find the end */
20939 slen = 1;
20940 plen = len2;
20942 if (after_pathsep(pbuf2, s + 1))
20944 --s;
20945 ++slen;
20946 --plen;
20951 /* Go back one path-separator */
20952 while (s > pbuf2 && !after_pathsep(pbuf2, s + 1))
20954 --s;
20955 ++slen;
20956 --plen;
20958 if (s <= pbuf2)
20959 break;
20961 /* Remember the character that is about to be splatted */
20962 ch = *s;
20963 *s = 0; /* get_short_pathname requires a null-terminated string */
20965 /* Try it in situ */
20966 p = pbuf2;
20967 if (!get_short_pathname(&p, &pbuf3, &plen))
20969 vim_free(pbuf2);
20970 return -1;
20972 *s = ch; /* Preserve the string */
20973 } while (plen == 0);
20975 if (plen > 0)
20977 /* Remember the length of the new string. */
20978 *fnamelen = len = plen + slen;
20979 vim_free(*bufp);
20980 if (len > len2)
20982 /* If there's not enough space in the currently allocated string,
20983 * then copy it to a buffer big enough.
20985 *fname= *bufp = vim_strnsave(p, len);
20986 if (*fname == NULL)
20987 return -1;
20989 else
20991 /* Transfer pbuf2 to being the main buffer (it's big enough) */
20992 *fname = *bufp = pbuf2;
20993 if (p != pbuf2)
20994 strncpy(*fname, p, plen);
20995 pbuf2 = NULL;
20997 /* Concat the next bit */
20998 strncpy(*fname + plen, s, slen);
20999 (*fname)[len] = '\0';
21001 vim_free(pbuf3);
21002 vim_free(pbuf2);
21003 return 0;
21007 * Get a pathname for a partial path.
21009 static int
21010 shortpath_for_partial(fnamep, bufp, fnamelen)
21011 char_u **fnamep;
21012 char_u **bufp;
21013 int *fnamelen;
21015 int sepcount, len, tflen;
21016 char_u *p;
21017 char_u *pbuf, *tfname;
21018 int hasTilde;
21020 /* Count up the path seperators from the RHS.. so we know which part
21021 * of the path to return.
21023 sepcount = 0;
21024 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
21025 if (vim_ispathsep(*p))
21026 ++sepcount;
21028 /* Need full path first (use expand_env() to remove a "~/") */
21029 hasTilde = (**fnamep == '~');
21030 if (hasTilde)
21031 pbuf = tfname = expand_env_save(*fnamep);
21032 else
21033 pbuf = tfname = FullName_save(*fnamep, FALSE);
21035 len = tflen = (int)STRLEN(tfname);
21037 if (!get_short_pathname(&tfname, &pbuf, &len))
21038 return -1;
21040 if (len == 0)
21042 /* Don't have a valid filename, so shorten the rest of the
21043 * path if we can. This CAN give us invalid 8.3 filenames, but
21044 * there's not a lot of point in guessing what it might be.
21046 len = tflen;
21047 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == -1)
21048 return -1;
21051 /* Count the paths backward to find the beginning of the desired string. */
21052 for (p = tfname + len - 1; p >= tfname; --p)
21054 #ifdef FEAT_MBYTE
21055 if (has_mbyte)
21056 p -= mb_head_off(tfname, p);
21057 #endif
21058 if (vim_ispathsep(*p))
21060 if (sepcount == 0 || (hasTilde && sepcount == 1))
21061 break;
21062 else
21063 sepcount --;
21066 if (hasTilde)
21068 --p;
21069 if (p >= tfname)
21070 *p = '~';
21071 else
21072 return -1;
21074 else
21075 ++p;
21077 /* Copy in the string - p indexes into tfname - allocated at pbuf */
21078 vim_free(*bufp);
21079 *fnamelen = (int)STRLEN(p);
21080 *bufp = pbuf;
21081 *fnamep = p;
21083 return 0;
21085 #endif /* WIN3264 */
21088 * Adjust a filename, according to a string of modifiers.
21089 * *fnamep must be NUL terminated when called. When returning, the length is
21090 * determined by *fnamelen.
21091 * Returns valid flags.
21092 * When there is an error, *fnamep is set to NULL.
21095 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
21096 char_u *src; /* string with modifiers */
21097 int *usedlen; /* characters after src that are used */
21098 char_u **fnamep; /* file name so far */
21099 char_u **bufp; /* buffer for allocated file name or NULL */
21100 int *fnamelen; /* length of fnamep */
21102 int valid = 0;
21103 char_u *tail;
21104 char_u *s, *p, *pbuf;
21105 char_u dirname[MAXPATHL];
21106 int c;
21107 int has_fullname = 0;
21108 #ifdef WIN3264
21109 int has_shortname = 0;
21110 #endif
21112 repeat:
21113 /* ":p" - full path/file_name */
21114 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
21116 has_fullname = 1;
21118 valid |= VALID_PATH;
21119 *usedlen += 2;
21121 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
21122 if ((*fnamep)[0] == '~'
21123 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
21124 && ((*fnamep)[1] == '/'
21125 # ifdef BACKSLASH_IN_FILENAME
21126 || (*fnamep)[1] == '\\'
21127 # endif
21128 || (*fnamep)[1] == NUL)
21130 #endif
21133 *fnamep = expand_env_save(*fnamep);
21134 vim_free(*bufp); /* free any allocated file name */
21135 *bufp = *fnamep;
21136 if (*fnamep == NULL)
21137 return -1;
21140 /* When "/." or "/.." is used: force expansion to get rid of it. */
21141 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
21143 if (vim_ispathsep(*p)
21144 && p[1] == '.'
21145 && (p[2] == NUL
21146 || vim_ispathsep(p[2])
21147 || (p[2] == '.'
21148 && (p[3] == NUL || vim_ispathsep(p[3])))))
21149 break;
21152 /* FullName_save() is slow, don't use it when not needed. */
21153 if (*p != NUL || !vim_isAbsName(*fnamep))
21155 *fnamep = FullName_save(*fnamep, *p != NUL);
21156 vim_free(*bufp); /* free any allocated file name */
21157 *bufp = *fnamep;
21158 if (*fnamep == NULL)
21159 return -1;
21162 /* Append a path separator to a directory. */
21163 if (mch_isdir(*fnamep))
21165 /* Make room for one or two extra characters. */
21166 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
21167 vim_free(*bufp); /* free any allocated file name */
21168 *bufp = *fnamep;
21169 if (*fnamep == NULL)
21170 return -1;
21171 add_pathsep(*fnamep);
21175 /* ":." - path relative to the current directory */
21176 /* ":~" - path relative to the home directory */
21177 /* ":8" - shortname path - postponed till after */
21178 while (src[*usedlen] == ':'
21179 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
21181 *usedlen += 2;
21182 if (c == '8')
21184 #ifdef WIN3264
21185 has_shortname = 1; /* Postpone this. */
21186 #endif
21187 continue;
21189 pbuf = NULL;
21190 /* Need full path first (use expand_env() to remove a "~/") */
21191 if (!has_fullname)
21193 if (c == '.' && **fnamep == '~')
21194 p = pbuf = expand_env_save(*fnamep);
21195 else
21196 p = pbuf = FullName_save(*fnamep, FALSE);
21198 else
21199 p = *fnamep;
21201 has_fullname = 0;
21203 if (p != NULL)
21205 if (c == '.')
21207 mch_dirname(dirname, MAXPATHL);
21208 s = shorten_fname(p, dirname);
21209 if (s != NULL)
21211 *fnamep = s;
21212 if (pbuf != NULL)
21214 vim_free(*bufp); /* free any allocated file name */
21215 *bufp = pbuf;
21216 pbuf = NULL;
21220 else
21222 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
21223 /* Only replace it when it starts with '~' */
21224 if (*dirname == '~')
21226 s = vim_strsave(dirname);
21227 if (s != NULL)
21229 *fnamep = s;
21230 vim_free(*bufp);
21231 *bufp = s;
21235 vim_free(pbuf);
21239 tail = gettail(*fnamep);
21240 *fnamelen = (int)STRLEN(*fnamep);
21242 /* ":h" - head, remove "/file_name", can be repeated */
21243 /* Don't remove the first "/" or "c:\" */
21244 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
21246 valid |= VALID_HEAD;
21247 *usedlen += 2;
21248 s = get_past_head(*fnamep);
21249 while (tail > s && after_pathsep(s, tail))
21250 --tail;
21251 *fnamelen = (int)(tail - *fnamep);
21252 #ifdef VMS
21253 if (*fnamelen > 0)
21254 *fnamelen += 1; /* the path separator is part of the path */
21255 #endif
21256 while (tail > s && !after_pathsep(s, tail))
21257 mb_ptr_back(*fnamep, tail);
21260 /* ":8" - shortname */
21261 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
21263 *usedlen += 2;
21264 #ifdef WIN3264
21265 has_shortname = 1;
21266 #endif
21269 #ifdef WIN3264
21270 /* Check shortname after we have done 'heads' and before we do 'tails'
21272 if (has_shortname)
21274 pbuf = NULL;
21275 /* Copy the string if it is shortened by :h */
21276 if (*fnamelen < (int)STRLEN(*fnamep))
21278 p = vim_strnsave(*fnamep, *fnamelen);
21279 if (p == 0)
21280 return -1;
21281 vim_free(*bufp);
21282 *bufp = *fnamep = p;
21285 /* Split into two implementations - makes it easier. First is where
21286 * there isn't a full name already, second is where there is.
21288 if (!has_fullname && !vim_isAbsName(*fnamep))
21290 if (shortpath_for_partial(fnamep, bufp, fnamelen) == -1)
21291 return -1;
21293 else
21295 int l;
21297 /* Simple case, already have the full-name
21298 * Nearly always shorter, so try first time. */
21299 l = *fnamelen;
21300 if (!get_short_pathname(fnamep, bufp, &l))
21301 return -1;
21303 if (l == 0)
21305 /* Couldn't find the filename.. search the paths.
21307 l = *fnamelen;
21308 if (shortpath_for_invalid_fname(fnamep, bufp, &l ) == -1)
21309 return -1;
21311 *fnamelen = l;
21314 #endif /* WIN3264 */
21316 /* ":t" - tail, just the basename */
21317 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
21319 *usedlen += 2;
21320 *fnamelen -= (int)(tail - *fnamep);
21321 *fnamep = tail;
21324 /* ":e" - extension, can be repeated */
21325 /* ":r" - root, without extension, can be repeated */
21326 while (src[*usedlen] == ':'
21327 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
21329 /* find a '.' in the tail:
21330 * - for second :e: before the current fname
21331 * - otherwise: The last '.'
21333 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
21334 s = *fnamep - 2;
21335 else
21336 s = *fnamep + *fnamelen - 1;
21337 for ( ; s > tail; --s)
21338 if (s[0] == '.')
21339 break;
21340 if (src[*usedlen + 1] == 'e') /* :e */
21342 if (s > tail)
21344 *fnamelen += (int)(*fnamep - (s + 1));
21345 *fnamep = s + 1;
21346 #ifdef VMS
21347 /* cut version from the extension */
21348 s = *fnamep + *fnamelen - 1;
21349 for ( ; s > *fnamep; --s)
21350 if (s[0] == ';')
21351 break;
21352 if (s > *fnamep)
21353 *fnamelen = s - *fnamep;
21354 #endif
21356 else if (*fnamep <= tail)
21357 *fnamelen = 0;
21359 else /* :r */
21361 if (s > tail) /* remove one extension */
21362 *fnamelen = (int)(s - *fnamep);
21364 *usedlen += 2;
21367 /* ":s?pat?foo?" - substitute */
21368 /* ":gs?pat?foo?" - global substitute */
21369 if (src[*usedlen] == ':'
21370 && (src[*usedlen + 1] == 's'
21371 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
21373 char_u *str;
21374 char_u *pat;
21375 char_u *sub;
21376 int sep;
21377 char_u *flags;
21378 int didit = FALSE;
21380 flags = (char_u *)"";
21381 s = src + *usedlen + 2;
21382 if (src[*usedlen + 1] == 'g')
21384 flags = (char_u *)"g";
21385 ++s;
21388 sep = *s++;
21389 if (sep)
21391 /* find end of pattern */
21392 p = vim_strchr(s, sep);
21393 if (p != NULL)
21395 pat = vim_strnsave(s, (int)(p - s));
21396 if (pat != NULL)
21398 s = p + 1;
21399 /* find end of substitution */
21400 p = vim_strchr(s, sep);
21401 if (p != NULL)
21403 sub = vim_strnsave(s, (int)(p - s));
21404 str = vim_strnsave(*fnamep, *fnamelen);
21405 if (sub != NULL && str != NULL)
21407 *usedlen = (int)(p + 1 - src);
21408 s = do_string_sub(str, pat, sub, flags);
21409 if (s != NULL)
21411 *fnamep = s;
21412 *fnamelen = (int)STRLEN(s);
21413 vim_free(*bufp);
21414 *bufp = s;
21415 didit = TRUE;
21418 vim_free(sub);
21419 vim_free(str);
21421 vim_free(pat);
21424 /* after using ":s", repeat all the modifiers */
21425 if (didit)
21426 goto repeat;
21430 return valid;
21434 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
21435 * "flags" can be "g" to do a global substitute.
21436 * Returns an allocated string, NULL for error.
21438 char_u *
21439 do_string_sub(str, pat, sub, flags)
21440 char_u *str;
21441 char_u *pat;
21442 char_u *sub;
21443 char_u *flags;
21445 int sublen;
21446 regmatch_T regmatch;
21447 int i;
21448 int do_all;
21449 char_u *tail;
21450 garray_T ga;
21451 char_u *ret;
21452 char_u *save_cpo;
21454 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
21455 save_cpo = p_cpo;
21456 p_cpo = (char_u *)"";
21458 ga_init2(&ga, 1, 200);
21460 do_all = (flags[0] == 'g');
21462 regmatch.rm_ic = p_ic;
21463 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
21464 if (regmatch.regprog != NULL)
21466 tail = str;
21467 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
21470 * Get some space for a temporary buffer to do the substitution
21471 * into. It will contain:
21472 * - The text up to where the match is.
21473 * - The substituted text.
21474 * - The text after the match.
21476 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
21477 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
21478 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
21480 ga_clear(&ga);
21481 break;
21484 /* copy the text up to where the match is */
21485 i = (int)(regmatch.startp[0] - tail);
21486 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
21487 /* add the substituted text */
21488 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
21489 + ga.ga_len + i, TRUE, TRUE, FALSE);
21490 ga.ga_len += i + sublen - 1;
21491 /* avoid getting stuck on a match with an empty string */
21492 if (tail == regmatch.endp[0])
21494 if (*tail == NUL)
21495 break;
21496 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
21497 ++ga.ga_len;
21499 else
21501 tail = regmatch.endp[0];
21502 if (*tail == NUL)
21503 break;
21505 if (!do_all)
21506 break;
21509 if (ga.ga_data != NULL)
21510 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
21512 vim_free(regmatch.regprog);
21515 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
21516 ga_clear(&ga);
21517 p_cpo = save_cpo;
21519 return ret;
21522 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */