Merged from the latest developing branch.
[MacVim.git] / src / eval.c
blob3994b17274e8384651b8a493c9e0e7ae3e4b690a
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 #if defined(FEAT_EVAL) || defined(PROTO)
21 #ifdef AMIGA
22 # include <time.h> /* for strftime() */
23 #endif
25 #ifdef MACOS
26 # include <time.h> /* for time_t */
27 #endif
29 #if defined(FEAT_FLOAT) && defined(HAVE_MATH_H)
30 # include <math.h>
31 #endif
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");
113 * All user-defined global variables are stored in dictionary "globvardict".
114 * "globvars_var" is the variable that is used for "g:".
116 static dict_T globvardict;
117 static dictitem_T globvars_var;
118 #define globvarht globvardict.dv_hashtab
121 * Old Vim variables such as "v:version" are also available without the "v:".
122 * Also in functions. We need a special hashtable for them.
124 static hashtab_T compat_hashtab;
127 * When recursively copying lists and dicts we need to remember which ones we
128 * have done to avoid endless recursiveness. This unique ID is used for that.
130 static int current_copyID = 0;
133 * Array to hold the hashtab with variables local to each sourced script.
134 * Each item holds a variable (nameless) that points to the dict_T.
136 typedef struct
138 dictitem_T sv_var;
139 dict_T sv_dict;
140 } scriptvar_T;
142 static garray_T ga_scripts = {0, 0, sizeof(scriptvar_T), 4, NULL};
143 #define SCRIPT_SV(id) (((scriptvar_T *)ga_scripts.ga_data)[(id) - 1])
144 #define SCRIPT_VARS(id) (SCRIPT_SV(id).sv_dict.dv_hashtab)
146 static int echo_attr = 0; /* attributes used for ":echo" */
148 /* Values for trans_function_name() argument: */
149 #define TFN_INT 1 /* internal function name OK */
150 #define TFN_QUIET 2 /* no error messages */
153 * Structure to hold info for a user function.
155 typedef struct ufunc ufunc_T;
157 struct ufunc
159 int uf_varargs; /* variable nr of arguments */
160 int uf_flags;
161 int uf_calls; /* nr of active calls */
162 garray_T uf_args; /* arguments */
163 garray_T uf_lines; /* function lines */
164 #ifdef FEAT_PROFILE
165 int uf_profiling; /* TRUE when func is being profiled */
166 /* profiling the function as a whole */
167 int uf_tm_count; /* nr of calls */
168 proftime_T uf_tm_total; /* time spent in function + children */
169 proftime_T uf_tm_self; /* time spent in function itself */
170 proftime_T uf_tm_children; /* time spent in children this call */
171 /* profiling the function per line */
172 int *uf_tml_count; /* nr of times line was executed */
173 proftime_T *uf_tml_total; /* time spent in a line + children */
174 proftime_T *uf_tml_self; /* time spent in a line itself */
175 proftime_T uf_tml_start; /* start time for current line */
176 proftime_T uf_tml_children; /* time spent in children for this line */
177 proftime_T uf_tml_wait; /* start wait time for current line */
178 int uf_tml_idx; /* index of line being timed; -1 if none */
179 int uf_tml_execed; /* line being timed was executed */
180 #endif
181 scid_T uf_script_ID; /* ID of script where function was defined,
182 used for s: variables */
183 int uf_refcount; /* for numbered function: reference count */
184 char_u uf_name[1]; /* name of function (actually longer); can
185 start with <SNR>123_ (<SNR> is K_SPECIAL
186 KS_EXTRA KE_SNR) */
189 /* function flags */
190 #define FC_ABORT 1 /* abort function on error */
191 #define FC_RANGE 2 /* function accepts range */
192 #define FC_DICT 4 /* Dict function, uses "self" */
195 * All user-defined functions are found in this hashtable.
197 static hashtab_T func_hashtab;
199 /* The names of packages that once were loaded are remembered. */
200 static garray_T ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
202 /* list heads for garbage collection */
203 static dict_T *first_dict = NULL; /* list of all dicts */
204 static list_T *first_list = NULL; /* list of all lists */
206 /* From user function to hashitem and back. */
207 static ufunc_T dumuf;
208 #define UF2HIKEY(fp) ((fp)->uf_name)
209 #define HIKEY2UF(p) ((ufunc_T *)(p - (dumuf.uf_name - (char_u *)&dumuf)))
210 #define HI2UF(hi) HIKEY2UF((hi)->hi_key)
212 #define FUNCARG(fp, j) ((char_u **)(fp->uf_args.ga_data))[j]
213 #define FUNCLINE(fp, j) ((char_u **)(fp->uf_lines.ga_data))[j]
215 #define MAX_FUNC_ARGS 20 /* maximum number of function arguments */
216 #define VAR_SHORT_LEN 20 /* short variable name length */
217 #define FIXVAR_CNT 12 /* number of fixed variables */
219 /* structure to hold info for a function that is currently being executed. */
220 typedef struct funccall_S funccall_T;
222 struct funccall_S
224 ufunc_T *func; /* function being called */
225 int linenr; /* next line to be executed */
226 int returned; /* ":return" used */
227 struct /* fixed variables for arguments */
229 dictitem_T var; /* variable (without room for name) */
230 char_u room[VAR_SHORT_LEN]; /* room for the name */
231 } fixvar[FIXVAR_CNT];
232 dict_T l_vars; /* l: local function variables */
233 dictitem_T l_vars_var; /* variable for l: scope */
234 dict_T l_avars; /* a: argument variables */
235 dictitem_T l_avars_var; /* variable for a: scope */
236 list_T l_varlist; /* list for a:000 */
237 listitem_T l_listitems[MAX_FUNC_ARGS]; /* listitems for a:000 */
238 typval_T *rettv; /* return value */
239 linenr_T breakpoint; /* next line with breakpoint or zero */
240 int dbg_tick; /* debug_tick when breakpoint was set */
241 int level; /* top nesting level of executed function */
242 #ifdef FEAT_PROFILE
243 proftime_T prof_child; /* time spent in a child */
244 #endif
245 funccall_T *caller; /* calling function or NULL */
249 * Info used by a ":for" loop.
251 typedef struct
253 int fi_semicolon; /* TRUE if ending in '; var]' */
254 int fi_varcount; /* nr of variables in the list */
255 listwatch_T fi_lw; /* keep an eye on the item used. */
256 list_T *fi_list; /* list being used */
257 } forinfo_T;
260 * Struct used by trans_function_name()
262 typedef struct
264 dict_T *fd_dict; /* Dictionary used */
265 char_u *fd_newkey; /* new key in "dict" in allocated memory */
266 dictitem_T *fd_di; /* Dictionary item used */
267 } funcdict_T;
271 * Array to hold the value of v: variables.
272 * The value is in a dictitem, so that it can also be used in the v: scope.
273 * The reason to use this table anyway is for very quick access to the
274 * variables with the VV_ defines.
276 #include "version.h"
278 /* values for vv_flags: */
279 #define VV_COMPAT 1 /* compatible, also used without "v:" */
280 #define VV_RO 2 /* read-only */
281 #define VV_RO_SBX 4 /* read-only in the sandbox */
283 #define VV_NAME(s, t) s, {{t}}, {0}
285 static struct vimvar
287 char *vv_name; /* name of variable, without v: */
288 dictitem_T vv_di; /* value and name for key */
289 char vv_filler[16]; /* space for LONGEST name below!!! */
290 char vv_flags; /* VV_COMPAT, VV_RO, VV_RO_SBX */
291 } vimvars[VV_LEN] =
294 * The order here must match the VV_ defines in vim.h!
295 * Initializing a union does not work, leave tv.vval empty to get zero's.
297 {VV_NAME("count", VAR_NUMBER), VV_COMPAT+VV_RO},
298 {VV_NAME("count1", VAR_NUMBER), VV_RO},
299 {VV_NAME("prevcount", VAR_NUMBER), VV_RO},
300 {VV_NAME("errmsg", VAR_STRING), VV_COMPAT},
301 {VV_NAME("warningmsg", VAR_STRING), 0},
302 {VV_NAME("statusmsg", VAR_STRING), 0},
303 {VV_NAME("shell_error", VAR_NUMBER), VV_COMPAT+VV_RO},
304 {VV_NAME("this_session", VAR_STRING), VV_COMPAT},
305 {VV_NAME("version", VAR_NUMBER), VV_COMPAT+VV_RO},
306 {VV_NAME("lnum", VAR_NUMBER), VV_RO_SBX},
307 {VV_NAME("termresponse", VAR_STRING), VV_RO},
308 {VV_NAME("fname", VAR_STRING), VV_RO},
309 {VV_NAME("lang", VAR_STRING), VV_RO},
310 {VV_NAME("lc_time", VAR_STRING), VV_RO},
311 {VV_NAME("ctype", VAR_STRING), VV_RO},
312 {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
313 {VV_NAME("charconvert_to", VAR_STRING), VV_RO},
314 {VV_NAME("fname_in", VAR_STRING), VV_RO},
315 {VV_NAME("fname_out", VAR_STRING), VV_RO},
316 {VV_NAME("fname_new", VAR_STRING), VV_RO},
317 {VV_NAME("fname_diff", VAR_STRING), VV_RO},
318 {VV_NAME("cmdarg", VAR_STRING), VV_RO},
319 {VV_NAME("foldstart", VAR_NUMBER), VV_RO_SBX},
320 {VV_NAME("foldend", VAR_NUMBER), VV_RO_SBX},
321 {VV_NAME("folddashes", VAR_STRING), VV_RO_SBX},
322 {VV_NAME("foldlevel", VAR_NUMBER), VV_RO_SBX},
323 {VV_NAME("progname", VAR_STRING), VV_RO},
324 {VV_NAME("servername", VAR_STRING), VV_RO},
325 {VV_NAME("dying", VAR_NUMBER), VV_RO},
326 {VV_NAME("exception", VAR_STRING), VV_RO},
327 {VV_NAME("throwpoint", VAR_STRING), VV_RO},
328 {VV_NAME("register", VAR_STRING), VV_RO},
329 {VV_NAME("cmdbang", VAR_NUMBER), VV_RO},
330 {VV_NAME("insertmode", VAR_STRING), VV_RO},
331 {VV_NAME("val", VAR_UNKNOWN), VV_RO},
332 {VV_NAME("key", VAR_UNKNOWN), VV_RO},
333 {VV_NAME("profiling", VAR_NUMBER), VV_RO},
334 {VV_NAME("fcs_reason", VAR_STRING), VV_RO},
335 {VV_NAME("fcs_choice", VAR_STRING), 0},
336 {VV_NAME("beval_bufnr", VAR_NUMBER), VV_RO},
337 {VV_NAME("beval_winnr", VAR_NUMBER), VV_RO},
338 {VV_NAME("beval_lnum", VAR_NUMBER), VV_RO},
339 {VV_NAME("beval_col", VAR_NUMBER), VV_RO},
340 {VV_NAME("beval_text", VAR_STRING), VV_RO},
341 {VV_NAME("scrollstart", VAR_STRING), 0},
342 {VV_NAME("swapname", VAR_STRING), VV_RO},
343 {VV_NAME("swapchoice", VAR_STRING), 0},
344 {VV_NAME("swapcommand", VAR_STRING), VV_RO},
345 {VV_NAME("char", VAR_STRING), VV_RO},
346 {VV_NAME("mouse_win", VAR_NUMBER), 0},
347 {VV_NAME("mouse_lnum", VAR_NUMBER), 0},
348 {VV_NAME("mouse_col", VAR_NUMBER), 0},
349 {VV_NAME("operator", VAR_STRING), VV_RO},
350 {VV_NAME("searchforward", VAR_NUMBER), 0},
353 /* shorthand */
354 #define vv_type vv_di.di_tv.v_type
355 #define vv_nr vv_di.di_tv.vval.v_number
356 #define vv_float vv_di.di_tv.vval.v_float
357 #define vv_str vv_di.di_tv.vval.v_string
358 #define vv_tv vv_di.di_tv
361 * The v: variables are stored in dictionary "vimvardict".
362 * "vimvars_var" is the variable that is used for the "l:" scope.
364 static dict_T vimvardict;
365 static dictitem_T vimvars_var;
366 #define vimvarht vimvardict.dv_hashtab
368 static void prepare_vimvar __ARGS((int idx, typval_T *save_tv));
369 static void restore_vimvar __ARGS((int idx, typval_T *save_tv));
370 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
371 static int call_vim_function __ARGS((char_u *func, int argc, char_u **argv, int safe, typval_T *rettv));
372 #endif
373 static int ex_let_vars __ARGS((char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars));
374 static char_u *skip_var_list __ARGS((char_u *arg, int *var_count, int *semicolon));
375 static char_u *skip_var_one __ARGS((char_u *arg));
376 static void list_hashtable_vars __ARGS((hashtab_T *ht, char_u *prefix, int empty, int *first));
377 static void list_glob_vars __ARGS((int *first));
378 static void list_buf_vars __ARGS((int *first));
379 static void list_win_vars __ARGS((int *first));
380 #ifdef FEAT_WINDOWS
381 static void list_tab_vars __ARGS((int *first));
382 #endif
383 static void list_vim_vars __ARGS((int *first));
384 static void list_script_vars __ARGS((int *first));
385 static void list_func_vars __ARGS((int *first));
386 static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg, int *first));
387 static char_u *ex_let_one __ARGS((char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op));
388 static int check_changedtick __ARGS((char_u *arg));
389 static char_u *get_lval __ARGS((char_u *name, typval_T *rettv, lval_T *lp, int unlet, int skip, int quiet, int fne_flags));
390 static void clear_lval __ARGS((lval_T *lp));
391 static void set_var_lval __ARGS((lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op));
392 static int tv_op __ARGS((typval_T *tv1, typval_T *tv2, char_u *op));
393 static void list_add_watch __ARGS((list_T *l, listwatch_T *lw));
394 static void list_rem_watch __ARGS((list_T *l, listwatch_T *lwrem));
395 static void list_fix_watch __ARGS((list_T *l, listitem_T *item));
396 static void ex_unletlock __ARGS((exarg_T *eap, char_u *argstart, int deep));
397 static int do_unlet_var __ARGS((lval_T *lp, char_u *name_end, int forceit));
398 static int do_lock_var __ARGS((lval_T *lp, char_u *name_end, int deep, int lock));
399 static void item_lock __ARGS((typval_T *tv, int deep, int lock));
400 static int tv_islocked __ARGS((typval_T *tv));
402 static int eval0 __ARGS((char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate));
403 static int eval1 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
404 static int eval2 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
405 static int eval3 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
406 static int eval4 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
407 static int eval5 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
408 static int eval6 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
409 static int eval7 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
411 static int eval_index __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
412 static int get_option_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
413 static int get_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
414 static int get_lit_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
415 static int get_list_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
416 static int rettv_list_alloc __ARGS((typval_T *rettv));
417 static listitem_T *listitem_alloc __ARGS((void));
418 static void listitem_free __ARGS((listitem_T *item));
419 static void listitem_remove __ARGS((list_T *l, listitem_T *item));
420 static long list_len __ARGS((list_T *l));
421 static int list_equal __ARGS((list_T *l1, list_T *l2, int ic));
422 static int dict_equal __ARGS((dict_T *d1, dict_T *d2, int ic));
423 static int tv_equal __ARGS((typval_T *tv1, typval_T *tv2, int ic));
424 static listitem_T *list_find __ARGS((list_T *l, long n));
425 static long list_find_nr __ARGS((list_T *l, long idx, int *errorp));
426 static long list_idx_of_item __ARGS((list_T *l, listitem_T *item));
427 static void list_append __ARGS((list_T *l, listitem_T *item));
428 static int list_append_tv __ARGS((list_T *l, typval_T *tv));
429 static int list_append_string __ARGS((list_T *l, char_u *str, int len));
430 static int list_append_number __ARGS((list_T *l, varnumber_T n));
431 static int list_insert_tv __ARGS((list_T *l, typval_T *tv, listitem_T *item));
432 static int list_extend __ARGS((list_T *l1, list_T *l2, listitem_T *bef));
433 static int list_concat __ARGS((list_T *l1, list_T *l2, typval_T *tv));
434 static list_T *list_copy __ARGS((list_T *orig, int deep, int copyID));
435 static void list_remove __ARGS((list_T *l, listitem_T *item, listitem_T *item2));
436 static char_u *list2string __ARGS((typval_T *tv, int copyID));
437 static int list_join __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo, int copyID));
438 static void set_ref_in_ht __ARGS((hashtab_T *ht, int copyID));
439 static void set_ref_in_list __ARGS((list_T *l, int copyID));
440 static void set_ref_in_item __ARGS((typval_T *tv, int copyID));
441 static void dict_unref __ARGS((dict_T *d));
442 static void dict_free __ARGS((dict_T *d, int recurse));
443 static dictitem_T *dictitem_alloc __ARGS((char_u *key));
444 static dictitem_T *dictitem_copy __ARGS((dictitem_T *org));
445 static void dictitem_remove __ARGS((dict_T *dict, dictitem_T *item));
446 static void dictitem_free __ARGS((dictitem_T *item));
447 static dict_T *dict_copy __ARGS((dict_T *orig, int deep, int copyID));
448 static int dict_add __ARGS((dict_T *d, dictitem_T *item));
449 static long dict_len __ARGS((dict_T *d));
450 static dictitem_T *dict_find __ARGS((dict_T *d, char_u *key, int len));
451 static char_u *dict2string __ARGS((typval_T *tv, int copyID));
452 static int get_dict_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
453 static char_u *echo_string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
454 static char_u *tv2string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
455 static char_u *string_quote __ARGS((char_u *str, int function));
456 #ifdef FEAT_FLOAT
457 static int string2float __ARGS((char_u *text, float_T *value));
458 #endif
459 static int get_env_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
460 static int find_internal_func __ARGS((char_u *name));
461 static char_u *deref_func_name __ARGS((char_u *name, int *lenp));
462 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));
463 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));
464 static void emsg_funcname __ARGS((char *ermsg, char_u *name));
466 #ifdef FEAT_FLOAT
467 static void f_abs __ARGS((typval_T *argvars, typval_T *rettv));
468 #endif
469 static void f_add __ARGS((typval_T *argvars, typval_T *rettv));
470 static void f_append __ARGS((typval_T *argvars, typval_T *rettv));
471 static void f_argc __ARGS((typval_T *argvars, typval_T *rettv));
472 static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv));
473 static void f_argv __ARGS((typval_T *argvars, typval_T *rettv));
474 #ifdef FEAT_FLOAT
475 static void f_atan __ARGS((typval_T *argvars, typval_T *rettv));
476 #endif
477 static void f_browse __ARGS((typval_T *argvars, typval_T *rettv));
478 static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv));
479 static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv));
480 static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv));
481 static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv));
482 static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv));
483 static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv));
484 static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv));
485 static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv));
486 static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv));
487 static void f_call __ARGS((typval_T *argvars, typval_T *rettv));
488 #ifdef FEAT_FLOAT
489 static void f_ceil __ARGS((typval_T *argvars, typval_T *rettv));
490 #endif
491 static void f_changenr __ARGS((typval_T *argvars, typval_T *rettv));
492 static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv));
493 static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv));
494 static void f_clearmatches __ARGS((typval_T *argvars, typval_T *rettv));
495 static void f_col __ARGS((typval_T *argvars, typval_T *rettv));
496 #if defined(FEAT_INS_EXPAND)
497 static void f_complete __ARGS((typval_T *argvars, typval_T *rettv));
498 static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv));
499 static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv));
500 #endif
501 static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv));
502 static void f_copy __ARGS((typval_T *argvars, typval_T *rettv));
503 #ifdef FEAT_FLOAT
504 static void f_cos __ARGS((typval_T *argvars, typval_T *rettv));
505 #endif
506 static void f_count __ARGS((typval_T *argvars, typval_T *rettv));
507 static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv));
508 static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv));
509 static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv));
510 static void f_delete __ARGS((typval_T *argvars, typval_T *rettv));
511 static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv));
513 static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv));
514 static void f_empty __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_escape __ARGS((typval_T *argvars, typval_T *rettv));
516 static void f_eval __ARGS((typval_T *argvars, typval_T *rettv));
517 static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_executable __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_exists __ARGS((typval_T *argvars, typval_T *rettv));
520 static void f_expand __ARGS((typval_T *argvars, typval_T *rettv));
521 static void f_extend __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_feedkeys __ARGS((typval_T *argvars, typval_T *rettv));
523 static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv));
524 static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv));
525 static void f_filter __ARGS((typval_T *argvars, typval_T *rettv));
526 static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv));
528 #ifdef FEAT_FLOAT
529 static void f_float2nr __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_floor __ARGS((typval_T *argvars, typval_T *rettv));
531 #endif
532 static void f_fnameescape __ARGS((typval_T *argvars, typval_T *rettv));
533 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
534 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
535 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
536 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
537 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
542 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
546 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
547 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
548 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
549 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
551 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
552 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_getpid __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
590 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
591 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
592 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
593 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
594 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
595 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
596 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
603 #ifdef FEAT_FLOAT
604 static void f_log10 __ARGS((typval_T *argvars, typval_T *rettv));
605 #endif
606 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
607 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
608 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
609 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
610 static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv));
611 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
618 #ifdef vim_mkdir
619 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
620 #endif
621 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
622 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
623 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
624 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
625 #ifdef FEAT_FLOAT
626 static void f_pow __ARGS((typval_T *argvars, typval_T *rettv));
627 #endif
628 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
629 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
630 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
631 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
632 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
633 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
634 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
635 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
636 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
637 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
638 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
639 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
640 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
641 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
642 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
643 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
644 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
645 #ifdef FEAT_FLOAT
646 static void f_round __ARGS((typval_T *argvars, typval_T *rettv));
647 #endif
648 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
649 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
650 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
651 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
652 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
653 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
654 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
655 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
656 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
657 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
667 #ifdef FEAT_FLOAT
668 static void f_sin __ARGS((typval_T *argvars, typval_T *rettv));
669 #endif
670 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
671 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
672 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
673 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
674 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
675 #ifdef FEAT_FLOAT
676 static void f_sqrt __ARGS((typval_T *argvars, typval_T *rettv));
677 static void f_str2float __ARGS((typval_T *argvars, typval_T *rettv));
678 #endif
679 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
680 #ifdef HAVE_STRFTIME
681 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
682 #endif
683 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
684 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
685 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
686 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
687 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
688 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
689 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
690 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
691 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
692 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
693 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
694 static void f_synstack __ARGS((typval_T *argvars, typval_T *rettv));
695 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
696 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
697 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
698 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
699 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
700 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
701 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
702 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
703 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
704 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
705 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
706 #ifdef FEAT_FLOAT
707 static void f_trunc __ARGS((typval_T *argvars, typval_T *rettv));
708 #endif
709 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
710 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
711 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
712 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
713 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
714 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
715 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
716 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
717 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
718 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
719 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
720 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
721 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
722 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
724 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
725 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
726 static int get_env_len __ARGS((char_u **arg));
727 static int get_id_len __ARGS((char_u **arg));
728 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
729 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
730 #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */
731 #define FNE_CHECK_START 2 /* find_name_end(): check name starts with
732 valid character */
733 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
734 static int eval_isnamec __ARGS((int c));
735 static int eval_isnamec1 __ARGS((int c));
736 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
737 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
738 static typval_T *alloc_tv __ARGS((void));
739 static typval_T *alloc_string_tv __ARGS((char_u *string));
740 static void init_tv __ARGS((typval_T *varp));
741 static long get_tv_number __ARGS((typval_T *varp));
742 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
743 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
744 static char_u *get_tv_string __ARGS((typval_T *varp));
745 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
746 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
747 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
748 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
749 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
750 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
751 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
752 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
753 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
754 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
755 static int var_check_ro __ARGS((int flags, char_u *name));
756 static int var_check_fixed __ARGS((int flags, char_u *name));
757 static int tv_check_lock __ARGS((int lock, char_u *name));
758 static void copy_tv __ARGS((typval_T *from, typval_T *to));
759 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
760 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
761 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
762 static int eval_fname_script __ARGS((char_u *p));
763 static int eval_fname_sid __ARGS((char_u *p));
764 static void list_func_head __ARGS((ufunc_T *fp, int indent));
765 static ufunc_T *find_func __ARGS((char_u *name));
766 static int function_exists __ARGS((char_u *name));
767 static int builtin_function __ARGS((char_u *name));
768 #ifdef FEAT_PROFILE
769 static void func_do_profile __ARGS((ufunc_T *fp));
770 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
771 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
772 static int
773 # ifdef __BORLANDC__
774 _RTLENTRYF
775 # endif
776 prof_total_cmp __ARGS((const void *s1, const void *s2));
777 static int
778 # ifdef __BORLANDC__
779 _RTLENTRYF
780 # endif
781 prof_self_cmp __ARGS((const void *s1, const void *s2));
782 #endif
783 static int script_autoload __ARGS((char_u *name, int reload));
784 static char_u *autoload_name __ARGS((char_u *name));
785 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
786 static void func_free __ARGS((ufunc_T *fp));
787 static void func_unref __ARGS((char_u *name));
788 static void func_ref __ARGS((char_u *name));
789 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));
790 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
791 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
792 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
793 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
794 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
795 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
797 /* Character used as separated in autoload function/variable names. */
798 #define AUTOLOAD_CHAR '#'
801 * Initialize the global and v: variables.
803 void
804 eval_init()
806 int i;
807 struct vimvar *p;
809 init_var_dict(&globvardict, &globvars_var);
810 init_var_dict(&vimvardict, &vimvars_var);
811 hash_init(&compat_hashtab);
812 hash_init(&func_hashtab);
814 for (i = 0; i < VV_LEN; ++i)
816 p = &vimvars[i];
817 STRCPY(p->vv_di.di_key, p->vv_name);
818 if (p->vv_flags & VV_RO)
819 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
820 else if (p->vv_flags & VV_RO_SBX)
821 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
822 else
823 p->vv_di.di_flags = DI_FLAGS_FIX;
825 /* add to v: scope dict, unless the value is not always available */
826 if (p->vv_type != VAR_UNKNOWN)
827 hash_add(&vimvarht, p->vv_di.di_key);
828 if (p->vv_flags & VV_COMPAT)
829 /* add to compat scope dict */
830 hash_add(&compat_hashtab, p->vv_di.di_key);
832 set_vim_var_nr(VV_SEARCHFORWARD, 1L);
835 #if defined(EXITFREE) || defined(PROTO)
836 void
837 eval_clear()
839 int i;
840 struct vimvar *p;
842 for (i = 0; i < VV_LEN; ++i)
844 p = &vimvars[i];
845 if (p->vv_di.di_tv.v_type == VAR_STRING)
847 vim_free(p->vv_di.di_tv.vval.v_string);
848 p->vv_di.di_tv.vval.v_string = NULL;
851 hash_clear(&vimvarht);
852 hash_clear(&compat_hashtab);
854 /* script-local variables */
855 for (i = 1; i <= ga_scripts.ga_len; ++i)
856 vars_clear(&SCRIPT_VARS(i));
857 ga_clear(&ga_scripts);
858 free_scriptnames();
860 /* global variables */
861 vars_clear(&globvarht);
863 /* autoloaded script names */
864 ga_clear_strings(&ga_loaded);
866 /* unreferenced lists and dicts */
867 (void)garbage_collect();
869 /* functions */
870 free_all_functions();
871 hash_clear(&func_hashtab);
873 #endif
876 * Return the name of the executed function.
878 char_u *
879 func_name(cookie)
880 void *cookie;
882 return ((funccall_T *)cookie)->func->uf_name;
886 * Return the address holding the next breakpoint line for a funccall cookie.
888 linenr_T *
889 func_breakpoint(cookie)
890 void *cookie;
892 return &((funccall_T *)cookie)->breakpoint;
896 * Return the address holding the debug tick for a funccall cookie.
898 int *
899 func_dbg_tick(cookie)
900 void *cookie;
902 return &((funccall_T *)cookie)->dbg_tick;
906 * Return the nesting level for a funccall cookie.
909 func_level(cookie)
910 void *cookie;
912 return ((funccall_T *)cookie)->level;
915 /* pointer to funccal for currently active function */
916 funccall_T *current_funccal = NULL;
919 * Return TRUE when a function was ended by a ":return" command.
922 current_func_returned()
924 return current_funccal->returned;
929 * Set an internal variable to a string value. Creates the variable if it does
930 * not already exist.
932 void
933 set_internal_string_var(name, value)
934 char_u *name;
935 char_u *value;
937 char_u *val;
938 typval_T *tvp;
940 val = vim_strsave(value);
941 if (val != NULL)
943 tvp = alloc_string_tv(val);
944 if (tvp != NULL)
946 set_var(name, tvp, FALSE);
947 free_tv(tvp);
952 static lval_T *redir_lval = NULL;
953 static garray_T redir_ga; /* only valid when redir_lval is not NULL */
954 static char_u *redir_endp = NULL;
955 static char_u *redir_varname = NULL;
958 * Start recording command output to a variable
959 * Returns OK if successfully completed the setup. FAIL otherwise.
962 var_redir_start(name, append)
963 char_u *name;
964 int append; /* append to an existing variable */
966 int save_emsg;
967 int err;
968 typval_T tv;
970 /* Make sure a valid variable name is specified */
971 if (!eval_isnamec1(*name))
973 EMSG(_(e_invarg));
974 return FAIL;
977 redir_varname = vim_strsave(name);
978 if (redir_varname == NULL)
979 return FAIL;
981 redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
982 if (redir_lval == NULL)
984 var_redir_stop();
985 return FAIL;
988 /* The output is stored in growarray "redir_ga" until redirection ends. */
989 ga_init2(&redir_ga, (int)sizeof(char), 500);
991 /* Parse the variable name (can be a dict or list entry). */
992 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
993 FNE_CHECK_START);
994 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
996 if (redir_endp != NULL && *redir_endp != NUL)
997 /* Trailing characters are present after the variable name */
998 EMSG(_(e_trailing));
999 else
1000 EMSG(_(e_invarg));
1001 var_redir_stop();
1002 return FAIL;
1005 /* check if we can write to the variable: set it to or append an empty
1006 * string */
1007 save_emsg = did_emsg;
1008 did_emsg = FALSE;
1009 tv.v_type = VAR_STRING;
1010 tv.vval.v_string = (char_u *)"";
1011 if (append)
1012 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
1013 else
1014 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
1015 err = did_emsg;
1016 did_emsg |= save_emsg;
1017 if (err)
1019 var_redir_stop();
1020 return FAIL;
1022 if (redir_lval->ll_newkey != NULL)
1024 /* Dictionary item was created, don't do it again. */
1025 vim_free(redir_lval->ll_newkey);
1026 redir_lval->ll_newkey = NULL;
1029 return OK;
1033 * Append "value[value_len]" to the variable set by var_redir_start().
1034 * The actual appending is postponed until redirection ends, because the value
1035 * appended may in fact be the string we write to, changing it may cause freed
1036 * memory to be used:
1037 * :redir => foo
1038 * :let foo
1039 * :redir END
1041 void
1042 var_redir_str(value, value_len)
1043 char_u *value;
1044 int value_len;
1046 int len;
1048 if (redir_lval == NULL)
1049 return;
1051 if (value_len == -1)
1052 len = (int)STRLEN(value); /* Append the entire string */
1053 else
1054 len = value_len; /* Append only "value_len" characters */
1056 if (ga_grow(&redir_ga, len) == OK)
1058 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1059 redir_ga.ga_len += len;
1061 else
1062 var_redir_stop();
1066 * Stop redirecting command output to a variable.
1068 void
1069 var_redir_stop()
1071 typval_T tv;
1073 if (redir_lval != NULL)
1075 /* Append the trailing NUL. */
1076 ga_append(&redir_ga, NUL);
1078 /* Assign the text to the variable. */
1079 tv.v_type = VAR_STRING;
1080 tv.vval.v_string = redir_ga.ga_data;
1081 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1082 vim_free(tv.vval.v_string);
1084 clear_lval(redir_lval);
1085 vim_free(redir_lval);
1086 redir_lval = NULL;
1088 vim_free(redir_varname);
1089 redir_varname = NULL;
1092 # if defined(FEAT_MBYTE) || defined(PROTO)
1094 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1095 char_u *enc_from;
1096 char_u *enc_to;
1097 char_u *fname_from;
1098 char_u *fname_to;
1100 int err = FALSE;
1102 set_vim_var_string(VV_CC_FROM, enc_from, -1);
1103 set_vim_var_string(VV_CC_TO, enc_to, -1);
1104 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1105 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1106 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1107 err = TRUE;
1108 set_vim_var_string(VV_CC_FROM, NULL, -1);
1109 set_vim_var_string(VV_CC_TO, NULL, -1);
1110 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1111 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1113 if (err)
1114 return FAIL;
1115 return OK;
1117 # endif
1119 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1121 eval_printexpr(fname, args)
1122 char_u *fname;
1123 char_u *args;
1125 int err = FALSE;
1127 set_vim_var_string(VV_FNAME_IN, fname, -1);
1128 set_vim_var_string(VV_CMDARG, args, -1);
1129 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1130 err = TRUE;
1131 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1132 set_vim_var_string(VV_CMDARG, NULL, -1);
1134 if (err)
1136 mch_remove(fname);
1137 return FAIL;
1139 return OK;
1141 # endif
1143 # if defined(FEAT_DIFF) || defined(PROTO)
1144 void
1145 eval_diff(origfile, newfile, outfile)
1146 char_u *origfile;
1147 char_u *newfile;
1148 char_u *outfile;
1150 int err = FALSE;
1152 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1153 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1154 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1155 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1156 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1157 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1158 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1161 void
1162 eval_patch(origfile, difffile, outfile)
1163 char_u *origfile;
1164 char_u *difffile;
1165 char_u *outfile;
1167 int err;
1169 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1170 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1171 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1172 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1173 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1174 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1175 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1177 # endif
1180 * Top level evaluation function, returning a boolean.
1181 * Sets "error" to TRUE if there was an error.
1182 * Return TRUE or FALSE.
1185 eval_to_bool(arg, error, nextcmd, skip)
1186 char_u *arg;
1187 int *error;
1188 char_u **nextcmd;
1189 int skip; /* only parse, don't execute */
1191 typval_T tv;
1192 int retval = FALSE;
1194 if (skip)
1195 ++emsg_skip;
1196 if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1197 *error = TRUE;
1198 else
1200 *error = FALSE;
1201 if (!skip)
1203 retval = (get_tv_number_chk(&tv, error) != 0);
1204 clear_tv(&tv);
1207 if (skip)
1208 --emsg_skip;
1210 return retval;
1214 * Top level evaluation function, returning a string. If "skip" is TRUE,
1215 * only parsing to "nextcmd" is done, without reporting errors. Return
1216 * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1218 char_u *
1219 eval_to_string_skip(arg, nextcmd, skip)
1220 char_u *arg;
1221 char_u **nextcmd;
1222 int skip; /* only parse, don't execute */
1224 typval_T tv;
1225 char_u *retval;
1227 if (skip)
1228 ++emsg_skip;
1229 if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1230 retval = NULL;
1231 else
1233 retval = vim_strsave(get_tv_string(&tv));
1234 clear_tv(&tv);
1236 if (skip)
1237 --emsg_skip;
1239 return retval;
1243 * Skip over an expression at "*pp".
1244 * Return FAIL for an error, OK otherwise.
1247 skip_expr(pp)
1248 char_u **pp;
1250 typval_T rettv;
1252 *pp = skipwhite(*pp);
1253 return eval1(pp, &rettv, FALSE);
1257 * Top level evaluation function, returning a string.
1258 * Return pointer to allocated memory, or NULL for failure.
1260 char_u *
1261 eval_to_string(arg, nextcmd, dolist)
1262 char_u *arg;
1263 char_u **nextcmd;
1264 int dolist; /* turn List into sequence of lines */
1266 typval_T tv;
1267 char_u *retval;
1268 garray_T ga;
1270 if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1271 retval = NULL;
1272 else
1274 if (dolist && tv.v_type == VAR_LIST)
1276 ga_init2(&ga, (int)sizeof(char), 80);
1277 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1278 ga_append(&ga, NUL);
1279 retval = (char_u *)ga.ga_data;
1281 else
1282 retval = vim_strsave(get_tv_string(&tv));
1283 clear_tv(&tv);
1286 return retval;
1290 * Call eval_to_string() without using current local variables and using
1291 * textlock. When "use_sandbox" is TRUE use the sandbox.
1293 char_u *
1294 eval_to_string_safe(arg, nextcmd, use_sandbox)
1295 char_u *arg;
1296 char_u **nextcmd;
1297 int use_sandbox;
1299 char_u *retval;
1300 void *save_funccalp;
1302 save_funccalp = save_funccal();
1303 if (use_sandbox)
1304 ++sandbox;
1305 ++textlock;
1306 retval = eval_to_string(arg, nextcmd, FALSE);
1307 if (use_sandbox)
1308 --sandbox;
1309 --textlock;
1310 restore_funccal(save_funccalp);
1311 return retval;
1315 * Top level evaluation function, returning a number.
1316 * Evaluates "expr" silently.
1317 * Returns -1 for an error.
1320 eval_to_number(expr)
1321 char_u *expr;
1323 typval_T rettv;
1324 int retval;
1325 char_u *p = skipwhite(expr);
1327 ++emsg_off;
1329 if (eval1(&p, &rettv, TRUE) == FAIL)
1330 retval = -1;
1331 else
1333 retval = get_tv_number_chk(&rettv, NULL);
1334 clear_tv(&rettv);
1336 --emsg_off;
1338 return retval;
1342 * Prepare v: variable "idx" to be used.
1343 * Save the current typeval in "save_tv".
1344 * When not used yet add the variable to the v: hashtable.
1346 static void
1347 prepare_vimvar(idx, save_tv)
1348 int idx;
1349 typval_T *save_tv;
1351 *save_tv = vimvars[idx].vv_tv;
1352 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1353 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1357 * Restore v: variable "idx" to typeval "save_tv".
1358 * When no longer defined, remove the variable from the v: hashtable.
1360 static void
1361 restore_vimvar(idx, save_tv)
1362 int idx;
1363 typval_T *save_tv;
1365 hashitem_T *hi;
1367 vimvars[idx].vv_tv = *save_tv;
1368 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1370 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1371 if (HASHITEM_EMPTY(hi))
1372 EMSG2(_(e_intern2), "restore_vimvar()");
1373 else
1374 hash_remove(&vimvarht, hi);
1378 #if defined(FEAT_SPELL) || defined(PROTO)
1380 * Evaluate an expression to a list with suggestions.
1381 * For the "expr:" part of 'spellsuggest'.
1383 list_T *
1384 eval_spell_expr(badword, expr)
1385 char_u *badword;
1386 char_u *expr;
1388 typval_T save_val;
1389 typval_T rettv;
1390 list_T *list = NULL;
1391 char_u *p = skipwhite(expr);
1393 /* Set "v:val" to the bad word. */
1394 prepare_vimvar(VV_VAL, &save_val);
1395 vimvars[VV_VAL].vv_type = VAR_STRING;
1396 vimvars[VV_VAL].vv_str = badword;
1397 if (p_verbose == 0)
1398 ++emsg_off;
1400 if (eval1(&p, &rettv, TRUE) == OK)
1402 if (rettv.v_type != VAR_LIST)
1403 clear_tv(&rettv);
1404 else
1405 list = rettv.vval.v_list;
1408 if (p_verbose == 0)
1409 --emsg_off;
1410 restore_vimvar(VV_VAL, &save_val);
1412 return list;
1416 * "list" is supposed to contain two items: a word and a number. Return the
1417 * word in "pp" and the number as the return value.
1418 * Return -1 if anything isn't right.
1419 * Used to get the good word and score from the eval_spell_expr() result.
1422 get_spellword(list, pp)
1423 list_T *list;
1424 char_u **pp;
1426 listitem_T *li;
1428 li = list->lv_first;
1429 if (li == NULL)
1430 return -1;
1431 *pp = get_tv_string(&li->li_tv);
1433 li = li->li_next;
1434 if (li == NULL)
1435 return -1;
1436 return get_tv_number(&li->li_tv);
1438 #endif
1441 * Top level evaluation function.
1442 * Returns an allocated typval_T with the result.
1443 * Returns NULL when there is an error.
1445 typval_T *
1446 eval_expr(arg, nextcmd)
1447 char_u *arg;
1448 char_u **nextcmd;
1450 typval_T *tv;
1452 tv = (typval_T *)alloc(sizeof(typval_T));
1453 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1455 vim_free(tv);
1456 tv = NULL;
1459 return tv;
1463 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1464 || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1466 * Call some vimL function and return the result in "*rettv".
1467 * Uses argv[argc] for the function arguments. Only Number and String
1468 * arguments are currently supported.
1469 * Returns OK or FAIL.
1471 static int
1472 call_vim_function(func, argc, argv, safe, rettv)
1473 char_u *func;
1474 int argc;
1475 char_u **argv;
1476 int safe; /* use the sandbox */
1477 typval_T *rettv;
1479 typval_T *argvars;
1480 long n;
1481 int len;
1482 int i;
1483 int doesrange;
1484 void *save_funccalp = NULL;
1485 int ret;
1487 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1488 if (argvars == NULL)
1489 return FAIL;
1491 for (i = 0; i < argc; i++)
1493 /* Pass a NULL or empty argument as an empty string */
1494 if (argv[i] == NULL || *argv[i] == NUL)
1496 argvars[i].v_type = VAR_STRING;
1497 argvars[i].vval.v_string = (char_u *)"";
1498 continue;
1501 /* Recognize a number argument, the others must be strings. */
1502 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1503 if (len != 0 && len == (int)STRLEN(argv[i]))
1505 argvars[i].v_type = VAR_NUMBER;
1506 argvars[i].vval.v_number = n;
1508 else
1510 argvars[i].v_type = VAR_STRING;
1511 argvars[i].vval.v_string = argv[i];
1515 if (safe)
1517 save_funccalp = save_funccal();
1518 ++sandbox;
1521 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1522 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1523 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1524 &doesrange, TRUE, NULL);
1525 if (safe)
1527 --sandbox;
1528 restore_funccal(save_funccalp);
1530 vim_free(argvars);
1532 if (ret == FAIL)
1533 clear_tv(rettv);
1535 return ret;
1538 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1540 * Call vimL function "func" and return the result as a string.
1541 * Returns NULL when calling the function fails.
1542 * Uses argv[argc] for the function arguments.
1544 void *
1545 call_func_retstr(func, argc, argv, safe)
1546 char_u *func;
1547 int argc;
1548 char_u **argv;
1549 int safe; /* use the sandbox */
1551 typval_T rettv;
1552 char_u *retval;
1554 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1555 return NULL;
1557 retval = vim_strsave(get_tv_string(&rettv));
1558 clear_tv(&rettv);
1559 return retval;
1561 # endif
1563 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1565 * Call vimL function "func" and return the result as a number.
1566 * Returns -1 when calling the function fails.
1567 * Uses argv[argc] for the function arguments.
1569 long
1570 call_func_retnr(func, argc, argv, safe)
1571 char_u *func;
1572 int argc;
1573 char_u **argv;
1574 int safe; /* use the sandbox */
1576 typval_T rettv;
1577 long retval;
1579 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1580 return -1;
1582 retval = get_tv_number_chk(&rettv, NULL);
1583 clear_tv(&rettv);
1584 return retval;
1586 # endif
1589 * Call vimL function "func" and return the result as a list
1590 * Uses argv[argc] for the function arguments.
1592 void *
1593 call_func_retlist(func, argc, argv, safe)
1594 char_u *func;
1595 int argc;
1596 char_u **argv;
1597 int safe; /* use the sandbox */
1599 typval_T rettv;
1601 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1602 return NULL;
1604 if (rettv.v_type != VAR_LIST)
1606 clear_tv(&rettv);
1607 return NULL;
1610 return rettv.vval.v_list;
1612 #endif
1616 * Save the current function call pointer, and set it to NULL.
1617 * Used when executing autocommands and for ":source".
1619 void *
1620 save_funccal()
1622 funccall_T *fc = current_funccal;
1624 current_funccal = NULL;
1625 return (void *)fc;
1628 void
1629 restore_funccal(vfc)
1630 void *vfc;
1632 funccall_T *fc = (funccall_T *)vfc;
1634 current_funccal = fc;
1637 #if defined(FEAT_PROFILE) || defined(PROTO)
1639 * Prepare profiling for entering a child or something else that is not
1640 * counted for the script/function itself.
1641 * Should always be called in pair with prof_child_exit().
1643 void
1644 prof_child_enter(tm)
1645 proftime_T *tm; /* place to store waittime */
1647 funccall_T *fc = current_funccal;
1649 if (fc != NULL && fc->func->uf_profiling)
1650 profile_start(&fc->prof_child);
1651 script_prof_save(tm);
1655 * Take care of time spent in a child.
1656 * Should always be called after prof_child_enter().
1658 void
1659 prof_child_exit(tm)
1660 proftime_T *tm; /* where waittime was stored */
1662 funccall_T *fc = current_funccal;
1664 if (fc != NULL && fc->func->uf_profiling)
1666 profile_end(&fc->prof_child);
1667 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1668 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1669 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1671 script_prof_restore(tm);
1673 #endif
1676 #ifdef FEAT_FOLDING
1678 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1679 * it in "*cp". Doesn't give error messages.
1682 eval_foldexpr(arg, cp)
1683 char_u *arg;
1684 int *cp;
1686 typval_T tv;
1687 int retval;
1688 char_u *s;
1689 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1690 OPT_LOCAL);
1692 ++emsg_off;
1693 if (use_sandbox)
1694 ++sandbox;
1695 ++textlock;
1696 *cp = NUL;
1697 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1698 retval = 0;
1699 else
1701 /* If the result is a number, just return the number. */
1702 if (tv.v_type == VAR_NUMBER)
1703 retval = tv.vval.v_number;
1704 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1705 retval = 0;
1706 else
1708 /* If the result is a string, check if there is a non-digit before
1709 * the number. */
1710 s = tv.vval.v_string;
1711 if (!VIM_ISDIGIT(*s) && *s != '-')
1712 *cp = *s++;
1713 retval = atol((char *)s);
1715 clear_tv(&tv);
1717 --emsg_off;
1718 if (use_sandbox)
1719 --sandbox;
1720 --textlock;
1722 return retval;
1724 #endif
1727 * ":let" list all variable values
1728 * ":let var1 var2" list variable values
1729 * ":let var = expr" assignment command.
1730 * ":let var += expr" assignment command.
1731 * ":let var -= expr" assignment command.
1732 * ":let var .= expr" assignment command.
1733 * ":let [var1, var2] = expr" unpack list.
1735 void
1736 ex_let(eap)
1737 exarg_T *eap;
1739 char_u *arg = eap->arg;
1740 char_u *expr = NULL;
1741 typval_T rettv;
1742 int i;
1743 int var_count = 0;
1744 int semicolon = 0;
1745 char_u op[2];
1746 char_u *argend;
1747 int first = TRUE;
1749 argend = skip_var_list(arg, &var_count, &semicolon);
1750 if (argend == NULL)
1751 return;
1752 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1753 --argend;
1754 expr = vim_strchr(argend, '=');
1755 if (expr == NULL)
1758 * ":let" without "=": list variables
1760 if (*arg == '[')
1761 EMSG(_(e_invarg));
1762 else if (!ends_excmd(*arg))
1763 /* ":let var1 var2" */
1764 arg = list_arg_vars(eap, arg, &first);
1765 else if (!eap->skip)
1767 /* ":let" */
1768 list_glob_vars(&first);
1769 list_buf_vars(&first);
1770 list_win_vars(&first);
1771 #ifdef FEAT_WINDOWS
1772 list_tab_vars(&first);
1773 #endif
1774 list_script_vars(&first);
1775 list_func_vars(&first);
1776 list_vim_vars(&first);
1778 eap->nextcmd = check_nextcmd(arg);
1780 else
1782 op[0] = '=';
1783 op[1] = NUL;
1784 if (expr > argend)
1786 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1787 op[0] = expr[-1]; /* +=, -= or .= */
1789 expr = skipwhite(expr + 1);
1791 if (eap->skip)
1792 ++emsg_skip;
1793 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1794 if (eap->skip)
1796 if (i != FAIL)
1797 clear_tv(&rettv);
1798 --emsg_skip;
1800 else if (i != FAIL)
1802 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1803 op);
1804 clear_tv(&rettv);
1810 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1811 * Handles both "var" with any type and "[var, var; var]" with a list type.
1812 * When "nextchars" is not NULL it points to a string with characters that
1813 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1814 * or concatenate.
1815 * Returns OK or FAIL;
1817 static int
1818 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1819 char_u *arg_start;
1820 typval_T *tv;
1821 int copy; /* copy values from "tv", don't move */
1822 int semicolon; /* from skip_var_list() */
1823 int var_count; /* from skip_var_list() */
1824 char_u *nextchars;
1826 char_u *arg = arg_start;
1827 list_T *l;
1828 int i;
1829 listitem_T *item;
1830 typval_T ltv;
1832 if (*arg != '[')
1835 * ":let var = expr" or ":for var in list"
1837 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1838 return FAIL;
1839 return OK;
1843 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1845 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1847 EMSG(_(e_listreq));
1848 return FAIL;
1851 i = list_len(l);
1852 if (semicolon == 0 && var_count < i)
1854 EMSG(_("E687: Less targets than List items"));
1855 return FAIL;
1857 if (var_count - semicolon > i)
1859 EMSG(_("E688: More targets than List items"));
1860 return FAIL;
1863 item = l->lv_first;
1864 while (*arg != ']')
1866 arg = skipwhite(arg + 1);
1867 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1868 item = item->li_next;
1869 if (arg == NULL)
1870 return FAIL;
1872 arg = skipwhite(arg);
1873 if (*arg == ';')
1875 /* Put the rest of the list (may be empty) in the var after ';'.
1876 * Create a new list for this. */
1877 l = list_alloc();
1878 if (l == NULL)
1879 return FAIL;
1880 while (item != NULL)
1882 list_append_tv(l, &item->li_tv);
1883 item = item->li_next;
1886 ltv.v_type = VAR_LIST;
1887 ltv.v_lock = 0;
1888 ltv.vval.v_list = l;
1889 l->lv_refcount = 1;
1891 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1892 (char_u *)"]", nextchars);
1893 clear_tv(&ltv);
1894 if (arg == NULL)
1895 return FAIL;
1896 break;
1898 else if (*arg != ',' && *arg != ']')
1900 EMSG2(_(e_intern2), "ex_let_vars()");
1901 return FAIL;
1905 return OK;
1909 * Skip over assignable variable "var" or list of variables "[var, var]".
1910 * Used for ":let varvar = expr" and ":for varvar in expr".
1911 * For "[var, var]" increment "*var_count" for each variable.
1912 * for "[var, var; var]" set "semicolon".
1913 * Return NULL for an error.
1915 static char_u *
1916 skip_var_list(arg, var_count, semicolon)
1917 char_u *arg;
1918 int *var_count;
1919 int *semicolon;
1921 char_u *p, *s;
1923 if (*arg == '[')
1925 /* "[var, var]": find the matching ']'. */
1926 p = arg;
1927 for (;;)
1929 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
1930 s = skip_var_one(p);
1931 if (s == p)
1933 EMSG2(_(e_invarg2), p);
1934 return NULL;
1936 ++*var_count;
1938 p = skipwhite(s);
1939 if (*p == ']')
1940 break;
1941 else if (*p == ';')
1943 if (*semicolon == 1)
1945 EMSG(_("Double ; in list of variables"));
1946 return NULL;
1948 *semicolon = 1;
1950 else if (*p != ',')
1952 EMSG2(_(e_invarg2), p);
1953 return NULL;
1956 return p + 1;
1958 else
1959 return skip_var_one(arg);
1963 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
1964 * l[idx].
1966 static char_u *
1967 skip_var_one(arg)
1968 char_u *arg;
1970 if (*arg == '@' && arg[1] != NUL)
1971 return arg + 2;
1972 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
1973 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1977 * List variables for hashtab "ht" with prefix "prefix".
1978 * If "empty" is TRUE also list NULL strings as empty strings.
1980 static void
1981 list_hashtable_vars(ht, prefix, empty, first)
1982 hashtab_T *ht;
1983 char_u *prefix;
1984 int empty;
1985 int *first;
1987 hashitem_T *hi;
1988 dictitem_T *di;
1989 int todo;
1991 todo = (int)ht->ht_used;
1992 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
1994 if (!HASHITEM_EMPTY(hi))
1996 --todo;
1997 di = HI2DI(hi);
1998 if (empty || di->di_tv.v_type != VAR_STRING
1999 || di->di_tv.vval.v_string != NULL)
2000 list_one_var(di, prefix, first);
2006 * List global variables.
2008 static void
2009 list_glob_vars(first)
2010 int *first;
2012 list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
2016 * List buffer variables.
2018 static void
2019 list_buf_vars(first)
2020 int *first;
2022 char_u numbuf[NUMBUFLEN];
2024 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:",
2025 TRUE, first);
2027 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
2028 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
2029 numbuf, first);
2033 * List window variables.
2035 static void
2036 list_win_vars(first)
2037 int *first;
2039 list_hashtable_vars(&curwin->w_vars.dv_hashtab,
2040 (char_u *)"w:", TRUE, first);
2043 #ifdef FEAT_WINDOWS
2045 * List tab page variables.
2047 static void
2048 list_tab_vars(first)
2049 int *first;
2051 list_hashtable_vars(&curtab->tp_vars.dv_hashtab,
2052 (char_u *)"t:", TRUE, first);
2054 #endif
2057 * List Vim variables.
2059 static void
2060 list_vim_vars(first)
2061 int *first;
2063 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2067 * List script-local variables, if there is a script.
2069 static void
2070 list_script_vars(first)
2071 int *first;
2073 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2074 list_hashtable_vars(&SCRIPT_VARS(current_SID),
2075 (char_u *)"s:", FALSE, first);
2079 * List function variables, if there is a function.
2081 static void
2082 list_func_vars(first)
2083 int *first;
2085 if (current_funccal != NULL)
2086 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2087 (char_u *)"l:", FALSE, first);
2091 * List variables in "arg".
2093 static char_u *
2094 list_arg_vars(eap, arg, first)
2095 exarg_T *eap;
2096 char_u *arg;
2097 int *first;
2099 int error = FALSE;
2100 int len;
2101 char_u *name;
2102 char_u *name_start;
2103 char_u *arg_subsc;
2104 char_u *tofree;
2105 typval_T tv;
2107 while (!ends_excmd(*arg) && !got_int)
2109 if (error || eap->skip)
2111 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2112 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2114 emsg_severe = TRUE;
2115 EMSG(_(e_trailing));
2116 break;
2119 else
2121 /* get_name_len() takes care of expanding curly braces */
2122 name_start = name = arg;
2123 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2124 if (len <= 0)
2126 /* This is mainly to keep test 49 working: when expanding
2127 * curly braces fails overrule the exception error message. */
2128 if (len < 0 && !aborting())
2130 emsg_severe = TRUE;
2131 EMSG2(_(e_invarg2), arg);
2132 break;
2134 error = TRUE;
2136 else
2138 if (tofree != NULL)
2139 name = tofree;
2140 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2141 error = TRUE;
2142 else
2144 /* handle d.key, l[idx], f(expr) */
2145 arg_subsc = arg;
2146 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2147 error = TRUE;
2148 else
2150 if (arg == arg_subsc && len == 2 && name[1] == ':')
2152 switch (*name)
2154 case 'g': list_glob_vars(first); break;
2155 case 'b': list_buf_vars(first); break;
2156 case 'w': list_win_vars(first); break;
2157 #ifdef FEAT_WINDOWS
2158 case 't': list_tab_vars(first); break;
2159 #endif
2160 case 'v': list_vim_vars(first); break;
2161 case 's': list_script_vars(first); break;
2162 case 'l': list_func_vars(first); break;
2163 default:
2164 EMSG2(_("E738: Can't list variables for %s"), name);
2167 else
2169 char_u numbuf[NUMBUFLEN];
2170 char_u *tf;
2171 int c;
2172 char_u *s;
2174 s = echo_string(&tv, &tf, numbuf, 0);
2175 c = *arg;
2176 *arg = NUL;
2177 list_one_var_a((char_u *)"",
2178 arg == arg_subsc ? name : name_start,
2179 tv.v_type,
2180 s == NULL ? (char_u *)"" : s,
2181 first);
2182 *arg = c;
2183 vim_free(tf);
2185 clear_tv(&tv);
2190 vim_free(tofree);
2193 arg = skipwhite(arg);
2196 return arg;
2200 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2201 * Returns a pointer to the char just after the var name.
2202 * Returns NULL if there is an error.
2204 static char_u *
2205 ex_let_one(arg, tv, copy, endchars, op)
2206 char_u *arg; /* points to variable name */
2207 typval_T *tv; /* value to assign to variable */
2208 int copy; /* copy value from "tv" */
2209 char_u *endchars; /* valid chars after variable name or NULL */
2210 char_u *op; /* "+", "-", "." or NULL*/
2212 int c1;
2213 char_u *name;
2214 char_u *p;
2215 char_u *arg_end = NULL;
2216 int len;
2217 int opt_flags;
2218 char_u *tofree = NULL;
2221 * ":let $VAR = expr": Set environment variable.
2223 if (*arg == '$')
2225 /* Find the end of the name. */
2226 ++arg;
2227 name = arg;
2228 len = get_env_len(&arg);
2229 if (len == 0)
2230 EMSG2(_(e_invarg2), name - 1);
2231 else
2233 if (op != NULL && (*op == '+' || *op == '-'))
2234 EMSG2(_(e_letwrong), op);
2235 else if (endchars != NULL
2236 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2237 EMSG(_(e_letunexp));
2238 else
2240 c1 = name[len];
2241 name[len] = NUL;
2242 p = get_tv_string_chk(tv);
2243 if (p != NULL && op != NULL && *op == '.')
2245 int mustfree = FALSE;
2246 char_u *s = vim_getenv(name, &mustfree);
2248 if (s != NULL)
2250 p = tofree = concat_str(s, p);
2251 if (mustfree)
2252 vim_free(s);
2255 if (p != NULL)
2257 vim_setenv(name, p);
2258 if (STRICMP(name, "HOME") == 0)
2259 init_homedir();
2260 else if (didset_vim && STRICMP(name, "VIM") == 0)
2261 didset_vim = FALSE;
2262 else if (didset_vimruntime
2263 && STRICMP(name, "VIMRUNTIME") == 0)
2264 didset_vimruntime = FALSE;
2265 arg_end = arg;
2267 name[len] = c1;
2268 vim_free(tofree);
2274 * ":let &option = expr": Set option value.
2275 * ":let &l:option = expr": Set local option value.
2276 * ":let &g:option = expr": Set global option value.
2278 else if (*arg == '&')
2280 /* Find the end of the name. */
2281 p = find_option_end(&arg, &opt_flags);
2282 if (p == NULL || (endchars != NULL
2283 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2284 EMSG(_(e_letunexp));
2285 else
2287 long n;
2288 int opt_type;
2289 long numval;
2290 char_u *stringval = NULL;
2291 char_u *s;
2293 c1 = *p;
2294 *p = NUL;
2296 n = get_tv_number(tv);
2297 s = get_tv_string_chk(tv); /* != NULL if number or string */
2298 if (s != NULL && op != NULL && *op != '=')
2300 opt_type = get_option_value(arg, &numval,
2301 &stringval, opt_flags);
2302 if ((opt_type == 1 && *op == '.')
2303 || (opt_type == 0 && *op != '.'))
2304 EMSG2(_(e_letwrong), op);
2305 else
2307 if (opt_type == 1) /* number */
2309 if (*op == '+')
2310 n = numval + n;
2311 else
2312 n = numval - n;
2314 else if (opt_type == 0 && stringval != NULL) /* string */
2316 s = concat_str(stringval, s);
2317 vim_free(stringval);
2318 stringval = s;
2322 if (s != NULL)
2324 set_option_value(arg, n, s, opt_flags);
2325 arg_end = p;
2327 *p = c1;
2328 vim_free(stringval);
2333 * ":let @r = expr": Set register contents.
2335 else if (*arg == '@')
2337 ++arg;
2338 if (op != NULL && (*op == '+' || *op == '-'))
2339 EMSG2(_(e_letwrong), op);
2340 else if (endchars != NULL
2341 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2342 EMSG(_(e_letunexp));
2343 else
2345 char_u *ptofree = NULL;
2346 char_u *s;
2348 p = get_tv_string_chk(tv);
2349 if (p != NULL && op != NULL && *op == '.')
2351 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2352 if (s != NULL)
2354 p = ptofree = concat_str(s, p);
2355 vim_free(s);
2358 if (p != NULL)
2360 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2361 arg_end = arg + 1;
2363 vim_free(ptofree);
2368 * ":let var = expr": Set internal variable.
2369 * ":let {expr} = expr": Idem, name made with curly braces
2371 else if (eval_isnamec1(*arg) || *arg == '{')
2373 lval_T lv;
2375 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2376 if (p != NULL && lv.ll_name != NULL)
2378 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2379 EMSG(_(e_letunexp));
2380 else
2382 set_var_lval(&lv, p, tv, copy, op);
2383 arg_end = p;
2386 clear_lval(&lv);
2389 else
2390 EMSG2(_(e_invarg2), arg);
2392 return arg_end;
2396 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2398 static int
2399 check_changedtick(arg)
2400 char_u *arg;
2402 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2404 EMSG2(_(e_readonlyvar), arg);
2405 return TRUE;
2407 return FALSE;
2411 * Get an lval: variable, Dict item or List item that can be assigned a value
2412 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2413 * "name.key", "name.key[expr]" etc.
2414 * Indexing only works if "name" is an existing List or Dictionary.
2415 * "name" points to the start of the name.
2416 * If "rettv" is not NULL it points to the value to be assigned.
2417 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2418 * wrong; must end in space or cmd separator.
2420 * Returns a pointer to just after the name, including indexes.
2421 * When an evaluation error occurs "lp->ll_name" is NULL;
2422 * Returns NULL for a parsing error. Still need to free items in "lp"!
2424 static char_u *
2425 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2426 char_u *name;
2427 typval_T *rettv;
2428 lval_T *lp;
2429 int unlet;
2430 int skip;
2431 int quiet; /* don't give error messages */
2432 int fne_flags; /* flags for find_name_end() */
2434 char_u *p;
2435 char_u *expr_start, *expr_end;
2436 int cc;
2437 dictitem_T *v;
2438 typval_T var1;
2439 typval_T var2;
2440 int empty1 = FALSE;
2441 listitem_T *ni;
2442 char_u *key = NULL;
2443 int len;
2444 hashtab_T *ht;
2446 /* Clear everything in "lp". */
2447 vim_memset(lp, 0, sizeof(lval_T));
2449 if (skip)
2451 /* When skipping just find the end of the name. */
2452 lp->ll_name = name;
2453 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2456 /* Find the end of the name. */
2457 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2458 if (expr_start != NULL)
2460 /* Don't expand the name when we already know there is an error. */
2461 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2462 && *p != '[' && *p != '.')
2464 EMSG(_(e_trailing));
2465 return NULL;
2468 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2469 if (lp->ll_exp_name == NULL)
2471 /* Report an invalid expression in braces, unless the
2472 * expression evaluation has been cancelled due to an
2473 * aborting error, an interrupt, or an exception. */
2474 if (!aborting() && !quiet)
2476 emsg_severe = TRUE;
2477 EMSG2(_(e_invarg2), name);
2478 return NULL;
2481 lp->ll_name = lp->ll_exp_name;
2483 else
2484 lp->ll_name = name;
2486 /* Without [idx] or .key we are done. */
2487 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2488 return p;
2490 cc = *p;
2491 *p = NUL;
2492 v = find_var(lp->ll_name, &ht);
2493 if (v == NULL && !quiet)
2494 EMSG2(_(e_undefvar), lp->ll_name);
2495 *p = cc;
2496 if (v == NULL)
2497 return NULL;
2500 * Loop until no more [idx] or .key is following.
2502 lp->ll_tv = &v->di_tv;
2503 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2505 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2506 && !(lp->ll_tv->v_type == VAR_DICT
2507 && lp->ll_tv->vval.v_dict != NULL))
2509 if (!quiet)
2510 EMSG(_("E689: Can only index a List or Dictionary"));
2511 return NULL;
2513 if (lp->ll_range)
2515 if (!quiet)
2516 EMSG(_("E708: [:] must come last"));
2517 return NULL;
2520 len = -1;
2521 if (*p == '.')
2523 key = p + 1;
2524 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2526 if (len == 0)
2528 if (!quiet)
2529 EMSG(_(e_emptykey));
2530 return NULL;
2532 p = key + len;
2534 else
2536 /* Get the index [expr] or the first index [expr: ]. */
2537 p = skipwhite(p + 1);
2538 if (*p == ':')
2539 empty1 = TRUE;
2540 else
2542 empty1 = FALSE;
2543 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2544 return NULL;
2545 if (get_tv_string_chk(&var1) == NULL)
2547 /* not a number or string */
2548 clear_tv(&var1);
2549 return NULL;
2553 /* Optionally get the second index [ :expr]. */
2554 if (*p == ':')
2556 if (lp->ll_tv->v_type == VAR_DICT)
2558 if (!quiet)
2559 EMSG(_(e_dictrange));
2560 if (!empty1)
2561 clear_tv(&var1);
2562 return NULL;
2564 if (rettv != NULL && (rettv->v_type != VAR_LIST
2565 || rettv->vval.v_list == NULL))
2567 if (!quiet)
2568 EMSG(_("E709: [:] requires a List value"));
2569 if (!empty1)
2570 clear_tv(&var1);
2571 return NULL;
2573 p = skipwhite(p + 1);
2574 if (*p == ']')
2575 lp->ll_empty2 = TRUE;
2576 else
2578 lp->ll_empty2 = FALSE;
2579 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2581 if (!empty1)
2582 clear_tv(&var1);
2583 return NULL;
2585 if (get_tv_string_chk(&var2) == NULL)
2587 /* not a number or string */
2588 if (!empty1)
2589 clear_tv(&var1);
2590 clear_tv(&var2);
2591 return NULL;
2594 lp->ll_range = TRUE;
2596 else
2597 lp->ll_range = FALSE;
2599 if (*p != ']')
2601 if (!quiet)
2602 EMSG(_(e_missbrac));
2603 if (!empty1)
2604 clear_tv(&var1);
2605 if (lp->ll_range && !lp->ll_empty2)
2606 clear_tv(&var2);
2607 return NULL;
2610 /* Skip to past ']'. */
2611 ++p;
2614 if (lp->ll_tv->v_type == VAR_DICT)
2616 if (len == -1)
2618 /* "[key]": get key from "var1" */
2619 key = get_tv_string(&var1); /* is number or string */
2620 if (*key == NUL)
2622 if (!quiet)
2623 EMSG(_(e_emptykey));
2624 clear_tv(&var1);
2625 return NULL;
2628 lp->ll_list = NULL;
2629 lp->ll_dict = lp->ll_tv->vval.v_dict;
2630 lp->ll_di = dict_find(lp->ll_dict, key, len);
2631 if (lp->ll_di == NULL)
2633 /* Key does not exist in dict: may need to add it. */
2634 if (*p == '[' || *p == '.' || unlet)
2636 if (!quiet)
2637 EMSG2(_(e_dictkey), key);
2638 if (len == -1)
2639 clear_tv(&var1);
2640 return NULL;
2642 if (len == -1)
2643 lp->ll_newkey = vim_strsave(key);
2644 else
2645 lp->ll_newkey = vim_strnsave(key, len);
2646 if (len == -1)
2647 clear_tv(&var1);
2648 if (lp->ll_newkey == NULL)
2649 p = NULL;
2650 break;
2652 if (len == -1)
2653 clear_tv(&var1);
2654 lp->ll_tv = &lp->ll_di->di_tv;
2656 else
2659 * Get the number and item for the only or first index of the List.
2661 if (empty1)
2662 lp->ll_n1 = 0;
2663 else
2665 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2666 clear_tv(&var1);
2668 lp->ll_dict = NULL;
2669 lp->ll_list = lp->ll_tv->vval.v_list;
2670 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2671 if (lp->ll_li == NULL)
2673 if (lp->ll_n1 < 0)
2675 lp->ll_n1 = 0;
2676 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2679 if (lp->ll_li == NULL)
2681 if (lp->ll_range && !lp->ll_empty2)
2682 clear_tv(&var2);
2683 return NULL;
2687 * May need to find the item or absolute index for the second
2688 * index of a range.
2689 * When no index given: "lp->ll_empty2" is TRUE.
2690 * Otherwise "lp->ll_n2" is set to the second index.
2692 if (lp->ll_range && !lp->ll_empty2)
2694 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2695 clear_tv(&var2);
2696 if (lp->ll_n2 < 0)
2698 ni = list_find(lp->ll_list, lp->ll_n2);
2699 if (ni == NULL)
2700 return NULL;
2701 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2704 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2705 if (lp->ll_n1 < 0)
2706 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2707 if (lp->ll_n2 < lp->ll_n1)
2708 return NULL;
2711 lp->ll_tv = &lp->ll_li->li_tv;
2715 return p;
2719 * Clear lval "lp" that was filled by get_lval().
2721 static void
2722 clear_lval(lp)
2723 lval_T *lp;
2725 vim_free(lp->ll_exp_name);
2726 vim_free(lp->ll_newkey);
2730 * Set a variable that was parsed by get_lval() to "rettv".
2731 * "endp" points to just after the parsed name.
2732 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2734 static void
2735 set_var_lval(lp, endp, rettv, copy, op)
2736 lval_T *lp;
2737 char_u *endp;
2738 typval_T *rettv;
2739 int copy;
2740 char_u *op;
2742 int cc;
2743 listitem_T *ri;
2744 dictitem_T *di;
2746 if (lp->ll_tv == NULL)
2748 if (!check_changedtick(lp->ll_name))
2750 cc = *endp;
2751 *endp = NUL;
2752 if (op != NULL && *op != '=')
2754 typval_T tv;
2756 /* handle +=, -= and .= */
2757 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2758 &tv, TRUE) == OK)
2760 if (tv_op(&tv, rettv, op) == OK)
2761 set_var(lp->ll_name, &tv, FALSE);
2762 clear_tv(&tv);
2765 else
2766 set_var(lp->ll_name, rettv, copy);
2767 *endp = cc;
2770 else if (tv_check_lock(lp->ll_newkey == NULL
2771 ? lp->ll_tv->v_lock
2772 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2774 else if (lp->ll_range)
2777 * Assign the List values to the list items.
2779 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2781 if (op != NULL && *op != '=')
2782 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2783 else
2785 clear_tv(&lp->ll_li->li_tv);
2786 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2788 ri = ri->li_next;
2789 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2790 break;
2791 if (lp->ll_li->li_next == NULL)
2793 /* Need to add an empty item. */
2794 if (list_append_number(lp->ll_list, 0) == FAIL)
2796 ri = NULL;
2797 break;
2800 lp->ll_li = lp->ll_li->li_next;
2801 ++lp->ll_n1;
2803 if (ri != NULL)
2804 EMSG(_("E710: List value has more items than target"));
2805 else if (lp->ll_empty2
2806 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2807 : lp->ll_n1 != lp->ll_n2)
2808 EMSG(_("E711: List value has not enough items"));
2810 else
2813 * Assign to a List or Dictionary item.
2815 if (lp->ll_newkey != NULL)
2817 if (op != NULL && *op != '=')
2819 EMSG2(_(e_letwrong), op);
2820 return;
2823 /* Need to add an item to the Dictionary. */
2824 di = dictitem_alloc(lp->ll_newkey);
2825 if (di == NULL)
2826 return;
2827 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2829 vim_free(di);
2830 return;
2832 lp->ll_tv = &di->di_tv;
2834 else if (op != NULL && *op != '=')
2836 tv_op(lp->ll_tv, rettv, op);
2837 return;
2839 else
2840 clear_tv(lp->ll_tv);
2843 * Assign the value to the variable or list item.
2845 if (copy)
2846 copy_tv(rettv, lp->ll_tv);
2847 else
2849 *lp->ll_tv = *rettv;
2850 lp->ll_tv->v_lock = 0;
2851 init_tv(rettv);
2857 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2858 * Returns OK or FAIL.
2860 static int
2861 tv_op(tv1, tv2, op)
2862 typval_T *tv1;
2863 typval_T *tv2;
2864 char_u *op;
2866 long n;
2867 char_u numbuf[NUMBUFLEN];
2868 char_u *s;
2870 /* Can't do anything with a Funcref or a Dict on the right. */
2871 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2873 switch (tv1->v_type)
2875 case VAR_DICT:
2876 case VAR_FUNC:
2877 break;
2879 case VAR_LIST:
2880 if (*op != '+' || tv2->v_type != VAR_LIST)
2881 break;
2882 /* List += List */
2883 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2884 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2885 return OK;
2887 case VAR_NUMBER:
2888 case VAR_STRING:
2889 if (tv2->v_type == VAR_LIST)
2890 break;
2891 if (*op == '+' || *op == '-')
2893 /* nr += nr or nr -= nr*/
2894 n = get_tv_number(tv1);
2895 #ifdef FEAT_FLOAT
2896 if (tv2->v_type == VAR_FLOAT)
2898 float_T f = n;
2900 if (*op == '+')
2901 f += tv2->vval.v_float;
2902 else
2903 f -= tv2->vval.v_float;
2904 clear_tv(tv1);
2905 tv1->v_type = VAR_FLOAT;
2906 tv1->vval.v_float = f;
2908 else
2909 #endif
2911 if (*op == '+')
2912 n += get_tv_number(tv2);
2913 else
2914 n -= get_tv_number(tv2);
2915 clear_tv(tv1);
2916 tv1->v_type = VAR_NUMBER;
2917 tv1->vval.v_number = n;
2920 else
2922 if (tv2->v_type == VAR_FLOAT)
2923 break;
2925 /* str .= str */
2926 s = get_tv_string(tv1);
2927 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2928 clear_tv(tv1);
2929 tv1->v_type = VAR_STRING;
2930 tv1->vval.v_string = s;
2932 return OK;
2934 #ifdef FEAT_FLOAT
2935 case VAR_FLOAT:
2937 float_T f;
2939 if (*op == '.' || (tv2->v_type != VAR_FLOAT
2940 && tv2->v_type != VAR_NUMBER
2941 && tv2->v_type != VAR_STRING))
2942 break;
2943 if (tv2->v_type == VAR_FLOAT)
2944 f = tv2->vval.v_float;
2945 else
2946 f = get_tv_number(tv2);
2947 if (*op == '+')
2948 tv1->vval.v_float += f;
2949 else
2950 tv1->vval.v_float -= f;
2952 return OK;
2953 #endif
2957 EMSG2(_(e_letwrong), op);
2958 return FAIL;
2962 * Add a watcher to a list.
2964 static void
2965 list_add_watch(l, lw)
2966 list_T *l;
2967 listwatch_T *lw;
2969 lw->lw_next = l->lv_watch;
2970 l->lv_watch = lw;
2974 * Remove a watcher from a list.
2975 * No warning when it isn't found...
2977 static void
2978 list_rem_watch(l, lwrem)
2979 list_T *l;
2980 listwatch_T *lwrem;
2982 listwatch_T *lw, **lwp;
2984 lwp = &l->lv_watch;
2985 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2987 if (lw == lwrem)
2989 *lwp = lw->lw_next;
2990 break;
2992 lwp = &lw->lw_next;
2997 * Just before removing an item from a list: advance watchers to the next
2998 * item.
3000 static void
3001 list_fix_watch(l, item)
3002 list_T *l;
3003 listitem_T *item;
3005 listwatch_T *lw;
3007 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3008 if (lw->lw_item == item)
3009 lw->lw_item = item->li_next;
3013 * Evaluate the expression used in a ":for var in expr" command.
3014 * "arg" points to "var".
3015 * Set "*errp" to TRUE for an error, FALSE otherwise;
3016 * Return a pointer that holds the info. Null when there is an error.
3018 void *
3019 eval_for_line(arg, errp, nextcmdp, skip)
3020 char_u *arg;
3021 int *errp;
3022 char_u **nextcmdp;
3023 int skip;
3025 forinfo_T *fi;
3026 char_u *expr;
3027 typval_T tv;
3028 list_T *l;
3030 *errp = TRUE; /* default: there is an error */
3032 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
3033 if (fi == NULL)
3034 return NULL;
3036 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
3037 if (expr == NULL)
3038 return fi;
3040 expr = skipwhite(expr);
3041 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
3043 EMSG(_("E690: Missing \"in\" after :for"));
3044 return fi;
3047 if (skip)
3048 ++emsg_skip;
3049 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
3051 *errp = FALSE;
3052 if (!skip)
3054 l = tv.vval.v_list;
3055 if (tv.v_type != VAR_LIST || l == NULL)
3057 EMSG(_(e_listreq));
3058 clear_tv(&tv);
3060 else
3062 /* No need to increment the refcount, it's already set for the
3063 * list being used in "tv". */
3064 fi->fi_list = l;
3065 list_add_watch(l, &fi->fi_lw);
3066 fi->fi_lw.lw_item = l->lv_first;
3070 if (skip)
3071 --emsg_skip;
3073 return fi;
3077 * Use the first item in a ":for" list. Advance to the next.
3078 * Assign the values to the variable (list). "arg" points to the first one.
3079 * Return TRUE when a valid item was found, FALSE when at end of list or
3080 * something wrong.
3083 next_for_item(fi_void, arg)
3084 void *fi_void;
3085 char_u *arg;
3087 forinfo_T *fi = (forinfo_T *)fi_void;
3088 int result;
3089 listitem_T *item;
3091 item = fi->fi_lw.lw_item;
3092 if (item == NULL)
3093 result = FALSE;
3094 else
3096 fi->fi_lw.lw_item = item->li_next;
3097 result = (ex_let_vars(arg, &item->li_tv, TRUE,
3098 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3100 return result;
3104 * Free the structure used to store info used by ":for".
3106 void
3107 free_for_info(fi_void)
3108 void *fi_void;
3110 forinfo_T *fi = (forinfo_T *)fi_void;
3112 if (fi != NULL && fi->fi_list != NULL)
3114 list_rem_watch(fi->fi_list, &fi->fi_lw);
3115 list_unref(fi->fi_list);
3117 vim_free(fi);
3120 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3122 void
3123 set_context_for_expression(xp, arg, cmdidx)
3124 expand_T *xp;
3125 char_u *arg;
3126 cmdidx_T cmdidx;
3128 int got_eq = FALSE;
3129 int c;
3130 char_u *p;
3132 if (cmdidx == CMD_let)
3134 xp->xp_context = EXPAND_USER_VARS;
3135 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3137 /* ":let var1 var2 ...": find last space. */
3138 for (p = arg + STRLEN(arg); p >= arg; )
3140 xp->xp_pattern = p;
3141 mb_ptr_back(arg, p);
3142 if (vim_iswhite(*p))
3143 break;
3145 return;
3148 else
3149 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3150 : EXPAND_EXPRESSION;
3151 while ((xp->xp_pattern = vim_strpbrk(arg,
3152 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3154 c = *xp->xp_pattern;
3155 if (c == '&')
3157 c = xp->xp_pattern[1];
3158 if (c == '&')
3160 ++xp->xp_pattern;
3161 xp->xp_context = cmdidx != CMD_let || got_eq
3162 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3164 else if (c != ' ')
3166 xp->xp_context = EXPAND_SETTINGS;
3167 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3168 xp->xp_pattern += 2;
3172 else if (c == '$')
3174 /* environment variable */
3175 xp->xp_context = EXPAND_ENV_VARS;
3177 else if (c == '=')
3179 got_eq = TRUE;
3180 xp->xp_context = EXPAND_EXPRESSION;
3182 else if (c == '<'
3183 && xp->xp_context == EXPAND_FUNCTIONS
3184 && vim_strchr(xp->xp_pattern, '(') == NULL)
3186 /* Function name can start with "<SNR>" */
3187 break;
3189 else if (cmdidx != CMD_let || got_eq)
3191 if (c == '"') /* string */
3193 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3194 if (c == '\\' && xp->xp_pattern[1] != NUL)
3195 ++xp->xp_pattern;
3196 xp->xp_context = EXPAND_NOTHING;
3198 else if (c == '\'') /* literal string */
3200 /* Trick: '' is like stopping and starting a literal string. */
3201 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3202 /* skip */ ;
3203 xp->xp_context = EXPAND_NOTHING;
3205 else if (c == '|')
3207 if (xp->xp_pattern[1] == '|')
3209 ++xp->xp_pattern;
3210 xp->xp_context = EXPAND_EXPRESSION;
3212 else
3213 xp->xp_context = EXPAND_COMMANDS;
3215 else
3216 xp->xp_context = EXPAND_EXPRESSION;
3218 else
3219 /* Doesn't look like something valid, expand as an expression
3220 * anyway. */
3221 xp->xp_context = EXPAND_EXPRESSION;
3222 arg = xp->xp_pattern;
3223 if (*arg != NUL)
3224 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3225 /* skip */ ;
3227 xp->xp_pattern = arg;
3230 #endif /* FEAT_CMDL_COMPL */
3233 * ":1,25call func(arg1, arg2)" function call.
3235 void
3236 ex_call(eap)
3237 exarg_T *eap;
3239 char_u *arg = eap->arg;
3240 char_u *startarg;
3241 char_u *name;
3242 char_u *tofree;
3243 int len;
3244 typval_T rettv;
3245 linenr_T lnum;
3246 int doesrange;
3247 int failed = FALSE;
3248 funcdict_T fudi;
3250 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3251 if (fudi.fd_newkey != NULL)
3253 /* Still need to give an error message for missing key. */
3254 EMSG2(_(e_dictkey), fudi.fd_newkey);
3255 vim_free(fudi.fd_newkey);
3257 if (tofree == NULL)
3258 return;
3260 /* Increase refcount on dictionary, it could get deleted when evaluating
3261 * the arguments. */
3262 if (fudi.fd_dict != NULL)
3263 ++fudi.fd_dict->dv_refcount;
3265 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3266 len = (int)STRLEN(tofree);
3267 name = deref_func_name(tofree, &len);
3269 /* Skip white space to allow ":call func ()". Not good, but required for
3270 * backward compatibility. */
3271 startarg = skipwhite(arg);
3272 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3274 if (*startarg != '(')
3276 EMSG2(_("E107: Missing braces: %s"), eap->arg);
3277 goto end;
3281 * When skipping, evaluate the function once, to find the end of the
3282 * arguments.
3283 * When the function takes a range, this is discovered after the first
3284 * call, and the loop is broken.
3286 if (eap->skip)
3288 ++emsg_skip;
3289 lnum = eap->line2; /* do it once, also with an invalid range */
3291 else
3292 lnum = eap->line1;
3293 for ( ; lnum <= eap->line2; ++lnum)
3295 if (!eap->skip && eap->addr_count > 0)
3297 curwin->w_cursor.lnum = lnum;
3298 curwin->w_cursor.col = 0;
3300 arg = startarg;
3301 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3302 eap->line1, eap->line2, &doesrange,
3303 !eap->skip, fudi.fd_dict) == FAIL)
3305 failed = TRUE;
3306 break;
3309 /* Handle a function returning a Funcref, Dictionary or List. */
3310 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3312 failed = TRUE;
3313 break;
3316 clear_tv(&rettv);
3317 if (doesrange || eap->skip)
3318 break;
3320 /* Stop when immediately aborting on error, or when an interrupt
3321 * occurred or an exception was thrown but not caught.
3322 * get_func_tv() returned OK, so that the check for trailing
3323 * characters below is executed. */
3324 if (aborting())
3325 break;
3327 if (eap->skip)
3328 --emsg_skip;
3330 if (!failed)
3332 /* Check for trailing illegal characters and a following command. */
3333 if (!ends_excmd(*arg))
3335 emsg_severe = TRUE;
3336 EMSG(_(e_trailing));
3338 else
3339 eap->nextcmd = check_nextcmd(arg);
3342 end:
3343 dict_unref(fudi.fd_dict);
3344 vim_free(tofree);
3348 * ":unlet[!] var1 ... " command.
3350 void
3351 ex_unlet(eap)
3352 exarg_T *eap;
3354 ex_unletlock(eap, eap->arg, 0);
3358 * ":lockvar" and ":unlockvar" commands
3360 void
3361 ex_lockvar(eap)
3362 exarg_T *eap;
3364 char_u *arg = eap->arg;
3365 int deep = 2;
3367 if (eap->forceit)
3368 deep = -1;
3369 else if (vim_isdigit(*arg))
3371 deep = getdigits(&arg);
3372 arg = skipwhite(arg);
3375 ex_unletlock(eap, arg, deep);
3379 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3381 static void
3382 ex_unletlock(eap, argstart, deep)
3383 exarg_T *eap;
3384 char_u *argstart;
3385 int deep;
3387 char_u *arg = argstart;
3388 char_u *name_end;
3389 int error = FALSE;
3390 lval_T lv;
3394 /* Parse the name and find the end. */
3395 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3396 FNE_CHECK_START);
3397 if (lv.ll_name == NULL)
3398 error = TRUE; /* error but continue parsing */
3399 if (name_end == NULL || (!vim_iswhite(*name_end)
3400 && !ends_excmd(*name_end)))
3402 if (name_end != NULL)
3404 emsg_severe = TRUE;
3405 EMSG(_(e_trailing));
3407 if (!(eap->skip || error))
3408 clear_lval(&lv);
3409 break;
3412 if (!error && !eap->skip)
3414 if (eap->cmdidx == CMD_unlet)
3416 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3417 error = TRUE;
3419 else
3421 if (do_lock_var(&lv, name_end, deep,
3422 eap->cmdidx == CMD_lockvar) == FAIL)
3423 error = TRUE;
3427 if (!eap->skip)
3428 clear_lval(&lv);
3430 arg = skipwhite(name_end);
3431 } while (!ends_excmd(*arg));
3433 eap->nextcmd = check_nextcmd(arg);
3436 static int
3437 do_unlet_var(lp, name_end, forceit)
3438 lval_T *lp;
3439 char_u *name_end;
3440 int forceit;
3442 int ret = OK;
3443 int cc;
3445 if (lp->ll_tv == NULL)
3447 cc = *name_end;
3448 *name_end = NUL;
3450 /* Normal name or expanded name. */
3451 if (check_changedtick(lp->ll_name))
3452 ret = FAIL;
3453 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3454 ret = FAIL;
3455 *name_end = cc;
3457 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3458 return FAIL;
3459 else if (lp->ll_range)
3461 listitem_T *li;
3463 /* Delete a range of List items. */
3464 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3466 li = lp->ll_li->li_next;
3467 listitem_remove(lp->ll_list, lp->ll_li);
3468 lp->ll_li = li;
3469 ++lp->ll_n1;
3472 else
3474 if (lp->ll_list != NULL)
3475 /* unlet a List item. */
3476 listitem_remove(lp->ll_list, lp->ll_li);
3477 else
3478 /* unlet a Dictionary item. */
3479 dictitem_remove(lp->ll_dict, lp->ll_di);
3482 return ret;
3486 * "unlet" a variable. Return OK if it existed, FAIL if not.
3487 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3490 do_unlet(name, forceit)
3491 char_u *name;
3492 int forceit;
3494 hashtab_T *ht;
3495 hashitem_T *hi;
3496 char_u *varname;
3497 dictitem_T *di;
3499 ht = find_var_ht(name, &varname);
3500 if (ht != NULL && *varname != NUL)
3502 hi = hash_find(ht, varname);
3503 if (!HASHITEM_EMPTY(hi))
3505 di = HI2DI(hi);
3506 if (var_check_fixed(di->di_flags, name)
3507 || var_check_ro(di->di_flags, name))
3508 return FAIL;
3509 delete_var(ht, hi);
3510 return OK;
3513 if (forceit)
3514 return OK;
3515 EMSG2(_("E108: No such variable: \"%s\""), name);
3516 return FAIL;
3520 * Lock or unlock variable indicated by "lp".
3521 * "deep" is the levels to go (-1 for unlimited);
3522 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3524 static int
3525 do_lock_var(lp, name_end, deep, lock)
3526 lval_T *lp;
3527 char_u *name_end;
3528 int deep;
3529 int lock;
3531 int ret = OK;
3532 int cc;
3533 dictitem_T *di;
3535 if (deep == 0) /* nothing to do */
3536 return OK;
3538 if (lp->ll_tv == NULL)
3540 cc = *name_end;
3541 *name_end = NUL;
3543 /* Normal name or expanded name. */
3544 if (check_changedtick(lp->ll_name))
3545 ret = FAIL;
3546 else
3548 di = find_var(lp->ll_name, NULL);
3549 if (di == NULL)
3550 ret = FAIL;
3551 else
3553 if (lock)
3554 di->di_flags |= DI_FLAGS_LOCK;
3555 else
3556 di->di_flags &= ~DI_FLAGS_LOCK;
3557 item_lock(&di->di_tv, deep, lock);
3560 *name_end = cc;
3562 else if (lp->ll_range)
3564 listitem_T *li = lp->ll_li;
3566 /* (un)lock a range of List items. */
3567 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3569 item_lock(&li->li_tv, deep, lock);
3570 li = li->li_next;
3571 ++lp->ll_n1;
3574 else if (lp->ll_list != NULL)
3575 /* (un)lock a List item. */
3576 item_lock(&lp->ll_li->li_tv, deep, lock);
3577 else
3578 /* un(lock) a Dictionary item. */
3579 item_lock(&lp->ll_di->di_tv, deep, lock);
3581 return ret;
3585 * Lock or unlock an item. "deep" is nr of levels to go.
3587 static void
3588 item_lock(tv, deep, lock)
3589 typval_T *tv;
3590 int deep;
3591 int lock;
3593 static int recurse = 0;
3594 list_T *l;
3595 listitem_T *li;
3596 dict_T *d;
3597 hashitem_T *hi;
3598 int todo;
3600 if (recurse >= DICT_MAXNEST)
3602 EMSG(_("E743: variable nested too deep for (un)lock"));
3603 return;
3605 if (deep == 0)
3606 return;
3607 ++recurse;
3609 /* lock/unlock the item itself */
3610 if (lock)
3611 tv->v_lock |= VAR_LOCKED;
3612 else
3613 tv->v_lock &= ~VAR_LOCKED;
3615 switch (tv->v_type)
3617 case VAR_LIST:
3618 if ((l = tv->vval.v_list) != NULL)
3620 if (lock)
3621 l->lv_lock |= VAR_LOCKED;
3622 else
3623 l->lv_lock &= ~VAR_LOCKED;
3624 if (deep < 0 || deep > 1)
3625 /* recursive: lock/unlock the items the List contains */
3626 for (li = l->lv_first; li != NULL; li = li->li_next)
3627 item_lock(&li->li_tv, deep - 1, lock);
3629 break;
3630 case VAR_DICT:
3631 if ((d = tv->vval.v_dict) != NULL)
3633 if (lock)
3634 d->dv_lock |= VAR_LOCKED;
3635 else
3636 d->dv_lock &= ~VAR_LOCKED;
3637 if (deep < 0 || deep > 1)
3639 /* recursive: lock/unlock the items the List contains */
3640 todo = (int)d->dv_hashtab.ht_used;
3641 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3643 if (!HASHITEM_EMPTY(hi))
3645 --todo;
3646 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3652 --recurse;
3656 * Return TRUE if typeval "tv" is locked: Either tha value is locked itself or
3657 * it refers to a List or Dictionary that is locked.
3659 static int
3660 tv_islocked(tv)
3661 typval_T *tv;
3663 return (tv->v_lock & VAR_LOCKED)
3664 || (tv->v_type == VAR_LIST
3665 && tv->vval.v_list != NULL
3666 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3667 || (tv->v_type == VAR_DICT
3668 && tv->vval.v_dict != NULL
3669 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3672 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3674 * Delete all "menutrans_" variables.
3676 void
3677 del_menutrans_vars()
3679 hashitem_T *hi;
3680 int todo;
3682 hash_lock(&globvarht);
3683 todo = (int)globvarht.ht_used;
3684 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3686 if (!HASHITEM_EMPTY(hi))
3688 --todo;
3689 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3690 delete_var(&globvarht, hi);
3693 hash_unlock(&globvarht);
3695 #endif
3697 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3700 * Local string buffer for the next two functions to store a variable name
3701 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3702 * get_user_var_name().
3705 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3707 static char_u *varnamebuf = NULL;
3708 static int varnamebuflen = 0;
3711 * Function to concatenate a prefix and a variable name.
3713 static char_u *
3714 cat_prefix_varname(prefix, name)
3715 int prefix;
3716 char_u *name;
3718 int len;
3720 len = (int)STRLEN(name) + 3;
3721 if (len > varnamebuflen)
3723 vim_free(varnamebuf);
3724 len += 10; /* some additional space */
3725 varnamebuf = alloc(len);
3726 if (varnamebuf == NULL)
3728 varnamebuflen = 0;
3729 return NULL;
3731 varnamebuflen = len;
3733 *varnamebuf = prefix;
3734 varnamebuf[1] = ':';
3735 STRCPY(varnamebuf + 2, name);
3736 return varnamebuf;
3740 * Function given to ExpandGeneric() to obtain the list of user defined
3741 * (global/buffer/window/built-in) variable names.
3743 /*ARGSUSED*/
3744 char_u *
3745 get_user_var_name(xp, idx)
3746 expand_T *xp;
3747 int idx;
3749 static long_u gdone;
3750 static long_u bdone;
3751 static long_u wdone;
3752 #ifdef FEAT_WINDOWS
3753 static long_u tdone;
3754 #endif
3755 static int vidx;
3756 static hashitem_T *hi;
3757 hashtab_T *ht;
3759 if (idx == 0)
3761 gdone = bdone = wdone = vidx = 0;
3762 #ifdef FEAT_WINDOWS
3763 tdone = 0;
3764 #endif
3767 /* Global variables */
3768 if (gdone < globvarht.ht_used)
3770 if (gdone++ == 0)
3771 hi = globvarht.ht_array;
3772 else
3773 ++hi;
3774 while (HASHITEM_EMPTY(hi))
3775 ++hi;
3776 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3777 return cat_prefix_varname('g', hi->hi_key);
3778 return hi->hi_key;
3781 /* b: variables */
3782 ht = &curbuf->b_vars.dv_hashtab;
3783 if (bdone < ht->ht_used)
3785 if (bdone++ == 0)
3786 hi = ht->ht_array;
3787 else
3788 ++hi;
3789 while (HASHITEM_EMPTY(hi))
3790 ++hi;
3791 return cat_prefix_varname('b', hi->hi_key);
3793 if (bdone == ht->ht_used)
3795 ++bdone;
3796 return (char_u *)"b:changedtick";
3799 /* w: variables */
3800 ht = &curwin->w_vars.dv_hashtab;
3801 if (wdone < ht->ht_used)
3803 if (wdone++ == 0)
3804 hi = ht->ht_array;
3805 else
3806 ++hi;
3807 while (HASHITEM_EMPTY(hi))
3808 ++hi;
3809 return cat_prefix_varname('w', hi->hi_key);
3812 #ifdef FEAT_WINDOWS
3813 /* t: variables */
3814 ht = &curtab->tp_vars.dv_hashtab;
3815 if (tdone < ht->ht_used)
3817 if (tdone++ == 0)
3818 hi = ht->ht_array;
3819 else
3820 ++hi;
3821 while (HASHITEM_EMPTY(hi))
3822 ++hi;
3823 return cat_prefix_varname('t', hi->hi_key);
3825 #endif
3827 /* v: variables */
3828 if (vidx < VV_LEN)
3829 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3831 vim_free(varnamebuf);
3832 varnamebuf = NULL;
3833 varnamebuflen = 0;
3834 return NULL;
3837 #endif /* FEAT_CMDL_COMPL */
3840 * types for expressions.
3842 typedef enum
3844 TYPE_UNKNOWN = 0
3845 , TYPE_EQUAL /* == */
3846 , TYPE_NEQUAL /* != */
3847 , TYPE_GREATER /* > */
3848 , TYPE_GEQUAL /* >= */
3849 , TYPE_SMALLER /* < */
3850 , TYPE_SEQUAL /* <= */
3851 , TYPE_MATCH /* =~ */
3852 , TYPE_NOMATCH /* !~ */
3853 } exptype_T;
3856 * The "evaluate" argument: When FALSE, the argument is only parsed but not
3857 * executed. The function may return OK, but the rettv will be of type
3858 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
3862 * Handle zero level expression.
3863 * This calls eval1() and handles error message and nextcmd.
3864 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3865 * Note: "rettv.v_lock" is not set.
3866 * Return OK or FAIL.
3868 static int
3869 eval0(arg, rettv, nextcmd, evaluate)
3870 char_u *arg;
3871 typval_T *rettv;
3872 char_u **nextcmd;
3873 int evaluate;
3875 int ret;
3876 char_u *p;
3878 p = skipwhite(arg);
3879 ret = eval1(&p, rettv, evaluate);
3880 if (ret == FAIL || !ends_excmd(*p))
3882 if (ret != FAIL)
3883 clear_tv(rettv);
3885 * Report the invalid expression unless the expression evaluation has
3886 * been cancelled due to an aborting error, an interrupt, or an
3887 * exception.
3889 if (!aborting())
3890 EMSG2(_(e_invexpr2), arg);
3891 ret = FAIL;
3893 if (nextcmd != NULL)
3894 *nextcmd = check_nextcmd(p);
3896 return ret;
3900 * Handle top level expression:
3901 * expr1 ? expr0 : expr0
3903 * "arg" must point to the first non-white of the expression.
3904 * "arg" is advanced to the next non-white after the recognized expression.
3906 * Note: "rettv.v_lock" is not set.
3908 * Return OK or FAIL.
3910 static int
3911 eval1(arg, rettv, evaluate)
3912 char_u **arg;
3913 typval_T *rettv;
3914 int evaluate;
3916 int result;
3917 typval_T var2;
3920 * Get the first variable.
3922 if (eval2(arg, rettv, evaluate) == FAIL)
3923 return FAIL;
3925 if ((*arg)[0] == '?')
3927 result = FALSE;
3928 if (evaluate)
3930 int error = FALSE;
3932 if (get_tv_number_chk(rettv, &error) != 0)
3933 result = TRUE;
3934 clear_tv(rettv);
3935 if (error)
3936 return FAIL;
3940 * Get the second variable.
3942 *arg = skipwhite(*arg + 1);
3943 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
3944 return FAIL;
3947 * Check for the ":".
3949 if ((*arg)[0] != ':')
3951 EMSG(_("E109: Missing ':' after '?'"));
3952 if (evaluate && result)
3953 clear_tv(rettv);
3954 return FAIL;
3958 * Get the third variable.
3960 *arg = skipwhite(*arg + 1);
3961 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
3963 if (evaluate && result)
3964 clear_tv(rettv);
3965 return FAIL;
3967 if (evaluate && !result)
3968 *rettv = var2;
3971 return OK;
3975 * Handle first level expression:
3976 * expr2 || expr2 || expr2 logical OR
3978 * "arg" must point to the first non-white of the expression.
3979 * "arg" is advanced to the next non-white after the recognized expression.
3981 * Return OK or FAIL.
3983 static int
3984 eval2(arg, rettv, evaluate)
3985 char_u **arg;
3986 typval_T *rettv;
3987 int evaluate;
3989 typval_T var2;
3990 long result;
3991 int first;
3992 int error = FALSE;
3995 * Get the first variable.
3997 if (eval3(arg, rettv, evaluate) == FAIL)
3998 return FAIL;
4001 * Repeat until there is no following "||".
4003 first = TRUE;
4004 result = FALSE;
4005 while ((*arg)[0] == '|' && (*arg)[1] == '|')
4007 if (evaluate && first)
4009 if (get_tv_number_chk(rettv, &error) != 0)
4010 result = TRUE;
4011 clear_tv(rettv);
4012 if (error)
4013 return FAIL;
4014 first = FALSE;
4018 * Get the second variable.
4020 *arg = skipwhite(*arg + 2);
4021 if (eval3(arg, &var2, evaluate && !result) == FAIL)
4022 return FAIL;
4025 * Compute the result.
4027 if (evaluate && !result)
4029 if (get_tv_number_chk(&var2, &error) != 0)
4030 result = TRUE;
4031 clear_tv(&var2);
4032 if (error)
4033 return FAIL;
4035 if (evaluate)
4037 rettv->v_type = VAR_NUMBER;
4038 rettv->vval.v_number = result;
4042 return OK;
4046 * Handle second level expression:
4047 * expr3 && expr3 && expr3 logical AND
4049 * "arg" must point to the first non-white of the expression.
4050 * "arg" is advanced to the next non-white after the recognized expression.
4052 * Return OK or FAIL.
4054 static int
4055 eval3(arg, rettv, evaluate)
4056 char_u **arg;
4057 typval_T *rettv;
4058 int evaluate;
4060 typval_T var2;
4061 long result;
4062 int first;
4063 int error = FALSE;
4066 * Get the first variable.
4068 if (eval4(arg, rettv, evaluate) == FAIL)
4069 return FAIL;
4072 * Repeat until there is no following "&&".
4074 first = TRUE;
4075 result = TRUE;
4076 while ((*arg)[0] == '&' && (*arg)[1] == '&')
4078 if (evaluate && first)
4080 if (get_tv_number_chk(rettv, &error) == 0)
4081 result = FALSE;
4082 clear_tv(rettv);
4083 if (error)
4084 return FAIL;
4085 first = FALSE;
4089 * Get the second variable.
4091 *arg = skipwhite(*arg + 2);
4092 if (eval4(arg, &var2, evaluate && result) == FAIL)
4093 return FAIL;
4096 * Compute the result.
4098 if (evaluate && result)
4100 if (get_tv_number_chk(&var2, &error) == 0)
4101 result = FALSE;
4102 clear_tv(&var2);
4103 if (error)
4104 return FAIL;
4106 if (evaluate)
4108 rettv->v_type = VAR_NUMBER;
4109 rettv->vval.v_number = result;
4113 return OK;
4117 * Handle third level expression:
4118 * var1 == var2
4119 * var1 =~ var2
4120 * var1 != var2
4121 * var1 !~ var2
4122 * var1 > var2
4123 * var1 >= var2
4124 * var1 < var2
4125 * var1 <= var2
4126 * var1 is var2
4127 * var1 isnot var2
4129 * "arg" must point to the first non-white of the expression.
4130 * "arg" is advanced to the next non-white after the recognized expression.
4132 * Return OK or FAIL.
4134 static int
4135 eval4(arg, rettv, evaluate)
4136 char_u **arg;
4137 typval_T *rettv;
4138 int evaluate;
4140 typval_T var2;
4141 char_u *p;
4142 int i;
4143 exptype_T type = TYPE_UNKNOWN;
4144 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4145 int len = 2;
4146 long n1, n2;
4147 char_u *s1, *s2;
4148 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4149 regmatch_T regmatch;
4150 int ic;
4151 char_u *save_cpo;
4154 * Get the first variable.
4156 if (eval5(arg, rettv, evaluate) == FAIL)
4157 return FAIL;
4159 p = *arg;
4160 switch (p[0])
4162 case '=': if (p[1] == '=')
4163 type = TYPE_EQUAL;
4164 else if (p[1] == '~')
4165 type = TYPE_MATCH;
4166 break;
4167 case '!': if (p[1] == '=')
4168 type = TYPE_NEQUAL;
4169 else if (p[1] == '~')
4170 type = TYPE_NOMATCH;
4171 break;
4172 case '>': if (p[1] != '=')
4174 type = TYPE_GREATER;
4175 len = 1;
4177 else
4178 type = TYPE_GEQUAL;
4179 break;
4180 case '<': if (p[1] != '=')
4182 type = TYPE_SMALLER;
4183 len = 1;
4185 else
4186 type = TYPE_SEQUAL;
4187 break;
4188 case 'i': if (p[1] == 's')
4190 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4191 len = 5;
4192 if (!vim_isIDc(p[len]))
4194 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4195 type_is = TRUE;
4198 break;
4202 * If there is a comparative operator, use it.
4204 if (type != TYPE_UNKNOWN)
4206 /* extra question mark appended: ignore case */
4207 if (p[len] == '?')
4209 ic = TRUE;
4210 ++len;
4212 /* extra '#' appended: match case */
4213 else if (p[len] == '#')
4215 ic = FALSE;
4216 ++len;
4218 /* nothing appended: use 'ignorecase' */
4219 else
4220 ic = p_ic;
4223 * Get the second variable.
4225 *arg = skipwhite(p + len);
4226 if (eval5(arg, &var2, evaluate) == FAIL)
4228 clear_tv(rettv);
4229 return FAIL;
4232 if (evaluate)
4234 if (type_is && rettv->v_type != var2.v_type)
4236 /* For "is" a different type always means FALSE, for "notis"
4237 * it means TRUE. */
4238 n1 = (type == TYPE_NEQUAL);
4240 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4242 if (type_is)
4244 n1 = (rettv->v_type == var2.v_type
4245 && rettv->vval.v_list == var2.vval.v_list);
4246 if (type == TYPE_NEQUAL)
4247 n1 = !n1;
4249 else if (rettv->v_type != var2.v_type
4250 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4252 if (rettv->v_type != var2.v_type)
4253 EMSG(_("E691: Can only compare List with List"));
4254 else
4255 EMSG(_("E692: Invalid operation for Lists"));
4256 clear_tv(rettv);
4257 clear_tv(&var2);
4258 return FAIL;
4260 else
4262 /* Compare two Lists for being equal or unequal. */
4263 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
4264 if (type == TYPE_NEQUAL)
4265 n1 = !n1;
4269 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4271 if (type_is)
4273 n1 = (rettv->v_type == var2.v_type
4274 && rettv->vval.v_dict == var2.vval.v_dict);
4275 if (type == TYPE_NEQUAL)
4276 n1 = !n1;
4278 else if (rettv->v_type != var2.v_type
4279 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4281 if (rettv->v_type != var2.v_type)
4282 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4283 else
4284 EMSG(_("E736: Invalid operation for Dictionary"));
4285 clear_tv(rettv);
4286 clear_tv(&var2);
4287 return FAIL;
4289 else
4291 /* Compare two Dictionaries for being equal or unequal. */
4292 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4293 if (type == TYPE_NEQUAL)
4294 n1 = !n1;
4298 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4300 if (rettv->v_type != var2.v_type
4301 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4303 if (rettv->v_type != var2.v_type)
4304 EMSG(_("E693: Can only compare Funcref with Funcref"));
4305 else
4306 EMSG(_("E694: Invalid operation for Funcrefs"));
4307 clear_tv(rettv);
4308 clear_tv(&var2);
4309 return FAIL;
4311 else
4313 /* Compare two Funcrefs for being equal or unequal. */
4314 if (rettv->vval.v_string == NULL
4315 || var2.vval.v_string == NULL)
4316 n1 = FALSE;
4317 else
4318 n1 = STRCMP(rettv->vval.v_string,
4319 var2.vval.v_string) == 0;
4320 if (type == TYPE_NEQUAL)
4321 n1 = !n1;
4325 #ifdef FEAT_FLOAT
4327 * If one of the two variables is a float, compare as a float.
4328 * When using "=~" or "!~", always compare as string.
4330 else if ((rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4331 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4333 float_T f1, f2;
4335 if (rettv->v_type == VAR_FLOAT)
4336 f1 = rettv->vval.v_float;
4337 else
4338 f1 = get_tv_number(rettv);
4339 if (var2.v_type == VAR_FLOAT)
4340 f2 = var2.vval.v_float;
4341 else
4342 f2 = get_tv_number(&var2);
4343 n1 = FALSE;
4344 switch (type)
4346 case TYPE_EQUAL: n1 = (f1 == f2); break;
4347 case TYPE_NEQUAL: n1 = (f1 != f2); break;
4348 case TYPE_GREATER: n1 = (f1 > f2); break;
4349 case TYPE_GEQUAL: n1 = (f1 >= f2); break;
4350 case TYPE_SMALLER: n1 = (f1 < f2); break;
4351 case TYPE_SEQUAL: n1 = (f1 <= f2); break;
4352 case TYPE_UNKNOWN:
4353 case TYPE_MATCH:
4354 case TYPE_NOMATCH: break; /* avoid gcc warning */
4357 #endif
4360 * If one of the two variables is a number, compare as a number.
4361 * When using "=~" or "!~", always compare as string.
4363 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4364 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4366 n1 = get_tv_number(rettv);
4367 n2 = get_tv_number(&var2);
4368 switch (type)
4370 case TYPE_EQUAL: n1 = (n1 == n2); break;
4371 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4372 case TYPE_GREATER: n1 = (n1 > n2); break;
4373 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4374 case TYPE_SMALLER: n1 = (n1 < n2); break;
4375 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4376 case TYPE_UNKNOWN:
4377 case TYPE_MATCH:
4378 case TYPE_NOMATCH: break; /* avoid gcc warning */
4381 else
4383 s1 = get_tv_string_buf(rettv, buf1);
4384 s2 = get_tv_string_buf(&var2, buf2);
4385 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4386 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4387 else
4388 i = 0;
4389 n1 = FALSE;
4390 switch (type)
4392 case TYPE_EQUAL: n1 = (i == 0); break;
4393 case TYPE_NEQUAL: n1 = (i != 0); break;
4394 case TYPE_GREATER: n1 = (i > 0); break;
4395 case TYPE_GEQUAL: n1 = (i >= 0); break;
4396 case TYPE_SMALLER: n1 = (i < 0); break;
4397 case TYPE_SEQUAL: n1 = (i <= 0); break;
4399 case TYPE_MATCH:
4400 case TYPE_NOMATCH:
4401 /* avoid 'l' flag in 'cpoptions' */
4402 save_cpo = p_cpo;
4403 p_cpo = (char_u *)"";
4404 regmatch.regprog = vim_regcomp(s2,
4405 RE_MAGIC + RE_STRING);
4406 regmatch.rm_ic = ic;
4407 if (regmatch.regprog != NULL)
4409 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4410 vim_free(regmatch.regprog);
4411 if (type == TYPE_NOMATCH)
4412 n1 = !n1;
4414 p_cpo = save_cpo;
4415 break;
4417 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4420 clear_tv(rettv);
4421 clear_tv(&var2);
4422 rettv->v_type = VAR_NUMBER;
4423 rettv->vval.v_number = n1;
4427 return OK;
4431 * Handle fourth level expression:
4432 * + number addition
4433 * - number subtraction
4434 * . string concatenation
4436 * "arg" must point to the first non-white of the expression.
4437 * "arg" is advanced to the next non-white after the recognized expression.
4439 * Return OK or FAIL.
4441 static int
4442 eval5(arg, rettv, evaluate)
4443 char_u **arg;
4444 typval_T *rettv;
4445 int evaluate;
4447 typval_T var2;
4448 typval_T var3;
4449 int op;
4450 long n1, n2;
4451 #ifdef FEAT_FLOAT
4452 float_T f1 = 0, f2 = 0;
4453 #endif
4454 char_u *s1, *s2;
4455 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4456 char_u *p;
4459 * Get the first variable.
4461 if (eval6(arg, rettv, evaluate) == FAIL)
4462 return FAIL;
4465 * Repeat computing, until no '+', '-' or '.' is following.
4467 for (;;)
4469 op = **arg;
4470 if (op != '+' && op != '-' && op != '.')
4471 break;
4473 if ((op != '+' || rettv->v_type != VAR_LIST)
4474 #ifdef FEAT_FLOAT
4475 && (op == '.' || rettv->v_type != VAR_FLOAT)
4476 #endif
4479 /* For "list + ...", an illegal use of the first operand as
4480 * a number cannot be determined before evaluating the 2nd
4481 * operand: if this is also a list, all is ok.
4482 * For "something . ...", "something - ..." or "non-list + ...",
4483 * we know that the first operand needs to be a string or number
4484 * without evaluating the 2nd operand. So check before to avoid
4485 * side effects after an error. */
4486 if (evaluate && get_tv_string_chk(rettv) == NULL)
4488 clear_tv(rettv);
4489 return FAIL;
4494 * Get the second variable.
4496 *arg = skipwhite(*arg + 1);
4497 if (eval6(arg, &var2, evaluate) == FAIL)
4499 clear_tv(rettv);
4500 return FAIL;
4503 if (evaluate)
4506 * Compute the result.
4508 if (op == '.')
4510 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4511 s2 = get_tv_string_buf_chk(&var2, buf2);
4512 if (s2 == NULL) /* type error ? */
4514 clear_tv(rettv);
4515 clear_tv(&var2);
4516 return FAIL;
4518 p = concat_str(s1, s2);
4519 clear_tv(rettv);
4520 rettv->v_type = VAR_STRING;
4521 rettv->vval.v_string = p;
4523 else if (op == '+' && rettv->v_type == VAR_LIST
4524 && var2.v_type == VAR_LIST)
4526 /* concatenate Lists */
4527 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4528 &var3) == FAIL)
4530 clear_tv(rettv);
4531 clear_tv(&var2);
4532 return FAIL;
4534 clear_tv(rettv);
4535 *rettv = var3;
4537 else
4539 int error = FALSE;
4541 #ifdef FEAT_FLOAT
4542 if (rettv->v_type == VAR_FLOAT)
4544 f1 = rettv->vval.v_float;
4545 n1 = 0;
4547 else
4548 #endif
4550 n1 = get_tv_number_chk(rettv, &error);
4551 if (error)
4553 /* This can only happen for "list + non-list". For
4554 * "non-list + ..." or "something - ...", we returned
4555 * before evaluating the 2nd operand. */
4556 clear_tv(rettv);
4557 return FAIL;
4559 #ifdef FEAT_FLOAT
4560 if (var2.v_type == VAR_FLOAT)
4561 f1 = n1;
4562 #endif
4564 #ifdef FEAT_FLOAT
4565 if (var2.v_type == VAR_FLOAT)
4567 f2 = var2.vval.v_float;
4568 n2 = 0;
4570 else
4571 #endif
4573 n2 = get_tv_number_chk(&var2, &error);
4574 if (error)
4576 clear_tv(rettv);
4577 clear_tv(&var2);
4578 return FAIL;
4580 #ifdef FEAT_FLOAT
4581 if (rettv->v_type == VAR_FLOAT)
4582 f2 = n2;
4583 #endif
4585 clear_tv(rettv);
4587 #ifdef FEAT_FLOAT
4588 /* If there is a float on either side the result is a float. */
4589 if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4591 if (op == '+')
4592 f1 = f1 + f2;
4593 else
4594 f1 = f1 - f2;
4595 rettv->v_type = VAR_FLOAT;
4596 rettv->vval.v_float = f1;
4598 else
4599 #endif
4601 if (op == '+')
4602 n1 = n1 + n2;
4603 else
4604 n1 = n1 - n2;
4605 rettv->v_type = VAR_NUMBER;
4606 rettv->vval.v_number = n1;
4609 clear_tv(&var2);
4612 return OK;
4616 * Handle fifth level expression:
4617 * * number multiplication
4618 * / number division
4619 * % number modulo
4621 * "arg" must point to the first non-white of the expression.
4622 * "arg" is advanced to the next non-white after the recognized expression.
4624 * Return OK or FAIL.
4626 static int
4627 eval6(arg, rettv, evaluate)
4628 char_u **arg;
4629 typval_T *rettv;
4630 int evaluate;
4632 typval_T var2;
4633 int op;
4634 long n1, n2;
4635 #ifdef FEAT_FLOAT
4636 int use_float = FALSE;
4637 float_T f1 = 0, f2;
4638 #endif
4639 int error = FALSE;
4642 * Get the first variable.
4644 if (eval7(arg, rettv, evaluate) == FAIL)
4645 return FAIL;
4648 * Repeat computing, until no '*', '/' or '%' is following.
4650 for (;;)
4652 op = **arg;
4653 if (op != '*' && op != '/' && op != '%')
4654 break;
4656 if (evaluate)
4658 #ifdef FEAT_FLOAT
4659 if (rettv->v_type == VAR_FLOAT)
4661 f1 = rettv->vval.v_float;
4662 use_float = TRUE;
4663 n1 = 0;
4665 else
4666 #endif
4667 n1 = get_tv_number_chk(rettv, &error);
4668 clear_tv(rettv);
4669 if (error)
4670 return FAIL;
4672 else
4673 n1 = 0;
4676 * Get the second variable.
4678 *arg = skipwhite(*arg + 1);
4679 if (eval7(arg, &var2, evaluate) == FAIL)
4680 return FAIL;
4682 if (evaluate)
4684 #ifdef FEAT_FLOAT
4685 if (var2.v_type == VAR_FLOAT)
4687 if (!use_float)
4689 f1 = n1;
4690 use_float = TRUE;
4692 f2 = var2.vval.v_float;
4693 n2 = 0;
4695 else
4696 #endif
4698 n2 = get_tv_number_chk(&var2, &error);
4699 clear_tv(&var2);
4700 if (error)
4701 return FAIL;
4702 #ifdef FEAT_FLOAT
4703 if (use_float)
4704 f2 = n2;
4705 #endif
4709 * Compute the result.
4710 * When either side is a float the result is a float.
4712 #ifdef FEAT_FLOAT
4713 if (use_float)
4715 if (op == '*')
4716 f1 = f1 * f2;
4717 else if (op == '/')
4719 /* We rely on the floating point library to handle divide
4720 * by zero to result in "inf" and not a crash. */
4721 f1 = f1 / f2;
4723 else
4725 EMSG(_("E804: Cannot use % with float"));
4726 return FAIL;
4728 rettv->v_type = VAR_FLOAT;
4729 rettv->vval.v_float = f1;
4731 else
4732 #endif
4734 if (op == '*')
4735 n1 = n1 * n2;
4736 else if (op == '/')
4738 if (n2 == 0) /* give an error message? */
4740 if (n1 == 0)
4741 n1 = -0x7fffffffL - 1L; /* similar to NaN */
4742 else if (n1 < 0)
4743 n1 = -0x7fffffffL;
4744 else
4745 n1 = 0x7fffffffL;
4747 else
4748 n1 = n1 / n2;
4750 else
4752 if (n2 == 0) /* give an error message? */
4753 n1 = 0;
4754 else
4755 n1 = n1 % n2;
4757 rettv->v_type = VAR_NUMBER;
4758 rettv->vval.v_number = n1;
4763 return OK;
4767 * Handle sixth level expression:
4768 * number number constant
4769 * "string" string constant
4770 * 'string' literal string constant
4771 * &option-name option value
4772 * @r register contents
4773 * identifier variable value
4774 * function() function call
4775 * $VAR environment variable
4776 * (expression) nested expression
4777 * [expr, expr] List
4778 * {key: val, key: val} Dictionary
4780 * Also handle:
4781 * ! in front logical NOT
4782 * - in front unary minus
4783 * + in front unary plus (ignored)
4784 * trailing [] subscript in String or List
4785 * trailing .name entry in Dictionary
4787 * "arg" must point to the first non-white of the expression.
4788 * "arg" is advanced to the next non-white after the recognized expression.
4790 * Return OK or FAIL.
4792 static int
4793 eval7(arg, rettv, evaluate)
4794 char_u **arg;
4795 typval_T *rettv;
4796 int evaluate;
4798 long n;
4799 int len;
4800 char_u *s;
4801 char_u *start_leader, *end_leader;
4802 int ret = OK;
4803 char_u *alias;
4806 * Initialise variable so that clear_tv() can't mistake this for a
4807 * string and free a string that isn't there.
4809 rettv->v_type = VAR_UNKNOWN;
4812 * Skip '!' and '-' characters. They are handled later.
4814 start_leader = *arg;
4815 while (**arg == '!' || **arg == '-' || **arg == '+')
4816 *arg = skipwhite(*arg + 1);
4817 end_leader = *arg;
4819 switch (**arg)
4822 * Number constant.
4824 case '0':
4825 case '1':
4826 case '2':
4827 case '3':
4828 case '4':
4829 case '5':
4830 case '6':
4831 case '7':
4832 case '8':
4833 case '9':
4835 #ifdef FEAT_FLOAT
4836 char_u *p = skipdigits(*arg + 1);
4837 int get_float = FALSE;
4839 /* We accept a float when the format matches
4840 * "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?". This is very
4841 * strict to avoid backwards compatibility problems. */
4842 if (p[0] == '.' && vim_isdigit(p[1]))
4844 get_float = TRUE;
4845 p = skipdigits(p + 2);
4846 if (*p == 'e' || *p == 'E')
4848 ++p;
4849 if (*p == '-' || *p == '+')
4850 ++p;
4851 if (!vim_isdigit(*p))
4852 get_float = FALSE;
4853 else
4854 p = skipdigits(p + 1);
4856 if (ASCII_ISALPHA(*p) || *p == '.')
4857 get_float = FALSE;
4859 if (get_float)
4861 float_T f;
4863 *arg += string2float(*arg, &f);
4864 if (evaluate)
4866 rettv->v_type = VAR_FLOAT;
4867 rettv->vval.v_float = f;
4870 else
4871 #endif
4873 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4874 *arg += len;
4875 if (evaluate)
4877 rettv->v_type = VAR_NUMBER;
4878 rettv->vval.v_number = n;
4881 break;
4885 * String constant: "string".
4887 case '"': ret = get_string_tv(arg, rettv, evaluate);
4888 break;
4891 * Literal string constant: 'str''ing'.
4893 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
4894 break;
4897 * List: [expr, expr]
4899 case '[': ret = get_list_tv(arg, rettv, evaluate);
4900 break;
4903 * Dictionary: {key: val, key: val}
4905 case '{': ret = get_dict_tv(arg, rettv, evaluate);
4906 break;
4909 * Option value: &name
4911 case '&': ret = get_option_tv(arg, rettv, evaluate);
4912 break;
4915 * Environment variable: $VAR.
4917 case '$': ret = get_env_tv(arg, rettv, evaluate);
4918 break;
4921 * Register contents: @r.
4923 case '@': ++*arg;
4924 if (evaluate)
4926 rettv->v_type = VAR_STRING;
4927 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4929 if (**arg != NUL)
4930 ++*arg;
4931 break;
4934 * nested expression: (expression).
4936 case '(': *arg = skipwhite(*arg + 1);
4937 ret = eval1(arg, rettv, evaluate); /* recursive! */
4938 if (**arg == ')')
4939 ++*arg;
4940 else if (ret == OK)
4942 EMSG(_("E110: Missing ')'"));
4943 clear_tv(rettv);
4944 ret = FAIL;
4946 break;
4948 default: ret = NOTDONE;
4949 break;
4952 if (ret == NOTDONE)
4955 * Must be a variable or function name.
4956 * Can also be a curly-braces kind of name: {expr}.
4958 s = *arg;
4959 len = get_name_len(arg, &alias, evaluate, TRUE);
4960 if (alias != NULL)
4961 s = alias;
4963 if (len <= 0)
4964 ret = FAIL;
4965 else
4967 if (**arg == '(') /* recursive! */
4969 /* If "s" is the name of a variable of type VAR_FUNC
4970 * use its contents. */
4971 s = deref_func_name(s, &len);
4973 /* Invoke the function. */
4974 ret = get_func_tv(s, len, rettv, arg,
4975 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
4976 &len, evaluate, NULL);
4977 /* Stop the expression evaluation when immediately
4978 * aborting on error, or when an interrupt occurred or
4979 * an exception was thrown but not caught. */
4980 if (aborting())
4982 if (ret == OK)
4983 clear_tv(rettv);
4984 ret = FAIL;
4987 else if (evaluate)
4988 ret = get_var_tv(s, len, rettv, TRUE);
4989 else
4990 ret = OK;
4993 if (alias != NULL)
4994 vim_free(alias);
4997 *arg = skipwhite(*arg);
4999 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
5000 * expr(expr). */
5001 if (ret == OK)
5002 ret = handle_subscript(arg, rettv, evaluate, TRUE);
5005 * Apply logical NOT and unary '-', from right to left, ignore '+'.
5007 if (ret == OK && evaluate && end_leader > start_leader)
5009 int error = FALSE;
5010 int val = 0;
5011 #ifdef FEAT_FLOAT
5012 float_T f = 0.0;
5014 if (rettv->v_type == VAR_FLOAT)
5015 f = rettv->vval.v_float;
5016 else
5017 #endif
5018 val = get_tv_number_chk(rettv, &error);
5019 if (error)
5021 clear_tv(rettv);
5022 ret = FAIL;
5024 else
5026 while (end_leader > start_leader)
5028 --end_leader;
5029 if (*end_leader == '!')
5031 #ifdef FEAT_FLOAT
5032 if (rettv->v_type == VAR_FLOAT)
5033 f = !f;
5034 else
5035 #endif
5036 val = !val;
5038 else if (*end_leader == '-')
5040 #ifdef FEAT_FLOAT
5041 if (rettv->v_type == VAR_FLOAT)
5042 f = -f;
5043 else
5044 #endif
5045 val = -val;
5048 #ifdef FEAT_FLOAT
5049 if (rettv->v_type == VAR_FLOAT)
5051 clear_tv(rettv);
5052 rettv->vval.v_float = f;
5054 else
5055 #endif
5057 clear_tv(rettv);
5058 rettv->v_type = VAR_NUMBER;
5059 rettv->vval.v_number = val;
5064 return ret;
5068 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
5069 * "*arg" points to the '[' or '.'.
5070 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
5072 static int
5073 eval_index(arg, rettv, evaluate, verbose)
5074 char_u **arg;
5075 typval_T *rettv;
5076 int evaluate;
5077 int verbose; /* give error messages */
5079 int empty1 = FALSE, empty2 = FALSE;
5080 typval_T var1, var2;
5081 long n1, n2 = 0;
5082 long len = -1;
5083 int range = FALSE;
5084 char_u *s;
5085 char_u *key = NULL;
5087 if (rettv->v_type == VAR_FUNC
5088 #ifdef FEAT_FLOAT
5089 || rettv->v_type == VAR_FLOAT
5090 #endif
5093 if (verbose)
5094 EMSG(_("E695: Cannot index a Funcref"));
5095 return FAIL;
5098 if (**arg == '.')
5101 * dict.name
5103 key = *arg + 1;
5104 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
5106 if (len == 0)
5107 return FAIL;
5108 *arg = skipwhite(key + len);
5110 else
5113 * something[idx]
5115 * Get the (first) variable from inside the [].
5117 *arg = skipwhite(*arg + 1);
5118 if (**arg == ':')
5119 empty1 = TRUE;
5120 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
5121 return FAIL;
5122 else if (evaluate && get_tv_string_chk(&var1) == NULL)
5124 /* not a number or string */
5125 clear_tv(&var1);
5126 return FAIL;
5130 * Get the second variable from inside the [:].
5132 if (**arg == ':')
5134 range = TRUE;
5135 *arg = skipwhite(*arg + 1);
5136 if (**arg == ']')
5137 empty2 = TRUE;
5138 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
5140 if (!empty1)
5141 clear_tv(&var1);
5142 return FAIL;
5144 else if (evaluate && get_tv_string_chk(&var2) == NULL)
5146 /* not a number or string */
5147 if (!empty1)
5148 clear_tv(&var1);
5149 clear_tv(&var2);
5150 return FAIL;
5154 /* Check for the ']'. */
5155 if (**arg != ']')
5157 if (verbose)
5158 EMSG(_(e_missbrac));
5159 clear_tv(&var1);
5160 if (range)
5161 clear_tv(&var2);
5162 return FAIL;
5164 *arg = skipwhite(*arg + 1); /* skip the ']' */
5167 if (evaluate)
5169 n1 = 0;
5170 if (!empty1 && rettv->v_type != VAR_DICT)
5172 n1 = get_tv_number(&var1);
5173 clear_tv(&var1);
5175 if (range)
5177 if (empty2)
5178 n2 = -1;
5179 else
5181 n2 = get_tv_number(&var2);
5182 clear_tv(&var2);
5186 switch (rettv->v_type)
5188 case VAR_NUMBER:
5189 case VAR_STRING:
5190 s = get_tv_string(rettv);
5191 len = (long)STRLEN(s);
5192 if (range)
5194 /* The resulting variable is a substring. If the indexes
5195 * are out of range the result is empty. */
5196 if (n1 < 0)
5198 n1 = len + n1;
5199 if (n1 < 0)
5200 n1 = 0;
5202 if (n2 < 0)
5203 n2 = len + n2;
5204 else if (n2 >= len)
5205 n2 = len;
5206 if (n1 >= len || n2 < 0 || n1 > n2)
5207 s = NULL;
5208 else
5209 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
5211 else
5213 /* The resulting variable is a string of a single
5214 * character. If the index is too big or negative the
5215 * result is empty. */
5216 if (n1 >= len || n1 < 0)
5217 s = NULL;
5218 else
5219 s = vim_strnsave(s + n1, 1);
5221 clear_tv(rettv);
5222 rettv->v_type = VAR_STRING;
5223 rettv->vval.v_string = s;
5224 break;
5226 case VAR_LIST:
5227 len = list_len(rettv->vval.v_list);
5228 if (n1 < 0)
5229 n1 = len + n1;
5230 if (!empty1 && (n1 < 0 || n1 >= len))
5232 /* For a range we allow invalid values and return an empty
5233 * list. A list index out of range is an error. */
5234 if (!range)
5236 if (verbose)
5237 EMSGN(_(e_listidx), n1);
5238 return FAIL;
5240 n1 = len;
5242 if (range)
5244 list_T *l;
5245 listitem_T *item;
5247 if (n2 < 0)
5248 n2 = len + n2;
5249 else if (n2 >= len)
5250 n2 = len - 1;
5251 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
5252 n2 = -1;
5253 l = list_alloc();
5254 if (l == NULL)
5255 return FAIL;
5256 for (item = list_find(rettv->vval.v_list, n1);
5257 n1 <= n2; ++n1)
5259 if (list_append_tv(l, &item->li_tv) == FAIL)
5261 list_free(l, TRUE);
5262 return FAIL;
5264 item = item->li_next;
5266 clear_tv(rettv);
5267 rettv->v_type = VAR_LIST;
5268 rettv->vval.v_list = l;
5269 ++l->lv_refcount;
5271 else
5273 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
5274 clear_tv(rettv);
5275 *rettv = var1;
5277 break;
5279 case VAR_DICT:
5280 if (range)
5282 if (verbose)
5283 EMSG(_(e_dictrange));
5284 if (len == -1)
5285 clear_tv(&var1);
5286 return FAIL;
5289 dictitem_T *item;
5291 if (len == -1)
5293 key = get_tv_string(&var1);
5294 if (*key == NUL)
5296 if (verbose)
5297 EMSG(_(e_emptykey));
5298 clear_tv(&var1);
5299 return FAIL;
5303 item = dict_find(rettv->vval.v_dict, key, (int)len);
5305 if (item == NULL && verbose)
5306 EMSG2(_(e_dictkey), key);
5307 if (len == -1)
5308 clear_tv(&var1);
5309 if (item == NULL)
5310 return FAIL;
5312 copy_tv(&item->di_tv, &var1);
5313 clear_tv(rettv);
5314 *rettv = var1;
5316 break;
5320 return OK;
5324 * Get an option value.
5325 * "arg" points to the '&' or '+' before the option name.
5326 * "arg" is advanced to character after the option name.
5327 * Return OK or FAIL.
5329 static int
5330 get_option_tv(arg, rettv, evaluate)
5331 char_u **arg;
5332 typval_T *rettv; /* when NULL, only check if option exists */
5333 int evaluate;
5335 char_u *option_end;
5336 long numval;
5337 char_u *stringval;
5338 int opt_type;
5339 int c;
5340 int working = (**arg == '+'); /* has("+option") */
5341 int ret = OK;
5342 int opt_flags;
5345 * Isolate the option name and find its value.
5347 option_end = find_option_end(arg, &opt_flags);
5348 if (option_end == NULL)
5350 if (rettv != NULL)
5351 EMSG2(_("E112: Option name missing: %s"), *arg);
5352 return FAIL;
5355 if (!evaluate)
5357 *arg = option_end;
5358 return OK;
5361 c = *option_end;
5362 *option_end = NUL;
5363 opt_type = get_option_value(*arg, &numval,
5364 rettv == NULL ? NULL : &stringval, opt_flags);
5366 if (opt_type == -3) /* invalid name */
5368 if (rettv != NULL)
5369 EMSG2(_("E113: Unknown option: %s"), *arg);
5370 ret = FAIL;
5372 else if (rettv != NULL)
5374 if (opt_type == -2) /* hidden string option */
5376 rettv->v_type = VAR_STRING;
5377 rettv->vval.v_string = NULL;
5379 else if (opt_type == -1) /* hidden number option */
5381 rettv->v_type = VAR_NUMBER;
5382 rettv->vval.v_number = 0;
5384 else if (opt_type == 1) /* number option */
5386 rettv->v_type = VAR_NUMBER;
5387 rettv->vval.v_number = numval;
5389 else /* string option */
5391 rettv->v_type = VAR_STRING;
5392 rettv->vval.v_string = stringval;
5395 else if (working && (opt_type == -2 || opt_type == -1))
5396 ret = FAIL;
5398 *option_end = c; /* put back for error messages */
5399 *arg = option_end;
5401 return ret;
5405 * Allocate a variable for a string constant.
5406 * Return OK or FAIL.
5408 static int
5409 get_string_tv(arg, rettv, evaluate)
5410 char_u **arg;
5411 typval_T *rettv;
5412 int evaluate;
5414 char_u *p;
5415 char_u *name;
5416 int extra = 0;
5419 * Find the end of the string, skipping backslashed characters.
5421 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5423 if (*p == '\\' && p[1] != NUL)
5425 ++p;
5426 /* A "\<x>" form occupies at least 4 characters, and produces up
5427 * to 6 characters: reserve space for 2 extra */
5428 if (*p == '<')
5429 extra += 2;
5433 if (*p != '"')
5435 EMSG2(_("E114: Missing quote: %s"), *arg);
5436 return FAIL;
5439 /* If only parsing, set *arg and return here */
5440 if (!evaluate)
5442 *arg = p + 1;
5443 return OK;
5447 * Copy the string into allocated memory, handling backslashed
5448 * characters.
5450 name = alloc((unsigned)(p - *arg + extra));
5451 if (name == NULL)
5452 return FAIL;
5453 rettv->v_type = VAR_STRING;
5454 rettv->vval.v_string = name;
5456 for (p = *arg + 1; *p != NUL && *p != '"'; )
5458 if (*p == '\\')
5460 switch (*++p)
5462 case 'b': *name++ = BS; ++p; break;
5463 case 'e': *name++ = ESC; ++p; break;
5464 case 'f': *name++ = FF; ++p; break;
5465 case 'n': *name++ = NL; ++p; break;
5466 case 'r': *name++ = CAR; ++p; break;
5467 case 't': *name++ = TAB; ++p; break;
5469 case 'X': /* hex: "\x1", "\x12" */
5470 case 'x':
5471 case 'u': /* Unicode: "\u0023" */
5472 case 'U':
5473 if (vim_isxdigit(p[1]))
5475 int n, nr;
5476 int c = toupper(*p);
5478 if (c == 'X')
5479 n = 2;
5480 else
5481 n = 4;
5482 nr = 0;
5483 while (--n >= 0 && vim_isxdigit(p[1]))
5485 ++p;
5486 nr = (nr << 4) + hex2nr(*p);
5488 ++p;
5489 #ifdef FEAT_MBYTE
5490 /* For "\u" store the number according to
5491 * 'encoding'. */
5492 if (c != 'X')
5493 name += (*mb_char2bytes)(nr, name);
5494 else
5495 #endif
5496 *name++ = nr;
5498 break;
5500 /* octal: "\1", "\12", "\123" */
5501 case '0':
5502 case '1':
5503 case '2':
5504 case '3':
5505 case '4':
5506 case '5':
5507 case '6':
5508 case '7': *name = *p++ - '0';
5509 if (*p >= '0' && *p <= '7')
5511 *name = (*name << 3) + *p++ - '0';
5512 if (*p >= '0' && *p <= '7')
5513 *name = (*name << 3) + *p++ - '0';
5515 ++name;
5516 break;
5518 /* Special key, e.g.: "\<C-W>" */
5519 case '<': extra = trans_special(&p, name, TRUE);
5520 if (extra != 0)
5522 name += extra;
5523 break;
5525 /* FALLTHROUGH */
5527 default: MB_COPY_CHAR(p, name);
5528 break;
5531 else
5532 MB_COPY_CHAR(p, name);
5535 *name = NUL;
5536 *arg = p + 1;
5538 return OK;
5542 * Allocate a variable for a 'str''ing' constant.
5543 * Return OK or FAIL.
5545 static int
5546 get_lit_string_tv(arg, rettv, evaluate)
5547 char_u **arg;
5548 typval_T *rettv;
5549 int evaluate;
5551 char_u *p;
5552 char_u *str;
5553 int reduce = 0;
5556 * Find the end of the string, skipping ''.
5558 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5560 if (*p == '\'')
5562 if (p[1] != '\'')
5563 break;
5564 ++reduce;
5565 ++p;
5569 if (*p != '\'')
5571 EMSG2(_("E115: Missing quote: %s"), *arg);
5572 return FAIL;
5575 /* If only parsing return after setting "*arg" */
5576 if (!evaluate)
5578 *arg = p + 1;
5579 return OK;
5583 * Copy the string into allocated memory, handling '' to ' reduction.
5585 str = alloc((unsigned)((p - *arg) - reduce));
5586 if (str == NULL)
5587 return FAIL;
5588 rettv->v_type = VAR_STRING;
5589 rettv->vval.v_string = str;
5591 for (p = *arg + 1; *p != NUL; )
5593 if (*p == '\'')
5595 if (p[1] != '\'')
5596 break;
5597 ++p;
5599 MB_COPY_CHAR(p, str);
5601 *str = NUL;
5602 *arg = p + 1;
5604 return OK;
5608 * Allocate a variable for a List and fill it from "*arg".
5609 * Return OK or FAIL.
5611 static int
5612 get_list_tv(arg, rettv, evaluate)
5613 char_u **arg;
5614 typval_T *rettv;
5615 int evaluate;
5617 list_T *l = NULL;
5618 typval_T tv;
5619 listitem_T *item;
5621 if (evaluate)
5623 l = list_alloc();
5624 if (l == NULL)
5625 return FAIL;
5628 *arg = skipwhite(*arg + 1);
5629 while (**arg != ']' && **arg != NUL)
5631 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5632 goto failret;
5633 if (evaluate)
5635 item = listitem_alloc();
5636 if (item != NULL)
5638 item->li_tv = tv;
5639 item->li_tv.v_lock = 0;
5640 list_append(l, item);
5642 else
5643 clear_tv(&tv);
5646 if (**arg == ']')
5647 break;
5648 if (**arg != ',')
5650 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5651 goto failret;
5653 *arg = skipwhite(*arg + 1);
5656 if (**arg != ']')
5658 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5659 failret:
5660 if (evaluate)
5661 list_free(l, TRUE);
5662 return FAIL;
5665 *arg = skipwhite(*arg + 1);
5666 if (evaluate)
5668 rettv->v_type = VAR_LIST;
5669 rettv->vval.v_list = l;
5670 ++l->lv_refcount;
5673 return OK;
5677 * Allocate an empty header for a list.
5678 * Caller should take care of the reference count.
5680 list_T *
5681 list_alloc()
5683 list_T *l;
5685 l = (list_T *)alloc_clear(sizeof(list_T));
5686 if (l != NULL)
5688 /* Prepend the list to the list of lists for garbage collection. */
5689 if (first_list != NULL)
5690 first_list->lv_used_prev = l;
5691 l->lv_used_prev = NULL;
5692 l->lv_used_next = first_list;
5693 first_list = l;
5695 return l;
5699 * Allocate an empty list for a return value.
5700 * Returns OK or FAIL.
5702 static int
5703 rettv_list_alloc(rettv)
5704 typval_T *rettv;
5706 list_T *l = list_alloc();
5708 if (l == NULL)
5709 return FAIL;
5711 rettv->vval.v_list = l;
5712 rettv->v_type = VAR_LIST;
5713 ++l->lv_refcount;
5714 return OK;
5718 * Unreference a list: decrement the reference count and free it when it
5719 * becomes zero.
5721 void
5722 list_unref(l)
5723 list_T *l;
5725 if (l != NULL && --l->lv_refcount <= 0)
5726 list_free(l, TRUE);
5730 * Free a list, including all items it points to.
5731 * Ignores the reference count.
5733 void
5734 list_free(l, recurse)
5735 list_T *l;
5736 int recurse; /* Free Lists and Dictionaries recursively. */
5738 listitem_T *item;
5740 /* Remove the list from the list of lists for garbage collection. */
5741 if (l->lv_used_prev == NULL)
5742 first_list = l->lv_used_next;
5743 else
5744 l->lv_used_prev->lv_used_next = l->lv_used_next;
5745 if (l->lv_used_next != NULL)
5746 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5748 for (item = l->lv_first; item != NULL; item = l->lv_first)
5750 /* Remove the item before deleting it. */
5751 l->lv_first = item->li_next;
5752 if (recurse || (item->li_tv.v_type != VAR_LIST
5753 && item->li_tv.v_type != VAR_DICT))
5754 clear_tv(&item->li_tv);
5755 vim_free(item);
5757 vim_free(l);
5761 * Allocate a list item.
5763 static listitem_T *
5764 listitem_alloc()
5766 return (listitem_T *)alloc(sizeof(listitem_T));
5770 * Free a list item. Also clears the value. Does not notify watchers.
5772 static void
5773 listitem_free(item)
5774 listitem_T *item;
5776 clear_tv(&item->li_tv);
5777 vim_free(item);
5781 * Remove a list item from a List and free it. Also clears the value.
5783 static void
5784 listitem_remove(l, item)
5785 list_T *l;
5786 listitem_T *item;
5788 list_remove(l, item, item);
5789 listitem_free(item);
5793 * Get the number of items in a list.
5795 static long
5796 list_len(l)
5797 list_T *l;
5799 if (l == NULL)
5800 return 0L;
5801 return l->lv_len;
5805 * Return TRUE when two lists have exactly the same values.
5807 static int
5808 list_equal(l1, l2, ic)
5809 list_T *l1;
5810 list_T *l2;
5811 int ic; /* ignore case for strings */
5813 listitem_T *item1, *item2;
5815 if (l1 == l2)
5816 return TRUE;
5817 if (list_len(l1) != list_len(l2))
5818 return FALSE;
5820 for (item1 = l1->lv_first, item2 = l2->lv_first;
5821 item1 != NULL && item2 != NULL;
5822 item1 = item1->li_next, item2 = item2->li_next)
5823 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5824 return FALSE;
5825 return item1 == NULL && item2 == NULL;
5828 #if defined(FEAT_PYTHON) || defined(PROTO)
5830 * Return the dictitem that an entry in a hashtable points to.
5832 dictitem_T *
5833 dict_lookup(hi)
5834 hashitem_T *hi;
5836 return HI2DI(hi);
5838 #endif
5841 * Return TRUE when two dictionaries have exactly the same key/values.
5843 static int
5844 dict_equal(d1, d2, ic)
5845 dict_T *d1;
5846 dict_T *d2;
5847 int ic; /* ignore case for strings */
5849 hashitem_T *hi;
5850 dictitem_T *item2;
5851 int todo;
5853 if (d1 == d2)
5854 return TRUE;
5855 if (dict_len(d1) != dict_len(d2))
5856 return FALSE;
5858 todo = (int)d1->dv_hashtab.ht_used;
5859 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5861 if (!HASHITEM_EMPTY(hi))
5863 item2 = dict_find(d2, hi->hi_key, -1);
5864 if (item2 == NULL)
5865 return FALSE;
5866 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5867 return FALSE;
5868 --todo;
5871 return TRUE;
5875 * Return TRUE if "tv1" and "tv2" have the same value.
5876 * Compares the items just like "==" would compare them, but strings and
5877 * numbers are different. Floats and numbers are also different.
5879 static int
5880 tv_equal(tv1, tv2, ic)
5881 typval_T *tv1;
5882 typval_T *tv2;
5883 int ic; /* ignore case */
5885 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5886 char_u *s1, *s2;
5887 static int recursive = 0; /* cach recursive loops */
5888 int r;
5890 if (tv1->v_type != tv2->v_type)
5891 return FALSE;
5892 /* Catch lists and dicts that have an endless loop by limiting
5893 * recursiveness to 1000. We guess they are equal then. */
5894 if (recursive >= 1000)
5895 return TRUE;
5897 switch (tv1->v_type)
5899 case VAR_LIST:
5900 ++recursive;
5901 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5902 --recursive;
5903 return r;
5905 case VAR_DICT:
5906 ++recursive;
5907 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5908 --recursive;
5909 return r;
5911 case VAR_FUNC:
5912 return (tv1->vval.v_string != NULL
5913 && tv2->vval.v_string != NULL
5914 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5916 case VAR_NUMBER:
5917 return tv1->vval.v_number == tv2->vval.v_number;
5919 #ifdef FEAT_FLOAT
5920 case VAR_FLOAT:
5921 return tv1->vval.v_float == tv2->vval.v_float;
5922 #endif
5924 case VAR_STRING:
5925 s1 = get_tv_string_buf(tv1, buf1);
5926 s2 = get_tv_string_buf(tv2, buf2);
5927 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5930 EMSG2(_(e_intern2), "tv_equal()");
5931 return TRUE;
5935 * Locate item with index "n" in list "l" and return it.
5936 * A negative index is counted from the end; -1 is the last item.
5937 * Returns NULL when "n" is out of range.
5939 static listitem_T *
5940 list_find(l, n)
5941 list_T *l;
5942 long n;
5944 listitem_T *item;
5945 long idx;
5947 if (l == NULL)
5948 return NULL;
5950 /* Negative index is relative to the end. */
5951 if (n < 0)
5952 n = l->lv_len + n;
5954 /* Check for index out of range. */
5955 if (n < 0 || n >= l->lv_len)
5956 return NULL;
5958 /* When there is a cached index may start search from there. */
5959 if (l->lv_idx_item != NULL)
5961 if (n < l->lv_idx / 2)
5963 /* closest to the start of the list */
5964 item = l->lv_first;
5965 idx = 0;
5967 else if (n > (l->lv_idx + l->lv_len) / 2)
5969 /* closest to the end of the list */
5970 item = l->lv_last;
5971 idx = l->lv_len - 1;
5973 else
5975 /* closest to the cached index */
5976 item = l->lv_idx_item;
5977 idx = l->lv_idx;
5980 else
5982 if (n < l->lv_len / 2)
5984 /* closest to the start of the list */
5985 item = l->lv_first;
5986 idx = 0;
5988 else
5990 /* closest to the end of the list */
5991 item = l->lv_last;
5992 idx = l->lv_len - 1;
5996 while (n > idx)
5998 /* search forward */
5999 item = item->li_next;
6000 ++idx;
6002 while (n < idx)
6004 /* search backward */
6005 item = item->li_prev;
6006 --idx;
6009 /* cache the used index */
6010 l->lv_idx = idx;
6011 l->lv_idx_item = item;
6013 return item;
6017 * Get list item "l[idx]" as a number.
6019 static long
6020 list_find_nr(l, idx, errorp)
6021 list_T *l;
6022 long idx;
6023 int *errorp; /* set to TRUE when something wrong */
6025 listitem_T *li;
6027 li = list_find(l, idx);
6028 if (li == NULL)
6030 if (errorp != NULL)
6031 *errorp = TRUE;
6032 return -1L;
6034 return get_tv_number_chk(&li->li_tv, errorp);
6038 * Locate "item" list "l" and return its index.
6039 * Returns -1 when "item" is not in the list.
6041 static long
6042 list_idx_of_item(l, item)
6043 list_T *l;
6044 listitem_T *item;
6046 long idx = 0;
6047 listitem_T *li;
6049 if (l == NULL)
6050 return -1;
6051 idx = 0;
6052 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
6053 ++idx;
6054 if (li == NULL)
6055 return -1;
6056 return idx;
6060 * Append item "item" to the end of list "l".
6062 static void
6063 list_append(l, item)
6064 list_T *l;
6065 listitem_T *item;
6067 if (l->lv_last == NULL)
6069 /* empty list */
6070 l->lv_first = item;
6071 l->lv_last = item;
6072 item->li_prev = NULL;
6074 else
6076 l->lv_last->li_next = item;
6077 item->li_prev = l->lv_last;
6078 l->lv_last = item;
6080 ++l->lv_len;
6081 item->li_next = NULL;
6085 * Append typval_T "tv" to the end of list "l".
6086 * Return FAIL when out of memory.
6088 static int
6089 list_append_tv(l, tv)
6090 list_T *l;
6091 typval_T *tv;
6093 listitem_T *li = listitem_alloc();
6095 if (li == NULL)
6096 return FAIL;
6097 copy_tv(tv, &li->li_tv);
6098 list_append(l, li);
6099 return OK;
6103 * Add a dictionary to a list. Used by getqflist().
6104 * Return FAIL when out of memory.
6107 list_append_dict(list, dict)
6108 list_T *list;
6109 dict_T *dict;
6111 listitem_T *li = listitem_alloc();
6113 if (li == NULL)
6114 return FAIL;
6115 li->li_tv.v_type = VAR_DICT;
6116 li->li_tv.v_lock = 0;
6117 li->li_tv.vval.v_dict = dict;
6118 list_append(list, li);
6119 ++dict->dv_refcount;
6120 return OK;
6124 * Make a copy of "str" and append it as an item to list "l".
6125 * When "len" >= 0 use "str[len]".
6126 * Returns FAIL when out of memory.
6128 static int
6129 list_append_string(l, str, len)
6130 list_T *l;
6131 char_u *str;
6132 int len;
6134 listitem_T *li = listitem_alloc();
6136 if (li == NULL)
6137 return FAIL;
6138 list_append(l, li);
6139 li->li_tv.v_type = VAR_STRING;
6140 li->li_tv.v_lock = 0;
6141 if (str == NULL)
6142 li->li_tv.vval.v_string = NULL;
6143 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
6144 : vim_strsave(str))) == NULL)
6145 return FAIL;
6146 return OK;
6150 * Append "n" to list "l".
6151 * Returns FAIL when out of memory.
6153 static int
6154 list_append_number(l, n)
6155 list_T *l;
6156 varnumber_T n;
6158 listitem_T *li;
6160 li = listitem_alloc();
6161 if (li == NULL)
6162 return FAIL;
6163 li->li_tv.v_type = VAR_NUMBER;
6164 li->li_tv.v_lock = 0;
6165 li->li_tv.vval.v_number = n;
6166 list_append(l, li);
6167 return OK;
6171 * Insert typval_T "tv" in list "l" before "item".
6172 * If "item" is NULL append at the end.
6173 * Return FAIL when out of memory.
6175 static int
6176 list_insert_tv(l, tv, item)
6177 list_T *l;
6178 typval_T *tv;
6179 listitem_T *item;
6181 listitem_T *ni = listitem_alloc();
6183 if (ni == NULL)
6184 return FAIL;
6185 copy_tv(tv, &ni->li_tv);
6186 if (item == NULL)
6187 /* Append new item at end of list. */
6188 list_append(l, ni);
6189 else
6191 /* Insert new item before existing item. */
6192 ni->li_prev = item->li_prev;
6193 ni->li_next = item;
6194 if (item->li_prev == NULL)
6196 l->lv_first = ni;
6197 ++l->lv_idx;
6199 else
6201 item->li_prev->li_next = ni;
6202 l->lv_idx_item = NULL;
6204 item->li_prev = ni;
6205 ++l->lv_len;
6207 return OK;
6211 * Extend "l1" with "l2".
6212 * If "bef" is NULL append at the end, otherwise insert before this item.
6213 * Returns FAIL when out of memory.
6215 static int
6216 list_extend(l1, l2, bef)
6217 list_T *l1;
6218 list_T *l2;
6219 listitem_T *bef;
6221 listitem_T *item;
6223 for (item = l2->lv_first; item != NULL; item = item->li_next)
6224 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
6225 return FAIL;
6226 return OK;
6230 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
6231 * Return FAIL when out of memory.
6233 static int
6234 list_concat(l1, l2, tv)
6235 list_T *l1;
6236 list_T *l2;
6237 typval_T *tv;
6239 list_T *l;
6241 /* make a copy of the first list. */
6242 l = list_copy(l1, FALSE, 0);
6243 if (l == NULL)
6244 return FAIL;
6245 tv->v_type = VAR_LIST;
6246 tv->vval.v_list = l;
6248 /* append all items from the second list */
6249 return list_extend(l, l2, NULL);
6253 * Make a copy of list "orig". Shallow if "deep" is FALSE.
6254 * The refcount of the new list is set to 1.
6255 * See item_copy() for "copyID".
6256 * Returns NULL when out of memory.
6258 static list_T *
6259 list_copy(orig, deep, copyID)
6260 list_T *orig;
6261 int deep;
6262 int copyID;
6264 list_T *copy;
6265 listitem_T *item;
6266 listitem_T *ni;
6268 if (orig == NULL)
6269 return NULL;
6271 copy = list_alloc();
6272 if (copy != NULL)
6274 if (copyID != 0)
6276 /* Do this before adding the items, because one of the items may
6277 * refer back to this list. */
6278 orig->lv_copyID = copyID;
6279 orig->lv_copylist = copy;
6281 for (item = orig->lv_first; item != NULL && !got_int;
6282 item = item->li_next)
6284 ni = listitem_alloc();
6285 if (ni == NULL)
6286 break;
6287 if (deep)
6289 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
6291 vim_free(ni);
6292 break;
6295 else
6296 copy_tv(&item->li_tv, &ni->li_tv);
6297 list_append(copy, ni);
6299 ++copy->lv_refcount;
6300 if (item != NULL)
6302 list_unref(copy);
6303 copy = NULL;
6307 return copy;
6311 * Remove items "item" to "item2" from list "l".
6312 * Does not free the listitem or the value!
6314 static void
6315 list_remove(l, item, item2)
6316 list_T *l;
6317 listitem_T *item;
6318 listitem_T *item2;
6320 listitem_T *ip;
6322 /* notify watchers */
6323 for (ip = item; ip != NULL; ip = ip->li_next)
6325 --l->lv_len;
6326 list_fix_watch(l, ip);
6327 if (ip == item2)
6328 break;
6331 if (item2->li_next == NULL)
6332 l->lv_last = item->li_prev;
6333 else
6334 item2->li_next->li_prev = item->li_prev;
6335 if (item->li_prev == NULL)
6336 l->lv_first = item2->li_next;
6337 else
6338 item->li_prev->li_next = item2->li_next;
6339 l->lv_idx_item = NULL;
6343 * Return an allocated string with the string representation of a list.
6344 * May return NULL.
6346 static char_u *
6347 list2string(tv, copyID)
6348 typval_T *tv;
6349 int copyID;
6351 garray_T ga;
6353 if (tv->vval.v_list == NULL)
6354 return NULL;
6355 ga_init2(&ga, (int)sizeof(char), 80);
6356 ga_append(&ga, '[');
6357 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6359 vim_free(ga.ga_data);
6360 return NULL;
6362 ga_append(&ga, ']');
6363 ga_append(&ga, NUL);
6364 return (char_u *)ga.ga_data;
6368 * Join list "l" into a string in "*gap", using separator "sep".
6369 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6370 * Return FAIL or OK.
6372 static int
6373 list_join(gap, l, sep, echo, copyID)
6374 garray_T *gap;
6375 list_T *l;
6376 char_u *sep;
6377 int echo;
6378 int copyID;
6380 int first = TRUE;
6381 char_u *tofree;
6382 char_u numbuf[NUMBUFLEN];
6383 listitem_T *item;
6384 char_u *s;
6386 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6388 if (first)
6389 first = FALSE;
6390 else
6391 ga_concat(gap, sep);
6393 if (echo)
6394 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6395 else
6396 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6397 if (s != NULL)
6398 ga_concat(gap, s);
6399 vim_free(tofree);
6400 if (s == NULL)
6401 return FAIL;
6403 return OK;
6407 * Garbage collection for lists and dictionaries.
6409 * We use reference counts to be able to free most items right away when they
6410 * are no longer used. But for composite items it's possible that it becomes
6411 * unused while the reference count is > 0: When there is a recursive
6412 * reference. Example:
6413 * :let l = [1, 2, 3]
6414 * :let d = {9: l}
6415 * :let l[1] = d
6417 * Since this is quite unusual we handle this with garbage collection: every
6418 * once in a while find out which lists and dicts are not referenced from any
6419 * variable.
6421 * Here is a good reference text about garbage collection (refers to Python
6422 * but it applies to all reference-counting mechanisms):
6423 * http://python.ca/nas/python/gc/
6427 * Do garbage collection for lists and dicts.
6428 * Return TRUE if some memory was freed.
6431 garbage_collect()
6433 dict_T *dd;
6434 list_T *ll;
6435 int copyID = ++current_copyID;
6436 buf_T *buf;
6437 win_T *wp;
6438 int i;
6439 funccall_T *fc;
6440 int did_free = FALSE;
6441 #ifdef FEAT_WINDOWS
6442 tabpage_T *tp;
6443 #endif
6445 /* Only do this once. */
6446 want_garbage_collect = FALSE;
6447 may_garbage_collect = FALSE;
6448 garbage_collect_at_exit = FALSE;
6451 * 1. Go through all accessible variables and mark all lists and dicts
6452 * with copyID.
6454 /* script-local variables */
6455 for (i = 1; i <= ga_scripts.ga_len; ++i)
6456 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6458 /* buffer-local variables */
6459 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6460 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6462 /* window-local variables */
6463 FOR_ALL_TAB_WINDOWS(tp, wp)
6464 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6466 #ifdef FEAT_WINDOWS
6467 /* tabpage-local variables */
6468 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6469 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6470 #endif
6472 /* global variables */
6473 set_ref_in_ht(&globvarht, copyID);
6475 /* function-local variables */
6476 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6478 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6479 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6483 * 2. Go through the list of dicts and free items without the copyID.
6485 for (dd = first_dict; dd != NULL; )
6486 if (dd->dv_copyID != copyID)
6488 /* Free the Dictionary and ordinary items it contains, but don't
6489 * recurse into Lists and Dictionaries, they will be in the list
6490 * of dicts or list of lists. */
6491 dict_free(dd, FALSE);
6492 did_free = TRUE;
6494 /* restart, next dict may also have been freed */
6495 dd = first_dict;
6497 else
6498 dd = dd->dv_used_next;
6501 * 3. Go through the list of lists and free items without the copyID.
6502 * But don't free a list that has a watcher (used in a for loop), these
6503 * are not referenced anywhere.
6505 for (ll = first_list; ll != NULL; )
6506 if (ll->lv_copyID != copyID && ll->lv_watch == NULL)
6508 /* Free the List and ordinary items it contains, but don't recurse
6509 * into Lists and Dictionaries, they will be in the list of dicts
6510 * or list of lists. */
6511 list_free(ll, FALSE);
6512 did_free = TRUE;
6514 /* restart, next list may also have been freed */
6515 ll = first_list;
6517 else
6518 ll = ll->lv_used_next;
6520 return did_free;
6524 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6526 static void
6527 set_ref_in_ht(ht, copyID)
6528 hashtab_T *ht;
6529 int copyID;
6531 int todo;
6532 hashitem_T *hi;
6534 todo = (int)ht->ht_used;
6535 for (hi = ht->ht_array; todo > 0; ++hi)
6536 if (!HASHITEM_EMPTY(hi))
6538 --todo;
6539 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6544 * Mark all lists and dicts referenced through list "l" with "copyID".
6546 static void
6547 set_ref_in_list(l, copyID)
6548 list_T *l;
6549 int copyID;
6551 listitem_T *li;
6553 for (li = l->lv_first; li != NULL; li = li->li_next)
6554 set_ref_in_item(&li->li_tv, copyID);
6558 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6560 static void
6561 set_ref_in_item(tv, copyID)
6562 typval_T *tv;
6563 int copyID;
6565 dict_T *dd;
6566 list_T *ll;
6568 switch (tv->v_type)
6570 case VAR_DICT:
6571 dd = tv->vval.v_dict;
6572 if (dd->dv_copyID != copyID)
6574 /* Didn't see this dict yet. */
6575 dd->dv_copyID = copyID;
6576 set_ref_in_ht(&dd->dv_hashtab, copyID);
6578 break;
6580 case VAR_LIST:
6581 ll = tv->vval.v_list;
6582 if (ll->lv_copyID != copyID)
6584 /* Didn't see this list yet. */
6585 ll->lv_copyID = copyID;
6586 set_ref_in_list(ll, copyID);
6588 break;
6590 return;
6594 * Allocate an empty header for a dictionary.
6596 dict_T *
6597 dict_alloc()
6599 dict_T *d;
6601 d = (dict_T *)alloc(sizeof(dict_T));
6602 if (d != NULL)
6604 /* Add the list to the list of dicts for garbage collection. */
6605 if (first_dict != NULL)
6606 first_dict->dv_used_prev = d;
6607 d->dv_used_next = first_dict;
6608 d->dv_used_prev = NULL;
6609 first_dict = d;
6611 hash_init(&d->dv_hashtab);
6612 d->dv_lock = 0;
6613 d->dv_refcount = 0;
6614 d->dv_copyID = 0;
6616 return d;
6620 * Unreference a Dictionary: decrement the reference count and free it when it
6621 * becomes zero.
6623 static void
6624 dict_unref(d)
6625 dict_T *d;
6627 if (d != NULL && --d->dv_refcount <= 0)
6628 dict_free(d, TRUE);
6632 * Free a Dictionary, including all items it contains.
6633 * Ignores the reference count.
6635 static void
6636 dict_free(d, recurse)
6637 dict_T *d;
6638 int recurse; /* Free Lists and Dictionaries recursively. */
6640 int todo;
6641 hashitem_T *hi;
6642 dictitem_T *di;
6644 /* Remove the dict from the list of dicts for garbage collection. */
6645 if (d->dv_used_prev == NULL)
6646 first_dict = d->dv_used_next;
6647 else
6648 d->dv_used_prev->dv_used_next = d->dv_used_next;
6649 if (d->dv_used_next != NULL)
6650 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6652 /* Lock the hashtab, we don't want it to resize while freeing items. */
6653 hash_lock(&d->dv_hashtab);
6654 todo = (int)d->dv_hashtab.ht_used;
6655 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6657 if (!HASHITEM_EMPTY(hi))
6659 /* Remove the item before deleting it, just in case there is
6660 * something recursive causing trouble. */
6661 di = HI2DI(hi);
6662 hash_remove(&d->dv_hashtab, hi);
6663 if (recurse || (di->di_tv.v_type != VAR_LIST
6664 && di->di_tv.v_type != VAR_DICT))
6665 clear_tv(&di->di_tv);
6666 vim_free(di);
6667 --todo;
6670 hash_clear(&d->dv_hashtab);
6671 vim_free(d);
6675 * Allocate a Dictionary item.
6676 * The "key" is copied to the new item.
6677 * Note that the value of the item "di_tv" still needs to be initialized!
6678 * Returns NULL when out of memory.
6680 static dictitem_T *
6681 dictitem_alloc(key)
6682 char_u *key;
6684 dictitem_T *di;
6686 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6687 if (di != NULL)
6689 STRCPY(di->di_key, key);
6690 di->di_flags = 0;
6692 return di;
6696 * Make a copy of a Dictionary item.
6698 static dictitem_T *
6699 dictitem_copy(org)
6700 dictitem_T *org;
6702 dictitem_T *di;
6704 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6705 + STRLEN(org->di_key)));
6706 if (di != NULL)
6708 STRCPY(di->di_key, org->di_key);
6709 di->di_flags = 0;
6710 copy_tv(&org->di_tv, &di->di_tv);
6712 return di;
6716 * Remove item "item" from Dictionary "dict" and free it.
6718 static void
6719 dictitem_remove(dict, item)
6720 dict_T *dict;
6721 dictitem_T *item;
6723 hashitem_T *hi;
6725 hi = hash_find(&dict->dv_hashtab, item->di_key);
6726 if (HASHITEM_EMPTY(hi))
6727 EMSG2(_(e_intern2), "dictitem_remove()");
6728 else
6729 hash_remove(&dict->dv_hashtab, hi);
6730 dictitem_free(item);
6734 * Free a dict item. Also clears the value.
6736 static void
6737 dictitem_free(item)
6738 dictitem_T *item;
6740 clear_tv(&item->di_tv);
6741 vim_free(item);
6745 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6746 * The refcount of the new dict is set to 1.
6747 * See item_copy() for "copyID".
6748 * Returns NULL when out of memory.
6750 static dict_T *
6751 dict_copy(orig, deep, copyID)
6752 dict_T *orig;
6753 int deep;
6754 int copyID;
6756 dict_T *copy;
6757 dictitem_T *di;
6758 int todo;
6759 hashitem_T *hi;
6761 if (orig == NULL)
6762 return NULL;
6764 copy = dict_alloc();
6765 if (copy != NULL)
6767 if (copyID != 0)
6769 orig->dv_copyID = copyID;
6770 orig->dv_copydict = copy;
6772 todo = (int)orig->dv_hashtab.ht_used;
6773 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6775 if (!HASHITEM_EMPTY(hi))
6777 --todo;
6779 di = dictitem_alloc(hi->hi_key);
6780 if (di == NULL)
6781 break;
6782 if (deep)
6784 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6785 copyID) == FAIL)
6787 vim_free(di);
6788 break;
6791 else
6792 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6793 if (dict_add(copy, di) == FAIL)
6795 dictitem_free(di);
6796 break;
6801 ++copy->dv_refcount;
6802 if (todo > 0)
6804 dict_unref(copy);
6805 copy = NULL;
6809 return copy;
6813 * Add item "item" to Dictionary "d".
6814 * Returns FAIL when out of memory and when key already existed.
6816 static int
6817 dict_add(d, item)
6818 dict_T *d;
6819 dictitem_T *item;
6821 return hash_add(&d->dv_hashtab, item->di_key);
6825 * Add a number or string entry to dictionary "d".
6826 * When "str" is NULL use number "nr", otherwise use "str".
6827 * Returns FAIL when out of memory and when key already exists.
6830 dict_add_nr_str(d, key, nr, str)
6831 dict_T *d;
6832 char *key;
6833 long nr;
6834 char_u *str;
6836 dictitem_T *item;
6838 item = dictitem_alloc((char_u *)key);
6839 if (item == NULL)
6840 return FAIL;
6841 item->di_tv.v_lock = 0;
6842 if (str == NULL)
6844 item->di_tv.v_type = VAR_NUMBER;
6845 item->di_tv.vval.v_number = nr;
6847 else
6849 item->di_tv.v_type = VAR_STRING;
6850 item->di_tv.vval.v_string = vim_strsave(str);
6852 if (dict_add(d, item) == FAIL)
6854 dictitem_free(item);
6855 return FAIL;
6857 return OK;
6861 * Get the number of items in a Dictionary.
6863 static long
6864 dict_len(d)
6865 dict_T *d;
6867 if (d == NULL)
6868 return 0L;
6869 return (long)d->dv_hashtab.ht_used;
6873 * Find item "key[len]" in Dictionary "d".
6874 * If "len" is negative use strlen(key).
6875 * Returns NULL when not found.
6877 static dictitem_T *
6878 dict_find(d, key, len)
6879 dict_T *d;
6880 char_u *key;
6881 int len;
6883 #define AKEYLEN 200
6884 char_u buf[AKEYLEN];
6885 char_u *akey;
6886 char_u *tofree = NULL;
6887 hashitem_T *hi;
6889 if (len < 0)
6890 akey = key;
6891 else if (len >= AKEYLEN)
6893 tofree = akey = vim_strnsave(key, len);
6894 if (akey == NULL)
6895 return NULL;
6897 else
6899 /* Avoid a malloc/free by using buf[]. */
6900 vim_strncpy(buf, key, len);
6901 akey = buf;
6904 hi = hash_find(&d->dv_hashtab, akey);
6905 vim_free(tofree);
6906 if (HASHITEM_EMPTY(hi))
6907 return NULL;
6908 return HI2DI(hi);
6912 * Get a string item from a dictionary.
6913 * When "save" is TRUE allocate memory for it.
6914 * Returns NULL if the entry doesn't exist or out of memory.
6916 char_u *
6917 get_dict_string(d, key, save)
6918 dict_T *d;
6919 char_u *key;
6920 int save;
6922 dictitem_T *di;
6923 char_u *s;
6925 di = dict_find(d, key, -1);
6926 if (di == NULL)
6927 return NULL;
6928 s = get_tv_string(&di->di_tv);
6929 if (save && s != NULL)
6930 s = vim_strsave(s);
6931 return s;
6935 * Get a number item from a dictionary.
6936 * Returns 0 if the entry doesn't exist or out of memory.
6938 long
6939 get_dict_number(d, key)
6940 dict_T *d;
6941 char_u *key;
6943 dictitem_T *di;
6945 di = dict_find(d, key, -1);
6946 if (di == NULL)
6947 return 0;
6948 return get_tv_number(&di->di_tv);
6952 * Return an allocated string with the string representation of a Dictionary.
6953 * May return NULL.
6955 static char_u *
6956 dict2string(tv, copyID)
6957 typval_T *tv;
6958 int copyID;
6960 garray_T ga;
6961 int first = TRUE;
6962 char_u *tofree;
6963 char_u numbuf[NUMBUFLEN];
6964 hashitem_T *hi;
6965 char_u *s;
6966 dict_T *d;
6967 int todo;
6969 if ((d = tv->vval.v_dict) == NULL)
6970 return NULL;
6971 ga_init2(&ga, (int)sizeof(char), 80);
6972 ga_append(&ga, '{');
6974 todo = (int)d->dv_hashtab.ht_used;
6975 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6977 if (!HASHITEM_EMPTY(hi))
6979 --todo;
6981 if (first)
6982 first = FALSE;
6983 else
6984 ga_concat(&ga, (char_u *)", ");
6986 tofree = string_quote(hi->hi_key, FALSE);
6987 if (tofree != NULL)
6989 ga_concat(&ga, tofree);
6990 vim_free(tofree);
6992 ga_concat(&ga, (char_u *)": ");
6993 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
6994 if (s != NULL)
6995 ga_concat(&ga, s);
6996 vim_free(tofree);
6997 if (s == NULL)
6998 break;
7001 if (todo > 0)
7003 vim_free(ga.ga_data);
7004 return NULL;
7007 ga_append(&ga, '}');
7008 ga_append(&ga, NUL);
7009 return (char_u *)ga.ga_data;
7013 * Allocate a variable for a Dictionary and fill it from "*arg".
7014 * Return OK or FAIL. Returns NOTDONE for {expr}.
7016 static int
7017 get_dict_tv(arg, rettv, evaluate)
7018 char_u **arg;
7019 typval_T *rettv;
7020 int evaluate;
7022 dict_T *d = NULL;
7023 typval_T tvkey;
7024 typval_T tv;
7025 char_u *key = NULL;
7026 dictitem_T *item;
7027 char_u *start = skipwhite(*arg + 1);
7028 char_u buf[NUMBUFLEN];
7031 * First check if it's not a curly-braces thing: {expr}.
7032 * Must do this without evaluating, otherwise a function may be called
7033 * twice. Unfortunately this means we need to call eval1() twice for the
7034 * first item.
7035 * But {} is an empty Dictionary.
7037 if (*start != '}')
7039 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
7040 return FAIL;
7041 if (*start == '}')
7042 return NOTDONE;
7045 if (evaluate)
7047 d = dict_alloc();
7048 if (d == NULL)
7049 return FAIL;
7051 tvkey.v_type = VAR_UNKNOWN;
7052 tv.v_type = VAR_UNKNOWN;
7054 *arg = skipwhite(*arg + 1);
7055 while (**arg != '}' && **arg != NUL)
7057 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
7058 goto failret;
7059 if (**arg != ':')
7061 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
7062 clear_tv(&tvkey);
7063 goto failret;
7065 if (evaluate)
7067 key = get_tv_string_buf_chk(&tvkey, buf);
7068 if (key == NULL || *key == NUL)
7070 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
7071 if (key != NULL)
7072 EMSG(_(e_emptykey));
7073 clear_tv(&tvkey);
7074 goto failret;
7078 *arg = skipwhite(*arg + 1);
7079 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
7081 if (evaluate)
7082 clear_tv(&tvkey);
7083 goto failret;
7085 if (evaluate)
7087 item = dict_find(d, key, -1);
7088 if (item != NULL)
7090 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
7091 clear_tv(&tvkey);
7092 clear_tv(&tv);
7093 goto failret;
7095 item = dictitem_alloc(key);
7096 clear_tv(&tvkey);
7097 if (item != NULL)
7099 item->di_tv = tv;
7100 item->di_tv.v_lock = 0;
7101 if (dict_add(d, item) == FAIL)
7102 dictitem_free(item);
7106 if (**arg == '}')
7107 break;
7108 if (**arg != ',')
7110 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
7111 goto failret;
7113 *arg = skipwhite(*arg + 1);
7116 if (**arg != '}')
7118 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
7119 failret:
7120 if (evaluate)
7121 dict_free(d, TRUE);
7122 return FAIL;
7125 *arg = skipwhite(*arg + 1);
7126 if (evaluate)
7128 rettv->v_type = VAR_DICT;
7129 rettv->vval.v_dict = d;
7130 ++d->dv_refcount;
7133 return OK;
7137 * Return a string with the string representation of a variable.
7138 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7139 * "numbuf" is used for a number.
7140 * Does not put quotes around strings, as ":echo" displays values.
7141 * When "copyID" is not NULL replace recursive lists and dicts with "...".
7142 * May return NULL.
7144 static char_u *
7145 echo_string(tv, tofree, numbuf, copyID)
7146 typval_T *tv;
7147 char_u **tofree;
7148 char_u *numbuf;
7149 int copyID;
7151 static int recurse = 0;
7152 char_u *r = NULL;
7154 if (recurse >= DICT_MAXNEST)
7156 EMSG(_("E724: variable nested too deep for displaying"));
7157 *tofree = NULL;
7158 return NULL;
7160 ++recurse;
7162 switch (tv->v_type)
7164 case VAR_FUNC:
7165 *tofree = NULL;
7166 r = tv->vval.v_string;
7167 break;
7169 case VAR_LIST:
7170 if (tv->vval.v_list == NULL)
7172 *tofree = NULL;
7173 r = NULL;
7175 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
7177 *tofree = NULL;
7178 r = (char_u *)"[...]";
7180 else
7182 tv->vval.v_list->lv_copyID = copyID;
7183 *tofree = list2string(tv, copyID);
7184 r = *tofree;
7186 break;
7188 case VAR_DICT:
7189 if (tv->vval.v_dict == NULL)
7191 *tofree = NULL;
7192 r = NULL;
7194 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
7196 *tofree = NULL;
7197 r = (char_u *)"{...}";
7199 else
7201 tv->vval.v_dict->dv_copyID = copyID;
7202 *tofree = dict2string(tv, copyID);
7203 r = *tofree;
7205 break;
7207 case VAR_STRING:
7208 case VAR_NUMBER:
7209 *tofree = NULL;
7210 r = get_tv_string_buf(tv, numbuf);
7211 break;
7213 #ifdef FEAT_FLOAT
7214 case VAR_FLOAT:
7215 *tofree = NULL;
7216 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
7217 r = numbuf;
7218 break;
7219 #endif
7221 default:
7222 EMSG2(_(e_intern2), "echo_string()");
7223 *tofree = NULL;
7226 --recurse;
7227 return r;
7231 * Return a string with the string representation of a variable.
7232 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7233 * "numbuf" is used for a number.
7234 * Puts quotes around strings, so that they can be parsed back by eval().
7235 * May return NULL.
7237 static char_u *
7238 tv2string(tv, tofree, numbuf, copyID)
7239 typval_T *tv;
7240 char_u **tofree;
7241 char_u *numbuf;
7242 int copyID;
7244 switch (tv->v_type)
7246 case VAR_FUNC:
7247 *tofree = string_quote(tv->vval.v_string, TRUE);
7248 return *tofree;
7249 case VAR_STRING:
7250 *tofree = string_quote(tv->vval.v_string, FALSE);
7251 return *tofree;
7252 #ifdef FEAT_FLOAT
7253 case VAR_FLOAT:
7254 *tofree = NULL;
7255 vim_snprintf((char *)numbuf, NUMBUFLEN - 1, "%g", tv->vval.v_float);
7256 return numbuf;
7257 #endif
7258 case VAR_NUMBER:
7259 case VAR_LIST:
7260 case VAR_DICT:
7261 break;
7262 default:
7263 EMSG2(_(e_intern2), "tv2string()");
7265 return echo_string(tv, tofree, numbuf, copyID);
7269 * Return string "str" in ' quotes, doubling ' characters.
7270 * If "str" is NULL an empty string is assumed.
7271 * If "function" is TRUE make it function('string').
7273 static char_u *
7274 string_quote(str, function)
7275 char_u *str;
7276 int function;
7278 unsigned len;
7279 char_u *p, *r, *s;
7281 len = (function ? 13 : 3);
7282 if (str != NULL)
7284 len += (unsigned)STRLEN(str);
7285 for (p = str; *p != NUL; mb_ptr_adv(p))
7286 if (*p == '\'')
7287 ++len;
7289 s = r = alloc(len);
7290 if (r != NULL)
7292 if (function)
7294 STRCPY(r, "function('");
7295 r += 10;
7297 else
7298 *r++ = '\'';
7299 if (str != NULL)
7300 for (p = str; *p != NUL; )
7302 if (*p == '\'')
7303 *r++ = '\'';
7304 MB_COPY_CHAR(p, r);
7306 *r++ = '\'';
7307 if (function)
7308 *r++ = ')';
7309 *r++ = NUL;
7311 return s;
7314 #ifdef FEAT_FLOAT
7316 * Convert the string "text" to a floating point number.
7317 * This uses strtod(). setlocale(LC_NUMERIC, "C") has been used to make sure
7318 * this always uses a decimal point.
7319 * Returns the length of the text that was consumed.
7321 static int
7322 string2float(text, value)
7323 char_u *text;
7324 float_T *value; /* result stored here */
7326 char *s = (char *)text;
7327 float_T f;
7329 f = strtod(s, &s);
7330 *value = f;
7331 return (int)((char_u *)s - text);
7333 #endif
7336 * Get the value of an environment variable.
7337 * "arg" is pointing to the '$'. It is advanced to after the name.
7338 * If the environment variable was not set, silently assume it is empty.
7339 * Always return OK.
7341 static int
7342 get_env_tv(arg, rettv, evaluate)
7343 char_u **arg;
7344 typval_T *rettv;
7345 int evaluate;
7347 char_u *string = NULL;
7348 int len;
7349 int cc;
7350 char_u *name;
7351 int mustfree = FALSE;
7353 ++*arg;
7354 name = *arg;
7355 len = get_env_len(arg);
7356 if (evaluate)
7358 if (len != 0)
7360 cc = name[len];
7361 name[len] = NUL;
7362 /* first try vim_getenv(), fast for normal environment vars */
7363 string = vim_getenv(name, &mustfree);
7364 if (string != NULL && *string != NUL)
7366 if (!mustfree)
7367 string = vim_strsave(string);
7369 else
7371 if (mustfree)
7372 vim_free(string);
7374 /* next try expanding things like $VIM and ${HOME} */
7375 string = expand_env_save(name - 1);
7376 if (string != NULL && *string == '$')
7378 vim_free(string);
7379 string = NULL;
7382 name[len] = cc;
7384 rettv->v_type = VAR_STRING;
7385 rettv->vval.v_string = string;
7388 return OK;
7392 * Array with names and number of arguments of all internal functions
7393 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7395 static struct fst
7397 char *f_name; /* function name */
7398 char f_min_argc; /* minimal number of arguments */
7399 char f_max_argc; /* maximal number of arguments */
7400 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7401 /* implementation of function */
7402 } functions[] =
7404 #ifdef FEAT_FLOAT
7405 {"abs", 1, 1, f_abs},
7406 #endif
7407 {"add", 2, 2, f_add},
7408 {"append", 2, 2, f_append},
7409 {"argc", 0, 0, f_argc},
7410 {"argidx", 0, 0, f_argidx},
7411 {"argv", 0, 1, f_argv},
7412 #ifdef FEAT_FLOAT
7413 {"atan", 1, 1, f_atan},
7414 #endif
7415 {"browse", 4, 4, f_browse},
7416 {"browsedir", 2, 2, f_browsedir},
7417 {"bufexists", 1, 1, f_bufexists},
7418 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7419 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7420 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7421 {"buflisted", 1, 1, f_buflisted},
7422 {"bufloaded", 1, 1, f_bufloaded},
7423 {"bufname", 1, 1, f_bufname},
7424 {"bufnr", 1, 2, f_bufnr},
7425 {"bufwinnr", 1, 1, f_bufwinnr},
7426 {"byte2line", 1, 1, f_byte2line},
7427 {"byteidx", 2, 2, f_byteidx},
7428 {"call", 2, 3, f_call},
7429 #ifdef FEAT_FLOAT
7430 {"ceil", 1, 1, f_ceil},
7431 #endif
7432 {"changenr", 0, 0, f_changenr},
7433 {"char2nr", 1, 1, f_char2nr},
7434 {"cindent", 1, 1, f_cindent},
7435 {"clearmatches", 0, 0, f_clearmatches},
7436 {"col", 1, 1, f_col},
7437 #if defined(FEAT_INS_EXPAND)
7438 {"complete", 2, 2, f_complete},
7439 {"complete_add", 1, 1, f_complete_add},
7440 {"complete_check", 0, 0, f_complete_check},
7441 #endif
7442 {"confirm", 1, 4, f_confirm},
7443 {"copy", 1, 1, f_copy},
7444 #ifdef FEAT_FLOAT
7445 {"cos", 1, 1, f_cos},
7446 #endif
7447 {"count", 2, 4, f_count},
7448 {"cscope_connection",0,3, f_cscope_connection},
7449 {"cursor", 1, 3, f_cursor},
7450 {"deepcopy", 1, 2, f_deepcopy},
7451 {"delete", 1, 1, f_delete},
7452 {"did_filetype", 0, 0, f_did_filetype},
7453 {"diff_filler", 1, 1, f_diff_filler},
7454 {"diff_hlID", 2, 2, f_diff_hlID},
7455 {"empty", 1, 1, f_empty},
7456 {"escape", 2, 2, f_escape},
7457 {"eval", 1, 1, f_eval},
7458 {"eventhandler", 0, 0, f_eventhandler},
7459 {"executable", 1, 1, f_executable},
7460 {"exists", 1, 1, f_exists},
7461 {"expand", 1, 2, f_expand},
7462 {"extend", 2, 3, f_extend},
7463 {"feedkeys", 1, 2, f_feedkeys},
7464 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7465 {"filereadable", 1, 1, f_filereadable},
7466 {"filewritable", 1, 1, f_filewritable},
7467 {"filter", 2, 2, f_filter},
7468 {"finddir", 1, 3, f_finddir},
7469 {"findfile", 1, 3, f_findfile},
7470 #ifdef FEAT_FLOAT
7471 {"float2nr", 1, 1, f_float2nr},
7472 {"floor", 1, 1, f_floor},
7473 #endif
7474 {"fnameescape", 1, 1, f_fnameescape},
7475 {"fnamemodify", 2, 2, f_fnamemodify},
7476 {"foldclosed", 1, 1, f_foldclosed},
7477 {"foldclosedend", 1, 1, f_foldclosedend},
7478 {"foldlevel", 1, 1, f_foldlevel},
7479 {"foldtext", 0, 0, f_foldtext},
7480 {"foldtextresult", 1, 1, f_foldtextresult},
7481 {"foreground", 0, 0, f_foreground},
7482 {"function", 1, 1, f_function},
7483 {"garbagecollect", 0, 1, f_garbagecollect},
7484 {"get", 2, 3, f_get},
7485 {"getbufline", 2, 3, f_getbufline},
7486 {"getbufvar", 2, 2, f_getbufvar},
7487 {"getchar", 0, 1, f_getchar},
7488 {"getcharmod", 0, 0, f_getcharmod},
7489 {"getcmdline", 0, 0, f_getcmdline},
7490 {"getcmdpos", 0, 0, f_getcmdpos},
7491 {"getcmdtype", 0, 0, f_getcmdtype},
7492 {"getcwd", 0, 0, f_getcwd},
7493 {"getfontname", 0, 1, f_getfontname},
7494 {"getfperm", 1, 1, f_getfperm},
7495 {"getfsize", 1, 1, f_getfsize},
7496 {"getftime", 1, 1, f_getftime},
7497 {"getftype", 1, 1, f_getftype},
7498 {"getline", 1, 2, f_getline},
7499 {"getloclist", 1, 1, f_getqflist},
7500 {"getmatches", 0, 0, f_getmatches},
7501 {"getpid", 0, 0, f_getpid},
7502 {"getpos", 1, 1, f_getpos},
7503 {"getqflist", 0, 0, f_getqflist},
7504 {"getreg", 0, 2, f_getreg},
7505 {"getregtype", 0, 1, f_getregtype},
7506 {"gettabwinvar", 3, 3, f_gettabwinvar},
7507 {"getwinposx", 0, 0, f_getwinposx},
7508 {"getwinposy", 0, 0, f_getwinposy},
7509 {"getwinvar", 2, 2, f_getwinvar},
7510 {"glob", 1, 1, f_glob},
7511 {"globpath", 2, 2, f_globpath},
7512 {"has", 1, 1, f_has},
7513 {"has_key", 2, 2, f_has_key},
7514 {"haslocaldir", 0, 0, f_haslocaldir},
7515 {"hasmapto", 1, 3, f_hasmapto},
7516 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7517 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7518 {"histadd", 2, 2, f_histadd},
7519 {"histdel", 1, 2, f_histdel},
7520 {"histget", 1, 2, f_histget},
7521 {"histnr", 1, 1, f_histnr},
7522 {"hlID", 1, 1, f_hlID},
7523 {"hlexists", 1, 1, f_hlexists},
7524 {"hostname", 0, 0, f_hostname},
7525 {"iconv", 3, 3, f_iconv},
7526 {"indent", 1, 1, f_indent},
7527 {"index", 2, 4, f_index},
7528 {"input", 1, 3, f_input},
7529 {"inputdialog", 1, 3, f_inputdialog},
7530 {"inputlist", 1, 1, f_inputlist},
7531 {"inputrestore", 0, 0, f_inputrestore},
7532 {"inputsave", 0, 0, f_inputsave},
7533 {"inputsecret", 1, 2, f_inputsecret},
7534 {"insert", 2, 3, f_insert},
7535 {"isdirectory", 1, 1, f_isdirectory},
7536 {"islocked", 1, 1, f_islocked},
7537 {"items", 1, 1, f_items},
7538 {"join", 1, 2, f_join},
7539 {"keys", 1, 1, f_keys},
7540 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7541 {"len", 1, 1, f_len},
7542 {"libcall", 3, 3, f_libcall},
7543 {"libcallnr", 3, 3, f_libcallnr},
7544 {"line", 1, 1, f_line},
7545 {"line2byte", 1, 1, f_line2byte},
7546 {"lispindent", 1, 1, f_lispindent},
7547 {"localtime", 0, 0, f_localtime},
7548 #ifdef FEAT_FLOAT
7549 {"log10", 1, 1, f_log10},
7550 #endif
7551 {"map", 2, 2, f_map},
7552 {"maparg", 1, 3, f_maparg},
7553 {"mapcheck", 1, 3, f_mapcheck},
7554 {"match", 2, 4, f_match},
7555 {"matchadd", 2, 4, f_matchadd},
7556 {"matcharg", 1, 1, f_matcharg},
7557 {"matchdelete", 1, 1, f_matchdelete},
7558 {"matchend", 2, 4, f_matchend},
7559 {"matchlist", 2, 4, f_matchlist},
7560 {"matchstr", 2, 4, f_matchstr},
7561 {"max", 1, 1, f_max},
7562 {"min", 1, 1, f_min},
7563 #ifdef vim_mkdir
7564 {"mkdir", 1, 3, f_mkdir},
7565 #endif
7566 {"mode", 0, 1, f_mode},
7567 {"nextnonblank", 1, 1, f_nextnonblank},
7568 {"nr2char", 1, 1, f_nr2char},
7569 {"pathshorten", 1, 1, f_pathshorten},
7570 #ifdef FEAT_FLOAT
7571 {"pow", 2, 2, f_pow},
7572 #endif
7573 {"prevnonblank", 1, 1, f_prevnonblank},
7574 {"printf", 2, 19, f_printf},
7575 {"pumvisible", 0, 0, f_pumvisible},
7576 {"range", 1, 3, f_range},
7577 {"readfile", 1, 3, f_readfile},
7578 {"reltime", 0, 2, f_reltime},
7579 {"reltimestr", 1, 1, f_reltimestr},
7580 {"remote_expr", 2, 3, f_remote_expr},
7581 {"remote_foreground", 1, 1, f_remote_foreground},
7582 {"remote_peek", 1, 2, f_remote_peek},
7583 {"remote_read", 1, 1, f_remote_read},
7584 {"remote_send", 2, 3, f_remote_send},
7585 {"remove", 2, 3, f_remove},
7586 {"rename", 2, 2, f_rename},
7587 {"repeat", 2, 2, f_repeat},
7588 {"resolve", 1, 1, f_resolve},
7589 {"reverse", 1, 1, f_reverse},
7590 #ifdef FEAT_FLOAT
7591 {"round", 1, 1, f_round},
7592 #endif
7593 {"search", 1, 4, f_search},
7594 {"searchdecl", 1, 3, f_searchdecl},
7595 {"searchpair", 3, 7, f_searchpair},
7596 {"searchpairpos", 3, 7, f_searchpairpos},
7597 {"searchpos", 1, 4, f_searchpos},
7598 {"server2client", 2, 2, f_server2client},
7599 {"serverlist", 0, 0, f_serverlist},
7600 {"setbufvar", 3, 3, f_setbufvar},
7601 {"setcmdpos", 1, 1, f_setcmdpos},
7602 {"setline", 2, 2, f_setline},
7603 {"setloclist", 2, 3, f_setloclist},
7604 {"setmatches", 1, 1, f_setmatches},
7605 {"setpos", 2, 2, f_setpos},
7606 {"setqflist", 1, 2, f_setqflist},
7607 {"setreg", 2, 3, f_setreg},
7608 {"settabwinvar", 4, 4, f_settabwinvar},
7609 {"setwinvar", 3, 3, f_setwinvar},
7610 {"shellescape", 1, 1, f_shellescape},
7611 {"simplify", 1, 1, f_simplify},
7612 #ifdef FEAT_FLOAT
7613 {"sin", 1, 1, f_sin},
7614 #endif
7615 {"sort", 1, 2, f_sort},
7616 {"soundfold", 1, 1, f_soundfold},
7617 {"spellbadword", 0, 1, f_spellbadword},
7618 {"spellsuggest", 1, 3, f_spellsuggest},
7619 {"split", 1, 3, f_split},
7620 #ifdef FEAT_FLOAT
7621 {"sqrt", 1, 1, f_sqrt},
7622 {"str2float", 1, 1, f_str2float},
7623 #endif
7624 {"str2nr", 1, 2, f_str2nr},
7625 #ifdef HAVE_STRFTIME
7626 {"strftime", 1, 2, f_strftime},
7627 #endif
7628 {"stridx", 2, 3, f_stridx},
7629 {"string", 1, 1, f_string},
7630 {"strlen", 1, 1, f_strlen},
7631 {"strpart", 2, 3, f_strpart},
7632 {"strridx", 2, 3, f_strridx},
7633 {"strtrans", 1, 1, f_strtrans},
7634 {"submatch", 1, 1, f_submatch},
7635 {"substitute", 4, 4, f_substitute},
7636 {"synID", 3, 3, f_synID},
7637 {"synIDattr", 2, 3, f_synIDattr},
7638 {"synIDtrans", 1, 1, f_synIDtrans},
7639 {"synstack", 2, 2, f_synstack},
7640 {"system", 1, 2, f_system},
7641 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7642 {"tabpagenr", 0, 1, f_tabpagenr},
7643 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7644 {"tagfiles", 0, 0, f_tagfiles},
7645 {"taglist", 1, 1, f_taglist},
7646 {"tempname", 0, 0, f_tempname},
7647 {"test", 1, 1, f_test},
7648 {"tolower", 1, 1, f_tolower},
7649 {"toupper", 1, 1, f_toupper},
7650 {"tr", 3, 3, f_tr},
7651 #ifdef FEAT_FLOAT
7652 {"trunc", 1, 1, f_trunc},
7653 #endif
7654 {"type", 1, 1, f_type},
7655 {"values", 1, 1, f_values},
7656 {"virtcol", 1, 1, f_virtcol},
7657 {"visualmode", 0, 1, f_visualmode},
7658 {"winbufnr", 1, 1, f_winbufnr},
7659 {"wincol", 0, 0, f_wincol},
7660 {"winheight", 1, 1, f_winheight},
7661 {"winline", 0, 0, f_winline},
7662 {"winnr", 0, 1, f_winnr},
7663 {"winrestcmd", 0, 0, f_winrestcmd},
7664 {"winrestview", 1, 1, f_winrestview},
7665 {"winsaveview", 0, 0, f_winsaveview},
7666 {"winwidth", 1, 1, f_winwidth},
7667 {"writefile", 2, 3, f_writefile},
7670 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7673 * Function given to ExpandGeneric() to obtain the list of internal
7674 * or user defined function names.
7676 char_u *
7677 get_function_name(xp, idx)
7678 expand_T *xp;
7679 int idx;
7681 static int intidx = -1;
7682 char_u *name;
7684 if (idx == 0)
7685 intidx = -1;
7686 if (intidx < 0)
7688 name = get_user_func_name(xp, idx);
7689 if (name != NULL)
7690 return name;
7692 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7694 STRCPY(IObuff, functions[intidx].f_name);
7695 STRCAT(IObuff, "(");
7696 if (functions[intidx].f_max_argc == 0)
7697 STRCAT(IObuff, ")");
7698 return IObuff;
7701 return NULL;
7705 * Function given to ExpandGeneric() to obtain the list of internal or
7706 * user defined variable or function names.
7708 /*ARGSUSED*/
7709 char_u *
7710 get_expr_name(xp, idx)
7711 expand_T *xp;
7712 int idx;
7714 static int intidx = -1;
7715 char_u *name;
7717 if (idx == 0)
7718 intidx = -1;
7719 if (intidx < 0)
7721 name = get_function_name(xp, idx);
7722 if (name != NULL)
7723 return name;
7725 return get_user_var_name(xp, ++intidx);
7728 #endif /* FEAT_CMDL_COMPL */
7731 * Find internal function in table above.
7732 * Return index, or -1 if not found
7734 static int
7735 find_internal_func(name)
7736 char_u *name; /* name of the function */
7738 int first = 0;
7739 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7740 int cmp;
7741 int x;
7744 * Find the function name in the table. Binary search.
7746 while (first <= last)
7748 x = first + ((unsigned)(last - first) >> 1);
7749 cmp = STRCMP(name, functions[x].f_name);
7750 if (cmp < 0)
7751 last = x - 1;
7752 else if (cmp > 0)
7753 first = x + 1;
7754 else
7755 return x;
7757 return -1;
7761 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7762 * name it contains, otherwise return "name".
7764 static char_u *
7765 deref_func_name(name, lenp)
7766 char_u *name;
7767 int *lenp;
7769 dictitem_T *v;
7770 int cc;
7772 cc = name[*lenp];
7773 name[*lenp] = NUL;
7774 v = find_var(name, NULL);
7775 name[*lenp] = cc;
7776 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7778 if (v->di_tv.vval.v_string == NULL)
7780 *lenp = 0;
7781 return (char_u *)""; /* just in case */
7783 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7784 return v->di_tv.vval.v_string;
7787 return name;
7791 * Allocate a variable for the result of a function.
7792 * Return OK or FAIL.
7794 static int
7795 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7796 evaluate, selfdict)
7797 char_u *name; /* name of the function */
7798 int len; /* length of "name" */
7799 typval_T *rettv;
7800 char_u **arg; /* argument, pointing to the '(' */
7801 linenr_T firstline; /* first line of range */
7802 linenr_T lastline; /* last line of range */
7803 int *doesrange; /* return: function handled range */
7804 int evaluate;
7805 dict_T *selfdict; /* Dictionary for "self" */
7807 char_u *argp;
7808 int ret = OK;
7809 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7810 int argcount = 0; /* number of arguments found */
7813 * Get the arguments.
7815 argp = *arg;
7816 while (argcount < MAX_FUNC_ARGS)
7818 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7819 if (*argp == ')' || *argp == ',' || *argp == NUL)
7820 break;
7821 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7823 ret = FAIL;
7824 break;
7826 ++argcount;
7827 if (*argp != ',')
7828 break;
7830 if (*argp == ')')
7831 ++argp;
7832 else
7833 ret = FAIL;
7835 if (ret == OK)
7836 ret = call_func(name, len, rettv, argcount, argvars,
7837 firstline, lastline, doesrange, evaluate, selfdict);
7838 else if (!aborting())
7840 if (argcount == MAX_FUNC_ARGS)
7841 emsg_funcname("E740: Too many arguments for function %s", name);
7842 else
7843 emsg_funcname("E116: Invalid arguments for function %s", name);
7846 while (--argcount >= 0)
7847 clear_tv(&argvars[argcount]);
7849 *arg = skipwhite(argp);
7850 return ret;
7855 * Call a function with its resolved parameters
7856 * Return OK when the function can't be called, FAIL otherwise.
7857 * Also returns OK when an error was encountered while executing the function.
7859 static int
7860 call_func(name, len, rettv, argcount, argvars, firstline, lastline,
7861 doesrange, evaluate, selfdict)
7862 char_u *name; /* name of the function */
7863 int len; /* length of "name" */
7864 typval_T *rettv; /* return value goes here */
7865 int argcount; /* number of "argvars" */
7866 typval_T *argvars; /* vars for arguments, must have "argcount"
7867 PLUS ONE elements! */
7868 linenr_T firstline; /* first line of range */
7869 linenr_T lastline; /* last line of range */
7870 int *doesrange; /* return: function handled range */
7871 int evaluate;
7872 dict_T *selfdict; /* Dictionary for "self" */
7874 int ret = FAIL;
7875 #define ERROR_UNKNOWN 0
7876 #define ERROR_TOOMANY 1
7877 #define ERROR_TOOFEW 2
7878 #define ERROR_SCRIPT 3
7879 #define ERROR_DICT 4
7880 #define ERROR_NONE 5
7881 #define ERROR_OTHER 6
7882 int error = ERROR_NONE;
7883 int i;
7884 int llen;
7885 ufunc_T *fp;
7886 int cc;
7887 #define FLEN_FIXED 40
7888 char_u fname_buf[FLEN_FIXED + 1];
7889 char_u *fname;
7892 * In a script change <SID>name() and s:name() to K_SNR 123_name().
7893 * Change <SNR>123_name() to K_SNR 123_name().
7894 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
7896 cc = name[len];
7897 name[len] = NUL;
7898 llen = eval_fname_script(name);
7899 if (llen > 0)
7901 fname_buf[0] = K_SPECIAL;
7902 fname_buf[1] = KS_EXTRA;
7903 fname_buf[2] = (int)KE_SNR;
7904 i = 3;
7905 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
7907 if (current_SID <= 0)
7908 error = ERROR_SCRIPT;
7909 else
7911 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
7912 i = (int)STRLEN(fname_buf);
7915 if (i + STRLEN(name + llen) < FLEN_FIXED)
7917 STRCPY(fname_buf + i, name + llen);
7918 fname = fname_buf;
7920 else
7922 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
7923 if (fname == NULL)
7924 error = ERROR_OTHER;
7925 else
7927 mch_memmove(fname, fname_buf, (size_t)i);
7928 STRCPY(fname + i, name + llen);
7932 else
7933 fname = name;
7935 *doesrange = FALSE;
7938 /* execute the function if no errors detected and executing */
7939 if (evaluate && error == ERROR_NONE)
7941 rettv->v_type = VAR_NUMBER; /* default is number rettv */
7942 error = ERROR_UNKNOWN;
7944 if (!builtin_function(fname))
7947 * User defined function.
7949 fp = find_func(fname);
7951 #ifdef FEAT_AUTOCMD
7952 /* Trigger FuncUndefined event, may load the function. */
7953 if (fp == NULL
7954 && apply_autocmds(EVENT_FUNCUNDEFINED,
7955 fname, fname, TRUE, NULL)
7956 && !aborting())
7958 /* executed an autocommand, search for the function again */
7959 fp = find_func(fname);
7961 #endif
7962 /* Try loading a package. */
7963 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
7965 /* loaded a package, search for the function again */
7966 fp = find_func(fname);
7969 if (fp != NULL)
7971 if (fp->uf_flags & FC_RANGE)
7972 *doesrange = TRUE;
7973 if (argcount < fp->uf_args.ga_len)
7974 error = ERROR_TOOFEW;
7975 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
7976 error = ERROR_TOOMANY;
7977 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
7978 error = ERROR_DICT;
7979 else
7982 * Call the user function.
7983 * Save and restore search patterns, script variables and
7984 * redo buffer.
7986 save_search_patterns();
7987 saveRedobuff();
7988 ++fp->uf_calls;
7989 call_user_func(fp, argcount, argvars, rettv,
7990 firstline, lastline,
7991 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
7992 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
7993 && fp->uf_refcount <= 0)
7994 /* Function was unreferenced while being used, free it
7995 * now. */
7996 func_free(fp);
7997 restoreRedobuff();
7998 restore_search_patterns();
7999 error = ERROR_NONE;
8003 else
8006 * Find the function name in the table, call its implementation.
8008 i = find_internal_func(fname);
8009 if (i >= 0)
8011 if (argcount < functions[i].f_min_argc)
8012 error = ERROR_TOOFEW;
8013 else if (argcount > functions[i].f_max_argc)
8014 error = ERROR_TOOMANY;
8015 else
8017 argvars[argcount].v_type = VAR_UNKNOWN;
8018 functions[i].f_func(argvars, rettv);
8019 error = ERROR_NONE;
8024 * The function call (or "FuncUndefined" autocommand sequence) might
8025 * have been aborted by an error, an interrupt, or an explicitly thrown
8026 * exception that has not been caught so far. This situation can be
8027 * tested for by calling aborting(). For an error in an internal
8028 * function or for the "E132" error in call_user_func(), however, the
8029 * throw point at which the "force_abort" flag (temporarily reset by
8030 * emsg()) is normally updated has not been reached yet. We need to
8031 * update that flag first to make aborting() reliable.
8033 update_force_abort();
8035 if (error == ERROR_NONE)
8036 ret = OK;
8039 * Report an error unless the argument evaluation or function call has been
8040 * cancelled due to an aborting error, an interrupt, or an exception.
8042 if (!aborting())
8044 switch (error)
8046 case ERROR_UNKNOWN:
8047 emsg_funcname(N_("E117: Unknown function: %s"), name);
8048 break;
8049 case ERROR_TOOMANY:
8050 emsg_funcname(e_toomanyarg, name);
8051 break;
8052 case ERROR_TOOFEW:
8053 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
8054 name);
8055 break;
8056 case ERROR_SCRIPT:
8057 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
8058 name);
8059 break;
8060 case ERROR_DICT:
8061 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
8062 name);
8063 break;
8067 name[len] = cc;
8068 if (fname != name && fname != fname_buf)
8069 vim_free(fname);
8071 return ret;
8075 * Give an error message with a function name. Handle <SNR> things.
8077 static void
8078 emsg_funcname(ermsg, name)
8079 char *ermsg;
8080 char_u *name;
8082 char_u *p;
8084 if (*name == K_SPECIAL)
8085 p = concat_str((char_u *)"<SNR>", name + 3);
8086 else
8087 p = name;
8088 EMSG2(_(ermsg), p);
8089 if (p != name)
8090 vim_free(p);
8093 /*********************************************
8094 * Implementation of the built-in functions
8097 #ifdef FEAT_FLOAT
8099 * "abs(expr)" function
8101 static void
8102 f_abs(argvars, rettv)
8103 typval_T *argvars;
8104 typval_T *rettv;
8106 if (argvars[0].v_type == VAR_FLOAT)
8108 rettv->v_type = VAR_FLOAT;
8109 rettv->vval.v_float = fabs(argvars[0].vval.v_float);
8111 else
8113 varnumber_T n;
8114 int error = FALSE;
8116 n = get_tv_number_chk(&argvars[0], &error);
8117 if (error)
8118 rettv->vval.v_number = -1;
8119 else if (n > 0)
8120 rettv->vval.v_number = n;
8121 else
8122 rettv->vval.v_number = -n;
8125 #endif
8128 * "add(list, item)" function
8130 static void
8131 f_add(argvars, rettv)
8132 typval_T *argvars;
8133 typval_T *rettv;
8135 list_T *l;
8137 rettv->vval.v_number = 1; /* Default: Failed */
8138 if (argvars[0].v_type == VAR_LIST)
8140 if ((l = argvars[0].vval.v_list) != NULL
8141 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
8142 && list_append_tv(l, &argvars[1]) == OK)
8143 copy_tv(&argvars[0], rettv);
8145 else
8146 EMSG(_(e_listreq));
8150 * "append(lnum, string/list)" function
8152 static void
8153 f_append(argvars, rettv)
8154 typval_T *argvars;
8155 typval_T *rettv;
8157 long lnum;
8158 char_u *line;
8159 list_T *l = NULL;
8160 listitem_T *li = NULL;
8161 typval_T *tv;
8162 long added = 0;
8164 lnum = get_tv_lnum(argvars);
8165 if (lnum >= 0
8166 && lnum <= curbuf->b_ml.ml_line_count
8167 && u_save(lnum, lnum + 1) == OK)
8169 if (argvars[1].v_type == VAR_LIST)
8171 l = argvars[1].vval.v_list;
8172 if (l == NULL)
8173 return;
8174 li = l->lv_first;
8176 rettv->vval.v_number = 0; /* Default: Success */
8177 for (;;)
8179 if (l == NULL)
8180 tv = &argvars[1]; /* append a string */
8181 else if (li == NULL)
8182 break; /* end of list */
8183 else
8184 tv = &li->li_tv; /* append item from list */
8185 line = get_tv_string_chk(tv);
8186 if (line == NULL) /* type error */
8188 rettv->vval.v_number = 1; /* Failed */
8189 break;
8191 ml_append(lnum + added, line, (colnr_T)0, FALSE);
8192 ++added;
8193 if (l == NULL)
8194 break;
8195 li = li->li_next;
8198 appended_lines_mark(lnum, added);
8199 if (curwin->w_cursor.lnum > lnum)
8200 curwin->w_cursor.lnum += added;
8202 else
8203 rettv->vval.v_number = 1; /* Failed */
8207 * "argc()" function
8209 /* ARGSUSED */
8210 static void
8211 f_argc(argvars, rettv)
8212 typval_T *argvars;
8213 typval_T *rettv;
8215 rettv->vval.v_number = ARGCOUNT;
8219 * "argidx()" function
8221 /* ARGSUSED */
8222 static void
8223 f_argidx(argvars, rettv)
8224 typval_T *argvars;
8225 typval_T *rettv;
8227 rettv->vval.v_number = curwin->w_arg_idx;
8231 * "argv(nr)" function
8233 static void
8234 f_argv(argvars, rettv)
8235 typval_T *argvars;
8236 typval_T *rettv;
8238 int idx;
8240 if (argvars[0].v_type != VAR_UNKNOWN)
8242 idx = get_tv_number_chk(&argvars[0], NULL);
8243 if (idx >= 0 && idx < ARGCOUNT)
8244 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
8245 else
8246 rettv->vval.v_string = NULL;
8247 rettv->v_type = VAR_STRING;
8249 else if (rettv_list_alloc(rettv) == OK)
8250 for (idx = 0; idx < ARGCOUNT; ++idx)
8251 list_append_string(rettv->vval.v_list,
8252 alist_name(&ARGLIST[idx]), -1);
8255 #ifdef FEAT_FLOAT
8256 static int get_float_arg __ARGS((typval_T *argvars, float_T *f));
8259 * Get the float value of "argvars[0]" into "f".
8260 * Returns FAIL when the argument is not a Number or Float.
8262 static int
8263 get_float_arg(argvars, f)
8264 typval_T *argvars;
8265 float_T *f;
8267 if (argvars[0].v_type == VAR_FLOAT)
8269 *f = argvars[0].vval.v_float;
8270 return OK;
8272 if (argvars[0].v_type == VAR_NUMBER)
8274 *f = (float_T)argvars[0].vval.v_number;
8275 return OK;
8277 EMSG(_("E808: Number or Float required"));
8278 return FAIL;
8282 * "atan()" function
8284 static void
8285 f_atan(argvars, rettv)
8286 typval_T *argvars;
8287 typval_T *rettv;
8289 float_T f;
8291 rettv->v_type = VAR_FLOAT;
8292 if (get_float_arg(argvars, &f) == OK)
8293 rettv->vval.v_float = atan(f);
8294 else
8295 rettv->vval.v_float = 0.0;
8297 #endif
8300 * "browse(save, title, initdir, default)" function
8302 /* ARGSUSED */
8303 static void
8304 f_browse(argvars, rettv)
8305 typval_T *argvars;
8306 typval_T *rettv;
8308 #ifdef FEAT_BROWSE
8309 int save;
8310 char_u *title;
8311 char_u *initdir;
8312 char_u *defname;
8313 char_u buf[NUMBUFLEN];
8314 char_u buf2[NUMBUFLEN];
8315 int error = FALSE;
8317 save = get_tv_number_chk(&argvars[0], &error);
8318 title = get_tv_string_chk(&argvars[1]);
8319 initdir = get_tv_string_buf_chk(&argvars[2], buf);
8320 defname = get_tv_string_buf_chk(&argvars[3], buf2);
8322 if (error || title == NULL || initdir == NULL || defname == NULL)
8323 rettv->vval.v_string = NULL;
8324 else
8325 rettv->vval.v_string =
8326 do_browse(save ? BROWSE_SAVE : 0,
8327 title, defname, NULL, initdir, NULL, curbuf);
8328 #else
8329 rettv->vval.v_string = NULL;
8330 #endif
8331 rettv->v_type = VAR_STRING;
8335 * "browsedir(title, initdir)" function
8337 /* ARGSUSED */
8338 static void
8339 f_browsedir(argvars, rettv)
8340 typval_T *argvars;
8341 typval_T *rettv;
8343 #ifdef FEAT_BROWSE
8344 char_u *title;
8345 char_u *initdir;
8346 char_u buf[NUMBUFLEN];
8348 title = get_tv_string_chk(&argvars[0]);
8349 initdir = get_tv_string_buf_chk(&argvars[1], buf);
8351 if (title == NULL || initdir == NULL)
8352 rettv->vval.v_string = NULL;
8353 else
8354 rettv->vval.v_string = do_browse(BROWSE_DIR,
8355 title, NULL, NULL, initdir, NULL, curbuf);
8356 #else
8357 rettv->vval.v_string = NULL;
8358 #endif
8359 rettv->v_type = VAR_STRING;
8362 static buf_T *find_buffer __ARGS((typval_T *avar));
8365 * Find a buffer by number or exact name.
8367 static buf_T *
8368 find_buffer(avar)
8369 typval_T *avar;
8371 buf_T *buf = NULL;
8373 if (avar->v_type == VAR_NUMBER)
8374 buf = buflist_findnr((int)avar->vval.v_number);
8375 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
8377 buf = buflist_findname_exp(avar->vval.v_string);
8378 if (buf == NULL)
8380 /* No full path name match, try a match with a URL or a "nofile"
8381 * buffer, these don't use the full path. */
8382 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8383 if (buf->b_fname != NULL
8384 && (path_with_url(buf->b_fname)
8385 #ifdef FEAT_QUICKFIX
8386 || bt_nofile(buf)
8387 #endif
8389 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
8390 break;
8393 return buf;
8397 * "bufexists(expr)" function
8399 static void
8400 f_bufexists(argvars, rettv)
8401 typval_T *argvars;
8402 typval_T *rettv;
8404 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
8408 * "buflisted(expr)" function
8410 static void
8411 f_buflisted(argvars, rettv)
8412 typval_T *argvars;
8413 typval_T *rettv;
8415 buf_T *buf;
8417 buf = find_buffer(&argvars[0]);
8418 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
8422 * "bufloaded(expr)" function
8424 static void
8425 f_bufloaded(argvars, rettv)
8426 typval_T *argvars;
8427 typval_T *rettv;
8429 buf_T *buf;
8431 buf = find_buffer(&argvars[0]);
8432 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
8435 static buf_T *get_buf_tv __ARGS((typval_T *tv));
8438 * Get buffer by number or pattern.
8440 static buf_T *
8441 get_buf_tv(tv)
8442 typval_T *tv;
8444 char_u *name = tv->vval.v_string;
8445 int save_magic;
8446 char_u *save_cpo;
8447 buf_T *buf;
8449 if (tv->v_type == VAR_NUMBER)
8450 return buflist_findnr((int)tv->vval.v_number);
8451 if (tv->v_type != VAR_STRING)
8452 return NULL;
8453 if (name == NULL || *name == NUL)
8454 return curbuf;
8455 if (name[0] == '$' && name[1] == NUL)
8456 return lastbuf;
8458 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
8459 save_magic = p_magic;
8460 p_magic = TRUE;
8461 save_cpo = p_cpo;
8462 p_cpo = (char_u *)"";
8464 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8465 TRUE, FALSE));
8467 p_magic = save_magic;
8468 p_cpo = save_cpo;
8470 /* If not found, try expanding the name, like done for bufexists(). */
8471 if (buf == NULL)
8472 buf = find_buffer(tv);
8474 return buf;
8478 * "bufname(expr)" function
8480 static void
8481 f_bufname(argvars, rettv)
8482 typval_T *argvars;
8483 typval_T *rettv;
8485 buf_T *buf;
8487 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8488 ++emsg_off;
8489 buf = get_buf_tv(&argvars[0]);
8490 rettv->v_type = VAR_STRING;
8491 if (buf != NULL && buf->b_fname != NULL)
8492 rettv->vval.v_string = vim_strsave(buf->b_fname);
8493 else
8494 rettv->vval.v_string = NULL;
8495 --emsg_off;
8499 * "bufnr(expr)" function
8501 static void
8502 f_bufnr(argvars, rettv)
8503 typval_T *argvars;
8504 typval_T *rettv;
8506 buf_T *buf;
8507 int error = FALSE;
8508 char_u *name;
8510 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8511 ++emsg_off;
8512 buf = get_buf_tv(&argvars[0]);
8513 --emsg_off;
8515 /* If the buffer isn't found and the second argument is not zero create a
8516 * new buffer. */
8517 if (buf == NULL
8518 && argvars[1].v_type != VAR_UNKNOWN
8519 && get_tv_number_chk(&argvars[1], &error) != 0
8520 && !error
8521 && (name = get_tv_string_chk(&argvars[0])) != NULL
8522 && !error)
8523 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8525 if (buf != NULL)
8526 rettv->vval.v_number = buf->b_fnum;
8527 else
8528 rettv->vval.v_number = -1;
8532 * "bufwinnr(nr)" function
8534 static void
8535 f_bufwinnr(argvars, rettv)
8536 typval_T *argvars;
8537 typval_T *rettv;
8539 #ifdef FEAT_WINDOWS
8540 win_T *wp;
8541 int winnr = 0;
8542 #endif
8543 buf_T *buf;
8545 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8546 ++emsg_off;
8547 buf = get_buf_tv(&argvars[0]);
8548 #ifdef FEAT_WINDOWS
8549 for (wp = firstwin; wp; wp = wp->w_next)
8551 ++winnr;
8552 if (wp->w_buffer == buf)
8553 break;
8555 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8556 #else
8557 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8558 #endif
8559 --emsg_off;
8563 * "byte2line(byte)" function
8565 /*ARGSUSED*/
8566 static void
8567 f_byte2line(argvars, rettv)
8568 typval_T *argvars;
8569 typval_T *rettv;
8571 #ifndef FEAT_BYTEOFF
8572 rettv->vval.v_number = -1;
8573 #else
8574 long boff = 0;
8576 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8577 if (boff < 0)
8578 rettv->vval.v_number = -1;
8579 else
8580 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8581 (linenr_T)0, &boff);
8582 #endif
8586 * "byteidx()" function
8588 /*ARGSUSED*/
8589 static void
8590 f_byteidx(argvars, rettv)
8591 typval_T *argvars;
8592 typval_T *rettv;
8594 #ifdef FEAT_MBYTE
8595 char_u *t;
8596 #endif
8597 char_u *str;
8598 long idx;
8600 str = get_tv_string_chk(&argvars[0]);
8601 idx = get_tv_number_chk(&argvars[1], NULL);
8602 rettv->vval.v_number = -1;
8603 if (str == NULL || idx < 0)
8604 return;
8606 #ifdef FEAT_MBYTE
8607 t = str;
8608 for ( ; idx > 0; idx--)
8610 if (*t == NUL) /* EOL reached */
8611 return;
8612 t += (*mb_ptr2len)(t);
8614 rettv->vval.v_number = (varnumber_T)(t - str);
8615 #else
8616 if ((size_t)idx <= STRLEN(str))
8617 rettv->vval.v_number = idx;
8618 #endif
8622 * "call(func, arglist)" function
8624 static void
8625 f_call(argvars, rettv)
8626 typval_T *argvars;
8627 typval_T *rettv;
8629 char_u *func;
8630 typval_T argv[MAX_FUNC_ARGS + 1];
8631 int argc = 0;
8632 listitem_T *item;
8633 int dummy;
8634 dict_T *selfdict = NULL;
8636 rettv->vval.v_number = 0;
8637 if (argvars[1].v_type != VAR_LIST)
8639 EMSG(_(e_listreq));
8640 return;
8642 if (argvars[1].vval.v_list == NULL)
8643 return;
8645 if (argvars[0].v_type == VAR_FUNC)
8646 func = argvars[0].vval.v_string;
8647 else
8648 func = get_tv_string(&argvars[0]);
8649 if (*func == NUL)
8650 return; /* type error or empty name */
8652 if (argvars[2].v_type != VAR_UNKNOWN)
8654 if (argvars[2].v_type != VAR_DICT)
8656 EMSG(_(e_dictreq));
8657 return;
8659 selfdict = argvars[2].vval.v_dict;
8662 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
8663 item = item->li_next)
8665 if (argc == MAX_FUNC_ARGS)
8667 EMSG(_("E699: Too many arguments"));
8668 break;
8670 /* Make a copy of each argument. This is needed to be able to set
8671 * v_lock to VAR_FIXED in the copy without changing the original list.
8673 copy_tv(&item->li_tv, &argv[argc++]);
8676 if (item == NULL)
8677 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
8678 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
8679 &dummy, TRUE, selfdict);
8681 /* Free the arguments. */
8682 while (argc > 0)
8683 clear_tv(&argv[--argc]);
8686 #ifdef FEAT_FLOAT
8688 * "ceil({float})" function
8690 static void
8691 f_ceil(argvars, rettv)
8692 typval_T *argvars;
8693 typval_T *rettv;
8695 float_T f;
8697 rettv->v_type = VAR_FLOAT;
8698 if (get_float_arg(argvars, &f) == OK)
8699 rettv->vval.v_float = ceil(f);
8700 else
8701 rettv->vval.v_float = 0.0;
8703 #endif
8706 * "changenr()" function
8708 /*ARGSUSED*/
8709 static void
8710 f_changenr(argvars, rettv)
8711 typval_T *argvars;
8712 typval_T *rettv;
8714 rettv->vval.v_number = curbuf->b_u_seq_cur;
8718 * "char2nr(string)" function
8720 static void
8721 f_char2nr(argvars, rettv)
8722 typval_T *argvars;
8723 typval_T *rettv;
8725 #ifdef FEAT_MBYTE
8726 if (has_mbyte)
8727 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
8728 else
8729 #endif
8730 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
8734 * "cindent(lnum)" function
8736 static void
8737 f_cindent(argvars, rettv)
8738 typval_T *argvars;
8739 typval_T *rettv;
8741 #ifdef FEAT_CINDENT
8742 pos_T pos;
8743 linenr_T lnum;
8745 pos = curwin->w_cursor;
8746 lnum = get_tv_lnum(argvars);
8747 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
8749 curwin->w_cursor.lnum = lnum;
8750 rettv->vval.v_number = get_c_indent();
8751 curwin->w_cursor = pos;
8753 else
8754 #endif
8755 rettv->vval.v_number = -1;
8759 * "clearmatches()" function
8761 /*ARGSUSED*/
8762 static void
8763 f_clearmatches(argvars, rettv)
8764 typval_T *argvars;
8765 typval_T *rettv;
8767 #ifdef FEAT_SEARCH_EXTRA
8768 clear_matches(curwin);
8769 #endif
8773 * "col(string)" function
8775 static void
8776 f_col(argvars, rettv)
8777 typval_T *argvars;
8778 typval_T *rettv;
8780 colnr_T col = 0;
8781 pos_T *fp;
8782 int fnum = curbuf->b_fnum;
8784 fp = var2fpos(&argvars[0], FALSE, &fnum);
8785 if (fp != NULL && fnum == curbuf->b_fnum)
8787 if (fp->col == MAXCOL)
8789 /* '> can be MAXCOL, get the length of the line then */
8790 if (fp->lnum <= curbuf->b_ml.ml_line_count)
8791 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
8792 else
8793 col = MAXCOL;
8795 else
8797 col = fp->col + 1;
8798 #ifdef FEAT_VIRTUALEDIT
8799 /* col(".") when the cursor is on the NUL at the end of the line
8800 * because of "coladd" can be seen as an extra column. */
8801 if (virtual_active() && fp == &curwin->w_cursor)
8803 char_u *p = ml_get_cursor();
8805 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
8806 curwin->w_virtcol - curwin->w_cursor.coladd))
8808 # ifdef FEAT_MBYTE
8809 int l;
8811 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
8812 col += l;
8813 # else
8814 if (*p != NUL && p[1] == NUL)
8815 ++col;
8816 # endif
8819 #endif
8822 rettv->vval.v_number = col;
8825 #if defined(FEAT_INS_EXPAND)
8827 * "complete()" function
8829 /*ARGSUSED*/
8830 static void
8831 f_complete(argvars, rettv)
8832 typval_T *argvars;
8833 typval_T *rettv;
8835 int startcol;
8837 if ((State & INSERT) == 0)
8839 EMSG(_("E785: complete() can only be used in Insert mode"));
8840 return;
8843 /* Check for undo allowed here, because if something was already inserted
8844 * the line was already saved for undo and this check isn't done. */
8845 if (!undo_allowed())
8846 return;
8848 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
8850 EMSG(_(e_invarg));
8851 return;
8854 startcol = get_tv_number_chk(&argvars[0], NULL);
8855 if (startcol <= 0)
8856 return;
8858 set_completion(startcol - 1, argvars[1].vval.v_list);
8862 * "complete_add()" function
8864 /*ARGSUSED*/
8865 static void
8866 f_complete_add(argvars, rettv)
8867 typval_T *argvars;
8868 typval_T *rettv;
8870 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
8874 * "complete_check()" function
8876 /*ARGSUSED*/
8877 static void
8878 f_complete_check(argvars, rettv)
8879 typval_T *argvars;
8880 typval_T *rettv;
8882 int saved = RedrawingDisabled;
8884 RedrawingDisabled = 0;
8885 ins_compl_check_keys(0);
8886 rettv->vval.v_number = compl_interrupted;
8887 RedrawingDisabled = saved;
8889 #endif
8892 * "confirm(message, buttons[, default [, type]])" function
8894 /*ARGSUSED*/
8895 static void
8896 f_confirm(argvars, rettv)
8897 typval_T *argvars;
8898 typval_T *rettv;
8900 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
8901 char_u *message;
8902 char_u *buttons = NULL;
8903 char_u buf[NUMBUFLEN];
8904 char_u buf2[NUMBUFLEN];
8905 int def = 1;
8906 int type = VIM_GENERIC;
8907 char_u *typestr;
8908 int error = FALSE;
8910 message = get_tv_string_chk(&argvars[0]);
8911 if (message == NULL)
8912 error = TRUE;
8913 if (argvars[1].v_type != VAR_UNKNOWN)
8915 buttons = get_tv_string_buf_chk(&argvars[1], buf);
8916 if (buttons == NULL)
8917 error = TRUE;
8918 if (argvars[2].v_type != VAR_UNKNOWN)
8920 def = get_tv_number_chk(&argvars[2], &error);
8921 if (argvars[3].v_type != VAR_UNKNOWN)
8923 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
8924 if (typestr == NULL)
8925 error = TRUE;
8926 else
8928 switch (TOUPPER_ASC(*typestr))
8930 case 'E': type = VIM_ERROR; break;
8931 case 'Q': type = VIM_QUESTION; break;
8932 case 'I': type = VIM_INFO; break;
8933 case 'W': type = VIM_WARNING; break;
8934 case 'G': type = VIM_GENERIC; break;
8941 if (buttons == NULL || *buttons == NUL)
8942 buttons = (char_u *)_("&Ok");
8944 if (error)
8945 rettv->vval.v_number = 0;
8946 else
8947 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
8948 def, NULL);
8949 #else
8950 rettv->vval.v_number = 0;
8951 #endif
8955 * "copy()" function
8957 static void
8958 f_copy(argvars, rettv)
8959 typval_T *argvars;
8960 typval_T *rettv;
8962 item_copy(&argvars[0], rettv, FALSE, 0);
8965 #ifdef FEAT_FLOAT
8967 * "cos()" function
8969 static void
8970 f_cos(argvars, rettv)
8971 typval_T *argvars;
8972 typval_T *rettv;
8974 float_T f;
8976 rettv->v_type = VAR_FLOAT;
8977 if (get_float_arg(argvars, &f) == OK)
8978 rettv->vval.v_float = cos(f);
8979 else
8980 rettv->vval.v_float = 0.0;
8982 #endif
8985 * "count()" function
8987 static void
8988 f_count(argvars, rettv)
8989 typval_T *argvars;
8990 typval_T *rettv;
8992 long n = 0;
8993 int ic = FALSE;
8995 if (argvars[0].v_type == VAR_LIST)
8997 listitem_T *li;
8998 list_T *l;
8999 long idx;
9001 if ((l = argvars[0].vval.v_list) != NULL)
9003 li = l->lv_first;
9004 if (argvars[2].v_type != VAR_UNKNOWN)
9006 int error = FALSE;
9008 ic = get_tv_number_chk(&argvars[2], &error);
9009 if (argvars[3].v_type != VAR_UNKNOWN)
9011 idx = get_tv_number_chk(&argvars[3], &error);
9012 if (!error)
9014 li = list_find(l, idx);
9015 if (li == NULL)
9016 EMSGN(_(e_listidx), idx);
9019 if (error)
9020 li = NULL;
9023 for ( ; li != NULL; li = li->li_next)
9024 if (tv_equal(&li->li_tv, &argvars[1], ic))
9025 ++n;
9028 else if (argvars[0].v_type == VAR_DICT)
9030 int todo;
9031 dict_T *d;
9032 hashitem_T *hi;
9034 if ((d = argvars[0].vval.v_dict) != NULL)
9036 int error = FALSE;
9038 if (argvars[2].v_type != VAR_UNKNOWN)
9040 ic = get_tv_number_chk(&argvars[2], &error);
9041 if (argvars[3].v_type != VAR_UNKNOWN)
9042 EMSG(_(e_invarg));
9045 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
9046 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
9048 if (!HASHITEM_EMPTY(hi))
9050 --todo;
9051 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
9052 ++n;
9057 else
9058 EMSG2(_(e_listdictarg), "count()");
9059 rettv->vval.v_number = n;
9063 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
9065 * Checks the existence of a cscope connection.
9067 /*ARGSUSED*/
9068 static void
9069 f_cscope_connection(argvars, rettv)
9070 typval_T *argvars;
9071 typval_T *rettv;
9073 #ifdef FEAT_CSCOPE
9074 int num = 0;
9075 char_u *dbpath = NULL;
9076 char_u *prepend = NULL;
9077 char_u buf[NUMBUFLEN];
9079 if (argvars[0].v_type != VAR_UNKNOWN
9080 && argvars[1].v_type != VAR_UNKNOWN)
9082 num = (int)get_tv_number(&argvars[0]);
9083 dbpath = get_tv_string(&argvars[1]);
9084 if (argvars[2].v_type != VAR_UNKNOWN)
9085 prepend = get_tv_string_buf(&argvars[2], buf);
9088 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
9089 #else
9090 rettv->vval.v_number = 0;
9091 #endif
9095 * "cursor(lnum, col)" function
9097 * Moves the cursor to the specified line and column
9099 /*ARGSUSED*/
9100 static void
9101 f_cursor(argvars, rettv)
9102 typval_T *argvars;
9103 typval_T *rettv;
9105 long line, col;
9106 #ifdef FEAT_VIRTUALEDIT
9107 long coladd = 0;
9108 #endif
9110 if (argvars[1].v_type == VAR_UNKNOWN)
9112 pos_T pos;
9114 if (list2fpos(argvars, &pos, NULL) == FAIL)
9115 return;
9116 line = pos.lnum;
9117 col = pos.col;
9118 #ifdef FEAT_VIRTUALEDIT
9119 coladd = pos.coladd;
9120 #endif
9122 else
9124 line = get_tv_lnum(argvars);
9125 col = get_tv_number_chk(&argvars[1], NULL);
9126 #ifdef FEAT_VIRTUALEDIT
9127 if (argvars[2].v_type != VAR_UNKNOWN)
9128 coladd = get_tv_number_chk(&argvars[2], NULL);
9129 #endif
9131 if (line < 0 || col < 0
9132 #ifdef FEAT_VIRTUALEDIT
9133 || coladd < 0
9134 #endif
9136 return; /* type error; errmsg already given */
9137 if (line > 0)
9138 curwin->w_cursor.lnum = line;
9139 if (col > 0)
9140 curwin->w_cursor.col = col - 1;
9141 #ifdef FEAT_VIRTUALEDIT
9142 curwin->w_cursor.coladd = coladd;
9143 #endif
9145 /* Make sure the cursor is in a valid position. */
9146 check_cursor();
9147 #ifdef FEAT_MBYTE
9148 /* Correct cursor for multi-byte character. */
9149 if (has_mbyte)
9150 mb_adjust_cursor();
9151 #endif
9153 curwin->w_set_curswant = TRUE;
9157 * "deepcopy()" function
9159 static void
9160 f_deepcopy(argvars, rettv)
9161 typval_T *argvars;
9162 typval_T *rettv;
9164 int noref = 0;
9166 if (argvars[1].v_type != VAR_UNKNOWN)
9167 noref = get_tv_number_chk(&argvars[1], NULL);
9168 if (noref < 0 || noref > 1)
9169 EMSG(_(e_invarg));
9170 else
9171 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? ++current_copyID : 0);
9175 * "delete()" function
9177 static void
9178 f_delete(argvars, rettv)
9179 typval_T *argvars;
9180 typval_T *rettv;
9182 if (check_restricted() || check_secure())
9183 rettv->vval.v_number = -1;
9184 else
9185 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
9189 * "did_filetype()" function
9191 /*ARGSUSED*/
9192 static void
9193 f_did_filetype(argvars, rettv)
9194 typval_T *argvars;
9195 typval_T *rettv;
9197 #ifdef FEAT_AUTOCMD
9198 rettv->vval.v_number = did_filetype;
9199 #else
9200 rettv->vval.v_number = 0;
9201 #endif
9205 * "diff_filler()" function
9207 /*ARGSUSED*/
9208 static void
9209 f_diff_filler(argvars, rettv)
9210 typval_T *argvars;
9211 typval_T *rettv;
9213 #ifdef FEAT_DIFF
9214 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
9215 #endif
9219 * "diff_hlID()" function
9221 /*ARGSUSED*/
9222 static void
9223 f_diff_hlID(argvars, rettv)
9224 typval_T *argvars;
9225 typval_T *rettv;
9227 #ifdef FEAT_DIFF
9228 linenr_T lnum = get_tv_lnum(argvars);
9229 static linenr_T prev_lnum = 0;
9230 static int changedtick = 0;
9231 static int fnum = 0;
9232 static int change_start = 0;
9233 static int change_end = 0;
9234 static hlf_T hlID = (hlf_T)0;
9235 int filler_lines;
9236 int col;
9238 if (lnum < 0) /* ignore type error in {lnum} arg */
9239 lnum = 0;
9240 if (lnum != prev_lnum
9241 || changedtick != curbuf->b_changedtick
9242 || fnum != curbuf->b_fnum)
9244 /* New line, buffer, change: need to get the values. */
9245 filler_lines = diff_check(curwin, lnum);
9246 if (filler_lines < 0)
9248 if (filler_lines == -1)
9250 change_start = MAXCOL;
9251 change_end = -1;
9252 if (diff_find_change(curwin, lnum, &change_start, &change_end))
9253 hlID = HLF_ADD; /* added line */
9254 else
9255 hlID = HLF_CHD; /* changed line */
9257 else
9258 hlID = HLF_ADD; /* added line */
9260 else
9261 hlID = (hlf_T)0;
9262 prev_lnum = lnum;
9263 changedtick = curbuf->b_changedtick;
9264 fnum = curbuf->b_fnum;
9267 if (hlID == HLF_CHD || hlID == HLF_TXD)
9269 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
9270 if (col >= change_start && col <= change_end)
9271 hlID = HLF_TXD; /* changed text */
9272 else
9273 hlID = HLF_CHD; /* changed line */
9275 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
9276 #endif
9280 * "empty({expr})" function
9282 static void
9283 f_empty(argvars, rettv)
9284 typval_T *argvars;
9285 typval_T *rettv;
9287 int n;
9289 switch (argvars[0].v_type)
9291 case VAR_STRING:
9292 case VAR_FUNC:
9293 n = argvars[0].vval.v_string == NULL
9294 || *argvars[0].vval.v_string == NUL;
9295 break;
9296 case VAR_NUMBER:
9297 n = argvars[0].vval.v_number == 0;
9298 break;
9299 #ifdef FEAT_FLOAT
9300 case VAR_FLOAT:
9301 n = argvars[0].vval.v_float == 0.0;
9302 break;
9303 #endif
9304 case VAR_LIST:
9305 n = argvars[0].vval.v_list == NULL
9306 || argvars[0].vval.v_list->lv_first == NULL;
9307 break;
9308 case VAR_DICT:
9309 n = argvars[0].vval.v_dict == NULL
9310 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
9311 break;
9312 default:
9313 EMSG2(_(e_intern2), "f_empty()");
9314 n = 0;
9317 rettv->vval.v_number = n;
9321 * "escape({string}, {chars})" function
9323 static void
9324 f_escape(argvars, rettv)
9325 typval_T *argvars;
9326 typval_T *rettv;
9328 char_u buf[NUMBUFLEN];
9330 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
9331 get_tv_string_buf(&argvars[1], buf));
9332 rettv->v_type = VAR_STRING;
9336 * "eval()" function
9338 /*ARGSUSED*/
9339 static void
9340 f_eval(argvars, rettv)
9341 typval_T *argvars;
9342 typval_T *rettv;
9344 char_u *s;
9346 s = get_tv_string_chk(&argvars[0]);
9347 if (s != NULL)
9348 s = skipwhite(s);
9350 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
9352 rettv->v_type = VAR_NUMBER;
9353 rettv->vval.v_number = 0;
9355 else if (*s != NUL)
9356 EMSG(_(e_trailing));
9360 * "eventhandler()" function
9362 /*ARGSUSED*/
9363 static void
9364 f_eventhandler(argvars, rettv)
9365 typval_T *argvars;
9366 typval_T *rettv;
9368 rettv->vval.v_number = vgetc_busy;
9372 * "executable()" function
9374 static void
9375 f_executable(argvars, rettv)
9376 typval_T *argvars;
9377 typval_T *rettv;
9379 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
9383 * "exists()" function
9385 static void
9386 f_exists(argvars, rettv)
9387 typval_T *argvars;
9388 typval_T *rettv;
9390 char_u *p;
9391 char_u *name;
9392 int n = FALSE;
9393 int len = 0;
9395 p = get_tv_string(&argvars[0]);
9396 if (*p == '$') /* environment variable */
9398 /* first try "normal" environment variables (fast) */
9399 if (mch_getenv(p + 1) != NULL)
9400 n = TRUE;
9401 else
9403 /* try expanding things like $VIM and ${HOME} */
9404 p = expand_env_save(p);
9405 if (p != NULL && *p != '$')
9406 n = TRUE;
9407 vim_free(p);
9410 else if (*p == '&' || *p == '+') /* option */
9412 n = (get_option_tv(&p, NULL, TRUE) == OK);
9413 if (*skipwhite(p) != NUL)
9414 n = FALSE; /* trailing garbage */
9416 else if (*p == '*') /* internal or user defined function */
9418 n = function_exists(p + 1);
9420 else if (*p == ':')
9422 n = cmd_exists(p + 1);
9424 else if (*p == '#')
9426 #ifdef FEAT_AUTOCMD
9427 if (p[1] == '#')
9428 n = autocmd_supported(p + 2);
9429 else
9430 n = au_exists(p + 1);
9431 #endif
9433 else /* internal variable */
9435 char_u *tofree;
9436 typval_T tv;
9438 /* get_name_len() takes care of expanding curly braces */
9439 name = p;
9440 len = get_name_len(&p, &tofree, TRUE, FALSE);
9441 if (len > 0)
9443 if (tofree != NULL)
9444 name = tofree;
9445 n = (get_var_tv(name, len, &tv, FALSE) == OK);
9446 if (n)
9448 /* handle d.key, l[idx], f(expr) */
9449 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
9450 if (n)
9451 clear_tv(&tv);
9454 if (*p != NUL)
9455 n = FALSE;
9457 vim_free(tofree);
9460 rettv->vval.v_number = n;
9464 * "expand()" function
9466 static void
9467 f_expand(argvars, rettv)
9468 typval_T *argvars;
9469 typval_T *rettv;
9471 char_u *s;
9472 int len;
9473 char_u *errormsg;
9474 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
9475 expand_T xpc;
9476 int error = FALSE;
9478 rettv->v_type = VAR_STRING;
9479 s = get_tv_string(&argvars[0]);
9480 if (*s == '%' || *s == '#' || *s == '<')
9482 ++emsg_off;
9483 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
9484 --emsg_off;
9486 else
9488 /* When the optional second argument is non-zero, don't remove matches
9489 * for 'suffixes' and 'wildignore' */
9490 if (argvars[1].v_type != VAR_UNKNOWN
9491 && get_tv_number_chk(&argvars[1], &error))
9492 flags |= WILD_KEEP_ALL;
9493 if (!error)
9495 ExpandInit(&xpc);
9496 xpc.xp_context = EXPAND_FILES;
9497 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
9499 else
9500 rettv->vval.v_string = NULL;
9505 * "extend(list, list [, idx])" function
9506 * "extend(dict, dict [, action])" function
9508 static void
9509 f_extend(argvars, rettv)
9510 typval_T *argvars;
9511 typval_T *rettv;
9513 rettv->vval.v_number = 0;
9514 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9516 list_T *l1, *l2;
9517 listitem_T *item;
9518 long before;
9519 int error = FALSE;
9521 l1 = argvars[0].vval.v_list;
9522 l2 = argvars[1].vval.v_list;
9523 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9524 && l2 != NULL)
9526 if (argvars[2].v_type != VAR_UNKNOWN)
9528 before = get_tv_number_chk(&argvars[2], &error);
9529 if (error)
9530 return; /* type error; errmsg already given */
9532 if (before == l1->lv_len)
9533 item = NULL;
9534 else
9536 item = list_find(l1, before);
9537 if (item == NULL)
9539 EMSGN(_(e_listidx), before);
9540 return;
9544 else
9545 item = NULL;
9546 list_extend(l1, l2, item);
9548 copy_tv(&argvars[0], rettv);
9551 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9553 dict_T *d1, *d2;
9554 dictitem_T *di1;
9555 char_u *action;
9556 int i;
9557 hashitem_T *hi2;
9558 int todo;
9560 d1 = argvars[0].vval.v_dict;
9561 d2 = argvars[1].vval.v_dict;
9562 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9563 && d2 != NULL)
9565 /* Check the third argument. */
9566 if (argvars[2].v_type != VAR_UNKNOWN)
9568 static char *(av[]) = {"keep", "force", "error"};
9570 action = get_tv_string_chk(&argvars[2]);
9571 if (action == NULL)
9572 return; /* type error; errmsg already given */
9573 for (i = 0; i < 3; ++i)
9574 if (STRCMP(action, av[i]) == 0)
9575 break;
9576 if (i == 3)
9578 EMSG2(_(e_invarg2), action);
9579 return;
9582 else
9583 action = (char_u *)"force";
9585 /* Go over all entries in the second dict and add them to the
9586 * first dict. */
9587 todo = (int)d2->dv_hashtab.ht_used;
9588 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9590 if (!HASHITEM_EMPTY(hi2))
9592 --todo;
9593 di1 = dict_find(d1, hi2->hi_key, -1);
9594 if (di1 == NULL)
9596 di1 = dictitem_copy(HI2DI(hi2));
9597 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9598 dictitem_free(di1);
9600 else if (*action == 'e')
9602 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9603 break;
9605 else if (*action == 'f')
9607 clear_tv(&di1->di_tv);
9608 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9613 copy_tv(&argvars[0], rettv);
9616 else
9617 EMSG2(_(e_listdictarg), "extend()");
9621 * "feedkeys()" function
9623 /*ARGSUSED*/
9624 static void
9625 f_feedkeys(argvars, rettv)
9626 typval_T *argvars;
9627 typval_T *rettv;
9629 int remap = TRUE;
9630 char_u *keys, *flags;
9631 char_u nbuf[NUMBUFLEN];
9632 int typed = FALSE;
9633 char_u *keys_esc;
9635 /* This is not allowed in the sandbox. If the commands would still be
9636 * executed in the sandbox it would be OK, but it probably happens later,
9637 * when "sandbox" is no longer set. */
9638 if (check_secure())
9639 return;
9641 rettv->vval.v_number = 0;
9642 keys = get_tv_string(&argvars[0]);
9643 if (*keys != NUL)
9645 if (argvars[1].v_type != VAR_UNKNOWN)
9647 flags = get_tv_string_buf(&argvars[1], nbuf);
9648 for ( ; *flags != NUL; ++flags)
9650 switch (*flags)
9652 case 'n': remap = FALSE; break;
9653 case 'm': remap = TRUE; break;
9654 case 't': typed = TRUE; break;
9659 /* Need to escape K_SPECIAL and CSI before putting the string in the
9660 * typeahead buffer. */
9661 keys_esc = vim_strsave_escape_csi(keys);
9662 if (keys_esc != NULL)
9664 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
9665 typebuf.tb_len, !typed, FALSE);
9666 vim_free(keys_esc);
9667 if (vgetc_busy)
9668 typebuf_was_filled = TRUE;
9674 * "filereadable()" function
9676 static void
9677 f_filereadable(argvars, rettv)
9678 typval_T *argvars;
9679 typval_T *rettv;
9681 FILE *fd;
9682 char_u *p;
9683 int n;
9685 p = get_tv_string(&argvars[0]);
9686 if (*p && !mch_isdir(p) && (fd = mch_fopen((char *)p, "r")) != NULL)
9688 n = TRUE;
9689 fclose(fd);
9691 else
9692 n = FALSE;
9694 rettv->vval.v_number = n;
9698 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
9699 * rights to write into.
9701 static void
9702 f_filewritable(argvars, rettv)
9703 typval_T *argvars;
9704 typval_T *rettv;
9706 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
9709 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
9711 static void
9712 findfilendir(argvars, rettv, find_what)
9713 typval_T *argvars;
9714 typval_T *rettv;
9715 int find_what;
9717 #ifdef FEAT_SEARCHPATH
9718 char_u *fname;
9719 char_u *fresult = NULL;
9720 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
9721 char_u *p;
9722 char_u pathbuf[NUMBUFLEN];
9723 int count = 1;
9724 int first = TRUE;
9725 int error = FALSE;
9726 #endif
9728 rettv->vval.v_string = NULL;
9729 rettv->v_type = VAR_STRING;
9731 #ifdef FEAT_SEARCHPATH
9732 fname = get_tv_string(&argvars[0]);
9734 if (argvars[1].v_type != VAR_UNKNOWN)
9736 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
9737 if (p == NULL)
9738 error = TRUE;
9739 else
9741 if (*p != NUL)
9742 path = p;
9744 if (argvars[2].v_type != VAR_UNKNOWN)
9745 count = get_tv_number_chk(&argvars[2], &error);
9749 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
9750 error = TRUE;
9752 if (*fname != NUL && !error)
9756 if (rettv->v_type == VAR_STRING)
9757 vim_free(fresult);
9758 fresult = find_file_in_path_option(first ? fname : NULL,
9759 first ? (int)STRLEN(fname) : 0,
9760 0, first, path,
9761 find_what,
9762 curbuf->b_ffname,
9763 find_what == FINDFILE_DIR
9764 ? (char_u *)"" : curbuf->b_p_sua);
9765 first = FALSE;
9767 if (fresult != NULL && rettv->v_type == VAR_LIST)
9768 list_append_string(rettv->vval.v_list, fresult, -1);
9770 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
9773 if (rettv->v_type == VAR_STRING)
9774 rettv->vval.v_string = fresult;
9775 #endif
9778 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
9779 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
9782 * Implementation of map() and filter().
9784 static void
9785 filter_map(argvars, rettv, map)
9786 typval_T *argvars;
9787 typval_T *rettv;
9788 int map;
9790 char_u buf[NUMBUFLEN];
9791 char_u *expr;
9792 listitem_T *li, *nli;
9793 list_T *l = NULL;
9794 dictitem_T *di;
9795 hashtab_T *ht;
9796 hashitem_T *hi;
9797 dict_T *d = NULL;
9798 typval_T save_val;
9799 typval_T save_key;
9800 int rem;
9801 int todo;
9802 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
9803 int save_did_emsg;
9805 rettv->vval.v_number = 0;
9806 if (argvars[0].v_type == VAR_LIST)
9808 if ((l = argvars[0].vval.v_list) == NULL
9809 || (map && tv_check_lock(l->lv_lock, ermsg)))
9810 return;
9812 else if (argvars[0].v_type == VAR_DICT)
9814 if ((d = argvars[0].vval.v_dict) == NULL
9815 || (map && tv_check_lock(d->dv_lock, ermsg)))
9816 return;
9818 else
9820 EMSG2(_(e_listdictarg), ermsg);
9821 return;
9824 expr = get_tv_string_buf_chk(&argvars[1], buf);
9825 /* On type errors, the preceding call has already displayed an error
9826 * message. Avoid a misleading error message for an empty string that
9827 * was not passed as argument. */
9828 if (expr != NULL)
9830 prepare_vimvar(VV_VAL, &save_val);
9831 expr = skipwhite(expr);
9833 /* We reset "did_emsg" to be able to detect whether an error
9834 * occurred during evaluation of the expression. */
9835 save_did_emsg = did_emsg;
9836 did_emsg = FALSE;
9838 if (argvars[0].v_type == VAR_DICT)
9840 prepare_vimvar(VV_KEY, &save_key);
9841 vimvars[VV_KEY].vv_type = VAR_STRING;
9843 ht = &d->dv_hashtab;
9844 hash_lock(ht);
9845 todo = (int)ht->ht_used;
9846 for (hi = ht->ht_array; todo > 0; ++hi)
9848 if (!HASHITEM_EMPTY(hi))
9850 --todo;
9851 di = HI2DI(hi);
9852 if (tv_check_lock(di->di_tv.v_lock, ermsg))
9853 break;
9854 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
9855 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
9856 || did_emsg)
9857 break;
9858 if (!map && rem)
9859 dictitem_remove(d, di);
9860 clear_tv(&vimvars[VV_KEY].vv_tv);
9863 hash_unlock(ht);
9865 restore_vimvar(VV_KEY, &save_key);
9867 else
9869 for (li = l->lv_first; li != NULL; li = nli)
9871 if (tv_check_lock(li->li_tv.v_lock, ermsg))
9872 break;
9873 nli = li->li_next;
9874 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
9875 || did_emsg)
9876 break;
9877 if (!map && rem)
9878 listitem_remove(l, li);
9882 restore_vimvar(VV_VAL, &save_val);
9884 did_emsg |= save_did_emsg;
9887 copy_tv(&argvars[0], rettv);
9890 static int
9891 filter_map_one(tv, expr, map, remp)
9892 typval_T *tv;
9893 char_u *expr;
9894 int map;
9895 int *remp;
9897 typval_T rettv;
9898 char_u *s;
9899 int retval = FAIL;
9901 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
9902 s = expr;
9903 if (eval1(&s, &rettv, TRUE) == FAIL)
9904 goto theend;
9905 if (*s != NUL) /* check for trailing chars after expr */
9907 EMSG2(_(e_invexpr2), s);
9908 goto theend;
9910 if (map)
9912 /* map(): replace the list item value */
9913 clear_tv(tv);
9914 rettv.v_lock = 0;
9915 *tv = rettv;
9917 else
9919 int error = FALSE;
9921 /* filter(): when expr is zero remove the item */
9922 *remp = (get_tv_number_chk(&rettv, &error) == 0);
9923 clear_tv(&rettv);
9924 /* On type error, nothing has been removed; return FAIL to stop the
9925 * loop. The error message was given by get_tv_number_chk(). */
9926 if (error)
9927 goto theend;
9929 retval = OK;
9930 theend:
9931 clear_tv(&vimvars[VV_VAL].vv_tv);
9932 return retval;
9936 * "filter()" function
9938 static void
9939 f_filter(argvars, rettv)
9940 typval_T *argvars;
9941 typval_T *rettv;
9943 filter_map(argvars, rettv, FALSE);
9947 * "finddir({fname}[, {path}[, {count}]])" function
9949 static void
9950 f_finddir(argvars, rettv)
9951 typval_T *argvars;
9952 typval_T *rettv;
9954 findfilendir(argvars, rettv, FINDFILE_DIR);
9958 * "findfile({fname}[, {path}[, {count}]])" function
9960 static void
9961 f_findfile(argvars, rettv)
9962 typval_T *argvars;
9963 typval_T *rettv;
9965 findfilendir(argvars, rettv, FINDFILE_FILE);
9968 #ifdef FEAT_FLOAT
9970 * "float2nr({float})" function
9972 static void
9973 f_float2nr(argvars, rettv)
9974 typval_T *argvars;
9975 typval_T *rettv;
9977 float_T f;
9979 if (get_float_arg(argvars, &f) == OK)
9981 if (f < -0x7fffffff)
9982 rettv->vval.v_number = -0x7fffffff;
9983 else if (f > 0x7fffffff)
9984 rettv->vval.v_number = 0x7fffffff;
9985 else
9986 rettv->vval.v_number = (varnumber_T)f;
9988 else
9989 rettv->vval.v_number = 0;
9993 * "floor({float})" function
9995 static void
9996 f_floor(argvars, rettv)
9997 typval_T *argvars;
9998 typval_T *rettv;
10000 float_T f;
10002 rettv->v_type = VAR_FLOAT;
10003 if (get_float_arg(argvars, &f) == OK)
10004 rettv->vval.v_float = floor(f);
10005 else
10006 rettv->vval.v_float = 0.0;
10008 #endif
10011 * "fnameescape({string})" function
10013 static void
10014 f_fnameescape(argvars, rettv)
10015 typval_T *argvars;
10016 typval_T *rettv;
10018 rettv->vval.v_string = vim_strsave_fnameescape(
10019 get_tv_string(&argvars[0]), FALSE);
10020 rettv->v_type = VAR_STRING;
10024 * "fnamemodify({fname}, {mods})" function
10026 static void
10027 f_fnamemodify(argvars, rettv)
10028 typval_T *argvars;
10029 typval_T *rettv;
10031 char_u *fname;
10032 char_u *mods;
10033 int usedlen = 0;
10034 int len;
10035 char_u *fbuf = NULL;
10036 char_u buf[NUMBUFLEN];
10038 fname = get_tv_string_chk(&argvars[0]);
10039 mods = get_tv_string_buf_chk(&argvars[1], buf);
10040 if (fname == NULL || mods == NULL)
10041 fname = NULL;
10042 else
10044 len = (int)STRLEN(fname);
10045 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
10048 rettv->v_type = VAR_STRING;
10049 if (fname == NULL)
10050 rettv->vval.v_string = NULL;
10051 else
10052 rettv->vval.v_string = vim_strnsave(fname, len);
10053 vim_free(fbuf);
10056 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
10059 * "foldclosed()" function
10061 static void
10062 foldclosed_both(argvars, rettv, end)
10063 typval_T *argvars;
10064 typval_T *rettv;
10065 int end;
10067 #ifdef FEAT_FOLDING
10068 linenr_T lnum;
10069 linenr_T first, last;
10071 lnum = get_tv_lnum(argvars);
10072 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10074 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
10076 if (end)
10077 rettv->vval.v_number = (varnumber_T)last;
10078 else
10079 rettv->vval.v_number = (varnumber_T)first;
10080 return;
10083 #endif
10084 rettv->vval.v_number = -1;
10088 * "foldclosed()" function
10090 static void
10091 f_foldclosed(argvars, rettv)
10092 typval_T *argvars;
10093 typval_T *rettv;
10095 foldclosed_both(argvars, rettv, FALSE);
10099 * "foldclosedend()" function
10101 static void
10102 f_foldclosedend(argvars, rettv)
10103 typval_T *argvars;
10104 typval_T *rettv;
10106 foldclosed_both(argvars, rettv, TRUE);
10110 * "foldlevel()" function
10112 static void
10113 f_foldlevel(argvars, rettv)
10114 typval_T *argvars;
10115 typval_T *rettv;
10117 #ifdef FEAT_FOLDING
10118 linenr_T lnum;
10120 lnum = get_tv_lnum(argvars);
10121 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10122 rettv->vval.v_number = foldLevel(lnum);
10123 else
10124 #endif
10125 rettv->vval.v_number = 0;
10129 * "foldtext()" function
10131 /*ARGSUSED*/
10132 static void
10133 f_foldtext(argvars, rettv)
10134 typval_T *argvars;
10135 typval_T *rettv;
10137 #ifdef FEAT_FOLDING
10138 linenr_T lnum;
10139 char_u *s;
10140 char_u *r;
10141 int len;
10142 char *txt;
10143 #endif
10145 rettv->v_type = VAR_STRING;
10146 rettv->vval.v_string = NULL;
10147 #ifdef FEAT_FOLDING
10148 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
10149 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
10150 <= curbuf->b_ml.ml_line_count
10151 && vimvars[VV_FOLDDASHES].vv_str != NULL)
10153 /* Find first non-empty line in the fold. */
10154 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
10155 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10157 if (!linewhite(lnum))
10158 break;
10159 ++lnum;
10162 /* Find interesting text in this line. */
10163 s = skipwhite(ml_get(lnum));
10164 /* skip C comment-start */
10165 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
10167 s = skipwhite(s + 2);
10168 if (*skipwhite(s) == NUL
10169 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10171 s = skipwhite(ml_get(lnum + 1));
10172 if (*s == '*')
10173 s = skipwhite(s + 1);
10176 txt = _("+-%s%3ld lines: ");
10177 r = alloc((unsigned)(STRLEN(txt)
10178 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
10179 + 20 /* for %3ld */
10180 + STRLEN(s))); /* concatenated */
10181 if (r != NULL)
10183 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
10184 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
10185 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
10186 len = (int)STRLEN(r);
10187 STRCAT(r, s);
10188 /* remove 'foldmarker' and 'commentstring' */
10189 foldtext_cleanup(r + len);
10190 rettv->vval.v_string = r;
10193 #endif
10197 * "foldtextresult(lnum)" function
10199 /*ARGSUSED*/
10200 static void
10201 f_foldtextresult(argvars, rettv)
10202 typval_T *argvars;
10203 typval_T *rettv;
10205 #ifdef FEAT_FOLDING
10206 linenr_T lnum;
10207 char_u *text;
10208 char_u buf[51];
10209 foldinfo_T foldinfo;
10210 int fold_count;
10211 #endif
10213 rettv->v_type = VAR_STRING;
10214 rettv->vval.v_string = NULL;
10215 #ifdef FEAT_FOLDING
10216 lnum = get_tv_lnum(argvars);
10217 /* treat illegal types and illegal string values for {lnum} the same */
10218 if (lnum < 0)
10219 lnum = 0;
10220 fold_count = foldedCount(curwin, lnum, &foldinfo);
10221 if (fold_count > 0)
10223 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
10224 &foldinfo, buf);
10225 if (text == buf)
10226 text = vim_strsave(text);
10227 rettv->vval.v_string = text;
10229 #endif
10233 * "foreground()" function
10235 /*ARGSUSED*/
10236 static void
10237 f_foreground(argvars, rettv)
10238 typval_T *argvars;
10239 typval_T *rettv;
10241 rettv->vval.v_number = 0;
10242 #ifdef FEAT_GUI
10243 if (gui.in_use)
10244 gui_mch_set_foreground();
10245 #else
10246 # ifdef WIN32
10247 win32_set_foreground();
10248 # endif
10249 #endif
10253 * "function()" function
10255 /*ARGSUSED*/
10256 static void
10257 f_function(argvars, rettv)
10258 typval_T *argvars;
10259 typval_T *rettv;
10261 char_u *s;
10263 rettv->vval.v_number = 0;
10264 s = get_tv_string(&argvars[0]);
10265 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
10266 EMSG2(_(e_invarg2), s);
10267 else if (!function_exists(s))
10268 EMSG2(_("E700: Unknown function: %s"), s);
10269 else
10271 rettv->vval.v_string = vim_strsave(s);
10272 rettv->v_type = VAR_FUNC;
10277 * "garbagecollect()" function
10279 /*ARGSUSED*/
10280 static void
10281 f_garbagecollect(argvars, rettv)
10282 typval_T *argvars;
10283 typval_T *rettv;
10285 /* This is postponed until we are back at the toplevel, because we may be
10286 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
10287 want_garbage_collect = TRUE;
10289 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
10290 garbage_collect_at_exit = TRUE;
10294 * "get()" function
10296 static void
10297 f_get(argvars, rettv)
10298 typval_T *argvars;
10299 typval_T *rettv;
10301 listitem_T *li;
10302 list_T *l;
10303 dictitem_T *di;
10304 dict_T *d;
10305 typval_T *tv = NULL;
10307 if (argvars[0].v_type == VAR_LIST)
10309 if ((l = argvars[0].vval.v_list) != NULL)
10311 int error = FALSE;
10313 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
10314 if (!error && li != NULL)
10315 tv = &li->li_tv;
10318 else if (argvars[0].v_type == VAR_DICT)
10320 if ((d = argvars[0].vval.v_dict) != NULL)
10322 di = dict_find(d, get_tv_string(&argvars[1]), -1);
10323 if (di != NULL)
10324 tv = &di->di_tv;
10327 else
10328 EMSG2(_(e_listdictarg), "get()");
10330 if (tv == NULL)
10332 if (argvars[2].v_type == VAR_UNKNOWN)
10333 rettv->vval.v_number = 0;
10334 else
10335 copy_tv(&argvars[2], rettv);
10337 else
10338 copy_tv(tv, rettv);
10341 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
10344 * Get line or list of lines from buffer "buf" into "rettv".
10345 * Return a range (from start to end) of lines in rettv from the specified
10346 * buffer.
10347 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
10349 static void
10350 get_buffer_lines(buf, start, end, retlist, rettv)
10351 buf_T *buf;
10352 linenr_T start;
10353 linenr_T end;
10354 int retlist;
10355 typval_T *rettv;
10357 char_u *p;
10359 if (retlist)
10361 if (rettv_list_alloc(rettv) == FAIL)
10362 return;
10364 else
10365 rettv->vval.v_number = 0;
10367 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
10368 return;
10370 if (!retlist)
10372 if (start >= 1 && start <= buf->b_ml.ml_line_count)
10373 p = ml_get_buf(buf, start, FALSE);
10374 else
10375 p = (char_u *)"";
10377 rettv->v_type = VAR_STRING;
10378 rettv->vval.v_string = vim_strsave(p);
10380 else
10382 if (end < start)
10383 return;
10385 if (start < 1)
10386 start = 1;
10387 if (end > buf->b_ml.ml_line_count)
10388 end = buf->b_ml.ml_line_count;
10389 while (start <= end)
10390 if (list_append_string(rettv->vval.v_list,
10391 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
10392 break;
10397 * "getbufline()" function
10399 static void
10400 f_getbufline(argvars, rettv)
10401 typval_T *argvars;
10402 typval_T *rettv;
10404 linenr_T lnum;
10405 linenr_T end;
10406 buf_T *buf;
10408 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10409 ++emsg_off;
10410 buf = get_buf_tv(&argvars[0]);
10411 --emsg_off;
10413 lnum = get_tv_lnum_buf(&argvars[1], buf);
10414 if (argvars[2].v_type == VAR_UNKNOWN)
10415 end = lnum;
10416 else
10417 end = get_tv_lnum_buf(&argvars[2], buf);
10419 get_buffer_lines(buf, lnum, end, TRUE, rettv);
10423 * "getbufvar()" function
10425 static void
10426 f_getbufvar(argvars, rettv)
10427 typval_T *argvars;
10428 typval_T *rettv;
10430 buf_T *buf;
10431 buf_T *save_curbuf;
10432 char_u *varname;
10433 dictitem_T *v;
10435 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10436 varname = get_tv_string_chk(&argvars[1]);
10437 ++emsg_off;
10438 buf = get_buf_tv(&argvars[0]);
10440 rettv->v_type = VAR_STRING;
10441 rettv->vval.v_string = NULL;
10443 if (buf != NULL && varname != NULL)
10445 /* set curbuf to be our buf, temporarily */
10446 save_curbuf = curbuf;
10447 curbuf = buf;
10449 if (*varname == '&') /* buffer-local-option */
10450 get_option_tv(&varname, rettv, TRUE);
10451 else
10453 if (*varname == NUL)
10454 /* let getbufvar({nr}, "") return the "b:" dictionary. The
10455 * scope prefix before the NUL byte is required by
10456 * find_var_in_ht(). */
10457 varname = (char_u *)"b:" + 2;
10458 /* look up the variable */
10459 v = find_var_in_ht(&curbuf->b_vars.dv_hashtab, varname, FALSE);
10460 if (v != NULL)
10461 copy_tv(&v->di_tv, rettv);
10464 /* restore previous notion of curbuf */
10465 curbuf = save_curbuf;
10468 --emsg_off;
10472 * "getchar()" function
10474 static void
10475 f_getchar(argvars, rettv)
10476 typval_T *argvars;
10477 typval_T *rettv;
10479 varnumber_T n;
10480 int error = FALSE;
10482 /* Position the cursor. Needed after a message that ends in a space. */
10483 windgoto(msg_row, msg_col);
10485 ++no_mapping;
10486 ++allow_keys;
10487 for (;;)
10489 if (argvars[0].v_type == VAR_UNKNOWN)
10490 /* getchar(): blocking wait. */
10491 n = safe_vgetc();
10492 else if (get_tv_number_chk(&argvars[0], &error) == 1)
10493 /* getchar(1): only check if char avail */
10494 n = vpeekc();
10495 else if (error || vpeekc() == NUL)
10496 /* illegal argument or getchar(0) and no char avail: return zero */
10497 n = 0;
10498 else
10499 /* getchar(0) and char avail: return char */
10500 n = safe_vgetc();
10501 if (n == K_IGNORE)
10502 continue;
10503 break;
10505 --no_mapping;
10506 --allow_keys;
10508 vimvars[VV_MOUSE_WIN].vv_nr = 0;
10509 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
10510 vimvars[VV_MOUSE_COL].vv_nr = 0;
10512 rettv->vval.v_number = n;
10513 if (IS_SPECIAL(n) || mod_mask != 0)
10515 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
10516 int i = 0;
10518 /* Turn a special key into three bytes, plus modifier. */
10519 if (mod_mask != 0)
10521 temp[i++] = K_SPECIAL;
10522 temp[i++] = KS_MODIFIER;
10523 temp[i++] = mod_mask;
10525 if (IS_SPECIAL(n))
10527 temp[i++] = K_SPECIAL;
10528 temp[i++] = K_SECOND(n);
10529 temp[i++] = K_THIRD(n);
10531 #ifdef FEAT_MBYTE
10532 else if (has_mbyte)
10533 i += (*mb_char2bytes)(n, temp + i);
10534 #endif
10535 else
10536 temp[i++] = n;
10537 temp[i++] = NUL;
10538 rettv->v_type = VAR_STRING;
10539 rettv->vval.v_string = vim_strsave(temp);
10541 #ifdef FEAT_MOUSE
10542 if (n == K_LEFTMOUSE
10543 || n == K_LEFTMOUSE_NM
10544 || n == K_LEFTDRAG
10545 || n == K_LEFTRELEASE
10546 || n == K_LEFTRELEASE_NM
10547 || n == K_MIDDLEMOUSE
10548 || n == K_MIDDLEDRAG
10549 || n == K_MIDDLERELEASE
10550 || n == K_RIGHTMOUSE
10551 || n == K_RIGHTDRAG
10552 || n == K_RIGHTRELEASE
10553 || n == K_X1MOUSE
10554 || n == K_X1DRAG
10555 || n == K_X1RELEASE
10556 || n == K_X2MOUSE
10557 || n == K_X2DRAG
10558 || n == K_X2RELEASE
10559 || n == K_MOUSEDOWN
10560 || n == K_MOUSEUP)
10562 int row = mouse_row;
10563 int col = mouse_col;
10564 win_T *win;
10565 linenr_T lnum;
10566 # ifdef FEAT_WINDOWS
10567 win_T *wp;
10568 # endif
10569 int n = 1;
10571 if (row >= 0 && col >= 0)
10573 /* Find the window at the mouse coordinates and compute the
10574 * text position. */
10575 win = mouse_find_win(&row, &col);
10576 (void)mouse_comp_pos(win, &row, &col, &lnum);
10577 # ifdef FEAT_WINDOWS
10578 for (wp = firstwin; wp != win; wp = wp->w_next)
10579 ++n;
10580 # endif
10581 vimvars[VV_MOUSE_WIN].vv_nr = n;
10582 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
10583 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
10586 #endif
10591 * "getcharmod()" function
10593 /*ARGSUSED*/
10594 static void
10595 f_getcharmod(argvars, rettv)
10596 typval_T *argvars;
10597 typval_T *rettv;
10599 rettv->vval.v_number = mod_mask;
10603 * "getcmdline()" function
10605 /*ARGSUSED*/
10606 static void
10607 f_getcmdline(argvars, rettv)
10608 typval_T *argvars;
10609 typval_T *rettv;
10611 rettv->v_type = VAR_STRING;
10612 rettv->vval.v_string = get_cmdline_str();
10616 * "getcmdpos()" function
10618 /*ARGSUSED*/
10619 static void
10620 f_getcmdpos(argvars, rettv)
10621 typval_T *argvars;
10622 typval_T *rettv;
10624 rettv->vval.v_number = get_cmdline_pos() + 1;
10628 * "getcmdtype()" function
10630 /*ARGSUSED*/
10631 static void
10632 f_getcmdtype(argvars, rettv)
10633 typval_T *argvars;
10634 typval_T *rettv;
10636 rettv->v_type = VAR_STRING;
10637 rettv->vval.v_string = alloc(2);
10638 if (rettv->vval.v_string != NULL)
10640 rettv->vval.v_string[0] = get_cmdline_type();
10641 rettv->vval.v_string[1] = NUL;
10646 * "getcwd()" function
10648 /*ARGSUSED*/
10649 static void
10650 f_getcwd(argvars, rettv)
10651 typval_T *argvars;
10652 typval_T *rettv;
10654 char_u cwd[MAXPATHL];
10656 rettv->v_type = VAR_STRING;
10657 if (mch_dirname(cwd, MAXPATHL) == FAIL)
10658 rettv->vval.v_string = NULL;
10659 else
10661 rettv->vval.v_string = vim_strsave(cwd);
10662 #ifdef BACKSLASH_IN_FILENAME
10663 if (rettv->vval.v_string != NULL)
10664 slash_adjust(rettv->vval.v_string);
10665 #endif
10670 * "getfontname()" function
10672 /*ARGSUSED*/
10673 static void
10674 f_getfontname(argvars, rettv)
10675 typval_T *argvars;
10676 typval_T *rettv;
10678 rettv->v_type = VAR_STRING;
10679 rettv->vval.v_string = NULL;
10680 #ifdef FEAT_GUI
10681 if (gui.in_use)
10683 GuiFont font;
10684 char_u *name = NULL;
10686 if (argvars[0].v_type == VAR_UNKNOWN)
10688 /* Get the "Normal" font. Either the name saved by
10689 * hl_set_font_name() or from the font ID. */
10690 font = gui.norm_font;
10691 name = hl_get_font_name();
10693 else
10695 name = get_tv_string(&argvars[0]);
10696 if (STRCMP(name, "*") == 0) /* don't use font dialog */
10697 return;
10698 font = gui_mch_get_font(name, FALSE);
10699 if (font == NOFONT)
10700 return; /* Invalid font name, return empty string. */
10702 rettv->vval.v_string = gui_mch_get_fontname(font, name);
10703 if (argvars[0].v_type != VAR_UNKNOWN)
10704 gui_mch_free_font(font);
10706 #endif
10710 * "getfperm({fname})" function
10712 static void
10713 f_getfperm(argvars, rettv)
10714 typval_T *argvars;
10715 typval_T *rettv;
10717 char_u *fname;
10718 struct stat st;
10719 char_u *perm = NULL;
10720 char_u flags[] = "rwx";
10721 int i;
10723 fname = get_tv_string(&argvars[0]);
10725 rettv->v_type = VAR_STRING;
10726 if (mch_stat((char *)fname, &st) >= 0)
10728 perm = vim_strsave((char_u *)"---------");
10729 if (perm != NULL)
10731 for (i = 0; i < 9; i++)
10733 if (st.st_mode & (1 << (8 - i)))
10734 perm[i] = flags[i % 3];
10738 rettv->vval.v_string = perm;
10742 * "getfsize({fname})" function
10744 static void
10745 f_getfsize(argvars, rettv)
10746 typval_T *argvars;
10747 typval_T *rettv;
10749 char_u *fname;
10750 struct stat st;
10752 fname = get_tv_string(&argvars[0]);
10754 rettv->v_type = VAR_NUMBER;
10756 if (mch_stat((char *)fname, &st) >= 0)
10758 if (mch_isdir(fname))
10759 rettv->vval.v_number = 0;
10760 else
10762 rettv->vval.v_number = (varnumber_T)st.st_size;
10764 /* non-perfect check for overflow */
10765 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
10766 rettv->vval.v_number = -2;
10769 else
10770 rettv->vval.v_number = -1;
10774 * "getftime({fname})" function
10776 static void
10777 f_getftime(argvars, rettv)
10778 typval_T *argvars;
10779 typval_T *rettv;
10781 char_u *fname;
10782 struct stat st;
10784 fname = get_tv_string(&argvars[0]);
10786 if (mch_stat((char *)fname, &st) >= 0)
10787 rettv->vval.v_number = (varnumber_T)st.st_mtime;
10788 else
10789 rettv->vval.v_number = -1;
10793 * "getftype({fname})" function
10795 static void
10796 f_getftype(argvars, rettv)
10797 typval_T *argvars;
10798 typval_T *rettv;
10800 char_u *fname;
10801 struct stat st;
10802 char_u *type = NULL;
10803 char *t;
10805 fname = get_tv_string(&argvars[0]);
10807 rettv->v_type = VAR_STRING;
10808 if (mch_lstat((char *)fname, &st) >= 0)
10810 #ifdef S_ISREG
10811 if (S_ISREG(st.st_mode))
10812 t = "file";
10813 else if (S_ISDIR(st.st_mode))
10814 t = "dir";
10815 # ifdef S_ISLNK
10816 else if (S_ISLNK(st.st_mode))
10817 t = "link";
10818 # endif
10819 # ifdef S_ISBLK
10820 else if (S_ISBLK(st.st_mode))
10821 t = "bdev";
10822 # endif
10823 # ifdef S_ISCHR
10824 else if (S_ISCHR(st.st_mode))
10825 t = "cdev";
10826 # endif
10827 # ifdef S_ISFIFO
10828 else if (S_ISFIFO(st.st_mode))
10829 t = "fifo";
10830 # endif
10831 # ifdef S_ISSOCK
10832 else if (S_ISSOCK(st.st_mode))
10833 t = "fifo";
10834 # endif
10835 else
10836 t = "other";
10837 #else
10838 # ifdef S_IFMT
10839 switch (st.st_mode & S_IFMT)
10841 case S_IFREG: t = "file"; break;
10842 case S_IFDIR: t = "dir"; break;
10843 # ifdef S_IFLNK
10844 case S_IFLNK: t = "link"; break;
10845 # endif
10846 # ifdef S_IFBLK
10847 case S_IFBLK: t = "bdev"; break;
10848 # endif
10849 # ifdef S_IFCHR
10850 case S_IFCHR: t = "cdev"; break;
10851 # endif
10852 # ifdef S_IFIFO
10853 case S_IFIFO: t = "fifo"; break;
10854 # endif
10855 # ifdef S_IFSOCK
10856 case S_IFSOCK: t = "socket"; break;
10857 # endif
10858 default: t = "other";
10860 # else
10861 if (mch_isdir(fname))
10862 t = "dir";
10863 else
10864 t = "file";
10865 # endif
10866 #endif
10867 type = vim_strsave((char_u *)t);
10869 rettv->vval.v_string = type;
10873 * "getline(lnum, [end])" function
10875 static void
10876 f_getline(argvars, rettv)
10877 typval_T *argvars;
10878 typval_T *rettv;
10880 linenr_T lnum;
10881 linenr_T end;
10882 int retlist;
10884 lnum = get_tv_lnum(argvars);
10885 if (argvars[1].v_type == VAR_UNKNOWN)
10887 end = 0;
10888 retlist = FALSE;
10890 else
10892 end = get_tv_lnum(&argvars[1]);
10893 retlist = TRUE;
10896 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
10900 * "getmatches()" function
10902 /*ARGSUSED*/
10903 static void
10904 f_getmatches(argvars, rettv)
10905 typval_T *argvars;
10906 typval_T *rettv;
10908 #ifdef FEAT_SEARCH_EXTRA
10909 dict_T *dict;
10910 matchitem_T *cur = curwin->w_match_head;
10912 rettv->vval.v_number = 0;
10914 if (rettv_list_alloc(rettv) == OK)
10916 while (cur != NULL)
10918 dict = dict_alloc();
10919 if (dict == NULL)
10920 return;
10921 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
10922 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
10923 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
10924 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
10925 list_append_dict(rettv->vval.v_list, dict);
10926 cur = cur->next;
10929 #endif
10933 * "getpid()" function
10935 /*ARGSUSED*/
10936 static void
10937 f_getpid(argvars, rettv)
10938 typval_T *argvars;
10939 typval_T *rettv;
10941 rettv->vval.v_number = mch_get_pid();
10945 * "getpos(string)" function
10947 static void
10948 f_getpos(argvars, rettv)
10949 typval_T *argvars;
10950 typval_T *rettv;
10952 pos_T *fp;
10953 list_T *l;
10954 int fnum = -1;
10956 if (rettv_list_alloc(rettv) == OK)
10958 l = rettv->vval.v_list;
10959 fp = var2fpos(&argvars[0], TRUE, &fnum);
10960 if (fnum != -1)
10961 list_append_number(l, (varnumber_T)fnum);
10962 else
10963 list_append_number(l, (varnumber_T)0);
10964 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
10965 : (varnumber_T)0);
10966 list_append_number(l, (fp != NULL)
10967 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
10968 : (varnumber_T)0);
10969 list_append_number(l,
10970 #ifdef FEAT_VIRTUALEDIT
10971 (fp != NULL) ? (varnumber_T)fp->coladd :
10972 #endif
10973 (varnumber_T)0);
10975 else
10976 rettv->vval.v_number = FALSE;
10980 * "getqflist()" and "getloclist()" functions
10982 /*ARGSUSED*/
10983 static void
10984 f_getqflist(argvars, rettv)
10985 typval_T *argvars;
10986 typval_T *rettv;
10988 #ifdef FEAT_QUICKFIX
10989 win_T *wp;
10990 #endif
10992 rettv->vval.v_number = 0;
10993 #ifdef FEAT_QUICKFIX
10994 if (rettv_list_alloc(rettv) == OK)
10996 wp = NULL;
10997 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
10999 wp = find_win_by_nr(&argvars[0], NULL);
11000 if (wp == NULL)
11001 return;
11004 (void)get_errorlist(wp, rettv->vval.v_list);
11006 #endif
11010 * "getreg()" function
11012 static void
11013 f_getreg(argvars, rettv)
11014 typval_T *argvars;
11015 typval_T *rettv;
11017 char_u *strregname;
11018 int regname;
11019 int arg2 = FALSE;
11020 int error = FALSE;
11022 if (argvars[0].v_type != VAR_UNKNOWN)
11024 strregname = get_tv_string_chk(&argvars[0]);
11025 error = strregname == NULL;
11026 if (argvars[1].v_type != VAR_UNKNOWN)
11027 arg2 = get_tv_number_chk(&argvars[1], &error);
11029 else
11030 strregname = vimvars[VV_REG].vv_str;
11031 regname = (strregname == NULL ? '"' : *strregname);
11032 if (regname == 0)
11033 regname = '"';
11035 rettv->v_type = VAR_STRING;
11036 rettv->vval.v_string = error ? NULL :
11037 get_reg_contents(regname, TRUE, arg2);
11041 * "getregtype()" function
11043 static void
11044 f_getregtype(argvars, rettv)
11045 typval_T *argvars;
11046 typval_T *rettv;
11048 char_u *strregname;
11049 int regname;
11050 char_u buf[NUMBUFLEN + 2];
11051 long reglen = 0;
11053 if (argvars[0].v_type != VAR_UNKNOWN)
11055 strregname = get_tv_string_chk(&argvars[0]);
11056 if (strregname == NULL) /* type error; errmsg already given */
11058 rettv->v_type = VAR_STRING;
11059 rettv->vval.v_string = NULL;
11060 return;
11063 else
11064 /* Default to v:register */
11065 strregname = vimvars[VV_REG].vv_str;
11067 regname = (strregname == NULL ? '"' : *strregname);
11068 if (regname == 0)
11069 regname = '"';
11071 buf[0] = NUL;
11072 buf[1] = NUL;
11073 switch (get_reg_type(regname, &reglen))
11075 case MLINE: buf[0] = 'V'; break;
11076 case MCHAR: buf[0] = 'v'; break;
11077 #ifdef FEAT_VISUAL
11078 case MBLOCK:
11079 buf[0] = Ctrl_V;
11080 sprintf((char *)buf + 1, "%ld", reglen + 1);
11081 break;
11082 #endif
11084 rettv->v_type = VAR_STRING;
11085 rettv->vval.v_string = vim_strsave(buf);
11089 * "gettabwinvar()" function
11091 static void
11092 f_gettabwinvar(argvars, rettv)
11093 typval_T *argvars;
11094 typval_T *rettv;
11096 getwinvar(argvars, rettv, 1);
11100 * "getwinposx()" function
11102 /*ARGSUSED*/
11103 static void
11104 f_getwinposx(argvars, rettv)
11105 typval_T *argvars;
11106 typval_T *rettv;
11108 rettv->vval.v_number = -1;
11109 #ifdef FEAT_GUI
11110 if (gui.in_use)
11112 int x, y;
11114 if (gui_mch_get_winpos(&x, &y) == OK)
11115 rettv->vval.v_number = x;
11117 #endif
11121 * "getwinposy()" function
11123 /*ARGSUSED*/
11124 static void
11125 f_getwinposy(argvars, rettv)
11126 typval_T *argvars;
11127 typval_T *rettv;
11129 rettv->vval.v_number = -1;
11130 #ifdef FEAT_GUI
11131 if (gui.in_use)
11133 int x, y;
11135 if (gui_mch_get_winpos(&x, &y) == OK)
11136 rettv->vval.v_number = y;
11138 #endif
11142 * Find window specified by "vp" in tabpage "tp".
11144 static win_T *
11145 find_win_by_nr(vp, tp)
11146 typval_T *vp;
11147 tabpage_T *tp; /* NULL for current tab page */
11149 #ifdef FEAT_WINDOWS
11150 win_T *wp;
11151 #endif
11152 int nr;
11154 nr = get_tv_number_chk(vp, NULL);
11156 #ifdef FEAT_WINDOWS
11157 if (nr < 0)
11158 return NULL;
11159 if (nr == 0)
11160 return curwin;
11162 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
11163 wp != NULL; wp = wp->w_next)
11164 if (--nr <= 0)
11165 break;
11166 return wp;
11167 #else
11168 if (nr == 0 || nr == 1)
11169 return curwin;
11170 return NULL;
11171 #endif
11175 * "getwinvar()" function
11177 static void
11178 f_getwinvar(argvars, rettv)
11179 typval_T *argvars;
11180 typval_T *rettv;
11182 getwinvar(argvars, rettv, 0);
11186 * getwinvar() and gettabwinvar()
11188 static void
11189 getwinvar(argvars, rettv, off)
11190 typval_T *argvars;
11191 typval_T *rettv;
11192 int off; /* 1 for gettabwinvar() */
11194 win_T *win, *oldcurwin;
11195 char_u *varname;
11196 dictitem_T *v;
11197 tabpage_T *tp;
11199 #ifdef FEAT_WINDOWS
11200 if (off == 1)
11201 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
11202 else
11203 tp = curtab;
11204 #endif
11205 win = find_win_by_nr(&argvars[off], tp);
11206 varname = get_tv_string_chk(&argvars[off + 1]);
11207 ++emsg_off;
11209 rettv->v_type = VAR_STRING;
11210 rettv->vval.v_string = NULL;
11212 if (win != NULL && varname != NULL)
11214 /* Set curwin to be our win, temporarily. Also set curbuf, so
11215 * that we can get buffer-local options. */
11216 oldcurwin = curwin;
11217 curwin = win;
11218 curbuf = win->w_buffer;
11220 if (*varname == '&') /* window-local-option */
11221 get_option_tv(&varname, rettv, 1);
11222 else
11224 if (*varname == NUL)
11225 /* let getwinvar({nr}, "") return the "w:" dictionary. The
11226 * scope prefix before the NUL byte is required by
11227 * find_var_in_ht(). */
11228 varname = (char_u *)"w:" + 2;
11229 /* look up the variable */
11230 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
11231 if (v != NULL)
11232 copy_tv(&v->di_tv, rettv);
11235 /* restore previous notion of curwin */
11236 curwin = oldcurwin;
11237 curbuf = curwin->w_buffer;
11240 --emsg_off;
11244 * "glob()" function
11246 static void
11247 f_glob(argvars, rettv)
11248 typval_T *argvars;
11249 typval_T *rettv;
11251 expand_T xpc;
11253 ExpandInit(&xpc);
11254 xpc.xp_context = EXPAND_FILES;
11255 rettv->v_type = VAR_STRING;
11256 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
11257 NULL, WILD_USE_NL|WILD_SILENT, WILD_ALL);
11261 * "globpath()" function
11263 static void
11264 f_globpath(argvars, rettv)
11265 typval_T *argvars;
11266 typval_T *rettv;
11268 char_u buf1[NUMBUFLEN];
11269 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
11271 rettv->v_type = VAR_STRING;
11272 if (file == NULL)
11273 rettv->vval.v_string = NULL;
11274 else
11275 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file);
11279 * "has()" function
11281 static void
11282 f_has(argvars, rettv)
11283 typval_T *argvars;
11284 typval_T *rettv;
11286 int i;
11287 char_u *name;
11288 int n = FALSE;
11289 static char *(has_list[]) =
11291 #ifdef AMIGA
11292 "amiga",
11293 # ifdef FEAT_ARP
11294 "arp",
11295 # endif
11296 #endif
11297 #ifdef __BEOS__
11298 "beos",
11299 #endif
11300 #ifdef MSDOS
11301 # ifdef DJGPP
11302 "dos32",
11303 # else
11304 "dos16",
11305 # endif
11306 #endif
11307 #ifdef MACOS
11308 "mac",
11309 #endif
11310 #if defined(MACOS_X_UNIX)
11311 "macunix",
11312 #endif
11313 #ifdef OS2
11314 "os2",
11315 #endif
11316 #ifdef __QNX__
11317 "qnx",
11318 #endif
11319 #ifdef RISCOS
11320 "riscos",
11321 #endif
11322 #ifdef UNIX
11323 "unix",
11324 #endif
11325 #ifdef VMS
11326 "vms",
11327 #endif
11328 #ifdef WIN16
11329 "win16",
11330 #endif
11331 #ifdef WIN32
11332 "win32",
11333 #endif
11334 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
11335 "win32unix",
11336 #endif
11337 #ifdef WIN64
11338 "win64",
11339 #endif
11340 #ifdef EBCDIC
11341 "ebcdic",
11342 #endif
11343 #ifndef CASE_INSENSITIVE_FILENAME
11344 "fname_case",
11345 #endif
11346 #ifdef FEAT_ARABIC
11347 "arabic",
11348 #endif
11349 #ifdef FEAT_AUTOCMD
11350 "autocmd",
11351 #endif
11352 #ifdef FEAT_BEVAL
11353 "balloon_eval",
11354 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
11355 "balloon_multiline",
11356 # endif
11357 #endif
11358 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
11359 "builtin_terms",
11360 # ifdef ALL_BUILTIN_TCAPS
11361 "all_builtin_terms",
11362 # endif
11363 #endif
11364 #ifdef FEAT_BYTEOFF
11365 "byte_offset",
11366 #endif
11367 #ifdef FEAT_CINDENT
11368 "cindent",
11369 #endif
11370 #ifdef FEAT_CLIENTSERVER
11371 "clientserver",
11372 #endif
11373 #ifdef FEAT_CLIPBOARD
11374 "clipboard",
11375 #endif
11376 #ifdef FEAT_CMDL_COMPL
11377 "cmdline_compl",
11378 #endif
11379 #ifdef FEAT_CMDHIST
11380 "cmdline_hist",
11381 #endif
11382 #ifdef FEAT_COMMENTS
11383 "comments",
11384 #endif
11385 #ifdef FEAT_CRYPT
11386 "cryptv",
11387 #endif
11388 #ifdef FEAT_CSCOPE
11389 "cscope",
11390 #endif
11391 #ifdef CURSOR_SHAPE
11392 "cursorshape",
11393 #endif
11394 #ifdef DEBUG
11395 "debug",
11396 #endif
11397 #ifdef FEAT_CON_DIALOG
11398 "dialog_con",
11399 #endif
11400 #ifdef FEAT_GUI_DIALOG
11401 "dialog_gui",
11402 #endif
11403 #ifdef FEAT_DIFF
11404 "diff",
11405 #endif
11406 #ifdef FEAT_DIGRAPHS
11407 "digraphs",
11408 #endif
11409 #ifdef FEAT_DND
11410 "dnd",
11411 #endif
11412 #ifdef FEAT_EMACS_TAGS
11413 "emacs_tags",
11414 #endif
11415 "eval", /* always present, of course! */
11416 #ifdef FEAT_EX_EXTRA
11417 "ex_extra",
11418 #endif
11419 #ifdef FEAT_SEARCH_EXTRA
11420 "extra_search",
11421 #endif
11422 #ifdef FEAT_FKMAP
11423 "farsi",
11424 #endif
11425 #ifdef FEAT_SEARCHPATH
11426 "file_in_path",
11427 #endif
11428 #if defined(UNIX) && !defined(USE_SYSTEM)
11429 "filterpipe",
11430 #endif
11431 #ifdef FEAT_FIND_ID
11432 "find_in_path",
11433 #endif
11434 #ifdef FEAT_FLOAT
11435 "float",
11436 #endif
11437 #ifdef FEAT_FOLDING
11438 "folding",
11439 #endif
11440 #ifdef FEAT_FOOTER
11441 "footer",
11442 #endif
11443 #if !defined(USE_SYSTEM) && defined(UNIX)
11444 "fork",
11445 #endif
11446 #ifdef FEAT_GETTEXT
11447 "gettext",
11448 #endif
11449 #ifdef FEAT_GUI
11450 "gui",
11451 #endif
11452 #ifdef FEAT_GUI_ATHENA
11453 # ifdef FEAT_GUI_NEXTAW
11454 "gui_neXtaw",
11455 # else
11456 "gui_athena",
11457 # endif
11458 #endif
11459 #ifdef FEAT_GUI_GTK
11460 "gui_gtk",
11461 # ifdef HAVE_GTK2
11462 "gui_gtk2",
11463 # endif
11464 #endif
11465 #ifdef FEAT_GUI_GNOME
11466 "gui_gnome",
11467 #endif
11468 #ifdef FEAT_GUI_MAC
11469 "gui_mac",
11470 #endif
11471 #ifdef FEAT_GUI_MOTIF
11472 "gui_motif",
11473 #endif
11474 #ifdef FEAT_GUI_PHOTON
11475 "gui_photon",
11476 #endif
11477 #ifdef FEAT_GUI_W16
11478 "gui_win16",
11479 #endif
11480 #ifdef FEAT_GUI_W32
11481 "gui_win32",
11482 #endif
11483 #ifdef FEAT_HANGULIN
11484 "hangul_input",
11485 #endif
11486 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
11487 "iconv",
11488 #endif
11489 #ifdef FEAT_INS_EXPAND
11490 "insert_expand",
11491 #endif
11492 #ifdef FEAT_JUMPLIST
11493 "jumplist",
11494 #endif
11495 #ifdef FEAT_KEYMAP
11496 "keymap",
11497 #endif
11498 #ifdef FEAT_LANGMAP
11499 "langmap",
11500 #endif
11501 #ifdef FEAT_LIBCALL
11502 "libcall",
11503 #endif
11504 #ifdef FEAT_LINEBREAK
11505 "linebreak",
11506 #endif
11507 #ifdef FEAT_LISP
11508 "lispindent",
11509 #endif
11510 #ifdef FEAT_LISTCMDS
11511 "listcmds",
11512 #endif
11513 #ifdef FEAT_LOCALMAP
11514 "localmap",
11515 #endif
11516 #ifdef FEAT_MENU
11517 "menu",
11518 #endif
11519 #ifdef FEAT_SESSION
11520 "mksession",
11521 #endif
11522 #ifdef FEAT_MODIFY_FNAME
11523 "modify_fname",
11524 #endif
11525 #ifdef FEAT_MOUSE
11526 "mouse",
11527 #endif
11528 #ifdef FEAT_MOUSESHAPE
11529 "mouseshape",
11530 #endif
11531 #if defined(UNIX) || defined(VMS)
11532 # ifdef FEAT_MOUSE_DEC
11533 "mouse_dec",
11534 # endif
11535 # ifdef FEAT_MOUSE_GPM
11536 "mouse_gpm",
11537 # endif
11538 # ifdef FEAT_MOUSE_JSB
11539 "mouse_jsbterm",
11540 # endif
11541 # ifdef FEAT_MOUSE_NET
11542 "mouse_netterm",
11543 # endif
11544 # ifdef FEAT_MOUSE_PTERM
11545 "mouse_pterm",
11546 # endif
11547 # ifdef FEAT_SYSMOUSE
11548 "mouse_sysmouse",
11549 # endif
11550 # ifdef FEAT_MOUSE_XTERM
11551 "mouse_xterm",
11552 # endif
11553 #endif
11554 #ifdef FEAT_MBYTE
11555 "multi_byte",
11556 #endif
11557 #ifdef FEAT_MBYTE_IME
11558 "multi_byte_ime",
11559 #endif
11560 #ifdef FEAT_MULTI_LANG
11561 "multi_lang",
11562 #endif
11563 #ifdef FEAT_MZSCHEME
11564 #ifndef DYNAMIC_MZSCHEME
11565 "mzscheme",
11566 #endif
11567 #endif
11568 #ifdef FEAT_OLE
11569 "ole",
11570 #endif
11571 #ifdef FEAT_OSFILETYPE
11572 "osfiletype",
11573 #endif
11574 #ifdef FEAT_PATH_EXTRA
11575 "path_extra",
11576 #endif
11577 #ifdef FEAT_PERL
11578 #ifndef DYNAMIC_PERL
11579 "perl",
11580 #endif
11581 #endif
11582 #ifdef FEAT_PYTHON
11583 #ifndef DYNAMIC_PYTHON
11584 "python",
11585 #endif
11586 #endif
11587 #ifdef FEAT_POSTSCRIPT
11588 "postscript",
11589 #endif
11590 #ifdef FEAT_PRINTER
11591 "printer",
11592 #endif
11593 #ifdef FEAT_PROFILE
11594 "profile",
11595 #endif
11596 #ifdef FEAT_RELTIME
11597 "reltime",
11598 #endif
11599 #ifdef FEAT_QUICKFIX
11600 "quickfix",
11601 #endif
11602 #ifdef FEAT_RIGHTLEFT
11603 "rightleft",
11604 #endif
11605 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11606 "ruby",
11607 #endif
11608 #ifdef FEAT_SCROLLBIND
11609 "scrollbind",
11610 #endif
11611 #ifdef FEAT_CMDL_INFO
11612 "showcmd",
11613 "cmdline_info",
11614 #endif
11615 #ifdef FEAT_SIGNS
11616 "signs",
11617 #endif
11618 #ifdef FEAT_SMARTINDENT
11619 "smartindent",
11620 #endif
11621 #ifdef FEAT_SNIFF
11622 "sniff",
11623 #endif
11624 #ifdef FEAT_STL_OPT
11625 "statusline",
11626 #endif
11627 #ifdef FEAT_SUN_WORKSHOP
11628 "sun_workshop",
11629 #endif
11630 #ifdef FEAT_NETBEANS_INTG
11631 "netbeans_intg",
11632 #endif
11633 #ifdef FEAT_SPELL
11634 "spell",
11635 #endif
11636 #ifdef FEAT_SYN_HL
11637 "syntax",
11638 #endif
11639 #if defined(USE_SYSTEM) || !defined(UNIX)
11640 "system",
11641 #endif
11642 #ifdef FEAT_TAG_BINS
11643 "tag_binary",
11644 #endif
11645 #ifdef FEAT_TAG_OLDSTATIC
11646 "tag_old_static",
11647 #endif
11648 #ifdef FEAT_TAG_ANYWHITE
11649 "tag_any_white",
11650 #endif
11651 #ifdef FEAT_TCL
11652 # ifndef DYNAMIC_TCL
11653 "tcl",
11654 # endif
11655 #endif
11656 #ifdef TERMINFO
11657 "terminfo",
11658 #endif
11659 #ifdef FEAT_TERMRESPONSE
11660 "termresponse",
11661 #endif
11662 #ifdef FEAT_TEXTOBJ
11663 "textobjects",
11664 #endif
11665 #ifdef HAVE_TGETENT
11666 "tgetent",
11667 #endif
11668 #ifdef FEAT_TITLE
11669 "title",
11670 #endif
11671 #ifdef FEAT_TOOLBAR
11672 "toolbar",
11673 #endif
11674 #ifdef FEAT_USR_CMDS
11675 "user-commands", /* was accidentally included in 5.4 */
11676 "user_commands",
11677 #endif
11678 #ifdef FEAT_VIMINFO
11679 "viminfo",
11680 #endif
11681 #ifdef FEAT_VERTSPLIT
11682 "vertsplit",
11683 #endif
11684 #ifdef FEAT_VIRTUALEDIT
11685 "virtualedit",
11686 #endif
11687 #ifdef FEAT_VISUAL
11688 "visual",
11689 #endif
11690 #ifdef FEAT_VISUALEXTRA
11691 "visualextra",
11692 #endif
11693 #ifdef FEAT_VREPLACE
11694 "vreplace",
11695 #endif
11696 #ifdef FEAT_WILDIGN
11697 "wildignore",
11698 #endif
11699 #ifdef FEAT_WILDMENU
11700 "wildmenu",
11701 #endif
11702 #ifdef FEAT_WINDOWS
11703 "windows",
11704 #endif
11705 #ifdef FEAT_WAK
11706 "winaltkeys",
11707 #endif
11708 #ifdef FEAT_WRITEBACKUP
11709 "writebackup",
11710 #endif
11711 #ifdef FEAT_XIM
11712 "xim",
11713 #endif
11714 #ifdef FEAT_XFONTSET
11715 "xfontset",
11716 #endif
11717 #ifdef USE_XSMP
11718 "xsmp",
11719 #endif
11720 #ifdef USE_XSMP_INTERACT
11721 "xsmp_interact",
11722 #endif
11723 #ifdef FEAT_XCLIPBOARD
11724 "xterm_clipboard",
11725 #endif
11726 #ifdef FEAT_XTERM_SAVE
11727 "xterm_save",
11728 #endif
11729 #if defined(UNIX) && defined(FEAT_X11)
11730 "X11",
11731 #endif
11732 NULL
11735 name = get_tv_string(&argvars[0]);
11736 for (i = 0; has_list[i] != NULL; ++i)
11737 if (STRICMP(name, has_list[i]) == 0)
11739 n = TRUE;
11740 break;
11743 if (n == FALSE)
11745 if (STRNICMP(name, "patch", 5) == 0)
11746 n = has_patch(atoi((char *)name + 5));
11747 else if (STRICMP(name, "vim_starting") == 0)
11748 n = (starting != 0);
11749 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
11750 else if (STRICMP(name, "balloon_multiline") == 0)
11751 n = multiline_balloon_available();
11752 #endif
11753 #ifdef DYNAMIC_TCL
11754 else if (STRICMP(name, "tcl") == 0)
11755 n = tcl_enabled(FALSE);
11756 #endif
11757 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
11758 else if (STRICMP(name, "iconv") == 0)
11759 n = iconv_enabled(FALSE);
11760 #endif
11761 #ifdef DYNAMIC_MZSCHEME
11762 else if (STRICMP(name, "mzscheme") == 0)
11763 n = mzscheme_enabled(FALSE);
11764 #endif
11765 #ifdef DYNAMIC_RUBY
11766 else if (STRICMP(name, "ruby") == 0)
11767 n = ruby_enabled(FALSE);
11768 #endif
11769 #ifdef DYNAMIC_PYTHON
11770 else if (STRICMP(name, "python") == 0)
11771 n = python_enabled(FALSE);
11772 #endif
11773 #ifdef DYNAMIC_PERL
11774 else if (STRICMP(name, "perl") == 0)
11775 n = perl_enabled(FALSE);
11776 #endif
11777 #ifdef FEAT_GUI
11778 else if (STRICMP(name, "gui_running") == 0)
11779 n = (gui.in_use || gui.starting);
11780 # ifdef FEAT_GUI_W32
11781 else if (STRICMP(name, "gui_win32s") == 0)
11782 n = gui_is_win32s();
11783 # endif
11784 # ifdef FEAT_BROWSE
11785 else if (STRICMP(name, "browse") == 0)
11786 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
11787 # endif
11788 #endif
11789 #ifdef FEAT_SYN_HL
11790 else if (STRICMP(name, "syntax_items") == 0)
11791 n = syntax_present(curbuf);
11792 #endif
11793 #if defined(WIN3264)
11794 else if (STRICMP(name, "win95") == 0)
11795 n = mch_windows95();
11796 #endif
11797 #ifdef FEAT_NETBEANS_INTG
11798 else if (STRICMP(name, "netbeans_enabled") == 0)
11799 n = usingNetbeans;
11800 #endif
11803 rettv->vval.v_number = n;
11807 * "has_key()" function
11809 static void
11810 f_has_key(argvars, rettv)
11811 typval_T *argvars;
11812 typval_T *rettv;
11814 rettv->vval.v_number = 0;
11815 if (argvars[0].v_type != VAR_DICT)
11817 EMSG(_(e_dictreq));
11818 return;
11820 if (argvars[0].vval.v_dict == NULL)
11821 return;
11823 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
11824 get_tv_string(&argvars[1]), -1) != NULL;
11828 * "haslocaldir()" function
11830 /*ARGSUSED*/
11831 static void
11832 f_haslocaldir(argvars, rettv)
11833 typval_T *argvars;
11834 typval_T *rettv;
11836 rettv->vval.v_number = (curwin->w_localdir != NULL);
11840 * "hasmapto()" function
11842 static void
11843 f_hasmapto(argvars, rettv)
11844 typval_T *argvars;
11845 typval_T *rettv;
11847 char_u *name;
11848 char_u *mode;
11849 char_u buf[NUMBUFLEN];
11850 int abbr = FALSE;
11852 name = get_tv_string(&argvars[0]);
11853 if (argvars[1].v_type == VAR_UNKNOWN)
11854 mode = (char_u *)"nvo";
11855 else
11857 mode = get_tv_string_buf(&argvars[1], buf);
11858 if (argvars[2].v_type != VAR_UNKNOWN)
11859 abbr = get_tv_number(&argvars[2]);
11862 if (map_to_exists(name, mode, abbr))
11863 rettv->vval.v_number = TRUE;
11864 else
11865 rettv->vval.v_number = FALSE;
11869 * "histadd()" function
11871 /*ARGSUSED*/
11872 static void
11873 f_histadd(argvars, rettv)
11874 typval_T *argvars;
11875 typval_T *rettv;
11877 #ifdef FEAT_CMDHIST
11878 int histype;
11879 char_u *str;
11880 char_u buf[NUMBUFLEN];
11881 #endif
11883 rettv->vval.v_number = FALSE;
11884 if (check_restricted() || check_secure())
11885 return;
11886 #ifdef FEAT_CMDHIST
11887 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11888 histype = str != NULL ? get_histtype(str) : -1;
11889 if (histype >= 0)
11891 str = get_tv_string_buf(&argvars[1], buf);
11892 if (*str != NUL)
11894 add_to_history(histype, str, FALSE, NUL);
11895 rettv->vval.v_number = TRUE;
11896 return;
11899 #endif
11903 * "histdel()" function
11905 /*ARGSUSED*/
11906 static void
11907 f_histdel(argvars, rettv)
11908 typval_T *argvars;
11909 typval_T *rettv;
11911 #ifdef FEAT_CMDHIST
11912 int n;
11913 char_u buf[NUMBUFLEN];
11914 char_u *str;
11916 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11917 if (str == NULL)
11918 n = 0;
11919 else if (argvars[1].v_type == VAR_UNKNOWN)
11920 /* only one argument: clear entire history */
11921 n = clr_history(get_histtype(str));
11922 else if (argvars[1].v_type == VAR_NUMBER)
11923 /* index given: remove that entry */
11924 n = del_history_idx(get_histtype(str),
11925 (int)get_tv_number(&argvars[1]));
11926 else
11927 /* string given: remove all matching entries */
11928 n = del_history_entry(get_histtype(str),
11929 get_tv_string_buf(&argvars[1], buf));
11930 rettv->vval.v_number = n;
11931 #else
11932 rettv->vval.v_number = 0;
11933 #endif
11937 * "histget()" function
11939 /*ARGSUSED*/
11940 static void
11941 f_histget(argvars, rettv)
11942 typval_T *argvars;
11943 typval_T *rettv;
11945 #ifdef FEAT_CMDHIST
11946 int type;
11947 int idx;
11948 char_u *str;
11950 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11951 if (str == NULL)
11952 rettv->vval.v_string = NULL;
11953 else
11955 type = get_histtype(str);
11956 if (argvars[1].v_type == VAR_UNKNOWN)
11957 idx = get_history_idx(type);
11958 else
11959 idx = (int)get_tv_number_chk(&argvars[1], NULL);
11960 /* -1 on type error */
11961 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
11963 #else
11964 rettv->vval.v_string = NULL;
11965 #endif
11966 rettv->v_type = VAR_STRING;
11970 * "histnr()" function
11972 /*ARGSUSED*/
11973 static void
11974 f_histnr(argvars, rettv)
11975 typval_T *argvars;
11976 typval_T *rettv;
11978 int i;
11980 #ifdef FEAT_CMDHIST
11981 char_u *history = get_tv_string_chk(&argvars[0]);
11983 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
11984 if (i >= HIST_CMD && i < HIST_COUNT)
11985 i = get_history_idx(i);
11986 else
11987 #endif
11988 i = -1;
11989 rettv->vval.v_number = i;
11993 * "highlightID(name)" function
11995 static void
11996 f_hlID(argvars, rettv)
11997 typval_T *argvars;
11998 typval_T *rettv;
12000 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
12004 * "highlight_exists()" function
12006 static void
12007 f_hlexists(argvars, rettv)
12008 typval_T *argvars;
12009 typval_T *rettv;
12011 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
12015 * "hostname()" function
12017 /*ARGSUSED*/
12018 static void
12019 f_hostname(argvars, rettv)
12020 typval_T *argvars;
12021 typval_T *rettv;
12023 char_u hostname[256];
12025 mch_get_host_name(hostname, 256);
12026 rettv->v_type = VAR_STRING;
12027 rettv->vval.v_string = vim_strsave(hostname);
12031 * iconv() function
12033 /*ARGSUSED*/
12034 static void
12035 f_iconv(argvars, rettv)
12036 typval_T *argvars;
12037 typval_T *rettv;
12039 #ifdef FEAT_MBYTE
12040 char_u buf1[NUMBUFLEN];
12041 char_u buf2[NUMBUFLEN];
12042 char_u *from, *to, *str;
12043 vimconv_T vimconv;
12044 #endif
12046 rettv->v_type = VAR_STRING;
12047 rettv->vval.v_string = NULL;
12049 #ifdef FEAT_MBYTE
12050 str = get_tv_string(&argvars[0]);
12051 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
12052 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
12053 vimconv.vc_type = CONV_NONE;
12054 convert_setup(&vimconv, from, to);
12056 /* If the encodings are equal, no conversion needed. */
12057 if (vimconv.vc_type == CONV_NONE)
12058 rettv->vval.v_string = vim_strsave(str);
12059 else
12060 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
12062 convert_setup(&vimconv, NULL, NULL);
12063 vim_free(from);
12064 vim_free(to);
12065 #endif
12069 * "indent()" function
12071 static void
12072 f_indent(argvars, rettv)
12073 typval_T *argvars;
12074 typval_T *rettv;
12076 linenr_T lnum;
12078 lnum = get_tv_lnum(argvars);
12079 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12080 rettv->vval.v_number = get_indent_lnum(lnum);
12081 else
12082 rettv->vval.v_number = -1;
12086 * "index()" function
12088 static void
12089 f_index(argvars, rettv)
12090 typval_T *argvars;
12091 typval_T *rettv;
12093 list_T *l;
12094 listitem_T *item;
12095 long idx = 0;
12096 int ic = FALSE;
12098 rettv->vval.v_number = -1;
12099 if (argvars[0].v_type != VAR_LIST)
12101 EMSG(_(e_listreq));
12102 return;
12104 l = argvars[0].vval.v_list;
12105 if (l != NULL)
12107 item = l->lv_first;
12108 if (argvars[2].v_type != VAR_UNKNOWN)
12110 int error = FALSE;
12112 /* Start at specified item. Use the cached index that list_find()
12113 * sets, so that a negative number also works. */
12114 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
12115 idx = l->lv_idx;
12116 if (argvars[3].v_type != VAR_UNKNOWN)
12117 ic = get_tv_number_chk(&argvars[3], &error);
12118 if (error)
12119 item = NULL;
12122 for ( ; item != NULL; item = item->li_next, ++idx)
12123 if (tv_equal(&item->li_tv, &argvars[1], ic))
12125 rettv->vval.v_number = idx;
12126 break;
12131 static int inputsecret_flag = 0;
12133 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
12136 * This function is used by f_input() and f_inputdialog() functions. The third
12137 * argument to f_input() specifies the type of completion to use at the
12138 * prompt. The third argument to f_inputdialog() specifies the value to return
12139 * when the user cancels the prompt.
12141 static void
12142 get_user_input(argvars, rettv, inputdialog)
12143 typval_T *argvars;
12144 typval_T *rettv;
12145 int inputdialog;
12147 char_u *prompt = get_tv_string_chk(&argvars[0]);
12148 char_u *p = NULL;
12149 int c;
12150 char_u buf[NUMBUFLEN];
12151 int cmd_silent_save = cmd_silent;
12152 char_u *defstr = (char_u *)"";
12153 int xp_type = EXPAND_NOTHING;
12154 char_u *xp_arg = NULL;
12156 rettv->v_type = VAR_STRING;
12157 rettv->vval.v_string = NULL;
12159 #ifdef NO_CONSOLE_INPUT
12160 /* While starting up, there is no place to enter text. */
12161 if (no_console_input())
12162 return;
12163 #endif
12165 cmd_silent = FALSE; /* Want to see the prompt. */
12166 if (prompt != NULL)
12168 /* Only the part of the message after the last NL is considered as
12169 * prompt for the command line */
12170 p = vim_strrchr(prompt, '\n');
12171 if (p == NULL)
12172 p = prompt;
12173 else
12175 ++p;
12176 c = *p;
12177 *p = NUL;
12178 msg_start();
12179 msg_clr_eos();
12180 msg_puts_attr(prompt, echo_attr);
12181 msg_didout = FALSE;
12182 msg_starthere();
12183 *p = c;
12185 cmdline_row = msg_row;
12187 if (argvars[1].v_type != VAR_UNKNOWN)
12189 defstr = get_tv_string_buf_chk(&argvars[1], buf);
12190 if (defstr != NULL)
12191 stuffReadbuffSpec(defstr);
12193 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
12195 char_u *xp_name;
12196 int xp_namelen;
12197 long argt;
12199 rettv->vval.v_string = NULL;
12201 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
12202 if (xp_name == NULL)
12203 return;
12205 xp_namelen = (int)STRLEN(xp_name);
12207 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
12208 &xp_arg) == FAIL)
12209 return;
12213 if (defstr != NULL)
12214 rettv->vval.v_string =
12215 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
12216 xp_type, xp_arg);
12218 vim_free(xp_arg);
12220 /* since the user typed this, no need to wait for return */
12221 need_wait_return = FALSE;
12222 msg_didout = FALSE;
12224 cmd_silent = cmd_silent_save;
12228 * "input()" function
12229 * Also handles inputsecret() when inputsecret is set.
12231 static void
12232 f_input(argvars, rettv)
12233 typval_T *argvars;
12234 typval_T *rettv;
12236 get_user_input(argvars, rettv, FALSE);
12240 * "inputdialog()" function
12242 static void
12243 f_inputdialog(argvars, rettv)
12244 typval_T *argvars;
12245 typval_T *rettv;
12247 #if defined(FEAT_GUI_TEXTDIALOG)
12248 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
12249 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
12251 char_u *message;
12252 char_u buf[NUMBUFLEN];
12253 char_u *defstr = (char_u *)"";
12255 message = get_tv_string_chk(&argvars[0]);
12256 if (argvars[1].v_type != VAR_UNKNOWN
12257 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
12258 vim_strncpy(IObuff, defstr, IOSIZE - 1);
12259 else
12260 IObuff[0] = NUL;
12261 if (message != NULL && defstr != NULL
12262 && do_dialog(VIM_QUESTION, NULL, message,
12263 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
12264 rettv->vval.v_string = vim_strsave(IObuff);
12265 else
12267 if (message != NULL && defstr != NULL
12268 && argvars[1].v_type != VAR_UNKNOWN
12269 && argvars[2].v_type != VAR_UNKNOWN)
12270 rettv->vval.v_string = vim_strsave(
12271 get_tv_string_buf(&argvars[2], buf));
12272 else
12273 rettv->vval.v_string = NULL;
12275 rettv->v_type = VAR_STRING;
12277 else
12278 #endif
12279 get_user_input(argvars, rettv, TRUE);
12283 * "inputlist()" function
12285 static void
12286 f_inputlist(argvars, rettv)
12287 typval_T *argvars;
12288 typval_T *rettv;
12290 listitem_T *li;
12291 int selected;
12292 int mouse_used;
12294 rettv->vval.v_number = 0;
12295 #ifdef NO_CONSOLE_INPUT
12296 /* While starting up, there is no place to enter text. */
12297 if (no_console_input())
12298 return;
12299 #endif
12300 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
12302 EMSG2(_(e_listarg), "inputlist()");
12303 return;
12306 msg_start();
12307 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
12308 lines_left = Rows; /* avoid more prompt */
12309 msg_scroll = TRUE;
12310 msg_clr_eos();
12312 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
12314 msg_puts(get_tv_string(&li->li_tv));
12315 msg_putchar('\n');
12318 /* Ask for choice. */
12319 selected = prompt_for_number(&mouse_used);
12320 if (mouse_used)
12321 selected -= lines_left;
12323 rettv->vval.v_number = selected;
12327 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
12330 * "inputrestore()" function
12332 /*ARGSUSED*/
12333 static void
12334 f_inputrestore(argvars, rettv)
12335 typval_T *argvars;
12336 typval_T *rettv;
12338 if (ga_userinput.ga_len > 0)
12340 --ga_userinput.ga_len;
12341 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
12342 + ga_userinput.ga_len);
12343 rettv->vval.v_number = 0; /* OK */
12345 else if (p_verbose > 1)
12347 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
12348 rettv->vval.v_number = 1; /* Failed */
12353 * "inputsave()" function
12355 /*ARGSUSED*/
12356 static void
12357 f_inputsave(argvars, rettv)
12358 typval_T *argvars;
12359 typval_T *rettv;
12361 /* Add an entry to the stack of typeahead storage. */
12362 if (ga_grow(&ga_userinput, 1) == OK)
12364 save_typeahead((tasave_T *)(ga_userinput.ga_data)
12365 + ga_userinput.ga_len);
12366 ++ga_userinput.ga_len;
12367 rettv->vval.v_number = 0; /* OK */
12369 else
12370 rettv->vval.v_number = 1; /* Failed */
12374 * "inputsecret()" function
12376 static void
12377 f_inputsecret(argvars, rettv)
12378 typval_T *argvars;
12379 typval_T *rettv;
12381 ++cmdline_star;
12382 ++inputsecret_flag;
12383 f_input(argvars, rettv);
12384 --cmdline_star;
12385 --inputsecret_flag;
12389 * "insert()" function
12391 static void
12392 f_insert(argvars, rettv)
12393 typval_T *argvars;
12394 typval_T *rettv;
12396 long before = 0;
12397 listitem_T *item;
12398 list_T *l;
12399 int error = FALSE;
12401 rettv->vval.v_number = 0;
12402 if (argvars[0].v_type != VAR_LIST)
12403 EMSG2(_(e_listarg), "insert()");
12404 else if ((l = argvars[0].vval.v_list) != NULL
12405 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
12407 if (argvars[2].v_type != VAR_UNKNOWN)
12408 before = get_tv_number_chk(&argvars[2], &error);
12409 if (error)
12410 return; /* type error; errmsg already given */
12412 if (before == l->lv_len)
12413 item = NULL;
12414 else
12416 item = list_find(l, before);
12417 if (item == NULL)
12419 EMSGN(_(e_listidx), before);
12420 l = NULL;
12423 if (l != NULL)
12425 list_insert_tv(l, &argvars[1], item);
12426 copy_tv(&argvars[0], rettv);
12432 * "isdirectory()" function
12434 static void
12435 f_isdirectory(argvars, rettv)
12436 typval_T *argvars;
12437 typval_T *rettv;
12439 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
12443 * "islocked()" function
12445 static void
12446 f_islocked(argvars, rettv)
12447 typval_T *argvars;
12448 typval_T *rettv;
12450 lval_T lv;
12451 char_u *end;
12452 dictitem_T *di;
12454 rettv->vval.v_number = -1;
12455 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
12456 FNE_CHECK_START);
12457 if (end != NULL && lv.ll_name != NULL)
12459 if (*end != NUL)
12460 EMSG(_(e_trailing));
12461 else
12463 if (lv.ll_tv == NULL)
12465 if (check_changedtick(lv.ll_name))
12466 rettv->vval.v_number = 1; /* always locked */
12467 else
12469 di = find_var(lv.ll_name, NULL);
12470 if (di != NULL)
12472 /* Consider a variable locked when:
12473 * 1. the variable itself is locked
12474 * 2. the value of the variable is locked.
12475 * 3. the List or Dict value is locked.
12477 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
12478 || tv_islocked(&di->di_tv));
12482 else if (lv.ll_range)
12483 EMSG(_("E786: Range not allowed"));
12484 else if (lv.ll_newkey != NULL)
12485 EMSG2(_(e_dictkey), lv.ll_newkey);
12486 else if (lv.ll_list != NULL)
12487 /* List item. */
12488 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
12489 else
12490 /* Dictionary item. */
12491 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
12495 clear_lval(&lv);
12498 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
12501 * Turn a dict into a list:
12502 * "what" == 0: list of keys
12503 * "what" == 1: list of values
12504 * "what" == 2: list of items
12506 static void
12507 dict_list(argvars, rettv, what)
12508 typval_T *argvars;
12509 typval_T *rettv;
12510 int what;
12512 list_T *l2;
12513 dictitem_T *di;
12514 hashitem_T *hi;
12515 listitem_T *li;
12516 listitem_T *li2;
12517 dict_T *d;
12518 int todo;
12520 rettv->vval.v_number = 0;
12521 if (argvars[0].v_type != VAR_DICT)
12523 EMSG(_(e_dictreq));
12524 return;
12526 if ((d = argvars[0].vval.v_dict) == NULL)
12527 return;
12529 if (rettv_list_alloc(rettv) == FAIL)
12530 return;
12532 todo = (int)d->dv_hashtab.ht_used;
12533 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12535 if (!HASHITEM_EMPTY(hi))
12537 --todo;
12538 di = HI2DI(hi);
12540 li = listitem_alloc();
12541 if (li == NULL)
12542 break;
12543 list_append(rettv->vval.v_list, li);
12545 if (what == 0)
12547 /* keys() */
12548 li->li_tv.v_type = VAR_STRING;
12549 li->li_tv.v_lock = 0;
12550 li->li_tv.vval.v_string = vim_strsave(di->di_key);
12552 else if (what == 1)
12554 /* values() */
12555 copy_tv(&di->di_tv, &li->li_tv);
12557 else
12559 /* items() */
12560 l2 = list_alloc();
12561 li->li_tv.v_type = VAR_LIST;
12562 li->li_tv.v_lock = 0;
12563 li->li_tv.vval.v_list = l2;
12564 if (l2 == NULL)
12565 break;
12566 ++l2->lv_refcount;
12568 li2 = listitem_alloc();
12569 if (li2 == NULL)
12570 break;
12571 list_append(l2, li2);
12572 li2->li_tv.v_type = VAR_STRING;
12573 li2->li_tv.v_lock = 0;
12574 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12576 li2 = listitem_alloc();
12577 if (li2 == NULL)
12578 break;
12579 list_append(l2, li2);
12580 copy_tv(&di->di_tv, &li2->li_tv);
12587 * "items(dict)" function
12589 static void
12590 f_items(argvars, rettv)
12591 typval_T *argvars;
12592 typval_T *rettv;
12594 dict_list(argvars, rettv, 2);
12598 * "join()" function
12600 static void
12601 f_join(argvars, rettv)
12602 typval_T *argvars;
12603 typval_T *rettv;
12605 garray_T ga;
12606 char_u *sep;
12608 rettv->vval.v_number = 0;
12609 if (argvars[0].v_type != VAR_LIST)
12611 EMSG(_(e_listreq));
12612 return;
12614 if (argvars[0].vval.v_list == NULL)
12615 return;
12616 if (argvars[1].v_type == VAR_UNKNOWN)
12617 sep = (char_u *)" ";
12618 else
12619 sep = get_tv_string_chk(&argvars[1]);
12621 rettv->v_type = VAR_STRING;
12623 if (sep != NULL)
12625 ga_init2(&ga, (int)sizeof(char), 80);
12626 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12627 ga_append(&ga, NUL);
12628 rettv->vval.v_string = (char_u *)ga.ga_data;
12630 else
12631 rettv->vval.v_string = NULL;
12635 * "keys()" function
12637 static void
12638 f_keys(argvars, rettv)
12639 typval_T *argvars;
12640 typval_T *rettv;
12642 dict_list(argvars, rettv, 0);
12646 * "last_buffer_nr()" function.
12648 /*ARGSUSED*/
12649 static void
12650 f_last_buffer_nr(argvars, rettv)
12651 typval_T *argvars;
12652 typval_T *rettv;
12654 int n = 0;
12655 buf_T *buf;
12657 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12658 if (n < buf->b_fnum)
12659 n = buf->b_fnum;
12661 rettv->vval.v_number = n;
12665 * "len()" function
12667 static void
12668 f_len(argvars, rettv)
12669 typval_T *argvars;
12670 typval_T *rettv;
12672 switch (argvars[0].v_type)
12674 case VAR_STRING:
12675 case VAR_NUMBER:
12676 rettv->vval.v_number = (varnumber_T)STRLEN(
12677 get_tv_string(&argvars[0]));
12678 break;
12679 case VAR_LIST:
12680 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
12681 break;
12682 case VAR_DICT:
12683 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
12684 break;
12685 default:
12686 EMSG(_("E701: Invalid type for len()"));
12687 break;
12691 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
12693 static void
12694 libcall_common(argvars, rettv, type)
12695 typval_T *argvars;
12696 typval_T *rettv;
12697 int type;
12699 #ifdef FEAT_LIBCALL
12700 char_u *string_in;
12701 char_u **string_result;
12702 int nr_result;
12703 #endif
12705 rettv->v_type = type;
12706 if (type == VAR_NUMBER)
12707 rettv->vval.v_number = 0;
12708 else
12709 rettv->vval.v_string = NULL;
12711 if (check_restricted() || check_secure())
12712 return;
12714 #ifdef FEAT_LIBCALL
12715 /* The first two args must be strings, otherwise its meaningless */
12716 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
12718 string_in = NULL;
12719 if (argvars[2].v_type == VAR_STRING)
12720 string_in = argvars[2].vval.v_string;
12721 if (type == VAR_NUMBER)
12722 string_result = NULL;
12723 else
12724 string_result = &rettv->vval.v_string;
12725 if (mch_libcall(argvars[0].vval.v_string,
12726 argvars[1].vval.v_string,
12727 string_in,
12728 argvars[2].vval.v_number,
12729 string_result,
12730 &nr_result) == OK
12731 && type == VAR_NUMBER)
12732 rettv->vval.v_number = nr_result;
12734 #endif
12738 * "libcall()" function
12740 static void
12741 f_libcall(argvars, rettv)
12742 typval_T *argvars;
12743 typval_T *rettv;
12745 libcall_common(argvars, rettv, VAR_STRING);
12749 * "libcallnr()" function
12751 static void
12752 f_libcallnr(argvars, rettv)
12753 typval_T *argvars;
12754 typval_T *rettv;
12756 libcall_common(argvars, rettv, VAR_NUMBER);
12760 * "line(string)" function
12762 static void
12763 f_line(argvars, rettv)
12764 typval_T *argvars;
12765 typval_T *rettv;
12767 linenr_T lnum = 0;
12768 pos_T *fp;
12769 int fnum;
12771 fp = var2fpos(&argvars[0], TRUE, &fnum);
12772 if (fp != NULL)
12773 lnum = fp->lnum;
12774 rettv->vval.v_number = lnum;
12778 * "line2byte(lnum)" function
12780 /*ARGSUSED*/
12781 static void
12782 f_line2byte(argvars, rettv)
12783 typval_T *argvars;
12784 typval_T *rettv;
12786 #ifndef FEAT_BYTEOFF
12787 rettv->vval.v_number = -1;
12788 #else
12789 linenr_T lnum;
12791 lnum = get_tv_lnum(argvars);
12792 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
12793 rettv->vval.v_number = -1;
12794 else
12795 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
12796 if (rettv->vval.v_number >= 0)
12797 ++rettv->vval.v_number;
12798 #endif
12802 * "lispindent(lnum)" function
12804 static void
12805 f_lispindent(argvars, rettv)
12806 typval_T *argvars;
12807 typval_T *rettv;
12809 #ifdef FEAT_LISP
12810 pos_T pos;
12811 linenr_T lnum;
12813 pos = curwin->w_cursor;
12814 lnum = get_tv_lnum(argvars);
12815 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12817 curwin->w_cursor.lnum = lnum;
12818 rettv->vval.v_number = get_lisp_indent();
12819 curwin->w_cursor = pos;
12821 else
12822 #endif
12823 rettv->vval.v_number = -1;
12827 * "localtime()" function
12829 /*ARGSUSED*/
12830 static void
12831 f_localtime(argvars, rettv)
12832 typval_T *argvars;
12833 typval_T *rettv;
12835 rettv->vval.v_number = (varnumber_T)time(NULL);
12838 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
12840 static void
12841 get_maparg(argvars, rettv, exact)
12842 typval_T *argvars;
12843 typval_T *rettv;
12844 int exact;
12846 char_u *keys;
12847 char_u *which;
12848 char_u buf[NUMBUFLEN];
12849 char_u *keys_buf = NULL;
12850 char_u *rhs;
12851 int mode;
12852 garray_T ga;
12853 int abbr = FALSE;
12855 /* return empty string for failure */
12856 rettv->v_type = VAR_STRING;
12857 rettv->vval.v_string = NULL;
12859 keys = get_tv_string(&argvars[0]);
12860 if (*keys == NUL)
12861 return;
12863 if (argvars[1].v_type != VAR_UNKNOWN)
12865 which = get_tv_string_buf_chk(&argvars[1], buf);
12866 if (argvars[2].v_type != VAR_UNKNOWN)
12867 abbr = get_tv_number(&argvars[2]);
12869 else
12870 which = (char_u *)"";
12871 if (which == NULL)
12872 return;
12874 mode = get_map_mode(&which, 0);
12876 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
12877 rhs = check_map(keys, mode, exact, FALSE, abbr);
12878 vim_free(keys_buf);
12879 if (rhs != NULL)
12881 ga_init(&ga);
12882 ga.ga_itemsize = 1;
12883 ga.ga_growsize = 40;
12885 while (*rhs != NUL)
12886 ga_concat(&ga, str2special(&rhs, FALSE));
12888 ga_append(&ga, NUL);
12889 rettv->vval.v_string = (char_u *)ga.ga_data;
12893 #ifdef FEAT_FLOAT
12895 * "log10()" function
12897 static void
12898 f_log10(argvars, rettv)
12899 typval_T *argvars;
12900 typval_T *rettv;
12902 float_T f;
12904 rettv->v_type = VAR_FLOAT;
12905 if (get_float_arg(argvars, &f) == OK)
12906 rettv->vval.v_float = log10(f);
12907 else
12908 rettv->vval.v_float = 0.0;
12910 #endif
12913 * "map()" function
12915 static void
12916 f_map(argvars, rettv)
12917 typval_T *argvars;
12918 typval_T *rettv;
12920 filter_map(argvars, rettv, TRUE);
12924 * "maparg()" function
12926 static void
12927 f_maparg(argvars, rettv)
12928 typval_T *argvars;
12929 typval_T *rettv;
12931 get_maparg(argvars, rettv, TRUE);
12935 * "mapcheck()" function
12937 static void
12938 f_mapcheck(argvars, rettv)
12939 typval_T *argvars;
12940 typval_T *rettv;
12942 get_maparg(argvars, rettv, FALSE);
12945 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
12947 static void
12948 find_some_match(argvars, rettv, type)
12949 typval_T *argvars;
12950 typval_T *rettv;
12951 int type;
12953 char_u *str = NULL;
12954 char_u *expr = NULL;
12955 char_u *pat;
12956 regmatch_T regmatch;
12957 char_u patbuf[NUMBUFLEN];
12958 char_u strbuf[NUMBUFLEN];
12959 char_u *save_cpo;
12960 long start = 0;
12961 long nth = 1;
12962 colnr_T startcol = 0;
12963 int match = 0;
12964 list_T *l = NULL;
12965 listitem_T *li = NULL;
12966 long idx = 0;
12967 char_u *tofree = NULL;
12969 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
12970 save_cpo = p_cpo;
12971 p_cpo = (char_u *)"";
12973 rettv->vval.v_number = -1;
12974 if (type == 3)
12976 /* return empty list when there are no matches */
12977 if (rettv_list_alloc(rettv) == FAIL)
12978 goto theend;
12980 else if (type == 2)
12982 rettv->v_type = VAR_STRING;
12983 rettv->vval.v_string = NULL;
12986 if (argvars[0].v_type == VAR_LIST)
12988 if ((l = argvars[0].vval.v_list) == NULL)
12989 goto theend;
12990 li = l->lv_first;
12992 else
12993 expr = str = get_tv_string(&argvars[0]);
12995 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
12996 if (pat == NULL)
12997 goto theend;
12999 if (argvars[2].v_type != VAR_UNKNOWN)
13001 int error = FALSE;
13003 start = get_tv_number_chk(&argvars[2], &error);
13004 if (error)
13005 goto theend;
13006 if (l != NULL)
13008 li = list_find(l, start);
13009 if (li == NULL)
13010 goto theend;
13011 idx = l->lv_idx; /* use the cached index */
13013 else
13015 if (start < 0)
13016 start = 0;
13017 if (start > (long)STRLEN(str))
13018 goto theend;
13019 /* When "count" argument is there ignore matches before "start",
13020 * otherwise skip part of the string. Differs when pattern is "^"
13021 * or "\<". */
13022 if (argvars[3].v_type != VAR_UNKNOWN)
13023 startcol = start;
13024 else
13025 str += start;
13028 if (argvars[3].v_type != VAR_UNKNOWN)
13029 nth = get_tv_number_chk(&argvars[3], &error);
13030 if (error)
13031 goto theend;
13034 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
13035 if (regmatch.regprog != NULL)
13037 regmatch.rm_ic = p_ic;
13039 for (;;)
13041 if (l != NULL)
13043 if (li == NULL)
13045 match = FALSE;
13046 break;
13048 vim_free(tofree);
13049 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
13050 if (str == NULL)
13051 break;
13054 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
13056 if (match && --nth <= 0)
13057 break;
13058 if (l == NULL && !match)
13059 break;
13061 /* Advance to just after the match. */
13062 if (l != NULL)
13064 li = li->li_next;
13065 ++idx;
13067 else
13069 #ifdef FEAT_MBYTE
13070 startcol = (colnr_T)(regmatch.startp[0]
13071 + (*mb_ptr2len)(regmatch.startp[0]) - str);
13072 #else
13073 startcol = regmatch.startp[0] + 1 - str;
13074 #endif
13078 if (match)
13080 if (type == 3)
13082 int i;
13084 /* return list with matched string and submatches */
13085 for (i = 0; i < NSUBEXP; ++i)
13087 if (regmatch.endp[i] == NULL)
13089 if (list_append_string(rettv->vval.v_list,
13090 (char_u *)"", 0) == FAIL)
13091 break;
13093 else if (list_append_string(rettv->vval.v_list,
13094 regmatch.startp[i],
13095 (int)(regmatch.endp[i] - regmatch.startp[i]))
13096 == FAIL)
13097 break;
13100 else if (type == 2)
13102 /* return matched string */
13103 if (l != NULL)
13104 copy_tv(&li->li_tv, rettv);
13105 else
13106 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
13107 (int)(regmatch.endp[0] - regmatch.startp[0]));
13109 else if (l != NULL)
13110 rettv->vval.v_number = idx;
13111 else
13113 if (type != 0)
13114 rettv->vval.v_number =
13115 (varnumber_T)(regmatch.startp[0] - str);
13116 else
13117 rettv->vval.v_number =
13118 (varnumber_T)(regmatch.endp[0] - str);
13119 rettv->vval.v_number += (varnumber_T)(str - expr);
13122 vim_free(regmatch.regprog);
13125 theend:
13126 vim_free(tofree);
13127 p_cpo = save_cpo;
13131 * "match()" function
13133 static void
13134 f_match(argvars, rettv)
13135 typval_T *argvars;
13136 typval_T *rettv;
13138 find_some_match(argvars, rettv, 1);
13142 * "matchadd()" function
13144 static void
13145 f_matchadd(argvars, rettv)
13146 typval_T *argvars;
13147 typval_T *rettv;
13149 #ifdef FEAT_SEARCH_EXTRA
13150 char_u buf[NUMBUFLEN];
13151 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
13152 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
13153 int prio = 10; /* default priority */
13154 int id = -1;
13155 int error = FALSE;
13157 rettv->vval.v_number = -1;
13159 if (grp == NULL || pat == NULL)
13160 return;
13161 if (argvars[2].v_type != VAR_UNKNOWN)
13163 prio = get_tv_number_chk(&argvars[2], &error);
13164 if (argvars[3].v_type != VAR_UNKNOWN)
13165 id = get_tv_number_chk(&argvars[3], &error);
13167 if (error == TRUE)
13168 return;
13169 if (id >= 1 && id <= 3)
13171 EMSGN("E798: ID is reserved for \":match\": %ld", id);
13172 return;
13175 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
13176 #endif
13180 * "matcharg()" function
13182 static void
13183 f_matcharg(argvars, rettv)
13184 typval_T *argvars;
13185 typval_T *rettv;
13187 if (rettv_list_alloc(rettv) == OK)
13189 #ifdef FEAT_SEARCH_EXTRA
13190 int id = get_tv_number(&argvars[0]);
13191 matchitem_T *m;
13193 if (id >= 1 && id <= 3)
13195 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
13197 list_append_string(rettv->vval.v_list,
13198 syn_id2name(m->hlg_id), -1);
13199 list_append_string(rettv->vval.v_list, m->pattern, -1);
13201 else
13203 list_append_string(rettv->vval.v_list, NUL, -1);
13204 list_append_string(rettv->vval.v_list, NUL, -1);
13207 #endif
13212 * "matchdelete()" function
13214 static void
13215 f_matchdelete(argvars, rettv)
13216 typval_T *argvars;
13217 typval_T *rettv;
13219 #ifdef FEAT_SEARCH_EXTRA
13220 rettv->vval.v_number = match_delete(curwin,
13221 (int)get_tv_number(&argvars[0]), TRUE);
13222 #endif
13226 * "matchend()" function
13228 static void
13229 f_matchend(argvars, rettv)
13230 typval_T *argvars;
13231 typval_T *rettv;
13233 find_some_match(argvars, rettv, 0);
13237 * "matchlist()" function
13239 static void
13240 f_matchlist(argvars, rettv)
13241 typval_T *argvars;
13242 typval_T *rettv;
13244 find_some_match(argvars, rettv, 3);
13248 * "matchstr()" function
13250 static void
13251 f_matchstr(argvars, rettv)
13252 typval_T *argvars;
13253 typval_T *rettv;
13255 find_some_match(argvars, rettv, 2);
13258 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
13260 static void
13261 max_min(argvars, rettv, domax)
13262 typval_T *argvars;
13263 typval_T *rettv;
13264 int domax;
13266 long n = 0;
13267 long i;
13268 int error = FALSE;
13270 if (argvars[0].v_type == VAR_LIST)
13272 list_T *l;
13273 listitem_T *li;
13275 l = argvars[0].vval.v_list;
13276 if (l != NULL)
13278 li = l->lv_first;
13279 if (li != NULL)
13281 n = get_tv_number_chk(&li->li_tv, &error);
13282 for (;;)
13284 li = li->li_next;
13285 if (li == NULL)
13286 break;
13287 i = get_tv_number_chk(&li->li_tv, &error);
13288 if (domax ? i > n : i < n)
13289 n = i;
13294 else if (argvars[0].v_type == VAR_DICT)
13296 dict_T *d;
13297 int first = TRUE;
13298 hashitem_T *hi;
13299 int todo;
13301 d = argvars[0].vval.v_dict;
13302 if (d != NULL)
13304 todo = (int)d->dv_hashtab.ht_used;
13305 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13307 if (!HASHITEM_EMPTY(hi))
13309 --todo;
13310 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
13311 if (first)
13313 n = i;
13314 first = FALSE;
13316 else if (domax ? i > n : i < n)
13317 n = i;
13322 else
13323 EMSG(_(e_listdictarg));
13324 rettv->vval.v_number = error ? 0 : n;
13328 * "max()" function
13330 static void
13331 f_max(argvars, rettv)
13332 typval_T *argvars;
13333 typval_T *rettv;
13335 max_min(argvars, rettv, TRUE);
13339 * "min()" function
13341 static void
13342 f_min(argvars, rettv)
13343 typval_T *argvars;
13344 typval_T *rettv;
13346 max_min(argvars, rettv, FALSE);
13349 static int mkdir_recurse __ARGS((char_u *dir, int prot));
13352 * Create the directory in which "dir" is located, and higher levels when
13353 * needed.
13355 static int
13356 mkdir_recurse(dir, prot)
13357 char_u *dir;
13358 int prot;
13360 char_u *p;
13361 char_u *updir;
13362 int r = FAIL;
13364 /* Get end of directory name in "dir".
13365 * We're done when it's "/" or "c:/". */
13366 p = gettail_sep(dir);
13367 if (p <= get_past_head(dir))
13368 return OK;
13370 /* If the directory exists we're done. Otherwise: create it.*/
13371 updir = vim_strnsave(dir, (int)(p - dir));
13372 if (updir == NULL)
13373 return FAIL;
13374 if (mch_isdir(updir))
13375 r = OK;
13376 else if (mkdir_recurse(updir, prot) == OK)
13377 r = vim_mkdir_emsg(updir, prot);
13378 vim_free(updir);
13379 return r;
13382 #ifdef vim_mkdir
13384 * "mkdir()" function
13386 static void
13387 f_mkdir(argvars, rettv)
13388 typval_T *argvars;
13389 typval_T *rettv;
13391 char_u *dir;
13392 char_u buf[NUMBUFLEN];
13393 int prot = 0755;
13395 rettv->vval.v_number = FAIL;
13396 if (check_restricted() || check_secure())
13397 return;
13399 dir = get_tv_string_buf(&argvars[0], buf);
13400 if (argvars[1].v_type != VAR_UNKNOWN)
13402 if (argvars[2].v_type != VAR_UNKNOWN)
13403 prot = get_tv_number_chk(&argvars[2], NULL);
13404 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
13405 mkdir_recurse(dir, prot);
13407 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
13409 #endif
13412 * "mode()" function
13414 /*ARGSUSED*/
13415 static void
13416 f_mode(argvars, rettv)
13417 typval_T *argvars;
13418 typval_T *rettv;
13420 char_u buf[3];
13422 buf[1] = NUL;
13423 buf[2] = NUL;
13425 #ifdef FEAT_VISUAL
13426 if (VIsual_active)
13428 if (VIsual_select)
13429 buf[0] = VIsual_mode + 's' - 'v';
13430 else
13431 buf[0] = VIsual_mode;
13433 else
13434 #endif
13435 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
13436 || State == CONFIRM)
13438 buf[0] = 'r';
13439 if (State == ASKMORE)
13440 buf[1] = 'm';
13441 else if (State == CONFIRM)
13442 buf[1] = '?';
13444 else if (State == EXTERNCMD)
13445 buf[0] = '!';
13446 else if (State & INSERT)
13448 #ifdef FEAT_VREPLACE
13449 if (State & VREPLACE_FLAG)
13451 buf[0] = 'R';
13452 buf[1] = 'v';
13454 else
13455 #endif
13456 if (State & REPLACE_FLAG)
13457 buf[0] = 'R';
13458 else
13459 buf[0] = 'i';
13461 else if (State & CMDLINE)
13463 buf[0] = 'c';
13464 if (exmode_active)
13465 buf[1] = 'v';
13467 else if (exmode_active)
13469 buf[0] = 'c';
13470 buf[1] = 'e';
13472 else
13474 buf[0] = 'n';
13475 if (finish_op)
13476 buf[1] = 'o';
13479 /* A zero number or empty string argument: return only major mode. */
13480 if (!(argvars[0].v_type == VAR_NUMBER && argvars[0].vval.v_number != 0)
13481 && !(argvars[0].v_type == VAR_STRING
13482 && *get_tv_string(&argvars[0]) != NUL))
13483 buf[1] = NUL;
13485 rettv->vval.v_string = vim_strsave(buf);
13486 rettv->v_type = VAR_STRING;
13490 * "nextnonblank()" function
13492 static void
13493 f_nextnonblank(argvars, rettv)
13494 typval_T *argvars;
13495 typval_T *rettv;
13497 linenr_T lnum;
13499 for (lnum = get_tv_lnum(argvars); ; ++lnum)
13501 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
13503 lnum = 0;
13504 break;
13506 if (*skipwhite(ml_get(lnum)) != NUL)
13507 break;
13509 rettv->vval.v_number = lnum;
13513 * "nr2char()" function
13515 static void
13516 f_nr2char(argvars, rettv)
13517 typval_T *argvars;
13518 typval_T *rettv;
13520 char_u buf[NUMBUFLEN];
13522 #ifdef FEAT_MBYTE
13523 if (has_mbyte)
13524 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
13525 else
13526 #endif
13528 buf[0] = (char_u)get_tv_number(&argvars[0]);
13529 buf[1] = NUL;
13531 rettv->v_type = VAR_STRING;
13532 rettv->vval.v_string = vim_strsave(buf);
13536 * "pathshorten()" function
13538 static void
13539 f_pathshorten(argvars, rettv)
13540 typval_T *argvars;
13541 typval_T *rettv;
13543 char_u *p;
13545 rettv->v_type = VAR_STRING;
13546 p = get_tv_string_chk(&argvars[0]);
13547 if (p == NULL)
13548 rettv->vval.v_string = NULL;
13549 else
13551 p = vim_strsave(p);
13552 rettv->vval.v_string = p;
13553 if (p != NULL)
13554 shorten_dir(p);
13558 #ifdef FEAT_FLOAT
13560 * "pow()" function
13562 static void
13563 f_pow(argvars, rettv)
13564 typval_T *argvars;
13565 typval_T *rettv;
13567 float_T fx, fy;
13569 rettv->v_type = VAR_FLOAT;
13570 if (get_float_arg(argvars, &fx) == OK
13571 && get_float_arg(&argvars[1], &fy) == OK)
13572 rettv->vval.v_float = pow(fx, fy);
13573 else
13574 rettv->vval.v_float = 0.0;
13576 #endif
13579 * "prevnonblank()" function
13581 static void
13582 f_prevnonblank(argvars, rettv)
13583 typval_T *argvars;
13584 typval_T *rettv;
13586 linenr_T lnum;
13588 lnum = get_tv_lnum(argvars);
13589 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
13590 lnum = 0;
13591 else
13592 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
13593 --lnum;
13594 rettv->vval.v_number = lnum;
13597 #ifdef HAVE_STDARG_H
13598 /* This dummy va_list is here because:
13599 * - passing a NULL pointer doesn't work when va_list isn't a pointer
13600 * - locally in the function results in a "used before set" warning
13601 * - using va_start() to initialize it gives "function with fixed args" error */
13602 static va_list ap;
13603 #endif
13606 * "printf()" function
13608 static void
13609 f_printf(argvars, rettv)
13610 typval_T *argvars;
13611 typval_T *rettv;
13613 rettv->v_type = VAR_STRING;
13614 rettv->vval.v_string = NULL;
13615 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
13617 char_u buf[NUMBUFLEN];
13618 int len;
13619 char_u *s;
13620 int saved_did_emsg = did_emsg;
13621 char *fmt;
13623 /* Get the required length, allocate the buffer and do it for real. */
13624 did_emsg = FALSE;
13625 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
13626 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
13627 if (!did_emsg)
13629 s = alloc(len + 1);
13630 if (s != NULL)
13632 rettv->vval.v_string = s;
13633 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
13636 did_emsg |= saved_did_emsg;
13638 #endif
13642 * "pumvisible()" function
13644 /*ARGSUSED*/
13645 static void
13646 f_pumvisible(argvars, rettv)
13647 typval_T *argvars;
13648 typval_T *rettv;
13650 rettv->vval.v_number = 0;
13651 #ifdef FEAT_INS_EXPAND
13652 if (pum_visible())
13653 rettv->vval.v_number = 1;
13654 #endif
13658 * "range()" function
13660 static void
13661 f_range(argvars, rettv)
13662 typval_T *argvars;
13663 typval_T *rettv;
13665 long start;
13666 long end;
13667 long stride = 1;
13668 long i;
13669 int error = FALSE;
13671 start = get_tv_number_chk(&argvars[0], &error);
13672 if (argvars[1].v_type == VAR_UNKNOWN)
13674 end = start - 1;
13675 start = 0;
13677 else
13679 end = get_tv_number_chk(&argvars[1], &error);
13680 if (argvars[2].v_type != VAR_UNKNOWN)
13681 stride = get_tv_number_chk(&argvars[2], &error);
13684 rettv->vval.v_number = 0;
13685 if (error)
13686 return; /* type error; errmsg already given */
13687 if (stride == 0)
13688 EMSG(_("E726: Stride is zero"));
13689 else if (stride > 0 ? end + 1 < start : end - 1 > start)
13690 EMSG(_("E727: Start past end"));
13691 else
13693 if (rettv_list_alloc(rettv) == OK)
13694 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
13695 if (list_append_number(rettv->vval.v_list,
13696 (varnumber_T)i) == FAIL)
13697 break;
13702 * "readfile()" function
13704 static void
13705 f_readfile(argvars, rettv)
13706 typval_T *argvars;
13707 typval_T *rettv;
13709 int binary = FALSE;
13710 char_u *fname;
13711 FILE *fd;
13712 listitem_T *li;
13713 #define FREAD_SIZE 200 /* optimized for text lines */
13714 char_u buf[FREAD_SIZE];
13715 int readlen; /* size of last fread() */
13716 int buflen; /* nr of valid chars in buf[] */
13717 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
13718 int tolist; /* first byte in buf[] still to be put in list */
13719 int chop; /* how many CR to chop off */
13720 char_u *prev = NULL; /* previously read bytes, if any */
13721 int prevlen = 0; /* length of "prev" if not NULL */
13722 char_u *s;
13723 int len;
13724 long maxline = MAXLNUM;
13725 long cnt = 0;
13727 if (argvars[1].v_type != VAR_UNKNOWN)
13729 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
13730 binary = TRUE;
13731 if (argvars[2].v_type != VAR_UNKNOWN)
13732 maxline = get_tv_number(&argvars[2]);
13735 if (rettv_list_alloc(rettv) == FAIL)
13736 return;
13738 /* Always open the file in binary mode, library functions have a mind of
13739 * their own about CR-LF conversion. */
13740 fname = get_tv_string(&argvars[0]);
13741 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
13743 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
13744 return;
13747 filtd = 0;
13748 while (cnt < maxline || maxline < 0)
13750 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
13751 buflen = filtd + readlen;
13752 tolist = 0;
13753 for ( ; filtd < buflen || readlen <= 0; ++filtd)
13755 if (buf[filtd] == '\n' || readlen <= 0)
13757 /* Only when in binary mode add an empty list item when the
13758 * last line ends in a '\n'. */
13759 if (!binary && readlen == 0 && filtd == 0)
13760 break;
13762 /* Found end-of-line or end-of-file: add a text line to the
13763 * list. */
13764 chop = 0;
13765 if (!binary)
13766 while (filtd - chop - 1 >= tolist
13767 && buf[filtd - chop - 1] == '\r')
13768 ++chop;
13769 len = filtd - tolist - chop;
13770 if (prev == NULL)
13771 s = vim_strnsave(buf + tolist, len);
13772 else
13774 s = alloc((unsigned)(prevlen + len + 1));
13775 if (s != NULL)
13777 mch_memmove(s, prev, prevlen);
13778 vim_free(prev);
13779 prev = NULL;
13780 mch_memmove(s + prevlen, buf + tolist, len);
13781 s[prevlen + len] = NUL;
13784 tolist = filtd + 1;
13786 li = listitem_alloc();
13787 if (li == NULL)
13789 vim_free(s);
13790 break;
13792 li->li_tv.v_type = VAR_STRING;
13793 li->li_tv.v_lock = 0;
13794 li->li_tv.vval.v_string = s;
13795 list_append(rettv->vval.v_list, li);
13797 if (++cnt >= maxline && maxline >= 0)
13798 break;
13799 if (readlen <= 0)
13800 break;
13802 else if (buf[filtd] == NUL)
13803 buf[filtd] = '\n';
13805 if (readlen <= 0)
13806 break;
13808 if (tolist == 0)
13810 /* "buf" is full, need to move text to an allocated buffer */
13811 if (prev == NULL)
13813 prev = vim_strnsave(buf, buflen);
13814 prevlen = buflen;
13816 else
13818 s = alloc((unsigned)(prevlen + buflen));
13819 if (s != NULL)
13821 mch_memmove(s, prev, prevlen);
13822 mch_memmove(s + prevlen, buf, buflen);
13823 vim_free(prev);
13824 prev = s;
13825 prevlen += buflen;
13828 filtd = 0;
13830 else
13832 mch_memmove(buf, buf + tolist, buflen - tolist);
13833 filtd -= tolist;
13838 * For a negative line count use only the lines at the end of the file,
13839 * free the rest.
13841 if (maxline < 0)
13842 while (cnt > -maxline)
13844 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
13845 --cnt;
13848 vim_free(prev);
13849 fclose(fd);
13852 #if defined(FEAT_RELTIME)
13853 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
13856 * Convert a List to proftime_T.
13857 * Return FAIL when there is something wrong.
13859 static int
13860 list2proftime(arg, tm)
13861 typval_T *arg;
13862 proftime_T *tm;
13864 long n1, n2;
13865 int error = FALSE;
13867 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
13868 || arg->vval.v_list->lv_len != 2)
13869 return FAIL;
13870 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
13871 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
13872 # ifdef WIN3264
13873 tm->HighPart = n1;
13874 tm->LowPart = n2;
13875 # else
13876 tm->tv_sec = n1;
13877 tm->tv_usec = n2;
13878 # endif
13879 return error ? FAIL : OK;
13881 #endif /* FEAT_RELTIME */
13884 * "reltime()" function
13886 static void
13887 f_reltime(argvars, rettv)
13888 typval_T *argvars;
13889 typval_T *rettv;
13891 #ifdef FEAT_RELTIME
13892 proftime_T res;
13893 proftime_T start;
13895 if (argvars[0].v_type == VAR_UNKNOWN)
13897 /* No arguments: get current time. */
13898 profile_start(&res);
13900 else if (argvars[1].v_type == VAR_UNKNOWN)
13902 if (list2proftime(&argvars[0], &res) == FAIL)
13903 return;
13904 profile_end(&res);
13906 else
13908 /* Two arguments: compute the difference. */
13909 if (list2proftime(&argvars[0], &start) == FAIL
13910 || list2proftime(&argvars[1], &res) == FAIL)
13911 return;
13912 profile_sub(&res, &start);
13915 if (rettv_list_alloc(rettv) == OK)
13917 long n1, n2;
13919 # ifdef WIN3264
13920 n1 = res.HighPart;
13921 n2 = res.LowPart;
13922 # else
13923 n1 = res.tv_sec;
13924 n2 = res.tv_usec;
13925 # endif
13926 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
13927 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
13929 #endif
13933 * "reltimestr()" function
13935 static void
13936 f_reltimestr(argvars, rettv)
13937 typval_T *argvars;
13938 typval_T *rettv;
13940 #ifdef FEAT_RELTIME
13941 proftime_T tm;
13942 #endif
13944 rettv->v_type = VAR_STRING;
13945 rettv->vval.v_string = NULL;
13946 #ifdef FEAT_RELTIME
13947 if (list2proftime(&argvars[0], &tm) == OK)
13948 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
13949 #endif
13952 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
13953 static void make_connection __ARGS((void));
13954 static int check_connection __ARGS((void));
13956 static void
13957 make_connection()
13959 if (X_DISPLAY == NULL
13960 # ifdef FEAT_GUI
13961 && !gui.in_use
13962 # endif
13965 x_force_connect = TRUE;
13966 setup_term_clip();
13967 x_force_connect = FALSE;
13971 static int
13972 check_connection()
13974 make_connection();
13975 if (X_DISPLAY == NULL)
13977 EMSG(_("E240: No connection to Vim server"));
13978 return FAIL;
13980 return OK;
13982 #endif
13984 #ifdef FEAT_CLIENTSERVER
13985 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
13987 static void
13988 remote_common(argvars, rettv, expr)
13989 typval_T *argvars;
13990 typval_T *rettv;
13991 int expr;
13993 char_u *server_name;
13994 char_u *keys;
13995 char_u *r = NULL;
13996 char_u buf[NUMBUFLEN];
13997 # ifdef WIN32
13998 HWND w;
13999 # else
14000 Window w;
14001 # endif
14003 if (check_restricted() || check_secure())
14004 return;
14006 # ifdef FEAT_X11
14007 if (check_connection() == FAIL)
14008 return;
14009 # endif
14011 server_name = get_tv_string_chk(&argvars[0]);
14012 if (server_name == NULL)
14013 return; /* type error; errmsg already given */
14014 keys = get_tv_string_buf(&argvars[1], buf);
14015 # ifdef WIN32
14016 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14017 # else
14018 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
14019 < 0)
14020 # endif
14022 if (r != NULL)
14023 EMSG(r); /* sending worked but evaluation failed */
14024 else
14025 EMSG2(_("E241: Unable to send to %s"), server_name);
14026 return;
14029 rettv->vval.v_string = r;
14031 if (argvars[2].v_type != VAR_UNKNOWN)
14033 dictitem_T v;
14034 char_u str[30];
14035 char_u *idvar;
14037 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
14038 v.di_tv.v_type = VAR_STRING;
14039 v.di_tv.vval.v_string = vim_strsave(str);
14040 idvar = get_tv_string_chk(&argvars[2]);
14041 if (idvar != NULL)
14042 set_var(idvar, &v.di_tv, FALSE);
14043 vim_free(v.di_tv.vval.v_string);
14046 #endif
14049 * "remote_expr()" function
14051 /*ARGSUSED*/
14052 static void
14053 f_remote_expr(argvars, rettv)
14054 typval_T *argvars;
14055 typval_T *rettv;
14057 rettv->v_type = VAR_STRING;
14058 rettv->vval.v_string = NULL;
14059 #ifdef FEAT_CLIENTSERVER
14060 remote_common(argvars, rettv, TRUE);
14061 #endif
14065 * "remote_foreground()" function
14067 /*ARGSUSED*/
14068 static void
14069 f_remote_foreground(argvars, rettv)
14070 typval_T *argvars;
14071 typval_T *rettv;
14073 rettv->vval.v_number = 0;
14074 #ifdef FEAT_CLIENTSERVER
14075 # ifdef WIN32
14076 /* On Win32 it's done in this application. */
14078 char_u *server_name = get_tv_string_chk(&argvars[0]);
14080 if (server_name != NULL)
14081 serverForeground(server_name);
14083 # else
14084 /* Send a foreground() expression to the server. */
14085 argvars[1].v_type = VAR_STRING;
14086 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
14087 argvars[2].v_type = VAR_UNKNOWN;
14088 remote_common(argvars, rettv, TRUE);
14089 vim_free(argvars[1].vval.v_string);
14090 # endif
14091 #endif
14094 /*ARGSUSED*/
14095 static void
14096 f_remote_peek(argvars, rettv)
14097 typval_T *argvars;
14098 typval_T *rettv;
14100 #ifdef FEAT_CLIENTSERVER
14101 dictitem_T v;
14102 char_u *s = NULL;
14103 # ifdef WIN32
14104 long_u n = 0;
14105 # endif
14106 char_u *serverid;
14108 if (check_restricted() || check_secure())
14110 rettv->vval.v_number = -1;
14111 return;
14113 serverid = get_tv_string_chk(&argvars[0]);
14114 if (serverid == NULL)
14116 rettv->vval.v_number = -1;
14117 return; /* type error; errmsg already given */
14119 # ifdef WIN32
14120 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14121 if (n == 0)
14122 rettv->vval.v_number = -1;
14123 else
14125 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
14126 rettv->vval.v_number = (s != NULL);
14128 # else
14129 rettv->vval.v_number = 0;
14130 if (check_connection() == FAIL)
14131 return;
14133 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
14134 serverStrToWin(serverid), &s);
14135 # endif
14137 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
14139 char_u *retvar;
14141 v.di_tv.v_type = VAR_STRING;
14142 v.di_tv.vval.v_string = vim_strsave(s);
14143 retvar = get_tv_string_chk(&argvars[1]);
14144 if (retvar != NULL)
14145 set_var(retvar, &v.di_tv, FALSE);
14146 vim_free(v.di_tv.vval.v_string);
14148 #else
14149 rettv->vval.v_number = -1;
14150 #endif
14153 /*ARGSUSED*/
14154 static void
14155 f_remote_read(argvars, rettv)
14156 typval_T *argvars;
14157 typval_T *rettv;
14159 char_u *r = NULL;
14161 #ifdef FEAT_CLIENTSERVER
14162 char_u *serverid = get_tv_string_chk(&argvars[0]);
14164 if (serverid != NULL && !check_restricted() && !check_secure())
14166 # ifdef WIN32
14167 /* The server's HWND is encoded in the 'id' parameter */
14168 long_u n = 0;
14170 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14171 if (n != 0)
14172 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
14173 if (r == NULL)
14174 # else
14175 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
14176 serverStrToWin(serverid), &r, FALSE) < 0)
14177 # endif
14178 EMSG(_("E277: Unable to read a server reply"));
14180 #endif
14181 rettv->v_type = VAR_STRING;
14182 rettv->vval.v_string = r;
14186 * "remote_send()" function
14188 /*ARGSUSED*/
14189 static void
14190 f_remote_send(argvars, rettv)
14191 typval_T *argvars;
14192 typval_T *rettv;
14194 rettv->v_type = VAR_STRING;
14195 rettv->vval.v_string = NULL;
14196 #ifdef FEAT_CLIENTSERVER
14197 remote_common(argvars, rettv, FALSE);
14198 #endif
14202 * "remove()" function
14204 static void
14205 f_remove(argvars, rettv)
14206 typval_T *argvars;
14207 typval_T *rettv;
14209 list_T *l;
14210 listitem_T *item, *item2;
14211 listitem_T *li;
14212 long idx;
14213 long end;
14214 char_u *key;
14215 dict_T *d;
14216 dictitem_T *di;
14218 rettv->vval.v_number = 0;
14219 if (argvars[0].v_type == VAR_DICT)
14221 if (argvars[2].v_type != VAR_UNKNOWN)
14222 EMSG2(_(e_toomanyarg), "remove()");
14223 else if ((d = argvars[0].vval.v_dict) != NULL
14224 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
14226 key = get_tv_string_chk(&argvars[1]);
14227 if (key != NULL)
14229 di = dict_find(d, key, -1);
14230 if (di == NULL)
14231 EMSG2(_(e_dictkey), key);
14232 else
14234 *rettv = di->di_tv;
14235 init_tv(&di->di_tv);
14236 dictitem_remove(d, di);
14241 else if (argvars[0].v_type != VAR_LIST)
14242 EMSG2(_(e_listdictarg), "remove()");
14243 else if ((l = argvars[0].vval.v_list) != NULL
14244 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
14246 int error = FALSE;
14248 idx = get_tv_number_chk(&argvars[1], &error);
14249 if (error)
14250 ; /* type error: do nothing, errmsg already given */
14251 else if ((item = list_find(l, idx)) == NULL)
14252 EMSGN(_(e_listidx), idx);
14253 else
14255 if (argvars[2].v_type == VAR_UNKNOWN)
14257 /* Remove one item, return its value. */
14258 list_remove(l, item, item);
14259 *rettv = item->li_tv;
14260 vim_free(item);
14262 else
14264 /* Remove range of items, return list with values. */
14265 end = get_tv_number_chk(&argvars[2], &error);
14266 if (error)
14267 ; /* type error: do nothing */
14268 else if ((item2 = list_find(l, end)) == NULL)
14269 EMSGN(_(e_listidx), end);
14270 else
14272 int cnt = 0;
14274 for (li = item; li != NULL; li = li->li_next)
14276 ++cnt;
14277 if (li == item2)
14278 break;
14280 if (li == NULL) /* didn't find "item2" after "item" */
14281 EMSG(_(e_invrange));
14282 else
14284 list_remove(l, item, item2);
14285 if (rettv_list_alloc(rettv) == OK)
14287 l = rettv->vval.v_list;
14288 l->lv_first = item;
14289 l->lv_last = item2;
14290 item->li_prev = NULL;
14291 item2->li_next = NULL;
14292 l->lv_len = cnt;
14302 * "rename({from}, {to})" function
14304 static void
14305 f_rename(argvars, rettv)
14306 typval_T *argvars;
14307 typval_T *rettv;
14309 char_u buf[NUMBUFLEN];
14311 if (check_restricted() || check_secure())
14312 rettv->vval.v_number = -1;
14313 else
14314 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
14315 get_tv_string_buf(&argvars[1], buf));
14319 * "repeat()" function
14321 /*ARGSUSED*/
14322 static void
14323 f_repeat(argvars, rettv)
14324 typval_T *argvars;
14325 typval_T *rettv;
14327 char_u *p;
14328 int n;
14329 int slen;
14330 int len;
14331 char_u *r;
14332 int i;
14334 n = get_tv_number(&argvars[1]);
14335 if (argvars[0].v_type == VAR_LIST)
14337 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
14338 while (n-- > 0)
14339 if (list_extend(rettv->vval.v_list,
14340 argvars[0].vval.v_list, NULL) == FAIL)
14341 break;
14343 else
14345 p = get_tv_string(&argvars[0]);
14346 rettv->v_type = VAR_STRING;
14347 rettv->vval.v_string = NULL;
14349 slen = (int)STRLEN(p);
14350 len = slen * n;
14351 if (len <= 0)
14352 return;
14354 r = alloc(len + 1);
14355 if (r != NULL)
14357 for (i = 0; i < n; i++)
14358 mch_memmove(r + i * slen, p, (size_t)slen);
14359 r[len] = NUL;
14362 rettv->vval.v_string = r;
14367 * "resolve()" function
14369 static void
14370 f_resolve(argvars, rettv)
14371 typval_T *argvars;
14372 typval_T *rettv;
14374 char_u *p;
14376 p = get_tv_string(&argvars[0]);
14377 #ifdef FEAT_SHORTCUT
14379 char_u *v = NULL;
14381 v = mch_resolve_shortcut(p);
14382 if (v != NULL)
14383 rettv->vval.v_string = v;
14384 else
14385 rettv->vval.v_string = vim_strsave(p);
14387 #else
14388 # ifdef HAVE_READLINK
14390 char_u buf[MAXPATHL + 1];
14391 char_u *cpy;
14392 int len;
14393 char_u *remain = NULL;
14394 char_u *q;
14395 int is_relative_to_current = FALSE;
14396 int has_trailing_pathsep = FALSE;
14397 int limit = 100;
14399 p = vim_strsave(p);
14401 if (p[0] == '.' && (vim_ispathsep(p[1])
14402 || (p[1] == '.' && (vim_ispathsep(p[2])))))
14403 is_relative_to_current = TRUE;
14405 len = STRLEN(p);
14406 if (len > 0 && after_pathsep(p, p + len))
14407 has_trailing_pathsep = TRUE;
14409 q = getnextcomp(p);
14410 if (*q != NUL)
14412 /* Separate the first path component in "p", and keep the
14413 * remainder (beginning with the path separator). */
14414 remain = vim_strsave(q - 1);
14415 q[-1] = NUL;
14418 for (;;)
14420 for (;;)
14422 len = readlink((char *)p, (char *)buf, MAXPATHL);
14423 if (len <= 0)
14424 break;
14425 buf[len] = NUL;
14427 if (limit-- == 0)
14429 vim_free(p);
14430 vim_free(remain);
14431 EMSG(_("E655: Too many symbolic links (cycle?)"));
14432 rettv->vval.v_string = NULL;
14433 goto fail;
14436 /* Ensure that the result will have a trailing path separator
14437 * if the argument has one. */
14438 if (remain == NULL && has_trailing_pathsep)
14439 add_pathsep(buf);
14441 /* Separate the first path component in the link value and
14442 * concatenate the remainders. */
14443 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
14444 if (*q != NUL)
14446 if (remain == NULL)
14447 remain = vim_strsave(q - 1);
14448 else
14450 cpy = concat_str(q - 1, remain);
14451 if (cpy != NULL)
14453 vim_free(remain);
14454 remain = cpy;
14457 q[-1] = NUL;
14460 q = gettail(p);
14461 if (q > p && *q == NUL)
14463 /* Ignore trailing path separator. */
14464 q[-1] = NUL;
14465 q = gettail(p);
14467 if (q > p && !mch_isFullName(buf))
14469 /* symlink is relative to directory of argument */
14470 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
14471 if (cpy != NULL)
14473 STRCPY(cpy, p);
14474 STRCPY(gettail(cpy), buf);
14475 vim_free(p);
14476 p = cpy;
14479 else
14481 vim_free(p);
14482 p = vim_strsave(buf);
14486 if (remain == NULL)
14487 break;
14489 /* Append the first path component of "remain" to "p". */
14490 q = getnextcomp(remain + 1);
14491 len = q - remain - (*q != NUL);
14492 cpy = vim_strnsave(p, STRLEN(p) + len);
14493 if (cpy != NULL)
14495 STRNCAT(cpy, remain, len);
14496 vim_free(p);
14497 p = cpy;
14499 /* Shorten "remain". */
14500 if (*q != NUL)
14501 STRMOVE(remain, q - 1);
14502 else
14504 vim_free(remain);
14505 remain = NULL;
14509 /* If the result is a relative path name, make it explicitly relative to
14510 * the current directory if and only if the argument had this form. */
14511 if (!vim_ispathsep(*p))
14513 if (is_relative_to_current
14514 && *p != NUL
14515 && !(p[0] == '.'
14516 && (p[1] == NUL
14517 || vim_ispathsep(p[1])
14518 || (p[1] == '.'
14519 && (p[2] == NUL
14520 || vim_ispathsep(p[2]))))))
14522 /* Prepend "./". */
14523 cpy = concat_str((char_u *)"./", p);
14524 if (cpy != NULL)
14526 vim_free(p);
14527 p = cpy;
14530 else if (!is_relative_to_current)
14532 /* Strip leading "./". */
14533 q = p;
14534 while (q[0] == '.' && vim_ispathsep(q[1]))
14535 q += 2;
14536 if (q > p)
14537 STRMOVE(p, p + 2);
14541 /* Ensure that the result will have no trailing path separator
14542 * if the argument had none. But keep "/" or "//". */
14543 if (!has_trailing_pathsep)
14545 q = p + STRLEN(p);
14546 if (after_pathsep(p, q))
14547 *gettail_sep(p) = NUL;
14550 rettv->vval.v_string = p;
14552 # else
14553 rettv->vval.v_string = vim_strsave(p);
14554 # endif
14555 #endif
14557 simplify_filename(rettv->vval.v_string);
14559 #ifdef HAVE_READLINK
14560 fail:
14561 #endif
14562 rettv->v_type = VAR_STRING;
14566 * "reverse({list})" function
14568 static void
14569 f_reverse(argvars, rettv)
14570 typval_T *argvars;
14571 typval_T *rettv;
14573 list_T *l;
14574 listitem_T *li, *ni;
14576 rettv->vval.v_number = 0;
14577 if (argvars[0].v_type != VAR_LIST)
14578 EMSG2(_(e_listarg), "reverse()");
14579 else if ((l = argvars[0].vval.v_list) != NULL
14580 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
14582 li = l->lv_last;
14583 l->lv_first = l->lv_last = NULL;
14584 l->lv_len = 0;
14585 while (li != NULL)
14587 ni = li->li_prev;
14588 list_append(l, li);
14589 li = ni;
14591 rettv->vval.v_list = l;
14592 rettv->v_type = VAR_LIST;
14593 ++l->lv_refcount;
14594 l->lv_idx = l->lv_len - l->lv_idx - 1;
14598 #define SP_NOMOVE 0x01 /* don't move cursor */
14599 #define SP_REPEAT 0x02 /* repeat to find outer pair */
14600 #define SP_RETCOUNT 0x04 /* return matchcount */
14601 #define SP_SETPCMARK 0x08 /* set previous context mark */
14602 #define SP_START 0x10 /* accept match at start position */
14603 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
14604 #define SP_END 0x40 /* leave cursor at end of match */
14606 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
14609 * Get flags for a search function.
14610 * Possibly sets "p_ws".
14611 * Returns BACKWARD, FORWARD or zero (for an error).
14613 static int
14614 get_search_arg(varp, flagsp)
14615 typval_T *varp;
14616 int *flagsp;
14618 int dir = FORWARD;
14619 char_u *flags;
14620 char_u nbuf[NUMBUFLEN];
14621 int mask;
14623 if (varp->v_type != VAR_UNKNOWN)
14625 flags = get_tv_string_buf_chk(varp, nbuf);
14626 if (flags == NULL)
14627 return 0; /* type error; errmsg already given */
14628 while (*flags != NUL)
14630 switch (*flags)
14632 case 'b': dir = BACKWARD; break;
14633 case 'w': p_ws = TRUE; break;
14634 case 'W': p_ws = FALSE; break;
14635 default: mask = 0;
14636 if (flagsp != NULL)
14637 switch (*flags)
14639 case 'c': mask = SP_START; break;
14640 case 'e': mask = SP_END; break;
14641 case 'm': mask = SP_RETCOUNT; break;
14642 case 'n': mask = SP_NOMOVE; break;
14643 case 'p': mask = SP_SUBPAT; break;
14644 case 'r': mask = SP_REPEAT; break;
14645 case 's': mask = SP_SETPCMARK; break;
14647 if (mask == 0)
14649 EMSG2(_(e_invarg2), flags);
14650 dir = 0;
14652 else
14653 *flagsp |= mask;
14655 if (dir == 0)
14656 break;
14657 ++flags;
14660 return dir;
14664 * Shared by search() and searchpos() functions
14666 static int
14667 search_cmn(argvars, match_pos, flagsp)
14668 typval_T *argvars;
14669 pos_T *match_pos;
14670 int *flagsp;
14672 int flags;
14673 char_u *pat;
14674 pos_T pos;
14675 pos_T save_cursor;
14676 int save_p_ws = p_ws;
14677 int dir;
14678 int retval = 0; /* default: FAIL */
14679 long lnum_stop = 0;
14680 proftime_T tm;
14681 #ifdef FEAT_RELTIME
14682 long time_limit = 0;
14683 #endif
14684 int options = SEARCH_KEEP;
14685 int subpatnum;
14687 pat = get_tv_string(&argvars[0]);
14688 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
14689 if (dir == 0)
14690 goto theend;
14691 flags = *flagsp;
14692 if (flags & SP_START)
14693 options |= SEARCH_START;
14694 if (flags & SP_END)
14695 options |= SEARCH_END;
14697 /* Optional arguments: line number to stop searching and timeout. */
14698 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
14700 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
14701 if (lnum_stop < 0)
14702 goto theend;
14703 #ifdef FEAT_RELTIME
14704 if (argvars[3].v_type != VAR_UNKNOWN)
14706 time_limit = get_tv_number_chk(&argvars[3], NULL);
14707 if (time_limit < 0)
14708 goto theend;
14710 #endif
14713 #ifdef FEAT_RELTIME
14714 /* Set the time limit, if there is one. */
14715 profile_setlimit(time_limit, &tm);
14716 #endif
14719 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
14720 * Check to make sure only those flags are set.
14721 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
14722 * flags cannot be set. Check for that condition also.
14724 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
14725 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14727 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
14728 goto theend;
14731 pos = save_cursor = curwin->w_cursor;
14732 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14733 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
14734 if (subpatnum != FAIL)
14736 if (flags & SP_SUBPAT)
14737 retval = subpatnum;
14738 else
14739 retval = pos.lnum;
14740 if (flags & SP_SETPCMARK)
14741 setpcmark();
14742 curwin->w_cursor = pos;
14743 if (match_pos != NULL)
14745 /* Store the match cursor position */
14746 match_pos->lnum = pos.lnum;
14747 match_pos->col = pos.col + 1;
14749 /* "/$" will put the cursor after the end of the line, may need to
14750 * correct that here */
14751 check_cursor();
14754 /* If 'n' flag is used: restore cursor position. */
14755 if (flags & SP_NOMOVE)
14756 curwin->w_cursor = save_cursor;
14757 else
14758 curwin->w_set_curswant = TRUE;
14759 theend:
14760 p_ws = save_p_ws;
14762 return retval;
14765 #ifdef FEAT_FLOAT
14767 * "round({float})" function
14769 static void
14770 f_round(argvars, rettv)
14771 typval_T *argvars;
14772 typval_T *rettv;
14774 float_T f;
14776 rettv->v_type = VAR_FLOAT;
14777 if (get_float_arg(argvars, &f) == OK)
14778 /* round() is not in C90, use ceil() or floor() instead. */
14779 rettv->vval.v_float = f > 0 ? floor(f + 0.5) : ceil(f - 0.5);
14780 else
14781 rettv->vval.v_float = 0.0;
14783 #endif
14786 * "search()" function
14788 static void
14789 f_search(argvars, rettv)
14790 typval_T *argvars;
14791 typval_T *rettv;
14793 int flags = 0;
14795 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
14799 * "searchdecl()" function
14801 static void
14802 f_searchdecl(argvars, rettv)
14803 typval_T *argvars;
14804 typval_T *rettv;
14806 int locally = 1;
14807 int thisblock = 0;
14808 int error = FALSE;
14809 char_u *name;
14811 rettv->vval.v_number = 1; /* default: FAIL */
14813 name = get_tv_string_chk(&argvars[0]);
14814 if (argvars[1].v_type != VAR_UNKNOWN)
14816 locally = get_tv_number_chk(&argvars[1], &error) == 0;
14817 if (!error && argvars[2].v_type != VAR_UNKNOWN)
14818 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
14820 if (!error && name != NULL)
14821 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
14822 locally, thisblock, SEARCH_KEEP) == FAIL;
14826 * Used by searchpair() and searchpairpos()
14828 static int
14829 searchpair_cmn(argvars, match_pos)
14830 typval_T *argvars;
14831 pos_T *match_pos;
14833 char_u *spat, *mpat, *epat;
14834 char_u *skip;
14835 int save_p_ws = p_ws;
14836 int dir;
14837 int flags = 0;
14838 char_u nbuf1[NUMBUFLEN];
14839 char_u nbuf2[NUMBUFLEN];
14840 char_u nbuf3[NUMBUFLEN];
14841 int retval = 0; /* default: FAIL */
14842 long lnum_stop = 0;
14843 long time_limit = 0;
14845 /* Get the three pattern arguments: start, middle, end. */
14846 spat = get_tv_string_chk(&argvars[0]);
14847 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
14848 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
14849 if (spat == NULL || mpat == NULL || epat == NULL)
14850 goto theend; /* type error */
14852 /* Handle the optional fourth argument: flags */
14853 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
14854 if (dir == 0)
14855 goto theend;
14857 /* Don't accept SP_END or SP_SUBPAT.
14858 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
14860 if ((flags & (SP_END | SP_SUBPAT)) != 0
14861 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14863 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
14864 goto theend;
14867 /* Using 'r' implies 'W', otherwise it doesn't work. */
14868 if (flags & SP_REPEAT)
14869 p_ws = FALSE;
14871 /* Optional fifth argument: skip expression */
14872 if (argvars[3].v_type == VAR_UNKNOWN
14873 || argvars[4].v_type == VAR_UNKNOWN)
14874 skip = (char_u *)"";
14875 else
14877 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
14878 if (argvars[5].v_type != VAR_UNKNOWN)
14880 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
14881 if (lnum_stop < 0)
14882 goto theend;
14883 #ifdef FEAT_RELTIME
14884 if (argvars[6].v_type != VAR_UNKNOWN)
14886 time_limit = get_tv_number_chk(&argvars[6], NULL);
14887 if (time_limit < 0)
14888 goto theend;
14890 #endif
14893 if (skip == NULL)
14894 goto theend; /* type error */
14896 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
14897 match_pos, lnum_stop, time_limit);
14899 theend:
14900 p_ws = save_p_ws;
14902 return retval;
14906 * "searchpair()" function
14908 static void
14909 f_searchpair(argvars, rettv)
14910 typval_T *argvars;
14911 typval_T *rettv;
14913 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
14917 * "searchpairpos()" function
14919 static void
14920 f_searchpairpos(argvars, rettv)
14921 typval_T *argvars;
14922 typval_T *rettv;
14924 pos_T match_pos;
14925 int lnum = 0;
14926 int col = 0;
14928 rettv->vval.v_number = 0;
14930 if (rettv_list_alloc(rettv) == FAIL)
14931 return;
14933 if (searchpair_cmn(argvars, &match_pos) > 0)
14935 lnum = match_pos.lnum;
14936 col = match_pos.col;
14939 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14940 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14944 * Search for a start/middle/end thing.
14945 * Used by searchpair(), see its documentation for the details.
14946 * Returns 0 or -1 for no match,
14948 long
14949 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
14950 lnum_stop, time_limit)
14951 char_u *spat; /* start pattern */
14952 char_u *mpat; /* middle pattern */
14953 char_u *epat; /* end pattern */
14954 int dir; /* BACKWARD or FORWARD */
14955 char_u *skip; /* skip expression */
14956 int flags; /* SP_SETPCMARK and other SP_ values */
14957 pos_T *match_pos;
14958 linenr_T lnum_stop; /* stop at this line if not zero */
14959 long time_limit; /* stop after this many msec */
14961 char_u *save_cpo;
14962 char_u *pat, *pat2 = NULL, *pat3 = NULL;
14963 long retval = 0;
14964 pos_T pos;
14965 pos_T firstpos;
14966 pos_T foundpos;
14967 pos_T save_cursor;
14968 pos_T save_pos;
14969 int n;
14970 int r;
14971 int nest = 1;
14972 int err;
14973 int options = SEARCH_KEEP;
14974 proftime_T tm;
14976 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
14977 save_cpo = p_cpo;
14978 p_cpo = (char_u *)"";
14980 #ifdef FEAT_RELTIME
14981 /* Set the time limit, if there is one. */
14982 profile_setlimit(time_limit, &tm);
14983 #endif
14985 /* Make two search patterns: start/end (pat2, for in nested pairs) and
14986 * start/middle/end (pat3, for the top pair). */
14987 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
14988 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
14989 if (pat2 == NULL || pat3 == NULL)
14990 goto theend;
14991 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
14992 if (*mpat == NUL)
14993 STRCPY(pat3, pat2);
14994 else
14995 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
14996 spat, epat, mpat);
14997 if (flags & SP_START)
14998 options |= SEARCH_START;
15000 save_cursor = curwin->w_cursor;
15001 pos = curwin->w_cursor;
15002 clearpos(&firstpos);
15003 clearpos(&foundpos);
15004 pat = pat3;
15005 for (;;)
15007 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15008 options, RE_SEARCH, lnum_stop, &tm);
15009 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
15010 /* didn't find it or found the first match again: FAIL */
15011 break;
15013 if (firstpos.lnum == 0)
15014 firstpos = pos;
15015 if (equalpos(pos, foundpos))
15017 /* Found the same position again. Can happen with a pattern that
15018 * has "\zs" at the end and searching backwards. Advance one
15019 * character and try again. */
15020 if (dir == BACKWARD)
15021 decl(&pos);
15022 else
15023 incl(&pos);
15025 foundpos = pos;
15027 /* clear the start flag to avoid getting stuck here */
15028 options &= ~SEARCH_START;
15030 /* If the skip pattern matches, ignore this match. */
15031 if (*skip != NUL)
15033 save_pos = curwin->w_cursor;
15034 curwin->w_cursor = pos;
15035 r = eval_to_bool(skip, &err, NULL, FALSE);
15036 curwin->w_cursor = save_pos;
15037 if (err)
15039 /* Evaluating {skip} caused an error, break here. */
15040 curwin->w_cursor = save_cursor;
15041 retval = -1;
15042 break;
15044 if (r)
15045 continue;
15048 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
15050 /* Found end when searching backwards or start when searching
15051 * forward: nested pair. */
15052 ++nest;
15053 pat = pat2; /* nested, don't search for middle */
15055 else
15057 /* Found end when searching forward or start when searching
15058 * backward: end of (nested) pair; or found middle in outer pair. */
15059 if (--nest == 1)
15060 pat = pat3; /* outer level, search for middle */
15063 if (nest == 0)
15065 /* Found the match: return matchcount or line number. */
15066 if (flags & SP_RETCOUNT)
15067 ++retval;
15068 else
15069 retval = pos.lnum;
15070 if (flags & SP_SETPCMARK)
15071 setpcmark();
15072 curwin->w_cursor = pos;
15073 if (!(flags & SP_REPEAT))
15074 break;
15075 nest = 1; /* search for next unmatched */
15079 if (match_pos != NULL)
15081 /* Store the match cursor position */
15082 match_pos->lnum = curwin->w_cursor.lnum;
15083 match_pos->col = curwin->w_cursor.col + 1;
15086 /* If 'n' flag is used or search failed: restore cursor position. */
15087 if ((flags & SP_NOMOVE) || retval == 0)
15088 curwin->w_cursor = save_cursor;
15090 theend:
15091 vim_free(pat2);
15092 vim_free(pat3);
15093 p_cpo = save_cpo;
15095 return retval;
15099 * "searchpos()" function
15101 static void
15102 f_searchpos(argvars, rettv)
15103 typval_T *argvars;
15104 typval_T *rettv;
15106 pos_T match_pos;
15107 int lnum = 0;
15108 int col = 0;
15109 int n;
15110 int flags = 0;
15112 rettv->vval.v_number = 0;
15114 if (rettv_list_alloc(rettv) == FAIL)
15115 return;
15117 n = search_cmn(argvars, &match_pos, &flags);
15118 if (n > 0)
15120 lnum = match_pos.lnum;
15121 col = match_pos.col;
15124 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15125 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15126 if (flags & SP_SUBPAT)
15127 list_append_number(rettv->vval.v_list, (varnumber_T)n);
15131 /*ARGSUSED*/
15132 static void
15133 f_server2client(argvars, rettv)
15134 typval_T *argvars;
15135 typval_T *rettv;
15137 #ifdef FEAT_CLIENTSERVER
15138 char_u buf[NUMBUFLEN];
15139 char_u *server = get_tv_string_chk(&argvars[0]);
15140 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
15142 rettv->vval.v_number = -1;
15143 if (server == NULL || reply == NULL)
15144 return;
15145 if (check_restricted() || check_secure())
15146 return;
15147 # ifdef FEAT_X11
15148 if (check_connection() == FAIL)
15149 return;
15150 # endif
15152 if (serverSendReply(server, reply) < 0)
15154 EMSG(_("E258: Unable to send to client"));
15155 return;
15157 rettv->vval.v_number = 0;
15158 #else
15159 rettv->vval.v_number = -1;
15160 #endif
15163 /*ARGSUSED*/
15164 static void
15165 f_serverlist(argvars, rettv)
15166 typval_T *argvars;
15167 typval_T *rettv;
15169 char_u *r = NULL;
15171 #ifdef FEAT_CLIENTSERVER
15172 # ifdef WIN32
15173 r = serverGetVimNames();
15174 # else
15175 make_connection();
15176 if (X_DISPLAY != NULL)
15177 r = serverGetVimNames(X_DISPLAY);
15178 # endif
15179 #endif
15180 rettv->v_type = VAR_STRING;
15181 rettv->vval.v_string = r;
15185 * "setbufvar()" function
15187 /*ARGSUSED*/
15188 static void
15189 f_setbufvar(argvars, rettv)
15190 typval_T *argvars;
15191 typval_T *rettv;
15193 buf_T *buf;
15194 aco_save_T aco;
15195 char_u *varname, *bufvarname;
15196 typval_T *varp;
15197 char_u nbuf[NUMBUFLEN];
15199 rettv->vval.v_number = 0;
15201 if (check_restricted() || check_secure())
15202 return;
15203 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
15204 varname = get_tv_string_chk(&argvars[1]);
15205 buf = get_buf_tv(&argvars[0]);
15206 varp = &argvars[2];
15208 if (buf != NULL && varname != NULL && varp != NULL)
15210 /* set curbuf to be our buf, temporarily */
15211 aucmd_prepbuf(&aco, buf);
15213 if (*varname == '&')
15215 long numval;
15216 char_u *strval;
15217 int error = FALSE;
15219 ++varname;
15220 numval = get_tv_number_chk(varp, &error);
15221 strval = get_tv_string_buf_chk(varp, nbuf);
15222 if (!error && strval != NULL)
15223 set_option_value(varname, numval, strval, OPT_LOCAL);
15225 else
15227 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
15228 if (bufvarname != NULL)
15230 STRCPY(bufvarname, "b:");
15231 STRCPY(bufvarname + 2, varname);
15232 set_var(bufvarname, varp, TRUE);
15233 vim_free(bufvarname);
15237 /* reset notion of buffer */
15238 aucmd_restbuf(&aco);
15243 * "setcmdpos()" function
15245 static void
15246 f_setcmdpos(argvars, rettv)
15247 typval_T *argvars;
15248 typval_T *rettv;
15250 int pos = (int)get_tv_number(&argvars[0]) - 1;
15252 if (pos >= 0)
15253 rettv->vval.v_number = set_cmdline_pos(pos);
15257 * "setline()" function
15259 static void
15260 f_setline(argvars, rettv)
15261 typval_T *argvars;
15262 typval_T *rettv;
15264 linenr_T lnum;
15265 char_u *line = NULL;
15266 list_T *l = NULL;
15267 listitem_T *li = NULL;
15268 long added = 0;
15269 linenr_T lcount = curbuf->b_ml.ml_line_count;
15271 lnum = get_tv_lnum(&argvars[0]);
15272 if (argvars[1].v_type == VAR_LIST)
15274 l = argvars[1].vval.v_list;
15275 li = l->lv_first;
15277 else
15278 line = get_tv_string_chk(&argvars[1]);
15280 rettv->vval.v_number = 0; /* OK */
15281 for (;;)
15283 if (l != NULL)
15285 /* list argument, get next string */
15286 if (li == NULL)
15287 break;
15288 line = get_tv_string_chk(&li->li_tv);
15289 li = li->li_next;
15292 rettv->vval.v_number = 1; /* FAIL */
15293 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
15294 break;
15295 if (lnum <= curbuf->b_ml.ml_line_count)
15297 /* existing line, replace it */
15298 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
15300 changed_bytes(lnum, 0);
15301 if (lnum == curwin->w_cursor.lnum)
15302 check_cursor_col();
15303 rettv->vval.v_number = 0; /* OK */
15306 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
15308 /* lnum is one past the last line, append the line */
15309 ++added;
15310 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
15311 rettv->vval.v_number = 0; /* OK */
15314 if (l == NULL) /* only one string argument */
15315 break;
15316 ++lnum;
15319 if (added > 0)
15320 appended_lines_mark(lcount, added);
15323 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
15326 * Used by "setqflist()" and "setloclist()" functions
15328 /*ARGSUSED*/
15329 static void
15330 set_qf_ll_list(wp, list_arg, action_arg, rettv)
15331 win_T *wp;
15332 typval_T *list_arg;
15333 typval_T *action_arg;
15334 typval_T *rettv;
15336 #ifdef FEAT_QUICKFIX
15337 char_u *act;
15338 int action = ' ';
15339 #endif
15341 rettv->vval.v_number = -1;
15343 #ifdef FEAT_QUICKFIX
15344 if (list_arg->v_type != VAR_LIST)
15345 EMSG(_(e_listreq));
15346 else
15348 list_T *l = list_arg->vval.v_list;
15350 if (action_arg->v_type == VAR_STRING)
15352 act = get_tv_string_chk(action_arg);
15353 if (act == NULL)
15354 return; /* type error; errmsg already given */
15355 if (*act == 'a' || *act == 'r')
15356 action = *act;
15359 if (l != NULL && set_errorlist(wp, l, action) == OK)
15360 rettv->vval.v_number = 0;
15362 #endif
15366 * "setloclist()" function
15368 /*ARGSUSED*/
15369 static void
15370 f_setloclist(argvars, rettv)
15371 typval_T *argvars;
15372 typval_T *rettv;
15374 win_T *win;
15376 rettv->vval.v_number = -1;
15378 win = find_win_by_nr(&argvars[0], NULL);
15379 if (win != NULL)
15380 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
15384 * "setmatches()" function
15386 static void
15387 f_setmatches(argvars, rettv)
15388 typval_T *argvars;
15389 typval_T *rettv;
15391 #ifdef FEAT_SEARCH_EXTRA
15392 list_T *l;
15393 listitem_T *li;
15394 dict_T *d;
15396 rettv->vval.v_number = -1;
15397 if (argvars[0].v_type != VAR_LIST)
15399 EMSG(_(e_listreq));
15400 return;
15402 if ((l = argvars[0].vval.v_list) != NULL)
15405 /* To some extent make sure that we are dealing with a list from
15406 * "getmatches()". */
15407 li = l->lv_first;
15408 while (li != NULL)
15410 if (li->li_tv.v_type != VAR_DICT
15411 || (d = li->li_tv.vval.v_dict) == NULL)
15413 EMSG(_(e_invarg));
15414 return;
15416 if (!(dict_find(d, (char_u *)"group", -1) != NULL
15417 && dict_find(d, (char_u *)"pattern", -1) != NULL
15418 && dict_find(d, (char_u *)"priority", -1) != NULL
15419 && dict_find(d, (char_u *)"id", -1) != NULL))
15421 EMSG(_(e_invarg));
15422 return;
15424 li = li->li_next;
15427 clear_matches(curwin);
15428 li = l->lv_first;
15429 while (li != NULL)
15431 d = li->li_tv.vval.v_dict;
15432 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
15433 get_dict_string(d, (char_u *)"pattern", FALSE),
15434 (int)get_dict_number(d, (char_u *)"priority"),
15435 (int)get_dict_number(d, (char_u *)"id"));
15436 li = li->li_next;
15438 rettv->vval.v_number = 0;
15440 #endif
15444 * "setpos()" function
15446 /*ARGSUSED*/
15447 static void
15448 f_setpos(argvars, rettv)
15449 typval_T *argvars;
15450 typval_T *rettv;
15452 pos_T pos;
15453 int fnum;
15454 char_u *name;
15456 rettv->vval.v_number = -1;
15457 name = get_tv_string_chk(argvars);
15458 if (name != NULL)
15460 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
15462 --pos.col;
15463 if (name[0] == '.' && name[1] == NUL)
15465 /* set cursor */
15466 if (fnum == curbuf->b_fnum)
15468 curwin->w_cursor = pos;
15469 check_cursor();
15470 rettv->vval.v_number = 0;
15472 else
15473 EMSG(_(e_invarg));
15475 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
15477 /* set mark */
15478 if (setmark_pos(name[1], &pos, fnum) == OK)
15479 rettv->vval.v_number = 0;
15481 else
15482 EMSG(_(e_invarg));
15488 * "setqflist()" function
15490 /*ARGSUSED*/
15491 static void
15492 f_setqflist(argvars, rettv)
15493 typval_T *argvars;
15494 typval_T *rettv;
15496 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
15500 * "setreg()" function
15502 static void
15503 f_setreg(argvars, rettv)
15504 typval_T *argvars;
15505 typval_T *rettv;
15507 int regname;
15508 char_u *strregname;
15509 char_u *stropt;
15510 char_u *strval;
15511 int append;
15512 char_u yank_type;
15513 long block_len;
15515 block_len = -1;
15516 yank_type = MAUTO;
15517 append = FALSE;
15519 strregname = get_tv_string_chk(argvars);
15520 rettv->vval.v_number = 1; /* FAIL is default */
15522 if (strregname == NULL)
15523 return; /* type error; errmsg already given */
15524 regname = *strregname;
15525 if (regname == 0 || regname == '@')
15526 regname = '"';
15527 else if (regname == '=')
15528 return;
15530 if (argvars[2].v_type != VAR_UNKNOWN)
15532 stropt = get_tv_string_chk(&argvars[2]);
15533 if (stropt == NULL)
15534 return; /* type error */
15535 for (; *stropt != NUL; ++stropt)
15536 switch (*stropt)
15538 case 'a': case 'A': /* append */
15539 append = TRUE;
15540 break;
15541 case 'v': case 'c': /* character-wise selection */
15542 yank_type = MCHAR;
15543 break;
15544 case 'V': case 'l': /* line-wise selection */
15545 yank_type = MLINE;
15546 break;
15547 #ifdef FEAT_VISUAL
15548 case 'b': case Ctrl_V: /* block-wise selection */
15549 yank_type = MBLOCK;
15550 if (VIM_ISDIGIT(stropt[1]))
15552 ++stropt;
15553 block_len = getdigits(&stropt) - 1;
15554 --stropt;
15556 break;
15557 #endif
15561 strval = get_tv_string_chk(&argvars[1]);
15562 if (strval != NULL)
15563 write_reg_contents_ex(regname, strval, -1,
15564 append, yank_type, block_len);
15565 rettv->vval.v_number = 0;
15569 * "settabwinvar()" function
15571 static void
15572 f_settabwinvar(argvars, rettv)
15573 typval_T *argvars;
15574 typval_T *rettv;
15576 setwinvar(argvars, rettv, 1);
15580 * "setwinvar()" function
15582 static void
15583 f_setwinvar(argvars, rettv)
15584 typval_T *argvars;
15585 typval_T *rettv;
15587 setwinvar(argvars, rettv, 0);
15591 * "setwinvar()" and "settabwinvar()" functions
15593 static void
15594 setwinvar(argvars, rettv, off)
15595 typval_T *argvars;
15596 typval_T *rettv;
15597 int off;
15599 win_T *win;
15600 #ifdef FEAT_WINDOWS
15601 win_T *save_curwin;
15602 tabpage_T *save_curtab;
15603 #endif
15604 char_u *varname, *winvarname;
15605 typval_T *varp;
15606 char_u nbuf[NUMBUFLEN];
15607 tabpage_T *tp;
15609 rettv->vval.v_number = 0;
15611 if (check_restricted() || check_secure())
15612 return;
15614 #ifdef FEAT_WINDOWS
15615 if (off == 1)
15616 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
15617 else
15618 tp = curtab;
15619 #endif
15620 win = find_win_by_nr(&argvars[off], tp);
15621 varname = get_tv_string_chk(&argvars[off + 1]);
15622 varp = &argvars[off + 2];
15624 if (win != NULL && varname != NULL && varp != NULL)
15626 #ifdef FEAT_WINDOWS
15627 /* set curwin to be our win, temporarily */
15628 save_curwin = curwin;
15629 save_curtab = curtab;
15630 goto_tabpage_tp(tp);
15631 if (!win_valid(win))
15632 return;
15633 curwin = win;
15634 curbuf = curwin->w_buffer;
15635 #endif
15637 if (*varname == '&')
15639 long numval;
15640 char_u *strval;
15641 int error = FALSE;
15643 ++varname;
15644 numval = get_tv_number_chk(varp, &error);
15645 strval = get_tv_string_buf_chk(varp, nbuf);
15646 if (!error && strval != NULL)
15647 set_option_value(varname, numval, strval, OPT_LOCAL);
15649 else
15651 winvarname = alloc((unsigned)STRLEN(varname) + 3);
15652 if (winvarname != NULL)
15654 STRCPY(winvarname, "w:");
15655 STRCPY(winvarname + 2, varname);
15656 set_var(winvarname, varp, TRUE);
15657 vim_free(winvarname);
15661 #ifdef FEAT_WINDOWS
15662 /* Restore current tabpage and window, if still valid (autocomands can
15663 * make them invalid). */
15664 if (valid_tabpage(save_curtab))
15665 goto_tabpage_tp(save_curtab);
15666 if (win_valid(save_curwin))
15668 curwin = save_curwin;
15669 curbuf = curwin->w_buffer;
15671 #endif
15676 * "shellescape({string})" function
15678 static void
15679 f_shellescape(argvars, rettv)
15680 typval_T *argvars;
15681 typval_T *rettv;
15683 rettv->vval.v_string = vim_strsave_shellescape(get_tv_string(&argvars[0]));
15684 rettv->v_type = VAR_STRING;
15688 * "simplify()" function
15690 static void
15691 f_simplify(argvars, rettv)
15692 typval_T *argvars;
15693 typval_T *rettv;
15695 char_u *p;
15697 p = get_tv_string(&argvars[0]);
15698 rettv->vval.v_string = vim_strsave(p);
15699 simplify_filename(rettv->vval.v_string); /* simplify in place */
15700 rettv->v_type = VAR_STRING;
15703 #ifdef FEAT_FLOAT
15705 * "sin()" function
15707 static void
15708 f_sin(argvars, rettv)
15709 typval_T *argvars;
15710 typval_T *rettv;
15712 float_T f;
15714 rettv->v_type = VAR_FLOAT;
15715 if (get_float_arg(argvars, &f) == OK)
15716 rettv->vval.v_float = sin(f);
15717 else
15718 rettv->vval.v_float = 0.0;
15720 #endif
15722 static int
15723 #ifdef __BORLANDC__
15724 _RTLENTRYF
15725 #endif
15726 item_compare __ARGS((const void *s1, const void *s2));
15727 static int
15728 #ifdef __BORLANDC__
15729 _RTLENTRYF
15730 #endif
15731 item_compare2 __ARGS((const void *s1, const void *s2));
15733 static int item_compare_ic;
15734 static char_u *item_compare_func;
15735 static int item_compare_func_err;
15736 #define ITEM_COMPARE_FAIL 999
15739 * Compare functions for f_sort() below.
15741 static int
15742 #ifdef __BORLANDC__
15743 _RTLENTRYF
15744 #endif
15745 item_compare(s1, s2)
15746 const void *s1;
15747 const void *s2;
15749 char_u *p1, *p2;
15750 char_u *tofree1, *tofree2;
15751 int res;
15752 char_u numbuf1[NUMBUFLEN];
15753 char_u numbuf2[NUMBUFLEN];
15755 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
15756 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
15757 if (p1 == NULL)
15758 p1 = (char_u *)"";
15759 if (p2 == NULL)
15760 p2 = (char_u *)"";
15761 if (item_compare_ic)
15762 res = STRICMP(p1, p2);
15763 else
15764 res = STRCMP(p1, p2);
15765 vim_free(tofree1);
15766 vim_free(tofree2);
15767 return res;
15770 static int
15771 #ifdef __BORLANDC__
15772 _RTLENTRYF
15773 #endif
15774 item_compare2(s1, s2)
15775 const void *s1;
15776 const void *s2;
15778 int res;
15779 typval_T rettv;
15780 typval_T argv[3];
15781 int dummy;
15783 /* shortcut after failure in previous call; compare all items equal */
15784 if (item_compare_func_err)
15785 return 0;
15787 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
15788 * in the copy without changing the original list items. */
15789 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
15790 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
15792 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
15793 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
15794 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
15795 clear_tv(&argv[0]);
15796 clear_tv(&argv[1]);
15798 if (res == FAIL)
15799 res = ITEM_COMPARE_FAIL;
15800 else
15801 /* return value has wrong type */
15802 res = get_tv_number_chk(&rettv, &item_compare_func_err);
15803 if (item_compare_func_err)
15804 res = ITEM_COMPARE_FAIL;
15805 clear_tv(&rettv);
15806 return res;
15810 * "sort({list})" function
15812 static void
15813 f_sort(argvars, rettv)
15814 typval_T *argvars;
15815 typval_T *rettv;
15817 list_T *l;
15818 listitem_T *li;
15819 listitem_T **ptrs;
15820 long len;
15821 long i;
15823 rettv->vval.v_number = 0;
15824 if (argvars[0].v_type != VAR_LIST)
15825 EMSG2(_(e_listarg), "sort()");
15826 else
15828 l = argvars[0].vval.v_list;
15829 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
15830 return;
15831 rettv->vval.v_list = l;
15832 rettv->v_type = VAR_LIST;
15833 ++l->lv_refcount;
15835 len = list_len(l);
15836 if (len <= 1)
15837 return; /* short list sorts pretty quickly */
15839 item_compare_ic = FALSE;
15840 item_compare_func = NULL;
15841 if (argvars[1].v_type != VAR_UNKNOWN)
15843 if (argvars[1].v_type == VAR_FUNC)
15844 item_compare_func = argvars[1].vval.v_string;
15845 else
15847 int error = FALSE;
15849 i = get_tv_number_chk(&argvars[1], &error);
15850 if (error)
15851 return; /* type error; errmsg already given */
15852 if (i == 1)
15853 item_compare_ic = TRUE;
15854 else
15855 item_compare_func = get_tv_string(&argvars[1]);
15859 /* Make an array with each entry pointing to an item in the List. */
15860 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
15861 if (ptrs == NULL)
15862 return;
15863 i = 0;
15864 for (li = l->lv_first; li != NULL; li = li->li_next)
15865 ptrs[i++] = li;
15867 item_compare_func_err = FALSE;
15868 /* test the compare function */
15869 if (item_compare_func != NULL
15870 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
15871 == ITEM_COMPARE_FAIL)
15872 EMSG(_("E702: Sort compare function failed"));
15873 else
15875 /* Sort the array with item pointers. */
15876 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
15877 item_compare_func == NULL ? item_compare : item_compare2);
15879 if (!item_compare_func_err)
15881 /* Clear the List and append the items in the sorted order. */
15882 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
15883 l->lv_len = 0;
15884 for (i = 0; i < len; ++i)
15885 list_append(l, ptrs[i]);
15889 vim_free(ptrs);
15894 * "soundfold({word})" function
15896 static void
15897 f_soundfold(argvars, rettv)
15898 typval_T *argvars;
15899 typval_T *rettv;
15901 char_u *s;
15903 rettv->v_type = VAR_STRING;
15904 s = get_tv_string(&argvars[0]);
15905 #ifdef FEAT_SPELL
15906 rettv->vval.v_string = eval_soundfold(s);
15907 #else
15908 rettv->vval.v_string = vim_strsave(s);
15909 #endif
15913 * "spellbadword()" function
15915 /* ARGSUSED */
15916 static void
15917 f_spellbadword(argvars, rettv)
15918 typval_T *argvars;
15919 typval_T *rettv;
15921 char_u *word = (char_u *)"";
15922 hlf_T attr = HLF_COUNT;
15923 int len = 0;
15925 if (rettv_list_alloc(rettv) == FAIL)
15926 return;
15928 #ifdef FEAT_SPELL
15929 if (argvars[0].v_type == VAR_UNKNOWN)
15931 /* Find the start and length of the badly spelled word. */
15932 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
15933 if (len != 0)
15934 word = ml_get_cursor();
15936 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15938 char_u *str = get_tv_string_chk(&argvars[0]);
15939 int capcol = -1;
15941 if (str != NULL)
15943 /* Check the argument for spelling. */
15944 while (*str != NUL)
15946 len = spell_check(curwin, str, &attr, &capcol, FALSE);
15947 if (attr != HLF_COUNT)
15949 word = str;
15950 break;
15952 str += len;
15956 #endif
15958 list_append_string(rettv->vval.v_list, word, len);
15959 list_append_string(rettv->vval.v_list, (char_u *)(
15960 attr == HLF_SPB ? "bad" :
15961 attr == HLF_SPR ? "rare" :
15962 attr == HLF_SPL ? "local" :
15963 attr == HLF_SPC ? "caps" :
15964 ""), -1);
15968 * "spellsuggest()" function
15970 /*ARGSUSED*/
15971 static void
15972 f_spellsuggest(argvars, rettv)
15973 typval_T *argvars;
15974 typval_T *rettv;
15976 #ifdef FEAT_SPELL
15977 char_u *str;
15978 int typeerr = FALSE;
15979 int maxcount;
15980 garray_T ga;
15981 int i;
15982 listitem_T *li;
15983 int need_capital = FALSE;
15984 #endif
15986 if (rettv_list_alloc(rettv) == FAIL)
15987 return;
15989 #ifdef FEAT_SPELL
15990 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15992 str = get_tv_string(&argvars[0]);
15993 if (argvars[1].v_type != VAR_UNKNOWN)
15995 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
15996 if (maxcount <= 0)
15997 return;
15998 if (argvars[2].v_type != VAR_UNKNOWN)
16000 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
16001 if (typeerr)
16002 return;
16005 else
16006 maxcount = 25;
16008 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
16010 for (i = 0; i < ga.ga_len; ++i)
16012 str = ((char_u **)ga.ga_data)[i];
16014 li = listitem_alloc();
16015 if (li == NULL)
16016 vim_free(str);
16017 else
16019 li->li_tv.v_type = VAR_STRING;
16020 li->li_tv.v_lock = 0;
16021 li->li_tv.vval.v_string = str;
16022 list_append(rettv->vval.v_list, li);
16025 ga_clear(&ga);
16027 #endif
16030 static void
16031 f_split(argvars, rettv)
16032 typval_T *argvars;
16033 typval_T *rettv;
16035 char_u *str;
16036 char_u *end;
16037 char_u *pat = NULL;
16038 regmatch_T regmatch;
16039 char_u patbuf[NUMBUFLEN];
16040 char_u *save_cpo;
16041 int match;
16042 colnr_T col = 0;
16043 int keepempty = FALSE;
16044 int typeerr = FALSE;
16046 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
16047 save_cpo = p_cpo;
16048 p_cpo = (char_u *)"";
16050 str = get_tv_string(&argvars[0]);
16051 if (argvars[1].v_type != VAR_UNKNOWN)
16053 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16054 if (pat == NULL)
16055 typeerr = TRUE;
16056 if (argvars[2].v_type != VAR_UNKNOWN)
16057 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
16059 if (pat == NULL || *pat == NUL)
16060 pat = (char_u *)"[\\x01- ]\\+";
16062 if (rettv_list_alloc(rettv) == FAIL)
16063 return;
16064 if (typeerr)
16065 return;
16067 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
16068 if (regmatch.regprog != NULL)
16070 regmatch.rm_ic = FALSE;
16071 while (*str != NUL || keepempty)
16073 if (*str == NUL)
16074 match = FALSE; /* empty item at the end */
16075 else
16076 match = vim_regexec_nl(&regmatch, str, col);
16077 if (match)
16078 end = regmatch.startp[0];
16079 else
16080 end = str + STRLEN(str);
16081 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
16082 && *str != NUL && match && end < regmatch.endp[0]))
16084 if (list_append_string(rettv->vval.v_list, str,
16085 (int)(end - str)) == FAIL)
16086 break;
16088 if (!match)
16089 break;
16090 /* Advance to just after the match. */
16091 if (regmatch.endp[0] > str)
16092 col = 0;
16093 else
16095 /* Don't get stuck at the same match. */
16096 #ifdef FEAT_MBYTE
16097 col = (*mb_ptr2len)(regmatch.endp[0]);
16098 #else
16099 col = 1;
16100 #endif
16102 str = regmatch.endp[0];
16105 vim_free(regmatch.regprog);
16108 p_cpo = save_cpo;
16111 #ifdef FEAT_FLOAT
16113 * "sqrt()" function
16115 static void
16116 f_sqrt(argvars, rettv)
16117 typval_T *argvars;
16118 typval_T *rettv;
16120 float_T f;
16122 rettv->v_type = VAR_FLOAT;
16123 if (get_float_arg(argvars, &f) == OK)
16124 rettv->vval.v_float = sqrt(f);
16125 else
16126 rettv->vval.v_float = 0.0;
16130 * "str2float()" function
16132 static void
16133 f_str2float(argvars, rettv)
16134 typval_T *argvars;
16135 typval_T *rettv;
16137 char_u *p = skipwhite(get_tv_string(&argvars[0]));
16139 if (*p == '+')
16140 p = skipwhite(p + 1);
16141 (void)string2float(p, &rettv->vval.v_float);
16142 rettv->v_type = VAR_FLOAT;
16144 #endif
16147 * "str2nr()" function
16149 static void
16150 f_str2nr(argvars, rettv)
16151 typval_T *argvars;
16152 typval_T *rettv;
16154 int base = 10;
16155 char_u *p;
16156 long n;
16158 if (argvars[1].v_type != VAR_UNKNOWN)
16160 base = get_tv_number(&argvars[1]);
16161 if (base != 8 && base != 10 && base != 16)
16163 EMSG(_(e_invarg));
16164 return;
16168 p = skipwhite(get_tv_string(&argvars[0]));
16169 if (*p == '+')
16170 p = skipwhite(p + 1);
16171 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
16172 rettv->vval.v_number = n;
16175 #ifdef HAVE_STRFTIME
16177 * "strftime({format}[, {time}])" function
16179 static void
16180 f_strftime(argvars, rettv)
16181 typval_T *argvars;
16182 typval_T *rettv;
16184 char_u result_buf[256];
16185 struct tm *curtime;
16186 time_t seconds;
16187 char_u *p;
16189 rettv->v_type = VAR_STRING;
16191 p = get_tv_string(&argvars[0]);
16192 if (argvars[1].v_type == VAR_UNKNOWN)
16193 seconds = time(NULL);
16194 else
16195 seconds = (time_t)get_tv_number(&argvars[1]);
16196 curtime = localtime(&seconds);
16197 /* MSVC returns NULL for an invalid value of seconds. */
16198 if (curtime == NULL)
16199 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
16200 else
16202 # ifdef FEAT_MBYTE
16203 vimconv_T conv;
16204 char_u *enc;
16206 conv.vc_type = CONV_NONE;
16207 enc = enc_locale();
16208 convert_setup(&conv, p_enc, enc);
16209 if (conv.vc_type != CONV_NONE)
16210 p = string_convert(&conv, p, NULL);
16211 # endif
16212 if (p != NULL)
16213 (void)strftime((char *)result_buf, sizeof(result_buf),
16214 (char *)p, curtime);
16215 else
16216 result_buf[0] = NUL;
16218 # ifdef FEAT_MBYTE
16219 if (conv.vc_type != CONV_NONE)
16220 vim_free(p);
16221 convert_setup(&conv, enc, p_enc);
16222 if (conv.vc_type != CONV_NONE)
16223 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
16224 else
16225 # endif
16226 rettv->vval.v_string = vim_strsave(result_buf);
16228 # ifdef FEAT_MBYTE
16229 /* Release conversion descriptors */
16230 convert_setup(&conv, NULL, NULL);
16231 vim_free(enc);
16232 # endif
16235 #endif
16238 * "stridx()" function
16240 static void
16241 f_stridx(argvars, rettv)
16242 typval_T *argvars;
16243 typval_T *rettv;
16245 char_u buf[NUMBUFLEN];
16246 char_u *needle;
16247 char_u *haystack;
16248 char_u *save_haystack;
16249 char_u *pos;
16250 int start_idx;
16252 needle = get_tv_string_chk(&argvars[1]);
16253 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
16254 rettv->vval.v_number = -1;
16255 if (needle == NULL || haystack == NULL)
16256 return; /* type error; errmsg already given */
16258 if (argvars[2].v_type != VAR_UNKNOWN)
16260 int error = FALSE;
16262 start_idx = get_tv_number_chk(&argvars[2], &error);
16263 if (error || start_idx >= (int)STRLEN(haystack))
16264 return;
16265 if (start_idx >= 0)
16266 haystack += start_idx;
16269 pos = (char_u *)strstr((char *)haystack, (char *)needle);
16270 if (pos != NULL)
16271 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
16275 * "string()" function
16277 static void
16278 f_string(argvars, rettv)
16279 typval_T *argvars;
16280 typval_T *rettv;
16282 char_u *tofree;
16283 char_u numbuf[NUMBUFLEN];
16285 rettv->v_type = VAR_STRING;
16286 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
16287 /* Make a copy if we have a value but it's not in allocated memory. */
16288 if (rettv->vval.v_string != NULL && tofree == NULL)
16289 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
16293 * "strlen()" function
16295 static void
16296 f_strlen(argvars, rettv)
16297 typval_T *argvars;
16298 typval_T *rettv;
16300 rettv->vval.v_number = (varnumber_T)(STRLEN(
16301 get_tv_string(&argvars[0])));
16305 * "strpart()" function
16307 static void
16308 f_strpart(argvars, rettv)
16309 typval_T *argvars;
16310 typval_T *rettv;
16312 char_u *p;
16313 int n;
16314 int len;
16315 int slen;
16316 int error = FALSE;
16318 p = get_tv_string(&argvars[0]);
16319 slen = (int)STRLEN(p);
16321 n = get_tv_number_chk(&argvars[1], &error);
16322 if (error)
16323 len = 0;
16324 else if (argvars[2].v_type != VAR_UNKNOWN)
16325 len = get_tv_number(&argvars[2]);
16326 else
16327 len = slen - n; /* default len: all bytes that are available. */
16330 * Only return the overlap between the specified part and the actual
16331 * string.
16333 if (n < 0)
16335 len += n;
16336 n = 0;
16338 else if (n > slen)
16339 n = slen;
16340 if (len < 0)
16341 len = 0;
16342 else if (n + len > slen)
16343 len = slen - n;
16345 rettv->v_type = VAR_STRING;
16346 rettv->vval.v_string = vim_strnsave(p + n, len);
16350 * "strridx()" function
16352 static void
16353 f_strridx(argvars, rettv)
16354 typval_T *argvars;
16355 typval_T *rettv;
16357 char_u buf[NUMBUFLEN];
16358 char_u *needle;
16359 char_u *haystack;
16360 char_u *rest;
16361 char_u *lastmatch = NULL;
16362 int haystack_len, end_idx;
16364 needle = get_tv_string_chk(&argvars[1]);
16365 haystack = get_tv_string_buf_chk(&argvars[0], buf);
16367 rettv->vval.v_number = -1;
16368 if (needle == NULL || haystack == NULL)
16369 return; /* type error; errmsg already given */
16371 haystack_len = (int)STRLEN(haystack);
16372 if (argvars[2].v_type != VAR_UNKNOWN)
16374 /* Third argument: upper limit for index */
16375 end_idx = get_tv_number_chk(&argvars[2], NULL);
16376 if (end_idx < 0)
16377 return; /* can never find a match */
16379 else
16380 end_idx = haystack_len;
16382 if (*needle == NUL)
16384 /* Empty string matches past the end. */
16385 lastmatch = haystack + end_idx;
16387 else
16389 for (rest = haystack; *rest != '\0'; ++rest)
16391 rest = (char_u *)strstr((char *)rest, (char *)needle);
16392 if (rest == NULL || rest > haystack + end_idx)
16393 break;
16394 lastmatch = rest;
16398 if (lastmatch == NULL)
16399 rettv->vval.v_number = -1;
16400 else
16401 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
16405 * "strtrans()" function
16407 static void
16408 f_strtrans(argvars, rettv)
16409 typval_T *argvars;
16410 typval_T *rettv;
16412 rettv->v_type = VAR_STRING;
16413 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
16417 * "submatch()" function
16419 static void
16420 f_submatch(argvars, rettv)
16421 typval_T *argvars;
16422 typval_T *rettv;
16424 rettv->v_type = VAR_STRING;
16425 rettv->vval.v_string =
16426 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
16430 * "substitute()" function
16432 static void
16433 f_substitute(argvars, rettv)
16434 typval_T *argvars;
16435 typval_T *rettv;
16437 char_u patbuf[NUMBUFLEN];
16438 char_u subbuf[NUMBUFLEN];
16439 char_u flagsbuf[NUMBUFLEN];
16441 char_u *str = get_tv_string_chk(&argvars[0]);
16442 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16443 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
16444 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
16446 rettv->v_type = VAR_STRING;
16447 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
16448 rettv->vval.v_string = NULL;
16449 else
16450 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
16454 * "synID(lnum, col, trans)" function
16456 /*ARGSUSED*/
16457 static void
16458 f_synID(argvars, rettv)
16459 typval_T *argvars;
16460 typval_T *rettv;
16462 int id = 0;
16463 #ifdef FEAT_SYN_HL
16464 long lnum;
16465 long col;
16466 int trans;
16467 int transerr = FALSE;
16469 lnum = get_tv_lnum(argvars); /* -1 on type error */
16470 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16471 trans = get_tv_number_chk(&argvars[2], &transerr);
16473 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16474 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
16475 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
16476 #endif
16478 rettv->vval.v_number = id;
16482 * "synIDattr(id, what [, mode])" function
16484 /*ARGSUSED*/
16485 static void
16486 f_synIDattr(argvars, rettv)
16487 typval_T *argvars;
16488 typval_T *rettv;
16490 char_u *p = NULL;
16491 #ifdef FEAT_SYN_HL
16492 int id;
16493 char_u *what;
16494 char_u *mode;
16495 char_u modebuf[NUMBUFLEN];
16496 int modec;
16498 id = get_tv_number(&argvars[0]);
16499 what = get_tv_string(&argvars[1]);
16500 if (argvars[2].v_type != VAR_UNKNOWN)
16502 mode = get_tv_string_buf(&argvars[2], modebuf);
16503 modec = TOLOWER_ASC(mode[0]);
16504 if (modec != 't' && modec != 'c'
16505 #ifdef FEAT_GUI
16506 && modec != 'g'
16507 #endif
16509 modec = 0; /* replace invalid with current */
16511 else
16513 #ifdef FEAT_GUI
16514 if (gui.in_use)
16515 modec = 'g';
16516 else
16517 #endif
16518 if (t_colors > 1)
16519 modec = 'c';
16520 else
16521 modec = 't';
16525 switch (TOLOWER_ASC(what[0]))
16527 case 'b':
16528 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
16529 p = highlight_color(id, what, modec);
16530 else /* bold */
16531 p = highlight_has_attr(id, HL_BOLD, modec);
16532 break;
16534 case 'f': /* fg[#] */
16535 p = highlight_color(id, what, modec);
16536 break;
16538 case 'i':
16539 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
16540 p = highlight_has_attr(id, HL_INVERSE, modec);
16541 else /* italic */
16542 p = highlight_has_attr(id, HL_ITALIC, modec);
16543 break;
16545 case 'n': /* name */
16546 p = get_highlight_name(NULL, id - 1);
16547 break;
16549 case 'r': /* reverse */
16550 p = highlight_has_attr(id, HL_INVERSE, modec);
16551 break;
16553 case 's': /* standout */
16554 p = highlight_has_attr(id, HL_STANDOUT, modec);
16555 break;
16557 case 'u':
16558 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
16559 /* underline */
16560 p = highlight_has_attr(id, HL_UNDERLINE, modec);
16561 else
16562 /* undercurl */
16563 p = highlight_has_attr(id, HL_UNDERCURL, modec);
16564 break;
16567 if (p != NULL)
16568 p = vim_strsave(p);
16569 #endif
16570 rettv->v_type = VAR_STRING;
16571 rettv->vval.v_string = p;
16575 * "synIDtrans(id)" function
16577 /*ARGSUSED*/
16578 static void
16579 f_synIDtrans(argvars, rettv)
16580 typval_T *argvars;
16581 typval_T *rettv;
16583 int id;
16585 #ifdef FEAT_SYN_HL
16586 id = get_tv_number(&argvars[0]);
16588 if (id > 0)
16589 id = syn_get_final_id(id);
16590 else
16591 #endif
16592 id = 0;
16594 rettv->vval.v_number = id;
16598 * "synstack(lnum, col)" function
16600 /*ARGSUSED*/
16601 static void
16602 f_synstack(argvars, rettv)
16603 typval_T *argvars;
16604 typval_T *rettv;
16606 #ifdef FEAT_SYN_HL
16607 long lnum;
16608 long col;
16609 int i;
16610 int id;
16611 #endif
16613 rettv->v_type = VAR_LIST;
16614 rettv->vval.v_list = NULL;
16616 #ifdef FEAT_SYN_HL
16617 lnum = get_tv_lnum(argvars); /* -1 on type error */
16618 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16620 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16621 && col >= 0 && col < (long)STRLEN(ml_get(lnum))
16622 && rettv_list_alloc(rettv) != FAIL)
16624 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
16625 for (i = 0; ; ++i)
16627 id = syn_get_stack_item(i);
16628 if (id < 0)
16629 break;
16630 if (list_append_number(rettv->vval.v_list, id) == FAIL)
16631 break;
16634 #endif
16638 * "system()" function
16640 static void
16641 f_system(argvars, rettv)
16642 typval_T *argvars;
16643 typval_T *rettv;
16645 char_u *res = NULL;
16646 char_u *p;
16647 char_u *infile = NULL;
16648 char_u buf[NUMBUFLEN];
16649 int err = FALSE;
16650 FILE *fd;
16652 if (check_restricted() || check_secure())
16653 goto done;
16655 if (argvars[1].v_type != VAR_UNKNOWN)
16658 * Write the string to a temp file, to be used for input of the shell
16659 * command.
16661 if ((infile = vim_tempname('i')) == NULL)
16663 EMSG(_(e_notmp));
16664 goto done;
16667 fd = mch_fopen((char *)infile, WRITEBIN);
16668 if (fd == NULL)
16670 EMSG2(_(e_notopen), infile);
16671 goto done;
16673 p = get_tv_string_buf_chk(&argvars[1], buf);
16674 if (p == NULL)
16676 fclose(fd);
16677 goto done; /* type error; errmsg already given */
16679 if (fwrite(p, STRLEN(p), 1, fd) != 1)
16680 err = TRUE;
16681 if (fclose(fd) != 0)
16682 err = TRUE;
16683 if (err)
16685 EMSG(_("E677: Error writing temp file"));
16686 goto done;
16690 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
16691 SHELL_SILENT | SHELL_COOKED);
16693 #ifdef USE_CR
16694 /* translate <CR> into <NL> */
16695 if (res != NULL)
16697 char_u *s;
16699 for (s = res; *s; ++s)
16701 if (*s == CAR)
16702 *s = NL;
16705 #else
16706 # ifdef USE_CRNL
16707 /* translate <CR><NL> into <NL> */
16708 if (res != NULL)
16710 char_u *s, *d;
16712 d = res;
16713 for (s = res; *s; ++s)
16715 if (s[0] == CAR && s[1] == NL)
16716 ++s;
16717 *d++ = *s;
16719 *d = NUL;
16721 # endif
16722 #endif
16724 done:
16725 if (infile != NULL)
16727 mch_remove(infile);
16728 vim_free(infile);
16730 rettv->v_type = VAR_STRING;
16731 rettv->vval.v_string = res;
16735 * "tabpagebuflist()" function
16737 /* ARGSUSED */
16738 static void
16739 f_tabpagebuflist(argvars, rettv)
16740 typval_T *argvars;
16741 typval_T *rettv;
16743 #ifndef FEAT_WINDOWS
16744 rettv->vval.v_number = 0;
16745 #else
16746 tabpage_T *tp;
16747 win_T *wp = NULL;
16749 if (argvars[0].v_type == VAR_UNKNOWN)
16750 wp = firstwin;
16751 else
16753 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16754 if (tp != NULL)
16755 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16757 if (wp == NULL)
16758 rettv->vval.v_number = 0;
16759 else
16761 if (rettv_list_alloc(rettv) == FAIL)
16762 rettv->vval.v_number = 0;
16763 else
16765 for (; wp != NULL; wp = wp->w_next)
16766 if (list_append_number(rettv->vval.v_list,
16767 wp->w_buffer->b_fnum) == FAIL)
16768 break;
16771 #endif
16776 * "tabpagenr()" function
16778 /* ARGSUSED */
16779 static void
16780 f_tabpagenr(argvars, rettv)
16781 typval_T *argvars;
16782 typval_T *rettv;
16784 int nr = 1;
16785 #ifdef FEAT_WINDOWS
16786 char_u *arg;
16788 if (argvars[0].v_type != VAR_UNKNOWN)
16790 arg = get_tv_string_chk(&argvars[0]);
16791 nr = 0;
16792 if (arg != NULL)
16794 if (STRCMP(arg, "$") == 0)
16795 nr = tabpage_index(NULL) - 1;
16796 else
16797 EMSG2(_(e_invexpr2), arg);
16800 else
16801 nr = tabpage_index(curtab);
16802 #endif
16803 rettv->vval.v_number = nr;
16807 #ifdef FEAT_WINDOWS
16808 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
16811 * Common code for tabpagewinnr() and winnr().
16813 static int
16814 get_winnr(tp, argvar)
16815 tabpage_T *tp;
16816 typval_T *argvar;
16818 win_T *twin;
16819 int nr = 1;
16820 win_T *wp;
16821 char_u *arg;
16823 twin = (tp == curtab) ? curwin : tp->tp_curwin;
16824 if (argvar->v_type != VAR_UNKNOWN)
16826 arg = get_tv_string_chk(argvar);
16827 if (arg == NULL)
16828 nr = 0; /* type error; errmsg already given */
16829 else if (STRCMP(arg, "$") == 0)
16830 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
16831 else if (STRCMP(arg, "#") == 0)
16833 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
16834 if (twin == NULL)
16835 nr = 0;
16837 else
16839 EMSG2(_(e_invexpr2), arg);
16840 nr = 0;
16844 if (nr > 0)
16845 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16846 wp != twin; wp = wp->w_next)
16848 if (wp == NULL)
16850 /* didn't find it in this tabpage */
16851 nr = 0;
16852 break;
16854 ++nr;
16856 return nr;
16858 #endif
16861 * "tabpagewinnr()" function
16863 /* ARGSUSED */
16864 static void
16865 f_tabpagewinnr(argvars, rettv)
16866 typval_T *argvars;
16867 typval_T *rettv;
16869 int nr = 1;
16870 #ifdef FEAT_WINDOWS
16871 tabpage_T *tp;
16873 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16874 if (tp == NULL)
16875 nr = 0;
16876 else
16877 nr = get_winnr(tp, &argvars[1]);
16878 #endif
16879 rettv->vval.v_number = nr;
16884 * "tagfiles()" function
16886 /*ARGSUSED*/
16887 static void
16888 f_tagfiles(argvars, rettv)
16889 typval_T *argvars;
16890 typval_T *rettv;
16892 char_u fname[MAXPATHL + 1];
16893 tagname_T tn;
16894 int first;
16896 if (rettv_list_alloc(rettv) == FAIL)
16898 rettv->vval.v_number = 0;
16899 return;
16902 for (first = TRUE; ; first = FALSE)
16903 if (get_tagfname(&tn, first, fname) == FAIL
16904 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
16905 break;
16906 tagname_free(&tn);
16910 * "taglist()" function
16912 static void
16913 f_taglist(argvars, rettv)
16914 typval_T *argvars;
16915 typval_T *rettv;
16917 char_u *tag_pattern;
16919 tag_pattern = get_tv_string(&argvars[0]);
16921 rettv->vval.v_number = FALSE;
16922 if (*tag_pattern == NUL)
16923 return;
16925 if (rettv_list_alloc(rettv) == OK)
16926 (void)get_tags(rettv->vval.v_list, tag_pattern);
16930 * "tempname()" function
16932 /*ARGSUSED*/
16933 static void
16934 f_tempname(argvars, rettv)
16935 typval_T *argvars;
16936 typval_T *rettv;
16938 static int x = 'A';
16940 rettv->v_type = VAR_STRING;
16941 rettv->vval.v_string = vim_tempname(x);
16943 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
16944 * names. Skip 'I' and 'O', they are used for shell redirection. */
16947 if (x == 'Z')
16948 x = '0';
16949 else if (x == '9')
16950 x = 'A';
16951 else
16953 #ifdef EBCDIC
16954 if (x == 'I')
16955 x = 'J';
16956 else if (x == 'R')
16957 x = 'S';
16958 else
16959 #endif
16960 ++x;
16962 } while (x == 'I' || x == 'O');
16966 * "test(list)" function: Just checking the walls...
16968 /*ARGSUSED*/
16969 static void
16970 f_test(argvars, rettv)
16971 typval_T *argvars;
16972 typval_T *rettv;
16974 /* Used for unit testing. Change the code below to your liking. */
16975 #if 0
16976 listitem_T *li;
16977 list_T *l;
16978 char_u *bad, *good;
16980 if (argvars[0].v_type != VAR_LIST)
16981 return;
16982 l = argvars[0].vval.v_list;
16983 if (l == NULL)
16984 return;
16985 li = l->lv_first;
16986 if (li == NULL)
16987 return;
16988 bad = get_tv_string(&li->li_tv);
16989 li = li->li_next;
16990 if (li == NULL)
16991 return;
16992 good = get_tv_string(&li->li_tv);
16993 rettv->vval.v_number = test_edit_score(bad, good);
16994 #endif
16998 * "tolower(string)" function
17000 static void
17001 f_tolower(argvars, rettv)
17002 typval_T *argvars;
17003 typval_T *rettv;
17005 char_u *p;
17007 p = vim_strsave(get_tv_string(&argvars[0]));
17008 rettv->v_type = VAR_STRING;
17009 rettv->vval.v_string = p;
17011 if (p != NULL)
17012 while (*p != NUL)
17014 #ifdef FEAT_MBYTE
17015 int l;
17017 if (enc_utf8)
17019 int c, lc;
17021 c = utf_ptr2char(p);
17022 lc = utf_tolower(c);
17023 l = utf_ptr2len(p);
17024 /* TODO: reallocate string when byte count changes. */
17025 if (utf_char2len(lc) == l)
17026 utf_char2bytes(lc, p);
17027 p += l;
17029 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
17030 p += l; /* skip multi-byte character */
17031 else
17032 #endif
17034 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
17035 ++p;
17041 * "toupper(string)" function
17043 static void
17044 f_toupper(argvars, rettv)
17045 typval_T *argvars;
17046 typval_T *rettv;
17048 rettv->v_type = VAR_STRING;
17049 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
17053 * "tr(string, fromstr, tostr)" function
17055 static void
17056 f_tr(argvars, rettv)
17057 typval_T *argvars;
17058 typval_T *rettv;
17060 char_u *instr;
17061 char_u *fromstr;
17062 char_u *tostr;
17063 char_u *p;
17064 #ifdef FEAT_MBYTE
17065 int inlen;
17066 int fromlen;
17067 int tolen;
17068 int idx;
17069 char_u *cpstr;
17070 int cplen;
17071 int first = TRUE;
17072 #endif
17073 char_u buf[NUMBUFLEN];
17074 char_u buf2[NUMBUFLEN];
17075 garray_T ga;
17077 instr = get_tv_string(&argvars[0]);
17078 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
17079 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
17081 /* Default return value: empty string. */
17082 rettv->v_type = VAR_STRING;
17083 rettv->vval.v_string = NULL;
17084 if (fromstr == NULL || tostr == NULL)
17085 return; /* type error; errmsg already given */
17086 ga_init2(&ga, (int)sizeof(char), 80);
17088 #ifdef FEAT_MBYTE
17089 if (!has_mbyte)
17090 #endif
17091 /* not multi-byte: fromstr and tostr must be the same length */
17092 if (STRLEN(fromstr) != STRLEN(tostr))
17094 #ifdef FEAT_MBYTE
17095 error:
17096 #endif
17097 EMSG2(_(e_invarg2), fromstr);
17098 ga_clear(&ga);
17099 return;
17102 /* fromstr and tostr have to contain the same number of chars */
17103 while (*instr != NUL)
17105 #ifdef FEAT_MBYTE
17106 if (has_mbyte)
17108 inlen = (*mb_ptr2len)(instr);
17109 cpstr = instr;
17110 cplen = inlen;
17111 idx = 0;
17112 for (p = fromstr; *p != NUL; p += fromlen)
17114 fromlen = (*mb_ptr2len)(p);
17115 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
17117 for (p = tostr; *p != NUL; p += tolen)
17119 tolen = (*mb_ptr2len)(p);
17120 if (idx-- == 0)
17122 cplen = tolen;
17123 cpstr = p;
17124 break;
17127 if (*p == NUL) /* tostr is shorter than fromstr */
17128 goto error;
17129 break;
17131 ++idx;
17134 if (first && cpstr == instr)
17136 /* Check that fromstr and tostr have the same number of
17137 * (multi-byte) characters. Done only once when a character
17138 * of instr doesn't appear in fromstr. */
17139 first = FALSE;
17140 for (p = tostr; *p != NUL; p += tolen)
17142 tolen = (*mb_ptr2len)(p);
17143 --idx;
17145 if (idx != 0)
17146 goto error;
17149 ga_grow(&ga, cplen);
17150 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
17151 ga.ga_len += cplen;
17153 instr += inlen;
17155 else
17156 #endif
17158 /* When not using multi-byte chars we can do it faster. */
17159 p = vim_strchr(fromstr, *instr);
17160 if (p != NULL)
17161 ga_append(&ga, tostr[p - fromstr]);
17162 else
17163 ga_append(&ga, *instr);
17164 ++instr;
17168 /* add a terminating NUL */
17169 ga_grow(&ga, 1);
17170 ga_append(&ga, NUL);
17172 rettv->vval.v_string = ga.ga_data;
17175 #ifdef FEAT_FLOAT
17177 * "trunc({float})" function
17179 static void
17180 f_trunc(argvars, rettv)
17181 typval_T *argvars;
17182 typval_T *rettv;
17184 float_T f;
17186 rettv->v_type = VAR_FLOAT;
17187 if (get_float_arg(argvars, &f) == OK)
17188 /* trunc() is not in C90, use floor() or ceil() instead. */
17189 rettv->vval.v_float = f > 0 ? floor(f) : ceil(f);
17190 else
17191 rettv->vval.v_float = 0.0;
17193 #endif
17196 * "type(expr)" function
17198 static void
17199 f_type(argvars, rettv)
17200 typval_T *argvars;
17201 typval_T *rettv;
17203 int n;
17205 switch (argvars[0].v_type)
17207 case VAR_NUMBER: n = 0; break;
17208 case VAR_STRING: n = 1; break;
17209 case VAR_FUNC: n = 2; break;
17210 case VAR_LIST: n = 3; break;
17211 case VAR_DICT: n = 4; break;
17212 #ifdef FEAT_FLOAT
17213 case VAR_FLOAT: n = 5; break;
17214 #endif
17215 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
17217 rettv->vval.v_number = n;
17221 * "values(dict)" function
17223 static void
17224 f_values(argvars, rettv)
17225 typval_T *argvars;
17226 typval_T *rettv;
17228 dict_list(argvars, rettv, 1);
17232 * "virtcol(string)" function
17234 static void
17235 f_virtcol(argvars, rettv)
17236 typval_T *argvars;
17237 typval_T *rettv;
17239 colnr_T vcol = 0;
17240 pos_T *fp;
17241 int fnum = curbuf->b_fnum;
17243 fp = var2fpos(&argvars[0], FALSE, &fnum);
17244 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
17245 && fnum == curbuf->b_fnum)
17247 getvvcol(curwin, fp, NULL, NULL, &vcol);
17248 ++vcol;
17251 rettv->vval.v_number = vcol;
17255 * "visualmode()" function
17257 /*ARGSUSED*/
17258 static void
17259 f_visualmode(argvars, rettv)
17260 typval_T *argvars;
17261 typval_T *rettv;
17263 #ifdef FEAT_VISUAL
17264 char_u str[2];
17266 rettv->v_type = VAR_STRING;
17267 str[0] = curbuf->b_visual_mode_eval;
17268 str[1] = NUL;
17269 rettv->vval.v_string = vim_strsave(str);
17271 /* A non-zero number or non-empty string argument: reset mode. */
17272 if ((argvars[0].v_type == VAR_NUMBER && argvars[0].vval.v_number != 0)
17273 || (argvars[0].v_type == VAR_STRING
17274 && *get_tv_string(&argvars[0]) != NUL))
17275 curbuf->b_visual_mode_eval = NUL;
17276 #else
17277 rettv->vval.v_number = 0; /* return anything, it won't work anyway */
17278 #endif
17282 * "winbufnr(nr)" function
17284 static void
17285 f_winbufnr(argvars, rettv)
17286 typval_T *argvars;
17287 typval_T *rettv;
17289 win_T *wp;
17291 wp = find_win_by_nr(&argvars[0], NULL);
17292 if (wp == NULL)
17293 rettv->vval.v_number = -1;
17294 else
17295 rettv->vval.v_number = wp->w_buffer->b_fnum;
17299 * "wincol()" function
17301 /*ARGSUSED*/
17302 static void
17303 f_wincol(argvars, rettv)
17304 typval_T *argvars;
17305 typval_T *rettv;
17307 validate_cursor();
17308 rettv->vval.v_number = curwin->w_wcol + 1;
17312 * "winheight(nr)" function
17314 static void
17315 f_winheight(argvars, rettv)
17316 typval_T *argvars;
17317 typval_T *rettv;
17319 win_T *wp;
17321 wp = find_win_by_nr(&argvars[0], NULL);
17322 if (wp == NULL)
17323 rettv->vval.v_number = -1;
17324 else
17325 rettv->vval.v_number = wp->w_height;
17329 * "winline()" function
17331 /*ARGSUSED*/
17332 static void
17333 f_winline(argvars, rettv)
17334 typval_T *argvars;
17335 typval_T *rettv;
17337 validate_cursor();
17338 rettv->vval.v_number = curwin->w_wrow + 1;
17342 * "winnr()" function
17344 /* ARGSUSED */
17345 static void
17346 f_winnr(argvars, rettv)
17347 typval_T *argvars;
17348 typval_T *rettv;
17350 int nr = 1;
17352 #ifdef FEAT_WINDOWS
17353 nr = get_winnr(curtab, &argvars[0]);
17354 #endif
17355 rettv->vval.v_number = nr;
17359 * "winrestcmd()" function
17361 /* ARGSUSED */
17362 static void
17363 f_winrestcmd(argvars, rettv)
17364 typval_T *argvars;
17365 typval_T *rettv;
17367 #ifdef FEAT_WINDOWS
17368 win_T *wp;
17369 int winnr = 1;
17370 garray_T ga;
17371 char_u buf[50];
17373 ga_init2(&ga, (int)sizeof(char), 70);
17374 for (wp = firstwin; wp != NULL; wp = wp->w_next)
17376 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
17377 ga_concat(&ga, buf);
17378 # ifdef FEAT_VERTSPLIT
17379 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
17380 ga_concat(&ga, buf);
17381 # endif
17382 ++winnr;
17384 ga_append(&ga, NUL);
17386 rettv->vval.v_string = ga.ga_data;
17387 #else
17388 rettv->vval.v_string = NULL;
17389 #endif
17390 rettv->v_type = VAR_STRING;
17394 * "winrestview()" function
17396 /* ARGSUSED */
17397 static void
17398 f_winrestview(argvars, rettv)
17399 typval_T *argvars;
17400 typval_T *rettv;
17402 dict_T *dict;
17404 if (argvars[0].v_type != VAR_DICT
17405 || (dict = argvars[0].vval.v_dict) == NULL)
17406 EMSG(_(e_invarg));
17407 else
17409 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
17410 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
17411 #ifdef FEAT_VIRTUALEDIT
17412 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
17413 #endif
17414 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
17415 curwin->w_set_curswant = FALSE;
17417 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
17418 #ifdef FEAT_DIFF
17419 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
17420 #endif
17421 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
17422 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
17424 check_cursor();
17425 changed_cline_bef_curs();
17426 invalidate_botline();
17427 redraw_later(VALID);
17429 if (curwin->w_topline == 0)
17430 curwin->w_topline = 1;
17431 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
17432 curwin->w_topline = curbuf->b_ml.ml_line_count;
17433 #ifdef FEAT_DIFF
17434 check_topfill(curwin, TRUE);
17435 #endif
17440 * "winsaveview()" function
17442 /* ARGSUSED */
17443 static void
17444 f_winsaveview(argvars, rettv)
17445 typval_T *argvars;
17446 typval_T *rettv;
17448 dict_T *dict;
17450 dict = dict_alloc();
17451 if (dict == NULL)
17452 return;
17453 rettv->v_type = VAR_DICT;
17454 rettv->vval.v_dict = dict;
17455 ++dict->dv_refcount;
17457 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
17458 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
17459 #ifdef FEAT_VIRTUALEDIT
17460 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
17461 #endif
17462 update_curswant();
17463 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
17465 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
17466 #ifdef FEAT_DIFF
17467 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
17468 #endif
17469 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
17470 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
17474 * "winwidth(nr)" function
17476 static void
17477 f_winwidth(argvars, rettv)
17478 typval_T *argvars;
17479 typval_T *rettv;
17481 win_T *wp;
17483 wp = find_win_by_nr(&argvars[0], NULL);
17484 if (wp == NULL)
17485 rettv->vval.v_number = -1;
17486 else
17487 #ifdef FEAT_VERTSPLIT
17488 rettv->vval.v_number = wp->w_width;
17489 #else
17490 rettv->vval.v_number = Columns;
17491 #endif
17495 * "writefile()" function
17497 static void
17498 f_writefile(argvars, rettv)
17499 typval_T *argvars;
17500 typval_T *rettv;
17502 int binary = FALSE;
17503 char_u *fname;
17504 FILE *fd;
17505 listitem_T *li;
17506 char_u *s;
17507 int ret = 0;
17508 int c;
17510 if (check_restricted() || check_secure())
17511 return;
17513 if (argvars[0].v_type != VAR_LIST)
17515 EMSG2(_(e_listarg), "writefile()");
17516 return;
17518 if (argvars[0].vval.v_list == NULL)
17519 return;
17521 if (argvars[2].v_type != VAR_UNKNOWN
17522 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
17523 binary = TRUE;
17525 /* Always open the file in binary mode, library functions have a mind of
17526 * their own about CR-LF conversion. */
17527 fname = get_tv_string(&argvars[1]);
17528 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
17530 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
17531 ret = -1;
17533 else
17535 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
17536 li = li->li_next)
17538 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
17540 if (*s == '\n')
17541 c = putc(NUL, fd);
17542 else
17543 c = putc(*s, fd);
17544 if (c == EOF)
17546 ret = -1;
17547 break;
17550 if (!binary || li->li_next != NULL)
17551 if (putc('\n', fd) == EOF)
17553 ret = -1;
17554 break;
17556 if (ret < 0)
17558 EMSG(_(e_write));
17559 break;
17562 fclose(fd);
17565 rettv->vval.v_number = ret;
17569 * Translate a String variable into a position.
17570 * Returns NULL when there is an error.
17572 static pos_T *
17573 var2fpos(varp, dollar_lnum, fnum)
17574 typval_T *varp;
17575 int dollar_lnum; /* TRUE when $ is last line */
17576 int *fnum; /* set to fnum for '0, 'A, etc. */
17578 char_u *name;
17579 static pos_T pos;
17580 pos_T *pp;
17582 /* Argument can be [lnum, col, coladd]. */
17583 if (varp->v_type == VAR_LIST)
17585 list_T *l;
17586 int len;
17587 int error = FALSE;
17588 listitem_T *li;
17590 l = varp->vval.v_list;
17591 if (l == NULL)
17592 return NULL;
17594 /* Get the line number */
17595 pos.lnum = list_find_nr(l, 0L, &error);
17596 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
17597 return NULL; /* invalid line number */
17599 /* Get the column number */
17600 pos.col = list_find_nr(l, 1L, &error);
17601 if (error)
17602 return NULL;
17603 len = (long)STRLEN(ml_get(pos.lnum));
17605 /* We accept "$" for the column number: last column. */
17606 li = list_find(l, 1L);
17607 if (li != NULL && li->li_tv.v_type == VAR_STRING
17608 && li->li_tv.vval.v_string != NULL
17609 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
17610 pos.col = len + 1;
17612 /* Accept a position up to the NUL after the line. */
17613 if (pos.col == 0 || (int)pos.col > len + 1)
17614 return NULL; /* invalid column number */
17615 --pos.col;
17617 #ifdef FEAT_VIRTUALEDIT
17618 /* Get the virtual offset. Defaults to zero. */
17619 pos.coladd = list_find_nr(l, 2L, &error);
17620 if (error)
17621 pos.coladd = 0;
17622 #endif
17624 return &pos;
17627 name = get_tv_string_chk(varp);
17628 if (name == NULL)
17629 return NULL;
17630 if (name[0] == '.') /* cursor */
17631 return &curwin->w_cursor;
17632 #ifdef FEAT_VISUAL
17633 if (name[0] == 'v' && name[1] == NUL) /* Visual start */
17635 if (VIsual_active)
17636 return &VIsual;
17637 return &curwin->w_cursor;
17639 #endif
17640 if (name[0] == '\'') /* mark */
17642 pp = getmark_fnum(name[1], FALSE, fnum);
17643 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
17644 return NULL;
17645 return pp;
17648 #ifdef FEAT_VIRTUALEDIT
17649 pos.coladd = 0;
17650 #endif
17652 if (name[0] == 'w' && dollar_lnum)
17654 pos.col = 0;
17655 if (name[1] == '0') /* "w0": first visible line */
17657 update_topline();
17658 pos.lnum = curwin->w_topline;
17659 return &pos;
17661 else if (name[1] == '$') /* "w$": last visible line */
17663 validate_botline();
17664 pos.lnum = curwin->w_botline - 1;
17665 return &pos;
17668 else if (name[0] == '$') /* last column or line */
17670 if (dollar_lnum)
17672 pos.lnum = curbuf->b_ml.ml_line_count;
17673 pos.col = 0;
17675 else
17677 pos.lnum = curwin->w_cursor.lnum;
17678 pos.col = (colnr_T)STRLEN(ml_get_curline());
17680 return &pos;
17682 return NULL;
17686 * Convert list in "arg" into a position and optional file number.
17687 * When "fnump" is NULL there is no file number, only 3 items.
17688 * Note that the column is passed on as-is, the caller may want to decrement
17689 * it to use 1 for the first column.
17690 * Return FAIL when conversion is not possible, doesn't check the position for
17691 * validity.
17693 static int
17694 list2fpos(arg, posp, fnump)
17695 typval_T *arg;
17696 pos_T *posp;
17697 int *fnump;
17699 list_T *l = arg->vval.v_list;
17700 long i = 0;
17701 long n;
17703 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
17704 * when "fnump" isn't NULL and "coladd" is optional. */
17705 if (arg->v_type != VAR_LIST
17706 || l == NULL
17707 || l->lv_len < (fnump == NULL ? 2 : 3)
17708 || l->lv_len > (fnump == NULL ? 3 : 4))
17709 return FAIL;
17711 if (fnump != NULL)
17713 n = list_find_nr(l, i++, NULL); /* fnum */
17714 if (n < 0)
17715 return FAIL;
17716 if (n == 0)
17717 n = curbuf->b_fnum; /* current buffer */
17718 *fnump = n;
17721 n = list_find_nr(l, i++, NULL); /* lnum */
17722 if (n < 0)
17723 return FAIL;
17724 posp->lnum = n;
17726 n = list_find_nr(l, i++, NULL); /* col */
17727 if (n < 0)
17728 return FAIL;
17729 posp->col = n;
17731 #ifdef FEAT_VIRTUALEDIT
17732 n = list_find_nr(l, i, NULL);
17733 if (n < 0)
17734 posp->coladd = 0;
17735 else
17736 posp->coladd = n;
17737 #endif
17739 return OK;
17743 * Get the length of an environment variable name.
17744 * Advance "arg" to the first character after the name.
17745 * Return 0 for error.
17747 static int
17748 get_env_len(arg)
17749 char_u **arg;
17751 char_u *p;
17752 int len;
17754 for (p = *arg; vim_isIDc(*p); ++p)
17756 if (p == *arg) /* no name found */
17757 return 0;
17759 len = (int)(p - *arg);
17760 *arg = p;
17761 return len;
17765 * Get the length of the name of a function or internal variable.
17766 * "arg" is advanced to the first non-white character after the name.
17767 * Return 0 if something is wrong.
17769 static int
17770 get_id_len(arg)
17771 char_u **arg;
17773 char_u *p;
17774 int len;
17776 /* Find the end of the name. */
17777 for (p = *arg; eval_isnamec(*p); ++p)
17779 if (p == *arg) /* no name found */
17780 return 0;
17782 len = (int)(p - *arg);
17783 *arg = skipwhite(p);
17785 return len;
17789 * Get the length of the name of a variable or function.
17790 * Only the name is recognized, does not handle ".key" or "[idx]".
17791 * "arg" is advanced to the first non-white character after the name.
17792 * Return -1 if curly braces expansion failed.
17793 * Return 0 if something else is wrong.
17794 * If the name contains 'magic' {}'s, expand them and return the
17795 * expanded name in an allocated string via 'alias' - caller must free.
17797 static int
17798 get_name_len(arg, alias, evaluate, verbose)
17799 char_u **arg;
17800 char_u **alias;
17801 int evaluate;
17802 int verbose;
17804 int len;
17805 char_u *p;
17806 char_u *expr_start;
17807 char_u *expr_end;
17809 *alias = NULL; /* default to no alias */
17811 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
17812 && (*arg)[2] == (int)KE_SNR)
17814 /* hard coded <SNR>, already translated */
17815 *arg += 3;
17816 return get_id_len(arg) + 3;
17818 len = eval_fname_script(*arg);
17819 if (len > 0)
17821 /* literal "<SID>", "s:" or "<SNR>" */
17822 *arg += len;
17826 * Find the end of the name; check for {} construction.
17828 p = find_name_end(*arg, &expr_start, &expr_end,
17829 len > 0 ? 0 : FNE_CHECK_START);
17830 if (expr_start != NULL)
17832 char_u *temp_string;
17834 if (!evaluate)
17836 len += (int)(p - *arg);
17837 *arg = skipwhite(p);
17838 return len;
17842 * Include any <SID> etc in the expanded string:
17843 * Thus the -len here.
17845 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
17846 if (temp_string == NULL)
17847 return -1;
17848 *alias = temp_string;
17849 *arg = skipwhite(p);
17850 return (int)STRLEN(temp_string);
17853 len += get_id_len(arg);
17854 if (len == 0 && verbose)
17855 EMSG2(_(e_invexpr2), *arg);
17857 return len;
17861 * Find the end of a variable or function name, taking care of magic braces.
17862 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
17863 * start and end of the first magic braces item.
17864 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
17865 * Return a pointer to just after the name. Equal to "arg" if there is no
17866 * valid name.
17868 static char_u *
17869 find_name_end(arg, expr_start, expr_end, flags)
17870 char_u *arg;
17871 char_u **expr_start;
17872 char_u **expr_end;
17873 int flags;
17875 int mb_nest = 0;
17876 int br_nest = 0;
17877 char_u *p;
17879 if (expr_start != NULL)
17881 *expr_start = NULL;
17882 *expr_end = NULL;
17885 /* Quick check for valid starting character. */
17886 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
17887 return arg;
17889 for (p = arg; *p != NUL
17890 && (eval_isnamec(*p)
17891 || *p == '{'
17892 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
17893 || mb_nest != 0
17894 || br_nest != 0); mb_ptr_adv(p))
17896 if (*p == '\'')
17898 /* skip over 'string' to avoid counting [ and ] inside it. */
17899 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
17901 if (*p == NUL)
17902 break;
17904 else if (*p == '"')
17906 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
17907 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
17908 if (*p == '\\' && p[1] != NUL)
17909 ++p;
17910 if (*p == NUL)
17911 break;
17914 if (mb_nest == 0)
17916 if (*p == '[')
17917 ++br_nest;
17918 else if (*p == ']')
17919 --br_nest;
17922 if (br_nest == 0)
17924 if (*p == '{')
17926 mb_nest++;
17927 if (expr_start != NULL && *expr_start == NULL)
17928 *expr_start = p;
17930 else if (*p == '}')
17932 mb_nest--;
17933 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
17934 *expr_end = p;
17939 return p;
17943 * Expands out the 'magic' {}'s in a variable/function name.
17944 * Note that this can call itself recursively, to deal with
17945 * constructs like foo{bar}{baz}{bam}
17946 * The four pointer arguments point to "foo{expre}ss{ion}bar"
17947 * "in_start" ^
17948 * "expr_start" ^
17949 * "expr_end" ^
17950 * "in_end" ^
17952 * Returns a new allocated string, which the caller must free.
17953 * Returns NULL for failure.
17955 static char_u *
17956 make_expanded_name(in_start, expr_start, expr_end, in_end)
17957 char_u *in_start;
17958 char_u *expr_start;
17959 char_u *expr_end;
17960 char_u *in_end;
17962 char_u c1;
17963 char_u *retval = NULL;
17964 char_u *temp_result;
17965 char_u *nextcmd = NULL;
17967 if (expr_end == NULL || in_end == NULL)
17968 return NULL;
17969 *expr_start = NUL;
17970 *expr_end = NUL;
17971 c1 = *in_end;
17972 *in_end = NUL;
17974 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
17975 if (temp_result != NULL && nextcmd == NULL)
17977 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
17978 + (in_end - expr_end) + 1));
17979 if (retval != NULL)
17981 STRCPY(retval, in_start);
17982 STRCAT(retval, temp_result);
17983 STRCAT(retval, expr_end + 1);
17986 vim_free(temp_result);
17988 *in_end = c1; /* put char back for error messages */
17989 *expr_start = '{';
17990 *expr_end = '}';
17992 if (retval != NULL)
17994 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
17995 if (expr_start != NULL)
17997 /* Further expansion! */
17998 temp_result = make_expanded_name(retval, expr_start,
17999 expr_end, temp_result);
18000 vim_free(retval);
18001 retval = temp_result;
18005 return retval;
18009 * Return TRUE if character "c" can be used in a variable or function name.
18010 * Does not include '{' or '}' for magic braces.
18012 static int
18013 eval_isnamec(c)
18014 int c;
18016 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
18020 * Return TRUE if character "c" can be used as the first character in a
18021 * variable or function name (excluding '{' and '}').
18023 static int
18024 eval_isnamec1(c)
18025 int c;
18027 return (ASCII_ISALPHA(c) || c == '_');
18031 * Set number v: variable to "val".
18033 void
18034 set_vim_var_nr(idx, val)
18035 int idx;
18036 long val;
18038 vimvars[idx].vv_nr = val;
18042 * Get number v: variable value.
18044 long
18045 get_vim_var_nr(idx)
18046 int idx;
18048 return vimvars[idx].vv_nr;
18051 #if defined(FEAT_AUTOCMD) || defined(PROTO)
18053 * Get string v: variable value. Uses a static buffer, can only be used once.
18055 char_u *
18056 get_vim_var_str(idx)
18057 int idx;
18059 return get_tv_string(&vimvars[idx].vv_tv);
18061 #endif
18064 * Set v:count, v:count1 and v:prevcount.
18066 void
18067 set_vcount(count, count1)
18068 long count;
18069 long count1;
18071 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
18072 vimvars[VV_COUNT].vv_nr = count;
18073 vimvars[VV_COUNT1].vv_nr = count1;
18077 * Set string v: variable to a copy of "val".
18079 void
18080 set_vim_var_string(idx, val, len)
18081 int idx;
18082 char_u *val;
18083 int len; /* length of "val" to use or -1 (whole string) */
18085 /* Need to do this (at least) once, since we can't initialize a union.
18086 * Will always be invoked when "v:progname" is set. */
18087 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
18089 vim_free(vimvars[idx].vv_str);
18090 if (val == NULL)
18091 vimvars[idx].vv_str = NULL;
18092 else if (len == -1)
18093 vimvars[idx].vv_str = vim_strsave(val);
18094 else
18095 vimvars[idx].vv_str = vim_strnsave(val, len);
18099 * Set v:register if needed.
18101 void
18102 set_reg_var(c)
18103 int c;
18105 char_u regname;
18107 if (c == 0 || c == ' ')
18108 regname = '"';
18109 else
18110 regname = c;
18111 /* Avoid free/alloc when the value is already right. */
18112 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
18113 set_vim_var_string(VV_REG, &regname, 1);
18117 * Get or set v:exception. If "oldval" == NULL, return the current value.
18118 * Otherwise, restore the value to "oldval" and return NULL.
18119 * Must always be called in pairs to save and restore v:exception! Does not
18120 * take care of memory allocations.
18122 char_u *
18123 v_exception(oldval)
18124 char_u *oldval;
18126 if (oldval == NULL)
18127 return vimvars[VV_EXCEPTION].vv_str;
18129 vimvars[VV_EXCEPTION].vv_str = oldval;
18130 return NULL;
18134 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
18135 * Otherwise, restore the value to "oldval" and return NULL.
18136 * Must always be called in pairs to save and restore v:throwpoint! Does not
18137 * take care of memory allocations.
18139 char_u *
18140 v_throwpoint(oldval)
18141 char_u *oldval;
18143 if (oldval == NULL)
18144 return vimvars[VV_THROWPOINT].vv_str;
18146 vimvars[VV_THROWPOINT].vv_str = oldval;
18147 return NULL;
18150 #if defined(FEAT_AUTOCMD) || defined(PROTO)
18152 * Set v:cmdarg.
18153 * If "eap" != NULL, use "eap" to generate the value and return the old value.
18154 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
18155 * Must always be called in pairs!
18157 char_u *
18158 set_cmdarg(eap, oldarg)
18159 exarg_T *eap;
18160 char_u *oldarg;
18162 char_u *oldval;
18163 char_u *newval;
18164 unsigned len;
18166 oldval = vimvars[VV_CMDARG].vv_str;
18167 if (eap == NULL)
18169 vim_free(oldval);
18170 vimvars[VV_CMDARG].vv_str = oldarg;
18171 return NULL;
18174 if (eap->force_bin == FORCE_BIN)
18175 len = 6;
18176 else if (eap->force_bin == FORCE_NOBIN)
18177 len = 8;
18178 else
18179 len = 0;
18181 if (eap->read_edit)
18182 len += 7;
18184 if (eap->force_ff != 0)
18185 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
18186 # ifdef FEAT_MBYTE
18187 if (eap->force_enc != 0)
18188 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
18189 if (eap->bad_char != 0)
18190 len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
18191 # endif
18193 newval = alloc(len + 1);
18194 if (newval == NULL)
18195 return NULL;
18197 if (eap->force_bin == FORCE_BIN)
18198 sprintf((char *)newval, " ++bin");
18199 else if (eap->force_bin == FORCE_NOBIN)
18200 sprintf((char *)newval, " ++nobin");
18201 else
18202 *newval = NUL;
18204 if (eap->read_edit)
18205 STRCAT(newval, " ++edit");
18207 if (eap->force_ff != 0)
18208 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
18209 eap->cmd + eap->force_ff);
18210 # ifdef FEAT_MBYTE
18211 if (eap->force_enc != 0)
18212 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
18213 eap->cmd + eap->force_enc);
18214 if (eap->bad_char != 0)
18215 sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
18216 eap->cmd + eap->bad_char);
18217 # endif
18218 vimvars[VV_CMDARG].vv_str = newval;
18219 return oldval;
18221 #endif
18224 * Get the value of internal variable "name".
18225 * Return OK or FAIL.
18227 static int
18228 get_var_tv(name, len, rettv, verbose)
18229 char_u *name;
18230 int len; /* length of "name" */
18231 typval_T *rettv; /* NULL when only checking existence */
18232 int verbose; /* may give error message */
18234 int ret = OK;
18235 typval_T *tv = NULL;
18236 typval_T atv;
18237 dictitem_T *v;
18238 int cc;
18240 /* truncate the name, so that we can use strcmp() */
18241 cc = name[len];
18242 name[len] = NUL;
18245 * Check for "b:changedtick".
18247 if (STRCMP(name, "b:changedtick") == 0)
18249 atv.v_type = VAR_NUMBER;
18250 atv.vval.v_number = curbuf->b_changedtick;
18251 tv = &atv;
18255 * Check for user-defined variables.
18257 else
18259 v = find_var(name, NULL);
18260 if (v != NULL)
18261 tv = &v->di_tv;
18264 if (tv == NULL)
18266 if (rettv != NULL && verbose)
18267 EMSG2(_(e_undefvar), name);
18268 ret = FAIL;
18270 else if (rettv != NULL)
18271 copy_tv(tv, rettv);
18273 name[len] = cc;
18275 return ret;
18279 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
18280 * Also handle function call with Funcref variable: func(expr)
18281 * Can all be combined: dict.func(expr)[idx]['func'](expr)
18283 static int
18284 handle_subscript(arg, rettv, evaluate, verbose)
18285 char_u **arg;
18286 typval_T *rettv;
18287 int evaluate; /* do more than finding the end */
18288 int verbose; /* give error messages */
18290 int ret = OK;
18291 dict_T *selfdict = NULL;
18292 char_u *s;
18293 int len;
18294 typval_T functv;
18296 while (ret == OK
18297 && (**arg == '['
18298 || (**arg == '.' && rettv->v_type == VAR_DICT)
18299 || (**arg == '(' && rettv->v_type == VAR_FUNC))
18300 && !vim_iswhite(*(*arg - 1)))
18302 if (**arg == '(')
18304 /* need to copy the funcref so that we can clear rettv */
18305 functv = *rettv;
18306 rettv->v_type = VAR_UNKNOWN;
18308 /* Invoke the function. Recursive! */
18309 s = functv.vval.v_string;
18310 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
18311 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
18312 &len, evaluate, selfdict);
18314 /* Clear the funcref afterwards, so that deleting it while
18315 * evaluating the arguments is possible (see test55). */
18316 clear_tv(&functv);
18318 /* Stop the expression evaluation when immediately aborting on
18319 * error, or when an interrupt occurred or an exception was thrown
18320 * but not caught. */
18321 if (aborting())
18323 if (ret == OK)
18324 clear_tv(rettv);
18325 ret = FAIL;
18327 dict_unref(selfdict);
18328 selfdict = NULL;
18330 else /* **arg == '[' || **arg == '.' */
18332 dict_unref(selfdict);
18333 if (rettv->v_type == VAR_DICT)
18335 selfdict = rettv->vval.v_dict;
18336 if (selfdict != NULL)
18337 ++selfdict->dv_refcount;
18339 else
18340 selfdict = NULL;
18341 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
18343 clear_tv(rettv);
18344 ret = FAIL;
18348 dict_unref(selfdict);
18349 return ret;
18353 * Allocate memory for a variable type-value, and make it empty (0 or NULL
18354 * value).
18356 static typval_T *
18357 alloc_tv()
18359 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
18363 * Allocate memory for a variable type-value, and assign a string to it.
18364 * The string "s" must have been allocated, it is consumed.
18365 * Return NULL for out of memory, the variable otherwise.
18367 static typval_T *
18368 alloc_string_tv(s)
18369 char_u *s;
18371 typval_T *rettv;
18373 rettv = alloc_tv();
18374 if (rettv != NULL)
18376 rettv->v_type = VAR_STRING;
18377 rettv->vval.v_string = s;
18379 else
18380 vim_free(s);
18381 return rettv;
18385 * Free the memory for a variable type-value.
18387 void
18388 free_tv(varp)
18389 typval_T *varp;
18391 if (varp != NULL)
18393 switch (varp->v_type)
18395 case VAR_FUNC:
18396 func_unref(varp->vval.v_string);
18397 /*FALLTHROUGH*/
18398 case VAR_STRING:
18399 vim_free(varp->vval.v_string);
18400 break;
18401 case VAR_LIST:
18402 list_unref(varp->vval.v_list);
18403 break;
18404 case VAR_DICT:
18405 dict_unref(varp->vval.v_dict);
18406 break;
18407 case VAR_NUMBER:
18408 #ifdef FEAT_FLOAT
18409 case VAR_FLOAT:
18410 #endif
18411 case VAR_UNKNOWN:
18412 break;
18413 default:
18414 EMSG2(_(e_intern2), "free_tv()");
18415 break;
18417 vim_free(varp);
18422 * Free the memory for a variable value and set the value to NULL or 0.
18424 void
18425 clear_tv(varp)
18426 typval_T *varp;
18428 if (varp != NULL)
18430 switch (varp->v_type)
18432 case VAR_FUNC:
18433 func_unref(varp->vval.v_string);
18434 /*FALLTHROUGH*/
18435 case VAR_STRING:
18436 vim_free(varp->vval.v_string);
18437 varp->vval.v_string = NULL;
18438 break;
18439 case VAR_LIST:
18440 list_unref(varp->vval.v_list);
18441 varp->vval.v_list = NULL;
18442 break;
18443 case VAR_DICT:
18444 dict_unref(varp->vval.v_dict);
18445 varp->vval.v_dict = NULL;
18446 break;
18447 case VAR_NUMBER:
18448 varp->vval.v_number = 0;
18449 break;
18450 #ifdef FEAT_FLOAT
18451 case VAR_FLOAT:
18452 varp->vval.v_float = 0.0;
18453 break;
18454 #endif
18455 case VAR_UNKNOWN:
18456 break;
18457 default:
18458 EMSG2(_(e_intern2), "clear_tv()");
18460 varp->v_lock = 0;
18465 * Set the value of a variable to NULL without freeing items.
18467 static void
18468 init_tv(varp)
18469 typval_T *varp;
18471 if (varp != NULL)
18472 vim_memset(varp, 0, sizeof(typval_T));
18476 * Get the number value of a variable.
18477 * If it is a String variable, uses vim_str2nr().
18478 * For incompatible types, return 0.
18479 * get_tv_number_chk() is similar to get_tv_number(), but informs the
18480 * caller of incompatible types: it sets *denote to TRUE if "denote"
18481 * is not NULL or returns -1 otherwise.
18483 static long
18484 get_tv_number(varp)
18485 typval_T *varp;
18487 int error = FALSE;
18489 return get_tv_number_chk(varp, &error); /* return 0L on error */
18492 long
18493 get_tv_number_chk(varp, denote)
18494 typval_T *varp;
18495 int *denote;
18497 long n = 0L;
18499 switch (varp->v_type)
18501 case VAR_NUMBER:
18502 return (long)(varp->vval.v_number);
18503 #ifdef FEAT_FLOAT
18504 case VAR_FLOAT:
18505 EMSG(_("E805: Using a Float as a Number"));
18506 break;
18507 #endif
18508 case VAR_FUNC:
18509 EMSG(_("E703: Using a Funcref as a Number"));
18510 break;
18511 case VAR_STRING:
18512 if (varp->vval.v_string != NULL)
18513 vim_str2nr(varp->vval.v_string, NULL, NULL,
18514 TRUE, TRUE, &n, NULL);
18515 return n;
18516 case VAR_LIST:
18517 EMSG(_("E745: Using a List as a Number"));
18518 break;
18519 case VAR_DICT:
18520 EMSG(_("E728: Using a Dictionary as a Number"));
18521 break;
18522 default:
18523 EMSG2(_(e_intern2), "get_tv_number()");
18524 break;
18526 if (denote == NULL) /* useful for values that must be unsigned */
18527 n = -1;
18528 else
18529 *denote = TRUE;
18530 return n;
18534 * Get the lnum from the first argument.
18535 * Also accepts ".", "$", etc., but that only works for the current buffer.
18536 * Returns -1 on error.
18538 static linenr_T
18539 get_tv_lnum(argvars)
18540 typval_T *argvars;
18542 typval_T rettv;
18543 linenr_T lnum;
18545 lnum = get_tv_number_chk(&argvars[0], NULL);
18546 if (lnum == 0) /* no valid number, try using line() */
18548 rettv.v_type = VAR_NUMBER;
18549 f_line(argvars, &rettv);
18550 lnum = rettv.vval.v_number;
18551 clear_tv(&rettv);
18553 return lnum;
18557 * Get the lnum from the first argument.
18558 * Also accepts "$", then "buf" is used.
18559 * Returns 0 on error.
18561 static linenr_T
18562 get_tv_lnum_buf(argvars, buf)
18563 typval_T *argvars;
18564 buf_T *buf;
18566 if (argvars[0].v_type == VAR_STRING
18567 && argvars[0].vval.v_string != NULL
18568 && argvars[0].vval.v_string[0] == '$'
18569 && buf != NULL)
18570 return buf->b_ml.ml_line_count;
18571 return get_tv_number_chk(&argvars[0], NULL);
18575 * Get the string value of a variable.
18576 * If it is a Number variable, the number is converted into a string.
18577 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
18578 * get_tv_string_buf() uses a given buffer.
18579 * If the String variable has never been set, return an empty string.
18580 * Never returns NULL;
18581 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
18582 * NULL on error.
18584 static char_u *
18585 get_tv_string(varp)
18586 typval_T *varp;
18588 static char_u mybuf[NUMBUFLEN];
18590 return get_tv_string_buf(varp, mybuf);
18593 static char_u *
18594 get_tv_string_buf(varp, buf)
18595 typval_T *varp;
18596 char_u *buf;
18598 char_u *res = get_tv_string_buf_chk(varp, buf);
18600 return res != NULL ? res : (char_u *)"";
18603 char_u *
18604 get_tv_string_chk(varp)
18605 typval_T *varp;
18607 static char_u mybuf[NUMBUFLEN];
18609 return get_tv_string_buf_chk(varp, mybuf);
18612 static char_u *
18613 get_tv_string_buf_chk(varp, buf)
18614 typval_T *varp;
18615 char_u *buf;
18617 switch (varp->v_type)
18619 case VAR_NUMBER:
18620 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
18621 return buf;
18622 case VAR_FUNC:
18623 EMSG(_("E729: using Funcref as a String"));
18624 break;
18625 case VAR_LIST:
18626 EMSG(_("E730: using List as a String"));
18627 break;
18628 case VAR_DICT:
18629 EMSG(_("E731: using Dictionary as a String"));
18630 break;
18631 #ifdef FEAT_FLOAT
18632 case VAR_FLOAT:
18633 EMSG(_("E806: using Float as a String"));
18634 break;
18635 #endif
18636 case VAR_STRING:
18637 if (varp->vval.v_string != NULL)
18638 return varp->vval.v_string;
18639 return (char_u *)"";
18640 default:
18641 EMSG2(_(e_intern2), "get_tv_string_buf()");
18642 break;
18644 return NULL;
18648 * Find variable "name" in the list of variables.
18649 * Return a pointer to it if found, NULL if not found.
18650 * Careful: "a:0" variables don't have a name.
18651 * When "htp" is not NULL we are writing to the variable, set "htp" to the
18652 * hashtab_T used.
18654 static dictitem_T *
18655 find_var(name, htp)
18656 char_u *name;
18657 hashtab_T **htp;
18659 char_u *varname;
18660 hashtab_T *ht;
18662 ht = find_var_ht(name, &varname);
18663 if (htp != NULL)
18664 *htp = ht;
18665 if (ht == NULL)
18666 return NULL;
18667 return find_var_in_ht(ht, varname, htp != NULL);
18671 * Find variable "varname" in hashtab "ht".
18672 * Returns NULL if not found.
18674 static dictitem_T *
18675 find_var_in_ht(ht, varname, writing)
18676 hashtab_T *ht;
18677 char_u *varname;
18678 int writing;
18680 hashitem_T *hi;
18682 if (*varname == NUL)
18684 /* Must be something like "s:", otherwise "ht" would be NULL. */
18685 switch (varname[-2])
18687 case 's': return &SCRIPT_SV(current_SID).sv_var;
18688 case 'g': return &globvars_var;
18689 case 'v': return &vimvars_var;
18690 case 'b': return &curbuf->b_bufvar;
18691 case 'w': return &curwin->w_winvar;
18692 #ifdef FEAT_WINDOWS
18693 case 't': return &curtab->tp_winvar;
18694 #endif
18695 case 'l': return current_funccal == NULL
18696 ? NULL : &current_funccal->l_vars_var;
18697 case 'a': return current_funccal == NULL
18698 ? NULL : &current_funccal->l_avars_var;
18700 return NULL;
18703 hi = hash_find(ht, varname);
18704 if (HASHITEM_EMPTY(hi))
18706 /* For global variables we may try auto-loading the script. If it
18707 * worked find the variable again. Don't auto-load a script if it was
18708 * loaded already, otherwise it would be loaded every time when
18709 * checking if a function name is a Funcref variable. */
18710 if (ht == &globvarht && !writing
18711 && script_autoload(varname, FALSE) && !aborting())
18712 hi = hash_find(ht, varname);
18713 if (HASHITEM_EMPTY(hi))
18714 return NULL;
18716 return HI2DI(hi);
18720 * Find the hashtab used for a variable name.
18721 * Set "varname" to the start of name without ':'.
18723 static hashtab_T *
18724 find_var_ht(name, varname)
18725 char_u *name;
18726 char_u **varname;
18728 hashitem_T *hi;
18730 if (name[1] != ':')
18732 /* The name must not start with a colon or #. */
18733 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
18734 return NULL;
18735 *varname = name;
18737 /* "version" is "v:version" in all scopes */
18738 hi = hash_find(&compat_hashtab, name);
18739 if (!HASHITEM_EMPTY(hi))
18740 return &compat_hashtab;
18742 if (current_funccal == NULL)
18743 return &globvarht; /* global variable */
18744 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
18746 *varname = name + 2;
18747 if (*name == 'g') /* global variable */
18748 return &globvarht;
18749 /* There must be no ':' or '#' in the rest of the name, unless g: is used
18751 if (vim_strchr(name + 2, ':') != NULL
18752 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
18753 return NULL;
18754 if (*name == 'b') /* buffer variable */
18755 return &curbuf->b_vars.dv_hashtab;
18756 if (*name == 'w') /* window variable */
18757 return &curwin->w_vars.dv_hashtab;
18758 #ifdef FEAT_WINDOWS
18759 if (*name == 't') /* tab page variable */
18760 return &curtab->tp_vars.dv_hashtab;
18761 #endif
18762 if (*name == 'v') /* v: variable */
18763 return &vimvarht;
18764 if (*name == 'a' && current_funccal != NULL) /* function argument */
18765 return &current_funccal->l_avars.dv_hashtab;
18766 if (*name == 'l' && current_funccal != NULL) /* local function variable */
18767 return &current_funccal->l_vars.dv_hashtab;
18768 if (*name == 's' /* script variable */
18769 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
18770 return &SCRIPT_VARS(current_SID);
18771 return NULL;
18775 * Get the string value of a (global/local) variable.
18776 * Returns NULL when it doesn't exist.
18778 char_u *
18779 get_var_value(name)
18780 char_u *name;
18782 dictitem_T *v;
18784 v = find_var(name, NULL);
18785 if (v == NULL)
18786 return NULL;
18787 return get_tv_string(&v->di_tv);
18791 * Allocate a new hashtab for a sourced script. It will be used while
18792 * sourcing this script and when executing functions defined in the script.
18794 void
18795 new_script_vars(id)
18796 scid_T id;
18798 int i;
18799 hashtab_T *ht;
18800 scriptvar_T *sv;
18802 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
18804 /* Re-allocating ga_data means that an ht_array pointing to
18805 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
18806 * at its init value. Also reset "v_dict", it's always the same. */
18807 for (i = 1; i <= ga_scripts.ga_len; ++i)
18809 ht = &SCRIPT_VARS(i);
18810 if (ht->ht_mask == HT_INIT_SIZE - 1)
18811 ht->ht_array = ht->ht_smallarray;
18812 sv = &SCRIPT_SV(i);
18813 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
18816 while (ga_scripts.ga_len < id)
18818 sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
18819 init_var_dict(&sv->sv_dict, &sv->sv_var);
18820 ++ga_scripts.ga_len;
18826 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
18827 * point to it.
18829 void
18830 init_var_dict(dict, dict_var)
18831 dict_T *dict;
18832 dictitem_T *dict_var;
18834 hash_init(&dict->dv_hashtab);
18835 dict->dv_refcount = 99999;
18836 dict_var->di_tv.vval.v_dict = dict;
18837 dict_var->di_tv.v_type = VAR_DICT;
18838 dict_var->di_tv.v_lock = VAR_FIXED;
18839 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
18840 dict_var->di_key[0] = NUL;
18844 * Clean up a list of internal variables.
18845 * Frees all allocated variables and the value they contain.
18846 * Clears hashtab "ht", does not free it.
18848 void
18849 vars_clear(ht)
18850 hashtab_T *ht;
18852 vars_clear_ext(ht, TRUE);
18856 * Like vars_clear(), but only free the value if "free_val" is TRUE.
18858 static void
18859 vars_clear_ext(ht, free_val)
18860 hashtab_T *ht;
18861 int free_val;
18863 int todo;
18864 hashitem_T *hi;
18865 dictitem_T *v;
18867 hash_lock(ht);
18868 todo = (int)ht->ht_used;
18869 for (hi = ht->ht_array; todo > 0; ++hi)
18871 if (!HASHITEM_EMPTY(hi))
18873 --todo;
18875 /* Free the variable. Don't remove it from the hashtab,
18876 * ht_array might change then. hash_clear() takes care of it
18877 * later. */
18878 v = HI2DI(hi);
18879 if (free_val)
18880 clear_tv(&v->di_tv);
18881 if ((v->di_flags & DI_FLAGS_FIX) == 0)
18882 vim_free(v);
18885 hash_clear(ht);
18886 ht->ht_used = 0;
18890 * Delete a variable from hashtab "ht" at item "hi".
18891 * Clear the variable value and free the dictitem.
18893 static void
18894 delete_var(ht, hi)
18895 hashtab_T *ht;
18896 hashitem_T *hi;
18898 dictitem_T *di = HI2DI(hi);
18900 hash_remove(ht, hi);
18901 clear_tv(&di->di_tv);
18902 vim_free(di);
18906 * List the value of one internal variable.
18908 static void
18909 list_one_var(v, prefix, first)
18910 dictitem_T *v;
18911 char_u *prefix;
18912 int *first;
18914 char_u *tofree;
18915 char_u *s;
18916 char_u numbuf[NUMBUFLEN];
18918 s = echo_string(&v->di_tv, &tofree, numbuf, ++current_copyID);
18919 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
18920 s == NULL ? (char_u *)"" : s, first);
18921 vim_free(tofree);
18924 static void
18925 list_one_var_a(prefix, name, type, string, first)
18926 char_u *prefix;
18927 char_u *name;
18928 int type;
18929 char_u *string;
18930 int *first; /* when TRUE clear rest of screen and set to FALSE */
18932 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
18933 msg_start();
18934 msg_puts(prefix);
18935 if (name != NULL) /* "a:" vars don't have a name stored */
18936 msg_puts(name);
18937 msg_putchar(' ');
18938 msg_advance(22);
18939 if (type == VAR_NUMBER)
18940 msg_putchar('#');
18941 else if (type == VAR_FUNC)
18942 msg_putchar('*');
18943 else if (type == VAR_LIST)
18945 msg_putchar('[');
18946 if (*string == '[')
18947 ++string;
18949 else if (type == VAR_DICT)
18951 msg_putchar('{');
18952 if (*string == '{')
18953 ++string;
18955 else
18956 msg_putchar(' ');
18958 msg_outtrans(string);
18960 if (type == VAR_FUNC)
18961 msg_puts((char_u *)"()");
18962 if (*first)
18964 msg_clr_eos();
18965 *first = FALSE;
18970 * Set variable "name" to value in "tv".
18971 * If the variable already exists, the value is updated.
18972 * Otherwise the variable is created.
18974 static void
18975 set_var(name, tv, copy)
18976 char_u *name;
18977 typval_T *tv;
18978 int copy; /* make copy of value in "tv" */
18980 dictitem_T *v;
18981 char_u *varname;
18982 hashtab_T *ht;
18983 char_u *p;
18985 if (tv->v_type == VAR_FUNC)
18987 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
18988 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
18989 ? name[2] : name[0]))
18991 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
18992 return;
18994 if (function_exists(name))
18996 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
18997 name);
18998 return;
19002 ht = find_var_ht(name, &varname);
19003 if (ht == NULL || *varname == NUL)
19005 EMSG2(_(e_illvar), name);
19006 return;
19009 v = find_var_in_ht(ht, varname, TRUE);
19010 if (v != NULL)
19012 /* existing variable, need to clear the value */
19013 if (var_check_ro(v->di_flags, name)
19014 || tv_check_lock(v->di_tv.v_lock, name))
19015 return;
19016 if (v->di_tv.v_type != tv->v_type
19017 && !((v->di_tv.v_type == VAR_STRING
19018 || v->di_tv.v_type == VAR_NUMBER)
19019 && (tv->v_type == VAR_STRING
19020 || tv->v_type == VAR_NUMBER))
19021 #ifdef FEAT_FLOAT
19022 && !((v->di_tv.v_type == VAR_NUMBER
19023 || v->di_tv.v_type == VAR_FLOAT)
19024 && (tv->v_type == VAR_NUMBER
19025 || tv->v_type == VAR_FLOAT))
19026 #endif
19029 EMSG2(_("E706: Variable type mismatch for: %s"), name);
19030 return;
19034 * Handle setting internal v: variables separately: we don't change
19035 * the type.
19037 if (ht == &vimvarht)
19039 if (v->di_tv.v_type == VAR_STRING)
19041 vim_free(v->di_tv.vval.v_string);
19042 if (copy || tv->v_type != VAR_STRING)
19043 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
19044 else
19046 /* Take over the string to avoid an extra alloc/free. */
19047 v->di_tv.vval.v_string = tv->vval.v_string;
19048 tv->vval.v_string = NULL;
19051 else if (v->di_tv.v_type != VAR_NUMBER)
19052 EMSG2(_(e_intern2), "set_var()");
19053 else
19055 v->di_tv.vval.v_number = get_tv_number(tv);
19056 if (STRCMP(varname, "searchforward") == 0)
19057 set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
19059 return;
19062 clear_tv(&v->di_tv);
19064 else /* add a new variable */
19066 /* Can't add "v:" variable. */
19067 if (ht == &vimvarht)
19069 EMSG2(_(e_illvar), name);
19070 return;
19073 /* Make sure the variable name is valid. */
19074 for (p = varname; *p != NUL; ++p)
19075 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
19076 && *p != AUTOLOAD_CHAR)
19078 EMSG2(_(e_illvar), varname);
19079 return;
19082 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
19083 + STRLEN(varname)));
19084 if (v == NULL)
19085 return;
19086 STRCPY(v->di_key, varname);
19087 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
19089 vim_free(v);
19090 return;
19092 v->di_flags = 0;
19095 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
19096 copy_tv(tv, &v->di_tv);
19097 else
19099 v->di_tv = *tv;
19100 v->di_tv.v_lock = 0;
19101 init_tv(tv);
19106 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
19107 * Also give an error message.
19109 static int
19110 var_check_ro(flags, name)
19111 int flags;
19112 char_u *name;
19114 if (flags & DI_FLAGS_RO)
19116 EMSG2(_(e_readonlyvar), name);
19117 return TRUE;
19119 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
19121 EMSG2(_(e_readonlysbx), name);
19122 return TRUE;
19124 return FALSE;
19128 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
19129 * Also give an error message.
19131 static int
19132 var_check_fixed(flags, name)
19133 int flags;
19134 char_u *name;
19136 if (flags & DI_FLAGS_FIX)
19138 EMSG2(_("E795: Cannot delete variable %s"), name);
19139 return TRUE;
19141 return FALSE;
19145 * Return TRUE if typeval "tv" is set to be locked (immutable).
19146 * Also give an error message, using "name".
19148 static int
19149 tv_check_lock(lock, name)
19150 int lock;
19151 char_u *name;
19153 if (lock & VAR_LOCKED)
19155 EMSG2(_("E741: Value is locked: %s"),
19156 name == NULL ? (char_u *)_("Unknown") : name);
19157 return TRUE;
19159 if (lock & VAR_FIXED)
19161 EMSG2(_("E742: Cannot change value of %s"),
19162 name == NULL ? (char_u *)_("Unknown") : name);
19163 return TRUE;
19165 return FALSE;
19169 * Copy the values from typval_T "from" to typval_T "to".
19170 * When needed allocates string or increases reference count.
19171 * Does not make a copy of a list or dict but copies the reference!
19173 static void
19174 copy_tv(from, to)
19175 typval_T *from;
19176 typval_T *to;
19178 to->v_type = from->v_type;
19179 to->v_lock = 0;
19180 switch (from->v_type)
19182 case VAR_NUMBER:
19183 to->vval.v_number = from->vval.v_number;
19184 break;
19185 #ifdef FEAT_FLOAT
19186 case VAR_FLOAT:
19187 to->vval.v_float = from->vval.v_float;
19188 break;
19189 #endif
19190 case VAR_STRING:
19191 case VAR_FUNC:
19192 if (from->vval.v_string == NULL)
19193 to->vval.v_string = NULL;
19194 else
19196 to->vval.v_string = vim_strsave(from->vval.v_string);
19197 if (from->v_type == VAR_FUNC)
19198 func_ref(to->vval.v_string);
19200 break;
19201 case VAR_LIST:
19202 if (from->vval.v_list == NULL)
19203 to->vval.v_list = NULL;
19204 else
19206 to->vval.v_list = from->vval.v_list;
19207 ++to->vval.v_list->lv_refcount;
19209 break;
19210 case VAR_DICT:
19211 if (from->vval.v_dict == NULL)
19212 to->vval.v_dict = NULL;
19213 else
19215 to->vval.v_dict = from->vval.v_dict;
19216 ++to->vval.v_dict->dv_refcount;
19218 break;
19219 default:
19220 EMSG2(_(e_intern2), "copy_tv()");
19221 break;
19226 * Make a copy of an item.
19227 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
19228 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
19229 * reference to an already copied list/dict can be used.
19230 * Returns FAIL or OK.
19232 static int
19233 item_copy(from, to, deep, copyID)
19234 typval_T *from;
19235 typval_T *to;
19236 int deep;
19237 int copyID;
19239 static int recurse = 0;
19240 int ret = OK;
19242 if (recurse >= DICT_MAXNEST)
19244 EMSG(_("E698: variable nested too deep for making a copy"));
19245 return FAIL;
19247 ++recurse;
19249 switch (from->v_type)
19251 case VAR_NUMBER:
19252 #ifdef FEAT_FLOAT
19253 case VAR_FLOAT:
19254 #endif
19255 case VAR_STRING:
19256 case VAR_FUNC:
19257 copy_tv(from, to);
19258 break;
19259 case VAR_LIST:
19260 to->v_type = VAR_LIST;
19261 to->v_lock = 0;
19262 if (from->vval.v_list == NULL)
19263 to->vval.v_list = NULL;
19264 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
19266 /* use the copy made earlier */
19267 to->vval.v_list = from->vval.v_list->lv_copylist;
19268 ++to->vval.v_list->lv_refcount;
19270 else
19271 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
19272 if (to->vval.v_list == NULL)
19273 ret = FAIL;
19274 break;
19275 case VAR_DICT:
19276 to->v_type = VAR_DICT;
19277 to->v_lock = 0;
19278 if (from->vval.v_dict == NULL)
19279 to->vval.v_dict = NULL;
19280 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
19282 /* use the copy made earlier */
19283 to->vval.v_dict = from->vval.v_dict->dv_copydict;
19284 ++to->vval.v_dict->dv_refcount;
19286 else
19287 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
19288 if (to->vval.v_dict == NULL)
19289 ret = FAIL;
19290 break;
19291 default:
19292 EMSG2(_(e_intern2), "item_copy()");
19293 ret = FAIL;
19295 --recurse;
19296 return ret;
19300 * ":echo expr1 ..." print each argument separated with a space, add a
19301 * newline at the end.
19302 * ":echon expr1 ..." print each argument plain.
19304 void
19305 ex_echo(eap)
19306 exarg_T *eap;
19308 char_u *arg = eap->arg;
19309 typval_T rettv;
19310 char_u *tofree;
19311 char_u *p;
19312 int needclr = TRUE;
19313 int atstart = TRUE;
19314 char_u numbuf[NUMBUFLEN];
19316 if (eap->skip)
19317 ++emsg_skip;
19318 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
19320 /* If eval1() causes an error message the text from the command may
19321 * still need to be cleared. E.g., "echo 22,44". */
19322 need_clr_eos = needclr;
19324 p = arg;
19325 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19328 * Report the invalid expression unless the expression evaluation
19329 * has been cancelled due to an aborting error, an interrupt, or an
19330 * exception.
19332 if (!aborting())
19333 EMSG2(_(e_invexpr2), p);
19334 need_clr_eos = FALSE;
19335 break;
19337 need_clr_eos = FALSE;
19339 if (!eap->skip)
19341 if (atstart)
19343 atstart = FALSE;
19344 /* Call msg_start() after eval1(), evaluating the expression
19345 * may cause a message to appear. */
19346 if (eap->cmdidx == CMD_echo)
19347 msg_start();
19349 else if (eap->cmdidx == CMD_echo)
19350 msg_puts_attr((char_u *)" ", echo_attr);
19351 p = echo_string(&rettv, &tofree, numbuf, ++current_copyID);
19352 if (p != NULL)
19353 for ( ; *p != NUL && !got_int; ++p)
19355 if (*p == '\n' || *p == '\r' || *p == TAB)
19357 if (*p != TAB && needclr)
19359 /* remove any text still there from the command */
19360 msg_clr_eos();
19361 needclr = FALSE;
19363 msg_putchar_attr(*p, echo_attr);
19365 else
19367 #ifdef FEAT_MBYTE
19368 if (has_mbyte)
19370 int i = (*mb_ptr2len)(p);
19372 (void)msg_outtrans_len_attr(p, i, echo_attr);
19373 p += i - 1;
19375 else
19376 #endif
19377 (void)msg_outtrans_len_attr(p, 1, echo_attr);
19380 vim_free(tofree);
19382 clear_tv(&rettv);
19383 arg = skipwhite(arg);
19385 eap->nextcmd = check_nextcmd(arg);
19387 if (eap->skip)
19388 --emsg_skip;
19389 else
19391 /* remove text that may still be there from the command */
19392 if (needclr)
19393 msg_clr_eos();
19394 if (eap->cmdidx == CMD_echo)
19395 msg_end();
19400 * ":echohl {name}".
19402 void
19403 ex_echohl(eap)
19404 exarg_T *eap;
19406 int id;
19408 id = syn_name2id(eap->arg);
19409 if (id == 0)
19410 echo_attr = 0;
19411 else
19412 echo_attr = syn_id2attr(id);
19416 * ":execute expr1 ..." execute the result of an expression.
19417 * ":echomsg expr1 ..." Print a message
19418 * ":echoerr expr1 ..." Print an error
19419 * Each gets spaces around each argument and a newline at the end for
19420 * echo commands
19422 void
19423 ex_execute(eap)
19424 exarg_T *eap;
19426 char_u *arg = eap->arg;
19427 typval_T rettv;
19428 int ret = OK;
19429 char_u *p;
19430 garray_T ga;
19431 int len;
19432 int save_did_emsg;
19434 ga_init2(&ga, 1, 80);
19436 if (eap->skip)
19437 ++emsg_skip;
19438 while (*arg != NUL && *arg != '|' && *arg != '\n')
19440 p = arg;
19441 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19444 * Report the invalid expression unless the expression evaluation
19445 * has been cancelled due to an aborting error, an interrupt, or an
19446 * exception.
19448 if (!aborting())
19449 EMSG2(_(e_invexpr2), p);
19450 ret = FAIL;
19451 break;
19454 if (!eap->skip)
19456 p = get_tv_string(&rettv);
19457 len = (int)STRLEN(p);
19458 if (ga_grow(&ga, len + 2) == FAIL)
19460 clear_tv(&rettv);
19461 ret = FAIL;
19462 break;
19464 if (ga.ga_len)
19465 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
19466 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
19467 ga.ga_len += len;
19470 clear_tv(&rettv);
19471 arg = skipwhite(arg);
19474 if (ret != FAIL && ga.ga_data != NULL)
19476 if (eap->cmdidx == CMD_echomsg)
19478 MSG_ATTR(ga.ga_data, echo_attr);
19479 out_flush();
19481 else if (eap->cmdidx == CMD_echoerr)
19483 /* We don't want to abort following commands, restore did_emsg. */
19484 save_did_emsg = did_emsg;
19485 EMSG((char_u *)ga.ga_data);
19486 if (!force_abort)
19487 did_emsg = save_did_emsg;
19489 else if (eap->cmdidx == CMD_execute)
19490 do_cmdline((char_u *)ga.ga_data,
19491 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
19494 ga_clear(&ga);
19496 if (eap->skip)
19497 --emsg_skip;
19499 eap->nextcmd = check_nextcmd(arg);
19503 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
19504 * "arg" points to the "&" or '+' when called, to "option" when returning.
19505 * Returns NULL when no option name found. Otherwise pointer to the char
19506 * after the option name.
19508 static char_u *
19509 find_option_end(arg, opt_flags)
19510 char_u **arg;
19511 int *opt_flags;
19513 char_u *p = *arg;
19515 ++p;
19516 if (*p == 'g' && p[1] == ':')
19518 *opt_flags = OPT_GLOBAL;
19519 p += 2;
19521 else if (*p == 'l' && p[1] == ':')
19523 *opt_flags = OPT_LOCAL;
19524 p += 2;
19526 else
19527 *opt_flags = 0;
19529 if (!ASCII_ISALPHA(*p))
19530 return NULL;
19531 *arg = p;
19533 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
19534 p += 4; /* termcap option */
19535 else
19536 while (ASCII_ISALPHA(*p))
19537 ++p;
19538 return p;
19542 * ":function"
19544 void
19545 ex_function(eap)
19546 exarg_T *eap;
19548 char_u *theline;
19549 int j;
19550 int c;
19551 int saved_did_emsg;
19552 char_u *name = NULL;
19553 char_u *p;
19554 char_u *arg;
19555 char_u *line_arg = NULL;
19556 garray_T newargs;
19557 garray_T newlines;
19558 int varargs = FALSE;
19559 int mustend = FALSE;
19560 int flags = 0;
19561 ufunc_T *fp;
19562 int indent;
19563 int nesting;
19564 char_u *skip_until = NULL;
19565 dictitem_T *v;
19566 funcdict_T fudi;
19567 static int func_nr = 0; /* number for nameless function */
19568 int paren;
19569 hashtab_T *ht;
19570 int todo;
19571 hashitem_T *hi;
19572 int sourcing_lnum_off;
19575 * ":function" without argument: list functions.
19577 if (ends_excmd(*eap->arg))
19579 if (!eap->skip)
19581 todo = (int)func_hashtab.ht_used;
19582 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19584 if (!HASHITEM_EMPTY(hi))
19586 --todo;
19587 fp = HI2UF(hi);
19588 if (!isdigit(*fp->uf_name))
19589 list_func_head(fp, FALSE);
19593 eap->nextcmd = check_nextcmd(eap->arg);
19594 return;
19598 * ":function /pat": list functions matching pattern.
19600 if (*eap->arg == '/')
19602 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
19603 if (!eap->skip)
19605 regmatch_T regmatch;
19607 c = *p;
19608 *p = NUL;
19609 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
19610 *p = c;
19611 if (regmatch.regprog != NULL)
19613 regmatch.rm_ic = p_ic;
19615 todo = (int)func_hashtab.ht_used;
19616 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19618 if (!HASHITEM_EMPTY(hi))
19620 --todo;
19621 fp = HI2UF(hi);
19622 if (!isdigit(*fp->uf_name)
19623 && vim_regexec(&regmatch, fp->uf_name, 0))
19624 list_func_head(fp, FALSE);
19629 if (*p == '/')
19630 ++p;
19631 eap->nextcmd = check_nextcmd(p);
19632 return;
19636 * Get the function name. There are these situations:
19637 * func normal function name
19638 * "name" == func, "fudi.fd_dict" == NULL
19639 * dict.func new dictionary entry
19640 * "name" == NULL, "fudi.fd_dict" set,
19641 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
19642 * dict.func existing dict entry with a Funcref
19643 * "name" == func, "fudi.fd_dict" set,
19644 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19645 * dict.func existing dict entry that's not a Funcref
19646 * "name" == NULL, "fudi.fd_dict" set,
19647 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19649 p = eap->arg;
19650 name = trans_function_name(&p, eap->skip, 0, &fudi);
19651 paren = (vim_strchr(p, '(') != NULL);
19652 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
19655 * Return on an invalid expression in braces, unless the expression
19656 * evaluation has been cancelled due to an aborting error, an
19657 * interrupt, or an exception.
19659 if (!aborting())
19661 if (!eap->skip && fudi.fd_newkey != NULL)
19662 EMSG2(_(e_dictkey), fudi.fd_newkey);
19663 vim_free(fudi.fd_newkey);
19664 return;
19666 else
19667 eap->skip = TRUE;
19670 /* An error in a function call during evaluation of an expression in magic
19671 * braces should not cause the function not to be defined. */
19672 saved_did_emsg = did_emsg;
19673 did_emsg = FALSE;
19676 * ":function func" with only function name: list function.
19678 if (!paren)
19680 if (!ends_excmd(*skipwhite(p)))
19682 EMSG(_(e_trailing));
19683 goto ret_free;
19685 eap->nextcmd = check_nextcmd(p);
19686 if (eap->nextcmd != NULL)
19687 *p = NUL;
19688 if (!eap->skip && !got_int)
19690 fp = find_func(name);
19691 if (fp != NULL)
19693 list_func_head(fp, TRUE);
19694 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
19696 if (FUNCLINE(fp, j) == NULL)
19697 continue;
19698 msg_putchar('\n');
19699 msg_outnum((long)(j + 1));
19700 if (j < 9)
19701 msg_putchar(' ');
19702 if (j < 99)
19703 msg_putchar(' ');
19704 msg_prt_line(FUNCLINE(fp, j), FALSE);
19705 out_flush(); /* show a line at a time */
19706 ui_breakcheck();
19708 if (!got_int)
19710 msg_putchar('\n');
19711 msg_puts((char_u *)" endfunction");
19714 else
19715 emsg_funcname("E123: Undefined function: %s", name);
19717 goto ret_free;
19721 * ":function name(arg1, arg2)" Define function.
19723 p = skipwhite(p);
19724 if (*p != '(')
19726 if (!eap->skip)
19728 EMSG2(_("E124: Missing '(': %s"), eap->arg);
19729 goto ret_free;
19731 /* attempt to continue by skipping some text */
19732 if (vim_strchr(p, '(') != NULL)
19733 p = vim_strchr(p, '(');
19735 p = skipwhite(p + 1);
19737 ga_init2(&newargs, (int)sizeof(char_u *), 3);
19738 ga_init2(&newlines, (int)sizeof(char_u *), 3);
19740 if (!eap->skip)
19742 /* Check the name of the function. Unless it's a dictionary function
19743 * (that we are overwriting). */
19744 if (name != NULL)
19745 arg = name;
19746 else
19747 arg = fudi.fd_newkey;
19748 if (arg != NULL && (fudi.fd_di == NULL
19749 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
19751 if (*arg == K_SPECIAL)
19752 j = 3;
19753 else
19754 j = 0;
19755 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
19756 : eval_isnamec(arg[j])))
19757 ++j;
19758 if (arg[j] != NUL)
19759 emsg_funcname(_(e_invarg2), arg);
19764 * Isolate the arguments: "arg1, arg2, ...)"
19766 while (*p != ')')
19768 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
19770 varargs = TRUE;
19771 p += 3;
19772 mustend = TRUE;
19774 else
19776 arg = p;
19777 while (ASCII_ISALNUM(*p) || *p == '_')
19778 ++p;
19779 if (arg == p || isdigit(*arg)
19780 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
19781 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
19783 if (!eap->skip)
19784 EMSG2(_("E125: Illegal argument: %s"), arg);
19785 break;
19787 if (ga_grow(&newargs, 1) == FAIL)
19788 goto erret;
19789 c = *p;
19790 *p = NUL;
19791 arg = vim_strsave(arg);
19792 if (arg == NULL)
19793 goto erret;
19794 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
19795 *p = c;
19796 newargs.ga_len++;
19797 if (*p == ',')
19798 ++p;
19799 else
19800 mustend = TRUE;
19802 p = skipwhite(p);
19803 if (mustend && *p != ')')
19805 if (!eap->skip)
19806 EMSG2(_(e_invarg2), eap->arg);
19807 break;
19810 ++p; /* skip the ')' */
19812 /* find extra arguments "range", "dict" and "abort" */
19813 for (;;)
19815 p = skipwhite(p);
19816 if (STRNCMP(p, "range", 5) == 0)
19818 flags |= FC_RANGE;
19819 p += 5;
19821 else if (STRNCMP(p, "dict", 4) == 0)
19823 flags |= FC_DICT;
19824 p += 4;
19826 else if (STRNCMP(p, "abort", 5) == 0)
19828 flags |= FC_ABORT;
19829 p += 5;
19831 else
19832 break;
19835 /* When there is a line break use what follows for the function body.
19836 * Makes 'exe "func Test()\n...\nendfunc"' work. */
19837 if (*p == '\n')
19838 line_arg = p + 1;
19839 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
19840 EMSG(_(e_trailing));
19843 * Read the body of the function, until ":endfunction" is found.
19845 if (KeyTyped)
19847 /* Check if the function already exists, don't let the user type the
19848 * whole function before telling him it doesn't work! For a script we
19849 * need to skip the body to be able to find what follows. */
19850 if (!eap->skip && !eap->forceit)
19852 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
19853 EMSG(_(e_funcdict));
19854 else if (name != NULL && find_func(name) != NULL)
19855 emsg_funcname(e_funcexts, name);
19858 if (!eap->skip && did_emsg)
19859 goto erret;
19861 msg_putchar('\n'); /* don't overwrite the function name */
19862 cmdline_row = msg_row;
19865 indent = 2;
19866 nesting = 0;
19867 for (;;)
19869 msg_scroll = TRUE;
19870 need_wait_return = FALSE;
19871 sourcing_lnum_off = sourcing_lnum;
19873 if (line_arg != NULL)
19875 /* Use eap->arg, split up in parts by line breaks. */
19876 theline = line_arg;
19877 p = vim_strchr(theline, '\n');
19878 if (p == NULL)
19879 line_arg += STRLEN(line_arg);
19880 else
19882 *p = NUL;
19883 line_arg = p + 1;
19886 else if (eap->getline == NULL)
19887 theline = getcmdline(':', 0L, indent);
19888 else
19889 theline = eap->getline(':', eap->cookie, indent);
19890 if (KeyTyped)
19891 lines_left = Rows - 1;
19892 if (theline == NULL)
19894 EMSG(_("E126: Missing :endfunction"));
19895 goto erret;
19898 /* Detect line continuation: sourcing_lnum increased more than one. */
19899 if (sourcing_lnum > sourcing_lnum_off + 1)
19900 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
19901 else
19902 sourcing_lnum_off = 0;
19904 if (skip_until != NULL)
19906 /* between ":append" and "." and between ":python <<EOF" and "EOF"
19907 * don't check for ":endfunc". */
19908 if (STRCMP(theline, skip_until) == 0)
19910 vim_free(skip_until);
19911 skip_until = NULL;
19914 else
19916 /* skip ':' and blanks*/
19917 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
19920 /* Check for "endfunction". */
19921 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
19923 if (line_arg == NULL)
19924 vim_free(theline);
19925 break;
19928 /* Increase indent inside "if", "while", "for" and "try", decrease
19929 * at "end". */
19930 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
19931 indent -= 2;
19932 else if (STRNCMP(p, "if", 2) == 0
19933 || STRNCMP(p, "wh", 2) == 0
19934 || STRNCMP(p, "for", 3) == 0
19935 || STRNCMP(p, "try", 3) == 0)
19936 indent += 2;
19938 /* Check for defining a function inside this function. */
19939 if (checkforcmd(&p, "function", 2))
19941 if (*p == '!')
19942 p = skipwhite(p + 1);
19943 p += eval_fname_script(p);
19944 if (ASCII_ISALPHA(*p))
19946 vim_free(trans_function_name(&p, TRUE, 0, NULL));
19947 if (*skipwhite(p) == '(')
19949 ++nesting;
19950 indent += 2;
19955 /* Check for ":append" or ":insert". */
19956 p = skip_range(p, NULL);
19957 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
19958 || (p[0] == 'i'
19959 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
19960 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
19961 skip_until = vim_strsave((char_u *)".");
19963 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
19964 arg = skipwhite(skiptowhite(p));
19965 if (arg[0] == '<' && arg[1] =='<'
19966 && ((p[0] == 'p' && p[1] == 'y'
19967 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
19968 || (p[0] == 'p' && p[1] == 'e'
19969 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
19970 || (p[0] == 't' && p[1] == 'c'
19971 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
19972 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
19973 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
19974 || (p[0] == 'm' && p[1] == 'z'
19975 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
19978 /* ":python <<" continues until a dot, like ":append" */
19979 p = skipwhite(arg + 2);
19980 if (*p == NUL)
19981 skip_until = vim_strsave((char_u *)".");
19982 else
19983 skip_until = vim_strsave(p);
19987 /* Add the line to the function. */
19988 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
19990 if (line_arg == NULL)
19991 vim_free(theline);
19992 goto erret;
19995 /* Copy the line to newly allocated memory. get_one_sourceline()
19996 * allocates 250 bytes per line, this saves 80% on average. The cost
19997 * is an extra alloc/free. */
19998 p = vim_strsave(theline);
19999 if (p != NULL)
20001 if (line_arg == NULL)
20002 vim_free(theline);
20003 theline = p;
20006 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
20008 /* Add NULL lines for continuation lines, so that the line count is
20009 * equal to the index in the growarray. */
20010 while (sourcing_lnum_off-- > 0)
20011 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
20013 /* Check for end of eap->arg. */
20014 if (line_arg != NULL && *line_arg == NUL)
20015 line_arg = NULL;
20018 /* Don't define the function when skipping commands or when an error was
20019 * detected. */
20020 if (eap->skip || did_emsg)
20021 goto erret;
20024 * If there are no errors, add the function
20026 if (fudi.fd_dict == NULL)
20028 v = find_var(name, &ht);
20029 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
20031 emsg_funcname("E707: Function name conflicts with variable: %s",
20032 name);
20033 goto erret;
20036 fp = find_func(name);
20037 if (fp != NULL)
20039 if (!eap->forceit)
20041 emsg_funcname(e_funcexts, name);
20042 goto erret;
20044 if (fp->uf_calls > 0)
20046 emsg_funcname("E127: Cannot redefine function %s: It is in use",
20047 name);
20048 goto erret;
20050 /* redefine existing function */
20051 ga_clear_strings(&(fp->uf_args));
20052 ga_clear_strings(&(fp->uf_lines));
20053 vim_free(name);
20054 name = NULL;
20057 else
20059 char numbuf[20];
20061 fp = NULL;
20062 if (fudi.fd_newkey == NULL && !eap->forceit)
20064 EMSG(_(e_funcdict));
20065 goto erret;
20067 if (fudi.fd_di == NULL)
20069 /* Can't add a function to a locked dictionary */
20070 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
20071 goto erret;
20073 /* Can't change an existing function if it is locked */
20074 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
20075 goto erret;
20077 /* Give the function a sequential number. Can only be used with a
20078 * Funcref! */
20079 vim_free(name);
20080 sprintf(numbuf, "%d", ++func_nr);
20081 name = vim_strsave((char_u *)numbuf);
20082 if (name == NULL)
20083 goto erret;
20086 if (fp == NULL)
20088 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
20090 int slen, plen;
20091 char_u *scriptname;
20093 /* Check that the autoload name matches the script name. */
20094 j = FAIL;
20095 if (sourcing_name != NULL)
20097 scriptname = autoload_name(name);
20098 if (scriptname != NULL)
20100 p = vim_strchr(scriptname, '/');
20101 plen = (int)STRLEN(p);
20102 slen = (int)STRLEN(sourcing_name);
20103 if (slen > plen && fnamecmp(p,
20104 sourcing_name + slen - plen) == 0)
20105 j = OK;
20106 vim_free(scriptname);
20109 if (j == FAIL)
20111 EMSG2(_("E746: Function name does not match script file name: %s"), name);
20112 goto erret;
20116 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
20117 if (fp == NULL)
20118 goto erret;
20120 if (fudi.fd_dict != NULL)
20122 if (fudi.fd_di == NULL)
20124 /* add new dict entry */
20125 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
20126 if (fudi.fd_di == NULL)
20128 vim_free(fp);
20129 goto erret;
20131 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
20133 vim_free(fudi.fd_di);
20134 vim_free(fp);
20135 goto erret;
20138 else
20139 /* overwrite existing dict entry */
20140 clear_tv(&fudi.fd_di->di_tv);
20141 fudi.fd_di->di_tv.v_type = VAR_FUNC;
20142 fudi.fd_di->di_tv.v_lock = 0;
20143 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
20144 fp->uf_refcount = 1;
20146 /* behave like "dict" was used */
20147 flags |= FC_DICT;
20150 /* insert the new function in the function list */
20151 STRCPY(fp->uf_name, name);
20152 hash_add(&func_hashtab, UF2HIKEY(fp));
20154 fp->uf_args = newargs;
20155 fp->uf_lines = newlines;
20156 #ifdef FEAT_PROFILE
20157 fp->uf_tml_count = NULL;
20158 fp->uf_tml_total = NULL;
20159 fp->uf_tml_self = NULL;
20160 fp->uf_profiling = FALSE;
20161 if (prof_def_func())
20162 func_do_profile(fp);
20163 #endif
20164 fp->uf_varargs = varargs;
20165 fp->uf_flags = flags;
20166 fp->uf_calls = 0;
20167 fp->uf_script_ID = current_SID;
20168 goto ret_free;
20170 erret:
20171 ga_clear_strings(&newargs);
20172 ga_clear_strings(&newlines);
20173 ret_free:
20174 vim_free(skip_until);
20175 vim_free(fudi.fd_newkey);
20176 vim_free(name);
20177 did_emsg |= saved_did_emsg;
20181 * Get a function name, translating "<SID>" and "<SNR>".
20182 * Also handles a Funcref in a List or Dictionary.
20183 * Returns the function name in allocated memory, or NULL for failure.
20184 * flags:
20185 * TFN_INT: internal function name OK
20186 * TFN_QUIET: be quiet
20187 * Advances "pp" to just after the function name (if no error).
20189 static char_u *
20190 trans_function_name(pp, skip, flags, fdp)
20191 char_u **pp;
20192 int skip; /* only find the end, don't evaluate */
20193 int flags;
20194 funcdict_T *fdp; /* return: info about dictionary used */
20196 char_u *name = NULL;
20197 char_u *start;
20198 char_u *end;
20199 int lead;
20200 char_u sid_buf[20];
20201 int len;
20202 lval_T lv;
20204 if (fdp != NULL)
20205 vim_memset(fdp, 0, sizeof(funcdict_T));
20206 start = *pp;
20208 /* Check for hard coded <SNR>: already translated function ID (from a user
20209 * command). */
20210 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
20211 && (*pp)[2] == (int)KE_SNR)
20213 *pp += 3;
20214 len = get_id_len(pp) + 3;
20215 return vim_strnsave(start, len);
20218 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
20219 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
20220 lead = eval_fname_script(start);
20221 if (lead > 2)
20222 start += lead;
20224 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
20225 lead > 2 ? 0 : FNE_CHECK_START);
20226 if (end == start)
20228 if (!skip)
20229 EMSG(_("E129: Function name required"));
20230 goto theend;
20232 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
20235 * Report an invalid expression in braces, unless the expression
20236 * evaluation has been cancelled due to an aborting error, an
20237 * interrupt, or an exception.
20239 if (!aborting())
20241 if (end != NULL)
20242 EMSG2(_(e_invarg2), start);
20244 else
20245 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
20246 goto theend;
20249 if (lv.ll_tv != NULL)
20251 if (fdp != NULL)
20253 fdp->fd_dict = lv.ll_dict;
20254 fdp->fd_newkey = lv.ll_newkey;
20255 lv.ll_newkey = NULL;
20256 fdp->fd_di = lv.ll_di;
20258 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
20260 name = vim_strsave(lv.ll_tv->vval.v_string);
20261 *pp = end;
20263 else
20265 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
20266 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
20267 EMSG(_(e_funcref));
20268 else
20269 *pp = end;
20270 name = NULL;
20272 goto theend;
20275 if (lv.ll_name == NULL)
20277 /* Error found, but continue after the function name. */
20278 *pp = end;
20279 goto theend;
20282 /* Check if the name is a Funcref. If so, use the value. */
20283 if (lv.ll_exp_name != NULL)
20285 len = (int)STRLEN(lv.ll_exp_name);
20286 name = deref_func_name(lv.ll_exp_name, &len);
20287 if (name == lv.ll_exp_name)
20288 name = NULL;
20290 else
20292 len = (int)(end - *pp);
20293 name = deref_func_name(*pp, &len);
20294 if (name == *pp)
20295 name = NULL;
20297 if (name != NULL)
20299 name = vim_strsave(name);
20300 *pp = end;
20301 goto theend;
20304 if (lv.ll_exp_name != NULL)
20306 len = (int)STRLEN(lv.ll_exp_name);
20307 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
20308 && STRNCMP(lv.ll_name, "s:", 2) == 0)
20310 /* When there was "s:" already or the name expanded to get a
20311 * leading "s:" then remove it. */
20312 lv.ll_name += 2;
20313 len -= 2;
20314 lead = 2;
20317 else
20319 if (lead == 2) /* skip over "s:" */
20320 lv.ll_name += 2;
20321 len = (int)(end - lv.ll_name);
20325 * Copy the function name to allocated memory.
20326 * Accept <SID>name() inside a script, translate into <SNR>123_name().
20327 * Accept <SNR>123_name() outside a script.
20329 if (skip)
20330 lead = 0; /* do nothing */
20331 else if (lead > 0)
20333 lead = 3;
20334 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
20335 || eval_fname_sid(*pp))
20337 /* It's "s:" or "<SID>" */
20338 if (current_SID <= 0)
20340 EMSG(_(e_usingsid));
20341 goto theend;
20343 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
20344 lead += (int)STRLEN(sid_buf);
20347 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
20349 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
20350 goto theend;
20352 name = alloc((unsigned)(len + lead + 1));
20353 if (name != NULL)
20355 if (lead > 0)
20357 name[0] = K_SPECIAL;
20358 name[1] = KS_EXTRA;
20359 name[2] = (int)KE_SNR;
20360 if (lead > 3) /* If it's "<SID>" */
20361 STRCPY(name + 3, sid_buf);
20363 mch_memmove(name + lead, lv.ll_name, (size_t)len);
20364 name[len + lead] = NUL;
20366 *pp = end;
20368 theend:
20369 clear_lval(&lv);
20370 return name;
20374 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
20375 * Return 2 if "p" starts with "s:".
20376 * Return 0 otherwise.
20378 static int
20379 eval_fname_script(p)
20380 char_u *p;
20382 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
20383 || STRNICMP(p + 1, "SNR>", 4) == 0))
20384 return 5;
20385 if (p[0] == 's' && p[1] == ':')
20386 return 2;
20387 return 0;
20391 * Return TRUE if "p" starts with "<SID>" or "s:".
20392 * Only works if eval_fname_script() returned non-zero for "p"!
20394 static int
20395 eval_fname_sid(p)
20396 char_u *p;
20398 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
20402 * List the head of the function: "name(arg1, arg2)".
20404 static void
20405 list_func_head(fp, indent)
20406 ufunc_T *fp;
20407 int indent;
20409 int j;
20411 msg_start();
20412 if (indent)
20413 MSG_PUTS(" ");
20414 MSG_PUTS("function ");
20415 if (fp->uf_name[0] == K_SPECIAL)
20417 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
20418 msg_puts(fp->uf_name + 3);
20420 else
20421 msg_puts(fp->uf_name);
20422 msg_putchar('(');
20423 for (j = 0; j < fp->uf_args.ga_len; ++j)
20425 if (j)
20426 MSG_PUTS(", ");
20427 msg_puts(FUNCARG(fp, j));
20429 if (fp->uf_varargs)
20431 if (j)
20432 MSG_PUTS(", ");
20433 MSG_PUTS("...");
20435 msg_putchar(')');
20436 msg_clr_eos();
20437 if (p_verbose > 0)
20438 last_set_msg(fp->uf_script_ID);
20442 * Find a function by name, return pointer to it in ufuncs.
20443 * Return NULL for unknown function.
20445 static ufunc_T *
20446 find_func(name)
20447 char_u *name;
20449 hashitem_T *hi;
20451 hi = hash_find(&func_hashtab, name);
20452 if (!HASHITEM_EMPTY(hi))
20453 return HI2UF(hi);
20454 return NULL;
20457 #if defined(EXITFREE) || defined(PROTO)
20458 void
20459 free_all_functions()
20461 hashitem_T *hi;
20463 /* Need to start all over every time, because func_free() may change the
20464 * hash table. */
20465 while (func_hashtab.ht_used > 0)
20466 for (hi = func_hashtab.ht_array; ; ++hi)
20467 if (!HASHITEM_EMPTY(hi))
20469 func_free(HI2UF(hi));
20470 break;
20473 #endif
20476 * Return TRUE if a function "name" exists.
20478 static int
20479 function_exists(name)
20480 char_u *name;
20482 char_u *nm = name;
20483 char_u *p;
20484 int n = FALSE;
20486 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
20487 nm = skipwhite(nm);
20489 /* Only accept "funcname", "funcname ", "funcname (..." and
20490 * "funcname(...", not "funcname!...". */
20491 if (p != NULL && (*nm == NUL || *nm == '('))
20493 if (builtin_function(p))
20494 n = (find_internal_func(p) >= 0);
20495 else
20496 n = (find_func(p) != NULL);
20498 vim_free(p);
20499 return n;
20503 * Return TRUE if "name" looks like a builtin function name: starts with a
20504 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
20506 static int
20507 builtin_function(name)
20508 char_u *name;
20510 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
20511 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
20514 #if defined(FEAT_PROFILE) || defined(PROTO)
20516 * Start profiling function "fp".
20518 static void
20519 func_do_profile(fp)
20520 ufunc_T *fp;
20522 fp->uf_tm_count = 0;
20523 profile_zero(&fp->uf_tm_self);
20524 profile_zero(&fp->uf_tm_total);
20525 if (fp->uf_tml_count == NULL)
20526 fp->uf_tml_count = (int *)alloc_clear((unsigned)
20527 (sizeof(int) * fp->uf_lines.ga_len));
20528 if (fp->uf_tml_total == NULL)
20529 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
20530 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20531 if (fp->uf_tml_self == NULL)
20532 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
20533 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20534 fp->uf_tml_idx = -1;
20535 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
20536 || fp->uf_tml_self == NULL)
20537 return; /* out of memory */
20539 fp->uf_profiling = TRUE;
20543 * Dump the profiling results for all functions in file "fd".
20545 void
20546 func_dump_profile(fd)
20547 FILE *fd;
20549 hashitem_T *hi;
20550 int todo;
20551 ufunc_T *fp;
20552 int i;
20553 ufunc_T **sorttab;
20554 int st_len = 0;
20556 todo = (int)func_hashtab.ht_used;
20557 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
20559 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
20561 if (!HASHITEM_EMPTY(hi))
20563 --todo;
20564 fp = HI2UF(hi);
20565 if (fp->uf_profiling)
20567 if (sorttab != NULL)
20568 sorttab[st_len++] = fp;
20570 if (fp->uf_name[0] == K_SPECIAL)
20571 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
20572 else
20573 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
20574 if (fp->uf_tm_count == 1)
20575 fprintf(fd, "Called 1 time\n");
20576 else
20577 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
20578 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
20579 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
20580 fprintf(fd, "\n");
20581 fprintf(fd, "count total (s) self (s)\n");
20583 for (i = 0; i < fp->uf_lines.ga_len; ++i)
20585 if (FUNCLINE(fp, i) == NULL)
20586 continue;
20587 prof_func_line(fd, fp->uf_tml_count[i],
20588 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
20589 fprintf(fd, "%s\n", FUNCLINE(fp, i));
20591 fprintf(fd, "\n");
20596 if (sorttab != NULL && st_len > 0)
20598 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20599 prof_total_cmp);
20600 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
20601 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20602 prof_self_cmp);
20603 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
20607 static void
20608 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
20609 FILE *fd;
20610 ufunc_T **sorttab;
20611 int st_len;
20612 char *title;
20613 int prefer_self; /* when equal print only self time */
20615 int i;
20616 ufunc_T *fp;
20618 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
20619 fprintf(fd, "count total (s) self (s) function\n");
20620 for (i = 0; i < 20 && i < st_len; ++i)
20622 fp = sorttab[i];
20623 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
20624 prefer_self);
20625 if (fp->uf_name[0] == K_SPECIAL)
20626 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
20627 else
20628 fprintf(fd, " %s()\n", fp->uf_name);
20630 fprintf(fd, "\n");
20634 * Print the count and times for one function or function line.
20636 static void
20637 prof_func_line(fd, count, total, self, prefer_self)
20638 FILE *fd;
20639 int count;
20640 proftime_T *total;
20641 proftime_T *self;
20642 int prefer_self; /* when equal print only self time */
20644 if (count > 0)
20646 fprintf(fd, "%5d ", count);
20647 if (prefer_self && profile_equal(total, self))
20648 fprintf(fd, " ");
20649 else
20650 fprintf(fd, "%s ", profile_msg(total));
20651 if (!prefer_self && profile_equal(total, self))
20652 fprintf(fd, " ");
20653 else
20654 fprintf(fd, "%s ", profile_msg(self));
20656 else
20657 fprintf(fd, " ");
20661 * Compare function for total time sorting.
20663 static int
20664 #ifdef __BORLANDC__
20665 _RTLENTRYF
20666 #endif
20667 prof_total_cmp(s1, s2)
20668 const void *s1;
20669 const void *s2;
20671 ufunc_T *p1, *p2;
20673 p1 = *(ufunc_T **)s1;
20674 p2 = *(ufunc_T **)s2;
20675 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
20679 * Compare function for self time sorting.
20681 static int
20682 #ifdef __BORLANDC__
20683 _RTLENTRYF
20684 #endif
20685 prof_self_cmp(s1, s2)
20686 const void *s1;
20687 const void *s2;
20689 ufunc_T *p1, *p2;
20691 p1 = *(ufunc_T **)s1;
20692 p2 = *(ufunc_T **)s2;
20693 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
20696 #endif
20699 * If "name" has a package name try autoloading the script for it.
20700 * Return TRUE if a package was loaded.
20702 static int
20703 script_autoload(name, reload)
20704 char_u *name;
20705 int reload; /* load script again when already loaded */
20707 char_u *p;
20708 char_u *scriptname, *tofree;
20709 int ret = FALSE;
20710 int i;
20712 /* If there is no '#' after name[0] there is no package name. */
20713 p = vim_strchr(name, AUTOLOAD_CHAR);
20714 if (p == NULL || p == name)
20715 return FALSE;
20717 tofree = scriptname = autoload_name(name);
20719 /* Find the name in the list of previously loaded package names. Skip
20720 * "autoload/", it's always the same. */
20721 for (i = 0; i < ga_loaded.ga_len; ++i)
20722 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
20723 break;
20724 if (!reload && i < ga_loaded.ga_len)
20725 ret = FALSE; /* was loaded already */
20726 else
20728 /* Remember the name if it wasn't loaded already. */
20729 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
20731 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
20732 tofree = NULL;
20735 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
20736 if (source_runtime(scriptname, FALSE) == OK)
20737 ret = TRUE;
20740 vim_free(tofree);
20741 return ret;
20745 * Return the autoload script name for a function or variable name.
20746 * Returns NULL when out of memory.
20748 static char_u *
20749 autoload_name(name)
20750 char_u *name;
20752 char_u *p;
20753 char_u *scriptname;
20755 /* Get the script file name: replace '#' with '/', append ".vim". */
20756 scriptname = alloc((unsigned)(STRLEN(name) + 14));
20757 if (scriptname == NULL)
20758 return FALSE;
20759 STRCPY(scriptname, "autoload/");
20760 STRCAT(scriptname, name);
20761 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
20762 STRCAT(scriptname, ".vim");
20763 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
20764 *p = '/';
20765 return scriptname;
20768 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
20771 * Function given to ExpandGeneric() to obtain the list of user defined
20772 * function names.
20774 char_u *
20775 get_user_func_name(xp, idx)
20776 expand_T *xp;
20777 int idx;
20779 static long_u done;
20780 static hashitem_T *hi;
20781 ufunc_T *fp;
20783 if (idx == 0)
20785 done = 0;
20786 hi = func_hashtab.ht_array;
20788 if (done < func_hashtab.ht_used)
20790 if (done++ > 0)
20791 ++hi;
20792 while (HASHITEM_EMPTY(hi))
20793 ++hi;
20794 fp = HI2UF(hi);
20796 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
20797 return fp->uf_name; /* prevents overflow */
20799 cat_func_name(IObuff, fp);
20800 if (xp->xp_context != EXPAND_USER_FUNC)
20802 STRCAT(IObuff, "(");
20803 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
20804 STRCAT(IObuff, ")");
20806 return IObuff;
20808 return NULL;
20811 #endif /* FEAT_CMDL_COMPL */
20814 * Copy the function name of "fp" to buffer "buf".
20815 * "buf" must be able to hold the function name plus three bytes.
20816 * Takes care of script-local function names.
20818 static void
20819 cat_func_name(buf, fp)
20820 char_u *buf;
20821 ufunc_T *fp;
20823 if (fp->uf_name[0] == K_SPECIAL)
20825 STRCPY(buf, "<SNR>");
20826 STRCAT(buf, fp->uf_name + 3);
20828 else
20829 STRCPY(buf, fp->uf_name);
20833 * ":delfunction {name}"
20835 void
20836 ex_delfunction(eap)
20837 exarg_T *eap;
20839 ufunc_T *fp = NULL;
20840 char_u *p;
20841 char_u *name;
20842 funcdict_T fudi;
20844 p = eap->arg;
20845 name = trans_function_name(&p, eap->skip, 0, &fudi);
20846 vim_free(fudi.fd_newkey);
20847 if (name == NULL)
20849 if (fudi.fd_dict != NULL && !eap->skip)
20850 EMSG(_(e_funcref));
20851 return;
20853 if (!ends_excmd(*skipwhite(p)))
20855 vim_free(name);
20856 EMSG(_(e_trailing));
20857 return;
20859 eap->nextcmd = check_nextcmd(p);
20860 if (eap->nextcmd != NULL)
20861 *p = NUL;
20863 if (!eap->skip)
20864 fp = find_func(name);
20865 vim_free(name);
20867 if (!eap->skip)
20869 if (fp == NULL)
20871 EMSG2(_(e_nofunc), eap->arg);
20872 return;
20874 if (fp->uf_calls > 0)
20876 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
20877 return;
20880 if (fudi.fd_dict != NULL)
20882 /* Delete the dict item that refers to the function, it will
20883 * invoke func_unref() and possibly delete the function. */
20884 dictitem_remove(fudi.fd_dict, fudi.fd_di);
20886 else
20887 func_free(fp);
20892 * Free a function and remove it from the list of functions.
20894 static void
20895 func_free(fp)
20896 ufunc_T *fp;
20898 hashitem_T *hi;
20900 /* clear this function */
20901 ga_clear_strings(&(fp->uf_args));
20902 ga_clear_strings(&(fp->uf_lines));
20903 #ifdef FEAT_PROFILE
20904 vim_free(fp->uf_tml_count);
20905 vim_free(fp->uf_tml_total);
20906 vim_free(fp->uf_tml_self);
20907 #endif
20909 /* remove the function from the function hashtable */
20910 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
20911 if (HASHITEM_EMPTY(hi))
20912 EMSG2(_(e_intern2), "func_free()");
20913 else
20914 hash_remove(&func_hashtab, hi);
20916 vim_free(fp);
20920 * Unreference a Function: decrement the reference count and free it when it
20921 * becomes zero. Only for numbered functions.
20923 static void
20924 func_unref(name)
20925 char_u *name;
20927 ufunc_T *fp;
20929 if (name != NULL && isdigit(*name))
20931 fp = find_func(name);
20932 if (fp == NULL)
20933 EMSG2(_(e_intern2), "func_unref()");
20934 else if (--fp->uf_refcount <= 0)
20936 /* Only delete it when it's not being used. Otherwise it's done
20937 * when "uf_calls" becomes zero. */
20938 if (fp->uf_calls == 0)
20939 func_free(fp);
20945 * Count a reference to a Function.
20947 static void
20948 func_ref(name)
20949 char_u *name;
20951 ufunc_T *fp;
20953 if (name != NULL && isdigit(*name))
20955 fp = find_func(name);
20956 if (fp == NULL)
20957 EMSG2(_(e_intern2), "func_ref()");
20958 else
20959 ++fp->uf_refcount;
20964 * Call a user function.
20966 static void
20967 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
20968 ufunc_T *fp; /* pointer to function */
20969 int argcount; /* nr of args */
20970 typval_T *argvars; /* arguments */
20971 typval_T *rettv; /* return value */
20972 linenr_T firstline; /* first line of range */
20973 linenr_T lastline; /* last line of range */
20974 dict_T *selfdict; /* Dictionary for "self" */
20976 char_u *save_sourcing_name;
20977 linenr_T save_sourcing_lnum;
20978 scid_T save_current_SID;
20979 funccall_T fc;
20980 int save_did_emsg;
20981 static int depth = 0;
20982 dictitem_T *v;
20983 int fixvar_idx = 0; /* index in fixvar[] */
20984 int i;
20985 int ai;
20986 char_u numbuf[NUMBUFLEN];
20987 char_u *name;
20988 #ifdef FEAT_PROFILE
20989 proftime_T wait_start;
20990 proftime_T call_start;
20991 #endif
20993 /* If depth of calling is getting too high, don't execute the function */
20994 if (depth >= p_mfd)
20996 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
20997 rettv->v_type = VAR_NUMBER;
20998 rettv->vval.v_number = -1;
20999 return;
21001 ++depth;
21003 line_breakcheck(); /* check for CTRL-C hit */
21005 fc.caller = current_funccal;
21006 current_funccal = &fc;
21007 fc.func = fp;
21008 fc.rettv = rettv;
21009 rettv->vval.v_number = 0;
21010 fc.linenr = 0;
21011 fc.returned = FALSE;
21012 fc.level = ex_nesting_level;
21013 /* Check if this function has a breakpoint. */
21014 fc.breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
21015 fc.dbg_tick = debug_tick;
21018 * Note about using fc.fixvar[]: This is an array of FIXVAR_CNT variables
21019 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
21020 * each argument variable and saves a lot of time.
21023 * Init l: variables.
21025 init_var_dict(&fc.l_vars, &fc.l_vars_var);
21026 if (selfdict != NULL)
21028 /* Set l:self to "selfdict". Use "name" to avoid a warning from
21029 * some compiler that checks the destination size. */
21030 v = &fc.fixvar[fixvar_idx++].var;
21031 name = v->di_key;
21032 STRCPY(name, "self");
21033 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
21034 hash_add(&fc.l_vars.dv_hashtab, DI2HIKEY(v));
21035 v->di_tv.v_type = VAR_DICT;
21036 v->di_tv.v_lock = 0;
21037 v->di_tv.vval.v_dict = selfdict;
21038 ++selfdict->dv_refcount;
21042 * Init a: variables.
21043 * Set a:0 to "argcount".
21044 * Set a:000 to a list with room for the "..." arguments.
21046 init_var_dict(&fc.l_avars, &fc.l_avars_var);
21047 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "0",
21048 (varnumber_T)(argcount - fp->uf_args.ga_len));
21049 v = &fc.fixvar[fixvar_idx++].var;
21050 STRCPY(v->di_key, "000");
21051 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21052 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
21053 v->di_tv.v_type = VAR_LIST;
21054 v->di_tv.v_lock = VAR_FIXED;
21055 v->di_tv.vval.v_list = &fc.l_varlist;
21056 vim_memset(&fc.l_varlist, 0, sizeof(list_T));
21057 fc.l_varlist.lv_refcount = 99999;
21058 fc.l_varlist.lv_lock = VAR_FIXED;
21061 * Set a:firstline to "firstline" and a:lastline to "lastline".
21062 * Set a:name to named arguments.
21063 * Set a:N to the "..." arguments.
21065 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "firstline",
21066 (varnumber_T)firstline);
21067 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "lastline",
21068 (varnumber_T)lastline);
21069 for (i = 0; i < argcount; ++i)
21071 ai = i - fp->uf_args.ga_len;
21072 if (ai < 0)
21073 /* named argument a:name */
21074 name = FUNCARG(fp, i);
21075 else
21077 /* "..." argument a:1, a:2, etc. */
21078 sprintf((char *)numbuf, "%d", ai + 1);
21079 name = numbuf;
21081 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
21083 v = &fc.fixvar[fixvar_idx++].var;
21084 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21086 else
21088 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
21089 + STRLEN(name)));
21090 if (v == NULL)
21091 break;
21092 v->di_flags = DI_FLAGS_RO;
21094 STRCPY(v->di_key, name);
21095 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
21097 /* Note: the values are copied directly to avoid alloc/free.
21098 * "argvars" must have VAR_FIXED for v_lock. */
21099 v->di_tv = argvars[i];
21100 v->di_tv.v_lock = VAR_FIXED;
21102 if (ai >= 0 && ai < MAX_FUNC_ARGS)
21104 list_append(&fc.l_varlist, &fc.l_listitems[ai]);
21105 fc.l_listitems[ai].li_tv = argvars[i];
21106 fc.l_listitems[ai].li_tv.v_lock = VAR_FIXED;
21110 /* Don't redraw while executing the function. */
21111 ++RedrawingDisabled;
21112 save_sourcing_name = sourcing_name;
21113 save_sourcing_lnum = sourcing_lnum;
21114 sourcing_lnum = 1;
21115 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
21116 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
21117 if (sourcing_name != NULL)
21119 if (save_sourcing_name != NULL
21120 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
21121 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
21122 else
21123 STRCPY(sourcing_name, "function ");
21124 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
21126 if (p_verbose >= 12)
21128 ++no_wait_return;
21129 verbose_enter_scroll();
21131 smsg((char_u *)_("calling %s"), sourcing_name);
21132 if (p_verbose >= 14)
21134 char_u buf[MSG_BUF_LEN];
21135 char_u numbuf2[NUMBUFLEN];
21136 char_u *tofree;
21137 char_u *s;
21139 msg_puts((char_u *)"(");
21140 for (i = 0; i < argcount; ++i)
21142 if (i > 0)
21143 msg_puts((char_u *)", ");
21144 if (argvars[i].v_type == VAR_NUMBER)
21145 msg_outnum((long)argvars[i].vval.v_number);
21146 else
21148 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
21149 if (s != NULL)
21151 trunc_string(s, buf, MSG_BUF_CLEN);
21152 msg_puts(buf);
21153 vim_free(tofree);
21157 msg_puts((char_u *)")");
21159 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21161 verbose_leave_scroll();
21162 --no_wait_return;
21165 #ifdef FEAT_PROFILE
21166 if (do_profiling == PROF_YES)
21168 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
21169 func_do_profile(fp);
21170 if (fp->uf_profiling
21171 || (fc.caller != NULL && &fc.caller->func->uf_profiling))
21173 ++fp->uf_tm_count;
21174 profile_start(&call_start);
21175 profile_zero(&fp->uf_tm_children);
21177 script_prof_save(&wait_start);
21179 #endif
21181 save_current_SID = current_SID;
21182 current_SID = fp->uf_script_ID;
21183 save_did_emsg = did_emsg;
21184 did_emsg = FALSE;
21186 /* call do_cmdline() to execute the lines */
21187 do_cmdline(NULL, get_func_line, (void *)&fc,
21188 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
21190 --RedrawingDisabled;
21192 /* when the function was aborted because of an error, return -1 */
21193 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
21195 clear_tv(rettv);
21196 rettv->v_type = VAR_NUMBER;
21197 rettv->vval.v_number = -1;
21200 #ifdef FEAT_PROFILE
21201 if (do_profiling == PROF_YES && (fp->uf_profiling
21202 || (fc.caller != NULL && &fc.caller->func->uf_profiling)))
21204 profile_end(&call_start);
21205 profile_sub_wait(&wait_start, &call_start);
21206 profile_add(&fp->uf_tm_total, &call_start);
21207 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
21208 if (fc.caller != NULL && &fc.caller->func->uf_profiling)
21210 profile_add(&fc.caller->func->uf_tm_children, &call_start);
21211 profile_add(&fc.caller->func->uf_tml_children, &call_start);
21214 #endif
21216 /* when being verbose, mention the return value */
21217 if (p_verbose >= 12)
21219 ++no_wait_return;
21220 verbose_enter_scroll();
21222 if (aborting())
21223 smsg((char_u *)_("%s aborted"), sourcing_name);
21224 else if (fc.rettv->v_type == VAR_NUMBER)
21225 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
21226 (long)fc.rettv->vval.v_number);
21227 else
21229 char_u buf[MSG_BUF_LEN];
21230 char_u numbuf2[NUMBUFLEN];
21231 char_u *tofree;
21232 char_u *s;
21234 /* The value may be very long. Skip the middle part, so that we
21235 * have some idea how it starts and ends. smsg() would always
21236 * truncate it at the end. */
21237 s = tv2string(fc.rettv, &tofree, numbuf2, 0);
21238 if (s != NULL)
21240 trunc_string(s, buf, MSG_BUF_CLEN);
21241 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
21242 vim_free(tofree);
21245 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21247 verbose_leave_scroll();
21248 --no_wait_return;
21251 vim_free(sourcing_name);
21252 sourcing_name = save_sourcing_name;
21253 sourcing_lnum = save_sourcing_lnum;
21254 current_SID = save_current_SID;
21255 #ifdef FEAT_PROFILE
21256 if (do_profiling == PROF_YES)
21257 script_prof_restore(&wait_start);
21258 #endif
21260 if (p_verbose >= 12 && sourcing_name != NULL)
21262 ++no_wait_return;
21263 verbose_enter_scroll();
21265 smsg((char_u *)_("continuing in %s"), sourcing_name);
21266 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21268 verbose_leave_scroll();
21269 --no_wait_return;
21272 did_emsg |= save_did_emsg;
21273 current_funccal = fc.caller;
21275 /* The a: variables typevals were not allocated, only free the allocated
21276 * variables. */
21277 vars_clear_ext(&fc.l_avars.dv_hashtab, FALSE);
21279 vars_clear(&fc.l_vars.dv_hashtab); /* free all l: variables */
21280 --depth;
21284 * Add a number variable "name" to dict "dp" with value "nr".
21286 static void
21287 add_nr_var(dp, v, name, nr)
21288 dict_T *dp;
21289 dictitem_T *v;
21290 char *name;
21291 varnumber_T nr;
21293 STRCPY(v->di_key, name);
21294 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21295 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
21296 v->di_tv.v_type = VAR_NUMBER;
21297 v->di_tv.v_lock = VAR_FIXED;
21298 v->di_tv.vval.v_number = nr;
21302 * ":return [expr]"
21304 void
21305 ex_return(eap)
21306 exarg_T *eap;
21308 char_u *arg = eap->arg;
21309 typval_T rettv;
21310 int returning = FALSE;
21312 if (current_funccal == NULL)
21314 EMSG(_("E133: :return not inside a function"));
21315 return;
21318 if (eap->skip)
21319 ++emsg_skip;
21321 eap->nextcmd = NULL;
21322 if ((*arg != NUL && *arg != '|' && *arg != '\n')
21323 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
21325 if (!eap->skip)
21326 returning = do_return(eap, FALSE, TRUE, &rettv);
21327 else
21328 clear_tv(&rettv);
21330 /* It's safer to return also on error. */
21331 else if (!eap->skip)
21334 * Return unless the expression evaluation has been cancelled due to an
21335 * aborting error, an interrupt, or an exception.
21337 if (!aborting())
21338 returning = do_return(eap, FALSE, TRUE, NULL);
21341 /* When skipping or the return gets pending, advance to the next command
21342 * in this line (!returning). Otherwise, ignore the rest of the line.
21343 * Following lines will be ignored by get_func_line(). */
21344 if (returning)
21345 eap->nextcmd = NULL;
21346 else if (eap->nextcmd == NULL) /* no argument */
21347 eap->nextcmd = check_nextcmd(arg);
21349 if (eap->skip)
21350 --emsg_skip;
21354 * Return from a function. Possibly makes the return pending. Also called
21355 * for a pending return at the ":endtry" or after returning from an extra
21356 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
21357 * when called due to a ":return" command. "rettv" may point to a typval_T
21358 * with the return rettv. Returns TRUE when the return can be carried out,
21359 * FALSE when the return gets pending.
21362 do_return(eap, reanimate, is_cmd, rettv)
21363 exarg_T *eap;
21364 int reanimate;
21365 int is_cmd;
21366 void *rettv;
21368 int idx;
21369 struct condstack *cstack = eap->cstack;
21371 if (reanimate)
21372 /* Undo the return. */
21373 current_funccal->returned = FALSE;
21376 * Cleanup (and inactivate) conditionals, but stop when a try conditional
21377 * not in its finally clause (which then is to be executed next) is found.
21378 * In this case, make the ":return" pending for execution at the ":endtry".
21379 * Otherwise, return normally.
21381 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
21382 if (idx >= 0)
21384 cstack->cs_pending[idx] = CSTP_RETURN;
21386 if (!is_cmd && !reanimate)
21387 /* A pending return again gets pending. "rettv" points to an
21388 * allocated variable with the rettv of the original ":return"'s
21389 * argument if present or is NULL else. */
21390 cstack->cs_rettv[idx] = rettv;
21391 else
21393 /* When undoing a return in order to make it pending, get the stored
21394 * return rettv. */
21395 if (reanimate)
21396 rettv = current_funccal->rettv;
21398 if (rettv != NULL)
21400 /* Store the value of the pending return. */
21401 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
21402 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
21403 else
21404 EMSG(_(e_outofmem));
21406 else
21407 cstack->cs_rettv[idx] = NULL;
21409 if (reanimate)
21411 /* The pending return value could be overwritten by a ":return"
21412 * without argument in a finally clause; reset the default
21413 * return value. */
21414 current_funccal->rettv->v_type = VAR_NUMBER;
21415 current_funccal->rettv->vval.v_number = 0;
21418 report_make_pending(CSTP_RETURN, rettv);
21420 else
21422 current_funccal->returned = TRUE;
21424 /* If the return is carried out now, store the return value. For
21425 * a return immediately after reanimation, the value is already
21426 * there. */
21427 if (!reanimate && rettv != NULL)
21429 clear_tv(current_funccal->rettv);
21430 *current_funccal->rettv = *(typval_T *)rettv;
21431 if (!is_cmd)
21432 vim_free(rettv);
21436 return idx < 0;
21440 * Free the variable with a pending return value.
21442 void
21443 discard_pending_return(rettv)
21444 void *rettv;
21446 free_tv((typval_T *)rettv);
21450 * Generate a return command for producing the value of "rettv". The result
21451 * is an allocated string. Used by report_pending() for verbose messages.
21453 char_u *
21454 get_return_cmd(rettv)
21455 void *rettv;
21457 char_u *s = NULL;
21458 char_u *tofree = NULL;
21459 char_u numbuf[NUMBUFLEN];
21461 if (rettv != NULL)
21462 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
21463 if (s == NULL)
21464 s = (char_u *)"";
21466 STRCPY(IObuff, ":return ");
21467 STRNCPY(IObuff + 8, s, IOSIZE - 8);
21468 if (STRLEN(s) + 8 >= IOSIZE)
21469 STRCPY(IObuff + IOSIZE - 4, "...");
21470 vim_free(tofree);
21471 return vim_strsave(IObuff);
21475 * Get next function line.
21476 * Called by do_cmdline() to get the next line.
21477 * Returns allocated string, or NULL for end of function.
21479 /* ARGSUSED */
21480 char_u *
21481 get_func_line(c, cookie, indent)
21482 int c; /* not used */
21483 void *cookie;
21484 int indent; /* not used */
21486 funccall_T *fcp = (funccall_T *)cookie;
21487 ufunc_T *fp = fcp->func;
21488 char_u *retval;
21489 garray_T *gap; /* growarray with function lines */
21491 /* If breakpoints have been added/deleted need to check for it. */
21492 if (fcp->dbg_tick != debug_tick)
21494 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21495 sourcing_lnum);
21496 fcp->dbg_tick = debug_tick;
21498 #ifdef FEAT_PROFILE
21499 if (do_profiling == PROF_YES)
21500 func_line_end(cookie);
21501 #endif
21503 gap = &fp->uf_lines;
21504 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21505 || fcp->returned)
21506 retval = NULL;
21507 else
21509 /* Skip NULL lines (continuation lines). */
21510 while (fcp->linenr < gap->ga_len
21511 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
21512 ++fcp->linenr;
21513 if (fcp->linenr >= gap->ga_len)
21514 retval = NULL;
21515 else
21517 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
21518 sourcing_lnum = fcp->linenr;
21519 #ifdef FEAT_PROFILE
21520 if (do_profiling == PROF_YES)
21521 func_line_start(cookie);
21522 #endif
21526 /* Did we encounter a breakpoint? */
21527 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
21529 dbg_breakpoint(fp->uf_name, sourcing_lnum);
21530 /* Find next breakpoint. */
21531 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21532 sourcing_lnum);
21533 fcp->dbg_tick = debug_tick;
21536 return retval;
21539 #if defined(FEAT_PROFILE) || defined(PROTO)
21541 * Called when starting to read a function line.
21542 * "sourcing_lnum" must be correct!
21543 * When skipping lines it may not actually be executed, but we won't find out
21544 * until later and we need to store the time now.
21546 void
21547 func_line_start(cookie)
21548 void *cookie;
21550 funccall_T *fcp = (funccall_T *)cookie;
21551 ufunc_T *fp = fcp->func;
21553 if (fp->uf_profiling && sourcing_lnum >= 1
21554 && sourcing_lnum <= fp->uf_lines.ga_len)
21556 fp->uf_tml_idx = sourcing_lnum - 1;
21557 /* Skip continuation lines. */
21558 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
21559 --fp->uf_tml_idx;
21560 fp->uf_tml_execed = FALSE;
21561 profile_start(&fp->uf_tml_start);
21562 profile_zero(&fp->uf_tml_children);
21563 profile_get_wait(&fp->uf_tml_wait);
21568 * Called when actually executing a function line.
21570 void
21571 func_line_exec(cookie)
21572 void *cookie;
21574 funccall_T *fcp = (funccall_T *)cookie;
21575 ufunc_T *fp = fcp->func;
21577 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21578 fp->uf_tml_execed = TRUE;
21582 * Called when done with a function line.
21584 void
21585 func_line_end(cookie)
21586 void *cookie;
21588 funccall_T *fcp = (funccall_T *)cookie;
21589 ufunc_T *fp = fcp->func;
21591 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21593 if (fp->uf_tml_execed)
21595 ++fp->uf_tml_count[fp->uf_tml_idx];
21596 profile_end(&fp->uf_tml_start);
21597 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
21598 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
21599 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
21600 &fp->uf_tml_children);
21602 fp->uf_tml_idx = -1;
21605 #endif
21608 * Return TRUE if the currently active function should be ended, because a
21609 * return was encountered or an error occurred. Used inside a ":while".
21612 func_has_ended(cookie)
21613 void *cookie;
21615 funccall_T *fcp = (funccall_T *)cookie;
21617 /* Ignore the "abort" flag if the abortion behavior has been changed due to
21618 * an error inside a try conditional. */
21619 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21620 || fcp->returned);
21624 * return TRUE if cookie indicates a function which "abort"s on errors.
21627 func_has_abort(cookie)
21628 void *cookie;
21630 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
21633 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
21634 typedef enum
21636 VAR_FLAVOUR_DEFAULT, /* doesn't start with uppercase */
21637 VAR_FLAVOUR_SESSION, /* starts with uppercase, some lower */
21638 VAR_FLAVOUR_VIMINFO /* all uppercase */
21639 } var_flavour_T;
21641 static var_flavour_T var_flavour __ARGS((char_u *varname));
21643 static var_flavour_T
21644 var_flavour(varname)
21645 char_u *varname;
21647 char_u *p = varname;
21649 if (ASCII_ISUPPER(*p))
21651 while (*(++p))
21652 if (ASCII_ISLOWER(*p))
21653 return VAR_FLAVOUR_SESSION;
21654 return VAR_FLAVOUR_VIMINFO;
21656 else
21657 return VAR_FLAVOUR_DEFAULT;
21659 #endif
21661 #if defined(FEAT_VIMINFO) || defined(PROTO)
21663 * Restore global vars that start with a capital from the viminfo file
21666 read_viminfo_varlist(virp, writing)
21667 vir_T *virp;
21668 int writing;
21670 char_u *tab;
21671 int type = VAR_NUMBER;
21672 typval_T tv;
21674 if (!writing && (find_viminfo_parameter('!') != NULL))
21676 tab = vim_strchr(virp->vir_line + 1, '\t');
21677 if (tab != NULL)
21679 *tab++ = '\0'; /* isolate the variable name */
21680 if (*tab == 'S') /* string var */
21681 type = VAR_STRING;
21682 #ifdef FEAT_FLOAT
21683 else if (*tab == 'F')
21684 type = VAR_FLOAT;
21685 #endif
21687 tab = vim_strchr(tab, '\t');
21688 if (tab != NULL)
21690 tv.v_type = type;
21691 if (type == VAR_STRING)
21692 tv.vval.v_string = viminfo_readstring(virp,
21693 (int)(tab - virp->vir_line + 1), TRUE);
21694 #ifdef FEAT_FLOAT
21695 else if (type == VAR_FLOAT)
21696 (void)string2float(tab + 1, &tv.vval.v_float);
21697 #endif
21698 else
21699 tv.vval.v_number = atol((char *)tab + 1);
21700 set_var(virp->vir_line + 1, &tv, FALSE);
21701 if (type == VAR_STRING)
21702 vim_free(tv.vval.v_string);
21707 return viminfo_readline(virp);
21711 * Write global vars that start with a capital to the viminfo file
21713 void
21714 write_viminfo_varlist(fp)
21715 FILE *fp;
21717 hashitem_T *hi;
21718 dictitem_T *this_var;
21719 int todo;
21720 char *s;
21721 char_u *p;
21722 char_u *tofree;
21723 char_u numbuf[NUMBUFLEN];
21725 if (find_viminfo_parameter('!') == NULL)
21726 return;
21728 fprintf(fp, _("\n# global variables:\n"));
21730 todo = (int)globvarht.ht_used;
21731 for (hi = globvarht.ht_array; todo > 0; ++hi)
21733 if (!HASHITEM_EMPTY(hi))
21735 --todo;
21736 this_var = HI2DI(hi);
21737 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
21739 switch (this_var->di_tv.v_type)
21741 case VAR_STRING: s = "STR"; break;
21742 case VAR_NUMBER: s = "NUM"; break;
21743 #ifdef FEAT_FLOAT
21744 case VAR_FLOAT: s = "FLO"; break;
21745 #endif
21746 default: continue;
21748 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
21749 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
21750 if (p != NULL)
21751 viminfo_writestring(fp, p);
21752 vim_free(tofree);
21757 #endif
21759 #if defined(FEAT_SESSION) || defined(PROTO)
21761 store_session_globals(fd)
21762 FILE *fd;
21764 hashitem_T *hi;
21765 dictitem_T *this_var;
21766 int todo;
21767 char_u *p, *t;
21769 todo = (int)globvarht.ht_used;
21770 for (hi = globvarht.ht_array; todo > 0; ++hi)
21772 if (!HASHITEM_EMPTY(hi))
21774 --todo;
21775 this_var = HI2DI(hi);
21776 if ((this_var->di_tv.v_type == VAR_NUMBER
21777 || this_var->di_tv.v_type == VAR_STRING)
21778 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
21780 /* Escape special characters with a backslash. Turn a LF and
21781 * CR into \n and \r. */
21782 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
21783 (char_u *)"\\\"\n\r");
21784 if (p == NULL) /* out of memory */
21785 break;
21786 for (t = p; *t != NUL; ++t)
21787 if (*t == '\n')
21788 *t = 'n';
21789 else if (*t == '\r')
21790 *t = 'r';
21791 if ((fprintf(fd, "let %s = %c%s%c",
21792 this_var->di_key,
21793 (this_var->di_tv.v_type == VAR_STRING) ? '"'
21794 : ' ',
21796 (this_var->di_tv.v_type == VAR_STRING) ? '"'
21797 : ' ') < 0)
21798 || put_eol(fd) == FAIL)
21800 vim_free(p);
21801 return FAIL;
21803 vim_free(p);
21805 #ifdef FEAT_FLOAT
21806 else if (this_var->di_tv.v_type == VAR_FLOAT
21807 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
21809 float_T f = this_var->di_tv.vval.v_float;
21810 int sign = ' ';
21812 if (f < 0)
21814 f = -f;
21815 sign = '-';
21817 if ((fprintf(fd, "let %s = %c&%f",
21818 this_var->di_key, sign, f) < 0)
21819 || put_eol(fd) == FAIL)
21820 return FAIL;
21822 #endif
21825 return OK;
21827 #endif
21830 * Display script name where an item was last set.
21831 * Should only be invoked when 'verbose' is non-zero.
21833 void
21834 last_set_msg(scriptID)
21835 scid_T scriptID;
21837 char_u *p;
21839 if (scriptID != 0)
21841 p = home_replace_save(NULL, get_scriptname(scriptID));
21842 if (p != NULL)
21844 verbose_enter();
21845 MSG_PUTS(_("\n\tLast set from "));
21846 MSG_PUTS(p);
21847 vim_free(p);
21848 verbose_leave();
21853 #endif /* FEAT_EVAL */
21856 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
21858 #ifdef WIN3264
21860 * Functions for ":8" filename modifier: get 8.3 version of a filename.
21862 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
21863 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
21864 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
21867 * Get the short path (8.3) for the filename in "fnamep".
21868 * Only works for a valid file name.
21869 * When the path gets longer "fnamep" is changed and the allocated buffer
21870 * is put in "bufp".
21871 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
21872 * Returns OK on success, FAIL on failure.
21874 static int
21875 get_short_pathname(fnamep, bufp, fnamelen)
21876 char_u **fnamep;
21877 char_u **bufp;
21878 int *fnamelen;
21880 int l, len;
21881 char_u *newbuf;
21883 len = *fnamelen;
21884 l = GetShortPathName(*fnamep, *fnamep, len);
21885 if (l > len - 1)
21887 /* If that doesn't work (not enough space), then save the string
21888 * and try again with a new buffer big enough. */
21889 newbuf = vim_strnsave(*fnamep, l);
21890 if (newbuf == NULL)
21891 return FAIL;
21893 vim_free(*bufp);
21894 *fnamep = *bufp = newbuf;
21896 /* Really should always succeed, as the buffer is big enough. */
21897 l = GetShortPathName(*fnamep, *fnamep, l+1);
21900 *fnamelen = l;
21901 return OK;
21905 * Get the short path (8.3) for the filename in "fname". The converted
21906 * path is returned in "bufp".
21908 * Some of the directories specified in "fname" may not exist. This function
21909 * will shorten the existing directories at the beginning of the path and then
21910 * append the remaining non-existing path.
21912 * fname - Pointer to the filename to shorten. On return, contains the
21913 * pointer to the shortened pathname
21914 * bufp - Pointer to an allocated buffer for the filename.
21915 * fnamelen - Length of the filename pointed to by fname
21917 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
21919 static int
21920 shortpath_for_invalid_fname(fname, bufp, fnamelen)
21921 char_u **fname;
21922 char_u **bufp;
21923 int *fnamelen;
21925 char_u *short_fname, *save_fname, *pbuf_unused;
21926 char_u *endp, *save_endp;
21927 char_u ch;
21928 int old_len, len;
21929 int new_len, sfx_len;
21930 int retval = OK;
21932 /* Make a copy */
21933 old_len = *fnamelen;
21934 save_fname = vim_strnsave(*fname, old_len);
21935 pbuf_unused = NULL;
21936 short_fname = NULL;
21938 endp = save_fname + old_len - 1; /* Find the end of the copy */
21939 save_endp = endp;
21942 * Try shortening the supplied path till it succeeds by removing one
21943 * directory at a time from the tail of the path.
21945 len = 0;
21946 for (;;)
21948 /* go back one path-separator */
21949 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
21950 --endp;
21951 if (endp <= save_fname)
21952 break; /* processed the complete path */
21955 * Replace the path separator with a NUL and try to shorten the
21956 * resulting path.
21958 ch = *endp;
21959 *endp = 0;
21960 short_fname = save_fname;
21961 len = STRLEN(short_fname) + 1;
21962 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
21964 retval = FAIL;
21965 goto theend;
21967 *endp = ch; /* preserve the string */
21969 if (len > 0)
21970 break; /* successfully shortened the path */
21972 /* failed to shorten the path. Skip the path separator */
21973 --endp;
21976 if (len > 0)
21979 * Succeeded in shortening the path. Now concatenate the shortened
21980 * path with the remaining path at the tail.
21983 /* Compute the length of the new path. */
21984 sfx_len = (int)(save_endp - endp) + 1;
21985 new_len = len + sfx_len;
21987 *fnamelen = new_len;
21988 vim_free(*bufp);
21989 if (new_len > old_len)
21991 /* There is not enough space in the currently allocated string,
21992 * copy it to a buffer big enough. */
21993 *fname = *bufp = vim_strnsave(short_fname, new_len);
21994 if (*fname == NULL)
21996 retval = FAIL;
21997 goto theend;
22000 else
22002 /* Transfer short_fname to the main buffer (it's big enough),
22003 * unless get_short_pathname() did its work in-place. */
22004 *fname = *bufp = save_fname;
22005 if (short_fname != save_fname)
22006 vim_strncpy(save_fname, short_fname, len);
22007 save_fname = NULL;
22010 /* concat the not-shortened part of the path */
22011 vim_strncpy(*fname + len, endp, sfx_len);
22012 (*fname)[new_len] = NUL;
22015 theend:
22016 vim_free(pbuf_unused);
22017 vim_free(save_fname);
22019 return retval;
22023 * Get a pathname for a partial path.
22024 * Returns OK for success, FAIL for failure.
22026 static int
22027 shortpath_for_partial(fnamep, bufp, fnamelen)
22028 char_u **fnamep;
22029 char_u **bufp;
22030 int *fnamelen;
22032 int sepcount, len, tflen;
22033 char_u *p;
22034 char_u *pbuf, *tfname;
22035 int hasTilde;
22037 /* Count up the path separators from the RHS.. so we know which part
22038 * of the path to return. */
22039 sepcount = 0;
22040 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
22041 if (vim_ispathsep(*p))
22042 ++sepcount;
22044 /* Need full path first (use expand_env() to remove a "~/") */
22045 hasTilde = (**fnamep == '~');
22046 if (hasTilde)
22047 pbuf = tfname = expand_env_save(*fnamep);
22048 else
22049 pbuf = tfname = FullName_save(*fnamep, FALSE);
22051 len = tflen = (int)STRLEN(tfname);
22053 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
22054 return FAIL;
22056 if (len == 0)
22058 /* Don't have a valid filename, so shorten the rest of the
22059 * path if we can. This CAN give us invalid 8.3 filenames, but
22060 * there's not a lot of point in guessing what it might be.
22062 len = tflen;
22063 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
22064 return FAIL;
22067 /* Count the paths backward to find the beginning of the desired string. */
22068 for (p = tfname + len - 1; p >= tfname; --p)
22070 #ifdef FEAT_MBYTE
22071 if (has_mbyte)
22072 p -= mb_head_off(tfname, p);
22073 #endif
22074 if (vim_ispathsep(*p))
22076 if (sepcount == 0 || (hasTilde && sepcount == 1))
22077 break;
22078 else
22079 sepcount --;
22082 if (hasTilde)
22084 --p;
22085 if (p >= tfname)
22086 *p = '~';
22087 else
22088 return FAIL;
22090 else
22091 ++p;
22093 /* Copy in the string - p indexes into tfname - allocated at pbuf */
22094 vim_free(*bufp);
22095 *fnamelen = (int)STRLEN(p);
22096 *bufp = pbuf;
22097 *fnamep = p;
22099 return OK;
22101 #endif /* WIN3264 */
22104 * Adjust a filename, according to a string of modifiers.
22105 * *fnamep must be NUL terminated when called. When returning, the length is
22106 * determined by *fnamelen.
22107 * Returns VALID_ flags or -1 for failure.
22108 * When there is an error, *fnamep is set to NULL.
22111 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
22112 char_u *src; /* string with modifiers */
22113 int *usedlen; /* characters after src that are used */
22114 char_u **fnamep; /* file name so far */
22115 char_u **bufp; /* buffer for allocated file name or NULL */
22116 int *fnamelen; /* length of fnamep */
22118 int valid = 0;
22119 char_u *tail;
22120 char_u *s, *p, *pbuf;
22121 char_u dirname[MAXPATHL];
22122 int c;
22123 int has_fullname = 0;
22124 #ifdef WIN3264
22125 int has_shortname = 0;
22126 #endif
22128 repeat:
22129 /* ":p" - full path/file_name */
22130 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
22132 has_fullname = 1;
22134 valid |= VALID_PATH;
22135 *usedlen += 2;
22137 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
22138 if ((*fnamep)[0] == '~'
22139 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
22140 && ((*fnamep)[1] == '/'
22141 # ifdef BACKSLASH_IN_FILENAME
22142 || (*fnamep)[1] == '\\'
22143 # endif
22144 || (*fnamep)[1] == NUL)
22146 #endif
22149 *fnamep = expand_env_save(*fnamep);
22150 vim_free(*bufp); /* free any allocated file name */
22151 *bufp = *fnamep;
22152 if (*fnamep == NULL)
22153 return -1;
22156 /* When "/." or "/.." is used: force expansion to get rid of it. */
22157 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
22159 if (vim_ispathsep(*p)
22160 && p[1] == '.'
22161 && (p[2] == NUL
22162 || vim_ispathsep(p[2])
22163 || (p[2] == '.'
22164 && (p[3] == NUL || vim_ispathsep(p[3])))))
22165 break;
22168 /* FullName_save() is slow, don't use it when not needed. */
22169 if (*p != NUL || !vim_isAbsName(*fnamep))
22171 *fnamep = FullName_save(*fnamep, *p != NUL);
22172 vim_free(*bufp); /* free any allocated file name */
22173 *bufp = *fnamep;
22174 if (*fnamep == NULL)
22175 return -1;
22178 /* Append a path separator to a directory. */
22179 if (mch_isdir(*fnamep))
22181 /* Make room for one or two extra characters. */
22182 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
22183 vim_free(*bufp); /* free any allocated file name */
22184 *bufp = *fnamep;
22185 if (*fnamep == NULL)
22186 return -1;
22187 add_pathsep(*fnamep);
22191 /* ":." - path relative to the current directory */
22192 /* ":~" - path relative to the home directory */
22193 /* ":8" - shortname path - postponed till after */
22194 while (src[*usedlen] == ':'
22195 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
22197 *usedlen += 2;
22198 if (c == '8')
22200 #ifdef WIN3264
22201 has_shortname = 1; /* Postpone this. */
22202 #endif
22203 continue;
22205 pbuf = NULL;
22206 /* Need full path first (use expand_env() to remove a "~/") */
22207 if (!has_fullname)
22209 if (c == '.' && **fnamep == '~')
22210 p = pbuf = expand_env_save(*fnamep);
22211 else
22212 p = pbuf = FullName_save(*fnamep, FALSE);
22214 else
22215 p = *fnamep;
22217 has_fullname = 0;
22219 if (p != NULL)
22221 if (c == '.')
22223 mch_dirname(dirname, MAXPATHL);
22224 s = shorten_fname(p, dirname);
22225 if (s != NULL)
22227 *fnamep = s;
22228 if (pbuf != NULL)
22230 vim_free(*bufp); /* free any allocated file name */
22231 *bufp = pbuf;
22232 pbuf = NULL;
22236 else
22238 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
22239 /* Only replace it when it starts with '~' */
22240 if (*dirname == '~')
22242 s = vim_strsave(dirname);
22243 if (s != NULL)
22245 *fnamep = s;
22246 vim_free(*bufp);
22247 *bufp = s;
22251 vim_free(pbuf);
22255 tail = gettail(*fnamep);
22256 *fnamelen = (int)STRLEN(*fnamep);
22258 /* ":h" - head, remove "/file_name", can be repeated */
22259 /* Don't remove the first "/" or "c:\" */
22260 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
22262 valid |= VALID_HEAD;
22263 *usedlen += 2;
22264 s = get_past_head(*fnamep);
22265 while (tail > s && after_pathsep(s, tail))
22266 mb_ptr_back(*fnamep, tail);
22267 *fnamelen = (int)(tail - *fnamep);
22268 #ifdef VMS
22269 if (*fnamelen > 0)
22270 *fnamelen += 1; /* the path separator is part of the path */
22271 #endif
22272 if (*fnamelen == 0)
22274 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
22275 p = vim_strsave((char_u *)".");
22276 if (p == NULL)
22277 return -1;
22278 vim_free(*bufp);
22279 *bufp = *fnamep = tail = p;
22280 *fnamelen = 1;
22282 else
22284 while (tail > s && !after_pathsep(s, tail))
22285 mb_ptr_back(*fnamep, tail);
22289 /* ":8" - shortname */
22290 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
22292 *usedlen += 2;
22293 #ifdef WIN3264
22294 has_shortname = 1;
22295 #endif
22298 #ifdef WIN3264
22299 /* Check shortname after we have done 'heads' and before we do 'tails'
22301 if (has_shortname)
22303 pbuf = NULL;
22304 /* Copy the string if it is shortened by :h */
22305 if (*fnamelen < (int)STRLEN(*fnamep))
22307 p = vim_strnsave(*fnamep, *fnamelen);
22308 if (p == 0)
22309 return -1;
22310 vim_free(*bufp);
22311 *bufp = *fnamep = p;
22314 /* Split into two implementations - makes it easier. First is where
22315 * there isn't a full name already, second is where there is.
22317 if (!has_fullname && !vim_isAbsName(*fnamep))
22319 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
22320 return -1;
22322 else
22324 int l;
22326 /* Simple case, already have the full-name
22327 * Nearly always shorter, so try first time. */
22328 l = *fnamelen;
22329 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
22330 return -1;
22332 if (l == 0)
22334 /* Couldn't find the filename.. search the paths.
22336 l = *fnamelen;
22337 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
22338 return -1;
22340 *fnamelen = l;
22343 #endif /* WIN3264 */
22345 /* ":t" - tail, just the basename */
22346 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
22348 *usedlen += 2;
22349 *fnamelen -= (int)(tail - *fnamep);
22350 *fnamep = tail;
22353 /* ":e" - extension, can be repeated */
22354 /* ":r" - root, without extension, can be repeated */
22355 while (src[*usedlen] == ':'
22356 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
22358 /* find a '.' in the tail:
22359 * - for second :e: before the current fname
22360 * - otherwise: The last '.'
22362 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
22363 s = *fnamep - 2;
22364 else
22365 s = *fnamep + *fnamelen - 1;
22366 for ( ; s > tail; --s)
22367 if (s[0] == '.')
22368 break;
22369 if (src[*usedlen + 1] == 'e') /* :e */
22371 if (s > tail)
22373 *fnamelen += (int)(*fnamep - (s + 1));
22374 *fnamep = s + 1;
22375 #ifdef VMS
22376 /* cut version from the extension */
22377 s = *fnamep + *fnamelen - 1;
22378 for ( ; s > *fnamep; --s)
22379 if (s[0] == ';')
22380 break;
22381 if (s > *fnamep)
22382 *fnamelen = s - *fnamep;
22383 #endif
22385 else if (*fnamep <= tail)
22386 *fnamelen = 0;
22388 else /* :r */
22390 if (s > tail) /* remove one extension */
22391 *fnamelen = (int)(s - *fnamep);
22393 *usedlen += 2;
22396 /* ":s?pat?foo?" - substitute */
22397 /* ":gs?pat?foo?" - global substitute */
22398 if (src[*usedlen] == ':'
22399 && (src[*usedlen + 1] == 's'
22400 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
22402 char_u *str;
22403 char_u *pat;
22404 char_u *sub;
22405 int sep;
22406 char_u *flags;
22407 int didit = FALSE;
22409 flags = (char_u *)"";
22410 s = src + *usedlen + 2;
22411 if (src[*usedlen + 1] == 'g')
22413 flags = (char_u *)"g";
22414 ++s;
22417 sep = *s++;
22418 if (sep)
22420 /* find end of pattern */
22421 p = vim_strchr(s, sep);
22422 if (p != NULL)
22424 pat = vim_strnsave(s, (int)(p - s));
22425 if (pat != NULL)
22427 s = p + 1;
22428 /* find end of substitution */
22429 p = vim_strchr(s, sep);
22430 if (p != NULL)
22432 sub = vim_strnsave(s, (int)(p - s));
22433 str = vim_strnsave(*fnamep, *fnamelen);
22434 if (sub != NULL && str != NULL)
22436 *usedlen = (int)(p + 1 - src);
22437 s = do_string_sub(str, pat, sub, flags);
22438 if (s != NULL)
22440 *fnamep = s;
22441 *fnamelen = (int)STRLEN(s);
22442 vim_free(*bufp);
22443 *bufp = s;
22444 didit = TRUE;
22447 vim_free(sub);
22448 vim_free(str);
22450 vim_free(pat);
22453 /* after using ":s", repeat all the modifiers */
22454 if (didit)
22455 goto repeat;
22459 return valid;
22463 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
22464 * "flags" can be "g" to do a global substitute.
22465 * Returns an allocated string, NULL for error.
22467 char_u *
22468 do_string_sub(str, pat, sub, flags)
22469 char_u *str;
22470 char_u *pat;
22471 char_u *sub;
22472 char_u *flags;
22474 int sublen;
22475 regmatch_T regmatch;
22476 int i;
22477 int do_all;
22478 char_u *tail;
22479 garray_T ga;
22480 char_u *ret;
22481 char_u *save_cpo;
22483 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
22484 save_cpo = p_cpo;
22485 p_cpo = (char_u *)"";
22487 ga_init2(&ga, 1, 200);
22489 do_all = (flags[0] == 'g');
22491 regmatch.rm_ic = p_ic;
22492 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
22493 if (regmatch.regprog != NULL)
22495 tail = str;
22496 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
22499 * Get some space for a temporary buffer to do the substitution
22500 * into. It will contain:
22501 * - The text up to where the match is.
22502 * - The substituted text.
22503 * - The text after the match.
22505 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
22506 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
22507 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
22509 ga_clear(&ga);
22510 break;
22513 /* copy the text up to where the match is */
22514 i = (int)(regmatch.startp[0] - tail);
22515 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
22516 /* add the substituted text */
22517 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
22518 + ga.ga_len + i, TRUE, TRUE, FALSE);
22519 ga.ga_len += i + sublen - 1;
22520 /* avoid getting stuck on a match with an empty string */
22521 if (tail == regmatch.endp[0])
22523 if (*tail == NUL)
22524 break;
22525 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
22526 ++ga.ga_len;
22528 else
22530 tail = regmatch.endp[0];
22531 if (*tail == NUL)
22532 break;
22534 if (!do_all)
22535 break;
22538 if (ga.ga_data != NULL)
22539 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
22541 vim_free(regmatch.regprog);
22544 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
22545 ga_clear(&ga);
22546 p_cpo = save_cpo;
22548 return ret;
22551 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */