Merged from the latest developing branch.
[MacVim/jjgod.git] / src / eval.c
blob77d641374ec494ce3b4a0684d366a5ab4b77412e
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
11 * eval.c: Expression evaluation.
13 #if defined(MSDOS) || defined(MSWIN)
14 # include "vimio.h" /* for mch_open(), must be before vim.h */
15 #endif
17 #include "vim.h"
19 #ifdef AMIGA
20 # include <time.h> /* for strftime() */
21 #endif
23 #ifdef MACOS
24 # include <time.h> /* for time_t */
25 #endif
27 #ifdef HAVE_FCNTL_H
28 # include <fcntl.h>
29 #endif
31 #if defined(FEAT_EVAL) || defined(PROTO)
33 #define DICT_MAXNEST 100 /* maximum nesting of lists and dicts */
36 * In a hashtab item "hi_key" points to "di_key" in a dictitem.
37 * This avoids adding a pointer to the hashtab item.
38 * DI2HIKEY() converts a dictitem pointer to a hashitem key pointer.
39 * HIKEY2DI() converts a hashitem key pointer to a dictitem pointer.
40 * HI2DI() converts a hashitem pointer to a dictitem pointer.
42 static dictitem_T dumdi;
43 #define DI2HIKEY(di) ((di)->di_key)
44 #define HIKEY2DI(p) ((dictitem_T *)(p - (dumdi.di_key - (char_u *)&dumdi)))
45 #define HI2DI(hi) HIKEY2DI((hi)->hi_key)
48 * Structure returned by get_lval() and used by set_var_lval().
49 * For a plain name:
50 * "name" points to the variable name.
51 * "exp_name" is NULL.
52 * "tv" is NULL
53 * For a magic braces name:
54 * "name" points to the expanded variable name.
55 * "exp_name" is non-NULL, to be freed later.
56 * "tv" is NULL
57 * For an index in a list:
58 * "name" points to the (expanded) variable name.
59 * "exp_name" NULL or non-NULL, to be freed later.
60 * "tv" points to the (first) list item value
61 * "li" points to the (first) list item
62 * "range", "n1", "n2" and "empty2" indicate what items are used.
63 * For an existing Dict item:
64 * "name" points to the (expanded) variable name.
65 * "exp_name" NULL or non-NULL, to be freed later.
66 * "tv" points to the dict item value
67 * "newkey" is NULL
68 * For a non-existing Dict item:
69 * "name" points to the (expanded) variable name.
70 * "exp_name" NULL or non-NULL, to be freed later.
71 * "tv" points to the Dictionary typval_T
72 * "newkey" is the key for the new item.
74 typedef struct lval_S
76 char_u *ll_name; /* start of variable name (can be NULL) */
77 char_u *ll_exp_name; /* NULL or expanded name in allocated memory. */
78 typval_T *ll_tv; /* Typeval of item being used. If "newkey"
79 isn't NULL it's the Dict to which to add
80 the item. */
81 listitem_T *ll_li; /* The list item or NULL. */
82 list_T *ll_list; /* The list or NULL. */
83 int ll_range; /* TRUE when a [i:j] range was used */
84 long ll_n1; /* First index for list */
85 long ll_n2; /* Second index for list range */
86 int ll_empty2; /* Second index is empty: [i:] */
87 dict_T *ll_dict; /* The Dictionary or NULL */
88 dictitem_T *ll_di; /* The dictitem or NULL */
89 char_u *ll_newkey; /* New key for Dict in alloc. mem or NULL. */
90 } lval_T;
93 static char *e_letunexp = N_("E18: Unexpected characters in :let");
94 static char *e_listidx = N_("E684: list index out of range: %ld");
95 static char *e_undefvar = N_("E121: Undefined variable: %s");
96 static char *e_missbrac = N_("E111: Missing ']'");
97 static char *e_listarg = N_("E686: Argument of %s must be a List");
98 static char *e_listdictarg = N_("E712: Argument of %s must be a List or Dictionary");
99 static char *e_emptykey = N_("E713: Cannot use empty key for Dictionary");
100 static char *e_listreq = N_("E714: List required");
101 static char *e_dictreq = N_("E715: Dictionary required");
102 static char *e_toomanyarg = N_("E118: Too many arguments for function: %s");
103 static char *e_dictkey = N_("E716: Key not present in Dictionary: %s");
104 static char *e_funcexts = N_("E122: Function %s already exists, add ! to replace it");
105 static char *e_funcdict = N_("E717: Dictionary entry already exists");
106 static char *e_funcref = N_("E718: Funcref required");
107 static char *e_dictrange = N_("E719: Cannot use [:] with a Dictionary");
108 static char *e_letwrong = N_("E734: Wrong variable type for %s=");
109 static char *e_nofunc = N_("E130: Unknown function: %s");
110 static char *e_illvar = N_("E461: Illegal variable name: %s");
112 * All user-defined global variables are stored in dictionary "globvardict".
113 * "globvars_var" is the variable that is used for "g:".
115 static dict_T globvardict;
116 static dictitem_T globvars_var;
117 #define globvarht globvardict.dv_hashtab
120 * Old Vim variables such as "v:version" are also available without the "v:".
121 * Also in functions. We need a special hashtable for them.
123 static hashtab_T compat_hashtab;
126 * When recursively copying lists and dicts we need to remember which ones we
127 * have done to avoid endless recursiveness. This unique ID is used for that.
129 static int current_copyID = 0;
132 * Array to hold the hashtab with variables local to each sourced script.
133 * Each item holds a variable (nameless) that points to the dict_T.
135 typedef struct
137 dictitem_T sv_var;
138 dict_T sv_dict;
139 } scriptvar_T;
141 static garray_T ga_scripts = {0, 0, sizeof(scriptvar_T), 4, NULL};
142 #define SCRIPT_SV(id) (((scriptvar_T *)ga_scripts.ga_data)[(id) - 1])
143 #define SCRIPT_VARS(id) (SCRIPT_SV(id).sv_dict.dv_hashtab)
145 static int echo_attr = 0; /* attributes used for ":echo" */
147 /* Values for trans_function_name() argument: */
148 #define TFN_INT 1 /* internal function name OK */
149 #define TFN_QUIET 2 /* no error messages */
152 * Structure to hold info for a user function.
154 typedef struct ufunc ufunc_T;
156 struct ufunc
158 int uf_varargs; /* variable nr of arguments */
159 int uf_flags;
160 int uf_calls; /* nr of active calls */
161 garray_T uf_args; /* arguments */
162 garray_T uf_lines; /* function lines */
163 #ifdef FEAT_PROFILE
164 int uf_profiling; /* TRUE when func is being profiled */
165 /* profiling the function as a whole */
166 int uf_tm_count; /* nr of calls */
167 proftime_T uf_tm_total; /* time spend in function + children */
168 proftime_T uf_tm_self; /* time spend in function itself */
169 proftime_T uf_tm_children; /* time spent in children this call */
170 /* profiling the function per line */
171 int *uf_tml_count; /* nr of times line was executed */
172 proftime_T *uf_tml_total; /* time spend in a line + children */
173 proftime_T *uf_tml_self; /* time spend in a line itself */
174 proftime_T uf_tml_start; /* start time for current line */
175 proftime_T uf_tml_children; /* time spent in children for this line */
176 proftime_T uf_tml_wait; /* start wait time for current line */
177 int uf_tml_idx; /* index of line being timed; -1 if none */
178 int uf_tml_execed; /* line being timed was executed */
179 #endif
180 scid_T uf_script_ID; /* ID of script where function was defined,
181 used for s: variables */
182 int uf_refcount; /* for numbered function: reference count */
183 char_u uf_name[1]; /* name of function (actually longer); can
184 start with <SNR>123_ (<SNR> is K_SPECIAL
185 KS_EXTRA KE_SNR) */
188 /* function flags */
189 #define FC_ABORT 1 /* abort function on error */
190 #define FC_RANGE 2 /* function accepts range */
191 #define FC_DICT 4 /* Dict function, uses "self" */
194 * All user-defined functions are found in this hashtable.
196 static hashtab_T func_hashtab;
198 /* The names of packages that once were loaded are remembered. */
199 static garray_T ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
201 /* list heads for garbage collection */
202 static dict_T *first_dict = NULL; /* list of all dicts */
203 static list_T *first_list = NULL; /* list of all lists */
205 /* From user function to hashitem and back. */
206 static ufunc_T dumuf;
207 #define UF2HIKEY(fp) ((fp)->uf_name)
208 #define HIKEY2UF(p) ((ufunc_T *)(p - (dumuf.uf_name - (char_u *)&dumuf)))
209 #define HI2UF(hi) HIKEY2UF((hi)->hi_key)
211 #define FUNCARG(fp, j) ((char_u **)(fp->uf_args.ga_data))[j]
212 #define FUNCLINE(fp, j) ((char_u **)(fp->uf_lines.ga_data))[j]
214 #define MAX_FUNC_ARGS 20 /* maximum number of function arguments */
215 #define VAR_SHORT_LEN 20 /* short variable name length */
216 #define FIXVAR_CNT 12 /* number of fixed variables */
218 /* structure to hold info for a function that is currently being executed. */
219 typedef struct funccall_S funccall_T;
221 struct funccall_S
223 ufunc_T *func; /* function being called */
224 int linenr; /* next line to be executed */
225 int returned; /* ":return" used */
226 struct /* fixed variables for arguments */
228 dictitem_T var; /* variable (without room for name) */
229 char_u room[VAR_SHORT_LEN]; /* room for the name */
230 } fixvar[FIXVAR_CNT];
231 dict_T l_vars; /* l: local function variables */
232 dictitem_T l_vars_var; /* variable for l: scope */
233 dict_T l_avars; /* a: argument variables */
234 dictitem_T l_avars_var; /* variable for a: scope */
235 list_T l_varlist; /* list for a:000 */
236 listitem_T l_listitems[MAX_FUNC_ARGS]; /* listitems for a:000 */
237 typval_T *rettv; /* return value */
238 linenr_T breakpoint; /* next line with breakpoint or zero */
239 int dbg_tick; /* debug_tick when breakpoint was set */
240 int level; /* top nesting level of executed function */
241 #ifdef FEAT_PROFILE
242 proftime_T prof_child; /* time spent in a child */
243 #endif
244 funccall_T *caller; /* calling function or NULL */
248 * Info used by a ":for" loop.
250 typedef struct
252 int fi_semicolon; /* TRUE if ending in '; var]' */
253 int fi_varcount; /* nr of variables in the list */
254 listwatch_T fi_lw; /* keep an eye on the item used. */
255 list_T *fi_list; /* list being used */
256 } forinfo_T;
259 * Struct used by trans_function_name()
261 typedef struct
263 dict_T *fd_dict; /* Dictionary used */
264 char_u *fd_newkey; /* new key in "dict" in allocated memory */
265 dictitem_T *fd_di; /* Dictionary item used */
266 } funcdict_T;
270 * Array to hold the value of v: variables.
271 * The value is in a dictitem, so that it can also be used in the v: scope.
272 * The reason to use this table anyway is for very quick access to the
273 * variables with the VV_ defines.
275 #include "version.h"
277 /* values for vv_flags: */
278 #define VV_COMPAT 1 /* compatible, also used without "v:" */
279 #define VV_RO 2 /* read-only */
280 #define VV_RO_SBX 4 /* read-only in the sandbox */
282 #define VV_NAME(s, t) s, {{t}}, {0}
284 static struct vimvar
286 char *vv_name; /* name of variable, without v: */
287 dictitem_T vv_di; /* value and name for key */
288 char vv_filler[16]; /* space for LONGEST name below!!! */
289 char vv_flags; /* VV_COMPAT, VV_RO, VV_RO_SBX */
290 } vimvars[VV_LEN] =
293 * The order here must match the VV_ defines in vim.h!
294 * Initializing a union does not work, leave tv.vval empty to get zero's.
296 {VV_NAME("count", VAR_NUMBER), VV_COMPAT+VV_RO},
297 {VV_NAME("count1", VAR_NUMBER), VV_RO},
298 {VV_NAME("prevcount", VAR_NUMBER), VV_RO},
299 {VV_NAME("errmsg", VAR_STRING), VV_COMPAT},
300 {VV_NAME("warningmsg", VAR_STRING), 0},
301 {VV_NAME("statusmsg", VAR_STRING), 0},
302 {VV_NAME("shell_error", VAR_NUMBER), VV_COMPAT+VV_RO},
303 {VV_NAME("this_session", VAR_STRING), VV_COMPAT},
304 {VV_NAME("version", VAR_NUMBER), VV_COMPAT+VV_RO},
305 {VV_NAME("lnum", VAR_NUMBER), VV_RO_SBX},
306 {VV_NAME("termresponse", VAR_STRING), VV_RO},
307 {VV_NAME("fname", VAR_STRING), VV_RO},
308 {VV_NAME("lang", VAR_STRING), VV_RO},
309 {VV_NAME("lc_time", VAR_STRING), VV_RO},
310 {VV_NAME("ctype", VAR_STRING), VV_RO},
311 {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
312 {VV_NAME("charconvert_to", VAR_STRING), VV_RO},
313 {VV_NAME("fname_in", VAR_STRING), VV_RO},
314 {VV_NAME("fname_out", VAR_STRING), VV_RO},
315 {VV_NAME("fname_new", VAR_STRING), VV_RO},
316 {VV_NAME("fname_diff", VAR_STRING), VV_RO},
317 {VV_NAME("cmdarg", VAR_STRING), VV_RO},
318 {VV_NAME("foldstart", VAR_NUMBER), VV_RO_SBX},
319 {VV_NAME("foldend", VAR_NUMBER), VV_RO_SBX},
320 {VV_NAME("folddashes", VAR_STRING), VV_RO_SBX},
321 {VV_NAME("foldlevel", VAR_NUMBER), VV_RO_SBX},
322 {VV_NAME("progname", VAR_STRING), VV_RO},
323 {VV_NAME("servername", VAR_STRING), VV_RO},
324 {VV_NAME("dying", VAR_NUMBER), VV_RO},
325 {VV_NAME("exception", VAR_STRING), VV_RO},
326 {VV_NAME("throwpoint", VAR_STRING), VV_RO},
327 {VV_NAME("register", VAR_STRING), VV_RO},
328 {VV_NAME("cmdbang", VAR_NUMBER), VV_RO},
329 {VV_NAME("insertmode", VAR_STRING), VV_RO},
330 {VV_NAME("val", VAR_UNKNOWN), VV_RO},
331 {VV_NAME("key", VAR_UNKNOWN), VV_RO},
332 {VV_NAME("profiling", VAR_NUMBER), VV_RO},
333 {VV_NAME("fcs_reason", VAR_STRING), VV_RO},
334 {VV_NAME("fcs_choice", VAR_STRING), 0},
335 {VV_NAME("beval_bufnr", VAR_NUMBER), VV_RO},
336 {VV_NAME("beval_winnr", VAR_NUMBER), VV_RO},
337 {VV_NAME("beval_lnum", VAR_NUMBER), VV_RO},
338 {VV_NAME("beval_col", VAR_NUMBER), VV_RO},
339 {VV_NAME("beval_text", VAR_STRING), VV_RO},
340 {VV_NAME("scrollstart", VAR_STRING), 0},
341 {VV_NAME("swapname", VAR_STRING), VV_RO},
342 {VV_NAME("swapchoice", VAR_STRING), 0},
343 {VV_NAME("swapcommand", VAR_STRING), VV_RO},
344 {VV_NAME("char", VAR_STRING), VV_RO},
345 {VV_NAME("mouse_win", VAR_NUMBER), 0},
346 {VV_NAME("mouse_lnum", VAR_NUMBER), 0},
347 {VV_NAME("mouse_col", VAR_NUMBER), 0},
350 /* shorthand */
351 #define vv_type vv_di.di_tv.v_type
352 #define vv_nr vv_di.di_tv.vval.v_number
353 #define vv_str vv_di.di_tv.vval.v_string
354 #define vv_tv vv_di.di_tv
357 * The v: variables are stored in dictionary "vimvardict".
358 * "vimvars_var" is the variable that is used for the "l:" scope.
360 static dict_T vimvardict;
361 static dictitem_T vimvars_var;
362 #define vimvarht vimvardict.dv_hashtab
364 static void prepare_vimvar __ARGS((int idx, typval_T *save_tv));
365 static void restore_vimvar __ARGS((int idx, typval_T *save_tv));
366 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
367 static int call_vim_function __ARGS((char_u *func, int argc, char_u **argv, int safe, typval_T *rettv));
368 #endif
369 static int ex_let_vars __ARGS((char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars));
370 static char_u *skip_var_list __ARGS((char_u *arg, int *var_count, int *semicolon));
371 static char_u *skip_var_one __ARGS((char_u *arg));
372 static void list_hashtable_vars __ARGS((hashtab_T *ht, char_u *prefix, int empty, int *first));
373 static void list_glob_vars __ARGS((int *first));
374 static void list_buf_vars __ARGS((int *first));
375 static void list_win_vars __ARGS((int *first));
376 #ifdef FEAT_WINDOWS
377 static void list_tab_vars __ARGS((int *first));
378 #endif
379 static void list_vim_vars __ARGS((int *first));
380 static void list_script_vars __ARGS((int *first));
381 static void list_func_vars __ARGS((int *first));
382 static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg, int *first));
383 static char_u *ex_let_one __ARGS((char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op));
384 static int check_changedtick __ARGS((char_u *arg));
385 static char_u *get_lval __ARGS((char_u *name, typval_T *rettv, lval_T *lp, int unlet, int skip, int quiet, int fne_flags));
386 static void clear_lval __ARGS((lval_T *lp));
387 static void set_var_lval __ARGS((lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op));
388 static int tv_op __ARGS((typval_T *tv1, typval_T *tv2, char_u *op));
389 static void list_add_watch __ARGS((list_T *l, listwatch_T *lw));
390 static void list_rem_watch __ARGS((list_T *l, listwatch_T *lwrem));
391 static void list_fix_watch __ARGS((list_T *l, listitem_T *item));
392 static void ex_unletlock __ARGS((exarg_T *eap, char_u *argstart, int deep));
393 static int do_unlet_var __ARGS((lval_T *lp, char_u *name_end, int forceit));
394 static int do_lock_var __ARGS((lval_T *lp, char_u *name_end, int deep, int lock));
395 static void item_lock __ARGS((typval_T *tv, int deep, int lock));
396 static int tv_islocked __ARGS((typval_T *tv));
398 static int eval0 __ARGS((char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate));
399 static int eval1 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
400 static int eval2 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
401 static int eval3 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
402 static int eval4 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
403 static int eval5 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
404 static int eval6 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
405 static int eval7 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
407 static int eval_index __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
408 static int get_option_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
409 static int get_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
410 static int get_lit_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
411 static int get_list_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
412 static int rettv_list_alloc __ARGS((typval_T *rettv));
413 static listitem_T *listitem_alloc __ARGS((void));
414 static void listitem_free __ARGS((listitem_T *item));
415 static void listitem_remove __ARGS((list_T *l, listitem_T *item));
416 static long list_len __ARGS((list_T *l));
417 static int list_equal __ARGS((list_T *l1, list_T *l2, int ic));
418 static int dict_equal __ARGS((dict_T *d1, dict_T *d2, int ic));
419 static int tv_equal __ARGS((typval_T *tv1, typval_T *tv2, int ic));
420 static listitem_T *list_find __ARGS((list_T *l, long n));
421 static long list_find_nr __ARGS((list_T *l, long idx, int *errorp));
422 static long list_idx_of_item __ARGS((list_T *l, listitem_T *item));
423 static void list_append __ARGS((list_T *l, listitem_T *item));
424 static int list_append_tv __ARGS((list_T *l, typval_T *tv));
425 static int list_append_string __ARGS((list_T *l, char_u *str, int len));
426 static int list_append_number __ARGS((list_T *l, varnumber_T n));
427 static int list_insert_tv __ARGS((list_T *l, typval_T *tv, listitem_T *item));
428 static int list_extend __ARGS((list_T *l1, list_T *l2, listitem_T *bef));
429 static int list_concat __ARGS((list_T *l1, list_T *l2, typval_T *tv));
430 static list_T *list_copy __ARGS((list_T *orig, int deep, int copyID));
431 static void list_remove __ARGS((list_T *l, listitem_T *item, listitem_T *item2));
432 static char_u *list2string __ARGS((typval_T *tv, int copyID));
433 static int list_join __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo, int copyID));
434 static void set_ref_in_ht __ARGS((hashtab_T *ht, int copyID));
435 static void set_ref_in_list __ARGS((list_T *l, int copyID));
436 static void set_ref_in_item __ARGS((typval_T *tv, int copyID));
437 static void dict_unref __ARGS((dict_T *d));
438 static void dict_free __ARGS((dict_T *d, int recurse));
439 static dictitem_T *dictitem_alloc __ARGS((char_u *key));
440 static dictitem_T *dictitem_copy __ARGS((dictitem_T *org));
441 static void dictitem_remove __ARGS((dict_T *dict, dictitem_T *item));
442 static void dictitem_free __ARGS((dictitem_T *item));
443 static dict_T *dict_copy __ARGS((dict_T *orig, int deep, int copyID));
444 static int dict_add __ARGS((dict_T *d, dictitem_T *item));
445 static long dict_len __ARGS((dict_T *d));
446 static dictitem_T *dict_find __ARGS((dict_T *d, char_u *key, int len));
447 static char_u *dict2string __ARGS((typval_T *tv, int copyID));
448 static int get_dict_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
449 static char_u *echo_string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
450 static char_u *tv2string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
451 static char_u *string_quote __ARGS((char_u *str, int function));
452 static int get_env_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
453 static int find_internal_func __ARGS((char_u *name));
454 static char_u *deref_func_name __ARGS((char_u *name, int *lenp));
455 static int get_func_tv __ARGS((char_u *name, int len, typval_T *rettv, char_u **arg, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
456 static int call_func __ARGS((char_u *name, int len, typval_T *rettv, int argcount, typval_T *argvars, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
457 static void emsg_funcname __ARGS((char *ermsg, char_u *name));
459 static void f_add __ARGS((typval_T *argvars, typval_T *rettv));
460 static void f_append __ARGS((typval_T *argvars, typval_T *rettv));
461 static void f_argc __ARGS((typval_T *argvars, typval_T *rettv));
462 static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv));
463 static void f_argv __ARGS((typval_T *argvars, typval_T *rettv));
464 static void f_browse __ARGS((typval_T *argvars, typval_T *rettv));
465 static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv));
466 static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv));
467 static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv));
468 static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv));
469 static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv));
470 static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv));
471 static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv));
472 static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv));
473 static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv));
474 static void f_call __ARGS((typval_T *argvars, typval_T *rettv));
475 static void f_changenr __ARGS((typval_T *argvars, typval_T *rettv));
476 static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv));
477 static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv));
478 static void f_clearmatches __ARGS((typval_T *argvars, typval_T *rettv));
479 static void f_col __ARGS((typval_T *argvars, typval_T *rettv));
480 #if defined(FEAT_INS_EXPAND)
481 static void f_complete __ARGS((typval_T *argvars, typval_T *rettv));
482 static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv));
483 static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv));
484 #endif
485 static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv));
486 static void f_copy __ARGS((typval_T *argvars, typval_T *rettv));
487 static void f_count __ARGS((typval_T *argvars, typval_T *rettv));
488 static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv));
489 static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv));
490 static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv));
491 static void f_delete __ARGS((typval_T *argvars, typval_T *rettv));
492 static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv));
493 static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv));
494 static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv));
495 static void f_empty __ARGS((typval_T *argvars, typval_T *rettv));
496 static void f_escape __ARGS((typval_T *argvars, typval_T *rettv));
497 static void f_eval __ARGS((typval_T *argvars, typval_T *rettv));
498 static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv));
499 static void f_executable __ARGS((typval_T *argvars, typval_T *rettv));
500 static void f_exists __ARGS((typval_T *argvars, typval_T *rettv));
501 static void f_expand __ARGS((typval_T *argvars, typval_T *rettv));
502 static void f_extend __ARGS((typval_T *argvars, typval_T *rettv));
503 static void f_feedkeys __ARGS((typval_T *argvars, typval_T *rettv));
504 static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv));
505 static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv));
506 static void f_filter __ARGS((typval_T *argvars, typval_T *rettv));
507 static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv));
508 static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv));
509 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
510 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
511 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
513 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
514 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
516 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
517 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
520 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
521 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
523 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
524 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
525 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
526 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
528 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
529 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
531 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
532 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
533 static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv));
534 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
535 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
536 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
537 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
542 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
546 static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv));
547 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
548 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
549 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
551 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
552 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
590 #ifdef vim_mkdir
591 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
592 #endif
593 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
594 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
595 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
596 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
603 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
604 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
605 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
606 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
607 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
608 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
609 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
610 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
611 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
618 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
619 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
620 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
621 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
622 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
623 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
624 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
625 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
626 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
627 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
628 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
629 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
630 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
631 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
632 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
633 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
634 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
635 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
636 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
637 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
638 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
639 #ifdef HAVE_STRFTIME
640 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
641 #endif
642 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
643 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
644 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
645 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
646 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
647 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
648 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
649 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
650 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
651 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
652 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
653 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
654 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
655 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
656 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
657 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
667 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
668 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
669 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
670 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
671 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
672 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
673 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
674 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
675 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
676 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
677 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
679 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
680 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
681 static int get_env_len __ARGS((char_u **arg));
682 static int get_id_len __ARGS((char_u **arg));
683 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
684 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
685 #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */
686 #define FNE_CHECK_START 2 /* find_name_end(): check name starts with
687 valid character */
688 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
689 static int eval_isnamec __ARGS((int c));
690 static int eval_isnamec1 __ARGS((int c));
691 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
692 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
693 static typval_T *alloc_tv __ARGS((void));
694 static typval_T *alloc_string_tv __ARGS((char_u *string));
695 static void init_tv __ARGS((typval_T *varp));
696 static long get_tv_number __ARGS((typval_T *varp));
697 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
698 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
699 static char_u *get_tv_string __ARGS((typval_T *varp));
700 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
701 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
702 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
703 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
704 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
705 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
706 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
707 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
708 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
709 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
710 static int var_check_ro __ARGS((int flags, char_u *name));
711 static int var_check_fixed __ARGS((int flags, char_u *name));
712 static int tv_check_lock __ARGS((int lock, char_u *name));
713 static void copy_tv __ARGS((typval_T *from, typval_T *to));
714 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
715 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
716 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
717 static int eval_fname_script __ARGS((char_u *p));
718 static int eval_fname_sid __ARGS((char_u *p));
719 static void list_func_head __ARGS((ufunc_T *fp, int indent));
720 static ufunc_T *find_func __ARGS((char_u *name));
721 static int function_exists __ARGS((char_u *name));
722 static int builtin_function __ARGS((char_u *name));
723 #ifdef FEAT_PROFILE
724 static void func_do_profile __ARGS((ufunc_T *fp));
725 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
726 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
727 static int
728 # ifdef __BORLANDC__
729 _RTLENTRYF
730 # endif
731 prof_total_cmp __ARGS((const void *s1, const void *s2));
732 static int
733 # ifdef __BORLANDC__
734 _RTLENTRYF
735 # endif
736 prof_self_cmp __ARGS((const void *s1, const void *s2));
737 #endif
738 static int script_autoload __ARGS((char_u *name, int reload));
739 static char_u *autoload_name __ARGS((char_u *name));
740 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
741 static void func_free __ARGS((ufunc_T *fp));
742 static void func_unref __ARGS((char_u *name));
743 static void func_ref __ARGS((char_u *name));
744 static void call_user_func __ARGS((ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rettv, linenr_T firstline, linenr_T lastline, dict_T *selfdict));
745 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
746 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
747 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
748 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
749 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
750 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
752 /* Character used as separated in autoload function/variable names. */
753 #define AUTOLOAD_CHAR '#'
756 * Initialize the global and v: variables.
758 void
759 eval_init()
761 int i;
762 struct vimvar *p;
764 init_var_dict(&globvardict, &globvars_var);
765 init_var_dict(&vimvardict, &vimvars_var);
766 hash_init(&compat_hashtab);
767 hash_init(&func_hashtab);
769 for (i = 0; i < VV_LEN; ++i)
771 p = &vimvars[i];
772 STRCPY(p->vv_di.di_key, p->vv_name);
773 if (p->vv_flags & VV_RO)
774 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
775 else if (p->vv_flags & VV_RO_SBX)
776 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
777 else
778 p->vv_di.di_flags = DI_FLAGS_FIX;
780 /* add to v: scope dict, unless the value is not always available */
781 if (p->vv_type != VAR_UNKNOWN)
782 hash_add(&vimvarht, p->vv_di.di_key);
783 if (p->vv_flags & VV_COMPAT)
784 /* add to compat scope dict */
785 hash_add(&compat_hashtab, p->vv_di.di_key);
789 #if defined(EXITFREE) || defined(PROTO)
790 void
791 eval_clear()
793 int i;
794 struct vimvar *p;
796 for (i = 0; i < VV_LEN; ++i)
798 p = &vimvars[i];
799 if (p->vv_di.di_tv.v_type == VAR_STRING)
801 vim_free(p->vv_di.di_tv.vval.v_string);
802 p->vv_di.di_tv.vval.v_string = NULL;
805 hash_clear(&vimvarht);
806 hash_clear(&compat_hashtab);
808 /* script-local variables */
809 for (i = 1; i <= ga_scripts.ga_len; ++i)
810 vars_clear(&SCRIPT_VARS(i));
811 ga_clear(&ga_scripts);
812 free_scriptnames();
814 /* global variables */
815 vars_clear(&globvarht);
817 /* functions */
818 free_all_functions();
819 hash_clear(&func_hashtab);
821 /* autoloaded script names */
822 ga_clear_strings(&ga_loaded);
824 /* unreferenced lists and dicts */
825 (void)garbage_collect();
827 #endif
830 * Return the name of the executed function.
832 char_u *
833 func_name(cookie)
834 void *cookie;
836 return ((funccall_T *)cookie)->func->uf_name;
840 * Return the address holding the next breakpoint line for a funccall cookie.
842 linenr_T *
843 func_breakpoint(cookie)
844 void *cookie;
846 return &((funccall_T *)cookie)->breakpoint;
850 * Return the address holding the debug tick for a funccall cookie.
852 int *
853 func_dbg_tick(cookie)
854 void *cookie;
856 return &((funccall_T *)cookie)->dbg_tick;
860 * Return the nesting level for a funccall cookie.
863 func_level(cookie)
864 void *cookie;
866 return ((funccall_T *)cookie)->level;
869 /* pointer to funccal for currently active function */
870 funccall_T *current_funccal = NULL;
873 * Return TRUE when a function was ended by a ":return" command.
876 current_func_returned()
878 return current_funccal->returned;
883 * Set an internal variable to a string value. Creates the variable if it does
884 * not already exist.
886 void
887 set_internal_string_var(name, value)
888 char_u *name;
889 char_u *value;
891 char_u *val;
892 typval_T *tvp;
894 val = vim_strsave(value);
895 if (val != NULL)
897 tvp = alloc_string_tv(val);
898 if (tvp != NULL)
900 set_var(name, tvp, FALSE);
901 free_tv(tvp);
906 static lval_T *redir_lval = NULL;
907 static garray_T redir_ga; /* only valid when redir_lval is not NULL */
908 static char_u *redir_endp = NULL;
909 static char_u *redir_varname = NULL;
912 * Start recording command output to a variable
913 * Returns OK if successfully completed the setup. FAIL otherwise.
916 var_redir_start(name, append)
917 char_u *name;
918 int append; /* append to an existing variable */
920 int save_emsg;
921 int err;
922 typval_T tv;
924 /* Make sure a valid variable name is specified */
925 if (!eval_isnamec1(*name))
927 EMSG(_(e_invarg));
928 return FAIL;
931 redir_varname = vim_strsave(name);
932 if (redir_varname == NULL)
933 return FAIL;
935 redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
936 if (redir_lval == NULL)
938 var_redir_stop();
939 return FAIL;
942 /* The output is stored in growarray "redir_ga" until redirection ends. */
943 ga_init2(&redir_ga, (int)sizeof(char), 500);
945 /* Parse the variable name (can be a dict or list entry). */
946 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
947 FNE_CHECK_START);
948 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
950 if (redir_endp != NULL && *redir_endp != NUL)
951 /* Trailing characters are present after the variable name */
952 EMSG(_(e_trailing));
953 else
954 EMSG(_(e_invarg));
955 var_redir_stop();
956 return FAIL;
959 /* check if we can write to the variable: set it to or append an empty
960 * string */
961 save_emsg = did_emsg;
962 did_emsg = FALSE;
963 tv.v_type = VAR_STRING;
964 tv.vval.v_string = (char_u *)"";
965 if (append)
966 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
967 else
968 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
969 err = did_emsg;
970 did_emsg |= save_emsg;
971 if (err)
973 var_redir_stop();
974 return FAIL;
976 if (redir_lval->ll_newkey != NULL)
978 /* Dictionary item was created, don't do it again. */
979 vim_free(redir_lval->ll_newkey);
980 redir_lval->ll_newkey = NULL;
983 return OK;
987 * Append "value[value_len]" to the variable set by var_redir_start().
988 * The actual appending is postponed until redirection ends, because the value
989 * appended may in fact be the string we write to, changing it may cause freed
990 * memory to be used:
991 * :redir => foo
992 * :let foo
993 * :redir END
995 void
996 var_redir_str(value, value_len)
997 char_u *value;
998 int value_len;
1000 int len;
1002 if (redir_lval == NULL)
1003 return;
1005 if (value_len == -1)
1006 len = (int)STRLEN(value); /* Append the entire string */
1007 else
1008 len = value_len; /* Append only "value_len" characters */
1010 if (ga_grow(&redir_ga, len) == OK)
1012 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1013 redir_ga.ga_len += len;
1015 else
1016 var_redir_stop();
1020 * Stop redirecting command output to a variable.
1022 void
1023 var_redir_stop()
1025 typval_T tv;
1027 if (redir_lval != NULL)
1029 /* Append the trailing NUL. */
1030 ga_append(&redir_ga, NUL);
1032 /* Assign the text to the variable. */
1033 tv.v_type = VAR_STRING;
1034 tv.vval.v_string = redir_ga.ga_data;
1035 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1036 vim_free(tv.vval.v_string);
1038 clear_lval(redir_lval);
1039 vim_free(redir_lval);
1040 redir_lval = NULL;
1042 vim_free(redir_varname);
1043 redir_varname = NULL;
1046 # if defined(FEAT_MBYTE) || defined(PROTO)
1048 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1049 char_u *enc_from;
1050 char_u *enc_to;
1051 char_u *fname_from;
1052 char_u *fname_to;
1054 int err = FALSE;
1056 set_vim_var_string(VV_CC_FROM, enc_from, -1);
1057 set_vim_var_string(VV_CC_TO, enc_to, -1);
1058 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1059 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1060 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1061 err = TRUE;
1062 set_vim_var_string(VV_CC_FROM, NULL, -1);
1063 set_vim_var_string(VV_CC_TO, NULL, -1);
1064 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1065 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1067 if (err)
1068 return FAIL;
1069 return OK;
1071 # endif
1073 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1075 eval_printexpr(fname, args)
1076 char_u *fname;
1077 char_u *args;
1079 int err = FALSE;
1081 set_vim_var_string(VV_FNAME_IN, fname, -1);
1082 set_vim_var_string(VV_CMDARG, args, -1);
1083 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1084 err = TRUE;
1085 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1086 set_vim_var_string(VV_CMDARG, NULL, -1);
1088 if (err)
1090 mch_remove(fname);
1091 return FAIL;
1093 return OK;
1095 # endif
1097 # if defined(FEAT_DIFF) || defined(PROTO)
1098 void
1099 eval_diff(origfile, newfile, outfile)
1100 char_u *origfile;
1101 char_u *newfile;
1102 char_u *outfile;
1104 int err = FALSE;
1106 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1107 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1108 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1109 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1110 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1111 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1112 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1115 void
1116 eval_patch(origfile, difffile, outfile)
1117 char_u *origfile;
1118 char_u *difffile;
1119 char_u *outfile;
1121 int err;
1123 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1124 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1125 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1126 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1127 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1128 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1129 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1131 # endif
1134 * Top level evaluation function, returning a boolean.
1135 * Sets "error" to TRUE if there was an error.
1136 * Return TRUE or FALSE.
1139 eval_to_bool(arg, error, nextcmd, skip)
1140 char_u *arg;
1141 int *error;
1142 char_u **nextcmd;
1143 int skip; /* only parse, don't execute */
1145 typval_T tv;
1146 int retval = FALSE;
1148 if (skip)
1149 ++emsg_skip;
1150 if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1151 *error = TRUE;
1152 else
1154 *error = FALSE;
1155 if (!skip)
1157 retval = (get_tv_number_chk(&tv, error) != 0);
1158 clear_tv(&tv);
1161 if (skip)
1162 --emsg_skip;
1164 return retval;
1168 * Top level evaluation function, returning a string. If "skip" is TRUE,
1169 * only parsing to "nextcmd" is done, without reporting errors. Return
1170 * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1172 char_u *
1173 eval_to_string_skip(arg, nextcmd, skip)
1174 char_u *arg;
1175 char_u **nextcmd;
1176 int skip; /* only parse, don't execute */
1178 typval_T tv;
1179 char_u *retval;
1181 if (skip)
1182 ++emsg_skip;
1183 if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1184 retval = NULL;
1185 else
1187 retval = vim_strsave(get_tv_string(&tv));
1188 clear_tv(&tv);
1190 if (skip)
1191 --emsg_skip;
1193 return retval;
1197 * Skip over an expression at "*pp".
1198 * Return FAIL for an error, OK otherwise.
1201 skip_expr(pp)
1202 char_u **pp;
1204 typval_T rettv;
1206 *pp = skipwhite(*pp);
1207 return eval1(pp, &rettv, FALSE);
1211 * Top level evaluation function, returning a string.
1212 * Return pointer to allocated memory, or NULL for failure.
1214 char_u *
1215 eval_to_string(arg, nextcmd, dolist)
1216 char_u *arg;
1217 char_u **nextcmd;
1218 int dolist; /* turn List into sequence of lines */
1220 typval_T tv;
1221 char_u *retval;
1222 garray_T ga;
1224 if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1225 retval = NULL;
1226 else
1228 if (dolist && tv.v_type == VAR_LIST)
1230 ga_init2(&ga, (int)sizeof(char), 80);
1231 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1232 ga_append(&ga, NUL);
1233 retval = (char_u *)ga.ga_data;
1235 else
1236 retval = vim_strsave(get_tv_string(&tv));
1237 clear_tv(&tv);
1240 return retval;
1244 * Call eval_to_string() without using current local variables and using
1245 * textlock. When "use_sandbox" is TRUE use the sandbox.
1247 char_u *
1248 eval_to_string_safe(arg, nextcmd, use_sandbox)
1249 char_u *arg;
1250 char_u **nextcmd;
1251 int use_sandbox;
1253 char_u *retval;
1254 void *save_funccalp;
1256 save_funccalp = save_funccal();
1257 if (use_sandbox)
1258 ++sandbox;
1259 ++textlock;
1260 retval = eval_to_string(arg, nextcmd, FALSE);
1261 if (use_sandbox)
1262 --sandbox;
1263 --textlock;
1264 restore_funccal(save_funccalp);
1265 return retval;
1269 * Top level evaluation function, returning a number.
1270 * Evaluates "expr" silently.
1271 * Returns -1 for an error.
1274 eval_to_number(expr)
1275 char_u *expr;
1277 typval_T rettv;
1278 int retval;
1279 char_u *p = skipwhite(expr);
1281 ++emsg_off;
1283 if (eval1(&p, &rettv, TRUE) == FAIL)
1284 retval = -1;
1285 else
1287 retval = get_tv_number_chk(&rettv, NULL);
1288 clear_tv(&rettv);
1290 --emsg_off;
1292 return retval;
1296 * Prepare v: variable "idx" to be used.
1297 * Save the current typeval in "save_tv".
1298 * When not used yet add the variable to the v: hashtable.
1300 static void
1301 prepare_vimvar(idx, save_tv)
1302 int idx;
1303 typval_T *save_tv;
1305 *save_tv = vimvars[idx].vv_tv;
1306 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1307 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1311 * Restore v: variable "idx" to typeval "save_tv".
1312 * When no longer defined, remove the variable from the v: hashtable.
1314 static void
1315 restore_vimvar(idx, save_tv)
1316 int idx;
1317 typval_T *save_tv;
1319 hashitem_T *hi;
1321 clear_tv(&vimvars[idx].vv_tv);
1322 vimvars[idx].vv_tv = *save_tv;
1323 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1325 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1326 if (HASHITEM_EMPTY(hi))
1327 EMSG2(_(e_intern2), "restore_vimvar()");
1328 else
1329 hash_remove(&vimvarht, hi);
1333 #if defined(FEAT_SPELL) || defined(PROTO)
1335 * Evaluate an expression to a list with suggestions.
1336 * For the "expr:" part of 'spellsuggest'.
1338 list_T *
1339 eval_spell_expr(badword, expr)
1340 char_u *badword;
1341 char_u *expr;
1343 typval_T save_val;
1344 typval_T rettv;
1345 list_T *list = NULL;
1346 char_u *p = skipwhite(expr);
1348 /* Set "v:val" to the bad word. */
1349 prepare_vimvar(VV_VAL, &save_val);
1350 vimvars[VV_VAL].vv_type = VAR_STRING;
1351 vimvars[VV_VAL].vv_str = badword;
1352 if (p_verbose == 0)
1353 ++emsg_off;
1355 if (eval1(&p, &rettv, TRUE) == OK)
1357 if (rettv.v_type != VAR_LIST)
1358 clear_tv(&rettv);
1359 else
1360 list = rettv.vval.v_list;
1363 if (p_verbose == 0)
1364 --emsg_off;
1365 vimvars[VV_VAL].vv_str = NULL;
1366 restore_vimvar(VV_VAL, &save_val);
1368 return list;
1372 * "list" is supposed to contain two items: a word and a number. Return the
1373 * word in "pp" and the number as the return value.
1374 * Return -1 if anything isn't right.
1375 * Used to get the good word and score from the eval_spell_expr() result.
1378 get_spellword(list, pp)
1379 list_T *list;
1380 char_u **pp;
1382 listitem_T *li;
1384 li = list->lv_first;
1385 if (li == NULL)
1386 return -1;
1387 *pp = get_tv_string(&li->li_tv);
1389 li = li->li_next;
1390 if (li == NULL)
1391 return -1;
1392 return get_tv_number(&li->li_tv);
1394 #endif
1397 * Top level evaluation function.
1398 * Returns an allocated typval_T with the result.
1399 * Returns NULL when there is an error.
1401 typval_T *
1402 eval_expr(arg, nextcmd)
1403 char_u *arg;
1404 char_u **nextcmd;
1406 typval_T *tv;
1408 tv = (typval_T *)alloc(sizeof(typval_T));
1409 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1411 vim_free(tv);
1412 tv = NULL;
1415 return tv;
1419 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1420 || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1422 * Call some vimL function and return the result in "*rettv".
1423 * Uses argv[argc] for the function arguments.
1424 * Returns OK or FAIL.
1426 static int
1427 call_vim_function(func, argc, argv, safe, rettv)
1428 char_u *func;
1429 int argc;
1430 char_u **argv;
1431 int safe; /* use the sandbox */
1432 typval_T *rettv;
1434 typval_T *argvars;
1435 long n;
1436 int len;
1437 int i;
1438 int doesrange;
1439 void *save_funccalp = NULL;
1440 int ret;
1442 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1443 if (argvars == NULL)
1444 return FAIL;
1446 for (i = 0; i < argc; i++)
1448 /* Pass a NULL or empty argument as an empty string */
1449 if (argv[i] == NULL || *argv[i] == NUL)
1451 argvars[i].v_type = VAR_STRING;
1452 argvars[i].vval.v_string = (char_u *)"";
1453 continue;
1456 /* Recognize a number argument, the others must be strings. */
1457 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1458 if (len != 0 && len == (int)STRLEN(argv[i]))
1460 argvars[i].v_type = VAR_NUMBER;
1461 argvars[i].vval.v_number = n;
1463 else
1465 argvars[i].v_type = VAR_STRING;
1466 argvars[i].vval.v_string = argv[i];
1470 if (safe)
1472 save_funccalp = save_funccal();
1473 ++sandbox;
1476 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1477 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1478 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1479 &doesrange, TRUE, NULL);
1480 if (safe)
1482 --sandbox;
1483 restore_funccal(save_funccalp);
1485 vim_free(argvars);
1487 if (ret == FAIL)
1488 clear_tv(rettv);
1490 return ret;
1493 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1495 * Call vimL function "func" and return the result as a string.
1496 * Returns NULL when calling the function fails.
1497 * Uses argv[argc] for the function arguments.
1499 void *
1500 call_func_retstr(func, argc, argv, safe)
1501 char_u *func;
1502 int argc;
1503 char_u **argv;
1504 int safe; /* use the sandbox */
1506 typval_T rettv;
1507 char_u *retval;
1509 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1510 return NULL;
1512 retval = vim_strsave(get_tv_string(&rettv));
1513 clear_tv(&rettv);
1514 return retval;
1516 # endif
1518 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1520 * Call vimL function "func" and return the result as a number.
1521 * Returns -1 when calling the function fails.
1522 * Uses argv[argc] for the function arguments.
1524 long
1525 call_func_retnr(func, argc, argv, safe)
1526 char_u *func;
1527 int argc;
1528 char_u **argv;
1529 int safe; /* use the sandbox */
1531 typval_T rettv;
1532 long retval;
1534 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1535 return -1;
1537 retval = get_tv_number_chk(&rettv, NULL);
1538 clear_tv(&rettv);
1539 return retval;
1541 # endif
1544 * Call vimL function "func" and return the result as a list
1545 * Uses argv[argc] for the function arguments.
1547 void *
1548 call_func_retlist(func, argc, argv, safe)
1549 char_u *func;
1550 int argc;
1551 char_u **argv;
1552 int safe; /* use the sandbox */
1554 typval_T rettv;
1556 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1557 return NULL;
1559 if (rettv.v_type != VAR_LIST)
1561 clear_tv(&rettv);
1562 return NULL;
1565 return rettv.vval.v_list;
1567 #endif
1571 * Save the current function call pointer, and set it to NULL.
1572 * Used when executing autocommands and for ":source".
1574 void *
1575 save_funccal()
1577 funccall_T *fc = current_funccal;
1579 current_funccal = NULL;
1580 return (void *)fc;
1583 void
1584 restore_funccal(vfc)
1585 void *vfc;
1587 funccall_T *fc = (funccall_T *)vfc;
1589 current_funccal = fc;
1592 #if defined(FEAT_PROFILE) || defined(PROTO)
1594 * Prepare profiling for entering a child or something else that is not
1595 * counted for the script/function itself.
1596 * Should always be called in pair with prof_child_exit().
1598 void
1599 prof_child_enter(tm)
1600 proftime_T *tm; /* place to store waittime */
1602 funccall_T *fc = current_funccal;
1604 if (fc != NULL && fc->func->uf_profiling)
1605 profile_start(&fc->prof_child);
1606 script_prof_save(tm);
1610 * Take care of time spent in a child.
1611 * Should always be called after prof_child_enter().
1613 void
1614 prof_child_exit(tm)
1615 proftime_T *tm; /* where waittime was stored */
1617 funccall_T *fc = current_funccal;
1619 if (fc != NULL && fc->func->uf_profiling)
1621 profile_end(&fc->prof_child);
1622 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1623 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1624 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1626 script_prof_restore(tm);
1628 #endif
1631 #ifdef FEAT_FOLDING
1633 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1634 * it in "*cp". Doesn't give error messages.
1637 eval_foldexpr(arg, cp)
1638 char_u *arg;
1639 int *cp;
1641 typval_T tv;
1642 int retval;
1643 char_u *s;
1644 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1645 OPT_LOCAL);
1647 ++emsg_off;
1648 if (use_sandbox)
1649 ++sandbox;
1650 ++textlock;
1651 *cp = NUL;
1652 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1653 retval = 0;
1654 else
1656 /* If the result is a number, just return the number. */
1657 if (tv.v_type == VAR_NUMBER)
1658 retval = tv.vval.v_number;
1659 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1660 retval = 0;
1661 else
1663 /* If the result is a string, check if there is a non-digit before
1664 * the number. */
1665 s = tv.vval.v_string;
1666 if (!VIM_ISDIGIT(*s) && *s != '-')
1667 *cp = *s++;
1668 retval = atol((char *)s);
1670 clear_tv(&tv);
1672 --emsg_off;
1673 if (use_sandbox)
1674 --sandbox;
1675 --textlock;
1677 return retval;
1679 #endif
1682 * ":let" list all variable values
1683 * ":let var1 var2" list variable values
1684 * ":let var = expr" assignment command.
1685 * ":let var += expr" assignment command.
1686 * ":let var -= expr" assignment command.
1687 * ":let var .= expr" assignment command.
1688 * ":let [var1, var2] = expr" unpack list.
1690 void
1691 ex_let(eap)
1692 exarg_T *eap;
1694 char_u *arg = eap->arg;
1695 char_u *expr = NULL;
1696 typval_T rettv;
1697 int i;
1698 int var_count = 0;
1699 int semicolon = 0;
1700 char_u op[2];
1701 char_u *argend;
1702 int first = TRUE;
1704 argend = skip_var_list(arg, &var_count, &semicolon);
1705 if (argend == NULL)
1706 return;
1707 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1708 --argend;
1709 expr = vim_strchr(argend, '=');
1710 if (expr == NULL)
1713 * ":let" without "=": list variables
1715 if (*arg == '[')
1716 EMSG(_(e_invarg));
1717 else if (!ends_excmd(*arg))
1718 /* ":let var1 var2" */
1719 arg = list_arg_vars(eap, arg, &first);
1720 else if (!eap->skip)
1722 /* ":let" */
1723 list_glob_vars(&first);
1724 list_buf_vars(&first);
1725 list_win_vars(&first);
1726 #ifdef FEAT_WINDOWS
1727 list_tab_vars(&first);
1728 #endif
1729 list_script_vars(&first);
1730 list_func_vars(&first);
1731 list_vim_vars(&first);
1733 eap->nextcmd = check_nextcmd(arg);
1735 else
1737 op[0] = '=';
1738 op[1] = NUL;
1739 if (expr > argend)
1741 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1742 op[0] = expr[-1]; /* +=, -= or .= */
1744 expr = skipwhite(expr + 1);
1746 if (eap->skip)
1747 ++emsg_skip;
1748 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1749 if (eap->skip)
1751 if (i != FAIL)
1752 clear_tv(&rettv);
1753 --emsg_skip;
1755 else if (i != FAIL)
1757 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1758 op);
1759 clear_tv(&rettv);
1765 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1766 * Handles both "var" with any type and "[var, var; var]" with a list type.
1767 * When "nextchars" is not NULL it points to a string with characters that
1768 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1769 * or concatenate.
1770 * Returns OK or FAIL;
1772 static int
1773 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1774 char_u *arg_start;
1775 typval_T *tv;
1776 int copy; /* copy values from "tv", don't move */
1777 int semicolon; /* from skip_var_list() */
1778 int var_count; /* from skip_var_list() */
1779 char_u *nextchars;
1781 char_u *arg = arg_start;
1782 list_T *l;
1783 int i;
1784 listitem_T *item;
1785 typval_T ltv;
1787 if (*arg != '[')
1790 * ":let var = expr" or ":for var in list"
1792 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1793 return FAIL;
1794 return OK;
1798 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1800 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1802 EMSG(_(e_listreq));
1803 return FAIL;
1806 i = list_len(l);
1807 if (semicolon == 0 && var_count < i)
1809 EMSG(_("E687: Less targets than List items"));
1810 return FAIL;
1812 if (var_count - semicolon > i)
1814 EMSG(_("E688: More targets than List items"));
1815 return FAIL;
1818 item = l->lv_first;
1819 while (*arg != ']')
1821 arg = skipwhite(arg + 1);
1822 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1823 item = item->li_next;
1824 if (arg == NULL)
1825 return FAIL;
1827 arg = skipwhite(arg);
1828 if (*arg == ';')
1830 /* Put the rest of the list (may be empty) in the var after ';'.
1831 * Create a new list for this. */
1832 l = list_alloc();
1833 if (l == NULL)
1834 return FAIL;
1835 while (item != NULL)
1837 list_append_tv(l, &item->li_tv);
1838 item = item->li_next;
1841 ltv.v_type = VAR_LIST;
1842 ltv.v_lock = 0;
1843 ltv.vval.v_list = l;
1844 l->lv_refcount = 1;
1846 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1847 (char_u *)"]", nextchars);
1848 clear_tv(&ltv);
1849 if (arg == NULL)
1850 return FAIL;
1851 break;
1853 else if (*arg != ',' && *arg != ']')
1855 EMSG2(_(e_intern2), "ex_let_vars()");
1856 return FAIL;
1860 return OK;
1864 * Skip over assignable variable "var" or list of variables "[var, var]".
1865 * Used for ":let varvar = expr" and ":for varvar in expr".
1866 * For "[var, var]" increment "*var_count" for each variable.
1867 * for "[var, var; var]" set "semicolon".
1868 * Return NULL for an error.
1870 static char_u *
1871 skip_var_list(arg, var_count, semicolon)
1872 char_u *arg;
1873 int *var_count;
1874 int *semicolon;
1876 char_u *p, *s;
1878 if (*arg == '[')
1880 /* "[var, var]": find the matching ']'. */
1881 p = arg;
1882 for (;;)
1884 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
1885 s = skip_var_one(p);
1886 if (s == p)
1888 EMSG2(_(e_invarg2), p);
1889 return NULL;
1891 ++*var_count;
1893 p = skipwhite(s);
1894 if (*p == ']')
1895 break;
1896 else if (*p == ';')
1898 if (*semicolon == 1)
1900 EMSG(_("Double ; in list of variables"));
1901 return NULL;
1903 *semicolon = 1;
1905 else if (*p != ',')
1907 EMSG2(_(e_invarg2), p);
1908 return NULL;
1911 return p + 1;
1913 else
1914 return skip_var_one(arg);
1918 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
1919 * l[idx].
1921 static char_u *
1922 skip_var_one(arg)
1923 char_u *arg;
1925 if (*arg == '@' && arg[1] != NUL)
1926 return arg + 2;
1927 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
1928 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1932 * List variables for hashtab "ht" with prefix "prefix".
1933 * If "empty" is TRUE also list NULL strings as empty strings.
1935 static void
1936 list_hashtable_vars(ht, prefix, empty, first)
1937 hashtab_T *ht;
1938 char_u *prefix;
1939 int empty;
1940 int *first;
1942 hashitem_T *hi;
1943 dictitem_T *di;
1944 int todo;
1946 todo = (int)ht->ht_used;
1947 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
1949 if (!HASHITEM_EMPTY(hi))
1951 --todo;
1952 di = HI2DI(hi);
1953 if (empty || di->di_tv.v_type != VAR_STRING
1954 || di->di_tv.vval.v_string != NULL)
1955 list_one_var(di, prefix, first);
1961 * List global variables.
1963 static void
1964 list_glob_vars(first)
1965 int *first;
1967 list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
1971 * List buffer variables.
1973 static void
1974 list_buf_vars(first)
1975 int *first;
1977 char_u numbuf[NUMBUFLEN];
1979 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:",
1980 TRUE, first);
1982 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
1983 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
1984 numbuf, first);
1988 * List window variables.
1990 static void
1991 list_win_vars(first)
1992 int *first;
1994 list_hashtable_vars(&curwin->w_vars.dv_hashtab,
1995 (char_u *)"w:", TRUE, first);
1998 #ifdef FEAT_WINDOWS
2000 * List tab page variables.
2002 static void
2003 list_tab_vars(first)
2004 int *first;
2006 list_hashtable_vars(&curtab->tp_vars.dv_hashtab,
2007 (char_u *)"t:", TRUE, first);
2009 #endif
2012 * List Vim variables.
2014 static void
2015 list_vim_vars(first)
2016 int *first;
2018 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2022 * List script-local variables, if there is a script.
2024 static void
2025 list_script_vars(first)
2026 int *first;
2028 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2029 list_hashtable_vars(&SCRIPT_VARS(current_SID),
2030 (char_u *)"s:", FALSE, first);
2034 * List function variables, if there is a function.
2036 static void
2037 list_func_vars(first)
2038 int *first;
2040 if (current_funccal != NULL)
2041 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2042 (char_u *)"l:", FALSE, first);
2046 * List variables in "arg".
2048 static char_u *
2049 list_arg_vars(eap, arg, first)
2050 exarg_T *eap;
2051 char_u *arg;
2052 int *first;
2054 int error = FALSE;
2055 int len;
2056 char_u *name;
2057 char_u *name_start;
2058 char_u *arg_subsc;
2059 char_u *tofree;
2060 typval_T tv;
2062 while (!ends_excmd(*arg) && !got_int)
2064 if (error || eap->skip)
2066 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2067 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2069 emsg_severe = TRUE;
2070 EMSG(_(e_trailing));
2071 break;
2074 else
2076 /* get_name_len() takes care of expanding curly braces */
2077 name_start = name = arg;
2078 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2079 if (len <= 0)
2081 /* This is mainly to keep test 49 working: when expanding
2082 * curly braces fails overrule the exception error message. */
2083 if (len < 0 && !aborting())
2085 emsg_severe = TRUE;
2086 EMSG2(_(e_invarg2), arg);
2087 break;
2089 error = TRUE;
2091 else
2093 if (tofree != NULL)
2094 name = tofree;
2095 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2096 error = TRUE;
2097 else
2099 /* handle d.key, l[idx], f(expr) */
2100 arg_subsc = arg;
2101 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2102 error = TRUE;
2103 else
2105 if (arg == arg_subsc && len == 2 && name[1] == ':')
2107 switch (*name)
2109 case 'g': list_glob_vars(first); break;
2110 case 'b': list_buf_vars(first); break;
2111 case 'w': list_win_vars(first); break;
2112 #ifdef FEAT_WINDOWS
2113 case 't': list_tab_vars(first); break;
2114 #endif
2115 case 'v': list_vim_vars(first); break;
2116 case 's': list_script_vars(first); break;
2117 case 'l': list_func_vars(first); break;
2118 default:
2119 EMSG2(_("E738: Can't list variables for %s"), name);
2122 else
2124 char_u numbuf[NUMBUFLEN];
2125 char_u *tf;
2126 int c;
2127 char_u *s;
2129 s = echo_string(&tv, &tf, numbuf, 0);
2130 c = *arg;
2131 *arg = NUL;
2132 list_one_var_a((char_u *)"",
2133 arg == arg_subsc ? name : name_start,
2134 tv.v_type,
2135 s == NULL ? (char_u *)"" : s,
2136 first);
2137 *arg = c;
2138 vim_free(tf);
2140 clear_tv(&tv);
2145 vim_free(tofree);
2148 arg = skipwhite(arg);
2151 return arg;
2155 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2156 * Returns a pointer to the char just after the var name.
2157 * Returns NULL if there is an error.
2159 static char_u *
2160 ex_let_one(arg, tv, copy, endchars, op)
2161 char_u *arg; /* points to variable name */
2162 typval_T *tv; /* value to assign to variable */
2163 int copy; /* copy value from "tv" */
2164 char_u *endchars; /* valid chars after variable name or NULL */
2165 char_u *op; /* "+", "-", "." or NULL*/
2167 int c1;
2168 char_u *name;
2169 char_u *p;
2170 char_u *arg_end = NULL;
2171 int len;
2172 int opt_flags;
2173 char_u *tofree = NULL;
2176 * ":let $VAR = expr": Set environment variable.
2178 if (*arg == '$')
2180 /* Find the end of the name. */
2181 ++arg;
2182 name = arg;
2183 len = get_env_len(&arg);
2184 if (len == 0)
2185 EMSG2(_(e_invarg2), name - 1);
2186 else
2188 if (op != NULL && (*op == '+' || *op == '-'))
2189 EMSG2(_(e_letwrong), op);
2190 else if (endchars != NULL
2191 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2192 EMSG(_(e_letunexp));
2193 else
2195 c1 = name[len];
2196 name[len] = NUL;
2197 p = get_tv_string_chk(tv);
2198 if (p != NULL && op != NULL && *op == '.')
2200 int mustfree = FALSE;
2201 char_u *s = vim_getenv(name, &mustfree);
2203 if (s != NULL)
2205 p = tofree = concat_str(s, p);
2206 if (mustfree)
2207 vim_free(s);
2210 if (p != NULL)
2212 vim_setenv(name, p);
2213 if (STRICMP(name, "HOME") == 0)
2214 init_homedir();
2215 else if (didset_vim && STRICMP(name, "VIM") == 0)
2216 didset_vim = FALSE;
2217 else if (didset_vimruntime
2218 && STRICMP(name, "VIMRUNTIME") == 0)
2219 didset_vimruntime = FALSE;
2220 arg_end = arg;
2222 name[len] = c1;
2223 vim_free(tofree);
2229 * ":let &option = expr": Set option value.
2230 * ":let &l:option = expr": Set local option value.
2231 * ":let &g:option = expr": Set global option value.
2233 else if (*arg == '&')
2235 /* Find the end of the name. */
2236 p = find_option_end(&arg, &opt_flags);
2237 if (p == NULL || (endchars != NULL
2238 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2239 EMSG(_(e_letunexp));
2240 else
2242 long n;
2243 int opt_type;
2244 long numval;
2245 char_u *stringval = NULL;
2246 char_u *s;
2248 c1 = *p;
2249 *p = NUL;
2251 n = get_tv_number(tv);
2252 s = get_tv_string_chk(tv); /* != NULL if number or string */
2253 if (s != NULL && op != NULL && *op != '=')
2255 opt_type = get_option_value(arg, &numval,
2256 &stringval, opt_flags);
2257 if ((opt_type == 1 && *op == '.')
2258 || (opt_type == 0 && *op != '.'))
2259 EMSG2(_(e_letwrong), op);
2260 else
2262 if (opt_type == 1) /* number */
2264 if (*op == '+')
2265 n = numval + n;
2266 else
2267 n = numval - n;
2269 else if (opt_type == 0 && stringval != NULL) /* string */
2271 s = concat_str(stringval, s);
2272 vim_free(stringval);
2273 stringval = s;
2277 if (s != NULL)
2279 set_option_value(arg, n, s, opt_flags);
2280 arg_end = p;
2282 *p = c1;
2283 vim_free(stringval);
2288 * ":let @r = expr": Set register contents.
2290 else if (*arg == '@')
2292 ++arg;
2293 if (op != NULL && (*op == '+' || *op == '-'))
2294 EMSG2(_(e_letwrong), op);
2295 else if (endchars != NULL
2296 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2297 EMSG(_(e_letunexp));
2298 else
2300 char_u *ptofree = NULL;
2301 char_u *s;
2303 p = get_tv_string_chk(tv);
2304 if (p != NULL && op != NULL && *op == '.')
2306 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2307 if (s != NULL)
2309 p = ptofree = concat_str(s, p);
2310 vim_free(s);
2313 if (p != NULL)
2315 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2316 arg_end = arg + 1;
2318 vim_free(ptofree);
2323 * ":let var = expr": Set internal variable.
2324 * ":let {expr} = expr": Idem, name made with curly braces
2326 else if (eval_isnamec1(*arg) || *arg == '{')
2328 lval_T lv;
2330 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2331 if (p != NULL && lv.ll_name != NULL)
2333 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2334 EMSG(_(e_letunexp));
2335 else
2337 set_var_lval(&lv, p, tv, copy, op);
2338 arg_end = p;
2341 clear_lval(&lv);
2344 else
2345 EMSG2(_(e_invarg2), arg);
2347 return arg_end;
2351 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2353 static int
2354 check_changedtick(arg)
2355 char_u *arg;
2357 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2359 EMSG2(_(e_readonlyvar), arg);
2360 return TRUE;
2362 return FALSE;
2366 * Get an lval: variable, Dict item or List item that can be assigned a value
2367 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2368 * "name.key", "name.key[expr]" etc.
2369 * Indexing only works if "name" is an existing List or Dictionary.
2370 * "name" points to the start of the name.
2371 * If "rettv" is not NULL it points to the value to be assigned.
2372 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2373 * wrong; must end in space or cmd separator.
2375 * Returns a pointer to just after the name, including indexes.
2376 * When an evaluation error occurs "lp->ll_name" is NULL;
2377 * Returns NULL for a parsing error. Still need to free items in "lp"!
2379 static char_u *
2380 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2381 char_u *name;
2382 typval_T *rettv;
2383 lval_T *lp;
2384 int unlet;
2385 int skip;
2386 int quiet; /* don't give error messages */
2387 int fne_flags; /* flags for find_name_end() */
2389 char_u *p;
2390 char_u *expr_start, *expr_end;
2391 int cc;
2392 dictitem_T *v;
2393 typval_T var1;
2394 typval_T var2;
2395 int empty1 = FALSE;
2396 listitem_T *ni;
2397 char_u *key = NULL;
2398 int len;
2399 hashtab_T *ht;
2401 /* Clear everything in "lp". */
2402 vim_memset(lp, 0, sizeof(lval_T));
2404 if (skip)
2406 /* When skipping just find the end of the name. */
2407 lp->ll_name = name;
2408 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2411 /* Find the end of the name. */
2412 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2413 if (expr_start != NULL)
2415 /* Don't expand the name when we already know there is an error. */
2416 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2417 && *p != '[' && *p != '.')
2419 EMSG(_(e_trailing));
2420 return NULL;
2423 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2424 if (lp->ll_exp_name == NULL)
2426 /* Report an invalid expression in braces, unless the
2427 * expression evaluation has been cancelled due to an
2428 * aborting error, an interrupt, or an exception. */
2429 if (!aborting() && !quiet)
2431 emsg_severe = TRUE;
2432 EMSG2(_(e_invarg2), name);
2433 return NULL;
2436 lp->ll_name = lp->ll_exp_name;
2438 else
2439 lp->ll_name = name;
2441 /* Without [idx] or .key we are done. */
2442 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2443 return p;
2445 cc = *p;
2446 *p = NUL;
2447 v = find_var(lp->ll_name, &ht);
2448 if (v == NULL && !quiet)
2449 EMSG2(_(e_undefvar), lp->ll_name);
2450 *p = cc;
2451 if (v == NULL)
2452 return NULL;
2455 * Loop until no more [idx] or .key is following.
2457 lp->ll_tv = &v->di_tv;
2458 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2460 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2461 && !(lp->ll_tv->v_type == VAR_DICT
2462 && lp->ll_tv->vval.v_dict != NULL))
2464 if (!quiet)
2465 EMSG(_("E689: Can only index a List or Dictionary"));
2466 return NULL;
2468 if (lp->ll_range)
2470 if (!quiet)
2471 EMSG(_("E708: [:] must come last"));
2472 return NULL;
2475 len = -1;
2476 if (*p == '.')
2478 key = p + 1;
2479 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2481 if (len == 0)
2483 if (!quiet)
2484 EMSG(_(e_emptykey));
2485 return NULL;
2487 p = key + len;
2489 else
2491 /* Get the index [expr] or the first index [expr: ]. */
2492 p = skipwhite(p + 1);
2493 if (*p == ':')
2494 empty1 = TRUE;
2495 else
2497 empty1 = FALSE;
2498 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2499 return NULL;
2500 if (get_tv_string_chk(&var1) == NULL)
2502 /* not a number or string */
2503 clear_tv(&var1);
2504 return NULL;
2508 /* Optionally get the second index [ :expr]. */
2509 if (*p == ':')
2511 if (lp->ll_tv->v_type == VAR_DICT)
2513 if (!quiet)
2514 EMSG(_(e_dictrange));
2515 if (!empty1)
2516 clear_tv(&var1);
2517 return NULL;
2519 if (rettv != NULL && (rettv->v_type != VAR_LIST
2520 || rettv->vval.v_list == NULL))
2522 if (!quiet)
2523 EMSG(_("E709: [:] requires a List value"));
2524 if (!empty1)
2525 clear_tv(&var1);
2526 return NULL;
2528 p = skipwhite(p + 1);
2529 if (*p == ']')
2530 lp->ll_empty2 = TRUE;
2531 else
2533 lp->ll_empty2 = FALSE;
2534 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2536 if (!empty1)
2537 clear_tv(&var1);
2538 return NULL;
2540 if (get_tv_string_chk(&var2) == NULL)
2542 /* not a number or string */
2543 if (!empty1)
2544 clear_tv(&var1);
2545 clear_tv(&var2);
2546 return NULL;
2549 lp->ll_range = TRUE;
2551 else
2552 lp->ll_range = FALSE;
2554 if (*p != ']')
2556 if (!quiet)
2557 EMSG(_(e_missbrac));
2558 if (!empty1)
2559 clear_tv(&var1);
2560 if (lp->ll_range && !lp->ll_empty2)
2561 clear_tv(&var2);
2562 return NULL;
2565 /* Skip to past ']'. */
2566 ++p;
2569 if (lp->ll_tv->v_type == VAR_DICT)
2571 if (len == -1)
2573 /* "[key]": get key from "var1" */
2574 key = get_tv_string(&var1); /* is number or string */
2575 if (*key == NUL)
2577 if (!quiet)
2578 EMSG(_(e_emptykey));
2579 clear_tv(&var1);
2580 return NULL;
2583 lp->ll_list = NULL;
2584 lp->ll_dict = lp->ll_tv->vval.v_dict;
2585 lp->ll_di = dict_find(lp->ll_dict, key, len);
2586 if (lp->ll_di == NULL)
2588 /* Key does not exist in dict: may need to add it. */
2589 if (*p == '[' || *p == '.' || unlet)
2591 if (!quiet)
2592 EMSG2(_(e_dictkey), key);
2593 if (len == -1)
2594 clear_tv(&var1);
2595 return NULL;
2597 if (len == -1)
2598 lp->ll_newkey = vim_strsave(key);
2599 else
2600 lp->ll_newkey = vim_strnsave(key, len);
2601 if (len == -1)
2602 clear_tv(&var1);
2603 if (lp->ll_newkey == NULL)
2604 p = NULL;
2605 break;
2607 if (len == -1)
2608 clear_tv(&var1);
2609 lp->ll_tv = &lp->ll_di->di_tv;
2611 else
2614 * Get the number and item for the only or first index of the List.
2616 if (empty1)
2617 lp->ll_n1 = 0;
2618 else
2620 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2621 clear_tv(&var1);
2623 lp->ll_dict = NULL;
2624 lp->ll_list = lp->ll_tv->vval.v_list;
2625 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2626 if (lp->ll_li == NULL)
2628 if (lp->ll_n1 < 0)
2630 lp->ll_n1 = 0;
2631 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2634 if (lp->ll_li == NULL)
2636 if (lp->ll_range && !lp->ll_empty2)
2637 clear_tv(&var2);
2638 return NULL;
2642 * May need to find the item or absolute index for the second
2643 * index of a range.
2644 * When no index given: "lp->ll_empty2" is TRUE.
2645 * Otherwise "lp->ll_n2" is set to the second index.
2647 if (lp->ll_range && !lp->ll_empty2)
2649 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2650 clear_tv(&var2);
2651 if (lp->ll_n2 < 0)
2653 ni = list_find(lp->ll_list, lp->ll_n2);
2654 if (ni == NULL)
2655 return NULL;
2656 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2659 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2660 if (lp->ll_n1 < 0)
2661 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2662 if (lp->ll_n2 < lp->ll_n1)
2663 return NULL;
2666 lp->ll_tv = &lp->ll_li->li_tv;
2670 return p;
2674 * Clear lval "lp" that was filled by get_lval().
2676 static void
2677 clear_lval(lp)
2678 lval_T *lp;
2680 vim_free(lp->ll_exp_name);
2681 vim_free(lp->ll_newkey);
2685 * Set a variable that was parsed by get_lval() to "rettv".
2686 * "endp" points to just after the parsed name.
2687 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2689 static void
2690 set_var_lval(lp, endp, rettv, copy, op)
2691 lval_T *lp;
2692 char_u *endp;
2693 typval_T *rettv;
2694 int copy;
2695 char_u *op;
2697 int cc;
2698 listitem_T *ri;
2699 dictitem_T *di;
2701 if (lp->ll_tv == NULL)
2703 if (!check_changedtick(lp->ll_name))
2705 cc = *endp;
2706 *endp = NUL;
2707 if (op != NULL && *op != '=')
2709 typval_T tv;
2711 /* handle +=, -= and .= */
2712 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2713 &tv, TRUE) == OK)
2715 if (tv_op(&tv, rettv, op) == OK)
2716 set_var(lp->ll_name, &tv, FALSE);
2717 clear_tv(&tv);
2720 else
2721 set_var(lp->ll_name, rettv, copy);
2722 *endp = cc;
2725 else if (tv_check_lock(lp->ll_newkey == NULL
2726 ? lp->ll_tv->v_lock
2727 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2729 else if (lp->ll_range)
2732 * Assign the List values to the list items.
2734 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2736 if (op != NULL && *op != '=')
2737 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2738 else
2740 clear_tv(&lp->ll_li->li_tv);
2741 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2743 ri = ri->li_next;
2744 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2745 break;
2746 if (lp->ll_li->li_next == NULL)
2748 /* Need to add an empty item. */
2749 if (list_append_number(lp->ll_list, 0) == FAIL)
2751 ri = NULL;
2752 break;
2755 lp->ll_li = lp->ll_li->li_next;
2756 ++lp->ll_n1;
2758 if (ri != NULL)
2759 EMSG(_("E710: List value has more items than target"));
2760 else if (lp->ll_empty2
2761 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2762 : lp->ll_n1 != lp->ll_n2)
2763 EMSG(_("E711: List value has not enough items"));
2765 else
2768 * Assign to a List or Dictionary item.
2770 if (lp->ll_newkey != NULL)
2772 if (op != NULL && *op != '=')
2774 EMSG2(_(e_letwrong), op);
2775 return;
2778 /* Need to add an item to the Dictionary. */
2779 di = dictitem_alloc(lp->ll_newkey);
2780 if (di == NULL)
2781 return;
2782 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2784 vim_free(di);
2785 return;
2787 lp->ll_tv = &di->di_tv;
2789 else if (op != NULL && *op != '=')
2791 tv_op(lp->ll_tv, rettv, op);
2792 return;
2794 else
2795 clear_tv(lp->ll_tv);
2798 * Assign the value to the variable or list item.
2800 if (copy)
2801 copy_tv(rettv, lp->ll_tv);
2802 else
2804 *lp->ll_tv = *rettv;
2805 lp->ll_tv->v_lock = 0;
2806 init_tv(rettv);
2812 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2813 * Returns OK or FAIL.
2815 static int
2816 tv_op(tv1, tv2, op)
2817 typval_T *tv1;
2818 typval_T *tv2;
2819 char_u *op;
2821 long n;
2822 char_u numbuf[NUMBUFLEN];
2823 char_u *s;
2825 /* Can't do anything with a Funcref or a Dict on the right. */
2826 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2828 switch (tv1->v_type)
2830 case VAR_DICT:
2831 case VAR_FUNC:
2832 break;
2834 case VAR_LIST:
2835 if (*op != '+' || tv2->v_type != VAR_LIST)
2836 break;
2837 /* List += List */
2838 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2839 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2840 return OK;
2842 case VAR_NUMBER:
2843 case VAR_STRING:
2844 if (tv2->v_type == VAR_LIST)
2845 break;
2846 if (*op == '+' || *op == '-')
2848 /* nr += nr or nr -= nr*/
2849 n = get_tv_number(tv1);
2850 if (*op == '+')
2851 n += get_tv_number(tv2);
2852 else
2853 n -= get_tv_number(tv2);
2854 clear_tv(tv1);
2855 tv1->v_type = VAR_NUMBER;
2856 tv1->vval.v_number = n;
2858 else
2860 /* str .= str */
2861 s = get_tv_string(tv1);
2862 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2863 clear_tv(tv1);
2864 tv1->v_type = VAR_STRING;
2865 tv1->vval.v_string = s;
2867 return OK;
2871 EMSG2(_(e_letwrong), op);
2872 return FAIL;
2876 * Add a watcher to a list.
2878 static void
2879 list_add_watch(l, lw)
2880 list_T *l;
2881 listwatch_T *lw;
2883 lw->lw_next = l->lv_watch;
2884 l->lv_watch = lw;
2888 * Remove a watcher from a list.
2889 * No warning when it isn't found...
2891 static void
2892 list_rem_watch(l, lwrem)
2893 list_T *l;
2894 listwatch_T *lwrem;
2896 listwatch_T *lw, **lwp;
2898 lwp = &l->lv_watch;
2899 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2901 if (lw == lwrem)
2903 *lwp = lw->lw_next;
2904 break;
2906 lwp = &lw->lw_next;
2911 * Just before removing an item from a list: advance watchers to the next
2912 * item.
2914 static void
2915 list_fix_watch(l, item)
2916 list_T *l;
2917 listitem_T *item;
2919 listwatch_T *lw;
2921 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2922 if (lw->lw_item == item)
2923 lw->lw_item = item->li_next;
2927 * Evaluate the expression used in a ":for var in expr" command.
2928 * "arg" points to "var".
2929 * Set "*errp" to TRUE for an error, FALSE otherwise;
2930 * Return a pointer that holds the info. Null when there is an error.
2932 void *
2933 eval_for_line(arg, errp, nextcmdp, skip)
2934 char_u *arg;
2935 int *errp;
2936 char_u **nextcmdp;
2937 int skip;
2939 forinfo_T *fi;
2940 char_u *expr;
2941 typval_T tv;
2942 list_T *l;
2944 *errp = TRUE; /* default: there is an error */
2946 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
2947 if (fi == NULL)
2948 return NULL;
2950 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
2951 if (expr == NULL)
2952 return fi;
2954 expr = skipwhite(expr);
2955 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
2957 EMSG(_("E690: Missing \"in\" after :for"));
2958 return fi;
2961 if (skip)
2962 ++emsg_skip;
2963 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
2965 *errp = FALSE;
2966 if (!skip)
2968 l = tv.vval.v_list;
2969 if (tv.v_type != VAR_LIST || l == NULL)
2971 EMSG(_(e_listreq));
2972 clear_tv(&tv);
2974 else
2976 /* No need to increment the refcount, it's already set for the
2977 * list being used in "tv". */
2978 fi->fi_list = l;
2979 list_add_watch(l, &fi->fi_lw);
2980 fi->fi_lw.lw_item = l->lv_first;
2984 if (skip)
2985 --emsg_skip;
2987 return fi;
2991 * Use the first item in a ":for" list. Advance to the next.
2992 * Assign the values to the variable (list). "arg" points to the first one.
2993 * Return TRUE when a valid item was found, FALSE when at end of list or
2994 * something wrong.
2997 next_for_item(fi_void, arg)
2998 void *fi_void;
2999 char_u *arg;
3001 forinfo_T *fi = (forinfo_T *)fi_void;
3002 int result;
3003 listitem_T *item;
3005 item = fi->fi_lw.lw_item;
3006 if (item == NULL)
3007 result = FALSE;
3008 else
3010 fi->fi_lw.lw_item = item->li_next;
3011 result = (ex_let_vars(arg, &item->li_tv, TRUE,
3012 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3014 return result;
3018 * Free the structure used to store info used by ":for".
3020 void
3021 free_for_info(fi_void)
3022 void *fi_void;
3024 forinfo_T *fi = (forinfo_T *)fi_void;
3026 if (fi != NULL && fi->fi_list != NULL)
3028 list_rem_watch(fi->fi_list, &fi->fi_lw);
3029 list_unref(fi->fi_list);
3031 vim_free(fi);
3034 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3036 void
3037 set_context_for_expression(xp, arg, cmdidx)
3038 expand_T *xp;
3039 char_u *arg;
3040 cmdidx_T cmdidx;
3042 int got_eq = FALSE;
3043 int c;
3044 char_u *p;
3046 if (cmdidx == CMD_let)
3048 xp->xp_context = EXPAND_USER_VARS;
3049 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3051 /* ":let var1 var2 ...": find last space. */
3052 for (p = arg + STRLEN(arg); p >= arg; )
3054 xp->xp_pattern = p;
3055 mb_ptr_back(arg, p);
3056 if (vim_iswhite(*p))
3057 break;
3059 return;
3062 else
3063 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3064 : EXPAND_EXPRESSION;
3065 while ((xp->xp_pattern = vim_strpbrk(arg,
3066 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3068 c = *xp->xp_pattern;
3069 if (c == '&')
3071 c = xp->xp_pattern[1];
3072 if (c == '&')
3074 ++xp->xp_pattern;
3075 xp->xp_context = cmdidx != CMD_let || got_eq
3076 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3078 else if (c != ' ')
3080 xp->xp_context = EXPAND_SETTINGS;
3081 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3082 xp->xp_pattern += 2;
3086 else if (c == '$')
3088 /* environment variable */
3089 xp->xp_context = EXPAND_ENV_VARS;
3091 else if (c == '=')
3093 got_eq = TRUE;
3094 xp->xp_context = EXPAND_EXPRESSION;
3096 else if (c == '<'
3097 && xp->xp_context == EXPAND_FUNCTIONS
3098 && vim_strchr(xp->xp_pattern, '(') == NULL)
3100 /* Function name can start with "<SNR>" */
3101 break;
3103 else if (cmdidx != CMD_let || got_eq)
3105 if (c == '"') /* string */
3107 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3108 if (c == '\\' && xp->xp_pattern[1] != NUL)
3109 ++xp->xp_pattern;
3110 xp->xp_context = EXPAND_NOTHING;
3112 else if (c == '\'') /* literal string */
3114 /* Trick: '' is like stopping and starting a literal string. */
3115 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3116 /* skip */ ;
3117 xp->xp_context = EXPAND_NOTHING;
3119 else if (c == '|')
3121 if (xp->xp_pattern[1] == '|')
3123 ++xp->xp_pattern;
3124 xp->xp_context = EXPAND_EXPRESSION;
3126 else
3127 xp->xp_context = EXPAND_COMMANDS;
3129 else
3130 xp->xp_context = EXPAND_EXPRESSION;
3132 else
3133 /* Doesn't look like something valid, expand as an expression
3134 * anyway. */
3135 xp->xp_context = EXPAND_EXPRESSION;
3136 arg = xp->xp_pattern;
3137 if (*arg != NUL)
3138 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3139 /* skip */ ;
3141 xp->xp_pattern = arg;
3144 #endif /* FEAT_CMDL_COMPL */
3147 * ":1,25call func(arg1, arg2)" function call.
3149 void
3150 ex_call(eap)
3151 exarg_T *eap;
3153 char_u *arg = eap->arg;
3154 char_u *startarg;
3155 char_u *name;
3156 char_u *tofree;
3157 int len;
3158 typval_T rettv;
3159 linenr_T lnum;
3160 int doesrange;
3161 int failed = FALSE;
3162 funcdict_T fudi;
3164 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3165 if (fudi.fd_newkey != NULL)
3167 /* Still need to give an error message for missing key. */
3168 EMSG2(_(e_dictkey), fudi.fd_newkey);
3169 vim_free(fudi.fd_newkey);
3171 if (tofree == NULL)
3172 return;
3174 /* Increase refcount on dictionary, it could get deleted when evaluating
3175 * the arguments. */
3176 if (fudi.fd_dict != NULL)
3177 ++fudi.fd_dict->dv_refcount;
3179 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3180 len = (int)STRLEN(tofree);
3181 name = deref_func_name(tofree, &len);
3183 /* Skip white space to allow ":call func ()". Not good, but required for
3184 * backward compatibility. */
3185 startarg = skipwhite(arg);
3186 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3188 if (*startarg != '(')
3190 EMSG2(_("E107: Missing braces: %s"), eap->arg);
3191 goto end;
3195 * When skipping, evaluate the function once, to find the end of the
3196 * arguments.
3197 * When the function takes a range, this is discovered after the first
3198 * call, and the loop is broken.
3200 if (eap->skip)
3202 ++emsg_skip;
3203 lnum = eap->line2; /* do it once, also with an invalid range */
3205 else
3206 lnum = eap->line1;
3207 for ( ; lnum <= eap->line2; ++lnum)
3209 if (!eap->skip && eap->addr_count > 0)
3211 curwin->w_cursor.lnum = lnum;
3212 curwin->w_cursor.col = 0;
3214 arg = startarg;
3215 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3216 eap->line1, eap->line2, &doesrange,
3217 !eap->skip, fudi.fd_dict) == FAIL)
3219 failed = TRUE;
3220 break;
3223 /* Handle a function returning a Funcref, Dictionary or List. */
3224 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3226 failed = TRUE;
3227 break;
3230 clear_tv(&rettv);
3231 if (doesrange || eap->skip)
3232 break;
3234 /* Stop when immediately aborting on error, or when an interrupt
3235 * occurred or an exception was thrown but not caught.
3236 * get_func_tv() returned OK, so that the check for trailing
3237 * characters below is executed. */
3238 if (aborting())
3239 break;
3241 if (eap->skip)
3242 --emsg_skip;
3244 if (!failed)
3246 /* Check for trailing illegal characters and a following command. */
3247 if (!ends_excmd(*arg))
3249 emsg_severe = TRUE;
3250 EMSG(_(e_trailing));
3252 else
3253 eap->nextcmd = check_nextcmd(arg);
3256 end:
3257 dict_unref(fudi.fd_dict);
3258 vim_free(tofree);
3262 * ":unlet[!] var1 ... " command.
3264 void
3265 ex_unlet(eap)
3266 exarg_T *eap;
3268 ex_unletlock(eap, eap->arg, 0);
3272 * ":lockvar" and ":unlockvar" commands
3274 void
3275 ex_lockvar(eap)
3276 exarg_T *eap;
3278 char_u *arg = eap->arg;
3279 int deep = 2;
3281 if (eap->forceit)
3282 deep = -1;
3283 else if (vim_isdigit(*arg))
3285 deep = getdigits(&arg);
3286 arg = skipwhite(arg);
3289 ex_unletlock(eap, arg, deep);
3293 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3295 static void
3296 ex_unletlock(eap, argstart, deep)
3297 exarg_T *eap;
3298 char_u *argstart;
3299 int deep;
3301 char_u *arg = argstart;
3302 char_u *name_end;
3303 int error = FALSE;
3304 lval_T lv;
3308 /* Parse the name and find the end. */
3309 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3310 FNE_CHECK_START);
3311 if (lv.ll_name == NULL)
3312 error = TRUE; /* error but continue parsing */
3313 if (name_end == NULL || (!vim_iswhite(*name_end)
3314 && !ends_excmd(*name_end)))
3316 if (name_end != NULL)
3318 emsg_severe = TRUE;
3319 EMSG(_(e_trailing));
3321 if (!(eap->skip || error))
3322 clear_lval(&lv);
3323 break;
3326 if (!error && !eap->skip)
3328 if (eap->cmdidx == CMD_unlet)
3330 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3331 error = TRUE;
3333 else
3335 if (do_lock_var(&lv, name_end, deep,
3336 eap->cmdidx == CMD_lockvar) == FAIL)
3337 error = TRUE;
3341 if (!eap->skip)
3342 clear_lval(&lv);
3344 arg = skipwhite(name_end);
3345 } while (!ends_excmd(*arg));
3347 eap->nextcmd = check_nextcmd(arg);
3350 static int
3351 do_unlet_var(lp, name_end, forceit)
3352 lval_T *lp;
3353 char_u *name_end;
3354 int forceit;
3356 int ret = OK;
3357 int cc;
3359 if (lp->ll_tv == NULL)
3361 cc = *name_end;
3362 *name_end = NUL;
3364 /* Normal name or expanded name. */
3365 if (check_changedtick(lp->ll_name))
3366 ret = FAIL;
3367 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3368 ret = FAIL;
3369 *name_end = cc;
3371 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3372 return FAIL;
3373 else if (lp->ll_range)
3375 listitem_T *li;
3377 /* Delete a range of List items. */
3378 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3380 li = lp->ll_li->li_next;
3381 listitem_remove(lp->ll_list, lp->ll_li);
3382 lp->ll_li = li;
3383 ++lp->ll_n1;
3386 else
3388 if (lp->ll_list != NULL)
3389 /* unlet a List item. */
3390 listitem_remove(lp->ll_list, lp->ll_li);
3391 else
3392 /* unlet a Dictionary item. */
3393 dictitem_remove(lp->ll_dict, lp->ll_di);
3396 return ret;
3400 * "unlet" a variable. Return OK if it existed, FAIL if not.
3401 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3404 do_unlet(name, forceit)
3405 char_u *name;
3406 int forceit;
3408 hashtab_T *ht;
3409 hashitem_T *hi;
3410 char_u *varname;
3412 ht = find_var_ht(name, &varname);
3413 if (ht != NULL && *varname != NUL)
3415 hi = hash_find(ht, varname);
3416 if (!HASHITEM_EMPTY(hi))
3418 if (var_check_fixed(HI2DI(hi)->di_flags, name))
3419 return FAIL;
3420 if (var_check_ro(HI2DI(hi)->di_flags, name))
3421 return FAIL;
3422 delete_var(ht, hi);
3423 return OK;
3426 if (forceit)
3427 return OK;
3428 EMSG2(_("E108: No such variable: \"%s\""), name);
3429 return FAIL;
3433 * Lock or unlock variable indicated by "lp".
3434 * "deep" is the levels to go (-1 for unlimited);
3435 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3437 static int
3438 do_lock_var(lp, name_end, deep, lock)
3439 lval_T *lp;
3440 char_u *name_end;
3441 int deep;
3442 int lock;
3444 int ret = OK;
3445 int cc;
3446 dictitem_T *di;
3448 if (deep == 0) /* nothing to do */
3449 return OK;
3451 if (lp->ll_tv == NULL)
3453 cc = *name_end;
3454 *name_end = NUL;
3456 /* Normal name or expanded name. */
3457 if (check_changedtick(lp->ll_name))
3458 ret = FAIL;
3459 else
3461 di = find_var(lp->ll_name, NULL);
3462 if (di == NULL)
3463 ret = FAIL;
3464 else
3466 if (lock)
3467 di->di_flags |= DI_FLAGS_LOCK;
3468 else
3469 di->di_flags &= ~DI_FLAGS_LOCK;
3470 item_lock(&di->di_tv, deep, lock);
3473 *name_end = cc;
3475 else if (lp->ll_range)
3477 listitem_T *li = lp->ll_li;
3479 /* (un)lock a range of List items. */
3480 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3482 item_lock(&li->li_tv, deep, lock);
3483 li = li->li_next;
3484 ++lp->ll_n1;
3487 else if (lp->ll_list != NULL)
3488 /* (un)lock a List item. */
3489 item_lock(&lp->ll_li->li_tv, deep, lock);
3490 else
3491 /* un(lock) a Dictionary item. */
3492 item_lock(&lp->ll_di->di_tv, deep, lock);
3494 return ret;
3498 * Lock or unlock an item. "deep" is nr of levels to go.
3500 static void
3501 item_lock(tv, deep, lock)
3502 typval_T *tv;
3503 int deep;
3504 int lock;
3506 static int recurse = 0;
3507 list_T *l;
3508 listitem_T *li;
3509 dict_T *d;
3510 hashitem_T *hi;
3511 int todo;
3513 if (recurse >= DICT_MAXNEST)
3515 EMSG(_("E743: variable nested too deep for (un)lock"));
3516 return;
3518 if (deep == 0)
3519 return;
3520 ++recurse;
3522 /* lock/unlock the item itself */
3523 if (lock)
3524 tv->v_lock |= VAR_LOCKED;
3525 else
3526 tv->v_lock &= ~VAR_LOCKED;
3528 switch (tv->v_type)
3530 case VAR_LIST:
3531 if ((l = tv->vval.v_list) != NULL)
3533 if (lock)
3534 l->lv_lock |= VAR_LOCKED;
3535 else
3536 l->lv_lock &= ~VAR_LOCKED;
3537 if (deep < 0 || deep > 1)
3538 /* recursive: lock/unlock the items the List contains */
3539 for (li = l->lv_first; li != NULL; li = li->li_next)
3540 item_lock(&li->li_tv, deep - 1, lock);
3542 break;
3543 case VAR_DICT:
3544 if ((d = tv->vval.v_dict) != NULL)
3546 if (lock)
3547 d->dv_lock |= VAR_LOCKED;
3548 else
3549 d->dv_lock &= ~VAR_LOCKED;
3550 if (deep < 0 || deep > 1)
3552 /* recursive: lock/unlock the items the List contains */
3553 todo = (int)d->dv_hashtab.ht_used;
3554 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3556 if (!HASHITEM_EMPTY(hi))
3558 --todo;
3559 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3565 --recurse;
3569 * Return TRUE if typeval "tv" is locked: Either tha value is locked itself or
3570 * it refers to a List or Dictionary that is locked.
3572 static int
3573 tv_islocked(tv)
3574 typval_T *tv;
3576 return (tv->v_lock & VAR_LOCKED)
3577 || (tv->v_type == VAR_LIST
3578 && tv->vval.v_list != NULL
3579 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3580 || (tv->v_type == VAR_DICT
3581 && tv->vval.v_dict != NULL
3582 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3585 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3587 * Delete all "menutrans_" variables.
3589 void
3590 del_menutrans_vars()
3592 hashitem_T *hi;
3593 int todo;
3595 hash_lock(&globvarht);
3596 todo = (int)globvarht.ht_used;
3597 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3599 if (!HASHITEM_EMPTY(hi))
3601 --todo;
3602 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3603 delete_var(&globvarht, hi);
3606 hash_unlock(&globvarht);
3608 #endif
3610 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3613 * Local string buffer for the next two functions to store a variable name
3614 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3615 * get_user_var_name().
3618 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3620 static char_u *varnamebuf = NULL;
3621 static int varnamebuflen = 0;
3624 * Function to concatenate a prefix and a variable name.
3626 static char_u *
3627 cat_prefix_varname(prefix, name)
3628 int prefix;
3629 char_u *name;
3631 int len;
3633 len = (int)STRLEN(name) + 3;
3634 if (len > varnamebuflen)
3636 vim_free(varnamebuf);
3637 len += 10; /* some additional space */
3638 varnamebuf = alloc(len);
3639 if (varnamebuf == NULL)
3641 varnamebuflen = 0;
3642 return NULL;
3644 varnamebuflen = len;
3646 *varnamebuf = prefix;
3647 varnamebuf[1] = ':';
3648 STRCPY(varnamebuf + 2, name);
3649 return varnamebuf;
3653 * Function given to ExpandGeneric() to obtain the list of user defined
3654 * (global/buffer/window/built-in) variable names.
3656 /*ARGSUSED*/
3657 char_u *
3658 get_user_var_name(xp, idx)
3659 expand_T *xp;
3660 int idx;
3662 static long_u gdone;
3663 static long_u bdone;
3664 static long_u wdone;
3665 #ifdef FEAT_WINDOWS
3666 static long_u tdone;
3667 #endif
3668 static int vidx;
3669 static hashitem_T *hi;
3670 hashtab_T *ht;
3672 if (idx == 0)
3674 gdone = bdone = wdone = vidx = 0;
3675 #ifdef FEAT_WINDOWS
3676 tdone = 0;
3677 #endif
3680 /* Global variables */
3681 if (gdone < globvarht.ht_used)
3683 if (gdone++ == 0)
3684 hi = globvarht.ht_array;
3685 else
3686 ++hi;
3687 while (HASHITEM_EMPTY(hi))
3688 ++hi;
3689 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3690 return cat_prefix_varname('g', hi->hi_key);
3691 return hi->hi_key;
3694 /* b: variables */
3695 ht = &curbuf->b_vars.dv_hashtab;
3696 if (bdone < ht->ht_used)
3698 if (bdone++ == 0)
3699 hi = ht->ht_array;
3700 else
3701 ++hi;
3702 while (HASHITEM_EMPTY(hi))
3703 ++hi;
3704 return cat_prefix_varname('b', hi->hi_key);
3706 if (bdone == ht->ht_used)
3708 ++bdone;
3709 return (char_u *)"b:changedtick";
3712 /* w: variables */
3713 ht = &curwin->w_vars.dv_hashtab;
3714 if (wdone < ht->ht_used)
3716 if (wdone++ == 0)
3717 hi = ht->ht_array;
3718 else
3719 ++hi;
3720 while (HASHITEM_EMPTY(hi))
3721 ++hi;
3722 return cat_prefix_varname('w', hi->hi_key);
3725 #ifdef FEAT_WINDOWS
3726 /* t: variables */
3727 ht = &curtab->tp_vars.dv_hashtab;
3728 if (tdone < ht->ht_used)
3730 if (tdone++ == 0)
3731 hi = ht->ht_array;
3732 else
3733 ++hi;
3734 while (HASHITEM_EMPTY(hi))
3735 ++hi;
3736 return cat_prefix_varname('t', hi->hi_key);
3738 #endif
3740 /* v: variables */
3741 if (vidx < VV_LEN)
3742 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3744 vim_free(varnamebuf);
3745 varnamebuf = NULL;
3746 varnamebuflen = 0;
3747 return NULL;
3750 #endif /* FEAT_CMDL_COMPL */
3753 * types for expressions.
3755 typedef enum
3757 TYPE_UNKNOWN = 0
3758 , TYPE_EQUAL /* == */
3759 , TYPE_NEQUAL /* != */
3760 , TYPE_GREATER /* > */
3761 , TYPE_GEQUAL /* >= */
3762 , TYPE_SMALLER /* < */
3763 , TYPE_SEQUAL /* <= */
3764 , TYPE_MATCH /* =~ */
3765 , TYPE_NOMATCH /* !~ */
3766 } exptype_T;
3769 * The "evaluate" argument: When FALSE, the argument is only parsed but not
3770 * executed. The function may return OK, but the rettv will be of type
3771 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
3775 * Handle zero level expression.
3776 * This calls eval1() and handles error message and nextcmd.
3777 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3778 * Note: "rettv.v_lock" is not set.
3779 * Return OK or FAIL.
3781 static int
3782 eval0(arg, rettv, nextcmd, evaluate)
3783 char_u *arg;
3784 typval_T *rettv;
3785 char_u **nextcmd;
3786 int evaluate;
3788 int ret;
3789 char_u *p;
3791 p = skipwhite(arg);
3792 ret = eval1(&p, rettv, evaluate);
3793 if (ret == FAIL || !ends_excmd(*p))
3795 if (ret != FAIL)
3796 clear_tv(rettv);
3798 * Report the invalid expression unless the expression evaluation has
3799 * been cancelled due to an aborting error, an interrupt, or an
3800 * exception.
3802 if (!aborting())
3803 EMSG2(_(e_invexpr2), arg);
3804 ret = FAIL;
3806 if (nextcmd != NULL)
3807 *nextcmd = check_nextcmd(p);
3809 return ret;
3813 * Handle top level expression:
3814 * expr1 ? expr0 : expr0
3816 * "arg" must point to the first non-white of the expression.
3817 * "arg" is advanced to the next non-white after the recognized expression.
3819 * Note: "rettv.v_lock" is not set.
3821 * Return OK or FAIL.
3823 static int
3824 eval1(arg, rettv, evaluate)
3825 char_u **arg;
3826 typval_T *rettv;
3827 int evaluate;
3829 int result;
3830 typval_T var2;
3833 * Get the first variable.
3835 if (eval2(arg, rettv, evaluate) == FAIL)
3836 return FAIL;
3838 if ((*arg)[0] == '?')
3840 result = FALSE;
3841 if (evaluate)
3843 int error = FALSE;
3845 if (get_tv_number_chk(rettv, &error) != 0)
3846 result = TRUE;
3847 clear_tv(rettv);
3848 if (error)
3849 return FAIL;
3853 * Get the second variable.
3855 *arg = skipwhite(*arg + 1);
3856 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
3857 return FAIL;
3860 * Check for the ":".
3862 if ((*arg)[0] != ':')
3864 EMSG(_("E109: Missing ':' after '?'"));
3865 if (evaluate && result)
3866 clear_tv(rettv);
3867 return FAIL;
3871 * Get the third variable.
3873 *arg = skipwhite(*arg + 1);
3874 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
3876 if (evaluate && result)
3877 clear_tv(rettv);
3878 return FAIL;
3880 if (evaluate && !result)
3881 *rettv = var2;
3884 return OK;
3888 * Handle first level expression:
3889 * expr2 || expr2 || expr2 logical OR
3891 * "arg" must point to the first non-white of the expression.
3892 * "arg" is advanced to the next non-white after the recognized expression.
3894 * Return OK or FAIL.
3896 static int
3897 eval2(arg, rettv, evaluate)
3898 char_u **arg;
3899 typval_T *rettv;
3900 int evaluate;
3902 typval_T var2;
3903 long result;
3904 int first;
3905 int error = FALSE;
3908 * Get the first variable.
3910 if (eval3(arg, rettv, evaluate) == FAIL)
3911 return FAIL;
3914 * Repeat until there is no following "||".
3916 first = TRUE;
3917 result = FALSE;
3918 while ((*arg)[0] == '|' && (*arg)[1] == '|')
3920 if (evaluate && first)
3922 if (get_tv_number_chk(rettv, &error) != 0)
3923 result = TRUE;
3924 clear_tv(rettv);
3925 if (error)
3926 return FAIL;
3927 first = FALSE;
3931 * Get the second variable.
3933 *arg = skipwhite(*arg + 2);
3934 if (eval3(arg, &var2, evaluate && !result) == FAIL)
3935 return FAIL;
3938 * Compute the result.
3940 if (evaluate && !result)
3942 if (get_tv_number_chk(&var2, &error) != 0)
3943 result = TRUE;
3944 clear_tv(&var2);
3945 if (error)
3946 return FAIL;
3948 if (evaluate)
3950 rettv->v_type = VAR_NUMBER;
3951 rettv->vval.v_number = result;
3955 return OK;
3959 * Handle second level expression:
3960 * expr3 && expr3 && expr3 logical AND
3962 * "arg" must point to the first non-white of the expression.
3963 * "arg" is advanced to the next non-white after the recognized expression.
3965 * Return OK or FAIL.
3967 static int
3968 eval3(arg, rettv, evaluate)
3969 char_u **arg;
3970 typval_T *rettv;
3971 int evaluate;
3973 typval_T var2;
3974 long result;
3975 int first;
3976 int error = FALSE;
3979 * Get the first variable.
3981 if (eval4(arg, rettv, evaluate) == FAIL)
3982 return FAIL;
3985 * Repeat until there is no following "&&".
3987 first = TRUE;
3988 result = TRUE;
3989 while ((*arg)[0] == '&' && (*arg)[1] == '&')
3991 if (evaluate && first)
3993 if (get_tv_number_chk(rettv, &error) == 0)
3994 result = FALSE;
3995 clear_tv(rettv);
3996 if (error)
3997 return FAIL;
3998 first = FALSE;
4002 * Get the second variable.
4004 *arg = skipwhite(*arg + 2);
4005 if (eval4(arg, &var2, evaluate && result) == FAIL)
4006 return FAIL;
4009 * Compute the result.
4011 if (evaluate && result)
4013 if (get_tv_number_chk(&var2, &error) == 0)
4014 result = FALSE;
4015 clear_tv(&var2);
4016 if (error)
4017 return FAIL;
4019 if (evaluate)
4021 rettv->v_type = VAR_NUMBER;
4022 rettv->vval.v_number = result;
4026 return OK;
4030 * Handle third level expression:
4031 * var1 == var2
4032 * var1 =~ var2
4033 * var1 != var2
4034 * var1 !~ var2
4035 * var1 > var2
4036 * var1 >= var2
4037 * var1 < var2
4038 * var1 <= var2
4039 * var1 is var2
4040 * var1 isnot var2
4042 * "arg" must point to the first non-white of the expression.
4043 * "arg" is advanced to the next non-white after the recognized expression.
4045 * Return OK or FAIL.
4047 static int
4048 eval4(arg, rettv, evaluate)
4049 char_u **arg;
4050 typval_T *rettv;
4051 int evaluate;
4053 typval_T var2;
4054 char_u *p;
4055 int i;
4056 exptype_T type = TYPE_UNKNOWN;
4057 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4058 int len = 2;
4059 long n1, n2;
4060 char_u *s1, *s2;
4061 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4062 regmatch_T regmatch;
4063 int ic;
4064 char_u *save_cpo;
4067 * Get the first variable.
4069 if (eval5(arg, rettv, evaluate) == FAIL)
4070 return FAIL;
4072 p = *arg;
4073 switch (p[0])
4075 case '=': if (p[1] == '=')
4076 type = TYPE_EQUAL;
4077 else if (p[1] == '~')
4078 type = TYPE_MATCH;
4079 break;
4080 case '!': if (p[1] == '=')
4081 type = TYPE_NEQUAL;
4082 else if (p[1] == '~')
4083 type = TYPE_NOMATCH;
4084 break;
4085 case '>': if (p[1] != '=')
4087 type = TYPE_GREATER;
4088 len = 1;
4090 else
4091 type = TYPE_GEQUAL;
4092 break;
4093 case '<': if (p[1] != '=')
4095 type = TYPE_SMALLER;
4096 len = 1;
4098 else
4099 type = TYPE_SEQUAL;
4100 break;
4101 case 'i': if (p[1] == 's')
4103 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4104 len = 5;
4105 if (!vim_isIDc(p[len]))
4107 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4108 type_is = TRUE;
4111 break;
4115 * If there is a comparitive operator, use it.
4117 if (type != TYPE_UNKNOWN)
4119 /* extra question mark appended: ignore case */
4120 if (p[len] == '?')
4122 ic = TRUE;
4123 ++len;
4125 /* extra '#' appended: match case */
4126 else if (p[len] == '#')
4128 ic = FALSE;
4129 ++len;
4131 /* nothing appened: use 'ignorecase' */
4132 else
4133 ic = p_ic;
4136 * Get the second variable.
4138 *arg = skipwhite(p + len);
4139 if (eval5(arg, &var2, evaluate) == FAIL)
4141 clear_tv(rettv);
4142 return FAIL;
4145 if (evaluate)
4147 if (type_is && rettv->v_type != var2.v_type)
4149 /* For "is" a different type always means FALSE, for "notis"
4150 * it means TRUE. */
4151 n1 = (type == TYPE_NEQUAL);
4153 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4155 if (type_is)
4157 n1 = (rettv->v_type == var2.v_type
4158 && rettv->vval.v_list == var2.vval.v_list);
4159 if (type == TYPE_NEQUAL)
4160 n1 = !n1;
4162 else if (rettv->v_type != var2.v_type
4163 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4165 if (rettv->v_type != var2.v_type)
4166 EMSG(_("E691: Can only compare List with List"));
4167 else
4168 EMSG(_("E692: Invalid operation for Lists"));
4169 clear_tv(rettv);
4170 clear_tv(&var2);
4171 return FAIL;
4173 else
4175 /* Compare two Lists for being equal or unequal. */
4176 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
4177 if (type == TYPE_NEQUAL)
4178 n1 = !n1;
4182 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4184 if (type_is)
4186 n1 = (rettv->v_type == var2.v_type
4187 && rettv->vval.v_dict == var2.vval.v_dict);
4188 if (type == TYPE_NEQUAL)
4189 n1 = !n1;
4191 else if (rettv->v_type != var2.v_type
4192 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4194 if (rettv->v_type != var2.v_type)
4195 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4196 else
4197 EMSG(_("E736: Invalid operation for Dictionary"));
4198 clear_tv(rettv);
4199 clear_tv(&var2);
4200 return FAIL;
4202 else
4204 /* Compare two Dictionaries for being equal or unequal. */
4205 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4206 if (type == TYPE_NEQUAL)
4207 n1 = !n1;
4211 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4213 if (rettv->v_type != var2.v_type
4214 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4216 if (rettv->v_type != var2.v_type)
4217 EMSG(_("E693: Can only compare Funcref with Funcref"));
4218 else
4219 EMSG(_("E694: Invalid operation for Funcrefs"));
4220 clear_tv(rettv);
4221 clear_tv(&var2);
4222 return FAIL;
4224 else
4226 /* Compare two Funcrefs for being equal or unequal. */
4227 if (rettv->vval.v_string == NULL
4228 || var2.vval.v_string == NULL)
4229 n1 = FALSE;
4230 else
4231 n1 = STRCMP(rettv->vval.v_string,
4232 var2.vval.v_string) == 0;
4233 if (type == TYPE_NEQUAL)
4234 n1 = !n1;
4239 * If one of the two variables is a number, compare as a number.
4240 * When using "=~" or "!~", always compare as string.
4242 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4243 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4245 n1 = get_tv_number(rettv);
4246 n2 = get_tv_number(&var2);
4247 switch (type)
4249 case TYPE_EQUAL: n1 = (n1 == n2); break;
4250 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4251 case TYPE_GREATER: n1 = (n1 > n2); break;
4252 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4253 case TYPE_SMALLER: n1 = (n1 < n2); break;
4254 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4255 case TYPE_UNKNOWN:
4256 case TYPE_MATCH:
4257 case TYPE_NOMATCH: break; /* avoid gcc warning */
4260 else
4262 s1 = get_tv_string_buf(rettv, buf1);
4263 s2 = get_tv_string_buf(&var2, buf2);
4264 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4265 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4266 else
4267 i = 0;
4268 n1 = FALSE;
4269 switch (type)
4271 case TYPE_EQUAL: n1 = (i == 0); break;
4272 case TYPE_NEQUAL: n1 = (i != 0); break;
4273 case TYPE_GREATER: n1 = (i > 0); break;
4274 case TYPE_GEQUAL: n1 = (i >= 0); break;
4275 case TYPE_SMALLER: n1 = (i < 0); break;
4276 case TYPE_SEQUAL: n1 = (i <= 0); break;
4278 case TYPE_MATCH:
4279 case TYPE_NOMATCH:
4280 /* avoid 'l' flag in 'cpoptions' */
4281 save_cpo = p_cpo;
4282 p_cpo = (char_u *)"";
4283 regmatch.regprog = vim_regcomp(s2,
4284 RE_MAGIC + RE_STRING);
4285 regmatch.rm_ic = ic;
4286 if (regmatch.regprog != NULL)
4288 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4289 vim_free(regmatch.regprog);
4290 if (type == TYPE_NOMATCH)
4291 n1 = !n1;
4293 p_cpo = save_cpo;
4294 break;
4296 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4299 clear_tv(rettv);
4300 clear_tv(&var2);
4301 rettv->v_type = VAR_NUMBER;
4302 rettv->vval.v_number = n1;
4306 return OK;
4310 * Handle fourth level expression:
4311 * + number addition
4312 * - number subtraction
4313 * . string concatenation
4315 * "arg" must point to the first non-white of the expression.
4316 * "arg" is advanced to the next non-white after the recognized expression.
4318 * Return OK or FAIL.
4320 static int
4321 eval5(arg, rettv, evaluate)
4322 char_u **arg;
4323 typval_T *rettv;
4324 int evaluate;
4326 typval_T var2;
4327 typval_T var3;
4328 int op;
4329 long n1, n2;
4330 char_u *s1, *s2;
4331 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4332 char_u *p;
4335 * Get the first variable.
4337 if (eval6(arg, rettv, evaluate) == FAIL)
4338 return FAIL;
4341 * Repeat computing, until no '+', '-' or '.' is following.
4343 for (;;)
4345 op = **arg;
4346 if (op != '+' && op != '-' && op != '.')
4347 break;
4349 if (op != '+' || rettv->v_type != VAR_LIST)
4351 /* For "list + ...", an illegal use of the first operand as
4352 * a number cannot be determined before evaluating the 2nd
4353 * operand: if this is also a list, all is ok.
4354 * For "something . ...", "something - ..." or "non-list + ...",
4355 * we know that the first operand needs to be a string or number
4356 * without evaluating the 2nd operand. So check before to avoid
4357 * side effects after an error. */
4358 if (evaluate && get_tv_string_chk(rettv) == NULL)
4360 clear_tv(rettv);
4361 return FAIL;
4366 * Get the second variable.
4368 *arg = skipwhite(*arg + 1);
4369 if (eval6(arg, &var2, evaluate) == FAIL)
4371 clear_tv(rettv);
4372 return FAIL;
4375 if (evaluate)
4378 * Compute the result.
4380 if (op == '.')
4382 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4383 s2 = get_tv_string_buf_chk(&var2, buf2);
4384 if (s2 == NULL) /* type error ? */
4386 clear_tv(rettv);
4387 clear_tv(&var2);
4388 return FAIL;
4390 p = concat_str(s1, s2);
4391 clear_tv(rettv);
4392 rettv->v_type = VAR_STRING;
4393 rettv->vval.v_string = p;
4395 else if (op == '+' && rettv->v_type == VAR_LIST
4396 && var2.v_type == VAR_LIST)
4398 /* concatenate Lists */
4399 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4400 &var3) == FAIL)
4402 clear_tv(rettv);
4403 clear_tv(&var2);
4404 return FAIL;
4406 clear_tv(rettv);
4407 *rettv = var3;
4409 else
4411 int error = FALSE;
4413 n1 = get_tv_number_chk(rettv, &error);
4414 if (error)
4416 /* This can only happen for "list + non-list".
4417 * For "non-list + ..." or "something - ...", we returned
4418 * before evaluating the 2nd operand. */
4419 clear_tv(rettv);
4420 return FAIL;
4422 n2 = get_tv_number_chk(&var2, &error);
4423 if (error)
4425 clear_tv(rettv);
4426 clear_tv(&var2);
4427 return FAIL;
4429 clear_tv(rettv);
4430 if (op == '+')
4431 n1 = n1 + n2;
4432 else
4433 n1 = n1 - n2;
4434 rettv->v_type = VAR_NUMBER;
4435 rettv->vval.v_number = n1;
4437 clear_tv(&var2);
4440 return OK;
4444 * Handle fifth level expression:
4445 * * number multiplication
4446 * / number division
4447 * % number modulo
4449 * "arg" must point to the first non-white of the expression.
4450 * "arg" is advanced to the next non-white after the recognized expression.
4452 * Return OK or FAIL.
4454 static int
4455 eval6(arg, rettv, evaluate)
4456 char_u **arg;
4457 typval_T *rettv;
4458 int evaluate;
4460 typval_T var2;
4461 int op;
4462 long n1, n2;
4463 int error = FALSE;
4466 * Get the first variable.
4468 if (eval7(arg, rettv, evaluate) == FAIL)
4469 return FAIL;
4472 * Repeat computing, until no '*', '/' or '%' is following.
4474 for (;;)
4476 op = **arg;
4477 if (op != '*' && op != '/' && op != '%')
4478 break;
4480 if (evaluate)
4482 n1 = get_tv_number_chk(rettv, &error);
4483 clear_tv(rettv);
4484 if (error)
4485 return FAIL;
4487 else
4488 n1 = 0;
4491 * Get the second variable.
4493 *arg = skipwhite(*arg + 1);
4494 if (eval7(arg, &var2, evaluate) == FAIL)
4495 return FAIL;
4497 if (evaluate)
4499 n2 = get_tv_number_chk(&var2, &error);
4500 clear_tv(&var2);
4501 if (error)
4502 return FAIL;
4505 * Compute the result.
4507 if (op == '*')
4508 n1 = n1 * n2;
4509 else if (op == '/')
4511 if (n2 == 0) /* give an error message? */
4512 n1 = 0x7fffffffL;
4513 else
4514 n1 = n1 / n2;
4516 else
4518 if (n2 == 0) /* give an error message? */
4519 n1 = 0;
4520 else
4521 n1 = n1 % n2;
4523 rettv->v_type = VAR_NUMBER;
4524 rettv->vval.v_number = n1;
4528 return OK;
4532 * Handle sixth level expression:
4533 * number number constant
4534 * "string" string constant
4535 * 'string' literal string constant
4536 * &option-name option value
4537 * @r register contents
4538 * identifier variable value
4539 * function() function call
4540 * $VAR environment variable
4541 * (expression) nested expression
4542 * [expr, expr] List
4543 * {key: val, key: val} Dictionary
4545 * Also handle:
4546 * ! in front logical NOT
4547 * - in front unary minus
4548 * + in front unary plus (ignored)
4549 * trailing [] subscript in String or List
4550 * trailing .name entry in Dictionary
4552 * "arg" must point to the first non-white of the expression.
4553 * "arg" is advanced to the next non-white after the recognized expression.
4555 * Return OK or FAIL.
4557 static int
4558 eval7(arg, rettv, evaluate)
4559 char_u **arg;
4560 typval_T *rettv;
4561 int evaluate;
4563 long n;
4564 int len;
4565 char_u *s;
4566 int val;
4567 char_u *start_leader, *end_leader;
4568 int ret = OK;
4569 char_u *alias;
4572 * Initialise variable so that clear_tv() can't mistake this for a
4573 * string and free a string that isn't there.
4575 rettv->v_type = VAR_UNKNOWN;
4578 * Skip '!' and '-' characters. They are handled later.
4580 start_leader = *arg;
4581 while (**arg == '!' || **arg == '-' || **arg == '+')
4582 *arg = skipwhite(*arg + 1);
4583 end_leader = *arg;
4585 switch (**arg)
4588 * Number constant.
4590 case '0':
4591 case '1':
4592 case '2':
4593 case '3':
4594 case '4':
4595 case '5':
4596 case '6':
4597 case '7':
4598 case '8':
4599 case '9':
4600 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4601 *arg += len;
4602 if (evaluate)
4604 rettv->v_type = VAR_NUMBER;
4605 rettv->vval.v_number = n;
4607 break;
4610 * String constant: "string".
4612 case '"': ret = get_string_tv(arg, rettv, evaluate);
4613 break;
4616 * Literal string constant: 'str''ing'.
4618 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
4619 break;
4622 * List: [expr, expr]
4624 case '[': ret = get_list_tv(arg, rettv, evaluate);
4625 break;
4628 * Dictionary: {key: val, key: val}
4630 case '{': ret = get_dict_tv(arg, rettv, evaluate);
4631 break;
4634 * Option value: &name
4636 case '&': ret = get_option_tv(arg, rettv, evaluate);
4637 break;
4640 * Environment variable: $VAR.
4642 case '$': ret = get_env_tv(arg, rettv, evaluate);
4643 break;
4646 * Register contents: @r.
4648 case '@': ++*arg;
4649 if (evaluate)
4651 rettv->v_type = VAR_STRING;
4652 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4654 if (**arg != NUL)
4655 ++*arg;
4656 break;
4659 * nested expression: (expression).
4661 case '(': *arg = skipwhite(*arg + 1);
4662 ret = eval1(arg, rettv, evaluate); /* recursive! */
4663 if (**arg == ')')
4664 ++*arg;
4665 else if (ret == OK)
4667 EMSG(_("E110: Missing ')'"));
4668 clear_tv(rettv);
4669 ret = FAIL;
4671 break;
4673 default: ret = NOTDONE;
4674 break;
4677 if (ret == NOTDONE)
4680 * Must be a variable or function name.
4681 * Can also be a curly-braces kind of name: {expr}.
4683 s = *arg;
4684 len = get_name_len(arg, &alias, evaluate, TRUE);
4685 if (alias != NULL)
4686 s = alias;
4688 if (len <= 0)
4689 ret = FAIL;
4690 else
4692 if (**arg == '(') /* recursive! */
4694 /* If "s" is the name of a variable of type VAR_FUNC
4695 * use its contents. */
4696 s = deref_func_name(s, &len);
4698 /* Invoke the function. */
4699 ret = get_func_tv(s, len, rettv, arg,
4700 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
4701 &len, evaluate, NULL);
4702 /* Stop the expression evaluation when immediately
4703 * aborting on error, or when an interrupt occurred or
4704 * an exception was thrown but not caught. */
4705 if (aborting())
4707 if (ret == OK)
4708 clear_tv(rettv);
4709 ret = FAIL;
4712 else if (evaluate)
4713 ret = get_var_tv(s, len, rettv, TRUE);
4714 else
4715 ret = OK;
4718 if (alias != NULL)
4719 vim_free(alias);
4722 *arg = skipwhite(*arg);
4724 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
4725 * expr(expr). */
4726 if (ret == OK)
4727 ret = handle_subscript(arg, rettv, evaluate, TRUE);
4730 * Apply logical NOT and unary '-', from right to left, ignore '+'.
4732 if (ret == OK && evaluate && end_leader > start_leader)
4734 int error = FALSE;
4736 val = get_tv_number_chk(rettv, &error);
4737 if (error)
4739 clear_tv(rettv);
4740 ret = FAIL;
4742 else
4744 while (end_leader > start_leader)
4746 --end_leader;
4747 if (*end_leader == '!')
4748 val = !val;
4749 else if (*end_leader == '-')
4750 val = -val;
4752 clear_tv(rettv);
4753 rettv->v_type = VAR_NUMBER;
4754 rettv->vval.v_number = val;
4758 return ret;
4762 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
4763 * "*arg" points to the '[' or '.'.
4764 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
4766 static int
4767 eval_index(arg, rettv, evaluate, verbose)
4768 char_u **arg;
4769 typval_T *rettv;
4770 int evaluate;
4771 int verbose; /* give error messages */
4773 int empty1 = FALSE, empty2 = FALSE;
4774 typval_T var1, var2;
4775 long n1, n2 = 0;
4776 long len = -1;
4777 int range = FALSE;
4778 char_u *s;
4779 char_u *key = NULL;
4781 if (rettv->v_type == VAR_FUNC)
4783 if (verbose)
4784 EMSG(_("E695: Cannot index a Funcref"));
4785 return FAIL;
4788 if (**arg == '.')
4791 * dict.name
4793 key = *arg + 1;
4794 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
4796 if (len == 0)
4797 return FAIL;
4798 *arg = skipwhite(key + len);
4800 else
4803 * something[idx]
4805 * Get the (first) variable from inside the [].
4807 *arg = skipwhite(*arg + 1);
4808 if (**arg == ':')
4809 empty1 = TRUE;
4810 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
4811 return FAIL;
4812 else if (evaluate && get_tv_string_chk(&var1) == NULL)
4814 /* not a number or string */
4815 clear_tv(&var1);
4816 return FAIL;
4820 * Get the second variable from inside the [:].
4822 if (**arg == ':')
4824 range = TRUE;
4825 *arg = skipwhite(*arg + 1);
4826 if (**arg == ']')
4827 empty2 = TRUE;
4828 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
4830 if (!empty1)
4831 clear_tv(&var1);
4832 return FAIL;
4834 else if (evaluate && get_tv_string_chk(&var2) == NULL)
4836 /* not a number or string */
4837 if (!empty1)
4838 clear_tv(&var1);
4839 clear_tv(&var2);
4840 return FAIL;
4844 /* Check for the ']'. */
4845 if (**arg != ']')
4847 if (verbose)
4848 EMSG(_(e_missbrac));
4849 clear_tv(&var1);
4850 if (range)
4851 clear_tv(&var2);
4852 return FAIL;
4854 *arg = skipwhite(*arg + 1); /* skip the ']' */
4857 if (evaluate)
4859 n1 = 0;
4860 if (!empty1 && rettv->v_type != VAR_DICT)
4862 n1 = get_tv_number(&var1);
4863 clear_tv(&var1);
4865 if (range)
4867 if (empty2)
4868 n2 = -1;
4869 else
4871 n2 = get_tv_number(&var2);
4872 clear_tv(&var2);
4876 switch (rettv->v_type)
4878 case VAR_NUMBER:
4879 case VAR_STRING:
4880 s = get_tv_string(rettv);
4881 len = (long)STRLEN(s);
4882 if (range)
4884 /* The resulting variable is a substring. If the indexes
4885 * are out of range the result is empty. */
4886 if (n1 < 0)
4888 n1 = len + n1;
4889 if (n1 < 0)
4890 n1 = 0;
4892 if (n2 < 0)
4893 n2 = len + n2;
4894 else if (n2 >= len)
4895 n2 = len;
4896 if (n1 >= len || n2 < 0 || n1 > n2)
4897 s = NULL;
4898 else
4899 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
4901 else
4903 /* The resulting variable is a string of a single
4904 * character. If the index is too big or negative the
4905 * result is empty. */
4906 if (n1 >= len || n1 < 0)
4907 s = NULL;
4908 else
4909 s = vim_strnsave(s + n1, 1);
4911 clear_tv(rettv);
4912 rettv->v_type = VAR_STRING;
4913 rettv->vval.v_string = s;
4914 break;
4916 case VAR_LIST:
4917 len = list_len(rettv->vval.v_list);
4918 if (n1 < 0)
4919 n1 = len + n1;
4920 if (!empty1 && (n1 < 0 || n1 >= len))
4922 /* For a range we allow invalid values and return an empty
4923 * list. A list index out of range is an error. */
4924 if (!range)
4926 if (verbose)
4927 EMSGN(_(e_listidx), n1);
4928 return FAIL;
4930 n1 = len;
4932 if (range)
4934 list_T *l;
4935 listitem_T *item;
4937 if (n2 < 0)
4938 n2 = len + n2;
4939 else if (n2 >= len)
4940 n2 = len - 1;
4941 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
4942 n2 = -1;
4943 l = list_alloc();
4944 if (l == NULL)
4945 return FAIL;
4946 for (item = list_find(rettv->vval.v_list, n1);
4947 n1 <= n2; ++n1)
4949 if (list_append_tv(l, &item->li_tv) == FAIL)
4951 list_free(l, TRUE);
4952 return FAIL;
4954 item = item->li_next;
4956 clear_tv(rettv);
4957 rettv->v_type = VAR_LIST;
4958 rettv->vval.v_list = l;
4959 ++l->lv_refcount;
4961 else
4963 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
4964 clear_tv(rettv);
4965 *rettv = var1;
4967 break;
4969 case VAR_DICT:
4970 if (range)
4972 if (verbose)
4973 EMSG(_(e_dictrange));
4974 if (len == -1)
4975 clear_tv(&var1);
4976 return FAIL;
4979 dictitem_T *item;
4981 if (len == -1)
4983 key = get_tv_string(&var1);
4984 if (*key == NUL)
4986 if (verbose)
4987 EMSG(_(e_emptykey));
4988 clear_tv(&var1);
4989 return FAIL;
4993 item = dict_find(rettv->vval.v_dict, key, (int)len);
4995 if (item == NULL && verbose)
4996 EMSG2(_(e_dictkey), key);
4997 if (len == -1)
4998 clear_tv(&var1);
4999 if (item == NULL)
5000 return FAIL;
5002 copy_tv(&item->di_tv, &var1);
5003 clear_tv(rettv);
5004 *rettv = var1;
5006 break;
5010 return OK;
5014 * Get an option value.
5015 * "arg" points to the '&' or '+' before the option name.
5016 * "arg" is advanced to character after the option name.
5017 * Return OK or FAIL.
5019 static int
5020 get_option_tv(arg, rettv, evaluate)
5021 char_u **arg;
5022 typval_T *rettv; /* when NULL, only check if option exists */
5023 int evaluate;
5025 char_u *option_end;
5026 long numval;
5027 char_u *stringval;
5028 int opt_type;
5029 int c;
5030 int working = (**arg == '+'); /* has("+option") */
5031 int ret = OK;
5032 int opt_flags;
5035 * Isolate the option name and find its value.
5037 option_end = find_option_end(arg, &opt_flags);
5038 if (option_end == NULL)
5040 if (rettv != NULL)
5041 EMSG2(_("E112: Option name missing: %s"), *arg);
5042 return FAIL;
5045 if (!evaluate)
5047 *arg = option_end;
5048 return OK;
5051 c = *option_end;
5052 *option_end = NUL;
5053 opt_type = get_option_value(*arg, &numval,
5054 rettv == NULL ? NULL : &stringval, opt_flags);
5056 if (opt_type == -3) /* invalid name */
5058 if (rettv != NULL)
5059 EMSG2(_("E113: Unknown option: %s"), *arg);
5060 ret = FAIL;
5062 else if (rettv != NULL)
5064 if (opt_type == -2) /* hidden string option */
5066 rettv->v_type = VAR_STRING;
5067 rettv->vval.v_string = NULL;
5069 else if (opt_type == -1) /* hidden number option */
5071 rettv->v_type = VAR_NUMBER;
5072 rettv->vval.v_number = 0;
5074 else if (opt_type == 1) /* number option */
5076 rettv->v_type = VAR_NUMBER;
5077 rettv->vval.v_number = numval;
5079 else /* string option */
5081 rettv->v_type = VAR_STRING;
5082 rettv->vval.v_string = stringval;
5085 else if (working && (opt_type == -2 || opt_type == -1))
5086 ret = FAIL;
5088 *option_end = c; /* put back for error messages */
5089 *arg = option_end;
5091 return ret;
5095 * Allocate a variable for a string constant.
5096 * Return OK or FAIL.
5098 static int
5099 get_string_tv(arg, rettv, evaluate)
5100 char_u **arg;
5101 typval_T *rettv;
5102 int evaluate;
5104 char_u *p;
5105 char_u *name;
5106 int extra = 0;
5109 * Find the end of the string, skipping backslashed characters.
5111 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5113 if (*p == '\\' && p[1] != NUL)
5115 ++p;
5116 /* A "\<x>" form occupies at least 4 characters, and produces up
5117 * to 6 characters: reserve space for 2 extra */
5118 if (*p == '<')
5119 extra += 2;
5123 if (*p != '"')
5125 EMSG2(_("E114: Missing quote: %s"), *arg);
5126 return FAIL;
5129 /* If only parsing, set *arg and return here */
5130 if (!evaluate)
5132 *arg = p + 1;
5133 return OK;
5137 * Copy the string into allocated memory, handling backslashed
5138 * characters.
5140 name = alloc((unsigned)(p - *arg + extra));
5141 if (name == NULL)
5142 return FAIL;
5143 rettv->v_type = VAR_STRING;
5144 rettv->vval.v_string = name;
5146 for (p = *arg + 1; *p != NUL && *p != '"'; )
5148 if (*p == '\\')
5150 switch (*++p)
5152 case 'b': *name++ = BS; ++p; break;
5153 case 'e': *name++ = ESC; ++p; break;
5154 case 'f': *name++ = FF; ++p; break;
5155 case 'n': *name++ = NL; ++p; break;
5156 case 'r': *name++ = CAR; ++p; break;
5157 case 't': *name++ = TAB; ++p; break;
5159 case 'X': /* hex: "\x1", "\x12" */
5160 case 'x':
5161 case 'u': /* Unicode: "\u0023" */
5162 case 'U':
5163 if (vim_isxdigit(p[1]))
5165 int n, nr;
5166 int c = toupper(*p);
5168 if (c == 'X')
5169 n = 2;
5170 else
5171 n = 4;
5172 nr = 0;
5173 while (--n >= 0 && vim_isxdigit(p[1]))
5175 ++p;
5176 nr = (nr << 4) + hex2nr(*p);
5178 ++p;
5179 #ifdef FEAT_MBYTE
5180 /* For "\u" store the number according to
5181 * 'encoding'. */
5182 if (c != 'X')
5183 name += (*mb_char2bytes)(nr, name);
5184 else
5185 #endif
5186 *name++ = nr;
5188 break;
5190 /* octal: "\1", "\12", "\123" */
5191 case '0':
5192 case '1':
5193 case '2':
5194 case '3':
5195 case '4':
5196 case '5':
5197 case '6':
5198 case '7': *name = *p++ - '0';
5199 if (*p >= '0' && *p <= '7')
5201 *name = (*name << 3) + *p++ - '0';
5202 if (*p >= '0' && *p <= '7')
5203 *name = (*name << 3) + *p++ - '0';
5205 ++name;
5206 break;
5208 /* Special key, e.g.: "\<C-W>" */
5209 case '<': extra = trans_special(&p, name, TRUE);
5210 if (extra != 0)
5212 name += extra;
5213 break;
5215 /* FALLTHROUGH */
5217 default: MB_COPY_CHAR(p, name);
5218 break;
5221 else
5222 MB_COPY_CHAR(p, name);
5225 *name = NUL;
5226 *arg = p + 1;
5228 return OK;
5232 * Allocate a variable for a 'str''ing' constant.
5233 * Return OK or FAIL.
5235 static int
5236 get_lit_string_tv(arg, rettv, evaluate)
5237 char_u **arg;
5238 typval_T *rettv;
5239 int evaluate;
5241 char_u *p;
5242 char_u *str;
5243 int reduce = 0;
5246 * Find the end of the string, skipping ''.
5248 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5250 if (*p == '\'')
5252 if (p[1] != '\'')
5253 break;
5254 ++reduce;
5255 ++p;
5259 if (*p != '\'')
5261 EMSG2(_("E115: Missing quote: %s"), *arg);
5262 return FAIL;
5265 /* If only parsing return after setting "*arg" */
5266 if (!evaluate)
5268 *arg = p + 1;
5269 return OK;
5273 * Copy the string into allocated memory, handling '' to ' reduction.
5275 str = alloc((unsigned)((p - *arg) - reduce));
5276 if (str == NULL)
5277 return FAIL;
5278 rettv->v_type = VAR_STRING;
5279 rettv->vval.v_string = str;
5281 for (p = *arg + 1; *p != NUL; )
5283 if (*p == '\'')
5285 if (p[1] != '\'')
5286 break;
5287 ++p;
5289 MB_COPY_CHAR(p, str);
5291 *str = NUL;
5292 *arg = p + 1;
5294 return OK;
5298 * Allocate a variable for a List and fill it from "*arg".
5299 * Return OK or FAIL.
5301 static int
5302 get_list_tv(arg, rettv, evaluate)
5303 char_u **arg;
5304 typval_T *rettv;
5305 int evaluate;
5307 list_T *l = NULL;
5308 typval_T tv;
5309 listitem_T *item;
5311 if (evaluate)
5313 l = list_alloc();
5314 if (l == NULL)
5315 return FAIL;
5318 *arg = skipwhite(*arg + 1);
5319 while (**arg != ']' && **arg != NUL)
5321 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5322 goto failret;
5323 if (evaluate)
5325 item = listitem_alloc();
5326 if (item != NULL)
5328 item->li_tv = tv;
5329 item->li_tv.v_lock = 0;
5330 list_append(l, item);
5332 else
5333 clear_tv(&tv);
5336 if (**arg == ']')
5337 break;
5338 if (**arg != ',')
5340 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5341 goto failret;
5343 *arg = skipwhite(*arg + 1);
5346 if (**arg != ']')
5348 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5349 failret:
5350 if (evaluate)
5351 list_free(l, TRUE);
5352 return FAIL;
5355 *arg = skipwhite(*arg + 1);
5356 if (evaluate)
5358 rettv->v_type = VAR_LIST;
5359 rettv->vval.v_list = l;
5360 ++l->lv_refcount;
5363 return OK;
5367 * Allocate an empty header for a list.
5368 * Caller should take care of the reference count.
5370 list_T *
5371 list_alloc()
5373 list_T *l;
5375 l = (list_T *)alloc_clear(sizeof(list_T));
5376 if (l != NULL)
5378 /* Prepend the list to the list of lists for garbage collection. */
5379 if (first_list != NULL)
5380 first_list->lv_used_prev = l;
5381 l->lv_used_prev = NULL;
5382 l->lv_used_next = first_list;
5383 first_list = l;
5385 return l;
5389 * Allocate an empty list for a return value.
5390 * Returns OK or FAIL.
5392 static int
5393 rettv_list_alloc(rettv)
5394 typval_T *rettv;
5396 list_T *l = list_alloc();
5398 if (l == NULL)
5399 return FAIL;
5401 rettv->vval.v_list = l;
5402 rettv->v_type = VAR_LIST;
5403 ++l->lv_refcount;
5404 return OK;
5408 * Unreference a list: decrement the reference count and free it when it
5409 * becomes zero.
5411 void
5412 list_unref(l)
5413 list_T *l;
5415 if (l != NULL && --l->lv_refcount <= 0)
5416 list_free(l, TRUE);
5420 * Free a list, including all items it points to.
5421 * Ignores the reference count.
5423 void
5424 list_free(l, recurse)
5425 list_T *l;
5426 int recurse; /* Free Lists and Dictionaries recursively. */
5428 listitem_T *item;
5430 /* Remove the list from the list of lists for garbage collection. */
5431 if (l->lv_used_prev == NULL)
5432 first_list = l->lv_used_next;
5433 else
5434 l->lv_used_prev->lv_used_next = l->lv_used_next;
5435 if (l->lv_used_next != NULL)
5436 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5438 for (item = l->lv_first; item != NULL; item = l->lv_first)
5440 /* Remove the item before deleting it. */
5441 l->lv_first = item->li_next;
5442 if (recurse || (item->li_tv.v_type != VAR_LIST
5443 && item->li_tv.v_type != VAR_DICT))
5444 clear_tv(&item->li_tv);
5445 vim_free(item);
5447 vim_free(l);
5451 * Allocate a list item.
5453 static listitem_T *
5454 listitem_alloc()
5456 return (listitem_T *)alloc(sizeof(listitem_T));
5460 * Free a list item. Also clears the value. Does not notify watchers.
5462 static void
5463 listitem_free(item)
5464 listitem_T *item;
5466 clear_tv(&item->li_tv);
5467 vim_free(item);
5471 * Remove a list item from a List and free it. Also clears the value.
5473 static void
5474 listitem_remove(l, item)
5475 list_T *l;
5476 listitem_T *item;
5478 list_remove(l, item, item);
5479 listitem_free(item);
5483 * Get the number of items in a list.
5485 static long
5486 list_len(l)
5487 list_T *l;
5489 if (l == NULL)
5490 return 0L;
5491 return l->lv_len;
5495 * Return TRUE when two lists have exactly the same values.
5497 static int
5498 list_equal(l1, l2, ic)
5499 list_T *l1;
5500 list_T *l2;
5501 int ic; /* ignore case for strings */
5503 listitem_T *item1, *item2;
5505 if (l1 == l2)
5506 return TRUE;
5507 if (list_len(l1) != list_len(l2))
5508 return FALSE;
5510 for (item1 = l1->lv_first, item2 = l2->lv_first;
5511 item1 != NULL && item2 != NULL;
5512 item1 = item1->li_next, item2 = item2->li_next)
5513 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5514 return FALSE;
5515 return item1 == NULL && item2 == NULL;
5518 #if defined(FEAT_PYTHON) || defined(PROTO)
5520 * Return the dictitem that an entry in a hashtable points to.
5522 dictitem_T *
5523 dict_lookup(hi)
5524 hashitem_T *hi;
5526 return HI2DI(hi);
5528 #endif
5531 * Return TRUE when two dictionaries have exactly the same key/values.
5533 static int
5534 dict_equal(d1, d2, ic)
5535 dict_T *d1;
5536 dict_T *d2;
5537 int ic; /* ignore case for strings */
5539 hashitem_T *hi;
5540 dictitem_T *item2;
5541 int todo;
5543 if (d1 == d2)
5544 return TRUE;
5545 if (dict_len(d1) != dict_len(d2))
5546 return FALSE;
5548 todo = (int)d1->dv_hashtab.ht_used;
5549 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5551 if (!HASHITEM_EMPTY(hi))
5553 item2 = dict_find(d2, hi->hi_key, -1);
5554 if (item2 == NULL)
5555 return FALSE;
5556 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5557 return FALSE;
5558 --todo;
5561 return TRUE;
5565 * Return TRUE if "tv1" and "tv2" have the same value.
5566 * Compares the items just like "==" would compare them, but strings and
5567 * numbers are different.
5569 static int
5570 tv_equal(tv1, tv2, ic)
5571 typval_T *tv1;
5572 typval_T *tv2;
5573 int ic; /* ignore case */
5575 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5576 char_u *s1, *s2;
5577 static int recursive = 0; /* cach recursive loops */
5578 int r;
5580 if (tv1->v_type != tv2->v_type)
5581 return FALSE;
5582 /* Catch lists and dicts that have an endless loop by limiting
5583 * recursiveness to 1000. We guess they are equal then. */
5584 if (recursive >= 1000)
5585 return TRUE;
5587 switch (tv1->v_type)
5589 case VAR_LIST:
5590 ++recursive;
5591 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5592 --recursive;
5593 return r;
5595 case VAR_DICT:
5596 ++recursive;
5597 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5598 --recursive;
5599 return r;
5601 case VAR_FUNC:
5602 return (tv1->vval.v_string != NULL
5603 && tv2->vval.v_string != NULL
5604 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5606 case VAR_NUMBER:
5607 return tv1->vval.v_number == tv2->vval.v_number;
5609 case VAR_STRING:
5610 s1 = get_tv_string_buf(tv1, buf1);
5611 s2 = get_tv_string_buf(tv2, buf2);
5612 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5615 EMSG2(_(e_intern2), "tv_equal()");
5616 return TRUE;
5620 * Locate item with index "n" in list "l" and return it.
5621 * A negative index is counted from the end; -1 is the last item.
5622 * Returns NULL when "n" is out of range.
5624 static listitem_T *
5625 list_find(l, n)
5626 list_T *l;
5627 long n;
5629 listitem_T *item;
5630 long idx;
5632 if (l == NULL)
5633 return NULL;
5635 /* Negative index is relative to the end. */
5636 if (n < 0)
5637 n = l->lv_len + n;
5639 /* Check for index out of range. */
5640 if (n < 0 || n >= l->lv_len)
5641 return NULL;
5643 /* When there is a cached index may start search from there. */
5644 if (l->lv_idx_item != NULL)
5646 if (n < l->lv_idx / 2)
5648 /* closest to the start of the list */
5649 item = l->lv_first;
5650 idx = 0;
5652 else if (n > (l->lv_idx + l->lv_len) / 2)
5654 /* closest to the end of the list */
5655 item = l->lv_last;
5656 idx = l->lv_len - 1;
5658 else
5660 /* closest to the cached index */
5661 item = l->lv_idx_item;
5662 idx = l->lv_idx;
5665 else
5667 if (n < l->lv_len / 2)
5669 /* closest to the start of the list */
5670 item = l->lv_first;
5671 idx = 0;
5673 else
5675 /* closest to the end of the list */
5676 item = l->lv_last;
5677 idx = l->lv_len - 1;
5681 while (n > idx)
5683 /* search forward */
5684 item = item->li_next;
5685 ++idx;
5687 while (n < idx)
5689 /* search backward */
5690 item = item->li_prev;
5691 --idx;
5694 /* cache the used index */
5695 l->lv_idx = idx;
5696 l->lv_idx_item = item;
5698 return item;
5702 * Get list item "l[idx]" as a number.
5704 static long
5705 list_find_nr(l, idx, errorp)
5706 list_T *l;
5707 long idx;
5708 int *errorp; /* set to TRUE when something wrong */
5710 listitem_T *li;
5712 li = list_find(l, idx);
5713 if (li == NULL)
5715 if (errorp != NULL)
5716 *errorp = TRUE;
5717 return -1L;
5719 return get_tv_number_chk(&li->li_tv, errorp);
5723 * Locate "item" list "l" and return its index.
5724 * Returns -1 when "item" is not in the list.
5726 static long
5727 list_idx_of_item(l, item)
5728 list_T *l;
5729 listitem_T *item;
5731 long idx = 0;
5732 listitem_T *li;
5734 if (l == NULL)
5735 return -1;
5736 idx = 0;
5737 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
5738 ++idx;
5739 if (li == NULL)
5740 return -1;
5741 return idx;
5745 * Append item "item" to the end of list "l".
5747 static void
5748 list_append(l, item)
5749 list_T *l;
5750 listitem_T *item;
5752 if (l->lv_last == NULL)
5754 /* empty list */
5755 l->lv_first = item;
5756 l->lv_last = item;
5757 item->li_prev = NULL;
5759 else
5761 l->lv_last->li_next = item;
5762 item->li_prev = l->lv_last;
5763 l->lv_last = item;
5765 ++l->lv_len;
5766 item->li_next = NULL;
5770 * Append typval_T "tv" to the end of list "l".
5771 * Return FAIL when out of memory.
5773 static int
5774 list_append_tv(l, tv)
5775 list_T *l;
5776 typval_T *tv;
5778 listitem_T *li = listitem_alloc();
5780 if (li == NULL)
5781 return FAIL;
5782 copy_tv(tv, &li->li_tv);
5783 list_append(l, li);
5784 return OK;
5788 * Add a dictionary to a list. Used by getqflist().
5789 * Return FAIL when out of memory.
5792 list_append_dict(list, dict)
5793 list_T *list;
5794 dict_T *dict;
5796 listitem_T *li = listitem_alloc();
5798 if (li == NULL)
5799 return FAIL;
5800 li->li_tv.v_type = VAR_DICT;
5801 li->li_tv.v_lock = 0;
5802 li->li_tv.vval.v_dict = dict;
5803 list_append(list, li);
5804 ++dict->dv_refcount;
5805 return OK;
5809 * Make a copy of "str" and append it as an item to list "l".
5810 * When "len" >= 0 use "str[len]".
5811 * Returns FAIL when out of memory.
5813 static int
5814 list_append_string(l, str, len)
5815 list_T *l;
5816 char_u *str;
5817 int len;
5819 listitem_T *li = listitem_alloc();
5821 if (li == NULL)
5822 return FAIL;
5823 list_append(l, li);
5824 li->li_tv.v_type = VAR_STRING;
5825 li->li_tv.v_lock = 0;
5826 if (str == NULL)
5827 li->li_tv.vval.v_string = NULL;
5828 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
5829 : vim_strsave(str))) == NULL)
5830 return FAIL;
5831 return OK;
5835 * Append "n" to list "l".
5836 * Returns FAIL when out of memory.
5838 static int
5839 list_append_number(l, n)
5840 list_T *l;
5841 varnumber_T n;
5843 listitem_T *li;
5845 li = listitem_alloc();
5846 if (li == NULL)
5847 return FAIL;
5848 li->li_tv.v_type = VAR_NUMBER;
5849 li->li_tv.v_lock = 0;
5850 li->li_tv.vval.v_number = n;
5851 list_append(l, li);
5852 return OK;
5856 * Insert typval_T "tv" in list "l" before "item".
5857 * If "item" is NULL append at the end.
5858 * Return FAIL when out of memory.
5860 static int
5861 list_insert_tv(l, tv, item)
5862 list_T *l;
5863 typval_T *tv;
5864 listitem_T *item;
5866 listitem_T *ni = listitem_alloc();
5868 if (ni == NULL)
5869 return FAIL;
5870 copy_tv(tv, &ni->li_tv);
5871 if (item == NULL)
5872 /* Append new item at end of list. */
5873 list_append(l, ni);
5874 else
5876 /* Insert new item before existing item. */
5877 ni->li_prev = item->li_prev;
5878 ni->li_next = item;
5879 if (item->li_prev == NULL)
5881 l->lv_first = ni;
5882 ++l->lv_idx;
5884 else
5886 item->li_prev->li_next = ni;
5887 l->lv_idx_item = NULL;
5889 item->li_prev = ni;
5890 ++l->lv_len;
5892 return OK;
5896 * Extend "l1" with "l2".
5897 * If "bef" is NULL append at the end, otherwise insert before this item.
5898 * Returns FAIL when out of memory.
5900 static int
5901 list_extend(l1, l2, bef)
5902 list_T *l1;
5903 list_T *l2;
5904 listitem_T *bef;
5906 listitem_T *item;
5908 for (item = l2->lv_first; item != NULL; item = item->li_next)
5909 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
5910 return FAIL;
5911 return OK;
5915 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
5916 * Return FAIL when out of memory.
5918 static int
5919 list_concat(l1, l2, tv)
5920 list_T *l1;
5921 list_T *l2;
5922 typval_T *tv;
5924 list_T *l;
5926 /* make a copy of the first list. */
5927 l = list_copy(l1, FALSE, 0);
5928 if (l == NULL)
5929 return FAIL;
5930 tv->v_type = VAR_LIST;
5931 tv->vval.v_list = l;
5933 /* append all items from the second list */
5934 return list_extend(l, l2, NULL);
5938 * Make a copy of list "orig". Shallow if "deep" is FALSE.
5939 * The refcount of the new list is set to 1.
5940 * See item_copy() for "copyID".
5941 * Returns NULL when out of memory.
5943 static list_T *
5944 list_copy(orig, deep, copyID)
5945 list_T *orig;
5946 int deep;
5947 int copyID;
5949 list_T *copy;
5950 listitem_T *item;
5951 listitem_T *ni;
5953 if (orig == NULL)
5954 return NULL;
5956 copy = list_alloc();
5957 if (copy != NULL)
5959 if (copyID != 0)
5961 /* Do this before adding the items, because one of the items may
5962 * refer back to this list. */
5963 orig->lv_copyID = copyID;
5964 orig->lv_copylist = copy;
5966 for (item = orig->lv_first; item != NULL && !got_int;
5967 item = item->li_next)
5969 ni = listitem_alloc();
5970 if (ni == NULL)
5971 break;
5972 if (deep)
5974 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
5976 vim_free(ni);
5977 break;
5980 else
5981 copy_tv(&item->li_tv, &ni->li_tv);
5982 list_append(copy, ni);
5984 ++copy->lv_refcount;
5985 if (item != NULL)
5987 list_unref(copy);
5988 copy = NULL;
5992 return copy;
5996 * Remove items "item" to "item2" from list "l".
5997 * Does not free the listitem or the value!
5999 static void
6000 list_remove(l, item, item2)
6001 list_T *l;
6002 listitem_T *item;
6003 listitem_T *item2;
6005 listitem_T *ip;
6007 /* notify watchers */
6008 for (ip = item; ip != NULL; ip = ip->li_next)
6010 --l->lv_len;
6011 list_fix_watch(l, ip);
6012 if (ip == item2)
6013 break;
6016 if (item2->li_next == NULL)
6017 l->lv_last = item->li_prev;
6018 else
6019 item2->li_next->li_prev = item->li_prev;
6020 if (item->li_prev == NULL)
6021 l->lv_first = item2->li_next;
6022 else
6023 item->li_prev->li_next = item2->li_next;
6024 l->lv_idx_item = NULL;
6028 * Return an allocated string with the string representation of a list.
6029 * May return NULL.
6031 static char_u *
6032 list2string(tv, copyID)
6033 typval_T *tv;
6034 int copyID;
6036 garray_T ga;
6038 if (tv->vval.v_list == NULL)
6039 return NULL;
6040 ga_init2(&ga, (int)sizeof(char), 80);
6041 ga_append(&ga, '[');
6042 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6044 vim_free(ga.ga_data);
6045 return NULL;
6047 ga_append(&ga, ']');
6048 ga_append(&ga, NUL);
6049 return (char_u *)ga.ga_data;
6053 * Join list "l" into a string in "*gap", using separator "sep".
6054 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6055 * Return FAIL or OK.
6057 static int
6058 list_join(gap, l, sep, echo, copyID)
6059 garray_T *gap;
6060 list_T *l;
6061 char_u *sep;
6062 int echo;
6063 int copyID;
6065 int first = TRUE;
6066 char_u *tofree;
6067 char_u numbuf[NUMBUFLEN];
6068 listitem_T *item;
6069 char_u *s;
6071 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6073 if (first)
6074 first = FALSE;
6075 else
6076 ga_concat(gap, sep);
6078 if (echo)
6079 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6080 else
6081 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6082 if (s != NULL)
6083 ga_concat(gap, s);
6084 vim_free(tofree);
6085 if (s == NULL)
6086 return FAIL;
6088 return OK;
6092 * Garbage collection for lists and dictionaries.
6094 * We use reference counts to be able to free most items right away when they
6095 * are no longer used. But for composite items it's possible that it becomes
6096 * unused while the reference count is > 0: When there is a recursive
6097 * reference. Example:
6098 * :let l = [1, 2, 3]
6099 * :let d = {9: l}
6100 * :let l[1] = d
6102 * Since this is quite unusual we handle this with garbage collection: every
6103 * once in a while find out which lists and dicts are not referenced from any
6104 * variable.
6106 * Here is a good reference text about garbage collection (refers to Python
6107 * but it applies to all reference-counting mechanisms):
6108 * http://python.ca/nas/python/gc/
6112 * Do garbage collection for lists and dicts.
6113 * Return TRUE if some memory was freed.
6116 garbage_collect()
6118 dict_T *dd;
6119 list_T *ll;
6120 int copyID = ++current_copyID;
6121 buf_T *buf;
6122 win_T *wp;
6123 int i;
6124 funccall_T *fc;
6125 int did_free = FALSE;
6126 #ifdef FEAT_WINDOWS
6127 tabpage_T *tp;
6128 #endif
6130 /* Only do this once. */
6131 want_garbage_collect = FALSE;
6132 may_garbage_collect = FALSE;
6135 * 1. Go through all accessible variables and mark all lists and dicts
6136 * with copyID.
6138 /* script-local variables */
6139 for (i = 1; i <= ga_scripts.ga_len; ++i)
6140 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6142 /* buffer-local variables */
6143 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6144 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6146 /* window-local variables */
6147 FOR_ALL_TAB_WINDOWS(tp, wp)
6148 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6150 #ifdef FEAT_WINDOWS
6151 /* tabpage-local variables */
6152 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6153 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6154 #endif
6156 /* global variables */
6157 set_ref_in_ht(&globvarht, copyID);
6159 /* function-local variables */
6160 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6162 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6163 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6167 * 2. Go through the list of dicts and free items without the copyID.
6169 for (dd = first_dict; dd != NULL; )
6170 if (dd->dv_copyID != copyID)
6172 /* Free the Dictionary and ordinary items it contains, but don't
6173 * recurse into Lists and Dictionaries, they will be in the list
6174 * of dicts or list of lists. */
6175 dict_free(dd, FALSE);
6176 did_free = TRUE;
6178 /* restart, next dict may also have been freed */
6179 dd = first_dict;
6181 else
6182 dd = dd->dv_used_next;
6185 * 3. Go through the list of lists and free items without the copyID.
6186 * But don't free a list that has a watcher (used in a for loop), these
6187 * are not referenced anywhere.
6189 for (ll = first_list; ll != NULL; )
6190 if (ll->lv_copyID != copyID && ll->lv_watch == NULL)
6192 /* Free the List and ordinary items it contains, but don't recurse
6193 * into Lists and Dictionaries, they will be in the list of dicts
6194 * or list of lists. */
6195 list_free(ll, FALSE);
6196 did_free = TRUE;
6198 /* restart, next list may also have been freed */
6199 ll = first_list;
6201 else
6202 ll = ll->lv_used_next;
6204 return did_free;
6208 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6210 static void
6211 set_ref_in_ht(ht, copyID)
6212 hashtab_T *ht;
6213 int copyID;
6215 int todo;
6216 hashitem_T *hi;
6218 todo = (int)ht->ht_used;
6219 for (hi = ht->ht_array; todo > 0; ++hi)
6220 if (!HASHITEM_EMPTY(hi))
6222 --todo;
6223 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6228 * Mark all lists and dicts referenced through list "l" with "copyID".
6230 static void
6231 set_ref_in_list(l, copyID)
6232 list_T *l;
6233 int copyID;
6235 listitem_T *li;
6237 for (li = l->lv_first; li != NULL; li = li->li_next)
6238 set_ref_in_item(&li->li_tv, copyID);
6242 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6244 static void
6245 set_ref_in_item(tv, copyID)
6246 typval_T *tv;
6247 int copyID;
6249 dict_T *dd;
6250 list_T *ll;
6252 switch (tv->v_type)
6254 case VAR_DICT:
6255 dd = tv->vval.v_dict;
6256 if (dd->dv_copyID != copyID)
6258 /* Didn't see this dict yet. */
6259 dd->dv_copyID = copyID;
6260 set_ref_in_ht(&dd->dv_hashtab, copyID);
6262 break;
6264 case VAR_LIST:
6265 ll = tv->vval.v_list;
6266 if (ll->lv_copyID != copyID)
6268 /* Didn't see this list yet. */
6269 ll->lv_copyID = copyID;
6270 set_ref_in_list(ll, copyID);
6272 break;
6274 return;
6278 * Allocate an empty header for a dictionary.
6280 dict_T *
6281 dict_alloc()
6283 dict_T *d;
6285 d = (dict_T *)alloc(sizeof(dict_T));
6286 if (d != NULL)
6288 /* Add the list to the list of dicts for garbage collection. */
6289 if (first_dict != NULL)
6290 first_dict->dv_used_prev = d;
6291 d->dv_used_next = first_dict;
6292 d->dv_used_prev = NULL;
6293 first_dict = d;
6295 hash_init(&d->dv_hashtab);
6296 d->dv_lock = 0;
6297 d->dv_refcount = 0;
6298 d->dv_copyID = 0;
6300 return d;
6304 * Unreference a Dictionary: decrement the reference count and free it when it
6305 * becomes zero.
6307 static void
6308 dict_unref(d)
6309 dict_T *d;
6311 if (d != NULL && --d->dv_refcount <= 0)
6312 dict_free(d, TRUE);
6316 * Free a Dictionary, including all items it contains.
6317 * Ignores the reference count.
6319 static void
6320 dict_free(d, recurse)
6321 dict_T *d;
6322 int recurse; /* Free Lists and Dictionaries recursively. */
6324 int todo;
6325 hashitem_T *hi;
6326 dictitem_T *di;
6328 /* Remove the dict from the list of dicts for garbage collection. */
6329 if (d->dv_used_prev == NULL)
6330 first_dict = d->dv_used_next;
6331 else
6332 d->dv_used_prev->dv_used_next = d->dv_used_next;
6333 if (d->dv_used_next != NULL)
6334 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6336 /* Lock the hashtab, we don't want it to resize while freeing items. */
6337 hash_lock(&d->dv_hashtab);
6338 todo = (int)d->dv_hashtab.ht_used;
6339 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6341 if (!HASHITEM_EMPTY(hi))
6343 /* Remove the item before deleting it, just in case there is
6344 * something recursive causing trouble. */
6345 di = HI2DI(hi);
6346 hash_remove(&d->dv_hashtab, hi);
6347 if (recurse || (di->di_tv.v_type != VAR_LIST
6348 && di->di_tv.v_type != VAR_DICT))
6349 clear_tv(&di->di_tv);
6350 vim_free(di);
6351 --todo;
6354 hash_clear(&d->dv_hashtab);
6355 vim_free(d);
6359 * Allocate a Dictionary item.
6360 * The "key" is copied to the new item.
6361 * Note that the value of the item "di_tv" still needs to be initialized!
6362 * Returns NULL when out of memory.
6364 static dictitem_T *
6365 dictitem_alloc(key)
6366 char_u *key;
6368 dictitem_T *di;
6370 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6371 if (di != NULL)
6373 STRCPY(di->di_key, key);
6374 di->di_flags = 0;
6376 return di;
6380 * Make a copy of a Dictionary item.
6382 static dictitem_T *
6383 dictitem_copy(org)
6384 dictitem_T *org;
6386 dictitem_T *di;
6388 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6389 + STRLEN(org->di_key)));
6390 if (di != NULL)
6392 STRCPY(di->di_key, org->di_key);
6393 di->di_flags = 0;
6394 copy_tv(&org->di_tv, &di->di_tv);
6396 return di;
6400 * Remove item "item" from Dictionary "dict" and free it.
6402 static void
6403 dictitem_remove(dict, item)
6404 dict_T *dict;
6405 dictitem_T *item;
6407 hashitem_T *hi;
6409 hi = hash_find(&dict->dv_hashtab, item->di_key);
6410 if (HASHITEM_EMPTY(hi))
6411 EMSG2(_(e_intern2), "dictitem_remove()");
6412 else
6413 hash_remove(&dict->dv_hashtab, hi);
6414 dictitem_free(item);
6418 * Free a dict item. Also clears the value.
6420 static void
6421 dictitem_free(item)
6422 dictitem_T *item;
6424 clear_tv(&item->di_tv);
6425 vim_free(item);
6429 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6430 * The refcount of the new dict is set to 1.
6431 * See item_copy() for "copyID".
6432 * Returns NULL when out of memory.
6434 static dict_T *
6435 dict_copy(orig, deep, copyID)
6436 dict_T *orig;
6437 int deep;
6438 int copyID;
6440 dict_T *copy;
6441 dictitem_T *di;
6442 int todo;
6443 hashitem_T *hi;
6445 if (orig == NULL)
6446 return NULL;
6448 copy = dict_alloc();
6449 if (copy != NULL)
6451 if (copyID != 0)
6453 orig->dv_copyID = copyID;
6454 orig->dv_copydict = copy;
6456 todo = (int)orig->dv_hashtab.ht_used;
6457 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6459 if (!HASHITEM_EMPTY(hi))
6461 --todo;
6463 di = dictitem_alloc(hi->hi_key);
6464 if (di == NULL)
6465 break;
6466 if (deep)
6468 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6469 copyID) == FAIL)
6471 vim_free(di);
6472 break;
6475 else
6476 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6477 if (dict_add(copy, di) == FAIL)
6479 dictitem_free(di);
6480 break;
6485 ++copy->dv_refcount;
6486 if (todo > 0)
6488 dict_unref(copy);
6489 copy = NULL;
6493 return copy;
6497 * Add item "item" to Dictionary "d".
6498 * Returns FAIL when out of memory and when key already existed.
6500 static int
6501 dict_add(d, item)
6502 dict_T *d;
6503 dictitem_T *item;
6505 return hash_add(&d->dv_hashtab, item->di_key);
6509 * Add a number or string entry to dictionary "d".
6510 * When "str" is NULL use number "nr", otherwise use "str".
6511 * Returns FAIL when out of memory and when key already exists.
6514 dict_add_nr_str(d, key, nr, str)
6515 dict_T *d;
6516 char *key;
6517 long nr;
6518 char_u *str;
6520 dictitem_T *item;
6522 item = dictitem_alloc((char_u *)key);
6523 if (item == NULL)
6524 return FAIL;
6525 item->di_tv.v_lock = 0;
6526 if (str == NULL)
6528 item->di_tv.v_type = VAR_NUMBER;
6529 item->di_tv.vval.v_number = nr;
6531 else
6533 item->di_tv.v_type = VAR_STRING;
6534 item->di_tv.vval.v_string = vim_strsave(str);
6536 if (dict_add(d, item) == FAIL)
6538 dictitem_free(item);
6539 return FAIL;
6541 return OK;
6545 * Get the number of items in a Dictionary.
6547 static long
6548 dict_len(d)
6549 dict_T *d;
6551 if (d == NULL)
6552 return 0L;
6553 return (long)d->dv_hashtab.ht_used;
6557 * Find item "key[len]" in Dictionary "d".
6558 * If "len" is negative use strlen(key).
6559 * Returns NULL when not found.
6561 static dictitem_T *
6562 dict_find(d, key, len)
6563 dict_T *d;
6564 char_u *key;
6565 int len;
6567 #define AKEYLEN 200
6568 char_u buf[AKEYLEN];
6569 char_u *akey;
6570 char_u *tofree = NULL;
6571 hashitem_T *hi;
6573 if (len < 0)
6574 akey = key;
6575 else if (len >= AKEYLEN)
6577 tofree = akey = vim_strnsave(key, len);
6578 if (akey == NULL)
6579 return NULL;
6581 else
6583 /* Avoid a malloc/free by using buf[]. */
6584 vim_strncpy(buf, key, len);
6585 akey = buf;
6588 hi = hash_find(&d->dv_hashtab, akey);
6589 vim_free(tofree);
6590 if (HASHITEM_EMPTY(hi))
6591 return NULL;
6592 return HI2DI(hi);
6596 * Get a string item from a dictionary.
6597 * When "save" is TRUE allocate memory for it.
6598 * Returns NULL if the entry doesn't exist or out of memory.
6600 char_u *
6601 get_dict_string(d, key, save)
6602 dict_T *d;
6603 char_u *key;
6604 int save;
6606 dictitem_T *di;
6607 char_u *s;
6609 di = dict_find(d, key, -1);
6610 if (di == NULL)
6611 return NULL;
6612 s = get_tv_string(&di->di_tv);
6613 if (save && s != NULL)
6614 s = vim_strsave(s);
6615 return s;
6619 * Get a number item from a dictionary.
6620 * Returns 0 if the entry doesn't exist or out of memory.
6622 long
6623 get_dict_number(d, key)
6624 dict_T *d;
6625 char_u *key;
6627 dictitem_T *di;
6629 di = dict_find(d, key, -1);
6630 if (di == NULL)
6631 return 0;
6632 return get_tv_number(&di->di_tv);
6636 * Return an allocated string with the string representation of a Dictionary.
6637 * May return NULL.
6639 static char_u *
6640 dict2string(tv, copyID)
6641 typval_T *tv;
6642 int copyID;
6644 garray_T ga;
6645 int first = TRUE;
6646 char_u *tofree;
6647 char_u numbuf[NUMBUFLEN];
6648 hashitem_T *hi;
6649 char_u *s;
6650 dict_T *d;
6651 int todo;
6653 if ((d = tv->vval.v_dict) == NULL)
6654 return NULL;
6655 ga_init2(&ga, (int)sizeof(char), 80);
6656 ga_append(&ga, '{');
6658 todo = (int)d->dv_hashtab.ht_used;
6659 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6661 if (!HASHITEM_EMPTY(hi))
6663 --todo;
6665 if (first)
6666 first = FALSE;
6667 else
6668 ga_concat(&ga, (char_u *)", ");
6670 tofree = string_quote(hi->hi_key, FALSE);
6671 if (tofree != NULL)
6673 ga_concat(&ga, tofree);
6674 vim_free(tofree);
6676 ga_concat(&ga, (char_u *)": ");
6677 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
6678 if (s != NULL)
6679 ga_concat(&ga, s);
6680 vim_free(tofree);
6681 if (s == NULL)
6682 break;
6685 if (todo > 0)
6687 vim_free(ga.ga_data);
6688 return NULL;
6691 ga_append(&ga, '}');
6692 ga_append(&ga, NUL);
6693 return (char_u *)ga.ga_data;
6697 * Allocate a variable for a Dictionary and fill it from "*arg".
6698 * Return OK or FAIL. Returns NOTDONE for {expr}.
6700 static int
6701 get_dict_tv(arg, rettv, evaluate)
6702 char_u **arg;
6703 typval_T *rettv;
6704 int evaluate;
6706 dict_T *d = NULL;
6707 typval_T tvkey;
6708 typval_T tv;
6709 char_u *key;
6710 dictitem_T *item;
6711 char_u *start = skipwhite(*arg + 1);
6712 char_u buf[NUMBUFLEN];
6715 * First check if it's not a curly-braces thing: {expr}.
6716 * Must do this without evaluating, otherwise a function may be called
6717 * twice. Unfortunately this means we need to call eval1() twice for the
6718 * first item.
6719 * But {} is an empty Dictionary.
6721 if (*start != '}')
6723 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
6724 return FAIL;
6725 if (*start == '}')
6726 return NOTDONE;
6729 if (evaluate)
6731 d = dict_alloc();
6732 if (d == NULL)
6733 return FAIL;
6735 tvkey.v_type = VAR_UNKNOWN;
6736 tv.v_type = VAR_UNKNOWN;
6738 *arg = skipwhite(*arg + 1);
6739 while (**arg != '}' && **arg != NUL)
6741 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
6742 goto failret;
6743 if (**arg != ':')
6745 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
6746 clear_tv(&tvkey);
6747 goto failret;
6749 key = get_tv_string_buf_chk(&tvkey, buf);
6750 if (key == NULL || *key == NUL)
6752 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
6753 if (key != NULL)
6754 EMSG(_(e_emptykey));
6755 clear_tv(&tvkey);
6756 goto failret;
6759 *arg = skipwhite(*arg + 1);
6760 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
6762 clear_tv(&tvkey);
6763 goto failret;
6765 if (evaluate)
6767 item = dict_find(d, key, -1);
6768 if (item != NULL)
6770 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
6771 clear_tv(&tvkey);
6772 clear_tv(&tv);
6773 goto failret;
6775 item = dictitem_alloc(key);
6776 clear_tv(&tvkey);
6777 if (item != NULL)
6779 item->di_tv = tv;
6780 item->di_tv.v_lock = 0;
6781 if (dict_add(d, item) == FAIL)
6782 dictitem_free(item);
6786 if (**arg == '}')
6787 break;
6788 if (**arg != ',')
6790 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
6791 goto failret;
6793 *arg = skipwhite(*arg + 1);
6796 if (**arg != '}')
6798 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
6799 failret:
6800 if (evaluate)
6801 dict_free(d, TRUE);
6802 return FAIL;
6805 *arg = skipwhite(*arg + 1);
6806 if (evaluate)
6808 rettv->v_type = VAR_DICT;
6809 rettv->vval.v_dict = d;
6810 ++d->dv_refcount;
6813 return OK;
6817 * Return a string with the string representation of a variable.
6818 * If the memory is allocated "tofree" is set to it, otherwise NULL.
6819 * "numbuf" is used for a number.
6820 * Does not put quotes around strings, as ":echo" displays values.
6821 * When "copyID" is not NULL replace recursive lists and dicts with "...".
6822 * May return NULL.
6824 static char_u *
6825 echo_string(tv, tofree, numbuf, copyID)
6826 typval_T *tv;
6827 char_u **tofree;
6828 char_u *numbuf;
6829 int copyID;
6831 static int recurse = 0;
6832 char_u *r = NULL;
6834 if (recurse >= DICT_MAXNEST)
6836 EMSG(_("E724: variable nested too deep for displaying"));
6837 *tofree = NULL;
6838 return NULL;
6840 ++recurse;
6842 switch (tv->v_type)
6844 case VAR_FUNC:
6845 *tofree = NULL;
6846 r = tv->vval.v_string;
6847 break;
6849 case VAR_LIST:
6850 if (tv->vval.v_list == NULL)
6852 *tofree = NULL;
6853 r = NULL;
6855 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
6857 *tofree = NULL;
6858 r = (char_u *)"[...]";
6860 else
6862 tv->vval.v_list->lv_copyID = copyID;
6863 *tofree = list2string(tv, copyID);
6864 r = *tofree;
6866 break;
6868 case VAR_DICT:
6869 if (tv->vval.v_dict == NULL)
6871 *tofree = NULL;
6872 r = NULL;
6874 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
6876 *tofree = NULL;
6877 r = (char_u *)"{...}";
6879 else
6881 tv->vval.v_dict->dv_copyID = copyID;
6882 *tofree = dict2string(tv, copyID);
6883 r = *tofree;
6885 break;
6887 case VAR_STRING:
6888 case VAR_NUMBER:
6889 *tofree = NULL;
6890 r = get_tv_string_buf(tv, numbuf);
6891 break;
6893 default:
6894 EMSG2(_(e_intern2), "echo_string()");
6895 *tofree = NULL;
6898 --recurse;
6899 return r;
6903 * Return a string with the string representation of a variable.
6904 * If the memory is allocated "tofree" is set to it, otherwise NULL.
6905 * "numbuf" is used for a number.
6906 * Puts quotes around strings, so that they can be parsed back by eval().
6907 * May return NULL.
6909 static char_u *
6910 tv2string(tv, tofree, numbuf, copyID)
6911 typval_T *tv;
6912 char_u **tofree;
6913 char_u *numbuf;
6914 int copyID;
6916 switch (tv->v_type)
6918 case VAR_FUNC:
6919 *tofree = string_quote(tv->vval.v_string, TRUE);
6920 return *tofree;
6921 case VAR_STRING:
6922 *tofree = string_quote(tv->vval.v_string, FALSE);
6923 return *tofree;
6924 case VAR_NUMBER:
6925 case VAR_LIST:
6926 case VAR_DICT:
6927 break;
6928 default:
6929 EMSG2(_(e_intern2), "tv2string()");
6931 return echo_string(tv, tofree, numbuf, copyID);
6935 * Return string "str" in ' quotes, doubling ' characters.
6936 * If "str" is NULL an empty string is assumed.
6937 * If "function" is TRUE make it function('string').
6939 static char_u *
6940 string_quote(str, function)
6941 char_u *str;
6942 int function;
6944 unsigned len;
6945 char_u *p, *r, *s;
6947 len = (function ? 13 : 3);
6948 if (str != NULL)
6950 len += (unsigned)STRLEN(str);
6951 for (p = str; *p != NUL; mb_ptr_adv(p))
6952 if (*p == '\'')
6953 ++len;
6955 s = r = alloc(len);
6956 if (r != NULL)
6958 if (function)
6960 STRCPY(r, "function('");
6961 r += 10;
6963 else
6964 *r++ = '\'';
6965 if (str != NULL)
6966 for (p = str; *p != NUL; )
6968 if (*p == '\'')
6969 *r++ = '\'';
6970 MB_COPY_CHAR(p, r);
6972 *r++ = '\'';
6973 if (function)
6974 *r++ = ')';
6975 *r++ = NUL;
6977 return s;
6981 * Get the value of an environment variable.
6982 * "arg" is pointing to the '$'. It is advanced to after the name.
6983 * If the environment variable was not set, silently assume it is empty.
6984 * Always return OK.
6986 static int
6987 get_env_tv(arg, rettv, evaluate)
6988 char_u **arg;
6989 typval_T *rettv;
6990 int evaluate;
6992 char_u *string = NULL;
6993 int len;
6994 int cc;
6995 char_u *name;
6996 int mustfree = FALSE;
6998 ++*arg;
6999 name = *arg;
7000 len = get_env_len(arg);
7001 if (evaluate)
7003 if (len != 0)
7005 cc = name[len];
7006 name[len] = NUL;
7007 /* first try vim_getenv(), fast for normal environment vars */
7008 string = vim_getenv(name, &mustfree);
7009 if (string != NULL && *string != NUL)
7011 if (!mustfree)
7012 string = vim_strsave(string);
7014 else
7016 if (mustfree)
7017 vim_free(string);
7019 /* next try expanding things like $VIM and ${HOME} */
7020 string = expand_env_save(name - 1);
7021 if (string != NULL && *string == '$')
7023 vim_free(string);
7024 string = NULL;
7027 name[len] = cc;
7029 rettv->v_type = VAR_STRING;
7030 rettv->vval.v_string = string;
7033 return OK;
7037 * Array with names and number of arguments of all internal functions
7038 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7040 static struct fst
7042 char *f_name; /* function name */
7043 char f_min_argc; /* minimal number of arguments */
7044 char f_max_argc; /* maximal number of arguments */
7045 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7046 /* implementation of function */
7047 } functions[] =
7049 {"add", 2, 2, f_add},
7050 {"append", 2, 2, f_append},
7051 {"argc", 0, 0, f_argc},
7052 {"argidx", 0, 0, f_argidx},
7053 {"argv", 0, 1, f_argv},
7054 {"browse", 4, 4, f_browse},
7055 {"browsedir", 2, 2, f_browsedir},
7056 {"bufexists", 1, 1, f_bufexists},
7057 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7058 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7059 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7060 {"buflisted", 1, 1, f_buflisted},
7061 {"bufloaded", 1, 1, f_bufloaded},
7062 {"bufname", 1, 1, f_bufname},
7063 {"bufnr", 1, 2, f_bufnr},
7064 {"bufwinnr", 1, 1, f_bufwinnr},
7065 {"byte2line", 1, 1, f_byte2line},
7066 {"byteidx", 2, 2, f_byteidx},
7067 {"call", 2, 3, f_call},
7068 {"changenr", 0, 0, f_changenr},
7069 {"char2nr", 1, 1, f_char2nr},
7070 {"cindent", 1, 1, f_cindent},
7071 {"clearmatches", 0, 0, f_clearmatches},
7072 {"col", 1, 1, f_col},
7073 #if defined(FEAT_INS_EXPAND)
7074 {"complete", 2, 2, f_complete},
7075 {"complete_add", 1, 1, f_complete_add},
7076 {"complete_check", 0, 0, f_complete_check},
7077 #endif
7078 {"confirm", 1, 4, f_confirm},
7079 {"copy", 1, 1, f_copy},
7080 {"count", 2, 4, f_count},
7081 {"cscope_connection",0,3, f_cscope_connection},
7082 {"cursor", 1, 3, f_cursor},
7083 {"deepcopy", 1, 2, f_deepcopy},
7084 {"delete", 1, 1, f_delete},
7085 {"did_filetype", 0, 0, f_did_filetype},
7086 {"diff_filler", 1, 1, f_diff_filler},
7087 {"diff_hlID", 2, 2, f_diff_hlID},
7088 {"empty", 1, 1, f_empty},
7089 {"escape", 2, 2, f_escape},
7090 {"eval", 1, 1, f_eval},
7091 {"eventhandler", 0, 0, f_eventhandler},
7092 {"executable", 1, 1, f_executable},
7093 {"exists", 1, 1, f_exists},
7094 {"expand", 1, 2, f_expand},
7095 {"extend", 2, 3, f_extend},
7096 {"feedkeys", 1, 2, f_feedkeys},
7097 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7098 {"filereadable", 1, 1, f_filereadable},
7099 {"filewritable", 1, 1, f_filewritable},
7100 {"filter", 2, 2, f_filter},
7101 {"finddir", 1, 3, f_finddir},
7102 {"findfile", 1, 3, f_findfile},
7103 {"fnamemodify", 2, 2, f_fnamemodify},
7104 {"foldclosed", 1, 1, f_foldclosed},
7105 {"foldclosedend", 1, 1, f_foldclosedend},
7106 {"foldlevel", 1, 1, f_foldlevel},
7107 {"foldtext", 0, 0, f_foldtext},
7108 {"foldtextresult", 1, 1, f_foldtextresult},
7109 {"foreground", 0, 0, f_foreground},
7110 {"function", 1, 1, f_function},
7111 {"garbagecollect", 0, 0, f_garbagecollect},
7112 {"get", 2, 3, f_get},
7113 {"getbufline", 2, 3, f_getbufline},
7114 {"getbufvar", 2, 2, f_getbufvar},
7115 {"getchar", 0, 1, f_getchar},
7116 {"getcharmod", 0, 0, f_getcharmod},
7117 {"getcmdline", 0, 0, f_getcmdline},
7118 {"getcmdpos", 0, 0, f_getcmdpos},
7119 {"getcmdtype", 0, 0, f_getcmdtype},
7120 {"getcwd", 0, 0, f_getcwd},
7121 {"getfontname", 0, 1, f_getfontname},
7122 {"getfperm", 1, 1, f_getfperm},
7123 {"getfsize", 1, 1, f_getfsize},
7124 {"getftime", 1, 1, f_getftime},
7125 {"getftype", 1, 1, f_getftype},
7126 {"getline", 1, 2, f_getline},
7127 {"getloclist", 1, 1, f_getqflist},
7128 {"getmatches", 0, 0, f_getmatches},
7129 {"getpos", 1, 1, f_getpos},
7130 {"getqflist", 0, 0, f_getqflist},
7131 {"getreg", 0, 2, f_getreg},
7132 {"getregtype", 0, 1, f_getregtype},
7133 {"gettabwinvar", 3, 3, f_gettabwinvar},
7134 {"getwinposx", 0, 0, f_getwinposx},
7135 {"getwinposy", 0, 0, f_getwinposy},
7136 {"getwinvar", 2, 2, f_getwinvar},
7137 {"glob", 1, 1, f_glob},
7138 {"globpath", 2, 2, f_globpath},
7139 {"has", 1, 1, f_has},
7140 {"has_key", 2, 2, f_has_key},
7141 {"haslocaldir", 0, 0, f_haslocaldir},
7142 {"hasmapto", 1, 3, f_hasmapto},
7143 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7144 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7145 {"histadd", 2, 2, f_histadd},
7146 {"histdel", 1, 2, f_histdel},
7147 {"histget", 1, 2, f_histget},
7148 {"histnr", 1, 1, f_histnr},
7149 {"hlID", 1, 1, f_hlID},
7150 {"hlexists", 1, 1, f_hlexists},
7151 {"hostname", 0, 0, f_hostname},
7152 {"iconv", 3, 3, f_iconv},
7153 {"indent", 1, 1, f_indent},
7154 {"index", 2, 4, f_index},
7155 {"input", 1, 3, f_input},
7156 {"inputdialog", 1, 3, f_inputdialog},
7157 {"inputlist", 1, 1, f_inputlist},
7158 {"inputrestore", 0, 0, f_inputrestore},
7159 {"inputsave", 0, 0, f_inputsave},
7160 {"inputsecret", 1, 2, f_inputsecret},
7161 {"insert", 2, 3, f_insert},
7162 {"isdirectory", 1, 1, f_isdirectory},
7163 {"islocked", 1, 1, f_islocked},
7164 {"items", 1, 1, f_items},
7165 {"join", 1, 2, f_join},
7166 {"keys", 1, 1, f_keys},
7167 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7168 {"len", 1, 1, f_len},
7169 {"libcall", 3, 3, f_libcall},
7170 {"libcallnr", 3, 3, f_libcallnr},
7171 {"line", 1, 1, f_line},
7172 {"line2byte", 1, 1, f_line2byte},
7173 {"lispindent", 1, 1, f_lispindent},
7174 {"localtime", 0, 0, f_localtime},
7175 {"map", 2, 2, f_map},
7176 {"maparg", 1, 3, f_maparg},
7177 {"mapcheck", 1, 3, f_mapcheck},
7178 {"match", 2, 4, f_match},
7179 {"matchadd", 2, 4, f_matchadd},
7180 {"matcharg", 1, 1, f_matcharg},
7181 {"matchdelete", 1, 1, f_matchdelete},
7182 {"matchend", 2, 4, f_matchend},
7183 {"matchlist", 2, 4, f_matchlist},
7184 {"matchstr", 2, 4, f_matchstr},
7185 {"max", 1, 1, f_max},
7186 {"min", 1, 1, f_min},
7187 #ifdef vim_mkdir
7188 {"mkdir", 1, 3, f_mkdir},
7189 #endif
7190 {"mode", 0, 0, f_mode},
7191 {"nextnonblank", 1, 1, f_nextnonblank},
7192 {"nr2char", 1, 1, f_nr2char},
7193 {"pathshorten", 1, 1, f_pathshorten},
7194 {"prevnonblank", 1, 1, f_prevnonblank},
7195 {"printf", 2, 19, f_printf},
7196 {"pumvisible", 0, 0, f_pumvisible},
7197 {"range", 1, 3, f_range},
7198 {"readfile", 1, 3, f_readfile},
7199 {"reltime", 0, 2, f_reltime},
7200 {"reltimestr", 1, 1, f_reltimestr},
7201 {"remote_expr", 2, 3, f_remote_expr},
7202 {"remote_foreground", 1, 1, f_remote_foreground},
7203 {"remote_peek", 1, 2, f_remote_peek},
7204 {"remote_read", 1, 1, f_remote_read},
7205 {"remote_send", 2, 3, f_remote_send},
7206 {"remove", 2, 3, f_remove},
7207 {"rename", 2, 2, f_rename},
7208 {"repeat", 2, 2, f_repeat},
7209 {"resolve", 1, 1, f_resolve},
7210 {"reverse", 1, 1, f_reverse},
7211 {"search", 1, 3, f_search},
7212 {"searchdecl", 1, 3, f_searchdecl},
7213 {"searchpair", 3, 6, f_searchpair},
7214 {"searchpairpos", 3, 6, f_searchpairpos},
7215 {"searchpos", 1, 3, f_searchpos},
7216 {"server2client", 2, 2, f_server2client},
7217 {"serverlist", 0, 0, f_serverlist},
7218 {"setbufvar", 3, 3, f_setbufvar},
7219 {"setcmdpos", 1, 1, f_setcmdpos},
7220 {"setline", 2, 2, f_setline},
7221 {"setloclist", 2, 3, f_setloclist},
7222 {"setmatches", 1, 1, f_setmatches},
7223 {"setpos", 2, 2, f_setpos},
7224 {"setqflist", 1, 2, f_setqflist},
7225 {"setreg", 2, 3, f_setreg},
7226 {"settabwinvar", 4, 4, f_settabwinvar},
7227 {"setwinvar", 3, 3, f_setwinvar},
7228 {"shellescape", 1, 1, f_shellescape},
7229 {"simplify", 1, 1, f_simplify},
7230 {"sort", 1, 2, f_sort},
7231 {"soundfold", 1, 1, f_soundfold},
7232 {"spellbadword", 0, 1, f_spellbadword},
7233 {"spellsuggest", 1, 3, f_spellsuggest},
7234 {"split", 1, 3, f_split},
7235 {"str2nr", 1, 2, f_str2nr},
7236 #ifdef HAVE_STRFTIME
7237 {"strftime", 1, 2, f_strftime},
7238 #endif
7239 {"stridx", 2, 3, f_stridx},
7240 {"string", 1, 1, f_string},
7241 {"strlen", 1, 1, f_strlen},
7242 {"strpart", 2, 3, f_strpart},
7243 {"strridx", 2, 3, f_strridx},
7244 {"strtrans", 1, 1, f_strtrans},
7245 {"submatch", 1, 1, f_submatch},
7246 {"substitute", 4, 4, f_substitute},
7247 {"synID", 3, 3, f_synID},
7248 {"synIDattr", 2, 3, f_synIDattr},
7249 {"synIDtrans", 1, 1, f_synIDtrans},
7250 {"system", 1, 2, f_system},
7251 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7252 {"tabpagenr", 0, 1, f_tabpagenr},
7253 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7254 {"tagfiles", 0, 0, f_tagfiles},
7255 {"taglist", 1, 1, f_taglist},
7256 {"tempname", 0, 0, f_tempname},
7257 {"test", 1, 1, f_test},
7258 {"tolower", 1, 1, f_tolower},
7259 {"toupper", 1, 1, f_toupper},
7260 {"tr", 3, 3, f_tr},
7261 {"type", 1, 1, f_type},
7262 {"values", 1, 1, f_values},
7263 {"virtcol", 1, 1, f_virtcol},
7264 {"visualmode", 0, 1, f_visualmode},
7265 {"winbufnr", 1, 1, f_winbufnr},
7266 {"wincol", 0, 0, f_wincol},
7267 {"winheight", 1, 1, f_winheight},
7268 {"winline", 0, 0, f_winline},
7269 {"winnr", 0, 1, f_winnr},
7270 {"winrestcmd", 0, 0, f_winrestcmd},
7271 {"winrestview", 1, 1, f_winrestview},
7272 {"winsaveview", 0, 0, f_winsaveview},
7273 {"winwidth", 1, 1, f_winwidth},
7274 {"writefile", 2, 3, f_writefile},
7277 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7280 * Function given to ExpandGeneric() to obtain the list of internal
7281 * or user defined function names.
7283 char_u *
7284 get_function_name(xp, idx)
7285 expand_T *xp;
7286 int idx;
7288 static int intidx = -1;
7289 char_u *name;
7291 if (idx == 0)
7292 intidx = -1;
7293 if (intidx < 0)
7295 name = get_user_func_name(xp, idx);
7296 if (name != NULL)
7297 return name;
7299 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7301 STRCPY(IObuff, functions[intidx].f_name);
7302 STRCAT(IObuff, "(");
7303 if (functions[intidx].f_max_argc == 0)
7304 STRCAT(IObuff, ")");
7305 return IObuff;
7308 return NULL;
7312 * Function given to ExpandGeneric() to obtain the list of internal or
7313 * user defined variable or function names.
7315 /*ARGSUSED*/
7316 char_u *
7317 get_expr_name(xp, idx)
7318 expand_T *xp;
7319 int idx;
7321 static int intidx = -1;
7322 char_u *name;
7324 if (idx == 0)
7325 intidx = -1;
7326 if (intidx < 0)
7328 name = get_function_name(xp, idx);
7329 if (name != NULL)
7330 return name;
7332 return get_user_var_name(xp, ++intidx);
7335 #endif /* FEAT_CMDL_COMPL */
7338 * Find internal function in table above.
7339 * Return index, or -1 if not found
7341 static int
7342 find_internal_func(name)
7343 char_u *name; /* name of the function */
7345 int first = 0;
7346 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7347 int cmp;
7348 int x;
7351 * Find the function name in the table. Binary search.
7353 while (first <= last)
7355 x = first + ((unsigned)(last - first) >> 1);
7356 cmp = STRCMP(name, functions[x].f_name);
7357 if (cmp < 0)
7358 last = x - 1;
7359 else if (cmp > 0)
7360 first = x + 1;
7361 else
7362 return x;
7364 return -1;
7368 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7369 * name it contains, otherwise return "name".
7371 static char_u *
7372 deref_func_name(name, lenp)
7373 char_u *name;
7374 int *lenp;
7376 dictitem_T *v;
7377 int cc;
7379 cc = name[*lenp];
7380 name[*lenp] = NUL;
7381 v = find_var(name, NULL);
7382 name[*lenp] = cc;
7383 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7385 if (v->di_tv.vval.v_string == NULL)
7387 *lenp = 0;
7388 return (char_u *)""; /* just in case */
7390 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7391 return v->di_tv.vval.v_string;
7394 return name;
7398 * Allocate a variable for the result of a function.
7399 * Return OK or FAIL.
7401 static int
7402 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7403 evaluate, selfdict)
7404 char_u *name; /* name of the function */
7405 int len; /* length of "name" */
7406 typval_T *rettv;
7407 char_u **arg; /* argument, pointing to the '(' */
7408 linenr_T firstline; /* first line of range */
7409 linenr_T lastline; /* last line of range */
7410 int *doesrange; /* return: function handled range */
7411 int evaluate;
7412 dict_T *selfdict; /* Dictionary for "self" */
7414 char_u *argp;
7415 int ret = OK;
7416 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7417 int argcount = 0; /* number of arguments found */
7420 * Get the arguments.
7422 argp = *arg;
7423 while (argcount < MAX_FUNC_ARGS)
7425 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7426 if (*argp == ')' || *argp == ',' || *argp == NUL)
7427 break;
7428 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7430 ret = FAIL;
7431 break;
7433 ++argcount;
7434 if (*argp != ',')
7435 break;
7437 if (*argp == ')')
7438 ++argp;
7439 else
7440 ret = FAIL;
7442 if (ret == OK)
7443 ret = call_func(name, len, rettv, argcount, argvars,
7444 firstline, lastline, doesrange, evaluate, selfdict);
7445 else if (!aborting())
7447 if (argcount == MAX_FUNC_ARGS)
7448 emsg_funcname("E740: Too many arguments for function %s", name);
7449 else
7450 emsg_funcname("E116: Invalid arguments for function %s", name);
7453 while (--argcount >= 0)
7454 clear_tv(&argvars[argcount]);
7456 *arg = skipwhite(argp);
7457 return ret;
7462 * Call a function with its resolved parameters
7463 * Return OK when the function can't be called, FAIL otherwise.
7464 * Also returns OK when an error was encountered while executing the function.
7466 static int
7467 call_func(name, len, rettv, argcount, argvars, firstline, lastline,
7468 doesrange, evaluate, selfdict)
7469 char_u *name; /* name of the function */
7470 int len; /* length of "name" */
7471 typval_T *rettv; /* return value goes here */
7472 int argcount; /* number of "argvars" */
7473 typval_T *argvars; /* vars for arguments, must have "argcount"
7474 PLUS ONE elements! */
7475 linenr_T firstline; /* first line of range */
7476 linenr_T lastline; /* last line of range */
7477 int *doesrange; /* return: function handled range */
7478 int evaluate;
7479 dict_T *selfdict; /* Dictionary for "self" */
7481 int ret = FAIL;
7482 #define ERROR_UNKNOWN 0
7483 #define ERROR_TOOMANY 1
7484 #define ERROR_TOOFEW 2
7485 #define ERROR_SCRIPT 3
7486 #define ERROR_DICT 4
7487 #define ERROR_NONE 5
7488 #define ERROR_OTHER 6
7489 int error = ERROR_NONE;
7490 int i;
7491 int llen;
7492 ufunc_T *fp;
7493 int cc;
7494 #define FLEN_FIXED 40
7495 char_u fname_buf[FLEN_FIXED + 1];
7496 char_u *fname;
7499 * In a script change <SID>name() and s:name() to K_SNR 123_name().
7500 * Change <SNR>123_name() to K_SNR 123_name().
7501 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
7503 cc = name[len];
7504 name[len] = NUL;
7505 llen = eval_fname_script(name);
7506 if (llen > 0)
7508 fname_buf[0] = K_SPECIAL;
7509 fname_buf[1] = KS_EXTRA;
7510 fname_buf[2] = (int)KE_SNR;
7511 i = 3;
7512 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
7514 if (current_SID <= 0)
7515 error = ERROR_SCRIPT;
7516 else
7518 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
7519 i = (int)STRLEN(fname_buf);
7522 if (i + STRLEN(name + llen) < FLEN_FIXED)
7524 STRCPY(fname_buf + i, name + llen);
7525 fname = fname_buf;
7527 else
7529 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
7530 if (fname == NULL)
7531 error = ERROR_OTHER;
7532 else
7534 mch_memmove(fname, fname_buf, (size_t)i);
7535 STRCPY(fname + i, name + llen);
7539 else
7540 fname = name;
7542 *doesrange = FALSE;
7545 /* execute the function if no errors detected and executing */
7546 if (evaluate && error == ERROR_NONE)
7548 rettv->v_type = VAR_NUMBER; /* default is number rettv */
7549 error = ERROR_UNKNOWN;
7551 if (!builtin_function(fname))
7554 * User defined function.
7556 fp = find_func(fname);
7558 #ifdef FEAT_AUTOCMD
7559 /* Trigger FuncUndefined event, may load the function. */
7560 if (fp == NULL
7561 && apply_autocmds(EVENT_FUNCUNDEFINED,
7562 fname, fname, TRUE, NULL)
7563 && !aborting())
7565 /* executed an autocommand, search for the function again */
7566 fp = find_func(fname);
7568 #endif
7569 /* Try loading a package. */
7570 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
7572 /* loaded a package, search for the function again */
7573 fp = find_func(fname);
7576 if (fp != NULL)
7578 if (fp->uf_flags & FC_RANGE)
7579 *doesrange = TRUE;
7580 if (argcount < fp->uf_args.ga_len)
7581 error = ERROR_TOOFEW;
7582 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
7583 error = ERROR_TOOMANY;
7584 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
7585 error = ERROR_DICT;
7586 else
7589 * Call the user function.
7590 * Save and restore search patterns, script variables and
7591 * redo buffer.
7593 save_search_patterns();
7594 saveRedobuff();
7595 ++fp->uf_calls;
7596 call_user_func(fp, argcount, argvars, rettv,
7597 firstline, lastline,
7598 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
7599 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
7600 && fp->uf_refcount <= 0)
7601 /* Function was unreferenced while being used, free it
7602 * now. */
7603 func_free(fp);
7604 restoreRedobuff();
7605 restore_search_patterns();
7606 error = ERROR_NONE;
7610 else
7613 * Find the function name in the table, call its implementation.
7615 i = find_internal_func(fname);
7616 if (i >= 0)
7618 if (argcount < functions[i].f_min_argc)
7619 error = ERROR_TOOFEW;
7620 else if (argcount > functions[i].f_max_argc)
7621 error = ERROR_TOOMANY;
7622 else
7624 argvars[argcount].v_type = VAR_UNKNOWN;
7625 functions[i].f_func(argvars, rettv);
7626 error = ERROR_NONE;
7631 * The function call (or "FuncUndefined" autocommand sequence) might
7632 * have been aborted by an error, an interrupt, or an explicitly thrown
7633 * exception that has not been caught so far. This situation can be
7634 * tested for by calling aborting(). For an error in an internal
7635 * function or for the "E132" error in call_user_func(), however, the
7636 * throw point at which the "force_abort" flag (temporarily reset by
7637 * emsg()) is normally updated has not been reached yet. We need to
7638 * update that flag first to make aborting() reliable.
7640 update_force_abort();
7642 if (error == ERROR_NONE)
7643 ret = OK;
7646 * Report an error unless the argument evaluation or function call has been
7647 * cancelled due to an aborting error, an interrupt, or an exception.
7649 if (!aborting())
7651 switch (error)
7653 case ERROR_UNKNOWN:
7654 emsg_funcname(N_("E117: Unknown function: %s"), name);
7655 break;
7656 case ERROR_TOOMANY:
7657 emsg_funcname(e_toomanyarg, name);
7658 break;
7659 case ERROR_TOOFEW:
7660 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
7661 name);
7662 break;
7663 case ERROR_SCRIPT:
7664 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
7665 name);
7666 break;
7667 case ERROR_DICT:
7668 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
7669 name);
7670 break;
7674 name[len] = cc;
7675 if (fname != name && fname != fname_buf)
7676 vim_free(fname);
7678 return ret;
7682 * Give an error message with a function name. Handle <SNR> things.
7684 static void
7685 emsg_funcname(ermsg, name)
7686 char *ermsg;
7687 char_u *name;
7689 char_u *p;
7691 if (*name == K_SPECIAL)
7692 p = concat_str((char_u *)"<SNR>", name + 3);
7693 else
7694 p = name;
7695 EMSG2(_(ermsg), p);
7696 if (p != name)
7697 vim_free(p);
7700 /*********************************************
7701 * Implementation of the built-in functions
7705 * "add(list, item)" function
7707 static void
7708 f_add(argvars, rettv)
7709 typval_T *argvars;
7710 typval_T *rettv;
7712 list_T *l;
7714 rettv->vval.v_number = 1; /* Default: Failed */
7715 if (argvars[0].v_type == VAR_LIST)
7717 if ((l = argvars[0].vval.v_list) != NULL
7718 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
7719 && list_append_tv(l, &argvars[1]) == OK)
7720 copy_tv(&argvars[0], rettv);
7722 else
7723 EMSG(_(e_listreq));
7727 * "append(lnum, string/list)" function
7729 static void
7730 f_append(argvars, rettv)
7731 typval_T *argvars;
7732 typval_T *rettv;
7734 long lnum;
7735 char_u *line;
7736 list_T *l = NULL;
7737 listitem_T *li = NULL;
7738 typval_T *tv;
7739 long added = 0;
7741 lnum = get_tv_lnum(argvars);
7742 if (lnum >= 0
7743 && lnum <= curbuf->b_ml.ml_line_count
7744 && u_save(lnum, lnum + 1) == OK)
7746 if (argvars[1].v_type == VAR_LIST)
7748 l = argvars[1].vval.v_list;
7749 if (l == NULL)
7750 return;
7751 li = l->lv_first;
7753 rettv->vval.v_number = 0; /* Default: Success */
7754 for (;;)
7756 if (l == NULL)
7757 tv = &argvars[1]; /* append a string */
7758 else if (li == NULL)
7759 break; /* end of list */
7760 else
7761 tv = &li->li_tv; /* append item from list */
7762 line = get_tv_string_chk(tv);
7763 if (line == NULL) /* type error */
7765 rettv->vval.v_number = 1; /* Failed */
7766 break;
7768 ml_append(lnum + added, line, (colnr_T)0, FALSE);
7769 ++added;
7770 if (l == NULL)
7771 break;
7772 li = li->li_next;
7775 appended_lines_mark(lnum, added);
7776 if (curwin->w_cursor.lnum > lnum)
7777 curwin->w_cursor.lnum += added;
7779 else
7780 rettv->vval.v_number = 1; /* Failed */
7784 * "argc()" function
7786 /* ARGSUSED */
7787 static void
7788 f_argc(argvars, rettv)
7789 typval_T *argvars;
7790 typval_T *rettv;
7792 rettv->vval.v_number = ARGCOUNT;
7796 * "argidx()" function
7798 /* ARGSUSED */
7799 static void
7800 f_argidx(argvars, rettv)
7801 typval_T *argvars;
7802 typval_T *rettv;
7804 rettv->vval.v_number = curwin->w_arg_idx;
7808 * "argv(nr)" function
7810 static void
7811 f_argv(argvars, rettv)
7812 typval_T *argvars;
7813 typval_T *rettv;
7815 int idx;
7817 if (argvars[0].v_type != VAR_UNKNOWN)
7819 idx = get_tv_number_chk(&argvars[0], NULL);
7820 if (idx >= 0 && idx < ARGCOUNT)
7821 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
7822 else
7823 rettv->vval.v_string = NULL;
7824 rettv->v_type = VAR_STRING;
7826 else if (rettv_list_alloc(rettv) == OK)
7827 for (idx = 0; idx < ARGCOUNT; ++idx)
7828 list_append_string(rettv->vval.v_list,
7829 alist_name(&ARGLIST[idx]), -1);
7833 * "browse(save, title, initdir, default)" function
7835 /* ARGSUSED */
7836 static void
7837 f_browse(argvars, rettv)
7838 typval_T *argvars;
7839 typval_T *rettv;
7841 #ifdef FEAT_BROWSE
7842 int save;
7843 char_u *title;
7844 char_u *initdir;
7845 char_u *defname;
7846 char_u buf[NUMBUFLEN];
7847 char_u buf2[NUMBUFLEN];
7848 int error = FALSE;
7850 save = get_tv_number_chk(&argvars[0], &error);
7851 title = get_tv_string_chk(&argvars[1]);
7852 initdir = get_tv_string_buf_chk(&argvars[2], buf);
7853 defname = get_tv_string_buf_chk(&argvars[3], buf2);
7855 if (error || title == NULL || initdir == NULL || defname == NULL)
7856 rettv->vval.v_string = NULL;
7857 else
7858 rettv->vval.v_string =
7859 do_browse(save ? BROWSE_SAVE : 0,
7860 title, defname, NULL, initdir, NULL, curbuf);
7861 #else
7862 rettv->vval.v_string = NULL;
7863 #endif
7864 rettv->v_type = VAR_STRING;
7868 * "browsedir(title, initdir)" function
7870 /* ARGSUSED */
7871 static void
7872 f_browsedir(argvars, rettv)
7873 typval_T *argvars;
7874 typval_T *rettv;
7876 #ifdef FEAT_BROWSE
7877 char_u *title;
7878 char_u *initdir;
7879 char_u buf[NUMBUFLEN];
7881 title = get_tv_string_chk(&argvars[0]);
7882 initdir = get_tv_string_buf_chk(&argvars[1], buf);
7884 if (title == NULL || initdir == NULL)
7885 rettv->vval.v_string = NULL;
7886 else
7887 rettv->vval.v_string = do_browse(BROWSE_DIR,
7888 title, NULL, NULL, initdir, NULL, curbuf);
7889 #else
7890 rettv->vval.v_string = NULL;
7891 #endif
7892 rettv->v_type = VAR_STRING;
7895 static buf_T *find_buffer __ARGS((typval_T *avar));
7898 * Find a buffer by number or exact name.
7900 static buf_T *
7901 find_buffer(avar)
7902 typval_T *avar;
7904 buf_T *buf = NULL;
7906 if (avar->v_type == VAR_NUMBER)
7907 buf = buflist_findnr((int)avar->vval.v_number);
7908 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
7910 buf = buflist_findname_exp(avar->vval.v_string);
7911 if (buf == NULL)
7913 /* No full path name match, try a match with a URL or a "nofile"
7914 * buffer, these don't use the full path. */
7915 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
7916 if (buf->b_fname != NULL
7917 && (path_with_url(buf->b_fname)
7918 #ifdef FEAT_QUICKFIX
7919 || bt_nofile(buf)
7920 #endif
7922 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
7923 break;
7926 return buf;
7930 * "bufexists(expr)" function
7932 static void
7933 f_bufexists(argvars, rettv)
7934 typval_T *argvars;
7935 typval_T *rettv;
7937 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
7941 * "buflisted(expr)" function
7943 static void
7944 f_buflisted(argvars, rettv)
7945 typval_T *argvars;
7946 typval_T *rettv;
7948 buf_T *buf;
7950 buf = find_buffer(&argvars[0]);
7951 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
7955 * "bufloaded(expr)" function
7957 static void
7958 f_bufloaded(argvars, rettv)
7959 typval_T *argvars;
7960 typval_T *rettv;
7962 buf_T *buf;
7964 buf = find_buffer(&argvars[0]);
7965 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
7968 static buf_T *get_buf_tv __ARGS((typval_T *tv));
7971 * Get buffer by number or pattern.
7973 static buf_T *
7974 get_buf_tv(tv)
7975 typval_T *tv;
7977 char_u *name = tv->vval.v_string;
7978 int save_magic;
7979 char_u *save_cpo;
7980 buf_T *buf;
7982 if (tv->v_type == VAR_NUMBER)
7983 return buflist_findnr((int)tv->vval.v_number);
7984 if (tv->v_type != VAR_STRING)
7985 return NULL;
7986 if (name == NULL || *name == NUL)
7987 return curbuf;
7988 if (name[0] == '$' && name[1] == NUL)
7989 return lastbuf;
7991 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
7992 save_magic = p_magic;
7993 p_magic = TRUE;
7994 save_cpo = p_cpo;
7995 p_cpo = (char_u *)"";
7997 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
7998 TRUE, FALSE));
8000 p_magic = save_magic;
8001 p_cpo = save_cpo;
8003 /* If not found, try expanding the name, like done for bufexists(). */
8004 if (buf == NULL)
8005 buf = find_buffer(tv);
8007 return buf;
8011 * "bufname(expr)" function
8013 static void
8014 f_bufname(argvars, rettv)
8015 typval_T *argvars;
8016 typval_T *rettv;
8018 buf_T *buf;
8020 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8021 ++emsg_off;
8022 buf = get_buf_tv(&argvars[0]);
8023 rettv->v_type = VAR_STRING;
8024 if (buf != NULL && buf->b_fname != NULL)
8025 rettv->vval.v_string = vim_strsave(buf->b_fname);
8026 else
8027 rettv->vval.v_string = NULL;
8028 --emsg_off;
8032 * "bufnr(expr)" function
8034 static void
8035 f_bufnr(argvars, rettv)
8036 typval_T *argvars;
8037 typval_T *rettv;
8039 buf_T *buf;
8040 int error = FALSE;
8041 char_u *name;
8043 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8044 ++emsg_off;
8045 buf = get_buf_tv(&argvars[0]);
8046 --emsg_off;
8048 /* If the buffer isn't found and the second argument is not zero create a
8049 * new buffer. */
8050 if (buf == NULL
8051 && argvars[1].v_type != VAR_UNKNOWN
8052 && get_tv_number_chk(&argvars[1], &error) != 0
8053 && !error
8054 && (name = get_tv_string_chk(&argvars[0])) != NULL
8055 && !error)
8056 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8058 if (buf != NULL)
8059 rettv->vval.v_number = buf->b_fnum;
8060 else
8061 rettv->vval.v_number = -1;
8065 * "bufwinnr(nr)" function
8067 static void
8068 f_bufwinnr(argvars, rettv)
8069 typval_T *argvars;
8070 typval_T *rettv;
8072 #ifdef FEAT_WINDOWS
8073 win_T *wp;
8074 int winnr = 0;
8075 #endif
8076 buf_T *buf;
8078 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8079 ++emsg_off;
8080 buf = get_buf_tv(&argvars[0]);
8081 #ifdef FEAT_WINDOWS
8082 for (wp = firstwin; wp; wp = wp->w_next)
8084 ++winnr;
8085 if (wp->w_buffer == buf)
8086 break;
8088 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8089 #else
8090 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8091 #endif
8092 --emsg_off;
8096 * "byte2line(byte)" function
8098 /*ARGSUSED*/
8099 static void
8100 f_byte2line(argvars, rettv)
8101 typval_T *argvars;
8102 typval_T *rettv;
8104 #ifndef FEAT_BYTEOFF
8105 rettv->vval.v_number = -1;
8106 #else
8107 long boff = 0;
8109 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8110 if (boff < 0)
8111 rettv->vval.v_number = -1;
8112 else
8113 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8114 (linenr_T)0, &boff);
8115 #endif
8119 * "byteidx()" function
8121 /*ARGSUSED*/
8122 static void
8123 f_byteidx(argvars, rettv)
8124 typval_T *argvars;
8125 typval_T *rettv;
8127 #ifdef FEAT_MBYTE
8128 char_u *t;
8129 #endif
8130 char_u *str;
8131 long idx;
8133 str = get_tv_string_chk(&argvars[0]);
8134 idx = get_tv_number_chk(&argvars[1], NULL);
8135 rettv->vval.v_number = -1;
8136 if (str == NULL || idx < 0)
8137 return;
8139 #ifdef FEAT_MBYTE
8140 t = str;
8141 for ( ; idx > 0; idx--)
8143 if (*t == NUL) /* EOL reached */
8144 return;
8145 t += (*mb_ptr2len)(t);
8147 rettv->vval.v_number = (varnumber_T)(t - str);
8148 #else
8149 if (idx <= STRLEN(str))
8150 rettv->vval.v_number = idx;
8151 #endif
8155 * "call(func, arglist)" function
8157 static void
8158 f_call(argvars, rettv)
8159 typval_T *argvars;
8160 typval_T *rettv;
8162 char_u *func;
8163 typval_T argv[MAX_FUNC_ARGS + 1];
8164 int argc = 0;
8165 listitem_T *item;
8166 int dummy;
8167 dict_T *selfdict = NULL;
8169 rettv->vval.v_number = 0;
8170 if (argvars[1].v_type != VAR_LIST)
8172 EMSG(_(e_listreq));
8173 return;
8175 if (argvars[1].vval.v_list == NULL)
8176 return;
8178 if (argvars[0].v_type == VAR_FUNC)
8179 func = argvars[0].vval.v_string;
8180 else
8181 func = get_tv_string(&argvars[0]);
8182 if (*func == NUL)
8183 return; /* type error or empty name */
8185 if (argvars[2].v_type != VAR_UNKNOWN)
8187 if (argvars[2].v_type != VAR_DICT)
8189 EMSG(_(e_dictreq));
8190 return;
8192 selfdict = argvars[2].vval.v_dict;
8195 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
8196 item = item->li_next)
8198 if (argc == MAX_FUNC_ARGS)
8200 EMSG(_("E699: Too many arguments"));
8201 break;
8203 /* Make a copy of each argument. This is needed to be able to set
8204 * v_lock to VAR_FIXED in the copy without changing the original list.
8206 copy_tv(&item->li_tv, &argv[argc++]);
8209 if (item == NULL)
8210 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
8211 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
8212 &dummy, TRUE, selfdict);
8214 /* Free the arguments. */
8215 while (argc > 0)
8216 clear_tv(&argv[--argc]);
8220 * "changenr()" function
8222 /*ARGSUSED*/
8223 static void
8224 f_changenr(argvars, rettv)
8225 typval_T *argvars;
8226 typval_T *rettv;
8228 rettv->vval.v_number = curbuf->b_u_seq_cur;
8232 * "char2nr(string)" function
8234 static void
8235 f_char2nr(argvars, rettv)
8236 typval_T *argvars;
8237 typval_T *rettv;
8239 #ifdef FEAT_MBYTE
8240 if (has_mbyte)
8241 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
8242 else
8243 #endif
8244 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
8248 * "cindent(lnum)" function
8250 static void
8251 f_cindent(argvars, rettv)
8252 typval_T *argvars;
8253 typval_T *rettv;
8255 #ifdef FEAT_CINDENT
8256 pos_T pos;
8257 linenr_T lnum;
8259 pos = curwin->w_cursor;
8260 lnum = get_tv_lnum(argvars);
8261 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
8263 curwin->w_cursor.lnum = lnum;
8264 rettv->vval.v_number = get_c_indent();
8265 curwin->w_cursor = pos;
8267 else
8268 #endif
8269 rettv->vval.v_number = -1;
8273 * "clearmatches()" function
8275 /*ARGSUSED*/
8276 static void
8277 f_clearmatches(argvars, rettv)
8278 typval_T *argvars;
8279 typval_T *rettv;
8281 #ifdef FEAT_SEARCH_EXTRA
8282 clear_matches(curwin);
8283 #endif
8287 * "col(string)" function
8289 static void
8290 f_col(argvars, rettv)
8291 typval_T *argvars;
8292 typval_T *rettv;
8294 colnr_T col = 0;
8295 pos_T *fp;
8296 int fnum = curbuf->b_fnum;
8298 fp = var2fpos(&argvars[0], FALSE, &fnum);
8299 if (fp != NULL && fnum == curbuf->b_fnum)
8301 if (fp->col == MAXCOL)
8303 /* '> can be MAXCOL, get the length of the line then */
8304 if (fp->lnum <= curbuf->b_ml.ml_line_count)
8305 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
8306 else
8307 col = MAXCOL;
8309 else
8311 col = fp->col + 1;
8312 #ifdef FEAT_VIRTUALEDIT
8313 /* col(".") when the cursor is on the NUL at the end of the line
8314 * because of "coladd" can be seen as an extra column. */
8315 if (virtual_active() && fp == &curwin->w_cursor)
8317 char_u *p = ml_get_cursor();
8319 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
8320 curwin->w_virtcol - curwin->w_cursor.coladd))
8322 # ifdef FEAT_MBYTE
8323 int l;
8325 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
8326 col += l;
8327 # else
8328 if (*p != NUL && p[1] == NUL)
8329 ++col;
8330 # endif
8333 #endif
8336 rettv->vval.v_number = col;
8339 #if defined(FEAT_INS_EXPAND)
8341 * "complete()" function
8343 /*ARGSUSED*/
8344 static void
8345 f_complete(argvars, rettv)
8346 typval_T *argvars;
8347 typval_T *rettv;
8349 int startcol;
8351 if ((State & INSERT) == 0)
8353 EMSG(_("E785: complete() can only be used in Insert mode"));
8354 return;
8357 /* Check for undo allowed here, because if something was already inserted
8358 * the line was already saved for undo and this check isn't done. */
8359 if (!undo_allowed())
8360 return;
8362 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
8364 EMSG(_(e_invarg));
8365 return;
8368 startcol = get_tv_number_chk(&argvars[0], NULL);
8369 if (startcol <= 0)
8370 return;
8372 set_completion(startcol - 1, argvars[1].vval.v_list);
8376 * "complete_add()" function
8378 /*ARGSUSED*/
8379 static void
8380 f_complete_add(argvars, rettv)
8381 typval_T *argvars;
8382 typval_T *rettv;
8384 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
8388 * "complete_check()" function
8390 /*ARGSUSED*/
8391 static void
8392 f_complete_check(argvars, rettv)
8393 typval_T *argvars;
8394 typval_T *rettv;
8396 int saved = RedrawingDisabled;
8398 RedrawingDisabled = 0;
8399 ins_compl_check_keys(0);
8400 rettv->vval.v_number = compl_interrupted;
8401 RedrawingDisabled = saved;
8403 #endif
8406 * "confirm(message, buttons[, default [, type]])" function
8408 /*ARGSUSED*/
8409 static void
8410 f_confirm(argvars, rettv)
8411 typval_T *argvars;
8412 typval_T *rettv;
8414 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
8415 char_u *message;
8416 char_u *buttons = NULL;
8417 char_u buf[NUMBUFLEN];
8418 char_u buf2[NUMBUFLEN];
8419 int def = 1;
8420 int type = VIM_GENERIC;
8421 char_u *typestr;
8422 int error = FALSE;
8424 message = get_tv_string_chk(&argvars[0]);
8425 if (message == NULL)
8426 error = TRUE;
8427 if (argvars[1].v_type != VAR_UNKNOWN)
8429 buttons = get_tv_string_buf_chk(&argvars[1], buf);
8430 if (buttons == NULL)
8431 error = TRUE;
8432 if (argvars[2].v_type != VAR_UNKNOWN)
8434 def = get_tv_number_chk(&argvars[2], &error);
8435 if (argvars[3].v_type != VAR_UNKNOWN)
8437 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
8438 if (typestr == NULL)
8439 error = TRUE;
8440 else
8442 switch (TOUPPER_ASC(*typestr))
8444 case 'E': type = VIM_ERROR; break;
8445 case 'Q': type = VIM_QUESTION; break;
8446 case 'I': type = VIM_INFO; break;
8447 case 'W': type = VIM_WARNING; break;
8448 case 'G': type = VIM_GENERIC; break;
8455 if (buttons == NULL || *buttons == NUL)
8456 buttons = (char_u *)_("&Ok");
8458 if (error)
8459 rettv->vval.v_number = 0;
8460 else
8461 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
8462 def, NULL);
8463 #else
8464 rettv->vval.v_number = 0;
8465 #endif
8469 * "copy()" function
8471 static void
8472 f_copy(argvars, rettv)
8473 typval_T *argvars;
8474 typval_T *rettv;
8476 item_copy(&argvars[0], rettv, FALSE, 0);
8480 * "count()" function
8482 static void
8483 f_count(argvars, rettv)
8484 typval_T *argvars;
8485 typval_T *rettv;
8487 long n = 0;
8488 int ic = FALSE;
8490 if (argvars[0].v_type == VAR_LIST)
8492 listitem_T *li;
8493 list_T *l;
8494 long idx;
8496 if ((l = argvars[0].vval.v_list) != NULL)
8498 li = l->lv_first;
8499 if (argvars[2].v_type != VAR_UNKNOWN)
8501 int error = FALSE;
8503 ic = get_tv_number_chk(&argvars[2], &error);
8504 if (argvars[3].v_type != VAR_UNKNOWN)
8506 idx = get_tv_number_chk(&argvars[3], &error);
8507 if (!error)
8509 li = list_find(l, idx);
8510 if (li == NULL)
8511 EMSGN(_(e_listidx), idx);
8514 if (error)
8515 li = NULL;
8518 for ( ; li != NULL; li = li->li_next)
8519 if (tv_equal(&li->li_tv, &argvars[1], ic))
8520 ++n;
8523 else if (argvars[0].v_type == VAR_DICT)
8525 int todo;
8526 dict_T *d;
8527 hashitem_T *hi;
8529 if ((d = argvars[0].vval.v_dict) != NULL)
8531 int error = FALSE;
8533 if (argvars[2].v_type != VAR_UNKNOWN)
8535 ic = get_tv_number_chk(&argvars[2], &error);
8536 if (argvars[3].v_type != VAR_UNKNOWN)
8537 EMSG(_(e_invarg));
8540 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
8541 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
8543 if (!HASHITEM_EMPTY(hi))
8545 --todo;
8546 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
8547 ++n;
8552 else
8553 EMSG2(_(e_listdictarg), "count()");
8554 rettv->vval.v_number = n;
8558 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
8560 * Checks the existence of a cscope connection.
8562 /*ARGSUSED*/
8563 static void
8564 f_cscope_connection(argvars, rettv)
8565 typval_T *argvars;
8566 typval_T *rettv;
8568 #ifdef FEAT_CSCOPE
8569 int num = 0;
8570 char_u *dbpath = NULL;
8571 char_u *prepend = NULL;
8572 char_u buf[NUMBUFLEN];
8574 if (argvars[0].v_type != VAR_UNKNOWN
8575 && argvars[1].v_type != VAR_UNKNOWN)
8577 num = (int)get_tv_number(&argvars[0]);
8578 dbpath = get_tv_string(&argvars[1]);
8579 if (argvars[2].v_type != VAR_UNKNOWN)
8580 prepend = get_tv_string_buf(&argvars[2], buf);
8583 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
8584 #else
8585 rettv->vval.v_number = 0;
8586 #endif
8590 * "cursor(lnum, col)" function
8592 * Moves the cursor to the specified line and column
8594 /*ARGSUSED*/
8595 static void
8596 f_cursor(argvars, rettv)
8597 typval_T *argvars;
8598 typval_T *rettv;
8600 long line, col;
8601 #ifdef FEAT_VIRTUALEDIT
8602 long coladd = 0;
8603 #endif
8605 if (argvars[1].v_type == VAR_UNKNOWN)
8607 pos_T pos;
8609 if (list2fpos(argvars, &pos, NULL) == FAIL)
8610 return;
8611 line = pos.lnum;
8612 col = pos.col;
8613 #ifdef FEAT_VIRTUALEDIT
8614 coladd = pos.coladd;
8615 #endif
8617 else
8619 line = get_tv_lnum(argvars);
8620 col = get_tv_number_chk(&argvars[1], NULL);
8621 #ifdef FEAT_VIRTUALEDIT
8622 if (argvars[2].v_type != VAR_UNKNOWN)
8623 coladd = get_tv_number_chk(&argvars[2], NULL);
8624 #endif
8626 if (line < 0 || col < 0
8627 #ifdef FEAT_VIRTUALEDIT
8628 || coladd < 0
8629 #endif
8631 return; /* type error; errmsg already given */
8632 if (line > 0)
8633 curwin->w_cursor.lnum = line;
8634 if (col > 0)
8635 curwin->w_cursor.col = col - 1;
8636 #ifdef FEAT_VIRTUALEDIT
8637 curwin->w_cursor.coladd = coladd;
8638 #endif
8640 /* Make sure the cursor is in a valid position. */
8641 check_cursor();
8642 #ifdef FEAT_MBYTE
8643 /* Correct cursor for multi-byte character. */
8644 if (has_mbyte)
8645 mb_adjust_cursor();
8646 #endif
8648 curwin->w_set_curswant = TRUE;
8652 * "deepcopy()" function
8654 static void
8655 f_deepcopy(argvars, rettv)
8656 typval_T *argvars;
8657 typval_T *rettv;
8659 int noref = 0;
8661 if (argvars[1].v_type != VAR_UNKNOWN)
8662 noref = get_tv_number_chk(&argvars[1], NULL);
8663 if (noref < 0 || noref > 1)
8664 EMSG(_(e_invarg));
8665 else
8666 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? ++current_copyID : 0);
8670 * "delete()" function
8672 static void
8673 f_delete(argvars, rettv)
8674 typval_T *argvars;
8675 typval_T *rettv;
8677 if (check_restricted() || check_secure())
8678 rettv->vval.v_number = -1;
8679 else
8680 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
8684 * "did_filetype()" function
8686 /*ARGSUSED*/
8687 static void
8688 f_did_filetype(argvars, rettv)
8689 typval_T *argvars;
8690 typval_T *rettv;
8692 #ifdef FEAT_AUTOCMD
8693 rettv->vval.v_number = did_filetype;
8694 #else
8695 rettv->vval.v_number = 0;
8696 #endif
8700 * "diff_filler()" function
8702 /*ARGSUSED*/
8703 static void
8704 f_diff_filler(argvars, rettv)
8705 typval_T *argvars;
8706 typval_T *rettv;
8708 #ifdef FEAT_DIFF
8709 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
8710 #endif
8714 * "diff_hlID()" function
8716 /*ARGSUSED*/
8717 static void
8718 f_diff_hlID(argvars, rettv)
8719 typval_T *argvars;
8720 typval_T *rettv;
8722 #ifdef FEAT_DIFF
8723 linenr_T lnum = get_tv_lnum(argvars);
8724 static linenr_T prev_lnum = 0;
8725 static int changedtick = 0;
8726 static int fnum = 0;
8727 static int change_start = 0;
8728 static int change_end = 0;
8729 static hlf_T hlID = 0;
8730 int filler_lines;
8731 int col;
8733 if (lnum < 0) /* ignore type error in {lnum} arg */
8734 lnum = 0;
8735 if (lnum != prev_lnum
8736 || changedtick != curbuf->b_changedtick
8737 || fnum != curbuf->b_fnum)
8739 /* New line, buffer, change: need to get the values. */
8740 filler_lines = diff_check(curwin, lnum);
8741 if (filler_lines < 0)
8743 if (filler_lines == -1)
8745 change_start = MAXCOL;
8746 change_end = -1;
8747 if (diff_find_change(curwin, lnum, &change_start, &change_end))
8748 hlID = HLF_ADD; /* added line */
8749 else
8750 hlID = HLF_CHD; /* changed line */
8752 else
8753 hlID = HLF_ADD; /* added line */
8755 else
8756 hlID = (hlf_T)0;
8757 prev_lnum = lnum;
8758 changedtick = curbuf->b_changedtick;
8759 fnum = curbuf->b_fnum;
8762 if (hlID == HLF_CHD || hlID == HLF_TXD)
8764 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
8765 if (col >= change_start && col <= change_end)
8766 hlID = HLF_TXD; /* changed text */
8767 else
8768 hlID = HLF_CHD; /* changed line */
8770 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
8771 #endif
8775 * "empty({expr})" function
8777 static void
8778 f_empty(argvars, rettv)
8779 typval_T *argvars;
8780 typval_T *rettv;
8782 int n;
8784 switch (argvars[0].v_type)
8786 case VAR_STRING:
8787 case VAR_FUNC:
8788 n = argvars[0].vval.v_string == NULL
8789 || *argvars[0].vval.v_string == NUL;
8790 break;
8791 case VAR_NUMBER:
8792 n = argvars[0].vval.v_number == 0;
8793 break;
8794 case VAR_LIST:
8795 n = argvars[0].vval.v_list == NULL
8796 || argvars[0].vval.v_list->lv_first == NULL;
8797 break;
8798 case VAR_DICT:
8799 n = argvars[0].vval.v_dict == NULL
8800 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
8801 break;
8802 default:
8803 EMSG2(_(e_intern2), "f_empty()");
8804 n = 0;
8807 rettv->vval.v_number = n;
8811 * "escape({string}, {chars})" function
8813 static void
8814 f_escape(argvars, rettv)
8815 typval_T *argvars;
8816 typval_T *rettv;
8818 char_u buf[NUMBUFLEN];
8820 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
8821 get_tv_string_buf(&argvars[1], buf));
8822 rettv->v_type = VAR_STRING;
8826 * "eval()" function
8828 /*ARGSUSED*/
8829 static void
8830 f_eval(argvars, rettv)
8831 typval_T *argvars;
8832 typval_T *rettv;
8834 char_u *s;
8836 s = get_tv_string_chk(&argvars[0]);
8837 if (s != NULL)
8838 s = skipwhite(s);
8840 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
8842 rettv->v_type = VAR_NUMBER;
8843 rettv->vval.v_number = 0;
8845 else if (*s != NUL)
8846 EMSG(_(e_trailing));
8850 * "eventhandler()" function
8852 /*ARGSUSED*/
8853 static void
8854 f_eventhandler(argvars, rettv)
8855 typval_T *argvars;
8856 typval_T *rettv;
8858 rettv->vval.v_number = vgetc_busy;
8862 * "executable()" function
8864 static void
8865 f_executable(argvars, rettv)
8866 typval_T *argvars;
8867 typval_T *rettv;
8869 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
8873 * "exists()" function
8875 static void
8876 f_exists(argvars, rettv)
8877 typval_T *argvars;
8878 typval_T *rettv;
8880 char_u *p;
8881 char_u *name;
8882 int n = FALSE;
8883 int len = 0;
8885 p = get_tv_string(&argvars[0]);
8886 if (*p == '$') /* environment variable */
8888 /* first try "normal" environment variables (fast) */
8889 if (mch_getenv(p + 1) != NULL)
8890 n = TRUE;
8891 else
8893 /* try expanding things like $VIM and ${HOME} */
8894 p = expand_env_save(p);
8895 if (p != NULL && *p != '$')
8896 n = TRUE;
8897 vim_free(p);
8900 else if (*p == '&' || *p == '+') /* option */
8902 n = (get_option_tv(&p, NULL, TRUE) == OK);
8903 if (*skipwhite(p) != NUL)
8904 n = FALSE; /* trailing garbage */
8906 else if (*p == '*') /* internal or user defined function */
8908 n = function_exists(p + 1);
8910 else if (*p == ':')
8912 n = cmd_exists(p + 1);
8914 else if (*p == '#')
8916 #ifdef FEAT_AUTOCMD
8917 if (p[1] == '#')
8918 n = autocmd_supported(p + 2);
8919 else
8920 n = au_exists(p + 1);
8921 #endif
8923 else /* internal variable */
8925 char_u *tofree;
8926 typval_T tv;
8928 /* get_name_len() takes care of expanding curly braces */
8929 name = p;
8930 len = get_name_len(&p, &tofree, TRUE, FALSE);
8931 if (len > 0)
8933 if (tofree != NULL)
8934 name = tofree;
8935 n = (get_var_tv(name, len, &tv, FALSE) == OK);
8936 if (n)
8938 /* handle d.key, l[idx], f(expr) */
8939 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
8940 if (n)
8941 clear_tv(&tv);
8944 if (*p != NUL)
8945 n = FALSE;
8947 vim_free(tofree);
8950 rettv->vval.v_number = n;
8954 * "expand()" function
8956 static void
8957 f_expand(argvars, rettv)
8958 typval_T *argvars;
8959 typval_T *rettv;
8961 char_u *s;
8962 int len;
8963 char_u *errormsg;
8964 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
8965 expand_T xpc;
8966 int error = FALSE;
8968 rettv->v_type = VAR_STRING;
8969 s = get_tv_string(&argvars[0]);
8970 if (*s == '%' || *s == '#' || *s == '<')
8972 ++emsg_off;
8973 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
8974 --emsg_off;
8976 else
8978 /* When the optional second argument is non-zero, don't remove matches
8979 * for 'suffixes' and 'wildignore' */
8980 if (argvars[1].v_type != VAR_UNKNOWN
8981 && get_tv_number_chk(&argvars[1], &error))
8982 flags |= WILD_KEEP_ALL;
8983 if (!error)
8985 ExpandInit(&xpc);
8986 xpc.xp_context = EXPAND_FILES;
8987 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
8989 else
8990 rettv->vval.v_string = NULL;
8995 * "extend(list, list [, idx])" function
8996 * "extend(dict, dict [, action])" function
8998 static void
8999 f_extend(argvars, rettv)
9000 typval_T *argvars;
9001 typval_T *rettv;
9003 rettv->vval.v_number = 0;
9004 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9006 list_T *l1, *l2;
9007 listitem_T *item;
9008 long before;
9009 int error = FALSE;
9011 l1 = argvars[0].vval.v_list;
9012 l2 = argvars[1].vval.v_list;
9013 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9014 && l2 != NULL)
9016 if (argvars[2].v_type != VAR_UNKNOWN)
9018 before = get_tv_number_chk(&argvars[2], &error);
9019 if (error)
9020 return; /* type error; errmsg already given */
9022 if (before == l1->lv_len)
9023 item = NULL;
9024 else
9026 item = list_find(l1, before);
9027 if (item == NULL)
9029 EMSGN(_(e_listidx), before);
9030 return;
9034 else
9035 item = NULL;
9036 list_extend(l1, l2, item);
9038 copy_tv(&argvars[0], rettv);
9041 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9043 dict_T *d1, *d2;
9044 dictitem_T *di1;
9045 char_u *action;
9046 int i;
9047 hashitem_T *hi2;
9048 int todo;
9050 d1 = argvars[0].vval.v_dict;
9051 d2 = argvars[1].vval.v_dict;
9052 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9053 && d2 != NULL)
9055 /* Check the third argument. */
9056 if (argvars[2].v_type != VAR_UNKNOWN)
9058 static char *(av[]) = {"keep", "force", "error"};
9060 action = get_tv_string_chk(&argvars[2]);
9061 if (action == NULL)
9062 return; /* type error; errmsg already given */
9063 for (i = 0; i < 3; ++i)
9064 if (STRCMP(action, av[i]) == 0)
9065 break;
9066 if (i == 3)
9068 EMSG2(_(e_invarg2), action);
9069 return;
9072 else
9073 action = (char_u *)"force";
9075 /* Go over all entries in the second dict and add them to the
9076 * first dict. */
9077 todo = (int)d2->dv_hashtab.ht_used;
9078 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9080 if (!HASHITEM_EMPTY(hi2))
9082 --todo;
9083 di1 = dict_find(d1, hi2->hi_key, -1);
9084 if (di1 == NULL)
9086 di1 = dictitem_copy(HI2DI(hi2));
9087 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9088 dictitem_free(di1);
9090 else if (*action == 'e')
9092 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9093 break;
9095 else if (*action == 'f')
9097 clear_tv(&di1->di_tv);
9098 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9103 copy_tv(&argvars[0], rettv);
9106 else
9107 EMSG2(_(e_listdictarg), "extend()");
9111 * "feedkeys()" function
9113 /*ARGSUSED*/
9114 static void
9115 f_feedkeys(argvars, rettv)
9116 typval_T *argvars;
9117 typval_T *rettv;
9119 int remap = TRUE;
9120 char_u *keys, *flags;
9121 char_u nbuf[NUMBUFLEN];
9122 int typed = FALSE;
9123 char_u *keys_esc;
9125 /* This is not allowed in the sandbox. If the commands would still be
9126 * executed in the sandbox it would be OK, but it probably happens later,
9127 * when "sandbox" is no longer set. */
9128 if (check_secure())
9129 return;
9131 rettv->vval.v_number = 0;
9132 keys = get_tv_string(&argvars[0]);
9133 if (*keys != NUL)
9135 if (argvars[1].v_type != VAR_UNKNOWN)
9137 flags = get_tv_string_buf(&argvars[1], nbuf);
9138 for ( ; *flags != NUL; ++flags)
9140 switch (*flags)
9142 case 'n': remap = FALSE; break;
9143 case 'm': remap = TRUE; break;
9144 case 't': typed = TRUE; break;
9149 /* Need to escape K_SPECIAL and CSI before putting the string in the
9150 * typeahead buffer. */
9151 keys_esc = vim_strsave_escape_csi(keys);
9152 if (keys_esc != NULL)
9154 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
9155 typebuf.tb_len, !typed, FALSE);
9156 vim_free(keys_esc);
9157 if (vgetc_busy)
9158 typebuf_was_filled = TRUE;
9164 * "filereadable()" function
9166 static void
9167 f_filereadable(argvars, rettv)
9168 typval_T *argvars;
9169 typval_T *rettv;
9171 FILE *fd;
9172 char_u *p;
9173 int n;
9175 p = get_tv_string(&argvars[0]);
9176 if (*p && !mch_isdir(p) && (fd = mch_fopen((char *)p, "r")) != NULL)
9178 n = TRUE;
9179 fclose(fd);
9181 else
9182 n = FALSE;
9184 rettv->vval.v_number = n;
9188 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
9189 * rights to write into.
9191 static void
9192 f_filewritable(argvars, rettv)
9193 typval_T *argvars;
9194 typval_T *rettv;
9196 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
9199 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int dir));
9201 static void
9202 findfilendir(argvars, rettv, dir)
9203 typval_T *argvars;
9204 typval_T *rettv;
9205 int dir;
9207 #ifdef FEAT_SEARCHPATH
9208 char_u *fname;
9209 char_u *fresult = NULL;
9210 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
9211 char_u *p;
9212 char_u pathbuf[NUMBUFLEN];
9213 int count = 1;
9214 int first = TRUE;
9215 int error = FALSE;
9216 #endif
9218 rettv->vval.v_string = NULL;
9219 rettv->v_type = VAR_STRING;
9221 #ifdef FEAT_SEARCHPATH
9222 fname = get_tv_string(&argvars[0]);
9224 if (argvars[1].v_type != VAR_UNKNOWN)
9226 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
9227 if (p == NULL)
9228 error = TRUE;
9229 else
9231 if (*p != NUL)
9232 path = p;
9234 if (argvars[2].v_type != VAR_UNKNOWN)
9235 count = get_tv_number_chk(&argvars[2], &error);
9239 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
9240 error = TRUE;
9242 if (*fname != NUL && !error)
9246 if (rettv->v_type == VAR_STRING)
9247 vim_free(fresult);
9248 fresult = find_file_in_path_option(first ? fname : NULL,
9249 first ? (int)STRLEN(fname) : 0,
9250 0, first, path, dir, curbuf->b_ffname,
9251 dir ? (char_u *)"" : curbuf->b_p_sua);
9252 first = FALSE;
9254 if (fresult != NULL && rettv->v_type == VAR_LIST)
9255 list_append_string(rettv->vval.v_list, fresult, -1);
9257 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
9260 if (rettv->v_type == VAR_STRING)
9261 rettv->vval.v_string = fresult;
9262 #endif
9265 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
9266 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
9269 * Implementation of map() and filter().
9271 static void
9272 filter_map(argvars, rettv, map)
9273 typval_T *argvars;
9274 typval_T *rettv;
9275 int map;
9277 char_u buf[NUMBUFLEN];
9278 char_u *expr;
9279 listitem_T *li, *nli;
9280 list_T *l = NULL;
9281 dictitem_T *di;
9282 hashtab_T *ht;
9283 hashitem_T *hi;
9284 dict_T *d = NULL;
9285 typval_T save_val;
9286 typval_T save_key;
9287 int rem;
9288 int todo;
9289 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
9290 int save_did_emsg;
9292 rettv->vval.v_number = 0;
9293 if (argvars[0].v_type == VAR_LIST)
9295 if ((l = argvars[0].vval.v_list) == NULL
9296 || (map && tv_check_lock(l->lv_lock, ermsg)))
9297 return;
9299 else if (argvars[0].v_type == VAR_DICT)
9301 if ((d = argvars[0].vval.v_dict) == NULL
9302 || (map && tv_check_lock(d->dv_lock, ermsg)))
9303 return;
9305 else
9307 EMSG2(_(e_listdictarg), ermsg);
9308 return;
9311 expr = get_tv_string_buf_chk(&argvars[1], buf);
9312 /* On type errors, the preceding call has already displayed an error
9313 * message. Avoid a misleading error message for an empty string that
9314 * was not passed as argument. */
9315 if (expr != NULL)
9317 prepare_vimvar(VV_VAL, &save_val);
9318 expr = skipwhite(expr);
9320 /* We reset "did_emsg" to be able to detect whether an error
9321 * occurred during evaluation of the expression. */
9322 save_did_emsg = did_emsg;
9323 did_emsg = FALSE;
9325 if (argvars[0].v_type == VAR_DICT)
9327 prepare_vimvar(VV_KEY, &save_key);
9328 vimvars[VV_KEY].vv_type = VAR_STRING;
9330 ht = &d->dv_hashtab;
9331 hash_lock(ht);
9332 todo = (int)ht->ht_used;
9333 for (hi = ht->ht_array; todo > 0; ++hi)
9335 if (!HASHITEM_EMPTY(hi))
9337 --todo;
9338 di = HI2DI(hi);
9339 if (tv_check_lock(di->di_tv.v_lock, ermsg))
9340 break;
9341 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
9342 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
9343 || did_emsg)
9344 break;
9345 if (!map && rem)
9346 dictitem_remove(d, di);
9347 clear_tv(&vimvars[VV_KEY].vv_tv);
9350 hash_unlock(ht);
9352 restore_vimvar(VV_KEY, &save_key);
9354 else
9356 for (li = l->lv_first; li != NULL; li = nli)
9358 if (tv_check_lock(li->li_tv.v_lock, ermsg))
9359 break;
9360 nli = li->li_next;
9361 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
9362 || did_emsg)
9363 break;
9364 if (!map && rem)
9365 listitem_remove(l, li);
9369 restore_vimvar(VV_VAL, &save_val);
9371 did_emsg |= save_did_emsg;
9374 copy_tv(&argvars[0], rettv);
9377 static int
9378 filter_map_one(tv, expr, map, remp)
9379 typval_T *tv;
9380 char_u *expr;
9381 int map;
9382 int *remp;
9384 typval_T rettv;
9385 char_u *s;
9387 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
9388 s = expr;
9389 if (eval1(&s, &rettv, TRUE) == FAIL)
9390 return FAIL;
9391 if (*s != NUL) /* check for trailing chars after expr */
9393 EMSG2(_(e_invexpr2), s);
9394 return FAIL;
9396 if (map)
9398 /* map(): replace the list item value */
9399 clear_tv(tv);
9400 rettv.v_lock = 0;
9401 *tv = rettv;
9403 else
9405 int error = FALSE;
9407 /* filter(): when expr is zero remove the item */
9408 *remp = (get_tv_number_chk(&rettv, &error) == 0);
9409 clear_tv(&rettv);
9410 /* On type error, nothing has been removed; return FAIL to stop the
9411 * loop. The error message was given by get_tv_number_chk(). */
9412 if (error)
9413 return FAIL;
9415 clear_tv(&vimvars[VV_VAL].vv_tv);
9416 return OK;
9420 * "filter()" function
9422 static void
9423 f_filter(argvars, rettv)
9424 typval_T *argvars;
9425 typval_T *rettv;
9427 filter_map(argvars, rettv, FALSE);
9431 * "finddir({fname}[, {path}[, {count}]])" function
9433 static void
9434 f_finddir(argvars, rettv)
9435 typval_T *argvars;
9436 typval_T *rettv;
9438 findfilendir(argvars, rettv, TRUE);
9442 * "findfile({fname}[, {path}[, {count}]])" function
9444 static void
9445 f_findfile(argvars, rettv)
9446 typval_T *argvars;
9447 typval_T *rettv;
9449 findfilendir(argvars, rettv, FALSE);
9453 * "fnamemodify({fname}, {mods})" function
9455 static void
9456 f_fnamemodify(argvars, rettv)
9457 typval_T *argvars;
9458 typval_T *rettv;
9460 char_u *fname;
9461 char_u *mods;
9462 int usedlen = 0;
9463 int len;
9464 char_u *fbuf = NULL;
9465 char_u buf[NUMBUFLEN];
9467 fname = get_tv_string_chk(&argvars[0]);
9468 mods = get_tv_string_buf_chk(&argvars[1], buf);
9469 if (fname == NULL || mods == NULL)
9470 fname = NULL;
9471 else
9473 len = (int)STRLEN(fname);
9474 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
9477 rettv->v_type = VAR_STRING;
9478 if (fname == NULL)
9479 rettv->vval.v_string = NULL;
9480 else
9481 rettv->vval.v_string = vim_strnsave(fname, len);
9482 vim_free(fbuf);
9485 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
9488 * "foldclosed()" function
9490 static void
9491 foldclosed_both(argvars, rettv, end)
9492 typval_T *argvars;
9493 typval_T *rettv;
9494 int end;
9496 #ifdef FEAT_FOLDING
9497 linenr_T lnum;
9498 linenr_T first, last;
9500 lnum = get_tv_lnum(argvars);
9501 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9503 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
9505 if (end)
9506 rettv->vval.v_number = (varnumber_T)last;
9507 else
9508 rettv->vval.v_number = (varnumber_T)first;
9509 return;
9512 #endif
9513 rettv->vval.v_number = -1;
9517 * "foldclosed()" function
9519 static void
9520 f_foldclosed(argvars, rettv)
9521 typval_T *argvars;
9522 typval_T *rettv;
9524 foldclosed_both(argvars, rettv, FALSE);
9528 * "foldclosedend()" function
9530 static void
9531 f_foldclosedend(argvars, rettv)
9532 typval_T *argvars;
9533 typval_T *rettv;
9535 foldclosed_both(argvars, rettv, TRUE);
9539 * "foldlevel()" function
9541 static void
9542 f_foldlevel(argvars, rettv)
9543 typval_T *argvars;
9544 typval_T *rettv;
9546 #ifdef FEAT_FOLDING
9547 linenr_T lnum;
9549 lnum = get_tv_lnum(argvars);
9550 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9551 rettv->vval.v_number = foldLevel(lnum);
9552 else
9553 #endif
9554 rettv->vval.v_number = 0;
9558 * "foldtext()" function
9560 /*ARGSUSED*/
9561 static void
9562 f_foldtext(argvars, rettv)
9563 typval_T *argvars;
9564 typval_T *rettv;
9566 #ifdef FEAT_FOLDING
9567 linenr_T lnum;
9568 char_u *s;
9569 char_u *r;
9570 int len;
9571 char *txt;
9572 #endif
9574 rettv->v_type = VAR_STRING;
9575 rettv->vval.v_string = NULL;
9576 #ifdef FEAT_FOLDING
9577 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
9578 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
9579 <= curbuf->b_ml.ml_line_count
9580 && vimvars[VV_FOLDDASHES].vv_str != NULL)
9582 /* Find first non-empty line in the fold. */
9583 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
9584 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
9586 if (!linewhite(lnum))
9587 break;
9588 ++lnum;
9591 /* Find interesting text in this line. */
9592 s = skipwhite(ml_get(lnum));
9593 /* skip C comment-start */
9594 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
9596 s = skipwhite(s + 2);
9597 if (*skipwhite(s) == NUL
9598 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
9600 s = skipwhite(ml_get(lnum + 1));
9601 if (*s == '*')
9602 s = skipwhite(s + 1);
9605 txt = _("+-%s%3ld lines: ");
9606 r = alloc((unsigned)(STRLEN(txt)
9607 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
9608 + 20 /* for %3ld */
9609 + STRLEN(s))); /* concatenated */
9610 if (r != NULL)
9612 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
9613 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
9614 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
9615 len = (int)STRLEN(r);
9616 STRCAT(r, s);
9617 /* remove 'foldmarker' and 'commentstring' */
9618 foldtext_cleanup(r + len);
9619 rettv->vval.v_string = r;
9622 #endif
9626 * "foldtextresult(lnum)" function
9628 /*ARGSUSED*/
9629 static void
9630 f_foldtextresult(argvars, rettv)
9631 typval_T *argvars;
9632 typval_T *rettv;
9634 #ifdef FEAT_FOLDING
9635 linenr_T lnum;
9636 char_u *text;
9637 char_u buf[51];
9638 foldinfo_T foldinfo;
9639 int fold_count;
9640 #endif
9642 rettv->v_type = VAR_STRING;
9643 rettv->vval.v_string = NULL;
9644 #ifdef FEAT_FOLDING
9645 lnum = get_tv_lnum(argvars);
9646 /* treat illegal types and illegal string values for {lnum} the same */
9647 if (lnum < 0)
9648 lnum = 0;
9649 fold_count = foldedCount(curwin, lnum, &foldinfo);
9650 if (fold_count > 0)
9652 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
9653 &foldinfo, buf);
9654 if (text == buf)
9655 text = vim_strsave(text);
9656 rettv->vval.v_string = text;
9658 #endif
9662 * "foreground()" function
9664 /*ARGSUSED*/
9665 static void
9666 f_foreground(argvars, rettv)
9667 typval_T *argvars;
9668 typval_T *rettv;
9670 rettv->vval.v_number = 0;
9671 #ifdef FEAT_GUI
9672 if (gui.in_use)
9673 gui_mch_set_foreground();
9674 #else
9675 # ifdef WIN32
9676 win32_set_foreground();
9677 # endif
9678 #endif
9682 * "function()" function
9684 /*ARGSUSED*/
9685 static void
9686 f_function(argvars, rettv)
9687 typval_T *argvars;
9688 typval_T *rettv;
9690 char_u *s;
9692 rettv->vval.v_number = 0;
9693 s = get_tv_string(&argvars[0]);
9694 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
9695 EMSG2(_(e_invarg2), s);
9696 else if (!function_exists(s))
9697 EMSG2(_("E700: Unknown function: %s"), s);
9698 else
9700 rettv->vval.v_string = vim_strsave(s);
9701 rettv->v_type = VAR_FUNC;
9706 * "garbagecollect()" function
9708 /*ARGSUSED*/
9709 static void
9710 f_garbagecollect(argvars, rettv)
9711 typval_T *argvars;
9712 typval_T *rettv;
9714 /* This is postponed until we are back at the toplevel, because we may be
9715 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
9716 want_garbage_collect = TRUE;
9720 * "get()" function
9722 static void
9723 f_get(argvars, rettv)
9724 typval_T *argvars;
9725 typval_T *rettv;
9727 listitem_T *li;
9728 list_T *l;
9729 dictitem_T *di;
9730 dict_T *d;
9731 typval_T *tv = NULL;
9733 if (argvars[0].v_type == VAR_LIST)
9735 if ((l = argvars[0].vval.v_list) != NULL)
9737 int error = FALSE;
9739 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
9740 if (!error && li != NULL)
9741 tv = &li->li_tv;
9744 else if (argvars[0].v_type == VAR_DICT)
9746 if ((d = argvars[0].vval.v_dict) != NULL)
9748 di = dict_find(d, get_tv_string(&argvars[1]), -1);
9749 if (di != NULL)
9750 tv = &di->di_tv;
9753 else
9754 EMSG2(_(e_listdictarg), "get()");
9756 if (tv == NULL)
9758 if (argvars[2].v_type == VAR_UNKNOWN)
9759 rettv->vval.v_number = 0;
9760 else
9761 copy_tv(&argvars[2], rettv);
9763 else
9764 copy_tv(tv, rettv);
9767 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
9770 * Get line or list of lines from buffer "buf" into "rettv".
9771 * Return a range (from start to end) of lines in rettv from the specified
9772 * buffer.
9773 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
9775 static void
9776 get_buffer_lines(buf, start, end, retlist, rettv)
9777 buf_T *buf;
9778 linenr_T start;
9779 linenr_T end;
9780 int retlist;
9781 typval_T *rettv;
9783 char_u *p;
9785 if (retlist)
9787 if (rettv_list_alloc(rettv) == FAIL)
9788 return;
9790 else
9791 rettv->vval.v_number = 0;
9793 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
9794 return;
9796 if (!retlist)
9798 if (start >= 1 && start <= buf->b_ml.ml_line_count)
9799 p = ml_get_buf(buf, start, FALSE);
9800 else
9801 p = (char_u *)"";
9803 rettv->v_type = VAR_STRING;
9804 rettv->vval.v_string = vim_strsave(p);
9806 else
9808 if (end < start)
9809 return;
9811 if (start < 1)
9812 start = 1;
9813 if (end > buf->b_ml.ml_line_count)
9814 end = buf->b_ml.ml_line_count;
9815 while (start <= end)
9816 if (list_append_string(rettv->vval.v_list,
9817 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
9818 break;
9823 * "getbufline()" function
9825 static void
9826 f_getbufline(argvars, rettv)
9827 typval_T *argvars;
9828 typval_T *rettv;
9830 linenr_T lnum;
9831 linenr_T end;
9832 buf_T *buf;
9834 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
9835 ++emsg_off;
9836 buf = get_buf_tv(&argvars[0]);
9837 --emsg_off;
9839 lnum = get_tv_lnum_buf(&argvars[1], buf);
9840 if (argvars[2].v_type == VAR_UNKNOWN)
9841 end = lnum;
9842 else
9843 end = get_tv_lnum_buf(&argvars[2], buf);
9845 get_buffer_lines(buf, lnum, end, TRUE, rettv);
9849 * "getbufvar()" function
9851 static void
9852 f_getbufvar(argvars, rettv)
9853 typval_T *argvars;
9854 typval_T *rettv;
9856 buf_T *buf;
9857 buf_T *save_curbuf;
9858 char_u *varname;
9859 dictitem_T *v;
9861 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
9862 varname = get_tv_string_chk(&argvars[1]);
9863 ++emsg_off;
9864 buf = get_buf_tv(&argvars[0]);
9866 rettv->v_type = VAR_STRING;
9867 rettv->vval.v_string = NULL;
9869 if (buf != NULL && varname != NULL)
9871 if (*varname == '&') /* buffer-local-option */
9873 /* set curbuf to be our buf, temporarily */
9874 save_curbuf = curbuf;
9875 curbuf = buf;
9877 get_option_tv(&varname, rettv, TRUE);
9879 /* restore previous notion of curbuf */
9880 curbuf = save_curbuf;
9882 else
9884 if (*varname == NUL)
9885 /* let getbufvar({nr}, "") return the "b:" dictionary. The
9886 * scope prefix before the NUL byte is required by
9887 * find_var_in_ht(). */
9888 varname = (char_u *)"b:" + 2;
9889 /* look up the variable */
9890 v = find_var_in_ht(&buf->b_vars.dv_hashtab, varname, FALSE);
9891 if (v != NULL)
9892 copy_tv(&v->di_tv, rettv);
9896 --emsg_off;
9900 * "getchar()" function
9902 static void
9903 f_getchar(argvars, rettv)
9904 typval_T *argvars;
9905 typval_T *rettv;
9907 varnumber_T n;
9908 int error = FALSE;
9910 /* Position the cursor. Needed after a message that ends in a space. */
9911 windgoto(msg_row, msg_col);
9913 ++no_mapping;
9914 ++allow_keys;
9915 for (;;)
9917 if (argvars[0].v_type == VAR_UNKNOWN)
9918 /* getchar(): blocking wait. */
9919 n = safe_vgetc();
9920 else if (get_tv_number_chk(&argvars[0], &error) == 1)
9921 /* getchar(1): only check if char avail */
9922 n = vpeekc();
9923 else if (error || vpeekc() == NUL)
9924 /* illegal argument or getchar(0) and no char avail: return zero */
9925 n = 0;
9926 else
9927 /* getchar(0) and char avail: return char */
9928 n = safe_vgetc();
9929 if (n == K_IGNORE)
9930 continue;
9931 break;
9933 --no_mapping;
9934 --allow_keys;
9936 vimvars[VV_MOUSE_WIN].vv_nr = 0;
9937 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
9938 vimvars[VV_MOUSE_COL].vv_nr = 0;
9940 rettv->vval.v_number = n;
9941 if (IS_SPECIAL(n) || mod_mask != 0)
9943 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
9944 int i = 0;
9946 /* Turn a special key into three bytes, plus modifier. */
9947 if (mod_mask != 0)
9949 temp[i++] = K_SPECIAL;
9950 temp[i++] = KS_MODIFIER;
9951 temp[i++] = mod_mask;
9953 if (IS_SPECIAL(n))
9955 temp[i++] = K_SPECIAL;
9956 temp[i++] = K_SECOND(n);
9957 temp[i++] = K_THIRD(n);
9959 #ifdef FEAT_MBYTE
9960 else if (has_mbyte)
9961 i += (*mb_char2bytes)(n, temp + i);
9962 #endif
9963 else
9964 temp[i++] = n;
9965 temp[i++] = NUL;
9966 rettv->v_type = VAR_STRING;
9967 rettv->vval.v_string = vim_strsave(temp);
9969 #ifdef FEAT_MOUSE
9970 if (n == K_LEFTMOUSE
9971 || n == K_LEFTMOUSE_NM
9972 || n == K_LEFTDRAG
9973 || n == K_LEFTRELEASE
9974 || n == K_LEFTRELEASE_NM
9975 || n == K_MIDDLEMOUSE
9976 || n == K_MIDDLEDRAG
9977 || n == K_MIDDLERELEASE
9978 || n == K_RIGHTMOUSE
9979 || n == K_RIGHTDRAG
9980 || n == K_RIGHTRELEASE
9981 || n == K_X1MOUSE
9982 || n == K_X1DRAG
9983 || n == K_X1RELEASE
9984 || n == K_X2MOUSE
9985 || n == K_X2DRAG
9986 || n == K_X2RELEASE
9987 || n == K_MOUSEDOWN
9988 || n == K_MOUSEUP)
9990 int row = mouse_row;
9991 int col = mouse_col;
9992 win_T *win;
9993 linenr_T lnum;
9994 # ifdef FEAT_WINDOWS
9995 win_T *wp;
9996 # endif
9997 int n = 1;
9999 if (row >= 0 && col >= 0)
10001 /* Find the window at the mouse coordinates and compute the
10002 * text position. */
10003 win = mouse_find_win(&row, &col);
10004 (void)mouse_comp_pos(win, &row, &col, &lnum);
10005 # ifdef FEAT_WINDOWS
10006 for (wp = firstwin; wp != win; wp = wp->w_next)
10007 ++n;
10008 # endif
10009 vimvars[VV_MOUSE_WIN].vv_nr = n;
10010 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
10011 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
10014 #endif
10019 * "getcharmod()" function
10021 /*ARGSUSED*/
10022 static void
10023 f_getcharmod(argvars, rettv)
10024 typval_T *argvars;
10025 typval_T *rettv;
10027 rettv->vval.v_number = mod_mask;
10031 * "getcmdline()" function
10033 /*ARGSUSED*/
10034 static void
10035 f_getcmdline(argvars, rettv)
10036 typval_T *argvars;
10037 typval_T *rettv;
10039 rettv->v_type = VAR_STRING;
10040 rettv->vval.v_string = get_cmdline_str();
10044 * "getcmdpos()" function
10046 /*ARGSUSED*/
10047 static void
10048 f_getcmdpos(argvars, rettv)
10049 typval_T *argvars;
10050 typval_T *rettv;
10052 rettv->vval.v_number = get_cmdline_pos() + 1;
10056 * "getcmdtype()" function
10058 /*ARGSUSED*/
10059 static void
10060 f_getcmdtype(argvars, rettv)
10061 typval_T *argvars;
10062 typval_T *rettv;
10064 rettv->v_type = VAR_STRING;
10065 rettv->vval.v_string = alloc(2);
10066 if (rettv->vval.v_string != NULL)
10068 rettv->vval.v_string[0] = get_cmdline_type();
10069 rettv->vval.v_string[1] = NUL;
10074 * "getcwd()" function
10076 /*ARGSUSED*/
10077 static void
10078 f_getcwd(argvars, rettv)
10079 typval_T *argvars;
10080 typval_T *rettv;
10082 char_u cwd[MAXPATHL];
10084 rettv->v_type = VAR_STRING;
10085 if (mch_dirname(cwd, MAXPATHL) == FAIL)
10086 rettv->vval.v_string = NULL;
10087 else
10089 rettv->vval.v_string = vim_strsave(cwd);
10090 #ifdef BACKSLASH_IN_FILENAME
10091 if (rettv->vval.v_string != NULL)
10092 slash_adjust(rettv->vval.v_string);
10093 #endif
10098 * "getfontname()" function
10100 /*ARGSUSED*/
10101 static void
10102 f_getfontname(argvars, rettv)
10103 typval_T *argvars;
10104 typval_T *rettv;
10106 rettv->v_type = VAR_STRING;
10107 rettv->vval.v_string = NULL;
10108 #ifdef FEAT_GUI
10109 if (gui.in_use)
10111 GuiFont font;
10112 char_u *name = NULL;
10114 if (argvars[0].v_type == VAR_UNKNOWN)
10116 /* Get the "Normal" font. Either the name saved by
10117 * hl_set_font_name() or from the font ID. */
10118 font = gui.norm_font;
10119 name = hl_get_font_name();
10121 else
10123 name = get_tv_string(&argvars[0]);
10124 if (STRCMP(name, "*") == 0) /* don't use font dialog */
10125 return;
10126 font = gui_mch_get_font(name, FALSE);
10127 if (font == NOFONT)
10128 return; /* Invalid font name, return empty string. */
10130 rettv->vval.v_string = gui_mch_get_fontname(font, name);
10131 if (argvars[0].v_type != VAR_UNKNOWN)
10132 gui_mch_free_font(font);
10134 #endif
10138 * "getfperm({fname})" function
10140 static void
10141 f_getfperm(argvars, rettv)
10142 typval_T *argvars;
10143 typval_T *rettv;
10145 char_u *fname;
10146 struct stat st;
10147 char_u *perm = NULL;
10148 char_u flags[] = "rwx";
10149 int i;
10151 fname = get_tv_string(&argvars[0]);
10153 rettv->v_type = VAR_STRING;
10154 if (mch_stat((char *)fname, &st) >= 0)
10156 perm = vim_strsave((char_u *)"---------");
10157 if (perm != NULL)
10159 for (i = 0; i < 9; i++)
10161 if (st.st_mode & (1 << (8 - i)))
10162 perm[i] = flags[i % 3];
10166 rettv->vval.v_string = perm;
10170 * "getfsize({fname})" function
10172 static void
10173 f_getfsize(argvars, rettv)
10174 typval_T *argvars;
10175 typval_T *rettv;
10177 char_u *fname;
10178 struct stat st;
10180 fname = get_tv_string(&argvars[0]);
10182 rettv->v_type = VAR_NUMBER;
10184 if (mch_stat((char *)fname, &st) >= 0)
10186 if (mch_isdir(fname))
10187 rettv->vval.v_number = 0;
10188 else
10190 rettv->vval.v_number = (varnumber_T)st.st_size;
10192 /* non-perfect check for overflow */
10193 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
10194 rettv->vval.v_number = -2;
10197 else
10198 rettv->vval.v_number = -1;
10202 * "getftime({fname})" function
10204 static void
10205 f_getftime(argvars, rettv)
10206 typval_T *argvars;
10207 typval_T *rettv;
10209 char_u *fname;
10210 struct stat st;
10212 fname = get_tv_string(&argvars[0]);
10214 if (mch_stat((char *)fname, &st) >= 0)
10215 rettv->vval.v_number = (varnumber_T)st.st_mtime;
10216 else
10217 rettv->vval.v_number = -1;
10221 * "getftype({fname})" function
10223 static void
10224 f_getftype(argvars, rettv)
10225 typval_T *argvars;
10226 typval_T *rettv;
10228 char_u *fname;
10229 struct stat st;
10230 char_u *type = NULL;
10231 char *t;
10233 fname = get_tv_string(&argvars[0]);
10235 rettv->v_type = VAR_STRING;
10236 if (mch_lstat((char *)fname, &st) >= 0)
10238 #ifdef S_ISREG
10239 if (S_ISREG(st.st_mode))
10240 t = "file";
10241 else if (S_ISDIR(st.st_mode))
10242 t = "dir";
10243 # ifdef S_ISLNK
10244 else if (S_ISLNK(st.st_mode))
10245 t = "link";
10246 # endif
10247 # ifdef S_ISBLK
10248 else if (S_ISBLK(st.st_mode))
10249 t = "bdev";
10250 # endif
10251 # ifdef S_ISCHR
10252 else if (S_ISCHR(st.st_mode))
10253 t = "cdev";
10254 # endif
10255 # ifdef S_ISFIFO
10256 else if (S_ISFIFO(st.st_mode))
10257 t = "fifo";
10258 # endif
10259 # ifdef S_ISSOCK
10260 else if (S_ISSOCK(st.st_mode))
10261 t = "fifo";
10262 # endif
10263 else
10264 t = "other";
10265 #else
10266 # ifdef S_IFMT
10267 switch (st.st_mode & S_IFMT)
10269 case S_IFREG: t = "file"; break;
10270 case S_IFDIR: t = "dir"; break;
10271 # ifdef S_IFLNK
10272 case S_IFLNK: t = "link"; break;
10273 # endif
10274 # ifdef S_IFBLK
10275 case S_IFBLK: t = "bdev"; break;
10276 # endif
10277 # ifdef S_IFCHR
10278 case S_IFCHR: t = "cdev"; break;
10279 # endif
10280 # ifdef S_IFIFO
10281 case S_IFIFO: t = "fifo"; break;
10282 # endif
10283 # ifdef S_IFSOCK
10284 case S_IFSOCK: t = "socket"; break;
10285 # endif
10286 default: t = "other";
10288 # else
10289 if (mch_isdir(fname))
10290 t = "dir";
10291 else
10292 t = "file";
10293 # endif
10294 #endif
10295 type = vim_strsave((char_u *)t);
10297 rettv->vval.v_string = type;
10301 * "getline(lnum, [end])" function
10303 static void
10304 f_getline(argvars, rettv)
10305 typval_T *argvars;
10306 typval_T *rettv;
10308 linenr_T lnum;
10309 linenr_T end;
10310 int retlist;
10312 lnum = get_tv_lnum(argvars);
10313 if (argvars[1].v_type == VAR_UNKNOWN)
10315 end = 0;
10316 retlist = FALSE;
10318 else
10320 end = get_tv_lnum(&argvars[1]);
10321 retlist = TRUE;
10324 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
10328 * "getmatches()" function
10330 /*ARGSUSED*/
10331 static void
10332 f_getmatches(argvars, rettv)
10333 typval_T *argvars;
10334 typval_T *rettv;
10336 #ifdef FEAT_SEARCH_EXTRA
10337 dict_T *dict;
10338 matchitem_T *cur = curwin->w_match_head;
10340 rettv->vval.v_number = 0;
10342 if (rettv_list_alloc(rettv) == OK)
10344 while (cur != NULL)
10346 dict = dict_alloc();
10347 if (dict == NULL)
10348 return;
10349 ++dict->dv_refcount;
10350 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
10351 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
10352 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
10353 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
10354 list_append_dict(rettv->vval.v_list, dict);
10355 cur = cur->next;
10358 #endif
10362 * "getpos(string)" function
10364 static void
10365 f_getpos(argvars, rettv)
10366 typval_T *argvars;
10367 typval_T *rettv;
10369 pos_T *fp;
10370 list_T *l;
10371 int fnum = -1;
10373 if (rettv_list_alloc(rettv) == OK)
10375 l = rettv->vval.v_list;
10376 fp = var2fpos(&argvars[0], TRUE, &fnum);
10377 if (fnum != -1)
10378 list_append_number(l, (varnumber_T)fnum);
10379 else
10380 list_append_number(l, (varnumber_T)0);
10381 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
10382 : (varnumber_T)0);
10383 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->col + 1
10384 : (varnumber_T)0);
10385 list_append_number(l,
10386 #ifdef FEAT_VIRTUALEDIT
10387 (fp != NULL) ? (varnumber_T)fp->coladd :
10388 #endif
10389 (varnumber_T)0);
10391 else
10392 rettv->vval.v_number = FALSE;
10396 * "getqflist()" and "getloclist()" functions
10398 /*ARGSUSED*/
10399 static void
10400 f_getqflist(argvars, rettv)
10401 typval_T *argvars;
10402 typval_T *rettv;
10404 #ifdef FEAT_QUICKFIX
10405 win_T *wp;
10406 #endif
10408 rettv->vval.v_number = 0;
10409 #ifdef FEAT_QUICKFIX
10410 if (rettv_list_alloc(rettv) == OK)
10412 wp = NULL;
10413 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
10415 wp = find_win_by_nr(&argvars[0], NULL);
10416 if (wp == NULL)
10417 return;
10420 (void)get_errorlist(wp, rettv->vval.v_list);
10422 #endif
10426 * "getreg()" function
10428 static void
10429 f_getreg(argvars, rettv)
10430 typval_T *argvars;
10431 typval_T *rettv;
10433 char_u *strregname;
10434 int regname;
10435 int arg2 = FALSE;
10436 int error = FALSE;
10438 if (argvars[0].v_type != VAR_UNKNOWN)
10440 strregname = get_tv_string_chk(&argvars[0]);
10441 error = strregname == NULL;
10442 if (argvars[1].v_type != VAR_UNKNOWN)
10443 arg2 = get_tv_number_chk(&argvars[1], &error);
10445 else
10446 strregname = vimvars[VV_REG].vv_str;
10447 regname = (strregname == NULL ? '"' : *strregname);
10448 if (regname == 0)
10449 regname = '"';
10451 rettv->v_type = VAR_STRING;
10452 rettv->vval.v_string = error ? NULL :
10453 get_reg_contents(regname, TRUE, arg2);
10457 * "getregtype()" function
10459 static void
10460 f_getregtype(argvars, rettv)
10461 typval_T *argvars;
10462 typval_T *rettv;
10464 char_u *strregname;
10465 int regname;
10466 char_u buf[NUMBUFLEN + 2];
10467 long reglen = 0;
10469 if (argvars[0].v_type != VAR_UNKNOWN)
10471 strregname = get_tv_string_chk(&argvars[0]);
10472 if (strregname == NULL) /* type error; errmsg already given */
10474 rettv->v_type = VAR_STRING;
10475 rettv->vval.v_string = NULL;
10476 return;
10479 else
10480 /* Default to v:register */
10481 strregname = vimvars[VV_REG].vv_str;
10483 regname = (strregname == NULL ? '"' : *strregname);
10484 if (regname == 0)
10485 regname = '"';
10487 buf[0] = NUL;
10488 buf[1] = NUL;
10489 switch (get_reg_type(regname, &reglen))
10491 case MLINE: buf[0] = 'V'; break;
10492 case MCHAR: buf[0] = 'v'; break;
10493 #ifdef FEAT_VISUAL
10494 case MBLOCK:
10495 buf[0] = Ctrl_V;
10496 sprintf((char *)buf + 1, "%ld", reglen + 1);
10497 break;
10498 #endif
10500 rettv->v_type = VAR_STRING;
10501 rettv->vval.v_string = vim_strsave(buf);
10505 * "gettabwinvar()" function
10507 static void
10508 f_gettabwinvar(argvars, rettv)
10509 typval_T *argvars;
10510 typval_T *rettv;
10512 getwinvar(argvars, rettv, 1);
10516 * "getwinposx()" function
10518 /*ARGSUSED*/
10519 static void
10520 f_getwinposx(argvars, rettv)
10521 typval_T *argvars;
10522 typval_T *rettv;
10524 rettv->vval.v_number = -1;
10525 #ifdef FEAT_GUI
10526 if (gui.in_use)
10528 int x, y;
10530 if (gui_mch_get_winpos(&x, &y) == OK)
10531 rettv->vval.v_number = x;
10533 #endif
10537 * "getwinposy()" function
10539 /*ARGSUSED*/
10540 static void
10541 f_getwinposy(argvars, rettv)
10542 typval_T *argvars;
10543 typval_T *rettv;
10545 rettv->vval.v_number = -1;
10546 #ifdef FEAT_GUI
10547 if (gui.in_use)
10549 int x, y;
10551 if (gui_mch_get_winpos(&x, &y) == OK)
10552 rettv->vval.v_number = y;
10554 #endif
10558 * Find window specifed by "vp" in tabpage "tp".
10560 static win_T *
10561 find_win_by_nr(vp, tp)
10562 typval_T *vp;
10563 tabpage_T *tp; /* NULL for current tab page */
10565 #ifdef FEAT_WINDOWS
10566 win_T *wp;
10567 #endif
10568 int nr;
10570 nr = get_tv_number_chk(vp, NULL);
10572 #ifdef FEAT_WINDOWS
10573 if (nr < 0)
10574 return NULL;
10575 if (nr == 0)
10576 return curwin;
10578 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
10579 wp != NULL; wp = wp->w_next)
10580 if (--nr <= 0)
10581 break;
10582 return wp;
10583 #else
10584 if (nr == 0 || nr == 1)
10585 return curwin;
10586 return NULL;
10587 #endif
10591 * "getwinvar()" function
10593 static void
10594 f_getwinvar(argvars, rettv)
10595 typval_T *argvars;
10596 typval_T *rettv;
10598 getwinvar(argvars, rettv, 0);
10602 * getwinvar() and gettabwinvar()
10604 static void
10605 getwinvar(argvars, rettv, off)
10606 typval_T *argvars;
10607 typval_T *rettv;
10608 int off; /* 1 for gettabwinvar() */
10610 win_T *win, *oldcurwin;
10611 char_u *varname;
10612 dictitem_T *v;
10613 tabpage_T *tp;
10615 #ifdef FEAT_WINDOWS
10616 if (off == 1)
10617 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
10618 else
10619 tp = curtab;
10620 #endif
10621 win = find_win_by_nr(&argvars[off], tp);
10622 varname = get_tv_string_chk(&argvars[off + 1]);
10623 ++emsg_off;
10625 rettv->v_type = VAR_STRING;
10626 rettv->vval.v_string = NULL;
10628 if (win != NULL && varname != NULL)
10630 /* Set curwin to be our win, temporarily. Also set curbuf, so
10631 * that we can get buffer-local options. */
10632 oldcurwin = curwin;
10633 curwin = win;
10634 curbuf = win->w_buffer;
10636 if (*varname == '&') /* window-local-option */
10637 get_option_tv(&varname, rettv, 1);
10638 else
10640 if (*varname == NUL)
10641 /* let getwinvar({nr}, "") return the "w:" dictionary. The
10642 * scope prefix before the NUL byte is required by
10643 * find_var_in_ht(). */
10644 varname = (char_u *)"w:" + 2;
10645 /* look up the variable */
10646 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
10647 if (v != NULL)
10648 copy_tv(&v->di_tv, rettv);
10651 /* restore previous notion of curwin */
10652 curwin = oldcurwin;
10653 curbuf = curwin->w_buffer;
10656 --emsg_off;
10660 * "glob()" function
10662 static void
10663 f_glob(argvars, rettv)
10664 typval_T *argvars;
10665 typval_T *rettv;
10667 expand_T xpc;
10669 ExpandInit(&xpc);
10670 xpc.xp_context = EXPAND_FILES;
10671 rettv->v_type = VAR_STRING;
10672 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
10673 NULL, WILD_USE_NL|WILD_SILENT, WILD_ALL);
10677 * "globpath()" function
10679 static void
10680 f_globpath(argvars, rettv)
10681 typval_T *argvars;
10682 typval_T *rettv;
10684 char_u buf1[NUMBUFLEN];
10685 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
10687 rettv->v_type = VAR_STRING;
10688 if (file == NULL)
10689 rettv->vval.v_string = NULL;
10690 else
10691 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file);
10695 * "has()" function
10697 static void
10698 f_has(argvars, rettv)
10699 typval_T *argvars;
10700 typval_T *rettv;
10702 int i;
10703 char_u *name;
10704 int n = FALSE;
10705 static char *(has_list[]) =
10707 #ifdef AMIGA
10708 "amiga",
10709 # ifdef FEAT_ARP
10710 "arp",
10711 # endif
10712 #endif
10713 #ifdef __BEOS__
10714 "beos",
10715 #endif
10716 #ifdef MSDOS
10717 # ifdef DJGPP
10718 "dos32",
10719 # else
10720 "dos16",
10721 # endif
10722 #endif
10723 #ifdef MACOS
10724 "mac",
10725 #endif
10726 #if defined(MACOS_X_UNIX)
10727 "macunix",
10728 #endif
10729 #ifdef OS2
10730 "os2",
10731 #endif
10732 #ifdef __QNX__
10733 "qnx",
10734 #endif
10735 #ifdef RISCOS
10736 "riscos",
10737 #endif
10738 #ifdef UNIX
10739 "unix",
10740 #endif
10741 #ifdef VMS
10742 "vms",
10743 #endif
10744 #ifdef WIN16
10745 "win16",
10746 #endif
10747 #ifdef WIN32
10748 "win32",
10749 #endif
10750 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
10751 "win32unix",
10752 #endif
10753 #ifdef WIN64
10754 "win64",
10755 #endif
10756 #ifdef EBCDIC
10757 "ebcdic",
10758 #endif
10759 #ifndef CASE_INSENSITIVE_FILENAME
10760 "fname_case",
10761 #endif
10762 #ifdef FEAT_ARABIC
10763 "arabic",
10764 #endif
10765 #ifdef FEAT_AUTOCMD
10766 "autocmd",
10767 #endif
10768 #ifdef FEAT_BEVAL
10769 "balloon_eval",
10770 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
10771 "balloon_multiline",
10772 # endif
10773 #endif
10774 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
10775 "builtin_terms",
10776 # ifdef ALL_BUILTIN_TCAPS
10777 "all_builtin_terms",
10778 # endif
10779 #endif
10780 #ifdef FEAT_BYTEOFF
10781 "byte_offset",
10782 #endif
10783 #ifdef FEAT_CINDENT
10784 "cindent",
10785 #endif
10786 #ifdef FEAT_CLIENTSERVER
10787 "clientserver",
10788 #endif
10789 #ifdef FEAT_CLIPBOARD
10790 "clipboard",
10791 #endif
10792 #ifdef FEAT_CMDL_COMPL
10793 "cmdline_compl",
10794 #endif
10795 #ifdef FEAT_CMDHIST
10796 "cmdline_hist",
10797 #endif
10798 #ifdef FEAT_COMMENTS
10799 "comments",
10800 #endif
10801 #ifdef FEAT_CRYPT
10802 "cryptv",
10803 #endif
10804 #ifdef FEAT_CSCOPE
10805 "cscope",
10806 #endif
10807 #ifdef CURSOR_SHAPE
10808 "cursorshape",
10809 #endif
10810 #ifdef DEBUG
10811 "debug",
10812 #endif
10813 #ifdef FEAT_CON_DIALOG
10814 "dialog_con",
10815 #endif
10816 #ifdef FEAT_GUI_DIALOG
10817 "dialog_gui",
10818 #endif
10819 #ifdef FEAT_DIFF
10820 "diff",
10821 #endif
10822 #ifdef FEAT_DIGRAPHS
10823 "digraphs",
10824 #endif
10825 #ifdef FEAT_DND
10826 "dnd",
10827 #endif
10828 #ifdef FEAT_EMACS_TAGS
10829 "emacs_tags",
10830 #endif
10831 "eval", /* always present, of course! */
10832 #ifdef FEAT_EX_EXTRA
10833 "ex_extra",
10834 #endif
10835 #ifdef FEAT_SEARCH_EXTRA
10836 "extra_search",
10837 #endif
10838 #ifdef FEAT_FKMAP
10839 "farsi",
10840 #endif
10841 #ifdef FEAT_SEARCHPATH
10842 "file_in_path",
10843 #endif
10844 #if defined(UNIX) && !defined(USE_SYSTEM)
10845 "filterpipe",
10846 #endif
10847 #ifdef FEAT_FIND_ID
10848 "find_in_path",
10849 #endif
10850 #ifdef FEAT_FOLDING
10851 "folding",
10852 #endif
10853 #ifdef FEAT_FOOTER
10854 "footer",
10855 #endif
10856 #if !defined(USE_SYSTEM) && defined(UNIX)
10857 "fork",
10858 #endif
10859 #ifdef FEAT_GETTEXT
10860 "gettext",
10861 #endif
10862 #ifdef FEAT_GUI
10863 "gui",
10864 #endif
10865 #ifdef FEAT_GUI_ATHENA
10866 # ifdef FEAT_GUI_NEXTAW
10867 "gui_neXtaw",
10868 # else
10869 "gui_athena",
10870 # endif
10871 #endif
10872 #ifdef FEAT_GUI_GTK
10873 "gui_gtk",
10874 # ifdef HAVE_GTK2
10875 "gui_gtk2",
10876 # endif
10877 #endif
10878 #ifdef FEAT_GUI_MAC
10879 "gui_mac",
10880 #endif
10881 #ifdef FEAT_GUI_MOTIF
10882 "gui_motif",
10883 #endif
10884 #ifdef FEAT_GUI_PHOTON
10885 "gui_photon",
10886 #endif
10887 #ifdef FEAT_GUI_W16
10888 "gui_win16",
10889 #endif
10890 #ifdef FEAT_GUI_W32
10891 "gui_win32",
10892 #endif
10893 #ifdef FEAT_HANGULIN
10894 "hangul_input",
10895 #endif
10896 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
10897 "iconv",
10898 #endif
10899 #ifdef FEAT_INS_EXPAND
10900 "insert_expand",
10901 #endif
10902 #ifdef FEAT_JUMPLIST
10903 "jumplist",
10904 #endif
10905 #ifdef FEAT_KEYMAP
10906 "keymap",
10907 #endif
10908 #ifdef FEAT_LANGMAP
10909 "langmap",
10910 #endif
10911 #ifdef FEAT_LIBCALL
10912 "libcall",
10913 #endif
10914 #ifdef FEAT_LINEBREAK
10915 "linebreak",
10916 #endif
10917 #ifdef FEAT_LISP
10918 "lispindent",
10919 #endif
10920 #ifdef FEAT_LISTCMDS
10921 "listcmds",
10922 #endif
10923 #ifdef FEAT_LOCALMAP
10924 "localmap",
10925 #endif
10926 #ifdef FEAT_MENU
10927 "menu",
10928 #endif
10929 #ifdef FEAT_SESSION
10930 "mksession",
10931 #endif
10932 #ifdef FEAT_MODIFY_FNAME
10933 "modify_fname",
10934 #endif
10935 #ifdef FEAT_MOUSE
10936 "mouse",
10937 #endif
10938 #ifdef FEAT_MOUSESHAPE
10939 "mouseshape",
10940 #endif
10941 #if defined(UNIX) || defined(VMS)
10942 # ifdef FEAT_MOUSE_DEC
10943 "mouse_dec",
10944 # endif
10945 # ifdef FEAT_MOUSE_GPM
10946 "mouse_gpm",
10947 # endif
10948 # ifdef FEAT_MOUSE_JSB
10949 "mouse_jsbterm",
10950 # endif
10951 # ifdef FEAT_MOUSE_NET
10952 "mouse_netterm",
10953 # endif
10954 # ifdef FEAT_MOUSE_PTERM
10955 "mouse_pterm",
10956 # endif
10957 # ifdef FEAT_MOUSE_XTERM
10958 "mouse_xterm",
10959 # endif
10960 #endif
10961 #ifdef FEAT_MBYTE
10962 "multi_byte",
10963 #endif
10964 #ifdef FEAT_MBYTE_IME
10965 "multi_byte_ime",
10966 #endif
10967 #ifdef FEAT_MULTI_LANG
10968 "multi_lang",
10969 #endif
10970 #ifdef FEAT_MZSCHEME
10971 #ifndef DYNAMIC_MZSCHEME
10972 "mzscheme",
10973 #endif
10974 #endif
10975 #ifdef FEAT_OLE
10976 "ole",
10977 #endif
10978 #ifdef FEAT_OSFILETYPE
10979 "osfiletype",
10980 #endif
10981 #ifdef FEAT_PATH_EXTRA
10982 "path_extra",
10983 #endif
10984 #ifdef FEAT_PERL
10985 #ifndef DYNAMIC_PERL
10986 "perl",
10987 #endif
10988 #endif
10989 #ifdef FEAT_PYTHON
10990 #ifndef DYNAMIC_PYTHON
10991 "python",
10992 #endif
10993 #endif
10994 #ifdef FEAT_POSTSCRIPT
10995 "postscript",
10996 #endif
10997 #ifdef FEAT_PRINTER
10998 "printer",
10999 #endif
11000 #ifdef FEAT_PROFILE
11001 "profile",
11002 #endif
11003 #ifdef FEAT_RELTIME
11004 "reltime",
11005 #endif
11006 #ifdef FEAT_QUICKFIX
11007 "quickfix",
11008 #endif
11009 #ifdef FEAT_RIGHTLEFT
11010 "rightleft",
11011 #endif
11012 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11013 "ruby",
11014 #endif
11015 #ifdef FEAT_SCROLLBIND
11016 "scrollbind",
11017 #endif
11018 #ifdef FEAT_CMDL_INFO
11019 "showcmd",
11020 "cmdline_info",
11021 #endif
11022 #ifdef FEAT_SIGNS
11023 "signs",
11024 #endif
11025 #ifdef FEAT_SMARTINDENT
11026 "smartindent",
11027 #endif
11028 #ifdef FEAT_SNIFF
11029 "sniff",
11030 #endif
11031 #ifdef FEAT_STL_OPT
11032 "statusline",
11033 #endif
11034 #ifdef FEAT_SUN_WORKSHOP
11035 "sun_workshop",
11036 #endif
11037 #ifdef FEAT_NETBEANS_INTG
11038 "netbeans_intg",
11039 #endif
11040 #ifdef FEAT_SPELL
11041 "spell",
11042 #endif
11043 #ifdef FEAT_SYN_HL
11044 "syntax",
11045 #endif
11046 #if defined(USE_SYSTEM) || !defined(UNIX)
11047 "system",
11048 #endif
11049 #ifdef FEAT_TAG_BINS
11050 "tag_binary",
11051 #endif
11052 #ifdef FEAT_TAG_OLDSTATIC
11053 "tag_old_static",
11054 #endif
11055 #ifdef FEAT_TAG_ANYWHITE
11056 "tag_any_white",
11057 #endif
11058 #ifdef FEAT_TCL
11059 # ifndef DYNAMIC_TCL
11060 "tcl",
11061 # endif
11062 #endif
11063 #ifdef TERMINFO
11064 "terminfo",
11065 #endif
11066 #ifdef FEAT_TERMRESPONSE
11067 "termresponse",
11068 #endif
11069 #ifdef FEAT_TEXTOBJ
11070 "textobjects",
11071 #endif
11072 #ifdef HAVE_TGETENT
11073 "tgetent",
11074 #endif
11075 #ifdef FEAT_TITLE
11076 "title",
11077 #endif
11078 #ifdef FEAT_TOOLBAR
11079 "toolbar",
11080 #endif
11081 #ifdef FEAT_USR_CMDS
11082 "user-commands", /* was accidentally included in 5.4 */
11083 "user_commands",
11084 #endif
11085 #ifdef FEAT_VIMINFO
11086 "viminfo",
11087 #endif
11088 #ifdef FEAT_VERTSPLIT
11089 "vertsplit",
11090 #endif
11091 #ifdef FEAT_VIRTUALEDIT
11092 "virtualedit",
11093 #endif
11094 #ifdef FEAT_VISUAL
11095 "visual",
11096 #endif
11097 #ifdef FEAT_VISUALEXTRA
11098 "visualextra",
11099 #endif
11100 #ifdef FEAT_VREPLACE
11101 "vreplace",
11102 #endif
11103 #ifdef FEAT_WILDIGN
11104 "wildignore",
11105 #endif
11106 #ifdef FEAT_WILDMENU
11107 "wildmenu",
11108 #endif
11109 #ifdef FEAT_WINDOWS
11110 "windows",
11111 #endif
11112 #ifdef FEAT_WAK
11113 "winaltkeys",
11114 #endif
11115 #ifdef FEAT_WRITEBACKUP
11116 "writebackup",
11117 #endif
11118 #ifdef FEAT_XIM
11119 "xim",
11120 #endif
11121 #ifdef FEAT_XFONTSET
11122 "xfontset",
11123 #endif
11124 #ifdef USE_XSMP
11125 "xsmp",
11126 #endif
11127 #ifdef USE_XSMP_INTERACT
11128 "xsmp_interact",
11129 #endif
11130 #ifdef FEAT_XCLIPBOARD
11131 "xterm_clipboard",
11132 #endif
11133 #ifdef FEAT_XTERM_SAVE
11134 "xterm_save",
11135 #endif
11136 #if defined(UNIX) && defined(FEAT_X11)
11137 "X11",
11138 #endif
11139 NULL
11142 name = get_tv_string(&argvars[0]);
11143 for (i = 0; has_list[i] != NULL; ++i)
11144 if (STRICMP(name, has_list[i]) == 0)
11146 n = TRUE;
11147 break;
11150 if (n == FALSE)
11152 if (STRNICMP(name, "patch", 5) == 0)
11153 n = has_patch(atoi((char *)name + 5));
11154 else if (STRICMP(name, "vim_starting") == 0)
11155 n = (starting != 0);
11156 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
11157 else if (STRICMP(name, "balloon_multiline") == 0)
11158 n = multiline_balloon_available();
11159 #endif
11160 #ifdef DYNAMIC_TCL
11161 else if (STRICMP(name, "tcl") == 0)
11162 n = tcl_enabled(FALSE);
11163 #endif
11164 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
11165 else if (STRICMP(name, "iconv") == 0)
11166 n = iconv_enabled(FALSE);
11167 #endif
11168 #ifdef DYNAMIC_MZSCHEME
11169 else if (STRICMP(name, "mzscheme") == 0)
11170 n = mzscheme_enabled(FALSE);
11171 #endif
11172 #ifdef DYNAMIC_RUBY
11173 else if (STRICMP(name, "ruby") == 0)
11174 n = ruby_enabled(FALSE);
11175 #endif
11176 #ifdef DYNAMIC_PYTHON
11177 else if (STRICMP(name, "python") == 0)
11178 n = python_enabled(FALSE);
11179 #endif
11180 #ifdef DYNAMIC_PERL
11181 else if (STRICMP(name, "perl") == 0)
11182 n = perl_enabled(FALSE);
11183 #endif
11184 #ifdef FEAT_GUI
11185 else if (STRICMP(name, "gui_running") == 0)
11186 n = (gui.in_use || gui.starting);
11187 # ifdef FEAT_GUI_W32
11188 else if (STRICMP(name, "gui_win32s") == 0)
11189 n = gui_is_win32s();
11190 # endif
11191 # ifdef FEAT_BROWSE
11192 else if (STRICMP(name, "browse") == 0)
11193 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
11194 # endif
11195 #endif
11196 #ifdef FEAT_SYN_HL
11197 else if (STRICMP(name, "syntax_items") == 0)
11198 n = syntax_present(curbuf);
11199 #endif
11200 #if defined(WIN3264)
11201 else if (STRICMP(name, "win95") == 0)
11202 n = mch_windows95();
11203 #endif
11204 #ifdef FEAT_NETBEANS_INTG
11205 else if (STRICMP(name, "netbeans_enabled") == 0)
11206 n = usingNetbeans;
11207 #endif
11210 rettv->vval.v_number = n;
11214 * "has_key()" function
11216 static void
11217 f_has_key(argvars, rettv)
11218 typval_T *argvars;
11219 typval_T *rettv;
11221 rettv->vval.v_number = 0;
11222 if (argvars[0].v_type != VAR_DICT)
11224 EMSG(_(e_dictreq));
11225 return;
11227 if (argvars[0].vval.v_dict == NULL)
11228 return;
11230 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
11231 get_tv_string(&argvars[1]), -1) != NULL;
11235 * "haslocaldir()" function
11237 /*ARGSUSED*/
11238 static void
11239 f_haslocaldir(argvars, rettv)
11240 typval_T *argvars;
11241 typval_T *rettv;
11243 rettv->vval.v_number = (curwin->w_localdir != NULL);
11247 * "hasmapto()" function
11249 static void
11250 f_hasmapto(argvars, rettv)
11251 typval_T *argvars;
11252 typval_T *rettv;
11254 char_u *name;
11255 char_u *mode;
11256 char_u buf[NUMBUFLEN];
11257 int abbr = FALSE;
11259 name = get_tv_string(&argvars[0]);
11260 if (argvars[1].v_type == VAR_UNKNOWN)
11261 mode = (char_u *)"nvo";
11262 else
11264 mode = get_tv_string_buf(&argvars[1], buf);
11265 if (argvars[2].v_type != VAR_UNKNOWN)
11266 abbr = get_tv_number(&argvars[2]);
11269 if (map_to_exists(name, mode, abbr))
11270 rettv->vval.v_number = TRUE;
11271 else
11272 rettv->vval.v_number = FALSE;
11276 * "histadd()" function
11278 /*ARGSUSED*/
11279 static void
11280 f_histadd(argvars, rettv)
11281 typval_T *argvars;
11282 typval_T *rettv;
11284 #ifdef FEAT_CMDHIST
11285 int histype;
11286 char_u *str;
11287 char_u buf[NUMBUFLEN];
11288 #endif
11290 rettv->vval.v_number = FALSE;
11291 if (check_restricted() || check_secure())
11292 return;
11293 #ifdef FEAT_CMDHIST
11294 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11295 histype = str != NULL ? get_histtype(str) : -1;
11296 if (histype >= 0)
11298 str = get_tv_string_buf(&argvars[1], buf);
11299 if (*str != NUL)
11301 add_to_history(histype, str, FALSE, NUL);
11302 rettv->vval.v_number = TRUE;
11303 return;
11306 #endif
11310 * "histdel()" function
11312 /*ARGSUSED*/
11313 static void
11314 f_histdel(argvars, rettv)
11315 typval_T *argvars;
11316 typval_T *rettv;
11318 #ifdef FEAT_CMDHIST
11319 int n;
11320 char_u buf[NUMBUFLEN];
11321 char_u *str;
11323 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11324 if (str == NULL)
11325 n = 0;
11326 else if (argvars[1].v_type == VAR_UNKNOWN)
11327 /* only one argument: clear entire history */
11328 n = clr_history(get_histtype(str));
11329 else if (argvars[1].v_type == VAR_NUMBER)
11330 /* index given: remove that entry */
11331 n = del_history_idx(get_histtype(str),
11332 (int)get_tv_number(&argvars[1]));
11333 else
11334 /* string given: remove all matching entries */
11335 n = del_history_entry(get_histtype(str),
11336 get_tv_string_buf(&argvars[1], buf));
11337 rettv->vval.v_number = n;
11338 #else
11339 rettv->vval.v_number = 0;
11340 #endif
11344 * "histget()" function
11346 /*ARGSUSED*/
11347 static void
11348 f_histget(argvars, rettv)
11349 typval_T *argvars;
11350 typval_T *rettv;
11352 #ifdef FEAT_CMDHIST
11353 int type;
11354 int idx;
11355 char_u *str;
11357 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11358 if (str == NULL)
11359 rettv->vval.v_string = NULL;
11360 else
11362 type = get_histtype(str);
11363 if (argvars[1].v_type == VAR_UNKNOWN)
11364 idx = get_history_idx(type);
11365 else
11366 idx = (int)get_tv_number_chk(&argvars[1], NULL);
11367 /* -1 on type error */
11368 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
11370 #else
11371 rettv->vval.v_string = NULL;
11372 #endif
11373 rettv->v_type = VAR_STRING;
11377 * "histnr()" function
11379 /*ARGSUSED*/
11380 static void
11381 f_histnr(argvars, rettv)
11382 typval_T *argvars;
11383 typval_T *rettv;
11385 int i;
11387 #ifdef FEAT_CMDHIST
11388 char_u *history = get_tv_string_chk(&argvars[0]);
11390 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
11391 if (i >= HIST_CMD && i < HIST_COUNT)
11392 i = get_history_idx(i);
11393 else
11394 #endif
11395 i = -1;
11396 rettv->vval.v_number = i;
11400 * "highlightID(name)" function
11402 static void
11403 f_hlID(argvars, rettv)
11404 typval_T *argvars;
11405 typval_T *rettv;
11407 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
11411 * "highlight_exists()" function
11413 static void
11414 f_hlexists(argvars, rettv)
11415 typval_T *argvars;
11416 typval_T *rettv;
11418 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
11422 * "hostname()" function
11424 /*ARGSUSED*/
11425 static void
11426 f_hostname(argvars, rettv)
11427 typval_T *argvars;
11428 typval_T *rettv;
11430 char_u hostname[256];
11432 mch_get_host_name(hostname, 256);
11433 rettv->v_type = VAR_STRING;
11434 rettv->vval.v_string = vim_strsave(hostname);
11438 * iconv() function
11440 /*ARGSUSED*/
11441 static void
11442 f_iconv(argvars, rettv)
11443 typval_T *argvars;
11444 typval_T *rettv;
11446 #ifdef FEAT_MBYTE
11447 char_u buf1[NUMBUFLEN];
11448 char_u buf2[NUMBUFLEN];
11449 char_u *from, *to, *str;
11450 vimconv_T vimconv;
11451 #endif
11453 rettv->v_type = VAR_STRING;
11454 rettv->vval.v_string = NULL;
11456 #ifdef FEAT_MBYTE
11457 str = get_tv_string(&argvars[0]);
11458 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
11459 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
11460 vimconv.vc_type = CONV_NONE;
11461 convert_setup(&vimconv, from, to);
11463 /* If the encodings are equal, no conversion needed. */
11464 if (vimconv.vc_type == CONV_NONE)
11465 rettv->vval.v_string = vim_strsave(str);
11466 else
11467 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
11469 convert_setup(&vimconv, NULL, NULL);
11470 vim_free(from);
11471 vim_free(to);
11472 #endif
11476 * "indent()" function
11478 static void
11479 f_indent(argvars, rettv)
11480 typval_T *argvars;
11481 typval_T *rettv;
11483 linenr_T lnum;
11485 lnum = get_tv_lnum(argvars);
11486 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
11487 rettv->vval.v_number = get_indent_lnum(lnum);
11488 else
11489 rettv->vval.v_number = -1;
11493 * "index()" function
11495 static void
11496 f_index(argvars, rettv)
11497 typval_T *argvars;
11498 typval_T *rettv;
11500 list_T *l;
11501 listitem_T *item;
11502 long idx = 0;
11503 int ic = FALSE;
11505 rettv->vval.v_number = -1;
11506 if (argvars[0].v_type != VAR_LIST)
11508 EMSG(_(e_listreq));
11509 return;
11511 l = argvars[0].vval.v_list;
11512 if (l != NULL)
11514 item = l->lv_first;
11515 if (argvars[2].v_type != VAR_UNKNOWN)
11517 int error = FALSE;
11519 /* Start at specified item. Use the cached index that list_find()
11520 * sets, so that a negative number also works. */
11521 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
11522 idx = l->lv_idx;
11523 if (argvars[3].v_type != VAR_UNKNOWN)
11524 ic = get_tv_number_chk(&argvars[3], &error);
11525 if (error)
11526 item = NULL;
11529 for ( ; item != NULL; item = item->li_next, ++idx)
11530 if (tv_equal(&item->li_tv, &argvars[1], ic))
11532 rettv->vval.v_number = idx;
11533 break;
11538 static int inputsecret_flag = 0;
11540 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
11543 * This function is used by f_input() and f_inputdialog() functions. The third
11544 * argument to f_input() specifies the type of completion to use at the
11545 * prompt. The third argument to f_inputdialog() specifies the value to return
11546 * when the user cancels the prompt.
11548 static void
11549 get_user_input(argvars, rettv, inputdialog)
11550 typval_T *argvars;
11551 typval_T *rettv;
11552 int inputdialog;
11554 char_u *prompt = get_tv_string_chk(&argvars[0]);
11555 char_u *p = NULL;
11556 int c;
11557 char_u buf[NUMBUFLEN];
11558 int cmd_silent_save = cmd_silent;
11559 char_u *defstr = (char_u *)"";
11560 int xp_type = EXPAND_NOTHING;
11561 char_u *xp_arg = NULL;
11563 rettv->v_type = VAR_STRING;
11565 #ifdef NO_CONSOLE_INPUT
11566 /* While starting up, there is no place to enter text. */
11567 if (no_console_input())
11569 rettv->vval.v_string = NULL;
11570 return;
11572 #endif
11574 cmd_silent = FALSE; /* Want to see the prompt. */
11575 if (prompt != NULL)
11577 /* Only the part of the message after the last NL is considered as
11578 * prompt for the command line */
11579 p = vim_strrchr(prompt, '\n');
11580 if (p == NULL)
11581 p = prompt;
11582 else
11584 ++p;
11585 c = *p;
11586 *p = NUL;
11587 msg_start();
11588 msg_clr_eos();
11589 msg_puts_attr(prompt, echo_attr);
11590 msg_didout = FALSE;
11591 msg_starthere();
11592 *p = c;
11594 cmdline_row = msg_row;
11596 if (argvars[1].v_type != VAR_UNKNOWN)
11598 defstr = get_tv_string_buf_chk(&argvars[1], buf);
11599 if (defstr != NULL)
11600 stuffReadbuffSpec(defstr);
11602 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
11604 char_u *xp_name;
11605 int xp_namelen;
11606 long argt;
11608 rettv->vval.v_string = NULL;
11610 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
11611 if (xp_name == NULL)
11612 return;
11614 xp_namelen = (int)STRLEN(xp_name);
11616 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
11617 &xp_arg) == FAIL)
11618 return;
11622 if (defstr != NULL)
11623 rettv->vval.v_string =
11624 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
11625 xp_type, xp_arg);
11627 vim_free(xp_arg);
11629 /* since the user typed this, no need to wait for return */
11630 need_wait_return = FALSE;
11631 msg_didout = FALSE;
11633 cmd_silent = cmd_silent_save;
11637 * "input()" function
11638 * Also handles inputsecret() when inputsecret is set.
11640 static void
11641 f_input(argvars, rettv)
11642 typval_T *argvars;
11643 typval_T *rettv;
11645 get_user_input(argvars, rettv, FALSE);
11649 * "inputdialog()" function
11651 static void
11652 f_inputdialog(argvars, rettv)
11653 typval_T *argvars;
11654 typval_T *rettv;
11656 #if defined(FEAT_GUI_TEXTDIALOG)
11657 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
11658 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
11660 char_u *message;
11661 char_u buf[NUMBUFLEN];
11662 char_u *defstr = (char_u *)"";
11664 message = get_tv_string_chk(&argvars[0]);
11665 if (argvars[1].v_type != VAR_UNKNOWN
11666 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
11667 vim_strncpy(IObuff, defstr, IOSIZE - 1);
11668 else
11669 IObuff[0] = NUL;
11670 if (message != NULL && defstr != NULL
11671 && do_dialog(VIM_QUESTION, NULL, message,
11672 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
11673 rettv->vval.v_string = vim_strsave(IObuff);
11674 else
11676 if (message != NULL && defstr != NULL
11677 && argvars[1].v_type != VAR_UNKNOWN
11678 && argvars[2].v_type != VAR_UNKNOWN)
11679 rettv->vval.v_string = vim_strsave(
11680 get_tv_string_buf(&argvars[2], buf));
11681 else
11682 rettv->vval.v_string = NULL;
11684 rettv->v_type = VAR_STRING;
11686 else
11687 #endif
11688 get_user_input(argvars, rettv, TRUE);
11692 * "inputlist()" function
11694 static void
11695 f_inputlist(argvars, rettv)
11696 typval_T *argvars;
11697 typval_T *rettv;
11699 listitem_T *li;
11700 int selected;
11701 int mouse_used;
11703 rettv->vval.v_number = 0;
11704 #ifdef NO_CONSOLE_INPUT
11705 /* While starting up, there is no place to enter text. */
11706 if (no_console_input())
11707 return;
11708 #endif
11709 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
11711 EMSG2(_(e_listarg), "inputlist()");
11712 return;
11715 msg_start();
11716 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
11717 lines_left = Rows; /* avoid more prompt */
11718 msg_scroll = TRUE;
11719 msg_clr_eos();
11721 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
11723 msg_puts(get_tv_string(&li->li_tv));
11724 msg_putchar('\n');
11727 /* Ask for choice. */
11728 selected = prompt_for_number(&mouse_used);
11729 if (mouse_used)
11730 selected -= lines_left;
11732 rettv->vval.v_number = selected;
11736 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
11739 * "inputrestore()" function
11741 /*ARGSUSED*/
11742 static void
11743 f_inputrestore(argvars, rettv)
11744 typval_T *argvars;
11745 typval_T *rettv;
11747 if (ga_userinput.ga_len > 0)
11749 --ga_userinput.ga_len;
11750 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
11751 + ga_userinput.ga_len);
11752 rettv->vval.v_number = 0; /* OK */
11754 else if (p_verbose > 1)
11756 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
11757 rettv->vval.v_number = 1; /* Failed */
11762 * "inputsave()" function
11764 /*ARGSUSED*/
11765 static void
11766 f_inputsave(argvars, rettv)
11767 typval_T *argvars;
11768 typval_T *rettv;
11770 /* Add an entry to the stack of typehead storage. */
11771 if (ga_grow(&ga_userinput, 1) == OK)
11773 save_typeahead((tasave_T *)(ga_userinput.ga_data)
11774 + ga_userinput.ga_len);
11775 ++ga_userinput.ga_len;
11776 rettv->vval.v_number = 0; /* OK */
11778 else
11779 rettv->vval.v_number = 1; /* Failed */
11783 * "inputsecret()" function
11785 static void
11786 f_inputsecret(argvars, rettv)
11787 typval_T *argvars;
11788 typval_T *rettv;
11790 ++cmdline_star;
11791 ++inputsecret_flag;
11792 f_input(argvars, rettv);
11793 --cmdline_star;
11794 --inputsecret_flag;
11798 * "insert()" function
11800 static void
11801 f_insert(argvars, rettv)
11802 typval_T *argvars;
11803 typval_T *rettv;
11805 long before = 0;
11806 listitem_T *item;
11807 list_T *l;
11808 int error = FALSE;
11810 rettv->vval.v_number = 0;
11811 if (argvars[0].v_type != VAR_LIST)
11812 EMSG2(_(e_listarg), "insert()");
11813 else if ((l = argvars[0].vval.v_list) != NULL
11814 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
11816 if (argvars[2].v_type != VAR_UNKNOWN)
11817 before = get_tv_number_chk(&argvars[2], &error);
11818 if (error)
11819 return; /* type error; errmsg already given */
11821 if (before == l->lv_len)
11822 item = NULL;
11823 else
11825 item = list_find(l, before);
11826 if (item == NULL)
11828 EMSGN(_(e_listidx), before);
11829 l = NULL;
11832 if (l != NULL)
11834 list_insert_tv(l, &argvars[1], item);
11835 copy_tv(&argvars[0], rettv);
11841 * "isdirectory()" function
11843 static void
11844 f_isdirectory(argvars, rettv)
11845 typval_T *argvars;
11846 typval_T *rettv;
11848 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
11852 * "islocked()" function
11854 static void
11855 f_islocked(argvars, rettv)
11856 typval_T *argvars;
11857 typval_T *rettv;
11859 lval_T lv;
11860 char_u *end;
11861 dictitem_T *di;
11863 rettv->vval.v_number = -1;
11864 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
11865 FNE_CHECK_START);
11866 if (end != NULL && lv.ll_name != NULL)
11868 if (*end != NUL)
11869 EMSG(_(e_trailing));
11870 else
11872 if (lv.ll_tv == NULL)
11874 if (check_changedtick(lv.ll_name))
11875 rettv->vval.v_number = 1; /* always locked */
11876 else
11878 di = find_var(lv.ll_name, NULL);
11879 if (di != NULL)
11881 /* Consider a variable locked when:
11882 * 1. the variable itself is locked
11883 * 2. the value of the variable is locked.
11884 * 3. the List or Dict value is locked.
11886 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
11887 || tv_islocked(&di->di_tv));
11891 else if (lv.ll_range)
11892 EMSG(_("E786: Range not allowed"));
11893 else if (lv.ll_newkey != NULL)
11894 EMSG2(_(e_dictkey), lv.ll_newkey);
11895 else if (lv.ll_list != NULL)
11896 /* List item. */
11897 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
11898 else
11899 /* Dictionary item. */
11900 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
11904 clear_lval(&lv);
11907 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
11910 * Turn a dict into a list:
11911 * "what" == 0: list of keys
11912 * "what" == 1: list of values
11913 * "what" == 2: list of items
11915 static void
11916 dict_list(argvars, rettv, what)
11917 typval_T *argvars;
11918 typval_T *rettv;
11919 int what;
11921 list_T *l2;
11922 dictitem_T *di;
11923 hashitem_T *hi;
11924 listitem_T *li;
11925 listitem_T *li2;
11926 dict_T *d;
11927 int todo;
11929 rettv->vval.v_number = 0;
11930 if (argvars[0].v_type != VAR_DICT)
11932 EMSG(_(e_dictreq));
11933 return;
11935 if ((d = argvars[0].vval.v_dict) == NULL)
11936 return;
11938 if (rettv_list_alloc(rettv) == FAIL)
11939 return;
11941 todo = (int)d->dv_hashtab.ht_used;
11942 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
11944 if (!HASHITEM_EMPTY(hi))
11946 --todo;
11947 di = HI2DI(hi);
11949 li = listitem_alloc();
11950 if (li == NULL)
11951 break;
11952 list_append(rettv->vval.v_list, li);
11954 if (what == 0)
11956 /* keys() */
11957 li->li_tv.v_type = VAR_STRING;
11958 li->li_tv.v_lock = 0;
11959 li->li_tv.vval.v_string = vim_strsave(di->di_key);
11961 else if (what == 1)
11963 /* values() */
11964 copy_tv(&di->di_tv, &li->li_tv);
11966 else
11968 /* items() */
11969 l2 = list_alloc();
11970 li->li_tv.v_type = VAR_LIST;
11971 li->li_tv.v_lock = 0;
11972 li->li_tv.vval.v_list = l2;
11973 if (l2 == NULL)
11974 break;
11975 ++l2->lv_refcount;
11977 li2 = listitem_alloc();
11978 if (li2 == NULL)
11979 break;
11980 list_append(l2, li2);
11981 li2->li_tv.v_type = VAR_STRING;
11982 li2->li_tv.v_lock = 0;
11983 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
11985 li2 = listitem_alloc();
11986 if (li2 == NULL)
11987 break;
11988 list_append(l2, li2);
11989 copy_tv(&di->di_tv, &li2->li_tv);
11996 * "items(dict)" function
11998 static void
11999 f_items(argvars, rettv)
12000 typval_T *argvars;
12001 typval_T *rettv;
12003 dict_list(argvars, rettv, 2);
12007 * "join()" function
12009 static void
12010 f_join(argvars, rettv)
12011 typval_T *argvars;
12012 typval_T *rettv;
12014 garray_T ga;
12015 char_u *sep;
12017 rettv->vval.v_number = 0;
12018 if (argvars[0].v_type != VAR_LIST)
12020 EMSG(_(e_listreq));
12021 return;
12023 if (argvars[0].vval.v_list == NULL)
12024 return;
12025 if (argvars[1].v_type == VAR_UNKNOWN)
12026 sep = (char_u *)" ";
12027 else
12028 sep = get_tv_string_chk(&argvars[1]);
12030 rettv->v_type = VAR_STRING;
12032 if (sep != NULL)
12034 ga_init2(&ga, (int)sizeof(char), 80);
12035 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12036 ga_append(&ga, NUL);
12037 rettv->vval.v_string = (char_u *)ga.ga_data;
12039 else
12040 rettv->vval.v_string = NULL;
12044 * "keys()" function
12046 static void
12047 f_keys(argvars, rettv)
12048 typval_T *argvars;
12049 typval_T *rettv;
12051 dict_list(argvars, rettv, 0);
12055 * "last_buffer_nr()" function.
12057 /*ARGSUSED*/
12058 static void
12059 f_last_buffer_nr(argvars, rettv)
12060 typval_T *argvars;
12061 typval_T *rettv;
12063 int n = 0;
12064 buf_T *buf;
12066 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12067 if (n < buf->b_fnum)
12068 n = buf->b_fnum;
12070 rettv->vval.v_number = n;
12074 * "len()" function
12076 static void
12077 f_len(argvars, rettv)
12078 typval_T *argvars;
12079 typval_T *rettv;
12081 switch (argvars[0].v_type)
12083 case VAR_STRING:
12084 case VAR_NUMBER:
12085 rettv->vval.v_number = (varnumber_T)STRLEN(
12086 get_tv_string(&argvars[0]));
12087 break;
12088 case VAR_LIST:
12089 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
12090 break;
12091 case VAR_DICT:
12092 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
12093 break;
12094 default:
12095 EMSG(_("E701: Invalid type for len()"));
12096 break;
12100 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
12102 static void
12103 libcall_common(argvars, rettv, type)
12104 typval_T *argvars;
12105 typval_T *rettv;
12106 int type;
12108 #ifdef FEAT_LIBCALL
12109 char_u *string_in;
12110 char_u **string_result;
12111 int nr_result;
12112 #endif
12114 rettv->v_type = type;
12115 if (type == VAR_NUMBER)
12116 rettv->vval.v_number = 0;
12117 else
12118 rettv->vval.v_string = NULL;
12120 if (check_restricted() || check_secure())
12121 return;
12123 #ifdef FEAT_LIBCALL
12124 /* The first two args must be strings, otherwise its meaningless */
12125 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
12127 string_in = NULL;
12128 if (argvars[2].v_type == VAR_STRING)
12129 string_in = argvars[2].vval.v_string;
12130 if (type == VAR_NUMBER)
12131 string_result = NULL;
12132 else
12133 string_result = &rettv->vval.v_string;
12134 if (mch_libcall(argvars[0].vval.v_string,
12135 argvars[1].vval.v_string,
12136 string_in,
12137 argvars[2].vval.v_number,
12138 string_result,
12139 &nr_result) == OK
12140 && type == VAR_NUMBER)
12141 rettv->vval.v_number = nr_result;
12143 #endif
12147 * "libcall()" function
12149 static void
12150 f_libcall(argvars, rettv)
12151 typval_T *argvars;
12152 typval_T *rettv;
12154 libcall_common(argvars, rettv, VAR_STRING);
12158 * "libcallnr()" function
12160 static void
12161 f_libcallnr(argvars, rettv)
12162 typval_T *argvars;
12163 typval_T *rettv;
12165 libcall_common(argvars, rettv, VAR_NUMBER);
12169 * "line(string)" function
12171 static void
12172 f_line(argvars, rettv)
12173 typval_T *argvars;
12174 typval_T *rettv;
12176 linenr_T lnum = 0;
12177 pos_T *fp;
12178 int fnum;
12180 fp = var2fpos(&argvars[0], TRUE, &fnum);
12181 if (fp != NULL)
12182 lnum = fp->lnum;
12183 rettv->vval.v_number = lnum;
12187 * "line2byte(lnum)" function
12189 /*ARGSUSED*/
12190 static void
12191 f_line2byte(argvars, rettv)
12192 typval_T *argvars;
12193 typval_T *rettv;
12195 #ifndef FEAT_BYTEOFF
12196 rettv->vval.v_number = -1;
12197 #else
12198 linenr_T lnum;
12200 lnum = get_tv_lnum(argvars);
12201 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
12202 rettv->vval.v_number = -1;
12203 else
12204 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
12205 if (rettv->vval.v_number >= 0)
12206 ++rettv->vval.v_number;
12207 #endif
12211 * "lispindent(lnum)" function
12213 static void
12214 f_lispindent(argvars, rettv)
12215 typval_T *argvars;
12216 typval_T *rettv;
12218 #ifdef FEAT_LISP
12219 pos_T pos;
12220 linenr_T lnum;
12222 pos = curwin->w_cursor;
12223 lnum = get_tv_lnum(argvars);
12224 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12226 curwin->w_cursor.lnum = lnum;
12227 rettv->vval.v_number = get_lisp_indent();
12228 curwin->w_cursor = pos;
12230 else
12231 #endif
12232 rettv->vval.v_number = -1;
12236 * "localtime()" function
12238 /*ARGSUSED*/
12239 static void
12240 f_localtime(argvars, rettv)
12241 typval_T *argvars;
12242 typval_T *rettv;
12244 rettv->vval.v_number = (varnumber_T)time(NULL);
12247 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
12249 static void
12250 get_maparg(argvars, rettv, exact)
12251 typval_T *argvars;
12252 typval_T *rettv;
12253 int exact;
12255 char_u *keys;
12256 char_u *which;
12257 char_u buf[NUMBUFLEN];
12258 char_u *keys_buf = NULL;
12259 char_u *rhs;
12260 int mode;
12261 garray_T ga;
12262 int abbr = FALSE;
12264 /* return empty string for failure */
12265 rettv->v_type = VAR_STRING;
12266 rettv->vval.v_string = NULL;
12268 keys = get_tv_string(&argvars[0]);
12269 if (*keys == NUL)
12270 return;
12272 if (argvars[1].v_type != VAR_UNKNOWN)
12274 which = get_tv_string_buf_chk(&argvars[1], buf);
12275 if (argvars[2].v_type != VAR_UNKNOWN)
12276 abbr = get_tv_number(&argvars[2]);
12278 else
12279 which = (char_u *)"";
12280 if (which == NULL)
12281 return;
12283 mode = get_map_mode(&which, 0);
12285 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
12286 rhs = check_map(keys, mode, exact, FALSE, abbr);
12287 vim_free(keys_buf);
12288 if (rhs != NULL)
12290 ga_init(&ga);
12291 ga.ga_itemsize = 1;
12292 ga.ga_growsize = 40;
12294 while (*rhs != NUL)
12295 ga_concat(&ga, str2special(&rhs, FALSE));
12297 ga_append(&ga, NUL);
12298 rettv->vval.v_string = (char_u *)ga.ga_data;
12303 * "map()" function
12305 static void
12306 f_map(argvars, rettv)
12307 typval_T *argvars;
12308 typval_T *rettv;
12310 filter_map(argvars, rettv, TRUE);
12314 * "maparg()" function
12316 static void
12317 f_maparg(argvars, rettv)
12318 typval_T *argvars;
12319 typval_T *rettv;
12321 get_maparg(argvars, rettv, TRUE);
12325 * "mapcheck()" function
12327 static void
12328 f_mapcheck(argvars, rettv)
12329 typval_T *argvars;
12330 typval_T *rettv;
12332 get_maparg(argvars, rettv, FALSE);
12335 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
12337 static void
12338 find_some_match(argvars, rettv, type)
12339 typval_T *argvars;
12340 typval_T *rettv;
12341 int type;
12343 char_u *str = NULL;
12344 char_u *expr = NULL;
12345 char_u *pat;
12346 regmatch_T regmatch;
12347 char_u patbuf[NUMBUFLEN];
12348 char_u strbuf[NUMBUFLEN];
12349 char_u *save_cpo;
12350 long start = 0;
12351 long nth = 1;
12352 colnr_T startcol = 0;
12353 int match = 0;
12354 list_T *l = NULL;
12355 listitem_T *li = NULL;
12356 long idx = 0;
12357 char_u *tofree = NULL;
12359 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
12360 save_cpo = p_cpo;
12361 p_cpo = (char_u *)"";
12363 rettv->vval.v_number = -1;
12364 if (type == 3)
12366 /* return empty list when there are no matches */
12367 if (rettv_list_alloc(rettv) == FAIL)
12368 goto theend;
12370 else if (type == 2)
12372 rettv->v_type = VAR_STRING;
12373 rettv->vval.v_string = NULL;
12376 if (argvars[0].v_type == VAR_LIST)
12378 if ((l = argvars[0].vval.v_list) == NULL)
12379 goto theend;
12380 li = l->lv_first;
12382 else
12383 expr = str = get_tv_string(&argvars[0]);
12385 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
12386 if (pat == NULL)
12387 goto theend;
12389 if (argvars[2].v_type != VAR_UNKNOWN)
12391 int error = FALSE;
12393 start = get_tv_number_chk(&argvars[2], &error);
12394 if (error)
12395 goto theend;
12396 if (l != NULL)
12398 li = list_find(l, start);
12399 if (li == NULL)
12400 goto theend;
12401 idx = l->lv_idx; /* use the cached index */
12403 else
12405 if (start < 0)
12406 start = 0;
12407 if (start > (long)STRLEN(str))
12408 goto theend;
12409 /* When "count" argument is there ignore matches before "start",
12410 * otherwise skip part of the string. Differs when pattern is "^"
12411 * or "\<". */
12412 if (argvars[3].v_type != VAR_UNKNOWN)
12413 startcol = start;
12414 else
12415 str += start;
12418 if (argvars[3].v_type != VAR_UNKNOWN)
12419 nth = get_tv_number_chk(&argvars[3], &error);
12420 if (error)
12421 goto theend;
12424 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
12425 if (regmatch.regprog != NULL)
12427 regmatch.rm_ic = p_ic;
12429 for (;;)
12431 if (l != NULL)
12433 if (li == NULL)
12435 match = FALSE;
12436 break;
12438 vim_free(tofree);
12439 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
12440 if (str == NULL)
12441 break;
12444 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
12446 if (match && --nth <= 0)
12447 break;
12448 if (l == NULL && !match)
12449 break;
12451 /* Advance to just after the match. */
12452 if (l != NULL)
12454 li = li->li_next;
12455 ++idx;
12457 else
12459 #ifdef FEAT_MBYTE
12460 startcol = (colnr_T)(regmatch.startp[0]
12461 + (*mb_ptr2len)(regmatch.startp[0]) - str);
12462 #else
12463 startcol = regmatch.startp[0] + 1 - str;
12464 #endif
12468 if (match)
12470 if (type == 3)
12472 int i;
12474 /* return list with matched string and submatches */
12475 for (i = 0; i < NSUBEXP; ++i)
12477 if (regmatch.endp[i] == NULL)
12479 if (list_append_string(rettv->vval.v_list,
12480 (char_u *)"", 0) == FAIL)
12481 break;
12483 else if (list_append_string(rettv->vval.v_list,
12484 regmatch.startp[i],
12485 (int)(regmatch.endp[i] - regmatch.startp[i]))
12486 == FAIL)
12487 break;
12490 else if (type == 2)
12492 /* return matched string */
12493 if (l != NULL)
12494 copy_tv(&li->li_tv, rettv);
12495 else
12496 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
12497 (int)(regmatch.endp[0] - regmatch.startp[0]));
12499 else if (l != NULL)
12500 rettv->vval.v_number = idx;
12501 else
12503 if (type != 0)
12504 rettv->vval.v_number =
12505 (varnumber_T)(regmatch.startp[0] - str);
12506 else
12507 rettv->vval.v_number =
12508 (varnumber_T)(regmatch.endp[0] - str);
12509 rettv->vval.v_number += (varnumber_T)(str - expr);
12512 vim_free(regmatch.regprog);
12515 theend:
12516 vim_free(tofree);
12517 p_cpo = save_cpo;
12521 * "match()" function
12523 static void
12524 f_match(argvars, rettv)
12525 typval_T *argvars;
12526 typval_T *rettv;
12528 find_some_match(argvars, rettv, 1);
12532 * "matchadd()" function
12534 static void
12535 f_matchadd(argvars, rettv)
12536 typval_T *argvars;
12537 typval_T *rettv;
12539 #ifdef FEAT_SEARCH_EXTRA
12540 char_u buf[NUMBUFLEN];
12541 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
12542 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
12543 int prio = 10; /* default priority */
12544 int id = -1;
12545 int error = FALSE;
12547 rettv->vval.v_number = -1;
12549 if (grp == NULL || pat == NULL)
12550 return;
12551 if (argvars[2].v_type != VAR_UNKNOWN)
12553 prio = get_tv_number_chk(&argvars[2], &error);
12554 if (argvars[3].v_type != VAR_UNKNOWN)
12555 id = get_tv_number_chk(&argvars[3], &error);
12557 if (error == TRUE)
12558 return;
12559 if (id >= 1 && id <= 3)
12561 EMSGN("E798: ID is reserved for \":match\": %ld", id);
12562 return;
12565 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
12566 #endif
12570 * "matcharg()" function
12572 static void
12573 f_matcharg(argvars, rettv)
12574 typval_T *argvars;
12575 typval_T *rettv;
12577 if (rettv_list_alloc(rettv) == OK)
12579 #ifdef FEAT_SEARCH_EXTRA
12580 int id = get_tv_number(&argvars[0]);
12581 matchitem_T *m;
12583 if (id >= 1 && id <= 3)
12585 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
12587 list_append_string(rettv->vval.v_list,
12588 syn_id2name(m->hlg_id), -1);
12589 list_append_string(rettv->vval.v_list, m->pattern, -1);
12591 else
12593 list_append_string(rettv->vval.v_list, NUL, -1);
12594 list_append_string(rettv->vval.v_list, NUL, -1);
12597 #endif
12602 * "matchdelete()" function
12604 static void
12605 f_matchdelete(argvars, rettv)
12606 typval_T *argvars;
12607 typval_T *rettv;
12609 #ifdef FEAT_SEARCH_EXTRA
12610 rettv->vval.v_number = match_delete(curwin,
12611 (int)get_tv_number(&argvars[0]), TRUE);
12612 #endif
12616 * "matchend()" function
12618 static void
12619 f_matchend(argvars, rettv)
12620 typval_T *argvars;
12621 typval_T *rettv;
12623 find_some_match(argvars, rettv, 0);
12627 * "matchlist()" function
12629 static void
12630 f_matchlist(argvars, rettv)
12631 typval_T *argvars;
12632 typval_T *rettv;
12634 find_some_match(argvars, rettv, 3);
12638 * "matchstr()" function
12640 static void
12641 f_matchstr(argvars, rettv)
12642 typval_T *argvars;
12643 typval_T *rettv;
12645 find_some_match(argvars, rettv, 2);
12648 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
12650 static void
12651 max_min(argvars, rettv, domax)
12652 typval_T *argvars;
12653 typval_T *rettv;
12654 int domax;
12656 long n = 0;
12657 long i;
12658 int error = FALSE;
12660 if (argvars[0].v_type == VAR_LIST)
12662 list_T *l;
12663 listitem_T *li;
12665 l = argvars[0].vval.v_list;
12666 if (l != NULL)
12668 li = l->lv_first;
12669 if (li != NULL)
12671 n = get_tv_number_chk(&li->li_tv, &error);
12672 for (;;)
12674 li = li->li_next;
12675 if (li == NULL)
12676 break;
12677 i = get_tv_number_chk(&li->li_tv, &error);
12678 if (domax ? i > n : i < n)
12679 n = i;
12684 else if (argvars[0].v_type == VAR_DICT)
12686 dict_T *d;
12687 int first = TRUE;
12688 hashitem_T *hi;
12689 int todo;
12691 d = argvars[0].vval.v_dict;
12692 if (d != NULL)
12694 todo = (int)d->dv_hashtab.ht_used;
12695 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12697 if (!HASHITEM_EMPTY(hi))
12699 --todo;
12700 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
12701 if (first)
12703 n = i;
12704 first = FALSE;
12706 else if (domax ? i > n : i < n)
12707 n = i;
12712 else
12713 EMSG(_(e_listdictarg));
12714 rettv->vval.v_number = error ? 0 : n;
12718 * "max()" function
12720 static void
12721 f_max(argvars, rettv)
12722 typval_T *argvars;
12723 typval_T *rettv;
12725 max_min(argvars, rettv, TRUE);
12729 * "min()" function
12731 static void
12732 f_min(argvars, rettv)
12733 typval_T *argvars;
12734 typval_T *rettv;
12736 max_min(argvars, rettv, FALSE);
12739 static int mkdir_recurse __ARGS((char_u *dir, int prot));
12742 * Create the directory in which "dir" is located, and higher levels when
12743 * needed.
12745 static int
12746 mkdir_recurse(dir, prot)
12747 char_u *dir;
12748 int prot;
12750 char_u *p;
12751 char_u *updir;
12752 int r = FAIL;
12754 /* Get end of directory name in "dir".
12755 * We're done when it's "/" or "c:/". */
12756 p = gettail_sep(dir);
12757 if (p <= get_past_head(dir))
12758 return OK;
12760 /* If the directory exists we're done. Otherwise: create it.*/
12761 updir = vim_strnsave(dir, (int)(p - dir));
12762 if (updir == NULL)
12763 return FAIL;
12764 if (mch_isdir(updir))
12765 r = OK;
12766 else if (mkdir_recurse(updir, prot) == OK)
12767 r = vim_mkdir_emsg(updir, prot);
12768 vim_free(updir);
12769 return r;
12772 #ifdef vim_mkdir
12774 * "mkdir()" function
12776 static void
12777 f_mkdir(argvars, rettv)
12778 typval_T *argvars;
12779 typval_T *rettv;
12781 char_u *dir;
12782 char_u buf[NUMBUFLEN];
12783 int prot = 0755;
12785 rettv->vval.v_number = FAIL;
12786 if (check_restricted() || check_secure())
12787 return;
12789 dir = get_tv_string_buf(&argvars[0], buf);
12790 if (argvars[1].v_type != VAR_UNKNOWN)
12792 if (argvars[2].v_type != VAR_UNKNOWN)
12793 prot = get_tv_number_chk(&argvars[2], NULL);
12794 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
12795 mkdir_recurse(dir, prot);
12797 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
12799 #endif
12802 * "mode()" function
12804 /*ARGSUSED*/
12805 static void
12806 f_mode(argvars, rettv)
12807 typval_T *argvars;
12808 typval_T *rettv;
12810 char_u buf[2];
12812 #ifdef FEAT_VISUAL
12813 if (VIsual_active)
12815 if (VIsual_select)
12816 buf[0] = VIsual_mode + 's' - 'v';
12817 else
12818 buf[0] = VIsual_mode;
12820 else
12821 #endif
12822 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE)
12823 buf[0] = 'r';
12824 else if (State & INSERT)
12826 if (State & REPLACE_FLAG)
12827 buf[0] = 'R';
12828 else
12829 buf[0] = 'i';
12831 else if (State & CMDLINE)
12832 buf[0] = 'c';
12833 else
12834 buf[0] = 'n';
12836 buf[1] = NUL;
12837 rettv->vval.v_string = vim_strsave(buf);
12838 rettv->v_type = VAR_STRING;
12842 * "nextnonblank()" function
12844 static void
12845 f_nextnonblank(argvars, rettv)
12846 typval_T *argvars;
12847 typval_T *rettv;
12849 linenr_T lnum;
12851 for (lnum = get_tv_lnum(argvars); ; ++lnum)
12853 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
12855 lnum = 0;
12856 break;
12858 if (*skipwhite(ml_get(lnum)) != NUL)
12859 break;
12861 rettv->vval.v_number = lnum;
12865 * "nr2char()" function
12867 static void
12868 f_nr2char(argvars, rettv)
12869 typval_T *argvars;
12870 typval_T *rettv;
12872 char_u buf[NUMBUFLEN];
12874 #ifdef FEAT_MBYTE
12875 if (has_mbyte)
12876 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
12877 else
12878 #endif
12880 buf[0] = (char_u)get_tv_number(&argvars[0]);
12881 buf[1] = NUL;
12883 rettv->v_type = VAR_STRING;
12884 rettv->vval.v_string = vim_strsave(buf);
12888 * "pathshorten()" function
12890 static void
12891 f_pathshorten(argvars, rettv)
12892 typval_T *argvars;
12893 typval_T *rettv;
12895 char_u *p;
12897 rettv->v_type = VAR_STRING;
12898 p = get_tv_string_chk(&argvars[0]);
12899 if (p == NULL)
12900 rettv->vval.v_string = NULL;
12901 else
12903 p = vim_strsave(p);
12904 rettv->vval.v_string = p;
12905 if (p != NULL)
12906 shorten_dir(p);
12911 * "prevnonblank()" function
12913 static void
12914 f_prevnonblank(argvars, rettv)
12915 typval_T *argvars;
12916 typval_T *rettv;
12918 linenr_T lnum;
12920 lnum = get_tv_lnum(argvars);
12921 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
12922 lnum = 0;
12923 else
12924 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
12925 --lnum;
12926 rettv->vval.v_number = lnum;
12929 #ifdef HAVE_STDARG_H
12930 /* This dummy va_list is here because:
12931 * - passing a NULL pointer doesn't work when va_list isn't a pointer
12932 * - locally in the function results in a "used before set" warning
12933 * - using va_start() to initialize it gives "function with fixed args" error */
12934 static va_list ap;
12935 #endif
12938 * "printf()" function
12940 static void
12941 f_printf(argvars, rettv)
12942 typval_T *argvars;
12943 typval_T *rettv;
12945 rettv->v_type = VAR_STRING;
12946 rettv->vval.v_string = NULL;
12947 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
12949 char_u buf[NUMBUFLEN];
12950 int len;
12951 char_u *s;
12952 int saved_did_emsg = did_emsg;
12953 char *fmt;
12955 /* Get the required length, allocate the buffer and do it for real. */
12956 did_emsg = FALSE;
12957 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
12958 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
12959 if (!did_emsg)
12961 s = alloc(len + 1);
12962 if (s != NULL)
12964 rettv->vval.v_string = s;
12965 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
12968 did_emsg |= saved_did_emsg;
12970 #endif
12974 * "pumvisible()" function
12976 /*ARGSUSED*/
12977 static void
12978 f_pumvisible(argvars, rettv)
12979 typval_T *argvars;
12980 typval_T *rettv;
12982 rettv->vval.v_number = 0;
12983 #ifdef FEAT_INS_EXPAND
12984 if (pum_visible())
12985 rettv->vval.v_number = 1;
12986 #endif
12990 * "range()" function
12992 static void
12993 f_range(argvars, rettv)
12994 typval_T *argvars;
12995 typval_T *rettv;
12997 long start;
12998 long end;
12999 long stride = 1;
13000 long i;
13001 int error = FALSE;
13003 start = get_tv_number_chk(&argvars[0], &error);
13004 if (argvars[1].v_type == VAR_UNKNOWN)
13006 end = start - 1;
13007 start = 0;
13009 else
13011 end = get_tv_number_chk(&argvars[1], &error);
13012 if (argvars[2].v_type != VAR_UNKNOWN)
13013 stride = get_tv_number_chk(&argvars[2], &error);
13016 rettv->vval.v_number = 0;
13017 if (error)
13018 return; /* type error; errmsg already given */
13019 if (stride == 0)
13020 EMSG(_("E726: Stride is zero"));
13021 else if (stride > 0 ? end + 1 < start : end - 1 > start)
13022 EMSG(_("E727: Start past end"));
13023 else
13025 if (rettv_list_alloc(rettv) == OK)
13026 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
13027 if (list_append_number(rettv->vval.v_list,
13028 (varnumber_T)i) == FAIL)
13029 break;
13034 * "readfile()" function
13036 static void
13037 f_readfile(argvars, rettv)
13038 typval_T *argvars;
13039 typval_T *rettv;
13041 int binary = FALSE;
13042 char_u *fname;
13043 FILE *fd;
13044 listitem_T *li;
13045 #define FREAD_SIZE 200 /* optimized for text lines */
13046 char_u buf[FREAD_SIZE];
13047 int readlen; /* size of last fread() */
13048 int buflen; /* nr of valid chars in buf[] */
13049 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
13050 int tolist; /* first byte in buf[] still to be put in list */
13051 int chop; /* how many CR to chop off */
13052 char_u *prev = NULL; /* previously read bytes, if any */
13053 int prevlen = 0; /* length of "prev" if not NULL */
13054 char_u *s;
13055 int len;
13056 long maxline = MAXLNUM;
13057 long cnt = 0;
13059 if (argvars[1].v_type != VAR_UNKNOWN)
13061 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
13062 binary = TRUE;
13063 if (argvars[2].v_type != VAR_UNKNOWN)
13064 maxline = get_tv_number(&argvars[2]);
13067 if (rettv_list_alloc(rettv) == FAIL)
13068 return;
13070 /* Always open the file in binary mode, library functions have a mind of
13071 * their own about CR-LF conversion. */
13072 fname = get_tv_string(&argvars[0]);
13073 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
13075 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
13076 return;
13079 filtd = 0;
13080 while (cnt < maxline || maxline < 0)
13082 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
13083 buflen = filtd + readlen;
13084 tolist = 0;
13085 for ( ; filtd < buflen || readlen <= 0; ++filtd)
13087 if (buf[filtd] == '\n' || readlen <= 0)
13089 /* Only when in binary mode add an empty list item when the
13090 * last line ends in a '\n'. */
13091 if (!binary && readlen == 0 && filtd == 0)
13092 break;
13094 /* Found end-of-line or end-of-file: add a text line to the
13095 * list. */
13096 chop = 0;
13097 if (!binary)
13098 while (filtd - chop - 1 >= tolist
13099 && buf[filtd - chop - 1] == '\r')
13100 ++chop;
13101 len = filtd - tolist - chop;
13102 if (prev == NULL)
13103 s = vim_strnsave(buf + tolist, len);
13104 else
13106 s = alloc((unsigned)(prevlen + len + 1));
13107 if (s != NULL)
13109 mch_memmove(s, prev, prevlen);
13110 vim_free(prev);
13111 prev = NULL;
13112 mch_memmove(s + prevlen, buf + tolist, len);
13113 s[prevlen + len] = NUL;
13116 tolist = filtd + 1;
13118 li = listitem_alloc();
13119 if (li == NULL)
13121 vim_free(s);
13122 break;
13124 li->li_tv.v_type = VAR_STRING;
13125 li->li_tv.v_lock = 0;
13126 li->li_tv.vval.v_string = s;
13127 list_append(rettv->vval.v_list, li);
13129 if (++cnt >= maxline && maxline >= 0)
13130 break;
13131 if (readlen <= 0)
13132 break;
13134 else if (buf[filtd] == NUL)
13135 buf[filtd] = '\n';
13137 if (readlen <= 0)
13138 break;
13140 if (tolist == 0)
13142 /* "buf" is full, need to move text to an allocated buffer */
13143 if (prev == NULL)
13145 prev = vim_strnsave(buf, buflen);
13146 prevlen = buflen;
13148 else
13150 s = alloc((unsigned)(prevlen + buflen));
13151 if (s != NULL)
13153 mch_memmove(s, prev, prevlen);
13154 mch_memmove(s + prevlen, buf, buflen);
13155 vim_free(prev);
13156 prev = s;
13157 prevlen += buflen;
13160 filtd = 0;
13162 else
13164 mch_memmove(buf, buf + tolist, buflen - tolist);
13165 filtd -= tolist;
13170 * For a negative line count use only the lines at the end of the file,
13171 * free the rest.
13173 if (maxline < 0)
13174 while (cnt > -maxline)
13176 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
13177 --cnt;
13180 vim_free(prev);
13181 fclose(fd);
13184 #if defined(FEAT_RELTIME)
13185 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
13188 * Convert a List to proftime_T.
13189 * Return FAIL when there is something wrong.
13191 static int
13192 list2proftime(arg, tm)
13193 typval_T *arg;
13194 proftime_T *tm;
13196 long n1, n2;
13197 int error = FALSE;
13199 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
13200 || arg->vval.v_list->lv_len != 2)
13201 return FAIL;
13202 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
13203 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
13204 # ifdef WIN3264
13205 tm->HighPart = n1;
13206 tm->LowPart = n2;
13207 # else
13208 tm->tv_sec = n1;
13209 tm->tv_usec = n2;
13210 # endif
13211 return error ? FAIL : OK;
13213 #endif /* FEAT_RELTIME */
13216 * "reltime()" function
13218 static void
13219 f_reltime(argvars, rettv)
13220 typval_T *argvars;
13221 typval_T *rettv;
13223 #ifdef FEAT_RELTIME
13224 proftime_T res;
13225 proftime_T start;
13227 if (argvars[0].v_type == VAR_UNKNOWN)
13229 /* No arguments: get current time. */
13230 profile_start(&res);
13232 else if (argvars[1].v_type == VAR_UNKNOWN)
13234 if (list2proftime(&argvars[0], &res) == FAIL)
13235 return;
13236 profile_end(&res);
13238 else
13240 /* Two arguments: compute the difference. */
13241 if (list2proftime(&argvars[0], &start) == FAIL
13242 || list2proftime(&argvars[1], &res) == FAIL)
13243 return;
13244 profile_sub(&res, &start);
13247 if (rettv_list_alloc(rettv) == OK)
13249 long n1, n2;
13251 # ifdef WIN3264
13252 n1 = res.HighPart;
13253 n2 = res.LowPart;
13254 # else
13255 n1 = res.tv_sec;
13256 n2 = res.tv_usec;
13257 # endif
13258 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
13259 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
13261 #endif
13265 * "reltimestr()" function
13267 static void
13268 f_reltimestr(argvars, rettv)
13269 typval_T *argvars;
13270 typval_T *rettv;
13272 #ifdef FEAT_RELTIME
13273 proftime_T tm;
13274 #endif
13276 rettv->v_type = VAR_STRING;
13277 rettv->vval.v_string = NULL;
13278 #ifdef FEAT_RELTIME
13279 if (list2proftime(&argvars[0], &tm) == OK)
13280 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
13281 #endif
13284 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
13285 static void make_connection __ARGS((void));
13286 static int check_connection __ARGS((void));
13288 static void
13289 make_connection()
13291 if (X_DISPLAY == NULL
13292 # ifdef FEAT_GUI
13293 && !gui.in_use
13294 # endif
13297 x_force_connect = TRUE;
13298 setup_term_clip();
13299 x_force_connect = FALSE;
13303 static int
13304 check_connection()
13306 make_connection();
13307 if (X_DISPLAY == NULL)
13309 EMSG(_("E240: No connection to Vim server"));
13310 return FAIL;
13312 return OK;
13314 #endif
13316 #ifdef FEAT_CLIENTSERVER
13317 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
13319 static void
13320 remote_common(argvars, rettv, expr)
13321 typval_T *argvars;
13322 typval_T *rettv;
13323 int expr;
13325 char_u *server_name;
13326 char_u *keys;
13327 char_u *r = NULL;
13328 char_u buf[NUMBUFLEN];
13329 # ifdef WIN32
13330 HWND w;
13331 # else
13332 Window w;
13333 # endif
13335 if (check_restricted() || check_secure())
13336 return;
13338 # ifdef FEAT_X11
13339 if (check_connection() == FAIL)
13340 return;
13341 # endif
13343 server_name = get_tv_string_chk(&argvars[0]);
13344 if (server_name == NULL)
13345 return; /* type error; errmsg already given */
13346 keys = get_tv_string_buf(&argvars[1], buf);
13347 # ifdef WIN32
13348 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
13349 # else
13350 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
13351 < 0)
13352 # endif
13354 if (r != NULL)
13355 EMSG(r); /* sending worked but evaluation failed */
13356 else
13357 EMSG2(_("E241: Unable to send to %s"), server_name);
13358 return;
13361 rettv->vval.v_string = r;
13363 if (argvars[2].v_type != VAR_UNKNOWN)
13365 dictitem_T v;
13366 char_u str[30];
13367 char_u *idvar;
13369 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
13370 v.di_tv.v_type = VAR_STRING;
13371 v.di_tv.vval.v_string = vim_strsave(str);
13372 idvar = get_tv_string_chk(&argvars[2]);
13373 if (idvar != NULL)
13374 set_var(idvar, &v.di_tv, FALSE);
13375 vim_free(v.di_tv.vval.v_string);
13378 #endif
13381 * "remote_expr()" function
13383 /*ARGSUSED*/
13384 static void
13385 f_remote_expr(argvars, rettv)
13386 typval_T *argvars;
13387 typval_T *rettv;
13389 rettv->v_type = VAR_STRING;
13390 rettv->vval.v_string = NULL;
13391 #ifdef FEAT_CLIENTSERVER
13392 remote_common(argvars, rettv, TRUE);
13393 #endif
13397 * "remote_foreground()" function
13399 /*ARGSUSED*/
13400 static void
13401 f_remote_foreground(argvars, rettv)
13402 typval_T *argvars;
13403 typval_T *rettv;
13405 rettv->vval.v_number = 0;
13406 #ifdef FEAT_CLIENTSERVER
13407 # ifdef WIN32
13408 /* On Win32 it's done in this application. */
13410 char_u *server_name = get_tv_string_chk(&argvars[0]);
13412 if (server_name != NULL)
13413 serverForeground(server_name);
13415 # else
13416 /* Send a foreground() expression to the server. */
13417 argvars[1].v_type = VAR_STRING;
13418 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
13419 argvars[2].v_type = VAR_UNKNOWN;
13420 remote_common(argvars, rettv, TRUE);
13421 vim_free(argvars[1].vval.v_string);
13422 # endif
13423 #endif
13426 /*ARGSUSED*/
13427 static void
13428 f_remote_peek(argvars, rettv)
13429 typval_T *argvars;
13430 typval_T *rettv;
13432 #ifdef FEAT_CLIENTSERVER
13433 dictitem_T v;
13434 char_u *s = NULL;
13435 # ifdef WIN32
13436 long_u n = 0;
13437 # endif
13438 char_u *serverid;
13440 if (check_restricted() || check_secure())
13442 rettv->vval.v_number = -1;
13443 return;
13445 serverid = get_tv_string_chk(&argvars[0]);
13446 if (serverid == NULL)
13448 rettv->vval.v_number = -1;
13449 return; /* type error; errmsg already given */
13451 # ifdef WIN32
13452 sscanf(serverid, SCANF_HEX_LONG_U, &n);
13453 if (n == 0)
13454 rettv->vval.v_number = -1;
13455 else
13457 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
13458 rettv->vval.v_number = (s != NULL);
13460 # else
13461 rettv->vval.v_number = 0;
13462 if (check_connection() == FAIL)
13463 return;
13465 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
13466 serverStrToWin(serverid), &s);
13467 # endif
13469 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
13471 char_u *retvar;
13473 v.di_tv.v_type = VAR_STRING;
13474 v.di_tv.vval.v_string = vim_strsave(s);
13475 retvar = get_tv_string_chk(&argvars[1]);
13476 if (retvar != NULL)
13477 set_var(retvar, &v.di_tv, FALSE);
13478 vim_free(v.di_tv.vval.v_string);
13480 #else
13481 rettv->vval.v_number = -1;
13482 #endif
13485 /*ARGSUSED*/
13486 static void
13487 f_remote_read(argvars, rettv)
13488 typval_T *argvars;
13489 typval_T *rettv;
13491 char_u *r = NULL;
13493 #ifdef FEAT_CLIENTSERVER
13494 char_u *serverid = get_tv_string_chk(&argvars[0]);
13496 if (serverid != NULL && !check_restricted() && !check_secure())
13498 # ifdef WIN32
13499 /* The server's HWND is encoded in the 'id' parameter */
13500 long_u n = 0;
13502 sscanf(serverid, SCANF_HEX_LONG_U, &n);
13503 if (n != 0)
13504 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
13505 if (r == NULL)
13506 # else
13507 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
13508 serverStrToWin(serverid), &r, FALSE) < 0)
13509 # endif
13510 EMSG(_("E277: Unable to read a server reply"));
13512 #endif
13513 rettv->v_type = VAR_STRING;
13514 rettv->vval.v_string = r;
13518 * "remote_send()" function
13520 /*ARGSUSED*/
13521 static void
13522 f_remote_send(argvars, rettv)
13523 typval_T *argvars;
13524 typval_T *rettv;
13526 rettv->v_type = VAR_STRING;
13527 rettv->vval.v_string = NULL;
13528 #ifdef FEAT_CLIENTSERVER
13529 remote_common(argvars, rettv, FALSE);
13530 #endif
13534 * "remove()" function
13536 static void
13537 f_remove(argvars, rettv)
13538 typval_T *argvars;
13539 typval_T *rettv;
13541 list_T *l;
13542 listitem_T *item, *item2;
13543 listitem_T *li;
13544 long idx;
13545 long end;
13546 char_u *key;
13547 dict_T *d;
13548 dictitem_T *di;
13550 rettv->vval.v_number = 0;
13551 if (argvars[0].v_type == VAR_DICT)
13553 if (argvars[2].v_type != VAR_UNKNOWN)
13554 EMSG2(_(e_toomanyarg), "remove()");
13555 else if ((d = argvars[0].vval.v_dict) != NULL
13556 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
13558 key = get_tv_string_chk(&argvars[1]);
13559 if (key != NULL)
13561 di = dict_find(d, key, -1);
13562 if (di == NULL)
13563 EMSG2(_(e_dictkey), key);
13564 else
13566 *rettv = di->di_tv;
13567 init_tv(&di->di_tv);
13568 dictitem_remove(d, di);
13573 else if (argvars[0].v_type != VAR_LIST)
13574 EMSG2(_(e_listdictarg), "remove()");
13575 else if ((l = argvars[0].vval.v_list) != NULL
13576 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
13578 int error = FALSE;
13580 idx = get_tv_number_chk(&argvars[1], &error);
13581 if (error)
13582 ; /* type error: do nothing, errmsg already given */
13583 else if ((item = list_find(l, idx)) == NULL)
13584 EMSGN(_(e_listidx), idx);
13585 else
13587 if (argvars[2].v_type == VAR_UNKNOWN)
13589 /* Remove one item, return its value. */
13590 list_remove(l, item, item);
13591 *rettv = item->li_tv;
13592 vim_free(item);
13594 else
13596 /* Remove range of items, return list with values. */
13597 end = get_tv_number_chk(&argvars[2], &error);
13598 if (error)
13599 ; /* type error: do nothing */
13600 else if ((item2 = list_find(l, end)) == NULL)
13601 EMSGN(_(e_listidx), end);
13602 else
13604 int cnt = 0;
13606 for (li = item; li != NULL; li = li->li_next)
13608 ++cnt;
13609 if (li == item2)
13610 break;
13612 if (li == NULL) /* didn't find "item2" after "item" */
13613 EMSG(_(e_invrange));
13614 else
13616 list_remove(l, item, item2);
13617 if (rettv_list_alloc(rettv) == OK)
13619 l = rettv->vval.v_list;
13620 l->lv_first = item;
13621 l->lv_last = item2;
13622 item->li_prev = NULL;
13623 item2->li_next = NULL;
13624 l->lv_len = cnt;
13634 * "rename({from}, {to})" function
13636 static void
13637 f_rename(argvars, rettv)
13638 typval_T *argvars;
13639 typval_T *rettv;
13641 char_u buf[NUMBUFLEN];
13643 if (check_restricted() || check_secure())
13644 rettv->vval.v_number = -1;
13645 else
13646 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
13647 get_tv_string_buf(&argvars[1], buf));
13651 * "repeat()" function
13653 /*ARGSUSED*/
13654 static void
13655 f_repeat(argvars, rettv)
13656 typval_T *argvars;
13657 typval_T *rettv;
13659 char_u *p;
13660 int n;
13661 int slen;
13662 int len;
13663 char_u *r;
13664 int i;
13666 n = get_tv_number(&argvars[1]);
13667 if (argvars[0].v_type == VAR_LIST)
13669 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
13670 while (n-- > 0)
13671 if (list_extend(rettv->vval.v_list,
13672 argvars[0].vval.v_list, NULL) == FAIL)
13673 break;
13675 else
13677 p = get_tv_string(&argvars[0]);
13678 rettv->v_type = VAR_STRING;
13679 rettv->vval.v_string = NULL;
13681 slen = (int)STRLEN(p);
13682 len = slen * n;
13683 if (len <= 0)
13684 return;
13686 r = alloc(len + 1);
13687 if (r != NULL)
13689 for (i = 0; i < n; i++)
13690 mch_memmove(r + i * slen, p, (size_t)slen);
13691 r[len] = NUL;
13694 rettv->vval.v_string = r;
13699 * "resolve()" function
13701 static void
13702 f_resolve(argvars, rettv)
13703 typval_T *argvars;
13704 typval_T *rettv;
13706 char_u *p;
13708 p = get_tv_string(&argvars[0]);
13709 #ifdef FEAT_SHORTCUT
13711 char_u *v = NULL;
13713 v = mch_resolve_shortcut(p);
13714 if (v != NULL)
13715 rettv->vval.v_string = v;
13716 else
13717 rettv->vval.v_string = vim_strsave(p);
13719 #else
13720 # ifdef HAVE_READLINK
13722 char_u buf[MAXPATHL + 1];
13723 char_u *cpy;
13724 int len;
13725 char_u *remain = NULL;
13726 char_u *q;
13727 int is_relative_to_current = FALSE;
13728 int has_trailing_pathsep = FALSE;
13729 int limit = 100;
13731 p = vim_strsave(p);
13733 if (p[0] == '.' && (vim_ispathsep(p[1])
13734 || (p[1] == '.' && (vim_ispathsep(p[2])))))
13735 is_relative_to_current = TRUE;
13737 len = STRLEN(p);
13738 if (len > 0 && after_pathsep(p, p + len))
13739 has_trailing_pathsep = TRUE;
13741 q = getnextcomp(p);
13742 if (*q != NUL)
13744 /* Separate the first path component in "p", and keep the
13745 * remainder (beginning with the path separator). */
13746 remain = vim_strsave(q - 1);
13747 q[-1] = NUL;
13750 for (;;)
13752 for (;;)
13754 len = readlink((char *)p, (char *)buf, MAXPATHL);
13755 if (len <= 0)
13756 break;
13757 buf[len] = NUL;
13759 if (limit-- == 0)
13761 vim_free(p);
13762 vim_free(remain);
13763 EMSG(_("E655: Too many symbolic links (cycle?)"));
13764 rettv->vval.v_string = NULL;
13765 goto fail;
13768 /* Ensure that the result will have a trailing path separator
13769 * if the argument has one. */
13770 if (remain == NULL && has_trailing_pathsep)
13771 add_pathsep(buf);
13773 /* Separate the first path component in the link value and
13774 * concatenate the remainders. */
13775 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
13776 if (*q != NUL)
13778 if (remain == NULL)
13779 remain = vim_strsave(q - 1);
13780 else
13782 cpy = concat_str(q - 1, remain);
13783 if (cpy != NULL)
13785 vim_free(remain);
13786 remain = cpy;
13789 q[-1] = NUL;
13792 q = gettail(p);
13793 if (q > p && *q == NUL)
13795 /* Ignore trailing path separator. */
13796 q[-1] = NUL;
13797 q = gettail(p);
13799 if (q > p && !mch_isFullName(buf))
13801 /* symlink is relative to directory of argument */
13802 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
13803 if (cpy != NULL)
13805 STRCPY(cpy, p);
13806 STRCPY(gettail(cpy), buf);
13807 vim_free(p);
13808 p = cpy;
13811 else
13813 vim_free(p);
13814 p = vim_strsave(buf);
13818 if (remain == NULL)
13819 break;
13821 /* Append the first path component of "remain" to "p". */
13822 q = getnextcomp(remain + 1);
13823 len = q - remain - (*q != NUL);
13824 cpy = vim_strnsave(p, STRLEN(p) + len);
13825 if (cpy != NULL)
13827 STRNCAT(cpy, remain, len);
13828 vim_free(p);
13829 p = cpy;
13831 /* Shorten "remain". */
13832 if (*q != NUL)
13833 mch_memmove(remain, q - 1, STRLEN(q - 1) + 1);
13834 else
13836 vim_free(remain);
13837 remain = NULL;
13841 /* If the result is a relative path name, make it explicitly relative to
13842 * the current directory if and only if the argument had this form. */
13843 if (!vim_ispathsep(*p))
13845 if (is_relative_to_current
13846 && *p != NUL
13847 && !(p[0] == '.'
13848 && (p[1] == NUL
13849 || vim_ispathsep(p[1])
13850 || (p[1] == '.'
13851 && (p[2] == NUL
13852 || vim_ispathsep(p[2]))))))
13854 /* Prepend "./". */
13855 cpy = concat_str((char_u *)"./", p);
13856 if (cpy != NULL)
13858 vim_free(p);
13859 p = cpy;
13862 else if (!is_relative_to_current)
13864 /* Strip leading "./". */
13865 q = p;
13866 while (q[0] == '.' && vim_ispathsep(q[1]))
13867 q += 2;
13868 if (q > p)
13869 mch_memmove(p, p + 2, STRLEN(p + 2) + (size_t)1);
13873 /* Ensure that the result will have no trailing path separator
13874 * if the argument had none. But keep "/" or "//". */
13875 if (!has_trailing_pathsep)
13877 q = p + STRLEN(p);
13878 if (after_pathsep(p, q))
13879 *gettail_sep(p) = NUL;
13882 rettv->vval.v_string = p;
13884 # else
13885 rettv->vval.v_string = vim_strsave(p);
13886 # endif
13887 #endif
13889 simplify_filename(rettv->vval.v_string);
13891 #ifdef HAVE_READLINK
13892 fail:
13893 #endif
13894 rettv->v_type = VAR_STRING;
13898 * "reverse({list})" function
13900 static void
13901 f_reverse(argvars, rettv)
13902 typval_T *argvars;
13903 typval_T *rettv;
13905 list_T *l;
13906 listitem_T *li, *ni;
13908 rettv->vval.v_number = 0;
13909 if (argvars[0].v_type != VAR_LIST)
13910 EMSG2(_(e_listarg), "reverse()");
13911 else if ((l = argvars[0].vval.v_list) != NULL
13912 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
13914 li = l->lv_last;
13915 l->lv_first = l->lv_last = NULL;
13916 l->lv_len = 0;
13917 while (li != NULL)
13919 ni = li->li_prev;
13920 list_append(l, li);
13921 li = ni;
13923 rettv->vval.v_list = l;
13924 rettv->v_type = VAR_LIST;
13925 ++l->lv_refcount;
13929 #define SP_NOMOVE 0x01 /* don't move cursor */
13930 #define SP_REPEAT 0x02 /* repeat to find outer pair */
13931 #define SP_RETCOUNT 0x04 /* return matchcount */
13932 #define SP_SETPCMARK 0x08 /* set previous context mark */
13933 #define SP_START 0x10 /* accept match at start position */
13934 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
13935 #define SP_END 0x40 /* leave cursor at end of match */
13937 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
13940 * Get flags for a search function.
13941 * Possibly sets "p_ws".
13942 * Returns BACKWARD, FORWARD or zero (for an error).
13944 static int
13945 get_search_arg(varp, flagsp)
13946 typval_T *varp;
13947 int *flagsp;
13949 int dir = FORWARD;
13950 char_u *flags;
13951 char_u nbuf[NUMBUFLEN];
13952 int mask;
13954 if (varp->v_type != VAR_UNKNOWN)
13956 flags = get_tv_string_buf_chk(varp, nbuf);
13957 if (flags == NULL)
13958 return 0; /* type error; errmsg already given */
13959 while (*flags != NUL)
13961 switch (*flags)
13963 case 'b': dir = BACKWARD; break;
13964 case 'w': p_ws = TRUE; break;
13965 case 'W': p_ws = FALSE; break;
13966 default: mask = 0;
13967 if (flagsp != NULL)
13968 switch (*flags)
13970 case 'c': mask = SP_START; break;
13971 case 'e': mask = SP_END; break;
13972 case 'm': mask = SP_RETCOUNT; break;
13973 case 'n': mask = SP_NOMOVE; break;
13974 case 'p': mask = SP_SUBPAT; break;
13975 case 'r': mask = SP_REPEAT; break;
13976 case 's': mask = SP_SETPCMARK; break;
13978 if (mask == 0)
13980 EMSG2(_(e_invarg2), flags);
13981 dir = 0;
13983 else
13984 *flagsp |= mask;
13986 if (dir == 0)
13987 break;
13988 ++flags;
13991 return dir;
13995 * Shared by search() and searchpos() functions
13997 static int
13998 search_cmn(argvars, match_pos, flagsp)
13999 typval_T *argvars;
14000 pos_T *match_pos;
14001 int *flagsp;
14003 int flags;
14004 char_u *pat;
14005 pos_T pos;
14006 pos_T save_cursor;
14007 int save_p_ws = p_ws;
14008 int dir;
14009 int retval = 0; /* default: FAIL */
14010 long lnum_stop = 0;
14011 int options = SEARCH_KEEP;
14012 int subpatnum;
14014 pat = get_tv_string(&argvars[0]);
14015 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
14016 if (dir == 0)
14017 goto theend;
14018 flags = *flagsp;
14019 if (flags & SP_START)
14020 options |= SEARCH_START;
14021 if (flags & SP_END)
14022 options |= SEARCH_END;
14024 /* Optional extra argument: line number to stop searching. */
14025 if (argvars[1].v_type != VAR_UNKNOWN
14026 && argvars[2].v_type != VAR_UNKNOWN)
14028 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
14029 if (lnum_stop < 0)
14030 goto theend;
14034 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
14035 * Check to make sure only those flags are set.
14036 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
14037 * flags cannot be set. Check for that condition also.
14039 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
14040 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14042 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
14043 goto theend;
14046 pos = save_cursor = curwin->w_cursor;
14047 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14048 options, RE_SEARCH, (linenr_T)lnum_stop);
14049 if (subpatnum != FAIL)
14051 if (flags & SP_SUBPAT)
14052 retval = subpatnum;
14053 else
14054 retval = pos.lnum;
14055 if (flags & SP_SETPCMARK)
14056 setpcmark();
14057 curwin->w_cursor = pos;
14058 if (match_pos != NULL)
14060 /* Store the match cursor position */
14061 match_pos->lnum = pos.lnum;
14062 match_pos->col = pos.col + 1;
14064 /* "/$" will put the cursor after the end of the line, may need to
14065 * correct that here */
14066 check_cursor();
14069 /* If 'n' flag is used: restore cursor position. */
14070 if (flags & SP_NOMOVE)
14071 curwin->w_cursor = save_cursor;
14072 else
14073 curwin->w_set_curswant = TRUE;
14074 theend:
14075 p_ws = save_p_ws;
14077 return retval;
14081 * "search()" function
14083 static void
14084 f_search(argvars, rettv)
14085 typval_T *argvars;
14086 typval_T *rettv;
14088 int flags = 0;
14090 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
14094 * "searchdecl()" function
14096 static void
14097 f_searchdecl(argvars, rettv)
14098 typval_T *argvars;
14099 typval_T *rettv;
14101 int locally = 1;
14102 int thisblock = 0;
14103 int error = FALSE;
14104 char_u *name;
14106 rettv->vval.v_number = 1; /* default: FAIL */
14108 name = get_tv_string_chk(&argvars[0]);
14109 if (argvars[1].v_type != VAR_UNKNOWN)
14111 locally = get_tv_number_chk(&argvars[1], &error) == 0;
14112 if (!error && argvars[2].v_type != VAR_UNKNOWN)
14113 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
14115 if (!error && name != NULL)
14116 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
14117 locally, thisblock, SEARCH_KEEP) == FAIL;
14121 * Used by searchpair() and searchpairpos()
14123 static int
14124 searchpair_cmn(argvars, match_pos)
14125 typval_T *argvars;
14126 pos_T *match_pos;
14128 char_u *spat, *mpat, *epat;
14129 char_u *skip;
14130 int save_p_ws = p_ws;
14131 int dir;
14132 int flags = 0;
14133 char_u nbuf1[NUMBUFLEN];
14134 char_u nbuf2[NUMBUFLEN];
14135 char_u nbuf3[NUMBUFLEN];
14136 int retval = 0; /* default: FAIL */
14137 long lnum_stop = 0;
14139 /* Get the three pattern arguments: start, middle, end. */
14140 spat = get_tv_string_chk(&argvars[0]);
14141 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
14142 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
14143 if (spat == NULL || mpat == NULL || epat == NULL)
14144 goto theend; /* type error */
14146 /* Handle the optional fourth argument: flags */
14147 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
14148 if (dir == 0)
14149 goto theend;
14151 /* Don't accept SP_END or SP_SUBPAT.
14152 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
14154 if ((flags & (SP_END | SP_SUBPAT)) != 0
14155 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14157 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
14158 goto theend;
14161 /* Optional fifth argument: skip expression */
14162 if (argvars[3].v_type == VAR_UNKNOWN
14163 || argvars[4].v_type == VAR_UNKNOWN)
14164 skip = (char_u *)"";
14165 else
14167 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
14168 if (argvars[5].v_type != VAR_UNKNOWN)
14170 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
14171 if (lnum_stop < 0)
14172 goto theend;
14175 if (skip == NULL)
14176 goto theend; /* type error */
14178 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
14179 match_pos, lnum_stop);
14181 theend:
14182 p_ws = save_p_ws;
14184 return retval;
14188 * "searchpair()" function
14190 static void
14191 f_searchpair(argvars, rettv)
14192 typval_T *argvars;
14193 typval_T *rettv;
14195 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
14199 * "searchpairpos()" function
14201 static void
14202 f_searchpairpos(argvars, rettv)
14203 typval_T *argvars;
14204 typval_T *rettv;
14206 pos_T match_pos;
14207 int lnum = 0;
14208 int col = 0;
14210 rettv->vval.v_number = 0;
14212 if (rettv_list_alloc(rettv) == FAIL)
14213 return;
14215 if (searchpair_cmn(argvars, &match_pos) > 0)
14217 lnum = match_pos.lnum;
14218 col = match_pos.col;
14221 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14222 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14226 * Search for a start/middle/end thing.
14227 * Used by searchpair(), see its documentation for the details.
14228 * Returns 0 or -1 for no match,
14230 long
14231 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos, lnum_stop)
14232 char_u *spat; /* start pattern */
14233 char_u *mpat; /* middle pattern */
14234 char_u *epat; /* end pattern */
14235 int dir; /* BACKWARD or FORWARD */
14236 char_u *skip; /* skip expression */
14237 int flags; /* SP_SETPCMARK and other SP_ values */
14238 pos_T *match_pos;
14239 linenr_T lnum_stop; /* stop at this line if not zero */
14241 char_u *save_cpo;
14242 char_u *pat, *pat2 = NULL, *pat3 = NULL;
14243 long retval = 0;
14244 pos_T pos;
14245 pos_T firstpos;
14246 pos_T foundpos;
14247 pos_T save_cursor;
14248 pos_T save_pos;
14249 int n;
14250 int r;
14251 int nest = 1;
14252 int err;
14253 int options = SEARCH_KEEP;
14255 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
14256 save_cpo = p_cpo;
14257 p_cpo = (char_u *)"";
14259 /* Make two search patterns: start/end (pat2, for in nested pairs) and
14260 * start/middle/end (pat3, for the top pair). */
14261 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
14262 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
14263 if (pat2 == NULL || pat3 == NULL)
14264 goto theend;
14265 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
14266 if (*mpat == NUL)
14267 STRCPY(pat3, pat2);
14268 else
14269 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
14270 spat, epat, mpat);
14271 if (flags & SP_START)
14272 options |= SEARCH_START;
14274 save_cursor = curwin->w_cursor;
14275 pos = curwin->w_cursor;
14276 clearpos(&firstpos);
14277 clearpos(&foundpos);
14278 pat = pat3;
14279 for (;;)
14281 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14282 options, RE_SEARCH, lnum_stop);
14283 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
14284 /* didn't find it or found the first match again: FAIL */
14285 break;
14287 if (firstpos.lnum == 0)
14288 firstpos = pos;
14289 if (equalpos(pos, foundpos))
14291 /* Found the same position again. Can happen with a pattern that
14292 * has "\zs" at the end and searching backwards. Advance one
14293 * character and try again. */
14294 if (dir == BACKWARD)
14295 decl(&pos);
14296 else
14297 incl(&pos);
14299 foundpos = pos;
14301 /* If the skip pattern matches, ignore this match. */
14302 if (*skip != NUL)
14304 save_pos = curwin->w_cursor;
14305 curwin->w_cursor = pos;
14306 r = eval_to_bool(skip, &err, NULL, FALSE);
14307 curwin->w_cursor = save_pos;
14308 if (err)
14310 /* Evaluating {skip} caused an error, break here. */
14311 curwin->w_cursor = save_cursor;
14312 retval = -1;
14313 break;
14315 if (r)
14316 continue;
14319 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
14321 /* Found end when searching backwards or start when searching
14322 * forward: nested pair. */
14323 ++nest;
14324 pat = pat2; /* nested, don't search for middle */
14326 else
14328 /* Found end when searching forward or start when searching
14329 * backward: end of (nested) pair; or found middle in outer pair. */
14330 if (--nest == 1)
14331 pat = pat3; /* outer level, search for middle */
14334 if (nest == 0)
14336 /* Found the match: return matchcount or line number. */
14337 if (flags & SP_RETCOUNT)
14338 ++retval;
14339 else
14340 retval = pos.lnum;
14341 if (flags & SP_SETPCMARK)
14342 setpcmark();
14343 curwin->w_cursor = pos;
14344 if (!(flags & SP_REPEAT))
14345 break;
14346 nest = 1; /* search for next unmatched */
14350 if (match_pos != NULL)
14352 /* Store the match cursor position */
14353 match_pos->lnum = curwin->w_cursor.lnum;
14354 match_pos->col = curwin->w_cursor.col + 1;
14357 /* If 'n' flag is used or search failed: restore cursor position. */
14358 if ((flags & SP_NOMOVE) || retval == 0)
14359 curwin->w_cursor = save_cursor;
14361 theend:
14362 vim_free(pat2);
14363 vim_free(pat3);
14364 p_cpo = save_cpo;
14366 return retval;
14370 * "searchpos()" function
14372 static void
14373 f_searchpos(argvars, rettv)
14374 typval_T *argvars;
14375 typval_T *rettv;
14377 pos_T match_pos;
14378 int lnum = 0;
14379 int col = 0;
14380 int n;
14381 int flags = 0;
14383 rettv->vval.v_number = 0;
14385 if (rettv_list_alloc(rettv) == FAIL)
14386 return;
14388 n = search_cmn(argvars, &match_pos, &flags);
14389 if (n > 0)
14391 lnum = match_pos.lnum;
14392 col = match_pos.col;
14395 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14396 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14397 if (flags & SP_SUBPAT)
14398 list_append_number(rettv->vval.v_list, (varnumber_T)n);
14402 /*ARGSUSED*/
14403 static void
14404 f_server2client(argvars, rettv)
14405 typval_T *argvars;
14406 typval_T *rettv;
14408 #ifdef FEAT_CLIENTSERVER
14409 char_u buf[NUMBUFLEN];
14410 char_u *server = get_tv_string_chk(&argvars[0]);
14411 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
14413 rettv->vval.v_number = -1;
14414 if (server == NULL || reply == NULL)
14415 return;
14416 if (check_restricted() || check_secure())
14417 return;
14418 # ifdef FEAT_X11
14419 if (check_connection() == FAIL)
14420 return;
14421 # endif
14423 if (serverSendReply(server, reply) < 0)
14425 EMSG(_("E258: Unable to send to client"));
14426 return;
14428 rettv->vval.v_number = 0;
14429 #else
14430 rettv->vval.v_number = -1;
14431 #endif
14434 /*ARGSUSED*/
14435 static void
14436 f_serverlist(argvars, rettv)
14437 typval_T *argvars;
14438 typval_T *rettv;
14440 char_u *r = NULL;
14442 #ifdef FEAT_CLIENTSERVER
14443 # ifdef WIN32
14444 r = serverGetVimNames();
14445 # else
14446 make_connection();
14447 if (X_DISPLAY != NULL)
14448 r = serverGetVimNames(X_DISPLAY);
14449 # endif
14450 #endif
14451 rettv->v_type = VAR_STRING;
14452 rettv->vval.v_string = r;
14456 * "setbufvar()" function
14458 /*ARGSUSED*/
14459 static void
14460 f_setbufvar(argvars, rettv)
14461 typval_T *argvars;
14462 typval_T *rettv;
14464 buf_T *buf;
14465 aco_save_T aco;
14466 char_u *varname, *bufvarname;
14467 typval_T *varp;
14468 char_u nbuf[NUMBUFLEN];
14470 rettv->vval.v_number = 0;
14472 if (check_restricted() || check_secure())
14473 return;
14474 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
14475 varname = get_tv_string_chk(&argvars[1]);
14476 buf = get_buf_tv(&argvars[0]);
14477 varp = &argvars[2];
14479 if (buf != NULL && varname != NULL && varp != NULL)
14481 /* set curbuf to be our buf, temporarily */
14482 aucmd_prepbuf(&aco, buf);
14484 if (*varname == '&')
14486 long numval;
14487 char_u *strval;
14488 int error = FALSE;
14490 ++varname;
14491 numval = get_tv_number_chk(varp, &error);
14492 strval = get_tv_string_buf_chk(varp, nbuf);
14493 if (!error && strval != NULL)
14494 set_option_value(varname, numval, strval, OPT_LOCAL);
14496 else
14498 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
14499 if (bufvarname != NULL)
14501 STRCPY(bufvarname, "b:");
14502 STRCPY(bufvarname + 2, varname);
14503 set_var(bufvarname, varp, TRUE);
14504 vim_free(bufvarname);
14508 /* reset notion of buffer */
14509 aucmd_restbuf(&aco);
14514 * "setcmdpos()" function
14516 static void
14517 f_setcmdpos(argvars, rettv)
14518 typval_T *argvars;
14519 typval_T *rettv;
14521 int pos = (int)get_tv_number(&argvars[0]) - 1;
14523 if (pos >= 0)
14524 rettv->vval.v_number = set_cmdline_pos(pos);
14528 * "setline()" function
14530 static void
14531 f_setline(argvars, rettv)
14532 typval_T *argvars;
14533 typval_T *rettv;
14535 linenr_T lnum;
14536 char_u *line = NULL;
14537 list_T *l = NULL;
14538 listitem_T *li = NULL;
14539 long added = 0;
14540 linenr_T lcount = curbuf->b_ml.ml_line_count;
14542 lnum = get_tv_lnum(&argvars[0]);
14543 if (argvars[1].v_type == VAR_LIST)
14545 l = argvars[1].vval.v_list;
14546 li = l->lv_first;
14548 else
14549 line = get_tv_string_chk(&argvars[1]);
14551 rettv->vval.v_number = 0; /* OK */
14552 for (;;)
14554 if (l != NULL)
14556 /* list argument, get next string */
14557 if (li == NULL)
14558 break;
14559 line = get_tv_string_chk(&li->li_tv);
14560 li = li->li_next;
14563 rettv->vval.v_number = 1; /* FAIL */
14564 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
14565 break;
14566 if (lnum <= curbuf->b_ml.ml_line_count)
14568 /* existing line, replace it */
14569 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
14571 changed_bytes(lnum, 0);
14572 if (lnum == curwin->w_cursor.lnum)
14573 check_cursor_col();
14574 rettv->vval.v_number = 0; /* OK */
14577 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
14579 /* lnum is one past the last line, append the line */
14580 ++added;
14581 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
14582 rettv->vval.v_number = 0; /* OK */
14585 if (l == NULL) /* only one string argument */
14586 break;
14587 ++lnum;
14590 if (added > 0)
14591 appended_lines_mark(lcount, added);
14595 * Used by "setqflist()" and "setloclist()" functions
14597 /*ARGSUSED*/
14598 static void
14599 set_qf_ll_list(wp, list_arg, action_arg, rettv)
14600 win_T *wp;
14601 typval_T *list_arg;
14602 typval_T *action_arg;
14603 typval_T *rettv;
14605 #ifdef FEAT_QUICKFIX
14606 char_u *act;
14607 int action = ' ';
14608 #endif
14610 rettv->vval.v_number = -1;
14612 #ifdef FEAT_QUICKFIX
14613 if (list_arg->v_type != VAR_LIST)
14614 EMSG(_(e_listreq));
14615 else
14617 list_T *l = list_arg->vval.v_list;
14619 if (action_arg->v_type == VAR_STRING)
14621 act = get_tv_string_chk(action_arg);
14622 if (act == NULL)
14623 return; /* type error; errmsg already given */
14624 if (*act == 'a' || *act == 'r')
14625 action = *act;
14628 if (l != NULL && set_errorlist(wp, l, action) == OK)
14629 rettv->vval.v_number = 0;
14631 #endif
14635 * "setloclist()" function
14637 /*ARGSUSED*/
14638 static void
14639 f_setloclist(argvars, rettv)
14640 typval_T *argvars;
14641 typval_T *rettv;
14643 win_T *win;
14645 rettv->vval.v_number = -1;
14647 win = find_win_by_nr(&argvars[0], NULL);
14648 if (win != NULL)
14649 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
14653 * "setmatches()" function
14655 static void
14656 f_setmatches(argvars, rettv)
14657 typval_T *argvars;
14658 typval_T *rettv;
14660 #ifdef FEAT_SEARCH_EXTRA
14661 list_T *l;
14662 listitem_T *li;
14663 dict_T *d;
14665 rettv->vval.v_number = -1;
14666 if (argvars[0].v_type != VAR_LIST)
14668 EMSG(_(e_listreq));
14669 return;
14671 if ((l = argvars[0].vval.v_list) != NULL)
14674 /* To some extent make sure that we are dealing with a list from
14675 * "getmatches()". */
14676 li = l->lv_first;
14677 while (li != NULL)
14679 if (li->li_tv.v_type != VAR_DICT
14680 || (d = li->li_tv.vval.v_dict) == NULL)
14682 EMSG(_(e_invarg));
14683 return;
14685 if (!(dict_find(d, (char_u *)"group", -1) != NULL
14686 && dict_find(d, (char_u *)"pattern", -1) != NULL
14687 && dict_find(d, (char_u *)"priority", -1) != NULL
14688 && dict_find(d, (char_u *)"id", -1) != NULL))
14690 EMSG(_(e_invarg));
14691 return;
14693 li = li->li_next;
14696 clear_matches(curwin);
14697 li = l->lv_first;
14698 while (li != NULL)
14700 d = li->li_tv.vval.v_dict;
14701 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
14702 get_dict_string(d, (char_u *)"pattern", FALSE),
14703 (int)get_dict_number(d, (char_u *)"priority"),
14704 (int)get_dict_number(d, (char_u *)"id"));
14705 li = li->li_next;
14707 rettv->vval.v_number = 0;
14709 #endif
14713 * "setpos()" function
14715 /*ARGSUSED*/
14716 static void
14717 f_setpos(argvars, rettv)
14718 typval_T *argvars;
14719 typval_T *rettv;
14721 pos_T pos;
14722 int fnum;
14723 char_u *name;
14725 name = get_tv_string_chk(argvars);
14726 if (name != NULL)
14728 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
14730 --pos.col;
14731 if (name[0] == '.') /* cursor */
14733 if (fnum == curbuf->b_fnum)
14735 curwin->w_cursor = pos;
14736 check_cursor();
14738 else
14739 EMSG(_(e_invarg));
14741 else if (name[0] == '\'') /* mark */
14742 (void)setmark_pos(name[1], &pos, fnum);
14743 else
14744 EMSG(_(e_invarg));
14750 * "setqflist()" function
14752 /*ARGSUSED*/
14753 static void
14754 f_setqflist(argvars, rettv)
14755 typval_T *argvars;
14756 typval_T *rettv;
14758 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
14762 * "setreg()" function
14764 static void
14765 f_setreg(argvars, rettv)
14766 typval_T *argvars;
14767 typval_T *rettv;
14769 int regname;
14770 char_u *strregname;
14771 char_u *stropt;
14772 char_u *strval;
14773 int append;
14774 char_u yank_type;
14775 long block_len;
14777 block_len = -1;
14778 yank_type = MAUTO;
14779 append = FALSE;
14781 strregname = get_tv_string_chk(argvars);
14782 rettv->vval.v_number = 1; /* FAIL is default */
14784 if (strregname == NULL)
14785 return; /* type error; errmsg already given */
14786 regname = *strregname;
14787 if (regname == 0 || regname == '@')
14788 regname = '"';
14789 else if (regname == '=')
14790 return;
14792 if (argvars[2].v_type != VAR_UNKNOWN)
14794 stropt = get_tv_string_chk(&argvars[2]);
14795 if (stropt == NULL)
14796 return; /* type error */
14797 for (; *stropt != NUL; ++stropt)
14798 switch (*stropt)
14800 case 'a': case 'A': /* append */
14801 append = TRUE;
14802 break;
14803 case 'v': case 'c': /* character-wise selection */
14804 yank_type = MCHAR;
14805 break;
14806 case 'V': case 'l': /* line-wise selection */
14807 yank_type = MLINE;
14808 break;
14809 #ifdef FEAT_VISUAL
14810 case 'b': case Ctrl_V: /* block-wise selection */
14811 yank_type = MBLOCK;
14812 if (VIM_ISDIGIT(stropt[1]))
14814 ++stropt;
14815 block_len = getdigits(&stropt) - 1;
14816 --stropt;
14818 break;
14819 #endif
14823 strval = get_tv_string_chk(&argvars[1]);
14824 if (strval != NULL)
14825 write_reg_contents_ex(regname, strval, -1,
14826 append, yank_type, block_len);
14827 rettv->vval.v_number = 0;
14831 * "settabwinvar()" function
14833 static void
14834 f_settabwinvar(argvars, rettv)
14835 typval_T *argvars;
14836 typval_T *rettv;
14838 setwinvar(argvars, rettv, 1);
14842 * "setwinvar()" function
14844 static void
14845 f_setwinvar(argvars, rettv)
14846 typval_T *argvars;
14847 typval_T *rettv;
14849 setwinvar(argvars, rettv, 0);
14853 * "setwinvar()" and "settabwinvar()" functions
14855 static void
14856 setwinvar(argvars, rettv, off)
14857 typval_T *argvars;
14858 typval_T *rettv;
14859 int off;
14861 win_T *win;
14862 #ifdef FEAT_WINDOWS
14863 win_T *save_curwin;
14864 tabpage_T *save_curtab;
14865 #endif
14866 char_u *varname, *winvarname;
14867 typval_T *varp;
14868 char_u nbuf[NUMBUFLEN];
14869 tabpage_T *tp;
14871 rettv->vval.v_number = 0;
14873 if (check_restricted() || check_secure())
14874 return;
14876 #ifdef FEAT_WINDOWS
14877 if (off == 1)
14878 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
14879 else
14880 tp = curtab;
14881 #endif
14882 win = find_win_by_nr(&argvars[off], tp);
14883 varname = get_tv_string_chk(&argvars[off + 1]);
14884 varp = &argvars[off + 2];
14886 if (win != NULL && varname != NULL && varp != NULL)
14888 #ifdef FEAT_WINDOWS
14889 /* set curwin to be our win, temporarily */
14890 save_curwin = curwin;
14891 save_curtab = curtab;
14892 goto_tabpage_tp(tp);
14893 if (!win_valid(win))
14894 return;
14895 curwin = win;
14896 curbuf = curwin->w_buffer;
14897 #endif
14899 if (*varname == '&')
14901 long numval;
14902 char_u *strval;
14903 int error = FALSE;
14905 ++varname;
14906 numval = get_tv_number_chk(varp, &error);
14907 strval = get_tv_string_buf_chk(varp, nbuf);
14908 if (!error && strval != NULL)
14909 set_option_value(varname, numval, strval, OPT_LOCAL);
14911 else
14913 winvarname = alloc((unsigned)STRLEN(varname) + 3);
14914 if (winvarname != NULL)
14916 STRCPY(winvarname, "w:");
14917 STRCPY(winvarname + 2, varname);
14918 set_var(winvarname, varp, TRUE);
14919 vim_free(winvarname);
14923 #ifdef FEAT_WINDOWS
14924 /* Restore current tabpage and window, if still valid (autocomands can
14925 * make them invalid). */
14926 if (valid_tabpage(save_curtab))
14927 goto_tabpage_tp(save_curtab);
14928 if (win_valid(save_curwin))
14930 curwin = save_curwin;
14931 curbuf = curwin->w_buffer;
14933 #endif
14938 * "shellescape({string})" function
14940 static void
14941 f_shellescape(argvars, rettv)
14942 typval_T *argvars;
14943 typval_T *rettv;
14945 rettv->vval.v_string = vim_strsave_shellescape(get_tv_string(&argvars[0]));
14946 rettv->v_type = VAR_STRING;
14950 * "simplify()" function
14952 static void
14953 f_simplify(argvars, rettv)
14954 typval_T *argvars;
14955 typval_T *rettv;
14957 char_u *p;
14959 p = get_tv_string(&argvars[0]);
14960 rettv->vval.v_string = vim_strsave(p);
14961 simplify_filename(rettv->vval.v_string); /* simplify in place */
14962 rettv->v_type = VAR_STRING;
14965 static int
14966 #ifdef __BORLANDC__
14967 _RTLENTRYF
14968 #endif
14969 item_compare __ARGS((const void *s1, const void *s2));
14970 static int
14971 #ifdef __BORLANDC__
14972 _RTLENTRYF
14973 #endif
14974 item_compare2 __ARGS((const void *s1, const void *s2));
14976 static int item_compare_ic;
14977 static char_u *item_compare_func;
14978 static int item_compare_func_err;
14979 #define ITEM_COMPARE_FAIL 999
14982 * Compare functions for f_sort() below.
14984 static int
14985 #ifdef __BORLANDC__
14986 _RTLENTRYF
14987 #endif
14988 item_compare(s1, s2)
14989 const void *s1;
14990 const void *s2;
14992 char_u *p1, *p2;
14993 char_u *tofree1, *tofree2;
14994 int res;
14995 char_u numbuf1[NUMBUFLEN];
14996 char_u numbuf2[NUMBUFLEN];
14998 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
14999 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
15000 if (p1 == NULL)
15001 p1 = (char_u *)"";
15002 if (p2 == NULL)
15003 p2 = (char_u *)"";
15004 if (item_compare_ic)
15005 res = STRICMP(p1, p2);
15006 else
15007 res = STRCMP(p1, p2);
15008 vim_free(tofree1);
15009 vim_free(tofree2);
15010 return res;
15013 static int
15014 #ifdef __BORLANDC__
15015 _RTLENTRYF
15016 #endif
15017 item_compare2(s1, s2)
15018 const void *s1;
15019 const void *s2;
15021 int res;
15022 typval_T rettv;
15023 typval_T argv[3];
15024 int dummy;
15026 /* shortcut after failure in previous call; compare all items equal */
15027 if (item_compare_func_err)
15028 return 0;
15030 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
15031 * in the copy without changing the original list items. */
15032 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
15033 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
15035 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
15036 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
15037 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
15038 clear_tv(&argv[0]);
15039 clear_tv(&argv[1]);
15041 if (res == FAIL)
15042 res = ITEM_COMPARE_FAIL;
15043 else
15044 /* return value has wrong type */
15045 res = get_tv_number_chk(&rettv, &item_compare_func_err);
15046 if (item_compare_func_err)
15047 res = ITEM_COMPARE_FAIL;
15048 clear_tv(&rettv);
15049 return res;
15053 * "sort({list})" function
15055 static void
15056 f_sort(argvars, rettv)
15057 typval_T *argvars;
15058 typval_T *rettv;
15060 list_T *l;
15061 listitem_T *li;
15062 listitem_T **ptrs;
15063 long len;
15064 long i;
15066 rettv->vval.v_number = 0;
15067 if (argvars[0].v_type != VAR_LIST)
15068 EMSG2(_(e_listarg), "sort()");
15069 else
15071 l = argvars[0].vval.v_list;
15072 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
15073 return;
15074 rettv->vval.v_list = l;
15075 rettv->v_type = VAR_LIST;
15076 ++l->lv_refcount;
15078 len = list_len(l);
15079 if (len <= 1)
15080 return; /* short list sorts pretty quickly */
15082 item_compare_ic = FALSE;
15083 item_compare_func = NULL;
15084 if (argvars[1].v_type != VAR_UNKNOWN)
15086 if (argvars[1].v_type == VAR_FUNC)
15087 item_compare_func = argvars[1].vval.v_string;
15088 else
15090 int error = FALSE;
15092 i = get_tv_number_chk(&argvars[1], &error);
15093 if (error)
15094 return; /* type error; errmsg already given */
15095 if (i == 1)
15096 item_compare_ic = TRUE;
15097 else
15098 item_compare_func = get_tv_string(&argvars[1]);
15102 /* Make an array with each entry pointing to an item in the List. */
15103 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
15104 if (ptrs == NULL)
15105 return;
15106 i = 0;
15107 for (li = l->lv_first; li != NULL; li = li->li_next)
15108 ptrs[i++] = li;
15110 item_compare_func_err = FALSE;
15111 /* test the compare function */
15112 if (item_compare_func != NULL
15113 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
15114 == ITEM_COMPARE_FAIL)
15115 EMSG(_("E702: Sort compare function failed"));
15116 else
15118 /* Sort the array with item pointers. */
15119 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
15120 item_compare_func == NULL ? item_compare : item_compare2);
15122 if (!item_compare_func_err)
15124 /* Clear the List and append the items in the sorted order. */
15125 l->lv_first = l->lv_last = NULL;
15126 l->lv_len = 0;
15127 for (i = 0; i < len; ++i)
15128 list_append(l, ptrs[i]);
15132 vim_free(ptrs);
15137 * "soundfold({word})" function
15139 static void
15140 f_soundfold(argvars, rettv)
15141 typval_T *argvars;
15142 typval_T *rettv;
15144 char_u *s;
15146 rettv->v_type = VAR_STRING;
15147 s = get_tv_string(&argvars[0]);
15148 #ifdef FEAT_SPELL
15149 rettv->vval.v_string = eval_soundfold(s);
15150 #else
15151 rettv->vval.v_string = vim_strsave(s);
15152 #endif
15156 * "spellbadword()" function
15158 /* ARGSUSED */
15159 static void
15160 f_spellbadword(argvars, rettv)
15161 typval_T *argvars;
15162 typval_T *rettv;
15164 char_u *word = (char_u *)"";
15165 hlf_T attr = HLF_COUNT;
15166 int len = 0;
15168 if (rettv_list_alloc(rettv) == FAIL)
15169 return;
15171 #ifdef FEAT_SPELL
15172 if (argvars[0].v_type == VAR_UNKNOWN)
15174 /* Find the start and length of the badly spelled word. */
15175 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
15176 if (len != 0)
15177 word = ml_get_cursor();
15179 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15181 char_u *str = get_tv_string_chk(&argvars[0]);
15182 int capcol = -1;
15184 if (str != NULL)
15186 /* Check the argument for spelling. */
15187 while (*str != NUL)
15189 len = spell_check(curwin, str, &attr, &capcol, FALSE);
15190 if (attr != HLF_COUNT)
15192 word = str;
15193 break;
15195 str += len;
15199 #endif
15201 list_append_string(rettv->vval.v_list, word, len);
15202 list_append_string(rettv->vval.v_list, (char_u *)(
15203 attr == HLF_SPB ? "bad" :
15204 attr == HLF_SPR ? "rare" :
15205 attr == HLF_SPL ? "local" :
15206 attr == HLF_SPC ? "caps" :
15207 ""), -1);
15211 * "spellsuggest()" function
15213 /*ARGSUSED*/
15214 static void
15215 f_spellsuggest(argvars, rettv)
15216 typval_T *argvars;
15217 typval_T *rettv;
15219 #ifdef FEAT_SPELL
15220 char_u *str;
15221 int typeerr = FALSE;
15222 int maxcount;
15223 garray_T ga;
15224 int i;
15225 listitem_T *li;
15226 int need_capital = FALSE;
15227 #endif
15229 if (rettv_list_alloc(rettv) == FAIL)
15230 return;
15232 #ifdef FEAT_SPELL
15233 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15235 str = get_tv_string(&argvars[0]);
15236 if (argvars[1].v_type != VAR_UNKNOWN)
15238 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
15239 if (maxcount <= 0)
15240 return;
15241 if (argvars[2].v_type != VAR_UNKNOWN)
15243 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
15244 if (typeerr)
15245 return;
15248 else
15249 maxcount = 25;
15251 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
15253 for (i = 0; i < ga.ga_len; ++i)
15255 str = ((char_u **)ga.ga_data)[i];
15257 li = listitem_alloc();
15258 if (li == NULL)
15259 vim_free(str);
15260 else
15262 li->li_tv.v_type = VAR_STRING;
15263 li->li_tv.v_lock = 0;
15264 li->li_tv.vval.v_string = str;
15265 list_append(rettv->vval.v_list, li);
15268 ga_clear(&ga);
15270 #endif
15273 static void
15274 f_split(argvars, rettv)
15275 typval_T *argvars;
15276 typval_T *rettv;
15278 char_u *str;
15279 char_u *end;
15280 char_u *pat = NULL;
15281 regmatch_T regmatch;
15282 char_u patbuf[NUMBUFLEN];
15283 char_u *save_cpo;
15284 int match;
15285 colnr_T col = 0;
15286 int keepempty = FALSE;
15287 int typeerr = FALSE;
15289 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15290 save_cpo = p_cpo;
15291 p_cpo = (char_u *)"";
15293 str = get_tv_string(&argvars[0]);
15294 if (argvars[1].v_type != VAR_UNKNOWN)
15296 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
15297 if (pat == NULL)
15298 typeerr = TRUE;
15299 if (argvars[2].v_type != VAR_UNKNOWN)
15300 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
15302 if (pat == NULL || *pat == NUL)
15303 pat = (char_u *)"[\\x01- ]\\+";
15305 if (rettv_list_alloc(rettv) == FAIL)
15306 return;
15307 if (typeerr)
15308 return;
15310 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
15311 if (regmatch.regprog != NULL)
15313 regmatch.rm_ic = FALSE;
15314 while (*str != NUL || keepempty)
15316 if (*str == NUL)
15317 match = FALSE; /* empty item at the end */
15318 else
15319 match = vim_regexec_nl(&regmatch, str, col);
15320 if (match)
15321 end = regmatch.startp[0];
15322 else
15323 end = str + STRLEN(str);
15324 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
15325 && *str != NUL && match && end < regmatch.endp[0]))
15327 if (list_append_string(rettv->vval.v_list, str,
15328 (int)(end - str)) == FAIL)
15329 break;
15331 if (!match)
15332 break;
15333 /* Advance to just after the match. */
15334 if (regmatch.endp[0] > str)
15335 col = 0;
15336 else
15338 /* Don't get stuck at the same match. */
15339 #ifdef FEAT_MBYTE
15340 col = (*mb_ptr2len)(regmatch.endp[0]);
15341 #else
15342 col = 1;
15343 #endif
15345 str = regmatch.endp[0];
15348 vim_free(regmatch.regprog);
15351 p_cpo = save_cpo;
15355 * "str2nr()" function
15357 static void
15358 f_str2nr(argvars, rettv)
15359 typval_T *argvars;
15360 typval_T *rettv;
15362 int base = 10;
15363 char_u *p;
15364 long n;
15366 if (argvars[1].v_type != VAR_UNKNOWN)
15368 base = get_tv_number(&argvars[1]);
15369 if (base != 8 && base != 10 && base != 16)
15371 EMSG(_(e_invarg));
15372 return;
15376 p = skipwhite(get_tv_string(&argvars[0]));
15377 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
15378 rettv->vval.v_number = n;
15381 #ifdef HAVE_STRFTIME
15383 * "strftime({format}[, {time}])" function
15385 static void
15386 f_strftime(argvars, rettv)
15387 typval_T *argvars;
15388 typval_T *rettv;
15390 char_u result_buf[256];
15391 struct tm *curtime;
15392 time_t seconds;
15393 char_u *p;
15395 rettv->v_type = VAR_STRING;
15397 p = get_tv_string(&argvars[0]);
15398 if (argvars[1].v_type == VAR_UNKNOWN)
15399 seconds = time(NULL);
15400 else
15401 seconds = (time_t)get_tv_number(&argvars[1]);
15402 curtime = localtime(&seconds);
15403 /* MSVC returns NULL for an invalid value of seconds. */
15404 if (curtime == NULL)
15405 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
15406 else
15408 # ifdef FEAT_MBYTE
15409 vimconv_T conv;
15410 char_u *enc;
15412 conv.vc_type = CONV_NONE;
15413 enc = enc_locale();
15414 convert_setup(&conv, p_enc, enc);
15415 if (conv.vc_type != CONV_NONE)
15416 p = string_convert(&conv, p, NULL);
15417 # endif
15418 if (p != NULL)
15419 (void)strftime((char *)result_buf, sizeof(result_buf),
15420 (char *)p, curtime);
15421 else
15422 result_buf[0] = NUL;
15424 # ifdef FEAT_MBYTE
15425 if (conv.vc_type != CONV_NONE)
15426 vim_free(p);
15427 convert_setup(&conv, enc, p_enc);
15428 if (conv.vc_type != CONV_NONE)
15429 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
15430 else
15431 # endif
15432 rettv->vval.v_string = vim_strsave(result_buf);
15434 # ifdef FEAT_MBYTE
15435 /* Release conversion descriptors */
15436 convert_setup(&conv, NULL, NULL);
15437 vim_free(enc);
15438 # endif
15441 #endif
15444 * "stridx()" function
15446 static void
15447 f_stridx(argvars, rettv)
15448 typval_T *argvars;
15449 typval_T *rettv;
15451 char_u buf[NUMBUFLEN];
15452 char_u *needle;
15453 char_u *haystack;
15454 char_u *save_haystack;
15455 char_u *pos;
15456 int start_idx;
15458 needle = get_tv_string_chk(&argvars[1]);
15459 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
15460 rettv->vval.v_number = -1;
15461 if (needle == NULL || haystack == NULL)
15462 return; /* type error; errmsg already given */
15464 if (argvars[2].v_type != VAR_UNKNOWN)
15466 int error = FALSE;
15468 start_idx = get_tv_number_chk(&argvars[2], &error);
15469 if (error || start_idx >= (int)STRLEN(haystack))
15470 return;
15471 if (start_idx >= 0)
15472 haystack += start_idx;
15475 pos = (char_u *)strstr((char *)haystack, (char *)needle);
15476 if (pos != NULL)
15477 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
15481 * "string()" function
15483 static void
15484 f_string(argvars, rettv)
15485 typval_T *argvars;
15486 typval_T *rettv;
15488 char_u *tofree;
15489 char_u numbuf[NUMBUFLEN];
15491 rettv->v_type = VAR_STRING;
15492 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
15493 /* Make a copy if we have a value but it's not in allocate memory. */
15494 if (rettv->vval.v_string != NULL && tofree == NULL)
15495 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
15499 * "strlen()" function
15501 static void
15502 f_strlen(argvars, rettv)
15503 typval_T *argvars;
15504 typval_T *rettv;
15506 rettv->vval.v_number = (varnumber_T)(STRLEN(
15507 get_tv_string(&argvars[0])));
15511 * "strpart()" function
15513 static void
15514 f_strpart(argvars, rettv)
15515 typval_T *argvars;
15516 typval_T *rettv;
15518 char_u *p;
15519 int n;
15520 int len;
15521 int slen;
15522 int error = FALSE;
15524 p = get_tv_string(&argvars[0]);
15525 slen = (int)STRLEN(p);
15527 n = get_tv_number_chk(&argvars[1], &error);
15528 if (error)
15529 len = 0;
15530 else if (argvars[2].v_type != VAR_UNKNOWN)
15531 len = get_tv_number(&argvars[2]);
15532 else
15533 len = slen - n; /* default len: all bytes that are available. */
15536 * Only return the overlap between the specified part and the actual
15537 * string.
15539 if (n < 0)
15541 len += n;
15542 n = 0;
15544 else if (n > slen)
15545 n = slen;
15546 if (len < 0)
15547 len = 0;
15548 else if (n + len > slen)
15549 len = slen - n;
15551 rettv->v_type = VAR_STRING;
15552 rettv->vval.v_string = vim_strnsave(p + n, len);
15556 * "strridx()" function
15558 static void
15559 f_strridx(argvars, rettv)
15560 typval_T *argvars;
15561 typval_T *rettv;
15563 char_u buf[NUMBUFLEN];
15564 char_u *needle;
15565 char_u *haystack;
15566 char_u *rest;
15567 char_u *lastmatch = NULL;
15568 int haystack_len, end_idx;
15570 needle = get_tv_string_chk(&argvars[1]);
15571 haystack = get_tv_string_buf_chk(&argvars[0], buf);
15573 rettv->vval.v_number = -1;
15574 if (needle == NULL || haystack == NULL)
15575 return; /* type error; errmsg already given */
15577 haystack_len = (int)STRLEN(haystack);
15578 if (argvars[2].v_type != VAR_UNKNOWN)
15580 /* Third argument: upper limit for index */
15581 end_idx = get_tv_number_chk(&argvars[2], NULL);
15582 if (end_idx < 0)
15583 return; /* can never find a match */
15585 else
15586 end_idx = haystack_len;
15588 if (*needle == NUL)
15590 /* Empty string matches past the end. */
15591 lastmatch = haystack + end_idx;
15593 else
15595 for (rest = haystack; *rest != '\0'; ++rest)
15597 rest = (char_u *)strstr((char *)rest, (char *)needle);
15598 if (rest == NULL || rest > haystack + end_idx)
15599 break;
15600 lastmatch = rest;
15604 if (lastmatch == NULL)
15605 rettv->vval.v_number = -1;
15606 else
15607 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
15611 * "strtrans()" function
15613 static void
15614 f_strtrans(argvars, rettv)
15615 typval_T *argvars;
15616 typval_T *rettv;
15618 rettv->v_type = VAR_STRING;
15619 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
15623 * "submatch()" function
15625 static void
15626 f_submatch(argvars, rettv)
15627 typval_T *argvars;
15628 typval_T *rettv;
15630 rettv->v_type = VAR_STRING;
15631 rettv->vval.v_string =
15632 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
15636 * "substitute()" function
15638 static void
15639 f_substitute(argvars, rettv)
15640 typval_T *argvars;
15641 typval_T *rettv;
15643 char_u patbuf[NUMBUFLEN];
15644 char_u subbuf[NUMBUFLEN];
15645 char_u flagsbuf[NUMBUFLEN];
15647 char_u *str = get_tv_string_chk(&argvars[0]);
15648 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
15649 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
15650 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
15652 rettv->v_type = VAR_STRING;
15653 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
15654 rettv->vval.v_string = NULL;
15655 else
15656 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
15660 * "synID(lnum, col, trans)" function
15662 /*ARGSUSED*/
15663 static void
15664 f_synID(argvars, rettv)
15665 typval_T *argvars;
15666 typval_T *rettv;
15668 int id = 0;
15669 #ifdef FEAT_SYN_HL
15670 long lnum;
15671 long col;
15672 int trans;
15673 int transerr = FALSE;
15675 lnum = get_tv_lnum(argvars); /* -1 on type error */
15676 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
15677 trans = get_tv_number_chk(&argvars[2], &transerr);
15679 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
15680 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
15681 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL);
15682 #endif
15684 rettv->vval.v_number = id;
15688 * "synIDattr(id, what [, mode])" function
15690 /*ARGSUSED*/
15691 static void
15692 f_synIDattr(argvars, rettv)
15693 typval_T *argvars;
15694 typval_T *rettv;
15696 char_u *p = NULL;
15697 #ifdef FEAT_SYN_HL
15698 int id;
15699 char_u *what;
15700 char_u *mode;
15701 char_u modebuf[NUMBUFLEN];
15702 int modec;
15704 id = get_tv_number(&argvars[0]);
15705 what = get_tv_string(&argvars[1]);
15706 if (argvars[2].v_type != VAR_UNKNOWN)
15708 mode = get_tv_string_buf(&argvars[2], modebuf);
15709 modec = TOLOWER_ASC(mode[0]);
15710 if (modec != 't' && modec != 'c'
15711 #ifdef FEAT_GUI
15712 && modec != 'g'
15713 #endif
15715 modec = 0; /* replace invalid with current */
15717 else
15719 #ifdef FEAT_GUI
15720 if (gui.in_use)
15721 modec = 'g';
15722 else
15723 #endif
15724 if (t_colors > 1)
15725 modec = 'c';
15726 else
15727 modec = 't';
15731 switch (TOLOWER_ASC(what[0]))
15733 case 'b':
15734 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
15735 p = highlight_color(id, what, modec);
15736 else /* bold */
15737 p = highlight_has_attr(id, HL_BOLD, modec);
15738 break;
15740 case 'f': /* fg[#] */
15741 p = highlight_color(id, what, modec);
15742 break;
15744 case 'i':
15745 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
15746 p = highlight_has_attr(id, HL_INVERSE, modec);
15747 else /* italic */
15748 p = highlight_has_attr(id, HL_ITALIC, modec);
15749 break;
15751 case 'n': /* name */
15752 p = get_highlight_name(NULL, id - 1);
15753 break;
15755 case 'r': /* reverse */
15756 p = highlight_has_attr(id, HL_INVERSE, modec);
15757 break;
15759 case 's': /* standout */
15760 p = highlight_has_attr(id, HL_STANDOUT, modec);
15761 break;
15763 case 'u':
15764 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
15765 /* underline */
15766 p = highlight_has_attr(id, HL_UNDERLINE, modec);
15767 else
15768 /* undercurl */
15769 p = highlight_has_attr(id, HL_UNDERCURL, modec);
15770 break;
15773 if (p != NULL)
15774 p = vim_strsave(p);
15775 #endif
15776 rettv->v_type = VAR_STRING;
15777 rettv->vval.v_string = p;
15781 * "synIDtrans(id)" function
15783 /*ARGSUSED*/
15784 static void
15785 f_synIDtrans(argvars, rettv)
15786 typval_T *argvars;
15787 typval_T *rettv;
15789 int id;
15791 #ifdef FEAT_SYN_HL
15792 id = get_tv_number(&argvars[0]);
15794 if (id > 0)
15795 id = syn_get_final_id(id);
15796 else
15797 #endif
15798 id = 0;
15800 rettv->vval.v_number = id;
15804 * "system()" function
15806 static void
15807 f_system(argvars, rettv)
15808 typval_T *argvars;
15809 typval_T *rettv;
15811 char_u *res = NULL;
15812 char_u *p;
15813 char_u *infile = NULL;
15814 char_u buf[NUMBUFLEN];
15815 int err = FALSE;
15816 FILE *fd;
15818 if (check_restricted() || check_secure())
15819 return;
15821 if (argvars[1].v_type != VAR_UNKNOWN)
15824 * Write the string to a temp file, to be used for input of the shell
15825 * command.
15827 if ((infile = vim_tempname('i')) == NULL)
15829 EMSG(_(e_notmp));
15830 return;
15833 fd = mch_fopen((char *)infile, WRITEBIN);
15834 if (fd == NULL)
15836 EMSG2(_(e_notopen), infile);
15837 goto done;
15839 p = get_tv_string_buf_chk(&argvars[1], buf);
15840 if (p == NULL)
15842 fclose(fd);
15843 goto done; /* type error; errmsg already given */
15845 if (fwrite(p, STRLEN(p), 1, fd) != 1)
15846 err = TRUE;
15847 if (fclose(fd) != 0)
15848 err = TRUE;
15849 if (err)
15851 EMSG(_("E677: Error writing temp file"));
15852 goto done;
15856 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
15857 SHELL_SILENT | SHELL_COOKED);
15859 #ifdef USE_CR
15860 /* translate <CR> into <NL> */
15861 if (res != NULL)
15863 char_u *s;
15865 for (s = res; *s; ++s)
15867 if (*s == CAR)
15868 *s = NL;
15871 #else
15872 # ifdef USE_CRNL
15873 /* translate <CR><NL> into <NL> */
15874 if (res != NULL)
15876 char_u *s, *d;
15878 d = res;
15879 for (s = res; *s; ++s)
15881 if (s[0] == CAR && s[1] == NL)
15882 ++s;
15883 *d++ = *s;
15885 *d = NUL;
15887 # endif
15888 #endif
15890 done:
15891 if (infile != NULL)
15893 mch_remove(infile);
15894 vim_free(infile);
15896 rettv->v_type = VAR_STRING;
15897 rettv->vval.v_string = res;
15901 * "tabpagebuflist()" function
15903 /* ARGSUSED */
15904 static void
15905 f_tabpagebuflist(argvars, rettv)
15906 typval_T *argvars;
15907 typval_T *rettv;
15909 #ifndef FEAT_WINDOWS
15910 rettv->vval.v_number = 0;
15911 #else
15912 tabpage_T *tp;
15913 win_T *wp = NULL;
15915 if (argvars[0].v_type == VAR_UNKNOWN)
15916 wp = firstwin;
15917 else
15919 tp = find_tabpage((int)get_tv_number(&argvars[0]));
15920 if (tp != NULL)
15921 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
15923 if (wp == NULL)
15924 rettv->vval.v_number = 0;
15925 else
15927 if (rettv_list_alloc(rettv) == FAIL)
15928 rettv->vval.v_number = 0;
15929 else
15931 for (; wp != NULL; wp = wp->w_next)
15932 if (list_append_number(rettv->vval.v_list,
15933 wp->w_buffer->b_fnum) == FAIL)
15934 break;
15937 #endif
15942 * "tabpagenr()" function
15944 /* ARGSUSED */
15945 static void
15946 f_tabpagenr(argvars, rettv)
15947 typval_T *argvars;
15948 typval_T *rettv;
15950 int nr = 1;
15951 #ifdef FEAT_WINDOWS
15952 char_u *arg;
15954 if (argvars[0].v_type != VAR_UNKNOWN)
15956 arg = get_tv_string_chk(&argvars[0]);
15957 nr = 0;
15958 if (arg != NULL)
15960 if (STRCMP(arg, "$") == 0)
15961 nr = tabpage_index(NULL) - 1;
15962 else
15963 EMSG2(_(e_invexpr2), arg);
15966 else
15967 nr = tabpage_index(curtab);
15968 #endif
15969 rettv->vval.v_number = nr;
15973 #ifdef FEAT_WINDOWS
15974 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
15977 * Common code for tabpagewinnr() and winnr().
15979 static int
15980 get_winnr(tp, argvar)
15981 tabpage_T *tp;
15982 typval_T *argvar;
15984 win_T *twin;
15985 int nr = 1;
15986 win_T *wp;
15987 char_u *arg;
15989 twin = (tp == curtab) ? curwin : tp->tp_curwin;
15990 if (argvar->v_type != VAR_UNKNOWN)
15992 arg = get_tv_string_chk(argvar);
15993 if (arg == NULL)
15994 nr = 0; /* type error; errmsg already given */
15995 else if (STRCMP(arg, "$") == 0)
15996 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
15997 else if (STRCMP(arg, "#") == 0)
15999 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
16000 if (twin == NULL)
16001 nr = 0;
16003 else
16005 EMSG2(_(e_invexpr2), arg);
16006 nr = 0;
16010 if (nr > 0)
16011 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16012 wp != twin; wp = wp->w_next)
16014 if (wp == NULL)
16016 /* didn't find it in this tabpage */
16017 nr = 0;
16018 break;
16020 ++nr;
16022 return nr;
16024 #endif
16027 * "tabpagewinnr()" function
16029 /* ARGSUSED */
16030 static void
16031 f_tabpagewinnr(argvars, rettv)
16032 typval_T *argvars;
16033 typval_T *rettv;
16035 int nr = 1;
16036 #ifdef FEAT_WINDOWS
16037 tabpage_T *tp;
16039 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16040 if (tp == NULL)
16041 nr = 0;
16042 else
16043 nr = get_winnr(tp, &argvars[1]);
16044 #endif
16045 rettv->vval.v_number = nr;
16050 * "tagfiles()" function
16052 /*ARGSUSED*/
16053 static void
16054 f_tagfiles(argvars, rettv)
16055 typval_T *argvars;
16056 typval_T *rettv;
16058 char_u fname[MAXPATHL + 1];
16059 tagname_T tn;
16060 int first;
16062 if (rettv_list_alloc(rettv) == FAIL)
16064 rettv->vval.v_number = 0;
16065 return;
16068 for (first = TRUE; ; first = FALSE)
16069 if (get_tagfname(&tn, first, fname) == FAIL
16070 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
16071 break;
16072 tagname_free(&tn);
16076 * "taglist()" function
16078 static void
16079 f_taglist(argvars, rettv)
16080 typval_T *argvars;
16081 typval_T *rettv;
16083 char_u *tag_pattern;
16085 tag_pattern = get_tv_string(&argvars[0]);
16087 rettv->vval.v_number = FALSE;
16088 if (*tag_pattern == NUL)
16089 return;
16091 if (rettv_list_alloc(rettv) == OK)
16092 (void)get_tags(rettv->vval.v_list, tag_pattern);
16096 * "tempname()" function
16098 /*ARGSUSED*/
16099 static void
16100 f_tempname(argvars, rettv)
16101 typval_T *argvars;
16102 typval_T *rettv;
16104 static int x = 'A';
16106 rettv->v_type = VAR_STRING;
16107 rettv->vval.v_string = vim_tempname(x);
16109 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
16110 * names. Skip 'I' and 'O', they are used for shell redirection. */
16113 if (x == 'Z')
16114 x = '0';
16115 else if (x == '9')
16116 x = 'A';
16117 else
16119 #ifdef EBCDIC
16120 if (x == 'I')
16121 x = 'J';
16122 else if (x == 'R')
16123 x = 'S';
16124 else
16125 #endif
16126 ++x;
16128 } while (x == 'I' || x == 'O');
16132 * "test(list)" function: Just checking the walls...
16134 /*ARGSUSED*/
16135 static void
16136 f_test(argvars, rettv)
16137 typval_T *argvars;
16138 typval_T *rettv;
16140 /* Used for unit testing. Change the code below to your liking. */
16141 #if 0
16142 listitem_T *li;
16143 list_T *l;
16144 char_u *bad, *good;
16146 if (argvars[0].v_type != VAR_LIST)
16147 return;
16148 l = argvars[0].vval.v_list;
16149 if (l == NULL)
16150 return;
16151 li = l->lv_first;
16152 if (li == NULL)
16153 return;
16154 bad = get_tv_string(&li->li_tv);
16155 li = li->li_next;
16156 if (li == NULL)
16157 return;
16158 good = get_tv_string(&li->li_tv);
16159 rettv->vval.v_number = test_edit_score(bad, good);
16160 #endif
16164 * "tolower(string)" function
16166 static void
16167 f_tolower(argvars, rettv)
16168 typval_T *argvars;
16169 typval_T *rettv;
16171 char_u *p;
16173 p = vim_strsave(get_tv_string(&argvars[0]));
16174 rettv->v_type = VAR_STRING;
16175 rettv->vval.v_string = p;
16177 if (p != NULL)
16178 while (*p != NUL)
16180 #ifdef FEAT_MBYTE
16181 int l;
16183 if (enc_utf8)
16185 int c, lc;
16187 c = utf_ptr2char(p);
16188 lc = utf_tolower(c);
16189 l = utf_ptr2len(p);
16190 /* TODO: reallocate string when byte count changes. */
16191 if (utf_char2len(lc) == l)
16192 utf_char2bytes(lc, p);
16193 p += l;
16195 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
16196 p += l; /* skip multi-byte character */
16197 else
16198 #endif
16200 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
16201 ++p;
16207 * "toupper(string)" function
16209 static void
16210 f_toupper(argvars, rettv)
16211 typval_T *argvars;
16212 typval_T *rettv;
16214 rettv->v_type = VAR_STRING;
16215 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
16219 * "tr(string, fromstr, tostr)" function
16221 static void
16222 f_tr(argvars, rettv)
16223 typval_T *argvars;
16224 typval_T *rettv;
16226 char_u *instr;
16227 char_u *fromstr;
16228 char_u *tostr;
16229 char_u *p;
16230 #ifdef FEAT_MBYTE
16231 int inlen;
16232 int fromlen;
16233 int tolen;
16234 int idx;
16235 char_u *cpstr;
16236 int cplen;
16237 int first = TRUE;
16238 #endif
16239 char_u buf[NUMBUFLEN];
16240 char_u buf2[NUMBUFLEN];
16241 garray_T ga;
16243 instr = get_tv_string(&argvars[0]);
16244 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
16245 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
16247 /* Default return value: empty string. */
16248 rettv->v_type = VAR_STRING;
16249 rettv->vval.v_string = NULL;
16250 if (fromstr == NULL || tostr == NULL)
16251 return; /* type error; errmsg already given */
16252 ga_init2(&ga, (int)sizeof(char), 80);
16254 #ifdef FEAT_MBYTE
16255 if (!has_mbyte)
16256 #endif
16257 /* not multi-byte: fromstr and tostr must be the same length */
16258 if (STRLEN(fromstr) != STRLEN(tostr))
16260 #ifdef FEAT_MBYTE
16261 error:
16262 #endif
16263 EMSG2(_(e_invarg2), fromstr);
16264 ga_clear(&ga);
16265 return;
16268 /* fromstr and tostr have to contain the same number of chars */
16269 while (*instr != NUL)
16271 #ifdef FEAT_MBYTE
16272 if (has_mbyte)
16274 inlen = (*mb_ptr2len)(instr);
16275 cpstr = instr;
16276 cplen = inlen;
16277 idx = 0;
16278 for (p = fromstr; *p != NUL; p += fromlen)
16280 fromlen = (*mb_ptr2len)(p);
16281 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
16283 for (p = tostr; *p != NUL; p += tolen)
16285 tolen = (*mb_ptr2len)(p);
16286 if (idx-- == 0)
16288 cplen = tolen;
16289 cpstr = p;
16290 break;
16293 if (*p == NUL) /* tostr is shorter than fromstr */
16294 goto error;
16295 break;
16297 ++idx;
16300 if (first && cpstr == instr)
16302 /* Check that fromstr and tostr have the same number of
16303 * (multi-byte) characters. Done only once when a character
16304 * of instr doesn't appear in fromstr. */
16305 first = FALSE;
16306 for (p = tostr; *p != NUL; p += tolen)
16308 tolen = (*mb_ptr2len)(p);
16309 --idx;
16311 if (idx != 0)
16312 goto error;
16315 ga_grow(&ga, cplen);
16316 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
16317 ga.ga_len += cplen;
16319 instr += inlen;
16321 else
16322 #endif
16324 /* When not using multi-byte chars we can do it faster. */
16325 p = vim_strchr(fromstr, *instr);
16326 if (p != NULL)
16327 ga_append(&ga, tostr[p - fromstr]);
16328 else
16329 ga_append(&ga, *instr);
16330 ++instr;
16334 /* add a terminating NUL */
16335 ga_grow(&ga, 1);
16336 ga_append(&ga, NUL);
16338 rettv->vval.v_string = ga.ga_data;
16342 * "type(expr)" function
16344 static void
16345 f_type(argvars, rettv)
16346 typval_T *argvars;
16347 typval_T *rettv;
16349 int n;
16351 switch (argvars[0].v_type)
16353 case VAR_NUMBER: n = 0; break;
16354 case VAR_STRING: n = 1; break;
16355 case VAR_FUNC: n = 2; break;
16356 case VAR_LIST: n = 3; break;
16357 case VAR_DICT: n = 4; break;
16358 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
16360 rettv->vval.v_number = n;
16364 * "values(dict)" function
16366 static void
16367 f_values(argvars, rettv)
16368 typval_T *argvars;
16369 typval_T *rettv;
16371 dict_list(argvars, rettv, 1);
16375 * "virtcol(string)" function
16377 static void
16378 f_virtcol(argvars, rettv)
16379 typval_T *argvars;
16380 typval_T *rettv;
16382 colnr_T vcol = 0;
16383 pos_T *fp;
16384 int fnum = curbuf->b_fnum;
16386 fp = var2fpos(&argvars[0], FALSE, &fnum);
16387 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
16388 && fnum == curbuf->b_fnum)
16390 getvvcol(curwin, fp, NULL, NULL, &vcol);
16391 ++vcol;
16394 rettv->vval.v_number = vcol;
16398 * "visualmode()" function
16400 /*ARGSUSED*/
16401 static void
16402 f_visualmode(argvars, rettv)
16403 typval_T *argvars;
16404 typval_T *rettv;
16406 #ifdef FEAT_VISUAL
16407 char_u str[2];
16409 rettv->v_type = VAR_STRING;
16410 str[0] = curbuf->b_visual_mode_eval;
16411 str[1] = NUL;
16412 rettv->vval.v_string = vim_strsave(str);
16414 /* A non-zero number or non-empty string argument: reset mode. */
16415 if ((argvars[0].v_type == VAR_NUMBER
16416 && argvars[0].vval.v_number != 0)
16417 || (argvars[0].v_type == VAR_STRING
16418 && *get_tv_string(&argvars[0]) != NUL))
16419 curbuf->b_visual_mode_eval = NUL;
16420 #else
16421 rettv->vval.v_number = 0; /* return anything, it won't work anyway */
16422 #endif
16426 * "winbufnr(nr)" function
16428 static void
16429 f_winbufnr(argvars, rettv)
16430 typval_T *argvars;
16431 typval_T *rettv;
16433 win_T *wp;
16435 wp = find_win_by_nr(&argvars[0], NULL);
16436 if (wp == NULL)
16437 rettv->vval.v_number = -1;
16438 else
16439 rettv->vval.v_number = wp->w_buffer->b_fnum;
16443 * "wincol()" function
16445 /*ARGSUSED*/
16446 static void
16447 f_wincol(argvars, rettv)
16448 typval_T *argvars;
16449 typval_T *rettv;
16451 validate_cursor();
16452 rettv->vval.v_number = curwin->w_wcol + 1;
16456 * "winheight(nr)" function
16458 static void
16459 f_winheight(argvars, rettv)
16460 typval_T *argvars;
16461 typval_T *rettv;
16463 win_T *wp;
16465 wp = find_win_by_nr(&argvars[0], NULL);
16466 if (wp == NULL)
16467 rettv->vval.v_number = -1;
16468 else
16469 rettv->vval.v_number = wp->w_height;
16473 * "winline()" function
16475 /*ARGSUSED*/
16476 static void
16477 f_winline(argvars, rettv)
16478 typval_T *argvars;
16479 typval_T *rettv;
16481 validate_cursor();
16482 rettv->vval.v_number = curwin->w_wrow + 1;
16486 * "winnr()" function
16488 /* ARGSUSED */
16489 static void
16490 f_winnr(argvars, rettv)
16491 typval_T *argvars;
16492 typval_T *rettv;
16494 int nr = 1;
16496 #ifdef FEAT_WINDOWS
16497 nr = get_winnr(curtab, &argvars[0]);
16498 #endif
16499 rettv->vval.v_number = nr;
16503 * "winrestcmd()" function
16505 /* ARGSUSED */
16506 static void
16507 f_winrestcmd(argvars, rettv)
16508 typval_T *argvars;
16509 typval_T *rettv;
16511 #ifdef FEAT_WINDOWS
16512 win_T *wp;
16513 int winnr = 1;
16514 garray_T ga;
16515 char_u buf[50];
16517 ga_init2(&ga, (int)sizeof(char), 70);
16518 for (wp = firstwin; wp != NULL; wp = wp->w_next)
16520 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
16521 ga_concat(&ga, buf);
16522 # ifdef FEAT_VERTSPLIT
16523 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
16524 ga_concat(&ga, buf);
16525 # endif
16526 ++winnr;
16528 ga_append(&ga, NUL);
16530 rettv->vval.v_string = ga.ga_data;
16531 #else
16532 rettv->vval.v_string = NULL;
16533 #endif
16534 rettv->v_type = VAR_STRING;
16538 * "winrestview()" function
16540 /* ARGSUSED */
16541 static void
16542 f_winrestview(argvars, rettv)
16543 typval_T *argvars;
16544 typval_T *rettv;
16546 dict_T *dict;
16548 if (argvars[0].v_type != VAR_DICT
16549 || (dict = argvars[0].vval.v_dict) == NULL)
16550 EMSG(_(e_invarg));
16551 else
16553 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
16554 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
16555 #ifdef FEAT_VIRTUALEDIT
16556 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
16557 #endif
16558 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
16559 curwin->w_set_curswant = FALSE;
16561 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
16562 #ifdef FEAT_DIFF
16563 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
16564 #endif
16565 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
16566 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
16568 check_cursor();
16569 changed_cline_bef_curs();
16570 invalidate_botline();
16571 redraw_later(VALID);
16573 if (curwin->w_topline == 0)
16574 curwin->w_topline = 1;
16575 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
16576 curwin->w_topline = curbuf->b_ml.ml_line_count;
16577 #ifdef FEAT_DIFF
16578 check_topfill(curwin, TRUE);
16579 #endif
16584 * "winsaveview()" function
16586 /* ARGSUSED */
16587 static void
16588 f_winsaveview(argvars, rettv)
16589 typval_T *argvars;
16590 typval_T *rettv;
16592 dict_T *dict;
16594 dict = dict_alloc();
16595 if (dict == NULL)
16596 return;
16597 rettv->v_type = VAR_DICT;
16598 rettv->vval.v_dict = dict;
16599 ++dict->dv_refcount;
16601 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
16602 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
16603 #ifdef FEAT_VIRTUALEDIT
16604 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
16605 #endif
16606 update_curswant();
16607 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
16609 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
16610 #ifdef FEAT_DIFF
16611 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
16612 #endif
16613 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
16614 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
16618 * "winwidth(nr)" function
16620 static void
16621 f_winwidth(argvars, rettv)
16622 typval_T *argvars;
16623 typval_T *rettv;
16625 win_T *wp;
16627 wp = find_win_by_nr(&argvars[0], NULL);
16628 if (wp == NULL)
16629 rettv->vval.v_number = -1;
16630 else
16631 #ifdef FEAT_VERTSPLIT
16632 rettv->vval.v_number = wp->w_width;
16633 #else
16634 rettv->vval.v_number = Columns;
16635 #endif
16639 * "writefile()" function
16641 static void
16642 f_writefile(argvars, rettv)
16643 typval_T *argvars;
16644 typval_T *rettv;
16646 int binary = FALSE;
16647 char_u *fname;
16648 FILE *fd;
16649 listitem_T *li;
16650 char_u *s;
16651 int ret = 0;
16652 int c;
16654 if (check_restricted() || check_secure())
16655 return;
16657 if (argvars[0].v_type != VAR_LIST)
16659 EMSG2(_(e_listarg), "writefile()");
16660 return;
16662 if (argvars[0].vval.v_list == NULL)
16663 return;
16665 if (argvars[2].v_type != VAR_UNKNOWN
16666 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
16667 binary = TRUE;
16669 /* Always open the file in binary mode, library functions have a mind of
16670 * their own about CR-LF conversion. */
16671 fname = get_tv_string(&argvars[1]);
16672 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
16674 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
16675 ret = -1;
16677 else
16679 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
16680 li = li->li_next)
16682 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
16684 if (*s == '\n')
16685 c = putc(NUL, fd);
16686 else
16687 c = putc(*s, fd);
16688 if (c == EOF)
16690 ret = -1;
16691 break;
16694 if (!binary || li->li_next != NULL)
16695 if (putc('\n', fd) == EOF)
16697 ret = -1;
16698 break;
16700 if (ret < 0)
16702 EMSG(_(e_write));
16703 break;
16706 fclose(fd);
16709 rettv->vval.v_number = ret;
16713 * Translate a String variable into a position.
16714 * Returns NULL when there is an error.
16716 static pos_T *
16717 var2fpos(varp, dollar_lnum, fnum)
16718 typval_T *varp;
16719 int dollar_lnum; /* TRUE when $ is last line */
16720 int *fnum; /* set to fnum for '0, 'A, etc. */
16722 char_u *name;
16723 static pos_T pos;
16724 pos_T *pp;
16726 /* Argument can be [lnum, col, coladd]. */
16727 if (varp->v_type == VAR_LIST)
16729 list_T *l;
16730 int len;
16731 int error = FALSE;
16732 listitem_T *li;
16734 l = varp->vval.v_list;
16735 if (l == NULL)
16736 return NULL;
16738 /* Get the line number */
16739 pos.lnum = list_find_nr(l, 0L, &error);
16740 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
16741 return NULL; /* invalid line number */
16743 /* Get the column number */
16744 pos.col = list_find_nr(l, 1L, &error);
16745 if (error)
16746 return NULL;
16747 len = (long)STRLEN(ml_get(pos.lnum));
16749 /* We accept "$" for the column number: last column. */
16750 li = list_find(l, 1L);
16751 if (li != NULL && li->li_tv.v_type == VAR_STRING
16752 && li->li_tv.vval.v_string != NULL
16753 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
16754 pos.col = len + 1;
16756 /* Accept a position up to the NUL after the line. */
16757 if (pos.col == 0 || (int)pos.col > len + 1)
16758 return NULL; /* invalid column number */
16759 --pos.col;
16761 #ifdef FEAT_VIRTUALEDIT
16762 /* Get the virtual offset. Defaults to zero. */
16763 pos.coladd = list_find_nr(l, 2L, &error);
16764 if (error)
16765 pos.coladd = 0;
16766 #endif
16768 return &pos;
16771 name = get_tv_string_chk(varp);
16772 if (name == NULL)
16773 return NULL;
16774 if (name[0] == '.') /* cursor */
16775 return &curwin->w_cursor;
16776 if (name[0] == '\'') /* mark */
16778 pp = getmark_fnum(name[1], FALSE, fnum);
16779 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
16780 return NULL;
16781 return pp;
16784 #ifdef FEAT_VIRTUALEDIT
16785 pos.coladd = 0;
16786 #endif
16788 if (name[0] == 'w' && dollar_lnum)
16790 pos.col = 0;
16791 if (name[1] == '0') /* "w0": first visible line */
16793 update_topline();
16794 pos.lnum = curwin->w_topline;
16795 return &pos;
16797 else if (name[1] == '$') /* "w$": last visible line */
16799 validate_botline();
16800 pos.lnum = curwin->w_botline - 1;
16801 return &pos;
16804 else if (name[0] == '$') /* last column or line */
16806 if (dollar_lnum)
16808 pos.lnum = curbuf->b_ml.ml_line_count;
16809 pos.col = 0;
16811 else
16813 pos.lnum = curwin->w_cursor.lnum;
16814 pos.col = (colnr_T)STRLEN(ml_get_curline());
16816 return &pos;
16818 return NULL;
16822 * Convert list in "arg" into a position and optional file number.
16823 * When "fnump" is NULL there is no file number, only 3 items.
16824 * Note that the column is passed on as-is, the caller may want to decrement
16825 * it to use 1 for the first column.
16826 * Return FAIL when conversion is not possible, doesn't check the position for
16827 * validity.
16829 static int
16830 list2fpos(arg, posp, fnump)
16831 typval_T *arg;
16832 pos_T *posp;
16833 int *fnump;
16835 list_T *l = arg->vval.v_list;
16836 long i = 0;
16837 long n;
16839 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
16840 * when "fnump" isn't NULL and "coladd" is optional. */
16841 if (arg->v_type != VAR_LIST
16842 || l == NULL
16843 || l->lv_len < (fnump == NULL ? 2 : 3)
16844 || l->lv_len > (fnump == NULL ? 3 : 4))
16845 return FAIL;
16847 if (fnump != NULL)
16849 n = list_find_nr(l, i++, NULL); /* fnum */
16850 if (n < 0)
16851 return FAIL;
16852 if (n == 0)
16853 n = curbuf->b_fnum; /* current buffer */
16854 *fnump = n;
16857 n = list_find_nr(l, i++, NULL); /* lnum */
16858 if (n < 0)
16859 return FAIL;
16860 posp->lnum = n;
16862 n = list_find_nr(l, i++, NULL); /* col */
16863 if (n < 0)
16864 return FAIL;
16865 posp->col = n;
16867 #ifdef FEAT_VIRTUALEDIT
16868 n = list_find_nr(l, i, NULL);
16869 if (n < 0)
16870 posp->coladd = 0;
16871 else
16872 posp->coladd = n;
16873 #endif
16875 return OK;
16879 * Get the length of an environment variable name.
16880 * Advance "arg" to the first character after the name.
16881 * Return 0 for error.
16883 static int
16884 get_env_len(arg)
16885 char_u **arg;
16887 char_u *p;
16888 int len;
16890 for (p = *arg; vim_isIDc(*p); ++p)
16892 if (p == *arg) /* no name found */
16893 return 0;
16895 len = (int)(p - *arg);
16896 *arg = p;
16897 return len;
16901 * Get the length of the name of a function or internal variable.
16902 * "arg" is advanced to the first non-white character after the name.
16903 * Return 0 if something is wrong.
16905 static int
16906 get_id_len(arg)
16907 char_u **arg;
16909 char_u *p;
16910 int len;
16912 /* Find the end of the name. */
16913 for (p = *arg; eval_isnamec(*p); ++p)
16915 if (p == *arg) /* no name found */
16916 return 0;
16918 len = (int)(p - *arg);
16919 *arg = skipwhite(p);
16921 return len;
16925 * Get the length of the name of a variable or function.
16926 * Only the name is recognized, does not handle ".key" or "[idx]".
16927 * "arg" is advanced to the first non-white character after the name.
16928 * Return -1 if curly braces expansion failed.
16929 * Return 0 if something else is wrong.
16930 * If the name contains 'magic' {}'s, expand them and return the
16931 * expanded name in an allocated string via 'alias' - caller must free.
16933 static int
16934 get_name_len(arg, alias, evaluate, verbose)
16935 char_u **arg;
16936 char_u **alias;
16937 int evaluate;
16938 int verbose;
16940 int len;
16941 char_u *p;
16942 char_u *expr_start;
16943 char_u *expr_end;
16945 *alias = NULL; /* default to no alias */
16947 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
16948 && (*arg)[2] == (int)KE_SNR)
16950 /* hard coded <SNR>, already translated */
16951 *arg += 3;
16952 return get_id_len(arg) + 3;
16954 len = eval_fname_script(*arg);
16955 if (len > 0)
16957 /* literal "<SID>", "s:" or "<SNR>" */
16958 *arg += len;
16962 * Find the end of the name; check for {} construction.
16964 p = find_name_end(*arg, &expr_start, &expr_end,
16965 len > 0 ? 0 : FNE_CHECK_START);
16966 if (expr_start != NULL)
16968 char_u *temp_string;
16970 if (!evaluate)
16972 len += (int)(p - *arg);
16973 *arg = skipwhite(p);
16974 return len;
16978 * Include any <SID> etc in the expanded string:
16979 * Thus the -len here.
16981 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
16982 if (temp_string == NULL)
16983 return -1;
16984 *alias = temp_string;
16985 *arg = skipwhite(p);
16986 return (int)STRLEN(temp_string);
16989 len += get_id_len(arg);
16990 if (len == 0 && verbose)
16991 EMSG2(_(e_invexpr2), *arg);
16993 return len;
16997 * Find the end of a variable or function name, taking care of magic braces.
16998 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
16999 * start and end of the first magic braces item.
17000 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
17001 * Return a pointer to just after the name. Equal to "arg" if there is no
17002 * valid name.
17004 static char_u *
17005 find_name_end(arg, expr_start, expr_end, flags)
17006 char_u *arg;
17007 char_u **expr_start;
17008 char_u **expr_end;
17009 int flags;
17011 int mb_nest = 0;
17012 int br_nest = 0;
17013 char_u *p;
17015 if (expr_start != NULL)
17017 *expr_start = NULL;
17018 *expr_end = NULL;
17021 /* Quick check for valid starting character. */
17022 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
17023 return arg;
17025 for (p = arg; *p != NUL
17026 && (eval_isnamec(*p)
17027 || *p == '{'
17028 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
17029 || mb_nest != 0
17030 || br_nest != 0); mb_ptr_adv(p))
17032 if (*p == '\'')
17034 /* skip over 'string' to avoid counting [ and ] inside it. */
17035 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
17037 if (*p == NUL)
17038 break;
17040 else if (*p == '"')
17042 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
17043 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
17044 if (*p == '\\' && p[1] != NUL)
17045 ++p;
17046 if (*p == NUL)
17047 break;
17050 if (mb_nest == 0)
17052 if (*p == '[')
17053 ++br_nest;
17054 else if (*p == ']')
17055 --br_nest;
17058 if (br_nest == 0)
17060 if (*p == '{')
17062 mb_nest++;
17063 if (expr_start != NULL && *expr_start == NULL)
17064 *expr_start = p;
17066 else if (*p == '}')
17068 mb_nest--;
17069 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
17070 *expr_end = p;
17075 return p;
17079 * Expands out the 'magic' {}'s in a variable/function name.
17080 * Note that this can call itself recursively, to deal with
17081 * constructs like foo{bar}{baz}{bam}
17082 * The four pointer arguments point to "foo{expre}ss{ion}bar"
17083 * "in_start" ^
17084 * "expr_start" ^
17085 * "expr_end" ^
17086 * "in_end" ^
17088 * Returns a new allocated string, which the caller must free.
17089 * Returns NULL for failure.
17091 static char_u *
17092 make_expanded_name(in_start, expr_start, expr_end, in_end)
17093 char_u *in_start;
17094 char_u *expr_start;
17095 char_u *expr_end;
17096 char_u *in_end;
17098 char_u c1;
17099 char_u *retval = NULL;
17100 char_u *temp_result;
17101 char_u *nextcmd = NULL;
17103 if (expr_end == NULL || in_end == NULL)
17104 return NULL;
17105 *expr_start = NUL;
17106 *expr_end = NUL;
17107 c1 = *in_end;
17108 *in_end = NUL;
17110 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
17111 if (temp_result != NULL && nextcmd == NULL)
17113 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
17114 + (in_end - expr_end) + 1));
17115 if (retval != NULL)
17117 STRCPY(retval, in_start);
17118 STRCAT(retval, temp_result);
17119 STRCAT(retval, expr_end + 1);
17122 vim_free(temp_result);
17124 *in_end = c1; /* put char back for error messages */
17125 *expr_start = '{';
17126 *expr_end = '}';
17128 if (retval != NULL)
17130 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
17131 if (expr_start != NULL)
17133 /* Further expansion! */
17134 temp_result = make_expanded_name(retval, expr_start,
17135 expr_end, temp_result);
17136 vim_free(retval);
17137 retval = temp_result;
17141 return retval;
17145 * Return TRUE if character "c" can be used in a variable or function name.
17146 * Does not include '{' or '}' for magic braces.
17148 static int
17149 eval_isnamec(c)
17150 int c;
17152 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
17156 * Return TRUE if character "c" can be used as the first character in a
17157 * variable or function name (excluding '{' and '}').
17159 static int
17160 eval_isnamec1(c)
17161 int c;
17163 return (ASCII_ISALPHA(c) || c == '_');
17167 * Set number v: variable to "val".
17169 void
17170 set_vim_var_nr(idx, val)
17171 int idx;
17172 long val;
17174 vimvars[idx].vv_nr = val;
17178 * Get number v: variable value.
17180 long
17181 get_vim_var_nr(idx)
17182 int idx;
17184 return vimvars[idx].vv_nr;
17187 #if defined(FEAT_AUTOCMD) || defined(PROTO)
17189 * Get string v: variable value. Uses a static buffer, can only be used once.
17191 char_u *
17192 get_vim_var_str(idx)
17193 int idx;
17195 return get_tv_string(&vimvars[idx].vv_tv);
17197 #endif
17200 * Set v:count, v:count1 and v:prevcount.
17202 void
17203 set_vcount(count, count1)
17204 long count;
17205 long count1;
17207 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
17208 vimvars[VV_COUNT].vv_nr = count;
17209 vimvars[VV_COUNT1].vv_nr = count1;
17213 * Set string v: variable to a copy of "val".
17215 void
17216 set_vim_var_string(idx, val, len)
17217 int idx;
17218 char_u *val;
17219 int len; /* length of "val" to use or -1 (whole string) */
17221 /* Need to do this (at least) once, since we can't initialize a union.
17222 * Will always be invoked when "v:progname" is set. */
17223 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
17225 vim_free(vimvars[idx].vv_str);
17226 if (val == NULL)
17227 vimvars[idx].vv_str = NULL;
17228 else if (len == -1)
17229 vimvars[idx].vv_str = vim_strsave(val);
17230 else
17231 vimvars[idx].vv_str = vim_strnsave(val, len);
17235 * Set v:register if needed.
17237 void
17238 set_reg_var(c)
17239 int c;
17241 char_u regname;
17243 if (c == 0 || c == ' ')
17244 regname = '"';
17245 else
17246 regname = c;
17247 /* Avoid free/alloc when the value is already right. */
17248 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
17249 set_vim_var_string(VV_REG, &regname, 1);
17253 * Get or set v:exception. If "oldval" == NULL, return the current value.
17254 * Otherwise, restore the value to "oldval" and return NULL.
17255 * Must always be called in pairs to save and restore v:exception! Does not
17256 * take care of memory allocations.
17258 char_u *
17259 v_exception(oldval)
17260 char_u *oldval;
17262 if (oldval == NULL)
17263 return vimvars[VV_EXCEPTION].vv_str;
17265 vimvars[VV_EXCEPTION].vv_str = oldval;
17266 return NULL;
17270 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
17271 * Otherwise, restore the value to "oldval" and return NULL.
17272 * Must always be called in pairs to save and restore v:throwpoint! Does not
17273 * take care of memory allocations.
17275 char_u *
17276 v_throwpoint(oldval)
17277 char_u *oldval;
17279 if (oldval == NULL)
17280 return vimvars[VV_THROWPOINT].vv_str;
17282 vimvars[VV_THROWPOINT].vv_str = oldval;
17283 return NULL;
17286 #if defined(FEAT_AUTOCMD) || defined(PROTO)
17288 * Set v:cmdarg.
17289 * If "eap" != NULL, use "eap" to generate the value and return the old value.
17290 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
17291 * Must always be called in pairs!
17293 char_u *
17294 set_cmdarg(eap, oldarg)
17295 exarg_T *eap;
17296 char_u *oldarg;
17298 char_u *oldval;
17299 char_u *newval;
17300 unsigned len;
17302 oldval = vimvars[VV_CMDARG].vv_str;
17303 if (eap == NULL)
17305 vim_free(oldval);
17306 vimvars[VV_CMDARG].vv_str = oldarg;
17307 return NULL;
17310 if (eap->force_bin == FORCE_BIN)
17311 len = 6;
17312 else if (eap->force_bin == FORCE_NOBIN)
17313 len = 8;
17314 else
17315 len = 0;
17317 if (eap->read_edit)
17318 len += 7;
17320 if (eap->force_ff != 0)
17321 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
17322 # ifdef FEAT_MBYTE
17323 if (eap->force_enc != 0)
17324 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
17325 if (eap->bad_char != 0)
17326 len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
17327 # endif
17329 newval = alloc(len + 1);
17330 if (newval == NULL)
17331 return NULL;
17333 if (eap->force_bin == FORCE_BIN)
17334 sprintf((char *)newval, " ++bin");
17335 else if (eap->force_bin == FORCE_NOBIN)
17336 sprintf((char *)newval, " ++nobin");
17337 else
17338 *newval = NUL;
17340 if (eap->read_edit)
17341 STRCAT(newval, " ++edit");
17343 if (eap->force_ff != 0)
17344 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
17345 eap->cmd + eap->force_ff);
17346 # ifdef FEAT_MBYTE
17347 if (eap->force_enc != 0)
17348 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
17349 eap->cmd + eap->force_enc);
17350 if (eap->bad_char != 0)
17351 sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
17352 eap->cmd + eap->bad_char);
17353 # endif
17354 vimvars[VV_CMDARG].vv_str = newval;
17355 return oldval;
17357 #endif
17360 * Get the value of internal variable "name".
17361 * Return OK or FAIL.
17363 static int
17364 get_var_tv(name, len, rettv, verbose)
17365 char_u *name;
17366 int len; /* length of "name" */
17367 typval_T *rettv; /* NULL when only checking existence */
17368 int verbose; /* may give error message */
17370 int ret = OK;
17371 typval_T *tv = NULL;
17372 typval_T atv;
17373 dictitem_T *v;
17374 int cc;
17376 /* truncate the name, so that we can use strcmp() */
17377 cc = name[len];
17378 name[len] = NUL;
17381 * Check for "b:changedtick".
17383 if (STRCMP(name, "b:changedtick") == 0)
17385 atv.v_type = VAR_NUMBER;
17386 atv.vval.v_number = curbuf->b_changedtick;
17387 tv = &atv;
17391 * Check for user-defined variables.
17393 else
17395 v = find_var(name, NULL);
17396 if (v != NULL)
17397 tv = &v->di_tv;
17400 if (tv == NULL)
17402 if (rettv != NULL && verbose)
17403 EMSG2(_(e_undefvar), name);
17404 ret = FAIL;
17406 else if (rettv != NULL)
17407 copy_tv(tv, rettv);
17409 name[len] = cc;
17411 return ret;
17415 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
17416 * Also handle function call with Funcref variable: func(expr)
17417 * Can all be combined: dict.func(expr)[idx]['func'](expr)
17419 static int
17420 handle_subscript(arg, rettv, evaluate, verbose)
17421 char_u **arg;
17422 typval_T *rettv;
17423 int evaluate; /* do more than finding the end */
17424 int verbose; /* give error messages */
17426 int ret = OK;
17427 dict_T *selfdict = NULL;
17428 char_u *s;
17429 int len;
17430 typval_T functv;
17432 while (ret == OK
17433 && (**arg == '['
17434 || (**arg == '.' && rettv->v_type == VAR_DICT)
17435 || (**arg == '(' && rettv->v_type == VAR_FUNC))
17436 && !vim_iswhite(*(*arg - 1)))
17438 if (**arg == '(')
17440 /* need to copy the funcref so that we can clear rettv */
17441 functv = *rettv;
17442 rettv->v_type = VAR_UNKNOWN;
17444 /* Invoke the function. Recursive! */
17445 s = functv.vval.v_string;
17446 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
17447 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
17448 &len, evaluate, selfdict);
17450 /* Clear the funcref afterwards, so that deleting it while
17451 * evaluating the arguments is possible (see test55). */
17452 clear_tv(&functv);
17454 /* Stop the expression evaluation when immediately aborting on
17455 * error, or when an interrupt occurred or an exception was thrown
17456 * but not caught. */
17457 if (aborting())
17459 if (ret == OK)
17460 clear_tv(rettv);
17461 ret = FAIL;
17463 dict_unref(selfdict);
17464 selfdict = NULL;
17466 else /* **arg == '[' || **arg == '.' */
17468 dict_unref(selfdict);
17469 if (rettv->v_type == VAR_DICT)
17471 selfdict = rettv->vval.v_dict;
17472 if (selfdict != NULL)
17473 ++selfdict->dv_refcount;
17475 else
17476 selfdict = NULL;
17477 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
17479 clear_tv(rettv);
17480 ret = FAIL;
17484 dict_unref(selfdict);
17485 return ret;
17489 * Allocate memory for a variable type-value, and make it emtpy (0 or NULL
17490 * value).
17492 static typval_T *
17493 alloc_tv()
17495 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
17499 * Allocate memory for a variable type-value, and assign a string to it.
17500 * The string "s" must have been allocated, it is consumed.
17501 * Return NULL for out of memory, the variable otherwise.
17503 static typval_T *
17504 alloc_string_tv(s)
17505 char_u *s;
17507 typval_T *rettv;
17509 rettv = alloc_tv();
17510 if (rettv != NULL)
17512 rettv->v_type = VAR_STRING;
17513 rettv->vval.v_string = s;
17515 else
17516 vim_free(s);
17517 return rettv;
17521 * Free the memory for a variable type-value.
17523 void
17524 free_tv(varp)
17525 typval_T *varp;
17527 if (varp != NULL)
17529 switch (varp->v_type)
17531 case VAR_FUNC:
17532 func_unref(varp->vval.v_string);
17533 /*FALLTHROUGH*/
17534 case VAR_STRING:
17535 vim_free(varp->vval.v_string);
17536 break;
17537 case VAR_LIST:
17538 list_unref(varp->vval.v_list);
17539 break;
17540 case VAR_DICT:
17541 dict_unref(varp->vval.v_dict);
17542 break;
17543 case VAR_NUMBER:
17544 case VAR_UNKNOWN:
17545 break;
17546 default:
17547 EMSG2(_(e_intern2), "free_tv()");
17548 break;
17550 vim_free(varp);
17555 * Free the memory for a variable value and set the value to NULL or 0.
17557 void
17558 clear_tv(varp)
17559 typval_T *varp;
17561 if (varp != NULL)
17563 switch (varp->v_type)
17565 case VAR_FUNC:
17566 func_unref(varp->vval.v_string);
17567 /*FALLTHROUGH*/
17568 case VAR_STRING:
17569 vim_free(varp->vval.v_string);
17570 varp->vval.v_string = NULL;
17571 break;
17572 case VAR_LIST:
17573 list_unref(varp->vval.v_list);
17574 varp->vval.v_list = NULL;
17575 break;
17576 case VAR_DICT:
17577 dict_unref(varp->vval.v_dict);
17578 varp->vval.v_dict = NULL;
17579 break;
17580 case VAR_NUMBER:
17581 varp->vval.v_number = 0;
17582 break;
17583 case VAR_UNKNOWN:
17584 break;
17585 default:
17586 EMSG2(_(e_intern2), "clear_tv()");
17588 varp->v_lock = 0;
17593 * Set the value of a variable to NULL without freeing items.
17595 static void
17596 init_tv(varp)
17597 typval_T *varp;
17599 if (varp != NULL)
17600 vim_memset(varp, 0, sizeof(typval_T));
17604 * Get the number value of a variable.
17605 * If it is a String variable, uses vim_str2nr().
17606 * For incompatible types, return 0.
17607 * get_tv_number_chk() is similar to get_tv_number(), but informs the
17608 * caller of incompatible types: it sets *denote to TRUE if "denote"
17609 * is not NULL or returns -1 otherwise.
17611 static long
17612 get_tv_number(varp)
17613 typval_T *varp;
17615 int error = FALSE;
17617 return get_tv_number_chk(varp, &error); /* return 0L on error */
17620 long
17621 get_tv_number_chk(varp, denote)
17622 typval_T *varp;
17623 int *denote;
17625 long n = 0L;
17627 switch (varp->v_type)
17629 case VAR_NUMBER:
17630 return (long)(varp->vval.v_number);
17631 case VAR_FUNC:
17632 EMSG(_("E703: Using a Funcref as a number"));
17633 break;
17634 case VAR_STRING:
17635 if (varp->vval.v_string != NULL)
17636 vim_str2nr(varp->vval.v_string, NULL, NULL,
17637 TRUE, TRUE, &n, NULL);
17638 return n;
17639 case VAR_LIST:
17640 EMSG(_("E745: Using a List as a number"));
17641 break;
17642 case VAR_DICT:
17643 EMSG(_("E728: Using a Dictionary as a number"));
17644 break;
17645 default:
17646 EMSG2(_(e_intern2), "get_tv_number()");
17647 break;
17649 if (denote == NULL) /* useful for values that must be unsigned */
17650 n = -1;
17651 else
17652 *denote = TRUE;
17653 return n;
17657 * Get the lnum from the first argument.
17658 * Also accepts ".", "$", etc., but that only works for the current buffer.
17659 * Returns -1 on error.
17661 static linenr_T
17662 get_tv_lnum(argvars)
17663 typval_T *argvars;
17665 typval_T rettv;
17666 linenr_T lnum;
17668 lnum = get_tv_number_chk(&argvars[0], NULL);
17669 if (lnum == 0) /* no valid number, try using line() */
17671 rettv.v_type = VAR_NUMBER;
17672 f_line(argvars, &rettv);
17673 lnum = rettv.vval.v_number;
17674 clear_tv(&rettv);
17676 return lnum;
17680 * Get the lnum from the first argument.
17681 * Also accepts "$", then "buf" is used.
17682 * Returns 0 on error.
17684 static linenr_T
17685 get_tv_lnum_buf(argvars, buf)
17686 typval_T *argvars;
17687 buf_T *buf;
17689 if (argvars[0].v_type == VAR_STRING
17690 && argvars[0].vval.v_string != NULL
17691 && argvars[0].vval.v_string[0] == '$'
17692 && buf != NULL)
17693 return buf->b_ml.ml_line_count;
17694 return get_tv_number_chk(&argvars[0], NULL);
17698 * Get the string value of a variable.
17699 * If it is a Number variable, the number is converted into a string.
17700 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
17701 * get_tv_string_buf() uses a given buffer.
17702 * If the String variable has never been set, return an empty string.
17703 * Never returns NULL;
17704 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
17705 * NULL on error.
17707 static char_u *
17708 get_tv_string(varp)
17709 typval_T *varp;
17711 static char_u mybuf[NUMBUFLEN];
17713 return get_tv_string_buf(varp, mybuf);
17716 static char_u *
17717 get_tv_string_buf(varp, buf)
17718 typval_T *varp;
17719 char_u *buf;
17721 char_u *res = get_tv_string_buf_chk(varp, buf);
17723 return res != NULL ? res : (char_u *)"";
17726 char_u *
17727 get_tv_string_chk(varp)
17728 typval_T *varp;
17730 static char_u mybuf[NUMBUFLEN];
17732 return get_tv_string_buf_chk(varp, mybuf);
17735 static char_u *
17736 get_tv_string_buf_chk(varp, buf)
17737 typval_T *varp;
17738 char_u *buf;
17740 switch (varp->v_type)
17742 case VAR_NUMBER:
17743 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
17744 return buf;
17745 case VAR_FUNC:
17746 EMSG(_("E729: using Funcref as a String"));
17747 break;
17748 case VAR_LIST:
17749 EMSG(_("E730: using List as a String"));
17750 break;
17751 case VAR_DICT:
17752 EMSG(_("E731: using Dictionary as a String"));
17753 break;
17754 case VAR_STRING:
17755 if (varp->vval.v_string != NULL)
17756 return varp->vval.v_string;
17757 return (char_u *)"";
17758 default:
17759 EMSG2(_(e_intern2), "get_tv_string_buf()");
17760 break;
17762 return NULL;
17766 * Find variable "name" in the list of variables.
17767 * Return a pointer to it if found, NULL if not found.
17768 * Careful: "a:0" variables don't have a name.
17769 * When "htp" is not NULL we are writing to the variable, set "htp" to the
17770 * hashtab_T used.
17772 static dictitem_T *
17773 find_var(name, htp)
17774 char_u *name;
17775 hashtab_T **htp;
17777 char_u *varname;
17778 hashtab_T *ht;
17780 ht = find_var_ht(name, &varname);
17781 if (htp != NULL)
17782 *htp = ht;
17783 if (ht == NULL)
17784 return NULL;
17785 return find_var_in_ht(ht, varname, htp != NULL);
17789 * Find variable "varname" in hashtab "ht".
17790 * Returns NULL if not found.
17792 static dictitem_T *
17793 find_var_in_ht(ht, varname, writing)
17794 hashtab_T *ht;
17795 char_u *varname;
17796 int writing;
17798 hashitem_T *hi;
17800 if (*varname == NUL)
17802 /* Must be something like "s:", otherwise "ht" would be NULL. */
17803 switch (varname[-2])
17805 case 's': return &SCRIPT_SV(current_SID).sv_var;
17806 case 'g': return &globvars_var;
17807 case 'v': return &vimvars_var;
17808 case 'b': return &curbuf->b_bufvar;
17809 case 'w': return &curwin->w_winvar;
17810 #ifdef FEAT_WINDOWS
17811 case 't': return &curtab->tp_winvar;
17812 #endif
17813 case 'l': return current_funccal == NULL
17814 ? NULL : &current_funccal->l_vars_var;
17815 case 'a': return current_funccal == NULL
17816 ? NULL : &current_funccal->l_avars_var;
17818 return NULL;
17821 hi = hash_find(ht, varname);
17822 if (HASHITEM_EMPTY(hi))
17824 /* For global variables we may try auto-loading the script. If it
17825 * worked find the variable again. Don't auto-load a script if it was
17826 * loaded already, otherwise it would be loaded every time when
17827 * checking if a function name is a Funcref variable. */
17828 if (ht == &globvarht && !writing
17829 && script_autoload(varname, FALSE) && !aborting())
17830 hi = hash_find(ht, varname);
17831 if (HASHITEM_EMPTY(hi))
17832 return NULL;
17834 return HI2DI(hi);
17838 * Find the hashtab used for a variable name.
17839 * Set "varname" to the start of name without ':'.
17841 static hashtab_T *
17842 find_var_ht(name, varname)
17843 char_u *name;
17844 char_u **varname;
17846 hashitem_T *hi;
17848 if (name[1] != ':')
17850 /* The name must not start with a colon or #. */
17851 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
17852 return NULL;
17853 *varname = name;
17855 /* "version" is "v:version" in all scopes */
17856 hi = hash_find(&compat_hashtab, name);
17857 if (!HASHITEM_EMPTY(hi))
17858 return &compat_hashtab;
17860 if (current_funccal == NULL)
17861 return &globvarht; /* global variable */
17862 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
17864 *varname = name + 2;
17865 if (*name == 'g') /* global variable */
17866 return &globvarht;
17867 /* There must be no ':' or '#' in the rest of the name, unless g: is used
17869 if (vim_strchr(name + 2, ':') != NULL
17870 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
17871 return NULL;
17872 if (*name == 'b') /* buffer variable */
17873 return &curbuf->b_vars.dv_hashtab;
17874 if (*name == 'w') /* window variable */
17875 return &curwin->w_vars.dv_hashtab;
17876 #ifdef FEAT_WINDOWS
17877 if (*name == 't') /* tab page variable */
17878 return &curtab->tp_vars.dv_hashtab;
17879 #endif
17880 if (*name == 'v') /* v: variable */
17881 return &vimvarht;
17882 if (*name == 'a' && current_funccal != NULL) /* function argument */
17883 return &current_funccal->l_avars.dv_hashtab;
17884 if (*name == 'l' && current_funccal != NULL) /* local function variable */
17885 return &current_funccal->l_vars.dv_hashtab;
17886 if (*name == 's' /* script variable */
17887 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
17888 return &SCRIPT_VARS(current_SID);
17889 return NULL;
17893 * Get the string value of a (global/local) variable.
17894 * Returns NULL when it doesn't exist.
17896 char_u *
17897 get_var_value(name)
17898 char_u *name;
17900 dictitem_T *v;
17902 v = find_var(name, NULL);
17903 if (v == NULL)
17904 return NULL;
17905 return get_tv_string(&v->di_tv);
17909 * Allocate a new hashtab for a sourced script. It will be used while
17910 * sourcing this script and when executing functions defined in the script.
17912 void
17913 new_script_vars(id)
17914 scid_T id;
17916 int i;
17917 hashtab_T *ht;
17918 scriptvar_T *sv;
17920 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
17922 /* Re-allocating ga_data means that an ht_array pointing to
17923 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
17924 * at its init value. Also reset "v_dict", it's always the same. */
17925 for (i = 1; i <= ga_scripts.ga_len; ++i)
17927 ht = &SCRIPT_VARS(i);
17928 if (ht->ht_mask == HT_INIT_SIZE - 1)
17929 ht->ht_array = ht->ht_smallarray;
17930 sv = &SCRIPT_SV(i);
17931 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
17934 while (ga_scripts.ga_len < id)
17936 sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
17937 init_var_dict(&sv->sv_dict, &sv->sv_var);
17938 ++ga_scripts.ga_len;
17944 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
17945 * point to it.
17947 void
17948 init_var_dict(dict, dict_var)
17949 dict_T *dict;
17950 dictitem_T *dict_var;
17952 hash_init(&dict->dv_hashtab);
17953 dict->dv_refcount = 99999;
17954 dict_var->di_tv.vval.v_dict = dict;
17955 dict_var->di_tv.v_type = VAR_DICT;
17956 dict_var->di_tv.v_lock = VAR_FIXED;
17957 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
17958 dict_var->di_key[0] = NUL;
17962 * Clean up a list of internal variables.
17963 * Frees all allocated variables and the value they contain.
17964 * Clears hashtab "ht", does not free it.
17966 void
17967 vars_clear(ht)
17968 hashtab_T *ht;
17970 vars_clear_ext(ht, TRUE);
17974 * Like vars_clear(), but only free the value if "free_val" is TRUE.
17976 static void
17977 vars_clear_ext(ht, free_val)
17978 hashtab_T *ht;
17979 int free_val;
17981 int todo;
17982 hashitem_T *hi;
17983 dictitem_T *v;
17985 hash_lock(ht);
17986 todo = (int)ht->ht_used;
17987 for (hi = ht->ht_array; todo > 0; ++hi)
17989 if (!HASHITEM_EMPTY(hi))
17991 --todo;
17993 /* Free the variable. Don't remove it from the hashtab,
17994 * ht_array might change then. hash_clear() takes care of it
17995 * later. */
17996 v = HI2DI(hi);
17997 if (free_val)
17998 clear_tv(&v->di_tv);
17999 if ((v->di_flags & DI_FLAGS_FIX) == 0)
18000 vim_free(v);
18003 hash_clear(ht);
18004 ht->ht_used = 0;
18008 * Delete a variable from hashtab "ht" at item "hi".
18009 * Clear the variable value and free the dictitem.
18011 static void
18012 delete_var(ht, hi)
18013 hashtab_T *ht;
18014 hashitem_T *hi;
18016 dictitem_T *di = HI2DI(hi);
18018 hash_remove(ht, hi);
18019 clear_tv(&di->di_tv);
18020 vim_free(di);
18024 * List the value of one internal variable.
18026 static void
18027 list_one_var(v, prefix, first)
18028 dictitem_T *v;
18029 char_u *prefix;
18030 int *first;
18032 char_u *tofree;
18033 char_u *s;
18034 char_u numbuf[NUMBUFLEN];
18036 s = echo_string(&v->di_tv, &tofree, numbuf, ++current_copyID);
18037 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
18038 s == NULL ? (char_u *)"" : s, first);
18039 vim_free(tofree);
18042 static void
18043 list_one_var_a(prefix, name, type, string, first)
18044 char_u *prefix;
18045 char_u *name;
18046 int type;
18047 char_u *string;
18048 int *first; /* when TRUE clear rest of screen and set to FALSE */
18050 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
18051 msg_start();
18052 msg_puts(prefix);
18053 if (name != NULL) /* "a:" vars don't have a name stored */
18054 msg_puts(name);
18055 msg_putchar(' ');
18056 msg_advance(22);
18057 if (type == VAR_NUMBER)
18058 msg_putchar('#');
18059 else if (type == VAR_FUNC)
18060 msg_putchar('*');
18061 else if (type == VAR_LIST)
18063 msg_putchar('[');
18064 if (*string == '[')
18065 ++string;
18067 else if (type == VAR_DICT)
18069 msg_putchar('{');
18070 if (*string == '{')
18071 ++string;
18073 else
18074 msg_putchar(' ');
18076 msg_outtrans(string);
18078 if (type == VAR_FUNC)
18079 msg_puts((char_u *)"()");
18080 if (*first)
18082 msg_clr_eos();
18083 *first = FALSE;
18088 * Set variable "name" to value in "tv".
18089 * If the variable already exists, the value is updated.
18090 * Otherwise the variable is created.
18092 static void
18093 set_var(name, tv, copy)
18094 char_u *name;
18095 typval_T *tv;
18096 int copy; /* make copy of value in "tv" */
18098 dictitem_T *v;
18099 char_u *varname;
18100 hashtab_T *ht;
18101 char_u *p;
18103 if (tv->v_type == VAR_FUNC)
18105 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
18106 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
18107 ? name[2] : name[0]))
18109 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
18110 return;
18112 if (function_exists(name))
18114 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
18115 name);
18116 return;
18120 ht = find_var_ht(name, &varname);
18121 if (ht == NULL || *varname == NUL)
18123 EMSG2(_(e_illvar), name);
18124 return;
18127 v = find_var_in_ht(ht, varname, TRUE);
18128 if (v != NULL)
18130 /* existing variable, need to clear the value */
18131 if (var_check_ro(v->di_flags, name)
18132 || tv_check_lock(v->di_tv.v_lock, name))
18133 return;
18134 if (v->di_tv.v_type != tv->v_type
18135 && !((v->di_tv.v_type == VAR_STRING
18136 || v->di_tv.v_type == VAR_NUMBER)
18137 && (tv->v_type == VAR_STRING
18138 || tv->v_type == VAR_NUMBER)))
18140 EMSG2(_("E706: Variable type mismatch for: %s"), name);
18141 return;
18145 * Handle setting internal v: variables separately: we don't change
18146 * the type.
18148 if (ht == &vimvarht)
18150 if (v->di_tv.v_type == VAR_STRING)
18152 vim_free(v->di_tv.vval.v_string);
18153 if (copy || tv->v_type != VAR_STRING)
18154 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
18155 else
18157 /* Take over the string to avoid an extra alloc/free. */
18158 v->di_tv.vval.v_string = tv->vval.v_string;
18159 tv->vval.v_string = NULL;
18162 else if (v->di_tv.v_type != VAR_NUMBER)
18163 EMSG2(_(e_intern2), "set_var()");
18164 else
18165 v->di_tv.vval.v_number = get_tv_number(tv);
18166 return;
18169 clear_tv(&v->di_tv);
18171 else /* add a new variable */
18173 /* Can't add "v:" variable. */
18174 if (ht == &vimvarht)
18176 EMSG2(_(e_illvar), name);
18177 return;
18180 /* Make sure the variable name is valid. */
18181 for (p = varname; *p != NUL; ++p)
18182 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
18183 && *p != AUTOLOAD_CHAR)
18185 EMSG2(_(e_illvar), varname);
18186 return;
18189 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
18190 + STRLEN(varname)));
18191 if (v == NULL)
18192 return;
18193 STRCPY(v->di_key, varname);
18194 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
18196 vim_free(v);
18197 return;
18199 v->di_flags = 0;
18202 if (copy || tv->v_type == VAR_NUMBER)
18203 copy_tv(tv, &v->di_tv);
18204 else
18206 v->di_tv = *tv;
18207 v->di_tv.v_lock = 0;
18208 init_tv(tv);
18213 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
18214 * Also give an error message.
18216 static int
18217 var_check_ro(flags, name)
18218 int flags;
18219 char_u *name;
18221 if (flags & DI_FLAGS_RO)
18223 EMSG2(_(e_readonlyvar), name);
18224 return TRUE;
18226 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
18228 EMSG2(_(e_readonlysbx), name);
18229 return TRUE;
18231 return FALSE;
18235 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
18236 * Also give an error message.
18238 static int
18239 var_check_fixed(flags, name)
18240 int flags;
18241 char_u *name;
18243 if (flags & DI_FLAGS_FIX)
18245 EMSG2(_("E795: Cannot delete variable %s"), name);
18246 return TRUE;
18248 return FALSE;
18252 * Return TRUE if typeval "tv" is set to be locked (immutable).
18253 * Also give an error message, using "name".
18255 static int
18256 tv_check_lock(lock, name)
18257 int lock;
18258 char_u *name;
18260 if (lock & VAR_LOCKED)
18262 EMSG2(_("E741: Value is locked: %s"),
18263 name == NULL ? (char_u *)_("Unknown") : name);
18264 return TRUE;
18266 if (lock & VAR_FIXED)
18268 EMSG2(_("E742: Cannot change value of %s"),
18269 name == NULL ? (char_u *)_("Unknown") : name);
18270 return TRUE;
18272 return FALSE;
18276 * Copy the values from typval_T "from" to typval_T "to".
18277 * When needed allocates string or increases reference count.
18278 * Does not make a copy of a list or dict but copies the reference!
18280 static void
18281 copy_tv(from, to)
18282 typval_T *from;
18283 typval_T *to;
18285 to->v_type = from->v_type;
18286 to->v_lock = 0;
18287 switch (from->v_type)
18289 case VAR_NUMBER:
18290 to->vval.v_number = from->vval.v_number;
18291 break;
18292 case VAR_STRING:
18293 case VAR_FUNC:
18294 if (from->vval.v_string == NULL)
18295 to->vval.v_string = NULL;
18296 else
18298 to->vval.v_string = vim_strsave(from->vval.v_string);
18299 if (from->v_type == VAR_FUNC)
18300 func_ref(to->vval.v_string);
18302 break;
18303 case VAR_LIST:
18304 if (from->vval.v_list == NULL)
18305 to->vval.v_list = NULL;
18306 else
18308 to->vval.v_list = from->vval.v_list;
18309 ++to->vval.v_list->lv_refcount;
18311 break;
18312 case VAR_DICT:
18313 if (from->vval.v_dict == NULL)
18314 to->vval.v_dict = NULL;
18315 else
18317 to->vval.v_dict = from->vval.v_dict;
18318 ++to->vval.v_dict->dv_refcount;
18320 break;
18321 default:
18322 EMSG2(_(e_intern2), "copy_tv()");
18323 break;
18328 * Make a copy of an item.
18329 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
18330 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
18331 * reference to an already copied list/dict can be used.
18332 * Returns FAIL or OK.
18334 static int
18335 item_copy(from, to, deep, copyID)
18336 typval_T *from;
18337 typval_T *to;
18338 int deep;
18339 int copyID;
18341 static int recurse = 0;
18342 int ret = OK;
18344 if (recurse >= DICT_MAXNEST)
18346 EMSG(_("E698: variable nested too deep for making a copy"));
18347 return FAIL;
18349 ++recurse;
18351 switch (from->v_type)
18353 case VAR_NUMBER:
18354 case VAR_STRING:
18355 case VAR_FUNC:
18356 copy_tv(from, to);
18357 break;
18358 case VAR_LIST:
18359 to->v_type = VAR_LIST;
18360 to->v_lock = 0;
18361 if (from->vval.v_list == NULL)
18362 to->vval.v_list = NULL;
18363 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
18365 /* use the copy made earlier */
18366 to->vval.v_list = from->vval.v_list->lv_copylist;
18367 ++to->vval.v_list->lv_refcount;
18369 else
18370 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
18371 if (to->vval.v_list == NULL)
18372 ret = FAIL;
18373 break;
18374 case VAR_DICT:
18375 to->v_type = VAR_DICT;
18376 to->v_lock = 0;
18377 if (from->vval.v_dict == NULL)
18378 to->vval.v_dict = NULL;
18379 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
18381 /* use the copy made earlier */
18382 to->vval.v_dict = from->vval.v_dict->dv_copydict;
18383 ++to->vval.v_dict->dv_refcount;
18385 else
18386 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
18387 if (to->vval.v_dict == NULL)
18388 ret = FAIL;
18389 break;
18390 default:
18391 EMSG2(_(e_intern2), "item_copy()");
18392 ret = FAIL;
18394 --recurse;
18395 return ret;
18399 * ":echo expr1 ..." print each argument separated with a space, add a
18400 * newline at the end.
18401 * ":echon expr1 ..." print each argument plain.
18403 void
18404 ex_echo(eap)
18405 exarg_T *eap;
18407 char_u *arg = eap->arg;
18408 typval_T rettv;
18409 char_u *tofree;
18410 char_u *p;
18411 int needclr = TRUE;
18412 int atstart = TRUE;
18413 char_u numbuf[NUMBUFLEN];
18415 if (eap->skip)
18416 ++emsg_skip;
18417 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
18419 p = arg;
18420 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
18423 * Report the invalid expression unless the expression evaluation
18424 * has been cancelled due to an aborting error, an interrupt, or an
18425 * exception.
18427 if (!aborting())
18428 EMSG2(_(e_invexpr2), p);
18429 break;
18431 if (!eap->skip)
18433 if (atstart)
18435 atstart = FALSE;
18436 /* Call msg_start() after eval1(), evaluating the expression
18437 * may cause a message to appear. */
18438 if (eap->cmdidx == CMD_echo)
18439 msg_start();
18441 else if (eap->cmdidx == CMD_echo)
18442 msg_puts_attr((char_u *)" ", echo_attr);
18443 p = echo_string(&rettv, &tofree, numbuf, ++current_copyID);
18444 if (p != NULL)
18445 for ( ; *p != NUL && !got_int; ++p)
18447 if (*p == '\n' || *p == '\r' || *p == TAB)
18449 if (*p != TAB && needclr)
18451 /* remove any text still there from the command */
18452 msg_clr_eos();
18453 needclr = FALSE;
18455 msg_putchar_attr(*p, echo_attr);
18457 else
18459 #ifdef FEAT_MBYTE
18460 if (has_mbyte)
18462 int i = (*mb_ptr2len)(p);
18464 (void)msg_outtrans_len_attr(p, i, echo_attr);
18465 p += i - 1;
18467 else
18468 #endif
18469 (void)msg_outtrans_len_attr(p, 1, echo_attr);
18472 vim_free(tofree);
18474 clear_tv(&rettv);
18475 arg = skipwhite(arg);
18477 eap->nextcmd = check_nextcmd(arg);
18479 if (eap->skip)
18480 --emsg_skip;
18481 else
18483 /* remove text that may still be there from the command */
18484 if (needclr)
18485 msg_clr_eos();
18486 if (eap->cmdidx == CMD_echo)
18487 msg_end();
18492 * ":echohl {name}".
18494 void
18495 ex_echohl(eap)
18496 exarg_T *eap;
18498 int id;
18500 id = syn_name2id(eap->arg);
18501 if (id == 0)
18502 echo_attr = 0;
18503 else
18504 echo_attr = syn_id2attr(id);
18508 * ":execute expr1 ..." execute the result of an expression.
18509 * ":echomsg expr1 ..." Print a message
18510 * ":echoerr expr1 ..." Print an error
18511 * Each gets spaces around each argument and a newline at the end for
18512 * echo commands
18514 void
18515 ex_execute(eap)
18516 exarg_T *eap;
18518 char_u *arg = eap->arg;
18519 typval_T rettv;
18520 int ret = OK;
18521 char_u *p;
18522 garray_T ga;
18523 int len;
18524 int save_did_emsg;
18526 ga_init2(&ga, 1, 80);
18528 if (eap->skip)
18529 ++emsg_skip;
18530 while (*arg != NUL && *arg != '|' && *arg != '\n')
18532 p = arg;
18533 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
18536 * Report the invalid expression unless the expression evaluation
18537 * has been cancelled due to an aborting error, an interrupt, or an
18538 * exception.
18540 if (!aborting())
18541 EMSG2(_(e_invexpr2), p);
18542 ret = FAIL;
18543 break;
18546 if (!eap->skip)
18548 p = get_tv_string(&rettv);
18549 len = (int)STRLEN(p);
18550 if (ga_grow(&ga, len + 2) == FAIL)
18552 clear_tv(&rettv);
18553 ret = FAIL;
18554 break;
18556 if (ga.ga_len)
18557 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
18558 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
18559 ga.ga_len += len;
18562 clear_tv(&rettv);
18563 arg = skipwhite(arg);
18566 if (ret != FAIL && ga.ga_data != NULL)
18568 if (eap->cmdidx == CMD_echomsg)
18570 MSG_ATTR(ga.ga_data, echo_attr);
18571 out_flush();
18573 else if (eap->cmdidx == CMD_echoerr)
18575 /* We don't want to abort following commands, restore did_emsg. */
18576 save_did_emsg = did_emsg;
18577 EMSG((char_u *)ga.ga_data);
18578 if (!force_abort)
18579 did_emsg = save_did_emsg;
18581 else if (eap->cmdidx == CMD_execute)
18582 do_cmdline((char_u *)ga.ga_data,
18583 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
18586 ga_clear(&ga);
18588 if (eap->skip)
18589 --emsg_skip;
18591 eap->nextcmd = check_nextcmd(arg);
18595 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
18596 * "arg" points to the "&" or '+' when called, to "option" when returning.
18597 * Returns NULL when no option name found. Otherwise pointer to the char
18598 * after the option name.
18600 static char_u *
18601 find_option_end(arg, opt_flags)
18602 char_u **arg;
18603 int *opt_flags;
18605 char_u *p = *arg;
18607 ++p;
18608 if (*p == 'g' && p[1] == ':')
18610 *opt_flags = OPT_GLOBAL;
18611 p += 2;
18613 else if (*p == 'l' && p[1] == ':')
18615 *opt_flags = OPT_LOCAL;
18616 p += 2;
18618 else
18619 *opt_flags = 0;
18621 if (!ASCII_ISALPHA(*p))
18622 return NULL;
18623 *arg = p;
18625 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
18626 p += 4; /* termcap option */
18627 else
18628 while (ASCII_ISALPHA(*p))
18629 ++p;
18630 return p;
18634 * ":function"
18636 void
18637 ex_function(eap)
18638 exarg_T *eap;
18640 char_u *theline;
18641 int j;
18642 int c;
18643 int saved_did_emsg;
18644 char_u *name = NULL;
18645 char_u *p;
18646 char_u *arg;
18647 char_u *line_arg = NULL;
18648 garray_T newargs;
18649 garray_T newlines;
18650 int varargs = FALSE;
18651 int mustend = FALSE;
18652 int flags = 0;
18653 ufunc_T *fp;
18654 int indent;
18655 int nesting;
18656 char_u *skip_until = NULL;
18657 dictitem_T *v;
18658 funcdict_T fudi;
18659 static int func_nr = 0; /* number for nameless function */
18660 int paren;
18661 hashtab_T *ht;
18662 int todo;
18663 hashitem_T *hi;
18664 int sourcing_lnum_off;
18667 * ":function" without argument: list functions.
18669 if (ends_excmd(*eap->arg))
18671 if (!eap->skip)
18673 todo = (int)func_hashtab.ht_used;
18674 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
18676 if (!HASHITEM_EMPTY(hi))
18678 --todo;
18679 fp = HI2UF(hi);
18680 if (!isdigit(*fp->uf_name))
18681 list_func_head(fp, FALSE);
18685 eap->nextcmd = check_nextcmd(eap->arg);
18686 return;
18690 * ":function /pat": list functions matching pattern.
18692 if (*eap->arg == '/')
18694 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
18695 if (!eap->skip)
18697 regmatch_T regmatch;
18699 c = *p;
18700 *p = NUL;
18701 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
18702 *p = c;
18703 if (regmatch.regprog != NULL)
18705 regmatch.rm_ic = p_ic;
18707 todo = (int)func_hashtab.ht_used;
18708 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
18710 if (!HASHITEM_EMPTY(hi))
18712 --todo;
18713 fp = HI2UF(hi);
18714 if (!isdigit(*fp->uf_name)
18715 && vim_regexec(&regmatch, fp->uf_name, 0))
18716 list_func_head(fp, FALSE);
18721 if (*p == '/')
18722 ++p;
18723 eap->nextcmd = check_nextcmd(p);
18724 return;
18728 * Get the function name. There are these situations:
18729 * func normal function name
18730 * "name" == func, "fudi.fd_dict" == NULL
18731 * dict.func new dictionary entry
18732 * "name" == NULL, "fudi.fd_dict" set,
18733 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
18734 * dict.func existing dict entry with a Funcref
18735 * "name" == func, "fudi.fd_dict" set,
18736 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
18737 * dict.func existing dict entry that's not a Funcref
18738 * "name" == NULL, "fudi.fd_dict" set,
18739 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
18741 p = eap->arg;
18742 name = trans_function_name(&p, eap->skip, 0, &fudi);
18743 paren = (vim_strchr(p, '(') != NULL);
18744 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
18747 * Return on an invalid expression in braces, unless the expression
18748 * evaluation has been cancelled due to an aborting error, an
18749 * interrupt, or an exception.
18751 if (!aborting())
18753 if (!eap->skip && fudi.fd_newkey != NULL)
18754 EMSG2(_(e_dictkey), fudi.fd_newkey);
18755 vim_free(fudi.fd_newkey);
18756 return;
18758 else
18759 eap->skip = TRUE;
18762 /* An error in a function call during evaluation of an expression in magic
18763 * braces should not cause the function not to be defined. */
18764 saved_did_emsg = did_emsg;
18765 did_emsg = FALSE;
18768 * ":function func" with only function name: list function.
18770 if (!paren)
18772 if (!ends_excmd(*skipwhite(p)))
18774 EMSG(_(e_trailing));
18775 goto ret_free;
18777 eap->nextcmd = check_nextcmd(p);
18778 if (eap->nextcmd != NULL)
18779 *p = NUL;
18780 if (!eap->skip && !got_int)
18782 fp = find_func(name);
18783 if (fp != NULL)
18785 list_func_head(fp, TRUE);
18786 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
18788 if (FUNCLINE(fp, j) == NULL)
18789 continue;
18790 msg_putchar('\n');
18791 msg_outnum((long)(j + 1));
18792 if (j < 9)
18793 msg_putchar(' ');
18794 if (j < 99)
18795 msg_putchar(' ');
18796 msg_prt_line(FUNCLINE(fp, j), FALSE);
18797 out_flush(); /* show a line at a time */
18798 ui_breakcheck();
18800 if (!got_int)
18802 msg_putchar('\n');
18803 msg_puts((char_u *)" endfunction");
18806 else
18807 emsg_funcname("E123: Undefined function: %s", name);
18809 goto ret_free;
18813 * ":function name(arg1, arg2)" Define function.
18815 p = skipwhite(p);
18816 if (*p != '(')
18818 if (!eap->skip)
18820 EMSG2(_("E124: Missing '(': %s"), eap->arg);
18821 goto ret_free;
18823 /* attempt to continue by skipping some text */
18824 if (vim_strchr(p, '(') != NULL)
18825 p = vim_strchr(p, '(');
18827 p = skipwhite(p + 1);
18829 ga_init2(&newargs, (int)sizeof(char_u *), 3);
18830 ga_init2(&newlines, (int)sizeof(char_u *), 3);
18832 if (!eap->skip)
18834 /* Check the name of the function. Unless it's a dictionary function
18835 * (that we are overwriting). */
18836 if (name != NULL)
18837 arg = name;
18838 else
18839 arg = fudi.fd_newkey;
18840 if (arg != NULL && (fudi.fd_di == NULL
18841 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
18843 if (*arg == K_SPECIAL)
18844 j = 3;
18845 else
18846 j = 0;
18847 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
18848 : eval_isnamec(arg[j])))
18849 ++j;
18850 if (arg[j] != NUL)
18851 emsg_funcname(_(e_invarg2), arg);
18856 * Isolate the arguments: "arg1, arg2, ...)"
18858 while (*p != ')')
18860 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
18862 varargs = TRUE;
18863 p += 3;
18864 mustend = TRUE;
18866 else
18868 arg = p;
18869 while (ASCII_ISALNUM(*p) || *p == '_')
18870 ++p;
18871 if (arg == p || isdigit(*arg)
18872 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
18873 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
18875 if (!eap->skip)
18876 EMSG2(_("E125: Illegal argument: %s"), arg);
18877 break;
18879 if (ga_grow(&newargs, 1) == FAIL)
18880 goto erret;
18881 c = *p;
18882 *p = NUL;
18883 arg = vim_strsave(arg);
18884 if (arg == NULL)
18885 goto erret;
18886 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
18887 *p = c;
18888 newargs.ga_len++;
18889 if (*p == ',')
18890 ++p;
18891 else
18892 mustend = TRUE;
18894 p = skipwhite(p);
18895 if (mustend && *p != ')')
18897 if (!eap->skip)
18898 EMSG2(_(e_invarg2), eap->arg);
18899 break;
18902 ++p; /* skip the ')' */
18904 /* find extra arguments "range", "dict" and "abort" */
18905 for (;;)
18907 p = skipwhite(p);
18908 if (STRNCMP(p, "range", 5) == 0)
18910 flags |= FC_RANGE;
18911 p += 5;
18913 else if (STRNCMP(p, "dict", 4) == 0)
18915 flags |= FC_DICT;
18916 p += 4;
18918 else if (STRNCMP(p, "abort", 5) == 0)
18920 flags |= FC_ABORT;
18921 p += 5;
18923 else
18924 break;
18927 /* When there is a line break use what follows for the function body.
18928 * Makes 'exe "func Test()\n...\nendfunc"' work. */
18929 if (*p == '\n')
18930 line_arg = p + 1;
18931 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
18932 EMSG(_(e_trailing));
18935 * Read the body of the function, until ":endfunction" is found.
18937 if (KeyTyped)
18939 /* Check if the function already exists, don't let the user type the
18940 * whole function before telling him it doesn't work! For a script we
18941 * need to skip the body to be able to find what follows. */
18942 if (!eap->skip && !eap->forceit)
18944 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
18945 EMSG(_(e_funcdict));
18946 else if (name != NULL && find_func(name) != NULL)
18947 emsg_funcname(e_funcexts, name);
18950 if (!eap->skip && did_emsg)
18951 goto erret;
18953 msg_putchar('\n'); /* don't overwrite the function name */
18954 cmdline_row = msg_row;
18957 indent = 2;
18958 nesting = 0;
18959 for (;;)
18961 msg_scroll = TRUE;
18962 need_wait_return = FALSE;
18963 sourcing_lnum_off = sourcing_lnum;
18965 if (line_arg != NULL)
18967 /* Use eap->arg, split up in parts by line breaks. */
18968 theline = line_arg;
18969 p = vim_strchr(theline, '\n');
18970 if (p == NULL)
18971 line_arg += STRLEN(line_arg);
18972 else
18974 *p = NUL;
18975 line_arg = p + 1;
18978 else if (eap->getline == NULL)
18979 theline = getcmdline(':', 0L, indent);
18980 else
18981 theline = eap->getline(':', eap->cookie, indent);
18982 if (KeyTyped)
18983 lines_left = Rows - 1;
18984 if (theline == NULL)
18986 EMSG(_("E126: Missing :endfunction"));
18987 goto erret;
18990 /* Detect line continuation: sourcing_lnum increased more than one. */
18991 if (sourcing_lnum > sourcing_lnum_off + 1)
18992 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
18993 else
18994 sourcing_lnum_off = 0;
18996 if (skip_until != NULL)
18998 /* between ":append" and "." and between ":python <<EOF" and "EOF"
18999 * don't check for ":endfunc". */
19000 if (STRCMP(theline, skip_until) == 0)
19002 vim_free(skip_until);
19003 skip_until = NULL;
19006 else
19008 /* skip ':' and blanks*/
19009 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
19012 /* Check for "endfunction". */
19013 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
19015 if (line_arg == NULL)
19016 vim_free(theline);
19017 break;
19020 /* Increase indent inside "if", "while", "for" and "try", decrease
19021 * at "end". */
19022 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
19023 indent -= 2;
19024 else if (STRNCMP(p, "if", 2) == 0
19025 || STRNCMP(p, "wh", 2) == 0
19026 || STRNCMP(p, "for", 3) == 0
19027 || STRNCMP(p, "try", 3) == 0)
19028 indent += 2;
19030 /* Check for defining a function inside this function. */
19031 if (checkforcmd(&p, "function", 2))
19033 if (*p == '!')
19034 p = skipwhite(p + 1);
19035 p += eval_fname_script(p);
19036 if (ASCII_ISALPHA(*p))
19038 vim_free(trans_function_name(&p, TRUE, 0, NULL));
19039 if (*skipwhite(p) == '(')
19041 ++nesting;
19042 indent += 2;
19047 /* Check for ":append" or ":insert". */
19048 p = skip_range(p, NULL);
19049 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
19050 || (p[0] == 'i'
19051 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
19052 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
19053 skip_until = vim_strsave((char_u *)".");
19055 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
19056 arg = skipwhite(skiptowhite(p));
19057 if (arg[0] == '<' && arg[1] =='<'
19058 && ((p[0] == 'p' && p[1] == 'y'
19059 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
19060 || (p[0] == 'p' && p[1] == 'e'
19061 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
19062 || (p[0] == 't' && p[1] == 'c'
19063 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
19064 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
19065 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
19066 || (p[0] == 'm' && p[1] == 'z'
19067 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
19070 /* ":python <<" continues until a dot, like ":append" */
19071 p = skipwhite(arg + 2);
19072 if (*p == NUL)
19073 skip_until = vim_strsave((char_u *)".");
19074 else
19075 skip_until = vim_strsave(p);
19079 /* Add the line to the function. */
19080 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
19082 if (line_arg == NULL)
19083 vim_free(theline);
19084 goto erret;
19087 /* Copy the line to newly allocated memory. get_one_sourceline()
19088 * allocates 250 bytes per line, this saves 80% on average. The cost
19089 * is an extra alloc/free. */
19090 p = vim_strsave(theline);
19091 if (p != NULL)
19093 if (line_arg == NULL)
19094 vim_free(theline);
19095 theline = p;
19098 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
19100 /* Add NULL lines for continuation lines, so that the line count is
19101 * equal to the index in the growarray. */
19102 while (sourcing_lnum_off-- > 0)
19103 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
19105 /* Check for end of eap->arg. */
19106 if (line_arg != NULL && *line_arg == NUL)
19107 line_arg = NULL;
19110 /* Don't define the function when skipping commands or when an error was
19111 * detected. */
19112 if (eap->skip || did_emsg)
19113 goto erret;
19116 * If there are no errors, add the function
19118 if (fudi.fd_dict == NULL)
19120 v = find_var(name, &ht);
19121 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
19123 emsg_funcname("E707: Function name conflicts with variable: %s",
19124 name);
19125 goto erret;
19128 fp = find_func(name);
19129 if (fp != NULL)
19131 if (!eap->forceit)
19133 emsg_funcname(e_funcexts, name);
19134 goto erret;
19136 if (fp->uf_calls > 0)
19138 emsg_funcname("E127: Cannot redefine function %s: It is in use",
19139 name);
19140 goto erret;
19142 /* redefine existing function */
19143 ga_clear_strings(&(fp->uf_args));
19144 ga_clear_strings(&(fp->uf_lines));
19145 vim_free(name);
19146 name = NULL;
19149 else
19151 char numbuf[20];
19153 fp = NULL;
19154 if (fudi.fd_newkey == NULL && !eap->forceit)
19156 EMSG(_(e_funcdict));
19157 goto erret;
19159 if (fudi.fd_di == NULL)
19161 /* Can't add a function to a locked dictionary */
19162 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
19163 goto erret;
19165 /* Can't change an existing function if it is locked */
19166 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
19167 goto erret;
19169 /* Give the function a sequential number. Can only be used with a
19170 * Funcref! */
19171 vim_free(name);
19172 sprintf(numbuf, "%d", ++func_nr);
19173 name = vim_strsave((char_u *)numbuf);
19174 if (name == NULL)
19175 goto erret;
19178 if (fp == NULL)
19180 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
19182 int slen, plen;
19183 char_u *scriptname;
19185 /* Check that the autoload name matches the script name. */
19186 j = FAIL;
19187 if (sourcing_name != NULL)
19189 scriptname = autoload_name(name);
19190 if (scriptname != NULL)
19192 p = vim_strchr(scriptname, '/');
19193 plen = (int)STRLEN(p);
19194 slen = (int)STRLEN(sourcing_name);
19195 if (slen > plen && fnamecmp(p,
19196 sourcing_name + slen - plen) == 0)
19197 j = OK;
19198 vim_free(scriptname);
19201 if (j == FAIL)
19203 EMSG2(_("E746: Function name does not match script file name: %s"), name);
19204 goto erret;
19208 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
19209 if (fp == NULL)
19210 goto erret;
19212 if (fudi.fd_dict != NULL)
19214 if (fudi.fd_di == NULL)
19216 /* add new dict entry */
19217 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
19218 if (fudi.fd_di == NULL)
19220 vim_free(fp);
19221 goto erret;
19223 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
19225 vim_free(fudi.fd_di);
19226 vim_free(fp);
19227 goto erret;
19230 else
19231 /* overwrite existing dict entry */
19232 clear_tv(&fudi.fd_di->di_tv);
19233 fudi.fd_di->di_tv.v_type = VAR_FUNC;
19234 fudi.fd_di->di_tv.v_lock = 0;
19235 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
19236 fp->uf_refcount = 1;
19238 /* behave like "dict" was used */
19239 flags |= FC_DICT;
19242 /* insert the new function in the function list */
19243 STRCPY(fp->uf_name, name);
19244 hash_add(&func_hashtab, UF2HIKEY(fp));
19246 fp->uf_args = newargs;
19247 fp->uf_lines = newlines;
19248 #ifdef FEAT_PROFILE
19249 fp->uf_tml_count = NULL;
19250 fp->uf_tml_total = NULL;
19251 fp->uf_tml_self = NULL;
19252 fp->uf_profiling = FALSE;
19253 if (prof_def_func())
19254 func_do_profile(fp);
19255 #endif
19256 fp->uf_varargs = varargs;
19257 fp->uf_flags = flags;
19258 fp->uf_calls = 0;
19259 fp->uf_script_ID = current_SID;
19260 goto ret_free;
19262 erret:
19263 ga_clear_strings(&newargs);
19264 ga_clear_strings(&newlines);
19265 ret_free:
19266 vim_free(skip_until);
19267 vim_free(fudi.fd_newkey);
19268 vim_free(name);
19269 did_emsg |= saved_did_emsg;
19273 * Get a function name, translating "<SID>" and "<SNR>".
19274 * Also handles a Funcref in a List or Dictionary.
19275 * Returns the function name in allocated memory, or NULL for failure.
19276 * flags:
19277 * TFN_INT: internal function name OK
19278 * TFN_QUIET: be quiet
19279 * Advances "pp" to just after the function name (if no error).
19281 static char_u *
19282 trans_function_name(pp, skip, flags, fdp)
19283 char_u **pp;
19284 int skip; /* only find the end, don't evaluate */
19285 int flags;
19286 funcdict_T *fdp; /* return: info about dictionary used */
19288 char_u *name = NULL;
19289 char_u *start;
19290 char_u *end;
19291 int lead;
19292 char_u sid_buf[20];
19293 int len;
19294 lval_T lv;
19296 if (fdp != NULL)
19297 vim_memset(fdp, 0, sizeof(funcdict_T));
19298 start = *pp;
19300 /* Check for hard coded <SNR>: already translated function ID (from a user
19301 * command). */
19302 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
19303 && (*pp)[2] == (int)KE_SNR)
19305 *pp += 3;
19306 len = get_id_len(pp) + 3;
19307 return vim_strnsave(start, len);
19310 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
19311 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
19312 lead = eval_fname_script(start);
19313 if (lead > 2)
19314 start += lead;
19316 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
19317 lead > 2 ? 0 : FNE_CHECK_START);
19318 if (end == start)
19320 if (!skip)
19321 EMSG(_("E129: Function name required"));
19322 goto theend;
19324 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
19327 * Report an invalid expression in braces, unless the expression
19328 * evaluation has been cancelled due to an aborting error, an
19329 * interrupt, or an exception.
19331 if (!aborting())
19333 if (end != NULL)
19334 EMSG2(_(e_invarg2), start);
19336 else
19337 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
19338 goto theend;
19341 if (lv.ll_tv != NULL)
19343 if (fdp != NULL)
19345 fdp->fd_dict = lv.ll_dict;
19346 fdp->fd_newkey = lv.ll_newkey;
19347 lv.ll_newkey = NULL;
19348 fdp->fd_di = lv.ll_di;
19350 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
19352 name = vim_strsave(lv.ll_tv->vval.v_string);
19353 *pp = end;
19355 else
19357 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
19358 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
19359 EMSG(_(e_funcref));
19360 else
19361 *pp = end;
19362 name = NULL;
19364 goto theend;
19367 if (lv.ll_name == NULL)
19369 /* Error found, but continue after the function name. */
19370 *pp = end;
19371 goto theend;
19374 if (lv.ll_exp_name != NULL)
19376 len = (int)STRLEN(lv.ll_exp_name);
19377 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
19378 && STRNCMP(lv.ll_name, "s:", 2) == 0)
19380 /* When there was "s:" already or the name expanded to get a
19381 * leading "s:" then remove it. */
19382 lv.ll_name += 2;
19383 len -= 2;
19384 lead = 2;
19387 else
19389 if (lead == 2) /* skip over "s:" */
19390 lv.ll_name += 2;
19391 len = (int)(end - lv.ll_name);
19395 * Copy the function name to allocated memory.
19396 * Accept <SID>name() inside a script, translate into <SNR>123_name().
19397 * Accept <SNR>123_name() outside a script.
19399 if (skip)
19400 lead = 0; /* do nothing */
19401 else if (lead > 0)
19403 lead = 3;
19404 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
19405 || eval_fname_sid(*pp))
19407 /* It's "s:" or "<SID>" */
19408 if (current_SID <= 0)
19410 EMSG(_(e_usingsid));
19411 goto theend;
19413 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
19414 lead += (int)STRLEN(sid_buf);
19417 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
19419 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
19420 goto theend;
19422 name = alloc((unsigned)(len + lead + 1));
19423 if (name != NULL)
19425 if (lead > 0)
19427 name[0] = K_SPECIAL;
19428 name[1] = KS_EXTRA;
19429 name[2] = (int)KE_SNR;
19430 if (lead > 3) /* If it's "<SID>" */
19431 STRCPY(name + 3, sid_buf);
19433 mch_memmove(name + lead, lv.ll_name, (size_t)len);
19434 name[len + lead] = NUL;
19436 *pp = end;
19438 theend:
19439 clear_lval(&lv);
19440 return name;
19444 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
19445 * Return 2 if "p" starts with "s:".
19446 * Return 0 otherwise.
19448 static int
19449 eval_fname_script(p)
19450 char_u *p;
19452 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
19453 || STRNICMP(p + 1, "SNR>", 4) == 0))
19454 return 5;
19455 if (p[0] == 's' && p[1] == ':')
19456 return 2;
19457 return 0;
19461 * Return TRUE if "p" starts with "<SID>" or "s:".
19462 * Only works if eval_fname_script() returned non-zero for "p"!
19464 static int
19465 eval_fname_sid(p)
19466 char_u *p;
19468 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
19472 * List the head of the function: "name(arg1, arg2)".
19474 static void
19475 list_func_head(fp, indent)
19476 ufunc_T *fp;
19477 int indent;
19479 int j;
19481 msg_start();
19482 if (indent)
19483 MSG_PUTS(" ");
19484 MSG_PUTS("function ");
19485 if (fp->uf_name[0] == K_SPECIAL)
19487 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
19488 msg_puts(fp->uf_name + 3);
19490 else
19491 msg_puts(fp->uf_name);
19492 msg_putchar('(');
19493 for (j = 0; j < fp->uf_args.ga_len; ++j)
19495 if (j)
19496 MSG_PUTS(", ");
19497 msg_puts(FUNCARG(fp, j));
19499 if (fp->uf_varargs)
19501 if (j)
19502 MSG_PUTS(", ");
19503 MSG_PUTS("...");
19505 msg_putchar(')');
19506 msg_clr_eos();
19507 if (p_verbose > 0)
19508 last_set_msg(fp->uf_script_ID);
19512 * Find a function by name, return pointer to it in ufuncs.
19513 * Return NULL for unknown function.
19515 static ufunc_T *
19516 find_func(name)
19517 char_u *name;
19519 hashitem_T *hi;
19521 hi = hash_find(&func_hashtab, name);
19522 if (!HASHITEM_EMPTY(hi))
19523 return HI2UF(hi);
19524 return NULL;
19527 #if defined(EXITFREE) || defined(PROTO)
19528 void
19529 free_all_functions()
19531 hashitem_T *hi;
19533 /* Need to start all over every time, because func_free() may change the
19534 * hash table. */
19535 while (func_hashtab.ht_used > 0)
19536 for (hi = func_hashtab.ht_array; ; ++hi)
19537 if (!HASHITEM_EMPTY(hi))
19539 func_free(HI2UF(hi));
19540 break;
19543 #endif
19546 * Return TRUE if a function "name" exists.
19548 static int
19549 function_exists(name)
19550 char_u *name;
19552 char_u *nm = name;
19553 char_u *p;
19554 int n = FALSE;
19556 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
19557 nm = skipwhite(nm);
19559 /* Only accept "funcname", "funcname ", "funcname (..." and
19560 * "funcname(...", not "funcname!...". */
19561 if (p != NULL && (*nm == NUL || *nm == '('))
19563 if (builtin_function(p))
19564 n = (find_internal_func(p) >= 0);
19565 else
19566 n = (find_func(p) != NULL);
19568 vim_free(p);
19569 return n;
19573 * Return TRUE if "name" looks like a builtin function name: starts with a
19574 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
19576 static int
19577 builtin_function(name)
19578 char_u *name;
19580 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
19581 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
19584 #if defined(FEAT_PROFILE) || defined(PROTO)
19586 * Start profiling function "fp".
19588 static void
19589 func_do_profile(fp)
19590 ufunc_T *fp;
19592 fp->uf_tm_count = 0;
19593 profile_zero(&fp->uf_tm_self);
19594 profile_zero(&fp->uf_tm_total);
19595 if (fp->uf_tml_count == NULL)
19596 fp->uf_tml_count = (int *)alloc_clear((unsigned)
19597 (sizeof(int) * fp->uf_lines.ga_len));
19598 if (fp->uf_tml_total == NULL)
19599 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
19600 (sizeof(proftime_T) * fp->uf_lines.ga_len));
19601 if (fp->uf_tml_self == NULL)
19602 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
19603 (sizeof(proftime_T) * fp->uf_lines.ga_len));
19604 fp->uf_tml_idx = -1;
19605 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
19606 || fp->uf_tml_self == NULL)
19607 return; /* out of memory */
19609 fp->uf_profiling = TRUE;
19613 * Dump the profiling results for all functions in file "fd".
19615 void
19616 func_dump_profile(fd)
19617 FILE *fd;
19619 hashitem_T *hi;
19620 int todo;
19621 ufunc_T *fp;
19622 int i;
19623 ufunc_T **sorttab;
19624 int st_len = 0;
19626 todo = (int)func_hashtab.ht_used;
19627 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
19629 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
19631 if (!HASHITEM_EMPTY(hi))
19633 --todo;
19634 fp = HI2UF(hi);
19635 if (fp->uf_profiling)
19637 if (sorttab != NULL)
19638 sorttab[st_len++] = fp;
19640 if (fp->uf_name[0] == K_SPECIAL)
19641 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
19642 else
19643 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
19644 if (fp->uf_tm_count == 1)
19645 fprintf(fd, "Called 1 time\n");
19646 else
19647 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
19648 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
19649 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
19650 fprintf(fd, "\n");
19651 fprintf(fd, "count total (s) self (s)\n");
19653 for (i = 0; i < fp->uf_lines.ga_len; ++i)
19655 if (FUNCLINE(fp, i) == NULL)
19656 continue;
19657 prof_func_line(fd, fp->uf_tml_count[i],
19658 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
19659 fprintf(fd, "%s\n", FUNCLINE(fp, i));
19661 fprintf(fd, "\n");
19666 if (sorttab != NULL && st_len > 0)
19668 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
19669 prof_total_cmp);
19670 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
19671 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
19672 prof_self_cmp);
19673 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
19677 static void
19678 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
19679 FILE *fd;
19680 ufunc_T **sorttab;
19681 int st_len;
19682 char *title;
19683 int prefer_self; /* when equal print only self time */
19685 int i;
19686 ufunc_T *fp;
19688 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
19689 fprintf(fd, "count total (s) self (s) function\n");
19690 for (i = 0; i < 20 && i < st_len; ++i)
19692 fp = sorttab[i];
19693 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
19694 prefer_self);
19695 if (fp->uf_name[0] == K_SPECIAL)
19696 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
19697 else
19698 fprintf(fd, " %s()\n", fp->uf_name);
19700 fprintf(fd, "\n");
19704 * Print the count and times for one function or function line.
19706 static void
19707 prof_func_line(fd, count, total, self, prefer_self)
19708 FILE *fd;
19709 int count;
19710 proftime_T *total;
19711 proftime_T *self;
19712 int prefer_self; /* when equal print only self time */
19714 if (count > 0)
19716 fprintf(fd, "%5d ", count);
19717 if (prefer_self && profile_equal(total, self))
19718 fprintf(fd, " ");
19719 else
19720 fprintf(fd, "%s ", profile_msg(total));
19721 if (!prefer_self && profile_equal(total, self))
19722 fprintf(fd, " ");
19723 else
19724 fprintf(fd, "%s ", profile_msg(self));
19726 else
19727 fprintf(fd, " ");
19731 * Compare function for total time sorting.
19733 static int
19734 #ifdef __BORLANDC__
19735 _RTLENTRYF
19736 #endif
19737 prof_total_cmp(s1, s2)
19738 const void *s1;
19739 const void *s2;
19741 ufunc_T *p1, *p2;
19743 p1 = *(ufunc_T **)s1;
19744 p2 = *(ufunc_T **)s2;
19745 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
19749 * Compare function for self time sorting.
19751 static int
19752 #ifdef __BORLANDC__
19753 _RTLENTRYF
19754 #endif
19755 prof_self_cmp(s1, s2)
19756 const void *s1;
19757 const void *s2;
19759 ufunc_T *p1, *p2;
19761 p1 = *(ufunc_T **)s1;
19762 p2 = *(ufunc_T **)s2;
19763 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
19766 #endif
19769 * If "name" has a package name try autoloading the script for it.
19770 * Return TRUE if a package was loaded.
19772 static int
19773 script_autoload(name, reload)
19774 char_u *name;
19775 int reload; /* load script again when already loaded */
19777 char_u *p;
19778 char_u *scriptname, *tofree;
19779 int ret = FALSE;
19780 int i;
19782 /* If there is no '#' after name[0] there is no package name. */
19783 p = vim_strchr(name, AUTOLOAD_CHAR);
19784 if (p == NULL || p == name)
19785 return FALSE;
19787 tofree = scriptname = autoload_name(name);
19789 /* Find the name in the list of previously loaded package names. Skip
19790 * "autoload/", it's always the same. */
19791 for (i = 0; i < ga_loaded.ga_len; ++i)
19792 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
19793 break;
19794 if (!reload && i < ga_loaded.ga_len)
19795 ret = FALSE; /* was loaded already */
19796 else
19798 /* Remember the name if it wasn't loaded already. */
19799 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
19801 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
19802 tofree = NULL;
19805 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
19806 if (source_runtime(scriptname, FALSE) == OK)
19807 ret = TRUE;
19810 vim_free(tofree);
19811 return ret;
19815 * Return the autoload script name for a function or variable name.
19816 * Returns NULL when out of memory.
19818 static char_u *
19819 autoload_name(name)
19820 char_u *name;
19822 char_u *p;
19823 char_u *scriptname;
19825 /* Get the script file name: replace '#' with '/', append ".vim". */
19826 scriptname = alloc((unsigned)(STRLEN(name) + 14));
19827 if (scriptname == NULL)
19828 return FALSE;
19829 STRCPY(scriptname, "autoload/");
19830 STRCAT(scriptname, name);
19831 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
19832 STRCAT(scriptname, ".vim");
19833 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
19834 *p = '/';
19835 return scriptname;
19838 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
19841 * Function given to ExpandGeneric() to obtain the list of user defined
19842 * function names.
19844 char_u *
19845 get_user_func_name(xp, idx)
19846 expand_T *xp;
19847 int idx;
19849 static long_u done;
19850 static hashitem_T *hi;
19851 ufunc_T *fp;
19853 if (idx == 0)
19855 done = 0;
19856 hi = func_hashtab.ht_array;
19858 if (done < func_hashtab.ht_used)
19860 if (done++ > 0)
19861 ++hi;
19862 while (HASHITEM_EMPTY(hi))
19863 ++hi;
19864 fp = HI2UF(hi);
19866 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
19867 return fp->uf_name; /* prevents overflow */
19869 cat_func_name(IObuff, fp);
19870 if (xp->xp_context != EXPAND_USER_FUNC)
19872 STRCAT(IObuff, "(");
19873 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
19874 STRCAT(IObuff, ")");
19876 return IObuff;
19878 return NULL;
19881 #endif /* FEAT_CMDL_COMPL */
19884 * Copy the function name of "fp" to buffer "buf".
19885 * "buf" must be able to hold the function name plus three bytes.
19886 * Takes care of script-local function names.
19888 static void
19889 cat_func_name(buf, fp)
19890 char_u *buf;
19891 ufunc_T *fp;
19893 if (fp->uf_name[0] == K_SPECIAL)
19895 STRCPY(buf, "<SNR>");
19896 STRCAT(buf, fp->uf_name + 3);
19898 else
19899 STRCPY(buf, fp->uf_name);
19903 * ":delfunction {name}"
19905 void
19906 ex_delfunction(eap)
19907 exarg_T *eap;
19909 ufunc_T *fp = NULL;
19910 char_u *p;
19911 char_u *name;
19912 funcdict_T fudi;
19914 p = eap->arg;
19915 name = trans_function_name(&p, eap->skip, 0, &fudi);
19916 vim_free(fudi.fd_newkey);
19917 if (name == NULL)
19919 if (fudi.fd_dict != NULL && !eap->skip)
19920 EMSG(_(e_funcref));
19921 return;
19923 if (!ends_excmd(*skipwhite(p)))
19925 vim_free(name);
19926 EMSG(_(e_trailing));
19927 return;
19929 eap->nextcmd = check_nextcmd(p);
19930 if (eap->nextcmd != NULL)
19931 *p = NUL;
19933 if (!eap->skip)
19934 fp = find_func(name);
19935 vim_free(name);
19937 if (!eap->skip)
19939 if (fp == NULL)
19941 EMSG2(_(e_nofunc), eap->arg);
19942 return;
19944 if (fp->uf_calls > 0)
19946 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
19947 return;
19950 if (fudi.fd_dict != NULL)
19952 /* Delete the dict item that refers to the function, it will
19953 * invoke func_unref() and possibly delete the function. */
19954 dictitem_remove(fudi.fd_dict, fudi.fd_di);
19956 else
19957 func_free(fp);
19962 * Free a function and remove it from the list of functions.
19964 static void
19965 func_free(fp)
19966 ufunc_T *fp;
19968 hashitem_T *hi;
19970 /* clear this function */
19971 ga_clear_strings(&(fp->uf_args));
19972 ga_clear_strings(&(fp->uf_lines));
19973 #ifdef FEAT_PROFILE
19974 vim_free(fp->uf_tml_count);
19975 vim_free(fp->uf_tml_total);
19976 vim_free(fp->uf_tml_self);
19977 #endif
19979 /* remove the function from the function hashtable */
19980 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
19981 if (HASHITEM_EMPTY(hi))
19982 EMSG2(_(e_intern2), "func_free()");
19983 else
19984 hash_remove(&func_hashtab, hi);
19986 vim_free(fp);
19990 * Unreference a Function: decrement the reference count and free it when it
19991 * becomes zero. Only for numbered functions.
19993 static void
19994 func_unref(name)
19995 char_u *name;
19997 ufunc_T *fp;
19999 if (name != NULL && isdigit(*name))
20001 fp = find_func(name);
20002 if (fp == NULL)
20003 EMSG2(_(e_intern2), "func_unref()");
20004 else if (--fp->uf_refcount <= 0)
20006 /* Only delete it when it's not being used. Otherwise it's done
20007 * when "uf_calls" becomes zero. */
20008 if (fp->uf_calls == 0)
20009 func_free(fp);
20015 * Count a reference to a Function.
20017 static void
20018 func_ref(name)
20019 char_u *name;
20021 ufunc_T *fp;
20023 if (name != NULL && isdigit(*name))
20025 fp = find_func(name);
20026 if (fp == NULL)
20027 EMSG2(_(e_intern2), "func_ref()");
20028 else
20029 ++fp->uf_refcount;
20034 * Call a user function.
20036 static void
20037 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
20038 ufunc_T *fp; /* pointer to function */
20039 int argcount; /* nr of args */
20040 typval_T *argvars; /* arguments */
20041 typval_T *rettv; /* return value */
20042 linenr_T firstline; /* first line of range */
20043 linenr_T lastline; /* last line of range */
20044 dict_T *selfdict; /* Dictionary for "self" */
20046 char_u *save_sourcing_name;
20047 linenr_T save_sourcing_lnum;
20048 scid_T save_current_SID;
20049 funccall_T fc;
20050 int save_did_emsg;
20051 static int depth = 0;
20052 dictitem_T *v;
20053 int fixvar_idx = 0; /* index in fixvar[] */
20054 int i;
20055 int ai;
20056 char_u numbuf[NUMBUFLEN];
20057 char_u *name;
20058 #ifdef FEAT_PROFILE
20059 proftime_T wait_start;
20060 proftime_T call_start;
20061 #endif
20063 /* If depth of calling is getting too high, don't execute the function */
20064 if (depth >= p_mfd)
20066 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
20067 rettv->v_type = VAR_NUMBER;
20068 rettv->vval.v_number = -1;
20069 return;
20071 ++depth;
20073 line_breakcheck(); /* check for CTRL-C hit */
20075 fc.caller = current_funccal;
20076 current_funccal = &fc;
20077 fc.func = fp;
20078 fc.rettv = rettv;
20079 rettv->vval.v_number = 0;
20080 fc.linenr = 0;
20081 fc.returned = FALSE;
20082 fc.level = ex_nesting_level;
20083 /* Check if this function has a breakpoint. */
20084 fc.breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
20085 fc.dbg_tick = debug_tick;
20088 * Note about using fc.fixvar[]: This is an array of FIXVAR_CNT variables
20089 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
20090 * each argument variable and saves a lot of time.
20093 * Init l: variables.
20095 init_var_dict(&fc.l_vars, &fc.l_vars_var);
20096 if (selfdict != NULL)
20098 /* Set l:self to "selfdict". Use "name" to avoid a warning from
20099 * some compiler that checks the destination size. */
20100 v = &fc.fixvar[fixvar_idx++].var;
20101 name = v->di_key;
20102 STRCPY(name, "self");
20103 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
20104 hash_add(&fc.l_vars.dv_hashtab, DI2HIKEY(v));
20105 v->di_tv.v_type = VAR_DICT;
20106 v->di_tv.v_lock = 0;
20107 v->di_tv.vval.v_dict = selfdict;
20108 ++selfdict->dv_refcount;
20112 * Init a: variables.
20113 * Set a:0 to "argcount".
20114 * Set a:000 to a list with room for the "..." arguments.
20116 init_var_dict(&fc.l_avars, &fc.l_avars_var);
20117 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "0",
20118 (varnumber_T)(argcount - fp->uf_args.ga_len));
20119 v = &fc.fixvar[fixvar_idx++].var;
20120 STRCPY(v->di_key, "000");
20121 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20122 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
20123 v->di_tv.v_type = VAR_LIST;
20124 v->di_tv.v_lock = VAR_FIXED;
20125 v->di_tv.vval.v_list = &fc.l_varlist;
20126 vim_memset(&fc.l_varlist, 0, sizeof(list_T));
20127 fc.l_varlist.lv_refcount = 99999;
20128 fc.l_varlist.lv_lock = VAR_FIXED;
20131 * Set a:firstline to "firstline" and a:lastline to "lastline".
20132 * Set a:name to named arguments.
20133 * Set a:N to the "..." arguments.
20135 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "firstline",
20136 (varnumber_T)firstline);
20137 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "lastline",
20138 (varnumber_T)lastline);
20139 for (i = 0; i < argcount; ++i)
20141 ai = i - fp->uf_args.ga_len;
20142 if (ai < 0)
20143 /* named argument a:name */
20144 name = FUNCARG(fp, i);
20145 else
20147 /* "..." argument a:1, a:2, etc. */
20148 sprintf((char *)numbuf, "%d", ai + 1);
20149 name = numbuf;
20151 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
20153 v = &fc.fixvar[fixvar_idx++].var;
20154 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20156 else
20158 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
20159 + STRLEN(name)));
20160 if (v == NULL)
20161 break;
20162 v->di_flags = DI_FLAGS_RO;
20164 STRCPY(v->di_key, name);
20165 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
20167 /* Note: the values are copied directly to avoid alloc/free.
20168 * "argvars" must have VAR_FIXED for v_lock. */
20169 v->di_tv = argvars[i];
20170 v->di_tv.v_lock = VAR_FIXED;
20172 if (ai >= 0 && ai < MAX_FUNC_ARGS)
20174 list_append(&fc.l_varlist, &fc.l_listitems[ai]);
20175 fc.l_listitems[ai].li_tv = argvars[i];
20176 fc.l_listitems[ai].li_tv.v_lock = VAR_FIXED;
20180 /* Don't redraw while executing the function. */
20181 ++RedrawingDisabled;
20182 save_sourcing_name = sourcing_name;
20183 save_sourcing_lnum = sourcing_lnum;
20184 sourcing_lnum = 1;
20185 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
20186 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
20187 if (sourcing_name != NULL)
20189 if (save_sourcing_name != NULL
20190 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
20191 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
20192 else
20193 STRCPY(sourcing_name, "function ");
20194 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
20196 if (p_verbose >= 12)
20198 ++no_wait_return;
20199 verbose_enter_scroll();
20201 smsg((char_u *)_("calling %s"), sourcing_name);
20202 if (p_verbose >= 14)
20204 char_u buf[MSG_BUF_LEN];
20205 char_u numbuf2[NUMBUFLEN];
20206 char_u *tofree;
20207 char_u *s;
20209 msg_puts((char_u *)"(");
20210 for (i = 0; i < argcount; ++i)
20212 if (i > 0)
20213 msg_puts((char_u *)", ");
20214 if (argvars[i].v_type == VAR_NUMBER)
20215 msg_outnum((long)argvars[i].vval.v_number);
20216 else
20218 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
20219 if (s != NULL)
20221 trunc_string(s, buf, MSG_BUF_CLEN);
20222 msg_puts(buf);
20223 vim_free(tofree);
20227 msg_puts((char_u *)")");
20229 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20231 verbose_leave_scroll();
20232 --no_wait_return;
20235 #ifdef FEAT_PROFILE
20236 if (do_profiling == PROF_YES)
20238 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
20239 func_do_profile(fp);
20240 if (fp->uf_profiling
20241 || (fc.caller != NULL && &fc.caller->func->uf_profiling))
20243 ++fp->uf_tm_count;
20244 profile_start(&call_start);
20245 profile_zero(&fp->uf_tm_children);
20247 script_prof_save(&wait_start);
20249 #endif
20251 save_current_SID = current_SID;
20252 current_SID = fp->uf_script_ID;
20253 save_did_emsg = did_emsg;
20254 did_emsg = FALSE;
20256 /* call do_cmdline() to execute the lines */
20257 do_cmdline(NULL, get_func_line, (void *)&fc,
20258 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
20260 --RedrawingDisabled;
20262 /* when the function was aborted because of an error, return -1 */
20263 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
20265 clear_tv(rettv);
20266 rettv->v_type = VAR_NUMBER;
20267 rettv->vval.v_number = -1;
20270 #ifdef FEAT_PROFILE
20271 if (do_profiling == PROF_YES && (fp->uf_profiling
20272 || (fc.caller != NULL && &fc.caller->func->uf_profiling)))
20274 profile_end(&call_start);
20275 profile_sub_wait(&wait_start, &call_start);
20276 profile_add(&fp->uf_tm_total, &call_start);
20277 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
20278 if (fc.caller != NULL && &fc.caller->func->uf_profiling)
20280 profile_add(&fc.caller->func->uf_tm_children, &call_start);
20281 profile_add(&fc.caller->func->uf_tml_children, &call_start);
20284 #endif
20286 /* when being verbose, mention the return value */
20287 if (p_verbose >= 12)
20289 ++no_wait_return;
20290 verbose_enter_scroll();
20292 if (aborting())
20293 smsg((char_u *)_("%s aborted"), sourcing_name);
20294 else if (fc.rettv->v_type == VAR_NUMBER)
20295 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
20296 (long)fc.rettv->vval.v_number);
20297 else
20299 char_u buf[MSG_BUF_LEN];
20300 char_u numbuf2[NUMBUFLEN];
20301 char_u *tofree;
20302 char_u *s;
20304 /* The value may be very long. Skip the middle part, so that we
20305 * have some idea how it starts and ends. smsg() would always
20306 * truncate it at the end. */
20307 s = tv2string(fc.rettv, &tofree, numbuf2, 0);
20308 if (s != NULL)
20310 trunc_string(s, buf, MSG_BUF_CLEN);
20311 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
20312 vim_free(tofree);
20315 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20317 verbose_leave_scroll();
20318 --no_wait_return;
20321 vim_free(sourcing_name);
20322 sourcing_name = save_sourcing_name;
20323 sourcing_lnum = save_sourcing_lnum;
20324 current_SID = save_current_SID;
20325 #ifdef FEAT_PROFILE
20326 if (do_profiling == PROF_YES)
20327 script_prof_restore(&wait_start);
20328 #endif
20330 if (p_verbose >= 12 && sourcing_name != NULL)
20332 ++no_wait_return;
20333 verbose_enter_scroll();
20335 smsg((char_u *)_("continuing in %s"), sourcing_name);
20336 msg_puts((char_u *)"\n"); /* don't overwrite this either */
20338 verbose_leave_scroll();
20339 --no_wait_return;
20342 did_emsg |= save_did_emsg;
20343 current_funccal = fc.caller;
20345 /* The a: variables typevals were not alloced, only free the allocated
20346 * variables. */
20347 vars_clear_ext(&fc.l_avars.dv_hashtab, FALSE);
20349 vars_clear(&fc.l_vars.dv_hashtab); /* free all l: variables */
20350 --depth;
20354 * Add a number variable "name" to dict "dp" with value "nr".
20356 static void
20357 add_nr_var(dp, v, name, nr)
20358 dict_T *dp;
20359 dictitem_T *v;
20360 char *name;
20361 varnumber_T nr;
20363 STRCPY(v->di_key, name);
20364 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
20365 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
20366 v->di_tv.v_type = VAR_NUMBER;
20367 v->di_tv.v_lock = VAR_FIXED;
20368 v->di_tv.vval.v_number = nr;
20372 * ":return [expr]"
20374 void
20375 ex_return(eap)
20376 exarg_T *eap;
20378 char_u *arg = eap->arg;
20379 typval_T rettv;
20380 int returning = FALSE;
20382 if (current_funccal == NULL)
20384 EMSG(_("E133: :return not inside a function"));
20385 return;
20388 if (eap->skip)
20389 ++emsg_skip;
20391 eap->nextcmd = NULL;
20392 if ((*arg != NUL && *arg != '|' && *arg != '\n')
20393 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
20395 if (!eap->skip)
20396 returning = do_return(eap, FALSE, TRUE, &rettv);
20397 else
20398 clear_tv(&rettv);
20400 /* It's safer to return also on error. */
20401 else if (!eap->skip)
20404 * Return unless the expression evaluation has been cancelled due to an
20405 * aborting error, an interrupt, or an exception.
20407 if (!aborting())
20408 returning = do_return(eap, FALSE, TRUE, NULL);
20411 /* When skipping or the return gets pending, advance to the next command
20412 * in this line (!returning). Otherwise, ignore the rest of the line.
20413 * Following lines will be ignored by get_func_line(). */
20414 if (returning)
20415 eap->nextcmd = NULL;
20416 else if (eap->nextcmd == NULL) /* no argument */
20417 eap->nextcmd = check_nextcmd(arg);
20419 if (eap->skip)
20420 --emsg_skip;
20424 * Return from a function. Possibly makes the return pending. Also called
20425 * for a pending return at the ":endtry" or after returning from an extra
20426 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
20427 * when called due to a ":return" command. "rettv" may point to a typval_T
20428 * with the return rettv. Returns TRUE when the return can be carried out,
20429 * FALSE when the return gets pending.
20432 do_return(eap, reanimate, is_cmd, rettv)
20433 exarg_T *eap;
20434 int reanimate;
20435 int is_cmd;
20436 void *rettv;
20438 int idx;
20439 struct condstack *cstack = eap->cstack;
20441 if (reanimate)
20442 /* Undo the return. */
20443 current_funccal->returned = FALSE;
20446 * Cleanup (and inactivate) conditionals, but stop when a try conditional
20447 * not in its finally clause (which then is to be executed next) is found.
20448 * In this case, make the ":return" pending for execution at the ":endtry".
20449 * Otherwise, return normally.
20451 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
20452 if (idx >= 0)
20454 cstack->cs_pending[idx] = CSTP_RETURN;
20456 if (!is_cmd && !reanimate)
20457 /* A pending return again gets pending. "rettv" points to an
20458 * allocated variable with the rettv of the original ":return"'s
20459 * argument if present or is NULL else. */
20460 cstack->cs_rettv[idx] = rettv;
20461 else
20463 /* When undoing a return in order to make it pending, get the stored
20464 * return rettv. */
20465 if (reanimate)
20466 rettv = current_funccal->rettv;
20468 if (rettv != NULL)
20470 /* Store the value of the pending return. */
20471 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
20472 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
20473 else
20474 EMSG(_(e_outofmem));
20476 else
20477 cstack->cs_rettv[idx] = NULL;
20479 if (reanimate)
20481 /* The pending return value could be overwritten by a ":return"
20482 * without argument in a finally clause; reset the default
20483 * return value. */
20484 current_funccal->rettv->v_type = VAR_NUMBER;
20485 current_funccal->rettv->vval.v_number = 0;
20488 report_make_pending(CSTP_RETURN, rettv);
20490 else
20492 current_funccal->returned = TRUE;
20494 /* If the return is carried out now, store the return value. For
20495 * a return immediately after reanimation, the value is already
20496 * there. */
20497 if (!reanimate && rettv != NULL)
20499 clear_tv(current_funccal->rettv);
20500 *current_funccal->rettv = *(typval_T *)rettv;
20501 if (!is_cmd)
20502 vim_free(rettv);
20506 return idx < 0;
20510 * Free the variable with a pending return value.
20512 void
20513 discard_pending_return(rettv)
20514 void *rettv;
20516 free_tv((typval_T *)rettv);
20520 * Generate a return command for producing the value of "rettv". The result
20521 * is an allocated string. Used by report_pending() for verbose messages.
20523 char_u *
20524 get_return_cmd(rettv)
20525 void *rettv;
20527 char_u *s = NULL;
20528 char_u *tofree = NULL;
20529 char_u numbuf[NUMBUFLEN];
20531 if (rettv != NULL)
20532 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
20533 if (s == NULL)
20534 s = (char_u *)"";
20536 STRCPY(IObuff, ":return ");
20537 STRNCPY(IObuff + 8, s, IOSIZE - 8);
20538 if (STRLEN(s) + 8 >= IOSIZE)
20539 STRCPY(IObuff + IOSIZE - 4, "...");
20540 vim_free(tofree);
20541 return vim_strsave(IObuff);
20545 * Get next function line.
20546 * Called by do_cmdline() to get the next line.
20547 * Returns allocated string, or NULL for end of function.
20549 /* ARGSUSED */
20550 char_u *
20551 get_func_line(c, cookie, indent)
20552 int c; /* not used */
20553 void *cookie;
20554 int indent; /* not used */
20556 funccall_T *fcp = (funccall_T *)cookie;
20557 ufunc_T *fp = fcp->func;
20558 char_u *retval;
20559 garray_T *gap; /* growarray with function lines */
20561 /* If breakpoints have been added/deleted need to check for it. */
20562 if (fcp->dbg_tick != debug_tick)
20564 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
20565 sourcing_lnum);
20566 fcp->dbg_tick = debug_tick;
20568 #ifdef FEAT_PROFILE
20569 if (do_profiling == PROF_YES)
20570 func_line_end(cookie);
20571 #endif
20573 gap = &fp->uf_lines;
20574 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
20575 || fcp->returned)
20576 retval = NULL;
20577 else
20579 /* Skip NULL lines (continuation lines). */
20580 while (fcp->linenr < gap->ga_len
20581 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
20582 ++fcp->linenr;
20583 if (fcp->linenr >= gap->ga_len)
20584 retval = NULL;
20585 else
20587 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
20588 sourcing_lnum = fcp->linenr;
20589 #ifdef FEAT_PROFILE
20590 if (do_profiling == PROF_YES)
20591 func_line_start(cookie);
20592 #endif
20596 /* Did we encounter a breakpoint? */
20597 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
20599 dbg_breakpoint(fp->uf_name, sourcing_lnum);
20600 /* Find next breakpoint. */
20601 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
20602 sourcing_lnum);
20603 fcp->dbg_tick = debug_tick;
20606 return retval;
20609 #if defined(FEAT_PROFILE) || defined(PROTO)
20611 * Called when starting to read a function line.
20612 * "sourcing_lnum" must be correct!
20613 * When skipping lines it may not actually be executed, but we won't find out
20614 * until later and we need to store the time now.
20616 void
20617 func_line_start(cookie)
20618 void *cookie;
20620 funccall_T *fcp = (funccall_T *)cookie;
20621 ufunc_T *fp = fcp->func;
20623 if (fp->uf_profiling && sourcing_lnum >= 1
20624 && sourcing_lnum <= fp->uf_lines.ga_len)
20626 fp->uf_tml_idx = sourcing_lnum - 1;
20627 /* Skip continuation lines. */
20628 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
20629 --fp->uf_tml_idx;
20630 fp->uf_tml_execed = FALSE;
20631 profile_start(&fp->uf_tml_start);
20632 profile_zero(&fp->uf_tml_children);
20633 profile_get_wait(&fp->uf_tml_wait);
20638 * Called when actually executing a function line.
20640 void
20641 func_line_exec(cookie)
20642 void *cookie;
20644 funccall_T *fcp = (funccall_T *)cookie;
20645 ufunc_T *fp = fcp->func;
20647 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
20648 fp->uf_tml_execed = TRUE;
20652 * Called when done with a function line.
20654 void
20655 func_line_end(cookie)
20656 void *cookie;
20658 funccall_T *fcp = (funccall_T *)cookie;
20659 ufunc_T *fp = fcp->func;
20661 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
20663 if (fp->uf_tml_execed)
20665 ++fp->uf_tml_count[fp->uf_tml_idx];
20666 profile_end(&fp->uf_tml_start);
20667 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
20668 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
20669 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
20670 &fp->uf_tml_children);
20672 fp->uf_tml_idx = -1;
20675 #endif
20678 * Return TRUE if the currently active function should be ended, because a
20679 * return was encountered or an error occured. Used inside a ":while".
20682 func_has_ended(cookie)
20683 void *cookie;
20685 funccall_T *fcp = (funccall_T *)cookie;
20687 /* Ignore the "abort" flag if the abortion behavior has been changed due to
20688 * an error inside a try conditional. */
20689 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
20690 || fcp->returned);
20694 * return TRUE if cookie indicates a function which "abort"s on errors.
20697 func_has_abort(cookie)
20698 void *cookie;
20700 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
20703 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
20704 typedef enum
20706 VAR_FLAVOUR_DEFAULT,
20707 VAR_FLAVOUR_SESSION,
20708 VAR_FLAVOUR_VIMINFO
20709 } var_flavour_T;
20711 static var_flavour_T var_flavour __ARGS((char_u *varname));
20713 static var_flavour_T
20714 var_flavour(varname)
20715 char_u *varname;
20717 char_u *p = varname;
20719 if (ASCII_ISUPPER(*p))
20721 while (*(++p))
20722 if (ASCII_ISLOWER(*p))
20723 return VAR_FLAVOUR_SESSION;
20724 return VAR_FLAVOUR_VIMINFO;
20726 else
20727 return VAR_FLAVOUR_DEFAULT;
20729 #endif
20731 #if defined(FEAT_VIMINFO) || defined(PROTO)
20733 * Restore global vars that start with a capital from the viminfo file
20736 read_viminfo_varlist(virp, writing)
20737 vir_T *virp;
20738 int writing;
20740 char_u *tab;
20741 int is_string = FALSE;
20742 typval_T tv;
20744 if (!writing && (find_viminfo_parameter('!') != NULL))
20746 tab = vim_strchr(virp->vir_line + 1, '\t');
20747 if (tab != NULL)
20749 *tab++ = '\0'; /* isolate the variable name */
20750 if (*tab == 'S') /* string var */
20751 is_string = TRUE;
20753 tab = vim_strchr(tab, '\t');
20754 if (tab != NULL)
20756 if (is_string)
20758 tv.v_type = VAR_STRING;
20759 tv.vval.v_string = viminfo_readstring(virp,
20760 (int)(tab - virp->vir_line + 1), TRUE);
20762 else
20764 tv.v_type = VAR_NUMBER;
20765 tv.vval.v_number = atol((char *)tab + 1);
20767 set_var(virp->vir_line + 1, &tv, FALSE);
20768 if (is_string)
20769 vim_free(tv.vval.v_string);
20774 return viminfo_readline(virp);
20778 * Write global vars that start with a capital to the viminfo file
20780 void
20781 write_viminfo_varlist(fp)
20782 FILE *fp;
20784 hashitem_T *hi;
20785 dictitem_T *this_var;
20786 int todo;
20787 char *s;
20788 char_u *p;
20789 char_u *tofree;
20790 char_u numbuf[NUMBUFLEN];
20792 if (find_viminfo_parameter('!') == NULL)
20793 return;
20795 fprintf(fp, _("\n# global variables:\n"));
20797 todo = (int)globvarht.ht_used;
20798 for (hi = globvarht.ht_array; todo > 0; ++hi)
20800 if (!HASHITEM_EMPTY(hi))
20802 --todo;
20803 this_var = HI2DI(hi);
20804 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
20806 switch (this_var->di_tv.v_type)
20808 case VAR_STRING: s = "STR"; break;
20809 case VAR_NUMBER: s = "NUM"; break;
20810 default: continue;
20812 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
20813 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
20814 if (p != NULL)
20815 viminfo_writestring(fp, p);
20816 vim_free(tofree);
20821 #endif
20823 #if defined(FEAT_SESSION) || defined(PROTO)
20825 store_session_globals(fd)
20826 FILE *fd;
20828 hashitem_T *hi;
20829 dictitem_T *this_var;
20830 int todo;
20831 char_u *p, *t;
20833 todo = (int)globvarht.ht_used;
20834 for (hi = globvarht.ht_array; todo > 0; ++hi)
20836 if (!HASHITEM_EMPTY(hi))
20838 --todo;
20839 this_var = HI2DI(hi);
20840 if ((this_var->di_tv.v_type == VAR_NUMBER
20841 || this_var->di_tv.v_type == VAR_STRING)
20842 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
20844 /* Escape special characters with a backslash. Turn a LF and
20845 * CR into \n and \r. */
20846 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
20847 (char_u *)"\\\"\n\r");
20848 if (p == NULL) /* out of memory */
20849 break;
20850 for (t = p; *t != NUL; ++t)
20851 if (*t == '\n')
20852 *t = 'n';
20853 else if (*t == '\r')
20854 *t = 'r';
20855 if ((fprintf(fd, "let %s = %c%s%c",
20856 this_var->di_key,
20857 (this_var->di_tv.v_type == VAR_STRING) ? '"'
20858 : ' ',
20860 (this_var->di_tv.v_type == VAR_STRING) ? '"'
20861 : ' ') < 0)
20862 || put_eol(fd) == FAIL)
20864 vim_free(p);
20865 return FAIL;
20867 vim_free(p);
20871 return OK;
20873 #endif
20876 * Display script name where an item was last set.
20877 * Should only be invoked when 'verbose' is non-zero.
20879 void
20880 last_set_msg(scriptID)
20881 scid_T scriptID;
20883 char_u *p;
20885 if (scriptID != 0)
20887 p = home_replace_save(NULL, get_scriptname(scriptID));
20888 if (p != NULL)
20890 verbose_enter();
20891 MSG_PUTS(_("\n\tLast set from "));
20892 MSG_PUTS(p);
20893 vim_free(p);
20894 verbose_leave();
20899 #endif /* FEAT_EVAL */
20901 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
20904 #ifdef WIN3264
20906 * Functions for ":8" filename modifier: get 8.3 version of a filename.
20908 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
20909 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
20910 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
20913 * Get the short pathname of a file.
20914 * Returns 1 on success. *fnamelen is 0 for nonexistent path.
20916 static int
20917 get_short_pathname(fnamep, bufp, fnamelen)
20918 char_u **fnamep;
20919 char_u **bufp;
20920 int *fnamelen;
20922 int l,len;
20923 char_u *newbuf;
20925 len = *fnamelen;
20927 l = GetShortPathName(*fnamep, *fnamep, len);
20928 if (l > len - 1)
20930 /* If that doesn't work (not enough space), then save the string
20931 * and try again with a new buffer big enough
20933 newbuf = vim_strnsave(*fnamep, l);
20934 if (newbuf == NULL)
20935 return 0;
20937 vim_free(*bufp);
20938 *fnamep = *bufp = newbuf;
20940 l = GetShortPathName(*fnamep,*fnamep,l+1);
20942 /* Really should always succeed, as the buffer is big enough */
20945 *fnamelen = l;
20946 return 1;
20950 * Create a short path name. Returns the length of the buffer it needs.
20951 * Doesn't copy over the end of the buffer passed in.
20953 static int
20954 shortpath_for_invalid_fname(fname, bufp, fnamelen)
20955 char_u **fname;
20956 char_u **bufp;
20957 int *fnamelen;
20959 char_u *s, *p, *pbuf2, *pbuf3;
20960 char_u ch;
20961 int len, len2, plen, slen;
20963 /* Make a copy */
20964 len2 = *fnamelen;
20965 pbuf2 = vim_strnsave(*fname, len2);
20966 pbuf3 = NULL;
20968 s = pbuf2 + len2 - 1; /* Find the end */
20969 slen = 1;
20970 plen = len2;
20972 if (after_pathsep(pbuf2, s + 1))
20974 --s;
20975 ++slen;
20976 --plen;
20981 /* Go back one path-separator */
20982 while (s > pbuf2 && !after_pathsep(pbuf2, s + 1))
20984 --s;
20985 ++slen;
20986 --plen;
20988 if (s <= pbuf2)
20989 break;
20991 /* Remember the character that is about to be splatted */
20992 ch = *s;
20993 *s = 0; /* get_short_pathname requires a null-terminated string */
20995 /* Try it in situ */
20996 p = pbuf2;
20997 if (!get_short_pathname(&p, &pbuf3, &plen))
20999 vim_free(pbuf2);
21000 return -1;
21002 *s = ch; /* Preserve the string */
21003 } while (plen == 0);
21005 if (plen > 0)
21007 /* Remember the length of the new string. */
21008 *fnamelen = len = plen + slen;
21009 vim_free(*bufp);
21010 if (len > len2)
21012 /* If there's not enough space in the currently allocated string,
21013 * then copy it to a buffer big enough.
21015 *fname= *bufp = vim_strnsave(p, len);
21016 if (*fname == NULL)
21017 return -1;
21019 else
21021 /* Transfer pbuf2 to being the main buffer (it's big enough) */
21022 *fname = *bufp = pbuf2;
21023 if (p != pbuf2)
21024 strncpy(*fname, p, plen);
21025 pbuf2 = NULL;
21027 /* Concat the next bit */
21028 strncpy(*fname + plen, s, slen);
21029 (*fname)[len] = '\0';
21031 vim_free(pbuf3);
21032 vim_free(pbuf2);
21033 return 0;
21037 * Get a pathname for a partial path.
21039 static int
21040 shortpath_for_partial(fnamep, bufp, fnamelen)
21041 char_u **fnamep;
21042 char_u **bufp;
21043 int *fnamelen;
21045 int sepcount, len, tflen;
21046 char_u *p;
21047 char_u *pbuf, *tfname;
21048 int hasTilde;
21050 /* Count up the path seperators from the RHS.. so we know which part
21051 * of the path to return.
21053 sepcount = 0;
21054 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
21055 if (vim_ispathsep(*p))
21056 ++sepcount;
21058 /* Need full path first (use expand_env() to remove a "~/") */
21059 hasTilde = (**fnamep == '~');
21060 if (hasTilde)
21061 pbuf = tfname = expand_env_save(*fnamep);
21062 else
21063 pbuf = tfname = FullName_save(*fnamep, FALSE);
21065 len = tflen = (int)STRLEN(tfname);
21067 if (!get_short_pathname(&tfname, &pbuf, &len))
21068 return -1;
21070 if (len == 0)
21072 /* Don't have a valid filename, so shorten the rest of the
21073 * path if we can. This CAN give us invalid 8.3 filenames, but
21074 * there's not a lot of point in guessing what it might be.
21076 len = tflen;
21077 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == -1)
21078 return -1;
21081 /* Count the paths backward to find the beginning of the desired string. */
21082 for (p = tfname + len - 1; p >= tfname; --p)
21084 #ifdef FEAT_MBYTE
21085 if (has_mbyte)
21086 p -= mb_head_off(tfname, p);
21087 #endif
21088 if (vim_ispathsep(*p))
21090 if (sepcount == 0 || (hasTilde && sepcount == 1))
21091 break;
21092 else
21093 sepcount --;
21096 if (hasTilde)
21098 --p;
21099 if (p >= tfname)
21100 *p = '~';
21101 else
21102 return -1;
21104 else
21105 ++p;
21107 /* Copy in the string - p indexes into tfname - allocated at pbuf */
21108 vim_free(*bufp);
21109 *fnamelen = (int)STRLEN(p);
21110 *bufp = pbuf;
21111 *fnamep = p;
21113 return 0;
21115 #endif /* WIN3264 */
21118 * Adjust a filename, according to a string of modifiers.
21119 * *fnamep must be NUL terminated when called. When returning, the length is
21120 * determined by *fnamelen.
21121 * Returns valid flags.
21122 * When there is an error, *fnamep is set to NULL.
21125 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
21126 char_u *src; /* string with modifiers */
21127 int *usedlen; /* characters after src that are used */
21128 char_u **fnamep; /* file name so far */
21129 char_u **bufp; /* buffer for allocated file name or NULL */
21130 int *fnamelen; /* length of fnamep */
21132 int valid = 0;
21133 char_u *tail;
21134 char_u *s, *p, *pbuf;
21135 char_u dirname[MAXPATHL];
21136 int c;
21137 int has_fullname = 0;
21138 #ifdef WIN3264
21139 int has_shortname = 0;
21140 #endif
21142 repeat:
21143 /* ":p" - full path/file_name */
21144 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
21146 has_fullname = 1;
21148 valid |= VALID_PATH;
21149 *usedlen += 2;
21151 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
21152 if ((*fnamep)[0] == '~'
21153 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
21154 && ((*fnamep)[1] == '/'
21155 # ifdef BACKSLASH_IN_FILENAME
21156 || (*fnamep)[1] == '\\'
21157 # endif
21158 || (*fnamep)[1] == NUL)
21160 #endif
21163 *fnamep = expand_env_save(*fnamep);
21164 vim_free(*bufp); /* free any allocated file name */
21165 *bufp = *fnamep;
21166 if (*fnamep == NULL)
21167 return -1;
21170 /* When "/." or "/.." is used: force expansion to get rid of it. */
21171 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
21173 if (vim_ispathsep(*p)
21174 && p[1] == '.'
21175 && (p[2] == NUL
21176 || vim_ispathsep(p[2])
21177 || (p[2] == '.'
21178 && (p[3] == NUL || vim_ispathsep(p[3])))))
21179 break;
21182 /* FullName_save() is slow, don't use it when not needed. */
21183 if (*p != NUL || !vim_isAbsName(*fnamep))
21185 *fnamep = FullName_save(*fnamep, *p != NUL);
21186 vim_free(*bufp); /* free any allocated file name */
21187 *bufp = *fnamep;
21188 if (*fnamep == NULL)
21189 return -1;
21192 /* Append a path separator to a directory. */
21193 if (mch_isdir(*fnamep))
21195 /* Make room for one or two extra characters. */
21196 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
21197 vim_free(*bufp); /* free any allocated file name */
21198 *bufp = *fnamep;
21199 if (*fnamep == NULL)
21200 return -1;
21201 add_pathsep(*fnamep);
21205 /* ":." - path relative to the current directory */
21206 /* ":~" - path relative to the home directory */
21207 /* ":8" - shortname path - postponed till after */
21208 while (src[*usedlen] == ':'
21209 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
21211 *usedlen += 2;
21212 if (c == '8')
21214 #ifdef WIN3264
21215 has_shortname = 1; /* Postpone this. */
21216 #endif
21217 continue;
21219 pbuf = NULL;
21220 /* Need full path first (use expand_env() to remove a "~/") */
21221 if (!has_fullname)
21223 if (c == '.' && **fnamep == '~')
21224 p = pbuf = expand_env_save(*fnamep);
21225 else
21226 p = pbuf = FullName_save(*fnamep, FALSE);
21228 else
21229 p = *fnamep;
21231 has_fullname = 0;
21233 if (p != NULL)
21235 if (c == '.')
21237 mch_dirname(dirname, MAXPATHL);
21238 s = shorten_fname(p, dirname);
21239 if (s != NULL)
21241 *fnamep = s;
21242 if (pbuf != NULL)
21244 vim_free(*bufp); /* free any allocated file name */
21245 *bufp = pbuf;
21246 pbuf = NULL;
21250 else
21252 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
21253 /* Only replace it when it starts with '~' */
21254 if (*dirname == '~')
21256 s = vim_strsave(dirname);
21257 if (s != NULL)
21259 *fnamep = s;
21260 vim_free(*bufp);
21261 *bufp = s;
21265 vim_free(pbuf);
21269 tail = gettail(*fnamep);
21270 *fnamelen = (int)STRLEN(*fnamep);
21272 /* ":h" - head, remove "/file_name", can be repeated */
21273 /* Don't remove the first "/" or "c:\" */
21274 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
21276 valid |= VALID_HEAD;
21277 *usedlen += 2;
21278 s = get_past_head(*fnamep);
21279 while (tail > s && after_pathsep(s, tail))
21280 --tail;
21281 *fnamelen = (int)(tail - *fnamep);
21282 #ifdef VMS
21283 if (*fnamelen > 0)
21284 *fnamelen += 1; /* the path separator is part of the path */
21285 #endif
21286 while (tail > s && !after_pathsep(s, tail))
21287 mb_ptr_back(*fnamep, tail);
21290 /* ":8" - shortname */
21291 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
21293 *usedlen += 2;
21294 #ifdef WIN3264
21295 has_shortname = 1;
21296 #endif
21299 #ifdef WIN3264
21300 /* Check shortname after we have done 'heads' and before we do 'tails'
21302 if (has_shortname)
21304 pbuf = NULL;
21305 /* Copy the string if it is shortened by :h */
21306 if (*fnamelen < (int)STRLEN(*fnamep))
21308 p = vim_strnsave(*fnamep, *fnamelen);
21309 if (p == 0)
21310 return -1;
21311 vim_free(*bufp);
21312 *bufp = *fnamep = p;
21315 /* Split into two implementations - makes it easier. First is where
21316 * there isn't a full name already, second is where there is.
21318 if (!has_fullname && !vim_isAbsName(*fnamep))
21320 if (shortpath_for_partial(fnamep, bufp, fnamelen) == -1)
21321 return -1;
21323 else
21325 int l;
21327 /* Simple case, already have the full-name
21328 * Nearly always shorter, so try first time. */
21329 l = *fnamelen;
21330 if (!get_short_pathname(fnamep, bufp, &l))
21331 return -1;
21333 if (l == 0)
21335 /* Couldn't find the filename.. search the paths.
21337 l = *fnamelen;
21338 if (shortpath_for_invalid_fname(fnamep, bufp, &l ) == -1)
21339 return -1;
21341 *fnamelen = l;
21344 #endif /* WIN3264 */
21346 /* ":t" - tail, just the basename */
21347 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
21349 *usedlen += 2;
21350 *fnamelen -= (int)(tail - *fnamep);
21351 *fnamep = tail;
21354 /* ":e" - extension, can be repeated */
21355 /* ":r" - root, without extension, can be repeated */
21356 while (src[*usedlen] == ':'
21357 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
21359 /* find a '.' in the tail:
21360 * - for second :e: before the current fname
21361 * - otherwise: The last '.'
21363 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
21364 s = *fnamep - 2;
21365 else
21366 s = *fnamep + *fnamelen - 1;
21367 for ( ; s > tail; --s)
21368 if (s[0] == '.')
21369 break;
21370 if (src[*usedlen + 1] == 'e') /* :e */
21372 if (s > tail)
21374 *fnamelen += (int)(*fnamep - (s + 1));
21375 *fnamep = s + 1;
21376 #ifdef VMS
21377 /* cut version from the extension */
21378 s = *fnamep + *fnamelen - 1;
21379 for ( ; s > *fnamep; --s)
21380 if (s[0] == ';')
21381 break;
21382 if (s > *fnamep)
21383 *fnamelen = s - *fnamep;
21384 #endif
21386 else if (*fnamep <= tail)
21387 *fnamelen = 0;
21389 else /* :r */
21391 if (s > tail) /* remove one extension */
21392 *fnamelen = (int)(s - *fnamep);
21394 *usedlen += 2;
21397 /* ":s?pat?foo?" - substitute */
21398 /* ":gs?pat?foo?" - global substitute */
21399 if (src[*usedlen] == ':'
21400 && (src[*usedlen + 1] == 's'
21401 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
21403 char_u *str;
21404 char_u *pat;
21405 char_u *sub;
21406 int sep;
21407 char_u *flags;
21408 int didit = FALSE;
21410 flags = (char_u *)"";
21411 s = src + *usedlen + 2;
21412 if (src[*usedlen + 1] == 'g')
21414 flags = (char_u *)"g";
21415 ++s;
21418 sep = *s++;
21419 if (sep)
21421 /* find end of pattern */
21422 p = vim_strchr(s, sep);
21423 if (p != NULL)
21425 pat = vim_strnsave(s, (int)(p - s));
21426 if (pat != NULL)
21428 s = p + 1;
21429 /* find end of substitution */
21430 p = vim_strchr(s, sep);
21431 if (p != NULL)
21433 sub = vim_strnsave(s, (int)(p - s));
21434 str = vim_strnsave(*fnamep, *fnamelen);
21435 if (sub != NULL && str != NULL)
21437 *usedlen = (int)(p + 1 - src);
21438 s = do_string_sub(str, pat, sub, flags);
21439 if (s != NULL)
21441 *fnamep = s;
21442 *fnamelen = (int)STRLEN(s);
21443 vim_free(*bufp);
21444 *bufp = s;
21445 didit = TRUE;
21448 vim_free(sub);
21449 vim_free(str);
21451 vim_free(pat);
21454 /* after using ":s", repeat all the modifiers */
21455 if (didit)
21456 goto repeat;
21460 return valid;
21464 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
21465 * "flags" can be "g" to do a global substitute.
21466 * Returns an allocated string, NULL for error.
21468 char_u *
21469 do_string_sub(str, pat, sub, flags)
21470 char_u *str;
21471 char_u *pat;
21472 char_u *sub;
21473 char_u *flags;
21475 int sublen;
21476 regmatch_T regmatch;
21477 int i;
21478 int do_all;
21479 char_u *tail;
21480 garray_T ga;
21481 char_u *ret;
21482 char_u *save_cpo;
21484 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
21485 save_cpo = p_cpo;
21486 p_cpo = (char_u *)"";
21488 ga_init2(&ga, 1, 200);
21490 do_all = (flags[0] == 'g');
21492 regmatch.rm_ic = p_ic;
21493 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
21494 if (regmatch.regprog != NULL)
21496 tail = str;
21497 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
21500 * Get some space for a temporary buffer to do the substitution
21501 * into. It will contain:
21502 * - The text up to where the match is.
21503 * - The substituted text.
21504 * - The text after the match.
21506 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
21507 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
21508 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
21510 ga_clear(&ga);
21511 break;
21514 /* copy the text up to where the match is */
21515 i = (int)(regmatch.startp[0] - tail);
21516 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
21517 /* add the substituted text */
21518 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
21519 + ga.ga_len + i, TRUE, TRUE, FALSE);
21520 ga.ga_len += i + sublen - 1;
21521 /* avoid getting stuck on a match with an empty string */
21522 if (tail == regmatch.endp[0])
21524 if (*tail == NUL)
21525 break;
21526 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
21527 ++ga.ga_len;
21529 else
21531 tail = regmatch.endp[0];
21532 if (*tail == NUL)
21533 break;
21535 if (!do_all)
21536 break;
21539 if (ga.ga_data != NULL)
21540 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
21542 vim_free(regmatch.regprog);
21545 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
21546 ga_clear(&ga);
21547 p_cpo = save_cpo;
21549 return ret;
21552 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */