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.
11 * eval.c: Expression evaluation.
16 #if defined(FEAT_EVAL) || defined(PROTO)
19 # include <time.h> /* for strftime() */
27 # include <time.h> /* for time_t */
30 #if defined(FEAT_FLOAT) && defined(HAVE_MATH_H)
34 #define DICT_MAXNEST 100 /* maximum nesting of lists and dicts */
36 #define DO_NOT_FREE_CNT 99999 /* refcount for dict or list that should not
40 * In a hashtab item "hi_key" points to "di_key" in a dictitem.
41 * This avoids adding a pointer to the hashtab item.
42 * DI2HIKEY() converts a dictitem pointer to a hashitem key pointer.
43 * HIKEY2DI() converts a hashitem key pointer to a dictitem pointer.
44 * HI2DI() converts a hashitem pointer to a dictitem pointer.
46 static dictitem_T dumdi;
47 #define DI2HIKEY(di) ((di)->di_key)
48 #define HIKEY2DI(p) ((dictitem_T *)(p - (dumdi.di_key - (char_u *)&dumdi)))
49 #define HI2DI(hi) HIKEY2DI((hi)->hi_key)
52 * Structure returned by get_lval() and used by set_var_lval().
54 * "name" points to the variable name.
57 * For a magic braces name:
58 * "name" points to the expanded variable name.
59 * "exp_name" is non-NULL, to be freed later.
61 * For an index in a list:
62 * "name" points to the (expanded) variable name.
63 * "exp_name" NULL or non-NULL, to be freed later.
64 * "tv" points to the (first) list item value
65 * "li" points to the (first) list item
66 * "range", "n1", "n2" and "empty2" indicate what items are used.
67 * For an existing Dict item:
68 * "name" points to the (expanded) variable name.
69 * "exp_name" NULL or non-NULL, to be freed later.
70 * "tv" points to the dict item value
72 * For a non-existing Dict item:
73 * "name" points to the (expanded) variable name.
74 * "exp_name" NULL or non-NULL, to be freed later.
75 * "tv" points to the Dictionary typval_T
76 * "newkey" is the key for the new item.
80 char_u *ll_name; /* start of variable name (can be NULL) */
81 char_u *ll_exp_name; /* NULL or expanded name in allocated memory. */
82 typval_T *ll_tv; /* Typeval of item being used. If "newkey"
83 isn't NULL it's the Dict to which to add
85 listitem_T *ll_li; /* The list item or NULL. */
86 list_T *ll_list; /* The list or NULL. */
87 int ll_range; /* TRUE when a [i:j] range was used */
88 long ll_n1; /* First index for list */
89 long ll_n2; /* Second index for list range */
90 int ll_empty2; /* Second index is empty: [i:] */
91 dict_T *ll_dict; /* The Dictionary or NULL */
92 dictitem_T *ll_di; /* The dictitem or NULL */
93 char_u *ll_newkey; /* New key for Dict in alloc. mem or NULL. */
97 static char *e_letunexp = N_("E18: Unexpected characters in :let");
98 static char *e_listidx = N_("E684: list index out of range: %ld");
99 static char *e_undefvar = N_("E121: Undefined variable: %s");
100 static char *e_missbrac = N_("E111: Missing ']'");
101 static char *e_listarg = N_("E686: Argument of %s must be a List");
102 static char *e_listdictarg = N_("E712: Argument of %s must be a List or Dictionary");
103 static char *e_emptykey = N_("E713: Cannot use empty key for Dictionary");
104 static char *e_listreq = N_("E714: List required");
105 static char *e_dictreq = N_("E715: Dictionary required");
106 static char *e_toomanyarg = N_("E118: Too many arguments for function: %s");
107 static char *e_dictkey = N_("E716: Key not present in Dictionary: %s");
108 static char *e_funcexts = N_("E122: Function %s already exists, add ! to replace it");
109 static char *e_funcdict = N_("E717: Dictionary entry already exists");
110 static char *e_funcref = N_("E718: Funcref required");
111 static char *e_dictrange = N_("E719: Cannot use [:] with a Dictionary");
112 static char *e_letwrong = N_("E734: Wrong variable type for %s=");
113 static char *e_nofunc = N_("E130: Unknown function: %s");
114 static char *e_illvar = N_("E461: Illegal variable name: %s");
117 * All user-defined global variables are stored in dictionary "globvardict".
118 * "globvars_var" is the variable that is used for "g:".
120 static dict_T globvardict;
121 static dictitem_T globvars_var;
122 #define globvarht globvardict.dv_hashtab
125 * Old Vim variables such as "v:version" are also available without the "v:".
126 * Also in functions. We need a special hashtable for them.
128 static hashtab_T compat_hashtab;
130 /* When using exists() don't auto-load a script. */
131 static int no_autoload = FALSE;
134 * When recursively copying lists and dicts we need to remember which ones we
135 * have done to avoid endless recursiveness. This unique ID is used for that.
136 * The last bit is used for previous_funccal, ignored when comparing.
138 static int current_copyID = 0;
140 #define COPYID_MASK (~0x1)
143 * Array to hold the hashtab with variables local to each sourced script.
144 * Each item holds a variable (nameless) that points to the dict_T.
152 static garray_T ga_scripts = {0, 0, sizeof(scriptvar_T *), 4, NULL};
153 #define SCRIPT_SV(id) (((scriptvar_T **)ga_scripts.ga_data)[(id) - 1])
154 #define SCRIPT_VARS(id) (SCRIPT_SV(id)->sv_dict.dv_hashtab)
156 static int echo_attr = 0; /* attributes used for ":echo" */
158 /* Values for trans_function_name() argument: */
159 #define TFN_INT 1 /* internal function name OK */
160 #define TFN_QUIET 2 /* no error messages */
163 * Structure to hold info for a user function.
165 typedef struct ufunc ufunc_T;
169 int uf_varargs; /* variable nr of arguments */
171 int uf_calls; /* nr of active calls */
172 garray_T uf_args; /* arguments */
173 garray_T uf_lines; /* function lines */
175 int uf_profiling; /* TRUE when func is being profiled */
176 /* profiling the function as a whole */
177 int uf_tm_count; /* nr of calls */
178 proftime_T uf_tm_total; /* time spent in function + children */
179 proftime_T uf_tm_self; /* time spent in function itself */
180 proftime_T uf_tm_children; /* time spent in children this call */
181 /* profiling the function per line */
182 int *uf_tml_count; /* nr of times line was executed */
183 proftime_T *uf_tml_total; /* time spent in a line + children */
184 proftime_T *uf_tml_self; /* time spent in a line itself */
185 proftime_T uf_tml_start; /* start time for current line */
186 proftime_T uf_tml_children; /* time spent in children for this line */
187 proftime_T uf_tml_wait; /* start wait time for current line */
188 int uf_tml_idx; /* index of line being timed; -1 if none */
189 int uf_tml_execed; /* line being timed was executed */
191 scid_T uf_script_ID; /* ID of script where function was defined,
192 used for s: variables */
193 int uf_refcount; /* for numbered function: reference count */
194 char_u uf_name[1]; /* name of function (actually longer); can
195 start with <SNR>123_ (<SNR> is K_SPECIAL
200 #define FC_ABORT 1 /* abort function on error */
201 #define FC_RANGE 2 /* function accepts range */
202 #define FC_DICT 4 /* Dict function, uses "self" */
205 * All user-defined functions are found in this hashtable.
207 static hashtab_T func_hashtab;
209 /* The names of packages that once were loaded are remembered. */
210 static garray_T ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
212 /* list heads for garbage collection */
213 static dict_T *first_dict = NULL; /* list of all dicts */
214 static list_T *first_list = NULL; /* list of all lists */
216 /* From user function to hashitem and back. */
217 static ufunc_T dumuf;
218 #define UF2HIKEY(fp) ((fp)->uf_name)
219 #define HIKEY2UF(p) ((ufunc_T *)(p - (dumuf.uf_name - (char_u *)&dumuf)))
220 #define HI2UF(hi) HIKEY2UF((hi)->hi_key)
222 #define FUNCARG(fp, j) ((char_u **)(fp->uf_args.ga_data))[j]
223 #define FUNCLINE(fp, j) ((char_u **)(fp->uf_lines.ga_data))[j]
225 #define MAX_FUNC_ARGS 20 /* maximum number of function arguments */
226 #define VAR_SHORT_LEN 20 /* short variable name length */
227 #define FIXVAR_CNT 12 /* number of fixed variables */
229 /* structure to hold info for a function that is currently being executed. */
230 typedef struct funccall_S funccall_T;
234 ufunc_T *func; /* function being called */
235 int linenr; /* next line to be executed */
236 int returned; /* ":return" used */
237 struct /* fixed variables for arguments */
239 dictitem_T var; /* variable (without room for name) */
240 char_u room[VAR_SHORT_LEN]; /* room for the name */
241 } fixvar[FIXVAR_CNT];
242 dict_T l_vars; /* l: local function variables */
243 dictitem_T l_vars_var; /* variable for l: scope */
244 dict_T l_avars; /* a: argument variables */
245 dictitem_T l_avars_var; /* variable for a: scope */
246 list_T l_varlist; /* list for a:000 */
247 listitem_T l_listitems[MAX_FUNC_ARGS]; /* listitems for a:000 */
248 typval_T *rettv; /* return value */
249 linenr_T breakpoint; /* next line with breakpoint or zero */
250 int dbg_tick; /* debug_tick when breakpoint was set */
251 int level; /* top nesting level of executed function */
253 proftime_T prof_child; /* time spent in a child */
255 funccall_T *caller; /* calling function or NULL */
259 * Info used by a ":for" loop.
263 int fi_semicolon; /* TRUE if ending in '; var]' */
264 int fi_varcount; /* nr of variables in the list */
265 listwatch_T fi_lw; /* keep an eye on the item used. */
266 list_T *fi_list; /* list being used */
270 * Struct used by trans_function_name()
274 dict_T *fd_dict; /* Dictionary used */
275 char_u *fd_newkey; /* new key in "dict" in allocated memory */
276 dictitem_T *fd_di; /* Dictionary item used */
281 * Array to hold the value of v: variables.
282 * The value is in a dictitem, so that it can also be used in the v: scope.
283 * The reason to use this table anyway is for very quick access to the
284 * variables with the VV_ defines.
288 /* values for vv_flags: */
289 #define VV_COMPAT 1 /* compatible, also used without "v:" */
290 #define VV_RO 2 /* read-only */
291 #define VV_RO_SBX 4 /* read-only in the sandbox */
293 #define VV_NAME(s, t) s, {{t, 0, {0}}, 0, {0}}, {0}
297 char *vv_name; /* name of variable, without v: */
298 dictitem_T vv_di; /* value and name for key */
299 char vv_filler[16]; /* space for LONGEST name below!!! */
300 char vv_flags; /* VV_COMPAT, VV_RO, VV_RO_SBX */
304 * The order here must match the VV_ defines in vim.h!
305 * Initializing a union does not work, leave tv.vval empty to get zero's.
307 {VV_NAME("count", VAR_NUMBER), VV_COMPAT+VV_RO},
308 {VV_NAME("count1", VAR_NUMBER), VV_RO},
309 {VV_NAME("prevcount", VAR_NUMBER), VV_RO},
310 {VV_NAME("errmsg", VAR_STRING), VV_COMPAT},
311 {VV_NAME("warningmsg", VAR_STRING), 0},
312 {VV_NAME("statusmsg", VAR_STRING), 0},
313 {VV_NAME("shell_error", VAR_NUMBER), VV_COMPAT+VV_RO},
314 {VV_NAME("this_session", VAR_STRING), VV_COMPAT},
315 {VV_NAME("version", VAR_NUMBER), VV_COMPAT+VV_RO},
316 {VV_NAME("lnum", VAR_NUMBER), VV_RO_SBX},
317 {VV_NAME("termresponse", VAR_STRING), VV_RO},
318 {VV_NAME("fname", VAR_STRING), VV_RO},
319 {VV_NAME("lang", VAR_STRING), VV_RO},
320 {VV_NAME("lc_time", VAR_STRING), VV_RO},
321 {VV_NAME("ctype", VAR_STRING), VV_RO},
322 {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
323 {VV_NAME("charconvert_to", VAR_STRING), VV_RO},
324 {VV_NAME("fname_in", VAR_STRING), VV_RO},
325 {VV_NAME("fname_out", VAR_STRING), VV_RO},
326 {VV_NAME("fname_new", VAR_STRING), VV_RO},
327 {VV_NAME("fname_diff", VAR_STRING), VV_RO},
328 {VV_NAME("cmdarg", VAR_STRING), VV_RO},
329 {VV_NAME("foldstart", VAR_NUMBER), VV_RO_SBX},
330 {VV_NAME("foldend", VAR_NUMBER), VV_RO_SBX},
331 {VV_NAME("folddashes", VAR_STRING), VV_RO_SBX},
332 {VV_NAME("foldlevel", VAR_NUMBER), VV_RO_SBX},
333 {VV_NAME("progname", VAR_STRING), VV_RO},
334 {VV_NAME("servername", VAR_STRING), VV_RO},
335 {VV_NAME("dying", VAR_NUMBER), VV_RO},
336 {VV_NAME("exception", VAR_STRING), VV_RO},
337 {VV_NAME("throwpoint", VAR_STRING), VV_RO},
338 {VV_NAME("register", VAR_STRING), VV_RO},
339 {VV_NAME("cmdbang", VAR_NUMBER), VV_RO},
340 {VV_NAME("insertmode", VAR_STRING), VV_RO},
341 {VV_NAME("val", VAR_UNKNOWN), VV_RO},
342 {VV_NAME("key", VAR_UNKNOWN), VV_RO},
343 {VV_NAME("profiling", VAR_NUMBER), VV_RO},
344 {VV_NAME("fcs_reason", VAR_STRING), VV_RO},
345 {VV_NAME("fcs_choice", VAR_STRING), 0},
346 {VV_NAME("beval_bufnr", VAR_NUMBER), VV_RO},
347 {VV_NAME("beval_winnr", VAR_NUMBER), VV_RO},
348 {VV_NAME("beval_lnum", VAR_NUMBER), VV_RO},
349 {VV_NAME("beval_col", VAR_NUMBER), VV_RO},
350 {VV_NAME("beval_text", VAR_STRING), VV_RO},
351 {VV_NAME("scrollstart", VAR_STRING), 0},
352 {VV_NAME("swapname", VAR_STRING), VV_RO},
353 {VV_NAME("swapchoice", VAR_STRING), 0},
354 {VV_NAME("swapcommand", VAR_STRING), VV_RO},
355 {VV_NAME("char", VAR_STRING), 0},
356 {VV_NAME("mouse_win", VAR_NUMBER), 0},
357 {VV_NAME("mouse_lnum", VAR_NUMBER), 0},
358 {VV_NAME("mouse_col", VAR_NUMBER), 0},
359 {VV_NAME("operator", VAR_STRING), VV_RO},
360 {VV_NAME("searchforward", VAR_NUMBER), 0},
361 {VV_NAME("oldfiles", VAR_LIST), 0},
362 {VV_NAME("windowid", VAR_NUMBER), VV_RO},
366 #define vv_type vv_di.di_tv.v_type
367 #define vv_nr vv_di.di_tv.vval.v_number
368 #define vv_float vv_di.di_tv.vval.v_float
369 #define vv_str vv_di.di_tv.vval.v_string
370 #define vv_list vv_di.di_tv.vval.v_list
371 #define vv_tv vv_di.di_tv
374 * The v: variables are stored in dictionary "vimvardict".
375 * "vimvars_var" is the variable that is used for the "l:" scope.
377 static dict_T vimvardict;
378 static dictitem_T vimvars_var;
379 #define vimvarht vimvardict.dv_hashtab
381 static void prepare_vimvar __ARGS((int idx, typval_T *save_tv));
382 static void restore_vimvar __ARGS((int idx, typval_T *save_tv));
383 static int ex_let_vars __ARGS((char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars));
384 static char_u *skip_var_list __ARGS((char_u *arg, int *var_count, int *semicolon));
385 static char_u *skip_var_one __ARGS((char_u *arg));
386 static void list_hashtable_vars __ARGS((hashtab_T *ht, char_u *prefix, int empty, int *first));
387 static void list_glob_vars __ARGS((int *first));
388 static void list_buf_vars __ARGS((int *first));
389 static void list_win_vars __ARGS((int *first));
391 static void list_tab_vars __ARGS((int *first));
393 static void list_vim_vars __ARGS((int *first));
394 static void list_script_vars __ARGS((int *first));
395 static void list_func_vars __ARGS((int *first));
396 static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg, int *first));
397 static char_u *ex_let_one __ARGS((char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op));
398 static int check_changedtick __ARGS((char_u *arg));
399 static char_u *get_lval __ARGS((char_u *name, typval_T *rettv, lval_T *lp, int unlet, int skip, int quiet, int fne_flags));
400 static void clear_lval __ARGS((lval_T *lp));
401 static void set_var_lval __ARGS((lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op));
402 static int tv_op __ARGS((typval_T *tv1, typval_T *tv2, char_u *op));
403 static void list_add_watch __ARGS((list_T *l, listwatch_T *lw));
404 static void list_rem_watch __ARGS((list_T *l, listwatch_T *lwrem));
405 static void list_fix_watch __ARGS((list_T *l, listitem_T *item));
406 static void ex_unletlock __ARGS((exarg_T *eap, char_u *argstart, int deep));
407 static int do_unlet_var __ARGS((lval_T *lp, char_u *name_end, int forceit));
408 static int do_lock_var __ARGS((lval_T *lp, char_u *name_end, int deep, int lock));
409 static void item_lock __ARGS((typval_T *tv, int deep, int lock));
410 static int tv_islocked __ARGS((typval_T *tv));
412 static int eval0 __ARGS((char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate));
413 static int eval1 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
414 static int eval2 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
415 static int eval3 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
416 static int eval4 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
417 static int eval5 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
418 static int eval6 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
419 static int eval7 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
421 static int eval_index __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
422 static int get_option_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
423 static int get_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
424 static int get_lit_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
425 static int get_list_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
426 static int rettv_list_alloc __ARGS((typval_T *rettv));
427 static listitem_T *listitem_alloc __ARGS((void));
428 static void listitem_free __ARGS((listitem_T *item));
429 static void listitem_remove __ARGS((list_T *l, listitem_T *item));
430 static long list_len __ARGS((list_T *l));
431 static int list_equal __ARGS((list_T *l1, list_T *l2, int ic, int recursive));
432 static int dict_equal __ARGS((dict_T *d1, dict_T *d2, int ic, int recursive));
433 static int tv_equal __ARGS((typval_T *tv1, typval_T *tv2, int ic, int recursive));
434 static listitem_T *list_find __ARGS((list_T *l, long n));
435 static long list_find_nr __ARGS((list_T *l, long idx, int *errorp));
436 static long list_idx_of_item __ARGS((list_T *l, listitem_T *item));
437 static void list_append __ARGS((list_T *l, listitem_T *item));
438 static int list_append_number __ARGS((list_T *l, varnumber_T n));
439 static int list_insert_tv __ARGS((list_T *l, typval_T *tv, listitem_T *item));
440 static int list_extend __ARGS((list_T *l1, list_T *l2, listitem_T *bef));
441 static int list_concat __ARGS((list_T *l1, list_T *l2, typval_T *tv));
442 static list_T *list_copy __ARGS((list_T *orig, int deep, int copyID));
443 static void list_remove __ARGS((list_T *l, listitem_T *item, listitem_T *item2));
444 static char_u *list2string __ARGS((typval_T *tv, int copyID));
445 static int list_join __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo, int copyID));
446 static int free_unref_items __ARGS((int copyID));
447 static void set_ref_in_ht __ARGS((hashtab_T *ht, int copyID));
448 static void set_ref_in_list __ARGS((list_T *l, int copyID));
449 static void set_ref_in_item __ARGS((typval_T *tv, int copyID));
450 static int rettv_dict_alloc __ARGS((typval_T *rettv));
451 static void dict_free __ARGS((dict_T *d, int recurse));
452 static dictitem_T *dictitem_copy __ARGS((dictitem_T *org));
453 static void dictitem_remove __ARGS((dict_T *dict, dictitem_T *item));
454 static dict_T *dict_copy __ARGS((dict_T *orig, int deep, int copyID));
455 static long dict_len __ARGS((dict_T *d));
456 static char_u *dict2string __ARGS((typval_T *tv, int copyID));
457 static int get_dict_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
458 static char_u *echo_string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
459 static char_u *tv2string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
460 static char_u *string_quote __ARGS((char_u *str, int function));
462 static int string2float __ARGS((char_u *text, float_T *value));
464 static int get_env_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
465 static int find_internal_func __ARGS((char_u *name));
466 static char_u *deref_func_name __ARGS((char_u *name, int *lenp));
467 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));
468 static int call_func __ARGS((char_u *funcname, int len, typval_T *rettv, int argcount, typval_T *argvars, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
469 static void emsg_funcname __ARGS((char *ermsg, char_u *name));
470 static int non_zero_arg __ARGS((typval_T *argvars));
473 static void f_abs __ARGS((typval_T *argvars, typval_T *rettv));
474 static void f_acos __ARGS((typval_T *argvars, typval_T *rettv));
476 static void f_add __ARGS((typval_T *argvars, typval_T *rettv));
477 static void f_and __ARGS((typval_T *argvars, typval_T *rettv));
478 static void f_append __ARGS((typval_T *argvars, typval_T *rettv));
479 static void f_argc __ARGS((typval_T *argvars, typval_T *rettv));
480 static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv));
481 static void f_argv __ARGS((typval_T *argvars, typval_T *rettv));
483 static void f_asin __ARGS((typval_T *argvars, typval_T *rettv));
484 static void f_atan __ARGS((typval_T *argvars, typval_T *rettv));
485 static void f_atan2 __ARGS((typval_T *argvars, typval_T *rettv));
487 static void f_browse __ARGS((typval_T *argvars, typval_T *rettv));
488 static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv));
489 static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv));
490 static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv));
491 static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv));
492 static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv));
493 static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv));
494 static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv));
495 static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv));
496 static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv));
497 static void f_call __ARGS((typval_T *argvars, typval_T *rettv));
499 static void f_ceil __ARGS((typval_T *argvars, typval_T *rettv));
501 static void f_changenr __ARGS((typval_T *argvars, typval_T *rettv));
502 static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv));
503 static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv));
504 static void f_clearmatches __ARGS((typval_T *argvars, typval_T *rettv));
505 static void f_col __ARGS((typval_T *argvars, typval_T *rettv));
506 #if defined(FEAT_INS_EXPAND)
507 static void f_complete __ARGS((typval_T *argvars, typval_T *rettv));
508 static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv));
509 static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv));
511 static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_copy __ARGS((typval_T *argvars, typval_T *rettv));
514 static void f_cos __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_cosh __ARGS((typval_T *argvars, typval_T *rettv));
517 static void f_count __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv));
520 static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv));
521 static void f_delete __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv));
523 static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv));
524 static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv));
525 static void f_empty __ARGS((typval_T *argvars, typval_T *rettv));
526 static void f_escape __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_eval __ARGS((typval_T *argvars, typval_T *rettv));
528 static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv));
529 static void f_executable __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_exists __ARGS((typval_T *argvars, typval_T *rettv));
532 static void f_exp __ARGS((typval_T *argvars, typval_T *rettv));
534 static void f_expand __ARGS((typval_T *argvars, typval_T *rettv));
535 static void f_extend __ARGS((typval_T *argvars, typval_T *rettv));
536 static void f_feedkeys __ARGS((typval_T *argvars, typval_T *rettv));
537 static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_filter __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_float2nr __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_floor __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_fmod __ARGS((typval_T *argvars, typval_T *rettv));
547 static void f_fnameescape __ARGS((typval_T *argvars, typval_T *rettv));
548 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
549 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
551 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
552 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_getpid __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_gettabvar __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
590 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
591 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
592 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
593 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
594 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
595 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
596 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
603 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
604 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
605 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
606 static void f_invert __ARGS((typval_T *argvars, typval_T *rettv));
607 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
608 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
609 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
610 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
611 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
618 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
619 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
621 static void f_log __ARGS((typval_T *argvars, typval_T *rettv));
622 static void f_log10 __ARGS((typval_T *argvars, typval_T *rettv));
624 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
625 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
626 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
627 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
628 static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv));
629 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
630 static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv));
631 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
632 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
633 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
634 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
635 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
637 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
639 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
641 static void f_mzeval __ARGS((typval_T *argvars, typval_T *rettv));
643 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
644 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
645 static void f_or __ARGS((typval_T *argvars, typval_T *rettv));
646 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
648 static void f_pow __ARGS((typval_T *argvars, typval_T *rettv));
650 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
651 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
652 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
653 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
654 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
655 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
656 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
657 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
668 static void f_round __ARGS((typval_T *argvars, typval_T *rettv));
670 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
671 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
672 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
673 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
674 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
675 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
676 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
677 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
678 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
679 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
680 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
681 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
682 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
683 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
684 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
685 static void f_settabvar __ARGS((typval_T *argvars, typval_T *rettv));
686 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
687 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
688 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
689 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
691 static void f_sin __ARGS((typval_T *argvars, typval_T *rettv));
692 static void f_sinh __ARGS((typval_T *argvars, typval_T *rettv));
694 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
695 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
696 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
697 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
698 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
700 static void f_sqrt __ARGS((typval_T *argvars, typval_T *rettv));
701 static void f_str2float __ARGS((typval_T *argvars, typval_T *rettv));
703 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
704 static void f_strchars __ARGS((typval_T *argvars, typval_T *rettv));
706 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
708 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
709 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
710 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
711 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
712 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
713 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
714 static void f_strdisplaywidth __ARGS((typval_T *argvars, typval_T *rettv));
715 static void f_strwidth __ARGS((typval_T *argvars, typval_T *rettv));
716 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
717 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
718 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
719 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
720 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
721 static void f_synstack __ARGS((typval_T *argvars, typval_T *rettv));
722 static void f_synconcealed __ARGS((typval_T *argvars, typval_T *rettv));
723 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
724 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
725 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
726 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
727 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
728 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
729 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
730 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
732 static void f_tan __ARGS((typval_T *argvars, typval_T *rettv));
733 static void f_tanh __ARGS((typval_T *argvars, typval_T *rettv));
735 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
736 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
737 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
739 static void f_trunc __ARGS((typval_T *argvars, typval_T *rettv));
741 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
742 static void f_undofile __ARGS((typval_T *argvars, typval_T *rettv));
743 static void f_undotree __ARGS((typval_T *argvars, typval_T *rettv));
744 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
745 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
746 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
747 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
748 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
749 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
750 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
751 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
752 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
753 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
754 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
755 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
756 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
757 static void f_xor __ARGS((typval_T *argvars, typval_T *rettv));
759 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
760 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
761 static int get_env_len __ARGS((char_u **arg));
762 static int get_id_len __ARGS((char_u **arg));
763 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
764 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
765 #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */
766 #define FNE_CHECK_START 2 /* find_name_end(): check name starts with
768 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
769 static int eval_isnamec __ARGS((int c));
770 static int eval_isnamec1 __ARGS((int c));
771 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
772 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
773 static typval_T *alloc_tv __ARGS((void));
774 static typval_T *alloc_string_tv __ARGS((char_u *string));
775 static void init_tv __ARGS((typval_T *varp));
776 static long get_tv_number __ARGS((typval_T *varp));
777 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
778 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
779 static char_u *get_tv_string __ARGS((typval_T *varp));
780 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
781 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
782 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
783 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
784 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
785 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
786 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
787 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
788 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
789 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
790 static int var_check_ro __ARGS((int flags, char_u *name));
791 static int var_check_fixed __ARGS((int flags, char_u *name));
792 static int var_check_func_name __ARGS((char_u *name, int new_var));
793 static int valid_varname __ARGS((char_u *varname));
794 static int tv_check_lock __ARGS((int lock, char_u *name));
795 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
796 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
797 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
798 static int eval_fname_script __ARGS((char_u *p));
799 static int eval_fname_sid __ARGS((char_u *p));
800 static void list_func_head __ARGS((ufunc_T *fp, int indent));
801 static ufunc_T *find_func __ARGS((char_u *name));
802 static int function_exists __ARGS((char_u *name));
803 static int builtin_function __ARGS((char_u *name));
805 static void func_do_profile __ARGS((ufunc_T *fp));
806 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
807 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
812 prof_total_cmp __ARGS((const void *s1, const void *s2));
817 prof_self_cmp __ARGS((const void *s1, const void *s2));
819 static int script_autoload __ARGS((char_u *name, int reload));
820 static char_u *autoload_name __ARGS((char_u *name));
821 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
822 static void func_free __ARGS((ufunc_T *fp));
823 static void func_unref __ARGS((char_u *name));
824 static void func_ref __ARGS((char_u *name));
825 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));
826 static int can_free_funccal __ARGS((funccall_T *fc, int copyID)) ;
827 static void free_funccal __ARGS((funccall_T *fc, int free_val));
828 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
829 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
830 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
831 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
832 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
833 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
837 static int compare_func_name __ARGS((const void *s1, const void *s2));
838 static void sortFunctions __ARGS(());
842 /* Character used as separated in autoload function/variable names. */
843 #define AUTOLOAD_CHAR '#'
846 * Initialize the global and v: variables.
854 init_var_dict(&globvardict, &globvars_var);
855 init_var_dict(&vimvardict, &vimvars_var);
856 vimvardict.dv_lock = VAR_FIXED;
857 hash_init(&compat_hashtab);
858 hash_init(&func_hashtab);
860 for (i = 0; i < VV_LEN; ++i)
863 STRCPY(p->vv_di.di_key, p->vv_name);
864 if (p->vv_flags & VV_RO)
865 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
866 else if (p->vv_flags & VV_RO_SBX)
867 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
869 p->vv_di.di_flags = DI_FLAGS_FIX;
871 /* add to v: scope dict, unless the value is not always available */
872 if (p->vv_type != VAR_UNKNOWN)
873 hash_add(&vimvarht, p->vv_di.di_key);
874 if (p->vv_flags & VV_COMPAT)
875 /* add to compat scope dict */
876 hash_add(&compat_hashtab, p->vv_di.di_key);
878 set_vim_var_nr(VV_SEARCHFORWARD, 1L);
882 * Sort the function table, to enable binary search.
888 #if defined(EXITFREE) || defined(PROTO)
895 for (i = 0; i < VV_LEN; ++i)
898 if (p->vv_di.di_tv.v_type == VAR_STRING)
903 else if (p->vv_di.di_tv.v_type == VAR_LIST)
905 list_unref(p->vv_list);
909 hash_clear(&vimvarht);
910 hash_init(&vimvarht); /* garbage_collect() will access it */
911 hash_clear(&compat_hashtab);
916 /* global variables */
917 vars_clear(&globvarht);
919 /* autoloaded script names */
920 ga_clear_strings(&ga_loaded);
922 /* script-local variables */
923 for (i = 1; i <= ga_scripts.ga_len; ++i)
925 vars_clear(&SCRIPT_VARS(i));
926 vim_free(SCRIPT_SV(i));
928 ga_clear(&ga_scripts);
930 /* unreferenced lists and dicts */
931 (void)garbage_collect();
934 free_all_functions();
935 hash_clear(&func_hashtab);
940 * Return the name of the executed function.
946 return ((funccall_T *)cookie)->func->uf_name;
950 * Return the address holding the next breakpoint line for a funccall cookie.
953 func_breakpoint(cookie)
956 return &((funccall_T *)cookie)->breakpoint;
960 * Return the address holding the debug tick for a funccall cookie.
963 func_dbg_tick(cookie)
966 return &((funccall_T *)cookie)->dbg_tick;
970 * Return the nesting level for a funccall cookie.
976 return ((funccall_T *)cookie)->level;
979 /* pointer to funccal for currently active function */
980 funccall_T *current_funccal = NULL;
982 /* pointer to list of previously used funccal, still around because some
983 * item in it is still being used. */
984 funccall_T *previous_funccal = NULL;
987 * Return TRUE when a function was ended by a ":return" command.
990 current_func_returned()
992 return current_funccal->returned;
997 * Set an internal variable to a string value. Creates the variable if it does
1001 set_internal_string_var(name, value)
1008 val = vim_strsave(value);
1011 tvp = alloc_string_tv(val);
1014 set_var(name, tvp, FALSE);
1020 static lval_T *redir_lval = NULL;
1021 static garray_T redir_ga; /* only valid when redir_lval is not NULL */
1022 static char_u *redir_endp = NULL;
1023 static char_u *redir_varname = NULL;
1026 * Start recording command output to a variable
1027 * Returns OK if successfully completed the setup. FAIL otherwise.
1030 var_redir_start(name, append)
1032 int append; /* append to an existing variable */
1038 /* Catch a bad name early. */
1039 if (!eval_isnamec1(*name))
1045 /* Make a copy of the name, it is used in redir_lval until redir ends. */
1046 redir_varname = vim_strsave(name);
1047 if (redir_varname == NULL)
1050 redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
1051 if (redir_lval == NULL)
1057 /* The output is stored in growarray "redir_ga" until redirection ends. */
1058 ga_init2(&redir_ga, (int)sizeof(char), 500);
1060 /* Parse the variable name (can be a dict or list entry). */
1061 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
1063 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
1065 clear_lval(redir_lval);
1066 if (redir_endp != NULL && *redir_endp != NUL)
1067 /* Trailing characters are present after the variable name */
1068 EMSG(_(e_trailing));
1071 redir_endp = NULL; /* don't store a value, only cleanup */
1076 /* check if we can write to the variable: set it to or append an empty
1078 save_emsg = did_emsg;
1080 tv.v_type = VAR_STRING;
1081 tv.vval.v_string = (char_u *)"";
1083 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
1085 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
1086 clear_lval(redir_lval);
1088 did_emsg |= save_emsg;
1091 redir_endp = NULL; /* don't store a value, only cleanup */
1100 * Append "value[value_len]" to the variable set by var_redir_start().
1101 * The actual appending is postponed until redirection ends, because the value
1102 * appended may in fact be the string we write to, changing it may cause freed
1103 * memory to be used:
1109 var_redir_str(value, value_len)
1115 if (redir_lval == NULL)
1118 if (value_len == -1)
1119 len = (int)STRLEN(value); /* Append the entire string */
1121 len = value_len; /* Append only "value_len" characters */
1123 if (ga_grow(&redir_ga, len) == OK)
1125 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1126 redir_ga.ga_len += len;
1133 * Stop redirecting command output to a variable.
1134 * Frees the allocated memory.
1141 if (redir_lval != NULL)
1143 /* If there was no error: assign the text to the variable. */
1144 if (redir_endp != NULL)
1146 ga_append(&redir_ga, NUL); /* Append the trailing NUL. */
1147 tv.v_type = VAR_STRING;
1148 tv.vval.v_string = redir_ga.ga_data;
1149 /* Call get_lval() again, if it's inside a Dict or List it may
1151 redir_endp = get_lval(redir_varname, NULL, redir_lval,
1152 FALSE, FALSE, FALSE, FNE_CHECK_START);
1153 if (redir_endp != NULL && redir_lval->ll_name != NULL)
1154 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1155 clear_lval(redir_lval);
1158 /* free the collected output */
1159 vim_free(redir_ga.ga_data);
1160 redir_ga.ga_data = NULL;
1162 vim_free(redir_lval);
1165 vim_free(redir_varname);
1166 redir_varname = NULL;
1169 # if defined(FEAT_MBYTE) || defined(PROTO)
1171 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1179 set_vim_var_string(VV_CC_FROM, enc_from, -1);
1180 set_vim_var_string(VV_CC_TO, enc_to, -1);
1181 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1182 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1183 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1185 set_vim_var_string(VV_CC_FROM, NULL, -1);
1186 set_vim_var_string(VV_CC_TO, NULL, -1);
1187 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1188 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1196 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1198 eval_printexpr(fname, args)
1204 set_vim_var_string(VV_FNAME_IN, fname, -1);
1205 set_vim_var_string(VV_CMDARG, args, -1);
1206 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1208 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1209 set_vim_var_string(VV_CMDARG, NULL, -1);
1220 # if defined(FEAT_DIFF) || defined(PROTO)
1222 eval_diff(origfile, newfile, outfile)
1229 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1230 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1231 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1232 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1233 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1234 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1235 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1239 eval_patch(origfile, difffile, outfile)
1246 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1247 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1248 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1249 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1250 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1251 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1252 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1257 * Top level evaluation function, returning a boolean.
1258 * Sets "error" to TRUE if there was an error.
1259 * Return TRUE or FALSE.
1262 eval_to_bool(arg, error, nextcmd, skip)
1266 int skip; /* only parse, don't execute */
1273 if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1280 retval = (get_tv_number_chk(&tv, error) != 0);
1291 * Top level evaluation function, returning a string. If "skip" is TRUE,
1292 * only parsing to "nextcmd" is done, without reporting errors. Return
1293 * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1296 eval_to_string_skip(arg, nextcmd, skip)
1299 int skip; /* only parse, don't execute */
1306 if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1310 retval = vim_strsave(get_tv_string(&tv));
1320 * Skip over an expression at "*pp".
1321 * Return FAIL for an error, OK otherwise.
1329 *pp = skipwhite(*pp);
1330 return eval1(pp, &rettv, FALSE);
1334 * Top level evaluation function, returning a string.
1335 * When "convert" is TRUE convert a List into a sequence of lines and convert
1336 * a Float to a String.
1337 * Return pointer to allocated memory, or NULL for failure.
1340 eval_to_string(arg, nextcmd, convert)
1349 char_u numbuf[NUMBUFLEN];
1352 if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1356 if (convert && tv.v_type == VAR_LIST)
1358 ga_init2(&ga, (int)sizeof(char), 80);
1359 if (tv.vval.v_list != NULL)
1361 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1362 if (tv.vval.v_list->lv_len > 0)
1365 ga_append(&ga, NUL);
1366 retval = (char_u *)ga.ga_data;
1369 else if (convert && tv.v_type == VAR_FLOAT)
1371 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv.vval.v_float);
1372 retval = vim_strsave(numbuf);
1376 retval = vim_strsave(get_tv_string(&tv));
1384 * Call eval_to_string() without using current local variables and using
1385 * textlock. When "use_sandbox" is TRUE use the sandbox.
1388 eval_to_string_safe(arg, nextcmd, use_sandbox)
1394 void *save_funccalp;
1396 save_funccalp = save_funccal();
1400 retval = eval_to_string(arg, nextcmd, FALSE);
1404 restore_funccal(save_funccalp);
1409 * Top level evaluation function, returning a number.
1410 * Evaluates "expr" silently.
1411 * Returns -1 for an error.
1414 eval_to_number(expr)
1419 char_u *p = skipwhite(expr);
1423 if (eval1(&p, &rettv, TRUE) == FAIL)
1427 retval = get_tv_number_chk(&rettv, NULL);
1436 * Prepare v: variable "idx" to be used.
1437 * Save the current typeval in "save_tv".
1438 * When not used yet add the variable to the v: hashtable.
1441 prepare_vimvar(idx, save_tv)
1445 *save_tv = vimvars[idx].vv_tv;
1446 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1447 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1451 * Restore v: variable "idx" to typeval "save_tv".
1452 * When no longer defined, remove the variable from the v: hashtable.
1455 restore_vimvar(idx, save_tv)
1461 vimvars[idx].vv_tv = *save_tv;
1462 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1464 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1465 if (HASHITEM_EMPTY(hi))
1466 EMSG2(_(e_intern2), "restore_vimvar()");
1468 hash_remove(&vimvarht, hi);
1472 #if defined(FEAT_SPELL) || defined(PROTO)
1474 * Evaluate an expression to a list with suggestions.
1475 * For the "expr:" part of 'spellsuggest'.
1476 * Returns NULL when there is an error.
1479 eval_spell_expr(badword, expr)
1485 list_T *list = NULL;
1486 char_u *p = skipwhite(expr);
1488 /* Set "v:val" to the bad word. */
1489 prepare_vimvar(VV_VAL, &save_val);
1490 vimvars[VV_VAL].vv_type = VAR_STRING;
1491 vimvars[VV_VAL].vv_str = badword;
1495 if (eval1(&p, &rettv, TRUE) == OK)
1497 if (rettv.v_type != VAR_LIST)
1500 list = rettv.vval.v_list;
1505 restore_vimvar(VV_VAL, &save_val);
1511 * "list" is supposed to contain two items: a word and a number. Return the
1512 * word in "pp" and the number as the return value.
1513 * Return -1 if anything isn't right.
1514 * Used to get the good word and score from the eval_spell_expr() result.
1517 get_spellword(list, pp)
1523 li = list->lv_first;
1526 *pp = get_tv_string(&li->li_tv);
1531 return get_tv_number(&li->li_tv);
1536 * Top level evaluation function.
1537 * Returns an allocated typval_T with the result.
1538 * Returns NULL when there is an error.
1541 eval_expr(arg, nextcmd)
1547 tv = (typval_T *)alloc(sizeof(typval_T));
1548 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1558 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1559 || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1561 * Call some vimL function and return the result in "*rettv".
1562 * Uses argv[argc] for the function arguments. Only Number and String
1563 * arguments are currently supported.
1564 * Returns OK or FAIL.
1567 call_vim_function(func, argc, argv, safe, rettv)
1571 int safe; /* use the sandbox */
1579 void *save_funccalp = NULL;
1582 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1583 if (argvars == NULL)
1586 for (i = 0; i < argc; i++)
1588 /* Pass a NULL or empty argument as an empty string */
1589 if (argv[i] == NULL || *argv[i] == NUL)
1591 argvars[i].v_type = VAR_STRING;
1592 argvars[i].vval.v_string = (char_u *)"";
1596 /* Recognize a number argument, the others must be strings. */
1597 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1598 if (len != 0 && len == (int)STRLEN(argv[i]))
1600 argvars[i].v_type = VAR_NUMBER;
1601 argvars[i].vval.v_number = n;
1605 argvars[i].v_type = VAR_STRING;
1606 argvars[i].vval.v_string = argv[i];
1612 save_funccalp = save_funccal();
1616 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1617 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1618 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1619 &doesrange, TRUE, NULL);
1623 restore_funccal(save_funccalp);
1633 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1635 * Call vimL function "func" and return the result as a string.
1636 * Returns NULL when calling the function fails.
1637 * Uses argv[argc] for the function arguments.
1640 call_func_retstr(func, argc, argv, safe)
1644 int safe; /* use the sandbox */
1649 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1652 retval = vim_strsave(get_tv_string(&rettv));
1658 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1660 * Call vimL function "func" and return the result as a number.
1661 * Returns -1 when calling the function fails.
1662 * Uses argv[argc] for the function arguments.
1665 call_func_retnr(func, argc, argv, safe)
1669 int safe; /* use the sandbox */
1674 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1677 retval = get_tv_number_chk(&rettv, NULL);
1684 * Call vimL function "func" and return the result as a List.
1685 * Uses argv[argc] for the function arguments.
1686 * Returns NULL when there is something wrong.
1689 call_func_retlist(func, argc, argv, safe)
1693 int safe; /* use the sandbox */
1697 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1700 if (rettv.v_type != VAR_LIST)
1706 return rettv.vval.v_list;
1712 * Save the current function call pointer, and set it to NULL.
1713 * Used when executing autocommands and for ":source".
1718 funccall_T *fc = current_funccal;
1720 current_funccal = NULL;
1725 restore_funccal(vfc)
1728 funccall_T *fc = (funccall_T *)vfc;
1730 current_funccal = fc;
1733 #if defined(FEAT_PROFILE) || defined(PROTO)
1735 * Prepare profiling for entering a child or something else that is not
1736 * counted for the script/function itself.
1737 * Should always be called in pair with prof_child_exit().
1740 prof_child_enter(tm)
1741 proftime_T *tm; /* place to store waittime */
1743 funccall_T *fc = current_funccal;
1745 if (fc != NULL && fc->func->uf_profiling)
1746 profile_start(&fc->prof_child);
1747 script_prof_save(tm);
1751 * Take care of time spent in a child.
1752 * Should always be called after prof_child_enter().
1756 proftime_T *tm; /* where waittime was stored */
1758 funccall_T *fc = current_funccal;
1760 if (fc != NULL && fc->func->uf_profiling)
1762 profile_end(&fc->prof_child);
1763 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1764 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1765 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1767 script_prof_restore(tm);
1774 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1775 * it in "*cp". Doesn't give error messages.
1778 eval_foldexpr(arg, cp)
1785 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1793 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1797 /* If the result is a number, just return the number. */
1798 if (tv.v_type == VAR_NUMBER)
1799 retval = tv.vval.v_number;
1800 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1804 /* If the result is a string, check if there is a non-digit before
1806 s = tv.vval.v_string;
1807 if (!VIM_ISDIGIT(*s) && *s != '-')
1809 retval = atol((char *)s);
1823 * ":let" list all variable values
1824 * ":let var1 var2" list variable values
1825 * ":let var = expr" assignment command.
1826 * ":let var += expr" assignment command.
1827 * ":let var -= expr" assignment command.
1828 * ":let var .= expr" assignment command.
1829 * ":let [var1, var2] = expr" unpack list.
1835 char_u *arg = eap->arg;
1836 char_u *expr = NULL;
1845 argend = skip_var_list(arg, &var_count, &semicolon);
1848 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1850 expr = vim_strchr(argend, '=');
1854 * ":let" without "=": list variables
1858 else if (!ends_excmd(*arg))
1859 /* ":let var1 var2" */
1860 arg = list_arg_vars(eap, arg, &first);
1861 else if (!eap->skip)
1864 list_glob_vars(&first);
1865 list_buf_vars(&first);
1866 list_win_vars(&first);
1868 list_tab_vars(&first);
1870 list_script_vars(&first);
1871 list_func_vars(&first);
1872 list_vim_vars(&first);
1874 eap->nextcmd = check_nextcmd(arg);
1882 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1883 op[0] = expr[-1]; /* +=, -= or .= */
1885 expr = skipwhite(expr + 1);
1889 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1898 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1906 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1907 * Handles both "var" with any type and "[var, var; var]" with a list type.
1908 * When "nextchars" is not NULL it points to a string with characters that
1909 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1911 * Returns OK or FAIL;
1914 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1917 int copy; /* copy values from "tv", don't move */
1918 int semicolon; /* from skip_var_list() */
1919 int var_count; /* from skip_var_list() */
1922 char_u *arg = arg_start;
1931 * ":let var = expr" or ":for var in list"
1933 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1939 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1941 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1948 if (semicolon == 0 && var_count < i)
1950 EMSG(_("E687: Less targets than List items"));
1953 if (var_count - semicolon > i)
1955 EMSG(_("E688: More targets than List items"));
1962 arg = skipwhite(arg + 1);
1963 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1964 item = item->li_next;
1968 arg = skipwhite(arg);
1971 /* Put the rest of the list (may be empty) in the var after ';'.
1972 * Create a new list for this. */
1976 while (item != NULL)
1978 list_append_tv(l, &item->li_tv);
1979 item = item->li_next;
1982 ltv.v_type = VAR_LIST;
1984 ltv.vval.v_list = l;
1987 arg = ex_let_one(skipwhite(arg + 1), <v, FALSE,
1988 (char_u *)"]", nextchars);
1994 else if (*arg != ',' && *arg != ']')
1996 EMSG2(_(e_intern2), "ex_let_vars()");
2005 * Skip over assignable variable "var" or list of variables "[var, var]".
2006 * Used for ":let varvar = expr" and ":for varvar in expr".
2007 * For "[var, var]" increment "*var_count" for each variable.
2008 * for "[var, var; var]" set "semicolon".
2009 * Return NULL for an error.
2012 skip_var_list(arg, var_count, semicolon)
2021 /* "[var, var]": find the matching ']'. */
2025 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
2026 s = skip_var_one(p);
2029 EMSG2(_(e_invarg2), p);
2039 if (*semicolon == 1)
2041 EMSG(_("Double ; in list of variables"));
2048 EMSG2(_(e_invarg2), p);
2055 return skip_var_one(arg);
2059 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
2066 if (*arg == '@' && arg[1] != NUL)
2068 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
2069 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2073 * List variables for hashtab "ht" with prefix "prefix".
2074 * If "empty" is TRUE also list NULL strings as empty strings.
2077 list_hashtable_vars(ht, prefix, empty, first)
2087 todo = (int)ht->ht_used;
2088 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
2090 if (!HASHITEM_EMPTY(hi))
2094 if (empty || di->di_tv.v_type != VAR_STRING
2095 || di->di_tv.vval.v_string != NULL)
2096 list_one_var(di, prefix, first);
2102 * List global variables.
2105 list_glob_vars(first)
2108 list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
2112 * List buffer variables.
2115 list_buf_vars(first)
2118 char_u numbuf[NUMBUFLEN];
2120 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:",
2123 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
2124 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
2129 * List window variables.
2132 list_win_vars(first)
2135 list_hashtable_vars(&curwin->w_vars.dv_hashtab,
2136 (char_u *)"w:", TRUE, first);
2141 * List tab page variables.
2144 list_tab_vars(first)
2147 list_hashtable_vars(&curtab->tp_vars.dv_hashtab,
2148 (char_u *)"t:", TRUE, first);
2153 * List Vim variables.
2156 list_vim_vars(first)
2159 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2163 * List script-local variables, if there is a script.
2166 list_script_vars(first)
2169 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2170 list_hashtable_vars(&SCRIPT_VARS(current_SID),
2171 (char_u *)"s:", FALSE, first);
2175 * List function variables, if there is a function.
2178 list_func_vars(first)
2181 if (current_funccal != NULL)
2182 list_hashtable_vars(¤t_funccal->l_vars.dv_hashtab,
2183 (char_u *)"l:", FALSE, first);
2187 * List variables in "arg".
2190 list_arg_vars(eap, arg, first)
2203 while (!ends_excmd(*arg) && !got_int)
2205 if (error || eap->skip)
2207 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2208 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2211 EMSG(_(e_trailing));
2217 /* get_name_len() takes care of expanding curly braces */
2218 name_start = name = arg;
2219 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2222 /* This is mainly to keep test 49 working: when expanding
2223 * curly braces fails overrule the exception error message. */
2224 if (len < 0 && !aborting())
2227 EMSG2(_(e_invarg2), arg);
2236 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2240 /* handle d.key, l[idx], f(expr) */
2242 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2246 if (arg == arg_subsc && len == 2 && name[1] == ':')
2250 case 'g': list_glob_vars(first); break;
2251 case 'b': list_buf_vars(first); break;
2252 case 'w': list_win_vars(first); break;
2254 case 't': list_tab_vars(first); break;
2256 case 'v': list_vim_vars(first); break;
2257 case 's': list_script_vars(first); break;
2258 case 'l': list_func_vars(first); break;
2260 EMSG2(_("E738: Can't list variables for %s"), name);
2265 char_u numbuf[NUMBUFLEN];
2270 s = echo_string(&tv, &tf, numbuf, 0);
2273 list_one_var_a((char_u *)"",
2274 arg == arg_subsc ? name : name_start,
2276 s == NULL ? (char_u *)"" : s,
2289 arg = skipwhite(arg);
2296 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2297 * Returns a pointer to the char just after the var name.
2298 * Returns NULL if there is an error.
2301 ex_let_one(arg, tv, copy, endchars, op)
2302 char_u *arg; /* points to variable name */
2303 typval_T *tv; /* value to assign to variable */
2304 int copy; /* copy value from "tv" */
2305 char_u *endchars; /* valid chars after variable name or NULL */
2306 char_u *op; /* "+", "-", "." or NULL*/
2311 char_u *arg_end = NULL;
2314 char_u *tofree = NULL;
2317 * ":let $VAR = expr": Set environment variable.
2321 /* Find the end of the name. */
2324 len = get_env_len(&arg);
2326 EMSG2(_(e_invarg2), name - 1);
2329 if (op != NULL && (*op == '+' || *op == '-'))
2330 EMSG2(_(e_letwrong), op);
2331 else if (endchars != NULL
2332 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2333 EMSG(_(e_letunexp));
2334 else if (!check_secure())
2338 p = get_tv_string_chk(tv);
2339 if (p != NULL && op != NULL && *op == '.')
2341 int mustfree = FALSE;
2342 char_u *s = vim_getenv(name, &mustfree);
2346 p = tofree = concat_str(s, p);
2353 vim_setenv(name, p);
2354 if (STRICMP(name, "HOME") == 0)
2356 else if (didset_vim && STRICMP(name, "VIM") == 0)
2358 else if (didset_vimruntime
2359 && STRICMP(name, "VIMRUNTIME") == 0)
2360 didset_vimruntime = FALSE;
2370 * ":let &option = expr": Set option value.
2371 * ":let &l:option = expr": Set local option value.
2372 * ":let &g:option = expr": Set global option value.
2374 else if (*arg == '&')
2376 /* Find the end of the name. */
2377 p = find_option_end(&arg, &opt_flags);
2378 if (p == NULL || (endchars != NULL
2379 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2380 EMSG(_(e_letunexp));
2386 char_u *stringval = NULL;
2392 n = get_tv_number(tv);
2393 s = get_tv_string_chk(tv); /* != NULL if number or string */
2394 if (s != NULL && op != NULL && *op != '=')
2396 opt_type = get_option_value(arg, &numval,
2397 &stringval, opt_flags);
2398 if ((opt_type == 1 && *op == '.')
2399 || (opt_type == 0 && *op != '.'))
2400 EMSG2(_(e_letwrong), op);
2403 if (opt_type == 1) /* number */
2410 else if (opt_type == 0 && stringval != NULL) /* string */
2412 s = concat_str(stringval, s);
2413 vim_free(stringval);
2420 set_option_value(arg, n, s, opt_flags);
2424 vim_free(stringval);
2429 * ":let @r = expr": Set register contents.
2431 else if (*arg == '@')
2434 if (op != NULL && (*op == '+' || *op == '-'))
2435 EMSG2(_(e_letwrong), op);
2436 else if (endchars != NULL
2437 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2438 EMSG(_(e_letunexp));
2441 char_u *ptofree = NULL;
2444 p = get_tv_string_chk(tv);
2445 if (p != NULL && op != NULL && *op == '.')
2447 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2450 p = ptofree = concat_str(s, p);
2456 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2464 * ":let var = expr": Set internal variable.
2465 * ":let {expr} = expr": Idem, name made with curly braces
2467 else if (eval_isnamec1(*arg) || *arg == '{')
2471 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2472 if (p != NULL && lv.ll_name != NULL)
2474 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2475 EMSG(_(e_letunexp));
2478 set_var_lval(&lv, p, tv, copy, op);
2486 EMSG2(_(e_invarg2), arg);
2492 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2495 check_changedtick(arg)
2498 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2500 EMSG2(_(e_readonlyvar), arg);
2507 * Get an lval: variable, Dict item or List item that can be assigned a value
2508 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2509 * "name.key", "name.key[expr]" etc.
2510 * Indexing only works if "name" is an existing List or Dictionary.
2511 * "name" points to the start of the name.
2512 * If "rettv" is not NULL it points to the value to be assigned.
2513 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2514 * wrong; must end in space or cmd separator.
2516 * Returns a pointer to just after the name, including indexes.
2517 * When an evaluation error occurs "lp->ll_name" is NULL;
2518 * Returns NULL for a parsing error. Still need to free items in "lp"!
2521 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2527 int quiet; /* don't give error messages */
2528 int fne_flags; /* flags for find_name_end() */
2531 char_u *expr_start, *expr_end;
2542 /* Clear everything in "lp". */
2543 vim_memset(lp, 0, sizeof(lval_T));
2547 /* When skipping just find the end of the name. */
2549 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2552 /* Find the end of the name. */
2553 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2554 if (expr_start != NULL)
2556 /* Don't expand the name when we already know there is an error. */
2557 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2558 && *p != '[' && *p != '.')
2560 EMSG(_(e_trailing));
2564 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2565 if (lp->ll_exp_name == NULL)
2567 /* Report an invalid expression in braces, unless the
2568 * expression evaluation has been cancelled due to an
2569 * aborting error, an interrupt, or an exception. */
2570 if (!aborting() && !quiet)
2573 EMSG2(_(e_invarg2), name);
2577 lp->ll_name = lp->ll_exp_name;
2582 /* Without [idx] or .key we are done. */
2583 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2588 v = find_var(lp->ll_name, &ht);
2589 if (v == NULL && !quiet)
2590 EMSG2(_(e_undefvar), lp->ll_name);
2596 * Loop until no more [idx] or .key is following.
2598 lp->ll_tv = &v->di_tv;
2599 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2601 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2602 && !(lp->ll_tv->v_type == VAR_DICT
2603 && lp->ll_tv->vval.v_dict != NULL))
2606 EMSG(_("E689: Can only index a List or Dictionary"));
2612 EMSG(_("E708: [:] must come last"));
2620 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2625 EMSG(_(e_emptykey));
2632 /* Get the index [expr] or the first index [expr: ]. */
2633 p = skipwhite(p + 1);
2639 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2641 if (get_tv_string_chk(&var1) == NULL)
2643 /* not a number or string */
2649 /* Optionally get the second index [ :expr]. */
2652 if (lp->ll_tv->v_type == VAR_DICT)
2655 EMSG(_(e_dictrange));
2660 if (rettv != NULL && (rettv->v_type != VAR_LIST
2661 || rettv->vval.v_list == NULL))
2664 EMSG(_("E709: [:] requires a List value"));
2669 p = skipwhite(p + 1);
2671 lp->ll_empty2 = TRUE;
2674 lp->ll_empty2 = FALSE;
2675 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2681 if (get_tv_string_chk(&var2) == NULL)
2683 /* not a number or string */
2690 lp->ll_range = TRUE;
2693 lp->ll_range = FALSE;
2698 EMSG(_(e_missbrac));
2701 if (lp->ll_range && !lp->ll_empty2)
2706 /* Skip to past ']'. */
2710 if (lp->ll_tv->v_type == VAR_DICT)
2714 /* "[key]": get key from "var1" */
2715 key = get_tv_string(&var1); /* is number or string */
2719 EMSG(_(e_emptykey));
2725 lp->ll_dict = lp->ll_tv->vval.v_dict;
2726 lp->ll_di = dict_find(lp->ll_dict, key, len);
2728 /* When assigning to g: check that a function and variable name is
2730 if (rettv != NULL && lp->ll_dict == &globvardict)
2732 if (rettv->v_type == VAR_FUNC
2733 && var_check_func_name(key, lp->ll_di == NULL))
2735 if (!valid_varname(key))
2739 if (lp->ll_di == NULL)
2741 /* Can't add "v:" variable. */
2742 if (lp->ll_dict == &vimvardict)
2744 EMSG2(_(e_illvar), name);
2748 /* Key does not exist in dict: may need to add it. */
2749 if (*p == '[' || *p == '.' || unlet)
2752 EMSG2(_(e_dictkey), key);
2758 lp->ll_newkey = vim_strsave(key);
2760 lp->ll_newkey = vim_strnsave(key, len);
2763 if (lp->ll_newkey == NULL)
2767 /* existing variable, need to check if it can be changed */
2768 else if (var_check_ro(lp->ll_di->di_flags, name))
2773 lp->ll_tv = &lp->ll_di->di_tv;
2778 * Get the number and item for the only or first index of the List.
2784 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2788 lp->ll_list = lp->ll_tv->vval.v_list;
2789 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2790 if (lp->ll_li == NULL)
2795 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2798 if (lp->ll_li == NULL)
2800 if (lp->ll_range && !lp->ll_empty2)
2803 EMSGN(_(e_listidx), lp->ll_n1);
2808 * May need to find the item or absolute index for the second
2810 * When no index given: "lp->ll_empty2" is TRUE.
2811 * Otherwise "lp->ll_n2" is set to the second index.
2813 if (lp->ll_range && !lp->ll_empty2)
2815 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2819 ni = list_find(lp->ll_list, lp->ll_n2);
2823 EMSGN(_(e_listidx), lp->ll_n2);
2826 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2829 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2831 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2832 if (lp->ll_n2 < lp->ll_n1)
2835 EMSGN(_(e_listidx), lp->ll_n2);
2840 lp->ll_tv = &lp->ll_li->li_tv;
2848 * Clear lval "lp" that was filled by get_lval().
2854 vim_free(lp->ll_exp_name);
2855 vim_free(lp->ll_newkey);
2859 * Set a variable that was parsed by get_lval() to "rettv".
2860 * "endp" points to just after the parsed name.
2861 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2864 set_var_lval(lp, endp, rettv, copy, op)
2875 if (lp->ll_tv == NULL)
2877 if (!check_changedtick(lp->ll_name))
2881 if (op != NULL && *op != '=')
2885 /* handle +=, -= and .= */
2886 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2889 if (tv_op(&tv, rettv, op) == OK)
2890 set_var(lp->ll_name, &tv, FALSE);
2895 set_var(lp->ll_name, rettv, copy);
2899 else if (tv_check_lock(lp->ll_newkey == NULL
2901 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2903 else if (lp->ll_range)
2906 * Assign the List values to the list items.
2908 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2910 if (op != NULL && *op != '=')
2911 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2914 clear_tv(&lp->ll_li->li_tv);
2915 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2918 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2920 if (lp->ll_li->li_next == NULL)
2922 /* Need to add an empty item. */
2923 if (list_append_number(lp->ll_list, 0) == FAIL)
2929 lp->ll_li = lp->ll_li->li_next;
2933 EMSG(_("E710: List value has more items than target"));
2934 else if (lp->ll_empty2
2935 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2936 : lp->ll_n1 != lp->ll_n2)
2937 EMSG(_("E711: List value has not enough items"));
2942 * Assign to a List or Dictionary item.
2944 if (lp->ll_newkey != NULL)
2946 if (op != NULL && *op != '=')
2948 EMSG2(_(e_letwrong), op);
2952 /* Need to add an item to the Dictionary. */
2953 di = dictitem_alloc(lp->ll_newkey);
2956 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2961 lp->ll_tv = &di->di_tv;
2963 else if (op != NULL && *op != '=')
2965 tv_op(lp->ll_tv, rettv, op);
2969 clear_tv(lp->ll_tv);
2972 * Assign the value to the variable or list item.
2975 copy_tv(rettv, lp->ll_tv);
2978 *lp->ll_tv = *rettv;
2979 lp->ll_tv->v_lock = 0;
2986 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2987 * Returns OK or FAIL.
2996 char_u numbuf[NUMBUFLEN];
2999 /* Can't do anything with a Funcref or a Dict on the right. */
3000 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
3002 switch (tv1->v_type)
3009 if (*op != '+' || tv2->v_type != VAR_LIST)
3012 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
3013 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
3018 if (tv2->v_type == VAR_LIST)
3020 if (*op == '+' || *op == '-')
3022 /* nr += nr or nr -= nr*/
3023 n = get_tv_number(tv1);
3025 if (tv2->v_type == VAR_FLOAT)
3030 f += tv2->vval.v_float;
3032 f -= tv2->vval.v_float;
3034 tv1->v_type = VAR_FLOAT;
3035 tv1->vval.v_float = f;
3041 n += get_tv_number(tv2);
3043 n -= get_tv_number(tv2);
3045 tv1->v_type = VAR_NUMBER;
3046 tv1->vval.v_number = n;
3051 if (tv2->v_type == VAR_FLOAT)
3055 s = get_tv_string(tv1);
3056 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
3058 tv1->v_type = VAR_STRING;
3059 tv1->vval.v_string = s;
3068 if (*op == '.' || (tv2->v_type != VAR_FLOAT
3069 && tv2->v_type != VAR_NUMBER
3070 && tv2->v_type != VAR_STRING))
3072 if (tv2->v_type == VAR_FLOAT)
3073 f = tv2->vval.v_float;
3075 f = get_tv_number(tv2);
3077 tv1->vval.v_float += f;
3079 tv1->vval.v_float -= f;
3086 EMSG2(_(e_letwrong), op);
3091 * Add a watcher to a list.
3094 list_add_watch(l, lw)
3098 lw->lw_next = l->lv_watch;
3103 * Remove a watcher from a list.
3104 * No warning when it isn't found...
3107 list_rem_watch(l, lwrem)
3111 listwatch_T *lw, **lwp;
3114 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3126 * Just before removing an item from a list: advance watchers to the next
3130 list_fix_watch(l, item)
3136 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3137 if (lw->lw_item == item)
3138 lw->lw_item = item->li_next;
3142 * Evaluate the expression used in a ":for var in expr" command.
3143 * "arg" points to "var".
3144 * Set "*errp" to TRUE for an error, FALSE otherwise;
3145 * Return a pointer that holds the info. Null when there is an error.
3148 eval_for_line(arg, errp, nextcmdp, skip)
3159 *errp = TRUE; /* default: there is an error */
3161 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
3165 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
3169 expr = skipwhite(expr);
3170 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
3172 EMSG(_("E690: Missing \"in\" after :for"));
3178 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
3184 if (tv.v_type != VAR_LIST || l == NULL)
3191 /* No need to increment the refcount, it's already set for the
3192 * list being used in "tv". */
3194 list_add_watch(l, &fi->fi_lw);
3195 fi->fi_lw.lw_item = l->lv_first;
3206 * Use the first item in a ":for" list. Advance to the next.
3207 * Assign the values to the variable (list). "arg" points to the first one.
3208 * Return TRUE when a valid item was found, FALSE when at end of list or
3212 next_for_item(fi_void, arg)
3216 forinfo_T *fi = (forinfo_T *)fi_void;
3220 item = fi->fi_lw.lw_item;
3225 fi->fi_lw.lw_item = item->li_next;
3226 result = (ex_let_vars(arg, &item->li_tv, TRUE,
3227 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3233 * Free the structure used to store info used by ":for".
3236 free_for_info(fi_void)
3239 forinfo_T *fi = (forinfo_T *)fi_void;
3241 if (fi != NULL && fi->fi_list != NULL)
3243 list_rem_watch(fi->fi_list, &fi->fi_lw);
3244 list_unref(fi->fi_list);
3249 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3252 set_context_for_expression(xp, arg, cmdidx)
3261 if (cmdidx == CMD_let)
3263 xp->xp_context = EXPAND_USER_VARS;
3264 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3266 /* ":let var1 var2 ...": find last space. */
3267 for (p = arg + STRLEN(arg); p >= arg; )
3270 mb_ptr_back(arg, p);
3271 if (vim_iswhite(*p))
3278 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3279 : EXPAND_EXPRESSION;
3280 while ((xp->xp_pattern = vim_strpbrk(arg,
3281 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3283 c = *xp->xp_pattern;
3286 c = xp->xp_pattern[1];
3290 xp->xp_context = cmdidx != CMD_let || got_eq
3291 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3295 xp->xp_context = EXPAND_SETTINGS;
3296 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3297 xp->xp_pattern += 2;
3303 /* environment variable */
3304 xp->xp_context = EXPAND_ENV_VARS;
3309 xp->xp_context = EXPAND_EXPRESSION;
3312 && xp->xp_context == EXPAND_FUNCTIONS
3313 && vim_strchr(xp->xp_pattern, '(') == NULL)
3315 /* Function name can start with "<SNR>" */
3318 else if (cmdidx != CMD_let || got_eq)
3320 if (c == '"') /* string */
3322 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3323 if (c == '\\' && xp->xp_pattern[1] != NUL)
3325 xp->xp_context = EXPAND_NOTHING;
3327 else if (c == '\'') /* literal string */
3329 /* Trick: '' is like stopping and starting a literal string. */
3330 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3332 xp->xp_context = EXPAND_NOTHING;
3336 if (xp->xp_pattern[1] == '|')
3339 xp->xp_context = EXPAND_EXPRESSION;
3342 xp->xp_context = EXPAND_COMMANDS;
3345 xp->xp_context = EXPAND_EXPRESSION;
3348 /* Doesn't look like something valid, expand as an expression
3350 xp->xp_context = EXPAND_EXPRESSION;
3351 arg = xp->xp_pattern;
3353 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3356 xp->xp_pattern = arg;
3359 #endif /* FEAT_CMDL_COMPL */
3362 * ":1,25call func(arg1, arg2)" function call.
3368 char_u *arg = eap->arg;
3381 /* trans_function_name() doesn't work well when skipping, use eval0()
3382 * instead to skip to any following command, e.g. for:
3383 * :if 0 | call dict.foo().bar() | endif */
3385 if (eval0(eap->arg, &rettv, &eap->nextcmd, FALSE) != FAIL)
3391 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3392 if (fudi.fd_newkey != NULL)
3394 /* Still need to give an error message for missing key. */
3395 EMSG2(_(e_dictkey), fudi.fd_newkey);
3396 vim_free(fudi.fd_newkey);
3401 /* Increase refcount on dictionary, it could get deleted when evaluating
3403 if (fudi.fd_dict != NULL)
3404 ++fudi.fd_dict->dv_refcount;
3406 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3407 len = (int)STRLEN(tofree);
3408 name = deref_func_name(tofree, &len);
3410 /* Skip white space to allow ":call func ()". Not good, but required for
3411 * backward compatibility. */
3412 startarg = skipwhite(arg);
3413 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3415 if (*startarg != '(')
3417 EMSG2(_("E107: Missing parentheses: %s"), eap->arg);
3422 * When skipping, evaluate the function once, to find the end of the
3424 * When the function takes a range, this is discovered after the first
3425 * call, and the loop is broken.
3430 lnum = eap->line2; /* do it once, also with an invalid range */
3434 for ( ; lnum <= eap->line2; ++lnum)
3436 if (!eap->skip && eap->addr_count > 0)
3438 curwin->w_cursor.lnum = lnum;
3439 curwin->w_cursor.col = 0;
3440 #ifdef FEAT_VIRTUALEDIT
3441 curwin->w_cursor.coladd = 0;
3445 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3446 eap->line1, eap->line2, &doesrange,
3447 !eap->skip, fudi.fd_dict) == FAIL)
3453 /* Handle a function returning a Funcref, Dictionary or List. */
3454 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3461 if (doesrange || eap->skip)
3464 /* Stop when immediately aborting on error, or when an interrupt
3465 * occurred or an exception was thrown but not caught.
3466 * get_func_tv() returned OK, so that the check for trailing
3467 * characters below is executed. */
3476 /* Check for trailing illegal characters and a following command. */
3477 if (!ends_excmd(*arg))
3480 EMSG(_(e_trailing));
3483 eap->nextcmd = check_nextcmd(arg);
3487 dict_unref(fudi.fd_dict);
3492 * ":unlet[!] var1 ... " command.
3498 ex_unletlock(eap, eap->arg, 0);
3502 * ":lockvar" and ":unlockvar" commands
3508 char_u *arg = eap->arg;
3513 else if (vim_isdigit(*arg))
3515 deep = getdigits(&arg);
3516 arg = skipwhite(arg);
3519 ex_unletlock(eap, arg, deep);
3523 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3526 ex_unletlock(eap, argstart, deep)
3531 char_u *arg = argstart;
3538 /* Parse the name and find the end. */
3539 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3541 if (lv.ll_name == NULL)
3542 error = TRUE; /* error but continue parsing */
3543 if (name_end == NULL || (!vim_iswhite(*name_end)
3544 && !ends_excmd(*name_end)))
3546 if (name_end != NULL)
3549 EMSG(_(e_trailing));
3551 if (!(eap->skip || error))
3556 if (!error && !eap->skip)
3558 if (eap->cmdidx == CMD_unlet)
3560 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3565 if (do_lock_var(&lv, name_end, deep,
3566 eap->cmdidx == CMD_lockvar) == FAIL)
3574 arg = skipwhite(name_end);
3575 } while (!ends_excmd(*arg));
3577 eap->nextcmd = check_nextcmd(arg);
3581 do_unlet_var(lp, name_end, forceit)
3589 if (lp->ll_tv == NULL)
3594 /* Normal name or expanded name. */
3595 if (check_changedtick(lp->ll_name))
3597 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3601 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3603 else if (lp->ll_range)
3607 /* Delete a range of List items. */
3608 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3610 li = lp->ll_li->li_next;
3611 listitem_remove(lp->ll_list, lp->ll_li);
3618 if (lp->ll_list != NULL)
3619 /* unlet a List item. */
3620 listitem_remove(lp->ll_list, lp->ll_li);
3622 /* unlet a Dictionary item. */
3623 dictitem_remove(lp->ll_dict, lp->ll_di);
3630 * "unlet" a variable. Return OK if it existed, FAIL if not.
3631 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3634 do_unlet(name, forceit)
3643 ht = find_var_ht(name, &varname);
3644 if (ht != NULL && *varname != NUL)
3646 hi = hash_find(ht, varname);
3647 if (!HASHITEM_EMPTY(hi))
3650 if (var_check_fixed(di->di_flags, name)
3651 || var_check_ro(di->di_flags, name))
3659 EMSG2(_("E108: No such variable: \"%s\""), name);
3664 * Lock or unlock variable indicated by "lp".
3665 * "deep" is the levels to go (-1 for unlimited);
3666 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3669 do_lock_var(lp, name_end, deep, lock)
3679 if (deep == 0) /* nothing to do */
3682 if (lp->ll_tv == NULL)
3687 /* Normal name or expanded name. */
3688 if (check_changedtick(lp->ll_name))
3692 di = find_var(lp->ll_name, NULL);
3698 di->di_flags |= DI_FLAGS_LOCK;
3700 di->di_flags &= ~DI_FLAGS_LOCK;
3701 item_lock(&di->di_tv, deep, lock);
3706 else if (lp->ll_range)
3708 listitem_T *li = lp->ll_li;
3710 /* (un)lock a range of List items. */
3711 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3713 item_lock(&li->li_tv, deep, lock);
3718 else if (lp->ll_list != NULL)
3719 /* (un)lock a List item. */
3720 item_lock(&lp->ll_li->li_tv, deep, lock);
3722 /* un(lock) a Dictionary item. */
3723 item_lock(&lp->ll_di->di_tv, deep, lock);
3729 * Lock or unlock an item. "deep" is nr of levels to go.
3732 item_lock(tv, deep, lock)
3737 static int recurse = 0;
3744 if (recurse >= DICT_MAXNEST)
3746 EMSG(_("E743: variable nested too deep for (un)lock"));
3753 /* lock/unlock the item itself */
3755 tv->v_lock |= VAR_LOCKED;
3757 tv->v_lock &= ~VAR_LOCKED;
3762 if ((l = tv->vval.v_list) != NULL)
3765 l->lv_lock |= VAR_LOCKED;
3767 l->lv_lock &= ~VAR_LOCKED;
3768 if (deep < 0 || deep > 1)
3769 /* recursive: lock/unlock the items the List contains */
3770 for (li = l->lv_first; li != NULL; li = li->li_next)
3771 item_lock(&li->li_tv, deep - 1, lock);
3775 if ((d = tv->vval.v_dict) != NULL)
3778 d->dv_lock |= VAR_LOCKED;
3780 d->dv_lock &= ~VAR_LOCKED;
3781 if (deep < 0 || deep > 1)
3783 /* recursive: lock/unlock the items the List contains */
3784 todo = (int)d->dv_hashtab.ht_used;
3785 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3787 if (!HASHITEM_EMPTY(hi))
3790 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3800 * Return TRUE if typeval "tv" is locked: Either that value is locked itself
3801 * or it refers to a List or Dictionary that is locked.
3807 return (tv->v_lock & VAR_LOCKED)
3808 || (tv->v_type == VAR_LIST
3809 && tv->vval.v_list != NULL
3810 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3811 || (tv->v_type == VAR_DICT
3812 && tv->vval.v_dict != NULL
3813 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3816 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3818 * Delete all "menutrans_" variables.
3821 del_menutrans_vars()
3826 hash_lock(&globvarht);
3827 todo = (int)globvarht.ht_used;
3828 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3830 if (!HASHITEM_EMPTY(hi))
3833 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3834 delete_var(&globvarht, hi);
3837 hash_unlock(&globvarht);
3841 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3844 * Local string buffer for the next two functions to store a variable name
3845 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3846 * get_user_var_name().
3849 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3851 static char_u *varnamebuf = NULL;
3852 static int varnamebuflen = 0;
3855 * Function to concatenate a prefix and a variable name.
3858 cat_prefix_varname(prefix, name)
3864 len = (int)STRLEN(name) + 3;
3865 if (len > varnamebuflen)
3867 vim_free(varnamebuf);
3868 len += 10; /* some additional space */
3869 varnamebuf = alloc(len);
3870 if (varnamebuf == NULL)
3875 varnamebuflen = len;
3877 *varnamebuf = prefix;
3878 varnamebuf[1] = ':';
3879 STRCPY(varnamebuf + 2, name);
3884 * Function given to ExpandGeneric() to obtain the list of user defined
3885 * (global/buffer/window/built-in) variable names.
3888 get_user_var_name(xp, idx)
3892 static long_u gdone;
3893 static long_u bdone;
3894 static long_u wdone;
3896 static long_u tdone;
3899 static hashitem_T *hi;
3904 gdone = bdone = wdone = vidx = 0;
3910 /* Global variables */
3911 if (gdone < globvarht.ht_used)
3914 hi = globvarht.ht_array;
3917 while (HASHITEM_EMPTY(hi))
3919 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3920 return cat_prefix_varname('g', hi->hi_key);
3925 ht = &curbuf->b_vars.dv_hashtab;
3926 if (bdone < ht->ht_used)
3932 while (HASHITEM_EMPTY(hi))
3934 return cat_prefix_varname('b', hi->hi_key);
3936 if (bdone == ht->ht_used)
3939 return (char_u *)"b:changedtick";
3943 ht = &curwin->w_vars.dv_hashtab;
3944 if (wdone < ht->ht_used)
3950 while (HASHITEM_EMPTY(hi))
3952 return cat_prefix_varname('w', hi->hi_key);
3957 ht = &curtab->tp_vars.dv_hashtab;
3958 if (tdone < ht->ht_used)
3964 while (HASHITEM_EMPTY(hi))
3966 return cat_prefix_varname('t', hi->hi_key);
3972 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3974 vim_free(varnamebuf);
3980 #endif /* FEAT_CMDL_COMPL */
3983 * types for expressions.
3988 , TYPE_EQUAL /* == */
3989 , TYPE_NEQUAL /* != */
3990 , TYPE_GREATER /* > */
3991 , TYPE_GEQUAL /* >= */
3992 , TYPE_SMALLER /* < */
3993 , TYPE_SEQUAL /* <= */
3994 , TYPE_MATCH /* =~ */
3995 , TYPE_NOMATCH /* !~ */
3999 * The "evaluate" argument: When FALSE, the argument is only parsed but not
4000 * executed. The function may return OK, but the rettv will be of type
4001 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
4005 * Handle zero level expression.
4006 * This calls eval1() and handles error message and nextcmd.
4007 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
4008 * Note: "rettv.v_lock" is not set.
4009 * Return OK or FAIL.
4012 eval0(arg, rettv, nextcmd, evaluate)
4022 ret = eval1(&p, rettv, evaluate);
4023 if (ret == FAIL || !ends_excmd(*p))
4028 * Report the invalid expression unless the expression evaluation has
4029 * been cancelled due to an aborting error, an interrupt, or an
4033 EMSG2(_(e_invexpr2), arg);
4036 if (nextcmd != NULL)
4037 *nextcmd = check_nextcmd(p);
4043 * Handle top level expression:
4044 * expr2 ? expr1 : expr1
4046 * "arg" must point to the first non-white of the expression.
4047 * "arg" is advanced to the next non-white after the recognized expression.
4049 * Note: "rettv.v_lock" is not set.
4051 * Return OK or FAIL.
4054 eval1(arg, rettv, evaluate)
4063 * Get the first variable.
4065 if (eval2(arg, rettv, evaluate) == FAIL)
4068 if ((*arg)[0] == '?')
4075 if (get_tv_number_chk(rettv, &error) != 0)
4083 * Get the second variable.
4085 *arg = skipwhite(*arg + 1);
4086 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
4090 * Check for the ":".
4092 if ((*arg)[0] != ':')
4094 EMSG(_("E109: Missing ':' after '?'"));
4095 if (evaluate && result)
4101 * Get the third variable.
4103 *arg = skipwhite(*arg + 1);
4104 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
4106 if (evaluate && result)
4110 if (evaluate && !result)
4118 * Handle first level expression:
4119 * expr2 || expr2 || expr2 logical OR
4121 * "arg" must point to the first non-white of the expression.
4122 * "arg" is advanced to the next non-white after the recognized expression.
4124 * Return OK or FAIL.
4127 eval2(arg, rettv, evaluate)
4138 * Get the first variable.
4140 if (eval3(arg, rettv, evaluate) == FAIL)
4144 * Repeat until there is no following "||".
4148 while ((*arg)[0] == '|' && (*arg)[1] == '|')
4150 if (evaluate && first)
4152 if (get_tv_number_chk(rettv, &error) != 0)
4161 * Get the second variable.
4163 *arg = skipwhite(*arg + 2);
4164 if (eval3(arg, &var2, evaluate && !result) == FAIL)
4168 * Compute the result.
4170 if (evaluate && !result)
4172 if (get_tv_number_chk(&var2, &error) != 0)
4180 rettv->v_type = VAR_NUMBER;
4181 rettv->vval.v_number = result;
4189 * Handle second level expression:
4190 * expr3 && expr3 && expr3 logical AND
4192 * "arg" must point to the first non-white of the expression.
4193 * "arg" is advanced to the next non-white after the recognized expression.
4195 * Return OK or FAIL.
4198 eval3(arg, rettv, evaluate)
4209 * Get the first variable.
4211 if (eval4(arg, rettv, evaluate) == FAIL)
4215 * Repeat until there is no following "&&".
4219 while ((*arg)[0] == '&' && (*arg)[1] == '&')
4221 if (evaluate && first)
4223 if (get_tv_number_chk(rettv, &error) == 0)
4232 * Get the second variable.
4234 *arg = skipwhite(*arg + 2);
4235 if (eval4(arg, &var2, evaluate && result) == FAIL)
4239 * Compute the result.
4241 if (evaluate && result)
4243 if (get_tv_number_chk(&var2, &error) == 0)
4251 rettv->v_type = VAR_NUMBER;
4252 rettv->vval.v_number = result;
4260 * Handle third level expression:
4272 * "arg" must point to the first non-white of the expression.
4273 * "arg" is advanced to the next non-white after the recognized expression.
4275 * Return OK or FAIL.
4278 eval4(arg, rettv, evaluate)
4286 exptype_T type = TYPE_UNKNOWN;
4287 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4291 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4292 regmatch_T regmatch;
4297 * Get the first variable.
4299 if (eval5(arg, rettv, evaluate) == FAIL)
4305 case '=': if (p[1] == '=')
4307 else if (p[1] == '~')
4310 case '!': if (p[1] == '=')
4312 else if (p[1] == '~')
4313 type = TYPE_NOMATCH;
4315 case '>': if (p[1] != '=')
4317 type = TYPE_GREATER;
4323 case '<': if (p[1] != '=')
4325 type = TYPE_SMALLER;
4331 case 'i': if (p[1] == 's')
4333 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4335 if (!vim_isIDc(p[len]))
4337 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4345 * If there is a comparative operator, use it.
4347 if (type != TYPE_UNKNOWN)
4349 /* extra question mark appended: ignore case */
4355 /* extra '#' appended: match case */
4356 else if (p[len] == '#')
4361 /* nothing appended: use 'ignorecase' */
4366 * Get the second variable.
4368 *arg = skipwhite(p + len);
4369 if (eval5(arg, &var2, evaluate) == FAIL)
4377 if (type_is && rettv->v_type != var2.v_type)
4379 /* For "is" a different type always means FALSE, for "notis"
4381 n1 = (type == TYPE_NEQUAL);
4383 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4387 n1 = (rettv->v_type == var2.v_type
4388 && rettv->vval.v_list == var2.vval.v_list);
4389 if (type == TYPE_NEQUAL)
4392 else if (rettv->v_type != var2.v_type
4393 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4395 if (rettv->v_type != var2.v_type)
4396 EMSG(_("E691: Can only compare List with List"));
4398 EMSG(_("E692: Invalid operation for Lists"));
4405 /* Compare two Lists for being equal or unequal. */
4406 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list,
4408 if (type == TYPE_NEQUAL)
4413 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4417 n1 = (rettv->v_type == var2.v_type
4418 && rettv->vval.v_dict == var2.vval.v_dict);
4419 if (type == TYPE_NEQUAL)
4422 else if (rettv->v_type != var2.v_type
4423 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4425 if (rettv->v_type != var2.v_type)
4426 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4428 EMSG(_("E736: Invalid operation for Dictionary"));
4435 /* Compare two Dictionaries for being equal or unequal. */
4436 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict,
4438 if (type == TYPE_NEQUAL)
4443 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4445 if (rettv->v_type != var2.v_type
4446 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4448 if (rettv->v_type != var2.v_type)
4449 EMSG(_("E693: Can only compare Funcref with Funcref"));
4451 EMSG(_("E694: Invalid operation for Funcrefs"));
4458 /* Compare two Funcrefs for being equal or unequal. */
4459 if (rettv->vval.v_string == NULL
4460 || var2.vval.v_string == NULL)
4463 n1 = STRCMP(rettv->vval.v_string,
4464 var2.vval.v_string) == 0;
4465 if (type == TYPE_NEQUAL)
4472 * If one of the two variables is a float, compare as a float.
4473 * When using "=~" or "!~", always compare as string.
4475 else if ((rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4476 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4480 if (rettv->v_type == VAR_FLOAT)
4481 f1 = rettv->vval.v_float;
4483 f1 = get_tv_number(rettv);
4484 if (var2.v_type == VAR_FLOAT)
4485 f2 = var2.vval.v_float;
4487 f2 = get_tv_number(&var2);
4491 case TYPE_EQUAL: n1 = (f1 == f2); break;
4492 case TYPE_NEQUAL: n1 = (f1 != f2); break;
4493 case TYPE_GREATER: n1 = (f1 > f2); break;
4494 case TYPE_GEQUAL: n1 = (f1 >= f2); break;
4495 case TYPE_SMALLER: n1 = (f1 < f2); break;
4496 case TYPE_SEQUAL: n1 = (f1 <= f2); break;
4499 case TYPE_NOMATCH: break; /* avoid gcc warning */
4505 * If one of the two variables is a number, compare as a number.
4506 * When using "=~" or "!~", always compare as string.
4508 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4509 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4511 n1 = get_tv_number(rettv);
4512 n2 = get_tv_number(&var2);
4515 case TYPE_EQUAL: n1 = (n1 == n2); break;
4516 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4517 case TYPE_GREATER: n1 = (n1 > n2); break;
4518 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4519 case TYPE_SMALLER: n1 = (n1 < n2); break;
4520 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4523 case TYPE_NOMATCH: break; /* avoid gcc warning */
4528 s1 = get_tv_string_buf(rettv, buf1);
4529 s2 = get_tv_string_buf(&var2, buf2);
4530 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4531 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4537 case TYPE_EQUAL: n1 = (i == 0); break;
4538 case TYPE_NEQUAL: n1 = (i != 0); break;
4539 case TYPE_GREATER: n1 = (i > 0); break;
4540 case TYPE_GEQUAL: n1 = (i >= 0); break;
4541 case TYPE_SMALLER: n1 = (i < 0); break;
4542 case TYPE_SEQUAL: n1 = (i <= 0); break;
4546 /* avoid 'l' flag in 'cpoptions' */
4548 p_cpo = (char_u *)"";
4549 regmatch.regprog = vim_regcomp(s2,
4550 RE_MAGIC + RE_STRING);
4551 regmatch.rm_ic = ic;
4552 if (regmatch.regprog != NULL)
4554 n1 = vim_regexec_nl(®match, s1, (colnr_T)0);
4555 vim_free(regmatch.regprog);
4556 if (type == TYPE_NOMATCH)
4562 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4567 rettv->v_type = VAR_NUMBER;
4568 rettv->vval.v_number = n1;
4576 * Handle fourth level expression:
4578 * - number subtraction
4579 * . string concatenation
4581 * "arg" must point to the first non-white of the expression.
4582 * "arg" is advanced to the next non-white after the recognized expression.
4584 * Return OK or FAIL.
4587 eval5(arg, rettv, evaluate)
4597 float_T f1 = 0, f2 = 0;
4600 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4604 * Get the first variable.
4606 if (eval6(arg, rettv, evaluate, FALSE) == FAIL)
4610 * Repeat computing, until no '+', '-' or '.' is following.
4615 if (op != '+' && op != '-' && op != '.')
4618 if ((op != '+' || rettv->v_type != VAR_LIST)
4620 && (op == '.' || rettv->v_type != VAR_FLOAT)
4624 /* For "list + ...", an illegal use of the first operand as
4625 * a number cannot be determined before evaluating the 2nd
4626 * operand: if this is also a list, all is ok.
4627 * For "something . ...", "something - ..." or "non-list + ...",
4628 * we know that the first operand needs to be a string or number
4629 * without evaluating the 2nd operand. So check before to avoid
4630 * side effects after an error. */
4631 if (evaluate && get_tv_string_chk(rettv) == NULL)
4639 * Get the second variable.
4641 *arg = skipwhite(*arg + 1);
4642 if (eval6(arg, &var2, evaluate, op == '.') == FAIL)
4651 * Compute the result.
4655 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4656 s2 = get_tv_string_buf_chk(&var2, buf2);
4657 if (s2 == NULL) /* type error ? */
4663 p = concat_str(s1, s2);
4665 rettv->v_type = VAR_STRING;
4666 rettv->vval.v_string = p;
4668 else if (op == '+' && rettv->v_type == VAR_LIST
4669 && var2.v_type == VAR_LIST)
4671 /* concatenate Lists */
4672 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4687 if (rettv->v_type == VAR_FLOAT)
4689 f1 = rettv->vval.v_float;
4695 n1 = get_tv_number_chk(rettv, &error);
4698 /* This can only happen for "list + non-list". For
4699 * "non-list + ..." or "something - ...", we returned
4700 * before evaluating the 2nd operand. */
4705 if (var2.v_type == VAR_FLOAT)
4710 if (var2.v_type == VAR_FLOAT)
4712 f2 = var2.vval.v_float;
4718 n2 = get_tv_number_chk(&var2, &error);
4726 if (rettv->v_type == VAR_FLOAT)
4733 /* If there is a float on either side the result is a float. */
4734 if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4740 rettv->v_type = VAR_FLOAT;
4741 rettv->vval.v_float = f1;
4750 rettv->v_type = VAR_NUMBER;
4751 rettv->vval.v_number = n1;
4761 * Handle fifth level expression:
4762 * * number multiplication
4766 * "arg" must point to the first non-white of the expression.
4767 * "arg" is advanced to the next non-white after the recognized expression.
4769 * Return OK or FAIL.
4772 eval6(arg, rettv, evaluate, want_string)
4776 int want_string; /* after "." operator */
4782 int use_float = FALSE;
4788 * Get the first variable.
4790 if (eval7(arg, rettv, evaluate, want_string) == FAIL)
4794 * Repeat computing, until no '*', '/' or '%' is following.
4799 if (op != '*' && op != '/' && op != '%')
4805 if (rettv->v_type == VAR_FLOAT)
4807 f1 = rettv->vval.v_float;
4813 n1 = get_tv_number_chk(rettv, &error);
4822 * Get the second variable.
4824 *arg = skipwhite(*arg + 1);
4825 if (eval7(arg, &var2, evaluate, FALSE) == FAIL)
4831 if (var2.v_type == VAR_FLOAT)
4838 f2 = var2.vval.v_float;
4844 n2 = get_tv_number_chk(&var2, &error);
4855 * Compute the result.
4856 * When either side is a float the result is a float.
4866 /* VMS crashes on divide by zero, work around it */
4870 f1 = -1 * __F_FLT_MAX - 1L; /* similar to NaN */
4872 f1 = -1 * __F_FLT_MAX;
4879 /* We rely on the floating point library to handle divide
4880 * by zero to result in "inf" and not a crash. */
4886 EMSG(_("E804: Cannot use '%' with Float"));
4889 rettv->v_type = VAR_FLOAT;
4890 rettv->vval.v_float = f1;
4899 if (n2 == 0) /* give an error message? */
4902 n1 = -0x7fffffffL - 1L; /* similar to NaN */
4913 if (n2 == 0) /* give an error message? */
4918 rettv->v_type = VAR_NUMBER;
4919 rettv->vval.v_number = n1;
4928 * Handle sixth level expression:
4929 * number number constant
4930 * "string" string constant
4931 * 'string' literal string constant
4932 * &option-name option value
4933 * @r register contents
4934 * identifier variable value
4935 * function() function call
4936 * $VAR environment variable
4937 * (expression) nested expression
4939 * {key: val, key: val} Dictionary
4942 * ! in front logical NOT
4943 * - in front unary minus
4944 * + in front unary plus (ignored)
4945 * trailing [] subscript in String or List
4946 * trailing .name entry in Dictionary
4948 * "arg" must point to the first non-white of the expression.
4949 * "arg" is advanced to the next non-white after the recognized expression.
4951 * Return OK or FAIL.
4954 eval7(arg, rettv, evaluate, want_string)
4958 int want_string UNUSED; /* after "." operator */
4963 char_u *start_leader, *end_leader;
4968 * Initialise variable so that clear_tv() can't mistake this for a
4969 * string and free a string that isn't there.
4971 rettv->v_type = VAR_UNKNOWN;
4974 * Skip '!' and '-' characters. They are handled later.
4976 start_leader = *arg;
4977 while (**arg == '!' || **arg == '-' || **arg == '+')
4978 *arg = skipwhite(*arg + 1);
4998 char_u *p = skipdigits(*arg + 1);
4999 int get_float = FALSE;
5001 /* We accept a float when the format matches
5002 * "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?". This is very
5003 * strict to avoid backwards compatibility problems.
5004 * Don't look for a float after the "." operator, so that
5005 * ":let vers = 1.2.3" doesn't fail. */
5006 if (!want_string && p[0] == '.' && vim_isdigit(p[1]))
5009 p = skipdigits(p + 2);
5010 if (*p == 'e' || *p == 'E')
5013 if (*p == '-' || *p == '+')
5015 if (!vim_isdigit(*p))
5018 p = skipdigits(p + 1);
5020 if (ASCII_ISALPHA(*p) || *p == '.')
5027 *arg += string2float(*arg, &f);
5030 rettv->v_type = VAR_FLOAT;
5031 rettv->vval.v_float = f;
5037 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
5041 rettv->v_type = VAR_NUMBER;
5042 rettv->vval.v_number = n;
5049 * String constant: "string".
5051 case '"': ret = get_string_tv(arg, rettv, evaluate);
5055 * Literal string constant: 'str''ing'.
5057 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
5061 * List: [expr, expr]
5063 case '[': ret = get_list_tv(arg, rettv, evaluate);
5067 * Dictionary: {key: val, key: val}
5069 case '{': ret = get_dict_tv(arg, rettv, evaluate);
5073 * Option value: &name
5075 case '&': ret = get_option_tv(arg, rettv, evaluate);
5079 * Environment variable: $VAR.
5081 case '$': ret = get_env_tv(arg, rettv, evaluate);
5085 * Register contents: @r.
5090 rettv->v_type = VAR_STRING;
5091 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
5098 * nested expression: (expression).
5100 case '(': *arg = skipwhite(*arg + 1);
5101 ret = eval1(arg, rettv, evaluate); /* recursive! */
5106 EMSG(_("E110: Missing ')'"));
5112 default: ret = NOTDONE;
5119 * Must be a variable or function name.
5120 * Can also be a curly-braces kind of name: {expr}.
5123 len = get_name_len(arg, &alias, evaluate, TRUE);
5131 if (**arg == '(') /* recursive! */
5133 /* If "s" is the name of a variable of type VAR_FUNC
5134 * use its contents. */
5135 s = deref_func_name(s, &len);
5137 /* Invoke the function. */
5138 ret = get_func_tv(s, len, rettv, arg,
5139 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
5140 &len, evaluate, NULL);
5141 /* Stop the expression evaluation when immediately
5142 * aborting on error, or when an interrupt occurred or
5143 * an exception was thrown but not caught. */
5152 ret = get_var_tv(s, len, rettv, TRUE);
5159 *arg = skipwhite(*arg);
5161 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
5164 ret = handle_subscript(arg, rettv, evaluate, TRUE);
5167 * Apply logical NOT and unary '-', from right to left, ignore '+'.
5169 if (ret == OK && evaluate && end_leader > start_leader)
5176 if (rettv->v_type == VAR_FLOAT)
5177 f = rettv->vval.v_float;
5180 val = get_tv_number_chk(rettv, &error);
5188 while (end_leader > start_leader)
5191 if (*end_leader == '!')
5194 if (rettv->v_type == VAR_FLOAT)
5200 else if (*end_leader == '-')
5203 if (rettv->v_type == VAR_FLOAT)
5211 if (rettv->v_type == VAR_FLOAT)
5214 rettv->vval.v_float = f;
5220 rettv->v_type = VAR_NUMBER;
5221 rettv->vval.v_number = val;
5230 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
5231 * "*arg" points to the '[' or '.'.
5232 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
5235 eval_index(arg, rettv, evaluate, verbose)
5239 int verbose; /* give error messages */
5241 int empty1 = FALSE, empty2 = FALSE;
5242 typval_T var1, var2;
5249 if (rettv->v_type == VAR_FUNC
5251 || rettv->v_type == VAR_FLOAT
5256 EMSG(_("E695: Cannot index a Funcref"));
5266 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
5270 *arg = skipwhite(key + len);
5277 * Get the (first) variable from inside the [].
5279 *arg = skipwhite(*arg + 1);
5282 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
5284 else if (evaluate && get_tv_string_chk(&var1) == NULL)
5286 /* not a number or string */
5292 * Get the second variable from inside the [:].
5297 *arg = skipwhite(*arg + 1);
5300 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
5306 else if (evaluate && get_tv_string_chk(&var2) == NULL)
5308 /* not a number or string */
5316 /* Check for the ']'. */
5320 EMSG(_(e_missbrac));
5326 *arg = skipwhite(*arg + 1); /* skip the ']' */
5332 if (!empty1 && rettv->v_type != VAR_DICT)
5334 n1 = get_tv_number(&var1);
5343 n2 = get_tv_number(&var2);
5348 switch (rettv->v_type)
5352 s = get_tv_string(rettv);
5353 len = (long)STRLEN(s);
5356 /* The resulting variable is a substring. If the indexes
5357 * are out of range the result is empty. */
5368 if (n1 >= len || n2 < 0 || n1 > n2)
5371 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
5375 /* The resulting variable is a string of a single
5376 * character. If the index is too big or negative the
5377 * result is empty. */
5378 if (n1 >= len || n1 < 0)
5381 s = vim_strnsave(s + n1, 1);
5384 rettv->v_type = VAR_STRING;
5385 rettv->vval.v_string = s;
5389 len = list_len(rettv->vval.v_list);
5392 if (!empty1 && (n1 < 0 || n1 >= len))
5394 /* For a range we allow invalid values and return an empty
5395 * list. A list index out of range is an error. */
5399 EMSGN(_(e_listidx), n1);
5413 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
5418 for (item = list_find(rettv->vval.v_list, n1);
5421 if (list_append_tv(l, &item->li_tv) == FAIL)
5426 item = item->li_next;
5429 rettv->v_type = VAR_LIST;
5430 rettv->vval.v_list = l;
5435 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
5445 EMSG(_(e_dictrange));
5455 key = get_tv_string(&var1);
5459 EMSG(_(e_emptykey));
5465 item = dict_find(rettv->vval.v_dict, key, (int)len);
5467 if (item == NULL && verbose)
5468 EMSG2(_(e_dictkey), key);
5474 copy_tv(&item->di_tv, &var1);
5486 * Get an option value.
5487 * "arg" points to the '&' or '+' before the option name.
5488 * "arg" is advanced to character after the option name.
5489 * Return OK or FAIL.
5492 get_option_tv(arg, rettv, evaluate)
5494 typval_T *rettv; /* when NULL, only check if option exists */
5502 int working = (**arg == '+'); /* has("+option") */
5507 * Isolate the option name and find its value.
5509 option_end = find_option_end(arg, &opt_flags);
5510 if (option_end == NULL)
5513 EMSG2(_("E112: Option name missing: %s"), *arg);
5525 opt_type = get_option_value(*arg, &numval,
5526 rettv == NULL ? NULL : &stringval, opt_flags);
5528 if (opt_type == -3) /* invalid name */
5531 EMSG2(_("E113: Unknown option: %s"), *arg);
5534 else if (rettv != NULL)
5536 if (opt_type == -2) /* hidden string option */
5538 rettv->v_type = VAR_STRING;
5539 rettv->vval.v_string = NULL;
5541 else if (opt_type == -1) /* hidden number option */
5543 rettv->v_type = VAR_NUMBER;
5544 rettv->vval.v_number = 0;
5546 else if (opt_type == 1) /* number option */
5548 rettv->v_type = VAR_NUMBER;
5549 rettv->vval.v_number = numval;
5551 else /* string option */
5553 rettv->v_type = VAR_STRING;
5554 rettv->vval.v_string = stringval;
5557 else if (working && (opt_type == -2 || opt_type == -1))
5560 *option_end = c; /* put back for error messages */
5567 * Allocate a variable for a string constant.
5568 * Return OK or FAIL.
5571 get_string_tv(arg, rettv, evaluate)
5581 * Find the end of the string, skipping backslashed characters.
5583 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5585 if (*p == '\\' && p[1] != NUL)
5588 /* A "\<x>" form occupies at least 4 characters, and produces up
5589 * to 6 characters: reserve space for 2 extra */
5597 EMSG2(_("E114: Missing quote: %s"), *arg);
5601 /* If only parsing, set *arg and return here */
5609 * Copy the string into allocated memory, handling backslashed
5612 name = alloc((unsigned)(p - *arg + extra));
5615 rettv->v_type = VAR_STRING;
5616 rettv->vval.v_string = name;
5618 for (p = *arg + 1; *p != NUL && *p != '"'; )
5624 case 'b': *name++ = BS; ++p; break;
5625 case 'e': *name++ = ESC; ++p; break;
5626 case 'f': *name++ = FF; ++p; break;
5627 case 'n': *name++ = NL; ++p; break;
5628 case 'r': *name++ = CAR; ++p; break;
5629 case 't': *name++ = TAB; ++p; break;
5631 case 'X': /* hex: "\x1", "\x12" */
5633 case 'u': /* Unicode: "\u0023" */
5635 if (vim_isxdigit(p[1]))
5638 int c = toupper(*p);
5645 while (--n >= 0 && vim_isxdigit(p[1]))
5648 nr = (nr << 4) + hex2nr(*p);
5652 /* For "\u" store the number according to
5655 name += (*mb_char2bytes)(nr, name);
5662 /* octal: "\1", "\12", "\123" */
5670 case '7': *name = *p++ - '0';
5671 if (*p >= '0' && *p <= '7')
5673 *name = (*name << 3) + *p++ - '0';
5674 if (*p >= '0' && *p <= '7')
5675 *name = (*name << 3) + *p++ - '0';
5680 /* Special key, e.g.: "\<C-W>" */
5681 case '<': extra = trans_special(&p, name, TRUE);
5689 default: MB_COPY_CHAR(p, name);
5694 MB_COPY_CHAR(p, name);
5704 * Allocate a variable for a 'str''ing' constant.
5705 * Return OK or FAIL.
5708 get_lit_string_tv(arg, rettv, evaluate)
5718 * Find the end of the string, skipping ''.
5720 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5733 EMSG2(_("E115: Missing quote: %s"), *arg);
5737 /* If only parsing return after setting "*arg" */
5745 * Copy the string into allocated memory, handling '' to ' reduction.
5747 str = alloc((unsigned)((p - *arg) - reduce));
5750 rettv->v_type = VAR_STRING;
5751 rettv->vval.v_string = str;
5753 for (p = *arg + 1; *p != NUL; )
5761 MB_COPY_CHAR(p, str);
5770 * Allocate a variable for a List and fill it from "*arg".
5771 * Return OK or FAIL.
5774 get_list_tv(arg, rettv, evaluate)
5790 *arg = skipwhite(*arg + 1);
5791 while (**arg != ']' && **arg != NUL)
5793 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5797 item = listitem_alloc();
5801 item->li_tv.v_lock = 0;
5802 list_append(l, item);
5812 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5815 *arg = skipwhite(*arg + 1);
5820 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5827 *arg = skipwhite(*arg + 1);
5830 rettv->v_type = VAR_LIST;
5831 rettv->vval.v_list = l;
5839 * Allocate an empty header for a list.
5840 * Caller should take care of the reference count.
5847 l = (list_T *)alloc_clear(sizeof(list_T));
5850 /* Prepend the list to the list of lists for garbage collection. */
5851 if (first_list != NULL)
5852 first_list->lv_used_prev = l;
5853 l->lv_used_prev = NULL;
5854 l->lv_used_next = first_list;
5861 * Allocate an empty list for a return value.
5862 * Returns OK or FAIL.
5865 rettv_list_alloc(rettv)
5868 list_T *l = list_alloc();
5873 rettv->vval.v_list = l;
5874 rettv->v_type = VAR_LIST;
5880 * Unreference a list: decrement the reference count and free it when it
5887 if (l != NULL && --l->lv_refcount <= 0)
5892 * Free a list, including all items it points to.
5893 * Ignores the reference count.
5896 list_free(l, recurse)
5898 int recurse; /* Free Lists and Dictionaries recursively. */
5902 /* Remove the list from the list of lists for garbage collection. */
5903 if (l->lv_used_prev == NULL)
5904 first_list = l->lv_used_next;
5906 l->lv_used_prev->lv_used_next = l->lv_used_next;
5907 if (l->lv_used_next != NULL)
5908 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5910 for (item = l->lv_first; item != NULL; item = l->lv_first)
5912 /* Remove the item before deleting it. */
5913 l->lv_first = item->li_next;
5914 if (recurse || (item->li_tv.v_type != VAR_LIST
5915 && item->li_tv.v_type != VAR_DICT))
5916 clear_tv(&item->li_tv);
5923 * Allocate a list item.
5928 return (listitem_T *)alloc(sizeof(listitem_T));
5932 * Free a list item. Also clears the value. Does not notify watchers.
5938 clear_tv(&item->li_tv);
5943 * Remove a list item from a List and free it. Also clears the value.
5946 listitem_remove(l, item)
5950 list_remove(l, item, item);
5951 listitem_free(item);
5955 * Get the number of items in a list.
5967 * Return TRUE when two lists have exactly the same values.
5970 list_equal(l1, l2, ic, recursive)
5973 int ic; /* ignore case for strings */
5974 int recursive; /* TRUE when used recursively */
5976 listitem_T *item1, *item2;
5978 if (l1 == NULL || l2 == NULL)
5982 if (list_len(l1) != list_len(l2))
5985 for (item1 = l1->lv_first, item2 = l2->lv_first;
5986 item1 != NULL && item2 != NULL;
5987 item1 = item1->li_next, item2 = item2->li_next)
5988 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic, recursive))
5990 return item1 == NULL && item2 == NULL;
5993 #if defined(FEAT_RUBY) || defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) \
5994 || defined(FEAT_MZSCHEME) || defined(FEAT_LUA) || defined(PROTO)
5996 * Return the dictitem that an entry in a hashtable points to.
6007 * Return TRUE when two dictionaries have exactly the same key/values.
6010 dict_equal(d1, d2, ic, recursive)
6013 int ic; /* ignore case for strings */
6014 int recursive; /* TRUE when used recursively */
6020 if (d1 == NULL || d2 == NULL)
6024 if (dict_len(d1) != dict_len(d2))
6027 todo = (int)d1->dv_hashtab.ht_used;
6028 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
6030 if (!HASHITEM_EMPTY(hi))
6032 item2 = dict_find(d2, hi->hi_key, -1);
6035 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic, recursive))
6043 static int tv_equal_recurse_limit;
6046 * Return TRUE if "tv1" and "tv2" have the same value.
6047 * Compares the items just like "==" would compare them, but strings and
6048 * numbers are different. Floats and numbers are also different.
6051 tv_equal(tv1, tv2, ic, recursive)
6054 int ic; /* ignore case */
6055 int recursive; /* TRUE when used recursively */
6057 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
6059 static int recursive_cnt = 0; /* catch recursive loops */
6062 if (tv1->v_type != tv2->v_type)
6065 /* Catch lists and dicts that have an endless loop by limiting
6066 * recursiveness to a limit. We guess they are equal then.
6067 * A fixed limit has the problem of still taking an awful long time.
6068 * Reduce the limit every time running into it. That should work fine for
6069 * deeply linked structures that are not recursively linked and catch
6070 * recursiveness quickly. */
6072 tv_equal_recurse_limit = 1000;
6073 if (recursive_cnt >= tv_equal_recurse_limit)
6075 --tv_equal_recurse_limit;
6079 switch (tv1->v_type)
6083 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic, TRUE);
6089 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic, TRUE);
6094 return (tv1->vval.v_string != NULL
6095 && tv2->vval.v_string != NULL
6096 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
6099 return tv1->vval.v_number == tv2->vval.v_number;
6103 return tv1->vval.v_float == tv2->vval.v_float;
6107 s1 = get_tv_string_buf(tv1, buf1);
6108 s2 = get_tv_string_buf(tv2, buf2);
6109 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
6112 EMSG2(_(e_intern2), "tv_equal()");
6117 * Locate item with index "n" in list "l" and return it.
6118 * A negative index is counted from the end; -1 is the last item.
6119 * Returns NULL when "n" is out of range.
6132 /* Negative index is relative to the end. */
6136 /* Check for index out of range. */
6137 if (n < 0 || n >= l->lv_len)
6140 /* When there is a cached index may start search from there. */
6141 if (l->lv_idx_item != NULL)
6143 if (n < l->lv_idx / 2)
6145 /* closest to the start of the list */
6149 else if (n > (l->lv_idx + l->lv_len) / 2)
6151 /* closest to the end of the list */
6153 idx = l->lv_len - 1;
6157 /* closest to the cached index */
6158 item = l->lv_idx_item;
6164 if (n < l->lv_len / 2)
6166 /* closest to the start of the list */
6172 /* closest to the end of the list */
6174 idx = l->lv_len - 1;
6180 /* search forward */
6181 item = item->li_next;
6186 /* search backward */
6187 item = item->li_prev;
6191 /* cache the used index */
6193 l->lv_idx_item = item;
6199 * Get list item "l[idx]" as a number.
6202 list_find_nr(l, idx, errorp)
6205 int *errorp; /* set to TRUE when something wrong */
6209 li = list_find(l, idx);
6216 return get_tv_number_chk(&li->li_tv, errorp);
6220 * Get list item "l[idx - 1]" as a string. Returns NULL for failure.
6223 list_find_str(l, idx)
6229 li = list_find(l, idx - 1);
6232 EMSGN(_(e_listidx), idx);
6235 return get_tv_string(&li->li_tv);
6239 * Locate "item" list "l" and return its index.
6240 * Returns -1 when "item" is not in the list.
6243 list_idx_of_item(l, item)
6253 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
6261 * Append item "item" to the end of list "l".
6264 list_append(l, item)
6268 if (l->lv_last == NULL)
6273 item->li_prev = NULL;
6277 l->lv_last->li_next = item;
6278 item->li_prev = l->lv_last;
6282 item->li_next = NULL;
6286 * Append typval_T "tv" to the end of list "l".
6287 * Return FAIL when out of memory.
6290 list_append_tv(l, tv)
6294 listitem_T *li = listitem_alloc();
6298 copy_tv(tv, &li->li_tv);
6304 * Add a dictionary to a list. Used by getqflist().
6305 * Return FAIL when out of memory.
6308 list_append_dict(list, dict)
6312 listitem_T *li = listitem_alloc();
6316 li->li_tv.v_type = VAR_DICT;
6317 li->li_tv.v_lock = 0;
6318 li->li_tv.vval.v_dict = dict;
6319 list_append(list, li);
6320 ++dict->dv_refcount;
6325 * Make a copy of "str" and append it as an item to list "l".
6326 * When "len" >= 0 use "str[len]".
6327 * Returns FAIL when out of memory.
6330 list_append_string(l, str, len)
6335 listitem_T *li = listitem_alloc();
6340 li->li_tv.v_type = VAR_STRING;
6341 li->li_tv.v_lock = 0;
6343 li->li_tv.vval.v_string = NULL;
6344 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
6345 : vim_strsave(str))) == NULL)
6351 * Append "n" to list "l".
6352 * Returns FAIL when out of memory.
6355 list_append_number(l, n)
6361 li = listitem_alloc();
6364 li->li_tv.v_type = VAR_NUMBER;
6365 li->li_tv.v_lock = 0;
6366 li->li_tv.vval.v_number = n;
6372 * Insert typval_T "tv" in list "l" before "item".
6373 * If "item" is NULL append at the end.
6374 * Return FAIL when out of memory.
6377 list_insert_tv(l, tv, item)
6382 listitem_T *ni = listitem_alloc();
6386 copy_tv(tv, &ni->li_tv);
6388 /* Append new item at end of list. */
6392 /* Insert new item before existing item. */
6393 ni->li_prev = item->li_prev;
6395 if (item->li_prev == NULL)
6402 item->li_prev->li_next = ni;
6403 l->lv_idx_item = NULL;
6412 * Extend "l1" with "l2".
6413 * If "bef" is NULL append at the end, otherwise insert before this item.
6414 * Returns FAIL when out of memory.
6417 list_extend(l1, l2, bef)
6423 int todo = l2->lv_len;
6425 /* We also quit the loop when we have inserted the original item count of
6426 * the list, avoid a hang when we extend a list with itself. */
6427 for (item = l2->lv_first; item != NULL && --todo >= 0; item = item->li_next)
6428 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
6434 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
6435 * Return FAIL when out of memory.
6438 list_concat(l1, l2, tv)
6445 if (l1 == NULL || l2 == NULL)
6448 /* make a copy of the first list. */
6449 l = list_copy(l1, FALSE, 0);
6452 tv->v_type = VAR_LIST;
6453 tv->vval.v_list = l;
6455 /* append all items from the second list */
6456 return list_extend(l, l2, NULL);
6460 * Make a copy of list "orig". Shallow if "deep" is FALSE.
6461 * The refcount of the new list is set to 1.
6462 * See item_copy() for "copyID".
6463 * Returns NULL when out of memory.
6466 list_copy(orig, deep, copyID)
6478 copy = list_alloc();
6483 /* Do this before adding the items, because one of the items may
6484 * refer back to this list. */
6485 orig->lv_copyID = copyID;
6486 orig->lv_copylist = copy;
6488 for (item = orig->lv_first; item != NULL && !got_int;
6489 item = item->li_next)
6491 ni = listitem_alloc();
6496 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
6503 copy_tv(&item->li_tv, &ni->li_tv);
6504 list_append(copy, ni);
6506 ++copy->lv_refcount;
6518 * Remove items "item" to "item2" from list "l".
6519 * Does not free the listitem or the value!
6522 list_remove(l, item, item2)
6529 /* notify watchers */
6530 for (ip = item; ip != NULL; ip = ip->li_next)
6533 list_fix_watch(l, ip);
6538 if (item2->li_next == NULL)
6539 l->lv_last = item->li_prev;
6541 item2->li_next->li_prev = item->li_prev;
6542 if (item->li_prev == NULL)
6543 l->lv_first = item2->li_next;
6545 item->li_prev->li_next = item2->li_next;
6546 l->lv_idx_item = NULL;
6550 * Return an allocated string with the string representation of a list.
6554 list2string(tv, copyID)
6560 if (tv->vval.v_list == NULL)
6562 ga_init2(&ga, (int)sizeof(char), 80);
6563 ga_append(&ga, '[');
6564 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6566 vim_free(ga.ga_data);
6569 ga_append(&ga, ']');
6570 ga_append(&ga, NUL);
6571 return (char_u *)ga.ga_data;
6575 * Join list "l" into a string in "*gap", using separator "sep".
6576 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6577 * Return FAIL or OK.
6580 list_join(gap, l, sep, echo, copyID)
6589 char_u numbuf[NUMBUFLEN];
6593 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6598 ga_concat(gap, sep);
6601 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6603 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6615 * Garbage collection for lists and dictionaries.
6617 * We use reference counts to be able to free most items right away when they
6618 * are no longer used. But for composite items it's possible that it becomes
6619 * unused while the reference count is > 0: When there is a recursive
6620 * reference. Example:
6621 * :let l = [1, 2, 3]
6625 * Since this is quite unusual we handle this with garbage collection: every
6626 * once in a while find out which lists and dicts are not referenced from any
6629 * Here is a good reference text about garbage collection (refers to Python
6630 * but it applies to all reference-counting mechanisms):
6631 * http://python.ca/nas/python/gc/
6635 * Do garbage collection for lists and dicts.
6636 * Return TRUE if some memory was freed.
6645 funccall_T *fc, **pfc;
6647 int did_free_funccal = FALSE;
6652 /* Only do this once. */
6653 want_garbage_collect = FALSE;
6654 may_garbage_collect = FALSE;
6655 garbage_collect_at_exit = FALSE;
6657 /* We advance by two because we add one for items referenced through
6658 * previous_funccal. */
6659 current_copyID += COPYID_INC;
6660 copyID = current_copyID;
6663 * 1. Go through all accessible variables and mark all lists and dicts
6667 /* Don't free variables in the previous_funccal list unless they are only
6668 * referenced through previous_funccal. This must be first, because if
6669 * the item is referenced elsewhere the funccal must not be freed. */
6670 for (fc = previous_funccal; fc != NULL; fc = fc->caller)
6672 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1);
6673 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1);
6676 /* script-local variables */
6677 for (i = 1; i <= ga_scripts.ga_len; ++i)
6678 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6680 /* buffer-local variables */
6681 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6682 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6684 /* window-local variables */
6685 FOR_ALL_TAB_WINDOWS(tp, wp)
6686 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6689 /* tabpage-local variables */
6690 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6691 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6694 /* global variables */
6695 set_ref_in_ht(&globvarht, copyID);
6697 /* function-local variables */
6698 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6700 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6701 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6705 set_ref_in_ht(&vimvarht, copyID);
6708 * 2. Free lists and dictionaries that are not referenced.
6710 did_free = free_unref_items(copyID);
6713 * 3. Check if any funccal can be freed now.
6715 for (pfc = &previous_funccal; *pfc != NULL; )
6717 if (can_free_funccal(*pfc, copyID))
6721 free_funccal(fc, TRUE);
6723 did_free_funccal = TRUE;
6726 pfc = &(*pfc)->caller;
6728 if (did_free_funccal)
6729 /* When a funccal was freed some more items might be garbage
6730 * collected, so run again. */
6731 (void)garbage_collect();
6737 * Free lists and dictionaries that are no longer referenced.
6740 free_unref_items(copyID)
6745 int did_free = FALSE;
6748 * Go through the list of dicts and free items without the copyID.
6750 for (dd = first_dict; dd != NULL; )
6751 if ((dd->dv_copyID & COPYID_MASK) != (copyID & COPYID_MASK))
6753 /* Free the Dictionary and ordinary items it contains, but don't
6754 * recurse into Lists and Dictionaries, they will be in the list
6755 * of dicts or list of lists. */
6756 dict_free(dd, FALSE);
6759 /* restart, next dict may also have been freed */
6763 dd = dd->dv_used_next;
6766 * Go through the list of lists and free items without the copyID.
6767 * But don't free a list that has a watcher (used in a for loop), these
6768 * are not referenced anywhere.
6770 for (ll = first_list; ll != NULL; )
6771 if ((ll->lv_copyID & COPYID_MASK) != (copyID & COPYID_MASK)
6772 && ll->lv_watch == NULL)
6774 /* Free the List and ordinary items it contains, but don't recurse
6775 * into Lists and Dictionaries, they will be in the list of dicts
6776 * or list of lists. */
6777 list_free(ll, FALSE);
6780 /* restart, next list may also have been freed */
6784 ll = ll->lv_used_next;
6790 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6793 set_ref_in_ht(ht, copyID)
6800 todo = (int)ht->ht_used;
6801 for (hi = ht->ht_array; todo > 0; ++hi)
6802 if (!HASHITEM_EMPTY(hi))
6805 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6810 * Mark all lists and dicts referenced through list "l" with "copyID".
6813 set_ref_in_list(l, copyID)
6819 for (li = l->lv_first; li != NULL; li = li->li_next)
6820 set_ref_in_item(&li->li_tv, copyID);
6824 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6827 set_ref_in_item(tv, copyID)
6837 dd = tv->vval.v_dict;
6838 if (dd != NULL && dd->dv_copyID != copyID)
6840 /* Didn't see this dict yet. */
6841 dd->dv_copyID = copyID;
6842 set_ref_in_ht(&dd->dv_hashtab, copyID);
6847 ll = tv->vval.v_list;
6848 if (ll != NULL && ll->lv_copyID != copyID)
6850 /* Didn't see this list yet. */
6851 ll->lv_copyID = copyID;
6852 set_ref_in_list(ll, copyID);
6860 * Allocate an empty header for a dictionary.
6867 d = (dict_T *)alloc(sizeof(dict_T));
6870 /* Add the list to the list of dicts for garbage collection. */
6871 if (first_dict != NULL)
6872 first_dict->dv_used_prev = d;
6873 d->dv_used_next = first_dict;
6874 d->dv_used_prev = NULL;
6877 hash_init(&d->dv_hashtab);
6886 * Allocate an empty dict for a return value.
6887 * Returns OK or FAIL.
6890 rettv_dict_alloc(rettv)
6893 dict_T *d = dict_alloc();
6898 rettv->vval.v_dict = d;
6899 rettv->v_type = VAR_DICT;
6906 * Unreference a Dictionary: decrement the reference count and free it when it
6913 if (d != NULL && --d->dv_refcount <= 0)
6918 * Free a Dictionary, including all items it contains.
6919 * Ignores the reference count.
6922 dict_free(d, recurse)
6924 int recurse; /* Free Lists and Dictionaries recursively. */
6930 /* Remove the dict from the list of dicts for garbage collection. */
6931 if (d->dv_used_prev == NULL)
6932 first_dict = d->dv_used_next;
6934 d->dv_used_prev->dv_used_next = d->dv_used_next;
6935 if (d->dv_used_next != NULL)
6936 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6938 /* Lock the hashtab, we don't want it to resize while freeing items. */
6939 hash_lock(&d->dv_hashtab);
6940 todo = (int)d->dv_hashtab.ht_used;
6941 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6943 if (!HASHITEM_EMPTY(hi))
6945 /* Remove the item before deleting it, just in case there is
6946 * something recursive causing trouble. */
6948 hash_remove(&d->dv_hashtab, hi);
6949 if (recurse || (di->di_tv.v_type != VAR_LIST
6950 && di->di_tv.v_type != VAR_DICT))
6951 clear_tv(&di->di_tv);
6956 hash_clear(&d->dv_hashtab);
6961 * Allocate a Dictionary item.
6962 * The "key" is copied to the new item.
6963 * Note that the value of the item "di_tv" still needs to be initialized!
6964 * Returns NULL when out of memory.
6972 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6975 STRCPY(di->di_key, key);
6982 * Make a copy of a Dictionary item.
6990 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6991 + STRLEN(org->di_key)));
6994 STRCPY(di->di_key, org->di_key);
6996 copy_tv(&org->di_tv, &di->di_tv);
7002 * Remove item "item" from Dictionary "dict" and free it.
7005 dictitem_remove(dict, item)
7011 hi = hash_find(&dict->dv_hashtab, item->di_key);
7012 if (HASHITEM_EMPTY(hi))
7013 EMSG2(_(e_intern2), "dictitem_remove()");
7015 hash_remove(&dict->dv_hashtab, hi);
7016 dictitem_free(item);
7020 * Free a dict item. Also clears the value.
7026 clear_tv(&item->di_tv);
7031 * Make a copy of dict "d". Shallow if "deep" is FALSE.
7032 * The refcount of the new dict is set to 1.
7033 * See item_copy() for "copyID".
7034 * Returns NULL when out of memory.
7037 dict_copy(orig, deep, copyID)
7050 copy = dict_alloc();
7055 orig->dv_copyID = copyID;
7056 orig->dv_copydict = copy;
7058 todo = (int)orig->dv_hashtab.ht_used;
7059 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
7061 if (!HASHITEM_EMPTY(hi))
7065 di = dictitem_alloc(hi->hi_key);
7070 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
7078 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
7079 if (dict_add(copy, di) == FAIL)
7087 ++copy->dv_refcount;
7099 * Add item "item" to Dictionary "d".
7100 * Returns FAIL when out of memory and when key already exists.
7107 return hash_add(&d->dv_hashtab, item->di_key);
7111 * Add a number or string entry to dictionary "d".
7112 * When "str" is NULL use number "nr", otherwise use "str".
7113 * Returns FAIL when out of memory and when key already exists.
7116 dict_add_nr_str(d, key, nr, str)
7124 item = dictitem_alloc((char_u *)key);
7127 item->di_tv.v_lock = 0;
7130 item->di_tv.v_type = VAR_NUMBER;
7131 item->di_tv.vval.v_number = nr;
7135 item->di_tv.v_type = VAR_STRING;
7136 item->di_tv.vval.v_string = vim_strsave(str);
7138 if (dict_add(d, item) == FAIL)
7140 dictitem_free(item);
7147 * Add a list entry to dictionary "d".
7148 * Returns FAIL when out of memory and when key already exists.
7151 dict_add_list(d, key, list)
7158 item = dictitem_alloc((char_u *)key);
7161 item->di_tv.v_lock = 0;
7162 item->di_tv.v_type = VAR_LIST;
7163 item->di_tv.vval.v_list = list;
7164 if (dict_add(d, item) == FAIL)
7166 dictitem_free(item);
7169 ++list->lv_refcount;
7174 * Get the number of items in a Dictionary.
7182 return (long)d->dv_hashtab.ht_used;
7186 * Find item "key[len]" in Dictionary "d".
7187 * If "len" is negative use strlen(key).
7188 * Returns NULL when not found.
7191 dict_find(d, key, len)
7197 char_u buf[AKEYLEN];
7199 char_u *tofree = NULL;
7204 else if (len >= AKEYLEN)
7206 tofree = akey = vim_strnsave(key, len);
7212 /* Avoid a malloc/free by using buf[]. */
7213 vim_strncpy(buf, key, len);
7217 hi = hash_find(&d->dv_hashtab, akey);
7219 if (HASHITEM_EMPTY(hi))
7225 * Get a string item from a dictionary.
7226 * When "save" is TRUE allocate memory for it.
7227 * Returns NULL if the entry doesn't exist or out of memory.
7230 get_dict_string(d, key, save)
7238 di = dict_find(d, key, -1);
7241 s = get_tv_string(&di->di_tv);
7242 if (save && s != NULL)
7248 * Get a number item from a dictionary.
7249 * Returns 0 if the entry doesn't exist or out of memory.
7252 get_dict_number(d, key)
7258 di = dict_find(d, key, -1);
7261 return get_tv_number(&di->di_tv);
7265 * Return an allocated string with the string representation of a Dictionary.
7269 dict2string(tv, copyID)
7276 char_u numbuf[NUMBUFLEN];
7282 if ((d = tv->vval.v_dict) == NULL)
7284 ga_init2(&ga, (int)sizeof(char), 80);
7285 ga_append(&ga, '{');
7287 todo = (int)d->dv_hashtab.ht_used;
7288 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
7290 if (!HASHITEM_EMPTY(hi))
7297 ga_concat(&ga, (char_u *)", ");
7299 tofree = string_quote(hi->hi_key, FALSE);
7302 ga_concat(&ga, tofree);
7305 ga_concat(&ga, (char_u *)": ");
7306 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
7316 vim_free(ga.ga_data);
7320 ga_append(&ga, '}');
7321 ga_append(&ga, NUL);
7322 return (char_u *)ga.ga_data;
7326 * Allocate a variable for a Dictionary and fill it from "*arg".
7327 * Return OK or FAIL. Returns NOTDONE for {expr}.
7330 get_dict_tv(arg, rettv, evaluate)
7340 char_u *start = skipwhite(*arg + 1);
7341 char_u buf[NUMBUFLEN];
7344 * First check if it's not a curly-braces thing: {expr}.
7345 * Must do this without evaluating, otherwise a function may be called
7346 * twice. Unfortunately this means we need to call eval1() twice for the
7348 * But {} is an empty Dictionary.
7352 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
7364 tvkey.v_type = VAR_UNKNOWN;
7365 tv.v_type = VAR_UNKNOWN;
7367 *arg = skipwhite(*arg + 1);
7368 while (**arg != '}' && **arg != NUL)
7370 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
7374 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
7380 key = get_tv_string_buf_chk(&tvkey, buf);
7381 if (key == NULL || *key == NUL)
7383 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
7385 EMSG(_(e_emptykey));
7391 *arg = skipwhite(*arg + 1);
7392 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
7400 item = dict_find(d, key, -1);
7403 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
7408 item = dictitem_alloc(key);
7413 item->di_tv.v_lock = 0;
7414 if (dict_add(d, item) == FAIL)
7415 dictitem_free(item);
7423 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
7426 *arg = skipwhite(*arg + 1);
7431 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
7438 *arg = skipwhite(*arg + 1);
7441 rettv->v_type = VAR_DICT;
7442 rettv->vval.v_dict = d;
7450 * Return a string with the string representation of a variable.
7451 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7452 * "numbuf" is used for a number.
7453 * Does not put quotes around strings, as ":echo" displays values.
7454 * When "copyID" is not NULL replace recursive lists and dicts with "...".
7458 echo_string(tv, tofree, numbuf, copyID)
7464 static int recurse = 0;
7467 if (recurse >= DICT_MAXNEST)
7469 EMSG(_("E724: variable nested too deep for displaying"));
7479 r = tv->vval.v_string;
7483 if (tv->vval.v_list == NULL)
7488 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
7491 r = (char_u *)"[...]";
7495 tv->vval.v_list->lv_copyID = copyID;
7496 *tofree = list2string(tv, copyID);
7502 if (tv->vval.v_dict == NULL)
7507 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
7510 r = (char_u *)"{...}";
7514 tv->vval.v_dict->dv_copyID = copyID;
7515 *tofree = dict2string(tv, copyID);
7523 r = get_tv_string_buf(tv, numbuf);
7529 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
7535 EMSG2(_(e_intern2), "echo_string()");
7544 * Return a string with the string representation of a variable.
7545 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7546 * "numbuf" is used for a number.
7547 * Puts quotes around strings, so that they can be parsed back by eval().
7551 tv2string(tv, tofree, numbuf, copyID)
7560 *tofree = string_quote(tv->vval.v_string, TRUE);
7563 *tofree = string_quote(tv->vval.v_string, FALSE);
7568 vim_snprintf((char *)numbuf, NUMBUFLEN - 1, "%g", tv->vval.v_float);
7576 EMSG2(_(e_intern2), "tv2string()");
7578 return echo_string(tv, tofree, numbuf, copyID);
7582 * Return string "str" in ' quotes, doubling ' characters.
7583 * If "str" is NULL an empty string is assumed.
7584 * If "function" is TRUE make it function('string').
7587 string_quote(str, function)
7594 len = (function ? 13 : 3);
7597 len += (unsigned)STRLEN(str);
7598 for (p = str; *p != NUL; mb_ptr_adv(p))
7607 STRCPY(r, "function('");
7613 for (p = str; *p != NUL; )
7629 * Convert the string "text" to a floating point number.
7630 * This uses strtod(). setlocale(LC_NUMERIC, "C") has been used to make sure
7631 * this always uses a decimal point.
7632 * Returns the length of the text that was consumed.
7635 string2float(text, value)
7637 float_T *value; /* result stored here */
7639 char *s = (char *)text;
7644 return (int)((char_u *)s - text);
7649 * Get the value of an environment variable.
7650 * "arg" is pointing to the '$'. It is advanced to after the name.
7651 * If the environment variable was not set, silently assume it is empty.
7655 get_env_tv(arg, rettv, evaluate)
7660 char_u *string = NULL;
7664 int mustfree = FALSE;
7668 len = get_env_len(arg);
7675 /* first try vim_getenv(), fast for normal environment vars */
7676 string = vim_getenv(name, &mustfree);
7677 if (string != NULL && *string != NUL)
7680 string = vim_strsave(string);
7687 /* next try expanding things like $VIM and ${HOME} */
7688 string = expand_env_save(name - 1);
7689 if (string != NULL && *string == '$')
7697 rettv->v_type = VAR_STRING;
7698 rettv->vval.v_string = string;
7705 * Array with names and number of arguments of all internal functions
7706 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7710 char *f_name; /* function name */
7711 char f_min_argc; /* minimal number of arguments */
7712 char f_max_argc; /* maximal number of arguments */
7713 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7714 /* implementation of function */
7718 {"abs", 1, 1, f_abs},
7719 {"acos", 1, 1, f_acos}, /* WJMc */
7721 {"add", 2, 2, f_add},
7722 {"and", 2, 2, f_and},
7723 {"append", 2, 2, f_append},
7724 {"argc", 0, 0, f_argc},
7725 {"argidx", 0, 0, f_argidx},
7726 {"argv", 0, 1, f_argv},
7728 {"asin", 1, 1, f_asin}, /* WJMc */
7729 {"atan", 1, 1, f_atan},
7730 {"atan2", 2, 2, f_atan2},
7732 {"browse", 4, 4, f_browse},
7733 {"browsedir", 2, 2, f_browsedir},
7734 {"bufexists", 1, 1, f_bufexists},
7735 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7736 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7737 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7738 {"buflisted", 1, 1, f_buflisted},
7739 {"bufloaded", 1, 1, f_bufloaded},
7740 {"bufname", 1, 1, f_bufname},
7741 {"bufnr", 1, 2, f_bufnr},
7742 {"bufwinnr", 1, 1, f_bufwinnr},
7743 {"byte2line", 1, 1, f_byte2line},
7744 {"byteidx", 2, 2, f_byteidx},
7745 {"call", 2, 3, f_call},
7747 {"ceil", 1, 1, f_ceil},
7749 {"changenr", 0, 0, f_changenr},
7750 {"char2nr", 1, 1, f_char2nr},
7751 {"cindent", 1, 1, f_cindent},
7752 {"clearmatches", 0, 0, f_clearmatches},
7753 {"col", 1, 1, f_col},
7754 #if defined(FEAT_INS_EXPAND)
7755 {"complete", 2, 2, f_complete},
7756 {"complete_add", 1, 1, f_complete_add},
7757 {"complete_check", 0, 0, f_complete_check},
7759 {"confirm", 1, 4, f_confirm},
7760 {"copy", 1, 1, f_copy},
7762 {"cos", 1, 1, f_cos},
7763 {"cosh", 1, 1, f_cosh},
7765 {"count", 2, 4, f_count},
7766 {"cscope_connection",0,3, f_cscope_connection},
7767 {"cursor", 1, 3, f_cursor},
7768 {"deepcopy", 1, 2, f_deepcopy},
7769 {"delete", 1, 1, f_delete},
7770 {"did_filetype", 0, 0, f_did_filetype},
7771 {"diff_filler", 1, 1, f_diff_filler},
7772 {"diff_hlID", 2, 2, f_diff_hlID},
7773 {"empty", 1, 1, f_empty},
7774 {"escape", 2, 2, f_escape},
7775 {"eval", 1, 1, f_eval},
7776 {"eventhandler", 0, 0, f_eventhandler},
7777 {"executable", 1, 1, f_executable},
7778 {"exists", 1, 1, f_exists},
7780 {"exp", 1, 1, f_exp},
7782 {"expand", 1, 2, f_expand},
7783 {"extend", 2, 3, f_extend},
7784 {"feedkeys", 1, 2, f_feedkeys},
7785 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7786 {"filereadable", 1, 1, f_filereadable},
7787 {"filewritable", 1, 1, f_filewritable},
7788 {"filter", 2, 2, f_filter},
7789 {"finddir", 1, 3, f_finddir},
7790 {"findfile", 1, 3, f_findfile},
7792 {"float2nr", 1, 1, f_float2nr},
7793 {"floor", 1, 1, f_floor},
7794 {"fmod", 2, 2, f_fmod},
7796 {"fnameescape", 1, 1, f_fnameescape},
7797 {"fnamemodify", 2, 2, f_fnamemodify},
7798 {"foldclosed", 1, 1, f_foldclosed},
7799 {"foldclosedend", 1, 1, f_foldclosedend},
7800 {"foldlevel", 1, 1, f_foldlevel},
7801 {"foldtext", 0, 0, f_foldtext},
7802 {"foldtextresult", 1, 1, f_foldtextresult},
7803 {"foreground", 0, 0, f_foreground},
7804 {"function", 1, 1, f_function},
7805 {"garbagecollect", 0, 1, f_garbagecollect},
7806 {"get", 2, 3, f_get},
7807 {"getbufline", 2, 3, f_getbufline},
7808 {"getbufvar", 2, 2, f_getbufvar},
7809 {"getchar", 0, 1, f_getchar},
7810 {"getcharmod", 0, 0, f_getcharmod},
7811 {"getcmdline", 0, 0, f_getcmdline},
7812 {"getcmdpos", 0, 0, f_getcmdpos},
7813 {"getcmdtype", 0, 0, f_getcmdtype},
7814 {"getcwd", 0, 0, f_getcwd},
7815 {"getfontname", 0, 1, f_getfontname},
7816 {"getfperm", 1, 1, f_getfperm},
7817 {"getfsize", 1, 1, f_getfsize},
7818 {"getftime", 1, 1, f_getftime},
7819 {"getftype", 1, 1, f_getftype},
7820 {"getline", 1, 2, f_getline},
7821 {"getloclist", 1, 1, f_getqflist},
7822 {"getmatches", 0, 0, f_getmatches},
7823 {"getpid", 0, 0, f_getpid},
7824 {"getpos", 1, 1, f_getpos},
7825 {"getqflist", 0, 0, f_getqflist},
7826 {"getreg", 0, 2, f_getreg},
7827 {"getregtype", 0, 1, f_getregtype},
7828 {"gettabvar", 2, 2, f_gettabvar},
7829 {"gettabwinvar", 3, 3, f_gettabwinvar},
7830 {"getwinposx", 0, 0, f_getwinposx},
7831 {"getwinposy", 0, 0, f_getwinposy},
7832 {"getwinvar", 2, 2, f_getwinvar},
7833 {"glob", 1, 2, f_glob},
7834 {"globpath", 2, 3, f_globpath},
7835 {"has", 1, 1, f_has},
7836 {"has_key", 2, 2, f_has_key},
7837 {"haslocaldir", 0, 0, f_haslocaldir},
7838 {"hasmapto", 1, 3, f_hasmapto},
7839 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7840 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7841 {"histadd", 2, 2, f_histadd},
7842 {"histdel", 1, 2, f_histdel},
7843 {"histget", 1, 2, f_histget},
7844 {"histnr", 1, 1, f_histnr},
7845 {"hlID", 1, 1, f_hlID},
7846 {"hlexists", 1, 1, f_hlexists},
7847 {"hostname", 0, 0, f_hostname},
7848 {"iconv", 3, 3, f_iconv},
7849 {"indent", 1, 1, f_indent},
7850 {"index", 2, 4, f_index},
7851 {"input", 1, 3, f_input},
7852 {"inputdialog", 1, 3, f_inputdialog},
7853 {"inputlist", 1, 1, f_inputlist},
7854 {"inputrestore", 0, 0, f_inputrestore},
7855 {"inputsave", 0, 0, f_inputsave},
7856 {"inputsecret", 1, 2, f_inputsecret},
7857 {"insert", 2, 3, f_insert},
7858 {"invert", 1, 1, f_invert},
7859 {"isdirectory", 1, 1, f_isdirectory},
7860 {"islocked", 1, 1, f_islocked},
7861 {"items", 1, 1, f_items},
7862 {"join", 1, 2, f_join},
7863 {"keys", 1, 1, f_keys},
7864 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7865 {"len", 1, 1, f_len},
7866 {"libcall", 3, 3, f_libcall},
7867 {"libcallnr", 3, 3, f_libcallnr},
7868 {"line", 1, 1, f_line},
7869 {"line2byte", 1, 1, f_line2byte},
7870 {"lispindent", 1, 1, f_lispindent},
7871 {"localtime", 0, 0, f_localtime},
7873 {"log", 1, 1, f_log},
7874 {"log10", 1, 1, f_log10},
7876 {"map", 2, 2, f_map},
7877 {"maparg", 1, 4, f_maparg},
7878 {"mapcheck", 1, 3, f_mapcheck},
7879 {"match", 2, 4, f_match},
7880 {"matchadd", 2, 4, f_matchadd},
7881 {"matcharg", 1, 1, f_matcharg},
7882 {"matchdelete", 1, 1, f_matchdelete},
7883 {"matchend", 2, 4, f_matchend},
7884 {"matchlist", 2, 4, f_matchlist},
7885 {"matchstr", 2, 4, f_matchstr},
7886 {"max", 1, 1, f_max},
7887 {"min", 1, 1, f_min},
7889 {"mkdir", 1, 3, f_mkdir},
7891 {"mode", 0, 1, f_mode},
7892 #ifdef FEAT_MZSCHEME
7893 {"mzeval", 1, 1, f_mzeval},
7895 {"nextnonblank", 1, 1, f_nextnonblank},
7896 {"nr2char", 1, 1, f_nr2char},
7898 {"pathshorten", 1, 1, f_pathshorten},
7900 {"pow", 2, 2, f_pow},
7902 {"prevnonblank", 1, 1, f_prevnonblank},
7903 {"printf", 2, 19, f_printf},
7904 {"pumvisible", 0, 0, f_pumvisible},
7905 {"range", 1, 3, f_range},
7906 {"readfile", 1, 3, f_readfile},
7907 {"reltime", 0, 2, f_reltime},
7908 {"reltimestr", 1, 1, f_reltimestr},
7909 {"remote_expr", 2, 3, f_remote_expr},
7910 {"remote_foreground", 1, 1, f_remote_foreground},
7911 {"remote_peek", 1, 2, f_remote_peek},
7912 {"remote_read", 1, 1, f_remote_read},
7913 {"remote_send", 2, 3, f_remote_send},
7914 {"remove", 2, 3, f_remove},
7915 {"rename", 2, 2, f_rename},
7916 {"repeat", 2, 2, f_repeat},
7917 {"resolve", 1, 1, f_resolve},
7918 {"reverse", 1, 1, f_reverse},
7920 {"round", 1, 1, f_round},
7922 {"search", 1, 4, f_search},
7923 {"searchdecl", 1, 3, f_searchdecl},
7924 {"searchpair", 3, 7, f_searchpair},
7925 {"searchpairpos", 3, 7, f_searchpairpos},
7926 {"searchpos", 1, 4, f_searchpos},
7927 {"server2client", 2, 2, f_server2client},
7928 {"serverlist", 0, 0, f_serverlist},
7929 {"setbufvar", 3, 3, f_setbufvar},
7930 {"setcmdpos", 1, 1, f_setcmdpos},
7931 {"setline", 2, 2, f_setline},
7932 {"setloclist", 2, 3, f_setloclist},
7933 {"setmatches", 1, 1, f_setmatches},
7934 {"setpos", 2, 2, f_setpos},
7935 {"setqflist", 1, 2, f_setqflist},
7936 {"setreg", 2, 3, f_setreg},
7937 {"settabvar", 3, 3, f_settabvar},
7938 {"settabwinvar", 4, 4, f_settabwinvar},
7939 {"setwinvar", 3, 3, f_setwinvar},
7940 {"shellescape", 1, 2, f_shellescape},
7941 {"simplify", 1, 1, f_simplify},
7943 {"sin", 1, 1, f_sin},
7944 {"sinh", 1, 1, f_sinh},
7946 {"sort", 1, 3, f_sort},
7947 {"soundfold", 1, 1, f_soundfold},
7948 {"spellbadword", 0, 1, f_spellbadword},
7949 {"spellsuggest", 1, 3, f_spellsuggest},
7950 {"split", 1, 3, f_split},
7952 {"sqrt", 1, 1, f_sqrt},
7953 {"str2float", 1, 1, f_str2float},
7955 {"str2nr", 1, 2, f_str2nr},
7956 {"strchars", 1, 1, f_strchars},
7957 {"strdisplaywidth", 1, 2, f_strdisplaywidth},
7958 #ifdef HAVE_STRFTIME
7959 {"strftime", 1, 2, f_strftime},
7961 {"stridx", 2, 3, f_stridx},
7962 {"string", 1, 1, f_string},
7963 {"strlen", 1, 1, f_strlen},
7964 {"strpart", 2, 3, f_strpart},
7965 {"strridx", 2, 3, f_strridx},
7966 {"strtrans", 1, 1, f_strtrans},
7967 {"strwidth", 1, 1, f_strwidth},
7968 {"submatch", 1, 1, f_submatch},
7969 {"substitute", 4, 4, f_substitute},
7970 {"synID", 3, 3, f_synID},
7971 {"synIDattr", 2, 3, f_synIDattr},
7972 {"synIDtrans", 1, 1, f_synIDtrans},
7973 {"synconcealed", 2, 2, f_synconcealed},
7974 {"synstack", 2, 2, f_synstack},
7975 {"system", 1, 2, f_system},
7976 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7977 {"tabpagenr", 0, 1, f_tabpagenr},
7978 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7979 {"tagfiles", 0, 0, f_tagfiles},
7980 {"taglist", 1, 1, f_taglist},
7982 {"tan", 1, 1, f_tan},
7983 {"tanh", 1, 1, f_tanh},
7985 {"tempname", 0, 0, f_tempname},
7986 {"test", 1, 1, f_test},
7987 {"tolower", 1, 1, f_tolower},
7988 {"toupper", 1, 1, f_toupper},
7991 {"trunc", 1, 1, f_trunc},
7993 {"type", 1, 1, f_type},
7994 {"undofile", 1, 1, f_undofile},
7995 {"undotree", 0, 0, f_undotree},
7996 {"values", 1, 1, f_values},
7997 {"virtcol", 1, 1, f_virtcol},
7998 {"visualmode", 0, 1, f_visualmode},
7999 {"winbufnr", 1, 1, f_winbufnr},
8000 {"wincol", 0, 0, f_wincol},
8001 {"winheight", 1, 1, f_winheight},
8002 {"winline", 0, 0, f_winline},
8003 {"winnr", 0, 1, f_winnr},
8004 {"winrestcmd", 0, 0, f_winrestcmd},
8005 {"winrestview", 1, 1, f_winrestview},
8006 {"winsaveview", 0, 0, f_winsaveview},
8007 {"winwidth", 1, 1, f_winwidth},
8008 {"writefile", 2, 3, f_writefile},
8009 {"xor", 2, 2, f_xor},
8012 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
8015 * Function given to ExpandGeneric() to obtain the list of internal
8016 * or user defined function names.
8019 get_function_name(xp, idx)
8023 static int intidx = -1;
8030 name = get_user_func_name(xp, idx);
8034 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
8036 STRCPY(IObuff, functions[intidx].f_name);
8037 STRCAT(IObuff, "(");
8038 if (functions[intidx].f_max_argc == 0)
8039 STRCAT(IObuff, ")");
8047 * Function given to ExpandGeneric() to obtain the list of internal or
8048 * user defined variable or function names.
8051 get_expr_name(xp, idx)
8055 static int intidx = -1;
8062 name = get_function_name(xp, idx);
8066 return get_user_var_name(xp, ++intidx);
8069 #endif /* FEAT_CMDL_COMPL */
8071 #if defined(EBCDIC) || defined(PROTO)
8073 * Compare struct fst by function name.
8076 compare_func_name(s1, s2)
8080 struct fst *p1 = (struct fst *)s1;
8081 struct fst *p2 = (struct fst *)s2;
8083 return STRCMP(p1->f_name, p2->f_name);
8087 * Sort the function table by function name.
8088 * The sorting of the table above is ASCII dependant.
8089 * On machines using EBCDIC we have to sort it.
8094 int funcCnt = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
8096 qsort(functions, (size_t)funcCnt, sizeof(struct fst), compare_func_name);
8102 * Find internal function in table above.
8103 * Return index, or -1 if not found
8106 find_internal_func(name)
8107 char_u *name; /* name of the function */
8110 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
8115 * Find the function name in the table. Binary search.
8117 while (first <= last)
8119 x = first + ((unsigned)(last - first) >> 1);
8120 cmp = STRCMP(name, functions[x].f_name);
8132 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
8133 * name it contains, otherwise return "name".
8136 deref_func_name(name, lenp)
8145 v = find_var(name, NULL);
8147 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
8149 if (v->di_tv.vval.v_string == NULL)
8152 return (char_u *)""; /* just in case */
8154 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
8155 return v->di_tv.vval.v_string;
8162 * Allocate a variable for the result of a function.
8163 * Return OK or FAIL.
8166 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
8168 char_u *name; /* name of the function */
8169 int len; /* length of "name" */
8171 char_u **arg; /* argument, pointing to the '(' */
8172 linenr_T firstline; /* first line of range */
8173 linenr_T lastline; /* last line of range */
8174 int *doesrange; /* return: function handled range */
8176 dict_T *selfdict; /* Dictionary for "self" */
8180 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
8181 int argcount = 0; /* number of arguments found */
8184 * Get the arguments.
8187 while (argcount < MAX_FUNC_ARGS)
8189 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
8190 if (*argp == ')' || *argp == ',' || *argp == NUL)
8192 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
8207 ret = call_func(name, len, rettv, argcount, argvars,
8208 firstline, lastline, doesrange, evaluate, selfdict);
8209 else if (!aborting())
8211 if (argcount == MAX_FUNC_ARGS)
8212 emsg_funcname(N_("E740: Too many arguments for function %s"), name);
8214 emsg_funcname(N_("E116: Invalid arguments for function %s"), name);
8217 while (--argcount >= 0)
8218 clear_tv(&argvars[argcount]);
8220 *arg = skipwhite(argp);
8226 * Call a function with its resolved parameters
8227 * Return OK when the function can't be called, FAIL otherwise.
8228 * Also returns OK when an error was encountered while executing the function.
8231 call_func(funcname, len, rettv, argcount, argvars, firstline, lastline,
8232 doesrange, evaluate, selfdict)
8233 char_u *funcname; /* name of the function */
8234 int len; /* length of "name" */
8235 typval_T *rettv; /* return value goes here */
8236 int argcount; /* number of "argvars" */
8237 typval_T *argvars; /* vars for arguments, must have "argcount"
8238 PLUS ONE elements! */
8239 linenr_T firstline; /* first line of range */
8240 linenr_T lastline; /* last line of range */
8241 int *doesrange; /* return: function handled range */
8243 dict_T *selfdict; /* Dictionary for "self" */
8246 #define ERROR_UNKNOWN 0
8247 #define ERROR_TOOMANY 1
8248 #define ERROR_TOOFEW 2
8249 #define ERROR_SCRIPT 3
8250 #define ERROR_DICT 4
8251 #define ERROR_NONE 5
8252 #define ERROR_OTHER 6
8253 int error = ERROR_NONE;
8257 #define FLEN_FIXED 40
8258 char_u fname_buf[FLEN_FIXED + 1];
8262 /* Make a copy of the name, if it comes from a funcref variable it could
8263 * be changed or deleted in the called function. */
8264 name = vim_strnsave(funcname, len);
8269 * In a script change <SID>name() and s:name() to K_SNR 123_name().
8270 * Change <SNR>123_name() to K_SNR 123_name().
8271 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
8273 llen = eval_fname_script(name);
8276 fname_buf[0] = K_SPECIAL;
8277 fname_buf[1] = KS_EXTRA;
8278 fname_buf[2] = (int)KE_SNR;
8280 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
8282 if (current_SID <= 0)
8283 error = ERROR_SCRIPT;
8286 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
8287 i = (int)STRLEN(fname_buf);
8290 if (i + STRLEN(name + llen) < FLEN_FIXED)
8292 STRCPY(fname_buf + i, name + llen);
8297 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
8299 error = ERROR_OTHER;
8302 mch_memmove(fname, fname_buf, (size_t)i);
8303 STRCPY(fname + i, name + llen);
8313 /* execute the function if no errors detected and executing */
8314 if (evaluate && error == ERROR_NONE)
8316 rettv->v_type = VAR_NUMBER; /* default rettv is number zero */
8317 rettv->vval.v_number = 0;
8318 error = ERROR_UNKNOWN;
8320 if (!builtin_function(fname))
8323 * User defined function.
8325 fp = find_func(fname);
8328 /* Trigger FuncUndefined event, may load the function. */
8330 && apply_autocmds(EVENT_FUNCUNDEFINED,
8331 fname, fname, TRUE, NULL)
8334 /* executed an autocommand, search for the function again */
8335 fp = find_func(fname);
8338 /* Try loading a package. */
8339 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
8341 /* loaded a package, search for the function again */
8342 fp = find_func(fname);
8347 if (fp->uf_flags & FC_RANGE)
8349 if (argcount < fp->uf_args.ga_len)
8350 error = ERROR_TOOFEW;
8351 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
8352 error = ERROR_TOOMANY;
8353 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
8358 * Call the user function.
8359 * Save and restore search patterns, script variables and
8362 save_search_patterns();
8365 call_user_func(fp, argcount, argvars, rettv,
8366 firstline, lastline,
8367 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
8368 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
8369 && fp->uf_refcount <= 0)
8370 /* Function was unreferenced while being used, free it
8374 restore_search_patterns();
8382 * Find the function name in the table, call its implementation.
8384 i = find_internal_func(fname);
8387 if (argcount < functions[i].f_min_argc)
8388 error = ERROR_TOOFEW;
8389 else if (argcount > functions[i].f_max_argc)
8390 error = ERROR_TOOMANY;
8393 argvars[argcount].v_type = VAR_UNKNOWN;
8394 functions[i].f_func(argvars, rettv);
8400 * The function call (or "FuncUndefined" autocommand sequence) might
8401 * have been aborted by an error, an interrupt, or an explicitly thrown
8402 * exception that has not been caught so far. This situation can be
8403 * tested for by calling aborting(). For an error in an internal
8404 * function or for the "E132" error in call_user_func(), however, the
8405 * throw point at which the "force_abort" flag (temporarily reset by
8406 * emsg()) is normally updated has not been reached yet. We need to
8407 * update that flag first to make aborting() reliable.
8409 update_force_abort();
8411 if (error == ERROR_NONE)
8415 * Report an error unless the argument evaluation or function call has been
8416 * cancelled due to an aborting error, an interrupt, or an exception.
8423 emsg_funcname(N_("E117: Unknown function: %s"), name);
8426 emsg_funcname(e_toomanyarg, name);
8429 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
8433 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
8437 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
8443 if (fname != name && fname != fname_buf)
8451 * Give an error message with a function name. Handle <SNR> things.
8452 * "ermsg" is to be passed without translation, use N_() instead of _().
8455 emsg_funcname(ermsg, name)
8461 if (*name == K_SPECIAL)
8462 p = concat_str((char_u *)"<SNR>", name + 3);
8471 * Return TRUE for a non-zero Number and a non-empty String.
8474 non_zero_arg(argvars)
8477 return ((argvars[0].v_type == VAR_NUMBER
8478 && argvars[0].vval.v_number != 0)
8479 || (argvars[0].v_type == VAR_STRING
8480 && argvars[0].vval.v_string != NULL
8481 && *argvars[0].vval.v_string != NUL));
8484 /*********************************************
8485 * Implementation of the built-in functions
8489 static int get_float_arg __ARGS((typval_T *argvars, float_T *f));
8492 * Get the float value of "argvars[0]" into "f".
8493 * Returns FAIL when the argument is not a Number or Float.
8496 get_float_arg(argvars, f)
8500 if (argvars[0].v_type == VAR_FLOAT)
8502 *f = argvars[0].vval.v_float;
8505 if (argvars[0].v_type == VAR_NUMBER)
8507 *f = (float_T)argvars[0].vval.v_number;
8510 EMSG(_("E808: Number or Float required"));
8515 * "abs(expr)" function
8518 f_abs(argvars, rettv)
8522 if (argvars[0].v_type == VAR_FLOAT)
8524 rettv->v_type = VAR_FLOAT;
8525 rettv->vval.v_float = fabs(argvars[0].vval.v_float);
8532 n = get_tv_number_chk(&argvars[0], &error);
8534 rettv->vval.v_number = -1;
8536 rettv->vval.v_number = n;
8538 rettv->vval.v_number = -n;
8546 f_acos(argvars, rettv)
8552 rettv->v_type = VAR_FLOAT;
8553 if (get_float_arg(argvars, &f) == OK)
8554 rettv->vval.v_float = acos(f);
8556 rettv->vval.v_float = 0.0;
8561 * "add(list, item)" function
8564 f_add(argvars, rettv)
8570 rettv->vval.v_number = 1; /* Default: Failed */
8571 if (argvars[0].v_type == VAR_LIST)
8573 if ((l = argvars[0].vval.v_list) != NULL
8574 && !tv_check_lock(l->lv_lock, (char_u *)_("add() argument"))
8575 && list_append_tv(l, &argvars[1]) == OK)
8576 copy_tv(&argvars[0], rettv);
8583 * "and(expr, expr)" function
8586 f_and(argvars, rettv)
8590 rettv->vval.v_number = get_tv_number_chk(&argvars[0], NULL)
8591 & get_tv_number_chk(&argvars[1], NULL);
8595 * "append(lnum, string/list)" function
8598 f_append(argvars, rettv)
8605 listitem_T *li = NULL;
8609 lnum = get_tv_lnum(argvars);
8611 && lnum <= curbuf->b_ml.ml_line_count
8612 && u_save(lnum, lnum + 1) == OK)
8614 if (argvars[1].v_type == VAR_LIST)
8616 l = argvars[1].vval.v_list;
8624 tv = &argvars[1]; /* append a string */
8625 else if (li == NULL)
8626 break; /* end of list */
8628 tv = &li->li_tv; /* append item from list */
8629 line = get_tv_string_chk(tv);
8630 if (line == NULL) /* type error */
8632 rettv->vval.v_number = 1; /* Failed */
8635 ml_append(lnum + added, line, (colnr_T)0, FALSE);
8642 appended_lines_mark(lnum, added);
8643 if (curwin->w_cursor.lnum > lnum)
8644 curwin->w_cursor.lnum += added;
8647 rettv->vval.v_number = 1; /* Failed */
8654 f_argc(argvars, rettv)
8655 typval_T *argvars UNUSED;
8658 rettv->vval.v_number = ARGCOUNT;
8662 * "argidx()" function
8665 f_argidx(argvars, rettv)
8666 typval_T *argvars UNUSED;
8669 rettv->vval.v_number = curwin->w_arg_idx;
8673 * "argv(nr)" function
8676 f_argv(argvars, rettv)
8682 if (argvars[0].v_type != VAR_UNKNOWN)
8684 idx = get_tv_number_chk(&argvars[0], NULL);
8685 if (idx >= 0 && idx < ARGCOUNT)
8686 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
8688 rettv->vval.v_string = NULL;
8689 rettv->v_type = VAR_STRING;
8691 else if (rettv_list_alloc(rettv) == OK)
8692 for (idx = 0; idx < ARGCOUNT; ++idx)
8693 list_append_string(rettv->vval.v_list,
8694 alist_name(&ARGLIST[idx]), -1);
8702 f_asin(argvars, rettv)
8708 rettv->v_type = VAR_FLOAT;
8709 if (get_float_arg(argvars, &f) == OK)
8710 rettv->vval.v_float = asin(f);
8712 rettv->vval.v_float = 0.0;
8719 f_atan(argvars, rettv)
8725 rettv->v_type = VAR_FLOAT;
8726 if (get_float_arg(argvars, &f) == OK)
8727 rettv->vval.v_float = atan(f);
8729 rettv->vval.v_float = 0.0;
8733 * "atan2()" function
8736 f_atan2(argvars, rettv)
8742 rettv->v_type = VAR_FLOAT;
8743 if (get_float_arg(argvars, &fx) == OK
8744 && get_float_arg(&argvars[1], &fy) == OK)
8745 rettv->vval.v_float = atan2(fx, fy);
8747 rettv->vval.v_float = 0.0;
8752 * "browse(save, title, initdir, default)" function
8755 f_browse(argvars, rettv)
8756 typval_T *argvars UNUSED;
8764 char_u buf[NUMBUFLEN];
8765 char_u buf2[NUMBUFLEN];
8768 save = get_tv_number_chk(&argvars[0], &error);
8769 title = get_tv_string_chk(&argvars[1]);
8770 initdir = get_tv_string_buf_chk(&argvars[2], buf);
8771 defname = get_tv_string_buf_chk(&argvars[3], buf2);
8773 if (error || title == NULL || initdir == NULL || defname == NULL)
8774 rettv->vval.v_string = NULL;
8776 rettv->vval.v_string =
8777 do_browse(save ? BROWSE_SAVE : 0,
8778 title, defname, NULL, initdir, NULL, curbuf);
8780 rettv->vval.v_string = NULL;
8782 rettv->v_type = VAR_STRING;
8786 * "browsedir(title, initdir)" function
8789 f_browsedir(argvars, rettv)
8790 typval_T *argvars UNUSED;
8796 char_u buf[NUMBUFLEN];
8798 title = get_tv_string_chk(&argvars[0]);
8799 initdir = get_tv_string_buf_chk(&argvars[1], buf);
8801 if (title == NULL || initdir == NULL)
8802 rettv->vval.v_string = NULL;
8804 rettv->vval.v_string = do_browse(BROWSE_DIR,
8805 title, NULL, NULL, initdir, NULL, curbuf);
8807 rettv->vval.v_string = NULL;
8809 rettv->v_type = VAR_STRING;
8812 static buf_T *find_buffer __ARGS((typval_T *avar));
8815 * Find a buffer by number or exact name.
8823 if (avar->v_type == VAR_NUMBER)
8824 buf = buflist_findnr((int)avar->vval.v_number);
8825 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
8827 buf = buflist_findname_exp(avar->vval.v_string);
8830 /* No full path name match, try a match with a URL or a "nofile"
8831 * buffer, these don't use the full path. */
8832 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8833 if (buf->b_fname != NULL
8834 && (path_with_url(buf->b_fname)
8835 #ifdef FEAT_QUICKFIX
8839 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
8847 * "bufexists(expr)" function
8850 f_bufexists(argvars, rettv)
8854 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
8858 * "buflisted(expr)" function
8861 f_buflisted(argvars, rettv)
8867 buf = find_buffer(&argvars[0]);
8868 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
8872 * "bufloaded(expr)" function
8875 f_bufloaded(argvars, rettv)
8881 buf = find_buffer(&argvars[0]);
8882 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
8885 static buf_T *get_buf_tv __ARGS((typval_T *tv));
8888 * Get buffer by number or pattern.
8894 char_u *name = tv->vval.v_string;
8899 if (tv->v_type == VAR_NUMBER)
8900 return buflist_findnr((int)tv->vval.v_number);
8901 if (tv->v_type != VAR_STRING)
8903 if (name == NULL || *name == NUL)
8905 if (name[0] == '$' && name[1] == NUL)
8908 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
8909 save_magic = p_magic;
8912 p_cpo = (char_u *)"";
8914 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8917 p_magic = save_magic;
8920 /* If not found, try expanding the name, like done for bufexists(). */
8922 buf = find_buffer(tv);
8928 * "bufname(expr)" function
8931 f_bufname(argvars, rettv)
8937 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8939 buf = get_buf_tv(&argvars[0]);
8940 rettv->v_type = VAR_STRING;
8941 if (buf != NULL && buf->b_fname != NULL)
8942 rettv->vval.v_string = vim_strsave(buf->b_fname);
8944 rettv->vval.v_string = NULL;
8949 * "bufnr(expr)" function
8952 f_bufnr(argvars, rettv)
8960 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8962 buf = get_buf_tv(&argvars[0]);
8965 /* If the buffer isn't found and the second argument is not zero create a
8968 && argvars[1].v_type != VAR_UNKNOWN
8969 && get_tv_number_chk(&argvars[1], &error) != 0
8971 && (name = get_tv_string_chk(&argvars[0])) != NULL
8973 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8976 rettv->vval.v_number = buf->b_fnum;
8978 rettv->vval.v_number = -1;
8982 * "bufwinnr(nr)" function
8985 f_bufwinnr(argvars, rettv)
8995 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8997 buf = get_buf_tv(&argvars[0]);
8999 for (wp = firstwin; wp; wp = wp->w_next)
9002 if (wp->w_buffer == buf)
9005 rettv->vval.v_number = (wp != NULL ? winnr : -1);
9007 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
9013 * "byte2line(byte)" function
9016 f_byte2line(argvars, rettv)
9017 typval_T *argvars UNUSED;
9020 #ifndef FEAT_BYTEOFF
9021 rettv->vval.v_number = -1;
9025 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
9027 rettv->vval.v_number = -1;
9029 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
9030 (linenr_T)0, &boff);
9035 * "byteidx()" function
9038 f_byteidx(argvars, rettv)
9048 str = get_tv_string_chk(&argvars[0]);
9049 idx = get_tv_number_chk(&argvars[1], NULL);
9050 rettv->vval.v_number = -1;
9051 if (str == NULL || idx < 0)
9056 for ( ; idx > 0; idx--)
9058 if (*t == NUL) /* EOL reached */
9060 t += (*mb_ptr2len)(t);
9062 rettv->vval.v_number = (varnumber_T)(t - str);
9064 if ((size_t)idx <= STRLEN(str))
9065 rettv->vval.v_number = idx;
9070 * "call(func, arglist)" function
9073 f_call(argvars, rettv)
9078 typval_T argv[MAX_FUNC_ARGS + 1];
9082 dict_T *selfdict = NULL;
9084 if (argvars[1].v_type != VAR_LIST)
9089 if (argvars[1].vval.v_list == NULL)
9092 if (argvars[0].v_type == VAR_FUNC)
9093 func = argvars[0].vval.v_string;
9095 func = get_tv_string(&argvars[0]);
9097 return; /* type error or empty name */
9099 if (argvars[2].v_type != VAR_UNKNOWN)
9101 if (argvars[2].v_type != VAR_DICT)
9106 selfdict = argvars[2].vval.v_dict;
9109 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
9110 item = item->li_next)
9112 if (argc == MAX_FUNC_ARGS)
9114 EMSG(_("E699: Too many arguments"));
9117 /* Make a copy of each argument. This is needed to be able to set
9118 * v_lock to VAR_FIXED in the copy without changing the original list.
9120 copy_tv(&item->li_tv, &argv[argc++]);
9124 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
9125 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
9126 &dummy, TRUE, selfdict);
9128 /* Free the arguments. */
9130 clear_tv(&argv[--argc]);
9135 * "ceil({float})" function
9138 f_ceil(argvars, rettv)
9144 rettv->v_type = VAR_FLOAT;
9145 if (get_float_arg(argvars, &f) == OK)
9146 rettv->vval.v_float = ceil(f);
9148 rettv->vval.v_float = 0.0;
9153 * "changenr()" function
9156 f_changenr(argvars, rettv)
9157 typval_T *argvars UNUSED;
9160 rettv->vval.v_number = curbuf->b_u_seq_cur;
9164 * "char2nr(string)" function
9167 f_char2nr(argvars, rettv)
9173 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
9176 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
9180 * "cindent(lnum)" function
9183 f_cindent(argvars, rettv)
9191 pos = curwin->w_cursor;
9192 lnum = get_tv_lnum(argvars);
9193 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9195 curwin->w_cursor.lnum = lnum;
9196 rettv->vval.v_number = get_c_indent();
9197 curwin->w_cursor = pos;
9201 rettv->vval.v_number = -1;
9205 * "clearmatches()" function
9208 f_clearmatches(argvars, rettv)
9209 typval_T *argvars UNUSED;
9210 typval_T *rettv UNUSED;
9212 #ifdef FEAT_SEARCH_EXTRA
9213 clear_matches(curwin);
9218 * "col(string)" function
9221 f_col(argvars, rettv)
9227 int fnum = curbuf->b_fnum;
9229 fp = var2fpos(&argvars[0], FALSE, &fnum);
9230 if (fp != NULL && fnum == curbuf->b_fnum)
9232 if (fp->col == MAXCOL)
9234 /* '> can be MAXCOL, get the length of the line then */
9235 if (fp->lnum <= curbuf->b_ml.ml_line_count)
9236 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
9243 #ifdef FEAT_VIRTUALEDIT
9244 /* col(".") when the cursor is on the NUL at the end of the line
9245 * because of "coladd" can be seen as an extra column. */
9246 if (virtual_active() && fp == &curwin->w_cursor)
9248 char_u *p = ml_get_cursor();
9250 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
9251 curwin->w_virtcol - curwin->w_cursor.coladd))
9256 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
9259 if (*p != NUL && p[1] == NUL)
9267 rettv->vval.v_number = col;
9270 #if defined(FEAT_INS_EXPAND)
9272 * "complete()" function
9275 f_complete(argvars, rettv)
9277 typval_T *rettv UNUSED;
9281 if ((State & INSERT) == 0)
9283 EMSG(_("E785: complete() can only be used in Insert mode"));
9287 /* Check for undo allowed here, because if something was already inserted
9288 * the line was already saved for undo and this check isn't done. */
9289 if (!undo_allowed())
9292 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
9298 startcol = get_tv_number_chk(&argvars[0], NULL);
9302 set_completion(startcol - 1, argvars[1].vval.v_list);
9306 * "complete_add()" function
9309 f_complete_add(argvars, rettv)
9313 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
9317 * "complete_check()" function
9320 f_complete_check(argvars, rettv)
9321 typval_T *argvars UNUSED;
9324 int saved = RedrawingDisabled;
9326 RedrawingDisabled = 0;
9327 ins_compl_check_keys(0);
9328 rettv->vval.v_number = compl_interrupted;
9329 RedrawingDisabled = saved;
9334 * "confirm(message, buttons[, default [, type]])" function
9337 f_confirm(argvars, rettv)
9338 typval_T *argvars UNUSED;
9339 typval_T *rettv UNUSED;
9341 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
9343 char_u *buttons = NULL;
9344 char_u buf[NUMBUFLEN];
9345 char_u buf2[NUMBUFLEN];
9347 int type = VIM_GENERIC;
9351 message = get_tv_string_chk(&argvars[0]);
9352 if (message == NULL)
9354 if (argvars[1].v_type != VAR_UNKNOWN)
9356 buttons = get_tv_string_buf_chk(&argvars[1], buf);
9357 if (buttons == NULL)
9359 if (argvars[2].v_type != VAR_UNKNOWN)
9361 def = get_tv_number_chk(&argvars[2], &error);
9362 if (argvars[3].v_type != VAR_UNKNOWN)
9364 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
9365 if (typestr == NULL)
9369 switch (TOUPPER_ASC(*typestr))
9371 case 'E': type = VIM_ERROR; break;
9372 case 'Q': type = VIM_QUESTION; break;
9373 case 'I': type = VIM_INFO; break;
9374 case 'W': type = VIM_WARNING; break;
9375 case 'G': type = VIM_GENERIC; break;
9382 if (buttons == NULL || *buttons == NUL)
9383 buttons = (char_u *)_("&Ok");
9386 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
9395 f_copy(argvars, rettv)
9399 item_copy(&argvars[0], rettv, FALSE, 0);
9407 f_cos(argvars, rettv)
9413 rettv->v_type = VAR_FLOAT;
9414 if (get_float_arg(argvars, &f) == OK)
9415 rettv->vval.v_float = cos(f);
9417 rettv->vval.v_float = 0.0;
9424 f_cosh(argvars, rettv)
9430 rettv->v_type = VAR_FLOAT;
9431 if (get_float_arg(argvars, &f) == OK)
9432 rettv->vval.v_float = cosh(f);
9434 rettv->vval.v_float = 0.0;
9439 * "count()" function
9442 f_count(argvars, rettv)
9449 if (argvars[0].v_type == VAR_LIST)
9455 if ((l = argvars[0].vval.v_list) != NULL)
9458 if (argvars[2].v_type != VAR_UNKNOWN)
9462 ic = get_tv_number_chk(&argvars[2], &error);
9463 if (argvars[3].v_type != VAR_UNKNOWN)
9465 idx = get_tv_number_chk(&argvars[3], &error);
9468 li = list_find(l, idx);
9470 EMSGN(_(e_listidx), idx);
9477 for ( ; li != NULL; li = li->li_next)
9478 if (tv_equal(&li->li_tv, &argvars[1], ic, FALSE))
9482 else if (argvars[0].v_type == VAR_DICT)
9488 if ((d = argvars[0].vval.v_dict) != NULL)
9492 if (argvars[2].v_type != VAR_UNKNOWN)
9494 ic = get_tv_number_chk(&argvars[2], &error);
9495 if (argvars[3].v_type != VAR_UNKNOWN)
9499 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
9500 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
9502 if (!HASHITEM_EMPTY(hi))
9505 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic, FALSE))
9512 EMSG2(_(e_listdictarg), "count()");
9513 rettv->vval.v_number = n;
9517 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
9519 * Checks the existence of a cscope connection.
9522 f_cscope_connection(argvars, rettv)
9523 typval_T *argvars UNUSED;
9524 typval_T *rettv UNUSED;
9528 char_u *dbpath = NULL;
9529 char_u *prepend = NULL;
9530 char_u buf[NUMBUFLEN];
9532 if (argvars[0].v_type != VAR_UNKNOWN
9533 && argvars[1].v_type != VAR_UNKNOWN)
9535 num = (int)get_tv_number(&argvars[0]);
9536 dbpath = get_tv_string(&argvars[1]);
9537 if (argvars[2].v_type != VAR_UNKNOWN)
9538 prepend = get_tv_string_buf(&argvars[2], buf);
9541 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
9546 * "cursor(lnum, col)" function
9548 * Moves the cursor to the specified line and column.
9549 * Returns 0 when the position could be set, -1 otherwise.
9552 f_cursor(argvars, rettv)
9557 #ifdef FEAT_VIRTUALEDIT
9561 rettv->vval.v_number = -1;
9562 if (argvars[1].v_type == VAR_UNKNOWN)
9566 if (list2fpos(argvars, &pos, NULL) == FAIL)
9570 #ifdef FEAT_VIRTUALEDIT
9571 coladd = pos.coladd;
9576 line = get_tv_lnum(argvars);
9577 col = get_tv_number_chk(&argvars[1], NULL);
9578 #ifdef FEAT_VIRTUALEDIT
9579 if (argvars[2].v_type != VAR_UNKNOWN)
9580 coladd = get_tv_number_chk(&argvars[2], NULL);
9583 if (line < 0 || col < 0
9584 #ifdef FEAT_VIRTUALEDIT
9588 return; /* type error; errmsg already given */
9590 curwin->w_cursor.lnum = line;
9592 curwin->w_cursor.col = col - 1;
9593 #ifdef FEAT_VIRTUALEDIT
9594 curwin->w_cursor.coladd = coladd;
9597 /* Make sure the cursor is in a valid position. */
9600 /* Correct cursor for multi-byte character. */
9605 curwin->w_set_curswant = TRUE;
9606 rettv->vval.v_number = 0;
9610 * "deepcopy()" function
9613 f_deepcopy(argvars, rettv)
9619 if (argvars[1].v_type != VAR_UNKNOWN)
9620 noref = get_tv_number_chk(&argvars[1], NULL);
9621 if (noref < 0 || noref > 1)
9625 current_copyID += COPYID_INC;
9626 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? current_copyID : 0);
9631 * "delete()" function
9634 f_delete(argvars, rettv)
9638 if (check_restricted() || check_secure())
9639 rettv->vval.v_number = -1;
9641 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
9645 * "did_filetype()" function
9648 f_did_filetype(argvars, rettv)
9649 typval_T *argvars UNUSED;
9650 typval_T *rettv UNUSED;
9653 rettv->vval.v_number = did_filetype;
9658 * "diff_filler()" function
9661 f_diff_filler(argvars, rettv)
9662 typval_T *argvars UNUSED;
9663 typval_T *rettv UNUSED;
9666 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
9671 * "diff_hlID()" function
9674 f_diff_hlID(argvars, rettv)
9675 typval_T *argvars UNUSED;
9676 typval_T *rettv UNUSED;
9679 linenr_T lnum = get_tv_lnum(argvars);
9680 static linenr_T prev_lnum = 0;
9681 static int changedtick = 0;
9682 static int fnum = 0;
9683 static int change_start = 0;
9684 static int change_end = 0;
9685 static hlf_T hlID = (hlf_T)0;
9689 if (lnum < 0) /* ignore type error in {lnum} arg */
9691 if (lnum != prev_lnum
9692 || changedtick != curbuf->b_changedtick
9693 || fnum != curbuf->b_fnum)
9695 /* New line, buffer, change: need to get the values. */
9696 filler_lines = diff_check(curwin, lnum);
9697 if (filler_lines < 0)
9699 if (filler_lines == -1)
9701 change_start = MAXCOL;
9703 if (diff_find_change(curwin, lnum, &change_start, &change_end))
9704 hlID = HLF_ADD; /* added line */
9706 hlID = HLF_CHD; /* changed line */
9709 hlID = HLF_ADD; /* added line */
9714 changedtick = curbuf->b_changedtick;
9715 fnum = curbuf->b_fnum;
9718 if (hlID == HLF_CHD || hlID == HLF_TXD)
9720 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
9721 if (col >= change_start && col <= change_end)
9722 hlID = HLF_TXD; /* changed text */
9724 hlID = HLF_CHD; /* changed line */
9726 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
9731 * "empty({expr})" function
9734 f_empty(argvars, rettv)
9740 switch (argvars[0].v_type)
9744 n = argvars[0].vval.v_string == NULL
9745 || *argvars[0].vval.v_string == NUL;
9748 n = argvars[0].vval.v_number == 0;
9752 n = argvars[0].vval.v_float == 0.0;
9756 n = argvars[0].vval.v_list == NULL
9757 || argvars[0].vval.v_list->lv_first == NULL;
9760 n = argvars[0].vval.v_dict == NULL
9761 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
9764 EMSG2(_(e_intern2), "f_empty()");
9768 rettv->vval.v_number = n;
9772 * "escape({string}, {chars})" function
9775 f_escape(argvars, rettv)
9779 char_u buf[NUMBUFLEN];
9781 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
9782 get_tv_string_buf(&argvars[1], buf));
9783 rettv->v_type = VAR_STRING;
9790 f_eval(argvars, rettv)
9796 s = get_tv_string_chk(&argvars[0]);
9800 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
9802 rettv->v_type = VAR_NUMBER;
9803 rettv->vval.v_number = 0;
9806 EMSG(_(e_trailing));
9810 * "eventhandler()" function
9813 f_eventhandler(argvars, rettv)
9814 typval_T *argvars UNUSED;
9817 rettv->vval.v_number = vgetc_busy;
9821 * "executable()" function
9824 f_executable(argvars, rettv)
9828 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
9832 * "exists()" function
9835 f_exists(argvars, rettv)
9846 p = get_tv_string(&argvars[0]);
9847 if (*p == '$') /* environment variable */
9849 /* first try "normal" environment variables (fast) */
9850 if (mch_getenv(p + 1) != NULL)
9854 /* try expanding things like $VIM and ${HOME} */
9855 p = expand_env_save(p);
9856 if (p != NULL && *p != '$')
9861 else if (*p == '&' || *p == '+') /* option */
9863 n = (get_option_tv(&p, NULL, TRUE) == OK);
9864 if (*skipwhite(p) != NUL)
9865 n = FALSE; /* trailing garbage */
9867 else if (*p == '*') /* internal or user defined function */
9869 n = function_exists(p + 1);
9873 n = cmd_exists(p + 1);
9879 n = autocmd_supported(p + 2);
9881 n = au_exists(p + 1);
9884 else /* internal variable */
9889 /* get_name_len() takes care of expanding curly braces */
9891 len = get_name_len(&p, &tofree, TRUE, FALSE);
9896 n = (get_var_tv(name, len, &tv, FALSE) == OK);
9899 /* handle d.key, l[idx], f(expr) */
9900 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
9911 rettv->vval.v_number = n;
9913 no_autoload = FALSE;
9921 f_exp(argvars, rettv)
9927 rettv->v_type = VAR_FLOAT;
9928 if (get_float_arg(argvars, &f) == OK)
9929 rettv->vval.v_float = exp(f);
9931 rettv->vval.v_float = 0.0;
9936 * "expand()" function
9939 f_expand(argvars, rettv)
9946 int options = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
9950 rettv->v_type = VAR_STRING;
9951 s = get_tv_string(&argvars[0]);
9952 if (*s == '%' || *s == '#' || *s == '<')
9955 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
9960 /* When the optional second argument is non-zero, don't remove matches
9961 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
9962 if (argvars[1].v_type != VAR_UNKNOWN
9963 && get_tv_number_chk(&argvars[1], &error))
9964 options |= WILD_KEEP_ALL;
9968 xpc.xp_context = EXPAND_FILES;
9970 options += WILD_ICASE;
9971 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, options, WILD_ALL);
9974 rettv->vval.v_string = NULL;
9979 * "extend(list, list [, idx])" function
9980 * "extend(dict, dict [, action])" function
9983 f_extend(argvars, rettv)
9987 char *arg_errmsg = N_("extend() argument");
9989 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9996 l1 = argvars[0].vval.v_list;
9997 l2 = argvars[1].vval.v_list;
9998 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)_(arg_errmsg))
10001 if (argvars[2].v_type != VAR_UNKNOWN)
10003 before = get_tv_number_chk(&argvars[2], &error);
10005 return; /* type error; errmsg already given */
10007 if (before == l1->lv_len)
10011 item = list_find(l1, before);
10014 EMSGN(_(e_listidx), before);
10021 list_extend(l1, l2, item);
10023 copy_tv(&argvars[0], rettv);
10026 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
10035 d1 = argvars[0].vval.v_dict;
10036 d2 = argvars[1].vval.v_dict;
10037 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)_(arg_errmsg))
10040 /* Check the third argument. */
10041 if (argvars[2].v_type != VAR_UNKNOWN)
10043 static char *(av[]) = {"keep", "force", "error"};
10045 action = get_tv_string_chk(&argvars[2]);
10046 if (action == NULL)
10047 return; /* type error; errmsg already given */
10048 for (i = 0; i < 3; ++i)
10049 if (STRCMP(action, av[i]) == 0)
10053 EMSG2(_(e_invarg2), action);
10058 action = (char_u *)"force";
10060 /* Go over all entries in the second dict and add them to the
10062 todo = (int)d2->dv_hashtab.ht_used;
10063 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
10065 if (!HASHITEM_EMPTY(hi2))
10068 di1 = dict_find(d1, hi2->hi_key, -1);
10071 di1 = dictitem_copy(HI2DI(hi2));
10072 if (di1 != NULL && dict_add(d1, di1) == FAIL)
10073 dictitem_free(di1);
10075 else if (*action == 'e')
10077 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
10080 else if (*action == 'f')
10082 clear_tv(&di1->di_tv);
10083 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
10088 copy_tv(&argvars[0], rettv);
10092 EMSG2(_(e_listdictarg), "extend()");
10096 * "feedkeys()" function
10099 f_feedkeys(argvars, rettv)
10101 typval_T *rettv UNUSED;
10104 char_u *keys, *flags;
10105 char_u nbuf[NUMBUFLEN];
10109 /* This is not allowed in the sandbox. If the commands would still be
10110 * executed in the sandbox it would be OK, but it probably happens later,
10111 * when "sandbox" is no longer set. */
10112 if (check_secure())
10115 keys = get_tv_string(&argvars[0]);
10118 if (argvars[1].v_type != VAR_UNKNOWN)
10120 flags = get_tv_string_buf(&argvars[1], nbuf);
10121 for ( ; *flags != NUL; ++flags)
10125 case 'n': remap = FALSE; break;
10126 case 'm': remap = TRUE; break;
10127 case 't': typed = TRUE; break;
10132 /* Need to escape K_SPECIAL and CSI before putting the string in the
10133 * typeahead buffer. */
10134 keys_esc = vim_strsave_escape_csi(keys);
10135 if (keys_esc != NULL)
10137 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
10138 typebuf.tb_len, !typed, FALSE);
10139 vim_free(keys_esc);
10141 typebuf_was_filled = TRUE;
10147 * "filereadable()" function
10150 f_filereadable(argvars, rettv)
10159 # define O_NONBLOCK 0
10161 p = get_tv_string(&argvars[0]);
10162 if (*p && !mch_isdir(p) && (fd = mch_open((char *)p,
10163 O_RDONLY | O_NONBLOCK, 0)) >= 0)
10171 rettv->vval.v_number = n;
10175 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
10176 * rights to write into.
10179 f_filewritable(argvars, rettv)
10183 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
10186 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
10189 findfilendir(argvars, rettv, find_what)
10194 #ifdef FEAT_SEARCHPATH
10196 char_u *fresult = NULL;
10197 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
10199 char_u pathbuf[NUMBUFLEN];
10205 rettv->vval.v_string = NULL;
10206 rettv->v_type = VAR_STRING;
10208 #ifdef FEAT_SEARCHPATH
10209 fname = get_tv_string(&argvars[0]);
10211 if (argvars[1].v_type != VAR_UNKNOWN)
10213 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
10221 if (argvars[2].v_type != VAR_UNKNOWN)
10222 count = get_tv_number_chk(&argvars[2], &error);
10226 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
10229 if (*fname != NUL && !error)
10233 if (rettv->v_type == VAR_STRING)
10235 fresult = find_file_in_path_option(first ? fname : NULL,
10236 first ? (int)STRLEN(fname) : 0,
10240 find_what == FINDFILE_DIR
10241 ? (char_u *)"" : curbuf->b_p_sua);
10244 if (fresult != NULL && rettv->v_type == VAR_LIST)
10245 list_append_string(rettv->vval.v_list, fresult, -1);
10247 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
10250 if (rettv->v_type == VAR_STRING)
10251 rettv->vval.v_string = fresult;
10255 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
10256 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
10259 * Implementation of map() and filter().
10262 filter_map(argvars, rettv, map)
10267 char_u buf[NUMBUFLEN];
10269 listitem_T *li, *nli;
10279 char_u *ermsg = (char_u *)(map ? "map()" : "filter()");
10280 char *arg_errmsg = (map ? N_("map() argument")
10281 : N_("filter() argument"));
10285 if (argvars[0].v_type == VAR_LIST)
10287 if ((l = argvars[0].vval.v_list) == NULL
10288 || tv_check_lock(l->lv_lock, (char_u *)_(arg_errmsg)))
10291 else if (argvars[0].v_type == VAR_DICT)
10293 if ((d = argvars[0].vval.v_dict) == NULL
10294 || tv_check_lock(d->dv_lock, (char_u *)_(arg_errmsg)))
10299 EMSG2(_(e_listdictarg), ermsg);
10303 expr = get_tv_string_buf_chk(&argvars[1], buf);
10304 /* On type errors, the preceding call has already displayed an error
10305 * message. Avoid a misleading error message for an empty string that
10306 * was not passed as argument. */
10309 prepare_vimvar(VV_VAL, &save_val);
10310 expr = skipwhite(expr);
10312 /* We reset "did_emsg" to be able to detect whether an error
10313 * occurred during evaluation of the expression. */
10314 save_did_emsg = did_emsg;
10317 prepare_vimvar(VV_KEY, &save_key);
10318 if (argvars[0].v_type == VAR_DICT)
10320 vimvars[VV_KEY].vv_type = VAR_STRING;
10322 ht = &d->dv_hashtab;
10324 todo = (int)ht->ht_used;
10325 for (hi = ht->ht_array; todo > 0; ++hi)
10327 if (!HASHITEM_EMPTY(hi))
10331 if (tv_check_lock(di->di_tv.v_lock,
10332 (char_u *)_(arg_errmsg)))
10334 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
10335 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
10339 dictitem_remove(d, di);
10340 clear_tv(&vimvars[VV_KEY].vv_tv);
10347 vimvars[VV_KEY].vv_type = VAR_NUMBER;
10349 for (li = l->lv_first; li != NULL; li = nli)
10351 if (tv_check_lock(li->li_tv.v_lock, (char_u *)_(arg_errmsg)))
10354 vimvars[VV_KEY].vv_nr = idx;
10355 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
10359 listitem_remove(l, li);
10364 restore_vimvar(VV_KEY, &save_key);
10365 restore_vimvar(VV_VAL, &save_val);
10367 did_emsg |= save_did_emsg;
10370 copy_tv(&argvars[0], rettv);
10374 filter_map_one(tv, expr, map, remp)
10384 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
10386 if (eval1(&s, &rettv, TRUE) == FAIL)
10388 if (*s != NUL) /* check for trailing chars after expr */
10390 EMSG2(_(e_invexpr2), s);
10395 /* map(): replace the list item value */
10404 /* filter(): when expr is zero remove the item */
10405 *remp = (get_tv_number_chk(&rettv, &error) == 0);
10407 /* On type error, nothing has been removed; return FAIL to stop the
10408 * loop. The error message was given by get_tv_number_chk(). */
10414 clear_tv(&vimvars[VV_VAL].vv_tv);
10419 * "filter()" function
10422 f_filter(argvars, rettv)
10426 filter_map(argvars, rettv, FALSE);
10430 * "finddir({fname}[, {path}[, {count}]])" function
10433 f_finddir(argvars, rettv)
10437 findfilendir(argvars, rettv, FINDFILE_DIR);
10441 * "findfile({fname}[, {path}[, {count}]])" function
10444 f_findfile(argvars, rettv)
10448 findfilendir(argvars, rettv, FINDFILE_FILE);
10453 * "float2nr({float})" function
10456 f_float2nr(argvars, rettv)
10462 if (get_float_arg(argvars, &f) == OK)
10464 if (f < -0x7fffffff)
10465 rettv->vval.v_number = -0x7fffffff;
10466 else if (f > 0x7fffffff)
10467 rettv->vval.v_number = 0x7fffffff;
10469 rettv->vval.v_number = (varnumber_T)f;
10474 * "floor({float})" function
10477 f_floor(argvars, rettv)
10483 rettv->v_type = VAR_FLOAT;
10484 if (get_float_arg(argvars, &f) == OK)
10485 rettv->vval.v_float = floor(f);
10487 rettv->vval.v_float = 0.0;
10491 * "fmod()" function
10494 f_fmod(argvars, rettv)
10500 rettv->v_type = VAR_FLOAT;
10501 if (get_float_arg(argvars, &fx) == OK
10502 && get_float_arg(&argvars[1], &fy) == OK)
10503 rettv->vval.v_float = fmod(fx, fy);
10505 rettv->vval.v_float = 0.0;
10510 * "fnameescape({string})" function
10513 f_fnameescape(argvars, rettv)
10517 rettv->vval.v_string = vim_strsave_fnameescape(
10518 get_tv_string(&argvars[0]), FALSE);
10519 rettv->v_type = VAR_STRING;
10523 * "fnamemodify({fname}, {mods})" function
10526 f_fnamemodify(argvars, rettv)
10534 char_u *fbuf = NULL;
10535 char_u buf[NUMBUFLEN];
10537 fname = get_tv_string_chk(&argvars[0]);
10538 mods = get_tv_string_buf_chk(&argvars[1], buf);
10539 if (fname == NULL || mods == NULL)
10543 len = (int)STRLEN(fname);
10544 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
10547 rettv->v_type = VAR_STRING;
10549 rettv->vval.v_string = NULL;
10551 rettv->vval.v_string = vim_strnsave(fname, len);
10555 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
10558 * "foldclosed()" function
10561 foldclosed_both(argvars, rettv, end)
10566 #ifdef FEAT_FOLDING
10568 linenr_T first, last;
10570 lnum = get_tv_lnum(argvars);
10571 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10573 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
10576 rettv->vval.v_number = (varnumber_T)last;
10578 rettv->vval.v_number = (varnumber_T)first;
10583 rettv->vval.v_number = -1;
10587 * "foldclosed()" function
10590 f_foldclosed(argvars, rettv)
10594 foldclosed_both(argvars, rettv, FALSE);
10598 * "foldclosedend()" function
10601 f_foldclosedend(argvars, rettv)
10605 foldclosed_both(argvars, rettv, TRUE);
10609 * "foldlevel()" function
10612 f_foldlevel(argvars, rettv)
10616 #ifdef FEAT_FOLDING
10619 lnum = get_tv_lnum(argvars);
10620 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10621 rettv->vval.v_number = foldLevel(lnum);
10626 * "foldtext()" function
10629 f_foldtext(argvars, rettv)
10630 typval_T *argvars UNUSED;
10633 #ifdef FEAT_FOLDING
10641 rettv->v_type = VAR_STRING;
10642 rettv->vval.v_string = NULL;
10643 #ifdef FEAT_FOLDING
10644 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
10645 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
10646 <= curbuf->b_ml.ml_line_count
10647 && vimvars[VV_FOLDDASHES].vv_str != NULL)
10649 /* Find first non-empty line in the fold. */
10650 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
10651 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10653 if (!linewhite(lnum))
10658 /* Find interesting text in this line. */
10659 s = skipwhite(ml_get(lnum));
10660 /* skip C comment-start */
10661 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
10663 s = skipwhite(s + 2);
10664 if (*skipwhite(s) == NUL
10665 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10667 s = skipwhite(ml_get(lnum + 1));
10669 s = skipwhite(s + 1);
10672 txt = _("+-%s%3ld lines: ");
10673 r = alloc((unsigned)(STRLEN(txt)
10674 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
10675 + 20 /* for %3ld */
10676 + STRLEN(s))); /* concatenated */
10679 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
10680 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
10681 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
10682 len = (int)STRLEN(r);
10684 /* remove 'foldmarker' and 'commentstring' */
10685 foldtext_cleanup(r + len);
10686 rettv->vval.v_string = r;
10693 * "foldtextresult(lnum)" function
10696 f_foldtextresult(argvars, rettv)
10697 typval_T *argvars UNUSED;
10700 #ifdef FEAT_FOLDING
10704 foldinfo_T foldinfo;
10708 rettv->v_type = VAR_STRING;
10709 rettv->vval.v_string = NULL;
10710 #ifdef FEAT_FOLDING
10711 lnum = get_tv_lnum(argvars);
10712 /* treat illegal types and illegal string values for {lnum} the same */
10715 fold_count = foldedCount(curwin, lnum, &foldinfo);
10716 if (fold_count > 0)
10718 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
10721 text = vim_strsave(text);
10722 rettv->vval.v_string = text;
10728 * "foreground()" function
10731 f_foreground(argvars, rettv)
10732 typval_T *argvars UNUSED;
10733 typval_T *rettv UNUSED;
10737 gui_mch_set_foreground();
10740 win32_set_foreground();
10746 * "function()" function
10749 f_function(argvars, rettv)
10755 s = get_tv_string(&argvars[0]);
10756 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
10757 EMSG2(_(e_invarg2), s);
10758 /* Don't check an autoload name for existence here. */
10759 else if (vim_strchr(s, AUTOLOAD_CHAR) == NULL && !function_exists(s))
10760 EMSG2(_("E700: Unknown function: %s"), s);
10763 rettv->vval.v_string = vim_strsave(s);
10764 rettv->v_type = VAR_FUNC;
10769 * "garbagecollect()" function
10772 f_garbagecollect(argvars, rettv)
10774 typval_T *rettv UNUSED;
10776 /* This is postponed until we are back at the toplevel, because we may be
10777 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
10778 want_garbage_collect = TRUE;
10780 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
10781 garbage_collect_at_exit = TRUE;
10788 f_get(argvars, rettv)
10796 typval_T *tv = NULL;
10798 if (argvars[0].v_type == VAR_LIST)
10800 if ((l = argvars[0].vval.v_list) != NULL)
10804 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
10805 if (!error && li != NULL)
10809 else if (argvars[0].v_type == VAR_DICT)
10811 if ((d = argvars[0].vval.v_dict) != NULL)
10813 di = dict_find(d, get_tv_string(&argvars[1]), -1);
10819 EMSG2(_(e_listdictarg), "get()");
10823 if (argvars[2].v_type != VAR_UNKNOWN)
10824 copy_tv(&argvars[2], rettv);
10827 copy_tv(tv, rettv);
10830 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
10833 * Get line or list of lines from buffer "buf" into "rettv".
10834 * Return a range (from start to end) of lines in rettv from the specified
10836 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
10839 get_buffer_lines(buf, start, end, retlist, rettv)
10848 if (retlist && rettv_list_alloc(rettv) == FAIL)
10851 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
10856 if (start >= 1 && start <= buf->b_ml.ml_line_count)
10857 p = ml_get_buf(buf, start, FALSE);
10861 rettv->v_type = VAR_STRING;
10862 rettv->vval.v_string = vim_strsave(p);
10871 if (end > buf->b_ml.ml_line_count)
10872 end = buf->b_ml.ml_line_count;
10873 while (start <= end)
10874 if (list_append_string(rettv->vval.v_list,
10875 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
10881 * "getbufline()" function
10884 f_getbufline(argvars, rettv)
10892 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10894 buf = get_buf_tv(&argvars[0]);
10897 lnum = get_tv_lnum_buf(&argvars[1], buf);
10898 if (argvars[2].v_type == VAR_UNKNOWN)
10901 end = get_tv_lnum_buf(&argvars[2], buf);
10903 get_buffer_lines(buf, lnum, end, TRUE, rettv);
10907 * "getbufvar()" function
10910 f_getbufvar(argvars, rettv)
10915 buf_T *save_curbuf;
10919 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10920 varname = get_tv_string_chk(&argvars[1]);
10922 buf = get_buf_tv(&argvars[0]);
10924 rettv->v_type = VAR_STRING;
10925 rettv->vval.v_string = NULL;
10927 if (buf != NULL && varname != NULL)
10929 /* set curbuf to be our buf, temporarily */
10930 save_curbuf = curbuf;
10933 if (*varname == '&') /* buffer-local-option */
10934 get_option_tv(&varname, rettv, TRUE);
10935 else if (STRCMP(varname, "changedtick") == 0)
10937 rettv->v_type = VAR_NUMBER;
10938 rettv->vval.v_number = curbuf->b_changedtick;
10942 if (*varname == NUL)
10943 /* let getbufvar({nr}, "") return the "b:" dictionary. The
10944 * scope prefix before the NUL byte is required by
10945 * find_var_in_ht(). */
10946 varname = (char_u *)"b:" + 2;
10947 /* look up the variable */
10948 v = find_var_in_ht(&curbuf->b_vars.dv_hashtab, varname, FALSE);
10950 copy_tv(&v->di_tv, rettv);
10953 /* restore previous notion of curbuf */
10954 curbuf = save_curbuf;
10961 * "getchar()" function
10964 f_getchar(argvars, rettv)
10971 /* Position the cursor. Needed after a message that ends in a space. */
10972 windgoto(msg_row, msg_col);
10978 if (argvars[0].v_type == VAR_UNKNOWN)
10979 /* getchar(): blocking wait. */
10981 else if (get_tv_number_chk(&argvars[0], &error) == 1)
10982 /* getchar(1): only check if char avail */
10984 else if (error || vpeekc() == NUL)
10985 /* illegal argument or getchar(0) and no char avail: return zero */
10988 /* getchar(0) and char avail: return char */
10997 vimvars[VV_MOUSE_WIN].vv_nr = 0;
10998 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
10999 vimvars[VV_MOUSE_COL].vv_nr = 0;
11001 rettv->vval.v_number = n;
11002 if (IS_SPECIAL(n) || mod_mask != 0)
11004 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
11007 /* Turn a special key into three bytes, plus modifier. */
11010 temp[i++] = K_SPECIAL;
11011 temp[i++] = KS_MODIFIER;
11012 temp[i++] = mod_mask;
11016 temp[i++] = K_SPECIAL;
11017 temp[i++] = K_SECOND(n);
11018 temp[i++] = K_THIRD(n);
11021 else if (has_mbyte)
11022 i += (*mb_char2bytes)(n, temp + i);
11027 rettv->v_type = VAR_STRING;
11028 rettv->vval.v_string = vim_strsave(temp);
11031 if (n == K_LEFTMOUSE
11032 || n == K_LEFTMOUSE_NM
11034 || n == K_LEFTRELEASE
11035 || n == K_LEFTRELEASE_NM
11036 || n == K_MIDDLEMOUSE
11037 || n == K_MIDDLEDRAG
11038 || n == K_MIDDLERELEASE
11039 || n == K_RIGHTMOUSE
11040 || n == K_RIGHTDRAG
11041 || n == K_RIGHTRELEASE
11044 || n == K_X1RELEASE
11047 || n == K_X2RELEASE
11048 || n == K_MOUSELEFT
11049 || n == K_MOUSERIGHT
11050 || n == K_MOUSEDOWN
11053 int row = mouse_row;
11054 int col = mouse_col;
11057 # ifdef FEAT_WINDOWS
11062 if (row >= 0 && col >= 0)
11064 /* Find the window at the mouse coordinates and compute the
11065 * text position. */
11066 win = mouse_find_win(&row, &col);
11067 (void)mouse_comp_pos(win, &row, &col, &lnum);
11068 # ifdef FEAT_WINDOWS
11069 for (wp = firstwin; wp != win; wp = wp->w_next)
11072 vimvars[VV_MOUSE_WIN].vv_nr = winnr;
11073 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
11074 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
11082 * "getcharmod()" function
11085 f_getcharmod(argvars, rettv)
11086 typval_T *argvars UNUSED;
11089 rettv->vval.v_number = mod_mask;
11093 * "getcmdline()" function
11096 f_getcmdline(argvars, rettv)
11097 typval_T *argvars UNUSED;
11100 rettv->v_type = VAR_STRING;
11101 rettv->vval.v_string = get_cmdline_str();
11105 * "getcmdpos()" function
11108 f_getcmdpos(argvars, rettv)
11109 typval_T *argvars UNUSED;
11112 rettv->vval.v_number = get_cmdline_pos() + 1;
11116 * "getcmdtype()" function
11119 f_getcmdtype(argvars, rettv)
11120 typval_T *argvars UNUSED;
11123 rettv->v_type = VAR_STRING;
11124 rettv->vval.v_string = alloc(2);
11125 if (rettv->vval.v_string != NULL)
11127 rettv->vval.v_string[0] = get_cmdline_type();
11128 rettv->vval.v_string[1] = NUL;
11133 * "getcwd()" function
11136 f_getcwd(argvars, rettv)
11137 typval_T *argvars UNUSED;
11142 rettv->v_type = VAR_STRING;
11143 rettv->vval.v_string = NULL;
11144 cwd = alloc(MAXPATHL);
11147 if (mch_dirname(cwd, MAXPATHL) != FAIL)
11149 rettv->vval.v_string = vim_strsave(cwd);
11150 #ifdef BACKSLASH_IN_FILENAME
11151 if (rettv->vval.v_string != NULL)
11152 slash_adjust(rettv->vval.v_string);
11160 * "getfontname()" function
11163 f_getfontname(argvars, rettv)
11164 typval_T *argvars UNUSED;
11167 rettv->v_type = VAR_STRING;
11168 rettv->vval.v_string = NULL;
11173 char_u *name = NULL;
11175 if (argvars[0].v_type == VAR_UNKNOWN)
11177 /* Get the "Normal" font. Either the name saved by
11178 * hl_set_font_name() or from the font ID. */
11179 font = gui.norm_font;
11180 name = hl_get_font_name();
11184 name = get_tv_string(&argvars[0]);
11185 if (STRCMP(name, "*") == 0) /* don't use font dialog */
11187 font = gui_mch_get_font(name, FALSE);
11188 if (font == NOFONT)
11189 return; /* Invalid font name, return empty string. */
11191 rettv->vval.v_string = gui_mch_get_fontname(font, name);
11192 if (argvars[0].v_type != VAR_UNKNOWN)
11193 gui_mch_free_font(font);
11199 * "getfperm({fname})" function
11202 f_getfperm(argvars, rettv)
11208 char_u *perm = NULL;
11209 char_u flags[] = "rwx";
11212 fname = get_tv_string(&argvars[0]);
11214 rettv->v_type = VAR_STRING;
11215 if (mch_stat((char *)fname, &st) >= 0)
11217 perm = vim_strsave((char_u *)"---------");
11220 for (i = 0; i < 9; i++)
11222 if (st.st_mode & (1 << (8 - i)))
11223 perm[i] = flags[i % 3];
11227 rettv->vval.v_string = perm;
11231 * "getfsize({fname})" function
11234 f_getfsize(argvars, rettv)
11241 fname = get_tv_string(&argvars[0]);
11243 rettv->v_type = VAR_NUMBER;
11245 if (mch_stat((char *)fname, &st) >= 0)
11247 if (mch_isdir(fname))
11248 rettv->vval.v_number = 0;
11251 rettv->vval.v_number = (varnumber_T)st.st_size;
11253 /* non-perfect check for overflow */
11254 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
11255 rettv->vval.v_number = -2;
11259 rettv->vval.v_number = -1;
11263 * "getftime({fname})" function
11266 f_getftime(argvars, rettv)
11273 fname = get_tv_string(&argvars[0]);
11275 if (mch_stat((char *)fname, &st) >= 0)
11276 rettv->vval.v_number = (varnumber_T)st.st_mtime;
11278 rettv->vval.v_number = -1;
11282 * "getftype({fname})" function
11285 f_getftype(argvars, rettv)
11291 char_u *type = NULL;
11294 fname = get_tv_string(&argvars[0]);
11296 rettv->v_type = VAR_STRING;
11297 if (mch_lstat((char *)fname, &st) >= 0)
11300 if (S_ISREG(st.st_mode))
11302 else if (S_ISDIR(st.st_mode))
11305 else if (S_ISLNK(st.st_mode))
11309 else if (S_ISBLK(st.st_mode))
11313 else if (S_ISCHR(st.st_mode))
11317 else if (S_ISFIFO(st.st_mode))
11321 else if (S_ISSOCK(st.st_mode))
11328 switch (st.st_mode & S_IFMT)
11330 case S_IFREG: t = "file"; break;
11331 case S_IFDIR: t = "dir"; break;
11333 case S_IFLNK: t = "link"; break;
11336 case S_IFBLK: t = "bdev"; break;
11339 case S_IFCHR: t = "cdev"; break;
11342 case S_IFIFO: t = "fifo"; break;
11345 case S_IFSOCK: t = "socket"; break;
11347 default: t = "other";
11350 if (mch_isdir(fname))
11356 type = vim_strsave((char_u *)t);
11358 rettv->vval.v_string = type;
11362 * "getline(lnum, [end])" function
11365 f_getline(argvars, rettv)
11373 lnum = get_tv_lnum(argvars);
11374 if (argvars[1].v_type == VAR_UNKNOWN)
11381 end = get_tv_lnum(&argvars[1]);
11385 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
11389 * "getmatches()" function
11392 f_getmatches(argvars, rettv)
11393 typval_T *argvars UNUSED;
11396 #ifdef FEAT_SEARCH_EXTRA
11398 matchitem_T *cur = curwin->w_match_head;
11400 if (rettv_list_alloc(rettv) == OK)
11402 while (cur != NULL)
11404 dict = dict_alloc();
11407 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
11408 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
11409 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
11410 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
11411 list_append_dict(rettv->vval.v_list, dict);
11419 * "getpid()" function
11422 f_getpid(argvars, rettv)
11423 typval_T *argvars UNUSED;
11426 rettv->vval.v_number = mch_get_pid();
11430 * "getpos(string)" function
11433 f_getpos(argvars, rettv)
11441 if (rettv_list_alloc(rettv) == OK)
11443 l = rettv->vval.v_list;
11444 fp = var2fpos(&argvars[0], TRUE, &fnum);
11446 list_append_number(l, (varnumber_T)fnum);
11448 list_append_number(l, (varnumber_T)0);
11449 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
11451 list_append_number(l, (fp != NULL)
11452 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
11454 list_append_number(l,
11455 #ifdef FEAT_VIRTUALEDIT
11456 (fp != NULL) ? (varnumber_T)fp->coladd :
11461 rettv->vval.v_number = FALSE;
11465 * "getqflist()" and "getloclist()" functions
11468 f_getqflist(argvars, rettv)
11469 typval_T *argvars UNUSED;
11470 typval_T *rettv UNUSED;
11472 #ifdef FEAT_QUICKFIX
11476 #ifdef FEAT_QUICKFIX
11477 if (rettv_list_alloc(rettv) == OK)
11480 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
11482 wp = find_win_by_nr(&argvars[0], NULL);
11487 (void)get_errorlist(wp, rettv->vval.v_list);
11493 * "getreg()" function
11496 f_getreg(argvars, rettv)
11500 char_u *strregname;
11505 if (argvars[0].v_type != VAR_UNKNOWN)
11507 strregname = get_tv_string_chk(&argvars[0]);
11508 error = strregname == NULL;
11509 if (argvars[1].v_type != VAR_UNKNOWN)
11510 arg2 = get_tv_number_chk(&argvars[1], &error);
11513 strregname = vimvars[VV_REG].vv_str;
11514 regname = (strregname == NULL ? '"' : *strregname);
11518 rettv->v_type = VAR_STRING;
11519 rettv->vval.v_string = error ? NULL :
11520 get_reg_contents(regname, TRUE, arg2);
11524 * "getregtype()" function
11527 f_getregtype(argvars, rettv)
11531 char_u *strregname;
11533 char_u buf[NUMBUFLEN + 2];
11536 if (argvars[0].v_type != VAR_UNKNOWN)
11538 strregname = get_tv_string_chk(&argvars[0]);
11539 if (strregname == NULL) /* type error; errmsg already given */
11541 rettv->v_type = VAR_STRING;
11542 rettv->vval.v_string = NULL;
11547 /* Default to v:register */
11548 strregname = vimvars[VV_REG].vv_str;
11550 regname = (strregname == NULL ? '"' : *strregname);
11556 switch (get_reg_type(regname, ®len))
11558 case MLINE: buf[0] = 'V'; break;
11559 case MCHAR: buf[0] = 'v'; break;
11563 sprintf((char *)buf + 1, "%ld", reglen + 1);
11567 rettv->v_type = VAR_STRING;
11568 rettv->vval.v_string = vim_strsave(buf);
11572 * "gettabvar()" function
11575 f_gettabvar(argvars, rettv)
11583 rettv->v_type = VAR_STRING;
11584 rettv->vval.v_string = NULL;
11586 varname = get_tv_string_chk(&argvars[1]);
11587 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
11588 if (tp != NULL && varname != NULL)
11590 /* look up the variable */
11591 v = find_var_in_ht(&tp->tp_vars.dv_hashtab, varname, FALSE);
11593 copy_tv(&v->di_tv, rettv);
11598 * "gettabwinvar()" function
11601 f_gettabwinvar(argvars, rettv)
11605 getwinvar(argvars, rettv, 1);
11609 * "getwinposx()" function
11612 f_getwinposx(argvars, rettv)
11613 typval_T *argvars UNUSED;
11616 rettv->vval.v_number = -1;
11622 if (gui_mch_get_winpos(&x, &y) == OK)
11623 rettv->vval.v_number = x;
11629 * "getwinposy()" function
11632 f_getwinposy(argvars, rettv)
11633 typval_T *argvars UNUSED;
11636 rettv->vval.v_number = -1;
11642 if (gui_mch_get_winpos(&x, &y) == OK)
11643 rettv->vval.v_number = y;
11649 * Find window specified by "vp" in tabpage "tp".
11652 find_win_by_nr(vp, tp)
11654 tabpage_T *tp; /* NULL for current tab page */
11656 #ifdef FEAT_WINDOWS
11661 nr = get_tv_number_chk(vp, NULL);
11663 #ifdef FEAT_WINDOWS
11669 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
11670 wp != NULL; wp = wp->w_next)
11675 if (nr == 0 || nr == 1)
11682 * "getwinvar()" function
11685 f_getwinvar(argvars, rettv)
11689 getwinvar(argvars, rettv, 0);
11693 * getwinvar() and gettabwinvar()
11696 getwinvar(argvars, rettv, off)
11699 int off; /* 1 for gettabwinvar() */
11701 win_T *win, *oldcurwin;
11706 #ifdef FEAT_WINDOWS
11708 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
11712 win = find_win_by_nr(&argvars[off], tp);
11713 varname = get_tv_string_chk(&argvars[off + 1]);
11716 rettv->v_type = VAR_STRING;
11717 rettv->vval.v_string = NULL;
11719 if (win != NULL && varname != NULL)
11721 /* Set curwin to be our win, temporarily. Also set curbuf, so
11722 * that we can get buffer-local options. */
11723 oldcurwin = curwin;
11725 curbuf = win->w_buffer;
11727 if (*varname == '&') /* window-local-option */
11728 get_option_tv(&varname, rettv, 1);
11731 if (*varname == NUL)
11732 /* let getwinvar({nr}, "") return the "w:" dictionary. The
11733 * scope prefix before the NUL byte is required by
11734 * find_var_in_ht(). */
11735 varname = (char_u *)"w:" + 2;
11736 /* look up the variable */
11737 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
11739 copy_tv(&v->di_tv, rettv);
11742 /* restore previous notion of curwin */
11743 curwin = oldcurwin;
11744 curbuf = curwin->w_buffer;
11751 * "glob()" function
11754 f_glob(argvars, rettv)
11758 int options = WILD_SILENT|WILD_USE_NL;
11762 /* When the optional second argument is non-zero, don't remove matches
11763 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11764 if (argvars[1].v_type != VAR_UNKNOWN
11765 && get_tv_number_chk(&argvars[1], &error))
11766 options |= WILD_KEEP_ALL;
11767 rettv->v_type = VAR_STRING;
11771 xpc.xp_context = EXPAND_FILES;
11773 options += WILD_ICASE;
11774 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
11775 NULL, options, WILD_ALL);
11778 rettv->vval.v_string = NULL;
11782 * "globpath()" function
11785 f_globpath(argvars, rettv)
11790 char_u buf1[NUMBUFLEN];
11791 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
11794 /* When the optional second argument is non-zero, don't remove matches
11795 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11796 if (argvars[2].v_type != VAR_UNKNOWN
11797 && get_tv_number_chk(&argvars[2], &error))
11798 flags |= WILD_KEEP_ALL;
11799 rettv->v_type = VAR_STRING;
11800 if (file == NULL || error)
11801 rettv->vval.v_string = NULL;
11803 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file,
11811 f_has(argvars, rettv)
11818 static char *(has_list[]) =
11839 #if defined(MACOS_X_UNIX)
11860 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
11863 #if defined(WIN64) || defined(_WIN64)
11869 #ifndef CASE_INSENSITIVE_FILENAME
11875 #ifdef FEAT_AUTOCMD
11880 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
11881 "balloon_multiline",
11884 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
11886 # ifdef ALL_BUILTIN_TCAPS
11887 "all_builtin_terms",
11890 #ifdef FEAT_BYTEOFF
11893 #ifdef FEAT_CINDENT
11896 #ifdef FEAT_CLIENTSERVER
11899 #ifdef FEAT_CLIPBOARD
11902 #ifdef FEAT_CMDL_COMPL
11905 #ifdef FEAT_CMDHIST
11908 #ifdef FEAT_COMMENTS
11911 #ifdef FEAT_CONCEAL
11920 #ifdef FEAT_CURSORBIND
11923 #ifdef CURSOR_SHAPE
11929 #ifdef FEAT_CON_DIALOG
11932 #ifdef FEAT_GUI_DIALOG
11938 #ifdef FEAT_DIGRAPHS
11944 #ifdef FEAT_EMACS_TAGS
11947 "eval", /* always present, of course! */
11948 #ifdef FEAT_EX_EXTRA
11951 #ifdef FEAT_SEARCH_EXTRA
11957 #ifdef FEAT_SEARCHPATH
11960 #if (defined(UNIX) && !defined(USE_SYSTEM)) || defined(WIN3264)
11963 #ifdef FEAT_FIND_ID
11969 #ifdef FEAT_FOLDING
11975 #if !defined(USE_SYSTEM) && defined(UNIX)
11978 #ifdef FEAT_GETTEXT
11984 #ifdef FEAT_GUI_ATHENA
11985 # ifdef FEAT_GUI_NEXTAW
11991 #ifdef FEAT_GUI_GTK
11995 #ifdef FEAT_GUI_GNOME
11998 #ifdef FEAT_GUI_MAC
12001 #ifdef FEAT_GUI_MOTIF
12004 #ifdef FEAT_GUI_PHOTON
12007 #ifdef FEAT_GUI_W16
12010 #ifdef FEAT_GUI_W32
12013 #ifdef FEAT_HANGULIN
12016 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
12019 #ifdef FEAT_INS_EXPAND
12022 #ifdef FEAT_JUMPLIST
12028 #ifdef FEAT_LANGMAP
12031 #ifdef FEAT_LIBCALL
12034 #ifdef FEAT_LINEBREAK
12040 #ifdef FEAT_LISTCMDS
12043 #ifdef FEAT_LOCALMAP
12047 # ifndef DYNAMIC_LUA
12054 #ifdef FEAT_SESSION
12057 #ifdef FEAT_MODIFY_FNAME
12063 #ifdef FEAT_MOUSESHAPE
12066 #if defined(UNIX) || defined(VMS)
12067 # ifdef FEAT_MOUSE_DEC
12070 # ifdef FEAT_MOUSE_GPM
12073 # ifdef FEAT_MOUSE_JSB
12076 # ifdef FEAT_MOUSE_NET
12079 # ifdef FEAT_MOUSE_PTERM
12082 # ifdef FEAT_SYSMOUSE
12085 # ifdef FEAT_MOUSE_XTERM
12092 #ifdef FEAT_MBYTE_IME
12095 #ifdef FEAT_MULTI_LANG
12098 #ifdef FEAT_MZSCHEME
12099 #ifndef DYNAMIC_MZSCHEME
12106 #ifdef FEAT_PATH_EXTRA
12110 #ifndef DYNAMIC_PERL
12114 #ifdef FEAT_PERSISTENT_UNDO
12118 #ifndef DYNAMIC_PYTHON
12122 #ifdef FEAT_PYTHON3
12123 #ifndef DYNAMIC_PYTHON3
12127 #ifdef FEAT_POSTSCRIPT
12130 #ifdef FEAT_PRINTER
12133 #ifdef FEAT_PROFILE
12136 #ifdef FEAT_RELTIME
12139 #ifdef FEAT_QUICKFIX
12142 #ifdef FEAT_RIGHTLEFT
12145 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
12148 #ifdef FEAT_SCROLLBIND
12151 #ifdef FEAT_CMDL_INFO
12158 #ifdef FEAT_SMARTINDENT
12167 #ifdef FEAT_STL_OPT
12170 #ifdef FEAT_SUN_WORKSHOP
12173 #ifdef FEAT_NETBEANS_INTG
12182 #if defined(USE_SYSTEM) || !defined(UNIX)
12185 #ifdef FEAT_TAG_BINS
12188 #ifdef FEAT_TAG_OLDSTATIC
12191 #ifdef FEAT_TAG_ANYWHITE
12195 # ifndef DYNAMIC_TCL
12202 #ifdef FEAT_TERMRESPONSE
12205 #ifdef FEAT_TEXTOBJ
12208 #ifdef HAVE_TGETENT
12214 #ifdef FEAT_TOOLBAR
12217 #if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
12220 #ifdef FEAT_USR_CMDS
12221 "user-commands", /* was accidentally included in 5.4 */
12224 #ifdef FEAT_VIMINFO
12227 #ifdef FEAT_VERTSPLIT
12230 #ifdef FEAT_VIRTUALEDIT
12236 #ifdef FEAT_VISUALEXTRA
12239 #ifdef FEAT_VREPLACE
12242 #ifdef FEAT_WILDIGN
12245 #ifdef FEAT_WILDMENU
12248 #ifdef FEAT_WINDOWS
12254 #ifdef FEAT_WRITEBACKUP
12260 #ifdef FEAT_XFONTSET
12266 #ifdef USE_XSMP_INTERACT
12269 #ifdef FEAT_XCLIPBOARD
12272 #ifdef FEAT_XTERM_SAVE
12275 #if defined(UNIX) && defined(FEAT_X11)
12281 name = get_tv_string(&argvars[0]);
12282 for (i = 0; has_list[i] != NULL; ++i)
12283 if (STRICMP(name, has_list[i]) == 0)
12291 if (STRNICMP(name, "patch", 5) == 0)
12292 n = has_patch(atoi((char *)name + 5));
12293 else if (STRICMP(name, "vim_starting") == 0)
12294 n = (starting != 0);
12296 else if (STRICMP(name, "multi_byte_encoding") == 0)
12299 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
12300 else if (STRICMP(name, "balloon_multiline") == 0)
12301 n = multiline_balloon_available();
12304 else if (STRICMP(name, "tcl") == 0)
12305 n = tcl_enabled(FALSE);
12307 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
12308 else if (STRICMP(name, "iconv") == 0)
12309 n = iconv_enabled(FALSE);
12312 else if (STRICMP(name, "lua") == 0)
12313 n = lua_enabled(FALSE);
12315 #ifdef DYNAMIC_MZSCHEME
12316 else if (STRICMP(name, "mzscheme") == 0)
12317 n = mzscheme_enabled(FALSE);
12319 #ifdef DYNAMIC_RUBY
12320 else if (STRICMP(name, "ruby") == 0)
12321 n = ruby_enabled(FALSE);
12324 #ifdef DYNAMIC_PYTHON
12325 else if (STRICMP(name, "python") == 0)
12326 n = python_enabled(FALSE);
12329 #ifdef FEAT_PYTHON3
12330 #ifdef DYNAMIC_PYTHON3
12331 else if (STRICMP(name, "python3") == 0)
12332 n = python3_enabled(FALSE);
12335 #ifdef DYNAMIC_PERL
12336 else if (STRICMP(name, "perl") == 0)
12337 n = perl_enabled(FALSE);
12340 else if (STRICMP(name, "gui_running") == 0)
12341 n = (gui.in_use || gui.starting);
12342 # ifdef FEAT_GUI_W32
12343 else if (STRICMP(name, "gui_win32s") == 0)
12344 n = gui_is_win32s();
12346 # ifdef FEAT_BROWSE
12347 else if (STRICMP(name, "browse") == 0)
12348 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
12352 else if (STRICMP(name, "syntax_items") == 0)
12353 n = syntax_present(curwin);
12355 #if defined(WIN3264)
12356 else if (STRICMP(name, "win95") == 0)
12357 n = mch_windows95();
12359 #ifdef FEAT_NETBEANS_INTG
12360 else if (STRICMP(name, "netbeans_enabled") == 0)
12361 n = netbeans_active();
12365 rettv->vval.v_number = n;
12369 * "has_key()" function
12372 f_has_key(argvars, rettv)
12376 if (argvars[0].v_type != VAR_DICT)
12378 EMSG(_(e_dictreq));
12381 if (argvars[0].vval.v_dict == NULL)
12384 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
12385 get_tv_string(&argvars[1]), -1) != NULL;
12389 * "haslocaldir()" function
12392 f_haslocaldir(argvars, rettv)
12393 typval_T *argvars UNUSED;
12396 rettv->vval.v_number = (curwin->w_localdir != NULL);
12400 * "hasmapto()" function
12403 f_hasmapto(argvars, rettv)
12409 char_u buf[NUMBUFLEN];
12412 name = get_tv_string(&argvars[0]);
12413 if (argvars[1].v_type == VAR_UNKNOWN)
12414 mode = (char_u *)"nvo";
12417 mode = get_tv_string_buf(&argvars[1], buf);
12418 if (argvars[2].v_type != VAR_UNKNOWN)
12419 abbr = get_tv_number(&argvars[2]);
12422 if (map_to_exists(name, mode, abbr))
12423 rettv->vval.v_number = TRUE;
12425 rettv->vval.v_number = FALSE;
12429 * "histadd()" function
12432 f_histadd(argvars, rettv)
12433 typval_T *argvars UNUSED;
12436 #ifdef FEAT_CMDHIST
12439 char_u buf[NUMBUFLEN];
12442 rettv->vval.v_number = FALSE;
12443 if (check_restricted() || check_secure())
12445 #ifdef FEAT_CMDHIST
12446 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12447 histype = str != NULL ? get_histtype(str) : -1;
12450 str = get_tv_string_buf(&argvars[1], buf);
12454 add_to_history(histype, str, FALSE, NUL);
12455 rettv->vval.v_number = TRUE;
12463 * "histdel()" function
12466 f_histdel(argvars, rettv)
12467 typval_T *argvars UNUSED;
12468 typval_T *rettv UNUSED;
12470 #ifdef FEAT_CMDHIST
12472 char_u buf[NUMBUFLEN];
12475 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12478 else if (argvars[1].v_type == VAR_UNKNOWN)
12479 /* only one argument: clear entire history */
12480 n = clr_history(get_histtype(str));
12481 else if (argvars[1].v_type == VAR_NUMBER)
12482 /* index given: remove that entry */
12483 n = del_history_idx(get_histtype(str),
12484 (int)get_tv_number(&argvars[1]));
12486 /* string given: remove all matching entries */
12487 n = del_history_entry(get_histtype(str),
12488 get_tv_string_buf(&argvars[1], buf));
12489 rettv->vval.v_number = n;
12494 * "histget()" function
12497 f_histget(argvars, rettv)
12498 typval_T *argvars UNUSED;
12501 #ifdef FEAT_CMDHIST
12506 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12508 rettv->vval.v_string = NULL;
12511 type = get_histtype(str);
12512 if (argvars[1].v_type == VAR_UNKNOWN)
12513 idx = get_history_idx(type);
12515 idx = (int)get_tv_number_chk(&argvars[1], NULL);
12516 /* -1 on type error */
12517 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
12520 rettv->vval.v_string = NULL;
12522 rettv->v_type = VAR_STRING;
12526 * "histnr()" function
12529 f_histnr(argvars, rettv)
12530 typval_T *argvars UNUSED;
12535 #ifdef FEAT_CMDHIST
12536 char_u *history = get_tv_string_chk(&argvars[0]);
12538 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
12539 if (i >= HIST_CMD && i < HIST_COUNT)
12540 i = get_history_idx(i);
12544 rettv->vval.v_number = i;
12548 * "highlightID(name)" function
12551 f_hlID(argvars, rettv)
12555 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
12559 * "highlight_exists()" function
12562 f_hlexists(argvars, rettv)
12566 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
12570 * "hostname()" function
12573 f_hostname(argvars, rettv)
12574 typval_T *argvars UNUSED;
12577 char_u hostname[256];
12579 mch_get_host_name(hostname, 256);
12580 rettv->v_type = VAR_STRING;
12581 rettv->vval.v_string = vim_strsave(hostname);
12588 f_iconv(argvars, rettv)
12589 typval_T *argvars UNUSED;
12593 char_u buf1[NUMBUFLEN];
12594 char_u buf2[NUMBUFLEN];
12595 char_u *from, *to, *str;
12599 rettv->v_type = VAR_STRING;
12600 rettv->vval.v_string = NULL;
12603 str = get_tv_string(&argvars[0]);
12604 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
12605 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
12606 vimconv.vc_type = CONV_NONE;
12607 convert_setup(&vimconv, from, to);
12609 /* If the encodings are equal, no conversion needed. */
12610 if (vimconv.vc_type == CONV_NONE)
12611 rettv->vval.v_string = vim_strsave(str);
12613 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
12615 convert_setup(&vimconv, NULL, NULL);
12622 * "indent()" function
12625 f_indent(argvars, rettv)
12631 lnum = get_tv_lnum(argvars);
12632 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12633 rettv->vval.v_number = get_indent_lnum(lnum);
12635 rettv->vval.v_number = -1;
12639 * "index()" function
12642 f_index(argvars, rettv)
12651 rettv->vval.v_number = -1;
12652 if (argvars[0].v_type != VAR_LIST)
12654 EMSG(_(e_listreq));
12657 l = argvars[0].vval.v_list;
12660 item = l->lv_first;
12661 if (argvars[2].v_type != VAR_UNKNOWN)
12665 /* Start at specified item. Use the cached index that list_find()
12666 * sets, so that a negative number also works. */
12667 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
12669 if (argvars[3].v_type != VAR_UNKNOWN)
12670 ic = get_tv_number_chk(&argvars[3], &error);
12675 for ( ; item != NULL; item = item->li_next, ++idx)
12676 if (tv_equal(&item->li_tv, &argvars[1], ic, FALSE))
12678 rettv->vval.v_number = idx;
12684 static int inputsecret_flag = 0;
12686 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
12689 * This function is used by f_input() and f_inputdialog() functions. The third
12690 * argument to f_input() specifies the type of completion to use at the
12691 * prompt. The third argument to f_inputdialog() specifies the value to return
12692 * when the user cancels the prompt.
12695 get_user_input(argvars, rettv, inputdialog)
12700 char_u *prompt = get_tv_string_chk(&argvars[0]);
12703 char_u buf[NUMBUFLEN];
12704 int cmd_silent_save = cmd_silent;
12705 char_u *defstr = (char_u *)"";
12706 int xp_type = EXPAND_NOTHING;
12707 char_u *xp_arg = NULL;
12709 rettv->v_type = VAR_STRING;
12710 rettv->vval.v_string = NULL;
12712 #ifdef NO_CONSOLE_INPUT
12713 /* While starting up, there is no place to enter text. */
12714 if (no_console_input())
12718 cmd_silent = FALSE; /* Want to see the prompt. */
12719 if (prompt != NULL)
12721 /* Only the part of the message after the last NL is considered as
12722 * prompt for the command line */
12723 p = vim_strrchr(prompt, '\n');
12733 msg_puts_attr(prompt, echo_attr);
12734 msg_didout = FALSE;
12738 cmdline_row = msg_row;
12740 if (argvars[1].v_type != VAR_UNKNOWN)
12742 defstr = get_tv_string_buf_chk(&argvars[1], buf);
12743 if (defstr != NULL)
12744 stuffReadbuffSpec(defstr);
12746 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
12752 rettv->vval.v_string = NULL;
12754 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
12755 if (xp_name == NULL)
12758 xp_namelen = (int)STRLEN(xp_name);
12760 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
12766 if (defstr != NULL)
12767 rettv->vval.v_string =
12768 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
12773 /* since the user typed this, no need to wait for return */
12774 need_wait_return = FALSE;
12775 msg_didout = FALSE;
12777 cmd_silent = cmd_silent_save;
12781 * "input()" function
12782 * Also handles inputsecret() when inputsecret is set.
12785 f_input(argvars, rettv)
12789 get_user_input(argvars, rettv, FALSE);
12793 * "inputdialog()" function
12796 f_inputdialog(argvars, rettv)
12800 #if defined(FEAT_GUI_TEXTDIALOG)
12801 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
12802 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
12805 char_u buf[NUMBUFLEN];
12806 char_u *defstr = (char_u *)"";
12808 message = get_tv_string_chk(&argvars[0]);
12809 if (argvars[1].v_type != VAR_UNKNOWN
12810 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
12811 vim_strncpy(IObuff, defstr, IOSIZE - 1);
12814 if (message != NULL && defstr != NULL
12815 && do_dialog(VIM_QUESTION, NULL, message,
12816 (char_u *)_("&OK\n&Cancel"), 1, IObuff, FALSE) == 1)
12817 rettv->vval.v_string = vim_strsave(IObuff);
12820 if (message != NULL && defstr != NULL
12821 && argvars[1].v_type != VAR_UNKNOWN
12822 && argvars[2].v_type != VAR_UNKNOWN)
12823 rettv->vval.v_string = vim_strsave(
12824 get_tv_string_buf(&argvars[2], buf));
12826 rettv->vval.v_string = NULL;
12828 rettv->v_type = VAR_STRING;
12832 get_user_input(argvars, rettv, TRUE);
12836 * "inputlist()" function
12839 f_inputlist(argvars, rettv)
12847 #ifdef NO_CONSOLE_INPUT
12848 /* While starting up, there is no place to enter text. */
12849 if (no_console_input())
12852 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
12854 EMSG2(_(e_listarg), "inputlist()");
12859 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
12860 lines_left = Rows; /* avoid more prompt */
12864 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
12866 msg_puts(get_tv_string(&li->li_tv));
12870 /* Ask for choice. */
12871 selected = prompt_for_number(&mouse_used);
12873 selected -= lines_left;
12875 rettv->vval.v_number = selected;
12879 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
12882 * "inputrestore()" function
12885 f_inputrestore(argvars, rettv)
12886 typval_T *argvars UNUSED;
12889 if (ga_userinput.ga_len > 0)
12891 --ga_userinput.ga_len;
12892 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
12893 + ga_userinput.ga_len);
12894 /* default return is zero == OK */
12896 else if (p_verbose > 1)
12898 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
12899 rettv->vval.v_number = 1; /* Failed */
12904 * "inputsave()" function
12907 f_inputsave(argvars, rettv)
12908 typval_T *argvars UNUSED;
12911 /* Add an entry to the stack of typeahead storage. */
12912 if (ga_grow(&ga_userinput, 1) == OK)
12914 save_typeahead((tasave_T *)(ga_userinput.ga_data)
12915 + ga_userinput.ga_len);
12916 ++ga_userinput.ga_len;
12917 /* default return is zero == OK */
12920 rettv->vval.v_number = 1; /* Failed */
12924 * "inputsecret()" function
12927 f_inputsecret(argvars, rettv)
12932 ++inputsecret_flag;
12933 f_input(argvars, rettv);
12935 --inputsecret_flag;
12939 * "insert()" function
12942 f_insert(argvars, rettv)
12951 if (argvars[0].v_type != VAR_LIST)
12952 EMSG2(_(e_listarg), "insert()");
12953 else if ((l = argvars[0].vval.v_list) != NULL
12954 && !tv_check_lock(l->lv_lock, (char_u *)_("insert() argument")))
12956 if (argvars[2].v_type != VAR_UNKNOWN)
12957 before = get_tv_number_chk(&argvars[2], &error);
12959 return; /* type error; errmsg already given */
12961 if (before == l->lv_len)
12965 item = list_find(l, before);
12968 EMSGN(_(e_listidx), before);
12974 list_insert_tv(l, &argvars[1], item);
12975 copy_tv(&argvars[0], rettv);
12981 * "invert(expr)" function
12984 f_invert(argvars, rettv)
12988 rettv->vval.v_number = ~get_tv_number_chk(&argvars[0], NULL);
12992 * "isdirectory()" function
12995 f_isdirectory(argvars, rettv)
12999 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
13003 * "islocked()" function
13006 f_islocked(argvars, rettv)
13014 rettv->vval.v_number = -1;
13015 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
13017 if (end != NULL && lv.ll_name != NULL)
13020 EMSG(_(e_trailing));
13023 if (lv.ll_tv == NULL)
13025 if (check_changedtick(lv.ll_name))
13026 rettv->vval.v_number = 1; /* always locked */
13029 di = find_var(lv.ll_name, NULL);
13032 /* Consider a variable locked when:
13033 * 1. the variable itself is locked
13034 * 2. the value of the variable is locked.
13035 * 3. the List or Dict value is locked.
13037 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
13038 || tv_islocked(&di->di_tv));
13042 else if (lv.ll_range)
13043 EMSG(_("E786: Range not allowed"));
13044 else if (lv.ll_newkey != NULL)
13045 EMSG2(_(e_dictkey), lv.ll_newkey);
13046 else if (lv.ll_list != NULL)
13048 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
13050 /* Dictionary item. */
13051 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
13058 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
13061 * Turn a dict into a list:
13062 * "what" == 0: list of keys
13063 * "what" == 1: list of values
13064 * "what" == 2: list of items
13067 dict_list(argvars, rettv, what)
13080 if (argvars[0].v_type != VAR_DICT)
13082 EMSG(_(e_dictreq));
13085 if ((d = argvars[0].vval.v_dict) == NULL)
13088 if (rettv_list_alloc(rettv) == FAIL)
13091 todo = (int)d->dv_hashtab.ht_used;
13092 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13094 if (!HASHITEM_EMPTY(hi))
13099 li = listitem_alloc();
13102 list_append(rettv->vval.v_list, li);
13107 li->li_tv.v_type = VAR_STRING;
13108 li->li_tv.v_lock = 0;
13109 li->li_tv.vval.v_string = vim_strsave(di->di_key);
13111 else if (what == 1)
13114 copy_tv(&di->di_tv, &li->li_tv);
13120 li->li_tv.v_type = VAR_LIST;
13121 li->li_tv.v_lock = 0;
13122 li->li_tv.vval.v_list = l2;
13127 li2 = listitem_alloc();
13130 list_append(l2, li2);
13131 li2->li_tv.v_type = VAR_STRING;
13132 li2->li_tv.v_lock = 0;
13133 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
13135 li2 = listitem_alloc();
13138 list_append(l2, li2);
13139 copy_tv(&di->di_tv, &li2->li_tv);
13146 * "items(dict)" function
13149 f_items(argvars, rettv)
13153 dict_list(argvars, rettv, 2);
13157 * "join()" function
13160 f_join(argvars, rettv)
13167 if (argvars[0].v_type != VAR_LIST)
13169 EMSG(_(e_listreq));
13172 if (argvars[0].vval.v_list == NULL)
13174 if (argvars[1].v_type == VAR_UNKNOWN)
13175 sep = (char_u *)" ";
13177 sep = get_tv_string_chk(&argvars[1]);
13179 rettv->v_type = VAR_STRING;
13183 ga_init2(&ga, (int)sizeof(char), 80);
13184 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
13185 ga_append(&ga, NUL);
13186 rettv->vval.v_string = (char_u *)ga.ga_data;
13189 rettv->vval.v_string = NULL;
13193 * "keys()" function
13196 f_keys(argvars, rettv)
13200 dict_list(argvars, rettv, 0);
13204 * "last_buffer_nr()" function.
13207 f_last_buffer_nr(argvars, rettv)
13208 typval_T *argvars UNUSED;
13214 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
13215 if (n < buf->b_fnum)
13218 rettv->vval.v_number = n;
13225 f_len(argvars, rettv)
13229 switch (argvars[0].v_type)
13233 rettv->vval.v_number = (varnumber_T)STRLEN(
13234 get_tv_string(&argvars[0]));
13237 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
13240 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
13243 EMSG(_("E701: Invalid type for len()"));
13248 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
13251 libcall_common(argvars, rettv, type)
13256 #ifdef FEAT_LIBCALL
13258 char_u **string_result;
13262 rettv->v_type = type;
13263 if (type != VAR_NUMBER)
13264 rettv->vval.v_string = NULL;
13266 if (check_restricted() || check_secure())
13269 #ifdef FEAT_LIBCALL
13270 /* The first two args must be strings, otherwise its meaningless */
13271 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
13274 if (argvars[2].v_type == VAR_STRING)
13275 string_in = argvars[2].vval.v_string;
13276 if (type == VAR_NUMBER)
13277 string_result = NULL;
13279 string_result = &rettv->vval.v_string;
13280 if (mch_libcall(argvars[0].vval.v_string,
13281 argvars[1].vval.v_string,
13283 argvars[2].vval.v_number,
13286 && type == VAR_NUMBER)
13287 rettv->vval.v_number = nr_result;
13293 * "libcall()" function
13296 f_libcall(argvars, rettv)
13300 libcall_common(argvars, rettv, VAR_STRING);
13304 * "libcallnr()" function
13307 f_libcallnr(argvars, rettv)
13311 libcall_common(argvars, rettv, VAR_NUMBER);
13315 * "line(string)" function
13318 f_line(argvars, rettv)
13326 fp = var2fpos(&argvars[0], TRUE, &fnum);
13329 rettv->vval.v_number = lnum;
13333 * "line2byte(lnum)" function
13336 f_line2byte(argvars, rettv)
13337 typval_T *argvars UNUSED;
13340 #ifndef FEAT_BYTEOFF
13341 rettv->vval.v_number = -1;
13345 lnum = get_tv_lnum(argvars);
13346 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
13347 rettv->vval.v_number = -1;
13349 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
13350 if (rettv->vval.v_number >= 0)
13351 ++rettv->vval.v_number;
13356 * "lispindent(lnum)" function
13359 f_lispindent(argvars, rettv)
13367 pos = curwin->w_cursor;
13368 lnum = get_tv_lnum(argvars);
13369 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
13371 curwin->w_cursor.lnum = lnum;
13372 rettv->vval.v_number = get_lisp_indent();
13373 curwin->w_cursor = pos;
13377 rettv->vval.v_number = -1;
13381 * "localtime()" function
13384 f_localtime(argvars, rettv)
13385 typval_T *argvars UNUSED;
13388 rettv->vval.v_number = (varnumber_T)time(NULL);
13391 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
13394 get_maparg(argvars, rettv, exact)
13401 char_u buf[NUMBUFLEN];
13402 char_u *keys_buf = NULL;
13406 int get_dict = FALSE;
13410 /* return empty string for failure */
13411 rettv->v_type = VAR_STRING;
13412 rettv->vval.v_string = NULL;
13414 keys = get_tv_string(&argvars[0]);
13418 if (argvars[1].v_type != VAR_UNKNOWN)
13420 which = get_tv_string_buf_chk(&argvars[1], buf);
13421 if (argvars[2].v_type != VAR_UNKNOWN)
13423 abbr = get_tv_number(&argvars[2]);
13424 if (argvars[3].v_type != VAR_UNKNOWN)
13425 get_dict = get_tv_number(&argvars[3]);
13429 which = (char_u *)"";
13433 mode = get_map_mode(&which, 0);
13435 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
13436 rhs = check_map(keys, mode, exact, FALSE, abbr, &mp, &buffer_local);
13437 vim_free(keys_buf);
13441 /* Return a string. */
13443 rettv->vval.v_string = str2special_save(rhs, FALSE);
13446 else if (rettv_dict_alloc(rettv) != FAIL && rhs != NULL)
13448 /* Return a dictionary. */
13449 char_u *lhs = str2special_save(mp->m_keys, TRUE);
13450 char_u *mapmode = map_mode_to_chars(mp->m_mode);
13451 dict_T *dict = rettv->vval.v_dict;
13453 dict_add_nr_str(dict, "lhs", 0L, lhs);
13454 dict_add_nr_str(dict, "rhs", 0L, mp->m_orig_str);
13455 dict_add_nr_str(dict, "noremap", mp->m_noremap ? 1L : 0L , NULL);
13456 dict_add_nr_str(dict, "expr", mp->m_expr ? 1L : 0L, NULL);
13457 dict_add_nr_str(dict, "silent", mp->m_silent ? 1L : 0L, NULL);
13458 dict_add_nr_str(dict, "sid", (long)mp->m_script_ID, NULL);
13459 dict_add_nr_str(dict, "buffer", (long)buffer_local, NULL);
13460 dict_add_nr_str(dict, "mode", 0L, mapmode);
13472 f_log(argvars, rettv)
13478 rettv->v_type = VAR_FLOAT;
13479 if (get_float_arg(argvars, &f) == OK)
13480 rettv->vval.v_float = log(f);
13482 rettv->vval.v_float = 0.0;
13486 * "log10()" function
13489 f_log10(argvars, rettv)
13495 rettv->v_type = VAR_FLOAT;
13496 if (get_float_arg(argvars, &f) == OK)
13497 rettv->vval.v_float = log10(f);
13499 rettv->vval.v_float = 0.0;
13507 f_map(argvars, rettv)
13511 filter_map(argvars, rettv, TRUE);
13515 * "maparg()" function
13518 f_maparg(argvars, rettv)
13522 get_maparg(argvars, rettv, TRUE);
13526 * "mapcheck()" function
13529 f_mapcheck(argvars, rettv)
13533 get_maparg(argvars, rettv, FALSE);
13536 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
13539 find_some_match(argvars, rettv, type)
13544 char_u *str = NULL;
13545 char_u *expr = NULL;
13547 regmatch_T regmatch;
13548 char_u patbuf[NUMBUFLEN];
13549 char_u strbuf[NUMBUFLEN];
13553 colnr_T startcol = 0;
13556 listitem_T *li = NULL;
13558 char_u *tofree = NULL;
13560 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
13562 p_cpo = (char_u *)"";
13564 rettv->vval.v_number = -1;
13567 /* return empty list when there are no matches */
13568 if (rettv_list_alloc(rettv) == FAIL)
13571 else if (type == 2)
13573 rettv->v_type = VAR_STRING;
13574 rettv->vval.v_string = NULL;
13577 if (argvars[0].v_type == VAR_LIST)
13579 if ((l = argvars[0].vval.v_list) == NULL)
13584 expr = str = get_tv_string(&argvars[0]);
13586 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
13590 if (argvars[2].v_type != VAR_UNKNOWN)
13594 start = get_tv_number_chk(&argvars[2], &error);
13599 li = list_find(l, start);
13602 idx = l->lv_idx; /* use the cached index */
13608 if (start > (long)STRLEN(str))
13610 /* When "count" argument is there ignore matches before "start",
13611 * otherwise skip part of the string. Differs when pattern is "^"
13613 if (argvars[3].v_type != VAR_UNKNOWN)
13619 if (argvars[3].v_type != VAR_UNKNOWN)
13620 nth = get_tv_number_chk(&argvars[3], &error);
13625 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
13626 if (regmatch.regprog != NULL)
13628 regmatch.rm_ic = p_ic;
13640 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
13645 match = vim_regexec_nl(®match, str, (colnr_T)startcol);
13647 if (match && --nth <= 0)
13649 if (l == NULL && !match)
13652 /* Advance to just after the match. */
13661 startcol = (colnr_T)(regmatch.startp[0]
13662 + (*mb_ptr2len)(regmatch.startp[0]) - str);
13664 startcol = (colnr_T)(regmatch.startp[0] + 1 - str);
13675 /* return list with matched string and submatches */
13676 for (i = 0; i < NSUBEXP; ++i)
13678 if (regmatch.endp[i] == NULL)
13680 if (list_append_string(rettv->vval.v_list,
13681 (char_u *)"", 0) == FAIL)
13684 else if (list_append_string(rettv->vval.v_list,
13685 regmatch.startp[i],
13686 (int)(regmatch.endp[i] - regmatch.startp[i]))
13691 else if (type == 2)
13693 /* return matched string */
13695 copy_tv(&li->li_tv, rettv);
13697 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
13698 (int)(regmatch.endp[0] - regmatch.startp[0]));
13700 else if (l != NULL)
13701 rettv->vval.v_number = idx;
13705 rettv->vval.v_number =
13706 (varnumber_T)(regmatch.startp[0] - str);
13708 rettv->vval.v_number =
13709 (varnumber_T)(regmatch.endp[0] - str);
13710 rettv->vval.v_number += (varnumber_T)(str - expr);
13713 vim_free(regmatch.regprog);
13722 * "match()" function
13725 f_match(argvars, rettv)
13729 find_some_match(argvars, rettv, 1);
13733 * "matchadd()" function
13736 f_matchadd(argvars, rettv)
13740 #ifdef FEAT_SEARCH_EXTRA
13741 char_u buf[NUMBUFLEN];
13742 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
13743 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
13744 int prio = 10; /* default priority */
13748 rettv->vval.v_number = -1;
13750 if (grp == NULL || pat == NULL)
13752 if (argvars[2].v_type != VAR_UNKNOWN)
13754 prio = get_tv_number_chk(&argvars[2], &error);
13755 if (argvars[3].v_type != VAR_UNKNOWN)
13756 id = get_tv_number_chk(&argvars[3], &error);
13760 if (id >= 1 && id <= 3)
13762 EMSGN("E798: ID is reserved for \":match\": %ld", id);
13766 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
13771 * "matcharg()" function
13774 f_matcharg(argvars, rettv)
13778 if (rettv_list_alloc(rettv) == OK)
13780 #ifdef FEAT_SEARCH_EXTRA
13781 int id = get_tv_number(&argvars[0]);
13784 if (id >= 1 && id <= 3)
13786 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
13788 list_append_string(rettv->vval.v_list,
13789 syn_id2name(m->hlg_id), -1);
13790 list_append_string(rettv->vval.v_list, m->pattern, -1);
13794 list_append_string(rettv->vval.v_list, NUL, -1);
13795 list_append_string(rettv->vval.v_list, NUL, -1);
13803 * "matchdelete()" function
13806 f_matchdelete(argvars, rettv)
13810 #ifdef FEAT_SEARCH_EXTRA
13811 rettv->vval.v_number = match_delete(curwin,
13812 (int)get_tv_number(&argvars[0]), TRUE);
13817 * "matchend()" function
13820 f_matchend(argvars, rettv)
13824 find_some_match(argvars, rettv, 0);
13828 * "matchlist()" function
13831 f_matchlist(argvars, rettv)
13835 find_some_match(argvars, rettv, 3);
13839 * "matchstr()" function
13842 f_matchstr(argvars, rettv)
13846 find_some_match(argvars, rettv, 2);
13849 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
13852 max_min(argvars, rettv, domax)
13861 if (argvars[0].v_type == VAR_LIST)
13866 l = argvars[0].vval.v_list;
13872 n = get_tv_number_chk(&li->li_tv, &error);
13878 i = get_tv_number_chk(&li->li_tv, &error);
13879 if (domax ? i > n : i < n)
13885 else if (argvars[0].v_type == VAR_DICT)
13892 d = argvars[0].vval.v_dict;
13895 todo = (int)d->dv_hashtab.ht_used;
13896 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13898 if (!HASHITEM_EMPTY(hi))
13901 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
13907 else if (domax ? i > n : i < n)
13914 EMSG(_(e_listdictarg));
13915 rettv->vval.v_number = error ? 0 : n;
13922 f_max(argvars, rettv)
13926 max_min(argvars, rettv, TRUE);
13933 f_min(argvars, rettv)
13937 max_min(argvars, rettv, FALSE);
13940 static int mkdir_recurse __ARGS((char_u *dir, int prot));
13943 * Create the directory in which "dir" is located, and higher levels when
13947 mkdir_recurse(dir, prot)
13955 /* Get end of directory name in "dir".
13956 * We're done when it's "/" or "c:/". */
13957 p = gettail_sep(dir);
13958 if (p <= get_past_head(dir))
13961 /* If the directory exists we're done. Otherwise: create it.*/
13962 updir = vim_strnsave(dir, (int)(p - dir));
13965 if (mch_isdir(updir))
13967 else if (mkdir_recurse(updir, prot) == OK)
13968 r = vim_mkdir_emsg(updir, prot);
13975 * "mkdir()" function
13978 f_mkdir(argvars, rettv)
13983 char_u buf[NUMBUFLEN];
13986 rettv->vval.v_number = FAIL;
13987 if (check_restricted() || check_secure())
13990 dir = get_tv_string_buf(&argvars[0], buf);
13991 if (argvars[1].v_type != VAR_UNKNOWN)
13993 if (argvars[2].v_type != VAR_UNKNOWN)
13994 prot = get_tv_number_chk(&argvars[2], NULL);
13995 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
13996 mkdir_recurse(dir, prot);
13998 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
14003 * "mode()" function
14006 f_mode(argvars, rettv)
14019 buf[0] = VIsual_mode + 's' - 'v';
14021 buf[0] = VIsual_mode;
14025 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
14026 || State == CONFIRM)
14029 if (State == ASKMORE)
14031 else if (State == CONFIRM)
14034 else if (State == EXTERNCMD)
14036 else if (State & INSERT)
14038 #ifdef FEAT_VREPLACE
14039 if (State & VREPLACE_FLAG)
14046 if (State & REPLACE_FLAG)
14051 else if (State & CMDLINE)
14057 else if (exmode_active)
14069 /* Clear out the minor mode when the argument is not a non-zero number or
14070 * non-empty string. */
14071 if (!non_zero_arg(&argvars[0]))
14074 rettv->vval.v_string = vim_strsave(buf);
14075 rettv->v_type = VAR_STRING;
14078 #ifdef FEAT_MZSCHEME
14080 * "mzeval()" function
14083 f_mzeval(argvars, rettv)
14088 char_u buf[NUMBUFLEN];
14090 str = get_tv_string_buf(&argvars[0], buf);
14091 do_mzeval(str, rettv);
14096 * "nextnonblank()" function
14099 f_nextnonblank(argvars, rettv)
14105 for (lnum = get_tv_lnum(argvars); ; ++lnum)
14107 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
14112 if (*skipwhite(ml_get(lnum)) != NUL)
14115 rettv->vval.v_number = lnum;
14119 * "nr2char()" function
14122 f_nr2char(argvars, rettv)
14126 char_u buf[NUMBUFLEN];
14130 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
14134 buf[0] = (char_u)get_tv_number(&argvars[0]);
14137 rettv->v_type = VAR_STRING;
14138 rettv->vval.v_string = vim_strsave(buf);
14142 * "or(expr, expr)" function
14145 f_or(argvars, rettv)
14149 rettv->vval.v_number = get_tv_number_chk(&argvars[0], NULL)
14150 | get_tv_number_chk(&argvars[1], NULL);
14154 * "pathshorten()" function
14157 f_pathshorten(argvars, rettv)
14163 rettv->v_type = VAR_STRING;
14164 p = get_tv_string_chk(&argvars[0]);
14166 rettv->vval.v_string = NULL;
14169 p = vim_strsave(p);
14170 rettv->vval.v_string = p;
14181 f_pow(argvars, rettv)
14187 rettv->v_type = VAR_FLOAT;
14188 if (get_float_arg(argvars, &fx) == OK
14189 && get_float_arg(&argvars[1], &fy) == OK)
14190 rettv->vval.v_float = pow(fx, fy);
14192 rettv->vval.v_float = 0.0;
14197 * "prevnonblank()" function
14200 f_prevnonblank(argvars, rettv)
14206 lnum = get_tv_lnum(argvars);
14207 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
14210 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
14212 rettv->vval.v_number = lnum;
14215 #ifdef HAVE_STDARG_H
14216 /* This dummy va_list is here because:
14217 * - passing a NULL pointer doesn't work when va_list isn't a pointer
14218 * - locally in the function results in a "used before set" warning
14219 * - using va_start() to initialize it gives "function with fixed args" error */
14224 * "printf()" function
14227 f_printf(argvars, rettv)
14231 rettv->v_type = VAR_STRING;
14232 rettv->vval.v_string = NULL;
14233 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
14235 char_u buf[NUMBUFLEN];
14238 int saved_did_emsg = did_emsg;
14241 /* Get the required length, allocate the buffer and do it for real. */
14243 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
14244 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
14247 s = alloc(len + 1);
14250 rettv->vval.v_string = s;
14251 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
14254 did_emsg |= saved_did_emsg;
14260 * "pumvisible()" function
14263 f_pumvisible(argvars, rettv)
14264 typval_T *argvars UNUSED;
14265 typval_T *rettv UNUSED;
14267 #ifdef FEAT_INS_EXPAND
14269 rettv->vval.v_number = 1;
14274 * "range()" function
14277 f_range(argvars, rettv)
14287 start = get_tv_number_chk(&argvars[0], &error);
14288 if (argvars[1].v_type == VAR_UNKNOWN)
14295 end = get_tv_number_chk(&argvars[1], &error);
14296 if (argvars[2].v_type != VAR_UNKNOWN)
14297 stride = get_tv_number_chk(&argvars[2], &error);
14301 return; /* type error; errmsg already given */
14303 EMSG(_("E726: Stride is zero"));
14304 else if (stride > 0 ? end + 1 < start : end - 1 > start)
14305 EMSG(_("E727: Start past end"));
14308 if (rettv_list_alloc(rettv) == OK)
14309 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
14310 if (list_append_number(rettv->vval.v_list,
14311 (varnumber_T)i) == FAIL)
14317 * "readfile()" function
14320 f_readfile(argvars, rettv)
14324 int binary = FALSE;
14328 #define FREAD_SIZE 200 /* optimized for text lines */
14329 char_u buf[FREAD_SIZE];
14330 int readlen; /* size of last fread() */
14331 int buflen; /* nr of valid chars in buf[] */
14332 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
14333 int tolist; /* first byte in buf[] still to be put in list */
14334 int chop; /* how many CR to chop off */
14335 char_u *prev = NULL; /* previously read bytes, if any */
14336 int prevlen = 0; /* length of "prev" if not NULL */
14339 long maxline = MAXLNUM;
14342 if (argvars[1].v_type != VAR_UNKNOWN)
14344 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
14346 if (argvars[2].v_type != VAR_UNKNOWN)
14347 maxline = get_tv_number(&argvars[2]);
14350 if (rettv_list_alloc(rettv) == FAIL)
14353 /* Always open the file in binary mode, library functions have a mind of
14354 * their own about CR-LF conversion. */
14355 fname = get_tv_string(&argvars[0]);
14356 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
14358 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
14363 while (cnt < maxline || maxline < 0)
14365 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
14366 buflen = filtd + readlen;
14368 for ( ; filtd < buflen || readlen <= 0; ++filtd)
14370 if (readlen <= 0 || buf[filtd] == '\n')
14372 /* In binary mode add an empty list item when the last
14373 * non-empty line ends in a '\n'. */
14374 if (!binary && readlen == 0 && filtd == 0 && prev == NULL)
14377 /* Found end-of-line or end-of-file: add a text line to the
14381 while (filtd - chop - 1 >= tolist
14382 && buf[filtd - chop - 1] == '\r')
14384 len = filtd - tolist - chop;
14386 s = vim_strnsave(buf + tolist, len);
14389 s = alloc((unsigned)(prevlen + len + 1));
14392 mch_memmove(s, prev, prevlen);
14395 mch_memmove(s + prevlen, buf + tolist, len);
14396 s[prevlen + len] = NUL;
14399 tolist = filtd + 1;
14401 li = listitem_alloc();
14407 li->li_tv.v_type = VAR_STRING;
14408 li->li_tv.v_lock = 0;
14409 li->li_tv.vval.v_string = s;
14410 list_append(rettv->vval.v_list, li);
14412 if (++cnt >= maxline && maxline >= 0)
14417 else if (buf[filtd] == NUL)
14420 else if (buf[filtd] == 0xef
14422 && filtd + 2 < buflen
14424 && buf[filtd + 1] == 0xbb
14425 && buf[filtd + 2] == 0xbf)
14427 /* remove utf-8 byte order mark */
14428 mch_memmove(buf + filtd, buf + filtd + 3, buflen - filtd - 3);
14439 if (buflen >= FREAD_SIZE / 2)
14441 /* "buf" is full, need to move text to an allocated buffer */
14444 prev = vim_strnsave(buf, buflen);
14449 s = alloc((unsigned)(prevlen + buflen));
14452 mch_memmove(s, prev, prevlen);
14453 mch_memmove(s + prevlen, buf, buflen);
14464 mch_memmove(buf, buf + tolist, buflen - tolist);
14470 * For a negative line count use only the lines at the end of the file,
14474 while (cnt > -maxline)
14476 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
14484 #if defined(FEAT_RELTIME)
14485 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
14488 * Convert a List to proftime_T.
14489 * Return FAIL when there is something wrong.
14492 list2proftime(arg, tm)
14499 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
14500 || arg->vval.v_list->lv_len != 2)
14502 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
14503 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
14511 return error ? FAIL : OK;
14513 #endif /* FEAT_RELTIME */
14516 * "reltime()" function
14519 f_reltime(argvars, rettv)
14523 #ifdef FEAT_RELTIME
14527 if (argvars[0].v_type == VAR_UNKNOWN)
14529 /* No arguments: get current time. */
14530 profile_start(&res);
14532 else if (argvars[1].v_type == VAR_UNKNOWN)
14534 if (list2proftime(&argvars[0], &res) == FAIL)
14540 /* Two arguments: compute the difference. */
14541 if (list2proftime(&argvars[0], &start) == FAIL
14542 || list2proftime(&argvars[1], &res) == FAIL)
14544 profile_sub(&res, &start);
14547 if (rettv_list_alloc(rettv) == OK)
14558 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
14559 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
14565 * "reltimestr()" function
14568 f_reltimestr(argvars, rettv)
14572 #ifdef FEAT_RELTIME
14576 rettv->v_type = VAR_STRING;
14577 rettv->vval.v_string = NULL;
14578 #ifdef FEAT_RELTIME
14579 if (list2proftime(&argvars[0], &tm) == OK)
14580 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
14584 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
14585 static void make_connection __ARGS((void));
14586 static int check_connection __ARGS((void));
14591 if (X_DISPLAY == NULL
14597 x_force_connect = TRUE;
14599 x_force_connect = FALSE;
14607 if (X_DISPLAY == NULL)
14609 EMSG(_("E240: No connection to Vim server"));
14616 #ifdef FEAT_CLIENTSERVER
14617 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
14620 remote_common(argvars, rettv, expr)
14625 char_u *server_name;
14628 char_u buf[NUMBUFLEN];
14635 if (check_restricted() || check_secure())
14639 if (check_connection() == FAIL)
14643 server_name = get_tv_string_chk(&argvars[0]);
14644 if (server_name == NULL)
14645 return; /* type error; errmsg already given */
14646 keys = get_tv_string_buf(&argvars[1], buf);
14648 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14650 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
14655 EMSG(r); /* sending worked but evaluation failed */
14657 EMSG2(_("E241: Unable to send to %s"), server_name);
14661 rettv->vval.v_string = r;
14663 if (argvars[2].v_type != VAR_UNKNOWN)
14669 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
14670 v.di_tv.v_type = VAR_STRING;
14671 v.di_tv.vval.v_string = vim_strsave(str);
14672 idvar = get_tv_string_chk(&argvars[2]);
14674 set_var(idvar, &v.di_tv, FALSE);
14675 vim_free(v.di_tv.vval.v_string);
14681 * "remote_expr()" function
14684 f_remote_expr(argvars, rettv)
14685 typval_T *argvars UNUSED;
14688 rettv->v_type = VAR_STRING;
14689 rettv->vval.v_string = NULL;
14690 #ifdef FEAT_CLIENTSERVER
14691 remote_common(argvars, rettv, TRUE);
14696 * "remote_foreground()" function
14699 f_remote_foreground(argvars, rettv)
14700 typval_T *argvars UNUSED;
14701 typval_T *rettv UNUSED;
14703 #ifdef FEAT_CLIENTSERVER
14705 /* On Win32 it's done in this application. */
14707 char_u *server_name = get_tv_string_chk(&argvars[0]);
14709 if (server_name != NULL)
14710 serverForeground(server_name);
14713 /* Send a foreground() expression to the server. */
14714 argvars[1].v_type = VAR_STRING;
14715 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
14716 argvars[2].v_type = VAR_UNKNOWN;
14717 remote_common(argvars, rettv, TRUE);
14718 vim_free(argvars[1].vval.v_string);
14724 f_remote_peek(argvars, rettv)
14725 typval_T *argvars UNUSED;
14728 #ifdef FEAT_CLIENTSERVER
14736 if (check_restricted() || check_secure())
14738 rettv->vval.v_number = -1;
14741 serverid = get_tv_string_chk(&argvars[0]);
14742 if (serverid == NULL)
14744 rettv->vval.v_number = -1;
14745 return; /* type error; errmsg already given */
14748 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14750 rettv->vval.v_number = -1;
14753 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
14754 rettv->vval.v_number = (s != NULL);
14757 if (check_connection() == FAIL)
14760 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
14761 serverStrToWin(serverid), &s);
14764 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
14768 v.di_tv.v_type = VAR_STRING;
14769 v.di_tv.vval.v_string = vim_strsave(s);
14770 retvar = get_tv_string_chk(&argvars[1]);
14771 if (retvar != NULL)
14772 set_var(retvar, &v.di_tv, FALSE);
14773 vim_free(v.di_tv.vval.v_string);
14776 rettv->vval.v_number = -1;
14781 f_remote_read(argvars, rettv)
14782 typval_T *argvars UNUSED;
14787 #ifdef FEAT_CLIENTSERVER
14788 char_u *serverid = get_tv_string_chk(&argvars[0]);
14790 if (serverid != NULL && !check_restricted() && !check_secure())
14793 /* The server's HWND is encoded in the 'id' parameter */
14796 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14798 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
14801 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
14802 serverStrToWin(serverid), &r, FALSE) < 0)
14804 EMSG(_("E277: Unable to read a server reply"));
14807 rettv->v_type = VAR_STRING;
14808 rettv->vval.v_string = r;
14812 * "remote_send()" function
14815 f_remote_send(argvars, rettv)
14816 typval_T *argvars UNUSED;
14819 rettv->v_type = VAR_STRING;
14820 rettv->vval.v_string = NULL;
14821 #ifdef FEAT_CLIENTSERVER
14822 remote_common(argvars, rettv, FALSE);
14827 * "remove()" function
14830 f_remove(argvars, rettv)
14835 listitem_T *item, *item2;
14842 char *arg_errmsg = N_("remove() argument");
14844 if (argvars[0].v_type == VAR_DICT)
14846 if (argvars[2].v_type != VAR_UNKNOWN)
14847 EMSG2(_(e_toomanyarg), "remove()");
14848 else if ((d = argvars[0].vval.v_dict) != NULL
14849 && !tv_check_lock(d->dv_lock, (char_u *)_(arg_errmsg)))
14851 key = get_tv_string_chk(&argvars[1]);
14854 di = dict_find(d, key, -1);
14856 EMSG2(_(e_dictkey), key);
14859 *rettv = di->di_tv;
14860 init_tv(&di->di_tv);
14861 dictitem_remove(d, di);
14866 else if (argvars[0].v_type != VAR_LIST)
14867 EMSG2(_(e_listdictarg), "remove()");
14868 else if ((l = argvars[0].vval.v_list) != NULL
14869 && !tv_check_lock(l->lv_lock, (char_u *)_(arg_errmsg)))
14873 idx = get_tv_number_chk(&argvars[1], &error);
14875 ; /* type error: do nothing, errmsg already given */
14876 else if ((item = list_find(l, idx)) == NULL)
14877 EMSGN(_(e_listidx), idx);
14880 if (argvars[2].v_type == VAR_UNKNOWN)
14882 /* Remove one item, return its value. */
14883 list_remove(l, item, item);
14884 *rettv = item->li_tv;
14889 /* Remove range of items, return list with values. */
14890 end = get_tv_number_chk(&argvars[2], &error);
14892 ; /* type error: do nothing */
14893 else if ((item2 = list_find(l, end)) == NULL)
14894 EMSGN(_(e_listidx), end);
14899 for (li = item; li != NULL; li = li->li_next)
14905 if (li == NULL) /* didn't find "item2" after "item" */
14906 EMSG(_(e_invrange));
14909 list_remove(l, item, item2);
14910 if (rettv_list_alloc(rettv) == OK)
14912 l = rettv->vval.v_list;
14913 l->lv_first = item;
14914 l->lv_last = item2;
14915 item->li_prev = NULL;
14916 item2->li_next = NULL;
14927 * "rename({from}, {to})" function
14930 f_rename(argvars, rettv)
14934 char_u buf[NUMBUFLEN];
14936 if (check_restricted() || check_secure())
14937 rettv->vval.v_number = -1;
14939 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
14940 get_tv_string_buf(&argvars[1], buf));
14944 * "repeat()" function
14947 f_repeat(argvars, rettv)
14958 n = get_tv_number(&argvars[1]);
14959 if (argvars[0].v_type == VAR_LIST)
14961 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
14963 if (list_extend(rettv->vval.v_list,
14964 argvars[0].vval.v_list, NULL) == FAIL)
14969 p = get_tv_string(&argvars[0]);
14970 rettv->v_type = VAR_STRING;
14971 rettv->vval.v_string = NULL;
14973 slen = (int)STRLEN(p);
14978 r = alloc(len + 1);
14981 for (i = 0; i < n; i++)
14982 mch_memmove(r + i * slen, p, (size_t)slen);
14986 rettv->vval.v_string = r;
14991 * "resolve()" function
14994 f_resolve(argvars, rettv)
14999 #ifdef HAVE_READLINK
15000 char_u *buf = NULL;
15003 p = get_tv_string(&argvars[0]);
15004 #ifdef FEAT_SHORTCUT
15008 v = mch_resolve_shortcut(p);
15010 rettv->vval.v_string = v;
15012 rettv->vval.v_string = vim_strsave(p);
15015 # ifdef HAVE_READLINK
15019 char_u *remain = NULL;
15021 int is_relative_to_current = FALSE;
15022 int has_trailing_pathsep = FALSE;
15025 p = vim_strsave(p);
15027 if (p[0] == '.' && (vim_ispathsep(p[1])
15028 || (p[1] == '.' && (vim_ispathsep(p[2])))))
15029 is_relative_to_current = TRUE;
15032 if (len > 0 && after_pathsep(p, p + len))
15034 has_trailing_pathsep = TRUE;
15035 p[len - 1] = NUL; /* the trailing slash breaks readlink() */
15038 q = getnextcomp(p);
15041 /* Separate the first path component in "p", and keep the
15042 * remainder (beginning with the path separator). */
15043 remain = vim_strsave(q - 1);
15047 buf = alloc(MAXPATHL + 1);
15055 len = readlink((char *)p, (char *)buf, MAXPATHL);
15064 EMSG(_("E655: Too many symbolic links (cycle?)"));
15065 rettv->vval.v_string = NULL;
15069 /* Ensure that the result will have a trailing path separator
15070 * if the argument has one. */
15071 if (remain == NULL && has_trailing_pathsep)
15074 /* Separate the first path component in the link value and
15075 * concatenate the remainders. */
15076 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
15079 if (remain == NULL)
15080 remain = vim_strsave(q - 1);
15083 cpy = concat_str(q - 1, remain);
15094 if (q > p && *q == NUL)
15096 /* Ignore trailing path separator. */
15100 if (q > p && !mch_isFullName(buf))
15102 /* symlink is relative to directory of argument */
15103 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
15107 STRCPY(gettail(cpy), buf);
15115 p = vim_strsave(buf);
15119 if (remain == NULL)
15122 /* Append the first path component of "remain" to "p". */
15123 q = getnextcomp(remain + 1);
15124 len = q - remain - (*q != NUL);
15125 cpy = vim_strnsave(p, STRLEN(p) + len);
15128 STRNCAT(cpy, remain, len);
15132 /* Shorten "remain". */
15134 STRMOVE(remain, q - 1);
15142 /* If the result is a relative path name, make it explicitly relative to
15143 * the current directory if and only if the argument had this form. */
15144 if (!vim_ispathsep(*p))
15146 if (is_relative_to_current
15150 || vim_ispathsep(p[1])
15153 || vim_ispathsep(p[2]))))))
15155 /* Prepend "./". */
15156 cpy = concat_str((char_u *)"./", p);
15163 else if (!is_relative_to_current)
15165 /* Strip leading "./". */
15167 while (q[0] == '.' && vim_ispathsep(q[1]))
15174 /* Ensure that the result will have no trailing path separator
15175 * if the argument had none. But keep "/" or "//". */
15176 if (!has_trailing_pathsep)
15179 if (after_pathsep(p, q))
15180 *gettail_sep(p) = NUL;
15183 rettv->vval.v_string = p;
15186 rettv->vval.v_string = vim_strsave(p);
15190 simplify_filename(rettv->vval.v_string);
15192 #ifdef HAVE_READLINK
15196 rettv->v_type = VAR_STRING;
15200 * "reverse({list})" function
15203 f_reverse(argvars, rettv)
15208 listitem_T *li, *ni;
15210 if (argvars[0].v_type != VAR_LIST)
15211 EMSG2(_(e_listarg), "reverse()");
15212 else if ((l = argvars[0].vval.v_list) != NULL
15213 && !tv_check_lock(l->lv_lock, (char_u *)_("reverse() argument")))
15216 l->lv_first = l->lv_last = NULL;
15221 list_append(l, li);
15224 rettv->vval.v_list = l;
15225 rettv->v_type = VAR_LIST;
15227 l->lv_idx = l->lv_len - l->lv_idx - 1;
15231 #define SP_NOMOVE 0x01 /* don't move cursor */
15232 #define SP_REPEAT 0x02 /* repeat to find outer pair */
15233 #define SP_RETCOUNT 0x04 /* return matchcount */
15234 #define SP_SETPCMARK 0x08 /* set previous context mark */
15235 #define SP_START 0x10 /* accept match at start position */
15236 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
15237 #define SP_END 0x40 /* leave cursor at end of match */
15239 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
15242 * Get flags for a search function.
15243 * Possibly sets "p_ws".
15244 * Returns BACKWARD, FORWARD or zero (for an error).
15247 get_search_arg(varp, flagsp)
15253 char_u nbuf[NUMBUFLEN];
15256 if (varp->v_type != VAR_UNKNOWN)
15258 flags = get_tv_string_buf_chk(varp, nbuf);
15260 return 0; /* type error; errmsg already given */
15261 while (*flags != NUL)
15265 case 'b': dir = BACKWARD; break;
15266 case 'w': p_ws = TRUE; break;
15267 case 'W': p_ws = FALSE; break;
15269 if (flagsp != NULL)
15272 case 'c': mask = SP_START; break;
15273 case 'e': mask = SP_END; break;
15274 case 'm': mask = SP_RETCOUNT; break;
15275 case 'n': mask = SP_NOMOVE; break;
15276 case 'p': mask = SP_SUBPAT; break;
15277 case 'r': mask = SP_REPEAT; break;
15278 case 's': mask = SP_SETPCMARK; break;
15282 EMSG2(_(e_invarg2), flags);
15297 * Shared by search() and searchpos() functions
15300 search_cmn(argvars, match_pos, flagsp)
15309 int save_p_ws = p_ws;
15311 int retval = 0; /* default: FAIL */
15312 long lnum_stop = 0;
15314 #ifdef FEAT_RELTIME
15315 long time_limit = 0;
15317 int options = SEARCH_KEEP;
15320 pat = get_tv_string(&argvars[0]);
15321 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
15325 if (flags & SP_START)
15326 options |= SEARCH_START;
15327 if (flags & SP_END)
15328 options |= SEARCH_END;
15330 /* Optional arguments: line number to stop searching and timeout. */
15331 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
15333 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
15336 #ifdef FEAT_RELTIME
15337 if (argvars[3].v_type != VAR_UNKNOWN)
15339 time_limit = get_tv_number_chk(&argvars[3], NULL);
15340 if (time_limit < 0)
15346 #ifdef FEAT_RELTIME
15347 /* Set the time limit, if there is one. */
15348 profile_setlimit(time_limit, &tm);
15352 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
15353 * Check to make sure only those flags are set.
15354 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
15355 * flags cannot be set. Check for that condition also.
15357 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
15358 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
15360 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
15364 pos = save_cursor = curwin->w_cursor;
15365 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15366 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
15367 if (subpatnum != FAIL)
15369 if (flags & SP_SUBPAT)
15370 retval = subpatnum;
15373 if (flags & SP_SETPCMARK)
15375 curwin->w_cursor = pos;
15376 if (match_pos != NULL)
15378 /* Store the match cursor position */
15379 match_pos->lnum = pos.lnum;
15380 match_pos->col = pos.col + 1;
15382 /* "/$" will put the cursor after the end of the line, may need to
15383 * correct that here */
15387 /* If 'n' flag is used: restore cursor position. */
15388 if (flags & SP_NOMOVE)
15389 curwin->w_cursor = save_cursor;
15391 curwin->w_set_curswant = TRUE;
15400 * "round({float})" function
15403 f_round(argvars, rettv)
15409 rettv->v_type = VAR_FLOAT;
15410 if (get_float_arg(argvars, &f) == OK)
15411 /* round() is not in C90, use ceil() or floor() instead. */
15412 rettv->vval.v_float = f > 0 ? floor(f + 0.5) : ceil(f - 0.5);
15414 rettv->vval.v_float = 0.0;
15419 * "search()" function
15422 f_search(argvars, rettv)
15428 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
15432 * "searchdecl()" function
15435 f_searchdecl(argvars, rettv)
15444 rettv->vval.v_number = 1; /* default: FAIL */
15446 name = get_tv_string_chk(&argvars[0]);
15447 if (argvars[1].v_type != VAR_UNKNOWN)
15449 locally = get_tv_number_chk(&argvars[1], &error) == 0;
15450 if (!error && argvars[2].v_type != VAR_UNKNOWN)
15451 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
15453 if (!error && name != NULL)
15454 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
15455 locally, thisblock, SEARCH_KEEP) == FAIL;
15459 * Used by searchpair() and searchpairpos()
15462 searchpair_cmn(argvars, match_pos)
15466 char_u *spat, *mpat, *epat;
15468 int save_p_ws = p_ws;
15471 char_u nbuf1[NUMBUFLEN];
15472 char_u nbuf2[NUMBUFLEN];
15473 char_u nbuf3[NUMBUFLEN];
15474 int retval = 0; /* default: FAIL */
15475 long lnum_stop = 0;
15476 long time_limit = 0;
15478 /* Get the three pattern arguments: start, middle, end. */
15479 spat = get_tv_string_chk(&argvars[0]);
15480 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
15481 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
15482 if (spat == NULL || mpat == NULL || epat == NULL)
15483 goto theend; /* type error */
15485 /* Handle the optional fourth argument: flags */
15486 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
15490 /* Don't accept SP_END or SP_SUBPAT.
15491 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
15493 if ((flags & (SP_END | SP_SUBPAT)) != 0
15494 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
15496 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
15500 /* Using 'r' implies 'W', otherwise it doesn't work. */
15501 if (flags & SP_REPEAT)
15504 /* Optional fifth argument: skip expression */
15505 if (argvars[3].v_type == VAR_UNKNOWN
15506 || argvars[4].v_type == VAR_UNKNOWN)
15507 skip = (char_u *)"";
15510 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
15511 if (argvars[5].v_type != VAR_UNKNOWN)
15513 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
15516 #ifdef FEAT_RELTIME
15517 if (argvars[6].v_type != VAR_UNKNOWN)
15519 time_limit = get_tv_number_chk(&argvars[6], NULL);
15520 if (time_limit < 0)
15527 goto theend; /* type error */
15529 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
15530 match_pos, lnum_stop, time_limit);
15539 * "searchpair()" function
15542 f_searchpair(argvars, rettv)
15546 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
15550 * "searchpairpos()" function
15553 f_searchpairpos(argvars, rettv)
15561 if (rettv_list_alloc(rettv) == FAIL)
15564 if (searchpair_cmn(argvars, &match_pos) > 0)
15566 lnum = match_pos.lnum;
15567 col = match_pos.col;
15570 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15571 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15575 * Search for a start/middle/end thing.
15576 * Used by searchpair(), see its documentation for the details.
15577 * Returns 0 or -1 for no match,
15580 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
15581 lnum_stop, time_limit)
15582 char_u *spat; /* start pattern */
15583 char_u *mpat; /* middle pattern */
15584 char_u *epat; /* end pattern */
15585 int dir; /* BACKWARD or FORWARD */
15586 char_u *skip; /* skip expression */
15587 int flags; /* SP_SETPCMARK and other SP_ values */
15589 linenr_T lnum_stop; /* stop at this line if not zero */
15590 long time_limit; /* stop after this many msec */
15593 char_u *pat, *pat2 = NULL, *pat3 = NULL;
15604 int options = SEARCH_KEEP;
15607 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15609 p_cpo = empty_option;
15611 #ifdef FEAT_RELTIME
15612 /* Set the time limit, if there is one. */
15613 profile_setlimit(time_limit, &tm);
15616 /* Make two search patterns: start/end (pat2, for in nested pairs) and
15617 * start/middle/end (pat3, for the top pair). */
15618 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
15619 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
15620 if (pat2 == NULL || pat3 == NULL)
15622 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
15624 STRCPY(pat3, pat2);
15626 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
15628 if (flags & SP_START)
15629 options |= SEARCH_START;
15631 save_cursor = curwin->w_cursor;
15632 pos = curwin->w_cursor;
15633 clearpos(&firstpos);
15634 clearpos(&foundpos);
15638 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15639 options, RE_SEARCH, lnum_stop, &tm);
15640 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
15641 /* didn't find it or found the first match again: FAIL */
15644 if (firstpos.lnum == 0)
15646 if (equalpos(pos, foundpos))
15648 /* Found the same position again. Can happen with a pattern that
15649 * has "\zs" at the end and searching backwards. Advance one
15650 * character and try again. */
15651 if (dir == BACKWARD)
15658 /* clear the start flag to avoid getting stuck here */
15659 options &= ~SEARCH_START;
15661 /* If the skip pattern matches, ignore this match. */
15664 save_pos = curwin->w_cursor;
15665 curwin->w_cursor = pos;
15666 r = eval_to_bool(skip, &err, NULL, FALSE);
15667 curwin->w_cursor = save_pos;
15670 /* Evaluating {skip} caused an error, break here. */
15671 curwin->w_cursor = save_cursor;
15679 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
15681 /* Found end when searching backwards or start when searching
15682 * forward: nested pair. */
15684 pat = pat2; /* nested, don't search for middle */
15688 /* Found end when searching forward or start when searching
15689 * backward: end of (nested) pair; or found middle in outer pair. */
15691 pat = pat3; /* outer level, search for middle */
15696 /* Found the match: return matchcount or line number. */
15697 if (flags & SP_RETCOUNT)
15701 if (flags & SP_SETPCMARK)
15703 curwin->w_cursor = pos;
15704 if (!(flags & SP_REPEAT))
15706 nest = 1; /* search for next unmatched */
15710 if (match_pos != NULL)
15712 /* Store the match cursor position */
15713 match_pos->lnum = curwin->w_cursor.lnum;
15714 match_pos->col = curwin->w_cursor.col + 1;
15717 /* If 'n' flag is used or search failed: restore cursor position. */
15718 if ((flags & SP_NOMOVE) || retval == 0)
15719 curwin->w_cursor = save_cursor;
15724 if (p_cpo == empty_option)
15727 /* Darn, evaluating the {skip} expression changed the value. */
15728 free_string_option(save_cpo);
15734 * "searchpos()" function
15737 f_searchpos(argvars, rettv)
15747 if (rettv_list_alloc(rettv) == FAIL)
15750 n = search_cmn(argvars, &match_pos, &flags);
15753 lnum = match_pos.lnum;
15754 col = match_pos.col;
15757 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15758 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15759 if (flags & SP_SUBPAT)
15760 list_append_number(rettv->vval.v_list, (varnumber_T)n);
15765 f_server2client(argvars, rettv)
15766 typval_T *argvars UNUSED;
15769 #ifdef FEAT_CLIENTSERVER
15770 char_u buf[NUMBUFLEN];
15771 char_u *server = get_tv_string_chk(&argvars[0]);
15772 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
15774 rettv->vval.v_number = -1;
15775 if (server == NULL || reply == NULL)
15777 if (check_restricted() || check_secure())
15780 if (check_connection() == FAIL)
15784 if (serverSendReply(server, reply) < 0)
15786 EMSG(_("E258: Unable to send to client"));
15789 rettv->vval.v_number = 0;
15791 rettv->vval.v_number = -1;
15796 f_serverlist(argvars, rettv)
15797 typval_T *argvars UNUSED;
15802 #ifdef FEAT_CLIENTSERVER
15804 r = serverGetVimNames();
15807 if (X_DISPLAY != NULL)
15808 r = serverGetVimNames(X_DISPLAY);
15811 rettv->v_type = VAR_STRING;
15812 rettv->vval.v_string = r;
15816 * "setbufvar()" function
15819 f_setbufvar(argvars, rettv)
15821 typval_T *rettv UNUSED;
15825 char_u *varname, *bufvarname;
15827 char_u nbuf[NUMBUFLEN];
15829 if (check_restricted() || check_secure())
15831 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
15832 varname = get_tv_string_chk(&argvars[1]);
15833 buf = get_buf_tv(&argvars[0]);
15834 varp = &argvars[2];
15836 if (buf != NULL && varname != NULL && varp != NULL)
15838 /* set curbuf to be our buf, temporarily */
15839 aucmd_prepbuf(&aco, buf);
15841 if (*varname == '&')
15848 numval = get_tv_number_chk(varp, &error);
15849 strval = get_tv_string_buf_chk(varp, nbuf);
15850 if (!error && strval != NULL)
15851 set_option_value(varname, numval, strval, OPT_LOCAL);
15855 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
15856 if (bufvarname != NULL)
15858 STRCPY(bufvarname, "b:");
15859 STRCPY(bufvarname + 2, varname);
15860 set_var(bufvarname, varp, TRUE);
15861 vim_free(bufvarname);
15865 /* reset notion of buffer */
15866 aucmd_restbuf(&aco);
15871 * "setcmdpos()" function
15874 f_setcmdpos(argvars, rettv)
15878 int pos = (int)get_tv_number(&argvars[0]) - 1;
15881 rettv->vval.v_number = set_cmdline_pos(pos);
15885 * "setline()" function
15888 f_setline(argvars, rettv)
15893 char_u *line = NULL;
15895 listitem_T *li = NULL;
15897 linenr_T lcount = curbuf->b_ml.ml_line_count;
15899 lnum = get_tv_lnum(&argvars[0]);
15900 if (argvars[1].v_type == VAR_LIST)
15902 l = argvars[1].vval.v_list;
15906 line = get_tv_string_chk(&argvars[1]);
15908 /* default result is zero == OK */
15913 /* list argument, get next string */
15916 line = get_tv_string_chk(&li->li_tv);
15920 rettv->vval.v_number = 1; /* FAIL */
15921 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
15923 if (lnum <= curbuf->b_ml.ml_line_count)
15925 /* existing line, replace it */
15926 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
15928 changed_bytes(lnum, 0);
15929 if (lnum == curwin->w_cursor.lnum)
15930 check_cursor_col();
15931 rettv->vval.v_number = 0; /* OK */
15934 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
15936 /* lnum is one past the last line, append the line */
15938 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
15939 rettv->vval.v_number = 0; /* OK */
15942 if (l == NULL) /* only one string argument */
15948 appended_lines_mark(lcount, added);
15951 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
15954 * Used by "setqflist()" and "setloclist()" functions
15957 set_qf_ll_list(wp, list_arg, action_arg, rettv)
15959 typval_T *list_arg UNUSED;
15960 typval_T *action_arg UNUSED;
15963 #ifdef FEAT_QUICKFIX
15968 rettv->vval.v_number = -1;
15970 #ifdef FEAT_QUICKFIX
15971 if (list_arg->v_type != VAR_LIST)
15972 EMSG(_(e_listreq));
15975 list_T *l = list_arg->vval.v_list;
15977 if (action_arg->v_type == VAR_STRING)
15979 act = get_tv_string_chk(action_arg);
15981 return; /* type error; errmsg already given */
15982 if (*act == 'a' || *act == 'r')
15986 if (l != NULL && set_errorlist(wp, l, action, NULL) == OK)
15987 rettv->vval.v_number = 0;
15993 * "setloclist()" function
15996 f_setloclist(argvars, rettv)
16002 rettv->vval.v_number = -1;
16004 win = find_win_by_nr(&argvars[0], NULL);
16006 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
16010 * "setmatches()" function
16013 f_setmatches(argvars, rettv)
16017 #ifdef FEAT_SEARCH_EXTRA
16022 rettv->vval.v_number = -1;
16023 if (argvars[0].v_type != VAR_LIST)
16025 EMSG(_(e_listreq));
16028 if ((l = argvars[0].vval.v_list) != NULL)
16031 /* To some extent make sure that we are dealing with a list from
16032 * "getmatches()". */
16036 if (li->li_tv.v_type != VAR_DICT
16037 || (d = li->li_tv.vval.v_dict) == NULL)
16042 if (!(dict_find(d, (char_u *)"group", -1) != NULL
16043 && dict_find(d, (char_u *)"pattern", -1) != NULL
16044 && dict_find(d, (char_u *)"priority", -1) != NULL
16045 && dict_find(d, (char_u *)"id", -1) != NULL))
16053 clear_matches(curwin);
16057 d = li->li_tv.vval.v_dict;
16058 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
16059 get_dict_string(d, (char_u *)"pattern", FALSE),
16060 (int)get_dict_number(d, (char_u *)"priority"),
16061 (int)get_dict_number(d, (char_u *)"id"));
16064 rettv->vval.v_number = 0;
16070 * "setpos()" function
16073 f_setpos(argvars, rettv)
16081 rettv->vval.v_number = -1;
16082 name = get_tv_string_chk(argvars);
16085 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
16089 if (name[0] == '.' && name[1] == NUL)
16092 if (fnum == curbuf->b_fnum)
16094 curwin->w_cursor = pos;
16096 rettv->vval.v_number = 0;
16101 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
16104 if (setmark_pos(name[1], &pos, fnum) == OK)
16105 rettv->vval.v_number = 0;
16114 * "setqflist()" function
16117 f_setqflist(argvars, rettv)
16121 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
16125 * "setreg()" function
16128 f_setreg(argvars, rettv)
16133 char_u *strregname;
16144 strregname = get_tv_string_chk(argvars);
16145 rettv->vval.v_number = 1; /* FAIL is default */
16147 if (strregname == NULL)
16148 return; /* type error; errmsg already given */
16149 regname = *strregname;
16150 if (regname == 0 || regname == '@')
16152 else if (regname == '=')
16155 if (argvars[2].v_type != VAR_UNKNOWN)
16157 stropt = get_tv_string_chk(&argvars[2]);
16158 if (stropt == NULL)
16159 return; /* type error */
16160 for (; *stropt != NUL; ++stropt)
16163 case 'a': case 'A': /* append */
16166 case 'v': case 'c': /* character-wise selection */
16169 case 'V': case 'l': /* line-wise selection */
16173 case 'b': case Ctrl_V: /* block-wise selection */
16174 yank_type = MBLOCK;
16175 if (VIM_ISDIGIT(stropt[1]))
16178 block_len = getdigits(&stropt) - 1;
16186 strval = get_tv_string_chk(&argvars[1]);
16187 if (strval != NULL)
16188 write_reg_contents_ex(regname, strval, -1,
16189 append, yank_type, block_len);
16190 rettv->vval.v_number = 0;
16194 * "settabvar()" function
16197 f_settabvar(argvars, rettv)
16201 tabpage_T *save_curtab;
16202 char_u *varname, *tabvarname;
16206 rettv->vval.v_number = 0;
16208 if (check_restricted() || check_secure())
16211 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
16212 varname = get_tv_string_chk(&argvars[1]);
16213 varp = &argvars[2];
16215 if (tp != NULL && varname != NULL && varp != NULL)
16217 save_curtab = curtab;
16218 goto_tabpage_tp(tp);
16220 tabvarname = alloc((unsigned)STRLEN(varname) + 3);
16221 if (tabvarname != NULL)
16223 STRCPY(tabvarname, "t:");
16224 STRCPY(tabvarname + 2, varname);
16225 set_var(tabvarname, varp, TRUE);
16226 vim_free(tabvarname);
16229 /* Restore current tabpage */
16230 if (valid_tabpage(save_curtab))
16231 goto_tabpage_tp(save_curtab);
16236 * "settabwinvar()" function
16239 f_settabwinvar(argvars, rettv)
16243 setwinvar(argvars, rettv, 1);
16247 * "setwinvar()" function
16250 f_setwinvar(argvars, rettv)
16254 setwinvar(argvars, rettv, 0);
16258 * "setwinvar()" and "settabwinvar()" functions
16261 setwinvar(argvars, rettv, off)
16263 typval_T *rettv UNUSED;
16267 #ifdef FEAT_WINDOWS
16268 win_T *save_curwin;
16269 tabpage_T *save_curtab;
16271 char_u *varname, *winvarname;
16273 char_u nbuf[NUMBUFLEN];
16276 if (check_restricted() || check_secure())
16279 #ifdef FEAT_WINDOWS
16281 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
16285 win = find_win_by_nr(&argvars[off], tp);
16286 varname = get_tv_string_chk(&argvars[off + 1]);
16287 varp = &argvars[off + 2];
16289 if (win != NULL && varname != NULL && varp != NULL)
16291 #ifdef FEAT_WINDOWS
16292 /* set curwin to be our win, temporarily */
16293 save_curwin = curwin;
16294 save_curtab = curtab;
16295 goto_tabpage_tp(tp);
16296 if (!win_valid(win))
16299 curbuf = curwin->w_buffer;
16302 if (*varname == '&')
16309 numval = get_tv_number_chk(varp, &error);
16310 strval = get_tv_string_buf_chk(varp, nbuf);
16311 if (!error && strval != NULL)
16312 set_option_value(varname, numval, strval, OPT_LOCAL);
16316 winvarname = alloc((unsigned)STRLEN(varname) + 3);
16317 if (winvarname != NULL)
16319 STRCPY(winvarname, "w:");
16320 STRCPY(winvarname + 2, varname);
16321 set_var(winvarname, varp, TRUE);
16322 vim_free(winvarname);
16326 #ifdef FEAT_WINDOWS
16327 /* Restore current tabpage and window, if still valid (autocomands can
16328 * make them invalid). */
16329 if (valid_tabpage(save_curtab))
16330 goto_tabpage_tp(save_curtab);
16331 if (win_valid(save_curwin))
16333 curwin = save_curwin;
16334 curbuf = curwin->w_buffer;
16341 * "shellescape({string})" function
16344 f_shellescape(argvars, rettv)
16348 rettv->vval.v_string = vim_strsave_shellescape(
16349 get_tv_string(&argvars[0]), non_zero_arg(&argvars[1]));
16350 rettv->v_type = VAR_STRING;
16354 * "simplify()" function
16357 f_simplify(argvars, rettv)
16363 p = get_tv_string(&argvars[0]);
16364 rettv->vval.v_string = vim_strsave(p);
16365 simplify_filename(rettv->vval.v_string); /* simplify in place */
16366 rettv->v_type = VAR_STRING;
16374 f_sin(argvars, rettv)
16380 rettv->v_type = VAR_FLOAT;
16381 if (get_float_arg(argvars, &f) == OK)
16382 rettv->vval.v_float = sin(f);
16384 rettv->vval.v_float = 0.0;
16388 * "sinh()" function
16391 f_sinh(argvars, rettv)
16397 rettv->v_type = VAR_FLOAT;
16398 if (get_float_arg(argvars, &f) == OK)
16399 rettv->vval.v_float = sinh(f);
16401 rettv->vval.v_float = 0.0;
16406 #ifdef __BORLANDC__
16409 item_compare __ARGS((const void *s1, const void *s2));
16411 #ifdef __BORLANDC__
16414 item_compare2 __ARGS((const void *s1, const void *s2));
16416 static int item_compare_ic;
16417 static char_u *item_compare_func;
16418 static dict_T *item_compare_selfdict;
16419 static int item_compare_func_err;
16420 #define ITEM_COMPARE_FAIL 999
16423 * Compare functions for f_sort() below.
16426 #ifdef __BORLANDC__
16429 item_compare(s1, s2)
16434 char_u *tofree1, *tofree2;
16436 char_u numbuf1[NUMBUFLEN];
16437 char_u numbuf2[NUMBUFLEN];
16439 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
16440 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
16445 if (item_compare_ic)
16446 res = STRICMP(p1, p2);
16448 res = STRCMP(p1, p2);
16455 #ifdef __BORLANDC__
16458 item_compare2(s1, s2)
16467 /* shortcut after failure in previous call; compare all items equal */
16468 if (item_compare_func_err)
16471 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
16472 * in the copy without changing the original list items. */
16473 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
16474 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
16476 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
16477 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
16478 &rettv, 2, argv, 0L, 0L, &dummy, TRUE,
16479 item_compare_selfdict);
16480 clear_tv(&argv[0]);
16481 clear_tv(&argv[1]);
16484 res = ITEM_COMPARE_FAIL;
16486 res = get_tv_number_chk(&rettv, &item_compare_func_err);
16487 if (item_compare_func_err)
16488 res = ITEM_COMPARE_FAIL; /* return value has wrong type */
16494 * "sort({list})" function
16497 f_sort(argvars, rettv)
16507 if (argvars[0].v_type != VAR_LIST)
16508 EMSG2(_(e_listarg), "sort()");
16511 l = argvars[0].vval.v_list;
16512 if (l == NULL || tv_check_lock(l->lv_lock,
16513 (char_u *)_("sort() argument")))
16515 rettv->vval.v_list = l;
16516 rettv->v_type = VAR_LIST;
16521 return; /* short list sorts pretty quickly */
16523 item_compare_ic = FALSE;
16524 item_compare_func = NULL;
16525 item_compare_selfdict = NULL;
16526 if (argvars[1].v_type != VAR_UNKNOWN)
16528 /* optional second argument: {func} */
16529 if (argvars[1].v_type == VAR_FUNC)
16530 item_compare_func = argvars[1].vval.v_string;
16535 i = get_tv_number_chk(&argvars[1], &error);
16537 return; /* type error; errmsg already given */
16539 item_compare_ic = TRUE;
16541 item_compare_func = get_tv_string(&argvars[1]);
16544 if (argvars[2].v_type != VAR_UNKNOWN)
16546 /* optional third argument: {dict} */
16547 if (argvars[2].v_type != VAR_DICT)
16549 EMSG(_(e_dictreq));
16552 item_compare_selfdict = argvars[2].vval.v_dict;
16556 /* Make an array with each entry pointing to an item in the List. */
16557 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
16561 for (li = l->lv_first; li != NULL; li = li->li_next)
16564 item_compare_func_err = FALSE;
16565 /* test the compare function */
16566 if (item_compare_func != NULL
16567 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
16568 == ITEM_COMPARE_FAIL)
16569 EMSG(_("E702: Sort compare function failed"));
16572 /* Sort the array with item pointers. */
16573 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
16574 item_compare_func == NULL ? item_compare : item_compare2);
16576 if (!item_compare_func_err)
16578 /* Clear the List and append the items in the sorted order. */
16579 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
16581 for (i = 0; i < len; ++i)
16582 list_append(l, ptrs[i]);
16591 * "soundfold({word})" function
16594 f_soundfold(argvars, rettv)
16600 rettv->v_type = VAR_STRING;
16601 s = get_tv_string(&argvars[0]);
16603 rettv->vval.v_string = eval_soundfold(s);
16605 rettv->vval.v_string = vim_strsave(s);
16610 * "spellbadword()" function
16613 f_spellbadword(argvars, rettv)
16614 typval_T *argvars UNUSED;
16617 char_u *word = (char_u *)"";
16618 hlf_T attr = HLF_COUNT;
16621 if (rettv_list_alloc(rettv) == FAIL)
16625 if (argvars[0].v_type == VAR_UNKNOWN)
16627 /* Find the start and length of the badly spelled word. */
16628 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
16630 word = ml_get_cursor();
16632 else if (curwin->w_p_spell && *curbuf->b_s.b_p_spl != NUL)
16634 char_u *str = get_tv_string_chk(&argvars[0]);
16639 /* Check the argument for spelling. */
16640 while (*str != NUL)
16642 len = spell_check(curwin, str, &attr, &capcol, FALSE);
16643 if (attr != HLF_COUNT)
16654 list_append_string(rettv->vval.v_list, word, len);
16655 list_append_string(rettv->vval.v_list, (char_u *)(
16656 attr == HLF_SPB ? "bad" :
16657 attr == HLF_SPR ? "rare" :
16658 attr == HLF_SPL ? "local" :
16659 attr == HLF_SPC ? "caps" :
16664 * "spellsuggest()" function
16667 f_spellsuggest(argvars, rettv)
16668 typval_T *argvars UNUSED;
16673 int typeerr = FALSE;
16678 int need_capital = FALSE;
16681 if (rettv_list_alloc(rettv) == FAIL)
16685 if (curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL)
16687 str = get_tv_string(&argvars[0]);
16688 if (argvars[1].v_type != VAR_UNKNOWN)
16690 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
16693 if (argvars[2].v_type != VAR_UNKNOWN)
16695 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
16703 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
16705 for (i = 0; i < ga.ga_len; ++i)
16707 str = ((char_u **)ga.ga_data)[i];
16709 li = listitem_alloc();
16714 li->li_tv.v_type = VAR_STRING;
16715 li->li_tv.v_lock = 0;
16716 li->li_tv.vval.v_string = str;
16717 list_append(rettv->vval.v_list, li);
16726 f_split(argvars, rettv)
16732 char_u *pat = NULL;
16733 regmatch_T regmatch;
16734 char_u patbuf[NUMBUFLEN];
16738 int keepempty = FALSE;
16739 int typeerr = FALSE;
16741 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
16743 p_cpo = (char_u *)"";
16745 str = get_tv_string(&argvars[0]);
16746 if (argvars[1].v_type != VAR_UNKNOWN)
16748 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16751 if (argvars[2].v_type != VAR_UNKNOWN)
16752 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
16754 if (pat == NULL || *pat == NUL)
16755 pat = (char_u *)"[\\x01- ]\\+";
16757 if (rettv_list_alloc(rettv) == FAIL)
16762 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
16763 if (regmatch.regprog != NULL)
16765 regmatch.rm_ic = FALSE;
16766 while (*str != NUL || keepempty)
16769 match = FALSE; /* empty item at the end */
16771 match = vim_regexec_nl(®match, str, col);
16773 end = regmatch.startp[0];
16775 end = str + STRLEN(str);
16776 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
16777 && *str != NUL && match && end < regmatch.endp[0]))
16779 if (list_append_string(rettv->vval.v_list, str,
16780 (int)(end - str)) == FAIL)
16785 /* Advance to just after the match. */
16786 if (regmatch.endp[0] > str)
16790 /* Don't get stuck at the same match. */
16792 col = (*mb_ptr2len)(regmatch.endp[0]);
16797 str = regmatch.endp[0];
16800 vim_free(regmatch.regprog);
16808 * "sqrt()" function
16811 f_sqrt(argvars, rettv)
16817 rettv->v_type = VAR_FLOAT;
16818 if (get_float_arg(argvars, &f) == OK)
16819 rettv->vval.v_float = sqrt(f);
16821 rettv->vval.v_float = 0.0;
16825 * "str2float()" function
16828 f_str2float(argvars, rettv)
16832 char_u *p = skipwhite(get_tv_string(&argvars[0]));
16835 p = skipwhite(p + 1);
16836 (void)string2float(p, &rettv->vval.v_float);
16837 rettv->v_type = VAR_FLOAT;
16842 * "str2nr()" function
16845 f_str2nr(argvars, rettv)
16853 if (argvars[1].v_type != VAR_UNKNOWN)
16855 base = get_tv_number(&argvars[1]);
16856 if (base != 8 && base != 10 && base != 16)
16863 p = skipwhite(get_tv_string(&argvars[0]));
16865 p = skipwhite(p + 1);
16866 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
16867 rettv->vval.v_number = n;
16870 #ifdef HAVE_STRFTIME
16872 * "strftime({format}[, {time}])" function
16875 f_strftime(argvars, rettv)
16879 char_u result_buf[256];
16880 struct tm *curtime;
16884 rettv->v_type = VAR_STRING;
16886 p = get_tv_string(&argvars[0]);
16887 if (argvars[1].v_type == VAR_UNKNOWN)
16888 seconds = time(NULL);
16890 seconds = (time_t)get_tv_number(&argvars[1]);
16891 curtime = localtime(&seconds);
16892 /* MSVC returns NULL for an invalid value of seconds. */
16893 if (curtime == NULL)
16894 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
16901 conv.vc_type = CONV_NONE;
16902 enc = enc_locale();
16903 convert_setup(&conv, p_enc, enc);
16904 if (conv.vc_type != CONV_NONE)
16905 p = string_convert(&conv, p, NULL);
16908 (void)strftime((char *)result_buf, sizeof(result_buf),
16909 (char *)p, curtime);
16911 result_buf[0] = NUL;
16914 if (conv.vc_type != CONV_NONE)
16916 convert_setup(&conv, enc, p_enc);
16917 if (conv.vc_type != CONV_NONE)
16918 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
16921 rettv->vval.v_string = vim_strsave(result_buf);
16924 /* Release conversion descriptors */
16925 convert_setup(&conv, NULL, NULL);
16933 * "stridx()" function
16936 f_stridx(argvars, rettv)
16940 char_u buf[NUMBUFLEN];
16943 char_u *save_haystack;
16947 needle = get_tv_string_chk(&argvars[1]);
16948 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
16949 rettv->vval.v_number = -1;
16950 if (needle == NULL || haystack == NULL)
16951 return; /* type error; errmsg already given */
16953 if (argvars[2].v_type != VAR_UNKNOWN)
16957 start_idx = get_tv_number_chk(&argvars[2], &error);
16958 if (error || start_idx >= (int)STRLEN(haystack))
16960 if (start_idx >= 0)
16961 haystack += start_idx;
16964 pos = (char_u *)strstr((char *)haystack, (char *)needle);
16966 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
16970 * "string()" function
16973 f_string(argvars, rettv)
16978 char_u numbuf[NUMBUFLEN];
16980 rettv->v_type = VAR_STRING;
16981 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
16982 /* Make a copy if we have a value but it's not in allocated memory. */
16983 if (rettv->vval.v_string != NULL && tofree == NULL)
16984 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
16988 * "strlen()" function
16991 f_strlen(argvars, rettv)
16995 rettv->vval.v_number = (varnumber_T)(STRLEN(
16996 get_tv_string(&argvars[0])));
17000 * "strchars()" function
17003 f_strchars(argvars, rettv)
17007 char_u *s = get_tv_string(&argvars[0]);
17009 varnumber_T len = 0;
17013 mb_cptr2char_adv(&s);
17016 rettv->vval.v_number = len;
17018 rettv->vval.v_number = (varnumber_T)(STRLEN(s));
17023 * "strdisplaywidth()" function
17026 f_strdisplaywidth(argvars, rettv)
17030 char_u *s = get_tv_string(&argvars[0]);
17033 if (argvars[1].v_type != VAR_UNKNOWN)
17034 col = get_tv_number(&argvars[1]);
17036 rettv->vval.v_number = (varnumber_T)(linetabsize_col(col, s) - col);
17040 * "strwidth()" function
17043 f_strwidth(argvars, rettv)
17047 char_u *s = get_tv_string(&argvars[0]);
17049 rettv->vval.v_number = (varnumber_T)(
17051 mb_string2cells(s, -1)
17059 * "strpart()" function
17062 f_strpart(argvars, rettv)
17072 p = get_tv_string(&argvars[0]);
17073 slen = (int)STRLEN(p);
17075 n = get_tv_number_chk(&argvars[1], &error);
17078 else if (argvars[2].v_type != VAR_UNKNOWN)
17079 len = get_tv_number(&argvars[2]);
17081 len = slen - n; /* default len: all bytes that are available. */
17084 * Only return the overlap between the specified part and the actual
17096 else if (n + len > slen)
17099 rettv->v_type = VAR_STRING;
17100 rettv->vval.v_string = vim_strnsave(p + n, len);
17104 * "strridx()" function
17107 f_strridx(argvars, rettv)
17111 char_u buf[NUMBUFLEN];
17115 char_u *lastmatch = NULL;
17116 int haystack_len, end_idx;
17118 needle = get_tv_string_chk(&argvars[1]);
17119 haystack = get_tv_string_buf_chk(&argvars[0], buf);
17121 rettv->vval.v_number = -1;
17122 if (needle == NULL || haystack == NULL)
17123 return; /* type error; errmsg already given */
17125 haystack_len = (int)STRLEN(haystack);
17126 if (argvars[2].v_type != VAR_UNKNOWN)
17128 /* Third argument: upper limit for index */
17129 end_idx = get_tv_number_chk(&argvars[2], NULL);
17131 return; /* can never find a match */
17134 end_idx = haystack_len;
17136 if (*needle == NUL)
17138 /* Empty string matches past the end. */
17139 lastmatch = haystack + end_idx;
17143 for (rest = haystack; *rest != '\0'; ++rest)
17145 rest = (char_u *)strstr((char *)rest, (char *)needle);
17146 if (rest == NULL || rest > haystack + end_idx)
17152 if (lastmatch == NULL)
17153 rettv->vval.v_number = -1;
17155 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
17159 * "strtrans()" function
17162 f_strtrans(argvars, rettv)
17166 rettv->v_type = VAR_STRING;
17167 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
17171 * "submatch()" function
17174 f_submatch(argvars, rettv)
17178 rettv->v_type = VAR_STRING;
17179 rettv->vval.v_string =
17180 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
17184 * "substitute()" function
17187 f_substitute(argvars, rettv)
17191 char_u patbuf[NUMBUFLEN];
17192 char_u subbuf[NUMBUFLEN];
17193 char_u flagsbuf[NUMBUFLEN];
17195 char_u *str = get_tv_string_chk(&argvars[0]);
17196 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
17197 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
17198 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
17200 rettv->v_type = VAR_STRING;
17201 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
17202 rettv->vval.v_string = NULL;
17204 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
17208 * "synID(lnum, col, trans)" function
17211 f_synID(argvars, rettv)
17212 typval_T *argvars UNUSED;
17220 int transerr = FALSE;
17222 lnum = get_tv_lnum(argvars); /* -1 on type error */
17223 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
17224 trans = get_tv_number_chk(&argvars[2], &transerr);
17226 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
17227 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
17228 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
17231 rettv->vval.v_number = id;
17235 * "synIDattr(id, what [, mode])" function
17238 f_synIDattr(argvars, rettv)
17239 typval_T *argvars UNUSED;
17247 char_u modebuf[NUMBUFLEN];
17250 id = get_tv_number(&argvars[0]);
17251 what = get_tv_string(&argvars[1]);
17252 if (argvars[2].v_type != VAR_UNKNOWN)
17254 mode = get_tv_string_buf(&argvars[2], modebuf);
17255 modec = TOLOWER_ASC(mode[0]);
17256 if (modec != 't' && modec != 'c' && modec != 'g')
17257 modec = 0; /* replace invalid with current */
17273 switch (TOLOWER_ASC(what[0]))
17276 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
17277 p = highlight_color(id, what, modec);
17279 p = highlight_has_attr(id, HL_BOLD, modec);
17282 case 'f': /* fg[#] or font */
17283 p = highlight_color(id, what, modec);
17287 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
17288 p = highlight_has_attr(id, HL_INVERSE, modec);
17290 p = highlight_has_attr(id, HL_ITALIC, modec);
17293 case 'n': /* name */
17294 p = get_highlight_name(NULL, id - 1);
17297 case 'r': /* reverse */
17298 p = highlight_has_attr(id, HL_INVERSE, modec);
17302 if (TOLOWER_ASC(what[1]) == 'p') /* sp[#] */
17303 p = highlight_color(id, what, modec);
17304 else /* standout */
17305 p = highlight_has_attr(id, HL_STANDOUT, modec);
17309 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
17311 p = highlight_has_attr(id, HL_UNDERLINE, modec);
17314 p = highlight_has_attr(id, HL_UNDERCURL, modec);
17319 p = vim_strsave(p);
17321 rettv->v_type = VAR_STRING;
17322 rettv->vval.v_string = p;
17326 * "synIDtrans(id)" function
17329 f_synIDtrans(argvars, rettv)
17330 typval_T *argvars UNUSED;
17336 id = get_tv_number(&argvars[0]);
17339 id = syn_get_final_id(id);
17344 rettv->vval.v_number = id;
17348 * "synconcealed(lnum, col)" function
17351 f_synconcealed(argvars, rettv)
17352 typval_T *argvars UNUSED;
17355 #if defined(FEAT_SYN_HL) && defined(FEAT_CONCEAL)
17358 int syntax_flags = 0;
17361 char_u str[NUMBUFLEN];
17364 rettv->v_type = VAR_LIST;
17365 rettv->vval.v_list = NULL;
17367 #if defined(FEAT_SYN_HL) && defined(FEAT_CONCEAL)
17368 lnum = get_tv_lnum(argvars); /* -1 on type error */
17369 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
17371 vim_memset(str, NUL, sizeof(str));
17373 if (rettv_list_alloc(rettv) != FAIL)
17375 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
17376 && col >= 0 && col <= (long)STRLEN(ml_get(lnum))
17377 && curwin->w_p_cole > 0)
17379 (void)syn_get_id(curwin, lnum, col, FALSE, NULL, FALSE);
17380 syntax_flags = get_syntax_info(&matchid);
17382 /* get the conceal character */
17383 if ((syntax_flags & HL_CONCEAL) && curwin->w_p_cole < 3)
17385 cchar = syn_get_sub_char();
17386 if (cchar == NUL && curwin->w_p_cole == 1 && lcs_conceal != NUL)
17387 cchar = lcs_conceal;
17392 (*mb_char2bytes)(cchar, str);
17400 list_append_number(rettv->vval.v_list,
17401 (syntax_flags & HL_CONCEAL) != 0);
17402 /* -1 to auto-determine strlen */
17403 list_append_string(rettv->vval.v_list, str, -1);
17404 list_append_number(rettv->vval.v_list, matchid);
17410 * "synstack(lnum, col)" function
17413 f_synstack(argvars, rettv)
17414 typval_T *argvars UNUSED;
17424 rettv->v_type = VAR_LIST;
17425 rettv->vval.v_list = NULL;
17428 lnum = get_tv_lnum(argvars); /* -1 on type error */
17429 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
17431 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
17432 && col >= 0 && col <= (long)STRLEN(ml_get(lnum))
17433 && rettv_list_alloc(rettv) != FAIL)
17435 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
17438 id = syn_get_stack_item(i);
17441 if (list_append_number(rettv->vval.v_list, id) == FAIL)
17449 * "system()" function
17452 f_system(argvars, rettv)
17456 char_u *res = NULL;
17458 char_u *infile = NULL;
17459 char_u buf[NUMBUFLEN];
17463 if (check_restricted() || check_secure())
17466 if (argvars[1].v_type != VAR_UNKNOWN)
17469 * Write the string to a temp file, to be used for input of the shell
17472 if ((infile = vim_tempname('i')) == NULL)
17478 fd = mch_fopen((char *)infile, WRITEBIN);
17481 EMSG2(_(e_notopen), infile);
17484 p = get_tv_string_buf_chk(&argvars[1], buf);
17488 goto done; /* type error; errmsg already given */
17490 if (fwrite(p, STRLEN(p), 1, fd) != 1)
17492 if (fclose(fd) != 0)
17496 EMSG(_("E677: Error writing temp file"));
17501 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
17502 SHELL_SILENT | SHELL_COOKED);
17505 /* translate <CR> into <NL> */
17510 for (s = res; *s; ++s)
17518 /* translate <CR><NL> into <NL> */
17524 for (s = res; *s; ++s)
17526 if (s[0] == CAR && s[1] == NL)
17536 if (infile != NULL)
17538 mch_remove(infile);
17541 rettv->v_type = VAR_STRING;
17542 rettv->vval.v_string = res;
17546 * "tabpagebuflist()" function
17549 f_tabpagebuflist(argvars, rettv)
17550 typval_T *argvars UNUSED;
17551 typval_T *rettv UNUSED;
17553 #ifdef FEAT_WINDOWS
17557 if (argvars[0].v_type == VAR_UNKNOWN)
17561 tp = find_tabpage((int)get_tv_number(&argvars[0]));
17563 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
17565 if (wp != NULL && rettv_list_alloc(rettv) != FAIL)
17567 for (; wp != NULL; wp = wp->w_next)
17568 if (list_append_number(rettv->vval.v_list,
17569 wp->w_buffer->b_fnum) == FAIL)
17577 * "tabpagenr()" function
17580 f_tabpagenr(argvars, rettv)
17581 typval_T *argvars UNUSED;
17585 #ifdef FEAT_WINDOWS
17588 if (argvars[0].v_type != VAR_UNKNOWN)
17590 arg = get_tv_string_chk(&argvars[0]);
17594 if (STRCMP(arg, "$") == 0)
17595 nr = tabpage_index(NULL) - 1;
17597 EMSG2(_(e_invexpr2), arg);
17601 nr = tabpage_index(curtab);
17603 rettv->vval.v_number = nr;
17607 #ifdef FEAT_WINDOWS
17608 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
17611 * Common code for tabpagewinnr() and winnr().
17614 get_winnr(tp, argvar)
17623 twin = (tp == curtab) ? curwin : tp->tp_curwin;
17624 if (argvar->v_type != VAR_UNKNOWN)
17626 arg = get_tv_string_chk(argvar);
17628 nr = 0; /* type error; errmsg already given */
17629 else if (STRCMP(arg, "$") == 0)
17630 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
17631 else if (STRCMP(arg, "#") == 0)
17633 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
17639 EMSG2(_(e_invexpr2), arg);
17645 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
17646 wp != twin; wp = wp->w_next)
17650 /* didn't find it in this tabpage */
17661 * "tabpagewinnr()" function
17664 f_tabpagewinnr(argvars, rettv)
17665 typval_T *argvars UNUSED;
17669 #ifdef FEAT_WINDOWS
17672 tp = find_tabpage((int)get_tv_number(&argvars[0]));
17676 nr = get_winnr(tp, &argvars[1]);
17678 rettv->vval.v_number = nr;
17683 * "tagfiles()" function
17686 f_tagfiles(argvars, rettv)
17687 typval_T *argvars UNUSED;
17694 if (rettv_list_alloc(rettv) == FAIL)
17696 fname = alloc(MAXPATHL);
17700 for (first = TRUE; ; first = FALSE)
17701 if (get_tagfname(&tn, first, fname) == FAIL
17702 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
17709 * "taglist()" function
17712 f_taglist(argvars, rettv)
17716 char_u *tag_pattern;
17718 tag_pattern = get_tv_string(&argvars[0]);
17720 rettv->vval.v_number = FALSE;
17721 if (*tag_pattern == NUL)
17724 if (rettv_list_alloc(rettv) == OK)
17725 (void)get_tags(rettv->vval.v_list, tag_pattern);
17729 * "tempname()" function
17732 f_tempname(argvars, rettv)
17733 typval_T *argvars UNUSED;
17736 static int x = 'A';
17738 rettv->v_type = VAR_STRING;
17739 rettv->vval.v_string = vim_tempname(x);
17741 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
17742 * names. Skip 'I' and 'O', they are used for shell redirection. */
17760 } while (x == 'I' || x == 'O');
17764 * "test(list)" function: Just checking the walls...
17767 f_test(argvars, rettv)
17768 typval_T *argvars UNUSED;
17769 typval_T *rettv UNUSED;
17771 /* Used for unit testing. Change the code below to your liking. */
17775 char_u *bad, *good;
17777 if (argvars[0].v_type != VAR_LIST)
17779 l = argvars[0].vval.v_list;
17785 bad = get_tv_string(&li->li_tv);
17789 good = get_tv_string(&li->li_tv);
17790 rettv->vval.v_number = test_edit_score(bad, good);
17799 f_tan(argvars, rettv)
17805 rettv->v_type = VAR_FLOAT;
17806 if (get_float_arg(argvars, &f) == OK)
17807 rettv->vval.v_float = tan(f);
17809 rettv->vval.v_float = 0.0;
17813 * "tanh()" function
17816 f_tanh(argvars, rettv)
17822 rettv->v_type = VAR_FLOAT;
17823 if (get_float_arg(argvars, &f) == OK)
17824 rettv->vval.v_float = tanh(f);
17826 rettv->vval.v_float = 0.0;
17831 * "tolower(string)" function
17834 f_tolower(argvars, rettv)
17840 p = vim_strsave(get_tv_string(&argvars[0]));
17841 rettv->v_type = VAR_STRING;
17842 rettv->vval.v_string = p;
17854 c = utf_ptr2char(p);
17855 lc = utf_tolower(c);
17856 l = utf_ptr2len(p);
17857 /* TODO: reallocate string when byte count changes. */
17858 if (utf_char2len(lc) == l)
17859 utf_char2bytes(lc, p);
17862 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
17863 p += l; /* skip multi-byte character */
17867 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
17874 * "toupper(string)" function
17877 f_toupper(argvars, rettv)
17881 rettv->v_type = VAR_STRING;
17882 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
17886 * "tr(string, fromstr, tostr)" function
17889 f_tr(argvars, rettv)
17906 char_u buf[NUMBUFLEN];
17907 char_u buf2[NUMBUFLEN];
17910 instr = get_tv_string(&argvars[0]);
17911 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
17912 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
17914 /* Default return value: empty string. */
17915 rettv->v_type = VAR_STRING;
17916 rettv->vval.v_string = NULL;
17917 if (fromstr == NULL || tostr == NULL)
17918 return; /* type error; errmsg already given */
17919 ga_init2(&ga, (int)sizeof(char), 80);
17924 /* not multi-byte: fromstr and tostr must be the same length */
17925 if (STRLEN(fromstr) != STRLEN(tostr))
17930 EMSG2(_(e_invarg2), fromstr);
17935 /* fromstr and tostr have to contain the same number of chars */
17936 while (*instr != NUL)
17941 inlen = (*mb_ptr2len)(instr);
17945 for (p = fromstr; *p != NUL; p += fromlen)
17947 fromlen = (*mb_ptr2len)(p);
17948 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
17950 for (p = tostr; *p != NUL; p += tolen)
17952 tolen = (*mb_ptr2len)(p);
17960 if (*p == NUL) /* tostr is shorter than fromstr */
17967 if (first && cpstr == instr)
17969 /* Check that fromstr and tostr have the same number of
17970 * (multi-byte) characters. Done only once when a character
17971 * of instr doesn't appear in fromstr. */
17973 for (p = tostr; *p != NUL; p += tolen)
17975 tolen = (*mb_ptr2len)(p);
17982 ga_grow(&ga, cplen);
17983 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
17984 ga.ga_len += cplen;
17991 /* When not using multi-byte chars we can do it faster. */
17992 p = vim_strchr(fromstr, *instr);
17994 ga_append(&ga, tostr[p - fromstr]);
17996 ga_append(&ga, *instr);
18001 /* add a terminating NUL */
18003 ga_append(&ga, NUL);
18005 rettv->vval.v_string = ga.ga_data;
18010 * "trunc({float})" function
18013 f_trunc(argvars, rettv)
18019 rettv->v_type = VAR_FLOAT;
18020 if (get_float_arg(argvars, &f) == OK)
18021 /* trunc() is not in C90, use floor() or ceil() instead. */
18022 rettv->vval.v_float = f > 0 ? floor(f) : ceil(f);
18024 rettv->vval.v_float = 0.0;
18029 * "type(expr)" function
18032 f_type(argvars, rettv)
18038 switch (argvars[0].v_type)
18040 case VAR_NUMBER: n = 0; break;
18041 case VAR_STRING: n = 1; break;
18042 case VAR_FUNC: n = 2; break;
18043 case VAR_LIST: n = 3; break;
18044 case VAR_DICT: n = 4; break;
18046 case VAR_FLOAT: n = 5; break;
18048 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
18050 rettv->vval.v_number = n;
18054 * "undofile(name)" function
18057 f_undofile(argvars, rettv)
18061 rettv->v_type = VAR_STRING;
18062 #ifdef FEAT_PERSISTENT_UNDO
18064 char_u *ffname = FullName_save(get_tv_string(&argvars[0]), FALSE);
18066 if (ffname != NULL)
18067 rettv->vval.v_string = u_get_undo_file_name(ffname, FALSE);
18071 rettv->vval.v_string = NULL;
18076 * "undotree()" function
18079 f_undotree(argvars, rettv)
18080 typval_T *argvars UNUSED;
18083 if (rettv_dict_alloc(rettv) == OK)
18085 dict_T *dict = rettv->vval.v_dict;
18088 dict_add_nr_str(dict, "synced", (long)curbuf->b_u_synced, NULL);
18089 dict_add_nr_str(dict, "seq_last", curbuf->b_u_seq_last, NULL);
18090 dict_add_nr_str(dict, "save_last",
18091 (long)curbuf->b_u_save_nr_last, NULL);
18092 dict_add_nr_str(dict, "seq_cur", curbuf->b_u_seq_cur, NULL);
18093 dict_add_nr_str(dict, "time_cur", (long)curbuf->b_u_time_cur, NULL);
18094 dict_add_nr_str(dict, "save_cur", (long)curbuf->b_u_save_nr_cur, NULL);
18096 list = list_alloc();
18099 u_eval_tree(curbuf->b_u_oldhead, list);
18100 dict_add_list(dict, "entries", list);
18106 * "values(dict)" function
18109 f_values(argvars, rettv)
18113 dict_list(argvars, rettv, 1);
18117 * "virtcol(string)" function
18120 f_virtcol(argvars, rettv)
18126 int fnum = curbuf->b_fnum;
18128 fp = var2fpos(&argvars[0], FALSE, &fnum);
18129 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
18130 && fnum == curbuf->b_fnum)
18132 getvvcol(curwin, fp, NULL, NULL, &vcol);
18136 rettv->vval.v_number = vcol;
18140 * "visualmode()" function
18143 f_visualmode(argvars, rettv)
18144 typval_T *argvars UNUSED;
18145 typval_T *rettv UNUSED;
18150 rettv->v_type = VAR_STRING;
18151 str[0] = curbuf->b_visual_mode_eval;
18153 rettv->vval.v_string = vim_strsave(str);
18155 /* A non-zero number or non-empty string argument: reset mode. */
18156 if (non_zero_arg(&argvars[0]))
18157 curbuf->b_visual_mode_eval = NUL;
18162 * "winbufnr(nr)" function
18165 f_winbufnr(argvars, rettv)
18171 wp = find_win_by_nr(&argvars[0], NULL);
18173 rettv->vval.v_number = -1;
18175 rettv->vval.v_number = wp->w_buffer->b_fnum;
18179 * "wincol()" function
18182 f_wincol(argvars, rettv)
18183 typval_T *argvars UNUSED;
18187 rettv->vval.v_number = curwin->w_wcol + 1;
18191 * "winheight(nr)" function
18194 f_winheight(argvars, rettv)
18200 wp = find_win_by_nr(&argvars[0], NULL);
18202 rettv->vval.v_number = -1;
18204 rettv->vval.v_number = wp->w_height;
18208 * "winline()" function
18211 f_winline(argvars, rettv)
18212 typval_T *argvars UNUSED;
18216 rettv->vval.v_number = curwin->w_wrow + 1;
18220 * "winnr()" function
18223 f_winnr(argvars, rettv)
18224 typval_T *argvars UNUSED;
18229 #ifdef FEAT_WINDOWS
18230 nr = get_winnr(curtab, &argvars[0]);
18232 rettv->vval.v_number = nr;
18236 * "winrestcmd()" function
18239 f_winrestcmd(argvars, rettv)
18240 typval_T *argvars UNUSED;
18243 #ifdef FEAT_WINDOWS
18249 ga_init2(&ga, (int)sizeof(char), 70);
18250 for (wp = firstwin; wp != NULL; wp = wp->w_next)
18252 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
18253 ga_concat(&ga, buf);
18254 # ifdef FEAT_VERTSPLIT
18255 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
18256 ga_concat(&ga, buf);
18260 ga_append(&ga, NUL);
18262 rettv->vval.v_string = ga.ga_data;
18264 rettv->vval.v_string = NULL;
18266 rettv->v_type = VAR_STRING;
18270 * "winrestview()" function
18273 f_winrestview(argvars, rettv)
18275 typval_T *rettv UNUSED;
18279 if (argvars[0].v_type != VAR_DICT
18280 || (dict = argvars[0].vval.v_dict) == NULL)
18284 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
18285 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
18286 #ifdef FEAT_VIRTUALEDIT
18287 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
18289 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
18290 curwin->w_set_curswant = FALSE;
18292 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
18294 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
18296 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
18297 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
18300 changed_cline_bef_curs();
18301 invalidate_botline();
18302 redraw_later(VALID);
18304 if (curwin->w_topline == 0)
18305 curwin->w_topline = 1;
18306 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
18307 curwin->w_topline = curbuf->b_ml.ml_line_count;
18309 check_topfill(curwin, TRUE);
18315 * "winsaveview()" function
18318 f_winsaveview(argvars, rettv)
18319 typval_T *argvars UNUSED;
18324 if (rettv_dict_alloc(rettv) == FAIL)
18326 dict = rettv->vval.v_dict;
18328 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
18329 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
18330 #ifdef FEAT_VIRTUALEDIT
18331 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
18334 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
18336 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
18338 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
18340 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
18341 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
18345 * "winwidth(nr)" function
18348 f_winwidth(argvars, rettv)
18354 wp = find_win_by_nr(&argvars[0], NULL);
18356 rettv->vval.v_number = -1;
18358 #ifdef FEAT_VERTSPLIT
18359 rettv->vval.v_number = wp->w_width;
18361 rettv->vval.v_number = Columns;
18366 * "writefile()" function
18369 f_writefile(argvars, rettv)
18373 int binary = FALSE;
18381 if (check_restricted() || check_secure())
18384 if (argvars[0].v_type != VAR_LIST)
18386 EMSG2(_(e_listarg), "writefile()");
18389 if (argvars[0].vval.v_list == NULL)
18392 if (argvars[2].v_type != VAR_UNKNOWN
18393 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
18396 /* Always open the file in binary mode, library functions have a mind of
18397 * their own about CR-LF conversion. */
18398 fname = get_tv_string(&argvars[1]);
18399 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
18401 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
18406 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
18409 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
18421 if (!binary || li->li_next != NULL)
18422 if (putc('\n', fd) == EOF)
18436 rettv->vval.v_number = ret;
18440 * "xor(expr, expr)" function
18443 f_xor(argvars, rettv)
18447 rettv->vval.v_number = get_tv_number_chk(&argvars[0], NULL)
18448 ^ get_tv_number_chk(&argvars[1], NULL);
18453 * Translate a String variable into a position.
18454 * Returns NULL when there is an error.
18457 var2fpos(varp, dollar_lnum, fnum)
18459 int dollar_lnum; /* TRUE when $ is last line */
18460 int *fnum; /* set to fnum for '0, 'A, etc. */
18466 /* Argument can be [lnum, col, coladd]. */
18467 if (varp->v_type == VAR_LIST)
18474 l = varp->vval.v_list;
18478 /* Get the line number */
18479 pos.lnum = list_find_nr(l, 0L, &error);
18480 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
18481 return NULL; /* invalid line number */
18483 /* Get the column number */
18484 pos.col = list_find_nr(l, 1L, &error);
18487 len = (long)STRLEN(ml_get(pos.lnum));
18489 /* We accept "$" for the column number: last column. */
18490 li = list_find(l, 1L);
18491 if (li != NULL && li->li_tv.v_type == VAR_STRING
18492 && li->li_tv.vval.v_string != NULL
18493 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
18496 /* Accept a position up to the NUL after the line. */
18497 if (pos.col == 0 || (int)pos.col > len + 1)
18498 return NULL; /* invalid column number */
18501 #ifdef FEAT_VIRTUALEDIT
18502 /* Get the virtual offset. Defaults to zero. */
18503 pos.coladd = list_find_nr(l, 2L, &error);
18511 name = get_tv_string_chk(varp);
18514 if (name[0] == '.') /* cursor */
18515 return &curwin->w_cursor;
18517 if (name[0] == 'v' && name[1] == NUL) /* Visual start */
18521 return &curwin->w_cursor;
18524 if (name[0] == '\'') /* mark */
18526 pp = getmark_fnum(name[1], FALSE, fnum);
18527 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
18532 #ifdef FEAT_VIRTUALEDIT
18536 if (name[0] == 'w' && dollar_lnum)
18539 if (name[1] == '0') /* "w0": first visible line */
18542 pos.lnum = curwin->w_topline;
18545 else if (name[1] == '$') /* "w$": last visible line */
18547 validate_botline();
18548 pos.lnum = curwin->w_botline - 1;
18552 else if (name[0] == '$') /* last column or line */
18556 pos.lnum = curbuf->b_ml.ml_line_count;
18561 pos.lnum = curwin->w_cursor.lnum;
18562 pos.col = (colnr_T)STRLEN(ml_get_curline());
18570 * Convert list in "arg" into a position and optional file number.
18571 * When "fnump" is NULL there is no file number, only 3 items.
18572 * Note that the column is passed on as-is, the caller may want to decrement
18573 * it to use 1 for the first column.
18574 * Return FAIL when conversion is not possible, doesn't check the position for
18578 list2fpos(arg, posp, fnump)
18583 list_T *l = arg->vval.v_list;
18587 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
18588 * when "fnump" isn't NULL and "coladd" is optional. */
18589 if (arg->v_type != VAR_LIST
18591 || l->lv_len < (fnump == NULL ? 2 : 3)
18592 || l->lv_len > (fnump == NULL ? 3 : 4))
18597 n = list_find_nr(l, i++, NULL); /* fnum */
18601 n = curbuf->b_fnum; /* current buffer */
18605 n = list_find_nr(l, i++, NULL); /* lnum */
18610 n = list_find_nr(l, i++, NULL); /* col */
18615 #ifdef FEAT_VIRTUALEDIT
18616 n = list_find_nr(l, i, NULL);
18627 * Get the length of an environment variable name.
18628 * Advance "arg" to the first character after the name.
18629 * Return 0 for error.
18638 for (p = *arg; vim_isIDc(*p); ++p)
18640 if (p == *arg) /* no name found */
18643 len = (int)(p - *arg);
18649 * Get the length of the name of a function or internal variable.
18650 * "arg" is advanced to the first non-white character after the name.
18651 * Return 0 if something is wrong.
18660 /* Find the end of the name. */
18661 for (p = *arg; eval_isnamec(*p); ++p)
18663 if (p == *arg) /* no name found */
18666 len = (int)(p - *arg);
18667 *arg = skipwhite(p);
18673 * Get the length of the name of a variable or function.
18674 * Only the name is recognized, does not handle ".key" or "[idx]".
18675 * "arg" is advanced to the first non-white character after the name.
18676 * Return -1 if curly braces expansion failed.
18677 * Return 0 if something else is wrong.
18678 * If the name contains 'magic' {}'s, expand them and return the
18679 * expanded name in an allocated string via 'alias' - caller must free.
18682 get_name_len(arg, alias, evaluate, verbose)
18690 char_u *expr_start;
18693 *alias = NULL; /* default to no alias */
18695 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
18696 && (*arg)[2] == (int)KE_SNR)
18698 /* hard coded <SNR>, already translated */
18700 return get_id_len(arg) + 3;
18702 len = eval_fname_script(*arg);
18705 /* literal "<SID>", "s:" or "<SNR>" */
18710 * Find the end of the name; check for {} construction.
18712 p = find_name_end(*arg, &expr_start, &expr_end,
18713 len > 0 ? 0 : FNE_CHECK_START);
18714 if (expr_start != NULL)
18716 char_u *temp_string;
18720 len += (int)(p - *arg);
18721 *arg = skipwhite(p);
18726 * Include any <SID> etc in the expanded string:
18727 * Thus the -len here.
18729 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
18730 if (temp_string == NULL)
18732 *alias = temp_string;
18733 *arg = skipwhite(p);
18734 return (int)STRLEN(temp_string);
18737 len += get_id_len(arg);
18738 if (len == 0 && verbose)
18739 EMSG2(_(e_invexpr2), *arg);
18745 * Find the end of a variable or function name, taking care of magic braces.
18746 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
18747 * start and end of the first magic braces item.
18748 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
18749 * Return a pointer to just after the name. Equal to "arg" if there is no
18753 find_name_end(arg, expr_start, expr_end, flags)
18755 char_u **expr_start;
18763 if (expr_start != NULL)
18765 *expr_start = NULL;
18769 /* Quick check for valid starting character. */
18770 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
18773 for (p = arg; *p != NUL
18774 && (eval_isnamec(*p)
18776 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
18778 || br_nest != 0); mb_ptr_adv(p))
18782 /* skip over 'string' to avoid counting [ and ] inside it. */
18783 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
18788 else if (*p == '"')
18790 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
18791 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
18792 if (*p == '\\' && p[1] != NUL)
18802 else if (*p == ']')
18811 if (expr_start != NULL && *expr_start == NULL)
18814 else if (*p == '}')
18817 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
18827 * Expands out the 'magic' {}'s in a variable/function name.
18828 * Note that this can call itself recursively, to deal with
18829 * constructs like foo{bar}{baz}{bam}
18830 * The four pointer arguments point to "foo{expre}ss{ion}bar"
18836 * Returns a new allocated string, which the caller must free.
18837 * Returns NULL for failure.
18840 make_expanded_name(in_start, expr_start, expr_end, in_end)
18842 char_u *expr_start;
18847 char_u *retval = NULL;
18848 char_u *temp_result;
18849 char_u *nextcmd = NULL;
18851 if (expr_end == NULL || in_end == NULL)
18858 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
18859 if (temp_result != NULL && nextcmd == NULL)
18861 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
18862 + (in_end - expr_end) + 1));
18863 if (retval != NULL)
18865 STRCPY(retval, in_start);
18866 STRCAT(retval, temp_result);
18867 STRCAT(retval, expr_end + 1);
18870 vim_free(temp_result);
18872 *in_end = c1; /* put char back for error messages */
18876 if (retval != NULL)
18878 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
18879 if (expr_start != NULL)
18881 /* Further expansion! */
18882 temp_result = make_expanded_name(retval, expr_start,
18883 expr_end, temp_result);
18885 retval = temp_result;
18893 * Return TRUE if character "c" can be used in a variable or function name.
18894 * Does not include '{' or '}' for magic braces.
18900 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
18904 * Return TRUE if character "c" can be used as the first character in a
18905 * variable or function name (excluding '{' and '}').
18911 return (ASCII_ISALPHA(c) || c == '_');
18915 * Set number v: variable to "val".
18918 set_vim_var_nr(idx, val)
18922 vimvars[idx].vv_nr = val;
18926 * Get number v: variable value.
18929 get_vim_var_nr(idx)
18932 return vimvars[idx].vv_nr;
18936 * Get string v: variable value. Uses a static buffer, can only be used once.
18939 get_vim_var_str(idx)
18942 return get_tv_string(&vimvars[idx].vv_tv);
18946 * Get List v: variable value. Caller must take care of reference count when
18950 get_vim_var_list(idx)
18953 return vimvars[idx].vv_list;
18957 * Set v:char to character "c".
18960 set_vim_var_char(c)
18964 char_u buf[MB_MAXBYTES];
18971 buf[(*mb_char2bytes)(c, buf)] = NUL;
18978 set_vim_var_string(VV_CHAR, buf, -1);
18982 * Set v:count to "count" and v:count1 to "count1".
18983 * When "set_prevcount" is TRUE first set v:prevcount from v:count.
18986 set_vcount(count, count1, set_prevcount)
18992 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
18993 vimvars[VV_COUNT].vv_nr = count;
18994 vimvars[VV_COUNT1].vv_nr = count1;
18998 * Set string v: variable to a copy of "val".
19001 set_vim_var_string(idx, val, len)
19004 int len; /* length of "val" to use or -1 (whole string) */
19006 /* Need to do this (at least) once, since we can't initialize a union.
19007 * Will always be invoked when "v:progname" is set. */
19008 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
19010 vim_free(vimvars[idx].vv_str);
19012 vimvars[idx].vv_str = NULL;
19013 else if (len == -1)
19014 vimvars[idx].vv_str = vim_strsave(val);
19016 vimvars[idx].vv_str = vim_strnsave(val, len);
19020 * Set List v: variable to "val".
19023 set_vim_var_list(idx, val)
19027 list_unref(vimvars[idx].vv_list);
19028 vimvars[idx].vv_list = val;
19030 ++val->lv_refcount;
19034 * Set v:register if needed.
19042 if (c == 0 || c == ' ')
19046 /* Avoid free/alloc when the value is already right. */
19047 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
19048 set_vim_var_string(VV_REG, ®name, 1);
19052 * Get or set v:exception. If "oldval" == NULL, return the current value.
19053 * Otherwise, restore the value to "oldval" and return NULL.
19054 * Must always be called in pairs to save and restore v:exception! Does not
19055 * take care of memory allocations.
19058 v_exception(oldval)
19061 if (oldval == NULL)
19062 return vimvars[VV_EXCEPTION].vv_str;
19064 vimvars[VV_EXCEPTION].vv_str = oldval;
19069 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
19070 * Otherwise, restore the value to "oldval" and return NULL.
19071 * Must always be called in pairs to save and restore v:throwpoint! Does not
19072 * take care of memory allocations.
19075 v_throwpoint(oldval)
19078 if (oldval == NULL)
19079 return vimvars[VV_THROWPOINT].vv_str;
19081 vimvars[VV_THROWPOINT].vv_str = oldval;
19085 #if defined(FEAT_AUTOCMD) || defined(PROTO)
19088 * If "eap" != NULL, use "eap" to generate the value and return the old value.
19089 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
19090 * Must always be called in pairs!
19093 set_cmdarg(eap, oldarg)
19101 oldval = vimvars[VV_CMDARG].vv_str;
19105 vimvars[VV_CMDARG].vv_str = oldarg;
19109 if (eap->force_bin == FORCE_BIN)
19111 else if (eap->force_bin == FORCE_NOBIN)
19116 if (eap->read_edit)
19119 if (eap->force_ff != 0)
19120 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
19122 if (eap->force_enc != 0)
19123 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
19124 if (eap->bad_char != 0)
19125 len += 7 + 4; /* " ++bad=" + "keep" or "drop" */
19128 newval = alloc(len + 1);
19129 if (newval == NULL)
19132 if (eap->force_bin == FORCE_BIN)
19133 sprintf((char *)newval, " ++bin");
19134 else if (eap->force_bin == FORCE_NOBIN)
19135 sprintf((char *)newval, " ++nobin");
19139 if (eap->read_edit)
19140 STRCAT(newval, " ++edit");
19142 if (eap->force_ff != 0)
19143 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
19144 eap->cmd + eap->force_ff);
19146 if (eap->force_enc != 0)
19147 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
19148 eap->cmd + eap->force_enc);
19149 if (eap->bad_char == BAD_KEEP)
19150 STRCPY(newval + STRLEN(newval), " ++bad=keep");
19151 else if (eap->bad_char == BAD_DROP)
19152 STRCPY(newval + STRLEN(newval), " ++bad=drop");
19153 else if (eap->bad_char != 0)
19154 sprintf((char *)newval + STRLEN(newval), " ++bad=%c", eap->bad_char);
19156 vimvars[VV_CMDARG].vv_str = newval;
19162 * Get the value of internal variable "name".
19163 * Return OK or FAIL.
19166 get_var_tv(name, len, rettv, verbose)
19168 int len; /* length of "name" */
19169 typval_T *rettv; /* NULL when only checking existence */
19170 int verbose; /* may give error message */
19173 typval_T *tv = NULL;
19178 /* truncate the name, so that we can use strcmp() */
19183 * Check for "b:changedtick".
19185 if (STRCMP(name, "b:changedtick") == 0)
19187 atv.v_type = VAR_NUMBER;
19188 atv.vval.v_number = curbuf->b_changedtick;
19193 * Check for user-defined variables.
19197 v = find_var(name, NULL);
19204 if (rettv != NULL && verbose)
19205 EMSG2(_(e_undefvar), name);
19208 else if (rettv != NULL)
19209 copy_tv(tv, rettv);
19217 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
19218 * Also handle function call with Funcref variable: func(expr)
19219 * Can all be combined: dict.func(expr)[idx]['func'](expr)
19222 handle_subscript(arg, rettv, evaluate, verbose)
19225 int evaluate; /* do more than finding the end */
19226 int verbose; /* give error messages */
19229 dict_T *selfdict = NULL;
19236 || (**arg == '.' && rettv->v_type == VAR_DICT)
19237 || (**arg == '(' && rettv->v_type == VAR_FUNC))
19238 && !vim_iswhite(*(*arg - 1)))
19242 /* need to copy the funcref so that we can clear rettv */
19244 rettv->v_type = VAR_UNKNOWN;
19246 /* Invoke the function. Recursive! */
19247 s = functv.vval.v_string;
19248 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
19249 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
19250 &len, evaluate, selfdict);
19252 /* Clear the funcref afterwards, so that deleting it while
19253 * evaluating the arguments is possible (see test55). */
19256 /* Stop the expression evaluation when immediately aborting on
19257 * error, or when an interrupt occurred or an exception was thrown
19258 * but not caught. */
19265 dict_unref(selfdict);
19268 else /* **arg == '[' || **arg == '.' */
19270 dict_unref(selfdict);
19271 if (rettv->v_type == VAR_DICT)
19273 selfdict = rettv->vval.v_dict;
19274 if (selfdict != NULL)
19275 ++selfdict->dv_refcount;
19279 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
19286 dict_unref(selfdict);
19291 * Allocate memory for a variable type-value, and make it empty (0 or NULL
19297 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
19301 * Allocate memory for a variable type-value, and assign a string to it.
19302 * The string "s" must have been allocated, it is consumed.
19303 * Return NULL for out of memory, the variable otherwise.
19311 rettv = alloc_tv();
19314 rettv->v_type = VAR_STRING;
19315 rettv->vval.v_string = s;
19323 * Free the memory for a variable type-value.
19331 switch (varp->v_type)
19334 func_unref(varp->vval.v_string);
19337 vim_free(varp->vval.v_string);
19340 list_unref(varp->vval.v_list);
19343 dict_unref(varp->vval.v_dict);
19352 EMSG2(_(e_intern2), "free_tv()");
19360 * Free the memory for a variable value and set the value to NULL or 0.
19368 switch (varp->v_type)
19371 func_unref(varp->vval.v_string);
19374 vim_free(varp->vval.v_string);
19375 varp->vval.v_string = NULL;
19378 list_unref(varp->vval.v_list);
19379 varp->vval.v_list = NULL;
19382 dict_unref(varp->vval.v_dict);
19383 varp->vval.v_dict = NULL;
19386 varp->vval.v_number = 0;
19390 varp->vval.v_float = 0.0;
19396 EMSG2(_(e_intern2), "clear_tv()");
19403 * Set the value of a variable to NULL without freeing items.
19410 vim_memset(varp, 0, sizeof(typval_T));
19414 * Get the number value of a variable.
19415 * If it is a String variable, uses vim_str2nr().
19416 * For incompatible types, return 0.
19417 * get_tv_number_chk() is similar to get_tv_number(), but informs the
19418 * caller of incompatible types: it sets *denote to TRUE if "denote"
19419 * is not NULL or returns -1 otherwise.
19422 get_tv_number(varp)
19427 return get_tv_number_chk(varp, &error); /* return 0L on error */
19431 get_tv_number_chk(varp, denote)
19437 switch (varp->v_type)
19440 return (long)(varp->vval.v_number);
19443 EMSG(_("E805: Using a Float as a Number"));
19447 EMSG(_("E703: Using a Funcref as a Number"));
19450 if (varp->vval.v_string != NULL)
19451 vim_str2nr(varp->vval.v_string, NULL, NULL,
19452 TRUE, TRUE, &n, NULL);
19455 EMSG(_("E745: Using a List as a Number"));
19458 EMSG(_("E728: Using a Dictionary as a Number"));
19461 EMSG2(_(e_intern2), "get_tv_number()");
19464 if (denote == NULL) /* useful for values that must be unsigned */
19472 * Get the lnum from the first argument.
19473 * Also accepts ".", "$", etc., but that only works for the current buffer.
19474 * Returns -1 on error.
19477 get_tv_lnum(argvars)
19483 lnum = get_tv_number_chk(&argvars[0], NULL);
19484 if (lnum == 0) /* no valid number, try using line() */
19486 rettv.v_type = VAR_NUMBER;
19487 f_line(argvars, &rettv);
19488 lnum = rettv.vval.v_number;
19495 * Get the lnum from the first argument.
19496 * Also accepts "$", then "buf" is used.
19497 * Returns 0 on error.
19500 get_tv_lnum_buf(argvars, buf)
19504 if (argvars[0].v_type == VAR_STRING
19505 && argvars[0].vval.v_string != NULL
19506 && argvars[0].vval.v_string[0] == '$'
19508 return buf->b_ml.ml_line_count;
19509 return get_tv_number_chk(&argvars[0], NULL);
19513 * Get the string value of a variable.
19514 * If it is a Number variable, the number is converted into a string.
19515 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
19516 * get_tv_string_buf() uses a given buffer.
19517 * If the String variable has never been set, return an empty string.
19518 * Never returns NULL;
19519 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
19523 get_tv_string(varp)
19526 static char_u mybuf[NUMBUFLEN];
19528 return get_tv_string_buf(varp, mybuf);
19532 get_tv_string_buf(varp, buf)
19536 char_u *res = get_tv_string_buf_chk(varp, buf);
19538 return res != NULL ? res : (char_u *)"";
19542 get_tv_string_chk(varp)
19545 static char_u mybuf[NUMBUFLEN];
19547 return get_tv_string_buf_chk(varp, mybuf);
19551 get_tv_string_buf_chk(varp, buf)
19555 switch (varp->v_type)
19558 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
19561 EMSG(_("E729: using Funcref as a String"));
19564 EMSG(_("E730: using List as a String"));
19567 EMSG(_("E731: using Dictionary as a String"));
19571 EMSG(_("E806: using Float as a String"));
19575 if (varp->vval.v_string != NULL)
19576 return varp->vval.v_string;
19577 return (char_u *)"";
19579 EMSG2(_(e_intern2), "get_tv_string_buf()");
19586 * Find variable "name" in the list of variables.
19587 * Return a pointer to it if found, NULL if not found.
19588 * Careful: "a:0" variables don't have a name.
19589 * When "htp" is not NULL we are writing to the variable, set "htp" to the
19592 static dictitem_T *
19593 find_var(name, htp)
19600 ht = find_var_ht(name, &varname);
19605 return find_var_in_ht(ht, varname, htp != NULL);
19609 * Find variable "varname" in hashtab "ht".
19610 * Returns NULL if not found.
19612 static dictitem_T *
19613 find_var_in_ht(ht, varname, writing)
19620 if (*varname == NUL)
19622 /* Must be something like "s:", otherwise "ht" would be NULL. */
19623 switch (varname[-2])
19625 case 's': return &SCRIPT_SV(current_SID)->sv_var;
19626 case 'g': return &globvars_var;
19627 case 'v': return &vimvars_var;
19628 case 'b': return &curbuf->b_bufvar;
19629 case 'w': return &curwin->w_winvar;
19630 #ifdef FEAT_WINDOWS
19631 case 't': return &curtab->tp_winvar;
19633 case 'l': return current_funccal == NULL
19634 ? NULL : ¤t_funccal->l_vars_var;
19635 case 'a': return current_funccal == NULL
19636 ? NULL : ¤t_funccal->l_avars_var;
19641 hi = hash_find(ht, varname);
19642 if (HASHITEM_EMPTY(hi))
19644 /* For global variables we may try auto-loading the script. If it
19645 * worked find the variable again. Don't auto-load a script if it was
19646 * loaded already, otherwise it would be loaded every time when
19647 * checking if a function name is a Funcref variable. */
19648 if (ht == &globvarht && !writing)
19650 /* Note: script_autoload() may make "hi" invalid. It must either
19651 * be obtained again or not used. */
19652 if (!script_autoload(varname, FALSE) || aborting())
19654 hi = hash_find(ht, varname);
19656 if (HASHITEM_EMPTY(hi))
19663 * Find the hashtab used for a variable name.
19664 * Set "varname" to the start of name without ':'.
19667 find_var_ht(name, varname)
19673 if (name[1] != ':')
19675 /* The name must not start with a colon or #. */
19676 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
19680 /* "version" is "v:version" in all scopes */
19681 hi = hash_find(&compat_hashtab, name);
19682 if (!HASHITEM_EMPTY(hi))
19683 return &compat_hashtab;
19685 if (current_funccal == NULL)
19686 return &globvarht; /* global variable */
19687 return ¤t_funccal->l_vars.dv_hashtab; /* l: variable */
19689 *varname = name + 2;
19690 if (*name == 'g') /* global variable */
19692 /* There must be no ':' or '#' in the rest of the name, unless g: is used
19694 if (vim_strchr(name + 2, ':') != NULL
19695 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
19697 if (*name == 'b') /* buffer variable */
19698 return &curbuf->b_vars.dv_hashtab;
19699 if (*name == 'w') /* window variable */
19700 return &curwin->w_vars.dv_hashtab;
19701 #ifdef FEAT_WINDOWS
19702 if (*name == 't') /* tab page variable */
19703 return &curtab->tp_vars.dv_hashtab;
19705 if (*name == 'v') /* v: variable */
19707 if (*name == 'a' && current_funccal != NULL) /* function argument */
19708 return ¤t_funccal->l_avars.dv_hashtab;
19709 if (*name == 'l' && current_funccal != NULL) /* local function variable */
19710 return ¤t_funccal->l_vars.dv_hashtab;
19711 if (*name == 's' /* script variable */
19712 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
19713 return &SCRIPT_VARS(current_SID);
19718 * Get the string value of a (global/local) variable.
19719 * Note: see get_tv_string() for how long the pointer remains valid.
19720 * Returns NULL when it doesn't exist.
19723 get_var_value(name)
19728 v = find_var(name, NULL);
19731 return get_tv_string(&v->di_tv);
19735 * Allocate a new hashtab for a sourced script. It will be used while
19736 * sourcing this script and when executing functions defined in the script.
19739 new_script_vars(id)
19746 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
19748 /* Re-allocating ga_data means that an ht_array pointing to
19749 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
19750 * at its init value. Also reset "v_dict", it's always the same. */
19751 for (i = 1; i <= ga_scripts.ga_len; ++i)
19753 ht = &SCRIPT_VARS(i);
19754 if (ht->ht_mask == HT_INIT_SIZE - 1)
19755 ht->ht_array = ht->ht_smallarray;
19757 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
19760 while (ga_scripts.ga_len < id)
19762 sv = SCRIPT_SV(ga_scripts.ga_len + 1) =
19763 (scriptvar_T *)alloc_clear(sizeof(scriptvar_T));
19764 init_var_dict(&sv->sv_dict, &sv->sv_var);
19765 ++ga_scripts.ga_len;
19771 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
19775 init_var_dict(dict, dict_var)
19777 dictitem_T *dict_var;
19779 hash_init(&dict->dv_hashtab);
19780 dict->dv_refcount = DO_NOT_FREE_CNT;
19781 dict->dv_copyID = 0;
19782 dict_var->di_tv.vval.v_dict = dict;
19783 dict_var->di_tv.v_type = VAR_DICT;
19784 dict_var->di_tv.v_lock = VAR_FIXED;
19785 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
19786 dict_var->di_key[0] = NUL;
19790 * Clean up a list of internal variables.
19791 * Frees all allocated variables and the value they contain.
19792 * Clears hashtab "ht", does not free it.
19798 vars_clear_ext(ht, TRUE);
19802 * Like vars_clear(), but only free the value if "free_val" is TRUE.
19805 vars_clear_ext(ht, free_val)
19814 todo = (int)ht->ht_used;
19815 for (hi = ht->ht_array; todo > 0; ++hi)
19817 if (!HASHITEM_EMPTY(hi))
19821 /* Free the variable. Don't remove it from the hashtab,
19822 * ht_array might change then. hash_clear() takes care of it
19826 clear_tv(&v->di_tv);
19827 if ((v->di_flags & DI_FLAGS_FIX) == 0)
19836 * Delete a variable from hashtab "ht" at item "hi".
19837 * Clear the variable value and free the dictitem.
19844 dictitem_T *di = HI2DI(hi);
19846 hash_remove(ht, hi);
19847 clear_tv(&di->di_tv);
19852 * List the value of one internal variable.
19855 list_one_var(v, prefix, first)
19862 char_u numbuf[NUMBUFLEN];
19864 current_copyID += COPYID_INC;
19865 s = echo_string(&v->di_tv, &tofree, numbuf, current_copyID);
19866 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
19867 s == NULL ? (char_u *)"" : s, first);
19872 list_one_var_a(prefix, name, type, string, first)
19877 int *first; /* when TRUE clear rest of screen and set to FALSE */
19879 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
19882 if (name != NULL) /* "a:" vars don't have a name stored */
19886 if (type == VAR_NUMBER)
19888 else if (type == VAR_FUNC)
19890 else if (type == VAR_LIST)
19893 if (*string == '[')
19896 else if (type == VAR_DICT)
19899 if (*string == '{')
19905 msg_outtrans(string);
19907 if (type == VAR_FUNC)
19908 msg_puts((char_u *)"()");
19917 * Set variable "name" to value in "tv".
19918 * If the variable already exists, the value is updated.
19919 * Otherwise the variable is created.
19922 set_var(name, tv, copy)
19925 int copy; /* make copy of value in "tv" */
19931 ht = find_var_ht(name, &varname);
19932 if (ht == NULL || *varname == NUL)
19934 EMSG2(_(e_illvar), name);
19937 v = find_var_in_ht(ht, varname, TRUE);
19939 if (tv->v_type == VAR_FUNC && var_check_func_name(name, v == NULL))
19944 /* existing variable, need to clear the value */
19945 if (var_check_ro(v->di_flags, name)
19946 || tv_check_lock(v->di_tv.v_lock, name))
19948 if (v->di_tv.v_type != tv->v_type
19949 && !((v->di_tv.v_type == VAR_STRING
19950 || v->di_tv.v_type == VAR_NUMBER)
19951 && (tv->v_type == VAR_STRING
19952 || tv->v_type == VAR_NUMBER))
19954 && !((v->di_tv.v_type == VAR_NUMBER
19955 || v->di_tv.v_type == VAR_FLOAT)
19956 && (tv->v_type == VAR_NUMBER
19957 || tv->v_type == VAR_FLOAT))
19961 EMSG2(_("E706: Variable type mismatch for: %s"), name);
19966 * Handle setting internal v: variables separately: we don't change
19969 if (ht == &vimvarht)
19971 if (v->di_tv.v_type == VAR_STRING)
19973 vim_free(v->di_tv.vval.v_string);
19974 if (copy || tv->v_type != VAR_STRING)
19975 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
19978 /* Take over the string to avoid an extra alloc/free. */
19979 v->di_tv.vval.v_string = tv->vval.v_string;
19980 tv->vval.v_string = NULL;
19983 else if (v->di_tv.v_type != VAR_NUMBER)
19984 EMSG2(_(e_intern2), "set_var()");
19987 v->di_tv.vval.v_number = get_tv_number(tv);
19988 if (STRCMP(varname, "searchforward") == 0)
19989 set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
19994 clear_tv(&v->di_tv);
19996 else /* add a new variable */
19998 /* Can't add "v:" variable. */
19999 if (ht == &vimvarht)
20001 EMSG2(_(e_illvar), name);
20005 /* Make sure the variable name is valid. */
20006 if (!valid_varname(varname))
20009 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
20010 + STRLEN(varname)));
20013 STRCPY(v->di_key, varname);
20014 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
20022 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
20023 copy_tv(tv, &v->di_tv);
20027 v->di_tv.v_lock = 0;
20033 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
20034 * Also give an error message.
20037 var_check_ro(flags, name)
20041 if (flags & DI_FLAGS_RO)
20043 EMSG2(_(e_readonlyvar), name);
20046 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
20048 EMSG2(_(e_readonlysbx), name);
20055 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
20056 * Also give an error message.
20059 var_check_fixed(flags, name)
20063 if (flags & DI_FLAGS_FIX)
20065 EMSG2(_("E795: Cannot delete variable %s"), name);
20072 * Check if a funcref is assigned to a valid variable name.
20073 * Return TRUE and give an error if not.
20076 var_check_func_name(name, new_var)
20077 char_u *name; /* points to start of variable name */
20078 int new_var; /* TRUE when creating the variable */
20080 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
20081 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
20082 ? name[2] : name[0]))
20084 EMSG2(_("E704: Funcref variable name must start with a capital: %s"),
20088 /* Don't allow hiding a function. When "v" is not NULL we might be
20089 * assigning another function to the same var, the type is checked
20091 if (new_var && function_exists(name))
20093 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
20101 * Check if a variable name is valid.
20102 * Return FALSE and give an error if not.
20105 valid_varname(varname)
20110 for (p = varname; *p != NUL; ++p)
20111 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
20112 && *p != AUTOLOAD_CHAR)
20114 EMSG2(_(e_illvar), varname);
20121 * Return TRUE if typeval "tv" is set to be locked (immutable).
20122 * Also give an error message, using "name".
20125 tv_check_lock(lock, name)
20129 if (lock & VAR_LOCKED)
20131 EMSG2(_("E741: Value is locked: %s"),
20132 name == NULL ? (char_u *)_("Unknown") : name);
20135 if (lock & VAR_FIXED)
20137 EMSG2(_("E742: Cannot change value of %s"),
20138 name == NULL ? (char_u *)_("Unknown") : name);
20145 * Copy the values from typval_T "from" to typval_T "to".
20146 * When needed allocates string or increases reference count.
20147 * Does not make a copy of a list or dict but copies the reference!
20148 * It is OK for "from" and "to" to point to the same item. This is used to
20149 * make a copy later.
20156 to->v_type = from->v_type;
20158 switch (from->v_type)
20161 to->vval.v_number = from->vval.v_number;
20165 to->vval.v_float = from->vval.v_float;
20170 if (from->vval.v_string == NULL)
20171 to->vval.v_string = NULL;
20174 to->vval.v_string = vim_strsave(from->vval.v_string);
20175 if (from->v_type == VAR_FUNC)
20176 func_ref(to->vval.v_string);
20180 if (from->vval.v_list == NULL)
20181 to->vval.v_list = NULL;
20184 to->vval.v_list = from->vval.v_list;
20185 ++to->vval.v_list->lv_refcount;
20189 if (from->vval.v_dict == NULL)
20190 to->vval.v_dict = NULL;
20193 to->vval.v_dict = from->vval.v_dict;
20194 ++to->vval.v_dict->dv_refcount;
20198 EMSG2(_(e_intern2), "copy_tv()");
20204 * Make a copy of an item.
20205 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
20206 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
20207 * reference to an already copied list/dict can be used.
20208 * Returns FAIL or OK.
20211 item_copy(from, to, deep, copyID)
20217 static int recurse = 0;
20220 if (recurse >= DICT_MAXNEST)
20222 EMSG(_("E698: variable nested too deep for making a copy"));
20227 switch (from->v_type)
20238 to->v_type = VAR_LIST;
20240 if (from->vval.v_list == NULL)
20241 to->vval.v_list = NULL;
20242 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
20244 /* use the copy made earlier */
20245 to->vval.v_list = from->vval.v_list->lv_copylist;
20246 ++to->vval.v_list->lv_refcount;
20249 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
20250 if (to->vval.v_list == NULL)
20254 to->v_type = VAR_DICT;
20256 if (from->vval.v_dict == NULL)
20257 to->vval.v_dict = NULL;
20258 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
20260 /* use the copy made earlier */
20261 to->vval.v_dict = from->vval.v_dict->dv_copydict;
20262 ++to->vval.v_dict->dv_refcount;
20265 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
20266 if (to->vval.v_dict == NULL)
20270 EMSG2(_(e_intern2), "item_copy()");
20278 * ":echo expr1 ..." print each argument separated with a space, add a
20279 * newline at the end.
20280 * ":echon expr1 ..." print each argument plain.
20286 char_u *arg = eap->arg;
20290 int needclr = TRUE;
20291 int atstart = TRUE;
20292 char_u numbuf[NUMBUFLEN];
20296 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
20298 /* If eval1() causes an error message the text from the command may
20299 * still need to be cleared. E.g., "echo 22,44". */
20300 need_clr_eos = needclr;
20303 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
20306 * Report the invalid expression unless the expression evaluation
20307 * has been cancelled due to an aborting error, an interrupt, or an
20311 EMSG2(_(e_invexpr2), p);
20312 need_clr_eos = FALSE;
20315 need_clr_eos = FALSE;
20322 /* Call msg_start() after eval1(), evaluating the expression
20323 * may cause a message to appear. */
20324 if (eap->cmdidx == CMD_echo)
20327 else if (eap->cmdidx == CMD_echo)
20328 msg_puts_attr((char_u *)" ", echo_attr);
20329 current_copyID += COPYID_INC;
20330 p = echo_string(&rettv, &tofree, numbuf, current_copyID);
20332 for ( ; *p != NUL && !got_int; ++p)
20334 if (*p == '\n' || *p == '\r' || *p == TAB)
20336 if (*p != TAB && needclr)
20338 /* remove any text still there from the command */
20342 msg_putchar_attr(*p, echo_attr);
20349 int i = (*mb_ptr2len)(p);
20351 (void)msg_outtrans_len_attr(p, i, echo_attr);
20356 (void)msg_outtrans_len_attr(p, 1, echo_attr);
20362 arg = skipwhite(arg);
20364 eap->nextcmd = check_nextcmd(arg);
20370 /* remove text that may still be there from the command */
20373 if (eap->cmdidx == CMD_echo)
20379 * ":echohl {name}".
20387 id = syn_name2id(eap->arg);
20391 echo_attr = syn_id2attr(id);
20395 * ":execute expr1 ..." execute the result of an expression.
20396 * ":echomsg expr1 ..." Print a message
20397 * ":echoerr expr1 ..." Print an error
20398 * Each gets spaces around each argument and a newline at the end for
20405 char_u *arg = eap->arg;
20413 ga_init2(&ga, 1, 80);
20417 while (*arg != NUL && *arg != '|' && *arg != '\n')
20420 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
20423 * Report the invalid expression unless the expression evaluation
20424 * has been cancelled due to an aborting error, an interrupt, or an
20428 EMSG2(_(e_invexpr2), p);
20435 p = get_tv_string(&rettv);
20436 len = (int)STRLEN(p);
20437 if (ga_grow(&ga, len + 2) == FAIL)
20444 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
20445 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
20450 arg = skipwhite(arg);
20453 if (ret != FAIL && ga.ga_data != NULL)
20455 if (eap->cmdidx == CMD_echomsg)
20457 MSG_ATTR(ga.ga_data, echo_attr);
20460 else if (eap->cmdidx == CMD_echoerr)
20462 /* We don't want to abort following commands, restore did_emsg. */
20463 save_did_emsg = did_emsg;
20464 EMSG((char_u *)ga.ga_data);
20466 did_emsg = save_did_emsg;
20468 else if (eap->cmdidx == CMD_execute)
20469 do_cmdline((char_u *)ga.ga_data,
20470 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
20478 eap->nextcmd = check_nextcmd(arg);
20482 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
20483 * "arg" points to the "&" or '+' when called, to "option" when returning.
20484 * Returns NULL when no option name found. Otherwise pointer to the char
20485 * after the option name.
20488 find_option_end(arg, opt_flags)
20495 if (*p == 'g' && p[1] == ':')
20497 *opt_flags = OPT_GLOBAL;
20500 else if (*p == 'l' && p[1] == ':')
20502 *opt_flags = OPT_LOCAL;
20508 if (!ASCII_ISALPHA(*p))
20512 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
20513 p += 4; /* termcap option */
20515 while (ASCII_ISALPHA(*p))
20531 int saved_did_emsg;
20532 char_u *name = NULL;
20535 char_u *line_arg = NULL;
20538 int varargs = FALSE;
20539 int mustend = FALSE;
20544 char_u *skip_until = NULL;
20547 static int func_nr = 0; /* number for nameless function */
20552 int sourcing_lnum_off;
20555 * ":function" without argument: list functions.
20557 if (ends_excmd(*eap->arg))
20561 todo = (int)func_hashtab.ht_used;
20562 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
20564 if (!HASHITEM_EMPTY(hi))
20568 if (!isdigit(*fp->uf_name))
20569 list_func_head(fp, FALSE);
20573 eap->nextcmd = check_nextcmd(eap->arg);
20578 * ":function /pat": list functions matching pattern.
20580 if (*eap->arg == '/')
20582 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
20585 regmatch_T regmatch;
20589 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
20591 if (regmatch.regprog != NULL)
20593 regmatch.rm_ic = p_ic;
20595 todo = (int)func_hashtab.ht_used;
20596 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
20598 if (!HASHITEM_EMPTY(hi))
20602 if (!isdigit(*fp->uf_name)
20603 && vim_regexec(®match, fp->uf_name, 0))
20604 list_func_head(fp, FALSE);
20607 vim_free(regmatch.regprog);
20612 eap->nextcmd = check_nextcmd(p);
20617 * Get the function name. There are these situations:
20618 * func normal function name
20619 * "name" == func, "fudi.fd_dict" == NULL
20620 * dict.func new dictionary entry
20621 * "name" == NULL, "fudi.fd_dict" set,
20622 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
20623 * dict.func existing dict entry with a Funcref
20624 * "name" == func, "fudi.fd_dict" set,
20625 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
20626 * dict.func existing dict entry that's not a Funcref
20627 * "name" == NULL, "fudi.fd_dict" set,
20628 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
20631 name = trans_function_name(&p, eap->skip, 0, &fudi);
20632 paren = (vim_strchr(p, '(') != NULL);
20633 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
20636 * Return on an invalid expression in braces, unless the expression
20637 * evaluation has been cancelled due to an aborting error, an
20638 * interrupt, or an exception.
20642 if (!eap->skip && fudi.fd_newkey != NULL)
20643 EMSG2(_(e_dictkey), fudi.fd_newkey);
20644 vim_free(fudi.fd_newkey);
20651 /* An error in a function call during evaluation of an expression in magic
20652 * braces should not cause the function not to be defined. */
20653 saved_did_emsg = did_emsg;
20657 * ":function func" with only function name: list function.
20661 if (!ends_excmd(*skipwhite(p)))
20663 EMSG(_(e_trailing));
20666 eap->nextcmd = check_nextcmd(p);
20667 if (eap->nextcmd != NULL)
20669 if (!eap->skip && !got_int)
20671 fp = find_func(name);
20674 list_func_head(fp, TRUE);
20675 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
20677 if (FUNCLINE(fp, j) == NULL)
20680 msg_outnum((long)(j + 1));
20685 msg_prt_line(FUNCLINE(fp, j), FALSE);
20686 out_flush(); /* show a line at a time */
20692 msg_puts((char_u *)" endfunction");
20696 emsg_funcname(N_("E123: Undefined function: %s"), name);
20702 * ":function name(arg1, arg2)" Define function.
20709 EMSG2(_("E124: Missing '(': %s"), eap->arg);
20712 /* attempt to continue by skipping some text */
20713 if (vim_strchr(p, '(') != NULL)
20714 p = vim_strchr(p, '(');
20716 p = skipwhite(p + 1);
20718 ga_init2(&newargs, (int)sizeof(char_u *), 3);
20719 ga_init2(&newlines, (int)sizeof(char_u *), 3);
20723 /* Check the name of the function. Unless it's a dictionary function
20724 * (that we are overwriting). */
20728 arg = fudi.fd_newkey;
20729 if (arg != NULL && (fudi.fd_di == NULL
20730 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
20732 if (*arg == K_SPECIAL)
20736 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
20737 : eval_isnamec(arg[j])))
20740 emsg_funcname((char *)e_invarg2, arg);
20745 * Isolate the arguments: "arg1, arg2, ...)"
20749 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
20758 while (ASCII_ISALNUM(*p) || *p == '_')
20760 if (arg == p || isdigit(*arg)
20761 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
20762 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
20765 EMSG2(_("E125: Illegal argument: %s"), arg);
20768 if (ga_grow(&newargs, 1) == FAIL)
20772 arg = vim_strsave(arg);
20776 /* Check for duplicate argument name. */
20777 for (i = 0; i < newargs.ga_len; ++i)
20778 if (STRCMP(((char_u **)(newargs.ga_data))[i], arg) == 0)
20780 EMSG2(_("E853: Duplicate argument name: %s"), arg);
20784 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
20793 if (mustend && *p != ')')
20796 EMSG2(_(e_invarg2), eap->arg);
20800 ++p; /* skip the ')' */
20802 /* find extra arguments "range", "dict" and "abort" */
20806 if (STRNCMP(p, "range", 5) == 0)
20811 else if (STRNCMP(p, "dict", 4) == 0)
20816 else if (STRNCMP(p, "abort", 5) == 0)
20825 /* When there is a line break use what follows for the function body.
20826 * Makes 'exe "func Test()\n...\nendfunc"' work. */
20829 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
20830 EMSG(_(e_trailing));
20833 * Read the body of the function, until ":endfunction" is found.
20837 /* Check if the function already exists, don't let the user type the
20838 * whole function before telling him it doesn't work! For a script we
20839 * need to skip the body to be able to find what follows. */
20840 if (!eap->skip && !eap->forceit)
20842 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
20843 EMSG(_(e_funcdict));
20844 else if (name != NULL && find_func(name) != NULL)
20845 emsg_funcname(e_funcexts, name);
20848 if (!eap->skip && did_emsg)
20851 msg_putchar('\n'); /* don't overwrite the function name */
20852 cmdline_row = msg_row;
20861 need_wait_return = FALSE;
20862 sourcing_lnum_off = sourcing_lnum;
20864 if (line_arg != NULL)
20866 /* Use eap->arg, split up in parts by line breaks. */
20867 theline = line_arg;
20868 p = vim_strchr(theline, '\n');
20870 line_arg += STRLEN(line_arg);
20877 else if (eap->getline == NULL)
20878 theline = getcmdline(':', 0L, indent);
20880 theline = eap->getline(':', eap->cookie, indent);
20882 lines_left = Rows - 1;
20883 if (theline == NULL)
20885 EMSG(_("E126: Missing :endfunction"));
20889 /* Detect line continuation: sourcing_lnum increased more than one. */
20890 if (sourcing_lnum > sourcing_lnum_off + 1)
20891 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
20893 sourcing_lnum_off = 0;
20895 if (skip_until != NULL)
20897 /* between ":append" and "." and between ":python <<EOF" and "EOF"
20898 * don't check for ":endfunc". */
20899 if (STRCMP(theline, skip_until) == 0)
20901 vim_free(skip_until);
20907 /* skip ':' and blanks*/
20908 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
20911 /* Check for "endfunction". */
20912 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
20914 if (line_arg == NULL)
20919 /* Increase indent inside "if", "while", "for" and "try", decrease
20921 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
20923 else if (STRNCMP(p, "if", 2) == 0
20924 || STRNCMP(p, "wh", 2) == 0
20925 || STRNCMP(p, "for", 3) == 0
20926 || STRNCMP(p, "try", 3) == 0)
20929 /* Check for defining a function inside this function. */
20930 if (checkforcmd(&p, "function", 2))
20933 p = skipwhite(p + 1);
20934 p += eval_fname_script(p);
20935 if (ASCII_ISALPHA(*p))
20937 vim_free(trans_function_name(&p, TRUE, 0, NULL));
20938 if (*skipwhite(p) == '(')
20946 /* Check for ":append" or ":insert". */
20947 p = skip_range(p, NULL);
20948 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
20950 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
20951 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
20952 skip_until = vim_strsave((char_u *)".");
20954 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
20955 arg = skipwhite(skiptowhite(p));
20956 if (arg[0] == '<' && arg[1] =='<'
20957 && ((p[0] == 'p' && p[1] == 'y'
20958 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
20959 || (p[0] == 'p' && p[1] == 'e'
20960 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
20961 || (p[0] == 't' && p[1] == 'c'
20962 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
20963 || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a'
20964 && !ASCII_ISALPHA(p[3]))
20965 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
20966 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
20967 || (p[0] == 'm' && p[1] == 'z'
20968 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
20971 /* ":python <<" continues until a dot, like ":append" */
20972 p = skipwhite(arg + 2);
20974 skip_until = vim_strsave((char_u *)".");
20976 skip_until = vim_strsave(p);
20980 /* Add the line to the function. */
20981 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
20983 if (line_arg == NULL)
20988 /* Copy the line to newly allocated memory. get_one_sourceline()
20989 * allocates 250 bytes per line, this saves 80% on average. The cost
20990 * is an extra alloc/free. */
20991 p = vim_strsave(theline);
20994 if (line_arg == NULL)
20999 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
21001 /* Add NULL lines for continuation lines, so that the line count is
21002 * equal to the index in the growarray. */
21003 while (sourcing_lnum_off-- > 0)
21004 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
21006 /* Check for end of eap->arg. */
21007 if (line_arg != NULL && *line_arg == NUL)
21011 /* Don't define the function when skipping commands or when an error was
21013 if (eap->skip || did_emsg)
21017 * If there are no errors, add the function
21019 if (fudi.fd_dict == NULL)
21021 v = find_var(name, &ht);
21022 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
21024 emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
21029 fp = find_func(name);
21034 emsg_funcname(e_funcexts, name);
21037 if (fp->uf_calls > 0)
21039 emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"),
21043 /* redefine existing function */
21044 ga_clear_strings(&(fp->uf_args));
21045 ga_clear_strings(&(fp->uf_lines));
21055 if (fudi.fd_newkey == NULL && !eap->forceit)
21057 EMSG(_(e_funcdict));
21060 if (fudi.fd_di == NULL)
21062 /* Can't add a function to a locked dictionary */
21063 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
21066 /* Can't change an existing function if it is locked */
21067 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
21070 /* Give the function a sequential number. Can only be used with a
21073 sprintf(numbuf, "%d", ++func_nr);
21074 name = vim_strsave((char_u *)numbuf);
21081 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
21084 char_u *scriptname;
21086 /* Check that the autoload name matches the script name. */
21088 if (sourcing_name != NULL)
21090 scriptname = autoload_name(name);
21091 if (scriptname != NULL)
21093 p = vim_strchr(scriptname, '/');
21094 plen = (int)STRLEN(p);
21095 slen = (int)STRLEN(sourcing_name);
21096 if (slen > plen && fnamecmp(p,
21097 sourcing_name + slen - plen) == 0)
21099 vim_free(scriptname);
21104 EMSG2(_("E746: Function name does not match script file name: %s"), name);
21109 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
21113 if (fudi.fd_dict != NULL)
21115 if (fudi.fd_di == NULL)
21117 /* add new dict entry */
21118 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
21119 if (fudi.fd_di == NULL)
21124 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
21126 vim_free(fudi.fd_di);
21132 /* overwrite existing dict entry */
21133 clear_tv(&fudi.fd_di->di_tv);
21134 fudi.fd_di->di_tv.v_type = VAR_FUNC;
21135 fudi.fd_di->di_tv.v_lock = 0;
21136 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
21137 fp->uf_refcount = 1;
21139 /* behave like "dict" was used */
21143 /* insert the new function in the function list */
21144 STRCPY(fp->uf_name, name);
21145 hash_add(&func_hashtab, UF2HIKEY(fp));
21147 fp->uf_args = newargs;
21148 fp->uf_lines = newlines;
21149 #ifdef FEAT_PROFILE
21150 fp->uf_tml_count = NULL;
21151 fp->uf_tml_total = NULL;
21152 fp->uf_tml_self = NULL;
21153 fp->uf_profiling = FALSE;
21154 if (prof_def_func())
21155 func_do_profile(fp);
21157 fp->uf_varargs = varargs;
21158 fp->uf_flags = flags;
21160 fp->uf_script_ID = current_SID;
21164 ga_clear_strings(&newargs);
21165 ga_clear_strings(&newlines);
21167 vim_free(skip_until);
21168 vim_free(fudi.fd_newkey);
21170 did_emsg |= saved_did_emsg;
21174 * Get a function name, translating "<SID>" and "<SNR>".
21175 * Also handles a Funcref in a List or Dictionary.
21176 * Returns the function name in allocated memory, or NULL for failure.
21178 * TFN_INT: internal function name OK
21179 * TFN_QUIET: be quiet
21180 * Advances "pp" to just after the function name (if no error).
21183 trans_function_name(pp, skip, flags, fdp)
21185 int skip; /* only find the end, don't evaluate */
21187 funcdict_T *fdp; /* return: info about dictionary used */
21189 char_u *name = NULL;
21193 char_u sid_buf[20];
21198 vim_memset(fdp, 0, sizeof(funcdict_T));
21201 /* Check for hard coded <SNR>: already translated function ID (from a user
21203 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
21204 && (*pp)[2] == (int)KE_SNR)
21207 len = get_id_len(pp) + 3;
21208 return vim_strnsave(start, len);
21211 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
21212 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
21213 lead = eval_fname_script(start);
21217 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
21218 lead > 2 ? 0 : FNE_CHECK_START);
21222 EMSG(_("E129: Function name required"));
21225 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
21228 * Report an invalid expression in braces, unless the expression
21229 * evaluation has been cancelled due to an aborting error, an
21230 * interrupt, or an exception.
21235 EMSG2(_(e_invarg2), start);
21238 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
21242 if (lv.ll_tv != NULL)
21246 fdp->fd_dict = lv.ll_dict;
21247 fdp->fd_newkey = lv.ll_newkey;
21248 lv.ll_newkey = NULL;
21249 fdp->fd_di = lv.ll_di;
21251 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
21253 name = vim_strsave(lv.ll_tv->vval.v_string);
21258 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
21259 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
21260 EMSG(_(e_funcref));
21268 if (lv.ll_name == NULL)
21270 /* Error found, but continue after the function name. */
21275 /* Check if the name is a Funcref. If so, use the value. */
21276 if (lv.ll_exp_name != NULL)
21278 len = (int)STRLEN(lv.ll_exp_name);
21279 name = deref_func_name(lv.ll_exp_name, &len);
21280 if (name == lv.ll_exp_name)
21285 len = (int)(end - *pp);
21286 name = deref_func_name(*pp, &len);
21292 name = vim_strsave(name);
21297 if (lv.ll_exp_name != NULL)
21299 len = (int)STRLEN(lv.ll_exp_name);
21300 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
21301 && STRNCMP(lv.ll_name, "s:", 2) == 0)
21303 /* When there was "s:" already or the name expanded to get a
21304 * leading "s:" then remove it. */
21312 if (lead == 2) /* skip over "s:" */
21314 len = (int)(end - lv.ll_name);
21318 * Copy the function name to allocated memory.
21319 * Accept <SID>name() inside a script, translate into <SNR>123_name().
21320 * Accept <SNR>123_name() outside a script.
21323 lead = 0; /* do nothing */
21327 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
21328 || eval_fname_sid(*pp))
21330 /* It's "s:" or "<SID>" */
21331 if (current_SID <= 0)
21333 EMSG(_(e_usingsid));
21336 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
21337 lead += (int)STRLEN(sid_buf);
21340 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
21342 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
21345 name = alloc((unsigned)(len + lead + 1));
21350 name[0] = K_SPECIAL;
21351 name[1] = KS_EXTRA;
21352 name[2] = (int)KE_SNR;
21353 if (lead > 3) /* If it's "<SID>" */
21354 STRCPY(name + 3, sid_buf);
21356 mch_memmove(name + lead, lv.ll_name, (size_t)len);
21357 name[len + lead] = NUL;
21367 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
21368 * Return 2 if "p" starts with "s:".
21369 * Return 0 otherwise.
21372 eval_fname_script(p)
21375 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
21376 || STRNICMP(p + 1, "SNR>", 4) == 0))
21378 if (p[0] == 's' && p[1] == ':')
21384 * Return TRUE if "p" starts with "<SID>" or "s:".
21385 * Only works if eval_fname_script() returned non-zero for "p"!
21391 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
21395 * List the head of the function: "name(arg1, arg2)".
21398 list_func_head(fp, indent)
21407 MSG_PUTS("function ");
21408 if (fp->uf_name[0] == K_SPECIAL)
21410 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
21411 msg_puts(fp->uf_name + 3);
21414 msg_puts(fp->uf_name);
21416 for (j = 0; j < fp->uf_args.ga_len; ++j)
21420 msg_puts(FUNCARG(fp, j));
21422 if (fp->uf_varargs)
21431 last_set_msg(fp->uf_script_ID);
21435 * Find a function by name, return pointer to it in ufuncs.
21436 * Return NULL for unknown function.
21444 hi = hash_find(&func_hashtab, name);
21445 if (!HASHITEM_EMPTY(hi))
21450 #if defined(EXITFREE) || defined(PROTO)
21452 free_all_functions()
21456 /* Need to start all over every time, because func_free() may change the
21458 while (func_hashtab.ht_used > 0)
21459 for (hi = func_hashtab.ht_array; ; ++hi)
21460 if (!HASHITEM_EMPTY(hi))
21462 func_free(HI2UF(hi));
21469 * Return TRUE if a function "name" exists.
21472 function_exists(name)
21479 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
21480 nm = skipwhite(nm);
21482 /* Only accept "funcname", "funcname ", "funcname (..." and
21483 * "funcname(...", not "funcname!...". */
21484 if (p != NULL && (*nm == NUL || *nm == '('))
21486 if (builtin_function(p))
21487 n = (find_internal_func(p) >= 0);
21489 n = (find_func(p) != NULL);
21496 * Return TRUE if "name" looks like a builtin function name: starts with a
21497 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
21500 builtin_function(name)
21503 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
21504 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
21507 #if defined(FEAT_PROFILE) || defined(PROTO)
21509 * Start profiling function "fp".
21512 func_do_profile(fp)
21515 int len = fp->uf_lines.ga_len;
21518 len = 1; /* avoid getting error for allocating zero bytes */
21519 fp->uf_tm_count = 0;
21520 profile_zero(&fp->uf_tm_self);
21521 profile_zero(&fp->uf_tm_total);
21522 if (fp->uf_tml_count == NULL)
21523 fp->uf_tml_count = (int *)alloc_clear((unsigned) (sizeof(int) * len));
21524 if (fp->uf_tml_total == NULL)
21525 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
21526 (sizeof(proftime_T) * len));
21527 if (fp->uf_tml_self == NULL)
21528 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
21529 (sizeof(proftime_T) * len));
21530 fp->uf_tml_idx = -1;
21531 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
21532 || fp->uf_tml_self == NULL)
21533 return; /* out of memory */
21535 fp->uf_profiling = TRUE;
21539 * Dump the profiling results for all functions in file "fd".
21542 func_dump_profile(fd)
21552 todo = (int)func_hashtab.ht_used;
21554 return; /* nothing to dump */
21556 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
21558 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
21560 if (!HASHITEM_EMPTY(hi))
21564 if (fp->uf_profiling)
21566 if (sorttab != NULL)
21567 sorttab[st_len++] = fp;
21569 if (fp->uf_name[0] == K_SPECIAL)
21570 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
21572 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
21573 if (fp->uf_tm_count == 1)
21574 fprintf(fd, "Called 1 time\n");
21576 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
21577 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
21578 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
21580 fprintf(fd, "count total (s) self (s)\n");
21582 for (i = 0; i < fp->uf_lines.ga_len; ++i)
21584 if (FUNCLINE(fp, i) == NULL)
21586 prof_func_line(fd, fp->uf_tml_count[i],
21587 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
21588 fprintf(fd, "%s\n", FUNCLINE(fp, i));
21595 if (sorttab != NULL && st_len > 0)
21597 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
21599 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
21600 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
21602 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
21609 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
21614 int prefer_self; /* when equal print only self time */
21619 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
21620 fprintf(fd, "count total (s) self (s) function\n");
21621 for (i = 0; i < 20 && i < st_len; ++i)
21624 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
21626 if (fp->uf_name[0] == K_SPECIAL)
21627 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
21629 fprintf(fd, " %s()\n", fp->uf_name);
21635 * Print the count and times for one function or function line.
21638 prof_func_line(fd, count, total, self, prefer_self)
21643 int prefer_self; /* when equal print only self time */
21647 fprintf(fd, "%5d ", count);
21648 if (prefer_self && profile_equal(total, self))
21651 fprintf(fd, "%s ", profile_msg(total));
21652 if (!prefer_self && profile_equal(total, self))
21655 fprintf(fd, "%s ", profile_msg(self));
21662 * Compare function for total time sorting.
21665 #ifdef __BORLANDC__
21668 prof_total_cmp(s1, s2)
21674 p1 = *(ufunc_T **)s1;
21675 p2 = *(ufunc_T **)s2;
21676 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
21680 * Compare function for self time sorting.
21683 #ifdef __BORLANDC__
21686 prof_self_cmp(s1, s2)
21692 p1 = *(ufunc_T **)s1;
21693 p2 = *(ufunc_T **)s2;
21694 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
21700 * If "name" has a package name try autoloading the script for it.
21701 * Return TRUE if a package was loaded.
21704 script_autoload(name, reload)
21706 int reload; /* load script again when already loaded */
21709 char_u *scriptname, *tofree;
21713 /* Return quickly when autoload disabled. */
21717 /* If there is no '#' after name[0] there is no package name. */
21718 p = vim_strchr(name, AUTOLOAD_CHAR);
21719 if (p == NULL || p == name)
21722 tofree = scriptname = autoload_name(name);
21724 /* Find the name in the list of previously loaded package names. Skip
21725 * "autoload/", it's always the same. */
21726 for (i = 0; i < ga_loaded.ga_len; ++i)
21727 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
21729 if (!reload && i < ga_loaded.ga_len)
21730 ret = FALSE; /* was loaded already */
21733 /* Remember the name if it wasn't loaded already. */
21734 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
21736 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
21740 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
21741 if (source_runtime(scriptname, FALSE) == OK)
21750 * Return the autoload script name for a function or variable name.
21751 * Returns NULL when out of memory.
21754 autoload_name(name)
21758 char_u *scriptname;
21760 /* Get the script file name: replace '#' with '/', append ".vim". */
21761 scriptname = alloc((unsigned)(STRLEN(name) + 14));
21762 if (scriptname == NULL)
21764 STRCPY(scriptname, "autoload/");
21765 STRCAT(scriptname, name);
21766 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
21767 STRCAT(scriptname, ".vim");
21768 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
21773 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
21776 * Function given to ExpandGeneric() to obtain the list of user defined
21780 get_user_func_name(xp, idx)
21784 static long_u done;
21785 static hashitem_T *hi;
21791 hi = func_hashtab.ht_array;
21793 if (done < func_hashtab.ht_used)
21797 while (HASHITEM_EMPTY(hi))
21801 if (fp->uf_flags & FC_DICT)
21802 return NULL; /* don't show dict functions */
21804 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
21805 return fp->uf_name; /* prevents overflow */
21807 cat_func_name(IObuff, fp);
21808 if (xp->xp_context != EXPAND_USER_FUNC)
21810 STRCAT(IObuff, "(");
21811 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
21812 STRCAT(IObuff, ")");
21819 #endif /* FEAT_CMDL_COMPL */
21822 * Copy the function name of "fp" to buffer "buf".
21823 * "buf" must be able to hold the function name plus three bytes.
21824 * Takes care of script-local function names.
21827 cat_func_name(buf, fp)
21831 if (fp->uf_name[0] == K_SPECIAL)
21833 STRCPY(buf, "<SNR>");
21834 STRCAT(buf, fp->uf_name + 3);
21837 STRCPY(buf, fp->uf_name);
21841 * ":delfunction {name}"
21844 ex_delfunction(eap)
21847 ufunc_T *fp = NULL;
21853 name = trans_function_name(&p, eap->skip, 0, &fudi);
21854 vim_free(fudi.fd_newkey);
21857 if (fudi.fd_dict != NULL && !eap->skip)
21858 EMSG(_(e_funcref));
21861 if (!ends_excmd(*skipwhite(p)))
21864 EMSG(_(e_trailing));
21867 eap->nextcmd = check_nextcmd(p);
21868 if (eap->nextcmd != NULL)
21872 fp = find_func(name);
21879 EMSG2(_(e_nofunc), eap->arg);
21882 if (fp->uf_calls > 0)
21884 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
21888 if (fudi.fd_dict != NULL)
21890 /* Delete the dict item that refers to the function, it will
21891 * invoke func_unref() and possibly delete the function. */
21892 dictitem_remove(fudi.fd_dict, fudi.fd_di);
21900 * Free a function and remove it from the list of functions.
21908 /* clear this function */
21909 ga_clear_strings(&(fp->uf_args));
21910 ga_clear_strings(&(fp->uf_lines));
21911 #ifdef FEAT_PROFILE
21912 vim_free(fp->uf_tml_count);
21913 vim_free(fp->uf_tml_total);
21914 vim_free(fp->uf_tml_self);
21917 /* remove the function from the function hashtable */
21918 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
21919 if (HASHITEM_EMPTY(hi))
21920 EMSG2(_(e_intern2), "func_free()");
21922 hash_remove(&func_hashtab, hi);
21928 * Unreference a Function: decrement the reference count and free it when it
21929 * becomes zero. Only for numbered functions.
21937 if (name != NULL && isdigit(*name))
21939 fp = find_func(name);
21941 EMSG2(_(e_intern2), "func_unref()");
21942 else if (--fp->uf_refcount <= 0)
21944 /* Only delete it when it's not being used. Otherwise it's done
21945 * when "uf_calls" becomes zero. */
21946 if (fp->uf_calls == 0)
21953 * Count a reference to a Function.
21961 if (name != NULL && isdigit(*name))
21963 fp = find_func(name);
21965 EMSG2(_(e_intern2), "func_ref()");
21972 * Call a user function.
21975 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
21976 ufunc_T *fp; /* pointer to function */
21977 int argcount; /* nr of args */
21978 typval_T *argvars; /* arguments */
21979 typval_T *rettv; /* return value */
21980 linenr_T firstline; /* first line of range */
21981 linenr_T lastline; /* last line of range */
21982 dict_T *selfdict; /* Dictionary for "self" */
21984 char_u *save_sourcing_name;
21985 linenr_T save_sourcing_lnum;
21986 scid_T save_current_SID;
21989 static int depth = 0;
21991 int fixvar_idx = 0; /* index in fixvar[] */
21994 char_u numbuf[NUMBUFLEN];
21996 #ifdef FEAT_PROFILE
21997 proftime_T wait_start;
21998 proftime_T call_start;
22001 /* If depth of calling is getting too high, don't execute the function */
22002 if (depth >= p_mfd)
22004 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
22005 rettv->v_type = VAR_NUMBER;
22006 rettv->vval.v_number = -1;
22011 line_breakcheck(); /* check for CTRL-C hit */
22013 fc = (funccall_T *)alloc(sizeof(funccall_T));
22014 fc->caller = current_funccal;
22015 current_funccal = fc;
22018 rettv->vval.v_number = 0;
22020 fc->returned = FALSE;
22021 fc->level = ex_nesting_level;
22022 /* Check if this function has a breakpoint. */
22023 fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
22024 fc->dbg_tick = debug_tick;
22027 * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables
22028 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
22029 * each argument variable and saves a lot of time.
22032 * Init l: variables.
22034 init_var_dict(&fc->l_vars, &fc->l_vars_var);
22035 if (selfdict != NULL)
22037 /* Set l:self to "selfdict". Use "name" to avoid a warning from
22038 * some compiler that checks the destination size. */
22039 v = &fc->fixvar[fixvar_idx++].var;
22041 STRCPY(name, "self");
22042 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
22043 hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
22044 v->di_tv.v_type = VAR_DICT;
22045 v->di_tv.v_lock = 0;
22046 v->di_tv.vval.v_dict = selfdict;
22047 ++selfdict->dv_refcount;
22051 * Init a: variables.
22052 * Set a:0 to "argcount".
22053 * Set a:000 to a list with room for the "..." arguments.
22055 init_var_dict(&fc->l_avars, &fc->l_avars_var);
22056 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0",
22057 (varnumber_T)(argcount - fp->uf_args.ga_len));
22058 /* Use "name" to avoid a warning from some compiler that checks the
22059 * destination size. */
22060 v = &fc->fixvar[fixvar_idx++].var;
22062 STRCPY(name, "000");
22063 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
22064 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
22065 v->di_tv.v_type = VAR_LIST;
22066 v->di_tv.v_lock = VAR_FIXED;
22067 v->di_tv.vval.v_list = &fc->l_varlist;
22068 vim_memset(&fc->l_varlist, 0, sizeof(list_T));
22069 fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT;
22070 fc->l_varlist.lv_lock = VAR_FIXED;
22073 * Set a:firstline to "firstline" and a:lastline to "lastline".
22074 * Set a:name to named arguments.
22075 * Set a:N to the "..." arguments.
22077 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline",
22078 (varnumber_T)firstline);
22079 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline",
22080 (varnumber_T)lastline);
22081 for (i = 0; i < argcount; ++i)
22083 ai = i - fp->uf_args.ga_len;
22085 /* named argument a:name */
22086 name = FUNCARG(fp, i);
22089 /* "..." argument a:1, a:2, etc. */
22090 sprintf((char *)numbuf, "%d", ai + 1);
22093 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
22095 v = &fc->fixvar[fixvar_idx++].var;
22096 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
22100 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
22104 v->di_flags = DI_FLAGS_RO;
22106 STRCPY(v->di_key, name);
22107 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
22109 /* Note: the values are copied directly to avoid alloc/free.
22110 * "argvars" must have VAR_FIXED for v_lock. */
22111 v->di_tv = argvars[i];
22112 v->di_tv.v_lock = VAR_FIXED;
22114 if (ai >= 0 && ai < MAX_FUNC_ARGS)
22116 list_append(&fc->l_varlist, &fc->l_listitems[ai]);
22117 fc->l_listitems[ai].li_tv = argvars[i];
22118 fc->l_listitems[ai].li_tv.v_lock = VAR_FIXED;
22122 /* Don't redraw while executing the function. */
22123 ++RedrawingDisabled;
22124 save_sourcing_name = sourcing_name;
22125 save_sourcing_lnum = sourcing_lnum;
22127 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
22128 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
22129 if (sourcing_name != NULL)
22131 if (save_sourcing_name != NULL
22132 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
22133 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
22135 STRCPY(sourcing_name, "function ");
22136 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
22138 if (p_verbose >= 12)
22141 verbose_enter_scroll();
22143 smsg((char_u *)_("calling %s"), sourcing_name);
22144 if (p_verbose >= 14)
22146 char_u buf[MSG_BUF_LEN];
22147 char_u numbuf2[NUMBUFLEN];
22151 msg_puts((char_u *)"(");
22152 for (i = 0; i < argcount; ++i)
22155 msg_puts((char_u *)", ");
22156 if (argvars[i].v_type == VAR_NUMBER)
22157 msg_outnum((long)argvars[i].vval.v_number);
22160 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
22163 trunc_string(s, buf, MSG_BUF_CLEN);
22169 msg_puts((char_u *)")");
22171 msg_puts((char_u *)"\n"); /* don't overwrite this either */
22173 verbose_leave_scroll();
22177 #ifdef FEAT_PROFILE
22178 if (do_profiling == PROF_YES)
22180 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
22181 func_do_profile(fp);
22182 if (fp->uf_profiling
22183 || (fc->caller != NULL && fc->caller->func->uf_profiling))
22186 profile_start(&call_start);
22187 profile_zero(&fp->uf_tm_children);
22189 script_prof_save(&wait_start);
22193 save_current_SID = current_SID;
22194 current_SID = fp->uf_script_ID;
22195 save_did_emsg = did_emsg;
22198 /* call do_cmdline() to execute the lines */
22199 do_cmdline(NULL, get_func_line, (void *)fc,
22200 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
22202 --RedrawingDisabled;
22204 /* when the function was aborted because of an error, return -1 */
22205 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
22208 rettv->v_type = VAR_NUMBER;
22209 rettv->vval.v_number = -1;
22212 #ifdef FEAT_PROFILE
22213 if (do_profiling == PROF_YES && (fp->uf_profiling
22214 || (fc->caller != NULL && fc->caller->func->uf_profiling)))
22216 profile_end(&call_start);
22217 profile_sub_wait(&wait_start, &call_start);
22218 profile_add(&fp->uf_tm_total, &call_start);
22219 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
22220 if (fc->caller != NULL && fc->caller->func->uf_profiling)
22222 profile_add(&fc->caller->func->uf_tm_children, &call_start);
22223 profile_add(&fc->caller->func->uf_tml_children, &call_start);
22228 /* when being verbose, mention the return value */
22229 if (p_verbose >= 12)
22232 verbose_enter_scroll();
22235 smsg((char_u *)_("%s aborted"), sourcing_name);
22236 else if (fc->rettv->v_type == VAR_NUMBER)
22237 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
22238 (long)fc->rettv->vval.v_number);
22241 char_u buf[MSG_BUF_LEN];
22242 char_u numbuf2[NUMBUFLEN];
22246 /* The value may be very long. Skip the middle part, so that we
22247 * have some idea how it starts and ends. smsg() would always
22248 * truncate it at the end. */
22249 s = tv2string(fc->rettv, &tofree, numbuf2, 0);
22252 trunc_string(s, buf, MSG_BUF_CLEN);
22253 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
22257 msg_puts((char_u *)"\n"); /* don't overwrite this either */
22259 verbose_leave_scroll();
22263 vim_free(sourcing_name);
22264 sourcing_name = save_sourcing_name;
22265 sourcing_lnum = save_sourcing_lnum;
22266 current_SID = save_current_SID;
22267 #ifdef FEAT_PROFILE
22268 if (do_profiling == PROF_YES)
22269 script_prof_restore(&wait_start);
22272 if (p_verbose >= 12 && sourcing_name != NULL)
22275 verbose_enter_scroll();
22277 smsg((char_u *)_("continuing in %s"), sourcing_name);
22278 msg_puts((char_u *)"\n"); /* don't overwrite this either */
22280 verbose_leave_scroll();
22284 did_emsg |= save_did_emsg;
22285 current_funccal = fc->caller;
22288 /* If the a:000 list and the l: and a: dicts are not referenced we can
22289 * free the funccall_T and what's in it. */
22290 if (fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
22291 && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
22292 && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT)
22294 free_funccal(fc, FALSE);
22302 /* "fc" is still in use. This can happen when returning "a:000" or
22303 * assigning "l:" to a global variable.
22304 * Link "fc" in the list for garbage collection later. */
22305 fc->caller = previous_funccal;
22306 previous_funccal = fc;
22308 /* Make a copy of the a: variables, since we didn't do that above. */
22309 todo = (int)fc->l_avars.dv_hashtab.ht_used;
22310 for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi)
22312 if (!HASHITEM_EMPTY(hi))
22316 copy_tv(&v->di_tv, &v->di_tv);
22320 /* Make a copy of the a:000 items, since we didn't do that above. */
22321 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
22322 copy_tv(&li->li_tv, &li->li_tv);
22327 * Return TRUE if items in "fc" do not have "copyID". That means they are not
22328 * referenced from anywhere that is in use.
22331 can_free_funccal(fc, copyID)
22335 return (fc->l_varlist.lv_copyID != copyID
22336 && fc->l_vars.dv_copyID != copyID
22337 && fc->l_avars.dv_copyID != copyID);
22341 * Free "fc" and what it contains.
22344 free_funccal(fc, free_val)
22346 int free_val; /* a: vars were allocated */
22350 /* The a: variables typevals may not have been allocated, only free the
22351 * allocated variables. */
22352 vars_clear_ext(&fc->l_avars.dv_hashtab, free_val);
22354 /* free all l: variables */
22355 vars_clear(&fc->l_vars.dv_hashtab);
22357 /* Free the a:000 variables if they were allocated. */
22359 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
22360 clear_tv(&li->li_tv);
22366 * Add a number variable "name" to dict "dp" with value "nr".
22369 add_nr_var(dp, v, name, nr)
22375 STRCPY(v->di_key, name);
22376 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
22377 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
22378 v->di_tv.v_type = VAR_NUMBER;
22379 v->di_tv.v_lock = VAR_FIXED;
22380 v->di_tv.vval.v_number = nr;
22390 char_u *arg = eap->arg;
22392 int returning = FALSE;
22394 if (current_funccal == NULL)
22396 EMSG(_("E133: :return not inside a function"));
22403 eap->nextcmd = NULL;
22404 if ((*arg != NUL && *arg != '|' && *arg != '\n')
22405 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
22408 returning = do_return(eap, FALSE, TRUE, &rettv);
22412 /* It's safer to return also on error. */
22413 else if (!eap->skip)
22416 * Return unless the expression evaluation has been cancelled due to an
22417 * aborting error, an interrupt, or an exception.
22420 returning = do_return(eap, FALSE, TRUE, NULL);
22423 /* When skipping or the return gets pending, advance to the next command
22424 * in this line (!returning). Otherwise, ignore the rest of the line.
22425 * Following lines will be ignored by get_func_line(). */
22427 eap->nextcmd = NULL;
22428 else if (eap->nextcmd == NULL) /* no argument */
22429 eap->nextcmd = check_nextcmd(arg);
22436 * Return from a function. Possibly makes the return pending. Also called
22437 * for a pending return at the ":endtry" or after returning from an extra
22438 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
22439 * when called due to a ":return" command. "rettv" may point to a typval_T
22440 * with the return rettv. Returns TRUE when the return can be carried out,
22441 * FALSE when the return gets pending.
22444 do_return(eap, reanimate, is_cmd, rettv)
22451 struct condstack *cstack = eap->cstack;
22454 /* Undo the return. */
22455 current_funccal->returned = FALSE;
22458 * Cleanup (and inactivate) conditionals, but stop when a try conditional
22459 * not in its finally clause (which then is to be executed next) is found.
22460 * In this case, make the ":return" pending for execution at the ":endtry".
22461 * Otherwise, return normally.
22463 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
22466 cstack->cs_pending[idx] = CSTP_RETURN;
22468 if (!is_cmd && !reanimate)
22469 /* A pending return again gets pending. "rettv" points to an
22470 * allocated variable with the rettv of the original ":return"'s
22471 * argument if present or is NULL else. */
22472 cstack->cs_rettv[idx] = rettv;
22475 /* When undoing a return in order to make it pending, get the stored
22478 rettv = current_funccal->rettv;
22482 /* Store the value of the pending return. */
22483 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
22484 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
22486 EMSG(_(e_outofmem));
22489 cstack->cs_rettv[idx] = NULL;
22493 /* The pending return value could be overwritten by a ":return"
22494 * without argument in a finally clause; reset the default
22496 current_funccal->rettv->v_type = VAR_NUMBER;
22497 current_funccal->rettv->vval.v_number = 0;
22500 report_make_pending(CSTP_RETURN, rettv);
22504 current_funccal->returned = TRUE;
22506 /* If the return is carried out now, store the return value. For
22507 * a return immediately after reanimation, the value is already
22509 if (!reanimate && rettv != NULL)
22511 clear_tv(current_funccal->rettv);
22512 *current_funccal->rettv = *(typval_T *)rettv;
22522 * Free the variable with a pending return value.
22525 discard_pending_return(rettv)
22528 free_tv((typval_T *)rettv);
22532 * Generate a return command for producing the value of "rettv". The result
22533 * is an allocated string. Used by report_pending() for verbose messages.
22536 get_return_cmd(rettv)
22540 char_u *tofree = NULL;
22541 char_u numbuf[NUMBUFLEN];
22544 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
22548 STRCPY(IObuff, ":return ");
22549 STRNCPY(IObuff + 8, s, IOSIZE - 8);
22550 if (STRLEN(s) + 8 >= IOSIZE)
22551 STRCPY(IObuff + IOSIZE - 4, "...");
22553 return vim_strsave(IObuff);
22557 * Get next function line.
22558 * Called by do_cmdline() to get the next line.
22559 * Returns allocated string, or NULL for end of function.
22562 get_func_line(c, cookie, indent)
22567 funccall_T *fcp = (funccall_T *)cookie;
22568 ufunc_T *fp = fcp->func;
22570 garray_T *gap; /* growarray with function lines */
22572 /* If breakpoints have been added/deleted need to check for it. */
22573 if (fcp->dbg_tick != debug_tick)
22575 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
22577 fcp->dbg_tick = debug_tick;
22579 #ifdef FEAT_PROFILE
22580 if (do_profiling == PROF_YES)
22581 func_line_end(cookie);
22584 gap = &fp->uf_lines;
22585 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
22590 /* Skip NULL lines (continuation lines). */
22591 while (fcp->linenr < gap->ga_len
22592 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
22594 if (fcp->linenr >= gap->ga_len)
22598 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
22599 sourcing_lnum = fcp->linenr;
22600 #ifdef FEAT_PROFILE
22601 if (do_profiling == PROF_YES)
22602 func_line_start(cookie);
22607 /* Did we encounter a breakpoint? */
22608 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
22610 dbg_breakpoint(fp->uf_name, sourcing_lnum);
22611 /* Find next breakpoint. */
22612 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
22614 fcp->dbg_tick = debug_tick;
22620 #if defined(FEAT_PROFILE) || defined(PROTO)
22622 * Called when starting to read a function line.
22623 * "sourcing_lnum" must be correct!
22624 * When skipping lines it may not actually be executed, but we won't find out
22625 * until later and we need to store the time now.
22628 func_line_start(cookie)
22631 funccall_T *fcp = (funccall_T *)cookie;
22632 ufunc_T *fp = fcp->func;
22634 if (fp->uf_profiling && sourcing_lnum >= 1
22635 && sourcing_lnum <= fp->uf_lines.ga_len)
22637 fp->uf_tml_idx = sourcing_lnum - 1;
22638 /* Skip continuation lines. */
22639 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
22641 fp->uf_tml_execed = FALSE;
22642 profile_start(&fp->uf_tml_start);
22643 profile_zero(&fp->uf_tml_children);
22644 profile_get_wait(&fp->uf_tml_wait);
22649 * Called when actually executing a function line.
22652 func_line_exec(cookie)
22655 funccall_T *fcp = (funccall_T *)cookie;
22656 ufunc_T *fp = fcp->func;
22658 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
22659 fp->uf_tml_execed = TRUE;
22663 * Called when done with a function line.
22666 func_line_end(cookie)
22669 funccall_T *fcp = (funccall_T *)cookie;
22670 ufunc_T *fp = fcp->func;
22672 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
22674 if (fp->uf_tml_execed)
22676 ++fp->uf_tml_count[fp->uf_tml_idx];
22677 profile_end(&fp->uf_tml_start);
22678 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
22679 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
22680 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
22681 &fp->uf_tml_children);
22683 fp->uf_tml_idx = -1;
22689 * Return TRUE if the currently active function should be ended, because a
22690 * return was encountered or an error occurred. Used inside a ":while".
22693 func_has_ended(cookie)
22696 funccall_T *fcp = (funccall_T *)cookie;
22698 /* Ignore the "abort" flag if the abortion behavior has been changed due to
22699 * an error inside a try conditional. */
22700 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
22705 * return TRUE if cookie indicates a function which "abort"s on errors.
22708 func_has_abort(cookie)
22711 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
22714 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
22717 VAR_FLAVOUR_DEFAULT, /* doesn't start with uppercase */
22718 VAR_FLAVOUR_SESSION, /* starts with uppercase, some lower */
22719 VAR_FLAVOUR_VIMINFO /* all uppercase */
22722 static var_flavour_T var_flavour __ARGS((char_u *varname));
22724 static var_flavour_T
22725 var_flavour(varname)
22728 char_u *p = varname;
22730 if (ASCII_ISUPPER(*p))
22733 if (ASCII_ISLOWER(*p))
22734 return VAR_FLAVOUR_SESSION;
22735 return VAR_FLAVOUR_VIMINFO;
22738 return VAR_FLAVOUR_DEFAULT;
22742 #if defined(FEAT_VIMINFO) || defined(PROTO)
22744 * Restore global vars that start with a capital from the viminfo file
22747 read_viminfo_varlist(virp, writing)
22752 int type = VAR_NUMBER;
22755 if (!writing && (find_viminfo_parameter('!') != NULL))
22757 tab = vim_strchr(virp->vir_line + 1, '\t');
22760 *tab++ = '\0'; /* isolate the variable name */
22763 case 'S': type = VAR_STRING; break;
22765 case 'F': type = VAR_FLOAT; break;
22767 case 'D': type = VAR_DICT; break;
22768 case 'L': type = VAR_LIST; break;
22771 tab = vim_strchr(tab, '\t');
22775 if (type == VAR_STRING || type == VAR_DICT || type == VAR_LIST)
22776 tv.vval.v_string = viminfo_readstring(virp,
22777 (int)(tab - virp->vir_line + 1), TRUE);
22779 else if (type == VAR_FLOAT)
22780 (void)string2float(tab + 1, &tv.vval.v_float);
22783 tv.vval.v_number = atol((char *)tab + 1);
22784 if (type == VAR_DICT || type == VAR_LIST)
22786 typval_T *etv = eval_expr(tv.vval.v_string, NULL);
22789 /* Failed to parse back the dict or list, use it as a
22791 tv.v_type = VAR_STRING;
22794 vim_free(tv.vval.v_string);
22799 set_var(virp->vir_line + 1, &tv, FALSE);
22801 if (tv.v_type == VAR_STRING)
22802 vim_free(tv.vval.v_string);
22803 else if (tv.v_type == VAR_DICT || tv.v_type == VAR_LIST)
22809 return viminfo_readline(virp);
22813 * Write global vars that start with a capital to the viminfo file
22816 write_viminfo_varlist(fp)
22820 dictitem_T *this_var;
22825 char_u numbuf[NUMBUFLEN];
22827 if (find_viminfo_parameter('!') == NULL)
22830 fputs(_("\n# global variables:\n"), fp);
22832 todo = (int)globvarht.ht_used;
22833 for (hi = globvarht.ht_array; todo > 0; ++hi)
22835 if (!HASHITEM_EMPTY(hi))
22838 this_var = HI2DI(hi);
22839 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
22841 switch (this_var->di_tv.v_type)
22843 case VAR_STRING: s = "STR"; break;
22844 case VAR_NUMBER: s = "NUM"; break;
22846 case VAR_FLOAT: s = "FLO"; break;
22848 case VAR_DICT: s = "DIC"; break;
22849 case VAR_LIST: s = "LIS"; break;
22852 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
22853 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
22855 viminfo_writestring(fp, p);
22863 #if defined(FEAT_SESSION) || defined(PROTO)
22865 store_session_globals(fd)
22869 dictitem_T *this_var;
22873 todo = (int)globvarht.ht_used;
22874 for (hi = globvarht.ht_array; todo > 0; ++hi)
22876 if (!HASHITEM_EMPTY(hi))
22879 this_var = HI2DI(hi);
22880 if ((this_var->di_tv.v_type == VAR_NUMBER
22881 || this_var->di_tv.v_type == VAR_STRING)
22882 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22884 /* Escape special characters with a backslash. Turn a LF and
22885 * CR into \n and \r. */
22886 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
22887 (char_u *)"\\\"\n\r");
22888 if (p == NULL) /* out of memory */
22890 for (t = p; *t != NUL; ++t)
22893 else if (*t == '\r')
22895 if ((fprintf(fd, "let %s = %c%s%c",
22897 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22900 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22902 || put_eol(fd) == FAIL)
22910 else if (this_var->di_tv.v_type == VAR_FLOAT
22911 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22913 float_T f = this_var->di_tv.vval.v_float;
22921 if ((fprintf(fd, "let %s = %c&%f",
22922 this_var->di_key, sign, f) < 0)
22923 || put_eol(fd) == FAIL)
22934 * Display script name where an item was last set.
22935 * Should only be invoked when 'verbose' is non-zero.
22938 last_set_msg(scriptID)
22945 p = home_replace_save(NULL, get_scriptname(scriptID));
22949 MSG_PUTS(_("\n\tLast set from "));
22958 * List v:oldfiles in a nice way.
22962 exarg_T *eap UNUSED;
22964 list_T *l = vimvars[VV_OLDFILES].vv_list;
22969 msg((char_u *)_("No old files"));
22974 for (li = l->lv_first; li != NULL && !got_int; li = li->li_next)
22976 msg_outnum((long)++nr);
22978 msg_outtrans(get_tv_string(&li->li_tv));
22980 out_flush(); /* output one line at a time */
22983 /* Assume "got_int" was set to truncate the listing. */
22986 #ifdef FEAT_BROWSE_CMD
22990 nr = prompt_for_number(FALSE);
22994 char_u *p = list_find_str(get_vim_var_list(VV_OLDFILES),
22999 p = expand_env_save(p);
23001 eap->cmdidx = CMD_edit;
23002 cmdmod.browse = FALSE;
23003 do_exedit(eap, NULL);
23012 #endif /* FEAT_EVAL */
23015 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
23019 * Functions for ":8" filename modifier: get 8.3 version of a filename.
23021 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
23022 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
23023 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
23026 * Get the short path (8.3) for the filename in "fnamep".
23027 * Only works for a valid file name.
23028 * When the path gets longer "fnamep" is changed and the allocated buffer
23029 * is put in "bufp".
23030 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
23031 * Returns OK on success, FAIL on failure.
23034 get_short_pathname(fnamep, bufp, fnamelen)
23043 l = GetShortPathName(*fnamep, *fnamep, len);
23046 /* If that doesn't work (not enough space), then save the string
23047 * and try again with a new buffer big enough. */
23048 newbuf = vim_strnsave(*fnamep, l);
23049 if (newbuf == NULL)
23053 *fnamep = *bufp = newbuf;
23055 /* Really should always succeed, as the buffer is big enough. */
23056 l = GetShortPathName(*fnamep, *fnamep, l+1);
23064 * Get the short path (8.3) for the filename in "fname". The converted
23065 * path is returned in "bufp".
23067 * Some of the directories specified in "fname" may not exist. This function
23068 * will shorten the existing directories at the beginning of the path and then
23069 * append the remaining non-existing path.
23071 * fname - Pointer to the filename to shorten. On return, contains the
23072 * pointer to the shortened pathname
23073 * bufp - Pointer to an allocated buffer for the filename.
23074 * fnamelen - Length of the filename pointed to by fname
23076 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
23079 shortpath_for_invalid_fname(fname, bufp, fnamelen)
23084 char_u *short_fname, *save_fname, *pbuf_unused;
23085 char_u *endp, *save_endp;
23088 int new_len, sfx_len;
23092 old_len = *fnamelen;
23093 save_fname = vim_strnsave(*fname, old_len);
23094 pbuf_unused = NULL;
23095 short_fname = NULL;
23097 endp = save_fname + old_len - 1; /* Find the end of the copy */
23101 * Try shortening the supplied path till it succeeds by removing one
23102 * directory at a time from the tail of the path.
23107 /* go back one path-separator */
23108 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
23110 if (endp <= save_fname)
23111 break; /* processed the complete path */
23114 * Replace the path separator with a NUL and try to shorten the
23119 short_fname = save_fname;
23120 len = (int)STRLEN(short_fname) + 1;
23121 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
23126 *endp = ch; /* preserve the string */
23129 break; /* successfully shortened the path */
23131 /* failed to shorten the path. Skip the path separator */
23138 * Succeeded in shortening the path. Now concatenate the shortened
23139 * path with the remaining path at the tail.
23142 /* Compute the length of the new path. */
23143 sfx_len = (int)(save_endp - endp) + 1;
23144 new_len = len + sfx_len;
23146 *fnamelen = new_len;
23148 if (new_len > old_len)
23150 /* There is not enough space in the currently allocated string,
23151 * copy it to a buffer big enough. */
23152 *fname = *bufp = vim_strnsave(short_fname, new_len);
23153 if (*fname == NULL)
23161 /* Transfer short_fname to the main buffer (it's big enough),
23162 * unless get_short_pathname() did its work in-place. */
23163 *fname = *bufp = save_fname;
23164 if (short_fname != save_fname)
23165 vim_strncpy(save_fname, short_fname, len);
23169 /* concat the not-shortened part of the path */
23170 vim_strncpy(*fname + len, endp, sfx_len);
23171 (*fname)[new_len] = NUL;
23175 vim_free(pbuf_unused);
23176 vim_free(save_fname);
23182 * Get a pathname for a partial path.
23183 * Returns OK for success, FAIL for failure.
23186 shortpath_for_partial(fnamep, bufp, fnamelen)
23191 int sepcount, len, tflen;
23193 char_u *pbuf, *tfname;
23196 /* Count up the path separators from the RHS.. so we know which part
23197 * of the path to return. */
23199 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
23200 if (vim_ispathsep(*p))
23203 /* Need full path first (use expand_env() to remove a "~/") */
23204 hasTilde = (**fnamep == '~');
23206 pbuf = tfname = expand_env_save(*fnamep);
23208 pbuf = tfname = FullName_save(*fnamep, FALSE);
23210 len = tflen = (int)STRLEN(tfname);
23212 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
23217 /* Don't have a valid filename, so shorten the rest of the
23218 * path if we can. This CAN give us invalid 8.3 filenames, but
23219 * there's not a lot of point in guessing what it might be.
23222 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
23226 /* Count the paths backward to find the beginning of the desired string. */
23227 for (p = tfname + len - 1; p >= tfname; --p)
23231 p -= mb_head_off(tfname, p);
23233 if (vim_ispathsep(*p))
23235 if (sepcount == 0 || (hasTilde && sepcount == 1))
23252 /* Copy in the string - p indexes into tfname - allocated at pbuf */
23254 *fnamelen = (int)STRLEN(p);
23260 #endif /* WIN3264 */
23263 * Adjust a filename, according to a string of modifiers.
23264 * *fnamep must be NUL terminated when called. When returning, the length is
23265 * determined by *fnamelen.
23266 * Returns VALID_ flags or -1 for failure.
23267 * When there is an error, *fnamep is set to NULL.
23270 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
23271 char_u *src; /* string with modifiers */
23272 int *usedlen; /* characters after src that are used */
23273 char_u **fnamep; /* file name so far */
23274 char_u **bufp; /* buffer for allocated file name or NULL */
23275 int *fnamelen; /* length of fnamep */
23279 char_u *s, *p, *pbuf;
23280 char_u dirname[MAXPATHL];
23282 int has_fullname = 0;
23284 char_u *fname_start = *fnamep;
23285 int has_shortname = 0;
23289 /* ":p" - full path/file_name */
23290 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
23294 valid |= VALID_PATH;
23297 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
23298 if ((*fnamep)[0] == '~'
23299 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
23300 && ((*fnamep)[1] == '/'
23301 # ifdef BACKSLASH_IN_FILENAME
23302 || (*fnamep)[1] == '\\'
23304 || (*fnamep)[1] == NUL)
23309 *fnamep = expand_env_save(*fnamep);
23310 vim_free(*bufp); /* free any allocated file name */
23312 if (*fnamep == NULL)
23316 /* When "/." or "/.." is used: force expansion to get rid of it. */
23317 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
23319 if (vim_ispathsep(*p)
23322 || vim_ispathsep(p[2])
23324 && (p[3] == NUL || vim_ispathsep(p[3])))))
23328 /* FullName_save() is slow, don't use it when not needed. */
23329 if (*p != NUL || !vim_isAbsName(*fnamep))
23331 *fnamep = FullName_save(*fnamep, *p != NUL);
23332 vim_free(*bufp); /* free any allocated file name */
23334 if (*fnamep == NULL)
23338 /* Append a path separator to a directory. */
23339 if (mch_isdir(*fnamep))
23341 /* Make room for one or two extra characters. */
23342 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
23343 vim_free(*bufp); /* free any allocated file name */
23345 if (*fnamep == NULL)
23347 add_pathsep(*fnamep);
23351 /* ":." - path relative to the current directory */
23352 /* ":~" - path relative to the home directory */
23353 /* ":8" - shortname path - postponed till after */
23354 while (src[*usedlen] == ':'
23355 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
23361 has_shortname = 1; /* Postpone this. */
23366 /* Need full path first (use expand_env() to remove a "~/") */
23369 if (c == '.' && **fnamep == '~')
23370 p = pbuf = expand_env_save(*fnamep);
23372 p = pbuf = FullName_save(*fnamep, FALSE);
23383 mch_dirname(dirname, MAXPATHL);
23384 s = shorten_fname(p, dirname);
23390 vim_free(*bufp); /* free any allocated file name */
23398 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
23399 /* Only replace it when it starts with '~' */
23400 if (*dirname == '~')
23402 s = vim_strsave(dirname);
23415 tail = gettail(*fnamep);
23416 *fnamelen = (int)STRLEN(*fnamep);
23418 /* ":h" - head, remove "/file_name", can be repeated */
23419 /* Don't remove the first "/" or "c:\" */
23420 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
23422 valid |= VALID_HEAD;
23424 s = get_past_head(*fnamep);
23425 while (tail > s && after_pathsep(s, tail))
23426 mb_ptr_back(*fnamep, tail);
23427 *fnamelen = (int)(tail - *fnamep);
23430 *fnamelen += 1; /* the path separator is part of the path */
23432 if (*fnamelen == 0)
23434 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
23435 p = vim_strsave((char_u *)".");
23439 *bufp = *fnamep = tail = p;
23444 while (tail > s && !after_pathsep(s, tail))
23445 mb_ptr_back(*fnamep, tail);
23449 /* ":8" - shortname */
23450 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
23460 * Handle ":8" after we have done 'heads' and before we do 'tails'.
23464 /* Copy the string if it is shortened by :h and when it wasn't copied
23465 * yet, because we are going to change it in place. Avoids changing
23466 * the buffer name for "%:8". */
23467 if (*fnamelen < (int)STRLEN(*fnamep) || *fnamep == fname_start)
23469 p = vim_strnsave(*fnamep, *fnamelen);
23473 *bufp = *fnamep = p;
23476 /* Split into two implementations - makes it easier. First is where
23477 * there isn't a full name already, second is where there is. */
23478 if (!has_fullname && !vim_isAbsName(*fnamep))
23480 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
23487 /* Simple case, already have the full-name.
23488 * Nearly always shorter, so try first time. */
23489 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
23494 /* Couldn't find the filename, search the paths. */
23496 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
23502 #endif /* WIN3264 */
23504 /* ":t" - tail, just the basename */
23505 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
23508 *fnamelen -= (int)(tail - *fnamep);
23512 /* ":e" - extension, can be repeated */
23513 /* ":r" - root, without extension, can be repeated */
23514 while (src[*usedlen] == ':'
23515 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
23517 /* find a '.' in the tail:
23518 * - for second :e: before the current fname
23519 * - otherwise: The last '.'
23521 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
23524 s = *fnamep + *fnamelen - 1;
23525 for ( ; s > tail; --s)
23528 if (src[*usedlen + 1] == 'e') /* :e */
23532 *fnamelen += (int)(*fnamep - (s + 1));
23535 /* cut version from the extension */
23536 s = *fnamep + *fnamelen - 1;
23537 for ( ; s > *fnamep; --s)
23541 *fnamelen = s - *fnamep;
23544 else if (*fnamep <= tail)
23549 if (s > tail) /* remove one extension */
23550 *fnamelen = (int)(s - *fnamep);
23555 /* ":s?pat?foo?" - substitute */
23556 /* ":gs?pat?foo?" - global substitute */
23557 if (src[*usedlen] == ':'
23558 && (src[*usedlen + 1] == 's'
23559 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
23568 flags = (char_u *)"";
23569 s = src + *usedlen + 2;
23570 if (src[*usedlen + 1] == 'g')
23572 flags = (char_u *)"g";
23579 /* find end of pattern */
23580 p = vim_strchr(s, sep);
23583 pat = vim_strnsave(s, (int)(p - s));
23587 /* find end of substitution */
23588 p = vim_strchr(s, sep);
23591 sub = vim_strnsave(s, (int)(p - s));
23592 str = vim_strnsave(*fnamep, *fnamelen);
23593 if (sub != NULL && str != NULL)
23595 *usedlen = (int)(p + 1 - src);
23596 s = do_string_sub(str, pat, sub, flags);
23600 *fnamelen = (int)STRLEN(s);
23612 /* after using ":s", repeat all the modifiers */
23622 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
23623 * "flags" can be "g" to do a global substitute.
23624 * Returns an allocated string, NULL for error.
23627 do_string_sub(str, pat, sub, flags)
23634 regmatch_T regmatch;
23642 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
23644 p_cpo = empty_option;
23646 ga_init2(&ga, 1, 200);
23648 do_all = (flags[0] == 'g');
23650 regmatch.rm_ic = p_ic;
23651 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
23652 if (regmatch.regprog != NULL)
23655 while (vim_regexec_nl(®match, str, (colnr_T)(tail - str)))
23658 * Get some space for a temporary buffer to do the substitution
23659 * into. It will contain:
23660 * - The text up to where the match is.
23661 * - The substituted text.
23662 * - The text after the match.
23664 sublen = vim_regsub(®match, sub, tail, FALSE, TRUE, FALSE);
23665 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
23666 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
23672 /* copy the text up to where the match is */
23673 i = (int)(regmatch.startp[0] - tail);
23674 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
23675 /* add the substituted text */
23676 (void)vim_regsub(®match, sub, (char_u *)ga.ga_data
23677 + ga.ga_len + i, TRUE, TRUE, FALSE);
23678 ga.ga_len += i + sublen - 1;
23679 /* avoid getting stuck on a match with an empty string */
23680 if (tail == regmatch.endp[0])
23684 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
23689 tail = regmatch.endp[0];
23697 if (ga.ga_data != NULL)
23698 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
23700 vim_free(regmatch.regprog);
23703 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
23705 if (p_cpo == empty_option)
23708 /* Darn, evaluating {sub} expression changed the value. */
23709 free_string_option(save_cpo);
23714 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */