Misc. changes for further hacks
[vim-kana.git] / src / eval.c
blobbcf9b79d9ca0dedc1e309788e8088069c4dbf8f8
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;
13960 #define SP_NOMOVE 0x01 /* don't move cursor */
13961 #define SP_REPEAT 0x02 /* repeat to find outer pair */
13962 #define SP_RETCOUNT 0x04 /* return matchcount */
13963 #define SP_SETPCMARK 0x08 /* set previous context mark */
13964 #define SP_START 0x10 /* accept match at start position */
13965 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
13966 #define SP_END 0x40 /* leave cursor at end of match */
13968 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
13971 * Get flags for a search function.
13972 * Possibly sets "p_ws".
13973 * Returns BACKWARD, FORWARD or zero (for an error).
13975 static int
13976 get_search_arg(varp, flagsp)
13977 typval_T *varp;
13978 int *flagsp;
13980 int dir = FORWARD;
13981 char_u *flags;
13982 char_u nbuf[NUMBUFLEN];
13983 int mask;
13985 if (varp->v_type != VAR_UNKNOWN)
13987 flags = get_tv_string_buf_chk(varp, nbuf);
13988 if (flags == NULL)
13989 return 0; /* type error; errmsg already given */
13990 while (*flags != NUL)
13992 switch (*flags)
13994 case 'b': dir = BACKWARD; break;
13995 case 'w': p_ws = TRUE; break;
13996 case 'W': p_ws = FALSE; break;
13997 default: mask = 0;
13998 if (flagsp != NULL)
13999 switch (*flags)
14001 case 'c': mask = SP_START; break;
14002 case 'e': mask = SP_END; break;
14003 case 'm': mask = SP_RETCOUNT; break;
14004 case 'n': mask = SP_NOMOVE; break;
14005 case 'p': mask = SP_SUBPAT; break;
14006 case 'r': mask = SP_REPEAT; break;
14007 case 's': mask = SP_SETPCMARK; break;
14009 if (mask == 0)
14011 EMSG2(_(e_invarg2), flags);
14012 dir = 0;
14014 else
14015 *flagsp |= mask;
14017 if (dir == 0)
14018 break;
14019 ++flags;
14022 return dir;
14026 * Shared by search() and searchpos() functions
14028 static int
14029 search_cmn(argvars, match_pos, flagsp)
14030 typval_T *argvars;
14031 pos_T *match_pos;
14032 int *flagsp;
14034 int flags;
14035 char_u *pat;
14036 pos_T pos;
14037 pos_T save_cursor;
14038 int save_p_ws = p_ws;
14039 int dir;
14040 int retval = 0; /* default: FAIL */
14041 long lnum_stop = 0;
14042 proftime_T tm;
14043 #ifdef FEAT_RELTIME
14044 long time_limit = 0;
14045 #endif
14046 int options = SEARCH_KEEP;
14047 int subpatnum;
14049 pat = get_tv_string(&argvars[0]);
14050 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
14051 if (dir == 0)
14052 goto theend;
14053 flags = *flagsp;
14054 if (flags & SP_START)
14055 options |= SEARCH_START;
14056 if (flags & SP_END)
14057 options |= SEARCH_END;
14059 /* Optional arguments: line number to stop searching and timeout. */
14060 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
14062 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
14063 if (lnum_stop < 0)
14064 goto theend;
14065 #ifdef FEAT_RELTIME
14066 if (argvars[3].v_type != VAR_UNKNOWN)
14068 time_limit = get_tv_number_chk(&argvars[3], NULL);
14069 if (time_limit < 0)
14070 goto theend;
14072 #endif
14075 #ifdef FEAT_RELTIME
14076 /* Set the time limit, if there is one. */
14077 profile_setlimit(time_limit, &tm);
14078 #endif
14081 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
14082 * Check to make sure only those flags are set.
14083 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
14084 * flags cannot be set. Check for that condition also.
14086 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
14087 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14089 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
14090 goto theend;
14093 pos = save_cursor = curwin->w_cursor;
14094 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14095 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
14096 if (subpatnum != FAIL)
14098 if (flags & SP_SUBPAT)
14099 retval = subpatnum;
14100 else
14101 retval = pos.lnum;
14102 if (flags & SP_SETPCMARK)
14103 setpcmark();
14104 curwin->w_cursor = pos;
14105 if (match_pos != NULL)
14107 /* Store the match cursor position */
14108 match_pos->lnum = pos.lnum;
14109 match_pos->col = pos.col + 1;
14111 /* "/$" will put the cursor after the end of the line, may need to
14112 * correct that here */
14113 check_cursor();
14116 /* If 'n' flag is used: restore cursor position. */
14117 if (flags & SP_NOMOVE)
14118 curwin->w_cursor = save_cursor;
14119 else
14120 curwin->w_set_curswant = TRUE;
14121 theend:
14122 p_ws = save_p_ws;
14124 return retval;
14128 * "search()" function
14130 static void
14131 f_search(argvars, rettv)
14132 typval_T *argvars;
14133 typval_T *rettv;
14135 int flags = 0;
14137 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
14141 * "searchdecl()" function
14143 static void
14144 f_searchdecl(argvars, rettv)
14145 typval_T *argvars;
14146 typval_T *rettv;
14148 int locally = 1;
14149 int thisblock = 0;
14150 int error = FALSE;
14151 char_u *name;
14153 rettv->vval.v_number = 1; /* default: FAIL */
14155 name = get_tv_string_chk(&argvars[0]);
14156 if (argvars[1].v_type != VAR_UNKNOWN)
14158 locally = get_tv_number_chk(&argvars[1], &error) == 0;
14159 if (!error && argvars[2].v_type != VAR_UNKNOWN)
14160 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
14162 if (!error && name != NULL)
14163 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
14164 locally, thisblock, SEARCH_KEEP) == FAIL;
14168 * Used by searchpair() and searchpairpos()
14170 static int
14171 searchpair_cmn(argvars, match_pos)
14172 typval_T *argvars;
14173 pos_T *match_pos;
14175 char_u *spat, *mpat, *epat;
14176 char_u *skip;
14177 int save_p_ws = p_ws;
14178 int dir;
14179 int flags = 0;
14180 char_u nbuf1[NUMBUFLEN];
14181 char_u nbuf2[NUMBUFLEN];
14182 char_u nbuf3[NUMBUFLEN];
14183 int retval = 0; /* default: FAIL */
14184 long lnum_stop = 0;
14185 long time_limit = 0;
14187 /* Get the three pattern arguments: start, middle, end. */
14188 spat = get_tv_string_chk(&argvars[0]);
14189 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
14190 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
14191 if (spat == NULL || mpat == NULL || epat == NULL)
14192 goto theend; /* type error */
14194 /* Handle the optional fourth argument: flags */
14195 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
14196 if (dir == 0)
14197 goto theend;
14199 /* Don't accept SP_END or SP_SUBPAT.
14200 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
14202 if ((flags & (SP_END | SP_SUBPAT)) != 0
14203 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14205 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
14206 goto theend;
14209 /* Using 'r' implies 'W', otherwise it doesn't work. */
14210 if (flags & SP_REPEAT)
14211 p_ws = FALSE;
14213 /* Optional fifth argument: skip expression */
14214 if (argvars[3].v_type == VAR_UNKNOWN
14215 || argvars[4].v_type == VAR_UNKNOWN)
14216 skip = (char_u *)"";
14217 else
14219 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
14220 if (argvars[5].v_type != VAR_UNKNOWN)
14222 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
14223 if (lnum_stop < 0)
14224 goto theend;
14225 #ifdef FEAT_RELTIME
14226 if (argvars[6].v_type != VAR_UNKNOWN)
14228 time_limit = get_tv_number_chk(&argvars[6], NULL);
14229 if (time_limit < 0)
14230 goto theend;
14232 #endif
14235 if (skip == NULL)
14236 goto theend; /* type error */
14238 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
14239 match_pos, lnum_stop, time_limit);
14241 theend:
14242 p_ws = save_p_ws;
14244 return retval;
14248 * "searchpair()" function
14250 static void
14251 f_searchpair(argvars, rettv)
14252 typval_T *argvars;
14253 typval_T *rettv;
14255 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
14259 * "searchpairpos()" function
14261 static void
14262 f_searchpairpos(argvars, rettv)
14263 typval_T *argvars;
14264 typval_T *rettv;
14266 pos_T match_pos;
14267 int lnum = 0;
14268 int col = 0;
14270 rettv->vval.v_number = 0;
14272 if (rettv_list_alloc(rettv) == FAIL)
14273 return;
14275 if (searchpair_cmn(argvars, &match_pos) > 0)
14277 lnum = match_pos.lnum;
14278 col = match_pos.col;
14281 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14282 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14286 * Search for a start/middle/end thing.
14287 * Used by searchpair(), see its documentation for the details.
14288 * Returns 0 or -1 for no match,
14290 long
14291 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
14292 lnum_stop, time_limit)
14293 char_u *spat; /* start pattern */
14294 char_u *mpat; /* middle pattern */
14295 char_u *epat; /* end pattern */
14296 int dir; /* BACKWARD or FORWARD */
14297 char_u *skip; /* skip expression */
14298 int flags; /* SP_SETPCMARK and other SP_ values */
14299 pos_T *match_pos;
14300 linenr_T lnum_stop; /* stop at this line if not zero */
14301 long time_limit; /* stop after this many msec */
14303 char_u *save_cpo;
14304 char_u *pat, *pat2 = NULL, *pat3 = NULL;
14305 long retval = 0;
14306 pos_T pos;
14307 pos_T firstpos;
14308 pos_T foundpos;
14309 pos_T save_cursor;
14310 pos_T save_pos;
14311 int n;
14312 int r;
14313 int nest = 1;
14314 int err;
14315 int options = SEARCH_KEEP;
14316 proftime_T tm;
14318 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
14319 save_cpo = p_cpo;
14320 p_cpo = (char_u *)"";
14322 #ifdef FEAT_RELTIME
14323 /* Set the time limit, if there is one. */
14324 profile_setlimit(time_limit, &tm);
14325 #endif
14327 /* Make two search patterns: start/end (pat2, for in nested pairs) and
14328 * start/middle/end (pat3, for the top pair). */
14329 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
14330 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
14331 if (pat2 == NULL || pat3 == NULL)
14332 goto theend;
14333 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
14334 if (*mpat == NUL)
14335 STRCPY(pat3, pat2);
14336 else
14337 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
14338 spat, epat, mpat);
14339 if (flags & SP_START)
14340 options |= SEARCH_START;
14342 save_cursor = curwin->w_cursor;
14343 pos = curwin->w_cursor;
14344 clearpos(&firstpos);
14345 clearpos(&foundpos);
14346 pat = pat3;
14347 for (;;)
14349 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14350 options, RE_SEARCH, lnum_stop, &tm);
14351 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
14352 /* didn't find it or found the first match again: FAIL */
14353 break;
14355 if (firstpos.lnum == 0)
14356 firstpos = pos;
14357 if (equalpos(pos, foundpos))
14359 /* Found the same position again. Can happen with a pattern that
14360 * has "\zs" at the end and searching backwards. Advance one
14361 * character and try again. */
14362 if (dir == BACKWARD)
14363 decl(&pos);
14364 else
14365 incl(&pos);
14367 foundpos = pos;
14369 /* clear the start flag to avoid getting stuck here */
14370 options &= ~SEARCH_START;
14372 /* If the skip pattern matches, ignore this match. */
14373 if (*skip != NUL)
14375 save_pos = curwin->w_cursor;
14376 curwin->w_cursor = pos;
14377 r = eval_to_bool(skip, &err, NULL, FALSE);
14378 curwin->w_cursor = save_pos;
14379 if (err)
14381 /* Evaluating {skip} caused an error, break here. */
14382 curwin->w_cursor = save_cursor;
14383 retval = -1;
14384 break;
14386 if (r)
14387 continue;
14390 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
14392 /* Found end when searching backwards or start when searching
14393 * forward: nested pair. */
14394 ++nest;
14395 pat = pat2; /* nested, don't search for middle */
14397 else
14399 /* Found end when searching forward or start when searching
14400 * backward: end of (nested) pair; or found middle in outer pair. */
14401 if (--nest == 1)
14402 pat = pat3; /* outer level, search for middle */
14405 if (nest == 0)
14407 /* Found the match: return matchcount or line number. */
14408 if (flags & SP_RETCOUNT)
14409 ++retval;
14410 else
14411 retval = pos.lnum;
14412 if (flags & SP_SETPCMARK)
14413 setpcmark();
14414 curwin->w_cursor = pos;
14415 if (!(flags & SP_REPEAT))
14416 break;
14417 nest = 1; /* search for next unmatched */
14421 if (match_pos != NULL)
14423 /* Store the match cursor position */
14424 match_pos->lnum = curwin->w_cursor.lnum;
14425 match_pos->col = curwin->w_cursor.col + 1;
14428 /* If 'n' flag is used or search failed: restore cursor position. */
14429 if ((flags & SP_NOMOVE) || retval == 0)
14430 curwin->w_cursor = save_cursor;
14432 theend:
14433 vim_free(pat2);
14434 vim_free(pat3);
14435 p_cpo = save_cpo;
14437 return retval;
14441 * "searchpos()" function
14443 static void
14444 f_searchpos(argvars, rettv)
14445 typval_T *argvars;
14446 typval_T *rettv;
14448 pos_T match_pos;
14449 int lnum = 0;
14450 int col = 0;
14451 int n;
14452 int flags = 0;
14454 rettv->vval.v_number = 0;
14456 if (rettv_list_alloc(rettv) == FAIL)
14457 return;
14459 n = search_cmn(argvars, &match_pos, &flags);
14460 if (n > 0)
14462 lnum = match_pos.lnum;
14463 col = match_pos.col;
14466 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14467 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14468 if (flags & SP_SUBPAT)
14469 list_append_number(rettv->vval.v_list, (varnumber_T)n);
14473 /*ARGSUSED*/
14474 static void
14475 f_server2client(argvars, rettv)
14476 typval_T *argvars;
14477 typval_T *rettv;
14479 #ifdef FEAT_CLIENTSERVER
14480 char_u buf[NUMBUFLEN];
14481 char_u *server = get_tv_string_chk(&argvars[0]);
14482 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
14484 rettv->vval.v_number = -1;
14485 if (server == NULL || reply == NULL)
14486 return;
14487 if (check_restricted() || check_secure())
14488 return;
14489 # ifdef FEAT_X11
14490 if (check_connection() == FAIL)
14491 return;
14492 # endif
14494 if (serverSendReply(server, reply) < 0)
14496 EMSG(_("E258: Unable to send to client"));
14497 return;
14499 rettv->vval.v_number = 0;
14500 #else
14501 rettv->vval.v_number = -1;
14502 #endif
14505 /*ARGSUSED*/
14506 static void
14507 f_serverlist(argvars, rettv)
14508 typval_T *argvars;
14509 typval_T *rettv;
14511 char_u *r = NULL;
14513 #ifdef FEAT_CLIENTSERVER
14514 # ifdef WIN32
14515 r = serverGetVimNames();
14516 # else
14517 make_connection();
14518 if (X_DISPLAY != NULL)
14519 r = serverGetVimNames(X_DISPLAY);
14520 # endif
14521 #endif
14522 rettv->v_type = VAR_STRING;
14523 rettv->vval.v_string = r;
14527 * "setbufvar()" function
14529 /*ARGSUSED*/
14530 static void
14531 f_setbufvar(argvars, rettv)
14532 typval_T *argvars;
14533 typval_T *rettv;
14535 buf_T *buf;
14536 aco_save_T aco;
14537 char_u *varname, *bufvarname;
14538 typval_T *varp;
14539 char_u nbuf[NUMBUFLEN];
14541 rettv->vval.v_number = 0;
14543 if (check_restricted() || check_secure())
14544 return;
14545 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
14546 varname = get_tv_string_chk(&argvars[1]);
14547 buf = get_buf_tv(&argvars[0]);
14548 varp = &argvars[2];
14550 if (buf != NULL && varname != NULL && varp != NULL)
14552 /* set curbuf to be our buf, temporarily */
14553 aucmd_prepbuf(&aco, buf);
14555 if (*varname == '&')
14557 long numval;
14558 char_u *strval;
14559 int error = FALSE;
14561 ++varname;
14562 numval = get_tv_number_chk(varp, &error);
14563 strval = get_tv_string_buf_chk(varp, nbuf);
14564 if (!error && strval != NULL)
14565 set_option_value(varname, numval, strval, OPT_LOCAL);
14567 else
14569 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
14570 if (bufvarname != NULL)
14572 STRCPY(bufvarname, "b:");
14573 STRCPY(bufvarname + 2, varname);
14574 set_var(bufvarname, varp, TRUE);
14575 vim_free(bufvarname);
14579 /* reset notion of buffer */
14580 aucmd_restbuf(&aco);
14585 * "setcmdpos()" function
14587 static void
14588 f_setcmdpos(argvars, rettv)
14589 typval_T *argvars;
14590 typval_T *rettv;
14592 int pos = (int)get_tv_number(&argvars[0]) - 1;
14594 if (pos >= 0)
14595 rettv->vval.v_number = set_cmdline_pos(pos);
14599 * "setline()" function
14601 static void
14602 f_setline(argvars, rettv)
14603 typval_T *argvars;
14604 typval_T *rettv;
14606 linenr_T lnum;
14607 char_u *line = NULL;
14608 list_T *l = NULL;
14609 listitem_T *li = NULL;
14610 long added = 0;
14611 linenr_T lcount = curbuf->b_ml.ml_line_count;
14613 lnum = get_tv_lnum(&argvars[0]);
14614 if (argvars[1].v_type == VAR_LIST)
14616 l = argvars[1].vval.v_list;
14617 li = l->lv_first;
14619 else
14620 line = get_tv_string_chk(&argvars[1]);
14622 rettv->vval.v_number = 0; /* OK */
14623 for (;;)
14625 if (l != NULL)
14627 /* list argument, get next string */
14628 if (li == NULL)
14629 break;
14630 line = get_tv_string_chk(&li->li_tv);
14631 li = li->li_next;
14634 rettv->vval.v_number = 1; /* FAIL */
14635 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
14636 break;
14637 if (lnum <= curbuf->b_ml.ml_line_count)
14639 /* existing line, replace it */
14640 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
14642 changed_bytes(lnum, 0);
14643 if (lnum == curwin->w_cursor.lnum)
14644 check_cursor_col();
14645 rettv->vval.v_number = 0; /* OK */
14648 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
14650 /* lnum is one past the last line, append the line */
14651 ++added;
14652 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
14653 rettv->vval.v_number = 0; /* OK */
14656 if (l == NULL) /* only one string argument */
14657 break;
14658 ++lnum;
14661 if (added > 0)
14662 appended_lines_mark(lcount, added);
14666 * Used by "setqflist()" and "setloclist()" functions
14668 /*ARGSUSED*/
14669 static void
14670 set_qf_ll_list(wp, list_arg, action_arg, rettv)
14671 win_T *wp;
14672 typval_T *list_arg;
14673 typval_T *action_arg;
14674 typval_T *rettv;
14676 #ifdef FEAT_QUICKFIX
14677 char_u *act;
14678 int action = ' ';
14679 #endif
14681 rettv->vval.v_number = -1;
14683 #ifdef FEAT_QUICKFIX
14684 if (list_arg->v_type != VAR_LIST)
14685 EMSG(_(e_listreq));
14686 else
14688 list_T *l = list_arg->vval.v_list;
14690 if (action_arg->v_type == VAR_STRING)
14692 act = get_tv_string_chk(action_arg);
14693 if (act == NULL)
14694 return; /* type error; errmsg already given */
14695 if (*act == 'a' || *act == 'r')
14696 action = *act;
14699 if (l != NULL && set_errorlist(wp, l, action) == OK)
14700 rettv->vval.v_number = 0;
14702 #endif
14706 * "setloclist()" function
14708 /*ARGSUSED*/
14709 static void
14710 f_setloclist(argvars, rettv)
14711 typval_T *argvars;
14712 typval_T *rettv;
14714 win_T *win;
14716 rettv->vval.v_number = -1;
14718 win = find_win_by_nr(&argvars[0], NULL);
14719 if (win != NULL)
14720 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
14724 * "setmatches()" function
14726 static void
14727 f_setmatches(argvars, rettv)
14728 typval_T *argvars;
14729 typval_T *rettv;
14731 #ifdef FEAT_SEARCH_EXTRA
14732 list_T *l;
14733 listitem_T *li;
14734 dict_T *d;
14736 rettv->vval.v_number = -1;
14737 if (argvars[0].v_type != VAR_LIST)
14739 EMSG(_(e_listreq));
14740 return;
14742 if ((l = argvars[0].vval.v_list) != NULL)
14745 /* To some extent make sure that we are dealing with a list from
14746 * "getmatches()". */
14747 li = l->lv_first;
14748 while (li != NULL)
14750 if (li->li_tv.v_type != VAR_DICT
14751 || (d = li->li_tv.vval.v_dict) == NULL)
14753 EMSG(_(e_invarg));
14754 return;
14756 if (!(dict_find(d, (char_u *)"group", -1) != NULL
14757 && dict_find(d, (char_u *)"pattern", -1) != NULL
14758 && dict_find(d, (char_u *)"priority", -1) != NULL
14759 && dict_find(d, (char_u *)"id", -1) != NULL))
14761 EMSG(_(e_invarg));
14762 return;
14764 li = li->li_next;
14767 clear_matches(curwin);
14768 li = l->lv_first;
14769 while (li != NULL)
14771 d = li->li_tv.vval.v_dict;
14772 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
14773 get_dict_string(d, (char_u *)"pattern", FALSE),
14774 (int)get_dict_number(d, (char_u *)"priority"),
14775 (int)get_dict_number(d, (char_u *)"id"));
14776 li = li->li_next;
14778 rettv->vval.v_number = 0;
14780 #endif
14784 * "setpos()" function
14786 /*ARGSUSED*/
14787 static void
14788 f_setpos(argvars, rettv)
14789 typval_T *argvars;
14790 typval_T *rettv;
14792 pos_T pos;
14793 int fnum;
14794 char_u *name;
14796 rettv->vval.v_number = -1;
14797 name = get_tv_string_chk(argvars);
14798 if (name != NULL)
14800 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
14802 --pos.col;
14803 if (name[0] == '.' && name[1] == NUL)
14805 /* set cursor */
14806 if (fnum == curbuf->b_fnum)
14808 curwin->w_cursor = pos;
14809 check_cursor();
14810 rettv->vval.v_number = 0;
14812 else
14813 EMSG(_(e_invarg));
14815 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
14817 /* set mark */
14818 if (setmark_pos(name[1], &pos, fnum) == OK)
14819 rettv->vval.v_number = 0;
14821 else
14822 EMSG(_(e_invarg));
14828 * "setqflist()" function
14830 /*ARGSUSED*/
14831 static void
14832 f_setqflist(argvars, rettv)
14833 typval_T *argvars;
14834 typval_T *rettv;
14836 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
14840 * "setreg()" function
14842 static void
14843 f_setreg(argvars, rettv)
14844 typval_T *argvars;
14845 typval_T *rettv;
14847 int regname;
14848 char_u *strregname;
14849 char_u *stropt;
14850 char_u *strval;
14851 int append;
14852 char_u yank_type;
14853 long block_len;
14855 block_len = -1;
14856 yank_type = MAUTO;
14857 append = FALSE;
14859 strregname = get_tv_string_chk(argvars);
14860 rettv->vval.v_number = 1; /* FAIL is default */
14862 if (strregname == NULL)
14863 return; /* type error; errmsg already given */
14864 regname = *strregname;
14865 if (regname == 0 || regname == '@')
14866 regname = '"';
14867 else if (regname == '=')
14868 return;
14870 if (argvars[2].v_type != VAR_UNKNOWN)
14872 stropt = get_tv_string_chk(&argvars[2]);
14873 if (stropt == NULL)
14874 return; /* type error */
14875 for (; *stropt != NUL; ++stropt)
14876 switch (*stropt)
14878 case 'a': case 'A': /* append */
14879 append = TRUE;
14880 break;
14881 case 'v': case 'c': /* character-wise selection */
14882 yank_type = MCHAR;
14883 break;
14884 case 'V': case 'l': /* line-wise selection */
14885 yank_type = MLINE;
14886 break;
14887 #ifdef FEAT_VISUAL
14888 case 'b': case Ctrl_V: /* block-wise selection */
14889 yank_type = MBLOCK;
14890 if (VIM_ISDIGIT(stropt[1]))
14892 ++stropt;
14893 block_len = getdigits(&stropt) - 1;
14894 --stropt;
14896 break;
14897 #endif
14901 strval = get_tv_string_chk(&argvars[1]);
14902 if (strval != NULL)
14903 write_reg_contents_ex(regname, strval, -1,
14904 append, yank_type, block_len);
14905 rettv->vval.v_number = 0;
14909 * "settabwinvar()" function
14911 static void
14912 f_settabwinvar(argvars, rettv)
14913 typval_T *argvars;
14914 typval_T *rettv;
14916 setwinvar(argvars, rettv, 1);
14920 * "setwinvar()" function
14922 static void
14923 f_setwinvar(argvars, rettv)
14924 typval_T *argvars;
14925 typval_T *rettv;
14927 setwinvar(argvars, rettv, 0);
14931 * "setwinvar()" and "settabwinvar()" functions
14933 static void
14934 setwinvar(argvars, rettv, off)
14935 typval_T *argvars;
14936 typval_T *rettv;
14937 int off;
14939 win_T *win;
14940 #ifdef FEAT_WINDOWS
14941 win_T *save_curwin;
14942 tabpage_T *save_curtab;
14943 #endif
14944 char_u *varname, *winvarname;
14945 typval_T *varp;
14946 char_u nbuf[NUMBUFLEN];
14947 tabpage_T *tp;
14949 rettv->vval.v_number = 0;
14951 if (check_restricted() || check_secure())
14952 return;
14954 #ifdef FEAT_WINDOWS
14955 if (off == 1)
14956 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
14957 else
14958 tp = curtab;
14959 #endif
14960 win = find_win_by_nr(&argvars[off], tp);
14961 varname = get_tv_string_chk(&argvars[off + 1]);
14962 varp = &argvars[off + 2];
14964 if (win != NULL && varname != NULL && varp != NULL)
14966 #ifdef FEAT_WINDOWS
14967 /* set curwin to be our win, temporarily */
14968 save_curwin = curwin;
14969 save_curtab = curtab;
14970 goto_tabpage_tp(tp);
14971 if (!win_valid(win))
14972 return;
14973 curwin = win;
14974 curbuf = curwin->w_buffer;
14975 #endif
14977 if (*varname == '&')
14979 long numval;
14980 char_u *strval;
14981 int error = FALSE;
14983 ++varname;
14984 numval = get_tv_number_chk(varp, &error);
14985 strval = get_tv_string_buf_chk(varp, nbuf);
14986 if (!error && strval != NULL)
14987 set_option_value(varname, numval, strval, OPT_LOCAL);
14989 else
14991 winvarname = alloc((unsigned)STRLEN(varname) + 3);
14992 if (winvarname != NULL)
14994 STRCPY(winvarname, "w:");
14995 STRCPY(winvarname + 2, varname);
14996 set_var(winvarname, varp, TRUE);
14997 vim_free(winvarname);
15001 #ifdef FEAT_WINDOWS
15002 /* Restore current tabpage and window, if still valid (autocomands can
15003 * make them invalid). */
15004 if (valid_tabpage(save_curtab))
15005 goto_tabpage_tp(save_curtab);
15006 if (win_valid(save_curwin))
15008 curwin = save_curwin;
15009 curbuf = curwin->w_buffer;
15011 #endif
15016 * "shellescape({string})" function
15018 static void
15019 f_shellescape(argvars, rettv)
15020 typval_T *argvars;
15021 typval_T *rettv;
15023 rettv->vval.v_string = vim_strsave_shellescape(get_tv_string(&argvars[0]));
15024 rettv->v_type = VAR_STRING;
15028 * "simplify()" function
15030 static void
15031 f_simplify(argvars, rettv)
15032 typval_T *argvars;
15033 typval_T *rettv;
15035 char_u *p;
15037 p = get_tv_string(&argvars[0]);
15038 rettv->vval.v_string = vim_strsave(p);
15039 simplify_filename(rettv->vval.v_string); /* simplify in place */
15040 rettv->v_type = VAR_STRING;
15043 static int
15044 #ifdef __BORLANDC__
15045 _RTLENTRYF
15046 #endif
15047 item_compare __ARGS((const void *s1, const void *s2));
15048 static int
15049 #ifdef __BORLANDC__
15050 _RTLENTRYF
15051 #endif
15052 item_compare2 __ARGS((const void *s1, const void *s2));
15054 static int item_compare_ic;
15055 static char_u *item_compare_func;
15056 static int item_compare_func_err;
15057 #define ITEM_COMPARE_FAIL 999
15060 * Compare functions for f_sort() below.
15062 static int
15063 #ifdef __BORLANDC__
15064 _RTLENTRYF
15065 #endif
15066 item_compare(s1, s2)
15067 const void *s1;
15068 const void *s2;
15070 char_u *p1, *p2;
15071 char_u *tofree1, *tofree2;
15072 int res;
15073 char_u numbuf1[NUMBUFLEN];
15074 char_u numbuf2[NUMBUFLEN];
15076 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
15077 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
15078 if (p1 == NULL)
15079 p1 = (char_u *)"";
15080 if (p2 == NULL)
15081 p2 = (char_u *)"";
15082 if (item_compare_ic)
15083 res = STRICMP(p1, p2);
15084 else
15085 res = STRCMP(p1, p2);
15086 vim_free(tofree1);
15087 vim_free(tofree2);
15088 return res;
15091 static int
15092 #ifdef __BORLANDC__
15093 _RTLENTRYF
15094 #endif
15095 item_compare2(s1, s2)
15096 const void *s1;
15097 const void *s2;
15099 int res;
15100 typval_T rettv;
15101 typval_T argv[3];
15102 int dummy;
15104 /* shortcut after failure in previous call; compare all items equal */
15105 if (item_compare_func_err)
15106 return 0;
15108 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
15109 * in the copy without changing the original list items. */
15110 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
15111 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
15113 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
15114 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
15115 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
15116 clear_tv(&argv[0]);
15117 clear_tv(&argv[1]);
15119 if (res == FAIL)
15120 res = ITEM_COMPARE_FAIL;
15121 else
15122 /* return value has wrong type */
15123 res = get_tv_number_chk(&rettv, &item_compare_func_err);
15124 if (item_compare_func_err)
15125 res = ITEM_COMPARE_FAIL;
15126 clear_tv(&rettv);
15127 return res;
15131 * "sort({list})" function
15133 static void
15134 f_sort(argvars, rettv)
15135 typval_T *argvars;
15136 typval_T *rettv;
15138 list_T *l;
15139 listitem_T *li;
15140 listitem_T **ptrs;
15141 long len;
15142 long i;
15144 rettv->vval.v_number = 0;
15145 if (argvars[0].v_type != VAR_LIST)
15146 EMSG2(_(e_listarg), "sort()");
15147 else
15149 l = argvars[0].vval.v_list;
15150 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
15151 return;
15152 rettv->vval.v_list = l;
15153 rettv->v_type = VAR_LIST;
15154 ++l->lv_refcount;
15156 len = list_len(l);
15157 if (len <= 1)
15158 return; /* short list sorts pretty quickly */
15160 item_compare_ic = FALSE;
15161 item_compare_func = NULL;
15162 if (argvars[1].v_type != VAR_UNKNOWN)
15164 if (argvars[1].v_type == VAR_FUNC)
15165 item_compare_func = argvars[1].vval.v_string;
15166 else
15168 int error = FALSE;
15170 i = get_tv_number_chk(&argvars[1], &error);
15171 if (error)
15172 return; /* type error; errmsg already given */
15173 if (i == 1)
15174 item_compare_ic = TRUE;
15175 else
15176 item_compare_func = get_tv_string(&argvars[1]);
15180 /* Make an array with each entry pointing to an item in the List. */
15181 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
15182 if (ptrs == NULL)
15183 return;
15184 i = 0;
15185 for (li = l->lv_first; li != NULL; li = li->li_next)
15186 ptrs[i++] = li;
15188 item_compare_func_err = FALSE;
15189 /* test the compare function */
15190 if (item_compare_func != NULL
15191 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
15192 == ITEM_COMPARE_FAIL)
15193 EMSG(_("E702: Sort compare function failed"));
15194 else
15196 /* Sort the array with item pointers. */
15197 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
15198 item_compare_func == NULL ? item_compare : item_compare2);
15200 if (!item_compare_func_err)
15202 /* Clear the List and append the items in the sorted order. */
15203 l->lv_first = l->lv_last = NULL;
15204 l->lv_len = 0;
15205 for (i = 0; i < len; ++i)
15206 list_append(l, ptrs[i]);
15210 vim_free(ptrs);
15215 * "soundfold({word})" function
15217 static void
15218 f_soundfold(argvars, rettv)
15219 typval_T *argvars;
15220 typval_T *rettv;
15222 char_u *s;
15224 rettv->v_type = VAR_STRING;
15225 s = get_tv_string(&argvars[0]);
15226 #ifdef FEAT_SPELL
15227 rettv->vval.v_string = eval_soundfold(s);
15228 #else
15229 rettv->vval.v_string = vim_strsave(s);
15230 #endif
15234 * "spellbadword()" function
15236 /* ARGSUSED */
15237 static void
15238 f_spellbadword(argvars, rettv)
15239 typval_T *argvars;
15240 typval_T *rettv;
15242 char_u *word = (char_u *)"";
15243 hlf_T attr = HLF_COUNT;
15244 int len = 0;
15246 if (rettv_list_alloc(rettv) == FAIL)
15247 return;
15249 #ifdef FEAT_SPELL
15250 if (argvars[0].v_type == VAR_UNKNOWN)
15252 /* Find the start and length of the badly spelled word. */
15253 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
15254 if (len != 0)
15255 word = ml_get_cursor();
15257 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15259 char_u *str = get_tv_string_chk(&argvars[0]);
15260 int capcol = -1;
15262 if (str != NULL)
15264 /* Check the argument for spelling. */
15265 while (*str != NUL)
15267 len = spell_check(curwin, str, &attr, &capcol, FALSE);
15268 if (attr != HLF_COUNT)
15270 word = str;
15271 break;
15273 str += len;
15277 #endif
15279 list_append_string(rettv->vval.v_list, word, len);
15280 list_append_string(rettv->vval.v_list, (char_u *)(
15281 attr == HLF_SPB ? "bad" :
15282 attr == HLF_SPR ? "rare" :
15283 attr == HLF_SPL ? "local" :
15284 attr == HLF_SPC ? "caps" :
15285 ""), -1);
15289 * "spellsuggest()" function
15291 /*ARGSUSED*/
15292 static void
15293 f_spellsuggest(argvars, rettv)
15294 typval_T *argvars;
15295 typval_T *rettv;
15297 #ifdef FEAT_SPELL
15298 char_u *str;
15299 int typeerr = FALSE;
15300 int maxcount;
15301 garray_T ga;
15302 int i;
15303 listitem_T *li;
15304 int need_capital = FALSE;
15305 #endif
15307 if (rettv_list_alloc(rettv) == FAIL)
15308 return;
15310 #ifdef FEAT_SPELL
15311 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15313 str = get_tv_string(&argvars[0]);
15314 if (argvars[1].v_type != VAR_UNKNOWN)
15316 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
15317 if (maxcount <= 0)
15318 return;
15319 if (argvars[2].v_type != VAR_UNKNOWN)
15321 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
15322 if (typeerr)
15323 return;
15326 else
15327 maxcount = 25;
15329 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
15331 for (i = 0; i < ga.ga_len; ++i)
15333 str = ((char_u **)ga.ga_data)[i];
15335 li = listitem_alloc();
15336 if (li == NULL)
15337 vim_free(str);
15338 else
15340 li->li_tv.v_type = VAR_STRING;
15341 li->li_tv.v_lock = 0;
15342 li->li_tv.vval.v_string = str;
15343 list_append(rettv->vval.v_list, li);
15346 ga_clear(&ga);
15348 #endif
15351 static void
15352 f_split(argvars, rettv)
15353 typval_T *argvars;
15354 typval_T *rettv;
15356 char_u *str;
15357 char_u *end;
15358 char_u *pat = NULL;
15359 regmatch_T regmatch;
15360 char_u patbuf[NUMBUFLEN];
15361 char_u *save_cpo;
15362 int match;
15363 colnr_T col = 0;
15364 int keepempty = FALSE;
15365 int typeerr = FALSE;
15367 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15368 save_cpo = p_cpo;
15369 p_cpo = (char_u *)"";
15371 str = get_tv_string(&argvars[0]);
15372 if (argvars[1].v_type != VAR_UNKNOWN)
15374 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
15375 if (pat == NULL)
15376 typeerr = TRUE;
15377 if (argvars[2].v_type != VAR_UNKNOWN)
15378 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
15380 if (pat == NULL || *pat == NUL)
15381 pat = (char_u *)"[\\x01- ]\\+";
15383 if (rettv_list_alloc(rettv) == FAIL)
15384 return;
15385 if (typeerr)
15386 return;
15388 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
15389 if (regmatch.regprog != NULL)
15391 regmatch.rm_ic = FALSE;
15392 while (*str != NUL || keepempty)
15394 if (*str == NUL)
15395 match = FALSE; /* empty item at the end */
15396 else
15397 match = vim_regexec_nl(&regmatch, str, col);
15398 if (match)
15399 end = regmatch.startp[0];
15400 else
15401 end = str + STRLEN(str);
15402 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
15403 && *str != NUL && match && end < regmatch.endp[0]))
15405 if (list_append_string(rettv->vval.v_list, str,
15406 (int)(end - str)) == FAIL)
15407 break;
15409 if (!match)
15410 break;
15411 /* Advance to just after the match. */
15412 if (regmatch.endp[0] > str)
15413 col = 0;
15414 else
15416 /* Don't get stuck at the same match. */
15417 #ifdef FEAT_MBYTE
15418 col = (*mb_ptr2len)(regmatch.endp[0]);
15419 #else
15420 col = 1;
15421 #endif
15423 str = regmatch.endp[0];
15426 vim_free(regmatch.regprog);
15429 p_cpo = save_cpo;
15433 * "str2nr()" function
15435 static void
15436 f_str2nr(argvars, rettv)
15437 typval_T *argvars;
15438 typval_T *rettv;
15440 int base = 10;
15441 char_u *p;
15442 long n;
15444 if (argvars[1].v_type != VAR_UNKNOWN)
15446 base = get_tv_number(&argvars[1]);
15447 if (base != 8 && base != 10 && base != 16)
15449 EMSG(_(e_invarg));
15450 return;
15454 p = skipwhite(get_tv_string(&argvars[0]));
15455 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
15456 rettv->vval.v_number = n;
15459 #ifdef HAVE_STRFTIME
15461 * "strftime({format}[, {time}])" function
15463 static void
15464 f_strftime(argvars, rettv)
15465 typval_T *argvars;
15466 typval_T *rettv;
15468 char_u result_buf[256];
15469 struct tm *curtime;
15470 time_t seconds;
15471 char_u *p;
15473 rettv->v_type = VAR_STRING;
15475 p = get_tv_string(&argvars[0]);
15476 if (argvars[1].v_type == VAR_UNKNOWN)
15477 seconds = time(NULL);
15478 else
15479 seconds = (time_t)get_tv_number(&argvars[1]);
15480 curtime = localtime(&seconds);
15481 /* MSVC returns NULL for an invalid value of seconds. */
15482 if (curtime == NULL)
15483 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
15484 else
15486 # ifdef FEAT_MBYTE
15487 vimconv_T conv;
15488 char_u *enc;
15490 conv.vc_type = CONV_NONE;
15491 enc = enc_locale();
15492 convert_setup(&conv, p_enc, enc);
15493 if (conv.vc_type != CONV_NONE)
15494 p = string_convert(&conv, p, NULL);
15495 # endif
15496 if (p != NULL)
15497 (void)strftime((char *)result_buf, sizeof(result_buf),
15498 (char *)p, curtime);
15499 else
15500 result_buf[0] = NUL;
15502 # ifdef FEAT_MBYTE
15503 if (conv.vc_type != CONV_NONE)
15504 vim_free(p);
15505 convert_setup(&conv, enc, p_enc);
15506 if (conv.vc_type != CONV_NONE)
15507 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
15508 else
15509 # endif
15510 rettv->vval.v_string = vim_strsave(result_buf);
15512 # ifdef FEAT_MBYTE
15513 /* Release conversion descriptors */
15514 convert_setup(&conv, NULL, NULL);
15515 vim_free(enc);
15516 # endif
15519 #endif
15522 * "stridx()" function
15524 static void
15525 f_stridx(argvars, rettv)
15526 typval_T *argvars;
15527 typval_T *rettv;
15529 char_u buf[NUMBUFLEN];
15530 char_u *needle;
15531 char_u *haystack;
15532 char_u *save_haystack;
15533 char_u *pos;
15534 int start_idx;
15536 needle = get_tv_string_chk(&argvars[1]);
15537 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
15538 rettv->vval.v_number = -1;
15539 if (needle == NULL || haystack == NULL)
15540 return; /* type error; errmsg already given */
15542 if (argvars[2].v_type != VAR_UNKNOWN)
15544 int error = FALSE;
15546 start_idx = get_tv_number_chk(&argvars[2], &error);
15547 if (error || start_idx >= (int)STRLEN(haystack))
15548 return;
15549 if (start_idx >= 0)
15550 haystack += start_idx;
15553 pos = (char_u *)strstr((char *)haystack, (char *)needle);
15554 if (pos != NULL)
15555 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
15559 * "string()" function
15561 static void
15562 f_string(argvars, rettv)
15563 typval_T *argvars;
15564 typval_T *rettv;
15566 char_u *tofree;
15567 char_u numbuf[NUMBUFLEN];
15569 rettv->v_type = VAR_STRING;
15570 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
15571 /* Make a copy if we have a value but it's not in allocate memory. */
15572 if (rettv->vval.v_string != NULL && tofree == NULL)
15573 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
15577 * "strlen()" function
15579 static void
15580 f_strlen(argvars, rettv)
15581 typval_T *argvars;
15582 typval_T *rettv;
15584 rettv->vval.v_number = (varnumber_T)(STRLEN(
15585 get_tv_string(&argvars[0])));
15589 * "strpart()" function
15591 static void
15592 f_strpart(argvars, rettv)
15593 typval_T *argvars;
15594 typval_T *rettv;
15596 char_u *p;
15597 int n;
15598 int len;
15599 int slen;
15600 int error = FALSE;
15602 p = get_tv_string(&argvars[0]);
15603 slen = (int)STRLEN(p);
15605 n = get_tv_number_chk(&argvars[1], &error);
15606 if (error)
15607 len = 0;
15608 else if (argvars[2].v_type != VAR_UNKNOWN)
15609 len = get_tv_number(&argvars[2]);
15610 else
15611 len = slen - n; /* default len: all bytes that are available. */
15614 * Only return the overlap between the specified part and the actual
15615 * string.
15617 if (n < 0)
15619 len += n;
15620 n = 0;
15622 else if (n > slen)
15623 n = slen;
15624 if (len < 0)
15625 len = 0;
15626 else if (n + len > slen)
15627 len = slen - n;
15629 rettv->v_type = VAR_STRING;
15630 rettv->vval.v_string = vim_strnsave(p + n, len);
15634 * "strridx()" function
15636 static void
15637 f_strridx(argvars, rettv)
15638 typval_T *argvars;
15639 typval_T *rettv;
15641 char_u buf[NUMBUFLEN];
15642 char_u *needle;
15643 char_u *haystack;
15644 char_u *rest;
15645 char_u *lastmatch = NULL;
15646 int haystack_len, end_idx;
15648 needle = get_tv_string_chk(&argvars[1]);
15649 haystack = get_tv_string_buf_chk(&argvars[0], buf);
15651 rettv->vval.v_number = -1;
15652 if (needle == NULL || haystack == NULL)
15653 return; /* type error; errmsg already given */
15655 haystack_len = (int)STRLEN(haystack);
15656 if (argvars[2].v_type != VAR_UNKNOWN)
15658 /* Third argument: upper limit for index */
15659 end_idx = get_tv_number_chk(&argvars[2], NULL);
15660 if (end_idx < 0)
15661 return; /* can never find a match */
15663 else
15664 end_idx = haystack_len;
15666 if (*needle == NUL)
15668 /* Empty string matches past the end. */
15669 lastmatch = haystack + end_idx;
15671 else
15673 for (rest = haystack; *rest != '\0'; ++rest)
15675 rest = (char_u *)strstr((char *)rest, (char *)needle);
15676 if (rest == NULL || rest > haystack + end_idx)
15677 break;
15678 lastmatch = rest;
15682 if (lastmatch == NULL)
15683 rettv->vval.v_number = -1;
15684 else
15685 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
15689 * "strtrans()" function
15691 static void
15692 f_strtrans(argvars, rettv)
15693 typval_T *argvars;
15694 typval_T *rettv;
15696 rettv->v_type = VAR_STRING;
15697 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
15701 * "submatch()" function
15703 static void
15704 f_submatch(argvars, rettv)
15705 typval_T *argvars;
15706 typval_T *rettv;
15708 rettv->v_type = VAR_STRING;
15709 rettv->vval.v_string =
15710 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
15714 * "substitute()" function
15716 static void
15717 f_substitute(argvars, rettv)
15718 typval_T *argvars;
15719 typval_T *rettv;
15721 char_u patbuf[NUMBUFLEN];
15722 char_u subbuf[NUMBUFLEN];
15723 char_u flagsbuf[NUMBUFLEN];
15725 char_u *str = get_tv_string_chk(&argvars[0]);
15726 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
15727 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
15728 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
15730 rettv->v_type = VAR_STRING;
15731 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
15732 rettv->vval.v_string = NULL;
15733 else
15734 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
15738 * "synID(lnum, col, trans)" function
15740 /*ARGSUSED*/
15741 static void
15742 f_synID(argvars, rettv)
15743 typval_T *argvars;
15744 typval_T *rettv;
15746 int id = 0;
15747 #ifdef FEAT_SYN_HL
15748 long lnum;
15749 long col;
15750 int trans;
15751 int transerr = FALSE;
15753 lnum = get_tv_lnum(argvars); /* -1 on type error */
15754 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
15755 trans = get_tv_number_chk(&argvars[2], &transerr);
15757 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
15758 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
15759 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
15760 #endif
15762 rettv->vval.v_number = id;
15766 * "synIDattr(id, what [, mode])" function
15768 /*ARGSUSED*/
15769 static void
15770 f_synIDattr(argvars, rettv)
15771 typval_T *argvars;
15772 typval_T *rettv;
15774 char_u *p = NULL;
15775 #ifdef FEAT_SYN_HL
15776 int id;
15777 char_u *what;
15778 char_u *mode;
15779 char_u modebuf[NUMBUFLEN];
15780 int modec;
15782 id = get_tv_number(&argvars[0]);
15783 what = get_tv_string(&argvars[1]);
15784 if (argvars[2].v_type != VAR_UNKNOWN)
15786 mode = get_tv_string_buf(&argvars[2], modebuf);
15787 modec = TOLOWER_ASC(mode[0]);
15788 if (modec != 't' && modec != 'c'
15789 #ifdef FEAT_GUI
15790 && modec != 'g'
15791 #endif
15793 modec = 0; /* replace invalid with current */
15795 else
15797 #ifdef FEAT_GUI
15798 if (gui.in_use)
15799 modec = 'g';
15800 else
15801 #endif
15802 if (t_colors > 1)
15803 modec = 'c';
15804 else
15805 modec = 't';
15809 switch (TOLOWER_ASC(what[0]))
15811 case 'b':
15812 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
15813 p = highlight_color(id, what, modec);
15814 else /* bold */
15815 p = highlight_has_attr(id, HL_BOLD, modec);
15816 break;
15818 case 'f': /* fg[#] */
15819 p = highlight_color(id, what, modec);
15820 break;
15822 case 'i':
15823 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
15824 p = highlight_has_attr(id, HL_INVERSE, modec);
15825 else /* italic */
15826 p = highlight_has_attr(id, HL_ITALIC, modec);
15827 break;
15829 case 'n': /* name */
15830 p = get_highlight_name(NULL, id - 1);
15831 break;
15833 case 'r': /* reverse */
15834 p = highlight_has_attr(id, HL_INVERSE, modec);
15835 break;
15837 case 's': /* standout */
15838 p = highlight_has_attr(id, HL_STANDOUT, modec);
15839 break;
15841 case 'u':
15842 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
15843 /* underline */
15844 p = highlight_has_attr(id, HL_UNDERLINE, modec);
15845 else
15846 /* undercurl */
15847 p = highlight_has_attr(id, HL_UNDERCURL, modec);
15848 break;
15851 if (p != NULL)
15852 p = vim_strsave(p);
15853 #endif
15854 rettv->v_type = VAR_STRING;
15855 rettv->vval.v_string = p;
15859 * "synIDtrans(id)" function
15861 /*ARGSUSED*/
15862 static void
15863 f_synIDtrans(argvars, rettv)
15864 typval_T *argvars;
15865 typval_T *rettv;
15867 int id;
15869 #ifdef FEAT_SYN_HL
15870 id = get_tv_number(&argvars[0]);
15872 if (id > 0)
15873 id = syn_get_final_id(id);
15874 else
15875 #endif
15876 id = 0;
15878 rettv->vval.v_number = id;
15882 * "synstack(lnum, col)" function
15884 /*ARGSUSED*/
15885 static void
15886 f_synstack(argvars, rettv)
15887 typval_T *argvars;
15888 typval_T *rettv;
15890 #ifdef FEAT_SYN_HL
15891 long lnum;
15892 long col;
15893 int i;
15894 int id;
15895 #endif
15897 rettv->v_type = VAR_LIST;
15898 rettv->vval.v_list = NULL;
15900 #ifdef FEAT_SYN_HL
15901 lnum = get_tv_lnum(argvars); /* -1 on type error */
15902 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
15904 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
15905 && col >= 0 && col < (long)STRLEN(ml_get(lnum))
15906 && rettv_list_alloc(rettv) != FAIL)
15908 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
15909 for (i = 0; ; ++i)
15911 id = syn_get_stack_item(i);
15912 if (id < 0)
15913 break;
15914 if (list_append_number(rettv->vval.v_list, id) == FAIL)
15915 break;
15918 #endif
15922 * "system()" function
15924 static void
15925 f_system(argvars, rettv)
15926 typval_T *argvars;
15927 typval_T *rettv;
15929 char_u *res = NULL;
15930 char_u *p;
15931 char_u *infile = NULL;
15932 char_u buf[NUMBUFLEN];
15933 int err = FALSE;
15934 FILE *fd;
15936 if (check_restricted() || check_secure())
15937 goto done;
15939 if (argvars[1].v_type != VAR_UNKNOWN)
15942 * Write the string to a temp file, to be used for input of the shell
15943 * command.
15945 if ((infile = vim_tempname('i')) == NULL)
15947 EMSG(_(e_notmp));
15948 goto done;
15951 fd = mch_fopen((char *)infile, WRITEBIN);
15952 if (fd == NULL)
15954 EMSG2(_(e_notopen), infile);
15955 goto done;
15957 p = get_tv_string_buf_chk(&argvars[1], buf);
15958 if (p == NULL)
15960 fclose(fd);
15961 goto done; /* type error; errmsg already given */
15963 if (fwrite(p, STRLEN(p), 1, fd) != 1)
15964 err = TRUE;
15965 if (fclose(fd) != 0)
15966 err = TRUE;
15967 if (err)
15969 EMSG(_("E677: Error writing temp file"));
15970 goto done;
15974 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
15975 SHELL_SILENT | SHELL_COOKED);
15977 #ifdef USE_CR
15978 /* translate <CR> into <NL> */
15979 if (res != NULL)
15981 char_u *s;
15983 for (s = res; *s; ++s)
15985 if (*s == CAR)
15986 *s = NL;
15989 #else
15990 # ifdef USE_CRNL
15991 /* translate <CR><NL> into <NL> */
15992 if (res != NULL)
15994 char_u *s, *d;
15996 d = res;
15997 for (s = res; *s; ++s)
15999 if (s[0] == CAR && s[1] == NL)
16000 ++s;
16001 *d++ = *s;
16003 *d = NUL;
16005 # endif
16006 #endif
16008 done:
16009 if (infile != NULL)
16011 mch_remove(infile);
16012 vim_free(infile);
16014 rettv->v_type = VAR_STRING;
16015 rettv->vval.v_string = res;
16019 * "tabpagebuflist()" function
16021 /* ARGSUSED */
16022 static void
16023 f_tabpagebuflist(argvars, rettv)
16024 typval_T *argvars;
16025 typval_T *rettv;
16027 #ifndef FEAT_WINDOWS
16028 rettv->vval.v_number = 0;
16029 #else
16030 tabpage_T *tp;
16031 win_T *wp = NULL;
16033 if (argvars[0].v_type == VAR_UNKNOWN)
16034 wp = firstwin;
16035 else
16037 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16038 if (tp != NULL)
16039 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16041 if (wp == NULL)
16042 rettv->vval.v_number = 0;
16043 else
16045 if (rettv_list_alloc(rettv) == FAIL)
16046 rettv->vval.v_number = 0;
16047 else
16049 for (; wp != NULL; wp = wp->w_next)
16050 if (list_append_number(rettv->vval.v_list,
16051 wp->w_buffer->b_fnum) == FAIL)
16052 break;
16055 #endif
16060 * "tabpagenr()" function
16062 /* ARGSUSED */
16063 static void
16064 f_tabpagenr(argvars, rettv)
16065 typval_T *argvars;
16066 typval_T *rettv;
16068 int nr = 1;
16069 #ifdef FEAT_WINDOWS
16070 char_u *arg;
16072 if (argvars[0].v_type != VAR_UNKNOWN)
16074 arg = get_tv_string_chk(&argvars[0]);
16075 nr = 0;
16076 if (arg != NULL)
16078 if (STRCMP(arg, "$") == 0)
16079 nr = tabpage_index(NULL) - 1;
16080 else
16081 EMSG2(_(e_invexpr2), arg);
16084 else
16085 nr = tabpage_index(curtab);
16086 #endif
16087 rettv->vval.v_number = nr;
16091 #ifdef FEAT_WINDOWS
16092 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
16095 * Common code for tabpagewinnr() and winnr().
16097 static int
16098 get_winnr(tp, argvar)
16099 tabpage_T *tp;
16100 typval_T *argvar;
16102 win_T *twin;
16103 int nr = 1;
16104 win_T *wp;
16105 char_u *arg;
16107 twin = (tp == curtab) ? curwin : tp->tp_curwin;
16108 if (argvar->v_type != VAR_UNKNOWN)
16110 arg = get_tv_string_chk(argvar);
16111 if (arg == NULL)
16112 nr = 0; /* type error; errmsg already given */
16113 else if (STRCMP(arg, "$") == 0)
16114 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
16115 else if (STRCMP(arg, "#") == 0)
16117 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
16118 if (twin == NULL)
16119 nr = 0;
16121 else
16123 EMSG2(_(e_invexpr2), arg);
16124 nr = 0;
16128 if (nr > 0)
16129 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16130 wp != twin; wp = wp->w_next)
16132 if (wp == NULL)
16134 /* didn't find it in this tabpage */
16135 nr = 0;
16136 break;
16138 ++nr;
16140 return nr;
16142 #endif
16145 * "tabpagewinnr()" function
16147 /* ARGSUSED */
16148 static void
16149 f_tabpagewinnr(argvars, rettv)
16150 typval_T *argvars;
16151 typval_T *rettv;
16153 int nr = 1;
16154 #ifdef FEAT_WINDOWS
16155 tabpage_T *tp;
16157 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16158 if (tp == NULL)
16159 nr = 0;
16160 else
16161 nr = get_winnr(tp, &argvars[1]);
16162 #endif
16163 rettv->vval.v_number = nr;
16168 * "tagfiles()" function
16170 /*ARGSUSED*/
16171 static void
16172 f_tagfiles(argvars, rettv)
16173 typval_T *argvars;
16174 typval_T *rettv;
16176 char_u fname[MAXPATHL + 1];
16177 tagname_T tn;
16178 int first;
16180 if (rettv_list_alloc(rettv) == FAIL)
16182 rettv->vval.v_number = 0;
16183 return;
16186 for (first = TRUE; ; first = FALSE)
16187 if (get_tagfname(&tn, first, fname) == FAIL
16188 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
16189 break;
16190 tagname_free(&tn);
16194 * "taglist()" function
16196 static void
16197 f_taglist(argvars, rettv)
16198 typval_T *argvars;
16199 typval_T *rettv;
16201 char_u *tag_pattern;
16203 tag_pattern = get_tv_string(&argvars[0]);
16205 rettv->vval.v_number = FALSE;
16206 if (*tag_pattern == NUL)
16207 return;
16209 if (rettv_list_alloc(rettv) == OK)
16210 (void)get_tags(rettv->vval.v_list, tag_pattern);
16214 * "tempname()" function
16216 /*ARGSUSED*/
16217 static void
16218 f_tempname(argvars, rettv)
16219 typval_T *argvars;
16220 typval_T *rettv;
16222 static int x = 'A';
16224 rettv->v_type = VAR_STRING;
16225 rettv->vval.v_string = vim_tempname(x);
16227 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
16228 * names. Skip 'I' and 'O', they are used for shell redirection. */
16231 if (x == 'Z')
16232 x = '0';
16233 else if (x == '9')
16234 x = 'A';
16235 else
16237 #ifdef EBCDIC
16238 if (x == 'I')
16239 x = 'J';
16240 else if (x == 'R')
16241 x = 'S';
16242 else
16243 #endif
16244 ++x;
16246 } while (x == 'I' || x == 'O');
16250 * "test(list)" function: Just checking the walls...
16252 /*ARGSUSED*/
16253 static void
16254 f_test(argvars, rettv)
16255 typval_T *argvars;
16256 typval_T *rettv;
16258 /* Used for unit testing. Change the code below to your liking. */
16259 #if 0
16260 listitem_T *li;
16261 list_T *l;
16262 char_u *bad, *good;
16264 if (argvars[0].v_type != VAR_LIST)
16265 return;
16266 l = argvars[0].vval.v_list;
16267 if (l == NULL)
16268 return;
16269 li = l->lv_first;
16270 if (li == NULL)
16271 return;
16272 bad = get_tv_string(&li->li_tv);
16273 li = li->li_next;
16274 if (li == NULL)
16275 return;
16276 good = get_tv_string(&li->li_tv);
16277 rettv->vval.v_number = test_edit_score(bad, good);
16278 #endif
16282 * "tolower(string)" function
16284 static void
16285 f_tolower(argvars, rettv)
16286 typval_T *argvars;
16287 typval_T *rettv;
16289 char_u *p;
16291 p = vim_strsave(get_tv_string(&argvars[0]));
16292 rettv->v_type = VAR_STRING;
16293 rettv->vval.v_string = p;
16295 if (p != NULL)
16296 while (*p != NUL)
16298 #ifdef FEAT_MBYTE
16299 int l;
16301 if (enc_utf8)
16303 int c, lc;
16305 c = utf_ptr2char(p);
16306 lc = utf_tolower(c);
16307 l = utf_ptr2len(p);
16308 /* TODO: reallocate string when byte count changes. */
16309 if (utf_char2len(lc) == l)
16310 utf_char2bytes(lc, p);
16311 p += l;
16313 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
16314 p += l; /* skip multi-byte character */
16315 else
16316 #endif
16318 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
16319 ++p;
16325 * "toupper(string)" function
16327 static void
16328 f_toupper(argvars, rettv)
16329 typval_T *argvars;
16330 typval_T *rettv;
16332 rettv->v_type = VAR_STRING;
16333 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
16337 * "tr(string, fromstr, tostr)" function
16339 static void
16340 f_tr(argvars, rettv)
16341 typval_T *argvars;
16342 typval_T *rettv;
16344 char_u *instr;
16345 char_u *fromstr;
16346 char_u *tostr;
16347 char_u *p;
16348 #ifdef FEAT_MBYTE
16349 int inlen;
16350 int fromlen;
16351 int tolen;
16352 int idx;
16353 char_u *cpstr;
16354 int cplen;
16355 int first = TRUE;
16356 #endif
16357 char_u buf[NUMBUFLEN];
16358 char_u buf2[NUMBUFLEN];
16359 garray_T ga;
16361 instr = get_tv_string(&argvars[0]);
16362 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
16363 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
16365 /* Default return value: empty string. */
16366 rettv->v_type = VAR_STRING;
16367 rettv->vval.v_string = NULL;
16368 if (fromstr == NULL || tostr == NULL)
16369 return; /* type error; errmsg already given */
16370 ga_init2(&ga, (int)sizeof(char), 80);
16372 #ifdef FEAT_MBYTE
16373 if (!has_mbyte)
16374 #endif
16375 /* not multi-byte: fromstr and tostr must be the same length */
16376 if (STRLEN(fromstr) != STRLEN(tostr))
16378 #ifdef FEAT_MBYTE
16379 error:
16380 #endif
16381 EMSG2(_(e_invarg2), fromstr);
16382 ga_clear(&ga);
16383 return;
16386 /* fromstr and tostr have to contain the same number of chars */
16387 while (*instr != NUL)
16389 #ifdef FEAT_MBYTE
16390 if (has_mbyte)
16392 inlen = (*mb_ptr2len)(instr);
16393 cpstr = instr;
16394 cplen = inlen;
16395 idx = 0;
16396 for (p = fromstr; *p != NUL; p += fromlen)
16398 fromlen = (*mb_ptr2len)(p);
16399 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
16401 for (p = tostr; *p != NUL; p += tolen)
16403 tolen = (*mb_ptr2len)(p);
16404 if (idx-- == 0)
16406 cplen = tolen;
16407 cpstr = p;
16408 break;
16411 if (*p == NUL) /* tostr is shorter than fromstr */
16412 goto error;
16413 break;
16415 ++idx;
16418 if (first && cpstr == instr)
16420 /* Check that fromstr and tostr have the same number of
16421 * (multi-byte) characters. Done only once when a character
16422 * of instr doesn't appear in fromstr. */
16423 first = FALSE;
16424 for (p = tostr; *p != NUL; p += tolen)
16426 tolen = (*mb_ptr2len)(p);
16427 --idx;
16429 if (idx != 0)
16430 goto error;
16433 ga_grow(&ga, cplen);
16434 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
16435 ga.ga_len += cplen;
16437 instr += inlen;
16439 else
16440 #endif
16442 /* When not using multi-byte chars we can do it faster. */
16443 p = vim_strchr(fromstr, *instr);
16444 if (p != NULL)
16445 ga_append(&ga, tostr[p - fromstr]);
16446 else
16447 ga_append(&ga, *instr);
16448 ++instr;
16452 /* add a terminating NUL */
16453 ga_grow(&ga, 1);
16454 ga_append(&ga, NUL);
16456 rettv->vval.v_string = ga.ga_data;
16460 * "type(expr)" function
16462 static void
16463 f_type(argvars, rettv)
16464 typval_T *argvars;
16465 typval_T *rettv;
16467 int n;
16469 switch (argvars[0].v_type)
16471 case VAR_NUMBER: n = 0; break;
16472 case VAR_STRING: n = 1; break;
16473 case VAR_FUNC: n = 2; break;
16474 case VAR_LIST: n = 3; break;
16475 case VAR_DICT: n = 4; break;
16476 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
16478 rettv->vval.v_number = n;
16482 * "values(dict)" function
16484 static void
16485 f_values(argvars, rettv)
16486 typval_T *argvars;
16487 typval_T *rettv;
16489 dict_list(argvars, rettv, 1);
16493 * "virtcol(string)" function
16495 static void
16496 f_virtcol(argvars, rettv)
16497 typval_T *argvars;
16498 typval_T *rettv;
16500 colnr_T vcol = 0;
16501 pos_T *fp;
16502 int fnum = curbuf->b_fnum;
16504 fp = var2fpos(&argvars[0], FALSE, &fnum);
16505 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
16506 && fnum == curbuf->b_fnum)
16508 getvvcol(curwin, fp, NULL, NULL, &vcol);
16509 ++vcol;
16512 rettv->vval.v_number = vcol;
16516 * "visualmode()" function
16518 /*ARGSUSED*/
16519 static void
16520 f_visualmode(argvars, rettv)
16521 typval_T *argvars;
16522 typval_T *rettv;
16524 #ifdef FEAT_VISUAL
16525 char_u str[2];
16527 rettv->v_type = VAR_STRING;
16528 str[0] = curbuf->b_visual_mode_eval;
16529 str[1] = NUL;
16530 rettv->vval.v_string = vim_strsave(str);
16532 /* A non-zero number or non-empty string argument: reset mode. */
16533 if ((argvars[0].v_type == VAR_NUMBER
16534 && argvars[0].vval.v_number != 0)
16535 || (argvars[0].v_type == VAR_STRING
16536 && *get_tv_string(&argvars[0]) != NUL))
16537 curbuf->b_visual_mode_eval = NUL;
16538 #else
16539 rettv->vval.v_number = 0; /* return anything, it won't work anyway */
16540 #endif
16544 * "winbufnr(nr)" function
16546 static void
16547 f_winbufnr(argvars, rettv)
16548 typval_T *argvars;
16549 typval_T *rettv;
16551 win_T *wp;
16553 wp = find_win_by_nr(&argvars[0], NULL);
16554 if (wp == NULL)
16555 rettv->vval.v_number = -1;
16556 else
16557 rettv->vval.v_number = wp->w_buffer->b_fnum;
16561 * "wincol()" function
16563 /*ARGSUSED*/
16564 static void
16565 f_wincol(argvars, rettv)
16566 typval_T *argvars;
16567 typval_T *rettv;
16569 validate_cursor();
16570 rettv->vval.v_number = curwin->w_wcol + 1;
16574 * "winheight(nr)" function
16576 static void
16577 f_winheight(argvars, rettv)
16578 typval_T *argvars;
16579 typval_T *rettv;
16581 win_T *wp;
16583 wp = find_win_by_nr(&argvars[0], NULL);
16584 if (wp == NULL)
16585 rettv->vval.v_number = -1;
16586 else
16587 rettv->vval.v_number = wp->w_height;
16591 * "winline()" function
16593 /*ARGSUSED*/
16594 static void
16595 f_winline(argvars, rettv)
16596 typval_T *argvars;
16597 typval_T *rettv;
16599 validate_cursor();
16600 rettv->vval.v_number = curwin->w_wrow + 1;
16604 * "winnr()" function
16606 /* ARGSUSED */
16607 static void
16608 f_winnr(argvars, rettv)
16609 typval_T *argvars;
16610 typval_T *rettv;
16612 int nr = 1;
16614 #ifdef FEAT_WINDOWS
16615 nr = get_winnr(curtab, &argvars[0]);
16616 #endif
16617 rettv->vval.v_number = nr;
16621 * "winrestcmd()" function
16623 /* ARGSUSED */
16624 static void
16625 f_winrestcmd(argvars, rettv)
16626 typval_T *argvars;
16627 typval_T *rettv;
16629 #ifdef FEAT_WINDOWS
16630 win_T *wp;
16631 int winnr = 1;
16632 garray_T ga;
16633 char_u buf[50];
16635 ga_init2(&ga, (int)sizeof(char), 70);
16636 for (wp = firstwin; wp != NULL; wp = wp->w_next)
16638 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
16639 ga_concat(&ga, buf);
16640 # ifdef FEAT_VERTSPLIT
16641 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
16642 ga_concat(&ga, buf);
16643 # endif
16644 ++winnr;
16646 ga_append(&ga, NUL);
16648 rettv->vval.v_string = ga.ga_data;
16649 #else
16650 rettv->vval.v_string = NULL;
16651 #endif
16652 rettv->v_type = VAR_STRING;
16656 * "winrestview()" function
16658 /* ARGSUSED */
16659 static void
16660 f_winrestview(argvars, rettv)
16661 typval_T *argvars;
16662 typval_T *rettv;
16664 dict_T *dict;
16666 if (argvars[0].v_type != VAR_DICT
16667 || (dict = argvars[0].vval.v_dict) == NULL)
16668 EMSG(_(e_invarg));
16669 else
16671 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
16672 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
16673 #ifdef FEAT_VIRTUALEDIT
16674 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
16675 #endif
16676 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
16677 curwin->w_set_curswant = FALSE;
16679 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
16680 #ifdef FEAT_DIFF
16681 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
16682 #endif
16683 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
16684 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
16686 check_cursor();
16687 changed_cline_bef_curs();
16688 invalidate_botline();
16689 redraw_later(VALID);
16691 if (curwin->w_topline == 0)
16692 curwin->w_topline = 1;
16693 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
16694 curwin->w_topline = curbuf->b_ml.ml_line_count;
16695 #ifdef FEAT_DIFF
16696 check_topfill(curwin, TRUE);
16697 #endif
16702 * "winsaveview()" function
16704 /* ARGSUSED */
16705 static void
16706 f_winsaveview(argvars, rettv)
16707 typval_T *argvars;
16708 typval_T *rettv;
16710 dict_T *dict;
16712 dict = dict_alloc();
16713 if (dict == NULL)
16714 return;
16715 rettv->v_type = VAR_DICT;
16716 rettv->vval.v_dict = dict;
16717 ++dict->dv_refcount;
16719 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
16720 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
16721 #ifdef FEAT_VIRTUALEDIT
16722 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
16723 #endif
16724 update_curswant();
16725 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
16727 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
16728 #ifdef FEAT_DIFF
16729 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
16730 #endif
16731 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
16732 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
16736 * "winwidth(nr)" function
16738 static void
16739 f_winwidth(argvars, rettv)
16740 typval_T *argvars;
16741 typval_T *rettv;
16743 win_T *wp;
16745 wp = find_win_by_nr(&argvars[0], NULL);
16746 if (wp == NULL)
16747 rettv->vval.v_number = -1;
16748 else
16749 #ifdef FEAT_VERTSPLIT
16750 rettv->vval.v_number = wp->w_width;
16751 #else
16752 rettv->vval.v_number = Columns;
16753 #endif
16757 * "writefile()" function
16759 static void
16760 f_writefile(argvars, rettv)
16761 typval_T *argvars;
16762 typval_T *rettv;
16764 int binary = FALSE;
16765 char_u *fname;
16766 FILE *fd;
16767 listitem_T *li;
16768 char_u *s;
16769 int ret = 0;
16770 int c;
16772 if (check_restricted() || check_secure())
16773 return;
16775 if (argvars[0].v_type != VAR_LIST)
16777 EMSG2(_(e_listarg), "writefile()");
16778 return;
16780 if (argvars[0].vval.v_list == NULL)
16781 return;
16783 if (argvars[2].v_type != VAR_UNKNOWN
16784 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
16785 binary = TRUE;
16787 /* Always open the file in binary mode, library functions have a mind of
16788 * their own about CR-LF conversion. */
16789 fname = get_tv_string(&argvars[1]);
16790 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
16792 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
16793 ret = -1;
16795 else
16797 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
16798 li = li->li_next)
16800 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
16802 if (*s == '\n')
16803 c = putc(NUL, fd);
16804 else
16805 c = putc(*s, fd);
16806 if (c == EOF)
16808 ret = -1;
16809 break;
16812 if (!binary || li->li_next != NULL)
16813 if (putc('\n', fd) == EOF)
16815 ret = -1;
16816 break;
16818 if (ret < 0)
16820 EMSG(_(e_write));
16821 break;
16824 fclose(fd);
16827 rettv->vval.v_number = ret;
16831 * Translate a String variable into a position.
16832 * Returns NULL when there is an error.
16834 static pos_T *
16835 var2fpos(varp, dollar_lnum, fnum)
16836 typval_T *varp;
16837 int dollar_lnum; /* TRUE when $ is last line */
16838 int *fnum; /* set to fnum for '0, 'A, etc. */
16840 char_u *name;
16841 static pos_T pos;
16842 pos_T *pp;
16844 /* Argument can be [lnum, col, coladd]. */
16845 if (varp->v_type == VAR_LIST)
16847 list_T *l;
16848 int len;
16849 int error = FALSE;
16850 listitem_T *li;
16852 l = varp->vval.v_list;
16853 if (l == NULL)
16854 return NULL;
16856 /* Get the line number */
16857 pos.lnum = list_find_nr(l, 0L, &error);
16858 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
16859 return NULL; /* invalid line number */
16861 /* Get the column number */
16862 pos.col = list_find_nr(l, 1L, &error);
16863 if (error)
16864 return NULL;
16865 len = (long)STRLEN(ml_get(pos.lnum));
16867 /* We accept "$" for the column number: last column. */
16868 li = list_find(l, 1L);
16869 if (li != NULL && li->li_tv.v_type == VAR_STRING
16870 && li->li_tv.vval.v_string != NULL
16871 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
16872 pos.col = len + 1;
16874 /* Accept a position up to the NUL after the line. */
16875 if (pos.col == 0 || (int)pos.col > len + 1)
16876 return NULL; /* invalid column number */
16877 --pos.col;
16879 #ifdef FEAT_VIRTUALEDIT
16880 /* Get the virtual offset. Defaults to zero. */
16881 pos.coladd = list_find_nr(l, 2L, &error);
16882 if (error)
16883 pos.coladd = 0;
16884 #endif
16886 return &pos;
16889 name = get_tv_string_chk(varp);
16890 if (name == NULL)
16891 return NULL;
16892 if (name[0] == '.') /* cursor */
16893 return &curwin->w_cursor;
16894 if (name[0] == '\'') /* mark */
16896 pp = getmark_fnum(name[1], FALSE, fnum);
16897 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
16898 return NULL;
16899 return pp;
16902 #ifdef FEAT_VIRTUALEDIT
16903 pos.coladd = 0;
16904 #endif
16906 if (name[0] == 'w' && dollar_lnum)
16908 pos.col = 0;
16909 if (name[1] == '0') /* "w0": first visible line */
16911 update_topline();
16912 pos.lnum = curwin->w_topline;
16913 return &pos;
16915 else if (name[1] == '$') /* "w$": last visible line */
16917 validate_botline();
16918 pos.lnum = curwin->w_botline - 1;
16919 return &pos;
16922 else if (name[0] == '$') /* last column or line */
16924 if (dollar_lnum)
16926 pos.lnum = curbuf->b_ml.ml_line_count;
16927 pos.col = 0;
16929 else
16931 pos.lnum = curwin->w_cursor.lnum;
16932 pos.col = (colnr_T)STRLEN(ml_get_curline());
16934 return &pos;
16936 return NULL;
16940 * Convert list in "arg" into a position and optional file number.
16941 * When "fnump" is NULL there is no file number, only 3 items.
16942 * Note that the column is passed on as-is, the caller may want to decrement
16943 * it to use 1 for the first column.
16944 * Return FAIL when conversion is not possible, doesn't check the position for
16945 * validity.
16947 static int
16948 list2fpos(arg, posp, fnump)
16949 typval_T *arg;
16950 pos_T *posp;
16951 int *fnump;
16953 list_T *l = arg->vval.v_list;
16954 long i = 0;
16955 long n;
16957 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
16958 * when "fnump" isn't NULL and "coladd" is optional. */
16959 if (arg->v_type != VAR_LIST
16960 || l == NULL
16961 || l->lv_len < (fnump == NULL ? 2 : 3)
16962 || l->lv_len > (fnump == NULL ? 3 : 4))
16963 return FAIL;
16965 if (fnump != NULL)
16967 n = list_find_nr(l, i++, NULL); /* fnum */
16968 if (n < 0)
16969 return FAIL;
16970 if (n == 0)
16971 n = curbuf->b_fnum; /* current buffer */
16972 *fnump = n;
16975 n = list_find_nr(l, i++, NULL); /* lnum */
16976 if (n < 0)
16977 return FAIL;
16978 posp->lnum = n;
16980 n = list_find_nr(l, i++, NULL); /* col */
16981 if (n < 0)
16982 return FAIL;
16983 posp->col = n;
16985 #ifdef FEAT_VIRTUALEDIT
16986 n = list_find_nr(l, i, NULL);
16987 if (n < 0)
16988 posp->coladd = 0;
16989 else
16990 posp->coladd = n;
16991 #endif
16993 return OK;
16997 * Get the length of an environment variable name.
16998 * Advance "arg" to the first character after the name.
16999 * Return 0 for error.
17001 static int
17002 get_env_len(arg)
17003 char_u **arg;
17005 char_u *p;
17006 int len;
17008 for (p = *arg; vim_isIDc(*p); ++p)
17010 if (p == *arg) /* no name found */
17011 return 0;
17013 len = (int)(p - *arg);
17014 *arg = p;
17015 return len;
17019 * Get the length of the name of a function or internal variable.
17020 * "arg" is advanced to the first non-white character after the name.
17021 * Return 0 if something is wrong.
17023 static int
17024 get_id_len(arg)
17025 char_u **arg;
17027 char_u *p;
17028 int len;
17030 /* Find the end of the name. */
17031 for (p = *arg; eval_isnamec(*p); ++p)
17033 if (p == *arg) /* no name found */
17034 return 0;
17036 len = (int)(p - *arg);
17037 *arg = skipwhite(p);
17039 return len;
17043 * Get the length of the name of a variable or function.
17044 * Only the name is recognized, does not handle ".key" or "[idx]".
17045 * "arg" is advanced to the first non-white character after the name.
17046 * Return -1 if curly braces expansion failed.
17047 * Return 0 if something else is wrong.
17048 * If the name contains 'magic' {}'s, expand them and return the
17049 * expanded name in an allocated string via 'alias' - caller must free.
17051 static int
17052 get_name_len(arg, alias, evaluate, verbose)
17053 char_u **arg;
17054 char_u **alias;
17055 int evaluate;
17056 int verbose;
17058 int len;
17059 char_u *p;
17060 char_u *expr_start;
17061 char_u *expr_end;
17063 *alias = NULL; /* default to no alias */
17065 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
17066 && (*arg)[2] == (int)KE_SNR)
17068 /* hard coded <SNR>, already translated */
17069 *arg += 3;
17070 return get_id_len(arg) + 3;
17072 len = eval_fname_script(*arg);
17073 if (len > 0)
17075 /* literal "<SID>", "s:" or "<SNR>" */
17076 *arg += len;
17080 * Find the end of the name; check for {} construction.
17082 p = find_name_end(*arg, &expr_start, &expr_end,
17083 len > 0 ? 0 : FNE_CHECK_START);
17084 if (expr_start != NULL)
17086 char_u *temp_string;
17088 if (!evaluate)
17090 len += (int)(p - *arg);
17091 *arg = skipwhite(p);
17092 return len;
17096 * Include any <SID> etc in the expanded string:
17097 * Thus the -len here.
17099 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
17100 if (temp_string == NULL)
17101 return -1;
17102 *alias = temp_string;
17103 *arg = skipwhite(p);
17104 return (int)STRLEN(temp_string);
17107 len += get_id_len(arg);
17108 if (len == 0 && verbose)
17109 EMSG2(_(e_invexpr2), *arg);
17111 return len;
17115 * Find the end of a variable or function name, taking care of magic braces.
17116 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
17117 * start and end of the first magic braces item.
17118 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
17119 * Return a pointer to just after the name. Equal to "arg" if there is no
17120 * valid name.
17122 static char_u *
17123 find_name_end(arg, expr_start, expr_end, flags)
17124 char_u *arg;
17125 char_u **expr_start;
17126 char_u **expr_end;
17127 int flags;
17129 int mb_nest = 0;
17130 int br_nest = 0;
17131 char_u *p;
17133 if (expr_start != NULL)
17135 *expr_start = NULL;
17136 *expr_end = NULL;
17139 /* Quick check for valid starting character. */
17140 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
17141 return arg;
17143 for (p = arg; *p != NUL
17144 && (eval_isnamec(*p)
17145 || *p == '{'
17146 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
17147 || mb_nest != 0
17148 || br_nest != 0); mb_ptr_adv(p))
17150 if (*p == '\'')
17152 /* skip over 'string' to avoid counting [ and ] inside it. */
17153 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
17155 if (*p == NUL)
17156 break;
17158 else if (*p == '"')
17160 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
17161 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
17162 if (*p == '\\' && p[1] != NUL)
17163 ++p;
17164 if (*p == NUL)
17165 break;
17168 if (mb_nest == 0)
17170 if (*p == '[')
17171 ++br_nest;
17172 else if (*p == ']')
17173 --br_nest;
17176 if (br_nest == 0)
17178 if (*p == '{')
17180 mb_nest++;
17181 if (expr_start != NULL && *expr_start == NULL)
17182 *expr_start = p;
17184 else if (*p == '}')
17186 mb_nest--;
17187 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
17188 *expr_end = p;
17193 return p;
17197 * Expands out the 'magic' {}'s in a variable/function name.
17198 * Note that this can call itself recursively, to deal with
17199 * constructs like foo{bar}{baz}{bam}
17200 * The four pointer arguments point to "foo{expre}ss{ion}bar"
17201 * "in_start" ^
17202 * "expr_start" ^
17203 * "expr_end" ^
17204 * "in_end" ^
17206 * Returns a new allocated string, which the caller must free.
17207 * Returns NULL for failure.
17209 static char_u *
17210 make_expanded_name(in_start, expr_start, expr_end, in_end)
17211 char_u *in_start;
17212 char_u *expr_start;
17213 char_u *expr_end;
17214 char_u *in_end;
17216 char_u c1;
17217 char_u *retval = NULL;
17218 char_u *temp_result;
17219 char_u *nextcmd = NULL;
17221 if (expr_end == NULL || in_end == NULL)
17222 return NULL;
17223 *expr_start = NUL;
17224 *expr_end = NUL;
17225 c1 = *in_end;
17226 *in_end = NUL;
17228 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
17229 if (temp_result != NULL && nextcmd == NULL)
17231 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
17232 + (in_end - expr_end) + 1));
17233 if (retval != NULL)
17235 STRCPY(retval, in_start);
17236 STRCAT(retval, temp_result);
17237 STRCAT(retval, expr_end + 1);
17240 vim_free(temp_result);
17242 *in_end = c1; /* put char back for error messages */
17243 *expr_start = '{';
17244 *expr_end = '}';
17246 if (retval != NULL)
17248 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
17249 if (expr_start != NULL)
17251 /* Further expansion! */
17252 temp_result = make_expanded_name(retval, expr_start,
17253 expr_end, temp_result);
17254 vim_free(retval);
17255 retval = temp_result;
17259 return retval;
17263 * Return TRUE if character "c" can be used in a variable or function name.
17264 * Does not include '{' or '}' for magic braces.
17266 static int
17267 eval_isnamec(c)
17268 int c;
17270 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
17274 * Return TRUE if character "c" can be used as the first character in a
17275 * variable or function name (excluding '{' and '}').
17277 static int
17278 eval_isnamec1(c)
17279 int c;
17281 return (ASCII_ISALPHA(c) || c == '_');
17285 * Set number v: variable to "val".
17287 void
17288 set_vim_var_nr(idx, val)
17289 int idx;
17290 long val;
17292 vimvars[idx].vv_nr = val;
17296 * Get number v: variable value.
17298 long
17299 get_vim_var_nr(idx)
17300 int idx;
17302 return vimvars[idx].vv_nr;
17305 #if defined(FEAT_AUTOCMD) || defined(PROTO)
17307 * Get string v: variable value. Uses a static buffer, can only be used once.
17309 char_u *
17310 get_vim_var_str(idx)
17311 int idx;
17313 return get_tv_string(&vimvars[idx].vv_tv);
17315 #endif
17318 * Set v:count, v:count1 and v:prevcount.
17320 void
17321 set_vcount(count, count1)
17322 long count;
17323 long count1;
17325 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
17326 vimvars[VV_COUNT].vv_nr = count;
17327 vimvars[VV_COUNT1].vv_nr = count1;
17331 * Set string v: variable to a copy of "val".
17333 void
17334 set_vim_var_string(idx, val, len)
17335 int idx;
17336 char_u *val;
17337 int len; /* length of "val" to use or -1 (whole string) */
17339 /* Need to do this (at least) once, since we can't initialize a union.
17340 * Will always be invoked when "v:progname" is set. */
17341 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
17343 vim_free(vimvars[idx].vv_str);
17344 if (val == NULL)
17345 vimvars[idx].vv_str = NULL;
17346 else if (len == -1)
17347 vimvars[idx].vv_str = vim_strsave(val);
17348 else
17349 vimvars[idx].vv_str = vim_strnsave(val, len);
17353 * Set v:register if needed.
17355 void
17356 set_reg_var(c)
17357 int c;
17359 char_u regname;
17361 if (c == 0 || c == ' ')
17362 regname = '"';
17363 else
17364 regname = c;
17365 /* Avoid free/alloc when the value is already right. */
17366 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
17367 set_vim_var_string(VV_REG, &regname, 1);
17371 * Get or set v:exception. If "oldval" == NULL, return the current value.
17372 * Otherwise, restore the value to "oldval" and return NULL.
17373 * Must always be called in pairs to save and restore v:exception! Does not
17374 * take care of memory allocations.
17376 char_u *
17377 v_exception(oldval)
17378 char_u *oldval;
17380 if (oldval == NULL)
17381 return vimvars[VV_EXCEPTION].vv_str;
17383 vimvars[VV_EXCEPTION].vv_str = oldval;
17384 return NULL;
17388 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
17389 * Otherwise, restore the value to "oldval" and return NULL.
17390 * Must always be called in pairs to save and restore v:throwpoint! Does not
17391 * take care of memory allocations.
17393 char_u *
17394 v_throwpoint(oldval)
17395 char_u *oldval;
17397 if (oldval == NULL)
17398 return vimvars[VV_THROWPOINT].vv_str;
17400 vimvars[VV_THROWPOINT].vv_str = oldval;
17401 return NULL;
17404 #if defined(FEAT_AUTOCMD) || defined(PROTO)
17406 * Set v:cmdarg.
17407 * If "eap" != NULL, use "eap" to generate the value and return the old value.
17408 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
17409 * Must always be called in pairs!
17411 char_u *
17412 set_cmdarg(eap, oldarg)
17413 exarg_T *eap;
17414 char_u *oldarg;
17416 char_u *oldval;
17417 char_u *newval;
17418 unsigned len;
17420 oldval = vimvars[VV_CMDARG].vv_str;
17421 if (eap == NULL)
17423 vim_free(oldval);
17424 vimvars[VV_CMDARG].vv_str = oldarg;
17425 return NULL;
17428 if (eap->force_bin == FORCE_BIN)
17429 len = 6;
17430 else if (eap->force_bin == FORCE_NOBIN)
17431 len = 8;
17432 else
17433 len = 0;
17435 if (eap->read_edit)
17436 len += 7;
17438 if (eap->force_ff != 0)
17439 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
17440 # ifdef FEAT_MBYTE
17441 if (eap->force_enc != 0)
17442 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
17443 if (eap->bad_char != 0)
17444 len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
17445 # endif
17447 newval = alloc(len + 1);
17448 if (newval == NULL)
17449 return NULL;
17451 if (eap->force_bin == FORCE_BIN)
17452 sprintf((char *)newval, " ++bin");
17453 else if (eap->force_bin == FORCE_NOBIN)
17454 sprintf((char *)newval, " ++nobin");
17455 else
17456 *newval = NUL;
17458 if (eap->read_edit)
17459 STRCAT(newval, " ++edit");
17461 if (eap->force_ff != 0)
17462 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
17463 eap->cmd + eap->force_ff);
17464 # ifdef FEAT_MBYTE
17465 if (eap->force_enc != 0)
17466 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
17467 eap->cmd + eap->force_enc);
17468 if (eap->bad_char != 0)
17469 sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
17470 eap->cmd + eap->bad_char);
17471 # endif
17472 vimvars[VV_CMDARG].vv_str = newval;
17473 return oldval;
17475 #endif
17478 * Get the value of internal variable "name".
17479 * Return OK or FAIL.
17481 static int
17482 get_var_tv(name, len, rettv, verbose)
17483 char_u *name;
17484 int len; /* length of "name" */
17485 typval_T *rettv; /* NULL when only checking existence */
17486 int verbose; /* may give error message */
17488 int ret = OK;
17489 typval_T *tv = NULL;
17490 typval_T atv;
17491 dictitem_T *v;
17492 int cc;
17494 /* truncate the name, so that we can use strcmp() */
17495 cc = name[len];
17496 name[len] = NUL;
17499 * Check for "b:changedtick".
17501 if (STRCMP(name, "b:changedtick") == 0)
17503 atv.v_type = VAR_NUMBER;
17504 atv.vval.v_number = curbuf->b_changedtick;
17505 tv = &atv;
17509 * Check for user-defined variables.
17511 else
17513 v = find_var(name, NULL);
17514 if (v != NULL)
17515 tv = &v->di_tv;
17518 if (tv == NULL)
17520 if (rettv != NULL && verbose)
17521 EMSG2(_(e_undefvar), name);
17522 ret = FAIL;
17524 else if (rettv != NULL)
17525 copy_tv(tv, rettv);
17527 name[len] = cc;
17529 return ret;
17533 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
17534 * Also handle function call with Funcref variable: func(expr)
17535 * Can all be combined: dict.func(expr)[idx]['func'](expr)
17537 static int
17538 handle_subscript(arg, rettv, evaluate, verbose)
17539 char_u **arg;
17540 typval_T *rettv;
17541 int evaluate; /* do more than finding the end */
17542 int verbose; /* give error messages */
17544 int ret = OK;
17545 dict_T *selfdict = NULL;
17546 char_u *s;
17547 int len;
17548 typval_T functv;
17550 while (ret == OK
17551 && (**arg == '['
17552 || (**arg == '.' && rettv->v_type == VAR_DICT)
17553 || (**arg == '(' && rettv->v_type == VAR_FUNC))
17554 && !vim_iswhite(*(*arg - 1)))
17556 if (**arg == '(')
17558 /* need to copy the funcref so that we can clear rettv */
17559 functv = *rettv;
17560 rettv->v_type = VAR_UNKNOWN;
17562 /* Invoke the function. Recursive! */
17563 s = functv.vval.v_string;
17564 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
17565 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
17566 &len, evaluate, selfdict);
17568 /* Clear the funcref afterwards, so that deleting it while
17569 * evaluating the arguments is possible (see test55). */
17570 clear_tv(&functv);
17572 /* Stop the expression evaluation when immediately aborting on
17573 * error, or when an interrupt occurred or an exception was thrown
17574 * but not caught. */
17575 if (aborting())
17577 if (ret == OK)
17578 clear_tv(rettv);
17579 ret = FAIL;
17581 dict_unref(selfdict);
17582 selfdict = NULL;
17584 else /* **arg == '[' || **arg == '.' */
17586 dict_unref(selfdict);
17587 if (rettv->v_type == VAR_DICT)
17589 selfdict = rettv->vval.v_dict;
17590 if (selfdict != NULL)
17591 ++selfdict->dv_refcount;
17593 else
17594 selfdict = NULL;
17595 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
17597 clear_tv(rettv);
17598 ret = FAIL;
17602 dict_unref(selfdict);
17603 return ret;
17607 * Allocate memory for a variable type-value, and make it emtpy (0 or NULL
17608 * value).
17610 static typval_T *
17611 alloc_tv()
17613 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
17617 * Allocate memory for a variable type-value, and assign a string to it.
17618 * The string "s" must have been allocated, it is consumed.
17619 * Return NULL for out of memory, the variable otherwise.
17621 static typval_T *
17622 alloc_string_tv(s)
17623 char_u *s;
17625 typval_T *rettv;
17627 rettv = alloc_tv();
17628 if (rettv != NULL)
17630 rettv->v_type = VAR_STRING;
17631 rettv->vval.v_string = s;
17633 else
17634 vim_free(s);
17635 return rettv;
17639 * Free the memory for a variable type-value.
17641 void
17642 free_tv(varp)
17643 typval_T *varp;
17645 if (varp != NULL)
17647 switch (varp->v_type)
17649 case VAR_FUNC:
17650 func_unref(varp->vval.v_string);
17651 /*FALLTHROUGH*/
17652 case VAR_STRING:
17653 vim_free(varp->vval.v_string);
17654 break;
17655 case VAR_LIST:
17656 list_unref(varp->vval.v_list);
17657 break;
17658 case VAR_DICT:
17659 dict_unref(varp->vval.v_dict);
17660 break;
17661 case VAR_NUMBER:
17662 case VAR_UNKNOWN:
17663 break;
17664 default:
17665 EMSG2(_(e_intern2), "free_tv()");
17666 break;
17668 vim_free(varp);
17673 * Free the memory for a variable value and set the value to NULL or 0.
17675 void
17676 clear_tv(varp)
17677 typval_T *varp;
17679 if (varp != NULL)
17681 switch (varp->v_type)
17683 case VAR_FUNC:
17684 func_unref(varp->vval.v_string);
17685 /*FALLTHROUGH*/
17686 case VAR_STRING:
17687 vim_free(varp->vval.v_string);
17688 varp->vval.v_string = NULL;
17689 break;
17690 case VAR_LIST:
17691 list_unref(varp->vval.v_list);
17692 varp->vval.v_list = NULL;
17693 break;
17694 case VAR_DICT:
17695 dict_unref(varp->vval.v_dict);
17696 varp->vval.v_dict = NULL;
17697 break;
17698 case VAR_NUMBER:
17699 varp->vval.v_number = 0;
17700 break;
17701 case VAR_UNKNOWN:
17702 break;
17703 default:
17704 EMSG2(_(e_intern2), "clear_tv()");
17706 varp->v_lock = 0;
17711 * Set the value of a variable to NULL without freeing items.
17713 static void
17714 init_tv(varp)
17715 typval_T *varp;
17717 if (varp != NULL)
17718 vim_memset(varp, 0, sizeof(typval_T));
17722 * Get the number value of a variable.
17723 * If it is a String variable, uses vim_str2nr().
17724 * For incompatible types, return 0.
17725 * get_tv_number_chk() is similar to get_tv_number(), but informs the
17726 * caller of incompatible types: it sets *denote to TRUE if "denote"
17727 * is not NULL or returns -1 otherwise.
17729 static long
17730 get_tv_number(varp)
17731 typval_T *varp;
17733 int error = FALSE;
17735 return get_tv_number_chk(varp, &error); /* return 0L on error */
17738 long
17739 get_tv_number_chk(varp, denote)
17740 typval_T *varp;
17741 int *denote;
17743 long n = 0L;
17745 switch (varp->v_type)
17747 case VAR_NUMBER:
17748 return (long)(varp->vval.v_number);
17749 case VAR_FUNC:
17750 EMSG(_("E703: Using a Funcref as a number"));
17751 break;
17752 case VAR_STRING:
17753 if (varp->vval.v_string != NULL)
17754 vim_str2nr(varp->vval.v_string, NULL, NULL,
17755 TRUE, TRUE, &n, NULL);
17756 return n;
17757 case VAR_LIST:
17758 EMSG(_("E745: Using a List as a number"));
17759 break;
17760 case VAR_DICT:
17761 EMSG(_("E728: Using a Dictionary as a number"));
17762 break;
17763 default:
17764 EMSG2(_(e_intern2), "get_tv_number()");
17765 break;
17767 if (denote == NULL) /* useful for values that must be unsigned */
17768 n = -1;
17769 else
17770 *denote = TRUE;
17771 return n;
17775 * Get the lnum from the first argument.
17776 * Also accepts ".", "$", etc., but that only works for the current buffer.
17777 * Returns -1 on error.
17779 static linenr_T
17780 get_tv_lnum(argvars)
17781 typval_T *argvars;
17783 typval_T rettv;
17784 linenr_T lnum;
17786 lnum = get_tv_number_chk(&argvars[0], NULL);
17787 if (lnum == 0) /* no valid number, try using line() */
17789 rettv.v_type = VAR_NUMBER;
17790 f_line(argvars, &rettv);
17791 lnum = rettv.vval.v_number;
17792 clear_tv(&rettv);
17794 return lnum;
17798 * Get the lnum from the first argument.
17799 * Also accepts "$", then "buf" is used.
17800 * Returns 0 on error.
17802 static linenr_T
17803 get_tv_lnum_buf(argvars, buf)
17804 typval_T *argvars;
17805 buf_T *buf;
17807 if (argvars[0].v_type == VAR_STRING
17808 && argvars[0].vval.v_string != NULL
17809 && argvars[0].vval.v_string[0] == '$'
17810 && buf != NULL)
17811 return buf->b_ml.ml_line_count;
17812 return get_tv_number_chk(&argvars[0], NULL);
17816 * Get the string value of a variable.
17817 * If it is a Number variable, the number is converted into a string.
17818 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
17819 * get_tv_string_buf() uses a given buffer.
17820 * If the String variable has never been set, return an empty string.
17821 * Never returns NULL;
17822 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
17823 * NULL on error.
17825 static char_u *
17826 get_tv_string(varp)
17827 typval_T *varp;
17829 static char_u mybuf[NUMBUFLEN];
17831 return get_tv_string_buf(varp, mybuf);
17834 static char_u *
17835 get_tv_string_buf(varp, buf)
17836 typval_T *varp;
17837 char_u *buf;
17839 char_u *res = get_tv_string_buf_chk(varp, buf);
17841 return res != NULL ? res : (char_u *)"";
17844 char_u *
17845 get_tv_string_chk(varp)
17846 typval_T *varp;
17848 static char_u mybuf[NUMBUFLEN];
17850 return get_tv_string_buf_chk(varp, mybuf);
17853 static char_u *
17854 get_tv_string_buf_chk(varp, buf)
17855 typval_T *varp;
17856 char_u *buf;
17858 switch (varp->v_type)
17860 case VAR_NUMBER:
17861 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
17862 return buf;
17863 case VAR_FUNC:
17864 EMSG(_("E729: using Funcref as a String"));
17865 break;
17866 case VAR_LIST:
17867 EMSG(_("E730: using List as a String"));
17868 break;
17869 case VAR_DICT:
17870 EMSG(_("E731: using Dictionary as a String"));
17871 break;
17872 case VAR_STRING:
17873 if (varp->vval.v_string != NULL)
17874 return varp->vval.v_string;
17875 return (char_u *)"";
17876 default:
17877 EMSG2(_(e_intern2), "get_tv_string_buf()");
17878 break;
17880 return NULL;
17884 * Find variable "name" in the list of variables.
17885 * Return a pointer to it if found, NULL if not found.
17886 * Careful: "a:0" variables don't have a name.
17887 * When "htp" is not NULL we are writing to the variable, set "htp" to the
17888 * hashtab_T used.
17890 static dictitem_T *
17891 find_var(name, htp)
17892 char_u *name;
17893 hashtab_T **htp;
17895 char_u *varname;
17896 hashtab_T *ht;
17898 ht = find_var_ht(name, &varname);
17899 if (htp != NULL)
17900 *htp = ht;
17901 if (ht == NULL)
17902 return NULL;
17903 return find_var_in_ht(ht, varname, htp != NULL);
17907 * Find variable "varname" in hashtab "ht".
17908 * Returns NULL if not found.
17910 static dictitem_T *
17911 find_var_in_ht(ht, varname, writing)
17912 hashtab_T *ht;
17913 char_u *varname;
17914 int writing;
17916 hashitem_T *hi;
17918 if (*varname == NUL)
17920 /* Must be something like "s:", otherwise "ht" would be NULL. */
17921 switch (varname[-2])
17923 case 's': return &SCRIPT_SV(current_SID).sv_var;
17924 case 'g': return &globvars_var;
17925 case 'v': return &vimvars_var;
17926 case 'b': return &curbuf->b_bufvar;
17927 case 'w': return &curwin->w_winvar;
17928 #ifdef FEAT_WINDOWS
17929 case 't': return &curtab->tp_winvar;
17930 #endif
17931 case 'l': return current_funccal == NULL
17932 ? NULL : &current_funccal->l_vars_var;
17933 case 'a': return current_funccal == NULL
17934 ? NULL : &current_funccal->l_avars_var;
17936 return NULL;
17939 hi = hash_find(ht, varname);
17940 if (HASHITEM_EMPTY(hi))
17942 /* For global variables we may try auto-loading the script. If it
17943 * worked find the variable again. Don't auto-load a script if it was
17944 * loaded already, otherwise it would be loaded every time when
17945 * checking if a function name is a Funcref variable. */
17946 if (ht == &globvarht && !writing
17947 && script_autoload(varname, FALSE) && !aborting())
17948 hi = hash_find(ht, varname);
17949 if (HASHITEM_EMPTY(hi))
17950 return NULL;
17952 return HI2DI(hi);
17956 * Find the hashtab used for a variable name.
17957 * Set "varname" to the start of name without ':'.
17959 static hashtab_T *
17960 find_var_ht(name, varname)
17961 char_u *name;
17962 char_u **varname;
17964 hashitem_T *hi;
17966 if (name[1] != ':')
17968 /* The name must not start with a colon or #. */
17969 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
17970 return NULL;
17971 *varname = name;
17973 /* "version" is "v:version" in all scopes */
17974 hi = hash_find(&compat_hashtab, name);
17975 if (!HASHITEM_EMPTY(hi))
17976 return &compat_hashtab;
17978 if (current_funccal == NULL)
17979 return &globvarht; /* global variable */
17980 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
17982 *varname = name + 2;
17983 if (*name == 'g') /* global variable */
17984 return &globvarht;
17985 /* There must be no ':' or '#' in the rest of the name, unless g: is used
17987 if (vim_strchr(name + 2, ':') != NULL
17988 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
17989 return NULL;
17990 if (*name == 'b') /* buffer variable */
17991 return &curbuf->b_vars.dv_hashtab;
17992 if (*name == 'w') /* window variable */
17993 return &curwin->w_vars.dv_hashtab;
17994 #ifdef FEAT_WINDOWS
17995 if (*name == 't') /* tab page variable */
17996 return &curtab->tp_vars.dv_hashtab;
17997 #endif
17998 if (*name == 'v') /* v: variable */
17999 return &vimvarht;
18000 if (*name == 'a' && current_funccal != NULL) /* function argument */
18001 return &current_funccal->l_avars.dv_hashtab;
18002 if (*name == 'l' && current_funccal != NULL) /* local function variable */
18003 return &current_funccal->l_vars.dv_hashtab;
18004 if (*name == 's' /* script variable */
18005 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
18006 return &SCRIPT_VARS(current_SID);
18007 return NULL;
18011 * Get the string value of a (global/local) variable.
18012 * Returns NULL when it doesn't exist.
18014 char_u *
18015 get_var_value(name)
18016 char_u *name;
18018 dictitem_T *v;
18020 v = find_var(name, NULL);
18021 if (v == NULL)
18022 return NULL;
18023 return get_tv_string(&v->di_tv);
18027 * Allocate a new hashtab for a sourced script. It will be used while
18028 * sourcing this script and when executing functions defined in the script.
18030 void
18031 new_script_vars(id)
18032 scid_T id;
18034 int i;
18035 hashtab_T *ht;
18036 scriptvar_T *sv;
18038 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
18040 /* Re-allocating ga_data means that an ht_array pointing to
18041 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
18042 * at its init value. Also reset "v_dict", it's always the same. */
18043 for (i = 1; i <= ga_scripts.ga_len; ++i)
18045 ht = &SCRIPT_VARS(i);
18046 if (ht->ht_mask == HT_INIT_SIZE - 1)
18047 ht->ht_array = ht->ht_smallarray;
18048 sv = &SCRIPT_SV(i);
18049 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
18052 while (ga_scripts.ga_len < id)
18054 sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
18055 init_var_dict(&sv->sv_dict, &sv->sv_var);
18056 ++ga_scripts.ga_len;
18062 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
18063 * point to it.
18065 void
18066 init_var_dict(dict, dict_var)
18067 dict_T *dict;
18068 dictitem_T *dict_var;
18070 hash_init(&dict->dv_hashtab);
18071 dict->dv_refcount = 99999;
18072 dict_var->di_tv.vval.v_dict = dict;
18073 dict_var->di_tv.v_type = VAR_DICT;
18074 dict_var->di_tv.v_lock = VAR_FIXED;
18075 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
18076 dict_var->di_key[0] = NUL;
18080 * Clean up a list of internal variables.
18081 * Frees all allocated variables and the value they contain.
18082 * Clears hashtab "ht", does not free it.
18084 void
18085 vars_clear(ht)
18086 hashtab_T *ht;
18088 vars_clear_ext(ht, TRUE);
18092 * Like vars_clear(), but only free the value if "free_val" is TRUE.
18094 static void
18095 vars_clear_ext(ht, free_val)
18096 hashtab_T *ht;
18097 int free_val;
18099 int todo;
18100 hashitem_T *hi;
18101 dictitem_T *v;
18103 hash_lock(ht);
18104 todo = (int)ht->ht_used;
18105 for (hi = ht->ht_array; todo > 0; ++hi)
18107 if (!HASHITEM_EMPTY(hi))
18109 --todo;
18111 /* Free the variable. Don't remove it from the hashtab,
18112 * ht_array might change then. hash_clear() takes care of it
18113 * later. */
18114 v = HI2DI(hi);
18115 if (free_val)
18116 clear_tv(&v->di_tv);
18117 if ((v->di_flags & DI_FLAGS_FIX) == 0)
18118 vim_free(v);
18121 hash_clear(ht);
18122 ht->ht_used = 0;
18126 * Delete a variable from hashtab "ht" at item "hi".
18127 * Clear the variable value and free the dictitem.
18129 static void
18130 delete_var(ht, hi)
18131 hashtab_T *ht;
18132 hashitem_T *hi;
18134 dictitem_T *di = HI2DI(hi);
18136 hash_remove(ht, hi);
18137 clear_tv(&di->di_tv);
18138 vim_free(di);
18142 * List the value of one internal variable.
18144 static void
18145 list_one_var(v, prefix, first)
18146 dictitem_T *v;
18147 char_u *prefix;
18148 int *first;
18150 char_u *tofree;
18151 char_u *s;
18152 char_u numbuf[NUMBUFLEN];
18154 s = echo_string(&v->di_tv, &tofree, numbuf, ++current_copyID);
18155 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
18156 s == NULL ? (char_u *)"" : s, first);
18157 vim_free(tofree);
18160 static void
18161 list_one_var_a(prefix, name, type, string, first)
18162 char_u *prefix;
18163 char_u *name;
18164 int type;
18165 char_u *string;
18166 int *first; /* when TRUE clear rest of screen and set to FALSE */
18168 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
18169 msg_start();
18170 msg_puts(prefix);
18171 if (name != NULL) /* "a:" vars don't have a name stored */
18172 msg_puts(name);
18173 msg_putchar(' ');
18174 msg_advance(22);
18175 if (type == VAR_NUMBER)
18176 msg_putchar('#');
18177 else if (type == VAR_FUNC)
18178 msg_putchar('*');
18179 else if (type == VAR_LIST)
18181 msg_putchar('[');
18182 if (*string == '[')
18183 ++string;
18185 else if (type == VAR_DICT)
18187 msg_putchar('{');
18188 if (*string == '{')
18189 ++string;
18191 else
18192 msg_putchar(' ');
18194 msg_outtrans(string);
18196 if (type == VAR_FUNC)
18197 msg_puts((char_u *)"()");
18198 if (*first)
18200 msg_clr_eos();
18201 *first = FALSE;
18206 * Set variable "name" to value in "tv".
18207 * If the variable already exists, the value is updated.
18208 * Otherwise the variable is created.
18210 static void
18211 set_var(name, tv, copy)
18212 char_u *name;
18213 typval_T *tv;
18214 int copy; /* make copy of value in "tv" */
18216 dictitem_T *v;
18217 char_u *varname;
18218 hashtab_T *ht;
18219 char_u *p;
18221 if (tv->v_type == VAR_FUNC)
18223 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
18224 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
18225 ? name[2] : name[0]))
18227 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
18228 return;
18230 if (function_exists(name))
18232 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
18233 name);
18234 return;
18238 ht = find_var_ht(name, &varname);
18239 if (ht == NULL || *varname == NUL)
18241 EMSG2(_(e_illvar), name);
18242 return;
18245 v = find_var_in_ht(ht, varname, TRUE);
18246 if (v != NULL)
18248 /* existing variable, need to clear the value */
18249 if (var_check_ro(v->di_flags, name)
18250 || tv_check_lock(v->di_tv.v_lock, name))
18251 return;
18252 if (v->di_tv.v_type != tv->v_type
18253 && !((v->di_tv.v_type == VAR_STRING
18254 || v->di_tv.v_type == VAR_NUMBER)
18255 && (tv->v_type == VAR_STRING
18256 || tv->v_type == VAR_NUMBER)))
18258 EMSG2(_("E706: Variable type mismatch for: %s"), name);
18259 return;
18263 * Handle setting internal v: variables separately: we don't change
18264 * the type.
18266 if (ht == &vimvarht)
18268 if (v->di_tv.v_type == VAR_STRING)
18270 vim_free(v->di_tv.vval.v_string);
18271 if (copy || tv->v_type != VAR_STRING)
18272 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
18273 else
18275 /* Take over the string to avoid an extra alloc/free. */
18276 v->di_tv.vval.v_string = tv->vval.v_string;
18277 tv->vval.v_string = NULL;
18280 else if (v->di_tv.v_type != VAR_NUMBER)
18281 EMSG2(_(e_intern2), "set_var()");
18282 else
18283 v->di_tv.vval.v_number = get_tv_number(tv);
18284 return;
18287 clear_tv(&v->di_tv);
18289 else /* add a new variable */
18291 /* Can't add "v:" variable. */
18292 if (ht == &vimvarht)
18294 EMSG2(_(e_illvar), name);
18295 return;
18298 /* Make sure the variable name is valid. */
18299 for (p = varname; *p != NUL; ++p)
18300 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
18301 && *p != AUTOLOAD_CHAR)
18303 EMSG2(_(e_illvar), varname);
18304 return;
18307 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
18308 + STRLEN(varname)));
18309 if (v == NULL)
18310 return;
18311 STRCPY(v->di_key, varname);
18312 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
18314 vim_free(v);
18315 return;
18317 v->di_flags = 0;
18320 if (copy || tv->v_type == VAR_NUMBER)
18321 copy_tv(tv, &v->di_tv);
18322 else
18324 v->di_tv = *tv;
18325 v->di_tv.v_lock = 0;
18326 init_tv(tv);
18331 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
18332 * Also give an error message.
18334 static int
18335 var_check_ro(flags, name)
18336 int flags;
18337 char_u *name;
18339 if (flags & DI_FLAGS_RO)
18341 EMSG2(_(e_readonlyvar), name);
18342 return TRUE;
18344 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
18346 EMSG2(_(e_readonlysbx), name);
18347 return TRUE;
18349 return FALSE;
18353 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
18354 * Also give an error message.
18356 static int
18357 var_check_fixed(flags, name)
18358 int flags;
18359 char_u *name;
18361 if (flags & DI_FLAGS_FIX)
18363 EMSG2(_("E795: Cannot delete variable %s"), name);
18364 return TRUE;
18366 return FALSE;
18370 * Return TRUE if typeval "tv" is set to be locked (immutable).
18371 * Also give an error message, using "name".
18373 static int
18374 tv_check_lock(lock, name)
18375 int lock;
18376 char_u *name;
18378 if (lock & VAR_LOCKED)
18380 EMSG2(_("E741: Value is locked: %s"),
18381 name == NULL ? (char_u *)_("Unknown") : name);
18382 return TRUE;
18384 if (lock & VAR_FIXED)
18386 EMSG2(_("E742: Cannot change value of %s"),
18387 name == NULL ? (char_u *)_("Unknown") : name);
18388 return TRUE;
18390 return FALSE;
18394 * Copy the values from typval_T "from" to typval_T "to".
18395 * When needed allocates string or increases reference count.
18396 * Does not make a copy of a list or dict but copies the reference!
18398 static void
18399 copy_tv(from, to)
18400 typval_T *from;
18401 typval_T *to;
18403 to->v_type = from->v_type;
18404 to->v_lock = 0;
18405 switch (from->v_type)
18407 case VAR_NUMBER:
18408 to->vval.v_number = from->vval.v_number;
18409 break;
18410 case VAR_STRING:
18411 case VAR_FUNC:
18412 if (from->vval.v_string == NULL)
18413 to->vval.v_string = NULL;
18414 else
18416 to->vval.v_string = vim_strsave(from->vval.v_string);
18417 if (from->v_type == VAR_FUNC)
18418 func_ref(to->vval.v_string);
18420 break;
18421 case VAR_LIST:
18422 if (from->vval.v_list == NULL)
18423 to->vval.v_list = NULL;
18424 else
18426 to->vval.v_list = from->vval.v_list;
18427 ++to->vval.v_list->lv_refcount;
18429 break;
18430 case VAR_DICT:
18431 if (from->vval.v_dict == NULL)
18432 to->vval.v_dict = NULL;
18433 else
18435 to->vval.v_dict = from->vval.v_dict;
18436 ++to->vval.v_dict->dv_refcount;
18438 break;
18439 default:
18440 EMSG2(_(e_intern2), "copy_tv()");
18441 break;
18446 * Make a copy of an item.
18447 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
18448 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
18449 * reference to an already copied list/dict can be used.
18450 * Returns FAIL or OK.
18452 static int
18453 item_copy(from, to, deep, copyID)
18454 typval_T *from;
18455 typval_T *to;
18456 int deep;
18457 int copyID;
18459 static int recurse = 0;
18460 int ret = OK;
18462 if (recurse >= DICT_MAXNEST)
18464 EMSG(_("E698: variable nested too deep for making a copy"));
18465 return FAIL;
18467 ++recurse;
18469 switch (from->v_type)
18471 case VAR_NUMBER:
18472 case VAR_STRING:
18473 case VAR_FUNC:
18474 copy_tv(from, to);
18475 break;
18476 case VAR_LIST:
18477 to->v_type = VAR_LIST;
18478 to->v_lock = 0;
18479 if (from->vval.v_list == NULL)
18480 to->vval.v_list = NULL;
18481 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
18483 /* use the copy made earlier */
18484 to->vval.v_list = from->vval.v_list->lv_copylist;
18485 ++to->vval.v_list->lv_refcount;
18487 else
18488 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
18489 if (to->vval.v_list == NULL)
18490 ret = FAIL;
18491 break;
18492 case VAR_DICT:
18493 to->v_type = VAR_DICT;
18494 to->v_lock = 0;
18495 if (from->vval.v_dict == NULL)
18496 to->vval.v_dict = NULL;
18497 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
18499 /* use the copy made earlier */
18500 to->vval.v_dict = from->vval.v_dict->dv_copydict;
18501 ++to->vval.v_dict->dv_refcount;
18503 else
18504 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
18505 if (to->vval.v_dict == NULL)
18506 ret = FAIL;
18507 break;
18508 default:
18509 EMSG2(_(e_intern2), "item_copy()");
18510 ret = FAIL;
18512 --recurse;
18513 return ret;
18517 * ":echo expr1 ..." print each argument separated with a space, add a
18518 * newline at the end.
18519 * ":echon expr1 ..." print each argument plain.
18521 void
18522 ex_echo(eap)
18523 exarg_T *eap;
18525 char_u *arg = eap->arg;
18526 typval_T rettv;
18527 char_u *tofree;
18528 char_u *p;
18529 int needclr = TRUE;
18530 int atstart = TRUE;
18531 char_u numbuf[NUMBUFLEN];
18533 if (eap->skip)
18534 ++emsg_skip;
18535 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
18537 p = arg;
18538 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
18541 * Report the invalid expression unless the expression evaluation
18542 * has been cancelled due to an aborting error, an interrupt, or an
18543 * exception.
18545 if (!aborting())
18546 EMSG2(_(e_invexpr2), p);
18547 break;
18549 if (!eap->skip)
18551 if (atstart)
18553 atstart = FALSE;
18554 /* Call msg_start() after eval1(), evaluating the expression
18555 * may cause a message to appear. */
18556 if (eap->cmdidx == CMD_echo)
18557 msg_start();
18559 else if (eap->cmdidx == CMD_echo)
18560 msg_puts_attr((char_u *)" ", echo_attr);
18561 p = echo_string(&rettv, &tofree, numbuf, ++current_copyID);
18562 if (p != NULL)
18563 for ( ; *p != NUL && !got_int; ++p)
18565 if (*p == '\n' || *p == '\r' || *p == TAB)
18567 if (*p != TAB && needclr)
18569 /* remove any text still there from the command */
18570 msg_clr_eos();
18571 needclr = FALSE;
18573 msg_putchar_attr(*p, echo_attr);
18575 else
18577 #ifdef FEAT_MBYTE
18578 if (has_mbyte)
18580 int i = (*mb_ptr2len)(p);
18582 (void)msg_outtrans_len_attr(p, i, echo_attr);
18583 p += i - 1;
18585 else
18586 #endif
18587 (void)msg_outtrans_len_attr(p, 1, echo_attr);
18590 vim_free(tofree);
18592 clear_tv(&rettv);
18593 arg = skipwhite(arg);
18595 eap->nextcmd = check_nextcmd(arg);
18597 if (eap->skip)
18598 --emsg_skip;
18599 else
18601 /* remove text that may still be there from the command */
18602 if (needclr)
18603 msg_clr_eos();
18604 if (eap->cmdidx == CMD_echo)
18605 msg_end();
18610 * ":echohl {name}".
18612 void
18613 ex_echohl(eap)
18614 exarg_T *eap;
18616 int id;
18618 id = syn_name2id(eap->arg);
18619 if (id == 0)
18620 echo_attr = 0;
18621 else
18622 echo_attr = syn_id2attr(id);
18626 * ":execute expr1 ..." execute the result of an expression.
18627 * ":echomsg expr1 ..." Print a message
18628 * ":echoerr expr1 ..." Print an error
18629 * Each gets spaces around each argument and a newline at the end for
18630 * echo commands
18632 void
18633 ex_execute(eap)
18634 exarg_T *eap;
18636 char_u *arg = eap->arg;
18637 typval_T rettv;
18638 int ret = OK;
18639 char_u *p;
18640 garray_T ga;
18641 int len;
18642 int save_did_emsg;
18644 ga_init2(&ga, 1, 80);
18646 if (eap->skip)
18647 ++emsg_skip;
18648 while (*arg != NUL && *arg != '|' && *arg != '\n')
18650 p = arg;
18651 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
18654 * Report the invalid expression unless the expression evaluation
18655 * has been cancelled due to an aborting error, an interrupt, or an
18656 * exception.
18658 if (!aborting())
18659 EMSG2(_(e_invexpr2), p);
18660 ret = FAIL;
18661 break;
18664 if (!eap->skip)
18666 p = get_tv_string(&rettv);
18667 len = (int)STRLEN(p);
18668 if (ga_grow(&ga, len + 2) == FAIL)
18670 clear_tv(&rettv);
18671 ret = FAIL;
18672 break;
18674 if (ga.ga_len)
18675 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
18676 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
18677 ga.ga_len += len;
18680 clear_tv(&rettv);
18681 arg = skipwhite(arg);
18684 if (ret != FAIL && ga.ga_data != NULL)
18686 if (eap->cmdidx == CMD_echomsg)
18688 MSG_ATTR(ga.ga_data, echo_attr);
18689 out_flush();
18691 else if (eap->cmdidx == CMD_echoerr)
18693 /* We don't want to abort following commands, restore did_emsg. */
18694 save_did_emsg = did_emsg;
18695 EMSG((char_u *)ga.ga_data);
18696 if (!force_abort)
18697 did_emsg = save_did_emsg;
18699 else if (eap->cmdidx == CMD_execute)
18700 do_cmdline((char_u *)ga.ga_data,
18701 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
18704 ga_clear(&ga);
18706 if (eap->skip)
18707 --emsg_skip;
18709 eap->nextcmd = check_nextcmd(arg);
18713 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
18714 * "arg" points to the "&" or '+' when called, to "option" when returning.
18715 * Returns NULL when no option name found. Otherwise pointer to the char
18716 * after the option name.
18718 static char_u *
18719 find_option_end(arg, opt_flags)
18720 char_u **arg;
18721 int *opt_flags;
18723 char_u *p = *arg;
18725 ++p;
18726 if (*p == 'g' && p[1] == ':')
18728 *opt_flags = OPT_GLOBAL;
18729 p += 2;
18731 else if (*p == 'l' && p[1] == ':')
18733 *opt_flags = OPT_LOCAL;
18734 p += 2;
18736 else
18737 *opt_flags = 0;
18739 if (!ASCII_ISALPHA(*p))
18740 return NULL;
18741 *arg = p;
18743 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
18744 p += 4; /* termcap option */
18745 else
18746 while (ASCII_ISALPHA(*p))
18747 ++p;
18748 return p;
18752 * ":function"
18754 void
18755 ex_function(eap)
18756 exarg_T *eap;
18758 char_u *theline;
18759 int j;
18760 int c;
18761 int saved_did_emsg;
18762 char_u *name = NULL;
18763 char_u *p;
18764 char_u *arg;
18765 char_u *line_arg = NULL;
18766 garray_T newargs;
18767 garray_T newlines;
18768 int varargs = FALSE;
18769 int mustend = FALSE;
18770 int flags = 0;
18771 ufunc_T *fp;
18772 int indent;
18773 int nesting;
18774 char_u *skip_until = NULL;
18775 dictitem_T *v;
18776 funcdict_T fudi;
18777 static int func_nr = 0; /* number for nameless function */
18778 int paren;
18779 hashtab_T *ht;
18780 int todo;
18781 hashitem_T *hi;
18782 int sourcing_lnum_off;
18785 * ":function" without argument: list functions.
18787 if (ends_excmd(*eap->arg))
18789 if (!eap->skip)
18791 todo = (int)func_hashtab.ht_used;
18792 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
18794 if (!HASHITEM_EMPTY(hi))
18796 --todo;
18797 fp = HI2UF(hi);
18798 if (!isdigit(*fp->uf_name))
18799 list_func_head(fp, FALSE);
18803 eap->nextcmd = check_nextcmd(eap->arg);
18804 return;
18808 * ":function /pat": list functions matching pattern.
18810 if (*eap->arg == '/')
18812 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
18813 if (!eap->skip)
18815 regmatch_T regmatch;
18817 c = *p;
18818 *p = NUL;
18819 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
18820 *p = c;
18821 if (regmatch.regprog != NULL)
18823 regmatch.rm_ic = p_ic;
18825 todo = (int)func_hashtab.ht_used;
18826 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
18828 if (!HASHITEM_EMPTY(hi))
18830 --todo;
18831 fp = HI2UF(hi);
18832 if (!isdigit(*fp->uf_name)
18833 && vim_regexec(&regmatch, fp->uf_name, 0))
18834 list_func_head(fp, FALSE);
18839 if (*p == '/')
18840 ++p;
18841 eap->nextcmd = check_nextcmd(p);
18842 return;
18846 * Get the function name. There are these situations:
18847 * func normal function name
18848 * "name" == func, "fudi.fd_dict" == NULL
18849 * dict.func new dictionary entry
18850 * "name" == NULL, "fudi.fd_dict" set,
18851 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
18852 * dict.func existing dict entry with a Funcref
18853 * "name" == func, "fudi.fd_dict" set,
18854 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
18855 * dict.func existing dict entry that's not a Funcref
18856 * "name" == NULL, "fudi.fd_dict" set,
18857 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
18859 p = eap->arg;
18860 name = trans_function_name(&p, eap->skip, 0, &fudi);
18861 paren = (vim_strchr(p, '(') != NULL);
18862 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
18865 * Return on an invalid expression in braces, unless the expression
18866 * evaluation has been cancelled due to an aborting error, an
18867 * interrupt, or an exception.
18869 if (!aborting())
18871 if (!eap->skip && fudi.fd_newkey != NULL)
18872 EMSG2(_(e_dictkey), fudi.fd_newkey);
18873 vim_free(fudi.fd_newkey);
18874 return;
18876 else
18877 eap->skip = TRUE;
18880 /* An error in a function call during evaluation of an expression in magic
18881 * braces should not cause the function not to be defined. */
18882 saved_did_emsg = did_emsg;
18883 did_emsg = FALSE;
18886 * ":function func" with only function name: list function.
18888 if (!paren)
18890 if (!ends_excmd(*skipwhite(p)))
18892 EMSG(_(e_trailing));
18893 goto ret_free;
18895 eap->nextcmd = check_nextcmd(p);
18896 if (eap->nextcmd != NULL)
18897 *p = NUL;
18898 if (!eap->skip && !got_int)
18900 fp = find_func(name);
18901 if (fp != NULL)
18903 list_func_head(fp, TRUE);
18904 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
18906 if (FUNCLINE(fp, j) == NULL)
18907 continue;
18908 msg_putchar('\n');
18909 msg_outnum((long)(j + 1));
18910 if (j < 9)
18911 msg_putchar(' ');
18912 if (j < 99)
18913 msg_putchar(' ');
18914 msg_prt_line(FUNCLINE(fp, j), FALSE);
18915 out_flush(); /* show a line at a time */
18916 ui_breakcheck();
18918 if (!got_int)
18920 msg_putchar('\n');
18921 msg_puts((char_u *)" endfunction");
18924 else
18925 emsg_funcname("E123: Undefined function: %s", name);
18927 goto ret_free;
18931 * ":function name(arg1, arg2)" Define function.
18933 p = skipwhite(p);
18934 if (*p != '(')
18936 if (!eap->skip)
18938 EMSG2(_("E124: Missing '(': %s"), eap->arg);
18939 goto ret_free;
18941 /* attempt to continue by skipping some text */
18942 if (vim_strchr(p, '(') != NULL)
18943 p = vim_strchr(p, '(');
18945 p = skipwhite(p + 1);
18947 ga_init2(&newargs, (int)sizeof(char_u *), 3);
18948 ga_init2(&newlines, (int)sizeof(char_u *), 3);
18950 if (!eap->skip)
18952 /* Check the name of the function. Unless it's a dictionary function
18953 * (that we are overwriting). */
18954 if (name != NULL)
18955 arg = name;
18956 else
18957 arg = fudi.fd_newkey;
18958 if (arg != NULL && (fudi.fd_di == NULL
18959 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
18961 if (*arg == K_SPECIAL)
18962 j = 3;
18963 else
18964 j = 0;
18965 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
18966 : eval_isnamec(arg[j])))
18967 ++j;
18968 if (arg[j] != NUL)
18969 emsg_funcname(_(e_invarg2), arg);
18974 * Isolate the arguments: "arg1, arg2, ...)"
18976 while (*p != ')')
18978 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
18980 varargs = TRUE;
18981 p += 3;
18982 mustend = TRUE;
18984 else
18986 arg = p;
18987 while (ASCII_ISALNUM(*p) || *p == '_')
18988 ++p;
18989 if (arg == p || isdigit(*arg)
18990 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
18991 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
18993 if (!eap->skip)
18994 EMSG2(_("E125: Illegal argument: %s"), arg);
18995 break;
18997 if (ga_grow(&newargs, 1) == FAIL)
18998 goto erret;
18999 c = *p;
19000 *p = NUL;
19001 arg = vim_strsave(arg);
19002 if (arg == NULL)
19003 goto erret;
19004 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
19005 *p = c;
19006 newargs.ga_len++;
19007 if (*p == ',')
19008 ++p;
19009 else
19010 mustend = TRUE;
19012 p = skipwhite(p);
19013 if (mustend && *p != ')')
19015 if (!eap->skip)
19016 EMSG2(_(e_invarg2), eap->arg);
19017 break;
19020 ++p; /* skip the ')' */
19022 /* find extra arguments "range", "dict" and "abort" */
19023 for (;;)
19025 p = skipwhite(p);
19026 if (STRNCMP(p, "range", 5) == 0)
19028 flags |= FC_RANGE;
19029 p += 5;
19031 else if (STRNCMP(p, "dict", 4) == 0)
19033 flags |= FC_DICT;
19034 p += 4;
19036 else if (STRNCMP(p, "abort", 5) == 0)
19038 flags |= FC_ABORT;
19039 p += 5;
19041 else
19042 break;
19045 /* When there is a line break use what follows for the function body.
19046 * Makes 'exe "func Test()\n...\nendfunc"' work. */
19047 if (*p == '\n')
19048 line_arg = p + 1;
19049 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
19050 EMSG(_(e_trailing));
19053 * Read the body of the function, until ":endfunction" is found.
19055 if (KeyTyped)
19057 /* Check if the function already exists, don't let the user type the
19058 * whole function before telling him it doesn't work! For a script we
19059 * need to skip the body to be able to find what follows. */
19060 if (!eap->skip && !eap->forceit)
19062 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
19063 EMSG(_(e_funcdict));
19064 else if (name != NULL && find_func(name) != NULL)
19065 emsg_funcname(e_funcexts, name);
19068 if (!eap->skip && did_emsg)
19069 goto erret;
19071 msg_putchar('\n'); /* don't overwrite the function name */
19072 cmdline_row = msg_row;
19075 indent = 2;
19076 nesting = 0;
19077 for (;;)
19079 msg_scroll = TRUE;
19080 need_wait_return = FALSE;
19081 sourcing_lnum_off = sourcing_lnum;
19083 if (line_arg != NULL)
19085 /* Use eap->arg, split up in parts by line breaks. */
19086 theline = line_arg;
19087 p = vim_strchr(theline, '\n');
19088 if (p == NULL)
19089 line_arg += STRLEN(line_arg);
19090 else
19092 *p = NUL;
19093 line_arg = p + 1;
19096 else if (eap->getline == NULL)
19097 theline = getcmdline(':', 0L, indent);
19098 else
19099 theline = eap->getline(':', eap->cookie, indent);
19100 if (KeyTyped)
19101 lines_left = Rows - 1;
19102 if (theline == NULL)
19104 EMSG(_("E126: Missing :endfunction"));
19105 goto erret;
19108 /* Detect line continuation: sourcing_lnum increased more than one. */
19109 if (sourcing_lnum > sourcing_lnum_off + 1)
19110 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
19111 else
19112 sourcing_lnum_off = 0;
19114 if (skip_until != NULL)
19116 /* between ":append" and "." and between ":python <<EOF" and "EOF"
19117 * don't check for ":endfunc". */
19118 if (STRCMP(theline, skip_until) == 0)
19120 vim_free(skip_until);
19121 skip_until = NULL;
19124 else
19126 /* skip ':' and blanks*/
19127 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
19130 /* Check for "endfunction". */
19131 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
19133 if (line_arg == NULL)
19134 vim_free(theline);
19135 break;
19138 /* Increase indent inside "if", "while", "for" and "try", decrease
19139 * at "end". */
19140 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
19141 indent -= 2;
19142 else if (STRNCMP(p, "if", 2) == 0
19143 || STRNCMP(p, "wh", 2) == 0
19144 || STRNCMP(p, "for", 3) == 0
19145 || STRNCMP(p, "try", 3) == 0)
19146 indent += 2;
19148 /* Check for defining a function inside this function. */
19149 if (checkforcmd(&p, "function", 2))
19151 if (*p == '!')
19152 p = skipwhite(p + 1);
19153 p += eval_fname_script(p);
19154 if (ASCII_ISALPHA(*p))
19156 vim_free(trans_function_name(&p, TRUE, 0, NULL));
19157 if (*skipwhite(p) == '(')
19159 ++nesting;
19160 indent += 2;
19165 /* Check for ":append" or ":insert". */
19166 p = skip_range(p, NULL);
19167 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
19168 || (p[0] == 'i'
19169 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
19170 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
19171 skip_until = vim_strsave((char_u *)".");
19173 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
19174 arg = skipwhite(skiptowhite(p));
19175 if (arg[0] == '<' && arg[1] =='<'
19176 && ((p[0] == 'p' && p[1] == 'y'
19177 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
19178 || (p[0] == 'p' && p[1] == 'e'
19179 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
19180 || (p[0] == 't' && p[1] == 'c'
19181 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
19182 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
19183 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
19184 || (p[0] == 'm' && p[1] == 'z'
19185 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
19188 /* ":python <<" continues until a dot, like ":append" */
19189 p = skipwhite(arg + 2);
19190 if (*p == NUL)
19191 skip_until = vim_strsave((char_u *)".");
19192 else
19193 skip_until = vim_strsave(p);
19197 /* Add the line to the function. */
19198 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
19200 if (line_arg == NULL)
19201 vim_free(theline);
19202 goto erret;
19205 /* Copy the line to newly allocated memory. get_one_sourceline()
19206 * allocates 250 bytes per line, this saves 80% on average. The cost
19207 * is an extra alloc/free. */
19208 p = vim_strsave(theline);
19209 if (p != NULL)
19211 if (line_arg == NULL)
19212 vim_free(theline);
19213 theline = p;
19216 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
19218 /* Add NULL lines for continuation lines, so that the line count is
19219 * equal to the index in the growarray. */
19220 while (sourcing_lnum_off-- > 0)
19221 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
19223 /* Check for end of eap->arg. */
19224 if (line_arg != NULL && *line_arg == NUL)
19225 line_arg = NULL;
19228 /* Don't define the function when skipping commands or when an error was
19229 * detected. */
19230 if (eap->skip || did_emsg)
19231 goto erret;
19234 * If there are no errors, add the function
19236 if (fudi.fd_dict == NULL)
19238 v = find_var(name, &ht);
19239 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
19241 emsg_funcname("E707: Function name conflicts with variable: %s",
19242 name);
19243 goto erret;
19246 fp = find_func(name);
19247 if (fp != NULL)
19249 if (!eap->forceit)
19251 emsg_funcname(e_funcexts, name);
19252 goto erret;
19254 if (fp->uf_calls > 0)
19256 emsg_funcname("E127: Cannot redefine function %s: It is in use",
19257 name);
19258 goto erret;
19260 /* redefine existing function */
19261 ga_clear_strings(&(fp->uf_args));
19262 ga_clear_strings(&(fp->uf_lines));
19263 vim_free(name);
19264 name = NULL;
19267 else
19269 char numbuf[20];
19271 fp = NULL;
19272 if (fudi.fd_newkey == NULL && !eap->forceit)
19274 EMSG(_(e_funcdict));
19275 goto erret;
19277 if (fudi.fd_di == NULL)
19279 /* Can't add a function to a locked dictionary */
19280 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
19281 goto erret;
19283 /* Can't change an existing function if it is locked */
19284 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
19285 goto erret;
19287 /* Give the function a sequential number. Can only be used with a
19288 * Funcref! */
19289 vim_free(name);
19290 sprintf(numbuf, "%d", ++func_nr);
19291 name = vim_strsave((char_u *)numbuf);
19292 if (name == NULL)
19293 goto erret;
19296 if (fp == NULL)
19298 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
19300 int slen, plen;
19301 char_u *scriptname;
19303 /* Check that the autoload name matches the script name. */
19304 j = FAIL;
19305 if (sourcing_name != NULL)
19307 scriptname = autoload_name(name);
19308 if (scriptname != NULL)
19310 p = vim_strchr(scriptname, '/');
19311 plen = (int)STRLEN(p);
19312 slen = (int)STRLEN(sourcing_name);
19313 if (slen > plen && fnamecmp(p,
19314 sourcing_name + slen - plen) == 0)
19315 j = OK;
19316 vim_free(scriptname);
19319 if (j == FAIL)
19321 EMSG2(_("E746: Function name does not match script file name: %s"), name);
19322 goto erret;
19326 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
19327 if (fp == NULL)
19328 goto erret;
19330 if (fudi.fd_dict != NULL)
19332 if (fudi.fd_di == NULL)
19334 /* add new dict entry */
19335 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
19336 if (fudi.fd_di == NULL)
19338 vim_free(fp);
19339 goto erret;
19341 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
19343 vim_free(fudi.fd_di);
19344 vim_free(fp);
19345 goto erret;
19348 else
19349 /* overwrite existing dict entry */
19350 clear_tv(&fudi.fd_di->di_tv);
19351 fudi.fd_di->di_tv.v_type = VAR_FUNC;
19352 fudi.fd_di->di_tv.v_lock = 0;
19353 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
19354 fp->uf_refcount = 1;
19356 /* behave like "dict" was used */
19357 flags |= FC_DICT;
19360 /* insert the new function in the function list */
19361 STRCPY(fp->uf_name, name);
19362 hash_add(&func_hashtab, UF2HIKEY(fp));
19364 fp->uf_args = newargs;
19365 fp->uf_lines = newlines;
19366 #ifdef FEAT_PROFILE
19367 fp->uf_tml_count = NULL;
19368 fp->uf_tml_total = NULL;
19369 fp->uf_tml_self = NULL;
19370 fp->uf_profiling = FALSE;
19371 if (prof_def_func())
19372 func_do_profile(fp);
19373 #endif
19374 fp->uf_varargs = varargs;
19375 fp->uf_flags = flags;
19376 fp->uf_calls = 0;
19377 fp->uf_script_ID = current_SID;
19378 goto ret_free;
19380 erret:
19381 ga_clear_strings(&newargs);
19382 ga_clear_strings(&newlines);
19383 ret_free:
19384 vim_free(skip_until);
19385 vim_free(fudi.fd_newkey);
19386 vim_free(name);
19387 did_emsg |= saved_did_emsg;
19391 * Get a function name, translating "<SID>" and "<SNR>".
19392 * Also handles a Funcref in a List or Dictionary.
19393 * Returns the function name in allocated memory, or NULL for failure.
19394 * flags:
19395 * TFN_INT: internal function name OK
19396 * TFN_QUIET: be quiet
19397 * Advances "pp" to just after the function name (if no error).
19399 static char_u *
19400 trans_function_name(pp, skip, flags, fdp)
19401 char_u **pp;
19402 int skip; /* only find the end, don't evaluate */
19403 int flags;
19404 funcdict_T *fdp; /* return: info about dictionary used */
19406 char_u *name = NULL;
19407 char_u *start;
19408 char_u *end;
19409 int lead;
19410 char_u sid_buf[20];
19411 int len;
19412 lval_T lv;
19414 if (fdp != NULL)
19415 vim_memset(fdp, 0, sizeof(funcdict_T));
19416 start = *pp;
19418 /* Check for hard coded <SNR>: already translated function ID (from a user
19419 * command). */
19420 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
19421 && (*pp)[2] == (int)KE_SNR)
19423 *pp += 3;
19424 len = get_id_len(pp) + 3;
19425 return vim_strnsave(start, len);
19428 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
19429 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
19430 lead = eval_fname_script(start);
19431 if (lead > 2)
19432 start += lead;
19434 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
19435 lead > 2 ? 0 : FNE_CHECK_START);
19436 if (end == start)
19438 if (!skip)
19439 EMSG(_("E129: Function name required"));
19440 goto theend;
19442 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
19445 * Report an invalid expression in braces, unless the expression
19446 * evaluation has been cancelled due to an aborting error, an
19447 * interrupt, or an exception.
19449 if (!aborting())
19451 if (end != NULL)
19452 EMSG2(_(e_invarg2), start);
19454 else
19455 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
19456 goto theend;
19459 if (lv.ll_tv != NULL)
19461 if (fdp != NULL)
19463 fdp->fd_dict = lv.ll_dict;
19464 fdp->fd_newkey = lv.ll_newkey;
19465 lv.ll_newkey = NULL;
19466 fdp->fd_di = lv.ll_di;
19468 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
19470 name = vim_strsave(lv.ll_tv->vval.v_string);
19471 *pp = end;
19473 else
19475 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
19476 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
19477 EMSG(_(e_funcref));
19478 else
19479 *pp = end;
19480 name = NULL;
19482 goto theend;
19485 if (lv.ll_name == NULL)
19487 /* Error found, but continue after the function name. */
19488 *pp = end;
19489 goto theend;
19492 /* Check if the name is a Funcref. If so, use the value. */
19493 if (lv.ll_exp_name != NULL)
19495 len = (int)STRLEN(lv.ll_exp_name);
19496 name = deref_func_name(lv.ll_exp_name, &len);
19497 if (name == lv.ll_exp_name)
19498 name = NULL;
19500 else
19502 len = (int)(end - *pp);
19503 name = deref_func_name(*pp, &len);
19504 if (name == *pp)
19505 name = NULL;
19507 if (name != NULL)
19509 name = vim_strsave(name);
19510 *pp = end;
19511 goto theend;
19514 if (lv.ll_exp_name != NULL)
19516 len = (int)STRLEN(lv.ll_exp_name);
19517 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
19518 && STRNCMP(lv.ll_name, "s:", 2) == 0)
19520 /* When there was "s:" already or the name expanded to get a
19521 * leading "s:" then remove it. */
19522 lv.ll_name += 2;
19523 len -= 2;
19524 lead = 2;
19527 else
19529 if (lead == 2) /* skip over "s:" */
19530 lv.ll_name += 2;
19531 len = (int)(end - lv.ll_name);
19535 * Copy the function name to allocated memory.
19536 * Accept <SID>name() inside a script, translate into <SNR>123_name().
19537 * Accept <SNR>123_name() outside a script.
19539 if (skip)
19540 lead = 0; /* do nothing */
19541 else if (lead > 0)
19543 lead = 3;
19544 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
19545 || eval_fname_sid(*pp))
19547 /* It's "s:" or "<SID>" */
19548 if (current_SID <= 0)
19550 EMSG(_(e_usingsid));
19551 goto theend;
19553 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
19554 lead += (int)STRLEN(sid_buf);
19557 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
19559 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
19560 goto theend;
19562 name = alloc((unsigned)(len + lead + 1));
19563 if (name != NULL)
19565 if (lead > 0)
19567 name[0] = K_SPECIAL;
19568 name[1] = KS_EXTRA;
19569 name[2] = (int)KE_SNR;
19570 if (lead > 3) /* If it's "<SID>" */
19571 STRCPY(name + 3, sid_buf);
19573 mch_memmove(name + lead, lv.ll_name, (size_t)len);
19574 name[len + lead] = NUL;
19576 *pp = end;
19578 theend:
19579 clear_lval(&lv);
19580 return name;
19584 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
19585 * Return 2 if "p" starts with "s:".
19586 * Return 0 otherwise.
19588 static int
19589 eval_fname_script(p)
19590 char_u *p;
19592 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
19593 || STRNICMP(p + 1, "SNR>", 4) == 0))
19594 return 5;
19595 if (p[0] == 's' && p[1] == ':')
19596 return 2;
19597 return 0;
19601 * Return TRUE if "p" starts with "<SID>" or "s:".
19602 * Only works if eval_fname_script() returned non-zero for "p"!
19604 static int
19605 eval_fname_sid(p)
19606 char_u *p;
19608 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
19612 * List the head of the function: "name(arg1, arg2)".
19614 static void
19615 list_func_head(fp, indent)
19616 ufunc_T *fp;
19617 int indent;
19619 int j;
19621 msg_start();
19622 if (indent)
19623 MSG_PUTS(" ");
19624 MSG_PUTS("function ");
19625 if (fp->uf_name[0] == K_SPECIAL)
19627 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
19628 msg_puts(fp->uf_name + 3);
19630 else
19631 msg_puts(fp->uf_name);
19632 msg_putchar('(');
19633 for (j = 0; j < fp->uf_args.ga_len; ++j)
19635 if (j)
19636 MSG_PUTS(", ");
19637 msg_puts(FUNCARG(fp, j));
19639 if (fp->uf_varargs)
19641 if (j)
19642 MSG_PUTS(", ");
19643 MSG_PUTS("...");
19645 msg_putchar(')');
19646 msg_clr_eos();
19647 if (p_verbose > 0)
19648 last_set_msg(fp->uf_script_ID);
19652 * Find a function by name, return pointer to it in ufuncs.
19653 * Return NULL for unknown function.
19655 static ufunc_T *
19656 find_func(name)
19657 char_u *name;
19659 hashitem_T *hi;
19661 hi = hash_find(&func_hashtab, name);
19662 if (!HASHITEM_EMPTY(hi))
19663 return HI2UF(hi);
19664 return NULL;
19667 #if defined(EXITFREE) || defined(PROTO)
19668 void
19669 free_all_functions()
19671 hashitem_T *hi;
19673 /* Need to start all over every time, because func_free() may change the
19674 * hash table. */
19675 while (func_hashtab.ht_used > 0)
19676 for (hi = func_hashtab.ht_array; ; ++hi)
19677 if (!HASHITEM_EMPTY(hi))
19679 func_free(HI2UF(hi));
19680 break;
19683 #endif
19686 * Return TRUE if a function "name" exists.
19688 static int
19689 function_exists(name)
19690 char_u *name;
19692 char_u *nm = name;
19693 char_u *p;
19694 int n = FALSE;
19696 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
19697 nm = skipwhite(nm);
19699 /* Only accept "funcname", "funcname ", "funcname (..." and
19700 * "funcname(...", not "funcname!...". */
19701 if (p != NULL && (*nm == NUL || *nm == '('))
19703 if (builtin_function(p))
19704 n = (find_internal_func(p) >= 0);
19705 else
19706 n = (find_func(p) != NULL);
19708 vim_free(p);
19709 return n;
19713 * Return TRUE if "name" looks like a builtin function name: starts with a
19714 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
19716 static int
19717 builtin_function(name)
19718 char_u *name;
19720 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
19721 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
19724 #if defined(FEAT_PROFILE) || defined(PROTO)
19726 * Start profiling function "fp".
19728 static void
19729 func_do_profile(fp)
19730 ufunc_T *fp;
19732 fp->uf_tm_count = 0;
19733 profile_zero(&fp->uf_tm_self);
19734 profile_zero(&fp->uf_tm_total);
19735 if (fp->uf_tml_count == NULL)
19736 fp->uf_tml_count = (int *)alloc_clear((unsigned)
19737 (sizeof(int) * fp->uf_lines.ga_len));
19738 if (fp->uf_tml_total == NULL)
19739 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
19740 (sizeof(proftime_T) * fp->uf_lines.ga_len));
19741 if (fp->uf_tml_self == NULL)
19742 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
19743 (sizeof(proftime_T) * fp->uf_lines.ga_len));
19744 fp->uf_tml_idx = -1;
19745 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
19746 || fp->uf_tml_self == NULL)
19747 return; /* out of memory */
19749 fp->uf_profiling = TRUE;
19753 * Dump the profiling results for all functions in file "fd".
19755 void
19756 func_dump_profile(fd)
19757 FILE *fd;
19759 hashitem_T *hi;
19760 int todo;
19761 ufunc_T *fp;
19762 int i;
19763 ufunc_T **sorttab;
19764 int st_len = 0;
19766 todo = (int)func_hashtab.ht_used;
19767 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
19769 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
19771 if (!HASHITEM_EMPTY(hi))
19773 --todo;
19774 fp = HI2UF(hi);
19775 if (fp->uf_profiling)
19777 if (sorttab != NULL)
19778 sorttab[st_len++] = fp;
19780 if (fp->uf_name[0] == K_SPECIAL)
19781 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
19782 else
19783 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
19784 if (fp->uf_tm_count == 1)
19785 fprintf(fd, "Called 1 time\n");
19786 else
19787 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
19788 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
19789 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
19790 fprintf(fd, "\n");
19791 fprintf(fd, "count total (s) self (s)\n");
19793 for (i = 0; i < fp->uf_lines.ga_len; ++i)
19795 if (FUNCLINE(fp, i) == NULL)
19796 continue;
19797 prof_func_line(fd, fp->uf_tml_count[i],
19798 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
19799 fprintf(fd, "%s\n", FUNCLINE(fp, i));
19801 fprintf(fd, "\n");
19806 if (sorttab != NULL && st_len > 0)
19808 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
19809 prof_total_cmp);
19810 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
19811 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
19812 prof_self_cmp);
19813 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
19817 static void
19818 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
19819 FILE *fd;
19820 ufunc_T **sorttab;
19821 int st_len;
19822 char *title;
19823 int prefer_self; /* when equal print only self time */
19825 int i;
19826 ufunc_T *fp;
19828 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
19829 fprintf(fd, "count total (s) self (s) function\n");
19830 for (i = 0; i < 20 && i < st_len; ++i)
19832 fp = sorttab[i];
19833 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
19834 prefer_self);
19835 if (fp->uf_name[0] == K_SPECIAL)
19836 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
19837 else
19838 fprintf(fd, " %s()\n", fp->uf_name);
19840 fprintf(fd, "\n");
19844 * Print the count and times for one function or function line.
19846 static void
19847 prof_func_line(fd, count, total, self, prefer_self)
19848 FILE *fd;
19849 int count;
19850 proftime_T *total;
19851 proftime_T *self;
19852 int prefer_self; /* when equal print only self time */
19854 if (count > 0)
19856 fprintf(fd, "%5d ", count);
19857 if (prefer_self && profile_equal(total, self))
19858 fprintf(fd, " ");
19859 else
19860 fprintf(fd, "%s ", profile_msg(total));
19861 if (!prefer_self && profile_equal(total, self))
19862 fprintf(fd, " ");
19863 else
19864 fprintf(fd, "%s ", profile_msg(self));
19866 else
19867 fprintf(fd, " ");
19871 * Compare function for total time sorting.
19873 static int
19874 #ifdef __BORLANDC__
19875 _RTLENTRYF
19876 #endif
19877 prof_total_cmp(s1, s2)
19878 const void *s1;
19879 const void *s2;
19881 ufunc_T *p1, *p2;
19883 p1 = *(ufunc_T **)s1;
19884 p2 = *(ufunc_T **)s2;
19885 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
19889 * Compare function for self time sorting.
19891 static int
19892 #ifdef __BORLANDC__
19893 _RTLENTRYF
19894 #endif
19895 prof_self_cmp(s1, s2)
19896 const void *s1;
19897 const void *s2;
19899 ufunc_T *p1, *p2;
19901 p1 = *(ufunc_T **)s1;
19902 p2 = *(ufunc_T **)s2;
19903 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
19906 #endif
19909 * If "name" has a package name try autoloading the script for it.
19910 * Return TRUE if a package was loaded.
19912 static int
19913 script_autoload(name, reload)
19914 char_u *name;
19915 int reload; /* load script again when already loaded */
19917 char_u *p;
19918 char_u *scriptname, *tofree;
19919 int ret = FALSE;
19920 int i;
19922 /* If there is no '#' after name[0] there is no package name. */
19923 p = vim_strchr(name, AUTOLOAD_CHAR);
19924 if (p == NULL || p == name)
19925 return FALSE;
19927 tofree = scriptname = autoload_name(name);
19929 /* Find the name in the list of previously loaded package names. Skip
19930 * "autoload/", it's always the same. */
19931 for (i = 0; i < ga_loaded.ga_len; ++i)
19932 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
19933 break;
19934 if (!reload && i < ga_loaded.ga_len)
19935 ret = FALSE; /* was loaded already */
19936 else
19938 /* Remember the name if it wasn't loaded already. */
19939 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
19941 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
19942 tofree = NULL;
19945 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
19946 if (source_runtime(scriptname, FALSE) == OK)
19947 ret = TRUE;
19950 vim_free(tofree);
19951 return ret;
19955 * Return the autoload script name for a function or variable name.
19956 * Returns NULL when out of memory.
19958 static char_u *
19959 autoload_name(name)
19960 char_u *name;
19962 char_u *p;
19963 char_u *scriptname;
19965 /* Get the script file name: replace '#' with '/', append ".vim". */
19966 scriptname = alloc((unsigned)(STRLEN(name) + 14));
19967 if (scriptname == NULL)
19968 return FALSE;
19969 STRCPY(scriptname, "autoload/");
19970 STRCAT(scriptname, name);
19971 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
19972 STRCAT(scriptname, ".vim");
19973 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
19974 *p = '/';
19975 return scriptname;
19978 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
19981 * Function given to ExpandGeneric() to obtain the list of user defined
19982 * function names.
19984 char_u *
19985 get_user_func_name(xp, idx)
19986 expand_T *xp;
19987 int idx;
19989 static long_u done;
19990 static hashitem_T *hi;
19991 ufunc_T *fp;
19993 if (idx == 0)
19995 done = 0;
19996 hi = func_hashtab.ht_array;
19998 if (done < func_hashtab.ht_used)
20000 if (done++ > 0)
20001 ++hi;
20002 while (HASHITEM_EMPTY(hi))
20003 ++hi;
20004 fp = HI2UF(hi);
20006 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
20007 return fp->uf_name; /* prevents overflow */
20009 cat_func_name(IObuff, fp);
20010 if (xp->xp_context != EXPAND_USER_FUNC)
20012 STRCAT(IObuff, "(");
20013 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
20014 STRCAT(IObuff, ")");
20016 return IObuff;
20018 return NULL;
20021 #endif /* FEAT_CMDL_COMPL */
20024 * Copy the function name of "fp" to buffer "buf".
20025 * "buf" must be able to hold the function name plus three bytes.
20026 * Takes care of script-local function names.
20028 static void
20029 cat_func_name(buf, fp)
20030 char_u *buf;
20031 ufunc_T *fp;
20033 if (fp->uf_name[0] == K_SPECIAL)
20035 STRCPY(buf, "<SNR>");
20036 STRCAT(buf, fp->uf_name + 3);
20038 else
20039 STRCPY(buf, fp->uf_name);
20043 * ":delfunction {name}"
20045 void
20046 ex_delfunction(eap)
20047 exarg_T *eap;
20049 ufunc_T *fp = NULL;
20050 char_u *p;
20051 char_u *name;
20052 funcdict_T fudi;
20054 p = eap->arg;
20055 name = trans_function_name(&p, eap->skip, 0, &fudi);
20056 vim_free(fudi.fd_newkey);
20057 if (name == NULL)
20059 if (fudi.fd_dict != NULL && !eap->skip)
20060 EMSG(_(e_funcref));
20061 return;
20063 if (!ends_excmd(*skipwhite(p)))
20065 vim_free(name);
20066 EMSG(_(e_trailing));
20067 return;
20069 eap->nextcmd = check_nextcmd(p);
20070 if (eap->nextcmd != NULL)
20071 *p = NUL;
20073 if (!eap->skip)
20074 fp = find_func(name);
20075 vim_free(name);
20077 if (!eap->skip)
20079 if (fp == NULL)
20081 EMSG2(_(e_nofunc), eap->arg);
20082 return;
20084 if (fp->uf_calls > 0)
20086 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
20087 return;
20090 if (fudi.fd_dict != NULL)
20092 /* Delete the dict item that refers to the function, it will
20093 * invoke func_unref() and possibly delete the function. */
20094 dictitem_remove(fudi.fd_dict, fudi.fd_di);
20096 else
20097 func_free(fp);
20102 * Free a function and remove it from the list of functions.
20104 static void
20105 func_free(fp)
20106 ufunc_T *fp;
20108 hashitem_T *hi;
20110 /* clear this function */
20111 ga_clear_strings(&(fp->uf_args));
20112 ga_clear_strings(&(fp->uf_lines));
20113 #ifdef FEAT_PROFILE
20114 vim_free(fp->uf_tml_count);
20115 vim_free(fp->uf_tml_total);
20116 vim_free(fp->uf_tml_self);
20117 #endif
20119 /* remove the function from the function hashtable */
20120 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
20121 if (HASHITEM_EMPTY(hi))
20122 EMSG2(_(e_intern2), "func_free()");
20123 else
20124 hash_remove(&func_hashtab, hi);
20126 vim_free(fp);
20130 * Unreference a Function: decrement the reference count and free it when it
20131 * becomes zero. Only for numbered functions.
20133 static void
20134 func_unref(name)
20135 char_u *name;
20137 ufunc_T *fp;
20139 if (name != NULL && isdigit(*name))
20141 fp = find_func(name);
20142 if (fp == NULL)
20143 EMSG2(_(e_intern2), "func_unref()");
20144 else if (--fp->uf_refcount <= 0)
20146 /* Only delete it when it's not being used. Otherwise it's done
20147 * when "uf_calls" becomes zero. */
20148 if (fp->uf_calls == 0)
20149 func_free(fp);
20155 * Count a reference to a Function.
20157 static void
20158 func_ref(name)
20159 char_u *name;
20161 ufunc_T *fp;
20163 if (name != NULL && isdigit(*name))
20165 fp = find_func(name);
20166 if (fp == NULL)
20167 EMSG2(_(e_intern2), "func_ref()");
20168 else
20169 ++fp->uf_refcount;
20174 * Call a user function.
20176 static void
20177 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
20178 ufunc_T *fp; /* pointer to function */
20179 int argcount; /* nr of args */
20180 typval_T *argvars; /* arguments */
20181 typval_T *rettv; /* return value */
20182 linenr_T firstline; /* first line of range */
20183 linenr_T lastline; /* last line of range */
20184 dict_T *selfdict; /* Dictionary for "self" */
20186 char_u *save_sourcing_name;
20187 linenr_T save_sourcing_lnum;
20188 scid_T save_current_SID;
20189 funccall_T fc;
20190 int save_did_emsg;
20191 static int depth = 0;
20192 dictitem_T *v;
20193 int fixvar_idx = 0; /* index in fixvar[] */
20194 int i;
20195 int ai;
20196 char_u numbuf[NUMBUFLEN];
20197 char_u *name;
20198 #ifdef FEAT_PROFILE
20199 proftime_T wait_start;
20200 proftime_T call_start;
20201 #endif
20203 /* If depth of calling is getting too high, don't execute the function */
20204 if (depth >= p_mfd)
20206 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
20207 rettv->v_type = VAR_NUMBER;
20208 rettv->vval.v_number = -1;
20209 return;
20211 ++depth;
20213 line_breakcheck(); /* check for CTRL-C hit */
20215 fc.caller = current_funccal;
20216 current_funccal = &fc;
20217 fc.func = fp;
20218 fc.rettv = rettv;
20219 rettv->vval.v_number = 0;
20220 fc.linenr = 0;
20221 fc.returned = FALSE;
20222 fc.level = ex_nesting_level;
20223 /* Check if this function has a breakpoint. */
20224 fc.breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
20225 fc.dbg_tick = debug_tick;
20228 * Note about using fc.fixvar[]: This is an array of FIXVAR_CNT variables
20229 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
20230 * each argument variable and saves a lot of time.
20233 * Init l: variables.
20235 init_var_dict(&fc.l_vars, &fc.l_vars_var);
20236 if (selfdict != NULL)
20238 /* Set l:self to "selfdict". Use "name" to avoid a warning from
20239 * some compiler that checks the destination size. */
20240 v = &fc.fixvar[fixvar_idx++].var;
20241 name = v->di_key;
20242 STRCPY(name, "self");
20243 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
20244 hash_add(&fc.l_vars.dv_hashtab, DI2HIKEY(v));
20245 v->di_tv.v_type = VAR_DICT;
20246 v->di_tv.v_lock = 0;
20247 v->di_tv.vval.v_dict = selfdict;
20248 ++selfdict->dv_refcount;
20252 * Init a: variables.
20253 * Set a:0 to "argcount".
20254 * Set a:000 to a list with room for the "..." arguments.
20256 init_var_dict(&fc.l_avars, &fc.l_avars_var);
20257 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "0",
20258 (varnumber_T)(argcount - fp->uf_args.ga_len));
20259 v = &fc.fixvar[fixvar_idx++].var;
20260 STRCPY(v->di_key, "000");
20261 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20262 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
20263 v->di_tv.v_type = VAR_LIST;
20264 v->di_tv.v_lock = VAR_FIXED;
20265 v->di_tv.vval.v_list = &fc.l_varlist;
20266 vim_memset(&fc.l_varlist, 0, sizeof(list_T));
20267 fc.l_varlist.lv_refcount = 99999;
20268 fc.l_varlist.lv_lock = VAR_FIXED;
20271 * Set a:firstline to "firstline" and a:lastline to "lastline".
20272 * Set a:name to named arguments.
20273 * Set a:N to the "..." arguments.
20275 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "firstline",
20276 (varnumber_T)firstline);
20277 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "lastline",
20278 (varnumber_T)lastline);
20279 for (i = 0; i < argcount; ++i)
20281 ai = i - fp->uf_args.ga_len;
20282 if (ai < 0)
20283 /* named argument a:name */
20284 name = FUNCARG(fp, i);
20285 else
20287 /* "..." argument a:1, a:2, etc. */
20288 sprintf((char *)numbuf, "%d", ai + 1);
20289 name = numbuf;
20291 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
20293 v = &fc.fixvar[fixvar_idx++].var;
20294 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20296 else
20298 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
20299 + STRLEN(name)));
20300 if (v == NULL)
20301 break;
20302 v->di_flags = DI_FLAGS_RO;
20304 STRCPY(v->di_key, name);
20305 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
20307 /* Note: the values are copied directly to avoid alloc/free.
20308 * "argvars" must have VAR_FIXED for v_lock. */
20309 v->di_tv = argvars[i];
20310 v->di_tv.v_lock = VAR_FIXED;
20312 if (ai >= 0 && ai < MAX_FUNC_ARGS)
20314 list_append(&fc.l_varlist, &fc.l_listitems[ai]);
20315 fc.l_listitems[ai].li_tv = argvars[i];
20316 fc.l_listitems[ai].li_tv.v_lock = VAR_FIXED;
20320 /* Don't redraw while executing the function. */
20321 ++RedrawingDisabled;
20322 save_sourcing_name = sourcing_name;
20323 save_sourcing_lnum = sourcing_lnum;
20324 sourcing_lnum = 1;
20325 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
20326 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
20327 if (sourcing_name != NULL)
20329 if (save_sourcing_name != NULL
20330 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
20331 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
20332 else
20333 STRCPY(sourcing_name, "function ");
20334 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
20336 if (p_verbose >= 12)
20338 ++no_wait_return;
20339 verbose_enter_scroll();
20341 smsg((char_u *)_("calling %s"), sourcing_name);
20342 if (p_verbose >= 14)
20344 char_u buf[MSG_BUF_LEN];
20345 char_u numbuf2[NUMBUFLEN];
20346 char_u *tofree;
20347 char_u *s;
20349 msg_puts((char_u *)"(");
20350 for (i = 0; i < argcount; ++i)
20352 if (i > 0)
20353 msg_puts((char_u *)", ");
20354 if (argvars[i].v_type == VAR_NUMBER)
20355 msg_outnum((long)argvars[i].vval.v_number);
20356 else
20358 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
20359 if (s != NULL)
20361 trunc_string(s, buf, MSG_BUF_CLEN);
20362 msg_puts(buf);
20363 vim_free(tofree);
20367 msg_puts((char_u *)")");
20369 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20371 verbose_leave_scroll();
20372 --no_wait_return;
20375 #ifdef FEAT_PROFILE
20376 if (do_profiling == PROF_YES)
20378 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
20379 func_do_profile(fp);
20380 if (fp->uf_profiling
20381 || (fc.caller != NULL && &fc.caller->func->uf_profiling))
20383 ++fp->uf_tm_count;
20384 profile_start(&call_start);
20385 profile_zero(&fp->uf_tm_children);
20387 script_prof_save(&wait_start);
20389 #endif
20391 save_current_SID = current_SID;
20392 current_SID = fp->uf_script_ID;
20393 save_did_emsg = did_emsg;
20394 did_emsg = FALSE;
20396 /* call do_cmdline() to execute the lines */
20397 do_cmdline(NULL, get_func_line, (void *)&fc,
20398 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
20400 --RedrawingDisabled;
20402 /* when the function was aborted because of an error, return -1 */
20403 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
20405 clear_tv(rettv);
20406 rettv->v_type = VAR_NUMBER;
20407 rettv->vval.v_number = -1;
20410 #ifdef FEAT_PROFILE
20411 if (do_profiling == PROF_YES && (fp->uf_profiling
20412 || (fc.caller != NULL && &fc.caller->func->uf_profiling)))
20414 profile_end(&call_start);
20415 profile_sub_wait(&wait_start, &call_start);
20416 profile_add(&fp->uf_tm_total, &call_start);
20417 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
20418 if (fc.caller != NULL && &fc.caller->func->uf_profiling)
20420 profile_add(&fc.caller->func->uf_tm_children, &call_start);
20421 profile_add(&fc.caller->func->uf_tml_children, &call_start);
20424 #endif
20426 /* when being verbose, mention the return value */
20427 if (p_verbose >= 12)
20429 ++no_wait_return;
20430 verbose_enter_scroll();
20432 if (aborting())
20433 smsg((char_u *)_("%s aborted"), sourcing_name);
20434 else if (fc.rettv->v_type == VAR_NUMBER)
20435 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
20436 (long)fc.rettv->vval.v_number);
20437 else
20439 char_u buf[MSG_BUF_LEN];
20440 char_u numbuf2[NUMBUFLEN];
20441 char_u *tofree;
20442 char_u *s;
20444 /* The value may be very long. Skip the middle part, so that we
20445 * have some idea how it starts and ends. smsg() would always
20446 * truncate it at the end. */
20447 s = tv2string(fc.rettv, &tofree, numbuf2, 0);
20448 if (s != NULL)
20450 trunc_string(s, buf, MSG_BUF_CLEN);
20451 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
20452 vim_free(tofree);
20455 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20457 verbose_leave_scroll();
20458 --no_wait_return;
20461 vim_free(sourcing_name);
20462 sourcing_name = save_sourcing_name;
20463 sourcing_lnum = save_sourcing_lnum;
20464 current_SID = save_current_SID;
20465 #ifdef FEAT_PROFILE
20466 if (do_profiling == PROF_YES)
20467 script_prof_restore(&wait_start);
20468 #endif
20470 if (p_verbose >= 12 && sourcing_name != NULL)
20472 ++no_wait_return;
20473 verbose_enter_scroll();
20475 smsg((char_u *)_("continuing in %s"), sourcing_name);
20476 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20478 verbose_leave_scroll();
20479 --no_wait_return;
20482 did_emsg |= save_did_emsg;
20483 current_funccal = fc.caller;
20485 /* The a: variables typevals were not alloced, only free the allocated
20486 * variables. */
20487 vars_clear_ext(&fc.l_avars.dv_hashtab, FALSE);
20489 vars_clear(&fc.l_vars.dv_hashtab); /* free all l: variables */
20490 --depth;
20494 * Add a number variable "name" to dict "dp" with value "nr".
20496 static void
20497 add_nr_var(dp, v, name, nr)
20498 dict_T *dp;
20499 dictitem_T *v;
20500 char *name;
20501 varnumber_T nr;
20503 STRCPY(v->di_key, name);
20504 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20505 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
20506 v->di_tv.v_type = VAR_NUMBER;
20507 v->di_tv.v_lock = VAR_FIXED;
20508 v->di_tv.vval.v_number = nr;
20512 * ":return [expr]"
20514 void
20515 ex_return(eap)
20516 exarg_T *eap;
20518 char_u *arg = eap->arg;
20519 typval_T rettv;
20520 int returning = FALSE;
20522 if (current_funccal == NULL)
20524 EMSG(_("E133: :return not inside a function"));
20525 return;
20528 if (eap->skip)
20529 ++emsg_skip;
20531 eap->nextcmd = NULL;
20532 if ((*arg != NUL && *arg != '|' && *arg != '\n')
20533 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
20535 if (!eap->skip)
20536 returning = do_return(eap, FALSE, TRUE, &rettv);
20537 else
20538 clear_tv(&rettv);
20540 /* It's safer to return also on error. */
20541 else if (!eap->skip)
20544 * Return unless the expression evaluation has been cancelled due to an
20545 * aborting error, an interrupt, or an exception.
20547 if (!aborting())
20548 returning = do_return(eap, FALSE, TRUE, NULL);
20551 /* When skipping or the return gets pending, advance to the next command
20552 * in this line (!returning). Otherwise, ignore the rest of the line.
20553 * Following lines will be ignored by get_func_line(). */
20554 if (returning)
20555 eap->nextcmd = NULL;
20556 else if (eap->nextcmd == NULL) /* no argument */
20557 eap->nextcmd = check_nextcmd(arg);
20559 if (eap->skip)
20560 --emsg_skip;
20564 * Return from a function. Possibly makes the return pending. Also called
20565 * for a pending return at the ":endtry" or after returning from an extra
20566 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
20567 * when called due to a ":return" command. "rettv" may point to a typval_T
20568 * with the return rettv. Returns TRUE when the return can be carried out,
20569 * FALSE when the return gets pending.
20572 do_return(eap, reanimate, is_cmd, rettv)
20573 exarg_T *eap;
20574 int reanimate;
20575 int is_cmd;
20576 void *rettv;
20578 int idx;
20579 struct condstack *cstack = eap->cstack;
20581 if (reanimate)
20582 /* Undo the return. */
20583 current_funccal->returned = FALSE;
20586 * Cleanup (and inactivate) conditionals, but stop when a try conditional
20587 * not in its finally clause (which then is to be executed next) is found.
20588 * In this case, make the ":return" pending for execution at the ":endtry".
20589 * Otherwise, return normally.
20591 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
20592 if (idx >= 0)
20594 cstack->cs_pending[idx] = CSTP_RETURN;
20596 if (!is_cmd && !reanimate)
20597 /* A pending return again gets pending. "rettv" points to an
20598 * allocated variable with the rettv of the original ":return"'s
20599 * argument if present or is NULL else. */
20600 cstack->cs_rettv[idx] = rettv;
20601 else
20603 /* When undoing a return in order to make it pending, get the stored
20604 * return rettv. */
20605 if (reanimate)
20606 rettv = current_funccal->rettv;
20608 if (rettv != NULL)
20610 /* Store the value of the pending return. */
20611 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
20612 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
20613 else
20614 EMSG(_(e_outofmem));
20616 else
20617 cstack->cs_rettv[idx] = NULL;
20619 if (reanimate)
20621 /* The pending return value could be overwritten by a ":return"
20622 * without argument in a finally clause; reset the default
20623 * return value. */
20624 current_funccal->rettv->v_type = VAR_NUMBER;
20625 current_funccal->rettv->vval.v_number = 0;
20628 report_make_pending(CSTP_RETURN, rettv);
20630 else
20632 current_funccal->returned = TRUE;
20634 /* If the return is carried out now, store the return value. For
20635 * a return immediately after reanimation, the value is already
20636 * there. */
20637 if (!reanimate && rettv != NULL)
20639 clear_tv(current_funccal->rettv);
20640 *current_funccal->rettv = *(typval_T *)rettv;
20641 if (!is_cmd)
20642 vim_free(rettv);
20646 return idx < 0;
20650 * Free the variable with a pending return value.
20652 void
20653 discard_pending_return(rettv)
20654 void *rettv;
20656 free_tv((typval_T *)rettv);
20660 * Generate a return command for producing the value of "rettv". The result
20661 * is an allocated string. Used by report_pending() for verbose messages.
20663 char_u *
20664 get_return_cmd(rettv)
20665 void *rettv;
20667 char_u *s = NULL;
20668 char_u *tofree = NULL;
20669 char_u numbuf[NUMBUFLEN];
20671 if (rettv != NULL)
20672 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
20673 if (s == NULL)
20674 s = (char_u *)"";
20676 STRCPY(IObuff, ":return ");
20677 STRNCPY(IObuff + 8, s, IOSIZE - 8);
20678 if (STRLEN(s) + 8 >= IOSIZE)
20679 STRCPY(IObuff + IOSIZE - 4, "...");
20680 vim_free(tofree);
20681 return vim_strsave(IObuff);
20685 * Get next function line.
20686 * Called by do_cmdline() to get the next line.
20687 * Returns allocated string, or NULL for end of function.
20689 /* ARGSUSED */
20690 char_u *
20691 get_func_line(c, cookie, indent)
20692 int c; /* not used */
20693 void *cookie;
20694 int indent; /* not used */
20696 funccall_T *fcp = (funccall_T *)cookie;
20697 ufunc_T *fp = fcp->func;
20698 char_u *retval;
20699 garray_T *gap; /* growarray with function lines */
20701 /* If breakpoints have been added/deleted need to check for it. */
20702 if (fcp->dbg_tick != debug_tick)
20704 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
20705 sourcing_lnum);
20706 fcp->dbg_tick = debug_tick;
20708 #ifdef FEAT_PROFILE
20709 if (do_profiling == PROF_YES)
20710 func_line_end(cookie);
20711 #endif
20713 gap = &fp->uf_lines;
20714 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
20715 || fcp->returned)
20716 retval = NULL;
20717 else
20719 /* Skip NULL lines (continuation lines). */
20720 while (fcp->linenr < gap->ga_len
20721 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
20722 ++fcp->linenr;
20723 if (fcp->linenr >= gap->ga_len)
20724 retval = NULL;
20725 else
20727 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
20728 sourcing_lnum = fcp->linenr;
20729 #ifdef FEAT_PROFILE
20730 if (do_profiling == PROF_YES)
20731 func_line_start(cookie);
20732 #endif
20736 /* Did we encounter a breakpoint? */
20737 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
20739 dbg_breakpoint(fp->uf_name, sourcing_lnum);
20740 /* Find next breakpoint. */
20741 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
20742 sourcing_lnum);
20743 fcp->dbg_tick = debug_tick;
20746 return retval;
20749 #if defined(FEAT_PROFILE) || defined(PROTO)
20751 * Called when starting to read a function line.
20752 * "sourcing_lnum" must be correct!
20753 * When skipping lines it may not actually be executed, but we won't find out
20754 * until later and we need to store the time now.
20756 void
20757 func_line_start(cookie)
20758 void *cookie;
20760 funccall_T *fcp = (funccall_T *)cookie;
20761 ufunc_T *fp = fcp->func;
20763 if (fp->uf_profiling && sourcing_lnum >= 1
20764 && sourcing_lnum <= fp->uf_lines.ga_len)
20766 fp->uf_tml_idx = sourcing_lnum - 1;
20767 /* Skip continuation lines. */
20768 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
20769 --fp->uf_tml_idx;
20770 fp->uf_tml_execed = FALSE;
20771 profile_start(&fp->uf_tml_start);
20772 profile_zero(&fp->uf_tml_children);
20773 profile_get_wait(&fp->uf_tml_wait);
20778 * Called when actually executing a function line.
20780 void
20781 func_line_exec(cookie)
20782 void *cookie;
20784 funccall_T *fcp = (funccall_T *)cookie;
20785 ufunc_T *fp = fcp->func;
20787 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
20788 fp->uf_tml_execed = TRUE;
20792 * Called when done with a function line.
20794 void
20795 func_line_end(cookie)
20796 void *cookie;
20798 funccall_T *fcp = (funccall_T *)cookie;
20799 ufunc_T *fp = fcp->func;
20801 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
20803 if (fp->uf_tml_execed)
20805 ++fp->uf_tml_count[fp->uf_tml_idx];
20806 profile_end(&fp->uf_tml_start);
20807 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
20808 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
20809 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
20810 &fp->uf_tml_children);
20812 fp->uf_tml_idx = -1;
20815 #endif
20818 * Return TRUE if the currently active function should be ended, because a
20819 * return was encountered or an error occured. Used inside a ":while".
20822 func_has_ended(cookie)
20823 void *cookie;
20825 funccall_T *fcp = (funccall_T *)cookie;
20827 /* Ignore the "abort" flag if the abortion behavior has been changed due to
20828 * an error inside a try conditional. */
20829 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
20830 || fcp->returned);
20834 * return TRUE if cookie indicates a function which "abort"s on errors.
20837 func_has_abort(cookie)
20838 void *cookie;
20840 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
20843 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
20844 typedef enum
20846 VAR_FLAVOUR_DEFAULT,
20847 VAR_FLAVOUR_SESSION,
20848 VAR_FLAVOUR_VIMINFO
20849 } var_flavour_T;
20851 static var_flavour_T var_flavour __ARGS((char_u *varname));
20853 static var_flavour_T
20854 var_flavour(varname)
20855 char_u *varname;
20857 char_u *p = varname;
20859 if (ASCII_ISUPPER(*p))
20861 while (*(++p))
20862 if (ASCII_ISLOWER(*p))
20863 return VAR_FLAVOUR_SESSION;
20864 return VAR_FLAVOUR_VIMINFO;
20866 else
20867 return VAR_FLAVOUR_DEFAULT;
20869 #endif
20871 #if defined(FEAT_VIMINFO) || defined(PROTO)
20873 * Restore global vars that start with a capital from the viminfo file
20876 read_viminfo_varlist(virp, writing)
20877 vir_T *virp;
20878 int writing;
20880 char_u *tab;
20881 int is_string = FALSE;
20882 typval_T tv;
20884 if (!writing && (find_viminfo_parameter('!') != NULL))
20886 tab = vim_strchr(virp->vir_line + 1, '\t');
20887 if (tab != NULL)
20889 *tab++ = '\0'; /* isolate the variable name */
20890 if (*tab == 'S') /* string var */
20891 is_string = TRUE;
20893 tab = vim_strchr(tab, '\t');
20894 if (tab != NULL)
20896 if (is_string)
20898 tv.v_type = VAR_STRING;
20899 tv.vval.v_string = viminfo_readstring(virp,
20900 (int)(tab - virp->vir_line + 1), TRUE);
20902 else
20904 tv.v_type = VAR_NUMBER;
20905 tv.vval.v_number = atol((char *)tab + 1);
20907 set_var(virp->vir_line + 1, &tv, FALSE);
20908 if (is_string)
20909 vim_free(tv.vval.v_string);
20914 return viminfo_readline(virp);
20918 * Write global vars that start with a capital to the viminfo file
20920 void
20921 write_viminfo_varlist(fp)
20922 FILE *fp;
20924 hashitem_T *hi;
20925 dictitem_T *this_var;
20926 int todo;
20927 char *s;
20928 char_u *p;
20929 char_u *tofree;
20930 char_u numbuf[NUMBUFLEN];
20932 if (find_viminfo_parameter('!') == NULL)
20933 return;
20935 fprintf(fp, _("\n# global variables:\n"));
20937 todo = (int)globvarht.ht_used;
20938 for (hi = globvarht.ht_array; todo > 0; ++hi)
20940 if (!HASHITEM_EMPTY(hi))
20942 --todo;
20943 this_var = HI2DI(hi);
20944 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
20946 switch (this_var->di_tv.v_type)
20948 case VAR_STRING: s = "STR"; break;
20949 case VAR_NUMBER: s = "NUM"; break;
20950 default: continue;
20952 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
20953 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
20954 if (p != NULL)
20955 viminfo_writestring(fp, p);
20956 vim_free(tofree);
20961 #endif
20963 #if defined(FEAT_SESSION) || defined(PROTO)
20965 store_session_globals(fd)
20966 FILE *fd;
20968 hashitem_T *hi;
20969 dictitem_T *this_var;
20970 int todo;
20971 char_u *p, *t;
20973 todo = (int)globvarht.ht_used;
20974 for (hi = globvarht.ht_array; todo > 0; ++hi)
20976 if (!HASHITEM_EMPTY(hi))
20978 --todo;
20979 this_var = HI2DI(hi);
20980 if ((this_var->di_tv.v_type == VAR_NUMBER
20981 || this_var->di_tv.v_type == VAR_STRING)
20982 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
20984 /* Escape special characters with a backslash. Turn a LF and
20985 * CR into \n and \r. */
20986 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
20987 (char_u *)"\\\"\n\r");
20988 if (p == NULL) /* out of memory */
20989 break;
20990 for (t = p; *t != NUL; ++t)
20991 if (*t == '\n')
20992 *t = 'n';
20993 else if (*t == '\r')
20994 *t = 'r';
20995 if ((fprintf(fd, "let %s = %c%s%c",
20996 this_var->di_key,
20997 (this_var->di_tv.v_type == VAR_STRING) ? '"'
20998 : ' ',
21000 (this_var->di_tv.v_type == VAR_STRING) ? '"'
21001 : ' ') < 0)
21002 || put_eol(fd) == FAIL)
21004 vim_free(p);
21005 return FAIL;
21007 vim_free(p);
21011 return OK;
21013 #endif
21016 * Display script name where an item was last set.
21017 * Should only be invoked when 'verbose' is non-zero.
21019 void
21020 last_set_msg(scriptID)
21021 scid_T scriptID;
21023 char_u *p;
21025 if (scriptID != 0)
21027 p = home_replace_save(NULL, get_scriptname(scriptID));
21028 if (p != NULL)
21030 verbose_enter();
21031 MSG_PUTS(_("\n\tLast set from "));
21032 MSG_PUTS(p);
21033 vim_free(p);
21034 verbose_leave();
21039 #endif /* FEAT_EVAL */
21041 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
21044 #ifdef WIN3264
21046 * Functions for ":8" filename modifier: get 8.3 version of a filename.
21048 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
21049 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
21050 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
21053 * Get the short pathname of a file.
21054 * Returns 1 on success. *fnamelen is 0 for nonexistent path.
21056 static int
21057 get_short_pathname(fnamep, bufp, fnamelen)
21058 char_u **fnamep;
21059 char_u **bufp;
21060 int *fnamelen;
21062 int l,len;
21063 char_u *newbuf;
21065 len = *fnamelen;
21067 l = GetShortPathName(*fnamep, *fnamep, len);
21068 if (l > len - 1)
21070 /* If that doesn't work (not enough space), then save the string
21071 * and try again with a new buffer big enough
21073 newbuf = vim_strnsave(*fnamep, l);
21074 if (newbuf == NULL)
21075 return 0;
21077 vim_free(*bufp);
21078 *fnamep = *bufp = newbuf;
21080 l = GetShortPathName(*fnamep,*fnamep,l+1);
21082 /* Really should always succeed, as the buffer is big enough */
21085 *fnamelen = l;
21086 return 1;
21090 * Create a short path name. Returns the length of the buffer it needs.
21091 * Doesn't copy over the end of the buffer passed in.
21093 static int
21094 shortpath_for_invalid_fname(fname, bufp, fnamelen)
21095 char_u **fname;
21096 char_u **bufp;
21097 int *fnamelen;
21099 char_u *s, *p, *pbuf2, *pbuf3;
21100 char_u ch;
21101 int len, len2, plen, slen;
21103 /* Make a copy */
21104 len2 = *fnamelen;
21105 pbuf2 = vim_strnsave(*fname, len2);
21106 pbuf3 = NULL;
21108 s = pbuf2 + len2 - 1; /* Find the end */
21109 slen = 1;
21110 plen = len2;
21112 if (after_pathsep(pbuf2, s + 1))
21114 --s;
21115 ++slen;
21116 --plen;
21121 /* Go back one path-separator */
21122 while (s > pbuf2 && !after_pathsep(pbuf2, s + 1))
21124 --s;
21125 ++slen;
21126 --plen;
21128 if (s <= pbuf2)
21129 break;
21131 /* Remember the character that is about to be splatted */
21132 ch = *s;
21133 *s = 0; /* get_short_pathname requires a null-terminated string */
21135 /* Try it in situ */
21136 p = pbuf2;
21137 if (!get_short_pathname(&p, &pbuf3, &plen))
21139 vim_free(pbuf2);
21140 return -1;
21142 *s = ch; /* Preserve the string */
21143 } while (plen == 0);
21145 if (plen > 0)
21147 /* Remember the length of the new string. */
21148 *fnamelen = len = plen + slen;
21149 vim_free(*bufp);
21150 if (len > len2)
21152 /* If there's not enough space in the currently allocated string,
21153 * then copy it to a buffer big enough.
21155 *fname= *bufp = vim_strnsave(p, len);
21156 if (*fname == NULL)
21157 return -1;
21159 else
21161 /* Transfer pbuf2 to being the main buffer (it's big enough) */
21162 *fname = *bufp = pbuf2;
21163 if (p != pbuf2)
21164 strncpy(*fname, p, plen);
21165 pbuf2 = NULL;
21167 /* Concat the next bit */
21168 strncpy(*fname + plen, s, slen);
21169 (*fname)[len] = '\0';
21171 vim_free(pbuf3);
21172 vim_free(pbuf2);
21173 return 0;
21177 * Get a pathname for a partial path.
21179 static int
21180 shortpath_for_partial(fnamep, bufp, fnamelen)
21181 char_u **fnamep;
21182 char_u **bufp;
21183 int *fnamelen;
21185 int sepcount, len, tflen;
21186 char_u *p;
21187 char_u *pbuf, *tfname;
21188 int hasTilde;
21190 /* Count up the path seperators from the RHS.. so we know which part
21191 * of the path to return.
21193 sepcount = 0;
21194 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
21195 if (vim_ispathsep(*p))
21196 ++sepcount;
21198 /* Need full path first (use expand_env() to remove a "~/") */
21199 hasTilde = (**fnamep == '~');
21200 if (hasTilde)
21201 pbuf = tfname = expand_env_save(*fnamep);
21202 else
21203 pbuf = tfname = FullName_save(*fnamep, FALSE);
21205 len = tflen = (int)STRLEN(tfname);
21207 if (!get_short_pathname(&tfname, &pbuf, &len))
21208 return -1;
21210 if (len == 0)
21212 /* Don't have a valid filename, so shorten the rest of the
21213 * path if we can. This CAN give us invalid 8.3 filenames, but
21214 * there's not a lot of point in guessing what it might be.
21216 len = tflen;
21217 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == -1)
21218 return -1;
21221 /* Count the paths backward to find the beginning of the desired string. */
21222 for (p = tfname + len - 1; p >= tfname; --p)
21224 #ifdef FEAT_MBYTE
21225 if (has_mbyte)
21226 p -= mb_head_off(tfname, p);
21227 #endif
21228 if (vim_ispathsep(*p))
21230 if (sepcount == 0 || (hasTilde && sepcount == 1))
21231 break;
21232 else
21233 sepcount --;
21236 if (hasTilde)
21238 --p;
21239 if (p >= tfname)
21240 *p = '~';
21241 else
21242 return -1;
21244 else
21245 ++p;
21247 /* Copy in the string - p indexes into tfname - allocated at pbuf */
21248 vim_free(*bufp);
21249 *fnamelen = (int)STRLEN(p);
21250 *bufp = pbuf;
21251 *fnamep = p;
21253 return 0;
21255 #endif /* WIN3264 */
21258 * Adjust a filename, according to a string of modifiers.
21259 * *fnamep must be NUL terminated when called. When returning, the length is
21260 * determined by *fnamelen.
21261 * Returns valid flags.
21262 * When there is an error, *fnamep is set to NULL.
21265 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
21266 char_u *src; /* string with modifiers */
21267 int *usedlen; /* characters after src that are used */
21268 char_u **fnamep; /* file name so far */
21269 char_u **bufp; /* buffer for allocated file name or NULL */
21270 int *fnamelen; /* length of fnamep */
21272 int valid = 0;
21273 char_u *tail;
21274 char_u *s, *p, *pbuf;
21275 char_u dirname[MAXPATHL];
21276 int c;
21277 int has_fullname = 0;
21278 #ifdef WIN3264
21279 int has_shortname = 0;
21280 #endif
21282 repeat:
21283 /* ":p" - full path/file_name */
21284 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
21286 has_fullname = 1;
21288 valid |= VALID_PATH;
21289 *usedlen += 2;
21291 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
21292 if ((*fnamep)[0] == '~'
21293 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
21294 && ((*fnamep)[1] == '/'
21295 # ifdef BACKSLASH_IN_FILENAME
21296 || (*fnamep)[1] == '\\'
21297 # endif
21298 || (*fnamep)[1] == NUL)
21300 #endif
21303 *fnamep = expand_env_save(*fnamep);
21304 vim_free(*bufp); /* free any allocated file name */
21305 *bufp = *fnamep;
21306 if (*fnamep == NULL)
21307 return -1;
21310 /* When "/." or "/.." is used: force expansion to get rid of it. */
21311 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
21313 if (vim_ispathsep(*p)
21314 && p[1] == '.'
21315 && (p[2] == NUL
21316 || vim_ispathsep(p[2])
21317 || (p[2] == '.'
21318 && (p[3] == NUL || vim_ispathsep(p[3])))))
21319 break;
21322 /* FullName_save() is slow, don't use it when not needed. */
21323 if (*p != NUL || !vim_isAbsName(*fnamep))
21325 *fnamep = FullName_save(*fnamep, *p != NUL);
21326 vim_free(*bufp); /* free any allocated file name */
21327 *bufp = *fnamep;
21328 if (*fnamep == NULL)
21329 return -1;
21332 /* Append a path separator to a directory. */
21333 if (mch_isdir(*fnamep))
21335 /* Make room for one or two extra characters. */
21336 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
21337 vim_free(*bufp); /* free any allocated file name */
21338 *bufp = *fnamep;
21339 if (*fnamep == NULL)
21340 return -1;
21341 add_pathsep(*fnamep);
21345 /* ":." - path relative to the current directory */
21346 /* ":~" - path relative to the home directory */
21347 /* ":8" - shortname path - postponed till after */
21348 while (src[*usedlen] == ':'
21349 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
21351 *usedlen += 2;
21352 if (c == '8')
21354 #ifdef WIN3264
21355 has_shortname = 1; /* Postpone this. */
21356 #endif
21357 continue;
21359 pbuf = NULL;
21360 /* Need full path first (use expand_env() to remove a "~/") */
21361 if (!has_fullname)
21363 if (c == '.' && **fnamep == '~')
21364 p = pbuf = expand_env_save(*fnamep);
21365 else
21366 p = pbuf = FullName_save(*fnamep, FALSE);
21368 else
21369 p = *fnamep;
21371 has_fullname = 0;
21373 if (p != NULL)
21375 if (c == '.')
21377 mch_dirname(dirname, MAXPATHL);
21378 s = shorten_fname(p, dirname);
21379 if (s != NULL)
21381 *fnamep = s;
21382 if (pbuf != NULL)
21384 vim_free(*bufp); /* free any allocated file name */
21385 *bufp = pbuf;
21386 pbuf = NULL;
21390 else
21392 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
21393 /* Only replace it when it starts with '~' */
21394 if (*dirname == '~')
21396 s = vim_strsave(dirname);
21397 if (s != NULL)
21399 *fnamep = s;
21400 vim_free(*bufp);
21401 *bufp = s;
21405 vim_free(pbuf);
21409 tail = gettail(*fnamep);
21410 *fnamelen = (int)STRLEN(*fnamep);
21412 /* ":h" - head, remove "/file_name", can be repeated */
21413 /* Don't remove the first "/" or "c:\" */
21414 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
21416 valid |= VALID_HEAD;
21417 *usedlen += 2;
21418 s = get_past_head(*fnamep);
21419 while (tail > s && after_pathsep(s, tail))
21420 mb_ptr_back(*fnamep, tail);
21421 *fnamelen = (int)(tail - *fnamep);
21422 #ifdef VMS
21423 if (*fnamelen > 0)
21424 *fnamelen += 1; /* the path separator is part of the path */
21425 #endif
21426 if (*fnamelen == 0)
21428 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
21429 p = vim_strsave((char_u *)".");
21430 if (p == NULL)
21431 return -1;
21432 vim_free(*bufp);
21433 *bufp = *fnamep = tail = p;
21434 *fnamelen = 1;
21436 else
21438 while (tail > s && !after_pathsep(s, tail))
21439 mb_ptr_back(*fnamep, tail);
21443 /* ":8" - shortname */
21444 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
21446 *usedlen += 2;
21447 #ifdef WIN3264
21448 has_shortname = 1;
21449 #endif
21452 #ifdef WIN3264
21453 /* Check shortname after we have done 'heads' and before we do 'tails'
21455 if (has_shortname)
21457 pbuf = NULL;
21458 /* Copy the string if it is shortened by :h */
21459 if (*fnamelen < (int)STRLEN(*fnamep))
21461 p = vim_strnsave(*fnamep, *fnamelen);
21462 if (p == 0)
21463 return -1;
21464 vim_free(*bufp);
21465 *bufp = *fnamep = p;
21468 /* Split into two implementations - makes it easier. First is where
21469 * there isn't a full name already, second is where there is.
21471 if (!has_fullname && !vim_isAbsName(*fnamep))
21473 if (shortpath_for_partial(fnamep, bufp, fnamelen) == -1)
21474 return -1;
21476 else
21478 int l;
21480 /* Simple case, already have the full-name
21481 * Nearly always shorter, so try first time. */
21482 l = *fnamelen;
21483 if (!get_short_pathname(fnamep, bufp, &l))
21484 return -1;
21486 if (l == 0)
21488 /* Couldn't find the filename.. search the paths.
21490 l = *fnamelen;
21491 if (shortpath_for_invalid_fname(fnamep, bufp, &l ) == -1)
21492 return -1;
21494 *fnamelen = l;
21497 #endif /* WIN3264 */
21499 /* ":t" - tail, just the basename */
21500 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
21502 *usedlen += 2;
21503 *fnamelen -= (int)(tail - *fnamep);
21504 *fnamep = tail;
21507 /* ":e" - extension, can be repeated */
21508 /* ":r" - root, without extension, can be repeated */
21509 while (src[*usedlen] == ':'
21510 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
21512 /* find a '.' in the tail:
21513 * - for second :e: before the current fname
21514 * - otherwise: The last '.'
21516 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
21517 s = *fnamep - 2;
21518 else
21519 s = *fnamep + *fnamelen - 1;
21520 for ( ; s > tail; --s)
21521 if (s[0] == '.')
21522 break;
21523 if (src[*usedlen + 1] == 'e') /* :e */
21525 if (s > tail)
21527 *fnamelen += (int)(*fnamep - (s + 1));
21528 *fnamep = s + 1;
21529 #ifdef VMS
21530 /* cut version from the extension */
21531 s = *fnamep + *fnamelen - 1;
21532 for ( ; s > *fnamep; --s)
21533 if (s[0] == ';')
21534 break;
21535 if (s > *fnamep)
21536 *fnamelen = s - *fnamep;
21537 #endif
21539 else if (*fnamep <= tail)
21540 *fnamelen = 0;
21542 else /* :r */
21544 if (s > tail) /* remove one extension */
21545 *fnamelen = (int)(s - *fnamep);
21547 *usedlen += 2;
21550 /* ":s?pat?foo?" - substitute */
21551 /* ":gs?pat?foo?" - global substitute */
21552 if (src[*usedlen] == ':'
21553 && (src[*usedlen + 1] == 's'
21554 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
21556 char_u *str;
21557 char_u *pat;
21558 char_u *sub;
21559 int sep;
21560 char_u *flags;
21561 int didit = FALSE;
21563 flags = (char_u *)"";
21564 s = src + *usedlen + 2;
21565 if (src[*usedlen + 1] == 'g')
21567 flags = (char_u *)"g";
21568 ++s;
21571 sep = *s++;
21572 if (sep)
21574 /* find end of pattern */
21575 p = vim_strchr(s, sep);
21576 if (p != NULL)
21578 pat = vim_strnsave(s, (int)(p - s));
21579 if (pat != NULL)
21581 s = p + 1;
21582 /* find end of substitution */
21583 p = vim_strchr(s, sep);
21584 if (p != NULL)
21586 sub = vim_strnsave(s, (int)(p - s));
21587 str = vim_strnsave(*fnamep, *fnamelen);
21588 if (sub != NULL && str != NULL)
21590 *usedlen = (int)(p + 1 - src);
21591 s = do_string_sub(str, pat, sub, flags);
21592 if (s != NULL)
21594 *fnamep = s;
21595 *fnamelen = (int)STRLEN(s);
21596 vim_free(*bufp);
21597 *bufp = s;
21598 didit = TRUE;
21601 vim_free(sub);
21602 vim_free(str);
21604 vim_free(pat);
21607 /* after using ":s", repeat all the modifiers */
21608 if (didit)
21609 goto repeat;
21613 return valid;
21617 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
21618 * "flags" can be "g" to do a global substitute.
21619 * Returns an allocated string, NULL for error.
21621 char_u *
21622 do_string_sub(str, pat, sub, flags)
21623 char_u *str;
21624 char_u *pat;
21625 char_u *sub;
21626 char_u *flags;
21628 int sublen;
21629 regmatch_T regmatch;
21630 int i;
21631 int do_all;
21632 char_u *tail;
21633 garray_T ga;
21634 char_u *ret;
21635 char_u *save_cpo;
21637 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
21638 save_cpo = p_cpo;
21639 p_cpo = (char_u *)"";
21641 ga_init2(&ga, 1, 200);
21643 do_all = (flags[0] == 'g');
21645 regmatch.rm_ic = p_ic;
21646 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
21647 if (regmatch.regprog != NULL)
21649 tail = str;
21650 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
21653 * Get some space for a temporary buffer to do the substitution
21654 * into. It will contain:
21655 * - The text up to where the match is.
21656 * - The substituted text.
21657 * - The text after the match.
21659 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
21660 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
21661 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
21663 ga_clear(&ga);
21664 break;
21667 /* copy the text up to where the match is */
21668 i = (int)(regmatch.startp[0] - tail);
21669 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
21670 /* add the substituted text */
21671 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
21672 + ga.ga_len + i, TRUE, TRUE, FALSE);
21673 ga.ga_len += i + sublen - 1;
21674 /* avoid getting stuck on a match with an empty string */
21675 if (tail == regmatch.endp[0])
21677 if (*tail == NUL)
21678 break;
21679 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
21680 ++ga.ga_len;
21682 else
21684 tail = regmatch.endp[0];
21685 if (*tail == NUL)
21686 break;
21688 if (!do_all)
21689 break;
21692 if (ga.ga_data != NULL)
21693 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
21695 vim_free(regmatch.regprog);
21698 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
21699 ga_clear(&ga);
21700 p_cpo = save_cpo;
21702 return ret;
21705 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */