Basic plugin architecture
[MacVim.git] / src / eval.c
blobbecd2938c581cc7446f61a1b8ad59c6afe424b22
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_fnameescape __ARGS((typval_T *argvars, typval_T *rettv));
511 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
513 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
514 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
516 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
517 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
520 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
521 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
523 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
524 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
525 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
526 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
528 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
529 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
531 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
532 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
533 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
534 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
535 static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv));
536 static void f_getpid __ARGS((typval_T *argvars, typval_T *rettv));
537 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
542 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
546 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
547 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
548 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
549 static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
551 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
552 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
590 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
591 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
592 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
593 #ifdef vim_mkdir
594 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
595 #endif
596 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
603 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
604 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
605 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
606 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
607 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
608 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
609 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
610 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
611 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
618 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
619 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
620 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
621 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
622 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
623 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
624 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
625 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
626 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
627 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
628 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
629 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
630 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
631 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
632 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
633 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
634 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
635 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
636 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
637 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
638 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
639 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
640 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
641 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
642 #ifdef HAVE_STRFTIME
643 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
644 #endif
645 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
646 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
647 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
648 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
649 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
650 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
651 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
652 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
653 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
654 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
655 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
656 static void f_synstack __ARGS((typval_T *argvars, typval_T *rettv));
657 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
667 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
668 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
669 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
670 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
671 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
672 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
673 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
674 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
675 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
676 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
677 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
678 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
679 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
680 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
681 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
683 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
684 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
685 static int get_env_len __ARGS((char_u **arg));
686 static int get_id_len __ARGS((char_u **arg));
687 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
688 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
689 #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */
690 #define FNE_CHECK_START 2 /* find_name_end(): check name starts with
691 valid character */
692 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
693 static int eval_isnamec __ARGS((int c));
694 static int eval_isnamec1 __ARGS((int c));
695 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
696 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
697 static typval_T *alloc_tv __ARGS((void));
698 static typval_T *alloc_string_tv __ARGS((char_u *string));
699 static void init_tv __ARGS((typval_T *varp));
700 static long get_tv_number __ARGS((typval_T *varp));
701 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
702 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
703 static char_u *get_tv_string __ARGS((typval_T *varp));
704 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
705 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
706 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
707 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
708 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
709 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
710 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
711 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
712 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
713 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
714 static int var_check_ro __ARGS((int flags, char_u *name));
715 static int var_check_fixed __ARGS((int flags, char_u *name));
716 static int tv_check_lock __ARGS((int lock, char_u *name));
717 static void copy_tv __ARGS((typval_T *from, typval_T *to));
718 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
719 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
720 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
721 static int eval_fname_script __ARGS((char_u *p));
722 static int eval_fname_sid __ARGS((char_u *p));
723 static void list_func_head __ARGS((ufunc_T *fp, int indent));
724 static ufunc_T *find_func __ARGS((char_u *name));
725 static int function_exists __ARGS((char_u *name));
726 static int builtin_function __ARGS((char_u *name));
727 #ifdef FEAT_PROFILE
728 static void func_do_profile __ARGS((ufunc_T *fp));
729 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
730 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
731 static int
732 # ifdef __BORLANDC__
733 _RTLENTRYF
734 # endif
735 prof_total_cmp __ARGS((const void *s1, const void *s2));
736 static int
737 # ifdef __BORLANDC__
738 _RTLENTRYF
739 # endif
740 prof_self_cmp __ARGS((const void *s1, const void *s2));
741 #endif
742 static int script_autoload __ARGS((char_u *name, int reload));
743 static char_u *autoload_name __ARGS((char_u *name));
744 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
745 static void func_free __ARGS((ufunc_T *fp));
746 static void func_unref __ARGS((char_u *name));
747 static void func_ref __ARGS((char_u *name));
748 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));
749 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
750 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
751 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
752 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
753 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
754 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
756 /* Character used as separated in autoload function/variable names. */
757 #define AUTOLOAD_CHAR '#'
760 * Initialize the global and v: variables.
762 void
763 eval_init()
765 int i;
766 struct vimvar *p;
768 init_var_dict(&globvardict, &globvars_var);
769 init_var_dict(&vimvardict, &vimvars_var);
770 hash_init(&compat_hashtab);
771 hash_init(&func_hashtab);
773 for (i = 0; i < VV_LEN; ++i)
775 p = &vimvars[i];
776 STRCPY(p->vv_di.di_key, p->vv_name);
777 if (p->vv_flags & VV_RO)
778 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
779 else if (p->vv_flags & VV_RO_SBX)
780 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
781 else
782 p->vv_di.di_flags = DI_FLAGS_FIX;
784 /* add to v: scope dict, unless the value is not always available */
785 if (p->vv_type != VAR_UNKNOWN)
786 hash_add(&vimvarht, p->vv_di.di_key);
787 if (p->vv_flags & VV_COMPAT)
788 /* add to compat scope dict */
789 hash_add(&compat_hashtab, p->vv_di.di_key);
793 #if defined(EXITFREE) || defined(PROTO)
794 void
795 eval_clear()
797 int i;
798 struct vimvar *p;
800 for (i = 0; i < VV_LEN; ++i)
802 p = &vimvars[i];
803 if (p->vv_di.di_tv.v_type == VAR_STRING)
805 vim_free(p->vv_di.di_tv.vval.v_string);
806 p->vv_di.di_tv.vval.v_string = NULL;
809 hash_clear(&vimvarht);
810 hash_clear(&compat_hashtab);
812 /* script-local variables */
813 for (i = 1; i <= ga_scripts.ga_len; ++i)
814 vars_clear(&SCRIPT_VARS(i));
815 ga_clear(&ga_scripts);
816 free_scriptnames();
818 /* global variables */
819 vars_clear(&globvarht);
821 /* functions */
822 free_all_functions();
823 hash_clear(&func_hashtab);
825 /* autoloaded script names */
826 ga_clear_strings(&ga_loaded);
828 /* unreferenced lists and dicts */
829 (void)garbage_collect();
831 #endif
834 * Return the name of the executed function.
836 char_u *
837 func_name(cookie)
838 void *cookie;
840 return ((funccall_T *)cookie)->func->uf_name;
844 * Return the address holding the next breakpoint line for a funccall cookie.
846 linenr_T *
847 func_breakpoint(cookie)
848 void *cookie;
850 return &((funccall_T *)cookie)->breakpoint;
854 * Return the address holding the debug tick for a funccall cookie.
856 int *
857 func_dbg_tick(cookie)
858 void *cookie;
860 return &((funccall_T *)cookie)->dbg_tick;
864 * Return the nesting level for a funccall cookie.
867 func_level(cookie)
868 void *cookie;
870 return ((funccall_T *)cookie)->level;
873 /* pointer to funccal for currently active function */
874 funccall_T *current_funccal = NULL;
877 * Return TRUE when a function was ended by a ":return" command.
880 current_func_returned()
882 return current_funccal->returned;
887 * Set an internal variable to a string value. Creates the variable if it does
888 * not already exist.
890 void
891 set_internal_string_var(name, value)
892 char_u *name;
893 char_u *value;
895 char_u *val;
896 typval_T *tvp;
898 val = vim_strsave(value);
899 if (val != NULL)
901 tvp = alloc_string_tv(val);
902 if (tvp != NULL)
904 set_var(name, tvp, FALSE);
905 free_tv(tvp);
910 static lval_T *redir_lval = NULL;
911 static garray_T redir_ga; /* only valid when redir_lval is not NULL */
912 static char_u *redir_endp = NULL;
913 static char_u *redir_varname = NULL;
916 * Start recording command output to a variable
917 * Returns OK if successfully completed the setup. FAIL otherwise.
920 var_redir_start(name, append)
921 char_u *name;
922 int append; /* append to an existing variable */
924 int save_emsg;
925 int err;
926 typval_T tv;
928 /* Make sure a valid variable name is specified */
929 if (!eval_isnamec1(*name))
931 EMSG(_(e_invarg));
932 return FAIL;
935 redir_varname = vim_strsave(name);
936 if (redir_varname == NULL)
937 return FAIL;
939 redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
940 if (redir_lval == NULL)
942 var_redir_stop();
943 return FAIL;
946 /* The output is stored in growarray "redir_ga" until redirection ends. */
947 ga_init2(&redir_ga, (int)sizeof(char), 500);
949 /* Parse the variable name (can be a dict or list entry). */
950 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
951 FNE_CHECK_START);
952 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
954 if (redir_endp != NULL && *redir_endp != NUL)
955 /* Trailing characters are present after the variable name */
956 EMSG(_(e_trailing));
957 else
958 EMSG(_(e_invarg));
959 var_redir_stop();
960 return FAIL;
963 /* check if we can write to the variable: set it to or append an empty
964 * string */
965 save_emsg = did_emsg;
966 did_emsg = FALSE;
967 tv.v_type = VAR_STRING;
968 tv.vval.v_string = (char_u *)"";
969 if (append)
970 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
971 else
972 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
973 err = did_emsg;
974 did_emsg |= save_emsg;
975 if (err)
977 var_redir_stop();
978 return FAIL;
980 if (redir_lval->ll_newkey != NULL)
982 /* Dictionary item was created, don't do it again. */
983 vim_free(redir_lval->ll_newkey);
984 redir_lval->ll_newkey = NULL;
987 return OK;
991 * Append "value[value_len]" to the variable set by var_redir_start().
992 * The actual appending is postponed until redirection ends, because the value
993 * appended may in fact be the string we write to, changing it may cause freed
994 * memory to be used:
995 * :redir => foo
996 * :let foo
997 * :redir END
999 void
1000 var_redir_str(value, value_len)
1001 char_u *value;
1002 int value_len;
1004 int len;
1006 if (redir_lval == NULL)
1007 return;
1009 if (value_len == -1)
1010 len = (int)STRLEN(value); /* Append the entire string */
1011 else
1012 len = value_len; /* Append only "value_len" characters */
1014 if (ga_grow(&redir_ga, len) == OK)
1016 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1017 redir_ga.ga_len += len;
1019 else
1020 var_redir_stop();
1024 * Stop redirecting command output to a variable.
1026 void
1027 var_redir_stop()
1029 typval_T tv;
1031 if (redir_lval != NULL)
1033 /* Append the trailing NUL. */
1034 ga_append(&redir_ga, NUL);
1036 /* Assign the text to the variable. */
1037 tv.v_type = VAR_STRING;
1038 tv.vval.v_string = redir_ga.ga_data;
1039 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1040 vim_free(tv.vval.v_string);
1042 clear_lval(redir_lval);
1043 vim_free(redir_lval);
1044 redir_lval = NULL;
1046 vim_free(redir_varname);
1047 redir_varname = NULL;
1050 # if defined(FEAT_MBYTE) || defined(PROTO)
1052 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1053 char_u *enc_from;
1054 char_u *enc_to;
1055 char_u *fname_from;
1056 char_u *fname_to;
1058 int err = FALSE;
1060 set_vim_var_string(VV_CC_FROM, enc_from, -1);
1061 set_vim_var_string(VV_CC_TO, enc_to, -1);
1062 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1063 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1064 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1065 err = TRUE;
1066 set_vim_var_string(VV_CC_FROM, NULL, -1);
1067 set_vim_var_string(VV_CC_TO, NULL, -1);
1068 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1069 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1071 if (err)
1072 return FAIL;
1073 return OK;
1075 # endif
1077 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1079 eval_printexpr(fname, args)
1080 char_u *fname;
1081 char_u *args;
1083 int err = FALSE;
1085 set_vim_var_string(VV_FNAME_IN, fname, -1);
1086 set_vim_var_string(VV_CMDARG, args, -1);
1087 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1088 err = TRUE;
1089 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1090 set_vim_var_string(VV_CMDARG, NULL, -1);
1092 if (err)
1094 mch_remove(fname);
1095 return FAIL;
1097 return OK;
1099 # endif
1101 # if defined(FEAT_DIFF) || defined(PROTO)
1102 void
1103 eval_diff(origfile, newfile, outfile)
1104 char_u *origfile;
1105 char_u *newfile;
1106 char_u *outfile;
1108 int err = FALSE;
1110 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1111 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1112 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1113 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1114 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1115 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1116 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1119 void
1120 eval_patch(origfile, difffile, outfile)
1121 char_u *origfile;
1122 char_u *difffile;
1123 char_u *outfile;
1125 int err;
1127 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1128 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1129 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1130 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1131 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1132 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1133 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1135 # endif
1138 * Top level evaluation function, returning a boolean.
1139 * Sets "error" to TRUE if there was an error.
1140 * Return TRUE or FALSE.
1143 eval_to_bool(arg, error, nextcmd, skip)
1144 char_u *arg;
1145 int *error;
1146 char_u **nextcmd;
1147 int skip; /* only parse, don't execute */
1149 typval_T tv;
1150 int retval = FALSE;
1152 if (skip)
1153 ++emsg_skip;
1154 if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1155 *error = TRUE;
1156 else
1158 *error = FALSE;
1159 if (!skip)
1161 retval = (get_tv_number_chk(&tv, error) != 0);
1162 clear_tv(&tv);
1165 if (skip)
1166 --emsg_skip;
1168 return retval;
1172 * Top level evaluation function, returning a string. If "skip" is TRUE,
1173 * only parsing to "nextcmd" is done, without reporting errors. Return
1174 * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1176 char_u *
1177 eval_to_string_skip(arg, nextcmd, skip)
1178 char_u *arg;
1179 char_u **nextcmd;
1180 int skip; /* only parse, don't execute */
1182 typval_T tv;
1183 char_u *retval;
1185 if (skip)
1186 ++emsg_skip;
1187 if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1188 retval = NULL;
1189 else
1191 retval = vim_strsave(get_tv_string(&tv));
1192 clear_tv(&tv);
1194 if (skip)
1195 --emsg_skip;
1197 return retval;
1201 * Skip over an expression at "*pp".
1202 * Return FAIL for an error, OK otherwise.
1205 skip_expr(pp)
1206 char_u **pp;
1208 typval_T rettv;
1210 *pp = skipwhite(*pp);
1211 return eval1(pp, &rettv, FALSE);
1215 * Top level evaluation function, returning a string.
1216 * Return pointer to allocated memory, or NULL for failure.
1218 char_u *
1219 eval_to_string(arg, nextcmd, dolist)
1220 char_u *arg;
1221 char_u **nextcmd;
1222 int dolist; /* turn List into sequence of lines */
1224 typval_T tv;
1225 char_u *retval;
1226 garray_T ga;
1228 if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1229 retval = NULL;
1230 else
1232 if (dolist && tv.v_type == VAR_LIST)
1234 ga_init2(&ga, (int)sizeof(char), 80);
1235 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1236 ga_append(&ga, NUL);
1237 retval = (char_u *)ga.ga_data;
1239 else
1240 retval = vim_strsave(get_tv_string(&tv));
1241 clear_tv(&tv);
1244 return retval;
1248 * Call eval_to_string() without using current local variables and using
1249 * textlock. When "use_sandbox" is TRUE use the sandbox.
1251 char_u *
1252 eval_to_string_safe(arg, nextcmd, use_sandbox)
1253 char_u *arg;
1254 char_u **nextcmd;
1255 int use_sandbox;
1257 char_u *retval;
1258 void *save_funccalp;
1260 save_funccalp = save_funccal();
1261 if (use_sandbox)
1262 ++sandbox;
1263 ++textlock;
1264 retval = eval_to_string(arg, nextcmd, FALSE);
1265 if (use_sandbox)
1266 --sandbox;
1267 --textlock;
1268 restore_funccal(save_funccalp);
1269 return retval;
1273 * Top level evaluation function, returning a number.
1274 * Evaluates "expr" silently.
1275 * Returns -1 for an error.
1278 eval_to_number(expr)
1279 char_u *expr;
1281 typval_T rettv;
1282 int retval;
1283 char_u *p = skipwhite(expr);
1285 ++emsg_off;
1287 if (eval1(&p, &rettv, TRUE) == FAIL)
1288 retval = -1;
1289 else
1291 retval = get_tv_number_chk(&rettv, NULL);
1292 clear_tv(&rettv);
1294 --emsg_off;
1296 return retval;
1300 * Prepare v: variable "idx" to be used.
1301 * Save the current typeval in "save_tv".
1302 * When not used yet add the variable to the v: hashtable.
1304 static void
1305 prepare_vimvar(idx, save_tv)
1306 int idx;
1307 typval_T *save_tv;
1309 *save_tv = vimvars[idx].vv_tv;
1310 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1311 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1315 * Restore v: variable "idx" to typeval "save_tv".
1316 * When no longer defined, remove the variable from the v: hashtable.
1318 static void
1319 restore_vimvar(idx, save_tv)
1320 int idx;
1321 typval_T *save_tv;
1323 hashitem_T *hi;
1325 vimvars[idx].vv_tv = *save_tv;
1326 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1328 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1329 if (HASHITEM_EMPTY(hi))
1330 EMSG2(_(e_intern2), "restore_vimvar()");
1331 else
1332 hash_remove(&vimvarht, hi);
1336 #if defined(FEAT_SPELL) || defined(PROTO)
1338 * Evaluate an expression to a list with suggestions.
1339 * For the "expr:" part of 'spellsuggest'.
1341 list_T *
1342 eval_spell_expr(badword, expr)
1343 char_u *badword;
1344 char_u *expr;
1346 typval_T save_val;
1347 typval_T rettv;
1348 list_T *list = NULL;
1349 char_u *p = skipwhite(expr);
1351 /* Set "v:val" to the bad word. */
1352 prepare_vimvar(VV_VAL, &save_val);
1353 vimvars[VV_VAL].vv_type = VAR_STRING;
1354 vimvars[VV_VAL].vv_str = badword;
1355 if (p_verbose == 0)
1356 ++emsg_off;
1358 if (eval1(&p, &rettv, TRUE) == OK)
1360 if (rettv.v_type != VAR_LIST)
1361 clear_tv(&rettv);
1362 else
1363 list = rettv.vval.v_list;
1366 if (p_verbose == 0)
1367 --emsg_off;
1368 restore_vimvar(VV_VAL, &save_val);
1370 return list;
1374 * "list" is supposed to contain two items: a word and a number. Return the
1375 * word in "pp" and the number as the return value.
1376 * Return -1 if anything isn't right.
1377 * Used to get the good word and score from the eval_spell_expr() result.
1380 get_spellword(list, pp)
1381 list_T *list;
1382 char_u **pp;
1384 listitem_T *li;
1386 li = list->lv_first;
1387 if (li == NULL)
1388 return -1;
1389 *pp = get_tv_string(&li->li_tv);
1391 li = li->li_next;
1392 if (li == NULL)
1393 return -1;
1394 return get_tv_number(&li->li_tv);
1396 #endif
1399 * Top level evaluation function.
1400 * Returns an allocated typval_T with the result.
1401 * Returns NULL when there is an error.
1403 typval_T *
1404 eval_expr(arg, nextcmd)
1405 char_u *arg;
1406 char_u **nextcmd;
1408 typval_T *tv;
1410 tv = (typval_T *)alloc(sizeof(typval_T));
1411 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1413 vim_free(tv);
1414 tv = NULL;
1417 return tv;
1421 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1422 || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1424 * Call some vimL function and return the result in "*rettv".
1425 * Uses argv[argc] for the function arguments.
1426 * Returns OK or FAIL.
1428 static int
1429 call_vim_function(func, argc, argv, safe, rettv)
1430 char_u *func;
1431 int argc;
1432 char_u **argv;
1433 int safe; /* use the sandbox */
1434 typval_T *rettv;
1436 typval_T *argvars;
1437 long n;
1438 int len;
1439 int i;
1440 int doesrange;
1441 void *save_funccalp = NULL;
1442 int ret;
1444 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1445 if (argvars == NULL)
1446 return FAIL;
1448 for (i = 0; i < argc; i++)
1450 /* Pass a NULL or empty argument as an empty string */
1451 if (argv[i] == NULL || *argv[i] == NUL)
1453 argvars[i].v_type = VAR_STRING;
1454 argvars[i].vval.v_string = (char_u *)"";
1455 continue;
1458 /* Recognize a number argument, the others must be strings. */
1459 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1460 if (len != 0 && len == (int)STRLEN(argv[i]))
1462 argvars[i].v_type = VAR_NUMBER;
1463 argvars[i].vval.v_number = n;
1465 else
1467 argvars[i].v_type = VAR_STRING;
1468 argvars[i].vval.v_string = argv[i];
1472 if (safe)
1474 save_funccalp = save_funccal();
1475 ++sandbox;
1478 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1479 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1480 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1481 &doesrange, TRUE, NULL);
1482 if (safe)
1484 --sandbox;
1485 restore_funccal(save_funccalp);
1487 vim_free(argvars);
1489 if (ret == FAIL)
1490 clear_tv(rettv);
1492 return ret;
1495 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1497 * Call vimL function "func" and return the result as a string.
1498 * Returns NULL when calling the function fails.
1499 * Uses argv[argc] for the function arguments.
1501 void *
1502 call_func_retstr(func, argc, argv, safe)
1503 char_u *func;
1504 int argc;
1505 char_u **argv;
1506 int safe; /* use the sandbox */
1508 typval_T rettv;
1509 char_u *retval;
1511 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1512 return NULL;
1514 retval = vim_strsave(get_tv_string(&rettv));
1515 clear_tv(&rettv);
1516 return retval;
1518 # endif
1520 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1522 * Call vimL function "func" and return the result as a number.
1523 * Returns -1 when calling the function fails.
1524 * Uses argv[argc] for the function arguments.
1526 long
1527 call_func_retnr(func, argc, argv, safe)
1528 char_u *func;
1529 int argc;
1530 char_u **argv;
1531 int safe; /* use the sandbox */
1533 typval_T rettv;
1534 long retval;
1536 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1537 return -1;
1539 retval = get_tv_number_chk(&rettv, NULL);
1540 clear_tv(&rettv);
1541 return retval;
1543 # endif
1546 * Call vimL function "func" and return the result as a list
1547 * Uses argv[argc] for the function arguments.
1549 void *
1550 call_func_retlist(func, argc, argv, safe)
1551 char_u *func;
1552 int argc;
1553 char_u **argv;
1554 int safe; /* use the sandbox */
1556 typval_T rettv;
1558 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1559 return NULL;
1561 if (rettv.v_type != VAR_LIST)
1563 clear_tv(&rettv);
1564 return NULL;
1567 return rettv.vval.v_list;
1569 #endif
1573 * Save the current function call pointer, and set it to NULL.
1574 * Used when executing autocommands and for ":source".
1576 void *
1577 save_funccal()
1579 funccall_T *fc = current_funccal;
1581 current_funccal = NULL;
1582 return (void *)fc;
1585 void
1586 restore_funccal(vfc)
1587 void *vfc;
1589 funccall_T *fc = (funccall_T *)vfc;
1591 current_funccal = fc;
1594 #if defined(FEAT_PROFILE) || defined(PROTO)
1596 * Prepare profiling for entering a child or something else that is not
1597 * counted for the script/function itself.
1598 * Should always be called in pair with prof_child_exit().
1600 void
1601 prof_child_enter(tm)
1602 proftime_T *tm; /* place to store waittime */
1604 funccall_T *fc = current_funccal;
1606 if (fc != NULL && fc->func->uf_profiling)
1607 profile_start(&fc->prof_child);
1608 script_prof_save(tm);
1612 * Take care of time spent in a child.
1613 * Should always be called after prof_child_enter().
1615 void
1616 prof_child_exit(tm)
1617 proftime_T *tm; /* where waittime was stored */
1619 funccall_T *fc = current_funccal;
1621 if (fc != NULL && fc->func->uf_profiling)
1623 profile_end(&fc->prof_child);
1624 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1625 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1626 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1628 script_prof_restore(tm);
1630 #endif
1633 #ifdef FEAT_FOLDING
1635 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1636 * it in "*cp". Doesn't give error messages.
1639 eval_foldexpr(arg, cp)
1640 char_u *arg;
1641 int *cp;
1643 typval_T tv;
1644 int retval;
1645 char_u *s;
1646 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1647 OPT_LOCAL);
1649 ++emsg_off;
1650 if (use_sandbox)
1651 ++sandbox;
1652 ++textlock;
1653 *cp = NUL;
1654 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1655 retval = 0;
1656 else
1658 /* If the result is a number, just return the number. */
1659 if (tv.v_type == VAR_NUMBER)
1660 retval = tv.vval.v_number;
1661 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1662 retval = 0;
1663 else
1665 /* If the result is a string, check if there is a non-digit before
1666 * the number. */
1667 s = tv.vval.v_string;
1668 if (!VIM_ISDIGIT(*s) && *s != '-')
1669 *cp = *s++;
1670 retval = atol((char *)s);
1672 clear_tv(&tv);
1674 --emsg_off;
1675 if (use_sandbox)
1676 --sandbox;
1677 --textlock;
1679 return retval;
1681 #endif
1684 * ":let" list all variable values
1685 * ":let var1 var2" list variable values
1686 * ":let var = expr" assignment command.
1687 * ":let var += expr" assignment command.
1688 * ":let var -= expr" assignment command.
1689 * ":let var .= expr" assignment command.
1690 * ":let [var1, var2] = expr" unpack list.
1692 void
1693 ex_let(eap)
1694 exarg_T *eap;
1696 char_u *arg = eap->arg;
1697 char_u *expr = NULL;
1698 typval_T rettv;
1699 int i;
1700 int var_count = 0;
1701 int semicolon = 0;
1702 char_u op[2];
1703 char_u *argend;
1704 int first = TRUE;
1706 argend = skip_var_list(arg, &var_count, &semicolon);
1707 if (argend == NULL)
1708 return;
1709 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1710 --argend;
1711 expr = vim_strchr(argend, '=');
1712 if (expr == NULL)
1715 * ":let" without "=": list variables
1717 if (*arg == '[')
1718 EMSG(_(e_invarg));
1719 else if (!ends_excmd(*arg))
1720 /* ":let var1 var2" */
1721 arg = list_arg_vars(eap, arg, &first);
1722 else if (!eap->skip)
1724 /* ":let" */
1725 list_glob_vars(&first);
1726 list_buf_vars(&first);
1727 list_win_vars(&first);
1728 #ifdef FEAT_WINDOWS
1729 list_tab_vars(&first);
1730 #endif
1731 list_script_vars(&first);
1732 list_func_vars(&first);
1733 list_vim_vars(&first);
1735 eap->nextcmd = check_nextcmd(arg);
1737 else
1739 op[0] = '=';
1740 op[1] = NUL;
1741 if (expr > argend)
1743 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1744 op[0] = expr[-1]; /* +=, -= or .= */
1746 expr = skipwhite(expr + 1);
1748 if (eap->skip)
1749 ++emsg_skip;
1750 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1751 if (eap->skip)
1753 if (i != FAIL)
1754 clear_tv(&rettv);
1755 --emsg_skip;
1757 else if (i != FAIL)
1759 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1760 op);
1761 clear_tv(&rettv);
1767 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1768 * Handles both "var" with any type and "[var, var; var]" with a list type.
1769 * When "nextchars" is not NULL it points to a string with characters that
1770 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1771 * or concatenate.
1772 * Returns OK or FAIL;
1774 static int
1775 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1776 char_u *arg_start;
1777 typval_T *tv;
1778 int copy; /* copy values from "tv", don't move */
1779 int semicolon; /* from skip_var_list() */
1780 int var_count; /* from skip_var_list() */
1781 char_u *nextchars;
1783 char_u *arg = arg_start;
1784 list_T *l;
1785 int i;
1786 listitem_T *item;
1787 typval_T ltv;
1789 if (*arg != '[')
1792 * ":let var = expr" or ":for var in list"
1794 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1795 return FAIL;
1796 return OK;
1800 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1802 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1804 EMSG(_(e_listreq));
1805 return FAIL;
1808 i = list_len(l);
1809 if (semicolon == 0 && var_count < i)
1811 EMSG(_("E687: Less targets than List items"));
1812 return FAIL;
1814 if (var_count - semicolon > i)
1816 EMSG(_("E688: More targets than List items"));
1817 return FAIL;
1820 item = l->lv_first;
1821 while (*arg != ']')
1823 arg = skipwhite(arg + 1);
1824 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1825 item = item->li_next;
1826 if (arg == NULL)
1827 return FAIL;
1829 arg = skipwhite(arg);
1830 if (*arg == ';')
1832 /* Put the rest of the list (may be empty) in the var after ';'.
1833 * Create a new list for this. */
1834 l = list_alloc();
1835 if (l == NULL)
1836 return FAIL;
1837 while (item != NULL)
1839 list_append_tv(l, &item->li_tv);
1840 item = item->li_next;
1843 ltv.v_type = VAR_LIST;
1844 ltv.v_lock = 0;
1845 ltv.vval.v_list = l;
1846 l->lv_refcount = 1;
1848 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1849 (char_u *)"]", nextchars);
1850 clear_tv(&ltv);
1851 if (arg == NULL)
1852 return FAIL;
1853 break;
1855 else if (*arg != ',' && *arg != ']')
1857 EMSG2(_(e_intern2), "ex_let_vars()");
1858 return FAIL;
1862 return OK;
1866 * Skip over assignable variable "var" or list of variables "[var, var]".
1867 * Used for ":let varvar = expr" and ":for varvar in expr".
1868 * For "[var, var]" increment "*var_count" for each variable.
1869 * for "[var, var; var]" set "semicolon".
1870 * Return NULL for an error.
1872 static char_u *
1873 skip_var_list(arg, var_count, semicolon)
1874 char_u *arg;
1875 int *var_count;
1876 int *semicolon;
1878 char_u *p, *s;
1880 if (*arg == '[')
1882 /* "[var, var]": find the matching ']'. */
1883 p = arg;
1884 for (;;)
1886 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
1887 s = skip_var_one(p);
1888 if (s == p)
1890 EMSG2(_(e_invarg2), p);
1891 return NULL;
1893 ++*var_count;
1895 p = skipwhite(s);
1896 if (*p == ']')
1897 break;
1898 else if (*p == ';')
1900 if (*semicolon == 1)
1902 EMSG(_("Double ; in list of variables"));
1903 return NULL;
1905 *semicolon = 1;
1907 else if (*p != ',')
1909 EMSG2(_(e_invarg2), p);
1910 return NULL;
1913 return p + 1;
1915 else
1916 return skip_var_one(arg);
1920 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
1921 * l[idx].
1923 static char_u *
1924 skip_var_one(arg)
1925 char_u *arg;
1927 if (*arg == '@' && arg[1] != NUL)
1928 return arg + 2;
1929 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
1930 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1934 * List variables for hashtab "ht" with prefix "prefix".
1935 * If "empty" is TRUE also list NULL strings as empty strings.
1937 static void
1938 list_hashtable_vars(ht, prefix, empty, first)
1939 hashtab_T *ht;
1940 char_u *prefix;
1941 int empty;
1942 int *first;
1944 hashitem_T *hi;
1945 dictitem_T *di;
1946 int todo;
1948 todo = (int)ht->ht_used;
1949 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
1951 if (!HASHITEM_EMPTY(hi))
1953 --todo;
1954 di = HI2DI(hi);
1955 if (empty || di->di_tv.v_type != VAR_STRING
1956 || di->di_tv.vval.v_string != NULL)
1957 list_one_var(di, prefix, first);
1963 * List global variables.
1965 static void
1966 list_glob_vars(first)
1967 int *first;
1969 list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
1973 * List buffer variables.
1975 static void
1976 list_buf_vars(first)
1977 int *first;
1979 char_u numbuf[NUMBUFLEN];
1981 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:",
1982 TRUE, first);
1984 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
1985 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
1986 numbuf, first);
1990 * List window variables.
1992 static void
1993 list_win_vars(first)
1994 int *first;
1996 list_hashtable_vars(&curwin->w_vars.dv_hashtab,
1997 (char_u *)"w:", TRUE, first);
2000 #ifdef FEAT_WINDOWS
2002 * List tab page variables.
2004 static void
2005 list_tab_vars(first)
2006 int *first;
2008 list_hashtable_vars(&curtab->tp_vars.dv_hashtab,
2009 (char_u *)"t:", TRUE, first);
2011 #endif
2014 * List Vim variables.
2016 static void
2017 list_vim_vars(first)
2018 int *first;
2020 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2024 * List script-local variables, if there is a script.
2026 static void
2027 list_script_vars(first)
2028 int *first;
2030 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2031 list_hashtable_vars(&SCRIPT_VARS(current_SID),
2032 (char_u *)"s:", FALSE, first);
2036 * List function variables, if there is a function.
2038 static void
2039 list_func_vars(first)
2040 int *first;
2042 if (current_funccal != NULL)
2043 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2044 (char_u *)"l:", FALSE, first);
2048 * List variables in "arg".
2050 static char_u *
2051 list_arg_vars(eap, arg, first)
2052 exarg_T *eap;
2053 char_u *arg;
2054 int *first;
2056 int error = FALSE;
2057 int len;
2058 char_u *name;
2059 char_u *name_start;
2060 char_u *arg_subsc;
2061 char_u *tofree;
2062 typval_T tv;
2064 while (!ends_excmd(*arg) && !got_int)
2066 if (error || eap->skip)
2068 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2069 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2071 emsg_severe = TRUE;
2072 EMSG(_(e_trailing));
2073 break;
2076 else
2078 /* get_name_len() takes care of expanding curly braces */
2079 name_start = name = arg;
2080 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2081 if (len <= 0)
2083 /* This is mainly to keep test 49 working: when expanding
2084 * curly braces fails overrule the exception error message. */
2085 if (len < 0 && !aborting())
2087 emsg_severe = TRUE;
2088 EMSG2(_(e_invarg2), arg);
2089 break;
2091 error = TRUE;
2093 else
2095 if (tofree != NULL)
2096 name = tofree;
2097 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2098 error = TRUE;
2099 else
2101 /* handle d.key, l[idx], f(expr) */
2102 arg_subsc = arg;
2103 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2104 error = TRUE;
2105 else
2107 if (arg == arg_subsc && len == 2 && name[1] == ':')
2109 switch (*name)
2111 case 'g': list_glob_vars(first); break;
2112 case 'b': list_buf_vars(first); break;
2113 case 'w': list_win_vars(first); break;
2114 #ifdef FEAT_WINDOWS
2115 case 't': list_tab_vars(first); break;
2116 #endif
2117 case 'v': list_vim_vars(first); break;
2118 case 's': list_script_vars(first); break;
2119 case 'l': list_func_vars(first); break;
2120 default:
2121 EMSG2(_("E738: Can't list variables for %s"), name);
2124 else
2126 char_u numbuf[NUMBUFLEN];
2127 char_u *tf;
2128 int c;
2129 char_u *s;
2131 s = echo_string(&tv, &tf, numbuf, 0);
2132 c = *arg;
2133 *arg = NUL;
2134 list_one_var_a((char_u *)"",
2135 arg == arg_subsc ? name : name_start,
2136 tv.v_type,
2137 s == NULL ? (char_u *)"" : s,
2138 first);
2139 *arg = c;
2140 vim_free(tf);
2142 clear_tv(&tv);
2147 vim_free(tofree);
2150 arg = skipwhite(arg);
2153 return arg;
2157 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2158 * Returns a pointer to the char just after the var name.
2159 * Returns NULL if there is an error.
2161 static char_u *
2162 ex_let_one(arg, tv, copy, endchars, op)
2163 char_u *arg; /* points to variable name */
2164 typval_T *tv; /* value to assign to variable */
2165 int copy; /* copy value from "tv" */
2166 char_u *endchars; /* valid chars after variable name or NULL */
2167 char_u *op; /* "+", "-", "." or NULL*/
2169 int c1;
2170 char_u *name;
2171 char_u *p;
2172 char_u *arg_end = NULL;
2173 int len;
2174 int opt_flags;
2175 char_u *tofree = NULL;
2178 * ":let $VAR = expr": Set environment variable.
2180 if (*arg == '$')
2182 /* Find the end of the name. */
2183 ++arg;
2184 name = arg;
2185 len = get_env_len(&arg);
2186 if (len == 0)
2187 EMSG2(_(e_invarg2), name - 1);
2188 else
2190 if (op != NULL && (*op == '+' || *op == '-'))
2191 EMSG2(_(e_letwrong), op);
2192 else if (endchars != NULL
2193 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2194 EMSG(_(e_letunexp));
2195 else
2197 c1 = name[len];
2198 name[len] = NUL;
2199 p = get_tv_string_chk(tv);
2200 if (p != NULL && op != NULL && *op == '.')
2202 int mustfree = FALSE;
2203 char_u *s = vim_getenv(name, &mustfree);
2205 if (s != NULL)
2207 p = tofree = concat_str(s, p);
2208 if (mustfree)
2209 vim_free(s);
2212 if (p != NULL)
2214 vim_setenv(name, p);
2215 if (STRICMP(name, "HOME") == 0)
2216 init_homedir();
2217 else if (didset_vim && STRICMP(name, "VIM") == 0)
2218 didset_vim = FALSE;
2219 else if (didset_vimruntime
2220 && STRICMP(name, "VIMRUNTIME") == 0)
2221 didset_vimruntime = FALSE;
2222 arg_end = arg;
2224 name[len] = c1;
2225 vim_free(tofree);
2231 * ":let &option = expr": Set option value.
2232 * ":let &l:option = expr": Set local option value.
2233 * ":let &g:option = expr": Set global option value.
2235 else if (*arg == '&')
2237 /* Find the end of the name. */
2238 p = find_option_end(&arg, &opt_flags);
2239 if (p == NULL || (endchars != NULL
2240 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2241 EMSG(_(e_letunexp));
2242 else
2244 long n;
2245 int opt_type;
2246 long numval;
2247 char_u *stringval = NULL;
2248 char_u *s;
2250 c1 = *p;
2251 *p = NUL;
2253 n = get_tv_number(tv);
2254 s = get_tv_string_chk(tv); /* != NULL if number or string */
2255 if (s != NULL && op != NULL && *op != '=')
2257 opt_type = get_option_value(arg, &numval,
2258 &stringval, opt_flags);
2259 if ((opt_type == 1 && *op == '.')
2260 || (opt_type == 0 && *op != '.'))
2261 EMSG2(_(e_letwrong), op);
2262 else
2264 if (opt_type == 1) /* number */
2266 if (*op == '+')
2267 n = numval + n;
2268 else
2269 n = numval - n;
2271 else if (opt_type == 0 && stringval != NULL) /* string */
2273 s = concat_str(stringval, s);
2274 vim_free(stringval);
2275 stringval = s;
2279 if (s != NULL)
2281 set_option_value(arg, n, s, opt_flags);
2282 arg_end = p;
2284 *p = c1;
2285 vim_free(stringval);
2290 * ":let @r = expr": Set register contents.
2292 else if (*arg == '@')
2294 ++arg;
2295 if (op != NULL && (*op == '+' || *op == '-'))
2296 EMSG2(_(e_letwrong), op);
2297 else if (endchars != NULL
2298 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2299 EMSG(_(e_letunexp));
2300 else
2302 char_u *ptofree = NULL;
2303 char_u *s;
2305 p = get_tv_string_chk(tv);
2306 if (p != NULL && op != NULL && *op == '.')
2308 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2309 if (s != NULL)
2311 p = ptofree = concat_str(s, p);
2312 vim_free(s);
2315 if (p != NULL)
2317 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2318 arg_end = arg + 1;
2320 vim_free(ptofree);
2325 * ":let var = expr": Set internal variable.
2326 * ":let {expr} = expr": Idem, name made with curly braces
2328 else if (eval_isnamec1(*arg) || *arg == '{')
2330 lval_T lv;
2332 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2333 if (p != NULL && lv.ll_name != NULL)
2335 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2336 EMSG(_(e_letunexp));
2337 else
2339 set_var_lval(&lv, p, tv, copy, op);
2340 arg_end = p;
2343 clear_lval(&lv);
2346 else
2347 EMSG2(_(e_invarg2), arg);
2349 return arg_end;
2353 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2355 static int
2356 check_changedtick(arg)
2357 char_u *arg;
2359 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2361 EMSG2(_(e_readonlyvar), arg);
2362 return TRUE;
2364 return FALSE;
2368 * Get an lval: variable, Dict item or List item that can be assigned a value
2369 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2370 * "name.key", "name.key[expr]" etc.
2371 * Indexing only works if "name" is an existing List or Dictionary.
2372 * "name" points to the start of the name.
2373 * If "rettv" is not NULL it points to the value to be assigned.
2374 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2375 * wrong; must end in space or cmd separator.
2377 * Returns a pointer to just after the name, including indexes.
2378 * When an evaluation error occurs "lp->ll_name" is NULL;
2379 * Returns NULL for a parsing error. Still need to free items in "lp"!
2381 static char_u *
2382 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2383 char_u *name;
2384 typval_T *rettv;
2385 lval_T *lp;
2386 int unlet;
2387 int skip;
2388 int quiet; /* don't give error messages */
2389 int fne_flags; /* flags for find_name_end() */
2391 char_u *p;
2392 char_u *expr_start, *expr_end;
2393 int cc;
2394 dictitem_T *v;
2395 typval_T var1;
2396 typval_T var2;
2397 int empty1 = FALSE;
2398 listitem_T *ni;
2399 char_u *key = NULL;
2400 int len;
2401 hashtab_T *ht;
2403 /* Clear everything in "lp". */
2404 vim_memset(lp, 0, sizeof(lval_T));
2406 if (skip)
2408 /* When skipping just find the end of the name. */
2409 lp->ll_name = name;
2410 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2413 /* Find the end of the name. */
2414 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2415 if (expr_start != NULL)
2417 /* Don't expand the name when we already know there is an error. */
2418 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2419 && *p != '[' && *p != '.')
2421 EMSG(_(e_trailing));
2422 return NULL;
2425 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2426 if (lp->ll_exp_name == NULL)
2428 /* Report an invalid expression in braces, unless the
2429 * expression evaluation has been cancelled due to an
2430 * aborting error, an interrupt, or an exception. */
2431 if (!aborting() && !quiet)
2433 emsg_severe = TRUE;
2434 EMSG2(_(e_invarg2), name);
2435 return NULL;
2438 lp->ll_name = lp->ll_exp_name;
2440 else
2441 lp->ll_name = name;
2443 /* Without [idx] or .key we are done. */
2444 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2445 return p;
2447 cc = *p;
2448 *p = NUL;
2449 v = find_var(lp->ll_name, &ht);
2450 if (v == NULL && !quiet)
2451 EMSG2(_(e_undefvar), lp->ll_name);
2452 *p = cc;
2453 if (v == NULL)
2454 return NULL;
2457 * Loop until no more [idx] or .key is following.
2459 lp->ll_tv = &v->di_tv;
2460 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2462 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2463 && !(lp->ll_tv->v_type == VAR_DICT
2464 && lp->ll_tv->vval.v_dict != NULL))
2466 if (!quiet)
2467 EMSG(_("E689: Can only index a List or Dictionary"));
2468 return NULL;
2470 if (lp->ll_range)
2472 if (!quiet)
2473 EMSG(_("E708: [:] must come last"));
2474 return NULL;
2477 len = -1;
2478 if (*p == '.')
2480 key = p + 1;
2481 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2483 if (len == 0)
2485 if (!quiet)
2486 EMSG(_(e_emptykey));
2487 return NULL;
2489 p = key + len;
2491 else
2493 /* Get the index [expr] or the first index [expr: ]. */
2494 p = skipwhite(p + 1);
2495 if (*p == ':')
2496 empty1 = TRUE;
2497 else
2499 empty1 = FALSE;
2500 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2501 return NULL;
2502 if (get_tv_string_chk(&var1) == NULL)
2504 /* not a number or string */
2505 clear_tv(&var1);
2506 return NULL;
2510 /* Optionally get the second index [ :expr]. */
2511 if (*p == ':')
2513 if (lp->ll_tv->v_type == VAR_DICT)
2515 if (!quiet)
2516 EMSG(_(e_dictrange));
2517 if (!empty1)
2518 clear_tv(&var1);
2519 return NULL;
2521 if (rettv != NULL && (rettv->v_type != VAR_LIST
2522 || rettv->vval.v_list == NULL))
2524 if (!quiet)
2525 EMSG(_("E709: [:] requires a List value"));
2526 if (!empty1)
2527 clear_tv(&var1);
2528 return NULL;
2530 p = skipwhite(p + 1);
2531 if (*p == ']')
2532 lp->ll_empty2 = TRUE;
2533 else
2535 lp->ll_empty2 = FALSE;
2536 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2538 if (!empty1)
2539 clear_tv(&var1);
2540 return NULL;
2542 if (get_tv_string_chk(&var2) == NULL)
2544 /* not a number or string */
2545 if (!empty1)
2546 clear_tv(&var1);
2547 clear_tv(&var2);
2548 return NULL;
2551 lp->ll_range = TRUE;
2553 else
2554 lp->ll_range = FALSE;
2556 if (*p != ']')
2558 if (!quiet)
2559 EMSG(_(e_missbrac));
2560 if (!empty1)
2561 clear_tv(&var1);
2562 if (lp->ll_range && !lp->ll_empty2)
2563 clear_tv(&var2);
2564 return NULL;
2567 /* Skip to past ']'. */
2568 ++p;
2571 if (lp->ll_tv->v_type == VAR_DICT)
2573 if (len == -1)
2575 /* "[key]": get key from "var1" */
2576 key = get_tv_string(&var1); /* is number or string */
2577 if (*key == NUL)
2579 if (!quiet)
2580 EMSG(_(e_emptykey));
2581 clear_tv(&var1);
2582 return NULL;
2585 lp->ll_list = NULL;
2586 lp->ll_dict = lp->ll_tv->vval.v_dict;
2587 lp->ll_di = dict_find(lp->ll_dict, key, len);
2588 if (lp->ll_di == NULL)
2590 /* Key does not exist in dict: may need to add it. */
2591 if (*p == '[' || *p == '.' || unlet)
2593 if (!quiet)
2594 EMSG2(_(e_dictkey), key);
2595 if (len == -1)
2596 clear_tv(&var1);
2597 return NULL;
2599 if (len == -1)
2600 lp->ll_newkey = vim_strsave(key);
2601 else
2602 lp->ll_newkey = vim_strnsave(key, len);
2603 if (len == -1)
2604 clear_tv(&var1);
2605 if (lp->ll_newkey == NULL)
2606 p = NULL;
2607 break;
2609 if (len == -1)
2610 clear_tv(&var1);
2611 lp->ll_tv = &lp->ll_di->di_tv;
2613 else
2616 * Get the number and item for the only or first index of the List.
2618 if (empty1)
2619 lp->ll_n1 = 0;
2620 else
2622 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2623 clear_tv(&var1);
2625 lp->ll_dict = NULL;
2626 lp->ll_list = lp->ll_tv->vval.v_list;
2627 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2628 if (lp->ll_li == NULL)
2630 if (lp->ll_n1 < 0)
2632 lp->ll_n1 = 0;
2633 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2636 if (lp->ll_li == NULL)
2638 if (lp->ll_range && !lp->ll_empty2)
2639 clear_tv(&var2);
2640 return NULL;
2644 * May need to find the item or absolute index for the second
2645 * index of a range.
2646 * When no index given: "lp->ll_empty2" is TRUE.
2647 * Otherwise "lp->ll_n2" is set to the second index.
2649 if (lp->ll_range && !lp->ll_empty2)
2651 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2652 clear_tv(&var2);
2653 if (lp->ll_n2 < 0)
2655 ni = list_find(lp->ll_list, lp->ll_n2);
2656 if (ni == NULL)
2657 return NULL;
2658 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2661 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2662 if (lp->ll_n1 < 0)
2663 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2664 if (lp->ll_n2 < lp->ll_n1)
2665 return NULL;
2668 lp->ll_tv = &lp->ll_li->li_tv;
2672 return p;
2676 * Clear lval "lp" that was filled by get_lval().
2678 static void
2679 clear_lval(lp)
2680 lval_T *lp;
2682 vim_free(lp->ll_exp_name);
2683 vim_free(lp->ll_newkey);
2687 * Set a variable that was parsed by get_lval() to "rettv".
2688 * "endp" points to just after the parsed name.
2689 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2691 static void
2692 set_var_lval(lp, endp, rettv, copy, op)
2693 lval_T *lp;
2694 char_u *endp;
2695 typval_T *rettv;
2696 int copy;
2697 char_u *op;
2699 int cc;
2700 listitem_T *ri;
2701 dictitem_T *di;
2703 if (lp->ll_tv == NULL)
2705 if (!check_changedtick(lp->ll_name))
2707 cc = *endp;
2708 *endp = NUL;
2709 if (op != NULL && *op != '=')
2711 typval_T tv;
2713 /* handle +=, -= and .= */
2714 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2715 &tv, TRUE) == OK)
2717 if (tv_op(&tv, rettv, op) == OK)
2718 set_var(lp->ll_name, &tv, FALSE);
2719 clear_tv(&tv);
2722 else
2723 set_var(lp->ll_name, rettv, copy);
2724 *endp = cc;
2727 else if (tv_check_lock(lp->ll_newkey == NULL
2728 ? lp->ll_tv->v_lock
2729 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2731 else if (lp->ll_range)
2734 * Assign the List values to the list items.
2736 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2738 if (op != NULL && *op != '=')
2739 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2740 else
2742 clear_tv(&lp->ll_li->li_tv);
2743 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2745 ri = ri->li_next;
2746 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2747 break;
2748 if (lp->ll_li->li_next == NULL)
2750 /* Need to add an empty item. */
2751 if (list_append_number(lp->ll_list, 0) == FAIL)
2753 ri = NULL;
2754 break;
2757 lp->ll_li = lp->ll_li->li_next;
2758 ++lp->ll_n1;
2760 if (ri != NULL)
2761 EMSG(_("E710: List value has more items than target"));
2762 else if (lp->ll_empty2
2763 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2764 : lp->ll_n1 != lp->ll_n2)
2765 EMSG(_("E711: List value has not enough items"));
2767 else
2770 * Assign to a List or Dictionary item.
2772 if (lp->ll_newkey != NULL)
2774 if (op != NULL && *op != '=')
2776 EMSG2(_(e_letwrong), op);
2777 return;
2780 /* Need to add an item to the Dictionary. */
2781 di = dictitem_alloc(lp->ll_newkey);
2782 if (di == NULL)
2783 return;
2784 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2786 vim_free(di);
2787 return;
2789 lp->ll_tv = &di->di_tv;
2791 else if (op != NULL && *op != '=')
2793 tv_op(lp->ll_tv, rettv, op);
2794 return;
2796 else
2797 clear_tv(lp->ll_tv);
2800 * Assign the value to the variable or list item.
2802 if (copy)
2803 copy_tv(rettv, lp->ll_tv);
2804 else
2806 *lp->ll_tv = *rettv;
2807 lp->ll_tv->v_lock = 0;
2808 init_tv(rettv);
2814 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2815 * Returns OK or FAIL.
2817 static int
2818 tv_op(tv1, tv2, op)
2819 typval_T *tv1;
2820 typval_T *tv2;
2821 char_u *op;
2823 long n;
2824 char_u numbuf[NUMBUFLEN];
2825 char_u *s;
2827 /* Can't do anything with a Funcref or a Dict on the right. */
2828 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2830 switch (tv1->v_type)
2832 case VAR_DICT:
2833 case VAR_FUNC:
2834 break;
2836 case VAR_LIST:
2837 if (*op != '+' || tv2->v_type != VAR_LIST)
2838 break;
2839 /* List += List */
2840 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2841 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2842 return OK;
2844 case VAR_NUMBER:
2845 case VAR_STRING:
2846 if (tv2->v_type == VAR_LIST)
2847 break;
2848 if (*op == '+' || *op == '-')
2850 /* nr += nr or nr -= nr*/
2851 n = get_tv_number(tv1);
2852 if (*op == '+')
2853 n += get_tv_number(tv2);
2854 else
2855 n -= get_tv_number(tv2);
2856 clear_tv(tv1);
2857 tv1->v_type = VAR_NUMBER;
2858 tv1->vval.v_number = n;
2860 else
2862 /* str .= str */
2863 s = get_tv_string(tv1);
2864 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2865 clear_tv(tv1);
2866 tv1->v_type = VAR_STRING;
2867 tv1->vval.v_string = s;
2869 return OK;
2873 EMSG2(_(e_letwrong), op);
2874 return FAIL;
2878 * Add a watcher to a list.
2880 static void
2881 list_add_watch(l, lw)
2882 list_T *l;
2883 listwatch_T *lw;
2885 lw->lw_next = l->lv_watch;
2886 l->lv_watch = lw;
2890 * Remove a watcher from a list.
2891 * No warning when it isn't found...
2893 static void
2894 list_rem_watch(l, lwrem)
2895 list_T *l;
2896 listwatch_T *lwrem;
2898 listwatch_T *lw, **lwp;
2900 lwp = &l->lv_watch;
2901 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2903 if (lw == lwrem)
2905 *lwp = lw->lw_next;
2906 break;
2908 lwp = &lw->lw_next;
2913 * Just before removing an item from a list: advance watchers to the next
2914 * item.
2916 static void
2917 list_fix_watch(l, item)
2918 list_T *l;
2919 listitem_T *item;
2921 listwatch_T *lw;
2923 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2924 if (lw->lw_item == item)
2925 lw->lw_item = item->li_next;
2929 * Evaluate the expression used in a ":for var in expr" command.
2930 * "arg" points to "var".
2931 * Set "*errp" to TRUE for an error, FALSE otherwise;
2932 * Return a pointer that holds the info. Null when there is an error.
2934 void *
2935 eval_for_line(arg, errp, nextcmdp, skip)
2936 char_u *arg;
2937 int *errp;
2938 char_u **nextcmdp;
2939 int skip;
2941 forinfo_T *fi;
2942 char_u *expr;
2943 typval_T tv;
2944 list_T *l;
2946 *errp = TRUE; /* default: there is an error */
2948 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
2949 if (fi == NULL)
2950 return NULL;
2952 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
2953 if (expr == NULL)
2954 return fi;
2956 expr = skipwhite(expr);
2957 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
2959 EMSG(_("E690: Missing \"in\" after :for"));
2960 return fi;
2963 if (skip)
2964 ++emsg_skip;
2965 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
2967 *errp = FALSE;
2968 if (!skip)
2970 l = tv.vval.v_list;
2971 if (tv.v_type != VAR_LIST || l == NULL)
2973 EMSG(_(e_listreq));
2974 clear_tv(&tv);
2976 else
2978 /* No need to increment the refcount, it's already set for the
2979 * list being used in "tv". */
2980 fi->fi_list = l;
2981 list_add_watch(l, &fi->fi_lw);
2982 fi->fi_lw.lw_item = l->lv_first;
2986 if (skip)
2987 --emsg_skip;
2989 return fi;
2993 * Use the first item in a ":for" list. Advance to the next.
2994 * Assign the values to the variable (list). "arg" points to the first one.
2995 * Return TRUE when a valid item was found, FALSE when at end of list or
2996 * something wrong.
2999 next_for_item(fi_void, arg)
3000 void *fi_void;
3001 char_u *arg;
3003 forinfo_T *fi = (forinfo_T *)fi_void;
3004 int result;
3005 listitem_T *item;
3007 item = fi->fi_lw.lw_item;
3008 if (item == NULL)
3009 result = FALSE;
3010 else
3012 fi->fi_lw.lw_item = item->li_next;
3013 result = (ex_let_vars(arg, &item->li_tv, TRUE,
3014 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3016 return result;
3020 * Free the structure used to store info used by ":for".
3022 void
3023 free_for_info(fi_void)
3024 void *fi_void;
3026 forinfo_T *fi = (forinfo_T *)fi_void;
3028 if (fi != NULL && fi->fi_list != NULL)
3030 list_rem_watch(fi->fi_list, &fi->fi_lw);
3031 list_unref(fi->fi_list);
3033 vim_free(fi);
3036 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3038 void
3039 set_context_for_expression(xp, arg, cmdidx)
3040 expand_T *xp;
3041 char_u *arg;
3042 cmdidx_T cmdidx;
3044 int got_eq = FALSE;
3045 int c;
3046 char_u *p;
3048 if (cmdidx == CMD_let)
3050 xp->xp_context = EXPAND_USER_VARS;
3051 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3053 /* ":let var1 var2 ...": find last space. */
3054 for (p = arg + STRLEN(arg); p >= arg; )
3056 xp->xp_pattern = p;
3057 mb_ptr_back(arg, p);
3058 if (vim_iswhite(*p))
3059 break;
3061 return;
3064 else
3065 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3066 : EXPAND_EXPRESSION;
3067 while ((xp->xp_pattern = vim_strpbrk(arg,
3068 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3070 c = *xp->xp_pattern;
3071 if (c == '&')
3073 c = xp->xp_pattern[1];
3074 if (c == '&')
3076 ++xp->xp_pattern;
3077 xp->xp_context = cmdidx != CMD_let || got_eq
3078 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3080 else if (c != ' ')
3082 xp->xp_context = EXPAND_SETTINGS;
3083 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3084 xp->xp_pattern += 2;
3088 else if (c == '$')
3090 /* environment variable */
3091 xp->xp_context = EXPAND_ENV_VARS;
3093 else if (c == '=')
3095 got_eq = TRUE;
3096 xp->xp_context = EXPAND_EXPRESSION;
3098 else if (c == '<'
3099 && xp->xp_context == EXPAND_FUNCTIONS
3100 && vim_strchr(xp->xp_pattern, '(') == NULL)
3102 /* Function name can start with "<SNR>" */
3103 break;
3105 else if (cmdidx != CMD_let || got_eq)
3107 if (c == '"') /* string */
3109 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3110 if (c == '\\' && xp->xp_pattern[1] != NUL)
3111 ++xp->xp_pattern;
3112 xp->xp_context = EXPAND_NOTHING;
3114 else if (c == '\'') /* literal string */
3116 /* Trick: '' is like stopping and starting a literal string. */
3117 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3118 /* skip */ ;
3119 xp->xp_context = EXPAND_NOTHING;
3121 else if (c == '|')
3123 if (xp->xp_pattern[1] == '|')
3125 ++xp->xp_pattern;
3126 xp->xp_context = EXPAND_EXPRESSION;
3128 else
3129 xp->xp_context = EXPAND_COMMANDS;
3131 else
3132 xp->xp_context = EXPAND_EXPRESSION;
3134 else
3135 /* Doesn't look like something valid, expand as an expression
3136 * anyway. */
3137 xp->xp_context = EXPAND_EXPRESSION;
3138 arg = xp->xp_pattern;
3139 if (*arg != NUL)
3140 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3141 /* skip */ ;
3143 xp->xp_pattern = arg;
3146 #endif /* FEAT_CMDL_COMPL */
3149 * ":1,25call func(arg1, arg2)" function call.
3151 void
3152 ex_call(eap)
3153 exarg_T *eap;
3155 char_u *arg = eap->arg;
3156 char_u *startarg;
3157 char_u *name;
3158 char_u *tofree;
3159 int len;
3160 typval_T rettv;
3161 linenr_T lnum;
3162 int doesrange;
3163 int failed = FALSE;
3164 funcdict_T fudi;
3166 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3167 if (fudi.fd_newkey != NULL)
3169 /* Still need to give an error message for missing key. */
3170 EMSG2(_(e_dictkey), fudi.fd_newkey);
3171 vim_free(fudi.fd_newkey);
3173 if (tofree == NULL)
3174 return;
3176 /* Increase refcount on dictionary, it could get deleted when evaluating
3177 * the arguments. */
3178 if (fudi.fd_dict != NULL)
3179 ++fudi.fd_dict->dv_refcount;
3181 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3182 len = (int)STRLEN(tofree);
3183 name = deref_func_name(tofree, &len);
3185 /* Skip white space to allow ":call func ()". Not good, but required for
3186 * backward compatibility. */
3187 startarg = skipwhite(arg);
3188 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3190 if (*startarg != '(')
3192 EMSG2(_("E107: Missing braces: %s"), eap->arg);
3193 goto end;
3197 * When skipping, evaluate the function once, to find the end of the
3198 * arguments.
3199 * When the function takes a range, this is discovered after the first
3200 * call, and the loop is broken.
3202 if (eap->skip)
3204 ++emsg_skip;
3205 lnum = eap->line2; /* do it once, also with an invalid range */
3207 else
3208 lnum = eap->line1;
3209 for ( ; lnum <= eap->line2; ++lnum)
3211 if (!eap->skip && eap->addr_count > 0)
3213 curwin->w_cursor.lnum = lnum;
3214 curwin->w_cursor.col = 0;
3216 arg = startarg;
3217 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3218 eap->line1, eap->line2, &doesrange,
3219 !eap->skip, fudi.fd_dict) == FAIL)
3221 failed = TRUE;
3222 break;
3225 /* Handle a function returning a Funcref, Dictionary or List. */
3226 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3228 failed = TRUE;
3229 break;
3232 clear_tv(&rettv);
3233 if (doesrange || eap->skip)
3234 break;
3236 /* Stop when immediately aborting on error, or when an interrupt
3237 * occurred or an exception was thrown but not caught.
3238 * get_func_tv() returned OK, so that the check for trailing
3239 * characters below is executed. */
3240 if (aborting())
3241 break;
3243 if (eap->skip)
3244 --emsg_skip;
3246 if (!failed)
3248 /* Check for trailing illegal characters and a following command. */
3249 if (!ends_excmd(*arg))
3251 emsg_severe = TRUE;
3252 EMSG(_(e_trailing));
3254 else
3255 eap->nextcmd = check_nextcmd(arg);
3258 end:
3259 dict_unref(fudi.fd_dict);
3260 vim_free(tofree);
3264 * ":unlet[!] var1 ... " command.
3266 void
3267 ex_unlet(eap)
3268 exarg_T *eap;
3270 ex_unletlock(eap, eap->arg, 0);
3274 * ":lockvar" and ":unlockvar" commands
3276 void
3277 ex_lockvar(eap)
3278 exarg_T *eap;
3280 char_u *arg = eap->arg;
3281 int deep = 2;
3283 if (eap->forceit)
3284 deep = -1;
3285 else if (vim_isdigit(*arg))
3287 deep = getdigits(&arg);
3288 arg = skipwhite(arg);
3291 ex_unletlock(eap, arg, deep);
3295 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3297 static void
3298 ex_unletlock(eap, argstart, deep)
3299 exarg_T *eap;
3300 char_u *argstart;
3301 int deep;
3303 char_u *arg = argstart;
3304 char_u *name_end;
3305 int error = FALSE;
3306 lval_T lv;
3310 /* Parse the name and find the end. */
3311 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3312 FNE_CHECK_START);
3313 if (lv.ll_name == NULL)
3314 error = TRUE; /* error but continue parsing */
3315 if (name_end == NULL || (!vim_iswhite(*name_end)
3316 && !ends_excmd(*name_end)))
3318 if (name_end != NULL)
3320 emsg_severe = TRUE;
3321 EMSG(_(e_trailing));
3323 if (!(eap->skip || error))
3324 clear_lval(&lv);
3325 break;
3328 if (!error && !eap->skip)
3330 if (eap->cmdidx == CMD_unlet)
3332 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3333 error = TRUE;
3335 else
3337 if (do_lock_var(&lv, name_end, deep,
3338 eap->cmdidx == CMD_lockvar) == FAIL)
3339 error = TRUE;
3343 if (!eap->skip)
3344 clear_lval(&lv);
3346 arg = skipwhite(name_end);
3347 } while (!ends_excmd(*arg));
3349 eap->nextcmd = check_nextcmd(arg);
3352 static int
3353 do_unlet_var(lp, name_end, forceit)
3354 lval_T *lp;
3355 char_u *name_end;
3356 int forceit;
3358 int ret = OK;
3359 int cc;
3361 if (lp->ll_tv == NULL)
3363 cc = *name_end;
3364 *name_end = NUL;
3366 /* Normal name or expanded name. */
3367 if (check_changedtick(lp->ll_name))
3368 ret = FAIL;
3369 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3370 ret = FAIL;
3371 *name_end = cc;
3373 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3374 return FAIL;
3375 else if (lp->ll_range)
3377 listitem_T *li;
3379 /* Delete a range of List items. */
3380 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3382 li = lp->ll_li->li_next;
3383 listitem_remove(lp->ll_list, lp->ll_li);
3384 lp->ll_li = li;
3385 ++lp->ll_n1;
3388 else
3390 if (lp->ll_list != NULL)
3391 /* unlet a List item. */
3392 listitem_remove(lp->ll_list, lp->ll_li);
3393 else
3394 /* unlet a Dictionary item. */
3395 dictitem_remove(lp->ll_dict, lp->ll_di);
3398 return ret;
3402 * "unlet" a variable. Return OK if it existed, FAIL if not.
3403 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3406 do_unlet(name, forceit)
3407 char_u *name;
3408 int forceit;
3410 hashtab_T *ht;
3411 hashitem_T *hi;
3412 char_u *varname;
3413 dictitem_T *di;
3415 ht = find_var_ht(name, &varname);
3416 if (ht != NULL && *varname != NUL)
3418 hi = hash_find(ht, varname);
3419 if (!HASHITEM_EMPTY(hi))
3421 di = HI2DI(hi);
3422 if (var_check_fixed(di->di_flags, name)
3423 || var_check_ro(di->di_flags, name))
3424 return FAIL;
3425 delete_var(ht, hi);
3426 return OK;
3429 if (forceit)
3430 return OK;
3431 EMSG2(_("E108: No such variable: \"%s\""), name);
3432 return FAIL;
3436 * Lock or unlock variable indicated by "lp".
3437 * "deep" is the levels to go (-1 for unlimited);
3438 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3440 static int
3441 do_lock_var(lp, name_end, deep, lock)
3442 lval_T *lp;
3443 char_u *name_end;
3444 int deep;
3445 int lock;
3447 int ret = OK;
3448 int cc;
3449 dictitem_T *di;
3451 if (deep == 0) /* nothing to do */
3452 return OK;
3454 if (lp->ll_tv == NULL)
3456 cc = *name_end;
3457 *name_end = NUL;
3459 /* Normal name or expanded name. */
3460 if (check_changedtick(lp->ll_name))
3461 ret = FAIL;
3462 else
3464 di = find_var(lp->ll_name, NULL);
3465 if (di == NULL)
3466 ret = FAIL;
3467 else
3469 if (lock)
3470 di->di_flags |= DI_FLAGS_LOCK;
3471 else
3472 di->di_flags &= ~DI_FLAGS_LOCK;
3473 item_lock(&di->di_tv, deep, lock);
3476 *name_end = cc;
3478 else if (lp->ll_range)
3480 listitem_T *li = lp->ll_li;
3482 /* (un)lock a range of List items. */
3483 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3485 item_lock(&li->li_tv, deep, lock);
3486 li = li->li_next;
3487 ++lp->ll_n1;
3490 else if (lp->ll_list != NULL)
3491 /* (un)lock a List item. */
3492 item_lock(&lp->ll_li->li_tv, deep, lock);
3493 else
3494 /* un(lock) a Dictionary item. */
3495 item_lock(&lp->ll_di->di_tv, deep, lock);
3497 return ret;
3501 * Lock or unlock an item. "deep" is nr of levels to go.
3503 static void
3504 item_lock(tv, deep, lock)
3505 typval_T *tv;
3506 int deep;
3507 int lock;
3509 static int recurse = 0;
3510 list_T *l;
3511 listitem_T *li;
3512 dict_T *d;
3513 hashitem_T *hi;
3514 int todo;
3516 if (recurse >= DICT_MAXNEST)
3518 EMSG(_("E743: variable nested too deep for (un)lock"));
3519 return;
3521 if (deep == 0)
3522 return;
3523 ++recurse;
3525 /* lock/unlock the item itself */
3526 if (lock)
3527 tv->v_lock |= VAR_LOCKED;
3528 else
3529 tv->v_lock &= ~VAR_LOCKED;
3531 switch (tv->v_type)
3533 case VAR_LIST:
3534 if ((l = tv->vval.v_list) != NULL)
3536 if (lock)
3537 l->lv_lock |= VAR_LOCKED;
3538 else
3539 l->lv_lock &= ~VAR_LOCKED;
3540 if (deep < 0 || deep > 1)
3541 /* recursive: lock/unlock the items the List contains */
3542 for (li = l->lv_first; li != NULL; li = li->li_next)
3543 item_lock(&li->li_tv, deep - 1, lock);
3545 break;
3546 case VAR_DICT:
3547 if ((d = tv->vval.v_dict) != NULL)
3549 if (lock)
3550 d->dv_lock |= VAR_LOCKED;
3551 else
3552 d->dv_lock &= ~VAR_LOCKED;
3553 if (deep < 0 || deep > 1)
3555 /* recursive: lock/unlock the items the List contains */
3556 todo = (int)d->dv_hashtab.ht_used;
3557 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3559 if (!HASHITEM_EMPTY(hi))
3561 --todo;
3562 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3568 --recurse;
3572 * Return TRUE if typeval "tv" is locked: Either tha value is locked itself or
3573 * it refers to a List or Dictionary that is locked.
3575 static int
3576 tv_islocked(tv)
3577 typval_T *tv;
3579 return (tv->v_lock & VAR_LOCKED)
3580 || (tv->v_type == VAR_LIST
3581 && tv->vval.v_list != NULL
3582 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3583 || (tv->v_type == VAR_DICT
3584 && tv->vval.v_dict != NULL
3585 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3588 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3590 * Delete all "menutrans_" variables.
3592 void
3593 del_menutrans_vars()
3595 hashitem_T *hi;
3596 int todo;
3598 hash_lock(&globvarht);
3599 todo = (int)globvarht.ht_used;
3600 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3602 if (!HASHITEM_EMPTY(hi))
3604 --todo;
3605 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3606 delete_var(&globvarht, hi);
3609 hash_unlock(&globvarht);
3611 #endif
3613 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3616 * Local string buffer for the next two functions to store a variable name
3617 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3618 * get_user_var_name().
3621 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3623 static char_u *varnamebuf = NULL;
3624 static int varnamebuflen = 0;
3627 * Function to concatenate a prefix and a variable name.
3629 static char_u *
3630 cat_prefix_varname(prefix, name)
3631 int prefix;
3632 char_u *name;
3634 int len;
3636 len = (int)STRLEN(name) + 3;
3637 if (len > varnamebuflen)
3639 vim_free(varnamebuf);
3640 len += 10; /* some additional space */
3641 varnamebuf = alloc(len);
3642 if (varnamebuf == NULL)
3644 varnamebuflen = 0;
3645 return NULL;
3647 varnamebuflen = len;
3649 *varnamebuf = prefix;
3650 varnamebuf[1] = ':';
3651 STRCPY(varnamebuf + 2, name);
3652 return varnamebuf;
3656 * Function given to ExpandGeneric() to obtain the list of user defined
3657 * (global/buffer/window/built-in) variable names.
3659 /*ARGSUSED*/
3660 char_u *
3661 get_user_var_name(xp, idx)
3662 expand_T *xp;
3663 int idx;
3665 static long_u gdone;
3666 static long_u bdone;
3667 static long_u wdone;
3668 #ifdef FEAT_WINDOWS
3669 static long_u tdone;
3670 #endif
3671 static int vidx;
3672 static hashitem_T *hi;
3673 hashtab_T *ht;
3675 if (idx == 0)
3677 gdone = bdone = wdone = vidx = 0;
3678 #ifdef FEAT_WINDOWS
3679 tdone = 0;
3680 #endif
3683 /* Global variables */
3684 if (gdone < globvarht.ht_used)
3686 if (gdone++ == 0)
3687 hi = globvarht.ht_array;
3688 else
3689 ++hi;
3690 while (HASHITEM_EMPTY(hi))
3691 ++hi;
3692 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3693 return cat_prefix_varname('g', hi->hi_key);
3694 return hi->hi_key;
3697 /* b: variables */
3698 ht = &curbuf->b_vars.dv_hashtab;
3699 if (bdone < ht->ht_used)
3701 if (bdone++ == 0)
3702 hi = ht->ht_array;
3703 else
3704 ++hi;
3705 while (HASHITEM_EMPTY(hi))
3706 ++hi;
3707 return cat_prefix_varname('b', hi->hi_key);
3709 if (bdone == ht->ht_used)
3711 ++bdone;
3712 return (char_u *)"b:changedtick";
3715 /* w: variables */
3716 ht = &curwin->w_vars.dv_hashtab;
3717 if (wdone < ht->ht_used)
3719 if (wdone++ == 0)
3720 hi = ht->ht_array;
3721 else
3722 ++hi;
3723 while (HASHITEM_EMPTY(hi))
3724 ++hi;
3725 return cat_prefix_varname('w', hi->hi_key);
3728 #ifdef FEAT_WINDOWS
3729 /* t: variables */
3730 ht = &curtab->tp_vars.dv_hashtab;
3731 if (tdone < ht->ht_used)
3733 if (tdone++ == 0)
3734 hi = ht->ht_array;
3735 else
3736 ++hi;
3737 while (HASHITEM_EMPTY(hi))
3738 ++hi;
3739 return cat_prefix_varname('t', hi->hi_key);
3741 #endif
3743 /* v: variables */
3744 if (vidx < VV_LEN)
3745 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3747 vim_free(varnamebuf);
3748 varnamebuf = NULL;
3749 varnamebuflen = 0;
3750 return NULL;
3753 #endif /* FEAT_CMDL_COMPL */
3756 * types for expressions.
3758 typedef enum
3760 TYPE_UNKNOWN = 0
3761 , TYPE_EQUAL /* == */
3762 , TYPE_NEQUAL /* != */
3763 , TYPE_GREATER /* > */
3764 , TYPE_GEQUAL /* >= */
3765 , TYPE_SMALLER /* < */
3766 , TYPE_SEQUAL /* <= */
3767 , TYPE_MATCH /* =~ */
3768 , TYPE_NOMATCH /* !~ */
3769 } exptype_T;
3772 * The "evaluate" argument: When FALSE, the argument is only parsed but not
3773 * executed. The function may return OK, but the rettv will be of type
3774 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
3778 * Handle zero level expression.
3779 * This calls eval1() and handles error message and nextcmd.
3780 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3781 * Note: "rettv.v_lock" is not set.
3782 * Return OK or FAIL.
3784 static int
3785 eval0(arg, rettv, nextcmd, evaluate)
3786 char_u *arg;
3787 typval_T *rettv;
3788 char_u **nextcmd;
3789 int evaluate;
3791 int ret;
3792 char_u *p;
3794 p = skipwhite(arg);
3795 ret = eval1(&p, rettv, evaluate);
3796 if (ret == FAIL || !ends_excmd(*p))
3798 if (ret != FAIL)
3799 clear_tv(rettv);
3801 * Report the invalid expression unless the expression evaluation has
3802 * been cancelled due to an aborting error, an interrupt, or an
3803 * exception.
3805 if (!aborting())
3806 EMSG2(_(e_invexpr2), arg);
3807 ret = FAIL;
3809 if (nextcmd != NULL)
3810 *nextcmd = check_nextcmd(p);
3812 return ret;
3816 * Handle top level expression:
3817 * expr1 ? expr0 : expr0
3819 * "arg" must point to the first non-white of the expression.
3820 * "arg" is advanced to the next non-white after the recognized expression.
3822 * Note: "rettv.v_lock" is not set.
3824 * Return OK or FAIL.
3826 static int
3827 eval1(arg, rettv, evaluate)
3828 char_u **arg;
3829 typval_T *rettv;
3830 int evaluate;
3832 int result;
3833 typval_T var2;
3836 * Get the first variable.
3838 if (eval2(arg, rettv, evaluate) == FAIL)
3839 return FAIL;
3841 if ((*arg)[0] == '?')
3843 result = FALSE;
3844 if (evaluate)
3846 int error = FALSE;
3848 if (get_tv_number_chk(rettv, &error) != 0)
3849 result = TRUE;
3850 clear_tv(rettv);
3851 if (error)
3852 return FAIL;
3856 * Get the second variable.
3858 *arg = skipwhite(*arg + 1);
3859 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
3860 return FAIL;
3863 * Check for the ":".
3865 if ((*arg)[0] != ':')
3867 EMSG(_("E109: Missing ':' after '?'"));
3868 if (evaluate && result)
3869 clear_tv(rettv);
3870 return FAIL;
3874 * Get the third variable.
3876 *arg = skipwhite(*arg + 1);
3877 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
3879 if (evaluate && result)
3880 clear_tv(rettv);
3881 return FAIL;
3883 if (evaluate && !result)
3884 *rettv = var2;
3887 return OK;
3891 * Handle first level expression:
3892 * expr2 || expr2 || expr2 logical OR
3894 * "arg" must point to the first non-white of the expression.
3895 * "arg" is advanced to the next non-white after the recognized expression.
3897 * Return OK or FAIL.
3899 static int
3900 eval2(arg, rettv, evaluate)
3901 char_u **arg;
3902 typval_T *rettv;
3903 int evaluate;
3905 typval_T var2;
3906 long result;
3907 int first;
3908 int error = FALSE;
3911 * Get the first variable.
3913 if (eval3(arg, rettv, evaluate) == FAIL)
3914 return FAIL;
3917 * Repeat until there is no following "||".
3919 first = TRUE;
3920 result = FALSE;
3921 while ((*arg)[0] == '|' && (*arg)[1] == '|')
3923 if (evaluate && first)
3925 if (get_tv_number_chk(rettv, &error) != 0)
3926 result = TRUE;
3927 clear_tv(rettv);
3928 if (error)
3929 return FAIL;
3930 first = FALSE;
3934 * Get the second variable.
3936 *arg = skipwhite(*arg + 2);
3937 if (eval3(arg, &var2, evaluate && !result) == FAIL)
3938 return FAIL;
3941 * Compute the result.
3943 if (evaluate && !result)
3945 if (get_tv_number_chk(&var2, &error) != 0)
3946 result = TRUE;
3947 clear_tv(&var2);
3948 if (error)
3949 return FAIL;
3951 if (evaluate)
3953 rettv->v_type = VAR_NUMBER;
3954 rettv->vval.v_number = result;
3958 return OK;
3962 * Handle second level expression:
3963 * expr3 && expr3 && expr3 logical AND
3965 * "arg" must point to the first non-white of the expression.
3966 * "arg" is advanced to the next non-white after the recognized expression.
3968 * Return OK or FAIL.
3970 static int
3971 eval3(arg, rettv, evaluate)
3972 char_u **arg;
3973 typval_T *rettv;
3974 int evaluate;
3976 typval_T var2;
3977 long result;
3978 int first;
3979 int error = FALSE;
3982 * Get the first variable.
3984 if (eval4(arg, rettv, evaluate) == FAIL)
3985 return FAIL;
3988 * Repeat until there is no following "&&".
3990 first = TRUE;
3991 result = TRUE;
3992 while ((*arg)[0] == '&' && (*arg)[1] == '&')
3994 if (evaluate && first)
3996 if (get_tv_number_chk(rettv, &error) == 0)
3997 result = FALSE;
3998 clear_tv(rettv);
3999 if (error)
4000 return FAIL;
4001 first = FALSE;
4005 * Get the second variable.
4007 *arg = skipwhite(*arg + 2);
4008 if (eval4(arg, &var2, evaluate && result) == FAIL)
4009 return FAIL;
4012 * Compute the result.
4014 if (evaluate && result)
4016 if (get_tv_number_chk(&var2, &error) == 0)
4017 result = FALSE;
4018 clear_tv(&var2);
4019 if (error)
4020 return FAIL;
4022 if (evaluate)
4024 rettv->v_type = VAR_NUMBER;
4025 rettv->vval.v_number = result;
4029 return OK;
4033 * Handle third level expression:
4034 * var1 == var2
4035 * var1 =~ var2
4036 * var1 != var2
4037 * var1 !~ var2
4038 * var1 > var2
4039 * var1 >= var2
4040 * var1 < var2
4041 * var1 <= var2
4042 * var1 is var2
4043 * var1 isnot var2
4045 * "arg" must point to the first non-white of the expression.
4046 * "arg" is advanced to the next non-white after the recognized expression.
4048 * Return OK or FAIL.
4050 static int
4051 eval4(arg, rettv, evaluate)
4052 char_u **arg;
4053 typval_T *rettv;
4054 int evaluate;
4056 typval_T var2;
4057 char_u *p;
4058 int i;
4059 exptype_T type = TYPE_UNKNOWN;
4060 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4061 int len = 2;
4062 long n1, n2;
4063 char_u *s1, *s2;
4064 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4065 regmatch_T regmatch;
4066 int ic;
4067 char_u *save_cpo;
4070 * Get the first variable.
4072 if (eval5(arg, rettv, evaluate) == FAIL)
4073 return FAIL;
4075 p = *arg;
4076 switch (p[0])
4078 case '=': if (p[1] == '=')
4079 type = TYPE_EQUAL;
4080 else if (p[1] == '~')
4081 type = TYPE_MATCH;
4082 break;
4083 case '!': if (p[1] == '=')
4084 type = TYPE_NEQUAL;
4085 else if (p[1] == '~')
4086 type = TYPE_NOMATCH;
4087 break;
4088 case '>': if (p[1] != '=')
4090 type = TYPE_GREATER;
4091 len = 1;
4093 else
4094 type = TYPE_GEQUAL;
4095 break;
4096 case '<': if (p[1] != '=')
4098 type = TYPE_SMALLER;
4099 len = 1;
4101 else
4102 type = TYPE_SEQUAL;
4103 break;
4104 case 'i': if (p[1] == 's')
4106 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4107 len = 5;
4108 if (!vim_isIDc(p[len]))
4110 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4111 type_is = TRUE;
4114 break;
4118 * If there is a comparitive operator, use it.
4120 if (type != TYPE_UNKNOWN)
4122 /* extra question mark appended: ignore case */
4123 if (p[len] == '?')
4125 ic = TRUE;
4126 ++len;
4128 /* extra '#' appended: match case */
4129 else if (p[len] == '#')
4131 ic = FALSE;
4132 ++len;
4134 /* nothing appened: use 'ignorecase' */
4135 else
4136 ic = p_ic;
4139 * Get the second variable.
4141 *arg = skipwhite(p + len);
4142 if (eval5(arg, &var2, evaluate) == FAIL)
4144 clear_tv(rettv);
4145 return FAIL;
4148 if (evaluate)
4150 if (type_is && rettv->v_type != var2.v_type)
4152 /* For "is" a different type always means FALSE, for "notis"
4153 * it means TRUE. */
4154 n1 = (type == TYPE_NEQUAL);
4156 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4158 if (type_is)
4160 n1 = (rettv->v_type == var2.v_type
4161 && rettv->vval.v_list == var2.vval.v_list);
4162 if (type == TYPE_NEQUAL)
4163 n1 = !n1;
4165 else if (rettv->v_type != var2.v_type
4166 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4168 if (rettv->v_type != var2.v_type)
4169 EMSG(_("E691: Can only compare List with List"));
4170 else
4171 EMSG(_("E692: Invalid operation for Lists"));
4172 clear_tv(rettv);
4173 clear_tv(&var2);
4174 return FAIL;
4176 else
4178 /* Compare two Lists for being equal or unequal. */
4179 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
4180 if (type == TYPE_NEQUAL)
4181 n1 = !n1;
4185 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4187 if (type_is)
4189 n1 = (rettv->v_type == var2.v_type
4190 && rettv->vval.v_dict == var2.vval.v_dict);
4191 if (type == TYPE_NEQUAL)
4192 n1 = !n1;
4194 else if (rettv->v_type != var2.v_type
4195 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4197 if (rettv->v_type != var2.v_type)
4198 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4199 else
4200 EMSG(_("E736: Invalid operation for Dictionary"));
4201 clear_tv(rettv);
4202 clear_tv(&var2);
4203 return FAIL;
4205 else
4207 /* Compare two Dictionaries for being equal or unequal. */
4208 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4209 if (type == TYPE_NEQUAL)
4210 n1 = !n1;
4214 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4216 if (rettv->v_type != var2.v_type
4217 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4219 if (rettv->v_type != var2.v_type)
4220 EMSG(_("E693: Can only compare Funcref with Funcref"));
4221 else
4222 EMSG(_("E694: Invalid operation for Funcrefs"));
4223 clear_tv(rettv);
4224 clear_tv(&var2);
4225 return FAIL;
4227 else
4229 /* Compare two Funcrefs for being equal or unequal. */
4230 if (rettv->vval.v_string == NULL
4231 || var2.vval.v_string == NULL)
4232 n1 = FALSE;
4233 else
4234 n1 = STRCMP(rettv->vval.v_string,
4235 var2.vval.v_string) == 0;
4236 if (type == TYPE_NEQUAL)
4237 n1 = !n1;
4242 * If one of the two variables is a number, compare as a number.
4243 * When using "=~" or "!~", always compare as string.
4245 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4246 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4248 n1 = get_tv_number(rettv);
4249 n2 = get_tv_number(&var2);
4250 switch (type)
4252 case TYPE_EQUAL: n1 = (n1 == n2); break;
4253 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4254 case TYPE_GREATER: n1 = (n1 > n2); break;
4255 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4256 case TYPE_SMALLER: n1 = (n1 < n2); break;
4257 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4258 case TYPE_UNKNOWN:
4259 case TYPE_MATCH:
4260 case TYPE_NOMATCH: break; /* avoid gcc warning */
4263 else
4265 s1 = get_tv_string_buf(rettv, buf1);
4266 s2 = get_tv_string_buf(&var2, buf2);
4267 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4268 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4269 else
4270 i = 0;
4271 n1 = FALSE;
4272 switch (type)
4274 case TYPE_EQUAL: n1 = (i == 0); break;
4275 case TYPE_NEQUAL: n1 = (i != 0); break;
4276 case TYPE_GREATER: n1 = (i > 0); break;
4277 case TYPE_GEQUAL: n1 = (i >= 0); break;
4278 case TYPE_SMALLER: n1 = (i < 0); break;
4279 case TYPE_SEQUAL: n1 = (i <= 0); break;
4281 case TYPE_MATCH:
4282 case TYPE_NOMATCH:
4283 /* avoid 'l' flag in 'cpoptions' */
4284 save_cpo = p_cpo;
4285 p_cpo = (char_u *)"";
4286 regmatch.regprog = vim_regcomp(s2,
4287 RE_MAGIC + RE_STRING);
4288 regmatch.rm_ic = ic;
4289 if (regmatch.regprog != NULL)
4291 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4292 vim_free(regmatch.regprog);
4293 if (type == TYPE_NOMATCH)
4294 n1 = !n1;
4296 p_cpo = save_cpo;
4297 break;
4299 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4302 clear_tv(rettv);
4303 clear_tv(&var2);
4304 rettv->v_type = VAR_NUMBER;
4305 rettv->vval.v_number = n1;
4309 return OK;
4313 * Handle fourth level expression:
4314 * + number addition
4315 * - number subtraction
4316 * . string concatenation
4318 * "arg" must point to the first non-white of the expression.
4319 * "arg" is advanced to the next non-white after the recognized expression.
4321 * Return OK or FAIL.
4323 static int
4324 eval5(arg, rettv, evaluate)
4325 char_u **arg;
4326 typval_T *rettv;
4327 int evaluate;
4329 typval_T var2;
4330 typval_T var3;
4331 int op;
4332 long n1, n2;
4333 char_u *s1, *s2;
4334 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4335 char_u *p;
4338 * Get the first variable.
4340 if (eval6(arg, rettv, evaluate) == FAIL)
4341 return FAIL;
4344 * Repeat computing, until no '+', '-' or '.' is following.
4346 for (;;)
4348 op = **arg;
4349 if (op != '+' && op != '-' && op != '.')
4350 break;
4352 if (op != '+' || rettv->v_type != VAR_LIST)
4354 /* For "list + ...", an illegal use of the first operand as
4355 * a number cannot be determined before evaluating the 2nd
4356 * operand: if this is also a list, all is ok.
4357 * For "something . ...", "something - ..." or "non-list + ...",
4358 * we know that the first operand needs to be a string or number
4359 * without evaluating the 2nd operand. So check before to avoid
4360 * side effects after an error. */
4361 if (evaluate && get_tv_string_chk(rettv) == NULL)
4363 clear_tv(rettv);
4364 return FAIL;
4369 * Get the second variable.
4371 *arg = skipwhite(*arg + 1);
4372 if (eval6(arg, &var2, evaluate) == FAIL)
4374 clear_tv(rettv);
4375 return FAIL;
4378 if (evaluate)
4381 * Compute the result.
4383 if (op == '.')
4385 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4386 s2 = get_tv_string_buf_chk(&var2, buf2);
4387 if (s2 == NULL) /* type error ? */
4389 clear_tv(rettv);
4390 clear_tv(&var2);
4391 return FAIL;
4393 p = concat_str(s1, s2);
4394 clear_tv(rettv);
4395 rettv->v_type = VAR_STRING;
4396 rettv->vval.v_string = p;
4398 else if (op == '+' && rettv->v_type == VAR_LIST
4399 && var2.v_type == VAR_LIST)
4401 /* concatenate Lists */
4402 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4403 &var3) == FAIL)
4405 clear_tv(rettv);
4406 clear_tv(&var2);
4407 return FAIL;
4409 clear_tv(rettv);
4410 *rettv = var3;
4412 else
4414 int error = FALSE;
4416 n1 = get_tv_number_chk(rettv, &error);
4417 if (error)
4419 /* This can only happen for "list + non-list".
4420 * For "non-list + ..." or "something - ...", we returned
4421 * before evaluating the 2nd operand. */
4422 clear_tv(rettv);
4423 return FAIL;
4425 n2 = get_tv_number_chk(&var2, &error);
4426 if (error)
4428 clear_tv(rettv);
4429 clear_tv(&var2);
4430 return FAIL;
4432 clear_tv(rettv);
4433 if (op == '+')
4434 n1 = n1 + n2;
4435 else
4436 n1 = n1 - n2;
4437 rettv->v_type = VAR_NUMBER;
4438 rettv->vval.v_number = n1;
4440 clear_tv(&var2);
4443 return OK;
4447 * Handle fifth level expression:
4448 * * number multiplication
4449 * / number division
4450 * % number modulo
4452 * "arg" must point to the first non-white of the expression.
4453 * "arg" is advanced to the next non-white after the recognized expression.
4455 * Return OK or FAIL.
4457 static int
4458 eval6(arg, rettv, evaluate)
4459 char_u **arg;
4460 typval_T *rettv;
4461 int evaluate;
4463 typval_T var2;
4464 int op;
4465 long n1, n2;
4466 int error = FALSE;
4469 * Get the first variable.
4471 if (eval7(arg, rettv, evaluate) == FAIL)
4472 return FAIL;
4475 * Repeat computing, until no '*', '/' or '%' is following.
4477 for (;;)
4479 op = **arg;
4480 if (op != '*' && op != '/' && op != '%')
4481 break;
4483 if (evaluate)
4485 n1 = get_tv_number_chk(rettv, &error);
4486 clear_tv(rettv);
4487 if (error)
4488 return FAIL;
4490 else
4491 n1 = 0;
4494 * Get the second variable.
4496 *arg = skipwhite(*arg + 1);
4497 if (eval7(arg, &var2, evaluate) == FAIL)
4498 return FAIL;
4500 if (evaluate)
4502 n2 = get_tv_number_chk(&var2, &error);
4503 clear_tv(&var2);
4504 if (error)
4505 return FAIL;
4508 * Compute the result.
4510 if (op == '*')
4511 n1 = n1 * n2;
4512 else if (op == '/')
4514 if (n2 == 0) /* give an error message? */
4515 n1 = 0x7fffffffL;
4516 else
4517 n1 = n1 / n2;
4519 else
4521 if (n2 == 0) /* give an error message? */
4522 n1 = 0;
4523 else
4524 n1 = n1 % n2;
4526 rettv->v_type = VAR_NUMBER;
4527 rettv->vval.v_number = n1;
4531 return OK;
4535 * Handle sixth level expression:
4536 * number number constant
4537 * "string" string constant
4538 * 'string' literal string constant
4539 * &option-name option value
4540 * @r register contents
4541 * identifier variable value
4542 * function() function call
4543 * $VAR environment variable
4544 * (expression) nested expression
4545 * [expr, expr] List
4546 * {key: val, key: val} Dictionary
4548 * Also handle:
4549 * ! in front logical NOT
4550 * - in front unary minus
4551 * + in front unary plus (ignored)
4552 * trailing [] subscript in String or List
4553 * trailing .name entry in Dictionary
4555 * "arg" must point to the first non-white of the expression.
4556 * "arg" is advanced to the next non-white after the recognized expression.
4558 * Return OK or FAIL.
4560 static int
4561 eval7(arg, rettv, evaluate)
4562 char_u **arg;
4563 typval_T *rettv;
4564 int evaluate;
4566 long n;
4567 int len;
4568 char_u *s;
4569 int val;
4570 char_u *start_leader, *end_leader;
4571 int ret = OK;
4572 char_u *alias;
4575 * Initialise variable so that clear_tv() can't mistake this for a
4576 * string and free a string that isn't there.
4578 rettv->v_type = VAR_UNKNOWN;
4581 * Skip '!' and '-' characters. They are handled later.
4583 start_leader = *arg;
4584 while (**arg == '!' || **arg == '-' || **arg == '+')
4585 *arg = skipwhite(*arg + 1);
4586 end_leader = *arg;
4588 switch (**arg)
4591 * Number constant.
4593 case '0':
4594 case '1':
4595 case '2':
4596 case '3':
4597 case '4':
4598 case '5':
4599 case '6':
4600 case '7':
4601 case '8':
4602 case '9':
4603 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4604 *arg += len;
4605 if (evaluate)
4607 rettv->v_type = VAR_NUMBER;
4608 rettv->vval.v_number = n;
4610 break;
4613 * String constant: "string".
4615 case '"': ret = get_string_tv(arg, rettv, evaluate);
4616 break;
4619 * Literal string constant: 'str''ing'.
4621 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
4622 break;
4625 * List: [expr, expr]
4627 case '[': ret = get_list_tv(arg, rettv, evaluate);
4628 break;
4631 * Dictionary: {key: val, key: val}
4633 case '{': ret = get_dict_tv(arg, rettv, evaluate);
4634 break;
4637 * Option value: &name
4639 case '&': ret = get_option_tv(arg, rettv, evaluate);
4640 break;
4643 * Environment variable: $VAR.
4645 case '$': ret = get_env_tv(arg, rettv, evaluate);
4646 break;
4649 * Register contents: @r.
4651 case '@': ++*arg;
4652 if (evaluate)
4654 rettv->v_type = VAR_STRING;
4655 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4657 if (**arg != NUL)
4658 ++*arg;
4659 break;
4662 * nested expression: (expression).
4664 case '(': *arg = skipwhite(*arg + 1);
4665 ret = eval1(arg, rettv, evaluate); /* recursive! */
4666 if (**arg == ')')
4667 ++*arg;
4668 else if (ret == OK)
4670 EMSG(_("E110: Missing ')'"));
4671 clear_tv(rettv);
4672 ret = FAIL;
4674 break;
4676 default: ret = NOTDONE;
4677 break;
4680 if (ret == NOTDONE)
4683 * Must be a variable or function name.
4684 * Can also be a curly-braces kind of name: {expr}.
4686 s = *arg;
4687 len = get_name_len(arg, &alias, evaluate, TRUE);
4688 if (alias != NULL)
4689 s = alias;
4691 if (len <= 0)
4692 ret = FAIL;
4693 else
4695 if (**arg == '(') /* recursive! */
4697 /* If "s" is the name of a variable of type VAR_FUNC
4698 * use its contents. */
4699 s = deref_func_name(s, &len);
4701 /* Invoke the function. */
4702 ret = get_func_tv(s, len, rettv, arg,
4703 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
4704 &len, evaluate, NULL);
4705 /* Stop the expression evaluation when immediately
4706 * aborting on error, or when an interrupt occurred or
4707 * an exception was thrown but not caught. */
4708 if (aborting())
4710 if (ret == OK)
4711 clear_tv(rettv);
4712 ret = FAIL;
4715 else if (evaluate)
4716 ret = get_var_tv(s, len, rettv, TRUE);
4717 else
4718 ret = OK;
4721 if (alias != NULL)
4722 vim_free(alias);
4725 *arg = skipwhite(*arg);
4727 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
4728 * expr(expr). */
4729 if (ret == OK)
4730 ret = handle_subscript(arg, rettv, evaluate, TRUE);
4733 * Apply logical NOT and unary '-', from right to left, ignore '+'.
4735 if (ret == OK && evaluate && end_leader > start_leader)
4737 int error = FALSE;
4739 val = get_tv_number_chk(rettv, &error);
4740 if (error)
4742 clear_tv(rettv);
4743 ret = FAIL;
4745 else
4747 while (end_leader > start_leader)
4749 --end_leader;
4750 if (*end_leader == '!')
4751 val = !val;
4752 else if (*end_leader == '-')
4753 val = -val;
4755 clear_tv(rettv);
4756 rettv->v_type = VAR_NUMBER;
4757 rettv->vval.v_number = val;
4761 return ret;
4765 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
4766 * "*arg" points to the '[' or '.'.
4767 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
4769 static int
4770 eval_index(arg, rettv, evaluate, verbose)
4771 char_u **arg;
4772 typval_T *rettv;
4773 int evaluate;
4774 int verbose; /* give error messages */
4776 int empty1 = FALSE, empty2 = FALSE;
4777 typval_T var1, var2;
4778 long n1, n2 = 0;
4779 long len = -1;
4780 int range = FALSE;
4781 char_u *s;
4782 char_u *key = NULL;
4784 if (rettv->v_type == VAR_FUNC)
4786 if (verbose)
4787 EMSG(_("E695: Cannot index a Funcref"));
4788 return FAIL;
4791 if (**arg == '.')
4794 * dict.name
4796 key = *arg + 1;
4797 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
4799 if (len == 0)
4800 return FAIL;
4801 *arg = skipwhite(key + len);
4803 else
4806 * something[idx]
4808 * Get the (first) variable from inside the [].
4810 *arg = skipwhite(*arg + 1);
4811 if (**arg == ':')
4812 empty1 = TRUE;
4813 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
4814 return FAIL;
4815 else if (evaluate && get_tv_string_chk(&var1) == NULL)
4817 /* not a number or string */
4818 clear_tv(&var1);
4819 return FAIL;
4823 * Get the second variable from inside the [:].
4825 if (**arg == ':')
4827 range = TRUE;
4828 *arg = skipwhite(*arg + 1);
4829 if (**arg == ']')
4830 empty2 = TRUE;
4831 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
4833 if (!empty1)
4834 clear_tv(&var1);
4835 return FAIL;
4837 else if (evaluate && get_tv_string_chk(&var2) == NULL)
4839 /* not a number or string */
4840 if (!empty1)
4841 clear_tv(&var1);
4842 clear_tv(&var2);
4843 return FAIL;
4847 /* Check for the ']'. */
4848 if (**arg != ']')
4850 if (verbose)
4851 EMSG(_(e_missbrac));
4852 clear_tv(&var1);
4853 if (range)
4854 clear_tv(&var2);
4855 return FAIL;
4857 *arg = skipwhite(*arg + 1); /* skip the ']' */
4860 if (evaluate)
4862 n1 = 0;
4863 if (!empty1 && rettv->v_type != VAR_DICT)
4865 n1 = get_tv_number(&var1);
4866 clear_tv(&var1);
4868 if (range)
4870 if (empty2)
4871 n2 = -1;
4872 else
4874 n2 = get_tv_number(&var2);
4875 clear_tv(&var2);
4879 switch (rettv->v_type)
4881 case VAR_NUMBER:
4882 case VAR_STRING:
4883 s = get_tv_string(rettv);
4884 len = (long)STRLEN(s);
4885 if (range)
4887 /* The resulting variable is a substring. If the indexes
4888 * are out of range the result is empty. */
4889 if (n1 < 0)
4891 n1 = len + n1;
4892 if (n1 < 0)
4893 n1 = 0;
4895 if (n2 < 0)
4896 n2 = len + n2;
4897 else if (n2 >= len)
4898 n2 = len;
4899 if (n1 >= len || n2 < 0 || n1 > n2)
4900 s = NULL;
4901 else
4902 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
4904 else
4906 /* The resulting variable is a string of a single
4907 * character. If the index is too big or negative the
4908 * result is empty. */
4909 if (n1 >= len || n1 < 0)
4910 s = NULL;
4911 else
4912 s = vim_strnsave(s + n1, 1);
4914 clear_tv(rettv);
4915 rettv->v_type = VAR_STRING;
4916 rettv->vval.v_string = s;
4917 break;
4919 case VAR_LIST:
4920 len = list_len(rettv->vval.v_list);
4921 if (n1 < 0)
4922 n1 = len + n1;
4923 if (!empty1 && (n1 < 0 || n1 >= len))
4925 /* For a range we allow invalid values and return an empty
4926 * list. A list index out of range is an error. */
4927 if (!range)
4929 if (verbose)
4930 EMSGN(_(e_listidx), n1);
4931 return FAIL;
4933 n1 = len;
4935 if (range)
4937 list_T *l;
4938 listitem_T *item;
4940 if (n2 < 0)
4941 n2 = len + n2;
4942 else if (n2 >= len)
4943 n2 = len - 1;
4944 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
4945 n2 = -1;
4946 l = list_alloc();
4947 if (l == NULL)
4948 return FAIL;
4949 for (item = list_find(rettv->vval.v_list, n1);
4950 n1 <= n2; ++n1)
4952 if (list_append_tv(l, &item->li_tv) == FAIL)
4954 list_free(l, TRUE);
4955 return FAIL;
4957 item = item->li_next;
4959 clear_tv(rettv);
4960 rettv->v_type = VAR_LIST;
4961 rettv->vval.v_list = l;
4962 ++l->lv_refcount;
4964 else
4966 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
4967 clear_tv(rettv);
4968 *rettv = var1;
4970 break;
4972 case VAR_DICT:
4973 if (range)
4975 if (verbose)
4976 EMSG(_(e_dictrange));
4977 if (len == -1)
4978 clear_tv(&var1);
4979 return FAIL;
4982 dictitem_T *item;
4984 if (len == -1)
4986 key = get_tv_string(&var1);
4987 if (*key == NUL)
4989 if (verbose)
4990 EMSG(_(e_emptykey));
4991 clear_tv(&var1);
4992 return FAIL;
4996 item = dict_find(rettv->vval.v_dict, key, (int)len);
4998 if (item == NULL && verbose)
4999 EMSG2(_(e_dictkey), key);
5000 if (len == -1)
5001 clear_tv(&var1);
5002 if (item == NULL)
5003 return FAIL;
5005 copy_tv(&item->di_tv, &var1);
5006 clear_tv(rettv);
5007 *rettv = var1;
5009 break;
5013 return OK;
5017 * Get an option value.
5018 * "arg" points to the '&' or '+' before the option name.
5019 * "arg" is advanced to character after the option name.
5020 * Return OK or FAIL.
5022 static int
5023 get_option_tv(arg, rettv, evaluate)
5024 char_u **arg;
5025 typval_T *rettv; /* when NULL, only check if option exists */
5026 int evaluate;
5028 char_u *option_end;
5029 long numval;
5030 char_u *stringval;
5031 int opt_type;
5032 int c;
5033 int working = (**arg == '+'); /* has("+option") */
5034 int ret = OK;
5035 int opt_flags;
5038 * Isolate the option name and find its value.
5040 option_end = find_option_end(arg, &opt_flags);
5041 if (option_end == NULL)
5043 if (rettv != NULL)
5044 EMSG2(_("E112: Option name missing: %s"), *arg);
5045 return FAIL;
5048 if (!evaluate)
5050 *arg = option_end;
5051 return OK;
5054 c = *option_end;
5055 *option_end = NUL;
5056 opt_type = get_option_value(*arg, &numval,
5057 rettv == NULL ? NULL : &stringval, opt_flags);
5059 if (opt_type == -3) /* invalid name */
5061 if (rettv != NULL)
5062 EMSG2(_("E113: Unknown option: %s"), *arg);
5063 ret = FAIL;
5065 else if (rettv != NULL)
5067 if (opt_type == -2) /* hidden string option */
5069 rettv->v_type = VAR_STRING;
5070 rettv->vval.v_string = NULL;
5072 else if (opt_type == -1) /* hidden number option */
5074 rettv->v_type = VAR_NUMBER;
5075 rettv->vval.v_number = 0;
5077 else if (opt_type == 1) /* number option */
5079 rettv->v_type = VAR_NUMBER;
5080 rettv->vval.v_number = numval;
5082 else /* string option */
5084 rettv->v_type = VAR_STRING;
5085 rettv->vval.v_string = stringval;
5088 else if (working && (opt_type == -2 || opt_type == -1))
5089 ret = FAIL;
5091 *option_end = c; /* put back for error messages */
5092 *arg = option_end;
5094 return ret;
5098 * Allocate a variable for a string constant.
5099 * Return OK or FAIL.
5101 static int
5102 get_string_tv(arg, rettv, evaluate)
5103 char_u **arg;
5104 typval_T *rettv;
5105 int evaluate;
5107 char_u *p;
5108 char_u *name;
5109 int extra = 0;
5112 * Find the end of the string, skipping backslashed characters.
5114 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5116 if (*p == '\\' && p[1] != NUL)
5118 ++p;
5119 /* A "\<x>" form occupies at least 4 characters, and produces up
5120 * to 6 characters: reserve space for 2 extra */
5121 if (*p == '<')
5122 extra += 2;
5126 if (*p != '"')
5128 EMSG2(_("E114: Missing quote: %s"), *arg);
5129 return FAIL;
5132 /* If only parsing, set *arg and return here */
5133 if (!evaluate)
5135 *arg = p + 1;
5136 return OK;
5140 * Copy the string into allocated memory, handling backslashed
5141 * characters.
5143 name = alloc((unsigned)(p - *arg + extra));
5144 if (name == NULL)
5145 return FAIL;
5146 rettv->v_type = VAR_STRING;
5147 rettv->vval.v_string = name;
5149 for (p = *arg + 1; *p != NUL && *p != '"'; )
5151 if (*p == '\\')
5153 switch (*++p)
5155 case 'b': *name++ = BS; ++p; break;
5156 case 'e': *name++ = ESC; ++p; break;
5157 case 'f': *name++ = FF; ++p; break;
5158 case 'n': *name++ = NL; ++p; break;
5159 case 'r': *name++ = CAR; ++p; break;
5160 case 't': *name++ = TAB; ++p; break;
5162 case 'X': /* hex: "\x1", "\x12" */
5163 case 'x':
5164 case 'u': /* Unicode: "\u0023" */
5165 case 'U':
5166 if (vim_isxdigit(p[1]))
5168 int n, nr;
5169 int c = toupper(*p);
5171 if (c == 'X')
5172 n = 2;
5173 else
5174 n = 4;
5175 nr = 0;
5176 while (--n >= 0 && vim_isxdigit(p[1]))
5178 ++p;
5179 nr = (nr << 4) + hex2nr(*p);
5181 ++p;
5182 #ifdef FEAT_MBYTE
5183 /* For "\u" store the number according to
5184 * 'encoding'. */
5185 if (c != 'X')
5186 name += (*mb_char2bytes)(nr, name);
5187 else
5188 #endif
5189 *name++ = nr;
5191 break;
5193 /* octal: "\1", "\12", "\123" */
5194 case '0':
5195 case '1':
5196 case '2':
5197 case '3':
5198 case '4':
5199 case '5':
5200 case '6':
5201 case '7': *name = *p++ - '0';
5202 if (*p >= '0' && *p <= '7')
5204 *name = (*name << 3) + *p++ - '0';
5205 if (*p >= '0' && *p <= '7')
5206 *name = (*name << 3) + *p++ - '0';
5208 ++name;
5209 break;
5211 /* Special key, e.g.: "\<C-W>" */
5212 case '<': extra = trans_special(&p, name, TRUE);
5213 if (extra != 0)
5215 name += extra;
5216 break;
5218 /* FALLTHROUGH */
5220 default: MB_COPY_CHAR(p, name);
5221 break;
5224 else
5225 MB_COPY_CHAR(p, name);
5228 *name = NUL;
5229 *arg = p + 1;
5231 return OK;
5235 * Allocate a variable for a 'str''ing' constant.
5236 * Return OK or FAIL.
5238 static int
5239 get_lit_string_tv(arg, rettv, evaluate)
5240 char_u **arg;
5241 typval_T *rettv;
5242 int evaluate;
5244 char_u *p;
5245 char_u *str;
5246 int reduce = 0;
5249 * Find the end of the string, skipping ''.
5251 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5253 if (*p == '\'')
5255 if (p[1] != '\'')
5256 break;
5257 ++reduce;
5258 ++p;
5262 if (*p != '\'')
5264 EMSG2(_("E115: Missing quote: %s"), *arg);
5265 return FAIL;
5268 /* If only parsing return after setting "*arg" */
5269 if (!evaluate)
5271 *arg = p + 1;
5272 return OK;
5276 * Copy the string into allocated memory, handling '' to ' reduction.
5278 str = alloc((unsigned)((p - *arg) - reduce));
5279 if (str == NULL)
5280 return FAIL;
5281 rettv->v_type = VAR_STRING;
5282 rettv->vval.v_string = str;
5284 for (p = *arg + 1; *p != NUL; )
5286 if (*p == '\'')
5288 if (p[1] != '\'')
5289 break;
5290 ++p;
5292 MB_COPY_CHAR(p, str);
5294 *str = NUL;
5295 *arg = p + 1;
5297 return OK;
5301 * Allocate a variable for a List and fill it from "*arg".
5302 * Return OK or FAIL.
5304 static int
5305 get_list_tv(arg, rettv, evaluate)
5306 char_u **arg;
5307 typval_T *rettv;
5308 int evaluate;
5310 list_T *l = NULL;
5311 typval_T tv;
5312 listitem_T *item;
5314 if (evaluate)
5316 l = list_alloc();
5317 if (l == NULL)
5318 return FAIL;
5321 *arg = skipwhite(*arg + 1);
5322 while (**arg != ']' && **arg != NUL)
5324 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5325 goto failret;
5326 if (evaluate)
5328 item = listitem_alloc();
5329 if (item != NULL)
5331 item->li_tv = tv;
5332 item->li_tv.v_lock = 0;
5333 list_append(l, item);
5335 else
5336 clear_tv(&tv);
5339 if (**arg == ']')
5340 break;
5341 if (**arg != ',')
5343 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5344 goto failret;
5346 *arg = skipwhite(*arg + 1);
5349 if (**arg != ']')
5351 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5352 failret:
5353 if (evaluate)
5354 list_free(l, TRUE);
5355 return FAIL;
5358 *arg = skipwhite(*arg + 1);
5359 if (evaluate)
5361 rettv->v_type = VAR_LIST;
5362 rettv->vval.v_list = l;
5363 ++l->lv_refcount;
5366 return OK;
5370 * Allocate an empty header for a list.
5371 * Caller should take care of the reference count.
5373 list_T *
5374 list_alloc()
5376 list_T *l;
5378 l = (list_T *)alloc_clear(sizeof(list_T));
5379 if (l != NULL)
5381 /* Prepend the list to the list of lists for garbage collection. */
5382 if (first_list != NULL)
5383 first_list->lv_used_prev = l;
5384 l->lv_used_prev = NULL;
5385 l->lv_used_next = first_list;
5386 first_list = l;
5388 return l;
5392 * Allocate an empty list for a return value.
5393 * Returns OK or FAIL.
5395 static int
5396 rettv_list_alloc(rettv)
5397 typval_T *rettv;
5399 list_T *l = list_alloc();
5401 if (l == NULL)
5402 return FAIL;
5404 rettv->vval.v_list = l;
5405 rettv->v_type = VAR_LIST;
5406 ++l->lv_refcount;
5407 return OK;
5411 * Unreference a list: decrement the reference count and free it when it
5412 * becomes zero.
5414 void
5415 list_unref(l)
5416 list_T *l;
5418 if (l != NULL && --l->lv_refcount <= 0)
5419 list_free(l, TRUE);
5423 * Free a list, including all items it points to.
5424 * Ignores the reference count.
5426 void
5427 list_free(l, recurse)
5428 list_T *l;
5429 int recurse; /* Free Lists and Dictionaries recursively. */
5431 listitem_T *item;
5433 /* Remove the list from the list of lists for garbage collection. */
5434 if (l->lv_used_prev == NULL)
5435 first_list = l->lv_used_next;
5436 else
5437 l->lv_used_prev->lv_used_next = l->lv_used_next;
5438 if (l->lv_used_next != NULL)
5439 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5441 for (item = l->lv_first; item != NULL; item = l->lv_first)
5443 /* Remove the item before deleting it. */
5444 l->lv_first = item->li_next;
5445 if (recurse || (item->li_tv.v_type != VAR_LIST
5446 && item->li_tv.v_type != VAR_DICT))
5447 clear_tv(&item->li_tv);
5448 vim_free(item);
5450 vim_free(l);
5454 * Allocate a list item.
5456 static listitem_T *
5457 listitem_alloc()
5459 return (listitem_T *)alloc(sizeof(listitem_T));
5463 * Free a list item. Also clears the value. Does not notify watchers.
5465 static void
5466 listitem_free(item)
5467 listitem_T *item;
5469 clear_tv(&item->li_tv);
5470 vim_free(item);
5474 * Remove a list item from a List and free it. Also clears the value.
5476 static void
5477 listitem_remove(l, item)
5478 list_T *l;
5479 listitem_T *item;
5481 list_remove(l, item, item);
5482 listitem_free(item);
5486 * Get the number of items in a list.
5488 static long
5489 list_len(l)
5490 list_T *l;
5492 if (l == NULL)
5493 return 0L;
5494 return l->lv_len;
5498 * Return TRUE when two lists have exactly the same values.
5500 static int
5501 list_equal(l1, l2, ic)
5502 list_T *l1;
5503 list_T *l2;
5504 int ic; /* ignore case for strings */
5506 listitem_T *item1, *item2;
5508 if (l1 == l2)
5509 return TRUE;
5510 if (list_len(l1) != list_len(l2))
5511 return FALSE;
5513 for (item1 = l1->lv_first, item2 = l2->lv_first;
5514 item1 != NULL && item2 != NULL;
5515 item1 = item1->li_next, item2 = item2->li_next)
5516 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5517 return FALSE;
5518 return item1 == NULL && item2 == NULL;
5521 #if defined(FEAT_PYTHON) || defined(PROTO) || defined(FEAT_GUI_MACVIM)
5523 * Return the dictitem that an entry in a hashtable points to.
5525 dictitem_T *
5526 dict_lookup(hi)
5527 hashitem_T *hi;
5529 return HI2DI(hi);
5531 #endif
5534 * Return TRUE when two dictionaries have exactly the same key/values.
5536 static int
5537 dict_equal(d1, d2, ic)
5538 dict_T *d1;
5539 dict_T *d2;
5540 int ic; /* ignore case for strings */
5542 hashitem_T *hi;
5543 dictitem_T *item2;
5544 int todo;
5546 if (d1 == d2)
5547 return TRUE;
5548 if (dict_len(d1) != dict_len(d2))
5549 return FALSE;
5551 todo = (int)d1->dv_hashtab.ht_used;
5552 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5554 if (!HASHITEM_EMPTY(hi))
5556 item2 = dict_find(d2, hi->hi_key, -1);
5557 if (item2 == NULL)
5558 return FALSE;
5559 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5560 return FALSE;
5561 --todo;
5564 return TRUE;
5568 * Return TRUE if "tv1" and "tv2" have the same value.
5569 * Compares the items just like "==" would compare them, but strings and
5570 * numbers are different.
5572 static int
5573 tv_equal(tv1, tv2, ic)
5574 typval_T *tv1;
5575 typval_T *tv2;
5576 int ic; /* ignore case */
5578 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5579 char_u *s1, *s2;
5580 static int recursive = 0; /* cach recursive loops */
5581 int r;
5583 if (tv1->v_type != tv2->v_type)
5584 return FALSE;
5585 /* Catch lists and dicts that have an endless loop by limiting
5586 * recursiveness to 1000. We guess they are equal then. */
5587 if (recursive >= 1000)
5588 return TRUE;
5590 switch (tv1->v_type)
5592 case VAR_LIST:
5593 ++recursive;
5594 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5595 --recursive;
5596 return r;
5598 case VAR_DICT:
5599 ++recursive;
5600 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5601 --recursive;
5602 return r;
5604 case VAR_FUNC:
5605 return (tv1->vval.v_string != NULL
5606 && tv2->vval.v_string != NULL
5607 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5609 case VAR_NUMBER:
5610 return tv1->vval.v_number == tv2->vval.v_number;
5612 case VAR_STRING:
5613 s1 = get_tv_string_buf(tv1, buf1);
5614 s2 = get_tv_string_buf(tv2, buf2);
5615 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5618 EMSG2(_(e_intern2), "tv_equal()");
5619 return TRUE;
5623 * Locate item with index "n" in list "l" and return it.
5624 * A negative index is counted from the end; -1 is the last item.
5625 * Returns NULL when "n" is out of range.
5627 static listitem_T *
5628 list_find(l, n)
5629 list_T *l;
5630 long n;
5632 listitem_T *item;
5633 long idx;
5635 if (l == NULL)
5636 return NULL;
5638 /* Negative index is relative to the end. */
5639 if (n < 0)
5640 n = l->lv_len + n;
5642 /* Check for index out of range. */
5643 if (n < 0 || n >= l->lv_len)
5644 return NULL;
5646 /* When there is a cached index may start search from there. */
5647 if (l->lv_idx_item != NULL)
5649 if (n < l->lv_idx / 2)
5651 /* closest to the start of the list */
5652 item = l->lv_first;
5653 idx = 0;
5655 else if (n > (l->lv_idx + l->lv_len) / 2)
5657 /* closest to the end of the list */
5658 item = l->lv_last;
5659 idx = l->lv_len - 1;
5661 else
5663 /* closest to the cached index */
5664 item = l->lv_idx_item;
5665 idx = l->lv_idx;
5668 else
5670 if (n < l->lv_len / 2)
5672 /* closest to the start of the list */
5673 item = l->lv_first;
5674 idx = 0;
5676 else
5678 /* closest to the end of the list */
5679 item = l->lv_last;
5680 idx = l->lv_len - 1;
5684 while (n > idx)
5686 /* search forward */
5687 item = item->li_next;
5688 ++idx;
5690 while (n < idx)
5692 /* search backward */
5693 item = item->li_prev;
5694 --idx;
5697 /* cache the used index */
5698 l->lv_idx = idx;
5699 l->lv_idx_item = item;
5701 return item;
5705 * Get list item "l[idx]" as a number.
5707 static long
5708 list_find_nr(l, idx, errorp)
5709 list_T *l;
5710 long idx;
5711 int *errorp; /* set to TRUE when something wrong */
5713 listitem_T *li;
5715 li = list_find(l, idx);
5716 if (li == NULL)
5718 if (errorp != NULL)
5719 *errorp = TRUE;
5720 return -1L;
5722 return get_tv_number_chk(&li->li_tv, errorp);
5726 * Locate "item" list "l" and return its index.
5727 * Returns -1 when "item" is not in the list.
5729 static long
5730 list_idx_of_item(l, item)
5731 list_T *l;
5732 listitem_T *item;
5734 long idx = 0;
5735 listitem_T *li;
5737 if (l == NULL)
5738 return -1;
5739 idx = 0;
5740 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
5741 ++idx;
5742 if (li == NULL)
5743 return -1;
5744 return idx;
5748 * Append item "item" to the end of list "l".
5750 static void
5751 list_append(l, item)
5752 list_T *l;
5753 listitem_T *item;
5755 if (l->lv_last == NULL)
5757 /* empty list */
5758 l->lv_first = item;
5759 l->lv_last = item;
5760 item->li_prev = NULL;
5762 else
5764 l->lv_last->li_next = item;
5765 item->li_prev = l->lv_last;
5766 l->lv_last = item;
5768 ++l->lv_len;
5769 item->li_next = NULL;
5773 * Append typval_T "tv" to the end of list "l".
5774 * Return FAIL when out of memory.
5776 static int
5777 list_append_tv(l, tv)
5778 list_T *l;
5779 typval_T *tv;
5781 listitem_T *li = listitem_alloc();
5783 if (li == NULL)
5784 return FAIL;
5785 copy_tv(tv, &li->li_tv);
5786 list_append(l, li);
5787 return OK;
5791 * Add a dictionary to a list. Used by getqflist().
5792 * Return FAIL when out of memory.
5795 list_append_dict(list, dict)
5796 list_T *list;
5797 dict_T *dict;
5799 listitem_T *li = listitem_alloc();
5801 if (li == NULL)
5802 return FAIL;
5803 li->li_tv.v_type = VAR_DICT;
5804 li->li_tv.v_lock = 0;
5805 li->li_tv.vval.v_dict = dict;
5806 list_append(list, li);
5807 ++dict->dv_refcount;
5808 return OK;
5812 * Make a copy of "str" and append it as an item to list "l".
5813 * When "len" >= 0 use "str[len]".
5814 * Returns FAIL when out of memory.
5816 static int
5817 list_append_string(l, str, len)
5818 list_T *l;
5819 char_u *str;
5820 int len;
5822 listitem_T *li = listitem_alloc();
5824 if (li == NULL)
5825 return FAIL;
5826 list_append(l, li);
5827 li->li_tv.v_type = VAR_STRING;
5828 li->li_tv.v_lock = 0;
5829 if (str == NULL)
5830 li->li_tv.vval.v_string = NULL;
5831 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
5832 : vim_strsave(str))) == NULL)
5833 return FAIL;
5834 return OK;
5838 * Append "n" to list "l".
5839 * Returns FAIL when out of memory.
5841 static int
5842 list_append_number(l, n)
5843 list_T *l;
5844 varnumber_T n;
5846 listitem_T *li;
5848 li = listitem_alloc();
5849 if (li == NULL)
5850 return FAIL;
5851 li->li_tv.v_type = VAR_NUMBER;
5852 li->li_tv.v_lock = 0;
5853 li->li_tv.vval.v_number = n;
5854 list_append(l, li);
5855 return OK;
5859 * Insert typval_T "tv" in list "l" before "item".
5860 * If "item" is NULL append at the end.
5861 * Return FAIL when out of memory.
5863 static int
5864 list_insert_tv(l, tv, item)
5865 list_T *l;
5866 typval_T *tv;
5867 listitem_T *item;
5869 listitem_T *ni = listitem_alloc();
5871 if (ni == NULL)
5872 return FAIL;
5873 copy_tv(tv, &ni->li_tv);
5874 if (item == NULL)
5875 /* Append new item at end of list. */
5876 list_append(l, ni);
5877 else
5879 /* Insert new item before existing item. */
5880 ni->li_prev = item->li_prev;
5881 ni->li_next = item;
5882 if (item->li_prev == NULL)
5884 l->lv_first = ni;
5885 ++l->lv_idx;
5887 else
5889 item->li_prev->li_next = ni;
5890 l->lv_idx_item = NULL;
5892 item->li_prev = ni;
5893 ++l->lv_len;
5895 return OK;
5899 * Extend "l1" with "l2".
5900 * If "bef" is NULL append at the end, otherwise insert before this item.
5901 * Returns FAIL when out of memory.
5903 static int
5904 list_extend(l1, l2, bef)
5905 list_T *l1;
5906 list_T *l2;
5907 listitem_T *bef;
5909 listitem_T *item;
5911 for (item = l2->lv_first; item != NULL; item = item->li_next)
5912 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
5913 return FAIL;
5914 return OK;
5918 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
5919 * Return FAIL when out of memory.
5921 static int
5922 list_concat(l1, l2, tv)
5923 list_T *l1;
5924 list_T *l2;
5925 typval_T *tv;
5927 list_T *l;
5929 /* make a copy of the first list. */
5930 l = list_copy(l1, FALSE, 0);
5931 if (l == NULL)
5932 return FAIL;
5933 tv->v_type = VAR_LIST;
5934 tv->vval.v_list = l;
5936 /* append all items from the second list */
5937 return list_extend(l, l2, NULL);
5941 * Make a copy of list "orig". Shallow if "deep" is FALSE.
5942 * The refcount of the new list is set to 1.
5943 * See item_copy() for "copyID".
5944 * Returns NULL when out of memory.
5946 static list_T *
5947 list_copy(orig, deep, copyID)
5948 list_T *orig;
5949 int deep;
5950 int copyID;
5952 list_T *copy;
5953 listitem_T *item;
5954 listitem_T *ni;
5956 if (orig == NULL)
5957 return NULL;
5959 copy = list_alloc();
5960 if (copy != NULL)
5962 if (copyID != 0)
5964 /* Do this before adding the items, because one of the items may
5965 * refer back to this list. */
5966 orig->lv_copyID = copyID;
5967 orig->lv_copylist = copy;
5969 for (item = orig->lv_first; item != NULL && !got_int;
5970 item = item->li_next)
5972 ni = listitem_alloc();
5973 if (ni == NULL)
5974 break;
5975 if (deep)
5977 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
5979 vim_free(ni);
5980 break;
5983 else
5984 copy_tv(&item->li_tv, &ni->li_tv);
5985 list_append(copy, ni);
5987 ++copy->lv_refcount;
5988 if (item != NULL)
5990 list_unref(copy);
5991 copy = NULL;
5995 return copy;
5999 * Remove items "item" to "item2" from list "l".
6000 * Does not free the listitem or the value!
6002 static void
6003 list_remove(l, item, item2)
6004 list_T *l;
6005 listitem_T *item;
6006 listitem_T *item2;
6008 listitem_T *ip;
6010 /* notify watchers */
6011 for (ip = item; ip != NULL; ip = ip->li_next)
6013 --l->lv_len;
6014 list_fix_watch(l, ip);
6015 if (ip == item2)
6016 break;
6019 if (item2->li_next == NULL)
6020 l->lv_last = item->li_prev;
6021 else
6022 item2->li_next->li_prev = item->li_prev;
6023 if (item->li_prev == NULL)
6024 l->lv_first = item2->li_next;
6025 else
6026 item->li_prev->li_next = item2->li_next;
6027 l->lv_idx_item = NULL;
6031 * Return an allocated string with the string representation of a list.
6032 * May return NULL.
6034 static char_u *
6035 list2string(tv, copyID)
6036 typval_T *tv;
6037 int copyID;
6039 garray_T ga;
6041 if (tv->vval.v_list == NULL)
6042 return NULL;
6043 ga_init2(&ga, (int)sizeof(char), 80);
6044 ga_append(&ga, '[');
6045 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6047 vim_free(ga.ga_data);
6048 return NULL;
6050 ga_append(&ga, ']');
6051 ga_append(&ga, NUL);
6052 return (char_u *)ga.ga_data;
6056 * Join list "l" into a string in "*gap", using separator "sep".
6057 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6058 * Return FAIL or OK.
6060 static int
6061 list_join(gap, l, sep, echo, copyID)
6062 garray_T *gap;
6063 list_T *l;
6064 char_u *sep;
6065 int echo;
6066 int copyID;
6068 int first = TRUE;
6069 char_u *tofree;
6070 char_u numbuf[NUMBUFLEN];
6071 listitem_T *item;
6072 char_u *s;
6074 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6076 if (first)
6077 first = FALSE;
6078 else
6079 ga_concat(gap, sep);
6081 if (echo)
6082 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6083 else
6084 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6085 if (s != NULL)
6086 ga_concat(gap, s);
6087 vim_free(tofree);
6088 if (s == NULL)
6089 return FAIL;
6091 return OK;
6095 * Garbage collection for lists and dictionaries.
6097 * We use reference counts to be able to free most items right away when they
6098 * are no longer used. But for composite items it's possible that it becomes
6099 * unused while the reference count is > 0: When there is a recursive
6100 * reference. Example:
6101 * :let l = [1, 2, 3]
6102 * :let d = {9: l}
6103 * :let l[1] = d
6105 * Since this is quite unusual we handle this with garbage collection: every
6106 * once in a while find out which lists and dicts are not referenced from any
6107 * variable.
6109 * Here is a good reference text about garbage collection (refers to Python
6110 * but it applies to all reference-counting mechanisms):
6111 * http://python.ca/nas/python/gc/
6115 * Do garbage collection for lists and dicts.
6116 * Return TRUE if some memory was freed.
6119 garbage_collect()
6121 dict_T *dd;
6122 list_T *ll;
6123 int copyID = ++current_copyID;
6124 buf_T *buf;
6125 win_T *wp;
6126 int i;
6127 funccall_T *fc;
6128 int did_free = FALSE;
6129 #ifdef FEAT_WINDOWS
6130 tabpage_T *tp;
6131 #endif
6133 /* Only do this once. */
6134 want_garbage_collect = FALSE;
6135 may_garbage_collect = FALSE;
6136 garbage_collect_at_exit = FALSE;
6139 * 1. Go through all accessible variables and mark all lists and dicts
6140 * with copyID.
6142 /* script-local variables */
6143 for (i = 1; i <= ga_scripts.ga_len; ++i)
6144 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6146 /* buffer-local variables */
6147 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6148 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6150 /* window-local variables */
6151 FOR_ALL_TAB_WINDOWS(tp, wp)
6152 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6154 #ifdef FEAT_WINDOWS
6155 /* tabpage-local variables */
6156 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6157 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6158 #endif
6160 /* global variables */
6161 set_ref_in_ht(&globvarht, copyID);
6163 /* function-local variables */
6164 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6166 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6167 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6171 * 2. Go through the list of dicts and free items without the copyID.
6173 for (dd = first_dict; dd != NULL; )
6174 if (dd->dv_copyID != copyID)
6176 /* Free the Dictionary and ordinary items it contains, but don't
6177 * recurse into Lists and Dictionaries, they will be in the list
6178 * of dicts or list of lists. */
6179 dict_free(dd, FALSE);
6180 did_free = TRUE;
6182 /* restart, next dict may also have been freed */
6183 dd = first_dict;
6185 else
6186 dd = dd->dv_used_next;
6189 * 3. Go through the list of lists and free items without the copyID.
6190 * But don't free a list that has a watcher (used in a for loop), these
6191 * are not referenced anywhere.
6193 for (ll = first_list; ll != NULL; )
6194 if (ll->lv_copyID != copyID && ll->lv_watch == NULL)
6196 /* Free the List and ordinary items it contains, but don't recurse
6197 * into Lists and Dictionaries, they will be in the list of dicts
6198 * or list of lists. */
6199 list_free(ll, FALSE);
6200 did_free = TRUE;
6202 /* restart, next list may also have been freed */
6203 ll = first_list;
6205 else
6206 ll = ll->lv_used_next;
6208 return did_free;
6212 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6214 static void
6215 set_ref_in_ht(ht, copyID)
6216 hashtab_T *ht;
6217 int copyID;
6219 int todo;
6220 hashitem_T *hi;
6222 todo = (int)ht->ht_used;
6223 for (hi = ht->ht_array; todo > 0; ++hi)
6224 if (!HASHITEM_EMPTY(hi))
6226 --todo;
6227 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6232 * Mark all lists and dicts referenced through list "l" with "copyID".
6234 static void
6235 set_ref_in_list(l, copyID)
6236 list_T *l;
6237 int copyID;
6239 listitem_T *li;
6241 for (li = l->lv_first; li != NULL; li = li->li_next)
6242 set_ref_in_item(&li->li_tv, copyID);
6246 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6248 static void
6249 set_ref_in_item(tv, copyID)
6250 typval_T *tv;
6251 int copyID;
6253 dict_T *dd;
6254 list_T *ll;
6256 switch (tv->v_type)
6258 case VAR_DICT:
6259 dd = tv->vval.v_dict;
6260 if (dd->dv_copyID != copyID)
6262 /* Didn't see this dict yet. */
6263 dd->dv_copyID = copyID;
6264 set_ref_in_ht(&dd->dv_hashtab, copyID);
6266 break;
6268 case VAR_LIST:
6269 ll = tv->vval.v_list;
6270 if (ll->lv_copyID != copyID)
6272 /* Didn't see this list yet. */
6273 ll->lv_copyID = copyID;
6274 set_ref_in_list(ll, copyID);
6276 break;
6278 return;
6282 * Allocate an empty header for a dictionary.
6284 dict_T *
6285 dict_alloc()
6287 dict_T *d;
6289 d = (dict_T *)alloc(sizeof(dict_T));
6290 if (d != NULL)
6292 /* Add the list to the list of dicts for garbage collection. */
6293 if (first_dict != NULL)
6294 first_dict->dv_used_prev = d;
6295 d->dv_used_next = first_dict;
6296 d->dv_used_prev = NULL;
6297 first_dict = d;
6299 hash_init(&d->dv_hashtab);
6300 d->dv_lock = 0;
6301 d->dv_refcount = 0;
6302 d->dv_copyID = 0;
6304 return d;
6308 * Unreference a Dictionary: decrement the reference count and free it when it
6309 * becomes zero.
6311 static void
6312 dict_unref(d)
6313 dict_T *d;
6315 if (d != NULL && --d->dv_refcount <= 0)
6316 dict_free(d, TRUE);
6320 * Free a Dictionary, including all items it contains.
6321 * Ignores the reference count.
6323 static void
6324 dict_free(d, recurse)
6325 dict_T *d;
6326 int recurse; /* Free Lists and Dictionaries recursively. */
6328 int todo;
6329 hashitem_T *hi;
6330 dictitem_T *di;
6332 /* Remove the dict from the list of dicts for garbage collection. */
6333 if (d->dv_used_prev == NULL)
6334 first_dict = d->dv_used_next;
6335 else
6336 d->dv_used_prev->dv_used_next = d->dv_used_next;
6337 if (d->dv_used_next != NULL)
6338 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6340 /* Lock the hashtab, we don't want it to resize while freeing items. */
6341 hash_lock(&d->dv_hashtab);
6342 todo = (int)d->dv_hashtab.ht_used;
6343 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6345 if (!HASHITEM_EMPTY(hi))
6347 /* Remove the item before deleting it, just in case there is
6348 * something recursive causing trouble. */
6349 di = HI2DI(hi);
6350 hash_remove(&d->dv_hashtab, hi);
6351 if (recurse || (di->di_tv.v_type != VAR_LIST
6352 && di->di_tv.v_type != VAR_DICT))
6353 clear_tv(&di->di_tv);
6354 vim_free(di);
6355 --todo;
6358 hash_clear(&d->dv_hashtab);
6359 vim_free(d);
6363 * Allocate a Dictionary item.
6364 * The "key" is copied to the new item.
6365 * Note that the value of the item "di_tv" still needs to be initialized!
6366 * Returns NULL when out of memory.
6368 static dictitem_T *
6369 dictitem_alloc(key)
6370 char_u *key;
6372 dictitem_T *di;
6374 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6375 if (di != NULL)
6377 STRCPY(di->di_key, key);
6378 di->di_flags = 0;
6380 return di;
6384 * Make a copy of a Dictionary item.
6386 static dictitem_T *
6387 dictitem_copy(org)
6388 dictitem_T *org;
6390 dictitem_T *di;
6392 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6393 + STRLEN(org->di_key)));
6394 if (di != NULL)
6396 STRCPY(di->di_key, org->di_key);
6397 di->di_flags = 0;
6398 copy_tv(&org->di_tv, &di->di_tv);
6400 return di;
6404 * Remove item "item" from Dictionary "dict" and free it.
6406 static void
6407 dictitem_remove(dict, item)
6408 dict_T *dict;
6409 dictitem_T *item;
6411 hashitem_T *hi;
6413 hi = hash_find(&dict->dv_hashtab, item->di_key);
6414 if (HASHITEM_EMPTY(hi))
6415 EMSG2(_(e_intern2), "dictitem_remove()");
6416 else
6417 hash_remove(&dict->dv_hashtab, hi);
6418 dictitem_free(item);
6422 * Free a dict item. Also clears the value.
6424 static void
6425 dictitem_free(item)
6426 dictitem_T *item;
6428 clear_tv(&item->di_tv);
6429 vim_free(item);
6433 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6434 * The refcount of the new dict is set to 1.
6435 * See item_copy() for "copyID".
6436 * Returns NULL when out of memory.
6438 static dict_T *
6439 dict_copy(orig, deep, copyID)
6440 dict_T *orig;
6441 int deep;
6442 int copyID;
6444 dict_T *copy;
6445 dictitem_T *di;
6446 int todo;
6447 hashitem_T *hi;
6449 if (orig == NULL)
6450 return NULL;
6452 copy = dict_alloc();
6453 if (copy != NULL)
6455 if (copyID != 0)
6457 orig->dv_copyID = copyID;
6458 orig->dv_copydict = copy;
6460 todo = (int)orig->dv_hashtab.ht_used;
6461 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6463 if (!HASHITEM_EMPTY(hi))
6465 --todo;
6467 di = dictitem_alloc(hi->hi_key);
6468 if (di == NULL)
6469 break;
6470 if (deep)
6472 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6473 copyID) == FAIL)
6475 vim_free(di);
6476 break;
6479 else
6480 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6481 if (dict_add(copy, di) == FAIL)
6483 dictitem_free(di);
6484 break;
6489 ++copy->dv_refcount;
6490 if (todo > 0)
6492 dict_unref(copy);
6493 copy = NULL;
6497 return copy;
6501 * Add item "item" to Dictionary "d".
6502 * Returns FAIL when out of memory and when key already existed.
6504 static int
6505 dict_add(d, item)
6506 dict_T *d;
6507 dictitem_T *item;
6509 return hash_add(&d->dv_hashtab, item->di_key);
6513 * Add a number or string entry to dictionary "d".
6514 * When "str" is NULL use number "nr", otherwise use "str".
6515 * Returns FAIL when out of memory and when key already exists.
6518 dict_add_nr_str(d, key, nr, str)
6519 dict_T *d;
6520 char *key;
6521 long nr;
6522 char_u *str;
6524 dictitem_T *item;
6526 item = dictitem_alloc((char_u *)key);
6527 if (item == NULL)
6528 return FAIL;
6529 item->di_tv.v_lock = 0;
6530 if (str == NULL)
6532 item->di_tv.v_type = VAR_NUMBER;
6533 item->di_tv.vval.v_number = nr;
6535 else
6537 item->di_tv.v_type = VAR_STRING;
6538 item->di_tv.vval.v_string = vim_strsave(str);
6540 if (dict_add(d, item) == FAIL)
6542 dictitem_free(item);
6543 return FAIL;
6545 return OK;
6549 * Get the number of items in a Dictionary.
6551 static long
6552 dict_len(d)
6553 dict_T *d;
6555 if (d == NULL)
6556 return 0L;
6557 return (long)d->dv_hashtab.ht_used;
6561 * Find item "key[len]" in Dictionary "d".
6562 * If "len" is negative use strlen(key).
6563 * Returns NULL when not found.
6565 static dictitem_T *
6566 dict_find(d, key, len)
6567 dict_T *d;
6568 char_u *key;
6569 int len;
6571 #define AKEYLEN 200
6572 char_u buf[AKEYLEN];
6573 char_u *akey;
6574 char_u *tofree = NULL;
6575 hashitem_T *hi;
6577 if (len < 0)
6578 akey = key;
6579 else if (len >= AKEYLEN)
6581 tofree = akey = vim_strnsave(key, len);
6582 if (akey == NULL)
6583 return NULL;
6585 else
6587 /* Avoid a malloc/free by using buf[]. */
6588 vim_strncpy(buf, key, len);
6589 akey = buf;
6592 hi = hash_find(&d->dv_hashtab, akey);
6593 vim_free(tofree);
6594 if (HASHITEM_EMPTY(hi))
6595 return NULL;
6596 return HI2DI(hi);
6600 * Get a string item from a dictionary.
6601 * When "save" is TRUE allocate memory for it.
6602 * Returns NULL if the entry doesn't exist or out of memory.
6604 char_u *
6605 get_dict_string(d, key, save)
6606 dict_T *d;
6607 char_u *key;
6608 int save;
6610 dictitem_T *di;
6611 char_u *s;
6613 di = dict_find(d, key, -1);
6614 if (di == NULL)
6615 return NULL;
6616 s = get_tv_string(&di->di_tv);
6617 if (save && s != NULL)
6618 s = vim_strsave(s);
6619 return s;
6623 * Get a number item from a dictionary.
6624 * Returns 0 if the entry doesn't exist or out of memory.
6626 long
6627 get_dict_number(d, key)
6628 dict_T *d;
6629 char_u *key;
6631 dictitem_T *di;
6633 di = dict_find(d, key, -1);
6634 if (di == NULL)
6635 return 0;
6636 return get_tv_number(&di->di_tv);
6640 * Return an allocated string with the string representation of a Dictionary.
6641 * May return NULL.
6643 static char_u *
6644 dict2string(tv, copyID)
6645 typval_T *tv;
6646 int copyID;
6648 garray_T ga;
6649 int first = TRUE;
6650 char_u *tofree;
6651 char_u numbuf[NUMBUFLEN];
6652 hashitem_T *hi;
6653 char_u *s;
6654 dict_T *d;
6655 int todo;
6657 if ((d = tv->vval.v_dict) == NULL)
6658 return NULL;
6659 ga_init2(&ga, (int)sizeof(char), 80);
6660 ga_append(&ga, '{');
6662 todo = (int)d->dv_hashtab.ht_used;
6663 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6665 if (!HASHITEM_EMPTY(hi))
6667 --todo;
6669 if (first)
6670 first = FALSE;
6671 else
6672 ga_concat(&ga, (char_u *)", ");
6674 tofree = string_quote(hi->hi_key, FALSE);
6675 if (tofree != NULL)
6677 ga_concat(&ga, tofree);
6678 vim_free(tofree);
6680 ga_concat(&ga, (char_u *)": ");
6681 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
6682 if (s != NULL)
6683 ga_concat(&ga, s);
6684 vim_free(tofree);
6685 if (s == NULL)
6686 break;
6689 if (todo > 0)
6691 vim_free(ga.ga_data);
6692 return NULL;
6695 ga_append(&ga, '}');
6696 ga_append(&ga, NUL);
6697 return (char_u *)ga.ga_data;
6701 * Allocate a variable for a Dictionary and fill it from "*arg".
6702 * Return OK or FAIL. Returns NOTDONE for {expr}.
6704 static int
6705 get_dict_tv(arg, rettv, evaluate)
6706 char_u **arg;
6707 typval_T *rettv;
6708 int evaluate;
6710 dict_T *d = NULL;
6711 typval_T tvkey;
6712 typval_T tv;
6713 char_u *key = NULL;
6714 dictitem_T *item;
6715 char_u *start = skipwhite(*arg + 1);
6716 char_u buf[NUMBUFLEN];
6719 * First check if it's not a curly-braces thing: {expr}.
6720 * Must do this without evaluating, otherwise a function may be called
6721 * twice. Unfortunately this means we need to call eval1() twice for the
6722 * first item.
6723 * But {} is an empty Dictionary.
6725 if (*start != '}')
6727 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
6728 return FAIL;
6729 if (*start == '}')
6730 return NOTDONE;
6733 if (evaluate)
6735 d = dict_alloc();
6736 if (d == NULL)
6737 return FAIL;
6739 tvkey.v_type = VAR_UNKNOWN;
6740 tv.v_type = VAR_UNKNOWN;
6742 *arg = skipwhite(*arg + 1);
6743 while (**arg != '}' && **arg != NUL)
6745 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
6746 goto failret;
6747 if (**arg != ':')
6749 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
6750 clear_tv(&tvkey);
6751 goto failret;
6753 if (evaluate)
6755 key = get_tv_string_buf_chk(&tvkey, buf);
6756 if (key == NULL || *key == NUL)
6758 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
6759 if (key != NULL)
6760 EMSG(_(e_emptykey));
6761 clear_tv(&tvkey);
6762 goto failret;
6766 *arg = skipwhite(*arg + 1);
6767 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
6769 if (evaluate)
6770 clear_tv(&tvkey);
6771 goto failret;
6773 if (evaluate)
6775 item = dict_find(d, key, -1);
6776 if (item != NULL)
6778 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
6779 clear_tv(&tvkey);
6780 clear_tv(&tv);
6781 goto failret;
6783 item = dictitem_alloc(key);
6784 clear_tv(&tvkey);
6785 if (item != NULL)
6787 item->di_tv = tv;
6788 item->di_tv.v_lock = 0;
6789 if (dict_add(d, item) == FAIL)
6790 dictitem_free(item);
6794 if (**arg == '}')
6795 break;
6796 if (**arg != ',')
6798 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
6799 goto failret;
6801 *arg = skipwhite(*arg + 1);
6804 if (**arg != '}')
6806 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
6807 failret:
6808 if (evaluate)
6809 dict_free(d, TRUE);
6810 return FAIL;
6813 *arg = skipwhite(*arg + 1);
6814 if (evaluate)
6816 rettv->v_type = VAR_DICT;
6817 rettv->vval.v_dict = d;
6818 ++d->dv_refcount;
6821 return OK;
6825 * Return a string with the string representation of a variable.
6826 * If the memory is allocated "tofree" is set to it, otherwise NULL.
6827 * "numbuf" is used for a number.
6828 * Does not put quotes around strings, as ":echo" displays values.
6829 * When "copyID" is not NULL replace recursive lists and dicts with "...".
6830 * May return NULL.
6832 static char_u *
6833 echo_string(tv, tofree, numbuf, copyID)
6834 typval_T *tv;
6835 char_u **tofree;
6836 char_u *numbuf;
6837 int copyID;
6839 static int recurse = 0;
6840 char_u *r = NULL;
6842 if (recurse >= DICT_MAXNEST)
6844 EMSG(_("E724: variable nested too deep for displaying"));
6845 *tofree = NULL;
6846 return NULL;
6848 ++recurse;
6850 switch (tv->v_type)
6852 case VAR_FUNC:
6853 *tofree = NULL;
6854 r = tv->vval.v_string;
6855 break;
6857 case VAR_LIST:
6858 if (tv->vval.v_list == NULL)
6860 *tofree = NULL;
6861 r = NULL;
6863 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
6865 *tofree = NULL;
6866 r = (char_u *)"[...]";
6868 else
6870 tv->vval.v_list->lv_copyID = copyID;
6871 *tofree = list2string(tv, copyID);
6872 r = *tofree;
6874 break;
6876 case VAR_DICT:
6877 if (tv->vval.v_dict == NULL)
6879 *tofree = NULL;
6880 r = NULL;
6882 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
6884 *tofree = NULL;
6885 r = (char_u *)"{...}";
6887 else
6889 tv->vval.v_dict->dv_copyID = copyID;
6890 *tofree = dict2string(tv, copyID);
6891 r = *tofree;
6893 break;
6895 case VAR_STRING:
6896 case VAR_NUMBER:
6897 *tofree = NULL;
6898 r = get_tv_string_buf(tv, numbuf);
6899 break;
6901 default:
6902 EMSG2(_(e_intern2), "echo_string()");
6903 *tofree = NULL;
6906 --recurse;
6907 return r;
6911 * Return a string with the string representation of a variable.
6912 * If the memory is allocated "tofree" is set to it, otherwise NULL.
6913 * "numbuf" is used for a number.
6914 * Puts quotes around strings, so that they can be parsed back by eval().
6915 * May return NULL.
6917 static char_u *
6918 tv2string(tv, tofree, numbuf, copyID)
6919 typval_T *tv;
6920 char_u **tofree;
6921 char_u *numbuf;
6922 int copyID;
6924 switch (tv->v_type)
6926 case VAR_FUNC:
6927 *tofree = string_quote(tv->vval.v_string, TRUE);
6928 return *tofree;
6929 case VAR_STRING:
6930 *tofree = string_quote(tv->vval.v_string, FALSE);
6931 return *tofree;
6932 case VAR_NUMBER:
6933 case VAR_LIST:
6934 case VAR_DICT:
6935 break;
6936 default:
6937 EMSG2(_(e_intern2), "tv2string()");
6939 return echo_string(tv, tofree, numbuf, copyID);
6943 * Return string "str" in ' quotes, doubling ' characters.
6944 * If "str" is NULL an empty string is assumed.
6945 * If "function" is TRUE make it function('string').
6947 static char_u *
6948 string_quote(str, function)
6949 char_u *str;
6950 int function;
6952 unsigned len;
6953 char_u *p, *r, *s;
6955 len = (function ? 13 : 3);
6956 if (str != NULL)
6958 len += (unsigned)STRLEN(str);
6959 for (p = str; *p != NUL; mb_ptr_adv(p))
6960 if (*p == '\'')
6961 ++len;
6963 s = r = alloc(len);
6964 if (r != NULL)
6966 if (function)
6968 STRCPY(r, "function('");
6969 r += 10;
6971 else
6972 *r++ = '\'';
6973 if (str != NULL)
6974 for (p = str; *p != NUL; )
6976 if (*p == '\'')
6977 *r++ = '\'';
6978 MB_COPY_CHAR(p, r);
6980 *r++ = '\'';
6981 if (function)
6982 *r++ = ')';
6983 *r++ = NUL;
6985 return s;
6989 * Get the value of an environment variable.
6990 * "arg" is pointing to the '$'. It is advanced to after the name.
6991 * If the environment variable was not set, silently assume it is empty.
6992 * Always return OK.
6994 static int
6995 get_env_tv(arg, rettv, evaluate)
6996 char_u **arg;
6997 typval_T *rettv;
6998 int evaluate;
7000 char_u *string = NULL;
7001 int len;
7002 int cc;
7003 char_u *name;
7004 int mustfree = FALSE;
7006 ++*arg;
7007 name = *arg;
7008 len = get_env_len(arg);
7009 if (evaluate)
7011 if (len != 0)
7013 cc = name[len];
7014 name[len] = NUL;
7015 /* first try vim_getenv(), fast for normal environment vars */
7016 string = vim_getenv(name, &mustfree);
7017 if (string != NULL && *string != NUL)
7019 if (!mustfree)
7020 string = vim_strsave(string);
7022 else
7024 if (mustfree)
7025 vim_free(string);
7027 /* next try expanding things like $VIM and ${HOME} */
7028 string = expand_env_save(name - 1);
7029 if (string != NULL && *string == '$')
7031 vim_free(string);
7032 string = NULL;
7035 name[len] = cc;
7037 rettv->v_type = VAR_STRING;
7038 rettv->vval.v_string = string;
7041 return OK;
7045 * Array with names and number of arguments of all internal functions
7046 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7048 static struct fst
7050 char *f_name; /* function name */
7051 char f_min_argc; /* minimal number of arguments */
7052 char f_max_argc; /* maximal number of arguments */
7053 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7054 /* implementation of function */
7055 } functions[] =
7057 {"add", 2, 2, f_add},
7058 {"append", 2, 2, f_append},
7059 {"argc", 0, 0, f_argc},
7060 {"argidx", 0, 0, f_argidx},
7061 {"argv", 0, 1, f_argv},
7062 {"browse", 4, 4, f_browse},
7063 {"browsedir", 2, 2, f_browsedir},
7064 {"bufexists", 1, 1, f_bufexists},
7065 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7066 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7067 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7068 {"buflisted", 1, 1, f_buflisted},
7069 {"bufloaded", 1, 1, f_bufloaded},
7070 {"bufname", 1, 1, f_bufname},
7071 {"bufnr", 1, 2, f_bufnr},
7072 {"bufwinnr", 1, 1, f_bufwinnr},
7073 {"byte2line", 1, 1, f_byte2line},
7074 {"byteidx", 2, 2, f_byteidx},
7075 {"call", 2, 3, f_call},
7076 {"changenr", 0, 0, f_changenr},
7077 {"char2nr", 1, 1, f_char2nr},
7078 {"cindent", 1, 1, f_cindent},
7079 {"clearmatches", 0, 0, f_clearmatches},
7080 {"col", 1, 1, f_col},
7081 #if defined(FEAT_INS_EXPAND)
7082 {"complete", 2, 2, f_complete},
7083 {"complete_add", 1, 1, f_complete_add},
7084 {"complete_check", 0, 0, f_complete_check},
7085 #endif
7086 {"confirm", 1, 4, f_confirm},
7087 {"copy", 1, 1, f_copy},
7088 {"count", 2, 4, f_count},
7089 {"cscope_connection",0,3, f_cscope_connection},
7090 {"cursor", 1, 3, f_cursor},
7091 {"deepcopy", 1, 2, f_deepcopy},
7092 {"delete", 1, 1, f_delete},
7093 {"did_filetype", 0, 0, f_did_filetype},
7094 {"diff_filler", 1, 1, f_diff_filler},
7095 {"diff_hlID", 2, 2, f_diff_hlID},
7096 {"empty", 1, 1, f_empty},
7097 {"escape", 2, 2, f_escape},
7098 {"eval", 1, 1, f_eval},
7099 {"eventhandler", 0, 0, f_eventhandler},
7100 {"executable", 1, 1, f_executable},
7101 {"exists", 1, 1, f_exists},
7102 {"expand", 1, 2, f_expand},
7103 {"extend", 2, 3, f_extend},
7104 {"feedkeys", 1, 2, f_feedkeys},
7105 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7106 {"filereadable", 1, 1, f_filereadable},
7107 {"filewritable", 1, 1, f_filewritable},
7108 {"filter", 2, 2, f_filter},
7109 {"finddir", 1, 3, f_finddir},
7110 {"findfile", 1, 3, f_findfile},
7111 {"fnameescape", 1, 1, f_fnameescape},
7112 {"fnamemodify", 2, 2, f_fnamemodify},
7113 {"foldclosed", 1, 1, f_foldclosed},
7114 {"foldclosedend", 1, 1, f_foldclosedend},
7115 {"foldlevel", 1, 1, f_foldlevel},
7116 {"foldtext", 0, 0, f_foldtext},
7117 {"foldtextresult", 1, 1, f_foldtextresult},
7118 {"foreground", 0, 0, f_foreground},
7119 {"function", 1, 1, f_function},
7120 {"garbagecollect", 0, 1, f_garbagecollect},
7121 {"get", 2, 3, f_get},
7122 {"getbufline", 2, 3, f_getbufline},
7123 {"getbufvar", 2, 2, f_getbufvar},
7124 {"getchar", 0, 1, f_getchar},
7125 {"getcharmod", 0, 0, f_getcharmod},
7126 {"getcmdline", 0, 0, f_getcmdline},
7127 {"getcmdpos", 0, 0, f_getcmdpos},
7128 {"getcmdtype", 0, 0, f_getcmdtype},
7129 {"getcwd", 0, 0, f_getcwd},
7130 {"getfontname", 0, 1, f_getfontname},
7131 {"getfperm", 1, 1, f_getfperm},
7132 {"getfsize", 1, 1, f_getfsize},
7133 {"getftime", 1, 1, f_getftime},
7134 {"getftype", 1, 1, f_getftype},
7135 {"getline", 1, 2, f_getline},
7136 {"getloclist", 1, 1, f_getqflist},
7137 {"getmatches", 0, 0, f_getmatches},
7138 {"getpid", 0, 0, f_getpid},
7139 {"getpos", 1, 1, f_getpos},
7140 {"getqflist", 0, 0, f_getqflist},
7141 {"getreg", 0, 2, f_getreg},
7142 {"getregtype", 0, 1, f_getregtype},
7143 {"gettabwinvar", 3, 3, f_gettabwinvar},
7144 {"getwinposx", 0, 0, f_getwinposx},
7145 {"getwinposy", 0, 0, f_getwinposy},
7146 {"getwinvar", 2, 2, f_getwinvar},
7147 {"glob", 1, 1, f_glob},
7148 {"globpath", 2, 2, f_globpath},
7149 {"has", 1, 1, f_has},
7150 {"has_key", 2, 2, f_has_key},
7151 {"haslocaldir", 0, 0, f_haslocaldir},
7152 {"hasmapto", 1, 3, f_hasmapto},
7153 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7154 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7155 {"histadd", 2, 2, f_histadd},
7156 {"histdel", 1, 2, f_histdel},
7157 {"histget", 1, 2, f_histget},
7158 {"histnr", 1, 1, f_histnr},
7159 {"hlID", 1, 1, f_hlID},
7160 {"hlexists", 1, 1, f_hlexists},
7161 {"hostname", 0, 0, f_hostname},
7162 {"iconv", 3, 3, f_iconv},
7163 {"indent", 1, 1, f_indent},
7164 {"index", 2, 4, f_index},
7165 {"input", 1, 3, f_input},
7166 {"inputdialog", 1, 3, f_inputdialog},
7167 {"inputlist", 1, 1, f_inputlist},
7168 {"inputrestore", 0, 0, f_inputrestore},
7169 {"inputsave", 0, 0, f_inputsave},
7170 {"inputsecret", 1, 2, f_inputsecret},
7171 {"insert", 2, 3, f_insert},
7172 {"isdirectory", 1, 1, f_isdirectory},
7173 {"islocked", 1, 1, f_islocked},
7174 {"items", 1, 1, f_items},
7175 {"join", 1, 2, f_join},
7176 {"keys", 1, 1, f_keys},
7177 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7178 {"len", 1, 1, f_len},
7179 {"libcall", 3, 3, f_libcall},
7180 {"libcallnr", 3, 3, f_libcallnr},
7181 {"line", 1, 1, f_line},
7182 {"line2byte", 1, 1, f_line2byte},
7183 {"lispindent", 1, 1, f_lispindent},
7184 {"localtime", 0, 0, f_localtime},
7185 {"map", 2, 2, f_map},
7186 {"maparg", 1, 3, f_maparg},
7187 {"mapcheck", 1, 3, f_mapcheck},
7188 {"match", 2, 4, f_match},
7189 {"matchadd", 2, 4, f_matchadd},
7190 {"matcharg", 1, 1, f_matcharg},
7191 {"matchdelete", 1, 1, f_matchdelete},
7192 {"matchend", 2, 4, f_matchend},
7193 {"matchlist", 2, 4, f_matchlist},
7194 {"matchstr", 2, 4, f_matchstr},
7195 {"max", 1, 1, f_max},
7196 {"min", 1, 1, f_min},
7197 #ifdef vim_mkdir
7198 {"mkdir", 1, 3, f_mkdir},
7199 #endif
7200 {"mode", 0, 0, f_mode},
7201 {"nextnonblank", 1, 1, f_nextnonblank},
7202 {"nr2char", 1, 1, f_nr2char},
7203 {"pathshorten", 1, 1, f_pathshorten},
7204 {"prevnonblank", 1, 1, f_prevnonblank},
7205 {"printf", 2, 19, f_printf},
7206 {"pumvisible", 0, 0, f_pumvisible},
7207 {"range", 1, 3, f_range},
7208 {"readfile", 1, 3, f_readfile},
7209 {"reltime", 0, 2, f_reltime},
7210 {"reltimestr", 1, 1, f_reltimestr},
7211 {"remote_expr", 2, 3, f_remote_expr},
7212 {"remote_foreground", 1, 1, f_remote_foreground},
7213 {"remote_peek", 1, 2, f_remote_peek},
7214 {"remote_read", 1, 1, f_remote_read},
7215 {"remote_send", 2, 3, f_remote_send},
7216 {"remove", 2, 3, f_remove},
7217 {"rename", 2, 2, f_rename},
7218 {"repeat", 2, 2, f_repeat},
7219 {"resolve", 1, 1, f_resolve},
7220 {"reverse", 1, 1, f_reverse},
7221 {"search", 1, 4, f_search},
7222 {"searchdecl", 1, 3, f_searchdecl},
7223 {"searchpair", 3, 7, f_searchpair},
7224 {"searchpairpos", 3, 7, f_searchpairpos},
7225 {"searchpos", 1, 4, f_searchpos},
7226 {"server2client", 2, 2, f_server2client},
7227 {"serverlist", 0, 0, f_serverlist},
7228 {"setbufvar", 3, 3, f_setbufvar},
7229 {"setcmdpos", 1, 1, f_setcmdpos},
7230 {"setline", 2, 2, f_setline},
7231 {"setloclist", 2, 3, f_setloclist},
7232 {"setmatches", 1, 1, f_setmatches},
7233 {"setpos", 2, 2, f_setpos},
7234 {"setqflist", 1, 2, f_setqflist},
7235 {"setreg", 2, 3, f_setreg},
7236 {"settabwinvar", 4, 4, f_settabwinvar},
7237 {"setwinvar", 3, 3, f_setwinvar},
7238 {"shellescape", 1, 1, f_shellescape},
7239 {"simplify", 1, 1, f_simplify},
7240 {"sort", 1, 2, f_sort},
7241 {"soundfold", 1, 1, f_soundfold},
7242 {"spellbadword", 0, 1, f_spellbadword},
7243 {"spellsuggest", 1, 3, f_spellsuggest},
7244 {"split", 1, 3, f_split},
7245 {"str2nr", 1, 2, f_str2nr},
7246 #ifdef HAVE_STRFTIME
7247 {"strftime", 1, 2, f_strftime},
7248 #endif
7249 {"stridx", 2, 3, f_stridx},
7250 {"string", 1, 1, f_string},
7251 {"strlen", 1, 1, f_strlen},
7252 {"strpart", 2, 3, f_strpart},
7253 {"strridx", 2, 3, f_strridx},
7254 {"strtrans", 1, 1, f_strtrans},
7255 {"submatch", 1, 1, f_submatch},
7256 {"substitute", 4, 4, f_substitute},
7257 {"synID", 3, 3, f_synID},
7258 {"synIDattr", 2, 3, f_synIDattr},
7259 {"synIDtrans", 1, 1, f_synIDtrans},
7260 {"synstack", 2, 2, f_synstack},
7261 {"system", 1, 2, f_system},
7262 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7263 {"tabpagenr", 0, 1, f_tabpagenr},
7264 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7265 {"tagfiles", 0, 0, f_tagfiles},
7266 {"taglist", 1, 1, f_taglist},
7267 {"tempname", 0, 0, f_tempname},
7268 {"test", 1, 1, f_test},
7269 {"tolower", 1, 1, f_tolower},
7270 {"toupper", 1, 1, f_toupper},
7271 {"tr", 3, 3, f_tr},
7272 {"type", 1, 1, f_type},
7273 {"values", 1, 1, f_values},
7274 {"virtcol", 1, 1, f_virtcol},
7275 {"visualmode", 0, 1, f_visualmode},
7276 {"winbufnr", 1, 1, f_winbufnr},
7277 {"wincol", 0, 0, f_wincol},
7278 {"winheight", 1, 1, f_winheight},
7279 {"winline", 0, 0, f_winline},
7280 {"winnr", 0, 1, f_winnr},
7281 {"winrestcmd", 0, 0, f_winrestcmd},
7282 {"winrestview", 1, 1, f_winrestview},
7283 {"winsaveview", 0, 0, f_winsaveview},
7284 {"winwidth", 1, 1, f_winwidth},
7285 {"writefile", 2, 3, f_writefile},
7288 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7291 * Function given to ExpandGeneric() to obtain the list of internal
7292 * or user defined function names.
7294 char_u *
7295 get_function_name(xp, idx)
7296 expand_T *xp;
7297 int idx;
7299 static int intidx = -1;
7300 char_u *name;
7302 if (idx == 0)
7303 intidx = -1;
7304 if (intidx < 0)
7306 name = get_user_func_name(xp, idx);
7307 if (name != NULL)
7308 return name;
7310 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7312 STRCPY(IObuff, functions[intidx].f_name);
7313 STRCAT(IObuff, "(");
7314 if (functions[intidx].f_max_argc == 0)
7315 STRCAT(IObuff, ")");
7316 return IObuff;
7319 return NULL;
7323 * Function given to ExpandGeneric() to obtain the list of internal or
7324 * user defined variable or function names.
7326 /*ARGSUSED*/
7327 char_u *
7328 get_expr_name(xp, idx)
7329 expand_T *xp;
7330 int idx;
7332 static int intidx = -1;
7333 char_u *name;
7335 if (idx == 0)
7336 intidx = -1;
7337 if (intidx < 0)
7339 name = get_function_name(xp, idx);
7340 if (name != NULL)
7341 return name;
7343 return get_user_var_name(xp, ++intidx);
7346 #endif /* FEAT_CMDL_COMPL */
7349 * Find internal function in table above.
7350 * Return index, or -1 if not found
7352 static int
7353 find_internal_func(name)
7354 char_u *name; /* name of the function */
7356 int first = 0;
7357 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7358 int cmp;
7359 int x;
7362 * Find the function name in the table. Binary search.
7364 while (first <= last)
7366 x = first + ((unsigned)(last - first) >> 1);
7367 cmp = STRCMP(name, functions[x].f_name);
7368 if (cmp < 0)
7369 last = x - 1;
7370 else if (cmp > 0)
7371 first = x + 1;
7372 else
7373 return x;
7375 return -1;
7379 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7380 * name it contains, otherwise return "name".
7382 static char_u *
7383 deref_func_name(name, lenp)
7384 char_u *name;
7385 int *lenp;
7387 dictitem_T *v;
7388 int cc;
7390 cc = name[*lenp];
7391 name[*lenp] = NUL;
7392 v = find_var(name, NULL);
7393 name[*lenp] = cc;
7394 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7396 if (v->di_tv.vval.v_string == NULL)
7398 *lenp = 0;
7399 return (char_u *)""; /* just in case */
7401 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7402 return v->di_tv.vval.v_string;
7405 return name;
7409 * Allocate a variable for the result of a function.
7410 * Return OK or FAIL.
7412 static int
7413 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7414 evaluate, selfdict)
7415 char_u *name; /* name of the function */
7416 int len; /* length of "name" */
7417 typval_T *rettv;
7418 char_u **arg; /* argument, pointing to the '(' */
7419 linenr_T firstline; /* first line of range */
7420 linenr_T lastline; /* last line of range */
7421 int *doesrange; /* return: function handled range */
7422 int evaluate;
7423 dict_T *selfdict; /* Dictionary for "self" */
7425 char_u *argp;
7426 int ret = OK;
7427 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7428 int argcount = 0; /* number of arguments found */
7431 * Get the arguments.
7433 argp = *arg;
7434 while (argcount < MAX_FUNC_ARGS)
7436 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7437 if (*argp == ')' || *argp == ',' || *argp == NUL)
7438 break;
7439 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7441 ret = FAIL;
7442 break;
7444 ++argcount;
7445 if (*argp != ',')
7446 break;
7448 if (*argp == ')')
7449 ++argp;
7450 else
7451 ret = FAIL;
7453 if (ret == OK)
7454 ret = call_func(name, len, rettv, argcount, argvars,
7455 firstline, lastline, doesrange, evaluate, selfdict);
7456 else if (!aborting())
7458 if (argcount == MAX_FUNC_ARGS)
7459 emsg_funcname("E740: Too many arguments for function %s", name);
7460 else
7461 emsg_funcname("E116: Invalid arguments for function %s", name);
7464 while (--argcount >= 0)
7465 clear_tv(&argvars[argcount]);
7467 *arg = skipwhite(argp);
7468 return ret;
7473 * Call a function with its resolved parameters
7474 * Return OK when the function can't be called, FAIL otherwise.
7475 * Also returns OK when an error was encountered while executing the function.
7477 static int
7478 call_func(name, len, rettv, argcount, argvars, firstline, lastline,
7479 doesrange, evaluate, selfdict)
7480 char_u *name; /* name of the function */
7481 int len; /* length of "name" */
7482 typval_T *rettv; /* return value goes here */
7483 int argcount; /* number of "argvars" */
7484 typval_T *argvars; /* vars for arguments, must have "argcount"
7485 PLUS ONE elements! */
7486 linenr_T firstline; /* first line of range */
7487 linenr_T lastline; /* last line of range */
7488 int *doesrange; /* return: function handled range */
7489 int evaluate;
7490 dict_T *selfdict; /* Dictionary for "self" */
7492 int ret = FAIL;
7493 #define ERROR_UNKNOWN 0
7494 #define ERROR_TOOMANY 1
7495 #define ERROR_TOOFEW 2
7496 #define ERROR_SCRIPT 3
7497 #define ERROR_DICT 4
7498 #define ERROR_NONE 5
7499 #define ERROR_OTHER 6
7500 int error = ERROR_NONE;
7501 int i;
7502 int llen;
7503 ufunc_T *fp;
7504 int cc;
7505 #define FLEN_FIXED 40
7506 char_u fname_buf[FLEN_FIXED + 1];
7507 char_u *fname;
7510 * In a script change <SID>name() and s:name() to K_SNR 123_name().
7511 * Change <SNR>123_name() to K_SNR 123_name().
7512 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
7514 cc = name[len];
7515 name[len] = NUL;
7516 llen = eval_fname_script(name);
7517 if (llen > 0)
7519 fname_buf[0] = K_SPECIAL;
7520 fname_buf[1] = KS_EXTRA;
7521 fname_buf[2] = (int)KE_SNR;
7522 i = 3;
7523 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
7525 if (current_SID <= 0)
7526 error = ERROR_SCRIPT;
7527 else
7529 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
7530 i = (int)STRLEN(fname_buf);
7533 if (i + STRLEN(name + llen) < FLEN_FIXED)
7535 STRCPY(fname_buf + i, name + llen);
7536 fname = fname_buf;
7538 else
7540 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
7541 if (fname == NULL)
7542 error = ERROR_OTHER;
7543 else
7545 mch_memmove(fname, fname_buf, (size_t)i);
7546 STRCPY(fname + i, name + llen);
7550 else
7551 fname = name;
7553 *doesrange = FALSE;
7556 /* execute the function if no errors detected and executing */
7557 if (evaluate && error == ERROR_NONE)
7559 rettv->v_type = VAR_NUMBER; /* default is number rettv */
7560 error = ERROR_UNKNOWN;
7562 if (!builtin_function(fname))
7565 * User defined function.
7567 fp = find_func(fname);
7569 #ifdef FEAT_AUTOCMD
7570 /* Trigger FuncUndefined event, may load the function. */
7571 if (fp == NULL
7572 && apply_autocmds(EVENT_FUNCUNDEFINED,
7573 fname, fname, TRUE, NULL)
7574 && !aborting())
7576 /* executed an autocommand, search for the function again */
7577 fp = find_func(fname);
7579 #endif
7580 /* Try loading a package. */
7581 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
7583 /* loaded a package, search for the function again */
7584 fp = find_func(fname);
7587 if (fp != NULL)
7589 if (fp->uf_flags & FC_RANGE)
7590 *doesrange = TRUE;
7591 if (argcount < fp->uf_args.ga_len)
7592 error = ERROR_TOOFEW;
7593 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
7594 error = ERROR_TOOMANY;
7595 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
7596 error = ERROR_DICT;
7597 else
7600 * Call the user function.
7601 * Save and restore search patterns, script variables and
7602 * redo buffer.
7604 save_search_patterns();
7605 saveRedobuff();
7606 ++fp->uf_calls;
7607 call_user_func(fp, argcount, argvars, rettv,
7608 firstline, lastline,
7609 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
7610 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
7611 && fp->uf_refcount <= 0)
7612 /* Function was unreferenced while being used, free it
7613 * now. */
7614 func_free(fp);
7615 restoreRedobuff();
7616 restore_search_patterns();
7617 error = ERROR_NONE;
7621 else
7624 * Find the function name in the table, call its implementation.
7626 i = find_internal_func(fname);
7627 if (i >= 0)
7629 if (argcount < functions[i].f_min_argc)
7630 error = ERROR_TOOFEW;
7631 else if (argcount > functions[i].f_max_argc)
7632 error = ERROR_TOOMANY;
7633 else
7635 argvars[argcount].v_type = VAR_UNKNOWN;
7636 functions[i].f_func(argvars, rettv);
7637 error = ERROR_NONE;
7642 * The function call (or "FuncUndefined" autocommand sequence) might
7643 * have been aborted by an error, an interrupt, or an explicitly thrown
7644 * exception that has not been caught so far. This situation can be
7645 * tested for by calling aborting(). For an error in an internal
7646 * function or for the "E132" error in call_user_func(), however, the
7647 * throw point at which the "force_abort" flag (temporarily reset by
7648 * emsg()) is normally updated has not been reached yet. We need to
7649 * update that flag first to make aborting() reliable.
7651 update_force_abort();
7653 if (error == ERROR_NONE)
7654 ret = OK;
7657 * Report an error unless the argument evaluation or function call has been
7658 * cancelled due to an aborting error, an interrupt, or an exception.
7660 if (!aborting())
7662 switch (error)
7664 case ERROR_UNKNOWN:
7665 emsg_funcname(N_("E117: Unknown function: %s"), name);
7666 break;
7667 case ERROR_TOOMANY:
7668 emsg_funcname(e_toomanyarg, name);
7669 break;
7670 case ERROR_TOOFEW:
7671 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
7672 name);
7673 break;
7674 case ERROR_SCRIPT:
7675 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
7676 name);
7677 break;
7678 case ERROR_DICT:
7679 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
7680 name);
7681 break;
7685 name[len] = cc;
7686 if (fname != name && fname != fname_buf)
7687 vim_free(fname);
7689 return ret;
7693 * Give an error message with a function name. Handle <SNR> things.
7695 static void
7696 emsg_funcname(ermsg, name)
7697 char *ermsg;
7698 char_u *name;
7700 char_u *p;
7702 if (*name == K_SPECIAL)
7703 p = concat_str((char_u *)"<SNR>", name + 3);
7704 else
7705 p = name;
7706 EMSG2(_(ermsg), p);
7707 if (p != name)
7708 vim_free(p);
7711 /*********************************************
7712 * Implementation of the built-in functions
7716 * "add(list, item)" function
7718 static void
7719 f_add(argvars, rettv)
7720 typval_T *argvars;
7721 typval_T *rettv;
7723 list_T *l;
7725 rettv->vval.v_number = 1; /* Default: Failed */
7726 if (argvars[0].v_type == VAR_LIST)
7728 if ((l = argvars[0].vval.v_list) != NULL
7729 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
7730 && list_append_tv(l, &argvars[1]) == OK)
7731 copy_tv(&argvars[0], rettv);
7733 else
7734 EMSG(_(e_listreq));
7738 * "append(lnum, string/list)" function
7740 static void
7741 f_append(argvars, rettv)
7742 typval_T *argvars;
7743 typval_T *rettv;
7745 long lnum;
7746 char_u *line;
7747 list_T *l = NULL;
7748 listitem_T *li = NULL;
7749 typval_T *tv;
7750 long added = 0;
7752 lnum = get_tv_lnum(argvars);
7753 if (lnum >= 0
7754 && lnum <= curbuf->b_ml.ml_line_count
7755 && u_save(lnum, lnum + 1) == OK)
7757 if (argvars[1].v_type == VAR_LIST)
7759 l = argvars[1].vval.v_list;
7760 if (l == NULL)
7761 return;
7762 li = l->lv_first;
7764 rettv->vval.v_number = 0; /* Default: Success */
7765 for (;;)
7767 if (l == NULL)
7768 tv = &argvars[1]; /* append a string */
7769 else if (li == NULL)
7770 break; /* end of list */
7771 else
7772 tv = &li->li_tv; /* append item from list */
7773 line = get_tv_string_chk(tv);
7774 if (line == NULL) /* type error */
7776 rettv->vval.v_number = 1; /* Failed */
7777 break;
7779 ml_append(lnum + added, line, (colnr_T)0, FALSE);
7780 ++added;
7781 if (l == NULL)
7782 break;
7783 li = li->li_next;
7786 appended_lines_mark(lnum, added);
7787 if (curwin->w_cursor.lnum > lnum)
7788 curwin->w_cursor.lnum += added;
7790 else
7791 rettv->vval.v_number = 1; /* Failed */
7795 * "argc()" function
7797 /* ARGSUSED */
7798 static void
7799 f_argc(argvars, rettv)
7800 typval_T *argvars;
7801 typval_T *rettv;
7803 rettv->vval.v_number = ARGCOUNT;
7807 * "argidx()" function
7809 /* ARGSUSED */
7810 static void
7811 f_argidx(argvars, rettv)
7812 typval_T *argvars;
7813 typval_T *rettv;
7815 rettv->vval.v_number = curwin->w_arg_idx;
7819 * "argv(nr)" function
7821 static void
7822 f_argv(argvars, rettv)
7823 typval_T *argvars;
7824 typval_T *rettv;
7826 int idx;
7828 if (argvars[0].v_type != VAR_UNKNOWN)
7830 idx = get_tv_number_chk(&argvars[0], NULL);
7831 if (idx >= 0 && idx < ARGCOUNT)
7832 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
7833 else
7834 rettv->vval.v_string = NULL;
7835 rettv->v_type = VAR_STRING;
7837 else if (rettv_list_alloc(rettv) == OK)
7838 for (idx = 0; idx < ARGCOUNT; ++idx)
7839 list_append_string(rettv->vval.v_list,
7840 alist_name(&ARGLIST[idx]), -1);
7844 * "browse(save, title, initdir, default)" function
7846 /* ARGSUSED */
7847 static void
7848 f_browse(argvars, rettv)
7849 typval_T *argvars;
7850 typval_T *rettv;
7852 #ifdef FEAT_BROWSE
7853 int save;
7854 char_u *title;
7855 char_u *initdir;
7856 char_u *defname;
7857 char_u buf[NUMBUFLEN];
7858 char_u buf2[NUMBUFLEN];
7859 int error = FALSE;
7861 save = get_tv_number_chk(&argvars[0], &error);
7862 title = get_tv_string_chk(&argvars[1]);
7863 initdir = get_tv_string_buf_chk(&argvars[2], buf);
7864 defname = get_tv_string_buf_chk(&argvars[3], buf2);
7866 if (error || title == NULL || initdir == NULL || defname == NULL)
7867 rettv->vval.v_string = NULL;
7868 else
7869 rettv->vval.v_string =
7870 do_browse(save ? BROWSE_SAVE : 0,
7871 title, defname, NULL, initdir, NULL, curbuf);
7872 #else
7873 rettv->vval.v_string = NULL;
7874 #endif
7875 rettv->v_type = VAR_STRING;
7879 * "browsedir(title, initdir)" function
7881 /* ARGSUSED */
7882 static void
7883 f_browsedir(argvars, rettv)
7884 typval_T *argvars;
7885 typval_T *rettv;
7887 #ifdef FEAT_BROWSE
7888 char_u *title;
7889 char_u *initdir;
7890 char_u buf[NUMBUFLEN];
7892 title = get_tv_string_chk(&argvars[0]);
7893 initdir = get_tv_string_buf_chk(&argvars[1], buf);
7895 if (title == NULL || initdir == NULL)
7896 rettv->vval.v_string = NULL;
7897 else
7898 rettv->vval.v_string = do_browse(BROWSE_DIR,
7899 title, NULL, NULL, initdir, NULL, curbuf);
7900 #else
7901 rettv->vval.v_string = NULL;
7902 #endif
7903 rettv->v_type = VAR_STRING;
7906 static buf_T *find_buffer __ARGS((typval_T *avar));
7909 * Find a buffer by number or exact name.
7911 static buf_T *
7912 find_buffer(avar)
7913 typval_T *avar;
7915 buf_T *buf = NULL;
7917 if (avar->v_type == VAR_NUMBER)
7918 buf = buflist_findnr((int)avar->vval.v_number);
7919 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
7921 buf = buflist_findname_exp(avar->vval.v_string);
7922 if (buf == NULL)
7924 /* No full path name match, try a match with a URL or a "nofile"
7925 * buffer, these don't use the full path. */
7926 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
7927 if (buf->b_fname != NULL
7928 && (path_with_url(buf->b_fname)
7929 #ifdef FEAT_QUICKFIX
7930 || bt_nofile(buf)
7931 #endif
7933 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
7934 break;
7937 return buf;
7941 * "bufexists(expr)" function
7943 static void
7944 f_bufexists(argvars, rettv)
7945 typval_T *argvars;
7946 typval_T *rettv;
7948 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
7952 * "buflisted(expr)" function
7954 static void
7955 f_buflisted(argvars, rettv)
7956 typval_T *argvars;
7957 typval_T *rettv;
7959 buf_T *buf;
7961 buf = find_buffer(&argvars[0]);
7962 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
7966 * "bufloaded(expr)" function
7968 static void
7969 f_bufloaded(argvars, rettv)
7970 typval_T *argvars;
7971 typval_T *rettv;
7973 buf_T *buf;
7975 buf = find_buffer(&argvars[0]);
7976 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
7979 static buf_T *get_buf_tv __ARGS((typval_T *tv));
7982 * Get buffer by number or pattern.
7984 static buf_T *
7985 get_buf_tv(tv)
7986 typval_T *tv;
7988 char_u *name = tv->vval.v_string;
7989 int save_magic;
7990 char_u *save_cpo;
7991 buf_T *buf;
7993 if (tv->v_type == VAR_NUMBER)
7994 return buflist_findnr((int)tv->vval.v_number);
7995 if (tv->v_type != VAR_STRING)
7996 return NULL;
7997 if (name == NULL || *name == NUL)
7998 return curbuf;
7999 if (name[0] == '$' && name[1] == NUL)
8000 return lastbuf;
8002 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
8003 save_magic = p_magic;
8004 p_magic = TRUE;
8005 save_cpo = p_cpo;
8006 p_cpo = (char_u *)"";
8008 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8009 TRUE, FALSE));
8011 p_magic = save_magic;
8012 p_cpo = save_cpo;
8014 /* If not found, try expanding the name, like done for bufexists(). */
8015 if (buf == NULL)
8016 buf = find_buffer(tv);
8018 return buf;
8022 * "bufname(expr)" function
8024 static void
8025 f_bufname(argvars, rettv)
8026 typval_T *argvars;
8027 typval_T *rettv;
8029 buf_T *buf;
8031 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8032 ++emsg_off;
8033 buf = get_buf_tv(&argvars[0]);
8034 rettv->v_type = VAR_STRING;
8035 if (buf != NULL && buf->b_fname != NULL)
8036 rettv->vval.v_string = vim_strsave(buf->b_fname);
8037 else
8038 rettv->vval.v_string = NULL;
8039 --emsg_off;
8043 * "bufnr(expr)" function
8045 static void
8046 f_bufnr(argvars, rettv)
8047 typval_T *argvars;
8048 typval_T *rettv;
8050 buf_T *buf;
8051 int error = FALSE;
8052 char_u *name;
8054 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8055 ++emsg_off;
8056 buf = get_buf_tv(&argvars[0]);
8057 --emsg_off;
8059 /* If the buffer isn't found and the second argument is not zero create a
8060 * new buffer. */
8061 if (buf == NULL
8062 && argvars[1].v_type != VAR_UNKNOWN
8063 && get_tv_number_chk(&argvars[1], &error) != 0
8064 && !error
8065 && (name = get_tv_string_chk(&argvars[0])) != NULL
8066 && !error)
8067 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8069 if (buf != NULL)
8070 rettv->vval.v_number = buf->b_fnum;
8071 else
8072 rettv->vval.v_number = -1;
8076 * "bufwinnr(nr)" function
8078 static void
8079 f_bufwinnr(argvars, rettv)
8080 typval_T *argvars;
8081 typval_T *rettv;
8083 #ifdef FEAT_WINDOWS
8084 win_T *wp;
8085 int winnr = 0;
8086 #endif
8087 buf_T *buf;
8089 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8090 ++emsg_off;
8091 buf = get_buf_tv(&argvars[0]);
8092 #ifdef FEAT_WINDOWS
8093 for (wp = firstwin; wp; wp = wp->w_next)
8095 ++winnr;
8096 if (wp->w_buffer == buf)
8097 break;
8099 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8100 #else
8101 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8102 #endif
8103 --emsg_off;
8107 * "byte2line(byte)" function
8109 /*ARGSUSED*/
8110 static void
8111 f_byte2line(argvars, rettv)
8112 typval_T *argvars;
8113 typval_T *rettv;
8115 #ifndef FEAT_BYTEOFF
8116 rettv->vval.v_number = -1;
8117 #else
8118 long boff = 0;
8120 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8121 if (boff < 0)
8122 rettv->vval.v_number = -1;
8123 else
8124 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8125 (linenr_T)0, &boff);
8126 #endif
8130 * "byteidx()" function
8132 /*ARGSUSED*/
8133 static void
8134 f_byteidx(argvars, rettv)
8135 typval_T *argvars;
8136 typval_T *rettv;
8138 #ifdef FEAT_MBYTE
8139 char_u *t;
8140 #endif
8141 char_u *str;
8142 long idx;
8144 str = get_tv_string_chk(&argvars[0]);
8145 idx = get_tv_number_chk(&argvars[1], NULL);
8146 rettv->vval.v_number = -1;
8147 if (str == NULL || idx < 0)
8148 return;
8150 #ifdef FEAT_MBYTE
8151 t = str;
8152 for ( ; idx > 0; idx--)
8154 if (*t == NUL) /* EOL reached */
8155 return;
8156 t += (*mb_ptr2len)(t);
8158 rettv->vval.v_number = (varnumber_T)(t - str);
8159 #else
8160 if (idx <= STRLEN(str))
8161 rettv->vval.v_number = idx;
8162 #endif
8166 * "call(func, arglist)" function
8168 static void
8169 f_call(argvars, rettv)
8170 typval_T *argvars;
8171 typval_T *rettv;
8173 char_u *func;
8174 typval_T argv[MAX_FUNC_ARGS + 1];
8175 int argc = 0;
8176 listitem_T *item;
8177 int dummy;
8178 dict_T *selfdict = NULL;
8180 rettv->vval.v_number = 0;
8181 if (argvars[1].v_type != VAR_LIST)
8183 EMSG(_(e_listreq));
8184 return;
8186 if (argvars[1].vval.v_list == NULL)
8187 return;
8189 if (argvars[0].v_type == VAR_FUNC)
8190 func = argvars[0].vval.v_string;
8191 else
8192 func = get_tv_string(&argvars[0]);
8193 if (*func == NUL)
8194 return; /* type error or empty name */
8196 if (argvars[2].v_type != VAR_UNKNOWN)
8198 if (argvars[2].v_type != VAR_DICT)
8200 EMSG(_(e_dictreq));
8201 return;
8203 selfdict = argvars[2].vval.v_dict;
8206 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
8207 item = item->li_next)
8209 if (argc == MAX_FUNC_ARGS)
8211 EMSG(_("E699: Too many arguments"));
8212 break;
8214 /* Make a copy of each argument. This is needed to be able to set
8215 * v_lock to VAR_FIXED in the copy without changing the original list.
8217 copy_tv(&item->li_tv, &argv[argc++]);
8220 if (item == NULL)
8221 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
8222 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
8223 &dummy, TRUE, selfdict);
8225 /* Free the arguments. */
8226 while (argc > 0)
8227 clear_tv(&argv[--argc]);
8231 * "changenr()" function
8233 /*ARGSUSED*/
8234 static void
8235 f_changenr(argvars, rettv)
8236 typval_T *argvars;
8237 typval_T *rettv;
8239 rettv->vval.v_number = curbuf->b_u_seq_cur;
8243 * "char2nr(string)" function
8245 static void
8246 f_char2nr(argvars, rettv)
8247 typval_T *argvars;
8248 typval_T *rettv;
8250 #ifdef FEAT_MBYTE
8251 if (has_mbyte)
8252 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
8253 else
8254 #endif
8255 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
8259 * "cindent(lnum)" function
8261 static void
8262 f_cindent(argvars, rettv)
8263 typval_T *argvars;
8264 typval_T *rettv;
8266 #ifdef FEAT_CINDENT
8267 pos_T pos;
8268 linenr_T lnum;
8270 pos = curwin->w_cursor;
8271 lnum = get_tv_lnum(argvars);
8272 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
8274 curwin->w_cursor.lnum = lnum;
8275 rettv->vval.v_number = get_c_indent();
8276 curwin->w_cursor = pos;
8278 else
8279 #endif
8280 rettv->vval.v_number = -1;
8284 * "clearmatches()" function
8286 /*ARGSUSED*/
8287 static void
8288 f_clearmatches(argvars, rettv)
8289 typval_T *argvars;
8290 typval_T *rettv;
8292 #ifdef FEAT_SEARCH_EXTRA
8293 clear_matches(curwin);
8294 #endif
8298 * "col(string)" function
8300 static void
8301 f_col(argvars, rettv)
8302 typval_T *argvars;
8303 typval_T *rettv;
8305 colnr_T col = 0;
8306 pos_T *fp;
8307 int fnum = curbuf->b_fnum;
8309 fp = var2fpos(&argvars[0], FALSE, &fnum);
8310 if (fp != NULL && fnum == curbuf->b_fnum)
8312 if (fp->col == MAXCOL)
8314 /* '> can be MAXCOL, get the length of the line then */
8315 if (fp->lnum <= curbuf->b_ml.ml_line_count)
8316 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
8317 else
8318 col = MAXCOL;
8320 else
8322 col = fp->col + 1;
8323 #ifdef FEAT_VIRTUALEDIT
8324 /* col(".") when the cursor is on the NUL at the end of the line
8325 * because of "coladd" can be seen as an extra column. */
8326 if (virtual_active() && fp == &curwin->w_cursor)
8328 char_u *p = ml_get_cursor();
8330 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
8331 curwin->w_virtcol - curwin->w_cursor.coladd))
8333 # ifdef FEAT_MBYTE
8334 int l;
8336 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
8337 col += l;
8338 # else
8339 if (*p != NUL && p[1] == NUL)
8340 ++col;
8341 # endif
8344 #endif
8347 rettv->vval.v_number = col;
8350 #if defined(FEAT_INS_EXPAND)
8352 * "complete()" function
8354 /*ARGSUSED*/
8355 static void
8356 f_complete(argvars, rettv)
8357 typval_T *argvars;
8358 typval_T *rettv;
8360 int startcol;
8362 if ((State & INSERT) == 0)
8364 EMSG(_("E785: complete() can only be used in Insert mode"));
8365 return;
8368 /* Check for undo allowed here, because if something was already inserted
8369 * the line was already saved for undo and this check isn't done. */
8370 if (!undo_allowed())
8371 return;
8373 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
8375 EMSG(_(e_invarg));
8376 return;
8379 startcol = get_tv_number_chk(&argvars[0], NULL);
8380 if (startcol <= 0)
8381 return;
8383 set_completion(startcol - 1, argvars[1].vval.v_list);
8387 * "complete_add()" function
8389 /*ARGSUSED*/
8390 static void
8391 f_complete_add(argvars, rettv)
8392 typval_T *argvars;
8393 typval_T *rettv;
8395 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
8399 * "complete_check()" function
8401 /*ARGSUSED*/
8402 static void
8403 f_complete_check(argvars, rettv)
8404 typval_T *argvars;
8405 typval_T *rettv;
8407 int saved = RedrawingDisabled;
8409 RedrawingDisabled = 0;
8410 ins_compl_check_keys(0);
8411 rettv->vval.v_number = compl_interrupted;
8412 RedrawingDisabled = saved;
8414 #endif
8417 * "confirm(message, buttons[, default [, type]])" function
8419 /*ARGSUSED*/
8420 static void
8421 f_confirm(argvars, rettv)
8422 typval_T *argvars;
8423 typval_T *rettv;
8425 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
8426 char_u *message;
8427 char_u *buttons = NULL;
8428 char_u buf[NUMBUFLEN];
8429 char_u buf2[NUMBUFLEN];
8430 int def = 1;
8431 int type = VIM_GENERIC;
8432 char_u *typestr;
8433 int error = FALSE;
8435 message = get_tv_string_chk(&argvars[0]);
8436 if (message == NULL)
8437 error = TRUE;
8438 if (argvars[1].v_type != VAR_UNKNOWN)
8440 buttons = get_tv_string_buf_chk(&argvars[1], buf);
8441 if (buttons == NULL)
8442 error = TRUE;
8443 if (argvars[2].v_type != VAR_UNKNOWN)
8445 def = get_tv_number_chk(&argvars[2], &error);
8446 if (argvars[3].v_type != VAR_UNKNOWN)
8448 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
8449 if (typestr == NULL)
8450 error = TRUE;
8451 else
8453 switch (TOUPPER_ASC(*typestr))
8455 case 'E': type = VIM_ERROR; break;
8456 case 'Q': type = VIM_QUESTION; break;
8457 case 'I': type = VIM_INFO; break;
8458 case 'W': type = VIM_WARNING; break;
8459 case 'G': type = VIM_GENERIC; break;
8466 if (buttons == NULL || *buttons == NUL)
8467 buttons = (char_u *)_("&Ok");
8469 if (error)
8470 rettv->vval.v_number = 0;
8471 else
8472 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
8473 def, NULL);
8474 #else
8475 rettv->vval.v_number = 0;
8476 #endif
8480 * "copy()" function
8482 static void
8483 f_copy(argvars, rettv)
8484 typval_T *argvars;
8485 typval_T *rettv;
8487 item_copy(&argvars[0], rettv, FALSE, 0);
8491 * "count()" function
8493 static void
8494 f_count(argvars, rettv)
8495 typval_T *argvars;
8496 typval_T *rettv;
8498 long n = 0;
8499 int ic = FALSE;
8501 if (argvars[0].v_type == VAR_LIST)
8503 listitem_T *li;
8504 list_T *l;
8505 long idx;
8507 if ((l = argvars[0].vval.v_list) != NULL)
8509 li = l->lv_first;
8510 if (argvars[2].v_type != VAR_UNKNOWN)
8512 int error = FALSE;
8514 ic = get_tv_number_chk(&argvars[2], &error);
8515 if (argvars[3].v_type != VAR_UNKNOWN)
8517 idx = get_tv_number_chk(&argvars[3], &error);
8518 if (!error)
8520 li = list_find(l, idx);
8521 if (li == NULL)
8522 EMSGN(_(e_listidx), idx);
8525 if (error)
8526 li = NULL;
8529 for ( ; li != NULL; li = li->li_next)
8530 if (tv_equal(&li->li_tv, &argvars[1], ic))
8531 ++n;
8534 else if (argvars[0].v_type == VAR_DICT)
8536 int todo;
8537 dict_T *d;
8538 hashitem_T *hi;
8540 if ((d = argvars[0].vval.v_dict) != NULL)
8542 int error = FALSE;
8544 if (argvars[2].v_type != VAR_UNKNOWN)
8546 ic = get_tv_number_chk(&argvars[2], &error);
8547 if (argvars[3].v_type != VAR_UNKNOWN)
8548 EMSG(_(e_invarg));
8551 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
8552 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
8554 if (!HASHITEM_EMPTY(hi))
8556 --todo;
8557 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
8558 ++n;
8563 else
8564 EMSG2(_(e_listdictarg), "count()");
8565 rettv->vval.v_number = n;
8569 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
8571 * Checks the existence of a cscope connection.
8573 /*ARGSUSED*/
8574 static void
8575 f_cscope_connection(argvars, rettv)
8576 typval_T *argvars;
8577 typval_T *rettv;
8579 #ifdef FEAT_CSCOPE
8580 int num = 0;
8581 char_u *dbpath = NULL;
8582 char_u *prepend = NULL;
8583 char_u buf[NUMBUFLEN];
8585 if (argvars[0].v_type != VAR_UNKNOWN
8586 && argvars[1].v_type != VAR_UNKNOWN)
8588 num = (int)get_tv_number(&argvars[0]);
8589 dbpath = get_tv_string(&argvars[1]);
8590 if (argvars[2].v_type != VAR_UNKNOWN)
8591 prepend = get_tv_string_buf(&argvars[2], buf);
8594 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
8595 #else
8596 rettv->vval.v_number = 0;
8597 #endif
8601 * "cursor(lnum, col)" function
8603 * Moves the cursor to the specified line and column
8605 /*ARGSUSED*/
8606 static void
8607 f_cursor(argvars, rettv)
8608 typval_T *argvars;
8609 typval_T *rettv;
8611 long line, col;
8612 #ifdef FEAT_VIRTUALEDIT
8613 long coladd = 0;
8614 #endif
8616 if (argvars[1].v_type == VAR_UNKNOWN)
8618 pos_T pos;
8620 if (list2fpos(argvars, &pos, NULL) == FAIL)
8621 return;
8622 line = pos.lnum;
8623 col = pos.col;
8624 #ifdef FEAT_VIRTUALEDIT
8625 coladd = pos.coladd;
8626 #endif
8628 else
8630 line = get_tv_lnum(argvars);
8631 col = get_tv_number_chk(&argvars[1], NULL);
8632 #ifdef FEAT_VIRTUALEDIT
8633 if (argvars[2].v_type != VAR_UNKNOWN)
8634 coladd = get_tv_number_chk(&argvars[2], NULL);
8635 #endif
8637 if (line < 0 || col < 0
8638 #ifdef FEAT_VIRTUALEDIT
8639 || coladd < 0
8640 #endif
8642 return; /* type error; errmsg already given */
8643 if (line > 0)
8644 curwin->w_cursor.lnum = line;
8645 if (col > 0)
8646 curwin->w_cursor.col = col - 1;
8647 #ifdef FEAT_VIRTUALEDIT
8648 curwin->w_cursor.coladd = coladd;
8649 #endif
8651 /* Make sure the cursor is in a valid position. */
8652 check_cursor();
8653 #ifdef FEAT_MBYTE
8654 /* Correct cursor for multi-byte character. */
8655 if (has_mbyte)
8656 mb_adjust_cursor();
8657 #endif
8659 curwin->w_set_curswant = TRUE;
8663 * "deepcopy()" function
8665 static void
8666 f_deepcopy(argvars, rettv)
8667 typval_T *argvars;
8668 typval_T *rettv;
8670 int noref = 0;
8672 if (argvars[1].v_type != VAR_UNKNOWN)
8673 noref = get_tv_number_chk(&argvars[1], NULL);
8674 if (noref < 0 || noref > 1)
8675 EMSG(_(e_invarg));
8676 else
8677 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? ++current_copyID : 0);
8681 * "delete()" function
8683 static void
8684 f_delete(argvars, rettv)
8685 typval_T *argvars;
8686 typval_T *rettv;
8688 if (check_restricted() || check_secure())
8689 rettv->vval.v_number = -1;
8690 else
8691 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
8695 * "did_filetype()" function
8697 /*ARGSUSED*/
8698 static void
8699 f_did_filetype(argvars, rettv)
8700 typval_T *argvars;
8701 typval_T *rettv;
8703 #ifdef FEAT_AUTOCMD
8704 rettv->vval.v_number = did_filetype;
8705 #else
8706 rettv->vval.v_number = 0;
8707 #endif
8711 * "diff_filler()" function
8713 /*ARGSUSED*/
8714 static void
8715 f_diff_filler(argvars, rettv)
8716 typval_T *argvars;
8717 typval_T *rettv;
8719 #ifdef FEAT_DIFF
8720 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
8721 #endif
8725 * "diff_hlID()" function
8727 /*ARGSUSED*/
8728 static void
8729 f_diff_hlID(argvars, rettv)
8730 typval_T *argvars;
8731 typval_T *rettv;
8733 #ifdef FEAT_DIFF
8734 linenr_T lnum = get_tv_lnum(argvars);
8735 static linenr_T prev_lnum = 0;
8736 static int changedtick = 0;
8737 static int fnum = 0;
8738 static int change_start = 0;
8739 static int change_end = 0;
8740 static hlf_T hlID = (hlf_T)0;
8741 int filler_lines;
8742 int col;
8744 if (lnum < 0) /* ignore type error in {lnum} arg */
8745 lnum = 0;
8746 if (lnum != prev_lnum
8747 || changedtick != curbuf->b_changedtick
8748 || fnum != curbuf->b_fnum)
8750 /* New line, buffer, change: need to get the values. */
8751 filler_lines = diff_check(curwin, lnum);
8752 if (filler_lines < 0)
8754 if (filler_lines == -1)
8756 change_start = MAXCOL;
8757 change_end = -1;
8758 if (diff_find_change(curwin, lnum, &change_start, &change_end))
8759 hlID = HLF_ADD; /* added line */
8760 else
8761 hlID = HLF_CHD; /* changed line */
8763 else
8764 hlID = HLF_ADD; /* added line */
8766 else
8767 hlID = (hlf_T)0;
8768 prev_lnum = lnum;
8769 changedtick = curbuf->b_changedtick;
8770 fnum = curbuf->b_fnum;
8773 if (hlID == HLF_CHD || hlID == HLF_TXD)
8775 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
8776 if (col >= change_start && col <= change_end)
8777 hlID = HLF_TXD; /* changed text */
8778 else
8779 hlID = HLF_CHD; /* changed line */
8781 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
8782 #endif
8786 * "empty({expr})" function
8788 static void
8789 f_empty(argvars, rettv)
8790 typval_T *argvars;
8791 typval_T *rettv;
8793 int n;
8795 switch (argvars[0].v_type)
8797 case VAR_STRING:
8798 case VAR_FUNC:
8799 n = argvars[0].vval.v_string == NULL
8800 || *argvars[0].vval.v_string == NUL;
8801 break;
8802 case VAR_NUMBER:
8803 n = argvars[0].vval.v_number == 0;
8804 break;
8805 case VAR_LIST:
8806 n = argvars[0].vval.v_list == NULL
8807 || argvars[0].vval.v_list->lv_first == NULL;
8808 break;
8809 case VAR_DICT:
8810 n = argvars[0].vval.v_dict == NULL
8811 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
8812 break;
8813 default:
8814 EMSG2(_(e_intern2), "f_empty()");
8815 n = 0;
8818 rettv->vval.v_number = n;
8822 * "escape({string}, {chars})" function
8824 static void
8825 f_escape(argvars, rettv)
8826 typval_T *argvars;
8827 typval_T *rettv;
8829 char_u buf[NUMBUFLEN];
8831 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
8832 get_tv_string_buf(&argvars[1], buf));
8833 rettv->v_type = VAR_STRING;
8837 * "eval()" function
8839 /*ARGSUSED*/
8840 static void
8841 f_eval(argvars, rettv)
8842 typval_T *argvars;
8843 typval_T *rettv;
8845 char_u *s;
8847 s = get_tv_string_chk(&argvars[0]);
8848 if (s != NULL)
8849 s = skipwhite(s);
8851 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
8853 rettv->v_type = VAR_NUMBER;
8854 rettv->vval.v_number = 0;
8856 else if (*s != NUL)
8857 EMSG(_(e_trailing));
8861 * "eventhandler()" function
8863 /*ARGSUSED*/
8864 static void
8865 f_eventhandler(argvars, rettv)
8866 typval_T *argvars;
8867 typval_T *rettv;
8869 rettv->vval.v_number = vgetc_busy;
8873 * "executable()" function
8875 static void
8876 f_executable(argvars, rettv)
8877 typval_T *argvars;
8878 typval_T *rettv;
8880 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
8884 * "exists()" function
8886 static void
8887 f_exists(argvars, rettv)
8888 typval_T *argvars;
8889 typval_T *rettv;
8891 char_u *p;
8892 char_u *name;
8893 int n = FALSE;
8894 int len = 0;
8896 p = get_tv_string(&argvars[0]);
8897 if (*p == '$') /* environment variable */
8899 /* first try "normal" environment variables (fast) */
8900 if (mch_getenv(p + 1) != NULL)
8901 n = TRUE;
8902 else
8904 /* try expanding things like $VIM and ${HOME} */
8905 p = expand_env_save(p);
8906 if (p != NULL && *p != '$')
8907 n = TRUE;
8908 vim_free(p);
8911 else if (*p == '&' || *p == '+') /* option */
8913 n = (get_option_tv(&p, NULL, TRUE) == OK);
8914 if (*skipwhite(p) != NUL)
8915 n = FALSE; /* trailing garbage */
8917 else if (*p == '*') /* internal or user defined function */
8919 n = function_exists(p + 1);
8921 else if (*p == ':')
8923 n = cmd_exists(p + 1);
8925 else if (*p == '#')
8927 #ifdef FEAT_AUTOCMD
8928 if (p[1] == '#')
8929 n = autocmd_supported(p + 2);
8930 else
8931 n = au_exists(p + 1);
8932 #endif
8934 else /* internal variable */
8936 char_u *tofree;
8937 typval_T tv;
8939 /* get_name_len() takes care of expanding curly braces */
8940 name = p;
8941 len = get_name_len(&p, &tofree, TRUE, FALSE);
8942 if (len > 0)
8944 if (tofree != NULL)
8945 name = tofree;
8946 n = (get_var_tv(name, len, &tv, FALSE) == OK);
8947 if (n)
8949 /* handle d.key, l[idx], f(expr) */
8950 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
8951 if (n)
8952 clear_tv(&tv);
8955 if (*p != NUL)
8956 n = FALSE;
8958 vim_free(tofree);
8961 rettv->vval.v_number = n;
8965 * "expand()" function
8967 static void
8968 f_expand(argvars, rettv)
8969 typval_T *argvars;
8970 typval_T *rettv;
8972 char_u *s;
8973 int len;
8974 char_u *errormsg;
8975 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
8976 expand_T xpc;
8977 int error = FALSE;
8979 rettv->v_type = VAR_STRING;
8980 s = get_tv_string(&argvars[0]);
8981 if (*s == '%' || *s == '#' || *s == '<')
8983 ++emsg_off;
8984 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
8985 --emsg_off;
8987 else
8989 /* When the optional second argument is non-zero, don't remove matches
8990 * for 'suffixes' and 'wildignore' */
8991 if (argvars[1].v_type != VAR_UNKNOWN
8992 && get_tv_number_chk(&argvars[1], &error))
8993 flags |= WILD_KEEP_ALL;
8994 if (!error)
8996 ExpandInit(&xpc);
8997 xpc.xp_context = EXPAND_FILES;
8998 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
9000 else
9001 rettv->vval.v_string = NULL;
9006 * "extend(list, list [, idx])" function
9007 * "extend(dict, dict [, action])" function
9009 static void
9010 f_extend(argvars, rettv)
9011 typval_T *argvars;
9012 typval_T *rettv;
9014 rettv->vval.v_number = 0;
9015 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9017 list_T *l1, *l2;
9018 listitem_T *item;
9019 long before;
9020 int error = FALSE;
9022 l1 = argvars[0].vval.v_list;
9023 l2 = argvars[1].vval.v_list;
9024 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9025 && l2 != NULL)
9027 if (argvars[2].v_type != VAR_UNKNOWN)
9029 before = get_tv_number_chk(&argvars[2], &error);
9030 if (error)
9031 return; /* type error; errmsg already given */
9033 if (before == l1->lv_len)
9034 item = NULL;
9035 else
9037 item = list_find(l1, before);
9038 if (item == NULL)
9040 EMSGN(_(e_listidx), before);
9041 return;
9045 else
9046 item = NULL;
9047 list_extend(l1, l2, item);
9049 copy_tv(&argvars[0], rettv);
9052 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9054 dict_T *d1, *d2;
9055 dictitem_T *di1;
9056 char_u *action;
9057 int i;
9058 hashitem_T *hi2;
9059 int todo;
9061 d1 = argvars[0].vval.v_dict;
9062 d2 = argvars[1].vval.v_dict;
9063 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9064 && d2 != NULL)
9066 /* Check the third argument. */
9067 if (argvars[2].v_type != VAR_UNKNOWN)
9069 static char *(av[]) = {"keep", "force", "error"};
9071 action = get_tv_string_chk(&argvars[2]);
9072 if (action == NULL)
9073 return; /* type error; errmsg already given */
9074 for (i = 0; i < 3; ++i)
9075 if (STRCMP(action, av[i]) == 0)
9076 break;
9077 if (i == 3)
9079 EMSG2(_(e_invarg2), action);
9080 return;
9083 else
9084 action = (char_u *)"force";
9086 /* Go over all entries in the second dict and add them to the
9087 * first dict. */
9088 todo = (int)d2->dv_hashtab.ht_used;
9089 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9091 if (!HASHITEM_EMPTY(hi2))
9093 --todo;
9094 di1 = dict_find(d1, hi2->hi_key, -1);
9095 if (di1 == NULL)
9097 di1 = dictitem_copy(HI2DI(hi2));
9098 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9099 dictitem_free(di1);
9101 else if (*action == 'e')
9103 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9104 break;
9106 else if (*action == 'f')
9108 clear_tv(&di1->di_tv);
9109 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9114 copy_tv(&argvars[0], rettv);
9117 else
9118 EMSG2(_(e_listdictarg), "extend()");
9122 * "feedkeys()" function
9124 /*ARGSUSED*/
9125 static void
9126 f_feedkeys(argvars, rettv)
9127 typval_T *argvars;
9128 typval_T *rettv;
9130 int remap = TRUE;
9131 char_u *keys, *flags;
9132 char_u nbuf[NUMBUFLEN];
9133 int typed = FALSE;
9134 char_u *keys_esc;
9136 /* This is not allowed in the sandbox. If the commands would still be
9137 * executed in the sandbox it would be OK, but it probably happens later,
9138 * when "sandbox" is no longer set. */
9139 if (check_secure())
9140 return;
9142 rettv->vval.v_number = 0;
9143 keys = get_tv_string(&argvars[0]);
9144 if (*keys != NUL)
9146 if (argvars[1].v_type != VAR_UNKNOWN)
9148 flags = get_tv_string_buf(&argvars[1], nbuf);
9149 for ( ; *flags != NUL; ++flags)
9151 switch (*flags)
9153 case 'n': remap = FALSE; break;
9154 case 'm': remap = TRUE; break;
9155 case 't': typed = TRUE; break;
9160 /* Need to escape K_SPECIAL and CSI before putting the string in the
9161 * typeahead buffer. */
9162 keys_esc = vim_strsave_escape_csi(keys);
9163 if (keys_esc != NULL)
9165 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
9166 typebuf.tb_len, !typed, FALSE);
9167 vim_free(keys_esc);
9168 if (vgetc_busy)
9169 typebuf_was_filled = TRUE;
9175 * "filereadable()" function
9177 static void
9178 f_filereadable(argvars, rettv)
9179 typval_T *argvars;
9180 typval_T *rettv;
9182 FILE *fd;
9183 char_u *p;
9184 int n;
9186 p = get_tv_string(&argvars[0]);
9187 if (*p && !mch_isdir(p) && (fd = mch_fopen((char *)p, "r")) != NULL)
9189 n = TRUE;
9190 fclose(fd);
9192 else
9193 n = FALSE;
9195 rettv->vval.v_number = n;
9199 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
9200 * rights to write into.
9202 static void
9203 f_filewritable(argvars, rettv)
9204 typval_T *argvars;
9205 typval_T *rettv;
9207 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
9210 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
9212 static void
9213 findfilendir(argvars, rettv, find_what)
9214 typval_T *argvars;
9215 typval_T *rettv;
9216 int find_what;
9218 #ifdef FEAT_SEARCHPATH
9219 char_u *fname;
9220 char_u *fresult = NULL;
9221 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
9222 char_u *p;
9223 char_u pathbuf[NUMBUFLEN];
9224 int count = 1;
9225 int first = TRUE;
9226 int error = FALSE;
9227 #endif
9229 rettv->vval.v_string = NULL;
9230 rettv->v_type = VAR_STRING;
9232 #ifdef FEAT_SEARCHPATH
9233 fname = get_tv_string(&argvars[0]);
9235 if (argvars[1].v_type != VAR_UNKNOWN)
9237 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
9238 if (p == NULL)
9239 error = TRUE;
9240 else
9242 if (*p != NUL)
9243 path = p;
9245 if (argvars[2].v_type != VAR_UNKNOWN)
9246 count = get_tv_number_chk(&argvars[2], &error);
9250 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
9251 error = TRUE;
9253 if (*fname != NUL && !error)
9257 if (rettv->v_type == VAR_STRING)
9258 vim_free(fresult);
9259 fresult = find_file_in_path_option(first ? fname : NULL,
9260 first ? (int)STRLEN(fname) : 0,
9261 0, first, path,
9262 find_what,
9263 curbuf->b_ffname,
9264 find_what == FINDFILE_DIR
9265 ? (char_u *)"" : curbuf->b_p_sua);
9266 first = FALSE;
9268 if (fresult != NULL && rettv->v_type == VAR_LIST)
9269 list_append_string(rettv->vval.v_list, fresult, -1);
9271 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
9274 if (rettv->v_type == VAR_STRING)
9275 rettv->vval.v_string = fresult;
9276 #endif
9279 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
9280 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
9283 * Implementation of map() and filter().
9285 static void
9286 filter_map(argvars, rettv, map)
9287 typval_T *argvars;
9288 typval_T *rettv;
9289 int map;
9291 char_u buf[NUMBUFLEN];
9292 char_u *expr;
9293 listitem_T *li, *nli;
9294 list_T *l = NULL;
9295 dictitem_T *di;
9296 hashtab_T *ht;
9297 hashitem_T *hi;
9298 dict_T *d = NULL;
9299 typval_T save_val;
9300 typval_T save_key;
9301 int rem;
9302 int todo;
9303 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
9304 int save_did_emsg;
9306 rettv->vval.v_number = 0;
9307 if (argvars[0].v_type == VAR_LIST)
9309 if ((l = argvars[0].vval.v_list) == NULL
9310 || (map && tv_check_lock(l->lv_lock, ermsg)))
9311 return;
9313 else if (argvars[0].v_type == VAR_DICT)
9315 if ((d = argvars[0].vval.v_dict) == NULL
9316 || (map && tv_check_lock(d->dv_lock, ermsg)))
9317 return;
9319 else
9321 EMSG2(_(e_listdictarg), ermsg);
9322 return;
9325 expr = get_tv_string_buf_chk(&argvars[1], buf);
9326 /* On type errors, the preceding call has already displayed an error
9327 * message. Avoid a misleading error message for an empty string that
9328 * was not passed as argument. */
9329 if (expr != NULL)
9331 prepare_vimvar(VV_VAL, &save_val);
9332 expr = skipwhite(expr);
9334 /* We reset "did_emsg" to be able to detect whether an error
9335 * occurred during evaluation of the expression. */
9336 save_did_emsg = did_emsg;
9337 did_emsg = FALSE;
9339 if (argvars[0].v_type == VAR_DICT)
9341 prepare_vimvar(VV_KEY, &save_key);
9342 vimvars[VV_KEY].vv_type = VAR_STRING;
9344 ht = &d->dv_hashtab;
9345 hash_lock(ht);
9346 todo = (int)ht->ht_used;
9347 for (hi = ht->ht_array; todo > 0; ++hi)
9349 if (!HASHITEM_EMPTY(hi))
9351 --todo;
9352 di = HI2DI(hi);
9353 if (tv_check_lock(di->di_tv.v_lock, ermsg))
9354 break;
9355 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
9356 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
9357 || did_emsg)
9358 break;
9359 if (!map && rem)
9360 dictitem_remove(d, di);
9361 clear_tv(&vimvars[VV_KEY].vv_tv);
9364 hash_unlock(ht);
9366 restore_vimvar(VV_KEY, &save_key);
9368 else
9370 for (li = l->lv_first; li != NULL; li = nli)
9372 if (tv_check_lock(li->li_tv.v_lock, ermsg))
9373 break;
9374 nli = li->li_next;
9375 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
9376 || did_emsg)
9377 break;
9378 if (!map && rem)
9379 listitem_remove(l, li);
9383 restore_vimvar(VV_VAL, &save_val);
9385 did_emsg |= save_did_emsg;
9388 copy_tv(&argvars[0], rettv);
9391 static int
9392 filter_map_one(tv, expr, map, remp)
9393 typval_T *tv;
9394 char_u *expr;
9395 int map;
9396 int *remp;
9398 typval_T rettv;
9399 char_u *s;
9400 int retval = FAIL;
9402 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
9403 s = expr;
9404 if (eval1(&s, &rettv, TRUE) == FAIL)
9405 goto theend;
9406 if (*s != NUL) /* check for trailing chars after expr */
9408 EMSG2(_(e_invexpr2), s);
9409 goto theend;
9411 if (map)
9413 /* map(): replace the list item value */
9414 clear_tv(tv);
9415 rettv.v_lock = 0;
9416 *tv = rettv;
9418 else
9420 int error = FALSE;
9422 /* filter(): when expr is zero remove the item */
9423 *remp = (get_tv_number_chk(&rettv, &error) == 0);
9424 clear_tv(&rettv);
9425 /* On type error, nothing has been removed; return FAIL to stop the
9426 * loop. The error message was given by get_tv_number_chk(). */
9427 if (error)
9428 goto theend;
9430 retval = OK;
9431 theend:
9432 clear_tv(&vimvars[VV_VAL].vv_tv);
9433 return retval;
9437 * "filter()" function
9439 static void
9440 f_filter(argvars, rettv)
9441 typval_T *argvars;
9442 typval_T *rettv;
9444 filter_map(argvars, rettv, FALSE);
9448 * "finddir({fname}[, {path}[, {count}]])" function
9450 static void
9451 f_finddir(argvars, rettv)
9452 typval_T *argvars;
9453 typval_T *rettv;
9455 findfilendir(argvars, rettv, FINDFILE_DIR);
9459 * "findfile({fname}[, {path}[, {count}]])" function
9461 static void
9462 f_findfile(argvars, rettv)
9463 typval_T *argvars;
9464 typval_T *rettv;
9466 findfilendir(argvars, rettv, FINDFILE_FILE);
9470 * "fnameescape({string})" function
9472 static void
9473 f_fnameescape(argvars, rettv)
9474 typval_T *argvars;
9475 typval_T *rettv;
9477 rettv->vval.v_string = vim_strsave_fnameescape(
9478 get_tv_string(&argvars[0]), FALSE);
9479 rettv->v_type = VAR_STRING;
9483 * "fnamemodify({fname}, {mods})" function
9485 static void
9486 f_fnamemodify(argvars, rettv)
9487 typval_T *argvars;
9488 typval_T *rettv;
9490 char_u *fname;
9491 char_u *mods;
9492 int usedlen = 0;
9493 int len;
9494 char_u *fbuf = NULL;
9495 char_u buf[NUMBUFLEN];
9497 fname = get_tv_string_chk(&argvars[0]);
9498 mods = get_tv_string_buf_chk(&argvars[1], buf);
9499 if (fname == NULL || mods == NULL)
9500 fname = NULL;
9501 else
9503 len = (int)STRLEN(fname);
9504 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
9507 rettv->v_type = VAR_STRING;
9508 if (fname == NULL)
9509 rettv->vval.v_string = NULL;
9510 else
9511 rettv->vval.v_string = vim_strnsave(fname, len);
9512 vim_free(fbuf);
9515 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
9518 * "foldclosed()" function
9520 static void
9521 foldclosed_both(argvars, rettv, end)
9522 typval_T *argvars;
9523 typval_T *rettv;
9524 int end;
9526 #ifdef FEAT_FOLDING
9527 linenr_T lnum;
9528 linenr_T first, last;
9530 lnum = get_tv_lnum(argvars);
9531 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9533 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
9535 if (end)
9536 rettv->vval.v_number = (varnumber_T)last;
9537 else
9538 rettv->vval.v_number = (varnumber_T)first;
9539 return;
9542 #endif
9543 rettv->vval.v_number = -1;
9547 * "foldclosed()" function
9549 static void
9550 f_foldclosed(argvars, rettv)
9551 typval_T *argvars;
9552 typval_T *rettv;
9554 foldclosed_both(argvars, rettv, FALSE);
9558 * "foldclosedend()" function
9560 static void
9561 f_foldclosedend(argvars, rettv)
9562 typval_T *argvars;
9563 typval_T *rettv;
9565 foldclosed_both(argvars, rettv, TRUE);
9569 * "foldlevel()" function
9571 static void
9572 f_foldlevel(argvars, rettv)
9573 typval_T *argvars;
9574 typval_T *rettv;
9576 #ifdef FEAT_FOLDING
9577 linenr_T lnum;
9579 lnum = get_tv_lnum(argvars);
9580 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9581 rettv->vval.v_number = foldLevel(lnum);
9582 else
9583 #endif
9584 rettv->vval.v_number = 0;
9588 * "foldtext()" function
9590 /*ARGSUSED*/
9591 static void
9592 f_foldtext(argvars, rettv)
9593 typval_T *argvars;
9594 typval_T *rettv;
9596 #ifdef FEAT_FOLDING
9597 linenr_T lnum;
9598 char_u *s;
9599 char_u *r;
9600 int len;
9601 char *txt;
9602 #endif
9604 rettv->v_type = VAR_STRING;
9605 rettv->vval.v_string = NULL;
9606 #ifdef FEAT_FOLDING
9607 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
9608 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
9609 <= curbuf->b_ml.ml_line_count
9610 && vimvars[VV_FOLDDASHES].vv_str != NULL)
9612 /* Find first non-empty line in the fold. */
9613 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
9614 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
9616 if (!linewhite(lnum))
9617 break;
9618 ++lnum;
9621 /* Find interesting text in this line. */
9622 s = skipwhite(ml_get(lnum));
9623 /* skip C comment-start */
9624 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
9626 s = skipwhite(s + 2);
9627 if (*skipwhite(s) == NUL
9628 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
9630 s = skipwhite(ml_get(lnum + 1));
9631 if (*s == '*')
9632 s = skipwhite(s + 1);
9635 txt = _("+-%s%3ld lines: ");
9636 r = alloc((unsigned)(STRLEN(txt)
9637 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
9638 + 20 /* for %3ld */
9639 + STRLEN(s))); /* concatenated */
9640 if (r != NULL)
9642 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
9643 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
9644 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
9645 len = (int)STRLEN(r);
9646 STRCAT(r, s);
9647 /* remove 'foldmarker' and 'commentstring' */
9648 foldtext_cleanup(r + len);
9649 rettv->vval.v_string = r;
9652 #endif
9656 * "foldtextresult(lnum)" function
9658 /*ARGSUSED*/
9659 static void
9660 f_foldtextresult(argvars, rettv)
9661 typval_T *argvars;
9662 typval_T *rettv;
9664 #ifdef FEAT_FOLDING
9665 linenr_T lnum;
9666 char_u *text;
9667 char_u buf[51];
9668 foldinfo_T foldinfo;
9669 int fold_count;
9670 #endif
9672 rettv->v_type = VAR_STRING;
9673 rettv->vval.v_string = NULL;
9674 #ifdef FEAT_FOLDING
9675 lnum = get_tv_lnum(argvars);
9676 /* treat illegal types and illegal string values for {lnum} the same */
9677 if (lnum < 0)
9678 lnum = 0;
9679 fold_count = foldedCount(curwin, lnum, &foldinfo);
9680 if (fold_count > 0)
9682 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
9683 &foldinfo, buf);
9684 if (text == buf)
9685 text = vim_strsave(text);
9686 rettv->vval.v_string = text;
9688 #endif
9692 * "foreground()" function
9694 /*ARGSUSED*/
9695 static void
9696 f_foreground(argvars, rettv)
9697 typval_T *argvars;
9698 typval_T *rettv;
9700 rettv->vval.v_number = 0;
9701 #ifdef FEAT_GUI
9702 if (gui.in_use)
9703 gui_mch_set_foreground();
9704 #else
9705 # ifdef WIN32
9706 win32_set_foreground();
9707 # endif
9708 #endif
9712 * "function()" function
9714 /*ARGSUSED*/
9715 static void
9716 f_function(argvars, rettv)
9717 typval_T *argvars;
9718 typval_T *rettv;
9720 char_u *s;
9722 rettv->vval.v_number = 0;
9723 s = get_tv_string(&argvars[0]);
9724 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
9725 EMSG2(_(e_invarg2), s);
9726 else if (!function_exists(s))
9727 EMSG2(_("E700: Unknown function: %s"), s);
9728 else
9730 rettv->vval.v_string = vim_strsave(s);
9731 rettv->v_type = VAR_FUNC;
9736 * "garbagecollect()" function
9738 /*ARGSUSED*/
9739 static void
9740 f_garbagecollect(argvars, rettv)
9741 typval_T *argvars;
9742 typval_T *rettv;
9744 /* This is postponed until we are back at the toplevel, because we may be
9745 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
9746 want_garbage_collect = TRUE;
9748 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
9749 garbage_collect_at_exit = TRUE;
9753 * "get()" function
9755 static void
9756 f_get(argvars, rettv)
9757 typval_T *argvars;
9758 typval_T *rettv;
9760 listitem_T *li;
9761 list_T *l;
9762 dictitem_T *di;
9763 dict_T *d;
9764 typval_T *tv = NULL;
9766 if (argvars[0].v_type == VAR_LIST)
9768 if ((l = argvars[0].vval.v_list) != NULL)
9770 int error = FALSE;
9772 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
9773 if (!error && li != NULL)
9774 tv = &li->li_tv;
9777 else if (argvars[0].v_type == VAR_DICT)
9779 if ((d = argvars[0].vval.v_dict) != NULL)
9781 di = dict_find(d, get_tv_string(&argvars[1]), -1);
9782 if (di != NULL)
9783 tv = &di->di_tv;
9786 else
9787 EMSG2(_(e_listdictarg), "get()");
9789 if (tv == NULL)
9791 if (argvars[2].v_type == VAR_UNKNOWN)
9792 rettv->vval.v_number = 0;
9793 else
9794 copy_tv(&argvars[2], rettv);
9796 else
9797 copy_tv(tv, rettv);
9800 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
9803 * Get line or list of lines from buffer "buf" into "rettv".
9804 * Return a range (from start to end) of lines in rettv from the specified
9805 * buffer.
9806 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
9808 static void
9809 get_buffer_lines(buf, start, end, retlist, rettv)
9810 buf_T *buf;
9811 linenr_T start;
9812 linenr_T end;
9813 int retlist;
9814 typval_T *rettv;
9816 char_u *p;
9818 if (retlist)
9820 if (rettv_list_alloc(rettv) == FAIL)
9821 return;
9823 else
9824 rettv->vval.v_number = 0;
9826 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
9827 return;
9829 if (!retlist)
9831 if (start >= 1 && start <= buf->b_ml.ml_line_count)
9832 p = ml_get_buf(buf, start, FALSE);
9833 else
9834 p = (char_u *)"";
9836 rettv->v_type = VAR_STRING;
9837 rettv->vval.v_string = vim_strsave(p);
9839 else
9841 if (end < start)
9842 return;
9844 if (start < 1)
9845 start = 1;
9846 if (end > buf->b_ml.ml_line_count)
9847 end = buf->b_ml.ml_line_count;
9848 while (start <= end)
9849 if (list_append_string(rettv->vval.v_list,
9850 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
9851 break;
9856 * "getbufline()" function
9858 static void
9859 f_getbufline(argvars, rettv)
9860 typval_T *argvars;
9861 typval_T *rettv;
9863 linenr_T lnum;
9864 linenr_T end;
9865 buf_T *buf;
9867 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
9868 ++emsg_off;
9869 buf = get_buf_tv(&argvars[0]);
9870 --emsg_off;
9872 lnum = get_tv_lnum_buf(&argvars[1], buf);
9873 if (argvars[2].v_type == VAR_UNKNOWN)
9874 end = lnum;
9875 else
9876 end = get_tv_lnum_buf(&argvars[2], buf);
9878 get_buffer_lines(buf, lnum, end, TRUE, rettv);
9882 * "getbufvar()" function
9884 static void
9885 f_getbufvar(argvars, rettv)
9886 typval_T *argvars;
9887 typval_T *rettv;
9889 buf_T *buf;
9890 buf_T *save_curbuf;
9891 char_u *varname;
9892 dictitem_T *v;
9894 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
9895 varname = get_tv_string_chk(&argvars[1]);
9896 ++emsg_off;
9897 buf = get_buf_tv(&argvars[0]);
9899 rettv->v_type = VAR_STRING;
9900 rettv->vval.v_string = NULL;
9902 if (buf != NULL && varname != NULL)
9904 if (*varname == '&') /* buffer-local-option */
9906 /* set curbuf to be our buf, temporarily */
9907 save_curbuf = curbuf;
9908 curbuf = buf;
9910 get_option_tv(&varname, rettv, TRUE);
9912 /* restore previous notion of curbuf */
9913 curbuf = save_curbuf;
9915 else
9917 if (*varname == NUL)
9918 /* let getbufvar({nr}, "") return the "b:" dictionary. The
9919 * scope prefix before the NUL byte is required by
9920 * find_var_in_ht(). */
9921 varname = (char_u *)"b:" + 2;
9922 /* look up the variable */
9923 v = find_var_in_ht(&buf->b_vars.dv_hashtab, varname, FALSE);
9924 if (v != NULL)
9925 copy_tv(&v->di_tv, rettv);
9929 --emsg_off;
9933 * "getchar()" function
9935 static void
9936 f_getchar(argvars, rettv)
9937 typval_T *argvars;
9938 typval_T *rettv;
9940 varnumber_T n;
9941 int error = FALSE;
9943 /* Position the cursor. Needed after a message that ends in a space. */
9944 windgoto(msg_row, msg_col);
9946 ++no_mapping;
9947 ++allow_keys;
9948 for (;;)
9950 if (argvars[0].v_type == VAR_UNKNOWN)
9951 /* getchar(): blocking wait. */
9952 n = safe_vgetc();
9953 else if (get_tv_number_chk(&argvars[0], &error) == 1)
9954 /* getchar(1): only check if char avail */
9955 n = vpeekc();
9956 else if (error || vpeekc() == NUL)
9957 /* illegal argument or getchar(0) and no char avail: return zero */
9958 n = 0;
9959 else
9960 /* getchar(0) and char avail: return char */
9961 n = safe_vgetc();
9962 if (n == K_IGNORE)
9963 continue;
9964 break;
9966 --no_mapping;
9967 --allow_keys;
9969 vimvars[VV_MOUSE_WIN].vv_nr = 0;
9970 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
9971 vimvars[VV_MOUSE_COL].vv_nr = 0;
9973 rettv->vval.v_number = n;
9974 if (IS_SPECIAL(n) || mod_mask != 0)
9976 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
9977 int i = 0;
9979 /* Turn a special key into three bytes, plus modifier. */
9980 if (mod_mask != 0)
9982 temp[i++] = K_SPECIAL;
9983 temp[i++] = KS_MODIFIER;
9984 temp[i++] = mod_mask;
9986 if (IS_SPECIAL(n))
9988 temp[i++] = K_SPECIAL;
9989 temp[i++] = K_SECOND(n);
9990 temp[i++] = K_THIRD(n);
9992 #ifdef FEAT_MBYTE
9993 else if (has_mbyte)
9994 i += (*mb_char2bytes)(n, temp + i);
9995 #endif
9996 else
9997 temp[i++] = n;
9998 temp[i++] = NUL;
9999 rettv->v_type = VAR_STRING;
10000 rettv->vval.v_string = vim_strsave(temp);
10002 #ifdef FEAT_MOUSE
10003 if (n == K_LEFTMOUSE
10004 || n == K_LEFTMOUSE_NM
10005 || n == K_LEFTDRAG
10006 || n == K_LEFTRELEASE
10007 || n == K_LEFTRELEASE_NM
10008 || n == K_MIDDLEMOUSE
10009 || n == K_MIDDLEDRAG
10010 || n == K_MIDDLERELEASE
10011 || n == K_RIGHTMOUSE
10012 || n == K_RIGHTDRAG
10013 || n == K_RIGHTRELEASE
10014 || n == K_X1MOUSE
10015 || n == K_X1DRAG
10016 || n == K_X1RELEASE
10017 || n == K_X2MOUSE
10018 || n == K_X2DRAG
10019 || n == K_X2RELEASE
10020 || n == K_MOUSEDOWN
10021 || n == K_MOUSEUP)
10023 int row = mouse_row;
10024 int col = mouse_col;
10025 win_T *win;
10026 linenr_T lnum;
10027 # ifdef FEAT_WINDOWS
10028 win_T *wp;
10029 # endif
10030 int n = 1;
10032 if (row >= 0 && col >= 0)
10034 /* Find the window at the mouse coordinates and compute the
10035 * text position. */
10036 win = mouse_find_win(&row, &col);
10037 (void)mouse_comp_pos(win, &row, &col, &lnum);
10038 # ifdef FEAT_WINDOWS
10039 for (wp = firstwin; wp != win; wp = wp->w_next)
10040 ++n;
10041 # endif
10042 vimvars[VV_MOUSE_WIN].vv_nr = n;
10043 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
10044 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
10047 #endif
10052 * "getcharmod()" function
10054 /*ARGSUSED*/
10055 static void
10056 f_getcharmod(argvars, rettv)
10057 typval_T *argvars;
10058 typval_T *rettv;
10060 rettv->vval.v_number = mod_mask;
10064 * "getcmdline()" function
10066 /*ARGSUSED*/
10067 static void
10068 f_getcmdline(argvars, rettv)
10069 typval_T *argvars;
10070 typval_T *rettv;
10072 rettv->v_type = VAR_STRING;
10073 rettv->vval.v_string = get_cmdline_str();
10077 * "getcmdpos()" function
10079 /*ARGSUSED*/
10080 static void
10081 f_getcmdpos(argvars, rettv)
10082 typval_T *argvars;
10083 typval_T *rettv;
10085 rettv->vval.v_number = get_cmdline_pos() + 1;
10089 * "getcmdtype()" function
10091 /*ARGSUSED*/
10092 static void
10093 f_getcmdtype(argvars, rettv)
10094 typval_T *argvars;
10095 typval_T *rettv;
10097 rettv->v_type = VAR_STRING;
10098 rettv->vval.v_string = alloc(2);
10099 if (rettv->vval.v_string != NULL)
10101 rettv->vval.v_string[0] = get_cmdline_type();
10102 rettv->vval.v_string[1] = NUL;
10107 * "getcwd()" function
10109 /*ARGSUSED*/
10110 static void
10111 f_getcwd(argvars, rettv)
10112 typval_T *argvars;
10113 typval_T *rettv;
10115 char_u cwd[MAXPATHL];
10117 rettv->v_type = VAR_STRING;
10118 if (mch_dirname(cwd, MAXPATHL) == FAIL)
10119 rettv->vval.v_string = NULL;
10120 else
10122 rettv->vval.v_string = vim_strsave(cwd);
10123 #ifdef BACKSLASH_IN_FILENAME
10124 if (rettv->vval.v_string != NULL)
10125 slash_adjust(rettv->vval.v_string);
10126 #endif
10131 * "getfontname()" function
10133 /*ARGSUSED*/
10134 static void
10135 f_getfontname(argvars, rettv)
10136 typval_T *argvars;
10137 typval_T *rettv;
10139 rettv->v_type = VAR_STRING;
10140 rettv->vval.v_string = NULL;
10141 #ifdef FEAT_GUI
10142 if (gui.in_use)
10144 GuiFont font;
10145 char_u *name = NULL;
10147 if (argvars[0].v_type == VAR_UNKNOWN)
10149 /* Get the "Normal" font. Either the name saved by
10150 * hl_set_font_name() or from the font ID. */
10151 font = gui.norm_font;
10152 name = hl_get_font_name();
10154 else
10156 name = get_tv_string(&argvars[0]);
10157 if (STRCMP(name, "*") == 0) /* don't use font dialog */
10158 return;
10159 font = gui_mch_get_font(name, FALSE);
10160 if (font == NOFONT)
10161 return; /* Invalid font name, return empty string. */
10163 rettv->vval.v_string = gui_mch_get_fontname(font, name);
10164 if (argvars[0].v_type != VAR_UNKNOWN)
10165 gui_mch_free_font(font);
10167 #endif
10171 * "getfperm({fname})" function
10173 static void
10174 f_getfperm(argvars, rettv)
10175 typval_T *argvars;
10176 typval_T *rettv;
10178 char_u *fname;
10179 struct stat st;
10180 char_u *perm = NULL;
10181 char_u flags[] = "rwx";
10182 int i;
10184 fname = get_tv_string(&argvars[0]);
10186 rettv->v_type = VAR_STRING;
10187 if (mch_stat((char *)fname, &st) >= 0)
10189 perm = vim_strsave((char_u *)"---------");
10190 if (perm != NULL)
10192 for (i = 0; i < 9; i++)
10194 if (st.st_mode & (1 << (8 - i)))
10195 perm[i] = flags[i % 3];
10199 rettv->vval.v_string = perm;
10203 * "getfsize({fname})" function
10205 static void
10206 f_getfsize(argvars, rettv)
10207 typval_T *argvars;
10208 typval_T *rettv;
10210 char_u *fname;
10211 struct stat st;
10213 fname = get_tv_string(&argvars[0]);
10215 rettv->v_type = VAR_NUMBER;
10217 if (mch_stat((char *)fname, &st) >= 0)
10219 if (mch_isdir(fname))
10220 rettv->vval.v_number = 0;
10221 else
10223 rettv->vval.v_number = (varnumber_T)st.st_size;
10225 /* non-perfect check for overflow */
10226 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
10227 rettv->vval.v_number = -2;
10230 else
10231 rettv->vval.v_number = -1;
10235 * "getftime({fname})" function
10237 static void
10238 f_getftime(argvars, rettv)
10239 typval_T *argvars;
10240 typval_T *rettv;
10242 char_u *fname;
10243 struct stat st;
10245 fname = get_tv_string(&argvars[0]);
10247 if (mch_stat((char *)fname, &st) >= 0)
10248 rettv->vval.v_number = (varnumber_T)st.st_mtime;
10249 else
10250 rettv->vval.v_number = -1;
10254 * "getftype({fname})" function
10256 static void
10257 f_getftype(argvars, rettv)
10258 typval_T *argvars;
10259 typval_T *rettv;
10261 char_u *fname;
10262 struct stat st;
10263 char_u *type = NULL;
10264 char *t;
10266 fname = get_tv_string(&argvars[0]);
10268 rettv->v_type = VAR_STRING;
10269 if (mch_lstat((char *)fname, &st) >= 0)
10271 #ifdef S_ISREG
10272 if (S_ISREG(st.st_mode))
10273 t = "file";
10274 else if (S_ISDIR(st.st_mode))
10275 t = "dir";
10276 # ifdef S_ISLNK
10277 else if (S_ISLNK(st.st_mode))
10278 t = "link";
10279 # endif
10280 # ifdef S_ISBLK
10281 else if (S_ISBLK(st.st_mode))
10282 t = "bdev";
10283 # endif
10284 # ifdef S_ISCHR
10285 else if (S_ISCHR(st.st_mode))
10286 t = "cdev";
10287 # endif
10288 # ifdef S_ISFIFO
10289 else if (S_ISFIFO(st.st_mode))
10290 t = "fifo";
10291 # endif
10292 # ifdef S_ISSOCK
10293 else if (S_ISSOCK(st.st_mode))
10294 t = "fifo";
10295 # endif
10296 else
10297 t = "other";
10298 #else
10299 # ifdef S_IFMT
10300 switch (st.st_mode & S_IFMT)
10302 case S_IFREG: t = "file"; break;
10303 case S_IFDIR: t = "dir"; break;
10304 # ifdef S_IFLNK
10305 case S_IFLNK: t = "link"; break;
10306 # endif
10307 # ifdef S_IFBLK
10308 case S_IFBLK: t = "bdev"; break;
10309 # endif
10310 # ifdef S_IFCHR
10311 case S_IFCHR: t = "cdev"; break;
10312 # endif
10313 # ifdef S_IFIFO
10314 case S_IFIFO: t = "fifo"; break;
10315 # endif
10316 # ifdef S_IFSOCK
10317 case S_IFSOCK: t = "socket"; break;
10318 # endif
10319 default: t = "other";
10321 # else
10322 if (mch_isdir(fname))
10323 t = "dir";
10324 else
10325 t = "file";
10326 # endif
10327 #endif
10328 type = vim_strsave((char_u *)t);
10330 rettv->vval.v_string = type;
10334 * "getline(lnum, [end])" function
10336 static void
10337 f_getline(argvars, rettv)
10338 typval_T *argvars;
10339 typval_T *rettv;
10341 linenr_T lnum;
10342 linenr_T end;
10343 int retlist;
10345 lnum = get_tv_lnum(argvars);
10346 if (argvars[1].v_type == VAR_UNKNOWN)
10348 end = 0;
10349 retlist = FALSE;
10351 else
10353 end = get_tv_lnum(&argvars[1]);
10354 retlist = TRUE;
10357 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
10361 * "getmatches()" function
10363 /*ARGSUSED*/
10364 static void
10365 f_getmatches(argvars, rettv)
10366 typval_T *argvars;
10367 typval_T *rettv;
10369 #ifdef FEAT_SEARCH_EXTRA
10370 dict_T *dict;
10371 matchitem_T *cur = curwin->w_match_head;
10373 rettv->vval.v_number = 0;
10375 if (rettv_list_alloc(rettv) == OK)
10377 while (cur != NULL)
10379 dict = dict_alloc();
10380 if (dict == NULL)
10381 return;
10382 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
10383 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
10384 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
10385 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
10386 list_append_dict(rettv->vval.v_list, dict);
10387 cur = cur->next;
10390 #endif
10394 * "getpid()" function
10396 /*ARGSUSED*/
10397 static void
10398 f_getpid(argvars, rettv)
10399 typval_T *argvars;
10400 typval_T *rettv;
10402 rettv->vval.v_number = mch_get_pid();
10406 * "getpos(string)" function
10408 static void
10409 f_getpos(argvars, rettv)
10410 typval_T *argvars;
10411 typval_T *rettv;
10413 pos_T *fp;
10414 list_T *l;
10415 int fnum = -1;
10417 if (rettv_list_alloc(rettv) == OK)
10419 l = rettv->vval.v_list;
10420 fp = var2fpos(&argvars[0], TRUE, &fnum);
10421 if (fnum != -1)
10422 list_append_number(l, (varnumber_T)fnum);
10423 else
10424 list_append_number(l, (varnumber_T)0);
10425 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
10426 : (varnumber_T)0);
10427 list_append_number(l, (fp != NULL)
10428 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
10429 : (varnumber_T)0);
10430 list_append_number(l,
10431 #ifdef FEAT_VIRTUALEDIT
10432 (fp != NULL) ? (varnumber_T)fp->coladd :
10433 #endif
10434 (varnumber_T)0);
10436 else
10437 rettv->vval.v_number = FALSE;
10441 * "getqflist()" and "getloclist()" functions
10443 /*ARGSUSED*/
10444 static void
10445 f_getqflist(argvars, rettv)
10446 typval_T *argvars;
10447 typval_T *rettv;
10449 #ifdef FEAT_QUICKFIX
10450 win_T *wp;
10451 #endif
10453 rettv->vval.v_number = 0;
10454 #ifdef FEAT_QUICKFIX
10455 if (rettv_list_alloc(rettv) == OK)
10457 wp = NULL;
10458 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
10460 wp = find_win_by_nr(&argvars[0], NULL);
10461 if (wp == NULL)
10462 return;
10465 (void)get_errorlist(wp, rettv->vval.v_list);
10467 #endif
10471 * "getreg()" function
10473 static void
10474 f_getreg(argvars, rettv)
10475 typval_T *argvars;
10476 typval_T *rettv;
10478 char_u *strregname;
10479 int regname;
10480 int arg2 = FALSE;
10481 int error = FALSE;
10483 if (argvars[0].v_type != VAR_UNKNOWN)
10485 strregname = get_tv_string_chk(&argvars[0]);
10486 error = strregname == NULL;
10487 if (argvars[1].v_type != VAR_UNKNOWN)
10488 arg2 = get_tv_number_chk(&argvars[1], &error);
10490 else
10491 strregname = vimvars[VV_REG].vv_str;
10492 regname = (strregname == NULL ? '"' : *strregname);
10493 if (regname == 0)
10494 regname = '"';
10496 rettv->v_type = VAR_STRING;
10497 rettv->vval.v_string = error ? NULL :
10498 get_reg_contents(regname, TRUE, arg2);
10502 * "getregtype()" function
10504 static void
10505 f_getregtype(argvars, rettv)
10506 typval_T *argvars;
10507 typval_T *rettv;
10509 char_u *strregname;
10510 int regname;
10511 char_u buf[NUMBUFLEN + 2];
10512 long reglen = 0;
10514 if (argvars[0].v_type != VAR_UNKNOWN)
10516 strregname = get_tv_string_chk(&argvars[0]);
10517 if (strregname == NULL) /* type error; errmsg already given */
10519 rettv->v_type = VAR_STRING;
10520 rettv->vval.v_string = NULL;
10521 return;
10524 else
10525 /* Default to v:register */
10526 strregname = vimvars[VV_REG].vv_str;
10528 regname = (strregname == NULL ? '"' : *strregname);
10529 if (regname == 0)
10530 regname = '"';
10532 buf[0] = NUL;
10533 buf[1] = NUL;
10534 switch (get_reg_type(regname, &reglen))
10536 case MLINE: buf[0] = 'V'; break;
10537 case MCHAR: buf[0] = 'v'; break;
10538 #ifdef FEAT_VISUAL
10539 case MBLOCK:
10540 buf[0] = Ctrl_V;
10541 sprintf((char *)buf + 1, "%ld", reglen + 1);
10542 break;
10543 #endif
10545 rettv->v_type = VAR_STRING;
10546 rettv->vval.v_string = vim_strsave(buf);
10550 * "gettabwinvar()" function
10552 static void
10553 f_gettabwinvar(argvars, rettv)
10554 typval_T *argvars;
10555 typval_T *rettv;
10557 getwinvar(argvars, rettv, 1);
10561 * "getwinposx()" function
10563 /*ARGSUSED*/
10564 static void
10565 f_getwinposx(argvars, rettv)
10566 typval_T *argvars;
10567 typval_T *rettv;
10569 rettv->vval.v_number = -1;
10570 #ifdef FEAT_GUI
10571 if (gui.in_use)
10573 int x, y;
10575 if (gui_mch_get_winpos(&x, &y) == OK)
10576 rettv->vval.v_number = x;
10578 #endif
10582 * "getwinposy()" function
10584 /*ARGSUSED*/
10585 static void
10586 f_getwinposy(argvars, rettv)
10587 typval_T *argvars;
10588 typval_T *rettv;
10590 rettv->vval.v_number = -1;
10591 #ifdef FEAT_GUI
10592 if (gui.in_use)
10594 int x, y;
10596 if (gui_mch_get_winpos(&x, &y) == OK)
10597 rettv->vval.v_number = y;
10599 #endif
10603 * Find window specifed by "vp" in tabpage "tp".
10605 static win_T *
10606 find_win_by_nr(vp, tp)
10607 typval_T *vp;
10608 tabpage_T *tp; /* NULL for current tab page */
10610 #ifdef FEAT_WINDOWS
10611 win_T *wp;
10612 #endif
10613 int nr;
10615 nr = get_tv_number_chk(vp, NULL);
10617 #ifdef FEAT_WINDOWS
10618 if (nr < 0)
10619 return NULL;
10620 if (nr == 0)
10621 return curwin;
10623 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
10624 wp != NULL; wp = wp->w_next)
10625 if (--nr <= 0)
10626 break;
10627 return wp;
10628 #else
10629 if (nr == 0 || nr == 1)
10630 return curwin;
10631 return NULL;
10632 #endif
10636 * "getwinvar()" function
10638 static void
10639 f_getwinvar(argvars, rettv)
10640 typval_T *argvars;
10641 typval_T *rettv;
10643 getwinvar(argvars, rettv, 0);
10647 * getwinvar() and gettabwinvar()
10649 static void
10650 getwinvar(argvars, rettv, off)
10651 typval_T *argvars;
10652 typval_T *rettv;
10653 int off; /* 1 for gettabwinvar() */
10655 win_T *win, *oldcurwin;
10656 char_u *varname;
10657 dictitem_T *v;
10658 tabpage_T *tp;
10660 #ifdef FEAT_WINDOWS
10661 if (off == 1)
10662 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
10663 else
10664 tp = curtab;
10665 #endif
10666 win = find_win_by_nr(&argvars[off], tp);
10667 varname = get_tv_string_chk(&argvars[off + 1]);
10668 ++emsg_off;
10670 rettv->v_type = VAR_STRING;
10671 rettv->vval.v_string = NULL;
10673 if (win != NULL && varname != NULL)
10675 /* Set curwin to be our win, temporarily. Also set curbuf, so
10676 * that we can get buffer-local options. */
10677 oldcurwin = curwin;
10678 curwin = win;
10679 curbuf = win->w_buffer;
10681 if (*varname == '&') /* window-local-option */
10682 get_option_tv(&varname, rettv, 1);
10683 else
10685 if (*varname == NUL)
10686 /* let getwinvar({nr}, "") return the "w:" dictionary. The
10687 * scope prefix before the NUL byte is required by
10688 * find_var_in_ht(). */
10689 varname = (char_u *)"w:" + 2;
10690 /* look up the variable */
10691 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
10692 if (v != NULL)
10693 copy_tv(&v->di_tv, rettv);
10696 /* restore previous notion of curwin */
10697 curwin = oldcurwin;
10698 curbuf = curwin->w_buffer;
10701 --emsg_off;
10705 * "glob()" function
10707 static void
10708 f_glob(argvars, rettv)
10709 typval_T *argvars;
10710 typval_T *rettv;
10712 expand_T xpc;
10714 ExpandInit(&xpc);
10715 xpc.xp_context = EXPAND_FILES;
10716 rettv->v_type = VAR_STRING;
10717 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
10718 NULL, WILD_USE_NL|WILD_SILENT, WILD_ALL);
10722 * "globpath()" function
10724 static void
10725 f_globpath(argvars, rettv)
10726 typval_T *argvars;
10727 typval_T *rettv;
10729 char_u buf1[NUMBUFLEN];
10730 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
10732 rettv->v_type = VAR_STRING;
10733 if (file == NULL)
10734 rettv->vval.v_string = NULL;
10735 else
10736 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file);
10740 * "has()" function
10742 static void
10743 f_has(argvars, rettv)
10744 typval_T *argvars;
10745 typval_T *rettv;
10747 int i;
10748 char_u *name;
10749 int n = FALSE;
10750 static char *(has_list[]) =
10752 #ifdef AMIGA
10753 "amiga",
10754 # ifdef FEAT_ARP
10755 "arp",
10756 # endif
10757 #endif
10758 #ifdef __BEOS__
10759 "beos",
10760 #endif
10761 #ifdef MSDOS
10762 # ifdef DJGPP
10763 "dos32",
10764 # else
10765 "dos16",
10766 # endif
10767 #endif
10768 #ifdef MACOS
10769 "mac",
10770 #endif
10771 #if defined(MACOS_X_UNIX)
10772 "macunix",
10773 #endif
10774 #ifdef OS2
10775 "os2",
10776 #endif
10777 #ifdef __QNX__
10778 "qnx",
10779 #endif
10780 #ifdef RISCOS
10781 "riscos",
10782 #endif
10783 #ifdef UNIX
10784 "unix",
10785 #endif
10786 #ifdef VMS
10787 "vms",
10788 #endif
10789 #ifdef WIN16
10790 "win16",
10791 #endif
10792 #ifdef WIN32
10793 "win32",
10794 #endif
10795 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
10796 "win32unix",
10797 #endif
10798 #ifdef WIN64
10799 "win64",
10800 #endif
10801 #ifdef EBCDIC
10802 "ebcdic",
10803 #endif
10804 #ifndef CASE_INSENSITIVE_FILENAME
10805 "fname_case",
10806 #endif
10807 #ifdef FEAT_ARABIC
10808 "arabic",
10809 #endif
10810 #ifdef FEAT_AUTOCMD
10811 "autocmd",
10812 #endif
10813 #ifdef FEAT_BEVAL
10814 "balloon_eval",
10815 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
10816 "balloon_multiline",
10817 # endif
10818 #endif
10819 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
10820 "builtin_terms",
10821 # ifdef ALL_BUILTIN_TCAPS
10822 "all_builtin_terms",
10823 # endif
10824 #endif
10825 #ifdef FEAT_BYTEOFF
10826 "byte_offset",
10827 #endif
10828 #ifdef FEAT_CINDENT
10829 "cindent",
10830 #endif
10831 #ifdef FEAT_CLIENTSERVER
10832 "clientserver",
10833 #endif
10834 #ifdef FEAT_CLIPBOARD
10835 "clipboard",
10836 #endif
10837 #ifdef FEAT_CMDL_COMPL
10838 "cmdline_compl",
10839 #endif
10840 #ifdef FEAT_CMDHIST
10841 "cmdline_hist",
10842 #endif
10843 #ifdef FEAT_COMMENTS
10844 "comments",
10845 #endif
10846 #ifdef FEAT_CRYPT
10847 "cryptv",
10848 #endif
10849 #ifdef FEAT_CSCOPE
10850 "cscope",
10851 #endif
10852 #ifdef CURSOR_SHAPE
10853 "cursorshape",
10854 #endif
10855 #ifdef DEBUG
10856 "debug",
10857 #endif
10858 #ifdef FEAT_CON_DIALOG
10859 "dialog_con",
10860 #endif
10861 #ifdef FEAT_GUI_DIALOG
10862 "dialog_gui",
10863 #endif
10864 #ifdef FEAT_DIFF
10865 "diff",
10866 #endif
10867 #ifdef FEAT_DIGRAPHS
10868 "digraphs",
10869 #endif
10870 #ifdef FEAT_DND
10871 "dnd",
10872 #endif
10873 #ifdef FEAT_EMACS_TAGS
10874 "emacs_tags",
10875 #endif
10876 "eval", /* always present, of course! */
10877 #ifdef FEAT_EX_EXTRA
10878 "ex_extra",
10879 #endif
10880 #ifdef FEAT_SEARCH_EXTRA
10881 "extra_search",
10882 #endif
10883 #ifdef FEAT_FKMAP
10884 "farsi",
10885 #endif
10886 #ifdef FEAT_SEARCHPATH
10887 "file_in_path",
10888 #endif
10889 #if defined(UNIX) && !defined(USE_SYSTEM)
10890 "filterpipe",
10891 #endif
10892 #ifdef FEAT_FIND_ID
10893 "find_in_path",
10894 #endif
10895 #ifdef FEAT_FOLDING
10896 "folding",
10897 #endif
10898 #ifdef FEAT_FOOTER
10899 "footer",
10900 #endif
10901 #if !defined(USE_SYSTEM) && defined(UNIX)
10902 "fork",
10903 #endif
10904 #ifdef FEAT_FULLSCREEN
10905 "fullscreen",
10906 #endif
10907 #ifdef FEAT_GETTEXT
10908 "gettext",
10909 #endif
10910 #ifdef FEAT_GUI
10911 "gui",
10912 #endif
10913 #ifdef FEAT_GUI_ATHENA
10914 # ifdef FEAT_GUI_NEXTAW
10915 "gui_neXtaw",
10916 # else
10917 "gui_athena",
10918 # endif
10919 #endif
10920 #ifdef FEAT_GUI_GTK
10921 "gui_gtk",
10922 # ifdef HAVE_GTK2
10923 "gui_gtk2",
10924 # endif
10925 #endif
10926 #ifdef FEAT_GUI_GNOME
10927 "gui_gnome",
10928 #endif
10929 #ifdef FEAT_GUI_MAC
10930 "gui_mac",
10931 #endif
10932 #ifdef FEAT_GUI_MACVIM
10933 "gui_macvim",
10934 #endif
10935 #ifdef FEAT_GUI_MOTIF
10936 "gui_motif",
10937 #endif
10938 #ifdef FEAT_GUI_PHOTON
10939 "gui_photon",
10940 #endif
10941 #ifdef FEAT_GUI_W16
10942 "gui_win16",
10943 #endif
10944 #ifdef FEAT_GUI_W32
10945 "gui_win32",
10946 #endif
10947 #ifdef FEAT_HANGULIN
10948 "hangul_input",
10949 #endif
10950 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
10951 "iconv",
10952 #endif
10953 #ifdef FEAT_INS_EXPAND
10954 "insert_expand",
10955 #endif
10956 #ifdef FEAT_JUMPLIST
10957 "jumplist",
10958 #endif
10959 #ifdef FEAT_KEYMAP
10960 "keymap",
10961 #endif
10962 #ifdef FEAT_LANGMAP
10963 "langmap",
10964 #endif
10965 #ifdef FEAT_LIBCALL
10966 "libcall",
10967 #endif
10968 #ifdef FEAT_LINEBREAK
10969 "linebreak",
10970 #endif
10971 #ifdef FEAT_LISP
10972 "lispindent",
10973 #endif
10974 #ifdef FEAT_LISTCMDS
10975 "listcmds",
10976 #endif
10977 #ifdef FEAT_LOCALMAP
10978 "localmap",
10979 #endif
10980 #ifdef FEAT_MENU
10981 "menu",
10982 #endif
10983 #ifdef FEAT_SESSION
10984 "mksession",
10985 #endif
10986 #ifdef FEAT_MODIFY_FNAME
10987 "modify_fname",
10988 #endif
10989 #ifdef FEAT_MOUSE
10990 "mouse",
10991 #endif
10992 #ifdef FEAT_MOUSESHAPE
10993 "mouseshape",
10994 #endif
10995 #if defined(UNIX) || defined(VMS)
10996 # ifdef FEAT_MOUSE_DEC
10997 "mouse_dec",
10998 # endif
10999 # ifdef FEAT_MOUSE_GPM
11000 "mouse_gpm",
11001 # endif
11002 # ifdef FEAT_MOUSE_JSB
11003 "mouse_jsbterm",
11004 # endif
11005 # ifdef FEAT_MOUSE_NET
11006 "mouse_netterm",
11007 # endif
11008 # ifdef FEAT_MOUSE_PTERM
11009 "mouse_pterm",
11010 # endif
11011 # ifdef FEAT_MOUSE_XTERM
11012 "mouse_xterm",
11013 # endif
11014 #endif
11015 #ifdef FEAT_MBYTE
11016 "multi_byte",
11017 #endif
11018 #ifdef FEAT_MBYTE_IME
11019 "multi_byte_ime",
11020 #endif
11021 #ifdef FEAT_MULTI_LANG
11022 "multi_lang",
11023 #endif
11024 #ifdef FEAT_MZSCHEME
11025 #ifndef DYNAMIC_MZSCHEME
11026 "mzscheme",
11027 #endif
11028 #endif
11029 #ifdef FEAT_OLE
11030 "ole",
11031 #endif
11032 #ifdef FEAT_OSFILETYPE
11033 "osfiletype",
11034 #endif
11035 #ifdef FEAT_PATH_EXTRA
11036 "path_extra",
11037 #endif
11038 #ifdef FEAT_PERL
11039 #ifndef DYNAMIC_PERL
11040 "perl",
11041 #endif
11042 #endif
11043 #ifdef FEAT_PYTHON
11044 #ifndef DYNAMIC_PYTHON
11045 "python",
11046 #endif
11047 #endif
11048 #ifdef FEAT_POSTSCRIPT
11049 "postscript",
11050 #endif
11051 #ifdef FEAT_PRINTER
11052 "printer",
11053 #endif
11054 #ifdef FEAT_PROFILE
11055 "profile",
11056 #endif
11057 #ifdef FEAT_RELTIME
11058 "reltime",
11059 #endif
11060 #ifdef FEAT_QUICKFIX
11061 "quickfix",
11062 #endif
11063 #ifdef FEAT_RIGHTLEFT
11064 "rightleft",
11065 #endif
11066 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11067 "ruby",
11068 #endif
11069 #ifdef FEAT_SCROLLBIND
11070 "scrollbind",
11071 #endif
11072 #ifdef FEAT_CMDL_INFO
11073 "showcmd",
11074 "cmdline_info",
11075 #endif
11076 #ifdef FEAT_SIGNS
11077 "signs",
11078 #endif
11079 #ifdef FEAT_SMARTINDENT
11080 "smartindent",
11081 #endif
11082 #ifdef FEAT_SNIFF
11083 "sniff",
11084 #endif
11085 #ifdef FEAT_STL_OPT
11086 "statusline",
11087 #endif
11088 #ifdef FEAT_SUN_WORKSHOP
11089 "sun_workshop",
11090 #endif
11091 #ifdef FEAT_NETBEANS_INTG
11092 "netbeans_intg",
11093 #endif
11094 #ifdef FEAT_ODB_EDITOR
11095 "odbeditor",
11096 #endif
11097 #ifdef FEAT_SPELL
11098 "spell",
11099 #endif
11100 #ifdef FEAT_SYN_HL
11101 "syntax",
11102 #endif
11103 #if defined(USE_SYSTEM) || !defined(UNIX)
11104 "system",
11105 #endif
11106 #ifdef FEAT_TAG_BINS
11107 "tag_binary",
11108 #endif
11109 #ifdef FEAT_TAG_OLDSTATIC
11110 "tag_old_static",
11111 #endif
11112 #ifdef FEAT_TAG_ANYWHITE
11113 "tag_any_white",
11114 #endif
11115 #ifdef FEAT_TCL
11116 # ifndef DYNAMIC_TCL
11117 "tcl",
11118 # endif
11119 #endif
11120 #ifdef TERMINFO
11121 "terminfo",
11122 #endif
11123 #ifdef FEAT_TERMRESPONSE
11124 "termresponse",
11125 #endif
11126 #ifdef FEAT_TEXTOBJ
11127 "textobjects",
11128 #endif
11129 #ifdef HAVE_TGETENT
11130 "tgetent",
11131 #endif
11132 #ifdef FEAT_TITLE
11133 "title",
11134 #endif
11135 #ifdef FEAT_TOOLBAR
11136 "toolbar",
11137 #endif
11138 #ifdef FEAT_TRANSPARENCY
11139 "transparency",
11140 #endif
11141 #ifdef FEAT_USR_CMDS
11142 "user-commands", /* was accidentally included in 5.4 */
11143 "user_commands",
11144 #endif
11145 #ifdef FEAT_VIMINFO
11146 "viminfo",
11147 #endif
11148 #ifdef FEAT_VERTSPLIT
11149 "vertsplit",
11150 #endif
11151 #ifdef FEAT_VIRTUALEDIT
11152 "virtualedit",
11153 #endif
11154 #ifdef FEAT_VISUAL
11155 "visual",
11156 #endif
11157 #ifdef FEAT_VISUALEXTRA
11158 "visualextra",
11159 #endif
11160 #ifdef FEAT_VREPLACE
11161 "vreplace",
11162 #endif
11163 #ifdef FEAT_WILDIGN
11164 "wildignore",
11165 #endif
11166 #ifdef FEAT_WILDMENU
11167 "wildmenu",
11168 #endif
11169 #ifdef FEAT_WINDOWS
11170 "windows",
11171 #endif
11172 #ifdef FEAT_WAK
11173 "winaltkeys",
11174 #endif
11175 #ifdef FEAT_WRITEBACKUP
11176 "writebackup",
11177 #endif
11178 #ifdef FEAT_XIM
11179 "xim",
11180 #endif
11181 #ifdef FEAT_XFONTSET
11182 "xfontset",
11183 #endif
11184 #ifdef USE_XSMP
11185 "xsmp",
11186 #endif
11187 #ifdef USE_XSMP_INTERACT
11188 "xsmp_interact",
11189 #endif
11190 #ifdef FEAT_XCLIPBOARD
11191 "xterm_clipboard",
11192 #endif
11193 #ifdef FEAT_XTERM_SAVE
11194 "xterm_save",
11195 #endif
11196 #if defined(UNIX) && defined(FEAT_X11)
11197 "X11",
11198 #endif
11199 NULL
11202 name = get_tv_string(&argvars[0]);
11203 for (i = 0; has_list[i] != NULL; ++i)
11204 if (STRICMP(name, has_list[i]) == 0)
11206 n = TRUE;
11207 break;
11210 if (n == FALSE)
11212 if (STRNICMP(name, "patch", 5) == 0)
11213 n = has_patch(atoi((char *)name + 5));
11214 else if (STRICMP(name, "vim_starting") == 0)
11215 n = (starting != 0);
11216 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
11217 else if (STRICMP(name, "balloon_multiline") == 0)
11218 n = multiline_balloon_available();
11219 #endif
11220 #ifdef DYNAMIC_TCL
11221 else if (STRICMP(name, "tcl") == 0)
11222 n = tcl_enabled(FALSE);
11223 #endif
11224 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
11225 else if (STRICMP(name, "iconv") == 0)
11226 n = iconv_enabled(FALSE);
11227 #endif
11228 #ifdef DYNAMIC_MZSCHEME
11229 else if (STRICMP(name, "mzscheme") == 0)
11230 n = mzscheme_enabled(FALSE);
11231 #endif
11232 #ifdef DYNAMIC_RUBY
11233 else if (STRICMP(name, "ruby") == 0)
11234 n = ruby_enabled(FALSE);
11235 #endif
11236 #ifdef DYNAMIC_PYTHON
11237 else if (STRICMP(name, "python") == 0)
11238 n = python_enabled(FALSE);
11239 #endif
11240 #ifdef DYNAMIC_PERL
11241 else if (STRICMP(name, "perl") == 0)
11242 n = perl_enabled(FALSE);
11243 #endif
11244 #ifdef FEAT_GUI
11245 else if (STRICMP(name, "gui_running") == 0)
11246 n = (gui.in_use || gui.starting);
11247 # ifdef FEAT_GUI_W32
11248 else if (STRICMP(name, "gui_win32s") == 0)
11249 n = gui_is_win32s();
11250 # endif
11251 # ifdef FEAT_BROWSE
11252 else if (STRICMP(name, "browse") == 0)
11253 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
11254 # endif
11255 #endif
11256 #ifdef FEAT_SYN_HL
11257 else if (STRICMP(name, "syntax_items") == 0)
11258 n = syntax_present(curbuf);
11259 #endif
11260 #if defined(WIN3264)
11261 else if (STRICMP(name, "win95") == 0)
11262 n = mch_windows95();
11263 #endif
11264 #ifdef FEAT_NETBEANS_INTG
11265 else if (STRICMP(name, "netbeans_enabled") == 0)
11266 n = usingNetbeans;
11267 #endif
11270 rettv->vval.v_number = n;
11274 * "has_key()" function
11276 static void
11277 f_has_key(argvars, rettv)
11278 typval_T *argvars;
11279 typval_T *rettv;
11281 rettv->vval.v_number = 0;
11282 if (argvars[0].v_type != VAR_DICT)
11284 EMSG(_(e_dictreq));
11285 return;
11287 if (argvars[0].vval.v_dict == NULL)
11288 return;
11290 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
11291 get_tv_string(&argvars[1]), -1) != NULL;
11295 * "haslocaldir()" function
11297 /*ARGSUSED*/
11298 static void
11299 f_haslocaldir(argvars, rettv)
11300 typval_T *argvars;
11301 typval_T *rettv;
11303 rettv->vval.v_number = (curwin->w_localdir != NULL);
11307 * "hasmapto()" function
11309 static void
11310 f_hasmapto(argvars, rettv)
11311 typval_T *argvars;
11312 typval_T *rettv;
11314 char_u *name;
11315 char_u *mode;
11316 char_u buf[NUMBUFLEN];
11317 int abbr = FALSE;
11319 name = get_tv_string(&argvars[0]);
11320 if (argvars[1].v_type == VAR_UNKNOWN)
11321 mode = (char_u *)"nvo";
11322 else
11324 mode = get_tv_string_buf(&argvars[1], buf);
11325 if (argvars[2].v_type != VAR_UNKNOWN)
11326 abbr = get_tv_number(&argvars[2]);
11329 if (map_to_exists(name, mode, abbr))
11330 rettv->vval.v_number = TRUE;
11331 else
11332 rettv->vval.v_number = FALSE;
11336 * "histadd()" function
11338 /*ARGSUSED*/
11339 static void
11340 f_histadd(argvars, rettv)
11341 typval_T *argvars;
11342 typval_T *rettv;
11344 #ifdef FEAT_CMDHIST
11345 int histype;
11346 char_u *str;
11347 char_u buf[NUMBUFLEN];
11348 #endif
11350 rettv->vval.v_number = FALSE;
11351 if (check_restricted() || check_secure())
11352 return;
11353 #ifdef FEAT_CMDHIST
11354 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11355 histype = str != NULL ? get_histtype(str) : -1;
11356 if (histype >= 0)
11358 str = get_tv_string_buf(&argvars[1], buf);
11359 if (*str != NUL)
11361 add_to_history(histype, str, FALSE, NUL);
11362 rettv->vval.v_number = TRUE;
11363 return;
11366 #endif
11370 * "histdel()" function
11372 /*ARGSUSED*/
11373 static void
11374 f_histdel(argvars, rettv)
11375 typval_T *argvars;
11376 typval_T *rettv;
11378 #ifdef FEAT_CMDHIST
11379 int n;
11380 char_u buf[NUMBUFLEN];
11381 char_u *str;
11383 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11384 if (str == NULL)
11385 n = 0;
11386 else if (argvars[1].v_type == VAR_UNKNOWN)
11387 /* only one argument: clear entire history */
11388 n = clr_history(get_histtype(str));
11389 else if (argvars[1].v_type == VAR_NUMBER)
11390 /* index given: remove that entry */
11391 n = del_history_idx(get_histtype(str),
11392 (int)get_tv_number(&argvars[1]));
11393 else
11394 /* string given: remove all matching entries */
11395 n = del_history_entry(get_histtype(str),
11396 get_tv_string_buf(&argvars[1], buf));
11397 rettv->vval.v_number = n;
11398 #else
11399 rettv->vval.v_number = 0;
11400 #endif
11404 * "histget()" function
11406 /*ARGSUSED*/
11407 static void
11408 f_histget(argvars, rettv)
11409 typval_T *argvars;
11410 typval_T *rettv;
11412 #ifdef FEAT_CMDHIST
11413 int type;
11414 int idx;
11415 char_u *str;
11417 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11418 if (str == NULL)
11419 rettv->vval.v_string = NULL;
11420 else
11422 type = get_histtype(str);
11423 if (argvars[1].v_type == VAR_UNKNOWN)
11424 idx = get_history_idx(type);
11425 else
11426 idx = (int)get_tv_number_chk(&argvars[1], NULL);
11427 /* -1 on type error */
11428 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
11430 #else
11431 rettv->vval.v_string = NULL;
11432 #endif
11433 rettv->v_type = VAR_STRING;
11437 * "histnr()" function
11439 /*ARGSUSED*/
11440 static void
11441 f_histnr(argvars, rettv)
11442 typval_T *argvars;
11443 typval_T *rettv;
11445 int i;
11447 #ifdef FEAT_CMDHIST
11448 char_u *history = get_tv_string_chk(&argvars[0]);
11450 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
11451 if (i >= HIST_CMD && i < HIST_COUNT)
11452 i = get_history_idx(i);
11453 else
11454 #endif
11455 i = -1;
11456 rettv->vval.v_number = i;
11460 * "highlightID(name)" function
11462 static void
11463 f_hlID(argvars, rettv)
11464 typval_T *argvars;
11465 typval_T *rettv;
11467 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
11471 * "highlight_exists()" function
11473 static void
11474 f_hlexists(argvars, rettv)
11475 typval_T *argvars;
11476 typval_T *rettv;
11478 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
11482 * "hostname()" function
11484 /*ARGSUSED*/
11485 static void
11486 f_hostname(argvars, rettv)
11487 typval_T *argvars;
11488 typval_T *rettv;
11490 char_u hostname[256];
11492 mch_get_host_name(hostname, 256);
11493 rettv->v_type = VAR_STRING;
11494 rettv->vval.v_string = vim_strsave(hostname);
11498 * iconv() function
11500 /*ARGSUSED*/
11501 static void
11502 f_iconv(argvars, rettv)
11503 typval_T *argvars;
11504 typval_T *rettv;
11506 #ifdef FEAT_MBYTE
11507 char_u buf1[NUMBUFLEN];
11508 char_u buf2[NUMBUFLEN];
11509 char_u *from, *to, *str;
11510 vimconv_T vimconv;
11511 #endif
11513 rettv->v_type = VAR_STRING;
11514 rettv->vval.v_string = NULL;
11516 #ifdef FEAT_MBYTE
11517 str = get_tv_string(&argvars[0]);
11518 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
11519 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
11520 vimconv.vc_type = CONV_NONE;
11521 convert_setup(&vimconv, from, to);
11523 /* If the encodings are equal, no conversion needed. */
11524 if (vimconv.vc_type == CONV_NONE)
11525 rettv->vval.v_string = vim_strsave(str);
11526 else
11527 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
11529 convert_setup(&vimconv, NULL, NULL);
11530 vim_free(from);
11531 vim_free(to);
11532 #endif
11536 * "indent()" function
11538 static void
11539 f_indent(argvars, rettv)
11540 typval_T *argvars;
11541 typval_T *rettv;
11543 linenr_T lnum;
11545 lnum = get_tv_lnum(argvars);
11546 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
11547 rettv->vval.v_number = get_indent_lnum(lnum);
11548 else
11549 rettv->vval.v_number = -1;
11553 * "index()" function
11555 static void
11556 f_index(argvars, rettv)
11557 typval_T *argvars;
11558 typval_T *rettv;
11560 list_T *l;
11561 listitem_T *item;
11562 long idx = 0;
11563 int ic = FALSE;
11565 rettv->vval.v_number = -1;
11566 if (argvars[0].v_type != VAR_LIST)
11568 EMSG(_(e_listreq));
11569 return;
11571 l = argvars[0].vval.v_list;
11572 if (l != NULL)
11574 item = l->lv_first;
11575 if (argvars[2].v_type != VAR_UNKNOWN)
11577 int error = FALSE;
11579 /* Start at specified item. Use the cached index that list_find()
11580 * sets, so that a negative number also works. */
11581 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
11582 idx = l->lv_idx;
11583 if (argvars[3].v_type != VAR_UNKNOWN)
11584 ic = get_tv_number_chk(&argvars[3], &error);
11585 if (error)
11586 item = NULL;
11589 for ( ; item != NULL; item = item->li_next, ++idx)
11590 if (tv_equal(&item->li_tv, &argvars[1], ic))
11592 rettv->vval.v_number = idx;
11593 break;
11598 static int inputsecret_flag = 0;
11600 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
11603 * This function is used by f_input() and f_inputdialog() functions. The third
11604 * argument to f_input() specifies the type of completion to use at the
11605 * prompt. The third argument to f_inputdialog() specifies the value to return
11606 * when the user cancels the prompt.
11608 static void
11609 get_user_input(argvars, rettv, inputdialog)
11610 typval_T *argvars;
11611 typval_T *rettv;
11612 int inputdialog;
11614 char_u *prompt = get_tv_string_chk(&argvars[0]);
11615 char_u *p = NULL;
11616 int c;
11617 char_u buf[NUMBUFLEN];
11618 int cmd_silent_save = cmd_silent;
11619 char_u *defstr = (char_u *)"";
11620 int xp_type = EXPAND_NOTHING;
11621 char_u *xp_arg = NULL;
11623 rettv->v_type = VAR_STRING;
11624 rettv->vval.v_string = NULL;
11626 #ifdef NO_CONSOLE_INPUT
11627 /* While starting up, there is no place to enter text. */
11628 if (no_console_input())
11629 return;
11630 #endif
11632 cmd_silent = FALSE; /* Want to see the prompt. */
11633 if (prompt != NULL)
11635 /* Only the part of the message after the last NL is considered as
11636 * prompt for the command line */
11637 p = vim_strrchr(prompt, '\n');
11638 if (p == NULL)
11639 p = prompt;
11640 else
11642 ++p;
11643 c = *p;
11644 *p = NUL;
11645 msg_start();
11646 msg_clr_eos();
11647 msg_puts_attr(prompt, echo_attr);
11648 msg_didout = FALSE;
11649 msg_starthere();
11650 *p = c;
11652 cmdline_row = msg_row;
11654 if (argvars[1].v_type != VAR_UNKNOWN)
11656 defstr = get_tv_string_buf_chk(&argvars[1], buf);
11657 if (defstr != NULL)
11658 stuffReadbuffSpec(defstr);
11660 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
11662 char_u *xp_name;
11663 int xp_namelen;
11664 long argt;
11666 rettv->vval.v_string = NULL;
11668 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
11669 if (xp_name == NULL)
11670 return;
11672 xp_namelen = (int)STRLEN(xp_name);
11674 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
11675 &xp_arg) == FAIL)
11676 return;
11680 if (defstr != NULL)
11681 rettv->vval.v_string =
11682 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
11683 xp_type, xp_arg);
11685 vim_free(xp_arg);
11687 /* since the user typed this, no need to wait for return */
11688 need_wait_return = FALSE;
11689 msg_didout = FALSE;
11691 cmd_silent = cmd_silent_save;
11695 * "input()" function
11696 * Also handles inputsecret() when inputsecret is set.
11698 static void
11699 f_input(argvars, rettv)
11700 typval_T *argvars;
11701 typval_T *rettv;
11703 get_user_input(argvars, rettv, FALSE);
11707 * "inputdialog()" function
11709 static void
11710 f_inputdialog(argvars, rettv)
11711 typval_T *argvars;
11712 typval_T *rettv;
11714 #if defined(FEAT_GUI_TEXTDIALOG)
11715 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
11716 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
11718 char_u *message;
11719 char_u buf[NUMBUFLEN];
11720 char_u *defstr = (char_u *)"";
11722 message = get_tv_string_chk(&argvars[0]);
11723 if (argvars[1].v_type != VAR_UNKNOWN
11724 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
11725 vim_strncpy(IObuff, defstr, IOSIZE - 1);
11726 else
11727 IObuff[0] = NUL;
11728 if (message != NULL && defstr != NULL
11729 && do_dialog(VIM_QUESTION, NULL, message,
11730 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
11731 rettv->vval.v_string = vim_strsave(IObuff);
11732 else
11734 if (message != NULL && defstr != NULL
11735 && argvars[1].v_type != VAR_UNKNOWN
11736 && argvars[2].v_type != VAR_UNKNOWN)
11737 rettv->vval.v_string = vim_strsave(
11738 get_tv_string_buf(&argvars[2], buf));
11739 else
11740 rettv->vval.v_string = NULL;
11742 rettv->v_type = VAR_STRING;
11744 else
11745 #endif
11746 get_user_input(argvars, rettv, TRUE);
11750 * "inputlist()" function
11752 static void
11753 f_inputlist(argvars, rettv)
11754 typval_T *argvars;
11755 typval_T *rettv;
11757 listitem_T *li;
11758 int selected;
11759 int mouse_used;
11761 rettv->vval.v_number = 0;
11762 #ifdef NO_CONSOLE_INPUT
11763 /* While starting up, there is no place to enter text. */
11764 if (no_console_input())
11765 return;
11766 #endif
11767 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
11769 EMSG2(_(e_listarg), "inputlist()");
11770 return;
11773 msg_start();
11774 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
11775 lines_left = Rows; /* avoid more prompt */
11776 msg_scroll = TRUE;
11777 msg_clr_eos();
11779 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
11781 msg_puts(get_tv_string(&li->li_tv));
11782 msg_putchar('\n');
11785 /* Ask for choice. */
11786 selected = prompt_for_number(&mouse_used);
11787 if (mouse_used)
11788 selected -= lines_left;
11790 rettv->vval.v_number = selected;
11794 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
11797 * "inputrestore()" function
11799 /*ARGSUSED*/
11800 static void
11801 f_inputrestore(argvars, rettv)
11802 typval_T *argvars;
11803 typval_T *rettv;
11805 if (ga_userinput.ga_len > 0)
11807 --ga_userinput.ga_len;
11808 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
11809 + ga_userinput.ga_len);
11810 rettv->vval.v_number = 0; /* OK */
11812 else if (p_verbose > 1)
11814 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
11815 rettv->vval.v_number = 1; /* Failed */
11820 * "inputsave()" function
11822 /*ARGSUSED*/
11823 static void
11824 f_inputsave(argvars, rettv)
11825 typval_T *argvars;
11826 typval_T *rettv;
11828 /* Add an entry to the stack of typehead storage. */
11829 if (ga_grow(&ga_userinput, 1) == OK)
11831 save_typeahead((tasave_T *)(ga_userinput.ga_data)
11832 + ga_userinput.ga_len);
11833 ++ga_userinput.ga_len;
11834 rettv->vval.v_number = 0; /* OK */
11836 else
11837 rettv->vval.v_number = 1; /* Failed */
11841 * "inputsecret()" function
11843 static void
11844 f_inputsecret(argvars, rettv)
11845 typval_T *argvars;
11846 typval_T *rettv;
11848 ++cmdline_star;
11849 ++inputsecret_flag;
11850 f_input(argvars, rettv);
11851 --cmdline_star;
11852 --inputsecret_flag;
11856 * "insert()" function
11858 static void
11859 f_insert(argvars, rettv)
11860 typval_T *argvars;
11861 typval_T *rettv;
11863 long before = 0;
11864 listitem_T *item;
11865 list_T *l;
11866 int error = FALSE;
11868 rettv->vval.v_number = 0;
11869 if (argvars[0].v_type != VAR_LIST)
11870 EMSG2(_(e_listarg), "insert()");
11871 else if ((l = argvars[0].vval.v_list) != NULL
11872 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
11874 if (argvars[2].v_type != VAR_UNKNOWN)
11875 before = get_tv_number_chk(&argvars[2], &error);
11876 if (error)
11877 return; /* type error; errmsg already given */
11879 if (before == l->lv_len)
11880 item = NULL;
11881 else
11883 item = list_find(l, before);
11884 if (item == NULL)
11886 EMSGN(_(e_listidx), before);
11887 l = NULL;
11890 if (l != NULL)
11892 list_insert_tv(l, &argvars[1], item);
11893 copy_tv(&argvars[0], rettv);
11899 * "isdirectory()" function
11901 static void
11902 f_isdirectory(argvars, rettv)
11903 typval_T *argvars;
11904 typval_T *rettv;
11906 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
11910 * "islocked()" function
11912 static void
11913 f_islocked(argvars, rettv)
11914 typval_T *argvars;
11915 typval_T *rettv;
11917 lval_T lv;
11918 char_u *end;
11919 dictitem_T *di;
11921 rettv->vval.v_number = -1;
11922 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
11923 FNE_CHECK_START);
11924 if (end != NULL && lv.ll_name != NULL)
11926 if (*end != NUL)
11927 EMSG(_(e_trailing));
11928 else
11930 if (lv.ll_tv == NULL)
11932 if (check_changedtick(lv.ll_name))
11933 rettv->vval.v_number = 1; /* always locked */
11934 else
11936 di = find_var(lv.ll_name, NULL);
11937 if (di != NULL)
11939 /* Consider a variable locked when:
11940 * 1. the variable itself is locked
11941 * 2. the value of the variable is locked.
11942 * 3. the List or Dict value is locked.
11944 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
11945 || tv_islocked(&di->di_tv));
11949 else if (lv.ll_range)
11950 EMSG(_("E786: Range not allowed"));
11951 else if (lv.ll_newkey != NULL)
11952 EMSG2(_(e_dictkey), lv.ll_newkey);
11953 else if (lv.ll_list != NULL)
11954 /* List item. */
11955 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
11956 else
11957 /* Dictionary item. */
11958 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
11962 clear_lval(&lv);
11965 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
11968 * Turn a dict into a list:
11969 * "what" == 0: list of keys
11970 * "what" == 1: list of values
11971 * "what" == 2: list of items
11973 static void
11974 dict_list(argvars, rettv, what)
11975 typval_T *argvars;
11976 typval_T *rettv;
11977 int what;
11979 list_T *l2;
11980 dictitem_T *di;
11981 hashitem_T *hi;
11982 listitem_T *li;
11983 listitem_T *li2;
11984 dict_T *d;
11985 int todo;
11987 rettv->vval.v_number = 0;
11988 if (argvars[0].v_type != VAR_DICT)
11990 EMSG(_(e_dictreq));
11991 return;
11993 if ((d = argvars[0].vval.v_dict) == NULL)
11994 return;
11996 if (rettv_list_alloc(rettv) == FAIL)
11997 return;
11999 todo = (int)d->dv_hashtab.ht_used;
12000 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12002 if (!HASHITEM_EMPTY(hi))
12004 --todo;
12005 di = HI2DI(hi);
12007 li = listitem_alloc();
12008 if (li == NULL)
12009 break;
12010 list_append(rettv->vval.v_list, li);
12012 if (what == 0)
12014 /* keys() */
12015 li->li_tv.v_type = VAR_STRING;
12016 li->li_tv.v_lock = 0;
12017 li->li_tv.vval.v_string = vim_strsave(di->di_key);
12019 else if (what == 1)
12021 /* values() */
12022 copy_tv(&di->di_tv, &li->li_tv);
12024 else
12026 /* items() */
12027 l2 = list_alloc();
12028 li->li_tv.v_type = VAR_LIST;
12029 li->li_tv.v_lock = 0;
12030 li->li_tv.vval.v_list = l2;
12031 if (l2 == NULL)
12032 break;
12033 ++l2->lv_refcount;
12035 li2 = listitem_alloc();
12036 if (li2 == NULL)
12037 break;
12038 list_append(l2, li2);
12039 li2->li_tv.v_type = VAR_STRING;
12040 li2->li_tv.v_lock = 0;
12041 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12043 li2 = listitem_alloc();
12044 if (li2 == NULL)
12045 break;
12046 list_append(l2, li2);
12047 copy_tv(&di->di_tv, &li2->li_tv);
12054 * "items(dict)" function
12056 static void
12057 f_items(argvars, rettv)
12058 typval_T *argvars;
12059 typval_T *rettv;
12061 dict_list(argvars, rettv, 2);
12065 * "join()" function
12067 static void
12068 f_join(argvars, rettv)
12069 typval_T *argvars;
12070 typval_T *rettv;
12072 garray_T ga;
12073 char_u *sep;
12075 rettv->vval.v_number = 0;
12076 if (argvars[0].v_type != VAR_LIST)
12078 EMSG(_(e_listreq));
12079 return;
12081 if (argvars[0].vval.v_list == NULL)
12082 return;
12083 if (argvars[1].v_type == VAR_UNKNOWN)
12084 sep = (char_u *)" ";
12085 else
12086 sep = get_tv_string_chk(&argvars[1]);
12088 rettv->v_type = VAR_STRING;
12090 if (sep != NULL)
12092 ga_init2(&ga, (int)sizeof(char), 80);
12093 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12094 ga_append(&ga, NUL);
12095 rettv->vval.v_string = (char_u *)ga.ga_data;
12097 else
12098 rettv->vval.v_string = NULL;
12102 * "keys()" function
12104 static void
12105 f_keys(argvars, rettv)
12106 typval_T *argvars;
12107 typval_T *rettv;
12109 dict_list(argvars, rettv, 0);
12113 * "last_buffer_nr()" function.
12115 /*ARGSUSED*/
12116 static void
12117 f_last_buffer_nr(argvars, rettv)
12118 typval_T *argvars;
12119 typval_T *rettv;
12121 int n = 0;
12122 buf_T *buf;
12124 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12125 if (n < buf->b_fnum)
12126 n = buf->b_fnum;
12128 rettv->vval.v_number = n;
12132 * "len()" function
12134 static void
12135 f_len(argvars, rettv)
12136 typval_T *argvars;
12137 typval_T *rettv;
12139 switch (argvars[0].v_type)
12141 case VAR_STRING:
12142 case VAR_NUMBER:
12143 rettv->vval.v_number = (varnumber_T)STRLEN(
12144 get_tv_string(&argvars[0]));
12145 break;
12146 case VAR_LIST:
12147 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
12148 break;
12149 case VAR_DICT:
12150 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
12151 break;
12152 default:
12153 EMSG(_("E701: Invalid type for len()"));
12154 break;
12158 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
12160 static void
12161 libcall_common(argvars, rettv, type)
12162 typval_T *argvars;
12163 typval_T *rettv;
12164 int type;
12166 #ifdef FEAT_LIBCALL
12167 char_u *string_in;
12168 char_u **string_result;
12169 int nr_result;
12170 #endif
12172 rettv->v_type = type;
12173 if (type == VAR_NUMBER)
12174 rettv->vval.v_number = 0;
12175 else
12176 rettv->vval.v_string = NULL;
12178 if (check_restricted() || check_secure())
12179 return;
12181 #ifdef FEAT_LIBCALL
12182 /* The first two args must be strings, otherwise its meaningless */
12183 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
12185 string_in = NULL;
12186 if (argvars[2].v_type == VAR_STRING)
12187 string_in = argvars[2].vval.v_string;
12188 if (type == VAR_NUMBER)
12189 string_result = NULL;
12190 else
12191 string_result = &rettv->vval.v_string;
12192 if (mch_libcall(argvars[0].vval.v_string,
12193 argvars[1].vval.v_string,
12194 string_in,
12195 argvars[2].vval.v_number,
12196 string_result,
12197 &nr_result) == OK
12198 && type == VAR_NUMBER)
12199 rettv->vval.v_number = nr_result;
12201 #endif
12205 * "libcall()" function
12207 static void
12208 f_libcall(argvars, rettv)
12209 typval_T *argvars;
12210 typval_T *rettv;
12212 libcall_common(argvars, rettv, VAR_STRING);
12216 * "libcallnr()" function
12218 static void
12219 f_libcallnr(argvars, rettv)
12220 typval_T *argvars;
12221 typval_T *rettv;
12223 libcall_common(argvars, rettv, VAR_NUMBER);
12227 * "line(string)" function
12229 static void
12230 f_line(argvars, rettv)
12231 typval_T *argvars;
12232 typval_T *rettv;
12234 linenr_T lnum = 0;
12235 pos_T *fp;
12236 int fnum;
12238 fp = var2fpos(&argvars[0], TRUE, &fnum);
12239 if (fp != NULL)
12240 lnum = fp->lnum;
12241 rettv->vval.v_number = lnum;
12245 * "line2byte(lnum)" function
12247 /*ARGSUSED*/
12248 static void
12249 f_line2byte(argvars, rettv)
12250 typval_T *argvars;
12251 typval_T *rettv;
12253 #ifndef FEAT_BYTEOFF
12254 rettv->vval.v_number = -1;
12255 #else
12256 linenr_T lnum;
12258 lnum = get_tv_lnum(argvars);
12259 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
12260 rettv->vval.v_number = -1;
12261 else
12262 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
12263 if (rettv->vval.v_number >= 0)
12264 ++rettv->vval.v_number;
12265 #endif
12269 * "lispindent(lnum)" function
12271 static void
12272 f_lispindent(argvars, rettv)
12273 typval_T *argvars;
12274 typval_T *rettv;
12276 #ifdef FEAT_LISP
12277 pos_T pos;
12278 linenr_T lnum;
12280 pos = curwin->w_cursor;
12281 lnum = get_tv_lnum(argvars);
12282 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12284 curwin->w_cursor.lnum = lnum;
12285 rettv->vval.v_number = get_lisp_indent();
12286 curwin->w_cursor = pos;
12288 else
12289 #endif
12290 rettv->vval.v_number = -1;
12294 * "localtime()" function
12296 /*ARGSUSED*/
12297 static void
12298 f_localtime(argvars, rettv)
12299 typval_T *argvars;
12300 typval_T *rettv;
12302 rettv->vval.v_number = (varnumber_T)time(NULL);
12305 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
12307 static void
12308 get_maparg(argvars, rettv, exact)
12309 typval_T *argvars;
12310 typval_T *rettv;
12311 int exact;
12313 char_u *keys;
12314 char_u *which;
12315 char_u buf[NUMBUFLEN];
12316 char_u *keys_buf = NULL;
12317 char_u *rhs;
12318 int mode;
12319 garray_T ga;
12320 int abbr = FALSE;
12322 /* return empty string for failure */
12323 rettv->v_type = VAR_STRING;
12324 rettv->vval.v_string = NULL;
12326 keys = get_tv_string(&argvars[0]);
12327 if (*keys == NUL)
12328 return;
12330 if (argvars[1].v_type != VAR_UNKNOWN)
12332 which = get_tv_string_buf_chk(&argvars[1], buf);
12333 if (argvars[2].v_type != VAR_UNKNOWN)
12334 abbr = get_tv_number(&argvars[2]);
12336 else
12337 which = (char_u *)"";
12338 if (which == NULL)
12339 return;
12341 mode = get_map_mode(&which, 0);
12343 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
12344 rhs = check_map(keys, mode, exact, FALSE, abbr);
12345 vim_free(keys_buf);
12346 if (rhs != NULL)
12348 ga_init(&ga);
12349 ga.ga_itemsize = 1;
12350 ga.ga_growsize = 40;
12352 while (*rhs != NUL)
12353 ga_concat(&ga, str2special(&rhs, FALSE));
12355 ga_append(&ga, NUL);
12356 rettv->vval.v_string = (char_u *)ga.ga_data;
12361 * "map()" function
12363 static void
12364 f_map(argvars, rettv)
12365 typval_T *argvars;
12366 typval_T *rettv;
12368 filter_map(argvars, rettv, TRUE);
12372 * "maparg()" function
12374 static void
12375 f_maparg(argvars, rettv)
12376 typval_T *argvars;
12377 typval_T *rettv;
12379 get_maparg(argvars, rettv, TRUE);
12383 * "mapcheck()" function
12385 static void
12386 f_mapcheck(argvars, rettv)
12387 typval_T *argvars;
12388 typval_T *rettv;
12390 get_maparg(argvars, rettv, FALSE);
12393 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
12395 static void
12396 find_some_match(argvars, rettv, type)
12397 typval_T *argvars;
12398 typval_T *rettv;
12399 int type;
12401 char_u *str = NULL;
12402 char_u *expr = NULL;
12403 char_u *pat;
12404 regmatch_T regmatch;
12405 char_u patbuf[NUMBUFLEN];
12406 char_u strbuf[NUMBUFLEN];
12407 char_u *save_cpo;
12408 long start = 0;
12409 long nth = 1;
12410 colnr_T startcol = 0;
12411 int match = 0;
12412 list_T *l = NULL;
12413 listitem_T *li = NULL;
12414 long idx = 0;
12415 char_u *tofree = NULL;
12417 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
12418 save_cpo = p_cpo;
12419 p_cpo = (char_u *)"";
12421 rettv->vval.v_number = -1;
12422 if (type == 3)
12424 /* return empty list when there are no matches */
12425 if (rettv_list_alloc(rettv) == FAIL)
12426 goto theend;
12428 else if (type == 2)
12430 rettv->v_type = VAR_STRING;
12431 rettv->vval.v_string = NULL;
12434 if (argvars[0].v_type == VAR_LIST)
12436 if ((l = argvars[0].vval.v_list) == NULL)
12437 goto theend;
12438 li = l->lv_first;
12440 else
12441 expr = str = get_tv_string(&argvars[0]);
12443 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
12444 if (pat == NULL)
12445 goto theend;
12447 if (argvars[2].v_type != VAR_UNKNOWN)
12449 int error = FALSE;
12451 start = get_tv_number_chk(&argvars[2], &error);
12452 if (error)
12453 goto theend;
12454 if (l != NULL)
12456 li = list_find(l, start);
12457 if (li == NULL)
12458 goto theend;
12459 idx = l->lv_idx; /* use the cached index */
12461 else
12463 if (start < 0)
12464 start = 0;
12465 if (start > (long)STRLEN(str))
12466 goto theend;
12467 /* When "count" argument is there ignore matches before "start",
12468 * otherwise skip part of the string. Differs when pattern is "^"
12469 * or "\<". */
12470 if (argvars[3].v_type != VAR_UNKNOWN)
12471 startcol = start;
12472 else
12473 str += start;
12476 if (argvars[3].v_type != VAR_UNKNOWN)
12477 nth = get_tv_number_chk(&argvars[3], &error);
12478 if (error)
12479 goto theend;
12482 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
12483 if (regmatch.regprog != NULL)
12485 regmatch.rm_ic = p_ic;
12487 for (;;)
12489 if (l != NULL)
12491 if (li == NULL)
12493 match = FALSE;
12494 break;
12496 vim_free(tofree);
12497 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
12498 if (str == NULL)
12499 break;
12502 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
12504 if (match && --nth <= 0)
12505 break;
12506 if (l == NULL && !match)
12507 break;
12509 /* Advance to just after the match. */
12510 if (l != NULL)
12512 li = li->li_next;
12513 ++idx;
12515 else
12517 #ifdef FEAT_MBYTE
12518 startcol = (colnr_T)(regmatch.startp[0]
12519 + (*mb_ptr2len)(regmatch.startp[0]) - str);
12520 #else
12521 startcol = regmatch.startp[0] + 1 - str;
12522 #endif
12526 if (match)
12528 if (type == 3)
12530 int i;
12532 /* return list with matched string and submatches */
12533 for (i = 0; i < NSUBEXP; ++i)
12535 if (regmatch.endp[i] == NULL)
12537 if (list_append_string(rettv->vval.v_list,
12538 (char_u *)"", 0) == FAIL)
12539 break;
12541 else if (list_append_string(rettv->vval.v_list,
12542 regmatch.startp[i],
12543 (int)(regmatch.endp[i] - regmatch.startp[i]))
12544 == FAIL)
12545 break;
12548 else if (type == 2)
12550 /* return matched string */
12551 if (l != NULL)
12552 copy_tv(&li->li_tv, rettv);
12553 else
12554 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
12555 (int)(regmatch.endp[0] - regmatch.startp[0]));
12557 else if (l != NULL)
12558 rettv->vval.v_number = idx;
12559 else
12561 if (type != 0)
12562 rettv->vval.v_number =
12563 (varnumber_T)(regmatch.startp[0] - str);
12564 else
12565 rettv->vval.v_number =
12566 (varnumber_T)(regmatch.endp[0] - str);
12567 rettv->vval.v_number += (varnumber_T)(str - expr);
12570 vim_free(regmatch.regprog);
12573 theend:
12574 vim_free(tofree);
12575 p_cpo = save_cpo;
12579 * "match()" function
12581 static void
12582 f_match(argvars, rettv)
12583 typval_T *argvars;
12584 typval_T *rettv;
12586 find_some_match(argvars, rettv, 1);
12590 * "matchadd()" function
12592 static void
12593 f_matchadd(argvars, rettv)
12594 typval_T *argvars;
12595 typval_T *rettv;
12597 #ifdef FEAT_SEARCH_EXTRA
12598 char_u buf[NUMBUFLEN];
12599 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
12600 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
12601 int prio = 10; /* default priority */
12602 int id = -1;
12603 int error = FALSE;
12605 rettv->vval.v_number = -1;
12607 if (grp == NULL || pat == NULL)
12608 return;
12609 if (argvars[2].v_type != VAR_UNKNOWN)
12611 prio = get_tv_number_chk(&argvars[2], &error);
12612 if (argvars[3].v_type != VAR_UNKNOWN)
12613 id = get_tv_number_chk(&argvars[3], &error);
12615 if (error == TRUE)
12616 return;
12617 if (id >= 1 && id <= 3)
12619 EMSGN("E798: ID is reserved for \":match\": %ld", id);
12620 return;
12623 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
12624 #endif
12628 * "matcharg()" function
12630 static void
12631 f_matcharg(argvars, rettv)
12632 typval_T *argvars;
12633 typval_T *rettv;
12635 if (rettv_list_alloc(rettv) == OK)
12637 #ifdef FEAT_SEARCH_EXTRA
12638 int id = get_tv_number(&argvars[0]);
12639 matchitem_T *m;
12641 if (id >= 1 && id <= 3)
12643 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
12645 list_append_string(rettv->vval.v_list,
12646 syn_id2name(m->hlg_id), -1);
12647 list_append_string(rettv->vval.v_list, m->pattern, -1);
12649 else
12651 list_append_string(rettv->vval.v_list, NUL, -1);
12652 list_append_string(rettv->vval.v_list, NUL, -1);
12655 #endif
12660 * "matchdelete()" function
12662 static void
12663 f_matchdelete(argvars, rettv)
12664 typval_T *argvars;
12665 typval_T *rettv;
12667 #ifdef FEAT_SEARCH_EXTRA
12668 rettv->vval.v_number = match_delete(curwin,
12669 (int)get_tv_number(&argvars[0]), TRUE);
12670 #endif
12674 * "matchend()" function
12676 static void
12677 f_matchend(argvars, rettv)
12678 typval_T *argvars;
12679 typval_T *rettv;
12681 find_some_match(argvars, rettv, 0);
12685 * "matchlist()" function
12687 static void
12688 f_matchlist(argvars, rettv)
12689 typval_T *argvars;
12690 typval_T *rettv;
12692 find_some_match(argvars, rettv, 3);
12696 * "matchstr()" function
12698 static void
12699 f_matchstr(argvars, rettv)
12700 typval_T *argvars;
12701 typval_T *rettv;
12703 find_some_match(argvars, rettv, 2);
12706 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
12708 static void
12709 max_min(argvars, rettv, domax)
12710 typval_T *argvars;
12711 typval_T *rettv;
12712 int domax;
12714 long n = 0;
12715 long i;
12716 int error = FALSE;
12718 if (argvars[0].v_type == VAR_LIST)
12720 list_T *l;
12721 listitem_T *li;
12723 l = argvars[0].vval.v_list;
12724 if (l != NULL)
12726 li = l->lv_first;
12727 if (li != NULL)
12729 n = get_tv_number_chk(&li->li_tv, &error);
12730 for (;;)
12732 li = li->li_next;
12733 if (li == NULL)
12734 break;
12735 i = get_tv_number_chk(&li->li_tv, &error);
12736 if (domax ? i > n : i < n)
12737 n = i;
12742 else if (argvars[0].v_type == VAR_DICT)
12744 dict_T *d;
12745 int first = TRUE;
12746 hashitem_T *hi;
12747 int todo;
12749 d = argvars[0].vval.v_dict;
12750 if (d != NULL)
12752 todo = (int)d->dv_hashtab.ht_used;
12753 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12755 if (!HASHITEM_EMPTY(hi))
12757 --todo;
12758 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
12759 if (first)
12761 n = i;
12762 first = FALSE;
12764 else if (domax ? i > n : i < n)
12765 n = i;
12770 else
12771 EMSG(_(e_listdictarg));
12772 rettv->vval.v_number = error ? 0 : n;
12776 * "max()" function
12778 static void
12779 f_max(argvars, rettv)
12780 typval_T *argvars;
12781 typval_T *rettv;
12783 max_min(argvars, rettv, TRUE);
12787 * "min()" function
12789 static void
12790 f_min(argvars, rettv)
12791 typval_T *argvars;
12792 typval_T *rettv;
12794 max_min(argvars, rettv, FALSE);
12797 static int mkdir_recurse __ARGS((char_u *dir, int prot));
12800 * Create the directory in which "dir" is located, and higher levels when
12801 * needed.
12803 static int
12804 mkdir_recurse(dir, prot)
12805 char_u *dir;
12806 int prot;
12808 char_u *p;
12809 char_u *updir;
12810 int r = FAIL;
12812 /* Get end of directory name in "dir".
12813 * We're done when it's "/" or "c:/". */
12814 p = gettail_sep(dir);
12815 if (p <= get_past_head(dir))
12816 return OK;
12818 /* If the directory exists we're done. Otherwise: create it.*/
12819 updir = vim_strnsave(dir, (int)(p - dir));
12820 if (updir == NULL)
12821 return FAIL;
12822 if (mch_isdir(updir))
12823 r = OK;
12824 else if (mkdir_recurse(updir, prot) == OK)
12825 r = vim_mkdir_emsg(updir, prot);
12826 vim_free(updir);
12827 return r;
12830 #ifdef vim_mkdir
12832 * "mkdir()" function
12834 static void
12835 f_mkdir(argvars, rettv)
12836 typval_T *argvars;
12837 typval_T *rettv;
12839 char_u *dir;
12840 char_u buf[NUMBUFLEN];
12841 int prot = 0755;
12843 rettv->vval.v_number = FAIL;
12844 if (check_restricted() || check_secure())
12845 return;
12847 dir = get_tv_string_buf(&argvars[0], buf);
12848 if (argvars[1].v_type != VAR_UNKNOWN)
12850 if (argvars[2].v_type != VAR_UNKNOWN)
12851 prot = get_tv_number_chk(&argvars[2], NULL);
12852 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
12853 mkdir_recurse(dir, prot);
12855 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
12857 #endif
12860 * "mode()" function
12862 /*ARGSUSED*/
12863 static void
12864 f_mode(argvars, rettv)
12865 typval_T *argvars;
12866 typval_T *rettv;
12868 char_u buf[2];
12870 #ifdef FEAT_VISUAL
12871 if (VIsual_active)
12873 if (VIsual_select)
12874 buf[0] = VIsual_mode + 's' - 'v';
12875 else
12876 buf[0] = VIsual_mode;
12878 else
12879 #endif
12880 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE)
12881 buf[0] = 'r';
12882 else if (State & INSERT)
12884 if (State & REPLACE_FLAG)
12885 buf[0] = 'R';
12886 else
12887 buf[0] = 'i';
12889 else if (State & CMDLINE)
12890 buf[0] = 'c';
12891 else
12892 buf[0] = 'n';
12894 buf[1] = NUL;
12895 rettv->vval.v_string = vim_strsave(buf);
12896 rettv->v_type = VAR_STRING;
12900 * "nextnonblank()" function
12902 static void
12903 f_nextnonblank(argvars, rettv)
12904 typval_T *argvars;
12905 typval_T *rettv;
12907 linenr_T lnum;
12909 for (lnum = get_tv_lnum(argvars); ; ++lnum)
12911 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
12913 lnum = 0;
12914 break;
12916 if (*skipwhite(ml_get(lnum)) != NUL)
12917 break;
12919 rettv->vval.v_number = lnum;
12923 * "nr2char()" function
12925 static void
12926 f_nr2char(argvars, rettv)
12927 typval_T *argvars;
12928 typval_T *rettv;
12930 char_u buf[NUMBUFLEN];
12932 #ifdef FEAT_MBYTE
12933 if (has_mbyte)
12934 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
12935 else
12936 #endif
12938 buf[0] = (char_u)get_tv_number(&argvars[0]);
12939 buf[1] = NUL;
12941 rettv->v_type = VAR_STRING;
12942 rettv->vval.v_string = vim_strsave(buf);
12946 * "pathshorten()" function
12948 static void
12949 f_pathshorten(argvars, rettv)
12950 typval_T *argvars;
12951 typval_T *rettv;
12953 char_u *p;
12955 rettv->v_type = VAR_STRING;
12956 p = get_tv_string_chk(&argvars[0]);
12957 if (p == NULL)
12958 rettv->vval.v_string = NULL;
12959 else
12961 p = vim_strsave(p);
12962 rettv->vval.v_string = p;
12963 if (p != NULL)
12964 shorten_dir(p);
12969 * "prevnonblank()" function
12971 static void
12972 f_prevnonblank(argvars, rettv)
12973 typval_T *argvars;
12974 typval_T *rettv;
12976 linenr_T lnum;
12978 lnum = get_tv_lnum(argvars);
12979 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
12980 lnum = 0;
12981 else
12982 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
12983 --lnum;
12984 rettv->vval.v_number = lnum;
12987 #ifdef HAVE_STDARG_H
12988 /* This dummy va_list is here because:
12989 * - passing a NULL pointer doesn't work when va_list isn't a pointer
12990 * - locally in the function results in a "used before set" warning
12991 * - using va_start() to initialize it gives "function with fixed args" error */
12992 static va_list ap;
12993 #endif
12996 * "printf()" function
12998 static void
12999 f_printf(argvars, rettv)
13000 typval_T *argvars;
13001 typval_T *rettv;
13003 rettv->v_type = VAR_STRING;
13004 rettv->vval.v_string = NULL;
13005 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
13007 char_u buf[NUMBUFLEN];
13008 int len;
13009 char_u *s;
13010 int saved_did_emsg = did_emsg;
13011 char *fmt;
13013 /* Get the required length, allocate the buffer and do it for real. */
13014 did_emsg = FALSE;
13015 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
13016 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
13017 if (!did_emsg)
13019 s = alloc(len + 1);
13020 if (s != NULL)
13022 rettv->vval.v_string = s;
13023 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
13026 did_emsg |= saved_did_emsg;
13028 #endif
13032 * "pumvisible()" function
13034 /*ARGSUSED*/
13035 static void
13036 f_pumvisible(argvars, rettv)
13037 typval_T *argvars;
13038 typval_T *rettv;
13040 rettv->vval.v_number = 0;
13041 #ifdef FEAT_INS_EXPAND
13042 if (pum_visible())
13043 rettv->vval.v_number = 1;
13044 #endif
13048 * "range()" function
13050 static void
13051 f_range(argvars, rettv)
13052 typval_T *argvars;
13053 typval_T *rettv;
13055 long start;
13056 long end;
13057 long stride = 1;
13058 long i;
13059 int error = FALSE;
13061 start = get_tv_number_chk(&argvars[0], &error);
13062 if (argvars[1].v_type == VAR_UNKNOWN)
13064 end = start - 1;
13065 start = 0;
13067 else
13069 end = get_tv_number_chk(&argvars[1], &error);
13070 if (argvars[2].v_type != VAR_UNKNOWN)
13071 stride = get_tv_number_chk(&argvars[2], &error);
13074 rettv->vval.v_number = 0;
13075 if (error)
13076 return; /* type error; errmsg already given */
13077 if (stride == 0)
13078 EMSG(_("E726: Stride is zero"));
13079 else if (stride > 0 ? end + 1 < start : end - 1 > start)
13080 EMSG(_("E727: Start past end"));
13081 else
13083 if (rettv_list_alloc(rettv) == OK)
13084 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
13085 if (list_append_number(rettv->vval.v_list,
13086 (varnumber_T)i) == FAIL)
13087 break;
13092 * "readfile()" function
13094 static void
13095 f_readfile(argvars, rettv)
13096 typval_T *argvars;
13097 typval_T *rettv;
13099 int binary = FALSE;
13100 char_u *fname;
13101 FILE *fd;
13102 listitem_T *li;
13103 #define FREAD_SIZE 200 /* optimized for text lines */
13104 char_u buf[FREAD_SIZE];
13105 int readlen; /* size of last fread() */
13106 int buflen; /* nr of valid chars in buf[] */
13107 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
13108 int tolist; /* first byte in buf[] still to be put in list */
13109 int chop; /* how many CR to chop off */
13110 char_u *prev = NULL; /* previously read bytes, if any */
13111 int prevlen = 0; /* length of "prev" if not NULL */
13112 char_u *s;
13113 int len;
13114 long maxline = MAXLNUM;
13115 long cnt = 0;
13117 if (argvars[1].v_type != VAR_UNKNOWN)
13119 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
13120 binary = TRUE;
13121 if (argvars[2].v_type != VAR_UNKNOWN)
13122 maxline = get_tv_number(&argvars[2]);
13125 if (rettv_list_alloc(rettv) == FAIL)
13126 return;
13128 /* Always open the file in binary mode, library functions have a mind of
13129 * their own about CR-LF conversion. */
13130 fname = get_tv_string(&argvars[0]);
13131 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
13133 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
13134 return;
13137 filtd = 0;
13138 while (cnt < maxline || maxline < 0)
13140 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
13141 buflen = filtd + readlen;
13142 tolist = 0;
13143 for ( ; filtd < buflen || readlen <= 0; ++filtd)
13145 if (buf[filtd] == '\n' || readlen <= 0)
13147 /* Only when in binary mode add an empty list item when the
13148 * last line ends in a '\n'. */
13149 if (!binary && readlen == 0 && filtd == 0)
13150 break;
13152 /* Found end-of-line or end-of-file: add a text line to the
13153 * list. */
13154 chop = 0;
13155 if (!binary)
13156 while (filtd - chop - 1 >= tolist
13157 && buf[filtd - chop - 1] == '\r')
13158 ++chop;
13159 len = filtd - tolist - chop;
13160 if (prev == NULL)
13161 s = vim_strnsave(buf + tolist, len);
13162 else
13164 s = alloc((unsigned)(prevlen + len + 1));
13165 if (s != NULL)
13167 mch_memmove(s, prev, prevlen);
13168 vim_free(prev);
13169 prev = NULL;
13170 mch_memmove(s + prevlen, buf + tolist, len);
13171 s[prevlen + len] = NUL;
13174 tolist = filtd + 1;
13176 li = listitem_alloc();
13177 if (li == NULL)
13179 vim_free(s);
13180 break;
13182 li->li_tv.v_type = VAR_STRING;
13183 li->li_tv.v_lock = 0;
13184 li->li_tv.vval.v_string = s;
13185 list_append(rettv->vval.v_list, li);
13187 if (++cnt >= maxline && maxline >= 0)
13188 break;
13189 if (readlen <= 0)
13190 break;
13192 else if (buf[filtd] == NUL)
13193 buf[filtd] = '\n';
13195 if (readlen <= 0)
13196 break;
13198 if (tolist == 0)
13200 /* "buf" is full, need to move text to an allocated buffer */
13201 if (prev == NULL)
13203 prev = vim_strnsave(buf, buflen);
13204 prevlen = buflen;
13206 else
13208 s = alloc((unsigned)(prevlen + buflen));
13209 if (s != NULL)
13211 mch_memmove(s, prev, prevlen);
13212 mch_memmove(s + prevlen, buf, buflen);
13213 vim_free(prev);
13214 prev = s;
13215 prevlen += buflen;
13218 filtd = 0;
13220 else
13222 mch_memmove(buf, buf + tolist, buflen - tolist);
13223 filtd -= tolist;
13228 * For a negative line count use only the lines at the end of the file,
13229 * free the rest.
13231 if (maxline < 0)
13232 while (cnt > -maxline)
13234 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
13235 --cnt;
13238 vim_free(prev);
13239 fclose(fd);
13242 #if defined(FEAT_RELTIME)
13243 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
13246 * Convert a List to proftime_T.
13247 * Return FAIL when there is something wrong.
13249 static int
13250 list2proftime(arg, tm)
13251 typval_T *arg;
13252 proftime_T *tm;
13254 long n1, n2;
13255 int error = FALSE;
13257 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
13258 || arg->vval.v_list->lv_len != 2)
13259 return FAIL;
13260 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
13261 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
13262 # ifdef WIN3264
13263 tm->HighPart = n1;
13264 tm->LowPart = n2;
13265 # else
13266 tm->tv_sec = n1;
13267 tm->tv_usec = n2;
13268 # endif
13269 return error ? FAIL : OK;
13271 #endif /* FEAT_RELTIME */
13274 * "reltime()" function
13276 static void
13277 f_reltime(argvars, rettv)
13278 typval_T *argvars;
13279 typval_T *rettv;
13281 #ifdef FEAT_RELTIME
13282 proftime_T res;
13283 proftime_T start;
13285 if (argvars[0].v_type == VAR_UNKNOWN)
13287 /* No arguments: get current time. */
13288 profile_start(&res);
13290 else if (argvars[1].v_type == VAR_UNKNOWN)
13292 if (list2proftime(&argvars[0], &res) == FAIL)
13293 return;
13294 profile_end(&res);
13296 else
13298 /* Two arguments: compute the difference. */
13299 if (list2proftime(&argvars[0], &start) == FAIL
13300 || list2proftime(&argvars[1], &res) == FAIL)
13301 return;
13302 profile_sub(&res, &start);
13305 if (rettv_list_alloc(rettv) == OK)
13307 long n1, n2;
13309 # ifdef WIN3264
13310 n1 = res.HighPart;
13311 n2 = res.LowPart;
13312 # else
13313 n1 = res.tv_sec;
13314 n2 = res.tv_usec;
13315 # endif
13316 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
13317 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
13319 #endif
13323 * "reltimestr()" function
13325 static void
13326 f_reltimestr(argvars, rettv)
13327 typval_T *argvars;
13328 typval_T *rettv;
13330 #ifdef FEAT_RELTIME
13331 proftime_T tm;
13332 #endif
13334 rettv->v_type = VAR_STRING;
13335 rettv->vval.v_string = NULL;
13336 #ifdef FEAT_RELTIME
13337 if (list2proftime(&argvars[0], &tm) == OK)
13338 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
13339 #endif
13342 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
13343 static void make_connection __ARGS((void));
13344 static int check_connection __ARGS((void));
13346 static void
13347 make_connection()
13349 if (X_DISPLAY == NULL
13350 # ifdef FEAT_GUI
13351 && !gui.in_use
13352 # endif
13355 x_force_connect = TRUE;
13356 setup_term_clip();
13357 x_force_connect = FALSE;
13361 static int
13362 check_connection()
13364 make_connection();
13365 if (X_DISPLAY == NULL)
13367 EMSG(_("E240: No connection to Vim server"));
13368 return FAIL;
13370 return OK;
13372 #endif
13374 #ifdef FEAT_CLIENTSERVER
13375 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
13377 static void
13378 remote_common(argvars, rettv, expr)
13379 typval_T *argvars;
13380 typval_T *rettv;
13381 int expr;
13383 char_u *server_name;
13384 char_u *keys;
13385 char_u *r = NULL;
13386 char_u buf[NUMBUFLEN];
13387 # ifdef WIN32
13388 HWND w;
13389 # elif defined(FEAT_X11)
13390 Window w;
13391 # elif defined(MAC_CLIENTSERVER)
13392 int w; // This is the port number ('w' is a bit confusing)
13393 # endif
13395 if (check_restricted() || check_secure())
13396 return;
13398 # ifdef FEAT_X11
13399 if (check_connection() == FAIL)
13400 return;
13401 # endif
13403 server_name = get_tv_string_chk(&argvars[0]);
13404 if (server_name == NULL)
13405 return; /* type error; errmsg already given */
13406 keys = get_tv_string_buf(&argvars[1], buf);
13407 # ifdef WIN32
13408 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
13409 # elif defined(FEAT_X11)
13410 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
13411 < 0)
13412 # elif defined(MAC_CLIENTSERVER)
13413 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
13414 # endif
13416 if (r != NULL)
13417 EMSG(r); /* sending worked but evaluation failed */
13418 else
13419 EMSG2(_("E241: Unable to send to %s"), server_name);
13420 return;
13423 rettv->vval.v_string = r;
13425 if (argvars[2].v_type != VAR_UNKNOWN)
13427 dictitem_T v;
13428 char_u str[30];
13429 char_u *idvar;
13431 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
13432 v.di_tv.v_type = VAR_STRING;
13433 v.di_tv.vval.v_string = vim_strsave(str);
13434 idvar = get_tv_string_chk(&argvars[2]);
13435 if (idvar != NULL)
13436 set_var(idvar, &v.di_tv, FALSE);
13437 vim_free(v.di_tv.vval.v_string);
13440 #endif
13443 * "remote_expr()" function
13445 /*ARGSUSED*/
13446 static void
13447 f_remote_expr(argvars, rettv)
13448 typval_T *argvars;
13449 typval_T *rettv;
13451 rettv->v_type = VAR_STRING;
13452 rettv->vval.v_string = NULL;
13453 #ifdef FEAT_CLIENTSERVER
13454 remote_common(argvars, rettv, TRUE);
13455 #endif
13459 * "remote_foreground()" function
13461 /*ARGSUSED*/
13462 static void
13463 f_remote_foreground(argvars, rettv)
13464 typval_T *argvars;
13465 typval_T *rettv;
13467 rettv->vval.v_number = 0;
13468 #ifdef FEAT_CLIENTSERVER
13469 # ifdef WIN32
13470 /* On Win32 it's done in this application. */
13472 char_u *server_name = get_tv_string_chk(&argvars[0]);
13474 if (server_name != NULL)
13475 serverForeground(server_name);
13477 # elif defined(FEAT_X11) || defined(MAC_CLIENTSERVER)
13478 /* Send a foreground() expression to the server. */
13479 argvars[1].v_type = VAR_STRING;
13480 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
13481 argvars[2].v_type = VAR_UNKNOWN;
13482 remote_common(argvars, rettv, TRUE);
13483 vim_free(argvars[1].vval.v_string);
13484 # endif
13485 #endif
13488 /*ARGSUSED*/
13489 static void
13490 f_remote_peek(argvars, rettv)
13491 typval_T *argvars;
13492 typval_T *rettv;
13494 #ifdef FEAT_CLIENTSERVER
13495 dictitem_T v;
13496 char_u *s = NULL;
13497 # ifdef WIN32
13498 long_u n = 0;
13499 # endif
13500 char_u *serverid;
13502 if (check_restricted() || check_secure())
13504 rettv->vval.v_number = -1;
13505 return;
13507 serverid = get_tv_string_chk(&argvars[0]);
13508 if (serverid == NULL)
13510 rettv->vval.v_number = -1;
13511 return; /* type error; errmsg already given */
13513 # ifdef WIN32
13514 sscanf(serverid, SCANF_HEX_LONG_U, &n);
13515 if (n == 0)
13516 rettv->vval.v_number = -1;
13517 else
13519 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
13520 rettv->vval.v_number = (s != NULL);
13522 # elif defined(FEAT_X11)
13523 rettv->vval.v_number = 0;
13524 if (check_connection() == FAIL)
13525 return;
13527 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
13528 serverStrToWin(serverid), &s);
13529 # elif defined(MAC_CLIENTSERVER)
13530 rettv->vval.v_number = serverPeekReply(serverStrToPort(serverid), &s);
13531 # endif
13533 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
13535 char_u *retvar;
13537 v.di_tv.v_type = VAR_STRING;
13538 v.di_tv.vval.v_string = vim_strsave(s);
13539 retvar = get_tv_string_chk(&argvars[1]);
13540 if (retvar != NULL)
13541 set_var(retvar, &v.di_tv, FALSE);
13542 vim_free(v.di_tv.vval.v_string);
13544 #else
13545 rettv->vval.v_number = -1;
13546 #endif
13549 /*ARGSUSED*/
13550 static void
13551 f_remote_read(argvars, rettv)
13552 typval_T *argvars;
13553 typval_T *rettv;
13555 char_u *r = NULL;
13557 #ifdef FEAT_CLIENTSERVER
13558 char_u *serverid = get_tv_string_chk(&argvars[0]);
13560 if (serverid != NULL && !check_restricted() && !check_secure())
13562 # ifdef WIN32
13563 /* The server's HWND is encoded in the 'id' parameter */
13564 long_u n = 0;
13566 sscanf(serverid, SCANF_HEX_LONG_U, &n);
13567 if (n != 0)
13568 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
13569 if (r == NULL)
13570 # elif defined(FEAT_X11)
13571 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
13572 serverStrToWin(serverid), &r, FALSE) < 0)
13573 # elif defined(MAC_CLIENTSERVER)
13574 if (serverReadReply(serverStrToPort(serverid), &r) < 0)
13575 # endif
13576 EMSG(_("E277: Unable to read a server reply"));
13578 #endif
13579 rettv->v_type = VAR_STRING;
13580 rettv->vval.v_string = r;
13584 * "remote_send()" function
13586 /*ARGSUSED*/
13587 static void
13588 f_remote_send(argvars, rettv)
13589 typval_T *argvars;
13590 typval_T *rettv;
13592 rettv->v_type = VAR_STRING;
13593 rettv->vval.v_string = NULL;
13594 #ifdef FEAT_CLIENTSERVER
13595 remote_common(argvars, rettv, FALSE);
13596 #endif
13600 * "remove()" function
13602 static void
13603 f_remove(argvars, rettv)
13604 typval_T *argvars;
13605 typval_T *rettv;
13607 list_T *l;
13608 listitem_T *item, *item2;
13609 listitem_T *li;
13610 long idx;
13611 long end;
13612 char_u *key;
13613 dict_T *d;
13614 dictitem_T *di;
13616 rettv->vval.v_number = 0;
13617 if (argvars[0].v_type == VAR_DICT)
13619 if (argvars[2].v_type != VAR_UNKNOWN)
13620 EMSG2(_(e_toomanyarg), "remove()");
13621 else if ((d = argvars[0].vval.v_dict) != NULL
13622 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
13624 key = get_tv_string_chk(&argvars[1]);
13625 if (key != NULL)
13627 di = dict_find(d, key, -1);
13628 if (di == NULL)
13629 EMSG2(_(e_dictkey), key);
13630 else
13632 *rettv = di->di_tv;
13633 init_tv(&di->di_tv);
13634 dictitem_remove(d, di);
13639 else if (argvars[0].v_type != VAR_LIST)
13640 EMSG2(_(e_listdictarg), "remove()");
13641 else if ((l = argvars[0].vval.v_list) != NULL
13642 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
13644 int error = FALSE;
13646 idx = get_tv_number_chk(&argvars[1], &error);
13647 if (error)
13648 ; /* type error: do nothing, errmsg already given */
13649 else if ((item = list_find(l, idx)) == NULL)
13650 EMSGN(_(e_listidx), idx);
13651 else
13653 if (argvars[2].v_type == VAR_UNKNOWN)
13655 /* Remove one item, return its value. */
13656 list_remove(l, item, item);
13657 *rettv = item->li_tv;
13658 vim_free(item);
13660 else
13662 /* Remove range of items, return list with values. */
13663 end = get_tv_number_chk(&argvars[2], &error);
13664 if (error)
13665 ; /* type error: do nothing */
13666 else if ((item2 = list_find(l, end)) == NULL)
13667 EMSGN(_(e_listidx), end);
13668 else
13670 int cnt = 0;
13672 for (li = item; li != NULL; li = li->li_next)
13674 ++cnt;
13675 if (li == item2)
13676 break;
13678 if (li == NULL) /* didn't find "item2" after "item" */
13679 EMSG(_(e_invrange));
13680 else
13682 list_remove(l, item, item2);
13683 if (rettv_list_alloc(rettv) == OK)
13685 l = rettv->vval.v_list;
13686 l->lv_first = item;
13687 l->lv_last = item2;
13688 item->li_prev = NULL;
13689 item2->li_next = NULL;
13690 l->lv_len = cnt;
13700 * "rename({from}, {to})" function
13702 static void
13703 f_rename(argvars, rettv)
13704 typval_T *argvars;
13705 typval_T *rettv;
13707 char_u buf[NUMBUFLEN];
13709 if (check_restricted() || check_secure())
13710 rettv->vval.v_number = -1;
13711 else
13712 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
13713 get_tv_string_buf(&argvars[1], buf));
13717 * "repeat()" function
13719 /*ARGSUSED*/
13720 static void
13721 f_repeat(argvars, rettv)
13722 typval_T *argvars;
13723 typval_T *rettv;
13725 char_u *p;
13726 int n;
13727 int slen;
13728 int len;
13729 char_u *r;
13730 int i;
13732 n = get_tv_number(&argvars[1]);
13733 if (argvars[0].v_type == VAR_LIST)
13735 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
13736 while (n-- > 0)
13737 if (list_extend(rettv->vval.v_list,
13738 argvars[0].vval.v_list, NULL) == FAIL)
13739 break;
13741 else
13743 p = get_tv_string(&argvars[0]);
13744 rettv->v_type = VAR_STRING;
13745 rettv->vval.v_string = NULL;
13747 slen = (int)STRLEN(p);
13748 len = slen * n;
13749 if (len <= 0)
13750 return;
13752 r = alloc(len + 1);
13753 if (r != NULL)
13755 for (i = 0; i < n; i++)
13756 mch_memmove(r + i * slen, p, (size_t)slen);
13757 r[len] = NUL;
13760 rettv->vval.v_string = r;
13765 * "resolve()" function
13767 static void
13768 f_resolve(argvars, rettv)
13769 typval_T *argvars;
13770 typval_T *rettv;
13772 char_u *p;
13774 p = get_tv_string(&argvars[0]);
13775 #ifdef FEAT_SHORTCUT
13777 char_u *v = NULL;
13779 v = mch_resolve_shortcut(p);
13780 if (v != NULL)
13781 rettv->vval.v_string = v;
13782 else
13783 rettv->vval.v_string = vim_strsave(p);
13785 #else
13786 # ifdef HAVE_READLINK
13788 char_u buf[MAXPATHL + 1];
13789 char_u *cpy;
13790 int len;
13791 char_u *remain = NULL;
13792 char_u *q;
13793 int is_relative_to_current = FALSE;
13794 int has_trailing_pathsep = FALSE;
13795 int limit = 100;
13797 p = vim_strsave(p);
13799 if (p[0] == '.' && (vim_ispathsep(p[1])
13800 || (p[1] == '.' && (vim_ispathsep(p[2])))))
13801 is_relative_to_current = TRUE;
13803 len = STRLEN(p);
13804 if (len > 0 && after_pathsep(p, p + len))
13805 has_trailing_pathsep = TRUE;
13807 q = getnextcomp(p);
13808 if (*q != NUL)
13810 /* Separate the first path component in "p", and keep the
13811 * remainder (beginning with the path separator). */
13812 remain = vim_strsave(q - 1);
13813 q[-1] = NUL;
13816 for (;;)
13818 for (;;)
13820 len = readlink((char *)p, (char *)buf, MAXPATHL);
13821 if (len <= 0)
13822 break;
13823 buf[len] = NUL;
13825 if (limit-- == 0)
13827 vim_free(p);
13828 vim_free(remain);
13829 EMSG(_("E655: Too many symbolic links (cycle?)"));
13830 rettv->vval.v_string = NULL;
13831 goto fail;
13834 /* Ensure that the result will have a trailing path separator
13835 * if the argument has one. */
13836 if (remain == NULL && has_trailing_pathsep)
13837 add_pathsep(buf);
13839 /* Separate the first path component in the link value and
13840 * concatenate the remainders. */
13841 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
13842 if (*q != NUL)
13844 if (remain == NULL)
13845 remain = vim_strsave(q - 1);
13846 else
13848 cpy = concat_str(q - 1, remain);
13849 if (cpy != NULL)
13851 vim_free(remain);
13852 remain = cpy;
13855 q[-1] = NUL;
13858 q = gettail(p);
13859 if (q > p && *q == NUL)
13861 /* Ignore trailing path separator. */
13862 q[-1] = NUL;
13863 q = gettail(p);
13865 if (q > p && !mch_isFullName(buf))
13867 /* symlink is relative to directory of argument */
13868 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
13869 if (cpy != NULL)
13871 STRCPY(cpy, p);
13872 STRCPY(gettail(cpy), buf);
13873 vim_free(p);
13874 p = cpy;
13877 else
13879 vim_free(p);
13880 p = vim_strsave(buf);
13884 if (remain == NULL)
13885 break;
13887 /* Append the first path component of "remain" to "p". */
13888 q = getnextcomp(remain + 1);
13889 len = q - remain - (*q != NUL);
13890 cpy = vim_strnsave(p, STRLEN(p) + len);
13891 if (cpy != NULL)
13893 STRNCAT(cpy, remain, len);
13894 vim_free(p);
13895 p = cpy;
13897 /* Shorten "remain". */
13898 if (*q != NUL)
13899 mch_memmove(remain, q - 1, STRLEN(q - 1) + 1);
13900 else
13902 vim_free(remain);
13903 remain = NULL;
13907 /* If the result is a relative path name, make it explicitly relative to
13908 * the current directory if and only if the argument had this form. */
13909 if (!vim_ispathsep(*p))
13911 if (is_relative_to_current
13912 && *p != NUL
13913 && !(p[0] == '.'
13914 && (p[1] == NUL
13915 || vim_ispathsep(p[1])
13916 || (p[1] == '.'
13917 && (p[2] == NUL
13918 || vim_ispathsep(p[2]))))))
13920 /* Prepend "./". */
13921 cpy = concat_str((char_u *)"./", p);
13922 if (cpy != NULL)
13924 vim_free(p);
13925 p = cpy;
13928 else if (!is_relative_to_current)
13930 /* Strip leading "./". */
13931 q = p;
13932 while (q[0] == '.' && vim_ispathsep(q[1]))
13933 q += 2;
13934 if (q > p)
13935 mch_memmove(p, p + 2, STRLEN(p + 2) + (size_t)1);
13939 /* Ensure that the result will have no trailing path separator
13940 * if the argument had none. But keep "/" or "//". */
13941 if (!has_trailing_pathsep)
13943 q = p + STRLEN(p);
13944 if (after_pathsep(p, q))
13945 *gettail_sep(p) = NUL;
13948 rettv->vval.v_string = p;
13950 # else
13951 rettv->vval.v_string = vim_strsave(p);
13952 # endif
13953 #endif
13955 simplify_filename(rettv->vval.v_string);
13957 #ifdef HAVE_READLINK
13958 fail:
13959 #endif
13960 rettv->v_type = VAR_STRING;
13964 * "reverse({list})" function
13966 static void
13967 f_reverse(argvars, rettv)
13968 typval_T *argvars;
13969 typval_T *rettv;
13971 list_T *l;
13972 listitem_T *li, *ni;
13974 rettv->vval.v_number = 0;
13975 if (argvars[0].v_type != VAR_LIST)
13976 EMSG2(_(e_listarg), "reverse()");
13977 else if ((l = argvars[0].vval.v_list) != NULL
13978 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
13980 li = l->lv_last;
13981 l->lv_first = l->lv_last = NULL;
13982 l->lv_len = 0;
13983 while (li != NULL)
13985 ni = li->li_prev;
13986 list_append(l, li);
13987 li = ni;
13989 rettv->vval.v_list = l;
13990 rettv->v_type = VAR_LIST;
13991 ++l->lv_refcount;
13992 l->lv_idx = l->lv_len - l->lv_idx - 1;
13996 #define SP_NOMOVE 0x01 /* don't move cursor */
13997 #define SP_REPEAT 0x02 /* repeat to find outer pair */
13998 #define SP_RETCOUNT 0x04 /* return matchcount */
13999 #define SP_SETPCMARK 0x08 /* set previous context mark */
14000 #define SP_START 0x10 /* accept match at start position */
14001 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
14002 #define SP_END 0x40 /* leave cursor at end of match */
14004 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
14007 * Get flags for a search function.
14008 * Possibly sets "p_ws".
14009 * Returns BACKWARD, FORWARD or zero (for an error).
14011 static int
14012 get_search_arg(varp, flagsp)
14013 typval_T *varp;
14014 int *flagsp;
14016 int dir = FORWARD;
14017 char_u *flags;
14018 char_u nbuf[NUMBUFLEN];
14019 int mask;
14021 if (varp->v_type != VAR_UNKNOWN)
14023 flags = get_tv_string_buf_chk(varp, nbuf);
14024 if (flags == NULL)
14025 return 0; /* type error; errmsg already given */
14026 while (*flags != NUL)
14028 switch (*flags)
14030 case 'b': dir = BACKWARD; break;
14031 case 'w': p_ws = TRUE; break;
14032 case 'W': p_ws = FALSE; break;
14033 default: mask = 0;
14034 if (flagsp != NULL)
14035 switch (*flags)
14037 case 'c': mask = SP_START; break;
14038 case 'e': mask = SP_END; break;
14039 case 'm': mask = SP_RETCOUNT; break;
14040 case 'n': mask = SP_NOMOVE; break;
14041 case 'p': mask = SP_SUBPAT; break;
14042 case 'r': mask = SP_REPEAT; break;
14043 case 's': mask = SP_SETPCMARK; break;
14045 if (mask == 0)
14047 EMSG2(_(e_invarg2), flags);
14048 dir = 0;
14050 else
14051 *flagsp |= mask;
14053 if (dir == 0)
14054 break;
14055 ++flags;
14058 return dir;
14062 * Shared by search() and searchpos() functions
14064 static int
14065 search_cmn(argvars, match_pos, flagsp)
14066 typval_T *argvars;
14067 pos_T *match_pos;
14068 int *flagsp;
14070 int flags;
14071 char_u *pat;
14072 pos_T pos;
14073 pos_T save_cursor;
14074 int save_p_ws = p_ws;
14075 int dir;
14076 int retval = 0; /* default: FAIL */
14077 long lnum_stop = 0;
14078 proftime_T tm;
14079 #ifdef FEAT_RELTIME
14080 long time_limit = 0;
14081 #endif
14082 int options = SEARCH_KEEP;
14083 int subpatnum;
14085 pat = get_tv_string(&argvars[0]);
14086 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
14087 if (dir == 0)
14088 goto theend;
14089 flags = *flagsp;
14090 if (flags & SP_START)
14091 options |= SEARCH_START;
14092 if (flags & SP_END)
14093 options |= SEARCH_END;
14095 /* Optional arguments: line number to stop searching and timeout. */
14096 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
14098 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
14099 if (lnum_stop < 0)
14100 goto theend;
14101 #ifdef FEAT_RELTIME
14102 if (argvars[3].v_type != VAR_UNKNOWN)
14104 time_limit = get_tv_number_chk(&argvars[3], NULL);
14105 if (time_limit < 0)
14106 goto theend;
14108 #endif
14111 #ifdef FEAT_RELTIME
14112 /* Set the time limit, if there is one. */
14113 profile_setlimit(time_limit, &tm);
14114 #endif
14117 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
14118 * Check to make sure only those flags are set.
14119 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
14120 * flags cannot be set. Check for that condition also.
14122 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
14123 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14125 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
14126 goto theend;
14129 pos = save_cursor = curwin->w_cursor;
14130 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14131 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
14132 if (subpatnum != FAIL)
14134 if (flags & SP_SUBPAT)
14135 retval = subpatnum;
14136 else
14137 retval = pos.lnum;
14138 if (flags & SP_SETPCMARK)
14139 setpcmark();
14140 curwin->w_cursor = pos;
14141 if (match_pos != NULL)
14143 /* Store the match cursor position */
14144 match_pos->lnum = pos.lnum;
14145 match_pos->col = pos.col + 1;
14147 /* "/$" will put the cursor after the end of the line, may need to
14148 * correct that here */
14149 check_cursor();
14152 /* If 'n' flag is used: restore cursor position. */
14153 if (flags & SP_NOMOVE)
14154 curwin->w_cursor = save_cursor;
14155 else
14156 curwin->w_set_curswant = TRUE;
14157 theend:
14158 p_ws = save_p_ws;
14160 return retval;
14164 * "search()" function
14166 static void
14167 f_search(argvars, rettv)
14168 typval_T *argvars;
14169 typval_T *rettv;
14171 int flags = 0;
14173 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
14177 * "searchdecl()" function
14179 static void
14180 f_searchdecl(argvars, rettv)
14181 typval_T *argvars;
14182 typval_T *rettv;
14184 int locally = 1;
14185 int thisblock = 0;
14186 int error = FALSE;
14187 char_u *name;
14189 rettv->vval.v_number = 1; /* default: FAIL */
14191 name = get_tv_string_chk(&argvars[0]);
14192 if (argvars[1].v_type != VAR_UNKNOWN)
14194 locally = get_tv_number_chk(&argvars[1], &error) == 0;
14195 if (!error && argvars[2].v_type != VAR_UNKNOWN)
14196 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
14198 if (!error && name != NULL)
14199 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
14200 locally, thisblock, SEARCH_KEEP) == FAIL;
14204 * Used by searchpair() and searchpairpos()
14206 static int
14207 searchpair_cmn(argvars, match_pos)
14208 typval_T *argvars;
14209 pos_T *match_pos;
14211 char_u *spat, *mpat, *epat;
14212 char_u *skip;
14213 int save_p_ws = p_ws;
14214 int dir;
14215 int flags = 0;
14216 char_u nbuf1[NUMBUFLEN];
14217 char_u nbuf2[NUMBUFLEN];
14218 char_u nbuf3[NUMBUFLEN];
14219 int retval = 0; /* default: FAIL */
14220 long lnum_stop = 0;
14221 long time_limit = 0;
14223 /* Get the three pattern arguments: start, middle, end. */
14224 spat = get_tv_string_chk(&argvars[0]);
14225 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
14226 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
14227 if (spat == NULL || mpat == NULL || epat == NULL)
14228 goto theend; /* type error */
14230 /* Handle the optional fourth argument: flags */
14231 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
14232 if (dir == 0)
14233 goto theend;
14235 /* Don't accept SP_END or SP_SUBPAT.
14236 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
14238 if ((flags & (SP_END | SP_SUBPAT)) != 0
14239 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14241 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
14242 goto theend;
14245 /* Using 'r' implies 'W', otherwise it doesn't work. */
14246 if (flags & SP_REPEAT)
14247 p_ws = FALSE;
14249 /* Optional fifth argument: skip expression */
14250 if (argvars[3].v_type == VAR_UNKNOWN
14251 || argvars[4].v_type == VAR_UNKNOWN)
14252 skip = (char_u *)"";
14253 else
14255 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
14256 if (argvars[5].v_type != VAR_UNKNOWN)
14258 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
14259 if (lnum_stop < 0)
14260 goto theend;
14261 #ifdef FEAT_RELTIME
14262 if (argvars[6].v_type != VAR_UNKNOWN)
14264 time_limit = get_tv_number_chk(&argvars[6], NULL);
14265 if (time_limit < 0)
14266 goto theend;
14268 #endif
14271 if (skip == NULL)
14272 goto theend; /* type error */
14274 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
14275 match_pos, lnum_stop, time_limit);
14277 theend:
14278 p_ws = save_p_ws;
14280 return retval;
14284 * "searchpair()" function
14286 static void
14287 f_searchpair(argvars, rettv)
14288 typval_T *argvars;
14289 typval_T *rettv;
14291 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
14295 * "searchpairpos()" function
14297 static void
14298 f_searchpairpos(argvars, rettv)
14299 typval_T *argvars;
14300 typval_T *rettv;
14302 pos_T match_pos;
14303 int lnum = 0;
14304 int col = 0;
14306 rettv->vval.v_number = 0;
14308 if (rettv_list_alloc(rettv) == FAIL)
14309 return;
14311 if (searchpair_cmn(argvars, &match_pos) > 0)
14313 lnum = match_pos.lnum;
14314 col = match_pos.col;
14317 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14318 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14322 * Search for a start/middle/end thing.
14323 * Used by searchpair(), see its documentation for the details.
14324 * Returns 0 or -1 for no match,
14326 long
14327 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
14328 lnum_stop, time_limit)
14329 char_u *spat; /* start pattern */
14330 char_u *mpat; /* middle pattern */
14331 char_u *epat; /* end pattern */
14332 int dir; /* BACKWARD or FORWARD */
14333 char_u *skip; /* skip expression */
14334 int flags; /* SP_SETPCMARK and other SP_ values */
14335 pos_T *match_pos;
14336 linenr_T lnum_stop; /* stop at this line if not zero */
14337 long time_limit; /* stop after this many msec */
14339 char_u *save_cpo;
14340 char_u *pat, *pat2 = NULL, *pat3 = NULL;
14341 long retval = 0;
14342 pos_T pos;
14343 pos_T firstpos;
14344 pos_T foundpos;
14345 pos_T save_cursor;
14346 pos_T save_pos;
14347 int n;
14348 int r;
14349 int nest = 1;
14350 int err;
14351 int options = SEARCH_KEEP;
14352 proftime_T tm;
14354 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
14355 save_cpo = p_cpo;
14356 p_cpo = (char_u *)"";
14358 #ifdef FEAT_RELTIME
14359 /* Set the time limit, if there is one. */
14360 profile_setlimit(time_limit, &tm);
14361 #endif
14363 /* Make two search patterns: start/end (pat2, for in nested pairs) and
14364 * start/middle/end (pat3, for the top pair). */
14365 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
14366 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
14367 if (pat2 == NULL || pat3 == NULL)
14368 goto theend;
14369 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
14370 if (*mpat == NUL)
14371 STRCPY(pat3, pat2);
14372 else
14373 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
14374 spat, epat, mpat);
14375 if (flags & SP_START)
14376 options |= SEARCH_START;
14378 save_cursor = curwin->w_cursor;
14379 pos = curwin->w_cursor;
14380 clearpos(&firstpos);
14381 clearpos(&foundpos);
14382 pat = pat3;
14383 for (;;)
14385 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14386 options, RE_SEARCH, lnum_stop, &tm);
14387 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
14388 /* didn't find it or found the first match again: FAIL */
14389 break;
14391 if (firstpos.lnum == 0)
14392 firstpos = pos;
14393 if (equalpos(pos, foundpos))
14395 /* Found the same position again. Can happen with a pattern that
14396 * has "\zs" at the end and searching backwards. Advance one
14397 * character and try again. */
14398 if (dir == BACKWARD)
14399 decl(&pos);
14400 else
14401 incl(&pos);
14403 foundpos = pos;
14405 /* clear the start flag to avoid getting stuck here */
14406 options &= ~SEARCH_START;
14408 /* If the skip pattern matches, ignore this match. */
14409 if (*skip != NUL)
14411 save_pos = curwin->w_cursor;
14412 curwin->w_cursor = pos;
14413 r = eval_to_bool(skip, &err, NULL, FALSE);
14414 curwin->w_cursor = save_pos;
14415 if (err)
14417 /* Evaluating {skip} caused an error, break here. */
14418 curwin->w_cursor = save_cursor;
14419 retval = -1;
14420 break;
14422 if (r)
14423 continue;
14426 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
14428 /* Found end when searching backwards or start when searching
14429 * forward: nested pair. */
14430 ++nest;
14431 pat = pat2; /* nested, don't search for middle */
14433 else
14435 /* Found end when searching forward or start when searching
14436 * backward: end of (nested) pair; or found middle in outer pair. */
14437 if (--nest == 1)
14438 pat = pat3; /* outer level, search for middle */
14441 if (nest == 0)
14443 /* Found the match: return matchcount or line number. */
14444 if (flags & SP_RETCOUNT)
14445 ++retval;
14446 else
14447 retval = pos.lnum;
14448 if (flags & SP_SETPCMARK)
14449 setpcmark();
14450 curwin->w_cursor = pos;
14451 if (!(flags & SP_REPEAT))
14452 break;
14453 nest = 1; /* search for next unmatched */
14457 if (match_pos != NULL)
14459 /* Store the match cursor position */
14460 match_pos->lnum = curwin->w_cursor.lnum;
14461 match_pos->col = curwin->w_cursor.col + 1;
14464 /* If 'n' flag is used or search failed: restore cursor position. */
14465 if ((flags & SP_NOMOVE) || retval == 0)
14466 curwin->w_cursor = save_cursor;
14468 theend:
14469 vim_free(pat2);
14470 vim_free(pat3);
14471 p_cpo = save_cpo;
14473 return retval;
14477 * "searchpos()" function
14479 static void
14480 f_searchpos(argvars, rettv)
14481 typval_T *argvars;
14482 typval_T *rettv;
14484 pos_T match_pos;
14485 int lnum = 0;
14486 int col = 0;
14487 int n;
14488 int flags = 0;
14490 rettv->vval.v_number = 0;
14492 if (rettv_list_alloc(rettv) == FAIL)
14493 return;
14495 n = search_cmn(argvars, &match_pos, &flags);
14496 if (n > 0)
14498 lnum = match_pos.lnum;
14499 col = match_pos.col;
14502 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14503 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14504 if (flags & SP_SUBPAT)
14505 list_append_number(rettv->vval.v_list, (varnumber_T)n);
14509 /*ARGSUSED*/
14510 static void
14511 f_server2client(argvars, rettv)
14512 typval_T *argvars;
14513 typval_T *rettv;
14515 #ifdef FEAT_CLIENTSERVER
14516 char_u buf[NUMBUFLEN];
14517 char_u *server = get_tv_string_chk(&argvars[0]);
14518 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
14520 rettv->vval.v_number = -1;
14521 if (server == NULL || reply == NULL)
14522 return;
14523 if (check_restricted() || check_secure())
14524 return;
14525 # ifdef FEAT_X11
14526 if (check_connection() == FAIL)
14527 return;
14528 # endif
14530 if (serverSendReply(server, reply) < 0)
14532 EMSG(_("E258: Unable to send to client"));
14533 return;
14535 rettv->vval.v_number = 0;
14536 #else
14537 rettv->vval.v_number = -1;
14538 #endif
14541 /*ARGSUSED*/
14542 static void
14543 f_serverlist(argvars, rettv)
14544 typval_T *argvars;
14545 typval_T *rettv;
14547 char_u *r = NULL;
14549 #ifdef FEAT_CLIENTSERVER
14550 # if defined(WIN32) || defined(MAC_CLIENTSERVER)
14551 r = serverGetVimNames();
14552 # elif defined(FEAT_X11)
14553 make_connection();
14554 if (X_DISPLAY != NULL)
14555 r = serverGetVimNames(X_DISPLAY);
14556 # endif
14557 #endif
14558 rettv->v_type = VAR_STRING;
14559 rettv->vval.v_string = r;
14563 * "setbufvar()" function
14565 /*ARGSUSED*/
14566 static void
14567 f_setbufvar(argvars, rettv)
14568 typval_T *argvars;
14569 typval_T *rettv;
14571 buf_T *buf;
14572 aco_save_T aco;
14573 char_u *varname, *bufvarname;
14574 typval_T *varp;
14575 char_u nbuf[NUMBUFLEN];
14577 rettv->vval.v_number = 0;
14579 if (check_restricted() || check_secure())
14580 return;
14581 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
14582 varname = get_tv_string_chk(&argvars[1]);
14583 buf = get_buf_tv(&argvars[0]);
14584 varp = &argvars[2];
14586 if (buf != NULL && varname != NULL && varp != NULL)
14588 /* set curbuf to be our buf, temporarily */
14589 aucmd_prepbuf(&aco, buf);
14591 if (*varname == '&')
14593 long numval;
14594 char_u *strval;
14595 int error = FALSE;
14597 ++varname;
14598 numval = get_tv_number_chk(varp, &error);
14599 strval = get_tv_string_buf_chk(varp, nbuf);
14600 if (!error && strval != NULL)
14601 set_option_value(varname, numval, strval, OPT_LOCAL);
14603 else
14605 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
14606 if (bufvarname != NULL)
14608 STRCPY(bufvarname, "b:");
14609 STRCPY(bufvarname + 2, varname);
14610 set_var(bufvarname, varp, TRUE);
14611 vim_free(bufvarname);
14615 /* reset notion of buffer */
14616 aucmd_restbuf(&aco);
14621 * "setcmdpos()" function
14623 static void
14624 f_setcmdpos(argvars, rettv)
14625 typval_T *argvars;
14626 typval_T *rettv;
14628 int pos = (int)get_tv_number(&argvars[0]) - 1;
14630 if (pos >= 0)
14631 rettv->vval.v_number = set_cmdline_pos(pos);
14635 * "setline()" function
14637 static void
14638 f_setline(argvars, rettv)
14639 typval_T *argvars;
14640 typval_T *rettv;
14642 linenr_T lnum;
14643 char_u *line = NULL;
14644 list_T *l = NULL;
14645 listitem_T *li = NULL;
14646 long added = 0;
14647 linenr_T lcount = curbuf->b_ml.ml_line_count;
14649 lnum = get_tv_lnum(&argvars[0]);
14650 if (argvars[1].v_type == VAR_LIST)
14652 l = argvars[1].vval.v_list;
14653 li = l->lv_first;
14655 else
14656 line = get_tv_string_chk(&argvars[1]);
14658 rettv->vval.v_number = 0; /* OK */
14659 for (;;)
14661 if (l != NULL)
14663 /* list argument, get next string */
14664 if (li == NULL)
14665 break;
14666 line = get_tv_string_chk(&li->li_tv);
14667 li = li->li_next;
14670 rettv->vval.v_number = 1; /* FAIL */
14671 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
14672 break;
14673 if (lnum <= curbuf->b_ml.ml_line_count)
14675 /* existing line, replace it */
14676 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
14678 changed_bytes(lnum, 0);
14679 if (lnum == curwin->w_cursor.lnum)
14680 check_cursor_col();
14681 rettv->vval.v_number = 0; /* OK */
14684 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
14686 /* lnum is one past the last line, append the line */
14687 ++added;
14688 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
14689 rettv->vval.v_number = 0; /* OK */
14692 if (l == NULL) /* only one string argument */
14693 break;
14694 ++lnum;
14697 if (added > 0)
14698 appended_lines_mark(lcount, added);
14701 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
14704 * Used by "setqflist()" and "setloclist()" functions
14706 /*ARGSUSED*/
14707 static void
14708 set_qf_ll_list(wp, list_arg, action_arg, rettv)
14709 win_T *wp;
14710 typval_T *list_arg;
14711 typval_T *action_arg;
14712 typval_T *rettv;
14714 #ifdef FEAT_QUICKFIX
14715 char_u *act;
14716 int action = ' ';
14717 #endif
14719 rettv->vval.v_number = -1;
14721 #ifdef FEAT_QUICKFIX
14722 if (list_arg->v_type != VAR_LIST)
14723 EMSG(_(e_listreq));
14724 else
14726 list_T *l = list_arg->vval.v_list;
14728 if (action_arg->v_type == VAR_STRING)
14730 act = get_tv_string_chk(action_arg);
14731 if (act == NULL)
14732 return; /* type error; errmsg already given */
14733 if (*act == 'a' || *act == 'r')
14734 action = *act;
14737 if (l != NULL && set_errorlist(wp, l, action) == OK)
14738 rettv->vval.v_number = 0;
14740 #endif
14744 * "setloclist()" function
14746 /*ARGSUSED*/
14747 static void
14748 f_setloclist(argvars, rettv)
14749 typval_T *argvars;
14750 typval_T *rettv;
14752 win_T *win;
14754 rettv->vval.v_number = -1;
14756 win = find_win_by_nr(&argvars[0], NULL);
14757 if (win != NULL)
14758 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
14762 * "setmatches()" function
14764 static void
14765 f_setmatches(argvars, rettv)
14766 typval_T *argvars;
14767 typval_T *rettv;
14769 #ifdef FEAT_SEARCH_EXTRA
14770 list_T *l;
14771 listitem_T *li;
14772 dict_T *d;
14774 rettv->vval.v_number = -1;
14775 if (argvars[0].v_type != VAR_LIST)
14777 EMSG(_(e_listreq));
14778 return;
14780 if ((l = argvars[0].vval.v_list) != NULL)
14783 /* To some extent make sure that we are dealing with a list from
14784 * "getmatches()". */
14785 li = l->lv_first;
14786 while (li != NULL)
14788 if (li->li_tv.v_type != VAR_DICT
14789 || (d = li->li_tv.vval.v_dict) == NULL)
14791 EMSG(_(e_invarg));
14792 return;
14794 if (!(dict_find(d, (char_u *)"group", -1) != NULL
14795 && dict_find(d, (char_u *)"pattern", -1) != NULL
14796 && dict_find(d, (char_u *)"priority", -1) != NULL
14797 && dict_find(d, (char_u *)"id", -1) != NULL))
14799 EMSG(_(e_invarg));
14800 return;
14802 li = li->li_next;
14805 clear_matches(curwin);
14806 li = l->lv_first;
14807 while (li != NULL)
14809 d = li->li_tv.vval.v_dict;
14810 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
14811 get_dict_string(d, (char_u *)"pattern", FALSE),
14812 (int)get_dict_number(d, (char_u *)"priority"),
14813 (int)get_dict_number(d, (char_u *)"id"));
14814 li = li->li_next;
14816 rettv->vval.v_number = 0;
14818 #endif
14822 * "setpos()" function
14824 /*ARGSUSED*/
14825 static void
14826 f_setpos(argvars, rettv)
14827 typval_T *argvars;
14828 typval_T *rettv;
14830 pos_T pos;
14831 int fnum;
14832 char_u *name;
14834 rettv->vval.v_number = -1;
14835 name = get_tv_string_chk(argvars);
14836 if (name != NULL)
14838 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
14840 --pos.col;
14841 if (name[0] == '.' && name[1] == NUL)
14843 /* set cursor */
14844 if (fnum == curbuf->b_fnum)
14846 curwin->w_cursor = pos;
14847 check_cursor();
14848 rettv->vval.v_number = 0;
14850 else
14851 EMSG(_(e_invarg));
14853 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
14855 /* set mark */
14856 if (setmark_pos(name[1], &pos, fnum) == OK)
14857 rettv->vval.v_number = 0;
14859 else
14860 EMSG(_(e_invarg));
14866 * "setqflist()" function
14868 /*ARGSUSED*/
14869 static void
14870 f_setqflist(argvars, rettv)
14871 typval_T *argvars;
14872 typval_T *rettv;
14874 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
14878 * "setreg()" function
14880 static void
14881 f_setreg(argvars, rettv)
14882 typval_T *argvars;
14883 typval_T *rettv;
14885 int regname;
14886 char_u *strregname;
14887 char_u *stropt;
14888 char_u *strval;
14889 int append;
14890 char_u yank_type;
14891 long block_len;
14893 block_len = -1;
14894 yank_type = MAUTO;
14895 append = FALSE;
14897 strregname = get_tv_string_chk(argvars);
14898 rettv->vval.v_number = 1; /* FAIL is default */
14900 if (strregname == NULL)
14901 return; /* type error; errmsg already given */
14902 regname = *strregname;
14903 if (regname == 0 || regname == '@')
14904 regname = '"';
14905 else if (regname == '=')
14906 return;
14908 if (argvars[2].v_type != VAR_UNKNOWN)
14910 stropt = get_tv_string_chk(&argvars[2]);
14911 if (stropt == NULL)
14912 return; /* type error */
14913 for (; *stropt != NUL; ++stropt)
14914 switch (*stropt)
14916 case 'a': case 'A': /* append */
14917 append = TRUE;
14918 break;
14919 case 'v': case 'c': /* character-wise selection */
14920 yank_type = MCHAR;
14921 break;
14922 case 'V': case 'l': /* line-wise selection */
14923 yank_type = MLINE;
14924 break;
14925 #ifdef FEAT_VISUAL
14926 case 'b': case Ctrl_V: /* block-wise selection */
14927 yank_type = MBLOCK;
14928 if (VIM_ISDIGIT(stropt[1]))
14930 ++stropt;
14931 block_len = getdigits(&stropt) - 1;
14932 --stropt;
14934 break;
14935 #endif
14939 strval = get_tv_string_chk(&argvars[1]);
14940 if (strval != NULL)
14941 write_reg_contents_ex(regname, strval, -1,
14942 append, yank_type, block_len);
14943 rettv->vval.v_number = 0;
14947 * "settabwinvar()" function
14949 static void
14950 f_settabwinvar(argvars, rettv)
14951 typval_T *argvars;
14952 typval_T *rettv;
14954 setwinvar(argvars, rettv, 1);
14958 * "setwinvar()" function
14960 static void
14961 f_setwinvar(argvars, rettv)
14962 typval_T *argvars;
14963 typval_T *rettv;
14965 setwinvar(argvars, rettv, 0);
14969 * "setwinvar()" and "settabwinvar()" functions
14971 static void
14972 setwinvar(argvars, rettv, off)
14973 typval_T *argvars;
14974 typval_T *rettv;
14975 int off;
14977 win_T *win;
14978 #ifdef FEAT_WINDOWS
14979 win_T *save_curwin;
14980 tabpage_T *save_curtab;
14981 #endif
14982 char_u *varname, *winvarname;
14983 typval_T *varp;
14984 char_u nbuf[NUMBUFLEN];
14985 tabpage_T *tp;
14987 rettv->vval.v_number = 0;
14989 if (check_restricted() || check_secure())
14990 return;
14992 #ifdef FEAT_WINDOWS
14993 if (off == 1)
14994 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
14995 else
14996 tp = curtab;
14997 #endif
14998 win = find_win_by_nr(&argvars[off], tp);
14999 varname = get_tv_string_chk(&argvars[off + 1]);
15000 varp = &argvars[off + 2];
15002 if (win != NULL && varname != NULL && varp != NULL)
15004 #ifdef FEAT_WINDOWS
15005 /* set curwin to be our win, temporarily */
15006 save_curwin = curwin;
15007 save_curtab = curtab;
15008 goto_tabpage_tp(tp);
15009 if (!win_valid(win))
15010 return;
15011 curwin = win;
15012 curbuf = curwin->w_buffer;
15013 #endif
15015 if (*varname == '&')
15017 long numval;
15018 char_u *strval;
15019 int error = FALSE;
15021 ++varname;
15022 numval = get_tv_number_chk(varp, &error);
15023 strval = get_tv_string_buf_chk(varp, nbuf);
15024 if (!error && strval != NULL)
15025 set_option_value(varname, numval, strval, OPT_LOCAL);
15027 else
15029 winvarname = alloc((unsigned)STRLEN(varname) + 3);
15030 if (winvarname != NULL)
15032 STRCPY(winvarname, "w:");
15033 STRCPY(winvarname + 2, varname);
15034 set_var(winvarname, varp, TRUE);
15035 vim_free(winvarname);
15039 #ifdef FEAT_WINDOWS
15040 /* Restore current tabpage and window, if still valid (autocomands can
15041 * make them invalid). */
15042 if (valid_tabpage(save_curtab))
15043 goto_tabpage_tp(save_curtab);
15044 if (win_valid(save_curwin))
15046 curwin = save_curwin;
15047 curbuf = curwin->w_buffer;
15049 #endif
15054 * "shellescape({string})" function
15056 static void
15057 f_shellescape(argvars, rettv)
15058 typval_T *argvars;
15059 typval_T *rettv;
15061 rettv->vval.v_string = vim_strsave_shellescape(get_tv_string(&argvars[0]));
15062 rettv->v_type = VAR_STRING;
15066 * "simplify()" function
15068 static void
15069 f_simplify(argvars, rettv)
15070 typval_T *argvars;
15071 typval_T *rettv;
15073 char_u *p;
15075 p = get_tv_string(&argvars[0]);
15076 rettv->vval.v_string = vim_strsave(p);
15077 simplify_filename(rettv->vval.v_string); /* simplify in place */
15078 rettv->v_type = VAR_STRING;
15081 static int
15082 #ifdef __BORLANDC__
15083 _RTLENTRYF
15084 #endif
15085 item_compare __ARGS((const void *s1, const void *s2));
15086 static int
15087 #ifdef __BORLANDC__
15088 _RTLENTRYF
15089 #endif
15090 item_compare2 __ARGS((const void *s1, const void *s2));
15092 static int item_compare_ic;
15093 static char_u *item_compare_func;
15094 static int item_compare_func_err;
15095 #define ITEM_COMPARE_FAIL 999
15098 * Compare functions for f_sort() below.
15100 static int
15101 #ifdef __BORLANDC__
15102 _RTLENTRYF
15103 #endif
15104 item_compare(s1, s2)
15105 const void *s1;
15106 const void *s2;
15108 char_u *p1, *p2;
15109 char_u *tofree1, *tofree2;
15110 int res;
15111 char_u numbuf1[NUMBUFLEN];
15112 char_u numbuf2[NUMBUFLEN];
15114 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
15115 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
15116 if (p1 == NULL)
15117 p1 = (char_u *)"";
15118 if (p2 == NULL)
15119 p2 = (char_u *)"";
15120 if (item_compare_ic)
15121 res = STRICMP(p1, p2);
15122 else
15123 res = STRCMP(p1, p2);
15124 vim_free(tofree1);
15125 vim_free(tofree2);
15126 return res;
15129 static int
15130 #ifdef __BORLANDC__
15131 _RTLENTRYF
15132 #endif
15133 item_compare2(s1, s2)
15134 const void *s1;
15135 const void *s2;
15137 int res;
15138 typval_T rettv;
15139 typval_T argv[3];
15140 int dummy;
15142 /* shortcut after failure in previous call; compare all items equal */
15143 if (item_compare_func_err)
15144 return 0;
15146 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
15147 * in the copy without changing the original list items. */
15148 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
15149 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
15151 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
15152 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
15153 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
15154 clear_tv(&argv[0]);
15155 clear_tv(&argv[1]);
15157 if (res == FAIL)
15158 res = ITEM_COMPARE_FAIL;
15159 else
15160 /* return value has wrong type */
15161 res = get_tv_number_chk(&rettv, &item_compare_func_err);
15162 if (item_compare_func_err)
15163 res = ITEM_COMPARE_FAIL;
15164 clear_tv(&rettv);
15165 return res;
15169 * "sort({list})" function
15171 static void
15172 f_sort(argvars, rettv)
15173 typval_T *argvars;
15174 typval_T *rettv;
15176 list_T *l;
15177 listitem_T *li;
15178 listitem_T **ptrs;
15179 long len;
15180 long i;
15182 rettv->vval.v_number = 0;
15183 if (argvars[0].v_type != VAR_LIST)
15184 EMSG2(_(e_listarg), "sort()");
15185 else
15187 l = argvars[0].vval.v_list;
15188 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
15189 return;
15190 rettv->vval.v_list = l;
15191 rettv->v_type = VAR_LIST;
15192 ++l->lv_refcount;
15194 len = list_len(l);
15195 if (len <= 1)
15196 return; /* short list sorts pretty quickly */
15198 item_compare_ic = FALSE;
15199 item_compare_func = NULL;
15200 if (argvars[1].v_type != VAR_UNKNOWN)
15202 if (argvars[1].v_type == VAR_FUNC)
15203 item_compare_func = argvars[1].vval.v_string;
15204 else
15206 int error = FALSE;
15208 i = get_tv_number_chk(&argvars[1], &error);
15209 if (error)
15210 return; /* type error; errmsg already given */
15211 if (i == 1)
15212 item_compare_ic = TRUE;
15213 else
15214 item_compare_func = get_tv_string(&argvars[1]);
15218 /* Make an array with each entry pointing to an item in the List. */
15219 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
15220 if (ptrs == NULL)
15221 return;
15222 i = 0;
15223 for (li = l->lv_first; li != NULL; li = li->li_next)
15224 ptrs[i++] = li;
15226 item_compare_func_err = FALSE;
15227 /* test the compare function */
15228 if (item_compare_func != NULL
15229 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
15230 == ITEM_COMPARE_FAIL)
15231 EMSG(_("E702: Sort compare function failed"));
15232 else
15234 /* Sort the array with item pointers. */
15235 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
15236 item_compare_func == NULL ? item_compare : item_compare2);
15238 if (!item_compare_func_err)
15240 /* Clear the List and append the items in the sorted order. */
15241 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
15242 l->lv_len = 0;
15243 for (i = 0; i < len; ++i)
15244 list_append(l, ptrs[i]);
15248 vim_free(ptrs);
15253 * "soundfold({word})" function
15255 static void
15256 f_soundfold(argvars, rettv)
15257 typval_T *argvars;
15258 typval_T *rettv;
15260 char_u *s;
15262 rettv->v_type = VAR_STRING;
15263 s = get_tv_string(&argvars[0]);
15264 #ifdef FEAT_SPELL
15265 rettv->vval.v_string = eval_soundfold(s);
15266 #else
15267 rettv->vval.v_string = vim_strsave(s);
15268 #endif
15272 * "spellbadword()" function
15274 /* ARGSUSED */
15275 static void
15276 f_spellbadword(argvars, rettv)
15277 typval_T *argvars;
15278 typval_T *rettv;
15280 char_u *word = (char_u *)"";
15281 hlf_T attr = HLF_COUNT;
15282 int len = 0;
15284 if (rettv_list_alloc(rettv) == FAIL)
15285 return;
15287 #ifdef FEAT_SPELL
15288 if (argvars[0].v_type == VAR_UNKNOWN)
15290 /* Find the start and length of the badly spelled word. */
15291 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
15292 if (len != 0)
15293 word = ml_get_cursor();
15295 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15297 char_u *str = get_tv_string_chk(&argvars[0]);
15298 int capcol = -1;
15300 if (str != NULL)
15302 /* Check the argument for spelling. */
15303 while (*str != NUL)
15305 len = spell_check(curwin, str, &attr, &capcol, FALSE);
15306 if (attr != HLF_COUNT)
15308 word = str;
15309 break;
15311 str += len;
15315 #endif
15317 list_append_string(rettv->vval.v_list, word, len);
15318 list_append_string(rettv->vval.v_list, (char_u *)(
15319 attr == HLF_SPB ? "bad" :
15320 attr == HLF_SPR ? "rare" :
15321 attr == HLF_SPL ? "local" :
15322 attr == HLF_SPC ? "caps" :
15323 ""), -1);
15327 * "spellsuggest()" function
15329 /*ARGSUSED*/
15330 static void
15331 f_spellsuggest(argvars, rettv)
15332 typval_T *argvars;
15333 typval_T *rettv;
15335 #ifdef FEAT_SPELL
15336 char_u *str;
15337 int typeerr = FALSE;
15338 int maxcount;
15339 garray_T ga;
15340 int i;
15341 listitem_T *li;
15342 int need_capital = FALSE;
15343 #endif
15345 if (rettv_list_alloc(rettv) == FAIL)
15346 return;
15348 #ifdef FEAT_SPELL
15349 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15351 str = get_tv_string(&argvars[0]);
15352 if (argvars[1].v_type != VAR_UNKNOWN)
15354 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
15355 if (maxcount <= 0)
15356 return;
15357 if (argvars[2].v_type != VAR_UNKNOWN)
15359 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
15360 if (typeerr)
15361 return;
15364 else
15365 maxcount = 25;
15367 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
15369 for (i = 0; i < ga.ga_len; ++i)
15371 str = ((char_u **)ga.ga_data)[i];
15373 li = listitem_alloc();
15374 if (li == NULL)
15375 vim_free(str);
15376 else
15378 li->li_tv.v_type = VAR_STRING;
15379 li->li_tv.v_lock = 0;
15380 li->li_tv.vval.v_string = str;
15381 list_append(rettv->vval.v_list, li);
15384 ga_clear(&ga);
15386 #endif
15389 static void
15390 f_split(argvars, rettv)
15391 typval_T *argvars;
15392 typval_T *rettv;
15394 char_u *str;
15395 char_u *end;
15396 char_u *pat = NULL;
15397 regmatch_T regmatch;
15398 char_u patbuf[NUMBUFLEN];
15399 char_u *save_cpo;
15400 int match;
15401 colnr_T col = 0;
15402 int keepempty = FALSE;
15403 int typeerr = FALSE;
15405 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15406 save_cpo = p_cpo;
15407 p_cpo = (char_u *)"";
15409 str = get_tv_string(&argvars[0]);
15410 if (argvars[1].v_type != VAR_UNKNOWN)
15412 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
15413 if (pat == NULL)
15414 typeerr = TRUE;
15415 if (argvars[2].v_type != VAR_UNKNOWN)
15416 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
15418 if (pat == NULL || *pat == NUL)
15419 pat = (char_u *)"[\\x01- ]\\+";
15421 if (rettv_list_alloc(rettv) == FAIL)
15422 return;
15423 if (typeerr)
15424 return;
15426 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
15427 if (regmatch.regprog != NULL)
15429 regmatch.rm_ic = FALSE;
15430 while (*str != NUL || keepempty)
15432 if (*str == NUL)
15433 match = FALSE; /* empty item at the end */
15434 else
15435 match = vim_regexec_nl(&regmatch, str, col);
15436 if (match)
15437 end = regmatch.startp[0];
15438 else
15439 end = str + STRLEN(str);
15440 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
15441 && *str != NUL && match && end < regmatch.endp[0]))
15443 if (list_append_string(rettv->vval.v_list, str,
15444 (int)(end - str)) == FAIL)
15445 break;
15447 if (!match)
15448 break;
15449 /* Advance to just after the match. */
15450 if (regmatch.endp[0] > str)
15451 col = 0;
15452 else
15454 /* Don't get stuck at the same match. */
15455 #ifdef FEAT_MBYTE
15456 col = (*mb_ptr2len)(regmatch.endp[0]);
15457 #else
15458 col = 1;
15459 #endif
15461 str = regmatch.endp[0];
15464 vim_free(regmatch.regprog);
15467 p_cpo = save_cpo;
15471 * "str2nr()" function
15473 static void
15474 f_str2nr(argvars, rettv)
15475 typval_T *argvars;
15476 typval_T *rettv;
15478 int base = 10;
15479 char_u *p;
15480 long n;
15482 if (argvars[1].v_type != VAR_UNKNOWN)
15484 base = get_tv_number(&argvars[1]);
15485 if (base != 8 && base != 10 && base != 16)
15487 EMSG(_(e_invarg));
15488 return;
15492 p = skipwhite(get_tv_string(&argvars[0]));
15493 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
15494 rettv->vval.v_number = n;
15497 #ifdef HAVE_STRFTIME
15499 * "strftime({format}[, {time}])" function
15501 static void
15502 f_strftime(argvars, rettv)
15503 typval_T *argvars;
15504 typval_T *rettv;
15506 char_u result_buf[256];
15507 struct tm *curtime;
15508 time_t seconds;
15509 char_u *p;
15511 rettv->v_type = VAR_STRING;
15513 p = get_tv_string(&argvars[0]);
15514 if (argvars[1].v_type == VAR_UNKNOWN)
15515 seconds = time(NULL);
15516 else
15517 seconds = (time_t)get_tv_number(&argvars[1]);
15518 curtime = localtime(&seconds);
15519 /* MSVC returns NULL for an invalid value of seconds. */
15520 if (curtime == NULL)
15521 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
15522 else
15524 # ifdef FEAT_MBYTE
15525 vimconv_T conv;
15526 char_u *enc;
15528 conv.vc_type = CONV_NONE;
15529 enc = enc_locale();
15530 convert_setup(&conv, p_enc, enc);
15531 if (conv.vc_type != CONV_NONE)
15532 p = string_convert(&conv, p, NULL);
15533 # endif
15534 if (p != NULL)
15535 (void)strftime((char *)result_buf, sizeof(result_buf),
15536 (char *)p, curtime);
15537 else
15538 result_buf[0] = NUL;
15540 # ifdef FEAT_MBYTE
15541 if (conv.vc_type != CONV_NONE)
15542 vim_free(p);
15543 convert_setup(&conv, enc, p_enc);
15544 if (conv.vc_type != CONV_NONE)
15545 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
15546 else
15547 # endif
15548 rettv->vval.v_string = vim_strsave(result_buf);
15550 # ifdef FEAT_MBYTE
15551 /* Release conversion descriptors */
15552 convert_setup(&conv, NULL, NULL);
15553 vim_free(enc);
15554 # endif
15557 #endif
15560 * "stridx()" function
15562 static void
15563 f_stridx(argvars, rettv)
15564 typval_T *argvars;
15565 typval_T *rettv;
15567 char_u buf[NUMBUFLEN];
15568 char_u *needle;
15569 char_u *haystack;
15570 char_u *save_haystack;
15571 char_u *pos;
15572 int start_idx;
15574 needle = get_tv_string_chk(&argvars[1]);
15575 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
15576 rettv->vval.v_number = -1;
15577 if (needle == NULL || haystack == NULL)
15578 return; /* type error; errmsg already given */
15580 if (argvars[2].v_type != VAR_UNKNOWN)
15582 int error = FALSE;
15584 start_idx = get_tv_number_chk(&argvars[2], &error);
15585 if (error || start_idx >= (int)STRLEN(haystack))
15586 return;
15587 if (start_idx >= 0)
15588 haystack += start_idx;
15591 pos = (char_u *)strstr((char *)haystack, (char *)needle);
15592 if (pos != NULL)
15593 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
15597 * "string()" function
15599 static void
15600 f_string(argvars, rettv)
15601 typval_T *argvars;
15602 typval_T *rettv;
15604 char_u *tofree;
15605 char_u numbuf[NUMBUFLEN];
15607 rettv->v_type = VAR_STRING;
15608 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
15609 /* Make a copy if we have a value but it's not in allocate memory. */
15610 if (rettv->vval.v_string != NULL && tofree == NULL)
15611 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
15615 * "strlen()" function
15617 static void
15618 f_strlen(argvars, rettv)
15619 typval_T *argvars;
15620 typval_T *rettv;
15622 rettv->vval.v_number = (varnumber_T)(STRLEN(
15623 get_tv_string(&argvars[0])));
15627 * "strpart()" function
15629 static void
15630 f_strpart(argvars, rettv)
15631 typval_T *argvars;
15632 typval_T *rettv;
15634 char_u *p;
15635 int n;
15636 int len;
15637 int slen;
15638 int error = FALSE;
15640 p = get_tv_string(&argvars[0]);
15641 slen = (int)STRLEN(p);
15643 n = get_tv_number_chk(&argvars[1], &error);
15644 if (error)
15645 len = 0;
15646 else if (argvars[2].v_type != VAR_UNKNOWN)
15647 len = get_tv_number(&argvars[2]);
15648 else
15649 len = slen - n; /* default len: all bytes that are available. */
15652 * Only return the overlap between the specified part and the actual
15653 * string.
15655 if (n < 0)
15657 len += n;
15658 n = 0;
15660 else if (n > slen)
15661 n = slen;
15662 if (len < 0)
15663 len = 0;
15664 else if (n + len > slen)
15665 len = slen - n;
15667 rettv->v_type = VAR_STRING;
15668 rettv->vval.v_string = vim_strnsave(p + n, len);
15672 * "strridx()" function
15674 static void
15675 f_strridx(argvars, rettv)
15676 typval_T *argvars;
15677 typval_T *rettv;
15679 char_u buf[NUMBUFLEN];
15680 char_u *needle;
15681 char_u *haystack;
15682 char_u *rest;
15683 char_u *lastmatch = NULL;
15684 int haystack_len, end_idx;
15686 needle = get_tv_string_chk(&argvars[1]);
15687 haystack = get_tv_string_buf_chk(&argvars[0], buf);
15689 rettv->vval.v_number = -1;
15690 if (needle == NULL || haystack == NULL)
15691 return; /* type error; errmsg already given */
15693 haystack_len = (int)STRLEN(haystack);
15694 if (argvars[2].v_type != VAR_UNKNOWN)
15696 /* Third argument: upper limit for index */
15697 end_idx = get_tv_number_chk(&argvars[2], NULL);
15698 if (end_idx < 0)
15699 return; /* can never find a match */
15701 else
15702 end_idx = haystack_len;
15704 if (*needle == NUL)
15706 /* Empty string matches past the end. */
15707 lastmatch = haystack + end_idx;
15709 else
15711 for (rest = haystack; *rest != '\0'; ++rest)
15713 rest = (char_u *)strstr((char *)rest, (char *)needle);
15714 if (rest == NULL || rest > haystack + end_idx)
15715 break;
15716 lastmatch = rest;
15720 if (lastmatch == NULL)
15721 rettv->vval.v_number = -1;
15722 else
15723 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
15727 * "strtrans()" function
15729 static void
15730 f_strtrans(argvars, rettv)
15731 typval_T *argvars;
15732 typval_T *rettv;
15734 rettv->v_type = VAR_STRING;
15735 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
15739 * "submatch()" function
15741 static void
15742 f_submatch(argvars, rettv)
15743 typval_T *argvars;
15744 typval_T *rettv;
15746 rettv->v_type = VAR_STRING;
15747 rettv->vval.v_string =
15748 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
15752 * "substitute()" function
15754 static void
15755 f_substitute(argvars, rettv)
15756 typval_T *argvars;
15757 typval_T *rettv;
15759 char_u patbuf[NUMBUFLEN];
15760 char_u subbuf[NUMBUFLEN];
15761 char_u flagsbuf[NUMBUFLEN];
15763 char_u *str = get_tv_string_chk(&argvars[0]);
15764 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
15765 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
15766 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
15768 rettv->v_type = VAR_STRING;
15769 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
15770 rettv->vval.v_string = NULL;
15771 else
15772 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
15776 * "synID(lnum, col, trans)" function
15778 /*ARGSUSED*/
15779 static void
15780 f_synID(argvars, rettv)
15781 typval_T *argvars;
15782 typval_T *rettv;
15784 int id = 0;
15785 #ifdef FEAT_SYN_HL
15786 long lnum;
15787 long col;
15788 int trans;
15789 int transerr = FALSE;
15791 lnum = get_tv_lnum(argvars); /* -1 on type error */
15792 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
15793 trans = get_tv_number_chk(&argvars[2], &transerr);
15795 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
15796 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
15797 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
15798 #endif
15800 rettv->vval.v_number = id;
15804 * "synIDattr(id, what [, mode])" function
15806 /*ARGSUSED*/
15807 static void
15808 f_synIDattr(argvars, rettv)
15809 typval_T *argvars;
15810 typval_T *rettv;
15812 char_u *p = NULL;
15813 #ifdef FEAT_SYN_HL
15814 int id;
15815 char_u *what;
15816 char_u *mode;
15817 char_u modebuf[NUMBUFLEN];
15818 int modec;
15820 id = get_tv_number(&argvars[0]);
15821 what = get_tv_string(&argvars[1]);
15822 if (argvars[2].v_type != VAR_UNKNOWN)
15824 mode = get_tv_string_buf(&argvars[2], modebuf);
15825 modec = TOLOWER_ASC(mode[0]);
15826 if (modec != 't' && modec != 'c'
15827 #ifdef FEAT_GUI
15828 && modec != 'g'
15829 #endif
15831 modec = 0; /* replace invalid with current */
15833 else
15835 #ifdef FEAT_GUI
15836 if (gui.in_use)
15837 modec = 'g';
15838 else
15839 #endif
15840 if (t_colors > 1)
15841 modec = 'c';
15842 else
15843 modec = 't';
15847 switch (TOLOWER_ASC(what[0]))
15849 case 'b':
15850 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
15851 p = highlight_color(id, what, modec);
15852 else /* bold */
15853 p = highlight_has_attr(id, HL_BOLD, modec);
15854 break;
15856 case 'f': /* fg[#] */
15857 p = highlight_color(id, what, modec);
15858 break;
15860 case 'i':
15861 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
15862 p = highlight_has_attr(id, HL_INVERSE, modec);
15863 else /* italic */
15864 p = highlight_has_attr(id, HL_ITALIC, modec);
15865 break;
15867 case 'n': /* name */
15868 p = get_highlight_name(NULL, id - 1);
15869 break;
15871 case 'r': /* reverse */
15872 p = highlight_has_attr(id, HL_INVERSE, modec);
15873 break;
15875 case 's': /* standout */
15876 p = highlight_has_attr(id, HL_STANDOUT, modec);
15877 break;
15879 case 'u':
15880 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
15881 /* underline */
15882 p = highlight_has_attr(id, HL_UNDERLINE, modec);
15883 else
15884 /* undercurl */
15885 p = highlight_has_attr(id, HL_UNDERCURL, modec);
15886 break;
15889 if (p != NULL)
15890 p = vim_strsave(p);
15891 #endif
15892 rettv->v_type = VAR_STRING;
15893 rettv->vval.v_string = p;
15897 * "synIDtrans(id)" function
15899 /*ARGSUSED*/
15900 static void
15901 f_synIDtrans(argvars, rettv)
15902 typval_T *argvars;
15903 typval_T *rettv;
15905 int id;
15907 #ifdef FEAT_SYN_HL
15908 id = get_tv_number(&argvars[0]);
15910 if (id > 0)
15911 id = syn_get_final_id(id);
15912 else
15913 #endif
15914 id = 0;
15916 rettv->vval.v_number = id;
15920 * "synstack(lnum, col)" function
15922 /*ARGSUSED*/
15923 static void
15924 f_synstack(argvars, rettv)
15925 typval_T *argvars;
15926 typval_T *rettv;
15928 #ifdef FEAT_SYN_HL
15929 long lnum;
15930 long col;
15931 int i;
15932 int id;
15933 #endif
15935 rettv->v_type = VAR_LIST;
15936 rettv->vval.v_list = NULL;
15938 #ifdef FEAT_SYN_HL
15939 lnum = get_tv_lnum(argvars); /* -1 on type error */
15940 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
15942 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
15943 && col >= 0 && col < (long)STRLEN(ml_get(lnum))
15944 && rettv_list_alloc(rettv) != FAIL)
15946 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
15947 for (i = 0; ; ++i)
15949 id = syn_get_stack_item(i);
15950 if (id < 0)
15951 break;
15952 if (list_append_number(rettv->vval.v_list, id) == FAIL)
15953 break;
15956 #endif
15960 * "system()" function
15962 static void
15963 f_system(argvars, rettv)
15964 typval_T *argvars;
15965 typval_T *rettv;
15967 char_u *res = NULL;
15968 char_u *p;
15969 char_u *infile = NULL;
15970 char_u buf[NUMBUFLEN];
15971 int err = FALSE;
15972 FILE *fd;
15974 if (check_restricted() || check_secure())
15975 goto done;
15977 if (argvars[1].v_type != VAR_UNKNOWN)
15980 * Write the string to a temp file, to be used for input of the shell
15981 * command.
15983 if ((infile = vim_tempname('i')) == NULL)
15985 EMSG(_(e_notmp));
15986 goto done;
15989 fd = mch_fopen((char *)infile, WRITEBIN);
15990 if (fd == NULL)
15992 EMSG2(_(e_notopen), infile);
15993 goto done;
15995 p = get_tv_string_buf_chk(&argvars[1], buf);
15996 if (p == NULL)
15998 fclose(fd);
15999 goto done; /* type error; errmsg already given */
16001 if (fwrite(p, STRLEN(p), 1, fd) != 1)
16002 err = TRUE;
16003 if (fclose(fd) != 0)
16004 err = TRUE;
16005 if (err)
16007 EMSG(_("E677: Error writing temp file"));
16008 goto done;
16012 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
16013 SHELL_SILENT | SHELL_COOKED);
16015 #ifdef USE_CR
16016 /* translate <CR> into <NL> */
16017 if (res != NULL)
16019 char_u *s;
16021 for (s = res; *s; ++s)
16023 if (*s == CAR)
16024 *s = NL;
16027 #else
16028 # ifdef USE_CRNL
16029 /* translate <CR><NL> into <NL> */
16030 if (res != NULL)
16032 char_u *s, *d;
16034 d = res;
16035 for (s = res; *s; ++s)
16037 if (s[0] == CAR && s[1] == NL)
16038 ++s;
16039 *d++ = *s;
16041 *d = NUL;
16043 # endif
16044 #endif
16046 done:
16047 if (infile != NULL)
16049 mch_remove(infile);
16050 vim_free(infile);
16052 rettv->v_type = VAR_STRING;
16053 rettv->vval.v_string = res;
16057 * "tabpagebuflist()" function
16059 /* ARGSUSED */
16060 static void
16061 f_tabpagebuflist(argvars, rettv)
16062 typval_T *argvars;
16063 typval_T *rettv;
16065 #ifndef FEAT_WINDOWS
16066 rettv->vval.v_number = 0;
16067 #else
16068 tabpage_T *tp;
16069 win_T *wp = NULL;
16071 if (argvars[0].v_type == VAR_UNKNOWN)
16072 wp = firstwin;
16073 else
16075 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16076 if (tp != NULL)
16077 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16079 if (wp == NULL)
16080 rettv->vval.v_number = 0;
16081 else
16083 if (rettv_list_alloc(rettv) == FAIL)
16084 rettv->vval.v_number = 0;
16085 else
16087 for (; wp != NULL; wp = wp->w_next)
16088 if (list_append_number(rettv->vval.v_list,
16089 wp->w_buffer->b_fnum) == FAIL)
16090 break;
16093 #endif
16098 * "tabpagenr()" function
16100 /* ARGSUSED */
16101 static void
16102 f_tabpagenr(argvars, rettv)
16103 typval_T *argvars;
16104 typval_T *rettv;
16106 int nr = 1;
16107 #ifdef FEAT_WINDOWS
16108 char_u *arg;
16110 if (argvars[0].v_type != VAR_UNKNOWN)
16112 arg = get_tv_string_chk(&argvars[0]);
16113 nr = 0;
16114 if (arg != NULL)
16116 if (STRCMP(arg, "$") == 0)
16117 nr = tabpage_index(NULL) - 1;
16118 else
16119 EMSG2(_(e_invexpr2), arg);
16122 else
16123 nr = tabpage_index(curtab);
16124 #endif
16125 rettv->vval.v_number = nr;
16129 #ifdef FEAT_WINDOWS
16130 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
16133 * Common code for tabpagewinnr() and winnr().
16135 static int
16136 get_winnr(tp, argvar)
16137 tabpage_T *tp;
16138 typval_T *argvar;
16140 win_T *twin;
16141 int nr = 1;
16142 win_T *wp;
16143 char_u *arg;
16145 twin = (tp == curtab) ? curwin : tp->tp_curwin;
16146 if (argvar->v_type != VAR_UNKNOWN)
16148 arg = get_tv_string_chk(argvar);
16149 if (arg == NULL)
16150 nr = 0; /* type error; errmsg already given */
16151 else if (STRCMP(arg, "$") == 0)
16152 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
16153 else if (STRCMP(arg, "#") == 0)
16155 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
16156 if (twin == NULL)
16157 nr = 0;
16159 else
16161 EMSG2(_(e_invexpr2), arg);
16162 nr = 0;
16166 if (nr > 0)
16167 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16168 wp != twin; wp = wp->w_next)
16170 if (wp == NULL)
16172 /* didn't find it in this tabpage */
16173 nr = 0;
16174 break;
16176 ++nr;
16178 return nr;
16180 #endif
16183 * "tabpagewinnr()" function
16185 /* ARGSUSED */
16186 static void
16187 f_tabpagewinnr(argvars, rettv)
16188 typval_T *argvars;
16189 typval_T *rettv;
16191 int nr = 1;
16192 #ifdef FEAT_WINDOWS
16193 tabpage_T *tp;
16195 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16196 if (tp == NULL)
16197 nr = 0;
16198 else
16199 nr = get_winnr(tp, &argvars[1]);
16200 #endif
16201 rettv->vval.v_number = nr;
16206 * "tagfiles()" function
16208 /*ARGSUSED*/
16209 static void
16210 f_tagfiles(argvars, rettv)
16211 typval_T *argvars;
16212 typval_T *rettv;
16214 char_u fname[MAXPATHL + 1];
16215 tagname_T tn;
16216 int first;
16218 if (rettv_list_alloc(rettv) == FAIL)
16220 rettv->vval.v_number = 0;
16221 return;
16224 for (first = TRUE; ; first = FALSE)
16225 if (get_tagfname(&tn, first, fname) == FAIL
16226 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
16227 break;
16228 tagname_free(&tn);
16232 * "taglist()" function
16234 static void
16235 f_taglist(argvars, rettv)
16236 typval_T *argvars;
16237 typval_T *rettv;
16239 char_u *tag_pattern;
16241 tag_pattern = get_tv_string(&argvars[0]);
16243 rettv->vval.v_number = FALSE;
16244 if (*tag_pattern == NUL)
16245 return;
16247 if (rettv_list_alloc(rettv) == OK)
16248 (void)get_tags(rettv->vval.v_list, tag_pattern);
16252 * "tempname()" function
16254 /*ARGSUSED*/
16255 static void
16256 f_tempname(argvars, rettv)
16257 typval_T *argvars;
16258 typval_T *rettv;
16260 static int x = 'A';
16262 rettv->v_type = VAR_STRING;
16263 rettv->vval.v_string = vim_tempname(x);
16265 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
16266 * names. Skip 'I' and 'O', they are used for shell redirection. */
16269 if (x == 'Z')
16270 x = '0';
16271 else if (x == '9')
16272 x = 'A';
16273 else
16275 #ifdef EBCDIC
16276 if (x == 'I')
16277 x = 'J';
16278 else if (x == 'R')
16279 x = 'S';
16280 else
16281 #endif
16282 ++x;
16284 } while (x == 'I' || x == 'O');
16288 * "test(list)" function: Just checking the walls...
16290 /*ARGSUSED*/
16291 static void
16292 f_test(argvars, rettv)
16293 typval_T *argvars;
16294 typval_T *rettv;
16296 /* Used for unit testing. Change the code below to your liking. */
16297 #if 0
16298 listitem_T *li;
16299 list_T *l;
16300 char_u *bad, *good;
16302 if (argvars[0].v_type != VAR_LIST)
16303 return;
16304 l = argvars[0].vval.v_list;
16305 if (l == NULL)
16306 return;
16307 li = l->lv_first;
16308 if (li == NULL)
16309 return;
16310 bad = get_tv_string(&li->li_tv);
16311 li = li->li_next;
16312 if (li == NULL)
16313 return;
16314 good = get_tv_string(&li->li_tv);
16315 rettv->vval.v_number = test_edit_score(bad, good);
16316 #endif
16320 * "tolower(string)" function
16322 static void
16323 f_tolower(argvars, rettv)
16324 typval_T *argvars;
16325 typval_T *rettv;
16327 char_u *p;
16329 p = vim_strsave(get_tv_string(&argvars[0]));
16330 rettv->v_type = VAR_STRING;
16331 rettv->vval.v_string = p;
16333 if (p != NULL)
16334 while (*p != NUL)
16336 #ifdef FEAT_MBYTE
16337 int l;
16339 if (enc_utf8)
16341 int c, lc;
16343 c = utf_ptr2char(p);
16344 lc = utf_tolower(c);
16345 l = utf_ptr2len(p);
16346 /* TODO: reallocate string when byte count changes. */
16347 if (utf_char2len(lc) == l)
16348 utf_char2bytes(lc, p);
16349 p += l;
16351 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
16352 p += l; /* skip multi-byte character */
16353 else
16354 #endif
16356 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
16357 ++p;
16363 * "toupper(string)" function
16365 static void
16366 f_toupper(argvars, rettv)
16367 typval_T *argvars;
16368 typval_T *rettv;
16370 rettv->v_type = VAR_STRING;
16371 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
16375 * "tr(string, fromstr, tostr)" function
16377 static void
16378 f_tr(argvars, rettv)
16379 typval_T *argvars;
16380 typval_T *rettv;
16382 char_u *instr;
16383 char_u *fromstr;
16384 char_u *tostr;
16385 char_u *p;
16386 #ifdef FEAT_MBYTE
16387 int inlen;
16388 int fromlen;
16389 int tolen;
16390 int idx;
16391 char_u *cpstr;
16392 int cplen;
16393 int first = TRUE;
16394 #endif
16395 char_u buf[NUMBUFLEN];
16396 char_u buf2[NUMBUFLEN];
16397 garray_T ga;
16399 instr = get_tv_string(&argvars[0]);
16400 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
16401 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
16403 /* Default return value: empty string. */
16404 rettv->v_type = VAR_STRING;
16405 rettv->vval.v_string = NULL;
16406 if (fromstr == NULL || tostr == NULL)
16407 return; /* type error; errmsg already given */
16408 ga_init2(&ga, (int)sizeof(char), 80);
16410 #ifdef FEAT_MBYTE
16411 if (!has_mbyte)
16412 #endif
16413 /* not multi-byte: fromstr and tostr must be the same length */
16414 if (STRLEN(fromstr) != STRLEN(tostr))
16416 #ifdef FEAT_MBYTE
16417 error:
16418 #endif
16419 EMSG2(_(e_invarg2), fromstr);
16420 ga_clear(&ga);
16421 return;
16424 /* fromstr and tostr have to contain the same number of chars */
16425 while (*instr != NUL)
16427 #ifdef FEAT_MBYTE
16428 if (has_mbyte)
16430 inlen = (*mb_ptr2len)(instr);
16431 cpstr = instr;
16432 cplen = inlen;
16433 idx = 0;
16434 for (p = fromstr; *p != NUL; p += fromlen)
16436 fromlen = (*mb_ptr2len)(p);
16437 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
16439 for (p = tostr; *p != NUL; p += tolen)
16441 tolen = (*mb_ptr2len)(p);
16442 if (idx-- == 0)
16444 cplen = tolen;
16445 cpstr = p;
16446 break;
16449 if (*p == NUL) /* tostr is shorter than fromstr */
16450 goto error;
16451 break;
16453 ++idx;
16456 if (first && cpstr == instr)
16458 /* Check that fromstr and tostr have the same number of
16459 * (multi-byte) characters. Done only once when a character
16460 * of instr doesn't appear in fromstr. */
16461 first = FALSE;
16462 for (p = tostr; *p != NUL; p += tolen)
16464 tolen = (*mb_ptr2len)(p);
16465 --idx;
16467 if (idx != 0)
16468 goto error;
16471 ga_grow(&ga, cplen);
16472 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
16473 ga.ga_len += cplen;
16475 instr += inlen;
16477 else
16478 #endif
16480 /* When not using multi-byte chars we can do it faster. */
16481 p = vim_strchr(fromstr, *instr);
16482 if (p != NULL)
16483 ga_append(&ga, tostr[p - fromstr]);
16484 else
16485 ga_append(&ga, *instr);
16486 ++instr;
16490 /* add a terminating NUL */
16491 ga_grow(&ga, 1);
16492 ga_append(&ga, NUL);
16494 rettv->vval.v_string = ga.ga_data;
16498 * "type(expr)" function
16500 static void
16501 f_type(argvars, rettv)
16502 typval_T *argvars;
16503 typval_T *rettv;
16505 int n;
16507 switch (argvars[0].v_type)
16509 case VAR_NUMBER: n = 0; break;
16510 case VAR_STRING: n = 1; break;
16511 case VAR_FUNC: n = 2; break;
16512 case VAR_LIST: n = 3; break;
16513 case VAR_DICT: n = 4; break;
16514 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
16516 rettv->vval.v_number = n;
16520 * "values(dict)" function
16522 static void
16523 f_values(argvars, rettv)
16524 typval_T *argvars;
16525 typval_T *rettv;
16527 dict_list(argvars, rettv, 1);
16531 * "virtcol(string)" function
16533 static void
16534 f_virtcol(argvars, rettv)
16535 typval_T *argvars;
16536 typval_T *rettv;
16538 colnr_T vcol = 0;
16539 pos_T *fp;
16540 int fnum = curbuf->b_fnum;
16542 fp = var2fpos(&argvars[0], FALSE, &fnum);
16543 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
16544 && fnum == curbuf->b_fnum)
16546 getvvcol(curwin, fp, NULL, NULL, &vcol);
16547 ++vcol;
16550 rettv->vval.v_number = vcol;
16554 * "visualmode()" function
16556 /*ARGSUSED*/
16557 static void
16558 f_visualmode(argvars, rettv)
16559 typval_T *argvars;
16560 typval_T *rettv;
16562 #ifdef FEAT_VISUAL
16563 char_u str[2];
16565 rettv->v_type = VAR_STRING;
16566 str[0] = curbuf->b_visual_mode_eval;
16567 str[1] = NUL;
16568 rettv->vval.v_string = vim_strsave(str);
16570 /* A non-zero number or non-empty string argument: reset mode. */
16571 if ((argvars[0].v_type == VAR_NUMBER
16572 && argvars[0].vval.v_number != 0)
16573 || (argvars[0].v_type == VAR_STRING
16574 && *get_tv_string(&argvars[0]) != NUL))
16575 curbuf->b_visual_mode_eval = NUL;
16576 #else
16577 rettv->vval.v_number = 0; /* return anything, it won't work anyway */
16578 #endif
16582 * "winbufnr(nr)" function
16584 static void
16585 f_winbufnr(argvars, rettv)
16586 typval_T *argvars;
16587 typval_T *rettv;
16589 win_T *wp;
16591 wp = find_win_by_nr(&argvars[0], NULL);
16592 if (wp == NULL)
16593 rettv->vval.v_number = -1;
16594 else
16595 rettv->vval.v_number = wp->w_buffer->b_fnum;
16599 * "wincol()" function
16601 /*ARGSUSED*/
16602 static void
16603 f_wincol(argvars, rettv)
16604 typval_T *argvars;
16605 typval_T *rettv;
16607 validate_cursor();
16608 rettv->vval.v_number = curwin->w_wcol + 1;
16612 * "winheight(nr)" function
16614 static void
16615 f_winheight(argvars, rettv)
16616 typval_T *argvars;
16617 typval_T *rettv;
16619 win_T *wp;
16621 wp = find_win_by_nr(&argvars[0], NULL);
16622 if (wp == NULL)
16623 rettv->vval.v_number = -1;
16624 else
16625 rettv->vval.v_number = wp->w_height;
16629 * "winline()" function
16631 /*ARGSUSED*/
16632 static void
16633 f_winline(argvars, rettv)
16634 typval_T *argvars;
16635 typval_T *rettv;
16637 validate_cursor();
16638 rettv->vval.v_number = curwin->w_wrow + 1;
16642 * "winnr()" function
16644 /* ARGSUSED */
16645 static void
16646 f_winnr(argvars, rettv)
16647 typval_T *argvars;
16648 typval_T *rettv;
16650 int nr = 1;
16652 #ifdef FEAT_WINDOWS
16653 nr = get_winnr(curtab, &argvars[0]);
16654 #endif
16655 rettv->vval.v_number = nr;
16659 * "winrestcmd()" function
16661 /* ARGSUSED */
16662 static void
16663 f_winrestcmd(argvars, rettv)
16664 typval_T *argvars;
16665 typval_T *rettv;
16667 #ifdef FEAT_WINDOWS
16668 win_T *wp;
16669 int winnr = 1;
16670 garray_T ga;
16671 char_u buf[50];
16673 ga_init2(&ga, (int)sizeof(char), 70);
16674 for (wp = firstwin; wp != NULL; wp = wp->w_next)
16676 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
16677 ga_concat(&ga, buf);
16678 # ifdef FEAT_VERTSPLIT
16679 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
16680 ga_concat(&ga, buf);
16681 # endif
16682 ++winnr;
16684 ga_append(&ga, NUL);
16686 rettv->vval.v_string = ga.ga_data;
16687 #else
16688 rettv->vval.v_string = NULL;
16689 #endif
16690 rettv->v_type = VAR_STRING;
16694 * "winrestview()" function
16696 /* ARGSUSED */
16697 static void
16698 f_winrestview(argvars, rettv)
16699 typval_T *argvars;
16700 typval_T *rettv;
16702 dict_T *dict;
16704 if (argvars[0].v_type != VAR_DICT
16705 || (dict = argvars[0].vval.v_dict) == NULL)
16706 EMSG(_(e_invarg));
16707 else
16709 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
16710 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
16711 #ifdef FEAT_VIRTUALEDIT
16712 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
16713 #endif
16714 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
16715 curwin->w_set_curswant = FALSE;
16717 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
16718 #ifdef FEAT_DIFF
16719 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
16720 #endif
16721 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
16722 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
16724 check_cursor();
16725 changed_cline_bef_curs();
16726 invalidate_botline();
16727 redraw_later(VALID);
16729 if (curwin->w_topline == 0)
16730 curwin->w_topline = 1;
16731 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
16732 curwin->w_topline = curbuf->b_ml.ml_line_count;
16733 #ifdef FEAT_DIFF
16734 check_topfill(curwin, TRUE);
16735 #endif
16740 * "winsaveview()" function
16742 /* ARGSUSED */
16743 static void
16744 f_winsaveview(argvars, rettv)
16745 typval_T *argvars;
16746 typval_T *rettv;
16748 dict_T *dict;
16750 dict = dict_alloc();
16751 if (dict == NULL)
16752 return;
16753 rettv->v_type = VAR_DICT;
16754 rettv->vval.v_dict = dict;
16755 ++dict->dv_refcount;
16757 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
16758 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
16759 #ifdef FEAT_VIRTUALEDIT
16760 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
16761 #endif
16762 update_curswant();
16763 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
16765 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
16766 #ifdef FEAT_DIFF
16767 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
16768 #endif
16769 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
16770 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
16774 * "winwidth(nr)" function
16776 static void
16777 f_winwidth(argvars, rettv)
16778 typval_T *argvars;
16779 typval_T *rettv;
16781 win_T *wp;
16783 wp = find_win_by_nr(&argvars[0], NULL);
16784 if (wp == NULL)
16785 rettv->vval.v_number = -1;
16786 else
16787 #ifdef FEAT_VERTSPLIT
16788 rettv->vval.v_number = wp->w_width;
16789 #else
16790 rettv->vval.v_number = Columns;
16791 #endif
16795 * "writefile()" function
16797 static void
16798 f_writefile(argvars, rettv)
16799 typval_T *argvars;
16800 typval_T *rettv;
16802 int binary = FALSE;
16803 char_u *fname;
16804 FILE *fd;
16805 listitem_T *li;
16806 char_u *s;
16807 int ret = 0;
16808 int c;
16810 if (check_restricted() || check_secure())
16811 return;
16813 if (argvars[0].v_type != VAR_LIST)
16815 EMSG2(_(e_listarg), "writefile()");
16816 return;
16818 if (argvars[0].vval.v_list == NULL)
16819 return;
16821 if (argvars[2].v_type != VAR_UNKNOWN
16822 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
16823 binary = TRUE;
16825 /* Always open the file in binary mode, library functions have a mind of
16826 * their own about CR-LF conversion. */
16827 fname = get_tv_string(&argvars[1]);
16828 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
16830 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
16831 ret = -1;
16833 else
16835 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
16836 li = li->li_next)
16838 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
16840 if (*s == '\n')
16841 c = putc(NUL, fd);
16842 else
16843 c = putc(*s, fd);
16844 if (c == EOF)
16846 ret = -1;
16847 break;
16850 if (!binary || li->li_next != NULL)
16851 if (putc('\n', fd) == EOF)
16853 ret = -1;
16854 break;
16856 if (ret < 0)
16858 EMSG(_(e_write));
16859 break;
16862 fclose(fd);
16865 rettv->vval.v_number = ret;
16869 * Translate a String variable into a position.
16870 * Returns NULL when there is an error.
16872 static pos_T *
16873 var2fpos(varp, dollar_lnum, fnum)
16874 typval_T *varp;
16875 int dollar_lnum; /* TRUE when $ is last line */
16876 int *fnum; /* set to fnum for '0, 'A, etc. */
16878 char_u *name;
16879 static pos_T pos;
16880 pos_T *pp;
16882 /* Argument can be [lnum, col, coladd]. */
16883 if (varp->v_type == VAR_LIST)
16885 list_T *l;
16886 int len;
16887 int error = FALSE;
16888 listitem_T *li;
16890 l = varp->vval.v_list;
16891 if (l == NULL)
16892 return NULL;
16894 /* Get the line number */
16895 pos.lnum = list_find_nr(l, 0L, &error);
16896 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
16897 return NULL; /* invalid line number */
16899 /* Get the column number */
16900 pos.col = list_find_nr(l, 1L, &error);
16901 if (error)
16902 return NULL;
16903 len = (long)STRLEN(ml_get(pos.lnum));
16905 /* We accept "$" for the column number: last column. */
16906 li = list_find(l, 1L);
16907 if (li != NULL && li->li_tv.v_type == VAR_STRING
16908 && li->li_tv.vval.v_string != NULL
16909 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
16910 pos.col = len + 1;
16912 /* Accept a position up to the NUL after the line. */
16913 if (pos.col == 0 || (int)pos.col > len + 1)
16914 return NULL; /* invalid column number */
16915 --pos.col;
16917 #ifdef FEAT_VIRTUALEDIT
16918 /* Get the virtual offset. Defaults to zero. */
16919 pos.coladd = list_find_nr(l, 2L, &error);
16920 if (error)
16921 pos.coladd = 0;
16922 #endif
16924 return &pos;
16927 name = get_tv_string_chk(varp);
16928 if (name == NULL)
16929 return NULL;
16930 if (name[0] == '.') /* cursor */
16931 return &curwin->w_cursor;
16932 #ifdef FEAT_VISUAL
16933 if (name[0] == 'v' && name[1] == NUL) /* Visual start */
16935 if (VIsual_active)
16936 return &VIsual;
16937 return &curwin->w_cursor;
16939 #endif
16940 if (name[0] == '\'') /* mark */
16942 pp = getmark_fnum(name[1], FALSE, fnum);
16943 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
16944 return NULL;
16945 return pp;
16948 #ifdef FEAT_VIRTUALEDIT
16949 pos.coladd = 0;
16950 #endif
16952 if (name[0] == 'w' && dollar_lnum)
16954 pos.col = 0;
16955 if (name[1] == '0') /* "w0": first visible line */
16957 update_topline();
16958 pos.lnum = curwin->w_topline;
16959 return &pos;
16961 else if (name[1] == '$') /* "w$": last visible line */
16963 validate_botline();
16964 pos.lnum = curwin->w_botline - 1;
16965 return &pos;
16968 else if (name[0] == '$') /* last column or line */
16970 if (dollar_lnum)
16972 pos.lnum = curbuf->b_ml.ml_line_count;
16973 pos.col = 0;
16975 else
16977 pos.lnum = curwin->w_cursor.lnum;
16978 pos.col = (colnr_T)STRLEN(ml_get_curline());
16980 return &pos;
16982 return NULL;
16986 * Convert list in "arg" into a position and optional file number.
16987 * When "fnump" is NULL there is no file number, only 3 items.
16988 * Note that the column is passed on as-is, the caller may want to decrement
16989 * it to use 1 for the first column.
16990 * Return FAIL when conversion is not possible, doesn't check the position for
16991 * validity.
16993 static int
16994 list2fpos(arg, posp, fnump)
16995 typval_T *arg;
16996 pos_T *posp;
16997 int *fnump;
16999 list_T *l = arg->vval.v_list;
17000 long i = 0;
17001 long n;
17003 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
17004 * when "fnump" isn't NULL and "coladd" is optional. */
17005 if (arg->v_type != VAR_LIST
17006 || l == NULL
17007 || l->lv_len < (fnump == NULL ? 2 : 3)
17008 || l->lv_len > (fnump == NULL ? 3 : 4))
17009 return FAIL;
17011 if (fnump != NULL)
17013 n = list_find_nr(l, i++, NULL); /* fnum */
17014 if (n < 0)
17015 return FAIL;
17016 if (n == 0)
17017 n = curbuf->b_fnum; /* current buffer */
17018 *fnump = n;
17021 n = list_find_nr(l, i++, NULL); /* lnum */
17022 if (n < 0)
17023 return FAIL;
17024 posp->lnum = n;
17026 n = list_find_nr(l, i++, NULL); /* col */
17027 if (n < 0)
17028 return FAIL;
17029 posp->col = n;
17031 #ifdef FEAT_VIRTUALEDIT
17032 n = list_find_nr(l, i, NULL);
17033 if (n < 0)
17034 posp->coladd = 0;
17035 else
17036 posp->coladd = n;
17037 #endif
17039 return OK;
17043 * Get the length of an environment variable name.
17044 * Advance "arg" to the first character after the name.
17045 * Return 0 for error.
17047 static int
17048 get_env_len(arg)
17049 char_u **arg;
17051 char_u *p;
17052 int len;
17054 for (p = *arg; vim_isIDc(*p); ++p)
17056 if (p == *arg) /* no name found */
17057 return 0;
17059 len = (int)(p - *arg);
17060 *arg = p;
17061 return len;
17065 * Get the length of the name of a function or internal variable.
17066 * "arg" is advanced to the first non-white character after the name.
17067 * Return 0 if something is wrong.
17069 static int
17070 get_id_len(arg)
17071 char_u **arg;
17073 char_u *p;
17074 int len;
17076 /* Find the end of the name. */
17077 for (p = *arg; eval_isnamec(*p); ++p)
17079 if (p == *arg) /* no name found */
17080 return 0;
17082 len = (int)(p - *arg);
17083 *arg = skipwhite(p);
17085 return len;
17089 * Get the length of the name of a variable or function.
17090 * Only the name is recognized, does not handle ".key" or "[idx]".
17091 * "arg" is advanced to the first non-white character after the name.
17092 * Return -1 if curly braces expansion failed.
17093 * Return 0 if something else is wrong.
17094 * If the name contains 'magic' {}'s, expand them and return the
17095 * expanded name in an allocated string via 'alias' - caller must free.
17097 static int
17098 get_name_len(arg, alias, evaluate, verbose)
17099 char_u **arg;
17100 char_u **alias;
17101 int evaluate;
17102 int verbose;
17104 int len;
17105 char_u *p;
17106 char_u *expr_start;
17107 char_u *expr_end;
17109 *alias = NULL; /* default to no alias */
17111 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
17112 && (*arg)[2] == (int)KE_SNR)
17114 /* hard coded <SNR>, already translated */
17115 *arg += 3;
17116 return get_id_len(arg) + 3;
17118 len = eval_fname_script(*arg);
17119 if (len > 0)
17121 /* literal "<SID>", "s:" or "<SNR>" */
17122 *arg += len;
17126 * Find the end of the name; check for {} construction.
17128 p = find_name_end(*arg, &expr_start, &expr_end,
17129 len > 0 ? 0 : FNE_CHECK_START);
17130 if (expr_start != NULL)
17132 char_u *temp_string;
17134 if (!evaluate)
17136 len += (int)(p - *arg);
17137 *arg = skipwhite(p);
17138 return len;
17142 * Include any <SID> etc in the expanded string:
17143 * Thus the -len here.
17145 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
17146 if (temp_string == NULL)
17147 return -1;
17148 *alias = temp_string;
17149 *arg = skipwhite(p);
17150 return (int)STRLEN(temp_string);
17153 len += get_id_len(arg);
17154 if (len == 0 && verbose)
17155 EMSG2(_(e_invexpr2), *arg);
17157 return len;
17161 * Find the end of a variable or function name, taking care of magic braces.
17162 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
17163 * start and end of the first magic braces item.
17164 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
17165 * Return a pointer to just after the name. Equal to "arg" if there is no
17166 * valid name.
17168 static char_u *
17169 find_name_end(arg, expr_start, expr_end, flags)
17170 char_u *arg;
17171 char_u **expr_start;
17172 char_u **expr_end;
17173 int flags;
17175 int mb_nest = 0;
17176 int br_nest = 0;
17177 char_u *p;
17179 if (expr_start != NULL)
17181 *expr_start = NULL;
17182 *expr_end = NULL;
17185 /* Quick check for valid starting character. */
17186 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
17187 return arg;
17189 for (p = arg; *p != NUL
17190 && (eval_isnamec(*p)
17191 || *p == '{'
17192 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
17193 || mb_nest != 0
17194 || br_nest != 0); mb_ptr_adv(p))
17196 if (*p == '\'')
17198 /* skip over 'string' to avoid counting [ and ] inside it. */
17199 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
17201 if (*p == NUL)
17202 break;
17204 else if (*p == '"')
17206 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
17207 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
17208 if (*p == '\\' && p[1] != NUL)
17209 ++p;
17210 if (*p == NUL)
17211 break;
17214 if (mb_nest == 0)
17216 if (*p == '[')
17217 ++br_nest;
17218 else if (*p == ']')
17219 --br_nest;
17222 if (br_nest == 0)
17224 if (*p == '{')
17226 mb_nest++;
17227 if (expr_start != NULL && *expr_start == NULL)
17228 *expr_start = p;
17230 else if (*p == '}')
17232 mb_nest--;
17233 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
17234 *expr_end = p;
17239 return p;
17243 * Expands out the 'magic' {}'s in a variable/function name.
17244 * Note that this can call itself recursively, to deal with
17245 * constructs like foo{bar}{baz}{bam}
17246 * The four pointer arguments point to "foo{expre}ss{ion}bar"
17247 * "in_start" ^
17248 * "expr_start" ^
17249 * "expr_end" ^
17250 * "in_end" ^
17252 * Returns a new allocated string, which the caller must free.
17253 * Returns NULL for failure.
17255 static char_u *
17256 make_expanded_name(in_start, expr_start, expr_end, in_end)
17257 char_u *in_start;
17258 char_u *expr_start;
17259 char_u *expr_end;
17260 char_u *in_end;
17262 char_u c1;
17263 char_u *retval = NULL;
17264 char_u *temp_result;
17265 char_u *nextcmd = NULL;
17267 if (expr_end == NULL || in_end == NULL)
17268 return NULL;
17269 *expr_start = NUL;
17270 *expr_end = NUL;
17271 c1 = *in_end;
17272 *in_end = NUL;
17274 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
17275 if (temp_result != NULL && nextcmd == NULL)
17277 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
17278 + (in_end - expr_end) + 1));
17279 if (retval != NULL)
17281 STRCPY(retval, in_start);
17282 STRCAT(retval, temp_result);
17283 STRCAT(retval, expr_end + 1);
17286 vim_free(temp_result);
17288 *in_end = c1; /* put char back for error messages */
17289 *expr_start = '{';
17290 *expr_end = '}';
17292 if (retval != NULL)
17294 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
17295 if (expr_start != NULL)
17297 /* Further expansion! */
17298 temp_result = make_expanded_name(retval, expr_start,
17299 expr_end, temp_result);
17300 vim_free(retval);
17301 retval = temp_result;
17305 return retval;
17309 * Return TRUE if character "c" can be used in a variable or function name.
17310 * Does not include '{' or '}' for magic braces.
17312 static int
17313 eval_isnamec(c)
17314 int c;
17316 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
17320 * Return TRUE if character "c" can be used as the first character in a
17321 * variable or function name (excluding '{' and '}').
17323 static int
17324 eval_isnamec1(c)
17325 int c;
17327 return (ASCII_ISALPHA(c) || c == '_');
17331 * Set number v: variable to "val".
17333 void
17334 set_vim_var_nr(idx, val)
17335 int idx;
17336 long val;
17338 vimvars[idx].vv_nr = val;
17342 * Get number v: variable value.
17344 long
17345 get_vim_var_nr(idx)
17346 int idx;
17348 return vimvars[idx].vv_nr;
17351 #if defined(FEAT_AUTOCMD) || defined(PROTO)
17353 * Get string v: variable value. Uses a static buffer, can only be used once.
17355 char_u *
17356 get_vim_var_str(idx)
17357 int idx;
17359 return get_tv_string(&vimvars[idx].vv_tv);
17361 #endif
17364 * Set v:count, v:count1 and v:prevcount.
17366 void
17367 set_vcount(count, count1)
17368 long count;
17369 long count1;
17371 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
17372 vimvars[VV_COUNT].vv_nr = count;
17373 vimvars[VV_COUNT1].vv_nr = count1;
17377 * Set string v: variable to a copy of "val".
17379 void
17380 set_vim_var_string(idx, val, len)
17381 int idx;
17382 char_u *val;
17383 int len; /* length of "val" to use or -1 (whole string) */
17385 /* Need to do this (at least) once, since we can't initialize a union.
17386 * Will always be invoked when "v:progname" is set. */
17387 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
17389 vim_free(vimvars[idx].vv_str);
17390 if (val == NULL)
17391 vimvars[idx].vv_str = NULL;
17392 else if (len == -1)
17393 vimvars[idx].vv_str = vim_strsave(val);
17394 else
17395 vimvars[idx].vv_str = vim_strnsave(val, len);
17399 * Set v:register if needed.
17401 void
17402 set_reg_var(c)
17403 int c;
17405 char_u regname;
17407 if (c == 0 || c == ' ')
17408 regname = '"';
17409 else
17410 regname = c;
17411 /* Avoid free/alloc when the value is already right. */
17412 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
17413 set_vim_var_string(VV_REG, &regname, 1);
17417 * Get or set v:exception. If "oldval" == NULL, return the current value.
17418 * Otherwise, restore the value to "oldval" and return NULL.
17419 * Must always be called in pairs to save and restore v:exception! Does not
17420 * take care of memory allocations.
17422 char_u *
17423 v_exception(oldval)
17424 char_u *oldval;
17426 if (oldval == NULL)
17427 return vimvars[VV_EXCEPTION].vv_str;
17429 vimvars[VV_EXCEPTION].vv_str = oldval;
17430 return NULL;
17434 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
17435 * Otherwise, restore the value to "oldval" and return NULL.
17436 * Must always be called in pairs to save and restore v:throwpoint! Does not
17437 * take care of memory allocations.
17439 char_u *
17440 v_throwpoint(oldval)
17441 char_u *oldval;
17443 if (oldval == NULL)
17444 return vimvars[VV_THROWPOINT].vv_str;
17446 vimvars[VV_THROWPOINT].vv_str = oldval;
17447 return NULL;
17450 #if defined(FEAT_AUTOCMD) || defined(PROTO)
17452 * Set v:cmdarg.
17453 * If "eap" != NULL, use "eap" to generate the value and return the old value.
17454 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
17455 * Must always be called in pairs!
17457 char_u *
17458 set_cmdarg(eap, oldarg)
17459 exarg_T *eap;
17460 char_u *oldarg;
17462 char_u *oldval;
17463 char_u *newval;
17464 unsigned len;
17466 oldval = vimvars[VV_CMDARG].vv_str;
17467 if (eap == NULL)
17469 vim_free(oldval);
17470 vimvars[VV_CMDARG].vv_str = oldarg;
17471 return NULL;
17474 if (eap->force_bin == FORCE_BIN)
17475 len = 6;
17476 else if (eap->force_bin == FORCE_NOBIN)
17477 len = 8;
17478 else
17479 len = 0;
17481 if (eap->read_edit)
17482 len += 7;
17484 if (eap->force_ff != 0)
17485 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
17486 # ifdef FEAT_MBYTE
17487 if (eap->force_enc != 0)
17488 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
17489 if (eap->bad_char != 0)
17490 len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
17491 # endif
17493 newval = alloc(len + 1);
17494 if (newval == NULL)
17495 return NULL;
17497 if (eap->force_bin == FORCE_BIN)
17498 sprintf((char *)newval, " ++bin");
17499 else if (eap->force_bin == FORCE_NOBIN)
17500 sprintf((char *)newval, " ++nobin");
17501 else
17502 *newval = NUL;
17504 if (eap->read_edit)
17505 STRCAT(newval, " ++edit");
17507 if (eap->force_ff != 0)
17508 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
17509 eap->cmd + eap->force_ff);
17510 # ifdef FEAT_MBYTE
17511 if (eap->force_enc != 0)
17512 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
17513 eap->cmd + eap->force_enc);
17514 if (eap->bad_char != 0)
17515 sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
17516 eap->cmd + eap->bad_char);
17517 # endif
17518 vimvars[VV_CMDARG].vv_str = newval;
17519 return oldval;
17521 #endif
17524 * Get the value of internal variable "name".
17525 * Return OK or FAIL.
17527 static int
17528 get_var_tv(name, len, rettv, verbose)
17529 char_u *name;
17530 int len; /* length of "name" */
17531 typval_T *rettv; /* NULL when only checking existence */
17532 int verbose; /* may give error message */
17534 int ret = OK;
17535 typval_T *tv = NULL;
17536 typval_T atv;
17537 dictitem_T *v;
17538 int cc;
17540 /* truncate the name, so that we can use strcmp() */
17541 cc = name[len];
17542 name[len] = NUL;
17545 * Check for "b:changedtick".
17547 if (STRCMP(name, "b:changedtick") == 0)
17549 atv.v_type = VAR_NUMBER;
17550 atv.vval.v_number = curbuf->b_changedtick;
17551 tv = &atv;
17555 * Check for user-defined variables.
17557 else
17559 v = find_var(name, NULL);
17560 if (v != NULL)
17561 tv = &v->di_tv;
17564 if (tv == NULL)
17566 if (rettv != NULL && verbose)
17567 EMSG2(_(e_undefvar), name);
17568 ret = FAIL;
17570 else if (rettv != NULL)
17571 copy_tv(tv, rettv);
17573 name[len] = cc;
17575 return ret;
17579 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
17580 * Also handle function call with Funcref variable: func(expr)
17581 * Can all be combined: dict.func(expr)[idx]['func'](expr)
17583 static int
17584 handle_subscript(arg, rettv, evaluate, verbose)
17585 char_u **arg;
17586 typval_T *rettv;
17587 int evaluate; /* do more than finding the end */
17588 int verbose; /* give error messages */
17590 int ret = OK;
17591 dict_T *selfdict = NULL;
17592 char_u *s;
17593 int len;
17594 typval_T functv;
17596 while (ret == OK
17597 && (**arg == '['
17598 || (**arg == '.' && rettv->v_type == VAR_DICT)
17599 || (**arg == '(' && rettv->v_type == VAR_FUNC))
17600 && !vim_iswhite(*(*arg - 1)))
17602 if (**arg == '(')
17604 /* need to copy the funcref so that we can clear rettv */
17605 functv = *rettv;
17606 rettv->v_type = VAR_UNKNOWN;
17608 /* Invoke the function. Recursive! */
17609 s = functv.vval.v_string;
17610 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
17611 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
17612 &len, evaluate, selfdict);
17614 /* Clear the funcref afterwards, so that deleting it while
17615 * evaluating the arguments is possible (see test55). */
17616 clear_tv(&functv);
17618 /* Stop the expression evaluation when immediately aborting on
17619 * error, or when an interrupt occurred or an exception was thrown
17620 * but not caught. */
17621 if (aborting())
17623 if (ret == OK)
17624 clear_tv(rettv);
17625 ret = FAIL;
17627 dict_unref(selfdict);
17628 selfdict = NULL;
17630 else /* **arg == '[' || **arg == '.' */
17632 dict_unref(selfdict);
17633 if (rettv->v_type == VAR_DICT)
17635 selfdict = rettv->vval.v_dict;
17636 if (selfdict != NULL)
17637 ++selfdict->dv_refcount;
17639 else
17640 selfdict = NULL;
17641 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
17643 clear_tv(rettv);
17644 ret = FAIL;
17648 dict_unref(selfdict);
17649 return ret;
17653 * Allocate memory for a variable type-value, and make it emtpy (0 or NULL
17654 * value).
17656 static typval_T *
17657 alloc_tv()
17659 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
17663 * Allocate memory for a variable type-value, and assign a string to it.
17664 * The string "s" must have been allocated, it is consumed.
17665 * Return NULL for out of memory, the variable otherwise.
17667 static typval_T *
17668 alloc_string_tv(s)
17669 char_u *s;
17671 typval_T *rettv;
17673 rettv = alloc_tv();
17674 if (rettv != NULL)
17676 rettv->v_type = VAR_STRING;
17677 rettv->vval.v_string = s;
17679 else
17680 vim_free(s);
17681 return rettv;
17685 * Free the memory for a variable type-value.
17687 void
17688 free_tv(varp)
17689 typval_T *varp;
17691 if (varp != NULL)
17693 switch (varp->v_type)
17695 case VAR_FUNC:
17696 func_unref(varp->vval.v_string);
17697 /*FALLTHROUGH*/
17698 case VAR_STRING:
17699 vim_free(varp->vval.v_string);
17700 break;
17701 case VAR_LIST:
17702 list_unref(varp->vval.v_list);
17703 break;
17704 case VAR_DICT:
17705 dict_unref(varp->vval.v_dict);
17706 break;
17707 case VAR_NUMBER:
17708 case VAR_UNKNOWN:
17709 break;
17710 default:
17711 EMSG2(_(e_intern2), "free_tv()");
17712 break;
17714 vim_free(varp);
17719 * Free the memory for a variable value and set the value to NULL or 0.
17721 void
17722 clear_tv(varp)
17723 typval_T *varp;
17725 if (varp != NULL)
17727 switch (varp->v_type)
17729 case VAR_FUNC:
17730 func_unref(varp->vval.v_string);
17731 /*FALLTHROUGH*/
17732 case VAR_STRING:
17733 vim_free(varp->vval.v_string);
17734 varp->vval.v_string = NULL;
17735 break;
17736 case VAR_LIST:
17737 list_unref(varp->vval.v_list);
17738 varp->vval.v_list = NULL;
17739 break;
17740 case VAR_DICT:
17741 dict_unref(varp->vval.v_dict);
17742 varp->vval.v_dict = NULL;
17743 break;
17744 case VAR_NUMBER:
17745 varp->vval.v_number = 0;
17746 break;
17747 case VAR_UNKNOWN:
17748 break;
17749 default:
17750 EMSG2(_(e_intern2), "clear_tv()");
17752 varp->v_lock = 0;
17757 * Set the value of a variable to NULL without freeing items.
17759 static void
17760 init_tv(varp)
17761 typval_T *varp;
17763 if (varp != NULL)
17764 vim_memset(varp, 0, sizeof(typval_T));
17768 * Get the number value of a variable.
17769 * If it is a String variable, uses vim_str2nr().
17770 * For incompatible types, return 0.
17771 * get_tv_number_chk() is similar to get_tv_number(), but informs the
17772 * caller of incompatible types: it sets *denote to TRUE if "denote"
17773 * is not NULL or returns -1 otherwise.
17775 static long
17776 get_tv_number(varp)
17777 typval_T *varp;
17779 int error = FALSE;
17781 return get_tv_number_chk(varp, &error); /* return 0L on error */
17784 long
17785 get_tv_number_chk(varp, denote)
17786 typval_T *varp;
17787 int *denote;
17789 long n = 0L;
17791 switch (varp->v_type)
17793 case VAR_NUMBER:
17794 return (long)(varp->vval.v_number);
17795 case VAR_FUNC:
17796 EMSG(_("E703: Using a Funcref as a number"));
17797 break;
17798 case VAR_STRING:
17799 if (varp->vval.v_string != NULL)
17800 vim_str2nr(varp->vval.v_string, NULL, NULL,
17801 TRUE, TRUE, &n, NULL);
17802 return n;
17803 case VAR_LIST:
17804 EMSG(_("E745: Using a List as a number"));
17805 break;
17806 case VAR_DICT:
17807 EMSG(_("E728: Using a Dictionary as a number"));
17808 break;
17809 default:
17810 EMSG2(_(e_intern2), "get_tv_number()");
17811 break;
17813 if (denote == NULL) /* useful for values that must be unsigned */
17814 n = -1;
17815 else
17816 *denote = TRUE;
17817 return n;
17821 * Get the lnum from the first argument.
17822 * Also accepts ".", "$", etc., but that only works for the current buffer.
17823 * Returns -1 on error.
17825 static linenr_T
17826 get_tv_lnum(argvars)
17827 typval_T *argvars;
17829 typval_T rettv;
17830 linenr_T lnum;
17832 lnum = get_tv_number_chk(&argvars[0], NULL);
17833 if (lnum == 0) /* no valid number, try using line() */
17835 rettv.v_type = VAR_NUMBER;
17836 f_line(argvars, &rettv);
17837 lnum = rettv.vval.v_number;
17838 clear_tv(&rettv);
17840 return lnum;
17844 * Get the lnum from the first argument.
17845 * Also accepts "$", then "buf" is used.
17846 * Returns 0 on error.
17848 static linenr_T
17849 get_tv_lnum_buf(argvars, buf)
17850 typval_T *argvars;
17851 buf_T *buf;
17853 if (argvars[0].v_type == VAR_STRING
17854 && argvars[0].vval.v_string != NULL
17855 && argvars[0].vval.v_string[0] == '$'
17856 && buf != NULL)
17857 return buf->b_ml.ml_line_count;
17858 return get_tv_number_chk(&argvars[0], NULL);
17862 * Get the string value of a variable.
17863 * If it is a Number variable, the number is converted into a string.
17864 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
17865 * get_tv_string_buf() uses a given buffer.
17866 * If the String variable has never been set, return an empty string.
17867 * Never returns NULL;
17868 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
17869 * NULL on error.
17871 static char_u *
17872 get_tv_string(varp)
17873 typval_T *varp;
17875 static char_u mybuf[NUMBUFLEN];
17877 return get_tv_string_buf(varp, mybuf);
17880 static char_u *
17881 get_tv_string_buf(varp, buf)
17882 typval_T *varp;
17883 char_u *buf;
17885 char_u *res = get_tv_string_buf_chk(varp, buf);
17887 return res != NULL ? res : (char_u *)"";
17890 char_u *
17891 get_tv_string_chk(varp)
17892 typval_T *varp;
17894 static char_u mybuf[NUMBUFLEN];
17896 return get_tv_string_buf_chk(varp, mybuf);
17899 static char_u *
17900 get_tv_string_buf_chk(varp, buf)
17901 typval_T *varp;
17902 char_u *buf;
17904 switch (varp->v_type)
17906 case VAR_NUMBER:
17907 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
17908 return buf;
17909 case VAR_FUNC:
17910 EMSG(_("E729: using Funcref as a String"));
17911 break;
17912 case VAR_LIST:
17913 EMSG(_("E730: using List as a String"));
17914 break;
17915 case VAR_DICT:
17916 EMSG(_("E731: using Dictionary as a String"));
17917 break;
17918 case VAR_STRING:
17919 if (varp->vval.v_string != NULL)
17920 return varp->vval.v_string;
17921 return (char_u *)"";
17922 default:
17923 EMSG2(_(e_intern2), "get_tv_string_buf()");
17924 break;
17926 return NULL;
17930 * Find variable "name" in the list of variables.
17931 * Return a pointer to it if found, NULL if not found.
17932 * Careful: "a:0" variables don't have a name.
17933 * When "htp" is not NULL we are writing to the variable, set "htp" to the
17934 * hashtab_T used.
17936 static dictitem_T *
17937 find_var(name, htp)
17938 char_u *name;
17939 hashtab_T **htp;
17941 char_u *varname;
17942 hashtab_T *ht;
17944 ht = find_var_ht(name, &varname);
17945 if (htp != NULL)
17946 *htp = ht;
17947 if (ht == NULL)
17948 return NULL;
17949 return find_var_in_ht(ht, varname, htp != NULL);
17953 * Find variable "varname" in hashtab "ht".
17954 * Returns NULL if not found.
17956 static dictitem_T *
17957 find_var_in_ht(ht, varname, writing)
17958 hashtab_T *ht;
17959 char_u *varname;
17960 int writing;
17962 hashitem_T *hi;
17964 if (*varname == NUL)
17966 /* Must be something like "s:", otherwise "ht" would be NULL. */
17967 switch (varname[-2])
17969 case 's': return &SCRIPT_SV(current_SID).sv_var;
17970 case 'g': return &globvars_var;
17971 case 'v': return &vimvars_var;
17972 case 'b': return &curbuf->b_bufvar;
17973 case 'w': return &curwin->w_winvar;
17974 #ifdef FEAT_WINDOWS
17975 case 't': return &curtab->tp_winvar;
17976 #endif
17977 case 'l': return current_funccal == NULL
17978 ? NULL : &current_funccal->l_vars_var;
17979 case 'a': return current_funccal == NULL
17980 ? NULL : &current_funccal->l_avars_var;
17982 return NULL;
17985 hi = hash_find(ht, varname);
17986 if (HASHITEM_EMPTY(hi))
17988 /* For global variables we may try auto-loading the script. If it
17989 * worked find the variable again. Don't auto-load a script if it was
17990 * loaded already, otherwise it would be loaded every time when
17991 * checking if a function name is a Funcref variable. */
17992 if (ht == &globvarht && !writing
17993 && script_autoload(varname, FALSE) && !aborting())
17994 hi = hash_find(ht, varname);
17995 if (HASHITEM_EMPTY(hi))
17996 return NULL;
17998 return HI2DI(hi);
18002 * Find the hashtab used for a variable name.
18003 * Set "varname" to the start of name without ':'.
18005 static hashtab_T *
18006 find_var_ht(name, varname)
18007 char_u *name;
18008 char_u **varname;
18010 hashitem_T *hi;
18012 if (name[1] != ':')
18014 /* The name must not start with a colon or #. */
18015 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
18016 return NULL;
18017 *varname = name;
18019 /* "version" is "v:version" in all scopes */
18020 hi = hash_find(&compat_hashtab, name);
18021 if (!HASHITEM_EMPTY(hi))
18022 return &compat_hashtab;
18024 if (current_funccal == NULL)
18025 return &globvarht; /* global variable */
18026 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
18028 *varname = name + 2;
18029 if (*name == 'g') /* global variable */
18030 return &globvarht;
18031 /* There must be no ':' or '#' in the rest of the name, unless g: is used
18033 if (vim_strchr(name + 2, ':') != NULL
18034 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
18035 return NULL;
18036 if (*name == 'b') /* buffer variable */
18037 return &curbuf->b_vars.dv_hashtab;
18038 if (*name == 'w') /* window variable */
18039 return &curwin->w_vars.dv_hashtab;
18040 #ifdef FEAT_WINDOWS
18041 if (*name == 't') /* tab page variable */
18042 return &curtab->tp_vars.dv_hashtab;
18043 #endif
18044 if (*name == 'v') /* v: variable */
18045 return &vimvarht;
18046 if (*name == 'a' && current_funccal != NULL) /* function argument */
18047 return &current_funccal->l_avars.dv_hashtab;
18048 if (*name == 'l' && current_funccal != NULL) /* local function variable */
18049 return &current_funccal->l_vars.dv_hashtab;
18050 if (*name == 's' /* script variable */
18051 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
18052 return &SCRIPT_VARS(current_SID);
18053 return NULL;
18057 * Get the string value of a (global/local) variable.
18058 * Returns NULL when it doesn't exist.
18060 char_u *
18061 get_var_value(name)
18062 char_u *name;
18064 dictitem_T *v;
18066 v = find_var(name, NULL);
18067 if (v == NULL)
18068 return NULL;
18069 return get_tv_string(&v->di_tv);
18073 * Allocate a new hashtab for a sourced script. It will be used while
18074 * sourcing this script and when executing functions defined in the script.
18076 void
18077 new_script_vars(id)
18078 scid_T id;
18080 int i;
18081 hashtab_T *ht;
18082 scriptvar_T *sv;
18084 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
18086 /* Re-allocating ga_data means that an ht_array pointing to
18087 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
18088 * at its init value. Also reset "v_dict", it's always the same. */
18089 for (i = 1; i <= ga_scripts.ga_len; ++i)
18091 ht = &SCRIPT_VARS(i);
18092 if (ht->ht_mask == HT_INIT_SIZE - 1)
18093 ht->ht_array = ht->ht_smallarray;
18094 sv = &SCRIPT_SV(i);
18095 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
18098 while (ga_scripts.ga_len < id)
18100 sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
18101 init_var_dict(&sv->sv_dict, &sv->sv_var);
18102 ++ga_scripts.ga_len;
18108 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
18109 * point to it.
18111 void
18112 init_var_dict(dict, dict_var)
18113 dict_T *dict;
18114 dictitem_T *dict_var;
18116 hash_init(&dict->dv_hashtab);
18117 dict->dv_refcount = 99999;
18118 dict_var->di_tv.vval.v_dict = dict;
18119 dict_var->di_tv.v_type = VAR_DICT;
18120 dict_var->di_tv.v_lock = VAR_FIXED;
18121 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
18122 dict_var->di_key[0] = NUL;
18126 * Clean up a list of internal variables.
18127 * Frees all allocated variables and the value they contain.
18128 * Clears hashtab "ht", does not free it.
18130 void
18131 vars_clear(ht)
18132 hashtab_T *ht;
18134 vars_clear_ext(ht, TRUE);
18138 * Like vars_clear(), but only free the value if "free_val" is TRUE.
18140 static void
18141 vars_clear_ext(ht, free_val)
18142 hashtab_T *ht;
18143 int free_val;
18145 int todo;
18146 hashitem_T *hi;
18147 dictitem_T *v;
18149 hash_lock(ht);
18150 todo = (int)ht->ht_used;
18151 for (hi = ht->ht_array; todo > 0; ++hi)
18153 if (!HASHITEM_EMPTY(hi))
18155 --todo;
18157 /* Free the variable. Don't remove it from the hashtab,
18158 * ht_array might change then. hash_clear() takes care of it
18159 * later. */
18160 v = HI2DI(hi);
18161 if (free_val)
18162 clear_tv(&v->di_tv);
18163 if ((v->di_flags & DI_FLAGS_FIX) == 0)
18164 vim_free(v);
18167 hash_clear(ht);
18168 ht->ht_used = 0;
18172 * Delete a variable from hashtab "ht" at item "hi".
18173 * Clear the variable value and free the dictitem.
18175 static void
18176 delete_var(ht, hi)
18177 hashtab_T *ht;
18178 hashitem_T *hi;
18180 dictitem_T *di = HI2DI(hi);
18182 hash_remove(ht, hi);
18183 clear_tv(&di->di_tv);
18184 vim_free(di);
18188 * List the value of one internal variable.
18190 static void
18191 list_one_var(v, prefix, first)
18192 dictitem_T *v;
18193 char_u *prefix;
18194 int *first;
18196 char_u *tofree;
18197 char_u *s;
18198 char_u numbuf[NUMBUFLEN];
18200 s = echo_string(&v->di_tv, &tofree, numbuf, ++current_copyID);
18201 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
18202 s == NULL ? (char_u *)"" : s, first);
18203 vim_free(tofree);
18206 static void
18207 list_one_var_a(prefix, name, type, string, first)
18208 char_u *prefix;
18209 char_u *name;
18210 int type;
18211 char_u *string;
18212 int *first; /* when TRUE clear rest of screen and set to FALSE */
18214 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
18215 msg_start();
18216 msg_puts(prefix);
18217 if (name != NULL) /* "a:" vars don't have a name stored */
18218 msg_puts(name);
18219 msg_putchar(' ');
18220 msg_advance(22);
18221 if (type == VAR_NUMBER)
18222 msg_putchar('#');
18223 else if (type == VAR_FUNC)
18224 msg_putchar('*');
18225 else if (type == VAR_LIST)
18227 msg_putchar('[');
18228 if (*string == '[')
18229 ++string;
18231 else if (type == VAR_DICT)
18233 msg_putchar('{');
18234 if (*string == '{')
18235 ++string;
18237 else
18238 msg_putchar(' ');
18240 msg_outtrans(string);
18242 if (type == VAR_FUNC)
18243 msg_puts((char_u *)"()");
18244 if (*first)
18246 msg_clr_eos();
18247 *first = FALSE;
18252 * Set variable "name" to value in "tv".
18253 * If the variable already exists, the value is updated.
18254 * Otherwise the variable is created.
18256 static void
18257 set_var(name, tv, copy)
18258 char_u *name;
18259 typval_T *tv;
18260 int copy; /* make copy of value in "tv" */
18262 dictitem_T *v;
18263 char_u *varname;
18264 hashtab_T *ht;
18265 char_u *p;
18267 if (tv->v_type == VAR_FUNC)
18269 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
18270 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
18271 ? name[2] : name[0]))
18273 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
18274 return;
18276 if (function_exists(name))
18278 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
18279 name);
18280 return;
18284 ht = find_var_ht(name, &varname);
18285 if (ht == NULL || *varname == NUL)
18287 EMSG2(_(e_illvar), name);
18288 return;
18291 v = find_var_in_ht(ht, varname, TRUE);
18292 if (v != NULL)
18294 /* existing variable, need to clear the value */
18295 if (var_check_ro(v->di_flags, name)
18296 || tv_check_lock(v->di_tv.v_lock, name))
18297 return;
18298 if (v->di_tv.v_type != tv->v_type
18299 && !((v->di_tv.v_type == VAR_STRING
18300 || v->di_tv.v_type == VAR_NUMBER)
18301 && (tv->v_type == VAR_STRING
18302 || tv->v_type == VAR_NUMBER)))
18304 EMSG2(_("E706: Variable type mismatch for: %s"), name);
18305 return;
18309 * Handle setting internal v: variables separately: we don't change
18310 * the type.
18312 if (ht == &vimvarht)
18314 if (v->di_tv.v_type == VAR_STRING)
18316 vim_free(v->di_tv.vval.v_string);
18317 if (copy || tv->v_type != VAR_STRING)
18318 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
18319 else
18321 /* Take over the string to avoid an extra alloc/free. */
18322 v->di_tv.vval.v_string = tv->vval.v_string;
18323 tv->vval.v_string = NULL;
18326 else if (v->di_tv.v_type != VAR_NUMBER)
18327 EMSG2(_(e_intern2), "set_var()");
18328 else
18329 v->di_tv.vval.v_number = get_tv_number(tv);
18330 return;
18333 clear_tv(&v->di_tv);
18335 else /* add a new variable */
18337 /* Can't add "v:" variable. */
18338 if (ht == &vimvarht)
18340 EMSG2(_(e_illvar), name);
18341 return;
18344 /* Make sure the variable name is valid. */
18345 for (p = varname; *p != NUL; ++p)
18346 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
18347 && *p != AUTOLOAD_CHAR)
18349 EMSG2(_(e_illvar), varname);
18350 return;
18353 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
18354 + STRLEN(varname)));
18355 if (v == NULL)
18356 return;
18357 STRCPY(v->di_key, varname);
18358 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
18360 vim_free(v);
18361 return;
18363 v->di_flags = 0;
18366 if (copy || tv->v_type == VAR_NUMBER)
18367 copy_tv(tv, &v->di_tv);
18368 else
18370 v->di_tv = *tv;
18371 v->di_tv.v_lock = 0;
18372 init_tv(tv);
18377 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
18378 * Also give an error message.
18380 static int
18381 var_check_ro(flags, name)
18382 int flags;
18383 char_u *name;
18385 if (flags & DI_FLAGS_RO)
18387 EMSG2(_(e_readonlyvar), name);
18388 return TRUE;
18390 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
18392 EMSG2(_(e_readonlysbx), name);
18393 return TRUE;
18395 return FALSE;
18399 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
18400 * Also give an error message.
18402 static int
18403 var_check_fixed(flags, name)
18404 int flags;
18405 char_u *name;
18407 if (flags & DI_FLAGS_FIX)
18409 EMSG2(_("E795: Cannot delete variable %s"), name);
18410 return TRUE;
18412 return FALSE;
18416 * Return TRUE if typeval "tv" is set to be locked (immutable).
18417 * Also give an error message, using "name".
18419 static int
18420 tv_check_lock(lock, name)
18421 int lock;
18422 char_u *name;
18424 if (lock & VAR_LOCKED)
18426 EMSG2(_("E741: Value is locked: %s"),
18427 name == NULL ? (char_u *)_("Unknown") : name);
18428 return TRUE;
18430 if (lock & VAR_FIXED)
18432 EMSG2(_("E742: Cannot change value of %s"),
18433 name == NULL ? (char_u *)_("Unknown") : name);
18434 return TRUE;
18436 return FALSE;
18440 * Copy the values from typval_T "from" to typval_T "to".
18441 * When needed allocates string or increases reference count.
18442 * Does not make a copy of a list or dict but copies the reference!
18444 static void
18445 copy_tv(from, to)
18446 typval_T *from;
18447 typval_T *to;
18449 to->v_type = from->v_type;
18450 to->v_lock = 0;
18451 switch (from->v_type)
18453 case VAR_NUMBER:
18454 to->vval.v_number = from->vval.v_number;
18455 break;
18456 case VAR_STRING:
18457 case VAR_FUNC:
18458 if (from->vval.v_string == NULL)
18459 to->vval.v_string = NULL;
18460 else
18462 to->vval.v_string = vim_strsave(from->vval.v_string);
18463 if (from->v_type == VAR_FUNC)
18464 func_ref(to->vval.v_string);
18466 break;
18467 case VAR_LIST:
18468 if (from->vval.v_list == NULL)
18469 to->vval.v_list = NULL;
18470 else
18472 to->vval.v_list = from->vval.v_list;
18473 ++to->vval.v_list->lv_refcount;
18475 break;
18476 case VAR_DICT:
18477 if (from->vval.v_dict == NULL)
18478 to->vval.v_dict = NULL;
18479 else
18481 to->vval.v_dict = from->vval.v_dict;
18482 ++to->vval.v_dict->dv_refcount;
18484 break;
18485 default:
18486 EMSG2(_(e_intern2), "copy_tv()");
18487 break;
18492 * Make a copy of an item.
18493 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
18494 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
18495 * reference to an already copied list/dict can be used.
18496 * Returns FAIL or OK.
18498 static int
18499 item_copy(from, to, deep, copyID)
18500 typval_T *from;
18501 typval_T *to;
18502 int deep;
18503 int copyID;
18505 static int recurse = 0;
18506 int ret = OK;
18508 if (recurse >= DICT_MAXNEST)
18510 EMSG(_("E698: variable nested too deep for making a copy"));
18511 return FAIL;
18513 ++recurse;
18515 switch (from->v_type)
18517 case VAR_NUMBER:
18518 case VAR_STRING:
18519 case VAR_FUNC:
18520 copy_tv(from, to);
18521 break;
18522 case VAR_LIST:
18523 to->v_type = VAR_LIST;
18524 to->v_lock = 0;
18525 if (from->vval.v_list == NULL)
18526 to->vval.v_list = NULL;
18527 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
18529 /* use the copy made earlier */
18530 to->vval.v_list = from->vval.v_list->lv_copylist;
18531 ++to->vval.v_list->lv_refcount;
18533 else
18534 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
18535 if (to->vval.v_list == NULL)
18536 ret = FAIL;
18537 break;
18538 case VAR_DICT:
18539 to->v_type = VAR_DICT;
18540 to->v_lock = 0;
18541 if (from->vval.v_dict == NULL)
18542 to->vval.v_dict = NULL;
18543 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
18545 /* use the copy made earlier */
18546 to->vval.v_dict = from->vval.v_dict->dv_copydict;
18547 ++to->vval.v_dict->dv_refcount;
18549 else
18550 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
18551 if (to->vval.v_dict == NULL)
18552 ret = FAIL;
18553 break;
18554 default:
18555 EMSG2(_(e_intern2), "item_copy()");
18556 ret = FAIL;
18558 --recurse;
18559 return ret;
18563 * ":echo expr1 ..." print each argument separated with a space, add a
18564 * newline at the end.
18565 * ":echon expr1 ..." print each argument plain.
18567 void
18568 ex_echo(eap)
18569 exarg_T *eap;
18571 char_u *arg = eap->arg;
18572 typval_T rettv;
18573 char_u *tofree;
18574 char_u *p;
18575 int needclr = TRUE;
18576 int atstart = TRUE;
18577 char_u numbuf[NUMBUFLEN];
18579 if (eap->skip)
18580 ++emsg_skip;
18581 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
18583 p = arg;
18584 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
18587 * Report the invalid expression unless the expression evaluation
18588 * has been cancelled due to an aborting error, an interrupt, or an
18589 * exception.
18591 if (!aborting())
18592 EMSG2(_(e_invexpr2), p);
18593 break;
18595 if (!eap->skip)
18597 if (atstart)
18599 atstart = FALSE;
18600 /* Call msg_start() after eval1(), evaluating the expression
18601 * may cause a message to appear. */
18602 if (eap->cmdidx == CMD_echo)
18603 msg_start();
18605 else if (eap->cmdidx == CMD_echo)
18606 msg_puts_attr((char_u *)" ", echo_attr);
18607 p = echo_string(&rettv, &tofree, numbuf, ++current_copyID);
18608 if (p != NULL)
18609 for ( ; *p != NUL && !got_int; ++p)
18611 if (*p == '\n' || *p == '\r' || *p == TAB)
18613 if (*p != TAB && needclr)
18615 /* remove any text still there from the command */
18616 msg_clr_eos();
18617 needclr = FALSE;
18619 msg_putchar_attr(*p, echo_attr);
18621 else
18623 #ifdef FEAT_MBYTE
18624 if (has_mbyte)
18626 int i = (*mb_ptr2len)(p);
18628 (void)msg_outtrans_len_attr(p, i, echo_attr);
18629 p += i - 1;
18631 else
18632 #endif
18633 (void)msg_outtrans_len_attr(p, 1, echo_attr);
18636 vim_free(tofree);
18638 clear_tv(&rettv);
18639 arg = skipwhite(arg);
18641 eap->nextcmd = check_nextcmd(arg);
18643 if (eap->skip)
18644 --emsg_skip;
18645 else
18647 /* remove text that may still be there from the command */
18648 if (needclr)
18649 msg_clr_eos();
18650 if (eap->cmdidx == CMD_echo)
18651 msg_end();
18656 * ":echohl {name}".
18658 void
18659 ex_echohl(eap)
18660 exarg_T *eap;
18662 int id;
18664 id = syn_name2id(eap->arg);
18665 if (id == 0)
18666 echo_attr = 0;
18667 else
18668 echo_attr = syn_id2attr(id);
18672 * ":execute expr1 ..." execute the result of an expression.
18673 * ":echomsg expr1 ..." Print a message
18674 * ":echoerr expr1 ..." Print an error
18675 * Each gets spaces around each argument and a newline at the end for
18676 * echo commands
18678 void
18679 ex_execute(eap)
18680 exarg_T *eap;
18682 char_u *arg = eap->arg;
18683 typval_T rettv;
18684 int ret = OK;
18685 char_u *p;
18686 garray_T ga;
18687 int len;
18688 int save_did_emsg;
18690 ga_init2(&ga, 1, 80);
18692 if (eap->skip)
18693 ++emsg_skip;
18694 while (*arg != NUL && *arg != '|' && *arg != '\n')
18696 p = arg;
18697 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
18700 * Report the invalid expression unless the expression evaluation
18701 * has been cancelled due to an aborting error, an interrupt, or an
18702 * exception.
18704 if (!aborting())
18705 EMSG2(_(e_invexpr2), p);
18706 ret = FAIL;
18707 break;
18710 if (!eap->skip)
18712 p = get_tv_string(&rettv);
18713 len = (int)STRLEN(p);
18714 if (ga_grow(&ga, len + 2) == FAIL)
18716 clear_tv(&rettv);
18717 ret = FAIL;
18718 break;
18720 if (ga.ga_len)
18721 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
18722 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
18723 ga.ga_len += len;
18726 clear_tv(&rettv);
18727 arg = skipwhite(arg);
18730 if (ret != FAIL && ga.ga_data != NULL)
18732 if (eap->cmdidx == CMD_echomsg)
18734 MSG_ATTR(ga.ga_data, echo_attr);
18735 out_flush();
18737 else if (eap->cmdidx == CMD_echoerr)
18739 /* We don't want to abort following commands, restore did_emsg. */
18740 save_did_emsg = did_emsg;
18741 EMSG((char_u *)ga.ga_data);
18742 if (!force_abort)
18743 did_emsg = save_did_emsg;
18745 else if (eap->cmdidx == CMD_execute)
18746 do_cmdline((char_u *)ga.ga_data,
18747 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
18750 ga_clear(&ga);
18752 if (eap->skip)
18753 --emsg_skip;
18755 eap->nextcmd = check_nextcmd(arg);
18759 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
18760 * "arg" points to the "&" or '+' when called, to "option" when returning.
18761 * Returns NULL when no option name found. Otherwise pointer to the char
18762 * after the option name.
18764 static char_u *
18765 find_option_end(arg, opt_flags)
18766 char_u **arg;
18767 int *opt_flags;
18769 char_u *p = *arg;
18771 ++p;
18772 if (*p == 'g' && p[1] == ':')
18774 *opt_flags = OPT_GLOBAL;
18775 p += 2;
18777 else if (*p == 'l' && p[1] == ':')
18779 *opt_flags = OPT_LOCAL;
18780 p += 2;
18782 else
18783 *opt_flags = 0;
18785 if (!ASCII_ISALPHA(*p))
18786 return NULL;
18787 *arg = p;
18789 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
18790 p += 4; /* termcap option */
18791 else
18792 while (ASCII_ISALPHA(*p))
18793 ++p;
18794 return p;
18798 * ":function"
18800 void
18801 ex_function(eap)
18802 exarg_T *eap;
18804 char_u *theline;
18805 int j;
18806 int c;
18807 int saved_did_emsg;
18808 char_u *name = NULL;
18809 char_u *p;
18810 char_u *arg;
18811 char_u *line_arg = NULL;
18812 garray_T newargs;
18813 garray_T newlines;
18814 int varargs = FALSE;
18815 int mustend = FALSE;
18816 int flags = 0;
18817 ufunc_T *fp;
18818 int indent;
18819 int nesting;
18820 char_u *skip_until = NULL;
18821 dictitem_T *v;
18822 funcdict_T fudi;
18823 static int func_nr = 0; /* number for nameless function */
18824 int paren;
18825 hashtab_T *ht;
18826 int todo;
18827 hashitem_T *hi;
18828 int sourcing_lnum_off;
18831 * ":function" without argument: list functions.
18833 if (ends_excmd(*eap->arg))
18835 if (!eap->skip)
18837 todo = (int)func_hashtab.ht_used;
18838 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
18840 if (!HASHITEM_EMPTY(hi))
18842 --todo;
18843 fp = HI2UF(hi);
18844 if (!isdigit(*fp->uf_name))
18845 list_func_head(fp, FALSE);
18849 eap->nextcmd = check_nextcmd(eap->arg);
18850 return;
18854 * ":function /pat": list functions matching pattern.
18856 if (*eap->arg == '/')
18858 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
18859 if (!eap->skip)
18861 regmatch_T regmatch;
18863 c = *p;
18864 *p = NUL;
18865 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
18866 *p = c;
18867 if (regmatch.regprog != NULL)
18869 regmatch.rm_ic = p_ic;
18871 todo = (int)func_hashtab.ht_used;
18872 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
18874 if (!HASHITEM_EMPTY(hi))
18876 --todo;
18877 fp = HI2UF(hi);
18878 if (!isdigit(*fp->uf_name)
18879 && vim_regexec(&regmatch, fp->uf_name, 0))
18880 list_func_head(fp, FALSE);
18885 if (*p == '/')
18886 ++p;
18887 eap->nextcmd = check_nextcmd(p);
18888 return;
18892 * Get the function name. There are these situations:
18893 * func normal function name
18894 * "name" == func, "fudi.fd_dict" == NULL
18895 * dict.func new dictionary entry
18896 * "name" == NULL, "fudi.fd_dict" set,
18897 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
18898 * dict.func existing dict entry with a Funcref
18899 * "name" == func, "fudi.fd_dict" set,
18900 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
18901 * dict.func existing dict entry that's not a Funcref
18902 * "name" == NULL, "fudi.fd_dict" set,
18903 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
18905 p = eap->arg;
18906 name = trans_function_name(&p, eap->skip, 0, &fudi);
18907 paren = (vim_strchr(p, '(') != NULL);
18908 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
18911 * Return on an invalid expression in braces, unless the expression
18912 * evaluation has been cancelled due to an aborting error, an
18913 * interrupt, or an exception.
18915 if (!aborting())
18917 if (!eap->skip && fudi.fd_newkey != NULL)
18918 EMSG2(_(e_dictkey), fudi.fd_newkey);
18919 vim_free(fudi.fd_newkey);
18920 return;
18922 else
18923 eap->skip = TRUE;
18926 /* An error in a function call during evaluation of an expression in magic
18927 * braces should not cause the function not to be defined. */
18928 saved_did_emsg = did_emsg;
18929 did_emsg = FALSE;
18932 * ":function func" with only function name: list function.
18934 if (!paren)
18936 if (!ends_excmd(*skipwhite(p)))
18938 EMSG(_(e_trailing));
18939 goto ret_free;
18941 eap->nextcmd = check_nextcmd(p);
18942 if (eap->nextcmd != NULL)
18943 *p = NUL;
18944 if (!eap->skip && !got_int)
18946 fp = find_func(name);
18947 if (fp != NULL)
18949 list_func_head(fp, TRUE);
18950 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
18952 if (FUNCLINE(fp, j) == NULL)
18953 continue;
18954 msg_putchar('\n');
18955 msg_outnum((long)(j + 1));
18956 if (j < 9)
18957 msg_putchar(' ');
18958 if (j < 99)
18959 msg_putchar(' ');
18960 msg_prt_line(FUNCLINE(fp, j), FALSE);
18961 out_flush(); /* show a line at a time */
18962 ui_breakcheck();
18964 if (!got_int)
18966 msg_putchar('\n');
18967 msg_puts((char_u *)" endfunction");
18970 else
18971 emsg_funcname("E123: Undefined function: %s", name);
18973 goto ret_free;
18977 * ":function name(arg1, arg2)" Define function.
18979 p = skipwhite(p);
18980 if (*p != '(')
18982 if (!eap->skip)
18984 EMSG2(_("E124: Missing '(': %s"), eap->arg);
18985 goto ret_free;
18987 /* attempt to continue by skipping some text */
18988 if (vim_strchr(p, '(') != NULL)
18989 p = vim_strchr(p, '(');
18991 p = skipwhite(p + 1);
18993 ga_init2(&newargs, (int)sizeof(char_u *), 3);
18994 ga_init2(&newlines, (int)sizeof(char_u *), 3);
18996 if (!eap->skip)
18998 /* Check the name of the function. Unless it's a dictionary function
18999 * (that we are overwriting). */
19000 if (name != NULL)
19001 arg = name;
19002 else
19003 arg = fudi.fd_newkey;
19004 if (arg != NULL && (fudi.fd_di == NULL
19005 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
19007 if (*arg == K_SPECIAL)
19008 j = 3;
19009 else
19010 j = 0;
19011 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
19012 : eval_isnamec(arg[j])))
19013 ++j;
19014 if (arg[j] != NUL)
19015 emsg_funcname(_(e_invarg2), arg);
19020 * Isolate the arguments: "arg1, arg2, ...)"
19022 while (*p != ')')
19024 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
19026 varargs = TRUE;
19027 p += 3;
19028 mustend = TRUE;
19030 else
19032 arg = p;
19033 while (ASCII_ISALNUM(*p) || *p == '_')
19034 ++p;
19035 if (arg == p || isdigit(*arg)
19036 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
19037 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
19039 if (!eap->skip)
19040 EMSG2(_("E125: Illegal argument: %s"), arg);
19041 break;
19043 if (ga_grow(&newargs, 1) == FAIL)
19044 goto erret;
19045 c = *p;
19046 *p = NUL;
19047 arg = vim_strsave(arg);
19048 if (arg == NULL)
19049 goto erret;
19050 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
19051 *p = c;
19052 newargs.ga_len++;
19053 if (*p == ',')
19054 ++p;
19055 else
19056 mustend = TRUE;
19058 p = skipwhite(p);
19059 if (mustend && *p != ')')
19061 if (!eap->skip)
19062 EMSG2(_(e_invarg2), eap->arg);
19063 break;
19066 ++p; /* skip the ')' */
19068 /* find extra arguments "range", "dict" and "abort" */
19069 for (;;)
19071 p = skipwhite(p);
19072 if (STRNCMP(p, "range", 5) == 0)
19074 flags |= FC_RANGE;
19075 p += 5;
19077 else if (STRNCMP(p, "dict", 4) == 0)
19079 flags |= FC_DICT;
19080 p += 4;
19082 else if (STRNCMP(p, "abort", 5) == 0)
19084 flags |= FC_ABORT;
19085 p += 5;
19087 else
19088 break;
19091 /* When there is a line break use what follows for the function body.
19092 * Makes 'exe "func Test()\n...\nendfunc"' work. */
19093 if (*p == '\n')
19094 line_arg = p + 1;
19095 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
19096 EMSG(_(e_trailing));
19099 * Read the body of the function, until ":endfunction" is found.
19101 if (KeyTyped)
19103 /* Check if the function already exists, don't let the user type the
19104 * whole function before telling him it doesn't work! For a script we
19105 * need to skip the body to be able to find what follows. */
19106 if (!eap->skip && !eap->forceit)
19108 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
19109 EMSG(_(e_funcdict));
19110 else if (name != NULL && find_func(name) != NULL)
19111 emsg_funcname(e_funcexts, name);
19114 if (!eap->skip && did_emsg)
19115 goto erret;
19117 msg_putchar('\n'); /* don't overwrite the function name */
19118 cmdline_row = msg_row;
19121 indent = 2;
19122 nesting = 0;
19123 for (;;)
19125 msg_scroll = TRUE;
19126 need_wait_return = FALSE;
19127 sourcing_lnum_off = sourcing_lnum;
19129 if (line_arg != NULL)
19131 /* Use eap->arg, split up in parts by line breaks. */
19132 theline = line_arg;
19133 p = vim_strchr(theline, '\n');
19134 if (p == NULL)
19135 line_arg += STRLEN(line_arg);
19136 else
19138 *p = NUL;
19139 line_arg = p + 1;
19142 else if (eap->getline == NULL)
19143 theline = getcmdline(':', 0L, indent);
19144 else
19145 theline = eap->getline(':', eap->cookie, indent);
19146 if (KeyTyped)
19147 lines_left = Rows - 1;
19148 if (theline == NULL)
19150 EMSG(_("E126: Missing :endfunction"));
19151 goto erret;
19154 /* Detect line continuation: sourcing_lnum increased more than one. */
19155 if (sourcing_lnum > sourcing_lnum_off + 1)
19156 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
19157 else
19158 sourcing_lnum_off = 0;
19160 if (skip_until != NULL)
19162 /* between ":append" and "." and between ":python <<EOF" and "EOF"
19163 * don't check for ":endfunc". */
19164 if (STRCMP(theline, skip_until) == 0)
19166 vim_free(skip_until);
19167 skip_until = NULL;
19170 else
19172 /* skip ':' and blanks*/
19173 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
19176 /* Check for "endfunction". */
19177 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
19179 if (line_arg == NULL)
19180 vim_free(theline);
19181 break;
19184 /* Increase indent inside "if", "while", "for" and "try", decrease
19185 * at "end". */
19186 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
19187 indent -= 2;
19188 else if (STRNCMP(p, "if", 2) == 0
19189 || STRNCMP(p, "wh", 2) == 0
19190 || STRNCMP(p, "for", 3) == 0
19191 || STRNCMP(p, "try", 3) == 0)
19192 indent += 2;
19194 /* Check for defining a function inside this function. */
19195 if (checkforcmd(&p, "function", 2))
19197 if (*p == '!')
19198 p = skipwhite(p + 1);
19199 p += eval_fname_script(p);
19200 if (ASCII_ISALPHA(*p))
19202 vim_free(trans_function_name(&p, TRUE, 0, NULL));
19203 if (*skipwhite(p) == '(')
19205 ++nesting;
19206 indent += 2;
19211 /* Check for ":append" or ":insert". */
19212 p = skip_range(p, NULL);
19213 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
19214 || (p[0] == 'i'
19215 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
19216 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
19217 skip_until = vim_strsave((char_u *)".");
19219 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
19220 arg = skipwhite(skiptowhite(p));
19221 if (arg[0] == '<' && arg[1] =='<'
19222 && ((p[0] == 'p' && p[1] == 'y'
19223 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
19224 || (p[0] == 'p' && p[1] == 'e'
19225 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
19226 || (p[0] == 't' && p[1] == 'c'
19227 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
19228 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
19229 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
19230 || (p[0] == 'm' && p[1] == 'z'
19231 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
19234 /* ":python <<" continues until a dot, like ":append" */
19235 p = skipwhite(arg + 2);
19236 if (*p == NUL)
19237 skip_until = vim_strsave((char_u *)".");
19238 else
19239 skip_until = vim_strsave(p);
19243 /* Add the line to the function. */
19244 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
19246 if (line_arg == NULL)
19247 vim_free(theline);
19248 goto erret;
19251 /* Copy the line to newly allocated memory. get_one_sourceline()
19252 * allocates 250 bytes per line, this saves 80% on average. The cost
19253 * is an extra alloc/free. */
19254 p = vim_strsave(theline);
19255 if (p != NULL)
19257 if (line_arg == NULL)
19258 vim_free(theline);
19259 theline = p;
19262 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
19264 /* Add NULL lines for continuation lines, so that the line count is
19265 * equal to the index in the growarray. */
19266 while (sourcing_lnum_off-- > 0)
19267 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
19269 /* Check for end of eap->arg. */
19270 if (line_arg != NULL && *line_arg == NUL)
19271 line_arg = NULL;
19274 /* Don't define the function when skipping commands or when an error was
19275 * detected. */
19276 if (eap->skip || did_emsg)
19277 goto erret;
19280 * If there are no errors, add the function
19282 if (fudi.fd_dict == NULL)
19284 v = find_var(name, &ht);
19285 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
19287 emsg_funcname("E707: Function name conflicts with variable: %s",
19288 name);
19289 goto erret;
19292 fp = find_func(name);
19293 if (fp != NULL)
19295 if (!eap->forceit)
19297 emsg_funcname(e_funcexts, name);
19298 goto erret;
19300 if (fp->uf_calls > 0)
19302 emsg_funcname("E127: Cannot redefine function %s: It is in use",
19303 name);
19304 goto erret;
19306 /* redefine existing function */
19307 ga_clear_strings(&(fp->uf_args));
19308 ga_clear_strings(&(fp->uf_lines));
19309 vim_free(name);
19310 name = NULL;
19313 else
19315 char numbuf[20];
19317 fp = NULL;
19318 if (fudi.fd_newkey == NULL && !eap->forceit)
19320 EMSG(_(e_funcdict));
19321 goto erret;
19323 if (fudi.fd_di == NULL)
19325 /* Can't add a function to a locked dictionary */
19326 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
19327 goto erret;
19329 /* Can't change an existing function if it is locked */
19330 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
19331 goto erret;
19333 /* Give the function a sequential number. Can only be used with a
19334 * Funcref! */
19335 vim_free(name);
19336 sprintf(numbuf, "%d", ++func_nr);
19337 name = vim_strsave((char_u *)numbuf);
19338 if (name == NULL)
19339 goto erret;
19342 if (fp == NULL)
19344 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
19346 int slen, plen;
19347 char_u *scriptname;
19349 /* Check that the autoload name matches the script name. */
19350 j = FAIL;
19351 if (sourcing_name != NULL)
19353 scriptname = autoload_name(name);
19354 if (scriptname != NULL)
19356 p = vim_strchr(scriptname, '/');
19357 plen = (int)STRLEN(p);
19358 slen = (int)STRLEN(sourcing_name);
19359 if (slen > plen && fnamecmp(p,
19360 sourcing_name + slen - plen) == 0)
19361 j = OK;
19362 vim_free(scriptname);
19365 if (j == FAIL)
19367 EMSG2(_("E746: Function name does not match script file name: %s"), name);
19368 goto erret;
19372 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
19373 if (fp == NULL)
19374 goto erret;
19376 if (fudi.fd_dict != NULL)
19378 if (fudi.fd_di == NULL)
19380 /* add new dict entry */
19381 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
19382 if (fudi.fd_di == NULL)
19384 vim_free(fp);
19385 goto erret;
19387 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
19389 vim_free(fudi.fd_di);
19390 vim_free(fp);
19391 goto erret;
19394 else
19395 /* overwrite existing dict entry */
19396 clear_tv(&fudi.fd_di->di_tv);
19397 fudi.fd_di->di_tv.v_type = VAR_FUNC;
19398 fudi.fd_di->di_tv.v_lock = 0;
19399 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
19400 fp->uf_refcount = 1;
19402 /* behave like "dict" was used */
19403 flags |= FC_DICT;
19406 /* insert the new function in the function list */
19407 STRCPY(fp->uf_name, name);
19408 hash_add(&func_hashtab, UF2HIKEY(fp));
19410 fp->uf_args = newargs;
19411 fp->uf_lines = newlines;
19412 #ifdef FEAT_PROFILE
19413 fp->uf_tml_count = NULL;
19414 fp->uf_tml_total = NULL;
19415 fp->uf_tml_self = NULL;
19416 fp->uf_profiling = FALSE;
19417 if (prof_def_func())
19418 func_do_profile(fp);
19419 #endif
19420 fp->uf_varargs = varargs;
19421 fp->uf_flags = flags;
19422 fp->uf_calls = 0;
19423 fp->uf_script_ID = current_SID;
19424 goto ret_free;
19426 erret:
19427 ga_clear_strings(&newargs);
19428 ga_clear_strings(&newlines);
19429 ret_free:
19430 vim_free(skip_until);
19431 vim_free(fudi.fd_newkey);
19432 vim_free(name);
19433 did_emsg |= saved_did_emsg;
19437 * Get a function name, translating "<SID>" and "<SNR>".
19438 * Also handles a Funcref in a List or Dictionary.
19439 * Returns the function name in allocated memory, or NULL for failure.
19440 * flags:
19441 * TFN_INT: internal function name OK
19442 * TFN_QUIET: be quiet
19443 * Advances "pp" to just after the function name (if no error).
19445 static char_u *
19446 trans_function_name(pp, skip, flags, fdp)
19447 char_u **pp;
19448 int skip; /* only find the end, don't evaluate */
19449 int flags;
19450 funcdict_T *fdp; /* return: info about dictionary used */
19452 char_u *name = NULL;
19453 char_u *start;
19454 char_u *end;
19455 int lead;
19456 char_u sid_buf[20];
19457 int len;
19458 lval_T lv;
19460 if (fdp != NULL)
19461 vim_memset(fdp, 0, sizeof(funcdict_T));
19462 start = *pp;
19464 /* Check for hard coded <SNR>: already translated function ID (from a user
19465 * command). */
19466 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
19467 && (*pp)[2] == (int)KE_SNR)
19469 *pp += 3;
19470 len = get_id_len(pp) + 3;
19471 return vim_strnsave(start, len);
19474 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
19475 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
19476 lead = eval_fname_script(start);
19477 if (lead > 2)
19478 start += lead;
19480 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
19481 lead > 2 ? 0 : FNE_CHECK_START);
19482 if (end == start)
19484 if (!skip)
19485 EMSG(_("E129: Function name required"));
19486 goto theend;
19488 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
19491 * Report an invalid expression in braces, unless the expression
19492 * evaluation has been cancelled due to an aborting error, an
19493 * interrupt, or an exception.
19495 if (!aborting())
19497 if (end != NULL)
19498 EMSG2(_(e_invarg2), start);
19500 else
19501 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
19502 goto theend;
19505 if (lv.ll_tv != NULL)
19507 if (fdp != NULL)
19509 fdp->fd_dict = lv.ll_dict;
19510 fdp->fd_newkey = lv.ll_newkey;
19511 lv.ll_newkey = NULL;
19512 fdp->fd_di = lv.ll_di;
19514 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
19516 name = vim_strsave(lv.ll_tv->vval.v_string);
19517 *pp = end;
19519 else
19521 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
19522 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
19523 EMSG(_(e_funcref));
19524 else
19525 *pp = end;
19526 name = NULL;
19528 goto theend;
19531 if (lv.ll_name == NULL)
19533 /* Error found, but continue after the function name. */
19534 *pp = end;
19535 goto theend;
19538 /* Check if the name is a Funcref. If so, use the value. */
19539 if (lv.ll_exp_name != NULL)
19541 len = (int)STRLEN(lv.ll_exp_name);
19542 name = deref_func_name(lv.ll_exp_name, &len);
19543 if (name == lv.ll_exp_name)
19544 name = NULL;
19546 else
19548 len = (int)(end - *pp);
19549 name = deref_func_name(*pp, &len);
19550 if (name == *pp)
19551 name = NULL;
19553 if (name != NULL)
19555 name = vim_strsave(name);
19556 *pp = end;
19557 goto theend;
19560 if (lv.ll_exp_name != NULL)
19562 len = (int)STRLEN(lv.ll_exp_name);
19563 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
19564 && STRNCMP(lv.ll_name, "s:", 2) == 0)
19566 /* When there was "s:" already or the name expanded to get a
19567 * leading "s:" then remove it. */
19568 lv.ll_name += 2;
19569 len -= 2;
19570 lead = 2;
19573 else
19575 if (lead == 2) /* skip over "s:" */
19576 lv.ll_name += 2;
19577 len = (int)(end - lv.ll_name);
19581 * Copy the function name to allocated memory.
19582 * Accept <SID>name() inside a script, translate into <SNR>123_name().
19583 * Accept <SNR>123_name() outside a script.
19585 if (skip)
19586 lead = 0; /* do nothing */
19587 else if (lead > 0)
19589 lead = 3;
19590 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
19591 || eval_fname_sid(*pp))
19593 /* It's "s:" or "<SID>" */
19594 if (current_SID <= 0)
19596 EMSG(_(e_usingsid));
19597 goto theend;
19599 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
19600 lead += (int)STRLEN(sid_buf);
19603 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
19605 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
19606 goto theend;
19608 name = alloc((unsigned)(len + lead + 1));
19609 if (name != NULL)
19611 if (lead > 0)
19613 name[0] = K_SPECIAL;
19614 name[1] = KS_EXTRA;
19615 name[2] = (int)KE_SNR;
19616 if (lead > 3) /* If it's "<SID>" */
19617 STRCPY(name + 3, sid_buf);
19619 mch_memmove(name + lead, lv.ll_name, (size_t)len);
19620 name[len + lead] = NUL;
19622 *pp = end;
19624 theend:
19625 clear_lval(&lv);
19626 return name;
19630 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
19631 * Return 2 if "p" starts with "s:".
19632 * Return 0 otherwise.
19634 static int
19635 eval_fname_script(p)
19636 char_u *p;
19638 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
19639 || STRNICMP(p + 1, "SNR>", 4) == 0))
19640 return 5;
19641 if (p[0] == 's' && p[1] == ':')
19642 return 2;
19643 return 0;
19647 * Return TRUE if "p" starts with "<SID>" or "s:".
19648 * Only works if eval_fname_script() returned non-zero for "p"!
19650 static int
19651 eval_fname_sid(p)
19652 char_u *p;
19654 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
19658 * List the head of the function: "name(arg1, arg2)".
19660 static void
19661 list_func_head(fp, indent)
19662 ufunc_T *fp;
19663 int indent;
19665 int j;
19667 msg_start();
19668 if (indent)
19669 MSG_PUTS(" ");
19670 MSG_PUTS("function ");
19671 if (fp->uf_name[0] == K_SPECIAL)
19673 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
19674 msg_puts(fp->uf_name + 3);
19676 else
19677 msg_puts(fp->uf_name);
19678 msg_putchar('(');
19679 for (j = 0; j < fp->uf_args.ga_len; ++j)
19681 if (j)
19682 MSG_PUTS(", ");
19683 msg_puts(FUNCARG(fp, j));
19685 if (fp->uf_varargs)
19687 if (j)
19688 MSG_PUTS(", ");
19689 MSG_PUTS("...");
19691 msg_putchar(')');
19692 msg_clr_eos();
19693 if (p_verbose > 0)
19694 last_set_msg(fp->uf_script_ID);
19698 * Find a function by name, return pointer to it in ufuncs.
19699 * Return NULL for unknown function.
19701 static ufunc_T *
19702 find_func(name)
19703 char_u *name;
19705 hashitem_T *hi;
19707 hi = hash_find(&func_hashtab, name);
19708 if (!HASHITEM_EMPTY(hi))
19709 return HI2UF(hi);
19710 return NULL;
19713 #if defined(EXITFREE) || defined(PROTO)
19714 void
19715 free_all_functions()
19717 hashitem_T *hi;
19719 /* Need to start all over every time, because func_free() may change the
19720 * hash table. */
19721 while (func_hashtab.ht_used > 0)
19722 for (hi = func_hashtab.ht_array; ; ++hi)
19723 if (!HASHITEM_EMPTY(hi))
19725 func_free(HI2UF(hi));
19726 break;
19729 #endif
19732 * Return TRUE if a function "name" exists.
19734 static int
19735 function_exists(name)
19736 char_u *name;
19738 char_u *nm = name;
19739 char_u *p;
19740 int n = FALSE;
19742 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
19743 nm = skipwhite(nm);
19745 /* Only accept "funcname", "funcname ", "funcname (..." and
19746 * "funcname(...", not "funcname!...". */
19747 if (p != NULL && (*nm == NUL || *nm == '('))
19749 if (builtin_function(p))
19750 n = (find_internal_func(p) >= 0);
19751 else
19752 n = (find_func(p) != NULL);
19754 vim_free(p);
19755 return n;
19759 * Return TRUE if "name" looks like a builtin function name: starts with a
19760 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
19762 static int
19763 builtin_function(name)
19764 char_u *name;
19766 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
19767 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
19770 #if defined(FEAT_PROFILE) || defined(PROTO)
19772 * Start profiling function "fp".
19774 static void
19775 func_do_profile(fp)
19776 ufunc_T *fp;
19778 fp->uf_tm_count = 0;
19779 profile_zero(&fp->uf_tm_self);
19780 profile_zero(&fp->uf_tm_total);
19781 if (fp->uf_tml_count == NULL)
19782 fp->uf_tml_count = (int *)alloc_clear((unsigned)
19783 (sizeof(int) * fp->uf_lines.ga_len));
19784 if (fp->uf_tml_total == NULL)
19785 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
19786 (sizeof(proftime_T) * fp->uf_lines.ga_len));
19787 if (fp->uf_tml_self == NULL)
19788 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
19789 (sizeof(proftime_T) * fp->uf_lines.ga_len));
19790 fp->uf_tml_idx = -1;
19791 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
19792 || fp->uf_tml_self == NULL)
19793 return; /* out of memory */
19795 fp->uf_profiling = TRUE;
19799 * Dump the profiling results for all functions in file "fd".
19801 void
19802 func_dump_profile(fd)
19803 FILE *fd;
19805 hashitem_T *hi;
19806 int todo;
19807 ufunc_T *fp;
19808 int i;
19809 ufunc_T **sorttab;
19810 int st_len = 0;
19812 todo = (int)func_hashtab.ht_used;
19813 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
19815 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
19817 if (!HASHITEM_EMPTY(hi))
19819 --todo;
19820 fp = HI2UF(hi);
19821 if (fp->uf_profiling)
19823 if (sorttab != NULL)
19824 sorttab[st_len++] = fp;
19826 if (fp->uf_name[0] == K_SPECIAL)
19827 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
19828 else
19829 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
19830 if (fp->uf_tm_count == 1)
19831 fprintf(fd, "Called 1 time\n");
19832 else
19833 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
19834 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
19835 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
19836 fprintf(fd, "\n");
19837 fprintf(fd, "count total (s) self (s)\n");
19839 for (i = 0; i < fp->uf_lines.ga_len; ++i)
19841 if (FUNCLINE(fp, i) == NULL)
19842 continue;
19843 prof_func_line(fd, fp->uf_tml_count[i],
19844 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
19845 fprintf(fd, "%s\n", FUNCLINE(fp, i));
19847 fprintf(fd, "\n");
19852 if (sorttab != NULL && st_len > 0)
19854 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
19855 prof_total_cmp);
19856 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
19857 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
19858 prof_self_cmp);
19859 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
19863 static void
19864 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
19865 FILE *fd;
19866 ufunc_T **sorttab;
19867 int st_len;
19868 char *title;
19869 int prefer_self; /* when equal print only self time */
19871 int i;
19872 ufunc_T *fp;
19874 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
19875 fprintf(fd, "count total (s) self (s) function\n");
19876 for (i = 0; i < 20 && i < st_len; ++i)
19878 fp = sorttab[i];
19879 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
19880 prefer_self);
19881 if (fp->uf_name[0] == K_SPECIAL)
19882 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
19883 else
19884 fprintf(fd, " %s()\n", fp->uf_name);
19886 fprintf(fd, "\n");
19890 * Print the count and times for one function or function line.
19892 static void
19893 prof_func_line(fd, count, total, self, prefer_self)
19894 FILE *fd;
19895 int count;
19896 proftime_T *total;
19897 proftime_T *self;
19898 int prefer_self; /* when equal print only self time */
19900 if (count > 0)
19902 fprintf(fd, "%5d ", count);
19903 if (prefer_self && profile_equal(total, self))
19904 fprintf(fd, " ");
19905 else
19906 fprintf(fd, "%s ", profile_msg(total));
19907 if (!prefer_self && profile_equal(total, self))
19908 fprintf(fd, " ");
19909 else
19910 fprintf(fd, "%s ", profile_msg(self));
19912 else
19913 fprintf(fd, " ");
19917 * Compare function for total time sorting.
19919 static int
19920 #ifdef __BORLANDC__
19921 _RTLENTRYF
19922 #endif
19923 prof_total_cmp(s1, s2)
19924 const void *s1;
19925 const void *s2;
19927 ufunc_T *p1, *p2;
19929 p1 = *(ufunc_T **)s1;
19930 p2 = *(ufunc_T **)s2;
19931 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
19935 * Compare function for self time sorting.
19937 static int
19938 #ifdef __BORLANDC__
19939 _RTLENTRYF
19940 #endif
19941 prof_self_cmp(s1, s2)
19942 const void *s1;
19943 const void *s2;
19945 ufunc_T *p1, *p2;
19947 p1 = *(ufunc_T **)s1;
19948 p2 = *(ufunc_T **)s2;
19949 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
19952 #endif
19955 * If "name" has a package name try autoloading the script for it.
19956 * Return TRUE if a package was loaded.
19958 static int
19959 script_autoload(name, reload)
19960 char_u *name;
19961 int reload; /* load script again when already loaded */
19963 char_u *p;
19964 char_u *scriptname, *tofree;
19965 int ret = FALSE;
19966 int i;
19968 /* If there is no '#' after name[0] there is no package name. */
19969 p = vim_strchr(name, AUTOLOAD_CHAR);
19970 if (p == NULL || p == name)
19971 return FALSE;
19973 tofree = scriptname = autoload_name(name);
19975 /* Find the name in the list of previously loaded package names. Skip
19976 * "autoload/", it's always the same. */
19977 for (i = 0; i < ga_loaded.ga_len; ++i)
19978 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
19979 break;
19980 if (!reload && i < ga_loaded.ga_len)
19981 ret = FALSE; /* was loaded already */
19982 else
19984 /* Remember the name if it wasn't loaded already. */
19985 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
19987 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
19988 tofree = NULL;
19991 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
19992 if (source_runtime(scriptname, FALSE) == OK)
19993 ret = TRUE;
19996 vim_free(tofree);
19997 return ret;
20001 * Return the autoload script name for a function or variable name.
20002 * Returns NULL when out of memory.
20004 static char_u *
20005 autoload_name(name)
20006 char_u *name;
20008 char_u *p;
20009 char_u *scriptname;
20011 /* Get the script file name: replace '#' with '/', append ".vim". */
20012 scriptname = alloc((unsigned)(STRLEN(name) + 14));
20013 if (scriptname == NULL)
20014 return FALSE;
20015 STRCPY(scriptname, "autoload/");
20016 STRCAT(scriptname, name);
20017 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
20018 STRCAT(scriptname, ".vim");
20019 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
20020 *p = '/';
20021 return scriptname;
20024 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
20027 * Function given to ExpandGeneric() to obtain the list of user defined
20028 * function names.
20030 char_u *
20031 get_user_func_name(xp, idx)
20032 expand_T *xp;
20033 int idx;
20035 static long_u done;
20036 static hashitem_T *hi;
20037 ufunc_T *fp;
20039 if (idx == 0)
20041 done = 0;
20042 hi = func_hashtab.ht_array;
20044 if (done < func_hashtab.ht_used)
20046 if (done++ > 0)
20047 ++hi;
20048 while (HASHITEM_EMPTY(hi))
20049 ++hi;
20050 fp = HI2UF(hi);
20052 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
20053 return fp->uf_name; /* prevents overflow */
20055 cat_func_name(IObuff, fp);
20056 if (xp->xp_context != EXPAND_USER_FUNC)
20058 STRCAT(IObuff, "(");
20059 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
20060 STRCAT(IObuff, ")");
20062 return IObuff;
20064 return NULL;
20067 #endif /* FEAT_CMDL_COMPL */
20070 * Copy the function name of "fp" to buffer "buf".
20071 * "buf" must be able to hold the function name plus three bytes.
20072 * Takes care of script-local function names.
20074 static void
20075 cat_func_name(buf, fp)
20076 char_u *buf;
20077 ufunc_T *fp;
20079 if (fp->uf_name[0] == K_SPECIAL)
20081 STRCPY(buf, "<SNR>");
20082 STRCAT(buf, fp->uf_name + 3);
20084 else
20085 STRCPY(buf, fp->uf_name);
20089 * ":delfunction {name}"
20091 void
20092 ex_delfunction(eap)
20093 exarg_T *eap;
20095 ufunc_T *fp = NULL;
20096 char_u *p;
20097 char_u *name;
20098 funcdict_T fudi;
20100 p = eap->arg;
20101 name = trans_function_name(&p, eap->skip, 0, &fudi);
20102 vim_free(fudi.fd_newkey);
20103 if (name == NULL)
20105 if (fudi.fd_dict != NULL && !eap->skip)
20106 EMSG(_(e_funcref));
20107 return;
20109 if (!ends_excmd(*skipwhite(p)))
20111 vim_free(name);
20112 EMSG(_(e_trailing));
20113 return;
20115 eap->nextcmd = check_nextcmd(p);
20116 if (eap->nextcmd != NULL)
20117 *p = NUL;
20119 if (!eap->skip)
20120 fp = find_func(name);
20121 vim_free(name);
20123 if (!eap->skip)
20125 if (fp == NULL)
20127 EMSG2(_(e_nofunc), eap->arg);
20128 return;
20130 if (fp->uf_calls > 0)
20132 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
20133 return;
20136 if (fudi.fd_dict != NULL)
20138 /* Delete the dict item that refers to the function, it will
20139 * invoke func_unref() and possibly delete the function. */
20140 dictitem_remove(fudi.fd_dict, fudi.fd_di);
20142 else
20143 func_free(fp);
20148 * Free a function and remove it from the list of functions.
20150 static void
20151 func_free(fp)
20152 ufunc_T *fp;
20154 hashitem_T *hi;
20156 /* clear this function */
20157 ga_clear_strings(&(fp->uf_args));
20158 ga_clear_strings(&(fp->uf_lines));
20159 #ifdef FEAT_PROFILE
20160 vim_free(fp->uf_tml_count);
20161 vim_free(fp->uf_tml_total);
20162 vim_free(fp->uf_tml_self);
20163 #endif
20165 /* remove the function from the function hashtable */
20166 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
20167 if (HASHITEM_EMPTY(hi))
20168 EMSG2(_(e_intern2), "func_free()");
20169 else
20170 hash_remove(&func_hashtab, hi);
20172 vim_free(fp);
20176 * Unreference a Function: decrement the reference count and free it when it
20177 * becomes zero. Only for numbered functions.
20179 static void
20180 func_unref(name)
20181 char_u *name;
20183 ufunc_T *fp;
20185 if (name != NULL && isdigit(*name))
20187 fp = find_func(name);
20188 if (fp == NULL)
20189 EMSG2(_(e_intern2), "func_unref()");
20190 else if (--fp->uf_refcount <= 0)
20192 /* Only delete it when it's not being used. Otherwise it's done
20193 * when "uf_calls" becomes zero. */
20194 if (fp->uf_calls == 0)
20195 func_free(fp);
20201 * Count a reference to a Function.
20203 static void
20204 func_ref(name)
20205 char_u *name;
20207 ufunc_T *fp;
20209 if (name != NULL && isdigit(*name))
20211 fp = find_func(name);
20212 if (fp == NULL)
20213 EMSG2(_(e_intern2), "func_ref()");
20214 else
20215 ++fp->uf_refcount;
20220 * Call a user function.
20222 static void
20223 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
20224 ufunc_T *fp; /* pointer to function */
20225 int argcount; /* nr of args */
20226 typval_T *argvars; /* arguments */
20227 typval_T *rettv; /* return value */
20228 linenr_T firstline; /* first line of range */
20229 linenr_T lastline; /* last line of range */
20230 dict_T *selfdict; /* Dictionary for "self" */
20232 char_u *save_sourcing_name;
20233 linenr_T save_sourcing_lnum;
20234 scid_T save_current_SID;
20235 funccall_T fc;
20236 int save_did_emsg;
20237 static int depth = 0;
20238 dictitem_T *v;
20239 int fixvar_idx = 0; /* index in fixvar[] */
20240 int i;
20241 int ai;
20242 char_u numbuf[NUMBUFLEN];
20243 char_u *name;
20244 #ifdef FEAT_PROFILE
20245 proftime_T wait_start;
20246 proftime_T call_start;
20247 #endif
20249 /* If depth of calling is getting too high, don't execute the function */
20250 if (depth >= p_mfd)
20252 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
20253 rettv->v_type = VAR_NUMBER;
20254 rettv->vval.v_number = -1;
20255 return;
20257 ++depth;
20259 line_breakcheck(); /* check for CTRL-C hit */
20261 fc.caller = current_funccal;
20262 current_funccal = &fc;
20263 fc.func = fp;
20264 fc.rettv = rettv;
20265 rettv->vval.v_number = 0;
20266 fc.linenr = 0;
20267 fc.returned = FALSE;
20268 fc.level = ex_nesting_level;
20269 /* Check if this function has a breakpoint. */
20270 fc.breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
20271 fc.dbg_tick = debug_tick;
20274 * Note about using fc.fixvar[]: This is an array of FIXVAR_CNT variables
20275 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
20276 * each argument variable and saves a lot of time.
20279 * Init l: variables.
20281 init_var_dict(&fc.l_vars, &fc.l_vars_var);
20282 if (selfdict != NULL)
20284 /* Set l:self to "selfdict". Use "name" to avoid a warning from
20285 * some compiler that checks the destination size. */
20286 v = &fc.fixvar[fixvar_idx++].var;
20287 name = v->di_key;
20288 STRCPY(name, "self");
20289 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
20290 hash_add(&fc.l_vars.dv_hashtab, DI2HIKEY(v));
20291 v->di_tv.v_type = VAR_DICT;
20292 v->di_tv.v_lock = 0;
20293 v->di_tv.vval.v_dict = selfdict;
20294 ++selfdict->dv_refcount;
20298 * Init a: variables.
20299 * Set a:0 to "argcount".
20300 * Set a:000 to a list with room for the "..." arguments.
20302 init_var_dict(&fc.l_avars, &fc.l_avars_var);
20303 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "0",
20304 (varnumber_T)(argcount - fp->uf_args.ga_len));
20305 v = &fc.fixvar[fixvar_idx++].var;
20306 STRCPY(v->di_key, "000");
20307 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20308 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
20309 v->di_tv.v_type = VAR_LIST;
20310 v->di_tv.v_lock = VAR_FIXED;
20311 v->di_tv.vval.v_list = &fc.l_varlist;
20312 vim_memset(&fc.l_varlist, 0, sizeof(list_T));
20313 fc.l_varlist.lv_refcount = 99999;
20314 fc.l_varlist.lv_lock = VAR_FIXED;
20317 * Set a:firstline to "firstline" and a:lastline to "lastline".
20318 * Set a:name to named arguments.
20319 * Set a:N to the "..." arguments.
20321 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "firstline",
20322 (varnumber_T)firstline);
20323 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "lastline",
20324 (varnumber_T)lastline);
20325 for (i = 0; i < argcount; ++i)
20327 ai = i - fp->uf_args.ga_len;
20328 if (ai < 0)
20329 /* named argument a:name */
20330 name = FUNCARG(fp, i);
20331 else
20333 /* "..." argument a:1, a:2, etc. */
20334 sprintf((char *)numbuf, "%d", ai + 1);
20335 name = numbuf;
20337 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
20339 v = &fc.fixvar[fixvar_idx++].var;
20340 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20342 else
20344 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
20345 + STRLEN(name)));
20346 if (v == NULL)
20347 break;
20348 v->di_flags = DI_FLAGS_RO;
20350 STRCPY(v->di_key, name);
20351 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
20353 /* Note: the values are copied directly to avoid alloc/free.
20354 * "argvars" must have VAR_FIXED for v_lock. */
20355 v->di_tv = argvars[i];
20356 v->di_tv.v_lock = VAR_FIXED;
20358 if (ai >= 0 && ai < MAX_FUNC_ARGS)
20360 list_append(&fc.l_varlist, &fc.l_listitems[ai]);
20361 fc.l_listitems[ai].li_tv = argvars[i];
20362 fc.l_listitems[ai].li_tv.v_lock = VAR_FIXED;
20366 /* Don't redraw while executing the function. */
20367 ++RedrawingDisabled;
20368 save_sourcing_name = sourcing_name;
20369 save_sourcing_lnum = sourcing_lnum;
20370 sourcing_lnum = 1;
20371 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
20372 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
20373 if (sourcing_name != NULL)
20375 if (save_sourcing_name != NULL
20376 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
20377 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
20378 else
20379 STRCPY(sourcing_name, "function ");
20380 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
20382 if (p_verbose >= 12)
20384 ++no_wait_return;
20385 verbose_enter_scroll();
20387 smsg((char_u *)_("calling %s"), sourcing_name);
20388 if (p_verbose >= 14)
20390 char_u buf[MSG_BUF_LEN];
20391 char_u numbuf2[NUMBUFLEN];
20392 char_u *tofree;
20393 char_u *s;
20395 msg_puts((char_u *)"(");
20396 for (i = 0; i < argcount; ++i)
20398 if (i > 0)
20399 msg_puts((char_u *)", ");
20400 if (argvars[i].v_type == VAR_NUMBER)
20401 msg_outnum((long)argvars[i].vval.v_number);
20402 else
20404 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
20405 if (s != NULL)
20407 trunc_string(s, buf, MSG_BUF_CLEN);
20408 msg_puts(buf);
20409 vim_free(tofree);
20413 msg_puts((char_u *)")");
20415 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20417 verbose_leave_scroll();
20418 --no_wait_return;
20421 #ifdef FEAT_PROFILE
20422 if (do_profiling == PROF_YES)
20424 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
20425 func_do_profile(fp);
20426 if (fp->uf_profiling
20427 || (fc.caller != NULL && &fc.caller->func->uf_profiling))
20429 ++fp->uf_tm_count;
20430 profile_start(&call_start);
20431 profile_zero(&fp->uf_tm_children);
20433 script_prof_save(&wait_start);
20435 #endif
20437 save_current_SID = current_SID;
20438 current_SID = fp->uf_script_ID;
20439 save_did_emsg = did_emsg;
20440 did_emsg = FALSE;
20442 /* call do_cmdline() to execute the lines */
20443 do_cmdline(NULL, get_func_line, (void *)&fc,
20444 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
20446 --RedrawingDisabled;
20448 /* when the function was aborted because of an error, return -1 */
20449 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
20451 clear_tv(rettv);
20452 rettv->v_type = VAR_NUMBER;
20453 rettv->vval.v_number = -1;
20456 #ifdef FEAT_PROFILE
20457 if (do_profiling == PROF_YES && (fp->uf_profiling
20458 || (fc.caller != NULL && &fc.caller->func->uf_profiling)))
20460 profile_end(&call_start);
20461 profile_sub_wait(&wait_start, &call_start);
20462 profile_add(&fp->uf_tm_total, &call_start);
20463 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
20464 if (fc.caller != NULL && &fc.caller->func->uf_profiling)
20466 profile_add(&fc.caller->func->uf_tm_children, &call_start);
20467 profile_add(&fc.caller->func->uf_tml_children, &call_start);
20470 #endif
20472 /* when being verbose, mention the return value */
20473 if (p_verbose >= 12)
20475 ++no_wait_return;
20476 verbose_enter_scroll();
20478 if (aborting())
20479 smsg((char_u *)_("%s aborted"), sourcing_name);
20480 else if (fc.rettv->v_type == VAR_NUMBER)
20481 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
20482 (long)fc.rettv->vval.v_number);
20483 else
20485 char_u buf[MSG_BUF_LEN];
20486 char_u numbuf2[NUMBUFLEN];
20487 char_u *tofree;
20488 char_u *s;
20490 /* The value may be very long. Skip the middle part, so that we
20491 * have some idea how it starts and ends. smsg() would always
20492 * truncate it at the end. */
20493 s = tv2string(fc.rettv, &tofree, numbuf2, 0);
20494 if (s != NULL)
20496 trunc_string(s, buf, MSG_BUF_CLEN);
20497 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
20498 vim_free(tofree);
20501 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20503 verbose_leave_scroll();
20504 --no_wait_return;
20507 vim_free(sourcing_name);
20508 sourcing_name = save_sourcing_name;
20509 sourcing_lnum = save_sourcing_lnum;
20510 current_SID = save_current_SID;
20511 #ifdef FEAT_PROFILE
20512 if (do_profiling == PROF_YES)
20513 script_prof_restore(&wait_start);
20514 #endif
20516 if (p_verbose >= 12 && sourcing_name != NULL)
20518 ++no_wait_return;
20519 verbose_enter_scroll();
20521 smsg((char_u *)_("continuing in %s"), sourcing_name);
20522 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20524 verbose_leave_scroll();
20525 --no_wait_return;
20528 did_emsg |= save_did_emsg;
20529 current_funccal = fc.caller;
20531 /* The a: variables typevals were not alloced, only free the allocated
20532 * variables. */
20533 vars_clear_ext(&fc.l_avars.dv_hashtab, FALSE);
20535 vars_clear(&fc.l_vars.dv_hashtab); /* free all l: variables */
20536 --depth;
20540 * Add a number variable "name" to dict "dp" with value "nr".
20542 static void
20543 add_nr_var(dp, v, name, nr)
20544 dict_T *dp;
20545 dictitem_T *v;
20546 char *name;
20547 varnumber_T nr;
20549 STRCPY(v->di_key, name);
20550 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20551 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
20552 v->di_tv.v_type = VAR_NUMBER;
20553 v->di_tv.v_lock = VAR_FIXED;
20554 v->di_tv.vval.v_number = nr;
20558 * ":return [expr]"
20560 void
20561 ex_return(eap)
20562 exarg_T *eap;
20564 char_u *arg = eap->arg;
20565 typval_T rettv;
20566 int returning = FALSE;
20568 if (current_funccal == NULL)
20570 EMSG(_("E133: :return not inside a function"));
20571 return;
20574 if (eap->skip)
20575 ++emsg_skip;
20577 eap->nextcmd = NULL;
20578 if ((*arg != NUL && *arg != '|' && *arg != '\n')
20579 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
20581 if (!eap->skip)
20582 returning = do_return(eap, FALSE, TRUE, &rettv);
20583 else
20584 clear_tv(&rettv);
20586 /* It's safer to return also on error. */
20587 else if (!eap->skip)
20590 * Return unless the expression evaluation has been cancelled due to an
20591 * aborting error, an interrupt, or an exception.
20593 if (!aborting())
20594 returning = do_return(eap, FALSE, TRUE, NULL);
20597 /* When skipping or the return gets pending, advance to the next command
20598 * in this line (!returning). Otherwise, ignore the rest of the line.
20599 * Following lines will be ignored by get_func_line(). */
20600 if (returning)
20601 eap->nextcmd = NULL;
20602 else if (eap->nextcmd == NULL) /* no argument */
20603 eap->nextcmd = check_nextcmd(arg);
20605 if (eap->skip)
20606 --emsg_skip;
20610 * Return from a function. Possibly makes the return pending. Also called
20611 * for a pending return at the ":endtry" or after returning from an extra
20612 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
20613 * when called due to a ":return" command. "rettv" may point to a typval_T
20614 * with the return rettv. Returns TRUE when the return can be carried out,
20615 * FALSE when the return gets pending.
20618 do_return(eap, reanimate, is_cmd, rettv)
20619 exarg_T *eap;
20620 int reanimate;
20621 int is_cmd;
20622 void *rettv;
20624 int idx;
20625 struct condstack *cstack = eap->cstack;
20627 if (reanimate)
20628 /* Undo the return. */
20629 current_funccal->returned = FALSE;
20632 * Cleanup (and inactivate) conditionals, but stop when a try conditional
20633 * not in its finally clause (which then is to be executed next) is found.
20634 * In this case, make the ":return" pending for execution at the ":endtry".
20635 * Otherwise, return normally.
20637 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
20638 if (idx >= 0)
20640 cstack->cs_pending[idx] = CSTP_RETURN;
20642 if (!is_cmd && !reanimate)
20643 /* A pending return again gets pending. "rettv" points to an
20644 * allocated variable with the rettv of the original ":return"'s
20645 * argument if present or is NULL else. */
20646 cstack->cs_rettv[idx] = rettv;
20647 else
20649 /* When undoing a return in order to make it pending, get the stored
20650 * return rettv. */
20651 if (reanimate)
20652 rettv = current_funccal->rettv;
20654 if (rettv != NULL)
20656 /* Store the value of the pending return. */
20657 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
20658 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
20659 else
20660 EMSG(_(e_outofmem));
20662 else
20663 cstack->cs_rettv[idx] = NULL;
20665 if (reanimate)
20667 /* The pending return value could be overwritten by a ":return"
20668 * without argument in a finally clause; reset the default
20669 * return value. */
20670 current_funccal->rettv->v_type = VAR_NUMBER;
20671 current_funccal->rettv->vval.v_number = 0;
20674 report_make_pending(CSTP_RETURN, rettv);
20676 else
20678 current_funccal->returned = TRUE;
20680 /* If the return is carried out now, store the return value. For
20681 * a return immediately after reanimation, the value is already
20682 * there. */
20683 if (!reanimate && rettv != NULL)
20685 clear_tv(current_funccal->rettv);
20686 *current_funccal->rettv = *(typval_T *)rettv;
20687 if (!is_cmd)
20688 vim_free(rettv);
20692 return idx < 0;
20696 * Free the variable with a pending return value.
20698 void
20699 discard_pending_return(rettv)
20700 void *rettv;
20702 free_tv((typval_T *)rettv);
20706 * Generate a return command for producing the value of "rettv". The result
20707 * is an allocated string. Used by report_pending() for verbose messages.
20709 char_u *
20710 get_return_cmd(rettv)
20711 void *rettv;
20713 char_u *s = NULL;
20714 char_u *tofree = NULL;
20715 char_u numbuf[NUMBUFLEN];
20717 if (rettv != NULL)
20718 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
20719 if (s == NULL)
20720 s = (char_u *)"";
20722 STRCPY(IObuff, ":return ");
20723 STRNCPY(IObuff + 8, s, IOSIZE - 8);
20724 if (STRLEN(s) + 8 >= IOSIZE)
20725 STRCPY(IObuff + IOSIZE - 4, "...");
20726 vim_free(tofree);
20727 return vim_strsave(IObuff);
20731 * Get next function line.
20732 * Called by do_cmdline() to get the next line.
20733 * Returns allocated string, or NULL for end of function.
20735 /* ARGSUSED */
20736 char_u *
20737 get_func_line(c, cookie, indent)
20738 int c; /* not used */
20739 void *cookie;
20740 int indent; /* not used */
20742 funccall_T *fcp = (funccall_T *)cookie;
20743 ufunc_T *fp = fcp->func;
20744 char_u *retval;
20745 garray_T *gap; /* growarray with function lines */
20747 /* If breakpoints have been added/deleted need to check for it. */
20748 if (fcp->dbg_tick != debug_tick)
20750 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
20751 sourcing_lnum);
20752 fcp->dbg_tick = debug_tick;
20754 #ifdef FEAT_PROFILE
20755 if (do_profiling == PROF_YES)
20756 func_line_end(cookie);
20757 #endif
20759 gap = &fp->uf_lines;
20760 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
20761 || fcp->returned)
20762 retval = NULL;
20763 else
20765 /* Skip NULL lines (continuation lines). */
20766 while (fcp->linenr < gap->ga_len
20767 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
20768 ++fcp->linenr;
20769 if (fcp->linenr >= gap->ga_len)
20770 retval = NULL;
20771 else
20773 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
20774 sourcing_lnum = fcp->linenr;
20775 #ifdef FEAT_PROFILE
20776 if (do_profiling == PROF_YES)
20777 func_line_start(cookie);
20778 #endif
20782 /* Did we encounter a breakpoint? */
20783 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
20785 dbg_breakpoint(fp->uf_name, sourcing_lnum);
20786 /* Find next breakpoint. */
20787 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
20788 sourcing_lnum);
20789 fcp->dbg_tick = debug_tick;
20792 return retval;
20795 #if defined(FEAT_PROFILE) || defined(PROTO)
20797 * Called when starting to read a function line.
20798 * "sourcing_lnum" must be correct!
20799 * When skipping lines it may not actually be executed, but we won't find out
20800 * until later and we need to store the time now.
20802 void
20803 func_line_start(cookie)
20804 void *cookie;
20806 funccall_T *fcp = (funccall_T *)cookie;
20807 ufunc_T *fp = fcp->func;
20809 if (fp->uf_profiling && sourcing_lnum >= 1
20810 && sourcing_lnum <= fp->uf_lines.ga_len)
20812 fp->uf_tml_idx = sourcing_lnum - 1;
20813 /* Skip continuation lines. */
20814 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
20815 --fp->uf_tml_idx;
20816 fp->uf_tml_execed = FALSE;
20817 profile_start(&fp->uf_tml_start);
20818 profile_zero(&fp->uf_tml_children);
20819 profile_get_wait(&fp->uf_tml_wait);
20824 * Called when actually executing a function line.
20826 void
20827 func_line_exec(cookie)
20828 void *cookie;
20830 funccall_T *fcp = (funccall_T *)cookie;
20831 ufunc_T *fp = fcp->func;
20833 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
20834 fp->uf_tml_execed = TRUE;
20838 * Called when done with a function line.
20840 void
20841 func_line_end(cookie)
20842 void *cookie;
20844 funccall_T *fcp = (funccall_T *)cookie;
20845 ufunc_T *fp = fcp->func;
20847 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
20849 if (fp->uf_tml_execed)
20851 ++fp->uf_tml_count[fp->uf_tml_idx];
20852 profile_end(&fp->uf_tml_start);
20853 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
20854 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
20855 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
20856 &fp->uf_tml_children);
20858 fp->uf_tml_idx = -1;
20861 #endif
20864 * Return TRUE if the currently active function should be ended, because a
20865 * return was encountered or an error occured. Used inside a ":while".
20868 func_has_ended(cookie)
20869 void *cookie;
20871 funccall_T *fcp = (funccall_T *)cookie;
20873 /* Ignore the "abort" flag if the abortion behavior has been changed due to
20874 * an error inside a try conditional. */
20875 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
20876 || fcp->returned);
20880 * return TRUE if cookie indicates a function which "abort"s on errors.
20883 func_has_abort(cookie)
20884 void *cookie;
20886 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
20889 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
20890 typedef enum
20892 VAR_FLAVOUR_DEFAULT,
20893 VAR_FLAVOUR_SESSION,
20894 VAR_FLAVOUR_VIMINFO
20895 } var_flavour_T;
20897 static var_flavour_T var_flavour __ARGS((char_u *varname));
20899 static var_flavour_T
20900 var_flavour(varname)
20901 char_u *varname;
20903 char_u *p = varname;
20905 if (ASCII_ISUPPER(*p))
20907 while (*(++p))
20908 if (ASCII_ISLOWER(*p))
20909 return VAR_FLAVOUR_SESSION;
20910 return VAR_FLAVOUR_VIMINFO;
20912 else
20913 return VAR_FLAVOUR_DEFAULT;
20915 #endif
20917 #if defined(FEAT_VIMINFO) || defined(PROTO)
20919 * Restore global vars that start with a capital from the viminfo file
20922 read_viminfo_varlist(virp, writing)
20923 vir_T *virp;
20924 int writing;
20926 char_u *tab;
20927 int is_string = FALSE;
20928 typval_T tv;
20930 if (!writing && (find_viminfo_parameter('!') != NULL))
20932 tab = vim_strchr(virp->vir_line + 1, '\t');
20933 if (tab != NULL)
20935 *tab++ = '\0'; /* isolate the variable name */
20936 if (*tab == 'S') /* string var */
20937 is_string = TRUE;
20939 tab = vim_strchr(tab, '\t');
20940 if (tab != NULL)
20942 if (is_string)
20944 tv.v_type = VAR_STRING;
20945 tv.vval.v_string = viminfo_readstring(virp,
20946 (int)(tab - virp->vir_line + 1), TRUE);
20948 else
20950 tv.v_type = VAR_NUMBER;
20951 tv.vval.v_number = atol((char *)tab + 1);
20953 set_var(virp->vir_line + 1, &tv, FALSE);
20954 if (is_string)
20955 vim_free(tv.vval.v_string);
20960 return viminfo_readline(virp);
20964 * Write global vars that start with a capital to the viminfo file
20966 void
20967 write_viminfo_varlist(fp)
20968 FILE *fp;
20970 hashitem_T *hi;
20971 dictitem_T *this_var;
20972 int todo;
20973 char *s;
20974 char_u *p;
20975 char_u *tofree;
20976 char_u numbuf[NUMBUFLEN];
20978 if (find_viminfo_parameter('!') == NULL)
20979 return;
20981 fprintf(fp, _("\n# global variables:\n"));
20983 todo = (int)globvarht.ht_used;
20984 for (hi = globvarht.ht_array; todo > 0; ++hi)
20986 if (!HASHITEM_EMPTY(hi))
20988 --todo;
20989 this_var = HI2DI(hi);
20990 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
20992 switch (this_var->di_tv.v_type)
20994 case VAR_STRING: s = "STR"; break;
20995 case VAR_NUMBER: s = "NUM"; break;
20996 default: continue;
20998 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
20999 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
21000 if (p != NULL)
21001 viminfo_writestring(fp, p);
21002 vim_free(tofree);
21007 #endif
21009 #if defined(FEAT_SESSION) || defined(PROTO)
21011 store_session_globals(fd)
21012 FILE *fd;
21014 hashitem_T *hi;
21015 dictitem_T *this_var;
21016 int todo;
21017 char_u *p, *t;
21019 todo = (int)globvarht.ht_used;
21020 for (hi = globvarht.ht_array; todo > 0; ++hi)
21022 if (!HASHITEM_EMPTY(hi))
21024 --todo;
21025 this_var = HI2DI(hi);
21026 if ((this_var->di_tv.v_type == VAR_NUMBER
21027 || this_var->di_tv.v_type == VAR_STRING)
21028 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
21030 /* Escape special characters with a backslash. Turn a LF and
21031 * CR into \n and \r. */
21032 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
21033 (char_u *)"\\\"\n\r");
21034 if (p == NULL) /* out of memory */
21035 break;
21036 for (t = p; *t != NUL; ++t)
21037 if (*t == '\n')
21038 *t = 'n';
21039 else if (*t == '\r')
21040 *t = 'r';
21041 if ((fprintf(fd, "let %s = %c%s%c",
21042 this_var->di_key,
21043 (this_var->di_tv.v_type == VAR_STRING) ? '"'
21044 : ' ',
21046 (this_var->di_tv.v_type == VAR_STRING) ? '"'
21047 : ' ') < 0)
21048 || put_eol(fd) == FAIL)
21050 vim_free(p);
21051 return FAIL;
21053 vim_free(p);
21057 return OK;
21059 #endif
21062 * Display script name where an item was last set.
21063 * Should only be invoked when 'verbose' is non-zero.
21065 void
21066 last_set_msg(scriptID)
21067 scid_T scriptID;
21069 char_u *p;
21071 if (scriptID != 0)
21073 p = home_replace_save(NULL, get_scriptname(scriptID));
21074 if (p != NULL)
21076 verbose_enter();
21077 MSG_PUTS(_("\n\tLast set from "));
21078 MSG_PUTS(p);
21079 vim_free(p);
21080 verbose_leave();
21085 #endif /* FEAT_EVAL */
21087 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
21090 #ifdef WIN3264
21092 * Functions for ":8" filename modifier: get 8.3 version of a filename.
21094 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
21095 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
21096 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
21099 * Get the short path (8.3) for the filename in "fnamep".
21100 * Only works for a valid file name.
21101 * When the path gets longer "fnamep" is changed and the allocated buffer
21102 * is put in "bufp".
21103 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
21104 * Returns OK on success, FAIL on failure.
21106 static int
21107 get_short_pathname(fnamep, bufp, fnamelen)
21108 char_u **fnamep;
21109 char_u **bufp;
21110 int *fnamelen;
21112 int l, len;
21113 char_u *newbuf;
21115 len = *fnamelen;
21116 l = GetShortPathName(*fnamep, *fnamep, len);
21117 if (l > len - 1)
21119 /* If that doesn't work (not enough space), then save the string
21120 * and try again with a new buffer big enough. */
21121 newbuf = vim_strnsave(*fnamep, l);
21122 if (newbuf == NULL)
21123 return FAIL;
21125 vim_free(*bufp);
21126 *fnamep = *bufp = newbuf;
21128 /* Really should always succeed, as the buffer is big enough. */
21129 l = GetShortPathName(*fnamep, *fnamep, l+1);
21132 *fnamelen = l;
21133 return OK;
21137 * Get the short path (8.3) for the filename in "fname". The converted
21138 * path is returned in "bufp".
21140 * Some of the directories specified in "fname" may not exist. This function
21141 * will shorten the existing directories at the beginning of the path and then
21142 * append the remaining non-existing path.
21144 * fname - Pointer to the filename to shorten. On return, contains the
21145 * pointer to the shortened pathname
21146 * bufp - Pointer to an allocated buffer for the filename.
21147 * fnamelen - Length of the filename pointed to by fname
21149 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
21151 static int
21152 shortpath_for_invalid_fname(fname, bufp, fnamelen)
21153 char_u **fname;
21154 char_u **bufp;
21155 int *fnamelen;
21157 char_u *short_fname, *save_fname, *pbuf_unused;
21158 char_u *endp, *save_endp;
21159 char_u ch;
21160 int old_len, len;
21161 int new_len, sfx_len;
21162 int retval = OK;
21164 /* Make a copy */
21165 old_len = *fnamelen;
21166 save_fname = vim_strnsave(*fname, old_len);
21167 pbuf_unused = NULL;
21168 short_fname = NULL;
21170 endp = save_fname + old_len - 1; /* Find the end of the copy */
21171 save_endp = endp;
21174 * Try shortening the supplied path till it succeeds by removing one
21175 * directory at a time from the tail of the path.
21177 len = 0;
21178 for (;;)
21180 /* go back one path-separator */
21181 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
21182 --endp;
21183 if (endp <= save_fname)
21184 break; /* processed the complete path */
21187 * Replace the path separator with a NUL and try to shorten the
21188 * resulting path.
21190 ch = *endp;
21191 *endp = 0;
21192 short_fname = save_fname;
21193 len = STRLEN(short_fname) + 1;
21194 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
21196 retval = FAIL;
21197 goto theend;
21199 *endp = ch; /* preserve the string */
21201 if (len > 0)
21202 break; /* successfully shortened the path */
21204 /* failed to shorten the path. Skip the path separator */
21205 --endp;
21208 if (len > 0)
21211 * Succeeded in shortening the path. Now concatenate the shortened
21212 * path with the remaining path at the tail.
21215 /* Compute the length of the new path. */
21216 sfx_len = (int)(save_endp - endp) + 1;
21217 new_len = len + sfx_len;
21219 *fnamelen = new_len;
21220 vim_free(*bufp);
21221 if (new_len > old_len)
21223 /* There is not enough space in the currently allocated string,
21224 * copy it to a buffer big enough. */
21225 *fname = *bufp = vim_strnsave(short_fname, new_len);
21226 if (*fname == NULL)
21228 retval = FAIL;
21229 goto theend;
21232 else
21234 /* Transfer short_fname to the main buffer (it's big enough),
21235 * unless get_short_pathname() did its work in-place. */
21236 *fname = *bufp = save_fname;
21237 if (short_fname != save_fname)
21238 vim_strncpy(save_fname, short_fname, len);
21239 save_fname = NULL;
21242 /* concat the not-shortened part of the path */
21243 vim_strncpy(*fname + len, endp, sfx_len);
21244 (*fname)[new_len] = NUL;
21247 theend:
21248 vim_free(pbuf_unused);
21249 vim_free(save_fname);
21251 return retval;
21255 * Get a pathname for a partial path.
21256 * Returns OK for success, FAIL for failure.
21258 static int
21259 shortpath_for_partial(fnamep, bufp, fnamelen)
21260 char_u **fnamep;
21261 char_u **bufp;
21262 int *fnamelen;
21264 int sepcount, len, tflen;
21265 char_u *p;
21266 char_u *pbuf, *tfname;
21267 int hasTilde;
21269 /* Count up the path seperators from the RHS.. so we know which part
21270 * of the path to return.
21272 sepcount = 0;
21273 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
21274 if (vim_ispathsep(*p))
21275 ++sepcount;
21277 /* Need full path first (use expand_env() to remove a "~/") */
21278 hasTilde = (**fnamep == '~');
21279 if (hasTilde)
21280 pbuf = tfname = expand_env_save(*fnamep);
21281 else
21282 pbuf = tfname = FullName_save(*fnamep, FALSE);
21284 len = tflen = (int)STRLEN(tfname);
21286 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
21287 return FAIL;
21289 if (len == 0)
21291 /* Don't have a valid filename, so shorten the rest of the
21292 * path if we can. This CAN give us invalid 8.3 filenames, but
21293 * there's not a lot of point in guessing what it might be.
21295 len = tflen;
21296 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
21297 return FAIL;
21300 /* Count the paths backward to find the beginning of the desired string. */
21301 for (p = tfname + len - 1; p >= tfname; --p)
21303 #ifdef FEAT_MBYTE
21304 if (has_mbyte)
21305 p -= mb_head_off(tfname, p);
21306 #endif
21307 if (vim_ispathsep(*p))
21309 if (sepcount == 0 || (hasTilde && sepcount == 1))
21310 break;
21311 else
21312 sepcount --;
21315 if (hasTilde)
21317 --p;
21318 if (p >= tfname)
21319 *p = '~';
21320 else
21321 return FAIL;
21323 else
21324 ++p;
21326 /* Copy in the string - p indexes into tfname - allocated at pbuf */
21327 vim_free(*bufp);
21328 *fnamelen = (int)STRLEN(p);
21329 *bufp = pbuf;
21330 *fnamep = p;
21332 return OK;
21334 #endif /* WIN3264 */
21337 * Adjust a filename, according to a string of modifiers.
21338 * *fnamep must be NUL terminated when called. When returning, the length is
21339 * determined by *fnamelen.
21340 * Returns VALID_ flags or -1 for failure.
21341 * When there is an error, *fnamep is set to NULL.
21344 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
21345 char_u *src; /* string with modifiers */
21346 int *usedlen; /* characters after src that are used */
21347 char_u **fnamep; /* file name so far */
21348 char_u **bufp; /* buffer for allocated file name or NULL */
21349 int *fnamelen; /* length of fnamep */
21351 int valid = 0;
21352 char_u *tail;
21353 char_u *s, *p, *pbuf;
21354 char_u dirname[MAXPATHL];
21355 int c;
21356 int has_fullname = 0;
21357 #ifdef WIN3264
21358 int has_shortname = 0;
21359 #endif
21361 repeat:
21362 /* ":p" - full path/file_name */
21363 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
21365 has_fullname = 1;
21367 valid |= VALID_PATH;
21368 *usedlen += 2;
21370 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
21371 if ((*fnamep)[0] == '~'
21372 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
21373 && ((*fnamep)[1] == '/'
21374 # ifdef BACKSLASH_IN_FILENAME
21375 || (*fnamep)[1] == '\\'
21376 # endif
21377 || (*fnamep)[1] == NUL)
21379 #endif
21382 *fnamep = expand_env_save(*fnamep);
21383 vim_free(*bufp); /* free any allocated file name */
21384 *bufp = *fnamep;
21385 if (*fnamep == NULL)
21386 return -1;
21389 /* When "/." or "/.." is used: force expansion to get rid of it. */
21390 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
21392 if (vim_ispathsep(*p)
21393 && p[1] == '.'
21394 && (p[2] == NUL
21395 || vim_ispathsep(p[2])
21396 || (p[2] == '.'
21397 && (p[3] == NUL || vim_ispathsep(p[3])))))
21398 break;
21401 /* FullName_save() is slow, don't use it when not needed. */
21402 if (*p != NUL || !vim_isAbsName(*fnamep))
21404 *fnamep = FullName_save(*fnamep, *p != NUL);
21405 vim_free(*bufp); /* free any allocated file name */
21406 *bufp = *fnamep;
21407 if (*fnamep == NULL)
21408 return -1;
21411 /* Append a path separator to a directory. */
21412 if (mch_isdir(*fnamep))
21414 /* Make room for one or two extra characters. */
21415 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
21416 vim_free(*bufp); /* free any allocated file name */
21417 *bufp = *fnamep;
21418 if (*fnamep == NULL)
21419 return -1;
21420 add_pathsep(*fnamep);
21424 /* ":." - path relative to the current directory */
21425 /* ":~" - path relative to the home directory */
21426 /* ":8" - shortname path - postponed till after */
21427 while (src[*usedlen] == ':'
21428 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
21430 *usedlen += 2;
21431 if (c == '8')
21433 #ifdef WIN3264
21434 has_shortname = 1; /* Postpone this. */
21435 #endif
21436 continue;
21438 pbuf = NULL;
21439 /* Need full path first (use expand_env() to remove a "~/") */
21440 if (!has_fullname)
21442 if (c == '.' && **fnamep == '~')
21443 p = pbuf = expand_env_save(*fnamep);
21444 else
21445 p = pbuf = FullName_save(*fnamep, FALSE);
21447 else
21448 p = *fnamep;
21450 has_fullname = 0;
21452 if (p != NULL)
21454 if (c == '.')
21456 mch_dirname(dirname, MAXPATHL);
21457 s = shorten_fname(p, dirname);
21458 if (s != NULL)
21460 *fnamep = s;
21461 if (pbuf != NULL)
21463 vim_free(*bufp); /* free any allocated file name */
21464 *bufp = pbuf;
21465 pbuf = NULL;
21469 else
21471 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
21472 /* Only replace it when it starts with '~' */
21473 if (*dirname == '~')
21475 s = vim_strsave(dirname);
21476 if (s != NULL)
21478 *fnamep = s;
21479 vim_free(*bufp);
21480 *bufp = s;
21484 vim_free(pbuf);
21488 tail = gettail(*fnamep);
21489 *fnamelen = (int)STRLEN(*fnamep);
21491 /* ":h" - head, remove "/file_name", can be repeated */
21492 /* Don't remove the first "/" or "c:\" */
21493 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
21495 valid |= VALID_HEAD;
21496 *usedlen += 2;
21497 s = get_past_head(*fnamep);
21498 while (tail > s && after_pathsep(s, tail))
21499 mb_ptr_back(*fnamep, tail);
21500 *fnamelen = (int)(tail - *fnamep);
21501 #ifdef VMS
21502 if (*fnamelen > 0)
21503 *fnamelen += 1; /* the path separator is part of the path */
21504 #endif
21505 if (*fnamelen == 0)
21507 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
21508 p = vim_strsave((char_u *)".");
21509 if (p == NULL)
21510 return -1;
21511 vim_free(*bufp);
21512 *bufp = *fnamep = tail = p;
21513 *fnamelen = 1;
21515 else
21517 while (tail > s && !after_pathsep(s, tail))
21518 mb_ptr_back(*fnamep, tail);
21522 /* ":8" - shortname */
21523 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
21525 *usedlen += 2;
21526 #ifdef WIN3264
21527 has_shortname = 1;
21528 #endif
21531 #ifdef WIN3264
21532 /* Check shortname after we have done 'heads' and before we do 'tails'
21534 if (has_shortname)
21536 pbuf = NULL;
21537 /* Copy the string if it is shortened by :h */
21538 if (*fnamelen < (int)STRLEN(*fnamep))
21540 p = vim_strnsave(*fnamep, *fnamelen);
21541 if (p == 0)
21542 return -1;
21543 vim_free(*bufp);
21544 *bufp = *fnamep = p;
21547 /* Split into two implementations - makes it easier. First is where
21548 * there isn't a full name already, second is where there is.
21550 if (!has_fullname && !vim_isAbsName(*fnamep))
21552 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
21553 return -1;
21555 else
21557 int l;
21559 /* Simple case, already have the full-name
21560 * Nearly always shorter, so try first time. */
21561 l = *fnamelen;
21562 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
21563 return -1;
21565 if (l == 0)
21567 /* Couldn't find the filename.. search the paths.
21569 l = *fnamelen;
21570 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
21571 return -1;
21573 *fnamelen = l;
21576 #endif /* WIN3264 */
21578 /* ":t" - tail, just the basename */
21579 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
21581 *usedlen += 2;
21582 *fnamelen -= (int)(tail - *fnamep);
21583 *fnamep = tail;
21586 /* ":e" - extension, can be repeated */
21587 /* ":r" - root, without extension, can be repeated */
21588 while (src[*usedlen] == ':'
21589 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
21591 /* find a '.' in the tail:
21592 * - for second :e: before the current fname
21593 * - otherwise: The last '.'
21595 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
21596 s = *fnamep - 2;
21597 else
21598 s = *fnamep + *fnamelen - 1;
21599 for ( ; s > tail; --s)
21600 if (s[0] == '.')
21601 break;
21602 if (src[*usedlen + 1] == 'e') /* :e */
21604 if (s > tail)
21606 *fnamelen += (int)(*fnamep - (s + 1));
21607 *fnamep = s + 1;
21608 #ifdef VMS
21609 /* cut version from the extension */
21610 s = *fnamep + *fnamelen - 1;
21611 for ( ; s > *fnamep; --s)
21612 if (s[0] == ';')
21613 break;
21614 if (s > *fnamep)
21615 *fnamelen = s - *fnamep;
21616 #endif
21618 else if (*fnamep <= tail)
21619 *fnamelen = 0;
21621 else /* :r */
21623 if (s > tail) /* remove one extension */
21624 *fnamelen = (int)(s - *fnamep);
21626 *usedlen += 2;
21629 /* ":s?pat?foo?" - substitute */
21630 /* ":gs?pat?foo?" - global substitute */
21631 if (src[*usedlen] == ':'
21632 && (src[*usedlen + 1] == 's'
21633 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
21635 char_u *str;
21636 char_u *pat;
21637 char_u *sub;
21638 int sep;
21639 char_u *flags;
21640 int didit = FALSE;
21642 flags = (char_u *)"";
21643 s = src + *usedlen + 2;
21644 if (src[*usedlen + 1] == 'g')
21646 flags = (char_u *)"g";
21647 ++s;
21650 sep = *s++;
21651 if (sep)
21653 /* find end of pattern */
21654 p = vim_strchr(s, sep);
21655 if (p != NULL)
21657 pat = vim_strnsave(s, (int)(p - s));
21658 if (pat != NULL)
21660 s = p + 1;
21661 /* find end of substitution */
21662 p = vim_strchr(s, sep);
21663 if (p != NULL)
21665 sub = vim_strnsave(s, (int)(p - s));
21666 str = vim_strnsave(*fnamep, *fnamelen);
21667 if (sub != NULL && str != NULL)
21669 *usedlen = (int)(p + 1 - src);
21670 s = do_string_sub(str, pat, sub, flags);
21671 if (s != NULL)
21673 *fnamep = s;
21674 *fnamelen = (int)STRLEN(s);
21675 vim_free(*bufp);
21676 *bufp = s;
21677 didit = TRUE;
21680 vim_free(sub);
21681 vim_free(str);
21683 vim_free(pat);
21686 /* after using ":s", repeat all the modifiers */
21687 if (didit)
21688 goto repeat;
21692 return valid;
21696 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
21697 * "flags" can be "g" to do a global substitute.
21698 * Returns an allocated string, NULL for error.
21700 char_u *
21701 do_string_sub(str, pat, sub, flags)
21702 char_u *str;
21703 char_u *pat;
21704 char_u *sub;
21705 char_u *flags;
21707 int sublen;
21708 regmatch_T regmatch;
21709 int i;
21710 int do_all;
21711 char_u *tail;
21712 garray_T ga;
21713 char_u *ret;
21714 char_u *save_cpo;
21716 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
21717 save_cpo = p_cpo;
21718 p_cpo = (char_u *)"";
21720 ga_init2(&ga, 1, 200);
21722 do_all = (flags[0] == 'g');
21724 regmatch.rm_ic = p_ic;
21725 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
21726 if (regmatch.regprog != NULL)
21728 tail = str;
21729 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
21732 * Get some space for a temporary buffer to do the substitution
21733 * into. It will contain:
21734 * - The text up to where the match is.
21735 * - The substituted text.
21736 * - The text after the match.
21738 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
21739 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
21740 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
21742 ga_clear(&ga);
21743 break;
21746 /* copy the text up to where the match is */
21747 i = (int)(regmatch.startp[0] - tail);
21748 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
21749 /* add the substituted text */
21750 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
21751 + ga.ga_len + i, TRUE, TRUE, FALSE);
21752 ga.ga_len += i + sublen - 1;
21753 /* avoid getting stuck on a match with an empty string */
21754 if (tail == regmatch.endp[0])
21756 if (*tail == NUL)
21757 break;
21758 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
21759 ++ga.ga_len;
21761 else
21763 tail = regmatch.endp[0];
21764 if (*tail == NUL)
21765 break;
21767 if (!do_all)
21768 break;
21771 if (ga.ga_data != NULL)
21772 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
21774 vim_free(regmatch.regprog);
21777 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
21778 ga_clear(&ga);
21779 p_cpo = save_cpo;
21781 return ret;
21784 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */