Merged from the latest developing branch.
[MacVim.git] / src / eval.c
blob1c4f60ea9eaded4105a78f77c33a3c05b7b8b181
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(WIN16) || defined(WIN32) || defined(_WIN64)
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 */
35 #define DO_NOT_FREE_CNT 99999 /* refcount for dict or list that should not
36 be freed. */
39 * In a hashtab item "hi_key" points to "di_key" in a dictitem.
40 * This avoids adding a pointer to the hashtab item.
41 * DI2HIKEY() converts a dictitem pointer to a hashitem key pointer.
42 * HIKEY2DI() converts a hashitem key pointer to a dictitem pointer.
43 * HI2DI() converts a hashitem pointer to a dictitem pointer.
45 static dictitem_T dumdi;
46 #define DI2HIKEY(di) ((di)->di_key)
47 #define HIKEY2DI(p) ((dictitem_T *)(p - (dumdi.di_key - (char_u *)&dumdi)))
48 #define HI2DI(hi) HIKEY2DI((hi)->hi_key)
51 * Structure returned by get_lval() and used by set_var_lval().
52 * For a plain name:
53 * "name" points to the variable name.
54 * "exp_name" is NULL.
55 * "tv" is NULL
56 * For a magic braces name:
57 * "name" points to the expanded variable name.
58 * "exp_name" is non-NULL, to be freed later.
59 * "tv" is NULL
60 * For an index in a list:
61 * "name" points to the (expanded) variable name.
62 * "exp_name" NULL or non-NULL, to be freed later.
63 * "tv" points to the (first) list item value
64 * "li" points to the (first) list item
65 * "range", "n1", "n2" and "empty2" indicate what items are used.
66 * For an existing Dict item:
67 * "name" points to the (expanded) variable name.
68 * "exp_name" NULL or non-NULL, to be freed later.
69 * "tv" points to the dict item value
70 * "newkey" is NULL
71 * For a non-existing Dict item:
72 * "name" points to the (expanded) variable name.
73 * "exp_name" NULL or non-NULL, to be freed later.
74 * "tv" points to the Dictionary typval_T
75 * "newkey" is the key for the new item.
77 typedef struct lval_S
79 char_u *ll_name; /* start of variable name (can be NULL) */
80 char_u *ll_exp_name; /* NULL or expanded name in allocated memory. */
81 typval_T *ll_tv; /* Typeval of item being used. If "newkey"
82 isn't NULL it's the Dict to which to add
83 the item. */
84 listitem_T *ll_li; /* The list item or NULL. */
85 list_T *ll_list; /* The list or NULL. */
86 int ll_range; /* TRUE when a [i:j] range was used */
87 long ll_n1; /* First index for list */
88 long ll_n2; /* Second index for list range */
89 int ll_empty2; /* Second index is empty: [i:] */
90 dict_T *ll_dict; /* The Dictionary or NULL */
91 dictitem_T *ll_di; /* The dictitem or NULL */
92 char_u *ll_newkey; /* New key for Dict in alloc. mem or NULL. */
93 } lval_T;
96 static char *e_letunexp = N_("E18: Unexpected characters in :let");
97 static char *e_listidx = N_("E684: list index out of range: %ld");
98 static char *e_undefvar = N_("E121: Undefined variable: %s");
99 static char *e_missbrac = N_("E111: Missing ']'");
100 static char *e_listarg = N_("E686: Argument of %s must be a List");
101 static char *e_listdictarg = N_("E712: Argument of %s must be a List or Dictionary");
102 static char *e_emptykey = N_("E713: Cannot use empty key for Dictionary");
103 static char *e_listreq = N_("E714: List required");
104 static char *e_dictreq = N_("E715: Dictionary required");
105 static char *e_toomanyarg = N_("E118: Too many arguments for function: %s");
106 static char *e_dictkey = N_("E716: Key not present in Dictionary: %s");
107 static char *e_funcexts = N_("E122: Function %s already exists, add ! to replace it");
108 static char *e_funcdict = N_("E717: Dictionary entry already exists");
109 static char *e_funcref = N_("E718: Funcref required");
110 static char *e_dictrange = N_("E719: Cannot use [:] with a Dictionary");
111 static char *e_letwrong = N_("E734: Wrong variable type for %s=");
112 static char *e_nofunc = N_("E130: Unknown function: %s");
113 static char *e_illvar = N_("E461: Illegal variable name: %s");
116 * All user-defined global variables are stored in dictionary "globvardict".
117 * "globvars_var" is the variable that is used for "g:".
119 static dict_T globvardict;
120 static dictitem_T globvars_var;
121 #define globvarht globvardict.dv_hashtab
124 * Old Vim variables such as "v:version" are also available without the "v:".
125 * Also in functions. We need a special hashtable for them.
127 static hashtab_T compat_hashtab;
130 * When recursively copying lists and dicts we need to remember which ones we
131 * have done to avoid endless recursiveness. This unique ID is used for that.
133 static int current_copyID = 0;
136 * Array to hold the hashtab with variables local to each sourced script.
137 * Each item holds a variable (nameless) that points to the dict_T.
139 typedef struct
141 dictitem_T sv_var;
142 dict_T sv_dict;
143 } scriptvar_T;
145 static garray_T ga_scripts = {0, 0, sizeof(scriptvar_T), 4, NULL};
146 #define SCRIPT_SV(id) (((scriptvar_T *)ga_scripts.ga_data)[(id) - 1])
147 #define SCRIPT_VARS(id) (SCRIPT_SV(id).sv_dict.dv_hashtab)
149 static int echo_attr = 0; /* attributes used for ":echo" */
151 /* Values for trans_function_name() argument: */
152 #define TFN_INT 1 /* internal function name OK */
153 #define TFN_QUIET 2 /* no error messages */
156 * Structure to hold info for a user function.
158 typedef struct ufunc ufunc_T;
160 struct ufunc
162 int uf_varargs; /* variable nr of arguments */
163 int uf_flags;
164 int uf_calls; /* nr of active calls */
165 garray_T uf_args; /* arguments */
166 garray_T uf_lines; /* function lines */
167 #ifdef FEAT_PROFILE
168 int uf_profiling; /* TRUE when func is being profiled */
169 /* profiling the function as a whole */
170 int uf_tm_count; /* nr of calls */
171 proftime_T uf_tm_total; /* time spent in function + children */
172 proftime_T uf_tm_self; /* time spent in function itself */
173 proftime_T uf_tm_children; /* time spent in children this call */
174 /* profiling the function per line */
175 int *uf_tml_count; /* nr of times line was executed */
176 proftime_T *uf_tml_total; /* time spent in a line + children */
177 proftime_T *uf_tml_self; /* time spent in a line itself */
178 proftime_T uf_tml_start; /* start time for current line */
179 proftime_T uf_tml_children; /* time spent in children for this line */
180 proftime_T uf_tml_wait; /* start wait time for current line */
181 int uf_tml_idx; /* index of line being timed; -1 if none */
182 int uf_tml_execed; /* line being timed was executed */
183 #endif
184 scid_T uf_script_ID; /* ID of script where function was defined,
185 used for s: variables */
186 int uf_refcount; /* for numbered function: reference count */
187 char_u uf_name[1]; /* name of function (actually longer); can
188 start with <SNR>123_ (<SNR> is K_SPECIAL
189 KS_EXTRA KE_SNR) */
192 /* function flags */
193 #define FC_ABORT 1 /* abort function on error */
194 #define FC_RANGE 2 /* function accepts range */
195 #define FC_DICT 4 /* Dict function, uses "self" */
198 * All user-defined functions are found in this hashtable.
200 static hashtab_T func_hashtab;
202 /* The names of packages that once were loaded are remembered. */
203 static garray_T ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
205 /* list heads for garbage collection */
206 static dict_T *first_dict = NULL; /* list of all dicts */
207 static list_T *first_list = NULL; /* list of all lists */
209 /* From user function to hashitem and back. */
210 static ufunc_T dumuf;
211 #define UF2HIKEY(fp) ((fp)->uf_name)
212 #define HIKEY2UF(p) ((ufunc_T *)(p - (dumuf.uf_name - (char_u *)&dumuf)))
213 #define HI2UF(hi) HIKEY2UF((hi)->hi_key)
215 #define FUNCARG(fp, j) ((char_u **)(fp->uf_args.ga_data))[j]
216 #define FUNCLINE(fp, j) ((char_u **)(fp->uf_lines.ga_data))[j]
218 #define MAX_FUNC_ARGS 20 /* maximum number of function arguments */
219 #define VAR_SHORT_LEN 20 /* short variable name length */
220 #define FIXVAR_CNT 12 /* number of fixed variables */
222 /* structure to hold info for a function that is currently being executed. */
223 typedef struct funccall_S funccall_T;
225 struct funccall_S
227 ufunc_T *func; /* function being called */
228 int linenr; /* next line to be executed */
229 int returned; /* ":return" used */
230 struct /* fixed variables for arguments */
232 dictitem_T var; /* variable (without room for name) */
233 char_u room[VAR_SHORT_LEN]; /* room for the name */
234 } fixvar[FIXVAR_CNT];
235 dict_T l_vars; /* l: local function variables */
236 dictitem_T l_vars_var; /* variable for l: scope */
237 dict_T l_avars; /* a: argument variables */
238 dictitem_T l_avars_var; /* variable for a: scope */
239 list_T l_varlist; /* list for a:000 */
240 listitem_T l_listitems[MAX_FUNC_ARGS]; /* listitems for a:000 */
241 typval_T *rettv; /* return value */
242 linenr_T breakpoint; /* next line with breakpoint or zero */
243 int dbg_tick; /* debug_tick when breakpoint was set */
244 int level; /* top nesting level of executed function */
245 #ifdef FEAT_PROFILE
246 proftime_T prof_child; /* time spent in a child */
247 #endif
248 funccall_T *caller; /* calling function or NULL */
252 * Info used by a ":for" loop.
254 typedef struct
256 int fi_semicolon; /* TRUE if ending in '; var]' */
257 int fi_varcount; /* nr of variables in the list */
258 listwatch_T fi_lw; /* keep an eye on the item used. */
259 list_T *fi_list; /* list being used */
260 } forinfo_T;
263 * Struct used by trans_function_name()
265 typedef struct
267 dict_T *fd_dict; /* Dictionary used */
268 char_u *fd_newkey; /* new key in "dict" in allocated memory */
269 dictitem_T *fd_di; /* Dictionary item used */
270 } funcdict_T;
274 * Array to hold the value of v: variables.
275 * The value is in a dictitem, so that it can also be used in the v: scope.
276 * The reason to use this table anyway is for very quick access to the
277 * variables with the VV_ defines.
279 #include "version.h"
281 /* values for vv_flags: */
282 #define VV_COMPAT 1 /* compatible, also used without "v:" */
283 #define VV_RO 2 /* read-only */
284 #define VV_RO_SBX 4 /* read-only in the sandbox */
286 #define VV_NAME(s, t) s, {{t}}, {0}
288 static struct vimvar
290 char *vv_name; /* name of variable, without v: */
291 dictitem_T vv_di; /* value and name for key */
292 char vv_filler[16]; /* space for LONGEST name below!!! */
293 char vv_flags; /* VV_COMPAT, VV_RO, VV_RO_SBX */
294 } vimvars[VV_LEN] =
297 * The order here must match the VV_ defines in vim.h!
298 * Initializing a union does not work, leave tv.vval empty to get zero's.
300 {VV_NAME("count", VAR_NUMBER), VV_COMPAT+VV_RO},
301 {VV_NAME("count1", VAR_NUMBER), VV_RO},
302 {VV_NAME("prevcount", VAR_NUMBER), VV_RO},
303 {VV_NAME("errmsg", VAR_STRING), VV_COMPAT},
304 {VV_NAME("warningmsg", VAR_STRING), 0},
305 {VV_NAME("statusmsg", VAR_STRING), 0},
306 {VV_NAME("shell_error", VAR_NUMBER), VV_COMPAT+VV_RO},
307 {VV_NAME("this_session", VAR_STRING), VV_COMPAT},
308 {VV_NAME("version", VAR_NUMBER), VV_COMPAT+VV_RO},
309 {VV_NAME("lnum", VAR_NUMBER), VV_RO_SBX},
310 {VV_NAME("termresponse", VAR_STRING), VV_RO},
311 {VV_NAME("fname", VAR_STRING), VV_RO},
312 {VV_NAME("lang", VAR_STRING), VV_RO},
313 {VV_NAME("lc_time", VAR_STRING), VV_RO},
314 {VV_NAME("ctype", VAR_STRING), VV_RO},
315 {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
316 {VV_NAME("charconvert_to", VAR_STRING), VV_RO},
317 {VV_NAME("fname_in", VAR_STRING), VV_RO},
318 {VV_NAME("fname_out", VAR_STRING), VV_RO},
319 {VV_NAME("fname_new", VAR_STRING), VV_RO},
320 {VV_NAME("fname_diff", VAR_STRING), VV_RO},
321 {VV_NAME("cmdarg", VAR_STRING), VV_RO},
322 {VV_NAME("foldstart", VAR_NUMBER), VV_RO_SBX},
323 {VV_NAME("foldend", VAR_NUMBER), VV_RO_SBX},
324 {VV_NAME("folddashes", VAR_STRING), VV_RO_SBX},
325 {VV_NAME("foldlevel", VAR_NUMBER), VV_RO_SBX},
326 {VV_NAME("progname", VAR_STRING), VV_RO},
327 {VV_NAME("servername", VAR_STRING), VV_RO},
328 {VV_NAME("dying", VAR_NUMBER), VV_RO},
329 {VV_NAME("exception", VAR_STRING), VV_RO},
330 {VV_NAME("throwpoint", VAR_STRING), VV_RO},
331 {VV_NAME("register", VAR_STRING), VV_RO},
332 {VV_NAME("cmdbang", VAR_NUMBER), VV_RO},
333 {VV_NAME("insertmode", VAR_STRING), VV_RO},
334 {VV_NAME("val", VAR_UNKNOWN), VV_RO},
335 {VV_NAME("key", VAR_UNKNOWN), VV_RO},
336 {VV_NAME("profiling", VAR_NUMBER), VV_RO},
337 {VV_NAME("fcs_reason", VAR_STRING), VV_RO},
338 {VV_NAME("fcs_choice", VAR_STRING), 0},
339 {VV_NAME("beval_bufnr", VAR_NUMBER), VV_RO},
340 {VV_NAME("beval_winnr", VAR_NUMBER), VV_RO},
341 {VV_NAME("beval_lnum", VAR_NUMBER), VV_RO},
342 {VV_NAME("beval_col", VAR_NUMBER), VV_RO},
343 {VV_NAME("beval_text", VAR_STRING), VV_RO},
344 {VV_NAME("scrollstart", VAR_STRING), 0},
345 {VV_NAME("swapname", VAR_STRING), VV_RO},
346 {VV_NAME("swapchoice", VAR_STRING), 0},
347 {VV_NAME("swapcommand", VAR_STRING), VV_RO},
348 {VV_NAME("char", VAR_STRING), VV_RO},
349 {VV_NAME("mouse_win", VAR_NUMBER), 0},
350 {VV_NAME("mouse_lnum", VAR_NUMBER), 0},
351 {VV_NAME("mouse_col", VAR_NUMBER), 0},
352 {VV_NAME("operator", VAR_STRING), VV_RO},
353 {VV_NAME("searchforward", VAR_NUMBER), 0},
354 {VV_NAME("oldfiles", VAR_LIST), 0},
357 /* shorthand */
358 #define vv_type vv_di.di_tv.v_type
359 #define vv_nr vv_di.di_tv.vval.v_number
360 #define vv_float vv_di.di_tv.vval.v_float
361 #define vv_str vv_di.di_tv.vval.v_string
362 #define vv_list vv_di.di_tv.vval.v_list
363 #define vv_tv vv_di.di_tv
366 * The v: variables are stored in dictionary "vimvardict".
367 * "vimvars_var" is the variable that is used for the "l:" scope.
369 static dict_T vimvardict;
370 static dictitem_T vimvars_var;
371 #define vimvarht vimvardict.dv_hashtab
373 static void prepare_vimvar __ARGS((int idx, typval_T *save_tv));
374 static void restore_vimvar __ARGS((int idx, typval_T *save_tv));
375 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
376 static int call_vim_function __ARGS((char_u *func, int argc, char_u **argv, int safe, typval_T *rettv));
377 #endif
378 static int ex_let_vars __ARGS((char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars));
379 static char_u *skip_var_list __ARGS((char_u *arg, int *var_count, int *semicolon));
380 static char_u *skip_var_one __ARGS((char_u *arg));
381 static void list_hashtable_vars __ARGS((hashtab_T *ht, char_u *prefix, int empty, int *first));
382 static void list_glob_vars __ARGS((int *first));
383 static void list_buf_vars __ARGS((int *first));
384 static void list_win_vars __ARGS((int *first));
385 #ifdef FEAT_WINDOWS
386 static void list_tab_vars __ARGS((int *first));
387 #endif
388 static void list_vim_vars __ARGS((int *first));
389 static void list_script_vars __ARGS((int *first));
390 static void list_func_vars __ARGS((int *first));
391 static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg, int *first));
392 static char_u *ex_let_one __ARGS((char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op));
393 static int check_changedtick __ARGS((char_u *arg));
394 static char_u *get_lval __ARGS((char_u *name, typval_T *rettv, lval_T *lp, int unlet, int skip, int quiet, int fne_flags));
395 static void clear_lval __ARGS((lval_T *lp));
396 static void set_var_lval __ARGS((lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op));
397 static int tv_op __ARGS((typval_T *tv1, typval_T *tv2, char_u *op));
398 static void list_add_watch __ARGS((list_T *l, listwatch_T *lw));
399 static void list_rem_watch __ARGS((list_T *l, listwatch_T *lwrem));
400 static void list_fix_watch __ARGS((list_T *l, listitem_T *item));
401 static void ex_unletlock __ARGS((exarg_T *eap, char_u *argstart, int deep));
402 static int do_unlet_var __ARGS((lval_T *lp, char_u *name_end, int forceit));
403 static int do_lock_var __ARGS((lval_T *lp, char_u *name_end, int deep, int lock));
404 static void item_lock __ARGS((typval_T *tv, int deep, int lock));
405 static int tv_islocked __ARGS((typval_T *tv));
407 static int eval0 __ARGS((char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate));
408 static int eval1 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
409 static int eval2 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
410 static int eval3 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
411 static int eval4 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
412 static int eval5 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
413 static int eval6 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
414 static int eval7 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
416 static int eval_index __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
417 static int get_option_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
418 static int get_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
419 static int get_lit_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
420 static int get_list_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
421 static int rettv_list_alloc __ARGS((typval_T *rettv));
422 static listitem_T *listitem_alloc __ARGS((void));
423 static void listitem_free __ARGS((listitem_T *item));
424 static void listitem_remove __ARGS((list_T *l, listitem_T *item));
425 static long list_len __ARGS((list_T *l));
426 static int list_equal __ARGS((list_T *l1, list_T *l2, int ic));
427 static int dict_equal __ARGS((dict_T *d1, dict_T *d2, int ic));
428 static int tv_equal __ARGS((typval_T *tv1, typval_T *tv2, int ic));
429 static listitem_T *list_find __ARGS((list_T *l, long n));
430 static long list_find_nr __ARGS((list_T *l, long idx, int *errorp));
431 static long list_idx_of_item __ARGS((list_T *l, listitem_T *item));
432 static void list_append __ARGS((list_T *l, listitem_T *item));
433 static int list_append_tv __ARGS((list_T *l, typval_T *tv));
434 static int list_append_number __ARGS((list_T *l, varnumber_T n));
435 static int list_insert_tv __ARGS((list_T *l, typval_T *tv, listitem_T *item));
436 static int list_extend __ARGS((list_T *l1, list_T *l2, listitem_T *bef));
437 static int list_concat __ARGS((list_T *l1, list_T *l2, typval_T *tv));
438 static list_T *list_copy __ARGS((list_T *orig, int deep, int copyID));
439 static void list_remove __ARGS((list_T *l, listitem_T *item, listitem_T *item2));
440 static char_u *list2string __ARGS((typval_T *tv, int copyID));
441 static int list_join __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo, int copyID));
442 static void set_ref_in_ht __ARGS((hashtab_T *ht, int copyID));
443 static void set_ref_in_list __ARGS((list_T *l, int copyID));
444 static void set_ref_in_item __ARGS((typval_T *tv, int copyID));
445 static void dict_unref __ARGS((dict_T *d));
446 static void dict_free __ARGS((dict_T *d, int recurse));
447 static dictitem_T *dictitem_alloc __ARGS((char_u *key));
448 static dictitem_T *dictitem_copy __ARGS((dictitem_T *org));
449 static void dictitem_remove __ARGS((dict_T *dict, dictitem_T *item));
450 static void dictitem_free __ARGS((dictitem_T *item));
451 static dict_T *dict_copy __ARGS((dict_T *orig, int deep, int copyID));
452 static int dict_add __ARGS((dict_T *d, dictitem_T *item));
453 static long dict_len __ARGS((dict_T *d));
454 static dictitem_T *dict_find __ARGS((dict_T *d, char_u *key, int len));
455 static char_u *dict2string __ARGS((typval_T *tv, int copyID));
456 static int get_dict_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
457 static char_u *echo_string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
458 static char_u *tv2string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
459 static char_u *string_quote __ARGS((char_u *str, int function));
460 #ifdef FEAT_FLOAT
461 static int string2float __ARGS((char_u *text, float_T *value));
462 #endif
463 static int get_env_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
464 static int find_internal_func __ARGS((char_u *name));
465 static char_u *deref_func_name __ARGS((char_u *name, int *lenp));
466 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));
467 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));
468 static void emsg_funcname __ARGS((char *ermsg, char_u *name));
469 static int non_zero_arg __ARGS((typval_T *argvars));
471 #ifdef FEAT_FLOAT
472 static void f_abs __ARGS((typval_T *argvars, typval_T *rettv));
473 #endif
474 static void f_add __ARGS((typval_T *argvars, typval_T *rettv));
475 static void f_append __ARGS((typval_T *argvars, typval_T *rettv));
476 static void f_argc __ARGS((typval_T *argvars, typval_T *rettv));
477 static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv));
478 static void f_argv __ARGS((typval_T *argvars, typval_T *rettv));
479 #ifdef FEAT_FLOAT
480 static void f_atan __ARGS((typval_T *argvars, typval_T *rettv));
481 #endif
482 static void f_browse __ARGS((typval_T *argvars, typval_T *rettv));
483 static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv));
484 static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv));
485 static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv));
486 static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv));
487 static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv));
488 static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv));
489 static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv));
490 static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv));
491 static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv));
492 static void f_call __ARGS((typval_T *argvars, typval_T *rettv));
493 #ifdef FEAT_FLOAT
494 static void f_ceil __ARGS((typval_T *argvars, typval_T *rettv));
495 #endif
496 static void f_changenr __ARGS((typval_T *argvars, typval_T *rettv));
497 static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv));
498 static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv));
499 static void f_clearmatches __ARGS((typval_T *argvars, typval_T *rettv));
500 static void f_col __ARGS((typval_T *argvars, typval_T *rettv));
501 #if defined(FEAT_INS_EXPAND)
502 static void f_complete __ARGS((typval_T *argvars, typval_T *rettv));
503 static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv));
504 static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv));
505 #endif
506 static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv));
507 static void f_copy __ARGS((typval_T *argvars, typval_T *rettv));
508 #ifdef FEAT_FLOAT
509 static void f_cos __ARGS((typval_T *argvars, typval_T *rettv));
510 #endif
511 static void f_count __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv));
513 static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv));
514 static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_delete __ARGS((typval_T *argvars, typval_T *rettv));
516 static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv));
517 static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_empty __ARGS((typval_T *argvars, typval_T *rettv));
520 static void f_escape __ARGS((typval_T *argvars, typval_T *rettv));
521 static void f_eval __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv));
523 static void f_executable __ARGS((typval_T *argvars, typval_T *rettv));
524 static void f_exists __ARGS((typval_T *argvars, typval_T *rettv));
525 static void f_expand __ARGS((typval_T *argvars, typval_T *rettv));
526 static void f_extend __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_feedkeys __ARGS((typval_T *argvars, typval_T *rettv));
528 static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv));
529 static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_filter __ARGS((typval_T *argvars, typval_T *rettv));
531 static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv));
532 static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv));
533 #ifdef FEAT_FLOAT
534 static void f_float2nr __ARGS((typval_T *argvars, typval_T *rettv));
535 static void f_floor __ARGS((typval_T *argvars, typval_T *rettv));
536 #endif
537 static void f_fnameescape __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
542 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
546 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
547 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
548 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
549 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
551 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
552 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_getpid __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
590 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
591 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
592 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
593 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
594 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
595 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
596 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
603 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
604 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
605 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
606 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
607 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
608 #ifdef FEAT_FLOAT
609 static void f_log10 __ARGS((typval_T *argvars, typval_T *rettv));
610 #endif
611 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv));
618 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
619 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
620 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
621 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
622 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
623 #ifdef vim_mkdir
624 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
625 #endif
626 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
627 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
628 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
629 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
630 #ifdef FEAT_FLOAT
631 static void f_pow __ARGS((typval_T *argvars, typval_T *rettv));
632 #endif
633 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
634 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
635 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
636 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
637 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
638 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
639 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
640 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
641 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
642 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
643 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
644 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
645 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
646 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
647 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
648 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
649 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
650 #ifdef FEAT_FLOAT
651 static void f_round __ARGS((typval_T *argvars, typval_T *rettv));
652 #endif
653 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
654 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
655 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
656 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
657 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
667 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
668 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
669 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
670 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
671 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
672 #ifdef FEAT_FLOAT
673 static void f_sin __ARGS((typval_T *argvars, typval_T *rettv));
674 #endif
675 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
676 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
677 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
678 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
679 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
680 #ifdef FEAT_FLOAT
681 static void f_sqrt __ARGS((typval_T *argvars, typval_T *rettv));
682 static void f_str2float __ARGS((typval_T *argvars, typval_T *rettv));
683 #endif
684 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
685 #ifdef HAVE_STRFTIME
686 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
687 #endif
688 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
689 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
690 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
691 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
692 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
693 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
694 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
695 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
696 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
697 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
698 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
699 static void f_synstack __ARGS((typval_T *argvars, typval_T *rettv));
700 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
701 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
702 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
703 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
704 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
705 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
706 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
707 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
708 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
709 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
710 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
711 #ifdef FEAT_FLOAT
712 static void f_trunc __ARGS((typval_T *argvars, typval_T *rettv));
713 #endif
714 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
715 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
716 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
717 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
718 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
719 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
720 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
721 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
722 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
723 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
724 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
725 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
726 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
727 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
729 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
730 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
731 static int get_env_len __ARGS((char_u **arg));
732 static int get_id_len __ARGS((char_u **arg));
733 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
734 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
735 #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */
736 #define FNE_CHECK_START 2 /* find_name_end(): check name starts with
737 valid character */
738 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
739 static int eval_isnamec __ARGS((int c));
740 static int eval_isnamec1 __ARGS((int c));
741 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
742 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
743 static typval_T *alloc_tv __ARGS((void));
744 static typval_T *alloc_string_tv __ARGS((char_u *string));
745 static void init_tv __ARGS((typval_T *varp));
746 static long get_tv_number __ARGS((typval_T *varp));
747 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
748 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
749 static char_u *get_tv_string __ARGS((typval_T *varp));
750 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
751 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
752 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
753 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
754 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
755 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
756 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
757 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
758 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
759 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
760 static int var_check_ro __ARGS((int flags, char_u *name));
761 static int var_check_fixed __ARGS((int flags, char_u *name));
762 static int tv_check_lock __ARGS((int lock, char_u *name));
763 static void copy_tv __ARGS((typval_T *from, typval_T *to));
764 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
765 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
766 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
767 static int eval_fname_script __ARGS((char_u *p));
768 static int eval_fname_sid __ARGS((char_u *p));
769 static void list_func_head __ARGS((ufunc_T *fp, int indent));
770 static ufunc_T *find_func __ARGS((char_u *name));
771 static int function_exists __ARGS((char_u *name));
772 static int builtin_function __ARGS((char_u *name));
773 #ifdef FEAT_PROFILE
774 static void func_do_profile __ARGS((ufunc_T *fp));
775 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
776 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
777 static int
778 # ifdef __BORLANDC__
779 _RTLENTRYF
780 # endif
781 prof_total_cmp __ARGS((const void *s1, const void *s2));
782 static int
783 # ifdef __BORLANDC__
784 _RTLENTRYF
785 # endif
786 prof_self_cmp __ARGS((const void *s1, const void *s2));
787 #endif
788 static int script_autoload __ARGS((char_u *name, int reload));
789 static char_u *autoload_name __ARGS((char_u *name));
790 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
791 static void func_free __ARGS((ufunc_T *fp));
792 static void func_unref __ARGS((char_u *name));
793 static void func_ref __ARGS((char_u *name));
794 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));
795 static int can_free_funccal __ARGS((funccall_T *fc, int copyID)) ;
796 static void free_funccal __ARGS((funccall_T *fc, int free_val));
797 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
798 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
799 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
800 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
801 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
802 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
804 /* Character used as separated in autoload function/variable names. */
805 #define AUTOLOAD_CHAR '#'
808 * Initialize the global and v: variables.
810 void
811 eval_init()
813 int i;
814 struct vimvar *p;
816 init_var_dict(&globvardict, &globvars_var);
817 init_var_dict(&vimvardict, &vimvars_var);
818 hash_init(&compat_hashtab);
819 hash_init(&func_hashtab);
821 for (i = 0; i < VV_LEN; ++i)
823 p = &vimvars[i];
824 STRCPY(p->vv_di.di_key, p->vv_name);
825 if (p->vv_flags & VV_RO)
826 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
827 else if (p->vv_flags & VV_RO_SBX)
828 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
829 else
830 p->vv_di.di_flags = DI_FLAGS_FIX;
832 /* add to v: scope dict, unless the value is not always available */
833 if (p->vv_type != VAR_UNKNOWN)
834 hash_add(&vimvarht, p->vv_di.di_key);
835 if (p->vv_flags & VV_COMPAT)
836 /* add to compat scope dict */
837 hash_add(&compat_hashtab, p->vv_di.di_key);
839 set_vim_var_nr(VV_SEARCHFORWARD, 1L);
842 #if defined(EXITFREE) || defined(PROTO)
843 void
844 eval_clear()
846 int i;
847 struct vimvar *p;
849 for (i = 0; i < VV_LEN; ++i)
851 p = &vimvars[i];
852 if (p->vv_di.di_tv.v_type == VAR_STRING)
854 vim_free(p->vv_str);
855 p->vv_str = NULL;
857 else if (p->vv_di.di_tv.v_type == VAR_LIST)
859 list_unref(p->vv_list);
860 p->vv_list = NULL;
863 hash_clear(&vimvarht);
864 hash_init(&vimvarht); /* garbage_collect() will access it */
865 hash_clear(&compat_hashtab);
867 /* script-local variables */
868 for (i = 1; i <= ga_scripts.ga_len; ++i)
869 vars_clear(&SCRIPT_VARS(i));
870 ga_clear(&ga_scripts);
871 free_scriptnames();
873 /* global variables */
874 vars_clear(&globvarht);
876 /* autoloaded script names */
877 ga_clear_strings(&ga_loaded);
879 /* unreferenced lists and dicts */
880 (void)garbage_collect();
882 /* functions */
883 free_all_functions();
884 hash_clear(&func_hashtab);
886 #endif
889 * Return the name of the executed function.
891 char_u *
892 func_name(cookie)
893 void *cookie;
895 return ((funccall_T *)cookie)->func->uf_name;
899 * Return the address holding the next breakpoint line for a funccall cookie.
901 linenr_T *
902 func_breakpoint(cookie)
903 void *cookie;
905 return &((funccall_T *)cookie)->breakpoint;
909 * Return the address holding the debug tick for a funccall cookie.
911 int *
912 func_dbg_tick(cookie)
913 void *cookie;
915 return &((funccall_T *)cookie)->dbg_tick;
919 * Return the nesting level for a funccall cookie.
922 func_level(cookie)
923 void *cookie;
925 return ((funccall_T *)cookie)->level;
928 /* pointer to funccal for currently active function */
929 funccall_T *current_funccal = NULL;
931 /* pointer to list of previously used funccal, still around because some
932 * item in it is still being used. */
933 funccall_T *previous_funccal = NULL;
936 * Return TRUE when a function was ended by a ":return" command.
939 current_func_returned()
941 return current_funccal->returned;
946 * Set an internal variable to a string value. Creates the variable if it does
947 * not already exist.
949 void
950 set_internal_string_var(name, value)
951 char_u *name;
952 char_u *value;
954 char_u *val;
955 typval_T *tvp;
957 val = vim_strsave(value);
958 if (val != NULL)
960 tvp = alloc_string_tv(val);
961 if (tvp != NULL)
963 set_var(name, tvp, FALSE);
964 free_tv(tvp);
969 static lval_T *redir_lval = NULL;
970 static garray_T redir_ga; /* only valid when redir_lval is not NULL */
971 static char_u *redir_endp = NULL;
972 static char_u *redir_varname = NULL;
975 * Start recording command output to a variable
976 * Returns OK if successfully completed the setup. FAIL otherwise.
979 var_redir_start(name, append)
980 char_u *name;
981 int append; /* append to an existing variable */
983 int save_emsg;
984 int err;
985 typval_T tv;
987 /* Make sure a valid variable name is specified */
988 if (!eval_isnamec1(*name))
990 EMSG(_(e_invarg));
991 return FAIL;
994 redir_varname = vim_strsave(name);
995 if (redir_varname == NULL)
996 return FAIL;
998 redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
999 if (redir_lval == NULL)
1001 var_redir_stop();
1002 return FAIL;
1005 /* The output is stored in growarray "redir_ga" until redirection ends. */
1006 ga_init2(&redir_ga, (int)sizeof(char), 500);
1008 /* Parse the variable name (can be a dict or list entry). */
1009 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
1010 FNE_CHECK_START);
1011 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
1013 if (redir_endp != NULL && *redir_endp != NUL)
1014 /* Trailing characters are present after the variable name */
1015 EMSG(_(e_trailing));
1016 else
1017 EMSG(_(e_invarg));
1018 var_redir_stop();
1019 return FAIL;
1022 /* check if we can write to the variable: set it to or append an empty
1023 * string */
1024 save_emsg = did_emsg;
1025 did_emsg = FALSE;
1026 tv.v_type = VAR_STRING;
1027 tv.vval.v_string = (char_u *)"";
1028 if (append)
1029 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
1030 else
1031 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
1032 err = did_emsg;
1033 did_emsg |= save_emsg;
1034 if (err)
1036 var_redir_stop();
1037 return FAIL;
1039 if (redir_lval->ll_newkey != NULL)
1041 /* Dictionary item was created, don't do it again. */
1042 vim_free(redir_lval->ll_newkey);
1043 redir_lval->ll_newkey = NULL;
1046 return OK;
1050 * Append "value[value_len]" to the variable set by var_redir_start().
1051 * The actual appending is postponed until redirection ends, because the value
1052 * appended may in fact be the string we write to, changing it may cause freed
1053 * memory to be used:
1054 * :redir => foo
1055 * :let foo
1056 * :redir END
1058 void
1059 var_redir_str(value, value_len)
1060 char_u *value;
1061 int value_len;
1063 int len;
1065 if (redir_lval == NULL)
1066 return;
1068 if (value_len == -1)
1069 len = (int)STRLEN(value); /* Append the entire string */
1070 else
1071 len = value_len; /* Append only "value_len" characters */
1073 if (ga_grow(&redir_ga, len) == OK)
1075 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1076 redir_ga.ga_len += len;
1078 else
1079 var_redir_stop();
1083 * Stop redirecting command output to a variable.
1085 void
1086 var_redir_stop()
1088 typval_T tv;
1090 if (redir_lval != NULL)
1092 /* Append the trailing NUL. */
1093 ga_append(&redir_ga, NUL);
1095 /* Assign the text to the variable. */
1096 tv.v_type = VAR_STRING;
1097 tv.vval.v_string = redir_ga.ga_data;
1098 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1099 vim_free(tv.vval.v_string);
1101 clear_lval(redir_lval);
1102 vim_free(redir_lval);
1103 redir_lval = NULL;
1105 vim_free(redir_varname);
1106 redir_varname = NULL;
1109 # if defined(FEAT_MBYTE) || defined(PROTO)
1111 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1112 char_u *enc_from;
1113 char_u *enc_to;
1114 char_u *fname_from;
1115 char_u *fname_to;
1117 int err = FALSE;
1119 set_vim_var_string(VV_CC_FROM, enc_from, -1);
1120 set_vim_var_string(VV_CC_TO, enc_to, -1);
1121 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1122 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1123 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1124 err = TRUE;
1125 set_vim_var_string(VV_CC_FROM, NULL, -1);
1126 set_vim_var_string(VV_CC_TO, NULL, -1);
1127 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1128 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1130 if (err)
1131 return FAIL;
1132 return OK;
1134 # endif
1136 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1138 eval_printexpr(fname, args)
1139 char_u *fname;
1140 char_u *args;
1142 int err = FALSE;
1144 set_vim_var_string(VV_FNAME_IN, fname, -1);
1145 set_vim_var_string(VV_CMDARG, args, -1);
1146 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1147 err = TRUE;
1148 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1149 set_vim_var_string(VV_CMDARG, NULL, -1);
1151 if (err)
1153 mch_remove(fname);
1154 return FAIL;
1156 return OK;
1158 # endif
1160 # if defined(FEAT_DIFF) || defined(PROTO)
1161 void
1162 eval_diff(origfile, newfile, outfile)
1163 char_u *origfile;
1164 char_u *newfile;
1165 char_u *outfile;
1167 int err = FALSE;
1169 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1170 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1171 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1172 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1173 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1174 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1175 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1178 void
1179 eval_patch(origfile, difffile, outfile)
1180 char_u *origfile;
1181 char_u *difffile;
1182 char_u *outfile;
1184 int err;
1186 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1187 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1188 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1189 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1190 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1191 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1192 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1194 # endif
1197 * Top level evaluation function, returning a boolean.
1198 * Sets "error" to TRUE if there was an error.
1199 * Return TRUE or FALSE.
1202 eval_to_bool(arg, error, nextcmd, skip)
1203 char_u *arg;
1204 int *error;
1205 char_u **nextcmd;
1206 int skip; /* only parse, don't execute */
1208 typval_T tv;
1209 int retval = FALSE;
1211 if (skip)
1212 ++emsg_skip;
1213 if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1214 *error = TRUE;
1215 else
1217 *error = FALSE;
1218 if (!skip)
1220 retval = (get_tv_number_chk(&tv, error) != 0);
1221 clear_tv(&tv);
1224 if (skip)
1225 --emsg_skip;
1227 return retval;
1231 * Top level evaluation function, returning a string. If "skip" is TRUE,
1232 * only parsing to "nextcmd" is done, without reporting errors. Return
1233 * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1235 char_u *
1236 eval_to_string_skip(arg, nextcmd, skip)
1237 char_u *arg;
1238 char_u **nextcmd;
1239 int skip; /* only parse, don't execute */
1241 typval_T tv;
1242 char_u *retval;
1244 if (skip)
1245 ++emsg_skip;
1246 if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1247 retval = NULL;
1248 else
1250 retval = vim_strsave(get_tv_string(&tv));
1251 clear_tv(&tv);
1253 if (skip)
1254 --emsg_skip;
1256 return retval;
1260 * Skip over an expression at "*pp".
1261 * Return FAIL for an error, OK otherwise.
1264 skip_expr(pp)
1265 char_u **pp;
1267 typval_T rettv;
1269 *pp = skipwhite(*pp);
1270 return eval1(pp, &rettv, FALSE);
1274 * Top level evaluation function, returning a string.
1275 * When "convert" is TRUE convert a List into a sequence of lines and convert
1276 * a Float to a String.
1277 * Return pointer to allocated memory, or NULL for failure.
1279 char_u *
1280 eval_to_string(arg, nextcmd, convert)
1281 char_u *arg;
1282 char_u **nextcmd;
1283 int convert;
1285 typval_T tv;
1286 char_u *retval;
1287 garray_T ga;
1288 #ifdef FEAT_FLOAT
1289 char_u numbuf[NUMBUFLEN];
1290 #endif
1292 if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1293 retval = NULL;
1294 else
1296 if (convert && tv.v_type == VAR_LIST)
1298 ga_init2(&ga, (int)sizeof(char), 80);
1299 if (tv.vval.v_list != NULL)
1300 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1301 ga_append(&ga, NUL);
1302 retval = (char_u *)ga.ga_data;
1304 #ifdef FEAT_FLOAT
1305 else if (convert && tv.v_type == VAR_FLOAT)
1307 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv.vval.v_float);
1308 retval = vim_strsave(numbuf);
1310 #endif
1311 else
1312 retval = vim_strsave(get_tv_string(&tv));
1313 clear_tv(&tv);
1316 return retval;
1320 * Call eval_to_string() without using current local variables and using
1321 * textlock. When "use_sandbox" is TRUE use the sandbox.
1323 char_u *
1324 eval_to_string_safe(arg, nextcmd, use_sandbox)
1325 char_u *arg;
1326 char_u **nextcmd;
1327 int use_sandbox;
1329 char_u *retval;
1330 void *save_funccalp;
1332 save_funccalp = save_funccal();
1333 if (use_sandbox)
1334 ++sandbox;
1335 ++textlock;
1336 retval = eval_to_string(arg, nextcmd, FALSE);
1337 if (use_sandbox)
1338 --sandbox;
1339 --textlock;
1340 restore_funccal(save_funccalp);
1341 return retval;
1345 * Top level evaluation function, returning a number.
1346 * Evaluates "expr" silently.
1347 * Returns -1 for an error.
1350 eval_to_number(expr)
1351 char_u *expr;
1353 typval_T rettv;
1354 int retval;
1355 char_u *p = skipwhite(expr);
1357 ++emsg_off;
1359 if (eval1(&p, &rettv, TRUE) == FAIL)
1360 retval = -1;
1361 else
1363 retval = get_tv_number_chk(&rettv, NULL);
1364 clear_tv(&rettv);
1366 --emsg_off;
1368 return retval;
1372 * Prepare v: variable "idx" to be used.
1373 * Save the current typeval in "save_tv".
1374 * When not used yet add the variable to the v: hashtable.
1376 static void
1377 prepare_vimvar(idx, save_tv)
1378 int idx;
1379 typval_T *save_tv;
1381 *save_tv = vimvars[idx].vv_tv;
1382 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1383 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1387 * Restore v: variable "idx" to typeval "save_tv".
1388 * When no longer defined, remove the variable from the v: hashtable.
1390 static void
1391 restore_vimvar(idx, save_tv)
1392 int idx;
1393 typval_T *save_tv;
1395 hashitem_T *hi;
1397 vimvars[idx].vv_tv = *save_tv;
1398 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1400 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1401 if (HASHITEM_EMPTY(hi))
1402 EMSG2(_(e_intern2), "restore_vimvar()");
1403 else
1404 hash_remove(&vimvarht, hi);
1408 #if defined(FEAT_SPELL) || defined(PROTO)
1410 * Evaluate an expression to a list with suggestions.
1411 * For the "expr:" part of 'spellsuggest'.
1412 * Returns NULL when there is an error.
1414 list_T *
1415 eval_spell_expr(badword, expr)
1416 char_u *badword;
1417 char_u *expr;
1419 typval_T save_val;
1420 typval_T rettv;
1421 list_T *list = NULL;
1422 char_u *p = skipwhite(expr);
1424 /* Set "v:val" to the bad word. */
1425 prepare_vimvar(VV_VAL, &save_val);
1426 vimvars[VV_VAL].vv_type = VAR_STRING;
1427 vimvars[VV_VAL].vv_str = badword;
1428 if (p_verbose == 0)
1429 ++emsg_off;
1431 if (eval1(&p, &rettv, TRUE) == OK)
1433 if (rettv.v_type != VAR_LIST)
1434 clear_tv(&rettv);
1435 else
1436 list = rettv.vval.v_list;
1439 if (p_verbose == 0)
1440 --emsg_off;
1441 restore_vimvar(VV_VAL, &save_val);
1443 return list;
1447 * "list" is supposed to contain two items: a word and a number. Return the
1448 * word in "pp" and the number as the return value.
1449 * Return -1 if anything isn't right.
1450 * Used to get the good word and score from the eval_spell_expr() result.
1453 get_spellword(list, pp)
1454 list_T *list;
1455 char_u **pp;
1457 listitem_T *li;
1459 li = list->lv_first;
1460 if (li == NULL)
1461 return -1;
1462 *pp = get_tv_string(&li->li_tv);
1464 li = li->li_next;
1465 if (li == NULL)
1466 return -1;
1467 return get_tv_number(&li->li_tv);
1469 #endif
1472 * Top level evaluation function.
1473 * Returns an allocated typval_T with the result.
1474 * Returns NULL when there is an error.
1476 typval_T *
1477 eval_expr(arg, nextcmd)
1478 char_u *arg;
1479 char_u **nextcmd;
1481 typval_T *tv;
1483 tv = (typval_T *)alloc(sizeof(typval_T));
1484 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1486 vim_free(tv);
1487 tv = NULL;
1490 return tv;
1494 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1495 || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1497 * Call some vimL function and return the result in "*rettv".
1498 * Uses argv[argc] for the function arguments. Only Number and String
1499 * arguments are currently supported.
1500 * Returns OK or FAIL.
1502 static int
1503 call_vim_function(func, argc, argv, safe, rettv)
1504 char_u *func;
1505 int argc;
1506 char_u **argv;
1507 int safe; /* use the sandbox */
1508 typval_T *rettv;
1510 typval_T *argvars;
1511 long n;
1512 int len;
1513 int i;
1514 int doesrange;
1515 void *save_funccalp = NULL;
1516 int ret;
1518 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1519 if (argvars == NULL)
1520 return FAIL;
1522 for (i = 0; i < argc; i++)
1524 /* Pass a NULL or empty argument as an empty string */
1525 if (argv[i] == NULL || *argv[i] == NUL)
1527 argvars[i].v_type = VAR_STRING;
1528 argvars[i].vval.v_string = (char_u *)"";
1529 continue;
1532 /* Recognize a number argument, the others must be strings. */
1533 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1534 if (len != 0 && len == (int)STRLEN(argv[i]))
1536 argvars[i].v_type = VAR_NUMBER;
1537 argvars[i].vval.v_number = n;
1539 else
1541 argvars[i].v_type = VAR_STRING;
1542 argvars[i].vval.v_string = argv[i];
1546 if (safe)
1548 save_funccalp = save_funccal();
1549 ++sandbox;
1552 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1553 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1554 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1555 &doesrange, TRUE, NULL);
1556 if (safe)
1558 --sandbox;
1559 restore_funccal(save_funccalp);
1561 vim_free(argvars);
1563 if (ret == FAIL)
1564 clear_tv(rettv);
1566 return ret;
1569 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1571 * Call vimL function "func" and return the result as a string.
1572 * Returns NULL when calling the function fails.
1573 * Uses argv[argc] for the function arguments.
1575 void *
1576 call_func_retstr(func, argc, argv, safe)
1577 char_u *func;
1578 int argc;
1579 char_u **argv;
1580 int safe; /* use the sandbox */
1582 typval_T rettv;
1583 char_u *retval;
1585 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1586 return NULL;
1588 retval = vim_strsave(get_tv_string(&rettv));
1589 clear_tv(&rettv);
1590 return retval;
1592 # endif
1594 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1596 * Call vimL function "func" and return the result as a number.
1597 * Returns -1 when calling the function fails.
1598 * Uses argv[argc] for the function arguments.
1600 long
1601 call_func_retnr(func, argc, argv, safe)
1602 char_u *func;
1603 int argc;
1604 char_u **argv;
1605 int safe; /* use the sandbox */
1607 typval_T rettv;
1608 long retval;
1610 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1611 return -1;
1613 retval = get_tv_number_chk(&rettv, NULL);
1614 clear_tv(&rettv);
1615 return retval;
1617 # endif
1620 * Call vimL function "func" and return the result as a List.
1621 * Uses argv[argc] for the function arguments.
1622 * Returns NULL when there is something wrong.
1624 void *
1625 call_func_retlist(func, argc, argv, safe)
1626 char_u *func;
1627 int argc;
1628 char_u **argv;
1629 int safe; /* use the sandbox */
1631 typval_T rettv;
1633 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1634 return NULL;
1636 if (rettv.v_type != VAR_LIST)
1638 clear_tv(&rettv);
1639 return NULL;
1642 return rettv.vval.v_list;
1644 #endif
1648 * Save the current function call pointer, and set it to NULL.
1649 * Used when executing autocommands and for ":source".
1651 void *
1652 save_funccal()
1654 funccall_T *fc = current_funccal;
1656 current_funccal = NULL;
1657 return (void *)fc;
1660 void
1661 restore_funccal(vfc)
1662 void *vfc;
1664 funccall_T *fc = (funccall_T *)vfc;
1666 current_funccal = fc;
1669 #if defined(FEAT_PROFILE) || defined(PROTO)
1671 * Prepare profiling for entering a child or something else that is not
1672 * counted for the script/function itself.
1673 * Should always be called in pair with prof_child_exit().
1675 void
1676 prof_child_enter(tm)
1677 proftime_T *tm; /* place to store waittime */
1679 funccall_T *fc = current_funccal;
1681 if (fc != NULL && fc->func->uf_profiling)
1682 profile_start(&fc->prof_child);
1683 script_prof_save(tm);
1687 * Take care of time spent in a child.
1688 * Should always be called after prof_child_enter().
1690 void
1691 prof_child_exit(tm)
1692 proftime_T *tm; /* where waittime was stored */
1694 funccall_T *fc = current_funccal;
1696 if (fc != NULL && fc->func->uf_profiling)
1698 profile_end(&fc->prof_child);
1699 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1700 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1701 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1703 script_prof_restore(tm);
1705 #endif
1708 #ifdef FEAT_FOLDING
1710 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1711 * it in "*cp". Doesn't give error messages.
1714 eval_foldexpr(arg, cp)
1715 char_u *arg;
1716 int *cp;
1718 typval_T tv;
1719 int retval;
1720 char_u *s;
1721 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1722 OPT_LOCAL);
1724 ++emsg_off;
1725 if (use_sandbox)
1726 ++sandbox;
1727 ++textlock;
1728 *cp = NUL;
1729 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1730 retval = 0;
1731 else
1733 /* If the result is a number, just return the number. */
1734 if (tv.v_type == VAR_NUMBER)
1735 retval = tv.vval.v_number;
1736 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1737 retval = 0;
1738 else
1740 /* If the result is a string, check if there is a non-digit before
1741 * the number. */
1742 s = tv.vval.v_string;
1743 if (!VIM_ISDIGIT(*s) && *s != '-')
1744 *cp = *s++;
1745 retval = atol((char *)s);
1747 clear_tv(&tv);
1749 --emsg_off;
1750 if (use_sandbox)
1751 --sandbox;
1752 --textlock;
1754 return retval;
1756 #endif
1759 * ":let" list all variable values
1760 * ":let var1 var2" list variable values
1761 * ":let var = expr" assignment command.
1762 * ":let var += expr" assignment command.
1763 * ":let var -= expr" assignment command.
1764 * ":let var .= expr" assignment command.
1765 * ":let [var1, var2] = expr" unpack list.
1767 void
1768 ex_let(eap)
1769 exarg_T *eap;
1771 char_u *arg = eap->arg;
1772 char_u *expr = NULL;
1773 typval_T rettv;
1774 int i;
1775 int var_count = 0;
1776 int semicolon = 0;
1777 char_u op[2];
1778 char_u *argend;
1779 int first = TRUE;
1781 argend = skip_var_list(arg, &var_count, &semicolon);
1782 if (argend == NULL)
1783 return;
1784 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1785 --argend;
1786 expr = vim_strchr(argend, '=');
1787 if (expr == NULL)
1790 * ":let" without "=": list variables
1792 if (*arg == '[')
1793 EMSG(_(e_invarg));
1794 else if (!ends_excmd(*arg))
1795 /* ":let var1 var2" */
1796 arg = list_arg_vars(eap, arg, &first);
1797 else if (!eap->skip)
1799 /* ":let" */
1800 list_glob_vars(&first);
1801 list_buf_vars(&first);
1802 list_win_vars(&first);
1803 #ifdef FEAT_WINDOWS
1804 list_tab_vars(&first);
1805 #endif
1806 list_script_vars(&first);
1807 list_func_vars(&first);
1808 list_vim_vars(&first);
1810 eap->nextcmd = check_nextcmd(arg);
1812 else
1814 op[0] = '=';
1815 op[1] = NUL;
1816 if (expr > argend)
1818 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1819 op[0] = expr[-1]; /* +=, -= or .= */
1821 expr = skipwhite(expr + 1);
1823 if (eap->skip)
1824 ++emsg_skip;
1825 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1826 if (eap->skip)
1828 if (i != FAIL)
1829 clear_tv(&rettv);
1830 --emsg_skip;
1832 else if (i != FAIL)
1834 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1835 op);
1836 clear_tv(&rettv);
1842 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1843 * Handles both "var" with any type and "[var, var; var]" with a list type.
1844 * When "nextchars" is not NULL it points to a string with characters that
1845 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1846 * or concatenate.
1847 * Returns OK or FAIL;
1849 static int
1850 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1851 char_u *arg_start;
1852 typval_T *tv;
1853 int copy; /* copy values from "tv", don't move */
1854 int semicolon; /* from skip_var_list() */
1855 int var_count; /* from skip_var_list() */
1856 char_u *nextchars;
1858 char_u *arg = arg_start;
1859 list_T *l;
1860 int i;
1861 listitem_T *item;
1862 typval_T ltv;
1864 if (*arg != '[')
1867 * ":let var = expr" or ":for var in list"
1869 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1870 return FAIL;
1871 return OK;
1875 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1877 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1879 EMSG(_(e_listreq));
1880 return FAIL;
1883 i = list_len(l);
1884 if (semicolon == 0 && var_count < i)
1886 EMSG(_("E687: Less targets than List items"));
1887 return FAIL;
1889 if (var_count - semicolon > i)
1891 EMSG(_("E688: More targets than List items"));
1892 return FAIL;
1895 item = l->lv_first;
1896 while (*arg != ']')
1898 arg = skipwhite(arg + 1);
1899 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1900 item = item->li_next;
1901 if (arg == NULL)
1902 return FAIL;
1904 arg = skipwhite(arg);
1905 if (*arg == ';')
1907 /* Put the rest of the list (may be empty) in the var after ';'.
1908 * Create a new list for this. */
1909 l = list_alloc();
1910 if (l == NULL)
1911 return FAIL;
1912 while (item != NULL)
1914 list_append_tv(l, &item->li_tv);
1915 item = item->li_next;
1918 ltv.v_type = VAR_LIST;
1919 ltv.v_lock = 0;
1920 ltv.vval.v_list = l;
1921 l->lv_refcount = 1;
1923 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1924 (char_u *)"]", nextchars);
1925 clear_tv(&ltv);
1926 if (arg == NULL)
1927 return FAIL;
1928 break;
1930 else if (*arg != ',' && *arg != ']')
1932 EMSG2(_(e_intern2), "ex_let_vars()");
1933 return FAIL;
1937 return OK;
1941 * Skip over assignable variable "var" or list of variables "[var, var]".
1942 * Used for ":let varvar = expr" and ":for varvar in expr".
1943 * For "[var, var]" increment "*var_count" for each variable.
1944 * for "[var, var; var]" set "semicolon".
1945 * Return NULL for an error.
1947 static char_u *
1948 skip_var_list(arg, var_count, semicolon)
1949 char_u *arg;
1950 int *var_count;
1951 int *semicolon;
1953 char_u *p, *s;
1955 if (*arg == '[')
1957 /* "[var, var]": find the matching ']'. */
1958 p = arg;
1959 for (;;)
1961 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
1962 s = skip_var_one(p);
1963 if (s == p)
1965 EMSG2(_(e_invarg2), p);
1966 return NULL;
1968 ++*var_count;
1970 p = skipwhite(s);
1971 if (*p == ']')
1972 break;
1973 else if (*p == ';')
1975 if (*semicolon == 1)
1977 EMSG(_("Double ; in list of variables"));
1978 return NULL;
1980 *semicolon = 1;
1982 else if (*p != ',')
1984 EMSG2(_(e_invarg2), p);
1985 return NULL;
1988 return p + 1;
1990 else
1991 return skip_var_one(arg);
1995 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
1996 * l[idx].
1998 static char_u *
1999 skip_var_one(arg)
2000 char_u *arg;
2002 if (*arg == '@' && arg[1] != NUL)
2003 return arg + 2;
2004 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
2005 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2009 * List variables for hashtab "ht" with prefix "prefix".
2010 * If "empty" is TRUE also list NULL strings as empty strings.
2012 static void
2013 list_hashtable_vars(ht, prefix, empty, first)
2014 hashtab_T *ht;
2015 char_u *prefix;
2016 int empty;
2017 int *first;
2019 hashitem_T *hi;
2020 dictitem_T *di;
2021 int todo;
2023 todo = (int)ht->ht_used;
2024 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
2026 if (!HASHITEM_EMPTY(hi))
2028 --todo;
2029 di = HI2DI(hi);
2030 if (empty || di->di_tv.v_type != VAR_STRING
2031 || di->di_tv.vval.v_string != NULL)
2032 list_one_var(di, prefix, first);
2038 * List global variables.
2040 static void
2041 list_glob_vars(first)
2042 int *first;
2044 list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
2048 * List buffer variables.
2050 static void
2051 list_buf_vars(first)
2052 int *first;
2054 char_u numbuf[NUMBUFLEN];
2056 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:",
2057 TRUE, first);
2059 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
2060 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
2061 numbuf, first);
2065 * List window variables.
2067 static void
2068 list_win_vars(first)
2069 int *first;
2071 list_hashtable_vars(&curwin->w_vars.dv_hashtab,
2072 (char_u *)"w:", TRUE, first);
2075 #ifdef FEAT_WINDOWS
2077 * List tab page variables.
2079 static void
2080 list_tab_vars(first)
2081 int *first;
2083 list_hashtable_vars(&curtab->tp_vars.dv_hashtab,
2084 (char_u *)"t:", TRUE, first);
2086 #endif
2089 * List Vim variables.
2091 static void
2092 list_vim_vars(first)
2093 int *first;
2095 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2099 * List script-local variables, if there is a script.
2101 static void
2102 list_script_vars(first)
2103 int *first;
2105 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2106 list_hashtable_vars(&SCRIPT_VARS(current_SID),
2107 (char_u *)"s:", FALSE, first);
2111 * List function variables, if there is a function.
2113 static void
2114 list_func_vars(first)
2115 int *first;
2117 if (current_funccal != NULL)
2118 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2119 (char_u *)"l:", FALSE, first);
2123 * List variables in "arg".
2125 static char_u *
2126 list_arg_vars(eap, arg, first)
2127 exarg_T *eap;
2128 char_u *arg;
2129 int *first;
2131 int error = FALSE;
2132 int len;
2133 char_u *name;
2134 char_u *name_start;
2135 char_u *arg_subsc;
2136 char_u *tofree;
2137 typval_T tv;
2139 while (!ends_excmd(*arg) && !got_int)
2141 if (error || eap->skip)
2143 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2144 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2146 emsg_severe = TRUE;
2147 EMSG(_(e_trailing));
2148 break;
2151 else
2153 /* get_name_len() takes care of expanding curly braces */
2154 name_start = name = arg;
2155 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2156 if (len <= 0)
2158 /* This is mainly to keep test 49 working: when expanding
2159 * curly braces fails overrule the exception error message. */
2160 if (len < 0 && !aborting())
2162 emsg_severe = TRUE;
2163 EMSG2(_(e_invarg2), arg);
2164 break;
2166 error = TRUE;
2168 else
2170 if (tofree != NULL)
2171 name = tofree;
2172 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2173 error = TRUE;
2174 else
2176 /* handle d.key, l[idx], f(expr) */
2177 arg_subsc = arg;
2178 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2179 error = TRUE;
2180 else
2182 if (arg == arg_subsc && len == 2 && name[1] == ':')
2184 switch (*name)
2186 case 'g': list_glob_vars(first); break;
2187 case 'b': list_buf_vars(first); break;
2188 case 'w': list_win_vars(first); break;
2189 #ifdef FEAT_WINDOWS
2190 case 't': list_tab_vars(first); break;
2191 #endif
2192 case 'v': list_vim_vars(first); break;
2193 case 's': list_script_vars(first); break;
2194 case 'l': list_func_vars(first); break;
2195 default:
2196 EMSG2(_("E738: Can't list variables for %s"), name);
2199 else
2201 char_u numbuf[NUMBUFLEN];
2202 char_u *tf;
2203 int c;
2204 char_u *s;
2206 s = echo_string(&tv, &tf, numbuf, 0);
2207 c = *arg;
2208 *arg = NUL;
2209 list_one_var_a((char_u *)"",
2210 arg == arg_subsc ? name : name_start,
2211 tv.v_type,
2212 s == NULL ? (char_u *)"" : s,
2213 first);
2214 *arg = c;
2215 vim_free(tf);
2217 clear_tv(&tv);
2222 vim_free(tofree);
2225 arg = skipwhite(arg);
2228 return arg;
2232 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2233 * Returns a pointer to the char just after the var name.
2234 * Returns NULL if there is an error.
2236 static char_u *
2237 ex_let_one(arg, tv, copy, endchars, op)
2238 char_u *arg; /* points to variable name */
2239 typval_T *tv; /* value to assign to variable */
2240 int copy; /* copy value from "tv" */
2241 char_u *endchars; /* valid chars after variable name or NULL */
2242 char_u *op; /* "+", "-", "." or NULL*/
2244 int c1;
2245 char_u *name;
2246 char_u *p;
2247 char_u *arg_end = NULL;
2248 int len;
2249 int opt_flags;
2250 char_u *tofree = NULL;
2253 * ":let $VAR = expr": Set environment variable.
2255 if (*arg == '$')
2257 /* Find the end of the name. */
2258 ++arg;
2259 name = arg;
2260 len = get_env_len(&arg);
2261 if (len == 0)
2262 EMSG2(_(e_invarg2), name - 1);
2263 else
2265 if (op != NULL && (*op == '+' || *op == '-'))
2266 EMSG2(_(e_letwrong), op);
2267 else if (endchars != NULL
2268 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2269 EMSG(_(e_letunexp));
2270 else
2272 c1 = name[len];
2273 name[len] = NUL;
2274 p = get_tv_string_chk(tv);
2275 if (p != NULL && op != NULL && *op == '.')
2277 int mustfree = FALSE;
2278 char_u *s = vim_getenv(name, &mustfree);
2280 if (s != NULL)
2282 p = tofree = concat_str(s, p);
2283 if (mustfree)
2284 vim_free(s);
2287 if (p != NULL)
2289 vim_setenv(name, p);
2290 if (STRICMP(name, "HOME") == 0)
2291 init_homedir();
2292 else if (didset_vim && STRICMP(name, "VIM") == 0)
2293 didset_vim = FALSE;
2294 else if (didset_vimruntime
2295 && STRICMP(name, "VIMRUNTIME") == 0)
2296 didset_vimruntime = FALSE;
2297 arg_end = arg;
2299 name[len] = c1;
2300 vim_free(tofree);
2306 * ":let &option = expr": Set option value.
2307 * ":let &l:option = expr": Set local option value.
2308 * ":let &g:option = expr": Set global option value.
2310 else if (*arg == '&')
2312 /* Find the end of the name. */
2313 p = find_option_end(&arg, &opt_flags);
2314 if (p == NULL || (endchars != NULL
2315 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2316 EMSG(_(e_letunexp));
2317 else
2319 long n;
2320 int opt_type;
2321 long numval;
2322 char_u *stringval = NULL;
2323 char_u *s;
2325 c1 = *p;
2326 *p = NUL;
2328 n = get_tv_number(tv);
2329 s = get_tv_string_chk(tv); /* != NULL if number or string */
2330 if (s != NULL && op != NULL && *op != '=')
2332 opt_type = get_option_value(arg, &numval,
2333 &stringval, opt_flags);
2334 if ((opt_type == 1 && *op == '.')
2335 || (opt_type == 0 && *op != '.'))
2336 EMSG2(_(e_letwrong), op);
2337 else
2339 if (opt_type == 1) /* number */
2341 if (*op == '+')
2342 n = numval + n;
2343 else
2344 n = numval - n;
2346 else if (opt_type == 0 && stringval != NULL) /* string */
2348 s = concat_str(stringval, s);
2349 vim_free(stringval);
2350 stringval = s;
2354 if (s != NULL)
2356 set_option_value(arg, n, s, opt_flags);
2357 arg_end = p;
2359 *p = c1;
2360 vim_free(stringval);
2365 * ":let @r = expr": Set register contents.
2367 else if (*arg == '@')
2369 ++arg;
2370 if (op != NULL && (*op == '+' || *op == '-'))
2371 EMSG2(_(e_letwrong), op);
2372 else if (endchars != NULL
2373 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2374 EMSG(_(e_letunexp));
2375 else
2377 char_u *ptofree = NULL;
2378 char_u *s;
2380 p = get_tv_string_chk(tv);
2381 if (p != NULL && op != NULL && *op == '.')
2383 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2384 if (s != NULL)
2386 p = ptofree = concat_str(s, p);
2387 vim_free(s);
2390 if (p != NULL)
2392 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2393 arg_end = arg + 1;
2395 vim_free(ptofree);
2400 * ":let var = expr": Set internal variable.
2401 * ":let {expr} = expr": Idem, name made with curly braces
2403 else if (eval_isnamec1(*arg) || *arg == '{')
2405 lval_T lv;
2407 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2408 if (p != NULL && lv.ll_name != NULL)
2410 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2411 EMSG(_(e_letunexp));
2412 else
2414 set_var_lval(&lv, p, tv, copy, op);
2415 arg_end = p;
2418 clear_lval(&lv);
2421 else
2422 EMSG2(_(e_invarg2), arg);
2424 return arg_end;
2428 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2430 static int
2431 check_changedtick(arg)
2432 char_u *arg;
2434 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2436 EMSG2(_(e_readonlyvar), arg);
2437 return TRUE;
2439 return FALSE;
2443 * Get an lval: variable, Dict item or List item that can be assigned a value
2444 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2445 * "name.key", "name.key[expr]" etc.
2446 * Indexing only works if "name" is an existing List or Dictionary.
2447 * "name" points to the start of the name.
2448 * If "rettv" is not NULL it points to the value to be assigned.
2449 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2450 * wrong; must end in space or cmd separator.
2452 * Returns a pointer to just after the name, including indexes.
2453 * When an evaluation error occurs "lp->ll_name" is NULL;
2454 * Returns NULL for a parsing error. Still need to free items in "lp"!
2456 static char_u *
2457 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2458 char_u *name;
2459 typval_T *rettv;
2460 lval_T *lp;
2461 int unlet;
2462 int skip;
2463 int quiet; /* don't give error messages */
2464 int fne_flags; /* flags for find_name_end() */
2466 char_u *p;
2467 char_u *expr_start, *expr_end;
2468 int cc;
2469 dictitem_T *v;
2470 typval_T var1;
2471 typval_T var2;
2472 int empty1 = FALSE;
2473 listitem_T *ni;
2474 char_u *key = NULL;
2475 int len;
2476 hashtab_T *ht;
2478 /* Clear everything in "lp". */
2479 vim_memset(lp, 0, sizeof(lval_T));
2481 if (skip)
2483 /* When skipping just find the end of the name. */
2484 lp->ll_name = name;
2485 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2488 /* Find the end of the name. */
2489 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2490 if (expr_start != NULL)
2492 /* Don't expand the name when we already know there is an error. */
2493 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2494 && *p != '[' && *p != '.')
2496 EMSG(_(e_trailing));
2497 return NULL;
2500 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2501 if (lp->ll_exp_name == NULL)
2503 /* Report an invalid expression in braces, unless the
2504 * expression evaluation has been cancelled due to an
2505 * aborting error, an interrupt, or an exception. */
2506 if (!aborting() && !quiet)
2508 emsg_severe = TRUE;
2509 EMSG2(_(e_invarg2), name);
2510 return NULL;
2513 lp->ll_name = lp->ll_exp_name;
2515 else
2516 lp->ll_name = name;
2518 /* Without [idx] or .key we are done. */
2519 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2520 return p;
2522 cc = *p;
2523 *p = NUL;
2524 v = find_var(lp->ll_name, &ht);
2525 if (v == NULL && !quiet)
2526 EMSG2(_(e_undefvar), lp->ll_name);
2527 *p = cc;
2528 if (v == NULL)
2529 return NULL;
2532 * Loop until no more [idx] or .key is following.
2534 lp->ll_tv = &v->di_tv;
2535 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2537 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2538 && !(lp->ll_tv->v_type == VAR_DICT
2539 && lp->ll_tv->vval.v_dict != NULL))
2541 if (!quiet)
2542 EMSG(_("E689: Can only index a List or Dictionary"));
2543 return NULL;
2545 if (lp->ll_range)
2547 if (!quiet)
2548 EMSG(_("E708: [:] must come last"));
2549 return NULL;
2552 len = -1;
2553 if (*p == '.')
2555 key = p + 1;
2556 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2558 if (len == 0)
2560 if (!quiet)
2561 EMSG(_(e_emptykey));
2562 return NULL;
2564 p = key + len;
2566 else
2568 /* Get the index [expr] or the first index [expr: ]. */
2569 p = skipwhite(p + 1);
2570 if (*p == ':')
2571 empty1 = TRUE;
2572 else
2574 empty1 = FALSE;
2575 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2576 return NULL;
2577 if (get_tv_string_chk(&var1) == NULL)
2579 /* not a number or string */
2580 clear_tv(&var1);
2581 return NULL;
2585 /* Optionally get the second index [ :expr]. */
2586 if (*p == ':')
2588 if (lp->ll_tv->v_type == VAR_DICT)
2590 if (!quiet)
2591 EMSG(_(e_dictrange));
2592 if (!empty1)
2593 clear_tv(&var1);
2594 return NULL;
2596 if (rettv != NULL && (rettv->v_type != VAR_LIST
2597 || rettv->vval.v_list == NULL))
2599 if (!quiet)
2600 EMSG(_("E709: [:] requires a List value"));
2601 if (!empty1)
2602 clear_tv(&var1);
2603 return NULL;
2605 p = skipwhite(p + 1);
2606 if (*p == ']')
2607 lp->ll_empty2 = TRUE;
2608 else
2610 lp->ll_empty2 = FALSE;
2611 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2613 if (!empty1)
2614 clear_tv(&var1);
2615 return NULL;
2617 if (get_tv_string_chk(&var2) == NULL)
2619 /* not a number or string */
2620 if (!empty1)
2621 clear_tv(&var1);
2622 clear_tv(&var2);
2623 return NULL;
2626 lp->ll_range = TRUE;
2628 else
2629 lp->ll_range = FALSE;
2631 if (*p != ']')
2633 if (!quiet)
2634 EMSG(_(e_missbrac));
2635 if (!empty1)
2636 clear_tv(&var1);
2637 if (lp->ll_range && !lp->ll_empty2)
2638 clear_tv(&var2);
2639 return NULL;
2642 /* Skip to past ']'. */
2643 ++p;
2646 if (lp->ll_tv->v_type == VAR_DICT)
2648 if (len == -1)
2650 /* "[key]": get key from "var1" */
2651 key = get_tv_string(&var1); /* is number or string */
2652 if (*key == NUL)
2654 if (!quiet)
2655 EMSG(_(e_emptykey));
2656 clear_tv(&var1);
2657 return NULL;
2660 lp->ll_list = NULL;
2661 lp->ll_dict = lp->ll_tv->vval.v_dict;
2662 lp->ll_di = dict_find(lp->ll_dict, key, len);
2663 if (lp->ll_di == NULL)
2665 /* Key does not exist in dict: may need to add it. */
2666 if (*p == '[' || *p == '.' || unlet)
2668 if (!quiet)
2669 EMSG2(_(e_dictkey), key);
2670 if (len == -1)
2671 clear_tv(&var1);
2672 return NULL;
2674 if (len == -1)
2675 lp->ll_newkey = vim_strsave(key);
2676 else
2677 lp->ll_newkey = vim_strnsave(key, len);
2678 if (len == -1)
2679 clear_tv(&var1);
2680 if (lp->ll_newkey == NULL)
2681 p = NULL;
2682 break;
2684 if (len == -1)
2685 clear_tv(&var1);
2686 lp->ll_tv = &lp->ll_di->di_tv;
2688 else
2691 * Get the number and item for the only or first index of the List.
2693 if (empty1)
2694 lp->ll_n1 = 0;
2695 else
2697 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2698 clear_tv(&var1);
2700 lp->ll_dict = NULL;
2701 lp->ll_list = lp->ll_tv->vval.v_list;
2702 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2703 if (lp->ll_li == NULL)
2705 if (lp->ll_n1 < 0)
2707 lp->ll_n1 = 0;
2708 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2711 if (lp->ll_li == NULL)
2713 if (lp->ll_range && !lp->ll_empty2)
2714 clear_tv(&var2);
2715 return NULL;
2719 * May need to find the item or absolute index for the second
2720 * index of a range.
2721 * When no index given: "lp->ll_empty2" is TRUE.
2722 * Otherwise "lp->ll_n2" is set to the second index.
2724 if (lp->ll_range && !lp->ll_empty2)
2726 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2727 clear_tv(&var2);
2728 if (lp->ll_n2 < 0)
2730 ni = list_find(lp->ll_list, lp->ll_n2);
2731 if (ni == NULL)
2732 return NULL;
2733 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2736 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2737 if (lp->ll_n1 < 0)
2738 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2739 if (lp->ll_n2 < lp->ll_n1)
2740 return NULL;
2743 lp->ll_tv = &lp->ll_li->li_tv;
2747 return p;
2751 * Clear lval "lp" that was filled by get_lval().
2753 static void
2754 clear_lval(lp)
2755 lval_T *lp;
2757 vim_free(lp->ll_exp_name);
2758 vim_free(lp->ll_newkey);
2762 * Set a variable that was parsed by get_lval() to "rettv".
2763 * "endp" points to just after the parsed name.
2764 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2766 static void
2767 set_var_lval(lp, endp, rettv, copy, op)
2768 lval_T *lp;
2769 char_u *endp;
2770 typval_T *rettv;
2771 int copy;
2772 char_u *op;
2774 int cc;
2775 listitem_T *ri;
2776 dictitem_T *di;
2778 if (lp->ll_tv == NULL)
2780 if (!check_changedtick(lp->ll_name))
2782 cc = *endp;
2783 *endp = NUL;
2784 if (op != NULL && *op != '=')
2786 typval_T tv;
2788 /* handle +=, -= and .= */
2789 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2790 &tv, TRUE) == OK)
2792 if (tv_op(&tv, rettv, op) == OK)
2793 set_var(lp->ll_name, &tv, FALSE);
2794 clear_tv(&tv);
2797 else
2798 set_var(lp->ll_name, rettv, copy);
2799 *endp = cc;
2802 else if (tv_check_lock(lp->ll_newkey == NULL
2803 ? lp->ll_tv->v_lock
2804 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2806 else if (lp->ll_range)
2809 * Assign the List values to the list items.
2811 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2813 if (op != NULL && *op != '=')
2814 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2815 else
2817 clear_tv(&lp->ll_li->li_tv);
2818 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2820 ri = ri->li_next;
2821 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2822 break;
2823 if (lp->ll_li->li_next == NULL)
2825 /* Need to add an empty item. */
2826 if (list_append_number(lp->ll_list, 0) == FAIL)
2828 ri = NULL;
2829 break;
2832 lp->ll_li = lp->ll_li->li_next;
2833 ++lp->ll_n1;
2835 if (ri != NULL)
2836 EMSG(_("E710: List value has more items than target"));
2837 else if (lp->ll_empty2
2838 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2839 : lp->ll_n1 != lp->ll_n2)
2840 EMSG(_("E711: List value has not enough items"));
2842 else
2845 * Assign to a List or Dictionary item.
2847 if (lp->ll_newkey != NULL)
2849 if (op != NULL && *op != '=')
2851 EMSG2(_(e_letwrong), op);
2852 return;
2855 /* Need to add an item to the Dictionary. */
2856 di = dictitem_alloc(lp->ll_newkey);
2857 if (di == NULL)
2858 return;
2859 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2861 vim_free(di);
2862 return;
2864 lp->ll_tv = &di->di_tv;
2866 else if (op != NULL && *op != '=')
2868 tv_op(lp->ll_tv, rettv, op);
2869 return;
2871 else
2872 clear_tv(lp->ll_tv);
2875 * Assign the value to the variable or list item.
2877 if (copy)
2878 copy_tv(rettv, lp->ll_tv);
2879 else
2881 *lp->ll_tv = *rettv;
2882 lp->ll_tv->v_lock = 0;
2883 init_tv(rettv);
2889 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2890 * Returns OK or FAIL.
2892 static int
2893 tv_op(tv1, tv2, op)
2894 typval_T *tv1;
2895 typval_T *tv2;
2896 char_u *op;
2898 long n;
2899 char_u numbuf[NUMBUFLEN];
2900 char_u *s;
2902 /* Can't do anything with a Funcref or a Dict on the right. */
2903 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2905 switch (tv1->v_type)
2907 case VAR_DICT:
2908 case VAR_FUNC:
2909 break;
2911 case VAR_LIST:
2912 if (*op != '+' || tv2->v_type != VAR_LIST)
2913 break;
2914 /* List += List */
2915 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2916 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2917 return OK;
2919 case VAR_NUMBER:
2920 case VAR_STRING:
2921 if (tv2->v_type == VAR_LIST)
2922 break;
2923 if (*op == '+' || *op == '-')
2925 /* nr += nr or nr -= nr*/
2926 n = get_tv_number(tv1);
2927 #ifdef FEAT_FLOAT
2928 if (tv2->v_type == VAR_FLOAT)
2930 float_T f = n;
2932 if (*op == '+')
2933 f += tv2->vval.v_float;
2934 else
2935 f -= tv2->vval.v_float;
2936 clear_tv(tv1);
2937 tv1->v_type = VAR_FLOAT;
2938 tv1->vval.v_float = f;
2940 else
2941 #endif
2943 if (*op == '+')
2944 n += get_tv_number(tv2);
2945 else
2946 n -= get_tv_number(tv2);
2947 clear_tv(tv1);
2948 tv1->v_type = VAR_NUMBER;
2949 tv1->vval.v_number = n;
2952 else
2954 if (tv2->v_type == VAR_FLOAT)
2955 break;
2957 /* str .= str */
2958 s = get_tv_string(tv1);
2959 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2960 clear_tv(tv1);
2961 tv1->v_type = VAR_STRING;
2962 tv1->vval.v_string = s;
2964 return OK;
2966 #ifdef FEAT_FLOAT
2967 case VAR_FLOAT:
2969 float_T f;
2971 if (*op == '.' || (tv2->v_type != VAR_FLOAT
2972 && tv2->v_type != VAR_NUMBER
2973 && tv2->v_type != VAR_STRING))
2974 break;
2975 if (tv2->v_type == VAR_FLOAT)
2976 f = tv2->vval.v_float;
2977 else
2978 f = get_tv_number(tv2);
2979 if (*op == '+')
2980 tv1->vval.v_float += f;
2981 else
2982 tv1->vval.v_float -= f;
2984 return OK;
2985 #endif
2989 EMSG2(_(e_letwrong), op);
2990 return FAIL;
2994 * Add a watcher to a list.
2996 static void
2997 list_add_watch(l, lw)
2998 list_T *l;
2999 listwatch_T *lw;
3001 lw->lw_next = l->lv_watch;
3002 l->lv_watch = lw;
3006 * Remove a watcher from a list.
3007 * No warning when it isn't found...
3009 static void
3010 list_rem_watch(l, lwrem)
3011 list_T *l;
3012 listwatch_T *lwrem;
3014 listwatch_T *lw, **lwp;
3016 lwp = &l->lv_watch;
3017 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3019 if (lw == lwrem)
3021 *lwp = lw->lw_next;
3022 break;
3024 lwp = &lw->lw_next;
3029 * Just before removing an item from a list: advance watchers to the next
3030 * item.
3032 static void
3033 list_fix_watch(l, item)
3034 list_T *l;
3035 listitem_T *item;
3037 listwatch_T *lw;
3039 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3040 if (lw->lw_item == item)
3041 lw->lw_item = item->li_next;
3045 * Evaluate the expression used in a ":for var in expr" command.
3046 * "arg" points to "var".
3047 * Set "*errp" to TRUE for an error, FALSE otherwise;
3048 * Return a pointer that holds the info. Null when there is an error.
3050 void *
3051 eval_for_line(arg, errp, nextcmdp, skip)
3052 char_u *arg;
3053 int *errp;
3054 char_u **nextcmdp;
3055 int skip;
3057 forinfo_T *fi;
3058 char_u *expr;
3059 typval_T tv;
3060 list_T *l;
3062 *errp = TRUE; /* default: there is an error */
3064 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
3065 if (fi == NULL)
3066 return NULL;
3068 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
3069 if (expr == NULL)
3070 return fi;
3072 expr = skipwhite(expr);
3073 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
3075 EMSG(_("E690: Missing \"in\" after :for"));
3076 return fi;
3079 if (skip)
3080 ++emsg_skip;
3081 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
3083 *errp = FALSE;
3084 if (!skip)
3086 l = tv.vval.v_list;
3087 if (tv.v_type != VAR_LIST || l == NULL)
3089 EMSG(_(e_listreq));
3090 clear_tv(&tv);
3092 else
3094 /* No need to increment the refcount, it's already set for the
3095 * list being used in "tv". */
3096 fi->fi_list = l;
3097 list_add_watch(l, &fi->fi_lw);
3098 fi->fi_lw.lw_item = l->lv_first;
3102 if (skip)
3103 --emsg_skip;
3105 return fi;
3109 * Use the first item in a ":for" list. Advance to the next.
3110 * Assign the values to the variable (list). "arg" points to the first one.
3111 * Return TRUE when a valid item was found, FALSE when at end of list or
3112 * something wrong.
3115 next_for_item(fi_void, arg)
3116 void *fi_void;
3117 char_u *arg;
3119 forinfo_T *fi = (forinfo_T *)fi_void;
3120 int result;
3121 listitem_T *item;
3123 item = fi->fi_lw.lw_item;
3124 if (item == NULL)
3125 result = FALSE;
3126 else
3128 fi->fi_lw.lw_item = item->li_next;
3129 result = (ex_let_vars(arg, &item->li_tv, TRUE,
3130 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3132 return result;
3136 * Free the structure used to store info used by ":for".
3138 void
3139 free_for_info(fi_void)
3140 void *fi_void;
3142 forinfo_T *fi = (forinfo_T *)fi_void;
3144 if (fi != NULL && fi->fi_list != NULL)
3146 list_rem_watch(fi->fi_list, &fi->fi_lw);
3147 list_unref(fi->fi_list);
3149 vim_free(fi);
3152 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3154 void
3155 set_context_for_expression(xp, arg, cmdidx)
3156 expand_T *xp;
3157 char_u *arg;
3158 cmdidx_T cmdidx;
3160 int got_eq = FALSE;
3161 int c;
3162 char_u *p;
3164 if (cmdidx == CMD_let)
3166 xp->xp_context = EXPAND_USER_VARS;
3167 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3169 /* ":let var1 var2 ...": find last space. */
3170 for (p = arg + STRLEN(arg); p >= arg; )
3172 xp->xp_pattern = p;
3173 mb_ptr_back(arg, p);
3174 if (vim_iswhite(*p))
3175 break;
3177 return;
3180 else
3181 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3182 : EXPAND_EXPRESSION;
3183 while ((xp->xp_pattern = vim_strpbrk(arg,
3184 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3186 c = *xp->xp_pattern;
3187 if (c == '&')
3189 c = xp->xp_pattern[1];
3190 if (c == '&')
3192 ++xp->xp_pattern;
3193 xp->xp_context = cmdidx != CMD_let || got_eq
3194 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3196 else if (c != ' ')
3198 xp->xp_context = EXPAND_SETTINGS;
3199 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3200 xp->xp_pattern += 2;
3204 else if (c == '$')
3206 /* environment variable */
3207 xp->xp_context = EXPAND_ENV_VARS;
3209 else if (c == '=')
3211 got_eq = TRUE;
3212 xp->xp_context = EXPAND_EXPRESSION;
3214 else if (c == '<'
3215 && xp->xp_context == EXPAND_FUNCTIONS
3216 && vim_strchr(xp->xp_pattern, '(') == NULL)
3218 /* Function name can start with "<SNR>" */
3219 break;
3221 else if (cmdidx != CMD_let || got_eq)
3223 if (c == '"') /* string */
3225 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3226 if (c == '\\' && xp->xp_pattern[1] != NUL)
3227 ++xp->xp_pattern;
3228 xp->xp_context = EXPAND_NOTHING;
3230 else if (c == '\'') /* literal string */
3232 /* Trick: '' is like stopping and starting a literal string. */
3233 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3234 /* skip */ ;
3235 xp->xp_context = EXPAND_NOTHING;
3237 else if (c == '|')
3239 if (xp->xp_pattern[1] == '|')
3241 ++xp->xp_pattern;
3242 xp->xp_context = EXPAND_EXPRESSION;
3244 else
3245 xp->xp_context = EXPAND_COMMANDS;
3247 else
3248 xp->xp_context = EXPAND_EXPRESSION;
3250 else
3251 /* Doesn't look like something valid, expand as an expression
3252 * anyway. */
3253 xp->xp_context = EXPAND_EXPRESSION;
3254 arg = xp->xp_pattern;
3255 if (*arg != NUL)
3256 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3257 /* skip */ ;
3259 xp->xp_pattern = arg;
3262 #endif /* FEAT_CMDL_COMPL */
3265 * ":1,25call func(arg1, arg2)" function call.
3267 void
3268 ex_call(eap)
3269 exarg_T *eap;
3271 char_u *arg = eap->arg;
3272 char_u *startarg;
3273 char_u *name;
3274 char_u *tofree;
3275 int len;
3276 typval_T rettv;
3277 linenr_T lnum;
3278 int doesrange;
3279 int failed = FALSE;
3280 funcdict_T fudi;
3282 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3283 if (fudi.fd_newkey != NULL)
3285 /* Still need to give an error message for missing key. */
3286 EMSG2(_(e_dictkey), fudi.fd_newkey);
3287 vim_free(fudi.fd_newkey);
3289 if (tofree == NULL)
3290 return;
3292 /* Increase refcount on dictionary, it could get deleted when evaluating
3293 * the arguments. */
3294 if (fudi.fd_dict != NULL)
3295 ++fudi.fd_dict->dv_refcount;
3297 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3298 len = (int)STRLEN(tofree);
3299 name = deref_func_name(tofree, &len);
3301 /* Skip white space to allow ":call func ()". Not good, but required for
3302 * backward compatibility. */
3303 startarg = skipwhite(arg);
3304 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3306 if (*startarg != '(')
3308 EMSG2(_("E107: Missing parentheses: %s"), eap->arg);
3309 goto end;
3313 * When skipping, evaluate the function once, to find the end of the
3314 * arguments.
3315 * When the function takes a range, this is discovered after the first
3316 * call, and the loop is broken.
3318 if (eap->skip)
3320 ++emsg_skip;
3321 lnum = eap->line2; /* do it once, also with an invalid range */
3323 else
3324 lnum = eap->line1;
3325 for ( ; lnum <= eap->line2; ++lnum)
3327 if (!eap->skip && eap->addr_count > 0)
3329 curwin->w_cursor.lnum = lnum;
3330 curwin->w_cursor.col = 0;
3332 arg = startarg;
3333 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3334 eap->line1, eap->line2, &doesrange,
3335 !eap->skip, fudi.fd_dict) == FAIL)
3337 failed = TRUE;
3338 break;
3341 /* Handle a function returning a Funcref, Dictionary or List. */
3342 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3344 failed = TRUE;
3345 break;
3348 clear_tv(&rettv);
3349 if (doesrange || eap->skip)
3350 break;
3352 /* Stop when immediately aborting on error, or when an interrupt
3353 * occurred or an exception was thrown but not caught.
3354 * get_func_tv() returned OK, so that the check for trailing
3355 * characters below is executed. */
3356 if (aborting())
3357 break;
3359 if (eap->skip)
3360 --emsg_skip;
3362 if (!failed)
3364 /* Check for trailing illegal characters and a following command. */
3365 if (!ends_excmd(*arg))
3367 emsg_severe = TRUE;
3368 EMSG(_(e_trailing));
3370 else
3371 eap->nextcmd = check_nextcmd(arg);
3374 end:
3375 dict_unref(fudi.fd_dict);
3376 vim_free(tofree);
3380 * ":unlet[!] var1 ... " command.
3382 void
3383 ex_unlet(eap)
3384 exarg_T *eap;
3386 ex_unletlock(eap, eap->arg, 0);
3390 * ":lockvar" and ":unlockvar" commands
3392 void
3393 ex_lockvar(eap)
3394 exarg_T *eap;
3396 char_u *arg = eap->arg;
3397 int deep = 2;
3399 if (eap->forceit)
3400 deep = -1;
3401 else if (vim_isdigit(*arg))
3403 deep = getdigits(&arg);
3404 arg = skipwhite(arg);
3407 ex_unletlock(eap, arg, deep);
3411 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3413 static void
3414 ex_unletlock(eap, argstart, deep)
3415 exarg_T *eap;
3416 char_u *argstart;
3417 int deep;
3419 char_u *arg = argstart;
3420 char_u *name_end;
3421 int error = FALSE;
3422 lval_T lv;
3426 /* Parse the name and find the end. */
3427 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3428 FNE_CHECK_START);
3429 if (lv.ll_name == NULL)
3430 error = TRUE; /* error but continue parsing */
3431 if (name_end == NULL || (!vim_iswhite(*name_end)
3432 && !ends_excmd(*name_end)))
3434 if (name_end != NULL)
3436 emsg_severe = TRUE;
3437 EMSG(_(e_trailing));
3439 if (!(eap->skip || error))
3440 clear_lval(&lv);
3441 break;
3444 if (!error && !eap->skip)
3446 if (eap->cmdidx == CMD_unlet)
3448 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3449 error = TRUE;
3451 else
3453 if (do_lock_var(&lv, name_end, deep,
3454 eap->cmdidx == CMD_lockvar) == FAIL)
3455 error = TRUE;
3459 if (!eap->skip)
3460 clear_lval(&lv);
3462 arg = skipwhite(name_end);
3463 } while (!ends_excmd(*arg));
3465 eap->nextcmd = check_nextcmd(arg);
3468 static int
3469 do_unlet_var(lp, name_end, forceit)
3470 lval_T *lp;
3471 char_u *name_end;
3472 int forceit;
3474 int ret = OK;
3475 int cc;
3477 if (lp->ll_tv == NULL)
3479 cc = *name_end;
3480 *name_end = NUL;
3482 /* Normal name or expanded name. */
3483 if (check_changedtick(lp->ll_name))
3484 ret = FAIL;
3485 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3486 ret = FAIL;
3487 *name_end = cc;
3489 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3490 return FAIL;
3491 else if (lp->ll_range)
3493 listitem_T *li;
3495 /* Delete a range of List items. */
3496 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3498 li = lp->ll_li->li_next;
3499 listitem_remove(lp->ll_list, lp->ll_li);
3500 lp->ll_li = li;
3501 ++lp->ll_n1;
3504 else
3506 if (lp->ll_list != NULL)
3507 /* unlet a List item. */
3508 listitem_remove(lp->ll_list, lp->ll_li);
3509 else
3510 /* unlet a Dictionary item. */
3511 dictitem_remove(lp->ll_dict, lp->ll_di);
3514 return ret;
3518 * "unlet" a variable. Return OK if it existed, FAIL if not.
3519 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3522 do_unlet(name, forceit)
3523 char_u *name;
3524 int forceit;
3526 hashtab_T *ht;
3527 hashitem_T *hi;
3528 char_u *varname;
3529 dictitem_T *di;
3531 ht = find_var_ht(name, &varname);
3532 if (ht != NULL && *varname != NUL)
3534 hi = hash_find(ht, varname);
3535 if (!HASHITEM_EMPTY(hi))
3537 di = HI2DI(hi);
3538 if (var_check_fixed(di->di_flags, name)
3539 || var_check_ro(di->di_flags, name))
3540 return FAIL;
3541 delete_var(ht, hi);
3542 return OK;
3545 if (forceit)
3546 return OK;
3547 EMSG2(_("E108: No such variable: \"%s\""), name);
3548 return FAIL;
3552 * Lock or unlock variable indicated by "lp".
3553 * "deep" is the levels to go (-1 for unlimited);
3554 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3556 static int
3557 do_lock_var(lp, name_end, deep, lock)
3558 lval_T *lp;
3559 char_u *name_end;
3560 int deep;
3561 int lock;
3563 int ret = OK;
3564 int cc;
3565 dictitem_T *di;
3567 if (deep == 0) /* nothing to do */
3568 return OK;
3570 if (lp->ll_tv == NULL)
3572 cc = *name_end;
3573 *name_end = NUL;
3575 /* Normal name or expanded name. */
3576 if (check_changedtick(lp->ll_name))
3577 ret = FAIL;
3578 else
3580 di = find_var(lp->ll_name, NULL);
3581 if (di == NULL)
3582 ret = FAIL;
3583 else
3585 if (lock)
3586 di->di_flags |= DI_FLAGS_LOCK;
3587 else
3588 di->di_flags &= ~DI_FLAGS_LOCK;
3589 item_lock(&di->di_tv, deep, lock);
3592 *name_end = cc;
3594 else if (lp->ll_range)
3596 listitem_T *li = lp->ll_li;
3598 /* (un)lock a range of List items. */
3599 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3601 item_lock(&li->li_tv, deep, lock);
3602 li = li->li_next;
3603 ++lp->ll_n1;
3606 else if (lp->ll_list != NULL)
3607 /* (un)lock a List item. */
3608 item_lock(&lp->ll_li->li_tv, deep, lock);
3609 else
3610 /* un(lock) a Dictionary item. */
3611 item_lock(&lp->ll_di->di_tv, deep, lock);
3613 return ret;
3617 * Lock or unlock an item. "deep" is nr of levels to go.
3619 static void
3620 item_lock(tv, deep, lock)
3621 typval_T *tv;
3622 int deep;
3623 int lock;
3625 static int recurse = 0;
3626 list_T *l;
3627 listitem_T *li;
3628 dict_T *d;
3629 hashitem_T *hi;
3630 int todo;
3632 if (recurse >= DICT_MAXNEST)
3634 EMSG(_("E743: variable nested too deep for (un)lock"));
3635 return;
3637 if (deep == 0)
3638 return;
3639 ++recurse;
3641 /* lock/unlock the item itself */
3642 if (lock)
3643 tv->v_lock |= VAR_LOCKED;
3644 else
3645 tv->v_lock &= ~VAR_LOCKED;
3647 switch (tv->v_type)
3649 case VAR_LIST:
3650 if ((l = tv->vval.v_list) != NULL)
3652 if (lock)
3653 l->lv_lock |= VAR_LOCKED;
3654 else
3655 l->lv_lock &= ~VAR_LOCKED;
3656 if (deep < 0 || deep > 1)
3657 /* recursive: lock/unlock the items the List contains */
3658 for (li = l->lv_first; li != NULL; li = li->li_next)
3659 item_lock(&li->li_tv, deep - 1, lock);
3661 break;
3662 case VAR_DICT:
3663 if ((d = tv->vval.v_dict) != NULL)
3665 if (lock)
3666 d->dv_lock |= VAR_LOCKED;
3667 else
3668 d->dv_lock &= ~VAR_LOCKED;
3669 if (deep < 0 || deep > 1)
3671 /* recursive: lock/unlock the items the List contains */
3672 todo = (int)d->dv_hashtab.ht_used;
3673 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3675 if (!HASHITEM_EMPTY(hi))
3677 --todo;
3678 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3684 --recurse;
3688 * Return TRUE if typeval "tv" is locked: Either that value is locked itself
3689 * or it refers to a List or Dictionary that is locked.
3691 static int
3692 tv_islocked(tv)
3693 typval_T *tv;
3695 return (tv->v_lock & VAR_LOCKED)
3696 || (tv->v_type == VAR_LIST
3697 && tv->vval.v_list != NULL
3698 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3699 || (tv->v_type == VAR_DICT
3700 && tv->vval.v_dict != NULL
3701 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3704 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3706 * Delete all "menutrans_" variables.
3708 void
3709 del_menutrans_vars()
3711 hashitem_T *hi;
3712 int todo;
3714 hash_lock(&globvarht);
3715 todo = (int)globvarht.ht_used;
3716 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3718 if (!HASHITEM_EMPTY(hi))
3720 --todo;
3721 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3722 delete_var(&globvarht, hi);
3725 hash_unlock(&globvarht);
3727 #endif
3729 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3732 * Local string buffer for the next two functions to store a variable name
3733 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3734 * get_user_var_name().
3737 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3739 static char_u *varnamebuf = NULL;
3740 static int varnamebuflen = 0;
3743 * Function to concatenate a prefix and a variable name.
3745 static char_u *
3746 cat_prefix_varname(prefix, name)
3747 int prefix;
3748 char_u *name;
3750 int len;
3752 len = (int)STRLEN(name) + 3;
3753 if (len > varnamebuflen)
3755 vim_free(varnamebuf);
3756 len += 10; /* some additional space */
3757 varnamebuf = alloc(len);
3758 if (varnamebuf == NULL)
3760 varnamebuflen = 0;
3761 return NULL;
3763 varnamebuflen = len;
3765 *varnamebuf = prefix;
3766 varnamebuf[1] = ':';
3767 STRCPY(varnamebuf + 2, name);
3768 return varnamebuf;
3772 * Function given to ExpandGeneric() to obtain the list of user defined
3773 * (global/buffer/window/built-in) variable names.
3775 /*ARGSUSED*/
3776 char_u *
3777 get_user_var_name(xp, idx)
3778 expand_T *xp;
3779 int idx;
3781 static long_u gdone;
3782 static long_u bdone;
3783 static long_u wdone;
3784 #ifdef FEAT_WINDOWS
3785 static long_u tdone;
3786 #endif
3787 static int vidx;
3788 static hashitem_T *hi;
3789 hashtab_T *ht;
3791 if (idx == 0)
3793 gdone = bdone = wdone = vidx = 0;
3794 #ifdef FEAT_WINDOWS
3795 tdone = 0;
3796 #endif
3799 /* Global variables */
3800 if (gdone < globvarht.ht_used)
3802 if (gdone++ == 0)
3803 hi = globvarht.ht_array;
3804 else
3805 ++hi;
3806 while (HASHITEM_EMPTY(hi))
3807 ++hi;
3808 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3809 return cat_prefix_varname('g', hi->hi_key);
3810 return hi->hi_key;
3813 /* b: variables */
3814 ht = &curbuf->b_vars.dv_hashtab;
3815 if (bdone < ht->ht_used)
3817 if (bdone++ == 0)
3818 hi = ht->ht_array;
3819 else
3820 ++hi;
3821 while (HASHITEM_EMPTY(hi))
3822 ++hi;
3823 return cat_prefix_varname('b', hi->hi_key);
3825 if (bdone == ht->ht_used)
3827 ++bdone;
3828 return (char_u *)"b:changedtick";
3831 /* w: variables */
3832 ht = &curwin->w_vars.dv_hashtab;
3833 if (wdone < ht->ht_used)
3835 if (wdone++ == 0)
3836 hi = ht->ht_array;
3837 else
3838 ++hi;
3839 while (HASHITEM_EMPTY(hi))
3840 ++hi;
3841 return cat_prefix_varname('w', hi->hi_key);
3844 #ifdef FEAT_WINDOWS
3845 /* t: variables */
3846 ht = &curtab->tp_vars.dv_hashtab;
3847 if (tdone < ht->ht_used)
3849 if (tdone++ == 0)
3850 hi = ht->ht_array;
3851 else
3852 ++hi;
3853 while (HASHITEM_EMPTY(hi))
3854 ++hi;
3855 return cat_prefix_varname('t', hi->hi_key);
3857 #endif
3859 /* v: variables */
3860 if (vidx < VV_LEN)
3861 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3863 vim_free(varnamebuf);
3864 varnamebuf = NULL;
3865 varnamebuflen = 0;
3866 return NULL;
3869 #endif /* FEAT_CMDL_COMPL */
3872 * types for expressions.
3874 typedef enum
3876 TYPE_UNKNOWN = 0
3877 , TYPE_EQUAL /* == */
3878 , TYPE_NEQUAL /* != */
3879 , TYPE_GREATER /* > */
3880 , TYPE_GEQUAL /* >= */
3881 , TYPE_SMALLER /* < */
3882 , TYPE_SEQUAL /* <= */
3883 , TYPE_MATCH /* =~ */
3884 , TYPE_NOMATCH /* !~ */
3885 } exptype_T;
3888 * The "evaluate" argument: When FALSE, the argument is only parsed but not
3889 * executed. The function may return OK, but the rettv will be of type
3890 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
3894 * Handle zero level expression.
3895 * This calls eval1() and handles error message and nextcmd.
3896 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3897 * Note: "rettv.v_lock" is not set.
3898 * Return OK or FAIL.
3900 static int
3901 eval0(arg, rettv, nextcmd, evaluate)
3902 char_u *arg;
3903 typval_T *rettv;
3904 char_u **nextcmd;
3905 int evaluate;
3907 int ret;
3908 char_u *p;
3910 p = skipwhite(arg);
3911 ret = eval1(&p, rettv, evaluate);
3912 if (ret == FAIL || !ends_excmd(*p))
3914 if (ret != FAIL)
3915 clear_tv(rettv);
3917 * Report the invalid expression unless the expression evaluation has
3918 * been cancelled due to an aborting error, an interrupt, or an
3919 * exception.
3921 if (!aborting())
3922 EMSG2(_(e_invexpr2), arg);
3923 ret = FAIL;
3925 if (nextcmd != NULL)
3926 *nextcmd = check_nextcmd(p);
3928 return ret;
3932 * Handle top level expression:
3933 * expr2 ? expr1 : expr1
3935 * "arg" must point to the first non-white of the expression.
3936 * "arg" is advanced to the next non-white after the recognized expression.
3938 * Note: "rettv.v_lock" is not set.
3940 * Return OK or FAIL.
3942 static int
3943 eval1(arg, rettv, evaluate)
3944 char_u **arg;
3945 typval_T *rettv;
3946 int evaluate;
3948 int result;
3949 typval_T var2;
3952 * Get the first variable.
3954 if (eval2(arg, rettv, evaluate) == FAIL)
3955 return FAIL;
3957 if ((*arg)[0] == '?')
3959 result = FALSE;
3960 if (evaluate)
3962 int error = FALSE;
3964 if (get_tv_number_chk(rettv, &error) != 0)
3965 result = TRUE;
3966 clear_tv(rettv);
3967 if (error)
3968 return FAIL;
3972 * Get the second variable.
3974 *arg = skipwhite(*arg + 1);
3975 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
3976 return FAIL;
3979 * Check for the ":".
3981 if ((*arg)[0] != ':')
3983 EMSG(_("E109: Missing ':' after '?'"));
3984 if (evaluate && result)
3985 clear_tv(rettv);
3986 return FAIL;
3990 * Get the third variable.
3992 *arg = skipwhite(*arg + 1);
3993 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
3995 if (evaluate && result)
3996 clear_tv(rettv);
3997 return FAIL;
3999 if (evaluate && !result)
4000 *rettv = var2;
4003 return OK;
4007 * Handle first level expression:
4008 * expr2 || expr2 || expr2 logical OR
4010 * "arg" must point to the first non-white of the expression.
4011 * "arg" is advanced to the next non-white after the recognized expression.
4013 * Return OK or FAIL.
4015 static int
4016 eval2(arg, rettv, evaluate)
4017 char_u **arg;
4018 typval_T *rettv;
4019 int evaluate;
4021 typval_T var2;
4022 long result;
4023 int first;
4024 int error = FALSE;
4027 * Get the first variable.
4029 if (eval3(arg, rettv, evaluate) == FAIL)
4030 return FAIL;
4033 * Repeat until there is no following "||".
4035 first = TRUE;
4036 result = FALSE;
4037 while ((*arg)[0] == '|' && (*arg)[1] == '|')
4039 if (evaluate && first)
4041 if (get_tv_number_chk(rettv, &error) != 0)
4042 result = TRUE;
4043 clear_tv(rettv);
4044 if (error)
4045 return FAIL;
4046 first = FALSE;
4050 * Get the second variable.
4052 *arg = skipwhite(*arg + 2);
4053 if (eval3(arg, &var2, evaluate && !result) == FAIL)
4054 return FAIL;
4057 * Compute the result.
4059 if (evaluate && !result)
4061 if (get_tv_number_chk(&var2, &error) != 0)
4062 result = TRUE;
4063 clear_tv(&var2);
4064 if (error)
4065 return FAIL;
4067 if (evaluate)
4069 rettv->v_type = VAR_NUMBER;
4070 rettv->vval.v_number = result;
4074 return OK;
4078 * Handle second level expression:
4079 * expr3 && expr3 && expr3 logical AND
4081 * "arg" must point to the first non-white of the expression.
4082 * "arg" is advanced to the next non-white after the recognized expression.
4084 * Return OK or FAIL.
4086 static int
4087 eval3(arg, rettv, evaluate)
4088 char_u **arg;
4089 typval_T *rettv;
4090 int evaluate;
4092 typval_T var2;
4093 long result;
4094 int first;
4095 int error = FALSE;
4098 * Get the first variable.
4100 if (eval4(arg, rettv, evaluate) == FAIL)
4101 return FAIL;
4104 * Repeat until there is no following "&&".
4106 first = TRUE;
4107 result = TRUE;
4108 while ((*arg)[0] == '&' && (*arg)[1] == '&')
4110 if (evaluate && first)
4112 if (get_tv_number_chk(rettv, &error) == 0)
4113 result = FALSE;
4114 clear_tv(rettv);
4115 if (error)
4116 return FAIL;
4117 first = FALSE;
4121 * Get the second variable.
4123 *arg = skipwhite(*arg + 2);
4124 if (eval4(arg, &var2, evaluate && result) == FAIL)
4125 return FAIL;
4128 * Compute the result.
4130 if (evaluate && result)
4132 if (get_tv_number_chk(&var2, &error) == 0)
4133 result = FALSE;
4134 clear_tv(&var2);
4135 if (error)
4136 return FAIL;
4138 if (evaluate)
4140 rettv->v_type = VAR_NUMBER;
4141 rettv->vval.v_number = result;
4145 return OK;
4149 * Handle third level expression:
4150 * var1 == var2
4151 * var1 =~ var2
4152 * var1 != var2
4153 * var1 !~ var2
4154 * var1 > var2
4155 * var1 >= var2
4156 * var1 < var2
4157 * var1 <= var2
4158 * var1 is var2
4159 * var1 isnot var2
4161 * "arg" must point to the first non-white of the expression.
4162 * "arg" is advanced to the next non-white after the recognized expression.
4164 * Return OK or FAIL.
4166 static int
4167 eval4(arg, rettv, evaluate)
4168 char_u **arg;
4169 typval_T *rettv;
4170 int evaluate;
4172 typval_T var2;
4173 char_u *p;
4174 int i;
4175 exptype_T type = TYPE_UNKNOWN;
4176 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4177 int len = 2;
4178 long n1, n2;
4179 char_u *s1, *s2;
4180 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4181 regmatch_T regmatch;
4182 int ic;
4183 char_u *save_cpo;
4186 * Get the first variable.
4188 if (eval5(arg, rettv, evaluate) == FAIL)
4189 return FAIL;
4191 p = *arg;
4192 switch (p[0])
4194 case '=': if (p[1] == '=')
4195 type = TYPE_EQUAL;
4196 else if (p[1] == '~')
4197 type = TYPE_MATCH;
4198 break;
4199 case '!': if (p[1] == '=')
4200 type = TYPE_NEQUAL;
4201 else if (p[1] == '~')
4202 type = TYPE_NOMATCH;
4203 break;
4204 case '>': if (p[1] != '=')
4206 type = TYPE_GREATER;
4207 len = 1;
4209 else
4210 type = TYPE_GEQUAL;
4211 break;
4212 case '<': if (p[1] != '=')
4214 type = TYPE_SMALLER;
4215 len = 1;
4217 else
4218 type = TYPE_SEQUAL;
4219 break;
4220 case 'i': if (p[1] == 's')
4222 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4223 len = 5;
4224 if (!vim_isIDc(p[len]))
4226 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4227 type_is = TRUE;
4230 break;
4234 * If there is a comparative operator, use it.
4236 if (type != TYPE_UNKNOWN)
4238 /* extra question mark appended: ignore case */
4239 if (p[len] == '?')
4241 ic = TRUE;
4242 ++len;
4244 /* extra '#' appended: match case */
4245 else if (p[len] == '#')
4247 ic = FALSE;
4248 ++len;
4250 /* nothing appended: use 'ignorecase' */
4251 else
4252 ic = p_ic;
4255 * Get the second variable.
4257 *arg = skipwhite(p + len);
4258 if (eval5(arg, &var2, evaluate) == FAIL)
4260 clear_tv(rettv);
4261 return FAIL;
4264 if (evaluate)
4266 if (type_is && rettv->v_type != var2.v_type)
4268 /* For "is" a different type always means FALSE, for "notis"
4269 * it means TRUE. */
4270 n1 = (type == TYPE_NEQUAL);
4272 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4274 if (type_is)
4276 n1 = (rettv->v_type == var2.v_type
4277 && rettv->vval.v_list == var2.vval.v_list);
4278 if (type == TYPE_NEQUAL)
4279 n1 = !n1;
4281 else if (rettv->v_type != var2.v_type
4282 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4284 if (rettv->v_type != var2.v_type)
4285 EMSG(_("E691: Can only compare List with List"));
4286 else
4287 EMSG(_("E692: Invalid operation for Lists"));
4288 clear_tv(rettv);
4289 clear_tv(&var2);
4290 return FAIL;
4292 else
4294 /* Compare two Lists for being equal or unequal. */
4295 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
4296 if (type == TYPE_NEQUAL)
4297 n1 = !n1;
4301 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4303 if (type_is)
4305 n1 = (rettv->v_type == var2.v_type
4306 && rettv->vval.v_dict == var2.vval.v_dict);
4307 if (type == TYPE_NEQUAL)
4308 n1 = !n1;
4310 else if (rettv->v_type != var2.v_type
4311 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4313 if (rettv->v_type != var2.v_type)
4314 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4315 else
4316 EMSG(_("E736: Invalid operation for Dictionary"));
4317 clear_tv(rettv);
4318 clear_tv(&var2);
4319 return FAIL;
4321 else
4323 /* Compare two Dictionaries for being equal or unequal. */
4324 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4325 if (type == TYPE_NEQUAL)
4326 n1 = !n1;
4330 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4332 if (rettv->v_type != var2.v_type
4333 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4335 if (rettv->v_type != var2.v_type)
4336 EMSG(_("E693: Can only compare Funcref with Funcref"));
4337 else
4338 EMSG(_("E694: Invalid operation for Funcrefs"));
4339 clear_tv(rettv);
4340 clear_tv(&var2);
4341 return FAIL;
4343 else
4345 /* Compare two Funcrefs for being equal or unequal. */
4346 if (rettv->vval.v_string == NULL
4347 || var2.vval.v_string == NULL)
4348 n1 = FALSE;
4349 else
4350 n1 = STRCMP(rettv->vval.v_string,
4351 var2.vval.v_string) == 0;
4352 if (type == TYPE_NEQUAL)
4353 n1 = !n1;
4357 #ifdef FEAT_FLOAT
4359 * If one of the two variables is a float, compare as a float.
4360 * When using "=~" or "!~", always compare as string.
4362 else if ((rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4363 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4365 float_T f1, f2;
4367 if (rettv->v_type == VAR_FLOAT)
4368 f1 = rettv->vval.v_float;
4369 else
4370 f1 = get_tv_number(rettv);
4371 if (var2.v_type == VAR_FLOAT)
4372 f2 = var2.vval.v_float;
4373 else
4374 f2 = get_tv_number(&var2);
4375 n1 = FALSE;
4376 switch (type)
4378 case TYPE_EQUAL: n1 = (f1 == f2); break;
4379 case TYPE_NEQUAL: n1 = (f1 != f2); break;
4380 case TYPE_GREATER: n1 = (f1 > f2); break;
4381 case TYPE_GEQUAL: n1 = (f1 >= f2); break;
4382 case TYPE_SMALLER: n1 = (f1 < f2); break;
4383 case TYPE_SEQUAL: n1 = (f1 <= f2); break;
4384 case TYPE_UNKNOWN:
4385 case TYPE_MATCH:
4386 case TYPE_NOMATCH: break; /* avoid gcc warning */
4389 #endif
4392 * If one of the two variables is a number, compare as a number.
4393 * When using "=~" or "!~", always compare as string.
4395 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4396 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4398 n1 = get_tv_number(rettv);
4399 n2 = get_tv_number(&var2);
4400 switch (type)
4402 case TYPE_EQUAL: n1 = (n1 == n2); break;
4403 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4404 case TYPE_GREATER: n1 = (n1 > n2); break;
4405 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4406 case TYPE_SMALLER: n1 = (n1 < n2); break;
4407 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4408 case TYPE_UNKNOWN:
4409 case TYPE_MATCH:
4410 case TYPE_NOMATCH: break; /* avoid gcc warning */
4413 else
4415 s1 = get_tv_string_buf(rettv, buf1);
4416 s2 = get_tv_string_buf(&var2, buf2);
4417 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4418 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4419 else
4420 i = 0;
4421 n1 = FALSE;
4422 switch (type)
4424 case TYPE_EQUAL: n1 = (i == 0); break;
4425 case TYPE_NEQUAL: n1 = (i != 0); break;
4426 case TYPE_GREATER: n1 = (i > 0); break;
4427 case TYPE_GEQUAL: n1 = (i >= 0); break;
4428 case TYPE_SMALLER: n1 = (i < 0); break;
4429 case TYPE_SEQUAL: n1 = (i <= 0); break;
4431 case TYPE_MATCH:
4432 case TYPE_NOMATCH:
4433 /* avoid 'l' flag in 'cpoptions' */
4434 save_cpo = p_cpo;
4435 p_cpo = (char_u *)"";
4436 regmatch.regprog = vim_regcomp(s2,
4437 RE_MAGIC + RE_STRING);
4438 regmatch.rm_ic = ic;
4439 if (regmatch.regprog != NULL)
4441 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4442 vim_free(regmatch.regprog);
4443 if (type == TYPE_NOMATCH)
4444 n1 = !n1;
4446 p_cpo = save_cpo;
4447 break;
4449 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4452 clear_tv(rettv);
4453 clear_tv(&var2);
4454 rettv->v_type = VAR_NUMBER;
4455 rettv->vval.v_number = n1;
4459 return OK;
4463 * Handle fourth level expression:
4464 * + number addition
4465 * - number subtraction
4466 * . string concatenation
4468 * "arg" must point to the first non-white of the expression.
4469 * "arg" is advanced to the next non-white after the recognized expression.
4471 * Return OK or FAIL.
4473 static int
4474 eval5(arg, rettv, evaluate)
4475 char_u **arg;
4476 typval_T *rettv;
4477 int evaluate;
4479 typval_T var2;
4480 typval_T var3;
4481 int op;
4482 long n1, n2;
4483 #ifdef FEAT_FLOAT
4484 float_T f1 = 0, f2 = 0;
4485 #endif
4486 char_u *s1, *s2;
4487 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4488 char_u *p;
4491 * Get the first variable.
4493 if (eval6(arg, rettv, evaluate, FALSE) == FAIL)
4494 return FAIL;
4497 * Repeat computing, until no '+', '-' or '.' is following.
4499 for (;;)
4501 op = **arg;
4502 if (op != '+' && op != '-' && op != '.')
4503 break;
4505 if ((op != '+' || rettv->v_type != VAR_LIST)
4506 #ifdef FEAT_FLOAT
4507 && (op == '.' || rettv->v_type != VAR_FLOAT)
4508 #endif
4511 /* For "list + ...", an illegal use of the first operand as
4512 * a number cannot be determined before evaluating the 2nd
4513 * operand: if this is also a list, all is ok.
4514 * For "something . ...", "something - ..." or "non-list + ...",
4515 * we know that the first operand needs to be a string or number
4516 * without evaluating the 2nd operand. So check before to avoid
4517 * side effects after an error. */
4518 if (evaluate && get_tv_string_chk(rettv) == NULL)
4520 clear_tv(rettv);
4521 return FAIL;
4526 * Get the second variable.
4528 *arg = skipwhite(*arg + 1);
4529 if (eval6(arg, &var2, evaluate, op == '.') == FAIL)
4531 clear_tv(rettv);
4532 return FAIL;
4535 if (evaluate)
4538 * Compute the result.
4540 if (op == '.')
4542 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4543 s2 = get_tv_string_buf_chk(&var2, buf2);
4544 if (s2 == NULL) /* type error ? */
4546 clear_tv(rettv);
4547 clear_tv(&var2);
4548 return FAIL;
4550 p = concat_str(s1, s2);
4551 clear_tv(rettv);
4552 rettv->v_type = VAR_STRING;
4553 rettv->vval.v_string = p;
4555 else if (op == '+' && rettv->v_type == VAR_LIST
4556 && var2.v_type == VAR_LIST)
4558 /* concatenate Lists */
4559 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4560 &var3) == FAIL)
4562 clear_tv(rettv);
4563 clear_tv(&var2);
4564 return FAIL;
4566 clear_tv(rettv);
4567 *rettv = var3;
4569 else
4571 int error = FALSE;
4573 #ifdef FEAT_FLOAT
4574 if (rettv->v_type == VAR_FLOAT)
4576 f1 = rettv->vval.v_float;
4577 n1 = 0;
4579 else
4580 #endif
4582 n1 = get_tv_number_chk(rettv, &error);
4583 if (error)
4585 /* This can only happen for "list + non-list". For
4586 * "non-list + ..." or "something - ...", we returned
4587 * before evaluating the 2nd operand. */
4588 clear_tv(rettv);
4589 return FAIL;
4591 #ifdef FEAT_FLOAT
4592 if (var2.v_type == VAR_FLOAT)
4593 f1 = n1;
4594 #endif
4596 #ifdef FEAT_FLOAT
4597 if (var2.v_type == VAR_FLOAT)
4599 f2 = var2.vval.v_float;
4600 n2 = 0;
4602 else
4603 #endif
4605 n2 = get_tv_number_chk(&var2, &error);
4606 if (error)
4608 clear_tv(rettv);
4609 clear_tv(&var2);
4610 return FAIL;
4612 #ifdef FEAT_FLOAT
4613 if (rettv->v_type == VAR_FLOAT)
4614 f2 = n2;
4615 #endif
4617 clear_tv(rettv);
4619 #ifdef FEAT_FLOAT
4620 /* If there is a float on either side the result is a float. */
4621 if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4623 if (op == '+')
4624 f1 = f1 + f2;
4625 else
4626 f1 = f1 - f2;
4627 rettv->v_type = VAR_FLOAT;
4628 rettv->vval.v_float = f1;
4630 else
4631 #endif
4633 if (op == '+')
4634 n1 = n1 + n2;
4635 else
4636 n1 = n1 - n2;
4637 rettv->v_type = VAR_NUMBER;
4638 rettv->vval.v_number = n1;
4641 clear_tv(&var2);
4644 return OK;
4648 * Handle fifth level expression:
4649 * * number multiplication
4650 * / number division
4651 * % number modulo
4653 * "arg" must point to the first non-white of the expression.
4654 * "arg" is advanced to the next non-white after the recognized expression.
4656 * Return OK or FAIL.
4658 static int
4659 eval6(arg, rettv, evaluate, want_string)
4660 char_u **arg;
4661 typval_T *rettv;
4662 int evaluate;
4663 int want_string; /* after "." operator */
4665 typval_T var2;
4666 int op;
4667 long n1, n2;
4668 #ifdef FEAT_FLOAT
4669 int use_float = FALSE;
4670 float_T f1 = 0, f2;
4671 #endif
4672 int error = FALSE;
4675 * Get the first variable.
4677 if (eval7(arg, rettv, evaluate, want_string) == FAIL)
4678 return FAIL;
4681 * Repeat computing, until no '*', '/' or '%' is following.
4683 for (;;)
4685 op = **arg;
4686 if (op != '*' && op != '/' && op != '%')
4687 break;
4689 if (evaluate)
4691 #ifdef FEAT_FLOAT
4692 if (rettv->v_type == VAR_FLOAT)
4694 f1 = rettv->vval.v_float;
4695 use_float = TRUE;
4696 n1 = 0;
4698 else
4699 #endif
4700 n1 = get_tv_number_chk(rettv, &error);
4701 clear_tv(rettv);
4702 if (error)
4703 return FAIL;
4705 else
4706 n1 = 0;
4709 * Get the second variable.
4711 *arg = skipwhite(*arg + 1);
4712 if (eval7(arg, &var2, evaluate, FALSE) == FAIL)
4713 return FAIL;
4715 if (evaluate)
4717 #ifdef FEAT_FLOAT
4718 if (var2.v_type == VAR_FLOAT)
4720 if (!use_float)
4722 f1 = n1;
4723 use_float = TRUE;
4725 f2 = var2.vval.v_float;
4726 n2 = 0;
4728 else
4729 #endif
4731 n2 = get_tv_number_chk(&var2, &error);
4732 clear_tv(&var2);
4733 if (error)
4734 return FAIL;
4735 #ifdef FEAT_FLOAT
4736 if (use_float)
4737 f2 = n2;
4738 #endif
4742 * Compute the result.
4743 * When either side is a float the result is a float.
4745 #ifdef FEAT_FLOAT
4746 if (use_float)
4748 if (op == '*')
4749 f1 = f1 * f2;
4750 else if (op == '/')
4752 /* We rely on the floating point library to handle divide
4753 * by zero to result in "inf" and not a crash. */
4754 f1 = f1 / f2;
4756 else
4758 EMSG(_("E804: Cannot use '%' with Float"));
4759 return FAIL;
4761 rettv->v_type = VAR_FLOAT;
4762 rettv->vval.v_float = f1;
4764 else
4765 #endif
4767 if (op == '*')
4768 n1 = n1 * n2;
4769 else if (op == '/')
4771 if (n2 == 0) /* give an error message? */
4773 if (n1 == 0)
4774 n1 = -0x7fffffffL - 1L; /* similar to NaN */
4775 else if (n1 < 0)
4776 n1 = -0x7fffffffL;
4777 else
4778 n1 = 0x7fffffffL;
4780 else
4781 n1 = n1 / n2;
4783 else
4785 if (n2 == 0) /* give an error message? */
4786 n1 = 0;
4787 else
4788 n1 = n1 % n2;
4790 rettv->v_type = VAR_NUMBER;
4791 rettv->vval.v_number = n1;
4796 return OK;
4800 * Handle sixth level expression:
4801 * number number constant
4802 * "string" string constant
4803 * 'string' literal string constant
4804 * &option-name option value
4805 * @r register contents
4806 * identifier variable value
4807 * function() function call
4808 * $VAR environment variable
4809 * (expression) nested expression
4810 * [expr, expr] List
4811 * {key: val, key: val} Dictionary
4813 * Also handle:
4814 * ! in front logical NOT
4815 * - in front unary minus
4816 * + in front unary plus (ignored)
4817 * trailing [] subscript in String or List
4818 * trailing .name entry in Dictionary
4820 * "arg" must point to the first non-white of the expression.
4821 * "arg" is advanced to the next non-white after the recognized expression.
4823 * Return OK or FAIL.
4825 static int
4826 eval7(arg, rettv, evaluate, want_string)
4827 char_u **arg;
4828 typval_T *rettv;
4829 int evaluate;
4830 int want_string; /* after "." operator */
4832 long n;
4833 int len;
4834 char_u *s;
4835 char_u *start_leader, *end_leader;
4836 int ret = OK;
4837 char_u *alias;
4840 * Initialise variable so that clear_tv() can't mistake this for a
4841 * string and free a string that isn't there.
4843 rettv->v_type = VAR_UNKNOWN;
4846 * Skip '!' and '-' characters. They are handled later.
4848 start_leader = *arg;
4849 while (**arg == '!' || **arg == '-' || **arg == '+')
4850 *arg = skipwhite(*arg + 1);
4851 end_leader = *arg;
4853 switch (**arg)
4856 * Number constant.
4858 case '0':
4859 case '1':
4860 case '2':
4861 case '3':
4862 case '4':
4863 case '5':
4864 case '6':
4865 case '7':
4866 case '8':
4867 case '9':
4869 #ifdef FEAT_FLOAT
4870 char_u *p = skipdigits(*arg + 1);
4871 int get_float = FALSE;
4873 /* We accept a float when the format matches
4874 * "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?". This is very
4875 * strict to avoid backwards compatibility problems.
4876 * Don't look for a float after the "." operator, so that
4877 * ":let vers = 1.2.3" doesn't fail. */
4878 if (!want_string && p[0] == '.' && vim_isdigit(p[1]))
4880 get_float = TRUE;
4881 p = skipdigits(p + 2);
4882 if (*p == 'e' || *p == 'E')
4884 ++p;
4885 if (*p == '-' || *p == '+')
4886 ++p;
4887 if (!vim_isdigit(*p))
4888 get_float = FALSE;
4889 else
4890 p = skipdigits(p + 1);
4892 if (ASCII_ISALPHA(*p) || *p == '.')
4893 get_float = FALSE;
4895 if (get_float)
4897 float_T f;
4899 *arg += string2float(*arg, &f);
4900 if (evaluate)
4902 rettv->v_type = VAR_FLOAT;
4903 rettv->vval.v_float = f;
4906 else
4907 #endif
4909 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4910 *arg += len;
4911 if (evaluate)
4913 rettv->v_type = VAR_NUMBER;
4914 rettv->vval.v_number = n;
4917 break;
4921 * String constant: "string".
4923 case '"': ret = get_string_tv(arg, rettv, evaluate);
4924 break;
4927 * Literal string constant: 'str''ing'.
4929 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
4930 break;
4933 * List: [expr, expr]
4935 case '[': ret = get_list_tv(arg, rettv, evaluate);
4936 break;
4939 * Dictionary: {key: val, key: val}
4941 case '{': ret = get_dict_tv(arg, rettv, evaluate);
4942 break;
4945 * Option value: &name
4947 case '&': ret = get_option_tv(arg, rettv, evaluate);
4948 break;
4951 * Environment variable: $VAR.
4953 case '$': ret = get_env_tv(arg, rettv, evaluate);
4954 break;
4957 * Register contents: @r.
4959 case '@': ++*arg;
4960 if (evaluate)
4962 rettv->v_type = VAR_STRING;
4963 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4965 if (**arg != NUL)
4966 ++*arg;
4967 break;
4970 * nested expression: (expression).
4972 case '(': *arg = skipwhite(*arg + 1);
4973 ret = eval1(arg, rettv, evaluate); /* recursive! */
4974 if (**arg == ')')
4975 ++*arg;
4976 else if (ret == OK)
4978 EMSG(_("E110: Missing ')'"));
4979 clear_tv(rettv);
4980 ret = FAIL;
4982 break;
4984 default: ret = NOTDONE;
4985 break;
4988 if (ret == NOTDONE)
4991 * Must be a variable or function name.
4992 * Can also be a curly-braces kind of name: {expr}.
4994 s = *arg;
4995 len = get_name_len(arg, &alias, evaluate, TRUE);
4996 if (alias != NULL)
4997 s = alias;
4999 if (len <= 0)
5000 ret = FAIL;
5001 else
5003 if (**arg == '(') /* recursive! */
5005 /* If "s" is the name of a variable of type VAR_FUNC
5006 * use its contents. */
5007 s = deref_func_name(s, &len);
5009 /* Invoke the function. */
5010 ret = get_func_tv(s, len, rettv, arg,
5011 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
5012 &len, evaluate, NULL);
5013 /* Stop the expression evaluation when immediately
5014 * aborting on error, or when an interrupt occurred or
5015 * an exception was thrown but not caught. */
5016 if (aborting())
5018 if (ret == OK)
5019 clear_tv(rettv);
5020 ret = FAIL;
5023 else if (evaluate)
5024 ret = get_var_tv(s, len, rettv, TRUE);
5025 else
5026 ret = OK;
5029 if (alias != NULL)
5030 vim_free(alias);
5033 *arg = skipwhite(*arg);
5035 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
5036 * expr(expr). */
5037 if (ret == OK)
5038 ret = handle_subscript(arg, rettv, evaluate, TRUE);
5041 * Apply logical NOT and unary '-', from right to left, ignore '+'.
5043 if (ret == OK && evaluate && end_leader > start_leader)
5045 int error = FALSE;
5046 int val = 0;
5047 #ifdef FEAT_FLOAT
5048 float_T f = 0.0;
5050 if (rettv->v_type == VAR_FLOAT)
5051 f = rettv->vval.v_float;
5052 else
5053 #endif
5054 val = get_tv_number_chk(rettv, &error);
5055 if (error)
5057 clear_tv(rettv);
5058 ret = FAIL;
5060 else
5062 while (end_leader > start_leader)
5064 --end_leader;
5065 if (*end_leader == '!')
5067 #ifdef FEAT_FLOAT
5068 if (rettv->v_type == VAR_FLOAT)
5069 f = !f;
5070 else
5071 #endif
5072 val = !val;
5074 else if (*end_leader == '-')
5076 #ifdef FEAT_FLOAT
5077 if (rettv->v_type == VAR_FLOAT)
5078 f = -f;
5079 else
5080 #endif
5081 val = -val;
5084 #ifdef FEAT_FLOAT
5085 if (rettv->v_type == VAR_FLOAT)
5087 clear_tv(rettv);
5088 rettv->vval.v_float = f;
5090 else
5091 #endif
5093 clear_tv(rettv);
5094 rettv->v_type = VAR_NUMBER;
5095 rettv->vval.v_number = val;
5100 return ret;
5104 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
5105 * "*arg" points to the '[' or '.'.
5106 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
5108 static int
5109 eval_index(arg, rettv, evaluate, verbose)
5110 char_u **arg;
5111 typval_T *rettv;
5112 int evaluate;
5113 int verbose; /* give error messages */
5115 int empty1 = FALSE, empty2 = FALSE;
5116 typval_T var1, var2;
5117 long n1, n2 = 0;
5118 long len = -1;
5119 int range = FALSE;
5120 char_u *s;
5121 char_u *key = NULL;
5123 if (rettv->v_type == VAR_FUNC
5124 #ifdef FEAT_FLOAT
5125 || rettv->v_type == VAR_FLOAT
5126 #endif
5129 if (verbose)
5130 EMSG(_("E695: Cannot index a Funcref"));
5131 return FAIL;
5134 if (**arg == '.')
5137 * dict.name
5139 key = *arg + 1;
5140 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
5142 if (len == 0)
5143 return FAIL;
5144 *arg = skipwhite(key + len);
5146 else
5149 * something[idx]
5151 * Get the (first) variable from inside the [].
5153 *arg = skipwhite(*arg + 1);
5154 if (**arg == ':')
5155 empty1 = TRUE;
5156 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
5157 return FAIL;
5158 else if (evaluate && get_tv_string_chk(&var1) == NULL)
5160 /* not a number or string */
5161 clear_tv(&var1);
5162 return FAIL;
5166 * Get the second variable from inside the [:].
5168 if (**arg == ':')
5170 range = TRUE;
5171 *arg = skipwhite(*arg + 1);
5172 if (**arg == ']')
5173 empty2 = TRUE;
5174 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
5176 if (!empty1)
5177 clear_tv(&var1);
5178 return FAIL;
5180 else if (evaluate && get_tv_string_chk(&var2) == NULL)
5182 /* not a number or string */
5183 if (!empty1)
5184 clear_tv(&var1);
5185 clear_tv(&var2);
5186 return FAIL;
5190 /* Check for the ']'. */
5191 if (**arg != ']')
5193 if (verbose)
5194 EMSG(_(e_missbrac));
5195 clear_tv(&var1);
5196 if (range)
5197 clear_tv(&var2);
5198 return FAIL;
5200 *arg = skipwhite(*arg + 1); /* skip the ']' */
5203 if (evaluate)
5205 n1 = 0;
5206 if (!empty1 && rettv->v_type != VAR_DICT)
5208 n1 = get_tv_number(&var1);
5209 clear_tv(&var1);
5211 if (range)
5213 if (empty2)
5214 n2 = -1;
5215 else
5217 n2 = get_tv_number(&var2);
5218 clear_tv(&var2);
5222 switch (rettv->v_type)
5224 case VAR_NUMBER:
5225 case VAR_STRING:
5226 s = get_tv_string(rettv);
5227 len = (long)STRLEN(s);
5228 if (range)
5230 /* The resulting variable is a substring. If the indexes
5231 * are out of range the result is empty. */
5232 if (n1 < 0)
5234 n1 = len + n1;
5235 if (n1 < 0)
5236 n1 = 0;
5238 if (n2 < 0)
5239 n2 = len + n2;
5240 else if (n2 >= len)
5241 n2 = len;
5242 if (n1 >= len || n2 < 0 || n1 > n2)
5243 s = NULL;
5244 else
5245 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
5247 else
5249 /* The resulting variable is a string of a single
5250 * character. If the index is too big or negative the
5251 * result is empty. */
5252 if (n1 >= len || n1 < 0)
5253 s = NULL;
5254 else
5255 s = vim_strnsave(s + n1, 1);
5257 clear_tv(rettv);
5258 rettv->v_type = VAR_STRING;
5259 rettv->vval.v_string = s;
5260 break;
5262 case VAR_LIST:
5263 len = list_len(rettv->vval.v_list);
5264 if (n1 < 0)
5265 n1 = len + n1;
5266 if (!empty1 && (n1 < 0 || n1 >= len))
5268 /* For a range we allow invalid values and return an empty
5269 * list. A list index out of range is an error. */
5270 if (!range)
5272 if (verbose)
5273 EMSGN(_(e_listidx), n1);
5274 return FAIL;
5276 n1 = len;
5278 if (range)
5280 list_T *l;
5281 listitem_T *item;
5283 if (n2 < 0)
5284 n2 = len + n2;
5285 else if (n2 >= len)
5286 n2 = len - 1;
5287 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
5288 n2 = -1;
5289 l = list_alloc();
5290 if (l == NULL)
5291 return FAIL;
5292 for (item = list_find(rettv->vval.v_list, n1);
5293 n1 <= n2; ++n1)
5295 if (list_append_tv(l, &item->li_tv) == FAIL)
5297 list_free(l, TRUE);
5298 return FAIL;
5300 item = item->li_next;
5302 clear_tv(rettv);
5303 rettv->v_type = VAR_LIST;
5304 rettv->vval.v_list = l;
5305 ++l->lv_refcount;
5307 else
5309 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
5310 clear_tv(rettv);
5311 *rettv = var1;
5313 break;
5315 case VAR_DICT:
5316 if (range)
5318 if (verbose)
5319 EMSG(_(e_dictrange));
5320 if (len == -1)
5321 clear_tv(&var1);
5322 return FAIL;
5325 dictitem_T *item;
5327 if (len == -1)
5329 key = get_tv_string(&var1);
5330 if (*key == NUL)
5332 if (verbose)
5333 EMSG(_(e_emptykey));
5334 clear_tv(&var1);
5335 return FAIL;
5339 item = dict_find(rettv->vval.v_dict, key, (int)len);
5341 if (item == NULL && verbose)
5342 EMSG2(_(e_dictkey), key);
5343 if (len == -1)
5344 clear_tv(&var1);
5345 if (item == NULL)
5346 return FAIL;
5348 copy_tv(&item->di_tv, &var1);
5349 clear_tv(rettv);
5350 *rettv = var1;
5352 break;
5356 return OK;
5360 * Get an option value.
5361 * "arg" points to the '&' or '+' before the option name.
5362 * "arg" is advanced to character after the option name.
5363 * Return OK or FAIL.
5365 static int
5366 get_option_tv(arg, rettv, evaluate)
5367 char_u **arg;
5368 typval_T *rettv; /* when NULL, only check if option exists */
5369 int evaluate;
5371 char_u *option_end;
5372 long numval;
5373 char_u *stringval;
5374 int opt_type;
5375 int c;
5376 int working = (**arg == '+'); /* has("+option") */
5377 int ret = OK;
5378 int opt_flags;
5381 * Isolate the option name and find its value.
5383 option_end = find_option_end(arg, &opt_flags);
5384 if (option_end == NULL)
5386 if (rettv != NULL)
5387 EMSG2(_("E112: Option name missing: %s"), *arg);
5388 return FAIL;
5391 if (!evaluate)
5393 *arg = option_end;
5394 return OK;
5397 c = *option_end;
5398 *option_end = NUL;
5399 opt_type = get_option_value(*arg, &numval,
5400 rettv == NULL ? NULL : &stringval, opt_flags);
5402 if (opt_type == -3) /* invalid name */
5404 if (rettv != NULL)
5405 EMSG2(_("E113: Unknown option: %s"), *arg);
5406 ret = FAIL;
5408 else if (rettv != NULL)
5410 if (opt_type == -2) /* hidden string option */
5412 rettv->v_type = VAR_STRING;
5413 rettv->vval.v_string = NULL;
5415 else if (opt_type == -1) /* hidden number option */
5417 rettv->v_type = VAR_NUMBER;
5418 rettv->vval.v_number = 0;
5420 else if (opt_type == 1) /* number option */
5422 rettv->v_type = VAR_NUMBER;
5423 rettv->vval.v_number = numval;
5425 else /* string option */
5427 rettv->v_type = VAR_STRING;
5428 rettv->vval.v_string = stringval;
5431 else if (working && (opt_type == -2 || opt_type == -1))
5432 ret = FAIL;
5434 *option_end = c; /* put back for error messages */
5435 *arg = option_end;
5437 return ret;
5441 * Allocate a variable for a string constant.
5442 * Return OK or FAIL.
5444 static int
5445 get_string_tv(arg, rettv, evaluate)
5446 char_u **arg;
5447 typval_T *rettv;
5448 int evaluate;
5450 char_u *p;
5451 char_u *name;
5452 int extra = 0;
5455 * Find the end of the string, skipping backslashed characters.
5457 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5459 if (*p == '\\' && p[1] != NUL)
5461 ++p;
5462 /* A "\<x>" form occupies at least 4 characters, and produces up
5463 * to 6 characters: reserve space for 2 extra */
5464 if (*p == '<')
5465 extra += 2;
5469 if (*p != '"')
5471 EMSG2(_("E114: Missing quote: %s"), *arg);
5472 return FAIL;
5475 /* If only parsing, set *arg and return here */
5476 if (!evaluate)
5478 *arg = p + 1;
5479 return OK;
5483 * Copy the string into allocated memory, handling backslashed
5484 * characters.
5486 name = alloc((unsigned)(p - *arg + extra));
5487 if (name == NULL)
5488 return FAIL;
5489 rettv->v_type = VAR_STRING;
5490 rettv->vval.v_string = name;
5492 for (p = *arg + 1; *p != NUL && *p != '"'; )
5494 if (*p == '\\')
5496 switch (*++p)
5498 case 'b': *name++ = BS; ++p; break;
5499 case 'e': *name++ = ESC; ++p; break;
5500 case 'f': *name++ = FF; ++p; break;
5501 case 'n': *name++ = NL; ++p; break;
5502 case 'r': *name++ = CAR; ++p; break;
5503 case 't': *name++ = TAB; ++p; break;
5505 case 'X': /* hex: "\x1", "\x12" */
5506 case 'x':
5507 case 'u': /* Unicode: "\u0023" */
5508 case 'U':
5509 if (vim_isxdigit(p[1]))
5511 int n, nr;
5512 int c = toupper(*p);
5514 if (c == 'X')
5515 n = 2;
5516 else
5517 n = 4;
5518 nr = 0;
5519 while (--n >= 0 && vim_isxdigit(p[1]))
5521 ++p;
5522 nr = (nr << 4) + hex2nr(*p);
5524 ++p;
5525 #ifdef FEAT_MBYTE
5526 /* For "\u" store the number according to
5527 * 'encoding'. */
5528 if (c != 'X')
5529 name += (*mb_char2bytes)(nr, name);
5530 else
5531 #endif
5532 *name++ = nr;
5534 break;
5536 /* octal: "\1", "\12", "\123" */
5537 case '0':
5538 case '1':
5539 case '2':
5540 case '3':
5541 case '4':
5542 case '5':
5543 case '6':
5544 case '7': *name = *p++ - '0';
5545 if (*p >= '0' && *p <= '7')
5547 *name = (*name << 3) + *p++ - '0';
5548 if (*p >= '0' && *p <= '7')
5549 *name = (*name << 3) + *p++ - '0';
5551 ++name;
5552 break;
5554 /* Special key, e.g.: "\<C-W>" */
5555 case '<': extra = trans_special(&p, name, TRUE);
5556 if (extra != 0)
5558 name += extra;
5559 break;
5561 /* FALLTHROUGH */
5563 default: MB_COPY_CHAR(p, name);
5564 break;
5567 else
5568 MB_COPY_CHAR(p, name);
5571 *name = NUL;
5572 *arg = p + 1;
5574 return OK;
5578 * Allocate a variable for a 'str''ing' constant.
5579 * Return OK or FAIL.
5581 static int
5582 get_lit_string_tv(arg, rettv, evaluate)
5583 char_u **arg;
5584 typval_T *rettv;
5585 int evaluate;
5587 char_u *p;
5588 char_u *str;
5589 int reduce = 0;
5592 * Find the end of the string, skipping ''.
5594 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5596 if (*p == '\'')
5598 if (p[1] != '\'')
5599 break;
5600 ++reduce;
5601 ++p;
5605 if (*p != '\'')
5607 EMSG2(_("E115: Missing quote: %s"), *arg);
5608 return FAIL;
5611 /* If only parsing return after setting "*arg" */
5612 if (!evaluate)
5614 *arg = p + 1;
5615 return OK;
5619 * Copy the string into allocated memory, handling '' to ' reduction.
5621 str = alloc((unsigned)((p - *arg) - reduce));
5622 if (str == NULL)
5623 return FAIL;
5624 rettv->v_type = VAR_STRING;
5625 rettv->vval.v_string = str;
5627 for (p = *arg + 1; *p != NUL; )
5629 if (*p == '\'')
5631 if (p[1] != '\'')
5632 break;
5633 ++p;
5635 MB_COPY_CHAR(p, str);
5637 *str = NUL;
5638 *arg = p + 1;
5640 return OK;
5644 * Allocate a variable for a List and fill it from "*arg".
5645 * Return OK or FAIL.
5647 static int
5648 get_list_tv(arg, rettv, evaluate)
5649 char_u **arg;
5650 typval_T *rettv;
5651 int evaluate;
5653 list_T *l = NULL;
5654 typval_T tv;
5655 listitem_T *item;
5657 if (evaluate)
5659 l = list_alloc();
5660 if (l == NULL)
5661 return FAIL;
5664 *arg = skipwhite(*arg + 1);
5665 while (**arg != ']' && **arg != NUL)
5667 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5668 goto failret;
5669 if (evaluate)
5671 item = listitem_alloc();
5672 if (item != NULL)
5674 item->li_tv = tv;
5675 item->li_tv.v_lock = 0;
5676 list_append(l, item);
5678 else
5679 clear_tv(&tv);
5682 if (**arg == ']')
5683 break;
5684 if (**arg != ',')
5686 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5687 goto failret;
5689 *arg = skipwhite(*arg + 1);
5692 if (**arg != ']')
5694 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5695 failret:
5696 if (evaluate)
5697 list_free(l, TRUE);
5698 return FAIL;
5701 *arg = skipwhite(*arg + 1);
5702 if (evaluate)
5704 rettv->v_type = VAR_LIST;
5705 rettv->vval.v_list = l;
5706 ++l->lv_refcount;
5709 return OK;
5713 * Allocate an empty header for a list.
5714 * Caller should take care of the reference count.
5716 list_T *
5717 list_alloc()
5719 list_T *l;
5721 l = (list_T *)alloc_clear(sizeof(list_T));
5722 if (l != NULL)
5724 /* Prepend the list to the list of lists for garbage collection. */
5725 if (first_list != NULL)
5726 first_list->lv_used_prev = l;
5727 l->lv_used_prev = NULL;
5728 l->lv_used_next = first_list;
5729 first_list = l;
5731 return l;
5735 * Allocate an empty list for a return value.
5736 * Returns OK or FAIL.
5738 static int
5739 rettv_list_alloc(rettv)
5740 typval_T *rettv;
5742 list_T *l = list_alloc();
5744 if (l == NULL)
5745 return FAIL;
5747 rettv->vval.v_list = l;
5748 rettv->v_type = VAR_LIST;
5749 ++l->lv_refcount;
5750 return OK;
5754 * Unreference a list: decrement the reference count and free it when it
5755 * becomes zero.
5757 void
5758 list_unref(l)
5759 list_T *l;
5761 if (l != NULL && --l->lv_refcount <= 0)
5762 list_free(l, TRUE);
5766 * Free a list, including all items it points to.
5767 * Ignores the reference count.
5769 void
5770 list_free(l, recurse)
5771 list_T *l;
5772 int recurse; /* Free Lists and Dictionaries recursively. */
5774 listitem_T *item;
5776 /* Remove the list from the list of lists for garbage collection. */
5777 if (l->lv_used_prev == NULL)
5778 first_list = l->lv_used_next;
5779 else
5780 l->lv_used_prev->lv_used_next = l->lv_used_next;
5781 if (l->lv_used_next != NULL)
5782 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5784 for (item = l->lv_first; item != NULL; item = l->lv_first)
5786 /* Remove the item before deleting it. */
5787 l->lv_first = item->li_next;
5788 if (recurse || (item->li_tv.v_type != VAR_LIST
5789 && item->li_tv.v_type != VAR_DICT))
5790 clear_tv(&item->li_tv);
5791 vim_free(item);
5793 vim_free(l);
5797 * Allocate a list item.
5799 static listitem_T *
5800 listitem_alloc()
5802 return (listitem_T *)alloc(sizeof(listitem_T));
5806 * Free a list item. Also clears the value. Does not notify watchers.
5808 static void
5809 listitem_free(item)
5810 listitem_T *item;
5812 clear_tv(&item->li_tv);
5813 vim_free(item);
5817 * Remove a list item from a List and free it. Also clears the value.
5819 static void
5820 listitem_remove(l, item)
5821 list_T *l;
5822 listitem_T *item;
5824 list_remove(l, item, item);
5825 listitem_free(item);
5829 * Get the number of items in a list.
5831 static long
5832 list_len(l)
5833 list_T *l;
5835 if (l == NULL)
5836 return 0L;
5837 return l->lv_len;
5841 * Return TRUE when two lists have exactly the same values.
5843 static int
5844 list_equal(l1, l2, ic)
5845 list_T *l1;
5846 list_T *l2;
5847 int ic; /* ignore case for strings */
5849 listitem_T *item1, *item2;
5851 if (l1 == NULL || l2 == NULL)
5852 return FALSE;
5853 if (l1 == l2)
5854 return TRUE;
5855 if (list_len(l1) != list_len(l2))
5856 return FALSE;
5858 for (item1 = l1->lv_first, item2 = l2->lv_first;
5859 item1 != NULL && item2 != NULL;
5860 item1 = item1->li_next, item2 = item2->li_next)
5861 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5862 return FALSE;
5863 return item1 == NULL && item2 == NULL;
5866 #if defined(FEAT_PYTHON) || defined(PROTO)
5868 * Return the dictitem that an entry in a hashtable points to.
5870 dictitem_T *
5871 dict_lookup(hi)
5872 hashitem_T *hi;
5874 return HI2DI(hi);
5876 #endif
5879 * Return TRUE when two dictionaries have exactly the same key/values.
5881 static int
5882 dict_equal(d1, d2, ic)
5883 dict_T *d1;
5884 dict_T *d2;
5885 int ic; /* ignore case for strings */
5887 hashitem_T *hi;
5888 dictitem_T *item2;
5889 int todo;
5891 if (d1 == NULL || d2 == NULL)
5892 return FALSE;
5893 if (d1 == d2)
5894 return TRUE;
5895 if (dict_len(d1) != dict_len(d2))
5896 return FALSE;
5898 todo = (int)d1->dv_hashtab.ht_used;
5899 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5901 if (!HASHITEM_EMPTY(hi))
5903 item2 = dict_find(d2, hi->hi_key, -1);
5904 if (item2 == NULL)
5905 return FALSE;
5906 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5907 return FALSE;
5908 --todo;
5911 return TRUE;
5915 * Return TRUE if "tv1" and "tv2" have the same value.
5916 * Compares the items just like "==" would compare them, but strings and
5917 * numbers are different. Floats and numbers are also different.
5919 static int
5920 tv_equal(tv1, tv2, ic)
5921 typval_T *tv1;
5922 typval_T *tv2;
5923 int ic; /* ignore case */
5925 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5926 char_u *s1, *s2;
5927 static int recursive = 0; /* cach recursive loops */
5928 int r;
5930 if (tv1->v_type != tv2->v_type)
5931 return FALSE;
5932 /* Catch lists and dicts that have an endless loop by limiting
5933 * recursiveness to 1000. We guess they are equal then. */
5934 if (recursive >= 1000)
5935 return TRUE;
5937 switch (tv1->v_type)
5939 case VAR_LIST:
5940 ++recursive;
5941 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5942 --recursive;
5943 return r;
5945 case VAR_DICT:
5946 ++recursive;
5947 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5948 --recursive;
5949 return r;
5951 case VAR_FUNC:
5952 return (tv1->vval.v_string != NULL
5953 && tv2->vval.v_string != NULL
5954 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5956 case VAR_NUMBER:
5957 return tv1->vval.v_number == tv2->vval.v_number;
5959 #ifdef FEAT_FLOAT
5960 case VAR_FLOAT:
5961 return tv1->vval.v_float == tv2->vval.v_float;
5962 #endif
5964 case VAR_STRING:
5965 s1 = get_tv_string_buf(tv1, buf1);
5966 s2 = get_tv_string_buf(tv2, buf2);
5967 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5970 EMSG2(_(e_intern2), "tv_equal()");
5971 return TRUE;
5975 * Locate item with index "n" in list "l" and return it.
5976 * A negative index is counted from the end; -1 is the last item.
5977 * Returns NULL when "n" is out of range.
5979 static listitem_T *
5980 list_find(l, n)
5981 list_T *l;
5982 long n;
5984 listitem_T *item;
5985 long idx;
5987 if (l == NULL)
5988 return NULL;
5990 /* Negative index is relative to the end. */
5991 if (n < 0)
5992 n = l->lv_len + n;
5994 /* Check for index out of range. */
5995 if (n < 0 || n >= l->lv_len)
5996 return NULL;
5998 /* When there is a cached index may start search from there. */
5999 if (l->lv_idx_item != NULL)
6001 if (n < l->lv_idx / 2)
6003 /* closest to the start of the list */
6004 item = l->lv_first;
6005 idx = 0;
6007 else if (n > (l->lv_idx + l->lv_len) / 2)
6009 /* closest to the end of the list */
6010 item = l->lv_last;
6011 idx = l->lv_len - 1;
6013 else
6015 /* closest to the cached index */
6016 item = l->lv_idx_item;
6017 idx = l->lv_idx;
6020 else
6022 if (n < l->lv_len / 2)
6024 /* closest to the start of the list */
6025 item = l->lv_first;
6026 idx = 0;
6028 else
6030 /* closest to the end of the list */
6031 item = l->lv_last;
6032 idx = l->lv_len - 1;
6036 while (n > idx)
6038 /* search forward */
6039 item = item->li_next;
6040 ++idx;
6042 while (n < idx)
6044 /* search backward */
6045 item = item->li_prev;
6046 --idx;
6049 /* cache the used index */
6050 l->lv_idx = idx;
6051 l->lv_idx_item = item;
6053 return item;
6057 * Get list item "l[idx]" as a number.
6059 static long
6060 list_find_nr(l, idx, errorp)
6061 list_T *l;
6062 long idx;
6063 int *errorp; /* set to TRUE when something wrong */
6065 listitem_T *li;
6067 li = list_find(l, idx);
6068 if (li == NULL)
6070 if (errorp != NULL)
6071 *errorp = TRUE;
6072 return -1L;
6074 return get_tv_number_chk(&li->li_tv, errorp);
6078 * Get list item "l[idx - 1]" as a string. Returns NULL for failure.
6080 char_u *
6081 list_find_str(l, idx)
6082 list_T *l;
6083 long idx;
6085 listitem_T *li;
6087 li = list_find(l, idx - 1);
6088 if (li == NULL)
6090 EMSGN(_(e_listidx), idx);
6091 return NULL;
6093 return get_tv_string(&li->li_tv);
6097 * Locate "item" list "l" and return its index.
6098 * Returns -1 when "item" is not in the list.
6100 static long
6101 list_idx_of_item(l, item)
6102 list_T *l;
6103 listitem_T *item;
6105 long idx = 0;
6106 listitem_T *li;
6108 if (l == NULL)
6109 return -1;
6110 idx = 0;
6111 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
6112 ++idx;
6113 if (li == NULL)
6114 return -1;
6115 return idx;
6119 * Append item "item" to the end of list "l".
6121 static void
6122 list_append(l, item)
6123 list_T *l;
6124 listitem_T *item;
6126 if (l->lv_last == NULL)
6128 /* empty list */
6129 l->lv_first = item;
6130 l->lv_last = item;
6131 item->li_prev = NULL;
6133 else
6135 l->lv_last->li_next = item;
6136 item->li_prev = l->lv_last;
6137 l->lv_last = item;
6139 ++l->lv_len;
6140 item->li_next = NULL;
6144 * Append typval_T "tv" to the end of list "l".
6145 * Return FAIL when out of memory.
6147 static int
6148 list_append_tv(l, tv)
6149 list_T *l;
6150 typval_T *tv;
6152 listitem_T *li = listitem_alloc();
6154 if (li == NULL)
6155 return FAIL;
6156 copy_tv(tv, &li->li_tv);
6157 list_append(l, li);
6158 return OK;
6162 * Add a dictionary to a list. Used by getqflist().
6163 * Return FAIL when out of memory.
6166 list_append_dict(list, dict)
6167 list_T *list;
6168 dict_T *dict;
6170 listitem_T *li = listitem_alloc();
6172 if (li == NULL)
6173 return FAIL;
6174 li->li_tv.v_type = VAR_DICT;
6175 li->li_tv.v_lock = 0;
6176 li->li_tv.vval.v_dict = dict;
6177 list_append(list, li);
6178 ++dict->dv_refcount;
6179 return OK;
6183 * Make a copy of "str" and append it as an item to list "l".
6184 * When "len" >= 0 use "str[len]".
6185 * Returns FAIL when out of memory.
6188 list_append_string(l, str, len)
6189 list_T *l;
6190 char_u *str;
6191 int len;
6193 listitem_T *li = listitem_alloc();
6195 if (li == NULL)
6196 return FAIL;
6197 list_append(l, li);
6198 li->li_tv.v_type = VAR_STRING;
6199 li->li_tv.v_lock = 0;
6200 if (str == NULL)
6201 li->li_tv.vval.v_string = NULL;
6202 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
6203 : vim_strsave(str))) == NULL)
6204 return FAIL;
6205 return OK;
6209 * Append "n" to list "l".
6210 * Returns FAIL when out of memory.
6212 static int
6213 list_append_number(l, n)
6214 list_T *l;
6215 varnumber_T n;
6217 listitem_T *li;
6219 li = listitem_alloc();
6220 if (li == NULL)
6221 return FAIL;
6222 li->li_tv.v_type = VAR_NUMBER;
6223 li->li_tv.v_lock = 0;
6224 li->li_tv.vval.v_number = n;
6225 list_append(l, li);
6226 return OK;
6230 * Insert typval_T "tv" in list "l" before "item".
6231 * If "item" is NULL append at the end.
6232 * Return FAIL when out of memory.
6234 static int
6235 list_insert_tv(l, tv, item)
6236 list_T *l;
6237 typval_T *tv;
6238 listitem_T *item;
6240 listitem_T *ni = listitem_alloc();
6242 if (ni == NULL)
6243 return FAIL;
6244 copy_tv(tv, &ni->li_tv);
6245 if (item == NULL)
6246 /* Append new item at end of list. */
6247 list_append(l, ni);
6248 else
6250 /* Insert new item before existing item. */
6251 ni->li_prev = item->li_prev;
6252 ni->li_next = item;
6253 if (item->li_prev == NULL)
6255 l->lv_first = ni;
6256 ++l->lv_idx;
6258 else
6260 item->li_prev->li_next = ni;
6261 l->lv_idx_item = NULL;
6263 item->li_prev = ni;
6264 ++l->lv_len;
6266 return OK;
6270 * Extend "l1" with "l2".
6271 * If "bef" is NULL append at the end, otherwise insert before this item.
6272 * Returns FAIL when out of memory.
6274 static int
6275 list_extend(l1, l2, bef)
6276 list_T *l1;
6277 list_T *l2;
6278 listitem_T *bef;
6280 listitem_T *item;
6281 int todo = l2->lv_len;
6283 /* We also quit the loop when we have inserted the original item count of
6284 * the list, avoid a hang when we extend a list with itself. */
6285 for (item = l2->lv_first; item != NULL && --todo >= 0; item = item->li_next)
6286 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
6287 return FAIL;
6288 return OK;
6292 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
6293 * Return FAIL when out of memory.
6295 static int
6296 list_concat(l1, l2, tv)
6297 list_T *l1;
6298 list_T *l2;
6299 typval_T *tv;
6301 list_T *l;
6303 if (l1 == NULL || l2 == NULL)
6304 return FAIL;
6306 /* make a copy of the first list. */
6307 l = list_copy(l1, FALSE, 0);
6308 if (l == NULL)
6309 return FAIL;
6310 tv->v_type = VAR_LIST;
6311 tv->vval.v_list = l;
6313 /* append all items from the second list */
6314 return list_extend(l, l2, NULL);
6318 * Make a copy of list "orig". Shallow if "deep" is FALSE.
6319 * The refcount of the new list is set to 1.
6320 * See item_copy() for "copyID".
6321 * Returns NULL when out of memory.
6323 static list_T *
6324 list_copy(orig, deep, copyID)
6325 list_T *orig;
6326 int deep;
6327 int copyID;
6329 list_T *copy;
6330 listitem_T *item;
6331 listitem_T *ni;
6333 if (orig == NULL)
6334 return NULL;
6336 copy = list_alloc();
6337 if (copy != NULL)
6339 if (copyID != 0)
6341 /* Do this before adding the items, because one of the items may
6342 * refer back to this list. */
6343 orig->lv_copyID = copyID;
6344 orig->lv_copylist = copy;
6346 for (item = orig->lv_first; item != NULL && !got_int;
6347 item = item->li_next)
6349 ni = listitem_alloc();
6350 if (ni == NULL)
6351 break;
6352 if (deep)
6354 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
6356 vim_free(ni);
6357 break;
6360 else
6361 copy_tv(&item->li_tv, &ni->li_tv);
6362 list_append(copy, ni);
6364 ++copy->lv_refcount;
6365 if (item != NULL)
6367 list_unref(copy);
6368 copy = NULL;
6372 return copy;
6376 * Remove items "item" to "item2" from list "l".
6377 * Does not free the listitem or the value!
6379 static void
6380 list_remove(l, item, item2)
6381 list_T *l;
6382 listitem_T *item;
6383 listitem_T *item2;
6385 listitem_T *ip;
6387 /* notify watchers */
6388 for (ip = item; ip != NULL; ip = ip->li_next)
6390 --l->lv_len;
6391 list_fix_watch(l, ip);
6392 if (ip == item2)
6393 break;
6396 if (item2->li_next == NULL)
6397 l->lv_last = item->li_prev;
6398 else
6399 item2->li_next->li_prev = item->li_prev;
6400 if (item->li_prev == NULL)
6401 l->lv_first = item2->li_next;
6402 else
6403 item->li_prev->li_next = item2->li_next;
6404 l->lv_idx_item = NULL;
6408 * Return an allocated string with the string representation of a list.
6409 * May return NULL.
6411 static char_u *
6412 list2string(tv, copyID)
6413 typval_T *tv;
6414 int copyID;
6416 garray_T ga;
6418 if (tv->vval.v_list == NULL)
6419 return NULL;
6420 ga_init2(&ga, (int)sizeof(char), 80);
6421 ga_append(&ga, '[');
6422 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6424 vim_free(ga.ga_data);
6425 return NULL;
6427 ga_append(&ga, ']');
6428 ga_append(&ga, NUL);
6429 return (char_u *)ga.ga_data;
6433 * Join list "l" into a string in "*gap", using separator "sep".
6434 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6435 * Return FAIL or OK.
6437 static int
6438 list_join(gap, l, sep, echo, copyID)
6439 garray_T *gap;
6440 list_T *l;
6441 char_u *sep;
6442 int echo;
6443 int copyID;
6445 int first = TRUE;
6446 char_u *tofree;
6447 char_u numbuf[NUMBUFLEN];
6448 listitem_T *item;
6449 char_u *s;
6451 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6453 if (first)
6454 first = FALSE;
6455 else
6456 ga_concat(gap, sep);
6458 if (echo)
6459 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6460 else
6461 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6462 if (s != NULL)
6463 ga_concat(gap, s);
6464 vim_free(tofree);
6465 if (s == NULL)
6466 return FAIL;
6468 return OK;
6472 * Garbage collection for lists and dictionaries.
6474 * We use reference counts to be able to free most items right away when they
6475 * are no longer used. But for composite items it's possible that it becomes
6476 * unused while the reference count is > 0: When there is a recursive
6477 * reference. Example:
6478 * :let l = [1, 2, 3]
6479 * :let d = {9: l}
6480 * :let l[1] = d
6482 * Since this is quite unusual we handle this with garbage collection: every
6483 * once in a while find out which lists and dicts are not referenced from any
6484 * variable.
6486 * Here is a good reference text about garbage collection (refers to Python
6487 * but it applies to all reference-counting mechanisms):
6488 * http://python.ca/nas/python/gc/
6492 * Do garbage collection for lists and dicts.
6493 * Return TRUE if some memory was freed.
6496 garbage_collect()
6498 dict_T *dd;
6499 list_T *ll;
6500 int copyID = ++current_copyID;
6501 buf_T *buf;
6502 win_T *wp;
6503 int i;
6504 funccall_T *fc, **pfc;
6505 int did_free = FALSE;
6506 #ifdef FEAT_WINDOWS
6507 tabpage_T *tp;
6508 #endif
6510 /* Only do this once. */
6511 want_garbage_collect = FALSE;
6512 may_garbage_collect = FALSE;
6513 garbage_collect_at_exit = FALSE;
6516 * 1. Go through all accessible variables and mark all lists and dicts
6517 * with copyID.
6519 /* script-local variables */
6520 for (i = 1; i <= ga_scripts.ga_len; ++i)
6521 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6523 /* buffer-local variables */
6524 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6525 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6527 /* window-local variables */
6528 FOR_ALL_TAB_WINDOWS(tp, wp)
6529 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6531 #ifdef FEAT_WINDOWS
6532 /* tabpage-local variables */
6533 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6534 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6535 #endif
6537 /* global variables */
6538 set_ref_in_ht(&globvarht, copyID);
6540 /* function-local variables */
6541 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6543 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6544 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6547 /* v: vars */
6548 set_ref_in_ht(&vimvarht, copyID);
6551 * 2. Go through the list of dicts and free items without the copyID.
6553 for (dd = first_dict; dd != NULL; )
6554 if (dd->dv_copyID != copyID)
6556 /* Free the Dictionary and ordinary items it contains, but don't
6557 * recurse into Lists and Dictionaries, they will be in the list
6558 * of dicts or list of lists. */
6559 dict_free(dd, FALSE);
6560 did_free = TRUE;
6562 /* restart, next dict may also have been freed */
6563 dd = first_dict;
6565 else
6566 dd = dd->dv_used_next;
6569 * 3. Go through the list of lists and free items without the copyID.
6570 * But don't free a list that has a watcher (used in a for loop), these
6571 * are not referenced anywhere.
6573 for (ll = first_list; ll != NULL; )
6574 if (ll->lv_copyID != copyID && ll->lv_watch == NULL)
6576 /* Free the List and ordinary items it contains, but don't recurse
6577 * into Lists and Dictionaries, they will be in the list of dicts
6578 * or list of lists. */
6579 list_free(ll, FALSE);
6580 did_free = TRUE;
6582 /* restart, next list may also have been freed */
6583 ll = first_list;
6585 else
6586 ll = ll->lv_used_next;
6588 /* check if any funccal can be freed now */
6589 for (pfc = &previous_funccal; *pfc != NULL; )
6591 if (can_free_funccal(*pfc, copyID))
6593 fc = *pfc;
6594 *pfc = fc->caller;
6595 free_funccal(fc, TRUE);
6596 did_free = TRUE;
6598 else
6599 pfc = &(*pfc)->caller;
6602 return did_free;
6606 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6608 static void
6609 set_ref_in_ht(ht, copyID)
6610 hashtab_T *ht;
6611 int copyID;
6613 int todo;
6614 hashitem_T *hi;
6616 todo = (int)ht->ht_used;
6617 for (hi = ht->ht_array; todo > 0; ++hi)
6618 if (!HASHITEM_EMPTY(hi))
6620 --todo;
6621 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6626 * Mark all lists and dicts referenced through list "l" with "copyID".
6628 static void
6629 set_ref_in_list(l, copyID)
6630 list_T *l;
6631 int copyID;
6633 listitem_T *li;
6635 for (li = l->lv_first; li != NULL; li = li->li_next)
6636 set_ref_in_item(&li->li_tv, copyID);
6640 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6642 static void
6643 set_ref_in_item(tv, copyID)
6644 typval_T *tv;
6645 int copyID;
6647 dict_T *dd;
6648 list_T *ll;
6650 switch (tv->v_type)
6652 case VAR_DICT:
6653 dd = tv->vval.v_dict;
6654 if (dd != NULL && dd->dv_copyID != copyID)
6656 /* Didn't see this dict yet. */
6657 dd->dv_copyID = copyID;
6658 set_ref_in_ht(&dd->dv_hashtab, copyID);
6660 break;
6662 case VAR_LIST:
6663 ll = tv->vval.v_list;
6664 if (ll != NULL && ll->lv_copyID != copyID)
6666 /* Didn't see this list yet. */
6667 ll->lv_copyID = copyID;
6668 set_ref_in_list(ll, copyID);
6670 break;
6672 return;
6676 * Allocate an empty header for a dictionary.
6678 dict_T *
6679 dict_alloc()
6681 dict_T *d;
6683 d = (dict_T *)alloc(sizeof(dict_T));
6684 if (d != NULL)
6686 /* Add the list to the list of dicts for garbage collection. */
6687 if (first_dict != NULL)
6688 first_dict->dv_used_prev = d;
6689 d->dv_used_next = first_dict;
6690 d->dv_used_prev = NULL;
6691 first_dict = d;
6693 hash_init(&d->dv_hashtab);
6694 d->dv_lock = 0;
6695 d->dv_refcount = 0;
6696 d->dv_copyID = 0;
6698 return d;
6702 * Unreference a Dictionary: decrement the reference count and free it when it
6703 * becomes zero.
6705 static void
6706 dict_unref(d)
6707 dict_T *d;
6709 if (d != NULL && --d->dv_refcount <= 0)
6710 dict_free(d, TRUE);
6714 * Free a Dictionary, including all items it contains.
6715 * Ignores the reference count.
6717 static void
6718 dict_free(d, recurse)
6719 dict_T *d;
6720 int recurse; /* Free Lists and Dictionaries recursively. */
6722 int todo;
6723 hashitem_T *hi;
6724 dictitem_T *di;
6726 /* Remove the dict from the list of dicts for garbage collection. */
6727 if (d->dv_used_prev == NULL)
6728 first_dict = d->dv_used_next;
6729 else
6730 d->dv_used_prev->dv_used_next = d->dv_used_next;
6731 if (d->dv_used_next != NULL)
6732 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6734 /* Lock the hashtab, we don't want it to resize while freeing items. */
6735 hash_lock(&d->dv_hashtab);
6736 todo = (int)d->dv_hashtab.ht_used;
6737 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6739 if (!HASHITEM_EMPTY(hi))
6741 /* Remove the item before deleting it, just in case there is
6742 * something recursive causing trouble. */
6743 di = HI2DI(hi);
6744 hash_remove(&d->dv_hashtab, hi);
6745 if (recurse || (di->di_tv.v_type != VAR_LIST
6746 && di->di_tv.v_type != VAR_DICT))
6747 clear_tv(&di->di_tv);
6748 vim_free(di);
6749 --todo;
6752 hash_clear(&d->dv_hashtab);
6753 vim_free(d);
6757 * Allocate a Dictionary item.
6758 * The "key" is copied to the new item.
6759 * Note that the value of the item "di_tv" still needs to be initialized!
6760 * Returns NULL when out of memory.
6762 static dictitem_T *
6763 dictitem_alloc(key)
6764 char_u *key;
6766 dictitem_T *di;
6768 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6769 if (di != NULL)
6771 STRCPY(di->di_key, key);
6772 di->di_flags = 0;
6774 return di;
6778 * Make a copy of a Dictionary item.
6780 static dictitem_T *
6781 dictitem_copy(org)
6782 dictitem_T *org;
6784 dictitem_T *di;
6786 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6787 + STRLEN(org->di_key)));
6788 if (di != NULL)
6790 STRCPY(di->di_key, org->di_key);
6791 di->di_flags = 0;
6792 copy_tv(&org->di_tv, &di->di_tv);
6794 return di;
6798 * Remove item "item" from Dictionary "dict" and free it.
6800 static void
6801 dictitem_remove(dict, item)
6802 dict_T *dict;
6803 dictitem_T *item;
6805 hashitem_T *hi;
6807 hi = hash_find(&dict->dv_hashtab, item->di_key);
6808 if (HASHITEM_EMPTY(hi))
6809 EMSG2(_(e_intern2), "dictitem_remove()");
6810 else
6811 hash_remove(&dict->dv_hashtab, hi);
6812 dictitem_free(item);
6816 * Free a dict item. Also clears the value.
6818 static void
6819 dictitem_free(item)
6820 dictitem_T *item;
6822 clear_tv(&item->di_tv);
6823 vim_free(item);
6827 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6828 * The refcount of the new dict is set to 1.
6829 * See item_copy() for "copyID".
6830 * Returns NULL when out of memory.
6832 static dict_T *
6833 dict_copy(orig, deep, copyID)
6834 dict_T *orig;
6835 int deep;
6836 int copyID;
6838 dict_T *copy;
6839 dictitem_T *di;
6840 int todo;
6841 hashitem_T *hi;
6843 if (orig == NULL)
6844 return NULL;
6846 copy = dict_alloc();
6847 if (copy != NULL)
6849 if (copyID != 0)
6851 orig->dv_copyID = copyID;
6852 orig->dv_copydict = copy;
6854 todo = (int)orig->dv_hashtab.ht_used;
6855 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6857 if (!HASHITEM_EMPTY(hi))
6859 --todo;
6861 di = dictitem_alloc(hi->hi_key);
6862 if (di == NULL)
6863 break;
6864 if (deep)
6866 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6867 copyID) == FAIL)
6869 vim_free(di);
6870 break;
6873 else
6874 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6875 if (dict_add(copy, di) == FAIL)
6877 dictitem_free(di);
6878 break;
6883 ++copy->dv_refcount;
6884 if (todo > 0)
6886 dict_unref(copy);
6887 copy = NULL;
6891 return copy;
6895 * Add item "item" to Dictionary "d".
6896 * Returns FAIL when out of memory and when key already existed.
6898 static int
6899 dict_add(d, item)
6900 dict_T *d;
6901 dictitem_T *item;
6903 return hash_add(&d->dv_hashtab, item->di_key);
6907 * Add a number or string entry to dictionary "d".
6908 * When "str" is NULL use number "nr", otherwise use "str".
6909 * Returns FAIL when out of memory and when key already exists.
6912 dict_add_nr_str(d, key, nr, str)
6913 dict_T *d;
6914 char *key;
6915 long nr;
6916 char_u *str;
6918 dictitem_T *item;
6920 item = dictitem_alloc((char_u *)key);
6921 if (item == NULL)
6922 return FAIL;
6923 item->di_tv.v_lock = 0;
6924 if (str == NULL)
6926 item->di_tv.v_type = VAR_NUMBER;
6927 item->di_tv.vval.v_number = nr;
6929 else
6931 item->di_tv.v_type = VAR_STRING;
6932 item->di_tv.vval.v_string = vim_strsave(str);
6934 if (dict_add(d, item) == FAIL)
6936 dictitem_free(item);
6937 return FAIL;
6939 return OK;
6943 * Get the number of items in a Dictionary.
6945 static long
6946 dict_len(d)
6947 dict_T *d;
6949 if (d == NULL)
6950 return 0L;
6951 return (long)d->dv_hashtab.ht_used;
6955 * Find item "key[len]" in Dictionary "d".
6956 * If "len" is negative use strlen(key).
6957 * Returns NULL when not found.
6959 static dictitem_T *
6960 dict_find(d, key, len)
6961 dict_T *d;
6962 char_u *key;
6963 int len;
6965 #define AKEYLEN 200
6966 char_u buf[AKEYLEN];
6967 char_u *akey;
6968 char_u *tofree = NULL;
6969 hashitem_T *hi;
6971 if (len < 0)
6972 akey = key;
6973 else if (len >= AKEYLEN)
6975 tofree = akey = vim_strnsave(key, len);
6976 if (akey == NULL)
6977 return NULL;
6979 else
6981 /* Avoid a malloc/free by using buf[]. */
6982 vim_strncpy(buf, key, len);
6983 akey = buf;
6986 hi = hash_find(&d->dv_hashtab, akey);
6987 vim_free(tofree);
6988 if (HASHITEM_EMPTY(hi))
6989 return NULL;
6990 return HI2DI(hi);
6994 * Get a string item from a dictionary.
6995 * When "save" is TRUE allocate memory for it.
6996 * Returns NULL if the entry doesn't exist or out of memory.
6998 char_u *
6999 get_dict_string(d, key, save)
7000 dict_T *d;
7001 char_u *key;
7002 int save;
7004 dictitem_T *di;
7005 char_u *s;
7007 di = dict_find(d, key, -1);
7008 if (di == NULL)
7009 return NULL;
7010 s = get_tv_string(&di->di_tv);
7011 if (save && s != NULL)
7012 s = vim_strsave(s);
7013 return s;
7017 * Get a number item from a dictionary.
7018 * Returns 0 if the entry doesn't exist or out of memory.
7020 long
7021 get_dict_number(d, key)
7022 dict_T *d;
7023 char_u *key;
7025 dictitem_T *di;
7027 di = dict_find(d, key, -1);
7028 if (di == NULL)
7029 return 0;
7030 return get_tv_number(&di->di_tv);
7034 * Return an allocated string with the string representation of a Dictionary.
7035 * May return NULL.
7037 static char_u *
7038 dict2string(tv, copyID)
7039 typval_T *tv;
7040 int copyID;
7042 garray_T ga;
7043 int first = TRUE;
7044 char_u *tofree;
7045 char_u numbuf[NUMBUFLEN];
7046 hashitem_T *hi;
7047 char_u *s;
7048 dict_T *d;
7049 int todo;
7051 if ((d = tv->vval.v_dict) == NULL)
7052 return NULL;
7053 ga_init2(&ga, (int)sizeof(char), 80);
7054 ga_append(&ga, '{');
7056 todo = (int)d->dv_hashtab.ht_used;
7057 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
7059 if (!HASHITEM_EMPTY(hi))
7061 --todo;
7063 if (first)
7064 first = FALSE;
7065 else
7066 ga_concat(&ga, (char_u *)", ");
7068 tofree = string_quote(hi->hi_key, FALSE);
7069 if (tofree != NULL)
7071 ga_concat(&ga, tofree);
7072 vim_free(tofree);
7074 ga_concat(&ga, (char_u *)": ");
7075 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
7076 if (s != NULL)
7077 ga_concat(&ga, s);
7078 vim_free(tofree);
7079 if (s == NULL)
7080 break;
7083 if (todo > 0)
7085 vim_free(ga.ga_data);
7086 return NULL;
7089 ga_append(&ga, '}');
7090 ga_append(&ga, NUL);
7091 return (char_u *)ga.ga_data;
7095 * Allocate a variable for a Dictionary and fill it from "*arg".
7096 * Return OK or FAIL. Returns NOTDONE for {expr}.
7098 static int
7099 get_dict_tv(arg, rettv, evaluate)
7100 char_u **arg;
7101 typval_T *rettv;
7102 int evaluate;
7104 dict_T *d = NULL;
7105 typval_T tvkey;
7106 typval_T tv;
7107 char_u *key = NULL;
7108 dictitem_T *item;
7109 char_u *start = skipwhite(*arg + 1);
7110 char_u buf[NUMBUFLEN];
7113 * First check if it's not a curly-braces thing: {expr}.
7114 * Must do this without evaluating, otherwise a function may be called
7115 * twice. Unfortunately this means we need to call eval1() twice for the
7116 * first item.
7117 * But {} is an empty Dictionary.
7119 if (*start != '}')
7121 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
7122 return FAIL;
7123 if (*start == '}')
7124 return NOTDONE;
7127 if (evaluate)
7129 d = dict_alloc();
7130 if (d == NULL)
7131 return FAIL;
7133 tvkey.v_type = VAR_UNKNOWN;
7134 tv.v_type = VAR_UNKNOWN;
7136 *arg = skipwhite(*arg + 1);
7137 while (**arg != '}' && **arg != NUL)
7139 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
7140 goto failret;
7141 if (**arg != ':')
7143 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
7144 clear_tv(&tvkey);
7145 goto failret;
7147 if (evaluate)
7149 key = get_tv_string_buf_chk(&tvkey, buf);
7150 if (key == NULL || *key == NUL)
7152 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
7153 if (key != NULL)
7154 EMSG(_(e_emptykey));
7155 clear_tv(&tvkey);
7156 goto failret;
7160 *arg = skipwhite(*arg + 1);
7161 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
7163 if (evaluate)
7164 clear_tv(&tvkey);
7165 goto failret;
7167 if (evaluate)
7169 item = dict_find(d, key, -1);
7170 if (item != NULL)
7172 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
7173 clear_tv(&tvkey);
7174 clear_tv(&tv);
7175 goto failret;
7177 item = dictitem_alloc(key);
7178 clear_tv(&tvkey);
7179 if (item != NULL)
7181 item->di_tv = tv;
7182 item->di_tv.v_lock = 0;
7183 if (dict_add(d, item) == FAIL)
7184 dictitem_free(item);
7188 if (**arg == '}')
7189 break;
7190 if (**arg != ',')
7192 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
7193 goto failret;
7195 *arg = skipwhite(*arg + 1);
7198 if (**arg != '}')
7200 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
7201 failret:
7202 if (evaluate)
7203 dict_free(d, TRUE);
7204 return FAIL;
7207 *arg = skipwhite(*arg + 1);
7208 if (evaluate)
7210 rettv->v_type = VAR_DICT;
7211 rettv->vval.v_dict = d;
7212 ++d->dv_refcount;
7215 return OK;
7219 * Return a string with the string representation of a variable.
7220 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7221 * "numbuf" is used for a number.
7222 * Does not put quotes around strings, as ":echo" displays values.
7223 * When "copyID" is not NULL replace recursive lists and dicts with "...".
7224 * May return NULL.
7226 static char_u *
7227 echo_string(tv, tofree, numbuf, copyID)
7228 typval_T *tv;
7229 char_u **tofree;
7230 char_u *numbuf;
7231 int copyID;
7233 static int recurse = 0;
7234 char_u *r = NULL;
7236 if (recurse >= DICT_MAXNEST)
7238 EMSG(_("E724: variable nested too deep for displaying"));
7239 *tofree = NULL;
7240 return NULL;
7242 ++recurse;
7244 switch (tv->v_type)
7246 case VAR_FUNC:
7247 *tofree = NULL;
7248 r = tv->vval.v_string;
7249 break;
7251 case VAR_LIST:
7252 if (tv->vval.v_list == NULL)
7254 *tofree = NULL;
7255 r = NULL;
7257 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
7259 *tofree = NULL;
7260 r = (char_u *)"[...]";
7262 else
7264 tv->vval.v_list->lv_copyID = copyID;
7265 *tofree = list2string(tv, copyID);
7266 r = *tofree;
7268 break;
7270 case VAR_DICT:
7271 if (tv->vval.v_dict == NULL)
7273 *tofree = NULL;
7274 r = NULL;
7276 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
7278 *tofree = NULL;
7279 r = (char_u *)"{...}";
7281 else
7283 tv->vval.v_dict->dv_copyID = copyID;
7284 *tofree = dict2string(tv, copyID);
7285 r = *tofree;
7287 break;
7289 case VAR_STRING:
7290 case VAR_NUMBER:
7291 *tofree = NULL;
7292 r = get_tv_string_buf(tv, numbuf);
7293 break;
7295 #ifdef FEAT_FLOAT
7296 case VAR_FLOAT:
7297 *tofree = NULL;
7298 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
7299 r = numbuf;
7300 break;
7301 #endif
7303 default:
7304 EMSG2(_(e_intern2), "echo_string()");
7305 *tofree = NULL;
7308 --recurse;
7309 return r;
7313 * Return a string with the string representation of a variable.
7314 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7315 * "numbuf" is used for a number.
7316 * Puts quotes around strings, so that they can be parsed back by eval().
7317 * May return NULL.
7319 static char_u *
7320 tv2string(tv, tofree, numbuf, copyID)
7321 typval_T *tv;
7322 char_u **tofree;
7323 char_u *numbuf;
7324 int copyID;
7326 switch (tv->v_type)
7328 case VAR_FUNC:
7329 *tofree = string_quote(tv->vval.v_string, TRUE);
7330 return *tofree;
7331 case VAR_STRING:
7332 *tofree = string_quote(tv->vval.v_string, FALSE);
7333 return *tofree;
7334 #ifdef FEAT_FLOAT
7335 case VAR_FLOAT:
7336 *tofree = NULL;
7337 vim_snprintf((char *)numbuf, NUMBUFLEN - 1, "%g", tv->vval.v_float);
7338 return numbuf;
7339 #endif
7340 case VAR_NUMBER:
7341 case VAR_LIST:
7342 case VAR_DICT:
7343 break;
7344 default:
7345 EMSG2(_(e_intern2), "tv2string()");
7347 return echo_string(tv, tofree, numbuf, copyID);
7351 * Return string "str" in ' quotes, doubling ' characters.
7352 * If "str" is NULL an empty string is assumed.
7353 * If "function" is TRUE make it function('string').
7355 static char_u *
7356 string_quote(str, function)
7357 char_u *str;
7358 int function;
7360 unsigned len;
7361 char_u *p, *r, *s;
7363 len = (function ? 13 : 3);
7364 if (str != NULL)
7366 len += (unsigned)STRLEN(str);
7367 for (p = str; *p != NUL; mb_ptr_adv(p))
7368 if (*p == '\'')
7369 ++len;
7371 s = r = alloc(len);
7372 if (r != NULL)
7374 if (function)
7376 STRCPY(r, "function('");
7377 r += 10;
7379 else
7380 *r++ = '\'';
7381 if (str != NULL)
7382 for (p = str; *p != NUL; )
7384 if (*p == '\'')
7385 *r++ = '\'';
7386 MB_COPY_CHAR(p, r);
7388 *r++ = '\'';
7389 if (function)
7390 *r++ = ')';
7391 *r++ = NUL;
7393 return s;
7396 #ifdef FEAT_FLOAT
7398 * Convert the string "text" to a floating point number.
7399 * This uses strtod(). setlocale(LC_NUMERIC, "C") has been used to make sure
7400 * this always uses a decimal point.
7401 * Returns the length of the text that was consumed.
7403 static int
7404 string2float(text, value)
7405 char_u *text;
7406 float_T *value; /* result stored here */
7408 char *s = (char *)text;
7409 float_T f;
7411 f = strtod(s, &s);
7412 *value = f;
7413 return (int)((char_u *)s - text);
7415 #endif
7418 * Get the value of an environment variable.
7419 * "arg" is pointing to the '$'. It is advanced to after the name.
7420 * If the environment variable was not set, silently assume it is empty.
7421 * Always return OK.
7423 static int
7424 get_env_tv(arg, rettv, evaluate)
7425 char_u **arg;
7426 typval_T *rettv;
7427 int evaluate;
7429 char_u *string = NULL;
7430 int len;
7431 int cc;
7432 char_u *name;
7433 int mustfree = FALSE;
7435 ++*arg;
7436 name = *arg;
7437 len = get_env_len(arg);
7438 if (evaluate)
7440 if (len != 0)
7442 cc = name[len];
7443 name[len] = NUL;
7444 /* first try vim_getenv(), fast for normal environment vars */
7445 string = vim_getenv(name, &mustfree);
7446 if (string != NULL && *string != NUL)
7448 if (!mustfree)
7449 string = vim_strsave(string);
7451 else
7453 if (mustfree)
7454 vim_free(string);
7456 /* next try expanding things like $VIM and ${HOME} */
7457 string = expand_env_save(name - 1);
7458 if (string != NULL && *string == '$')
7460 vim_free(string);
7461 string = NULL;
7464 name[len] = cc;
7466 rettv->v_type = VAR_STRING;
7467 rettv->vval.v_string = string;
7470 return OK;
7474 * Array with names and number of arguments of all internal functions
7475 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7477 static struct fst
7479 char *f_name; /* function name */
7480 char f_min_argc; /* minimal number of arguments */
7481 char f_max_argc; /* maximal number of arguments */
7482 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7483 /* implementation of function */
7484 } functions[] =
7486 #ifdef FEAT_FLOAT
7487 {"abs", 1, 1, f_abs},
7488 #endif
7489 {"add", 2, 2, f_add},
7490 {"append", 2, 2, f_append},
7491 {"argc", 0, 0, f_argc},
7492 {"argidx", 0, 0, f_argidx},
7493 {"argv", 0, 1, f_argv},
7494 #ifdef FEAT_FLOAT
7495 {"atan", 1, 1, f_atan},
7496 #endif
7497 {"browse", 4, 4, f_browse},
7498 {"browsedir", 2, 2, f_browsedir},
7499 {"bufexists", 1, 1, f_bufexists},
7500 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7501 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7502 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7503 {"buflisted", 1, 1, f_buflisted},
7504 {"bufloaded", 1, 1, f_bufloaded},
7505 {"bufname", 1, 1, f_bufname},
7506 {"bufnr", 1, 2, f_bufnr},
7507 {"bufwinnr", 1, 1, f_bufwinnr},
7508 {"byte2line", 1, 1, f_byte2line},
7509 {"byteidx", 2, 2, f_byteidx},
7510 {"call", 2, 3, f_call},
7511 #ifdef FEAT_FLOAT
7512 {"ceil", 1, 1, f_ceil},
7513 #endif
7514 {"changenr", 0, 0, f_changenr},
7515 {"char2nr", 1, 1, f_char2nr},
7516 {"cindent", 1, 1, f_cindent},
7517 {"clearmatches", 0, 0, f_clearmatches},
7518 {"col", 1, 1, f_col},
7519 #if defined(FEAT_INS_EXPAND)
7520 {"complete", 2, 2, f_complete},
7521 {"complete_add", 1, 1, f_complete_add},
7522 {"complete_check", 0, 0, f_complete_check},
7523 #endif
7524 {"confirm", 1, 4, f_confirm},
7525 {"copy", 1, 1, f_copy},
7526 #ifdef FEAT_FLOAT
7527 {"cos", 1, 1, f_cos},
7528 #endif
7529 {"count", 2, 4, f_count},
7530 {"cscope_connection",0,3, f_cscope_connection},
7531 {"cursor", 1, 3, f_cursor},
7532 {"deepcopy", 1, 2, f_deepcopy},
7533 {"delete", 1, 1, f_delete},
7534 {"did_filetype", 0, 0, f_did_filetype},
7535 {"diff_filler", 1, 1, f_diff_filler},
7536 {"diff_hlID", 2, 2, f_diff_hlID},
7537 {"empty", 1, 1, f_empty},
7538 {"escape", 2, 2, f_escape},
7539 {"eval", 1, 1, f_eval},
7540 {"eventhandler", 0, 0, f_eventhandler},
7541 {"executable", 1, 1, f_executable},
7542 {"exists", 1, 1, f_exists},
7543 {"expand", 1, 2, f_expand},
7544 {"extend", 2, 3, f_extend},
7545 {"feedkeys", 1, 2, f_feedkeys},
7546 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7547 {"filereadable", 1, 1, f_filereadable},
7548 {"filewritable", 1, 1, f_filewritable},
7549 {"filter", 2, 2, f_filter},
7550 {"finddir", 1, 3, f_finddir},
7551 {"findfile", 1, 3, f_findfile},
7552 #ifdef FEAT_FLOAT
7553 {"float2nr", 1, 1, f_float2nr},
7554 {"floor", 1, 1, f_floor},
7555 #endif
7556 {"fnameescape", 1, 1, f_fnameescape},
7557 {"fnamemodify", 2, 2, f_fnamemodify},
7558 {"foldclosed", 1, 1, f_foldclosed},
7559 {"foldclosedend", 1, 1, f_foldclosedend},
7560 {"foldlevel", 1, 1, f_foldlevel},
7561 {"foldtext", 0, 0, f_foldtext},
7562 {"foldtextresult", 1, 1, f_foldtextresult},
7563 {"foreground", 0, 0, f_foreground},
7564 {"function", 1, 1, f_function},
7565 {"garbagecollect", 0, 1, f_garbagecollect},
7566 {"get", 2, 3, f_get},
7567 {"getbufline", 2, 3, f_getbufline},
7568 {"getbufvar", 2, 2, f_getbufvar},
7569 {"getchar", 0, 1, f_getchar},
7570 {"getcharmod", 0, 0, f_getcharmod},
7571 {"getcmdline", 0, 0, f_getcmdline},
7572 {"getcmdpos", 0, 0, f_getcmdpos},
7573 {"getcmdtype", 0, 0, f_getcmdtype},
7574 {"getcwd", 0, 0, f_getcwd},
7575 {"getfontname", 0, 1, f_getfontname},
7576 {"getfperm", 1, 1, f_getfperm},
7577 {"getfsize", 1, 1, f_getfsize},
7578 {"getftime", 1, 1, f_getftime},
7579 {"getftype", 1, 1, f_getftype},
7580 {"getline", 1, 2, f_getline},
7581 {"getloclist", 1, 1, f_getqflist},
7582 {"getmatches", 0, 0, f_getmatches},
7583 {"getpid", 0, 0, f_getpid},
7584 {"getpos", 1, 1, f_getpos},
7585 {"getqflist", 0, 0, f_getqflist},
7586 {"getreg", 0, 2, f_getreg},
7587 {"getregtype", 0, 1, f_getregtype},
7588 {"gettabwinvar", 3, 3, f_gettabwinvar},
7589 {"getwinposx", 0, 0, f_getwinposx},
7590 {"getwinposy", 0, 0, f_getwinposy},
7591 {"getwinvar", 2, 2, f_getwinvar},
7592 {"glob", 1, 2, f_glob},
7593 {"globpath", 2, 3, f_globpath},
7594 {"has", 1, 1, f_has},
7595 {"has_key", 2, 2, f_has_key},
7596 {"haslocaldir", 0, 0, f_haslocaldir},
7597 {"hasmapto", 1, 3, f_hasmapto},
7598 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7599 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7600 {"histadd", 2, 2, f_histadd},
7601 {"histdel", 1, 2, f_histdel},
7602 {"histget", 1, 2, f_histget},
7603 {"histnr", 1, 1, f_histnr},
7604 {"hlID", 1, 1, f_hlID},
7605 {"hlexists", 1, 1, f_hlexists},
7606 {"hostname", 0, 0, f_hostname},
7607 {"iconv", 3, 3, f_iconv},
7608 {"indent", 1, 1, f_indent},
7609 {"index", 2, 4, f_index},
7610 {"input", 1, 3, f_input},
7611 {"inputdialog", 1, 3, f_inputdialog},
7612 {"inputlist", 1, 1, f_inputlist},
7613 {"inputrestore", 0, 0, f_inputrestore},
7614 {"inputsave", 0, 0, f_inputsave},
7615 {"inputsecret", 1, 2, f_inputsecret},
7616 {"insert", 2, 3, f_insert},
7617 {"isdirectory", 1, 1, f_isdirectory},
7618 {"islocked", 1, 1, f_islocked},
7619 {"items", 1, 1, f_items},
7620 {"join", 1, 2, f_join},
7621 {"keys", 1, 1, f_keys},
7622 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7623 {"len", 1, 1, f_len},
7624 {"libcall", 3, 3, f_libcall},
7625 {"libcallnr", 3, 3, f_libcallnr},
7626 {"line", 1, 1, f_line},
7627 {"line2byte", 1, 1, f_line2byte},
7628 {"lispindent", 1, 1, f_lispindent},
7629 {"localtime", 0, 0, f_localtime},
7630 #ifdef FEAT_FLOAT
7631 {"log10", 1, 1, f_log10},
7632 #endif
7633 {"map", 2, 2, f_map},
7634 {"maparg", 1, 3, f_maparg},
7635 {"mapcheck", 1, 3, f_mapcheck},
7636 {"match", 2, 4, f_match},
7637 {"matchadd", 2, 4, f_matchadd},
7638 {"matcharg", 1, 1, f_matcharg},
7639 {"matchdelete", 1, 1, f_matchdelete},
7640 {"matchend", 2, 4, f_matchend},
7641 {"matchlist", 2, 4, f_matchlist},
7642 {"matchstr", 2, 4, f_matchstr},
7643 {"max", 1, 1, f_max},
7644 {"min", 1, 1, f_min},
7645 #ifdef vim_mkdir
7646 {"mkdir", 1, 3, f_mkdir},
7647 #endif
7648 {"mode", 0, 1, f_mode},
7649 {"nextnonblank", 1, 1, f_nextnonblank},
7650 {"nr2char", 1, 1, f_nr2char},
7651 {"pathshorten", 1, 1, f_pathshorten},
7652 #ifdef FEAT_FLOAT
7653 {"pow", 2, 2, f_pow},
7654 #endif
7655 {"prevnonblank", 1, 1, f_prevnonblank},
7656 {"printf", 2, 19, f_printf},
7657 {"pumvisible", 0, 0, f_pumvisible},
7658 {"range", 1, 3, f_range},
7659 {"readfile", 1, 3, f_readfile},
7660 {"reltime", 0, 2, f_reltime},
7661 {"reltimestr", 1, 1, f_reltimestr},
7662 {"remote_expr", 2, 3, f_remote_expr},
7663 {"remote_foreground", 1, 1, f_remote_foreground},
7664 {"remote_peek", 1, 2, f_remote_peek},
7665 {"remote_read", 1, 1, f_remote_read},
7666 {"remote_send", 2, 3, f_remote_send},
7667 {"remove", 2, 3, f_remove},
7668 {"rename", 2, 2, f_rename},
7669 {"repeat", 2, 2, f_repeat},
7670 {"resolve", 1, 1, f_resolve},
7671 {"reverse", 1, 1, f_reverse},
7672 #ifdef FEAT_FLOAT
7673 {"round", 1, 1, f_round},
7674 #endif
7675 {"search", 1, 4, f_search},
7676 {"searchdecl", 1, 3, f_searchdecl},
7677 {"searchpair", 3, 7, f_searchpair},
7678 {"searchpairpos", 3, 7, f_searchpairpos},
7679 {"searchpos", 1, 4, f_searchpos},
7680 {"server2client", 2, 2, f_server2client},
7681 {"serverlist", 0, 0, f_serverlist},
7682 {"setbufvar", 3, 3, f_setbufvar},
7683 {"setcmdpos", 1, 1, f_setcmdpos},
7684 {"setline", 2, 2, f_setline},
7685 {"setloclist", 2, 3, f_setloclist},
7686 {"setmatches", 1, 1, f_setmatches},
7687 {"setpos", 2, 2, f_setpos},
7688 {"setqflist", 1, 2, f_setqflist},
7689 {"setreg", 2, 3, f_setreg},
7690 {"settabwinvar", 4, 4, f_settabwinvar},
7691 {"setwinvar", 3, 3, f_setwinvar},
7692 {"shellescape", 1, 2, f_shellescape},
7693 {"simplify", 1, 1, f_simplify},
7694 #ifdef FEAT_FLOAT
7695 {"sin", 1, 1, f_sin},
7696 #endif
7697 {"sort", 1, 2, f_sort},
7698 {"soundfold", 1, 1, f_soundfold},
7699 {"spellbadword", 0, 1, f_spellbadword},
7700 {"spellsuggest", 1, 3, f_spellsuggest},
7701 {"split", 1, 3, f_split},
7702 #ifdef FEAT_FLOAT
7703 {"sqrt", 1, 1, f_sqrt},
7704 {"str2float", 1, 1, f_str2float},
7705 #endif
7706 {"str2nr", 1, 2, f_str2nr},
7707 #ifdef HAVE_STRFTIME
7708 {"strftime", 1, 2, f_strftime},
7709 #endif
7710 {"stridx", 2, 3, f_stridx},
7711 {"string", 1, 1, f_string},
7712 {"strlen", 1, 1, f_strlen},
7713 {"strpart", 2, 3, f_strpart},
7714 {"strridx", 2, 3, f_strridx},
7715 {"strtrans", 1, 1, f_strtrans},
7716 {"submatch", 1, 1, f_submatch},
7717 {"substitute", 4, 4, f_substitute},
7718 {"synID", 3, 3, f_synID},
7719 {"synIDattr", 2, 3, f_synIDattr},
7720 {"synIDtrans", 1, 1, f_synIDtrans},
7721 {"synstack", 2, 2, f_synstack},
7722 {"system", 1, 2, f_system},
7723 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7724 {"tabpagenr", 0, 1, f_tabpagenr},
7725 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7726 {"tagfiles", 0, 0, f_tagfiles},
7727 {"taglist", 1, 1, f_taglist},
7728 {"tempname", 0, 0, f_tempname},
7729 {"test", 1, 1, f_test},
7730 {"tolower", 1, 1, f_tolower},
7731 {"toupper", 1, 1, f_toupper},
7732 {"tr", 3, 3, f_tr},
7733 #ifdef FEAT_FLOAT
7734 {"trunc", 1, 1, f_trunc},
7735 #endif
7736 {"type", 1, 1, f_type},
7737 {"values", 1, 1, f_values},
7738 {"virtcol", 1, 1, f_virtcol},
7739 {"visualmode", 0, 1, f_visualmode},
7740 {"winbufnr", 1, 1, f_winbufnr},
7741 {"wincol", 0, 0, f_wincol},
7742 {"winheight", 1, 1, f_winheight},
7743 {"winline", 0, 0, f_winline},
7744 {"winnr", 0, 1, f_winnr},
7745 {"winrestcmd", 0, 0, f_winrestcmd},
7746 {"winrestview", 1, 1, f_winrestview},
7747 {"winsaveview", 0, 0, f_winsaveview},
7748 {"winwidth", 1, 1, f_winwidth},
7749 {"writefile", 2, 3, f_writefile},
7752 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7755 * Function given to ExpandGeneric() to obtain the list of internal
7756 * or user defined function names.
7758 char_u *
7759 get_function_name(xp, idx)
7760 expand_T *xp;
7761 int idx;
7763 static int intidx = -1;
7764 char_u *name;
7766 if (idx == 0)
7767 intidx = -1;
7768 if (intidx < 0)
7770 name = get_user_func_name(xp, idx);
7771 if (name != NULL)
7772 return name;
7774 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7776 STRCPY(IObuff, functions[intidx].f_name);
7777 STRCAT(IObuff, "(");
7778 if (functions[intidx].f_max_argc == 0)
7779 STRCAT(IObuff, ")");
7780 return IObuff;
7783 return NULL;
7787 * Function given to ExpandGeneric() to obtain the list of internal or
7788 * user defined variable or function names.
7790 /*ARGSUSED*/
7791 char_u *
7792 get_expr_name(xp, idx)
7793 expand_T *xp;
7794 int idx;
7796 static int intidx = -1;
7797 char_u *name;
7799 if (idx == 0)
7800 intidx = -1;
7801 if (intidx < 0)
7803 name = get_function_name(xp, idx);
7804 if (name != NULL)
7805 return name;
7807 return get_user_var_name(xp, ++intidx);
7810 #endif /* FEAT_CMDL_COMPL */
7813 * Find internal function in table above.
7814 * Return index, or -1 if not found
7816 static int
7817 find_internal_func(name)
7818 char_u *name; /* name of the function */
7820 int first = 0;
7821 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7822 int cmp;
7823 int x;
7826 * Find the function name in the table. Binary search.
7828 while (first <= last)
7830 x = first + ((unsigned)(last - first) >> 1);
7831 cmp = STRCMP(name, functions[x].f_name);
7832 if (cmp < 0)
7833 last = x - 1;
7834 else if (cmp > 0)
7835 first = x + 1;
7836 else
7837 return x;
7839 return -1;
7843 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7844 * name it contains, otherwise return "name".
7846 static char_u *
7847 deref_func_name(name, lenp)
7848 char_u *name;
7849 int *lenp;
7851 dictitem_T *v;
7852 int cc;
7854 cc = name[*lenp];
7855 name[*lenp] = NUL;
7856 v = find_var(name, NULL);
7857 name[*lenp] = cc;
7858 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7860 if (v->di_tv.vval.v_string == NULL)
7862 *lenp = 0;
7863 return (char_u *)""; /* just in case */
7865 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7866 return v->di_tv.vval.v_string;
7869 return name;
7873 * Allocate a variable for the result of a function.
7874 * Return OK or FAIL.
7876 static int
7877 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7878 evaluate, selfdict)
7879 char_u *name; /* name of the function */
7880 int len; /* length of "name" */
7881 typval_T *rettv;
7882 char_u **arg; /* argument, pointing to the '(' */
7883 linenr_T firstline; /* first line of range */
7884 linenr_T lastline; /* last line of range */
7885 int *doesrange; /* return: function handled range */
7886 int evaluate;
7887 dict_T *selfdict; /* Dictionary for "self" */
7889 char_u *argp;
7890 int ret = OK;
7891 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7892 int argcount = 0; /* number of arguments found */
7895 * Get the arguments.
7897 argp = *arg;
7898 while (argcount < MAX_FUNC_ARGS)
7900 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7901 if (*argp == ')' || *argp == ',' || *argp == NUL)
7902 break;
7903 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7905 ret = FAIL;
7906 break;
7908 ++argcount;
7909 if (*argp != ',')
7910 break;
7912 if (*argp == ')')
7913 ++argp;
7914 else
7915 ret = FAIL;
7917 if (ret == OK)
7918 ret = call_func(name, len, rettv, argcount, argvars,
7919 firstline, lastline, doesrange, evaluate, selfdict);
7920 else if (!aborting())
7922 if (argcount == MAX_FUNC_ARGS)
7923 emsg_funcname(N_("E740: Too many arguments for function %s"), name);
7924 else
7925 emsg_funcname(N_("E116: Invalid arguments for function %s"), name);
7928 while (--argcount >= 0)
7929 clear_tv(&argvars[argcount]);
7931 *arg = skipwhite(argp);
7932 return ret;
7937 * Call a function with its resolved parameters
7938 * Return OK when the function can't be called, FAIL otherwise.
7939 * Also returns OK when an error was encountered while executing the function.
7941 static int
7942 call_func(name, len, rettv, argcount, argvars, firstline, lastline,
7943 doesrange, evaluate, selfdict)
7944 char_u *name; /* name of the function */
7945 int len; /* length of "name" */
7946 typval_T *rettv; /* return value goes here */
7947 int argcount; /* number of "argvars" */
7948 typval_T *argvars; /* vars for arguments, must have "argcount"
7949 PLUS ONE elements! */
7950 linenr_T firstline; /* first line of range */
7951 linenr_T lastline; /* last line of range */
7952 int *doesrange; /* return: function handled range */
7953 int evaluate;
7954 dict_T *selfdict; /* Dictionary for "self" */
7956 int ret = FAIL;
7957 #define ERROR_UNKNOWN 0
7958 #define ERROR_TOOMANY 1
7959 #define ERROR_TOOFEW 2
7960 #define ERROR_SCRIPT 3
7961 #define ERROR_DICT 4
7962 #define ERROR_NONE 5
7963 #define ERROR_OTHER 6
7964 int error = ERROR_NONE;
7965 int i;
7966 int llen;
7967 ufunc_T *fp;
7968 int cc;
7969 #define FLEN_FIXED 40
7970 char_u fname_buf[FLEN_FIXED + 1];
7971 char_u *fname;
7974 * In a script change <SID>name() and s:name() to K_SNR 123_name().
7975 * Change <SNR>123_name() to K_SNR 123_name().
7976 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
7978 cc = name[len];
7979 name[len] = NUL;
7980 llen = eval_fname_script(name);
7981 if (llen > 0)
7983 fname_buf[0] = K_SPECIAL;
7984 fname_buf[1] = KS_EXTRA;
7985 fname_buf[2] = (int)KE_SNR;
7986 i = 3;
7987 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
7989 if (current_SID <= 0)
7990 error = ERROR_SCRIPT;
7991 else
7993 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
7994 i = (int)STRLEN(fname_buf);
7997 if (i + STRLEN(name + llen) < FLEN_FIXED)
7999 STRCPY(fname_buf + i, name + llen);
8000 fname = fname_buf;
8002 else
8004 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
8005 if (fname == NULL)
8006 error = ERROR_OTHER;
8007 else
8009 mch_memmove(fname, fname_buf, (size_t)i);
8010 STRCPY(fname + i, name + llen);
8014 else
8015 fname = name;
8017 *doesrange = FALSE;
8020 /* execute the function if no errors detected and executing */
8021 if (evaluate && error == ERROR_NONE)
8023 rettv->v_type = VAR_NUMBER; /* default rettv is number zero */
8024 rettv->vval.v_number = 0;
8025 error = ERROR_UNKNOWN;
8027 if (!builtin_function(fname))
8030 * User defined function.
8032 fp = find_func(fname);
8034 #ifdef FEAT_AUTOCMD
8035 /* Trigger FuncUndefined event, may load the function. */
8036 if (fp == NULL
8037 && apply_autocmds(EVENT_FUNCUNDEFINED,
8038 fname, fname, TRUE, NULL)
8039 && !aborting())
8041 /* executed an autocommand, search for the function again */
8042 fp = find_func(fname);
8044 #endif
8045 /* Try loading a package. */
8046 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
8048 /* loaded a package, search for the function again */
8049 fp = find_func(fname);
8052 if (fp != NULL)
8054 if (fp->uf_flags & FC_RANGE)
8055 *doesrange = TRUE;
8056 if (argcount < fp->uf_args.ga_len)
8057 error = ERROR_TOOFEW;
8058 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
8059 error = ERROR_TOOMANY;
8060 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
8061 error = ERROR_DICT;
8062 else
8065 * Call the user function.
8066 * Save and restore search patterns, script variables and
8067 * redo buffer.
8069 save_search_patterns();
8070 saveRedobuff();
8071 ++fp->uf_calls;
8072 call_user_func(fp, argcount, argvars, rettv,
8073 firstline, lastline,
8074 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
8075 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
8076 && fp->uf_refcount <= 0)
8077 /* Function was unreferenced while being used, free it
8078 * now. */
8079 func_free(fp);
8080 restoreRedobuff();
8081 restore_search_patterns();
8082 error = ERROR_NONE;
8086 else
8089 * Find the function name in the table, call its implementation.
8091 i = find_internal_func(fname);
8092 if (i >= 0)
8094 if (argcount < functions[i].f_min_argc)
8095 error = ERROR_TOOFEW;
8096 else if (argcount > functions[i].f_max_argc)
8097 error = ERROR_TOOMANY;
8098 else
8100 argvars[argcount].v_type = VAR_UNKNOWN;
8101 functions[i].f_func(argvars, rettv);
8102 error = ERROR_NONE;
8107 * The function call (or "FuncUndefined" autocommand sequence) might
8108 * have been aborted by an error, an interrupt, or an explicitly thrown
8109 * exception that has not been caught so far. This situation can be
8110 * tested for by calling aborting(). For an error in an internal
8111 * function or for the "E132" error in call_user_func(), however, the
8112 * throw point at which the "force_abort" flag (temporarily reset by
8113 * emsg()) is normally updated has not been reached yet. We need to
8114 * update that flag first to make aborting() reliable.
8116 update_force_abort();
8118 if (error == ERROR_NONE)
8119 ret = OK;
8122 * Report an error unless the argument evaluation or function call has been
8123 * cancelled due to an aborting error, an interrupt, or an exception.
8125 if (!aborting())
8127 switch (error)
8129 case ERROR_UNKNOWN:
8130 emsg_funcname(N_("E117: Unknown function: %s"), name);
8131 break;
8132 case ERROR_TOOMANY:
8133 emsg_funcname(e_toomanyarg, name);
8134 break;
8135 case ERROR_TOOFEW:
8136 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
8137 name);
8138 break;
8139 case ERROR_SCRIPT:
8140 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
8141 name);
8142 break;
8143 case ERROR_DICT:
8144 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
8145 name);
8146 break;
8150 name[len] = cc;
8151 if (fname != name && fname != fname_buf)
8152 vim_free(fname);
8154 return ret;
8158 * Give an error message with a function name. Handle <SNR> things.
8159 * "ermsg" is to be passed without translation, use N_() instead of _().
8161 static void
8162 emsg_funcname(ermsg, name)
8163 char *ermsg;
8164 char_u *name;
8166 char_u *p;
8168 if (*name == K_SPECIAL)
8169 p = concat_str((char_u *)"<SNR>", name + 3);
8170 else
8171 p = name;
8172 EMSG2(_(ermsg), p);
8173 if (p != name)
8174 vim_free(p);
8178 * Return TRUE for a non-zero Number and a non-empty String.
8180 static int
8181 non_zero_arg(argvars)
8182 typval_T *argvars;
8184 return ((argvars[0].v_type == VAR_NUMBER
8185 && argvars[0].vval.v_number != 0)
8186 || (argvars[0].v_type == VAR_STRING
8187 && argvars[0].vval.v_string != NULL
8188 && *argvars[0].vval.v_string != NUL));
8191 /*********************************************
8192 * Implementation of the built-in functions
8195 #ifdef FEAT_FLOAT
8197 * "abs(expr)" function
8199 static void
8200 f_abs(argvars, rettv)
8201 typval_T *argvars;
8202 typval_T *rettv;
8204 if (argvars[0].v_type == VAR_FLOAT)
8206 rettv->v_type = VAR_FLOAT;
8207 rettv->vval.v_float = fabs(argvars[0].vval.v_float);
8209 else
8211 varnumber_T n;
8212 int error = FALSE;
8214 n = get_tv_number_chk(&argvars[0], &error);
8215 if (error)
8216 rettv->vval.v_number = -1;
8217 else if (n > 0)
8218 rettv->vval.v_number = n;
8219 else
8220 rettv->vval.v_number = -n;
8223 #endif
8226 * "add(list, item)" function
8228 static void
8229 f_add(argvars, rettv)
8230 typval_T *argvars;
8231 typval_T *rettv;
8233 list_T *l;
8235 rettv->vval.v_number = 1; /* Default: Failed */
8236 if (argvars[0].v_type == VAR_LIST)
8238 if ((l = argvars[0].vval.v_list) != NULL
8239 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
8240 && list_append_tv(l, &argvars[1]) == OK)
8241 copy_tv(&argvars[0], rettv);
8243 else
8244 EMSG(_(e_listreq));
8248 * "append(lnum, string/list)" function
8250 static void
8251 f_append(argvars, rettv)
8252 typval_T *argvars;
8253 typval_T *rettv;
8255 long lnum;
8256 char_u *line;
8257 list_T *l = NULL;
8258 listitem_T *li = NULL;
8259 typval_T *tv;
8260 long added = 0;
8262 lnum = get_tv_lnum(argvars);
8263 if (lnum >= 0
8264 && lnum <= curbuf->b_ml.ml_line_count
8265 && u_save(lnum, lnum + 1) == OK)
8267 if (argvars[1].v_type == VAR_LIST)
8269 l = argvars[1].vval.v_list;
8270 if (l == NULL)
8271 return;
8272 li = l->lv_first;
8274 for (;;)
8276 if (l == NULL)
8277 tv = &argvars[1]; /* append a string */
8278 else if (li == NULL)
8279 break; /* end of list */
8280 else
8281 tv = &li->li_tv; /* append item from list */
8282 line = get_tv_string_chk(tv);
8283 if (line == NULL) /* type error */
8285 rettv->vval.v_number = 1; /* Failed */
8286 break;
8288 ml_append(lnum + added, line, (colnr_T)0, FALSE);
8289 ++added;
8290 if (l == NULL)
8291 break;
8292 li = li->li_next;
8295 appended_lines_mark(lnum, added);
8296 if (curwin->w_cursor.lnum > lnum)
8297 curwin->w_cursor.lnum += added;
8299 else
8300 rettv->vval.v_number = 1; /* Failed */
8304 * "argc()" function
8306 /* ARGSUSED */
8307 static void
8308 f_argc(argvars, rettv)
8309 typval_T *argvars;
8310 typval_T *rettv;
8312 rettv->vval.v_number = ARGCOUNT;
8316 * "argidx()" function
8318 /* ARGSUSED */
8319 static void
8320 f_argidx(argvars, rettv)
8321 typval_T *argvars;
8322 typval_T *rettv;
8324 rettv->vval.v_number = curwin->w_arg_idx;
8328 * "argv(nr)" function
8330 static void
8331 f_argv(argvars, rettv)
8332 typval_T *argvars;
8333 typval_T *rettv;
8335 int idx;
8337 if (argvars[0].v_type != VAR_UNKNOWN)
8339 idx = get_tv_number_chk(&argvars[0], NULL);
8340 if (idx >= 0 && idx < ARGCOUNT)
8341 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
8342 else
8343 rettv->vval.v_string = NULL;
8344 rettv->v_type = VAR_STRING;
8346 else if (rettv_list_alloc(rettv) == OK)
8347 for (idx = 0; idx < ARGCOUNT; ++idx)
8348 list_append_string(rettv->vval.v_list,
8349 alist_name(&ARGLIST[idx]), -1);
8352 #ifdef FEAT_FLOAT
8353 static int get_float_arg __ARGS((typval_T *argvars, float_T *f));
8356 * Get the float value of "argvars[0]" into "f".
8357 * Returns FAIL when the argument is not a Number or Float.
8359 static int
8360 get_float_arg(argvars, f)
8361 typval_T *argvars;
8362 float_T *f;
8364 if (argvars[0].v_type == VAR_FLOAT)
8366 *f = argvars[0].vval.v_float;
8367 return OK;
8369 if (argvars[0].v_type == VAR_NUMBER)
8371 *f = (float_T)argvars[0].vval.v_number;
8372 return OK;
8374 EMSG(_("E808: Number or Float required"));
8375 return FAIL;
8379 * "atan()" function
8381 static void
8382 f_atan(argvars, rettv)
8383 typval_T *argvars;
8384 typval_T *rettv;
8386 float_T f;
8388 rettv->v_type = VAR_FLOAT;
8389 if (get_float_arg(argvars, &f) == OK)
8390 rettv->vval.v_float = atan(f);
8391 else
8392 rettv->vval.v_float = 0.0;
8394 #endif
8397 * "browse(save, title, initdir, default)" function
8399 /* ARGSUSED */
8400 static void
8401 f_browse(argvars, rettv)
8402 typval_T *argvars;
8403 typval_T *rettv;
8405 #ifdef FEAT_BROWSE
8406 int save;
8407 char_u *title;
8408 char_u *initdir;
8409 char_u *defname;
8410 char_u buf[NUMBUFLEN];
8411 char_u buf2[NUMBUFLEN];
8412 int error = FALSE;
8414 save = get_tv_number_chk(&argvars[0], &error);
8415 title = get_tv_string_chk(&argvars[1]);
8416 initdir = get_tv_string_buf_chk(&argvars[2], buf);
8417 defname = get_tv_string_buf_chk(&argvars[3], buf2);
8419 if (error || title == NULL || initdir == NULL || defname == NULL)
8420 rettv->vval.v_string = NULL;
8421 else
8422 rettv->vval.v_string =
8423 do_browse(save ? BROWSE_SAVE : 0,
8424 title, defname, NULL, initdir, NULL, curbuf);
8425 #else
8426 rettv->vval.v_string = NULL;
8427 #endif
8428 rettv->v_type = VAR_STRING;
8432 * "browsedir(title, initdir)" function
8434 /* ARGSUSED */
8435 static void
8436 f_browsedir(argvars, rettv)
8437 typval_T *argvars;
8438 typval_T *rettv;
8440 #ifdef FEAT_BROWSE
8441 char_u *title;
8442 char_u *initdir;
8443 char_u buf[NUMBUFLEN];
8445 title = get_tv_string_chk(&argvars[0]);
8446 initdir = get_tv_string_buf_chk(&argvars[1], buf);
8448 if (title == NULL || initdir == NULL)
8449 rettv->vval.v_string = NULL;
8450 else
8451 rettv->vval.v_string = do_browse(BROWSE_DIR,
8452 title, NULL, NULL, initdir, NULL, curbuf);
8453 #else
8454 rettv->vval.v_string = NULL;
8455 #endif
8456 rettv->v_type = VAR_STRING;
8459 static buf_T *find_buffer __ARGS((typval_T *avar));
8462 * Find a buffer by number or exact name.
8464 static buf_T *
8465 find_buffer(avar)
8466 typval_T *avar;
8468 buf_T *buf = NULL;
8470 if (avar->v_type == VAR_NUMBER)
8471 buf = buflist_findnr((int)avar->vval.v_number);
8472 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
8474 buf = buflist_findname_exp(avar->vval.v_string);
8475 if (buf == NULL)
8477 /* No full path name match, try a match with a URL or a "nofile"
8478 * buffer, these don't use the full path. */
8479 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8480 if (buf->b_fname != NULL
8481 && (path_with_url(buf->b_fname)
8482 #ifdef FEAT_QUICKFIX
8483 || bt_nofile(buf)
8484 #endif
8486 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
8487 break;
8490 return buf;
8494 * "bufexists(expr)" function
8496 static void
8497 f_bufexists(argvars, rettv)
8498 typval_T *argvars;
8499 typval_T *rettv;
8501 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
8505 * "buflisted(expr)" function
8507 static void
8508 f_buflisted(argvars, rettv)
8509 typval_T *argvars;
8510 typval_T *rettv;
8512 buf_T *buf;
8514 buf = find_buffer(&argvars[0]);
8515 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
8519 * "bufloaded(expr)" function
8521 static void
8522 f_bufloaded(argvars, rettv)
8523 typval_T *argvars;
8524 typval_T *rettv;
8526 buf_T *buf;
8528 buf = find_buffer(&argvars[0]);
8529 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
8532 static buf_T *get_buf_tv __ARGS((typval_T *tv));
8535 * Get buffer by number or pattern.
8537 static buf_T *
8538 get_buf_tv(tv)
8539 typval_T *tv;
8541 char_u *name = tv->vval.v_string;
8542 int save_magic;
8543 char_u *save_cpo;
8544 buf_T *buf;
8546 if (tv->v_type == VAR_NUMBER)
8547 return buflist_findnr((int)tv->vval.v_number);
8548 if (tv->v_type != VAR_STRING)
8549 return NULL;
8550 if (name == NULL || *name == NUL)
8551 return curbuf;
8552 if (name[0] == '$' && name[1] == NUL)
8553 return lastbuf;
8555 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
8556 save_magic = p_magic;
8557 p_magic = TRUE;
8558 save_cpo = p_cpo;
8559 p_cpo = (char_u *)"";
8561 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8562 TRUE, FALSE));
8564 p_magic = save_magic;
8565 p_cpo = save_cpo;
8567 /* If not found, try expanding the name, like done for bufexists(). */
8568 if (buf == NULL)
8569 buf = find_buffer(tv);
8571 return buf;
8575 * "bufname(expr)" function
8577 static void
8578 f_bufname(argvars, rettv)
8579 typval_T *argvars;
8580 typval_T *rettv;
8582 buf_T *buf;
8584 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8585 ++emsg_off;
8586 buf = get_buf_tv(&argvars[0]);
8587 rettv->v_type = VAR_STRING;
8588 if (buf != NULL && buf->b_fname != NULL)
8589 rettv->vval.v_string = vim_strsave(buf->b_fname);
8590 else
8591 rettv->vval.v_string = NULL;
8592 --emsg_off;
8596 * "bufnr(expr)" function
8598 static void
8599 f_bufnr(argvars, rettv)
8600 typval_T *argvars;
8601 typval_T *rettv;
8603 buf_T *buf;
8604 int error = FALSE;
8605 char_u *name;
8607 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8608 ++emsg_off;
8609 buf = get_buf_tv(&argvars[0]);
8610 --emsg_off;
8612 /* If the buffer isn't found and the second argument is not zero create a
8613 * new buffer. */
8614 if (buf == NULL
8615 && argvars[1].v_type != VAR_UNKNOWN
8616 && get_tv_number_chk(&argvars[1], &error) != 0
8617 && !error
8618 && (name = get_tv_string_chk(&argvars[0])) != NULL
8619 && !error)
8620 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8622 if (buf != NULL)
8623 rettv->vval.v_number = buf->b_fnum;
8624 else
8625 rettv->vval.v_number = -1;
8629 * "bufwinnr(nr)" function
8631 static void
8632 f_bufwinnr(argvars, rettv)
8633 typval_T *argvars;
8634 typval_T *rettv;
8636 #ifdef FEAT_WINDOWS
8637 win_T *wp;
8638 int winnr = 0;
8639 #endif
8640 buf_T *buf;
8642 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8643 ++emsg_off;
8644 buf = get_buf_tv(&argvars[0]);
8645 #ifdef FEAT_WINDOWS
8646 for (wp = firstwin; wp; wp = wp->w_next)
8648 ++winnr;
8649 if (wp->w_buffer == buf)
8650 break;
8652 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8653 #else
8654 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8655 #endif
8656 --emsg_off;
8660 * "byte2line(byte)" function
8662 /*ARGSUSED*/
8663 static void
8664 f_byte2line(argvars, rettv)
8665 typval_T *argvars;
8666 typval_T *rettv;
8668 #ifndef FEAT_BYTEOFF
8669 rettv->vval.v_number = -1;
8670 #else
8671 long boff = 0;
8673 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8674 if (boff < 0)
8675 rettv->vval.v_number = -1;
8676 else
8677 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8678 (linenr_T)0, &boff);
8679 #endif
8683 * "byteidx()" function
8685 /*ARGSUSED*/
8686 static void
8687 f_byteidx(argvars, rettv)
8688 typval_T *argvars;
8689 typval_T *rettv;
8691 #ifdef FEAT_MBYTE
8692 char_u *t;
8693 #endif
8694 char_u *str;
8695 long idx;
8697 str = get_tv_string_chk(&argvars[0]);
8698 idx = get_tv_number_chk(&argvars[1], NULL);
8699 rettv->vval.v_number = -1;
8700 if (str == NULL || idx < 0)
8701 return;
8703 #ifdef FEAT_MBYTE
8704 t = str;
8705 for ( ; idx > 0; idx--)
8707 if (*t == NUL) /* EOL reached */
8708 return;
8709 t += (*mb_ptr2len)(t);
8711 rettv->vval.v_number = (varnumber_T)(t - str);
8712 #else
8713 if ((size_t)idx <= STRLEN(str))
8714 rettv->vval.v_number = idx;
8715 #endif
8719 * "call(func, arglist)" function
8721 static void
8722 f_call(argvars, rettv)
8723 typval_T *argvars;
8724 typval_T *rettv;
8726 char_u *func;
8727 typval_T argv[MAX_FUNC_ARGS + 1];
8728 int argc = 0;
8729 listitem_T *item;
8730 int dummy;
8731 dict_T *selfdict = NULL;
8733 if (argvars[1].v_type != VAR_LIST)
8735 EMSG(_(e_listreq));
8736 return;
8738 if (argvars[1].vval.v_list == NULL)
8739 return;
8741 if (argvars[0].v_type == VAR_FUNC)
8742 func = argvars[0].vval.v_string;
8743 else
8744 func = get_tv_string(&argvars[0]);
8745 if (*func == NUL)
8746 return; /* type error or empty name */
8748 if (argvars[2].v_type != VAR_UNKNOWN)
8750 if (argvars[2].v_type != VAR_DICT)
8752 EMSG(_(e_dictreq));
8753 return;
8755 selfdict = argvars[2].vval.v_dict;
8758 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
8759 item = item->li_next)
8761 if (argc == MAX_FUNC_ARGS)
8763 EMSG(_("E699: Too many arguments"));
8764 break;
8766 /* Make a copy of each argument. This is needed to be able to set
8767 * v_lock to VAR_FIXED in the copy without changing the original list.
8769 copy_tv(&item->li_tv, &argv[argc++]);
8772 if (item == NULL)
8773 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
8774 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
8775 &dummy, TRUE, selfdict);
8777 /* Free the arguments. */
8778 while (argc > 0)
8779 clear_tv(&argv[--argc]);
8782 #ifdef FEAT_FLOAT
8784 * "ceil({float})" function
8786 static void
8787 f_ceil(argvars, rettv)
8788 typval_T *argvars;
8789 typval_T *rettv;
8791 float_T f;
8793 rettv->v_type = VAR_FLOAT;
8794 if (get_float_arg(argvars, &f) == OK)
8795 rettv->vval.v_float = ceil(f);
8796 else
8797 rettv->vval.v_float = 0.0;
8799 #endif
8802 * "changenr()" function
8804 /*ARGSUSED*/
8805 static void
8806 f_changenr(argvars, rettv)
8807 typval_T *argvars;
8808 typval_T *rettv;
8810 rettv->vval.v_number = curbuf->b_u_seq_cur;
8814 * "char2nr(string)" function
8816 static void
8817 f_char2nr(argvars, rettv)
8818 typval_T *argvars;
8819 typval_T *rettv;
8821 #ifdef FEAT_MBYTE
8822 if (has_mbyte)
8823 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
8824 else
8825 #endif
8826 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
8830 * "cindent(lnum)" function
8832 static void
8833 f_cindent(argvars, rettv)
8834 typval_T *argvars;
8835 typval_T *rettv;
8837 #ifdef FEAT_CINDENT
8838 pos_T pos;
8839 linenr_T lnum;
8841 pos = curwin->w_cursor;
8842 lnum = get_tv_lnum(argvars);
8843 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
8845 curwin->w_cursor.lnum = lnum;
8846 rettv->vval.v_number = get_c_indent();
8847 curwin->w_cursor = pos;
8849 else
8850 #endif
8851 rettv->vval.v_number = -1;
8855 * "clearmatches()" function
8857 /*ARGSUSED*/
8858 static void
8859 f_clearmatches(argvars, rettv)
8860 typval_T *argvars;
8861 typval_T *rettv;
8863 #ifdef FEAT_SEARCH_EXTRA
8864 clear_matches(curwin);
8865 #endif
8869 * "col(string)" function
8871 static void
8872 f_col(argvars, rettv)
8873 typval_T *argvars;
8874 typval_T *rettv;
8876 colnr_T col = 0;
8877 pos_T *fp;
8878 int fnum = curbuf->b_fnum;
8880 fp = var2fpos(&argvars[0], FALSE, &fnum);
8881 if (fp != NULL && fnum == curbuf->b_fnum)
8883 if (fp->col == MAXCOL)
8885 /* '> can be MAXCOL, get the length of the line then */
8886 if (fp->lnum <= curbuf->b_ml.ml_line_count)
8887 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
8888 else
8889 col = MAXCOL;
8891 else
8893 col = fp->col + 1;
8894 #ifdef FEAT_VIRTUALEDIT
8895 /* col(".") when the cursor is on the NUL at the end of the line
8896 * because of "coladd" can be seen as an extra column. */
8897 if (virtual_active() && fp == &curwin->w_cursor)
8899 char_u *p = ml_get_cursor();
8901 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
8902 curwin->w_virtcol - curwin->w_cursor.coladd))
8904 # ifdef FEAT_MBYTE
8905 int l;
8907 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
8908 col += l;
8909 # else
8910 if (*p != NUL && p[1] == NUL)
8911 ++col;
8912 # endif
8915 #endif
8918 rettv->vval.v_number = col;
8921 #if defined(FEAT_INS_EXPAND)
8923 * "complete()" function
8925 /*ARGSUSED*/
8926 static void
8927 f_complete(argvars, rettv)
8928 typval_T *argvars;
8929 typval_T *rettv;
8931 int startcol;
8933 if ((State & INSERT) == 0)
8935 EMSG(_("E785: complete() can only be used in Insert mode"));
8936 return;
8939 /* Check for undo allowed here, because if something was already inserted
8940 * the line was already saved for undo and this check isn't done. */
8941 if (!undo_allowed())
8942 return;
8944 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
8946 EMSG(_(e_invarg));
8947 return;
8950 startcol = get_tv_number_chk(&argvars[0], NULL);
8951 if (startcol <= 0)
8952 return;
8954 set_completion(startcol - 1, argvars[1].vval.v_list);
8958 * "complete_add()" function
8960 /*ARGSUSED*/
8961 static void
8962 f_complete_add(argvars, rettv)
8963 typval_T *argvars;
8964 typval_T *rettv;
8966 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
8970 * "complete_check()" function
8972 /*ARGSUSED*/
8973 static void
8974 f_complete_check(argvars, rettv)
8975 typval_T *argvars;
8976 typval_T *rettv;
8978 int saved = RedrawingDisabled;
8980 RedrawingDisabled = 0;
8981 ins_compl_check_keys(0);
8982 rettv->vval.v_number = compl_interrupted;
8983 RedrawingDisabled = saved;
8985 #endif
8988 * "confirm(message, buttons[, default [, type]])" function
8990 /*ARGSUSED*/
8991 static void
8992 f_confirm(argvars, rettv)
8993 typval_T *argvars;
8994 typval_T *rettv;
8996 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
8997 char_u *message;
8998 char_u *buttons = NULL;
8999 char_u buf[NUMBUFLEN];
9000 char_u buf2[NUMBUFLEN];
9001 int def = 1;
9002 int type = VIM_GENERIC;
9003 char_u *typestr;
9004 int error = FALSE;
9006 message = get_tv_string_chk(&argvars[0]);
9007 if (message == NULL)
9008 error = TRUE;
9009 if (argvars[1].v_type != VAR_UNKNOWN)
9011 buttons = get_tv_string_buf_chk(&argvars[1], buf);
9012 if (buttons == NULL)
9013 error = TRUE;
9014 if (argvars[2].v_type != VAR_UNKNOWN)
9016 def = get_tv_number_chk(&argvars[2], &error);
9017 if (argvars[3].v_type != VAR_UNKNOWN)
9019 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
9020 if (typestr == NULL)
9021 error = TRUE;
9022 else
9024 switch (TOUPPER_ASC(*typestr))
9026 case 'E': type = VIM_ERROR; break;
9027 case 'Q': type = VIM_QUESTION; break;
9028 case 'I': type = VIM_INFO; break;
9029 case 'W': type = VIM_WARNING; break;
9030 case 'G': type = VIM_GENERIC; break;
9037 if (buttons == NULL || *buttons == NUL)
9038 buttons = (char_u *)_("&Ok");
9040 if (!error)
9041 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
9042 def, NULL);
9043 #endif
9047 * "copy()" function
9049 static void
9050 f_copy(argvars, rettv)
9051 typval_T *argvars;
9052 typval_T *rettv;
9054 item_copy(&argvars[0], rettv, FALSE, 0);
9057 #ifdef FEAT_FLOAT
9059 * "cos()" function
9061 static void
9062 f_cos(argvars, rettv)
9063 typval_T *argvars;
9064 typval_T *rettv;
9066 float_T f;
9068 rettv->v_type = VAR_FLOAT;
9069 if (get_float_arg(argvars, &f) == OK)
9070 rettv->vval.v_float = cos(f);
9071 else
9072 rettv->vval.v_float = 0.0;
9074 #endif
9077 * "count()" function
9079 static void
9080 f_count(argvars, rettv)
9081 typval_T *argvars;
9082 typval_T *rettv;
9084 long n = 0;
9085 int ic = FALSE;
9087 if (argvars[0].v_type == VAR_LIST)
9089 listitem_T *li;
9090 list_T *l;
9091 long idx;
9093 if ((l = argvars[0].vval.v_list) != NULL)
9095 li = l->lv_first;
9096 if (argvars[2].v_type != VAR_UNKNOWN)
9098 int error = FALSE;
9100 ic = get_tv_number_chk(&argvars[2], &error);
9101 if (argvars[3].v_type != VAR_UNKNOWN)
9103 idx = get_tv_number_chk(&argvars[3], &error);
9104 if (!error)
9106 li = list_find(l, idx);
9107 if (li == NULL)
9108 EMSGN(_(e_listidx), idx);
9111 if (error)
9112 li = NULL;
9115 for ( ; li != NULL; li = li->li_next)
9116 if (tv_equal(&li->li_tv, &argvars[1], ic))
9117 ++n;
9120 else if (argvars[0].v_type == VAR_DICT)
9122 int todo;
9123 dict_T *d;
9124 hashitem_T *hi;
9126 if ((d = argvars[0].vval.v_dict) != NULL)
9128 int error = FALSE;
9130 if (argvars[2].v_type != VAR_UNKNOWN)
9132 ic = get_tv_number_chk(&argvars[2], &error);
9133 if (argvars[3].v_type != VAR_UNKNOWN)
9134 EMSG(_(e_invarg));
9137 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
9138 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
9140 if (!HASHITEM_EMPTY(hi))
9142 --todo;
9143 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
9144 ++n;
9149 else
9150 EMSG2(_(e_listdictarg), "count()");
9151 rettv->vval.v_number = n;
9155 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
9157 * Checks the existence of a cscope connection.
9159 /*ARGSUSED*/
9160 static void
9161 f_cscope_connection(argvars, rettv)
9162 typval_T *argvars;
9163 typval_T *rettv;
9165 #ifdef FEAT_CSCOPE
9166 int num = 0;
9167 char_u *dbpath = NULL;
9168 char_u *prepend = NULL;
9169 char_u buf[NUMBUFLEN];
9171 if (argvars[0].v_type != VAR_UNKNOWN
9172 && argvars[1].v_type != VAR_UNKNOWN)
9174 num = (int)get_tv_number(&argvars[0]);
9175 dbpath = get_tv_string(&argvars[1]);
9176 if (argvars[2].v_type != VAR_UNKNOWN)
9177 prepend = get_tv_string_buf(&argvars[2], buf);
9180 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
9181 #endif
9185 * "cursor(lnum, col)" function
9187 * Moves the cursor to the specified line and column.
9188 * Returns 0 when the position could be set, -1 otherwise.
9190 /*ARGSUSED*/
9191 static void
9192 f_cursor(argvars, rettv)
9193 typval_T *argvars;
9194 typval_T *rettv;
9196 long line, col;
9197 #ifdef FEAT_VIRTUALEDIT
9198 long coladd = 0;
9199 #endif
9201 rettv->vval.v_number = -1;
9202 if (argvars[1].v_type == VAR_UNKNOWN)
9204 pos_T pos;
9206 if (list2fpos(argvars, &pos, NULL) == FAIL)
9207 return;
9208 line = pos.lnum;
9209 col = pos.col;
9210 #ifdef FEAT_VIRTUALEDIT
9211 coladd = pos.coladd;
9212 #endif
9214 else
9216 line = get_tv_lnum(argvars);
9217 col = get_tv_number_chk(&argvars[1], NULL);
9218 #ifdef FEAT_VIRTUALEDIT
9219 if (argvars[2].v_type != VAR_UNKNOWN)
9220 coladd = get_tv_number_chk(&argvars[2], NULL);
9221 #endif
9223 if (line < 0 || col < 0
9224 #ifdef FEAT_VIRTUALEDIT
9225 || coladd < 0
9226 #endif
9228 return; /* type error; errmsg already given */
9229 if (line > 0)
9230 curwin->w_cursor.lnum = line;
9231 if (col > 0)
9232 curwin->w_cursor.col = col - 1;
9233 #ifdef FEAT_VIRTUALEDIT
9234 curwin->w_cursor.coladd = coladd;
9235 #endif
9237 /* Make sure the cursor is in a valid position. */
9238 check_cursor();
9239 #ifdef FEAT_MBYTE
9240 /* Correct cursor for multi-byte character. */
9241 if (has_mbyte)
9242 mb_adjust_cursor();
9243 #endif
9245 curwin->w_set_curswant = TRUE;
9246 rettv->vval.v_number = 0;
9250 * "deepcopy()" function
9252 static void
9253 f_deepcopy(argvars, rettv)
9254 typval_T *argvars;
9255 typval_T *rettv;
9257 int noref = 0;
9259 if (argvars[1].v_type != VAR_UNKNOWN)
9260 noref = get_tv_number_chk(&argvars[1], NULL);
9261 if (noref < 0 || noref > 1)
9262 EMSG(_(e_invarg));
9263 else
9264 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? ++current_copyID : 0);
9268 * "delete()" function
9270 static void
9271 f_delete(argvars, rettv)
9272 typval_T *argvars;
9273 typval_T *rettv;
9275 if (check_restricted() || check_secure())
9276 rettv->vval.v_number = -1;
9277 else
9278 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
9282 * "did_filetype()" function
9284 /*ARGSUSED*/
9285 static void
9286 f_did_filetype(argvars, rettv)
9287 typval_T *argvars;
9288 typval_T *rettv;
9290 #ifdef FEAT_AUTOCMD
9291 rettv->vval.v_number = did_filetype;
9292 #endif
9296 * "diff_filler()" function
9298 /*ARGSUSED*/
9299 static void
9300 f_diff_filler(argvars, rettv)
9301 typval_T *argvars;
9302 typval_T *rettv;
9304 #ifdef FEAT_DIFF
9305 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
9306 #endif
9310 * "diff_hlID()" function
9312 /*ARGSUSED*/
9313 static void
9314 f_diff_hlID(argvars, rettv)
9315 typval_T *argvars;
9316 typval_T *rettv;
9318 #ifdef FEAT_DIFF
9319 linenr_T lnum = get_tv_lnum(argvars);
9320 static linenr_T prev_lnum = 0;
9321 static int changedtick = 0;
9322 static int fnum = 0;
9323 static int change_start = 0;
9324 static int change_end = 0;
9325 static hlf_T hlID = (hlf_T)0;
9326 int filler_lines;
9327 int col;
9329 if (lnum < 0) /* ignore type error in {lnum} arg */
9330 lnum = 0;
9331 if (lnum != prev_lnum
9332 || changedtick != curbuf->b_changedtick
9333 || fnum != curbuf->b_fnum)
9335 /* New line, buffer, change: need to get the values. */
9336 filler_lines = diff_check(curwin, lnum);
9337 if (filler_lines < 0)
9339 if (filler_lines == -1)
9341 change_start = MAXCOL;
9342 change_end = -1;
9343 if (diff_find_change(curwin, lnum, &change_start, &change_end))
9344 hlID = HLF_ADD; /* added line */
9345 else
9346 hlID = HLF_CHD; /* changed line */
9348 else
9349 hlID = HLF_ADD; /* added line */
9351 else
9352 hlID = (hlf_T)0;
9353 prev_lnum = lnum;
9354 changedtick = curbuf->b_changedtick;
9355 fnum = curbuf->b_fnum;
9358 if (hlID == HLF_CHD || hlID == HLF_TXD)
9360 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
9361 if (col >= change_start && col <= change_end)
9362 hlID = HLF_TXD; /* changed text */
9363 else
9364 hlID = HLF_CHD; /* changed line */
9366 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
9367 #endif
9371 * "empty({expr})" function
9373 static void
9374 f_empty(argvars, rettv)
9375 typval_T *argvars;
9376 typval_T *rettv;
9378 int n;
9380 switch (argvars[0].v_type)
9382 case VAR_STRING:
9383 case VAR_FUNC:
9384 n = argvars[0].vval.v_string == NULL
9385 || *argvars[0].vval.v_string == NUL;
9386 break;
9387 case VAR_NUMBER:
9388 n = argvars[0].vval.v_number == 0;
9389 break;
9390 #ifdef FEAT_FLOAT
9391 case VAR_FLOAT:
9392 n = argvars[0].vval.v_float == 0.0;
9393 break;
9394 #endif
9395 case VAR_LIST:
9396 n = argvars[0].vval.v_list == NULL
9397 || argvars[0].vval.v_list->lv_first == NULL;
9398 break;
9399 case VAR_DICT:
9400 n = argvars[0].vval.v_dict == NULL
9401 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
9402 break;
9403 default:
9404 EMSG2(_(e_intern2), "f_empty()");
9405 n = 0;
9408 rettv->vval.v_number = n;
9412 * "escape({string}, {chars})" function
9414 static void
9415 f_escape(argvars, rettv)
9416 typval_T *argvars;
9417 typval_T *rettv;
9419 char_u buf[NUMBUFLEN];
9421 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
9422 get_tv_string_buf(&argvars[1], buf));
9423 rettv->v_type = VAR_STRING;
9427 * "eval()" function
9429 /*ARGSUSED*/
9430 static void
9431 f_eval(argvars, rettv)
9432 typval_T *argvars;
9433 typval_T *rettv;
9435 char_u *s;
9437 s = get_tv_string_chk(&argvars[0]);
9438 if (s != NULL)
9439 s = skipwhite(s);
9441 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
9443 rettv->v_type = VAR_NUMBER;
9444 rettv->vval.v_number = 0;
9446 else if (*s != NUL)
9447 EMSG(_(e_trailing));
9451 * "eventhandler()" function
9453 /*ARGSUSED*/
9454 static void
9455 f_eventhandler(argvars, rettv)
9456 typval_T *argvars;
9457 typval_T *rettv;
9459 rettv->vval.v_number = vgetc_busy;
9463 * "executable()" function
9465 static void
9466 f_executable(argvars, rettv)
9467 typval_T *argvars;
9468 typval_T *rettv;
9470 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
9474 * "exists()" function
9476 static void
9477 f_exists(argvars, rettv)
9478 typval_T *argvars;
9479 typval_T *rettv;
9481 char_u *p;
9482 char_u *name;
9483 int n = FALSE;
9484 int len = 0;
9486 p = get_tv_string(&argvars[0]);
9487 if (*p == '$') /* environment variable */
9489 /* first try "normal" environment variables (fast) */
9490 if (mch_getenv(p + 1) != NULL)
9491 n = TRUE;
9492 else
9494 /* try expanding things like $VIM and ${HOME} */
9495 p = expand_env_save(p);
9496 if (p != NULL && *p != '$')
9497 n = TRUE;
9498 vim_free(p);
9501 else if (*p == '&' || *p == '+') /* option */
9503 n = (get_option_tv(&p, NULL, TRUE) == OK);
9504 if (*skipwhite(p) != NUL)
9505 n = FALSE; /* trailing garbage */
9507 else if (*p == '*') /* internal or user defined function */
9509 n = function_exists(p + 1);
9511 else if (*p == ':')
9513 n = cmd_exists(p + 1);
9515 else if (*p == '#')
9517 #ifdef FEAT_AUTOCMD
9518 if (p[1] == '#')
9519 n = autocmd_supported(p + 2);
9520 else
9521 n = au_exists(p + 1);
9522 #endif
9524 else /* internal variable */
9526 char_u *tofree;
9527 typval_T tv;
9529 /* get_name_len() takes care of expanding curly braces */
9530 name = p;
9531 len = get_name_len(&p, &tofree, TRUE, FALSE);
9532 if (len > 0)
9534 if (tofree != NULL)
9535 name = tofree;
9536 n = (get_var_tv(name, len, &tv, FALSE) == OK);
9537 if (n)
9539 /* handle d.key, l[idx], f(expr) */
9540 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
9541 if (n)
9542 clear_tv(&tv);
9545 if (*p != NUL)
9546 n = FALSE;
9548 vim_free(tofree);
9551 rettv->vval.v_number = n;
9555 * "expand()" function
9557 static void
9558 f_expand(argvars, rettv)
9559 typval_T *argvars;
9560 typval_T *rettv;
9562 char_u *s;
9563 int len;
9564 char_u *errormsg;
9565 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
9566 expand_T xpc;
9567 int error = FALSE;
9569 rettv->v_type = VAR_STRING;
9570 s = get_tv_string(&argvars[0]);
9571 if (*s == '%' || *s == '#' || *s == '<')
9573 ++emsg_off;
9574 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
9575 --emsg_off;
9577 else
9579 /* When the optional second argument is non-zero, don't remove matches
9580 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
9581 if (argvars[1].v_type != VAR_UNKNOWN
9582 && get_tv_number_chk(&argvars[1], &error))
9583 flags |= WILD_KEEP_ALL;
9584 if (!error)
9586 ExpandInit(&xpc);
9587 xpc.xp_context = EXPAND_FILES;
9588 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
9590 else
9591 rettv->vval.v_string = NULL;
9596 * "extend(list, list [, idx])" function
9597 * "extend(dict, dict [, action])" function
9599 static void
9600 f_extend(argvars, rettv)
9601 typval_T *argvars;
9602 typval_T *rettv;
9604 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9606 list_T *l1, *l2;
9607 listitem_T *item;
9608 long before;
9609 int error = FALSE;
9611 l1 = argvars[0].vval.v_list;
9612 l2 = argvars[1].vval.v_list;
9613 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9614 && l2 != NULL)
9616 if (argvars[2].v_type != VAR_UNKNOWN)
9618 before = get_tv_number_chk(&argvars[2], &error);
9619 if (error)
9620 return; /* type error; errmsg already given */
9622 if (before == l1->lv_len)
9623 item = NULL;
9624 else
9626 item = list_find(l1, before);
9627 if (item == NULL)
9629 EMSGN(_(e_listidx), before);
9630 return;
9634 else
9635 item = NULL;
9636 list_extend(l1, l2, item);
9638 copy_tv(&argvars[0], rettv);
9641 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9643 dict_T *d1, *d2;
9644 dictitem_T *di1;
9645 char_u *action;
9646 int i;
9647 hashitem_T *hi2;
9648 int todo;
9650 d1 = argvars[0].vval.v_dict;
9651 d2 = argvars[1].vval.v_dict;
9652 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9653 && d2 != NULL)
9655 /* Check the third argument. */
9656 if (argvars[2].v_type != VAR_UNKNOWN)
9658 static char *(av[]) = {"keep", "force", "error"};
9660 action = get_tv_string_chk(&argvars[2]);
9661 if (action == NULL)
9662 return; /* type error; errmsg already given */
9663 for (i = 0; i < 3; ++i)
9664 if (STRCMP(action, av[i]) == 0)
9665 break;
9666 if (i == 3)
9668 EMSG2(_(e_invarg2), action);
9669 return;
9672 else
9673 action = (char_u *)"force";
9675 /* Go over all entries in the second dict and add them to the
9676 * first dict. */
9677 todo = (int)d2->dv_hashtab.ht_used;
9678 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9680 if (!HASHITEM_EMPTY(hi2))
9682 --todo;
9683 di1 = dict_find(d1, hi2->hi_key, -1);
9684 if (di1 == NULL)
9686 di1 = dictitem_copy(HI2DI(hi2));
9687 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9688 dictitem_free(di1);
9690 else if (*action == 'e')
9692 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9693 break;
9695 else if (*action == 'f')
9697 clear_tv(&di1->di_tv);
9698 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9703 copy_tv(&argvars[0], rettv);
9706 else
9707 EMSG2(_(e_listdictarg), "extend()");
9711 * "feedkeys()" function
9713 /*ARGSUSED*/
9714 static void
9715 f_feedkeys(argvars, rettv)
9716 typval_T *argvars;
9717 typval_T *rettv;
9719 int remap = TRUE;
9720 char_u *keys, *flags;
9721 char_u nbuf[NUMBUFLEN];
9722 int typed = FALSE;
9723 char_u *keys_esc;
9725 /* This is not allowed in the sandbox. If the commands would still be
9726 * executed in the sandbox it would be OK, but it probably happens later,
9727 * when "sandbox" is no longer set. */
9728 if (check_secure())
9729 return;
9731 keys = get_tv_string(&argvars[0]);
9732 if (*keys != NUL)
9734 if (argvars[1].v_type != VAR_UNKNOWN)
9736 flags = get_tv_string_buf(&argvars[1], nbuf);
9737 for ( ; *flags != NUL; ++flags)
9739 switch (*flags)
9741 case 'n': remap = FALSE; break;
9742 case 'm': remap = TRUE; break;
9743 case 't': typed = TRUE; break;
9748 /* Need to escape K_SPECIAL and CSI before putting the string in the
9749 * typeahead buffer. */
9750 keys_esc = vim_strsave_escape_csi(keys);
9751 if (keys_esc != NULL)
9753 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
9754 typebuf.tb_len, !typed, FALSE);
9755 vim_free(keys_esc);
9756 if (vgetc_busy)
9757 typebuf_was_filled = TRUE;
9763 * "filereadable()" function
9765 static void
9766 f_filereadable(argvars, rettv)
9767 typval_T *argvars;
9768 typval_T *rettv;
9770 int fd;
9771 char_u *p;
9772 int n;
9774 #ifndef O_NONBLOCK
9775 # define O_NONBLOCK 0
9776 #endif
9777 p = get_tv_string(&argvars[0]);
9778 if (*p && !mch_isdir(p) && (fd = mch_open((char *)p,
9779 O_RDONLY | O_NONBLOCK, 0)) >= 0)
9781 n = TRUE;
9782 close(fd);
9784 else
9785 n = FALSE;
9787 rettv->vval.v_number = n;
9791 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
9792 * rights to write into.
9794 static void
9795 f_filewritable(argvars, rettv)
9796 typval_T *argvars;
9797 typval_T *rettv;
9799 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
9802 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
9804 static void
9805 findfilendir(argvars, rettv, find_what)
9806 typval_T *argvars;
9807 typval_T *rettv;
9808 int find_what;
9810 #ifdef FEAT_SEARCHPATH
9811 char_u *fname;
9812 char_u *fresult = NULL;
9813 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
9814 char_u *p;
9815 char_u pathbuf[NUMBUFLEN];
9816 int count = 1;
9817 int first = TRUE;
9818 int error = FALSE;
9819 #endif
9821 rettv->vval.v_string = NULL;
9822 rettv->v_type = VAR_STRING;
9824 #ifdef FEAT_SEARCHPATH
9825 fname = get_tv_string(&argvars[0]);
9827 if (argvars[1].v_type != VAR_UNKNOWN)
9829 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
9830 if (p == NULL)
9831 error = TRUE;
9832 else
9834 if (*p != NUL)
9835 path = p;
9837 if (argvars[2].v_type != VAR_UNKNOWN)
9838 count = get_tv_number_chk(&argvars[2], &error);
9842 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
9843 error = TRUE;
9845 if (*fname != NUL && !error)
9849 if (rettv->v_type == VAR_STRING)
9850 vim_free(fresult);
9851 fresult = find_file_in_path_option(first ? fname : NULL,
9852 first ? (int)STRLEN(fname) : 0,
9853 0, first, path,
9854 find_what,
9855 curbuf->b_ffname,
9856 find_what == FINDFILE_DIR
9857 ? (char_u *)"" : curbuf->b_p_sua);
9858 first = FALSE;
9860 if (fresult != NULL && rettv->v_type == VAR_LIST)
9861 list_append_string(rettv->vval.v_list, fresult, -1);
9863 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
9866 if (rettv->v_type == VAR_STRING)
9867 rettv->vval.v_string = fresult;
9868 #endif
9871 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
9872 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
9875 * Implementation of map() and filter().
9877 static void
9878 filter_map(argvars, rettv, map)
9879 typval_T *argvars;
9880 typval_T *rettv;
9881 int map;
9883 char_u buf[NUMBUFLEN];
9884 char_u *expr;
9885 listitem_T *li, *nli;
9886 list_T *l = NULL;
9887 dictitem_T *di;
9888 hashtab_T *ht;
9889 hashitem_T *hi;
9890 dict_T *d = NULL;
9891 typval_T save_val;
9892 typval_T save_key;
9893 int rem;
9894 int todo;
9895 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
9896 int save_did_emsg;
9898 if (argvars[0].v_type == VAR_LIST)
9900 if ((l = argvars[0].vval.v_list) == NULL
9901 || (map && tv_check_lock(l->lv_lock, ermsg)))
9902 return;
9904 else if (argvars[0].v_type == VAR_DICT)
9906 if ((d = argvars[0].vval.v_dict) == NULL
9907 || (map && tv_check_lock(d->dv_lock, ermsg)))
9908 return;
9910 else
9912 EMSG2(_(e_listdictarg), ermsg);
9913 return;
9916 expr = get_tv_string_buf_chk(&argvars[1], buf);
9917 /* On type errors, the preceding call has already displayed an error
9918 * message. Avoid a misleading error message for an empty string that
9919 * was not passed as argument. */
9920 if (expr != NULL)
9922 prepare_vimvar(VV_VAL, &save_val);
9923 expr = skipwhite(expr);
9925 /* We reset "did_emsg" to be able to detect whether an error
9926 * occurred during evaluation of the expression. */
9927 save_did_emsg = did_emsg;
9928 did_emsg = FALSE;
9930 if (argvars[0].v_type == VAR_DICT)
9932 prepare_vimvar(VV_KEY, &save_key);
9933 vimvars[VV_KEY].vv_type = VAR_STRING;
9935 ht = &d->dv_hashtab;
9936 hash_lock(ht);
9937 todo = (int)ht->ht_used;
9938 for (hi = ht->ht_array; todo > 0; ++hi)
9940 if (!HASHITEM_EMPTY(hi))
9942 --todo;
9943 di = HI2DI(hi);
9944 if (tv_check_lock(di->di_tv.v_lock, ermsg))
9945 break;
9946 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
9947 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
9948 || did_emsg)
9949 break;
9950 if (!map && rem)
9951 dictitem_remove(d, di);
9952 clear_tv(&vimvars[VV_KEY].vv_tv);
9955 hash_unlock(ht);
9957 restore_vimvar(VV_KEY, &save_key);
9959 else
9961 for (li = l->lv_first; li != NULL; li = nli)
9963 if (tv_check_lock(li->li_tv.v_lock, ermsg))
9964 break;
9965 nli = li->li_next;
9966 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
9967 || did_emsg)
9968 break;
9969 if (!map && rem)
9970 listitem_remove(l, li);
9974 restore_vimvar(VV_VAL, &save_val);
9976 did_emsg |= save_did_emsg;
9979 copy_tv(&argvars[0], rettv);
9982 static int
9983 filter_map_one(tv, expr, map, remp)
9984 typval_T *tv;
9985 char_u *expr;
9986 int map;
9987 int *remp;
9989 typval_T rettv;
9990 char_u *s;
9991 int retval = FAIL;
9993 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
9994 s = expr;
9995 if (eval1(&s, &rettv, TRUE) == FAIL)
9996 goto theend;
9997 if (*s != NUL) /* check for trailing chars after expr */
9999 EMSG2(_(e_invexpr2), s);
10000 goto theend;
10002 if (map)
10004 /* map(): replace the list item value */
10005 clear_tv(tv);
10006 rettv.v_lock = 0;
10007 *tv = rettv;
10009 else
10011 int error = FALSE;
10013 /* filter(): when expr is zero remove the item */
10014 *remp = (get_tv_number_chk(&rettv, &error) == 0);
10015 clear_tv(&rettv);
10016 /* On type error, nothing has been removed; return FAIL to stop the
10017 * loop. The error message was given by get_tv_number_chk(). */
10018 if (error)
10019 goto theend;
10021 retval = OK;
10022 theend:
10023 clear_tv(&vimvars[VV_VAL].vv_tv);
10024 return retval;
10028 * "filter()" function
10030 static void
10031 f_filter(argvars, rettv)
10032 typval_T *argvars;
10033 typval_T *rettv;
10035 filter_map(argvars, rettv, FALSE);
10039 * "finddir({fname}[, {path}[, {count}]])" function
10041 static void
10042 f_finddir(argvars, rettv)
10043 typval_T *argvars;
10044 typval_T *rettv;
10046 findfilendir(argvars, rettv, FINDFILE_DIR);
10050 * "findfile({fname}[, {path}[, {count}]])" function
10052 static void
10053 f_findfile(argvars, rettv)
10054 typval_T *argvars;
10055 typval_T *rettv;
10057 findfilendir(argvars, rettv, FINDFILE_FILE);
10060 #ifdef FEAT_FLOAT
10062 * "float2nr({float})" function
10064 static void
10065 f_float2nr(argvars, rettv)
10066 typval_T *argvars;
10067 typval_T *rettv;
10069 float_T f;
10071 if (get_float_arg(argvars, &f) == OK)
10073 if (f < -0x7fffffff)
10074 rettv->vval.v_number = -0x7fffffff;
10075 else if (f > 0x7fffffff)
10076 rettv->vval.v_number = 0x7fffffff;
10077 else
10078 rettv->vval.v_number = (varnumber_T)f;
10083 * "floor({float})" function
10085 static void
10086 f_floor(argvars, rettv)
10087 typval_T *argvars;
10088 typval_T *rettv;
10090 float_T f;
10092 rettv->v_type = VAR_FLOAT;
10093 if (get_float_arg(argvars, &f) == OK)
10094 rettv->vval.v_float = floor(f);
10095 else
10096 rettv->vval.v_float = 0.0;
10098 #endif
10101 * "fnameescape({string})" function
10103 static void
10104 f_fnameescape(argvars, rettv)
10105 typval_T *argvars;
10106 typval_T *rettv;
10108 rettv->vval.v_string = vim_strsave_fnameescape(
10109 get_tv_string(&argvars[0]), FALSE);
10110 rettv->v_type = VAR_STRING;
10114 * "fnamemodify({fname}, {mods})" function
10116 static void
10117 f_fnamemodify(argvars, rettv)
10118 typval_T *argvars;
10119 typval_T *rettv;
10121 char_u *fname;
10122 char_u *mods;
10123 int usedlen = 0;
10124 int len;
10125 char_u *fbuf = NULL;
10126 char_u buf[NUMBUFLEN];
10128 fname = get_tv_string_chk(&argvars[0]);
10129 mods = get_tv_string_buf_chk(&argvars[1], buf);
10130 if (fname == NULL || mods == NULL)
10131 fname = NULL;
10132 else
10134 len = (int)STRLEN(fname);
10135 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
10138 rettv->v_type = VAR_STRING;
10139 if (fname == NULL)
10140 rettv->vval.v_string = NULL;
10141 else
10142 rettv->vval.v_string = vim_strnsave(fname, len);
10143 vim_free(fbuf);
10146 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
10149 * "foldclosed()" function
10151 static void
10152 foldclosed_both(argvars, rettv, end)
10153 typval_T *argvars;
10154 typval_T *rettv;
10155 int end;
10157 #ifdef FEAT_FOLDING
10158 linenr_T lnum;
10159 linenr_T first, last;
10161 lnum = get_tv_lnum(argvars);
10162 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10164 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
10166 if (end)
10167 rettv->vval.v_number = (varnumber_T)last;
10168 else
10169 rettv->vval.v_number = (varnumber_T)first;
10170 return;
10173 #endif
10174 rettv->vval.v_number = -1;
10178 * "foldclosed()" function
10180 static void
10181 f_foldclosed(argvars, rettv)
10182 typval_T *argvars;
10183 typval_T *rettv;
10185 foldclosed_both(argvars, rettv, FALSE);
10189 * "foldclosedend()" function
10191 static void
10192 f_foldclosedend(argvars, rettv)
10193 typval_T *argvars;
10194 typval_T *rettv;
10196 foldclosed_both(argvars, rettv, TRUE);
10200 * "foldlevel()" function
10202 static void
10203 f_foldlevel(argvars, rettv)
10204 typval_T *argvars;
10205 typval_T *rettv;
10207 #ifdef FEAT_FOLDING
10208 linenr_T lnum;
10210 lnum = get_tv_lnum(argvars);
10211 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10212 rettv->vval.v_number = foldLevel(lnum);
10213 #endif
10217 * "foldtext()" function
10219 /*ARGSUSED*/
10220 static void
10221 f_foldtext(argvars, rettv)
10222 typval_T *argvars;
10223 typval_T *rettv;
10225 #ifdef FEAT_FOLDING
10226 linenr_T lnum;
10227 char_u *s;
10228 char_u *r;
10229 int len;
10230 char *txt;
10231 #endif
10233 rettv->v_type = VAR_STRING;
10234 rettv->vval.v_string = NULL;
10235 #ifdef FEAT_FOLDING
10236 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
10237 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
10238 <= curbuf->b_ml.ml_line_count
10239 && vimvars[VV_FOLDDASHES].vv_str != NULL)
10241 /* Find first non-empty line in the fold. */
10242 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
10243 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10245 if (!linewhite(lnum))
10246 break;
10247 ++lnum;
10250 /* Find interesting text in this line. */
10251 s = skipwhite(ml_get(lnum));
10252 /* skip C comment-start */
10253 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
10255 s = skipwhite(s + 2);
10256 if (*skipwhite(s) == NUL
10257 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10259 s = skipwhite(ml_get(lnum + 1));
10260 if (*s == '*')
10261 s = skipwhite(s + 1);
10264 txt = _("+-%s%3ld lines: ");
10265 r = alloc((unsigned)(STRLEN(txt)
10266 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
10267 + 20 /* for %3ld */
10268 + STRLEN(s))); /* concatenated */
10269 if (r != NULL)
10271 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
10272 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
10273 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
10274 len = (int)STRLEN(r);
10275 STRCAT(r, s);
10276 /* remove 'foldmarker' and 'commentstring' */
10277 foldtext_cleanup(r + len);
10278 rettv->vval.v_string = r;
10281 #endif
10285 * "foldtextresult(lnum)" function
10287 /*ARGSUSED*/
10288 static void
10289 f_foldtextresult(argvars, rettv)
10290 typval_T *argvars;
10291 typval_T *rettv;
10293 #ifdef FEAT_FOLDING
10294 linenr_T lnum;
10295 char_u *text;
10296 char_u buf[51];
10297 foldinfo_T foldinfo;
10298 int fold_count;
10299 #endif
10301 rettv->v_type = VAR_STRING;
10302 rettv->vval.v_string = NULL;
10303 #ifdef FEAT_FOLDING
10304 lnum = get_tv_lnum(argvars);
10305 /* treat illegal types and illegal string values for {lnum} the same */
10306 if (lnum < 0)
10307 lnum = 0;
10308 fold_count = foldedCount(curwin, lnum, &foldinfo);
10309 if (fold_count > 0)
10311 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
10312 &foldinfo, buf);
10313 if (text == buf)
10314 text = vim_strsave(text);
10315 rettv->vval.v_string = text;
10317 #endif
10321 * "foreground()" function
10323 /*ARGSUSED*/
10324 static void
10325 f_foreground(argvars, rettv)
10326 typval_T *argvars;
10327 typval_T *rettv;
10329 #ifdef FEAT_GUI
10330 if (gui.in_use)
10331 gui_mch_set_foreground();
10332 #else
10333 # ifdef WIN32
10334 win32_set_foreground();
10335 # endif
10336 #endif
10340 * "function()" function
10342 /*ARGSUSED*/
10343 static void
10344 f_function(argvars, rettv)
10345 typval_T *argvars;
10346 typval_T *rettv;
10348 char_u *s;
10350 s = get_tv_string(&argvars[0]);
10351 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
10352 EMSG2(_(e_invarg2), s);
10353 /* Don't check an autoload name for existence here. */
10354 else if (vim_strchr(s, AUTOLOAD_CHAR) == NULL && !function_exists(s))
10355 EMSG2(_("E700: Unknown function: %s"), s);
10356 else
10358 rettv->vval.v_string = vim_strsave(s);
10359 rettv->v_type = VAR_FUNC;
10364 * "garbagecollect()" function
10366 /*ARGSUSED*/
10367 static void
10368 f_garbagecollect(argvars, rettv)
10369 typval_T *argvars;
10370 typval_T *rettv;
10372 /* This is postponed until we are back at the toplevel, because we may be
10373 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
10374 want_garbage_collect = TRUE;
10376 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
10377 garbage_collect_at_exit = TRUE;
10381 * "get()" function
10383 static void
10384 f_get(argvars, rettv)
10385 typval_T *argvars;
10386 typval_T *rettv;
10388 listitem_T *li;
10389 list_T *l;
10390 dictitem_T *di;
10391 dict_T *d;
10392 typval_T *tv = NULL;
10394 if (argvars[0].v_type == VAR_LIST)
10396 if ((l = argvars[0].vval.v_list) != NULL)
10398 int error = FALSE;
10400 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
10401 if (!error && li != NULL)
10402 tv = &li->li_tv;
10405 else if (argvars[0].v_type == VAR_DICT)
10407 if ((d = argvars[0].vval.v_dict) != NULL)
10409 di = dict_find(d, get_tv_string(&argvars[1]), -1);
10410 if (di != NULL)
10411 tv = &di->di_tv;
10414 else
10415 EMSG2(_(e_listdictarg), "get()");
10417 if (tv == NULL)
10419 if (argvars[2].v_type != VAR_UNKNOWN)
10420 copy_tv(&argvars[2], rettv);
10422 else
10423 copy_tv(tv, rettv);
10426 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
10429 * Get line or list of lines from buffer "buf" into "rettv".
10430 * Return a range (from start to end) of lines in rettv from the specified
10431 * buffer.
10432 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
10434 static void
10435 get_buffer_lines(buf, start, end, retlist, rettv)
10436 buf_T *buf;
10437 linenr_T start;
10438 linenr_T end;
10439 int retlist;
10440 typval_T *rettv;
10442 char_u *p;
10444 if (retlist && rettv_list_alloc(rettv) == FAIL)
10445 return;
10447 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
10448 return;
10450 if (!retlist)
10452 if (start >= 1 && start <= buf->b_ml.ml_line_count)
10453 p = ml_get_buf(buf, start, FALSE);
10454 else
10455 p = (char_u *)"";
10457 rettv->v_type = VAR_STRING;
10458 rettv->vval.v_string = vim_strsave(p);
10460 else
10462 if (end < start)
10463 return;
10465 if (start < 1)
10466 start = 1;
10467 if (end > buf->b_ml.ml_line_count)
10468 end = buf->b_ml.ml_line_count;
10469 while (start <= end)
10470 if (list_append_string(rettv->vval.v_list,
10471 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
10472 break;
10477 * "getbufline()" function
10479 static void
10480 f_getbufline(argvars, rettv)
10481 typval_T *argvars;
10482 typval_T *rettv;
10484 linenr_T lnum;
10485 linenr_T end;
10486 buf_T *buf;
10488 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10489 ++emsg_off;
10490 buf = get_buf_tv(&argvars[0]);
10491 --emsg_off;
10493 lnum = get_tv_lnum_buf(&argvars[1], buf);
10494 if (argvars[2].v_type == VAR_UNKNOWN)
10495 end = lnum;
10496 else
10497 end = get_tv_lnum_buf(&argvars[2], buf);
10499 get_buffer_lines(buf, lnum, end, TRUE, rettv);
10503 * "getbufvar()" function
10505 static void
10506 f_getbufvar(argvars, rettv)
10507 typval_T *argvars;
10508 typval_T *rettv;
10510 buf_T *buf;
10511 buf_T *save_curbuf;
10512 char_u *varname;
10513 dictitem_T *v;
10515 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10516 varname = get_tv_string_chk(&argvars[1]);
10517 ++emsg_off;
10518 buf = get_buf_tv(&argvars[0]);
10520 rettv->v_type = VAR_STRING;
10521 rettv->vval.v_string = NULL;
10523 if (buf != NULL && varname != NULL)
10525 /* set curbuf to be our buf, temporarily */
10526 save_curbuf = curbuf;
10527 curbuf = buf;
10529 if (*varname == '&') /* buffer-local-option */
10530 get_option_tv(&varname, rettv, TRUE);
10531 else
10533 if (*varname == NUL)
10534 /* let getbufvar({nr}, "") return the "b:" dictionary. The
10535 * scope prefix before the NUL byte is required by
10536 * find_var_in_ht(). */
10537 varname = (char_u *)"b:" + 2;
10538 /* look up the variable */
10539 v = find_var_in_ht(&curbuf->b_vars.dv_hashtab, varname, FALSE);
10540 if (v != NULL)
10541 copy_tv(&v->di_tv, rettv);
10544 /* restore previous notion of curbuf */
10545 curbuf = save_curbuf;
10548 --emsg_off;
10552 * "getchar()" function
10554 static void
10555 f_getchar(argvars, rettv)
10556 typval_T *argvars;
10557 typval_T *rettv;
10559 varnumber_T n;
10560 int error = FALSE;
10562 /* Position the cursor. Needed after a message that ends in a space. */
10563 windgoto(msg_row, msg_col);
10565 ++no_mapping;
10566 ++allow_keys;
10567 for (;;)
10569 if (argvars[0].v_type == VAR_UNKNOWN)
10570 /* getchar(): blocking wait. */
10571 n = safe_vgetc();
10572 else if (get_tv_number_chk(&argvars[0], &error) == 1)
10573 /* getchar(1): only check if char avail */
10574 n = vpeekc();
10575 else if (error || vpeekc() == NUL)
10576 /* illegal argument or getchar(0) and no char avail: return zero */
10577 n = 0;
10578 else
10579 /* getchar(0) and char avail: return char */
10580 n = safe_vgetc();
10581 if (n == K_IGNORE)
10582 continue;
10583 break;
10585 --no_mapping;
10586 --allow_keys;
10588 vimvars[VV_MOUSE_WIN].vv_nr = 0;
10589 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
10590 vimvars[VV_MOUSE_COL].vv_nr = 0;
10592 rettv->vval.v_number = n;
10593 if (IS_SPECIAL(n) || mod_mask != 0)
10595 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
10596 int i = 0;
10598 /* Turn a special key into three bytes, plus modifier. */
10599 if (mod_mask != 0)
10601 temp[i++] = K_SPECIAL;
10602 temp[i++] = KS_MODIFIER;
10603 temp[i++] = mod_mask;
10605 if (IS_SPECIAL(n))
10607 temp[i++] = K_SPECIAL;
10608 temp[i++] = K_SECOND(n);
10609 temp[i++] = K_THIRD(n);
10611 #ifdef FEAT_MBYTE
10612 else if (has_mbyte)
10613 i += (*mb_char2bytes)(n, temp + i);
10614 #endif
10615 else
10616 temp[i++] = n;
10617 temp[i++] = NUL;
10618 rettv->v_type = VAR_STRING;
10619 rettv->vval.v_string = vim_strsave(temp);
10621 #ifdef FEAT_MOUSE
10622 if (n == K_LEFTMOUSE
10623 || n == K_LEFTMOUSE_NM
10624 || n == K_LEFTDRAG
10625 || n == K_LEFTRELEASE
10626 || n == K_LEFTRELEASE_NM
10627 || n == K_MIDDLEMOUSE
10628 || n == K_MIDDLEDRAG
10629 || n == K_MIDDLERELEASE
10630 || n == K_RIGHTMOUSE
10631 || n == K_RIGHTDRAG
10632 || n == K_RIGHTRELEASE
10633 || n == K_X1MOUSE
10634 || n == K_X1DRAG
10635 || n == K_X1RELEASE
10636 || n == K_X2MOUSE
10637 || n == K_X2DRAG
10638 || n == K_X2RELEASE
10639 || n == K_MOUSEDOWN
10640 || n == K_MOUSEUP)
10642 int row = mouse_row;
10643 int col = mouse_col;
10644 win_T *win;
10645 linenr_T lnum;
10646 # ifdef FEAT_WINDOWS
10647 win_T *wp;
10648 # endif
10649 int winnr = 1;
10651 if (row >= 0 && col >= 0)
10653 /* Find the window at the mouse coordinates and compute the
10654 * text position. */
10655 win = mouse_find_win(&row, &col);
10656 (void)mouse_comp_pos(win, &row, &col, &lnum);
10657 # ifdef FEAT_WINDOWS
10658 for (wp = firstwin; wp != win; wp = wp->w_next)
10659 ++winnr;
10660 # endif
10661 vimvars[VV_MOUSE_WIN].vv_nr = winnr;
10662 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
10663 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
10666 #endif
10671 * "getcharmod()" function
10673 /*ARGSUSED*/
10674 static void
10675 f_getcharmod(argvars, rettv)
10676 typval_T *argvars;
10677 typval_T *rettv;
10679 rettv->vval.v_number = mod_mask;
10683 * "getcmdline()" function
10685 /*ARGSUSED*/
10686 static void
10687 f_getcmdline(argvars, rettv)
10688 typval_T *argvars;
10689 typval_T *rettv;
10691 rettv->v_type = VAR_STRING;
10692 rettv->vval.v_string = get_cmdline_str();
10696 * "getcmdpos()" function
10698 /*ARGSUSED*/
10699 static void
10700 f_getcmdpos(argvars, rettv)
10701 typval_T *argvars;
10702 typval_T *rettv;
10704 rettv->vval.v_number = get_cmdline_pos() + 1;
10708 * "getcmdtype()" function
10710 /*ARGSUSED*/
10711 static void
10712 f_getcmdtype(argvars, rettv)
10713 typval_T *argvars;
10714 typval_T *rettv;
10716 rettv->v_type = VAR_STRING;
10717 rettv->vval.v_string = alloc(2);
10718 if (rettv->vval.v_string != NULL)
10720 rettv->vval.v_string[0] = get_cmdline_type();
10721 rettv->vval.v_string[1] = NUL;
10726 * "getcwd()" function
10728 /*ARGSUSED*/
10729 static void
10730 f_getcwd(argvars, rettv)
10731 typval_T *argvars;
10732 typval_T *rettv;
10734 char_u cwd[MAXPATHL];
10736 rettv->v_type = VAR_STRING;
10737 if (mch_dirname(cwd, MAXPATHL) == FAIL)
10738 rettv->vval.v_string = NULL;
10739 else
10741 rettv->vval.v_string = vim_strsave(cwd);
10742 #ifdef BACKSLASH_IN_FILENAME
10743 if (rettv->vval.v_string != NULL)
10744 slash_adjust(rettv->vval.v_string);
10745 #endif
10750 * "getfontname()" function
10752 /*ARGSUSED*/
10753 static void
10754 f_getfontname(argvars, rettv)
10755 typval_T *argvars;
10756 typval_T *rettv;
10758 rettv->v_type = VAR_STRING;
10759 rettv->vval.v_string = NULL;
10760 #ifdef FEAT_GUI
10761 if (gui.in_use)
10763 GuiFont font;
10764 char_u *name = NULL;
10766 if (argvars[0].v_type == VAR_UNKNOWN)
10768 /* Get the "Normal" font. Either the name saved by
10769 * hl_set_font_name() or from the font ID. */
10770 font = gui.norm_font;
10771 name = hl_get_font_name();
10773 else
10775 name = get_tv_string(&argvars[0]);
10776 if (STRCMP(name, "*") == 0) /* don't use font dialog */
10777 return;
10778 font = gui_mch_get_font(name, FALSE);
10779 if (font == NOFONT)
10780 return; /* Invalid font name, return empty string. */
10782 rettv->vval.v_string = gui_mch_get_fontname(font, name);
10783 if (argvars[0].v_type != VAR_UNKNOWN)
10784 gui_mch_free_font(font);
10786 #endif
10790 * "getfperm({fname})" function
10792 static void
10793 f_getfperm(argvars, rettv)
10794 typval_T *argvars;
10795 typval_T *rettv;
10797 char_u *fname;
10798 struct stat st;
10799 char_u *perm = NULL;
10800 char_u flags[] = "rwx";
10801 int i;
10803 fname = get_tv_string(&argvars[0]);
10805 rettv->v_type = VAR_STRING;
10806 if (mch_stat((char *)fname, &st) >= 0)
10808 perm = vim_strsave((char_u *)"---------");
10809 if (perm != NULL)
10811 for (i = 0; i < 9; i++)
10813 if (st.st_mode & (1 << (8 - i)))
10814 perm[i] = flags[i % 3];
10818 rettv->vval.v_string = perm;
10822 * "getfsize({fname})" function
10824 static void
10825 f_getfsize(argvars, rettv)
10826 typval_T *argvars;
10827 typval_T *rettv;
10829 char_u *fname;
10830 struct stat st;
10832 fname = get_tv_string(&argvars[0]);
10834 rettv->v_type = VAR_NUMBER;
10836 if (mch_stat((char *)fname, &st) >= 0)
10838 if (mch_isdir(fname))
10839 rettv->vval.v_number = 0;
10840 else
10842 rettv->vval.v_number = (varnumber_T)st.st_size;
10844 /* non-perfect check for overflow */
10845 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
10846 rettv->vval.v_number = -2;
10849 else
10850 rettv->vval.v_number = -1;
10854 * "getftime({fname})" function
10856 static void
10857 f_getftime(argvars, rettv)
10858 typval_T *argvars;
10859 typval_T *rettv;
10861 char_u *fname;
10862 struct stat st;
10864 fname = get_tv_string(&argvars[0]);
10866 if (mch_stat((char *)fname, &st) >= 0)
10867 rettv->vval.v_number = (varnumber_T)st.st_mtime;
10868 else
10869 rettv->vval.v_number = -1;
10873 * "getftype({fname})" function
10875 static void
10876 f_getftype(argvars, rettv)
10877 typval_T *argvars;
10878 typval_T *rettv;
10880 char_u *fname;
10881 struct stat st;
10882 char_u *type = NULL;
10883 char *t;
10885 fname = get_tv_string(&argvars[0]);
10887 rettv->v_type = VAR_STRING;
10888 if (mch_lstat((char *)fname, &st) >= 0)
10890 #ifdef S_ISREG
10891 if (S_ISREG(st.st_mode))
10892 t = "file";
10893 else if (S_ISDIR(st.st_mode))
10894 t = "dir";
10895 # ifdef S_ISLNK
10896 else if (S_ISLNK(st.st_mode))
10897 t = "link";
10898 # endif
10899 # ifdef S_ISBLK
10900 else if (S_ISBLK(st.st_mode))
10901 t = "bdev";
10902 # endif
10903 # ifdef S_ISCHR
10904 else if (S_ISCHR(st.st_mode))
10905 t = "cdev";
10906 # endif
10907 # ifdef S_ISFIFO
10908 else if (S_ISFIFO(st.st_mode))
10909 t = "fifo";
10910 # endif
10911 # ifdef S_ISSOCK
10912 else if (S_ISSOCK(st.st_mode))
10913 t = "fifo";
10914 # endif
10915 else
10916 t = "other";
10917 #else
10918 # ifdef S_IFMT
10919 switch (st.st_mode & S_IFMT)
10921 case S_IFREG: t = "file"; break;
10922 case S_IFDIR: t = "dir"; break;
10923 # ifdef S_IFLNK
10924 case S_IFLNK: t = "link"; break;
10925 # endif
10926 # ifdef S_IFBLK
10927 case S_IFBLK: t = "bdev"; break;
10928 # endif
10929 # ifdef S_IFCHR
10930 case S_IFCHR: t = "cdev"; break;
10931 # endif
10932 # ifdef S_IFIFO
10933 case S_IFIFO: t = "fifo"; break;
10934 # endif
10935 # ifdef S_IFSOCK
10936 case S_IFSOCK: t = "socket"; break;
10937 # endif
10938 default: t = "other";
10940 # else
10941 if (mch_isdir(fname))
10942 t = "dir";
10943 else
10944 t = "file";
10945 # endif
10946 #endif
10947 type = vim_strsave((char_u *)t);
10949 rettv->vval.v_string = type;
10953 * "getline(lnum, [end])" function
10955 static void
10956 f_getline(argvars, rettv)
10957 typval_T *argvars;
10958 typval_T *rettv;
10960 linenr_T lnum;
10961 linenr_T end;
10962 int retlist;
10964 lnum = get_tv_lnum(argvars);
10965 if (argvars[1].v_type == VAR_UNKNOWN)
10967 end = 0;
10968 retlist = FALSE;
10970 else
10972 end = get_tv_lnum(&argvars[1]);
10973 retlist = TRUE;
10976 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
10980 * "getmatches()" function
10982 /*ARGSUSED*/
10983 static void
10984 f_getmatches(argvars, rettv)
10985 typval_T *argvars;
10986 typval_T *rettv;
10988 #ifdef FEAT_SEARCH_EXTRA
10989 dict_T *dict;
10990 matchitem_T *cur = curwin->w_match_head;
10992 if (rettv_list_alloc(rettv) == OK)
10994 while (cur != NULL)
10996 dict = dict_alloc();
10997 if (dict == NULL)
10998 return;
10999 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
11000 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
11001 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
11002 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
11003 list_append_dict(rettv->vval.v_list, dict);
11004 cur = cur->next;
11007 #endif
11011 * "getpid()" function
11013 /*ARGSUSED*/
11014 static void
11015 f_getpid(argvars, rettv)
11016 typval_T *argvars;
11017 typval_T *rettv;
11019 rettv->vval.v_number = mch_get_pid();
11023 * "getpos(string)" function
11025 static void
11026 f_getpos(argvars, rettv)
11027 typval_T *argvars;
11028 typval_T *rettv;
11030 pos_T *fp;
11031 list_T *l;
11032 int fnum = -1;
11034 if (rettv_list_alloc(rettv) == OK)
11036 l = rettv->vval.v_list;
11037 fp = var2fpos(&argvars[0], TRUE, &fnum);
11038 if (fnum != -1)
11039 list_append_number(l, (varnumber_T)fnum);
11040 else
11041 list_append_number(l, (varnumber_T)0);
11042 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
11043 : (varnumber_T)0);
11044 list_append_number(l, (fp != NULL)
11045 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
11046 : (varnumber_T)0);
11047 list_append_number(l,
11048 #ifdef FEAT_VIRTUALEDIT
11049 (fp != NULL) ? (varnumber_T)fp->coladd :
11050 #endif
11051 (varnumber_T)0);
11053 else
11054 rettv->vval.v_number = FALSE;
11058 * "getqflist()" and "getloclist()" functions
11060 /*ARGSUSED*/
11061 static void
11062 f_getqflist(argvars, rettv)
11063 typval_T *argvars;
11064 typval_T *rettv;
11066 #ifdef FEAT_QUICKFIX
11067 win_T *wp;
11068 #endif
11070 #ifdef FEAT_QUICKFIX
11071 if (rettv_list_alloc(rettv) == OK)
11073 wp = NULL;
11074 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
11076 wp = find_win_by_nr(&argvars[0], NULL);
11077 if (wp == NULL)
11078 return;
11081 (void)get_errorlist(wp, rettv->vval.v_list);
11083 #endif
11087 * "getreg()" function
11089 static void
11090 f_getreg(argvars, rettv)
11091 typval_T *argvars;
11092 typval_T *rettv;
11094 char_u *strregname;
11095 int regname;
11096 int arg2 = FALSE;
11097 int error = FALSE;
11099 if (argvars[0].v_type != VAR_UNKNOWN)
11101 strregname = get_tv_string_chk(&argvars[0]);
11102 error = strregname == NULL;
11103 if (argvars[1].v_type != VAR_UNKNOWN)
11104 arg2 = get_tv_number_chk(&argvars[1], &error);
11106 else
11107 strregname = vimvars[VV_REG].vv_str;
11108 regname = (strregname == NULL ? '"' : *strregname);
11109 if (regname == 0)
11110 regname = '"';
11112 rettv->v_type = VAR_STRING;
11113 rettv->vval.v_string = error ? NULL :
11114 get_reg_contents(regname, TRUE, arg2);
11118 * "getregtype()" function
11120 static void
11121 f_getregtype(argvars, rettv)
11122 typval_T *argvars;
11123 typval_T *rettv;
11125 char_u *strregname;
11126 int regname;
11127 char_u buf[NUMBUFLEN + 2];
11128 long reglen = 0;
11130 if (argvars[0].v_type != VAR_UNKNOWN)
11132 strregname = get_tv_string_chk(&argvars[0]);
11133 if (strregname == NULL) /* type error; errmsg already given */
11135 rettv->v_type = VAR_STRING;
11136 rettv->vval.v_string = NULL;
11137 return;
11140 else
11141 /* Default to v:register */
11142 strregname = vimvars[VV_REG].vv_str;
11144 regname = (strregname == NULL ? '"' : *strregname);
11145 if (regname == 0)
11146 regname = '"';
11148 buf[0] = NUL;
11149 buf[1] = NUL;
11150 switch (get_reg_type(regname, &reglen))
11152 case MLINE: buf[0] = 'V'; break;
11153 case MCHAR: buf[0] = 'v'; break;
11154 #ifdef FEAT_VISUAL
11155 case MBLOCK:
11156 buf[0] = Ctrl_V;
11157 sprintf((char *)buf + 1, "%ld", reglen + 1);
11158 break;
11159 #endif
11161 rettv->v_type = VAR_STRING;
11162 rettv->vval.v_string = vim_strsave(buf);
11166 * "gettabwinvar()" function
11168 static void
11169 f_gettabwinvar(argvars, rettv)
11170 typval_T *argvars;
11171 typval_T *rettv;
11173 getwinvar(argvars, rettv, 1);
11177 * "getwinposx()" function
11179 /*ARGSUSED*/
11180 static void
11181 f_getwinposx(argvars, rettv)
11182 typval_T *argvars;
11183 typval_T *rettv;
11185 rettv->vval.v_number = -1;
11186 #ifdef FEAT_GUI
11187 if (gui.in_use)
11189 int x, y;
11191 if (gui_mch_get_winpos(&x, &y) == OK)
11192 rettv->vval.v_number = x;
11194 #endif
11198 * "getwinposy()" function
11200 /*ARGSUSED*/
11201 static void
11202 f_getwinposy(argvars, rettv)
11203 typval_T *argvars;
11204 typval_T *rettv;
11206 rettv->vval.v_number = -1;
11207 #ifdef FEAT_GUI
11208 if (gui.in_use)
11210 int x, y;
11212 if (gui_mch_get_winpos(&x, &y) == OK)
11213 rettv->vval.v_number = y;
11215 #endif
11219 * Find window specified by "vp" in tabpage "tp".
11221 static win_T *
11222 find_win_by_nr(vp, tp)
11223 typval_T *vp;
11224 tabpage_T *tp; /* NULL for current tab page */
11226 #ifdef FEAT_WINDOWS
11227 win_T *wp;
11228 #endif
11229 int nr;
11231 nr = get_tv_number_chk(vp, NULL);
11233 #ifdef FEAT_WINDOWS
11234 if (nr < 0)
11235 return NULL;
11236 if (nr == 0)
11237 return curwin;
11239 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
11240 wp != NULL; wp = wp->w_next)
11241 if (--nr <= 0)
11242 break;
11243 return wp;
11244 #else
11245 if (nr == 0 || nr == 1)
11246 return curwin;
11247 return NULL;
11248 #endif
11252 * "getwinvar()" function
11254 static void
11255 f_getwinvar(argvars, rettv)
11256 typval_T *argvars;
11257 typval_T *rettv;
11259 getwinvar(argvars, rettv, 0);
11263 * getwinvar() and gettabwinvar()
11265 static void
11266 getwinvar(argvars, rettv, off)
11267 typval_T *argvars;
11268 typval_T *rettv;
11269 int off; /* 1 for gettabwinvar() */
11271 win_T *win, *oldcurwin;
11272 char_u *varname;
11273 dictitem_T *v;
11274 tabpage_T *tp;
11276 #ifdef FEAT_WINDOWS
11277 if (off == 1)
11278 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
11279 else
11280 tp = curtab;
11281 #endif
11282 win = find_win_by_nr(&argvars[off], tp);
11283 varname = get_tv_string_chk(&argvars[off + 1]);
11284 ++emsg_off;
11286 rettv->v_type = VAR_STRING;
11287 rettv->vval.v_string = NULL;
11289 if (win != NULL && varname != NULL)
11291 /* Set curwin to be our win, temporarily. Also set curbuf, so
11292 * that we can get buffer-local options. */
11293 oldcurwin = curwin;
11294 curwin = win;
11295 curbuf = win->w_buffer;
11297 if (*varname == '&') /* window-local-option */
11298 get_option_tv(&varname, rettv, 1);
11299 else
11301 if (*varname == NUL)
11302 /* let getwinvar({nr}, "") return the "w:" dictionary. The
11303 * scope prefix before the NUL byte is required by
11304 * find_var_in_ht(). */
11305 varname = (char_u *)"w:" + 2;
11306 /* look up the variable */
11307 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
11308 if (v != NULL)
11309 copy_tv(&v->di_tv, rettv);
11312 /* restore previous notion of curwin */
11313 curwin = oldcurwin;
11314 curbuf = curwin->w_buffer;
11317 --emsg_off;
11321 * "glob()" function
11323 static void
11324 f_glob(argvars, rettv)
11325 typval_T *argvars;
11326 typval_T *rettv;
11328 int flags = WILD_SILENT|WILD_USE_NL;
11329 expand_T xpc;
11330 int error = FALSE;
11332 /* When the optional second argument is non-zero, don't remove matches
11333 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11334 if (argvars[1].v_type != VAR_UNKNOWN
11335 && get_tv_number_chk(&argvars[1], &error))
11336 flags |= WILD_KEEP_ALL;
11337 rettv->v_type = VAR_STRING;
11338 if (!error)
11340 ExpandInit(&xpc);
11341 xpc.xp_context = EXPAND_FILES;
11342 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
11343 NULL, flags, WILD_ALL);
11345 else
11346 rettv->vval.v_string = NULL;
11350 * "globpath()" function
11352 static void
11353 f_globpath(argvars, rettv)
11354 typval_T *argvars;
11355 typval_T *rettv;
11357 int flags = 0;
11358 char_u buf1[NUMBUFLEN];
11359 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
11360 int error = FALSE;
11362 /* When the optional second argument is non-zero, don't remove matches
11363 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11364 if (argvars[2].v_type != VAR_UNKNOWN
11365 && get_tv_number_chk(&argvars[2], &error))
11366 flags |= WILD_KEEP_ALL;
11367 rettv->v_type = VAR_STRING;
11368 if (file == NULL || error)
11369 rettv->vval.v_string = NULL;
11370 else
11371 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file,
11372 flags);
11376 * "has()" function
11378 static void
11379 f_has(argvars, rettv)
11380 typval_T *argvars;
11381 typval_T *rettv;
11383 int i;
11384 char_u *name;
11385 int n = FALSE;
11386 static char *(has_list[]) =
11388 #ifdef AMIGA
11389 "amiga",
11390 # ifdef FEAT_ARP
11391 "arp",
11392 # endif
11393 #endif
11394 #ifdef __BEOS__
11395 "beos",
11396 #endif
11397 #ifdef MSDOS
11398 # ifdef DJGPP
11399 "dos32",
11400 # else
11401 "dos16",
11402 # endif
11403 #endif
11404 #ifdef MACOS
11405 "mac",
11406 #endif
11407 #if defined(MACOS_X_UNIX)
11408 "macunix",
11409 #endif
11410 #ifdef OS2
11411 "os2",
11412 #endif
11413 #ifdef __QNX__
11414 "qnx",
11415 #endif
11416 #ifdef RISCOS
11417 "riscos",
11418 #endif
11419 #ifdef UNIX
11420 "unix",
11421 #endif
11422 #ifdef VMS
11423 "vms",
11424 #endif
11425 #ifdef WIN16
11426 "win16",
11427 #endif
11428 #ifdef WIN32
11429 "win32",
11430 #endif
11431 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
11432 "win32unix",
11433 #endif
11434 #ifdef WIN64
11435 "win64",
11436 #endif
11437 #ifdef EBCDIC
11438 "ebcdic",
11439 #endif
11440 #ifndef CASE_INSENSITIVE_FILENAME
11441 "fname_case",
11442 #endif
11443 #ifdef FEAT_ARABIC
11444 "arabic",
11445 #endif
11446 #ifdef FEAT_AUTOCMD
11447 "autocmd",
11448 #endif
11449 #ifdef FEAT_BEVAL
11450 "balloon_eval",
11451 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
11452 "balloon_multiline",
11453 # endif
11454 #endif
11455 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
11456 "builtin_terms",
11457 # ifdef ALL_BUILTIN_TCAPS
11458 "all_builtin_terms",
11459 # endif
11460 #endif
11461 #ifdef FEAT_BYTEOFF
11462 "byte_offset",
11463 #endif
11464 #ifdef FEAT_CINDENT
11465 "cindent",
11466 #endif
11467 #ifdef FEAT_CLIENTSERVER
11468 "clientserver",
11469 #endif
11470 #ifdef FEAT_CLIPBOARD
11471 "clipboard",
11472 #endif
11473 #ifdef FEAT_CMDL_COMPL
11474 "cmdline_compl",
11475 #endif
11476 #ifdef FEAT_CMDHIST
11477 "cmdline_hist",
11478 #endif
11479 #ifdef FEAT_COMMENTS
11480 "comments",
11481 #endif
11482 #ifdef FEAT_CRYPT
11483 "cryptv",
11484 #endif
11485 #ifdef FEAT_CSCOPE
11486 "cscope",
11487 #endif
11488 #ifdef CURSOR_SHAPE
11489 "cursorshape",
11490 #endif
11491 #ifdef DEBUG
11492 "debug",
11493 #endif
11494 #ifdef FEAT_CON_DIALOG
11495 "dialog_con",
11496 #endif
11497 #ifdef FEAT_GUI_DIALOG
11498 "dialog_gui",
11499 #endif
11500 #ifdef FEAT_DIFF
11501 "diff",
11502 #endif
11503 #ifdef FEAT_DIGRAPHS
11504 "digraphs",
11505 #endif
11506 #ifdef FEAT_DND
11507 "dnd",
11508 #endif
11509 #ifdef FEAT_EMACS_TAGS
11510 "emacs_tags",
11511 #endif
11512 "eval", /* always present, of course! */
11513 #ifdef FEAT_EX_EXTRA
11514 "ex_extra",
11515 #endif
11516 #ifdef FEAT_SEARCH_EXTRA
11517 "extra_search",
11518 #endif
11519 #ifdef FEAT_FKMAP
11520 "farsi",
11521 #endif
11522 #ifdef FEAT_SEARCHPATH
11523 "file_in_path",
11524 #endif
11525 #if defined(UNIX) && !defined(USE_SYSTEM)
11526 "filterpipe",
11527 #endif
11528 #ifdef FEAT_FIND_ID
11529 "find_in_path",
11530 #endif
11531 #ifdef FEAT_FLOAT
11532 "float",
11533 #endif
11534 #ifdef FEAT_FOLDING
11535 "folding",
11536 #endif
11537 #ifdef FEAT_FOOTER
11538 "footer",
11539 #endif
11540 #if !defined(USE_SYSTEM) && defined(UNIX)
11541 "fork",
11542 #endif
11543 #ifdef FEAT_GETTEXT
11544 "gettext",
11545 #endif
11546 #ifdef FEAT_GUI
11547 "gui",
11548 #endif
11549 #ifdef FEAT_GUI_ATHENA
11550 # ifdef FEAT_GUI_NEXTAW
11551 "gui_neXtaw",
11552 # else
11553 "gui_athena",
11554 # endif
11555 #endif
11556 #ifdef FEAT_GUI_GTK
11557 "gui_gtk",
11558 # ifdef HAVE_GTK2
11559 "gui_gtk2",
11560 # endif
11561 #endif
11562 #ifdef FEAT_GUI_GNOME
11563 "gui_gnome",
11564 #endif
11565 #ifdef FEAT_GUI_MAC
11566 "gui_mac",
11567 #endif
11568 #ifdef FEAT_GUI_MOTIF
11569 "gui_motif",
11570 #endif
11571 #ifdef FEAT_GUI_PHOTON
11572 "gui_photon",
11573 #endif
11574 #ifdef FEAT_GUI_W16
11575 "gui_win16",
11576 #endif
11577 #ifdef FEAT_GUI_W32
11578 "gui_win32",
11579 #endif
11580 #ifdef FEAT_HANGULIN
11581 "hangul_input",
11582 #endif
11583 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
11584 "iconv",
11585 #endif
11586 #ifdef FEAT_INS_EXPAND
11587 "insert_expand",
11588 #endif
11589 #ifdef FEAT_JUMPLIST
11590 "jumplist",
11591 #endif
11592 #ifdef FEAT_KEYMAP
11593 "keymap",
11594 #endif
11595 #ifdef FEAT_LANGMAP
11596 "langmap",
11597 #endif
11598 #ifdef FEAT_LIBCALL
11599 "libcall",
11600 #endif
11601 #ifdef FEAT_LINEBREAK
11602 "linebreak",
11603 #endif
11604 #ifdef FEAT_LISP
11605 "lispindent",
11606 #endif
11607 #ifdef FEAT_LISTCMDS
11608 "listcmds",
11609 #endif
11610 #ifdef FEAT_LOCALMAP
11611 "localmap",
11612 #endif
11613 #ifdef FEAT_MENU
11614 "menu",
11615 #endif
11616 #ifdef FEAT_SESSION
11617 "mksession",
11618 #endif
11619 #ifdef FEAT_MODIFY_FNAME
11620 "modify_fname",
11621 #endif
11622 #ifdef FEAT_MOUSE
11623 "mouse",
11624 #endif
11625 #ifdef FEAT_MOUSESHAPE
11626 "mouseshape",
11627 #endif
11628 #if defined(UNIX) || defined(VMS)
11629 # ifdef FEAT_MOUSE_DEC
11630 "mouse_dec",
11631 # endif
11632 # ifdef FEAT_MOUSE_GPM
11633 "mouse_gpm",
11634 # endif
11635 # ifdef FEAT_MOUSE_JSB
11636 "mouse_jsbterm",
11637 # endif
11638 # ifdef FEAT_MOUSE_NET
11639 "mouse_netterm",
11640 # endif
11641 # ifdef FEAT_MOUSE_PTERM
11642 "mouse_pterm",
11643 # endif
11644 # ifdef FEAT_SYSMOUSE
11645 "mouse_sysmouse",
11646 # endif
11647 # ifdef FEAT_MOUSE_XTERM
11648 "mouse_xterm",
11649 # endif
11650 #endif
11651 #ifdef FEAT_MBYTE
11652 "multi_byte",
11653 #endif
11654 #ifdef FEAT_MBYTE_IME
11655 "multi_byte_ime",
11656 #endif
11657 #ifdef FEAT_MULTI_LANG
11658 "multi_lang",
11659 #endif
11660 #ifdef FEAT_MZSCHEME
11661 #ifndef DYNAMIC_MZSCHEME
11662 "mzscheme",
11663 #endif
11664 #endif
11665 #ifdef FEAT_OLE
11666 "ole",
11667 #endif
11668 #ifdef FEAT_OSFILETYPE
11669 "osfiletype",
11670 #endif
11671 #ifdef FEAT_PATH_EXTRA
11672 "path_extra",
11673 #endif
11674 #ifdef FEAT_PERL
11675 #ifndef DYNAMIC_PERL
11676 "perl",
11677 #endif
11678 #endif
11679 #ifdef FEAT_PYTHON
11680 #ifndef DYNAMIC_PYTHON
11681 "python",
11682 #endif
11683 #endif
11684 #ifdef FEAT_POSTSCRIPT
11685 "postscript",
11686 #endif
11687 #ifdef FEAT_PRINTER
11688 "printer",
11689 #endif
11690 #ifdef FEAT_PROFILE
11691 "profile",
11692 #endif
11693 #ifdef FEAT_RELTIME
11694 "reltime",
11695 #endif
11696 #ifdef FEAT_QUICKFIX
11697 "quickfix",
11698 #endif
11699 #ifdef FEAT_RIGHTLEFT
11700 "rightleft",
11701 #endif
11702 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11703 "ruby",
11704 #endif
11705 #ifdef FEAT_SCROLLBIND
11706 "scrollbind",
11707 #endif
11708 #ifdef FEAT_CMDL_INFO
11709 "showcmd",
11710 "cmdline_info",
11711 #endif
11712 #ifdef FEAT_SIGNS
11713 "signs",
11714 #endif
11715 #ifdef FEAT_SMARTINDENT
11716 "smartindent",
11717 #endif
11718 #ifdef FEAT_SNIFF
11719 "sniff",
11720 #endif
11721 #ifdef FEAT_STL_OPT
11722 "statusline",
11723 #endif
11724 #ifdef FEAT_SUN_WORKSHOP
11725 "sun_workshop",
11726 #endif
11727 #ifdef FEAT_NETBEANS_INTG
11728 "netbeans_intg",
11729 #endif
11730 #ifdef FEAT_SPELL
11731 "spell",
11732 #endif
11733 #ifdef FEAT_SYN_HL
11734 "syntax",
11735 #endif
11736 #if defined(USE_SYSTEM) || !defined(UNIX)
11737 "system",
11738 #endif
11739 #ifdef FEAT_TAG_BINS
11740 "tag_binary",
11741 #endif
11742 #ifdef FEAT_TAG_OLDSTATIC
11743 "tag_old_static",
11744 #endif
11745 #ifdef FEAT_TAG_ANYWHITE
11746 "tag_any_white",
11747 #endif
11748 #ifdef FEAT_TCL
11749 # ifndef DYNAMIC_TCL
11750 "tcl",
11751 # endif
11752 #endif
11753 #ifdef TERMINFO
11754 "terminfo",
11755 #endif
11756 #ifdef FEAT_TERMRESPONSE
11757 "termresponse",
11758 #endif
11759 #ifdef FEAT_TEXTOBJ
11760 "textobjects",
11761 #endif
11762 #ifdef HAVE_TGETENT
11763 "tgetent",
11764 #endif
11765 #ifdef FEAT_TITLE
11766 "title",
11767 #endif
11768 #ifdef FEAT_TOOLBAR
11769 "toolbar",
11770 #endif
11771 #ifdef FEAT_USR_CMDS
11772 "user-commands", /* was accidentally included in 5.4 */
11773 "user_commands",
11774 #endif
11775 #ifdef FEAT_VIMINFO
11776 "viminfo",
11777 #endif
11778 #ifdef FEAT_VERTSPLIT
11779 "vertsplit",
11780 #endif
11781 #ifdef FEAT_VIRTUALEDIT
11782 "virtualedit",
11783 #endif
11784 #ifdef FEAT_VISUAL
11785 "visual",
11786 #endif
11787 #ifdef FEAT_VISUALEXTRA
11788 "visualextra",
11789 #endif
11790 #ifdef FEAT_VREPLACE
11791 "vreplace",
11792 #endif
11793 #ifdef FEAT_WILDIGN
11794 "wildignore",
11795 #endif
11796 #ifdef FEAT_WILDMENU
11797 "wildmenu",
11798 #endif
11799 #ifdef FEAT_WINDOWS
11800 "windows",
11801 #endif
11802 #ifdef FEAT_WAK
11803 "winaltkeys",
11804 #endif
11805 #ifdef FEAT_WRITEBACKUP
11806 "writebackup",
11807 #endif
11808 #ifdef FEAT_XIM
11809 "xim",
11810 #endif
11811 #ifdef FEAT_XFONTSET
11812 "xfontset",
11813 #endif
11814 #ifdef USE_XSMP
11815 "xsmp",
11816 #endif
11817 #ifdef USE_XSMP_INTERACT
11818 "xsmp_interact",
11819 #endif
11820 #ifdef FEAT_XCLIPBOARD
11821 "xterm_clipboard",
11822 #endif
11823 #ifdef FEAT_XTERM_SAVE
11824 "xterm_save",
11825 #endif
11826 #if defined(UNIX) && defined(FEAT_X11)
11827 "X11",
11828 #endif
11829 NULL
11832 name = get_tv_string(&argvars[0]);
11833 for (i = 0; has_list[i] != NULL; ++i)
11834 if (STRICMP(name, has_list[i]) == 0)
11836 n = TRUE;
11837 break;
11840 if (n == FALSE)
11842 if (STRNICMP(name, "patch", 5) == 0)
11843 n = has_patch(atoi((char *)name + 5));
11844 else if (STRICMP(name, "vim_starting") == 0)
11845 n = (starting != 0);
11846 #ifdef FEAT_MBYTE
11847 else if (STRICMP(name, "multi_byte_encoding") == 0)
11848 n = has_mbyte;
11849 #endif
11850 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
11851 else if (STRICMP(name, "balloon_multiline") == 0)
11852 n = multiline_balloon_available();
11853 #endif
11854 #ifdef DYNAMIC_TCL
11855 else if (STRICMP(name, "tcl") == 0)
11856 n = tcl_enabled(FALSE);
11857 #endif
11858 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
11859 else if (STRICMP(name, "iconv") == 0)
11860 n = iconv_enabled(FALSE);
11861 #endif
11862 #ifdef DYNAMIC_MZSCHEME
11863 else if (STRICMP(name, "mzscheme") == 0)
11864 n = mzscheme_enabled(FALSE);
11865 #endif
11866 #ifdef DYNAMIC_RUBY
11867 else if (STRICMP(name, "ruby") == 0)
11868 n = ruby_enabled(FALSE);
11869 #endif
11870 #ifdef DYNAMIC_PYTHON
11871 else if (STRICMP(name, "python") == 0)
11872 n = python_enabled(FALSE);
11873 #endif
11874 #ifdef DYNAMIC_PERL
11875 else if (STRICMP(name, "perl") == 0)
11876 n = perl_enabled(FALSE);
11877 #endif
11878 #ifdef FEAT_GUI
11879 else if (STRICMP(name, "gui_running") == 0)
11880 n = (gui.in_use || gui.starting);
11881 # ifdef FEAT_GUI_W32
11882 else if (STRICMP(name, "gui_win32s") == 0)
11883 n = gui_is_win32s();
11884 # endif
11885 # ifdef FEAT_BROWSE
11886 else if (STRICMP(name, "browse") == 0)
11887 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
11888 # endif
11889 #endif
11890 #ifdef FEAT_SYN_HL
11891 else if (STRICMP(name, "syntax_items") == 0)
11892 n = syntax_present(curbuf);
11893 #endif
11894 #if defined(WIN3264)
11895 else if (STRICMP(name, "win95") == 0)
11896 n = mch_windows95();
11897 #endif
11898 #ifdef FEAT_NETBEANS_INTG
11899 else if (STRICMP(name, "netbeans_enabled") == 0)
11900 n = usingNetbeans;
11901 #endif
11904 rettv->vval.v_number = n;
11908 * "has_key()" function
11910 static void
11911 f_has_key(argvars, rettv)
11912 typval_T *argvars;
11913 typval_T *rettv;
11915 if (argvars[0].v_type != VAR_DICT)
11917 EMSG(_(e_dictreq));
11918 return;
11920 if (argvars[0].vval.v_dict == NULL)
11921 return;
11923 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
11924 get_tv_string(&argvars[1]), -1) != NULL;
11928 * "haslocaldir()" function
11930 /*ARGSUSED*/
11931 static void
11932 f_haslocaldir(argvars, rettv)
11933 typval_T *argvars;
11934 typval_T *rettv;
11936 rettv->vval.v_number = (curwin->w_localdir != NULL);
11940 * "hasmapto()" function
11942 static void
11943 f_hasmapto(argvars, rettv)
11944 typval_T *argvars;
11945 typval_T *rettv;
11947 char_u *name;
11948 char_u *mode;
11949 char_u buf[NUMBUFLEN];
11950 int abbr = FALSE;
11952 name = get_tv_string(&argvars[0]);
11953 if (argvars[1].v_type == VAR_UNKNOWN)
11954 mode = (char_u *)"nvo";
11955 else
11957 mode = get_tv_string_buf(&argvars[1], buf);
11958 if (argvars[2].v_type != VAR_UNKNOWN)
11959 abbr = get_tv_number(&argvars[2]);
11962 if (map_to_exists(name, mode, abbr))
11963 rettv->vval.v_number = TRUE;
11964 else
11965 rettv->vval.v_number = FALSE;
11969 * "histadd()" function
11971 /*ARGSUSED*/
11972 static void
11973 f_histadd(argvars, rettv)
11974 typval_T *argvars;
11975 typval_T *rettv;
11977 #ifdef FEAT_CMDHIST
11978 int histype;
11979 char_u *str;
11980 char_u buf[NUMBUFLEN];
11981 #endif
11983 rettv->vval.v_number = FALSE;
11984 if (check_restricted() || check_secure())
11985 return;
11986 #ifdef FEAT_CMDHIST
11987 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11988 histype = str != NULL ? get_histtype(str) : -1;
11989 if (histype >= 0)
11991 str = get_tv_string_buf(&argvars[1], buf);
11992 if (*str != NUL)
11994 add_to_history(histype, str, FALSE, NUL);
11995 rettv->vval.v_number = TRUE;
11996 return;
11999 #endif
12003 * "histdel()" function
12005 /*ARGSUSED*/
12006 static void
12007 f_histdel(argvars, rettv)
12008 typval_T *argvars;
12009 typval_T *rettv;
12011 #ifdef FEAT_CMDHIST
12012 int n;
12013 char_u buf[NUMBUFLEN];
12014 char_u *str;
12016 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12017 if (str == NULL)
12018 n = 0;
12019 else if (argvars[1].v_type == VAR_UNKNOWN)
12020 /* only one argument: clear entire history */
12021 n = clr_history(get_histtype(str));
12022 else if (argvars[1].v_type == VAR_NUMBER)
12023 /* index given: remove that entry */
12024 n = del_history_idx(get_histtype(str),
12025 (int)get_tv_number(&argvars[1]));
12026 else
12027 /* string given: remove all matching entries */
12028 n = del_history_entry(get_histtype(str),
12029 get_tv_string_buf(&argvars[1], buf));
12030 rettv->vval.v_number = n;
12031 #endif
12035 * "histget()" function
12037 /*ARGSUSED*/
12038 static void
12039 f_histget(argvars, rettv)
12040 typval_T *argvars;
12041 typval_T *rettv;
12043 #ifdef FEAT_CMDHIST
12044 int type;
12045 int idx;
12046 char_u *str;
12048 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12049 if (str == NULL)
12050 rettv->vval.v_string = NULL;
12051 else
12053 type = get_histtype(str);
12054 if (argvars[1].v_type == VAR_UNKNOWN)
12055 idx = get_history_idx(type);
12056 else
12057 idx = (int)get_tv_number_chk(&argvars[1], NULL);
12058 /* -1 on type error */
12059 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
12061 #else
12062 rettv->vval.v_string = NULL;
12063 #endif
12064 rettv->v_type = VAR_STRING;
12068 * "histnr()" function
12070 /*ARGSUSED*/
12071 static void
12072 f_histnr(argvars, rettv)
12073 typval_T *argvars;
12074 typval_T *rettv;
12076 int i;
12078 #ifdef FEAT_CMDHIST
12079 char_u *history = get_tv_string_chk(&argvars[0]);
12081 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
12082 if (i >= HIST_CMD && i < HIST_COUNT)
12083 i = get_history_idx(i);
12084 else
12085 #endif
12086 i = -1;
12087 rettv->vval.v_number = i;
12091 * "highlightID(name)" function
12093 static void
12094 f_hlID(argvars, rettv)
12095 typval_T *argvars;
12096 typval_T *rettv;
12098 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
12102 * "highlight_exists()" function
12104 static void
12105 f_hlexists(argvars, rettv)
12106 typval_T *argvars;
12107 typval_T *rettv;
12109 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
12113 * "hostname()" function
12115 /*ARGSUSED*/
12116 static void
12117 f_hostname(argvars, rettv)
12118 typval_T *argvars;
12119 typval_T *rettv;
12121 char_u hostname[256];
12123 mch_get_host_name(hostname, 256);
12124 rettv->v_type = VAR_STRING;
12125 rettv->vval.v_string = vim_strsave(hostname);
12129 * iconv() function
12131 /*ARGSUSED*/
12132 static void
12133 f_iconv(argvars, rettv)
12134 typval_T *argvars;
12135 typval_T *rettv;
12137 #ifdef FEAT_MBYTE
12138 char_u buf1[NUMBUFLEN];
12139 char_u buf2[NUMBUFLEN];
12140 char_u *from, *to, *str;
12141 vimconv_T vimconv;
12142 #endif
12144 rettv->v_type = VAR_STRING;
12145 rettv->vval.v_string = NULL;
12147 #ifdef FEAT_MBYTE
12148 str = get_tv_string(&argvars[0]);
12149 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
12150 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
12151 vimconv.vc_type = CONV_NONE;
12152 convert_setup(&vimconv, from, to);
12154 /* If the encodings are equal, no conversion needed. */
12155 if (vimconv.vc_type == CONV_NONE)
12156 rettv->vval.v_string = vim_strsave(str);
12157 else
12158 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
12160 convert_setup(&vimconv, NULL, NULL);
12161 vim_free(from);
12162 vim_free(to);
12163 #endif
12167 * "indent()" function
12169 static void
12170 f_indent(argvars, rettv)
12171 typval_T *argvars;
12172 typval_T *rettv;
12174 linenr_T lnum;
12176 lnum = get_tv_lnum(argvars);
12177 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12178 rettv->vval.v_number = get_indent_lnum(lnum);
12179 else
12180 rettv->vval.v_number = -1;
12184 * "index()" function
12186 static void
12187 f_index(argvars, rettv)
12188 typval_T *argvars;
12189 typval_T *rettv;
12191 list_T *l;
12192 listitem_T *item;
12193 long idx = 0;
12194 int ic = FALSE;
12196 rettv->vval.v_number = -1;
12197 if (argvars[0].v_type != VAR_LIST)
12199 EMSG(_(e_listreq));
12200 return;
12202 l = argvars[0].vval.v_list;
12203 if (l != NULL)
12205 item = l->lv_first;
12206 if (argvars[2].v_type != VAR_UNKNOWN)
12208 int error = FALSE;
12210 /* Start at specified item. Use the cached index that list_find()
12211 * sets, so that a negative number also works. */
12212 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
12213 idx = l->lv_idx;
12214 if (argvars[3].v_type != VAR_UNKNOWN)
12215 ic = get_tv_number_chk(&argvars[3], &error);
12216 if (error)
12217 item = NULL;
12220 for ( ; item != NULL; item = item->li_next, ++idx)
12221 if (tv_equal(&item->li_tv, &argvars[1], ic))
12223 rettv->vval.v_number = idx;
12224 break;
12229 static int inputsecret_flag = 0;
12231 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
12234 * This function is used by f_input() and f_inputdialog() functions. The third
12235 * argument to f_input() specifies the type of completion to use at the
12236 * prompt. The third argument to f_inputdialog() specifies the value to return
12237 * when the user cancels the prompt.
12239 static void
12240 get_user_input(argvars, rettv, inputdialog)
12241 typval_T *argvars;
12242 typval_T *rettv;
12243 int inputdialog;
12245 char_u *prompt = get_tv_string_chk(&argvars[0]);
12246 char_u *p = NULL;
12247 int c;
12248 char_u buf[NUMBUFLEN];
12249 int cmd_silent_save = cmd_silent;
12250 char_u *defstr = (char_u *)"";
12251 int xp_type = EXPAND_NOTHING;
12252 char_u *xp_arg = NULL;
12254 rettv->v_type = VAR_STRING;
12255 rettv->vval.v_string = NULL;
12257 #ifdef NO_CONSOLE_INPUT
12258 /* While starting up, there is no place to enter text. */
12259 if (no_console_input())
12260 return;
12261 #endif
12263 cmd_silent = FALSE; /* Want to see the prompt. */
12264 if (prompt != NULL)
12266 /* Only the part of the message after the last NL is considered as
12267 * prompt for the command line */
12268 p = vim_strrchr(prompt, '\n');
12269 if (p == NULL)
12270 p = prompt;
12271 else
12273 ++p;
12274 c = *p;
12275 *p = NUL;
12276 msg_start();
12277 msg_clr_eos();
12278 msg_puts_attr(prompt, echo_attr);
12279 msg_didout = FALSE;
12280 msg_starthere();
12281 *p = c;
12283 cmdline_row = msg_row;
12285 if (argvars[1].v_type != VAR_UNKNOWN)
12287 defstr = get_tv_string_buf_chk(&argvars[1], buf);
12288 if (defstr != NULL)
12289 stuffReadbuffSpec(defstr);
12291 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
12293 char_u *xp_name;
12294 int xp_namelen;
12295 long argt;
12297 rettv->vval.v_string = NULL;
12299 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
12300 if (xp_name == NULL)
12301 return;
12303 xp_namelen = (int)STRLEN(xp_name);
12305 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
12306 &xp_arg) == FAIL)
12307 return;
12311 if (defstr != NULL)
12312 rettv->vval.v_string =
12313 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
12314 xp_type, xp_arg);
12316 vim_free(xp_arg);
12318 /* since the user typed this, no need to wait for return */
12319 need_wait_return = FALSE;
12320 msg_didout = FALSE;
12322 cmd_silent = cmd_silent_save;
12326 * "input()" function
12327 * Also handles inputsecret() when inputsecret is set.
12329 static void
12330 f_input(argvars, rettv)
12331 typval_T *argvars;
12332 typval_T *rettv;
12334 get_user_input(argvars, rettv, FALSE);
12338 * "inputdialog()" function
12340 static void
12341 f_inputdialog(argvars, rettv)
12342 typval_T *argvars;
12343 typval_T *rettv;
12345 #if defined(FEAT_GUI_TEXTDIALOG)
12346 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
12347 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
12349 char_u *message;
12350 char_u buf[NUMBUFLEN];
12351 char_u *defstr = (char_u *)"";
12353 message = get_tv_string_chk(&argvars[0]);
12354 if (argvars[1].v_type != VAR_UNKNOWN
12355 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
12356 vim_strncpy(IObuff, defstr, IOSIZE - 1);
12357 else
12358 IObuff[0] = NUL;
12359 if (message != NULL && defstr != NULL
12360 && do_dialog(VIM_QUESTION, NULL, message,
12361 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
12362 rettv->vval.v_string = vim_strsave(IObuff);
12363 else
12365 if (message != NULL && defstr != NULL
12366 && argvars[1].v_type != VAR_UNKNOWN
12367 && argvars[2].v_type != VAR_UNKNOWN)
12368 rettv->vval.v_string = vim_strsave(
12369 get_tv_string_buf(&argvars[2], buf));
12370 else
12371 rettv->vval.v_string = NULL;
12373 rettv->v_type = VAR_STRING;
12375 else
12376 #endif
12377 get_user_input(argvars, rettv, TRUE);
12381 * "inputlist()" function
12383 static void
12384 f_inputlist(argvars, rettv)
12385 typval_T *argvars;
12386 typval_T *rettv;
12388 listitem_T *li;
12389 int selected;
12390 int mouse_used;
12392 #ifdef NO_CONSOLE_INPUT
12393 /* While starting up, there is no place to enter text. */
12394 if (no_console_input())
12395 return;
12396 #endif
12397 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
12399 EMSG2(_(e_listarg), "inputlist()");
12400 return;
12403 msg_start();
12404 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
12405 lines_left = Rows; /* avoid more prompt */
12406 msg_scroll = TRUE;
12407 msg_clr_eos();
12409 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
12411 msg_puts(get_tv_string(&li->li_tv));
12412 msg_putchar('\n');
12415 /* Ask for choice. */
12416 selected = prompt_for_number(&mouse_used);
12417 if (mouse_used)
12418 selected -= lines_left;
12420 rettv->vval.v_number = selected;
12424 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
12427 * "inputrestore()" function
12429 /*ARGSUSED*/
12430 static void
12431 f_inputrestore(argvars, rettv)
12432 typval_T *argvars;
12433 typval_T *rettv;
12435 if (ga_userinput.ga_len > 0)
12437 --ga_userinput.ga_len;
12438 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
12439 + ga_userinput.ga_len);
12440 /* default return is zero == OK */
12442 else if (p_verbose > 1)
12444 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
12445 rettv->vval.v_number = 1; /* Failed */
12450 * "inputsave()" function
12452 /*ARGSUSED*/
12453 static void
12454 f_inputsave(argvars, rettv)
12455 typval_T *argvars;
12456 typval_T *rettv;
12458 /* Add an entry to the stack of typeahead storage. */
12459 if (ga_grow(&ga_userinput, 1) == OK)
12461 save_typeahead((tasave_T *)(ga_userinput.ga_data)
12462 + ga_userinput.ga_len);
12463 ++ga_userinput.ga_len;
12464 /* default return is zero == OK */
12466 else
12467 rettv->vval.v_number = 1; /* Failed */
12471 * "inputsecret()" function
12473 static void
12474 f_inputsecret(argvars, rettv)
12475 typval_T *argvars;
12476 typval_T *rettv;
12478 ++cmdline_star;
12479 ++inputsecret_flag;
12480 f_input(argvars, rettv);
12481 --cmdline_star;
12482 --inputsecret_flag;
12486 * "insert()" function
12488 static void
12489 f_insert(argvars, rettv)
12490 typval_T *argvars;
12491 typval_T *rettv;
12493 long before = 0;
12494 listitem_T *item;
12495 list_T *l;
12496 int error = FALSE;
12498 if (argvars[0].v_type != VAR_LIST)
12499 EMSG2(_(e_listarg), "insert()");
12500 else if ((l = argvars[0].vval.v_list) != NULL
12501 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
12503 if (argvars[2].v_type != VAR_UNKNOWN)
12504 before = get_tv_number_chk(&argvars[2], &error);
12505 if (error)
12506 return; /* type error; errmsg already given */
12508 if (before == l->lv_len)
12509 item = NULL;
12510 else
12512 item = list_find(l, before);
12513 if (item == NULL)
12515 EMSGN(_(e_listidx), before);
12516 l = NULL;
12519 if (l != NULL)
12521 list_insert_tv(l, &argvars[1], item);
12522 copy_tv(&argvars[0], rettv);
12528 * "isdirectory()" function
12530 static void
12531 f_isdirectory(argvars, rettv)
12532 typval_T *argvars;
12533 typval_T *rettv;
12535 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
12539 * "islocked()" function
12541 static void
12542 f_islocked(argvars, rettv)
12543 typval_T *argvars;
12544 typval_T *rettv;
12546 lval_T lv;
12547 char_u *end;
12548 dictitem_T *di;
12550 rettv->vval.v_number = -1;
12551 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
12552 FNE_CHECK_START);
12553 if (end != NULL && lv.ll_name != NULL)
12555 if (*end != NUL)
12556 EMSG(_(e_trailing));
12557 else
12559 if (lv.ll_tv == NULL)
12561 if (check_changedtick(lv.ll_name))
12562 rettv->vval.v_number = 1; /* always locked */
12563 else
12565 di = find_var(lv.ll_name, NULL);
12566 if (di != NULL)
12568 /* Consider a variable locked when:
12569 * 1. the variable itself is locked
12570 * 2. the value of the variable is locked.
12571 * 3. the List or Dict value is locked.
12573 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
12574 || tv_islocked(&di->di_tv));
12578 else if (lv.ll_range)
12579 EMSG(_("E786: Range not allowed"));
12580 else if (lv.ll_newkey != NULL)
12581 EMSG2(_(e_dictkey), lv.ll_newkey);
12582 else if (lv.ll_list != NULL)
12583 /* List item. */
12584 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
12585 else
12586 /* Dictionary item. */
12587 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
12591 clear_lval(&lv);
12594 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
12597 * Turn a dict into a list:
12598 * "what" == 0: list of keys
12599 * "what" == 1: list of values
12600 * "what" == 2: list of items
12602 static void
12603 dict_list(argvars, rettv, what)
12604 typval_T *argvars;
12605 typval_T *rettv;
12606 int what;
12608 list_T *l2;
12609 dictitem_T *di;
12610 hashitem_T *hi;
12611 listitem_T *li;
12612 listitem_T *li2;
12613 dict_T *d;
12614 int todo;
12616 if (argvars[0].v_type != VAR_DICT)
12618 EMSG(_(e_dictreq));
12619 return;
12621 if ((d = argvars[0].vval.v_dict) == NULL)
12622 return;
12624 if (rettv_list_alloc(rettv) == FAIL)
12625 return;
12627 todo = (int)d->dv_hashtab.ht_used;
12628 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12630 if (!HASHITEM_EMPTY(hi))
12632 --todo;
12633 di = HI2DI(hi);
12635 li = listitem_alloc();
12636 if (li == NULL)
12637 break;
12638 list_append(rettv->vval.v_list, li);
12640 if (what == 0)
12642 /* keys() */
12643 li->li_tv.v_type = VAR_STRING;
12644 li->li_tv.v_lock = 0;
12645 li->li_tv.vval.v_string = vim_strsave(di->di_key);
12647 else if (what == 1)
12649 /* values() */
12650 copy_tv(&di->di_tv, &li->li_tv);
12652 else
12654 /* items() */
12655 l2 = list_alloc();
12656 li->li_tv.v_type = VAR_LIST;
12657 li->li_tv.v_lock = 0;
12658 li->li_tv.vval.v_list = l2;
12659 if (l2 == NULL)
12660 break;
12661 ++l2->lv_refcount;
12663 li2 = listitem_alloc();
12664 if (li2 == NULL)
12665 break;
12666 list_append(l2, li2);
12667 li2->li_tv.v_type = VAR_STRING;
12668 li2->li_tv.v_lock = 0;
12669 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12671 li2 = listitem_alloc();
12672 if (li2 == NULL)
12673 break;
12674 list_append(l2, li2);
12675 copy_tv(&di->di_tv, &li2->li_tv);
12682 * "items(dict)" function
12684 static void
12685 f_items(argvars, rettv)
12686 typval_T *argvars;
12687 typval_T *rettv;
12689 dict_list(argvars, rettv, 2);
12693 * "join()" function
12695 static void
12696 f_join(argvars, rettv)
12697 typval_T *argvars;
12698 typval_T *rettv;
12700 garray_T ga;
12701 char_u *sep;
12703 if (argvars[0].v_type != VAR_LIST)
12705 EMSG(_(e_listreq));
12706 return;
12708 if (argvars[0].vval.v_list == NULL)
12709 return;
12710 if (argvars[1].v_type == VAR_UNKNOWN)
12711 sep = (char_u *)" ";
12712 else
12713 sep = get_tv_string_chk(&argvars[1]);
12715 rettv->v_type = VAR_STRING;
12717 if (sep != NULL)
12719 ga_init2(&ga, (int)sizeof(char), 80);
12720 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12721 ga_append(&ga, NUL);
12722 rettv->vval.v_string = (char_u *)ga.ga_data;
12724 else
12725 rettv->vval.v_string = NULL;
12729 * "keys()" function
12731 static void
12732 f_keys(argvars, rettv)
12733 typval_T *argvars;
12734 typval_T *rettv;
12736 dict_list(argvars, rettv, 0);
12740 * "last_buffer_nr()" function.
12742 /*ARGSUSED*/
12743 static void
12744 f_last_buffer_nr(argvars, rettv)
12745 typval_T *argvars;
12746 typval_T *rettv;
12748 int n = 0;
12749 buf_T *buf;
12751 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12752 if (n < buf->b_fnum)
12753 n = buf->b_fnum;
12755 rettv->vval.v_number = n;
12759 * "len()" function
12761 static void
12762 f_len(argvars, rettv)
12763 typval_T *argvars;
12764 typval_T *rettv;
12766 switch (argvars[0].v_type)
12768 case VAR_STRING:
12769 case VAR_NUMBER:
12770 rettv->vval.v_number = (varnumber_T)STRLEN(
12771 get_tv_string(&argvars[0]));
12772 break;
12773 case VAR_LIST:
12774 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
12775 break;
12776 case VAR_DICT:
12777 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
12778 break;
12779 default:
12780 EMSG(_("E701: Invalid type for len()"));
12781 break;
12785 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
12787 static void
12788 libcall_common(argvars, rettv, type)
12789 typval_T *argvars;
12790 typval_T *rettv;
12791 int type;
12793 #ifdef FEAT_LIBCALL
12794 char_u *string_in;
12795 char_u **string_result;
12796 int nr_result;
12797 #endif
12799 rettv->v_type = type;
12800 if (type != VAR_NUMBER)
12801 rettv->vval.v_string = NULL;
12803 if (check_restricted() || check_secure())
12804 return;
12806 #ifdef FEAT_LIBCALL
12807 /* The first two args must be strings, otherwise its meaningless */
12808 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
12810 string_in = NULL;
12811 if (argvars[2].v_type == VAR_STRING)
12812 string_in = argvars[2].vval.v_string;
12813 if (type == VAR_NUMBER)
12814 string_result = NULL;
12815 else
12816 string_result = &rettv->vval.v_string;
12817 if (mch_libcall(argvars[0].vval.v_string,
12818 argvars[1].vval.v_string,
12819 string_in,
12820 argvars[2].vval.v_number,
12821 string_result,
12822 &nr_result) == OK
12823 && type == VAR_NUMBER)
12824 rettv->vval.v_number = nr_result;
12826 #endif
12830 * "libcall()" function
12832 static void
12833 f_libcall(argvars, rettv)
12834 typval_T *argvars;
12835 typval_T *rettv;
12837 libcall_common(argvars, rettv, VAR_STRING);
12841 * "libcallnr()" function
12843 static void
12844 f_libcallnr(argvars, rettv)
12845 typval_T *argvars;
12846 typval_T *rettv;
12848 libcall_common(argvars, rettv, VAR_NUMBER);
12852 * "line(string)" function
12854 static void
12855 f_line(argvars, rettv)
12856 typval_T *argvars;
12857 typval_T *rettv;
12859 linenr_T lnum = 0;
12860 pos_T *fp;
12861 int fnum;
12863 fp = var2fpos(&argvars[0], TRUE, &fnum);
12864 if (fp != NULL)
12865 lnum = fp->lnum;
12866 rettv->vval.v_number = lnum;
12870 * "line2byte(lnum)" function
12872 /*ARGSUSED*/
12873 static void
12874 f_line2byte(argvars, rettv)
12875 typval_T *argvars;
12876 typval_T *rettv;
12878 #ifndef FEAT_BYTEOFF
12879 rettv->vval.v_number = -1;
12880 #else
12881 linenr_T lnum;
12883 lnum = get_tv_lnum(argvars);
12884 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
12885 rettv->vval.v_number = -1;
12886 else
12887 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
12888 if (rettv->vval.v_number >= 0)
12889 ++rettv->vval.v_number;
12890 #endif
12894 * "lispindent(lnum)" function
12896 static void
12897 f_lispindent(argvars, rettv)
12898 typval_T *argvars;
12899 typval_T *rettv;
12901 #ifdef FEAT_LISP
12902 pos_T pos;
12903 linenr_T lnum;
12905 pos = curwin->w_cursor;
12906 lnum = get_tv_lnum(argvars);
12907 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12909 curwin->w_cursor.lnum = lnum;
12910 rettv->vval.v_number = get_lisp_indent();
12911 curwin->w_cursor = pos;
12913 else
12914 #endif
12915 rettv->vval.v_number = -1;
12919 * "localtime()" function
12921 /*ARGSUSED*/
12922 static void
12923 f_localtime(argvars, rettv)
12924 typval_T *argvars;
12925 typval_T *rettv;
12927 rettv->vval.v_number = (varnumber_T)time(NULL);
12930 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
12932 static void
12933 get_maparg(argvars, rettv, exact)
12934 typval_T *argvars;
12935 typval_T *rettv;
12936 int exact;
12938 char_u *keys;
12939 char_u *which;
12940 char_u buf[NUMBUFLEN];
12941 char_u *keys_buf = NULL;
12942 char_u *rhs;
12943 int mode;
12944 garray_T ga;
12945 int abbr = FALSE;
12947 /* return empty string for failure */
12948 rettv->v_type = VAR_STRING;
12949 rettv->vval.v_string = NULL;
12951 keys = get_tv_string(&argvars[0]);
12952 if (*keys == NUL)
12953 return;
12955 if (argvars[1].v_type != VAR_UNKNOWN)
12957 which = get_tv_string_buf_chk(&argvars[1], buf);
12958 if (argvars[2].v_type != VAR_UNKNOWN)
12959 abbr = get_tv_number(&argvars[2]);
12961 else
12962 which = (char_u *)"";
12963 if (which == NULL)
12964 return;
12966 mode = get_map_mode(&which, 0);
12968 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
12969 rhs = check_map(keys, mode, exact, FALSE, abbr);
12970 vim_free(keys_buf);
12971 if (rhs != NULL)
12973 ga_init(&ga);
12974 ga.ga_itemsize = 1;
12975 ga.ga_growsize = 40;
12977 while (*rhs != NUL)
12978 ga_concat(&ga, str2special(&rhs, FALSE));
12980 ga_append(&ga, NUL);
12981 rettv->vval.v_string = (char_u *)ga.ga_data;
12985 #ifdef FEAT_FLOAT
12987 * "log10()" function
12989 static void
12990 f_log10(argvars, rettv)
12991 typval_T *argvars;
12992 typval_T *rettv;
12994 float_T f;
12996 rettv->v_type = VAR_FLOAT;
12997 if (get_float_arg(argvars, &f) == OK)
12998 rettv->vval.v_float = log10(f);
12999 else
13000 rettv->vval.v_float = 0.0;
13002 #endif
13005 * "map()" function
13007 static void
13008 f_map(argvars, rettv)
13009 typval_T *argvars;
13010 typval_T *rettv;
13012 filter_map(argvars, rettv, TRUE);
13016 * "maparg()" function
13018 static void
13019 f_maparg(argvars, rettv)
13020 typval_T *argvars;
13021 typval_T *rettv;
13023 get_maparg(argvars, rettv, TRUE);
13027 * "mapcheck()" function
13029 static void
13030 f_mapcheck(argvars, rettv)
13031 typval_T *argvars;
13032 typval_T *rettv;
13034 get_maparg(argvars, rettv, FALSE);
13037 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
13039 static void
13040 find_some_match(argvars, rettv, type)
13041 typval_T *argvars;
13042 typval_T *rettv;
13043 int type;
13045 char_u *str = NULL;
13046 char_u *expr = NULL;
13047 char_u *pat;
13048 regmatch_T regmatch;
13049 char_u patbuf[NUMBUFLEN];
13050 char_u strbuf[NUMBUFLEN];
13051 char_u *save_cpo;
13052 long start = 0;
13053 long nth = 1;
13054 colnr_T startcol = 0;
13055 int match = 0;
13056 list_T *l = NULL;
13057 listitem_T *li = NULL;
13058 long idx = 0;
13059 char_u *tofree = NULL;
13061 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
13062 save_cpo = p_cpo;
13063 p_cpo = (char_u *)"";
13065 rettv->vval.v_number = -1;
13066 if (type == 3)
13068 /* return empty list when there are no matches */
13069 if (rettv_list_alloc(rettv) == FAIL)
13070 goto theend;
13072 else if (type == 2)
13074 rettv->v_type = VAR_STRING;
13075 rettv->vval.v_string = NULL;
13078 if (argvars[0].v_type == VAR_LIST)
13080 if ((l = argvars[0].vval.v_list) == NULL)
13081 goto theend;
13082 li = l->lv_first;
13084 else
13085 expr = str = get_tv_string(&argvars[0]);
13087 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
13088 if (pat == NULL)
13089 goto theend;
13091 if (argvars[2].v_type != VAR_UNKNOWN)
13093 int error = FALSE;
13095 start = get_tv_number_chk(&argvars[2], &error);
13096 if (error)
13097 goto theend;
13098 if (l != NULL)
13100 li = list_find(l, start);
13101 if (li == NULL)
13102 goto theend;
13103 idx = l->lv_idx; /* use the cached index */
13105 else
13107 if (start < 0)
13108 start = 0;
13109 if (start > (long)STRLEN(str))
13110 goto theend;
13111 /* When "count" argument is there ignore matches before "start",
13112 * otherwise skip part of the string. Differs when pattern is "^"
13113 * or "\<". */
13114 if (argvars[3].v_type != VAR_UNKNOWN)
13115 startcol = start;
13116 else
13117 str += start;
13120 if (argvars[3].v_type != VAR_UNKNOWN)
13121 nth = get_tv_number_chk(&argvars[3], &error);
13122 if (error)
13123 goto theend;
13126 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
13127 if (regmatch.regprog != NULL)
13129 regmatch.rm_ic = p_ic;
13131 for (;;)
13133 if (l != NULL)
13135 if (li == NULL)
13137 match = FALSE;
13138 break;
13140 vim_free(tofree);
13141 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
13142 if (str == NULL)
13143 break;
13146 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
13148 if (match && --nth <= 0)
13149 break;
13150 if (l == NULL && !match)
13151 break;
13153 /* Advance to just after the match. */
13154 if (l != NULL)
13156 li = li->li_next;
13157 ++idx;
13159 else
13161 #ifdef FEAT_MBYTE
13162 startcol = (colnr_T)(regmatch.startp[0]
13163 + (*mb_ptr2len)(regmatch.startp[0]) - str);
13164 #else
13165 startcol = regmatch.startp[0] + 1 - str;
13166 #endif
13170 if (match)
13172 if (type == 3)
13174 int i;
13176 /* return list with matched string and submatches */
13177 for (i = 0; i < NSUBEXP; ++i)
13179 if (regmatch.endp[i] == NULL)
13181 if (list_append_string(rettv->vval.v_list,
13182 (char_u *)"", 0) == FAIL)
13183 break;
13185 else if (list_append_string(rettv->vval.v_list,
13186 regmatch.startp[i],
13187 (int)(regmatch.endp[i] - regmatch.startp[i]))
13188 == FAIL)
13189 break;
13192 else if (type == 2)
13194 /* return matched string */
13195 if (l != NULL)
13196 copy_tv(&li->li_tv, rettv);
13197 else
13198 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
13199 (int)(regmatch.endp[0] - regmatch.startp[0]));
13201 else if (l != NULL)
13202 rettv->vval.v_number = idx;
13203 else
13205 if (type != 0)
13206 rettv->vval.v_number =
13207 (varnumber_T)(regmatch.startp[0] - str);
13208 else
13209 rettv->vval.v_number =
13210 (varnumber_T)(regmatch.endp[0] - str);
13211 rettv->vval.v_number += (varnumber_T)(str - expr);
13214 vim_free(regmatch.regprog);
13217 theend:
13218 vim_free(tofree);
13219 p_cpo = save_cpo;
13223 * "match()" function
13225 static void
13226 f_match(argvars, rettv)
13227 typval_T *argvars;
13228 typval_T *rettv;
13230 find_some_match(argvars, rettv, 1);
13234 * "matchadd()" function
13236 static void
13237 f_matchadd(argvars, rettv)
13238 typval_T *argvars;
13239 typval_T *rettv;
13241 #ifdef FEAT_SEARCH_EXTRA
13242 char_u buf[NUMBUFLEN];
13243 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
13244 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
13245 int prio = 10; /* default priority */
13246 int id = -1;
13247 int error = FALSE;
13249 rettv->vval.v_number = -1;
13251 if (grp == NULL || pat == NULL)
13252 return;
13253 if (argvars[2].v_type != VAR_UNKNOWN)
13255 prio = get_tv_number_chk(&argvars[2], &error);
13256 if (argvars[3].v_type != VAR_UNKNOWN)
13257 id = get_tv_number_chk(&argvars[3], &error);
13259 if (error == TRUE)
13260 return;
13261 if (id >= 1 && id <= 3)
13263 EMSGN("E798: ID is reserved for \":match\": %ld", id);
13264 return;
13267 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
13268 #endif
13272 * "matcharg()" function
13274 static void
13275 f_matcharg(argvars, rettv)
13276 typval_T *argvars;
13277 typval_T *rettv;
13279 if (rettv_list_alloc(rettv) == OK)
13281 #ifdef FEAT_SEARCH_EXTRA
13282 int id = get_tv_number(&argvars[0]);
13283 matchitem_T *m;
13285 if (id >= 1 && id <= 3)
13287 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
13289 list_append_string(rettv->vval.v_list,
13290 syn_id2name(m->hlg_id), -1);
13291 list_append_string(rettv->vval.v_list, m->pattern, -1);
13293 else
13295 list_append_string(rettv->vval.v_list, NUL, -1);
13296 list_append_string(rettv->vval.v_list, NUL, -1);
13299 #endif
13304 * "matchdelete()" function
13306 static void
13307 f_matchdelete(argvars, rettv)
13308 typval_T *argvars;
13309 typval_T *rettv;
13311 #ifdef FEAT_SEARCH_EXTRA
13312 rettv->vval.v_number = match_delete(curwin,
13313 (int)get_tv_number(&argvars[0]), TRUE);
13314 #endif
13318 * "matchend()" function
13320 static void
13321 f_matchend(argvars, rettv)
13322 typval_T *argvars;
13323 typval_T *rettv;
13325 find_some_match(argvars, rettv, 0);
13329 * "matchlist()" function
13331 static void
13332 f_matchlist(argvars, rettv)
13333 typval_T *argvars;
13334 typval_T *rettv;
13336 find_some_match(argvars, rettv, 3);
13340 * "matchstr()" function
13342 static void
13343 f_matchstr(argvars, rettv)
13344 typval_T *argvars;
13345 typval_T *rettv;
13347 find_some_match(argvars, rettv, 2);
13350 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
13352 static void
13353 max_min(argvars, rettv, domax)
13354 typval_T *argvars;
13355 typval_T *rettv;
13356 int domax;
13358 long n = 0;
13359 long i;
13360 int error = FALSE;
13362 if (argvars[0].v_type == VAR_LIST)
13364 list_T *l;
13365 listitem_T *li;
13367 l = argvars[0].vval.v_list;
13368 if (l != NULL)
13370 li = l->lv_first;
13371 if (li != NULL)
13373 n = get_tv_number_chk(&li->li_tv, &error);
13374 for (;;)
13376 li = li->li_next;
13377 if (li == NULL)
13378 break;
13379 i = get_tv_number_chk(&li->li_tv, &error);
13380 if (domax ? i > n : i < n)
13381 n = i;
13386 else if (argvars[0].v_type == VAR_DICT)
13388 dict_T *d;
13389 int first = TRUE;
13390 hashitem_T *hi;
13391 int todo;
13393 d = argvars[0].vval.v_dict;
13394 if (d != NULL)
13396 todo = (int)d->dv_hashtab.ht_used;
13397 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13399 if (!HASHITEM_EMPTY(hi))
13401 --todo;
13402 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
13403 if (first)
13405 n = i;
13406 first = FALSE;
13408 else if (domax ? i > n : i < n)
13409 n = i;
13414 else
13415 EMSG(_(e_listdictarg));
13416 rettv->vval.v_number = error ? 0 : n;
13420 * "max()" function
13422 static void
13423 f_max(argvars, rettv)
13424 typval_T *argvars;
13425 typval_T *rettv;
13427 max_min(argvars, rettv, TRUE);
13431 * "min()" function
13433 static void
13434 f_min(argvars, rettv)
13435 typval_T *argvars;
13436 typval_T *rettv;
13438 max_min(argvars, rettv, FALSE);
13441 static int mkdir_recurse __ARGS((char_u *dir, int prot));
13444 * Create the directory in which "dir" is located, and higher levels when
13445 * needed.
13447 static int
13448 mkdir_recurse(dir, prot)
13449 char_u *dir;
13450 int prot;
13452 char_u *p;
13453 char_u *updir;
13454 int r = FAIL;
13456 /* Get end of directory name in "dir".
13457 * We're done when it's "/" or "c:/". */
13458 p = gettail_sep(dir);
13459 if (p <= get_past_head(dir))
13460 return OK;
13462 /* If the directory exists we're done. Otherwise: create it.*/
13463 updir = vim_strnsave(dir, (int)(p - dir));
13464 if (updir == NULL)
13465 return FAIL;
13466 if (mch_isdir(updir))
13467 r = OK;
13468 else if (mkdir_recurse(updir, prot) == OK)
13469 r = vim_mkdir_emsg(updir, prot);
13470 vim_free(updir);
13471 return r;
13474 #ifdef vim_mkdir
13476 * "mkdir()" function
13478 static void
13479 f_mkdir(argvars, rettv)
13480 typval_T *argvars;
13481 typval_T *rettv;
13483 char_u *dir;
13484 char_u buf[NUMBUFLEN];
13485 int prot = 0755;
13487 rettv->vval.v_number = FAIL;
13488 if (check_restricted() || check_secure())
13489 return;
13491 dir = get_tv_string_buf(&argvars[0], buf);
13492 if (argvars[1].v_type != VAR_UNKNOWN)
13494 if (argvars[2].v_type != VAR_UNKNOWN)
13495 prot = get_tv_number_chk(&argvars[2], NULL);
13496 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
13497 mkdir_recurse(dir, prot);
13499 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
13501 #endif
13504 * "mode()" function
13506 /*ARGSUSED*/
13507 static void
13508 f_mode(argvars, rettv)
13509 typval_T *argvars;
13510 typval_T *rettv;
13512 char_u buf[3];
13514 buf[1] = NUL;
13515 buf[2] = NUL;
13517 #ifdef FEAT_VISUAL
13518 if (VIsual_active)
13520 if (VIsual_select)
13521 buf[0] = VIsual_mode + 's' - 'v';
13522 else
13523 buf[0] = VIsual_mode;
13525 else
13526 #endif
13527 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
13528 || State == CONFIRM)
13530 buf[0] = 'r';
13531 if (State == ASKMORE)
13532 buf[1] = 'm';
13533 else if (State == CONFIRM)
13534 buf[1] = '?';
13536 else if (State == EXTERNCMD)
13537 buf[0] = '!';
13538 else if (State & INSERT)
13540 #ifdef FEAT_VREPLACE
13541 if (State & VREPLACE_FLAG)
13543 buf[0] = 'R';
13544 buf[1] = 'v';
13546 else
13547 #endif
13548 if (State & REPLACE_FLAG)
13549 buf[0] = 'R';
13550 else
13551 buf[0] = 'i';
13553 else if (State & CMDLINE)
13555 buf[0] = 'c';
13556 if (exmode_active)
13557 buf[1] = 'v';
13559 else if (exmode_active)
13561 buf[0] = 'c';
13562 buf[1] = 'e';
13564 else
13566 buf[0] = 'n';
13567 if (finish_op)
13568 buf[1] = 'o';
13571 /* Clear out the minor mode when the argument is not a non-zero number or
13572 * non-empty string. */
13573 if (!non_zero_arg(&argvars[0]))
13574 buf[1] = NUL;
13576 rettv->vval.v_string = vim_strsave(buf);
13577 rettv->v_type = VAR_STRING;
13581 * "nextnonblank()" function
13583 static void
13584 f_nextnonblank(argvars, rettv)
13585 typval_T *argvars;
13586 typval_T *rettv;
13588 linenr_T lnum;
13590 for (lnum = get_tv_lnum(argvars); ; ++lnum)
13592 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
13594 lnum = 0;
13595 break;
13597 if (*skipwhite(ml_get(lnum)) != NUL)
13598 break;
13600 rettv->vval.v_number = lnum;
13604 * "nr2char()" function
13606 static void
13607 f_nr2char(argvars, rettv)
13608 typval_T *argvars;
13609 typval_T *rettv;
13611 char_u buf[NUMBUFLEN];
13613 #ifdef FEAT_MBYTE
13614 if (has_mbyte)
13615 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
13616 else
13617 #endif
13619 buf[0] = (char_u)get_tv_number(&argvars[0]);
13620 buf[1] = NUL;
13622 rettv->v_type = VAR_STRING;
13623 rettv->vval.v_string = vim_strsave(buf);
13627 * "pathshorten()" function
13629 static void
13630 f_pathshorten(argvars, rettv)
13631 typval_T *argvars;
13632 typval_T *rettv;
13634 char_u *p;
13636 rettv->v_type = VAR_STRING;
13637 p = get_tv_string_chk(&argvars[0]);
13638 if (p == NULL)
13639 rettv->vval.v_string = NULL;
13640 else
13642 p = vim_strsave(p);
13643 rettv->vval.v_string = p;
13644 if (p != NULL)
13645 shorten_dir(p);
13649 #ifdef FEAT_FLOAT
13651 * "pow()" function
13653 static void
13654 f_pow(argvars, rettv)
13655 typval_T *argvars;
13656 typval_T *rettv;
13658 float_T fx, fy;
13660 rettv->v_type = VAR_FLOAT;
13661 if (get_float_arg(argvars, &fx) == OK
13662 && get_float_arg(&argvars[1], &fy) == OK)
13663 rettv->vval.v_float = pow(fx, fy);
13664 else
13665 rettv->vval.v_float = 0.0;
13667 #endif
13670 * "prevnonblank()" function
13672 static void
13673 f_prevnonblank(argvars, rettv)
13674 typval_T *argvars;
13675 typval_T *rettv;
13677 linenr_T lnum;
13679 lnum = get_tv_lnum(argvars);
13680 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
13681 lnum = 0;
13682 else
13683 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
13684 --lnum;
13685 rettv->vval.v_number = lnum;
13688 #ifdef HAVE_STDARG_H
13689 /* This dummy va_list is here because:
13690 * - passing a NULL pointer doesn't work when va_list isn't a pointer
13691 * - locally in the function results in a "used before set" warning
13692 * - using va_start() to initialize it gives "function with fixed args" error */
13693 static va_list ap;
13694 #endif
13697 * "printf()" function
13699 static void
13700 f_printf(argvars, rettv)
13701 typval_T *argvars;
13702 typval_T *rettv;
13704 rettv->v_type = VAR_STRING;
13705 rettv->vval.v_string = NULL;
13706 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
13708 char_u buf[NUMBUFLEN];
13709 int len;
13710 char_u *s;
13711 int saved_did_emsg = did_emsg;
13712 char *fmt;
13714 /* Get the required length, allocate the buffer and do it for real. */
13715 did_emsg = FALSE;
13716 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
13717 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
13718 if (!did_emsg)
13720 s = alloc(len + 1);
13721 if (s != NULL)
13723 rettv->vval.v_string = s;
13724 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
13727 did_emsg |= saved_did_emsg;
13729 #endif
13733 * "pumvisible()" function
13735 /*ARGSUSED*/
13736 static void
13737 f_pumvisible(argvars, rettv)
13738 typval_T *argvars;
13739 typval_T *rettv;
13741 #ifdef FEAT_INS_EXPAND
13742 if (pum_visible())
13743 rettv->vval.v_number = 1;
13744 #endif
13748 * "range()" function
13750 static void
13751 f_range(argvars, rettv)
13752 typval_T *argvars;
13753 typval_T *rettv;
13755 long start;
13756 long end;
13757 long stride = 1;
13758 long i;
13759 int error = FALSE;
13761 start = get_tv_number_chk(&argvars[0], &error);
13762 if (argvars[1].v_type == VAR_UNKNOWN)
13764 end = start - 1;
13765 start = 0;
13767 else
13769 end = get_tv_number_chk(&argvars[1], &error);
13770 if (argvars[2].v_type != VAR_UNKNOWN)
13771 stride = get_tv_number_chk(&argvars[2], &error);
13774 if (error)
13775 return; /* type error; errmsg already given */
13776 if (stride == 0)
13777 EMSG(_("E726: Stride is zero"));
13778 else if (stride > 0 ? end + 1 < start : end - 1 > start)
13779 EMSG(_("E727: Start past end"));
13780 else
13782 if (rettv_list_alloc(rettv) == OK)
13783 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
13784 if (list_append_number(rettv->vval.v_list,
13785 (varnumber_T)i) == FAIL)
13786 break;
13791 * "readfile()" function
13793 static void
13794 f_readfile(argvars, rettv)
13795 typval_T *argvars;
13796 typval_T *rettv;
13798 int binary = FALSE;
13799 char_u *fname;
13800 FILE *fd;
13801 listitem_T *li;
13802 #define FREAD_SIZE 200 /* optimized for text lines */
13803 char_u buf[FREAD_SIZE];
13804 int readlen; /* size of last fread() */
13805 int buflen; /* nr of valid chars in buf[] */
13806 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
13807 int tolist; /* first byte in buf[] still to be put in list */
13808 int chop; /* how many CR to chop off */
13809 char_u *prev = NULL; /* previously read bytes, if any */
13810 int prevlen = 0; /* length of "prev" if not NULL */
13811 char_u *s;
13812 int len;
13813 long maxline = MAXLNUM;
13814 long cnt = 0;
13816 if (argvars[1].v_type != VAR_UNKNOWN)
13818 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
13819 binary = TRUE;
13820 if (argvars[2].v_type != VAR_UNKNOWN)
13821 maxline = get_tv_number(&argvars[2]);
13824 if (rettv_list_alloc(rettv) == FAIL)
13825 return;
13827 /* Always open the file in binary mode, library functions have a mind of
13828 * their own about CR-LF conversion. */
13829 fname = get_tv_string(&argvars[0]);
13830 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
13832 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
13833 return;
13836 filtd = 0;
13837 while (cnt < maxline || maxline < 0)
13839 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
13840 buflen = filtd + readlen;
13841 tolist = 0;
13842 for ( ; filtd < buflen || readlen <= 0; ++filtd)
13844 if (buf[filtd] == '\n' || readlen <= 0)
13846 /* Only when in binary mode add an empty list item when the
13847 * last line ends in a '\n'. */
13848 if (!binary && readlen == 0 && filtd == 0)
13849 break;
13851 /* Found end-of-line or end-of-file: add a text line to the
13852 * list. */
13853 chop = 0;
13854 if (!binary)
13855 while (filtd - chop - 1 >= tolist
13856 && buf[filtd - chop - 1] == '\r')
13857 ++chop;
13858 len = filtd - tolist - chop;
13859 if (prev == NULL)
13860 s = vim_strnsave(buf + tolist, len);
13861 else
13863 s = alloc((unsigned)(prevlen + len + 1));
13864 if (s != NULL)
13866 mch_memmove(s, prev, prevlen);
13867 vim_free(prev);
13868 prev = NULL;
13869 mch_memmove(s + prevlen, buf + tolist, len);
13870 s[prevlen + len] = NUL;
13873 tolist = filtd + 1;
13875 li = listitem_alloc();
13876 if (li == NULL)
13878 vim_free(s);
13879 break;
13881 li->li_tv.v_type = VAR_STRING;
13882 li->li_tv.v_lock = 0;
13883 li->li_tv.vval.v_string = s;
13884 list_append(rettv->vval.v_list, li);
13886 if (++cnt >= maxline && maxline >= 0)
13887 break;
13888 if (readlen <= 0)
13889 break;
13891 else if (buf[filtd] == NUL)
13892 buf[filtd] = '\n';
13894 if (readlen <= 0)
13895 break;
13897 if (tolist == 0)
13899 /* "buf" is full, need to move text to an allocated buffer */
13900 if (prev == NULL)
13902 prev = vim_strnsave(buf, buflen);
13903 prevlen = buflen;
13905 else
13907 s = alloc((unsigned)(prevlen + buflen));
13908 if (s != NULL)
13910 mch_memmove(s, prev, prevlen);
13911 mch_memmove(s + prevlen, buf, buflen);
13912 vim_free(prev);
13913 prev = s;
13914 prevlen += buflen;
13917 filtd = 0;
13919 else
13921 mch_memmove(buf, buf + tolist, buflen - tolist);
13922 filtd -= tolist;
13927 * For a negative line count use only the lines at the end of the file,
13928 * free the rest.
13930 if (maxline < 0)
13931 while (cnt > -maxline)
13933 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
13934 --cnt;
13937 vim_free(prev);
13938 fclose(fd);
13941 #if defined(FEAT_RELTIME)
13942 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
13945 * Convert a List to proftime_T.
13946 * Return FAIL when there is something wrong.
13948 static int
13949 list2proftime(arg, tm)
13950 typval_T *arg;
13951 proftime_T *tm;
13953 long n1, n2;
13954 int error = FALSE;
13956 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
13957 || arg->vval.v_list->lv_len != 2)
13958 return FAIL;
13959 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
13960 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
13961 # ifdef WIN3264
13962 tm->HighPart = n1;
13963 tm->LowPart = n2;
13964 # else
13965 tm->tv_sec = n1;
13966 tm->tv_usec = n2;
13967 # endif
13968 return error ? FAIL : OK;
13970 #endif /* FEAT_RELTIME */
13973 * "reltime()" function
13975 static void
13976 f_reltime(argvars, rettv)
13977 typval_T *argvars;
13978 typval_T *rettv;
13980 #ifdef FEAT_RELTIME
13981 proftime_T res;
13982 proftime_T start;
13984 if (argvars[0].v_type == VAR_UNKNOWN)
13986 /* No arguments: get current time. */
13987 profile_start(&res);
13989 else if (argvars[1].v_type == VAR_UNKNOWN)
13991 if (list2proftime(&argvars[0], &res) == FAIL)
13992 return;
13993 profile_end(&res);
13995 else
13997 /* Two arguments: compute the difference. */
13998 if (list2proftime(&argvars[0], &start) == FAIL
13999 || list2proftime(&argvars[1], &res) == FAIL)
14000 return;
14001 profile_sub(&res, &start);
14004 if (rettv_list_alloc(rettv) == OK)
14006 long n1, n2;
14008 # ifdef WIN3264
14009 n1 = res.HighPart;
14010 n2 = res.LowPart;
14011 # else
14012 n1 = res.tv_sec;
14013 n2 = res.tv_usec;
14014 # endif
14015 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
14016 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
14018 #endif
14022 * "reltimestr()" function
14024 static void
14025 f_reltimestr(argvars, rettv)
14026 typval_T *argvars;
14027 typval_T *rettv;
14029 #ifdef FEAT_RELTIME
14030 proftime_T tm;
14031 #endif
14033 rettv->v_type = VAR_STRING;
14034 rettv->vval.v_string = NULL;
14035 #ifdef FEAT_RELTIME
14036 if (list2proftime(&argvars[0], &tm) == OK)
14037 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
14038 #endif
14041 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
14042 static void make_connection __ARGS((void));
14043 static int check_connection __ARGS((void));
14045 static void
14046 make_connection()
14048 if (X_DISPLAY == NULL
14049 # ifdef FEAT_GUI
14050 && !gui.in_use
14051 # endif
14054 x_force_connect = TRUE;
14055 setup_term_clip();
14056 x_force_connect = FALSE;
14060 static int
14061 check_connection()
14063 make_connection();
14064 if (X_DISPLAY == NULL)
14066 EMSG(_("E240: No connection to Vim server"));
14067 return FAIL;
14069 return OK;
14071 #endif
14073 #ifdef FEAT_CLIENTSERVER
14074 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
14076 static void
14077 remote_common(argvars, rettv, expr)
14078 typval_T *argvars;
14079 typval_T *rettv;
14080 int expr;
14082 char_u *server_name;
14083 char_u *keys;
14084 char_u *r = NULL;
14085 char_u buf[NUMBUFLEN];
14086 # ifdef WIN32
14087 HWND w;
14088 # else
14089 Window w;
14090 # endif
14092 if (check_restricted() || check_secure())
14093 return;
14095 # ifdef FEAT_X11
14096 if (check_connection() == FAIL)
14097 return;
14098 # endif
14100 server_name = get_tv_string_chk(&argvars[0]);
14101 if (server_name == NULL)
14102 return; /* type error; errmsg already given */
14103 keys = get_tv_string_buf(&argvars[1], buf);
14104 # ifdef WIN32
14105 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14106 # else
14107 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
14108 < 0)
14109 # endif
14111 if (r != NULL)
14112 EMSG(r); /* sending worked but evaluation failed */
14113 else
14114 EMSG2(_("E241: Unable to send to %s"), server_name);
14115 return;
14118 rettv->vval.v_string = r;
14120 if (argvars[2].v_type != VAR_UNKNOWN)
14122 dictitem_T v;
14123 char_u str[30];
14124 char_u *idvar;
14126 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
14127 v.di_tv.v_type = VAR_STRING;
14128 v.di_tv.vval.v_string = vim_strsave(str);
14129 idvar = get_tv_string_chk(&argvars[2]);
14130 if (idvar != NULL)
14131 set_var(idvar, &v.di_tv, FALSE);
14132 vim_free(v.di_tv.vval.v_string);
14135 #endif
14138 * "remote_expr()" function
14140 /*ARGSUSED*/
14141 static void
14142 f_remote_expr(argvars, rettv)
14143 typval_T *argvars;
14144 typval_T *rettv;
14146 rettv->v_type = VAR_STRING;
14147 rettv->vval.v_string = NULL;
14148 #ifdef FEAT_CLIENTSERVER
14149 remote_common(argvars, rettv, TRUE);
14150 #endif
14154 * "remote_foreground()" function
14156 /*ARGSUSED*/
14157 static void
14158 f_remote_foreground(argvars, rettv)
14159 typval_T *argvars;
14160 typval_T *rettv;
14162 #ifdef FEAT_CLIENTSERVER
14163 # ifdef WIN32
14164 /* On Win32 it's done in this application. */
14166 char_u *server_name = get_tv_string_chk(&argvars[0]);
14168 if (server_name != NULL)
14169 serverForeground(server_name);
14171 # else
14172 /* Send a foreground() expression to the server. */
14173 argvars[1].v_type = VAR_STRING;
14174 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
14175 argvars[2].v_type = VAR_UNKNOWN;
14176 remote_common(argvars, rettv, TRUE);
14177 vim_free(argvars[1].vval.v_string);
14178 # endif
14179 #endif
14182 /*ARGSUSED*/
14183 static void
14184 f_remote_peek(argvars, rettv)
14185 typval_T *argvars;
14186 typval_T *rettv;
14188 #ifdef FEAT_CLIENTSERVER
14189 dictitem_T v;
14190 char_u *s = NULL;
14191 # ifdef WIN32
14192 long_u n = 0;
14193 # endif
14194 char_u *serverid;
14196 if (check_restricted() || check_secure())
14198 rettv->vval.v_number = -1;
14199 return;
14201 serverid = get_tv_string_chk(&argvars[0]);
14202 if (serverid == NULL)
14204 rettv->vval.v_number = -1;
14205 return; /* type error; errmsg already given */
14207 # ifdef WIN32
14208 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14209 if (n == 0)
14210 rettv->vval.v_number = -1;
14211 else
14213 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
14214 rettv->vval.v_number = (s != NULL);
14216 # else
14217 if (check_connection() == FAIL)
14218 return;
14220 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
14221 serverStrToWin(serverid), &s);
14222 # endif
14224 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
14226 char_u *retvar;
14228 v.di_tv.v_type = VAR_STRING;
14229 v.di_tv.vval.v_string = vim_strsave(s);
14230 retvar = get_tv_string_chk(&argvars[1]);
14231 if (retvar != NULL)
14232 set_var(retvar, &v.di_tv, FALSE);
14233 vim_free(v.di_tv.vval.v_string);
14235 #else
14236 rettv->vval.v_number = -1;
14237 #endif
14240 /*ARGSUSED*/
14241 static void
14242 f_remote_read(argvars, rettv)
14243 typval_T *argvars;
14244 typval_T *rettv;
14246 char_u *r = NULL;
14248 #ifdef FEAT_CLIENTSERVER
14249 char_u *serverid = get_tv_string_chk(&argvars[0]);
14251 if (serverid != NULL && !check_restricted() && !check_secure())
14253 # ifdef WIN32
14254 /* The server's HWND is encoded in the 'id' parameter */
14255 long_u n = 0;
14257 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14258 if (n != 0)
14259 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
14260 if (r == NULL)
14261 # else
14262 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
14263 serverStrToWin(serverid), &r, FALSE) < 0)
14264 # endif
14265 EMSG(_("E277: Unable to read a server reply"));
14267 #endif
14268 rettv->v_type = VAR_STRING;
14269 rettv->vval.v_string = r;
14273 * "remote_send()" function
14275 /*ARGSUSED*/
14276 static void
14277 f_remote_send(argvars, rettv)
14278 typval_T *argvars;
14279 typval_T *rettv;
14281 rettv->v_type = VAR_STRING;
14282 rettv->vval.v_string = NULL;
14283 #ifdef FEAT_CLIENTSERVER
14284 remote_common(argvars, rettv, FALSE);
14285 #endif
14289 * "remove()" function
14291 static void
14292 f_remove(argvars, rettv)
14293 typval_T *argvars;
14294 typval_T *rettv;
14296 list_T *l;
14297 listitem_T *item, *item2;
14298 listitem_T *li;
14299 long idx;
14300 long end;
14301 char_u *key;
14302 dict_T *d;
14303 dictitem_T *di;
14305 if (argvars[0].v_type == VAR_DICT)
14307 if (argvars[2].v_type != VAR_UNKNOWN)
14308 EMSG2(_(e_toomanyarg), "remove()");
14309 else if ((d = argvars[0].vval.v_dict) != NULL
14310 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
14312 key = get_tv_string_chk(&argvars[1]);
14313 if (key != NULL)
14315 di = dict_find(d, key, -1);
14316 if (di == NULL)
14317 EMSG2(_(e_dictkey), key);
14318 else
14320 *rettv = di->di_tv;
14321 init_tv(&di->di_tv);
14322 dictitem_remove(d, di);
14327 else if (argvars[0].v_type != VAR_LIST)
14328 EMSG2(_(e_listdictarg), "remove()");
14329 else if ((l = argvars[0].vval.v_list) != NULL
14330 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
14332 int error = FALSE;
14334 idx = get_tv_number_chk(&argvars[1], &error);
14335 if (error)
14336 ; /* type error: do nothing, errmsg already given */
14337 else if ((item = list_find(l, idx)) == NULL)
14338 EMSGN(_(e_listidx), idx);
14339 else
14341 if (argvars[2].v_type == VAR_UNKNOWN)
14343 /* Remove one item, return its value. */
14344 list_remove(l, item, item);
14345 *rettv = item->li_tv;
14346 vim_free(item);
14348 else
14350 /* Remove range of items, return list with values. */
14351 end = get_tv_number_chk(&argvars[2], &error);
14352 if (error)
14353 ; /* type error: do nothing */
14354 else if ((item2 = list_find(l, end)) == NULL)
14355 EMSGN(_(e_listidx), end);
14356 else
14358 int cnt = 0;
14360 for (li = item; li != NULL; li = li->li_next)
14362 ++cnt;
14363 if (li == item2)
14364 break;
14366 if (li == NULL) /* didn't find "item2" after "item" */
14367 EMSG(_(e_invrange));
14368 else
14370 list_remove(l, item, item2);
14371 if (rettv_list_alloc(rettv) == OK)
14373 l = rettv->vval.v_list;
14374 l->lv_first = item;
14375 l->lv_last = item2;
14376 item->li_prev = NULL;
14377 item2->li_next = NULL;
14378 l->lv_len = cnt;
14388 * "rename({from}, {to})" function
14390 static void
14391 f_rename(argvars, rettv)
14392 typval_T *argvars;
14393 typval_T *rettv;
14395 char_u buf[NUMBUFLEN];
14397 if (check_restricted() || check_secure())
14398 rettv->vval.v_number = -1;
14399 else
14400 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
14401 get_tv_string_buf(&argvars[1], buf));
14405 * "repeat()" function
14407 /*ARGSUSED*/
14408 static void
14409 f_repeat(argvars, rettv)
14410 typval_T *argvars;
14411 typval_T *rettv;
14413 char_u *p;
14414 int n;
14415 int slen;
14416 int len;
14417 char_u *r;
14418 int i;
14420 n = get_tv_number(&argvars[1]);
14421 if (argvars[0].v_type == VAR_LIST)
14423 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
14424 while (n-- > 0)
14425 if (list_extend(rettv->vval.v_list,
14426 argvars[0].vval.v_list, NULL) == FAIL)
14427 break;
14429 else
14431 p = get_tv_string(&argvars[0]);
14432 rettv->v_type = VAR_STRING;
14433 rettv->vval.v_string = NULL;
14435 slen = (int)STRLEN(p);
14436 len = slen * n;
14437 if (len <= 0)
14438 return;
14440 r = alloc(len + 1);
14441 if (r != NULL)
14443 for (i = 0; i < n; i++)
14444 mch_memmove(r + i * slen, p, (size_t)slen);
14445 r[len] = NUL;
14448 rettv->vval.v_string = r;
14453 * "resolve()" function
14455 static void
14456 f_resolve(argvars, rettv)
14457 typval_T *argvars;
14458 typval_T *rettv;
14460 char_u *p;
14462 p = get_tv_string(&argvars[0]);
14463 #ifdef FEAT_SHORTCUT
14465 char_u *v = NULL;
14467 v = mch_resolve_shortcut(p);
14468 if (v != NULL)
14469 rettv->vval.v_string = v;
14470 else
14471 rettv->vval.v_string = vim_strsave(p);
14473 #else
14474 # ifdef HAVE_READLINK
14476 char_u buf[MAXPATHL + 1];
14477 char_u *cpy;
14478 int len;
14479 char_u *remain = NULL;
14480 char_u *q;
14481 int is_relative_to_current = FALSE;
14482 int has_trailing_pathsep = FALSE;
14483 int limit = 100;
14485 p = vim_strsave(p);
14487 if (p[0] == '.' && (vim_ispathsep(p[1])
14488 || (p[1] == '.' && (vim_ispathsep(p[2])))))
14489 is_relative_to_current = TRUE;
14491 len = STRLEN(p);
14492 if (len > 0 && after_pathsep(p, p + len))
14493 has_trailing_pathsep = TRUE;
14495 q = getnextcomp(p);
14496 if (*q != NUL)
14498 /* Separate the first path component in "p", and keep the
14499 * remainder (beginning with the path separator). */
14500 remain = vim_strsave(q - 1);
14501 q[-1] = NUL;
14504 for (;;)
14506 for (;;)
14508 len = readlink((char *)p, (char *)buf, MAXPATHL);
14509 if (len <= 0)
14510 break;
14511 buf[len] = NUL;
14513 if (limit-- == 0)
14515 vim_free(p);
14516 vim_free(remain);
14517 EMSG(_("E655: Too many symbolic links (cycle?)"));
14518 rettv->vval.v_string = NULL;
14519 goto fail;
14522 /* Ensure that the result will have a trailing path separator
14523 * if the argument has one. */
14524 if (remain == NULL && has_trailing_pathsep)
14525 add_pathsep(buf);
14527 /* Separate the first path component in the link value and
14528 * concatenate the remainders. */
14529 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
14530 if (*q != NUL)
14532 if (remain == NULL)
14533 remain = vim_strsave(q - 1);
14534 else
14536 cpy = concat_str(q - 1, remain);
14537 if (cpy != NULL)
14539 vim_free(remain);
14540 remain = cpy;
14543 q[-1] = NUL;
14546 q = gettail(p);
14547 if (q > p && *q == NUL)
14549 /* Ignore trailing path separator. */
14550 q[-1] = NUL;
14551 q = gettail(p);
14553 if (q > p && !mch_isFullName(buf))
14555 /* symlink is relative to directory of argument */
14556 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
14557 if (cpy != NULL)
14559 STRCPY(cpy, p);
14560 STRCPY(gettail(cpy), buf);
14561 vim_free(p);
14562 p = cpy;
14565 else
14567 vim_free(p);
14568 p = vim_strsave(buf);
14572 if (remain == NULL)
14573 break;
14575 /* Append the first path component of "remain" to "p". */
14576 q = getnextcomp(remain + 1);
14577 len = q - remain - (*q != NUL);
14578 cpy = vim_strnsave(p, STRLEN(p) + len);
14579 if (cpy != NULL)
14581 STRNCAT(cpy, remain, len);
14582 vim_free(p);
14583 p = cpy;
14585 /* Shorten "remain". */
14586 if (*q != NUL)
14587 STRMOVE(remain, q - 1);
14588 else
14590 vim_free(remain);
14591 remain = NULL;
14595 /* If the result is a relative path name, make it explicitly relative to
14596 * the current directory if and only if the argument had this form. */
14597 if (!vim_ispathsep(*p))
14599 if (is_relative_to_current
14600 && *p != NUL
14601 && !(p[0] == '.'
14602 && (p[1] == NUL
14603 || vim_ispathsep(p[1])
14604 || (p[1] == '.'
14605 && (p[2] == NUL
14606 || vim_ispathsep(p[2]))))))
14608 /* Prepend "./". */
14609 cpy = concat_str((char_u *)"./", p);
14610 if (cpy != NULL)
14612 vim_free(p);
14613 p = cpy;
14616 else if (!is_relative_to_current)
14618 /* Strip leading "./". */
14619 q = p;
14620 while (q[0] == '.' && vim_ispathsep(q[1]))
14621 q += 2;
14622 if (q > p)
14623 STRMOVE(p, p + 2);
14627 /* Ensure that the result will have no trailing path separator
14628 * if the argument had none. But keep "/" or "//". */
14629 if (!has_trailing_pathsep)
14631 q = p + STRLEN(p);
14632 if (after_pathsep(p, q))
14633 *gettail_sep(p) = NUL;
14636 rettv->vval.v_string = p;
14638 # else
14639 rettv->vval.v_string = vim_strsave(p);
14640 # endif
14641 #endif
14643 simplify_filename(rettv->vval.v_string);
14645 #ifdef HAVE_READLINK
14646 fail:
14647 #endif
14648 rettv->v_type = VAR_STRING;
14652 * "reverse({list})" function
14654 static void
14655 f_reverse(argvars, rettv)
14656 typval_T *argvars;
14657 typval_T *rettv;
14659 list_T *l;
14660 listitem_T *li, *ni;
14662 if (argvars[0].v_type != VAR_LIST)
14663 EMSG2(_(e_listarg), "reverse()");
14664 else if ((l = argvars[0].vval.v_list) != NULL
14665 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
14667 li = l->lv_last;
14668 l->lv_first = l->lv_last = NULL;
14669 l->lv_len = 0;
14670 while (li != NULL)
14672 ni = li->li_prev;
14673 list_append(l, li);
14674 li = ni;
14676 rettv->vval.v_list = l;
14677 rettv->v_type = VAR_LIST;
14678 ++l->lv_refcount;
14679 l->lv_idx = l->lv_len - l->lv_idx - 1;
14683 #define SP_NOMOVE 0x01 /* don't move cursor */
14684 #define SP_REPEAT 0x02 /* repeat to find outer pair */
14685 #define SP_RETCOUNT 0x04 /* return matchcount */
14686 #define SP_SETPCMARK 0x08 /* set previous context mark */
14687 #define SP_START 0x10 /* accept match at start position */
14688 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
14689 #define SP_END 0x40 /* leave cursor at end of match */
14691 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
14694 * Get flags for a search function.
14695 * Possibly sets "p_ws".
14696 * Returns BACKWARD, FORWARD or zero (for an error).
14698 static int
14699 get_search_arg(varp, flagsp)
14700 typval_T *varp;
14701 int *flagsp;
14703 int dir = FORWARD;
14704 char_u *flags;
14705 char_u nbuf[NUMBUFLEN];
14706 int mask;
14708 if (varp->v_type != VAR_UNKNOWN)
14710 flags = get_tv_string_buf_chk(varp, nbuf);
14711 if (flags == NULL)
14712 return 0; /* type error; errmsg already given */
14713 while (*flags != NUL)
14715 switch (*flags)
14717 case 'b': dir = BACKWARD; break;
14718 case 'w': p_ws = TRUE; break;
14719 case 'W': p_ws = FALSE; break;
14720 default: mask = 0;
14721 if (flagsp != NULL)
14722 switch (*flags)
14724 case 'c': mask = SP_START; break;
14725 case 'e': mask = SP_END; break;
14726 case 'm': mask = SP_RETCOUNT; break;
14727 case 'n': mask = SP_NOMOVE; break;
14728 case 'p': mask = SP_SUBPAT; break;
14729 case 'r': mask = SP_REPEAT; break;
14730 case 's': mask = SP_SETPCMARK; break;
14732 if (mask == 0)
14734 EMSG2(_(e_invarg2), flags);
14735 dir = 0;
14737 else
14738 *flagsp |= mask;
14740 if (dir == 0)
14741 break;
14742 ++flags;
14745 return dir;
14749 * Shared by search() and searchpos() functions
14751 static int
14752 search_cmn(argvars, match_pos, flagsp)
14753 typval_T *argvars;
14754 pos_T *match_pos;
14755 int *flagsp;
14757 int flags;
14758 char_u *pat;
14759 pos_T pos;
14760 pos_T save_cursor;
14761 int save_p_ws = p_ws;
14762 int dir;
14763 int retval = 0; /* default: FAIL */
14764 long lnum_stop = 0;
14765 proftime_T tm;
14766 #ifdef FEAT_RELTIME
14767 long time_limit = 0;
14768 #endif
14769 int options = SEARCH_KEEP;
14770 int subpatnum;
14772 pat = get_tv_string(&argvars[0]);
14773 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
14774 if (dir == 0)
14775 goto theend;
14776 flags = *flagsp;
14777 if (flags & SP_START)
14778 options |= SEARCH_START;
14779 if (flags & SP_END)
14780 options |= SEARCH_END;
14782 /* Optional arguments: line number to stop searching and timeout. */
14783 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
14785 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
14786 if (lnum_stop < 0)
14787 goto theend;
14788 #ifdef FEAT_RELTIME
14789 if (argvars[3].v_type != VAR_UNKNOWN)
14791 time_limit = get_tv_number_chk(&argvars[3], NULL);
14792 if (time_limit < 0)
14793 goto theend;
14795 #endif
14798 #ifdef FEAT_RELTIME
14799 /* Set the time limit, if there is one. */
14800 profile_setlimit(time_limit, &tm);
14801 #endif
14804 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
14805 * Check to make sure only those flags are set.
14806 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
14807 * flags cannot be set. Check for that condition also.
14809 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
14810 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14812 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
14813 goto theend;
14816 pos = save_cursor = curwin->w_cursor;
14817 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14818 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
14819 if (subpatnum != FAIL)
14821 if (flags & SP_SUBPAT)
14822 retval = subpatnum;
14823 else
14824 retval = pos.lnum;
14825 if (flags & SP_SETPCMARK)
14826 setpcmark();
14827 curwin->w_cursor = pos;
14828 if (match_pos != NULL)
14830 /* Store the match cursor position */
14831 match_pos->lnum = pos.lnum;
14832 match_pos->col = pos.col + 1;
14834 /* "/$" will put the cursor after the end of the line, may need to
14835 * correct that here */
14836 check_cursor();
14839 /* If 'n' flag is used: restore cursor position. */
14840 if (flags & SP_NOMOVE)
14841 curwin->w_cursor = save_cursor;
14842 else
14843 curwin->w_set_curswant = TRUE;
14844 theend:
14845 p_ws = save_p_ws;
14847 return retval;
14850 #ifdef FEAT_FLOAT
14852 * "round({float})" function
14854 static void
14855 f_round(argvars, rettv)
14856 typval_T *argvars;
14857 typval_T *rettv;
14859 float_T f;
14861 rettv->v_type = VAR_FLOAT;
14862 if (get_float_arg(argvars, &f) == OK)
14863 /* round() is not in C90, use ceil() or floor() instead. */
14864 rettv->vval.v_float = f > 0 ? floor(f + 0.5) : ceil(f - 0.5);
14865 else
14866 rettv->vval.v_float = 0.0;
14868 #endif
14871 * "search()" function
14873 static void
14874 f_search(argvars, rettv)
14875 typval_T *argvars;
14876 typval_T *rettv;
14878 int flags = 0;
14880 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
14884 * "searchdecl()" function
14886 static void
14887 f_searchdecl(argvars, rettv)
14888 typval_T *argvars;
14889 typval_T *rettv;
14891 int locally = 1;
14892 int thisblock = 0;
14893 int error = FALSE;
14894 char_u *name;
14896 rettv->vval.v_number = 1; /* default: FAIL */
14898 name = get_tv_string_chk(&argvars[0]);
14899 if (argvars[1].v_type != VAR_UNKNOWN)
14901 locally = get_tv_number_chk(&argvars[1], &error) == 0;
14902 if (!error && argvars[2].v_type != VAR_UNKNOWN)
14903 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
14905 if (!error && name != NULL)
14906 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
14907 locally, thisblock, SEARCH_KEEP) == FAIL;
14911 * Used by searchpair() and searchpairpos()
14913 static int
14914 searchpair_cmn(argvars, match_pos)
14915 typval_T *argvars;
14916 pos_T *match_pos;
14918 char_u *spat, *mpat, *epat;
14919 char_u *skip;
14920 int save_p_ws = p_ws;
14921 int dir;
14922 int flags = 0;
14923 char_u nbuf1[NUMBUFLEN];
14924 char_u nbuf2[NUMBUFLEN];
14925 char_u nbuf3[NUMBUFLEN];
14926 int retval = 0; /* default: FAIL */
14927 long lnum_stop = 0;
14928 long time_limit = 0;
14930 /* Get the three pattern arguments: start, middle, end. */
14931 spat = get_tv_string_chk(&argvars[0]);
14932 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
14933 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
14934 if (spat == NULL || mpat == NULL || epat == NULL)
14935 goto theend; /* type error */
14937 /* Handle the optional fourth argument: flags */
14938 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
14939 if (dir == 0)
14940 goto theend;
14942 /* Don't accept SP_END or SP_SUBPAT.
14943 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
14945 if ((flags & (SP_END | SP_SUBPAT)) != 0
14946 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14948 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
14949 goto theend;
14952 /* Using 'r' implies 'W', otherwise it doesn't work. */
14953 if (flags & SP_REPEAT)
14954 p_ws = FALSE;
14956 /* Optional fifth argument: skip expression */
14957 if (argvars[3].v_type == VAR_UNKNOWN
14958 || argvars[4].v_type == VAR_UNKNOWN)
14959 skip = (char_u *)"";
14960 else
14962 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
14963 if (argvars[5].v_type != VAR_UNKNOWN)
14965 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
14966 if (lnum_stop < 0)
14967 goto theend;
14968 #ifdef FEAT_RELTIME
14969 if (argvars[6].v_type != VAR_UNKNOWN)
14971 time_limit = get_tv_number_chk(&argvars[6], NULL);
14972 if (time_limit < 0)
14973 goto theend;
14975 #endif
14978 if (skip == NULL)
14979 goto theend; /* type error */
14981 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
14982 match_pos, lnum_stop, time_limit);
14984 theend:
14985 p_ws = save_p_ws;
14987 return retval;
14991 * "searchpair()" function
14993 static void
14994 f_searchpair(argvars, rettv)
14995 typval_T *argvars;
14996 typval_T *rettv;
14998 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
15002 * "searchpairpos()" function
15004 static void
15005 f_searchpairpos(argvars, rettv)
15006 typval_T *argvars;
15007 typval_T *rettv;
15009 pos_T match_pos;
15010 int lnum = 0;
15011 int col = 0;
15013 if (rettv_list_alloc(rettv) == FAIL)
15014 return;
15016 if (searchpair_cmn(argvars, &match_pos) > 0)
15018 lnum = match_pos.lnum;
15019 col = match_pos.col;
15022 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15023 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15027 * Search for a start/middle/end thing.
15028 * Used by searchpair(), see its documentation for the details.
15029 * Returns 0 or -1 for no match,
15031 long
15032 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
15033 lnum_stop, time_limit)
15034 char_u *spat; /* start pattern */
15035 char_u *mpat; /* middle pattern */
15036 char_u *epat; /* end pattern */
15037 int dir; /* BACKWARD or FORWARD */
15038 char_u *skip; /* skip expression */
15039 int flags; /* SP_SETPCMARK and other SP_ values */
15040 pos_T *match_pos;
15041 linenr_T lnum_stop; /* stop at this line if not zero */
15042 long time_limit; /* stop after this many msec */
15044 char_u *save_cpo;
15045 char_u *pat, *pat2 = NULL, *pat3 = NULL;
15046 long retval = 0;
15047 pos_T pos;
15048 pos_T firstpos;
15049 pos_T foundpos;
15050 pos_T save_cursor;
15051 pos_T save_pos;
15052 int n;
15053 int r;
15054 int nest = 1;
15055 int err;
15056 int options = SEARCH_KEEP;
15057 proftime_T tm;
15059 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15060 save_cpo = p_cpo;
15061 p_cpo = empty_option;
15063 #ifdef FEAT_RELTIME
15064 /* Set the time limit, if there is one. */
15065 profile_setlimit(time_limit, &tm);
15066 #endif
15068 /* Make two search patterns: start/end (pat2, for in nested pairs) and
15069 * start/middle/end (pat3, for the top pair). */
15070 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
15071 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
15072 if (pat2 == NULL || pat3 == NULL)
15073 goto theend;
15074 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
15075 if (*mpat == NUL)
15076 STRCPY(pat3, pat2);
15077 else
15078 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
15079 spat, epat, mpat);
15080 if (flags & SP_START)
15081 options |= SEARCH_START;
15083 save_cursor = curwin->w_cursor;
15084 pos = curwin->w_cursor;
15085 clearpos(&firstpos);
15086 clearpos(&foundpos);
15087 pat = pat3;
15088 for (;;)
15090 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15091 options, RE_SEARCH, lnum_stop, &tm);
15092 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
15093 /* didn't find it or found the first match again: FAIL */
15094 break;
15096 if (firstpos.lnum == 0)
15097 firstpos = pos;
15098 if (equalpos(pos, foundpos))
15100 /* Found the same position again. Can happen with a pattern that
15101 * has "\zs" at the end and searching backwards. Advance one
15102 * character and try again. */
15103 if (dir == BACKWARD)
15104 decl(&pos);
15105 else
15106 incl(&pos);
15108 foundpos = pos;
15110 /* clear the start flag to avoid getting stuck here */
15111 options &= ~SEARCH_START;
15113 /* If the skip pattern matches, ignore this match. */
15114 if (*skip != NUL)
15116 save_pos = curwin->w_cursor;
15117 curwin->w_cursor = pos;
15118 r = eval_to_bool(skip, &err, NULL, FALSE);
15119 curwin->w_cursor = save_pos;
15120 if (err)
15122 /* Evaluating {skip} caused an error, break here. */
15123 curwin->w_cursor = save_cursor;
15124 retval = -1;
15125 break;
15127 if (r)
15128 continue;
15131 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
15133 /* Found end when searching backwards or start when searching
15134 * forward: nested pair. */
15135 ++nest;
15136 pat = pat2; /* nested, don't search for middle */
15138 else
15140 /* Found end when searching forward or start when searching
15141 * backward: end of (nested) pair; or found middle in outer pair. */
15142 if (--nest == 1)
15143 pat = pat3; /* outer level, search for middle */
15146 if (nest == 0)
15148 /* Found the match: return matchcount or line number. */
15149 if (flags & SP_RETCOUNT)
15150 ++retval;
15151 else
15152 retval = pos.lnum;
15153 if (flags & SP_SETPCMARK)
15154 setpcmark();
15155 curwin->w_cursor = pos;
15156 if (!(flags & SP_REPEAT))
15157 break;
15158 nest = 1; /* search for next unmatched */
15162 if (match_pos != NULL)
15164 /* Store the match cursor position */
15165 match_pos->lnum = curwin->w_cursor.lnum;
15166 match_pos->col = curwin->w_cursor.col + 1;
15169 /* If 'n' flag is used or search failed: restore cursor position. */
15170 if ((flags & SP_NOMOVE) || retval == 0)
15171 curwin->w_cursor = save_cursor;
15173 theend:
15174 vim_free(pat2);
15175 vim_free(pat3);
15176 if (p_cpo == empty_option)
15177 p_cpo = save_cpo;
15178 else
15179 /* Darn, evaluating the {skip} expression changed the value. */
15180 free_string_option(save_cpo);
15182 return retval;
15186 * "searchpos()" function
15188 static void
15189 f_searchpos(argvars, rettv)
15190 typval_T *argvars;
15191 typval_T *rettv;
15193 pos_T match_pos;
15194 int lnum = 0;
15195 int col = 0;
15196 int n;
15197 int flags = 0;
15199 if (rettv_list_alloc(rettv) == FAIL)
15200 return;
15202 n = search_cmn(argvars, &match_pos, &flags);
15203 if (n > 0)
15205 lnum = match_pos.lnum;
15206 col = match_pos.col;
15209 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15210 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15211 if (flags & SP_SUBPAT)
15212 list_append_number(rettv->vval.v_list, (varnumber_T)n);
15216 /*ARGSUSED*/
15217 static void
15218 f_server2client(argvars, rettv)
15219 typval_T *argvars;
15220 typval_T *rettv;
15222 #ifdef FEAT_CLIENTSERVER
15223 char_u buf[NUMBUFLEN];
15224 char_u *server = get_tv_string_chk(&argvars[0]);
15225 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
15227 rettv->vval.v_number = -1;
15228 if (server == NULL || reply == NULL)
15229 return;
15230 if (check_restricted() || check_secure())
15231 return;
15232 # ifdef FEAT_X11
15233 if (check_connection() == FAIL)
15234 return;
15235 # endif
15237 if (serverSendReply(server, reply) < 0)
15239 EMSG(_("E258: Unable to send to client"));
15240 return;
15242 rettv->vval.v_number = 0;
15243 #else
15244 rettv->vval.v_number = -1;
15245 #endif
15248 /*ARGSUSED*/
15249 static void
15250 f_serverlist(argvars, rettv)
15251 typval_T *argvars;
15252 typval_T *rettv;
15254 char_u *r = NULL;
15256 #ifdef FEAT_CLIENTSERVER
15257 # ifdef WIN32
15258 r = serverGetVimNames();
15259 # else
15260 make_connection();
15261 if (X_DISPLAY != NULL)
15262 r = serverGetVimNames(X_DISPLAY);
15263 # endif
15264 #endif
15265 rettv->v_type = VAR_STRING;
15266 rettv->vval.v_string = r;
15270 * "setbufvar()" function
15272 /*ARGSUSED*/
15273 static void
15274 f_setbufvar(argvars, rettv)
15275 typval_T *argvars;
15276 typval_T *rettv;
15278 buf_T *buf;
15279 aco_save_T aco;
15280 char_u *varname, *bufvarname;
15281 typval_T *varp;
15282 char_u nbuf[NUMBUFLEN];
15284 if (check_restricted() || check_secure())
15285 return;
15286 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
15287 varname = get_tv_string_chk(&argvars[1]);
15288 buf = get_buf_tv(&argvars[0]);
15289 varp = &argvars[2];
15291 if (buf != NULL && varname != NULL && varp != NULL)
15293 /* set curbuf to be our buf, temporarily */
15294 aucmd_prepbuf(&aco, buf);
15296 if (*varname == '&')
15298 long numval;
15299 char_u *strval;
15300 int error = FALSE;
15302 ++varname;
15303 numval = get_tv_number_chk(varp, &error);
15304 strval = get_tv_string_buf_chk(varp, nbuf);
15305 if (!error && strval != NULL)
15306 set_option_value(varname, numval, strval, OPT_LOCAL);
15308 else
15310 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
15311 if (bufvarname != NULL)
15313 STRCPY(bufvarname, "b:");
15314 STRCPY(bufvarname + 2, varname);
15315 set_var(bufvarname, varp, TRUE);
15316 vim_free(bufvarname);
15320 /* reset notion of buffer */
15321 aucmd_restbuf(&aco);
15326 * "setcmdpos()" function
15328 static void
15329 f_setcmdpos(argvars, rettv)
15330 typval_T *argvars;
15331 typval_T *rettv;
15333 int pos = (int)get_tv_number(&argvars[0]) - 1;
15335 if (pos >= 0)
15336 rettv->vval.v_number = set_cmdline_pos(pos);
15340 * "setline()" function
15342 static void
15343 f_setline(argvars, rettv)
15344 typval_T *argvars;
15345 typval_T *rettv;
15347 linenr_T lnum;
15348 char_u *line = NULL;
15349 list_T *l = NULL;
15350 listitem_T *li = NULL;
15351 long added = 0;
15352 linenr_T lcount = curbuf->b_ml.ml_line_count;
15354 lnum = get_tv_lnum(&argvars[0]);
15355 if (argvars[1].v_type == VAR_LIST)
15357 l = argvars[1].vval.v_list;
15358 li = l->lv_first;
15360 else
15361 line = get_tv_string_chk(&argvars[1]);
15363 /* default result is zero == OK */
15364 for (;;)
15366 if (l != NULL)
15368 /* list argument, get next string */
15369 if (li == NULL)
15370 break;
15371 line = get_tv_string_chk(&li->li_tv);
15372 li = li->li_next;
15375 rettv->vval.v_number = 1; /* FAIL */
15376 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
15377 break;
15378 if (lnum <= curbuf->b_ml.ml_line_count)
15380 /* existing line, replace it */
15381 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
15383 changed_bytes(lnum, 0);
15384 if (lnum == curwin->w_cursor.lnum)
15385 check_cursor_col();
15386 rettv->vval.v_number = 0; /* OK */
15389 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
15391 /* lnum is one past the last line, append the line */
15392 ++added;
15393 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
15394 rettv->vval.v_number = 0; /* OK */
15397 if (l == NULL) /* only one string argument */
15398 break;
15399 ++lnum;
15402 if (added > 0)
15403 appended_lines_mark(lcount, added);
15406 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
15409 * Used by "setqflist()" and "setloclist()" functions
15411 /*ARGSUSED*/
15412 static void
15413 set_qf_ll_list(wp, list_arg, action_arg, rettv)
15414 win_T *wp;
15415 typval_T *list_arg;
15416 typval_T *action_arg;
15417 typval_T *rettv;
15419 #ifdef FEAT_QUICKFIX
15420 char_u *act;
15421 int action = ' ';
15422 #endif
15424 rettv->vval.v_number = -1;
15426 #ifdef FEAT_QUICKFIX
15427 if (list_arg->v_type != VAR_LIST)
15428 EMSG(_(e_listreq));
15429 else
15431 list_T *l = list_arg->vval.v_list;
15433 if (action_arg->v_type == VAR_STRING)
15435 act = get_tv_string_chk(action_arg);
15436 if (act == NULL)
15437 return; /* type error; errmsg already given */
15438 if (*act == 'a' || *act == 'r')
15439 action = *act;
15442 if (l != NULL && set_errorlist(wp, l, action) == OK)
15443 rettv->vval.v_number = 0;
15445 #endif
15449 * "setloclist()" function
15451 /*ARGSUSED*/
15452 static void
15453 f_setloclist(argvars, rettv)
15454 typval_T *argvars;
15455 typval_T *rettv;
15457 win_T *win;
15459 rettv->vval.v_number = -1;
15461 win = find_win_by_nr(&argvars[0], NULL);
15462 if (win != NULL)
15463 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
15467 * "setmatches()" function
15469 static void
15470 f_setmatches(argvars, rettv)
15471 typval_T *argvars;
15472 typval_T *rettv;
15474 #ifdef FEAT_SEARCH_EXTRA
15475 list_T *l;
15476 listitem_T *li;
15477 dict_T *d;
15479 rettv->vval.v_number = -1;
15480 if (argvars[0].v_type != VAR_LIST)
15482 EMSG(_(e_listreq));
15483 return;
15485 if ((l = argvars[0].vval.v_list) != NULL)
15488 /* To some extent make sure that we are dealing with a list from
15489 * "getmatches()". */
15490 li = l->lv_first;
15491 while (li != NULL)
15493 if (li->li_tv.v_type != VAR_DICT
15494 || (d = li->li_tv.vval.v_dict) == NULL)
15496 EMSG(_(e_invarg));
15497 return;
15499 if (!(dict_find(d, (char_u *)"group", -1) != NULL
15500 && dict_find(d, (char_u *)"pattern", -1) != NULL
15501 && dict_find(d, (char_u *)"priority", -1) != NULL
15502 && dict_find(d, (char_u *)"id", -1) != NULL))
15504 EMSG(_(e_invarg));
15505 return;
15507 li = li->li_next;
15510 clear_matches(curwin);
15511 li = l->lv_first;
15512 while (li != NULL)
15514 d = li->li_tv.vval.v_dict;
15515 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
15516 get_dict_string(d, (char_u *)"pattern", FALSE),
15517 (int)get_dict_number(d, (char_u *)"priority"),
15518 (int)get_dict_number(d, (char_u *)"id"));
15519 li = li->li_next;
15521 rettv->vval.v_number = 0;
15523 #endif
15527 * "setpos()" function
15529 /*ARGSUSED*/
15530 static void
15531 f_setpos(argvars, rettv)
15532 typval_T *argvars;
15533 typval_T *rettv;
15535 pos_T pos;
15536 int fnum;
15537 char_u *name;
15539 rettv->vval.v_number = -1;
15540 name = get_tv_string_chk(argvars);
15541 if (name != NULL)
15543 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
15545 --pos.col;
15546 if (name[0] == '.' && name[1] == NUL)
15548 /* set cursor */
15549 if (fnum == curbuf->b_fnum)
15551 curwin->w_cursor = pos;
15552 check_cursor();
15553 rettv->vval.v_number = 0;
15555 else
15556 EMSG(_(e_invarg));
15558 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
15560 /* set mark */
15561 if (setmark_pos(name[1], &pos, fnum) == OK)
15562 rettv->vval.v_number = 0;
15564 else
15565 EMSG(_(e_invarg));
15571 * "setqflist()" function
15573 /*ARGSUSED*/
15574 static void
15575 f_setqflist(argvars, rettv)
15576 typval_T *argvars;
15577 typval_T *rettv;
15579 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
15583 * "setreg()" function
15585 static void
15586 f_setreg(argvars, rettv)
15587 typval_T *argvars;
15588 typval_T *rettv;
15590 int regname;
15591 char_u *strregname;
15592 char_u *stropt;
15593 char_u *strval;
15594 int append;
15595 char_u yank_type;
15596 long block_len;
15598 block_len = -1;
15599 yank_type = MAUTO;
15600 append = FALSE;
15602 strregname = get_tv_string_chk(argvars);
15603 rettv->vval.v_number = 1; /* FAIL is default */
15605 if (strregname == NULL)
15606 return; /* type error; errmsg already given */
15607 regname = *strregname;
15608 if (regname == 0 || regname == '@')
15609 regname = '"';
15610 else if (regname == '=')
15611 return;
15613 if (argvars[2].v_type != VAR_UNKNOWN)
15615 stropt = get_tv_string_chk(&argvars[2]);
15616 if (stropt == NULL)
15617 return; /* type error */
15618 for (; *stropt != NUL; ++stropt)
15619 switch (*stropt)
15621 case 'a': case 'A': /* append */
15622 append = TRUE;
15623 break;
15624 case 'v': case 'c': /* character-wise selection */
15625 yank_type = MCHAR;
15626 break;
15627 case 'V': case 'l': /* line-wise selection */
15628 yank_type = MLINE;
15629 break;
15630 #ifdef FEAT_VISUAL
15631 case 'b': case Ctrl_V: /* block-wise selection */
15632 yank_type = MBLOCK;
15633 if (VIM_ISDIGIT(stropt[1]))
15635 ++stropt;
15636 block_len = getdigits(&stropt) - 1;
15637 --stropt;
15639 break;
15640 #endif
15644 strval = get_tv_string_chk(&argvars[1]);
15645 if (strval != NULL)
15646 write_reg_contents_ex(regname, strval, -1,
15647 append, yank_type, block_len);
15648 rettv->vval.v_number = 0;
15652 * "settabwinvar()" function
15654 static void
15655 f_settabwinvar(argvars, rettv)
15656 typval_T *argvars;
15657 typval_T *rettv;
15659 setwinvar(argvars, rettv, 1);
15663 * "setwinvar()" function
15665 static void
15666 f_setwinvar(argvars, rettv)
15667 typval_T *argvars;
15668 typval_T *rettv;
15670 setwinvar(argvars, rettv, 0);
15674 * "setwinvar()" and "settabwinvar()" functions
15676 /*ARGSUSED*/
15677 static void
15678 setwinvar(argvars, rettv, off)
15679 typval_T *argvars;
15680 typval_T *rettv;
15681 int off;
15683 win_T *win;
15684 #ifdef FEAT_WINDOWS
15685 win_T *save_curwin;
15686 tabpage_T *save_curtab;
15687 #endif
15688 char_u *varname, *winvarname;
15689 typval_T *varp;
15690 char_u nbuf[NUMBUFLEN];
15691 tabpage_T *tp;
15693 if (check_restricted() || check_secure())
15694 return;
15696 #ifdef FEAT_WINDOWS
15697 if (off == 1)
15698 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
15699 else
15700 tp = curtab;
15701 #endif
15702 win = find_win_by_nr(&argvars[off], tp);
15703 varname = get_tv_string_chk(&argvars[off + 1]);
15704 varp = &argvars[off + 2];
15706 if (win != NULL && varname != NULL && varp != NULL)
15708 #ifdef FEAT_WINDOWS
15709 /* set curwin to be our win, temporarily */
15710 save_curwin = curwin;
15711 save_curtab = curtab;
15712 goto_tabpage_tp(tp);
15713 if (!win_valid(win))
15714 return;
15715 curwin = win;
15716 curbuf = curwin->w_buffer;
15717 #endif
15719 if (*varname == '&')
15721 long numval;
15722 char_u *strval;
15723 int error = FALSE;
15725 ++varname;
15726 numval = get_tv_number_chk(varp, &error);
15727 strval = get_tv_string_buf_chk(varp, nbuf);
15728 if (!error && strval != NULL)
15729 set_option_value(varname, numval, strval, OPT_LOCAL);
15731 else
15733 winvarname = alloc((unsigned)STRLEN(varname) + 3);
15734 if (winvarname != NULL)
15736 STRCPY(winvarname, "w:");
15737 STRCPY(winvarname + 2, varname);
15738 set_var(winvarname, varp, TRUE);
15739 vim_free(winvarname);
15743 #ifdef FEAT_WINDOWS
15744 /* Restore current tabpage and window, if still valid (autocomands can
15745 * make them invalid). */
15746 if (valid_tabpage(save_curtab))
15747 goto_tabpage_tp(save_curtab);
15748 if (win_valid(save_curwin))
15750 curwin = save_curwin;
15751 curbuf = curwin->w_buffer;
15753 #endif
15758 * "shellescape({string})" function
15760 static void
15761 f_shellescape(argvars, rettv)
15762 typval_T *argvars;
15763 typval_T *rettv;
15765 rettv->vval.v_string = vim_strsave_shellescape(
15766 get_tv_string(&argvars[0]), non_zero_arg(&argvars[1]));
15767 rettv->v_type = VAR_STRING;
15771 * "simplify()" function
15773 static void
15774 f_simplify(argvars, rettv)
15775 typval_T *argvars;
15776 typval_T *rettv;
15778 char_u *p;
15780 p = get_tv_string(&argvars[0]);
15781 rettv->vval.v_string = vim_strsave(p);
15782 simplify_filename(rettv->vval.v_string); /* simplify in place */
15783 rettv->v_type = VAR_STRING;
15786 #ifdef FEAT_FLOAT
15788 * "sin()" function
15790 static void
15791 f_sin(argvars, rettv)
15792 typval_T *argvars;
15793 typval_T *rettv;
15795 float_T f;
15797 rettv->v_type = VAR_FLOAT;
15798 if (get_float_arg(argvars, &f) == OK)
15799 rettv->vval.v_float = sin(f);
15800 else
15801 rettv->vval.v_float = 0.0;
15803 #endif
15805 static int
15806 #ifdef __BORLANDC__
15807 _RTLENTRYF
15808 #endif
15809 item_compare __ARGS((const void *s1, const void *s2));
15810 static int
15811 #ifdef __BORLANDC__
15812 _RTLENTRYF
15813 #endif
15814 item_compare2 __ARGS((const void *s1, const void *s2));
15816 static int item_compare_ic;
15817 static char_u *item_compare_func;
15818 static int item_compare_func_err;
15819 #define ITEM_COMPARE_FAIL 999
15822 * Compare functions for f_sort() below.
15824 static int
15825 #ifdef __BORLANDC__
15826 _RTLENTRYF
15827 #endif
15828 item_compare(s1, s2)
15829 const void *s1;
15830 const void *s2;
15832 char_u *p1, *p2;
15833 char_u *tofree1, *tofree2;
15834 int res;
15835 char_u numbuf1[NUMBUFLEN];
15836 char_u numbuf2[NUMBUFLEN];
15838 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
15839 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
15840 if (p1 == NULL)
15841 p1 = (char_u *)"";
15842 if (p2 == NULL)
15843 p2 = (char_u *)"";
15844 if (item_compare_ic)
15845 res = STRICMP(p1, p2);
15846 else
15847 res = STRCMP(p1, p2);
15848 vim_free(tofree1);
15849 vim_free(tofree2);
15850 return res;
15853 static int
15854 #ifdef __BORLANDC__
15855 _RTLENTRYF
15856 #endif
15857 item_compare2(s1, s2)
15858 const void *s1;
15859 const void *s2;
15861 int res;
15862 typval_T rettv;
15863 typval_T argv[3];
15864 int dummy;
15866 /* shortcut after failure in previous call; compare all items equal */
15867 if (item_compare_func_err)
15868 return 0;
15870 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
15871 * in the copy without changing the original list items. */
15872 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
15873 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
15875 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
15876 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
15877 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
15878 clear_tv(&argv[0]);
15879 clear_tv(&argv[1]);
15881 if (res == FAIL)
15882 res = ITEM_COMPARE_FAIL;
15883 else
15884 res = get_tv_number_chk(&rettv, &item_compare_func_err);
15885 if (item_compare_func_err)
15886 res = ITEM_COMPARE_FAIL; /* return value has wrong type */
15887 clear_tv(&rettv);
15888 return res;
15892 * "sort({list})" function
15894 static void
15895 f_sort(argvars, rettv)
15896 typval_T *argvars;
15897 typval_T *rettv;
15899 list_T *l;
15900 listitem_T *li;
15901 listitem_T **ptrs;
15902 long len;
15903 long i;
15905 if (argvars[0].v_type != VAR_LIST)
15906 EMSG2(_(e_listarg), "sort()");
15907 else
15909 l = argvars[0].vval.v_list;
15910 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
15911 return;
15912 rettv->vval.v_list = l;
15913 rettv->v_type = VAR_LIST;
15914 ++l->lv_refcount;
15916 len = list_len(l);
15917 if (len <= 1)
15918 return; /* short list sorts pretty quickly */
15920 item_compare_ic = FALSE;
15921 item_compare_func = NULL;
15922 if (argvars[1].v_type != VAR_UNKNOWN)
15924 if (argvars[1].v_type == VAR_FUNC)
15925 item_compare_func = argvars[1].vval.v_string;
15926 else
15928 int error = FALSE;
15930 i = get_tv_number_chk(&argvars[1], &error);
15931 if (error)
15932 return; /* type error; errmsg already given */
15933 if (i == 1)
15934 item_compare_ic = TRUE;
15935 else
15936 item_compare_func = get_tv_string(&argvars[1]);
15940 /* Make an array with each entry pointing to an item in the List. */
15941 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
15942 if (ptrs == NULL)
15943 return;
15944 i = 0;
15945 for (li = l->lv_first; li != NULL; li = li->li_next)
15946 ptrs[i++] = li;
15948 item_compare_func_err = FALSE;
15949 /* test the compare function */
15950 if (item_compare_func != NULL
15951 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
15952 == ITEM_COMPARE_FAIL)
15953 EMSG(_("E702: Sort compare function failed"));
15954 else
15956 /* Sort the array with item pointers. */
15957 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
15958 item_compare_func == NULL ? item_compare : item_compare2);
15960 if (!item_compare_func_err)
15962 /* Clear the List and append the items in the sorted order. */
15963 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
15964 l->lv_len = 0;
15965 for (i = 0; i < len; ++i)
15966 list_append(l, ptrs[i]);
15970 vim_free(ptrs);
15975 * "soundfold({word})" function
15977 static void
15978 f_soundfold(argvars, rettv)
15979 typval_T *argvars;
15980 typval_T *rettv;
15982 char_u *s;
15984 rettv->v_type = VAR_STRING;
15985 s = get_tv_string(&argvars[0]);
15986 #ifdef FEAT_SPELL
15987 rettv->vval.v_string = eval_soundfold(s);
15988 #else
15989 rettv->vval.v_string = vim_strsave(s);
15990 #endif
15994 * "spellbadword()" function
15996 /* ARGSUSED */
15997 static void
15998 f_spellbadword(argvars, rettv)
15999 typval_T *argvars;
16000 typval_T *rettv;
16002 char_u *word = (char_u *)"";
16003 hlf_T attr = HLF_COUNT;
16004 int len = 0;
16006 if (rettv_list_alloc(rettv) == FAIL)
16007 return;
16009 #ifdef FEAT_SPELL
16010 if (argvars[0].v_type == VAR_UNKNOWN)
16012 /* Find the start and length of the badly spelled word. */
16013 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
16014 if (len != 0)
16015 word = ml_get_cursor();
16017 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16019 char_u *str = get_tv_string_chk(&argvars[0]);
16020 int capcol = -1;
16022 if (str != NULL)
16024 /* Check the argument for spelling. */
16025 while (*str != NUL)
16027 len = spell_check(curwin, str, &attr, &capcol, FALSE);
16028 if (attr != HLF_COUNT)
16030 word = str;
16031 break;
16033 str += len;
16037 #endif
16039 list_append_string(rettv->vval.v_list, word, len);
16040 list_append_string(rettv->vval.v_list, (char_u *)(
16041 attr == HLF_SPB ? "bad" :
16042 attr == HLF_SPR ? "rare" :
16043 attr == HLF_SPL ? "local" :
16044 attr == HLF_SPC ? "caps" :
16045 ""), -1);
16049 * "spellsuggest()" function
16051 /*ARGSUSED*/
16052 static void
16053 f_spellsuggest(argvars, rettv)
16054 typval_T *argvars;
16055 typval_T *rettv;
16057 #ifdef FEAT_SPELL
16058 char_u *str;
16059 int typeerr = FALSE;
16060 int maxcount;
16061 garray_T ga;
16062 int i;
16063 listitem_T *li;
16064 int need_capital = FALSE;
16065 #endif
16067 if (rettv_list_alloc(rettv) == FAIL)
16068 return;
16070 #ifdef FEAT_SPELL
16071 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16073 str = get_tv_string(&argvars[0]);
16074 if (argvars[1].v_type != VAR_UNKNOWN)
16076 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
16077 if (maxcount <= 0)
16078 return;
16079 if (argvars[2].v_type != VAR_UNKNOWN)
16081 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
16082 if (typeerr)
16083 return;
16086 else
16087 maxcount = 25;
16089 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
16091 for (i = 0; i < ga.ga_len; ++i)
16093 str = ((char_u **)ga.ga_data)[i];
16095 li = listitem_alloc();
16096 if (li == NULL)
16097 vim_free(str);
16098 else
16100 li->li_tv.v_type = VAR_STRING;
16101 li->li_tv.v_lock = 0;
16102 li->li_tv.vval.v_string = str;
16103 list_append(rettv->vval.v_list, li);
16106 ga_clear(&ga);
16108 #endif
16111 static void
16112 f_split(argvars, rettv)
16113 typval_T *argvars;
16114 typval_T *rettv;
16116 char_u *str;
16117 char_u *end;
16118 char_u *pat = NULL;
16119 regmatch_T regmatch;
16120 char_u patbuf[NUMBUFLEN];
16121 char_u *save_cpo;
16122 int match;
16123 colnr_T col = 0;
16124 int keepempty = FALSE;
16125 int typeerr = FALSE;
16127 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
16128 save_cpo = p_cpo;
16129 p_cpo = (char_u *)"";
16131 str = get_tv_string(&argvars[0]);
16132 if (argvars[1].v_type != VAR_UNKNOWN)
16134 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16135 if (pat == NULL)
16136 typeerr = TRUE;
16137 if (argvars[2].v_type != VAR_UNKNOWN)
16138 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
16140 if (pat == NULL || *pat == NUL)
16141 pat = (char_u *)"[\\x01- ]\\+";
16143 if (rettv_list_alloc(rettv) == FAIL)
16144 return;
16145 if (typeerr)
16146 return;
16148 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
16149 if (regmatch.regprog != NULL)
16151 regmatch.rm_ic = FALSE;
16152 while (*str != NUL || keepempty)
16154 if (*str == NUL)
16155 match = FALSE; /* empty item at the end */
16156 else
16157 match = vim_regexec_nl(&regmatch, str, col);
16158 if (match)
16159 end = regmatch.startp[0];
16160 else
16161 end = str + STRLEN(str);
16162 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
16163 && *str != NUL && match && end < regmatch.endp[0]))
16165 if (list_append_string(rettv->vval.v_list, str,
16166 (int)(end - str)) == FAIL)
16167 break;
16169 if (!match)
16170 break;
16171 /* Advance to just after the match. */
16172 if (regmatch.endp[0] > str)
16173 col = 0;
16174 else
16176 /* Don't get stuck at the same match. */
16177 #ifdef FEAT_MBYTE
16178 col = (*mb_ptr2len)(regmatch.endp[0]);
16179 #else
16180 col = 1;
16181 #endif
16183 str = regmatch.endp[0];
16186 vim_free(regmatch.regprog);
16189 p_cpo = save_cpo;
16192 #ifdef FEAT_FLOAT
16194 * "sqrt()" function
16196 static void
16197 f_sqrt(argvars, rettv)
16198 typval_T *argvars;
16199 typval_T *rettv;
16201 float_T f;
16203 rettv->v_type = VAR_FLOAT;
16204 if (get_float_arg(argvars, &f) == OK)
16205 rettv->vval.v_float = sqrt(f);
16206 else
16207 rettv->vval.v_float = 0.0;
16211 * "str2float()" function
16213 static void
16214 f_str2float(argvars, rettv)
16215 typval_T *argvars;
16216 typval_T *rettv;
16218 char_u *p = skipwhite(get_tv_string(&argvars[0]));
16220 if (*p == '+')
16221 p = skipwhite(p + 1);
16222 (void)string2float(p, &rettv->vval.v_float);
16223 rettv->v_type = VAR_FLOAT;
16225 #endif
16228 * "str2nr()" function
16230 static void
16231 f_str2nr(argvars, rettv)
16232 typval_T *argvars;
16233 typval_T *rettv;
16235 int base = 10;
16236 char_u *p;
16237 long n;
16239 if (argvars[1].v_type != VAR_UNKNOWN)
16241 base = get_tv_number(&argvars[1]);
16242 if (base != 8 && base != 10 && base != 16)
16244 EMSG(_(e_invarg));
16245 return;
16249 p = skipwhite(get_tv_string(&argvars[0]));
16250 if (*p == '+')
16251 p = skipwhite(p + 1);
16252 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
16253 rettv->vval.v_number = n;
16256 #ifdef HAVE_STRFTIME
16258 * "strftime({format}[, {time}])" function
16260 static void
16261 f_strftime(argvars, rettv)
16262 typval_T *argvars;
16263 typval_T *rettv;
16265 char_u result_buf[256];
16266 struct tm *curtime;
16267 time_t seconds;
16268 char_u *p;
16270 rettv->v_type = VAR_STRING;
16272 p = get_tv_string(&argvars[0]);
16273 if (argvars[1].v_type == VAR_UNKNOWN)
16274 seconds = time(NULL);
16275 else
16276 seconds = (time_t)get_tv_number(&argvars[1]);
16277 curtime = localtime(&seconds);
16278 /* MSVC returns NULL for an invalid value of seconds. */
16279 if (curtime == NULL)
16280 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
16281 else
16283 # ifdef FEAT_MBYTE
16284 vimconv_T conv;
16285 char_u *enc;
16287 conv.vc_type = CONV_NONE;
16288 enc = enc_locale();
16289 convert_setup(&conv, p_enc, enc);
16290 if (conv.vc_type != CONV_NONE)
16291 p = string_convert(&conv, p, NULL);
16292 # endif
16293 if (p != NULL)
16294 (void)strftime((char *)result_buf, sizeof(result_buf),
16295 (char *)p, curtime);
16296 else
16297 result_buf[0] = NUL;
16299 # ifdef FEAT_MBYTE
16300 if (conv.vc_type != CONV_NONE)
16301 vim_free(p);
16302 convert_setup(&conv, enc, p_enc);
16303 if (conv.vc_type != CONV_NONE)
16304 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
16305 else
16306 # endif
16307 rettv->vval.v_string = vim_strsave(result_buf);
16309 # ifdef FEAT_MBYTE
16310 /* Release conversion descriptors */
16311 convert_setup(&conv, NULL, NULL);
16312 vim_free(enc);
16313 # endif
16316 #endif
16319 * "stridx()" function
16321 static void
16322 f_stridx(argvars, rettv)
16323 typval_T *argvars;
16324 typval_T *rettv;
16326 char_u buf[NUMBUFLEN];
16327 char_u *needle;
16328 char_u *haystack;
16329 char_u *save_haystack;
16330 char_u *pos;
16331 int start_idx;
16333 needle = get_tv_string_chk(&argvars[1]);
16334 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
16335 rettv->vval.v_number = -1;
16336 if (needle == NULL || haystack == NULL)
16337 return; /* type error; errmsg already given */
16339 if (argvars[2].v_type != VAR_UNKNOWN)
16341 int error = FALSE;
16343 start_idx = get_tv_number_chk(&argvars[2], &error);
16344 if (error || start_idx >= (int)STRLEN(haystack))
16345 return;
16346 if (start_idx >= 0)
16347 haystack += start_idx;
16350 pos = (char_u *)strstr((char *)haystack, (char *)needle);
16351 if (pos != NULL)
16352 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
16356 * "string()" function
16358 static void
16359 f_string(argvars, rettv)
16360 typval_T *argvars;
16361 typval_T *rettv;
16363 char_u *tofree;
16364 char_u numbuf[NUMBUFLEN];
16366 rettv->v_type = VAR_STRING;
16367 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
16368 /* Make a copy if we have a value but it's not in allocated memory. */
16369 if (rettv->vval.v_string != NULL && tofree == NULL)
16370 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
16374 * "strlen()" function
16376 static void
16377 f_strlen(argvars, rettv)
16378 typval_T *argvars;
16379 typval_T *rettv;
16381 rettv->vval.v_number = (varnumber_T)(STRLEN(
16382 get_tv_string(&argvars[0])));
16386 * "strpart()" function
16388 static void
16389 f_strpart(argvars, rettv)
16390 typval_T *argvars;
16391 typval_T *rettv;
16393 char_u *p;
16394 int n;
16395 int len;
16396 int slen;
16397 int error = FALSE;
16399 p = get_tv_string(&argvars[0]);
16400 slen = (int)STRLEN(p);
16402 n = get_tv_number_chk(&argvars[1], &error);
16403 if (error)
16404 len = 0;
16405 else if (argvars[2].v_type != VAR_UNKNOWN)
16406 len = get_tv_number(&argvars[2]);
16407 else
16408 len = slen - n; /* default len: all bytes that are available. */
16411 * Only return the overlap between the specified part and the actual
16412 * string.
16414 if (n < 0)
16416 len += n;
16417 n = 0;
16419 else if (n > slen)
16420 n = slen;
16421 if (len < 0)
16422 len = 0;
16423 else if (n + len > slen)
16424 len = slen - n;
16426 rettv->v_type = VAR_STRING;
16427 rettv->vval.v_string = vim_strnsave(p + n, len);
16431 * "strridx()" function
16433 static void
16434 f_strridx(argvars, rettv)
16435 typval_T *argvars;
16436 typval_T *rettv;
16438 char_u buf[NUMBUFLEN];
16439 char_u *needle;
16440 char_u *haystack;
16441 char_u *rest;
16442 char_u *lastmatch = NULL;
16443 int haystack_len, end_idx;
16445 needle = get_tv_string_chk(&argvars[1]);
16446 haystack = get_tv_string_buf_chk(&argvars[0], buf);
16448 rettv->vval.v_number = -1;
16449 if (needle == NULL || haystack == NULL)
16450 return; /* type error; errmsg already given */
16452 haystack_len = (int)STRLEN(haystack);
16453 if (argvars[2].v_type != VAR_UNKNOWN)
16455 /* Third argument: upper limit for index */
16456 end_idx = get_tv_number_chk(&argvars[2], NULL);
16457 if (end_idx < 0)
16458 return; /* can never find a match */
16460 else
16461 end_idx = haystack_len;
16463 if (*needle == NUL)
16465 /* Empty string matches past the end. */
16466 lastmatch = haystack + end_idx;
16468 else
16470 for (rest = haystack; *rest != '\0'; ++rest)
16472 rest = (char_u *)strstr((char *)rest, (char *)needle);
16473 if (rest == NULL || rest > haystack + end_idx)
16474 break;
16475 lastmatch = rest;
16479 if (lastmatch == NULL)
16480 rettv->vval.v_number = -1;
16481 else
16482 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
16486 * "strtrans()" function
16488 static void
16489 f_strtrans(argvars, rettv)
16490 typval_T *argvars;
16491 typval_T *rettv;
16493 rettv->v_type = VAR_STRING;
16494 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
16498 * "submatch()" function
16500 static void
16501 f_submatch(argvars, rettv)
16502 typval_T *argvars;
16503 typval_T *rettv;
16505 rettv->v_type = VAR_STRING;
16506 rettv->vval.v_string =
16507 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
16511 * "substitute()" function
16513 static void
16514 f_substitute(argvars, rettv)
16515 typval_T *argvars;
16516 typval_T *rettv;
16518 char_u patbuf[NUMBUFLEN];
16519 char_u subbuf[NUMBUFLEN];
16520 char_u flagsbuf[NUMBUFLEN];
16522 char_u *str = get_tv_string_chk(&argvars[0]);
16523 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16524 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
16525 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
16527 rettv->v_type = VAR_STRING;
16528 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
16529 rettv->vval.v_string = NULL;
16530 else
16531 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
16535 * "synID(lnum, col, trans)" function
16537 /*ARGSUSED*/
16538 static void
16539 f_synID(argvars, rettv)
16540 typval_T *argvars;
16541 typval_T *rettv;
16543 int id = 0;
16544 #ifdef FEAT_SYN_HL
16545 long lnum;
16546 long col;
16547 int trans;
16548 int transerr = FALSE;
16550 lnum = get_tv_lnum(argvars); /* -1 on type error */
16551 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16552 trans = get_tv_number_chk(&argvars[2], &transerr);
16554 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16555 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
16556 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
16557 #endif
16559 rettv->vval.v_number = id;
16563 * "synIDattr(id, what [, mode])" function
16565 /*ARGSUSED*/
16566 static void
16567 f_synIDattr(argvars, rettv)
16568 typval_T *argvars;
16569 typval_T *rettv;
16571 char_u *p = NULL;
16572 #ifdef FEAT_SYN_HL
16573 int id;
16574 char_u *what;
16575 char_u *mode;
16576 char_u modebuf[NUMBUFLEN];
16577 int modec;
16579 id = get_tv_number(&argvars[0]);
16580 what = get_tv_string(&argvars[1]);
16581 if (argvars[2].v_type != VAR_UNKNOWN)
16583 mode = get_tv_string_buf(&argvars[2], modebuf);
16584 modec = TOLOWER_ASC(mode[0]);
16585 if (modec != 't' && modec != 'c'
16586 #ifdef FEAT_GUI
16587 && modec != 'g'
16588 #endif
16590 modec = 0; /* replace invalid with current */
16592 else
16594 #ifdef FEAT_GUI
16595 if (gui.in_use)
16596 modec = 'g';
16597 else
16598 #endif
16599 if (t_colors > 1)
16600 modec = 'c';
16601 else
16602 modec = 't';
16606 switch (TOLOWER_ASC(what[0]))
16608 case 'b':
16609 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
16610 p = highlight_color(id, what, modec);
16611 else /* bold */
16612 p = highlight_has_attr(id, HL_BOLD, modec);
16613 break;
16615 case 'f': /* fg[#] */
16616 p = highlight_color(id, what, modec);
16617 break;
16619 case 'i':
16620 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
16621 p = highlight_has_attr(id, HL_INVERSE, modec);
16622 else /* italic */
16623 p = highlight_has_attr(id, HL_ITALIC, modec);
16624 break;
16626 case 'n': /* name */
16627 p = get_highlight_name(NULL, id - 1);
16628 break;
16630 case 'r': /* reverse */
16631 p = highlight_has_attr(id, HL_INVERSE, modec);
16632 break;
16634 case 's':
16635 if (TOLOWER_ASC(what[1]) == 'p') /* sp[#] */
16636 p = highlight_color(id, what, modec);
16637 else /* standout */
16638 p = highlight_has_attr(id, HL_STANDOUT, modec);
16639 break;
16641 case 'u':
16642 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
16643 /* underline */
16644 p = highlight_has_attr(id, HL_UNDERLINE, modec);
16645 else
16646 /* undercurl */
16647 p = highlight_has_attr(id, HL_UNDERCURL, modec);
16648 break;
16651 if (p != NULL)
16652 p = vim_strsave(p);
16653 #endif
16654 rettv->v_type = VAR_STRING;
16655 rettv->vval.v_string = p;
16659 * "synIDtrans(id)" function
16661 /*ARGSUSED*/
16662 static void
16663 f_synIDtrans(argvars, rettv)
16664 typval_T *argvars;
16665 typval_T *rettv;
16667 int id;
16669 #ifdef FEAT_SYN_HL
16670 id = get_tv_number(&argvars[0]);
16672 if (id > 0)
16673 id = syn_get_final_id(id);
16674 else
16675 #endif
16676 id = 0;
16678 rettv->vval.v_number = id;
16682 * "synstack(lnum, col)" function
16684 /*ARGSUSED*/
16685 static void
16686 f_synstack(argvars, rettv)
16687 typval_T *argvars;
16688 typval_T *rettv;
16690 #ifdef FEAT_SYN_HL
16691 long lnum;
16692 long col;
16693 int i;
16694 int id;
16695 #endif
16697 rettv->v_type = VAR_LIST;
16698 rettv->vval.v_list = NULL;
16700 #ifdef FEAT_SYN_HL
16701 lnum = get_tv_lnum(argvars); /* -1 on type error */
16702 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16704 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16705 && col >= 0 && (col == 0 || col < (long)STRLEN(ml_get(lnum)))
16706 && rettv_list_alloc(rettv) != FAIL)
16708 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
16709 for (i = 0; ; ++i)
16711 id = syn_get_stack_item(i);
16712 if (id < 0)
16713 break;
16714 if (list_append_number(rettv->vval.v_list, id) == FAIL)
16715 break;
16718 #endif
16722 * "system()" function
16724 static void
16725 f_system(argvars, rettv)
16726 typval_T *argvars;
16727 typval_T *rettv;
16729 char_u *res = NULL;
16730 char_u *p;
16731 char_u *infile = NULL;
16732 char_u buf[NUMBUFLEN];
16733 int err = FALSE;
16734 FILE *fd;
16736 if (check_restricted() || check_secure())
16737 goto done;
16739 if (argvars[1].v_type != VAR_UNKNOWN)
16742 * Write the string to a temp file, to be used for input of the shell
16743 * command.
16745 if ((infile = vim_tempname('i')) == NULL)
16747 EMSG(_(e_notmp));
16748 goto done;
16751 fd = mch_fopen((char *)infile, WRITEBIN);
16752 if (fd == NULL)
16754 EMSG2(_(e_notopen), infile);
16755 goto done;
16757 p = get_tv_string_buf_chk(&argvars[1], buf);
16758 if (p == NULL)
16760 fclose(fd);
16761 goto done; /* type error; errmsg already given */
16763 if (fwrite(p, STRLEN(p), 1, fd) != 1)
16764 err = TRUE;
16765 if (fclose(fd) != 0)
16766 err = TRUE;
16767 if (err)
16769 EMSG(_("E677: Error writing temp file"));
16770 goto done;
16774 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
16775 SHELL_SILENT | SHELL_COOKED);
16777 #ifdef USE_CR
16778 /* translate <CR> into <NL> */
16779 if (res != NULL)
16781 char_u *s;
16783 for (s = res; *s; ++s)
16785 if (*s == CAR)
16786 *s = NL;
16789 #else
16790 # ifdef USE_CRNL
16791 /* translate <CR><NL> into <NL> */
16792 if (res != NULL)
16794 char_u *s, *d;
16796 d = res;
16797 for (s = res; *s; ++s)
16799 if (s[0] == CAR && s[1] == NL)
16800 ++s;
16801 *d++ = *s;
16803 *d = NUL;
16805 # endif
16806 #endif
16808 done:
16809 if (infile != NULL)
16811 mch_remove(infile);
16812 vim_free(infile);
16814 rettv->v_type = VAR_STRING;
16815 rettv->vval.v_string = res;
16819 * "tabpagebuflist()" function
16821 /* ARGSUSED */
16822 static void
16823 f_tabpagebuflist(argvars, rettv)
16824 typval_T *argvars;
16825 typval_T *rettv;
16827 #ifdef FEAT_WINDOWS
16828 tabpage_T *tp;
16829 win_T *wp = NULL;
16831 if (argvars[0].v_type == VAR_UNKNOWN)
16832 wp = firstwin;
16833 else
16835 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16836 if (tp != NULL)
16837 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16839 if (wp != NULL && rettv_list_alloc(rettv) != FAIL)
16841 for (; wp != NULL; wp = wp->w_next)
16842 if (list_append_number(rettv->vval.v_list,
16843 wp->w_buffer->b_fnum) == FAIL)
16844 break;
16846 #endif
16851 * "tabpagenr()" function
16853 /* ARGSUSED */
16854 static void
16855 f_tabpagenr(argvars, rettv)
16856 typval_T *argvars;
16857 typval_T *rettv;
16859 int nr = 1;
16860 #ifdef FEAT_WINDOWS
16861 char_u *arg;
16863 if (argvars[0].v_type != VAR_UNKNOWN)
16865 arg = get_tv_string_chk(&argvars[0]);
16866 nr = 0;
16867 if (arg != NULL)
16869 if (STRCMP(arg, "$") == 0)
16870 nr = tabpage_index(NULL) - 1;
16871 else
16872 EMSG2(_(e_invexpr2), arg);
16875 else
16876 nr = tabpage_index(curtab);
16877 #endif
16878 rettv->vval.v_number = nr;
16882 #ifdef FEAT_WINDOWS
16883 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
16886 * Common code for tabpagewinnr() and winnr().
16888 static int
16889 get_winnr(tp, argvar)
16890 tabpage_T *tp;
16891 typval_T *argvar;
16893 win_T *twin;
16894 int nr = 1;
16895 win_T *wp;
16896 char_u *arg;
16898 twin = (tp == curtab) ? curwin : tp->tp_curwin;
16899 if (argvar->v_type != VAR_UNKNOWN)
16901 arg = get_tv_string_chk(argvar);
16902 if (arg == NULL)
16903 nr = 0; /* type error; errmsg already given */
16904 else if (STRCMP(arg, "$") == 0)
16905 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
16906 else if (STRCMP(arg, "#") == 0)
16908 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
16909 if (twin == NULL)
16910 nr = 0;
16912 else
16914 EMSG2(_(e_invexpr2), arg);
16915 nr = 0;
16919 if (nr > 0)
16920 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16921 wp != twin; wp = wp->w_next)
16923 if (wp == NULL)
16925 /* didn't find it in this tabpage */
16926 nr = 0;
16927 break;
16929 ++nr;
16931 return nr;
16933 #endif
16936 * "tabpagewinnr()" function
16938 /* ARGSUSED */
16939 static void
16940 f_tabpagewinnr(argvars, rettv)
16941 typval_T *argvars;
16942 typval_T *rettv;
16944 int nr = 1;
16945 #ifdef FEAT_WINDOWS
16946 tabpage_T *tp;
16948 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16949 if (tp == NULL)
16950 nr = 0;
16951 else
16952 nr = get_winnr(tp, &argvars[1]);
16953 #endif
16954 rettv->vval.v_number = nr;
16959 * "tagfiles()" function
16961 /*ARGSUSED*/
16962 static void
16963 f_tagfiles(argvars, rettv)
16964 typval_T *argvars;
16965 typval_T *rettv;
16967 char_u fname[MAXPATHL + 1];
16968 tagname_T tn;
16969 int first;
16971 if (rettv_list_alloc(rettv) == FAIL)
16972 return;
16974 for (first = TRUE; ; first = FALSE)
16975 if (get_tagfname(&tn, first, fname) == FAIL
16976 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
16977 break;
16978 tagname_free(&tn);
16982 * "taglist()" function
16984 static void
16985 f_taglist(argvars, rettv)
16986 typval_T *argvars;
16987 typval_T *rettv;
16989 char_u *tag_pattern;
16991 tag_pattern = get_tv_string(&argvars[0]);
16993 rettv->vval.v_number = FALSE;
16994 if (*tag_pattern == NUL)
16995 return;
16997 if (rettv_list_alloc(rettv) == OK)
16998 (void)get_tags(rettv->vval.v_list, tag_pattern);
17002 * "tempname()" function
17004 /*ARGSUSED*/
17005 static void
17006 f_tempname(argvars, rettv)
17007 typval_T *argvars;
17008 typval_T *rettv;
17010 static int x = 'A';
17012 rettv->v_type = VAR_STRING;
17013 rettv->vval.v_string = vim_tempname(x);
17015 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
17016 * names. Skip 'I' and 'O', they are used for shell redirection. */
17019 if (x == 'Z')
17020 x = '0';
17021 else if (x == '9')
17022 x = 'A';
17023 else
17025 #ifdef EBCDIC
17026 if (x == 'I')
17027 x = 'J';
17028 else if (x == 'R')
17029 x = 'S';
17030 else
17031 #endif
17032 ++x;
17034 } while (x == 'I' || x == 'O');
17038 * "test(list)" function: Just checking the walls...
17040 /*ARGSUSED*/
17041 static void
17042 f_test(argvars, rettv)
17043 typval_T *argvars;
17044 typval_T *rettv;
17046 /* Used for unit testing. Change the code below to your liking. */
17047 #if 0
17048 listitem_T *li;
17049 list_T *l;
17050 char_u *bad, *good;
17052 if (argvars[0].v_type != VAR_LIST)
17053 return;
17054 l = argvars[0].vval.v_list;
17055 if (l == NULL)
17056 return;
17057 li = l->lv_first;
17058 if (li == NULL)
17059 return;
17060 bad = get_tv_string(&li->li_tv);
17061 li = li->li_next;
17062 if (li == NULL)
17063 return;
17064 good = get_tv_string(&li->li_tv);
17065 rettv->vval.v_number = test_edit_score(bad, good);
17066 #endif
17070 * "tolower(string)" function
17072 static void
17073 f_tolower(argvars, rettv)
17074 typval_T *argvars;
17075 typval_T *rettv;
17077 char_u *p;
17079 p = vim_strsave(get_tv_string(&argvars[0]));
17080 rettv->v_type = VAR_STRING;
17081 rettv->vval.v_string = p;
17083 if (p != NULL)
17084 while (*p != NUL)
17086 #ifdef FEAT_MBYTE
17087 int l;
17089 if (enc_utf8)
17091 int c, lc;
17093 c = utf_ptr2char(p);
17094 lc = utf_tolower(c);
17095 l = utf_ptr2len(p);
17096 /* TODO: reallocate string when byte count changes. */
17097 if (utf_char2len(lc) == l)
17098 utf_char2bytes(lc, p);
17099 p += l;
17101 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
17102 p += l; /* skip multi-byte character */
17103 else
17104 #endif
17106 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
17107 ++p;
17113 * "toupper(string)" function
17115 static void
17116 f_toupper(argvars, rettv)
17117 typval_T *argvars;
17118 typval_T *rettv;
17120 rettv->v_type = VAR_STRING;
17121 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
17125 * "tr(string, fromstr, tostr)" function
17127 static void
17128 f_tr(argvars, rettv)
17129 typval_T *argvars;
17130 typval_T *rettv;
17132 char_u *instr;
17133 char_u *fromstr;
17134 char_u *tostr;
17135 char_u *p;
17136 #ifdef FEAT_MBYTE
17137 int inlen;
17138 int fromlen;
17139 int tolen;
17140 int idx;
17141 char_u *cpstr;
17142 int cplen;
17143 int first = TRUE;
17144 #endif
17145 char_u buf[NUMBUFLEN];
17146 char_u buf2[NUMBUFLEN];
17147 garray_T ga;
17149 instr = get_tv_string(&argvars[0]);
17150 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
17151 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
17153 /* Default return value: empty string. */
17154 rettv->v_type = VAR_STRING;
17155 rettv->vval.v_string = NULL;
17156 if (fromstr == NULL || tostr == NULL)
17157 return; /* type error; errmsg already given */
17158 ga_init2(&ga, (int)sizeof(char), 80);
17160 #ifdef FEAT_MBYTE
17161 if (!has_mbyte)
17162 #endif
17163 /* not multi-byte: fromstr and tostr must be the same length */
17164 if (STRLEN(fromstr) != STRLEN(tostr))
17166 #ifdef FEAT_MBYTE
17167 error:
17168 #endif
17169 EMSG2(_(e_invarg2), fromstr);
17170 ga_clear(&ga);
17171 return;
17174 /* fromstr and tostr have to contain the same number of chars */
17175 while (*instr != NUL)
17177 #ifdef FEAT_MBYTE
17178 if (has_mbyte)
17180 inlen = (*mb_ptr2len)(instr);
17181 cpstr = instr;
17182 cplen = inlen;
17183 idx = 0;
17184 for (p = fromstr; *p != NUL; p += fromlen)
17186 fromlen = (*mb_ptr2len)(p);
17187 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
17189 for (p = tostr; *p != NUL; p += tolen)
17191 tolen = (*mb_ptr2len)(p);
17192 if (idx-- == 0)
17194 cplen = tolen;
17195 cpstr = p;
17196 break;
17199 if (*p == NUL) /* tostr is shorter than fromstr */
17200 goto error;
17201 break;
17203 ++idx;
17206 if (first && cpstr == instr)
17208 /* Check that fromstr and tostr have the same number of
17209 * (multi-byte) characters. Done only once when a character
17210 * of instr doesn't appear in fromstr. */
17211 first = FALSE;
17212 for (p = tostr; *p != NUL; p += tolen)
17214 tolen = (*mb_ptr2len)(p);
17215 --idx;
17217 if (idx != 0)
17218 goto error;
17221 ga_grow(&ga, cplen);
17222 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
17223 ga.ga_len += cplen;
17225 instr += inlen;
17227 else
17228 #endif
17230 /* When not using multi-byte chars we can do it faster. */
17231 p = vim_strchr(fromstr, *instr);
17232 if (p != NULL)
17233 ga_append(&ga, tostr[p - fromstr]);
17234 else
17235 ga_append(&ga, *instr);
17236 ++instr;
17240 /* add a terminating NUL */
17241 ga_grow(&ga, 1);
17242 ga_append(&ga, NUL);
17244 rettv->vval.v_string = ga.ga_data;
17247 #ifdef FEAT_FLOAT
17249 * "trunc({float})" function
17251 static void
17252 f_trunc(argvars, rettv)
17253 typval_T *argvars;
17254 typval_T *rettv;
17256 float_T f;
17258 rettv->v_type = VAR_FLOAT;
17259 if (get_float_arg(argvars, &f) == OK)
17260 /* trunc() is not in C90, use floor() or ceil() instead. */
17261 rettv->vval.v_float = f > 0 ? floor(f) : ceil(f);
17262 else
17263 rettv->vval.v_float = 0.0;
17265 #endif
17268 * "type(expr)" function
17270 static void
17271 f_type(argvars, rettv)
17272 typval_T *argvars;
17273 typval_T *rettv;
17275 int n;
17277 switch (argvars[0].v_type)
17279 case VAR_NUMBER: n = 0; break;
17280 case VAR_STRING: n = 1; break;
17281 case VAR_FUNC: n = 2; break;
17282 case VAR_LIST: n = 3; break;
17283 case VAR_DICT: n = 4; break;
17284 #ifdef FEAT_FLOAT
17285 case VAR_FLOAT: n = 5; break;
17286 #endif
17287 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
17289 rettv->vval.v_number = n;
17293 * "values(dict)" function
17295 static void
17296 f_values(argvars, rettv)
17297 typval_T *argvars;
17298 typval_T *rettv;
17300 dict_list(argvars, rettv, 1);
17304 * "virtcol(string)" function
17306 static void
17307 f_virtcol(argvars, rettv)
17308 typval_T *argvars;
17309 typval_T *rettv;
17311 colnr_T vcol = 0;
17312 pos_T *fp;
17313 int fnum = curbuf->b_fnum;
17315 fp = var2fpos(&argvars[0], FALSE, &fnum);
17316 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
17317 && fnum == curbuf->b_fnum)
17319 getvvcol(curwin, fp, NULL, NULL, &vcol);
17320 ++vcol;
17323 rettv->vval.v_number = vcol;
17327 * "visualmode()" function
17329 /*ARGSUSED*/
17330 static void
17331 f_visualmode(argvars, rettv)
17332 typval_T *argvars;
17333 typval_T *rettv;
17335 #ifdef FEAT_VISUAL
17336 char_u str[2];
17338 rettv->v_type = VAR_STRING;
17339 str[0] = curbuf->b_visual_mode_eval;
17340 str[1] = NUL;
17341 rettv->vval.v_string = vim_strsave(str);
17343 /* A non-zero number or non-empty string argument: reset mode. */
17344 if (non_zero_arg(&argvars[0]))
17345 curbuf->b_visual_mode_eval = NUL;
17346 #endif
17350 * "winbufnr(nr)" function
17352 static void
17353 f_winbufnr(argvars, rettv)
17354 typval_T *argvars;
17355 typval_T *rettv;
17357 win_T *wp;
17359 wp = find_win_by_nr(&argvars[0], NULL);
17360 if (wp == NULL)
17361 rettv->vval.v_number = -1;
17362 else
17363 rettv->vval.v_number = wp->w_buffer->b_fnum;
17367 * "wincol()" function
17369 /*ARGSUSED*/
17370 static void
17371 f_wincol(argvars, rettv)
17372 typval_T *argvars;
17373 typval_T *rettv;
17375 validate_cursor();
17376 rettv->vval.v_number = curwin->w_wcol + 1;
17380 * "winheight(nr)" function
17382 static void
17383 f_winheight(argvars, rettv)
17384 typval_T *argvars;
17385 typval_T *rettv;
17387 win_T *wp;
17389 wp = find_win_by_nr(&argvars[0], NULL);
17390 if (wp == NULL)
17391 rettv->vval.v_number = -1;
17392 else
17393 rettv->vval.v_number = wp->w_height;
17397 * "winline()" function
17399 /*ARGSUSED*/
17400 static void
17401 f_winline(argvars, rettv)
17402 typval_T *argvars;
17403 typval_T *rettv;
17405 validate_cursor();
17406 rettv->vval.v_number = curwin->w_wrow + 1;
17410 * "winnr()" function
17412 /* ARGSUSED */
17413 static void
17414 f_winnr(argvars, rettv)
17415 typval_T *argvars;
17416 typval_T *rettv;
17418 int nr = 1;
17420 #ifdef FEAT_WINDOWS
17421 nr = get_winnr(curtab, &argvars[0]);
17422 #endif
17423 rettv->vval.v_number = nr;
17427 * "winrestcmd()" function
17429 /* ARGSUSED */
17430 static void
17431 f_winrestcmd(argvars, rettv)
17432 typval_T *argvars;
17433 typval_T *rettv;
17435 #ifdef FEAT_WINDOWS
17436 win_T *wp;
17437 int winnr = 1;
17438 garray_T ga;
17439 char_u buf[50];
17441 ga_init2(&ga, (int)sizeof(char), 70);
17442 for (wp = firstwin; wp != NULL; wp = wp->w_next)
17444 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
17445 ga_concat(&ga, buf);
17446 # ifdef FEAT_VERTSPLIT
17447 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
17448 ga_concat(&ga, buf);
17449 # endif
17450 ++winnr;
17452 ga_append(&ga, NUL);
17454 rettv->vval.v_string = ga.ga_data;
17455 #else
17456 rettv->vval.v_string = NULL;
17457 #endif
17458 rettv->v_type = VAR_STRING;
17462 * "winrestview()" function
17464 /* ARGSUSED */
17465 static void
17466 f_winrestview(argvars, rettv)
17467 typval_T *argvars;
17468 typval_T *rettv;
17470 dict_T *dict;
17472 if (argvars[0].v_type != VAR_DICT
17473 || (dict = argvars[0].vval.v_dict) == NULL)
17474 EMSG(_(e_invarg));
17475 else
17477 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
17478 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
17479 #ifdef FEAT_VIRTUALEDIT
17480 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
17481 #endif
17482 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
17483 curwin->w_set_curswant = FALSE;
17485 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
17486 #ifdef FEAT_DIFF
17487 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
17488 #endif
17489 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
17490 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
17492 check_cursor();
17493 changed_cline_bef_curs();
17494 invalidate_botline();
17495 redraw_later(VALID);
17497 if (curwin->w_topline == 0)
17498 curwin->w_topline = 1;
17499 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
17500 curwin->w_topline = curbuf->b_ml.ml_line_count;
17501 #ifdef FEAT_DIFF
17502 check_topfill(curwin, TRUE);
17503 #endif
17508 * "winsaveview()" function
17510 /* ARGSUSED */
17511 static void
17512 f_winsaveview(argvars, rettv)
17513 typval_T *argvars;
17514 typval_T *rettv;
17516 dict_T *dict;
17518 dict = dict_alloc();
17519 if (dict == NULL)
17520 return;
17521 rettv->v_type = VAR_DICT;
17522 rettv->vval.v_dict = dict;
17523 ++dict->dv_refcount;
17525 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
17526 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
17527 #ifdef FEAT_VIRTUALEDIT
17528 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
17529 #endif
17530 update_curswant();
17531 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
17533 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
17534 #ifdef FEAT_DIFF
17535 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
17536 #endif
17537 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
17538 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
17542 * "winwidth(nr)" function
17544 static void
17545 f_winwidth(argvars, rettv)
17546 typval_T *argvars;
17547 typval_T *rettv;
17549 win_T *wp;
17551 wp = find_win_by_nr(&argvars[0], NULL);
17552 if (wp == NULL)
17553 rettv->vval.v_number = -1;
17554 else
17555 #ifdef FEAT_VERTSPLIT
17556 rettv->vval.v_number = wp->w_width;
17557 #else
17558 rettv->vval.v_number = Columns;
17559 #endif
17563 * "writefile()" function
17565 static void
17566 f_writefile(argvars, rettv)
17567 typval_T *argvars;
17568 typval_T *rettv;
17570 int binary = FALSE;
17571 char_u *fname;
17572 FILE *fd;
17573 listitem_T *li;
17574 char_u *s;
17575 int ret = 0;
17576 int c;
17578 if (check_restricted() || check_secure())
17579 return;
17581 if (argvars[0].v_type != VAR_LIST)
17583 EMSG2(_(e_listarg), "writefile()");
17584 return;
17586 if (argvars[0].vval.v_list == NULL)
17587 return;
17589 if (argvars[2].v_type != VAR_UNKNOWN
17590 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
17591 binary = TRUE;
17593 /* Always open the file in binary mode, library functions have a mind of
17594 * their own about CR-LF conversion. */
17595 fname = get_tv_string(&argvars[1]);
17596 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
17598 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
17599 ret = -1;
17601 else
17603 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
17604 li = li->li_next)
17606 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
17608 if (*s == '\n')
17609 c = putc(NUL, fd);
17610 else
17611 c = putc(*s, fd);
17612 if (c == EOF)
17614 ret = -1;
17615 break;
17618 if (!binary || li->li_next != NULL)
17619 if (putc('\n', fd) == EOF)
17621 ret = -1;
17622 break;
17624 if (ret < 0)
17626 EMSG(_(e_write));
17627 break;
17630 fclose(fd);
17633 rettv->vval.v_number = ret;
17637 * Translate a String variable into a position.
17638 * Returns NULL when there is an error.
17640 static pos_T *
17641 var2fpos(varp, dollar_lnum, fnum)
17642 typval_T *varp;
17643 int dollar_lnum; /* TRUE when $ is last line */
17644 int *fnum; /* set to fnum for '0, 'A, etc. */
17646 char_u *name;
17647 static pos_T pos;
17648 pos_T *pp;
17650 /* Argument can be [lnum, col, coladd]. */
17651 if (varp->v_type == VAR_LIST)
17653 list_T *l;
17654 int len;
17655 int error = FALSE;
17656 listitem_T *li;
17658 l = varp->vval.v_list;
17659 if (l == NULL)
17660 return NULL;
17662 /* Get the line number */
17663 pos.lnum = list_find_nr(l, 0L, &error);
17664 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
17665 return NULL; /* invalid line number */
17667 /* Get the column number */
17668 pos.col = list_find_nr(l, 1L, &error);
17669 if (error)
17670 return NULL;
17671 len = (long)STRLEN(ml_get(pos.lnum));
17673 /* We accept "$" for the column number: last column. */
17674 li = list_find(l, 1L);
17675 if (li != NULL && li->li_tv.v_type == VAR_STRING
17676 && li->li_tv.vval.v_string != NULL
17677 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
17678 pos.col = len + 1;
17680 /* Accept a position up to the NUL after the line. */
17681 if (pos.col == 0 || (int)pos.col > len + 1)
17682 return NULL; /* invalid column number */
17683 --pos.col;
17685 #ifdef FEAT_VIRTUALEDIT
17686 /* Get the virtual offset. Defaults to zero. */
17687 pos.coladd = list_find_nr(l, 2L, &error);
17688 if (error)
17689 pos.coladd = 0;
17690 #endif
17692 return &pos;
17695 name = get_tv_string_chk(varp);
17696 if (name == NULL)
17697 return NULL;
17698 if (name[0] == '.') /* cursor */
17699 return &curwin->w_cursor;
17700 #ifdef FEAT_VISUAL
17701 if (name[0] == 'v' && name[1] == NUL) /* Visual start */
17703 if (VIsual_active)
17704 return &VIsual;
17705 return &curwin->w_cursor;
17707 #endif
17708 if (name[0] == '\'') /* mark */
17710 pp = getmark_fnum(name[1], FALSE, fnum);
17711 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
17712 return NULL;
17713 return pp;
17716 #ifdef FEAT_VIRTUALEDIT
17717 pos.coladd = 0;
17718 #endif
17720 if (name[0] == 'w' && dollar_lnum)
17722 pos.col = 0;
17723 if (name[1] == '0') /* "w0": first visible line */
17725 update_topline();
17726 pos.lnum = curwin->w_topline;
17727 return &pos;
17729 else if (name[1] == '$') /* "w$": last visible line */
17731 validate_botline();
17732 pos.lnum = curwin->w_botline - 1;
17733 return &pos;
17736 else if (name[0] == '$') /* last column or line */
17738 if (dollar_lnum)
17740 pos.lnum = curbuf->b_ml.ml_line_count;
17741 pos.col = 0;
17743 else
17745 pos.lnum = curwin->w_cursor.lnum;
17746 pos.col = (colnr_T)STRLEN(ml_get_curline());
17748 return &pos;
17750 return NULL;
17754 * Convert list in "arg" into a position and optional file number.
17755 * When "fnump" is NULL there is no file number, only 3 items.
17756 * Note that the column is passed on as-is, the caller may want to decrement
17757 * it to use 1 for the first column.
17758 * Return FAIL when conversion is not possible, doesn't check the position for
17759 * validity.
17761 static int
17762 list2fpos(arg, posp, fnump)
17763 typval_T *arg;
17764 pos_T *posp;
17765 int *fnump;
17767 list_T *l = arg->vval.v_list;
17768 long i = 0;
17769 long n;
17771 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
17772 * when "fnump" isn't NULL and "coladd" is optional. */
17773 if (arg->v_type != VAR_LIST
17774 || l == NULL
17775 || l->lv_len < (fnump == NULL ? 2 : 3)
17776 || l->lv_len > (fnump == NULL ? 3 : 4))
17777 return FAIL;
17779 if (fnump != NULL)
17781 n = list_find_nr(l, i++, NULL); /* fnum */
17782 if (n < 0)
17783 return FAIL;
17784 if (n == 0)
17785 n = curbuf->b_fnum; /* current buffer */
17786 *fnump = n;
17789 n = list_find_nr(l, i++, NULL); /* lnum */
17790 if (n < 0)
17791 return FAIL;
17792 posp->lnum = n;
17794 n = list_find_nr(l, i++, NULL); /* col */
17795 if (n < 0)
17796 return FAIL;
17797 posp->col = n;
17799 #ifdef FEAT_VIRTUALEDIT
17800 n = list_find_nr(l, i, NULL);
17801 if (n < 0)
17802 posp->coladd = 0;
17803 else
17804 posp->coladd = n;
17805 #endif
17807 return OK;
17811 * Get the length of an environment variable name.
17812 * Advance "arg" to the first character after the name.
17813 * Return 0 for error.
17815 static int
17816 get_env_len(arg)
17817 char_u **arg;
17819 char_u *p;
17820 int len;
17822 for (p = *arg; vim_isIDc(*p); ++p)
17824 if (p == *arg) /* no name found */
17825 return 0;
17827 len = (int)(p - *arg);
17828 *arg = p;
17829 return len;
17833 * Get the length of the name of a function or internal variable.
17834 * "arg" is advanced to the first non-white character after the name.
17835 * Return 0 if something is wrong.
17837 static int
17838 get_id_len(arg)
17839 char_u **arg;
17841 char_u *p;
17842 int len;
17844 /* Find the end of the name. */
17845 for (p = *arg; eval_isnamec(*p); ++p)
17847 if (p == *arg) /* no name found */
17848 return 0;
17850 len = (int)(p - *arg);
17851 *arg = skipwhite(p);
17853 return len;
17857 * Get the length of the name of a variable or function.
17858 * Only the name is recognized, does not handle ".key" or "[idx]".
17859 * "arg" is advanced to the first non-white character after the name.
17860 * Return -1 if curly braces expansion failed.
17861 * Return 0 if something else is wrong.
17862 * If the name contains 'magic' {}'s, expand them and return the
17863 * expanded name in an allocated string via 'alias' - caller must free.
17865 static int
17866 get_name_len(arg, alias, evaluate, verbose)
17867 char_u **arg;
17868 char_u **alias;
17869 int evaluate;
17870 int verbose;
17872 int len;
17873 char_u *p;
17874 char_u *expr_start;
17875 char_u *expr_end;
17877 *alias = NULL; /* default to no alias */
17879 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
17880 && (*arg)[2] == (int)KE_SNR)
17882 /* hard coded <SNR>, already translated */
17883 *arg += 3;
17884 return get_id_len(arg) + 3;
17886 len = eval_fname_script(*arg);
17887 if (len > 0)
17889 /* literal "<SID>", "s:" or "<SNR>" */
17890 *arg += len;
17894 * Find the end of the name; check for {} construction.
17896 p = find_name_end(*arg, &expr_start, &expr_end,
17897 len > 0 ? 0 : FNE_CHECK_START);
17898 if (expr_start != NULL)
17900 char_u *temp_string;
17902 if (!evaluate)
17904 len += (int)(p - *arg);
17905 *arg = skipwhite(p);
17906 return len;
17910 * Include any <SID> etc in the expanded string:
17911 * Thus the -len here.
17913 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
17914 if (temp_string == NULL)
17915 return -1;
17916 *alias = temp_string;
17917 *arg = skipwhite(p);
17918 return (int)STRLEN(temp_string);
17921 len += get_id_len(arg);
17922 if (len == 0 && verbose)
17923 EMSG2(_(e_invexpr2), *arg);
17925 return len;
17929 * Find the end of a variable or function name, taking care of magic braces.
17930 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
17931 * start and end of the first magic braces item.
17932 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
17933 * Return a pointer to just after the name. Equal to "arg" if there is no
17934 * valid name.
17936 static char_u *
17937 find_name_end(arg, expr_start, expr_end, flags)
17938 char_u *arg;
17939 char_u **expr_start;
17940 char_u **expr_end;
17941 int flags;
17943 int mb_nest = 0;
17944 int br_nest = 0;
17945 char_u *p;
17947 if (expr_start != NULL)
17949 *expr_start = NULL;
17950 *expr_end = NULL;
17953 /* Quick check for valid starting character. */
17954 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
17955 return arg;
17957 for (p = arg; *p != NUL
17958 && (eval_isnamec(*p)
17959 || *p == '{'
17960 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
17961 || mb_nest != 0
17962 || br_nest != 0); mb_ptr_adv(p))
17964 if (*p == '\'')
17966 /* skip over 'string' to avoid counting [ and ] inside it. */
17967 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
17969 if (*p == NUL)
17970 break;
17972 else if (*p == '"')
17974 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
17975 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
17976 if (*p == '\\' && p[1] != NUL)
17977 ++p;
17978 if (*p == NUL)
17979 break;
17982 if (mb_nest == 0)
17984 if (*p == '[')
17985 ++br_nest;
17986 else if (*p == ']')
17987 --br_nest;
17990 if (br_nest == 0)
17992 if (*p == '{')
17994 mb_nest++;
17995 if (expr_start != NULL && *expr_start == NULL)
17996 *expr_start = p;
17998 else if (*p == '}')
18000 mb_nest--;
18001 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
18002 *expr_end = p;
18007 return p;
18011 * Expands out the 'magic' {}'s in a variable/function name.
18012 * Note that this can call itself recursively, to deal with
18013 * constructs like foo{bar}{baz}{bam}
18014 * The four pointer arguments point to "foo{expre}ss{ion}bar"
18015 * "in_start" ^
18016 * "expr_start" ^
18017 * "expr_end" ^
18018 * "in_end" ^
18020 * Returns a new allocated string, which the caller must free.
18021 * Returns NULL for failure.
18023 static char_u *
18024 make_expanded_name(in_start, expr_start, expr_end, in_end)
18025 char_u *in_start;
18026 char_u *expr_start;
18027 char_u *expr_end;
18028 char_u *in_end;
18030 char_u c1;
18031 char_u *retval = NULL;
18032 char_u *temp_result;
18033 char_u *nextcmd = NULL;
18035 if (expr_end == NULL || in_end == NULL)
18036 return NULL;
18037 *expr_start = NUL;
18038 *expr_end = NUL;
18039 c1 = *in_end;
18040 *in_end = NUL;
18042 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
18043 if (temp_result != NULL && nextcmd == NULL)
18045 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
18046 + (in_end - expr_end) + 1));
18047 if (retval != NULL)
18049 STRCPY(retval, in_start);
18050 STRCAT(retval, temp_result);
18051 STRCAT(retval, expr_end + 1);
18054 vim_free(temp_result);
18056 *in_end = c1; /* put char back for error messages */
18057 *expr_start = '{';
18058 *expr_end = '}';
18060 if (retval != NULL)
18062 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
18063 if (expr_start != NULL)
18065 /* Further expansion! */
18066 temp_result = make_expanded_name(retval, expr_start,
18067 expr_end, temp_result);
18068 vim_free(retval);
18069 retval = temp_result;
18073 return retval;
18077 * Return TRUE if character "c" can be used in a variable or function name.
18078 * Does not include '{' or '}' for magic braces.
18080 static int
18081 eval_isnamec(c)
18082 int c;
18084 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
18088 * Return TRUE if character "c" can be used as the first character in a
18089 * variable or function name (excluding '{' and '}').
18091 static int
18092 eval_isnamec1(c)
18093 int c;
18095 return (ASCII_ISALPHA(c) || c == '_');
18099 * Set number v: variable to "val".
18101 void
18102 set_vim_var_nr(idx, val)
18103 int idx;
18104 long val;
18106 vimvars[idx].vv_nr = val;
18110 * Get number v: variable value.
18112 long
18113 get_vim_var_nr(idx)
18114 int idx;
18116 return vimvars[idx].vv_nr;
18120 * Get string v: variable value. Uses a static buffer, can only be used once.
18122 char_u *
18123 get_vim_var_str(idx)
18124 int idx;
18126 return get_tv_string(&vimvars[idx].vv_tv);
18130 * Get List v: variable value. Caller must take care of reference count when
18131 * needed.
18133 list_T *
18134 get_vim_var_list(idx)
18135 int idx;
18137 return vimvars[idx].vv_list;
18141 * Set v:count to "count" and v:count1 to "count1".
18142 * When "set_prevcount" is TRUE first set v:prevcount from v:count.
18144 void
18145 set_vcount(count, count1, set_prevcount)
18146 long count;
18147 long count1;
18148 int set_prevcount;
18150 if (set_prevcount)
18151 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
18152 vimvars[VV_COUNT].vv_nr = count;
18153 vimvars[VV_COUNT1].vv_nr = count1;
18157 * Set string v: variable to a copy of "val".
18159 void
18160 set_vim_var_string(idx, val, len)
18161 int idx;
18162 char_u *val;
18163 int len; /* length of "val" to use or -1 (whole string) */
18165 /* Need to do this (at least) once, since we can't initialize a union.
18166 * Will always be invoked when "v:progname" is set. */
18167 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
18169 vim_free(vimvars[idx].vv_str);
18170 if (val == NULL)
18171 vimvars[idx].vv_str = NULL;
18172 else if (len == -1)
18173 vimvars[idx].vv_str = vim_strsave(val);
18174 else
18175 vimvars[idx].vv_str = vim_strnsave(val, len);
18179 * Set List v: variable to "val".
18181 void
18182 set_vim_var_list(idx, val)
18183 int idx;
18184 list_T *val;
18186 list_unref(vimvars[idx].vv_list);
18187 vimvars[idx].vv_list = val;
18188 if (val != NULL)
18189 ++val->lv_refcount;
18193 * Set v:register if needed.
18195 void
18196 set_reg_var(c)
18197 int c;
18199 char_u regname;
18201 if (c == 0 || c == ' ')
18202 regname = '"';
18203 else
18204 regname = c;
18205 /* Avoid free/alloc when the value is already right. */
18206 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
18207 set_vim_var_string(VV_REG, &regname, 1);
18211 * Get or set v:exception. If "oldval" == NULL, return the current value.
18212 * Otherwise, restore the value to "oldval" and return NULL.
18213 * Must always be called in pairs to save and restore v:exception! Does not
18214 * take care of memory allocations.
18216 char_u *
18217 v_exception(oldval)
18218 char_u *oldval;
18220 if (oldval == NULL)
18221 return vimvars[VV_EXCEPTION].vv_str;
18223 vimvars[VV_EXCEPTION].vv_str = oldval;
18224 return NULL;
18228 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
18229 * Otherwise, restore the value to "oldval" and return NULL.
18230 * Must always be called in pairs to save and restore v:throwpoint! Does not
18231 * take care of memory allocations.
18233 char_u *
18234 v_throwpoint(oldval)
18235 char_u *oldval;
18237 if (oldval == NULL)
18238 return vimvars[VV_THROWPOINT].vv_str;
18240 vimvars[VV_THROWPOINT].vv_str = oldval;
18241 return NULL;
18244 #if defined(FEAT_AUTOCMD) || defined(PROTO)
18246 * Set v:cmdarg.
18247 * If "eap" != NULL, use "eap" to generate the value and return the old value.
18248 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
18249 * Must always be called in pairs!
18251 char_u *
18252 set_cmdarg(eap, oldarg)
18253 exarg_T *eap;
18254 char_u *oldarg;
18256 char_u *oldval;
18257 char_u *newval;
18258 unsigned len;
18260 oldval = vimvars[VV_CMDARG].vv_str;
18261 if (eap == NULL)
18263 vim_free(oldval);
18264 vimvars[VV_CMDARG].vv_str = oldarg;
18265 return NULL;
18268 if (eap->force_bin == FORCE_BIN)
18269 len = 6;
18270 else if (eap->force_bin == FORCE_NOBIN)
18271 len = 8;
18272 else
18273 len = 0;
18275 if (eap->read_edit)
18276 len += 7;
18278 if (eap->force_ff != 0)
18279 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
18280 # ifdef FEAT_MBYTE
18281 if (eap->force_enc != 0)
18282 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
18283 if (eap->bad_char != 0)
18284 len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
18285 # endif
18287 newval = alloc(len + 1);
18288 if (newval == NULL)
18289 return NULL;
18291 if (eap->force_bin == FORCE_BIN)
18292 sprintf((char *)newval, " ++bin");
18293 else if (eap->force_bin == FORCE_NOBIN)
18294 sprintf((char *)newval, " ++nobin");
18295 else
18296 *newval = NUL;
18298 if (eap->read_edit)
18299 STRCAT(newval, " ++edit");
18301 if (eap->force_ff != 0)
18302 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
18303 eap->cmd + eap->force_ff);
18304 # ifdef FEAT_MBYTE
18305 if (eap->force_enc != 0)
18306 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
18307 eap->cmd + eap->force_enc);
18308 if (eap->bad_char != 0)
18309 sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
18310 eap->cmd + eap->bad_char);
18311 # endif
18312 vimvars[VV_CMDARG].vv_str = newval;
18313 return oldval;
18315 #endif
18318 * Get the value of internal variable "name".
18319 * Return OK or FAIL.
18321 static int
18322 get_var_tv(name, len, rettv, verbose)
18323 char_u *name;
18324 int len; /* length of "name" */
18325 typval_T *rettv; /* NULL when only checking existence */
18326 int verbose; /* may give error message */
18328 int ret = OK;
18329 typval_T *tv = NULL;
18330 typval_T atv;
18331 dictitem_T *v;
18332 int cc;
18334 /* truncate the name, so that we can use strcmp() */
18335 cc = name[len];
18336 name[len] = NUL;
18339 * Check for "b:changedtick".
18341 if (STRCMP(name, "b:changedtick") == 0)
18343 atv.v_type = VAR_NUMBER;
18344 atv.vval.v_number = curbuf->b_changedtick;
18345 tv = &atv;
18349 * Check for user-defined variables.
18351 else
18353 v = find_var(name, NULL);
18354 if (v != NULL)
18355 tv = &v->di_tv;
18358 if (tv == NULL)
18360 if (rettv != NULL && verbose)
18361 EMSG2(_(e_undefvar), name);
18362 ret = FAIL;
18364 else if (rettv != NULL)
18365 copy_tv(tv, rettv);
18367 name[len] = cc;
18369 return ret;
18373 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
18374 * Also handle function call with Funcref variable: func(expr)
18375 * Can all be combined: dict.func(expr)[idx]['func'](expr)
18377 static int
18378 handle_subscript(arg, rettv, evaluate, verbose)
18379 char_u **arg;
18380 typval_T *rettv;
18381 int evaluate; /* do more than finding the end */
18382 int verbose; /* give error messages */
18384 int ret = OK;
18385 dict_T *selfdict = NULL;
18386 char_u *s;
18387 int len;
18388 typval_T functv;
18390 while (ret == OK
18391 && (**arg == '['
18392 || (**arg == '.' && rettv->v_type == VAR_DICT)
18393 || (**arg == '(' && rettv->v_type == VAR_FUNC))
18394 && !vim_iswhite(*(*arg - 1)))
18396 if (**arg == '(')
18398 /* need to copy the funcref so that we can clear rettv */
18399 functv = *rettv;
18400 rettv->v_type = VAR_UNKNOWN;
18402 /* Invoke the function. Recursive! */
18403 s = functv.vval.v_string;
18404 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
18405 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
18406 &len, evaluate, selfdict);
18408 /* Clear the funcref afterwards, so that deleting it while
18409 * evaluating the arguments is possible (see test55). */
18410 clear_tv(&functv);
18412 /* Stop the expression evaluation when immediately aborting on
18413 * error, or when an interrupt occurred or an exception was thrown
18414 * but not caught. */
18415 if (aborting())
18417 if (ret == OK)
18418 clear_tv(rettv);
18419 ret = FAIL;
18421 dict_unref(selfdict);
18422 selfdict = NULL;
18424 else /* **arg == '[' || **arg == '.' */
18426 dict_unref(selfdict);
18427 if (rettv->v_type == VAR_DICT)
18429 selfdict = rettv->vval.v_dict;
18430 if (selfdict != NULL)
18431 ++selfdict->dv_refcount;
18433 else
18434 selfdict = NULL;
18435 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
18437 clear_tv(rettv);
18438 ret = FAIL;
18442 dict_unref(selfdict);
18443 return ret;
18447 * Allocate memory for a variable type-value, and make it empty (0 or NULL
18448 * value).
18450 static typval_T *
18451 alloc_tv()
18453 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
18457 * Allocate memory for a variable type-value, and assign a string to it.
18458 * The string "s" must have been allocated, it is consumed.
18459 * Return NULL for out of memory, the variable otherwise.
18461 static typval_T *
18462 alloc_string_tv(s)
18463 char_u *s;
18465 typval_T *rettv;
18467 rettv = alloc_tv();
18468 if (rettv != NULL)
18470 rettv->v_type = VAR_STRING;
18471 rettv->vval.v_string = s;
18473 else
18474 vim_free(s);
18475 return rettv;
18479 * Free the memory for a variable type-value.
18481 void
18482 free_tv(varp)
18483 typval_T *varp;
18485 if (varp != NULL)
18487 switch (varp->v_type)
18489 case VAR_FUNC:
18490 func_unref(varp->vval.v_string);
18491 /*FALLTHROUGH*/
18492 case VAR_STRING:
18493 vim_free(varp->vval.v_string);
18494 break;
18495 case VAR_LIST:
18496 list_unref(varp->vval.v_list);
18497 break;
18498 case VAR_DICT:
18499 dict_unref(varp->vval.v_dict);
18500 break;
18501 case VAR_NUMBER:
18502 #ifdef FEAT_FLOAT
18503 case VAR_FLOAT:
18504 #endif
18505 case VAR_UNKNOWN:
18506 break;
18507 default:
18508 EMSG2(_(e_intern2), "free_tv()");
18509 break;
18511 vim_free(varp);
18516 * Free the memory for a variable value and set the value to NULL or 0.
18518 void
18519 clear_tv(varp)
18520 typval_T *varp;
18522 if (varp != NULL)
18524 switch (varp->v_type)
18526 case VAR_FUNC:
18527 func_unref(varp->vval.v_string);
18528 /*FALLTHROUGH*/
18529 case VAR_STRING:
18530 vim_free(varp->vval.v_string);
18531 varp->vval.v_string = NULL;
18532 break;
18533 case VAR_LIST:
18534 list_unref(varp->vval.v_list);
18535 varp->vval.v_list = NULL;
18536 break;
18537 case VAR_DICT:
18538 dict_unref(varp->vval.v_dict);
18539 varp->vval.v_dict = NULL;
18540 break;
18541 case VAR_NUMBER:
18542 varp->vval.v_number = 0;
18543 break;
18544 #ifdef FEAT_FLOAT
18545 case VAR_FLOAT:
18546 varp->vval.v_float = 0.0;
18547 break;
18548 #endif
18549 case VAR_UNKNOWN:
18550 break;
18551 default:
18552 EMSG2(_(e_intern2), "clear_tv()");
18554 varp->v_lock = 0;
18559 * Set the value of a variable to NULL without freeing items.
18561 static void
18562 init_tv(varp)
18563 typval_T *varp;
18565 if (varp != NULL)
18566 vim_memset(varp, 0, sizeof(typval_T));
18570 * Get the number value of a variable.
18571 * If it is a String variable, uses vim_str2nr().
18572 * For incompatible types, return 0.
18573 * get_tv_number_chk() is similar to get_tv_number(), but informs the
18574 * caller of incompatible types: it sets *denote to TRUE if "denote"
18575 * is not NULL or returns -1 otherwise.
18577 static long
18578 get_tv_number(varp)
18579 typval_T *varp;
18581 int error = FALSE;
18583 return get_tv_number_chk(varp, &error); /* return 0L on error */
18586 long
18587 get_tv_number_chk(varp, denote)
18588 typval_T *varp;
18589 int *denote;
18591 long n = 0L;
18593 switch (varp->v_type)
18595 case VAR_NUMBER:
18596 return (long)(varp->vval.v_number);
18597 #ifdef FEAT_FLOAT
18598 case VAR_FLOAT:
18599 EMSG(_("E805: Using a Float as a Number"));
18600 break;
18601 #endif
18602 case VAR_FUNC:
18603 EMSG(_("E703: Using a Funcref as a Number"));
18604 break;
18605 case VAR_STRING:
18606 if (varp->vval.v_string != NULL)
18607 vim_str2nr(varp->vval.v_string, NULL, NULL,
18608 TRUE, TRUE, &n, NULL);
18609 return n;
18610 case VAR_LIST:
18611 EMSG(_("E745: Using a List as a Number"));
18612 break;
18613 case VAR_DICT:
18614 EMSG(_("E728: Using a Dictionary as a Number"));
18615 break;
18616 default:
18617 EMSG2(_(e_intern2), "get_tv_number()");
18618 break;
18620 if (denote == NULL) /* useful for values that must be unsigned */
18621 n = -1;
18622 else
18623 *denote = TRUE;
18624 return n;
18628 * Get the lnum from the first argument.
18629 * Also accepts ".", "$", etc., but that only works for the current buffer.
18630 * Returns -1 on error.
18632 static linenr_T
18633 get_tv_lnum(argvars)
18634 typval_T *argvars;
18636 typval_T rettv;
18637 linenr_T lnum;
18639 lnum = get_tv_number_chk(&argvars[0], NULL);
18640 if (lnum == 0) /* no valid number, try using line() */
18642 rettv.v_type = VAR_NUMBER;
18643 f_line(argvars, &rettv);
18644 lnum = rettv.vval.v_number;
18645 clear_tv(&rettv);
18647 return lnum;
18651 * Get the lnum from the first argument.
18652 * Also accepts "$", then "buf" is used.
18653 * Returns 0 on error.
18655 static linenr_T
18656 get_tv_lnum_buf(argvars, buf)
18657 typval_T *argvars;
18658 buf_T *buf;
18660 if (argvars[0].v_type == VAR_STRING
18661 && argvars[0].vval.v_string != NULL
18662 && argvars[0].vval.v_string[0] == '$'
18663 && buf != NULL)
18664 return buf->b_ml.ml_line_count;
18665 return get_tv_number_chk(&argvars[0], NULL);
18669 * Get the string value of a variable.
18670 * If it is a Number variable, the number is converted into a string.
18671 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
18672 * get_tv_string_buf() uses a given buffer.
18673 * If the String variable has never been set, return an empty string.
18674 * Never returns NULL;
18675 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
18676 * NULL on error.
18678 static char_u *
18679 get_tv_string(varp)
18680 typval_T *varp;
18682 static char_u mybuf[NUMBUFLEN];
18684 return get_tv_string_buf(varp, mybuf);
18687 static char_u *
18688 get_tv_string_buf(varp, buf)
18689 typval_T *varp;
18690 char_u *buf;
18692 char_u *res = get_tv_string_buf_chk(varp, buf);
18694 return res != NULL ? res : (char_u *)"";
18697 char_u *
18698 get_tv_string_chk(varp)
18699 typval_T *varp;
18701 static char_u mybuf[NUMBUFLEN];
18703 return get_tv_string_buf_chk(varp, mybuf);
18706 static char_u *
18707 get_tv_string_buf_chk(varp, buf)
18708 typval_T *varp;
18709 char_u *buf;
18711 switch (varp->v_type)
18713 case VAR_NUMBER:
18714 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
18715 return buf;
18716 case VAR_FUNC:
18717 EMSG(_("E729: using Funcref as a String"));
18718 break;
18719 case VAR_LIST:
18720 EMSG(_("E730: using List as a String"));
18721 break;
18722 case VAR_DICT:
18723 EMSG(_("E731: using Dictionary as a String"));
18724 break;
18725 #ifdef FEAT_FLOAT
18726 case VAR_FLOAT:
18727 EMSG(_("E806: using Float as a String"));
18728 break;
18729 #endif
18730 case VAR_STRING:
18731 if (varp->vval.v_string != NULL)
18732 return varp->vval.v_string;
18733 return (char_u *)"";
18734 default:
18735 EMSG2(_(e_intern2), "get_tv_string_buf()");
18736 break;
18738 return NULL;
18742 * Find variable "name" in the list of variables.
18743 * Return a pointer to it if found, NULL if not found.
18744 * Careful: "a:0" variables don't have a name.
18745 * When "htp" is not NULL we are writing to the variable, set "htp" to the
18746 * hashtab_T used.
18748 static dictitem_T *
18749 find_var(name, htp)
18750 char_u *name;
18751 hashtab_T **htp;
18753 char_u *varname;
18754 hashtab_T *ht;
18756 ht = find_var_ht(name, &varname);
18757 if (htp != NULL)
18758 *htp = ht;
18759 if (ht == NULL)
18760 return NULL;
18761 return find_var_in_ht(ht, varname, htp != NULL);
18765 * Find variable "varname" in hashtab "ht".
18766 * Returns NULL if not found.
18768 static dictitem_T *
18769 find_var_in_ht(ht, varname, writing)
18770 hashtab_T *ht;
18771 char_u *varname;
18772 int writing;
18774 hashitem_T *hi;
18776 if (*varname == NUL)
18778 /* Must be something like "s:", otherwise "ht" would be NULL. */
18779 switch (varname[-2])
18781 case 's': return &SCRIPT_SV(current_SID).sv_var;
18782 case 'g': return &globvars_var;
18783 case 'v': return &vimvars_var;
18784 case 'b': return &curbuf->b_bufvar;
18785 case 'w': return &curwin->w_winvar;
18786 #ifdef FEAT_WINDOWS
18787 case 't': return &curtab->tp_winvar;
18788 #endif
18789 case 'l': return current_funccal == NULL
18790 ? NULL : &current_funccal->l_vars_var;
18791 case 'a': return current_funccal == NULL
18792 ? NULL : &current_funccal->l_avars_var;
18794 return NULL;
18797 hi = hash_find(ht, varname);
18798 if (HASHITEM_EMPTY(hi))
18800 /* For global variables we may try auto-loading the script. If it
18801 * worked find the variable again. Don't auto-load a script if it was
18802 * loaded already, otherwise it would be loaded every time when
18803 * checking if a function name is a Funcref variable. */
18804 if (ht == &globvarht && !writing
18805 && script_autoload(varname, FALSE) && !aborting())
18806 hi = hash_find(ht, varname);
18807 if (HASHITEM_EMPTY(hi))
18808 return NULL;
18810 return HI2DI(hi);
18814 * Find the hashtab used for a variable name.
18815 * Set "varname" to the start of name without ':'.
18817 static hashtab_T *
18818 find_var_ht(name, varname)
18819 char_u *name;
18820 char_u **varname;
18822 hashitem_T *hi;
18824 if (name[1] != ':')
18826 /* The name must not start with a colon or #. */
18827 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
18828 return NULL;
18829 *varname = name;
18831 /* "version" is "v:version" in all scopes */
18832 hi = hash_find(&compat_hashtab, name);
18833 if (!HASHITEM_EMPTY(hi))
18834 return &compat_hashtab;
18836 if (current_funccal == NULL)
18837 return &globvarht; /* global variable */
18838 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
18840 *varname = name + 2;
18841 if (*name == 'g') /* global variable */
18842 return &globvarht;
18843 /* There must be no ':' or '#' in the rest of the name, unless g: is used
18845 if (vim_strchr(name + 2, ':') != NULL
18846 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
18847 return NULL;
18848 if (*name == 'b') /* buffer variable */
18849 return &curbuf->b_vars.dv_hashtab;
18850 if (*name == 'w') /* window variable */
18851 return &curwin->w_vars.dv_hashtab;
18852 #ifdef FEAT_WINDOWS
18853 if (*name == 't') /* tab page variable */
18854 return &curtab->tp_vars.dv_hashtab;
18855 #endif
18856 if (*name == 'v') /* v: variable */
18857 return &vimvarht;
18858 if (*name == 'a' && current_funccal != NULL) /* function argument */
18859 return &current_funccal->l_avars.dv_hashtab;
18860 if (*name == 'l' && current_funccal != NULL) /* local function variable */
18861 return &current_funccal->l_vars.dv_hashtab;
18862 if (*name == 's' /* script variable */
18863 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
18864 return &SCRIPT_VARS(current_SID);
18865 return NULL;
18869 * Get the string value of a (global/local) variable.
18870 * Returns NULL when it doesn't exist.
18872 char_u *
18873 get_var_value(name)
18874 char_u *name;
18876 dictitem_T *v;
18878 v = find_var(name, NULL);
18879 if (v == NULL)
18880 return NULL;
18881 return get_tv_string(&v->di_tv);
18885 * Allocate a new hashtab for a sourced script. It will be used while
18886 * sourcing this script and when executing functions defined in the script.
18888 void
18889 new_script_vars(id)
18890 scid_T id;
18892 int i;
18893 hashtab_T *ht;
18894 scriptvar_T *sv;
18896 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
18898 /* Re-allocating ga_data means that an ht_array pointing to
18899 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
18900 * at its init value. Also reset "v_dict", it's always the same. */
18901 for (i = 1; i <= ga_scripts.ga_len; ++i)
18903 ht = &SCRIPT_VARS(i);
18904 if (ht->ht_mask == HT_INIT_SIZE - 1)
18905 ht->ht_array = ht->ht_smallarray;
18906 sv = &SCRIPT_SV(i);
18907 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
18910 while (ga_scripts.ga_len < id)
18912 sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
18913 init_var_dict(&sv->sv_dict, &sv->sv_var);
18914 ++ga_scripts.ga_len;
18920 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
18921 * point to it.
18923 void
18924 init_var_dict(dict, dict_var)
18925 dict_T *dict;
18926 dictitem_T *dict_var;
18928 hash_init(&dict->dv_hashtab);
18929 dict->dv_refcount = DO_NOT_FREE_CNT;
18930 dict_var->di_tv.vval.v_dict = dict;
18931 dict_var->di_tv.v_type = VAR_DICT;
18932 dict_var->di_tv.v_lock = VAR_FIXED;
18933 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
18934 dict_var->di_key[0] = NUL;
18938 * Clean up a list of internal variables.
18939 * Frees all allocated variables and the value they contain.
18940 * Clears hashtab "ht", does not free it.
18942 void
18943 vars_clear(ht)
18944 hashtab_T *ht;
18946 vars_clear_ext(ht, TRUE);
18950 * Like vars_clear(), but only free the value if "free_val" is TRUE.
18952 static void
18953 vars_clear_ext(ht, free_val)
18954 hashtab_T *ht;
18955 int free_val;
18957 int todo;
18958 hashitem_T *hi;
18959 dictitem_T *v;
18961 hash_lock(ht);
18962 todo = (int)ht->ht_used;
18963 for (hi = ht->ht_array; todo > 0; ++hi)
18965 if (!HASHITEM_EMPTY(hi))
18967 --todo;
18969 /* Free the variable. Don't remove it from the hashtab,
18970 * ht_array might change then. hash_clear() takes care of it
18971 * later. */
18972 v = HI2DI(hi);
18973 if (free_val)
18974 clear_tv(&v->di_tv);
18975 if ((v->di_flags & DI_FLAGS_FIX) == 0)
18976 vim_free(v);
18979 hash_clear(ht);
18980 ht->ht_used = 0;
18984 * Delete a variable from hashtab "ht" at item "hi".
18985 * Clear the variable value and free the dictitem.
18987 static void
18988 delete_var(ht, hi)
18989 hashtab_T *ht;
18990 hashitem_T *hi;
18992 dictitem_T *di = HI2DI(hi);
18994 hash_remove(ht, hi);
18995 clear_tv(&di->di_tv);
18996 vim_free(di);
19000 * List the value of one internal variable.
19002 static void
19003 list_one_var(v, prefix, first)
19004 dictitem_T *v;
19005 char_u *prefix;
19006 int *first;
19008 char_u *tofree;
19009 char_u *s;
19010 char_u numbuf[NUMBUFLEN];
19012 s = echo_string(&v->di_tv, &tofree, numbuf, ++current_copyID);
19013 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
19014 s == NULL ? (char_u *)"" : s, first);
19015 vim_free(tofree);
19018 static void
19019 list_one_var_a(prefix, name, type, string, first)
19020 char_u *prefix;
19021 char_u *name;
19022 int type;
19023 char_u *string;
19024 int *first; /* when TRUE clear rest of screen and set to FALSE */
19026 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
19027 msg_start();
19028 msg_puts(prefix);
19029 if (name != NULL) /* "a:" vars don't have a name stored */
19030 msg_puts(name);
19031 msg_putchar(' ');
19032 msg_advance(22);
19033 if (type == VAR_NUMBER)
19034 msg_putchar('#');
19035 else if (type == VAR_FUNC)
19036 msg_putchar('*');
19037 else if (type == VAR_LIST)
19039 msg_putchar('[');
19040 if (*string == '[')
19041 ++string;
19043 else if (type == VAR_DICT)
19045 msg_putchar('{');
19046 if (*string == '{')
19047 ++string;
19049 else
19050 msg_putchar(' ');
19052 msg_outtrans(string);
19054 if (type == VAR_FUNC)
19055 msg_puts((char_u *)"()");
19056 if (*first)
19058 msg_clr_eos();
19059 *first = FALSE;
19064 * Set variable "name" to value in "tv".
19065 * If the variable already exists, the value is updated.
19066 * Otherwise the variable is created.
19068 static void
19069 set_var(name, tv, copy)
19070 char_u *name;
19071 typval_T *tv;
19072 int copy; /* make copy of value in "tv" */
19074 dictitem_T *v;
19075 char_u *varname;
19076 hashtab_T *ht;
19077 char_u *p;
19079 if (tv->v_type == VAR_FUNC)
19081 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
19082 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
19083 ? name[2] : name[0]))
19085 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
19086 return;
19088 if (function_exists(name))
19090 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
19091 name);
19092 return;
19096 ht = find_var_ht(name, &varname);
19097 if (ht == NULL || *varname == NUL)
19099 EMSG2(_(e_illvar), name);
19100 return;
19103 v = find_var_in_ht(ht, varname, TRUE);
19104 if (v != NULL)
19106 /* existing variable, need to clear the value */
19107 if (var_check_ro(v->di_flags, name)
19108 || tv_check_lock(v->di_tv.v_lock, name))
19109 return;
19110 if (v->di_tv.v_type != tv->v_type
19111 && !((v->di_tv.v_type == VAR_STRING
19112 || v->di_tv.v_type == VAR_NUMBER)
19113 && (tv->v_type == VAR_STRING
19114 || tv->v_type == VAR_NUMBER))
19115 #ifdef FEAT_FLOAT
19116 && !((v->di_tv.v_type == VAR_NUMBER
19117 || v->di_tv.v_type == VAR_FLOAT)
19118 && (tv->v_type == VAR_NUMBER
19119 || tv->v_type == VAR_FLOAT))
19120 #endif
19123 EMSG2(_("E706: Variable type mismatch for: %s"), name);
19124 return;
19128 * Handle setting internal v: variables separately: we don't change
19129 * the type.
19131 if (ht == &vimvarht)
19133 if (v->di_tv.v_type == VAR_STRING)
19135 vim_free(v->di_tv.vval.v_string);
19136 if (copy || tv->v_type != VAR_STRING)
19137 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
19138 else
19140 /* Take over the string to avoid an extra alloc/free. */
19141 v->di_tv.vval.v_string = tv->vval.v_string;
19142 tv->vval.v_string = NULL;
19145 else if (v->di_tv.v_type != VAR_NUMBER)
19146 EMSG2(_(e_intern2), "set_var()");
19147 else
19149 v->di_tv.vval.v_number = get_tv_number(tv);
19150 if (STRCMP(varname, "searchforward") == 0)
19151 set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
19153 return;
19156 clear_tv(&v->di_tv);
19158 else /* add a new variable */
19160 /* Can't add "v:" variable. */
19161 if (ht == &vimvarht)
19163 EMSG2(_(e_illvar), name);
19164 return;
19167 /* Make sure the variable name is valid. */
19168 for (p = varname; *p != NUL; ++p)
19169 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
19170 && *p != AUTOLOAD_CHAR)
19172 EMSG2(_(e_illvar), varname);
19173 return;
19176 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
19177 + STRLEN(varname)));
19178 if (v == NULL)
19179 return;
19180 STRCPY(v->di_key, varname);
19181 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
19183 vim_free(v);
19184 return;
19186 v->di_flags = 0;
19189 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
19190 copy_tv(tv, &v->di_tv);
19191 else
19193 v->di_tv = *tv;
19194 v->di_tv.v_lock = 0;
19195 init_tv(tv);
19200 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
19201 * Also give an error message.
19203 static int
19204 var_check_ro(flags, name)
19205 int flags;
19206 char_u *name;
19208 if (flags & DI_FLAGS_RO)
19210 EMSG2(_(e_readonlyvar), name);
19211 return TRUE;
19213 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
19215 EMSG2(_(e_readonlysbx), name);
19216 return TRUE;
19218 return FALSE;
19222 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
19223 * Also give an error message.
19225 static int
19226 var_check_fixed(flags, name)
19227 int flags;
19228 char_u *name;
19230 if (flags & DI_FLAGS_FIX)
19232 EMSG2(_("E795: Cannot delete variable %s"), name);
19233 return TRUE;
19235 return FALSE;
19239 * Return TRUE if typeval "tv" is set to be locked (immutable).
19240 * Also give an error message, using "name".
19242 static int
19243 tv_check_lock(lock, name)
19244 int lock;
19245 char_u *name;
19247 if (lock & VAR_LOCKED)
19249 EMSG2(_("E741: Value is locked: %s"),
19250 name == NULL ? (char_u *)_("Unknown") : name);
19251 return TRUE;
19253 if (lock & VAR_FIXED)
19255 EMSG2(_("E742: Cannot change value of %s"),
19256 name == NULL ? (char_u *)_("Unknown") : name);
19257 return TRUE;
19259 return FALSE;
19263 * Copy the values from typval_T "from" to typval_T "to".
19264 * When needed allocates string or increases reference count.
19265 * Does not make a copy of a list or dict but copies the reference!
19266 * It is OK for "from" and "to" to point to the same item. This is used to
19267 * make a copy later.
19269 static void
19270 copy_tv(from, to)
19271 typval_T *from;
19272 typval_T *to;
19274 to->v_type = from->v_type;
19275 to->v_lock = 0;
19276 switch (from->v_type)
19278 case VAR_NUMBER:
19279 to->vval.v_number = from->vval.v_number;
19280 break;
19281 #ifdef FEAT_FLOAT
19282 case VAR_FLOAT:
19283 to->vval.v_float = from->vval.v_float;
19284 break;
19285 #endif
19286 case VAR_STRING:
19287 case VAR_FUNC:
19288 if (from->vval.v_string == NULL)
19289 to->vval.v_string = NULL;
19290 else
19292 to->vval.v_string = vim_strsave(from->vval.v_string);
19293 if (from->v_type == VAR_FUNC)
19294 func_ref(to->vval.v_string);
19296 break;
19297 case VAR_LIST:
19298 if (from->vval.v_list == NULL)
19299 to->vval.v_list = NULL;
19300 else
19302 to->vval.v_list = from->vval.v_list;
19303 ++to->vval.v_list->lv_refcount;
19305 break;
19306 case VAR_DICT:
19307 if (from->vval.v_dict == NULL)
19308 to->vval.v_dict = NULL;
19309 else
19311 to->vval.v_dict = from->vval.v_dict;
19312 ++to->vval.v_dict->dv_refcount;
19314 break;
19315 default:
19316 EMSG2(_(e_intern2), "copy_tv()");
19317 break;
19322 * Make a copy of an item.
19323 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
19324 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
19325 * reference to an already copied list/dict can be used.
19326 * Returns FAIL or OK.
19328 static int
19329 item_copy(from, to, deep, copyID)
19330 typval_T *from;
19331 typval_T *to;
19332 int deep;
19333 int copyID;
19335 static int recurse = 0;
19336 int ret = OK;
19338 if (recurse >= DICT_MAXNEST)
19340 EMSG(_("E698: variable nested too deep for making a copy"));
19341 return FAIL;
19343 ++recurse;
19345 switch (from->v_type)
19347 case VAR_NUMBER:
19348 #ifdef FEAT_FLOAT
19349 case VAR_FLOAT:
19350 #endif
19351 case VAR_STRING:
19352 case VAR_FUNC:
19353 copy_tv(from, to);
19354 break;
19355 case VAR_LIST:
19356 to->v_type = VAR_LIST;
19357 to->v_lock = 0;
19358 if (from->vval.v_list == NULL)
19359 to->vval.v_list = NULL;
19360 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
19362 /* use the copy made earlier */
19363 to->vval.v_list = from->vval.v_list->lv_copylist;
19364 ++to->vval.v_list->lv_refcount;
19366 else
19367 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
19368 if (to->vval.v_list == NULL)
19369 ret = FAIL;
19370 break;
19371 case VAR_DICT:
19372 to->v_type = VAR_DICT;
19373 to->v_lock = 0;
19374 if (from->vval.v_dict == NULL)
19375 to->vval.v_dict = NULL;
19376 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
19378 /* use the copy made earlier */
19379 to->vval.v_dict = from->vval.v_dict->dv_copydict;
19380 ++to->vval.v_dict->dv_refcount;
19382 else
19383 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
19384 if (to->vval.v_dict == NULL)
19385 ret = FAIL;
19386 break;
19387 default:
19388 EMSG2(_(e_intern2), "item_copy()");
19389 ret = FAIL;
19391 --recurse;
19392 return ret;
19396 * ":echo expr1 ..." print each argument separated with a space, add a
19397 * newline at the end.
19398 * ":echon expr1 ..." print each argument plain.
19400 void
19401 ex_echo(eap)
19402 exarg_T *eap;
19404 char_u *arg = eap->arg;
19405 typval_T rettv;
19406 char_u *tofree;
19407 char_u *p;
19408 int needclr = TRUE;
19409 int atstart = TRUE;
19410 char_u numbuf[NUMBUFLEN];
19412 if (eap->skip)
19413 ++emsg_skip;
19414 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
19416 /* If eval1() causes an error message the text from the command may
19417 * still need to be cleared. E.g., "echo 22,44". */
19418 need_clr_eos = needclr;
19420 p = arg;
19421 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19424 * Report the invalid expression unless the expression evaluation
19425 * has been cancelled due to an aborting error, an interrupt, or an
19426 * exception.
19428 if (!aborting())
19429 EMSG2(_(e_invexpr2), p);
19430 need_clr_eos = FALSE;
19431 break;
19433 need_clr_eos = FALSE;
19435 if (!eap->skip)
19437 if (atstart)
19439 atstart = FALSE;
19440 /* Call msg_start() after eval1(), evaluating the expression
19441 * may cause a message to appear. */
19442 if (eap->cmdidx == CMD_echo)
19443 msg_start();
19445 else if (eap->cmdidx == CMD_echo)
19446 msg_puts_attr((char_u *)" ", echo_attr);
19447 p = echo_string(&rettv, &tofree, numbuf, ++current_copyID);
19448 if (p != NULL)
19449 for ( ; *p != NUL && !got_int; ++p)
19451 if (*p == '\n' || *p == '\r' || *p == TAB)
19453 if (*p != TAB && needclr)
19455 /* remove any text still there from the command */
19456 msg_clr_eos();
19457 needclr = FALSE;
19459 msg_putchar_attr(*p, echo_attr);
19461 else
19463 #ifdef FEAT_MBYTE
19464 if (has_mbyte)
19466 int i = (*mb_ptr2len)(p);
19468 (void)msg_outtrans_len_attr(p, i, echo_attr);
19469 p += i - 1;
19471 else
19472 #endif
19473 (void)msg_outtrans_len_attr(p, 1, echo_attr);
19476 vim_free(tofree);
19478 clear_tv(&rettv);
19479 arg = skipwhite(arg);
19481 eap->nextcmd = check_nextcmd(arg);
19483 if (eap->skip)
19484 --emsg_skip;
19485 else
19487 /* remove text that may still be there from the command */
19488 if (needclr)
19489 msg_clr_eos();
19490 if (eap->cmdidx == CMD_echo)
19491 msg_end();
19496 * ":echohl {name}".
19498 void
19499 ex_echohl(eap)
19500 exarg_T *eap;
19502 int id;
19504 id = syn_name2id(eap->arg);
19505 if (id == 0)
19506 echo_attr = 0;
19507 else
19508 echo_attr = syn_id2attr(id);
19512 * ":execute expr1 ..." execute the result of an expression.
19513 * ":echomsg expr1 ..." Print a message
19514 * ":echoerr expr1 ..." Print an error
19515 * Each gets spaces around each argument and a newline at the end for
19516 * echo commands
19518 void
19519 ex_execute(eap)
19520 exarg_T *eap;
19522 char_u *arg = eap->arg;
19523 typval_T rettv;
19524 int ret = OK;
19525 char_u *p;
19526 garray_T ga;
19527 int len;
19528 int save_did_emsg;
19530 ga_init2(&ga, 1, 80);
19532 if (eap->skip)
19533 ++emsg_skip;
19534 while (*arg != NUL && *arg != '|' && *arg != '\n')
19536 p = arg;
19537 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19540 * Report the invalid expression unless the expression evaluation
19541 * has been cancelled due to an aborting error, an interrupt, or an
19542 * exception.
19544 if (!aborting())
19545 EMSG2(_(e_invexpr2), p);
19546 ret = FAIL;
19547 break;
19550 if (!eap->skip)
19552 p = get_tv_string(&rettv);
19553 len = (int)STRLEN(p);
19554 if (ga_grow(&ga, len + 2) == FAIL)
19556 clear_tv(&rettv);
19557 ret = FAIL;
19558 break;
19560 if (ga.ga_len)
19561 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
19562 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
19563 ga.ga_len += len;
19566 clear_tv(&rettv);
19567 arg = skipwhite(arg);
19570 if (ret != FAIL && ga.ga_data != NULL)
19572 if (eap->cmdidx == CMD_echomsg)
19574 MSG_ATTR(ga.ga_data, echo_attr);
19575 out_flush();
19577 else if (eap->cmdidx == CMD_echoerr)
19579 /* We don't want to abort following commands, restore did_emsg. */
19580 save_did_emsg = did_emsg;
19581 EMSG((char_u *)ga.ga_data);
19582 if (!force_abort)
19583 did_emsg = save_did_emsg;
19585 else if (eap->cmdidx == CMD_execute)
19586 do_cmdline((char_u *)ga.ga_data,
19587 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
19590 ga_clear(&ga);
19592 if (eap->skip)
19593 --emsg_skip;
19595 eap->nextcmd = check_nextcmd(arg);
19599 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
19600 * "arg" points to the "&" or '+' when called, to "option" when returning.
19601 * Returns NULL when no option name found. Otherwise pointer to the char
19602 * after the option name.
19604 static char_u *
19605 find_option_end(arg, opt_flags)
19606 char_u **arg;
19607 int *opt_flags;
19609 char_u *p = *arg;
19611 ++p;
19612 if (*p == 'g' && p[1] == ':')
19614 *opt_flags = OPT_GLOBAL;
19615 p += 2;
19617 else if (*p == 'l' && p[1] == ':')
19619 *opt_flags = OPT_LOCAL;
19620 p += 2;
19622 else
19623 *opt_flags = 0;
19625 if (!ASCII_ISALPHA(*p))
19626 return NULL;
19627 *arg = p;
19629 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
19630 p += 4; /* termcap option */
19631 else
19632 while (ASCII_ISALPHA(*p))
19633 ++p;
19634 return p;
19638 * ":function"
19640 void
19641 ex_function(eap)
19642 exarg_T *eap;
19644 char_u *theline;
19645 int j;
19646 int c;
19647 int saved_did_emsg;
19648 char_u *name = NULL;
19649 char_u *p;
19650 char_u *arg;
19651 char_u *line_arg = NULL;
19652 garray_T newargs;
19653 garray_T newlines;
19654 int varargs = FALSE;
19655 int mustend = FALSE;
19656 int flags = 0;
19657 ufunc_T *fp;
19658 int indent;
19659 int nesting;
19660 char_u *skip_until = NULL;
19661 dictitem_T *v;
19662 funcdict_T fudi;
19663 static int func_nr = 0; /* number for nameless function */
19664 int paren;
19665 hashtab_T *ht;
19666 int todo;
19667 hashitem_T *hi;
19668 int sourcing_lnum_off;
19671 * ":function" without argument: list functions.
19673 if (ends_excmd(*eap->arg))
19675 if (!eap->skip)
19677 todo = (int)func_hashtab.ht_used;
19678 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19680 if (!HASHITEM_EMPTY(hi))
19682 --todo;
19683 fp = HI2UF(hi);
19684 if (!isdigit(*fp->uf_name))
19685 list_func_head(fp, FALSE);
19689 eap->nextcmd = check_nextcmd(eap->arg);
19690 return;
19694 * ":function /pat": list functions matching pattern.
19696 if (*eap->arg == '/')
19698 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
19699 if (!eap->skip)
19701 regmatch_T regmatch;
19703 c = *p;
19704 *p = NUL;
19705 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
19706 *p = c;
19707 if (regmatch.regprog != NULL)
19709 regmatch.rm_ic = p_ic;
19711 todo = (int)func_hashtab.ht_used;
19712 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19714 if (!HASHITEM_EMPTY(hi))
19716 --todo;
19717 fp = HI2UF(hi);
19718 if (!isdigit(*fp->uf_name)
19719 && vim_regexec(&regmatch, fp->uf_name, 0))
19720 list_func_head(fp, FALSE);
19723 vim_free(regmatch.regprog);
19726 if (*p == '/')
19727 ++p;
19728 eap->nextcmd = check_nextcmd(p);
19729 return;
19733 * Get the function name. There are these situations:
19734 * func normal function name
19735 * "name" == func, "fudi.fd_dict" == NULL
19736 * dict.func new dictionary entry
19737 * "name" == NULL, "fudi.fd_dict" set,
19738 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
19739 * dict.func existing dict entry with a Funcref
19740 * "name" == func, "fudi.fd_dict" set,
19741 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19742 * dict.func existing dict entry that's not a Funcref
19743 * "name" == NULL, "fudi.fd_dict" set,
19744 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19746 p = eap->arg;
19747 name = trans_function_name(&p, eap->skip, 0, &fudi);
19748 paren = (vim_strchr(p, '(') != NULL);
19749 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
19752 * Return on an invalid expression in braces, unless the expression
19753 * evaluation has been cancelled due to an aborting error, an
19754 * interrupt, or an exception.
19756 if (!aborting())
19758 if (!eap->skip && fudi.fd_newkey != NULL)
19759 EMSG2(_(e_dictkey), fudi.fd_newkey);
19760 vim_free(fudi.fd_newkey);
19761 return;
19763 else
19764 eap->skip = TRUE;
19767 /* An error in a function call during evaluation of an expression in magic
19768 * braces should not cause the function not to be defined. */
19769 saved_did_emsg = did_emsg;
19770 did_emsg = FALSE;
19773 * ":function func" with only function name: list function.
19775 if (!paren)
19777 if (!ends_excmd(*skipwhite(p)))
19779 EMSG(_(e_trailing));
19780 goto ret_free;
19782 eap->nextcmd = check_nextcmd(p);
19783 if (eap->nextcmd != NULL)
19784 *p = NUL;
19785 if (!eap->skip && !got_int)
19787 fp = find_func(name);
19788 if (fp != NULL)
19790 list_func_head(fp, TRUE);
19791 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
19793 if (FUNCLINE(fp, j) == NULL)
19794 continue;
19795 msg_putchar('\n');
19796 msg_outnum((long)(j + 1));
19797 if (j < 9)
19798 msg_putchar(' ');
19799 if (j < 99)
19800 msg_putchar(' ');
19801 msg_prt_line(FUNCLINE(fp, j), FALSE);
19802 out_flush(); /* show a line at a time */
19803 ui_breakcheck();
19805 if (!got_int)
19807 msg_putchar('\n');
19808 msg_puts((char_u *)" endfunction");
19811 else
19812 emsg_funcname(N_("E123: Undefined function: %s"), name);
19814 goto ret_free;
19818 * ":function name(arg1, arg2)" Define function.
19820 p = skipwhite(p);
19821 if (*p != '(')
19823 if (!eap->skip)
19825 EMSG2(_("E124: Missing '(': %s"), eap->arg);
19826 goto ret_free;
19828 /* attempt to continue by skipping some text */
19829 if (vim_strchr(p, '(') != NULL)
19830 p = vim_strchr(p, '(');
19832 p = skipwhite(p + 1);
19834 ga_init2(&newargs, (int)sizeof(char_u *), 3);
19835 ga_init2(&newlines, (int)sizeof(char_u *), 3);
19837 if (!eap->skip)
19839 /* Check the name of the function. Unless it's a dictionary function
19840 * (that we are overwriting). */
19841 if (name != NULL)
19842 arg = name;
19843 else
19844 arg = fudi.fd_newkey;
19845 if (arg != NULL && (fudi.fd_di == NULL
19846 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
19848 if (*arg == K_SPECIAL)
19849 j = 3;
19850 else
19851 j = 0;
19852 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
19853 : eval_isnamec(arg[j])))
19854 ++j;
19855 if (arg[j] != NUL)
19856 emsg_funcname((char *)e_invarg2, arg);
19861 * Isolate the arguments: "arg1, arg2, ...)"
19863 while (*p != ')')
19865 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
19867 varargs = TRUE;
19868 p += 3;
19869 mustend = TRUE;
19871 else
19873 arg = p;
19874 while (ASCII_ISALNUM(*p) || *p == '_')
19875 ++p;
19876 if (arg == p || isdigit(*arg)
19877 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
19878 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
19880 if (!eap->skip)
19881 EMSG2(_("E125: Illegal argument: %s"), arg);
19882 break;
19884 if (ga_grow(&newargs, 1) == FAIL)
19885 goto erret;
19886 c = *p;
19887 *p = NUL;
19888 arg = vim_strsave(arg);
19889 if (arg == NULL)
19890 goto erret;
19891 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
19892 *p = c;
19893 newargs.ga_len++;
19894 if (*p == ',')
19895 ++p;
19896 else
19897 mustend = TRUE;
19899 p = skipwhite(p);
19900 if (mustend && *p != ')')
19902 if (!eap->skip)
19903 EMSG2(_(e_invarg2), eap->arg);
19904 break;
19907 ++p; /* skip the ')' */
19909 /* find extra arguments "range", "dict" and "abort" */
19910 for (;;)
19912 p = skipwhite(p);
19913 if (STRNCMP(p, "range", 5) == 0)
19915 flags |= FC_RANGE;
19916 p += 5;
19918 else if (STRNCMP(p, "dict", 4) == 0)
19920 flags |= FC_DICT;
19921 p += 4;
19923 else if (STRNCMP(p, "abort", 5) == 0)
19925 flags |= FC_ABORT;
19926 p += 5;
19928 else
19929 break;
19932 /* When there is a line break use what follows for the function body.
19933 * Makes 'exe "func Test()\n...\nendfunc"' work. */
19934 if (*p == '\n')
19935 line_arg = p + 1;
19936 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
19937 EMSG(_(e_trailing));
19940 * Read the body of the function, until ":endfunction" is found.
19942 if (KeyTyped)
19944 /* Check if the function already exists, don't let the user type the
19945 * whole function before telling him it doesn't work! For a script we
19946 * need to skip the body to be able to find what follows. */
19947 if (!eap->skip && !eap->forceit)
19949 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
19950 EMSG(_(e_funcdict));
19951 else if (name != NULL && find_func(name) != NULL)
19952 emsg_funcname(e_funcexts, name);
19955 if (!eap->skip && did_emsg)
19956 goto erret;
19958 msg_putchar('\n'); /* don't overwrite the function name */
19959 cmdline_row = msg_row;
19962 indent = 2;
19963 nesting = 0;
19964 for (;;)
19966 msg_scroll = TRUE;
19967 need_wait_return = FALSE;
19968 sourcing_lnum_off = sourcing_lnum;
19970 if (line_arg != NULL)
19972 /* Use eap->arg, split up in parts by line breaks. */
19973 theline = line_arg;
19974 p = vim_strchr(theline, '\n');
19975 if (p == NULL)
19976 line_arg += STRLEN(line_arg);
19977 else
19979 *p = NUL;
19980 line_arg = p + 1;
19983 else if (eap->getline == NULL)
19984 theline = getcmdline(':', 0L, indent);
19985 else
19986 theline = eap->getline(':', eap->cookie, indent);
19987 if (KeyTyped)
19988 lines_left = Rows - 1;
19989 if (theline == NULL)
19991 EMSG(_("E126: Missing :endfunction"));
19992 goto erret;
19995 /* Detect line continuation: sourcing_lnum increased more than one. */
19996 if (sourcing_lnum > sourcing_lnum_off + 1)
19997 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
19998 else
19999 sourcing_lnum_off = 0;
20001 if (skip_until != NULL)
20003 /* between ":append" and "." and between ":python <<EOF" and "EOF"
20004 * don't check for ":endfunc". */
20005 if (STRCMP(theline, skip_until) == 0)
20007 vim_free(skip_until);
20008 skip_until = NULL;
20011 else
20013 /* skip ':' and blanks*/
20014 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
20017 /* Check for "endfunction". */
20018 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
20020 if (line_arg == NULL)
20021 vim_free(theline);
20022 break;
20025 /* Increase indent inside "if", "while", "for" and "try", decrease
20026 * at "end". */
20027 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
20028 indent -= 2;
20029 else if (STRNCMP(p, "if", 2) == 0
20030 || STRNCMP(p, "wh", 2) == 0
20031 || STRNCMP(p, "for", 3) == 0
20032 || STRNCMP(p, "try", 3) == 0)
20033 indent += 2;
20035 /* Check for defining a function inside this function. */
20036 if (checkforcmd(&p, "function", 2))
20038 if (*p == '!')
20039 p = skipwhite(p + 1);
20040 p += eval_fname_script(p);
20041 if (ASCII_ISALPHA(*p))
20043 vim_free(trans_function_name(&p, TRUE, 0, NULL));
20044 if (*skipwhite(p) == '(')
20046 ++nesting;
20047 indent += 2;
20052 /* Check for ":append" or ":insert". */
20053 p = skip_range(p, NULL);
20054 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
20055 || (p[0] == 'i'
20056 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
20057 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
20058 skip_until = vim_strsave((char_u *)".");
20060 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
20061 arg = skipwhite(skiptowhite(p));
20062 if (arg[0] == '<' && arg[1] =='<'
20063 && ((p[0] == 'p' && p[1] == 'y'
20064 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
20065 || (p[0] == 'p' && p[1] == 'e'
20066 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
20067 || (p[0] == 't' && p[1] == 'c'
20068 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
20069 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
20070 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
20071 || (p[0] == 'm' && p[1] == 'z'
20072 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
20075 /* ":python <<" continues until a dot, like ":append" */
20076 p = skipwhite(arg + 2);
20077 if (*p == NUL)
20078 skip_until = vim_strsave((char_u *)".");
20079 else
20080 skip_until = vim_strsave(p);
20084 /* Add the line to the function. */
20085 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
20087 if (line_arg == NULL)
20088 vim_free(theline);
20089 goto erret;
20092 /* Copy the line to newly allocated memory. get_one_sourceline()
20093 * allocates 250 bytes per line, this saves 80% on average. The cost
20094 * is an extra alloc/free. */
20095 p = vim_strsave(theline);
20096 if (p != NULL)
20098 if (line_arg == NULL)
20099 vim_free(theline);
20100 theline = p;
20103 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
20105 /* Add NULL lines for continuation lines, so that the line count is
20106 * equal to the index in the growarray. */
20107 while (sourcing_lnum_off-- > 0)
20108 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
20110 /* Check for end of eap->arg. */
20111 if (line_arg != NULL && *line_arg == NUL)
20112 line_arg = NULL;
20115 /* Don't define the function when skipping commands or when an error was
20116 * detected. */
20117 if (eap->skip || did_emsg)
20118 goto erret;
20121 * If there are no errors, add the function
20123 if (fudi.fd_dict == NULL)
20125 v = find_var(name, &ht);
20126 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
20128 emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
20129 name);
20130 goto erret;
20133 fp = find_func(name);
20134 if (fp != NULL)
20136 if (!eap->forceit)
20138 emsg_funcname(e_funcexts, name);
20139 goto erret;
20141 if (fp->uf_calls > 0)
20143 emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"),
20144 name);
20145 goto erret;
20147 /* redefine existing function */
20148 ga_clear_strings(&(fp->uf_args));
20149 ga_clear_strings(&(fp->uf_lines));
20150 vim_free(name);
20151 name = NULL;
20154 else
20156 char numbuf[20];
20158 fp = NULL;
20159 if (fudi.fd_newkey == NULL && !eap->forceit)
20161 EMSG(_(e_funcdict));
20162 goto erret;
20164 if (fudi.fd_di == NULL)
20166 /* Can't add a function to a locked dictionary */
20167 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
20168 goto erret;
20170 /* Can't change an existing function if it is locked */
20171 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
20172 goto erret;
20174 /* Give the function a sequential number. Can only be used with a
20175 * Funcref! */
20176 vim_free(name);
20177 sprintf(numbuf, "%d", ++func_nr);
20178 name = vim_strsave((char_u *)numbuf);
20179 if (name == NULL)
20180 goto erret;
20183 if (fp == NULL)
20185 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
20187 int slen, plen;
20188 char_u *scriptname;
20190 /* Check that the autoload name matches the script name. */
20191 j = FAIL;
20192 if (sourcing_name != NULL)
20194 scriptname = autoload_name(name);
20195 if (scriptname != NULL)
20197 p = vim_strchr(scriptname, '/');
20198 plen = (int)STRLEN(p);
20199 slen = (int)STRLEN(sourcing_name);
20200 if (slen > plen && fnamecmp(p,
20201 sourcing_name + slen - plen) == 0)
20202 j = OK;
20203 vim_free(scriptname);
20206 if (j == FAIL)
20208 EMSG2(_("E746: Function name does not match script file name: %s"), name);
20209 goto erret;
20213 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
20214 if (fp == NULL)
20215 goto erret;
20217 if (fudi.fd_dict != NULL)
20219 if (fudi.fd_di == NULL)
20221 /* add new dict entry */
20222 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
20223 if (fudi.fd_di == NULL)
20225 vim_free(fp);
20226 goto erret;
20228 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
20230 vim_free(fudi.fd_di);
20231 vim_free(fp);
20232 goto erret;
20235 else
20236 /* overwrite existing dict entry */
20237 clear_tv(&fudi.fd_di->di_tv);
20238 fudi.fd_di->di_tv.v_type = VAR_FUNC;
20239 fudi.fd_di->di_tv.v_lock = 0;
20240 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
20241 fp->uf_refcount = 1;
20243 /* behave like "dict" was used */
20244 flags |= FC_DICT;
20247 /* insert the new function in the function list */
20248 STRCPY(fp->uf_name, name);
20249 hash_add(&func_hashtab, UF2HIKEY(fp));
20251 fp->uf_args = newargs;
20252 fp->uf_lines = newlines;
20253 #ifdef FEAT_PROFILE
20254 fp->uf_tml_count = NULL;
20255 fp->uf_tml_total = NULL;
20256 fp->uf_tml_self = NULL;
20257 fp->uf_profiling = FALSE;
20258 if (prof_def_func())
20259 func_do_profile(fp);
20260 #endif
20261 fp->uf_varargs = varargs;
20262 fp->uf_flags = flags;
20263 fp->uf_calls = 0;
20264 fp->uf_script_ID = current_SID;
20265 goto ret_free;
20267 erret:
20268 ga_clear_strings(&newargs);
20269 ga_clear_strings(&newlines);
20270 ret_free:
20271 vim_free(skip_until);
20272 vim_free(fudi.fd_newkey);
20273 vim_free(name);
20274 did_emsg |= saved_did_emsg;
20278 * Get a function name, translating "<SID>" and "<SNR>".
20279 * Also handles a Funcref in a List or Dictionary.
20280 * Returns the function name in allocated memory, or NULL for failure.
20281 * flags:
20282 * TFN_INT: internal function name OK
20283 * TFN_QUIET: be quiet
20284 * Advances "pp" to just after the function name (if no error).
20286 static char_u *
20287 trans_function_name(pp, skip, flags, fdp)
20288 char_u **pp;
20289 int skip; /* only find the end, don't evaluate */
20290 int flags;
20291 funcdict_T *fdp; /* return: info about dictionary used */
20293 char_u *name = NULL;
20294 char_u *start;
20295 char_u *end;
20296 int lead;
20297 char_u sid_buf[20];
20298 int len;
20299 lval_T lv;
20301 if (fdp != NULL)
20302 vim_memset(fdp, 0, sizeof(funcdict_T));
20303 start = *pp;
20305 /* Check for hard coded <SNR>: already translated function ID (from a user
20306 * command). */
20307 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
20308 && (*pp)[2] == (int)KE_SNR)
20310 *pp += 3;
20311 len = get_id_len(pp) + 3;
20312 return vim_strnsave(start, len);
20315 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
20316 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
20317 lead = eval_fname_script(start);
20318 if (lead > 2)
20319 start += lead;
20321 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
20322 lead > 2 ? 0 : FNE_CHECK_START);
20323 if (end == start)
20325 if (!skip)
20326 EMSG(_("E129: Function name required"));
20327 goto theend;
20329 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
20332 * Report an invalid expression in braces, unless the expression
20333 * evaluation has been cancelled due to an aborting error, an
20334 * interrupt, or an exception.
20336 if (!aborting())
20338 if (end != NULL)
20339 EMSG2(_(e_invarg2), start);
20341 else
20342 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
20343 goto theend;
20346 if (lv.ll_tv != NULL)
20348 if (fdp != NULL)
20350 fdp->fd_dict = lv.ll_dict;
20351 fdp->fd_newkey = lv.ll_newkey;
20352 lv.ll_newkey = NULL;
20353 fdp->fd_di = lv.ll_di;
20355 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
20357 name = vim_strsave(lv.ll_tv->vval.v_string);
20358 *pp = end;
20360 else
20362 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
20363 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
20364 EMSG(_(e_funcref));
20365 else
20366 *pp = end;
20367 name = NULL;
20369 goto theend;
20372 if (lv.ll_name == NULL)
20374 /* Error found, but continue after the function name. */
20375 *pp = end;
20376 goto theend;
20379 /* Check if the name is a Funcref. If so, use the value. */
20380 if (lv.ll_exp_name != NULL)
20382 len = (int)STRLEN(lv.ll_exp_name);
20383 name = deref_func_name(lv.ll_exp_name, &len);
20384 if (name == lv.ll_exp_name)
20385 name = NULL;
20387 else
20389 len = (int)(end - *pp);
20390 name = deref_func_name(*pp, &len);
20391 if (name == *pp)
20392 name = NULL;
20394 if (name != NULL)
20396 name = vim_strsave(name);
20397 *pp = end;
20398 goto theend;
20401 if (lv.ll_exp_name != NULL)
20403 len = (int)STRLEN(lv.ll_exp_name);
20404 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
20405 && STRNCMP(lv.ll_name, "s:", 2) == 0)
20407 /* When there was "s:" already or the name expanded to get a
20408 * leading "s:" then remove it. */
20409 lv.ll_name += 2;
20410 len -= 2;
20411 lead = 2;
20414 else
20416 if (lead == 2) /* skip over "s:" */
20417 lv.ll_name += 2;
20418 len = (int)(end - lv.ll_name);
20422 * Copy the function name to allocated memory.
20423 * Accept <SID>name() inside a script, translate into <SNR>123_name().
20424 * Accept <SNR>123_name() outside a script.
20426 if (skip)
20427 lead = 0; /* do nothing */
20428 else if (lead > 0)
20430 lead = 3;
20431 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
20432 || eval_fname_sid(*pp))
20434 /* It's "s:" or "<SID>" */
20435 if (current_SID <= 0)
20437 EMSG(_(e_usingsid));
20438 goto theend;
20440 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
20441 lead += (int)STRLEN(sid_buf);
20444 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
20446 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
20447 goto theend;
20449 name = alloc((unsigned)(len + lead + 1));
20450 if (name != NULL)
20452 if (lead > 0)
20454 name[0] = K_SPECIAL;
20455 name[1] = KS_EXTRA;
20456 name[2] = (int)KE_SNR;
20457 if (lead > 3) /* If it's "<SID>" */
20458 STRCPY(name + 3, sid_buf);
20460 mch_memmove(name + lead, lv.ll_name, (size_t)len);
20461 name[len + lead] = NUL;
20463 *pp = end;
20465 theend:
20466 clear_lval(&lv);
20467 return name;
20471 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
20472 * Return 2 if "p" starts with "s:".
20473 * Return 0 otherwise.
20475 static int
20476 eval_fname_script(p)
20477 char_u *p;
20479 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
20480 || STRNICMP(p + 1, "SNR>", 4) == 0))
20481 return 5;
20482 if (p[0] == 's' && p[1] == ':')
20483 return 2;
20484 return 0;
20488 * Return TRUE if "p" starts with "<SID>" or "s:".
20489 * Only works if eval_fname_script() returned non-zero for "p"!
20491 static int
20492 eval_fname_sid(p)
20493 char_u *p;
20495 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
20499 * List the head of the function: "name(arg1, arg2)".
20501 static void
20502 list_func_head(fp, indent)
20503 ufunc_T *fp;
20504 int indent;
20506 int j;
20508 msg_start();
20509 if (indent)
20510 MSG_PUTS(" ");
20511 MSG_PUTS("function ");
20512 if (fp->uf_name[0] == K_SPECIAL)
20514 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
20515 msg_puts(fp->uf_name + 3);
20517 else
20518 msg_puts(fp->uf_name);
20519 msg_putchar('(');
20520 for (j = 0; j < fp->uf_args.ga_len; ++j)
20522 if (j)
20523 MSG_PUTS(", ");
20524 msg_puts(FUNCARG(fp, j));
20526 if (fp->uf_varargs)
20528 if (j)
20529 MSG_PUTS(", ");
20530 MSG_PUTS("...");
20532 msg_putchar(')');
20533 msg_clr_eos();
20534 if (p_verbose > 0)
20535 last_set_msg(fp->uf_script_ID);
20539 * Find a function by name, return pointer to it in ufuncs.
20540 * Return NULL for unknown function.
20542 static ufunc_T *
20543 find_func(name)
20544 char_u *name;
20546 hashitem_T *hi;
20548 hi = hash_find(&func_hashtab, name);
20549 if (!HASHITEM_EMPTY(hi))
20550 return HI2UF(hi);
20551 return NULL;
20554 #if defined(EXITFREE) || defined(PROTO)
20555 void
20556 free_all_functions()
20558 hashitem_T *hi;
20560 /* Need to start all over every time, because func_free() may change the
20561 * hash table. */
20562 while (func_hashtab.ht_used > 0)
20563 for (hi = func_hashtab.ht_array; ; ++hi)
20564 if (!HASHITEM_EMPTY(hi))
20566 func_free(HI2UF(hi));
20567 break;
20570 #endif
20573 * Return TRUE if a function "name" exists.
20575 static int
20576 function_exists(name)
20577 char_u *name;
20579 char_u *nm = name;
20580 char_u *p;
20581 int n = FALSE;
20583 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
20584 nm = skipwhite(nm);
20586 /* Only accept "funcname", "funcname ", "funcname (..." and
20587 * "funcname(...", not "funcname!...". */
20588 if (p != NULL && (*nm == NUL || *nm == '('))
20590 if (builtin_function(p))
20591 n = (find_internal_func(p) >= 0);
20592 else
20593 n = (find_func(p) != NULL);
20595 vim_free(p);
20596 return n;
20600 * Return TRUE if "name" looks like a builtin function name: starts with a
20601 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
20603 static int
20604 builtin_function(name)
20605 char_u *name;
20607 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
20608 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
20611 #if defined(FEAT_PROFILE) || defined(PROTO)
20613 * Start profiling function "fp".
20615 static void
20616 func_do_profile(fp)
20617 ufunc_T *fp;
20619 fp->uf_tm_count = 0;
20620 profile_zero(&fp->uf_tm_self);
20621 profile_zero(&fp->uf_tm_total);
20622 if (fp->uf_tml_count == NULL)
20623 fp->uf_tml_count = (int *)alloc_clear((unsigned)
20624 (sizeof(int) * fp->uf_lines.ga_len));
20625 if (fp->uf_tml_total == NULL)
20626 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
20627 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20628 if (fp->uf_tml_self == NULL)
20629 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
20630 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20631 fp->uf_tml_idx = -1;
20632 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
20633 || fp->uf_tml_self == NULL)
20634 return; /* out of memory */
20636 fp->uf_profiling = TRUE;
20640 * Dump the profiling results for all functions in file "fd".
20642 void
20643 func_dump_profile(fd)
20644 FILE *fd;
20646 hashitem_T *hi;
20647 int todo;
20648 ufunc_T *fp;
20649 int i;
20650 ufunc_T **sorttab;
20651 int st_len = 0;
20653 todo = (int)func_hashtab.ht_used;
20654 if (todo == 0)
20655 return; /* nothing to dump */
20657 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
20659 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
20661 if (!HASHITEM_EMPTY(hi))
20663 --todo;
20664 fp = HI2UF(hi);
20665 if (fp->uf_profiling)
20667 if (sorttab != NULL)
20668 sorttab[st_len++] = fp;
20670 if (fp->uf_name[0] == K_SPECIAL)
20671 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
20672 else
20673 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
20674 if (fp->uf_tm_count == 1)
20675 fprintf(fd, "Called 1 time\n");
20676 else
20677 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
20678 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
20679 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
20680 fprintf(fd, "\n");
20681 fprintf(fd, "count total (s) self (s)\n");
20683 for (i = 0; i < fp->uf_lines.ga_len; ++i)
20685 if (FUNCLINE(fp, i) == NULL)
20686 continue;
20687 prof_func_line(fd, fp->uf_tml_count[i],
20688 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
20689 fprintf(fd, "%s\n", FUNCLINE(fp, i));
20691 fprintf(fd, "\n");
20696 if (sorttab != NULL && st_len > 0)
20698 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20699 prof_total_cmp);
20700 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
20701 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20702 prof_self_cmp);
20703 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
20706 vim_free(sorttab);
20709 static void
20710 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
20711 FILE *fd;
20712 ufunc_T **sorttab;
20713 int st_len;
20714 char *title;
20715 int prefer_self; /* when equal print only self time */
20717 int i;
20718 ufunc_T *fp;
20720 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
20721 fprintf(fd, "count total (s) self (s) function\n");
20722 for (i = 0; i < 20 && i < st_len; ++i)
20724 fp = sorttab[i];
20725 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
20726 prefer_self);
20727 if (fp->uf_name[0] == K_SPECIAL)
20728 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
20729 else
20730 fprintf(fd, " %s()\n", fp->uf_name);
20732 fprintf(fd, "\n");
20736 * Print the count and times for one function or function line.
20738 static void
20739 prof_func_line(fd, count, total, self, prefer_self)
20740 FILE *fd;
20741 int count;
20742 proftime_T *total;
20743 proftime_T *self;
20744 int prefer_self; /* when equal print only self time */
20746 if (count > 0)
20748 fprintf(fd, "%5d ", count);
20749 if (prefer_self && profile_equal(total, self))
20750 fprintf(fd, " ");
20751 else
20752 fprintf(fd, "%s ", profile_msg(total));
20753 if (!prefer_self && profile_equal(total, self))
20754 fprintf(fd, " ");
20755 else
20756 fprintf(fd, "%s ", profile_msg(self));
20758 else
20759 fprintf(fd, " ");
20763 * Compare function for total time sorting.
20765 static int
20766 #ifdef __BORLANDC__
20767 _RTLENTRYF
20768 #endif
20769 prof_total_cmp(s1, s2)
20770 const void *s1;
20771 const void *s2;
20773 ufunc_T *p1, *p2;
20775 p1 = *(ufunc_T **)s1;
20776 p2 = *(ufunc_T **)s2;
20777 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
20781 * Compare function for self time sorting.
20783 static int
20784 #ifdef __BORLANDC__
20785 _RTLENTRYF
20786 #endif
20787 prof_self_cmp(s1, s2)
20788 const void *s1;
20789 const void *s2;
20791 ufunc_T *p1, *p2;
20793 p1 = *(ufunc_T **)s1;
20794 p2 = *(ufunc_T **)s2;
20795 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
20798 #endif
20801 * If "name" has a package name try autoloading the script for it.
20802 * Return TRUE if a package was loaded.
20804 static int
20805 script_autoload(name, reload)
20806 char_u *name;
20807 int reload; /* load script again when already loaded */
20809 char_u *p;
20810 char_u *scriptname, *tofree;
20811 int ret = FALSE;
20812 int i;
20814 /* If there is no '#' after name[0] there is no package name. */
20815 p = vim_strchr(name, AUTOLOAD_CHAR);
20816 if (p == NULL || p == name)
20817 return FALSE;
20819 tofree = scriptname = autoload_name(name);
20821 /* Find the name in the list of previously loaded package names. Skip
20822 * "autoload/", it's always the same. */
20823 for (i = 0; i < ga_loaded.ga_len; ++i)
20824 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
20825 break;
20826 if (!reload && i < ga_loaded.ga_len)
20827 ret = FALSE; /* was loaded already */
20828 else
20830 /* Remember the name if it wasn't loaded already. */
20831 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
20833 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
20834 tofree = NULL;
20837 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
20838 if (source_runtime(scriptname, FALSE) == OK)
20839 ret = TRUE;
20842 vim_free(tofree);
20843 return ret;
20847 * Return the autoload script name for a function or variable name.
20848 * Returns NULL when out of memory.
20850 static char_u *
20851 autoload_name(name)
20852 char_u *name;
20854 char_u *p;
20855 char_u *scriptname;
20857 /* Get the script file name: replace '#' with '/', append ".vim". */
20858 scriptname = alloc((unsigned)(STRLEN(name) + 14));
20859 if (scriptname == NULL)
20860 return FALSE;
20861 STRCPY(scriptname, "autoload/");
20862 STRCAT(scriptname, name);
20863 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
20864 STRCAT(scriptname, ".vim");
20865 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
20866 *p = '/';
20867 return scriptname;
20870 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
20873 * Function given to ExpandGeneric() to obtain the list of user defined
20874 * function names.
20876 char_u *
20877 get_user_func_name(xp, idx)
20878 expand_T *xp;
20879 int idx;
20881 static long_u done;
20882 static hashitem_T *hi;
20883 ufunc_T *fp;
20885 if (idx == 0)
20887 done = 0;
20888 hi = func_hashtab.ht_array;
20890 if (done < func_hashtab.ht_used)
20892 if (done++ > 0)
20893 ++hi;
20894 while (HASHITEM_EMPTY(hi))
20895 ++hi;
20896 fp = HI2UF(hi);
20898 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
20899 return fp->uf_name; /* prevents overflow */
20901 cat_func_name(IObuff, fp);
20902 if (xp->xp_context != EXPAND_USER_FUNC)
20904 STRCAT(IObuff, "(");
20905 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
20906 STRCAT(IObuff, ")");
20908 return IObuff;
20910 return NULL;
20913 #endif /* FEAT_CMDL_COMPL */
20916 * Copy the function name of "fp" to buffer "buf".
20917 * "buf" must be able to hold the function name plus three bytes.
20918 * Takes care of script-local function names.
20920 static void
20921 cat_func_name(buf, fp)
20922 char_u *buf;
20923 ufunc_T *fp;
20925 if (fp->uf_name[0] == K_SPECIAL)
20927 STRCPY(buf, "<SNR>");
20928 STRCAT(buf, fp->uf_name + 3);
20930 else
20931 STRCPY(buf, fp->uf_name);
20935 * ":delfunction {name}"
20937 void
20938 ex_delfunction(eap)
20939 exarg_T *eap;
20941 ufunc_T *fp = NULL;
20942 char_u *p;
20943 char_u *name;
20944 funcdict_T fudi;
20946 p = eap->arg;
20947 name = trans_function_name(&p, eap->skip, 0, &fudi);
20948 vim_free(fudi.fd_newkey);
20949 if (name == NULL)
20951 if (fudi.fd_dict != NULL && !eap->skip)
20952 EMSG(_(e_funcref));
20953 return;
20955 if (!ends_excmd(*skipwhite(p)))
20957 vim_free(name);
20958 EMSG(_(e_trailing));
20959 return;
20961 eap->nextcmd = check_nextcmd(p);
20962 if (eap->nextcmd != NULL)
20963 *p = NUL;
20965 if (!eap->skip)
20966 fp = find_func(name);
20967 vim_free(name);
20969 if (!eap->skip)
20971 if (fp == NULL)
20973 EMSG2(_(e_nofunc), eap->arg);
20974 return;
20976 if (fp->uf_calls > 0)
20978 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
20979 return;
20982 if (fudi.fd_dict != NULL)
20984 /* Delete the dict item that refers to the function, it will
20985 * invoke func_unref() and possibly delete the function. */
20986 dictitem_remove(fudi.fd_dict, fudi.fd_di);
20988 else
20989 func_free(fp);
20994 * Free a function and remove it from the list of functions.
20996 static void
20997 func_free(fp)
20998 ufunc_T *fp;
21000 hashitem_T *hi;
21002 /* clear this function */
21003 ga_clear_strings(&(fp->uf_args));
21004 ga_clear_strings(&(fp->uf_lines));
21005 #ifdef FEAT_PROFILE
21006 vim_free(fp->uf_tml_count);
21007 vim_free(fp->uf_tml_total);
21008 vim_free(fp->uf_tml_self);
21009 #endif
21011 /* remove the function from the function hashtable */
21012 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
21013 if (HASHITEM_EMPTY(hi))
21014 EMSG2(_(e_intern2), "func_free()");
21015 else
21016 hash_remove(&func_hashtab, hi);
21018 vim_free(fp);
21022 * Unreference a Function: decrement the reference count and free it when it
21023 * becomes zero. Only for numbered functions.
21025 static void
21026 func_unref(name)
21027 char_u *name;
21029 ufunc_T *fp;
21031 if (name != NULL && isdigit(*name))
21033 fp = find_func(name);
21034 if (fp == NULL)
21035 EMSG2(_(e_intern2), "func_unref()");
21036 else if (--fp->uf_refcount <= 0)
21038 /* Only delete it when it's not being used. Otherwise it's done
21039 * when "uf_calls" becomes zero. */
21040 if (fp->uf_calls == 0)
21041 func_free(fp);
21047 * Count a reference to a Function.
21049 static void
21050 func_ref(name)
21051 char_u *name;
21053 ufunc_T *fp;
21055 if (name != NULL && isdigit(*name))
21057 fp = find_func(name);
21058 if (fp == NULL)
21059 EMSG2(_(e_intern2), "func_ref()");
21060 else
21061 ++fp->uf_refcount;
21066 * Call a user function.
21068 static void
21069 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
21070 ufunc_T *fp; /* pointer to function */
21071 int argcount; /* nr of args */
21072 typval_T *argvars; /* arguments */
21073 typval_T *rettv; /* return value */
21074 linenr_T firstline; /* first line of range */
21075 linenr_T lastline; /* last line of range */
21076 dict_T *selfdict; /* Dictionary for "self" */
21078 char_u *save_sourcing_name;
21079 linenr_T save_sourcing_lnum;
21080 scid_T save_current_SID;
21081 funccall_T *fc;
21082 int save_did_emsg;
21083 static int depth = 0;
21084 dictitem_T *v;
21085 int fixvar_idx = 0; /* index in fixvar[] */
21086 int i;
21087 int ai;
21088 char_u numbuf[NUMBUFLEN];
21089 char_u *name;
21090 #ifdef FEAT_PROFILE
21091 proftime_T wait_start;
21092 proftime_T call_start;
21093 #endif
21095 /* If depth of calling is getting too high, don't execute the function */
21096 if (depth >= p_mfd)
21098 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
21099 rettv->v_type = VAR_NUMBER;
21100 rettv->vval.v_number = -1;
21101 return;
21103 ++depth;
21105 line_breakcheck(); /* check for CTRL-C hit */
21107 fc = (funccall_T *)alloc(sizeof(funccall_T));
21108 fc->caller = current_funccal;
21109 current_funccal = fc;
21110 fc->func = fp;
21111 fc->rettv = rettv;
21112 rettv->vval.v_number = 0;
21113 fc->linenr = 0;
21114 fc->returned = FALSE;
21115 fc->level = ex_nesting_level;
21116 /* Check if this function has a breakpoint. */
21117 fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
21118 fc->dbg_tick = debug_tick;
21121 * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables
21122 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
21123 * each argument variable and saves a lot of time.
21126 * Init l: variables.
21128 init_var_dict(&fc->l_vars, &fc->l_vars_var);
21129 if (selfdict != NULL)
21131 /* Set l:self to "selfdict". Use "name" to avoid a warning from
21132 * some compiler that checks the destination size. */
21133 v = &fc->fixvar[fixvar_idx++].var;
21134 name = v->di_key;
21135 STRCPY(name, "self");
21136 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
21137 hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
21138 v->di_tv.v_type = VAR_DICT;
21139 v->di_tv.v_lock = 0;
21140 v->di_tv.vval.v_dict = selfdict;
21141 ++selfdict->dv_refcount;
21145 * Init a: variables.
21146 * Set a:0 to "argcount".
21147 * Set a:000 to a list with room for the "..." arguments.
21149 init_var_dict(&fc->l_avars, &fc->l_avars_var);
21150 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0",
21151 (varnumber_T)(argcount - fp->uf_args.ga_len));
21152 /* Use "name" to avoid a warning from some compiler that checks the
21153 * destination size. */
21154 v = &fc->fixvar[fixvar_idx++].var;
21155 name = v->di_key;
21156 STRCPY(name, "000");
21157 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21158 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21159 v->di_tv.v_type = VAR_LIST;
21160 v->di_tv.v_lock = VAR_FIXED;
21161 v->di_tv.vval.v_list = &fc->l_varlist;
21162 vim_memset(&fc->l_varlist, 0, sizeof(list_T));
21163 fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT;
21164 fc->l_varlist.lv_lock = VAR_FIXED;
21167 * Set a:firstline to "firstline" and a:lastline to "lastline".
21168 * Set a:name to named arguments.
21169 * Set a:N to the "..." arguments.
21171 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline",
21172 (varnumber_T)firstline);
21173 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline",
21174 (varnumber_T)lastline);
21175 for (i = 0; i < argcount; ++i)
21177 ai = i - fp->uf_args.ga_len;
21178 if (ai < 0)
21179 /* named argument a:name */
21180 name = FUNCARG(fp, i);
21181 else
21183 /* "..." argument a:1, a:2, etc. */
21184 sprintf((char *)numbuf, "%d", ai + 1);
21185 name = numbuf;
21187 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
21189 v = &fc->fixvar[fixvar_idx++].var;
21190 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21192 else
21194 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
21195 + STRLEN(name)));
21196 if (v == NULL)
21197 break;
21198 v->di_flags = DI_FLAGS_RO;
21200 STRCPY(v->di_key, name);
21201 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21203 /* Note: the values are copied directly to avoid alloc/free.
21204 * "argvars" must have VAR_FIXED for v_lock. */
21205 v->di_tv = argvars[i];
21206 v->di_tv.v_lock = VAR_FIXED;
21208 if (ai >= 0 && ai < MAX_FUNC_ARGS)
21210 list_append(&fc->l_varlist, &fc->l_listitems[ai]);
21211 fc->l_listitems[ai].li_tv = argvars[i];
21212 fc->l_listitems[ai].li_tv.v_lock = VAR_FIXED;
21216 /* Don't redraw while executing the function. */
21217 ++RedrawingDisabled;
21218 save_sourcing_name = sourcing_name;
21219 save_sourcing_lnum = sourcing_lnum;
21220 sourcing_lnum = 1;
21221 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
21222 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
21223 if (sourcing_name != NULL)
21225 if (save_sourcing_name != NULL
21226 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
21227 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
21228 else
21229 STRCPY(sourcing_name, "function ");
21230 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
21232 if (p_verbose >= 12)
21234 ++no_wait_return;
21235 verbose_enter_scroll();
21237 smsg((char_u *)_("calling %s"), sourcing_name);
21238 if (p_verbose >= 14)
21240 char_u buf[MSG_BUF_LEN];
21241 char_u numbuf2[NUMBUFLEN];
21242 char_u *tofree;
21243 char_u *s;
21245 msg_puts((char_u *)"(");
21246 for (i = 0; i < argcount; ++i)
21248 if (i > 0)
21249 msg_puts((char_u *)", ");
21250 if (argvars[i].v_type == VAR_NUMBER)
21251 msg_outnum((long)argvars[i].vval.v_number);
21252 else
21254 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
21255 if (s != NULL)
21257 trunc_string(s, buf, MSG_BUF_CLEN);
21258 msg_puts(buf);
21259 vim_free(tofree);
21263 msg_puts((char_u *)")");
21265 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21267 verbose_leave_scroll();
21268 --no_wait_return;
21271 #ifdef FEAT_PROFILE
21272 if (do_profiling == PROF_YES)
21274 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
21275 func_do_profile(fp);
21276 if (fp->uf_profiling
21277 || (fc->caller != NULL && fc->caller->func->uf_profiling))
21279 ++fp->uf_tm_count;
21280 profile_start(&call_start);
21281 profile_zero(&fp->uf_tm_children);
21283 script_prof_save(&wait_start);
21285 #endif
21287 save_current_SID = current_SID;
21288 current_SID = fp->uf_script_ID;
21289 save_did_emsg = did_emsg;
21290 did_emsg = FALSE;
21292 /* call do_cmdline() to execute the lines */
21293 do_cmdline(NULL, get_func_line, (void *)fc,
21294 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
21296 --RedrawingDisabled;
21298 /* when the function was aborted because of an error, return -1 */
21299 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
21301 clear_tv(rettv);
21302 rettv->v_type = VAR_NUMBER;
21303 rettv->vval.v_number = -1;
21306 #ifdef FEAT_PROFILE
21307 if (do_profiling == PROF_YES && (fp->uf_profiling
21308 || (fc->caller != NULL && fc->caller->func->uf_profiling)))
21310 profile_end(&call_start);
21311 profile_sub_wait(&wait_start, &call_start);
21312 profile_add(&fp->uf_tm_total, &call_start);
21313 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
21314 if (fc->caller != NULL && fc->caller->func->uf_profiling)
21316 profile_add(&fc->caller->func->uf_tm_children, &call_start);
21317 profile_add(&fc->caller->func->uf_tml_children, &call_start);
21320 #endif
21322 /* when being verbose, mention the return value */
21323 if (p_verbose >= 12)
21325 ++no_wait_return;
21326 verbose_enter_scroll();
21328 if (aborting())
21329 smsg((char_u *)_("%s aborted"), sourcing_name);
21330 else if (fc->rettv->v_type == VAR_NUMBER)
21331 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
21332 (long)fc->rettv->vval.v_number);
21333 else
21335 char_u buf[MSG_BUF_LEN];
21336 char_u numbuf2[NUMBUFLEN];
21337 char_u *tofree;
21338 char_u *s;
21340 /* The value may be very long. Skip the middle part, so that we
21341 * have some idea how it starts and ends. smsg() would always
21342 * truncate it at the end. */
21343 s = tv2string(fc->rettv, &tofree, numbuf2, 0);
21344 if (s != NULL)
21346 trunc_string(s, buf, MSG_BUF_CLEN);
21347 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
21348 vim_free(tofree);
21351 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21353 verbose_leave_scroll();
21354 --no_wait_return;
21357 vim_free(sourcing_name);
21358 sourcing_name = save_sourcing_name;
21359 sourcing_lnum = save_sourcing_lnum;
21360 current_SID = save_current_SID;
21361 #ifdef FEAT_PROFILE
21362 if (do_profiling == PROF_YES)
21363 script_prof_restore(&wait_start);
21364 #endif
21366 if (p_verbose >= 12 && sourcing_name != NULL)
21368 ++no_wait_return;
21369 verbose_enter_scroll();
21371 smsg((char_u *)_("continuing in %s"), sourcing_name);
21372 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21374 verbose_leave_scroll();
21375 --no_wait_return;
21378 did_emsg |= save_did_emsg;
21379 current_funccal = fc->caller;
21380 --depth;
21382 /* if the a:000 list and the a: dict are not referenced we can free the
21383 * funccall_T and what's in it. */
21384 if (fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
21385 && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
21386 && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT)
21388 free_funccal(fc, FALSE);
21390 else
21392 hashitem_T *hi;
21393 listitem_T *li;
21394 int todo;
21396 /* "fc" is still in use. This can happen when returning "a:000" or
21397 * assigning "l:" to a global variable.
21398 * Link "fc" in the list for garbage collection later. */
21399 fc->caller = previous_funccal;
21400 previous_funccal = fc;
21402 /* Make a copy of the a: variables, since we didn't do that above. */
21403 todo = (int)fc->l_avars.dv_hashtab.ht_used;
21404 for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi)
21406 if (!HASHITEM_EMPTY(hi))
21408 --todo;
21409 v = HI2DI(hi);
21410 copy_tv(&v->di_tv, &v->di_tv);
21414 /* Make a copy of the a:000 items, since we didn't do that above. */
21415 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21416 copy_tv(&li->li_tv, &li->li_tv);
21421 * Return TRUE if items in "fc" do not have "copyID". That means they are not
21422 * referenced from anywhere.
21424 static int
21425 can_free_funccal(fc, copyID)
21426 funccall_T *fc;
21427 int copyID;
21429 return (fc->l_varlist.lv_copyID != copyID
21430 && fc->l_vars.dv_copyID != copyID
21431 && fc->l_avars.dv_copyID != copyID);
21435 * Free "fc" and what it contains.
21437 static void
21438 free_funccal(fc, free_val)
21439 funccall_T *fc;
21440 int free_val; /* a: vars were allocated */
21442 listitem_T *li;
21444 /* The a: variables typevals may not have been allocated, only free the
21445 * allocated variables. */
21446 vars_clear_ext(&fc->l_avars.dv_hashtab, free_val);
21448 /* free all l: variables */
21449 vars_clear(&fc->l_vars.dv_hashtab);
21451 /* Free the a:000 variables if they were allocated. */
21452 if (free_val)
21453 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21454 clear_tv(&li->li_tv);
21456 vim_free(fc);
21460 * Add a number variable "name" to dict "dp" with value "nr".
21462 static void
21463 add_nr_var(dp, v, name, nr)
21464 dict_T *dp;
21465 dictitem_T *v;
21466 char *name;
21467 varnumber_T nr;
21469 STRCPY(v->di_key, name);
21470 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21471 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
21472 v->di_tv.v_type = VAR_NUMBER;
21473 v->di_tv.v_lock = VAR_FIXED;
21474 v->di_tv.vval.v_number = nr;
21478 * ":return [expr]"
21480 void
21481 ex_return(eap)
21482 exarg_T *eap;
21484 char_u *arg = eap->arg;
21485 typval_T rettv;
21486 int returning = FALSE;
21488 if (current_funccal == NULL)
21490 EMSG(_("E133: :return not inside a function"));
21491 return;
21494 if (eap->skip)
21495 ++emsg_skip;
21497 eap->nextcmd = NULL;
21498 if ((*arg != NUL && *arg != '|' && *arg != '\n')
21499 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
21501 if (!eap->skip)
21502 returning = do_return(eap, FALSE, TRUE, &rettv);
21503 else
21504 clear_tv(&rettv);
21506 /* It's safer to return also on error. */
21507 else if (!eap->skip)
21510 * Return unless the expression evaluation has been cancelled due to an
21511 * aborting error, an interrupt, or an exception.
21513 if (!aborting())
21514 returning = do_return(eap, FALSE, TRUE, NULL);
21517 /* When skipping or the return gets pending, advance to the next command
21518 * in this line (!returning). Otherwise, ignore the rest of the line.
21519 * Following lines will be ignored by get_func_line(). */
21520 if (returning)
21521 eap->nextcmd = NULL;
21522 else if (eap->nextcmd == NULL) /* no argument */
21523 eap->nextcmd = check_nextcmd(arg);
21525 if (eap->skip)
21526 --emsg_skip;
21530 * Return from a function. Possibly makes the return pending. Also called
21531 * for a pending return at the ":endtry" or after returning from an extra
21532 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
21533 * when called due to a ":return" command. "rettv" may point to a typval_T
21534 * with the return rettv. Returns TRUE when the return can be carried out,
21535 * FALSE when the return gets pending.
21538 do_return(eap, reanimate, is_cmd, rettv)
21539 exarg_T *eap;
21540 int reanimate;
21541 int is_cmd;
21542 void *rettv;
21544 int idx;
21545 struct condstack *cstack = eap->cstack;
21547 if (reanimate)
21548 /* Undo the return. */
21549 current_funccal->returned = FALSE;
21552 * Cleanup (and inactivate) conditionals, but stop when a try conditional
21553 * not in its finally clause (which then is to be executed next) is found.
21554 * In this case, make the ":return" pending for execution at the ":endtry".
21555 * Otherwise, return normally.
21557 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
21558 if (idx >= 0)
21560 cstack->cs_pending[idx] = CSTP_RETURN;
21562 if (!is_cmd && !reanimate)
21563 /* A pending return again gets pending. "rettv" points to an
21564 * allocated variable with the rettv of the original ":return"'s
21565 * argument if present or is NULL else. */
21566 cstack->cs_rettv[idx] = rettv;
21567 else
21569 /* When undoing a return in order to make it pending, get the stored
21570 * return rettv. */
21571 if (reanimate)
21572 rettv = current_funccal->rettv;
21574 if (rettv != NULL)
21576 /* Store the value of the pending return. */
21577 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
21578 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
21579 else
21580 EMSG(_(e_outofmem));
21582 else
21583 cstack->cs_rettv[idx] = NULL;
21585 if (reanimate)
21587 /* The pending return value could be overwritten by a ":return"
21588 * without argument in a finally clause; reset the default
21589 * return value. */
21590 current_funccal->rettv->v_type = VAR_NUMBER;
21591 current_funccal->rettv->vval.v_number = 0;
21594 report_make_pending(CSTP_RETURN, rettv);
21596 else
21598 current_funccal->returned = TRUE;
21600 /* If the return is carried out now, store the return value. For
21601 * a return immediately after reanimation, the value is already
21602 * there. */
21603 if (!reanimate && rettv != NULL)
21605 clear_tv(current_funccal->rettv);
21606 *current_funccal->rettv = *(typval_T *)rettv;
21607 if (!is_cmd)
21608 vim_free(rettv);
21612 return idx < 0;
21616 * Free the variable with a pending return value.
21618 void
21619 discard_pending_return(rettv)
21620 void *rettv;
21622 free_tv((typval_T *)rettv);
21626 * Generate a return command for producing the value of "rettv". The result
21627 * is an allocated string. Used by report_pending() for verbose messages.
21629 char_u *
21630 get_return_cmd(rettv)
21631 void *rettv;
21633 char_u *s = NULL;
21634 char_u *tofree = NULL;
21635 char_u numbuf[NUMBUFLEN];
21637 if (rettv != NULL)
21638 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
21639 if (s == NULL)
21640 s = (char_u *)"";
21642 STRCPY(IObuff, ":return ");
21643 STRNCPY(IObuff + 8, s, IOSIZE - 8);
21644 if (STRLEN(s) + 8 >= IOSIZE)
21645 STRCPY(IObuff + IOSIZE - 4, "...");
21646 vim_free(tofree);
21647 return vim_strsave(IObuff);
21651 * Get next function line.
21652 * Called by do_cmdline() to get the next line.
21653 * Returns allocated string, or NULL for end of function.
21655 /* ARGSUSED */
21656 char_u *
21657 get_func_line(c, cookie, indent)
21658 int c; /* not used */
21659 void *cookie;
21660 int indent; /* not used */
21662 funccall_T *fcp = (funccall_T *)cookie;
21663 ufunc_T *fp = fcp->func;
21664 char_u *retval;
21665 garray_T *gap; /* growarray with function lines */
21667 /* If breakpoints have been added/deleted need to check for it. */
21668 if (fcp->dbg_tick != debug_tick)
21670 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21671 sourcing_lnum);
21672 fcp->dbg_tick = debug_tick;
21674 #ifdef FEAT_PROFILE
21675 if (do_profiling == PROF_YES)
21676 func_line_end(cookie);
21677 #endif
21679 gap = &fp->uf_lines;
21680 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21681 || fcp->returned)
21682 retval = NULL;
21683 else
21685 /* Skip NULL lines (continuation lines). */
21686 while (fcp->linenr < gap->ga_len
21687 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
21688 ++fcp->linenr;
21689 if (fcp->linenr >= gap->ga_len)
21690 retval = NULL;
21691 else
21693 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
21694 sourcing_lnum = fcp->linenr;
21695 #ifdef FEAT_PROFILE
21696 if (do_profiling == PROF_YES)
21697 func_line_start(cookie);
21698 #endif
21702 /* Did we encounter a breakpoint? */
21703 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
21705 dbg_breakpoint(fp->uf_name, sourcing_lnum);
21706 /* Find next breakpoint. */
21707 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21708 sourcing_lnum);
21709 fcp->dbg_tick = debug_tick;
21712 return retval;
21715 #if defined(FEAT_PROFILE) || defined(PROTO)
21717 * Called when starting to read a function line.
21718 * "sourcing_lnum" must be correct!
21719 * When skipping lines it may not actually be executed, but we won't find out
21720 * until later and we need to store the time now.
21722 void
21723 func_line_start(cookie)
21724 void *cookie;
21726 funccall_T *fcp = (funccall_T *)cookie;
21727 ufunc_T *fp = fcp->func;
21729 if (fp->uf_profiling && sourcing_lnum >= 1
21730 && sourcing_lnum <= fp->uf_lines.ga_len)
21732 fp->uf_tml_idx = sourcing_lnum - 1;
21733 /* Skip continuation lines. */
21734 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
21735 --fp->uf_tml_idx;
21736 fp->uf_tml_execed = FALSE;
21737 profile_start(&fp->uf_tml_start);
21738 profile_zero(&fp->uf_tml_children);
21739 profile_get_wait(&fp->uf_tml_wait);
21744 * Called when actually executing a function line.
21746 void
21747 func_line_exec(cookie)
21748 void *cookie;
21750 funccall_T *fcp = (funccall_T *)cookie;
21751 ufunc_T *fp = fcp->func;
21753 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21754 fp->uf_tml_execed = TRUE;
21758 * Called when done with a function line.
21760 void
21761 func_line_end(cookie)
21762 void *cookie;
21764 funccall_T *fcp = (funccall_T *)cookie;
21765 ufunc_T *fp = fcp->func;
21767 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21769 if (fp->uf_tml_execed)
21771 ++fp->uf_tml_count[fp->uf_tml_idx];
21772 profile_end(&fp->uf_tml_start);
21773 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
21774 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
21775 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
21776 &fp->uf_tml_children);
21778 fp->uf_tml_idx = -1;
21781 #endif
21784 * Return TRUE if the currently active function should be ended, because a
21785 * return was encountered or an error occurred. Used inside a ":while".
21788 func_has_ended(cookie)
21789 void *cookie;
21791 funccall_T *fcp = (funccall_T *)cookie;
21793 /* Ignore the "abort" flag if the abortion behavior has been changed due to
21794 * an error inside a try conditional. */
21795 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21796 || fcp->returned);
21800 * return TRUE if cookie indicates a function which "abort"s on errors.
21803 func_has_abort(cookie)
21804 void *cookie;
21806 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
21809 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
21810 typedef enum
21812 VAR_FLAVOUR_DEFAULT, /* doesn't start with uppercase */
21813 VAR_FLAVOUR_SESSION, /* starts with uppercase, some lower */
21814 VAR_FLAVOUR_VIMINFO /* all uppercase */
21815 } var_flavour_T;
21817 static var_flavour_T var_flavour __ARGS((char_u *varname));
21819 static var_flavour_T
21820 var_flavour(varname)
21821 char_u *varname;
21823 char_u *p = varname;
21825 if (ASCII_ISUPPER(*p))
21827 while (*(++p))
21828 if (ASCII_ISLOWER(*p))
21829 return VAR_FLAVOUR_SESSION;
21830 return VAR_FLAVOUR_VIMINFO;
21832 else
21833 return VAR_FLAVOUR_DEFAULT;
21835 #endif
21837 #if defined(FEAT_VIMINFO) || defined(PROTO)
21839 * Restore global vars that start with a capital from the viminfo file
21842 read_viminfo_varlist(virp, writing)
21843 vir_T *virp;
21844 int writing;
21846 char_u *tab;
21847 int type = VAR_NUMBER;
21848 typval_T tv;
21850 if (!writing && (find_viminfo_parameter('!') != NULL))
21852 tab = vim_strchr(virp->vir_line + 1, '\t');
21853 if (tab != NULL)
21855 *tab++ = '\0'; /* isolate the variable name */
21856 if (*tab == 'S') /* string var */
21857 type = VAR_STRING;
21858 #ifdef FEAT_FLOAT
21859 else if (*tab == 'F')
21860 type = VAR_FLOAT;
21861 #endif
21863 tab = vim_strchr(tab, '\t');
21864 if (tab != NULL)
21866 tv.v_type = type;
21867 if (type == VAR_STRING)
21868 tv.vval.v_string = viminfo_readstring(virp,
21869 (int)(tab - virp->vir_line + 1), TRUE);
21870 #ifdef FEAT_FLOAT
21871 else if (type == VAR_FLOAT)
21872 (void)string2float(tab + 1, &tv.vval.v_float);
21873 #endif
21874 else
21875 tv.vval.v_number = atol((char *)tab + 1);
21876 set_var(virp->vir_line + 1, &tv, FALSE);
21877 if (type == VAR_STRING)
21878 vim_free(tv.vval.v_string);
21883 return viminfo_readline(virp);
21887 * Write global vars that start with a capital to the viminfo file
21889 void
21890 write_viminfo_varlist(fp)
21891 FILE *fp;
21893 hashitem_T *hi;
21894 dictitem_T *this_var;
21895 int todo;
21896 char *s;
21897 char_u *p;
21898 char_u *tofree;
21899 char_u numbuf[NUMBUFLEN];
21901 if (find_viminfo_parameter('!') == NULL)
21902 return;
21904 fprintf(fp, _("\n# global variables:\n"));
21906 todo = (int)globvarht.ht_used;
21907 for (hi = globvarht.ht_array; todo > 0; ++hi)
21909 if (!HASHITEM_EMPTY(hi))
21911 --todo;
21912 this_var = HI2DI(hi);
21913 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
21915 switch (this_var->di_tv.v_type)
21917 case VAR_STRING: s = "STR"; break;
21918 case VAR_NUMBER: s = "NUM"; break;
21919 #ifdef FEAT_FLOAT
21920 case VAR_FLOAT: s = "FLO"; break;
21921 #endif
21922 default: continue;
21924 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
21925 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
21926 if (p != NULL)
21927 viminfo_writestring(fp, p);
21928 vim_free(tofree);
21933 #endif
21935 #if defined(FEAT_SESSION) || defined(PROTO)
21937 store_session_globals(fd)
21938 FILE *fd;
21940 hashitem_T *hi;
21941 dictitem_T *this_var;
21942 int todo;
21943 char_u *p, *t;
21945 todo = (int)globvarht.ht_used;
21946 for (hi = globvarht.ht_array; todo > 0; ++hi)
21948 if (!HASHITEM_EMPTY(hi))
21950 --todo;
21951 this_var = HI2DI(hi);
21952 if ((this_var->di_tv.v_type == VAR_NUMBER
21953 || this_var->di_tv.v_type == VAR_STRING)
21954 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
21956 /* Escape special characters with a backslash. Turn a LF and
21957 * CR into \n and \r. */
21958 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
21959 (char_u *)"\\\"\n\r");
21960 if (p == NULL) /* out of memory */
21961 break;
21962 for (t = p; *t != NUL; ++t)
21963 if (*t == '\n')
21964 *t = 'n';
21965 else if (*t == '\r')
21966 *t = 'r';
21967 if ((fprintf(fd, "let %s = %c%s%c",
21968 this_var->di_key,
21969 (this_var->di_tv.v_type == VAR_STRING) ? '"'
21970 : ' ',
21972 (this_var->di_tv.v_type == VAR_STRING) ? '"'
21973 : ' ') < 0)
21974 || put_eol(fd) == FAIL)
21976 vim_free(p);
21977 return FAIL;
21979 vim_free(p);
21981 #ifdef FEAT_FLOAT
21982 else if (this_var->di_tv.v_type == VAR_FLOAT
21983 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
21985 float_T f = this_var->di_tv.vval.v_float;
21986 int sign = ' ';
21988 if (f < 0)
21990 f = -f;
21991 sign = '-';
21993 if ((fprintf(fd, "let %s = %c&%f",
21994 this_var->di_key, sign, f) < 0)
21995 || put_eol(fd) == FAIL)
21996 return FAIL;
21998 #endif
22001 return OK;
22003 #endif
22006 * Display script name where an item was last set.
22007 * Should only be invoked when 'verbose' is non-zero.
22009 void
22010 last_set_msg(scriptID)
22011 scid_T scriptID;
22013 char_u *p;
22015 if (scriptID != 0)
22017 p = home_replace_save(NULL, get_scriptname(scriptID));
22018 if (p != NULL)
22020 verbose_enter();
22021 MSG_PUTS(_("\n\tLast set from "));
22022 MSG_PUTS(p);
22023 vim_free(p);
22024 verbose_leave();
22030 * List v:oldfiles in a nice way.
22032 /*ARGSUSED*/
22033 void
22034 ex_oldfiles(eap)
22035 exarg_T *eap;
22037 list_T *l = vimvars[VV_OLDFILES].vv_list;
22038 listitem_T *li;
22039 int nr = 0;
22041 if (l == NULL)
22042 msg((char_u *)_("No old files"));
22043 else
22045 msg_start();
22046 msg_scroll = TRUE;
22047 for (li = l->lv_first; li != NULL && !got_int; li = li->li_next)
22049 msg_outnum((long)++nr);
22050 MSG_PUTS(": ");
22051 msg_outtrans(get_tv_string(&li->li_tv));
22052 msg_putchar('\n');
22053 out_flush(); /* output one line at a time */
22054 ui_breakcheck();
22056 /* Assume "got_int" was set to truncate the listing. */
22057 got_int = FALSE;
22059 #ifdef FEAT_BROWSE_CMD
22060 if (cmdmod.browse)
22062 quit_more = FALSE;
22063 nr = prompt_for_number(FALSE);
22064 msg_starthere();
22065 if (nr > 0)
22067 char_u *p = list_find_str(get_vim_var_list(VV_OLDFILES),
22068 (long)nr);
22070 if (p != NULL)
22072 p = expand_env_save(p);
22073 eap->arg = p;
22074 eap->cmdidx = CMD_edit;
22075 cmdmod.browse = FALSE;
22076 do_exedit(eap, NULL);
22077 vim_free(p);
22081 #endif
22085 #endif /* FEAT_EVAL */
22088 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
22090 #ifdef WIN3264
22092 * Functions for ":8" filename modifier: get 8.3 version of a filename.
22094 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22095 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
22096 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22099 * Get the short path (8.3) for the filename in "fnamep".
22100 * Only works for a valid file name.
22101 * When the path gets longer "fnamep" is changed and the allocated buffer
22102 * is put in "bufp".
22103 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
22104 * Returns OK on success, FAIL on failure.
22106 static int
22107 get_short_pathname(fnamep, bufp, fnamelen)
22108 char_u **fnamep;
22109 char_u **bufp;
22110 int *fnamelen;
22112 int l, len;
22113 char_u *newbuf;
22115 len = *fnamelen;
22116 l = GetShortPathName(*fnamep, *fnamep, len);
22117 if (l > len - 1)
22119 /* If that doesn't work (not enough space), then save the string
22120 * and try again with a new buffer big enough. */
22121 newbuf = vim_strnsave(*fnamep, l);
22122 if (newbuf == NULL)
22123 return FAIL;
22125 vim_free(*bufp);
22126 *fnamep = *bufp = newbuf;
22128 /* Really should always succeed, as the buffer is big enough. */
22129 l = GetShortPathName(*fnamep, *fnamep, l+1);
22132 *fnamelen = l;
22133 return OK;
22137 * Get the short path (8.3) for the filename in "fname". The converted
22138 * path is returned in "bufp".
22140 * Some of the directories specified in "fname" may not exist. This function
22141 * will shorten the existing directories at the beginning of the path and then
22142 * append the remaining non-existing path.
22144 * fname - Pointer to the filename to shorten. On return, contains the
22145 * pointer to the shortened pathname
22146 * bufp - Pointer to an allocated buffer for the filename.
22147 * fnamelen - Length of the filename pointed to by fname
22149 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
22151 static int
22152 shortpath_for_invalid_fname(fname, bufp, fnamelen)
22153 char_u **fname;
22154 char_u **bufp;
22155 int *fnamelen;
22157 char_u *short_fname, *save_fname, *pbuf_unused;
22158 char_u *endp, *save_endp;
22159 char_u ch;
22160 int old_len, len;
22161 int new_len, sfx_len;
22162 int retval = OK;
22164 /* Make a copy */
22165 old_len = *fnamelen;
22166 save_fname = vim_strnsave(*fname, old_len);
22167 pbuf_unused = NULL;
22168 short_fname = NULL;
22170 endp = save_fname + old_len - 1; /* Find the end of the copy */
22171 save_endp = endp;
22174 * Try shortening the supplied path till it succeeds by removing one
22175 * directory at a time from the tail of the path.
22177 len = 0;
22178 for (;;)
22180 /* go back one path-separator */
22181 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
22182 --endp;
22183 if (endp <= save_fname)
22184 break; /* processed the complete path */
22187 * Replace the path separator with a NUL and try to shorten the
22188 * resulting path.
22190 ch = *endp;
22191 *endp = 0;
22192 short_fname = save_fname;
22193 len = (int)STRLEN(short_fname) + 1;
22194 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
22196 retval = FAIL;
22197 goto theend;
22199 *endp = ch; /* preserve the string */
22201 if (len > 0)
22202 break; /* successfully shortened the path */
22204 /* failed to shorten the path. Skip the path separator */
22205 --endp;
22208 if (len > 0)
22211 * Succeeded in shortening the path. Now concatenate the shortened
22212 * path with the remaining path at the tail.
22215 /* Compute the length of the new path. */
22216 sfx_len = (int)(save_endp - endp) + 1;
22217 new_len = len + sfx_len;
22219 *fnamelen = new_len;
22220 vim_free(*bufp);
22221 if (new_len > old_len)
22223 /* There is not enough space in the currently allocated string,
22224 * copy it to a buffer big enough. */
22225 *fname = *bufp = vim_strnsave(short_fname, new_len);
22226 if (*fname == NULL)
22228 retval = FAIL;
22229 goto theend;
22232 else
22234 /* Transfer short_fname to the main buffer (it's big enough),
22235 * unless get_short_pathname() did its work in-place. */
22236 *fname = *bufp = save_fname;
22237 if (short_fname != save_fname)
22238 vim_strncpy(save_fname, short_fname, len);
22239 save_fname = NULL;
22242 /* concat the not-shortened part of the path */
22243 vim_strncpy(*fname + len, endp, sfx_len);
22244 (*fname)[new_len] = NUL;
22247 theend:
22248 vim_free(pbuf_unused);
22249 vim_free(save_fname);
22251 return retval;
22255 * Get a pathname for a partial path.
22256 * Returns OK for success, FAIL for failure.
22258 static int
22259 shortpath_for_partial(fnamep, bufp, fnamelen)
22260 char_u **fnamep;
22261 char_u **bufp;
22262 int *fnamelen;
22264 int sepcount, len, tflen;
22265 char_u *p;
22266 char_u *pbuf, *tfname;
22267 int hasTilde;
22269 /* Count up the path separators from the RHS.. so we know which part
22270 * of the path to return. */
22271 sepcount = 0;
22272 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
22273 if (vim_ispathsep(*p))
22274 ++sepcount;
22276 /* Need full path first (use expand_env() to remove a "~/") */
22277 hasTilde = (**fnamep == '~');
22278 if (hasTilde)
22279 pbuf = tfname = expand_env_save(*fnamep);
22280 else
22281 pbuf = tfname = FullName_save(*fnamep, FALSE);
22283 len = tflen = (int)STRLEN(tfname);
22285 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
22286 return FAIL;
22288 if (len == 0)
22290 /* Don't have a valid filename, so shorten the rest of the
22291 * path if we can. This CAN give us invalid 8.3 filenames, but
22292 * there's not a lot of point in guessing what it might be.
22294 len = tflen;
22295 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
22296 return FAIL;
22299 /* Count the paths backward to find the beginning of the desired string. */
22300 for (p = tfname + len - 1; p >= tfname; --p)
22302 #ifdef FEAT_MBYTE
22303 if (has_mbyte)
22304 p -= mb_head_off(tfname, p);
22305 #endif
22306 if (vim_ispathsep(*p))
22308 if (sepcount == 0 || (hasTilde && sepcount == 1))
22309 break;
22310 else
22311 sepcount --;
22314 if (hasTilde)
22316 --p;
22317 if (p >= tfname)
22318 *p = '~';
22319 else
22320 return FAIL;
22322 else
22323 ++p;
22325 /* Copy in the string - p indexes into tfname - allocated at pbuf */
22326 vim_free(*bufp);
22327 *fnamelen = (int)STRLEN(p);
22328 *bufp = pbuf;
22329 *fnamep = p;
22331 return OK;
22333 #endif /* WIN3264 */
22336 * Adjust a filename, according to a string of modifiers.
22337 * *fnamep must be NUL terminated when called. When returning, the length is
22338 * determined by *fnamelen.
22339 * Returns VALID_ flags or -1 for failure.
22340 * When there is an error, *fnamep is set to NULL.
22343 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
22344 char_u *src; /* string with modifiers */
22345 int *usedlen; /* characters after src that are used */
22346 char_u **fnamep; /* file name so far */
22347 char_u **bufp; /* buffer for allocated file name or NULL */
22348 int *fnamelen; /* length of fnamep */
22350 int valid = 0;
22351 char_u *tail;
22352 char_u *s, *p, *pbuf;
22353 char_u dirname[MAXPATHL];
22354 int c;
22355 int has_fullname = 0;
22356 #ifdef WIN3264
22357 int has_shortname = 0;
22358 #endif
22360 repeat:
22361 /* ":p" - full path/file_name */
22362 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
22364 has_fullname = 1;
22366 valid |= VALID_PATH;
22367 *usedlen += 2;
22369 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
22370 if ((*fnamep)[0] == '~'
22371 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
22372 && ((*fnamep)[1] == '/'
22373 # ifdef BACKSLASH_IN_FILENAME
22374 || (*fnamep)[1] == '\\'
22375 # endif
22376 || (*fnamep)[1] == NUL)
22378 #endif
22381 *fnamep = expand_env_save(*fnamep);
22382 vim_free(*bufp); /* free any allocated file name */
22383 *bufp = *fnamep;
22384 if (*fnamep == NULL)
22385 return -1;
22388 /* When "/." or "/.." is used: force expansion to get rid of it. */
22389 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
22391 if (vim_ispathsep(*p)
22392 && p[1] == '.'
22393 && (p[2] == NUL
22394 || vim_ispathsep(p[2])
22395 || (p[2] == '.'
22396 && (p[3] == NUL || vim_ispathsep(p[3])))))
22397 break;
22400 /* FullName_save() is slow, don't use it when not needed. */
22401 if (*p != NUL || !vim_isAbsName(*fnamep))
22403 *fnamep = FullName_save(*fnamep, *p != NUL);
22404 vim_free(*bufp); /* free any allocated file name */
22405 *bufp = *fnamep;
22406 if (*fnamep == NULL)
22407 return -1;
22410 /* Append a path separator to a directory. */
22411 if (mch_isdir(*fnamep))
22413 /* Make room for one or two extra characters. */
22414 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
22415 vim_free(*bufp); /* free any allocated file name */
22416 *bufp = *fnamep;
22417 if (*fnamep == NULL)
22418 return -1;
22419 add_pathsep(*fnamep);
22423 /* ":." - path relative to the current directory */
22424 /* ":~" - path relative to the home directory */
22425 /* ":8" - shortname path - postponed till after */
22426 while (src[*usedlen] == ':'
22427 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
22429 *usedlen += 2;
22430 if (c == '8')
22432 #ifdef WIN3264
22433 has_shortname = 1; /* Postpone this. */
22434 #endif
22435 continue;
22437 pbuf = NULL;
22438 /* Need full path first (use expand_env() to remove a "~/") */
22439 if (!has_fullname)
22441 if (c == '.' && **fnamep == '~')
22442 p = pbuf = expand_env_save(*fnamep);
22443 else
22444 p = pbuf = FullName_save(*fnamep, FALSE);
22446 else
22447 p = *fnamep;
22449 has_fullname = 0;
22451 if (p != NULL)
22453 if (c == '.')
22455 mch_dirname(dirname, MAXPATHL);
22456 s = shorten_fname(p, dirname);
22457 if (s != NULL)
22459 *fnamep = s;
22460 if (pbuf != NULL)
22462 vim_free(*bufp); /* free any allocated file name */
22463 *bufp = pbuf;
22464 pbuf = NULL;
22468 else
22470 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
22471 /* Only replace it when it starts with '~' */
22472 if (*dirname == '~')
22474 s = vim_strsave(dirname);
22475 if (s != NULL)
22477 *fnamep = s;
22478 vim_free(*bufp);
22479 *bufp = s;
22483 vim_free(pbuf);
22487 tail = gettail(*fnamep);
22488 *fnamelen = (int)STRLEN(*fnamep);
22490 /* ":h" - head, remove "/file_name", can be repeated */
22491 /* Don't remove the first "/" or "c:\" */
22492 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
22494 valid |= VALID_HEAD;
22495 *usedlen += 2;
22496 s = get_past_head(*fnamep);
22497 while (tail > s && after_pathsep(s, tail))
22498 mb_ptr_back(*fnamep, tail);
22499 *fnamelen = (int)(tail - *fnamep);
22500 #ifdef VMS
22501 if (*fnamelen > 0)
22502 *fnamelen += 1; /* the path separator is part of the path */
22503 #endif
22504 if (*fnamelen == 0)
22506 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
22507 p = vim_strsave((char_u *)".");
22508 if (p == NULL)
22509 return -1;
22510 vim_free(*bufp);
22511 *bufp = *fnamep = tail = p;
22512 *fnamelen = 1;
22514 else
22516 while (tail > s && !after_pathsep(s, tail))
22517 mb_ptr_back(*fnamep, tail);
22521 /* ":8" - shortname */
22522 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
22524 *usedlen += 2;
22525 #ifdef WIN3264
22526 has_shortname = 1;
22527 #endif
22530 #ifdef WIN3264
22531 /* Check shortname after we have done 'heads' and before we do 'tails'
22533 if (has_shortname)
22535 pbuf = NULL;
22536 /* Copy the string if it is shortened by :h */
22537 if (*fnamelen < (int)STRLEN(*fnamep))
22539 p = vim_strnsave(*fnamep, *fnamelen);
22540 if (p == 0)
22541 return -1;
22542 vim_free(*bufp);
22543 *bufp = *fnamep = p;
22546 /* Split into two implementations - makes it easier. First is where
22547 * there isn't a full name already, second is where there is.
22549 if (!has_fullname && !vim_isAbsName(*fnamep))
22551 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
22552 return -1;
22554 else
22556 int l;
22558 /* Simple case, already have the full-name
22559 * Nearly always shorter, so try first time. */
22560 l = *fnamelen;
22561 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
22562 return -1;
22564 if (l == 0)
22566 /* Couldn't find the filename.. search the paths.
22568 l = *fnamelen;
22569 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
22570 return -1;
22572 *fnamelen = l;
22575 #endif /* WIN3264 */
22577 /* ":t" - tail, just the basename */
22578 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
22580 *usedlen += 2;
22581 *fnamelen -= (int)(tail - *fnamep);
22582 *fnamep = tail;
22585 /* ":e" - extension, can be repeated */
22586 /* ":r" - root, without extension, can be repeated */
22587 while (src[*usedlen] == ':'
22588 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
22590 /* find a '.' in the tail:
22591 * - for second :e: before the current fname
22592 * - otherwise: The last '.'
22594 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
22595 s = *fnamep - 2;
22596 else
22597 s = *fnamep + *fnamelen - 1;
22598 for ( ; s > tail; --s)
22599 if (s[0] == '.')
22600 break;
22601 if (src[*usedlen + 1] == 'e') /* :e */
22603 if (s > tail)
22605 *fnamelen += (int)(*fnamep - (s + 1));
22606 *fnamep = s + 1;
22607 #ifdef VMS
22608 /* cut version from the extension */
22609 s = *fnamep + *fnamelen - 1;
22610 for ( ; s > *fnamep; --s)
22611 if (s[0] == ';')
22612 break;
22613 if (s > *fnamep)
22614 *fnamelen = s - *fnamep;
22615 #endif
22617 else if (*fnamep <= tail)
22618 *fnamelen = 0;
22620 else /* :r */
22622 if (s > tail) /* remove one extension */
22623 *fnamelen = (int)(s - *fnamep);
22625 *usedlen += 2;
22628 /* ":s?pat?foo?" - substitute */
22629 /* ":gs?pat?foo?" - global substitute */
22630 if (src[*usedlen] == ':'
22631 && (src[*usedlen + 1] == 's'
22632 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
22634 char_u *str;
22635 char_u *pat;
22636 char_u *sub;
22637 int sep;
22638 char_u *flags;
22639 int didit = FALSE;
22641 flags = (char_u *)"";
22642 s = src + *usedlen + 2;
22643 if (src[*usedlen + 1] == 'g')
22645 flags = (char_u *)"g";
22646 ++s;
22649 sep = *s++;
22650 if (sep)
22652 /* find end of pattern */
22653 p = vim_strchr(s, sep);
22654 if (p != NULL)
22656 pat = vim_strnsave(s, (int)(p - s));
22657 if (pat != NULL)
22659 s = p + 1;
22660 /* find end of substitution */
22661 p = vim_strchr(s, sep);
22662 if (p != NULL)
22664 sub = vim_strnsave(s, (int)(p - s));
22665 str = vim_strnsave(*fnamep, *fnamelen);
22666 if (sub != NULL && str != NULL)
22668 *usedlen = (int)(p + 1 - src);
22669 s = do_string_sub(str, pat, sub, flags);
22670 if (s != NULL)
22672 *fnamep = s;
22673 *fnamelen = (int)STRLEN(s);
22674 vim_free(*bufp);
22675 *bufp = s;
22676 didit = TRUE;
22679 vim_free(sub);
22680 vim_free(str);
22682 vim_free(pat);
22685 /* after using ":s", repeat all the modifiers */
22686 if (didit)
22687 goto repeat;
22691 return valid;
22695 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
22696 * "flags" can be "g" to do a global substitute.
22697 * Returns an allocated string, NULL for error.
22699 char_u *
22700 do_string_sub(str, pat, sub, flags)
22701 char_u *str;
22702 char_u *pat;
22703 char_u *sub;
22704 char_u *flags;
22706 int sublen;
22707 regmatch_T regmatch;
22708 int i;
22709 int do_all;
22710 char_u *tail;
22711 garray_T ga;
22712 char_u *ret;
22713 char_u *save_cpo;
22715 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
22716 save_cpo = p_cpo;
22717 p_cpo = empty_option;
22719 ga_init2(&ga, 1, 200);
22721 do_all = (flags[0] == 'g');
22723 regmatch.rm_ic = p_ic;
22724 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
22725 if (regmatch.regprog != NULL)
22727 tail = str;
22728 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
22731 * Get some space for a temporary buffer to do the substitution
22732 * into. It will contain:
22733 * - The text up to where the match is.
22734 * - The substituted text.
22735 * - The text after the match.
22737 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
22738 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
22739 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
22741 ga_clear(&ga);
22742 break;
22745 /* copy the text up to where the match is */
22746 i = (int)(regmatch.startp[0] - tail);
22747 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
22748 /* add the substituted text */
22749 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
22750 + ga.ga_len + i, TRUE, TRUE, FALSE);
22751 ga.ga_len += i + sublen - 1;
22752 /* avoid getting stuck on a match with an empty string */
22753 if (tail == regmatch.endp[0])
22755 if (*tail == NUL)
22756 break;
22757 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
22758 ++ga.ga_len;
22760 else
22762 tail = regmatch.endp[0];
22763 if (*tail == NUL)
22764 break;
22766 if (!do_all)
22767 break;
22770 if (ga.ga_data != NULL)
22771 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
22773 vim_free(regmatch.regprog);
22776 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
22777 ga_clear(&ga);
22778 if (p_cpo == empty_option)
22779 p_cpo = save_cpo;
22780 else
22781 /* Darn, evaluating {sub} expression changed the value. */
22782 free_string_option(save_cpo);
22784 return ret;
22787 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */