Merged from the latest developing branch.
[MacVim.git] / src / eval.c
blobe008df24aacd897c0651be16b5a1db649e8739cd
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
11 * eval.c: Expression evaluation.
13 #if defined(MSDOS) || defined(MSWIN)
14 # include "vimio.h" /* for mch_open(), must be before vim.h */
15 #endif
17 #include "vim.h"
19 #ifdef AMIGA
20 # include <time.h> /* for strftime() */
21 #endif
23 #ifdef MACOS
24 # include <time.h> /* for time_t */
25 #endif
27 #ifdef HAVE_FCNTL_H
28 # include <fcntl.h>
29 #endif
31 #if defined(FEAT_EVAL) || defined(PROTO)
33 #define DICT_MAXNEST 100 /* maximum nesting of lists and dicts */
36 * In a hashtab item "hi_key" points to "di_key" in a dictitem.
37 * This avoids adding a pointer to the hashtab item.
38 * DI2HIKEY() converts a dictitem pointer to a hashitem key pointer.
39 * HIKEY2DI() converts a hashitem key pointer to a dictitem pointer.
40 * HI2DI() converts a hashitem pointer to a dictitem pointer.
42 static dictitem_T dumdi;
43 #define DI2HIKEY(di) ((di)->di_key)
44 #define HIKEY2DI(p) ((dictitem_T *)(p - (dumdi.di_key - (char_u *)&dumdi)))
45 #define HI2DI(hi) HIKEY2DI((hi)->hi_key)
48 * Structure returned by get_lval() and used by set_var_lval().
49 * For a plain name:
50 * "name" points to the variable name.
51 * "exp_name" is NULL.
52 * "tv" is NULL
53 * For a magic braces name:
54 * "name" points to the expanded variable name.
55 * "exp_name" is non-NULL, to be freed later.
56 * "tv" is NULL
57 * For an index in a list:
58 * "name" points to the (expanded) variable name.
59 * "exp_name" NULL or non-NULL, to be freed later.
60 * "tv" points to the (first) list item value
61 * "li" points to the (first) list item
62 * "range", "n1", "n2" and "empty2" indicate what items are used.
63 * For an existing Dict item:
64 * "name" points to the (expanded) variable name.
65 * "exp_name" NULL or non-NULL, to be freed later.
66 * "tv" points to the dict item value
67 * "newkey" is NULL
68 * For a non-existing Dict item:
69 * "name" points to the (expanded) variable name.
70 * "exp_name" NULL or non-NULL, to be freed later.
71 * "tv" points to the Dictionary typval_T
72 * "newkey" is the key for the new item.
74 typedef struct lval_S
76 char_u *ll_name; /* start of variable name (can be NULL) */
77 char_u *ll_exp_name; /* NULL or expanded name in allocated memory. */
78 typval_T *ll_tv; /* Typeval of item being used. If "newkey"
79 isn't NULL it's the Dict to which to add
80 the item. */
81 listitem_T *ll_li; /* The list item or NULL. */
82 list_T *ll_list; /* The list or NULL. */
83 int ll_range; /* TRUE when a [i:j] range was used */
84 long ll_n1; /* First index for list */
85 long ll_n2; /* Second index for list range */
86 int ll_empty2; /* Second index is empty: [i:] */
87 dict_T *ll_dict; /* The Dictionary or NULL */
88 dictitem_T *ll_di; /* The dictitem or NULL */
89 char_u *ll_newkey; /* New key for Dict in alloc. mem or NULL. */
90 } lval_T;
93 static char *e_letunexp = N_("E18: Unexpected characters in :let");
94 static char *e_listidx = N_("E684: list index out of range: %ld");
95 static char *e_undefvar = N_("E121: Undefined variable: %s");
96 static char *e_missbrac = N_("E111: Missing ']'");
97 static char *e_listarg = N_("E686: Argument of %s must be a List");
98 static char *e_listdictarg = N_("E712: Argument of %s must be a List or Dictionary");
99 static char *e_emptykey = N_("E713: Cannot use empty key for Dictionary");
100 static char *e_listreq = N_("E714: List required");
101 static char *e_dictreq = N_("E715: Dictionary required");
102 static char *e_toomanyarg = N_("E118: Too many arguments for function: %s");
103 static char *e_dictkey = N_("E716: Key not present in Dictionary: %s");
104 static char *e_funcexts = N_("E122: Function %s already exists, add ! to replace it");
105 static char *e_funcdict = N_("E717: Dictionary entry already exists");
106 static char *e_funcref = N_("E718: Funcref required");
107 static char *e_dictrange = N_("E719: Cannot use [:] with a Dictionary");
108 static char *e_letwrong = N_("E734: Wrong variable type for %s=");
109 static char *e_nofunc = N_("E130: Unknown function: %s");
110 static char *e_illvar = N_("E461: Illegal variable name: %s");
112 * All user-defined global variables are stored in dictionary "globvardict".
113 * "globvars_var" is the variable that is used for "g:".
115 static dict_T globvardict;
116 static dictitem_T globvars_var;
117 #define globvarht globvardict.dv_hashtab
120 * Old Vim variables such as "v:version" are also available without the "v:".
121 * Also in functions. We need a special hashtable for them.
123 static hashtab_T compat_hashtab;
126 * When recursively copying lists and dicts we need to remember which ones we
127 * have done to avoid endless recursiveness. This unique ID is used for that.
129 static int current_copyID = 0;
132 * Array to hold the hashtab with variables local to each sourced script.
133 * Each item holds a variable (nameless) that points to the dict_T.
135 typedef struct
137 dictitem_T sv_var;
138 dict_T sv_dict;
139 } scriptvar_T;
141 static garray_T ga_scripts = {0, 0, sizeof(scriptvar_T), 4, NULL};
142 #define SCRIPT_SV(id) (((scriptvar_T *)ga_scripts.ga_data)[(id) - 1])
143 #define SCRIPT_VARS(id) (SCRIPT_SV(id).sv_dict.dv_hashtab)
145 static int echo_attr = 0; /* attributes used for ":echo" */
147 /* Values for trans_function_name() argument: */
148 #define TFN_INT 1 /* internal function name OK */
149 #define TFN_QUIET 2 /* no error messages */
152 * Structure to hold info for a user function.
154 typedef struct ufunc ufunc_T;
156 struct ufunc
158 int uf_varargs; /* variable nr of arguments */
159 int uf_flags;
160 int uf_calls; /* nr of active calls */
161 garray_T uf_args; /* arguments */
162 garray_T uf_lines; /* function lines */
163 #ifdef FEAT_PROFILE
164 int uf_profiling; /* TRUE when func is being profiled */
165 /* profiling the function as a whole */
166 int uf_tm_count; /* nr of calls */
167 proftime_T uf_tm_total; /* time spend in function + children */
168 proftime_T uf_tm_self; /* time spend in function itself */
169 proftime_T uf_tm_children; /* time spent in children this call */
170 /* profiling the function per line */
171 int *uf_tml_count; /* nr of times line was executed */
172 proftime_T *uf_tml_total; /* time spend in a line + children */
173 proftime_T *uf_tml_self; /* time spend in a line itself */
174 proftime_T uf_tml_start; /* start time for current line */
175 proftime_T uf_tml_children; /* time spent in children for this line */
176 proftime_T uf_tml_wait; /* start wait time for current line */
177 int uf_tml_idx; /* index of line being timed; -1 if none */
178 int uf_tml_execed; /* line being timed was executed */
179 #endif
180 scid_T uf_script_ID; /* ID of script where function was defined,
181 used for s: variables */
182 int uf_refcount; /* for numbered function: reference count */
183 char_u uf_name[1]; /* name of function (actually longer); can
184 start with <SNR>123_ (<SNR> is K_SPECIAL
185 KS_EXTRA KE_SNR) */
188 /* function flags */
189 #define FC_ABORT 1 /* abort function on error */
190 #define FC_RANGE 2 /* function accepts range */
191 #define FC_DICT 4 /* Dict function, uses "self" */
194 * All user-defined functions are found in this hashtable.
196 static hashtab_T func_hashtab;
198 /* The names of packages that once were loaded are remembered. */
199 static garray_T ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
201 /* list heads for garbage collection */
202 static dict_T *first_dict = NULL; /* list of all dicts */
203 static list_T *first_list = NULL; /* list of all lists */
205 /* From user function to hashitem and back. */
206 static ufunc_T dumuf;
207 #define UF2HIKEY(fp) ((fp)->uf_name)
208 #define HIKEY2UF(p) ((ufunc_T *)(p - (dumuf.uf_name - (char_u *)&dumuf)))
209 #define HI2UF(hi) HIKEY2UF((hi)->hi_key)
211 #define FUNCARG(fp, j) ((char_u **)(fp->uf_args.ga_data))[j]
212 #define FUNCLINE(fp, j) ((char_u **)(fp->uf_lines.ga_data))[j]
214 #define MAX_FUNC_ARGS 20 /* maximum number of function arguments */
215 #define VAR_SHORT_LEN 20 /* short variable name length */
216 #define FIXVAR_CNT 12 /* number of fixed variables */
218 /* structure to hold info for a function that is currently being executed. */
219 typedef struct funccall_S funccall_T;
221 struct funccall_S
223 ufunc_T *func; /* function being called */
224 int linenr; /* next line to be executed */
225 int returned; /* ":return" used */
226 struct /* fixed variables for arguments */
228 dictitem_T var; /* variable (without room for name) */
229 char_u room[VAR_SHORT_LEN]; /* room for the name */
230 } fixvar[FIXVAR_CNT];
231 dict_T l_vars; /* l: local function variables */
232 dictitem_T l_vars_var; /* variable for l: scope */
233 dict_T l_avars; /* a: argument variables */
234 dictitem_T l_avars_var; /* variable for a: scope */
235 list_T l_varlist; /* list for a:000 */
236 listitem_T l_listitems[MAX_FUNC_ARGS]; /* listitems for a:000 */
237 typval_T *rettv; /* return value */
238 linenr_T breakpoint; /* next line with breakpoint or zero */
239 int dbg_tick; /* debug_tick when breakpoint was set */
240 int level; /* top nesting level of executed function */
241 #ifdef FEAT_PROFILE
242 proftime_T prof_child; /* time spent in a child */
243 #endif
244 funccall_T *caller; /* calling function or NULL */
248 * Info used by a ":for" loop.
250 typedef struct
252 int fi_semicolon; /* TRUE if ending in '; var]' */
253 int fi_varcount; /* nr of variables in the list */
254 listwatch_T fi_lw; /* keep an eye on the item used. */
255 list_T *fi_list; /* list being used */
256 } forinfo_T;
259 * Struct used by trans_function_name()
261 typedef struct
263 dict_T *fd_dict; /* Dictionary used */
264 char_u *fd_newkey; /* new key in "dict" in allocated memory */
265 dictitem_T *fd_di; /* Dictionary item used */
266 } funcdict_T;
270 * Array to hold the value of v: variables.
271 * The value is in a dictitem, so that it can also be used in the v: scope.
272 * The reason to use this table anyway is for very quick access to the
273 * variables with the VV_ defines.
275 #include "version.h"
277 /* values for vv_flags: */
278 #define VV_COMPAT 1 /* compatible, also used without "v:" */
279 #define VV_RO 2 /* read-only */
280 #define VV_RO_SBX 4 /* read-only in the sandbox */
282 #define VV_NAME(s, t) s, {{t}}, {0}
284 static struct vimvar
286 char *vv_name; /* name of variable, without v: */
287 dictitem_T vv_di; /* value and name for key */
288 char vv_filler[16]; /* space for LONGEST name below!!! */
289 char vv_flags; /* VV_COMPAT, VV_RO, VV_RO_SBX */
290 } vimvars[VV_LEN] =
293 * The order here must match the VV_ defines in vim.h!
294 * Initializing a union does not work, leave tv.vval empty to get zero's.
296 {VV_NAME("count", VAR_NUMBER), VV_COMPAT+VV_RO},
297 {VV_NAME("count1", VAR_NUMBER), VV_RO},
298 {VV_NAME("prevcount", VAR_NUMBER), VV_RO},
299 {VV_NAME("errmsg", VAR_STRING), VV_COMPAT},
300 {VV_NAME("warningmsg", VAR_STRING), 0},
301 {VV_NAME("statusmsg", VAR_STRING), 0},
302 {VV_NAME("shell_error", VAR_NUMBER), VV_COMPAT+VV_RO},
303 {VV_NAME("this_session", VAR_STRING), VV_COMPAT},
304 {VV_NAME("version", VAR_NUMBER), VV_COMPAT+VV_RO},
305 {VV_NAME("lnum", VAR_NUMBER), VV_RO_SBX},
306 {VV_NAME("termresponse", VAR_STRING), VV_RO},
307 {VV_NAME("fname", VAR_STRING), VV_RO},
308 {VV_NAME("lang", VAR_STRING), VV_RO},
309 {VV_NAME("lc_time", VAR_STRING), VV_RO},
310 {VV_NAME("ctype", VAR_STRING), VV_RO},
311 {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
312 {VV_NAME("charconvert_to", VAR_STRING), VV_RO},
313 {VV_NAME("fname_in", VAR_STRING), VV_RO},
314 {VV_NAME("fname_out", VAR_STRING), VV_RO},
315 {VV_NAME("fname_new", VAR_STRING), VV_RO},
316 {VV_NAME("fname_diff", VAR_STRING), VV_RO},
317 {VV_NAME("cmdarg", VAR_STRING), VV_RO},
318 {VV_NAME("foldstart", VAR_NUMBER), VV_RO_SBX},
319 {VV_NAME("foldend", VAR_NUMBER), VV_RO_SBX},
320 {VV_NAME("folddashes", VAR_STRING), VV_RO_SBX},
321 {VV_NAME("foldlevel", VAR_NUMBER), VV_RO_SBX},
322 {VV_NAME("progname", VAR_STRING), VV_RO},
323 {VV_NAME("servername", VAR_STRING), VV_RO},
324 {VV_NAME("dying", VAR_NUMBER), VV_RO},
325 {VV_NAME("exception", VAR_STRING), VV_RO},
326 {VV_NAME("throwpoint", VAR_STRING), VV_RO},
327 {VV_NAME("register", VAR_STRING), VV_RO},
328 {VV_NAME("cmdbang", VAR_NUMBER), VV_RO},
329 {VV_NAME("insertmode", VAR_STRING), VV_RO},
330 {VV_NAME("val", VAR_UNKNOWN), VV_RO},
331 {VV_NAME("key", VAR_UNKNOWN), VV_RO},
332 {VV_NAME("profiling", VAR_NUMBER), VV_RO},
333 {VV_NAME("fcs_reason", VAR_STRING), VV_RO},
334 {VV_NAME("fcs_choice", VAR_STRING), 0},
335 {VV_NAME("beval_bufnr", VAR_NUMBER), VV_RO},
336 {VV_NAME("beval_winnr", VAR_NUMBER), VV_RO},
337 {VV_NAME("beval_lnum", VAR_NUMBER), VV_RO},
338 {VV_NAME("beval_col", VAR_NUMBER), VV_RO},
339 {VV_NAME("beval_text", VAR_STRING), VV_RO},
340 {VV_NAME("scrollstart", VAR_STRING), 0},
341 {VV_NAME("swapname", VAR_STRING), VV_RO},
342 {VV_NAME("swapchoice", VAR_STRING), 0},
343 {VV_NAME("swapcommand", VAR_STRING), VV_RO},
344 {VV_NAME("char", VAR_STRING), VV_RO},
345 {VV_NAME("mouse_win", VAR_NUMBER), 0},
346 {VV_NAME("mouse_lnum", VAR_NUMBER), 0},
347 {VV_NAME("mouse_col", VAR_NUMBER), 0},
348 {VV_NAME("operator", VAR_STRING), VV_RO},
351 /* shorthand */
352 #define vv_type vv_di.di_tv.v_type
353 #define vv_nr vv_di.di_tv.vval.v_number
354 #define vv_str vv_di.di_tv.vval.v_string
355 #define vv_tv vv_di.di_tv
358 * The v: variables are stored in dictionary "vimvardict".
359 * "vimvars_var" is the variable that is used for the "l:" scope.
361 static dict_T vimvardict;
362 static dictitem_T vimvars_var;
363 #define vimvarht vimvardict.dv_hashtab
365 static void prepare_vimvar __ARGS((int idx, typval_T *save_tv));
366 static void restore_vimvar __ARGS((int idx, typval_T *save_tv));
367 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
368 static int call_vim_function __ARGS((char_u *func, int argc, char_u **argv, int safe, typval_T *rettv));
369 #endif
370 static int ex_let_vars __ARGS((char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars));
371 static char_u *skip_var_list __ARGS((char_u *arg, int *var_count, int *semicolon));
372 static char_u *skip_var_one __ARGS((char_u *arg));
373 static void list_hashtable_vars __ARGS((hashtab_T *ht, char_u *prefix, int empty, int *first));
374 static void list_glob_vars __ARGS((int *first));
375 static void list_buf_vars __ARGS((int *first));
376 static void list_win_vars __ARGS((int *first));
377 #ifdef FEAT_WINDOWS
378 static void list_tab_vars __ARGS((int *first));
379 #endif
380 static void list_vim_vars __ARGS((int *first));
381 static void list_script_vars __ARGS((int *first));
382 static void list_func_vars __ARGS((int *first));
383 static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg, int *first));
384 static char_u *ex_let_one __ARGS((char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op));
385 static int check_changedtick __ARGS((char_u *arg));
386 static char_u *get_lval __ARGS((char_u *name, typval_T *rettv, lval_T *lp, int unlet, int skip, int quiet, int fne_flags));
387 static void clear_lval __ARGS((lval_T *lp));
388 static void set_var_lval __ARGS((lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op));
389 static int tv_op __ARGS((typval_T *tv1, typval_T *tv2, char_u *op));
390 static void list_add_watch __ARGS((list_T *l, listwatch_T *lw));
391 static void list_rem_watch __ARGS((list_T *l, listwatch_T *lwrem));
392 static void list_fix_watch __ARGS((list_T *l, listitem_T *item));
393 static void ex_unletlock __ARGS((exarg_T *eap, char_u *argstart, int deep));
394 static int do_unlet_var __ARGS((lval_T *lp, char_u *name_end, int forceit));
395 static int do_lock_var __ARGS((lval_T *lp, char_u *name_end, int deep, int lock));
396 static void item_lock __ARGS((typval_T *tv, int deep, int lock));
397 static int tv_islocked __ARGS((typval_T *tv));
399 static int eval0 __ARGS((char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate));
400 static int eval1 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
401 static int eval2 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
402 static int eval3 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
403 static int eval4 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
404 static int eval5 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
405 static int eval6 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
406 static int eval7 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
408 static int eval_index __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
409 static int get_option_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
410 static int get_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
411 static int get_lit_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
412 static int get_list_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
413 static int rettv_list_alloc __ARGS((typval_T *rettv));
414 static listitem_T *listitem_alloc __ARGS((void));
415 static void listitem_free __ARGS((listitem_T *item));
416 static void listitem_remove __ARGS((list_T *l, listitem_T *item));
417 static long list_len __ARGS((list_T *l));
418 static int list_equal __ARGS((list_T *l1, list_T *l2, int ic));
419 static int dict_equal __ARGS((dict_T *d1, dict_T *d2, int ic));
420 static int tv_equal __ARGS((typval_T *tv1, typval_T *tv2, int ic));
421 static listitem_T *list_find __ARGS((list_T *l, long n));
422 static long list_find_nr __ARGS((list_T *l, long idx, int *errorp));
423 static long list_idx_of_item __ARGS((list_T *l, listitem_T *item));
424 static void list_append __ARGS((list_T *l, listitem_T *item));
425 static int list_append_tv __ARGS((list_T *l, typval_T *tv));
426 static int list_append_string __ARGS((list_T *l, char_u *str, int len));
427 static int list_append_number __ARGS((list_T *l, varnumber_T n));
428 static int list_insert_tv __ARGS((list_T *l, typval_T *tv, listitem_T *item));
429 static int list_extend __ARGS((list_T *l1, list_T *l2, listitem_T *bef));
430 static int list_concat __ARGS((list_T *l1, list_T *l2, typval_T *tv));
431 static list_T *list_copy __ARGS((list_T *orig, int deep, int copyID));
432 static void list_remove __ARGS((list_T *l, listitem_T *item, listitem_T *item2));
433 static char_u *list2string __ARGS((typval_T *tv, int copyID));
434 static int list_join __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo, int copyID));
435 static void set_ref_in_ht __ARGS((hashtab_T *ht, int copyID));
436 static void set_ref_in_list __ARGS((list_T *l, int copyID));
437 static void set_ref_in_item __ARGS((typval_T *tv, int copyID));
438 static void dict_unref __ARGS((dict_T *d));
439 static void dict_free __ARGS((dict_T *d, int recurse));
440 static dictitem_T *dictitem_alloc __ARGS((char_u *key));
441 static dictitem_T *dictitem_copy __ARGS((dictitem_T *org));
442 static void dictitem_remove __ARGS((dict_T *dict, dictitem_T *item));
443 static void dictitem_free __ARGS((dictitem_T *item));
444 static dict_T *dict_copy __ARGS((dict_T *orig, int deep, int copyID));
445 static int dict_add __ARGS((dict_T *d, dictitem_T *item));
446 static long dict_len __ARGS((dict_T *d));
447 static dictitem_T *dict_find __ARGS((dict_T *d, char_u *key, int len));
448 static char_u *dict2string __ARGS((typval_T *tv, int copyID));
449 static int get_dict_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
450 static char_u *echo_string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
451 static char_u *tv2string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
452 static char_u *string_quote __ARGS((char_u *str, int function));
453 static int get_env_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
454 static int find_internal_func __ARGS((char_u *name));
455 static char_u *deref_func_name __ARGS((char_u *name, int *lenp));
456 static int get_func_tv __ARGS((char_u *name, int len, typval_T *rettv, char_u **arg, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
457 static int call_func __ARGS((char_u *name, int len, typval_T *rettv, int argcount, typval_T *argvars, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
458 static void emsg_funcname __ARGS((char *ermsg, char_u *name));
460 static void f_add __ARGS((typval_T *argvars, typval_T *rettv));
461 static void f_append __ARGS((typval_T *argvars, typval_T *rettv));
462 static void f_argc __ARGS((typval_T *argvars, typval_T *rettv));
463 static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv));
464 static void f_argv __ARGS((typval_T *argvars, typval_T *rettv));
465 static void f_browse __ARGS((typval_T *argvars, typval_T *rettv));
466 static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv));
467 static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv));
468 static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv));
469 static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv));
470 static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv));
471 static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv));
472 static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv));
473 static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv));
474 static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv));
475 static void f_call __ARGS((typval_T *argvars, typval_T *rettv));
476 static void f_changenr __ARGS((typval_T *argvars, typval_T *rettv));
477 static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv));
478 static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv));
479 static void f_clearmatches __ARGS((typval_T *argvars, typval_T *rettv));
480 static void f_col __ARGS((typval_T *argvars, typval_T *rettv));
481 #if defined(FEAT_INS_EXPAND)
482 static void f_complete __ARGS((typval_T *argvars, typval_T *rettv));
483 static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv));
484 static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv));
485 #endif
486 static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv));
487 static void f_copy __ARGS((typval_T *argvars, typval_T *rettv));
488 static void f_count __ARGS((typval_T *argvars, typval_T *rettv));
489 static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv));
490 static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv));
491 static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv));
492 static void f_delete __ARGS((typval_T *argvars, typval_T *rettv));
493 static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv));
494 static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv));
495 static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv));
496 static void f_empty __ARGS((typval_T *argvars, typval_T *rettv));
497 static void f_escape __ARGS((typval_T *argvars, typval_T *rettv));
498 static void f_eval __ARGS((typval_T *argvars, typval_T *rettv));
499 static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv));
500 static void f_executable __ARGS((typval_T *argvars, typval_T *rettv));
501 static void f_exists __ARGS((typval_T *argvars, typval_T *rettv));
502 static void f_expand __ARGS((typval_T *argvars, typval_T *rettv));
503 static void f_extend __ARGS((typval_T *argvars, typval_T *rettv));
504 static void f_feedkeys __ARGS((typval_T *argvars, typval_T *rettv));
505 static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv));
506 static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv));
507 static void f_filter __ARGS((typval_T *argvars, typval_T *rettv));
508 static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv));
509 static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv));
510 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
511 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
513 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
514 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
516 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
517 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
520 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
521 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
523 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
524 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
525 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
526 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
528 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
529 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
531 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
532 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
533 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
534 static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv));
535 static void f_getpid __ARGS((typval_T *argvars, typval_T *rettv));
536 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
537 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
542 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
546 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
547 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
548 static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv));
549 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
551 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
552 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
590 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
591 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
592 #ifdef vim_mkdir
593 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
594 #endif
595 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
596 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
603 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
604 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
605 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
606 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
607 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
608 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
609 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
610 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
611 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
618 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
619 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
620 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
621 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
622 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
623 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
624 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
625 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
626 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
627 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
628 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
629 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
630 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
631 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
632 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
633 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
634 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
635 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
636 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
637 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
638 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
639 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
640 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
641 #ifdef HAVE_STRFTIME
642 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
643 #endif
644 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
645 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
646 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
647 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
648 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
649 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
650 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
651 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
652 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
653 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
654 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
655 static void f_synstack __ARGS((typval_T *argvars, typval_T *rettv));
656 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
657 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
667 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
668 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
669 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
670 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
671 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
672 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
673 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
674 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
675 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
676 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
677 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
678 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
679 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
680 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
682 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
683 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
684 static int get_env_len __ARGS((char_u **arg));
685 static int get_id_len __ARGS((char_u **arg));
686 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
687 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
688 #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */
689 #define FNE_CHECK_START 2 /* find_name_end(): check name starts with
690 valid character */
691 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
692 static int eval_isnamec __ARGS((int c));
693 static int eval_isnamec1 __ARGS((int c));
694 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
695 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
696 static typval_T *alloc_tv __ARGS((void));
697 static typval_T *alloc_string_tv __ARGS((char_u *string));
698 static void init_tv __ARGS((typval_T *varp));
699 static long get_tv_number __ARGS((typval_T *varp));
700 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
701 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
702 static char_u *get_tv_string __ARGS((typval_T *varp));
703 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
704 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
705 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
706 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
707 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
708 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
709 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
710 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
711 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
712 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
713 static int var_check_ro __ARGS((int flags, char_u *name));
714 static int var_check_fixed __ARGS((int flags, char_u *name));
715 static int tv_check_lock __ARGS((int lock, char_u *name));
716 static void copy_tv __ARGS((typval_T *from, typval_T *to));
717 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
718 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
719 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
720 static int eval_fname_script __ARGS((char_u *p));
721 static int eval_fname_sid __ARGS((char_u *p));
722 static void list_func_head __ARGS((ufunc_T *fp, int indent));
723 static ufunc_T *find_func __ARGS((char_u *name));
724 static int function_exists __ARGS((char_u *name));
725 static int builtin_function __ARGS((char_u *name));
726 #ifdef FEAT_PROFILE
727 static void func_do_profile __ARGS((ufunc_T *fp));
728 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
729 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
730 static int
731 # ifdef __BORLANDC__
732 _RTLENTRYF
733 # endif
734 prof_total_cmp __ARGS((const void *s1, const void *s2));
735 static int
736 # ifdef __BORLANDC__
737 _RTLENTRYF
738 # endif
739 prof_self_cmp __ARGS((const void *s1, const void *s2));
740 #endif
741 static int script_autoload __ARGS((char_u *name, int reload));
742 static char_u *autoload_name __ARGS((char_u *name));
743 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
744 static void func_free __ARGS((ufunc_T *fp));
745 static void func_unref __ARGS((char_u *name));
746 static void func_ref __ARGS((char_u *name));
747 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));
748 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
749 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
750 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
751 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
752 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
753 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
755 /* Character used as separated in autoload function/variable names. */
756 #define AUTOLOAD_CHAR '#'
759 * Initialize the global and v: variables.
761 void
762 eval_init()
764 int i;
765 struct vimvar *p;
767 init_var_dict(&globvardict, &globvars_var);
768 init_var_dict(&vimvardict, &vimvars_var);
769 hash_init(&compat_hashtab);
770 hash_init(&func_hashtab);
772 for (i = 0; i < VV_LEN; ++i)
774 p = &vimvars[i];
775 STRCPY(p->vv_di.di_key, p->vv_name);
776 if (p->vv_flags & VV_RO)
777 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
778 else if (p->vv_flags & VV_RO_SBX)
779 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
780 else
781 p->vv_di.di_flags = DI_FLAGS_FIX;
783 /* add to v: scope dict, unless the value is not always available */
784 if (p->vv_type != VAR_UNKNOWN)
785 hash_add(&vimvarht, p->vv_di.di_key);
786 if (p->vv_flags & VV_COMPAT)
787 /* add to compat scope dict */
788 hash_add(&compat_hashtab, p->vv_di.di_key);
792 #if defined(EXITFREE) || defined(PROTO)
793 void
794 eval_clear()
796 int i;
797 struct vimvar *p;
799 for (i = 0; i < VV_LEN; ++i)
801 p = &vimvars[i];
802 if (p->vv_di.di_tv.v_type == VAR_STRING)
804 vim_free(p->vv_di.di_tv.vval.v_string);
805 p->vv_di.di_tv.vval.v_string = NULL;
808 hash_clear(&vimvarht);
809 hash_clear(&compat_hashtab);
811 /* script-local variables */
812 for (i = 1; i <= ga_scripts.ga_len; ++i)
813 vars_clear(&SCRIPT_VARS(i));
814 ga_clear(&ga_scripts);
815 free_scriptnames();
817 /* global variables */
818 vars_clear(&globvarht);
820 /* functions */
821 free_all_functions();
822 hash_clear(&func_hashtab);
824 /* autoloaded script names */
825 ga_clear_strings(&ga_loaded);
827 /* unreferenced lists and dicts */
828 (void)garbage_collect();
830 #endif
833 * Return the name of the executed function.
835 char_u *
836 func_name(cookie)
837 void *cookie;
839 return ((funccall_T *)cookie)->func->uf_name;
843 * Return the address holding the next breakpoint line for a funccall cookie.
845 linenr_T *
846 func_breakpoint(cookie)
847 void *cookie;
849 return &((funccall_T *)cookie)->breakpoint;
853 * Return the address holding the debug tick for a funccall cookie.
855 int *
856 func_dbg_tick(cookie)
857 void *cookie;
859 return &((funccall_T *)cookie)->dbg_tick;
863 * Return the nesting level for a funccall cookie.
866 func_level(cookie)
867 void *cookie;
869 return ((funccall_T *)cookie)->level;
872 /* pointer to funccal for currently active function */
873 funccall_T *current_funccal = NULL;
876 * Return TRUE when a function was ended by a ":return" command.
879 current_func_returned()
881 return current_funccal->returned;
886 * Set an internal variable to a string value. Creates the variable if it does
887 * not already exist.
889 void
890 set_internal_string_var(name, value)
891 char_u *name;
892 char_u *value;
894 char_u *val;
895 typval_T *tvp;
897 val = vim_strsave(value);
898 if (val != NULL)
900 tvp = alloc_string_tv(val);
901 if (tvp != NULL)
903 set_var(name, tvp, FALSE);
904 free_tv(tvp);
909 static lval_T *redir_lval = NULL;
910 static garray_T redir_ga; /* only valid when redir_lval is not NULL */
911 static char_u *redir_endp = NULL;
912 static char_u *redir_varname = NULL;
915 * Start recording command output to a variable
916 * Returns OK if successfully completed the setup. FAIL otherwise.
919 var_redir_start(name, append)
920 char_u *name;
921 int append; /* append to an existing variable */
923 int save_emsg;
924 int err;
925 typval_T tv;
927 /* Make sure a valid variable name is specified */
928 if (!eval_isnamec1(*name))
930 EMSG(_(e_invarg));
931 return FAIL;
934 redir_varname = vim_strsave(name);
935 if (redir_varname == NULL)
936 return FAIL;
938 redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
939 if (redir_lval == NULL)
941 var_redir_stop();
942 return FAIL;
945 /* The output is stored in growarray "redir_ga" until redirection ends. */
946 ga_init2(&redir_ga, (int)sizeof(char), 500);
948 /* Parse the variable name (can be a dict or list entry). */
949 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
950 FNE_CHECK_START);
951 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
953 if (redir_endp != NULL && *redir_endp != NUL)
954 /* Trailing characters are present after the variable name */
955 EMSG(_(e_trailing));
956 else
957 EMSG(_(e_invarg));
958 var_redir_stop();
959 return FAIL;
962 /* check if we can write to the variable: set it to or append an empty
963 * string */
964 save_emsg = did_emsg;
965 did_emsg = FALSE;
966 tv.v_type = VAR_STRING;
967 tv.vval.v_string = (char_u *)"";
968 if (append)
969 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
970 else
971 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
972 err = did_emsg;
973 did_emsg |= save_emsg;
974 if (err)
976 var_redir_stop();
977 return FAIL;
979 if (redir_lval->ll_newkey != NULL)
981 /* Dictionary item was created, don't do it again. */
982 vim_free(redir_lval->ll_newkey);
983 redir_lval->ll_newkey = NULL;
986 return OK;
990 * Append "value[value_len]" to the variable set by var_redir_start().
991 * The actual appending is postponed until redirection ends, because the value
992 * appended may in fact be the string we write to, changing it may cause freed
993 * memory to be used:
994 * :redir => foo
995 * :let foo
996 * :redir END
998 void
999 var_redir_str(value, value_len)
1000 char_u *value;
1001 int value_len;
1003 int len;
1005 if (redir_lval == NULL)
1006 return;
1008 if (value_len == -1)
1009 len = (int)STRLEN(value); /* Append the entire string */
1010 else
1011 len = value_len; /* Append only "value_len" characters */
1013 if (ga_grow(&redir_ga, len) == OK)
1015 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1016 redir_ga.ga_len += len;
1018 else
1019 var_redir_stop();
1023 * Stop redirecting command output to a variable.
1025 void
1026 var_redir_stop()
1028 typval_T tv;
1030 if (redir_lval != NULL)
1032 /* Append the trailing NUL. */
1033 ga_append(&redir_ga, NUL);
1035 /* Assign the text to the variable. */
1036 tv.v_type = VAR_STRING;
1037 tv.vval.v_string = redir_ga.ga_data;
1038 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1039 vim_free(tv.vval.v_string);
1041 clear_lval(redir_lval);
1042 vim_free(redir_lval);
1043 redir_lval = NULL;
1045 vim_free(redir_varname);
1046 redir_varname = NULL;
1049 # if defined(FEAT_MBYTE) || defined(PROTO)
1051 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1052 char_u *enc_from;
1053 char_u *enc_to;
1054 char_u *fname_from;
1055 char_u *fname_to;
1057 int err = FALSE;
1059 set_vim_var_string(VV_CC_FROM, enc_from, -1);
1060 set_vim_var_string(VV_CC_TO, enc_to, -1);
1061 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1062 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1063 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1064 err = TRUE;
1065 set_vim_var_string(VV_CC_FROM, NULL, -1);
1066 set_vim_var_string(VV_CC_TO, NULL, -1);
1067 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1068 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1070 if (err)
1071 return FAIL;
1072 return OK;
1074 # endif
1076 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1078 eval_printexpr(fname, args)
1079 char_u *fname;
1080 char_u *args;
1082 int err = FALSE;
1084 set_vim_var_string(VV_FNAME_IN, fname, -1);
1085 set_vim_var_string(VV_CMDARG, args, -1);
1086 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1087 err = TRUE;
1088 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1089 set_vim_var_string(VV_CMDARG, NULL, -1);
1091 if (err)
1093 mch_remove(fname);
1094 return FAIL;
1096 return OK;
1098 # endif
1100 # if defined(FEAT_DIFF) || defined(PROTO)
1101 void
1102 eval_diff(origfile, newfile, outfile)
1103 char_u *origfile;
1104 char_u *newfile;
1105 char_u *outfile;
1107 int err = FALSE;
1109 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1110 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1111 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1112 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1113 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1114 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1115 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1118 void
1119 eval_patch(origfile, difffile, outfile)
1120 char_u *origfile;
1121 char_u *difffile;
1122 char_u *outfile;
1124 int err;
1126 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1127 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1128 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1129 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1130 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1131 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1132 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1134 # endif
1137 * Top level evaluation function, returning a boolean.
1138 * Sets "error" to TRUE if there was an error.
1139 * Return TRUE or FALSE.
1142 eval_to_bool(arg, error, nextcmd, skip)
1143 char_u *arg;
1144 int *error;
1145 char_u **nextcmd;
1146 int skip; /* only parse, don't execute */
1148 typval_T tv;
1149 int retval = FALSE;
1151 if (skip)
1152 ++emsg_skip;
1153 if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1154 *error = TRUE;
1155 else
1157 *error = FALSE;
1158 if (!skip)
1160 retval = (get_tv_number_chk(&tv, error) != 0);
1161 clear_tv(&tv);
1164 if (skip)
1165 --emsg_skip;
1167 return retval;
1171 * Top level evaluation function, returning a string. If "skip" is TRUE,
1172 * only parsing to "nextcmd" is done, without reporting errors. Return
1173 * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1175 char_u *
1176 eval_to_string_skip(arg, nextcmd, skip)
1177 char_u *arg;
1178 char_u **nextcmd;
1179 int skip; /* only parse, don't execute */
1181 typval_T tv;
1182 char_u *retval;
1184 if (skip)
1185 ++emsg_skip;
1186 if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1187 retval = NULL;
1188 else
1190 retval = vim_strsave(get_tv_string(&tv));
1191 clear_tv(&tv);
1193 if (skip)
1194 --emsg_skip;
1196 return retval;
1200 * Skip over an expression at "*pp".
1201 * Return FAIL for an error, OK otherwise.
1204 skip_expr(pp)
1205 char_u **pp;
1207 typval_T rettv;
1209 *pp = skipwhite(*pp);
1210 return eval1(pp, &rettv, FALSE);
1214 * Top level evaluation function, returning a string.
1215 * Return pointer to allocated memory, or NULL for failure.
1217 char_u *
1218 eval_to_string(arg, nextcmd, dolist)
1219 char_u *arg;
1220 char_u **nextcmd;
1221 int dolist; /* turn List into sequence of lines */
1223 typval_T tv;
1224 char_u *retval;
1225 garray_T ga;
1227 if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1228 retval = NULL;
1229 else
1231 if (dolist && tv.v_type == VAR_LIST)
1233 ga_init2(&ga, (int)sizeof(char), 80);
1234 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1235 ga_append(&ga, NUL);
1236 retval = (char_u *)ga.ga_data;
1238 else
1239 retval = vim_strsave(get_tv_string(&tv));
1240 clear_tv(&tv);
1243 return retval;
1247 * Call eval_to_string() without using current local variables and using
1248 * textlock. When "use_sandbox" is TRUE use the sandbox.
1250 char_u *
1251 eval_to_string_safe(arg, nextcmd, use_sandbox)
1252 char_u *arg;
1253 char_u **nextcmd;
1254 int use_sandbox;
1256 char_u *retval;
1257 void *save_funccalp;
1259 save_funccalp = save_funccal();
1260 if (use_sandbox)
1261 ++sandbox;
1262 ++textlock;
1263 retval = eval_to_string(arg, nextcmd, FALSE);
1264 if (use_sandbox)
1265 --sandbox;
1266 --textlock;
1267 restore_funccal(save_funccalp);
1268 return retval;
1272 * Top level evaluation function, returning a number.
1273 * Evaluates "expr" silently.
1274 * Returns -1 for an error.
1277 eval_to_number(expr)
1278 char_u *expr;
1280 typval_T rettv;
1281 int retval;
1282 char_u *p = skipwhite(expr);
1284 ++emsg_off;
1286 if (eval1(&p, &rettv, TRUE) == FAIL)
1287 retval = -1;
1288 else
1290 retval = get_tv_number_chk(&rettv, NULL);
1291 clear_tv(&rettv);
1293 --emsg_off;
1295 return retval;
1299 * Prepare v: variable "idx" to be used.
1300 * Save the current typeval in "save_tv".
1301 * When not used yet add the variable to the v: hashtable.
1303 static void
1304 prepare_vimvar(idx, save_tv)
1305 int idx;
1306 typval_T *save_tv;
1308 *save_tv = vimvars[idx].vv_tv;
1309 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1310 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1314 * Restore v: variable "idx" to typeval "save_tv".
1315 * When no longer defined, remove the variable from the v: hashtable.
1317 static void
1318 restore_vimvar(idx, save_tv)
1319 int idx;
1320 typval_T *save_tv;
1322 hashitem_T *hi;
1324 vimvars[idx].vv_tv = *save_tv;
1325 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1327 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1328 if (HASHITEM_EMPTY(hi))
1329 EMSG2(_(e_intern2), "restore_vimvar()");
1330 else
1331 hash_remove(&vimvarht, hi);
1335 #if defined(FEAT_SPELL) || defined(PROTO)
1337 * Evaluate an expression to a list with suggestions.
1338 * For the "expr:" part of 'spellsuggest'.
1340 list_T *
1341 eval_spell_expr(badword, expr)
1342 char_u *badword;
1343 char_u *expr;
1345 typval_T save_val;
1346 typval_T rettv;
1347 list_T *list = NULL;
1348 char_u *p = skipwhite(expr);
1350 /* Set "v:val" to the bad word. */
1351 prepare_vimvar(VV_VAL, &save_val);
1352 vimvars[VV_VAL].vv_type = VAR_STRING;
1353 vimvars[VV_VAL].vv_str = badword;
1354 if (p_verbose == 0)
1355 ++emsg_off;
1357 if (eval1(&p, &rettv, TRUE) == OK)
1359 if (rettv.v_type != VAR_LIST)
1360 clear_tv(&rettv);
1361 else
1362 list = rettv.vval.v_list;
1365 if (p_verbose == 0)
1366 --emsg_off;
1367 restore_vimvar(VV_VAL, &save_val);
1369 return list;
1373 * "list" is supposed to contain two items: a word and a number. Return the
1374 * word in "pp" and the number as the return value.
1375 * Return -1 if anything isn't right.
1376 * Used to get the good word and score from the eval_spell_expr() result.
1379 get_spellword(list, pp)
1380 list_T *list;
1381 char_u **pp;
1383 listitem_T *li;
1385 li = list->lv_first;
1386 if (li == NULL)
1387 return -1;
1388 *pp = get_tv_string(&li->li_tv);
1390 li = li->li_next;
1391 if (li == NULL)
1392 return -1;
1393 return get_tv_number(&li->li_tv);
1395 #endif
1398 * Top level evaluation function.
1399 * Returns an allocated typval_T with the result.
1400 * Returns NULL when there is an error.
1402 typval_T *
1403 eval_expr(arg, nextcmd)
1404 char_u *arg;
1405 char_u **nextcmd;
1407 typval_T *tv;
1409 tv = (typval_T *)alloc(sizeof(typval_T));
1410 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1412 vim_free(tv);
1413 tv = NULL;
1416 return tv;
1420 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1421 || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1423 * Call some vimL function and return the result in "*rettv".
1424 * Uses argv[argc] for the function arguments.
1425 * Returns OK or FAIL.
1427 static int
1428 call_vim_function(func, argc, argv, safe, rettv)
1429 char_u *func;
1430 int argc;
1431 char_u **argv;
1432 int safe; /* use the sandbox */
1433 typval_T *rettv;
1435 typval_T *argvars;
1436 long n;
1437 int len;
1438 int i;
1439 int doesrange;
1440 void *save_funccalp = NULL;
1441 int ret;
1443 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1444 if (argvars == NULL)
1445 return FAIL;
1447 for (i = 0; i < argc; i++)
1449 /* Pass a NULL or empty argument as an empty string */
1450 if (argv[i] == NULL || *argv[i] == NUL)
1452 argvars[i].v_type = VAR_STRING;
1453 argvars[i].vval.v_string = (char_u *)"";
1454 continue;
1457 /* Recognize a number argument, the others must be strings. */
1458 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1459 if (len != 0 && len == (int)STRLEN(argv[i]))
1461 argvars[i].v_type = VAR_NUMBER;
1462 argvars[i].vval.v_number = n;
1464 else
1466 argvars[i].v_type = VAR_STRING;
1467 argvars[i].vval.v_string = argv[i];
1471 if (safe)
1473 save_funccalp = save_funccal();
1474 ++sandbox;
1477 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1478 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1479 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1480 &doesrange, TRUE, NULL);
1481 if (safe)
1483 --sandbox;
1484 restore_funccal(save_funccalp);
1486 vim_free(argvars);
1488 if (ret == FAIL)
1489 clear_tv(rettv);
1491 return ret;
1494 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1496 * Call vimL function "func" and return the result as a string.
1497 * Returns NULL when calling the function fails.
1498 * Uses argv[argc] for the function arguments.
1500 void *
1501 call_func_retstr(func, argc, argv, safe)
1502 char_u *func;
1503 int argc;
1504 char_u **argv;
1505 int safe; /* use the sandbox */
1507 typval_T rettv;
1508 char_u *retval;
1510 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1511 return NULL;
1513 retval = vim_strsave(get_tv_string(&rettv));
1514 clear_tv(&rettv);
1515 return retval;
1517 # endif
1519 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1521 * Call vimL function "func" and return the result as a number.
1522 * Returns -1 when calling the function fails.
1523 * Uses argv[argc] for the function arguments.
1525 long
1526 call_func_retnr(func, argc, argv, safe)
1527 char_u *func;
1528 int argc;
1529 char_u **argv;
1530 int safe; /* use the sandbox */
1532 typval_T rettv;
1533 long retval;
1535 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1536 return -1;
1538 retval = get_tv_number_chk(&rettv, NULL);
1539 clear_tv(&rettv);
1540 return retval;
1542 # endif
1545 * Call vimL function "func" and return the result as a list
1546 * Uses argv[argc] for the function arguments.
1548 void *
1549 call_func_retlist(func, argc, argv, safe)
1550 char_u *func;
1551 int argc;
1552 char_u **argv;
1553 int safe; /* use the sandbox */
1555 typval_T rettv;
1557 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1558 return NULL;
1560 if (rettv.v_type != VAR_LIST)
1562 clear_tv(&rettv);
1563 return NULL;
1566 return rettv.vval.v_list;
1568 #endif
1572 * Save the current function call pointer, and set it to NULL.
1573 * Used when executing autocommands and for ":source".
1575 void *
1576 save_funccal()
1578 funccall_T *fc = current_funccal;
1580 current_funccal = NULL;
1581 return (void *)fc;
1584 void
1585 restore_funccal(vfc)
1586 void *vfc;
1588 funccall_T *fc = (funccall_T *)vfc;
1590 current_funccal = fc;
1593 #if defined(FEAT_PROFILE) || defined(PROTO)
1595 * Prepare profiling for entering a child or something else that is not
1596 * counted for the script/function itself.
1597 * Should always be called in pair with prof_child_exit().
1599 void
1600 prof_child_enter(tm)
1601 proftime_T *tm; /* place to store waittime */
1603 funccall_T *fc = current_funccal;
1605 if (fc != NULL && fc->func->uf_profiling)
1606 profile_start(&fc->prof_child);
1607 script_prof_save(tm);
1611 * Take care of time spent in a child.
1612 * Should always be called after prof_child_enter().
1614 void
1615 prof_child_exit(tm)
1616 proftime_T *tm; /* where waittime was stored */
1618 funccall_T *fc = current_funccal;
1620 if (fc != NULL && fc->func->uf_profiling)
1622 profile_end(&fc->prof_child);
1623 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1624 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1625 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1627 script_prof_restore(tm);
1629 #endif
1632 #ifdef FEAT_FOLDING
1634 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1635 * it in "*cp". Doesn't give error messages.
1638 eval_foldexpr(arg, cp)
1639 char_u *arg;
1640 int *cp;
1642 typval_T tv;
1643 int retval;
1644 char_u *s;
1645 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1646 OPT_LOCAL);
1648 ++emsg_off;
1649 if (use_sandbox)
1650 ++sandbox;
1651 ++textlock;
1652 *cp = NUL;
1653 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1654 retval = 0;
1655 else
1657 /* If the result is a number, just return the number. */
1658 if (tv.v_type == VAR_NUMBER)
1659 retval = tv.vval.v_number;
1660 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1661 retval = 0;
1662 else
1664 /* If the result is a string, check if there is a non-digit before
1665 * the number. */
1666 s = tv.vval.v_string;
1667 if (!VIM_ISDIGIT(*s) && *s != '-')
1668 *cp = *s++;
1669 retval = atol((char *)s);
1671 clear_tv(&tv);
1673 --emsg_off;
1674 if (use_sandbox)
1675 --sandbox;
1676 --textlock;
1678 return retval;
1680 #endif
1683 * ":let" list all variable values
1684 * ":let var1 var2" list variable values
1685 * ":let var = expr" assignment command.
1686 * ":let var += expr" assignment command.
1687 * ":let var -= expr" assignment command.
1688 * ":let var .= expr" assignment command.
1689 * ":let [var1, var2] = expr" unpack list.
1691 void
1692 ex_let(eap)
1693 exarg_T *eap;
1695 char_u *arg = eap->arg;
1696 char_u *expr = NULL;
1697 typval_T rettv;
1698 int i;
1699 int var_count = 0;
1700 int semicolon = 0;
1701 char_u op[2];
1702 char_u *argend;
1703 int first = TRUE;
1705 argend = skip_var_list(arg, &var_count, &semicolon);
1706 if (argend == NULL)
1707 return;
1708 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1709 --argend;
1710 expr = vim_strchr(argend, '=');
1711 if (expr == NULL)
1714 * ":let" without "=": list variables
1716 if (*arg == '[')
1717 EMSG(_(e_invarg));
1718 else if (!ends_excmd(*arg))
1719 /* ":let var1 var2" */
1720 arg = list_arg_vars(eap, arg, &first);
1721 else if (!eap->skip)
1723 /* ":let" */
1724 list_glob_vars(&first);
1725 list_buf_vars(&first);
1726 list_win_vars(&first);
1727 #ifdef FEAT_WINDOWS
1728 list_tab_vars(&first);
1729 #endif
1730 list_script_vars(&first);
1731 list_func_vars(&first);
1732 list_vim_vars(&first);
1734 eap->nextcmd = check_nextcmd(arg);
1736 else
1738 op[0] = '=';
1739 op[1] = NUL;
1740 if (expr > argend)
1742 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1743 op[0] = expr[-1]; /* +=, -= or .= */
1745 expr = skipwhite(expr + 1);
1747 if (eap->skip)
1748 ++emsg_skip;
1749 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1750 if (eap->skip)
1752 if (i != FAIL)
1753 clear_tv(&rettv);
1754 --emsg_skip;
1756 else if (i != FAIL)
1758 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1759 op);
1760 clear_tv(&rettv);
1766 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1767 * Handles both "var" with any type and "[var, var; var]" with a list type.
1768 * When "nextchars" is not NULL it points to a string with characters that
1769 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1770 * or concatenate.
1771 * Returns OK or FAIL;
1773 static int
1774 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1775 char_u *arg_start;
1776 typval_T *tv;
1777 int copy; /* copy values from "tv", don't move */
1778 int semicolon; /* from skip_var_list() */
1779 int var_count; /* from skip_var_list() */
1780 char_u *nextchars;
1782 char_u *arg = arg_start;
1783 list_T *l;
1784 int i;
1785 listitem_T *item;
1786 typval_T ltv;
1788 if (*arg != '[')
1791 * ":let var = expr" or ":for var in list"
1793 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1794 return FAIL;
1795 return OK;
1799 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1801 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1803 EMSG(_(e_listreq));
1804 return FAIL;
1807 i = list_len(l);
1808 if (semicolon == 0 && var_count < i)
1810 EMSG(_("E687: Less targets than List items"));
1811 return FAIL;
1813 if (var_count - semicolon > i)
1815 EMSG(_("E688: More targets than List items"));
1816 return FAIL;
1819 item = l->lv_first;
1820 while (*arg != ']')
1822 arg = skipwhite(arg + 1);
1823 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1824 item = item->li_next;
1825 if (arg == NULL)
1826 return FAIL;
1828 arg = skipwhite(arg);
1829 if (*arg == ';')
1831 /* Put the rest of the list (may be empty) in the var after ';'.
1832 * Create a new list for this. */
1833 l = list_alloc();
1834 if (l == NULL)
1835 return FAIL;
1836 while (item != NULL)
1838 list_append_tv(l, &item->li_tv);
1839 item = item->li_next;
1842 ltv.v_type = VAR_LIST;
1843 ltv.v_lock = 0;
1844 ltv.vval.v_list = l;
1845 l->lv_refcount = 1;
1847 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1848 (char_u *)"]", nextchars);
1849 clear_tv(&ltv);
1850 if (arg == NULL)
1851 return FAIL;
1852 break;
1854 else if (*arg != ',' && *arg != ']')
1856 EMSG2(_(e_intern2), "ex_let_vars()");
1857 return FAIL;
1861 return OK;
1865 * Skip over assignable variable "var" or list of variables "[var, var]".
1866 * Used for ":let varvar = expr" and ":for varvar in expr".
1867 * For "[var, var]" increment "*var_count" for each variable.
1868 * for "[var, var; var]" set "semicolon".
1869 * Return NULL for an error.
1871 static char_u *
1872 skip_var_list(arg, var_count, semicolon)
1873 char_u *arg;
1874 int *var_count;
1875 int *semicolon;
1877 char_u *p, *s;
1879 if (*arg == '[')
1881 /* "[var, var]": find the matching ']'. */
1882 p = arg;
1883 for (;;)
1885 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
1886 s = skip_var_one(p);
1887 if (s == p)
1889 EMSG2(_(e_invarg2), p);
1890 return NULL;
1892 ++*var_count;
1894 p = skipwhite(s);
1895 if (*p == ']')
1896 break;
1897 else if (*p == ';')
1899 if (*semicolon == 1)
1901 EMSG(_("Double ; in list of variables"));
1902 return NULL;
1904 *semicolon = 1;
1906 else if (*p != ',')
1908 EMSG2(_(e_invarg2), p);
1909 return NULL;
1912 return p + 1;
1914 else
1915 return skip_var_one(arg);
1919 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
1920 * l[idx].
1922 static char_u *
1923 skip_var_one(arg)
1924 char_u *arg;
1926 if (*arg == '@' && arg[1] != NUL)
1927 return arg + 2;
1928 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
1929 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1933 * List variables for hashtab "ht" with prefix "prefix".
1934 * If "empty" is TRUE also list NULL strings as empty strings.
1936 static void
1937 list_hashtable_vars(ht, prefix, empty, first)
1938 hashtab_T *ht;
1939 char_u *prefix;
1940 int empty;
1941 int *first;
1943 hashitem_T *hi;
1944 dictitem_T *di;
1945 int todo;
1947 todo = (int)ht->ht_used;
1948 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
1950 if (!HASHITEM_EMPTY(hi))
1952 --todo;
1953 di = HI2DI(hi);
1954 if (empty || di->di_tv.v_type != VAR_STRING
1955 || di->di_tv.vval.v_string != NULL)
1956 list_one_var(di, prefix, first);
1962 * List global variables.
1964 static void
1965 list_glob_vars(first)
1966 int *first;
1968 list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
1972 * List buffer variables.
1974 static void
1975 list_buf_vars(first)
1976 int *first;
1978 char_u numbuf[NUMBUFLEN];
1980 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:",
1981 TRUE, first);
1983 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
1984 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
1985 numbuf, first);
1989 * List window variables.
1991 static void
1992 list_win_vars(first)
1993 int *first;
1995 list_hashtable_vars(&curwin->w_vars.dv_hashtab,
1996 (char_u *)"w:", TRUE, first);
1999 #ifdef FEAT_WINDOWS
2001 * List tab page variables.
2003 static void
2004 list_tab_vars(first)
2005 int *first;
2007 list_hashtable_vars(&curtab->tp_vars.dv_hashtab,
2008 (char_u *)"t:", TRUE, first);
2010 #endif
2013 * List Vim variables.
2015 static void
2016 list_vim_vars(first)
2017 int *first;
2019 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2023 * List script-local variables, if there is a script.
2025 static void
2026 list_script_vars(first)
2027 int *first;
2029 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2030 list_hashtable_vars(&SCRIPT_VARS(current_SID),
2031 (char_u *)"s:", FALSE, first);
2035 * List function variables, if there is a function.
2037 static void
2038 list_func_vars(first)
2039 int *first;
2041 if (current_funccal != NULL)
2042 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2043 (char_u *)"l:", FALSE, first);
2047 * List variables in "arg".
2049 static char_u *
2050 list_arg_vars(eap, arg, first)
2051 exarg_T *eap;
2052 char_u *arg;
2053 int *first;
2055 int error = FALSE;
2056 int len;
2057 char_u *name;
2058 char_u *name_start;
2059 char_u *arg_subsc;
2060 char_u *tofree;
2061 typval_T tv;
2063 while (!ends_excmd(*arg) && !got_int)
2065 if (error || eap->skip)
2067 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2068 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2070 emsg_severe = TRUE;
2071 EMSG(_(e_trailing));
2072 break;
2075 else
2077 /* get_name_len() takes care of expanding curly braces */
2078 name_start = name = arg;
2079 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2080 if (len <= 0)
2082 /* This is mainly to keep test 49 working: when expanding
2083 * curly braces fails overrule the exception error message. */
2084 if (len < 0 && !aborting())
2086 emsg_severe = TRUE;
2087 EMSG2(_(e_invarg2), arg);
2088 break;
2090 error = TRUE;
2092 else
2094 if (tofree != NULL)
2095 name = tofree;
2096 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2097 error = TRUE;
2098 else
2100 /* handle d.key, l[idx], f(expr) */
2101 arg_subsc = arg;
2102 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2103 error = TRUE;
2104 else
2106 if (arg == arg_subsc && len == 2 && name[1] == ':')
2108 switch (*name)
2110 case 'g': list_glob_vars(first); break;
2111 case 'b': list_buf_vars(first); break;
2112 case 'w': list_win_vars(first); break;
2113 #ifdef FEAT_WINDOWS
2114 case 't': list_tab_vars(first); break;
2115 #endif
2116 case 'v': list_vim_vars(first); break;
2117 case 's': list_script_vars(first); break;
2118 case 'l': list_func_vars(first); break;
2119 default:
2120 EMSG2(_("E738: Can't list variables for %s"), name);
2123 else
2125 char_u numbuf[NUMBUFLEN];
2126 char_u *tf;
2127 int c;
2128 char_u *s;
2130 s = echo_string(&tv, &tf, numbuf, 0);
2131 c = *arg;
2132 *arg = NUL;
2133 list_one_var_a((char_u *)"",
2134 arg == arg_subsc ? name : name_start,
2135 tv.v_type,
2136 s == NULL ? (char_u *)"" : s,
2137 first);
2138 *arg = c;
2139 vim_free(tf);
2141 clear_tv(&tv);
2146 vim_free(tofree);
2149 arg = skipwhite(arg);
2152 return arg;
2156 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2157 * Returns a pointer to the char just after the var name.
2158 * Returns NULL if there is an error.
2160 static char_u *
2161 ex_let_one(arg, tv, copy, endchars, op)
2162 char_u *arg; /* points to variable name */
2163 typval_T *tv; /* value to assign to variable */
2164 int copy; /* copy value from "tv" */
2165 char_u *endchars; /* valid chars after variable name or NULL */
2166 char_u *op; /* "+", "-", "." or NULL*/
2168 int c1;
2169 char_u *name;
2170 char_u *p;
2171 char_u *arg_end = NULL;
2172 int len;
2173 int opt_flags;
2174 char_u *tofree = NULL;
2177 * ":let $VAR = expr": Set environment variable.
2179 if (*arg == '$')
2181 /* Find the end of the name. */
2182 ++arg;
2183 name = arg;
2184 len = get_env_len(&arg);
2185 if (len == 0)
2186 EMSG2(_(e_invarg2), name - 1);
2187 else
2189 if (op != NULL && (*op == '+' || *op == '-'))
2190 EMSG2(_(e_letwrong), op);
2191 else if (endchars != NULL
2192 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2193 EMSG(_(e_letunexp));
2194 else
2196 c1 = name[len];
2197 name[len] = NUL;
2198 p = get_tv_string_chk(tv);
2199 if (p != NULL && op != NULL && *op == '.')
2201 int mustfree = FALSE;
2202 char_u *s = vim_getenv(name, &mustfree);
2204 if (s != NULL)
2206 p = tofree = concat_str(s, p);
2207 if (mustfree)
2208 vim_free(s);
2211 if (p != NULL)
2213 vim_setenv(name, p);
2214 if (STRICMP(name, "HOME") == 0)
2215 init_homedir();
2216 else if (didset_vim && STRICMP(name, "VIM") == 0)
2217 didset_vim = FALSE;
2218 else if (didset_vimruntime
2219 && STRICMP(name, "VIMRUNTIME") == 0)
2220 didset_vimruntime = FALSE;
2221 arg_end = arg;
2223 name[len] = c1;
2224 vim_free(tofree);
2230 * ":let &option = expr": Set option value.
2231 * ":let &l:option = expr": Set local option value.
2232 * ":let &g:option = expr": Set global option value.
2234 else if (*arg == '&')
2236 /* Find the end of the name. */
2237 p = find_option_end(&arg, &opt_flags);
2238 if (p == NULL || (endchars != NULL
2239 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2240 EMSG(_(e_letunexp));
2241 else
2243 long n;
2244 int opt_type;
2245 long numval;
2246 char_u *stringval = NULL;
2247 char_u *s;
2249 c1 = *p;
2250 *p = NUL;
2252 n = get_tv_number(tv);
2253 s = get_tv_string_chk(tv); /* != NULL if number or string */
2254 if (s != NULL && op != NULL && *op != '=')
2256 opt_type = get_option_value(arg, &numval,
2257 &stringval, opt_flags);
2258 if ((opt_type == 1 && *op == '.')
2259 || (opt_type == 0 && *op != '.'))
2260 EMSG2(_(e_letwrong), op);
2261 else
2263 if (opt_type == 1) /* number */
2265 if (*op == '+')
2266 n = numval + n;
2267 else
2268 n = numval - n;
2270 else if (opt_type == 0 && stringval != NULL) /* string */
2272 s = concat_str(stringval, s);
2273 vim_free(stringval);
2274 stringval = s;
2278 if (s != NULL)
2280 set_option_value(arg, n, s, opt_flags);
2281 arg_end = p;
2283 *p = c1;
2284 vim_free(stringval);
2289 * ":let @r = expr": Set register contents.
2291 else if (*arg == '@')
2293 ++arg;
2294 if (op != NULL && (*op == '+' || *op == '-'))
2295 EMSG2(_(e_letwrong), op);
2296 else if (endchars != NULL
2297 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2298 EMSG(_(e_letunexp));
2299 else
2301 char_u *ptofree = NULL;
2302 char_u *s;
2304 p = get_tv_string_chk(tv);
2305 if (p != NULL && op != NULL && *op == '.')
2307 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2308 if (s != NULL)
2310 p = ptofree = concat_str(s, p);
2311 vim_free(s);
2314 if (p != NULL)
2316 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2317 arg_end = arg + 1;
2319 vim_free(ptofree);
2324 * ":let var = expr": Set internal variable.
2325 * ":let {expr} = expr": Idem, name made with curly braces
2327 else if (eval_isnamec1(*arg) || *arg == '{')
2329 lval_T lv;
2331 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2332 if (p != NULL && lv.ll_name != NULL)
2334 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2335 EMSG(_(e_letunexp));
2336 else
2338 set_var_lval(&lv, p, tv, copy, op);
2339 arg_end = p;
2342 clear_lval(&lv);
2345 else
2346 EMSG2(_(e_invarg2), arg);
2348 return arg_end;
2352 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2354 static int
2355 check_changedtick(arg)
2356 char_u *arg;
2358 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2360 EMSG2(_(e_readonlyvar), arg);
2361 return TRUE;
2363 return FALSE;
2367 * Get an lval: variable, Dict item or List item that can be assigned a value
2368 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2369 * "name.key", "name.key[expr]" etc.
2370 * Indexing only works if "name" is an existing List or Dictionary.
2371 * "name" points to the start of the name.
2372 * If "rettv" is not NULL it points to the value to be assigned.
2373 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2374 * wrong; must end in space or cmd separator.
2376 * Returns a pointer to just after the name, including indexes.
2377 * When an evaluation error occurs "lp->ll_name" is NULL;
2378 * Returns NULL for a parsing error. Still need to free items in "lp"!
2380 static char_u *
2381 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2382 char_u *name;
2383 typval_T *rettv;
2384 lval_T *lp;
2385 int unlet;
2386 int skip;
2387 int quiet; /* don't give error messages */
2388 int fne_flags; /* flags for find_name_end() */
2390 char_u *p;
2391 char_u *expr_start, *expr_end;
2392 int cc;
2393 dictitem_T *v;
2394 typval_T var1;
2395 typval_T var2;
2396 int empty1 = FALSE;
2397 listitem_T *ni;
2398 char_u *key = NULL;
2399 int len;
2400 hashtab_T *ht;
2402 /* Clear everything in "lp". */
2403 vim_memset(lp, 0, sizeof(lval_T));
2405 if (skip)
2407 /* When skipping just find the end of the name. */
2408 lp->ll_name = name;
2409 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2412 /* Find the end of the name. */
2413 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2414 if (expr_start != NULL)
2416 /* Don't expand the name when we already know there is an error. */
2417 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2418 && *p != '[' && *p != '.')
2420 EMSG(_(e_trailing));
2421 return NULL;
2424 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2425 if (lp->ll_exp_name == NULL)
2427 /* Report an invalid expression in braces, unless the
2428 * expression evaluation has been cancelled due to an
2429 * aborting error, an interrupt, or an exception. */
2430 if (!aborting() && !quiet)
2432 emsg_severe = TRUE;
2433 EMSG2(_(e_invarg2), name);
2434 return NULL;
2437 lp->ll_name = lp->ll_exp_name;
2439 else
2440 lp->ll_name = name;
2442 /* Without [idx] or .key we are done. */
2443 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2444 return p;
2446 cc = *p;
2447 *p = NUL;
2448 v = find_var(lp->ll_name, &ht);
2449 if (v == NULL && !quiet)
2450 EMSG2(_(e_undefvar), lp->ll_name);
2451 *p = cc;
2452 if (v == NULL)
2453 return NULL;
2456 * Loop until no more [idx] or .key is following.
2458 lp->ll_tv = &v->di_tv;
2459 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2461 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2462 && !(lp->ll_tv->v_type == VAR_DICT
2463 && lp->ll_tv->vval.v_dict != NULL))
2465 if (!quiet)
2466 EMSG(_("E689: Can only index a List or Dictionary"));
2467 return NULL;
2469 if (lp->ll_range)
2471 if (!quiet)
2472 EMSG(_("E708: [:] must come last"));
2473 return NULL;
2476 len = -1;
2477 if (*p == '.')
2479 key = p + 1;
2480 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2482 if (len == 0)
2484 if (!quiet)
2485 EMSG(_(e_emptykey));
2486 return NULL;
2488 p = key + len;
2490 else
2492 /* Get the index [expr] or the first index [expr: ]. */
2493 p = skipwhite(p + 1);
2494 if (*p == ':')
2495 empty1 = TRUE;
2496 else
2498 empty1 = FALSE;
2499 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2500 return NULL;
2501 if (get_tv_string_chk(&var1) == NULL)
2503 /* not a number or string */
2504 clear_tv(&var1);
2505 return NULL;
2509 /* Optionally get the second index [ :expr]. */
2510 if (*p == ':')
2512 if (lp->ll_tv->v_type == VAR_DICT)
2514 if (!quiet)
2515 EMSG(_(e_dictrange));
2516 if (!empty1)
2517 clear_tv(&var1);
2518 return NULL;
2520 if (rettv != NULL && (rettv->v_type != VAR_LIST
2521 || rettv->vval.v_list == NULL))
2523 if (!quiet)
2524 EMSG(_("E709: [:] requires a List value"));
2525 if (!empty1)
2526 clear_tv(&var1);
2527 return NULL;
2529 p = skipwhite(p + 1);
2530 if (*p == ']')
2531 lp->ll_empty2 = TRUE;
2532 else
2534 lp->ll_empty2 = FALSE;
2535 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2537 if (!empty1)
2538 clear_tv(&var1);
2539 return NULL;
2541 if (get_tv_string_chk(&var2) == NULL)
2543 /* not a number or string */
2544 if (!empty1)
2545 clear_tv(&var1);
2546 clear_tv(&var2);
2547 return NULL;
2550 lp->ll_range = TRUE;
2552 else
2553 lp->ll_range = FALSE;
2555 if (*p != ']')
2557 if (!quiet)
2558 EMSG(_(e_missbrac));
2559 if (!empty1)
2560 clear_tv(&var1);
2561 if (lp->ll_range && !lp->ll_empty2)
2562 clear_tv(&var2);
2563 return NULL;
2566 /* Skip to past ']'. */
2567 ++p;
2570 if (lp->ll_tv->v_type == VAR_DICT)
2572 if (len == -1)
2574 /* "[key]": get key from "var1" */
2575 key = get_tv_string(&var1); /* is number or string */
2576 if (*key == NUL)
2578 if (!quiet)
2579 EMSG(_(e_emptykey));
2580 clear_tv(&var1);
2581 return NULL;
2584 lp->ll_list = NULL;
2585 lp->ll_dict = lp->ll_tv->vval.v_dict;
2586 lp->ll_di = dict_find(lp->ll_dict, key, len);
2587 if (lp->ll_di == NULL)
2589 /* Key does not exist in dict: may need to add it. */
2590 if (*p == '[' || *p == '.' || unlet)
2592 if (!quiet)
2593 EMSG2(_(e_dictkey), key);
2594 if (len == -1)
2595 clear_tv(&var1);
2596 return NULL;
2598 if (len == -1)
2599 lp->ll_newkey = vim_strsave(key);
2600 else
2601 lp->ll_newkey = vim_strnsave(key, len);
2602 if (len == -1)
2603 clear_tv(&var1);
2604 if (lp->ll_newkey == NULL)
2605 p = NULL;
2606 break;
2608 if (len == -1)
2609 clear_tv(&var1);
2610 lp->ll_tv = &lp->ll_di->di_tv;
2612 else
2615 * Get the number and item for the only or first index of the List.
2617 if (empty1)
2618 lp->ll_n1 = 0;
2619 else
2621 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2622 clear_tv(&var1);
2624 lp->ll_dict = NULL;
2625 lp->ll_list = lp->ll_tv->vval.v_list;
2626 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2627 if (lp->ll_li == NULL)
2629 if (lp->ll_n1 < 0)
2631 lp->ll_n1 = 0;
2632 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2635 if (lp->ll_li == NULL)
2637 if (lp->ll_range && !lp->ll_empty2)
2638 clear_tv(&var2);
2639 return NULL;
2643 * May need to find the item or absolute index for the second
2644 * index of a range.
2645 * When no index given: "lp->ll_empty2" is TRUE.
2646 * Otherwise "lp->ll_n2" is set to the second index.
2648 if (lp->ll_range && !lp->ll_empty2)
2650 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2651 clear_tv(&var2);
2652 if (lp->ll_n2 < 0)
2654 ni = list_find(lp->ll_list, lp->ll_n2);
2655 if (ni == NULL)
2656 return NULL;
2657 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2660 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2661 if (lp->ll_n1 < 0)
2662 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2663 if (lp->ll_n2 < lp->ll_n1)
2664 return NULL;
2667 lp->ll_tv = &lp->ll_li->li_tv;
2671 return p;
2675 * Clear lval "lp" that was filled by get_lval().
2677 static void
2678 clear_lval(lp)
2679 lval_T *lp;
2681 vim_free(lp->ll_exp_name);
2682 vim_free(lp->ll_newkey);
2686 * Set a variable that was parsed by get_lval() to "rettv".
2687 * "endp" points to just after the parsed name.
2688 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2690 static void
2691 set_var_lval(lp, endp, rettv, copy, op)
2692 lval_T *lp;
2693 char_u *endp;
2694 typval_T *rettv;
2695 int copy;
2696 char_u *op;
2698 int cc;
2699 listitem_T *ri;
2700 dictitem_T *di;
2702 if (lp->ll_tv == NULL)
2704 if (!check_changedtick(lp->ll_name))
2706 cc = *endp;
2707 *endp = NUL;
2708 if (op != NULL && *op != '=')
2710 typval_T tv;
2712 /* handle +=, -= and .= */
2713 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2714 &tv, TRUE) == OK)
2716 if (tv_op(&tv, rettv, op) == OK)
2717 set_var(lp->ll_name, &tv, FALSE);
2718 clear_tv(&tv);
2721 else
2722 set_var(lp->ll_name, rettv, copy);
2723 *endp = cc;
2726 else if (tv_check_lock(lp->ll_newkey == NULL
2727 ? lp->ll_tv->v_lock
2728 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2730 else if (lp->ll_range)
2733 * Assign the List values to the list items.
2735 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2737 if (op != NULL && *op != '=')
2738 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2739 else
2741 clear_tv(&lp->ll_li->li_tv);
2742 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2744 ri = ri->li_next;
2745 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2746 break;
2747 if (lp->ll_li->li_next == NULL)
2749 /* Need to add an empty item. */
2750 if (list_append_number(lp->ll_list, 0) == FAIL)
2752 ri = NULL;
2753 break;
2756 lp->ll_li = lp->ll_li->li_next;
2757 ++lp->ll_n1;
2759 if (ri != NULL)
2760 EMSG(_("E710: List value has more items than target"));
2761 else if (lp->ll_empty2
2762 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2763 : lp->ll_n1 != lp->ll_n2)
2764 EMSG(_("E711: List value has not enough items"));
2766 else
2769 * Assign to a List or Dictionary item.
2771 if (lp->ll_newkey != NULL)
2773 if (op != NULL && *op != '=')
2775 EMSG2(_(e_letwrong), op);
2776 return;
2779 /* Need to add an item to the Dictionary. */
2780 di = dictitem_alloc(lp->ll_newkey);
2781 if (di == NULL)
2782 return;
2783 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2785 vim_free(di);
2786 return;
2788 lp->ll_tv = &di->di_tv;
2790 else if (op != NULL && *op != '=')
2792 tv_op(lp->ll_tv, rettv, op);
2793 return;
2795 else
2796 clear_tv(lp->ll_tv);
2799 * Assign the value to the variable or list item.
2801 if (copy)
2802 copy_tv(rettv, lp->ll_tv);
2803 else
2805 *lp->ll_tv = *rettv;
2806 lp->ll_tv->v_lock = 0;
2807 init_tv(rettv);
2813 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2814 * Returns OK or FAIL.
2816 static int
2817 tv_op(tv1, tv2, op)
2818 typval_T *tv1;
2819 typval_T *tv2;
2820 char_u *op;
2822 long n;
2823 char_u numbuf[NUMBUFLEN];
2824 char_u *s;
2826 /* Can't do anything with a Funcref or a Dict on the right. */
2827 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2829 switch (tv1->v_type)
2831 case VAR_DICT:
2832 case VAR_FUNC:
2833 break;
2835 case VAR_LIST:
2836 if (*op != '+' || tv2->v_type != VAR_LIST)
2837 break;
2838 /* List += List */
2839 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2840 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2841 return OK;
2843 case VAR_NUMBER:
2844 case VAR_STRING:
2845 if (tv2->v_type == VAR_LIST)
2846 break;
2847 if (*op == '+' || *op == '-')
2849 /* nr += nr or nr -= nr*/
2850 n = get_tv_number(tv1);
2851 if (*op == '+')
2852 n += get_tv_number(tv2);
2853 else
2854 n -= get_tv_number(tv2);
2855 clear_tv(tv1);
2856 tv1->v_type = VAR_NUMBER;
2857 tv1->vval.v_number = n;
2859 else
2861 /* str .= str */
2862 s = get_tv_string(tv1);
2863 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2864 clear_tv(tv1);
2865 tv1->v_type = VAR_STRING;
2866 tv1->vval.v_string = s;
2868 return OK;
2872 EMSG2(_(e_letwrong), op);
2873 return FAIL;
2877 * Add a watcher to a list.
2879 static void
2880 list_add_watch(l, lw)
2881 list_T *l;
2882 listwatch_T *lw;
2884 lw->lw_next = l->lv_watch;
2885 l->lv_watch = lw;
2889 * Remove a watcher from a list.
2890 * No warning when it isn't found...
2892 static void
2893 list_rem_watch(l, lwrem)
2894 list_T *l;
2895 listwatch_T *lwrem;
2897 listwatch_T *lw, **lwp;
2899 lwp = &l->lv_watch;
2900 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2902 if (lw == lwrem)
2904 *lwp = lw->lw_next;
2905 break;
2907 lwp = &lw->lw_next;
2912 * Just before removing an item from a list: advance watchers to the next
2913 * item.
2915 static void
2916 list_fix_watch(l, item)
2917 list_T *l;
2918 listitem_T *item;
2920 listwatch_T *lw;
2922 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2923 if (lw->lw_item == item)
2924 lw->lw_item = item->li_next;
2928 * Evaluate the expression used in a ":for var in expr" command.
2929 * "arg" points to "var".
2930 * Set "*errp" to TRUE for an error, FALSE otherwise;
2931 * Return a pointer that holds the info. Null when there is an error.
2933 void *
2934 eval_for_line(arg, errp, nextcmdp, skip)
2935 char_u *arg;
2936 int *errp;
2937 char_u **nextcmdp;
2938 int skip;
2940 forinfo_T *fi;
2941 char_u *expr;
2942 typval_T tv;
2943 list_T *l;
2945 *errp = TRUE; /* default: there is an error */
2947 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
2948 if (fi == NULL)
2949 return NULL;
2951 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
2952 if (expr == NULL)
2953 return fi;
2955 expr = skipwhite(expr);
2956 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
2958 EMSG(_("E690: Missing \"in\" after :for"));
2959 return fi;
2962 if (skip)
2963 ++emsg_skip;
2964 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
2966 *errp = FALSE;
2967 if (!skip)
2969 l = tv.vval.v_list;
2970 if (tv.v_type != VAR_LIST || l == NULL)
2972 EMSG(_(e_listreq));
2973 clear_tv(&tv);
2975 else
2977 /* No need to increment the refcount, it's already set for the
2978 * list being used in "tv". */
2979 fi->fi_list = l;
2980 list_add_watch(l, &fi->fi_lw);
2981 fi->fi_lw.lw_item = l->lv_first;
2985 if (skip)
2986 --emsg_skip;
2988 return fi;
2992 * Use the first item in a ":for" list. Advance to the next.
2993 * Assign the values to the variable (list). "arg" points to the first one.
2994 * Return TRUE when a valid item was found, FALSE when at end of list or
2995 * something wrong.
2998 next_for_item(fi_void, arg)
2999 void *fi_void;
3000 char_u *arg;
3002 forinfo_T *fi = (forinfo_T *)fi_void;
3003 int result;
3004 listitem_T *item;
3006 item = fi->fi_lw.lw_item;
3007 if (item == NULL)
3008 result = FALSE;
3009 else
3011 fi->fi_lw.lw_item = item->li_next;
3012 result = (ex_let_vars(arg, &item->li_tv, TRUE,
3013 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3015 return result;
3019 * Free the structure used to store info used by ":for".
3021 void
3022 free_for_info(fi_void)
3023 void *fi_void;
3025 forinfo_T *fi = (forinfo_T *)fi_void;
3027 if (fi != NULL && fi->fi_list != NULL)
3029 list_rem_watch(fi->fi_list, &fi->fi_lw);
3030 list_unref(fi->fi_list);
3032 vim_free(fi);
3035 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3037 void
3038 set_context_for_expression(xp, arg, cmdidx)
3039 expand_T *xp;
3040 char_u *arg;
3041 cmdidx_T cmdidx;
3043 int got_eq = FALSE;
3044 int c;
3045 char_u *p;
3047 if (cmdidx == CMD_let)
3049 xp->xp_context = EXPAND_USER_VARS;
3050 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3052 /* ":let var1 var2 ...": find last space. */
3053 for (p = arg + STRLEN(arg); p >= arg; )
3055 xp->xp_pattern = p;
3056 mb_ptr_back(arg, p);
3057 if (vim_iswhite(*p))
3058 break;
3060 return;
3063 else
3064 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3065 : EXPAND_EXPRESSION;
3066 while ((xp->xp_pattern = vim_strpbrk(arg,
3067 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3069 c = *xp->xp_pattern;
3070 if (c == '&')
3072 c = xp->xp_pattern[1];
3073 if (c == '&')
3075 ++xp->xp_pattern;
3076 xp->xp_context = cmdidx != CMD_let || got_eq
3077 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3079 else if (c != ' ')
3081 xp->xp_context = EXPAND_SETTINGS;
3082 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3083 xp->xp_pattern += 2;
3087 else if (c == '$')
3089 /* environment variable */
3090 xp->xp_context = EXPAND_ENV_VARS;
3092 else if (c == '=')
3094 got_eq = TRUE;
3095 xp->xp_context = EXPAND_EXPRESSION;
3097 else if (c == '<'
3098 && xp->xp_context == EXPAND_FUNCTIONS
3099 && vim_strchr(xp->xp_pattern, '(') == NULL)
3101 /* Function name can start with "<SNR>" */
3102 break;
3104 else if (cmdidx != CMD_let || got_eq)
3106 if (c == '"') /* string */
3108 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3109 if (c == '\\' && xp->xp_pattern[1] != NUL)
3110 ++xp->xp_pattern;
3111 xp->xp_context = EXPAND_NOTHING;
3113 else if (c == '\'') /* literal string */
3115 /* Trick: '' is like stopping and starting a literal string. */
3116 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3117 /* skip */ ;
3118 xp->xp_context = EXPAND_NOTHING;
3120 else if (c == '|')
3122 if (xp->xp_pattern[1] == '|')
3124 ++xp->xp_pattern;
3125 xp->xp_context = EXPAND_EXPRESSION;
3127 else
3128 xp->xp_context = EXPAND_COMMANDS;
3130 else
3131 xp->xp_context = EXPAND_EXPRESSION;
3133 else
3134 /* Doesn't look like something valid, expand as an expression
3135 * anyway. */
3136 xp->xp_context = EXPAND_EXPRESSION;
3137 arg = xp->xp_pattern;
3138 if (*arg != NUL)
3139 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3140 /* skip */ ;
3142 xp->xp_pattern = arg;
3145 #endif /* FEAT_CMDL_COMPL */
3148 * ":1,25call func(arg1, arg2)" function call.
3150 void
3151 ex_call(eap)
3152 exarg_T *eap;
3154 char_u *arg = eap->arg;
3155 char_u *startarg;
3156 char_u *name;
3157 char_u *tofree;
3158 int len;
3159 typval_T rettv;
3160 linenr_T lnum;
3161 int doesrange;
3162 int failed = FALSE;
3163 funcdict_T fudi;
3165 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3166 if (fudi.fd_newkey != NULL)
3168 /* Still need to give an error message for missing key. */
3169 EMSG2(_(e_dictkey), fudi.fd_newkey);
3170 vim_free(fudi.fd_newkey);
3172 if (tofree == NULL)
3173 return;
3175 /* Increase refcount on dictionary, it could get deleted when evaluating
3176 * the arguments. */
3177 if (fudi.fd_dict != NULL)
3178 ++fudi.fd_dict->dv_refcount;
3180 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3181 len = (int)STRLEN(tofree);
3182 name = deref_func_name(tofree, &len);
3184 /* Skip white space to allow ":call func ()". Not good, but required for
3185 * backward compatibility. */
3186 startarg = skipwhite(arg);
3187 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3189 if (*startarg != '(')
3191 EMSG2(_("E107: Missing braces: %s"), eap->arg);
3192 goto end;
3196 * When skipping, evaluate the function once, to find the end of the
3197 * arguments.
3198 * When the function takes a range, this is discovered after the first
3199 * call, and the loop is broken.
3201 if (eap->skip)
3203 ++emsg_skip;
3204 lnum = eap->line2; /* do it once, also with an invalid range */
3206 else
3207 lnum = eap->line1;
3208 for ( ; lnum <= eap->line2; ++lnum)
3210 if (!eap->skip && eap->addr_count > 0)
3212 curwin->w_cursor.lnum = lnum;
3213 curwin->w_cursor.col = 0;
3215 arg = startarg;
3216 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3217 eap->line1, eap->line2, &doesrange,
3218 !eap->skip, fudi.fd_dict) == FAIL)
3220 failed = TRUE;
3221 break;
3224 /* Handle a function returning a Funcref, Dictionary or List. */
3225 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3227 failed = TRUE;
3228 break;
3231 clear_tv(&rettv);
3232 if (doesrange || eap->skip)
3233 break;
3235 /* Stop when immediately aborting on error, or when an interrupt
3236 * occurred or an exception was thrown but not caught.
3237 * get_func_tv() returned OK, so that the check for trailing
3238 * characters below is executed. */
3239 if (aborting())
3240 break;
3242 if (eap->skip)
3243 --emsg_skip;
3245 if (!failed)
3247 /* Check for trailing illegal characters and a following command. */
3248 if (!ends_excmd(*arg))
3250 emsg_severe = TRUE;
3251 EMSG(_(e_trailing));
3253 else
3254 eap->nextcmd = check_nextcmd(arg);
3257 end:
3258 dict_unref(fudi.fd_dict);
3259 vim_free(tofree);
3263 * ":unlet[!] var1 ... " command.
3265 void
3266 ex_unlet(eap)
3267 exarg_T *eap;
3269 ex_unletlock(eap, eap->arg, 0);
3273 * ":lockvar" and ":unlockvar" commands
3275 void
3276 ex_lockvar(eap)
3277 exarg_T *eap;
3279 char_u *arg = eap->arg;
3280 int deep = 2;
3282 if (eap->forceit)
3283 deep = -1;
3284 else if (vim_isdigit(*arg))
3286 deep = getdigits(&arg);
3287 arg = skipwhite(arg);
3290 ex_unletlock(eap, arg, deep);
3294 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3296 static void
3297 ex_unletlock(eap, argstart, deep)
3298 exarg_T *eap;
3299 char_u *argstart;
3300 int deep;
3302 char_u *arg = argstart;
3303 char_u *name_end;
3304 int error = FALSE;
3305 lval_T lv;
3309 /* Parse the name and find the end. */
3310 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3311 FNE_CHECK_START);
3312 if (lv.ll_name == NULL)
3313 error = TRUE; /* error but continue parsing */
3314 if (name_end == NULL || (!vim_iswhite(*name_end)
3315 && !ends_excmd(*name_end)))
3317 if (name_end != NULL)
3319 emsg_severe = TRUE;
3320 EMSG(_(e_trailing));
3322 if (!(eap->skip || error))
3323 clear_lval(&lv);
3324 break;
3327 if (!error && !eap->skip)
3329 if (eap->cmdidx == CMD_unlet)
3331 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3332 error = TRUE;
3334 else
3336 if (do_lock_var(&lv, name_end, deep,
3337 eap->cmdidx == CMD_lockvar) == FAIL)
3338 error = TRUE;
3342 if (!eap->skip)
3343 clear_lval(&lv);
3345 arg = skipwhite(name_end);
3346 } while (!ends_excmd(*arg));
3348 eap->nextcmd = check_nextcmd(arg);
3351 static int
3352 do_unlet_var(lp, name_end, forceit)
3353 lval_T *lp;
3354 char_u *name_end;
3355 int forceit;
3357 int ret = OK;
3358 int cc;
3360 if (lp->ll_tv == NULL)
3362 cc = *name_end;
3363 *name_end = NUL;
3365 /* Normal name or expanded name. */
3366 if (check_changedtick(lp->ll_name))
3367 ret = FAIL;
3368 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3369 ret = FAIL;
3370 *name_end = cc;
3372 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3373 return FAIL;
3374 else if (lp->ll_range)
3376 listitem_T *li;
3378 /* Delete a range of List items. */
3379 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3381 li = lp->ll_li->li_next;
3382 listitem_remove(lp->ll_list, lp->ll_li);
3383 lp->ll_li = li;
3384 ++lp->ll_n1;
3387 else
3389 if (lp->ll_list != NULL)
3390 /* unlet a List item. */
3391 listitem_remove(lp->ll_list, lp->ll_li);
3392 else
3393 /* unlet a Dictionary item. */
3394 dictitem_remove(lp->ll_dict, lp->ll_di);
3397 return ret;
3401 * "unlet" a variable. Return OK if it existed, FAIL if not.
3402 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3405 do_unlet(name, forceit)
3406 char_u *name;
3407 int forceit;
3409 hashtab_T *ht;
3410 hashitem_T *hi;
3411 char_u *varname;
3412 dictitem_T *di;
3414 ht = find_var_ht(name, &varname);
3415 if (ht != NULL && *varname != NUL)
3417 hi = hash_find(ht, varname);
3418 if (!HASHITEM_EMPTY(hi))
3420 di = HI2DI(hi);
3421 if (var_check_fixed(di->di_flags, name)
3422 || var_check_ro(di->di_flags, name))
3423 return FAIL;
3424 delete_var(ht, hi);
3425 return OK;
3428 if (forceit)
3429 return OK;
3430 EMSG2(_("E108: No such variable: \"%s\""), name);
3431 return FAIL;
3435 * Lock or unlock variable indicated by "lp".
3436 * "deep" is the levels to go (-1 for unlimited);
3437 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3439 static int
3440 do_lock_var(lp, name_end, deep, lock)
3441 lval_T *lp;
3442 char_u *name_end;
3443 int deep;
3444 int lock;
3446 int ret = OK;
3447 int cc;
3448 dictitem_T *di;
3450 if (deep == 0) /* nothing to do */
3451 return OK;
3453 if (lp->ll_tv == NULL)
3455 cc = *name_end;
3456 *name_end = NUL;
3458 /* Normal name or expanded name. */
3459 if (check_changedtick(lp->ll_name))
3460 ret = FAIL;
3461 else
3463 di = find_var(lp->ll_name, NULL);
3464 if (di == NULL)
3465 ret = FAIL;
3466 else
3468 if (lock)
3469 di->di_flags |= DI_FLAGS_LOCK;
3470 else
3471 di->di_flags &= ~DI_FLAGS_LOCK;
3472 item_lock(&di->di_tv, deep, lock);
3475 *name_end = cc;
3477 else if (lp->ll_range)
3479 listitem_T *li = lp->ll_li;
3481 /* (un)lock a range of List items. */
3482 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3484 item_lock(&li->li_tv, deep, lock);
3485 li = li->li_next;
3486 ++lp->ll_n1;
3489 else if (lp->ll_list != NULL)
3490 /* (un)lock a List item. */
3491 item_lock(&lp->ll_li->li_tv, deep, lock);
3492 else
3493 /* un(lock) a Dictionary item. */
3494 item_lock(&lp->ll_di->di_tv, deep, lock);
3496 return ret;
3500 * Lock or unlock an item. "deep" is nr of levels to go.
3502 static void
3503 item_lock(tv, deep, lock)
3504 typval_T *tv;
3505 int deep;
3506 int lock;
3508 static int recurse = 0;
3509 list_T *l;
3510 listitem_T *li;
3511 dict_T *d;
3512 hashitem_T *hi;
3513 int todo;
3515 if (recurse >= DICT_MAXNEST)
3517 EMSG(_("E743: variable nested too deep for (un)lock"));
3518 return;
3520 if (deep == 0)
3521 return;
3522 ++recurse;
3524 /* lock/unlock the item itself */
3525 if (lock)
3526 tv->v_lock |= VAR_LOCKED;
3527 else
3528 tv->v_lock &= ~VAR_LOCKED;
3530 switch (tv->v_type)
3532 case VAR_LIST:
3533 if ((l = tv->vval.v_list) != NULL)
3535 if (lock)
3536 l->lv_lock |= VAR_LOCKED;
3537 else
3538 l->lv_lock &= ~VAR_LOCKED;
3539 if (deep < 0 || deep > 1)
3540 /* recursive: lock/unlock the items the List contains */
3541 for (li = l->lv_first; li != NULL; li = li->li_next)
3542 item_lock(&li->li_tv, deep - 1, lock);
3544 break;
3545 case VAR_DICT:
3546 if ((d = tv->vval.v_dict) != NULL)
3548 if (lock)
3549 d->dv_lock |= VAR_LOCKED;
3550 else
3551 d->dv_lock &= ~VAR_LOCKED;
3552 if (deep < 0 || deep > 1)
3554 /* recursive: lock/unlock the items the List contains */
3555 todo = (int)d->dv_hashtab.ht_used;
3556 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3558 if (!HASHITEM_EMPTY(hi))
3560 --todo;
3561 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3567 --recurse;
3571 * Return TRUE if typeval "tv" is locked: Either tha value is locked itself or
3572 * it refers to a List or Dictionary that is locked.
3574 static int
3575 tv_islocked(tv)
3576 typval_T *tv;
3578 return (tv->v_lock & VAR_LOCKED)
3579 || (tv->v_type == VAR_LIST
3580 && tv->vval.v_list != NULL
3581 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3582 || (tv->v_type == VAR_DICT
3583 && tv->vval.v_dict != NULL
3584 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3587 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3589 * Delete all "menutrans_" variables.
3591 void
3592 del_menutrans_vars()
3594 hashitem_T *hi;
3595 int todo;
3597 hash_lock(&globvarht);
3598 todo = (int)globvarht.ht_used;
3599 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3601 if (!HASHITEM_EMPTY(hi))
3603 --todo;
3604 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3605 delete_var(&globvarht, hi);
3608 hash_unlock(&globvarht);
3610 #endif
3612 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3615 * Local string buffer for the next two functions to store a variable name
3616 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3617 * get_user_var_name().
3620 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3622 static char_u *varnamebuf = NULL;
3623 static int varnamebuflen = 0;
3626 * Function to concatenate a prefix and a variable name.
3628 static char_u *
3629 cat_prefix_varname(prefix, name)
3630 int prefix;
3631 char_u *name;
3633 int len;
3635 len = (int)STRLEN(name) + 3;
3636 if (len > varnamebuflen)
3638 vim_free(varnamebuf);
3639 len += 10; /* some additional space */
3640 varnamebuf = alloc(len);
3641 if (varnamebuf == NULL)
3643 varnamebuflen = 0;
3644 return NULL;
3646 varnamebuflen = len;
3648 *varnamebuf = prefix;
3649 varnamebuf[1] = ':';
3650 STRCPY(varnamebuf + 2, name);
3651 return varnamebuf;
3655 * Function given to ExpandGeneric() to obtain the list of user defined
3656 * (global/buffer/window/built-in) variable names.
3658 /*ARGSUSED*/
3659 char_u *
3660 get_user_var_name(xp, idx)
3661 expand_T *xp;
3662 int idx;
3664 static long_u gdone;
3665 static long_u bdone;
3666 static long_u wdone;
3667 #ifdef FEAT_WINDOWS
3668 static long_u tdone;
3669 #endif
3670 static int vidx;
3671 static hashitem_T *hi;
3672 hashtab_T *ht;
3674 if (idx == 0)
3676 gdone = bdone = wdone = vidx = 0;
3677 #ifdef FEAT_WINDOWS
3678 tdone = 0;
3679 #endif
3682 /* Global variables */
3683 if (gdone < globvarht.ht_used)
3685 if (gdone++ == 0)
3686 hi = globvarht.ht_array;
3687 else
3688 ++hi;
3689 while (HASHITEM_EMPTY(hi))
3690 ++hi;
3691 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3692 return cat_prefix_varname('g', hi->hi_key);
3693 return hi->hi_key;
3696 /* b: variables */
3697 ht = &curbuf->b_vars.dv_hashtab;
3698 if (bdone < ht->ht_used)
3700 if (bdone++ == 0)
3701 hi = ht->ht_array;
3702 else
3703 ++hi;
3704 while (HASHITEM_EMPTY(hi))
3705 ++hi;
3706 return cat_prefix_varname('b', hi->hi_key);
3708 if (bdone == ht->ht_used)
3710 ++bdone;
3711 return (char_u *)"b:changedtick";
3714 /* w: variables */
3715 ht = &curwin->w_vars.dv_hashtab;
3716 if (wdone < ht->ht_used)
3718 if (wdone++ == 0)
3719 hi = ht->ht_array;
3720 else
3721 ++hi;
3722 while (HASHITEM_EMPTY(hi))
3723 ++hi;
3724 return cat_prefix_varname('w', hi->hi_key);
3727 #ifdef FEAT_WINDOWS
3728 /* t: variables */
3729 ht = &curtab->tp_vars.dv_hashtab;
3730 if (tdone < ht->ht_used)
3732 if (tdone++ == 0)
3733 hi = ht->ht_array;
3734 else
3735 ++hi;
3736 while (HASHITEM_EMPTY(hi))
3737 ++hi;
3738 return cat_prefix_varname('t', hi->hi_key);
3740 #endif
3742 /* v: variables */
3743 if (vidx < VV_LEN)
3744 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3746 vim_free(varnamebuf);
3747 varnamebuf = NULL;
3748 varnamebuflen = 0;
3749 return NULL;
3752 #endif /* FEAT_CMDL_COMPL */
3755 * types for expressions.
3757 typedef enum
3759 TYPE_UNKNOWN = 0
3760 , TYPE_EQUAL /* == */
3761 , TYPE_NEQUAL /* != */
3762 , TYPE_GREATER /* > */
3763 , TYPE_GEQUAL /* >= */
3764 , TYPE_SMALLER /* < */
3765 , TYPE_SEQUAL /* <= */
3766 , TYPE_MATCH /* =~ */
3767 , TYPE_NOMATCH /* !~ */
3768 } exptype_T;
3771 * The "evaluate" argument: When FALSE, the argument is only parsed but not
3772 * executed. The function may return OK, but the rettv will be of type
3773 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
3777 * Handle zero level expression.
3778 * This calls eval1() and handles error message and nextcmd.
3779 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3780 * Note: "rettv.v_lock" is not set.
3781 * Return OK or FAIL.
3783 static int
3784 eval0(arg, rettv, nextcmd, evaluate)
3785 char_u *arg;
3786 typval_T *rettv;
3787 char_u **nextcmd;
3788 int evaluate;
3790 int ret;
3791 char_u *p;
3793 p = skipwhite(arg);
3794 ret = eval1(&p, rettv, evaluate);
3795 if (ret == FAIL || !ends_excmd(*p))
3797 if (ret != FAIL)
3798 clear_tv(rettv);
3800 * Report the invalid expression unless the expression evaluation has
3801 * been cancelled due to an aborting error, an interrupt, or an
3802 * exception.
3804 if (!aborting())
3805 EMSG2(_(e_invexpr2), arg);
3806 ret = FAIL;
3808 if (nextcmd != NULL)
3809 *nextcmd = check_nextcmd(p);
3811 return ret;
3815 * Handle top level expression:
3816 * expr1 ? expr0 : expr0
3818 * "arg" must point to the first non-white of the expression.
3819 * "arg" is advanced to the next non-white after the recognized expression.
3821 * Note: "rettv.v_lock" is not set.
3823 * Return OK or FAIL.
3825 static int
3826 eval1(arg, rettv, evaluate)
3827 char_u **arg;
3828 typval_T *rettv;
3829 int evaluate;
3831 int result;
3832 typval_T var2;
3835 * Get the first variable.
3837 if (eval2(arg, rettv, evaluate) == FAIL)
3838 return FAIL;
3840 if ((*arg)[0] == '?')
3842 result = FALSE;
3843 if (evaluate)
3845 int error = FALSE;
3847 if (get_tv_number_chk(rettv, &error) != 0)
3848 result = TRUE;
3849 clear_tv(rettv);
3850 if (error)
3851 return FAIL;
3855 * Get the second variable.
3857 *arg = skipwhite(*arg + 1);
3858 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
3859 return FAIL;
3862 * Check for the ":".
3864 if ((*arg)[0] != ':')
3866 EMSG(_("E109: Missing ':' after '?'"));
3867 if (evaluate && result)
3868 clear_tv(rettv);
3869 return FAIL;
3873 * Get the third variable.
3875 *arg = skipwhite(*arg + 1);
3876 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
3878 if (evaluate && result)
3879 clear_tv(rettv);
3880 return FAIL;
3882 if (evaluate && !result)
3883 *rettv = var2;
3886 return OK;
3890 * Handle first level expression:
3891 * expr2 || expr2 || expr2 logical OR
3893 * "arg" must point to the first non-white of the expression.
3894 * "arg" is advanced to the next non-white after the recognized expression.
3896 * Return OK or FAIL.
3898 static int
3899 eval2(arg, rettv, evaluate)
3900 char_u **arg;
3901 typval_T *rettv;
3902 int evaluate;
3904 typval_T var2;
3905 long result;
3906 int first;
3907 int error = FALSE;
3910 * Get the first variable.
3912 if (eval3(arg, rettv, evaluate) == FAIL)
3913 return FAIL;
3916 * Repeat until there is no following "||".
3918 first = TRUE;
3919 result = FALSE;
3920 while ((*arg)[0] == '|' && (*arg)[1] == '|')
3922 if (evaluate && first)
3924 if (get_tv_number_chk(rettv, &error) != 0)
3925 result = TRUE;
3926 clear_tv(rettv);
3927 if (error)
3928 return FAIL;
3929 first = FALSE;
3933 * Get the second variable.
3935 *arg = skipwhite(*arg + 2);
3936 if (eval3(arg, &var2, evaluate && !result) == FAIL)
3937 return FAIL;
3940 * Compute the result.
3942 if (evaluate && !result)
3944 if (get_tv_number_chk(&var2, &error) != 0)
3945 result = TRUE;
3946 clear_tv(&var2);
3947 if (error)
3948 return FAIL;
3950 if (evaluate)
3952 rettv->v_type = VAR_NUMBER;
3953 rettv->vval.v_number = result;
3957 return OK;
3961 * Handle second level expression:
3962 * expr3 && expr3 && expr3 logical AND
3964 * "arg" must point to the first non-white of the expression.
3965 * "arg" is advanced to the next non-white after the recognized expression.
3967 * Return OK or FAIL.
3969 static int
3970 eval3(arg, rettv, evaluate)
3971 char_u **arg;
3972 typval_T *rettv;
3973 int evaluate;
3975 typval_T var2;
3976 long result;
3977 int first;
3978 int error = FALSE;
3981 * Get the first variable.
3983 if (eval4(arg, rettv, evaluate) == FAIL)
3984 return FAIL;
3987 * Repeat until there is no following "&&".
3989 first = TRUE;
3990 result = TRUE;
3991 while ((*arg)[0] == '&' && (*arg)[1] == '&')
3993 if (evaluate && first)
3995 if (get_tv_number_chk(rettv, &error) == 0)
3996 result = FALSE;
3997 clear_tv(rettv);
3998 if (error)
3999 return FAIL;
4000 first = FALSE;
4004 * Get the second variable.
4006 *arg = skipwhite(*arg + 2);
4007 if (eval4(arg, &var2, evaluate && result) == FAIL)
4008 return FAIL;
4011 * Compute the result.
4013 if (evaluate && result)
4015 if (get_tv_number_chk(&var2, &error) == 0)
4016 result = FALSE;
4017 clear_tv(&var2);
4018 if (error)
4019 return FAIL;
4021 if (evaluate)
4023 rettv->v_type = VAR_NUMBER;
4024 rettv->vval.v_number = result;
4028 return OK;
4032 * Handle third level expression:
4033 * var1 == var2
4034 * var1 =~ var2
4035 * var1 != var2
4036 * var1 !~ var2
4037 * var1 > var2
4038 * var1 >= var2
4039 * var1 < var2
4040 * var1 <= var2
4041 * var1 is var2
4042 * var1 isnot var2
4044 * "arg" must point to the first non-white of the expression.
4045 * "arg" is advanced to the next non-white after the recognized expression.
4047 * Return OK or FAIL.
4049 static int
4050 eval4(arg, rettv, evaluate)
4051 char_u **arg;
4052 typval_T *rettv;
4053 int evaluate;
4055 typval_T var2;
4056 char_u *p;
4057 int i;
4058 exptype_T type = TYPE_UNKNOWN;
4059 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4060 int len = 2;
4061 long n1, n2;
4062 char_u *s1, *s2;
4063 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4064 regmatch_T regmatch;
4065 int ic;
4066 char_u *save_cpo;
4069 * Get the first variable.
4071 if (eval5(arg, rettv, evaluate) == FAIL)
4072 return FAIL;
4074 p = *arg;
4075 switch (p[0])
4077 case '=': if (p[1] == '=')
4078 type = TYPE_EQUAL;
4079 else if (p[1] == '~')
4080 type = TYPE_MATCH;
4081 break;
4082 case '!': if (p[1] == '=')
4083 type = TYPE_NEQUAL;
4084 else if (p[1] == '~')
4085 type = TYPE_NOMATCH;
4086 break;
4087 case '>': if (p[1] != '=')
4089 type = TYPE_GREATER;
4090 len = 1;
4092 else
4093 type = TYPE_GEQUAL;
4094 break;
4095 case '<': if (p[1] != '=')
4097 type = TYPE_SMALLER;
4098 len = 1;
4100 else
4101 type = TYPE_SEQUAL;
4102 break;
4103 case 'i': if (p[1] == 's')
4105 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4106 len = 5;
4107 if (!vim_isIDc(p[len]))
4109 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4110 type_is = TRUE;
4113 break;
4117 * If there is a comparitive operator, use it.
4119 if (type != TYPE_UNKNOWN)
4121 /* extra question mark appended: ignore case */
4122 if (p[len] == '?')
4124 ic = TRUE;
4125 ++len;
4127 /* extra '#' appended: match case */
4128 else if (p[len] == '#')
4130 ic = FALSE;
4131 ++len;
4133 /* nothing appened: use 'ignorecase' */
4134 else
4135 ic = p_ic;
4138 * Get the second variable.
4140 *arg = skipwhite(p + len);
4141 if (eval5(arg, &var2, evaluate) == FAIL)
4143 clear_tv(rettv);
4144 return FAIL;
4147 if (evaluate)
4149 if (type_is && rettv->v_type != var2.v_type)
4151 /* For "is" a different type always means FALSE, for "notis"
4152 * it means TRUE. */
4153 n1 = (type == TYPE_NEQUAL);
4155 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4157 if (type_is)
4159 n1 = (rettv->v_type == var2.v_type
4160 && rettv->vval.v_list == var2.vval.v_list);
4161 if (type == TYPE_NEQUAL)
4162 n1 = !n1;
4164 else if (rettv->v_type != var2.v_type
4165 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4167 if (rettv->v_type != var2.v_type)
4168 EMSG(_("E691: Can only compare List with List"));
4169 else
4170 EMSG(_("E692: Invalid operation for Lists"));
4171 clear_tv(rettv);
4172 clear_tv(&var2);
4173 return FAIL;
4175 else
4177 /* Compare two Lists for being equal or unequal. */
4178 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
4179 if (type == TYPE_NEQUAL)
4180 n1 = !n1;
4184 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4186 if (type_is)
4188 n1 = (rettv->v_type == var2.v_type
4189 && rettv->vval.v_dict == var2.vval.v_dict);
4190 if (type == TYPE_NEQUAL)
4191 n1 = !n1;
4193 else if (rettv->v_type != var2.v_type
4194 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4196 if (rettv->v_type != var2.v_type)
4197 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4198 else
4199 EMSG(_("E736: Invalid operation for Dictionary"));
4200 clear_tv(rettv);
4201 clear_tv(&var2);
4202 return FAIL;
4204 else
4206 /* Compare two Dictionaries for being equal or unequal. */
4207 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4208 if (type == TYPE_NEQUAL)
4209 n1 = !n1;
4213 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4215 if (rettv->v_type != var2.v_type
4216 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4218 if (rettv->v_type != var2.v_type)
4219 EMSG(_("E693: Can only compare Funcref with Funcref"));
4220 else
4221 EMSG(_("E694: Invalid operation for Funcrefs"));
4222 clear_tv(rettv);
4223 clear_tv(&var2);
4224 return FAIL;
4226 else
4228 /* Compare two Funcrefs for being equal or unequal. */
4229 if (rettv->vval.v_string == NULL
4230 || var2.vval.v_string == NULL)
4231 n1 = FALSE;
4232 else
4233 n1 = STRCMP(rettv->vval.v_string,
4234 var2.vval.v_string) == 0;
4235 if (type == TYPE_NEQUAL)
4236 n1 = !n1;
4241 * If one of the two variables is a number, compare as a number.
4242 * When using "=~" or "!~", always compare as string.
4244 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4245 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4247 n1 = get_tv_number(rettv);
4248 n2 = get_tv_number(&var2);
4249 switch (type)
4251 case TYPE_EQUAL: n1 = (n1 == n2); break;
4252 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4253 case TYPE_GREATER: n1 = (n1 > n2); break;
4254 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4255 case TYPE_SMALLER: n1 = (n1 < n2); break;
4256 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4257 case TYPE_UNKNOWN:
4258 case TYPE_MATCH:
4259 case TYPE_NOMATCH: break; /* avoid gcc warning */
4262 else
4264 s1 = get_tv_string_buf(rettv, buf1);
4265 s2 = get_tv_string_buf(&var2, buf2);
4266 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4267 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4268 else
4269 i = 0;
4270 n1 = FALSE;
4271 switch (type)
4273 case TYPE_EQUAL: n1 = (i == 0); break;
4274 case TYPE_NEQUAL: n1 = (i != 0); break;
4275 case TYPE_GREATER: n1 = (i > 0); break;
4276 case TYPE_GEQUAL: n1 = (i >= 0); break;
4277 case TYPE_SMALLER: n1 = (i < 0); break;
4278 case TYPE_SEQUAL: n1 = (i <= 0); break;
4280 case TYPE_MATCH:
4281 case TYPE_NOMATCH:
4282 /* avoid 'l' flag in 'cpoptions' */
4283 save_cpo = p_cpo;
4284 p_cpo = (char_u *)"";
4285 regmatch.regprog = vim_regcomp(s2,
4286 RE_MAGIC + RE_STRING);
4287 regmatch.rm_ic = ic;
4288 if (regmatch.regprog != NULL)
4290 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4291 vim_free(regmatch.regprog);
4292 if (type == TYPE_NOMATCH)
4293 n1 = !n1;
4295 p_cpo = save_cpo;
4296 break;
4298 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4301 clear_tv(rettv);
4302 clear_tv(&var2);
4303 rettv->v_type = VAR_NUMBER;
4304 rettv->vval.v_number = n1;
4308 return OK;
4312 * Handle fourth level expression:
4313 * + number addition
4314 * - number subtraction
4315 * . string concatenation
4317 * "arg" must point to the first non-white of the expression.
4318 * "arg" is advanced to the next non-white after the recognized expression.
4320 * Return OK or FAIL.
4322 static int
4323 eval5(arg, rettv, evaluate)
4324 char_u **arg;
4325 typval_T *rettv;
4326 int evaluate;
4328 typval_T var2;
4329 typval_T var3;
4330 int op;
4331 long n1, n2;
4332 char_u *s1, *s2;
4333 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4334 char_u *p;
4337 * Get the first variable.
4339 if (eval6(arg, rettv, evaluate) == FAIL)
4340 return FAIL;
4343 * Repeat computing, until no '+', '-' or '.' is following.
4345 for (;;)
4347 op = **arg;
4348 if (op != '+' && op != '-' && op != '.')
4349 break;
4351 if (op != '+' || rettv->v_type != VAR_LIST)
4353 /* For "list + ...", an illegal use of the first operand as
4354 * a number cannot be determined before evaluating the 2nd
4355 * operand: if this is also a list, all is ok.
4356 * For "something . ...", "something - ..." or "non-list + ...",
4357 * we know that the first operand needs to be a string or number
4358 * without evaluating the 2nd operand. So check before to avoid
4359 * side effects after an error. */
4360 if (evaluate && get_tv_string_chk(rettv) == NULL)
4362 clear_tv(rettv);
4363 return FAIL;
4368 * Get the second variable.
4370 *arg = skipwhite(*arg + 1);
4371 if (eval6(arg, &var2, evaluate) == FAIL)
4373 clear_tv(rettv);
4374 return FAIL;
4377 if (evaluate)
4380 * Compute the result.
4382 if (op == '.')
4384 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4385 s2 = get_tv_string_buf_chk(&var2, buf2);
4386 if (s2 == NULL) /* type error ? */
4388 clear_tv(rettv);
4389 clear_tv(&var2);
4390 return FAIL;
4392 p = concat_str(s1, s2);
4393 clear_tv(rettv);
4394 rettv->v_type = VAR_STRING;
4395 rettv->vval.v_string = p;
4397 else if (op == '+' && rettv->v_type == VAR_LIST
4398 && var2.v_type == VAR_LIST)
4400 /* concatenate Lists */
4401 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4402 &var3) == FAIL)
4404 clear_tv(rettv);
4405 clear_tv(&var2);
4406 return FAIL;
4408 clear_tv(rettv);
4409 *rettv = var3;
4411 else
4413 int error = FALSE;
4415 n1 = get_tv_number_chk(rettv, &error);
4416 if (error)
4418 /* This can only happen for "list + non-list".
4419 * For "non-list + ..." or "something - ...", we returned
4420 * before evaluating the 2nd operand. */
4421 clear_tv(rettv);
4422 return FAIL;
4424 n2 = get_tv_number_chk(&var2, &error);
4425 if (error)
4427 clear_tv(rettv);
4428 clear_tv(&var2);
4429 return FAIL;
4431 clear_tv(rettv);
4432 if (op == '+')
4433 n1 = n1 + n2;
4434 else
4435 n1 = n1 - n2;
4436 rettv->v_type = VAR_NUMBER;
4437 rettv->vval.v_number = n1;
4439 clear_tv(&var2);
4442 return OK;
4446 * Handle fifth level expression:
4447 * * number multiplication
4448 * / number division
4449 * % number modulo
4451 * "arg" must point to the first non-white of the expression.
4452 * "arg" is advanced to the next non-white after the recognized expression.
4454 * Return OK or FAIL.
4456 static int
4457 eval6(arg, rettv, evaluate)
4458 char_u **arg;
4459 typval_T *rettv;
4460 int evaluate;
4462 typval_T var2;
4463 int op;
4464 long n1, n2;
4465 int error = FALSE;
4468 * Get the first variable.
4470 if (eval7(arg, rettv, evaluate) == FAIL)
4471 return FAIL;
4474 * Repeat computing, until no '*', '/' or '%' is following.
4476 for (;;)
4478 op = **arg;
4479 if (op != '*' && op != '/' && op != '%')
4480 break;
4482 if (evaluate)
4484 n1 = get_tv_number_chk(rettv, &error);
4485 clear_tv(rettv);
4486 if (error)
4487 return FAIL;
4489 else
4490 n1 = 0;
4493 * Get the second variable.
4495 *arg = skipwhite(*arg + 1);
4496 if (eval7(arg, &var2, evaluate) == FAIL)
4497 return FAIL;
4499 if (evaluate)
4501 n2 = get_tv_number_chk(&var2, &error);
4502 clear_tv(&var2);
4503 if (error)
4504 return FAIL;
4507 * Compute the result.
4509 if (op == '*')
4510 n1 = n1 * n2;
4511 else if (op == '/')
4513 if (n2 == 0) /* give an error message? */
4514 n1 = 0x7fffffffL;
4515 else
4516 n1 = n1 / n2;
4518 else
4520 if (n2 == 0) /* give an error message? */
4521 n1 = 0;
4522 else
4523 n1 = n1 % n2;
4525 rettv->v_type = VAR_NUMBER;
4526 rettv->vval.v_number = n1;
4530 return OK;
4534 * Handle sixth level expression:
4535 * number number constant
4536 * "string" string constant
4537 * 'string' literal string constant
4538 * &option-name option value
4539 * @r register contents
4540 * identifier variable value
4541 * function() function call
4542 * $VAR environment variable
4543 * (expression) nested expression
4544 * [expr, expr] List
4545 * {key: val, key: val} Dictionary
4547 * Also handle:
4548 * ! in front logical NOT
4549 * - in front unary minus
4550 * + in front unary plus (ignored)
4551 * trailing [] subscript in String or List
4552 * trailing .name entry in Dictionary
4554 * "arg" must point to the first non-white of the expression.
4555 * "arg" is advanced to the next non-white after the recognized expression.
4557 * Return OK or FAIL.
4559 static int
4560 eval7(arg, rettv, evaluate)
4561 char_u **arg;
4562 typval_T *rettv;
4563 int evaluate;
4565 long n;
4566 int len;
4567 char_u *s;
4568 int val;
4569 char_u *start_leader, *end_leader;
4570 int ret = OK;
4571 char_u *alias;
4574 * Initialise variable so that clear_tv() can't mistake this for a
4575 * string and free a string that isn't there.
4577 rettv->v_type = VAR_UNKNOWN;
4580 * Skip '!' and '-' characters. They are handled later.
4582 start_leader = *arg;
4583 while (**arg == '!' || **arg == '-' || **arg == '+')
4584 *arg = skipwhite(*arg + 1);
4585 end_leader = *arg;
4587 switch (**arg)
4590 * Number constant.
4592 case '0':
4593 case '1':
4594 case '2':
4595 case '3':
4596 case '4':
4597 case '5':
4598 case '6':
4599 case '7':
4600 case '8':
4601 case '9':
4602 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4603 *arg += len;
4604 if (evaluate)
4606 rettv->v_type = VAR_NUMBER;
4607 rettv->vval.v_number = n;
4609 break;
4612 * String constant: "string".
4614 case '"': ret = get_string_tv(arg, rettv, evaluate);
4615 break;
4618 * Literal string constant: 'str''ing'.
4620 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
4621 break;
4624 * List: [expr, expr]
4626 case '[': ret = get_list_tv(arg, rettv, evaluate);
4627 break;
4630 * Dictionary: {key: val, key: val}
4632 case '{': ret = get_dict_tv(arg, rettv, evaluate);
4633 break;
4636 * Option value: &name
4638 case '&': ret = get_option_tv(arg, rettv, evaluate);
4639 break;
4642 * Environment variable: $VAR.
4644 case '$': ret = get_env_tv(arg, rettv, evaluate);
4645 break;
4648 * Register contents: @r.
4650 case '@': ++*arg;
4651 if (evaluate)
4653 rettv->v_type = VAR_STRING;
4654 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4656 if (**arg != NUL)
4657 ++*arg;
4658 break;
4661 * nested expression: (expression).
4663 case '(': *arg = skipwhite(*arg + 1);
4664 ret = eval1(arg, rettv, evaluate); /* recursive! */
4665 if (**arg == ')')
4666 ++*arg;
4667 else if (ret == OK)
4669 EMSG(_("E110: Missing ')'"));
4670 clear_tv(rettv);
4671 ret = FAIL;
4673 break;
4675 default: ret = NOTDONE;
4676 break;
4679 if (ret == NOTDONE)
4682 * Must be a variable or function name.
4683 * Can also be a curly-braces kind of name: {expr}.
4685 s = *arg;
4686 len = get_name_len(arg, &alias, evaluate, TRUE);
4687 if (alias != NULL)
4688 s = alias;
4690 if (len <= 0)
4691 ret = FAIL;
4692 else
4694 if (**arg == '(') /* recursive! */
4696 /* If "s" is the name of a variable of type VAR_FUNC
4697 * use its contents. */
4698 s = deref_func_name(s, &len);
4700 /* Invoke the function. */
4701 ret = get_func_tv(s, len, rettv, arg,
4702 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
4703 &len, evaluate, NULL);
4704 /* Stop the expression evaluation when immediately
4705 * aborting on error, or when an interrupt occurred or
4706 * an exception was thrown but not caught. */
4707 if (aborting())
4709 if (ret == OK)
4710 clear_tv(rettv);
4711 ret = FAIL;
4714 else if (evaluate)
4715 ret = get_var_tv(s, len, rettv, TRUE);
4716 else
4717 ret = OK;
4720 if (alias != NULL)
4721 vim_free(alias);
4724 *arg = skipwhite(*arg);
4726 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
4727 * expr(expr). */
4728 if (ret == OK)
4729 ret = handle_subscript(arg, rettv, evaluate, TRUE);
4732 * Apply logical NOT and unary '-', from right to left, ignore '+'.
4734 if (ret == OK && evaluate && end_leader > start_leader)
4736 int error = FALSE;
4738 val = get_tv_number_chk(rettv, &error);
4739 if (error)
4741 clear_tv(rettv);
4742 ret = FAIL;
4744 else
4746 while (end_leader > start_leader)
4748 --end_leader;
4749 if (*end_leader == '!')
4750 val = !val;
4751 else if (*end_leader == '-')
4752 val = -val;
4754 clear_tv(rettv);
4755 rettv->v_type = VAR_NUMBER;
4756 rettv->vval.v_number = val;
4760 return ret;
4764 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
4765 * "*arg" points to the '[' or '.'.
4766 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
4768 static int
4769 eval_index(arg, rettv, evaluate, verbose)
4770 char_u **arg;
4771 typval_T *rettv;
4772 int evaluate;
4773 int verbose; /* give error messages */
4775 int empty1 = FALSE, empty2 = FALSE;
4776 typval_T var1, var2;
4777 long n1, n2 = 0;
4778 long len = -1;
4779 int range = FALSE;
4780 char_u *s;
4781 char_u *key = NULL;
4783 if (rettv->v_type == VAR_FUNC)
4785 if (verbose)
4786 EMSG(_("E695: Cannot index a Funcref"));
4787 return FAIL;
4790 if (**arg == '.')
4793 * dict.name
4795 key = *arg + 1;
4796 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
4798 if (len == 0)
4799 return FAIL;
4800 *arg = skipwhite(key + len);
4802 else
4805 * something[idx]
4807 * Get the (first) variable from inside the [].
4809 *arg = skipwhite(*arg + 1);
4810 if (**arg == ':')
4811 empty1 = TRUE;
4812 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
4813 return FAIL;
4814 else if (evaluate && get_tv_string_chk(&var1) == NULL)
4816 /* not a number or string */
4817 clear_tv(&var1);
4818 return FAIL;
4822 * Get the second variable from inside the [:].
4824 if (**arg == ':')
4826 range = TRUE;
4827 *arg = skipwhite(*arg + 1);
4828 if (**arg == ']')
4829 empty2 = TRUE;
4830 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
4832 if (!empty1)
4833 clear_tv(&var1);
4834 return FAIL;
4836 else if (evaluate && get_tv_string_chk(&var2) == NULL)
4838 /* not a number or string */
4839 if (!empty1)
4840 clear_tv(&var1);
4841 clear_tv(&var2);
4842 return FAIL;
4846 /* Check for the ']'. */
4847 if (**arg != ']')
4849 if (verbose)
4850 EMSG(_(e_missbrac));
4851 clear_tv(&var1);
4852 if (range)
4853 clear_tv(&var2);
4854 return FAIL;
4856 *arg = skipwhite(*arg + 1); /* skip the ']' */
4859 if (evaluate)
4861 n1 = 0;
4862 if (!empty1 && rettv->v_type != VAR_DICT)
4864 n1 = get_tv_number(&var1);
4865 clear_tv(&var1);
4867 if (range)
4869 if (empty2)
4870 n2 = -1;
4871 else
4873 n2 = get_tv_number(&var2);
4874 clear_tv(&var2);
4878 switch (rettv->v_type)
4880 case VAR_NUMBER:
4881 case VAR_STRING:
4882 s = get_tv_string(rettv);
4883 len = (long)STRLEN(s);
4884 if (range)
4886 /* The resulting variable is a substring. If the indexes
4887 * are out of range the result is empty. */
4888 if (n1 < 0)
4890 n1 = len + n1;
4891 if (n1 < 0)
4892 n1 = 0;
4894 if (n2 < 0)
4895 n2 = len + n2;
4896 else if (n2 >= len)
4897 n2 = len;
4898 if (n1 >= len || n2 < 0 || n1 > n2)
4899 s = NULL;
4900 else
4901 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
4903 else
4905 /* The resulting variable is a string of a single
4906 * character. If the index is too big or negative the
4907 * result is empty. */
4908 if (n1 >= len || n1 < 0)
4909 s = NULL;
4910 else
4911 s = vim_strnsave(s + n1, 1);
4913 clear_tv(rettv);
4914 rettv->v_type = VAR_STRING;
4915 rettv->vval.v_string = s;
4916 break;
4918 case VAR_LIST:
4919 len = list_len(rettv->vval.v_list);
4920 if (n1 < 0)
4921 n1 = len + n1;
4922 if (!empty1 && (n1 < 0 || n1 >= len))
4924 /* For a range we allow invalid values and return an empty
4925 * list. A list index out of range is an error. */
4926 if (!range)
4928 if (verbose)
4929 EMSGN(_(e_listidx), n1);
4930 return FAIL;
4932 n1 = len;
4934 if (range)
4936 list_T *l;
4937 listitem_T *item;
4939 if (n2 < 0)
4940 n2 = len + n2;
4941 else if (n2 >= len)
4942 n2 = len - 1;
4943 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
4944 n2 = -1;
4945 l = list_alloc();
4946 if (l == NULL)
4947 return FAIL;
4948 for (item = list_find(rettv->vval.v_list, n1);
4949 n1 <= n2; ++n1)
4951 if (list_append_tv(l, &item->li_tv) == FAIL)
4953 list_free(l, TRUE);
4954 return FAIL;
4956 item = item->li_next;
4958 clear_tv(rettv);
4959 rettv->v_type = VAR_LIST;
4960 rettv->vval.v_list = l;
4961 ++l->lv_refcount;
4963 else
4965 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
4966 clear_tv(rettv);
4967 *rettv = var1;
4969 break;
4971 case VAR_DICT:
4972 if (range)
4974 if (verbose)
4975 EMSG(_(e_dictrange));
4976 if (len == -1)
4977 clear_tv(&var1);
4978 return FAIL;
4981 dictitem_T *item;
4983 if (len == -1)
4985 key = get_tv_string(&var1);
4986 if (*key == NUL)
4988 if (verbose)
4989 EMSG(_(e_emptykey));
4990 clear_tv(&var1);
4991 return FAIL;
4995 item = dict_find(rettv->vval.v_dict, key, (int)len);
4997 if (item == NULL && verbose)
4998 EMSG2(_(e_dictkey), key);
4999 if (len == -1)
5000 clear_tv(&var1);
5001 if (item == NULL)
5002 return FAIL;
5004 copy_tv(&item->di_tv, &var1);
5005 clear_tv(rettv);
5006 *rettv = var1;
5008 break;
5012 return OK;
5016 * Get an option value.
5017 * "arg" points to the '&' or '+' before the option name.
5018 * "arg" is advanced to character after the option name.
5019 * Return OK or FAIL.
5021 static int
5022 get_option_tv(arg, rettv, evaluate)
5023 char_u **arg;
5024 typval_T *rettv; /* when NULL, only check if option exists */
5025 int evaluate;
5027 char_u *option_end;
5028 long numval;
5029 char_u *stringval;
5030 int opt_type;
5031 int c;
5032 int working = (**arg == '+'); /* has("+option") */
5033 int ret = OK;
5034 int opt_flags;
5037 * Isolate the option name and find its value.
5039 option_end = find_option_end(arg, &opt_flags);
5040 if (option_end == NULL)
5042 if (rettv != NULL)
5043 EMSG2(_("E112: Option name missing: %s"), *arg);
5044 return FAIL;
5047 if (!evaluate)
5049 *arg = option_end;
5050 return OK;
5053 c = *option_end;
5054 *option_end = NUL;
5055 opt_type = get_option_value(*arg, &numval,
5056 rettv == NULL ? NULL : &stringval, opt_flags);
5058 if (opt_type == -3) /* invalid name */
5060 if (rettv != NULL)
5061 EMSG2(_("E113: Unknown option: %s"), *arg);
5062 ret = FAIL;
5064 else if (rettv != NULL)
5066 if (opt_type == -2) /* hidden string option */
5068 rettv->v_type = VAR_STRING;
5069 rettv->vval.v_string = NULL;
5071 else if (opt_type == -1) /* hidden number option */
5073 rettv->v_type = VAR_NUMBER;
5074 rettv->vval.v_number = 0;
5076 else if (opt_type == 1) /* number option */
5078 rettv->v_type = VAR_NUMBER;
5079 rettv->vval.v_number = numval;
5081 else /* string option */
5083 rettv->v_type = VAR_STRING;
5084 rettv->vval.v_string = stringval;
5087 else if (working && (opt_type == -2 || opt_type == -1))
5088 ret = FAIL;
5090 *option_end = c; /* put back for error messages */
5091 *arg = option_end;
5093 return ret;
5097 * Allocate a variable for a string constant.
5098 * Return OK or FAIL.
5100 static int
5101 get_string_tv(arg, rettv, evaluate)
5102 char_u **arg;
5103 typval_T *rettv;
5104 int evaluate;
5106 char_u *p;
5107 char_u *name;
5108 int extra = 0;
5111 * Find the end of the string, skipping backslashed characters.
5113 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5115 if (*p == '\\' && p[1] != NUL)
5117 ++p;
5118 /* A "\<x>" form occupies at least 4 characters, and produces up
5119 * to 6 characters: reserve space for 2 extra */
5120 if (*p == '<')
5121 extra += 2;
5125 if (*p != '"')
5127 EMSG2(_("E114: Missing quote: %s"), *arg);
5128 return FAIL;
5131 /* If only parsing, set *arg and return here */
5132 if (!evaluate)
5134 *arg = p + 1;
5135 return OK;
5139 * Copy the string into allocated memory, handling backslashed
5140 * characters.
5142 name = alloc((unsigned)(p - *arg + extra));
5143 if (name == NULL)
5144 return FAIL;
5145 rettv->v_type = VAR_STRING;
5146 rettv->vval.v_string = name;
5148 for (p = *arg + 1; *p != NUL && *p != '"'; )
5150 if (*p == '\\')
5152 switch (*++p)
5154 case 'b': *name++ = BS; ++p; break;
5155 case 'e': *name++ = ESC; ++p; break;
5156 case 'f': *name++ = FF; ++p; break;
5157 case 'n': *name++ = NL; ++p; break;
5158 case 'r': *name++ = CAR; ++p; break;
5159 case 't': *name++ = TAB; ++p; break;
5161 case 'X': /* hex: "\x1", "\x12" */
5162 case 'x':
5163 case 'u': /* Unicode: "\u0023" */
5164 case 'U':
5165 if (vim_isxdigit(p[1]))
5167 int n, nr;
5168 int c = toupper(*p);
5170 if (c == 'X')
5171 n = 2;
5172 else
5173 n = 4;
5174 nr = 0;
5175 while (--n >= 0 && vim_isxdigit(p[1]))
5177 ++p;
5178 nr = (nr << 4) + hex2nr(*p);
5180 ++p;
5181 #ifdef FEAT_MBYTE
5182 /* For "\u" store the number according to
5183 * 'encoding'. */
5184 if (c != 'X')
5185 name += (*mb_char2bytes)(nr, name);
5186 else
5187 #endif
5188 *name++ = nr;
5190 break;
5192 /* octal: "\1", "\12", "\123" */
5193 case '0':
5194 case '1':
5195 case '2':
5196 case '3':
5197 case '4':
5198 case '5':
5199 case '6':
5200 case '7': *name = *p++ - '0';
5201 if (*p >= '0' && *p <= '7')
5203 *name = (*name << 3) + *p++ - '0';
5204 if (*p >= '0' && *p <= '7')
5205 *name = (*name << 3) + *p++ - '0';
5207 ++name;
5208 break;
5210 /* Special key, e.g.: "\<C-W>" */
5211 case '<': extra = trans_special(&p, name, TRUE);
5212 if (extra != 0)
5214 name += extra;
5215 break;
5217 /* FALLTHROUGH */
5219 default: MB_COPY_CHAR(p, name);
5220 break;
5223 else
5224 MB_COPY_CHAR(p, name);
5227 *name = NUL;
5228 *arg = p + 1;
5230 return OK;
5234 * Allocate a variable for a 'str''ing' constant.
5235 * Return OK or FAIL.
5237 static int
5238 get_lit_string_tv(arg, rettv, evaluate)
5239 char_u **arg;
5240 typval_T *rettv;
5241 int evaluate;
5243 char_u *p;
5244 char_u *str;
5245 int reduce = 0;
5248 * Find the end of the string, skipping ''.
5250 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5252 if (*p == '\'')
5254 if (p[1] != '\'')
5255 break;
5256 ++reduce;
5257 ++p;
5261 if (*p != '\'')
5263 EMSG2(_("E115: Missing quote: %s"), *arg);
5264 return FAIL;
5267 /* If only parsing return after setting "*arg" */
5268 if (!evaluate)
5270 *arg = p + 1;
5271 return OK;
5275 * Copy the string into allocated memory, handling '' to ' reduction.
5277 str = alloc((unsigned)((p - *arg) - reduce));
5278 if (str == NULL)
5279 return FAIL;
5280 rettv->v_type = VAR_STRING;
5281 rettv->vval.v_string = str;
5283 for (p = *arg + 1; *p != NUL; )
5285 if (*p == '\'')
5287 if (p[1] != '\'')
5288 break;
5289 ++p;
5291 MB_COPY_CHAR(p, str);
5293 *str = NUL;
5294 *arg = p + 1;
5296 return OK;
5300 * Allocate a variable for a List and fill it from "*arg".
5301 * Return OK or FAIL.
5303 static int
5304 get_list_tv(arg, rettv, evaluate)
5305 char_u **arg;
5306 typval_T *rettv;
5307 int evaluate;
5309 list_T *l = NULL;
5310 typval_T tv;
5311 listitem_T *item;
5313 if (evaluate)
5315 l = list_alloc();
5316 if (l == NULL)
5317 return FAIL;
5320 *arg = skipwhite(*arg + 1);
5321 while (**arg != ']' && **arg != NUL)
5323 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5324 goto failret;
5325 if (evaluate)
5327 item = listitem_alloc();
5328 if (item != NULL)
5330 item->li_tv = tv;
5331 item->li_tv.v_lock = 0;
5332 list_append(l, item);
5334 else
5335 clear_tv(&tv);
5338 if (**arg == ']')
5339 break;
5340 if (**arg != ',')
5342 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5343 goto failret;
5345 *arg = skipwhite(*arg + 1);
5348 if (**arg != ']')
5350 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5351 failret:
5352 if (evaluate)
5353 list_free(l, TRUE);
5354 return FAIL;
5357 *arg = skipwhite(*arg + 1);
5358 if (evaluate)
5360 rettv->v_type = VAR_LIST;
5361 rettv->vval.v_list = l;
5362 ++l->lv_refcount;
5365 return OK;
5369 * Allocate an empty header for a list.
5370 * Caller should take care of the reference count.
5372 list_T *
5373 list_alloc()
5375 list_T *l;
5377 l = (list_T *)alloc_clear(sizeof(list_T));
5378 if (l != NULL)
5380 /* Prepend the list to the list of lists for garbage collection. */
5381 if (first_list != NULL)
5382 first_list->lv_used_prev = l;
5383 l->lv_used_prev = NULL;
5384 l->lv_used_next = first_list;
5385 first_list = l;
5387 return l;
5391 * Allocate an empty list for a return value.
5392 * Returns OK or FAIL.
5394 static int
5395 rettv_list_alloc(rettv)
5396 typval_T *rettv;
5398 list_T *l = list_alloc();
5400 if (l == NULL)
5401 return FAIL;
5403 rettv->vval.v_list = l;
5404 rettv->v_type = VAR_LIST;
5405 ++l->lv_refcount;
5406 return OK;
5410 * Unreference a list: decrement the reference count and free it when it
5411 * becomes zero.
5413 void
5414 list_unref(l)
5415 list_T *l;
5417 if (l != NULL && --l->lv_refcount <= 0)
5418 list_free(l, TRUE);
5422 * Free a list, including all items it points to.
5423 * Ignores the reference count.
5425 void
5426 list_free(l, recurse)
5427 list_T *l;
5428 int recurse; /* Free Lists and Dictionaries recursively. */
5430 listitem_T *item;
5432 /* Remove the list from the list of lists for garbage collection. */
5433 if (l->lv_used_prev == NULL)
5434 first_list = l->lv_used_next;
5435 else
5436 l->lv_used_prev->lv_used_next = l->lv_used_next;
5437 if (l->lv_used_next != NULL)
5438 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5440 for (item = l->lv_first; item != NULL; item = l->lv_first)
5442 /* Remove the item before deleting it. */
5443 l->lv_first = item->li_next;
5444 if (recurse || (item->li_tv.v_type != VAR_LIST
5445 && item->li_tv.v_type != VAR_DICT))
5446 clear_tv(&item->li_tv);
5447 vim_free(item);
5449 vim_free(l);
5453 * Allocate a list item.
5455 static listitem_T *
5456 listitem_alloc()
5458 return (listitem_T *)alloc(sizeof(listitem_T));
5462 * Free a list item. Also clears the value. Does not notify watchers.
5464 static void
5465 listitem_free(item)
5466 listitem_T *item;
5468 clear_tv(&item->li_tv);
5469 vim_free(item);
5473 * Remove a list item from a List and free it. Also clears the value.
5475 static void
5476 listitem_remove(l, item)
5477 list_T *l;
5478 listitem_T *item;
5480 list_remove(l, item, item);
5481 listitem_free(item);
5485 * Get the number of items in a list.
5487 static long
5488 list_len(l)
5489 list_T *l;
5491 if (l == NULL)
5492 return 0L;
5493 return l->lv_len;
5497 * Return TRUE when two lists have exactly the same values.
5499 static int
5500 list_equal(l1, l2, ic)
5501 list_T *l1;
5502 list_T *l2;
5503 int ic; /* ignore case for strings */
5505 listitem_T *item1, *item2;
5507 if (l1 == l2)
5508 return TRUE;
5509 if (list_len(l1) != list_len(l2))
5510 return FALSE;
5512 for (item1 = l1->lv_first, item2 = l2->lv_first;
5513 item1 != NULL && item2 != NULL;
5514 item1 = item1->li_next, item2 = item2->li_next)
5515 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5516 return FALSE;
5517 return item1 == NULL && item2 == NULL;
5520 #if defined(FEAT_PYTHON) || defined(PROTO)
5522 * Return the dictitem that an entry in a hashtable points to.
5524 dictitem_T *
5525 dict_lookup(hi)
5526 hashitem_T *hi;
5528 return HI2DI(hi);
5530 #endif
5533 * Return TRUE when two dictionaries have exactly the same key/values.
5535 static int
5536 dict_equal(d1, d2, ic)
5537 dict_T *d1;
5538 dict_T *d2;
5539 int ic; /* ignore case for strings */
5541 hashitem_T *hi;
5542 dictitem_T *item2;
5543 int todo;
5545 if (d1 == d2)
5546 return TRUE;
5547 if (dict_len(d1) != dict_len(d2))
5548 return FALSE;
5550 todo = (int)d1->dv_hashtab.ht_used;
5551 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5553 if (!HASHITEM_EMPTY(hi))
5555 item2 = dict_find(d2, hi->hi_key, -1);
5556 if (item2 == NULL)
5557 return FALSE;
5558 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5559 return FALSE;
5560 --todo;
5563 return TRUE;
5567 * Return TRUE if "tv1" and "tv2" have the same value.
5568 * Compares the items just like "==" would compare them, but strings and
5569 * numbers are different.
5571 static int
5572 tv_equal(tv1, tv2, ic)
5573 typval_T *tv1;
5574 typval_T *tv2;
5575 int ic; /* ignore case */
5577 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5578 char_u *s1, *s2;
5579 static int recursive = 0; /* cach recursive loops */
5580 int r;
5582 if (tv1->v_type != tv2->v_type)
5583 return FALSE;
5584 /* Catch lists and dicts that have an endless loop by limiting
5585 * recursiveness to 1000. We guess they are equal then. */
5586 if (recursive >= 1000)
5587 return TRUE;
5589 switch (tv1->v_type)
5591 case VAR_LIST:
5592 ++recursive;
5593 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5594 --recursive;
5595 return r;
5597 case VAR_DICT:
5598 ++recursive;
5599 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5600 --recursive;
5601 return r;
5603 case VAR_FUNC:
5604 return (tv1->vval.v_string != NULL
5605 && tv2->vval.v_string != NULL
5606 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5608 case VAR_NUMBER:
5609 return tv1->vval.v_number == tv2->vval.v_number;
5611 case VAR_STRING:
5612 s1 = get_tv_string_buf(tv1, buf1);
5613 s2 = get_tv_string_buf(tv2, buf2);
5614 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5617 EMSG2(_(e_intern2), "tv_equal()");
5618 return TRUE;
5622 * Locate item with index "n" in list "l" and return it.
5623 * A negative index is counted from the end; -1 is the last item.
5624 * Returns NULL when "n" is out of range.
5626 static listitem_T *
5627 list_find(l, n)
5628 list_T *l;
5629 long n;
5631 listitem_T *item;
5632 long idx;
5634 if (l == NULL)
5635 return NULL;
5637 /* Negative index is relative to the end. */
5638 if (n < 0)
5639 n = l->lv_len + n;
5641 /* Check for index out of range. */
5642 if (n < 0 || n >= l->lv_len)
5643 return NULL;
5645 /* When there is a cached index may start search from there. */
5646 if (l->lv_idx_item != NULL)
5648 if (n < l->lv_idx / 2)
5650 /* closest to the start of the list */
5651 item = l->lv_first;
5652 idx = 0;
5654 else if (n > (l->lv_idx + l->lv_len) / 2)
5656 /* closest to the end of the list */
5657 item = l->lv_last;
5658 idx = l->lv_len - 1;
5660 else
5662 /* closest to the cached index */
5663 item = l->lv_idx_item;
5664 idx = l->lv_idx;
5667 else
5669 if (n < l->lv_len / 2)
5671 /* closest to the start of the list */
5672 item = l->lv_first;
5673 idx = 0;
5675 else
5677 /* closest to the end of the list */
5678 item = l->lv_last;
5679 idx = l->lv_len - 1;
5683 while (n > idx)
5685 /* search forward */
5686 item = item->li_next;
5687 ++idx;
5689 while (n < idx)
5691 /* search backward */
5692 item = item->li_prev;
5693 --idx;
5696 /* cache the used index */
5697 l->lv_idx = idx;
5698 l->lv_idx_item = item;
5700 return item;
5704 * Get list item "l[idx]" as a number.
5706 static long
5707 list_find_nr(l, idx, errorp)
5708 list_T *l;
5709 long idx;
5710 int *errorp; /* set to TRUE when something wrong */
5712 listitem_T *li;
5714 li = list_find(l, idx);
5715 if (li == NULL)
5717 if (errorp != NULL)
5718 *errorp = TRUE;
5719 return -1L;
5721 return get_tv_number_chk(&li->li_tv, errorp);
5725 * Locate "item" list "l" and return its index.
5726 * Returns -1 when "item" is not in the list.
5728 static long
5729 list_idx_of_item(l, item)
5730 list_T *l;
5731 listitem_T *item;
5733 long idx = 0;
5734 listitem_T *li;
5736 if (l == NULL)
5737 return -1;
5738 idx = 0;
5739 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
5740 ++idx;
5741 if (li == NULL)
5742 return -1;
5743 return idx;
5747 * Append item "item" to the end of list "l".
5749 static void
5750 list_append(l, item)
5751 list_T *l;
5752 listitem_T *item;
5754 if (l->lv_last == NULL)
5756 /* empty list */
5757 l->lv_first = item;
5758 l->lv_last = item;
5759 item->li_prev = NULL;
5761 else
5763 l->lv_last->li_next = item;
5764 item->li_prev = l->lv_last;
5765 l->lv_last = item;
5767 ++l->lv_len;
5768 item->li_next = NULL;
5772 * Append typval_T "tv" to the end of list "l".
5773 * Return FAIL when out of memory.
5775 static int
5776 list_append_tv(l, tv)
5777 list_T *l;
5778 typval_T *tv;
5780 listitem_T *li = listitem_alloc();
5782 if (li == NULL)
5783 return FAIL;
5784 copy_tv(tv, &li->li_tv);
5785 list_append(l, li);
5786 return OK;
5790 * Add a dictionary to a list. Used by getqflist().
5791 * Return FAIL when out of memory.
5794 list_append_dict(list, dict)
5795 list_T *list;
5796 dict_T *dict;
5798 listitem_T *li = listitem_alloc();
5800 if (li == NULL)
5801 return FAIL;
5802 li->li_tv.v_type = VAR_DICT;
5803 li->li_tv.v_lock = 0;
5804 li->li_tv.vval.v_dict = dict;
5805 list_append(list, li);
5806 ++dict->dv_refcount;
5807 return OK;
5811 * Make a copy of "str" and append it as an item to list "l".
5812 * When "len" >= 0 use "str[len]".
5813 * Returns FAIL when out of memory.
5815 static int
5816 list_append_string(l, str, len)
5817 list_T *l;
5818 char_u *str;
5819 int len;
5821 listitem_T *li = listitem_alloc();
5823 if (li == NULL)
5824 return FAIL;
5825 list_append(l, li);
5826 li->li_tv.v_type = VAR_STRING;
5827 li->li_tv.v_lock = 0;
5828 if (str == NULL)
5829 li->li_tv.vval.v_string = NULL;
5830 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
5831 : vim_strsave(str))) == NULL)
5832 return FAIL;
5833 return OK;
5837 * Append "n" to list "l".
5838 * Returns FAIL when out of memory.
5840 static int
5841 list_append_number(l, n)
5842 list_T *l;
5843 varnumber_T n;
5845 listitem_T *li;
5847 li = listitem_alloc();
5848 if (li == NULL)
5849 return FAIL;
5850 li->li_tv.v_type = VAR_NUMBER;
5851 li->li_tv.v_lock = 0;
5852 li->li_tv.vval.v_number = n;
5853 list_append(l, li);
5854 return OK;
5858 * Insert typval_T "tv" in list "l" before "item".
5859 * If "item" is NULL append at the end.
5860 * Return FAIL when out of memory.
5862 static int
5863 list_insert_tv(l, tv, item)
5864 list_T *l;
5865 typval_T *tv;
5866 listitem_T *item;
5868 listitem_T *ni = listitem_alloc();
5870 if (ni == NULL)
5871 return FAIL;
5872 copy_tv(tv, &ni->li_tv);
5873 if (item == NULL)
5874 /* Append new item at end of list. */
5875 list_append(l, ni);
5876 else
5878 /* Insert new item before existing item. */
5879 ni->li_prev = item->li_prev;
5880 ni->li_next = item;
5881 if (item->li_prev == NULL)
5883 l->lv_first = ni;
5884 ++l->lv_idx;
5886 else
5888 item->li_prev->li_next = ni;
5889 l->lv_idx_item = NULL;
5891 item->li_prev = ni;
5892 ++l->lv_len;
5894 return OK;
5898 * Extend "l1" with "l2".
5899 * If "bef" is NULL append at the end, otherwise insert before this item.
5900 * Returns FAIL when out of memory.
5902 static int
5903 list_extend(l1, l2, bef)
5904 list_T *l1;
5905 list_T *l2;
5906 listitem_T *bef;
5908 listitem_T *item;
5910 for (item = l2->lv_first; item != NULL; item = item->li_next)
5911 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
5912 return FAIL;
5913 return OK;
5917 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
5918 * Return FAIL when out of memory.
5920 static int
5921 list_concat(l1, l2, tv)
5922 list_T *l1;
5923 list_T *l2;
5924 typval_T *tv;
5926 list_T *l;
5928 /* make a copy of the first list. */
5929 l = list_copy(l1, FALSE, 0);
5930 if (l == NULL)
5931 return FAIL;
5932 tv->v_type = VAR_LIST;
5933 tv->vval.v_list = l;
5935 /* append all items from the second list */
5936 return list_extend(l, l2, NULL);
5940 * Make a copy of list "orig". Shallow if "deep" is FALSE.
5941 * The refcount of the new list is set to 1.
5942 * See item_copy() for "copyID".
5943 * Returns NULL when out of memory.
5945 static list_T *
5946 list_copy(orig, deep, copyID)
5947 list_T *orig;
5948 int deep;
5949 int copyID;
5951 list_T *copy;
5952 listitem_T *item;
5953 listitem_T *ni;
5955 if (orig == NULL)
5956 return NULL;
5958 copy = list_alloc();
5959 if (copy != NULL)
5961 if (copyID != 0)
5963 /* Do this before adding the items, because one of the items may
5964 * refer back to this list. */
5965 orig->lv_copyID = copyID;
5966 orig->lv_copylist = copy;
5968 for (item = orig->lv_first; item != NULL && !got_int;
5969 item = item->li_next)
5971 ni = listitem_alloc();
5972 if (ni == NULL)
5973 break;
5974 if (deep)
5976 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
5978 vim_free(ni);
5979 break;
5982 else
5983 copy_tv(&item->li_tv, &ni->li_tv);
5984 list_append(copy, ni);
5986 ++copy->lv_refcount;
5987 if (item != NULL)
5989 list_unref(copy);
5990 copy = NULL;
5994 return copy;
5998 * Remove items "item" to "item2" from list "l".
5999 * Does not free the listitem or the value!
6001 static void
6002 list_remove(l, item, item2)
6003 list_T *l;
6004 listitem_T *item;
6005 listitem_T *item2;
6007 listitem_T *ip;
6009 /* notify watchers */
6010 for (ip = item; ip != NULL; ip = ip->li_next)
6012 --l->lv_len;
6013 list_fix_watch(l, ip);
6014 if (ip == item2)
6015 break;
6018 if (item2->li_next == NULL)
6019 l->lv_last = item->li_prev;
6020 else
6021 item2->li_next->li_prev = item->li_prev;
6022 if (item->li_prev == NULL)
6023 l->lv_first = item2->li_next;
6024 else
6025 item->li_prev->li_next = item2->li_next;
6026 l->lv_idx_item = NULL;
6030 * Return an allocated string with the string representation of a list.
6031 * May return NULL.
6033 static char_u *
6034 list2string(tv, copyID)
6035 typval_T *tv;
6036 int copyID;
6038 garray_T ga;
6040 if (tv->vval.v_list == NULL)
6041 return NULL;
6042 ga_init2(&ga, (int)sizeof(char), 80);
6043 ga_append(&ga, '[');
6044 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6046 vim_free(ga.ga_data);
6047 return NULL;
6049 ga_append(&ga, ']');
6050 ga_append(&ga, NUL);
6051 return (char_u *)ga.ga_data;
6055 * Join list "l" into a string in "*gap", using separator "sep".
6056 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6057 * Return FAIL or OK.
6059 static int
6060 list_join(gap, l, sep, echo, copyID)
6061 garray_T *gap;
6062 list_T *l;
6063 char_u *sep;
6064 int echo;
6065 int copyID;
6067 int first = TRUE;
6068 char_u *tofree;
6069 char_u numbuf[NUMBUFLEN];
6070 listitem_T *item;
6071 char_u *s;
6073 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6075 if (first)
6076 first = FALSE;
6077 else
6078 ga_concat(gap, sep);
6080 if (echo)
6081 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6082 else
6083 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6084 if (s != NULL)
6085 ga_concat(gap, s);
6086 vim_free(tofree);
6087 if (s == NULL)
6088 return FAIL;
6090 return OK;
6094 * Garbage collection for lists and dictionaries.
6096 * We use reference counts to be able to free most items right away when they
6097 * are no longer used. But for composite items it's possible that it becomes
6098 * unused while the reference count is > 0: When there is a recursive
6099 * reference. Example:
6100 * :let l = [1, 2, 3]
6101 * :let d = {9: l}
6102 * :let l[1] = d
6104 * Since this is quite unusual we handle this with garbage collection: every
6105 * once in a while find out which lists and dicts are not referenced from any
6106 * variable.
6108 * Here is a good reference text about garbage collection (refers to Python
6109 * but it applies to all reference-counting mechanisms):
6110 * http://python.ca/nas/python/gc/
6114 * Do garbage collection for lists and dicts.
6115 * Return TRUE if some memory was freed.
6118 garbage_collect()
6120 dict_T *dd;
6121 list_T *ll;
6122 int copyID = ++current_copyID;
6123 buf_T *buf;
6124 win_T *wp;
6125 int i;
6126 funccall_T *fc;
6127 int did_free = FALSE;
6128 #ifdef FEAT_WINDOWS
6129 tabpage_T *tp;
6130 #endif
6132 /* Only do this once. */
6133 want_garbage_collect = FALSE;
6134 may_garbage_collect = FALSE;
6135 garbage_collect_at_exit = FALSE;
6138 * 1. Go through all accessible variables and mark all lists and dicts
6139 * with copyID.
6141 /* script-local variables */
6142 for (i = 1; i <= ga_scripts.ga_len; ++i)
6143 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6145 /* buffer-local variables */
6146 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6147 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6149 /* window-local variables */
6150 FOR_ALL_TAB_WINDOWS(tp, wp)
6151 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6153 #ifdef FEAT_WINDOWS
6154 /* tabpage-local variables */
6155 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6156 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6157 #endif
6159 /* global variables */
6160 set_ref_in_ht(&globvarht, copyID);
6162 /* function-local variables */
6163 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6165 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6166 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6170 * 2. Go through the list of dicts and free items without the copyID.
6172 for (dd = first_dict; dd != NULL; )
6173 if (dd->dv_copyID != copyID)
6175 /* Free the Dictionary and ordinary items it contains, but don't
6176 * recurse into Lists and Dictionaries, they will be in the list
6177 * of dicts or list of lists. */
6178 dict_free(dd, FALSE);
6179 did_free = TRUE;
6181 /* restart, next dict may also have been freed */
6182 dd = first_dict;
6184 else
6185 dd = dd->dv_used_next;
6188 * 3. Go through the list of lists and free items without the copyID.
6189 * But don't free a list that has a watcher (used in a for loop), these
6190 * are not referenced anywhere.
6192 for (ll = first_list; ll != NULL; )
6193 if (ll->lv_copyID != copyID && ll->lv_watch == NULL)
6195 /* Free the List and ordinary items it contains, but don't recurse
6196 * into Lists and Dictionaries, they will be in the list of dicts
6197 * or list of lists. */
6198 list_free(ll, FALSE);
6199 did_free = TRUE;
6201 /* restart, next list may also have been freed */
6202 ll = first_list;
6204 else
6205 ll = ll->lv_used_next;
6207 return did_free;
6211 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6213 static void
6214 set_ref_in_ht(ht, copyID)
6215 hashtab_T *ht;
6216 int copyID;
6218 int todo;
6219 hashitem_T *hi;
6221 todo = (int)ht->ht_used;
6222 for (hi = ht->ht_array; todo > 0; ++hi)
6223 if (!HASHITEM_EMPTY(hi))
6225 --todo;
6226 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6231 * Mark all lists and dicts referenced through list "l" with "copyID".
6233 static void
6234 set_ref_in_list(l, copyID)
6235 list_T *l;
6236 int copyID;
6238 listitem_T *li;
6240 for (li = l->lv_first; li != NULL; li = li->li_next)
6241 set_ref_in_item(&li->li_tv, copyID);
6245 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6247 static void
6248 set_ref_in_item(tv, copyID)
6249 typval_T *tv;
6250 int copyID;
6252 dict_T *dd;
6253 list_T *ll;
6255 switch (tv->v_type)
6257 case VAR_DICT:
6258 dd = tv->vval.v_dict;
6259 if (dd->dv_copyID != copyID)
6261 /* Didn't see this dict yet. */
6262 dd->dv_copyID = copyID;
6263 set_ref_in_ht(&dd->dv_hashtab, copyID);
6265 break;
6267 case VAR_LIST:
6268 ll = tv->vval.v_list;
6269 if (ll->lv_copyID != copyID)
6271 /* Didn't see this list yet. */
6272 ll->lv_copyID = copyID;
6273 set_ref_in_list(ll, copyID);
6275 break;
6277 return;
6281 * Allocate an empty header for a dictionary.
6283 dict_T *
6284 dict_alloc()
6286 dict_T *d;
6288 d = (dict_T *)alloc(sizeof(dict_T));
6289 if (d != NULL)
6291 /* Add the list to the list of dicts for garbage collection. */
6292 if (first_dict != NULL)
6293 first_dict->dv_used_prev = d;
6294 d->dv_used_next = first_dict;
6295 d->dv_used_prev = NULL;
6296 first_dict = d;
6298 hash_init(&d->dv_hashtab);
6299 d->dv_lock = 0;
6300 d->dv_refcount = 0;
6301 d->dv_copyID = 0;
6303 return d;
6307 * Unreference a Dictionary: decrement the reference count and free it when it
6308 * becomes zero.
6310 static void
6311 dict_unref(d)
6312 dict_T *d;
6314 if (d != NULL && --d->dv_refcount <= 0)
6315 dict_free(d, TRUE);
6319 * Free a Dictionary, including all items it contains.
6320 * Ignores the reference count.
6322 static void
6323 dict_free(d, recurse)
6324 dict_T *d;
6325 int recurse; /* Free Lists and Dictionaries recursively. */
6327 int todo;
6328 hashitem_T *hi;
6329 dictitem_T *di;
6331 /* Remove the dict from the list of dicts for garbage collection. */
6332 if (d->dv_used_prev == NULL)
6333 first_dict = d->dv_used_next;
6334 else
6335 d->dv_used_prev->dv_used_next = d->dv_used_next;
6336 if (d->dv_used_next != NULL)
6337 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6339 /* Lock the hashtab, we don't want it to resize while freeing items. */
6340 hash_lock(&d->dv_hashtab);
6341 todo = (int)d->dv_hashtab.ht_used;
6342 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6344 if (!HASHITEM_EMPTY(hi))
6346 /* Remove the item before deleting it, just in case there is
6347 * something recursive causing trouble. */
6348 di = HI2DI(hi);
6349 hash_remove(&d->dv_hashtab, hi);
6350 if (recurse || (di->di_tv.v_type != VAR_LIST
6351 && di->di_tv.v_type != VAR_DICT))
6352 clear_tv(&di->di_tv);
6353 vim_free(di);
6354 --todo;
6357 hash_clear(&d->dv_hashtab);
6358 vim_free(d);
6362 * Allocate a Dictionary item.
6363 * The "key" is copied to the new item.
6364 * Note that the value of the item "di_tv" still needs to be initialized!
6365 * Returns NULL when out of memory.
6367 static dictitem_T *
6368 dictitem_alloc(key)
6369 char_u *key;
6371 dictitem_T *di;
6373 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6374 if (di != NULL)
6376 STRCPY(di->di_key, key);
6377 di->di_flags = 0;
6379 return di;
6383 * Make a copy of a Dictionary item.
6385 static dictitem_T *
6386 dictitem_copy(org)
6387 dictitem_T *org;
6389 dictitem_T *di;
6391 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6392 + STRLEN(org->di_key)));
6393 if (di != NULL)
6395 STRCPY(di->di_key, org->di_key);
6396 di->di_flags = 0;
6397 copy_tv(&org->di_tv, &di->di_tv);
6399 return di;
6403 * Remove item "item" from Dictionary "dict" and free it.
6405 static void
6406 dictitem_remove(dict, item)
6407 dict_T *dict;
6408 dictitem_T *item;
6410 hashitem_T *hi;
6412 hi = hash_find(&dict->dv_hashtab, item->di_key);
6413 if (HASHITEM_EMPTY(hi))
6414 EMSG2(_(e_intern2), "dictitem_remove()");
6415 else
6416 hash_remove(&dict->dv_hashtab, hi);
6417 dictitem_free(item);
6421 * Free a dict item. Also clears the value.
6423 static void
6424 dictitem_free(item)
6425 dictitem_T *item;
6427 clear_tv(&item->di_tv);
6428 vim_free(item);
6432 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6433 * The refcount of the new dict is set to 1.
6434 * See item_copy() for "copyID".
6435 * Returns NULL when out of memory.
6437 static dict_T *
6438 dict_copy(orig, deep, copyID)
6439 dict_T *orig;
6440 int deep;
6441 int copyID;
6443 dict_T *copy;
6444 dictitem_T *di;
6445 int todo;
6446 hashitem_T *hi;
6448 if (orig == NULL)
6449 return NULL;
6451 copy = dict_alloc();
6452 if (copy != NULL)
6454 if (copyID != 0)
6456 orig->dv_copyID = copyID;
6457 orig->dv_copydict = copy;
6459 todo = (int)orig->dv_hashtab.ht_used;
6460 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6462 if (!HASHITEM_EMPTY(hi))
6464 --todo;
6466 di = dictitem_alloc(hi->hi_key);
6467 if (di == NULL)
6468 break;
6469 if (deep)
6471 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6472 copyID) == FAIL)
6474 vim_free(di);
6475 break;
6478 else
6479 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6480 if (dict_add(copy, di) == FAIL)
6482 dictitem_free(di);
6483 break;
6488 ++copy->dv_refcount;
6489 if (todo > 0)
6491 dict_unref(copy);
6492 copy = NULL;
6496 return copy;
6500 * Add item "item" to Dictionary "d".
6501 * Returns FAIL when out of memory and when key already existed.
6503 static int
6504 dict_add(d, item)
6505 dict_T *d;
6506 dictitem_T *item;
6508 return hash_add(&d->dv_hashtab, item->di_key);
6512 * Add a number or string entry to dictionary "d".
6513 * When "str" is NULL use number "nr", otherwise use "str".
6514 * Returns FAIL when out of memory and when key already exists.
6517 dict_add_nr_str(d, key, nr, str)
6518 dict_T *d;
6519 char *key;
6520 long nr;
6521 char_u *str;
6523 dictitem_T *item;
6525 item = dictitem_alloc((char_u *)key);
6526 if (item == NULL)
6527 return FAIL;
6528 item->di_tv.v_lock = 0;
6529 if (str == NULL)
6531 item->di_tv.v_type = VAR_NUMBER;
6532 item->di_tv.vval.v_number = nr;
6534 else
6536 item->di_tv.v_type = VAR_STRING;
6537 item->di_tv.vval.v_string = vim_strsave(str);
6539 if (dict_add(d, item) == FAIL)
6541 dictitem_free(item);
6542 return FAIL;
6544 return OK;
6548 * Get the number of items in a Dictionary.
6550 static long
6551 dict_len(d)
6552 dict_T *d;
6554 if (d == NULL)
6555 return 0L;
6556 return (long)d->dv_hashtab.ht_used;
6560 * Find item "key[len]" in Dictionary "d".
6561 * If "len" is negative use strlen(key).
6562 * Returns NULL when not found.
6564 static dictitem_T *
6565 dict_find(d, key, len)
6566 dict_T *d;
6567 char_u *key;
6568 int len;
6570 #define AKEYLEN 200
6571 char_u buf[AKEYLEN];
6572 char_u *akey;
6573 char_u *tofree = NULL;
6574 hashitem_T *hi;
6576 if (len < 0)
6577 akey = key;
6578 else if (len >= AKEYLEN)
6580 tofree = akey = vim_strnsave(key, len);
6581 if (akey == NULL)
6582 return NULL;
6584 else
6586 /* Avoid a malloc/free by using buf[]. */
6587 vim_strncpy(buf, key, len);
6588 akey = buf;
6591 hi = hash_find(&d->dv_hashtab, akey);
6592 vim_free(tofree);
6593 if (HASHITEM_EMPTY(hi))
6594 return NULL;
6595 return HI2DI(hi);
6599 * Get a string item from a dictionary.
6600 * When "save" is TRUE allocate memory for it.
6601 * Returns NULL if the entry doesn't exist or out of memory.
6603 char_u *
6604 get_dict_string(d, key, save)
6605 dict_T *d;
6606 char_u *key;
6607 int save;
6609 dictitem_T *di;
6610 char_u *s;
6612 di = dict_find(d, key, -1);
6613 if (di == NULL)
6614 return NULL;
6615 s = get_tv_string(&di->di_tv);
6616 if (save && s != NULL)
6617 s = vim_strsave(s);
6618 return s;
6622 * Get a number item from a dictionary.
6623 * Returns 0 if the entry doesn't exist or out of memory.
6625 long
6626 get_dict_number(d, key)
6627 dict_T *d;
6628 char_u *key;
6630 dictitem_T *di;
6632 di = dict_find(d, key, -1);
6633 if (di == NULL)
6634 return 0;
6635 return get_tv_number(&di->di_tv);
6639 * Return an allocated string with the string representation of a Dictionary.
6640 * May return NULL.
6642 static char_u *
6643 dict2string(tv, copyID)
6644 typval_T *tv;
6645 int copyID;
6647 garray_T ga;
6648 int first = TRUE;
6649 char_u *tofree;
6650 char_u numbuf[NUMBUFLEN];
6651 hashitem_T *hi;
6652 char_u *s;
6653 dict_T *d;
6654 int todo;
6656 if ((d = tv->vval.v_dict) == NULL)
6657 return NULL;
6658 ga_init2(&ga, (int)sizeof(char), 80);
6659 ga_append(&ga, '{');
6661 todo = (int)d->dv_hashtab.ht_used;
6662 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6664 if (!HASHITEM_EMPTY(hi))
6666 --todo;
6668 if (first)
6669 first = FALSE;
6670 else
6671 ga_concat(&ga, (char_u *)", ");
6673 tofree = string_quote(hi->hi_key, FALSE);
6674 if (tofree != NULL)
6676 ga_concat(&ga, tofree);
6677 vim_free(tofree);
6679 ga_concat(&ga, (char_u *)": ");
6680 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
6681 if (s != NULL)
6682 ga_concat(&ga, s);
6683 vim_free(tofree);
6684 if (s == NULL)
6685 break;
6688 if (todo > 0)
6690 vim_free(ga.ga_data);
6691 return NULL;
6694 ga_append(&ga, '}');
6695 ga_append(&ga, NUL);
6696 return (char_u *)ga.ga_data;
6700 * Allocate a variable for a Dictionary and fill it from "*arg".
6701 * Return OK or FAIL. Returns NOTDONE for {expr}.
6703 static int
6704 get_dict_tv(arg, rettv, evaluate)
6705 char_u **arg;
6706 typval_T *rettv;
6707 int evaluate;
6709 dict_T *d = NULL;
6710 typval_T tvkey;
6711 typval_T tv;
6712 char_u *key = NULL;
6713 dictitem_T *item;
6714 char_u *start = skipwhite(*arg + 1);
6715 char_u buf[NUMBUFLEN];
6718 * First check if it's not a curly-braces thing: {expr}.
6719 * Must do this without evaluating, otherwise a function may be called
6720 * twice. Unfortunately this means we need to call eval1() twice for the
6721 * first item.
6722 * But {} is an empty Dictionary.
6724 if (*start != '}')
6726 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
6727 return FAIL;
6728 if (*start == '}')
6729 return NOTDONE;
6732 if (evaluate)
6734 d = dict_alloc();
6735 if (d == NULL)
6736 return FAIL;
6738 tvkey.v_type = VAR_UNKNOWN;
6739 tv.v_type = VAR_UNKNOWN;
6741 *arg = skipwhite(*arg + 1);
6742 while (**arg != '}' && **arg != NUL)
6744 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
6745 goto failret;
6746 if (**arg != ':')
6748 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
6749 clear_tv(&tvkey);
6750 goto failret;
6752 if (evaluate)
6754 key = get_tv_string_buf_chk(&tvkey, buf);
6755 if (key == NULL || *key == NUL)
6757 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
6758 if (key != NULL)
6759 EMSG(_(e_emptykey));
6760 clear_tv(&tvkey);
6761 goto failret;
6765 *arg = skipwhite(*arg + 1);
6766 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
6768 if (evaluate)
6769 clear_tv(&tvkey);
6770 goto failret;
6772 if (evaluate)
6774 item = dict_find(d, key, -1);
6775 if (item != NULL)
6777 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
6778 clear_tv(&tvkey);
6779 clear_tv(&tv);
6780 goto failret;
6782 item = dictitem_alloc(key);
6783 clear_tv(&tvkey);
6784 if (item != NULL)
6786 item->di_tv = tv;
6787 item->di_tv.v_lock = 0;
6788 if (dict_add(d, item) == FAIL)
6789 dictitem_free(item);
6793 if (**arg == '}')
6794 break;
6795 if (**arg != ',')
6797 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
6798 goto failret;
6800 *arg = skipwhite(*arg + 1);
6803 if (**arg != '}')
6805 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
6806 failret:
6807 if (evaluate)
6808 dict_free(d, TRUE);
6809 return FAIL;
6812 *arg = skipwhite(*arg + 1);
6813 if (evaluate)
6815 rettv->v_type = VAR_DICT;
6816 rettv->vval.v_dict = d;
6817 ++d->dv_refcount;
6820 return OK;
6824 * Return a string with the string representation of a variable.
6825 * If the memory is allocated "tofree" is set to it, otherwise NULL.
6826 * "numbuf" is used for a number.
6827 * Does not put quotes around strings, as ":echo" displays values.
6828 * When "copyID" is not NULL replace recursive lists and dicts with "...".
6829 * May return NULL.
6831 static char_u *
6832 echo_string(tv, tofree, numbuf, copyID)
6833 typval_T *tv;
6834 char_u **tofree;
6835 char_u *numbuf;
6836 int copyID;
6838 static int recurse = 0;
6839 char_u *r = NULL;
6841 if (recurse >= DICT_MAXNEST)
6843 EMSG(_("E724: variable nested too deep for displaying"));
6844 *tofree = NULL;
6845 return NULL;
6847 ++recurse;
6849 switch (tv->v_type)
6851 case VAR_FUNC:
6852 *tofree = NULL;
6853 r = tv->vval.v_string;
6854 break;
6856 case VAR_LIST:
6857 if (tv->vval.v_list == NULL)
6859 *tofree = NULL;
6860 r = NULL;
6862 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
6864 *tofree = NULL;
6865 r = (char_u *)"[...]";
6867 else
6869 tv->vval.v_list->lv_copyID = copyID;
6870 *tofree = list2string(tv, copyID);
6871 r = *tofree;
6873 break;
6875 case VAR_DICT:
6876 if (tv->vval.v_dict == NULL)
6878 *tofree = NULL;
6879 r = NULL;
6881 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
6883 *tofree = NULL;
6884 r = (char_u *)"{...}";
6886 else
6888 tv->vval.v_dict->dv_copyID = copyID;
6889 *tofree = dict2string(tv, copyID);
6890 r = *tofree;
6892 break;
6894 case VAR_STRING:
6895 case VAR_NUMBER:
6896 *tofree = NULL;
6897 r = get_tv_string_buf(tv, numbuf);
6898 break;
6900 default:
6901 EMSG2(_(e_intern2), "echo_string()");
6902 *tofree = NULL;
6905 --recurse;
6906 return r;
6910 * Return a string with the string representation of a variable.
6911 * If the memory is allocated "tofree" is set to it, otherwise NULL.
6912 * "numbuf" is used for a number.
6913 * Puts quotes around strings, so that they can be parsed back by eval().
6914 * May return NULL.
6916 static char_u *
6917 tv2string(tv, tofree, numbuf, copyID)
6918 typval_T *tv;
6919 char_u **tofree;
6920 char_u *numbuf;
6921 int copyID;
6923 switch (tv->v_type)
6925 case VAR_FUNC:
6926 *tofree = string_quote(tv->vval.v_string, TRUE);
6927 return *tofree;
6928 case VAR_STRING:
6929 *tofree = string_quote(tv->vval.v_string, FALSE);
6930 return *tofree;
6931 case VAR_NUMBER:
6932 case VAR_LIST:
6933 case VAR_DICT:
6934 break;
6935 default:
6936 EMSG2(_(e_intern2), "tv2string()");
6938 return echo_string(tv, tofree, numbuf, copyID);
6942 * Return string "str" in ' quotes, doubling ' characters.
6943 * If "str" is NULL an empty string is assumed.
6944 * If "function" is TRUE make it function('string').
6946 static char_u *
6947 string_quote(str, function)
6948 char_u *str;
6949 int function;
6951 unsigned len;
6952 char_u *p, *r, *s;
6954 len = (function ? 13 : 3);
6955 if (str != NULL)
6957 len += (unsigned)STRLEN(str);
6958 for (p = str; *p != NUL; mb_ptr_adv(p))
6959 if (*p == '\'')
6960 ++len;
6962 s = r = alloc(len);
6963 if (r != NULL)
6965 if (function)
6967 STRCPY(r, "function('");
6968 r += 10;
6970 else
6971 *r++ = '\'';
6972 if (str != NULL)
6973 for (p = str; *p != NUL; )
6975 if (*p == '\'')
6976 *r++ = '\'';
6977 MB_COPY_CHAR(p, r);
6979 *r++ = '\'';
6980 if (function)
6981 *r++ = ')';
6982 *r++ = NUL;
6984 return s;
6988 * Get the value of an environment variable.
6989 * "arg" is pointing to the '$'. It is advanced to after the name.
6990 * If the environment variable was not set, silently assume it is empty.
6991 * Always return OK.
6993 static int
6994 get_env_tv(arg, rettv, evaluate)
6995 char_u **arg;
6996 typval_T *rettv;
6997 int evaluate;
6999 char_u *string = NULL;
7000 int len;
7001 int cc;
7002 char_u *name;
7003 int mustfree = FALSE;
7005 ++*arg;
7006 name = *arg;
7007 len = get_env_len(arg);
7008 if (evaluate)
7010 if (len != 0)
7012 cc = name[len];
7013 name[len] = NUL;
7014 /* first try vim_getenv(), fast for normal environment vars */
7015 string = vim_getenv(name, &mustfree);
7016 if (string != NULL && *string != NUL)
7018 if (!mustfree)
7019 string = vim_strsave(string);
7021 else
7023 if (mustfree)
7024 vim_free(string);
7026 /* next try expanding things like $VIM and ${HOME} */
7027 string = expand_env_save(name - 1);
7028 if (string != NULL && *string == '$')
7030 vim_free(string);
7031 string = NULL;
7034 name[len] = cc;
7036 rettv->v_type = VAR_STRING;
7037 rettv->vval.v_string = string;
7040 return OK;
7044 * Array with names and number of arguments of all internal functions
7045 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7047 static struct fst
7049 char *f_name; /* function name */
7050 char f_min_argc; /* minimal number of arguments */
7051 char f_max_argc; /* maximal number of arguments */
7052 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7053 /* implementation of function */
7054 } functions[] =
7056 {"add", 2, 2, f_add},
7057 {"append", 2, 2, f_append},
7058 {"argc", 0, 0, f_argc},
7059 {"argidx", 0, 0, f_argidx},
7060 {"argv", 0, 1, f_argv},
7061 {"browse", 4, 4, f_browse},
7062 {"browsedir", 2, 2, f_browsedir},
7063 {"bufexists", 1, 1, f_bufexists},
7064 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7065 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7066 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7067 {"buflisted", 1, 1, f_buflisted},
7068 {"bufloaded", 1, 1, f_bufloaded},
7069 {"bufname", 1, 1, f_bufname},
7070 {"bufnr", 1, 2, f_bufnr},
7071 {"bufwinnr", 1, 1, f_bufwinnr},
7072 {"byte2line", 1, 1, f_byte2line},
7073 {"byteidx", 2, 2, f_byteidx},
7074 {"call", 2, 3, f_call},
7075 {"changenr", 0, 0, f_changenr},
7076 {"char2nr", 1, 1, f_char2nr},
7077 {"cindent", 1, 1, f_cindent},
7078 {"clearmatches", 0, 0, f_clearmatches},
7079 {"col", 1, 1, f_col},
7080 #if defined(FEAT_INS_EXPAND)
7081 {"complete", 2, 2, f_complete},
7082 {"complete_add", 1, 1, f_complete_add},
7083 {"complete_check", 0, 0, f_complete_check},
7084 #endif
7085 {"confirm", 1, 4, f_confirm},
7086 {"copy", 1, 1, f_copy},
7087 {"count", 2, 4, f_count},
7088 {"cscope_connection",0,3, f_cscope_connection},
7089 {"cursor", 1, 3, f_cursor},
7090 {"deepcopy", 1, 2, f_deepcopy},
7091 {"delete", 1, 1, f_delete},
7092 {"did_filetype", 0, 0, f_did_filetype},
7093 {"diff_filler", 1, 1, f_diff_filler},
7094 {"diff_hlID", 2, 2, f_diff_hlID},
7095 {"empty", 1, 1, f_empty},
7096 {"escape", 2, 2, f_escape},
7097 {"eval", 1, 1, f_eval},
7098 {"eventhandler", 0, 0, f_eventhandler},
7099 {"executable", 1, 1, f_executable},
7100 {"exists", 1, 1, f_exists},
7101 {"expand", 1, 2, f_expand},
7102 {"extend", 2, 3, f_extend},
7103 {"feedkeys", 1, 2, f_feedkeys},
7104 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7105 {"filereadable", 1, 1, f_filereadable},
7106 {"filewritable", 1, 1, f_filewritable},
7107 {"filter", 2, 2, f_filter},
7108 {"finddir", 1, 3, f_finddir},
7109 {"findfile", 1, 3, f_findfile},
7110 {"fnamemodify", 2, 2, f_fnamemodify},
7111 {"foldclosed", 1, 1, f_foldclosed},
7112 {"foldclosedend", 1, 1, f_foldclosedend},
7113 {"foldlevel", 1, 1, f_foldlevel},
7114 {"foldtext", 0, 0, f_foldtext},
7115 {"foldtextresult", 1, 1, f_foldtextresult},
7116 {"foreground", 0, 0, f_foreground},
7117 {"function", 1, 1, f_function},
7118 {"garbagecollect", 0, 1, f_garbagecollect},
7119 {"get", 2, 3, f_get},
7120 {"getbufline", 2, 3, f_getbufline},
7121 {"getbufvar", 2, 2, f_getbufvar},
7122 {"getchar", 0, 1, f_getchar},
7123 {"getcharmod", 0, 0, f_getcharmod},
7124 {"getcmdline", 0, 0, f_getcmdline},
7125 {"getcmdpos", 0, 0, f_getcmdpos},
7126 {"getcmdtype", 0, 0, f_getcmdtype},
7127 {"getcwd", 0, 0, f_getcwd},
7128 {"getfontname", 0, 1, f_getfontname},
7129 {"getfperm", 1, 1, f_getfperm},
7130 {"getfsize", 1, 1, f_getfsize},
7131 {"getftime", 1, 1, f_getftime},
7132 {"getftype", 1, 1, f_getftype},
7133 {"getline", 1, 2, f_getline},
7134 {"getloclist", 1, 1, f_getqflist},
7135 {"getmatches", 0, 0, f_getmatches},
7136 {"getpid", 0, 0, f_getpid},
7137 {"getpos", 1, 1, f_getpos},
7138 {"getqflist", 0, 0, f_getqflist},
7139 {"getreg", 0, 2, f_getreg},
7140 {"getregtype", 0, 1, f_getregtype},
7141 {"gettabwinvar", 3, 3, f_gettabwinvar},
7142 {"getwinposx", 0, 0, f_getwinposx},
7143 {"getwinposy", 0, 0, f_getwinposy},
7144 {"getwinvar", 2, 2, f_getwinvar},
7145 {"glob", 1, 1, f_glob},
7146 {"globpath", 2, 2, f_globpath},
7147 {"has", 1, 1, f_has},
7148 {"has_key", 2, 2, f_has_key},
7149 {"haslocaldir", 0, 0, f_haslocaldir},
7150 {"hasmapto", 1, 3, f_hasmapto},
7151 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7152 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7153 {"histadd", 2, 2, f_histadd},
7154 {"histdel", 1, 2, f_histdel},
7155 {"histget", 1, 2, f_histget},
7156 {"histnr", 1, 1, f_histnr},
7157 {"hlID", 1, 1, f_hlID},
7158 {"hlexists", 1, 1, f_hlexists},
7159 {"hostname", 0, 0, f_hostname},
7160 {"iconv", 3, 3, f_iconv},
7161 {"indent", 1, 1, f_indent},
7162 {"index", 2, 4, f_index},
7163 {"input", 1, 3, f_input},
7164 {"inputdialog", 1, 3, f_inputdialog},
7165 {"inputlist", 1, 1, f_inputlist},
7166 {"inputrestore", 0, 0, f_inputrestore},
7167 {"inputsave", 0, 0, f_inputsave},
7168 {"inputsecret", 1, 2, f_inputsecret},
7169 {"insert", 2, 3, f_insert},
7170 {"isdirectory", 1, 1, f_isdirectory},
7171 {"islocked", 1, 1, f_islocked},
7172 {"items", 1, 1, f_items},
7173 {"join", 1, 2, f_join},
7174 {"keys", 1, 1, f_keys},
7175 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7176 {"len", 1, 1, f_len},
7177 {"libcall", 3, 3, f_libcall},
7178 {"libcallnr", 3, 3, f_libcallnr},
7179 {"line", 1, 1, f_line},
7180 {"line2byte", 1, 1, f_line2byte},
7181 {"lispindent", 1, 1, f_lispindent},
7182 {"localtime", 0, 0, f_localtime},
7183 {"map", 2, 2, f_map},
7184 {"maparg", 1, 3, f_maparg},
7185 {"mapcheck", 1, 3, f_mapcheck},
7186 {"match", 2, 4, f_match},
7187 {"matchadd", 2, 4, f_matchadd},
7188 {"matcharg", 1, 1, f_matcharg},
7189 {"matchdelete", 1, 1, f_matchdelete},
7190 {"matchend", 2, 4, f_matchend},
7191 {"matchlist", 2, 4, f_matchlist},
7192 {"matchstr", 2, 4, f_matchstr},
7193 {"max", 1, 1, f_max},
7194 {"min", 1, 1, f_min},
7195 #ifdef vim_mkdir
7196 {"mkdir", 1, 3, f_mkdir},
7197 #endif
7198 {"mode", 0, 0, f_mode},
7199 {"nextnonblank", 1, 1, f_nextnonblank},
7200 {"nr2char", 1, 1, f_nr2char},
7201 {"pathshorten", 1, 1, f_pathshorten},
7202 {"prevnonblank", 1, 1, f_prevnonblank},
7203 {"printf", 2, 19, f_printf},
7204 {"pumvisible", 0, 0, f_pumvisible},
7205 {"range", 1, 3, f_range},
7206 {"readfile", 1, 3, f_readfile},
7207 {"reltime", 0, 2, f_reltime},
7208 {"reltimestr", 1, 1, f_reltimestr},
7209 {"remote_expr", 2, 3, f_remote_expr},
7210 {"remote_foreground", 1, 1, f_remote_foreground},
7211 {"remote_peek", 1, 2, f_remote_peek},
7212 {"remote_read", 1, 1, f_remote_read},
7213 {"remote_send", 2, 3, f_remote_send},
7214 {"remove", 2, 3, f_remove},
7215 {"rename", 2, 2, f_rename},
7216 {"repeat", 2, 2, f_repeat},
7217 {"resolve", 1, 1, f_resolve},
7218 {"reverse", 1, 1, f_reverse},
7219 {"search", 1, 4, f_search},
7220 {"searchdecl", 1, 3, f_searchdecl},
7221 {"searchpair", 3, 7, f_searchpair},
7222 {"searchpairpos", 3, 7, f_searchpairpos},
7223 {"searchpos", 1, 4, f_searchpos},
7224 {"server2client", 2, 2, f_server2client},
7225 {"serverlist", 0, 0, f_serverlist},
7226 {"setbufvar", 3, 3, f_setbufvar},
7227 {"setcmdpos", 1, 1, f_setcmdpos},
7228 {"setline", 2, 2, f_setline},
7229 {"setloclist", 2, 3, f_setloclist},
7230 {"setmatches", 1, 1, f_setmatches},
7231 {"setpos", 2, 2, f_setpos},
7232 {"setqflist", 1, 2, f_setqflist},
7233 {"setreg", 2, 3, f_setreg},
7234 {"settabwinvar", 4, 4, f_settabwinvar},
7235 {"setwinvar", 3, 3, f_setwinvar},
7236 {"shellescape", 1, 1, f_shellescape},
7237 {"simplify", 1, 1, f_simplify},
7238 {"sort", 1, 2, f_sort},
7239 {"soundfold", 1, 1, f_soundfold},
7240 {"spellbadword", 0, 1, f_spellbadword},
7241 {"spellsuggest", 1, 3, f_spellsuggest},
7242 {"split", 1, 3, f_split},
7243 {"str2nr", 1, 2, f_str2nr},
7244 #ifdef HAVE_STRFTIME
7245 {"strftime", 1, 2, f_strftime},
7246 #endif
7247 {"stridx", 2, 3, f_stridx},
7248 {"string", 1, 1, f_string},
7249 {"strlen", 1, 1, f_strlen},
7250 {"strpart", 2, 3, f_strpart},
7251 {"strridx", 2, 3, f_strridx},
7252 {"strtrans", 1, 1, f_strtrans},
7253 {"submatch", 1, 1, f_submatch},
7254 {"substitute", 4, 4, f_substitute},
7255 {"synID", 3, 3, f_synID},
7256 {"synIDattr", 2, 3, f_synIDattr},
7257 {"synIDtrans", 1, 1, f_synIDtrans},
7258 {"synstack", 2, 2, f_synstack},
7259 {"system", 1, 2, f_system},
7260 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7261 {"tabpagenr", 0, 1, f_tabpagenr},
7262 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7263 {"tagfiles", 0, 0, f_tagfiles},
7264 {"taglist", 1, 1, f_taglist},
7265 {"tempname", 0, 0, f_tempname},
7266 {"test", 1, 1, f_test},
7267 {"tolower", 1, 1, f_tolower},
7268 {"toupper", 1, 1, f_toupper},
7269 {"tr", 3, 3, f_tr},
7270 {"type", 1, 1, f_type},
7271 {"values", 1, 1, f_values},
7272 {"virtcol", 1, 1, f_virtcol},
7273 {"visualmode", 0, 1, f_visualmode},
7274 {"winbufnr", 1, 1, f_winbufnr},
7275 {"wincol", 0, 0, f_wincol},
7276 {"winheight", 1, 1, f_winheight},
7277 {"winline", 0, 0, f_winline},
7278 {"winnr", 0, 1, f_winnr},
7279 {"winrestcmd", 0, 0, f_winrestcmd},
7280 {"winrestview", 1, 1, f_winrestview},
7281 {"winsaveview", 0, 0, f_winsaveview},
7282 {"winwidth", 1, 1, f_winwidth},
7283 {"writefile", 2, 3, f_writefile},
7286 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7289 * Function given to ExpandGeneric() to obtain the list of internal
7290 * or user defined function names.
7292 char_u *
7293 get_function_name(xp, idx)
7294 expand_T *xp;
7295 int idx;
7297 static int intidx = -1;
7298 char_u *name;
7300 if (idx == 0)
7301 intidx = -1;
7302 if (intidx < 0)
7304 name = get_user_func_name(xp, idx);
7305 if (name != NULL)
7306 return name;
7308 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7310 STRCPY(IObuff, functions[intidx].f_name);
7311 STRCAT(IObuff, "(");
7312 if (functions[intidx].f_max_argc == 0)
7313 STRCAT(IObuff, ")");
7314 return IObuff;
7317 return NULL;
7321 * Function given to ExpandGeneric() to obtain the list of internal or
7322 * user defined variable or function names.
7324 /*ARGSUSED*/
7325 char_u *
7326 get_expr_name(xp, idx)
7327 expand_T *xp;
7328 int idx;
7330 static int intidx = -1;
7331 char_u *name;
7333 if (idx == 0)
7334 intidx = -1;
7335 if (intidx < 0)
7337 name = get_function_name(xp, idx);
7338 if (name != NULL)
7339 return name;
7341 return get_user_var_name(xp, ++intidx);
7344 #endif /* FEAT_CMDL_COMPL */
7347 * Find internal function in table above.
7348 * Return index, or -1 if not found
7350 static int
7351 find_internal_func(name)
7352 char_u *name; /* name of the function */
7354 int first = 0;
7355 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7356 int cmp;
7357 int x;
7360 * Find the function name in the table. Binary search.
7362 while (first <= last)
7364 x = first + ((unsigned)(last - first) >> 1);
7365 cmp = STRCMP(name, functions[x].f_name);
7366 if (cmp < 0)
7367 last = x - 1;
7368 else if (cmp > 0)
7369 first = x + 1;
7370 else
7371 return x;
7373 return -1;
7377 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7378 * name it contains, otherwise return "name".
7380 static char_u *
7381 deref_func_name(name, lenp)
7382 char_u *name;
7383 int *lenp;
7385 dictitem_T *v;
7386 int cc;
7388 cc = name[*lenp];
7389 name[*lenp] = NUL;
7390 v = find_var(name, NULL);
7391 name[*lenp] = cc;
7392 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7394 if (v->di_tv.vval.v_string == NULL)
7396 *lenp = 0;
7397 return (char_u *)""; /* just in case */
7399 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7400 return v->di_tv.vval.v_string;
7403 return name;
7407 * Allocate a variable for the result of a function.
7408 * Return OK or FAIL.
7410 static int
7411 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7412 evaluate, selfdict)
7413 char_u *name; /* name of the function */
7414 int len; /* length of "name" */
7415 typval_T *rettv;
7416 char_u **arg; /* argument, pointing to the '(' */
7417 linenr_T firstline; /* first line of range */
7418 linenr_T lastline; /* last line of range */
7419 int *doesrange; /* return: function handled range */
7420 int evaluate;
7421 dict_T *selfdict; /* Dictionary for "self" */
7423 char_u *argp;
7424 int ret = OK;
7425 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7426 int argcount = 0; /* number of arguments found */
7429 * Get the arguments.
7431 argp = *arg;
7432 while (argcount < MAX_FUNC_ARGS)
7434 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7435 if (*argp == ')' || *argp == ',' || *argp == NUL)
7436 break;
7437 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7439 ret = FAIL;
7440 break;
7442 ++argcount;
7443 if (*argp != ',')
7444 break;
7446 if (*argp == ')')
7447 ++argp;
7448 else
7449 ret = FAIL;
7451 if (ret == OK)
7452 ret = call_func(name, len, rettv, argcount, argvars,
7453 firstline, lastline, doesrange, evaluate, selfdict);
7454 else if (!aborting())
7456 if (argcount == MAX_FUNC_ARGS)
7457 emsg_funcname("E740: Too many arguments for function %s", name);
7458 else
7459 emsg_funcname("E116: Invalid arguments for function %s", name);
7462 while (--argcount >= 0)
7463 clear_tv(&argvars[argcount]);
7465 *arg = skipwhite(argp);
7466 return ret;
7471 * Call a function with its resolved parameters
7472 * Return OK when the function can't be called, FAIL otherwise.
7473 * Also returns OK when an error was encountered while executing the function.
7475 static int
7476 call_func(name, len, rettv, argcount, argvars, firstline, lastline,
7477 doesrange, evaluate, selfdict)
7478 char_u *name; /* name of the function */
7479 int len; /* length of "name" */
7480 typval_T *rettv; /* return value goes here */
7481 int argcount; /* number of "argvars" */
7482 typval_T *argvars; /* vars for arguments, must have "argcount"
7483 PLUS ONE elements! */
7484 linenr_T firstline; /* first line of range */
7485 linenr_T lastline; /* last line of range */
7486 int *doesrange; /* return: function handled range */
7487 int evaluate;
7488 dict_T *selfdict; /* Dictionary for "self" */
7490 int ret = FAIL;
7491 #define ERROR_UNKNOWN 0
7492 #define ERROR_TOOMANY 1
7493 #define ERROR_TOOFEW 2
7494 #define ERROR_SCRIPT 3
7495 #define ERROR_DICT 4
7496 #define ERROR_NONE 5
7497 #define ERROR_OTHER 6
7498 int error = ERROR_NONE;
7499 int i;
7500 int llen;
7501 ufunc_T *fp;
7502 int cc;
7503 #define FLEN_FIXED 40
7504 char_u fname_buf[FLEN_FIXED + 1];
7505 char_u *fname;
7508 * In a script change <SID>name() and s:name() to K_SNR 123_name().
7509 * Change <SNR>123_name() to K_SNR 123_name().
7510 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
7512 cc = name[len];
7513 name[len] = NUL;
7514 llen = eval_fname_script(name);
7515 if (llen > 0)
7517 fname_buf[0] = K_SPECIAL;
7518 fname_buf[1] = KS_EXTRA;
7519 fname_buf[2] = (int)KE_SNR;
7520 i = 3;
7521 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
7523 if (current_SID <= 0)
7524 error = ERROR_SCRIPT;
7525 else
7527 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
7528 i = (int)STRLEN(fname_buf);
7531 if (i + STRLEN(name + llen) < FLEN_FIXED)
7533 STRCPY(fname_buf + i, name + llen);
7534 fname = fname_buf;
7536 else
7538 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
7539 if (fname == NULL)
7540 error = ERROR_OTHER;
7541 else
7543 mch_memmove(fname, fname_buf, (size_t)i);
7544 STRCPY(fname + i, name + llen);
7548 else
7549 fname = name;
7551 *doesrange = FALSE;
7554 /* execute the function if no errors detected and executing */
7555 if (evaluate && error == ERROR_NONE)
7557 rettv->v_type = VAR_NUMBER; /* default is number rettv */
7558 error = ERROR_UNKNOWN;
7560 if (!builtin_function(fname))
7563 * User defined function.
7565 fp = find_func(fname);
7567 #ifdef FEAT_AUTOCMD
7568 /* Trigger FuncUndefined event, may load the function. */
7569 if (fp == NULL
7570 && apply_autocmds(EVENT_FUNCUNDEFINED,
7571 fname, fname, TRUE, NULL)
7572 && !aborting())
7574 /* executed an autocommand, search for the function again */
7575 fp = find_func(fname);
7577 #endif
7578 /* Try loading a package. */
7579 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
7581 /* loaded a package, search for the function again */
7582 fp = find_func(fname);
7585 if (fp != NULL)
7587 if (fp->uf_flags & FC_RANGE)
7588 *doesrange = TRUE;
7589 if (argcount < fp->uf_args.ga_len)
7590 error = ERROR_TOOFEW;
7591 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
7592 error = ERROR_TOOMANY;
7593 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
7594 error = ERROR_DICT;
7595 else
7598 * Call the user function.
7599 * Save and restore search patterns, script variables and
7600 * redo buffer.
7602 save_search_patterns();
7603 saveRedobuff();
7604 ++fp->uf_calls;
7605 call_user_func(fp, argcount, argvars, rettv,
7606 firstline, lastline,
7607 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
7608 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
7609 && fp->uf_refcount <= 0)
7610 /* Function was unreferenced while being used, free it
7611 * now. */
7612 func_free(fp);
7613 restoreRedobuff();
7614 restore_search_patterns();
7615 error = ERROR_NONE;
7619 else
7622 * Find the function name in the table, call its implementation.
7624 i = find_internal_func(fname);
7625 if (i >= 0)
7627 if (argcount < functions[i].f_min_argc)
7628 error = ERROR_TOOFEW;
7629 else if (argcount > functions[i].f_max_argc)
7630 error = ERROR_TOOMANY;
7631 else
7633 argvars[argcount].v_type = VAR_UNKNOWN;
7634 functions[i].f_func(argvars, rettv);
7635 error = ERROR_NONE;
7640 * The function call (or "FuncUndefined" autocommand sequence) might
7641 * have been aborted by an error, an interrupt, or an explicitly thrown
7642 * exception that has not been caught so far. This situation can be
7643 * tested for by calling aborting(). For an error in an internal
7644 * function or for the "E132" error in call_user_func(), however, the
7645 * throw point at which the "force_abort" flag (temporarily reset by
7646 * emsg()) is normally updated has not been reached yet. We need to
7647 * update that flag first to make aborting() reliable.
7649 update_force_abort();
7651 if (error == ERROR_NONE)
7652 ret = OK;
7655 * Report an error unless the argument evaluation or function call has been
7656 * cancelled due to an aborting error, an interrupt, or an exception.
7658 if (!aborting())
7660 switch (error)
7662 case ERROR_UNKNOWN:
7663 emsg_funcname(N_("E117: Unknown function: %s"), name);
7664 break;
7665 case ERROR_TOOMANY:
7666 emsg_funcname(e_toomanyarg, name);
7667 break;
7668 case ERROR_TOOFEW:
7669 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
7670 name);
7671 break;
7672 case ERROR_SCRIPT:
7673 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
7674 name);
7675 break;
7676 case ERROR_DICT:
7677 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
7678 name);
7679 break;
7683 name[len] = cc;
7684 if (fname != name && fname != fname_buf)
7685 vim_free(fname);
7687 return ret;
7691 * Give an error message with a function name. Handle <SNR> things.
7693 static void
7694 emsg_funcname(ermsg, name)
7695 char *ermsg;
7696 char_u *name;
7698 char_u *p;
7700 if (*name == K_SPECIAL)
7701 p = concat_str((char_u *)"<SNR>", name + 3);
7702 else
7703 p = name;
7704 EMSG2(_(ermsg), p);
7705 if (p != name)
7706 vim_free(p);
7709 /*********************************************
7710 * Implementation of the built-in functions
7714 * "add(list, item)" function
7716 static void
7717 f_add(argvars, rettv)
7718 typval_T *argvars;
7719 typval_T *rettv;
7721 list_T *l;
7723 rettv->vval.v_number = 1; /* Default: Failed */
7724 if (argvars[0].v_type == VAR_LIST)
7726 if ((l = argvars[0].vval.v_list) != NULL
7727 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
7728 && list_append_tv(l, &argvars[1]) == OK)
7729 copy_tv(&argvars[0], rettv);
7731 else
7732 EMSG(_(e_listreq));
7736 * "append(lnum, string/list)" function
7738 static void
7739 f_append(argvars, rettv)
7740 typval_T *argvars;
7741 typval_T *rettv;
7743 long lnum;
7744 char_u *line;
7745 list_T *l = NULL;
7746 listitem_T *li = NULL;
7747 typval_T *tv;
7748 long added = 0;
7750 lnum = get_tv_lnum(argvars);
7751 if (lnum >= 0
7752 && lnum <= curbuf->b_ml.ml_line_count
7753 && u_save(lnum, lnum + 1) == OK)
7755 if (argvars[1].v_type == VAR_LIST)
7757 l = argvars[1].vval.v_list;
7758 if (l == NULL)
7759 return;
7760 li = l->lv_first;
7762 rettv->vval.v_number = 0; /* Default: Success */
7763 for (;;)
7765 if (l == NULL)
7766 tv = &argvars[1]; /* append a string */
7767 else if (li == NULL)
7768 break; /* end of list */
7769 else
7770 tv = &li->li_tv; /* append item from list */
7771 line = get_tv_string_chk(tv);
7772 if (line == NULL) /* type error */
7774 rettv->vval.v_number = 1; /* Failed */
7775 break;
7777 ml_append(lnum + added, line, (colnr_T)0, FALSE);
7778 ++added;
7779 if (l == NULL)
7780 break;
7781 li = li->li_next;
7784 appended_lines_mark(lnum, added);
7785 if (curwin->w_cursor.lnum > lnum)
7786 curwin->w_cursor.lnum += added;
7788 else
7789 rettv->vval.v_number = 1; /* Failed */
7793 * "argc()" function
7795 /* ARGSUSED */
7796 static void
7797 f_argc(argvars, rettv)
7798 typval_T *argvars;
7799 typval_T *rettv;
7801 rettv->vval.v_number = ARGCOUNT;
7805 * "argidx()" function
7807 /* ARGSUSED */
7808 static void
7809 f_argidx(argvars, rettv)
7810 typval_T *argvars;
7811 typval_T *rettv;
7813 rettv->vval.v_number = curwin->w_arg_idx;
7817 * "argv(nr)" function
7819 static void
7820 f_argv(argvars, rettv)
7821 typval_T *argvars;
7822 typval_T *rettv;
7824 int idx;
7826 if (argvars[0].v_type != VAR_UNKNOWN)
7828 idx = get_tv_number_chk(&argvars[0], NULL);
7829 if (idx >= 0 && idx < ARGCOUNT)
7830 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
7831 else
7832 rettv->vval.v_string = NULL;
7833 rettv->v_type = VAR_STRING;
7835 else if (rettv_list_alloc(rettv) == OK)
7836 for (idx = 0; idx < ARGCOUNT; ++idx)
7837 list_append_string(rettv->vval.v_list,
7838 alist_name(&ARGLIST[idx]), -1);
7842 * "browse(save, title, initdir, default)" function
7844 /* ARGSUSED */
7845 static void
7846 f_browse(argvars, rettv)
7847 typval_T *argvars;
7848 typval_T *rettv;
7850 #ifdef FEAT_BROWSE
7851 int save;
7852 char_u *title;
7853 char_u *initdir;
7854 char_u *defname;
7855 char_u buf[NUMBUFLEN];
7856 char_u buf2[NUMBUFLEN];
7857 int error = FALSE;
7859 save = get_tv_number_chk(&argvars[0], &error);
7860 title = get_tv_string_chk(&argvars[1]);
7861 initdir = get_tv_string_buf_chk(&argvars[2], buf);
7862 defname = get_tv_string_buf_chk(&argvars[3], buf2);
7864 if (error || title == NULL || initdir == NULL || defname == NULL)
7865 rettv->vval.v_string = NULL;
7866 else
7867 rettv->vval.v_string =
7868 do_browse(save ? BROWSE_SAVE : 0,
7869 title, defname, NULL, initdir, NULL, curbuf);
7870 #else
7871 rettv->vval.v_string = NULL;
7872 #endif
7873 rettv->v_type = VAR_STRING;
7877 * "browsedir(title, initdir)" function
7879 /* ARGSUSED */
7880 static void
7881 f_browsedir(argvars, rettv)
7882 typval_T *argvars;
7883 typval_T *rettv;
7885 #ifdef FEAT_BROWSE
7886 char_u *title;
7887 char_u *initdir;
7888 char_u buf[NUMBUFLEN];
7890 title = get_tv_string_chk(&argvars[0]);
7891 initdir = get_tv_string_buf_chk(&argvars[1], buf);
7893 if (title == NULL || initdir == NULL)
7894 rettv->vval.v_string = NULL;
7895 else
7896 rettv->vval.v_string = do_browse(BROWSE_DIR,
7897 title, NULL, NULL, initdir, NULL, curbuf);
7898 #else
7899 rettv->vval.v_string = NULL;
7900 #endif
7901 rettv->v_type = VAR_STRING;
7904 static buf_T *find_buffer __ARGS((typval_T *avar));
7907 * Find a buffer by number or exact name.
7909 static buf_T *
7910 find_buffer(avar)
7911 typval_T *avar;
7913 buf_T *buf = NULL;
7915 if (avar->v_type == VAR_NUMBER)
7916 buf = buflist_findnr((int)avar->vval.v_number);
7917 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
7919 buf = buflist_findname_exp(avar->vval.v_string);
7920 if (buf == NULL)
7922 /* No full path name match, try a match with a URL or a "nofile"
7923 * buffer, these don't use the full path. */
7924 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
7925 if (buf->b_fname != NULL
7926 && (path_with_url(buf->b_fname)
7927 #ifdef FEAT_QUICKFIX
7928 || bt_nofile(buf)
7929 #endif
7931 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
7932 break;
7935 return buf;
7939 * "bufexists(expr)" function
7941 static void
7942 f_bufexists(argvars, rettv)
7943 typval_T *argvars;
7944 typval_T *rettv;
7946 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
7950 * "buflisted(expr)" function
7952 static void
7953 f_buflisted(argvars, rettv)
7954 typval_T *argvars;
7955 typval_T *rettv;
7957 buf_T *buf;
7959 buf = find_buffer(&argvars[0]);
7960 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
7964 * "bufloaded(expr)" function
7966 static void
7967 f_bufloaded(argvars, rettv)
7968 typval_T *argvars;
7969 typval_T *rettv;
7971 buf_T *buf;
7973 buf = find_buffer(&argvars[0]);
7974 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
7977 static buf_T *get_buf_tv __ARGS((typval_T *tv));
7980 * Get buffer by number or pattern.
7982 static buf_T *
7983 get_buf_tv(tv)
7984 typval_T *tv;
7986 char_u *name = tv->vval.v_string;
7987 int save_magic;
7988 char_u *save_cpo;
7989 buf_T *buf;
7991 if (tv->v_type == VAR_NUMBER)
7992 return buflist_findnr((int)tv->vval.v_number);
7993 if (tv->v_type != VAR_STRING)
7994 return NULL;
7995 if (name == NULL || *name == NUL)
7996 return curbuf;
7997 if (name[0] == '$' && name[1] == NUL)
7998 return lastbuf;
8000 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
8001 save_magic = p_magic;
8002 p_magic = TRUE;
8003 save_cpo = p_cpo;
8004 p_cpo = (char_u *)"";
8006 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8007 TRUE, FALSE));
8009 p_magic = save_magic;
8010 p_cpo = save_cpo;
8012 /* If not found, try expanding the name, like done for bufexists(). */
8013 if (buf == NULL)
8014 buf = find_buffer(tv);
8016 return buf;
8020 * "bufname(expr)" function
8022 static void
8023 f_bufname(argvars, rettv)
8024 typval_T *argvars;
8025 typval_T *rettv;
8027 buf_T *buf;
8029 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8030 ++emsg_off;
8031 buf = get_buf_tv(&argvars[0]);
8032 rettv->v_type = VAR_STRING;
8033 if (buf != NULL && buf->b_fname != NULL)
8034 rettv->vval.v_string = vim_strsave(buf->b_fname);
8035 else
8036 rettv->vval.v_string = NULL;
8037 --emsg_off;
8041 * "bufnr(expr)" function
8043 static void
8044 f_bufnr(argvars, rettv)
8045 typval_T *argvars;
8046 typval_T *rettv;
8048 buf_T *buf;
8049 int error = FALSE;
8050 char_u *name;
8052 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8053 ++emsg_off;
8054 buf = get_buf_tv(&argvars[0]);
8055 --emsg_off;
8057 /* If the buffer isn't found and the second argument is not zero create a
8058 * new buffer. */
8059 if (buf == NULL
8060 && argvars[1].v_type != VAR_UNKNOWN
8061 && get_tv_number_chk(&argvars[1], &error) != 0
8062 && !error
8063 && (name = get_tv_string_chk(&argvars[0])) != NULL
8064 && !error)
8065 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8067 if (buf != NULL)
8068 rettv->vval.v_number = buf->b_fnum;
8069 else
8070 rettv->vval.v_number = -1;
8074 * "bufwinnr(nr)" function
8076 static void
8077 f_bufwinnr(argvars, rettv)
8078 typval_T *argvars;
8079 typval_T *rettv;
8081 #ifdef FEAT_WINDOWS
8082 win_T *wp;
8083 int winnr = 0;
8084 #endif
8085 buf_T *buf;
8087 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8088 ++emsg_off;
8089 buf = get_buf_tv(&argvars[0]);
8090 #ifdef FEAT_WINDOWS
8091 for (wp = firstwin; wp; wp = wp->w_next)
8093 ++winnr;
8094 if (wp->w_buffer == buf)
8095 break;
8097 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8098 #else
8099 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8100 #endif
8101 --emsg_off;
8105 * "byte2line(byte)" function
8107 /*ARGSUSED*/
8108 static void
8109 f_byte2line(argvars, rettv)
8110 typval_T *argvars;
8111 typval_T *rettv;
8113 #ifndef FEAT_BYTEOFF
8114 rettv->vval.v_number = -1;
8115 #else
8116 long boff = 0;
8118 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8119 if (boff < 0)
8120 rettv->vval.v_number = -1;
8121 else
8122 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8123 (linenr_T)0, &boff);
8124 #endif
8128 * "byteidx()" function
8130 /*ARGSUSED*/
8131 static void
8132 f_byteidx(argvars, rettv)
8133 typval_T *argvars;
8134 typval_T *rettv;
8136 #ifdef FEAT_MBYTE
8137 char_u *t;
8138 #endif
8139 char_u *str;
8140 long idx;
8142 str = get_tv_string_chk(&argvars[0]);
8143 idx = get_tv_number_chk(&argvars[1], NULL);
8144 rettv->vval.v_number = -1;
8145 if (str == NULL || idx < 0)
8146 return;
8148 #ifdef FEAT_MBYTE
8149 t = str;
8150 for ( ; idx > 0; idx--)
8152 if (*t == NUL) /* EOL reached */
8153 return;
8154 t += (*mb_ptr2len)(t);
8156 rettv->vval.v_number = (varnumber_T)(t - str);
8157 #else
8158 if (idx <= STRLEN(str))
8159 rettv->vval.v_number = idx;
8160 #endif
8164 * "call(func, arglist)" function
8166 static void
8167 f_call(argvars, rettv)
8168 typval_T *argvars;
8169 typval_T *rettv;
8171 char_u *func;
8172 typval_T argv[MAX_FUNC_ARGS + 1];
8173 int argc = 0;
8174 listitem_T *item;
8175 int dummy;
8176 dict_T *selfdict = NULL;
8178 rettv->vval.v_number = 0;
8179 if (argvars[1].v_type != VAR_LIST)
8181 EMSG(_(e_listreq));
8182 return;
8184 if (argvars[1].vval.v_list == NULL)
8185 return;
8187 if (argvars[0].v_type == VAR_FUNC)
8188 func = argvars[0].vval.v_string;
8189 else
8190 func = get_tv_string(&argvars[0]);
8191 if (*func == NUL)
8192 return; /* type error or empty name */
8194 if (argvars[2].v_type != VAR_UNKNOWN)
8196 if (argvars[2].v_type != VAR_DICT)
8198 EMSG(_(e_dictreq));
8199 return;
8201 selfdict = argvars[2].vval.v_dict;
8204 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
8205 item = item->li_next)
8207 if (argc == MAX_FUNC_ARGS)
8209 EMSG(_("E699: Too many arguments"));
8210 break;
8212 /* Make a copy of each argument. This is needed to be able to set
8213 * v_lock to VAR_FIXED in the copy without changing the original list.
8215 copy_tv(&item->li_tv, &argv[argc++]);
8218 if (item == NULL)
8219 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
8220 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
8221 &dummy, TRUE, selfdict);
8223 /* Free the arguments. */
8224 while (argc > 0)
8225 clear_tv(&argv[--argc]);
8229 * "changenr()" function
8231 /*ARGSUSED*/
8232 static void
8233 f_changenr(argvars, rettv)
8234 typval_T *argvars;
8235 typval_T *rettv;
8237 rettv->vval.v_number = curbuf->b_u_seq_cur;
8241 * "char2nr(string)" function
8243 static void
8244 f_char2nr(argvars, rettv)
8245 typval_T *argvars;
8246 typval_T *rettv;
8248 #ifdef FEAT_MBYTE
8249 if (has_mbyte)
8250 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
8251 else
8252 #endif
8253 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
8257 * "cindent(lnum)" function
8259 static void
8260 f_cindent(argvars, rettv)
8261 typval_T *argvars;
8262 typval_T *rettv;
8264 #ifdef FEAT_CINDENT
8265 pos_T pos;
8266 linenr_T lnum;
8268 pos = curwin->w_cursor;
8269 lnum = get_tv_lnum(argvars);
8270 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
8272 curwin->w_cursor.lnum = lnum;
8273 rettv->vval.v_number = get_c_indent();
8274 curwin->w_cursor = pos;
8276 else
8277 #endif
8278 rettv->vval.v_number = -1;
8282 * "clearmatches()" function
8284 /*ARGSUSED*/
8285 static void
8286 f_clearmatches(argvars, rettv)
8287 typval_T *argvars;
8288 typval_T *rettv;
8290 #ifdef FEAT_SEARCH_EXTRA
8291 clear_matches(curwin);
8292 #endif
8296 * "col(string)" function
8298 static void
8299 f_col(argvars, rettv)
8300 typval_T *argvars;
8301 typval_T *rettv;
8303 colnr_T col = 0;
8304 pos_T *fp;
8305 int fnum = curbuf->b_fnum;
8307 fp = var2fpos(&argvars[0], FALSE, &fnum);
8308 if (fp != NULL && fnum == curbuf->b_fnum)
8310 if (fp->col == MAXCOL)
8312 /* '> can be MAXCOL, get the length of the line then */
8313 if (fp->lnum <= curbuf->b_ml.ml_line_count)
8314 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
8315 else
8316 col = MAXCOL;
8318 else
8320 col = fp->col + 1;
8321 #ifdef FEAT_VIRTUALEDIT
8322 /* col(".") when the cursor is on the NUL at the end of the line
8323 * because of "coladd" can be seen as an extra column. */
8324 if (virtual_active() && fp == &curwin->w_cursor)
8326 char_u *p = ml_get_cursor();
8328 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
8329 curwin->w_virtcol - curwin->w_cursor.coladd))
8331 # ifdef FEAT_MBYTE
8332 int l;
8334 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
8335 col += l;
8336 # else
8337 if (*p != NUL && p[1] == NUL)
8338 ++col;
8339 # endif
8342 #endif
8345 rettv->vval.v_number = col;
8348 #if defined(FEAT_INS_EXPAND)
8350 * "complete()" function
8352 /*ARGSUSED*/
8353 static void
8354 f_complete(argvars, rettv)
8355 typval_T *argvars;
8356 typval_T *rettv;
8358 int startcol;
8360 if ((State & INSERT) == 0)
8362 EMSG(_("E785: complete() can only be used in Insert mode"));
8363 return;
8366 /* Check for undo allowed here, because if something was already inserted
8367 * the line was already saved for undo and this check isn't done. */
8368 if (!undo_allowed())
8369 return;
8371 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
8373 EMSG(_(e_invarg));
8374 return;
8377 startcol = get_tv_number_chk(&argvars[0], NULL);
8378 if (startcol <= 0)
8379 return;
8381 set_completion(startcol - 1, argvars[1].vval.v_list);
8385 * "complete_add()" function
8387 /*ARGSUSED*/
8388 static void
8389 f_complete_add(argvars, rettv)
8390 typval_T *argvars;
8391 typval_T *rettv;
8393 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
8397 * "complete_check()" function
8399 /*ARGSUSED*/
8400 static void
8401 f_complete_check(argvars, rettv)
8402 typval_T *argvars;
8403 typval_T *rettv;
8405 int saved = RedrawingDisabled;
8407 RedrawingDisabled = 0;
8408 ins_compl_check_keys(0);
8409 rettv->vval.v_number = compl_interrupted;
8410 RedrawingDisabled = saved;
8412 #endif
8415 * "confirm(message, buttons[, default [, type]])" function
8417 /*ARGSUSED*/
8418 static void
8419 f_confirm(argvars, rettv)
8420 typval_T *argvars;
8421 typval_T *rettv;
8423 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
8424 char_u *message;
8425 char_u *buttons = NULL;
8426 char_u buf[NUMBUFLEN];
8427 char_u buf2[NUMBUFLEN];
8428 int def = 1;
8429 int type = VIM_GENERIC;
8430 char_u *typestr;
8431 int error = FALSE;
8433 message = get_tv_string_chk(&argvars[0]);
8434 if (message == NULL)
8435 error = TRUE;
8436 if (argvars[1].v_type != VAR_UNKNOWN)
8438 buttons = get_tv_string_buf_chk(&argvars[1], buf);
8439 if (buttons == NULL)
8440 error = TRUE;
8441 if (argvars[2].v_type != VAR_UNKNOWN)
8443 def = get_tv_number_chk(&argvars[2], &error);
8444 if (argvars[3].v_type != VAR_UNKNOWN)
8446 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
8447 if (typestr == NULL)
8448 error = TRUE;
8449 else
8451 switch (TOUPPER_ASC(*typestr))
8453 case 'E': type = VIM_ERROR; break;
8454 case 'Q': type = VIM_QUESTION; break;
8455 case 'I': type = VIM_INFO; break;
8456 case 'W': type = VIM_WARNING; break;
8457 case 'G': type = VIM_GENERIC; break;
8464 if (buttons == NULL || *buttons == NUL)
8465 buttons = (char_u *)_("&Ok");
8467 if (error)
8468 rettv->vval.v_number = 0;
8469 else
8470 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
8471 def, NULL);
8472 #else
8473 rettv->vval.v_number = 0;
8474 #endif
8478 * "copy()" function
8480 static void
8481 f_copy(argvars, rettv)
8482 typval_T *argvars;
8483 typval_T *rettv;
8485 item_copy(&argvars[0], rettv, FALSE, 0);
8489 * "count()" function
8491 static void
8492 f_count(argvars, rettv)
8493 typval_T *argvars;
8494 typval_T *rettv;
8496 long n = 0;
8497 int ic = FALSE;
8499 if (argvars[0].v_type == VAR_LIST)
8501 listitem_T *li;
8502 list_T *l;
8503 long idx;
8505 if ((l = argvars[0].vval.v_list) != NULL)
8507 li = l->lv_first;
8508 if (argvars[2].v_type != VAR_UNKNOWN)
8510 int error = FALSE;
8512 ic = get_tv_number_chk(&argvars[2], &error);
8513 if (argvars[3].v_type != VAR_UNKNOWN)
8515 idx = get_tv_number_chk(&argvars[3], &error);
8516 if (!error)
8518 li = list_find(l, idx);
8519 if (li == NULL)
8520 EMSGN(_(e_listidx), idx);
8523 if (error)
8524 li = NULL;
8527 for ( ; li != NULL; li = li->li_next)
8528 if (tv_equal(&li->li_tv, &argvars[1], ic))
8529 ++n;
8532 else if (argvars[0].v_type == VAR_DICT)
8534 int todo;
8535 dict_T *d;
8536 hashitem_T *hi;
8538 if ((d = argvars[0].vval.v_dict) != NULL)
8540 int error = FALSE;
8542 if (argvars[2].v_type != VAR_UNKNOWN)
8544 ic = get_tv_number_chk(&argvars[2], &error);
8545 if (argvars[3].v_type != VAR_UNKNOWN)
8546 EMSG(_(e_invarg));
8549 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
8550 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
8552 if (!HASHITEM_EMPTY(hi))
8554 --todo;
8555 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
8556 ++n;
8561 else
8562 EMSG2(_(e_listdictarg), "count()");
8563 rettv->vval.v_number = n;
8567 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
8569 * Checks the existence of a cscope connection.
8571 /*ARGSUSED*/
8572 static void
8573 f_cscope_connection(argvars, rettv)
8574 typval_T *argvars;
8575 typval_T *rettv;
8577 #ifdef FEAT_CSCOPE
8578 int num = 0;
8579 char_u *dbpath = NULL;
8580 char_u *prepend = NULL;
8581 char_u buf[NUMBUFLEN];
8583 if (argvars[0].v_type != VAR_UNKNOWN
8584 && argvars[1].v_type != VAR_UNKNOWN)
8586 num = (int)get_tv_number(&argvars[0]);
8587 dbpath = get_tv_string(&argvars[1]);
8588 if (argvars[2].v_type != VAR_UNKNOWN)
8589 prepend = get_tv_string_buf(&argvars[2], buf);
8592 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
8593 #else
8594 rettv->vval.v_number = 0;
8595 #endif
8599 * "cursor(lnum, col)" function
8601 * Moves the cursor to the specified line and column
8603 /*ARGSUSED*/
8604 static void
8605 f_cursor(argvars, rettv)
8606 typval_T *argvars;
8607 typval_T *rettv;
8609 long line, col;
8610 #ifdef FEAT_VIRTUALEDIT
8611 long coladd = 0;
8612 #endif
8614 if (argvars[1].v_type == VAR_UNKNOWN)
8616 pos_T pos;
8618 if (list2fpos(argvars, &pos, NULL) == FAIL)
8619 return;
8620 line = pos.lnum;
8621 col = pos.col;
8622 #ifdef FEAT_VIRTUALEDIT
8623 coladd = pos.coladd;
8624 #endif
8626 else
8628 line = get_tv_lnum(argvars);
8629 col = get_tv_number_chk(&argvars[1], NULL);
8630 #ifdef FEAT_VIRTUALEDIT
8631 if (argvars[2].v_type != VAR_UNKNOWN)
8632 coladd = get_tv_number_chk(&argvars[2], NULL);
8633 #endif
8635 if (line < 0 || col < 0
8636 #ifdef FEAT_VIRTUALEDIT
8637 || coladd < 0
8638 #endif
8640 return; /* type error; errmsg already given */
8641 if (line > 0)
8642 curwin->w_cursor.lnum = line;
8643 if (col > 0)
8644 curwin->w_cursor.col = col - 1;
8645 #ifdef FEAT_VIRTUALEDIT
8646 curwin->w_cursor.coladd = coladd;
8647 #endif
8649 /* Make sure the cursor is in a valid position. */
8650 check_cursor();
8651 #ifdef FEAT_MBYTE
8652 /* Correct cursor for multi-byte character. */
8653 if (has_mbyte)
8654 mb_adjust_cursor();
8655 #endif
8657 curwin->w_set_curswant = TRUE;
8661 * "deepcopy()" function
8663 static void
8664 f_deepcopy(argvars, rettv)
8665 typval_T *argvars;
8666 typval_T *rettv;
8668 int noref = 0;
8670 if (argvars[1].v_type != VAR_UNKNOWN)
8671 noref = get_tv_number_chk(&argvars[1], NULL);
8672 if (noref < 0 || noref > 1)
8673 EMSG(_(e_invarg));
8674 else
8675 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? ++current_copyID : 0);
8679 * "delete()" function
8681 static void
8682 f_delete(argvars, rettv)
8683 typval_T *argvars;
8684 typval_T *rettv;
8686 if (check_restricted() || check_secure())
8687 rettv->vval.v_number = -1;
8688 else
8689 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
8693 * "did_filetype()" function
8695 /*ARGSUSED*/
8696 static void
8697 f_did_filetype(argvars, rettv)
8698 typval_T *argvars;
8699 typval_T *rettv;
8701 #ifdef FEAT_AUTOCMD
8702 rettv->vval.v_number = did_filetype;
8703 #else
8704 rettv->vval.v_number = 0;
8705 #endif
8709 * "diff_filler()" function
8711 /*ARGSUSED*/
8712 static void
8713 f_diff_filler(argvars, rettv)
8714 typval_T *argvars;
8715 typval_T *rettv;
8717 #ifdef FEAT_DIFF
8718 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
8719 #endif
8723 * "diff_hlID()" function
8725 /*ARGSUSED*/
8726 static void
8727 f_diff_hlID(argvars, rettv)
8728 typval_T *argvars;
8729 typval_T *rettv;
8731 #ifdef FEAT_DIFF
8732 linenr_T lnum = get_tv_lnum(argvars);
8733 static linenr_T prev_lnum = 0;
8734 static int changedtick = 0;
8735 static int fnum = 0;
8736 static int change_start = 0;
8737 static int change_end = 0;
8738 static hlf_T hlID = (hlf_T)0;
8739 int filler_lines;
8740 int col;
8742 if (lnum < 0) /* ignore type error in {lnum} arg */
8743 lnum = 0;
8744 if (lnum != prev_lnum
8745 || changedtick != curbuf->b_changedtick
8746 || fnum != curbuf->b_fnum)
8748 /* New line, buffer, change: need to get the values. */
8749 filler_lines = diff_check(curwin, lnum);
8750 if (filler_lines < 0)
8752 if (filler_lines == -1)
8754 change_start = MAXCOL;
8755 change_end = -1;
8756 if (diff_find_change(curwin, lnum, &change_start, &change_end))
8757 hlID = HLF_ADD; /* added line */
8758 else
8759 hlID = HLF_CHD; /* changed line */
8761 else
8762 hlID = HLF_ADD; /* added line */
8764 else
8765 hlID = (hlf_T)0;
8766 prev_lnum = lnum;
8767 changedtick = curbuf->b_changedtick;
8768 fnum = curbuf->b_fnum;
8771 if (hlID == HLF_CHD || hlID == HLF_TXD)
8773 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
8774 if (col >= change_start && col <= change_end)
8775 hlID = HLF_TXD; /* changed text */
8776 else
8777 hlID = HLF_CHD; /* changed line */
8779 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
8780 #endif
8784 * "empty({expr})" function
8786 static void
8787 f_empty(argvars, rettv)
8788 typval_T *argvars;
8789 typval_T *rettv;
8791 int n;
8793 switch (argvars[0].v_type)
8795 case VAR_STRING:
8796 case VAR_FUNC:
8797 n = argvars[0].vval.v_string == NULL
8798 || *argvars[0].vval.v_string == NUL;
8799 break;
8800 case VAR_NUMBER:
8801 n = argvars[0].vval.v_number == 0;
8802 break;
8803 case VAR_LIST:
8804 n = argvars[0].vval.v_list == NULL
8805 || argvars[0].vval.v_list->lv_first == NULL;
8806 break;
8807 case VAR_DICT:
8808 n = argvars[0].vval.v_dict == NULL
8809 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
8810 break;
8811 default:
8812 EMSG2(_(e_intern2), "f_empty()");
8813 n = 0;
8816 rettv->vval.v_number = n;
8820 * "escape({string}, {chars})" function
8822 static void
8823 f_escape(argvars, rettv)
8824 typval_T *argvars;
8825 typval_T *rettv;
8827 char_u buf[NUMBUFLEN];
8829 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
8830 get_tv_string_buf(&argvars[1], buf));
8831 rettv->v_type = VAR_STRING;
8835 * "eval()" function
8837 /*ARGSUSED*/
8838 static void
8839 f_eval(argvars, rettv)
8840 typval_T *argvars;
8841 typval_T *rettv;
8843 char_u *s;
8845 s = get_tv_string_chk(&argvars[0]);
8846 if (s != NULL)
8847 s = skipwhite(s);
8849 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
8851 rettv->v_type = VAR_NUMBER;
8852 rettv->vval.v_number = 0;
8854 else if (*s != NUL)
8855 EMSG(_(e_trailing));
8859 * "eventhandler()" function
8861 /*ARGSUSED*/
8862 static void
8863 f_eventhandler(argvars, rettv)
8864 typval_T *argvars;
8865 typval_T *rettv;
8867 rettv->vval.v_number = vgetc_busy;
8871 * "executable()" function
8873 static void
8874 f_executable(argvars, rettv)
8875 typval_T *argvars;
8876 typval_T *rettv;
8878 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
8882 * "exists()" function
8884 static void
8885 f_exists(argvars, rettv)
8886 typval_T *argvars;
8887 typval_T *rettv;
8889 char_u *p;
8890 char_u *name;
8891 int n = FALSE;
8892 int len = 0;
8894 p = get_tv_string(&argvars[0]);
8895 if (*p == '$') /* environment variable */
8897 /* first try "normal" environment variables (fast) */
8898 if (mch_getenv(p + 1) != NULL)
8899 n = TRUE;
8900 else
8902 /* try expanding things like $VIM and ${HOME} */
8903 p = expand_env_save(p);
8904 if (p != NULL && *p != '$')
8905 n = TRUE;
8906 vim_free(p);
8909 else if (*p == '&' || *p == '+') /* option */
8911 n = (get_option_tv(&p, NULL, TRUE) == OK);
8912 if (*skipwhite(p) != NUL)
8913 n = FALSE; /* trailing garbage */
8915 else if (*p == '*') /* internal or user defined function */
8917 n = function_exists(p + 1);
8919 else if (*p == ':')
8921 n = cmd_exists(p + 1);
8923 else if (*p == '#')
8925 #ifdef FEAT_AUTOCMD
8926 if (p[1] == '#')
8927 n = autocmd_supported(p + 2);
8928 else
8929 n = au_exists(p + 1);
8930 #endif
8932 else /* internal variable */
8934 char_u *tofree;
8935 typval_T tv;
8937 /* get_name_len() takes care of expanding curly braces */
8938 name = p;
8939 len = get_name_len(&p, &tofree, TRUE, FALSE);
8940 if (len > 0)
8942 if (tofree != NULL)
8943 name = tofree;
8944 n = (get_var_tv(name, len, &tv, FALSE) == OK);
8945 if (n)
8947 /* handle d.key, l[idx], f(expr) */
8948 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
8949 if (n)
8950 clear_tv(&tv);
8953 if (*p != NUL)
8954 n = FALSE;
8956 vim_free(tofree);
8959 rettv->vval.v_number = n;
8963 * "expand()" function
8965 static void
8966 f_expand(argvars, rettv)
8967 typval_T *argvars;
8968 typval_T *rettv;
8970 char_u *s;
8971 int len;
8972 char_u *errormsg;
8973 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
8974 expand_T xpc;
8975 int error = FALSE;
8977 rettv->v_type = VAR_STRING;
8978 s = get_tv_string(&argvars[0]);
8979 if (*s == '%' || *s == '#' || *s == '<')
8981 ++emsg_off;
8982 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
8983 --emsg_off;
8985 else
8987 /* When the optional second argument is non-zero, don't remove matches
8988 * for 'suffixes' and 'wildignore' */
8989 if (argvars[1].v_type != VAR_UNKNOWN
8990 && get_tv_number_chk(&argvars[1], &error))
8991 flags |= WILD_KEEP_ALL;
8992 if (!error)
8994 ExpandInit(&xpc);
8995 xpc.xp_context = EXPAND_FILES;
8996 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
8998 else
8999 rettv->vval.v_string = NULL;
9004 * "extend(list, list [, idx])" function
9005 * "extend(dict, dict [, action])" function
9007 static void
9008 f_extend(argvars, rettv)
9009 typval_T *argvars;
9010 typval_T *rettv;
9012 rettv->vval.v_number = 0;
9013 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9015 list_T *l1, *l2;
9016 listitem_T *item;
9017 long before;
9018 int error = FALSE;
9020 l1 = argvars[0].vval.v_list;
9021 l2 = argvars[1].vval.v_list;
9022 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9023 && l2 != NULL)
9025 if (argvars[2].v_type != VAR_UNKNOWN)
9027 before = get_tv_number_chk(&argvars[2], &error);
9028 if (error)
9029 return; /* type error; errmsg already given */
9031 if (before == l1->lv_len)
9032 item = NULL;
9033 else
9035 item = list_find(l1, before);
9036 if (item == NULL)
9038 EMSGN(_(e_listidx), before);
9039 return;
9043 else
9044 item = NULL;
9045 list_extend(l1, l2, item);
9047 copy_tv(&argvars[0], rettv);
9050 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9052 dict_T *d1, *d2;
9053 dictitem_T *di1;
9054 char_u *action;
9055 int i;
9056 hashitem_T *hi2;
9057 int todo;
9059 d1 = argvars[0].vval.v_dict;
9060 d2 = argvars[1].vval.v_dict;
9061 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9062 && d2 != NULL)
9064 /* Check the third argument. */
9065 if (argvars[2].v_type != VAR_UNKNOWN)
9067 static char *(av[]) = {"keep", "force", "error"};
9069 action = get_tv_string_chk(&argvars[2]);
9070 if (action == NULL)
9071 return; /* type error; errmsg already given */
9072 for (i = 0; i < 3; ++i)
9073 if (STRCMP(action, av[i]) == 0)
9074 break;
9075 if (i == 3)
9077 EMSG2(_(e_invarg2), action);
9078 return;
9081 else
9082 action = (char_u *)"force";
9084 /* Go over all entries in the second dict and add them to the
9085 * first dict. */
9086 todo = (int)d2->dv_hashtab.ht_used;
9087 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9089 if (!HASHITEM_EMPTY(hi2))
9091 --todo;
9092 di1 = dict_find(d1, hi2->hi_key, -1);
9093 if (di1 == NULL)
9095 di1 = dictitem_copy(HI2DI(hi2));
9096 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9097 dictitem_free(di1);
9099 else if (*action == 'e')
9101 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9102 break;
9104 else if (*action == 'f')
9106 clear_tv(&di1->di_tv);
9107 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9112 copy_tv(&argvars[0], rettv);
9115 else
9116 EMSG2(_(e_listdictarg), "extend()");
9120 * "feedkeys()" function
9122 /*ARGSUSED*/
9123 static void
9124 f_feedkeys(argvars, rettv)
9125 typval_T *argvars;
9126 typval_T *rettv;
9128 int remap = TRUE;
9129 char_u *keys, *flags;
9130 char_u nbuf[NUMBUFLEN];
9131 int typed = FALSE;
9132 char_u *keys_esc;
9134 /* This is not allowed in the sandbox. If the commands would still be
9135 * executed in the sandbox it would be OK, but it probably happens later,
9136 * when "sandbox" is no longer set. */
9137 if (check_secure())
9138 return;
9140 rettv->vval.v_number = 0;
9141 keys = get_tv_string(&argvars[0]);
9142 if (*keys != NUL)
9144 if (argvars[1].v_type != VAR_UNKNOWN)
9146 flags = get_tv_string_buf(&argvars[1], nbuf);
9147 for ( ; *flags != NUL; ++flags)
9149 switch (*flags)
9151 case 'n': remap = FALSE; break;
9152 case 'm': remap = TRUE; break;
9153 case 't': typed = TRUE; break;
9158 /* Need to escape K_SPECIAL and CSI before putting the string in the
9159 * typeahead buffer. */
9160 keys_esc = vim_strsave_escape_csi(keys);
9161 if (keys_esc != NULL)
9163 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
9164 typebuf.tb_len, !typed, FALSE);
9165 vim_free(keys_esc);
9166 if (vgetc_busy)
9167 typebuf_was_filled = TRUE;
9173 * "filereadable()" function
9175 static void
9176 f_filereadable(argvars, rettv)
9177 typval_T *argvars;
9178 typval_T *rettv;
9180 FILE *fd;
9181 char_u *p;
9182 int n;
9184 p = get_tv_string(&argvars[0]);
9185 if (*p && !mch_isdir(p) && (fd = mch_fopen((char *)p, "r")) != NULL)
9187 n = TRUE;
9188 fclose(fd);
9190 else
9191 n = FALSE;
9193 rettv->vval.v_number = n;
9197 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
9198 * rights to write into.
9200 static void
9201 f_filewritable(argvars, rettv)
9202 typval_T *argvars;
9203 typval_T *rettv;
9205 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
9208 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
9210 static void
9211 findfilendir(argvars, rettv, find_what)
9212 typval_T *argvars;
9213 typval_T *rettv;
9214 int find_what;
9216 #ifdef FEAT_SEARCHPATH
9217 char_u *fname;
9218 char_u *fresult = NULL;
9219 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
9220 char_u *p;
9221 char_u pathbuf[NUMBUFLEN];
9222 int count = 1;
9223 int first = TRUE;
9224 int error = FALSE;
9225 #endif
9227 rettv->vval.v_string = NULL;
9228 rettv->v_type = VAR_STRING;
9230 #ifdef FEAT_SEARCHPATH
9231 fname = get_tv_string(&argvars[0]);
9233 if (argvars[1].v_type != VAR_UNKNOWN)
9235 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
9236 if (p == NULL)
9237 error = TRUE;
9238 else
9240 if (*p != NUL)
9241 path = p;
9243 if (argvars[2].v_type != VAR_UNKNOWN)
9244 count = get_tv_number_chk(&argvars[2], &error);
9248 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
9249 error = TRUE;
9251 if (*fname != NUL && !error)
9255 if (rettv->v_type == VAR_STRING)
9256 vim_free(fresult);
9257 fresult = find_file_in_path_option(first ? fname : NULL,
9258 first ? (int)STRLEN(fname) : 0,
9259 0, first, path,
9260 find_what,
9261 curbuf->b_ffname,
9262 find_what == FINDFILE_DIR
9263 ? (char_u *)"" : curbuf->b_p_sua);
9264 first = FALSE;
9266 if (fresult != NULL && rettv->v_type == VAR_LIST)
9267 list_append_string(rettv->vval.v_list, fresult, -1);
9269 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
9272 if (rettv->v_type == VAR_STRING)
9273 rettv->vval.v_string = fresult;
9274 #endif
9277 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
9278 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
9281 * Implementation of map() and filter().
9283 static void
9284 filter_map(argvars, rettv, map)
9285 typval_T *argvars;
9286 typval_T *rettv;
9287 int map;
9289 char_u buf[NUMBUFLEN];
9290 char_u *expr;
9291 listitem_T *li, *nli;
9292 list_T *l = NULL;
9293 dictitem_T *di;
9294 hashtab_T *ht;
9295 hashitem_T *hi;
9296 dict_T *d = NULL;
9297 typval_T save_val;
9298 typval_T save_key;
9299 int rem;
9300 int todo;
9301 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
9302 int save_did_emsg;
9304 rettv->vval.v_number = 0;
9305 if (argvars[0].v_type == VAR_LIST)
9307 if ((l = argvars[0].vval.v_list) == NULL
9308 || (map && tv_check_lock(l->lv_lock, ermsg)))
9309 return;
9311 else if (argvars[0].v_type == VAR_DICT)
9313 if ((d = argvars[0].vval.v_dict) == NULL
9314 || (map && tv_check_lock(d->dv_lock, ermsg)))
9315 return;
9317 else
9319 EMSG2(_(e_listdictarg), ermsg);
9320 return;
9323 expr = get_tv_string_buf_chk(&argvars[1], buf);
9324 /* On type errors, the preceding call has already displayed an error
9325 * message. Avoid a misleading error message for an empty string that
9326 * was not passed as argument. */
9327 if (expr != NULL)
9329 prepare_vimvar(VV_VAL, &save_val);
9330 expr = skipwhite(expr);
9332 /* We reset "did_emsg" to be able to detect whether an error
9333 * occurred during evaluation of the expression. */
9334 save_did_emsg = did_emsg;
9335 did_emsg = FALSE;
9337 if (argvars[0].v_type == VAR_DICT)
9339 prepare_vimvar(VV_KEY, &save_key);
9340 vimvars[VV_KEY].vv_type = VAR_STRING;
9342 ht = &d->dv_hashtab;
9343 hash_lock(ht);
9344 todo = (int)ht->ht_used;
9345 for (hi = ht->ht_array; todo > 0; ++hi)
9347 if (!HASHITEM_EMPTY(hi))
9349 --todo;
9350 di = HI2DI(hi);
9351 if (tv_check_lock(di->di_tv.v_lock, ermsg))
9352 break;
9353 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
9354 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
9355 || did_emsg)
9356 break;
9357 if (!map && rem)
9358 dictitem_remove(d, di);
9359 clear_tv(&vimvars[VV_KEY].vv_tv);
9362 hash_unlock(ht);
9364 restore_vimvar(VV_KEY, &save_key);
9366 else
9368 for (li = l->lv_first; li != NULL; li = nli)
9370 if (tv_check_lock(li->li_tv.v_lock, ermsg))
9371 break;
9372 nli = li->li_next;
9373 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
9374 || did_emsg)
9375 break;
9376 if (!map && rem)
9377 listitem_remove(l, li);
9381 restore_vimvar(VV_VAL, &save_val);
9383 did_emsg |= save_did_emsg;
9386 copy_tv(&argvars[0], rettv);
9389 static int
9390 filter_map_one(tv, expr, map, remp)
9391 typval_T *tv;
9392 char_u *expr;
9393 int map;
9394 int *remp;
9396 typval_T rettv;
9397 char_u *s;
9398 int retval = FAIL;
9400 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
9401 s = expr;
9402 if (eval1(&s, &rettv, TRUE) == FAIL)
9403 goto theend;
9404 if (*s != NUL) /* check for trailing chars after expr */
9406 EMSG2(_(e_invexpr2), s);
9407 goto theend;
9409 if (map)
9411 /* map(): replace the list item value */
9412 clear_tv(tv);
9413 rettv.v_lock = 0;
9414 *tv = rettv;
9416 else
9418 int error = FALSE;
9420 /* filter(): when expr is zero remove the item */
9421 *remp = (get_tv_number_chk(&rettv, &error) == 0);
9422 clear_tv(&rettv);
9423 /* On type error, nothing has been removed; return FAIL to stop the
9424 * loop. The error message was given by get_tv_number_chk(). */
9425 if (error)
9426 goto theend;
9428 retval = OK;
9429 theend:
9430 clear_tv(&vimvars[VV_VAL].vv_tv);
9431 return retval;
9435 * "filter()" function
9437 static void
9438 f_filter(argvars, rettv)
9439 typval_T *argvars;
9440 typval_T *rettv;
9442 filter_map(argvars, rettv, FALSE);
9446 * "finddir({fname}[, {path}[, {count}]])" function
9448 static void
9449 f_finddir(argvars, rettv)
9450 typval_T *argvars;
9451 typval_T *rettv;
9453 findfilendir(argvars, rettv, FINDFILE_DIR);
9457 * "findfile({fname}[, {path}[, {count}]])" function
9459 static void
9460 f_findfile(argvars, rettv)
9461 typval_T *argvars;
9462 typval_T *rettv;
9464 findfilendir(argvars, rettv, FINDFILE_FILE);
9468 * "fnamemodify({fname}, {mods})" function
9470 static void
9471 f_fnamemodify(argvars, rettv)
9472 typval_T *argvars;
9473 typval_T *rettv;
9475 char_u *fname;
9476 char_u *mods;
9477 int usedlen = 0;
9478 int len;
9479 char_u *fbuf = NULL;
9480 char_u buf[NUMBUFLEN];
9482 fname = get_tv_string_chk(&argvars[0]);
9483 mods = get_tv_string_buf_chk(&argvars[1], buf);
9484 if (fname == NULL || mods == NULL)
9485 fname = NULL;
9486 else
9488 len = (int)STRLEN(fname);
9489 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
9492 rettv->v_type = VAR_STRING;
9493 if (fname == NULL)
9494 rettv->vval.v_string = NULL;
9495 else
9496 rettv->vval.v_string = vim_strnsave(fname, len);
9497 vim_free(fbuf);
9500 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
9503 * "foldclosed()" function
9505 static void
9506 foldclosed_both(argvars, rettv, end)
9507 typval_T *argvars;
9508 typval_T *rettv;
9509 int end;
9511 #ifdef FEAT_FOLDING
9512 linenr_T lnum;
9513 linenr_T first, last;
9515 lnum = get_tv_lnum(argvars);
9516 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9518 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
9520 if (end)
9521 rettv->vval.v_number = (varnumber_T)last;
9522 else
9523 rettv->vval.v_number = (varnumber_T)first;
9524 return;
9527 #endif
9528 rettv->vval.v_number = -1;
9532 * "foldclosed()" function
9534 static void
9535 f_foldclosed(argvars, rettv)
9536 typval_T *argvars;
9537 typval_T *rettv;
9539 foldclosed_both(argvars, rettv, FALSE);
9543 * "foldclosedend()" function
9545 static void
9546 f_foldclosedend(argvars, rettv)
9547 typval_T *argvars;
9548 typval_T *rettv;
9550 foldclosed_both(argvars, rettv, TRUE);
9554 * "foldlevel()" function
9556 static void
9557 f_foldlevel(argvars, rettv)
9558 typval_T *argvars;
9559 typval_T *rettv;
9561 #ifdef FEAT_FOLDING
9562 linenr_T lnum;
9564 lnum = get_tv_lnum(argvars);
9565 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9566 rettv->vval.v_number = foldLevel(lnum);
9567 else
9568 #endif
9569 rettv->vval.v_number = 0;
9573 * "foldtext()" function
9575 /*ARGSUSED*/
9576 static void
9577 f_foldtext(argvars, rettv)
9578 typval_T *argvars;
9579 typval_T *rettv;
9581 #ifdef FEAT_FOLDING
9582 linenr_T lnum;
9583 char_u *s;
9584 char_u *r;
9585 int len;
9586 char *txt;
9587 #endif
9589 rettv->v_type = VAR_STRING;
9590 rettv->vval.v_string = NULL;
9591 #ifdef FEAT_FOLDING
9592 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
9593 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
9594 <= curbuf->b_ml.ml_line_count
9595 && vimvars[VV_FOLDDASHES].vv_str != NULL)
9597 /* Find first non-empty line in the fold. */
9598 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
9599 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
9601 if (!linewhite(lnum))
9602 break;
9603 ++lnum;
9606 /* Find interesting text in this line. */
9607 s = skipwhite(ml_get(lnum));
9608 /* skip C comment-start */
9609 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
9611 s = skipwhite(s + 2);
9612 if (*skipwhite(s) == NUL
9613 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
9615 s = skipwhite(ml_get(lnum + 1));
9616 if (*s == '*')
9617 s = skipwhite(s + 1);
9620 txt = _("+-%s%3ld lines: ");
9621 r = alloc((unsigned)(STRLEN(txt)
9622 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
9623 + 20 /* for %3ld */
9624 + STRLEN(s))); /* concatenated */
9625 if (r != NULL)
9627 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
9628 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
9629 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
9630 len = (int)STRLEN(r);
9631 STRCAT(r, s);
9632 /* remove 'foldmarker' and 'commentstring' */
9633 foldtext_cleanup(r + len);
9634 rettv->vval.v_string = r;
9637 #endif
9641 * "foldtextresult(lnum)" function
9643 /*ARGSUSED*/
9644 static void
9645 f_foldtextresult(argvars, rettv)
9646 typval_T *argvars;
9647 typval_T *rettv;
9649 #ifdef FEAT_FOLDING
9650 linenr_T lnum;
9651 char_u *text;
9652 char_u buf[51];
9653 foldinfo_T foldinfo;
9654 int fold_count;
9655 #endif
9657 rettv->v_type = VAR_STRING;
9658 rettv->vval.v_string = NULL;
9659 #ifdef FEAT_FOLDING
9660 lnum = get_tv_lnum(argvars);
9661 /* treat illegal types and illegal string values for {lnum} the same */
9662 if (lnum < 0)
9663 lnum = 0;
9664 fold_count = foldedCount(curwin, lnum, &foldinfo);
9665 if (fold_count > 0)
9667 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
9668 &foldinfo, buf);
9669 if (text == buf)
9670 text = vim_strsave(text);
9671 rettv->vval.v_string = text;
9673 #endif
9677 * "foreground()" function
9679 /*ARGSUSED*/
9680 static void
9681 f_foreground(argvars, rettv)
9682 typval_T *argvars;
9683 typval_T *rettv;
9685 rettv->vval.v_number = 0;
9686 #ifdef FEAT_GUI
9687 if (gui.in_use)
9688 gui_mch_set_foreground();
9689 #else
9690 # ifdef WIN32
9691 win32_set_foreground();
9692 # endif
9693 #endif
9697 * "function()" function
9699 /*ARGSUSED*/
9700 static void
9701 f_function(argvars, rettv)
9702 typval_T *argvars;
9703 typval_T *rettv;
9705 char_u *s;
9707 rettv->vval.v_number = 0;
9708 s = get_tv_string(&argvars[0]);
9709 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
9710 EMSG2(_(e_invarg2), s);
9711 else if (!function_exists(s))
9712 EMSG2(_("E700: Unknown function: %s"), s);
9713 else
9715 rettv->vval.v_string = vim_strsave(s);
9716 rettv->v_type = VAR_FUNC;
9721 * "garbagecollect()" function
9723 /*ARGSUSED*/
9724 static void
9725 f_garbagecollect(argvars, rettv)
9726 typval_T *argvars;
9727 typval_T *rettv;
9729 /* This is postponed until we are back at the toplevel, because we may be
9730 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
9731 want_garbage_collect = TRUE;
9733 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
9734 garbage_collect_at_exit = TRUE;
9738 * "get()" function
9740 static void
9741 f_get(argvars, rettv)
9742 typval_T *argvars;
9743 typval_T *rettv;
9745 listitem_T *li;
9746 list_T *l;
9747 dictitem_T *di;
9748 dict_T *d;
9749 typval_T *tv = NULL;
9751 if (argvars[0].v_type == VAR_LIST)
9753 if ((l = argvars[0].vval.v_list) != NULL)
9755 int error = FALSE;
9757 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
9758 if (!error && li != NULL)
9759 tv = &li->li_tv;
9762 else if (argvars[0].v_type == VAR_DICT)
9764 if ((d = argvars[0].vval.v_dict) != NULL)
9766 di = dict_find(d, get_tv_string(&argvars[1]), -1);
9767 if (di != NULL)
9768 tv = &di->di_tv;
9771 else
9772 EMSG2(_(e_listdictarg), "get()");
9774 if (tv == NULL)
9776 if (argvars[2].v_type == VAR_UNKNOWN)
9777 rettv->vval.v_number = 0;
9778 else
9779 copy_tv(&argvars[2], rettv);
9781 else
9782 copy_tv(tv, rettv);
9785 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
9788 * Get line or list of lines from buffer "buf" into "rettv".
9789 * Return a range (from start to end) of lines in rettv from the specified
9790 * buffer.
9791 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
9793 static void
9794 get_buffer_lines(buf, start, end, retlist, rettv)
9795 buf_T *buf;
9796 linenr_T start;
9797 linenr_T end;
9798 int retlist;
9799 typval_T *rettv;
9801 char_u *p;
9803 if (retlist)
9805 if (rettv_list_alloc(rettv) == FAIL)
9806 return;
9808 else
9809 rettv->vval.v_number = 0;
9811 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
9812 return;
9814 if (!retlist)
9816 if (start >= 1 && start <= buf->b_ml.ml_line_count)
9817 p = ml_get_buf(buf, start, FALSE);
9818 else
9819 p = (char_u *)"";
9821 rettv->v_type = VAR_STRING;
9822 rettv->vval.v_string = vim_strsave(p);
9824 else
9826 if (end < start)
9827 return;
9829 if (start < 1)
9830 start = 1;
9831 if (end > buf->b_ml.ml_line_count)
9832 end = buf->b_ml.ml_line_count;
9833 while (start <= end)
9834 if (list_append_string(rettv->vval.v_list,
9835 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
9836 break;
9841 * "getbufline()" function
9843 static void
9844 f_getbufline(argvars, rettv)
9845 typval_T *argvars;
9846 typval_T *rettv;
9848 linenr_T lnum;
9849 linenr_T end;
9850 buf_T *buf;
9852 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
9853 ++emsg_off;
9854 buf = get_buf_tv(&argvars[0]);
9855 --emsg_off;
9857 lnum = get_tv_lnum_buf(&argvars[1], buf);
9858 if (argvars[2].v_type == VAR_UNKNOWN)
9859 end = lnum;
9860 else
9861 end = get_tv_lnum_buf(&argvars[2], buf);
9863 get_buffer_lines(buf, lnum, end, TRUE, rettv);
9867 * "getbufvar()" function
9869 static void
9870 f_getbufvar(argvars, rettv)
9871 typval_T *argvars;
9872 typval_T *rettv;
9874 buf_T *buf;
9875 buf_T *save_curbuf;
9876 char_u *varname;
9877 dictitem_T *v;
9879 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
9880 varname = get_tv_string_chk(&argvars[1]);
9881 ++emsg_off;
9882 buf = get_buf_tv(&argvars[0]);
9884 rettv->v_type = VAR_STRING;
9885 rettv->vval.v_string = NULL;
9887 if (buf != NULL && varname != NULL)
9889 if (*varname == '&') /* buffer-local-option */
9891 /* set curbuf to be our buf, temporarily */
9892 save_curbuf = curbuf;
9893 curbuf = buf;
9895 get_option_tv(&varname, rettv, TRUE);
9897 /* restore previous notion of curbuf */
9898 curbuf = save_curbuf;
9900 else
9902 if (*varname == NUL)
9903 /* let getbufvar({nr}, "") return the "b:" dictionary. The
9904 * scope prefix before the NUL byte is required by
9905 * find_var_in_ht(). */
9906 varname = (char_u *)"b:" + 2;
9907 /* look up the variable */
9908 v = find_var_in_ht(&buf->b_vars.dv_hashtab, varname, FALSE);
9909 if (v != NULL)
9910 copy_tv(&v->di_tv, rettv);
9914 --emsg_off;
9918 * "getchar()" function
9920 static void
9921 f_getchar(argvars, rettv)
9922 typval_T *argvars;
9923 typval_T *rettv;
9925 varnumber_T n;
9926 int error = FALSE;
9928 /* Position the cursor. Needed after a message that ends in a space. */
9929 windgoto(msg_row, msg_col);
9931 ++no_mapping;
9932 ++allow_keys;
9933 for (;;)
9935 if (argvars[0].v_type == VAR_UNKNOWN)
9936 /* getchar(): blocking wait. */
9937 n = safe_vgetc();
9938 else if (get_tv_number_chk(&argvars[0], &error) == 1)
9939 /* getchar(1): only check if char avail */
9940 n = vpeekc();
9941 else if (error || vpeekc() == NUL)
9942 /* illegal argument or getchar(0) and no char avail: return zero */
9943 n = 0;
9944 else
9945 /* getchar(0) and char avail: return char */
9946 n = safe_vgetc();
9947 if (n == K_IGNORE)
9948 continue;
9949 break;
9951 --no_mapping;
9952 --allow_keys;
9954 vimvars[VV_MOUSE_WIN].vv_nr = 0;
9955 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
9956 vimvars[VV_MOUSE_COL].vv_nr = 0;
9958 rettv->vval.v_number = n;
9959 if (IS_SPECIAL(n) || mod_mask != 0)
9961 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
9962 int i = 0;
9964 /* Turn a special key into three bytes, plus modifier. */
9965 if (mod_mask != 0)
9967 temp[i++] = K_SPECIAL;
9968 temp[i++] = KS_MODIFIER;
9969 temp[i++] = mod_mask;
9971 if (IS_SPECIAL(n))
9973 temp[i++] = K_SPECIAL;
9974 temp[i++] = K_SECOND(n);
9975 temp[i++] = K_THIRD(n);
9977 #ifdef FEAT_MBYTE
9978 else if (has_mbyte)
9979 i += (*mb_char2bytes)(n, temp + i);
9980 #endif
9981 else
9982 temp[i++] = n;
9983 temp[i++] = NUL;
9984 rettv->v_type = VAR_STRING;
9985 rettv->vval.v_string = vim_strsave(temp);
9987 #ifdef FEAT_MOUSE
9988 if (n == K_LEFTMOUSE
9989 || n == K_LEFTMOUSE_NM
9990 || n == K_LEFTDRAG
9991 || n == K_LEFTRELEASE
9992 || n == K_LEFTRELEASE_NM
9993 || n == K_MIDDLEMOUSE
9994 || n == K_MIDDLEDRAG
9995 || n == K_MIDDLERELEASE
9996 || n == K_RIGHTMOUSE
9997 || n == K_RIGHTDRAG
9998 || n == K_RIGHTRELEASE
9999 || n == K_X1MOUSE
10000 || n == K_X1DRAG
10001 || n == K_X1RELEASE
10002 || n == K_X2MOUSE
10003 || n == K_X2DRAG
10004 || n == K_X2RELEASE
10005 || n == K_MOUSEDOWN
10006 || n == K_MOUSEUP)
10008 int row = mouse_row;
10009 int col = mouse_col;
10010 win_T *win;
10011 linenr_T lnum;
10012 # ifdef FEAT_WINDOWS
10013 win_T *wp;
10014 # endif
10015 int n = 1;
10017 if (row >= 0 && col >= 0)
10019 /* Find the window at the mouse coordinates and compute the
10020 * text position. */
10021 win = mouse_find_win(&row, &col);
10022 (void)mouse_comp_pos(win, &row, &col, &lnum);
10023 # ifdef FEAT_WINDOWS
10024 for (wp = firstwin; wp != win; wp = wp->w_next)
10025 ++n;
10026 # endif
10027 vimvars[VV_MOUSE_WIN].vv_nr = n;
10028 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
10029 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
10032 #endif
10037 * "getcharmod()" function
10039 /*ARGSUSED*/
10040 static void
10041 f_getcharmod(argvars, rettv)
10042 typval_T *argvars;
10043 typval_T *rettv;
10045 rettv->vval.v_number = mod_mask;
10049 * "getcmdline()" function
10051 /*ARGSUSED*/
10052 static void
10053 f_getcmdline(argvars, rettv)
10054 typval_T *argvars;
10055 typval_T *rettv;
10057 rettv->v_type = VAR_STRING;
10058 rettv->vval.v_string = get_cmdline_str();
10062 * "getcmdpos()" function
10064 /*ARGSUSED*/
10065 static void
10066 f_getcmdpos(argvars, rettv)
10067 typval_T *argvars;
10068 typval_T *rettv;
10070 rettv->vval.v_number = get_cmdline_pos() + 1;
10074 * "getcmdtype()" function
10076 /*ARGSUSED*/
10077 static void
10078 f_getcmdtype(argvars, rettv)
10079 typval_T *argvars;
10080 typval_T *rettv;
10082 rettv->v_type = VAR_STRING;
10083 rettv->vval.v_string = alloc(2);
10084 if (rettv->vval.v_string != NULL)
10086 rettv->vval.v_string[0] = get_cmdline_type();
10087 rettv->vval.v_string[1] = NUL;
10092 * "getcwd()" function
10094 /*ARGSUSED*/
10095 static void
10096 f_getcwd(argvars, rettv)
10097 typval_T *argvars;
10098 typval_T *rettv;
10100 char_u cwd[MAXPATHL];
10102 rettv->v_type = VAR_STRING;
10103 if (mch_dirname(cwd, MAXPATHL) == FAIL)
10104 rettv->vval.v_string = NULL;
10105 else
10107 rettv->vval.v_string = vim_strsave(cwd);
10108 #ifdef BACKSLASH_IN_FILENAME
10109 if (rettv->vval.v_string != NULL)
10110 slash_adjust(rettv->vval.v_string);
10111 #endif
10116 * "getfontname()" function
10118 /*ARGSUSED*/
10119 static void
10120 f_getfontname(argvars, rettv)
10121 typval_T *argvars;
10122 typval_T *rettv;
10124 rettv->v_type = VAR_STRING;
10125 rettv->vval.v_string = NULL;
10126 #ifdef FEAT_GUI
10127 if (gui.in_use)
10129 GuiFont font;
10130 char_u *name = NULL;
10132 if (argvars[0].v_type == VAR_UNKNOWN)
10134 /* Get the "Normal" font. Either the name saved by
10135 * hl_set_font_name() or from the font ID. */
10136 font = gui.norm_font;
10137 name = hl_get_font_name();
10139 else
10141 name = get_tv_string(&argvars[0]);
10142 if (STRCMP(name, "*") == 0) /* don't use font dialog */
10143 return;
10144 font = gui_mch_get_font(name, FALSE);
10145 if (font == NOFONT)
10146 return; /* Invalid font name, return empty string. */
10148 rettv->vval.v_string = gui_mch_get_fontname(font, name);
10149 if (argvars[0].v_type != VAR_UNKNOWN)
10150 gui_mch_free_font(font);
10152 #endif
10156 * "getfperm({fname})" function
10158 static void
10159 f_getfperm(argvars, rettv)
10160 typval_T *argvars;
10161 typval_T *rettv;
10163 char_u *fname;
10164 struct stat st;
10165 char_u *perm = NULL;
10166 char_u flags[] = "rwx";
10167 int i;
10169 fname = get_tv_string(&argvars[0]);
10171 rettv->v_type = VAR_STRING;
10172 if (mch_stat((char *)fname, &st) >= 0)
10174 perm = vim_strsave((char_u *)"---------");
10175 if (perm != NULL)
10177 for (i = 0; i < 9; i++)
10179 if (st.st_mode & (1 << (8 - i)))
10180 perm[i] = flags[i % 3];
10184 rettv->vval.v_string = perm;
10188 * "getfsize({fname})" function
10190 static void
10191 f_getfsize(argvars, rettv)
10192 typval_T *argvars;
10193 typval_T *rettv;
10195 char_u *fname;
10196 struct stat st;
10198 fname = get_tv_string(&argvars[0]);
10200 rettv->v_type = VAR_NUMBER;
10202 if (mch_stat((char *)fname, &st) >= 0)
10204 if (mch_isdir(fname))
10205 rettv->vval.v_number = 0;
10206 else
10208 rettv->vval.v_number = (varnumber_T)st.st_size;
10210 /* non-perfect check for overflow */
10211 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
10212 rettv->vval.v_number = -2;
10215 else
10216 rettv->vval.v_number = -1;
10220 * "getftime({fname})" function
10222 static void
10223 f_getftime(argvars, rettv)
10224 typval_T *argvars;
10225 typval_T *rettv;
10227 char_u *fname;
10228 struct stat st;
10230 fname = get_tv_string(&argvars[0]);
10232 if (mch_stat((char *)fname, &st) >= 0)
10233 rettv->vval.v_number = (varnumber_T)st.st_mtime;
10234 else
10235 rettv->vval.v_number = -1;
10239 * "getftype({fname})" function
10241 static void
10242 f_getftype(argvars, rettv)
10243 typval_T *argvars;
10244 typval_T *rettv;
10246 char_u *fname;
10247 struct stat st;
10248 char_u *type = NULL;
10249 char *t;
10251 fname = get_tv_string(&argvars[0]);
10253 rettv->v_type = VAR_STRING;
10254 if (mch_lstat((char *)fname, &st) >= 0)
10256 #ifdef S_ISREG
10257 if (S_ISREG(st.st_mode))
10258 t = "file";
10259 else if (S_ISDIR(st.st_mode))
10260 t = "dir";
10261 # ifdef S_ISLNK
10262 else if (S_ISLNK(st.st_mode))
10263 t = "link";
10264 # endif
10265 # ifdef S_ISBLK
10266 else if (S_ISBLK(st.st_mode))
10267 t = "bdev";
10268 # endif
10269 # ifdef S_ISCHR
10270 else if (S_ISCHR(st.st_mode))
10271 t = "cdev";
10272 # endif
10273 # ifdef S_ISFIFO
10274 else if (S_ISFIFO(st.st_mode))
10275 t = "fifo";
10276 # endif
10277 # ifdef S_ISSOCK
10278 else if (S_ISSOCK(st.st_mode))
10279 t = "fifo";
10280 # endif
10281 else
10282 t = "other";
10283 #else
10284 # ifdef S_IFMT
10285 switch (st.st_mode & S_IFMT)
10287 case S_IFREG: t = "file"; break;
10288 case S_IFDIR: t = "dir"; break;
10289 # ifdef S_IFLNK
10290 case S_IFLNK: t = "link"; break;
10291 # endif
10292 # ifdef S_IFBLK
10293 case S_IFBLK: t = "bdev"; break;
10294 # endif
10295 # ifdef S_IFCHR
10296 case S_IFCHR: t = "cdev"; break;
10297 # endif
10298 # ifdef S_IFIFO
10299 case S_IFIFO: t = "fifo"; break;
10300 # endif
10301 # ifdef S_IFSOCK
10302 case S_IFSOCK: t = "socket"; break;
10303 # endif
10304 default: t = "other";
10306 # else
10307 if (mch_isdir(fname))
10308 t = "dir";
10309 else
10310 t = "file";
10311 # endif
10312 #endif
10313 type = vim_strsave((char_u *)t);
10315 rettv->vval.v_string = type;
10319 * "getline(lnum, [end])" function
10321 static void
10322 f_getline(argvars, rettv)
10323 typval_T *argvars;
10324 typval_T *rettv;
10326 linenr_T lnum;
10327 linenr_T end;
10328 int retlist;
10330 lnum = get_tv_lnum(argvars);
10331 if (argvars[1].v_type == VAR_UNKNOWN)
10333 end = 0;
10334 retlist = FALSE;
10336 else
10338 end = get_tv_lnum(&argvars[1]);
10339 retlist = TRUE;
10342 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
10346 * "getmatches()" function
10348 /*ARGSUSED*/
10349 static void
10350 f_getmatches(argvars, rettv)
10351 typval_T *argvars;
10352 typval_T *rettv;
10354 #ifdef FEAT_SEARCH_EXTRA
10355 dict_T *dict;
10356 matchitem_T *cur = curwin->w_match_head;
10358 rettv->vval.v_number = 0;
10360 if (rettv_list_alloc(rettv) == OK)
10362 while (cur != NULL)
10364 dict = dict_alloc();
10365 if (dict == NULL)
10366 return;
10367 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
10368 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
10369 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
10370 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
10371 list_append_dict(rettv->vval.v_list, dict);
10372 cur = cur->next;
10375 #endif
10379 * "getpid()" function
10381 /*ARGSUSED*/
10382 static void
10383 f_getpid(argvars, rettv)
10384 typval_T *argvars;
10385 typval_T *rettv;
10387 rettv->vval.v_number = mch_get_pid();
10391 * "getpos(string)" function
10393 static void
10394 f_getpos(argvars, rettv)
10395 typval_T *argvars;
10396 typval_T *rettv;
10398 pos_T *fp;
10399 list_T *l;
10400 int fnum = -1;
10402 if (rettv_list_alloc(rettv) == OK)
10404 l = rettv->vval.v_list;
10405 fp = var2fpos(&argvars[0], TRUE, &fnum);
10406 if (fnum != -1)
10407 list_append_number(l, (varnumber_T)fnum);
10408 else
10409 list_append_number(l, (varnumber_T)0);
10410 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
10411 : (varnumber_T)0);
10412 list_append_number(l, (fp != NULL)
10413 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
10414 : (varnumber_T)0);
10415 list_append_number(l,
10416 #ifdef FEAT_VIRTUALEDIT
10417 (fp != NULL) ? (varnumber_T)fp->coladd :
10418 #endif
10419 (varnumber_T)0);
10421 else
10422 rettv->vval.v_number = FALSE;
10426 * "getqflist()" and "getloclist()" functions
10428 /*ARGSUSED*/
10429 static void
10430 f_getqflist(argvars, rettv)
10431 typval_T *argvars;
10432 typval_T *rettv;
10434 #ifdef FEAT_QUICKFIX
10435 win_T *wp;
10436 #endif
10438 rettv->vval.v_number = 0;
10439 #ifdef FEAT_QUICKFIX
10440 if (rettv_list_alloc(rettv) == OK)
10442 wp = NULL;
10443 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
10445 wp = find_win_by_nr(&argvars[0], NULL);
10446 if (wp == NULL)
10447 return;
10450 (void)get_errorlist(wp, rettv->vval.v_list);
10452 #endif
10456 * "getreg()" function
10458 static void
10459 f_getreg(argvars, rettv)
10460 typval_T *argvars;
10461 typval_T *rettv;
10463 char_u *strregname;
10464 int regname;
10465 int arg2 = FALSE;
10466 int error = FALSE;
10468 if (argvars[0].v_type != VAR_UNKNOWN)
10470 strregname = get_tv_string_chk(&argvars[0]);
10471 error = strregname == NULL;
10472 if (argvars[1].v_type != VAR_UNKNOWN)
10473 arg2 = get_tv_number_chk(&argvars[1], &error);
10475 else
10476 strregname = vimvars[VV_REG].vv_str;
10477 regname = (strregname == NULL ? '"' : *strregname);
10478 if (regname == 0)
10479 regname = '"';
10481 rettv->v_type = VAR_STRING;
10482 rettv->vval.v_string = error ? NULL :
10483 get_reg_contents(regname, TRUE, arg2);
10487 * "getregtype()" function
10489 static void
10490 f_getregtype(argvars, rettv)
10491 typval_T *argvars;
10492 typval_T *rettv;
10494 char_u *strregname;
10495 int regname;
10496 char_u buf[NUMBUFLEN + 2];
10497 long reglen = 0;
10499 if (argvars[0].v_type != VAR_UNKNOWN)
10501 strregname = get_tv_string_chk(&argvars[0]);
10502 if (strregname == NULL) /* type error; errmsg already given */
10504 rettv->v_type = VAR_STRING;
10505 rettv->vval.v_string = NULL;
10506 return;
10509 else
10510 /* Default to v:register */
10511 strregname = vimvars[VV_REG].vv_str;
10513 regname = (strregname == NULL ? '"' : *strregname);
10514 if (regname == 0)
10515 regname = '"';
10517 buf[0] = NUL;
10518 buf[1] = NUL;
10519 switch (get_reg_type(regname, &reglen))
10521 case MLINE: buf[0] = 'V'; break;
10522 case MCHAR: buf[0] = 'v'; break;
10523 #ifdef FEAT_VISUAL
10524 case MBLOCK:
10525 buf[0] = Ctrl_V;
10526 sprintf((char *)buf + 1, "%ld", reglen + 1);
10527 break;
10528 #endif
10530 rettv->v_type = VAR_STRING;
10531 rettv->vval.v_string = vim_strsave(buf);
10535 * "gettabwinvar()" function
10537 static void
10538 f_gettabwinvar(argvars, rettv)
10539 typval_T *argvars;
10540 typval_T *rettv;
10542 getwinvar(argvars, rettv, 1);
10546 * "getwinposx()" function
10548 /*ARGSUSED*/
10549 static void
10550 f_getwinposx(argvars, rettv)
10551 typval_T *argvars;
10552 typval_T *rettv;
10554 rettv->vval.v_number = -1;
10555 #ifdef FEAT_GUI
10556 if (gui.in_use)
10558 int x, y;
10560 if (gui_mch_get_winpos(&x, &y) == OK)
10561 rettv->vval.v_number = x;
10563 #endif
10567 * "getwinposy()" function
10569 /*ARGSUSED*/
10570 static void
10571 f_getwinposy(argvars, rettv)
10572 typval_T *argvars;
10573 typval_T *rettv;
10575 rettv->vval.v_number = -1;
10576 #ifdef FEAT_GUI
10577 if (gui.in_use)
10579 int x, y;
10581 if (gui_mch_get_winpos(&x, &y) == OK)
10582 rettv->vval.v_number = y;
10584 #endif
10588 * Find window specifed by "vp" in tabpage "tp".
10590 static win_T *
10591 find_win_by_nr(vp, tp)
10592 typval_T *vp;
10593 tabpage_T *tp; /* NULL for current tab page */
10595 #ifdef FEAT_WINDOWS
10596 win_T *wp;
10597 #endif
10598 int nr;
10600 nr = get_tv_number_chk(vp, NULL);
10602 #ifdef FEAT_WINDOWS
10603 if (nr < 0)
10604 return NULL;
10605 if (nr == 0)
10606 return curwin;
10608 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
10609 wp != NULL; wp = wp->w_next)
10610 if (--nr <= 0)
10611 break;
10612 return wp;
10613 #else
10614 if (nr == 0 || nr == 1)
10615 return curwin;
10616 return NULL;
10617 #endif
10621 * "getwinvar()" function
10623 static void
10624 f_getwinvar(argvars, rettv)
10625 typval_T *argvars;
10626 typval_T *rettv;
10628 getwinvar(argvars, rettv, 0);
10632 * getwinvar() and gettabwinvar()
10634 static void
10635 getwinvar(argvars, rettv, off)
10636 typval_T *argvars;
10637 typval_T *rettv;
10638 int off; /* 1 for gettabwinvar() */
10640 win_T *win, *oldcurwin;
10641 char_u *varname;
10642 dictitem_T *v;
10643 tabpage_T *tp;
10645 #ifdef FEAT_WINDOWS
10646 if (off == 1)
10647 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
10648 else
10649 tp = curtab;
10650 #endif
10651 win = find_win_by_nr(&argvars[off], tp);
10652 varname = get_tv_string_chk(&argvars[off + 1]);
10653 ++emsg_off;
10655 rettv->v_type = VAR_STRING;
10656 rettv->vval.v_string = NULL;
10658 if (win != NULL && varname != NULL)
10660 /* Set curwin to be our win, temporarily. Also set curbuf, so
10661 * that we can get buffer-local options. */
10662 oldcurwin = curwin;
10663 curwin = win;
10664 curbuf = win->w_buffer;
10666 if (*varname == '&') /* window-local-option */
10667 get_option_tv(&varname, rettv, 1);
10668 else
10670 if (*varname == NUL)
10671 /* let getwinvar({nr}, "") return the "w:" dictionary. The
10672 * scope prefix before the NUL byte is required by
10673 * find_var_in_ht(). */
10674 varname = (char_u *)"w:" + 2;
10675 /* look up the variable */
10676 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
10677 if (v != NULL)
10678 copy_tv(&v->di_tv, rettv);
10681 /* restore previous notion of curwin */
10682 curwin = oldcurwin;
10683 curbuf = curwin->w_buffer;
10686 --emsg_off;
10690 * "glob()" function
10692 static void
10693 f_glob(argvars, rettv)
10694 typval_T *argvars;
10695 typval_T *rettv;
10697 expand_T xpc;
10699 ExpandInit(&xpc);
10700 xpc.xp_context = EXPAND_FILES;
10701 rettv->v_type = VAR_STRING;
10702 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
10703 NULL, WILD_USE_NL|WILD_SILENT, WILD_ALL);
10707 * "globpath()" function
10709 static void
10710 f_globpath(argvars, rettv)
10711 typval_T *argvars;
10712 typval_T *rettv;
10714 char_u buf1[NUMBUFLEN];
10715 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
10717 rettv->v_type = VAR_STRING;
10718 if (file == NULL)
10719 rettv->vval.v_string = NULL;
10720 else
10721 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file);
10725 * "has()" function
10727 static void
10728 f_has(argvars, rettv)
10729 typval_T *argvars;
10730 typval_T *rettv;
10732 int i;
10733 char_u *name;
10734 int n = FALSE;
10735 static char *(has_list[]) =
10737 #ifdef AMIGA
10738 "amiga",
10739 # ifdef FEAT_ARP
10740 "arp",
10741 # endif
10742 #endif
10743 #ifdef __BEOS__
10744 "beos",
10745 #endif
10746 #ifdef MSDOS
10747 # ifdef DJGPP
10748 "dos32",
10749 # else
10750 "dos16",
10751 # endif
10752 #endif
10753 #ifdef MACOS
10754 "mac",
10755 #endif
10756 #if defined(MACOS_X_UNIX)
10757 "macunix",
10758 #endif
10759 #ifdef OS2
10760 "os2",
10761 #endif
10762 #ifdef __QNX__
10763 "qnx",
10764 #endif
10765 #ifdef RISCOS
10766 "riscos",
10767 #endif
10768 #ifdef UNIX
10769 "unix",
10770 #endif
10771 #ifdef VMS
10772 "vms",
10773 #endif
10774 #ifdef WIN16
10775 "win16",
10776 #endif
10777 #ifdef WIN32
10778 "win32",
10779 #endif
10780 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
10781 "win32unix",
10782 #endif
10783 #ifdef WIN64
10784 "win64",
10785 #endif
10786 #ifdef EBCDIC
10787 "ebcdic",
10788 #endif
10789 #ifndef CASE_INSENSITIVE_FILENAME
10790 "fname_case",
10791 #endif
10792 #ifdef FEAT_ARABIC
10793 "arabic",
10794 #endif
10795 #ifdef FEAT_AUTOCMD
10796 "autocmd",
10797 #endif
10798 #ifdef FEAT_BEVAL
10799 "balloon_eval",
10800 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
10801 "balloon_multiline",
10802 # endif
10803 #endif
10804 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
10805 "builtin_terms",
10806 # ifdef ALL_BUILTIN_TCAPS
10807 "all_builtin_terms",
10808 # endif
10809 #endif
10810 #ifdef FEAT_BYTEOFF
10811 "byte_offset",
10812 #endif
10813 #ifdef FEAT_CINDENT
10814 "cindent",
10815 #endif
10816 #ifdef FEAT_CLIENTSERVER
10817 "clientserver",
10818 #endif
10819 #ifdef FEAT_CLIPBOARD
10820 "clipboard",
10821 #endif
10822 #ifdef FEAT_CMDL_COMPL
10823 "cmdline_compl",
10824 #endif
10825 #ifdef FEAT_CMDHIST
10826 "cmdline_hist",
10827 #endif
10828 #ifdef FEAT_COMMENTS
10829 "comments",
10830 #endif
10831 #ifdef FEAT_CRYPT
10832 "cryptv",
10833 #endif
10834 #ifdef FEAT_CSCOPE
10835 "cscope",
10836 #endif
10837 #ifdef CURSOR_SHAPE
10838 "cursorshape",
10839 #endif
10840 #ifdef DEBUG
10841 "debug",
10842 #endif
10843 #ifdef FEAT_CON_DIALOG
10844 "dialog_con",
10845 #endif
10846 #ifdef FEAT_GUI_DIALOG
10847 "dialog_gui",
10848 #endif
10849 #ifdef FEAT_DIFF
10850 "diff",
10851 #endif
10852 #ifdef FEAT_DIGRAPHS
10853 "digraphs",
10854 #endif
10855 #ifdef FEAT_DND
10856 "dnd",
10857 #endif
10858 #ifdef FEAT_EMACS_TAGS
10859 "emacs_tags",
10860 #endif
10861 "eval", /* always present, of course! */
10862 #ifdef FEAT_EX_EXTRA
10863 "ex_extra",
10864 #endif
10865 #ifdef FEAT_SEARCH_EXTRA
10866 "extra_search",
10867 #endif
10868 #ifdef FEAT_FKMAP
10869 "farsi",
10870 #endif
10871 #ifdef FEAT_SEARCHPATH
10872 "file_in_path",
10873 #endif
10874 #if defined(UNIX) && !defined(USE_SYSTEM)
10875 "filterpipe",
10876 #endif
10877 #ifdef FEAT_FIND_ID
10878 "find_in_path",
10879 #endif
10880 #ifdef FEAT_FOLDING
10881 "folding",
10882 #endif
10883 #ifdef FEAT_FOOTER
10884 "footer",
10885 #endif
10886 #if !defined(USE_SYSTEM) && defined(UNIX)
10887 "fork",
10888 #endif
10889 #ifdef FEAT_GETTEXT
10890 "gettext",
10891 #endif
10892 #ifdef FEAT_GUI
10893 "gui",
10894 #endif
10895 #ifdef FEAT_GUI_ATHENA
10896 # ifdef FEAT_GUI_NEXTAW
10897 "gui_neXtaw",
10898 # else
10899 "gui_athena",
10900 # endif
10901 #endif
10902 #ifdef FEAT_GUI_GTK
10903 "gui_gtk",
10904 # ifdef HAVE_GTK2
10905 "gui_gtk2",
10906 # endif
10907 #endif
10908 #ifdef FEAT_GUI_GNOME
10909 "gui_gnome",
10910 #endif
10911 #ifdef FEAT_GUI_MAC
10912 "gui_mac",
10913 #endif
10914 #ifdef FEAT_GUI_MOTIF
10915 "gui_motif",
10916 #endif
10917 #ifdef FEAT_GUI_PHOTON
10918 "gui_photon",
10919 #endif
10920 #ifdef FEAT_GUI_W16
10921 "gui_win16",
10922 #endif
10923 #ifdef FEAT_GUI_W32
10924 "gui_win32",
10925 #endif
10926 #ifdef FEAT_HANGULIN
10927 "hangul_input",
10928 #endif
10929 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
10930 "iconv",
10931 #endif
10932 #ifdef FEAT_INS_EXPAND
10933 "insert_expand",
10934 #endif
10935 #ifdef FEAT_JUMPLIST
10936 "jumplist",
10937 #endif
10938 #ifdef FEAT_KEYMAP
10939 "keymap",
10940 #endif
10941 #ifdef FEAT_LANGMAP
10942 "langmap",
10943 #endif
10944 #ifdef FEAT_LIBCALL
10945 "libcall",
10946 #endif
10947 #ifdef FEAT_LINEBREAK
10948 "linebreak",
10949 #endif
10950 #ifdef FEAT_LISP
10951 "lispindent",
10952 #endif
10953 #ifdef FEAT_LISTCMDS
10954 "listcmds",
10955 #endif
10956 #ifdef FEAT_LOCALMAP
10957 "localmap",
10958 #endif
10959 #ifdef FEAT_MENU
10960 "menu",
10961 #endif
10962 #ifdef FEAT_SESSION
10963 "mksession",
10964 #endif
10965 #ifdef FEAT_MODIFY_FNAME
10966 "modify_fname",
10967 #endif
10968 #ifdef FEAT_MOUSE
10969 "mouse",
10970 #endif
10971 #ifdef FEAT_MOUSESHAPE
10972 "mouseshape",
10973 #endif
10974 #if defined(UNIX) || defined(VMS)
10975 # ifdef FEAT_MOUSE_DEC
10976 "mouse_dec",
10977 # endif
10978 # ifdef FEAT_MOUSE_GPM
10979 "mouse_gpm",
10980 # endif
10981 # ifdef FEAT_MOUSE_JSB
10982 "mouse_jsbterm",
10983 # endif
10984 # ifdef FEAT_MOUSE_NET
10985 "mouse_netterm",
10986 # endif
10987 # ifdef FEAT_MOUSE_PTERM
10988 "mouse_pterm",
10989 # endif
10990 # ifdef FEAT_MOUSE_XTERM
10991 "mouse_xterm",
10992 # endif
10993 #endif
10994 #ifdef FEAT_MBYTE
10995 "multi_byte",
10996 #endif
10997 #ifdef FEAT_MBYTE_IME
10998 "multi_byte_ime",
10999 #endif
11000 #ifdef FEAT_MULTI_LANG
11001 "multi_lang",
11002 #endif
11003 #ifdef FEAT_MZSCHEME
11004 #ifndef DYNAMIC_MZSCHEME
11005 "mzscheme",
11006 #endif
11007 #endif
11008 #ifdef FEAT_OLE
11009 "ole",
11010 #endif
11011 #ifdef FEAT_OSFILETYPE
11012 "osfiletype",
11013 #endif
11014 #ifdef FEAT_PATH_EXTRA
11015 "path_extra",
11016 #endif
11017 #ifdef FEAT_PERL
11018 #ifndef DYNAMIC_PERL
11019 "perl",
11020 #endif
11021 #endif
11022 #ifdef FEAT_PYTHON
11023 #ifndef DYNAMIC_PYTHON
11024 "python",
11025 #endif
11026 #endif
11027 #ifdef FEAT_POSTSCRIPT
11028 "postscript",
11029 #endif
11030 #ifdef FEAT_PRINTER
11031 "printer",
11032 #endif
11033 #ifdef FEAT_PROFILE
11034 "profile",
11035 #endif
11036 #ifdef FEAT_RELTIME
11037 "reltime",
11038 #endif
11039 #ifdef FEAT_QUICKFIX
11040 "quickfix",
11041 #endif
11042 #ifdef FEAT_RIGHTLEFT
11043 "rightleft",
11044 #endif
11045 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11046 "ruby",
11047 #endif
11048 #ifdef FEAT_SCROLLBIND
11049 "scrollbind",
11050 #endif
11051 #ifdef FEAT_CMDL_INFO
11052 "showcmd",
11053 "cmdline_info",
11054 #endif
11055 #ifdef FEAT_SIGNS
11056 "signs",
11057 #endif
11058 #ifdef FEAT_SMARTINDENT
11059 "smartindent",
11060 #endif
11061 #ifdef FEAT_SNIFF
11062 "sniff",
11063 #endif
11064 #ifdef FEAT_STL_OPT
11065 "statusline",
11066 #endif
11067 #ifdef FEAT_SUN_WORKSHOP
11068 "sun_workshop",
11069 #endif
11070 #ifdef FEAT_NETBEANS_INTG
11071 "netbeans_intg",
11072 #endif
11073 #ifdef FEAT_SPELL
11074 "spell",
11075 #endif
11076 #ifdef FEAT_SYN_HL
11077 "syntax",
11078 #endif
11079 #if defined(USE_SYSTEM) || !defined(UNIX)
11080 "system",
11081 #endif
11082 #ifdef FEAT_TAG_BINS
11083 "tag_binary",
11084 #endif
11085 #ifdef FEAT_TAG_OLDSTATIC
11086 "tag_old_static",
11087 #endif
11088 #ifdef FEAT_TAG_ANYWHITE
11089 "tag_any_white",
11090 #endif
11091 #ifdef FEAT_TCL
11092 # ifndef DYNAMIC_TCL
11093 "tcl",
11094 # endif
11095 #endif
11096 #ifdef TERMINFO
11097 "terminfo",
11098 #endif
11099 #ifdef FEAT_TERMRESPONSE
11100 "termresponse",
11101 #endif
11102 #ifdef FEAT_TEXTOBJ
11103 "textobjects",
11104 #endif
11105 #ifdef HAVE_TGETENT
11106 "tgetent",
11107 #endif
11108 #ifdef FEAT_TITLE
11109 "title",
11110 #endif
11111 #ifdef FEAT_TOOLBAR
11112 "toolbar",
11113 #endif
11114 #ifdef FEAT_USR_CMDS
11115 "user-commands", /* was accidentally included in 5.4 */
11116 "user_commands",
11117 #endif
11118 #ifdef FEAT_VIMINFO
11119 "viminfo",
11120 #endif
11121 #ifdef FEAT_VERTSPLIT
11122 "vertsplit",
11123 #endif
11124 #ifdef FEAT_VIRTUALEDIT
11125 "virtualedit",
11126 #endif
11127 #ifdef FEAT_VISUAL
11128 "visual",
11129 #endif
11130 #ifdef FEAT_VISUALEXTRA
11131 "visualextra",
11132 #endif
11133 #ifdef FEAT_VREPLACE
11134 "vreplace",
11135 #endif
11136 #ifdef FEAT_WILDIGN
11137 "wildignore",
11138 #endif
11139 #ifdef FEAT_WILDMENU
11140 "wildmenu",
11141 #endif
11142 #ifdef FEAT_WINDOWS
11143 "windows",
11144 #endif
11145 #ifdef FEAT_WAK
11146 "winaltkeys",
11147 #endif
11148 #ifdef FEAT_WRITEBACKUP
11149 "writebackup",
11150 #endif
11151 #ifdef FEAT_XIM
11152 "xim",
11153 #endif
11154 #ifdef FEAT_XFONTSET
11155 "xfontset",
11156 #endif
11157 #ifdef USE_XSMP
11158 "xsmp",
11159 #endif
11160 #ifdef USE_XSMP_INTERACT
11161 "xsmp_interact",
11162 #endif
11163 #ifdef FEAT_XCLIPBOARD
11164 "xterm_clipboard",
11165 #endif
11166 #ifdef FEAT_XTERM_SAVE
11167 "xterm_save",
11168 #endif
11169 #if defined(UNIX) && defined(FEAT_X11)
11170 "X11",
11171 #endif
11172 NULL
11175 name = get_tv_string(&argvars[0]);
11176 for (i = 0; has_list[i] != NULL; ++i)
11177 if (STRICMP(name, has_list[i]) == 0)
11179 n = TRUE;
11180 break;
11183 if (n == FALSE)
11185 if (STRNICMP(name, "patch", 5) == 0)
11186 n = has_patch(atoi((char *)name + 5));
11187 else if (STRICMP(name, "vim_starting") == 0)
11188 n = (starting != 0);
11189 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
11190 else if (STRICMP(name, "balloon_multiline") == 0)
11191 n = multiline_balloon_available();
11192 #endif
11193 #ifdef DYNAMIC_TCL
11194 else if (STRICMP(name, "tcl") == 0)
11195 n = tcl_enabled(FALSE);
11196 #endif
11197 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
11198 else if (STRICMP(name, "iconv") == 0)
11199 n = iconv_enabled(FALSE);
11200 #endif
11201 #ifdef DYNAMIC_MZSCHEME
11202 else if (STRICMP(name, "mzscheme") == 0)
11203 n = mzscheme_enabled(FALSE);
11204 #endif
11205 #ifdef DYNAMIC_RUBY
11206 else if (STRICMP(name, "ruby") == 0)
11207 n = ruby_enabled(FALSE);
11208 #endif
11209 #ifdef DYNAMIC_PYTHON
11210 else if (STRICMP(name, "python") == 0)
11211 n = python_enabled(FALSE);
11212 #endif
11213 #ifdef DYNAMIC_PERL
11214 else if (STRICMP(name, "perl") == 0)
11215 n = perl_enabled(FALSE);
11216 #endif
11217 #ifdef FEAT_GUI
11218 else if (STRICMP(name, "gui_running") == 0)
11219 n = (gui.in_use || gui.starting);
11220 # ifdef FEAT_GUI_W32
11221 else if (STRICMP(name, "gui_win32s") == 0)
11222 n = gui_is_win32s();
11223 # endif
11224 # ifdef FEAT_BROWSE
11225 else if (STRICMP(name, "browse") == 0)
11226 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
11227 # endif
11228 #endif
11229 #ifdef FEAT_SYN_HL
11230 else if (STRICMP(name, "syntax_items") == 0)
11231 n = syntax_present(curbuf);
11232 #endif
11233 #if defined(WIN3264)
11234 else if (STRICMP(name, "win95") == 0)
11235 n = mch_windows95();
11236 #endif
11237 #ifdef FEAT_NETBEANS_INTG
11238 else if (STRICMP(name, "netbeans_enabled") == 0)
11239 n = usingNetbeans;
11240 #endif
11243 rettv->vval.v_number = n;
11247 * "has_key()" function
11249 static void
11250 f_has_key(argvars, rettv)
11251 typval_T *argvars;
11252 typval_T *rettv;
11254 rettv->vval.v_number = 0;
11255 if (argvars[0].v_type != VAR_DICT)
11257 EMSG(_(e_dictreq));
11258 return;
11260 if (argvars[0].vval.v_dict == NULL)
11261 return;
11263 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
11264 get_tv_string(&argvars[1]), -1) != NULL;
11268 * "haslocaldir()" function
11270 /*ARGSUSED*/
11271 static void
11272 f_haslocaldir(argvars, rettv)
11273 typval_T *argvars;
11274 typval_T *rettv;
11276 rettv->vval.v_number = (curwin->w_localdir != NULL);
11280 * "hasmapto()" function
11282 static void
11283 f_hasmapto(argvars, rettv)
11284 typval_T *argvars;
11285 typval_T *rettv;
11287 char_u *name;
11288 char_u *mode;
11289 char_u buf[NUMBUFLEN];
11290 int abbr = FALSE;
11292 name = get_tv_string(&argvars[0]);
11293 if (argvars[1].v_type == VAR_UNKNOWN)
11294 mode = (char_u *)"nvo";
11295 else
11297 mode = get_tv_string_buf(&argvars[1], buf);
11298 if (argvars[2].v_type != VAR_UNKNOWN)
11299 abbr = get_tv_number(&argvars[2]);
11302 if (map_to_exists(name, mode, abbr))
11303 rettv->vval.v_number = TRUE;
11304 else
11305 rettv->vval.v_number = FALSE;
11309 * "histadd()" function
11311 /*ARGSUSED*/
11312 static void
11313 f_histadd(argvars, rettv)
11314 typval_T *argvars;
11315 typval_T *rettv;
11317 #ifdef FEAT_CMDHIST
11318 int histype;
11319 char_u *str;
11320 char_u buf[NUMBUFLEN];
11321 #endif
11323 rettv->vval.v_number = FALSE;
11324 if (check_restricted() || check_secure())
11325 return;
11326 #ifdef FEAT_CMDHIST
11327 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11328 histype = str != NULL ? get_histtype(str) : -1;
11329 if (histype >= 0)
11331 str = get_tv_string_buf(&argvars[1], buf);
11332 if (*str != NUL)
11334 add_to_history(histype, str, FALSE, NUL);
11335 rettv->vval.v_number = TRUE;
11336 return;
11339 #endif
11343 * "histdel()" function
11345 /*ARGSUSED*/
11346 static void
11347 f_histdel(argvars, rettv)
11348 typval_T *argvars;
11349 typval_T *rettv;
11351 #ifdef FEAT_CMDHIST
11352 int n;
11353 char_u buf[NUMBUFLEN];
11354 char_u *str;
11356 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11357 if (str == NULL)
11358 n = 0;
11359 else if (argvars[1].v_type == VAR_UNKNOWN)
11360 /* only one argument: clear entire history */
11361 n = clr_history(get_histtype(str));
11362 else if (argvars[1].v_type == VAR_NUMBER)
11363 /* index given: remove that entry */
11364 n = del_history_idx(get_histtype(str),
11365 (int)get_tv_number(&argvars[1]));
11366 else
11367 /* string given: remove all matching entries */
11368 n = del_history_entry(get_histtype(str),
11369 get_tv_string_buf(&argvars[1], buf));
11370 rettv->vval.v_number = n;
11371 #else
11372 rettv->vval.v_number = 0;
11373 #endif
11377 * "histget()" function
11379 /*ARGSUSED*/
11380 static void
11381 f_histget(argvars, rettv)
11382 typval_T *argvars;
11383 typval_T *rettv;
11385 #ifdef FEAT_CMDHIST
11386 int type;
11387 int idx;
11388 char_u *str;
11390 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11391 if (str == NULL)
11392 rettv->vval.v_string = NULL;
11393 else
11395 type = get_histtype(str);
11396 if (argvars[1].v_type == VAR_UNKNOWN)
11397 idx = get_history_idx(type);
11398 else
11399 idx = (int)get_tv_number_chk(&argvars[1], NULL);
11400 /* -1 on type error */
11401 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
11403 #else
11404 rettv->vval.v_string = NULL;
11405 #endif
11406 rettv->v_type = VAR_STRING;
11410 * "histnr()" function
11412 /*ARGSUSED*/
11413 static void
11414 f_histnr(argvars, rettv)
11415 typval_T *argvars;
11416 typval_T *rettv;
11418 int i;
11420 #ifdef FEAT_CMDHIST
11421 char_u *history = get_tv_string_chk(&argvars[0]);
11423 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
11424 if (i >= HIST_CMD && i < HIST_COUNT)
11425 i = get_history_idx(i);
11426 else
11427 #endif
11428 i = -1;
11429 rettv->vval.v_number = i;
11433 * "highlightID(name)" function
11435 static void
11436 f_hlID(argvars, rettv)
11437 typval_T *argvars;
11438 typval_T *rettv;
11440 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
11444 * "highlight_exists()" function
11446 static void
11447 f_hlexists(argvars, rettv)
11448 typval_T *argvars;
11449 typval_T *rettv;
11451 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
11455 * "hostname()" function
11457 /*ARGSUSED*/
11458 static void
11459 f_hostname(argvars, rettv)
11460 typval_T *argvars;
11461 typval_T *rettv;
11463 char_u hostname[256];
11465 mch_get_host_name(hostname, 256);
11466 rettv->v_type = VAR_STRING;
11467 rettv->vval.v_string = vim_strsave(hostname);
11471 * iconv() function
11473 /*ARGSUSED*/
11474 static void
11475 f_iconv(argvars, rettv)
11476 typval_T *argvars;
11477 typval_T *rettv;
11479 #ifdef FEAT_MBYTE
11480 char_u buf1[NUMBUFLEN];
11481 char_u buf2[NUMBUFLEN];
11482 char_u *from, *to, *str;
11483 vimconv_T vimconv;
11484 #endif
11486 rettv->v_type = VAR_STRING;
11487 rettv->vval.v_string = NULL;
11489 #ifdef FEAT_MBYTE
11490 str = get_tv_string(&argvars[0]);
11491 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
11492 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
11493 vimconv.vc_type = CONV_NONE;
11494 convert_setup(&vimconv, from, to);
11496 /* If the encodings are equal, no conversion needed. */
11497 if (vimconv.vc_type == CONV_NONE)
11498 rettv->vval.v_string = vim_strsave(str);
11499 else
11500 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
11502 convert_setup(&vimconv, NULL, NULL);
11503 vim_free(from);
11504 vim_free(to);
11505 #endif
11509 * "indent()" function
11511 static void
11512 f_indent(argvars, rettv)
11513 typval_T *argvars;
11514 typval_T *rettv;
11516 linenr_T lnum;
11518 lnum = get_tv_lnum(argvars);
11519 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
11520 rettv->vval.v_number = get_indent_lnum(lnum);
11521 else
11522 rettv->vval.v_number = -1;
11526 * "index()" function
11528 static void
11529 f_index(argvars, rettv)
11530 typval_T *argvars;
11531 typval_T *rettv;
11533 list_T *l;
11534 listitem_T *item;
11535 long idx = 0;
11536 int ic = FALSE;
11538 rettv->vval.v_number = -1;
11539 if (argvars[0].v_type != VAR_LIST)
11541 EMSG(_(e_listreq));
11542 return;
11544 l = argvars[0].vval.v_list;
11545 if (l != NULL)
11547 item = l->lv_first;
11548 if (argvars[2].v_type != VAR_UNKNOWN)
11550 int error = FALSE;
11552 /* Start at specified item. Use the cached index that list_find()
11553 * sets, so that a negative number also works. */
11554 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
11555 idx = l->lv_idx;
11556 if (argvars[3].v_type != VAR_UNKNOWN)
11557 ic = get_tv_number_chk(&argvars[3], &error);
11558 if (error)
11559 item = NULL;
11562 for ( ; item != NULL; item = item->li_next, ++idx)
11563 if (tv_equal(&item->li_tv, &argvars[1], ic))
11565 rettv->vval.v_number = idx;
11566 break;
11571 static int inputsecret_flag = 0;
11573 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
11576 * This function is used by f_input() and f_inputdialog() functions. The third
11577 * argument to f_input() specifies the type of completion to use at the
11578 * prompt. The third argument to f_inputdialog() specifies the value to return
11579 * when the user cancels the prompt.
11581 static void
11582 get_user_input(argvars, rettv, inputdialog)
11583 typval_T *argvars;
11584 typval_T *rettv;
11585 int inputdialog;
11587 char_u *prompt = get_tv_string_chk(&argvars[0]);
11588 char_u *p = NULL;
11589 int c;
11590 char_u buf[NUMBUFLEN];
11591 int cmd_silent_save = cmd_silent;
11592 char_u *defstr = (char_u *)"";
11593 int xp_type = EXPAND_NOTHING;
11594 char_u *xp_arg = NULL;
11596 rettv->v_type = VAR_STRING;
11597 rettv->vval.v_string = NULL;
11599 #ifdef NO_CONSOLE_INPUT
11600 /* While starting up, there is no place to enter text. */
11601 if (no_console_input())
11602 return;
11603 #endif
11605 cmd_silent = FALSE; /* Want to see the prompt. */
11606 if (prompt != NULL)
11608 /* Only the part of the message after the last NL is considered as
11609 * prompt for the command line */
11610 p = vim_strrchr(prompt, '\n');
11611 if (p == NULL)
11612 p = prompt;
11613 else
11615 ++p;
11616 c = *p;
11617 *p = NUL;
11618 msg_start();
11619 msg_clr_eos();
11620 msg_puts_attr(prompt, echo_attr);
11621 msg_didout = FALSE;
11622 msg_starthere();
11623 *p = c;
11625 cmdline_row = msg_row;
11627 if (argvars[1].v_type != VAR_UNKNOWN)
11629 defstr = get_tv_string_buf_chk(&argvars[1], buf);
11630 if (defstr != NULL)
11631 stuffReadbuffSpec(defstr);
11633 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
11635 char_u *xp_name;
11636 int xp_namelen;
11637 long argt;
11639 rettv->vval.v_string = NULL;
11641 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
11642 if (xp_name == NULL)
11643 return;
11645 xp_namelen = (int)STRLEN(xp_name);
11647 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
11648 &xp_arg) == FAIL)
11649 return;
11653 if (defstr != NULL)
11654 rettv->vval.v_string =
11655 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
11656 xp_type, xp_arg);
11658 vim_free(xp_arg);
11660 /* since the user typed this, no need to wait for return */
11661 need_wait_return = FALSE;
11662 msg_didout = FALSE;
11664 cmd_silent = cmd_silent_save;
11668 * "input()" function
11669 * Also handles inputsecret() when inputsecret is set.
11671 static void
11672 f_input(argvars, rettv)
11673 typval_T *argvars;
11674 typval_T *rettv;
11676 get_user_input(argvars, rettv, FALSE);
11680 * "inputdialog()" function
11682 static void
11683 f_inputdialog(argvars, rettv)
11684 typval_T *argvars;
11685 typval_T *rettv;
11687 #if defined(FEAT_GUI_TEXTDIALOG)
11688 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
11689 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
11691 char_u *message;
11692 char_u buf[NUMBUFLEN];
11693 char_u *defstr = (char_u *)"";
11695 message = get_tv_string_chk(&argvars[0]);
11696 if (argvars[1].v_type != VAR_UNKNOWN
11697 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
11698 vim_strncpy(IObuff, defstr, IOSIZE - 1);
11699 else
11700 IObuff[0] = NUL;
11701 if (message != NULL && defstr != NULL
11702 && do_dialog(VIM_QUESTION, NULL, message,
11703 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
11704 rettv->vval.v_string = vim_strsave(IObuff);
11705 else
11707 if (message != NULL && defstr != NULL
11708 && argvars[1].v_type != VAR_UNKNOWN
11709 && argvars[2].v_type != VAR_UNKNOWN)
11710 rettv->vval.v_string = vim_strsave(
11711 get_tv_string_buf(&argvars[2], buf));
11712 else
11713 rettv->vval.v_string = NULL;
11715 rettv->v_type = VAR_STRING;
11717 else
11718 #endif
11719 get_user_input(argvars, rettv, TRUE);
11723 * "inputlist()" function
11725 static void
11726 f_inputlist(argvars, rettv)
11727 typval_T *argvars;
11728 typval_T *rettv;
11730 listitem_T *li;
11731 int selected;
11732 int mouse_used;
11734 rettv->vval.v_number = 0;
11735 #ifdef NO_CONSOLE_INPUT
11736 /* While starting up, there is no place to enter text. */
11737 if (no_console_input())
11738 return;
11739 #endif
11740 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
11742 EMSG2(_(e_listarg), "inputlist()");
11743 return;
11746 msg_start();
11747 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
11748 lines_left = Rows; /* avoid more prompt */
11749 msg_scroll = TRUE;
11750 msg_clr_eos();
11752 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
11754 msg_puts(get_tv_string(&li->li_tv));
11755 msg_putchar('\n');
11758 /* Ask for choice. */
11759 selected = prompt_for_number(&mouse_used);
11760 if (mouse_used)
11761 selected -= lines_left;
11763 rettv->vval.v_number = selected;
11767 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
11770 * "inputrestore()" function
11772 /*ARGSUSED*/
11773 static void
11774 f_inputrestore(argvars, rettv)
11775 typval_T *argvars;
11776 typval_T *rettv;
11778 if (ga_userinput.ga_len > 0)
11780 --ga_userinput.ga_len;
11781 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
11782 + ga_userinput.ga_len);
11783 rettv->vval.v_number = 0; /* OK */
11785 else if (p_verbose > 1)
11787 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
11788 rettv->vval.v_number = 1; /* Failed */
11793 * "inputsave()" function
11795 /*ARGSUSED*/
11796 static void
11797 f_inputsave(argvars, rettv)
11798 typval_T *argvars;
11799 typval_T *rettv;
11801 /* Add an entry to the stack of typehead storage. */
11802 if (ga_grow(&ga_userinput, 1) == OK)
11804 save_typeahead((tasave_T *)(ga_userinput.ga_data)
11805 + ga_userinput.ga_len);
11806 ++ga_userinput.ga_len;
11807 rettv->vval.v_number = 0; /* OK */
11809 else
11810 rettv->vval.v_number = 1; /* Failed */
11814 * "inputsecret()" function
11816 static void
11817 f_inputsecret(argvars, rettv)
11818 typval_T *argvars;
11819 typval_T *rettv;
11821 ++cmdline_star;
11822 ++inputsecret_flag;
11823 f_input(argvars, rettv);
11824 --cmdline_star;
11825 --inputsecret_flag;
11829 * "insert()" function
11831 static void
11832 f_insert(argvars, rettv)
11833 typval_T *argvars;
11834 typval_T *rettv;
11836 long before = 0;
11837 listitem_T *item;
11838 list_T *l;
11839 int error = FALSE;
11841 rettv->vval.v_number = 0;
11842 if (argvars[0].v_type != VAR_LIST)
11843 EMSG2(_(e_listarg), "insert()");
11844 else if ((l = argvars[0].vval.v_list) != NULL
11845 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
11847 if (argvars[2].v_type != VAR_UNKNOWN)
11848 before = get_tv_number_chk(&argvars[2], &error);
11849 if (error)
11850 return; /* type error; errmsg already given */
11852 if (before == l->lv_len)
11853 item = NULL;
11854 else
11856 item = list_find(l, before);
11857 if (item == NULL)
11859 EMSGN(_(e_listidx), before);
11860 l = NULL;
11863 if (l != NULL)
11865 list_insert_tv(l, &argvars[1], item);
11866 copy_tv(&argvars[0], rettv);
11872 * "isdirectory()" function
11874 static void
11875 f_isdirectory(argvars, rettv)
11876 typval_T *argvars;
11877 typval_T *rettv;
11879 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
11883 * "islocked()" function
11885 static void
11886 f_islocked(argvars, rettv)
11887 typval_T *argvars;
11888 typval_T *rettv;
11890 lval_T lv;
11891 char_u *end;
11892 dictitem_T *di;
11894 rettv->vval.v_number = -1;
11895 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
11896 FNE_CHECK_START);
11897 if (end != NULL && lv.ll_name != NULL)
11899 if (*end != NUL)
11900 EMSG(_(e_trailing));
11901 else
11903 if (lv.ll_tv == NULL)
11905 if (check_changedtick(lv.ll_name))
11906 rettv->vval.v_number = 1; /* always locked */
11907 else
11909 di = find_var(lv.ll_name, NULL);
11910 if (di != NULL)
11912 /* Consider a variable locked when:
11913 * 1. the variable itself is locked
11914 * 2. the value of the variable is locked.
11915 * 3. the List or Dict value is locked.
11917 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
11918 || tv_islocked(&di->di_tv));
11922 else if (lv.ll_range)
11923 EMSG(_("E786: Range not allowed"));
11924 else if (lv.ll_newkey != NULL)
11925 EMSG2(_(e_dictkey), lv.ll_newkey);
11926 else if (lv.ll_list != NULL)
11927 /* List item. */
11928 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
11929 else
11930 /* Dictionary item. */
11931 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
11935 clear_lval(&lv);
11938 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
11941 * Turn a dict into a list:
11942 * "what" == 0: list of keys
11943 * "what" == 1: list of values
11944 * "what" == 2: list of items
11946 static void
11947 dict_list(argvars, rettv, what)
11948 typval_T *argvars;
11949 typval_T *rettv;
11950 int what;
11952 list_T *l2;
11953 dictitem_T *di;
11954 hashitem_T *hi;
11955 listitem_T *li;
11956 listitem_T *li2;
11957 dict_T *d;
11958 int todo;
11960 rettv->vval.v_number = 0;
11961 if (argvars[0].v_type != VAR_DICT)
11963 EMSG(_(e_dictreq));
11964 return;
11966 if ((d = argvars[0].vval.v_dict) == NULL)
11967 return;
11969 if (rettv_list_alloc(rettv) == FAIL)
11970 return;
11972 todo = (int)d->dv_hashtab.ht_used;
11973 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
11975 if (!HASHITEM_EMPTY(hi))
11977 --todo;
11978 di = HI2DI(hi);
11980 li = listitem_alloc();
11981 if (li == NULL)
11982 break;
11983 list_append(rettv->vval.v_list, li);
11985 if (what == 0)
11987 /* keys() */
11988 li->li_tv.v_type = VAR_STRING;
11989 li->li_tv.v_lock = 0;
11990 li->li_tv.vval.v_string = vim_strsave(di->di_key);
11992 else if (what == 1)
11994 /* values() */
11995 copy_tv(&di->di_tv, &li->li_tv);
11997 else
11999 /* items() */
12000 l2 = list_alloc();
12001 li->li_tv.v_type = VAR_LIST;
12002 li->li_tv.v_lock = 0;
12003 li->li_tv.vval.v_list = l2;
12004 if (l2 == NULL)
12005 break;
12006 ++l2->lv_refcount;
12008 li2 = listitem_alloc();
12009 if (li2 == NULL)
12010 break;
12011 list_append(l2, li2);
12012 li2->li_tv.v_type = VAR_STRING;
12013 li2->li_tv.v_lock = 0;
12014 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12016 li2 = listitem_alloc();
12017 if (li2 == NULL)
12018 break;
12019 list_append(l2, li2);
12020 copy_tv(&di->di_tv, &li2->li_tv);
12027 * "items(dict)" function
12029 static void
12030 f_items(argvars, rettv)
12031 typval_T *argvars;
12032 typval_T *rettv;
12034 dict_list(argvars, rettv, 2);
12038 * "join()" function
12040 static void
12041 f_join(argvars, rettv)
12042 typval_T *argvars;
12043 typval_T *rettv;
12045 garray_T ga;
12046 char_u *sep;
12048 rettv->vval.v_number = 0;
12049 if (argvars[0].v_type != VAR_LIST)
12051 EMSG(_(e_listreq));
12052 return;
12054 if (argvars[0].vval.v_list == NULL)
12055 return;
12056 if (argvars[1].v_type == VAR_UNKNOWN)
12057 sep = (char_u *)" ";
12058 else
12059 sep = get_tv_string_chk(&argvars[1]);
12061 rettv->v_type = VAR_STRING;
12063 if (sep != NULL)
12065 ga_init2(&ga, (int)sizeof(char), 80);
12066 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12067 ga_append(&ga, NUL);
12068 rettv->vval.v_string = (char_u *)ga.ga_data;
12070 else
12071 rettv->vval.v_string = NULL;
12075 * "keys()" function
12077 static void
12078 f_keys(argvars, rettv)
12079 typval_T *argvars;
12080 typval_T *rettv;
12082 dict_list(argvars, rettv, 0);
12086 * "last_buffer_nr()" function.
12088 /*ARGSUSED*/
12089 static void
12090 f_last_buffer_nr(argvars, rettv)
12091 typval_T *argvars;
12092 typval_T *rettv;
12094 int n = 0;
12095 buf_T *buf;
12097 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12098 if (n < buf->b_fnum)
12099 n = buf->b_fnum;
12101 rettv->vval.v_number = n;
12105 * "len()" function
12107 static void
12108 f_len(argvars, rettv)
12109 typval_T *argvars;
12110 typval_T *rettv;
12112 switch (argvars[0].v_type)
12114 case VAR_STRING:
12115 case VAR_NUMBER:
12116 rettv->vval.v_number = (varnumber_T)STRLEN(
12117 get_tv_string(&argvars[0]));
12118 break;
12119 case VAR_LIST:
12120 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
12121 break;
12122 case VAR_DICT:
12123 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
12124 break;
12125 default:
12126 EMSG(_("E701: Invalid type for len()"));
12127 break;
12131 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
12133 static void
12134 libcall_common(argvars, rettv, type)
12135 typval_T *argvars;
12136 typval_T *rettv;
12137 int type;
12139 #ifdef FEAT_LIBCALL
12140 char_u *string_in;
12141 char_u **string_result;
12142 int nr_result;
12143 #endif
12145 rettv->v_type = type;
12146 if (type == VAR_NUMBER)
12147 rettv->vval.v_number = 0;
12148 else
12149 rettv->vval.v_string = NULL;
12151 if (check_restricted() || check_secure())
12152 return;
12154 #ifdef FEAT_LIBCALL
12155 /* The first two args must be strings, otherwise its meaningless */
12156 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
12158 string_in = NULL;
12159 if (argvars[2].v_type == VAR_STRING)
12160 string_in = argvars[2].vval.v_string;
12161 if (type == VAR_NUMBER)
12162 string_result = NULL;
12163 else
12164 string_result = &rettv->vval.v_string;
12165 if (mch_libcall(argvars[0].vval.v_string,
12166 argvars[1].vval.v_string,
12167 string_in,
12168 argvars[2].vval.v_number,
12169 string_result,
12170 &nr_result) == OK
12171 && type == VAR_NUMBER)
12172 rettv->vval.v_number = nr_result;
12174 #endif
12178 * "libcall()" function
12180 static void
12181 f_libcall(argvars, rettv)
12182 typval_T *argvars;
12183 typval_T *rettv;
12185 libcall_common(argvars, rettv, VAR_STRING);
12189 * "libcallnr()" function
12191 static void
12192 f_libcallnr(argvars, rettv)
12193 typval_T *argvars;
12194 typval_T *rettv;
12196 libcall_common(argvars, rettv, VAR_NUMBER);
12200 * "line(string)" function
12202 static void
12203 f_line(argvars, rettv)
12204 typval_T *argvars;
12205 typval_T *rettv;
12207 linenr_T lnum = 0;
12208 pos_T *fp;
12209 int fnum;
12211 fp = var2fpos(&argvars[0], TRUE, &fnum);
12212 if (fp != NULL)
12213 lnum = fp->lnum;
12214 rettv->vval.v_number = lnum;
12218 * "line2byte(lnum)" function
12220 /*ARGSUSED*/
12221 static void
12222 f_line2byte(argvars, rettv)
12223 typval_T *argvars;
12224 typval_T *rettv;
12226 #ifndef FEAT_BYTEOFF
12227 rettv->vval.v_number = -1;
12228 #else
12229 linenr_T lnum;
12231 lnum = get_tv_lnum(argvars);
12232 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
12233 rettv->vval.v_number = -1;
12234 else
12235 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
12236 if (rettv->vval.v_number >= 0)
12237 ++rettv->vval.v_number;
12238 #endif
12242 * "lispindent(lnum)" function
12244 static void
12245 f_lispindent(argvars, rettv)
12246 typval_T *argvars;
12247 typval_T *rettv;
12249 #ifdef FEAT_LISP
12250 pos_T pos;
12251 linenr_T lnum;
12253 pos = curwin->w_cursor;
12254 lnum = get_tv_lnum(argvars);
12255 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12257 curwin->w_cursor.lnum = lnum;
12258 rettv->vval.v_number = get_lisp_indent();
12259 curwin->w_cursor = pos;
12261 else
12262 #endif
12263 rettv->vval.v_number = -1;
12267 * "localtime()" function
12269 /*ARGSUSED*/
12270 static void
12271 f_localtime(argvars, rettv)
12272 typval_T *argvars;
12273 typval_T *rettv;
12275 rettv->vval.v_number = (varnumber_T)time(NULL);
12278 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
12280 static void
12281 get_maparg(argvars, rettv, exact)
12282 typval_T *argvars;
12283 typval_T *rettv;
12284 int exact;
12286 char_u *keys;
12287 char_u *which;
12288 char_u buf[NUMBUFLEN];
12289 char_u *keys_buf = NULL;
12290 char_u *rhs;
12291 int mode;
12292 garray_T ga;
12293 int abbr = FALSE;
12295 /* return empty string for failure */
12296 rettv->v_type = VAR_STRING;
12297 rettv->vval.v_string = NULL;
12299 keys = get_tv_string(&argvars[0]);
12300 if (*keys == NUL)
12301 return;
12303 if (argvars[1].v_type != VAR_UNKNOWN)
12305 which = get_tv_string_buf_chk(&argvars[1], buf);
12306 if (argvars[2].v_type != VAR_UNKNOWN)
12307 abbr = get_tv_number(&argvars[2]);
12309 else
12310 which = (char_u *)"";
12311 if (which == NULL)
12312 return;
12314 mode = get_map_mode(&which, 0);
12316 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
12317 rhs = check_map(keys, mode, exact, FALSE, abbr);
12318 vim_free(keys_buf);
12319 if (rhs != NULL)
12321 ga_init(&ga);
12322 ga.ga_itemsize = 1;
12323 ga.ga_growsize = 40;
12325 while (*rhs != NUL)
12326 ga_concat(&ga, str2special(&rhs, FALSE));
12328 ga_append(&ga, NUL);
12329 rettv->vval.v_string = (char_u *)ga.ga_data;
12334 * "map()" function
12336 static void
12337 f_map(argvars, rettv)
12338 typval_T *argvars;
12339 typval_T *rettv;
12341 filter_map(argvars, rettv, TRUE);
12345 * "maparg()" function
12347 static void
12348 f_maparg(argvars, rettv)
12349 typval_T *argvars;
12350 typval_T *rettv;
12352 get_maparg(argvars, rettv, TRUE);
12356 * "mapcheck()" function
12358 static void
12359 f_mapcheck(argvars, rettv)
12360 typval_T *argvars;
12361 typval_T *rettv;
12363 get_maparg(argvars, rettv, FALSE);
12366 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
12368 static void
12369 find_some_match(argvars, rettv, type)
12370 typval_T *argvars;
12371 typval_T *rettv;
12372 int type;
12374 char_u *str = NULL;
12375 char_u *expr = NULL;
12376 char_u *pat;
12377 regmatch_T regmatch;
12378 char_u patbuf[NUMBUFLEN];
12379 char_u strbuf[NUMBUFLEN];
12380 char_u *save_cpo;
12381 long start = 0;
12382 long nth = 1;
12383 colnr_T startcol = 0;
12384 int match = 0;
12385 list_T *l = NULL;
12386 listitem_T *li = NULL;
12387 long idx = 0;
12388 char_u *tofree = NULL;
12390 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
12391 save_cpo = p_cpo;
12392 p_cpo = (char_u *)"";
12394 rettv->vval.v_number = -1;
12395 if (type == 3)
12397 /* return empty list when there are no matches */
12398 if (rettv_list_alloc(rettv) == FAIL)
12399 goto theend;
12401 else if (type == 2)
12403 rettv->v_type = VAR_STRING;
12404 rettv->vval.v_string = NULL;
12407 if (argvars[0].v_type == VAR_LIST)
12409 if ((l = argvars[0].vval.v_list) == NULL)
12410 goto theend;
12411 li = l->lv_first;
12413 else
12414 expr = str = get_tv_string(&argvars[0]);
12416 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
12417 if (pat == NULL)
12418 goto theend;
12420 if (argvars[2].v_type != VAR_UNKNOWN)
12422 int error = FALSE;
12424 start = get_tv_number_chk(&argvars[2], &error);
12425 if (error)
12426 goto theend;
12427 if (l != NULL)
12429 li = list_find(l, start);
12430 if (li == NULL)
12431 goto theend;
12432 idx = l->lv_idx; /* use the cached index */
12434 else
12436 if (start < 0)
12437 start = 0;
12438 if (start > (long)STRLEN(str))
12439 goto theend;
12440 /* When "count" argument is there ignore matches before "start",
12441 * otherwise skip part of the string. Differs when pattern is "^"
12442 * or "\<". */
12443 if (argvars[3].v_type != VAR_UNKNOWN)
12444 startcol = start;
12445 else
12446 str += start;
12449 if (argvars[3].v_type != VAR_UNKNOWN)
12450 nth = get_tv_number_chk(&argvars[3], &error);
12451 if (error)
12452 goto theend;
12455 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
12456 if (regmatch.regprog != NULL)
12458 regmatch.rm_ic = p_ic;
12460 for (;;)
12462 if (l != NULL)
12464 if (li == NULL)
12466 match = FALSE;
12467 break;
12469 vim_free(tofree);
12470 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
12471 if (str == NULL)
12472 break;
12475 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
12477 if (match && --nth <= 0)
12478 break;
12479 if (l == NULL && !match)
12480 break;
12482 /* Advance to just after the match. */
12483 if (l != NULL)
12485 li = li->li_next;
12486 ++idx;
12488 else
12490 #ifdef FEAT_MBYTE
12491 startcol = (colnr_T)(regmatch.startp[0]
12492 + (*mb_ptr2len)(regmatch.startp[0]) - str);
12493 #else
12494 startcol = regmatch.startp[0] + 1 - str;
12495 #endif
12499 if (match)
12501 if (type == 3)
12503 int i;
12505 /* return list with matched string and submatches */
12506 for (i = 0; i < NSUBEXP; ++i)
12508 if (regmatch.endp[i] == NULL)
12510 if (list_append_string(rettv->vval.v_list,
12511 (char_u *)"", 0) == FAIL)
12512 break;
12514 else if (list_append_string(rettv->vval.v_list,
12515 regmatch.startp[i],
12516 (int)(regmatch.endp[i] - regmatch.startp[i]))
12517 == FAIL)
12518 break;
12521 else if (type == 2)
12523 /* return matched string */
12524 if (l != NULL)
12525 copy_tv(&li->li_tv, rettv);
12526 else
12527 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
12528 (int)(regmatch.endp[0] - regmatch.startp[0]));
12530 else if (l != NULL)
12531 rettv->vval.v_number = idx;
12532 else
12534 if (type != 0)
12535 rettv->vval.v_number =
12536 (varnumber_T)(regmatch.startp[0] - str);
12537 else
12538 rettv->vval.v_number =
12539 (varnumber_T)(regmatch.endp[0] - str);
12540 rettv->vval.v_number += (varnumber_T)(str - expr);
12543 vim_free(regmatch.regprog);
12546 theend:
12547 vim_free(tofree);
12548 p_cpo = save_cpo;
12552 * "match()" function
12554 static void
12555 f_match(argvars, rettv)
12556 typval_T *argvars;
12557 typval_T *rettv;
12559 find_some_match(argvars, rettv, 1);
12563 * "matchadd()" function
12565 static void
12566 f_matchadd(argvars, rettv)
12567 typval_T *argvars;
12568 typval_T *rettv;
12570 #ifdef FEAT_SEARCH_EXTRA
12571 char_u buf[NUMBUFLEN];
12572 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
12573 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
12574 int prio = 10; /* default priority */
12575 int id = -1;
12576 int error = FALSE;
12578 rettv->vval.v_number = -1;
12580 if (grp == NULL || pat == NULL)
12581 return;
12582 if (argvars[2].v_type != VAR_UNKNOWN)
12584 prio = get_tv_number_chk(&argvars[2], &error);
12585 if (argvars[3].v_type != VAR_UNKNOWN)
12586 id = get_tv_number_chk(&argvars[3], &error);
12588 if (error == TRUE)
12589 return;
12590 if (id >= 1 && id <= 3)
12592 EMSGN("E798: ID is reserved for \":match\": %ld", id);
12593 return;
12596 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
12597 #endif
12601 * "matcharg()" function
12603 static void
12604 f_matcharg(argvars, rettv)
12605 typval_T *argvars;
12606 typval_T *rettv;
12608 if (rettv_list_alloc(rettv) == OK)
12610 #ifdef FEAT_SEARCH_EXTRA
12611 int id = get_tv_number(&argvars[0]);
12612 matchitem_T *m;
12614 if (id >= 1 && id <= 3)
12616 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
12618 list_append_string(rettv->vval.v_list,
12619 syn_id2name(m->hlg_id), -1);
12620 list_append_string(rettv->vval.v_list, m->pattern, -1);
12622 else
12624 list_append_string(rettv->vval.v_list, NUL, -1);
12625 list_append_string(rettv->vval.v_list, NUL, -1);
12628 #endif
12633 * "matchdelete()" function
12635 static void
12636 f_matchdelete(argvars, rettv)
12637 typval_T *argvars;
12638 typval_T *rettv;
12640 #ifdef FEAT_SEARCH_EXTRA
12641 rettv->vval.v_number = match_delete(curwin,
12642 (int)get_tv_number(&argvars[0]), TRUE);
12643 #endif
12647 * "matchend()" function
12649 static void
12650 f_matchend(argvars, rettv)
12651 typval_T *argvars;
12652 typval_T *rettv;
12654 find_some_match(argvars, rettv, 0);
12658 * "matchlist()" function
12660 static void
12661 f_matchlist(argvars, rettv)
12662 typval_T *argvars;
12663 typval_T *rettv;
12665 find_some_match(argvars, rettv, 3);
12669 * "matchstr()" function
12671 static void
12672 f_matchstr(argvars, rettv)
12673 typval_T *argvars;
12674 typval_T *rettv;
12676 find_some_match(argvars, rettv, 2);
12679 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
12681 static void
12682 max_min(argvars, rettv, domax)
12683 typval_T *argvars;
12684 typval_T *rettv;
12685 int domax;
12687 long n = 0;
12688 long i;
12689 int error = FALSE;
12691 if (argvars[0].v_type == VAR_LIST)
12693 list_T *l;
12694 listitem_T *li;
12696 l = argvars[0].vval.v_list;
12697 if (l != NULL)
12699 li = l->lv_first;
12700 if (li != NULL)
12702 n = get_tv_number_chk(&li->li_tv, &error);
12703 for (;;)
12705 li = li->li_next;
12706 if (li == NULL)
12707 break;
12708 i = get_tv_number_chk(&li->li_tv, &error);
12709 if (domax ? i > n : i < n)
12710 n = i;
12715 else if (argvars[0].v_type == VAR_DICT)
12717 dict_T *d;
12718 int first = TRUE;
12719 hashitem_T *hi;
12720 int todo;
12722 d = argvars[0].vval.v_dict;
12723 if (d != NULL)
12725 todo = (int)d->dv_hashtab.ht_used;
12726 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12728 if (!HASHITEM_EMPTY(hi))
12730 --todo;
12731 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
12732 if (first)
12734 n = i;
12735 first = FALSE;
12737 else if (domax ? i > n : i < n)
12738 n = i;
12743 else
12744 EMSG(_(e_listdictarg));
12745 rettv->vval.v_number = error ? 0 : n;
12749 * "max()" function
12751 static void
12752 f_max(argvars, rettv)
12753 typval_T *argvars;
12754 typval_T *rettv;
12756 max_min(argvars, rettv, TRUE);
12760 * "min()" function
12762 static void
12763 f_min(argvars, rettv)
12764 typval_T *argvars;
12765 typval_T *rettv;
12767 max_min(argvars, rettv, FALSE);
12770 static int mkdir_recurse __ARGS((char_u *dir, int prot));
12773 * Create the directory in which "dir" is located, and higher levels when
12774 * needed.
12776 static int
12777 mkdir_recurse(dir, prot)
12778 char_u *dir;
12779 int prot;
12781 char_u *p;
12782 char_u *updir;
12783 int r = FAIL;
12785 /* Get end of directory name in "dir".
12786 * We're done when it's "/" or "c:/". */
12787 p = gettail_sep(dir);
12788 if (p <= get_past_head(dir))
12789 return OK;
12791 /* If the directory exists we're done. Otherwise: create it.*/
12792 updir = vim_strnsave(dir, (int)(p - dir));
12793 if (updir == NULL)
12794 return FAIL;
12795 if (mch_isdir(updir))
12796 r = OK;
12797 else if (mkdir_recurse(updir, prot) == OK)
12798 r = vim_mkdir_emsg(updir, prot);
12799 vim_free(updir);
12800 return r;
12803 #ifdef vim_mkdir
12805 * "mkdir()" function
12807 static void
12808 f_mkdir(argvars, rettv)
12809 typval_T *argvars;
12810 typval_T *rettv;
12812 char_u *dir;
12813 char_u buf[NUMBUFLEN];
12814 int prot = 0755;
12816 rettv->vval.v_number = FAIL;
12817 if (check_restricted() || check_secure())
12818 return;
12820 dir = get_tv_string_buf(&argvars[0], buf);
12821 if (argvars[1].v_type != VAR_UNKNOWN)
12823 if (argvars[2].v_type != VAR_UNKNOWN)
12824 prot = get_tv_number_chk(&argvars[2], NULL);
12825 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
12826 mkdir_recurse(dir, prot);
12828 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
12830 #endif
12833 * "mode()" function
12835 /*ARGSUSED*/
12836 static void
12837 f_mode(argvars, rettv)
12838 typval_T *argvars;
12839 typval_T *rettv;
12841 char_u buf[2];
12843 #ifdef FEAT_VISUAL
12844 if (VIsual_active)
12846 if (VIsual_select)
12847 buf[0] = VIsual_mode + 's' - 'v';
12848 else
12849 buf[0] = VIsual_mode;
12851 else
12852 #endif
12853 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE)
12854 buf[0] = 'r';
12855 else if (State & INSERT)
12857 if (State & REPLACE_FLAG)
12858 buf[0] = 'R';
12859 else
12860 buf[0] = 'i';
12862 else if (State & CMDLINE)
12863 buf[0] = 'c';
12864 else
12865 buf[0] = 'n';
12867 buf[1] = NUL;
12868 rettv->vval.v_string = vim_strsave(buf);
12869 rettv->v_type = VAR_STRING;
12873 * "nextnonblank()" function
12875 static void
12876 f_nextnonblank(argvars, rettv)
12877 typval_T *argvars;
12878 typval_T *rettv;
12880 linenr_T lnum;
12882 for (lnum = get_tv_lnum(argvars); ; ++lnum)
12884 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
12886 lnum = 0;
12887 break;
12889 if (*skipwhite(ml_get(lnum)) != NUL)
12890 break;
12892 rettv->vval.v_number = lnum;
12896 * "nr2char()" function
12898 static void
12899 f_nr2char(argvars, rettv)
12900 typval_T *argvars;
12901 typval_T *rettv;
12903 char_u buf[NUMBUFLEN];
12905 #ifdef FEAT_MBYTE
12906 if (has_mbyte)
12907 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
12908 else
12909 #endif
12911 buf[0] = (char_u)get_tv_number(&argvars[0]);
12912 buf[1] = NUL;
12914 rettv->v_type = VAR_STRING;
12915 rettv->vval.v_string = vim_strsave(buf);
12919 * "pathshorten()" function
12921 static void
12922 f_pathshorten(argvars, rettv)
12923 typval_T *argvars;
12924 typval_T *rettv;
12926 char_u *p;
12928 rettv->v_type = VAR_STRING;
12929 p = get_tv_string_chk(&argvars[0]);
12930 if (p == NULL)
12931 rettv->vval.v_string = NULL;
12932 else
12934 p = vim_strsave(p);
12935 rettv->vval.v_string = p;
12936 if (p != NULL)
12937 shorten_dir(p);
12942 * "prevnonblank()" function
12944 static void
12945 f_prevnonblank(argvars, rettv)
12946 typval_T *argvars;
12947 typval_T *rettv;
12949 linenr_T lnum;
12951 lnum = get_tv_lnum(argvars);
12952 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
12953 lnum = 0;
12954 else
12955 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
12956 --lnum;
12957 rettv->vval.v_number = lnum;
12960 #ifdef HAVE_STDARG_H
12961 /* This dummy va_list is here because:
12962 * - passing a NULL pointer doesn't work when va_list isn't a pointer
12963 * - locally in the function results in a "used before set" warning
12964 * - using va_start() to initialize it gives "function with fixed args" error */
12965 static va_list ap;
12966 #endif
12969 * "printf()" function
12971 static void
12972 f_printf(argvars, rettv)
12973 typval_T *argvars;
12974 typval_T *rettv;
12976 rettv->v_type = VAR_STRING;
12977 rettv->vval.v_string = NULL;
12978 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
12980 char_u buf[NUMBUFLEN];
12981 int len;
12982 char_u *s;
12983 int saved_did_emsg = did_emsg;
12984 char *fmt;
12986 /* Get the required length, allocate the buffer and do it for real. */
12987 did_emsg = FALSE;
12988 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
12989 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
12990 if (!did_emsg)
12992 s = alloc(len + 1);
12993 if (s != NULL)
12995 rettv->vval.v_string = s;
12996 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
12999 did_emsg |= saved_did_emsg;
13001 #endif
13005 * "pumvisible()" function
13007 /*ARGSUSED*/
13008 static void
13009 f_pumvisible(argvars, rettv)
13010 typval_T *argvars;
13011 typval_T *rettv;
13013 rettv->vval.v_number = 0;
13014 #ifdef FEAT_INS_EXPAND
13015 if (pum_visible())
13016 rettv->vval.v_number = 1;
13017 #endif
13021 * "range()" function
13023 static void
13024 f_range(argvars, rettv)
13025 typval_T *argvars;
13026 typval_T *rettv;
13028 long start;
13029 long end;
13030 long stride = 1;
13031 long i;
13032 int error = FALSE;
13034 start = get_tv_number_chk(&argvars[0], &error);
13035 if (argvars[1].v_type == VAR_UNKNOWN)
13037 end = start - 1;
13038 start = 0;
13040 else
13042 end = get_tv_number_chk(&argvars[1], &error);
13043 if (argvars[2].v_type != VAR_UNKNOWN)
13044 stride = get_tv_number_chk(&argvars[2], &error);
13047 rettv->vval.v_number = 0;
13048 if (error)
13049 return; /* type error; errmsg already given */
13050 if (stride == 0)
13051 EMSG(_("E726: Stride is zero"));
13052 else if (stride > 0 ? end + 1 < start : end - 1 > start)
13053 EMSG(_("E727: Start past end"));
13054 else
13056 if (rettv_list_alloc(rettv) == OK)
13057 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
13058 if (list_append_number(rettv->vval.v_list,
13059 (varnumber_T)i) == FAIL)
13060 break;
13065 * "readfile()" function
13067 static void
13068 f_readfile(argvars, rettv)
13069 typval_T *argvars;
13070 typval_T *rettv;
13072 int binary = FALSE;
13073 char_u *fname;
13074 FILE *fd;
13075 listitem_T *li;
13076 #define FREAD_SIZE 200 /* optimized for text lines */
13077 char_u buf[FREAD_SIZE];
13078 int readlen; /* size of last fread() */
13079 int buflen; /* nr of valid chars in buf[] */
13080 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
13081 int tolist; /* first byte in buf[] still to be put in list */
13082 int chop; /* how many CR to chop off */
13083 char_u *prev = NULL; /* previously read bytes, if any */
13084 int prevlen = 0; /* length of "prev" if not NULL */
13085 char_u *s;
13086 int len;
13087 long maxline = MAXLNUM;
13088 long cnt = 0;
13090 if (argvars[1].v_type != VAR_UNKNOWN)
13092 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
13093 binary = TRUE;
13094 if (argvars[2].v_type != VAR_UNKNOWN)
13095 maxline = get_tv_number(&argvars[2]);
13098 if (rettv_list_alloc(rettv) == FAIL)
13099 return;
13101 /* Always open the file in binary mode, library functions have a mind of
13102 * their own about CR-LF conversion. */
13103 fname = get_tv_string(&argvars[0]);
13104 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
13106 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
13107 return;
13110 filtd = 0;
13111 while (cnt < maxline || maxline < 0)
13113 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
13114 buflen = filtd + readlen;
13115 tolist = 0;
13116 for ( ; filtd < buflen || readlen <= 0; ++filtd)
13118 if (buf[filtd] == '\n' || readlen <= 0)
13120 /* Only when in binary mode add an empty list item when the
13121 * last line ends in a '\n'. */
13122 if (!binary && readlen == 0 && filtd == 0)
13123 break;
13125 /* Found end-of-line or end-of-file: add a text line to the
13126 * list. */
13127 chop = 0;
13128 if (!binary)
13129 while (filtd - chop - 1 >= tolist
13130 && buf[filtd - chop - 1] == '\r')
13131 ++chop;
13132 len = filtd - tolist - chop;
13133 if (prev == NULL)
13134 s = vim_strnsave(buf + tolist, len);
13135 else
13137 s = alloc((unsigned)(prevlen + len + 1));
13138 if (s != NULL)
13140 mch_memmove(s, prev, prevlen);
13141 vim_free(prev);
13142 prev = NULL;
13143 mch_memmove(s + prevlen, buf + tolist, len);
13144 s[prevlen + len] = NUL;
13147 tolist = filtd + 1;
13149 li = listitem_alloc();
13150 if (li == NULL)
13152 vim_free(s);
13153 break;
13155 li->li_tv.v_type = VAR_STRING;
13156 li->li_tv.v_lock = 0;
13157 li->li_tv.vval.v_string = s;
13158 list_append(rettv->vval.v_list, li);
13160 if (++cnt >= maxline && maxline >= 0)
13161 break;
13162 if (readlen <= 0)
13163 break;
13165 else if (buf[filtd] == NUL)
13166 buf[filtd] = '\n';
13168 if (readlen <= 0)
13169 break;
13171 if (tolist == 0)
13173 /* "buf" is full, need to move text to an allocated buffer */
13174 if (prev == NULL)
13176 prev = vim_strnsave(buf, buflen);
13177 prevlen = buflen;
13179 else
13181 s = alloc((unsigned)(prevlen + buflen));
13182 if (s != NULL)
13184 mch_memmove(s, prev, prevlen);
13185 mch_memmove(s + prevlen, buf, buflen);
13186 vim_free(prev);
13187 prev = s;
13188 prevlen += buflen;
13191 filtd = 0;
13193 else
13195 mch_memmove(buf, buf + tolist, buflen - tolist);
13196 filtd -= tolist;
13201 * For a negative line count use only the lines at the end of the file,
13202 * free the rest.
13204 if (maxline < 0)
13205 while (cnt > -maxline)
13207 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
13208 --cnt;
13211 vim_free(prev);
13212 fclose(fd);
13215 #if defined(FEAT_RELTIME)
13216 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
13219 * Convert a List to proftime_T.
13220 * Return FAIL when there is something wrong.
13222 static int
13223 list2proftime(arg, tm)
13224 typval_T *arg;
13225 proftime_T *tm;
13227 long n1, n2;
13228 int error = FALSE;
13230 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
13231 || arg->vval.v_list->lv_len != 2)
13232 return FAIL;
13233 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
13234 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
13235 # ifdef WIN3264
13236 tm->HighPart = n1;
13237 tm->LowPart = n2;
13238 # else
13239 tm->tv_sec = n1;
13240 tm->tv_usec = n2;
13241 # endif
13242 return error ? FAIL : OK;
13244 #endif /* FEAT_RELTIME */
13247 * "reltime()" function
13249 static void
13250 f_reltime(argvars, rettv)
13251 typval_T *argvars;
13252 typval_T *rettv;
13254 #ifdef FEAT_RELTIME
13255 proftime_T res;
13256 proftime_T start;
13258 if (argvars[0].v_type == VAR_UNKNOWN)
13260 /* No arguments: get current time. */
13261 profile_start(&res);
13263 else if (argvars[1].v_type == VAR_UNKNOWN)
13265 if (list2proftime(&argvars[0], &res) == FAIL)
13266 return;
13267 profile_end(&res);
13269 else
13271 /* Two arguments: compute the difference. */
13272 if (list2proftime(&argvars[0], &start) == FAIL
13273 || list2proftime(&argvars[1], &res) == FAIL)
13274 return;
13275 profile_sub(&res, &start);
13278 if (rettv_list_alloc(rettv) == OK)
13280 long n1, n2;
13282 # ifdef WIN3264
13283 n1 = res.HighPart;
13284 n2 = res.LowPart;
13285 # else
13286 n1 = res.tv_sec;
13287 n2 = res.tv_usec;
13288 # endif
13289 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
13290 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
13292 #endif
13296 * "reltimestr()" function
13298 static void
13299 f_reltimestr(argvars, rettv)
13300 typval_T *argvars;
13301 typval_T *rettv;
13303 #ifdef FEAT_RELTIME
13304 proftime_T tm;
13305 #endif
13307 rettv->v_type = VAR_STRING;
13308 rettv->vval.v_string = NULL;
13309 #ifdef FEAT_RELTIME
13310 if (list2proftime(&argvars[0], &tm) == OK)
13311 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
13312 #endif
13315 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
13316 static void make_connection __ARGS((void));
13317 static int check_connection __ARGS((void));
13319 static void
13320 make_connection()
13322 if (X_DISPLAY == NULL
13323 # ifdef FEAT_GUI
13324 && !gui.in_use
13325 # endif
13328 x_force_connect = TRUE;
13329 setup_term_clip();
13330 x_force_connect = FALSE;
13334 static int
13335 check_connection()
13337 make_connection();
13338 if (X_DISPLAY == NULL)
13340 EMSG(_("E240: No connection to Vim server"));
13341 return FAIL;
13343 return OK;
13345 #endif
13347 #ifdef FEAT_CLIENTSERVER
13348 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
13350 static void
13351 remote_common(argvars, rettv, expr)
13352 typval_T *argvars;
13353 typval_T *rettv;
13354 int expr;
13356 char_u *server_name;
13357 char_u *keys;
13358 char_u *r = NULL;
13359 char_u buf[NUMBUFLEN];
13360 # ifdef WIN32
13361 HWND w;
13362 # else
13363 Window w;
13364 # endif
13366 if (check_restricted() || check_secure())
13367 return;
13369 # ifdef FEAT_X11
13370 if (check_connection() == FAIL)
13371 return;
13372 # endif
13374 server_name = get_tv_string_chk(&argvars[0]);
13375 if (server_name == NULL)
13376 return; /* type error; errmsg already given */
13377 keys = get_tv_string_buf(&argvars[1], buf);
13378 # ifdef WIN32
13379 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
13380 # else
13381 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
13382 < 0)
13383 # endif
13385 if (r != NULL)
13386 EMSG(r); /* sending worked but evaluation failed */
13387 else
13388 EMSG2(_("E241: Unable to send to %s"), server_name);
13389 return;
13392 rettv->vval.v_string = r;
13394 if (argvars[2].v_type != VAR_UNKNOWN)
13396 dictitem_T v;
13397 char_u str[30];
13398 char_u *idvar;
13400 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
13401 v.di_tv.v_type = VAR_STRING;
13402 v.di_tv.vval.v_string = vim_strsave(str);
13403 idvar = get_tv_string_chk(&argvars[2]);
13404 if (idvar != NULL)
13405 set_var(idvar, &v.di_tv, FALSE);
13406 vim_free(v.di_tv.vval.v_string);
13409 #endif
13412 * "remote_expr()" function
13414 /*ARGSUSED*/
13415 static void
13416 f_remote_expr(argvars, rettv)
13417 typval_T *argvars;
13418 typval_T *rettv;
13420 rettv->v_type = VAR_STRING;
13421 rettv->vval.v_string = NULL;
13422 #ifdef FEAT_CLIENTSERVER
13423 remote_common(argvars, rettv, TRUE);
13424 #endif
13428 * "remote_foreground()" function
13430 /*ARGSUSED*/
13431 static void
13432 f_remote_foreground(argvars, rettv)
13433 typval_T *argvars;
13434 typval_T *rettv;
13436 rettv->vval.v_number = 0;
13437 #ifdef FEAT_CLIENTSERVER
13438 # ifdef WIN32
13439 /* On Win32 it's done in this application. */
13441 char_u *server_name = get_tv_string_chk(&argvars[0]);
13443 if (server_name != NULL)
13444 serverForeground(server_name);
13446 # else
13447 /* Send a foreground() expression to the server. */
13448 argvars[1].v_type = VAR_STRING;
13449 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
13450 argvars[2].v_type = VAR_UNKNOWN;
13451 remote_common(argvars, rettv, TRUE);
13452 vim_free(argvars[1].vval.v_string);
13453 # endif
13454 #endif
13457 /*ARGSUSED*/
13458 static void
13459 f_remote_peek(argvars, rettv)
13460 typval_T *argvars;
13461 typval_T *rettv;
13463 #ifdef FEAT_CLIENTSERVER
13464 dictitem_T v;
13465 char_u *s = NULL;
13466 # ifdef WIN32
13467 long_u n = 0;
13468 # endif
13469 char_u *serverid;
13471 if (check_restricted() || check_secure())
13473 rettv->vval.v_number = -1;
13474 return;
13476 serverid = get_tv_string_chk(&argvars[0]);
13477 if (serverid == NULL)
13479 rettv->vval.v_number = -1;
13480 return; /* type error; errmsg already given */
13482 # ifdef WIN32
13483 sscanf(serverid, SCANF_HEX_LONG_U, &n);
13484 if (n == 0)
13485 rettv->vval.v_number = -1;
13486 else
13488 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
13489 rettv->vval.v_number = (s != NULL);
13491 # else
13492 rettv->vval.v_number = 0;
13493 if (check_connection() == FAIL)
13494 return;
13496 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
13497 serverStrToWin(serverid), &s);
13498 # endif
13500 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
13502 char_u *retvar;
13504 v.di_tv.v_type = VAR_STRING;
13505 v.di_tv.vval.v_string = vim_strsave(s);
13506 retvar = get_tv_string_chk(&argvars[1]);
13507 if (retvar != NULL)
13508 set_var(retvar, &v.di_tv, FALSE);
13509 vim_free(v.di_tv.vval.v_string);
13511 #else
13512 rettv->vval.v_number = -1;
13513 #endif
13516 /*ARGSUSED*/
13517 static void
13518 f_remote_read(argvars, rettv)
13519 typval_T *argvars;
13520 typval_T *rettv;
13522 char_u *r = NULL;
13524 #ifdef FEAT_CLIENTSERVER
13525 char_u *serverid = get_tv_string_chk(&argvars[0]);
13527 if (serverid != NULL && !check_restricted() && !check_secure())
13529 # ifdef WIN32
13530 /* The server's HWND is encoded in the 'id' parameter */
13531 long_u n = 0;
13533 sscanf(serverid, SCANF_HEX_LONG_U, &n);
13534 if (n != 0)
13535 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
13536 if (r == NULL)
13537 # else
13538 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
13539 serverStrToWin(serverid), &r, FALSE) < 0)
13540 # endif
13541 EMSG(_("E277: Unable to read a server reply"));
13543 #endif
13544 rettv->v_type = VAR_STRING;
13545 rettv->vval.v_string = r;
13549 * "remote_send()" function
13551 /*ARGSUSED*/
13552 static void
13553 f_remote_send(argvars, rettv)
13554 typval_T *argvars;
13555 typval_T *rettv;
13557 rettv->v_type = VAR_STRING;
13558 rettv->vval.v_string = NULL;
13559 #ifdef FEAT_CLIENTSERVER
13560 remote_common(argvars, rettv, FALSE);
13561 #endif
13565 * "remove()" function
13567 static void
13568 f_remove(argvars, rettv)
13569 typval_T *argvars;
13570 typval_T *rettv;
13572 list_T *l;
13573 listitem_T *item, *item2;
13574 listitem_T *li;
13575 long idx;
13576 long end;
13577 char_u *key;
13578 dict_T *d;
13579 dictitem_T *di;
13581 rettv->vval.v_number = 0;
13582 if (argvars[0].v_type == VAR_DICT)
13584 if (argvars[2].v_type != VAR_UNKNOWN)
13585 EMSG2(_(e_toomanyarg), "remove()");
13586 else if ((d = argvars[0].vval.v_dict) != NULL
13587 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
13589 key = get_tv_string_chk(&argvars[1]);
13590 if (key != NULL)
13592 di = dict_find(d, key, -1);
13593 if (di == NULL)
13594 EMSG2(_(e_dictkey), key);
13595 else
13597 *rettv = di->di_tv;
13598 init_tv(&di->di_tv);
13599 dictitem_remove(d, di);
13604 else if (argvars[0].v_type != VAR_LIST)
13605 EMSG2(_(e_listdictarg), "remove()");
13606 else if ((l = argvars[0].vval.v_list) != NULL
13607 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
13609 int error = FALSE;
13611 idx = get_tv_number_chk(&argvars[1], &error);
13612 if (error)
13613 ; /* type error: do nothing, errmsg already given */
13614 else if ((item = list_find(l, idx)) == NULL)
13615 EMSGN(_(e_listidx), idx);
13616 else
13618 if (argvars[2].v_type == VAR_UNKNOWN)
13620 /* Remove one item, return its value. */
13621 list_remove(l, item, item);
13622 *rettv = item->li_tv;
13623 vim_free(item);
13625 else
13627 /* Remove range of items, return list with values. */
13628 end = get_tv_number_chk(&argvars[2], &error);
13629 if (error)
13630 ; /* type error: do nothing */
13631 else if ((item2 = list_find(l, end)) == NULL)
13632 EMSGN(_(e_listidx), end);
13633 else
13635 int cnt = 0;
13637 for (li = item; li != NULL; li = li->li_next)
13639 ++cnt;
13640 if (li == item2)
13641 break;
13643 if (li == NULL) /* didn't find "item2" after "item" */
13644 EMSG(_(e_invrange));
13645 else
13647 list_remove(l, item, item2);
13648 if (rettv_list_alloc(rettv) == OK)
13650 l = rettv->vval.v_list;
13651 l->lv_first = item;
13652 l->lv_last = item2;
13653 item->li_prev = NULL;
13654 item2->li_next = NULL;
13655 l->lv_len = cnt;
13665 * "rename({from}, {to})" function
13667 static void
13668 f_rename(argvars, rettv)
13669 typval_T *argvars;
13670 typval_T *rettv;
13672 char_u buf[NUMBUFLEN];
13674 if (check_restricted() || check_secure())
13675 rettv->vval.v_number = -1;
13676 else
13677 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
13678 get_tv_string_buf(&argvars[1], buf));
13682 * "repeat()" function
13684 /*ARGSUSED*/
13685 static void
13686 f_repeat(argvars, rettv)
13687 typval_T *argvars;
13688 typval_T *rettv;
13690 char_u *p;
13691 int n;
13692 int slen;
13693 int len;
13694 char_u *r;
13695 int i;
13697 n = get_tv_number(&argvars[1]);
13698 if (argvars[0].v_type == VAR_LIST)
13700 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
13701 while (n-- > 0)
13702 if (list_extend(rettv->vval.v_list,
13703 argvars[0].vval.v_list, NULL) == FAIL)
13704 break;
13706 else
13708 p = get_tv_string(&argvars[0]);
13709 rettv->v_type = VAR_STRING;
13710 rettv->vval.v_string = NULL;
13712 slen = (int)STRLEN(p);
13713 len = slen * n;
13714 if (len <= 0)
13715 return;
13717 r = alloc(len + 1);
13718 if (r != NULL)
13720 for (i = 0; i < n; i++)
13721 mch_memmove(r + i * slen, p, (size_t)slen);
13722 r[len] = NUL;
13725 rettv->vval.v_string = r;
13730 * "resolve()" function
13732 static void
13733 f_resolve(argvars, rettv)
13734 typval_T *argvars;
13735 typval_T *rettv;
13737 char_u *p;
13739 p = get_tv_string(&argvars[0]);
13740 #ifdef FEAT_SHORTCUT
13742 char_u *v = NULL;
13744 v = mch_resolve_shortcut(p);
13745 if (v != NULL)
13746 rettv->vval.v_string = v;
13747 else
13748 rettv->vval.v_string = vim_strsave(p);
13750 #else
13751 # ifdef HAVE_READLINK
13753 char_u buf[MAXPATHL + 1];
13754 char_u *cpy;
13755 int len;
13756 char_u *remain = NULL;
13757 char_u *q;
13758 int is_relative_to_current = FALSE;
13759 int has_trailing_pathsep = FALSE;
13760 int limit = 100;
13762 p = vim_strsave(p);
13764 if (p[0] == '.' && (vim_ispathsep(p[1])
13765 || (p[1] == '.' && (vim_ispathsep(p[2])))))
13766 is_relative_to_current = TRUE;
13768 len = STRLEN(p);
13769 if (len > 0 && after_pathsep(p, p + len))
13770 has_trailing_pathsep = TRUE;
13772 q = getnextcomp(p);
13773 if (*q != NUL)
13775 /* Separate the first path component in "p", and keep the
13776 * remainder (beginning with the path separator). */
13777 remain = vim_strsave(q - 1);
13778 q[-1] = NUL;
13781 for (;;)
13783 for (;;)
13785 len = readlink((char *)p, (char *)buf, MAXPATHL);
13786 if (len <= 0)
13787 break;
13788 buf[len] = NUL;
13790 if (limit-- == 0)
13792 vim_free(p);
13793 vim_free(remain);
13794 EMSG(_("E655: Too many symbolic links (cycle?)"));
13795 rettv->vval.v_string = NULL;
13796 goto fail;
13799 /* Ensure that the result will have a trailing path separator
13800 * if the argument has one. */
13801 if (remain == NULL && has_trailing_pathsep)
13802 add_pathsep(buf);
13804 /* Separate the first path component in the link value and
13805 * concatenate the remainders. */
13806 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
13807 if (*q != NUL)
13809 if (remain == NULL)
13810 remain = vim_strsave(q - 1);
13811 else
13813 cpy = concat_str(q - 1, remain);
13814 if (cpy != NULL)
13816 vim_free(remain);
13817 remain = cpy;
13820 q[-1] = NUL;
13823 q = gettail(p);
13824 if (q > p && *q == NUL)
13826 /* Ignore trailing path separator. */
13827 q[-1] = NUL;
13828 q = gettail(p);
13830 if (q > p && !mch_isFullName(buf))
13832 /* symlink is relative to directory of argument */
13833 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
13834 if (cpy != NULL)
13836 STRCPY(cpy, p);
13837 STRCPY(gettail(cpy), buf);
13838 vim_free(p);
13839 p = cpy;
13842 else
13844 vim_free(p);
13845 p = vim_strsave(buf);
13849 if (remain == NULL)
13850 break;
13852 /* Append the first path component of "remain" to "p". */
13853 q = getnextcomp(remain + 1);
13854 len = q - remain - (*q != NUL);
13855 cpy = vim_strnsave(p, STRLEN(p) + len);
13856 if (cpy != NULL)
13858 STRNCAT(cpy, remain, len);
13859 vim_free(p);
13860 p = cpy;
13862 /* Shorten "remain". */
13863 if (*q != NUL)
13864 mch_memmove(remain, q - 1, STRLEN(q - 1) + 1);
13865 else
13867 vim_free(remain);
13868 remain = NULL;
13872 /* If the result is a relative path name, make it explicitly relative to
13873 * the current directory if and only if the argument had this form. */
13874 if (!vim_ispathsep(*p))
13876 if (is_relative_to_current
13877 && *p != NUL
13878 && !(p[0] == '.'
13879 && (p[1] == NUL
13880 || vim_ispathsep(p[1])
13881 || (p[1] == '.'
13882 && (p[2] == NUL
13883 || vim_ispathsep(p[2]))))))
13885 /* Prepend "./". */
13886 cpy = concat_str((char_u *)"./", p);
13887 if (cpy != NULL)
13889 vim_free(p);
13890 p = cpy;
13893 else if (!is_relative_to_current)
13895 /* Strip leading "./". */
13896 q = p;
13897 while (q[0] == '.' && vim_ispathsep(q[1]))
13898 q += 2;
13899 if (q > p)
13900 mch_memmove(p, p + 2, STRLEN(p + 2) + (size_t)1);
13904 /* Ensure that the result will have no trailing path separator
13905 * if the argument had none. But keep "/" or "//". */
13906 if (!has_trailing_pathsep)
13908 q = p + STRLEN(p);
13909 if (after_pathsep(p, q))
13910 *gettail_sep(p) = NUL;
13913 rettv->vval.v_string = p;
13915 # else
13916 rettv->vval.v_string = vim_strsave(p);
13917 # endif
13918 #endif
13920 simplify_filename(rettv->vval.v_string);
13922 #ifdef HAVE_READLINK
13923 fail:
13924 #endif
13925 rettv->v_type = VAR_STRING;
13929 * "reverse({list})" function
13931 static void
13932 f_reverse(argvars, rettv)
13933 typval_T *argvars;
13934 typval_T *rettv;
13936 list_T *l;
13937 listitem_T *li, *ni;
13939 rettv->vval.v_number = 0;
13940 if (argvars[0].v_type != VAR_LIST)
13941 EMSG2(_(e_listarg), "reverse()");
13942 else if ((l = argvars[0].vval.v_list) != NULL
13943 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
13945 li = l->lv_last;
13946 l->lv_first = l->lv_last = NULL;
13947 l->lv_len = 0;
13948 while (li != NULL)
13950 ni = li->li_prev;
13951 list_append(l, li);
13952 li = ni;
13954 rettv->vval.v_list = l;
13955 rettv->v_type = VAR_LIST;
13956 ++l->lv_refcount;
13957 l->lv_idx = l->lv_len - l->lv_idx - 1;
13961 #define SP_NOMOVE 0x01 /* don't move cursor */
13962 #define SP_REPEAT 0x02 /* repeat to find outer pair */
13963 #define SP_RETCOUNT 0x04 /* return matchcount */
13964 #define SP_SETPCMARK 0x08 /* set previous context mark */
13965 #define SP_START 0x10 /* accept match at start position */
13966 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
13967 #define SP_END 0x40 /* leave cursor at end of match */
13969 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
13972 * Get flags for a search function.
13973 * Possibly sets "p_ws".
13974 * Returns BACKWARD, FORWARD or zero (for an error).
13976 static int
13977 get_search_arg(varp, flagsp)
13978 typval_T *varp;
13979 int *flagsp;
13981 int dir = FORWARD;
13982 char_u *flags;
13983 char_u nbuf[NUMBUFLEN];
13984 int mask;
13986 if (varp->v_type != VAR_UNKNOWN)
13988 flags = get_tv_string_buf_chk(varp, nbuf);
13989 if (flags == NULL)
13990 return 0; /* type error; errmsg already given */
13991 while (*flags != NUL)
13993 switch (*flags)
13995 case 'b': dir = BACKWARD; break;
13996 case 'w': p_ws = TRUE; break;
13997 case 'W': p_ws = FALSE; break;
13998 default: mask = 0;
13999 if (flagsp != NULL)
14000 switch (*flags)
14002 case 'c': mask = SP_START; break;
14003 case 'e': mask = SP_END; break;
14004 case 'm': mask = SP_RETCOUNT; break;
14005 case 'n': mask = SP_NOMOVE; break;
14006 case 'p': mask = SP_SUBPAT; break;
14007 case 'r': mask = SP_REPEAT; break;
14008 case 's': mask = SP_SETPCMARK; break;
14010 if (mask == 0)
14012 EMSG2(_(e_invarg2), flags);
14013 dir = 0;
14015 else
14016 *flagsp |= mask;
14018 if (dir == 0)
14019 break;
14020 ++flags;
14023 return dir;
14027 * Shared by search() and searchpos() functions
14029 static int
14030 search_cmn(argvars, match_pos, flagsp)
14031 typval_T *argvars;
14032 pos_T *match_pos;
14033 int *flagsp;
14035 int flags;
14036 char_u *pat;
14037 pos_T pos;
14038 pos_T save_cursor;
14039 int save_p_ws = p_ws;
14040 int dir;
14041 int retval = 0; /* default: FAIL */
14042 long lnum_stop = 0;
14043 proftime_T tm;
14044 #ifdef FEAT_RELTIME
14045 long time_limit = 0;
14046 #endif
14047 int options = SEARCH_KEEP;
14048 int subpatnum;
14050 pat = get_tv_string(&argvars[0]);
14051 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
14052 if (dir == 0)
14053 goto theend;
14054 flags = *flagsp;
14055 if (flags & SP_START)
14056 options |= SEARCH_START;
14057 if (flags & SP_END)
14058 options |= SEARCH_END;
14060 /* Optional arguments: line number to stop searching and timeout. */
14061 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
14063 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
14064 if (lnum_stop < 0)
14065 goto theend;
14066 #ifdef FEAT_RELTIME
14067 if (argvars[3].v_type != VAR_UNKNOWN)
14069 time_limit = get_tv_number_chk(&argvars[3], NULL);
14070 if (time_limit < 0)
14071 goto theend;
14073 #endif
14076 #ifdef FEAT_RELTIME
14077 /* Set the time limit, if there is one. */
14078 profile_setlimit(time_limit, &tm);
14079 #endif
14082 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
14083 * Check to make sure only those flags are set.
14084 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
14085 * flags cannot be set. Check for that condition also.
14087 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
14088 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14090 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
14091 goto theend;
14094 pos = save_cursor = curwin->w_cursor;
14095 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14096 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
14097 if (subpatnum != FAIL)
14099 if (flags & SP_SUBPAT)
14100 retval = subpatnum;
14101 else
14102 retval = pos.lnum;
14103 if (flags & SP_SETPCMARK)
14104 setpcmark();
14105 curwin->w_cursor = pos;
14106 if (match_pos != NULL)
14108 /* Store the match cursor position */
14109 match_pos->lnum = pos.lnum;
14110 match_pos->col = pos.col + 1;
14112 /* "/$" will put the cursor after the end of the line, may need to
14113 * correct that here */
14114 check_cursor();
14117 /* If 'n' flag is used: restore cursor position. */
14118 if (flags & SP_NOMOVE)
14119 curwin->w_cursor = save_cursor;
14120 else
14121 curwin->w_set_curswant = TRUE;
14122 theend:
14123 p_ws = save_p_ws;
14125 return retval;
14129 * "search()" function
14131 static void
14132 f_search(argvars, rettv)
14133 typval_T *argvars;
14134 typval_T *rettv;
14136 int flags = 0;
14138 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
14142 * "searchdecl()" function
14144 static void
14145 f_searchdecl(argvars, rettv)
14146 typval_T *argvars;
14147 typval_T *rettv;
14149 int locally = 1;
14150 int thisblock = 0;
14151 int error = FALSE;
14152 char_u *name;
14154 rettv->vval.v_number = 1; /* default: FAIL */
14156 name = get_tv_string_chk(&argvars[0]);
14157 if (argvars[1].v_type != VAR_UNKNOWN)
14159 locally = get_tv_number_chk(&argvars[1], &error) == 0;
14160 if (!error && argvars[2].v_type != VAR_UNKNOWN)
14161 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
14163 if (!error && name != NULL)
14164 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
14165 locally, thisblock, SEARCH_KEEP) == FAIL;
14169 * Used by searchpair() and searchpairpos()
14171 static int
14172 searchpair_cmn(argvars, match_pos)
14173 typval_T *argvars;
14174 pos_T *match_pos;
14176 char_u *spat, *mpat, *epat;
14177 char_u *skip;
14178 int save_p_ws = p_ws;
14179 int dir;
14180 int flags = 0;
14181 char_u nbuf1[NUMBUFLEN];
14182 char_u nbuf2[NUMBUFLEN];
14183 char_u nbuf3[NUMBUFLEN];
14184 int retval = 0; /* default: FAIL */
14185 long lnum_stop = 0;
14186 long time_limit = 0;
14188 /* Get the three pattern arguments: start, middle, end. */
14189 spat = get_tv_string_chk(&argvars[0]);
14190 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
14191 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
14192 if (spat == NULL || mpat == NULL || epat == NULL)
14193 goto theend; /* type error */
14195 /* Handle the optional fourth argument: flags */
14196 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
14197 if (dir == 0)
14198 goto theend;
14200 /* Don't accept SP_END or SP_SUBPAT.
14201 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
14203 if ((flags & (SP_END | SP_SUBPAT)) != 0
14204 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14206 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
14207 goto theend;
14210 /* Using 'r' implies 'W', otherwise it doesn't work. */
14211 if (flags & SP_REPEAT)
14212 p_ws = FALSE;
14214 /* Optional fifth argument: skip expression */
14215 if (argvars[3].v_type == VAR_UNKNOWN
14216 || argvars[4].v_type == VAR_UNKNOWN)
14217 skip = (char_u *)"";
14218 else
14220 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
14221 if (argvars[5].v_type != VAR_UNKNOWN)
14223 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
14224 if (lnum_stop < 0)
14225 goto theend;
14226 #ifdef FEAT_RELTIME
14227 if (argvars[6].v_type != VAR_UNKNOWN)
14229 time_limit = get_tv_number_chk(&argvars[6], NULL);
14230 if (time_limit < 0)
14231 goto theend;
14233 #endif
14236 if (skip == NULL)
14237 goto theend; /* type error */
14239 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
14240 match_pos, lnum_stop, time_limit);
14242 theend:
14243 p_ws = save_p_ws;
14245 return retval;
14249 * "searchpair()" function
14251 static void
14252 f_searchpair(argvars, rettv)
14253 typval_T *argvars;
14254 typval_T *rettv;
14256 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
14260 * "searchpairpos()" function
14262 static void
14263 f_searchpairpos(argvars, rettv)
14264 typval_T *argvars;
14265 typval_T *rettv;
14267 pos_T match_pos;
14268 int lnum = 0;
14269 int col = 0;
14271 rettv->vval.v_number = 0;
14273 if (rettv_list_alloc(rettv) == FAIL)
14274 return;
14276 if (searchpair_cmn(argvars, &match_pos) > 0)
14278 lnum = match_pos.lnum;
14279 col = match_pos.col;
14282 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14283 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14287 * Search for a start/middle/end thing.
14288 * Used by searchpair(), see its documentation for the details.
14289 * Returns 0 or -1 for no match,
14291 long
14292 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
14293 lnum_stop, time_limit)
14294 char_u *spat; /* start pattern */
14295 char_u *mpat; /* middle pattern */
14296 char_u *epat; /* end pattern */
14297 int dir; /* BACKWARD or FORWARD */
14298 char_u *skip; /* skip expression */
14299 int flags; /* SP_SETPCMARK and other SP_ values */
14300 pos_T *match_pos;
14301 linenr_T lnum_stop; /* stop at this line if not zero */
14302 long time_limit; /* stop after this many msec */
14304 char_u *save_cpo;
14305 char_u *pat, *pat2 = NULL, *pat3 = NULL;
14306 long retval = 0;
14307 pos_T pos;
14308 pos_T firstpos;
14309 pos_T foundpos;
14310 pos_T save_cursor;
14311 pos_T save_pos;
14312 int n;
14313 int r;
14314 int nest = 1;
14315 int err;
14316 int options = SEARCH_KEEP;
14317 proftime_T tm;
14319 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
14320 save_cpo = p_cpo;
14321 p_cpo = (char_u *)"";
14323 #ifdef FEAT_RELTIME
14324 /* Set the time limit, if there is one. */
14325 profile_setlimit(time_limit, &tm);
14326 #endif
14328 /* Make two search patterns: start/end (pat2, for in nested pairs) and
14329 * start/middle/end (pat3, for the top pair). */
14330 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
14331 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
14332 if (pat2 == NULL || pat3 == NULL)
14333 goto theend;
14334 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
14335 if (*mpat == NUL)
14336 STRCPY(pat3, pat2);
14337 else
14338 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
14339 spat, epat, mpat);
14340 if (flags & SP_START)
14341 options |= SEARCH_START;
14343 save_cursor = curwin->w_cursor;
14344 pos = curwin->w_cursor;
14345 clearpos(&firstpos);
14346 clearpos(&foundpos);
14347 pat = pat3;
14348 for (;;)
14350 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14351 options, RE_SEARCH, lnum_stop, &tm);
14352 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
14353 /* didn't find it or found the first match again: FAIL */
14354 break;
14356 if (firstpos.lnum == 0)
14357 firstpos = pos;
14358 if (equalpos(pos, foundpos))
14360 /* Found the same position again. Can happen with a pattern that
14361 * has "\zs" at the end and searching backwards. Advance one
14362 * character and try again. */
14363 if (dir == BACKWARD)
14364 decl(&pos);
14365 else
14366 incl(&pos);
14368 foundpos = pos;
14370 /* clear the start flag to avoid getting stuck here */
14371 options &= ~SEARCH_START;
14373 /* If the skip pattern matches, ignore this match. */
14374 if (*skip != NUL)
14376 save_pos = curwin->w_cursor;
14377 curwin->w_cursor = pos;
14378 r = eval_to_bool(skip, &err, NULL, FALSE);
14379 curwin->w_cursor = save_pos;
14380 if (err)
14382 /* Evaluating {skip} caused an error, break here. */
14383 curwin->w_cursor = save_cursor;
14384 retval = -1;
14385 break;
14387 if (r)
14388 continue;
14391 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
14393 /* Found end when searching backwards or start when searching
14394 * forward: nested pair. */
14395 ++nest;
14396 pat = pat2; /* nested, don't search for middle */
14398 else
14400 /* Found end when searching forward or start when searching
14401 * backward: end of (nested) pair; or found middle in outer pair. */
14402 if (--nest == 1)
14403 pat = pat3; /* outer level, search for middle */
14406 if (nest == 0)
14408 /* Found the match: return matchcount or line number. */
14409 if (flags & SP_RETCOUNT)
14410 ++retval;
14411 else
14412 retval = pos.lnum;
14413 if (flags & SP_SETPCMARK)
14414 setpcmark();
14415 curwin->w_cursor = pos;
14416 if (!(flags & SP_REPEAT))
14417 break;
14418 nest = 1; /* search for next unmatched */
14422 if (match_pos != NULL)
14424 /* Store the match cursor position */
14425 match_pos->lnum = curwin->w_cursor.lnum;
14426 match_pos->col = curwin->w_cursor.col + 1;
14429 /* If 'n' flag is used or search failed: restore cursor position. */
14430 if ((flags & SP_NOMOVE) || retval == 0)
14431 curwin->w_cursor = save_cursor;
14433 theend:
14434 vim_free(pat2);
14435 vim_free(pat3);
14436 p_cpo = save_cpo;
14438 return retval;
14442 * "searchpos()" function
14444 static void
14445 f_searchpos(argvars, rettv)
14446 typval_T *argvars;
14447 typval_T *rettv;
14449 pos_T match_pos;
14450 int lnum = 0;
14451 int col = 0;
14452 int n;
14453 int flags = 0;
14455 rettv->vval.v_number = 0;
14457 if (rettv_list_alloc(rettv) == FAIL)
14458 return;
14460 n = search_cmn(argvars, &match_pos, &flags);
14461 if (n > 0)
14463 lnum = match_pos.lnum;
14464 col = match_pos.col;
14467 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14468 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14469 if (flags & SP_SUBPAT)
14470 list_append_number(rettv->vval.v_list, (varnumber_T)n);
14474 /*ARGSUSED*/
14475 static void
14476 f_server2client(argvars, rettv)
14477 typval_T *argvars;
14478 typval_T *rettv;
14480 #ifdef FEAT_CLIENTSERVER
14481 char_u buf[NUMBUFLEN];
14482 char_u *server = get_tv_string_chk(&argvars[0]);
14483 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
14485 rettv->vval.v_number = -1;
14486 if (server == NULL || reply == NULL)
14487 return;
14488 if (check_restricted() || check_secure())
14489 return;
14490 # ifdef FEAT_X11
14491 if (check_connection() == FAIL)
14492 return;
14493 # endif
14495 if (serverSendReply(server, reply) < 0)
14497 EMSG(_("E258: Unable to send to client"));
14498 return;
14500 rettv->vval.v_number = 0;
14501 #else
14502 rettv->vval.v_number = -1;
14503 #endif
14506 /*ARGSUSED*/
14507 static void
14508 f_serverlist(argvars, rettv)
14509 typval_T *argvars;
14510 typval_T *rettv;
14512 char_u *r = NULL;
14514 #ifdef FEAT_CLIENTSERVER
14515 # ifdef WIN32
14516 r = serverGetVimNames();
14517 # else
14518 make_connection();
14519 if (X_DISPLAY != NULL)
14520 r = serverGetVimNames(X_DISPLAY);
14521 # endif
14522 #endif
14523 rettv->v_type = VAR_STRING;
14524 rettv->vval.v_string = r;
14528 * "setbufvar()" function
14530 /*ARGSUSED*/
14531 static void
14532 f_setbufvar(argvars, rettv)
14533 typval_T *argvars;
14534 typval_T *rettv;
14536 buf_T *buf;
14537 aco_save_T aco;
14538 char_u *varname, *bufvarname;
14539 typval_T *varp;
14540 char_u nbuf[NUMBUFLEN];
14542 rettv->vval.v_number = 0;
14544 if (check_restricted() || check_secure())
14545 return;
14546 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
14547 varname = get_tv_string_chk(&argvars[1]);
14548 buf = get_buf_tv(&argvars[0]);
14549 varp = &argvars[2];
14551 if (buf != NULL && varname != NULL && varp != NULL)
14553 /* set curbuf to be our buf, temporarily */
14554 aucmd_prepbuf(&aco, buf);
14556 if (*varname == '&')
14558 long numval;
14559 char_u *strval;
14560 int error = FALSE;
14562 ++varname;
14563 numval = get_tv_number_chk(varp, &error);
14564 strval = get_tv_string_buf_chk(varp, nbuf);
14565 if (!error && strval != NULL)
14566 set_option_value(varname, numval, strval, OPT_LOCAL);
14568 else
14570 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
14571 if (bufvarname != NULL)
14573 STRCPY(bufvarname, "b:");
14574 STRCPY(bufvarname + 2, varname);
14575 set_var(bufvarname, varp, TRUE);
14576 vim_free(bufvarname);
14580 /* reset notion of buffer */
14581 aucmd_restbuf(&aco);
14586 * "setcmdpos()" function
14588 static void
14589 f_setcmdpos(argvars, rettv)
14590 typval_T *argvars;
14591 typval_T *rettv;
14593 int pos = (int)get_tv_number(&argvars[0]) - 1;
14595 if (pos >= 0)
14596 rettv->vval.v_number = set_cmdline_pos(pos);
14600 * "setline()" function
14602 static void
14603 f_setline(argvars, rettv)
14604 typval_T *argvars;
14605 typval_T *rettv;
14607 linenr_T lnum;
14608 char_u *line = NULL;
14609 list_T *l = NULL;
14610 listitem_T *li = NULL;
14611 long added = 0;
14612 linenr_T lcount = curbuf->b_ml.ml_line_count;
14614 lnum = get_tv_lnum(&argvars[0]);
14615 if (argvars[1].v_type == VAR_LIST)
14617 l = argvars[1].vval.v_list;
14618 li = l->lv_first;
14620 else
14621 line = get_tv_string_chk(&argvars[1]);
14623 rettv->vval.v_number = 0; /* OK */
14624 for (;;)
14626 if (l != NULL)
14628 /* list argument, get next string */
14629 if (li == NULL)
14630 break;
14631 line = get_tv_string_chk(&li->li_tv);
14632 li = li->li_next;
14635 rettv->vval.v_number = 1; /* FAIL */
14636 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
14637 break;
14638 if (lnum <= curbuf->b_ml.ml_line_count)
14640 /* existing line, replace it */
14641 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
14643 changed_bytes(lnum, 0);
14644 if (lnum == curwin->w_cursor.lnum)
14645 check_cursor_col();
14646 rettv->vval.v_number = 0; /* OK */
14649 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
14651 /* lnum is one past the last line, append the line */
14652 ++added;
14653 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
14654 rettv->vval.v_number = 0; /* OK */
14657 if (l == NULL) /* only one string argument */
14658 break;
14659 ++lnum;
14662 if (added > 0)
14663 appended_lines_mark(lcount, added);
14666 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
14669 * Used by "setqflist()" and "setloclist()" functions
14671 /*ARGSUSED*/
14672 static void
14673 set_qf_ll_list(wp, list_arg, action_arg, rettv)
14674 win_T *wp;
14675 typval_T *list_arg;
14676 typval_T *action_arg;
14677 typval_T *rettv;
14679 #ifdef FEAT_QUICKFIX
14680 char_u *act;
14681 int action = ' ';
14682 #endif
14684 rettv->vval.v_number = -1;
14686 #ifdef FEAT_QUICKFIX
14687 if (list_arg->v_type != VAR_LIST)
14688 EMSG(_(e_listreq));
14689 else
14691 list_T *l = list_arg->vval.v_list;
14693 if (action_arg->v_type == VAR_STRING)
14695 act = get_tv_string_chk(action_arg);
14696 if (act == NULL)
14697 return; /* type error; errmsg already given */
14698 if (*act == 'a' || *act == 'r')
14699 action = *act;
14702 if (l != NULL && set_errorlist(wp, l, action) == OK)
14703 rettv->vval.v_number = 0;
14705 #endif
14709 * "setloclist()" function
14711 /*ARGSUSED*/
14712 static void
14713 f_setloclist(argvars, rettv)
14714 typval_T *argvars;
14715 typval_T *rettv;
14717 win_T *win;
14719 rettv->vval.v_number = -1;
14721 win = find_win_by_nr(&argvars[0], NULL);
14722 if (win != NULL)
14723 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
14727 * "setmatches()" function
14729 static void
14730 f_setmatches(argvars, rettv)
14731 typval_T *argvars;
14732 typval_T *rettv;
14734 #ifdef FEAT_SEARCH_EXTRA
14735 list_T *l;
14736 listitem_T *li;
14737 dict_T *d;
14739 rettv->vval.v_number = -1;
14740 if (argvars[0].v_type != VAR_LIST)
14742 EMSG(_(e_listreq));
14743 return;
14745 if ((l = argvars[0].vval.v_list) != NULL)
14748 /* To some extent make sure that we are dealing with a list from
14749 * "getmatches()". */
14750 li = l->lv_first;
14751 while (li != NULL)
14753 if (li->li_tv.v_type != VAR_DICT
14754 || (d = li->li_tv.vval.v_dict) == NULL)
14756 EMSG(_(e_invarg));
14757 return;
14759 if (!(dict_find(d, (char_u *)"group", -1) != NULL
14760 && dict_find(d, (char_u *)"pattern", -1) != NULL
14761 && dict_find(d, (char_u *)"priority", -1) != NULL
14762 && dict_find(d, (char_u *)"id", -1) != NULL))
14764 EMSG(_(e_invarg));
14765 return;
14767 li = li->li_next;
14770 clear_matches(curwin);
14771 li = l->lv_first;
14772 while (li != NULL)
14774 d = li->li_tv.vval.v_dict;
14775 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
14776 get_dict_string(d, (char_u *)"pattern", FALSE),
14777 (int)get_dict_number(d, (char_u *)"priority"),
14778 (int)get_dict_number(d, (char_u *)"id"));
14779 li = li->li_next;
14781 rettv->vval.v_number = 0;
14783 #endif
14787 * "setpos()" function
14789 /*ARGSUSED*/
14790 static void
14791 f_setpos(argvars, rettv)
14792 typval_T *argvars;
14793 typval_T *rettv;
14795 pos_T pos;
14796 int fnum;
14797 char_u *name;
14799 rettv->vval.v_number = -1;
14800 name = get_tv_string_chk(argvars);
14801 if (name != NULL)
14803 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
14805 --pos.col;
14806 if (name[0] == '.' && name[1] == NUL)
14808 /* set cursor */
14809 if (fnum == curbuf->b_fnum)
14811 curwin->w_cursor = pos;
14812 check_cursor();
14813 rettv->vval.v_number = 0;
14815 else
14816 EMSG(_(e_invarg));
14818 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
14820 /* set mark */
14821 if (setmark_pos(name[1], &pos, fnum) == OK)
14822 rettv->vval.v_number = 0;
14824 else
14825 EMSG(_(e_invarg));
14831 * "setqflist()" function
14833 /*ARGSUSED*/
14834 static void
14835 f_setqflist(argvars, rettv)
14836 typval_T *argvars;
14837 typval_T *rettv;
14839 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
14843 * "setreg()" function
14845 static void
14846 f_setreg(argvars, rettv)
14847 typval_T *argvars;
14848 typval_T *rettv;
14850 int regname;
14851 char_u *strregname;
14852 char_u *stropt;
14853 char_u *strval;
14854 int append;
14855 char_u yank_type;
14856 long block_len;
14858 block_len = -1;
14859 yank_type = MAUTO;
14860 append = FALSE;
14862 strregname = get_tv_string_chk(argvars);
14863 rettv->vval.v_number = 1; /* FAIL is default */
14865 if (strregname == NULL)
14866 return; /* type error; errmsg already given */
14867 regname = *strregname;
14868 if (regname == 0 || regname == '@')
14869 regname = '"';
14870 else if (regname == '=')
14871 return;
14873 if (argvars[2].v_type != VAR_UNKNOWN)
14875 stropt = get_tv_string_chk(&argvars[2]);
14876 if (stropt == NULL)
14877 return; /* type error */
14878 for (; *stropt != NUL; ++stropt)
14879 switch (*stropt)
14881 case 'a': case 'A': /* append */
14882 append = TRUE;
14883 break;
14884 case 'v': case 'c': /* character-wise selection */
14885 yank_type = MCHAR;
14886 break;
14887 case 'V': case 'l': /* line-wise selection */
14888 yank_type = MLINE;
14889 break;
14890 #ifdef FEAT_VISUAL
14891 case 'b': case Ctrl_V: /* block-wise selection */
14892 yank_type = MBLOCK;
14893 if (VIM_ISDIGIT(stropt[1]))
14895 ++stropt;
14896 block_len = getdigits(&stropt) - 1;
14897 --stropt;
14899 break;
14900 #endif
14904 strval = get_tv_string_chk(&argvars[1]);
14905 if (strval != NULL)
14906 write_reg_contents_ex(regname, strval, -1,
14907 append, yank_type, block_len);
14908 rettv->vval.v_number = 0;
14912 * "settabwinvar()" function
14914 static void
14915 f_settabwinvar(argvars, rettv)
14916 typval_T *argvars;
14917 typval_T *rettv;
14919 setwinvar(argvars, rettv, 1);
14923 * "setwinvar()" function
14925 static void
14926 f_setwinvar(argvars, rettv)
14927 typval_T *argvars;
14928 typval_T *rettv;
14930 setwinvar(argvars, rettv, 0);
14934 * "setwinvar()" and "settabwinvar()" functions
14936 static void
14937 setwinvar(argvars, rettv, off)
14938 typval_T *argvars;
14939 typval_T *rettv;
14940 int off;
14942 win_T *win;
14943 #ifdef FEAT_WINDOWS
14944 win_T *save_curwin;
14945 tabpage_T *save_curtab;
14946 #endif
14947 char_u *varname, *winvarname;
14948 typval_T *varp;
14949 char_u nbuf[NUMBUFLEN];
14950 tabpage_T *tp;
14952 rettv->vval.v_number = 0;
14954 if (check_restricted() || check_secure())
14955 return;
14957 #ifdef FEAT_WINDOWS
14958 if (off == 1)
14959 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
14960 else
14961 tp = curtab;
14962 #endif
14963 win = find_win_by_nr(&argvars[off], tp);
14964 varname = get_tv_string_chk(&argvars[off + 1]);
14965 varp = &argvars[off + 2];
14967 if (win != NULL && varname != NULL && varp != NULL)
14969 #ifdef FEAT_WINDOWS
14970 /* set curwin to be our win, temporarily */
14971 save_curwin = curwin;
14972 save_curtab = curtab;
14973 goto_tabpage_tp(tp);
14974 if (!win_valid(win))
14975 return;
14976 curwin = win;
14977 curbuf = curwin->w_buffer;
14978 #endif
14980 if (*varname == '&')
14982 long numval;
14983 char_u *strval;
14984 int error = FALSE;
14986 ++varname;
14987 numval = get_tv_number_chk(varp, &error);
14988 strval = get_tv_string_buf_chk(varp, nbuf);
14989 if (!error && strval != NULL)
14990 set_option_value(varname, numval, strval, OPT_LOCAL);
14992 else
14994 winvarname = alloc((unsigned)STRLEN(varname) + 3);
14995 if (winvarname != NULL)
14997 STRCPY(winvarname, "w:");
14998 STRCPY(winvarname + 2, varname);
14999 set_var(winvarname, varp, TRUE);
15000 vim_free(winvarname);
15004 #ifdef FEAT_WINDOWS
15005 /* Restore current tabpage and window, if still valid (autocomands can
15006 * make them invalid). */
15007 if (valid_tabpage(save_curtab))
15008 goto_tabpage_tp(save_curtab);
15009 if (win_valid(save_curwin))
15011 curwin = save_curwin;
15012 curbuf = curwin->w_buffer;
15014 #endif
15019 * "shellescape({string})" function
15021 static void
15022 f_shellescape(argvars, rettv)
15023 typval_T *argvars;
15024 typval_T *rettv;
15026 rettv->vval.v_string = vim_strsave_shellescape(get_tv_string(&argvars[0]));
15027 rettv->v_type = VAR_STRING;
15031 * "simplify()" function
15033 static void
15034 f_simplify(argvars, rettv)
15035 typval_T *argvars;
15036 typval_T *rettv;
15038 char_u *p;
15040 p = get_tv_string(&argvars[0]);
15041 rettv->vval.v_string = vim_strsave(p);
15042 simplify_filename(rettv->vval.v_string); /* simplify in place */
15043 rettv->v_type = VAR_STRING;
15046 static int
15047 #ifdef __BORLANDC__
15048 _RTLENTRYF
15049 #endif
15050 item_compare __ARGS((const void *s1, const void *s2));
15051 static int
15052 #ifdef __BORLANDC__
15053 _RTLENTRYF
15054 #endif
15055 item_compare2 __ARGS((const void *s1, const void *s2));
15057 static int item_compare_ic;
15058 static char_u *item_compare_func;
15059 static int item_compare_func_err;
15060 #define ITEM_COMPARE_FAIL 999
15063 * Compare functions for f_sort() below.
15065 static int
15066 #ifdef __BORLANDC__
15067 _RTLENTRYF
15068 #endif
15069 item_compare(s1, s2)
15070 const void *s1;
15071 const void *s2;
15073 char_u *p1, *p2;
15074 char_u *tofree1, *tofree2;
15075 int res;
15076 char_u numbuf1[NUMBUFLEN];
15077 char_u numbuf2[NUMBUFLEN];
15079 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
15080 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
15081 if (p1 == NULL)
15082 p1 = (char_u *)"";
15083 if (p2 == NULL)
15084 p2 = (char_u *)"";
15085 if (item_compare_ic)
15086 res = STRICMP(p1, p2);
15087 else
15088 res = STRCMP(p1, p2);
15089 vim_free(tofree1);
15090 vim_free(tofree2);
15091 return res;
15094 static int
15095 #ifdef __BORLANDC__
15096 _RTLENTRYF
15097 #endif
15098 item_compare2(s1, s2)
15099 const void *s1;
15100 const void *s2;
15102 int res;
15103 typval_T rettv;
15104 typval_T argv[3];
15105 int dummy;
15107 /* shortcut after failure in previous call; compare all items equal */
15108 if (item_compare_func_err)
15109 return 0;
15111 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
15112 * in the copy without changing the original list items. */
15113 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
15114 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
15116 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
15117 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
15118 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
15119 clear_tv(&argv[0]);
15120 clear_tv(&argv[1]);
15122 if (res == FAIL)
15123 res = ITEM_COMPARE_FAIL;
15124 else
15125 /* return value has wrong type */
15126 res = get_tv_number_chk(&rettv, &item_compare_func_err);
15127 if (item_compare_func_err)
15128 res = ITEM_COMPARE_FAIL;
15129 clear_tv(&rettv);
15130 return res;
15134 * "sort({list})" function
15136 static void
15137 f_sort(argvars, rettv)
15138 typval_T *argvars;
15139 typval_T *rettv;
15141 list_T *l;
15142 listitem_T *li;
15143 listitem_T **ptrs;
15144 long len;
15145 long i;
15147 rettv->vval.v_number = 0;
15148 if (argvars[0].v_type != VAR_LIST)
15149 EMSG2(_(e_listarg), "sort()");
15150 else
15152 l = argvars[0].vval.v_list;
15153 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
15154 return;
15155 rettv->vval.v_list = l;
15156 rettv->v_type = VAR_LIST;
15157 ++l->lv_refcount;
15159 len = list_len(l);
15160 if (len <= 1)
15161 return; /* short list sorts pretty quickly */
15163 item_compare_ic = FALSE;
15164 item_compare_func = NULL;
15165 if (argvars[1].v_type != VAR_UNKNOWN)
15167 if (argvars[1].v_type == VAR_FUNC)
15168 item_compare_func = argvars[1].vval.v_string;
15169 else
15171 int error = FALSE;
15173 i = get_tv_number_chk(&argvars[1], &error);
15174 if (error)
15175 return; /* type error; errmsg already given */
15176 if (i == 1)
15177 item_compare_ic = TRUE;
15178 else
15179 item_compare_func = get_tv_string(&argvars[1]);
15183 /* Make an array with each entry pointing to an item in the List. */
15184 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
15185 if (ptrs == NULL)
15186 return;
15187 i = 0;
15188 for (li = l->lv_first; li != NULL; li = li->li_next)
15189 ptrs[i++] = li;
15191 item_compare_func_err = FALSE;
15192 /* test the compare function */
15193 if (item_compare_func != NULL
15194 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
15195 == ITEM_COMPARE_FAIL)
15196 EMSG(_("E702: Sort compare function failed"));
15197 else
15199 /* Sort the array with item pointers. */
15200 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
15201 item_compare_func == NULL ? item_compare : item_compare2);
15203 if (!item_compare_func_err)
15205 /* Clear the List and append the items in the sorted order. */
15206 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
15207 l->lv_len = 0;
15208 for (i = 0; i < len; ++i)
15209 list_append(l, ptrs[i]);
15213 vim_free(ptrs);
15218 * "soundfold({word})" function
15220 static void
15221 f_soundfold(argvars, rettv)
15222 typval_T *argvars;
15223 typval_T *rettv;
15225 char_u *s;
15227 rettv->v_type = VAR_STRING;
15228 s = get_tv_string(&argvars[0]);
15229 #ifdef FEAT_SPELL
15230 rettv->vval.v_string = eval_soundfold(s);
15231 #else
15232 rettv->vval.v_string = vim_strsave(s);
15233 #endif
15237 * "spellbadword()" function
15239 /* ARGSUSED */
15240 static void
15241 f_spellbadword(argvars, rettv)
15242 typval_T *argvars;
15243 typval_T *rettv;
15245 char_u *word = (char_u *)"";
15246 hlf_T attr = HLF_COUNT;
15247 int len = 0;
15249 if (rettv_list_alloc(rettv) == FAIL)
15250 return;
15252 #ifdef FEAT_SPELL
15253 if (argvars[0].v_type == VAR_UNKNOWN)
15255 /* Find the start and length of the badly spelled word. */
15256 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
15257 if (len != 0)
15258 word = ml_get_cursor();
15260 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15262 char_u *str = get_tv_string_chk(&argvars[0]);
15263 int capcol = -1;
15265 if (str != NULL)
15267 /* Check the argument for spelling. */
15268 while (*str != NUL)
15270 len = spell_check(curwin, str, &attr, &capcol, FALSE);
15271 if (attr != HLF_COUNT)
15273 word = str;
15274 break;
15276 str += len;
15280 #endif
15282 list_append_string(rettv->vval.v_list, word, len);
15283 list_append_string(rettv->vval.v_list, (char_u *)(
15284 attr == HLF_SPB ? "bad" :
15285 attr == HLF_SPR ? "rare" :
15286 attr == HLF_SPL ? "local" :
15287 attr == HLF_SPC ? "caps" :
15288 ""), -1);
15292 * "spellsuggest()" function
15294 /*ARGSUSED*/
15295 static void
15296 f_spellsuggest(argvars, rettv)
15297 typval_T *argvars;
15298 typval_T *rettv;
15300 #ifdef FEAT_SPELL
15301 char_u *str;
15302 int typeerr = FALSE;
15303 int maxcount;
15304 garray_T ga;
15305 int i;
15306 listitem_T *li;
15307 int need_capital = FALSE;
15308 #endif
15310 if (rettv_list_alloc(rettv) == FAIL)
15311 return;
15313 #ifdef FEAT_SPELL
15314 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15316 str = get_tv_string(&argvars[0]);
15317 if (argvars[1].v_type != VAR_UNKNOWN)
15319 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
15320 if (maxcount <= 0)
15321 return;
15322 if (argvars[2].v_type != VAR_UNKNOWN)
15324 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
15325 if (typeerr)
15326 return;
15329 else
15330 maxcount = 25;
15332 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
15334 for (i = 0; i < ga.ga_len; ++i)
15336 str = ((char_u **)ga.ga_data)[i];
15338 li = listitem_alloc();
15339 if (li == NULL)
15340 vim_free(str);
15341 else
15343 li->li_tv.v_type = VAR_STRING;
15344 li->li_tv.v_lock = 0;
15345 li->li_tv.vval.v_string = str;
15346 list_append(rettv->vval.v_list, li);
15349 ga_clear(&ga);
15351 #endif
15354 static void
15355 f_split(argvars, rettv)
15356 typval_T *argvars;
15357 typval_T *rettv;
15359 char_u *str;
15360 char_u *end;
15361 char_u *pat = NULL;
15362 regmatch_T regmatch;
15363 char_u patbuf[NUMBUFLEN];
15364 char_u *save_cpo;
15365 int match;
15366 colnr_T col = 0;
15367 int keepempty = FALSE;
15368 int typeerr = FALSE;
15370 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15371 save_cpo = p_cpo;
15372 p_cpo = (char_u *)"";
15374 str = get_tv_string(&argvars[0]);
15375 if (argvars[1].v_type != VAR_UNKNOWN)
15377 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
15378 if (pat == NULL)
15379 typeerr = TRUE;
15380 if (argvars[2].v_type != VAR_UNKNOWN)
15381 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
15383 if (pat == NULL || *pat == NUL)
15384 pat = (char_u *)"[\\x01- ]\\+";
15386 if (rettv_list_alloc(rettv) == FAIL)
15387 return;
15388 if (typeerr)
15389 return;
15391 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
15392 if (regmatch.regprog != NULL)
15394 regmatch.rm_ic = FALSE;
15395 while (*str != NUL || keepempty)
15397 if (*str == NUL)
15398 match = FALSE; /* empty item at the end */
15399 else
15400 match = vim_regexec_nl(&regmatch, str, col);
15401 if (match)
15402 end = regmatch.startp[0];
15403 else
15404 end = str + STRLEN(str);
15405 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
15406 && *str != NUL && match && end < regmatch.endp[0]))
15408 if (list_append_string(rettv->vval.v_list, str,
15409 (int)(end - str)) == FAIL)
15410 break;
15412 if (!match)
15413 break;
15414 /* Advance to just after the match. */
15415 if (regmatch.endp[0] > str)
15416 col = 0;
15417 else
15419 /* Don't get stuck at the same match. */
15420 #ifdef FEAT_MBYTE
15421 col = (*mb_ptr2len)(regmatch.endp[0]);
15422 #else
15423 col = 1;
15424 #endif
15426 str = regmatch.endp[0];
15429 vim_free(regmatch.regprog);
15432 p_cpo = save_cpo;
15436 * "str2nr()" function
15438 static void
15439 f_str2nr(argvars, rettv)
15440 typval_T *argvars;
15441 typval_T *rettv;
15443 int base = 10;
15444 char_u *p;
15445 long n;
15447 if (argvars[1].v_type != VAR_UNKNOWN)
15449 base = get_tv_number(&argvars[1]);
15450 if (base != 8 && base != 10 && base != 16)
15452 EMSG(_(e_invarg));
15453 return;
15457 p = skipwhite(get_tv_string(&argvars[0]));
15458 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
15459 rettv->vval.v_number = n;
15462 #ifdef HAVE_STRFTIME
15464 * "strftime({format}[, {time}])" function
15466 static void
15467 f_strftime(argvars, rettv)
15468 typval_T *argvars;
15469 typval_T *rettv;
15471 char_u result_buf[256];
15472 struct tm *curtime;
15473 time_t seconds;
15474 char_u *p;
15476 rettv->v_type = VAR_STRING;
15478 p = get_tv_string(&argvars[0]);
15479 if (argvars[1].v_type == VAR_UNKNOWN)
15480 seconds = time(NULL);
15481 else
15482 seconds = (time_t)get_tv_number(&argvars[1]);
15483 curtime = localtime(&seconds);
15484 /* MSVC returns NULL for an invalid value of seconds. */
15485 if (curtime == NULL)
15486 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
15487 else
15489 # ifdef FEAT_MBYTE
15490 vimconv_T conv;
15491 char_u *enc;
15493 conv.vc_type = CONV_NONE;
15494 enc = enc_locale();
15495 convert_setup(&conv, p_enc, enc);
15496 if (conv.vc_type != CONV_NONE)
15497 p = string_convert(&conv, p, NULL);
15498 # endif
15499 if (p != NULL)
15500 (void)strftime((char *)result_buf, sizeof(result_buf),
15501 (char *)p, curtime);
15502 else
15503 result_buf[0] = NUL;
15505 # ifdef FEAT_MBYTE
15506 if (conv.vc_type != CONV_NONE)
15507 vim_free(p);
15508 convert_setup(&conv, enc, p_enc);
15509 if (conv.vc_type != CONV_NONE)
15510 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
15511 else
15512 # endif
15513 rettv->vval.v_string = vim_strsave(result_buf);
15515 # ifdef FEAT_MBYTE
15516 /* Release conversion descriptors */
15517 convert_setup(&conv, NULL, NULL);
15518 vim_free(enc);
15519 # endif
15522 #endif
15525 * "stridx()" function
15527 static void
15528 f_stridx(argvars, rettv)
15529 typval_T *argvars;
15530 typval_T *rettv;
15532 char_u buf[NUMBUFLEN];
15533 char_u *needle;
15534 char_u *haystack;
15535 char_u *save_haystack;
15536 char_u *pos;
15537 int start_idx;
15539 needle = get_tv_string_chk(&argvars[1]);
15540 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
15541 rettv->vval.v_number = -1;
15542 if (needle == NULL || haystack == NULL)
15543 return; /* type error; errmsg already given */
15545 if (argvars[2].v_type != VAR_UNKNOWN)
15547 int error = FALSE;
15549 start_idx = get_tv_number_chk(&argvars[2], &error);
15550 if (error || start_idx >= (int)STRLEN(haystack))
15551 return;
15552 if (start_idx >= 0)
15553 haystack += start_idx;
15556 pos = (char_u *)strstr((char *)haystack, (char *)needle);
15557 if (pos != NULL)
15558 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
15562 * "string()" function
15564 static void
15565 f_string(argvars, rettv)
15566 typval_T *argvars;
15567 typval_T *rettv;
15569 char_u *tofree;
15570 char_u numbuf[NUMBUFLEN];
15572 rettv->v_type = VAR_STRING;
15573 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
15574 /* Make a copy if we have a value but it's not in allocate memory. */
15575 if (rettv->vval.v_string != NULL && tofree == NULL)
15576 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
15580 * "strlen()" function
15582 static void
15583 f_strlen(argvars, rettv)
15584 typval_T *argvars;
15585 typval_T *rettv;
15587 rettv->vval.v_number = (varnumber_T)(STRLEN(
15588 get_tv_string(&argvars[0])));
15592 * "strpart()" function
15594 static void
15595 f_strpart(argvars, rettv)
15596 typval_T *argvars;
15597 typval_T *rettv;
15599 char_u *p;
15600 int n;
15601 int len;
15602 int slen;
15603 int error = FALSE;
15605 p = get_tv_string(&argvars[0]);
15606 slen = (int)STRLEN(p);
15608 n = get_tv_number_chk(&argvars[1], &error);
15609 if (error)
15610 len = 0;
15611 else if (argvars[2].v_type != VAR_UNKNOWN)
15612 len = get_tv_number(&argvars[2]);
15613 else
15614 len = slen - n; /* default len: all bytes that are available. */
15617 * Only return the overlap between the specified part and the actual
15618 * string.
15620 if (n < 0)
15622 len += n;
15623 n = 0;
15625 else if (n > slen)
15626 n = slen;
15627 if (len < 0)
15628 len = 0;
15629 else if (n + len > slen)
15630 len = slen - n;
15632 rettv->v_type = VAR_STRING;
15633 rettv->vval.v_string = vim_strnsave(p + n, len);
15637 * "strridx()" function
15639 static void
15640 f_strridx(argvars, rettv)
15641 typval_T *argvars;
15642 typval_T *rettv;
15644 char_u buf[NUMBUFLEN];
15645 char_u *needle;
15646 char_u *haystack;
15647 char_u *rest;
15648 char_u *lastmatch = NULL;
15649 int haystack_len, end_idx;
15651 needle = get_tv_string_chk(&argvars[1]);
15652 haystack = get_tv_string_buf_chk(&argvars[0], buf);
15654 rettv->vval.v_number = -1;
15655 if (needle == NULL || haystack == NULL)
15656 return; /* type error; errmsg already given */
15658 haystack_len = (int)STRLEN(haystack);
15659 if (argvars[2].v_type != VAR_UNKNOWN)
15661 /* Third argument: upper limit for index */
15662 end_idx = get_tv_number_chk(&argvars[2], NULL);
15663 if (end_idx < 0)
15664 return; /* can never find a match */
15666 else
15667 end_idx = haystack_len;
15669 if (*needle == NUL)
15671 /* Empty string matches past the end. */
15672 lastmatch = haystack + end_idx;
15674 else
15676 for (rest = haystack; *rest != '\0'; ++rest)
15678 rest = (char_u *)strstr((char *)rest, (char *)needle);
15679 if (rest == NULL || rest > haystack + end_idx)
15680 break;
15681 lastmatch = rest;
15685 if (lastmatch == NULL)
15686 rettv->vval.v_number = -1;
15687 else
15688 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
15692 * "strtrans()" function
15694 static void
15695 f_strtrans(argvars, rettv)
15696 typval_T *argvars;
15697 typval_T *rettv;
15699 rettv->v_type = VAR_STRING;
15700 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
15704 * "submatch()" function
15706 static void
15707 f_submatch(argvars, rettv)
15708 typval_T *argvars;
15709 typval_T *rettv;
15711 rettv->v_type = VAR_STRING;
15712 rettv->vval.v_string =
15713 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
15717 * "substitute()" function
15719 static void
15720 f_substitute(argvars, rettv)
15721 typval_T *argvars;
15722 typval_T *rettv;
15724 char_u patbuf[NUMBUFLEN];
15725 char_u subbuf[NUMBUFLEN];
15726 char_u flagsbuf[NUMBUFLEN];
15728 char_u *str = get_tv_string_chk(&argvars[0]);
15729 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
15730 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
15731 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
15733 rettv->v_type = VAR_STRING;
15734 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
15735 rettv->vval.v_string = NULL;
15736 else
15737 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
15741 * "synID(lnum, col, trans)" function
15743 /*ARGSUSED*/
15744 static void
15745 f_synID(argvars, rettv)
15746 typval_T *argvars;
15747 typval_T *rettv;
15749 int id = 0;
15750 #ifdef FEAT_SYN_HL
15751 long lnum;
15752 long col;
15753 int trans;
15754 int transerr = FALSE;
15756 lnum = get_tv_lnum(argvars); /* -1 on type error */
15757 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
15758 trans = get_tv_number_chk(&argvars[2], &transerr);
15760 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
15761 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
15762 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
15763 #endif
15765 rettv->vval.v_number = id;
15769 * "synIDattr(id, what [, mode])" function
15771 /*ARGSUSED*/
15772 static void
15773 f_synIDattr(argvars, rettv)
15774 typval_T *argvars;
15775 typval_T *rettv;
15777 char_u *p = NULL;
15778 #ifdef FEAT_SYN_HL
15779 int id;
15780 char_u *what;
15781 char_u *mode;
15782 char_u modebuf[NUMBUFLEN];
15783 int modec;
15785 id = get_tv_number(&argvars[0]);
15786 what = get_tv_string(&argvars[1]);
15787 if (argvars[2].v_type != VAR_UNKNOWN)
15789 mode = get_tv_string_buf(&argvars[2], modebuf);
15790 modec = TOLOWER_ASC(mode[0]);
15791 if (modec != 't' && modec != 'c'
15792 #ifdef FEAT_GUI
15793 && modec != 'g'
15794 #endif
15796 modec = 0; /* replace invalid with current */
15798 else
15800 #ifdef FEAT_GUI
15801 if (gui.in_use)
15802 modec = 'g';
15803 else
15804 #endif
15805 if (t_colors > 1)
15806 modec = 'c';
15807 else
15808 modec = 't';
15812 switch (TOLOWER_ASC(what[0]))
15814 case 'b':
15815 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
15816 p = highlight_color(id, what, modec);
15817 else /* bold */
15818 p = highlight_has_attr(id, HL_BOLD, modec);
15819 break;
15821 case 'f': /* fg[#] */
15822 p = highlight_color(id, what, modec);
15823 break;
15825 case 'i':
15826 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
15827 p = highlight_has_attr(id, HL_INVERSE, modec);
15828 else /* italic */
15829 p = highlight_has_attr(id, HL_ITALIC, modec);
15830 break;
15832 case 'n': /* name */
15833 p = get_highlight_name(NULL, id - 1);
15834 break;
15836 case 'r': /* reverse */
15837 p = highlight_has_attr(id, HL_INVERSE, modec);
15838 break;
15840 case 's': /* standout */
15841 p = highlight_has_attr(id, HL_STANDOUT, modec);
15842 break;
15844 case 'u':
15845 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
15846 /* underline */
15847 p = highlight_has_attr(id, HL_UNDERLINE, modec);
15848 else
15849 /* undercurl */
15850 p = highlight_has_attr(id, HL_UNDERCURL, modec);
15851 break;
15854 if (p != NULL)
15855 p = vim_strsave(p);
15856 #endif
15857 rettv->v_type = VAR_STRING;
15858 rettv->vval.v_string = p;
15862 * "synIDtrans(id)" function
15864 /*ARGSUSED*/
15865 static void
15866 f_synIDtrans(argvars, rettv)
15867 typval_T *argvars;
15868 typval_T *rettv;
15870 int id;
15872 #ifdef FEAT_SYN_HL
15873 id = get_tv_number(&argvars[0]);
15875 if (id > 0)
15876 id = syn_get_final_id(id);
15877 else
15878 #endif
15879 id = 0;
15881 rettv->vval.v_number = id;
15885 * "synstack(lnum, col)" function
15887 /*ARGSUSED*/
15888 static void
15889 f_synstack(argvars, rettv)
15890 typval_T *argvars;
15891 typval_T *rettv;
15893 #ifdef FEAT_SYN_HL
15894 long lnum;
15895 long col;
15896 int i;
15897 int id;
15898 #endif
15900 rettv->v_type = VAR_LIST;
15901 rettv->vval.v_list = NULL;
15903 #ifdef FEAT_SYN_HL
15904 lnum = get_tv_lnum(argvars); /* -1 on type error */
15905 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
15907 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
15908 && col >= 0 && col < (long)STRLEN(ml_get(lnum))
15909 && rettv_list_alloc(rettv) != FAIL)
15911 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
15912 for (i = 0; ; ++i)
15914 id = syn_get_stack_item(i);
15915 if (id < 0)
15916 break;
15917 if (list_append_number(rettv->vval.v_list, id) == FAIL)
15918 break;
15921 #endif
15925 * "system()" function
15927 static void
15928 f_system(argvars, rettv)
15929 typval_T *argvars;
15930 typval_T *rettv;
15932 char_u *res = NULL;
15933 char_u *p;
15934 char_u *infile = NULL;
15935 char_u buf[NUMBUFLEN];
15936 int err = FALSE;
15937 FILE *fd;
15939 if (check_restricted() || check_secure())
15940 goto done;
15942 if (argvars[1].v_type != VAR_UNKNOWN)
15945 * Write the string to a temp file, to be used for input of the shell
15946 * command.
15948 if ((infile = vim_tempname('i')) == NULL)
15950 EMSG(_(e_notmp));
15951 goto done;
15954 fd = mch_fopen((char *)infile, WRITEBIN);
15955 if (fd == NULL)
15957 EMSG2(_(e_notopen), infile);
15958 goto done;
15960 p = get_tv_string_buf_chk(&argvars[1], buf);
15961 if (p == NULL)
15963 fclose(fd);
15964 goto done; /* type error; errmsg already given */
15966 if (fwrite(p, STRLEN(p), 1, fd) != 1)
15967 err = TRUE;
15968 if (fclose(fd) != 0)
15969 err = TRUE;
15970 if (err)
15972 EMSG(_("E677: Error writing temp file"));
15973 goto done;
15977 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
15978 SHELL_SILENT | SHELL_COOKED);
15980 #ifdef USE_CR
15981 /* translate <CR> into <NL> */
15982 if (res != NULL)
15984 char_u *s;
15986 for (s = res; *s; ++s)
15988 if (*s == CAR)
15989 *s = NL;
15992 #else
15993 # ifdef USE_CRNL
15994 /* translate <CR><NL> into <NL> */
15995 if (res != NULL)
15997 char_u *s, *d;
15999 d = res;
16000 for (s = res; *s; ++s)
16002 if (s[0] == CAR && s[1] == NL)
16003 ++s;
16004 *d++ = *s;
16006 *d = NUL;
16008 # endif
16009 #endif
16011 done:
16012 if (infile != NULL)
16014 mch_remove(infile);
16015 vim_free(infile);
16017 rettv->v_type = VAR_STRING;
16018 rettv->vval.v_string = res;
16022 * "tabpagebuflist()" function
16024 /* ARGSUSED */
16025 static void
16026 f_tabpagebuflist(argvars, rettv)
16027 typval_T *argvars;
16028 typval_T *rettv;
16030 #ifndef FEAT_WINDOWS
16031 rettv->vval.v_number = 0;
16032 #else
16033 tabpage_T *tp;
16034 win_T *wp = NULL;
16036 if (argvars[0].v_type == VAR_UNKNOWN)
16037 wp = firstwin;
16038 else
16040 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16041 if (tp != NULL)
16042 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16044 if (wp == NULL)
16045 rettv->vval.v_number = 0;
16046 else
16048 if (rettv_list_alloc(rettv) == FAIL)
16049 rettv->vval.v_number = 0;
16050 else
16052 for (; wp != NULL; wp = wp->w_next)
16053 if (list_append_number(rettv->vval.v_list,
16054 wp->w_buffer->b_fnum) == FAIL)
16055 break;
16058 #endif
16063 * "tabpagenr()" function
16065 /* ARGSUSED */
16066 static void
16067 f_tabpagenr(argvars, rettv)
16068 typval_T *argvars;
16069 typval_T *rettv;
16071 int nr = 1;
16072 #ifdef FEAT_WINDOWS
16073 char_u *arg;
16075 if (argvars[0].v_type != VAR_UNKNOWN)
16077 arg = get_tv_string_chk(&argvars[0]);
16078 nr = 0;
16079 if (arg != NULL)
16081 if (STRCMP(arg, "$") == 0)
16082 nr = tabpage_index(NULL) - 1;
16083 else
16084 EMSG2(_(e_invexpr2), arg);
16087 else
16088 nr = tabpage_index(curtab);
16089 #endif
16090 rettv->vval.v_number = nr;
16094 #ifdef FEAT_WINDOWS
16095 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
16098 * Common code for tabpagewinnr() and winnr().
16100 static int
16101 get_winnr(tp, argvar)
16102 tabpage_T *tp;
16103 typval_T *argvar;
16105 win_T *twin;
16106 int nr = 1;
16107 win_T *wp;
16108 char_u *arg;
16110 twin = (tp == curtab) ? curwin : tp->tp_curwin;
16111 if (argvar->v_type != VAR_UNKNOWN)
16113 arg = get_tv_string_chk(argvar);
16114 if (arg == NULL)
16115 nr = 0; /* type error; errmsg already given */
16116 else if (STRCMP(arg, "$") == 0)
16117 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
16118 else if (STRCMP(arg, "#") == 0)
16120 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
16121 if (twin == NULL)
16122 nr = 0;
16124 else
16126 EMSG2(_(e_invexpr2), arg);
16127 nr = 0;
16131 if (nr > 0)
16132 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16133 wp != twin; wp = wp->w_next)
16135 if (wp == NULL)
16137 /* didn't find it in this tabpage */
16138 nr = 0;
16139 break;
16141 ++nr;
16143 return nr;
16145 #endif
16148 * "tabpagewinnr()" function
16150 /* ARGSUSED */
16151 static void
16152 f_tabpagewinnr(argvars, rettv)
16153 typval_T *argvars;
16154 typval_T *rettv;
16156 int nr = 1;
16157 #ifdef FEAT_WINDOWS
16158 tabpage_T *tp;
16160 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16161 if (tp == NULL)
16162 nr = 0;
16163 else
16164 nr = get_winnr(tp, &argvars[1]);
16165 #endif
16166 rettv->vval.v_number = nr;
16171 * "tagfiles()" function
16173 /*ARGSUSED*/
16174 static void
16175 f_tagfiles(argvars, rettv)
16176 typval_T *argvars;
16177 typval_T *rettv;
16179 char_u fname[MAXPATHL + 1];
16180 tagname_T tn;
16181 int first;
16183 if (rettv_list_alloc(rettv) == FAIL)
16185 rettv->vval.v_number = 0;
16186 return;
16189 for (first = TRUE; ; first = FALSE)
16190 if (get_tagfname(&tn, first, fname) == FAIL
16191 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
16192 break;
16193 tagname_free(&tn);
16197 * "taglist()" function
16199 static void
16200 f_taglist(argvars, rettv)
16201 typval_T *argvars;
16202 typval_T *rettv;
16204 char_u *tag_pattern;
16206 tag_pattern = get_tv_string(&argvars[0]);
16208 rettv->vval.v_number = FALSE;
16209 if (*tag_pattern == NUL)
16210 return;
16212 if (rettv_list_alloc(rettv) == OK)
16213 (void)get_tags(rettv->vval.v_list, tag_pattern);
16217 * "tempname()" function
16219 /*ARGSUSED*/
16220 static void
16221 f_tempname(argvars, rettv)
16222 typval_T *argvars;
16223 typval_T *rettv;
16225 static int x = 'A';
16227 rettv->v_type = VAR_STRING;
16228 rettv->vval.v_string = vim_tempname(x);
16230 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
16231 * names. Skip 'I' and 'O', they are used for shell redirection. */
16234 if (x == 'Z')
16235 x = '0';
16236 else if (x == '9')
16237 x = 'A';
16238 else
16240 #ifdef EBCDIC
16241 if (x == 'I')
16242 x = 'J';
16243 else if (x == 'R')
16244 x = 'S';
16245 else
16246 #endif
16247 ++x;
16249 } while (x == 'I' || x == 'O');
16253 * "test(list)" function: Just checking the walls...
16255 /*ARGSUSED*/
16256 static void
16257 f_test(argvars, rettv)
16258 typval_T *argvars;
16259 typval_T *rettv;
16261 /* Used for unit testing. Change the code below to your liking. */
16262 #if 0
16263 listitem_T *li;
16264 list_T *l;
16265 char_u *bad, *good;
16267 if (argvars[0].v_type != VAR_LIST)
16268 return;
16269 l = argvars[0].vval.v_list;
16270 if (l == NULL)
16271 return;
16272 li = l->lv_first;
16273 if (li == NULL)
16274 return;
16275 bad = get_tv_string(&li->li_tv);
16276 li = li->li_next;
16277 if (li == NULL)
16278 return;
16279 good = get_tv_string(&li->li_tv);
16280 rettv->vval.v_number = test_edit_score(bad, good);
16281 #endif
16285 * "tolower(string)" function
16287 static void
16288 f_tolower(argvars, rettv)
16289 typval_T *argvars;
16290 typval_T *rettv;
16292 char_u *p;
16294 p = vim_strsave(get_tv_string(&argvars[0]));
16295 rettv->v_type = VAR_STRING;
16296 rettv->vval.v_string = p;
16298 if (p != NULL)
16299 while (*p != NUL)
16301 #ifdef FEAT_MBYTE
16302 int l;
16304 if (enc_utf8)
16306 int c, lc;
16308 c = utf_ptr2char(p);
16309 lc = utf_tolower(c);
16310 l = utf_ptr2len(p);
16311 /* TODO: reallocate string when byte count changes. */
16312 if (utf_char2len(lc) == l)
16313 utf_char2bytes(lc, p);
16314 p += l;
16316 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
16317 p += l; /* skip multi-byte character */
16318 else
16319 #endif
16321 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
16322 ++p;
16328 * "toupper(string)" function
16330 static void
16331 f_toupper(argvars, rettv)
16332 typval_T *argvars;
16333 typval_T *rettv;
16335 rettv->v_type = VAR_STRING;
16336 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
16340 * "tr(string, fromstr, tostr)" function
16342 static void
16343 f_tr(argvars, rettv)
16344 typval_T *argvars;
16345 typval_T *rettv;
16347 char_u *instr;
16348 char_u *fromstr;
16349 char_u *tostr;
16350 char_u *p;
16351 #ifdef FEAT_MBYTE
16352 int inlen;
16353 int fromlen;
16354 int tolen;
16355 int idx;
16356 char_u *cpstr;
16357 int cplen;
16358 int first = TRUE;
16359 #endif
16360 char_u buf[NUMBUFLEN];
16361 char_u buf2[NUMBUFLEN];
16362 garray_T ga;
16364 instr = get_tv_string(&argvars[0]);
16365 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
16366 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
16368 /* Default return value: empty string. */
16369 rettv->v_type = VAR_STRING;
16370 rettv->vval.v_string = NULL;
16371 if (fromstr == NULL || tostr == NULL)
16372 return; /* type error; errmsg already given */
16373 ga_init2(&ga, (int)sizeof(char), 80);
16375 #ifdef FEAT_MBYTE
16376 if (!has_mbyte)
16377 #endif
16378 /* not multi-byte: fromstr and tostr must be the same length */
16379 if (STRLEN(fromstr) != STRLEN(tostr))
16381 #ifdef FEAT_MBYTE
16382 error:
16383 #endif
16384 EMSG2(_(e_invarg2), fromstr);
16385 ga_clear(&ga);
16386 return;
16389 /* fromstr and tostr have to contain the same number of chars */
16390 while (*instr != NUL)
16392 #ifdef FEAT_MBYTE
16393 if (has_mbyte)
16395 inlen = (*mb_ptr2len)(instr);
16396 cpstr = instr;
16397 cplen = inlen;
16398 idx = 0;
16399 for (p = fromstr; *p != NUL; p += fromlen)
16401 fromlen = (*mb_ptr2len)(p);
16402 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
16404 for (p = tostr; *p != NUL; p += tolen)
16406 tolen = (*mb_ptr2len)(p);
16407 if (idx-- == 0)
16409 cplen = tolen;
16410 cpstr = p;
16411 break;
16414 if (*p == NUL) /* tostr is shorter than fromstr */
16415 goto error;
16416 break;
16418 ++idx;
16421 if (first && cpstr == instr)
16423 /* Check that fromstr and tostr have the same number of
16424 * (multi-byte) characters. Done only once when a character
16425 * of instr doesn't appear in fromstr. */
16426 first = FALSE;
16427 for (p = tostr; *p != NUL; p += tolen)
16429 tolen = (*mb_ptr2len)(p);
16430 --idx;
16432 if (idx != 0)
16433 goto error;
16436 ga_grow(&ga, cplen);
16437 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
16438 ga.ga_len += cplen;
16440 instr += inlen;
16442 else
16443 #endif
16445 /* When not using multi-byte chars we can do it faster. */
16446 p = vim_strchr(fromstr, *instr);
16447 if (p != NULL)
16448 ga_append(&ga, tostr[p - fromstr]);
16449 else
16450 ga_append(&ga, *instr);
16451 ++instr;
16455 /* add a terminating NUL */
16456 ga_grow(&ga, 1);
16457 ga_append(&ga, NUL);
16459 rettv->vval.v_string = ga.ga_data;
16463 * "type(expr)" function
16465 static void
16466 f_type(argvars, rettv)
16467 typval_T *argvars;
16468 typval_T *rettv;
16470 int n;
16472 switch (argvars[0].v_type)
16474 case VAR_NUMBER: n = 0; break;
16475 case VAR_STRING: n = 1; break;
16476 case VAR_FUNC: n = 2; break;
16477 case VAR_LIST: n = 3; break;
16478 case VAR_DICT: n = 4; break;
16479 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
16481 rettv->vval.v_number = n;
16485 * "values(dict)" function
16487 static void
16488 f_values(argvars, rettv)
16489 typval_T *argvars;
16490 typval_T *rettv;
16492 dict_list(argvars, rettv, 1);
16496 * "virtcol(string)" function
16498 static void
16499 f_virtcol(argvars, rettv)
16500 typval_T *argvars;
16501 typval_T *rettv;
16503 colnr_T vcol = 0;
16504 pos_T *fp;
16505 int fnum = curbuf->b_fnum;
16507 fp = var2fpos(&argvars[0], FALSE, &fnum);
16508 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
16509 && fnum == curbuf->b_fnum)
16511 getvvcol(curwin, fp, NULL, NULL, &vcol);
16512 ++vcol;
16515 rettv->vval.v_number = vcol;
16519 * "visualmode()" function
16521 /*ARGSUSED*/
16522 static void
16523 f_visualmode(argvars, rettv)
16524 typval_T *argvars;
16525 typval_T *rettv;
16527 #ifdef FEAT_VISUAL
16528 char_u str[2];
16530 rettv->v_type = VAR_STRING;
16531 str[0] = curbuf->b_visual_mode_eval;
16532 str[1] = NUL;
16533 rettv->vval.v_string = vim_strsave(str);
16535 /* A non-zero number or non-empty string argument: reset mode. */
16536 if ((argvars[0].v_type == VAR_NUMBER
16537 && argvars[0].vval.v_number != 0)
16538 || (argvars[0].v_type == VAR_STRING
16539 && *get_tv_string(&argvars[0]) != NUL))
16540 curbuf->b_visual_mode_eval = NUL;
16541 #else
16542 rettv->vval.v_number = 0; /* return anything, it won't work anyway */
16543 #endif
16547 * "winbufnr(nr)" function
16549 static void
16550 f_winbufnr(argvars, rettv)
16551 typval_T *argvars;
16552 typval_T *rettv;
16554 win_T *wp;
16556 wp = find_win_by_nr(&argvars[0], NULL);
16557 if (wp == NULL)
16558 rettv->vval.v_number = -1;
16559 else
16560 rettv->vval.v_number = wp->w_buffer->b_fnum;
16564 * "wincol()" function
16566 /*ARGSUSED*/
16567 static void
16568 f_wincol(argvars, rettv)
16569 typval_T *argvars;
16570 typval_T *rettv;
16572 validate_cursor();
16573 rettv->vval.v_number = curwin->w_wcol + 1;
16577 * "winheight(nr)" function
16579 static void
16580 f_winheight(argvars, rettv)
16581 typval_T *argvars;
16582 typval_T *rettv;
16584 win_T *wp;
16586 wp = find_win_by_nr(&argvars[0], NULL);
16587 if (wp == NULL)
16588 rettv->vval.v_number = -1;
16589 else
16590 rettv->vval.v_number = wp->w_height;
16594 * "winline()" function
16596 /*ARGSUSED*/
16597 static void
16598 f_winline(argvars, rettv)
16599 typval_T *argvars;
16600 typval_T *rettv;
16602 validate_cursor();
16603 rettv->vval.v_number = curwin->w_wrow + 1;
16607 * "winnr()" function
16609 /* ARGSUSED */
16610 static void
16611 f_winnr(argvars, rettv)
16612 typval_T *argvars;
16613 typval_T *rettv;
16615 int nr = 1;
16617 #ifdef FEAT_WINDOWS
16618 nr = get_winnr(curtab, &argvars[0]);
16619 #endif
16620 rettv->vval.v_number = nr;
16624 * "winrestcmd()" function
16626 /* ARGSUSED */
16627 static void
16628 f_winrestcmd(argvars, rettv)
16629 typval_T *argvars;
16630 typval_T *rettv;
16632 #ifdef FEAT_WINDOWS
16633 win_T *wp;
16634 int winnr = 1;
16635 garray_T ga;
16636 char_u buf[50];
16638 ga_init2(&ga, (int)sizeof(char), 70);
16639 for (wp = firstwin; wp != NULL; wp = wp->w_next)
16641 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
16642 ga_concat(&ga, buf);
16643 # ifdef FEAT_VERTSPLIT
16644 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
16645 ga_concat(&ga, buf);
16646 # endif
16647 ++winnr;
16649 ga_append(&ga, NUL);
16651 rettv->vval.v_string = ga.ga_data;
16652 #else
16653 rettv->vval.v_string = NULL;
16654 #endif
16655 rettv->v_type = VAR_STRING;
16659 * "winrestview()" function
16661 /* ARGSUSED */
16662 static void
16663 f_winrestview(argvars, rettv)
16664 typval_T *argvars;
16665 typval_T *rettv;
16667 dict_T *dict;
16669 if (argvars[0].v_type != VAR_DICT
16670 || (dict = argvars[0].vval.v_dict) == NULL)
16671 EMSG(_(e_invarg));
16672 else
16674 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
16675 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
16676 #ifdef FEAT_VIRTUALEDIT
16677 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
16678 #endif
16679 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
16680 curwin->w_set_curswant = FALSE;
16682 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
16683 #ifdef FEAT_DIFF
16684 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
16685 #endif
16686 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
16687 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
16689 check_cursor();
16690 changed_cline_bef_curs();
16691 invalidate_botline();
16692 redraw_later(VALID);
16694 if (curwin->w_topline == 0)
16695 curwin->w_topline = 1;
16696 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
16697 curwin->w_topline = curbuf->b_ml.ml_line_count;
16698 #ifdef FEAT_DIFF
16699 check_topfill(curwin, TRUE);
16700 #endif
16705 * "winsaveview()" function
16707 /* ARGSUSED */
16708 static void
16709 f_winsaveview(argvars, rettv)
16710 typval_T *argvars;
16711 typval_T *rettv;
16713 dict_T *dict;
16715 dict = dict_alloc();
16716 if (dict == NULL)
16717 return;
16718 rettv->v_type = VAR_DICT;
16719 rettv->vval.v_dict = dict;
16720 ++dict->dv_refcount;
16722 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
16723 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
16724 #ifdef FEAT_VIRTUALEDIT
16725 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
16726 #endif
16727 update_curswant();
16728 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
16730 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
16731 #ifdef FEAT_DIFF
16732 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
16733 #endif
16734 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
16735 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
16739 * "winwidth(nr)" function
16741 static void
16742 f_winwidth(argvars, rettv)
16743 typval_T *argvars;
16744 typval_T *rettv;
16746 win_T *wp;
16748 wp = find_win_by_nr(&argvars[0], NULL);
16749 if (wp == NULL)
16750 rettv->vval.v_number = -1;
16751 else
16752 #ifdef FEAT_VERTSPLIT
16753 rettv->vval.v_number = wp->w_width;
16754 #else
16755 rettv->vval.v_number = Columns;
16756 #endif
16760 * "writefile()" function
16762 static void
16763 f_writefile(argvars, rettv)
16764 typval_T *argvars;
16765 typval_T *rettv;
16767 int binary = FALSE;
16768 char_u *fname;
16769 FILE *fd;
16770 listitem_T *li;
16771 char_u *s;
16772 int ret = 0;
16773 int c;
16775 if (check_restricted() || check_secure())
16776 return;
16778 if (argvars[0].v_type != VAR_LIST)
16780 EMSG2(_(e_listarg), "writefile()");
16781 return;
16783 if (argvars[0].vval.v_list == NULL)
16784 return;
16786 if (argvars[2].v_type != VAR_UNKNOWN
16787 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
16788 binary = TRUE;
16790 /* Always open the file in binary mode, library functions have a mind of
16791 * their own about CR-LF conversion. */
16792 fname = get_tv_string(&argvars[1]);
16793 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
16795 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
16796 ret = -1;
16798 else
16800 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
16801 li = li->li_next)
16803 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
16805 if (*s == '\n')
16806 c = putc(NUL, fd);
16807 else
16808 c = putc(*s, fd);
16809 if (c == EOF)
16811 ret = -1;
16812 break;
16815 if (!binary || li->li_next != NULL)
16816 if (putc('\n', fd) == EOF)
16818 ret = -1;
16819 break;
16821 if (ret < 0)
16823 EMSG(_(e_write));
16824 break;
16827 fclose(fd);
16830 rettv->vval.v_number = ret;
16834 * Translate a String variable into a position.
16835 * Returns NULL when there is an error.
16837 static pos_T *
16838 var2fpos(varp, dollar_lnum, fnum)
16839 typval_T *varp;
16840 int dollar_lnum; /* TRUE when $ is last line */
16841 int *fnum; /* set to fnum for '0, 'A, etc. */
16843 char_u *name;
16844 static pos_T pos;
16845 pos_T *pp;
16847 /* Argument can be [lnum, col, coladd]. */
16848 if (varp->v_type == VAR_LIST)
16850 list_T *l;
16851 int len;
16852 int error = FALSE;
16853 listitem_T *li;
16855 l = varp->vval.v_list;
16856 if (l == NULL)
16857 return NULL;
16859 /* Get the line number */
16860 pos.lnum = list_find_nr(l, 0L, &error);
16861 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
16862 return NULL; /* invalid line number */
16864 /* Get the column number */
16865 pos.col = list_find_nr(l, 1L, &error);
16866 if (error)
16867 return NULL;
16868 len = (long)STRLEN(ml_get(pos.lnum));
16870 /* We accept "$" for the column number: last column. */
16871 li = list_find(l, 1L);
16872 if (li != NULL && li->li_tv.v_type == VAR_STRING
16873 && li->li_tv.vval.v_string != NULL
16874 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
16875 pos.col = len + 1;
16877 /* Accept a position up to the NUL after the line. */
16878 if (pos.col == 0 || (int)pos.col > len + 1)
16879 return NULL; /* invalid column number */
16880 --pos.col;
16882 #ifdef FEAT_VIRTUALEDIT
16883 /* Get the virtual offset. Defaults to zero. */
16884 pos.coladd = list_find_nr(l, 2L, &error);
16885 if (error)
16886 pos.coladd = 0;
16887 #endif
16889 return &pos;
16892 name = get_tv_string_chk(varp);
16893 if (name == NULL)
16894 return NULL;
16895 if (name[0] == '.') /* cursor */
16896 return &curwin->w_cursor;
16897 if (name[0] == '\'') /* mark */
16899 pp = getmark_fnum(name[1], FALSE, fnum);
16900 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
16901 return NULL;
16902 return pp;
16905 #ifdef FEAT_VIRTUALEDIT
16906 pos.coladd = 0;
16907 #endif
16909 if (name[0] == 'w' && dollar_lnum)
16911 pos.col = 0;
16912 if (name[1] == '0') /* "w0": first visible line */
16914 update_topline();
16915 pos.lnum = curwin->w_topline;
16916 return &pos;
16918 else if (name[1] == '$') /* "w$": last visible line */
16920 validate_botline();
16921 pos.lnum = curwin->w_botline - 1;
16922 return &pos;
16925 else if (name[0] == '$') /* last column or line */
16927 if (dollar_lnum)
16929 pos.lnum = curbuf->b_ml.ml_line_count;
16930 pos.col = 0;
16932 else
16934 pos.lnum = curwin->w_cursor.lnum;
16935 pos.col = (colnr_T)STRLEN(ml_get_curline());
16937 return &pos;
16939 return NULL;
16943 * Convert list in "arg" into a position and optional file number.
16944 * When "fnump" is NULL there is no file number, only 3 items.
16945 * Note that the column is passed on as-is, the caller may want to decrement
16946 * it to use 1 for the first column.
16947 * Return FAIL when conversion is not possible, doesn't check the position for
16948 * validity.
16950 static int
16951 list2fpos(arg, posp, fnump)
16952 typval_T *arg;
16953 pos_T *posp;
16954 int *fnump;
16956 list_T *l = arg->vval.v_list;
16957 long i = 0;
16958 long n;
16960 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
16961 * when "fnump" isn't NULL and "coladd" is optional. */
16962 if (arg->v_type != VAR_LIST
16963 || l == NULL
16964 || l->lv_len < (fnump == NULL ? 2 : 3)
16965 || l->lv_len > (fnump == NULL ? 3 : 4))
16966 return FAIL;
16968 if (fnump != NULL)
16970 n = list_find_nr(l, i++, NULL); /* fnum */
16971 if (n < 0)
16972 return FAIL;
16973 if (n == 0)
16974 n = curbuf->b_fnum; /* current buffer */
16975 *fnump = n;
16978 n = list_find_nr(l, i++, NULL); /* lnum */
16979 if (n < 0)
16980 return FAIL;
16981 posp->lnum = n;
16983 n = list_find_nr(l, i++, NULL); /* col */
16984 if (n < 0)
16985 return FAIL;
16986 posp->col = n;
16988 #ifdef FEAT_VIRTUALEDIT
16989 n = list_find_nr(l, i, NULL);
16990 if (n < 0)
16991 posp->coladd = 0;
16992 else
16993 posp->coladd = n;
16994 #endif
16996 return OK;
17000 * Get the length of an environment variable name.
17001 * Advance "arg" to the first character after the name.
17002 * Return 0 for error.
17004 static int
17005 get_env_len(arg)
17006 char_u **arg;
17008 char_u *p;
17009 int len;
17011 for (p = *arg; vim_isIDc(*p); ++p)
17013 if (p == *arg) /* no name found */
17014 return 0;
17016 len = (int)(p - *arg);
17017 *arg = p;
17018 return len;
17022 * Get the length of the name of a function or internal variable.
17023 * "arg" is advanced to the first non-white character after the name.
17024 * Return 0 if something is wrong.
17026 static int
17027 get_id_len(arg)
17028 char_u **arg;
17030 char_u *p;
17031 int len;
17033 /* Find the end of the name. */
17034 for (p = *arg; eval_isnamec(*p); ++p)
17036 if (p == *arg) /* no name found */
17037 return 0;
17039 len = (int)(p - *arg);
17040 *arg = skipwhite(p);
17042 return len;
17046 * Get the length of the name of a variable or function.
17047 * Only the name is recognized, does not handle ".key" or "[idx]".
17048 * "arg" is advanced to the first non-white character after the name.
17049 * Return -1 if curly braces expansion failed.
17050 * Return 0 if something else is wrong.
17051 * If the name contains 'magic' {}'s, expand them and return the
17052 * expanded name in an allocated string via 'alias' - caller must free.
17054 static int
17055 get_name_len(arg, alias, evaluate, verbose)
17056 char_u **arg;
17057 char_u **alias;
17058 int evaluate;
17059 int verbose;
17061 int len;
17062 char_u *p;
17063 char_u *expr_start;
17064 char_u *expr_end;
17066 *alias = NULL; /* default to no alias */
17068 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
17069 && (*arg)[2] == (int)KE_SNR)
17071 /* hard coded <SNR>, already translated */
17072 *arg += 3;
17073 return get_id_len(arg) + 3;
17075 len = eval_fname_script(*arg);
17076 if (len > 0)
17078 /* literal "<SID>", "s:" or "<SNR>" */
17079 *arg += len;
17083 * Find the end of the name; check for {} construction.
17085 p = find_name_end(*arg, &expr_start, &expr_end,
17086 len > 0 ? 0 : FNE_CHECK_START);
17087 if (expr_start != NULL)
17089 char_u *temp_string;
17091 if (!evaluate)
17093 len += (int)(p - *arg);
17094 *arg = skipwhite(p);
17095 return len;
17099 * Include any <SID> etc in the expanded string:
17100 * Thus the -len here.
17102 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
17103 if (temp_string == NULL)
17104 return -1;
17105 *alias = temp_string;
17106 *arg = skipwhite(p);
17107 return (int)STRLEN(temp_string);
17110 len += get_id_len(arg);
17111 if (len == 0 && verbose)
17112 EMSG2(_(e_invexpr2), *arg);
17114 return len;
17118 * Find the end of a variable or function name, taking care of magic braces.
17119 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
17120 * start and end of the first magic braces item.
17121 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
17122 * Return a pointer to just after the name. Equal to "arg" if there is no
17123 * valid name.
17125 static char_u *
17126 find_name_end(arg, expr_start, expr_end, flags)
17127 char_u *arg;
17128 char_u **expr_start;
17129 char_u **expr_end;
17130 int flags;
17132 int mb_nest = 0;
17133 int br_nest = 0;
17134 char_u *p;
17136 if (expr_start != NULL)
17138 *expr_start = NULL;
17139 *expr_end = NULL;
17142 /* Quick check for valid starting character. */
17143 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
17144 return arg;
17146 for (p = arg; *p != NUL
17147 && (eval_isnamec(*p)
17148 || *p == '{'
17149 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
17150 || mb_nest != 0
17151 || br_nest != 0); mb_ptr_adv(p))
17153 if (*p == '\'')
17155 /* skip over 'string' to avoid counting [ and ] inside it. */
17156 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
17158 if (*p == NUL)
17159 break;
17161 else if (*p == '"')
17163 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
17164 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
17165 if (*p == '\\' && p[1] != NUL)
17166 ++p;
17167 if (*p == NUL)
17168 break;
17171 if (mb_nest == 0)
17173 if (*p == '[')
17174 ++br_nest;
17175 else if (*p == ']')
17176 --br_nest;
17179 if (br_nest == 0)
17181 if (*p == '{')
17183 mb_nest++;
17184 if (expr_start != NULL && *expr_start == NULL)
17185 *expr_start = p;
17187 else if (*p == '}')
17189 mb_nest--;
17190 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
17191 *expr_end = p;
17196 return p;
17200 * Expands out the 'magic' {}'s in a variable/function name.
17201 * Note that this can call itself recursively, to deal with
17202 * constructs like foo{bar}{baz}{bam}
17203 * The four pointer arguments point to "foo{expre}ss{ion}bar"
17204 * "in_start" ^
17205 * "expr_start" ^
17206 * "expr_end" ^
17207 * "in_end" ^
17209 * Returns a new allocated string, which the caller must free.
17210 * Returns NULL for failure.
17212 static char_u *
17213 make_expanded_name(in_start, expr_start, expr_end, in_end)
17214 char_u *in_start;
17215 char_u *expr_start;
17216 char_u *expr_end;
17217 char_u *in_end;
17219 char_u c1;
17220 char_u *retval = NULL;
17221 char_u *temp_result;
17222 char_u *nextcmd = NULL;
17224 if (expr_end == NULL || in_end == NULL)
17225 return NULL;
17226 *expr_start = NUL;
17227 *expr_end = NUL;
17228 c1 = *in_end;
17229 *in_end = NUL;
17231 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
17232 if (temp_result != NULL && nextcmd == NULL)
17234 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
17235 + (in_end - expr_end) + 1));
17236 if (retval != NULL)
17238 STRCPY(retval, in_start);
17239 STRCAT(retval, temp_result);
17240 STRCAT(retval, expr_end + 1);
17243 vim_free(temp_result);
17245 *in_end = c1; /* put char back for error messages */
17246 *expr_start = '{';
17247 *expr_end = '}';
17249 if (retval != NULL)
17251 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
17252 if (expr_start != NULL)
17254 /* Further expansion! */
17255 temp_result = make_expanded_name(retval, expr_start,
17256 expr_end, temp_result);
17257 vim_free(retval);
17258 retval = temp_result;
17262 return retval;
17266 * Return TRUE if character "c" can be used in a variable or function name.
17267 * Does not include '{' or '}' for magic braces.
17269 static int
17270 eval_isnamec(c)
17271 int c;
17273 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
17277 * Return TRUE if character "c" can be used as the first character in a
17278 * variable or function name (excluding '{' and '}').
17280 static int
17281 eval_isnamec1(c)
17282 int c;
17284 return (ASCII_ISALPHA(c) || c == '_');
17288 * Set number v: variable to "val".
17290 void
17291 set_vim_var_nr(idx, val)
17292 int idx;
17293 long val;
17295 vimvars[idx].vv_nr = val;
17299 * Get number v: variable value.
17301 long
17302 get_vim_var_nr(idx)
17303 int idx;
17305 return vimvars[idx].vv_nr;
17308 #if defined(FEAT_AUTOCMD) || defined(PROTO)
17310 * Get string v: variable value. Uses a static buffer, can only be used once.
17312 char_u *
17313 get_vim_var_str(idx)
17314 int idx;
17316 return get_tv_string(&vimvars[idx].vv_tv);
17318 #endif
17321 * Set v:count, v:count1 and v:prevcount.
17323 void
17324 set_vcount(count, count1)
17325 long count;
17326 long count1;
17328 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
17329 vimvars[VV_COUNT].vv_nr = count;
17330 vimvars[VV_COUNT1].vv_nr = count1;
17334 * Set string v: variable to a copy of "val".
17336 void
17337 set_vim_var_string(idx, val, len)
17338 int idx;
17339 char_u *val;
17340 int len; /* length of "val" to use or -1 (whole string) */
17342 /* Need to do this (at least) once, since we can't initialize a union.
17343 * Will always be invoked when "v:progname" is set. */
17344 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
17346 vim_free(vimvars[idx].vv_str);
17347 if (val == NULL)
17348 vimvars[idx].vv_str = NULL;
17349 else if (len == -1)
17350 vimvars[idx].vv_str = vim_strsave(val);
17351 else
17352 vimvars[idx].vv_str = vim_strnsave(val, len);
17356 * Set v:register if needed.
17358 void
17359 set_reg_var(c)
17360 int c;
17362 char_u regname;
17364 if (c == 0 || c == ' ')
17365 regname = '"';
17366 else
17367 regname = c;
17368 /* Avoid free/alloc when the value is already right. */
17369 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
17370 set_vim_var_string(VV_REG, &regname, 1);
17374 * Get or set v:exception. If "oldval" == NULL, return the current value.
17375 * Otherwise, restore the value to "oldval" and return NULL.
17376 * Must always be called in pairs to save and restore v:exception! Does not
17377 * take care of memory allocations.
17379 char_u *
17380 v_exception(oldval)
17381 char_u *oldval;
17383 if (oldval == NULL)
17384 return vimvars[VV_EXCEPTION].vv_str;
17386 vimvars[VV_EXCEPTION].vv_str = oldval;
17387 return NULL;
17391 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
17392 * Otherwise, restore the value to "oldval" and return NULL.
17393 * Must always be called in pairs to save and restore v:throwpoint! Does not
17394 * take care of memory allocations.
17396 char_u *
17397 v_throwpoint(oldval)
17398 char_u *oldval;
17400 if (oldval == NULL)
17401 return vimvars[VV_THROWPOINT].vv_str;
17403 vimvars[VV_THROWPOINT].vv_str = oldval;
17404 return NULL;
17407 #if defined(FEAT_AUTOCMD) || defined(PROTO)
17409 * Set v:cmdarg.
17410 * If "eap" != NULL, use "eap" to generate the value and return the old value.
17411 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
17412 * Must always be called in pairs!
17414 char_u *
17415 set_cmdarg(eap, oldarg)
17416 exarg_T *eap;
17417 char_u *oldarg;
17419 char_u *oldval;
17420 char_u *newval;
17421 unsigned len;
17423 oldval = vimvars[VV_CMDARG].vv_str;
17424 if (eap == NULL)
17426 vim_free(oldval);
17427 vimvars[VV_CMDARG].vv_str = oldarg;
17428 return NULL;
17431 if (eap->force_bin == FORCE_BIN)
17432 len = 6;
17433 else if (eap->force_bin == FORCE_NOBIN)
17434 len = 8;
17435 else
17436 len = 0;
17438 if (eap->read_edit)
17439 len += 7;
17441 if (eap->force_ff != 0)
17442 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
17443 # ifdef FEAT_MBYTE
17444 if (eap->force_enc != 0)
17445 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
17446 if (eap->bad_char != 0)
17447 len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
17448 # endif
17450 newval = alloc(len + 1);
17451 if (newval == NULL)
17452 return NULL;
17454 if (eap->force_bin == FORCE_BIN)
17455 sprintf((char *)newval, " ++bin");
17456 else if (eap->force_bin == FORCE_NOBIN)
17457 sprintf((char *)newval, " ++nobin");
17458 else
17459 *newval = NUL;
17461 if (eap->read_edit)
17462 STRCAT(newval, " ++edit");
17464 if (eap->force_ff != 0)
17465 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
17466 eap->cmd + eap->force_ff);
17467 # ifdef FEAT_MBYTE
17468 if (eap->force_enc != 0)
17469 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
17470 eap->cmd + eap->force_enc);
17471 if (eap->bad_char != 0)
17472 sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
17473 eap->cmd + eap->bad_char);
17474 # endif
17475 vimvars[VV_CMDARG].vv_str = newval;
17476 return oldval;
17478 #endif
17481 * Get the value of internal variable "name".
17482 * Return OK or FAIL.
17484 static int
17485 get_var_tv(name, len, rettv, verbose)
17486 char_u *name;
17487 int len; /* length of "name" */
17488 typval_T *rettv; /* NULL when only checking existence */
17489 int verbose; /* may give error message */
17491 int ret = OK;
17492 typval_T *tv = NULL;
17493 typval_T atv;
17494 dictitem_T *v;
17495 int cc;
17497 /* truncate the name, so that we can use strcmp() */
17498 cc = name[len];
17499 name[len] = NUL;
17502 * Check for "b:changedtick".
17504 if (STRCMP(name, "b:changedtick") == 0)
17506 atv.v_type = VAR_NUMBER;
17507 atv.vval.v_number = curbuf->b_changedtick;
17508 tv = &atv;
17512 * Check for user-defined variables.
17514 else
17516 v = find_var(name, NULL);
17517 if (v != NULL)
17518 tv = &v->di_tv;
17521 if (tv == NULL)
17523 if (rettv != NULL && verbose)
17524 EMSG2(_(e_undefvar), name);
17525 ret = FAIL;
17527 else if (rettv != NULL)
17528 copy_tv(tv, rettv);
17530 name[len] = cc;
17532 return ret;
17536 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
17537 * Also handle function call with Funcref variable: func(expr)
17538 * Can all be combined: dict.func(expr)[idx]['func'](expr)
17540 static int
17541 handle_subscript(arg, rettv, evaluate, verbose)
17542 char_u **arg;
17543 typval_T *rettv;
17544 int evaluate; /* do more than finding the end */
17545 int verbose; /* give error messages */
17547 int ret = OK;
17548 dict_T *selfdict = NULL;
17549 char_u *s;
17550 int len;
17551 typval_T functv;
17553 while (ret == OK
17554 && (**arg == '['
17555 || (**arg == '.' && rettv->v_type == VAR_DICT)
17556 || (**arg == '(' && rettv->v_type == VAR_FUNC))
17557 && !vim_iswhite(*(*arg - 1)))
17559 if (**arg == '(')
17561 /* need to copy the funcref so that we can clear rettv */
17562 functv = *rettv;
17563 rettv->v_type = VAR_UNKNOWN;
17565 /* Invoke the function. Recursive! */
17566 s = functv.vval.v_string;
17567 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
17568 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
17569 &len, evaluate, selfdict);
17571 /* Clear the funcref afterwards, so that deleting it while
17572 * evaluating the arguments is possible (see test55). */
17573 clear_tv(&functv);
17575 /* Stop the expression evaluation when immediately aborting on
17576 * error, or when an interrupt occurred or an exception was thrown
17577 * but not caught. */
17578 if (aborting())
17580 if (ret == OK)
17581 clear_tv(rettv);
17582 ret = FAIL;
17584 dict_unref(selfdict);
17585 selfdict = NULL;
17587 else /* **arg == '[' || **arg == '.' */
17589 dict_unref(selfdict);
17590 if (rettv->v_type == VAR_DICT)
17592 selfdict = rettv->vval.v_dict;
17593 if (selfdict != NULL)
17594 ++selfdict->dv_refcount;
17596 else
17597 selfdict = NULL;
17598 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
17600 clear_tv(rettv);
17601 ret = FAIL;
17605 dict_unref(selfdict);
17606 return ret;
17610 * Allocate memory for a variable type-value, and make it emtpy (0 or NULL
17611 * value).
17613 static typval_T *
17614 alloc_tv()
17616 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
17620 * Allocate memory for a variable type-value, and assign a string to it.
17621 * The string "s" must have been allocated, it is consumed.
17622 * Return NULL for out of memory, the variable otherwise.
17624 static typval_T *
17625 alloc_string_tv(s)
17626 char_u *s;
17628 typval_T *rettv;
17630 rettv = alloc_tv();
17631 if (rettv != NULL)
17633 rettv->v_type = VAR_STRING;
17634 rettv->vval.v_string = s;
17636 else
17637 vim_free(s);
17638 return rettv;
17642 * Free the memory for a variable type-value.
17644 void
17645 free_tv(varp)
17646 typval_T *varp;
17648 if (varp != NULL)
17650 switch (varp->v_type)
17652 case VAR_FUNC:
17653 func_unref(varp->vval.v_string);
17654 /*FALLTHROUGH*/
17655 case VAR_STRING:
17656 vim_free(varp->vval.v_string);
17657 break;
17658 case VAR_LIST:
17659 list_unref(varp->vval.v_list);
17660 break;
17661 case VAR_DICT:
17662 dict_unref(varp->vval.v_dict);
17663 break;
17664 case VAR_NUMBER:
17665 case VAR_UNKNOWN:
17666 break;
17667 default:
17668 EMSG2(_(e_intern2), "free_tv()");
17669 break;
17671 vim_free(varp);
17676 * Free the memory for a variable value and set the value to NULL or 0.
17678 void
17679 clear_tv(varp)
17680 typval_T *varp;
17682 if (varp != NULL)
17684 switch (varp->v_type)
17686 case VAR_FUNC:
17687 func_unref(varp->vval.v_string);
17688 /*FALLTHROUGH*/
17689 case VAR_STRING:
17690 vim_free(varp->vval.v_string);
17691 varp->vval.v_string = NULL;
17692 break;
17693 case VAR_LIST:
17694 list_unref(varp->vval.v_list);
17695 varp->vval.v_list = NULL;
17696 break;
17697 case VAR_DICT:
17698 dict_unref(varp->vval.v_dict);
17699 varp->vval.v_dict = NULL;
17700 break;
17701 case VAR_NUMBER:
17702 varp->vval.v_number = 0;
17703 break;
17704 case VAR_UNKNOWN:
17705 break;
17706 default:
17707 EMSG2(_(e_intern2), "clear_tv()");
17709 varp->v_lock = 0;
17714 * Set the value of a variable to NULL without freeing items.
17716 static void
17717 init_tv(varp)
17718 typval_T *varp;
17720 if (varp != NULL)
17721 vim_memset(varp, 0, sizeof(typval_T));
17725 * Get the number value of a variable.
17726 * If it is a String variable, uses vim_str2nr().
17727 * For incompatible types, return 0.
17728 * get_tv_number_chk() is similar to get_tv_number(), but informs the
17729 * caller of incompatible types: it sets *denote to TRUE if "denote"
17730 * is not NULL or returns -1 otherwise.
17732 static long
17733 get_tv_number(varp)
17734 typval_T *varp;
17736 int error = FALSE;
17738 return get_tv_number_chk(varp, &error); /* return 0L on error */
17741 long
17742 get_tv_number_chk(varp, denote)
17743 typval_T *varp;
17744 int *denote;
17746 long n = 0L;
17748 switch (varp->v_type)
17750 case VAR_NUMBER:
17751 return (long)(varp->vval.v_number);
17752 case VAR_FUNC:
17753 EMSG(_("E703: Using a Funcref as a number"));
17754 break;
17755 case VAR_STRING:
17756 if (varp->vval.v_string != NULL)
17757 vim_str2nr(varp->vval.v_string, NULL, NULL,
17758 TRUE, TRUE, &n, NULL);
17759 return n;
17760 case VAR_LIST:
17761 EMSG(_("E745: Using a List as a number"));
17762 break;
17763 case VAR_DICT:
17764 EMSG(_("E728: Using a Dictionary as a number"));
17765 break;
17766 default:
17767 EMSG2(_(e_intern2), "get_tv_number()");
17768 break;
17770 if (denote == NULL) /* useful for values that must be unsigned */
17771 n = -1;
17772 else
17773 *denote = TRUE;
17774 return n;
17778 * Get the lnum from the first argument.
17779 * Also accepts ".", "$", etc., but that only works for the current buffer.
17780 * Returns -1 on error.
17782 static linenr_T
17783 get_tv_lnum(argvars)
17784 typval_T *argvars;
17786 typval_T rettv;
17787 linenr_T lnum;
17789 lnum = get_tv_number_chk(&argvars[0], NULL);
17790 if (lnum == 0) /* no valid number, try using line() */
17792 rettv.v_type = VAR_NUMBER;
17793 f_line(argvars, &rettv);
17794 lnum = rettv.vval.v_number;
17795 clear_tv(&rettv);
17797 return lnum;
17801 * Get the lnum from the first argument.
17802 * Also accepts "$", then "buf" is used.
17803 * Returns 0 on error.
17805 static linenr_T
17806 get_tv_lnum_buf(argvars, buf)
17807 typval_T *argvars;
17808 buf_T *buf;
17810 if (argvars[0].v_type == VAR_STRING
17811 && argvars[0].vval.v_string != NULL
17812 && argvars[0].vval.v_string[0] == '$'
17813 && buf != NULL)
17814 return buf->b_ml.ml_line_count;
17815 return get_tv_number_chk(&argvars[0], NULL);
17819 * Get the string value of a variable.
17820 * If it is a Number variable, the number is converted into a string.
17821 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
17822 * get_tv_string_buf() uses a given buffer.
17823 * If the String variable has never been set, return an empty string.
17824 * Never returns NULL;
17825 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
17826 * NULL on error.
17828 static char_u *
17829 get_tv_string(varp)
17830 typval_T *varp;
17832 static char_u mybuf[NUMBUFLEN];
17834 return get_tv_string_buf(varp, mybuf);
17837 static char_u *
17838 get_tv_string_buf(varp, buf)
17839 typval_T *varp;
17840 char_u *buf;
17842 char_u *res = get_tv_string_buf_chk(varp, buf);
17844 return res != NULL ? res : (char_u *)"";
17847 char_u *
17848 get_tv_string_chk(varp)
17849 typval_T *varp;
17851 static char_u mybuf[NUMBUFLEN];
17853 return get_tv_string_buf_chk(varp, mybuf);
17856 static char_u *
17857 get_tv_string_buf_chk(varp, buf)
17858 typval_T *varp;
17859 char_u *buf;
17861 switch (varp->v_type)
17863 case VAR_NUMBER:
17864 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
17865 return buf;
17866 case VAR_FUNC:
17867 EMSG(_("E729: using Funcref as a String"));
17868 break;
17869 case VAR_LIST:
17870 EMSG(_("E730: using List as a String"));
17871 break;
17872 case VAR_DICT:
17873 EMSG(_("E731: using Dictionary as a String"));
17874 break;
17875 case VAR_STRING:
17876 if (varp->vval.v_string != NULL)
17877 return varp->vval.v_string;
17878 return (char_u *)"";
17879 default:
17880 EMSG2(_(e_intern2), "get_tv_string_buf()");
17881 break;
17883 return NULL;
17887 * Find variable "name" in the list of variables.
17888 * Return a pointer to it if found, NULL if not found.
17889 * Careful: "a:0" variables don't have a name.
17890 * When "htp" is not NULL we are writing to the variable, set "htp" to the
17891 * hashtab_T used.
17893 static dictitem_T *
17894 find_var(name, htp)
17895 char_u *name;
17896 hashtab_T **htp;
17898 char_u *varname;
17899 hashtab_T *ht;
17901 ht = find_var_ht(name, &varname);
17902 if (htp != NULL)
17903 *htp = ht;
17904 if (ht == NULL)
17905 return NULL;
17906 return find_var_in_ht(ht, varname, htp != NULL);
17910 * Find variable "varname" in hashtab "ht".
17911 * Returns NULL if not found.
17913 static dictitem_T *
17914 find_var_in_ht(ht, varname, writing)
17915 hashtab_T *ht;
17916 char_u *varname;
17917 int writing;
17919 hashitem_T *hi;
17921 if (*varname == NUL)
17923 /* Must be something like "s:", otherwise "ht" would be NULL. */
17924 switch (varname[-2])
17926 case 's': return &SCRIPT_SV(current_SID).sv_var;
17927 case 'g': return &globvars_var;
17928 case 'v': return &vimvars_var;
17929 case 'b': return &curbuf->b_bufvar;
17930 case 'w': return &curwin->w_winvar;
17931 #ifdef FEAT_WINDOWS
17932 case 't': return &curtab->tp_winvar;
17933 #endif
17934 case 'l': return current_funccal == NULL
17935 ? NULL : &current_funccal->l_vars_var;
17936 case 'a': return current_funccal == NULL
17937 ? NULL : &current_funccal->l_avars_var;
17939 return NULL;
17942 hi = hash_find(ht, varname);
17943 if (HASHITEM_EMPTY(hi))
17945 /* For global variables we may try auto-loading the script. If it
17946 * worked find the variable again. Don't auto-load a script if it was
17947 * loaded already, otherwise it would be loaded every time when
17948 * checking if a function name is a Funcref variable. */
17949 if (ht == &globvarht && !writing
17950 && script_autoload(varname, FALSE) && !aborting())
17951 hi = hash_find(ht, varname);
17952 if (HASHITEM_EMPTY(hi))
17953 return NULL;
17955 return HI2DI(hi);
17959 * Find the hashtab used for a variable name.
17960 * Set "varname" to the start of name without ':'.
17962 static hashtab_T *
17963 find_var_ht(name, varname)
17964 char_u *name;
17965 char_u **varname;
17967 hashitem_T *hi;
17969 if (name[1] != ':')
17971 /* The name must not start with a colon or #. */
17972 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
17973 return NULL;
17974 *varname = name;
17976 /* "version" is "v:version" in all scopes */
17977 hi = hash_find(&compat_hashtab, name);
17978 if (!HASHITEM_EMPTY(hi))
17979 return &compat_hashtab;
17981 if (current_funccal == NULL)
17982 return &globvarht; /* global variable */
17983 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
17985 *varname = name + 2;
17986 if (*name == 'g') /* global variable */
17987 return &globvarht;
17988 /* There must be no ':' or '#' in the rest of the name, unless g: is used
17990 if (vim_strchr(name + 2, ':') != NULL
17991 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
17992 return NULL;
17993 if (*name == 'b') /* buffer variable */
17994 return &curbuf->b_vars.dv_hashtab;
17995 if (*name == 'w') /* window variable */
17996 return &curwin->w_vars.dv_hashtab;
17997 #ifdef FEAT_WINDOWS
17998 if (*name == 't') /* tab page variable */
17999 return &curtab->tp_vars.dv_hashtab;
18000 #endif
18001 if (*name == 'v') /* v: variable */
18002 return &vimvarht;
18003 if (*name == 'a' && current_funccal != NULL) /* function argument */
18004 return &current_funccal->l_avars.dv_hashtab;
18005 if (*name == 'l' && current_funccal != NULL) /* local function variable */
18006 return &current_funccal->l_vars.dv_hashtab;
18007 if (*name == 's' /* script variable */
18008 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
18009 return &SCRIPT_VARS(current_SID);
18010 return NULL;
18014 * Get the string value of a (global/local) variable.
18015 * Returns NULL when it doesn't exist.
18017 char_u *
18018 get_var_value(name)
18019 char_u *name;
18021 dictitem_T *v;
18023 v = find_var(name, NULL);
18024 if (v == NULL)
18025 return NULL;
18026 return get_tv_string(&v->di_tv);
18030 * Allocate a new hashtab for a sourced script. It will be used while
18031 * sourcing this script and when executing functions defined in the script.
18033 void
18034 new_script_vars(id)
18035 scid_T id;
18037 int i;
18038 hashtab_T *ht;
18039 scriptvar_T *sv;
18041 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
18043 /* Re-allocating ga_data means that an ht_array pointing to
18044 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
18045 * at its init value. Also reset "v_dict", it's always the same. */
18046 for (i = 1; i <= ga_scripts.ga_len; ++i)
18048 ht = &SCRIPT_VARS(i);
18049 if (ht->ht_mask == HT_INIT_SIZE - 1)
18050 ht->ht_array = ht->ht_smallarray;
18051 sv = &SCRIPT_SV(i);
18052 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
18055 while (ga_scripts.ga_len < id)
18057 sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
18058 init_var_dict(&sv->sv_dict, &sv->sv_var);
18059 ++ga_scripts.ga_len;
18065 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
18066 * point to it.
18068 void
18069 init_var_dict(dict, dict_var)
18070 dict_T *dict;
18071 dictitem_T *dict_var;
18073 hash_init(&dict->dv_hashtab);
18074 dict->dv_refcount = 99999;
18075 dict_var->di_tv.vval.v_dict = dict;
18076 dict_var->di_tv.v_type = VAR_DICT;
18077 dict_var->di_tv.v_lock = VAR_FIXED;
18078 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
18079 dict_var->di_key[0] = NUL;
18083 * Clean up a list of internal variables.
18084 * Frees all allocated variables and the value they contain.
18085 * Clears hashtab "ht", does not free it.
18087 void
18088 vars_clear(ht)
18089 hashtab_T *ht;
18091 vars_clear_ext(ht, TRUE);
18095 * Like vars_clear(), but only free the value if "free_val" is TRUE.
18097 static void
18098 vars_clear_ext(ht, free_val)
18099 hashtab_T *ht;
18100 int free_val;
18102 int todo;
18103 hashitem_T *hi;
18104 dictitem_T *v;
18106 hash_lock(ht);
18107 todo = (int)ht->ht_used;
18108 for (hi = ht->ht_array; todo > 0; ++hi)
18110 if (!HASHITEM_EMPTY(hi))
18112 --todo;
18114 /* Free the variable. Don't remove it from the hashtab,
18115 * ht_array might change then. hash_clear() takes care of it
18116 * later. */
18117 v = HI2DI(hi);
18118 if (free_val)
18119 clear_tv(&v->di_tv);
18120 if ((v->di_flags & DI_FLAGS_FIX) == 0)
18121 vim_free(v);
18124 hash_clear(ht);
18125 ht->ht_used = 0;
18129 * Delete a variable from hashtab "ht" at item "hi".
18130 * Clear the variable value and free the dictitem.
18132 static void
18133 delete_var(ht, hi)
18134 hashtab_T *ht;
18135 hashitem_T *hi;
18137 dictitem_T *di = HI2DI(hi);
18139 hash_remove(ht, hi);
18140 clear_tv(&di->di_tv);
18141 vim_free(di);
18145 * List the value of one internal variable.
18147 static void
18148 list_one_var(v, prefix, first)
18149 dictitem_T *v;
18150 char_u *prefix;
18151 int *first;
18153 char_u *tofree;
18154 char_u *s;
18155 char_u numbuf[NUMBUFLEN];
18157 s = echo_string(&v->di_tv, &tofree, numbuf, ++current_copyID);
18158 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
18159 s == NULL ? (char_u *)"" : s, first);
18160 vim_free(tofree);
18163 static void
18164 list_one_var_a(prefix, name, type, string, first)
18165 char_u *prefix;
18166 char_u *name;
18167 int type;
18168 char_u *string;
18169 int *first; /* when TRUE clear rest of screen and set to FALSE */
18171 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
18172 msg_start();
18173 msg_puts(prefix);
18174 if (name != NULL) /* "a:" vars don't have a name stored */
18175 msg_puts(name);
18176 msg_putchar(' ');
18177 msg_advance(22);
18178 if (type == VAR_NUMBER)
18179 msg_putchar('#');
18180 else if (type == VAR_FUNC)
18181 msg_putchar('*');
18182 else if (type == VAR_LIST)
18184 msg_putchar('[');
18185 if (*string == '[')
18186 ++string;
18188 else if (type == VAR_DICT)
18190 msg_putchar('{');
18191 if (*string == '{')
18192 ++string;
18194 else
18195 msg_putchar(' ');
18197 msg_outtrans(string);
18199 if (type == VAR_FUNC)
18200 msg_puts((char_u *)"()");
18201 if (*first)
18203 msg_clr_eos();
18204 *first = FALSE;
18209 * Set variable "name" to value in "tv".
18210 * If the variable already exists, the value is updated.
18211 * Otherwise the variable is created.
18213 static void
18214 set_var(name, tv, copy)
18215 char_u *name;
18216 typval_T *tv;
18217 int copy; /* make copy of value in "tv" */
18219 dictitem_T *v;
18220 char_u *varname;
18221 hashtab_T *ht;
18222 char_u *p;
18224 if (tv->v_type == VAR_FUNC)
18226 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
18227 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
18228 ? name[2] : name[0]))
18230 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
18231 return;
18233 if (function_exists(name))
18235 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
18236 name);
18237 return;
18241 ht = find_var_ht(name, &varname);
18242 if (ht == NULL || *varname == NUL)
18244 EMSG2(_(e_illvar), name);
18245 return;
18248 v = find_var_in_ht(ht, varname, TRUE);
18249 if (v != NULL)
18251 /* existing variable, need to clear the value */
18252 if (var_check_ro(v->di_flags, name)
18253 || tv_check_lock(v->di_tv.v_lock, name))
18254 return;
18255 if (v->di_tv.v_type != tv->v_type
18256 && !((v->di_tv.v_type == VAR_STRING
18257 || v->di_tv.v_type == VAR_NUMBER)
18258 && (tv->v_type == VAR_STRING
18259 || tv->v_type == VAR_NUMBER)))
18261 EMSG2(_("E706: Variable type mismatch for: %s"), name);
18262 return;
18266 * Handle setting internal v: variables separately: we don't change
18267 * the type.
18269 if (ht == &vimvarht)
18271 if (v->di_tv.v_type == VAR_STRING)
18273 vim_free(v->di_tv.vval.v_string);
18274 if (copy || tv->v_type != VAR_STRING)
18275 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
18276 else
18278 /* Take over the string to avoid an extra alloc/free. */
18279 v->di_tv.vval.v_string = tv->vval.v_string;
18280 tv->vval.v_string = NULL;
18283 else if (v->di_tv.v_type != VAR_NUMBER)
18284 EMSG2(_(e_intern2), "set_var()");
18285 else
18286 v->di_tv.vval.v_number = get_tv_number(tv);
18287 return;
18290 clear_tv(&v->di_tv);
18292 else /* add a new variable */
18294 /* Can't add "v:" variable. */
18295 if (ht == &vimvarht)
18297 EMSG2(_(e_illvar), name);
18298 return;
18301 /* Make sure the variable name is valid. */
18302 for (p = varname; *p != NUL; ++p)
18303 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
18304 && *p != AUTOLOAD_CHAR)
18306 EMSG2(_(e_illvar), varname);
18307 return;
18310 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
18311 + STRLEN(varname)));
18312 if (v == NULL)
18313 return;
18314 STRCPY(v->di_key, varname);
18315 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
18317 vim_free(v);
18318 return;
18320 v->di_flags = 0;
18323 if (copy || tv->v_type == VAR_NUMBER)
18324 copy_tv(tv, &v->di_tv);
18325 else
18327 v->di_tv = *tv;
18328 v->di_tv.v_lock = 0;
18329 init_tv(tv);
18334 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
18335 * Also give an error message.
18337 static int
18338 var_check_ro(flags, name)
18339 int flags;
18340 char_u *name;
18342 if (flags & DI_FLAGS_RO)
18344 EMSG2(_(e_readonlyvar), name);
18345 return TRUE;
18347 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
18349 EMSG2(_(e_readonlysbx), name);
18350 return TRUE;
18352 return FALSE;
18356 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
18357 * Also give an error message.
18359 static int
18360 var_check_fixed(flags, name)
18361 int flags;
18362 char_u *name;
18364 if (flags & DI_FLAGS_FIX)
18366 EMSG2(_("E795: Cannot delete variable %s"), name);
18367 return TRUE;
18369 return FALSE;
18373 * Return TRUE if typeval "tv" is set to be locked (immutable).
18374 * Also give an error message, using "name".
18376 static int
18377 tv_check_lock(lock, name)
18378 int lock;
18379 char_u *name;
18381 if (lock & VAR_LOCKED)
18383 EMSG2(_("E741: Value is locked: %s"),
18384 name == NULL ? (char_u *)_("Unknown") : name);
18385 return TRUE;
18387 if (lock & VAR_FIXED)
18389 EMSG2(_("E742: Cannot change value of %s"),
18390 name == NULL ? (char_u *)_("Unknown") : name);
18391 return TRUE;
18393 return FALSE;
18397 * Copy the values from typval_T "from" to typval_T "to".
18398 * When needed allocates string or increases reference count.
18399 * Does not make a copy of a list or dict but copies the reference!
18401 static void
18402 copy_tv(from, to)
18403 typval_T *from;
18404 typval_T *to;
18406 to->v_type = from->v_type;
18407 to->v_lock = 0;
18408 switch (from->v_type)
18410 case VAR_NUMBER:
18411 to->vval.v_number = from->vval.v_number;
18412 break;
18413 case VAR_STRING:
18414 case VAR_FUNC:
18415 if (from->vval.v_string == NULL)
18416 to->vval.v_string = NULL;
18417 else
18419 to->vval.v_string = vim_strsave(from->vval.v_string);
18420 if (from->v_type == VAR_FUNC)
18421 func_ref(to->vval.v_string);
18423 break;
18424 case VAR_LIST:
18425 if (from->vval.v_list == NULL)
18426 to->vval.v_list = NULL;
18427 else
18429 to->vval.v_list = from->vval.v_list;
18430 ++to->vval.v_list->lv_refcount;
18432 break;
18433 case VAR_DICT:
18434 if (from->vval.v_dict == NULL)
18435 to->vval.v_dict = NULL;
18436 else
18438 to->vval.v_dict = from->vval.v_dict;
18439 ++to->vval.v_dict->dv_refcount;
18441 break;
18442 default:
18443 EMSG2(_(e_intern2), "copy_tv()");
18444 break;
18449 * Make a copy of an item.
18450 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
18451 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
18452 * reference to an already copied list/dict can be used.
18453 * Returns FAIL or OK.
18455 static int
18456 item_copy(from, to, deep, copyID)
18457 typval_T *from;
18458 typval_T *to;
18459 int deep;
18460 int copyID;
18462 static int recurse = 0;
18463 int ret = OK;
18465 if (recurse >= DICT_MAXNEST)
18467 EMSG(_("E698: variable nested too deep for making a copy"));
18468 return FAIL;
18470 ++recurse;
18472 switch (from->v_type)
18474 case VAR_NUMBER:
18475 case VAR_STRING:
18476 case VAR_FUNC:
18477 copy_tv(from, to);
18478 break;
18479 case VAR_LIST:
18480 to->v_type = VAR_LIST;
18481 to->v_lock = 0;
18482 if (from->vval.v_list == NULL)
18483 to->vval.v_list = NULL;
18484 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
18486 /* use the copy made earlier */
18487 to->vval.v_list = from->vval.v_list->lv_copylist;
18488 ++to->vval.v_list->lv_refcount;
18490 else
18491 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
18492 if (to->vval.v_list == NULL)
18493 ret = FAIL;
18494 break;
18495 case VAR_DICT:
18496 to->v_type = VAR_DICT;
18497 to->v_lock = 0;
18498 if (from->vval.v_dict == NULL)
18499 to->vval.v_dict = NULL;
18500 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
18502 /* use the copy made earlier */
18503 to->vval.v_dict = from->vval.v_dict->dv_copydict;
18504 ++to->vval.v_dict->dv_refcount;
18506 else
18507 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
18508 if (to->vval.v_dict == NULL)
18509 ret = FAIL;
18510 break;
18511 default:
18512 EMSG2(_(e_intern2), "item_copy()");
18513 ret = FAIL;
18515 --recurse;
18516 return ret;
18520 * ":echo expr1 ..." print each argument separated with a space, add a
18521 * newline at the end.
18522 * ":echon expr1 ..." print each argument plain.
18524 void
18525 ex_echo(eap)
18526 exarg_T *eap;
18528 char_u *arg = eap->arg;
18529 typval_T rettv;
18530 char_u *tofree;
18531 char_u *p;
18532 int needclr = TRUE;
18533 int atstart = TRUE;
18534 char_u numbuf[NUMBUFLEN];
18536 if (eap->skip)
18537 ++emsg_skip;
18538 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
18540 p = arg;
18541 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
18544 * Report the invalid expression unless the expression evaluation
18545 * has been cancelled due to an aborting error, an interrupt, or an
18546 * exception.
18548 if (!aborting())
18549 EMSG2(_(e_invexpr2), p);
18550 break;
18552 if (!eap->skip)
18554 if (atstart)
18556 atstart = FALSE;
18557 /* Call msg_start() after eval1(), evaluating the expression
18558 * may cause a message to appear. */
18559 if (eap->cmdidx == CMD_echo)
18560 msg_start();
18562 else if (eap->cmdidx == CMD_echo)
18563 msg_puts_attr((char_u *)" ", echo_attr);
18564 p = echo_string(&rettv, &tofree, numbuf, ++current_copyID);
18565 if (p != NULL)
18566 for ( ; *p != NUL && !got_int; ++p)
18568 if (*p == '\n' || *p == '\r' || *p == TAB)
18570 if (*p != TAB && needclr)
18572 /* remove any text still there from the command */
18573 msg_clr_eos();
18574 needclr = FALSE;
18576 msg_putchar_attr(*p, echo_attr);
18578 else
18580 #ifdef FEAT_MBYTE
18581 if (has_mbyte)
18583 int i = (*mb_ptr2len)(p);
18585 (void)msg_outtrans_len_attr(p, i, echo_attr);
18586 p += i - 1;
18588 else
18589 #endif
18590 (void)msg_outtrans_len_attr(p, 1, echo_attr);
18593 vim_free(tofree);
18595 clear_tv(&rettv);
18596 arg = skipwhite(arg);
18598 eap->nextcmd = check_nextcmd(arg);
18600 if (eap->skip)
18601 --emsg_skip;
18602 else
18604 /* remove text that may still be there from the command */
18605 if (needclr)
18606 msg_clr_eos();
18607 if (eap->cmdidx == CMD_echo)
18608 msg_end();
18613 * ":echohl {name}".
18615 void
18616 ex_echohl(eap)
18617 exarg_T *eap;
18619 int id;
18621 id = syn_name2id(eap->arg);
18622 if (id == 0)
18623 echo_attr = 0;
18624 else
18625 echo_attr = syn_id2attr(id);
18629 * ":execute expr1 ..." execute the result of an expression.
18630 * ":echomsg expr1 ..." Print a message
18631 * ":echoerr expr1 ..." Print an error
18632 * Each gets spaces around each argument and a newline at the end for
18633 * echo commands
18635 void
18636 ex_execute(eap)
18637 exarg_T *eap;
18639 char_u *arg = eap->arg;
18640 typval_T rettv;
18641 int ret = OK;
18642 char_u *p;
18643 garray_T ga;
18644 int len;
18645 int save_did_emsg;
18647 ga_init2(&ga, 1, 80);
18649 if (eap->skip)
18650 ++emsg_skip;
18651 while (*arg != NUL && *arg != '|' && *arg != '\n')
18653 p = arg;
18654 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
18657 * Report the invalid expression unless the expression evaluation
18658 * has been cancelled due to an aborting error, an interrupt, or an
18659 * exception.
18661 if (!aborting())
18662 EMSG2(_(e_invexpr2), p);
18663 ret = FAIL;
18664 break;
18667 if (!eap->skip)
18669 p = get_tv_string(&rettv);
18670 len = (int)STRLEN(p);
18671 if (ga_grow(&ga, len + 2) == FAIL)
18673 clear_tv(&rettv);
18674 ret = FAIL;
18675 break;
18677 if (ga.ga_len)
18678 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
18679 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
18680 ga.ga_len += len;
18683 clear_tv(&rettv);
18684 arg = skipwhite(arg);
18687 if (ret != FAIL && ga.ga_data != NULL)
18689 if (eap->cmdidx == CMD_echomsg)
18691 MSG_ATTR(ga.ga_data, echo_attr);
18692 out_flush();
18694 else if (eap->cmdidx == CMD_echoerr)
18696 /* We don't want to abort following commands, restore did_emsg. */
18697 save_did_emsg = did_emsg;
18698 EMSG((char_u *)ga.ga_data);
18699 if (!force_abort)
18700 did_emsg = save_did_emsg;
18702 else if (eap->cmdidx == CMD_execute)
18703 do_cmdline((char_u *)ga.ga_data,
18704 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
18707 ga_clear(&ga);
18709 if (eap->skip)
18710 --emsg_skip;
18712 eap->nextcmd = check_nextcmd(arg);
18716 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
18717 * "arg" points to the "&" or '+' when called, to "option" when returning.
18718 * Returns NULL when no option name found. Otherwise pointer to the char
18719 * after the option name.
18721 static char_u *
18722 find_option_end(arg, opt_flags)
18723 char_u **arg;
18724 int *opt_flags;
18726 char_u *p = *arg;
18728 ++p;
18729 if (*p == 'g' && p[1] == ':')
18731 *opt_flags = OPT_GLOBAL;
18732 p += 2;
18734 else if (*p == 'l' && p[1] == ':')
18736 *opt_flags = OPT_LOCAL;
18737 p += 2;
18739 else
18740 *opt_flags = 0;
18742 if (!ASCII_ISALPHA(*p))
18743 return NULL;
18744 *arg = p;
18746 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
18747 p += 4; /* termcap option */
18748 else
18749 while (ASCII_ISALPHA(*p))
18750 ++p;
18751 return p;
18755 * ":function"
18757 void
18758 ex_function(eap)
18759 exarg_T *eap;
18761 char_u *theline;
18762 int j;
18763 int c;
18764 int saved_did_emsg;
18765 char_u *name = NULL;
18766 char_u *p;
18767 char_u *arg;
18768 char_u *line_arg = NULL;
18769 garray_T newargs;
18770 garray_T newlines;
18771 int varargs = FALSE;
18772 int mustend = FALSE;
18773 int flags = 0;
18774 ufunc_T *fp;
18775 int indent;
18776 int nesting;
18777 char_u *skip_until = NULL;
18778 dictitem_T *v;
18779 funcdict_T fudi;
18780 static int func_nr = 0; /* number for nameless function */
18781 int paren;
18782 hashtab_T *ht;
18783 int todo;
18784 hashitem_T *hi;
18785 int sourcing_lnum_off;
18788 * ":function" without argument: list functions.
18790 if (ends_excmd(*eap->arg))
18792 if (!eap->skip)
18794 todo = (int)func_hashtab.ht_used;
18795 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
18797 if (!HASHITEM_EMPTY(hi))
18799 --todo;
18800 fp = HI2UF(hi);
18801 if (!isdigit(*fp->uf_name))
18802 list_func_head(fp, FALSE);
18806 eap->nextcmd = check_nextcmd(eap->arg);
18807 return;
18811 * ":function /pat": list functions matching pattern.
18813 if (*eap->arg == '/')
18815 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
18816 if (!eap->skip)
18818 regmatch_T regmatch;
18820 c = *p;
18821 *p = NUL;
18822 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
18823 *p = c;
18824 if (regmatch.regprog != NULL)
18826 regmatch.rm_ic = p_ic;
18828 todo = (int)func_hashtab.ht_used;
18829 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
18831 if (!HASHITEM_EMPTY(hi))
18833 --todo;
18834 fp = HI2UF(hi);
18835 if (!isdigit(*fp->uf_name)
18836 && vim_regexec(&regmatch, fp->uf_name, 0))
18837 list_func_head(fp, FALSE);
18842 if (*p == '/')
18843 ++p;
18844 eap->nextcmd = check_nextcmd(p);
18845 return;
18849 * Get the function name. There are these situations:
18850 * func normal function name
18851 * "name" == func, "fudi.fd_dict" == NULL
18852 * dict.func new dictionary entry
18853 * "name" == NULL, "fudi.fd_dict" set,
18854 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
18855 * dict.func existing dict entry with a Funcref
18856 * "name" == func, "fudi.fd_dict" set,
18857 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
18858 * dict.func existing dict entry that's not a Funcref
18859 * "name" == NULL, "fudi.fd_dict" set,
18860 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
18862 p = eap->arg;
18863 name = trans_function_name(&p, eap->skip, 0, &fudi);
18864 paren = (vim_strchr(p, '(') != NULL);
18865 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
18868 * Return on an invalid expression in braces, unless the expression
18869 * evaluation has been cancelled due to an aborting error, an
18870 * interrupt, or an exception.
18872 if (!aborting())
18874 if (!eap->skip && fudi.fd_newkey != NULL)
18875 EMSG2(_(e_dictkey), fudi.fd_newkey);
18876 vim_free(fudi.fd_newkey);
18877 return;
18879 else
18880 eap->skip = TRUE;
18883 /* An error in a function call during evaluation of an expression in magic
18884 * braces should not cause the function not to be defined. */
18885 saved_did_emsg = did_emsg;
18886 did_emsg = FALSE;
18889 * ":function func" with only function name: list function.
18891 if (!paren)
18893 if (!ends_excmd(*skipwhite(p)))
18895 EMSG(_(e_trailing));
18896 goto ret_free;
18898 eap->nextcmd = check_nextcmd(p);
18899 if (eap->nextcmd != NULL)
18900 *p = NUL;
18901 if (!eap->skip && !got_int)
18903 fp = find_func(name);
18904 if (fp != NULL)
18906 list_func_head(fp, TRUE);
18907 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
18909 if (FUNCLINE(fp, j) == NULL)
18910 continue;
18911 msg_putchar('\n');
18912 msg_outnum((long)(j + 1));
18913 if (j < 9)
18914 msg_putchar(' ');
18915 if (j < 99)
18916 msg_putchar(' ');
18917 msg_prt_line(FUNCLINE(fp, j), FALSE);
18918 out_flush(); /* show a line at a time */
18919 ui_breakcheck();
18921 if (!got_int)
18923 msg_putchar('\n');
18924 msg_puts((char_u *)" endfunction");
18927 else
18928 emsg_funcname("E123: Undefined function: %s", name);
18930 goto ret_free;
18934 * ":function name(arg1, arg2)" Define function.
18936 p = skipwhite(p);
18937 if (*p != '(')
18939 if (!eap->skip)
18941 EMSG2(_("E124: Missing '(': %s"), eap->arg);
18942 goto ret_free;
18944 /* attempt to continue by skipping some text */
18945 if (vim_strchr(p, '(') != NULL)
18946 p = vim_strchr(p, '(');
18948 p = skipwhite(p + 1);
18950 ga_init2(&newargs, (int)sizeof(char_u *), 3);
18951 ga_init2(&newlines, (int)sizeof(char_u *), 3);
18953 if (!eap->skip)
18955 /* Check the name of the function. Unless it's a dictionary function
18956 * (that we are overwriting). */
18957 if (name != NULL)
18958 arg = name;
18959 else
18960 arg = fudi.fd_newkey;
18961 if (arg != NULL && (fudi.fd_di == NULL
18962 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
18964 if (*arg == K_SPECIAL)
18965 j = 3;
18966 else
18967 j = 0;
18968 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
18969 : eval_isnamec(arg[j])))
18970 ++j;
18971 if (arg[j] != NUL)
18972 emsg_funcname(_(e_invarg2), arg);
18977 * Isolate the arguments: "arg1, arg2, ...)"
18979 while (*p != ')')
18981 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
18983 varargs = TRUE;
18984 p += 3;
18985 mustend = TRUE;
18987 else
18989 arg = p;
18990 while (ASCII_ISALNUM(*p) || *p == '_')
18991 ++p;
18992 if (arg == p || isdigit(*arg)
18993 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
18994 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
18996 if (!eap->skip)
18997 EMSG2(_("E125: Illegal argument: %s"), arg);
18998 break;
19000 if (ga_grow(&newargs, 1) == FAIL)
19001 goto erret;
19002 c = *p;
19003 *p = NUL;
19004 arg = vim_strsave(arg);
19005 if (arg == NULL)
19006 goto erret;
19007 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
19008 *p = c;
19009 newargs.ga_len++;
19010 if (*p == ',')
19011 ++p;
19012 else
19013 mustend = TRUE;
19015 p = skipwhite(p);
19016 if (mustend && *p != ')')
19018 if (!eap->skip)
19019 EMSG2(_(e_invarg2), eap->arg);
19020 break;
19023 ++p; /* skip the ')' */
19025 /* find extra arguments "range", "dict" and "abort" */
19026 for (;;)
19028 p = skipwhite(p);
19029 if (STRNCMP(p, "range", 5) == 0)
19031 flags |= FC_RANGE;
19032 p += 5;
19034 else if (STRNCMP(p, "dict", 4) == 0)
19036 flags |= FC_DICT;
19037 p += 4;
19039 else if (STRNCMP(p, "abort", 5) == 0)
19041 flags |= FC_ABORT;
19042 p += 5;
19044 else
19045 break;
19048 /* When there is a line break use what follows for the function body.
19049 * Makes 'exe "func Test()\n...\nendfunc"' work. */
19050 if (*p == '\n')
19051 line_arg = p + 1;
19052 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
19053 EMSG(_(e_trailing));
19056 * Read the body of the function, until ":endfunction" is found.
19058 if (KeyTyped)
19060 /* Check if the function already exists, don't let the user type the
19061 * whole function before telling him it doesn't work! For a script we
19062 * need to skip the body to be able to find what follows. */
19063 if (!eap->skip && !eap->forceit)
19065 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
19066 EMSG(_(e_funcdict));
19067 else if (name != NULL && find_func(name) != NULL)
19068 emsg_funcname(e_funcexts, name);
19071 if (!eap->skip && did_emsg)
19072 goto erret;
19074 msg_putchar('\n'); /* don't overwrite the function name */
19075 cmdline_row = msg_row;
19078 indent = 2;
19079 nesting = 0;
19080 for (;;)
19082 msg_scroll = TRUE;
19083 need_wait_return = FALSE;
19084 sourcing_lnum_off = sourcing_lnum;
19086 if (line_arg != NULL)
19088 /* Use eap->arg, split up in parts by line breaks. */
19089 theline = line_arg;
19090 p = vim_strchr(theline, '\n');
19091 if (p == NULL)
19092 line_arg += STRLEN(line_arg);
19093 else
19095 *p = NUL;
19096 line_arg = p + 1;
19099 else if (eap->getline == NULL)
19100 theline = getcmdline(':', 0L, indent);
19101 else
19102 theline = eap->getline(':', eap->cookie, indent);
19103 if (KeyTyped)
19104 lines_left = Rows - 1;
19105 if (theline == NULL)
19107 EMSG(_("E126: Missing :endfunction"));
19108 goto erret;
19111 /* Detect line continuation: sourcing_lnum increased more than one. */
19112 if (sourcing_lnum > sourcing_lnum_off + 1)
19113 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
19114 else
19115 sourcing_lnum_off = 0;
19117 if (skip_until != NULL)
19119 /* between ":append" and "." and between ":python <<EOF" and "EOF"
19120 * don't check for ":endfunc". */
19121 if (STRCMP(theline, skip_until) == 0)
19123 vim_free(skip_until);
19124 skip_until = NULL;
19127 else
19129 /* skip ':' and blanks*/
19130 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
19133 /* Check for "endfunction". */
19134 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
19136 if (line_arg == NULL)
19137 vim_free(theline);
19138 break;
19141 /* Increase indent inside "if", "while", "for" and "try", decrease
19142 * at "end". */
19143 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
19144 indent -= 2;
19145 else if (STRNCMP(p, "if", 2) == 0
19146 || STRNCMP(p, "wh", 2) == 0
19147 || STRNCMP(p, "for", 3) == 0
19148 || STRNCMP(p, "try", 3) == 0)
19149 indent += 2;
19151 /* Check for defining a function inside this function. */
19152 if (checkforcmd(&p, "function", 2))
19154 if (*p == '!')
19155 p = skipwhite(p + 1);
19156 p += eval_fname_script(p);
19157 if (ASCII_ISALPHA(*p))
19159 vim_free(trans_function_name(&p, TRUE, 0, NULL));
19160 if (*skipwhite(p) == '(')
19162 ++nesting;
19163 indent += 2;
19168 /* Check for ":append" or ":insert". */
19169 p = skip_range(p, NULL);
19170 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
19171 || (p[0] == 'i'
19172 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
19173 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
19174 skip_until = vim_strsave((char_u *)".");
19176 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
19177 arg = skipwhite(skiptowhite(p));
19178 if (arg[0] == '<' && arg[1] =='<'
19179 && ((p[0] == 'p' && p[1] == 'y'
19180 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
19181 || (p[0] == 'p' && p[1] == 'e'
19182 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
19183 || (p[0] == 't' && p[1] == 'c'
19184 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
19185 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
19186 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
19187 || (p[0] == 'm' && p[1] == 'z'
19188 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
19191 /* ":python <<" continues until a dot, like ":append" */
19192 p = skipwhite(arg + 2);
19193 if (*p == NUL)
19194 skip_until = vim_strsave((char_u *)".");
19195 else
19196 skip_until = vim_strsave(p);
19200 /* Add the line to the function. */
19201 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
19203 if (line_arg == NULL)
19204 vim_free(theline);
19205 goto erret;
19208 /* Copy the line to newly allocated memory. get_one_sourceline()
19209 * allocates 250 bytes per line, this saves 80% on average. The cost
19210 * is an extra alloc/free. */
19211 p = vim_strsave(theline);
19212 if (p != NULL)
19214 if (line_arg == NULL)
19215 vim_free(theline);
19216 theline = p;
19219 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
19221 /* Add NULL lines for continuation lines, so that the line count is
19222 * equal to the index in the growarray. */
19223 while (sourcing_lnum_off-- > 0)
19224 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
19226 /* Check for end of eap->arg. */
19227 if (line_arg != NULL && *line_arg == NUL)
19228 line_arg = NULL;
19231 /* Don't define the function when skipping commands or when an error was
19232 * detected. */
19233 if (eap->skip || did_emsg)
19234 goto erret;
19237 * If there are no errors, add the function
19239 if (fudi.fd_dict == NULL)
19241 v = find_var(name, &ht);
19242 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
19244 emsg_funcname("E707: Function name conflicts with variable: %s",
19245 name);
19246 goto erret;
19249 fp = find_func(name);
19250 if (fp != NULL)
19252 if (!eap->forceit)
19254 emsg_funcname(e_funcexts, name);
19255 goto erret;
19257 if (fp->uf_calls > 0)
19259 emsg_funcname("E127: Cannot redefine function %s: It is in use",
19260 name);
19261 goto erret;
19263 /* redefine existing function */
19264 ga_clear_strings(&(fp->uf_args));
19265 ga_clear_strings(&(fp->uf_lines));
19266 vim_free(name);
19267 name = NULL;
19270 else
19272 char numbuf[20];
19274 fp = NULL;
19275 if (fudi.fd_newkey == NULL && !eap->forceit)
19277 EMSG(_(e_funcdict));
19278 goto erret;
19280 if (fudi.fd_di == NULL)
19282 /* Can't add a function to a locked dictionary */
19283 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
19284 goto erret;
19286 /* Can't change an existing function if it is locked */
19287 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
19288 goto erret;
19290 /* Give the function a sequential number. Can only be used with a
19291 * Funcref! */
19292 vim_free(name);
19293 sprintf(numbuf, "%d", ++func_nr);
19294 name = vim_strsave((char_u *)numbuf);
19295 if (name == NULL)
19296 goto erret;
19299 if (fp == NULL)
19301 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
19303 int slen, plen;
19304 char_u *scriptname;
19306 /* Check that the autoload name matches the script name. */
19307 j = FAIL;
19308 if (sourcing_name != NULL)
19310 scriptname = autoload_name(name);
19311 if (scriptname != NULL)
19313 p = vim_strchr(scriptname, '/');
19314 plen = (int)STRLEN(p);
19315 slen = (int)STRLEN(sourcing_name);
19316 if (slen > plen && fnamecmp(p,
19317 sourcing_name + slen - plen) == 0)
19318 j = OK;
19319 vim_free(scriptname);
19322 if (j == FAIL)
19324 EMSG2(_("E746: Function name does not match script file name: %s"), name);
19325 goto erret;
19329 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
19330 if (fp == NULL)
19331 goto erret;
19333 if (fudi.fd_dict != NULL)
19335 if (fudi.fd_di == NULL)
19337 /* add new dict entry */
19338 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
19339 if (fudi.fd_di == NULL)
19341 vim_free(fp);
19342 goto erret;
19344 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
19346 vim_free(fudi.fd_di);
19347 vim_free(fp);
19348 goto erret;
19351 else
19352 /* overwrite existing dict entry */
19353 clear_tv(&fudi.fd_di->di_tv);
19354 fudi.fd_di->di_tv.v_type = VAR_FUNC;
19355 fudi.fd_di->di_tv.v_lock = 0;
19356 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
19357 fp->uf_refcount = 1;
19359 /* behave like "dict" was used */
19360 flags |= FC_DICT;
19363 /* insert the new function in the function list */
19364 STRCPY(fp->uf_name, name);
19365 hash_add(&func_hashtab, UF2HIKEY(fp));
19367 fp->uf_args = newargs;
19368 fp->uf_lines = newlines;
19369 #ifdef FEAT_PROFILE
19370 fp->uf_tml_count = NULL;
19371 fp->uf_tml_total = NULL;
19372 fp->uf_tml_self = NULL;
19373 fp->uf_profiling = FALSE;
19374 if (prof_def_func())
19375 func_do_profile(fp);
19376 #endif
19377 fp->uf_varargs = varargs;
19378 fp->uf_flags = flags;
19379 fp->uf_calls = 0;
19380 fp->uf_script_ID = current_SID;
19381 goto ret_free;
19383 erret:
19384 ga_clear_strings(&newargs);
19385 ga_clear_strings(&newlines);
19386 ret_free:
19387 vim_free(skip_until);
19388 vim_free(fudi.fd_newkey);
19389 vim_free(name);
19390 did_emsg |= saved_did_emsg;
19394 * Get a function name, translating "<SID>" and "<SNR>".
19395 * Also handles a Funcref in a List or Dictionary.
19396 * Returns the function name in allocated memory, or NULL for failure.
19397 * flags:
19398 * TFN_INT: internal function name OK
19399 * TFN_QUIET: be quiet
19400 * Advances "pp" to just after the function name (if no error).
19402 static char_u *
19403 trans_function_name(pp, skip, flags, fdp)
19404 char_u **pp;
19405 int skip; /* only find the end, don't evaluate */
19406 int flags;
19407 funcdict_T *fdp; /* return: info about dictionary used */
19409 char_u *name = NULL;
19410 char_u *start;
19411 char_u *end;
19412 int lead;
19413 char_u sid_buf[20];
19414 int len;
19415 lval_T lv;
19417 if (fdp != NULL)
19418 vim_memset(fdp, 0, sizeof(funcdict_T));
19419 start = *pp;
19421 /* Check for hard coded <SNR>: already translated function ID (from a user
19422 * command). */
19423 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
19424 && (*pp)[2] == (int)KE_SNR)
19426 *pp += 3;
19427 len = get_id_len(pp) + 3;
19428 return vim_strnsave(start, len);
19431 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
19432 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
19433 lead = eval_fname_script(start);
19434 if (lead > 2)
19435 start += lead;
19437 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
19438 lead > 2 ? 0 : FNE_CHECK_START);
19439 if (end == start)
19441 if (!skip)
19442 EMSG(_("E129: Function name required"));
19443 goto theend;
19445 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
19448 * Report an invalid expression in braces, unless the expression
19449 * evaluation has been cancelled due to an aborting error, an
19450 * interrupt, or an exception.
19452 if (!aborting())
19454 if (end != NULL)
19455 EMSG2(_(e_invarg2), start);
19457 else
19458 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
19459 goto theend;
19462 if (lv.ll_tv != NULL)
19464 if (fdp != NULL)
19466 fdp->fd_dict = lv.ll_dict;
19467 fdp->fd_newkey = lv.ll_newkey;
19468 lv.ll_newkey = NULL;
19469 fdp->fd_di = lv.ll_di;
19471 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
19473 name = vim_strsave(lv.ll_tv->vval.v_string);
19474 *pp = end;
19476 else
19478 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
19479 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
19480 EMSG(_(e_funcref));
19481 else
19482 *pp = end;
19483 name = NULL;
19485 goto theend;
19488 if (lv.ll_name == NULL)
19490 /* Error found, but continue after the function name. */
19491 *pp = end;
19492 goto theend;
19495 /* Check if the name is a Funcref. If so, use the value. */
19496 if (lv.ll_exp_name != NULL)
19498 len = (int)STRLEN(lv.ll_exp_name);
19499 name = deref_func_name(lv.ll_exp_name, &len);
19500 if (name == lv.ll_exp_name)
19501 name = NULL;
19503 else
19505 len = (int)(end - *pp);
19506 name = deref_func_name(*pp, &len);
19507 if (name == *pp)
19508 name = NULL;
19510 if (name != NULL)
19512 name = vim_strsave(name);
19513 *pp = end;
19514 goto theend;
19517 if (lv.ll_exp_name != NULL)
19519 len = (int)STRLEN(lv.ll_exp_name);
19520 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
19521 && STRNCMP(lv.ll_name, "s:", 2) == 0)
19523 /* When there was "s:" already or the name expanded to get a
19524 * leading "s:" then remove it. */
19525 lv.ll_name += 2;
19526 len -= 2;
19527 lead = 2;
19530 else
19532 if (lead == 2) /* skip over "s:" */
19533 lv.ll_name += 2;
19534 len = (int)(end - lv.ll_name);
19538 * Copy the function name to allocated memory.
19539 * Accept <SID>name() inside a script, translate into <SNR>123_name().
19540 * Accept <SNR>123_name() outside a script.
19542 if (skip)
19543 lead = 0; /* do nothing */
19544 else if (lead > 0)
19546 lead = 3;
19547 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
19548 || eval_fname_sid(*pp))
19550 /* It's "s:" or "<SID>" */
19551 if (current_SID <= 0)
19553 EMSG(_(e_usingsid));
19554 goto theend;
19556 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
19557 lead += (int)STRLEN(sid_buf);
19560 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
19562 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
19563 goto theend;
19565 name = alloc((unsigned)(len + lead + 1));
19566 if (name != NULL)
19568 if (lead > 0)
19570 name[0] = K_SPECIAL;
19571 name[1] = KS_EXTRA;
19572 name[2] = (int)KE_SNR;
19573 if (lead > 3) /* If it's "<SID>" */
19574 STRCPY(name + 3, sid_buf);
19576 mch_memmove(name + lead, lv.ll_name, (size_t)len);
19577 name[len + lead] = NUL;
19579 *pp = end;
19581 theend:
19582 clear_lval(&lv);
19583 return name;
19587 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
19588 * Return 2 if "p" starts with "s:".
19589 * Return 0 otherwise.
19591 static int
19592 eval_fname_script(p)
19593 char_u *p;
19595 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
19596 || STRNICMP(p + 1, "SNR>", 4) == 0))
19597 return 5;
19598 if (p[0] == 's' && p[1] == ':')
19599 return 2;
19600 return 0;
19604 * Return TRUE if "p" starts with "<SID>" or "s:".
19605 * Only works if eval_fname_script() returned non-zero for "p"!
19607 static int
19608 eval_fname_sid(p)
19609 char_u *p;
19611 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
19615 * List the head of the function: "name(arg1, arg2)".
19617 static void
19618 list_func_head(fp, indent)
19619 ufunc_T *fp;
19620 int indent;
19622 int j;
19624 msg_start();
19625 if (indent)
19626 MSG_PUTS(" ");
19627 MSG_PUTS("function ");
19628 if (fp->uf_name[0] == K_SPECIAL)
19630 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
19631 msg_puts(fp->uf_name + 3);
19633 else
19634 msg_puts(fp->uf_name);
19635 msg_putchar('(');
19636 for (j = 0; j < fp->uf_args.ga_len; ++j)
19638 if (j)
19639 MSG_PUTS(", ");
19640 msg_puts(FUNCARG(fp, j));
19642 if (fp->uf_varargs)
19644 if (j)
19645 MSG_PUTS(", ");
19646 MSG_PUTS("...");
19648 msg_putchar(')');
19649 msg_clr_eos();
19650 if (p_verbose > 0)
19651 last_set_msg(fp->uf_script_ID);
19655 * Find a function by name, return pointer to it in ufuncs.
19656 * Return NULL for unknown function.
19658 static ufunc_T *
19659 find_func(name)
19660 char_u *name;
19662 hashitem_T *hi;
19664 hi = hash_find(&func_hashtab, name);
19665 if (!HASHITEM_EMPTY(hi))
19666 return HI2UF(hi);
19667 return NULL;
19670 #if defined(EXITFREE) || defined(PROTO)
19671 void
19672 free_all_functions()
19674 hashitem_T *hi;
19676 /* Need to start all over every time, because func_free() may change the
19677 * hash table. */
19678 while (func_hashtab.ht_used > 0)
19679 for (hi = func_hashtab.ht_array; ; ++hi)
19680 if (!HASHITEM_EMPTY(hi))
19682 func_free(HI2UF(hi));
19683 break;
19686 #endif
19689 * Return TRUE if a function "name" exists.
19691 static int
19692 function_exists(name)
19693 char_u *name;
19695 char_u *nm = name;
19696 char_u *p;
19697 int n = FALSE;
19699 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
19700 nm = skipwhite(nm);
19702 /* Only accept "funcname", "funcname ", "funcname (..." and
19703 * "funcname(...", not "funcname!...". */
19704 if (p != NULL && (*nm == NUL || *nm == '('))
19706 if (builtin_function(p))
19707 n = (find_internal_func(p) >= 0);
19708 else
19709 n = (find_func(p) != NULL);
19711 vim_free(p);
19712 return n;
19716 * Return TRUE if "name" looks like a builtin function name: starts with a
19717 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
19719 static int
19720 builtin_function(name)
19721 char_u *name;
19723 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
19724 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
19727 #if defined(FEAT_PROFILE) || defined(PROTO)
19729 * Start profiling function "fp".
19731 static void
19732 func_do_profile(fp)
19733 ufunc_T *fp;
19735 fp->uf_tm_count = 0;
19736 profile_zero(&fp->uf_tm_self);
19737 profile_zero(&fp->uf_tm_total);
19738 if (fp->uf_tml_count == NULL)
19739 fp->uf_tml_count = (int *)alloc_clear((unsigned)
19740 (sizeof(int) * fp->uf_lines.ga_len));
19741 if (fp->uf_tml_total == NULL)
19742 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
19743 (sizeof(proftime_T) * fp->uf_lines.ga_len));
19744 if (fp->uf_tml_self == NULL)
19745 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
19746 (sizeof(proftime_T) * fp->uf_lines.ga_len));
19747 fp->uf_tml_idx = -1;
19748 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
19749 || fp->uf_tml_self == NULL)
19750 return; /* out of memory */
19752 fp->uf_profiling = TRUE;
19756 * Dump the profiling results for all functions in file "fd".
19758 void
19759 func_dump_profile(fd)
19760 FILE *fd;
19762 hashitem_T *hi;
19763 int todo;
19764 ufunc_T *fp;
19765 int i;
19766 ufunc_T **sorttab;
19767 int st_len = 0;
19769 todo = (int)func_hashtab.ht_used;
19770 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
19772 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
19774 if (!HASHITEM_EMPTY(hi))
19776 --todo;
19777 fp = HI2UF(hi);
19778 if (fp->uf_profiling)
19780 if (sorttab != NULL)
19781 sorttab[st_len++] = fp;
19783 if (fp->uf_name[0] == K_SPECIAL)
19784 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
19785 else
19786 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
19787 if (fp->uf_tm_count == 1)
19788 fprintf(fd, "Called 1 time\n");
19789 else
19790 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
19791 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
19792 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
19793 fprintf(fd, "\n");
19794 fprintf(fd, "count total (s) self (s)\n");
19796 for (i = 0; i < fp->uf_lines.ga_len; ++i)
19798 if (FUNCLINE(fp, i) == NULL)
19799 continue;
19800 prof_func_line(fd, fp->uf_tml_count[i],
19801 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
19802 fprintf(fd, "%s\n", FUNCLINE(fp, i));
19804 fprintf(fd, "\n");
19809 if (sorttab != NULL && st_len > 0)
19811 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
19812 prof_total_cmp);
19813 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
19814 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
19815 prof_self_cmp);
19816 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
19820 static void
19821 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
19822 FILE *fd;
19823 ufunc_T **sorttab;
19824 int st_len;
19825 char *title;
19826 int prefer_self; /* when equal print only self time */
19828 int i;
19829 ufunc_T *fp;
19831 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
19832 fprintf(fd, "count total (s) self (s) function\n");
19833 for (i = 0; i < 20 && i < st_len; ++i)
19835 fp = sorttab[i];
19836 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
19837 prefer_self);
19838 if (fp->uf_name[0] == K_SPECIAL)
19839 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
19840 else
19841 fprintf(fd, " %s()\n", fp->uf_name);
19843 fprintf(fd, "\n");
19847 * Print the count and times for one function or function line.
19849 static void
19850 prof_func_line(fd, count, total, self, prefer_self)
19851 FILE *fd;
19852 int count;
19853 proftime_T *total;
19854 proftime_T *self;
19855 int prefer_self; /* when equal print only self time */
19857 if (count > 0)
19859 fprintf(fd, "%5d ", count);
19860 if (prefer_self && profile_equal(total, self))
19861 fprintf(fd, " ");
19862 else
19863 fprintf(fd, "%s ", profile_msg(total));
19864 if (!prefer_self && profile_equal(total, self))
19865 fprintf(fd, " ");
19866 else
19867 fprintf(fd, "%s ", profile_msg(self));
19869 else
19870 fprintf(fd, " ");
19874 * Compare function for total time sorting.
19876 static int
19877 #ifdef __BORLANDC__
19878 _RTLENTRYF
19879 #endif
19880 prof_total_cmp(s1, s2)
19881 const void *s1;
19882 const void *s2;
19884 ufunc_T *p1, *p2;
19886 p1 = *(ufunc_T **)s1;
19887 p2 = *(ufunc_T **)s2;
19888 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
19892 * Compare function for self time sorting.
19894 static int
19895 #ifdef __BORLANDC__
19896 _RTLENTRYF
19897 #endif
19898 prof_self_cmp(s1, s2)
19899 const void *s1;
19900 const void *s2;
19902 ufunc_T *p1, *p2;
19904 p1 = *(ufunc_T **)s1;
19905 p2 = *(ufunc_T **)s2;
19906 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
19909 #endif
19912 * If "name" has a package name try autoloading the script for it.
19913 * Return TRUE if a package was loaded.
19915 static int
19916 script_autoload(name, reload)
19917 char_u *name;
19918 int reload; /* load script again when already loaded */
19920 char_u *p;
19921 char_u *scriptname, *tofree;
19922 int ret = FALSE;
19923 int i;
19925 /* If there is no '#' after name[0] there is no package name. */
19926 p = vim_strchr(name, AUTOLOAD_CHAR);
19927 if (p == NULL || p == name)
19928 return FALSE;
19930 tofree = scriptname = autoload_name(name);
19932 /* Find the name in the list of previously loaded package names. Skip
19933 * "autoload/", it's always the same. */
19934 for (i = 0; i < ga_loaded.ga_len; ++i)
19935 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
19936 break;
19937 if (!reload && i < ga_loaded.ga_len)
19938 ret = FALSE; /* was loaded already */
19939 else
19941 /* Remember the name if it wasn't loaded already. */
19942 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
19944 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
19945 tofree = NULL;
19948 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
19949 if (source_runtime(scriptname, FALSE) == OK)
19950 ret = TRUE;
19953 vim_free(tofree);
19954 return ret;
19958 * Return the autoload script name for a function or variable name.
19959 * Returns NULL when out of memory.
19961 static char_u *
19962 autoload_name(name)
19963 char_u *name;
19965 char_u *p;
19966 char_u *scriptname;
19968 /* Get the script file name: replace '#' with '/', append ".vim". */
19969 scriptname = alloc((unsigned)(STRLEN(name) + 14));
19970 if (scriptname == NULL)
19971 return FALSE;
19972 STRCPY(scriptname, "autoload/");
19973 STRCAT(scriptname, name);
19974 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
19975 STRCAT(scriptname, ".vim");
19976 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
19977 *p = '/';
19978 return scriptname;
19981 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
19984 * Function given to ExpandGeneric() to obtain the list of user defined
19985 * function names.
19987 char_u *
19988 get_user_func_name(xp, idx)
19989 expand_T *xp;
19990 int idx;
19992 static long_u done;
19993 static hashitem_T *hi;
19994 ufunc_T *fp;
19996 if (idx == 0)
19998 done = 0;
19999 hi = func_hashtab.ht_array;
20001 if (done < func_hashtab.ht_used)
20003 if (done++ > 0)
20004 ++hi;
20005 while (HASHITEM_EMPTY(hi))
20006 ++hi;
20007 fp = HI2UF(hi);
20009 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
20010 return fp->uf_name; /* prevents overflow */
20012 cat_func_name(IObuff, fp);
20013 if (xp->xp_context != EXPAND_USER_FUNC)
20015 STRCAT(IObuff, "(");
20016 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
20017 STRCAT(IObuff, ")");
20019 return IObuff;
20021 return NULL;
20024 #endif /* FEAT_CMDL_COMPL */
20027 * Copy the function name of "fp" to buffer "buf".
20028 * "buf" must be able to hold the function name plus three bytes.
20029 * Takes care of script-local function names.
20031 static void
20032 cat_func_name(buf, fp)
20033 char_u *buf;
20034 ufunc_T *fp;
20036 if (fp->uf_name[0] == K_SPECIAL)
20038 STRCPY(buf, "<SNR>");
20039 STRCAT(buf, fp->uf_name + 3);
20041 else
20042 STRCPY(buf, fp->uf_name);
20046 * ":delfunction {name}"
20048 void
20049 ex_delfunction(eap)
20050 exarg_T *eap;
20052 ufunc_T *fp = NULL;
20053 char_u *p;
20054 char_u *name;
20055 funcdict_T fudi;
20057 p = eap->arg;
20058 name = trans_function_name(&p, eap->skip, 0, &fudi);
20059 vim_free(fudi.fd_newkey);
20060 if (name == NULL)
20062 if (fudi.fd_dict != NULL && !eap->skip)
20063 EMSG(_(e_funcref));
20064 return;
20066 if (!ends_excmd(*skipwhite(p)))
20068 vim_free(name);
20069 EMSG(_(e_trailing));
20070 return;
20072 eap->nextcmd = check_nextcmd(p);
20073 if (eap->nextcmd != NULL)
20074 *p = NUL;
20076 if (!eap->skip)
20077 fp = find_func(name);
20078 vim_free(name);
20080 if (!eap->skip)
20082 if (fp == NULL)
20084 EMSG2(_(e_nofunc), eap->arg);
20085 return;
20087 if (fp->uf_calls > 0)
20089 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
20090 return;
20093 if (fudi.fd_dict != NULL)
20095 /* Delete the dict item that refers to the function, it will
20096 * invoke func_unref() and possibly delete the function. */
20097 dictitem_remove(fudi.fd_dict, fudi.fd_di);
20099 else
20100 func_free(fp);
20105 * Free a function and remove it from the list of functions.
20107 static void
20108 func_free(fp)
20109 ufunc_T *fp;
20111 hashitem_T *hi;
20113 /* clear this function */
20114 ga_clear_strings(&(fp->uf_args));
20115 ga_clear_strings(&(fp->uf_lines));
20116 #ifdef FEAT_PROFILE
20117 vim_free(fp->uf_tml_count);
20118 vim_free(fp->uf_tml_total);
20119 vim_free(fp->uf_tml_self);
20120 #endif
20122 /* remove the function from the function hashtable */
20123 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
20124 if (HASHITEM_EMPTY(hi))
20125 EMSG2(_(e_intern2), "func_free()");
20126 else
20127 hash_remove(&func_hashtab, hi);
20129 vim_free(fp);
20133 * Unreference a Function: decrement the reference count and free it when it
20134 * becomes zero. Only for numbered functions.
20136 static void
20137 func_unref(name)
20138 char_u *name;
20140 ufunc_T *fp;
20142 if (name != NULL && isdigit(*name))
20144 fp = find_func(name);
20145 if (fp == NULL)
20146 EMSG2(_(e_intern2), "func_unref()");
20147 else if (--fp->uf_refcount <= 0)
20149 /* Only delete it when it's not being used. Otherwise it's done
20150 * when "uf_calls" becomes zero. */
20151 if (fp->uf_calls == 0)
20152 func_free(fp);
20158 * Count a reference to a Function.
20160 static void
20161 func_ref(name)
20162 char_u *name;
20164 ufunc_T *fp;
20166 if (name != NULL && isdigit(*name))
20168 fp = find_func(name);
20169 if (fp == NULL)
20170 EMSG2(_(e_intern2), "func_ref()");
20171 else
20172 ++fp->uf_refcount;
20177 * Call a user function.
20179 static void
20180 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
20181 ufunc_T *fp; /* pointer to function */
20182 int argcount; /* nr of args */
20183 typval_T *argvars; /* arguments */
20184 typval_T *rettv; /* return value */
20185 linenr_T firstline; /* first line of range */
20186 linenr_T lastline; /* last line of range */
20187 dict_T *selfdict; /* Dictionary for "self" */
20189 char_u *save_sourcing_name;
20190 linenr_T save_sourcing_lnum;
20191 scid_T save_current_SID;
20192 funccall_T fc;
20193 int save_did_emsg;
20194 static int depth = 0;
20195 dictitem_T *v;
20196 int fixvar_idx = 0; /* index in fixvar[] */
20197 int i;
20198 int ai;
20199 char_u numbuf[NUMBUFLEN];
20200 char_u *name;
20201 #ifdef FEAT_PROFILE
20202 proftime_T wait_start;
20203 proftime_T call_start;
20204 #endif
20206 /* If depth of calling is getting too high, don't execute the function */
20207 if (depth >= p_mfd)
20209 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
20210 rettv->v_type = VAR_NUMBER;
20211 rettv->vval.v_number = -1;
20212 return;
20214 ++depth;
20216 line_breakcheck(); /* check for CTRL-C hit */
20218 fc.caller = current_funccal;
20219 current_funccal = &fc;
20220 fc.func = fp;
20221 fc.rettv = rettv;
20222 rettv->vval.v_number = 0;
20223 fc.linenr = 0;
20224 fc.returned = FALSE;
20225 fc.level = ex_nesting_level;
20226 /* Check if this function has a breakpoint. */
20227 fc.breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
20228 fc.dbg_tick = debug_tick;
20231 * Note about using fc.fixvar[]: This is an array of FIXVAR_CNT variables
20232 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
20233 * each argument variable and saves a lot of time.
20236 * Init l: variables.
20238 init_var_dict(&fc.l_vars, &fc.l_vars_var);
20239 if (selfdict != NULL)
20241 /* Set l:self to "selfdict". Use "name" to avoid a warning from
20242 * some compiler that checks the destination size. */
20243 v = &fc.fixvar[fixvar_idx++].var;
20244 name = v->di_key;
20245 STRCPY(name, "self");
20246 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
20247 hash_add(&fc.l_vars.dv_hashtab, DI2HIKEY(v));
20248 v->di_tv.v_type = VAR_DICT;
20249 v->di_tv.v_lock = 0;
20250 v->di_tv.vval.v_dict = selfdict;
20251 ++selfdict->dv_refcount;
20255 * Init a: variables.
20256 * Set a:0 to "argcount".
20257 * Set a:000 to a list with room for the "..." arguments.
20259 init_var_dict(&fc.l_avars, &fc.l_avars_var);
20260 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "0",
20261 (varnumber_T)(argcount - fp->uf_args.ga_len));
20262 v = &fc.fixvar[fixvar_idx++].var;
20263 STRCPY(v->di_key, "000");
20264 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20265 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
20266 v->di_tv.v_type = VAR_LIST;
20267 v->di_tv.v_lock = VAR_FIXED;
20268 v->di_tv.vval.v_list = &fc.l_varlist;
20269 vim_memset(&fc.l_varlist, 0, sizeof(list_T));
20270 fc.l_varlist.lv_refcount = 99999;
20271 fc.l_varlist.lv_lock = VAR_FIXED;
20274 * Set a:firstline to "firstline" and a:lastline to "lastline".
20275 * Set a:name to named arguments.
20276 * Set a:N to the "..." arguments.
20278 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "firstline",
20279 (varnumber_T)firstline);
20280 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "lastline",
20281 (varnumber_T)lastline);
20282 for (i = 0; i < argcount; ++i)
20284 ai = i - fp->uf_args.ga_len;
20285 if (ai < 0)
20286 /* named argument a:name */
20287 name = FUNCARG(fp, i);
20288 else
20290 /* "..." argument a:1, a:2, etc. */
20291 sprintf((char *)numbuf, "%d", ai + 1);
20292 name = numbuf;
20294 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
20296 v = &fc.fixvar[fixvar_idx++].var;
20297 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20299 else
20301 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
20302 + STRLEN(name)));
20303 if (v == NULL)
20304 break;
20305 v->di_flags = DI_FLAGS_RO;
20307 STRCPY(v->di_key, name);
20308 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
20310 /* Note: the values are copied directly to avoid alloc/free.
20311 * "argvars" must have VAR_FIXED for v_lock. */
20312 v->di_tv = argvars[i];
20313 v->di_tv.v_lock = VAR_FIXED;
20315 if (ai >= 0 && ai < MAX_FUNC_ARGS)
20317 list_append(&fc.l_varlist, &fc.l_listitems[ai]);
20318 fc.l_listitems[ai].li_tv = argvars[i];
20319 fc.l_listitems[ai].li_tv.v_lock = VAR_FIXED;
20323 /* Don't redraw while executing the function. */
20324 ++RedrawingDisabled;
20325 save_sourcing_name = sourcing_name;
20326 save_sourcing_lnum = sourcing_lnum;
20327 sourcing_lnum = 1;
20328 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
20329 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
20330 if (sourcing_name != NULL)
20332 if (save_sourcing_name != NULL
20333 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
20334 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
20335 else
20336 STRCPY(sourcing_name, "function ");
20337 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
20339 if (p_verbose >= 12)
20341 ++no_wait_return;
20342 verbose_enter_scroll();
20344 smsg((char_u *)_("calling %s"), sourcing_name);
20345 if (p_verbose >= 14)
20347 char_u buf[MSG_BUF_LEN];
20348 char_u numbuf2[NUMBUFLEN];
20349 char_u *tofree;
20350 char_u *s;
20352 msg_puts((char_u *)"(");
20353 for (i = 0; i < argcount; ++i)
20355 if (i > 0)
20356 msg_puts((char_u *)", ");
20357 if (argvars[i].v_type == VAR_NUMBER)
20358 msg_outnum((long)argvars[i].vval.v_number);
20359 else
20361 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
20362 if (s != NULL)
20364 trunc_string(s, buf, MSG_BUF_CLEN);
20365 msg_puts(buf);
20366 vim_free(tofree);
20370 msg_puts((char_u *)")");
20372 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20374 verbose_leave_scroll();
20375 --no_wait_return;
20378 #ifdef FEAT_PROFILE
20379 if (do_profiling == PROF_YES)
20381 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
20382 func_do_profile(fp);
20383 if (fp->uf_profiling
20384 || (fc.caller != NULL && &fc.caller->func->uf_profiling))
20386 ++fp->uf_tm_count;
20387 profile_start(&call_start);
20388 profile_zero(&fp->uf_tm_children);
20390 script_prof_save(&wait_start);
20392 #endif
20394 save_current_SID = current_SID;
20395 current_SID = fp->uf_script_ID;
20396 save_did_emsg = did_emsg;
20397 did_emsg = FALSE;
20399 /* call do_cmdline() to execute the lines */
20400 do_cmdline(NULL, get_func_line, (void *)&fc,
20401 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
20403 --RedrawingDisabled;
20405 /* when the function was aborted because of an error, return -1 */
20406 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
20408 clear_tv(rettv);
20409 rettv->v_type = VAR_NUMBER;
20410 rettv->vval.v_number = -1;
20413 #ifdef FEAT_PROFILE
20414 if (do_profiling == PROF_YES && (fp->uf_profiling
20415 || (fc.caller != NULL && &fc.caller->func->uf_profiling)))
20417 profile_end(&call_start);
20418 profile_sub_wait(&wait_start, &call_start);
20419 profile_add(&fp->uf_tm_total, &call_start);
20420 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
20421 if (fc.caller != NULL && &fc.caller->func->uf_profiling)
20423 profile_add(&fc.caller->func->uf_tm_children, &call_start);
20424 profile_add(&fc.caller->func->uf_tml_children, &call_start);
20427 #endif
20429 /* when being verbose, mention the return value */
20430 if (p_verbose >= 12)
20432 ++no_wait_return;
20433 verbose_enter_scroll();
20435 if (aborting())
20436 smsg((char_u *)_("%s aborted"), sourcing_name);
20437 else if (fc.rettv->v_type == VAR_NUMBER)
20438 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
20439 (long)fc.rettv->vval.v_number);
20440 else
20442 char_u buf[MSG_BUF_LEN];
20443 char_u numbuf2[NUMBUFLEN];
20444 char_u *tofree;
20445 char_u *s;
20447 /* The value may be very long. Skip the middle part, so that we
20448 * have some idea how it starts and ends. smsg() would always
20449 * truncate it at the end. */
20450 s = tv2string(fc.rettv, &tofree, numbuf2, 0);
20451 if (s != NULL)
20453 trunc_string(s, buf, MSG_BUF_CLEN);
20454 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
20455 vim_free(tofree);
20458 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20460 verbose_leave_scroll();
20461 --no_wait_return;
20464 vim_free(sourcing_name);
20465 sourcing_name = save_sourcing_name;
20466 sourcing_lnum = save_sourcing_lnum;
20467 current_SID = save_current_SID;
20468 #ifdef FEAT_PROFILE
20469 if (do_profiling == PROF_YES)
20470 script_prof_restore(&wait_start);
20471 #endif
20473 if (p_verbose >= 12 && sourcing_name != NULL)
20475 ++no_wait_return;
20476 verbose_enter_scroll();
20478 smsg((char_u *)_("continuing in %s"), sourcing_name);
20479 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20481 verbose_leave_scroll();
20482 --no_wait_return;
20485 did_emsg |= save_did_emsg;
20486 current_funccal = fc.caller;
20488 /* The a: variables typevals were not alloced, only free the allocated
20489 * variables. */
20490 vars_clear_ext(&fc.l_avars.dv_hashtab, FALSE);
20492 vars_clear(&fc.l_vars.dv_hashtab); /* free all l: variables */
20493 --depth;
20497 * Add a number variable "name" to dict "dp" with value "nr".
20499 static void
20500 add_nr_var(dp, v, name, nr)
20501 dict_T *dp;
20502 dictitem_T *v;
20503 char *name;
20504 varnumber_T nr;
20506 STRCPY(v->di_key, name);
20507 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20508 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
20509 v->di_tv.v_type = VAR_NUMBER;
20510 v->di_tv.v_lock = VAR_FIXED;
20511 v->di_tv.vval.v_number = nr;
20515 * ":return [expr]"
20517 void
20518 ex_return(eap)
20519 exarg_T *eap;
20521 char_u *arg = eap->arg;
20522 typval_T rettv;
20523 int returning = FALSE;
20525 if (current_funccal == NULL)
20527 EMSG(_("E133: :return not inside a function"));
20528 return;
20531 if (eap->skip)
20532 ++emsg_skip;
20534 eap->nextcmd = NULL;
20535 if ((*arg != NUL && *arg != '|' && *arg != '\n')
20536 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
20538 if (!eap->skip)
20539 returning = do_return(eap, FALSE, TRUE, &rettv);
20540 else
20541 clear_tv(&rettv);
20543 /* It's safer to return also on error. */
20544 else if (!eap->skip)
20547 * Return unless the expression evaluation has been cancelled due to an
20548 * aborting error, an interrupt, or an exception.
20550 if (!aborting())
20551 returning = do_return(eap, FALSE, TRUE, NULL);
20554 /* When skipping or the return gets pending, advance to the next command
20555 * in this line (!returning). Otherwise, ignore the rest of the line.
20556 * Following lines will be ignored by get_func_line(). */
20557 if (returning)
20558 eap->nextcmd = NULL;
20559 else if (eap->nextcmd == NULL) /* no argument */
20560 eap->nextcmd = check_nextcmd(arg);
20562 if (eap->skip)
20563 --emsg_skip;
20567 * Return from a function. Possibly makes the return pending. Also called
20568 * for a pending return at the ":endtry" or after returning from an extra
20569 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
20570 * when called due to a ":return" command. "rettv" may point to a typval_T
20571 * with the return rettv. Returns TRUE when the return can be carried out,
20572 * FALSE when the return gets pending.
20575 do_return(eap, reanimate, is_cmd, rettv)
20576 exarg_T *eap;
20577 int reanimate;
20578 int is_cmd;
20579 void *rettv;
20581 int idx;
20582 struct condstack *cstack = eap->cstack;
20584 if (reanimate)
20585 /* Undo the return. */
20586 current_funccal->returned = FALSE;
20589 * Cleanup (and inactivate) conditionals, but stop when a try conditional
20590 * not in its finally clause (which then is to be executed next) is found.
20591 * In this case, make the ":return" pending for execution at the ":endtry".
20592 * Otherwise, return normally.
20594 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
20595 if (idx >= 0)
20597 cstack->cs_pending[idx] = CSTP_RETURN;
20599 if (!is_cmd && !reanimate)
20600 /* A pending return again gets pending. "rettv" points to an
20601 * allocated variable with the rettv of the original ":return"'s
20602 * argument if present or is NULL else. */
20603 cstack->cs_rettv[idx] = rettv;
20604 else
20606 /* When undoing a return in order to make it pending, get the stored
20607 * return rettv. */
20608 if (reanimate)
20609 rettv = current_funccal->rettv;
20611 if (rettv != NULL)
20613 /* Store the value of the pending return. */
20614 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
20615 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
20616 else
20617 EMSG(_(e_outofmem));
20619 else
20620 cstack->cs_rettv[idx] = NULL;
20622 if (reanimate)
20624 /* The pending return value could be overwritten by a ":return"
20625 * without argument in a finally clause; reset the default
20626 * return value. */
20627 current_funccal->rettv->v_type = VAR_NUMBER;
20628 current_funccal->rettv->vval.v_number = 0;
20631 report_make_pending(CSTP_RETURN, rettv);
20633 else
20635 current_funccal->returned = TRUE;
20637 /* If the return is carried out now, store the return value. For
20638 * a return immediately after reanimation, the value is already
20639 * there. */
20640 if (!reanimate && rettv != NULL)
20642 clear_tv(current_funccal->rettv);
20643 *current_funccal->rettv = *(typval_T *)rettv;
20644 if (!is_cmd)
20645 vim_free(rettv);
20649 return idx < 0;
20653 * Free the variable with a pending return value.
20655 void
20656 discard_pending_return(rettv)
20657 void *rettv;
20659 free_tv((typval_T *)rettv);
20663 * Generate a return command for producing the value of "rettv". The result
20664 * is an allocated string. Used by report_pending() for verbose messages.
20666 char_u *
20667 get_return_cmd(rettv)
20668 void *rettv;
20670 char_u *s = NULL;
20671 char_u *tofree = NULL;
20672 char_u numbuf[NUMBUFLEN];
20674 if (rettv != NULL)
20675 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
20676 if (s == NULL)
20677 s = (char_u *)"";
20679 STRCPY(IObuff, ":return ");
20680 STRNCPY(IObuff + 8, s, IOSIZE - 8);
20681 if (STRLEN(s) + 8 >= IOSIZE)
20682 STRCPY(IObuff + IOSIZE - 4, "...");
20683 vim_free(tofree);
20684 return vim_strsave(IObuff);
20688 * Get next function line.
20689 * Called by do_cmdline() to get the next line.
20690 * Returns allocated string, or NULL for end of function.
20692 /* ARGSUSED */
20693 char_u *
20694 get_func_line(c, cookie, indent)
20695 int c; /* not used */
20696 void *cookie;
20697 int indent; /* not used */
20699 funccall_T *fcp = (funccall_T *)cookie;
20700 ufunc_T *fp = fcp->func;
20701 char_u *retval;
20702 garray_T *gap; /* growarray with function lines */
20704 /* If breakpoints have been added/deleted need to check for it. */
20705 if (fcp->dbg_tick != debug_tick)
20707 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
20708 sourcing_lnum);
20709 fcp->dbg_tick = debug_tick;
20711 #ifdef FEAT_PROFILE
20712 if (do_profiling == PROF_YES)
20713 func_line_end(cookie);
20714 #endif
20716 gap = &fp->uf_lines;
20717 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
20718 || fcp->returned)
20719 retval = NULL;
20720 else
20722 /* Skip NULL lines (continuation lines). */
20723 while (fcp->linenr < gap->ga_len
20724 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
20725 ++fcp->linenr;
20726 if (fcp->linenr >= gap->ga_len)
20727 retval = NULL;
20728 else
20730 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
20731 sourcing_lnum = fcp->linenr;
20732 #ifdef FEAT_PROFILE
20733 if (do_profiling == PROF_YES)
20734 func_line_start(cookie);
20735 #endif
20739 /* Did we encounter a breakpoint? */
20740 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
20742 dbg_breakpoint(fp->uf_name, sourcing_lnum);
20743 /* Find next breakpoint. */
20744 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
20745 sourcing_lnum);
20746 fcp->dbg_tick = debug_tick;
20749 return retval;
20752 #if defined(FEAT_PROFILE) || defined(PROTO)
20754 * Called when starting to read a function line.
20755 * "sourcing_lnum" must be correct!
20756 * When skipping lines it may not actually be executed, but we won't find out
20757 * until later and we need to store the time now.
20759 void
20760 func_line_start(cookie)
20761 void *cookie;
20763 funccall_T *fcp = (funccall_T *)cookie;
20764 ufunc_T *fp = fcp->func;
20766 if (fp->uf_profiling && sourcing_lnum >= 1
20767 && sourcing_lnum <= fp->uf_lines.ga_len)
20769 fp->uf_tml_idx = sourcing_lnum - 1;
20770 /* Skip continuation lines. */
20771 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
20772 --fp->uf_tml_idx;
20773 fp->uf_tml_execed = FALSE;
20774 profile_start(&fp->uf_tml_start);
20775 profile_zero(&fp->uf_tml_children);
20776 profile_get_wait(&fp->uf_tml_wait);
20781 * Called when actually executing a function line.
20783 void
20784 func_line_exec(cookie)
20785 void *cookie;
20787 funccall_T *fcp = (funccall_T *)cookie;
20788 ufunc_T *fp = fcp->func;
20790 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
20791 fp->uf_tml_execed = TRUE;
20795 * Called when done with a function line.
20797 void
20798 func_line_end(cookie)
20799 void *cookie;
20801 funccall_T *fcp = (funccall_T *)cookie;
20802 ufunc_T *fp = fcp->func;
20804 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
20806 if (fp->uf_tml_execed)
20808 ++fp->uf_tml_count[fp->uf_tml_idx];
20809 profile_end(&fp->uf_tml_start);
20810 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
20811 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
20812 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
20813 &fp->uf_tml_children);
20815 fp->uf_tml_idx = -1;
20818 #endif
20821 * Return TRUE if the currently active function should be ended, because a
20822 * return was encountered or an error occured. Used inside a ":while".
20825 func_has_ended(cookie)
20826 void *cookie;
20828 funccall_T *fcp = (funccall_T *)cookie;
20830 /* Ignore the "abort" flag if the abortion behavior has been changed due to
20831 * an error inside a try conditional. */
20832 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
20833 || fcp->returned);
20837 * return TRUE if cookie indicates a function which "abort"s on errors.
20840 func_has_abort(cookie)
20841 void *cookie;
20843 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
20846 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
20847 typedef enum
20849 VAR_FLAVOUR_DEFAULT,
20850 VAR_FLAVOUR_SESSION,
20851 VAR_FLAVOUR_VIMINFO
20852 } var_flavour_T;
20854 static var_flavour_T var_flavour __ARGS((char_u *varname));
20856 static var_flavour_T
20857 var_flavour(varname)
20858 char_u *varname;
20860 char_u *p = varname;
20862 if (ASCII_ISUPPER(*p))
20864 while (*(++p))
20865 if (ASCII_ISLOWER(*p))
20866 return VAR_FLAVOUR_SESSION;
20867 return VAR_FLAVOUR_VIMINFO;
20869 else
20870 return VAR_FLAVOUR_DEFAULT;
20872 #endif
20874 #if defined(FEAT_VIMINFO) || defined(PROTO)
20876 * Restore global vars that start with a capital from the viminfo file
20879 read_viminfo_varlist(virp, writing)
20880 vir_T *virp;
20881 int writing;
20883 char_u *tab;
20884 int is_string = FALSE;
20885 typval_T tv;
20887 if (!writing && (find_viminfo_parameter('!') != NULL))
20889 tab = vim_strchr(virp->vir_line + 1, '\t');
20890 if (tab != NULL)
20892 *tab++ = '\0'; /* isolate the variable name */
20893 if (*tab == 'S') /* string var */
20894 is_string = TRUE;
20896 tab = vim_strchr(tab, '\t');
20897 if (tab != NULL)
20899 if (is_string)
20901 tv.v_type = VAR_STRING;
20902 tv.vval.v_string = viminfo_readstring(virp,
20903 (int)(tab - virp->vir_line + 1), TRUE);
20905 else
20907 tv.v_type = VAR_NUMBER;
20908 tv.vval.v_number = atol((char *)tab + 1);
20910 set_var(virp->vir_line + 1, &tv, FALSE);
20911 if (is_string)
20912 vim_free(tv.vval.v_string);
20917 return viminfo_readline(virp);
20921 * Write global vars that start with a capital to the viminfo file
20923 void
20924 write_viminfo_varlist(fp)
20925 FILE *fp;
20927 hashitem_T *hi;
20928 dictitem_T *this_var;
20929 int todo;
20930 char *s;
20931 char_u *p;
20932 char_u *tofree;
20933 char_u numbuf[NUMBUFLEN];
20935 if (find_viminfo_parameter('!') == NULL)
20936 return;
20938 fprintf(fp, _("\n# global variables:\n"));
20940 todo = (int)globvarht.ht_used;
20941 for (hi = globvarht.ht_array; todo > 0; ++hi)
20943 if (!HASHITEM_EMPTY(hi))
20945 --todo;
20946 this_var = HI2DI(hi);
20947 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
20949 switch (this_var->di_tv.v_type)
20951 case VAR_STRING: s = "STR"; break;
20952 case VAR_NUMBER: s = "NUM"; break;
20953 default: continue;
20955 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
20956 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
20957 if (p != NULL)
20958 viminfo_writestring(fp, p);
20959 vim_free(tofree);
20964 #endif
20966 #if defined(FEAT_SESSION) || defined(PROTO)
20968 store_session_globals(fd)
20969 FILE *fd;
20971 hashitem_T *hi;
20972 dictitem_T *this_var;
20973 int todo;
20974 char_u *p, *t;
20976 todo = (int)globvarht.ht_used;
20977 for (hi = globvarht.ht_array; todo > 0; ++hi)
20979 if (!HASHITEM_EMPTY(hi))
20981 --todo;
20982 this_var = HI2DI(hi);
20983 if ((this_var->di_tv.v_type == VAR_NUMBER
20984 || this_var->di_tv.v_type == VAR_STRING)
20985 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
20987 /* Escape special characters with a backslash. Turn a LF and
20988 * CR into \n and \r. */
20989 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
20990 (char_u *)"\\\"\n\r");
20991 if (p == NULL) /* out of memory */
20992 break;
20993 for (t = p; *t != NUL; ++t)
20994 if (*t == '\n')
20995 *t = 'n';
20996 else if (*t == '\r')
20997 *t = 'r';
20998 if ((fprintf(fd, "let %s = %c%s%c",
20999 this_var->di_key,
21000 (this_var->di_tv.v_type == VAR_STRING) ? '"'
21001 : ' ',
21003 (this_var->di_tv.v_type == VAR_STRING) ? '"'
21004 : ' ') < 0)
21005 || put_eol(fd) == FAIL)
21007 vim_free(p);
21008 return FAIL;
21010 vim_free(p);
21014 return OK;
21016 #endif
21019 * Display script name where an item was last set.
21020 * Should only be invoked when 'verbose' is non-zero.
21022 void
21023 last_set_msg(scriptID)
21024 scid_T scriptID;
21026 char_u *p;
21028 if (scriptID != 0)
21030 p = home_replace_save(NULL, get_scriptname(scriptID));
21031 if (p != NULL)
21033 verbose_enter();
21034 MSG_PUTS(_("\n\tLast set from "));
21035 MSG_PUTS(p);
21036 vim_free(p);
21037 verbose_leave();
21042 #endif /* FEAT_EVAL */
21044 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
21047 #ifdef WIN3264
21049 * Functions for ":8" filename modifier: get 8.3 version of a filename.
21051 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
21052 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
21053 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
21056 * Get the short pathname of a file.
21057 * Returns 1 on success. *fnamelen is 0 for nonexistent path.
21059 static int
21060 get_short_pathname(fnamep, bufp, fnamelen)
21061 char_u **fnamep;
21062 char_u **bufp;
21063 int *fnamelen;
21065 int l,len;
21066 char_u *newbuf;
21068 len = *fnamelen;
21070 l = GetShortPathName(*fnamep, *fnamep, len);
21071 if (l > len - 1)
21073 /* If that doesn't work (not enough space), then save the string
21074 * and try again with a new buffer big enough
21076 newbuf = vim_strnsave(*fnamep, l);
21077 if (newbuf == NULL)
21078 return 0;
21080 vim_free(*bufp);
21081 *fnamep = *bufp = newbuf;
21083 l = GetShortPathName(*fnamep,*fnamep,l+1);
21085 /* Really should always succeed, as the buffer is big enough */
21088 *fnamelen = l;
21089 return 1;
21093 * Create a short path name. Returns the length of the buffer it needs.
21094 * Doesn't copy over the end of the buffer passed in.
21096 static int
21097 shortpath_for_invalid_fname(fname, bufp, fnamelen)
21098 char_u **fname;
21099 char_u **bufp;
21100 int *fnamelen;
21102 char_u *s, *p, *pbuf2, *pbuf3;
21103 char_u ch;
21104 int len, len2, plen, slen;
21106 /* Make a copy */
21107 len2 = *fnamelen;
21108 pbuf2 = vim_strnsave(*fname, len2);
21109 pbuf3 = NULL;
21111 s = pbuf2 + len2 - 1; /* Find the end */
21112 slen = 1;
21113 plen = len2;
21115 if (after_pathsep(pbuf2, s + 1))
21117 --s;
21118 ++slen;
21119 --plen;
21124 /* Go back one path-separator */
21125 while (s > pbuf2 && !after_pathsep(pbuf2, s + 1))
21127 --s;
21128 ++slen;
21129 --plen;
21131 if (s <= pbuf2)
21132 break;
21134 /* Remember the character that is about to be splatted */
21135 ch = *s;
21136 *s = 0; /* get_short_pathname requires a null-terminated string */
21138 /* Try it in situ */
21139 p = pbuf2;
21140 if (!get_short_pathname(&p, &pbuf3, &plen))
21142 vim_free(pbuf2);
21143 return -1;
21145 *s = ch; /* Preserve the string */
21146 } while (plen == 0);
21148 if (plen > 0)
21150 /* Remember the length of the new string. */
21151 *fnamelen = len = plen + slen;
21152 vim_free(*bufp);
21153 if (len > len2)
21155 /* If there's not enough space in the currently allocated string,
21156 * then copy it to a buffer big enough.
21158 *fname= *bufp = vim_strnsave(p, len);
21159 if (*fname == NULL)
21160 return -1;
21162 else
21164 /* Transfer pbuf2 to being the main buffer (it's big enough) */
21165 *fname = *bufp = pbuf2;
21166 if (p != pbuf2)
21167 strncpy(*fname, p, plen);
21168 pbuf2 = NULL;
21170 /* Concat the next bit */
21171 strncpy(*fname + plen, s, slen);
21172 (*fname)[len] = '\0';
21174 vim_free(pbuf3);
21175 vim_free(pbuf2);
21176 return 0;
21180 * Get a pathname for a partial path.
21182 static int
21183 shortpath_for_partial(fnamep, bufp, fnamelen)
21184 char_u **fnamep;
21185 char_u **bufp;
21186 int *fnamelen;
21188 int sepcount, len, tflen;
21189 char_u *p;
21190 char_u *pbuf, *tfname;
21191 int hasTilde;
21193 /* Count up the path seperators from the RHS.. so we know which part
21194 * of the path to return.
21196 sepcount = 0;
21197 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
21198 if (vim_ispathsep(*p))
21199 ++sepcount;
21201 /* Need full path first (use expand_env() to remove a "~/") */
21202 hasTilde = (**fnamep == '~');
21203 if (hasTilde)
21204 pbuf = tfname = expand_env_save(*fnamep);
21205 else
21206 pbuf = tfname = FullName_save(*fnamep, FALSE);
21208 len = tflen = (int)STRLEN(tfname);
21210 if (!get_short_pathname(&tfname, &pbuf, &len))
21211 return -1;
21213 if (len == 0)
21215 /* Don't have a valid filename, so shorten the rest of the
21216 * path if we can. This CAN give us invalid 8.3 filenames, but
21217 * there's not a lot of point in guessing what it might be.
21219 len = tflen;
21220 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == -1)
21221 return -1;
21224 /* Count the paths backward to find the beginning of the desired string. */
21225 for (p = tfname + len - 1; p >= tfname; --p)
21227 #ifdef FEAT_MBYTE
21228 if (has_mbyte)
21229 p -= mb_head_off(tfname, p);
21230 #endif
21231 if (vim_ispathsep(*p))
21233 if (sepcount == 0 || (hasTilde && sepcount == 1))
21234 break;
21235 else
21236 sepcount --;
21239 if (hasTilde)
21241 --p;
21242 if (p >= tfname)
21243 *p = '~';
21244 else
21245 return -1;
21247 else
21248 ++p;
21250 /* Copy in the string - p indexes into tfname - allocated at pbuf */
21251 vim_free(*bufp);
21252 *fnamelen = (int)STRLEN(p);
21253 *bufp = pbuf;
21254 *fnamep = p;
21256 return 0;
21258 #endif /* WIN3264 */
21261 * Adjust a filename, according to a string of modifiers.
21262 * *fnamep must be NUL terminated when called. When returning, the length is
21263 * determined by *fnamelen.
21264 * Returns valid flags.
21265 * When there is an error, *fnamep is set to NULL.
21268 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
21269 char_u *src; /* string with modifiers */
21270 int *usedlen; /* characters after src that are used */
21271 char_u **fnamep; /* file name so far */
21272 char_u **bufp; /* buffer for allocated file name or NULL */
21273 int *fnamelen; /* length of fnamep */
21275 int valid = 0;
21276 char_u *tail;
21277 char_u *s, *p, *pbuf;
21278 char_u dirname[MAXPATHL];
21279 int c;
21280 int has_fullname = 0;
21281 #ifdef WIN3264
21282 int has_shortname = 0;
21283 #endif
21285 repeat:
21286 /* ":p" - full path/file_name */
21287 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
21289 has_fullname = 1;
21291 valid |= VALID_PATH;
21292 *usedlen += 2;
21294 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
21295 if ((*fnamep)[0] == '~'
21296 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
21297 && ((*fnamep)[1] == '/'
21298 # ifdef BACKSLASH_IN_FILENAME
21299 || (*fnamep)[1] == '\\'
21300 # endif
21301 || (*fnamep)[1] == NUL)
21303 #endif
21306 *fnamep = expand_env_save(*fnamep);
21307 vim_free(*bufp); /* free any allocated file name */
21308 *bufp = *fnamep;
21309 if (*fnamep == NULL)
21310 return -1;
21313 /* When "/." or "/.." is used: force expansion to get rid of it. */
21314 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
21316 if (vim_ispathsep(*p)
21317 && p[1] == '.'
21318 && (p[2] == NUL
21319 || vim_ispathsep(p[2])
21320 || (p[2] == '.'
21321 && (p[3] == NUL || vim_ispathsep(p[3])))))
21322 break;
21325 /* FullName_save() is slow, don't use it when not needed. */
21326 if (*p != NUL || !vim_isAbsName(*fnamep))
21328 *fnamep = FullName_save(*fnamep, *p != NUL);
21329 vim_free(*bufp); /* free any allocated file name */
21330 *bufp = *fnamep;
21331 if (*fnamep == NULL)
21332 return -1;
21335 /* Append a path separator to a directory. */
21336 if (mch_isdir(*fnamep))
21338 /* Make room for one or two extra characters. */
21339 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
21340 vim_free(*bufp); /* free any allocated file name */
21341 *bufp = *fnamep;
21342 if (*fnamep == NULL)
21343 return -1;
21344 add_pathsep(*fnamep);
21348 /* ":." - path relative to the current directory */
21349 /* ":~" - path relative to the home directory */
21350 /* ":8" - shortname path - postponed till after */
21351 while (src[*usedlen] == ':'
21352 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
21354 *usedlen += 2;
21355 if (c == '8')
21357 #ifdef WIN3264
21358 has_shortname = 1; /* Postpone this. */
21359 #endif
21360 continue;
21362 pbuf = NULL;
21363 /* Need full path first (use expand_env() to remove a "~/") */
21364 if (!has_fullname)
21366 if (c == '.' && **fnamep == '~')
21367 p = pbuf = expand_env_save(*fnamep);
21368 else
21369 p = pbuf = FullName_save(*fnamep, FALSE);
21371 else
21372 p = *fnamep;
21374 has_fullname = 0;
21376 if (p != NULL)
21378 if (c == '.')
21380 mch_dirname(dirname, MAXPATHL);
21381 s = shorten_fname(p, dirname);
21382 if (s != NULL)
21384 *fnamep = s;
21385 if (pbuf != NULL)
21387 vim_free(*bufp); /* free any allocated file name */
21388 *bufp = pbuf;
21389 pbuf = NULL;
21393 else
21395 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
21396 /* Only replace it when it starts with '~' */
21397 if (*dirname == '~')
21399 s = vim_strsave(dirname);
21400 if (s != NULL)
21402 *fnamep = s;
21403 vim_free(*bufp);
21404 *bufp = s;
21408 vim_free(pbuf);
21412 tail = gettail(*fnamep);
21413 *fnamelen = (int)STRLEN(*fnamep);
21415 /* ":h" - head, remove "/file_name", can be repeated */
21416 /* Don't remove the first "/" or "c:\" */
21417 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
21419 valid |= VALID_HEAD;
21420 *usedlen += 2;
21421 s = get_past_head(*fnamep);
21422 while (tail > s && after_pathsep(s, tail))
21423 mb_ptr_back(*fnamep, tail);
21424 *fnamelen = (int)(tail - *fnamep);
21425 #ifdef VMS
21426 if (*fnamelen > 0)
21427 *fnamelen += 1; /* the path separator is part of the path */
21428 #endif
21429 if (*fnamelen == 0)
21431 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
21432 p = vim_strsave((char_u *)".");
21433 if (p == NULL)
21434 return -1;
21435 vim_free(*bufp);
21436 *bufp = *fnamep = tail = p;
21437 *fnamelen = 1;
21439 else
21441 while (tail > s && !after_pathsep(s, tail))
21442 mb_ptr_back(*fnamep, tail);
21446 /* ":8" - shortname */
21447 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
21449 *usedlen += 2;
21450 #ifdef WIN3264
21451 has_shortname = 1;
21452 #endif
21455 #ifdef WIN3264
21456 /* Check shortname after we have done 'heads' and before we do 'tails'
21458 if (has_shortname)
21460 pbuf = NULL;
21461 /* Copy the string if it is shortened by :h */
21462 if (*fnamelen < (int)STRLEN(*fnamep))
21464 p = vim_strnsave(*fnamep, *fnamelen);
21465 if (p == 0)
21466 return -1;
21467 vim_free(*bufp);
21468 *bufp = *fnamep = p;
21471 /* Split into two implementations - makes it easier. First is where
21472 * there isn't a full name already, second is where there is.
21474 if (!has_fullname && !vim_isAbsName(*fnamep))
21476 if (shortpath_for_partial(fnamep, bufp, fnamelen) == -1)
21477 return -1;
21479 else
21481 int l;
21483 /* Simple case, already have the full-name
21484 * Nearly always shorter, so try first time. */
21485 l = *fnamelen;
21486 if (!get_short_pathname(fnamep, bufp, &l))
21487 return -1;
21489 if (l == 0)
21491 /* Couldn't find the filename.. search the paths.
21493 l = *fnamelen;
21494 if (shortpath_for_invalid_fname(fnamep, bufp, &l ) == -1)
21495 return -1;
21497 *fnamelen = l;
21500 #endif /* WIN3264 */
21502 /* ":t" - tail, just the basename */
21503 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
21505 *usedlen += 2;
21506 *fnamelen -= (int)(tail - *fnamep);
21507 *fnamep = tail;
21510 /* ":e" - extension, can be repeated */
21511 /* ":r" - root, without extension, can be repeated */
21512 while (src[*usedlen] == ':'
21513 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
21515 /* find a '.' in the tail:
21516 * - for second :e: before the current fname
21517 * - otherwise: The last '.'
21519 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
21520 s = *fnamep - 2;
21521 else
21522 s = *fnamep + *fnamelen - 1;
21523 for ( ; s > tail; --s)
21524 if (s[0] == '.')
21525 break;
21526 if (src[*usedlen + 1] == 'e') /* :e */
21528 if (s > tail)
21530 *fnamelen += (int)(*fnamep - (s + 1));
21531 *fnamep = s + 1;
21532 #ifdef VMS
21533 /* cut version from the extension */
21534 s = *fnamep + *fnamelen - 1;
21535 for ( ; s > *fnamep; --s)
21536 if (s[0] == ';')
21537 break;
21538 if (s > *fnamep)
21539 *fnamelen = s - *fnamep;
21540 #endif
21542 else if (*fnamep <= tail)
21543 *fnamelen = 0;
21545 else /* :r */
21547 if (s > tail) /* remove one extension */
21548 *fnamelen = (int)(s - *fnamep);
21550 *usedlen += 2;
21553 /* ":s?pat?foo?" - substitute */
21554 /* ":gs?pat?foo?" - global substitute */
21555 if (src[*usedlen] == ':'
21556 && (src[*usedlen + 1] == 's'
21557 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
21559 char_u *str;
21560 char_u *pat;
21561 char_u *sub;
21562 int sep;
21563 char_u *flags;
21564 int didit = FALSE;
21566 flags = (char_u *)"";
21567 s = src + *usedlen + 2;
21568 if (src[*usedlen + 1] == 'g')
21570 flags = (char_u *)"g";
21571 ++s;
21574 sep = *s++;
21575 if (sep)
21577 /* find end of pattern */
21578 p = vim_strchr(s, sep);
21579 if (p != NULL)
21581 pat = vim_strnsave(s, (int)(p - s));
21582 if (pat != NULL)
21584 s = p + 1;
21585 /* find end of substitution */
21586 p = vim_strchr(s, sep);
21587 if (p != NULL)
21589 sub = vim_strnsave(s, (int)(p - s));
21590 str = vim_strnsave(*fnamep, *fnamelen);
21591 if (sub != NULL && str != NULL)
21593 *usedlen = (int)(p + 1 - src);
21594 s = do_string_sub(str, pat, sub, flags);
21595 if (s != NULL)
21597 *fnamep = s;
21598 *fnamelen = (int)STRLEN(s);
21599 vim_free(*bufp);
21600 *bufp = s;
21601 didit = TRUE;
21604 vim_free(sub);
21605 vim_free(str);
21607 vim_free(pat);
21610 /* after using ":s", repeat all the modifiers */
21611 if (didit)
21612 goto repeat;
21616 return valid;
21620 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
21621 * "flags" can be "g" to do a global substitute.
21622 * Returns an allocated string, NULL for error.
21624 char_u *
21625 do_string_sub(str, pat, sub, flags)
21626 char_u *str;
21627 char_u *pat;
21628 char_u *sub;
21629 char_u *flags;
21631 int sublen;
21632 regmatch_T regmatch;
21633 int i;
21634 int do_all;
21635 char_u *tail;
21636 garray_T ga;
21637 char_u *ret;
21638 char_u *save_cpo;
21640 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
21641 save_cpo = p_cpo;
21642 p_cpo = (char_u *)"";
21644 ga_init2(&ga, 1, 200);
21646 do_all = (flags[0] == 'g');
21648 regmatch.rm_ic = p_ic;
21649 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
21650 if (regmatch.regprog != NULL)
21652 tail = str;
21653 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
21656 * Get some space for a temporary buffer to do the substitution
21657 * into. It will contain:
21658 * - The text up to where the match is.
21659 * - The substituted text.
21660 * - The text after the match.
21662 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
21663 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
21664 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
21666 ga_clear(&ga);
21667 break;
21670 /* copy the text up to where the match is */
21671 i = (int)(regmatch.startp[0] - tail);
21672 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
21673 /* add the substituted text */
21674 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
21675 + ga.ga_len + i, TRUE, TRUE, FALSE);
21676 ga.ga_len += i + sublen - 1;
21677 /* avoid getting stuck on a match with an empty string */
21678 if (tail == regmatch.endp[0])
21680 if (*tail == NUL)
21681 break;
21682 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
21683 ++ga.ga_len;
21685 else
21687 tail = regmatch.endp[0];
21688 if (*tail == NUL)
21689 break;
21691 if (!do_all)
21692 break;
21695 if (ga.ga_data != NULL)
21696 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
21698 vim_free(regmatch.regprog);
21701 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
21702 ga_clear(&ga);
21703 p_cpo = save_cpo;
21705 return ret;
21708 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */