Merge commit 'vim_mainline/vim' into floating_point
[vim_extended.git] / src / eval.c
blobf6cf4e8b7de2b5c2a801b0d8e20796b1cd80e58c
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
11 * eval.c: Expression evaluation.
13 #if defined(MSDOS) || defined(WIN16) || defined(WIN32) || defined(_WIN64)
14 # include "vimio.h" /* for mch_open(), must be before vim.h */
15 #endif
17 #include "vim.h"
19 #if defined(FEAT_EVAL) || defined(PROTO)
21 #ifdef AMIGA
22 # include <time.h> /* for strftime() */
23 #endif
25 #ifdef MACOS
26 # include <time.h> /* for time_t */
27 #endif
29 #if defined(FEAT_FLOAT) && defined(HAVE_MATH_H)
30 # include <math.h>
31 #endif
33 #define DICT_MAXNEST 100 /* maximum nesting of lists and dicts */
35 #define DO_NOT_FREE_CNT 99999 /* refcount for dict or list that should not
36 be freed. */
39 * In a hashtab item "hi_key" points to "di_key" in a dictitem.
40 * This avoids adding a pointer to the hashtab item.
41 * DI2HIKEY() converts a dictitem pointer to a hashitem key pointer.
42 * HIKEY2DI() converts a hashitem key pointer to a dictitem pointer.
43 * HI2DI() converts a hashitem pointer to a dictitem pointer.
45 static dictitem_T dumdi;
46 #define DI2HIKEY(di) ((di)->di_key)
47 #define HIKEY2DI(p) ((dictitem_T *)(p - (dumdi.di_key - (char_u *)&dumdi)))
48 #define HI2DI(hi) HIKEY2DI((hi)->hi_key)
51 * Structure returned by get_lval() and used by set_var_lval().
52 * For a plain name:
53 * "name" points to the variable name.
54 * "exp_name" is NULL.
55 * "tv" is NULL
56 * For a magic braces name:
57 * "name" points to the expanded variable name.
58 * "exp_name" is non-NULL, to be freed later.
59 * "tv" is NULL
60 * For an index in a list:
61 * "name" points to the (expanded) variable name.
62 * "exp_name" NULL or non-NULL, to be freed later.
63 * "tv" points to the (first) list item value
64 * "li" points to the (first) list item
65 * "range", "n1", "n2" and "empty2" indicate what items are used.
66 * For an existing Dict item:
67 * "name" points to the (expanded) variable name.
68 * "exp_name" NULL or non-NULL, to be freed later.
69 * "tv" points to the dict item value
70 * "newkey" is NULL
71 * For a non-existing Dict item:
72 * "name" points to the (expanded) variable name.
73 * "exp_name" NULL or non-NULL, to be freed later.
74 * "tv" points to the Dictionary typval_T
75 * "newkey" is the key for the new item.
77 typedef struct lval_S
79 char_u *ll_name; /* start of variable name (can be NULL) */
80 char_u *ll_exp_name; /* NULL or expanded name in allocated memory. */
81 typval_T *ll_tv; /* Typeval of item being used. If "newkey"
82 isn't NULL it's the Dict to which to add
83 the item. */
84 listitem_T *ll_li; /* The list item or NULL. */
85 list_T *ll_list; /* The list or NULL. */
86 int ll_range; /* TRUE when a [i:j] range was used */
87 long ll_n1; /* First index for list */
88 long ll_n2; /* Second index for list range */
89 int ll_empty2; /* Second index is empty: [i:] */
90 dict_T *ll_dict; /* The Dictionary or NULL */
91 dictitem_T *ll_di; /* The dictitem or NULL */
92 char_u *ll_newkey; /* New key for Dict in alloc. mem or NULL. */
93 } lval_T;
96 static char *e_letunexp = N_("E18: Unexpected characters in :let");
97 static char *e_listidx = N_("E684: list index out of range: %ld");
98 static char *e_undefvar = N_("E121: Undefined variable: %s");
99 static char *e_missbrac = N_("E111: Missing ']'");
100 static char *e_listarg = N_("E686: Argument of %s must be a List");
101 static char *e_listdictarg = N_("E712: Argument of %s must be a List or Dictionary");
102 static char *e_emptykey = N_("E713: Cannot use empty key for Dictionary");
103 static char *e_listreq = N_("E714: List required");
104 static char *e_dictreq = N_("E715: Dictionary required");
105 static char *e_toomanyarg = N_("E118: Too many arguments for function: %s");
106 static char *e_dictkey = N_("E716: Key not present in Dictionary: %s");
107 static char *e_funcexts = N_("E122: Function %s already exists, add ! to replace it");
108 static char *e_funcdict = N_("E717: Dictionary entry already exists");
109 static char *e_funcref = N_("E718: Funcref required");
110 static char *e_dictrange = N_("E719: Cannot use [:] with a Dictionary");
111 static char *e_letwrong = N_("E734: Wrong variable type for %s=");
112 static char *e_nofunc = N_("E130: Unknown function: %s");
113 static char *e_illvar = N_("E461: Illegal variable name: %s");
116 * All user-defined global variables are stored in dictionary "globvardict".
117 * "globvars_var" is the variable that is used for "g:".
119 static dict_T globvardict;
120 static dictitem_T globvars_var;
121 #define globvarht globvardict.dv_hashtab
124 * Old Vim variables such as "v:version" are also available without the "v:".
125 * Also in functions. We need a special hashtable for them.
127 static hashtab_T compat_hashtab;
130 * When recursively copying lists and dicts we need to remember which ones we
131 * have done to avoid endless recursiveness. This unique ID is used for that.
133 static int current_copyID = 0;
136 * Array to hold the hashtab with variables local to each sourced script.
137 * Each item holds a variable (nameless) that points to the dict_T.
139 typedef struct
141 dictitem_T sv_var;
142 dict_T sv_dict;
143 } scriptvar_T;
145 static garray_T ga_scripts = {0, 0, sizeof(scriptvar_T), 4, NULL};
146 #define SCRIPT_SV(id) (((scriptvar_T *)ga_scripts.ga_data)[(id) - 1])
147 #define SCRIPT_VARS(id) (SCRIPT_SV(id).sv_dict.dv_hashtab)
149 static int echo_attr = 0; /* attributes used for ":echo" */
151 /* Values for trans_function_name() argument: */
152 #define TFN_INT 1 /* internal function name OK */
153 #define TFN_QUIET 2 /* no error messages */
156 * Structure to hold info for a user function.
158 typedef struct ufunc ufunc_T;
160 struct ufunc
162 int uf_varargs; /* variable nr of arguments */
163 int uf_flags;
164 int uf_calls; /* nr of active calls */
165 garray_T uf_args; /* arguments */
166 garray_T uf_lines; /* function lines */
167 #ifdef FEAT_PROFILE
168 int uf_profiling; /* TRUE when func is being profiled */
169 /* profiling the function as a whole */
170 int uf_tm_count; /* nr of calls */
171 proftime_T uf_tm_total; /* time spent in function + children */
172 proftime_T uf_tm_self; /* time spent in function itself */
173 proftime_T uf_tm_children; /* time spent in children this call */
174 /* profiling the function per line */
175 int *uf_tml_count; /* nr of times line was executed */
176 proftime_T *uf_tml_total; /* time spent in a line + children */
177 proftime_T *uf_tml_self; /* time spent in a line itself */
178 proftime_T uf_tml_start; /* start time for current line */
179 proftime_T uf_tml_children; /* time spent in children for this line */
180 proftime_T uf_tml_wait; /* start wait time for current line */
181 int uf_tml_idx; /* index of line being timed; -1 if none */
182 int uf_tml_execed; /* line being timed was executed */
183 #endif
184 scid_T uf_script_ID; /* ID of script where function was defined,
185 used for s: variables */
186 int uf_refcount; /* for numbered function: reference count */
187 char_u uf_name[1]; /* name of function (actually longer); can
188 start with <SNR>123_ (<SNR> is K_SPECIAL
189 KS_EXTRA KE_SNR) */
192 /* function flags */
193 #define FC_ABORT 1 /* abort function on error */
194 #define FC_RANGE 2 /* function accepts range */
195 #define FC_DICT 4 /* Dict function, uses "self" */
198 * All user-defined functions are found in this hashtable.
200 static hashtab_T func_hashtab;
202 /* The names of packages that once were loaded are remembered. */
203 static garray_T ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
205 /* list heads for garbage collection */
206 static dict_T *first_dict = NULL; /* list of all dicts */
207 static list_T *first_list = NULL; /* list of all lists */
209 /* From user function to hashitem and back. */
210 static ufunc_T dumuf;
211 #define UF2HIKEY(fp) ((fp)->uf_name)
212 #define HIKEY2UF(p) ((ufunc_T *)(p - (dumuf.uf_name - (char_u *)&dumuf)))
213 #define HI2UF(hi) HIKEY2UF((hi)->hi_key)
215 #define FUNCARG(fp, j) ((char_u **)(fp->uf_args.ga_data))[j]
216 #define FUNCLINE(fp, j) ((char_u **)(fp->uf_lines.ga_data))[j]
218 #define MAX_FUNC_ARGS 20 /* maximum number of function arguments */
219 #define VAR_SHORT_LEN 20 /* short variable name length */
220 #define FIXVAR_CNT 12 /* number of fixed variables */
222 /* structure to hold info for a function that is currently being executed. */
223 typedef struct funccall_S funccall_T;
225 struct funccall_S
227 ufunc_T *func; /* function being called */
228 int linenr; /* next line to be executed */
229 int returned; /* ":return" used */
230 struct /* fixed variables for arguments */
232 dictitem_T var; /* variable (without room for name) */
233 char_u room[VAR_SHORT_LEN]; /* room for the name */
234 } fixvar[FIXVAR_CNT];
235 dict_T l_vars; /* l: local function variables */
236 dictitem_T l_vars_var; /* variable for l: scope */
237 dict_T l_avars; /* a: argument variables */
238 dictitem_T l_avars_var; /* variable for a: scope */
239 list_T l_varlist; /* list for a:000 */
240 listitem_T l_listitems[MAX_FUNC_ARGS]; /* listitems for a:000 */
241 typval_T *rettv; /* return value */
242 linenr_T breakpoint; /* next line with breakpoint or zero */
243 int dbg_tick; /* debug_tick when breakpoint was set */
244 int level; /* top nesting level of executed function */
245 #ifdef FEAT_PROFILE
246 proftime_T prof_child; /* time spent in a child */
247 #endif
248 funccall_T *caller; /* calling function or NULL */
252 * Info used by a ":for" loop.
254 typedef struct
256 int fi_semicolon; /* TRUE if ending in '; var]' */
257 int fi_varcount; /* nr of variables in the list */
258 listwatch_T fi_lw; /* keep an eye on the item used. */
259 list_T *fi_list; /* list being used */
260 } forinfo_T;
263 * Struct used by trans_function_name()
265 typedef struct
267 dict_T *fd_dict; /* Dictionary used */
268 char_u *fd_newkey; /* new key in "dict" in allocated memory */
269 dictitem_T *fd_di; /* Dictionary item used */
270 } funcdict_T;
274 * Array to hold the value of v: variables.
275 * The value is in a dictitem, so that it can also be used in the v: scope.
276 * The reason to use this table anyway is for very quick access to the
277 * variables with the VV_ defines.
279 #include "version.h"
281 /* values for vv_flags: */
282 #define VV_COMPAT 1 /* compatible, also used without "v:" */
283 #define VV_RO 2 /* read-only */
284 #define VV_RO_SBX 4 /* read-only in the sandbox */
286 #define VV_NAME(s, t) s, {{t}}, {0}
288 static struct vimvar
290 char *vv_name; /* name of variable, without v: */
291 dictitem_T vv_di; /* value and name for key */
292 char vv_filler[16]; /* space for LONGEST name below!!! */
293 char vv_flags; /* VV_COMPAT, VV_RO, VV_RO_SBX */
294 } vimvars[VV_LEN] =
297 * The order here must match the VV_ defines in vim.h!
298 * Initializing a union does not work, leave tv.vval empty to get zero's.
300 {VV_NAME("count", VAR_NUMBER), VV_COMPAT+VV_RO},
301 {VV_NAME("count1", VAR_NUMBER), VV_RO},
302 {VV_NAME("prevcount", VAR_NUMBER), VV_RO},
303 {VV_NAME("errmsg", VAR_STRING), VV_COMPAT},
304 {VV_NAME("warningmsg", VAR_STRING), 0},
305 {VV_NAME("statusmsg", VAR_STRING), 0},
306 {VV_NAME("shell_error", VAR_NUMBER), VV_COMPAT+VV_RO},
307 {VV_NAME("this_session", VAR_STRING), VV_COMPAT},
308 {VV_NAME("version", VAR_NUMBER), VV_COMPAT+VV_RO},
309 {VV_NAME("lnum", VAR_NUMBER), VV_RO_SBX},
310 {VV_NAME("termresponse", VAR_STRING), VV_RO},
311 {VV_NAME("fname", VAR_STRING), VV_RO},
312 {VV_NAME("lang", VAR_STRING), VV_RO},
313 {VV_NAME("lc_time", VAR_STRING), VV_RO},
314 {VV_NAME("ctype", VAR_STRING), VV_RO},
315 {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
316 {VV_NAME("charconvert_to", VAR_STRING), VV_RO},
317 {VV_NAME("fname_in", VAR_STRING), VV_RO},
318 {VV_NAME("fname_out", VAR_STRING), VV_RO},
319 {VV_NAME("fname_new", VAR_STRING), VV_RO},
320 {VV_NAME("fname_diff", VAR_STRING), VV_RO},
321 {VV_NAME("cmdarg", VAR_STRING), VV_RO},
322 {VV_NAME("foldstart", VAR_NUMBER), VV_RO_SBX},
323 {VV_NAME("foldend", VAR_NUMBER), VV_RO_SBX},
324 {VV_NAME("folddashes", VAR_STRING), VV_RO_SBX},
325 {VV_NAME("foldlevel", VAR_NUMBER), VV_RO_SBX},
326 {VV_NAME("progname", VAR_STRING), VV_RO},
327 {VV_NAME("servername", VAR_STRING), VV_RO},
328 {VV_NAME("dying", VAR_NUMBER), VV_RO},
329 {VV_NAME("exception", VAR_STRING), VV_RO},
330 {VV_NAME("throwpoint", VAR_STRING), VV_RO},
331 {VV_NAME("register", VAR_STRING), VV_RO},
332 {VV_NAME("cmdbang", VAR_NUMBER), VV_RO},
333 {VV_NAME("insertmode", VAR_STRING), VV_RO},
334 {VV_NAME("val", VAR_UNKNOWN), VV_RO},
335 {VV_NAME("key", VAR_UNKNOWN), VV_RO},
336 {VV_NAME("profiling", VAR_NUMBER), VV_RO},
337 {VV_NAME("fcs_reason", VAR_STRING), VV_RO},
338 {VV_NAME("fcs_choice", VAR_STRING), 0},
339 {VV_NAME("beval_bufnr", VAR_NUMBER), VV_RO},
340 {VV_NAME("beval_winnr", VAR_NUMBER), VV_RO},
341 {VV_NAME("beval_lnum", VAR_NUMBER), VV_RO},
342 {VV_NAME("beval_col", VAR_NUMBER), VV_RO},
343 {VV_NAME("beval_text", VAR_STRING), VV_RO},
344 {VV_NAME("scrollstart", VAR_STRING), 0},
345 {VV_NAME("swapname", VAR_STRING), VV_RO},
346 {VV_NAME("swapchoice", VAR_STRING), 0},
347 {VV_NAME("swapcommand", VAR_STRING), VV_RO},
348 {VV_NAME("char", VAR_STRING), VV_RO},
349 {VV_NAME("mouse_win", VAR_NUMBER), 0},
350 {VV_NAME("mouse_lnum", VAR_NUMBER), 0},
351 {VV_NAME("mouse_col", VAR_NUMBER), 0},
352 {VV_NAME("operator", VAR_STRING), VV_RO},
353 {VV_NAME("searchforward", VAR_NUMBER), 0},
354 {VV_NAME("oldfiles", VAR_LIST), 0},
357 /* shorthand */
358 #define vv_type vv_di.di_tv.v_type
359 #define vv_nr vv_di.di_tv.vval.v_number
360 #define vv_float vv_di.di_tv.vval.v_float
361 #define vv_str vv_di.di_tv.vval.v_string
362 #define vv_list vv_di.di_tv.vval.v_list
363 #define vv_tv vv_di.di_tv
366 * The v: variables are stored in dictionary "vimvardict".
367 * "vimvars_var" is the variable that is used for the "l:" scope.
369 static dict_T vimvardict;
370 static dictitem_T vimvars_var;
371 #define vimvarht vimvardict.dv_hashtab
373 static void prepare_vimvar __ARGS((int idx, typval_T *save_tv));
374 static void restore_vimvar __ARGS((int idx, typval_T *save_tv));
375 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
376 static int call_vim_function __ARGS((char_u *func, int argc, char_u **argv, int safe, typval_T *rettv));
377 #endif
378 static int ex_let_vars __ARGS((char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars));
379 static char_u *skip_var_list __ARGS((char_u *arg, int *var_count, int *semicolon));
380 static char_u *skip_var_one __ARGS((char_u *arg));
381 static void list_hashtable_vars __ARGS((hashtab_T *ht, char_u *prefix, int empty, int *first));
382 static void list_glob_vars __ARGS((int *first));
383 static void list_buf_vars __ARGS((int *first));
384 static void list_win_vars __ARGS((int *first));
385 #ifdef FEAT_WINDOWS
386 static void list_tab_vars __ARGS((int *first));
387 #endif
388 static void list_vim_vars __ARGS((int *first));
389 static void list_script_vars __ARGS((int *first));
390 static void list_func_vars __ARGS((int *first));
391 static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg, int *first));
392 static char_u *ex_let_one __ARGS((char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op));
393 static int check_changedtick __ARGS((char_u *arg));
394 static char_u *get_lval __ARGS((char_u *name, typval_T *rettv, lval_T *lp, int unlet, int skip, int quiet, int fne_flags));
395 static void clear_lval __ARGS((lval_T *lp));
396 static void set_var_lval __ARGS((lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op));
397 static int tv_op __ARGS((typval_T *tv1, typval_T *tv2, char_u *op));
398 static void list_add_watch __ARGS((list_T *l, listwatch_T *lw));
399 static void list_rem_watch __ARGS((list_T *l, listwatch_T *lwrem));
400 static void list_fix_watch __ARGS((list_T *l, listitem_T *item));
401 static void ex_unletlock __ARGS((exarg_T *eap, char_u *argstart, int deep));
402 static int do_unlet_var __ARGS((lval_T *lp, char_u *name_end, int forceit));
403 static int do_lock_var __ARGS((lval_T *lp, char_u *name_end, int deep, int lock));
404 static void item_lock __ARGS((typval_T *tv, int deep, int lock));
405 static int tv_islocked __ARGS((typval_T *tv));
407 static int eval0 __ARGS((char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate));
408 static int eval1 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
409 static int eval2 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
410 static int eval3 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
411 static int eval4 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
412 static int eval5 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
413 static int eval6 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
414 static int eval7 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
416 static int eval_index __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
417 static int get_option_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
418 static int get_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
419 static int get_lit_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
420 static int get_list_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
421 static int rettv_list_alloc __ARGS((typval_T *rettv));
422 static listitem_T *listitem_alloc __ARGS((void));
423 static void listitem_free __ARGS((listitem_T *item));
424 static void listitem_remove __ARGS((list_T *l, listitem_T *item));
425 static long list_len __ARGS((list_T *l));
426 static int list_equal __ARGS((list_T *l1, list_T *l2, int ic));
427 static int dict_equal __ARGS((dict_T *d1, dict_T *d2, int ic));
428 static int tv_equal __ARGS((typval_T *tv1, typval_T *tv2, int ic));
429 static listitem_T *list_find __ARGS((list_T *l, long n));
430 static long list_find_nr __ARGS((list_T *l, long idx, int *errorp));
431 static long list_idx_of_item __ARGS((list_T *l, listitem_T *item));
432 static void list_append __ARGS((list_T *l, listitem_T *item));
433 static int list_append_tv __ARGS((list_T *l, typval_T *tv));
434 static int list_append_number __ARGS((list_T *l, varnumber_T n));
435 static int list_insert_tv __ARGS((list_T *l, typval_T *tv, listitem_T *item));
436 static int list_extend __ARGS((list_T *l1, list_T *l2, listitem_T *bef));
437 static int list_concat __ARGS((list_T *l1, list_T *l2, typval_T *tv));
438 static list_T *list_copy __ARGS((list_T *orig, int deep, int copyID));
439 static void list_remove __ARGS((list_T *l, listitem_T *item, listitem_T *item2));
440 static char_u *list2string __ARGS((typval_T *tv, int copyID));
441 static int list_join __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo, int copyID));
442 static void set_ref_in_ht __ARGS((hashtab_T *ht, int copyID));
443 static void set_ref_in_list __ARGS((list_T *l, int copyID));
444 static void set_ref_in_item __ARGS((typval_T *tv, int copyID));
445 static void dict_unref __ARGS((dict_T *d));
446 static void dict_free __ARGS((dict_T *d, int recurse));
447 static dictitem_T *dictitem_alloc __ARGS((char_u *key));
448 static dictitem_T *dictitem_copy __ARGS((dictitem_T *org));
449 static void dictitem_remove __ARGS((dict_T *dict, dictitem_T *item));
450 static void dictitem_free __ARGS((dictitem_T *item));
451 static dict_T *dict_copy __ARGS((dict_T *orig, int deep, int copyID));
452 static int dict_add __ARGS((dict_T *d, dictitem_T *item));
453 static long dict_len __ARGS((dict_T *d));
454 static dictitem_T *dict_find __ARGS((dict_T *d, char_u *key, int len));
455 static char_u *dict2string __ARGS((typval_T *tv, int copyID));
456 static int get_dict_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
457 static char_u *echo_string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
458 static char_u *tv2string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
459 static char_u *string_quote __ARGS((char_u *str, int function));
460 #ifdef FEAT_FLOAT
461 static int string2float __ARGS((char_u *text, float_T *value));
462 #endif
463 static int get_env_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
464 static int find_internal_func __ARGS((char_u *name));
465 static char_u *deref_func_name __ARGS((char_u *name, int *lenp));
466 static int get_func_tv __ARGS((char_u *name, int len, typval_T *rettv, char_u **arg, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
467 static int call_func __ARGS((char_u *name, int len, typval_T *rettv, int argcount, typval_T *argvars, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
468 static void emsg_funcname __ARGS((char *ermsg, char_u *name));
469 static int non_zero_arg __ARGS((typval_T *argvars));
471 #ifdef FEAT_FLOAT
472 static void f_abs __ARGS((typval_T *argvars, typval_T *rettv));
474 /* Below are the 10 added FP functions - I've kept them together */
475 /* here and in their definitions later on. Because the functions[] */
476 /* table must be in ASCII order, they are scattered there - WJMc */
478 static void f_acos __ARGS((typval_T *argvars, typval_T *rettv));
479 static void f_asin __ARGS((typval_T *argvars, typval_T *rettv));
480 static void f_atan2 __ARGS((typval_T *argvars, typval_T *rettv)); /* 2 args */
481 static void f_cosh __ARGS((typval_T *argvars, typval_T *rettv));
482 static void f_exp __ARGS((typval_T *argvars, typval_T *rettv));
483 static void f_fmod __ARGS((typval_T *argvars, typval_T *rettv)); /* 2 args */
484 static void f_log __ARGS((typval_T *argvars, typval_T *rettv));
485 static void f_sinh __ARGS((typval_T *argvars, typval_T *rettv));
486 static void f_tan __ARGS((typval_T *argvars, typval_T *rettv));
487 static void f_tanh __ARGS((typval_T *argvars, typval_T *rettv));
488 #endif
489 static void f_add __ARGS((typval_T *argvars, typval_T *rettv));
490 static void f_append __ARGS((typval_T *argvars, typval_T *rettv));
491 static void f_argc __ARGS((typval_T *argvars, typval_T *rettv));
492 static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv));
493 static void f_argv __ARGS((typval_T *argvars, typval_T *rettv));
494 #ifdef FEAT_FLOAT
495 static void f_atan __ARGS((typval_T *argvars, typval_T *rettv));
496 #endif
497 static void f_browse __ARGS((typval_T *argvars, typval_T *rettv));
498 static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv));
499 static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv));
500 static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv));
501 static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv));
502 static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv));
503 static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv));
504 static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv));
505 static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv));
506 static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv));
507 static void f_call __ARGS((typval_T *argvars, typval_T *rettv));
508 #ifdef FEAT_FLOAT
509 static void f_ceil __ARGS((typval_T *argvars, typval_T *rettv));
510 #endif
511 static void f_changenr __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv));
513 static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv));
514 static void f_clearmatches __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_col __ARGS((typval_T *argvars, typval_T *rettv));
516 #if defined(FEAT_INS_EXPAND)
517 static void f_complete __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv));
520 #endif
521 static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_copy __ARGS((typval_T *argvars, typval_T *rettv));
523 #ifdef FEAT_FLOAT
524 static void f_cos __ARGS((typval_T *argvars, typval_T *rettv));
525 #endif
526 static void f_count __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv));
528 static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv));
529 static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_delete __ARGS((typval_T *argvars, typval_T *rettv));
531 static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv));
532 static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv));
533 static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv));
534 static void f_empty __ARGS((typval_T *argvars, typval_T *rettv));
535 static void f_escape __ARGS((typval_T *argvars, typval_T *rettv));
536 static void f_eval __ARGS((typval_T *argvars, typval_T *rettv));
537 static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_executable __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_exists __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_expand __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_extend __ARGS((typval_T *argvars, typval_T *rettv));
542 static void f_feedkeys __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_filter __ARGS((typval_T *argvars, typval_T *rettv));
546 static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv));
547 static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv));
548 #ifdef FEAT_FLOAT
549 static void f_float2nr __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_floor __ARGS((typval_T *argvars, typval_T *rettv));
551 #endif
552 static void f_fnameescape __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_getpid __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
590 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
591 static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv));
592 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
593 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
594 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
595 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
596 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
603 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
604 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
605 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
606 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
607 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
608 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
609 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
610 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
611 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
618 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
619 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
620 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
621 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
622 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
623 #ifdef FEAT_FLOAT
624 static void f_log10 __ARGS((typval_T *argvars, typval_T *rettv));
625 #endif
626 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
627 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
628 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
629 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
630 static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv));
631 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
632 static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv));
633 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
634 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
635 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
636 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
637 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
638 #ifdef vim_mkdir
639 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
640 #endif
641 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
642 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
643 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
644 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
645 #ifdef FEAT_FLOAT
646 static void f_pow __ARGS((typval_T *argvars, typval_T *rettv));
647 #endif
648 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
649 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
650 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
651 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
652 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
653 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
654 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
655 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
656 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
657 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
665 #ifdef FEAT_FLOAT
666 static void f_round __ARGS((typval_T *argvars, typval_T *rettv));
667 #endif
668 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
669 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
670 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
671 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
672 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
673 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
674 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
675 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
676 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
677 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
678 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
679 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
680 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
681 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
682 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
683 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
684 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
685 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
686 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
687 #ifdef FEAT_FLOAT
688 static void f_sin __ARGS((typval_T *argvars, typval_T *rettv));
689 #endif
690 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
691 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
692 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
693 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
694 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
695 #ifdef FEAT_FLOAT
696 static void f_sqrt __ARGS((typval_T *argvars, typval_T *rettv));
697 static void f_str2float __ARGS((typval_T *argvars, typval_T *rettv));
698 #endif
699 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
700 #ifdef HAVE_STRFTIME
701 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
702 #endif
703 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
704 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
705 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
706 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
707 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
708 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
709 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
710 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
711 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
712 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
713 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
714 static void f_synstack __ARGS((typval_T *argvars, typval_T *rettv));
715 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
716 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
717 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
718 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
719 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
720 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
721 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
722 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
723 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
724 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
725 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
726 #ifdef FEAT_FLOAT
727 static void f_trunc __ARGS((typval_T *argvars, typval_T *rettv));
728 #endif
729 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
730 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
731 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
732 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
733 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
734 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
735 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
736 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
737 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
738 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
739 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
740 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
741 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
742 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
744 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
745 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
746 static int get_env_len __ARGS((char_u **arg));
747 static int get_id_len __ARGS((char_u **arg));
748 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
749 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
750 #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */
751 #define FNE_CHECK_START 2 /* find_name_end(): check name starts with
752 valid character */
753 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
754 static int eval_isnamec __ARGS((int c));
755 static int eval_isnamec1 __ARGS((int c));
756 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
757 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
758 static typval_T *alloc_tv __ARGS((void));
759 static typval_T *alloc_string_tv __ARGS((char_u *string));
760 static void init_tv __ARGS((typval_T *varp));
761 static long get_tv_number __ARGS((typval_T *varp));
762 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
763 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
764 static char_u *get_tv_string __ARGS((typval_T *varp));
765 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
766 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
767 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
768 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
769 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
770 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
771 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
772 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
773 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
774 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
775 static int var_check_ro __ARGS((int flags, char_u *name));
776 static int var_check_fixed __ARGS((int flags, char_u *name));
777 static int tv_check_lock __ARGS((int lock, char_u *name));
778 static void copy_tv __ARGS((typval_T *from, typval_T *to));
779 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
780 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
781 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
782 static int eval_fname_script __ARGS((char_u *p));
783 static int eval_fname_sid __ARGS((char_u *p));
784 static void list_func_head __ARGS((ufunc_T *fp, int indent));
785 static ufunc_T *find_func __ARGS((char_u *name));
786 static int function_exists __ARGS((char_u *name));
787 static int builtin_function __ARGS((char_u *name));
788 #ifdef FEAT_PROFILE
789 static void func_do_profile __ARGS((ufunc_T *fp));
790 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
791 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
792 static int
793 # ifdef __BORLANDC__
794 _RTLENTRYF
795 # endif
796 prof_total_cmp __ARGS((const void *s1, const void *s2));
797 static int
798 # ifdef __BORLANDC__
799 _RTLENTRYF
800 # endif
801 prof_self_cmp __ARGS((const void *s1, const void *s2));
802 #endif
803 static int script_autoload __ARGS((char_u *name, int reload));
804 static char_u *autoload_name __ARGS((char_u *name));
805 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
806 static void func_free __ARGS((ufunc_T *fp));
807 static void func_unref __ARGS((char_u *name));
808 static void func_ref __ARGS((char_u *name));
809 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));
810 static int can_free_funccal __ARGS((funccall_T *fc, int copyID)) ;
811 static void free_funccal __ARGS((funccall_T *fc, int free_val));
812 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
813 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
814 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
815 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
816 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
817 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
819 /* Character used as separated in autoload function/variable names. */
820 #define AUTOLOAD_CHAR '#'
823 * Initialize the global and v: variables.
825 void
826 eval_init()
828 int i;
829 struct vimvar *p;
831 init_var_dict(&globvardict, &globvars_var);
832 init_var_dict(&vimvardict, &vimvars_var);
833 hash_init(&compat_hashtab);
834 hash_init(&func_hashtab);
836 for (i = 0; i < VV_LEN; ++i)
838 p = &vimvars[i];
839 STRCPY(p->vv_di.di_key, p->vv_name);
840 if (p->vv_flags & VV_RO)
841 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
842 else if (p->vv_flags & VV_RO_SBX)
843 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
844 else
845 p->vv_di.di_flags = DI_FLAGS_FIX;
847 /* add to v: scope dict, unless the value is not always available */
848 if (p->vv_type != VAR_UNKNOWN)
849 hash_add(&vimvarht, p->vv_di.di_key);
850 if (p->vv_flags & VV_COMPAT)
851 /* add to compat scope dict */
852 hash_add(&compat_hashtab, p->vv_di.di_key);
854 set_vim_var_nr(VV_SEARCHFORWARD, 1L);
857 #if defined(EXITFREE) || defined(PROTO)
858 void
859 eval_clear()
861 int i;
862 struct vimvar *p;
864 for (i = 0; i < VV_LEN; ++i)
866 p = &vimvars[i];
867 if (p->vv_di.di_tv.v_type == VAR_STRING)
869 vim_free(p->vv_str);
870 p->vv_str = NULL;
872 else if (p->vv_di.di_tv.v_type == VAR_LIST)
874 list_unref(p->vv_list);
875 p->vv_list = NULL;
878 hash_clear(&vimvarht);
879 hash_init(&vimvarht); /* garbage_collect() will access it */
880 hash_clear(&compat_hashtab);
882 /* script-local variables */
883 for (i = 1; i <= ga_scripts.ga_len; ++i)
884 vars_clear(&SCRIPT_VARS(i));
885 ga_clear(&ga_scripts);
886 free_scriptnames();
888 /* global variables */
889 vars_clear(&globvarht);
891 /* autoloaded script names */
892 ga_clear_strings(&ga_loaded);
894 /* unreferenced lists and dicts */
895 (void)garbage_collect();
897 /* functions */
898 free_all_functions();
899 hash_clear(&func_hashtab);
901 #endif
904 * Return the name of the executed function.
906 char_u *
907 func_name(cookie)
908 void *cookie;
910 return ((funccall_T *)cookie)->func->uf_name;
914 * Return the address holding the next breakpoint line for a funccall cookie.
916 linenr_T *
917 func_breakpoint(cookie)
918 void *cookie;
920 return &((funccall_T *)cookie)->breakpoint;
924 * Return the address holding the debug tick for a funccall cookie.
926 int *
927 func_dbg_tick(cookie)
928 void *cookie;
930 return &((funccall_T *)cookie)->dbg_tick;
934 * Return the nesting level for a funccall cookie.
937 func_level(cookie)
938 void *cookie;
940 return ((funccall_T *)cookie)->level;
943 /* pointer to funccal for currently active function */
944 funccall_T *current_funccal = NULL;
946 /* pointer to list of previously used funccal, still around because some
947 * item in it is still being used. */
948 funccall_T *previous_funccal = NULL;
951 * Return TRUE when a function was ended by a ":return" command.
954 current_func_returned()
956 return current_funccal->returned;
961 * Set an internal variable to a string value. Creates the variable if it does
962 * not already exist.
964 void
965 set_internal_string_var(name, value)
966 char_u *name;
967 char_u *value;
969 char_u *val;
970 typval_T *tvp;
972 val = vim_strsave(value);
973 if (val != NULL)
975 tvp = alloc_string_tv(val);
976 if (tvp != NULL)
978 set_var(name, tvp, FALSE);
979 free_tv(tvp);
984 static lval_T *redir_lval = NULL;
985 static garray_T redir_ga; /* only valid when redir_lval is not NULL */
986 static char_u *redir_endp = NULL;
987 static char_u *redir_varname = NULL;
990 * Start recording command output to a variable
991 * Returns OK if successfully completed the setup. FAIL otherwise.
994 var_redir_start(name, append)
995 char_u *name;
996 int append; /* append to an existing variable */
998 int save_emsg;
999 int err;
1000 typval_T tv;
1002 /* Make sure a valid variable name is specified */
1003 if (!eval_isnamec1(*name))
1005 EMSG(_(e_invarg));
1006 return FAIL;
1009 redir_varname = vim_strsave(name);
1010 if (redir_varname == NULL)
1011 return FAIL;
1013 redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
1014 if (redir_lval == NULL)
1016 var_redir_stop();
1017 return FAIL;
1020 /* The output is stored in growarray "redir_ga" until redirection ends. */
1021 ga_init2(&redir_ga, (int)sizeof(char), 500);
1023 /* Parse the variable name (can be a dict or list entry). */
1024 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
1025 FNE_CHECK_START);
1026 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
1028 if (redir_endp != NULL && *redir_endp != NUL)
1029 /* Trailing characters are present after the variable name */
1030 EMSG(_(e_trailing));
1031 else
1032 EMSG(_(e_invarg));
1033 var_redir_stop();
1034 return FAIL;
1037 /* check if we can write to the variable: set it to or append an empty
1038 * string */
1039 save_emsg = did_emsg;
1040 did_emsg = FALSE;
1041 tv.v_type = VAR_STRING;
1042 tv.vval.v_string = (char_u *)"";
1043 if (append)
1044 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
1045 else
1046 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
1047 err = did_emsg;
1048 did_emsg |= save_emsg;
1049 if (err)
1051 var_redir_stop();
1052 return FAIL;
1054 if (redir_lval->ll_newkey != NULL)
1056 /* Dictionary item was created, don't do it again. */
1057 vim_free(redir_lval->ll_newkey);
1058 redir_lval->ll_newkey = NULL;
1061 return OK;
1065 * Append "value[value_len]" to the variable set by var_redir_start().
1066 * The actual appending is postponed until redirection ends, because the value
1067 * appended may in fact be the string we write to, changing it may cause freed
1068 * memory to be used:
1069 * :redir => foo
1070 * :let foo
1071 * :redir END
1073 void
1074 var_redir_str(value, value_len)
1075 char_u *value;
1076 int value_len;
1078 int len;
1080 if (redir_lval == NULL)
1081 return;
1083 if (value_len == -1)
1084 len = (int)STRLEN(value); /* Append the entire string */
1085 else
1086 len = value_len; /* Append only "value_len" characters */
1088 if (ga_grow(&redir_ga, len) == OK)
1090 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1091 redir_ga.ga_len += len;
1093 else
1094 var_redir_stop();
1098 * Stop redirecting command output to a variable.
1100 void
1101 var_redir_stop()
1103 typval_T tv;
1105 if (redir_lval != NULL)
1107 /* Append the trailing NUL. */
1108 ga_append(&redir_ga, NUL);
1110 /* Assign the text to the variable. */
1111 tv.v_type = VAR_STRING;
1112 tv.vval.v_string = redir_ga.ga_data;
1113 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1114 vim_free(tv.vval.v_string);
1116 clear_lval(redir_lval);
1117 vim_free(redir_lval);
1118 redir_lval = NULL;
1120 vim_free(redir_varname);
1121 redir_varname = NULL;
1124 # if defined(FEAT_MBYTE) || defined(PROTO)
1126 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1127 char_u *enc_from;
1128 char_u *enc_to;
1129 char_u *fname_from;
1130 char_u *fname_to;
1132 int err = FALSE;
1134 set_vim_var_string(VV_CC_FROM, enc_from, -1);
1135 set_vim_var_string(VV_CC_TO, enc_to, -1);
1136 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1137 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1138 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1139 err = TRUE;
1140 set_vim_var_string(VV_CC_FROM, NULL, -1);
1141 set_vim_var_string(VV_CC_TO, NULL, -1);
1142 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1143 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1145 if (err)
1146 return FAIL;
1147 return OK;
1149 # endif
1151 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1153 eval_printexpr(fname, args)
1154 char_u *fname;
1155 char_u *args;
1157 int err = FALSE;
1159 set_vim_var_string(VV_FNAME_IN, fname, -1);
1160 set_vim_var_string(VV_CMDARG, args, -1);
1161 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1162 err = TRUE;
1163 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1164 set_vim_var_string(VV_CMDARG, NULL, -1);
1166 if (err)
1168 mch_remove(fname);
1169 return FAIL;
1171 return OK;
1173 # endif
1175 # if defined(FEAT_DIFF) || defined(PROTO)
1176 void
1177 eval_diff(origfile, newfile, outfile)
1178 char_u *origfile;
1179 char_u *newfile;
1180 char_u *outfile;
1182 int err = FALSE;
1184 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1185 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1186 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1187 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1188 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1189 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1190 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1193 void
1194 eval_patch(origfile, difffile, outfile)
1195 char_u *origfile;
1196 char_u *difffile;
1197 char_u *outfile;
1199 int err;
1201 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1202 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1203 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1204 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1205 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1206 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1207 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1209 # endif
1212 * Top level evaluation function, returning a boolean.
1213 * Sets "error" to TRUE if there was an error.
1214 * Return TRUE or FALSE.
1217 eval_to_bool(arg, error, nextcmd, skip)
1218 char_u *arg;
1219 int *error;
1220 char_u **nextcmd;
1221 int skip; /* only parse, don't execute */
1223 typval_T tv;
1224 int retval = FALSE;
1226 if (skip)
1227 ++emsg_skip;
1228 if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1229 *error = TRUE;
1230 else
1232 *error = FALSE;
1233 if (!skip)
1235 retval = (get_tv_number_chk(&tv, error) != 0);
1236 clear_tv(&tv);
1239 if (skip)
1240 --emsg_skip;
1242 return retval;
1246 * Top level evaluation function, returning a string. If "skip" is TRUE,
1247 * only parsing to "nextcmd" is done, without reporting errors. Return
1248 * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1250 char_u *
1251 eval_to_string_skip(arg, nextcmd, skip)
1252 char_u *arg;
1253 char_u **nextcmd;
1254 int skip; /* only parse, don't execute */
1256 typval_T tv;
1257 char_u *retval;
1259 if (skip)
1260 ++emsg_skip;
1261 if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1262 retval = NULL;
1263 else
1265 retval = vim_strsave(get_tv_string(&tv));
1266 clear_tv(&tv);
1268 if (skip)
1269 --emsg_skip;
1271 return retval;
1275 * Skip over an expression at "*pp".
1276 * Return FAIL for an error, OK otherwise.
1279 skip_expr(pp)
1280 char_u **pp;
1282 typval_T rettv;
1284 *pp = skipwhite(*pp);
1285 return eval1(pp, &rettv, FALSE);
1289 * Top level evaluation function, returning a string.
1290 * When "convert" is TRUE convert a List into a sequence of lines and convert
1291 * a Float to a String.
1292 * Return pointer to allocated memory, or NULL for failure.
1294 char_u *
1295 eval_to_string(arg, nextcmd, convert)
1296 char_u *arg;
1297 char_u **nextcmd;
1298 int convert;
1300 typval_T tv;
1301 char_u *retval;
1302 garray_T ga;
1303 char_u numbuf[NUMBUFLEN];
1305 if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1306 retval = NULL;
1307 else
1309 if (convert && tv.v_type == VAR_LIST)
1311 ga_init2(&ga, (int)sizeof(char), 80);
1312 if (tv.vval.v_list != NULL)
1313 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1314 ga_append(&ga, NUL);
1315 retval = (char_u *)ga.ga_data;
1317 #ifdef FEAT_FLOAT
1318 else if (convert && tv.v_type == VAR_FLOAT)
1320 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv.vval.v_float);
1321 retval = vim_strsave(numbuf);
1323 #endif
1324 else
1325 retval = vim_strsave(get_tv_string(&tv));
1326 clear_tv(&tv);
1329 return retval;
1333 * Call eval_to_string() without using current local variables and using
1334 * textlock. When "use_sandbox" is TRUE use the sandbox.
1336 char_u *
1337 eval_to_string_safe(arg, nextcmd, use_sandbox)
1338 char_u *arg;
1339 char_u **nextcmd;
1340 int use_sandbox;
1342 char_u *retval;
1343 void *save_funccalp;
1345 save_funccalp = save_funccal();
1346 if (use_sandbox)
1347 ++sandbox;
1348 ++textlock;
1349 retval = eval_to_string(arg, nextcmd, FALSE);
1350 if (use_sandbox)
1351 --sandbox;
1352 --textlock;
1353 restore_funccal(save_funccalp);
1354 return retval;
1358 * Top level evaluation function, returning a number.
1359 * Evaluates "expr" silently.
1360 * Returns -1 for an error.
1363 eval_to_number(expr)
1364 char_u *expr;
1366 typval_T rettv;
1367 int retval;
1368 char_u *p = skipwhite(expr);
1370 ++emsg_off;
1372 if (eval1(&p, &rettv, TRUE) == FAIL)
1373 retval = -1;
1374 else
1376 retval = get_tv_number_chk(&rettv, NULL);
1377 clear_tv(&rettv);
1379 --emsg_off;
1381 return retval;
1385 * Prepare v: variable "idx" to be used.
1386 * Save the current typeval in "save_tv".
1387 * When not used yet add the variable to the v: hashtable.
1389 static void
1390 prepare_vimvar(idx, save_tv)
1391 int idx;
1392 typval_T *save_tv;
1394 *save_tv = vimvars[idx].vv_tv;
1395 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1396 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1400 * Restore v: variable "idx" to typeval "save_tv".
1401 * When no longer defined, remove the variable from the v: hashtable.
1403 static void
1404 restore_vimvar(idx, save_tv)
1405 int idx;
1406 typval_T *save_tv;
1408 hashitem_T *hi;
1410 vimvars[idx].vv_tv = *save_tv;
1411 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1413 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1414 if (HASHITEM_EMPTY(hi))
1415 EMSG2(_(e_intern2), "restore_vimvar()");
1416 else
1417 hash_remove(&vimvarht, hi);
1421 #if defined(FEAT_SPELL) || defined(PROTO)
1423 * Evaluate an expression to a list with suggestions.
1424 * For the "expr:" part of 'spellsuggest'.
1425 * Returns NULL when there is an error.
1427 list_T *
1428 eval_spell_expr(badword, expr)
1429 char_u *badword;
1430 char_u *expr;
1432 typval_T save_val;
1433 typval_T rettv;
1434 list_T *list = NULL;
1435 char_u *p = skipwhite(expr);
1437 /* Set "v:val" to the bad word. */
1438 prepare_vimvar(VV_VAL, &save_val);
1439 vimvars[VV_VAL].vv_type = VAR_STRING;
1440 vimvars[VV_VAL].vv_str = badword;
1441 if (p_verbose == 0)
1442 ++emsg_off;
1444 if (eval1(&p, &rettv, TRUE) == OK)
1446 if (rettv.v_type != VAR_LIST)
1447 clear_tv(&rettv);
1448 else
1449 list = rettv.vval.v_list;
1452 if (p_verbose == 0)
1453 --emsg_off;
1454 restore_vimvar(VV_VAL, &save_val);
1456 return list;
1460 * "list" is supposed to contain two items: a word and a number. Return the
1461 * word in "pp" and the number as the return value.
1462 * Return -1 if anything isn't right.
1463 * Used to get the good word and score from the eval_spell_expr() result.
1466 get_spellword(list, pp)
1467 list_T *list;
1468 char_u **pp;
1470 listitem_T *li;
1472 li = list->lv_first;
1473 if (li == NULL)
1474 return -1;
1475 *pp = get_tv_string(&li->li_tv);
1477 li = li->li_next;
1478 if (li == NULL)
1479 return -1;
1480 return get_tv_number(&li->li_tv);
1482 #endif
1485 * Top level evaluation function.
1486 * Returns an allocated typval_T with the result.
1487 * Returns NULL when there is an error.
1489 typval_T *
1490 eval_expr(arg, nextcmd)
1491 char_u *arg;
1492 char_u **nextcmd;
1494 typval_T *tv;
1496 tv = (typval_T *)alloc(sizeof(typval_T));
1497 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1499 vim_free(tv);
1500 tv = NULL;
1503 return tv;
1507 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1508 || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1510 * Call some vimL function and return the result in "*rettv".
1511 * Uses argv[argc] for the function arguments. Only Number and String
1512 * arguments are currently supported.
1513 * Returns OK or FAIL.
1515 static int
1516 call_vim_function(func, argc, argv, safe, rettv)
1517 char_u *func;
1518 int argc;
1519 char_u **argv;
1520 int safe; /* use the sandbox */
1521 typval_T *rettv;
1523 typval_T *argvars;
1524 long n;
1525 int len;
1526 int i;
1527 int doesrange;
1528 void *save_funccalp = NULL;
1529 int ret;
1531 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1532 if (argvars == NULL)
1533 return FAIL;
1535 for (i = 0; i < argc; i++)
1537 /* Pass a NULL or empty argument as an empty string */
1538 if (argv[i] == NULL || *argv[i] == NUL)
1540 argvars[i].v_type = VAR_STRING;
1541 argvars[i].vval.v_string = (char_u *)"";
1542 continue;
1545 /* Recognize a number argument, the others must be strings. */
1546 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1547 if (len != 0 && len == (int)STRLEN(argv[i]))
1549 argvars[i].v_type = VAR_NUMBER;
1550 argvars[i].vval.v_number = n;
1552 else
1554 argvars[i].v_type = VAR_STRING;
1555 argvars[i].vval.v_string = argv[i];
1559 if (safe)
1561 save_funccalp = save_funccal();
1562 ++sandbox;
1565 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1566 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1567 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1568 &doesrange, TRUE, NULL);
1569 if (safe)
1571 --sandbox;
1572 restore_funccal(save_funccalp);
1574 vim_free(argvars);
1576 if (ret == FAIL)
1577 clear_tv(rettv);
1579 return ret;
1582 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1584 * Call vimL function "func" and return the result as a string.
1585 * Returns NULL when calling the function fails.
1586 * Uses argv[argc] for the function arguments.
1588 void *
1589 call_func_retstr(func, argc, argv, safe)
1590 char_u *func;
1591 int argc;
1592 char_u **argv;
1593 int safe; /* use the sandbox */
1595 typval_T rettv;
1596 char_u *retval;
1598 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1599 return NULL;
1601 retval = vim_strsave(get_tv_string(&rettv));
1602 clear_tv(&rettv);
1603 return retval;
1605 # endif
1607 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1609 * Call vimL function "func" and return the result as a number.
1610 * Returns -1 when calling the function fails.
1611 * Uses argv[argc] for the function arguments.
1613 long
1614 call_func_retnr(func, argc, argv, safe)
1615 char_u *func;
1616 int argc;
1617 char_u **argv;
1618 int safe; /* use the sandbox */
1620 typval_T rettv;
1621 long retval;
1623 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1624 return -1;
1626 retval = get_tv_number_chk(&rettv, NULL);
1627 clear_tv(&rettv);
1628 return retval;
1630 # endif
1633 * Call vimL function "func" and return the result as a List.
1634 * Uses argv[argc] for the function arguments.
1635 * Returns NULL when there is something wrong.
1637 void *
1638 call_func_retlist(func, argc, argv, safe)
1639 char_u *func;
1640 int argc;
1641 char_u **argv;
1642 int safe; /* use the sandbox */
1644 typval_T rettv;
1646 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1647 return NULL;
1649 if (rettv.v_type != VAR_LIST)
1651 clear_tv(&rettv);
1652 return NULL;
1655 return rettv.vval.v_list;
1657 #endif
1661 * Save the current function call pointer, and set it to NULL.
1662 * Used when executing autocommands and for ":source".
1664 void *
1665 save_funccal()
1667 funccall_T *fc = current_funccal;
1669 current_funccal = NULL;
1670 return (void *)fc;
1673 void
1674 restore_funccal(vfc)
1675 void *vfc;
1677 funccall_T *fc = (funccall_T *)vfc;
1679 current_funccal = fc;
1682 #if defined(FEAT_PROFILE) || defined(PROTO)
1684 * Prepare profiling for entering a child or something else that is not
1685 * counted for the script/function itself.
1686 * Should always be called in pair with prof_child_exit().
1688 void
1689 prof_child_enter(tm)
1690 proftime_T *tm; /* place to store waittime */
1692 funccall_T *fc = current_funccal;
1694 if (fc != NULL && fc->func->uf_profiling)
1695 profile_start(&fc->prof_child);
1696 script_prof_save(tm);
1700 * Take care of time spent in a child.
1701 * Should always be called after prof_child_enter().
1703 void
1704 prof_child_exit(tm)
1705 proftime_T *tm; /* where waittime was stored */
1707 funccall_T *fc = current_funccal;
1709 if (fc != NULL && fc->func->uf_profiling)
1711 profile_end(&fc->prof_child);
1712 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1713 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1714 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1716 script_prof_restore(tm);
1718 #endif
1721 #ifdef FEAT_FOLDING
1723 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1724 * it in "*cp". Doesn't give error messages.
1727 eval_foldexpr(arg, cp)
1728 char_u *arg;
1729 int *cp;
1731 typval_T tv;
1732 int retval;
1733 char_u *s;
1734 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1735 OPT_LOCAL);
1737 ++emsg_off;
1738 if (use_sandbox)
1739 ++sandbox;
1740 ++textlock;
1741 *cp = NUL;
1742 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1743 retval = 0;
1744 else
1746 /* If the result is a number, just return the number. */
1747 if (tv.v_type == VAR_NUMBER)
1748 retval = tv.vval.v_number;
1749 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1750 retval = 0;
1751 else
1753 /* If the result is a string, check if there is a non-digit before
1754 * the number. */
1755 s = tv.vval.v_string;
1756 if (!VIM_ISDIGIT(*s) && *s != '-')
1757 *cp = *s++;
1758 retval = atol((char *)s);
1760 clear_tv(&tv);
1762 --emsg_off;
1763 if (use_sandbox)
1764 --sandbox;
1765 --textlock;
1767 return retval;
1769 #endif
1772 * ":let" list all variable values
1773 * ":let var1 var2" list variable values
1774 * ":let var = expr" assignment command.
1775 * ":let var += expr" assignment command.
1776 * ":let var -= expr" assignment command.
1777 * ":let var .= expr" assignment command.
1778 * ":let [var1, var2] = expr" unpack list.
1780 void
1781 ex_let(eap)
1782 exarg_T *eap;
1784 char_u *arg = eap->arg;
1785 char_u *expr = NULL;
1786 typval_T rettv;
1787 int i;
1788 int var_count = 0;
1789 int semicolon = 0;
1790 char_u op[2];
1791 char_u *argend;
1792 int first = TRUE;
1794 argend = skip_var_list(arg, &var_count, &semicolon);
1795 if (argend == NULL)
1796 return;
1797 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1798 --argend;
1799 expr = vim_strchr(argend, '=');
1800 if (expr == NULL)
1803 * ":let" without "=": list variables
1805 if (*arg == '[')
1806 EMSG(_(e_invarg));
1807 else if (!ends_excmd(*arg))
1808 /* ":let var1 var2" */
1809 arg = list_arg_vars(eap, arg, &first);
1810 else if (!eap->skip)
1812 /* ":let" */
1813 list_glob_vars(&first);
1814 list_buf_vars(&first);
1815 list_win_vars(&first);
1816 #ifdef FEAT_WINDOWS
1817 list_tab_vars(&first);
1818 #endif
1819 list_script_vars(&first);
1820 list_func_vars(&first);
1821 list_vim_vars(&first);
1823 eap->nextcmd = check_nextcmd(arg);
1825 else
1827 op[0] = '=';
1828 op[1] = NUL;
1829 if (expr > argend)
1831 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1832 op[0] = expr[-1]; /* +=, -= or .= */
1834 expr = skipwhite(expr + 1);
1836 if (eap->skip)
1837 ++emsg_skip;
1838 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1839 if (eap->skip)
1841 if (i != FAIL)
1842 clear_tv(&rettv);
1843 --emsg_skip;
1845 else if (i != FAIL)
1847 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1848 op);
1849 clear_tv(&rettv);
1855 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1856 * Handles both "var" with any type and "[var, var; var]" with a list type.
1857 * When "nextchars" is not NULL it points to a string with characters that
1858 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1859 * or concatenate.
1860 * Returns OK or FAIL;
1862 static int
1863 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1864 char_u *arg_start;
1865 typval_T *tv;
1866 int copy; /* copy values from "tv", don't move */
1867 int semicolon; /* from skip_var_list() */
1868 int var_count; /* from skip_var_list() */
1869 char_u *nextchars;
1871 char_u *arg = arg_start;
1872 list_T *l;
1873 int i;
1874 listitem_T *item;
1875 typval_T ltv;
1877 if (*arg != '[')
1880 * ":let var = expr" or ":for var in list"
1882 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1883 return FAIL;
1884 return OK;
1888 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1890 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1892 EMSG(_(e_listreq));
1893 return FAIL;
1896 i = list_len(l);
1897 if (semicolon == 0 && var_count < i)
1899 EMSG(_("E687: Less targets than List items"));
1900 return FAIL;
1902 if (var_count - semicolon > i)
1904 EMSG(_("E688: More targets than List items"));
1905 return FAIL;
1908 item = l->lv_first;
1909 while (*arg != ']')
1911 arg = skipwhite(arg + 1);
1912 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1913 item = item->li_next;
1914 if (arg == NULL)
1915 return FAIL;
1917 arg = skipwhite(arg);
1918 if (*arg == ';')
1920 /* Put the rest of the list (may be empty) in the var after ';'.
1921 * Create a new list for this. */
1922 l = list_alloc();
1923 if (l == NULL)
1924 return FAIL;
1925 while (item != NULL)
1927 list_append_tv(l, &item->li_tv);
1928 item = item->li_next;
1931 ltv.v_type = VAR_LIST;
1932 ltv.v_lock = 0;
1933 ltv.vval.v_list = l;
1934 l->lv_refcount = 1;
1936 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1937 (char_u *)"]", nextchars);
1938 clear_tv(&ltv);
1939 if (arg == NULL)
1940 return FAIL;
1941 break;
1943 else if (*arg != ',' && *arg != ']')
1945 EMSG2(_(e_intern2), "ex_let_vars()");
1946 return FAIL;
1950 return OK;
1954 * Skip over assignable variable "var" or list of variables "[var, var]".
1955 * Used for ":let varvar = expr" and ":for varvar in expr".
1956 * For "[var, var]" increment "*var_count" for each variable.
1957 * for "[var, var; var]" set "semicolon".
1958 * Return NULL for an error.
1960 static char_u *
1961 skip_var_list(arg, var_count, semicolon)
1962 char_u *arg;
1963 int *var_count;
1964 int *semicolon;
1966 char_u *p, *s;
1968 if (*arg == '[')
1970 /* "[var, var]": find the matching ']'. */
1971 p = arg;
1972 for (;;)
1974 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
1975 s = skip_var_one(p);
1976 if (s == p)
1978 EMSG2(_(e_invarg2), p);
1979 return NULL;
1981 ++*var_count;
1983 p = skipwhite(s);
1984 if (*p == ']')
1985 break;
1986 else if (*p == ';')
1988 if (*semicolon == 1)
1990 EMSG(_("Double ; in list of variables"));
1991 return NULL;
1993 *semicolon = 1;
1995 else if (*p != ',')
1997 EMSG2(_(e_invarg2), p);
1998 return NULL;
2001 return p + 1;
2003 else
2004 return skip_var_one(arg);
2008 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
2009 * l[idx].
2011 static char_u *
2012 skip_var_one(arg)
2013 char_u *arg;
2015 if (*arg == '@' && arg[1] != NUL)
2016 return arg + 2;
2017 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
2018 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2022 * List variables for hashtab "ht" with prefix "prefix".
2023 * If "empty" is TRUE also list NULL strings as empty strings.
2025 static void
2026 list_hashtable_vars(ht, prefix, empty, first)
2027 hashtab_T *ht;
2028 char_u *prefix;
2029 int empty;
2030 int *first;
2032 hashitem_T *hi;
2033 dictitem_T *di;
2034 int todo;
2036 todo = (int)ht->ht_used;
2037 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
2039 if (!HASHITEM_EMPTY(hi))
2041 --todo;
2042 di = HI2DI(hi);
2043 if (empty || di->di_tv.v_type != VAR_STRING
2044 || di->di_tv.vval.v_string != NULL)
2045 list_one_var(di, prefix, first);
2051 * List global variables.
2053 static void
2054 list_glob_vars(first)
2055 int *first;
2057 list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
2061 * List buffer variables.
2063 static void
2064 list_buf_vars(first)
2065 int *first;
2067 char_u numbuf[NUMBUFLEN];
2069 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:",
2070 TRUE, first);
2072 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
2073 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
2074 numbuf, first);
2078 * List window variables.
2080 static void
2081 list_win_vars(first)
2082 int *first;
2084 list_hashtable_vars(&curwin->w_vars.dv_hashtab,
2085 (char_u *)"w:", TRUE, first);
2088 #ifdef FEAT_WINDOWS
2090 * List tab page variables.
2092 static void
2093 list_tab_vars(first)
2094 int *first;
2096 list_hashtable_vars(&curtab->tp_vars.dv_hashtab,
2097 (char_u *)"t:", TRUE, first);
2099 #endif
2102 * List Vim variables.
2104 static void
2105 list_vim_vars(first)
2106 int *first;
2108 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2112 * List script-local variables, if there is a script.
2114 static void
2115 list_script_vars(first)
2116 int *first;
2118 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2119 list_hashtable_vars(&SCRIPT_VARS(current_SID),
2120 (char_u *)"s:", FALSE, first);
2124 * List function variables, if there is a function.
2126 static void
2127 list_func_vars(first)
2128 int *first;
2130 if (current_funccal != NULL)
2131 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2132 (char_u *)"l:", FALSE, first);
2136 * List variables in "arg".
2138 static char_u *
2139 list_arg_vars(eap, arg, first)
2140 exarg_T *eap;
2141 char_u *arg;
2142 int *first;
2144 int error = FALSE;
2145 int len;
2146 char_u *name;
2147 char_u *name_start;
2148 char_u *arg_subsc;
2149 char_u *tofree;
2150 typval_T tv;
2152 while (!ends_excmd(*arg) && !got_int)
2154 if (error || eap->skip)
2156 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2157 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2159 emsg_severe = TRUE;
2160 EMSG(_(e_trailing));
2161 break;
2164 else
2166 /* get_name_len() takes care of expanding curly braces */
2167 name_start = name = arg;
2168 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2169 if (len <= 0)
2171 /* This is mainly to keep test 49 working: when expanding
2172 * curly braces fails overrule the exception error message. */
2173 if (len < 0 && !aborting())
2175 emsg_severe = TRUE;
2176 EMSG2(_(e_invarg2), arg);
2177 break;
2179 error = TRUE;
2181 else
2183 if (tofree != NULL)
2184 name = tofree;
2185 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2186 error = TRUE;
2187 else
2189 /* handle d.key, l[idx], f(expr) */
2190 arg_subsc = arg;
2191 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2192 error = TRUE;
2193 else
2195 if (arg == arg_subsc && len == 2 && name[1] == ':')
2197 switch (*name)
2199 case 'g': list_glob_vars(first); break;
2200 case 'b': list_buf_vars(first); break;
2201 case 'w': list_win_vars(first); break;
2202 #ifdef FEAT_WINDOWS
2203 case 't': list_tab_vars(first); break;
2204 #endif
2205 case 'v': list_vim_vars(first); break;
2206 case 's': list_script_vars(first); break;
2207 case 'l': list_func_vars(first); break;
2208 default:
2209 EMSG2(_("E738: Can't list variables for %s"), name);
2212 else
2214 char_u numbuf[NUMBUFLEN];
2215 char_u *tf;
2216 int c;
2217 char_u *s;
2219 s = echo_string(&tv, &tf, numbuf, 0);
2220 c = *arg;
2221 *arg = NUL;
2222 list_one_var_a((char_u *)"",
2223 arg == arg_subsc ? name : name_start,
2224 tv.v_type,
2225 s == NULL ? (char_u *)"" : s,
2226 first);
2227 *arg = c;
2228 vim_free(tf);
2230 clear_tv(&tv);
2235 vim_free(tofree);
2238 arg = skipwhite(arg);
2241 return arg;
2245 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2246 * Returns a pointer to the char just after the var name.
2247 * Returns NULL if there is an error.
2249 static char_u *
2250 ex_let_one(arg, tv, copy, endchars, op)
2251 char_u *arg; /* points to variable name */
2252 typval_T *tv; /* value to assign to variable */
2253 int copy; /* copy value from "tv" */
2254 char_u *endchars; /* valid chars after variable name or NULL */
2255 char_u *op; /* "+", "-", "." or NULL*/
2257 int c1;
2258 char_u *name;
2259 char_u *p;
2260 char_u *arg_end = NULL;
2261 int len;
2262 int opt_flags;
2263 char_u *tofree = NULL;
2266 * ":let $VAR = expr": Set environment variable.
2268 if (*arg == '$')
2270 /* Find the end of the name. */
2271 ++arg;
2272 name = arg;
2273 len = get_env_len(&arg);
2274 if (len == 0)
2275 EMSG2(_(e_invarg2), name - 1);
2276 else
2278 if (op != NULL && (*op == '+' || *op == '-'))
2279 EMSG2(_(e_letwrong), op);
2280 else if (endchars != NULL
2281 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2282 EMSG(_(e_letunexp));
2283 else
2285 c1 = name[len];
2286 name[len] = NUL;
2287 p = get_tv_string_chk(tv);
2288 if (p != NULL && op != NULL && *op == '.')
2290 int mustfree = FALSE;
2291 char_u *s = vim_getenv(name, &mustfree);
2293 if (s != NULL)
2295 p = tofree = concat_str(s, p);
2296 if (mustfree)
2297 vim_free(s);
2300 if (p != NULL)
2302 vim_setenv(name, p);
2303 if (STRICMP(name, "HOME") == 0)
2304 init_homedir();
2305 else if (didset_vim && STRICMP(name, "VIM") == 0)
2306 didset_vim = FALSE;
2307 else if (didset_vimruntime
2308 && STRICMP(name, "VIMRUNTIME") == 0)
2309 didset_vimruntime = FALSE;
2310 arg_end = arg;
2312 name[len] = c1;
2313 vim_free(tofree);
2319 * ":let &option = expr": Set option value.
2320 * ":let &l:option = expr": Set local option value.
2321 * ":let &g:option = expr": Set global option value.
2323 else if (*arg == '&')
2325 /* Find the end of the name. */
2326 p = find_option_end(&arg, &opt_flags);
2327 if (p == NULL || (endchars != NULL
2328 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2329 EMSG(_(e_letunexp));
2330 else
2332 long n;
2333 int opt_type;
2334 long numval;
2335 char_u *stringval = NULL;
2336 char_u *s;
2338 c1 = *p;
2339 *p = NUL;
2341 n = get_tv_number(tv);
2342 s = get_tv_string_chk(tv); /* != NULL if number or string */
2343 if (s != NULL && op != NULL && *op != '=')
2345 opt_type = get_option_value(arg, &numval,
2346 &stringval, opt_flags);
2347 if ((opt_type == 1 && *op == '.')
2348 || (opt_type == 0 && *op != '.'))
2349 EMSG2(_(e_letwrong), op);
2350 else
2352 if (opt_type == 1) /* number */
2354 if (*op == '+')
2355 n = numval + n;
2356 else
2357 n = numval - n;
2359 else if (opt_type == 0 && stringval != NULL) /* string */
2361 s = concat_str(stringval, s);
2362 vim_free(stringval);
2363 stringval = s;
2367 if (s != NULL)
2369 set_option_value(arg, n, s, opt_flags);
2370 arg_end = p;
2372 *p = c1;
2373 vim_free(stringval);
2378 * ":let @r = expr": Set register contents.
2380 else if (*arg == '@')
2382 ++arg;
2383 if (op != NULL && (*op == '+' || *op == '-'))
2384 EMSG2(_(e_letwrong), op);
2385 else if (endchars != NULL
2386 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2387 EMSG(_(e_letunexp));
2388 else
2390 char_u *ptofree = NULL;
2391 char_u *s;
2393 p = get_tv_string_chk(tv);
2394 if (p != NULL && op != NULL && *op == '.')
2396 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2397 if (s != NULL)
2399 p = ptofree = concat_str(s, p);
2400 vim_free(s);
2403 if (p != NULL)
2405 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2406 arg_end = arg + 1;
2408 vim_free(ptofree);
2413 * ":let var = expr": Set internal variable.
2414 * ":let {expr} = expr": Idem, name made with curly braces
2416 else if (eval_isnamec1(*arg) || *arg == '{')
2418 lval_T lv;
2420 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2421 if (p != NULL && lv.ll_name != NULL)
2423 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2424 EMSG(_(e_letunexp));
2425 else
2427 set_var_lval(&lv, p, tv, copy, op);
2428 arg_end = p;
2431 clear_lval(&lv);
2434 else
2435 EMSG2(_(e_invarg2), arg);
2437 return arg_end;
2441 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2443 static int
2444 check_changedtick(arg)
2445 char_u *arg;
2447 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2449 EMSG2(_(e_readonlyvar), arg);
2450 return TRUE;
2452 return FALSE;
2456 * Get an lval: variable, Dict item or List item that can be assigned a value
2457 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2458 * "name.key", "name.key[expr]" etc.
2459 * Indexing only works if "name" is an existing List or Dictionary.
2460 * "name" points to the start of the name.
2461 * If "rettv" is not NULL it points to the value to be assigned.
2462 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2463 * wrong; must end in space or cmd separator.
2465 * Returns a pointer to just after the name, including indexes.
2466 * When an evaluation error occurs "lp->ll_name" is NULL;
2467 * Returns NULL for a parsing error. Still need to free items in "lp"!
2469 static char_u *
2470 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2471 char_u *name;
2472 typval_T *rettv;
2473 lval_T *lp;
2474 int unlet;
2475 int skip;
2476 int quiet; /* don't give error messages */
2477 int fne_flags; /* flags for find_name_end() */
2479 char_u *p;
2480 char_u *expr_start, *expr_end;
2481 int cc;
2482 dictitem_T *v;
2483 typval_T var1;
2484 typval_T var2;
2485 int empty1 = FALSE;
2486 listitem_T *ni;
2487 char_u *key = NULL;
2488 int len;
2489 hashtab_T *ht;
2491 /* Clear everything in "lp". */
2492 vim_memset(lp, 0, sizeof(lval_T));
2494 if (skip)
2496 /* When skipping just find the end of the name. */
2497 lp->ll_name = name;
2498 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2501 /* Find the end of the name. */
2502 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2503 if (expr_start != NULL)
2505 /* Don't expand the name when we already know there is an error. */
2506 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2507 && *p != '[' && *p != '.')
2509 EMSG(_(e_trailing));
2510 return NULL;
2513 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2514 if (lp->ll_exp_name == NULL)
2516 /* Report an invalid expression in braces, unless the
2517 * expression evaluation has been cancelled due to an
2518 * aborting error, an interrupt, or an exception. */
2519 if (!aborting() && !quiet)
2521 emsg_severe = TRUE;
2522 EMSG2(_(e_invarg2), name);
2523 return NULL;
2526 lp->ll_name = lp->ll_exp_name;
2528 else
2529 lp->ll_name = name;
2531 /* Without [idx] or .key we are done. */
2532 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2533 return p;
2535 cc = *p;
2536 *p = NUL;
2537 v = find_var(lp->ll_name, &ht);
2538 if (v == NULL && !quiet)
2539 EMSG2(_(e_undefvar), lp->ll_name);
2540 *p = cc;
2541 if (v == NULL)
2542 return NULL;
2545 * Loop until no more [idx] or .key is following.
2547 lp->ll_tv = &v->di_tv;
2548 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2550 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2551 && !(lp->ll_tv->v_type == VAR_DICT
2552 && lp->ll_tv->vval.v_dict != NULL))
2554 if (!quiet)
2555 EMSG(_("E689: Can only index a List or Dictionary"));
2556 return NULL;
2558 if (lp->ll_range)
2560 if (!quiet)
2561 EMSG(_("E708: [:] must come last"));
2562 return NULL;
2565 len = -1;
2566 if (*p == '.')
2568 key = p + 1;
2569 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2571 if (len == 0)
2573 if (!quiet)
2574 EMSG(_(e_emptykey));
2575 return NULL;
2577 p = key + len;
2579 else
2581 /* Get the index [expr] or the first index [expr: ]. */
2582 p = skipwhite(p + 1);
2583 if (*p == ':')
2584 empty1 = TRUE;
2585 else
2587 empty1 = FALSE;
2588 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2589 return NULL;
2590 if (get_tv_string_chk(&var1) == NULL)
2592 /* not a number or string */
2593 clear_tv(&var1);
2594 return NULL;
2598 /* Optionally get the second index [ :expr]. */
2599 if (*p == ':')
2601 if (lp->ll_tv->v_type == VAR_DICT)
2603 if (!quiet)
2604 EMSG(_(e_dictrange));
2605 if (!empty1)
2606 clear_tv(&var1);
2607 return NULL;
2609 if (rettv != NULL && (rettv->v_type != VAR_LIST
2610 || rettv->vval.v_list == NULL))
2612 if (!quiet)
2613 EMSG(_("E709: [:] requires a List value"));
2614 if (!empty1)
2615 clear_tv(&var1);
2616 return NULL;
2618 p = skipwhite(p + 1);
2619 if (*p == ']')
2620 lp->ll_empty2 = TRUE;
2621 else
2623 lp->ll_empty2 = FALSE;
2624 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2626 if (!empty1)
2627 clear_tv(&var1);
2628 return NULL;
2630 if (get_tv_string_chk(&var2) == NULL)
2632 /* not a number or string */
2633 if (!empty1)
2634 clear_tv(&var1);
2635 clear_tv(&var2);
2636 return NULL;
2639 lp->ll_range = TRUE;
2641 else
2642 lp->ll_range = FALSE;
2644 if (*p != ']')
2646 if (!quiet)
2647 EMSG(_(e_missbrac));
2648 if (!empty1)
2649 clear_tv(&var1);
2650 if (lp->ll_range && !lp->ll_empty2)
2651 clear_tv(&var2);
2652 return NULL;
2655 /* Skip to past ']'. */
2656 ++p;
2659 if (lp->ll_tv->v_type == VAR_DICT)
2661 if (len == -1)
2663 /* "[key]": get key from "var1" */
2664 key = get_tv_string(&var1); /* is number or string */
2665 if (*key == NUL)
2667 if (!quiet)
2668 EMSG(_(e_emptykey));
2669 clear_tv(&var1);
2670 return NULL;
2673 lp->ll_list = NULL;
2674 lp->ll_dict = lp->ll_tv->vval.v_dict;
2675 lp->ll_di = dict_find(lp->ll_dict, key, len);
2676 if (lp->ll_di == NULL)
2678 /* Key does not exist in dict: may need to add it. */
2679 if (*p == '[' || *p == '.' || unlet)
2681 if (!quiet)
2682 EMSG2(_(e_dictkey), key);
2683 if (len == -1)
2684 clear_tv(&var1);
2685 return NULL;
2687 if (len == -1)
2688 lp->ll_newkey = vim_strsave(key);
2689 else
2690 lp->ll_newkey = vim_strnsave(key, len);
2691 if (len == -1)
2692 clear_tv(&var1);
2693 if (lp->ll_newkey == NULL)
2694 p = NULL;
2695 break;
2697 if (len == -1)
2698 clear_tv(&var1);
2699 lp->ll_tv = &lp->ll_di->di_tv;
2701 else
2704 * Get the number and item for the only or first index of the List.
2706 if (empty1)
2707 lp->ll_n1 = 0;
2708 else
2710 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2711 clear_tv(&var1);
2713 lp->ll_dict = NULL;
2714 lp->ll_list = lp->ll_tv->vval.v_list;
2715 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2716 if (lp->ll_li == NULL)
2718 if (lp->ll_n1 < 0)
2720 lp->ll_n1 = 0;
2721 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2724 if (lp->ll_li == NULL)
2726 if (lp->ll_range && !lp->ll_empty2)
2727 clear_tv(&var2);
2728 return NULL;
2732 * May need to find the item or absolute index for the second
2733 * index of a range.
2734 * When no index given: "lp->ll_empty2" is TRUE.
2735 * Otherwise "lp->ll_n2" is set to the second index.
2737 if (lp->ll_range && !lp->ll_empty2)
2739 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2740 clear_tv(&var2);
2741 if (lp->ll_n2 < 0)
2743 ni = list_find(lp->ll_list, lp->ll_n2);
2744 if (ni == NULL)
2745 return NULL;
2746 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2749 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2750 if (lp->ll_n1 < 0)
2751 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2752 if (lp->ll_n2 < lp->ll_n1)
2753 return NULL;
2756 lp->ll_tv = &lp->ll_li->li_tv;
2760 return p;
2764 * Clear lval "lp" that was filled by get_lval().
2766 static void
2767 clear_lval(lp)
2768 lval_T *lp;
2770 vim_free(lp->ll_exp_name);
2771 vim_free(lp->ll_newkey);
2775 * Set a variable that was parsed by get_lval() to "rettv".
2776 * "endp" points to just after the parsed name.
2777 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2779 static void
2780 set_var_lval(lp, endp, rettv, copy, op)
2781 lval_T *lp;
2782 char_u *endp;
2783 typval_T *rettv;
2784 int copy;
2785 char_u *op;
2787 int cc;
2788 listitem_T *ri;
2789 dictitem_T *di;
2791 if (lp->ll_tv == NULL)
2793 if (!check_changedtick(lp->ll_name))
2795 cc = *endp;
2796 *endp = NUL;
2797 if (op != NULL && *op != '=')
2799 typval_T tv;
2801 /* handle +=, -= and .= */
2802 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2803 &tv, TRUE) == OK)
2805 if (tv_op(&tv, rettv, op) == OK)
2806 set_var(lp->ll_name, &tv, FALSE);
2807 clear_tv(&tv);
2810 else
2811 set_var(lp->ll_name, rettv, copy);
2812 *endp = cc;
2815 else if (tv_check_lock(lp->ll_newkey == NULL
2816 ? lp->ll_tv->v_lock
2817 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2819 else if (lp->ll_range)
2822 * Assign the List values to the list items.
2824 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2826 if (op != NULL && *op != '=')
2827 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2828 else
2830 clear_tv(&lp->ll_li->li_tv);
2831 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2833 ri = ri->li_next;
2834 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2835 break;
2836 if (lp->ll_li->li_next == NULL)
2838 /* Need to add an empty item. */
2839 if (list_append_number(lp->ll_list, 0) == FAIL)
2841 ri = NULL;
2842 break;
2845 lp->ll_li = lp->ll_li->li_next;
2846 ++lp->ll_n1;
2848 if (ri != NULL)
2849 EMSG(_("E710: List value has more items than target"));
2850 else if (lp->ll_empty2
2851 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2852 : lp->ll_n1 != lp->ll_n2)
2853 EMSG(_("E711: List value has not enough items"));
2855 else
2858 * Assign to a List or Dictionary item.
2860 if (lp->ll_newkey != NULL)
2862 if (op != NULL && *op != '=')
2864 EMSG2(_(e_letwrong), op);
2865 return;
2868 /* Need to add an item to the Dictionary. */
2869 di = dictitem_alloc(lp->ll_newkey);
2870 if (di == NULL)
2871 return;
2872 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2874 vim_free(di);
2875 return;
2877 lp->ll_tv = &di->di_tv;
2879 else if (op != NULL && *op != '=')
2881 tv_op(lp->ll_tv, rettv, op);
2882 return;
2884 else
2885 clear_tv(lp->ll_tv);
2888 * Assign the value to the variable or list item.
2890 if (copy)
2891 copy_tv(rettv, lp->ll_tv);
2892 else
2894 *lp->ll_tv = *rettv;
2895 lp->ll_tv->v_lock = 0;
2896 init_tv(rettv);
2902 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2903 * Returns OK or FAIL.
2905 static int
2906 tv_op(tv1, tv2, op)
2907 typval_T *tv1;
2908 typval_T *tv2;
2909 char_u *op;
2911 long n;
2912 char_u numbuf[NUMBUFLEN];
2913 char_u *s;
2915 /* Can't do anything with a Funcref or a Dict on the right. */
2916 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2918 switch (tv1->v_type)
2920 case VAR_DICT:
2921 case VAR_FUNC:
2922 break;
2924 case VAR_LIST:
2925 if (*op != '+' || tv2->v_type != VAR_LIST)
2926 break;
2927 /* List += List */
2928 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2929 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2930 return OK;
2932 case VAR_NUMBER:
2933 case VAR_STRING:
2934 if (tv2->v_type == VAR_LIST)
2935 break;
2936 if (*op == '+' || *op == '-')
2938 /* nr += nr or nr -= nr*/
2939 n = get_tv_number(tv1);
2940 #ifdef FEAT_FLOAT
2941 if (tv2->v_type == VAR_FLOAT)
2943 float_T f = n;
2945 if (*op == '+')
2946 f += tv2->vval.v_float;
2947 else
2948 f -= tv2->vval.v_float;
2949 clear_tv(tv1);
2950 tv1->v_type = VAR_FLOAT;
2951 tv1->vval.v_float = f;
2953 else
2954 #endif
2956 if (*op == '+')
2957 n += get_tv_number(tv2);
2958 else
2959 n -= get_tv_number(tv2);
2960 clear_tv(tv1);
2961 tv1->v_type = VAR_NUMBER;
2962 tv1->vval.v_number = n;
2965 else
2967 if (tv2->v_type == VAR_FLOAT)
2968 break;
2970 /* str .= str */
2971 s = get_tv_string(tv1);
2972 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2973 clear_tv(tv1);
2974 tv1->v_type = VAR_STRING;
2975 tv1->vval.v_string = s;
2977 return OK;
2979 #ifdef FEAT_FLOAT
2980 case VAR_FLOAT:
2982 float_T f;
2984 if (*op == '.' || (tv2->v_type != VAR_FLOAT
2985 && tv2->v_type != VAR_NUMBER
2986 && tv2->v_type != VAR_STRING))
2987 break;
2988 if (tv2->v_type == VAR_FLOAT)
2989 f = tv2->vval.v_float;
2990 else
2991 f = get_tv_number(tv2);
2992 if (*op == '+')
2993 tv1->vval.v_float += f;
2994 else
2995 tv1->vval.v_float -= f;
2997 return OK;
2998 #endif
3002 EMSG2(_(e_letwrong), op);
3003 return FAIL;
3007 * Add a watcher to a list.
3009 static void
3010 list_add_watch(l, lw)
3011 list_T *l;
3012 listwatch_T *lw;
3014 lw->lw_next = l->lv_watch;
3015 l->lv_watch = lw;
3019 * Remove a watcher from a list.
3020 * No warning when it isn't found...
3022 static void
3023 list_rem_watch(l, lwrem)
3024 list_T *l;
3025 listwatch_T *lwrem;
3027 listwatch_T *lw, **lwp;
3029 lwp = &l->lv_watch;
3030 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3032 if (lw == lwrem)
3034 *lwp = lw->lw_next;
3035 break;
3037 lwp = &lw->lw_next;
3042 * Just before removing an item from a list: advance watchers to the next
3043 * item.
3045 static void
3046 list_fix_watch(l, item)
3047 list_T *l;
3048 listitem_T *item;
3050 listwatch_T *lw;
3052 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3053 if (lw->lw_item == item)
3054 lw->lw_item = item->li_next;
3058 * Evaluate the expression used in a ":for var in expr" command.
3059 * "arg" points to "var".
3060 * Set "*errp" to TRUE for an error, FALSE otherwise;
3061 * Return a pointer that holds the info. Null when there is an error.
3063 void *
3064 eval_for_line(arg, errp, nextcmdp, skip)
3065 char_u *arg;
3066 int *errp;
3067 char_u **nextcmdp;
3068 int skip;
3070 forinfo_T *fi;
3071 char_u *expr;
3072 typval_T tv;
3073 list_T *l;
3075 *errp = TRUE; /* default: there is an error */
3077 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
3078 if (fi == NULL)
3079 return NULL;
3081 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
3082 if (expr == NULL)
3083 return fi;
3085 expr = skipwhite(expr);
3086 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
3088 EMSG(_("E690: Missing \"in\" after :for"));
3089 return fi;
3092 if (skip)
3093 ++emsg_skip;
3094 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
3096 *errp = FALSE;
3097 if (!skip)
3099 l = tv.vval.v_list;
3100 if (tv.v_type != VAR_LIST || l == NULL)
3102 EMSG(_(e_listreq));
3103 clear_tv(&tv);
3105 else
3107 /* No need to increment the refcount, it's already set for the
3108 * list being used in "tv". */
3109 fi->fi_list = l;
3110 list_add_watch(l, &fi->fi_lw);
3111 fi->fi_lw.lw_item = l->lv_first;
3115 if (skip)
3116 --emsg_skip;
3118 return fi;
3122 * Use the first item in a ":for" list. Advance to the next.
3123 * Assign the values to the variable (list). "arg" points to the first one.
3124 * Return TRUE when a valid item was found, FALSE when at end of list or
3125 * something wrong.
3128 next_for_item(fi_void, arg)
3129 void *fi_void;
3130 char_u *arg;
3132 forinfo_T *fi = (forinfo_T *)fi_void;
3133 int result;
3134 listitem_T *item;
3136 item = fi->fi_lw.lw_item;
3137 if (item == NULL)
3138 result = FALSE;
3139 else
3141 fi->fi_lw.lw_item = item->li_next;
3142 result = (ex_let_vars(arg, &item->li_tv, TRUE,
3143 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3145 return result;
3149 * Free the structure used to store info used by ":for".
3151 void
3152 free_for_info(fi_void)
3153 void *fi_void;
3155 forinfo_T *fi = (forinfo_T *)fi_void;
3157 if (fi != NULL && fi->fi_list != NULL)
3159 list_rem_watch(fi->fi_list, &fi->fi_lw);
3160 list_unref(fi->fi_list);
3162 vim_free(fi);
3165 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3167 void
3168 set_context_for_expression(xp, arg, cmdidx)
3169 expand_T *xp;
3170 char_u *arg;
3171 cmdidx_T cmdidx;
3173 int got_eq = FALSE;
3174 int c;
3175 char_u *p;
3177 if (cmdidx == CMD_let)
3179 xp->xp_context = EXPAND_USER_VARS;
3180 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3182 /* ":let var1 var2 ...": find last space. */
3183 for (p = arg + STRLEN(arg); p >= arg; )
3185 xp->xp_pattern = p;
3186 mb_ptr_back(arg, p);
3187 if (vim_iswhite(*p))
3188 break;
3190 return;
3193 else
3194 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3195 : EXPAND_EXPRESSION;
3196 while ((xp->xp_pattern = vim_strpbrk(arg,
3197 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3199 c = *xp->xp_pattern;
3200 if (c == '&')
3202 c = xp->xp_pattern[1];
3203 if (c == '&')
3205 ++xp->xp_pattern;
3206 xp->xp_context = cmdidx != CMD_let || got_eq
3207 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3209 else if (c != ' ')
3211 xp->xp_context = EXPAND_SETTINGS;
3212 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3213 xp->xp_pattern += 2;
3217 else if (c == '$')
3219 /* environment variable */
3220 xp->xp_context = EXPAND_ENV_VARS;
3222 else if (c == '=')
3224 got_eq = TRUE;
3225 xp->xp_context = EXPAND_EXPRESSION;
3227 else if (c == '<'
3228 && xp->xp_context == EXPAND_FUNCTIONS
3229 && vim_strchr(xp->xp_pattern, '(') == NULL)
3231 /* Function name can start with "<SNR>" */
3232 break;
3234 else if (cmdidx != CMD_let || got_eq)
3236 if (c == '"') /* string */
3238 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3239 if (c == '\\' && xp->xp_pattern[1] != NUL)
3240 ++xp->xp_pattern;
3241 xp->xp_context = EXPAND_NOTHING;
3243 else if (c == '\'') /* literal string */
3245 /* Trick: '' is like stopping and starting a literal string. */
3246 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3247 /* skip */ ;
3248 xp->xp_context = EXPAND_NOTHING;
3250 else if (c == '|')
3252 if (xp->xp_pattern[1] == '|')
3254 ++xp->xp_pattern;
3255 xp->xp_context = EXPAND_EXPRESSION;
3257 else
3258 xp->xp_context = EXPAND_COMMANDS;
3260 else
3261 xp->xp_context = EXPAND_EXPRESSION;
3263 else
3264 /* Doesn't look like something valid, expand as an expression
3265 * anyway. */
3266 xp->xp_context = EXPAND_EXPRESSION;
3267 arg = xp->xp_pattern;
3268 if (*arg != NUL)
3269 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3270 /* skip */ ;
3272 xp->xp_pattern = arg;
3275 #endif /* FEAT_CMDL_COMPL */
3278 * ":1,25call func(arg1, arg2)" function call.
3280 void
3281 ex_call(eap)
3282 exarg_T *eap;
3284 char_u *arg = eap->arg;
3285 char_u *startarg;
3286 char_u *name;
3287 char_u *tofree;
3288 int len;
3289 typval_T rettv;
3290 linenr_T lnum;
3291 int doesrange;
3292 int failed = FALSE;
3293 funcdict_T fudi;
3295 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3296 if (fudi.fd_newkey != NULL)
3298 /* Still need to give an error message for missing key. */
3299 EMSG2(_(e_dictkey), fudi.fd_newkey);
3300 vim_free(fudi.fd_newkey);
3302 if (tofree == NULL)
3303 return;
3305 /* Increase refcount on dictionary, it could get deleted when evaluating
3306 * the arguments. */
3307 if (fudi.fd_dict != NULL)
3308 ++fudi.fd_dict->dv_refcount;
3310 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3311 len = (int)STRLEN(tofree);
3312 name = deref_func_name(tofree, &len);
3314 /* Skip white space to allow ":call func ()". Not good, but required for
3315 * backward compatibility. */
3316 startarg = skipwhite(arg);
3317 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3319 if (*startarg != '(')
3321 EMSG2(_("E107: Missing parentheses: %s"), eap->arg);
3322 goto end;
3326 * When skipping, evaluate the function once, to find the end of the
3327 * arguments.
3328 * When the function takes a range, this is discovered after the first
3329 * call, and the loop is broken.
3331 if (eap->skip)
3333 ++emsg_skip;
3334 lnum = eap->line2; /* do it once, also with an invalid range */
3336 else
3337 lnum = eap->line1;
3338 for ( ; lnum <= eap->line2; ++lnum)
3340 if (!eap->skip && eap->addr_count > 0)
3342 curwin->w_cursor.lnum = lnum;
3343 curwin->w_cursor.col = 0;
3345 arg = startarg;
3346 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3347 eap->line1, eap->line2, &doesrange,
3348 !eap->skip, fudi.fd_dict) == FAIL)
3350 failed = TRUE;
3351 break;
3354 /* Handle a function returning a Funcref, Dictionary or List. */
3355 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3357 failed = TRUE;
3358 break;
3361 clear_tv(&rettv);
3362 if (doesrange || eap->skip)
3363 break;
3365 /* Stop when immediately aborting on error, or when an interrupt
3366 * occurred or an exception was thrown but not caught.
3367 * get_func_tv() returned OK, so that the check for trailing
3368 * characters below is executed. */
3369 if (aborting())
3370 break;
3372 if (eap->skip)
3373 --emsg_skip;
3375 if (!failed)
3377 /* Check for trailing illegal characters and a following command. */
3378 if (!ends_excmd(*arg))
3380 emsg_severe = TRUE;
3381 EMSG(_(e_trailing));
3383 else
3384 eap->nextcmd = check_nextcmd(arg);
3387 end:
3388 dict_unref(fudi.fd_dict);
3389 vim_free(tofree);
3393 * ":unlet[!] var1 ... " command.
3395 void
3396 ex_unlet(eap)
3397 exarg_T *eap;
3399 ex_unletlock(eap, eap->arg, 0);
3403 * ":lockvar" and ":unlockvar" commands
3405 void
3406 ex_lockvar(eap)
3407 exarg_T *eap;
3409 char_u *arg = eap->arg;
3410 int deep = 2;
3412 if (eap->forceit)
3413 deep = -1;
3414 else if (vim_isdigit(*arg))
3416 deep = getdigits(&arg);
3417 arg = skipwhite(arg);
3420 ex_unletlock(eap, arg, deep);
3424 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3426 static void
3427 ex_unletlock(eap, argstart, deep)
3428 exarg_T *eap;
3429 char_u *argstart;
3430 int deep;
3432 char_u *arg = argstart;
3433 char_u *name_end;
3434 int error = FALSE;
3435 lval_T lv;
3439 /* Parse the name and find the end. */
3440 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3441 FNE_CHECK_START);
3442 if (lv.ll_name == NULL)
3443 error = TRUE; /* error but continue parsing */
3444 if (name_end == NULL || (!vim_iswhite(*name_end)
3445 && !ends_excmd(*name_end)))
3447 if (name_end != NULL)
3449 emsg_severe = TRUE;
3450 EMSG(_(e_trailing));
3452 if (!(eap->skip || error))
3453 clear_lval(&lv);
3454 break;
3457 if (!error && !eap->skip)
3459 if (eap->cmdidx == CMD_unlet)
3461 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3462 error = TRUE;
3464 else
3466 if (do_lock_var(&lv, name_end, deep,
3467 eap->cmdidx == CMD_lockvar) == FAIL)
3468 error = TRUE;
3472 if (!eap->skip)
3473 clear_lval(&lv);
3475 arg = skipwhite(name_end);
3476 } while (!ends_excmd(*arg));
3478 eap->nextcmd = check_nextcmd(arg);
3481 static int
3482 do_unlet_var(lp, name_end, forceit)
3483 lval_T *lp;
3484 char_u *name_end;
3485 int forceit;
3487 int ret = OK;
3488 int cc;
3490 if (lp->ll_tv == NULL)
3492 cc = *name_end;
3493 *name_end = NUL;
3495 /* Normal name or expanded name. */
3496 if (check_changedtick(lp->ll_name))
3497 ret = FAIL;
3498 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3499 ret = FAIL;
3500 *name_end = cc;
3502 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3503 return FAIL;
3504 else if (lp->ll_range)
3506 listitem_T *li;
3508 /* Delete a range of List items. */
3509 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3511 li = lp->ll_li->li_next;
3512 listitem_remove(lp->ll_list, lp->ll_li);
3513 lp->ll_li = li;
3514 ++lp->ll_n1;
3517 else
3519 if (lp->ll_list != NULL)
3520 /* unlet a List item. */
3521 listitem_remove(lp->ll_list, lp->ll_li);
3522 else
3523 /* unlet a Dictionary item. */
3524 dictitem_remove(lp->ll_dict, lp->ll_di);
3527 return ret;
3531 * "unlet" a variable. Return OK if it existed, FAIL if not.
3532 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3535 do_unlet(name, forceit)
3536 char_u *name;
3537 int forceit;
3539 hashtab_T *ht;
3540 hashitem_T *hi;
3541 char_u *varname;
3542 dictitem_T *di;
3544 ht = find_var_ht(name, &varname);
3545 if (ht != NULL && *varname != NUL)
3547 hi = hash_find(ht, varname);
3548 if (!HASHITEM_EMPTY(hi))
3550 di = HI2DI(hi);
3551 if (var_check_fixed(di->di_flags, name)
3552 || var_check_ro(di->di_flags, name))
3553 return FAIL;
3554 delete_var(ht, hi);
3555 return OK;
3558 if (forceit)
3559 return OK;
3560 EMSG2(_("E108: No such variable: \"%s\""), name);
3561 return FAIL;
3565 * Lock or unlock variable indicated by "lp".
3566 * "deep" is the levels to go (-1 for unlimited);
3567 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3569 static int
3570 do_lock_var(lp, name_end, deep, lock)
3571 lval_T *lp;
3572 char_u *name_end;
3573 int deep;
3574 int lock;
3576 int ret = OK;
3577 int cc;
3578 dictitem_T *di;
3580 if (deep == 0) /* nothing to do */
3581 return OK;
3583 if (lp->ll_tv == NULL)
3585 cc = *name_end;
3586 *name_end = NUL;
3588 /* Normal name or expanded name. */
3589 if (check_changedtick(lp->ll_name))
3590 ret = FAIL;
3591 else
3593 di = find_var(lp->ll_name, NULL);
3594 if (di == NULL)
3595 ret = FAIL;
3596 else
3598 if (lock)
3599 di->di_flags |= DI_FLAGS_LOCK;
3600 else
3601 di->di_flags &= ~DI_FLAGS_LOCK;
3602 item_lock(&di->di_tv, deep, lock);
3605 *name_end = cc;
3607 else if (lp->ll_range)
3609 listitem_T *li = lp->ll_li;
3611 /* (un)lock a range of List items. */
3612 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3614 item_lock(&li->li_tv, deep, lock);
3615 li = li->li_next;
3616 ++lp->ll_n1;
3619 else if (lp->ll_list != NULL)
3620 /* (un)lock a List item. */
3621 item_lock(&lp->ll_li->li_tv, deep, lock);
3622 else
3623 /* un(lock) a Dictionary item. */
3624 item_lock(&lp->ll_di->di_tv, deep, lock);
3626 return ret;
3630 * Lock or unlock an item. "deep" is nr of levels to go.
3632 static void
3633 item_lock(tv, deep, lock)
3634 typval_T *tv;
3635 int deep;
3636 int lock;
3638 static int recurse = 0;
3639 list_T *l;
3640 listitem_T *li;
3641 dict_T *d;
3642 hashitem_T *hi;
3643 int todo;
3645 if (recurse >= DICT_MAXNEST)
3647 EMSG(_("E743: variable nested too deep for (un)lock"));
3648 return;
3650 if (deep == 0)
3651 return;
3652 ++recurse;
3654 /* lock/unlock the item itself */
3655 if (lock)
3656 tv->v_lock |= VAR_LOCKED;
3657 else
3658 tv->v_lock &= ~VAR_LOCKED;
3660 switch (tv->v_type)
3662 case VAR_LIST:
3663 if ((l = tv->vval.v_list) != NULL)
3665 if (lock)
3666 l->lv_lock |= VAR_LOCKED;
3667 else
3668 l->lv_lock &= ~VAR_LOCKED;
3669 if (deep < 0 || deep > 1)
3670 /* recursive: lock/unlock the items the List contains */
3671 for (li = l->lv_first; li != NULL; li = li->li_next)
3672 item_lock(&li->li_tv, deep - 1, lock);
3674 break;
3675 case VAR_DICT:
3676 if ((d = tv->vval.v_dict) != NULL)
3678 if (lock)
3679 d->dv_lock |= VAR_LOCKED;
3680 else
3681 d->dv_lock &= ~VAR_LOCKED;
3682 if (deep < 0 || deep > 1)
3684 /* recursive: lock/unlock the items the List contains */
3685 todo = (int)d->dv_hashtab.ht_used;
3686 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3688 if (!HASHITEM_EMPTY(hi))
3690 --todo;
3691 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3697 --recurse;
3701 * Return TRUE if typeval "tv" is locked: Either that value is locked itself
3702 * or it refers to a List or Dictionary that is locked.
3704 static int
3705 tv_islocked(tv)
3706 typval_T *tv;
3708 return (tv->v_lock & VAR_LOCKED)
3709 || (tv->v_type == VAR_LIST
3710 && tv->vval.v_list != NULL
3711 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3712 || (tv->v_type == VAR_DICT
3713 && tv->vval.v_dict != NULL
3714 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3717 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3719 * Delete all "menutrans_" variables.
3721 void
3722 del_menutrans_vars()
3724 hashitem_T *hi;
3725 int todo;
3727 hash_lock(&globvarht);
3728 todo = (int)globvarht.ht_used;
3729 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3731 if (!HASHITEM_EMPTY(hi))
3733 --todo;
3734 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3735 delete_var(&globvarht, hi);
3738 hash_unlock(&globvarht);
3740 #endif
3742 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3745 * Local string buffer for the next two functions to store a variable name
3746 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3747 * get_user_var_name().
3750 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3752 static char_u *varnamebuf = NULL;
3753 static int varnamebuflen = 0;
3756 * Function to concatenate a prefix and a variable name.
3758 static char_u *
3759 cat_prefix_varname(prefix, name)
3760 int prefix;
3761 char_u *name;
3763 int len;
3765 len = (int)STRLEN(name) + 3;
3766 if (len > varnamebuflen)
3768 vim_free(varnamebuf);
3769 len += 10; /* some additional space */
3770 varnamebuf = alloc(len);
3771 if (varnamebuf == NULL)
3773 varnamebuflen = 0;
3774 return NULL;
3776 varnamebuflen = len;
3778 *varnamebuf = prefix;
3779 varnamebuf[1] = ':';
3780 STRCPY(varnamebuf + 2, name);
3781 return varnamebuf;
3785 * Function given to ExpandGeneric() to obtain the list of user defined
3786 * (global/buffer/window/built-in) variable names.
3788 /*ARGSUSED*/
3789 char_u *
3790 get_user_var_name(xp, idx)
3791 expand_T *xp;
3792 int idx;
3794 static long_u gdone;
3795 static long_u bdone;
3796 static long_u wdone;
3797 #ifdef FEAT_WINDOWS
3798 static long_u tdone;
3799 #endif
3800 static int vidx;
3801 static hashitem_T *hi;
3802 hashtab_T *ht;
3804 if (idx == 0)
3806 gdone = bdone = wdone = vidx = 0;
3807 #ifdef FEAT_WINDOWS
3808 tdone = 0;
3809 #endif
3812 /* Global variables */
3813 if (gdone < globvarht.ht_used)
3815 if (gdone++ == 0)
3816 hi = globvarht.ht_array;
3817 else
3818 ++hi;
3819 while (HASHITEM_EMPTY(hi))
3820 ++hi;
3821 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3822 return cat_prefix_varname('g', hi->hi_key);
3823 return hi->hi_key;
3826 /* b: variables */
3827 ht = &curbuf->b_vars.dv_hashtab;
3828 if (bdone < ht->ht_used)
3830 if (bdone++ == 0)
3831 hi = ht->ht_array;
3832 else
3833 ++hi;
3834 while (HASHITEM_EMPTY(hi))
3835 ++hi;
3836 return cat_prefix_varname('b', hi->hi_key);
3838 if (bdone == ht->ht_used)
3840 ++bdone;
3841 return (char_u *)"b:changedtick";
3844 /* w: variables */
3845 ht = &curwin->w_vars.dv_hashtab;
3846 if (wdone < ht->ht_used)
3848 if (wdone++ == 0)
3849 hi = ht->ht_array;
3850 else
3851 ++hi;
3852 while (HASHITEM_EMPTY(hi))
3853 ++hi;
3854 return cat_prefix_varname('w', hi->hi_key);
3857 #ifdef FEAT_WINDOWS
3858 /* t: variables */
3859 ht = &curtab->tp_vars.dv_hashtab;
3860 if (tdone < ht->ht_used)
3862 if (tdone++ == 0)
3863 hi = ht->ht_array;
3864 else
3865 ++hi;
3866 while (HASHITEM_EMPTY(hi))
3867 ++hi;
3868 return cat_prefix_varname('t', hi->hi_key);
3870 #endif
3872 /* v: variables */
3873 if (vidx < VV_LEN)
3874 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3876 vim_free(varnamebuf);
3877 varnamebuf = NULL;
3878 varnamebuflen = 0;
3879 return NULL;
3882 #endif /* FEAT_CMDL_COMPL */
3885 * types for expressions.
3887 typedef enum
3889 TYPE_UNKNOWN = 0
3890 , TYPE_EQUAL /* == */
3891 , TYPE_NEQUAL /* != */
3892 , TYPE_GREATER /* > */
3893 , TYPE_GEQUAL /* >= */
3894 , TYPE_SMALLER /* < */
3895 , TYPE_SEQUAL /* <= */
3896 , TYPE_MATCH /* =~ */
3897 , TYPE_NOMATCH /* !~ */
3898 } exptype_T;
3901 * The "evaluate" argument: When FALSE, the argument is only parsed but not
3902 * executed. The function may return OK, but the rettv will be of type
3903 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
3907 * Handle zero level expression.
3908 * This calls eval1() and handles error message and nextcmd.
3909 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3910 * Note: "rettv.v_lock" is not set.
3911 * Return OK or FAIL.
3913 static int
3914 eval0(arg, rettv, nextcmd, evaluate)
3915 char_u *arg;
3916 typval_T *rettv;
3917 char_u **nextcmd;
3918 int evaluate;
3920 int ret;
3921 char_u *p;
3923 p = skipwhite(arg);
3924 ret = eval1(&p, rettv, evaluate);
3925 if (ret == FAIL || !ends_excmd(*p))
3927 if (ret != FAIL)
3928 clear_tv(rettv);
3930 * Report the invalid expression unless the expression evaluation has
3931 * been cancelled due to an aborting error, an interrupt, or an
3932 * exception.
3934 if (!aborting())
3935 EMSG2(_(e_invexpr2), arg);
3936 ret = FAIL;
3938 if (nextcmd != NULL)
3939 *nextcmd = check_nextcmd(p);
3941 return ret;
3945 * Handle top level expression:
3946 * expr1 ? expr0 : expr0
3948 * "arg" must point to the first non-white of the expression.
3949 * "arg" is advanced to the next non-white after the recognized expression.
3951 * Note: "rettv.v_lock" is not set.
3953 * Return OK or FAIL.
3955 static int
3956 eval1(arg, rettv, evaluate)
3957 char_u **arg;
3958 typval_T *rettv;
3959 int evaluate;
3961 int result;
3962 typval_T var2;
3965 * Get the first variable.
3967 if (eval2(arg, rettv, evaluate) == FAIL)
3968 return FAIL;
3970 if ((*arg)[0] == '?')
3972 result = FALSE;
3973 if (evaluate)
3975 int error = FALSE;
3977 if (get_tv_number_chk(rettv, &error) != 0)
3978 result = TRUE;
3979 clear_tv(rettv);
3980 if (error)
3981 return FAIL;
3985 * Get the second variable.
3987 *arg = skipwhite(*arg + 1);
3988 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
3989 return FAIL;
3992 * Check for the ":".
3994 if ((*arg)[0] != ':')
3996 EMSG(_("E109: Missing ':' after '?'"));
3997 if (evaluate && result)
3998 clear_tv(rettv);
3999 return FAIL;
4003 * Get the third variable.
4005 *arg = skipwhite(*arg + 1);
4006 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
4008 if (evaluate && result)
4009 clear_tv(rettv);
4010 return FAIL;
4012 if (evaluate && !result)
4013 *rettv = var2;
4016 return OK;
4020 * Handle first level expression:
4021 * expr2 || expr2 || expr2 logical OR
4023 * "arg" must point to the first non-white of the expression.
4024 * "arg" is advanced to the next non-white after the recognized expression.
4026 * Return OK or FAIL.
4028 static int
4029 eval2(arg, rettv, evaluate)
4030 char_u **arg;
4031 typval_T *rettv;
4032 int evaluate;
4034 typval_T var2;
4035 long result;
4036 int first;
4037 int error = FALSE;
4040 * Get the first variable.
4042 if (eval3(arg, rettv, evaluate) == FAIL)
4043 return FAIL;
4046 * Repeat until there is no following "||".
4048 first = TRUE;
4049 result = FALSE;
4050 while ((*arg)[0] == '|' && (*arg)[1] == '|')
4052 if (evaluate && first)
4054 if (get_tv_number_chk(rettv, &error) != 0)
4055 result = TRUE;
4056 clear_tv(rettv);
4057 if (error)
4058 return FAIL;
4059 first = FALSE;
4063 * Get the second variable.
4065 *arg = skipwhite(*arg + 2);
4066 if (eval3(arg, &var2, evaluate && !result) == FAIL)
4067 return FAIL;
4070 * Compute the result.
4072 if (evaluate && !result)
4074 if (get_tv_number_chk(&var2, &error) != 0)
4075 result = TRUE;
4076 clear_tv(&var2);
4077 if (error)
4078 return FAIL;
4080 if (evaluate)
4082 rettv->v_type = VAR_NUMBER;
4083 rettv->vval.v_number = result;
4087 return OK;
4091 * Handle second level expression:
4092 * expr3 && expr3 && expr3 logical AND
4094 * "arg" must point to the first non-white of the expression.
4095 * "arg" is advanced to the next non-white after the recognized expression.
4097 * Return OK or FAIL.
4099 static int
4100 eval3(arg, rettv, evaluate)
4101 char_u **arg;
4102 typval_T *rettv;
4103 int evaluate;
4105 typval_T var2;
4106 long result;
4107 int first;
4108 int error = FALSE;
4111 * Get the first variable.
4113 if (eval4(arg, rettv, evaluate) == FAIL)
4114 return FAIL;
4117 * Repeat until there is no following "&&".
4119 first = TRUE;
4120 result = TRUE;
4121 while ((*arg)[0] == '&' && (*arg)[1] == '&')
4123 if (evaluate && first)
4125 if (get_tv_number_chk(rettv, &error) == 0)
4126 result = FALSE;
4127 clear_tv(rettv);
4128 if (error)
4129 return FAIL;
4130 first = FALSE;
4134 * Get the second variable.
4136 *arg = skipwhite(*arg + 2);
4137 if (eval4(arg, &var2, evaluate && result) == FAIL)
4138 return FAIL;
4141 * Compute the result.
4143 if (evaluate && result)
4145 if (get_tv_number_chk(&var2, &error) == 0)
4146 result = FALSE;
4147 clear_tv(&var2);
4148 if (error)
4149 return FAIL;
4151 if (evaluate)
4153 rettv->v_type = VAR_NUMBER;
4154 rettv->vval.v_number = result;
4158 return OK;
4162 * Handle third level expression:
4163 * var1 == var2
4164 * var1 =~ var2
4165 * var1 != var2
4166 * var1 !~ var2
4167 * var1 > var2
4168 * var1 >= var2
4169 * var1 < var2
4170 * var1 <= var2
4171 * var1 is var2
4172 * var1 isnot var2
4174 * "arg" must point to the first non-white of the expression.
4175 * "arg" is advanced to the next non-white after the recognized expression.
4177 * Return OK or FAIL.
4179 static int
4180 eval4(arg, rettv, evaluate)
4181 char_u **arg;
4182 typval_T *rettv;
4183 int evaluate;
4185 typval_T var2;
4186 char_u *p;
4187 int i;
4188 exptype_T type = TYPE_UNKNOWN;
4189 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4190 int len = 2;
4191 long n1, n2;
4192 char_u *s1, *s2;
4193 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4194 regmatch_T regmatch;
4195 int ic;
4196 char_u *save_cpo;
4199 * Get the first variable.
4201 if (eval5(arg, rettv, evaluate) == FAIL)
4202 return FAIL;
4204 p = *arg;
4205 switch (p[0])
4207 case '=': if (p[1] == '=')
4208 type = TYPE_EQUAL;
4209 else if (p[1] == '~')
4210 type = TYPE_MATCH;
4211 break;
4212 case '!': if (p[1] == '=')
4213 type = TYPE_NEQUAL;
4214 else if (p[1] == '~')
4215 type = TYPE_NOMATCH;
4216 break;
4217 case '>': if (p[1] != '=')
4219 type = TYPE_GREATER;
4220 len = 1;
4222 else
4223 type = TYPE_GEQUAL;
4224 break;
4225 case '<': if (p[1] != '=')
4227 type = TYPE_SMALLER;
4228 len = 1;
4230 else
4231 type = TYPE_SEQUAL;
4232 break;
4233 case 'i': if (p[1] == 's')
4235 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4236 len = 5;
4237 if (!vim_isIDc(p[len]))
4239 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4240 type_is = TRUE;
4243 break;
4247 * If there is a comparative operator, use it.
4249 if (type != TYPE_UNKNOWN)
4251 /* extra question mark appended: ignore case */
4252 if (p[len] == '?')
4254 ic = TRUE;
4255 ++len;
4257 /* extra '#' appended: match case */
4258 else if (p[len] == '#')
4260 ic = FALSE;
4261 ++len;
4263 /* nothing appended: use 'ignorecase' */
4264 else
4265 ic = p_ic;
4268 * Get the second variable.
4270 *arg = skipwhite(p + len);
4271 if (eval5(arg, &var2, evaluate) == FAIL)
4273 clear_tv(rettv);
4274 return FAIL;
4277 if (evaluate)
4279 if (type_is && rettv->v_type != var2.v_type)
4281 /* For "is" a different type always means FALSE, for "notis"
4282 * it means TRUE. */
4283 n1 = (type == TYPE_NEQUAL);
4285 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4287 if (type_is)
4289 n1 = (rettv->v_type == var2.v_type
4290 && rettv->vval.v_list == var2.vval.v_list);
4291 if (type == TYPE_NEQUAL)
4292 n1 = !n1;
4294 else if (rettv->v_type != var2.v_type
4295 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4297 if (rettv->v_type != var2.v_type)
4298 EMSG(_("E691: Can only compare List with List"));
4299 else
4300 EMSG(_("E692: Invalid operation for Lists"));
4301 clear_tv(rettv);
4302 clear_tv(&var2);
4303 return FAIL;
4305 else
4307 /* Compare two Lists for being equal or unequal. */
4308 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
4309 if (type == TYPE_NEQUAL)
4310 n1 = !n1;
4314 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4316 if (type_is)
4318 n1 = (rettv->v_type == var2.v_type
4319 && rettv->vval.v_dict == var2.vval.v_dict);
4320 if (type == TYPE_NEQUAL)
4321 n1 = !n1;
4323 else if (rettv->v_type != var2.v_type
4324 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4326 if (rettv->v_type != var2.v_type)
4327 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4328 else
4329 EMSG(_("E736: Invalid operation for Dictionary"));
4330 clear_tv(rettv);
4331 clear_tv(&var2);
4332 return FAIL;
4334 else
4336 /* Compare two Dictionaries for being equal or unequal. */
4337 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4338 if (type == TYPE_NEQUAL)
4339 n1 = !n1;
4343 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4345 if (rettv->v_type != var2.v_type
4346 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4348 if (rettv->v_type != var2.v_type)
4349 EMSG(_("E693: Can only compare Funcref with Funcref"));
4350 else
4351 EMSG(_("E694: Invalid operation for Funcrefs"));
4352 clear_tv(rettv);
4353 clear_tv(&var2);
4354 return FAIL;
4356 else
4358 /* Compare two Funcrefs for being equal or unequal. */
4359 if (rettv->vval.v_string == NULL
4360 || var2.vval.v_string == NULL)
4361 n1 = FALSE;
4362 else
4363 n1 = STRCMP(rettv->vval.v_string,
4364 var2.vval.v_string) == 0;
4365 if (type == TYPE_NEQUAL)
4366 n1 = !n1;
4370 #ifdef FEAT_FLOAT
4372 * If one of the two variables is a float, compare as a float.
4373 * When using "=~" or "!~", always compare as string.
4375 else if ((rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4376 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4378 float_T f1, f2;
4380 if (rettv->v_type == VAR_FLOAT)
4381 f1 = rettv->vval.v_float;
4382 else
4383 f1 = get_tv_number(rettv);
4384 if (var2.v_type == VAR_FLOAT)
4385 f2 = var2.vval.v_float;
4386 else
4387 f2 = get_tv_number(&var2);
4388 n1 = FALSE;
4389 switch (type)
4391 case TYPE_EQUAL: n1 = (f1 == f2); break;
4392 case TYPE_NEQUAL: n1 = (f1 != f2); break;
4393 case TYPE_GREATER: n1 = (f1 > f2); break;
4394 case TYPE_GEQUAL: n1 = (f1 >= f2); break;
4395 case TYPE_SMALLER: n1 = (f1 < f2); break;
4396 case TYPE_SEQUAL: n1 = (f1 <= f2); break;
4397 case TYPE_UNKNOWN:
4398 case TYPE_MATCH:
4399 case TYPE_NOMATCH: break; /* avoid gcc warning */
4402 #endif
4405 * If one of the two variables is a number, compare as a number.
4406 * When using "=~" or "!~", always compare as string.
4408 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4409 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4411 n1 = get_tv_number(rettv);
4412 n2 = get_tv_number(&var2);
4413 switch (type)
4415 case TYPE_EQUAL: n1 = (n1 == n2); break;
4416 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4417 case TYPE_GREATER: n1 = (n1 > n2); break;
4418 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4419 case TYPE_SMALLER: n1 = (n1 < n2); break;
4420 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4421 case TYPE_UNKNOWN:
4422 case TYPE_MATCH:
4423 case TYPE_NOMATCH: break; /* avoid gcc warning */
4426 else
4428 s1 = get_tv_string_buf(rettv, buf1);
4429 s2 = get_tv_string_buf(&var2, buf2);
4430 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4431 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4432 else
4433 i = 0;
4434 n1 = FALSE;
4435 switch (type)
4437 case TYPE_EQUAL: n1 = (i == 0); break;
4438 case TYPE_NEQUAL: n1 = (i != 0); break;
4439 case TYPE_GREATER: n1 = (i > 0); break;
4440 case TYPE_GEQUAL: n1 = (i >= 0); break;
4441 case TYPE_SMALLER: n1 = (i < 0); break;
4442 case TYPE_SEQUAL: n1 = (i <= 0); break;
4444 case TYPE_MATCH:
4445 case TYPE_NOMATCH:
4446 /* avoid 'l' flag in 'cpoptions' */
4447 save_cpo = p_cpo;
4448 p_cpo = (char_u *)"";
4449 regmatch.regprog = vim_regcomp(s2,
4450 RE_MAGIC + RE_STRING);
4451 regmatch.rm_ic = ic;
4452 if (regmatch.regprog != NULL)
4454 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4455 vim_free(regmatch.regprog);
4456 if (type == TYPE_NOMATCH)
4457 n1 = !n1;
4459 p_cpo = save_cpo;
4460 break;
4462 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4465 clear_tv(rettv);
4466 clear_tv(&var2);
4467 rettv->v_type = VAR_NUMBER;
4468 rettv->vval.v_number = n1;
4472 return OK;
4476 * Handle fourth level expression:
4477 * + number addition
4478 * - number subtraction
4479 * . string concatenation
4481 * "arg" must point to the first non-white of the expression.
4482 * "arg" is advanced to the next non-white after the recognized expression.
4484 * Return OK or FAIL.
4486 static int
4487 eval5(arg, rettv, evaluate)
4488 char_u **arg;
4489 typval_T *rettv;
4490 int evaluate;
4492 typval_T var2;
4493 typval_T var3;
4494 int op;
4495 long n1, n2;
4496 #ifdef FEAT_FLOAT
4497 float_T f1 = 0, f2 = 0;
4498 #endif
4499 char_u *s1, *s2;
4500 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4501 char_u *p;
4504 * Get the first variable.
4506 if (eval6(arg, rettv, evaluate, FALSE) == FAIL)
4507 return FAIL;
4510 * Repeat computing, until no '+', '-' or '.' is following.
4512 for (;;)
4514 op = **arg;
4515 if (op != '+' && op != '-' && op != '.')
4516 break;
4518 if ((op != '+' || rettv->v_type != VAR_LIST)
4519 #ifdef FEAT_FLOAT
4520 && (op == '.' || rettv->v_type != VAR_FLOAT)
4521 #endif
4524 /* For "list + ...", an illegal use of the first operand as
4525 * a number cannot be determined before evaluating the 2nd
4526 * operand: if this is also a list, all is ok.
4527 * For "something . ...", "something - ..." or "non-list + ...",
4528 * we know that the first operand needs to be a string or number
4529 * without evaluating the 2nd operand. So check before to avoid
4530 * side effects after an error. */
4531 if (evaluate && get_tv_string_chk(rettv) == NULL)
4533 clear_tv(rettv);
4534 return FAIL;
4539 * Get the second variable.
4541 *arg = skipwhite(*arg + 1);
4542 if (eval6(arg, &var2, evaluate, op == '.') == FAIL)
4544 clear_tv(rettv);
4545 return FAIL;
4548 if (evaluate)
4551 * Compute the result.
4553 if (op == '.')
4555 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4556 s2 = get_tv_string_buf_chk(&var2, buf2);
4557 if (s2 == NULL) /* type error ? */
4559 clear_tv(rettv);
4560 clear_tv(&var2);
4561 return FAIL;
4563 p = concat_str(s1, s2);
4564 clear_tv(rettv);
4565 rettv->v_type = VAR_STRING;
4566 rettv->vval.v_string = p;
4568 else if (op == '+' && rettv->v_type == VAR_LIST
4569 && var2.v_type == VAR_LIST)
4571 /* concatenate Lists */
4572 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4573 &var3) == FAIL)
4575 clear_tv(rettv);
4576 clear_tv(&var2);
4577 return FAIL;
4579 clear_tv(rettv);
4580 *rettv = var3;
4582 else
4584 int error = FALSE;
4586 #ifdef FEAT_FLOAT
4587 if (rettv->v_type == VAR_FLOAT)
4589 f1 = rettv->vval.v_float;
4590 n1 = 0;
4592 else
4593 #endif
4595 n1 = get_tv_number_chk(rettv, &error);
4596 if (error)
4598 /* This can only happen for "list + non-list". For
4599 * "non-list + ..." or "something - ...", we returned
4600 * before evaluating the 2nd operand. */
4601 clear_tv(rettv);
4602 return FAIL;
4604 #ifdef FEAT_FLOAT
4605 if (var2.v_type == VAR_FLOAT)
4606 f1 = n1;
4607 #endif
4609 #ifdef FEAT_FLOAT
4610 if (var2.v_type == VAR_FLOAT)
4612 f2 = var2.vval.v_float;
4613 n2 = 0;
4615 else
4616 #endif
4618 n2 = get_tv_number_chk(&var2, &error);
4619 if (error)
4621 clear_tv(rettv);
4622 clear_tv(&var2);
4623 return FAIL;
4625 #ifdef FEAT_FLOAT
4626 if (rettv->v_type == VAR_FLOAT)
4627 f2 = n2;
4628 #endif
4630 clear_tv(rettv);
4632 #ifdef FEAT_FLOAT
4633 /* If there is a float on either side the result is a float. */
4634 if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4636 if (op == '+')
4637 f1 = f1 + f2;
4638 else
4639 f1 = f1 - f2;
4640 rettv->v_type = VAR_FLOAT;
4641 rettv->vval.v_float = f1;
4643 else
4644 #endif
4646 if (op == '+')
4647 n1 = n1 + n2;
4648 else
4649 n1 = n1 - n2;
4650 rettv->v_type = VAR_NUMBER;
4651 rettv->vval.v_number = n1;
4654 clear_tv(&var2);
4657 return OK;
4661 * Handle fifth level expression:
4662 * * number multiplication
4663 * / number division
4664 * % number modulo
4666 * "arg" must point to the first non-white of the expression.
4667 * "arg" is advanced to the next non-white after the recognized expression.
4669 * Return OK or FAIL.
4671 static int
4672 eval6(arg, rettv, evaluate, want_string)
4673 char_u **arg;
4674 typval_T *rettv;
4675 int evaluate;
4676 int want_string; /* after "." operator */
4678 typval_T var2;
4679 int op;
4680 long n1, n2;
4681 #ifdef FEAT_FLOAT
4682 int use_float = FALSE;
4683 float_T f1 = 0, f2;
4684 #endif
4685 int error = FALSE;
4688 * Get the first variable.
4690 if (eval7(arg, rettv, evaluate, want_string) == FAIL)
4691 return FAIL;
4694 * Repeat computing, until no '*', '/' or '%' is following.
4696 for (;;)
4698 op = **arg;
4699 if (op != '*' && op != '/' && op != '%')
4700 break;
4702 if (evaluate)
4704 #ifdef FEAT_FLOAT
4705 if (rettv->v_type == VAR_FLOAT)
4707 f1 = rettv->vval.v_float;
4708 use_float = TRUE;
4709 n1 = 0;
4711 else
4712 #endif
4713 n1 = get_tv_number_chk(rettv, &error);
4714 clear_tv(rettv);
4715 if (error)
4716 return FAIL;
4718 else
4719 n1 = 0;
4722 * Get the second variable.
4724 *arg = skipwhite(*arg + 1);
4725 if (eval7(arg, &var2, evaluate, FALSE) == FAIL)
4726 return FAIL;
4728 if (evaluate)
4730 #ifdef FEAT_FLOAT
4731 if (var2.v_type == VAR_FLOAT)
4733 if (!use_float)
4735 f1 = n1;
4736 use_float = TRUE;
4738 f2 = var2.vval.v_float;
4739 n2 = 0;
4741 else
4742 #endif
4744 n2 = get_tv_number_chk(&var2, &error);
4745 clear_tv(&var2);
4746 if (error)
4747 return FAIL;
4748 #ifdef FEAT_FLOAT
4749 if (use_float)
4750 f2 = n2;
4751 #endif
4755 * Compute the result.
4756 * When either side is a float the result is a float.
4758 #ifdef FEAT_FLOAT
4759 if (use_float)
4761 if (op == '*')
4762 f1 = f1 * f2;
4763 else if (op == '/')
4765 /* We rely on the floating point library to handle divide
4766 * by zero to result in "inf" and not a crash. */
4767 f1 = f1 / f2;
4769 else
4771 EMSG(_("E804: Cannot use '%' with Float"));
4772 return FAIL;
4774 rettv->v_type = VAR_FLOAT;
4775 rettv->vval.v_float = f1;
4777 else
4778 #endif
4780 if (op == '*')
4781 n1 = n1 * n2;
4782 else if (op == '/')
4784 if (n2 == 0) /* give an error message? */
4786 if (n1 == 0)
4787 n1 = -0x7fffffffL - 1L; /* similar to NaN */
4788 else if (n1 < 0)
4789 n1 = -0x7fffffffL;
4790 else
4791 n1 = 0x7fffffffL;
4793 else
4794 n1 = n1 / n2;
4796 else
4798 if (n2 == 0) /* give an error message? */
4799 n1 = 0;
4800 else
4801 n1 = n1 % n2;
4803 rettv->v_type = VAR_NUMBER;
4804 rettv->vval.v_number = n1;
4809 return OK;
4813 * Handle sixth level expression:
4814 * number number constant
4815 * "string" string constant
4816 * 'string' literal string constant
4817 * &option-name option value
4818 * @r register contents
4819 * identifier variable value
4820 * function() function call
4821 * $VAR environment variable
4822 * (expression) nested expression
4823 * [expr, expr] List
4824 * {key: val, key: val} Dictionary
4826 * Also handle:
4827 * ! in front logical NOT
4828 * - in front unary minus
4829 * + in front unary plus (ignored)
4830 * trailing [] subscript in String or List
4831 * trailing .name entry in Dictionary
4833 * "arg" must point to the first non-white of the expression.
4834 * "arg" is advanced to the next non-white after the recognized expression.
4836 * Return OK or FAIL.
4838 static int
4839 eval7(arg, rettv, evaluate, want_string)
4840 char_u **arg;
4841 typval_T *rettv;
4842 int evaluate;
4843 int want_string; /* after "." operator */
4845 long n;
4846 int len;
4847 char_u *s;
4848 char_u *start_leader, *end_leader;
4849 int ret = OK;
4850 char_u *alias;
4853 * Initialise variable so that clear_tv() can't mistake this for a
4854 * string and free a string that isn't there.
4856 rettv->v_type = VAR_UNKNOWN;
4859 * Skip '!' and '-' characters. They are handled later.
4861 start_leader = *arg;
4862 while (**arg == '!' || **arg == '-' || **arg == '+')
4863 *arg = skipwhite(*arg + 1);
4864 end_leader = *arg;
4866 switch (**arg)
4869 * Number constant.
4871 case '0':
4872 case '1':
4873 case '2':
4874 case '3':
4875 case '4':
4876 case '5':
4877 case '6':
4878 case '7':
4879 case '8':
4880 case '9':
4882 #ifdef FEAT_FLOAT
4883 char_u *p = skipdigits(*arg + 1);
4884 int get_float = FALSE;
4886 /* We accept a float when the format matches
4887 * "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?". This is very
4888 * strict to avoid backwards compatibility problems.
4889 * Don't look for a float after the "." operator, so that
4890 * ":let vers = 1.2.3" doesn't fail. */
4891 if (!want_string && p[0] == '.' && vim_isdigit(p[1]))
4893 get_float = TRUE;
4894 p = skipdigits(p + 2);
4895 if (*p == 'e' || *p == 'E')
4897 ++p;
4898 if (*p == '-' || *p == '+')
4899 ++p;
4900 if (!vim_isdigit(*p))
4901 get_float = FALSE;
4902 else
4903 p = skipdigits(p + 1);
4905 if (ASCII_ISALPHA(*p) || *p == '.')
4906 get_float = FALSE;
4908 if (get_float)
4910 float_T f;
4912 *arg += string2float(*arg, &f);
4913 if (evaluate)
4915 rettv->v_type = VAR_FLOAT;
4916 rettv->vval.v_float = f;
4919 else
4920 #endif
4922 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4923 *arg += len;
4924 if (evaluate)
4926 rettv->v_type = VAR_NUMBER;
4927 rettv->vval.v_number = n;
4930 break;
4934 * String constant: "string".
4936 case '"': ret = get_string_tv(arg, rettv, evaluate);
4937 break;
4940 * Literal string constant: 'str''ing'.
4942 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
4943 break;
4946 * List: [expr, expr]
4948 case '[': ret = get_list_tv(arg, rettv, evaluate);
4949 break;
4952 * Dictionary: {key: val, key: val}
4954 case '{': ret = get_dict_tv(arg, rettv, evaluate);
4955 break;
4958 * Option value: &name
4960 case '&': ret = get_option_tv(arg, rettv, evaluate);
4961 break;
4964 * Environment variable: $VAR.
4966 case '$': ret = get_env_tv(arg, rettv, evaluate);
4967 break;
4970 * Register contents: @r.
4972 case '@': ++*arg;
4973 if (evaluate)
4975 rettv->v_type = VAR_STRING;
4976 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4978 if (**arg != NUL)
4979 ++*arg;
4980 break;
4983 * nested expression: (expression).
4985 case '(': *arg = skipwhite(*arg + 1);
4986 ret = eval1(arg, rettv, evaluate); /* recursive! */
4987 if (**arg == ')')
4988 ++*arg;
4989 else if (ret == OK)
4991 EMSG(_("E110: Missing ')'"));
4992 clear_tv(rettv);
4993 ret = FAIL;
4995 break;
4997 default: ret = NOTDONE;
4998 break;
5001 if (ret == NOTDONE)
5004 * Must be a variable or function name.
5005 * Can also be a curly-braces kind of name: {expr}.
5007 s = *arg;
5008 len = get_name_len(arg, &alias, evaluate, TRUE);
5009 if (alias != NULL)
5010 s = alias;
5012 if (len <= 0)
5013 ret = FAIL;
5014 else
5016 if (**arg == '(') /* recursive! */
5018 /* If "s" is the name of a variable of type VAR_FUNC
5019 * use its contents. */
5020 s = deref_func_name(s, &len);
5022 /* Invoke the function. */
5023 ret = get_func_tv(s, len, rettv, arg,
5024 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
5025 &len, evaluate, NULL);
5026 /* Stop the expression evaluation when immediately
5027 * aborting on error, or when an interrupt occurred or
5028 * an exception was thrown but not caught. */
5029 if (aborting())
5031 if (ret == OK)
5032 clear_tv(rettv);
5033 ret = FAIL;
5036 else if (evaluate)
5037 ret = get_var_tv(s, len, rettv, TRUE);
5038 else
5039 ret = OK;
5042 if (alias != NULL)
5043 vim_free(alias);
5046 *arg = skipwhite(*arg);
5048 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
5049 * expr(expr). */
5050 if (ret == OK)
5051 ret = handle_subscript(arg, rettv, evaluate, TRUE);
5054 * Apply logical NOT and unary '-', from right to left, ignore '+'.
5056 if (ret == OK && evaluate && end_leader > start_leader)
5058 int error = FALSE;
5059 int val = 0;
5060 #ifdef FEAT_FLOAT
5061 float_T f = 0.0;
5063 if (rettv->v_type == VAR_FLOAT)
5064 f = rettv->vval.v_float;
5065 else
5066 #endif
5067 val = get_tv_number_chk(rettv, &error);
5068 if (error)
5070 clear_tv(rettv);
5071 ret = FAIL;
5073 else
5075 while (end_leader > start_leader)
5077 --end_leader;
5078 if (*end_leader == '!')
5080 #ifdef FEAT_FLOAT
5081 if (rettv->v_type == VAR_FLOAT)
5082 f = !f;
5083 else
5084 #endif
5085 val = !val;
5087 else if (*end_leader == '-')
5089 #ifdef FEAT_FLOAT
5090 if (rettv->v_type == VAR_FLOAT)
5091 f = -f;
5092 else
5093 #endif
5094 val = -val;
5097 #ifdef FEAT_FLOAT
5098 if (rettv->v_type == VAR_FLOAT)
5100 clear_tv(rettv);
5101 rettv->vval.v_float = f;
5103 else
5104 #endif
5106 clear_tv(rettv);
5107 rettv->v_type = VAR_NUMBER;
5108 rettv->vval.v_number = val;
5113 return ret;
5117 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
5118 * "*arg" points to the '[' or '.'.
5119 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
5121 static int
5122 eval_index(arg, rettv, evaluate, verbose)
5123 char_u **arg;
5124 typval_T *rettv;
5125 int evaluate;
5126 int verbose; /* give error messages */
5128 int empty1 = FALSE, empty2 = FALSE;
5129 typval_T var1, var2;
5130 long n1, n2 = 0;
5131 long len = -1;
5132 int range = FALSE;
5133 char_u *s;
5134 char_u *key = NULL;
5136 if (rettv->v_type == VAR_FUNC
5137 #ifdef FEAT_FLOAT
5138 || rettv->v_type == VAR_FLOAT
5139 #endif
5142 if (verbose)
5143 EMSG(_("E695: Cannot index a Funcref"));
5144 return FAIL;
5147 if (**arg == '.')
5150 * dict.name
5152 key = *arg + 1;
5153 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
5155 if (len == 0)
5156 return FAIL;
5157 *arg = skipwhite(key + len);
5159 else
5162 * something[idx]
5164 * Get the (first) variable from inside the [].
5166 *arg = skipwhite(*arg + 1);
5167 if (**arg == ':')
5168 empty1 = TRUE;
5169 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
5170 return FAIL;
5171 else if (evaluate && get_tv_string_chk(&var1) == NULL)
5173 /* not a number or string */
5174 clear_tv(&var1);
5175 return FAIL;
5179 * Get the second variable from inside the [:].
5181 if (**arg == ':')
5183 range = TRUE;
5184 *arg = skipwhite(*arg + 1);
5185 if (**arg == ']')
5186 empty2 = TRUE;
5187 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
5189 if (!empty1)
5190 clear_tv(&var1);
5191 return FAIL;
5193 else if (evaluate && get_tv_string_chk(&var2) == NULL)
5195 /* not a number or string */
5196 if (!empty1)
5197 clear_tv(&var1);
5198 clear_tv(&var2);
5199 return FAIL;
5203 /* Check for the ']'. */
5204 if (**arg != ']')
5206 if (verbose)
5207 EMSG(_(e_missbrac));
5208 clear_tv(&var1);
5209 if (range)
5210 clear_tv(&var2);
5211 return FAIL;
5213 *arg = skipwhite(*arg + 1); /* skip the ']' */
5216 if (evaluate)
5218 n1 = 0;
5219 if (!empty1 && rettv->v_type != VAR_DICT)
5221 n1 = get_tv_number(&var1);
5222 clear_tv(&var1);
5224 if (range)
5226 if (empty2)
5227 n2 = -1;
5228 else
5230 n2 = get_tv_number(&var2);
5231 clear_tv(&var2);
5235 switch (rettv->v_type)
5237 case VAR_NUMBER:
5238 case VAR_STRING:
5239 s = get_tv_string(rettv);
5240 len = (long)STRLEN(s);
5241 if (range)
5243 /* The resulting variable is a substring. If the indexes
5244 * are out of range the result is empty. */
5245 if (n1 < 0)
5247 n1 = len + n1;
5248 if (n1 < 0)
5249 n1 = 0;
5251 if (n2 < 0)
5252 n2 = len + n2;
5253 else if (n2 >= len)
5254 n2 = len;
5255 if (n1 >= len || n2 < 0 || n1 > n2)
5256 s = NULL;
5257 else
5258 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
5260 else
5262 /* The resulting variable is a string of a single
5263 * character. If the index is too big or negative the
5264 * result is empty. */
5265 if (n1 >= len || n1 < 0)
5266 s = NULL;
5267 else
5268 s = vim_strnsave(s + n1, 1);
5270 clear_tv(rettv);
5271 rettv->v_type = VAR_STRING;
5272 rettv->vval.v_string = s;
5273 break;
5275 case VAR_LIST:
5276 len = list_len(rettv->vval.v_list);
5277 if (n1 < 0)
5278 n1 = len + n1;
5279 if (!empty1 && (n1 < 0 || n1 >= len))
5281 /* For a range we allow invalid values and return an empty
5282 * list. A list index out of range is an error. */
5283 if (!range)
5285 if (verbose)
5286 EMSGN(_(e_listidx), n1);
5287 return FAIL;
5289 n1 = len;
5291 if (range)
5293 list_T *l;
5294 listitem_T *item;
5296 if (n2 < 0)
5297 n2 = len + n2;
5298 else if (n2 >= len)
5299 n2 = len - 1;
5300 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
5301 n2 = -1;
5302 l = list_alloc();
5303 if (l == NULL)
5304 return FAIL;
5305 for (item = list_find(rettv->vval.v_list, n1);
5306 n1 <= n2; ++n1)
5308 if (list_append_tv(l, &item->li_tv) == FAIL)
5310 list_free(l, TRUE);
5311 return FAIL;
5313 item = item->li_next;
5315 clear_tv(rettv);
5316 rettv->v_type = VAR_LIST;
5317 rettv->vval.v_list = l;
5318 ++l->lv_refcount;
5320 else
5322 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
5323 clear_tv(rettv);
5324 *rettv = var1;
5326 break;
5328 case VAR_DICT:
5329 if (range)
5331 if (verbose)
5332 EMSG(_(e_dictrange));
5333 if (len == -1)
5334 clear_tv(&var1);
5335 return FAIL;
5338 dictitem_T *item;
5340 if (len == -1)
5342 key = get_tv_string(&var1);
5343 if (*key == NUL)
5345 if (verbose)
5346 EMSG(_(e_emptykey));
5347 clear_tv(&var1);
5348 return FAIL;
5352 item = dict_find(rettv->vval.v_dict, key, (int)len);
5354 if (item == NULL && verbose)
5355 EMSG2(_(e_dictkey), key);
5356 if (len == -1)
5357 clear_tv(&var1);
5358 if (item == NULL)
5359 return FAIL;
5361 copy_tv(&item->di_tv, &var1);
5362 clear_tv(rettv);
5363 *rettv = var1;
5365 break;
5369 return OK;
5373 * Get an option value.
5374 * "arg" points to the '&' or '+' before the option name.
5375 * "arg" is advanced to character after the option name.
5376 * Return OK or FAIL.
5378 static int
5379 get_option_tv(arg, rettv, evaluate)
5380 char_u **arg;
5381 typval_T *rettv; /* when NULL, only check if option exists */
5382 int evaluate;
5384 char_u *option_end;
5385 long numval;
5386 char_u *stringval;
5387 int opt_type;
5388 int c;
5389 int working = (**arg == '+'); /* has("+option") */
5390 int ret = OK;
5391 int opt_flags;
5394 * Isolate the option name and find its value.
5396 option_end = find_option_end(arg, &opt_flags);
5397 if (option_end == NULL)
5399 if (rettv != NULL)
5400 EMSG2(_("E112: Option name missing: %s"), *arg);
5401 return FAIL;
5404 if (!evaluate)
5406 *arg = option_end;
5407 return OK;
5410 c = *option_end;
5411 *option_end = NUL;
5412 opt_type = get_option_value(*arg, &numval,
5413 rettv == NULL ? NULL : &stringval, opt_flags);
5415 if (opt_type == -3) /* invalid name */
5417 if (rettv != NULL)
5418 EMSG2(_("E113: Unknown option: %s"), *arg);
5419 ret = FAIL;
5421 else if (rettv != NULL)
5423 if (opt_type == -2) /* hidden string option */
5425 rettv->v_type = VAR_STRING;
5426 rettv->vval.v_string = NULL;
5428 else if (opt_type == -1) /* hidden number option */
5430 rettv->v_type = VAR_NUMBER;
5431 rettv->vval.v_number = 0;
5433 else if (opt_type == 1) /* number option */
5435 rettv->v_type = VAR_NUMBER;
5436 rettv->vval.v_number = numval;
5438 else /* string option */
5440 rettv->v_type = VAR_STRING;
5441 rettv->vval.v_string = stringval;
5444 else if (working && (opt_type == -2 || opt_type == -1))
5445 ret = FAIL;
5447 *option_end = c; /* put back for error messages */
5448 *arg = option_end;
5450 return ret;
5454 * Allocate a variable for a string constant.
5455 * Return OK or FAIL.
5457 static int
5458 get_string_tv(arg, rettv, evaluate)
5459 char_u **arg;
5460 typval_T *rettv;
5461 int evaluate;
5463 char_u *p;
5464 char_u *name;
5465 int extra = 0;
5468 * Find the end of the string, skipping backslashed characters.
5470 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5472 if (*p == '\\' && p[1] != NUL)
5474 ++p;
5475 /* A "\<x>" form occupies at least 4 characters, and produces up
5476 * to 6 characters: reserve space for 2 extra */
5477 if (*p == '<')
5478 extra += 2;
5482 if (*p != '"')
5484 EMSG2(_("E114: Missing quote: %s"), *arg);
5485 return FAIL;
5488 /* If only parsing, set *arg and return here */
5489 if (!evaluate)
5491 *arg = p + 1;
5492 return OK;
5496 * Copy the string into allocated memory, handling backslashed
5497 * characters.
5499 name = alloc((unsigned)(p - *arg + extra));
5500 if (name == NULL)
5501 return FAIL;
5502 rettv->v_type = VAR_STRING;
5503 rettv->vval.v_string = name;
5505 for (p = *arg + 1; *p != NUL && *p != '"'; )
5507 if (*p == '\\')
5509 switch (*++p)
5511 case 'b': *name++ = BS; ++p; break;
5512 case 'e': *name++ = ESC; ++p; break;
5513 case 'f': *name++ = FF; ++p; break;
5514 case 'n': *name++ = NL; ++p; break;
5515 case 'r': *name++ = CAR; ++p; break;
5516 case 't': *name++ = TAB; ++p; break;
5518 case 'X': /* hex: "\x1", "\x12" */
5519 case 'x':
5520 case 'u': /* Unicode: "\u0023" */
5521 case 'U':
5522 if (vim_isxdigit(p[1]))
5524 int n, nr;
5525 int c = toupper(*p);
5527 if (c == 'X')
5528 n = 2;
5529 else
5530 n = 4;
5531 nr = 0;
5532 while (--n >= 0 && vim_isxdigit(p[1]))
5534 ++p;
5535 nr = (nr << 4) + hex2nr(*p);
5537 ++p;
5538 #ifdef FEAT_MBYTE
5539 /* For "\u" store the number according to
5540 * 'encoding'. */
5541 if (c != 'X')
5542 name += (*mb_char2bytes)(nr, name);
5543 else
5544 #endif
5545 *name++ = nr;
5547 break;
5549 /* octal: "\1", "\12", "\123" */
5550 case '0':
5551 case '1':
5552 case '2':
5553 case '3':
5554 case '4':
5555 case '5':
5556 case '6':
5557 case '7': *name = *p++ - '0';
5558 if (*p >= '0' && *p <= '7')
5560 *name = (*name << 3) + *p++ - '0';
5561 if (*p >= '0' && *p <= '7')
5562 *name = (*name << 3) + *p++ - '0';
5564 ++name;
5565 break;
5567 /* Special key, e.g.: "\<C-W>" */
5568 case '<': extra = trans_special(&p, name, TRUE);
5569 if (extra != 0)
5571 name += extra;
5572 break;
5574 /* FALLTHROUGH */
5576 default: MB_COPY_CHAR(p, name);
5577 break;
5580 else
5581 MB_COPY_CHAR(p, name);
5584 *name = NUL;
5585 *arg = p + 1;
5587 return OK;
5591 * Allocate a variable for a 'str''ing' constant.
5592 * Return OK or FAIL.
5594 static int
5595 get_lit_string_tv(arg, rettv, evaluate)
5596 char_u **arg;
5597 typval_T *rettv;
5598 int evaluate;
5600 char_u *p;
5601 char_u *str;
5602 int reduce = 0;
5605 * Find the end of the string, skipping ''.
5607 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5609 if (*p == '\'')
5611 if (p[1] != '\'')
5612 break;
5613 ++reduce;
5614 ++p;
5618 if (*p != '\'')
5620 EMSG2(_("E115: Missing quote: %s"), *arg);
5621 return FAIL;
5624 /* If only parsing return after setting "*arg" */
5625 if (!evaluate)
5627 *arg = p + 1;
5628 return OK;
5632 * Copy the string into allocated memory, handling '' to ' reduction.
5634 str = alloc((unsigned)((p - *arg) - reduce));
5635 if (str == NULL)
5636 return FAIL;
5637 rettv->v_type = VAR_STRING;
5638 rettv->vval.v_string = str;
5640 for (p = *arg + 1; *p != NUL; )
5642 if (*p == '\'')
5644 if (p[1] != '\'')
5645 break;
5646 ++p;
5648 MB_COPY_CHAR(p, str);
5650 *str = NUL;
5651 *arg = p + 1;
5653 return OK;
5657 * Allocate a variable for a List and fill it from "*arg".
5658 * Return OK or FAIL.
5660 static int
5661 get_list_tv(arg, rettv, evaluate)
5662 char_u **arg;
5663 typval_T *rettv;
5664 int evaluate;
5666 list_T *l = NULL;
5667 typval_T tv;
5668 listitem_T *item;
5670 if (evaluate)
5672 l = list_alloc();
5673 if (l == NULL)
5674 return FAIL;
5677 *arg = skipwhite(*arg + 1);
5678 while (**arg != ']' && **arg != NUL)
5680 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5681 goto failret;
5682 if (evaluate)
5684 item = listitem_alloc();
5685 if (item != NULL)
5687 item->li_tv = tv;
5688 item->li_tv.v_lock = 0;
5689 list_append(l, item);
5691 else
5692 clear_tv(&tv);
5695 if (**arg == ']')
5696 break;
5697 if (**arg != ',')
5699 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5700 goto failret;
5702 *arg = skipwhite(*arg + 1);
5705 if (**arg != ']')
5707 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5708 failret:
5709 if (evaluate)
5710 list_free(l, TRUE);
5711 return FAIL;
5714 *arg = skipwhite(*arg + 1);
5715 if (evaluate)
5717 rettv->v_type = VAR_LIST;
5718 rettv->vval.v_list = l;
5719 ++l->lv_refcount;
5722 return OK;
5726 * Allocate an empty header for a list.
5727 * Caller should take care of the reference count.
5729 list_T *
5730 list_alloc()
5732 list_T *l;
5734 l = (list_T *)alloc_clear(sizeof(list_T));
5735 if (l != NULL)
5737 /* Prepend the list to the list of lists for garbage collection. */
5738 if (first_list != NULL)
5739 first_list->lv_used_prev = l;
5740 l->lv_used_prev = NULL;
5741 l->lv_used_next = first_list;
5742 first_list = l;
5744 return l;
5748 * Allocate an empty list for a return value.
5749 * Returns OK or FAIL.
5751 static int
5752 rettv_list_alloc(rettv)
5753 typval_T *rettv;
5755 list_T *l = list_alloc();
5757 if (l == NULL)
5758 return FAIL;
5760 rettv->vval.v_list = l;
5761 rettv->v_type = VAR_LIST;
5762 ++l->lv_refcount;
5763 return OK;
5767 * Unreference a list: decrement the reference count and free it when it
5768 * becomes zero.
5770 void
5771 list_unref(l)
5772 list_T *l;
5774 if (l != NULL && --l->lv_refcount <= 0)
5775 list_free(l, TRUE);
5779 * Free a list, including all items it points to.
5780 * Ignores the reference count.
5782 void
5783 list_free(l, recurse)
5784 list_T *l;
5785 int recurse; /* Free Lists and Dictionaries recursively. */
5787 listitem_T *item;
5789 /* Remove the list from the list of lists for garbage collection. */
5790 if (l->lv_used_prev == NULL)
5791 first_list = l->lv_used_next;
5792 else
5793 l->lv_used_prev->lv_used_next = l->lv_used_next;
5794 if (l->lv_used_next != NULL)
5795 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5797 for (item = l->lv_first; item != NULL; item = l->lv_first)
5799 /* Remove the item before deleting it. */
5800 l->lv_first = item->li_next;
5801 if (recurse || (item->li_tv.v_type != VAR_LIST
5802 && item->li_tv.v_type != VAR_DICT))
5803 clear_tv(&item->li_tv);
5804 vim_free(item);
5806 vim_free(l);
5810 * Allocate a list item.
5812 static listitem_T *
5813 listitem_alloc()
5815 return (listitem_T *)alloc(sizeof(listitem_T));
5819 * Free a list item. Also clears the value. Does not notify watchers.
5821 static void
5822 listitem_free(item)
5823 listitem_T *item;
5825 clear_tv(&item->li_tv);
5826 vim_free(item);
5830 * Remove a list item from a List and free it. Also clears the value.
5832 static void
5833 listitem_remove(l, item)
5834 list_T *l;
5835 listitem_T *item;
5837 list_remove(l, item, item);
5838 listitem_free(item);
5842 * Get the number of items in a list.
5844 static long
5845 list_len(l)
5846 list_T *l;
5848 if (l == NULL)
5849 return 0L;
5850 return l->lv_len;
5854 * Return TRUE when two lists have exactly the same values.
5856 static int
5857 list_equal(l1, l2, ic)
5858 list_T *l1;
5859 list_T *l2;
5860 int ic; /* ignore case for strings */
5862 listitem_T *item1, *item2;
5864 if (l1 == NULL || l2 == NULL)
5865 return FALSE;
5866 if (l1 == l2)
5867 return TRUE;
5868 if (list_len(l1) != list_len(l2))
5869 return FALSE;
5871 for (item1 = l1->lv_first, item2 = l2->lv_first;
5872 item1 != NULL && item2 != NULL;
5873 item1 = item1->li_next, item2 = item2->li_next)
5874 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5875 return FALSE;
5876 return item1 == NULL && item2 == NULL;
5879 #if defined(FEAT_PYTHON) || defined(PROTO)
5881 * Return the dictitem that an entry in a hashtable points to.
5883 dictitem_T *
5884 dict_lookup(hi)
5885 hashitem_T *hi;
5887 return HI2DI(hi);
5889 #endif
5892 * Return TRUE when two dictionaries have exactly the same key/values.
5894 static int
5895 dict_equal(d1, d2, ic)
5896 dict_T *d1;
5897 dict_T *d2;
5898 int ic; /* ignore case for strings */
5900 hashitem_T *hi;
5901 dictitem_T *item2;
5902 int todo;
5904 if (d1 == NULL || d2 == NULL)
5905 return FALSE;
5906 if (d1 == d2)
5907 return TRUE;
5908 if (dict_len(d1) != dict_len(d2))
5909 return FALSE;
5911 todo = (int)d1->dv_hashtab.ht_used;
5912 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5914 if (!HASHITEM_EMPTY(hi))
5916 item2 = dict_find(d2, hi->hi_key, -1);
5917 if (item2 == NULL)
5918 return FALSE;
5919 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5920 return FALSE;
5921 --todo;
5924 return TRUE;
5928 * Return TRUE if "tv1" and "tv2" have the same value.
5929 * Compares the items just like "==" would compare them, but strings and
5930 * numbers are different. Floats and numbers are also different.
5932 static int
5933 tv_equal(tv1, tv2, ic)
5934 typval_T *tv1;
5935 typval_T *tv2;
5936 int ic; /* ignore case */
5938 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5939 char_u *s1, *s2;
5940 static int recursive = 0; /* cach recursive loops */
5941 int r;
5943 if (tv1->v_type != tv2->v_type)
5944 return FALSE;
5945 /* Catch lists and dicts that have an endless loop by limiting
5946 * recursiveness to 1000. We guess they are equal then. */
5947 if (recursive >= 1000)
5948 return TRUE;
5950 switch (tv1->v_type)
5952 case VAR_LIST:
5953 ++recursive;
5954 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5955 --recursive;
5956 return r;
5958 case VAR_DICT:
5959 ++recursive;
5960 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5961 --recursive;
5962 return r;
5964 case VAR_FUNC:
5965 return (tv1->vval.v_string != NULL
5966 && tv2->vval.v_string != NULL
5967 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5969 case VAR_NUMBER:
5970 return tv1->vval.v_number == tv2->vval.v_number;
5972 #ifdef FEAT_FLOAT
5973 case VAR_FLOAT:
5974 return tv1->vval.v_float == tv2->vval.v_float;
5975 #endif
5977 case VAR_STRING:
5978 s1 = get_tv_string_buf(tv1, buf1);
5979 s2 = get_tv_string_buf(tv2, buf2);
5980 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5983 EMSG2(_(e_intern2), "tv_equal()");
5984 return TRUE;
5988 * Locate item with index "n" in list "l" and return it.
5989 * A negative index is counted from the end; -1 is the last item.
5990 * Returns NULL when "n" is out of range.
5992 static listitem_T *
5993 list_find(l, n)
5994 list_T *l;
5995 long n;
5997 listitem_T *item;
5998 long idx;
6000 if (l == NULL)
6001 return NULL;
6003 /* Negative index is relative to the end. */
6004 if (n < 0)
6005 n = l->lv_len + n;
6007 /* Check for index out of range. */
6008 if (n < 0 || n >= l->lv_len)
6009 return NULL;
6011 /* When there is a cached index may start search from there. */
6012 if (l->lv_idx_item != NULL)
6014 if (n < l->lv_idx / 2)
6016 /* closest to the start of the list */
6017 item = l->lv_first;
6018 idx = 0;
6020 else if (n > (l->lv_idx + l->lv_len) / 2)
6022 /* closest to the end of the list */
6023 item = l->lv_last;
6024 idx = l->lv_len - 1;
6026 else
6028 /* closest to the cached index */
6029 item = l->lv_idx_item;
6030 idx = l->lv_idx;
6033 else
6035 if (n < l->lv_len / 2)
6037 /* closest to the start of the list */
6038 item = l->lv_first;
6039 idx = 0;
6041 else
6043 /* closest to the end of the list */
6044 item = l->lv_last;
6045 idx = l->lv_len - 1;
6049 while (n > idx)
6051 /* search forward */
6052 item = item->li_next;
6053 ++idx;
6055 while (n < idx)
6057 /* search backward */
6058 item = item->li_prev;
6059 --idx;
6062 /* cache the used index */
6063 l->lv_idx = idx;
6064 l->lv_idx_item = item;
6066 return item;
6070 * Get list item "l[idx]" as a number.
6072 static long
6073 list_find_nr(l, idx, errorp)
6074 list_T *l;
6075 long idx;
6076 int *errorp; /* set to TRUE when something wrong */
6078 listitem_T *li;
6080 li = list_find(l, idx);
6081 if (li == NULL)
6083 if (errorp != NULL)
6084 *errorp = TRUE;
6085 return -1L;
6087 return get_tv_number_chk(&li->li_tv, errorp);
6091 * Get list item "l[idx - 1]" as a string. Returns NULL for failure.
6093 char_u *
6094 list_find_str(l, idx)
6095 list_T *l;
6096 long idx;
6098 listitem_T *li;
6100 li = list_find(l, idx - 1);
6101 if (li == NULL)
6103 EMSGN(_(e_listidx), idx);
6104 return NULL;
6106 return get_tv_string(&li->li_tv);
6110 * Locate "item" list "l" and return its index.
6111 * Returns -1 when "item" is not in the list.
6113 static long
6114 list_idx_of_item(l, item)
6115 list_T *l;
6116 listitem_T *item;
6118 long idx = 0;
6119 listitem_T *li;
6121 if (l == NULL)
6122 return -1;
6123 idx = 0;
6124 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
6125 ++idx;
6126 if (li == NULL)
6127 return -1;
6128 return idx;
6132 * Append item "item" to the end of list "l".
6134 static void
6135 list_append(l, item)
6136 list_T *l;
6137 listitem_T *item;
6139 if (l->lv_last == NULL)
6141 /* empty list */
6142 l->lv_first = item;
6143 l->lv_last = item;
6144 item->li_prev = NULL;
6146 else
6148 l->lv_last->li_next = item;
6149 item->li_prev = l->lv_last;
6150 l->lv_last = item;
6152 ++l->lv_len;
6153 item->li_next = NULL;
6157 * Append typval_T "tv" to the end of list "l".
6158 * Return FAIL when out of memory.
6160 static int
6161 list_append_tv(l, tv)
6162 list_T *l;
6163 typval_T *tv;
6165 listitem_T *li = listitem_alloc();
6167 if (li == NULL)
6168 return FAIL;
6169 copy_tv(tv, &li->li_tv);
6170 list_append(l, li);
6171 return OK;
6175 * Add a dictionary to a list. Used by getqflist().
6176 * Return FAIL when out of memory.
6179 list_append_dict(list, dict)
6180 list_T *list;
6181 dict_T *dict;
6183 listitem_T *li = listitem_alloc();
6185 if (li == NULL)
6186 return FAIL;
6187 li->li_tv.v_type = VAR_DICT;
6188 li->li_tv.v_lock = 0;
6189 li->li_tv.vval.v_dict = dict;
6190 list_append(list, li);
6191 ++dict->dv_refcount;
6192 return OK;
6196 * Make a copy of "str" and append it as an item to list "l".
6197 * When "len" >= 0 use "str[len]".
6198 * Returns FAIL when out of memory.
6201 list_append_string(l, str, len)
6202 list_T *l;
6203 char_u *str;
6204 int len;
6206 listitem_T *li = listitem_alloc();
6208 if (li == NULL)
6209 return FAIL;
6210 list_append(l, li);
6211 li->li_tv.v_type = VAR_STRING;
6212 li->li_tv.v_lock = 0;
6213 if (str == NULL)
6214 li->li_tv.vval.v_string = NULL;
6215 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
6216 : vim_strsave(str))) == NULL)
6217 return FAIL;
6218 return OK;
6222 * Append "n" to list "l".
6223 * Returns FAIL when out of memory.
6225 static int
6226 list_append_number(l, n)
6227 list_T *l;
6228 varnumber_T n;
6230 listitem_T *li;
6232 li = listitem_alloc();
6233 if (li == NULL)
6234 return FAIL;
6235 li->li_tv.v_type = VAR_NUMBER;
6236 li->li_tv.v_lock = 0;
6237 li->li_tv.vval.v_number = n;
6238 list_append(l, li);
6239 return OK;
6243 * Insert typval_T "tv" in list "l" before "item".
6244 * If "item" is NULL append at the end.
6245 * Return FAIL when out of memory.
6247 static int
6248 list_insert_tv(l, tv, item)
6249 list_T *l;
6250 typval_T *tv;
6251 listitem_T *item;
6253 listitem_T *ni = listitem_alloc();
6255 if (ni == NULL)
6256 return FAIL;
6257 copy_tv(tv, &ni->li_tv);
6258 if (item == NULL)
6259 /* Append new item at end of list. */
6260 list_append(l, ni);
6261 else
6263 /* Insert new item before existing item. */
6264 ni->li_prev = item->li_prev;
6265 ni->li_next = item;
6266 if (item->li_prev == NULL)
6268 l->lv_first = ni;
6269 ++l->lv_idx;
6271 else
6273 item->li_prev->li_next = ni;
6274 l->lv_idx_item = NULL;
6276 item->li_prev = ni;
6277 ++l->lv_len;
6279 return OK;
6283 * Extend "l1" with "l2".
6284 * If "bef" is NULL append at the end, otherwise insert before this item.
6285 * Returns FAIL when out of memory.
6287 static int
6288 list_extend(l1, l2, bef)
6289 list_T *l1;
6290 list_T *l2;
6291 listitem_T *bef;
6293 listitem_T *item;
6294 int todo = l2->lv_len;
6296 /* We also quit the loop when we have inserted the original item count of
6297 * the list, avoid a hang when we extend a list with itself. */
6298 for (item = l2->lv_first; item != NULL && --todo >= 0; item = item->li_next)
6299 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
6300 return FAIL;
6301 return OK;
6305 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
6306 * Return FAIL when out of memory.
6308 static int
6309 list_concat(l1, l2, tv)
6310 list_T *l1;
6311 list_T *l2;
6312 typval_T *tv;
6314 list_T *l;
6316 if (l1 == NULL || l2 == NULL)
6317 return FAIL;
6319 /* make a copy of the first list. */
6320 l = list_copy(l1, FALSE, 0);
6321 if (l == NULL)
6322 return FAIL;
6323 tv->v_type = VAR_LIST;
6324 tv->vval.v_list = l;
6326 /* append all items from the second list */
6327 return list_extend(l, l2, NULL);
6331 * Make a copy of list "orig". Shallow if "deep" is FALSE.
6332 * The refcount of the new list is set to 1.
6333 * See item_copy() for "copyID".
6334 * Returns NULL when out of memory.
6336 static list_T *
6337 list_copy(orig, deep, copyID)
6338 list_T *orig;
6339 int deep;
6340 int copyID;
6342 list_T *copy;
6343 listitem_T *item;
6344 listitem_T *ni;
6346 if (orig == NULL)
6347 return NULL;
6349 copy = list_alloc();
6350 if (copy != NULL)
6352 if (copyID != 0)
6354 /* Do this before adding the items, because one of the items may
6355 * refer back to this list. */
6356 orig->lv_copyID = copyID;
6357 orig->lv_copylist = copy;
6359 for (item = orig->lv_first; item != NULL && !got_int;
6360 item = item->li_next)
6362 ni = listitem_alloc();
6363 if (ni == NULL)
6364 break;
6365 if (deep)
6367 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
6369 vim_free(ni);
6370 break;
6373 else
6374 copy_tv(&item->li_tv, &ni->li_tv);
6375 list_append(copy, ni);
6377 ++copy->lv_refcount;
6378 if (item != NULL)
6380 list_unref(copy);
6381 copy = NULL;
6385 return copy;
6389 * Remove items "item" to "item2" from list "l".
6390 * Does not free the listitem or the value!
6392 static void
6393 list_remove(l, item, item2)
6394 list_T *l;
6395 listitem_T *item;
6396 listitem_T *item2;
6398 listitem_T *ip;
6400 /* notify watchers */
6401 for (ip = item; ip != NULL; ip = ip->li_next)
6403 --l->lv_len;
6404 list_fix_watch(l, ip);
6405 if (ip == item2)
6406 break;
6409 if (item2->li_next == NULL)
6410 l->lv_last = item->li_prev;
6411 else
6412 item2->li_next->li_prev = item->li_prev;
6413 if (item->li_prev == NULL)
6414 l->lv_first = item2->li_next;
6415 else
6416 item->li_prev->li_next = item2->li_next;
6417 l->lv_idx_item = NULL;
6421 * Return an allocated string with the string representation of a list.
6422 * May return NULL.
6424 static char_u *
6425 list2string(tv, copyID)
6426 typval_T *tv;
6427 int copyID;
6429 garray_T ga;
6431 if (tv->vval.v_list == NULL)
6432 return NULL;
6433 ga_init2(&ga, (int)sizeof(char), 80);
6434 ga_append(&ga, '[');
6435 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6437 vim_free(ga.ga_data);
6438 return NULL;
6440 ga_append(&ga, ']');
6441 ga_append(&ga, NUL);
6442 return (char_u *)ga.ga_data;
6446 * Join list "l" into a string in "*gap", using separator "sep".
6447 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6448 * Return FAIL or OK.
6450 static int
6451 list_join(gap, l, sep, echo, copyID)
6452 garray_T *gap;
6453 list_T *l;
6454 char_u *sep;
6455 int echo;
6456 int copyID;
6458 int first = TRUE;
6459 char_u *tofree;
6460 char_u numbuf[NUMBUFLEN];
6461 listitem_T *item;
6462 char_u *s;
6464 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6466 if (first)
6467 first = FALSE;
6468 else
6469 ga_concat(gap, sep);
6471 if (echo)
6472 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6473 else
6474 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6475 if (s != NULL)
6476 ga_concat(gap, s);
6477 vim_free(tofree);
6478 if (s == NULL)
6479 return FAIL;
6481 return OK;
6485 * Garbage collection for lists and dictionaries.
6487 * We use reference counts to be able to free most items right away when they
6488 * are no longer used. But for composite items it's possible that it becomes
6489 * unused while the reference count is > 0: When there is a recursive
6490 * reference. Example:
6491 * :let l = [1, 2, 3]
6492 * :let d = {9: l}
6493 * :let l[1] = d
6495 * Since this is quite unusual we handle this with garbage collection: every
6496 * once in a while find out which lists and dicts are not referenced from any
6497 * variable.
6499 * Here is a good reference text about garbage collection (refers to Python
6500 * but it applies to all reference-counting mechanisms):
6501 * http://python.ca/nas/python/gc/
6505 * Do garbage collection for lists and dicts.
6506 * Return TRUE if some memory was freed.
6509 garbage_collect()
6511 dict_T *dd;
6512 list_T *ll;
6513 int copyID = ++current_copyID;
6514 buf_T *buf;
6515 win_T *wp;
6516 int i;
6517 funccall_T *fc, **pfc;
6518 int did_free = FALSE;
6519 #ifdef FEAT_WINDOWS
6520 tabpage_T *tp;
6521 #endif
6523 /* Only do this once. */
6524 want_garbage_collect = FALSE;
6525 may_garbage_collect = FALSE;
6526 garbage_collect_at_exit = FALSE;
6529 * 1. Go through all accessible variables and mark all lists and dicts
6530 * with copyID.
6532 /* script-local variables */
6533 for (i = 1; i <= ga_scripts.ga_len; ++i)
6534 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6536 /* buffer-local variables */
6537 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6538 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6540 /* window-local variables */
6541 FOR_ALL_TAB_WINDOWS(tp, wp)
6542 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6544 #ifdef FEAT_WINDOWS
6545 /* tabpage-local variables */
6546 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6547 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6548 #endif
6550 /* global variables */
6551 set_ref_in_ht(&globvarht, copyID);
6553 /* function-local variables */
6554 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6556 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6557 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6560 /* v: vars */
6561 set_ref_in_ht(&vimvarht, copyID);
6564 * 2. Go through the list of dicts and free items without the copyID.
6566 for (dd = first_dict; dd != NULL; )
6567 if (dd->dv_copyID != copyID)
6569 /* Free the Dictionary and ordinary items it contains, but don't
6570 * recurse into Lists and Dictionaries, they will be in the list
6571 * of dicts or list of lists. */
6572 dict_free(dd, FALSE);
6573 did_free = TRUE;
6575 /* restart, next dict may also have been freed */
6576 dd = first_dict;
6578 else
6579 dd = dd->dv_used_next;
6582 * 3. Go through the list of lists and free items without the copyID.
6583 * But don't free a list that has a watcher (used in a for loop), these
6584 * are not referenced anywhere.
6586 for (ll = first_list; ll != NULL; )
6587 if (ll->lv_copyID != copyID && ll->lv_watch == NULL)
6589 /* Free the List and ordinary items it contains, but don't recurse
6590 * into Lists and Dictionaries, they will be in the list of dicts
6591 * or list of lists. */
6592 list_free(ll, FALSE);
6593 did_free = TRUE;
6595 /* restart, next list may also have been freed */
6596 ll = first_list;
6598 else
6599 ll = ll->lv_used_next;
6601 /* check if any funccal can be freed now */
6602 for (pfc = &previous_funccal; *pfc != NULL; )
6604 if (can_free_funccal(*pfc, copyID))
6606 fc = *pfc;
6607 *pfc = fc->caller;
6608 free_funccal(fc, TRUE);
6609 did_free = TRUE;
6611 else
6612 pfc = &(*pfc)->caller;
6615 return did_free;
6619 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6621 static void
6622 set_ref_in_ht(ht, copyID)
6623 hashtab_T *ht;
6624 int copyID;
6626 int todo;
6627 hashitem_T *hi;
6629 todo = (int)ht->ht_used;
6630 for (hi = ht->ht_array; todo > 0; ++hi)
6631 if (!HASHITEM_EMPTY(hi))
6633 --todo;
6634 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6639 * Mark all lists and dicts referenced through list "l" with "copyID".
6641 static void
6642 set_ref_in_list(l, copyID)
6643 list_T *l;
6644 int copyID;
6646 listitem_T *li;
6648 for (li = l->lv_first; li != NULL; li = li->li_next)
6649 set_ref_in_item(&li->li_tv, copyID);
6653 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6655 static void
6656 set_ref_in_item(tv, copyID)
6657 typval_T *tv;
6658 int copyID;
6660 dict_T *dd;
6661 list_T *ll;
6663 switch (tv->v_type)
6665 case VAR_DICT:
6666 dd = tv->vval.v_dict;
6667 if (dd != NULL && dd->dv_copyID != copyID)
6669 /* Didn't see this dict yet. */
6670 dd->dv_copyID = copyID;
6671 set_ref_in_ht(&dd->dv_hashtab, copyID);
6673 break;
6675 case VAR_LIST:
6676 ll = tv->vval.v_list;
6677 if (ll != NULL && ll->lv_copyID != copyID)
6679 /* Didn't see this list yet. */
6680 ll->lv_copyID = copyID;
6681 set_ref_in_list(ll, copyID);
6683 break;
6685 return;
6689 * Allocate an empty header for a dictionary.
6691 dict_T *
6692 dict_alloc()
6694 dict_T *d;
6696 d = (dict_T *)alloc(sizeof(dict_T));
6697 if (d != NULL)
6699 /* Add the list to the list of dicts for garbage collection. */
6700 if (first_dict != NULL)
6701 first_dict->dv_used_prev = d;
6702 d->dv_used_next = first_dict;
6703 d->dv_used_prev = NULL;
6704 first_dict = d;
6706 hash_init(&d->dv_hashtab);
6707 d->dv_lock = 0;
6708 d->dv_refcount = 0;
6709 d->dv_copyID = 0;
6711 return d;
6715 * Unreference a Dictionary: decrement the reference count and free it when it
6716 * becomes zero.
6718 static void
6719 dict_unref(d)
6720 dict_T *d;
6722 if (d != NULL && --d->dv_refcount <= 0)
6723 dict_free(d, TRUE);
6727 * Free a Dictionary, including all items it contains.
6728 * Ignores the reference count.
6730 static void
6731 dict_free(d, recurse)
6732 dict_T *d;
6733 int recurse; /* Free Lists and Dictionaries recursively. */
6735 int todo;
6736 hashitem_T *hi;
6737 dictitem_T *di;
6739 /* Remove the dict from the list of dicts for garbage collection. */
6740 if (d->dv_used_prev == NULL)
6741 first_dict = d->dv_used_next;
6742 else
6743 d->dv_used_prev->dv_used_next = d->dv_used_next;
6744 if (d->dv_used_next != NULL)
6745 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6747 /* Lock the hashtab, we don't want it to resize while freeing items. */
6748 hash_lock(&d->dv_hashtab);
6749 todo = (int)d->dv_hashtab.ht_used;
6750 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6752 if (!HASHITEM_EMPTY(hi))
6754 /* Remove the item before deleting it, just in case there is
6755 * something recursive causing trouble. */
6756 di = HI2DI(hi);
6757 hash_remove(&d->dv_hashtab, hi);
6758 if (recurse || (di->di_tv.v_type != VAR_LIST
6759 && di->di_tv.v_type != VAR_DICT))
6760 clear_tv(&di->di_tv);
6761 vim_free(di);
6762 --todo;
6765 hash_clear(&d->dv_hashtab);
6766 vim_free(d);
6770 * Allocate a Dictionary item.
6771 * The "key" is copied to the new item.
6772 * Note that the value of the item "di_tv" still needs to be initialized!
6773 * Returns NULL when out of memory.
6775 static dictitem_T *
6776 dictitem_alloc(key)
6777 char_u *key;
6779 dictitem_T *di;
6781 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6782 if (di != NULL)
6784 STRCPY(di->di_key, key);
6785 di->di_flags = 0;
6787 return di;
6791 * Make a copy of a Dictionary item.
6793 static dictitem_T *
6794 dictitem_copy(org)
6795 dictitem_T *org;
6797 dictitem_T *di;
6799 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6800 + STRLEN(org->di_key)));
6801 if (di != NULL)
6803 STRCPY(di->di_key, org->di_key);
6804 di->di_flags = 0;
6805 copy_tv(&org->di_tv, &di->di_tv);
6807 return di;
6811 * Remove item "item" from Dictionary "dict" and free it.
6813 static void
6814 dictitem_remove(dict, item)
6815 dict_T *dict;
6816 dictitem_T *item;
6818 hashitem_T *hi;
6820 hi = hash_find(&dict->dv_hashtab, item->di_key);
6821 if (HASHITEM_EMPTY(hi))
6822 EMSG2(_(e_intern2), "dictitem_remove()");
6823 else
6824 hash_remove(&dict->dv_hashtab, hi);
6825 dictitem_free(item);
6829 * Free a dict item. Also clears the value.
6831 static void
6832 dictitem_free(item)
6833 dictitem_T *item;
6835 clear_tv(&item->di_tv);
6836 vim_free(item);
6840 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6841 * The refcount of the new dict is set to 1.
6842 * See item_copy() for "copyID".
6843 * Returns NULL when out of memory.
6845 static dict_T *
6846 dict_copy(orig, deep, copyID)
6847 dict_T *orig;
6848 int deep;
6849 int copyID;
6851 dict_T *copy;
6852 dictitem_T *di;
6853 int todo;
6854 hashitem_T *hi;
6856 if (orig == NULL)
6857 return NULL;
6859 copy = dict_alloc();
6860 if (copy != NULL)
6862 if (copyID != 0)
6864 orig->dv_copyID = copyID;
6865 orig->dv_copydict = copy;
6867 todo = (int)orig->dv_hashtab.ht_used;
6868 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6870 if (!HASHITEM_EMPTY(hi))
6872 --todo;
6874 di = dictitem_alloc(hi->hi_key);
6875 if (di == NULL)
6876 break;
6877 if (deep)
6879 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6880 copyID) == FAIL)
6882 vim_free(di);
6883 break;
6886 else
6887 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6888 if (dict_add(copy, di) == FAIL)
6890 dictitem_free(di);
6891 break;
6896 ++copy->dv_refcount;
6897 if (todo > 0)
6899 dict_unref(copy);
6900 copy = NULL;
6904 return copy;
6908 * Add item "item" to Dictionary "d".
6909 * Returns FAIL when out of memory and when key already existed.
6911 static int
6912 dict_add(d, item)
6913 dict_T *d;
6914 dictitem_T *item;
6916 return hash_add(&d->dv_hashtab, item->di_key);
6920 * Add a number or string entry to dictionary "d".
6921 * When "str" is NULL use number "nr", otherwise use "str".
6922 * Returns FAIL when out of memory and when key already exists.
6925 dict_add_nr_str(d, key, nr, str)
6926 dict_T *d;
6927 char *key;
6928 long nr;
6929 char_u *str;
6931 dictitem_T *item;
6933 item = dictitem_alloc((char_u *)key);
6934 if (item == NULL)
6935 return FAIL;
6936 item->di_tv.v_lock = 0;
6937 if (str == NULL)
6939 item->di_tv.v_type = VAR_NUMBER;
6940 item->di_tv.vval.v_number = nr;
6942 else
6944 item->di_tv.v_type = VAR_STRING;
6945 item->di_tv.vval.v_string = vim_strsave(str);
6947 if (dict_add(d, item) == FAIL)
6949 dictitem_free(item);
6950 return FAIL;
6952 return OK;
6956 * Get the number of items in a Dictionary.
6958 static long
6959 dict_len(d)
6960 dict_T *d;
6962 if (d == NULL)
6963 return 0L;
6964 return (long)d->dv_hashtab.ht_used;
6968 * Find item "key[len]" in Dictionary "d".
6969 * If "len" is negative use strlen(key).
6970 * Returns NULL when not found.
6972 static dictitem_T *
6973 dict_find(d, key, len)
6974 dict_T *d;
6975 char_u *key;
6976 int len;
6978 #define AKEYLEN 200
6979 char_u buf[AKEYLEN];
6980 char_u *akey;
6981 char_u *tofree = NULL;
6982 hashitem_T *hi;
6984 if (len < 0)
6985 akey = key;
6986 else if (len >= AKEYLEN)
6988 tofree = akey = vim_strnsave(key, len);
6989 if (akey == NULL)
6990 return NULL;
6992 else
6994 /* Avoid a malloc/free by using buf[]. */
6995 vim_strncpy(buf, key, len);
6996 akey = buf;
6999 hi = hash_find(&d->dv_hashtab, akey);
7000 vim_free(tofree);
7001 if (HASHITEM_EMPTY(hi))
7002 return NULL;
7003 return HI2DI(hi);
7007 * Get a string item from a dictionary.
7008 * When "save" is TRUE allocate memory for it.
7009 * Returns NULL if the entry doesn't exist or out of memory.
7011 char_u *
7012 get_dict_string(d, key, save)
7013 dict_T *d;
7014 char_u *key;
7015 int save;
7017 dictitem_T *di;
7018 char_u *s;
7020 di = dict_find(d, key, -1);
7021 if (di == NULL)
7022 return NULL;
7023 s = get_tv_string(&di->di_tv);
7024 if (save && s != NULL)
7025 s = vim_strsave(s);
7026 return s;
7030 * Get a number item from a dictionary.
7031 * Returns 0 if the entry doesn't exist or out of memory.
7033 long
7034 get_dict_number(d, key)
7035 dict_T *d;
7036 char_u *key;
7038 dictitem_T *di;
7040 di = dict_find(d, key, -1);
7041 if (di == NULL)
7042 return 0;
7043 return get_tv_number(&di->di_tv);
7047 * Return an allocated string with the string representation of a Dictionary.
7048 * May return NULL.
7050 static char_u *
7051 dict2string(tv, copyID)
7052 typval_T *tv;
7053 int copyID;
7055 garray_T ga;
7056 int first = TRUE;
7057 char_u *tofree;
7058 char_u numbuf[NUMBUFLEN];
7059 hashitem_T *hi;
7060 char_u *s;
7061 dict_T *d;
7062 int todo;
7064 if ((d = tv->vval.v_dict) == NULL)
7065 return NULL;
7066 ga_init2(&ga, (int)sizeof(char), 80);
7067 ga_append(&ga, '{');
7069 todo = (int)d->dv_hashtab.ht_used;
7070 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
7072 if (!HASHITEM_EMPTY(hi))
7074 --todo;
7076 if (first)
7077 first = FALSE;
7078 else
7079 ga_concat(&ga, (char_u *)", ");
7081 tofree = string_quote(hi->hi_key, FALSE);
7082 if (tofree != NULL)
7084 ga_concat(&ga, tofree);
7085 vim_free(tofree);
7087 ga_concat(&ga, (char_u *)": ");
7088 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
7089 if (s != NULL)
7090 ga_concat(&ga, s);
7091 vim_free(tofree);
7092 if (s == NULL)
7093 break;
7096 if (todo > 0)
7098 vim_free(ga.ga_data);
7099 return NULL;
7102 ga_append(&ga, '}');
7103 ga_append(&ga, NUL);
7104 return (char_u *)ga.ga_data;
7108 * Allocate a variable for a Dictionary and fill it from "*arg".
7109 * Return OK or FAIL. Returns NOTDONE for {expr}.
7111 static int
7112 get_dict_tv(arg, rettv, evaluate)
7113 char_u **arg;
7114 typval_T *rettv;
7115 int evaluate;
7117 dict_T *d = NULL;
7118 typval_T tvkey;
7119 typval_T tv;
7120 char_u *key = NULL;
7121 dictitem_T *item;
7122 char_u *start = skipwhite(*arg + 1);
7123 char_u buf[NUMBUFLEN];
7126 * First check if it's not a curly-braces thing: {expr}.
7127 * Must do this without evaluating, otherwise a function may be called
7128 * twice. Unfortunately this means we need to call eval1() twice for the
7129 * first item.
7130 * But {} is an empty Dictionary.
7132 if (*start != '}')
7134 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
7135 return FAIL;
7136 if (*start == '}')
7137 return NOTDONE;
7140 if (evaluate)
7142 d = dict_alloc();
7143 if (d == NULL)
7144 return FAIL;
7146 tvkey.v_type = VAR_UNKNOWN;
7147 tv.v_type = VAR_UNKNOWN;
7149 *arg = skipwhite(*arg + 1);
7150 while (**arg != '}' && **arg != NUL)
7152 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
7153 goto failret;
7154 if (**arg != ':')
7156 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
7157 clear_tv(&tvkey);
7158 goto failret;
7160 if (evaluate)
7162 key = get_tv_string_buf_chk(&tvkey, buf);
7163 if (key == NULL || *key == NUL)
7165 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
7166 if (key != NULL)
7167 EMSG(_(e_emptykey));
7168 clear_tv(&tvkey);
7169 goto failret;
7173 *arg = skipwhite(*arg + 1);
7174 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
7176 if (evaluate)
7177 clear_tv(&tvkey);
7178 goto failret;
7180 if (evaluate)
7182 item = dict_find(d, key, -1);
7183 if (item != NULL)
7185 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
7186 clear_tv(&tvkey);
7187 clear_tv(&tv);
7188 goto failret;
7190 item = dictitem_alloc(key);
7191 clear_tv(&tvkey);
7192 if (item != NULL)
7194 item->di_tv = tv;
7195 item->di_tv.v_lock = 0;
7196 if (dict_add(d, item) == FAIL)
7197 dictitem_free(item);
7201 if (**arg == '}')
7202 break;
7203 if (**arg != ',')
7205 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
7206 goto failret;
7208 *arg = skipwhite(*arg + 1);
7211 if (**arg != '}')
7213 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
7214 failret:
7215 if (evaluate)
7216 dict_free(d, TRUE);
7217 return FAIL;
7220 *arg = skipwhite(*arg + 1);
7221 if (evaluate)
7223 rettv->v_type = VAR_DICT;
7224 rettv->vval.v_dict = d;
7225 ++d->dv_refcount;
7228 return OK;
7232 * Return a string with the string representation of a variable.
7233 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7234 * "numbuf" is used for a number.
7235 * Does not put quotes around strings, as ":echo" displays values.
7236 * When "copyID" is not NULL replace recursive lists and dicts with "...".
7237 * May return NULL.
7239 static char_u *
7240 echo_string(tv, tofree, numbuf, copyID)
7241 typval_T *tv;
7242 char_u **tofree;
7243 char_u *numbuf;
7244 int copyID;
7246 static int recurse = 0;
7247 char_u *r = NULL;
7249 if (recurse >= DICT_MAXNEST)
7251 EMSG(_("E724: variable nested too deep for displaying"));
7252 *tofree = NULL;
7253 return NULL;
7255 ++recurse;
7257 switch (tv->v_type)
7259 case VAR_FUNC:
7260 *tofree = NULL;
7261 r = tv->vval.v_string;
7262 break;
7264 case VAR_LIST:
7265 if (tv->vval.v_list == NULL)
7267 *tofree = NULL;
7268 r = NULL;
7270 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
7272 *tofree = NULL;
7273 r = (char_u *)"[...]";
7275 else
7277 tv->vval.v_list->lv_copyID = copyID;
7278 *tofree = list2string(tv, copyID);
7279 r = *tofree;
7281 break;
7283 case VAR_DICT:
7284 if (tv->vval.v_dict == NULL)
7286 *tofree = NULL;
7287 r = NULL;
7289 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
7291 *tofree = NULL;
7292 r = (char_u *)"{...}";
7294 else
7296 tv->vval.v_dict->dv_copyID = copyID;
7297 *tofree = dict2string(tv, copyID);
7298 r = *tofree;
7300 break;
7302 case VAR_STRING:
7303 case VAR_NUMBER:
7304 *tofree = NULL;
7305 r = get_tv_string_buf(tv, numbuf);
7306 break;
7308 #ifdef FEAT_FLOAT
7309 case VAR_FLOAT:
7310 *tofree = NULL;
7311 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
7312 r = numbuf;
7313 break;
7314 #endif
7316 default:
7317 EMSG2(_(e_intern2), "echo_string()");
7318 *tofree = NULL;
7321 --recurse;
7322 return r;
7326 * Return a string with the string representation of a variable.
7327 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7328 * "numbuf" is used for a number.
7329 * Puts quotes around strings, so that they can be parsed back by eval().
7330 * May return NULL.
7332 static char_u *
7333 tv2string(tv, tofree, numbuf, copyID)
7334 typval_T *tv;
7335 char_u **tofree;
7336 char_u *numbuf;
7337 int copyID;
7339 switch (tv->v_type)
7341 case VAR_FUNC:
7342 *tofree = string_quote(tv->vval.v_string, TRUE);
7343 return *tofree;
7344 case VAR_STRING:
7345 *tofree = string_quote(tv->vval.v_string, FALSE);
7346 return *tofree;
7347 #ifdef FEAT_FLOAT
7348 case VAR_FLOAT:
7349 *tofree = NULL;
7350 vim_snprintf((char *)numbuf, NUMBUFLEN - 1, "%g", tv->vval.v_float);
7351 return numbuf;
7352 #endif
7353 case VAR_NUMBER:
7354 case VAR_LIST:
7355 case VAR_DICT:
7356 break;
7357 default:
7358 EMSG2(_(e_intern2), "tv2string()");
7360 return echo_string(tv, tofree, numbuf, copyID);
7364 * Return string "str" in ' quotes, doubling ' characters.
7365 * If "str" is NULL an empty string is assumed.
7366 * If "function" is TRUE make it function('string').
7368 static char_u *
7369 string_quote(str, function)
7370 char_u *str;
7371 int function;
7373 unsigned len;
7374 char_u *p, *r, *s;
7376 len = (function ? 13 : 3);
7377 if (str != NULL)
7379 len += (unsigned)STRLEN(str);
7380 for (p = str; *p != NUL; mb_ptr_adv(p))
7381 if (*p == '\'')
7382 ++len;
7384 s = r = alloc(len);
7385 if (r != NULL)
7387 if (function)
7389 STRCPY(r, "function('");
7390 r += 10;
7392 else
7393 *r++ = '\'';
7394 if (str != NULL)
7395 for (p = str; *p != NUL; )
7397 if (*p == '\'')
7398 *r++ = '\'';
7399 MB_COPY_CHAR(p, r);
7401 *r++ = '\'';
7402 if (function)
7403 *r++ = ')';
7404 *r++ = NUL;
7406 return s;
7409 #ifdef FEAT_FLOAT
7411 * Convert the string "text" to a floating point number.
7412 * This uses strtod(). setlocale(LC_NUMERIC, "C") has been used to make sure
7413 * this always uses a decimal point.
7414 * Returns the length of the text that was consumed.
7416 static int
7417 string2float(text, value)
7418 char_u *text;
7419 float_T *value; /* result stored here */
7421 char *s = (char *)text;
7422 float_T f;
7424 f = strtod(s, &s);
7425 *value = f;
7426 return (int)((char_u *)s - text);
7428 #endif
7431 * Get the value of an environment variable.
7432 * "arg" is pointing to the '$'. It is advanced to after the name.
7433 * If the environment variable was not set, silently assume it is empty.
7434 * Always return OK.
7436 static int
7437 get_env_tv(arg, rettv, evaluate)
7438 char_u **arg;
7439 typval_T *rettv;
7440 int evaluate;
7442 char_u *string = NULL;
7443 int len;
7444 int cc;
7445 char_u *name;
7446 int mustfree = FALSE;
7448 ++*arg;
7449 name = *arg;
7450 len = get_env_len(arg);
7451 if (evaluate)
7453 if (len != 0)
7455 cc = name[len];
7456 name[len] = NUL;
7457 /* first try vim_getenv(), fast for normal environment vars */
7458 string = vim_getenv(name, &mustfree);
7459 if (string != NULL && *string != NUL)
7461 if (!mustfree)
7462 string = vim_strsave(string);
7464 else
7466 if (mustfree)
7467 vim_free(string);
7469 /* next try expanding things like $VIM and ${HOME} */
7470 string = expand_env_save(name - 1);
7471 if (string != NULL && *string == '$')
7473 vim_free(string);
7474 string = NULL;
7477 name[len] = cc;
7479 rettv->v_type = VAR_STRING;
7480 rettv->vval.v_string = string;
7483 return OK;
7487 * Array with names and number of arguments of all internal functions
7488 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7490 static struct fst
7492 char *f_name; /* function name */
7493 char f_min_argc; /* minimal number of arguments */
7494 char f_max_argc; /* maximal number of arguments */
7495 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7496 /* implementation of function */
7497 } functions[] =
7499 #ifdef FEAT_FLOAT
7500 {"abs", 1, 1, f_abs},
7501 {"acos", 1, 1, f_acos}, /* WJMc */
7502 #endif
7503 {"add", 2, 2, f_add},
7504 {"append", 2, 2, f_append},
7505 {"argc", 0, 0, f_argc},
7506 {"argidx", 0, 0, f_argidx},
7507 {"argv", 0, 1, f_argv},
7508 #ifdef FEAT_FLOAT
7509 {"asin", 1, 1, f_asin}, /* WJMc */
7510 {"atan", 1, 1, f_atan},
7511 {"atan2", 2, 2, f_atan2}, /* WJMc */
7512 #endif
7513 {"browse", 4, 4, f_browse},
7514 {"browsedir", 2, 2, f_browsedir},
7515 {"bufexists", 1, 1, f_bufexists},
7516 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7517 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7518 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7519 {"buflisted", 1, 1, f_buflisted},
7520 {"bufloaded", 1, 1, f_bufloaded},
7521 {"bufname", 1, 1, f_bufname},
7522 {"bufnr", 1, 2, f_bufnr},
7523 {"bufwinnr", 1, 1, f_bufwinnr},
7524 {"byte2line", 1, 1, f_byte2line},
7525 {"byteidx", 2, 2, f_byteidx},
7526 {"call", 2, 3, f_call},
7527 #ifdef FEAT_FLOAT
7528 {"ceil", 1, 1, f_ceil},
7529 #endif
7530 {"changenr", 0, 0, f_changenr},
7531 {"char2nr", 1, 1, f_char2nr},
7532 {"cindent", 1, 1, f_cindent},
7533 {"clearmatches", 0, 0, f_clearmatches},
7534 {"col", 1, 1, f_col},
7535 #if defined(FEAT_INS_EXPAND)
7536 {"complete", 2, 2, f_complete},
7537 {"complete_add", 1, 1, f_complete_add},
7538 {"complete_check", 0, 0, f_complete_check},
7539 #endif
7540 {"confirm", 1, 4, f_confirm},
7541 {"copy", 1, 1, f_copy},
7542 #ifdef FEAT_FLOAT
7543 {"cos", 1, 1, f_cos},
7544 {"cosh", 1, 1, f_cosh}, /* WJMc */
7545 #endif
7546 {"count", 2, 4, f_count},
7547 {"cscope_connection",0,3, f_cscope_connection},
7548 {"cursor", 1, 3, f_cursor},
7549 {"deepcopy", 1, 2, f_deepcopy},
7550 {"delete", 1, 1, f_delete},
7551 {"did_filetype", 0, 0, f_did_filetype},
7552 {"diff_filler", 1, 1, f_diff_filler},
7553 {"diff_hlID", 2, 2, f_diff_hlID},
7554 {"empty", 1, 1, f_empty},
7555 {"escape", 2, 2, f_escape},
7556 {"eval", 1, 1, f_eval},
7557 {"eventhandler", 0, 0, f_eventhandler},
7558 {"executable", 1, 1, f_executable},
7559 {"exists", 1, 1, f_exists},
7560 #ifdef FEAT_FLOAT
7561 {"exp", 1, 1, f_exp}, /* WJMc */
7562 #endif
7563 {"expand", 1, 2, f_expand},
7564 {"extend", 2, 3, f_extend},
7565 {"feedkeys", 1, 2, f_feedkeys},
7566 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7567 {"filereadable", 1, 1, f_filereadable},
7568 {"filewritable", 1, 1, f_filewritable},
7569 {"filter", 2, 2, f_filter},
7570 {"finddir", 1, 3, f_finddir},
7571 {"findfile", 1, 3, f_findfile},
7572 #ifdef FEAT_FLOAT
7573 {"float2nr", 1, 1, f_float2nr},
7574 {"floor", 1, 1, f_floor},
7575 {"fmod", 2, 2, f_fmod}, /* WJMc */
7576 #endif
7577 {"fnameescape", 1, 1, f_fnameescape},
7578 {"fnamemodify", 2, 2, f_fnamemodify},
7579 {"foldclosed", 1, 1, f_foldclosed},
7580 {"foldclosedend", 1, 1, f_foldclosedend},
7581 {"foldlevel", 1, 1, f_foldlevel},
7582 {"foldtext", 0, 0, f_foldtext},
7583 {"foldtextresult", 1, 1, f_foldtextresult},
7584 {"foreground", 0, 0, f_foreground},
7585 {"function", 1, 1, f_function},
7586 {"garbagecollect", 0, 1, f_garbagecollect},
7587 {"get", 2, 3, f_get},
7588 {"getbufline", 2, 3, f_getbufline},
7589 {"getbufvar", 2, 2, f_getbufvar},
7590 {"getchar", 0, 1, f_getchar},
7591 {"getcharmod", 0, 0, f_getcharmod},
7592 {"getcmdline", 0, 0, f_getcmdline},
7593 {"getcmdpos", 0, 0, f_getcmdpos},
7594 {"getcmdtype", 0, 0, f_getcmdtype},
7595 {"getcwd", 0, 0, f_getcwd},
7596 {"getfontname", 0, 1, f_getfontname},
7597 {"getfperm", 1, 1, f_getfperm},
7598 {"getfsize", 1, 1, f_getfsize},
7599 {"getftime", 1, 1, f_getftime},
7600 {"getftype", 1, 1, f_getftype},
7601 {"getline", 1, 2, f_getline},
7602 {"getloclist", 1, 1, f_getqflist},
7603 {"getmatches", 0, 0, f_getmatches},
7604 {"getpid", 0, 0, f_getpid},
7605 {"getpos", 1, 1, f_getpos},
7606 {"getqflist", 0, 0, f_getqflist},
7607 {"getreg", 0, 2, f_getreg},
7608 {"getregtype", 0, 1, f_getregtype},
7609 {"gettabwinvar", 3, 3, f_gettabwinvar},
7610 {"getwinposx", 0, 0, f_getwinposx},
7611 {"getwinposy", 0, 0, f_getwinposy},
7612 {"getwinvar", 2, 2, f_getwinvar},
7613 {"glob", 1, 2, f_glob},
7614 {"globpath", 2, 3, f_globpath},
7615 {"has", 1, 1, f_has},
7616 {"has_key", 2, 2, f_has_key},
7617 {"haslocaldir", 0, 0, f_haslocaldir},
7618 {"hasmapto", 1, 3, f_hasmapto},
7619 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7620 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7621 {"histadd", 2, 2, f_histadd},
7622 {"histdel", 1, 2, f_histdel},
7623 {"histget", 1, 2, f_histget},
7624 {"histnr", 1, 1, f_histnr},
7625 {"hlID", 1, 1, f_hlID},
7626 {"hlexists", 1, 1, f_hlexists},
7627 {"hostname", 0, 0, f_hostname},
7628 {"iconv", 3, 3, f_iconv},
7629 {"indent", 1, 1, f_indent},
7630 {"index", 2, 4, f_index},
7631 {"input", 1, 3, f_input},
7632 {"inputdialog", 1, 3, f_inputdialog},
7633 {"inputlist", 1, 1, f_inputlist},
7634 {"inputrestore", 0, 0, f_inputrestore},
7635 {"inputsave", 0, 0, f_inputsave},
7636 {"inputsecret", 1, 2, f_inputsecret},
7637 {"insert", 2, 3, f_insert},
7638 {"isdirectory", 1, 1, f_isdirectory},
7639 {"islocked", 1, 1, f_islocked},
7640 {"items", 1, 1, f_items},
7641 {"join", 1, 2, f_join},
7642 {"keys", 1, 1, f_keys},
7643 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7644 {"len", 1, 1, f_len},
7645 {"libcall", 3, 3, f_libcall},
7646 {"libcallnr", 3, 3, f_libcallnr},
7647 {"line", 1, 1, f_line},
7648 {"line2byte", 1, 1, f_line2byte},
7649 {"lispindent", 1, 1, f_lispindent},
7650 {"localtime", 0, 0, f_localtime},
7651 #ifdef FEAT_FLOAT
7652 {"log", 1, 1, f_log}, /* WJMc */
7653 {"log10", 1, 1, f_log10},
7654 #endif
7655 {"map", 2, 2, f_map},
7656 {"maparg", 1, 3, f_maparg},
7657 {"mapcheck", 1, 3, f_mapcheck},
7658 {"match", 2, 4, f_match},
7659 {"matchadd", 2, 4, f_matchadd},
7660 {"matcharg", 1, 1, f_matcharg},
7661 {"matchdelete", 1, 1, f_matchdelete},
7662 {"matchend", 2, 4, f_matchend},
7663 {"matchlist", 2, 4, f_matchlist},
7664 {"matchstr", 2, 4, f_matchstr},
7665 {"max", 1, 1, f_max},
7666 {"min", 1, 1, f_min},
7667 #ifdef vim_mkdir
7668 {"mkdir", 1, 3, f_mkdir},
7669 #endif
7670 {"mode", 0, 1, f_mode},
7671 {"nextnonblank", 1, 1, f_nextnonblank},
7672 {"nr2char", 1, 1, f_nr2char},
7673 {"pathshorten", 1, 1, f_pathshorten},
7674 #ifdef FEAT_FLOAT
7675 {"pow", 2, 2, f_pow},
7676 #endif
7677 {"prevnonblank", 1, 1, f_prevnonblank},
7678 {"printf", 2, 19, f_printf},
7679 {"pumvisible", 0, 0, f_pumvisible},
7680 {"range", 1, 3, f_range},
7681 {"readfile", 1, 3, f_readfile},
7682 {"reltime", 0, 2, f_reltime},
7683 {"reltimestr", 1, 1, f_reltimestr},
7684 {"remote_expr", 2, 3, f_remote_expr},
7685 {"remote_foreground", 1, 1, f_remote_foreground},
7686 {"remote_peek", 1, 2, f_remote_peek},
7687 {"remote_read", 1, 1, f_remote_read},
7688 {"remote_send", 2, 3, f_remote_send},
7689 {"remove", 2, 3, f_remove},
7690 {"rename", 2, 2, f_rename},
7691 {"repeat", 2, 2, f_repeat},
7692 {"resolve", 1, 1, f_resolve},
7693 {"reverse", 1, 1, f_reverse},
7694 #ifdef FEAT_FLOAT
7695 {"round", 1, 1, f_round},
7696 #endif
7697 {"search", 1, 4, f_search},
7698 {"searchdecl", 1, 3, f_searchdecl},
7699 {"searchpair", 3, 7, f_searchpair},
7700 {"searchpairpos", 3, 7, f_searchpairpos},
7701 {"searchpos", 1, 4, f_searchpos},
7702 {"server2client", 2, 2, f_server2client},
7703 {"serverlist", 0, 0, f_serverlist},
7704 {"setbufvar", 3, 3, f_setbufvar},
7705 {"setcmdpos", 1, 1, f_setcmdpos},
7706 {"setline", 2, 2, f_setline},
7707 {"setloclist", 2, 3, f_setloclist},
7708 {"setmatches", 1, 1, f_setmatches},
7709 {"setpos", 2, 2, f_setpos},
7710 {"setqflist", 1, 2, f_setqflist},
7711 {"setreg", 2, 3, f_setreg},
7712 {"settabwinvar", 4, 4, f_settabwinvar},
7713 {"setwinvar", 3, 3, f_setwinvar},
7714 {"shellescape", 1, 2, f_shellescape},
7715 {"simplify", 1, 1, f_simplify},
7716 #ifdef FEAT_FLOAT
7717 {"sin", 1, 1, f_sin},
7718 {"sinh", 1, 1, f_sinh}, /* WJMc */
7719 #endif
7720 {"sort", 1, 2, f_sort},
7721 {"soundfold", 1, 1, f_soundfold},
7722 {"spellbadword", 0, 1, f_spellbadword},
7723 {"spellsuggest", 1, 3, f_spellsuggest},
7724 {"split", 1, 3, f_split},
7725 #ifdef FEAT_FLOAT
7726 {"sqrt", 1, 1, f_sqrt},
7727 {"str2float", 1, 1, f_str2float},
7728 #endif
7729 {"str2nr", 1, 2, f_str2nr},
7730 #ifdef HAVE_STRFTIME
7731 {"strftime", 1, 2, f_strftime},
7732 #endif
7733 {"stridx", 2, 3, f_stridx},
7734 {"string", 1, 1, f_string},
7735 {"strlen", 1, 1, f_strlen},
7736 {"strpart", 2, 3, f_strpart},
7737 {"strridx", 2, 3, f_strridx},
7738 {"strtrans", 1, 1, f_strtrans},
7739 {"submatch", 1, 1, f_submatch},
7740 {"substitute", 4, 4, f_substitute},
7741 {"synID", 3, 3, f_synID},
7742 {"synIDattr", 2, 3, f_synIDattr},
7743 {"synIDtrans", 1, 1, f_synIDtrans},
7744 {"synstack", 2, 2, f_synstack},
7745 {"system", 1, 2, f_system},
7746 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7747 {"tabpagenr", 0, 1, f_tabpagenr},
7748 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7749 {"tagfiles", 0, 0, f_tagfiles},
7750 {"taglist", 1, 1, f_taglist},
7751 {"tan", 1, 1, f_tan}, /* WJMc */
7752 {"tanh", 1, 1, f_tanh}, /* WJMc */
7753 {"tempname", 0, 0, f_tempname},
7754 {"test", 1, 1, f_test},
7755 {"tolower", 1, 1, f_tolower},
7756 {"toupper", 1, 1, f_toupper},
7757 {"tr", 3, 3, f_tr},
7758 #ifdef FEAT_FLOAT
7759 {"trunc", 1, 1, f_trunc},
7760 #endif
7761 {"type", 1, 1, f_type},
7762 {"values", 1, 1, f_values},
7763 {"virtcol", 1, 1, f_virtcol},
7764 {"visualmode", 0, 1, f_visualmode},
7765 {"winbufnr", 1, 1, f_winbufnr},
7766 {"wincol", 0, 0, f_wincol},
7767 {"winheight", 1, 1, f_winheight},
7768 {"winline", 0, 0, f_winline},
7769 {"winnr", 0, 1, f_winnr},
7770 {"winrestcmd", 0, 0, f_winrestcmd},
7771 {"winrestview", 1, 1, f_winrestview},
7772 {"winsaveview", 0, 0, f_winsaveview},
7773 {"winwidth", 1, 1, f_winwidth},
7774 {"writefile", 2, 3, f_writefile},
7777 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7780 * Function given to ExpandGeneric() to obtain the list of internal
7781 * or user defined function names.
7783 char_u *
7784 get_function_name(xp, idx)
7785 expand_T *xp;
7786 int idx;
7788 static int intidx = -1;
7789 char_u *name;
7791 if (idx == 0)
7792 intidx = -1;
7793 if (intidx < 0)
7795 name = get_user_func_name(xp, idx);
7796 if (name != NULL)
7797 return name;
7799 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7801 STRCPY(IObuff, functions[intidx].f_name);
7802 STRCAT(IObuff, "(");
7803 if (functions[intidx].f_max_argc == 0)
7804 STRCAT(IObuff, ")");
7805 return IObuff;
7808 return NULL;
7812 * Function given to ExpandGeneric() to obtain the list of internal or
7813 * user defined variable or function names.
7815 /*ARGSUSED*/
7816 char_u *
7817 get_expr_name(xp, idx)
7818 expand_T *xp;
7819 int idx;
7821 static int intidx = -1;
7822 char_u *name;
7824 if (idx == 0)
7825 intidx = -1;
7826 if (intidx < 0)
7828 name = get_function_name(xp, idx);
7829 if (name != NULL)
7830 return name;
7832 return get_user_var_name(xp, ++intidx);
7835 #endif /* FEAT_CMDL_COMPL */
7838 * Find internal function in table above.
7839 * Return index, or -1 if not found
7841 static int
7842 find_internal_func(name)
7843 char_u *name; /* name of the function */
7845 int first = 0;
7846 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7847 int cmp;
7848 int x;
7851 * Find the function name in the table. Binary search.
7853 while (first <= last)
7855 x = first + ((unsigned)(last - first) >> 1);
7856 cmp = STRCMP(name, functions[x].f_name);
7857 if (cmp < 0)
7858 last = x - 1;
7859 else if (cmp > 0)
7860 first = x + 1;
7861 else
7862 return x;
7864 return -1;
7868 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7869 * name it contains, otherwise return "name".
7871 static char_u *
7872 deref_func_name(name, lenp)
7873 char_u *name;
7874 int *lenp;
7876 dictitem_T *v;
7877 int cc;
7879 cc = name[*lenp];
7880 name[*lenp] = NUL;
7881 v = find_var(name, NULL);
7882 name[*lenp] = cc;
7883 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7885 if (v->di_tv.vval.v_string == NULL)
7887 *lenp = 0;
7888 return (char_u *)""; /* just in case */
7890 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7891 return v->di_tv.vval.v_string;
7894 return name;
7898 * Allocate a variable for the result of a function.
7899 * Return OK or FAIL.
7901 static int
7902 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7903 evaluate, selfdict)
7904 char_u *name; /* name of the function */
7905 int len; /* length of "name" */
7906 typval_T *rettv;
7907 char_u **arg; /* argument, pointing to the '(' */
7908 linenr_T firstline; /* first line of range */
7909 linenr_T lastline; /* last line of range */
7910 int *doesrange; /* return: function handled range */
7911 int evaluate;
7912 dict_T *selfdict; /* Dictionary for "self" */
7914 char_u *argp;
7915 int ret = OK;
7916 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7917 int argcount = 0; /* number of arguments found */
7920 * Get the arguments.
7922 argp = *arg;
7923 while (argcount < MAX_FUNC_ARGS)
7925 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7926 if (*argp == ')' || *argp == ',' || *argp == NUL)
7927 break;
7928 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7930 ret = FAIL;
7931 break;
7933 ++argcount;
7934 if (*argp != ',')
7935 break;
7937 if (*argp == ')')
7938 ++argp;
7939 else
7940 ret = FAIL;
7942 if (ret == OK)
7943 ret = call_func(name, len, rettv, argcount, argvars,
7944 firstline, lastline, doesrange, evaluate, selfdict);
7945 else if (!aborting())
7947 if (argcount == MAX_FUNC_ARGS)
7948 emsg_funcname("E740: Too many arguments for function %s", name);
7949 else
7950 emsg_funcname("E116: Invalid arguments for function %s", name);
7953 while (--argcount >= 0)
7954 clear_tv(&argvars[argcount]);
7956 *arg = skipwhite(argp);
7957 return ret;
7962 * Call a function with its resolved parameters
7963 * Return OK when the function can't be called, FAIL otherwise.
7964 * Also returns OK when an error was encountered while executing the function.
7966 static int
7967 call_func(name, len, rettv, argcount, argvars, firstline, lastline,
7968 doesrange, evaluate, selfdict)
7969 char_u *name; /* name of the function */
7970 int len; /* length of "name" */
7971 typval_T *rettv; /* return value goes here */
7972 int argcount; /* number of "argvars" */
7973 typval_T *argvars; /* vars for arguments, must have "argcount"
7974 PLUS ONE elements! */
7975 linenr_T firstline; /* first line of range */
7976 linenr_T lastline; /* last line of range */
7977 int *doesrange; /* return: function handled range */
7978 int evaluate;
7979 dict_T *selfdict; /* Dictionary for "self" */
7981 int ret = FAIL;
7982 #define ERROR_UNKNOWN 0
7983 #define ERROR_TOOMANY 1
7984 #define ERROR_TOOFEW 2
7985 #define ERROR_SCRIPT 3
7986 #define ERROR_DICT 4
7987 #define ERROR_NONE 5
7988 #define ERROR_OTHER 6
7989 int error = ERROR_NONE;
7990 int i;
7991 int llen;
7992 ufunc_T *fp;
7993 int cc;
7994 #define FLEN_FIXED 40
7995 char_u fname_buf[FLEN_FIXED + 1];
7996 char_u *fname;
7999 * In a script change <SID>name() and s:name() to K_SNR 123_name().
8000 * Change <SNR>123_name() to K_SNR 123_name().
8001 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
8003 cc = name[len];
8004 name[len] = NUL;
8005 llen = eval_fname_script(name);
8006 if (llen > 0)
8008 fname_buf[0] = K_SPECIAL;
8009 fname_buf[1] = KS_EXTRA;
8010 fname_buf[2] = (int)KE_SNR;
8011 i = 3;
8012 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
8014 if (current_SID <= 0)
8015 error = ERROR_SCRIPT;
8016 else
8018 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
8019 i = (int)STRLEN(fname_buf);
8022 if (i + STRLEN(name + llen) < FLEN_FIXED)
8024 STRCPY(fname_buf + i, name + llen);
8025 fname = fname_buf;
8027 else
8029 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
8030 if (fname == NULL)
8031 error = ERROR_OTHER;
8032 else
8034 mch_memmove(fname, fname_buf, (size_t)i);
8035 STRCPY(fname + i, name + llen);
8039 else
8040 fname = name;
8042 *doesrange = FALSE;
8045 /* execute the function if no errors detected and executing */
8046 if (evaluate && error == ERROR_NONE)
8048 rettv->v_type = VAR_NUMBER; /* default is number rettv */
8049 error = ERROR_UNKNOWN;
8051 if (!builtin_function(fname))
8054 * User defined function.
8056 fp = find_func(fname);
8058 #ifdef FEAT_AUTOCMD
8059 /* Trigger FuncUndefined event, may load the function. */
8060 if (fp == NULL
8061 && apply_autocmds(EVENT_FUNCUNDEFINED,
8062 fname, fname, TRUE, NULL)
8063 && !aborting())
8065 /* executed an autocommand, search for the function again */
8066 fp = find_func(fname);
8068 #endif
8069 /* Try loading a package. */
8070 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
8072 /* loaded a package, search for the function again */
8073 fp = find_func(fname);
8076 if (fp != NULL)
8078 if (fp->uf_flags & FC_RANGE)
8079 *doesrange = TRUE;
8080 if (argcount < fp->uf_args.ga_len)
8081 error = ERROR_TOOFEW;
8082 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
8083 error = ERROR_TOOMANY;
8084 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
8085 error = ERROR_DICT;
8086 else
8089 * Call the user function.
8090 * Save and restore search patterns, script variables and
8091 * redo buffer.
8093 save_search_patterns();
8094 saveRedobuff();
8095 ++fp->uf_calls;
8096 call_user_func(fp, argcount, argvars, rettv,
8097 firstline, lastline,
8098 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
8099 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
8100 && fp->uf_refcount <= 0)
8101 /* Function was unreferenced while being used, free it
8102 * now. */
8103 func_free(fp);
8104 restoreRedobuff();
8105 restore_search_patterns();
8106 error = ERROR_NONE;
8110 else
8113 * Find the function name in the table, call its implementation.
8115 i = find_internal_func(fname);
8116 if (i >= 0)
8118 if (argcount < functions[i].f_min_argc)
8119 error = ERROR_TOOFEW;
8120 else if (argcount > functions[i].f_max_argc)
8121 error = ERROR_TOOMANY;
8122 else
8124 argvars[argcount].v_type = VAR_UNKNOWN;
8125 functions[i].f_func(argvars, rettv);
8126 error = ERROR_NONE;
8131 * The function call (or "FuncUndefined" autocommand sequence) might
8132 * have been aborted by an error, an interrupt, or an explicitly thrown
8133 * exception that has not been caught so far. This situation can be
8134 * tested for by calling aborting(). For an error in an internal
8135 * function or for the "E132" error in call_user_func(), however, the
8136 * throw point at which the "force_abort" flag (temporarily reset by
8137 * emsg()) is normally updated has not been reached yet. We need to
8138 * update that flag first to make aborting() reliable.
8140 update_force_abort();
8142 if (error == ERROR_NONE)
8143 ret = OK;
8146 * Report an error unless the argument evaluation or function call has been
8147 * cancelled due to an aborting error, an interrupt, or an exception.
8149 if (!aborting())
8151 switch (error)
8153 case ERROR_UNKNOWN:
8154 emsg_funcname(N_("E117: Unknown function: %s"), name);
8155 break;
8156 case ERROR_TOOMANY:
8157 emsg_funcname(e_toomanyarg, name);
8158 break;
8159 case ERROR_TOOFEW:
8160 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
8161 name);
8162 break;
8163 case ERROR_SCRIPT:
8164 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
8165 name);
8166 break;
8167 case ERROR_DICT:
8168 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
8169 name);
8170 break;
8174 name[len] = cc;
8175 if (fname != name && fname != fname_buf)
8176 vim_free(fname);
8178 return ret;
8182 * Give an error message with a function name. Handle <SNR> things.
8184 static void
8185 emsg_funcname(ermsg, name)
8186 char *ermsg;
8187 char_u *name;
8189 char_u *p;
8191 if (*name == K_SPECIAL)
8192 p = concat_str((char_u *)"<SNR>", name + 3);
8193 else
8194 p = name;
8195 EMSG2(_(ermsg), p);
8196 if (p != name)
8197 vim_free(p);
8201 * Return TRUE for a non-zero Number and a non-empty String.
8203 static int
8204 non_zero_arg(argvars)
8205 typval_T *argvars;
8207 return ((argvars[0].v_type == VAR_NUMBER
8208 && argvars[0].vval.v_number != 0)
8209 || (argvars[0].v_type == VAR_STRING
8210 && argvars[0].vval.v_string != NULL
8211 && *argvars[0].vval.v_string != NUL));
8214 /*********************************************
8215 * Implementation of the built-in functions
8218 #ifdef FEAT_FLOAT
8220 * "abs(expr)" function
8222 static void
8223 f_abs(argvars, rettv)
8224 typval_T *argvars;
8225 typval_T *rettv;
8227 if (argvars[0].v_type == VAR_FLOAT)
8229 rettv->v_type = VAR_FLOAT;
8230 rettv->vval.v_float = fabs(argvars[0].vval.v_float);
8232 else
8234 varnumber_T n;
8235 int error = FALSE;
8237 n = get_tv_number_chk(&argvars[0], &error);
8238 if (error)
8239 rettv->vval.v_number = -1;
8240 else if (n > 0)
8241 rettv->vval.v_number = n;
8242 else
8243 rettv->vval.v_number = -n;
8246 #endif
8249 * "add(list, item)" function
8251 static void
8252 f_add(argvars, rettv)
8253 typval_T *argvars;
8254 typval_T *rettv;
8256 list_T *l;
8258 rettv->vval.v_number = 1; /* Default: Failed */
8259 if (argvars[0].v_type == VAR_LIST)
8261 if ((l = argvars[0].vval.v_list) != NULL
8262 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
8263 && list_append_tv(l, &argvars[1]) == OK)
8264 copy_tv(&argvars[0], rettv);
8266 else
8267 EMSG(_(e_listreq));
8271 * "append(lnum, string/list)" function
8273 static void
8274 f_append(argvars, rettv)
8275 typval_T *argvars;
8276 typval_T *rettv;
8278 long lnum;
8279 char_u *line;
8280 list_T *l = NULL;
8281 listitem_T *li = NULL;
8282 typval_T *tv;
8283 long added = 0;
8285 lnum = get_tv_lnum(argvars);
8286 if (lnum >= 0
8287 && lnum <= curbuf->b_ml.ml_line_count
8288 && u_save(lnum, lnum + 1) == OK)
8290 if (argvars[1].v_type == VAR_LIST)
8292 l = argvars[1].vval.v_list;
8293 if (l == NULL)
8294 return;
8295 li = l->lv_first;
8297 rettv->vval.v_number = 0; /* Default: Success */
8298 for (;;)
8300 if (l == NULL)
8301 tv = &argvars[1]; /* append a string */
8302 else if (li == NULL)
8303 break; /* end of list */
8304 else
8305 tv = &li->li_tv; /* append item from list */
8306 line = get_tv_string_chk(tv);
8307 if (line == NULL) /* type error */
8309 rettv->vval.v_number = 1; /* Failed */
8310 break;
8312 ml_append(lnum + added, line, (colnr_T)0, FALSE);
8313 ++added;
8314 if (l == NULL)
8315 break;
8316 li = li->li_next;
8319 appended_lines_mark(lnum, added);
8320 if (curwin->w_cursor.lnum > lnum)
8321 curwin->w_cursor.lnum += added;
8323 else
8324 rettv->vval.v_number = 1; /* Failed */
8328 * "argc()" function
8330 /* ARGSUSED */
8331 static void
8332 f_argc(argvars, rettv)
8333 typval_T *argvars;
8334 typval_T *rettv;
8336 rettv->vval.v_number = ARGCOUNT;
8340 * "argidx()" function
8342 /* ARGSUSED */
8343 static void
8344 f_argidx(argvars, rettv)
8345 typval_T *argvars;
8346 typval_T *rettv;
8348 rettv->vval.v_number = curwin->w_arg_idx;
8352 * "argv(nr)" function
8354 static void
8355 f_argv(argvars, rettv)
8356 typval_T *argvars;
8357 typval_T *rettv;
8359 int idx;
8361 if (argvars[0].v_type != VAR_UNKNOWN)
8363 idx = get_tv_number_chk(&argvars[0], NULL);
8364 if (idx >= 0 && idx < ARGCOUNT)
8365 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
8366 else
8367 rettv->vval.v_string = NULL;
8368 rettv->v_type = VAR_STRING;
8370 else if (rettv_list_alloc(rettv) == OK)
8371 for (idx = 0; idx < ARGCOUNT; ++idx)
8372 list_append_string(rettv->vval.v_list,
8373 alist_name(&ARGLIST[idx]), -1);
8376 #ifdef FEAT_FLOAT
8377 static int get_float_arg __ARGS((typval_T *argvars, float_T *f));
8380 * Get the float value of "argvars[0]" into "f".
8381 * Returns FAIL when the argument is not a Number or Float.
8383 static int
8384 get_float_arg(argvars, f)
8385 typval_T *argvars;
8386 float_T *f;
8388 if (argvars[0].v_type == VAR_FLOAT)
8390 *f = argvars[0].vval.v_float;
8391 return OK;
8393 if (argvars[0].v_type == VAR_NUMBER)
8395 *f = (float_T)argvars[0].vval.v_number;
8396 return OK;
8398 EMSG(_("E808: Number or Float required"));
8399 return FAIL;
8402 /* The 10 added FP functions are defined immediately before atan() - WJMc */
8405 * "acos()" function
8407 static void
8408 f_acos(argvars, rettv)
8409 typval_T *argvars;
8410 typval_T *rettv;
8412 float_T f;
8414 rettv->v_type = VAR_FLOAT;
8415 if (get_float_arg(argvars, &f) == OK)
8416 rettv->vval.v_float = acos(f);
8417 else
8418 rettv->vval.v_float = 0.0;
8422 * "asin()" function
8424 static void
8425 f_asin(argvars, rettv)
8426 typval_T *argvars;
8427 typval_T *rettv;
8429 float_T f;
8431 rettv->v_type = VAR_FLOAT;
8432 if (get_float_arg(argvars, &f) == OK)
8433 rettv->vval.v_float = asin(f);
8434 else
8435 rettv->vval.v_float = 0.0;
8439 * "atan2()" function
8441 static void
8442 f_atan2(argvars, rettv)
8443 typval_T *argvars;
8444 typval_T *rettv;
8446 float_T fx, fy;
8448 rettv->v_type = VAR_FLOAT;
8449 if (get_float_arg(argvars, &fx) == OK
8450 && get_float_arg(&argvars[1], &fy) == OK)
8451 rettv->vval.v_float = atan2(fx, fy);
8452 else
8453 rettv->vval.v_float = 0.0;
8457 * "cosh()" function
8459 static void
8460 f_cosh(argvars, rettv)
8461 typval_T *argvars;
8462 typval_T *rettv;
8464 float_T f;
8466 rettv->v_type = VAR_FLOAT;
8467 if (get_float_arg(argvars, &f) == OK)
8468 rettv->vval.v_float = cosh(f);
8469 else
8470 rettv->vval.v_float = 0.0;
8474 * "exp()" function
8476 static void
8477 f_exp(argvars, rettv)
8478 typval_T *argvars;
8479 typval_T *rettv;
8481 float_T f;
8483 rettv->v_type = VAR_FLOAT;
8484 if (get_float_arg(argvars, &f) == OK)
8485 rettv->vval.v_float = exp(f);
8486 else
8487 rettv->vval.v_float = 0.0;
8491 * "fmod()" function
8493 static void
8494 f_fmod(argvars, rettv)
8495 typval_T *argvars;
8496 typval_T *rettv;
8498 float_T fx, fy;
8500 rettv->v_type = VAR_FLOAT;
8501 if (get_float_arg(argvars, &fx) == OK
8502 && get_float_arg(&argvars[1], &fy) == OK)
8503 rettv->vval.v_float = fmod(fx, fy);
8504 else
8505 rettv->vval.v_float = 0.0;
8509 * "log()" function
8511 static void
8512 f_log(argvars, rettv)
8513 typval_T *argvars;
8514 typval_T *rettv;
8516 float_T f;
8518 rettv->v_type = VAR_FLOAT;
8519 if (get_float_arg(argvars, &f) == OK)
8520 rettv->vval.v_float = log(f);
8521 else
8522 rettv->vval.v_float = 0.0;
8526 * "sinh()" function
8528 static void
8529 f_sinh(argvars, rettv)
8530 typval_T *argvars;
8531 typval_T *rettv;
8533 float_T f;
8535 rettv->v_type = VAR_FLOAT;
8536 if (get_float_arg(argvars, &f) == OK)
8537 rettv->vval.v_float = sinh(f);
8538 else
8539 rettv->vval.v_float = 0.0;
8543 * "tan()" function
8545 static void
8546 f_tan(argvars, rettv)
8547 typval_T *argvars;
8548 typval_T *rettv;
8550 float_T f;
8552 rettv->v_type = VAR_FLOAT;
8553 if (get_float_arg(argvars, &f) == OK)
8554 rettv->vval.v_float = tan(f);
8555 else
8556 rettv->vval.v_float = 0.0;
8560 * "tanh()" function
8562 static void
8563 f_tanh(argvars, rettv)
8564 typval_T *argvars;
8565 typval_T *rettv;
8567 float_T f;
8569 rettv->v_type = VAR_FLOAT;
8570 if (get_float_arg(argvars, &f) == OK)
8571 rettv->vval.v_float = tanh(f);
8572 else
8573 rettv->vval.v_float = 0.0;
8576 /* End of the 10 added FP functions - WJMc */
8579 * "atan()" function
8581 static void
8582 f_atan(argvars, rettv)
8583 typval_T *argvars;
8584 typval_T *rettv;
8586 float_T f;
8588 rettv->v_type = VAR_FLOAT;
8589 if (get_float_arg(argvars, &f) == OK)
8590 rettv->vval.v_float = atan(f);
8591 else
8592 rettv->vval.v_float = 0.0;
8594 #endif
8597 * "browse(save, title, initdir, default)" function
8599 /* ARGSUSED */
8600 static void
8601 f_browse(argvars, rettv)
8602 typval_T *argvars;
8603 typval_T *rettv;
8605 #ifdef FEAT_BROWSE
8606 int save;
8607 char_u *title;
8608 char_u *initdir;
8609 char_u *defname;
8610 char_u buf[NUMBUFLEN];
8611 char_u buf2[NUMBUFLEN];
8612 int error = FALSE;
8614 save = get_tv_number_chk(&argvars[0], &error);
8615 title = get_tv_string_chk(&argvars[1]);
8616 initdir = get_tv_string_buf_chk(&argvars[2], buf);
8617 defname = get_tv_string_buf_chk(&argvars[3], buf2);
8619 if (error || title == NULL || initdir == NULL || defname == NULL)
8620 rettv->vval.v_string = NULL;
8621 else
8622 rettv->vval.v_string =
8623 do_browse(save ? BROWSE_SAVE : 0,
8624 title, defname, NULL, initdir, NULL, curbuf);
8625 #else
8626 rettv->vval.v_string = NULL;
8627 #endif
8628 rettv->v_type = VAR_STRING;
8632 * "browsedir(title, initdir)" function
8634 /* ARGSUSED */
8635 static void
8636 f_browsedir(argvars, rettv)
8637 typval_T *argvars;
8638 typval_T *rettv;
8640 #ifdef FEAT_BROWSE
8641 char_u *title;
8642 char_u *initdir;
8643 char_u buf[NUMBUFLEN];
8645 title = get_tv_string_chk(&argvars[0]);
8646 initdir = get_tv_string_buf_chk(&argvars[1], buf);
8648 if (title == NULL || initdir == NULL)
8649 rettv->vval.v_string = NULL;
8650 else
8651 rettv->vval.v_string = do_browse(BROWSE_DIR,
8652 title, NULL, NULL, initdir, NULL, curbuf);
8653 #else
8654 rettv->vval.v_string = NULL;
8655 #endif
8656 rettv->v_type = VAR_STRING;
8659 static buf_T *find_buffer __ARGS((typval_T *avar));
8662 * Find a buffer by number or exact name.
8664 static buf_T *
8665 find_buffer(avar)
8666 typval_T *avar;
8668 buf_T *buf = NULL;
8670 if (avar->v_type == VAR_NUMBER)
8671 buf = buflist_findnr((int)avar->vval.v_number);
8672 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
8674 buf = buflist_findname_exp(avar->vval.v_string);
8675 if (buf == NULL)
8677 /* No full path name match, try a match with a URL or a "nofile"
8678 * buffer, these don't use the full path. */
8679 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8680 if (buf->b_fname != NULL
8681 && (path_with_url(buf->b_fname)
8682 #ifdef FEAT_QUICKFIX
8683 || bt_nofile(buf)
8684 #endif
8686 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
8687 break;
8690 return buf;
8694 * "bufexists(expr)" function
8696 static void
8697 f_bufexists(argvars, rettv)
8698 typval_T *argvars;
8699 typval_T *rettv;
8701 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
8705 * "buflisted(expr)" function
8707 static void
8708 f_buflisted(argvars, rettv)
8709 typval_T *argvars;
8710 typval_T *rettv;
8712 buf_T *buf;
8714 buf = find_buffer(&argvars[0]);
8715 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
8719 * "bufloaded(expr)" function
8721 static void
8722 f_bufloaded(argvars, rettv)
8723 typval_T *argvars;
8724 typval_T *rettv;
8726 buf_T *buf;
8728 buf = find_buffer(&argvars[0]);
8729 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
8732 static buf_T *get_buf_tv __ARGS((typval_T *tv));
8735 * Get buffer by number or pattern.
8737 static buf_T *
8738 get_buf_tv(tv)
8739 typval_T *tv;
8741 char_u *name = tv->vval.v_string;
8742 int save_magic;
8743 char_u *save_cpo;
8744 buf_T *buf;
8746 if (tv->v_type == VAR_NUMBER)
8747 return buflist_findnr((int)tv->vval.v_number);
8748 if (tv->v_type != VAR_STRING)
8749 return NULL;
8750 if (name == NULL || *name == NUL)
8751 return curbuf;
8752 if (name[0] == '$' && name[1] == NUL)
8753 return lastbuf;
8755 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
8756 save_magic = p_magic;
8757 p_magic = TRUE;
8758 save_cpo = p_cpo;
8759 p_cpo = (char_u *)"";
8761 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8762 TRUE, FALSE));
8764 p_magic = save_magic;
8765 p_cpo = save_cpo;
8767 /* If not found, try expanding the name, like done for bufexists(). */
8768 if (buf == NULL)
8769 buf = find_buffer(tv);
8771 return buf;
8775 * "bufname(expr)" function
8777 static void
8778 f_bufname(argvars, rettv)
8779 typval_T *argvars;
8780 typval_T *rettv;
8782 buf_T *buf;
8784 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8785 ++emsg_off;
8786 buf = get_buf_tv(&argvars[0]);
8787 rettv->v_type = VAR_STRING;
8788 if (buf != NULL && buf->b_fname != NULL)
8789 rettv->vval.v_string = vim_strsave(buf->b_fname);
8790 else
8791 rettv->vval.v_string = NULL;
8792 --emsg_off;
8796 * "bufnr(expr)" function
8798 static void
8799 f_bufnr(argvars, rettv)
8800 typval_T *argvars;
8801 typval_T *rettv;
8803 buf_T *buf;
8804 int error = FALSE;
8805 char_u *name;
8807 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8808 ++emsg_off;
8809 buf = get_buf_tv(&argvars[0]);
8810 --emsg_off;
8812 /* If the buffer isn't found and the second argument is not zero create a
8813 * new buffer. */
8814 if (buf == NULL
8815 && argvars[1].v_type != VAR_UNKNOWN
8816 && get_tv_number_chk(&argvars[1], &error) != 0
8817 && !error
8818 && (name = get_tv_string_chk(&argvars[0])) != NULL
8819 && !error)
8820 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8822 if (buf != NULL)
8823 rettv->vval.v_number = buf->b_fnum;
8824 else
8825 rettv->vval.v_number = -1;
8829 * "bufwinnr(nr)" function
8831 static void
8832 f_bufwinnr(argvars, rettv)
8833 typval_T *argvars;
8834 typval_T *rettv;
8836 #ifdef FEAT_WINDOWS
8837 win_T *wp;
8838 int winnr = 0;
8839 #endif
8840 buf_T *buf;
8842 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8843 ++emsg_off;
8844 buf = get_buf_tv(&argvars[0]);
8845 #ifdef FEAT_WINDOWS
8846 for (wp = firstwin; wp; wp = wp->w_next)
8848 ++winnr;
8849 if (wp->w_buffer == buf)
8850 break;
8852 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8853 #else
8854 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8855 #endif
8856 --emsg_off;
8860 * "byte2line(byte)" function
8862 /*ARGSUSED*/
8863 static void
8864 f_byte2line(argvars, rettv)
8865 typval_T *argvars;
8866 typval_T *rettv;
8868 #ifndef FEAT_BYTEOFF
8869 rettv->vval.v_number = -1;
8870 #else
8871 long boff = 0;
8873 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8874 if (boff < 0)
8875 rettv->vval.v_number = -1;
8876 else
8877 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8878 (linenr_T)0, &boff);
8879 #endif
8883 * "byteidx()" function
8885 /*ARGSUSED*/
8886 static void
8887 f_byteidx(argvars, rettv)
8888 typval_T *argvars;
8889 typval_T *rettv;
8891 #ifdef FEAT_MBYTE
8892 char_u *t;
8893 #endif
8894 char_u *str;
8895 long idx;
8897 str = get_tv_string_chk(&argvars[0]);
8898 idx = get_tv_number_chk(&argvars[1], NULL);
8899 rettv->vval.v_number = -1;
8900 if (str == NULL || idx < 0)
8901 return;
8903 #ifdef FEAT_MBYTE
8904 t = str;
8905 for ( ; idx > 0; idx--)
8907 if (*t == NUL) /* EOL reached */
8908 return;
8909 t += (*mb_ptr2len)(t);
8911 rettv->vval.v_number = (varnumber_T)(t - str);
8912 #else
8913 if ((size_t)idx <= STRLEN(str))
8914 rettv->vval.v_number = idx;
8915 #endif
8919 * "call(func, arglist)" function
8921 static void
8922 f_call(argvars, rettv)
8923 typval_T *argvars;
8924 typval_T *rettv;
8926 char_u *func;
8927 typval_T argv[MAX_FUNC_ARGS + 1];
8928 int argc = 0;
8929 listitem_T *item;
8930 int dummy;
8931 dict_T *selfdict = NULL;
8933 rettv->vval.v_number = 0;
8934 if (argvars[1].v_type != VAR_LIST)
8936 EMSG(_(e_listreq));
8937 return;
8939 if (argvars[1].vval.v_list == NULL)
8940 return;
8942 if (argvars[0].v_type == VAR_FUNC)
8943 func = argvars[0].vval.v_string;
8944 else
8945 func = get_tv_string(&argvars[0]);
8946 if (*func == NUL)
8947 return; /* type error or empty name */
8949 if (argvars[2].v_type != VAR_UNKNOWN)
8951 if (argvars[2].v_type != VAR_DICT)
8953 EMSG(_(e_dictreq));
8954 return;
8956 selfdict = argvars[2].vval.v_dict;
8959 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
8960 item = item->li_next)
8962 if (argc == MAX_FUNC_ARGS)
8964 EMSG(_("E699: Too many arguments"));
8965 break;
8967 /* Make a copy of each argument. This is needed to be able to set
8968 * v_lock to VAR_FIXED in the copy without changing the original list.
8970 copy_tv(&item->li_tv, &argv[argc++]);
8973 if (item == NULL)
8974 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
8975 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
8976 &dummy, TRUE, selfdict);
8978 /* Free the arguments. */
8979 while (argc > 0)
8980 clear_tv(&argv[--argc]);
8983 #ifdef FEAT_FLOAT
8985 * "ceil({float})" function
8987 static void
8988 f_ceil(argvars, rettv)
8989 typval_T *argvars;
8990 typval_T *rettv;
8992 float_T f;
8994 rettv->v_type = VAR_FLOAT;
8995 if (get_float_arg(argvars, &f) == OK)
8996 rettv->vval.v_float = ceil(f);
8997 else
8998 rettv->vval.v_float = 0.0;
9000 #endif
9003 * "changenr()" function
9005 /*ARGSUSED*/
9006 static void
9007 f_changenr(argvars, rettv)
9008 typval_T *argvars;
9009 typval_T *rettv;
9011 rettv->vval.v_number = curbuf->b_u_seq_cur;
9015 * "char2nr(string)" function
9017 static void
9018 f_char2nr(argvars, rettv)
9019 typval_T *argvars;
9020 typval_T *rettv;
9022 #ifdef FEAT_MBYTE
9023 if (has_mbyte)
9024 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
9025 else
9026 #endif
9027 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
9031 * "cindent(lnum)" function
9033 static void
9034 f_cindent(argvars, rettv)
9035 typval_T *argvars;
9036 typval_T *rettv;
9038 #ifdef FEAT_CINDENT
9039 pos_T pos;
9040 linenr_T lnum;
9042 pos = curwin->w_cursor;
9043 lnum = get_tv_lnum(argvars);
9044 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9046 curwin->w_cursor.lnum = lnum;
9047 rettv->vval.v_number = get_c_indent();
9048 curwin->w_cursor = pos;
9050 else
9051 #endif
9052 rettv->vval.v_number = -1;
9056 * "clearmatches()" function
9058 /*ARGSUSED*/
9059 static void
9060 f_clearmatches(argvars, rettv)
9061 typval_T *argvars;
9062 typval_T *rettv;
9064 #ifdef FEAT_SEARCH_EXTRA
9065 clear_matches(curwin);
9066 #endif
9070 * "col(string)" function
9072 static void
9073 f_col(argvars, rettv)
9074 typval_T *argvars;
9075 typval_T *rettv;
9077 colnr_T col = 0;
9078 pos_T *fp;
9079 int fnum = curbuf->b_fnum;
9081 fp = var2fpos(&argvars[0], FALSE, &fnum);
9082 if (fp != NULL && fnum == curbuf->b_fnum)
9084 if (fp->col == MAXCOL)
9086 /* '> can be MAXCOL, get the length of the line then */
9087 if (fp->lnum <= curbuf->b_ml.ml_line_count)
9088 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
9089 else
9090 col = MAXCOL;
9092 else
9094 col = fp->col + 1;
9095 #ifdef FEAT_VIRTUALEDIT
9096 /* col(".") when the cursor is on the NUL at the end of the line
9097 * because of "coladd" can be seen as an extra column. */
9098 if (virtual_active() && fp == &curwin->w_cursor)
9100 char_u *p = ml_get_cursor();
9102 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
9103 curwin->w_virtcol - curwin->w_cursor.coladd))
9105 # ifdef FEAT_MBYTE
9106 int l;
9108 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
9109 col += l;
9110 # else
9111 if (*p != NUL && p[1] == NUL)
9112 ++col;
9113 # endif
9116 #endif
9119 rettv->vval.v_number = col;
9122 #if defined(FEAT_INS_EXPAND)
9124 * "complete()" function
9126 /*ARGSUSED*/
9127 static void
9128 f_complete(argvars, rettv)
9129 typval_T *argvars;
9130 typval_T *rettv;
9132 int startcol;
9134 if ((State & INSERT) == 0)
9136 EMSG(_("E785: complete() can only be used in Insert mode"));
9137 return;
9140 /* Check for undo allowed here, because if something was already inserted
9141 * the line was already saved for undo and this check isn't done. */
9142 if (!undo_allowed())
9143 return;
9145 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
9147 EMSG(_(e_invarg));
9148 return;
9151 startcol = get_tv_number_chk(&argvars[0], NULL);
9152 if (startcol <= 0)
9153 return;
9155 set_completion(startcol - 1, argvars[1].vval.v_list);
9159 * "complete_add()" function
9161 /*ARGSUSED*/
9162 static void
9163 f_complete_add(argvars, rettv)
9164 typval_T *argvars;
9165 typval_T *rettv;
9167 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
9171 * "complete_check()" function
9173 /*ARGSUSED*/
9174 static void
9175 f_complete_check(argvars, rettv)
9176 typval_T *argvars;
9177 typval_T *rettv;
9179 int saved = RedrawingDisabled;
9181 RedrawingDisabled = 0;
9182 ins_compl_check_keys(0);
9183 rettv->vval.v_number = compl_interrupted;
9184 RedrawingDisabled = saved;
9186 #endif
9189 * "confirm(message, buttons[, default [, type]])" function
9191 /*ARGSUSED*/
9192 static void
9193 f_confirm(argvars, rettv)
9194 typval_T *argvars;
9195 typval_T *rettv;
9197 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
9198 char_u *message;
9199 char_u *buttons = NULL;
9200 char_u buf[NUMBUFLEN];
9201 char_u buf2[NUMBUFLEN];
9202 int def = 1;
9203 int type = VIM_GENERIC;
9204 char_u *typestr;
9205 int error = FALSE;
9207 message = get_tv_string_chk(&argvars[0]);
9208 if (message == NULL)
9209 error = TRUE;
9210 if (argvars[1].v_type != VAR_UNKNOWN)
9212 buttons = get_tv_string_buf_chk(&argvars[1], buf);
9213 if (buttons == NULL)
9214 error = TRUE;
9215 if (argvars[2].v_type != VAR_UNKNOWN)
9217 def = get_tv_number_chk(&argvars[2], &error);
9218 if (argvars[3].v_type != VAR_UNKNOWN)
9220 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
9221 if (typestr == NULL)
9222 error = TRUE;
9223 else
9225 switch (TOUPPER_ASC(*typestr))
9227 case 'E': type = VIM_ERROR; break;
9228 case 'Q': type = VIM_QUESTION; break;
9229 case 'I': type = VIM_INFO; break;
9230 case 'W': type = VIM_WARNING; break;
9231 case 'G': type = VIM_GENERIC; break;
9238 if (buttons == NULL || *buttons == NUL)
9239 buttons = (char_u *)_("&Ok");
9241 if (error)
9242 rettv->vval.v_number = 0;
9243 else
9244 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
9245 def, NULL);
9246 #else
9247 rettv->vval.v_number = 0;
9248 #endif
9252 * "copy()" function
9254 static void
9255 f_copy(argvars, rettv)
9256 typval_T *argvars;
9257 typval_T *rettv;
9259 item_copy(&argvars[0], rettv, FALSE, 0);
9262 #ifdef FEAT_FLOAT
9264 * "cos()" function
9266 static void
9267 f_cos(argvars, rettv)
9268 typval_T *argvars;
9269 typval_T *rettv;
9271 float_T f;
9273 rettv->v_type = VAR_FLOAT;
9274 if (get_float_arg(argvars, &f) == OK)
9275 rettv->vval.v_float = cos(f);
9276 else
9277 rettv->vval.v_float = 0.0;
9279 #endif
9282 * "count()" function
9284 static void
9285 f_count(argvars, rettv)
9286 typval_T *argvars;
9287 typval_T *rettv;
9289 long n = 0;
9290 int ic = FALSE;
9292 if (argvars[0].v_type == VAR_LIST)
9294 listitem_T *li;
9295 list_T *l;
9296 long idx;
9298 if ((l = argvars[0].vval.v_list) != NULL)
9300 li = l->lv_first;
9301 if (argvars[2].v_type != VAR_UNKNOWN)
9303 int error = FALSE;
9305 ic = get_tv_number_chk(&argvars[2], &error);
9306 if (argvars[3].v_type != VAR_UNKNOWN)
9308 idx = get_tv_number_chk(&argvars[3], &error);
9309 if (!error)
9311 li = list_find(l, idx);
9312 if (li == NULL)
9313 EMSGN(_(e_listidx), idx);
9316 if (error)
9317 li = NULL;
9320 for ( ; li != NULL; li = li->li_next)
9321 if (tv_equal(&li->li_tv, &argvars[1], ic))
9322 ++n;
9325 else if (argvars[0].v_type == VAR_DICT)
9327 int todo;
9328 dict_T *d;
9329 hashitem_T *hi;
9331 if ((d = argvars[0].vval.v_dict) != NULL)
9333 int error = FALSE;
9335 if (argvars[2].v_type != VAR_UNKNOWN)
9337 ic = get_tv_number_chk(&argvars[2], &error);
9338 if (argvars[3].v_type != VAR_UNKNOWN)
9339 EMSG(_(e_invarg));
9342 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
9343 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
9345 if (!HASHITEM_EMPTY(hi))
9347 --todo;
9348 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
9349 ++n;
9354 else
9355 EMSG2(_(e_listdictarg), "count()");
9356 rettv->vval.v_number = n;
9360 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
9362 * Checks the existence of a cscope connection.
9364 /*ARGSUSED*/
9365 static void
9366 f_cscope_connection(argvars, rettv)
9367 typval_T *argvars;
9368 typval_T *rettv;
9370 #ifdef FEAT_CSCOPE
9371 int num = 0;
9372 char_u *dbpath = NULL;
9373 char_u *prepend = NULL;
9374 char_u buf[NUMBUFLEN];
9376 if (argvars[0].v_type != VAR_UNKNOWN
9377 && argvars[1].v_type != VAR_UNKNOWN)
9379 num = (int)get_tv_number(&argvars[0]);
9380 dbpath = get_tv_string(&argvars[1]);
9381 if (argvars[2].v_type != VAR_UNKNOWN)
9382 prepend = get_tv_string_buf(&argvars[2], buf);
9385 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
9386 #else
9387 rettv->vval.v_number = 0;
9388 #endif
9392 * "cursor(lnum, col)" function
9394 * Moves the cursor to the specified line and column
9396 /*ARGSUSED*/
9397 static void
9398 f_cursor(argvars, rettv)
9399 typval_T *argvars;
9400 typval_T *rettv;
9402 long line, col;
9403 #ifdef FEAT_VIRTUALEDIT
9404 long coladd = 0;
9405 #endif
9407 if (argvars[1].v_type == VAR_UNKNOWN)
9409 pos_T pos;
9411 if (list2fpos(argvars, &pos, NULL) == FAIL)
9412 return;
9413 line = pos.lnum;
9414 col = pos.col;
9415 #ifdef FEAT_VIRTUALEDIT
9416 coladd = pos.coladd;
9417 #endif
9419 else
9421 line = get_tv_lnum(argvars);
9422 col = get_tv_number_chk(&argvars[1], NULL);
9423 #ifdef FEAT_VIRTUALEDIT
9424 if (argvars[2].v_type != VAR_UNKNOWN)
9425 coladd = get_tv_number_chk(&argvars[2], NULL);
9426 #endif
9428 if (line < 0 || col < 0
9429 #ifdef FEAT_VIRTUALEDIT
9430 || coladd < 0
9431 #endif
9433 return; /* type error; errmsg already given */
9434 if (line > 0)
9435 curwin->w_cursor.lnum = line;
9436 if (col > 0)
9437 curwin->w_cursor.col = col - 1;
9438 #ifdef FEAT_VIRTUALEDIT
9439 curwin->w_cursor.coladd = coladd;
9440 #endif
9442 /* Make sure the cursor is in a valid position. */
9443 check_cursor();
9444 #ifdef FEAT_MBYTE
9445 /* Correct cursor for multi-byte character. */
9446 if (has_mbyte)
9447 mb_adjust_cursor();
9448 #endif
9450 curwin->w_set_curswant = TRUE;
9454 * "deepcopy()" function
9456 static void
9457 f_deepcopy(argvars, rettv)
9458 typval_T *argvars;
9459 typval_T *rettv;
9461 int noref = 0;
9463 if (argvars[1].v_type != VAR_UNKNOWN)
9464 noref = get_tv_number_chk(&argvars[1], NULL);
9465 if (noref < 0 || noref > 1)
9466 EMSG(_(e_invarg));
9467 else
9468 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? ++current_copyID : 0);
9472 * "delete()" function
9474 static void
9475 f_delete(argvars, rettv)
9476 typval_T *argvars;
9477 typval_T *rettv;
9479 if (check_restricted() || check_secure())
9480 rettv->vval.v_number = -1;
9481 else
9482 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
9486 * "did_filetype()" function
9488 /*ARGSUSED*/
9489 static void
9490 f_did_filetype(argvars, rettv)
9491 typval_T *argvars;
9492 typval_T *rettv;
9494 #ifdef FEAT_AUTOCMD
9495 rettv->vval.v_number = did_filetype;
9496 #else
9497 rettv->vval.v_number = 0;
9498 #endif
9502 * "diff_filler()" function
9504 /*ARGSUSED*/
9505 static void
9506 f_diff_filler(argvars, rettv)
9507 typval_T *argvars;
9508 typval_T *rettv;
9510 #ifdef FEAT_DIFF
9511 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
9512 #endif
9516 * "diff_hlID()" function
9518 /*ARGSUSED*/
9519 static void
9520 f_diff_hlID(argvars, rettv)
9521 typval_T *argvars;
9522 typval_T *rettv;
9524 #ifdef FEAT_DIFF
9525 linenr_T lnum = get_tv_lnum(argvars);
9526 static linenr_T prev_lnum = 0;
9527 static int changedtick = 0;
9528 static int fnum = 0;
9529 static int change_start = 0;
9530 static int change_end = 0;
9531 static hlf_T hlID = (hlf_T)0;
9532 int filler_lines;
9533 int col;
9535 if (lnum < 0) /* ignore type error in {lnum} arg */
9536 lnum = 0;
9537 if (lnum != prev_lnum
9538 || changedtick != curbuf->b_changedtick
9539 || fnum != curbuf->b_fnum)
9541 /* New line, buffer, change: need to get the values. */
9542 filler_lines = diff_check(curwin, lnum);
9543 if (filler_lines < 0)
9545 if (filler_lines == -1)
9547 change_start = MAXCOL;
9548 change_end = -1;
9549 if (diff_find_change(curwin, lnum, &change_start, &change_end))
9550 hlID = HLF_ADD; /* added line */
9551 else
9552 hlID = HLF_CHD; /* changed line */
9554 else
9555 hlID = HLF_ADD; /* added line */
9557 else
9558 hlID = (hlf_T)0;
9559 prev_lnum = lnum;
9560 changedtick = curbuf->b_changedtick;
9561 fnum = curbuf->b_fnum;
9564 if (hlID == HLF_CHD || hlID == HLF_TXD)
9566 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
9567 if (col >= change_start && col <= change_end)
9568 hlID = HLF_TXD; /* changed text */
9569 else
9570 hlID = HLF_CHD; /* changed line */
9572 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
9573 #endif
9577 * "empty({expr})" function
9579 static void
9580 f_empty(argvars, rettv)
9581 typval_T *argvars;
9582 typval_T *rettv;
9584 int n;
9586 switch (argvars[0].v_type)
9588 case VAR_STRING:
9589 case VAR_FUNC:
9590 n = argvars[0].vval.v_string == NULL
9591 || *argvars[0].vval.v_string == NUL;
9592 break;
9593 case VAR_NUMBER:
9594 n = argvars[0].vval.v_number == 0;
9595 break;
9596 #ifdef FEAT_FLOAT
9597 case VAR_FLOAT:
9598 n = argvars[0].vval.v_float == 0.0;
9599 break;
9600 #endif
9601 case VAR_LIST:
9602 n = argvars[0].vval.v_list == NULL
9603 || argvars[0].vval.v_list->lv_first == NULL;
9604 break;
9605 case VAR_DICT:
9606 n = argvars[0].vval.v_dict == NULL
9607 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
9608 break;
9609 default:
9610 EMSG2(_(e_intern2), "f_empty()");
9611 n = 0;
9614 rettv->vval.v_number = n;
9618 * "escape({string}, {chars})" function
9620 static void
9621 f_escape(argvars, rettv)
9622 typval_T *argvars;
9623 typval_T *rettv;
9625 char_u buf[NUMBUFLEN];
9627 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
9628 get_tv_string_buf(&argvars[1], buf));
9629 rettv->v_type = VAR_STRING;
9633 * "eval()" function
9635 /*ARGSUSED*/
9636 static void
9637 f_eval(argvars, rettv)
9638 typval_T *argvars;
9639 typval_T *rettv;
9641 char_u *s;
9643 s = get_tv_string_chk(&argvars[0]);
9644 if (s != NULL)
9645 s = skipwhite(s);
9647 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
9649 rettv->v_type = VAR_NUMBER;
9650 rettv->vval.v_number = 0;
9652 else if (*s != NUL)
9653 EMSG(_(e_trailing));
9657 * "eventhandler()" function
9659 /*ARGSUSED*/
9660 static void
9661 f_eventhandler(argvars, rettv)
9662 typval_T *argvars;
9663 typval_T *rettv;
9665 rettv->vval.v_number = vgetc_busy;
9669 * "executable()" function
9671 static void
9672 f_executable(argvars, rettv)
9673 typval_T *argvars;
9674 typval_T *rettv;
9676 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
9680 * "exists()" function
9682 static void
9683 f_exists(argvars, rettv)
9684 typval_T *argvars;
9685 typval_T *rettv;
9687 char_u *p;
9688 char_u *name;
9689 int n = FALSE;
9690 int len = 0;
9692 p = get_tv_string(&argvars[0]);
9693 if (*p == '$') /* environment variable */
9695 /* first try "normal" environment variables (fast) */
9696 if (mch_getenv(p + 1) != NULL)
9697 n = TRUE;
9698 else
9700 /* try expanding things like $VIM and ${HOME} */
9701 p = expand_env_save(p);
9702 if (p != NULL && *p != '$')
9703 n = TRUE;
9704 vim_free(p);
9707 else if (*p == '&' || *p == '+') /* option */
9709 n = (get_option_tv(&p, NULL, TRUE) == OK);
9710 if (*skipwhite(p) != NUL)
9711 n = FALSE; /* trailing garbage */
9713 else if (*p == '*') /* internal or user defined function */
9715 n = function_exists(p + 1);
9717 else if (*p == ':')
9719 n = cmd_exists(p + 1);
9721 else if (*p == '#')
9723 #ifdef FEAT_AUTOCMD
9724 if (p[1] == '#')
9725 n = autocmd_supported(p + 2);
9726 else
9727 n = au_exists(p + 1);
9728 #endif
9730 else /* internal variable */
9732 char_u *tofree;
9733 typval_T tv;
9735 /* get_name_len() takes care of expanding curly braces */
9736 name = p;
9737 len = get_name_len(&p, &tofree, TRUE, FALSE);
9738 if (len > 0)
9740 if (tofree != NULL)
9741 name = tofree;
9742 n = (get_var_tv(name, len, &tv, FALSE) == OK);
9743 if (n)
9745 /* handle d.key, l[idx], f(expr) */
9746 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
9747 if (n)
9748 clear_tv(&tv);
9751 if (*p != NUL)
9752 n = FALSE;
9754 vim_free(tofree);
9757 rettv->vval.v_number = n;
9761 * "expand()" function
9763 static void
9764 f_expand(argvars, rettv)
9765 typval_T *argvars;
9766 typval_T *rettv;
9768 char_u *s;
9769 int len;
9770 char_u *errormsg;
9771 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
9772 expand_T xpc;
9773 int error = FALSE;
9775 rettv->v_type = VAR_STRING;
9776 s = get_tv_string(&argvars[0]);
9777 if (*s == '%' || *s == '#' || *s == '<')
9779 ++emsg_off;
9780 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
9781 --emsg_off;
9783 else
9785 /* When the optional second argument is non-zero, don't remove matches
9786 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
9787 if (argvars[1].v_type != VAR_UNKNOWN
9788 && get_tv_number_chk(&argvars[1], &error))
9789 flags |= WILD_KEEP_ALL;
9790 if (!error)
9792 ExpandInit(&xpc);
9793 xpc.xp_context = EXPAND_FILES;
9794 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
9796 else
9797 rettv->vval.v_string = NULL;
9802 * "extend(list, list [, idx])" function
9803 * "extend(dict, dict [, action])" function
9805 static void
9806 f_extend(argvars, rettv)
9807 typval_T *argvars;
9808 typval_T *rettv;
9810 rettv->vval.v_number = 0;
9811 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9813 list_T *l1, *l2;
9814 listitem_T *item;
9815 long before;
9816 int error = FALSE;
9818 l1 = argvars[0].vval.v_list;
9819 l2 = argvars[1].vval.v_list;
9820 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9821 && l2 != NULL)
9823 if (argvars[2].v_type != VAR_UNKNOWN)
9825 before = get_tv_number_chk(&argvars[2], &error);
9826 if (error)
9827 return; /* type error; errmsg already given */
9829 if (before == l1->lv_len)
9830 item = NULL;
9831 else
9833 item = list_find(l1, before);
9834 if (item == NULL)
9836 EMSGN(_(e_listidx), before);
9837 return;
9841 else
9842 item = NULL;
9843 list_extend(l1, l2, item);
9845 copy_tv(&argvars[0], rettv);
9848 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9850 dict_T *d1, *d2;
9851 dictitem_T *di1;
9852 char_u *action;
9853 int i;
9854 hashitem_T *hi2;
9855 int todo;
9857 d1 = argvars[0].vval.v_dict;
9858 d2 = argvars[1].vval.v_dict;
9859 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9860 && d2 != NULL)
9862 /* Check the third argument. */
9863 if (argvars[2].v_type != VAR_UNKNOWN)
9865 static char *(av[]) = {"keep", "force", "error"};
9867 action = get_tv_string_chk(&argvars[2]);
9868 if (action == NULL)
9869 return; /* type error; errmsg already given */
9870 for (i = 0; i < 3; ++i)
9871 if (STRCMP(action, av[i]) == 0)
9872 break;
9873 if (i == 3)
9875 EMSG2(_(e_invarg2), action);
9876 return;
9879 else
9880 action = (char_u *)"force";
9882 /* Go over all entries in the second dict and add them to the
9883 * first dict. */
9884 todo = (int)d2->dv_hashtab.ht_used;
9885 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9887 if (!HASHITEM_EMPTY(hi2))
9889 --todo;
9890 di1 = dict_find(d1, hi2->hi_key, -1);
9891 if (di1 == NULL)
9893 di1 = dictitem_copy(HI2DI(hi2));
9894 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9895 dictitem_free(di1);
9897 else if (*action == 'e')
9899 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9900 break;
9902 else if (*action == 'f')
9904 clear_tv(&di1->di_tv);
9905 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9910 copy_tv(&argvars[0], rettv);
9913 else
9914 EMSG2(_(e_listdictarg), "extend()");
9918 * "feedkeys()" function
9920 /*ARGSUSED*/
9921 static void
9922 f_feedkeys(argvars, rettv)
9923 typval_T *argvars;
9924 typval_T *rettv;
9926 int remap = TRUE;
9927 char_u *keys, *flags;
9928 char_u nbuf[NUMBUFLEN];
9929 int typed = FALSE;
9930 char_u *keys_esc;
9932 /* This is not allowed in the sandbox. If the commands would still be
9933 * executed in the sandbox it would be OK, but it probably happens later,
9934 * when "sandbox" is no longer set. */
9935 if (check_secure())
9936 return;
9938 rettv->vval.v_number = 0;
9939 keys = get_tv_string(&argvars[0]);
9940 if (*keys != NUL)
9942 if (argvars[1].v_type != VAR_UNKNOWN)
9944 flags = get_tv_string_buf(&argvars[1], nbuf);
9945 for ( ; *flags != NUL; ++flags)
9947 switch (*flags)
9949 case 'n': remap = FALSE; break;
9950 case 'm': remap = TRUE; break;
9951 case 't': typed = TRUE; break;
9956 /* Need to escape K_SPECIAL and CSI before putting the string in the
9957 * typeahead buffer. */
9958 keys_esc = vim_strsave_escape_csi(keys);
9959 if (keys_esc != NULL)
9961 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
9962 typebuf.tb_len, !typed, FALSE);
9963 vim_free(keys_esc);
9964 if (vgetc_busy)
9965 typebuf_was_filled = TRUE;
9971 * "filereadable()" function
9973 static void
9974 f_filereadable(argvars, rettv)
9975 typval_T *argvars;
9976 typval_T *rettv;
9978 int fd;
9979 char_u *p;
9980 int n;
9982 #ifndef O_NONBLOCK
9983 # define O_NONBLOCK 0
9984 #endif
9985 p = get_tv_string(&argvars[0]);
9986 if (*p && !mch_isdir(p) && (fd = mch_open((char *)p,
9987 O_RDONLY | O_NONBLOCK, 0)) >= 0)
9989 n = TRUE;
9990 close(fd);
9992 else
9993 n = FALSE;
9995 rettv->vval.v_number = n;
9999 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
10000 * rights to write into.
10002 static void
10003 f_filewritable(argvars, rettv)
10004 typval_T *argvars;
10005 typval_T *rettv;
10007 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
10010 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
10012 static void
10013 findfilendir(argvars, rettv, find_what)
10014 typval_T *argvars;
10015 typval_T *rettv;
10016 int find_what;
10018 #ifdef FEAT_SEARCHPATH
10019 char_u *fname;
10020 char_u *fresult = NULL;
10021 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
10022 char_u *p;
10023 char_u pathbuf[NUMBUFLEN];
10024 int count = 1;
10025 int first = TRUE;
10026 int error = FALSE;
10027 #endif
10029 rettv->vval.v_string = NULL;
10030 rettv->v_type = VAR_STRING;
10032 #ifdef FEAT_SEARCHPATH
10033 fname = get_tv_string(&argvars[0]);
10035 if (argvars[1].v_type != VAR_UNKNOWN)
10037 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
10038 if (p == NULL)
10039 error = TRUE;
10040 else
10042 if (*p != NUL)
10043 path = p;
10045 if (argvars[2].v_type != VAR_UNKNOWN)
10046 count = get_tv_number_chk(&argvars[2], &error);
10050 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
10051 error = TRUE;
10053 if (*fname != NUL && !error)
10057 if (rettv->v_type == VAR_STRING)
10058 vim_free(fresult);
10059 fresult = find_file_in_path_option(first ? fname : NULL,
10060 first ? (int)STRLEN(fname) : 0,
10061 0, first, path,
10062 find_what,
10063 curbuf->b_ffname,
10064 find_what == FINDFILE_DIR
10065 ? (char_u *)"" : curbuf->b_p_sua);
10066 first = FALSE;
10068 if (fresult != NULL && rettv->v_type == VAR_LIST)
10069 list_append_string(rettv->vval.v_list, fresult, -1);
10071 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
10074 if (rettv->v_type == VAR_STRING)
10075 rettv->vval.v_string = fresult;
10076 #endif
10079 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
10080 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
10083 * Implementation of map() and filter().
10085 static void
10086 filter_map(argvars, rettv, map)
10087 typval_T *argvars;
10088 typval_T *rettv;
10089 int map;
10091 char_u buf[NUMBUFLEN];
10092 char_u *expr;
10093 listitem_T *li, *nli;
10094 list_T *l = NULL;
10095 dictitem_T *di;
10096 hashtab_T *ht;
10097 hashitem_T *hi;
10098 dict_T *d = NULL;
10099 typval_T save_val;
10100 typval_T save_key;
10101 int rem;
10102 int todo;
10103 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
10104 int save_did_emsg;
10106 rettv->vval.v_number = 0;
10107 if (argvars[0].v_type == VAR_LIST)
10109 if ((l = argvars[0].vval.v_list) == NULL
10110 || (map && tv_check_lock(l->lv_lock, ermsg)))
10111 return;
10113 else if (argvars[0].v_type == VAR_DICT)
10115 if ((d = argvars[0].vval.v_dict) == NULL
10116 || (map && tv_check_lock(d->dv_lock, ermsg)))
10117 return;
10119 else
10121 EMSG2(_(e_listdictarg), ermsg);
10122 return;
10125 expr = get_tv_string_buf_chk(&argvars[1], buf);
10126 /* On type errors, the preceding call has already displayed an error
10127 * message. Avoid a misleading error message for an empty string that
10128 * was not passed as argument. */
10129 if (expr != NULL)
10131 prepare_vimvar(VV_VAL, &save_val);
10132 expr = skipwhite(expr);
10134 /* We reset "did_emsg" to be able to detect whether an error
10135 * occurred during evaluation of the expression. */
10136 save_did_emsg = did_emsg;
10137 did_emsg = FALSE;
10139 if (argvars[0].v_type == VAR_DICT)
10141 prepare_vimvar(VV_KEY, &save_key);
10142 vimvars[VV_KEY].vv_type = VAR_STRING;
10144 ht = &d->dv_hashtab;
10145 hash_lock(ht);
10146 todo = (int)ht->ht_used;
10147 for (hi = ht->ht_array; todo > 0; ++hi)
10149 if (!HASHITEM_EMPTY(hi))
10151 --todo;
10152 di = HI2DI(hi);
10153 if (tv_check_lock(di->di_tv.v_lock, ermsg))
10154 break;
10155 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
10156 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
10157 || did_emsg)
10158 break;
10159 if (!map && rem)
10160 dictitem_remove(d, di);
10161 clear_tv(&vimvars[VV_KEY].vv_tv);
10164 hash_unlock(ht);
10166 restore_vimvar(VV_KEY, &save_key);
10168 else
10170 for (li = l->lv_first; li != NULL; li = nli)
10172 if (tv_check_lock(li->li_tv.v_lock, ermsg))
10173 break;
10174 nli = li->li_next;
10175 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
10176 || did_emsg)
10177 break;
10178 if (!map && rem)
10179 listitem_remove(l, li);
10183 restore_vimvar(VV_VAL, &save_val);
10185 did_emsg |= save_did_emsg;
10188 copy_tv(&argvars[0], rettv);
10191 static int
10192 filter_map_one(tv, expr, map, remp)
10193 typval_T *tv;
10194 char_u *expr;
10195 int map;
10196 int *remp;
10198 typval_T rettv;
10199 char_u *s;
10200 int retval = FAIL;
10202 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
10203 s = expr;
10204 if (eval1(&s, &rettv, TRUE) == FAIL)
10205 goto theend;
10206 if (*s != NUL) /* check for trailing chars after expr */
10208 EMSG2(_(e_invexpr2), s);
10209 goto theend;
10211 if (map)
10213 /* map(): replace the list item value */
10214 clear_tv(tv);
10215 rettv.v_lock = 0;
10216 *tv = rettv;
10218 else
10220 int error = FALSE;
10222 /* filter(): when expr is zero remove the item */
10223 *remp = (get_tv_number_chk(&rettv, &error) == 0);
10224 clear_tv(&rettv);
10225 /* On type error, nothing has been removed; return FAIL to stop the
10226 * loop. The error message was given by get_tv_number_chk(). */
10227 if (error)
10228 goto theend;
10230 retval = OK;
10231 theend:
10232 clear_tv(&vimvars[VV_VAL].vv_tv);
10233 return retval;
10237 * "filter()" function
10239 static void
10240 f_filter(argvars, rettv)
10241 typval_T *argvars;
10242 typval_T *rettv;
10244 filter_map(argvars, rettv, FALSE);
10248 * "finddir({fname}[, {path}[, {count}]])" function
10250 static void
10251 f_finddir(argvars, rettv)
10252 typval_T *argvars;
10253 typval_T *rettv;
10255 findfilendir(argvars, rettv, FINDFILE_DIR);
10259 * "findfile({fname}[, {path}[, {count}]])" function
10261 static void
10262 f_findfile(argvars, rettv)
10263 typval_T *argvars;
10264 typval_T *rettv;
10266 findfilendir(argvars, rettv, FINDFILE_FILE);
10269 #ifdef FEAT_FLOAT
10271 * "float2nr({float})" function
10273 static void
10274 f_float2nr(argvars, rettv)
10275 typval_T *argvars;
10276 typval_T *rettv;
10278 float_T f;
10280 if (get_float_arg(argvars, &f) == OK)
10282 if (f < -0x7fffffff)
10283 rettv->vval.v_number = -0x7fffffff;
10284 else if (f > 0x7fffffff)
10285 rettv->vval.v_number = 0x7fffffff;
10286 else
10287 rettv->vval.v_number = (varnumber_T)f;
10289 else
10290 rettv->vval.v_number = 0;
10294 * "floor({float})" function
10296 static void
10297 f_floor(argvars, rettv)
10298 typval_T *argvars;
10299 typval_T *rettv;
10301 float_T f;
10303 rettv->v_type = VAR_FLOAT;
10304 if (get_float_arg(argvars, &f) == OK)
10305 rettv->vval.v_float = floor(f);
10306 else
10307 rettv->vval.v_float = 0.0;
10309 #endif
10312 * "fnameescape({string})" function
10314 static void
10315 f_fnameescape(argvars, rettv)
10316 typval_T *argvars;
10317 typval_T *rettv;
10319 rettv->vval.v_string = vim_strsave_fnameescape(
10320 get_tv_string(&argvars[0]), FALSE);
10321 rettv->v_type = VAR_STRING;
10325 * "fnamemodify({fname}, {mods})" function
10327 static void
10328 f_fnamemodify(argvars, rettv)
10329 typval_T *argvars;
10330 typval_T *rettv;
10332 char_u *fname;
10333 char_u *mods;
10334 int usedlen = 0;
10335 int len;
10336 char_u *fbuf = NULL;
10337 char_u buf[NUMBUFLEN];
10339 fname = get_tv_string_chk(&argvars[0]);
10340 mods = get_tv_string_buf_chk(&argvars[1], buf);
10341 if (fname == NULL || mods == NULL)
10342 fname = NULL;
10343 else
10345 len = (int)STRLEN(fname);
10346 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
10349 rettv->v_type = VAR_STRING;
10350 if (fname == NULL)
10351 rettv->vval.v_string = NULL;
10352 else
10353 rettv->vval.v_string = vim_strnsave(fname, len);
10354 vim_free(fbuf);
10357 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
10360 * "foldclosed()" function
10362 static void
10363 foldclosed_both(argvars, rettv, end)
10364 typval_T *argvars;
10365 typval_T *rettv;
10366 int end;
10368 #ifdef FEAT_FOLDING
10369 linenr_T lnum;
10370 linenr_T first, last;
10372 lnum = get_tv_lnum(argvars);
10373 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10375 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
10377 if (end)
10378 rettv->vval.v_number = (varnumber_T)last;
10379 else
10380 rettv->vval.v_number = (varnumber_T)first;
10381 return;
10384 #endif
10385 rettv->vval.v_number = -1;
10389 * "foldclosed()" function
10391 static void
10392 f_foldclosed(argvars, rettv)
10393 typval_T *argvars;
10394 typval_T *rettv;
10396 foldclosed_both(argvars, rettv, FALSE);
10400 * "foldclosedend()" function
10402 static void
10403 f_foldclosedend(argvars, rettv)
10404 typval_T *argvars;
10405 typval_T *rettv;
10407 foldclosed_both(argvars, rettv, TRUE);
10411 * "foldlevel()" function
10413 static void
10414 f_foldlevel(argvars, rettv)
10415 typval_T *argvars;
10416 typval_T *rettv;
10418 #ifdef FEAT_FOLDING
10419 linenr_T lnum;
10421 lnum = get_tv_lnum(argvars);
10422 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10423 rettv->vval.v_number = foldLevel(lnum);
10424 else
10425 #endif
10426 rettv->vval.v_number = 0;
10430 * "foldtext()" function
10432 /*ARGSUSED*/
10433 static void
10434 f_foldtext(argvars, rettv)
10435 typval_T *argvars;
10436 typval_T *rettv;
10438 #ifdef FEAT_FOLDING
10439 linenr_T lnum;
10440 char_u *s;
10441 char_u *r;
10442 int len;
10443 char *txt;
10444 #endif
10446 rettv->v_type = VAR_STRING;
10447 rettv->vval.v_string = NULL;
10448 #ifdef FEAT_FOLDING
10449 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
10450 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
10451 <= curbuf->b_ml.ml_line_count
10452 && vimvars[VV_FOLDDASHES].vv_str != NULL)
10454 /* Find first non-empty line in the fold. */
10455 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
10456 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10458 if (!linewhite(lnum))
10459 break;
10460 ++lnum;
10463 /* Find interesting text in this line. */
10464 s = skipwhite(ml_get(lnum));
10465 /* skip C comment-start */
10466 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
10468 s = skipwhite(s + 2);
10469 if (*skipwhite(s) == NUL
10470 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10472 s = skipwhite(ml_get(lnum + 1));
10473 if (*s == '*')
10474 s = skipwhite(s + 1);
10477 txt = _("+-%s%3ld lines: ");
10478 r = alloc((unsigned)(STRLEN(txt)
10479 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
10480 + 20 /* for %3ld */
10481 + STRLEN(s))); /* concatenated */
10482 if (r != NULL)
10484 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
10485 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
10486 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
10487 len = (int)STRLEN(r);
10488 STRCAT(r, s);
10489 /* remove 'foldmarker' and 'commentstring' */
10490 foldtext_cleanup(r + len);
10491 rettv->vval.v_string = r;
10494 #endif
10498 * "foldtextresult(lnum)" function
10500 /*ARGSUSED*/
10501 static void
10502 f_foldtextresult(argvars, rettv)
10503 typval_T *argvars;
10504 typval_T *rettv;
10506 #ifdef FEAT_FOLDING
10507 linenr_T lnum;
10508 char_u *text;
10509 char_u buf[51];
10510 foldinfo_T foldinfo;
10511 int fold_count;
10512 #endif
10514 rettv->v_type = VAR_STRING;
10515 rettv->vval.v_string = NULL;
10516 #ifdef FEAT_FOLDING
10517 lnum = get_tv_lnum(argvars);
10518 /* treat illegal types and illegal string values for {lnum} the same */
10519 if (lnum < 0)
10520 lnum = 0;
10521 fold_count = foldedCount(curwin, lnum, &foldinfo);
10522 if (fold_count > 0)
10524 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
10525 &foldinfo, buf);
10526 if (text == buf)
10527 text = vim_strsave(text);
10528 rettv->vval.v_string = text;
10530 #endif
10534 * "foreground()" function
10536 /*ARGSUSED*/
10537 static void
10538 f_foreground(argvars, rettv)
10539 typval_T *argvars;
10540 typval_T *rettv;
10542 rettv->vval.v_number = 0;
10543 #ifdef FEAT_GUI
10544 if (gui.in_use)
10545 gui_mch_set_foreground();
10546 #else
10547 # ifdef WIN32
10548 win32_set_foreground();
10549 # endif
10550 #endif
10554 * "function()" function
10556 /*ARGSUSED*/
10557 static void
10558 f_function(argvars, rettv)
10559 typval_T *argvars;
10560 typval_T *rettv;
10562 char_u *s;
10564 rettv->vval.v_number = 0;
10565 s = get_tv_string(&argvars[0]);
10566 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
10567 EMSG2(_(e_invarg2), s);
10568 /* Don't check an autoload name for existence here. */
10569 else if (vim_strchr(s, AUTOLOAD_CHAR) == NULL && !function_exists(s))
10570 EMSG2(_("E700: Unknown function: %s"), s);
10571 else
10573 rettv->vval.v_string = vim_strsave(s);
10574 rettv->v_type = VAR_FUNC;
10579 * "garbagecollect()" function
10581 /*ARGSUSED*/
10582 static void
10583 f_garbagecollect(argvars, rettv)
10584 typval_T *argvars;
10585 typval_T *rettv;
10587 /* This is postponed until we are back at the toplevel, because we may be
10588 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
10589 want_garbage_collect = TRUE;
10591 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
10592 garbage_collect_at_exit = TRUE;
10596 * "get()" function
10598 static void
10599 f_get(argvars, rettv)
10600 typval_T *argvars;
10601 typval_T *rettv;
10603 listitem_T *li;
10604 list_T *l;
10605 dictitem_T *di;
10606 dict_T *d;
10607 typval_T *tv = NULL;
10609 if (argvars[0].v_type == VAR_LIST)
10611 if ((l = argvars[0].vval.v_list) != NULL)
10613 int error = FALSE;
10615 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
10616 if (!error && li != NULL)
10617 tv = &li->li_tv;
10620 else if (argvars[0].v_type == VAR_DICT)
10622 if ((d = argvars[0].vval.v_dict) != NULL)
10624 di = dict_find(d, get_tv_string(&argvars[1]), -1);
10625 if (di != NULL)
10626 tv = &di->di_tv;
10629 else
10630 EMSG2(_(e_listdictarg), "get()");
10632 if (tv == NULL)
10634 if (argvars[2].v_type == VAR_UNKNOWN)
10635 rettv->vval.v_number = 0;
10636 else
10637 copy_tv(&argvars[2], rettv);
10639 else
10640 copy_tv(tv, rettv);
10643 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
10646 * Get line or list of lines from buffer "buf" into "rettv".
10647 * Return a range (from start to end) of lines in rettv from the specified
10648 * buffer.
10649 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
10651 static void
10652 get_buffer_lines(buf, start, end, retlist, rettv)
10653 buf_T *buf;
10654 linenr_T start;
10655 linenr_T end;
10656 int retlist;
10657 typval_T *rettv;
10659 char_u *p;
10661 if (retlist)
10663 if (rettv_list_alloc(rettv) == FAIL)
10664 return;
10666 else
10667 rettv->vval.v_number = 0;
10669 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
10670 return;
10672 if (!retlist)
10674 if (start >= 1 && start <= buf->b_ml.ml_line_count)
10675 p = ml_get_buf(buf, start, FALSE);
10676 else
10677 p = (char_u *)"";
10679 rettv->v_type = VAR_STRING;
10680 rettv->vval.v_string = vim_strsave(p);
10682 else
10684 if (end < start)
10685 return;
10687 if (start < 1)
10688 start = 1;
10689 if (end > buf->b_ml.ml_line_count)
10690 end = buf->b_ml.ml_line_count;
10691 while (start <= end)
10692 if (list_append_string(rettv->vval.v_list,
10693 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
10694 break;
10699 * "getbufline()" function
10701 static void
10702 f_getbufline(argvars, rettv)
10703 typval_T *argvars;
10704 typval_T *rettv;
10706 linenr_T lnum;
10707 linenr_T end;
10708 buf_T *buf;
10710 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10711 ++emsg_off;
10712 buf = get_buf_tv(&argvars[0]);
10713 --emsg_off;
10715 lnum = get_tv_lnum_buf(&argvars[1], buf);
10716 if (argvars[2].v_type == VAR_UNKNOWN)
10717 end = lnum;
10718 else
10719 end = get_tv_lnum_buf(&argvars[2], buf);
10721 get_buffer_lines(buf, lnum, end, TRUE, rettv);
10725 * "getbufvar()" function
10727 static void
10728 f_getbufvar(argvars, rettv)
10729 typval_T *argvars;
10730 typval_T *rettv;
10732 buf_T *buf;
10733 buf_T *save_curbuf;
10734 char_u *varname;
10735 dictitem_T *v;
10737 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10738 varname = get_tv_string_chk(&argvars[1]);
10739 ++emsg_off;
10740 buf = get_buf_tv(&argvars[0]);
10742 rettv->v_type = VAR_STRING;
10743 rettv->vval.v_string = NULL;
10745 if (buf != NULL && varname != NULL)
10747 /* set curbuf to be our buf, temporarily */
10748 save_curbuf = curbuf;
10749 curbuf = buf;
10751 if (*varname == '&') /* buffer-local-option */
10752 get_option_tv(&varname, rettv, TRUE);
10753 else
10755 if (*varname == NUL)
10756 /* let getbufvar({nr}, "") return the "b:" dictionary. The
10757 * scope prefix before the NUL byte is required by
10758 * find_var_in_ht(). */
10759 varname = (char_u *)"b:" + 2;
10760 /* look up the variable */
10761 v = find_var_in_ht(&curbuf->b_vars.dv_hashtab, varname, FALSE);
10762 if (v != NULL)
10763 copy_tv(&v->di_tv, rettv);
10766 /* restore previous notion of curbuf */
10767 curbuf = save_curbuf;
10770 --emsg_off;
10774 * "getchar()" function
10776 static void
10777 f_getchar(argvars, rettv)
10778 typval_T *argvars;
10779 typval_T *rettv;
10781 varnumber_T n;
10782 int error = FALSE;
10784 /* Position the cursor. Needed after a message that ends in a space. */
10785 windgoto(msg_row, msg_col);
10787 ++no_mapping;
10788 ++allow_keys;
10789 for (;;)
10791 if (argvars[0].v_type == VAR_UNKNOWN)
10792 /* getchar(): blocking wait. */
10793 n = safe_vgetc();
10794 else if (get_tv_number_chk(&argvars[0], &error) == 1)
10795 /* getchar(1): only check if char avail */
10796 n = vpeekc();
10797 else if (error || vpeekc() == NUL)
10798 /* illegal argument or getchar(0) and no char avail: return zero */
10799 n = 0;
10800 else
10801 /* getchar(0) and char avail: return char */
10802 n = safe_vgetc();
10803 if (n == K_IGNORE)
10804 continue;
10805 break;
10807 --no_mapping;
10808 --allow_keys;
10810 vimvars[VV_MOUSE_WIN].vv_nr = 0;
10811 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
10812 vimvars[VV_MOUSE_COL].vv_nr = 0;
10814 rettv->vval.v_number = n;
10815 if (IS_SPECIAL(n) || mod_mask != 0)
10817 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
10818 int i = 0;
10820 /* Turn a special key into three bytes, plus modifier. */
10821 if (mod_mask != 0)
10823 temp[i++] = K_SPECIAL;
10824 temp[i++] = KS_MODIFIER;
10825 temp[i++] = mod_mask;
10827 if (IS_SPECIAL(n))
10829 temp[i++] = K_SPECIAL;
10830 temp[i++] = K_SECOND(n);
10831 temp[i++] = K_THIRD(n);
10833 #ifdef FEAT_MBYTE
10834 else if (has_mbyte)
10835 i += (*mb_char2bytes)(n, temp + i);
10836 #endif
10837 else
10838 temp[i++] = n;
10839 temp[i++] = NUL;
10840 rettv->v_type = VAR_STRING;
10841 rettv->vval.v_string = vim_strsave(temp);
10843 #ifdef FEAT_MOUSE
10844 if (n == K_LEFTMOUSE
10845 || n == K_LEFTMOUSE_NM
10846 || n == K_LEFTDRAG
10847 || n == K_LEFTRELEASE
10848 || n == K_LEFTRELEASE_NM
10849 || n == K_MIDDLEMOUSE
10850 || n == K_MIDDLEDRAG
10851 || n == K_MIDDLERELEASE
10852 || n == K_RIGHTMOUSE
10853 || n == K_RIGHTDRAG
10854 || n == K_RIGHTRELEASE
10855 || n == K_X1MOUSE
10856 || n == K_X1DRAG
10857 || n == K_X1RELEASE
10858 || n == K_X2MOUSE
10859 || n == K_X2DRAG
10860 || n == K_X2RELEASE
10861 || n == K_MOUSEDOWN
10862 || n == K_MOUSEUP)
10864 int row = mouse_row;
10865 int col = mouse_col;
10866 win_T *win;
10867 linenr_T lnum;
10868 # ifdef FEAT_WINDOWS
10869 win_T *wp;
10870 # endif
10871 int winnr = 1;
10873 if (row >= 0 && col >= 0)
10875 /* Find the window at the mouse coordinates and compute the
10876 * text position. */
10877 win = mouse_find_win(&row, &col);
10878 (void)mouse_comp_pos(win, &row, &col, &lnum);
10879 # ifdef FEAT_WINDOWS
10880 for (wp = firstwin; wp != win; wp = wp->w_next)
10881 ++winnr;
10882 # endif
10883 vimvars[VV_MOUSE_WIN].vv_nr = winnr;
10884 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
10885 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
10888 #endif
10893 * "getcharmod()" function
10895 /*ARGSUSED*/
10896 static void
10897 f_getcharmod(argvars, rettv)
10898 typval_T *argvars;
10899 typval_T *rettv;
10901 rettv->vval.v_number = mod_mask;
10905 * "getcmdline()" function
10907 /*ARGSUSED*/
10908 static void
10909 f_getcmdline(argvars, rettv)
10910 typval_T *argvars;
10911 typval_T *rettv;
10913 rettv->v_type = VAR_STRING;
10914 rettv->vval.v_string = get_cmdline_str();
10918 * "getcmdpos()" function
10920 /*ARGSUSED*/
10921 static void
10922 f_getcmdpos(argvars, rettv)
10923 typval_T *argvars;
10924 typval_T *rettv;
10926 rettv->vval.v_number = get_cmdline_pos() + 1;
10930 * "getcmdtype()" function
10932 /*ARGSUSED*/
10933 static void
10934 f_getcmdtype(argvars, rettv)
10935 typval_T *argvars;
10936 typval_T *rettv;
10938 rettv->v_type = VAR_STRING;
10939 rettv->vval.v_string = alloc(2);
10940 if (rettv->vval.v_string != NULL)
10942 rettv->vval.v_string[0] = get_cmdline_type();
10943 rettv->vval.v_string[1] = NUL;
10948 * "getcwd()" function
10950 /*ARGSUSED*/
10951 static void
10952 f_getcwd(argvars, rettv)
10953 typval_T *argvars;
10954 typval_T *rettv;
10956 char_u cwd[MAXPATHL];
10958 rettv->v_type = VAR_STRING;
10959 if (mch_dirname(cwd, MAXPATHL) == FAIL)
10960 rettv->vval.v_string = NULL;
10961 else
10963 rettv->vval.v_string = vim_strsave(cwd);
10964 #ifdef BACKSLASH_IN_FILENAME
10965 if (rettv->vval.v_string != NULL)
10966 slash_adjust(rettv->vval.v_string);
10967 #endif
10972 * "getfontname()" function
10974 /*ARGSUSED*/
10975 static void
10976 f_getfontname(argvars, rettv)
10977 typval_T *argvars;
10978 typval_T *rettv;
10980 rettv->v_type = VAR_STRING;
10981 rettv->vval.v_string = NULL;
10982 #ifdef FEAT_GUI
10983 if (gui.in_use)
10985 GuiFont font;
10986 char_u *name = NULL;
10988 if (argvars[0].v_type == VAR_UNKNOWN)
10990 /* Get the "Normal" font. Either the name saved by
10991 * hl_set_font_name() or from the font ID. */
10992 font = gui.norm_font;
10993 name = hl_get_font_name();
10995 else
10997 name = get_tv_string(&argvars[0]);
10998 if (STRCMP(name, "*") == 0) /* don't use font dialog */
10999 return;
11000 font = gui_mch_get_font(name, FALSE);
11001 if (font == NOFONT)
11002 return; /* Invalid font name, return empty string. */
11004 rettv->vval.v_string = gui_mch_get_fontname(font, name);
11005 if (argvars[0].v_type != VAR_UNKNOWN)
11006 gui_mch_free_font(font);
11008 #endif
11012 * "getfperm({fname})" function
11014 static void
11015 f_getfperm(argvars, rettv)
11016 typval_T *argvars;
11017 typval_T *rettv;
11019 char_u *fname;
11020 struct stat st;
11021 char_u *perm = NULL;
11022 char_u flags[] = "rwx";
11023 int i;
11025 fname = get_tv_string(&argvars[0]);
11027 rettv->v_type = VAR_STRING;
11028 if (mch_stat((char *)fname, &st) >= 0)
11030 perm = vim_strsave((char_u *)"---------");
11031 if (perm != NULL)
11033 for (i = 0; i < 9; i++)
11035 if (st.st_mode & (1 << (8 - i)))
11036 perm[i] = flags[i % 3];
11040 rettv->vval.v_string = perm;
11044 * "getfsize({fname})" function
11046 static void
11047 f_getfsize(argvars, rettv)
11048 typval_T *argvars;
11049 typval_T *rettv;
11051 char_u *fname;
11052 struct stat st;
11054 fname = get_tv_string(&argvars[0]);
11056 rettv->v_type = VAR_NUMBER;
11058 if (mch_stat((char *)fname, &st) >= 0)
11060 if (mch_isdir(fname))
11061 rettv->vval.v_number = 0;
11062 else
11064 rettv->vval.v_number = (varnumber_T)st.st_size;
11066 /* non-perfect check for overflow */
11067 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
11068 rettv->vval.v_number = -2;
11071 else
11072 rettv->vval.v_number = -1;
11076 * "getftime({fname})" function
11078 static void
11079 f_getftime(argvars, rettv)
11080 typval_T *argvars;
11081 typval_T *rettv;
11083 char_u *fname;
11084 struct stat st;
11086 fname = get_tv_string(&argvars[0]);
11088 if (mch_stat((char *)fname, &st) >= 0)
11089 rettv->vval.v_number = (varnumber_T)st.st_mtime;
11090 else
11091 rettv->vval.v_number = -1;
11095 * "getftype({fname})" function
11097 static void
11098 f_getftype(argvars, rettv)
11099 typval_T *argvars;
11100 typval_T *rettv;
11102 char_u *fname;
11103 struct stat st;
11104 char_u *type = NULL;
11105 char *t;
11107 fname = get_tv_string(&argvars[0]);
11109 rettv->v_type = VAR_STRING;
11110 if (mch_lstat((char *)fname, &st) >= 0)
11112 #ifdef S_ISREG
11113 if (S_ISREG(st.st_mode))
11114 t = "file";
11115 else if (S_ISDIR(st.st_mode))
11116 t = "dir";
11117 # ifdef S_ISLNK
11118 else if (S_ISLNK(st.st_mode))
11119 t = "link";
11120 # endif
11121 # ifdef S_ISBLK
11122 else if (S_ISBLK(st.st_mode))
11123 t = "bdev";
11124 # endif
11125 # ifdef S_ISCHR
11126 else if (S_ISCHR(st.st_mode))
11127 t = "cdev";
11128 # endif
11129 # ifdef S_ISFIFO
11130 else if (S_ISFIFO(st.st_mode))
11131 t = "fifo";
11132 # endif
11133 # ifdef S_ISSOCK
11134 else if (S_ISSOCK(st.st_mode))
11135 t = "fifo";
11136 # endif
11137 else
11138 t = "other";
11139 #else
11140 # ifdef S_IFMT
11141 switch (st.st_mode & S_IFMT)
11143 case S_IFREG: t = "file"; break;
11144 case S_IFDIR: t = "dir"; break;
11145 # ifdef S_IFLNK
11146 case S_IFLNK: t = "link"; break;
11147 # endif
11148 # ifdef S_IFBLK
11149 case S_IFBLK: t = "bdev"; break;
11150 # endif
11151 # ifdef S_IFCHR
11152 case S_IFCHR: t = "cdev"; break;
11153 # endif
11154 # ifdef S_IFIFO
11155 case S_IFIFO: t = "fifo"; break;
11156 # endif
11157 # ifdef S_IFSOCK
11158 case S_IFSOCK: t = "socket"; break;
11159 # endif
11160 default: t = "other";
11162 # else
11163 if (mch_isdir(fname))
11164 t = "dir";
11165 else
11166 t = "file";
11167 # endif
11168 #endif
11169 type = vim_strsave((char_u *)t);
11171 rettv->vval.v_string = type;
11175 * "getline(lnum, [end])" function
11177 static void
11178 f_getline(argvars, rettv)
11179 typval_T *argvars;
11180 typval_T *rettv;
11182 linenr_T lnum;
11183 linenr_T end;
11184 int retlist;
11186 lnum = get_tv_lnum(argvars);
11187 if (argvars[1].v_type == VAR_UNKNOWN)
11189 end = 0;
11190 retlist = FALSE;
11192 else
11194 end = get_tv_lnum(&argvars[1]);
11195 retlist = TRUE;
11198 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
11202 * "getmatches()" function
11204 /*ARGSUSED*/
11205 static void
11206 f_getmatches(argvars, rettv)
11207 typval_T *argvars;
11208 typval_T *rettv;
11210 #ifdef FEAT_SEARCH_EXTRA
11211 dict_T *dict;
11212 matchitem_T *cur = curwin->w_match_head;
11214 rettv->vval.v_number = 0;
11216 if (rettv_list_alloc(rettv) == OK)
11218 while (cur != NULL)
11220 dict = dict_alloc();
11221 if (dict == NULL)
11222 return;
11223 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
11224 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
11225 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
11226 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
11227 list_append_dict(rettv->vval.v_list, dict);
11228 cur = cur->next;
11231 #endif
11235 * "getpid()" function
11237 /*ARGSUSED*/
11238 static void
11239 f_getpid(argvars, rettv)
11240 typval_T *argvars;
11241 typval_T *rettv;
11243 rettv->vval.v_number = mch_get_pid();
11247 * "getpos(string)" function
11249 static void
11250 f_getpos(argvars, rettv)
11251 typval_T *argvars;
11252 typval_T *rettv;
11254 pos_T *fp;
11255 list_T *l;
11256 int fnum = -1;
11258 if (rettv_list_alloc(rettv) == OK)
11260 l = rettv->vval.v_list;
11261 fp = var2fpos(&argvars[0], TRUE, &fnum);
11262 if (fnum != -1)
11263 list_append_number(l, (varnumber_T)fnum);
11264 else
11265 list_append_number(l, (varnumber_T)0);
11266 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
11267 : (varnumber_T)0);
11268 list_append_number(l, (fp != NULL)
11269 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
11270 : (varnumber_T)0);
11271 list_append_number(l,
11272 #ifdef FEAT_VIRTUALEDIT
11273 (fp != NULL) ? (varnumber_T)fp->coladd :
11274 #endif
11275 (varnumber_T)0);
11277 else
11278 rettv->vval.v_number = FALSE;
11282 * "getqflist()" and "getloclist()" functions
11284 /*ARGSUSED*/
11285 static void
11286 f_getqflist(argvars, rettv)
11287 typval_T *argvars;
11288 typval_T *rettv;
11290 #ifdef FEAT_QUICKFIX
11291 win_T *wp;
11292 #endif
11294 rettv->vval.v_number = 0;
11295 #ifdef FEAT_QUICKFIX
11296 if (rettv_list_alloc(rettv) == OK)
11298 wp = NULL;
11299 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
11301 wp = find_win_by_nr(&argvars[0], NULL);
11302 if (wp == NULL)
11303 return;
11306 (void)get_errorlist(wp, rettv->vval.v_list);
11308 #endif
11312 * "getreg()" function
11314 static void
11315 f_getreg(argvars, rettv)
11316 typval_T *argvars;
11317 typval_T *rettv;
11319 char_u *strregname;
11320 int regname;
11321 int arg2 = FALSE;
11322 int error = FALSE;
11324 if (argvars[0].v_type != VAR_UNKNOWN)
11326 strregname = get_tv_string_chk(&argvars[0]);
11327 error = strregname == NULL;
11328 if (argvars[1].v_type != VAR_UNKNOWN)
11329 arg2 = get_tv_number_chk(&argvars[1], &error);
11331 else
11332 strregname = vimvars[VV_REG].vv_str;
11333 regname = (strregname == NULL ? '"' : *strregname);
11334 if (regname == 0)
11335 regname = '"';
11337 rettv->v_type = VAR_STRING;
11338 rettv->vval.v_string = error ? NULL :
11339 get_reg_contents(regname, TRUE, arg2);
11343 * "getregtype()" function
11345 static void
11346 f_getregtype(argvars, rettv)
11347 typval_T *argvars;
11348 typval_T *rettv;
11350 char_u *strregname;
11351 int regname;
11352 char_u buf[NUMBUFLEN + 2];
11353 long reglen = 0;
11355 if (argvars[0].v_type != VAR_UNKNOWN)
11357 strregname = get_tv_string_chk(&argvars[0]);
11358 if (strregname == NULL) /* type error; errmsg already given */
11360 rettv->v_type = VAR_STRING;
11361 rettv->vval.v_string = NULL;
11362 return;
11365 else
11366 /* Default to v:register */
11367 strregname = vimvars[VV_REG].vv_str;
11369 regname = (strregname == NULL ? '"' : *strregname);
11370 if (regname == 0)
11371 regname = '"';
11373 buf[0] = NUL;
11374 buf[1] = NUL;
11375 switch (get_reg_type(regname, &reglen))
11377 case MLINE: buf[0] = 'V'; break;
11378 case MCHAR: buf[0] = 'v'; break;
11379 #ifdef FEAT_VISUAL
11380 case MBLOCK:
11381 buf[0] = Ctrl_V;
11382 sprintf((char *)buf + 1, "%ld", reglen + 1);
11383 break;
11384 #endif
11386 rettv->v_type = VAR_STRING;
11387 rettv->vval.v_string = vim_strsave(buf);
11391 * "gettabwinvar()" function
11393 static void
11394 f_gettabwinvar(argvars, rettv)
11395 typval_T *argvars;
11396 typval_T *rettv;
11398 getwinvar(argvars, rettv, 1);
11402 * "getwinposx()" function
11404 /*ARGSUSED*/
11405 static void
11406 f_getwinposx(argvars, rettv)
11407 typval_T *argvars;
11408 typval_T *rettv;
11410 rettv->vval.v_number = -1;
11411 #ifdef FEAT_GUI
11412 if (gui.in_use)
11414 int x, y;
11416 if (gui_mch_get_winpos(&x, &y) == OK)
11417 rettv->vval.v_number = x;
11419 #endif
11423 * "getwinposy()" function
11425 /*ARGSUSED*/
11426 static void
11427 f_getwinposy(argvars, rettv)
11428 typval_T *argvars;
11429 typval_T *rettv;
11431 rettv->vval.v_number = -1;
11432 #ifdef FEAT_GUI
11433 if (gui.in_use)
11435 int x, y;
11437 if (gui_mch_get_winpos(&x, &y) == OK)
11438 rettv->vval.v_number = y;
11440 #endif
11444 * Find window specified by "vp" in tabpage "tp".
11446 static win_T *
11447 find_win_by_nr(vp, tp)
11448 typval_T *vp;
11449 tabpage_T *tp; /* NULL for current tab page */
11451 #ifdef FEAT_WINDOWS
11452 win_T *wp;
11453 #endif
11454 int nr;
11456 nr = get_tv_number_chk(vp, NULL);
11458 #ifdef FEAT_WINDOWS
11459 if (nr < 0)
11460 return NULL;
11461 if (nr == 0)
11462 return curwin;
11464 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
11465 wp != NULL; wp = wp->w_next)
11466 if (--nr <= 0)
11467 break;
11468 return wp;
11469 #else
11470 if (nr == 0 || nr == 1)
11471 return curwin;
11472 return NULL;
11473 #endif
11477 * "getwinvar()" function
11479 static void
11480 f_getwinvar(argvars, rettv)
11481 typval_T *argvars;
11482 typval_T *rettv;
11484 getwinvar(argvars, rettv, 0);
11488 * getwinvar() and gettabwinvar()
11490 static void
11491 getwinvar(argvars, rettv, off)
11492 typval_T *argvars;
11493 typval_T *rettv;
11494 int off; /* 1 for gettabwinvar() */
11496 win_T *win, *oldcurwin;
11497 char_u *varname;
11498 dictitem_T *v;
11499 tabpage_T *tp;
11501 #ifdef FEAT_WINDOWS
11502 if (off == 1)
11503 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
11504 else
11505 tp = curtab;
11506 #endif
11507 win = find_win_by_nr(&argvars[off], tp);
11508 varname = get_tv_string_chk(&argvars[off + 1]);
11509 ++emsg_off;
11511 rettv->v_type = VAR_STRING;
11512 rettv->vval.v_string = NULL;
11514 if (win != NULL && varname != NULL)
11516 /* Set curwin to be our win, temporarily. Also set curbuf, so
11517 * that we can get buffer-local options. */
11518 oldcurwin = curwin;
11519 curwin = win;
11520 curbuf = win->w_buffer;
11522 if (*varname == '&') /* window-local-option */
11523 get_option_tv(&varname, rettv, 1);
11524 else
11526 if (*varname == NUL)
11527 /* let getwinvar({nr}, "") return the "w:" dictionary. The
11528 * scope prefix before the NUL byte is required by
11529 * find_var_in_ht(). */
11530 varname = (char_u *)"w:" + 2;
11531 /* look up the variable */
11532 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
11533 if (v != NULL)
11534 copy_tv(&v->di_tv, rettv);
11537 /* restore previous notion of curwin */
11538 curwin = oldcurwin;
11539 curbuf = curwin->w_buffer;
11542 --emsg_off;
11546 * "glob()" function
11548 static void
11549 f_glob(argvars, rettv)
11550 typval_T *argvars;
11551 typval_T *rettv;
11553 int flags = WILD_SILENT|WILD_USE_NL;
11554 expand_T xpc;
11555 int error = FALSE;
11557 /* When the optional second argument is non-zero, don't remove matches
11558 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11559 if (argvars[1].v_type != VAR_UNKNOWN
11560 && get_tv_number_chk(&argvars[1], &error))
11561 flags |= WILD_KEEP_ALL;
11562 rettv->v_type = VAR_STRING;
11563 if (!error)
11565 ExpandInit(&xpc);
11566 xpc.xp_context = EXPAND_FILES;
11567 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
11568 NULL, flags, WILD_ALL);
11570 else
11571 rettv->vval.v_string = NULL;
11575 * "globpath()" function
11577 static void
11578 f_globpath(argvars, rettv)
11579 typval_T *argvars;
11580 typval_T *rettv;
11582 int flags = 0;
11583 char_u buf1[NUMBUFLEN];
11584 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
11585 int error = FALSE;
11587 /* When the optional second argument is non-zero, don't remove matches
11588 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11589 if (argvars[2].v_type != VAR_UNKNOWN
11590 && get_tv_number_chk(&argvars[2], &error))
11591 flags |= WILD_KEEP_ALL;
11592 rettv->v_type = VAR_STRING;
11593 if (file == NULL || error)
11594 rettv->vval.v_string = NULL;
11595 else
11596 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file,
11597 flags);
11601 * "has()" function
11603 static void
11604 f_has(argvars, rettv)
11605 typval_T *argvars;
11606 typval_T *rettv;
11608 int i;
11609 char_u *name;
11610 int n = FALSE;
11611 static char *(has_list[]) =
11613 #ifdef AMIGA
11614 "amiga",
11615 # ifdef FEAT_ARP
11616 "arp",
11617 # endif
11618 #endif
11619 #ifdef __BEOS__
11620 "beos",
11621 #endif
11622 #ifdef MSDOS
11623 # ifdef DJGPP
11624 "dos32",
11625 # else
11626 "dos16",
11627 # endif
11628 #endif
11629 #ifdef MACOS
11630 "mac",
11631 #endif
11632 #if defined(MACOS_X_UNIX)
11633 "macunix",
11634 #endif
11635 #ifdef OS2
11636 "os2",
11637 #endif
11638 #ifdef __QNX__
11639 "qnx",
11640 #endif
11641 #ifdef RISCOS
11642 "riscos",
11643 #endif
11644 #ifdef UNIX
11645 "unix",
11646 #endif
11647 #ifdef VMS
11648 "vms",
11649 #endif
11650 #ifdef WIN16
11651 "win16",
11652 #endif
11653 #ifdef WIN32
11654 "win32",
11655 #endif
11656 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
11657 "win32unix",
11658 #endif
11659 #ifdef WIN64
11660 "win64",
11661 #endif
11662 #ifdef EBCDIC
11663 "ebcdic",
11664 #endif
11665 #ifndef CASE_INSENSITIVE_FILENAME
11666 "fname_case",
11667 #endif
11668 #ifdef FEAT_ARABIC
11669 "arabic",
11670 #endif
11671 #ifdef FEAT_AUTOCMD
11672 "autocmd",
11673 #endif
11674 #ifdef FEAT_BEVAL
11675 "balloon_eval",
11676 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
11677 "balloon_multiline",
11678 # endif
11679 #endif
11680 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
11681 "builtin_terms",
11682 # ifdef ALL_BUILTIN_TCAPS
11683 "all_builtin_terms",
11684 # endif
11685 #endif
11686 #ifdef FEAT_BYTEOFF
11687 "byte_offset",
11688 #endif
11689 #ifdef FEAT_CINDENT
11690 "cindent",
11691 #endif
11692 #ifdef FEAT_CLIENTSERVER
11693 "clientserver",
11694 #endif
11695 #ifdef FEAT_CLIPBOARD
11696 "clipboard",
11697 #endif
11698 #ifdef FEAT_CMDL_COMPL
11699 "cmdline_compl",
11700 #endif
11701 #ifdef FEAT_CMDHIST
11702 "cmdline_hist",
11703 #endif
11704 #ifdef FEAT_COMMENTS
11705 "comments",
11706 #endif
11707 #ifdef FEAT_CRYPT
11708 "cryptv",
11709 #endif
11710 #ifdef FEAT_CSCOPE
11711 "cscope",
11712 #endif
11713 #ifdef CURSOR_SHAPE
11714 "cursorshape",
11715 #endif
11716 #ifdef DEBUG
11717 "debug",
11718 #endif
11719 #ifdef FEAT_CON_DIALOG
11720 "dialog_con",
11721 #endif
11722 #ifdef FEAT_GUI_DIALOG
11723 "dialog_gui",
11724 #endif
11725 #ifdef FEAT_DIFF
11726 "diff",
11727 #endif
11728 #ifdef FEAT_DIGRAPHS
11729 "digraphs",
11730 #endif
11731 #ifdef FEAT_DND
11732 "dnd",
11733 #endif
11734 #ifdef FEAT_EMACS_TAGS
11735 "emacs_tags",
11736 #endif
11737 "eval", /* always present, of course! */
11738 #ifdef FEAT_EX_EXTRA
11739 "ex_extra",
11740 #endif
11741 #ifdef FEAT_SEARCH_EXTRA
11742 "extra_search",
11743 #endif
11744 #ifdef FEAT_FKMAP
11745 "farsi",
11746 #endif
11747 #ifdef FEAT_SEARCHPATH
11748 "file_in_path",
11749 #endif
11750 #if defined(UNIX) && !defined(USE_SYSTEM)
11751 "filterpipe",
11752 #endif
11753 #ifdef FEAT_FIND_ID
11754 "find_in_path",
11755 #endif
11756 #ifdef FEAT_FLOAT
11757 "float",
11758 #endif
11759 #ifdef FEAT_FOLDING
11760 "folding",
11761 #endif
11762 #ifdef FEAT_FOOTER
11763 "footer",
11764 #endif
11765 #if !defined(USE_SYSTEM) && defined(UNIX)
11766 "fork",
11767 #endif
11768 #ifdef FEAT_GETTEXT
11769 "gettext",
11770 #endif
11771 #ifdef FEAT_GUI
11772 "gui",
11773 #endif
11774 #ifdef FEAT_GUI_ATHENA
11775 # ifdef FEAT_GUI_NEXTAW
11776 "gui_neXtaw",
11777 # else
11778 "gui_athena",
11779 # endif
11780 #endif
11781 #ifdef FEAT_GUI_GTK
11782 "gui_gtk",
11783 # ifdef HAVE_GTK2
11784 "gui_gtk2",
11785 # endif
11786 #endif
11787 #ifdef FEAT_GUI_GNOME
11788 "gui_gnome",
11789 #endif
11790 #ifdef FEAT_GUI_MAC
11791 "gui_mac",
11792 #endif
11793 #ifdef FEAT_GUI_MOTIF
11794 "gui_motif",
11795 #endif
11796 #ifdef FEAT_GUI_PHOTON
11797 "gui_photon",
11798 #endif
11799 #ifdef FEAT_GUI_W16
11800 "gui_win16",
11801 #endif
11802 #ifdef FEAT_GUI_W32
11803 "gui_win32",
11804 #endif
11805 #ifdef FEAT_HANGULIN
11806 "hangul_input",
11807 #endif
11808 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
11809 "iconv",
11810 #endif
11811 #ifdef FEAT_INS_EXPAND
11812 "insert_expand",
11813 #endif
11814 #ifdef FEAT_JUMPLIST
11815 "jumplist",
11816 #endif
11817 #ifdef FEAT_KEYMAP
11818 "keymap",
11819 #endif
11820 #ifdef FEAT_LANGMAP
11821 "langmap",
11822 #endif
11823 #ifdef FEAT_LIBCALL
11824 "libcall",
11825 #endif
11826 #ifdef FEAT_LINEBREAK
11827 "linebreak",
11828 #endif
11829 #ifdef FEAT_LISP
11830 "lispindent",
11831 #endif
11832 #ifdef FEAT_LISTCMDS
11833 "listcmds",
11834 #endif
11835 #ifdef FEAT_LOCALMAP
11836 "localmap",
11837 #endif
11838 #ifdef FEAT_MENU
11839 "menu",
11840 #endif
11841 #ifdef FEAT_SESSION
11842 "mksession",
11843 #endif
11844 #ifdef FEAT_MODIFY_FNAME
11845 "modify_fname",
11846 #endif
11847 #ifdef FEAT_MOUSE
11848 "mouse",
11849 #endif
11850 #ifdef FEAT_MOUSESHAPE
11851 "mouseshape",
11852 #endif
11853 #if defined(UNIX) || defined(VMS)
11854 # ifdef FEAT_MOUSE_DEC
11855 "mouse_dec",
11856 # endif
11857 # ifdef FEAT_MOUSE_GPM
11858 "mouse_gpm",
11859 # endif
11860 # ifdef FEAT_MOUSE_JSB
11861 "mouse_jsbterm",
11862 # endif
11863 # ifdef FEAT_MOUSE_NET
11864 "mouse_netterm",
11865 # endif
11866 # ifdef FEAT_MOUSE_PTERM
11867 "mouse_pterm",
11868 # endif
11869 # ifdef FEAT_SYSMOUSE
11870 "mouse_sysmouse",
11871 # endif
11872 # ifdef FEAT_MOUSE_XTERM
11873 "mouse_xterm",
11874 # endif
11875 #endif
11876 #ifdef FEAT_MBYTE
11877 "multi_byte",
11878 #endif
11879 #ifdef FEAT_MBYTE_IME
11880 "multi_byte_ime",
11881 #endif
11882 #ifdef FEAT_MULTI_LANG
11883 "multi_lang",
11884 #endif
11885 #ifdef FEAT_MZSCHEME
11886 #ifndef DYNAMIC_MZSCHEME
11887 "mzscheme",
11888 #endif
11889 #endif
11890 #ifdef FEAT_OLE
11891 "ole",
11892 #endif
11893 #ifdef FEAT_OSFILETYPE
11894 "osfiletype",
11895 #endif
11896 #ifdef FEAT_PATH_EXTRA
11897 "path_extra",
11898 #endif
11899 #ifdef FEAT_PERL
11900 #ifndef DYNAMIC_PERL
11901 "perl",
11902 #endif
11903 #endif
11904 #ifdef FEAT_PYTHON
11905 #ifndef DYNAMIC_PYTHON
11906 "python",
11907 #endif
11908 #endif
11909 #ifdef FEAT_POSTSCRIPT
11910 "postscript",
11911 #endif
11912 #ifdef FEAT_PRINTER
11913 "printer",
11914 #endif
11915 #ifdef FEAT_PROFILE
11916 "profile",
11917 #endif
11918 #ifdef FEAT_RELTIME
11919 "reltime",
11920 #endif
11921 #ifdef FEAT_QUICKFIX
11922 "quickfix",
11923 #endif
11924 #ifdef FEAT_RIGHTLEFT
11925 "rightleft",
11926 #endif
11927 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11928 "ruby",
11929 #endif
11930 #ifdef FEAT_SCROLLBIND
11931 "scrollbind",
11932 #endif
11933 #ifdef FEAT_CMDL_INFO
11934 "showcmd",
11935 "cmdline_info",
11936 #endif
11937 #ifdef FEAT_SIGNS
11938 "signs",
11939 #endif
11940 #ifdef FEAT_SMARTINDENT
11941 "smartindent",
11942 #endif
11943 #ifdef FEAT_SNIFF
11944 "sniff",
11945 #endif
11946 #ifdef FEAT_STL_OPT
11947 "statusline",
11948 #endif
11949 #ifdef FEAT_SUN_WORKSHOP
11950 "sun_workshop",
11951 #endif
11952 #ifdef FEAT_NETBEANS_INTG
11953 "netbeans_intg",
11954 #endif
11955 #ifdef FEAT_SPELL
11956 "spell",
11957 #endif
11958 #ifdef FEAT_SYN_HL
11959 "syntax",
11960 #endif
11961 #if defined(USE_SYSTEM) || !defined(UNIX)
11962 "system",
11963 #endif
11964 #ifdef FEAT_TAG_BINS
11965 "tag_binary",
11966 #endif
11967 #ifdef FEAT_TAG_OLDSTATIC
11968 "tag_old_static",
11969 #endif
11970 #ifdef FEAT_TAG_ANYWHITE
11971 "tag_any_white",
11972 #endif
11973 #ifdef FEAT_TCL
11974 # ifndef DYNAMIC_TCL
11975 "tcl",
11976 # endif
11977 #endif
11978 #ifdef TERMINFO
11979 "terminfo",
11980 #endif
11981 #ifdef FEAT_TERMRESPONSE
11982 "termresponse",
11983 #endif
11984 #ifdef FEAT_TEXTOBJ
11985 "textobjects",
11986 #endif
11987 #ifdef HAVE_TGETENT
11988 "tgetent",
11989 #endif
11990 #ifdef FEAT_TITLE
11991 "title",
11992 #endif
11993 #ifdef FEAT_TOOLBAR
11994 "toolbar",
11995 #endif
11996 #ifdef FEAT_USR_CMDS
11997 "user-commands", /* was accidentally included in 5.4 */
11998 "user_commands",
11999 #endif
12000 #ifdef FEAT_VIMINFO
12001 "viminfo",
12002 #endif
12003 #ifdef FEAT_VERTSPLIT
12004 "vertsplit",
12005 #endif
12006 #ifdef FEAT_VIRTUALEDIT
12007 "virtualedit",
12008 #endif
12009 #ifdef FEAT_VISUAL
12010 "visual",
12011 #endif
12012 #ifdef FEAT_VISUALEXTRA
12013 "visualextra",
12014 #endif
12015 #ifdef FEAT_VREPLACE
12016 "vreplace",
12017 #endif
12018 #ifdef FEAT_WILDIGN
12019 "wildignore",
12020 #endif
12021 #ifdef FEAT_WILDMENU
12022 "wildmenu",
12023 #endif
12024 #ifdef FEAT_WINDOWS
12025 "windows",
12026 #endif
12027 #ifdef FEAT_WAK
12028 "winaltkeys",
12029 #endif
12030 #ifdef FEAT_WRITEBACKUP
12031 "writebackup",
12032 #endif
12033 #ifdef FEAT_XIM
12034 "xim",
12035 #endif
12036 #ifdef FEAT_XFONTSET
12037 "xfontset",
12038 #endif
12039 #ifdef USE_XSMP
12040 "xsmp",
12041 #endif
12042 #ifdef USE_XSMP_INTERACT
12043 "xsmp_interact",
12044 #endif
12045 #ifdef FEAT_XCLIPBOARD
12046 "xterm_clipboard",
12047 #endif
12048 #ifdef FEAT_XTERM_SAVE
12049 "xterm_save",
12050 #endif
12051 #if defined(UNIX) && defined(FEAT_X11)
12052 "X11",
12053 #endif
12054 NULL
12057 name = get_tv_string(&argvars[0]);
12058 for (i = 0; has_list[i] != NULL; ++i)
12059 if (STRICMP(name, has_list[i]) == 0)
12061 n = TRUE;
12062 break;
12065 if (n == FALSE)
12067 if (STRNICMP(name, "patch", 5) == 0)
12068 n = has_patch(atoi((char *)name + 5));
12069 else if (STRICMP(name, "vim_starting") == 0)
12070 n = (starting != 0);
12071 #ifdef FEAT_MBYTE
12072 else if (STRICMP(name, "multi_byte_encoding") == 0)
12073 n = has_mbyte;
12074 #endif
12075 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
12076 else if (STRICMP(name, "balloon_multiline") == 0)
12077 n = multiline_balloon_available();
12078 #endif
12079 #ifdef DYNAMIC_TCL
12080 else if (STRICMP(name, "tcl") == 0)
12081 n = tcl_enabled(FALSE);
12082 #endif
12083 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
12084 else if (STRICMP(name, "iconv") == 0)
12085 n = iconv_enabled(FALSE);
12086 #endif
12087 #ifdef DYNAMIC_MZSCHEME
12088 else if (STRICMP(name, "mzscheme") == 0)
12089 n = mzscheme_enabled(FALSE);
12090 #endif
12091 #ifdef DYNAMIC_RUBY
12092 else if (STRICMP(name, "ruby") == 0)
12093 n = ruby_enabled(FALSE);
12094 #endif
12095 #ifdef DYNAMIC_PYTHON
12096 else if (STRICMP(name, "python") == 0)
12097 n = python_enabled(FALSE);
12098 #endif
12099 #ifdef DYNAMIC_PERL
12100 else if (STRICMP(name, "perl") == 0)
12101 n = perl_enabled(FALSE);
12102 #endif
12103 #ifdef FEAT_GUI
12104 else if (STRICMP(name, "gui_running") == 0)
12105 n = (gui.in_use || gui.starting);
12106 # ifdef FEAT_GUI_W32
12107 else if (STRICMP(name, "gui_win32s") == 0)
12108 n = gui_is_win32s();
12109 # endif
12110 # ifdef FEAT_BROWSE
12111 else if (STRICMP(name, "browse") == 0)
12112 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
12113 # endif
12114 #endif
12115 #ifdef FEAT_SYN_HL
12116 else if (STRICMP(name, "syntax_items") == 0)
12117 n = syntax_present(curbuf);
12118 #endif
12119 #if defined(WIN3264)
12120 else if (STRICMP(name, "win95") == 0)
12121 n = mch_windows95();
12122 #endif
12123 #ifdef FEAT_NETBEANS_INTG
12124 else if (STRICMP(name, "netbeans_enabled") == 0)
12125 n = usingNetbeans;
12126 #endif
12129 rettv->vval.v_number = n;
12133 * "has_key()" function
12135 static void
12136 f_has_key(argvars, rettv)
12137 typval_T *argvars;
12138 typval_T *rettv;
12140 rettv->vval.v_number = 0;
12141 if (argvars[0].v_type != VAR_DICT)
12143 EMSG(_(e_dictreq));
12144 return;
12146 if (argvars[0].vval.v_dict == NULL)
12147 return;
12149 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
12150 get_tv_string(&argvars[1]), -1) != NULL;
12154 * "haslocaldir()" function
12156 /*ARGSUSED*/
12157 static void
12158 f_haslocaldir(argvars, rettv)
12159 typval_T *argvars;
12160 typval_T *rettv;
12162 rettv->vval.v_number = (curwin->w_localdir != NULL);
12166 * "hasmapto()" function
12168 static void
12169 f_hasmapto(argvars, rettv)
12170 typval_T *argvars;
12171 typval_T *rettv;
12173 char_u *name;
12174 char_u *mode;
12175 char_u buf[NUMBUFLEN];
12176 int abbr = FALSE;
12178 name = get_tv_string(&argvars[0]);
12179 if (argvars[1].v_type == VAR_UNKNOWN)
12180 mode = (char_u *)"nvo";
12181 else
12183 mode = get_tv_string_buf(&argvars[1], buf);
12184 if (argvars[2].v_type != VAR_UNKNOWN)
12185 abbr = get_tv_number(&argvars[2]);
12188 if (map_to_exists(name, mode, abbr))
12189 rettv->vval.v_number = TRUE;
12190 else
12191 rettv->vval.v_number = FALSE;
12195 * "histadd()" function
12197 /*ARGSUSED*/
12198 static void
12199 f_histadd(argvars, rettv)
12200 typval_T *argvars;
12201 typval_T *rettv;
12203 #ifdef FEAT_CMDHIST
12204 int histype;
12205 char_u *str;
12206 char_u buf[NUMBUFLEN];
12207 #endif
12209 rettv->vval.v_number = FALSE;
12210 if (check_restricted() || check_secure())
12211 return;
12212 #ifdef FEAT_CMDHIST
12213 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12214 histype = str != NULL ? get_histtype(str) : -1;
12215 if (histype >= 0)
12217 str = get_tv_string_buf(&argvars[1], buf);
12218 if (*str != NUL)
12220 add_to_history(histype, str, FALSE, NUL);
12221 rettv->vval.v_number = TRUE;
12222 return;
12225 #endif
12229 * "histdel()" function
12231 /*ARGSUSED*/
12232 static void
12233 f_histdel(argvars, rettv)
12234 typval_T *argvars;
12235 typval_T *rettv;
12237 #ifdef FEAT_CMDHIST
12238 int n;
12239 char_u buf[NUMBUFLEN];
12240 char_u *str;
12242 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12243 if (str == NULL)
12244 n = 0;
12245 else if (argvars[1].v_type == VAR_UNKNOWN)
12246 /* only one argument: clear entire history */
12247 n = clr_history(get_histtype(str));
12248 else if (argvars[1].v_type == VAR_NUMBER)
12249 /* index given: remove that entry */
12250 n = del_history_idx(get_histtype(str),
12251 (int)get_tv_number(&argvars[1]));
12252 else
12253 /* string given: remove all matching entries */
12254 n = del_history_entry(get_histtype(str),
12255 get_tv_string_buf(&argvars[1], buf));
12256 rettv->vval.v_number = n;
12257 #else
12258 rettv->vval.v_number = 0;
12259 #endif
12263 * "histget()" function
12265 /*ARGSUSED*/
12266 static void
12267 f_histget(argvars, rettv)
12268 typval_T *argvars;
12269 typval_T *rettv;
12271 #ifdef FEAT_CMDHIST
12272 int type;
12273 int idx;
12274 char_u *str;
12276 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12277 if (str == NULL)
12278 rettv->vval.v_string = NULL;
12279 else
12281 type = get_histtype(str);
12282 if (argvars[1].v_type == VAR_UNKNOWN)
12283 idx = get_history_idx(type);
12284 else
12285 idx = (int)get_tv_number_chk(&argvars[1], NULL);
12286 /* -1 on type error */
12287 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
12289 #else
12290 rettv->vval.v_string = NULL;
12291 #endif
12292 rettv->v_type = VAR_STRING;
12296 * "histnr()" function
12298 /*ARGSUSED*/
12299 static void
12300 f_histnr(argvars, rettv)
12301 typval_T *argvars;
12302 typval_T *rettv;
12304 int i;
12306 #ifdef FEAT_CMDHIST
12307 char_u *history = get_tv_string_chk(&argvars[0]);
12309 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
12310 if (i >= HIST_CMD && i < HIST_COUNT)
12311 i = get_history_idx(i);
12312 else
12313 #endif
12314 i = -1;
12315 rettv->vval.v_number = i;
12319 * "highlightID(name)" function
12321 static void
12322 f_hlID(argvars, rettv)
12323 typval_T *argvars;
12324 typval_T *rettv;
12326 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
12330 * "highlight_exists()" function
12332 static void
12333 f_hlexists(argvars, rettv)
12334 typval_T *argvars;
12335 typval_T *rettv;
12337 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
12341 * "hostname()" function
12343 /*ARGSUSED*/
12344 static void
12345 f_hostname(argvars, rettv)
12346 typval_T *argvars;
12347 typval_T *rettv;
12349 char_u hostname[256];
12351 mch_get_host_name(hostname, 256);
12352 rettv->v_type = VAR_STRING;
12353 rettv->vval.v_string = vim_strsave(hostname);
12357 * iconv() function
12359 /*ARGSUSED*/
12360 static void
12361 f_iconv(argvars, rettv)
12362 typval_T *argvars;
12363 typval_T *rettv;
12365 #ifdef FEAT_MBYTE
12366 char_u buf1[NUMBUFLEN];
12367 char_u buf2[NUMBUFLEN];
12368 char_u *from, *to, *str;
12369 vimconv_T vimconv;
12370 #endif
12372 rettv->v_type = VAR_STRING;
12373 rettv->vval.v_string = NULL;
12375 #ifdef FEAT_MBYTE
12376 str = get_tv_string(&argvars[0]);
12377 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
12378 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
12379 vimconv.vc_type = CONV_NONE;
12380 convert_setup(&vimconv, from, to);
12382 /* If the encodings are equal, no conversion needed. */
12383 if (vimconv.vc_type == CONV_NONE)
12384 rettv->vval.v_string = vim_strsave(str);
12385 else
12386 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
12388 convert_setup(&vimconv, NULL, NULL);
12389 vim_free(from);
12390 vim_free(to);
12391 #endif
12395 * "indent()" function
12397 static void
12398 f_indent(argvars, rettv)
12399 typval_T *argvars;
12400 typval_T *rettv;
12402 linenr_T lnum;
12404 lnum = get_tv_lnum(argvars);
12405 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12406 rettv->vval.v_number = get_indent_lnum(lnum);
12407 else
12408 rettv->vval.v_number = -1;
12412 * "index()" function
12414 static void
12415 f_index(argvars, rettv)
12416 typval_T *argvars;
12417 typval_T *rettv;
12419 list_T *l;
12420 listitem_T *item;
12421 long idx = 0;
12422 int ic = FALSE;
12424 rettv->vval.v_number = -1;
12425 if (argvars[0].v_type != VAR_LIST)
12427 EMSG(_(e_listreq));
12428 return;
12430 l = argvars[0].vval.v_list;
12431 if (l != NULL)
12433 item = l->lv_first;
12434 if (argvars[2].v_type != VAR_UNKNOWN)
12436 int error = FALSE;
12438 /* Start at specified item. Use the cached index that list_find()
12439 * sets, so that a negative number also works. */
12440 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
12441 idx = l->lv_idx;
12442 if (argvars[3].v_type != VAR_UNKNOWN)
12443 ic = get_tv_number_chk(&argvars[3], &error);
12444 if (error)
12445 item = NULL;
12448 for ( ; item != NULL; item = item->li_next, ++idx)
12449 if (tv_equal(&item->li_tv, &argvars[1], ic))
12451 rettv->vval.v_number = idx;
12452 break;
12457 static int inputsecret_flag = 0;
12459 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
12462 * This function is used by f_input() and f_inputdialog() functions. The third
12463 * argument to f_input() specifies the type of completion to use at the
12464 * prompt. The third argument to f_inputdialog() specifies the value to return
12465 * when the user cancels the prompt.
12467 static void
12468 get_user_input(argvars, rettv, inputdialog)
12469 typval_T *argvars;
12470 typval_T *rettv;
12471 int inputdialog;
12473 char_u *prompt = get_tv_string_chk(&argvars[0]);
12474 char_u *p = NULL;
12475 int c;
12476 char_u buf[NUMBUFLEN];
12477 int cmd_silent_save = cmd_silent;
12478 char_u *defstr = (char_u *)"";
12479 int xp_type = EXPAND_NOTHING;
12480 char_u *xp_arg = NULL;
12482 rettv->v_type = VAR_STRING;
12483 rettv->vval.v_string = NULL;
12485 #ifdef NO_CONSOLE_INPUT
12486 /* While starting up, there is no place to enter text. */
12487 if (no_console_input())
12488 return;
12489 #endif
12491 cmd_silent = FALSE; /* Want to see the prompt. */
12492 if (prompt != NULL)
12494 /* Only the part of the message after the last NL is considered as
12495 * prompt for the command line */
12496 p = vim_strrchr(prompt, '\n');
12497 if (p == NULL)
12498 p = prompt;
12499 else
12501 ++p;
12502 c = *p;
12503 *p = NUL;
12504 msg_start();
12505 msg_clr_eos();
12506 msg_puts_attr(prompt, echo_attr);
12507 msg_didout = FALSE;
12508 msg_starthere();
12509 *p = c;
12511 cmdline_row = msg_row;
12513 if (argvars[1].v_type != VAR_UNKNOWN)
12515 defstr = get_tv_string_buf_chk(&argvars[1], buf);
12516 if (defstr != NULL)
12517 stuffReadbuffSpec(defstr);
12519 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
12521 char_u *xp_name;
12522 int xp_namelen;
12523 long argt;
12525 rettv->vval.v_string = NULL;
12527 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
12528 if (xp_name == NULL)
12529 return;
12531 xp_namelen = (int)STRLEN(xp_name);
12533 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
12534 &xp_arg) == FAIL)
12535 return;
12539 if (defstr != NULL)
12540 rettv->vval.v_string =
12541 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
12542 xp_type, xp_arg);
12544 vim_free(xp_arg);
12546 /* since the user typed this, no need to wait for return */
12547 need_wait_return = FALSE;
12548 msg_didout = FALSE;
12550 cmd_silent = cmd_silent_save;
12554 * "input()" function
12555 * Also handles inputsecret() when inputsecret is set.
12557 static void
12558 f_input(argvars, rettv)
12559 typval_T *argvars;
12560 typval_T *rettv;
12562 get_user_input(argvars, rettv, FALSE);
12566 * "inputdialog()" function
12568 static void
12569 f_inputdialog(argvars, rettv)
12570 typval_T *argvars;
12571 typval_T *rettv;
12573 #if defined(FEAT_GUI_TEXTDIALOG)
12574 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
12575 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
12577 char_u *message;
12578 char_u buf[NUMBUFLEN];
12579 char_u *defstr = (char_u *)"";
12581 message = get_tv_string_chk(&argvars[0]);
12582 if (argvars[1].v_type != VAR_UNKNOWN
12583 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
12584 vim_strncpy(IObuff, defstr, IOSIZE - 1);
12585 else
12586 IObuff[0] = NUL;
12587 if (message != NULL && defstr != NULL
12588 && do_dialog(VIM_QUESTION, NULL, message,
12589 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
12590 rettv->vval.v_string = vim_strsave(IObuff);
12591 else
12593 if (message != NULL && defstr != NULL
12594 && argvars[1].v_type != VAR_UNKNOWN
12595 && argvars[2].v_type != VAR_UNKNOWN)
12596 rettv->vval.v_string = vim_strsave(
12597 get_tv_string_buf(&argvars[2], buf));
12598 else
12599 rettv->vval.v_string = NULL;
12601 rettv->v_type = VAR_STRING;
12603 else
12604 #endif
12605 get_user_input(argvars, rettv, TRUE);
12609 * "inputlist()" function
12611 static void
12612 f_inputlist(argvars, rettv)
12613 typval_T *argvars;
12614 typval_T *rettv;
12616 listitem_T *li;
12617 int selected;
12618 int mouse_used;
12620 rettv->vval.v_number = 0;
12621 #ifdef NO_CONSOLE_INPUT
12622 /* While starting up, there is no place to enter text. */
12623 if (no_console_input())
12624 return;
12625 #endif
12626 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
12628 EMSG2(_(e_listarg), "inputlist()");
12629 return;
12632 msg_start();
12633 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
12634 lines_left = Rows; /* avoid more prompt */
12635 msg_scroll = TRUE;
12636 msg_clr_eos();
12638 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
12640 msg_puts(get_tv_string(&li->li_tv));
12641 msg_putchar('\n');
12644 /* Ask for choice. */
12645 selected = prompt_for_number(&mouse_used);
12646 if (mouse_used)
12647 selected -= lines_left;
12649 rettv->vval.v_number = selected;
12653 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
12656 * "inputrestore()" function
12658 /*ARGSUSED*/
12659 static void
12660 f_inputrestore(argvars, rettv)
12661 typval_T *argvars;
12662 typval_T *rettv;
12664 if (ga_userinput.ga_len > 0)
12666 --ga_userinput.ga_len;
12667 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
12668 + ga_userinput.ga_len);
12669 rettv->vval.v_number = 0; /* OK */
12671 else if (p_verbose > 1)
12673 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
12674 rettv->vval.v_number = 1; /* Failed */
12679 * "inputsave()" function
12681 /*ARGSUSED*/
12682 static void
12683 f_inputsave(argvars, rettv)
12684 typval_T *argvars;
12685 typval_T *rettv;
12687 /* Add an entry to the stack of typeahead storage. */
12688 if (ga_grow(&ga_userinput, 1) == OK)
12690 save_typeahead((tasave_T *)(ga_userinput.ga_data)
12691 + ga_userinput.ga_len);
12692 ++ga_userinput.ga_len;
12693 rettv->vval.v_number = 0; /* OK */
12695 else
12696 rettv->vval.v_number = 1; /* Failed */
12700 * "inputsecret()" function
12702 static void
12703 f_inputsecret(argvars, rettv)
12704 typval_T *argvars;
12705 typval_T *rettv;
12707 ++cmdline_star;
12708 ++inputsecret_flag;
12709 f_input(argvars, rettv);
12710 --cmdline_star;
12711 --inputsecret_flag;
12715 * "insert()" function
12717 static void
12718 f_insert(argvars, rettv)
12719 typval_T *argvars;
12720 typval_T *rettv;
12722 long before = 0;
12723 listitem_T *item;
12724 list_T *l;
12725 int error = FALSE;
12727 rettv->vval.v_number = 0;
12728 if (argvars[0].v_type != VAR_LIST)
12729 EMSG2(_(e_listarg), "insert()");
12730 else if ((l = argvars[0].vval.v_list) != NULL
12731 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
12733 if (argvars[2].v_type != VAR_UNKNOWN)
12734 before = get_tv_number_chk(&argvars[2], &error);
12735 if (error)
12736 return; /* type error; errmsg already given */
12738 if (before == l->lv_len)
12739 item = NULL;
12740 else
12742 item = list_find(l, before);
12743 if (item == NULL)
12745 EMSGN(_(e_listidx), before);
12746 l = NULL;
12749 if (l != NULL)
12751 list_insert_tv(l, &argvars[1], item);
12752 copy_tv(&argvars[0], rettv);
12758 * "isdirectory()" function
12760 static void
12761 f_isdirectory(argvars, rettv)
12762 typval_T *argvars;
12763 typval_T *rettv;
12765 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
12769 * "islocked()" function
12771 static void
12772 f_islocked(argvars, rettv)
12773 typval_T *argvars;
12774 typval_T *rettv;
12776 lval_T lv;
12777 char_u *end;
12778 dictitem_T *di;
12780 rettv->vval.v_number = -1;
12781 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
12782 FNE_CHECK_START);
12783 if (end != NULL && lv.ll_name != NULL)
12785 if (*end != NUL)
12786 EMSG(_(e_trailing));
12787 else
12789 if (lv.ll_tv == NULL)
12791 if (check_changedtick(lv.ll_name))
12792 rettv->vval.v_number = 1; /* always locked */
12793 else
12795 di = find_var(lv.ll_name, NULL);
12796 if (di != NULL)
12798 /* Consider a variable locked when:
12799 * 1. the variable itself is locked
12800 * 2. the value of the variable is locked.
12801 * 3. the List or Dict value is locked.
12803 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
12804 || tv_islocked(&di->di_tv));
12808 else if (lv.ll_range)
12809 EMSG(_("E786: Range not allowed"));
12810 else if (lv.ll_newkey != NULL)
12811 EMSG2(_(e_dictkey), lv.ll_newkey);
12812 else if (lv.ll_list != NULL)
12813 /* List item. */
12814 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
12815 else
12816 /* Dictionary item. */
12817 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
12821 clear_lval(&lv);
12824 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
12827 * Turn a dict into a list:
12828 * "what" == 0: list of keys
12829 * "what" == 1: list of values
12830 * "what" == 2: list of items
12832 static void
12833 dict_list(argvars, rettv, what)
12834 typval_T *argvars;
12835 typval_T *rettv;
12836 int what;
12838 list_T *l2;
12839 dictitem_T *di;
12840 hashitem_T *hi;
12841 listitem_T *li;
12842 listitem_T *li2;
12843 dict_T *d;
12844 int todo;
12846 rettv->vval.v_number = 0;
12847 if (argvars[0].v_type != VAR_DICT)
12849 EMSG(_(e_dictreq));
12850 return;
12852 if ((d = argvars[0].vval.v_dict) == NULL)
12853 return;
12855 if (rettv_list_alloc(rettv) == FAIL)
12856 return;
12858 todo = (int)d->dv_hashtab.ht_used;
12859 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12861 if (!HASHITEM_EMPTY(hi))
12863 --todo;
12864 di = HI2DI(hi);
12866 li = listitem_alloc();
12867 if (li == NULL)
12868 break;
12869 list_append(rettv->vval.v_list, li);
12871 if (what == 0)
12873 /* keys() */
12874 li->li_tv.v_type = VAR_STRING;
12875 li->li_tv.v_lock = 0;
12876 li->li_tv.vval.v_string = vim_strsave(di->di_key);
12878 else if (what == 1)
12880 /* values() */
12881 copy_tv(&di->di_tv, &li->li_tv);
12883 else
12885 /* items() */
12886 l2 = list_alloc();
12887 li->li_tv.v_type = VAR_LIST;
12888 li->li_tv.v_lock = 0;
12889 li->li_tv.vval.v_list = l2;
12890 if (l2 == NULL)
12891 break;
12892 ++l2->lv_refcount;
12894 li2 = listitem_alloc();
12895 if (li2 == NULL)
12896 break;
12897 list_append(l2, li2);
12898 li2->li_tv.v_type = VAR_STRING;
12899 li2->li_tv.v_lock = 0;
12900 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12902 li2 = listitem_alloc();
12903 if (li2 == NULL)
12904 break;
12905 list_append(l2, li2);
12906 copy_tv(&di->di_tv, &li2->li_tv);
12913 * "items(dict)" function
12915 static void
12916 f_items(argvars, rettv)
12917 typval_T *argvars;
12918 typval_T *rettv;
12920 dict_list(argvars, rettv, 2);
12924 * "join()" function
12926 static void
12927 f_join(argvars, rettv)
12928 typval_T *argvars;
12929 typval_T *rettv;
12931 garray_T ga;
12932 char_u *sep;
12934 rettv->vval.v_number = 0;
12935 if (argvars[0].v_type != VAR_LIST)
12937 EMSG(_(e_listreq));
12938 return;
12940 if (argvars[0].vval.v_list == NULL)
12941 return;
12942 if (argvars[1].v_type == VAR_UNKNOWN)
12943 sep = (char_u *)" ";
12944 else
12945 sep = get_tv_string_chk(&argvars[1]);
12947 rettv->v_type = VAR_STRING;
12949 if (sep != NULL)
12951 ga_init2(&ga, (int)sizeof(char), 80);
12952 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12953 ga_append(&ga, NUL);
12954 rettv->vval.v_string = (char_u *)ga.ga_data;
12956 else
12957 rettv->vval.v_string = NULL;
12961 * "keys()" function
12963 static void
12964 f_keys(argvars, rettv)
12965 typval_T *argvars;
12966 typval_T *rettv;
12968 dict_list(argvars, rettv, 0);
12972 * "last_buffer_nr()" function.
12974 /*ARGSUSED*/
12975 static void
12976 f_last_buffer_nr(argvars, rettv)
12977 typval_T *argvars;
12978 typval_T *rettv;
12980 int n = 0;
12981 buf_T *buf;
12983 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12984 if (n < buf->b_fnum)
12985 n = buf->b_fnum;
12987 rettv->vval.v_number = n;
12991 * "len()" function
12993 static void
12994 f_len(argvars, rettv)
12995 typval_T *argvars;
12996 typval_T *rettv;
12998 switch (argvars[0].v_type)
13000 case VAR_STRING:
13001 case VAR_NUMBER:
13002 rettv->vval.v_number = (varnumber_T)STRLEN(
13003 get_tv_string(&argvars[0]));
13004 break;
13005 case VAR_LIST:
13006 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
13007 break;
13008 case VAR_DICT:
13009 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
13010 break;
13011 default:
13012 EMSG(_("E701: Invalid type for len()"));
13013 break;
13017 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
13019 static void
13020 libcall_common(argvars, rettv, type)
13021 typval_T *argvars;
13022 typval_T *rettv;
13023 int type;
13025 #ifdef FEAT_LIBCALL
13026 char_u *string_in;
13027 char_u **string_result;
13028 int nr_result;
13029 #endif
13031 rettv->v_type = type;
13032 if (type == VAR_NUMBER)
13033 rettv->vval.v_number = 0;
13034 else
13035 rettv->vval.v_string = NULL;
13037 if (check_restricted() || check_secure())
13038 return;
13040 #ifdef FEAT_LIBCALL
13041 /* The first two args must be strings, otherwise its meaningless */
13042 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
13044 string_in = NULL;
13045 if (argvars[2].v_type == VAR_STRING)
13046 string_in = argvars[2].vval.v_string;
13047 if (type == VAR_NUMBER)
13048 string_result = NULL;
13049 else
13050 string_result = &rettv->vval.v_string;
13051 if (mch_libcall(argvars[0].vval.v_string,
13052 argvars[1].vval.v_string,
13053 string_in,
13054 argvars[2].vval.v_number,
13055 string_result,
13056 &nr_result) == OK
13057 && type == VAR_NUMBER)
13058 rettv->vval.v_number = nr_result;
13060 #endif
13064 * "libcall()" function
13066 static void
13067 f_libcall(argvars, rettv)
13068 typval_T *argvars;
13069 typval_T *rettv;
13071 libcall_common(argvars, rettv, VAR_STRING);
13075 * "libcallnr()" function
13077 static void
13078 f_libcallnr(argvars, rettv)
13079 typval_T *argvars;
13080 typval_T *rettv;
13082 libcall_common(argvars, rettv, VAR_NUMBER);
13086 * "line(string)" function
13088 static void
13089 f_line(argvars, rettv)
13090 typval_T *argvars;
13091 typval_T *rettv;
13093 linenr_T lnum = 0;
13094 pos_T *fp;
13095 int fnum;
13097 fp = var2fpos(&argvars[0], TRUE, &fnum);
13098 if (fp != NULL)
13099 lnum = fp->lnum;
13100 rettv->vval.v_number = lnum;
13104 * "line2byte(lnum)" function
13106 /*ARGSUSED*/
13107 static void
13108 f_line2byte(argvars, rettv)
13109 typval_T *argvars;
13110 typval_T *rettv;
13112 #ifndef FEAT_BYTEOFF
13113 rettv->vval.v_number = -1;
13114 #else
13115 linenr_T lnum;
13117 lnum = get_tv_lnum(argvars);
13118 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
13119 rettv->vval.v_number = -1;
13120 else
13121 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
13122 if (rettv->vval.v_number >= 0)
13123 ++rettv->vval.v_number;
13124 #endif
13128 * "lispindent(lnum)" function
13130 static void
13131 f_lispindent(argvars, rettv)
13132 typval_T *argvars;
13133 typval_T *rettv;
13135 #ifdef FEAT_LISP
13136 pos_T pos;
13137 linenr_T lnum;
13139 pos = curwin->w_cursor;
13140 lnum = get_tv_lnum(argvars);
13141 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
13143 curwin->w_cursor.lnum = lnum;
13144 rettv->vval.v_number = get_lisp_indent();
13145 curwin->w_cursor = pos;
13147 else
13148 #endif
13149 rettv->vval.v_number = -1;
13153 * "localtime()" function
13155 /*ARGSUSED*/
13156 static void
13157 f_localtime(argvars, rettv)
13158 typval_T *argvars;
13159 typval_T *rettv;
13161 rettv->vval.v_number = (varnumber_T)time(NULL);
13164 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
13166 static void
13167 get_maparg(argvars, rettv, exact)
13168 typval_T *argvars;
13169 typval_T *rettv;
13170 int exact;
13172 char_u *keys;
13173 char_u *which;
13174 char_u buf[NUMBUFLEN];
13175 char_u *keys_buf = NULL;
13176 char_u *rhs;
13177 int mode;
13178 garray_T ga;
13179 int abbr = FALSE;
13181 /* return empty string for failure */
13182 rettv->v_type = VAR_STRING;
13183 rettv->vval.v_string = NULL;
13185 keys = get_tv_string(&argvars[0]);
13186 if (*keys == NUL)
13187 return;
13189 if (argvars[1].v_type != VAR_UNKNOWN)
13191 which = get_tv_string_buf_chk(&argvars[1], buf);
13192 if (argvars[2].v_type != VAR_UNKNOWN)
13193 abbr = get_tv_number(&argvars[2]);
13195 else
13196 which = (char_u *)"";
13197 if (which == NULL)
13198 return;
13200 mode = get_map_mode(&which, 0);
13202 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
13203 rhs = check_map(keys, mode, exact, FALSE, abbr);
13204 vim_free(keys_buf);
13205 if (rhs != NULL)
13207 ga_init(&ga);
13208 ga.ga_itemsize = 1;
13209 ga.ga_growsize = 40;
13211 while (*rhs != NUL)
13212 ga_concat(&ga, str2special(&rhs, FALSE));
13214 ga_append(&ga, NUL);
13215 rettv->vval.v_string = (char_u *)ga.ga_data;
13219 #ifdef FEAT_FLOAT
13221 * "log10()" function
13223 static void
13224 f_log10(argvars, rettv)
13225 typval_T *argvars;
13226 typval_T *rettv;
13228 float_T f;
13230 rettv->v_type = VAR_FLOAT;
13231 if (get_float_arg(argvars, &f) == OK)
13232 rettv->vval.v_float = log10(f);
13233 else
13234 rettv->vval.v_float = 0.0;
13236 #endif
13239 * "map()" function
13241 static void
13242 f_map(argvars, rettv)
13243 typval_T *argvars;
13244 typval_T *rettv;
13246 filter_map(argvars, rettv, TRUE);
13250 * "maparg()" function
13252 static void
13253 f_maparg(argvars, rettv)
13254 typval_T *argvars;
13255 typval_T *rettv;
13257 get_maparg(argvars, rettv, TRUE);
13261 * "mapcheck()" function
13263 static void
13264 f_mapcheck(argvars, rettv)
13265 typval_T *argvars;
13266 typval_T *rettv;
13268 get_maparg(argvars, rettv, FALSE);
13271 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
13273 static void
13274 find_some_match(argvars, rettv, type)
13275 typval_T *argvars;
13276 typval_T *rettv;
13277 int type;
13279 char_u *str = NULL;
13280 char_u *expr = NULL;
13281 char_u *pat;
13282 regmatch_T regmatch;
13283 char_u patbuf[NUMBUFLEN];
13284 char_u strbuf[NUMBUFLEN];
13285 char_u *save_cpo;
13286 long start = 0;
13287 long nth = 1;
13288 colnr_T startcol = 0;
13289 int match = 0;
13290 list_T *l = NULL;
13291 listitem_T *li = NULL;
13292 long idx = 0;
13293 char_u *tofree = NULL;
13295 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
13296 save_cpo = p_cpo;
13297 p_cpo = (char_u *)"";
13299 rettv->vval.v_number = -1;
13300 if (type == 3)
13302 /* return empty list when there are no matches */
13303 if (rettv_list_alloc(rettv) == FAIL)
13304 goto theend;
13306 else if (type == 2)
13308 rettv->v_type = VAR_STRING;
13309 rettv->vval.v_string = NULL;
13312 if (argvars[0].v_type == VAR_LIST)
13314 if ((l = argvars[0].vval.v_list) == NULL)
13315 goto theend;
13316 li = l->lv_first;
13318 else
13319 expr = str = get_tv_string(&argvars[0]);
13321 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
13322 if (pat == NULL)
13323 goto theend;
13325 if (argvars[2].v_type != VAR_UNKNOWN)
13327 int error = FALSE;
13329 start = get_tv_number_chk(&argvars[2], &error);
13330 if (error)
13331 goto theend;
13332 if (l != NULL)
13334 li = list_find(l, start);
13335 if (li == NULL)
13336 goto theend;
13337 idx = l->lv_idx; /* use the cached index */
13339 else
13341 if (start < 0)
13342 start = 0;
13343 if (start > (long)STRLEN(str))
13344 goto theend;
13345 /* When "count" argument is there ignore matches before "start",
13346 * otherwise skip part of the string. Differs when pattern is "^"
13347 * or "\<". */
13348 if (argvars[3].v_type != VAR_UNKNOWN)
13349 startcol = start;
13350 else
13351 str += start;
13354 if (argvars[3].v_type != VAR_UNKNOWN)
13355 nth = get_tv_number_chk(&argvars[3], &error);
13356 if (error)
13357 goto theend;
13360 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
13361 if (regmatch.regprog != NULL)
13363 regmatch.rm_ic = p_ic;
13365 for (;;)
13367 if (l != NULL)
13369 if (li == NULL)
13371 match = FALSE;
13372 break;
13374 vim_free(tofree);
13375 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
13376 if (str == NULL)
13377 break;
13380 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
13382 if (match && --nth <= 0)
13383 break;
13384 if (l == NULL && !match)
13385 break;
13387 /* Advance to just after the match. */
13388 if (l != NULL)
13390 li = li->li_next;
13391 ++idx;
13393 else
13395 #ifdef FEAT_MBYTE
13396 startcol = (colnr_T)(regmatch.startp[0]
13397 + (*mb_ptr2len)(regmatch.startp[0]) - str);
13398 #else
13399 startcol = regmatch.startp[0] + 1 - str;
13400 #endif
13404 if (match)
13406 if (type == 3)
13408 int i;
13410 /* return list with matched string and submatches */
13411 for (i = 0; i < NSUBEXP; ++i)
13413 if (regmatch.endp[i] == NULL)
13415 if (list_append_string(rettv->vval.v_list,
13416 (char_u *)"", 0) == FAIL)
13417 break;
13419 else if (list_append_string(rettv->vval.v_list,
13420 regmatch.startp[i],
13421 (int)(regmatch.endp[i] - regmatch.startp[i]))
13422 == FAIL)
13423 break;
13426 else if (type == 2)
13428 /* return matched string */
13429 if (l != NULL)
13430 copy_tv(&li->li_tv, rettv);
13431 else
13432 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
13433 (int)(regmatch.endp[0] - regmatch.startp[0]));
13435 else if (l != NULL)
13436 rettv->vval.v_number = idx;
13437 else
13439 if (type != 0)
13440 rettv->vval.v_number =
13441 (varnumber_T)(regmatch.startp[0] - str);
13442 else
13443 rettv->vval.v_number =
13444 (varnumber_T)(regmatch.endp[0] - str);
13445 rettv->vval.v_number += (varnumber_T)(str - expr);
13448 vim_free(regmatch.regprog);
13451 theend:
13452 vim_free(tofree);
13453 p_cpo = save_cpo;
13457 * "match()" function
13459 static void
13460 f_match(argvars, rettv)
13461 typval_T *argvars;
13462 typval_T *rettv;
13464 find_some_match(argvars, rettv, 1);
13468 * "matchadd()" function
13470 static void
13471 f_matchadd(argvars, rettv)
13472 typval_T *argvars;
13473 typval_T *rettv;
13475 #ifdef FEAT_SEARCH_EXTRA
13476 char_u buf[NUMBUFLEN];
13477 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
13478 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
13479 int prio = 10; /* default priority */
13480 int id = -1;
13481 int error = FALSE;
13483 rettv->vval.v_number = -1;
13485 if (grp == NULL || pat == NULL)
13486 return;
13487 if (argvars[2].v_type != VAR_UNKNOWN)
13489 prio = get_tv_number_chk(&argvars[2], &error);
13490 if (argvars[3].v_type != VAR_UNKNOWN)
13491 id = get_tv_number_chk(&argvars[3], &error);
13493 if (error == TRUE)
13494 return;
13495 if (id >= 1 && id <= 3)
13497 EMSGN("E798: ID is reserved for \":match\": %ld", id);
13498 return;
13501 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
13502 #endif
13506 * "matcharg()" function
13508 static void
13509 f_matcharg(argvars, rettv)
13510 typval_T *argvars;
13511 typval_T *rettv;
13513 if (rettv_list_alloc(rettv) == OK)
13515 #ifdef FEAT_SEARCH_EXTRA
13516 int id = get_tv_number(&argvars[0]);
13517 matchitem_T *m;
13519 if (id >= 1 && id <= 3)
13521 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
13523 list_append_string(rettv->vval.v_list,
13524 syn_id2name(m->hlg_id), -1);
13525 list_append_string(rettv->vval.v_list, m->pattern, -1);
13527 else
13529 list_append_string(rettv->vval.v_list, NUL, -1);
13530 list_append_string(rettv->vval.v_list, NUL, -1);
13533 #endif
13538 * "matchdelete()" function
13540 static void
13541 f_matchdelete(argvars, rettv)
13542 typval_T *argvars;
13543 typval_T *rettv;
13545 #ifdef FEAT_SEARCH_EXTRA
13546 rettv->vval.v_number = match_delete(curwin,
13547 (int)get_tv_number(&argvars[0]), TRUE);
13548 #endif
13552 * "matchend()" function
13554 static void
13555 f_matchend(argvars, rettv)
13556 typval_T *argvars;
13557 typval_T *rettv;
13559 find_some_match(argvars, rettv, 0);
13563 * "matchlist()" function
13565 static void
13566 f_matchlist(argvars, rettv)
13567 typval_T *argvars;
13568 typval_T *rettv;
13570 find_some_match(argvars, rettv, 3);
13574 * "matchstr()" function
13576 static void
13577 f_matchstr(argvars, rettv)
13578 typval_T *argvars;
13579 typval_T *rettv;
13581 find_some_match(argvars, rettv, 2);
13584 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
13586 static void
13587 max_min(argvars, rettv, domax)
13588 typval_T *argvars;
13589 typval_T *rettv;
13590 int domax;
13592 long n = 0;
13593 long i;
13594 int error = FALSE;
13596 if (argvars[0].v_type == VAR_LIST)
13598 list_T *l;
13599 listitem_T *li;
13601 l = argvars[0].vval.v_list;
13602 if (l != NULL)
13604 li = l->lv_first;
13605 if (li != NULL)
13607 n = get_tv_number_chk(&li->li_tv, &error);
13608 for (;;)
13610 li = li->li_next;
13611 if (li == NULL)
13612 break;
13613 i = get_tv_number_chk(&li->li_tv, &error);
13614 if (domax ? i > n : i < n)
13615 n = i;
13620 else if (argvars[0].v_type == VAR_DICT)
13622 dict_T *d;
13623 int first = TRUE;
13624 hashitem_T *hi;
13625 int todo;
13627 d = argvars[0].vval.v_dict;
13628 if (d != NULL)
13630 todo = (int)d->dv_hashtab.ht_used;
13631 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13633 if (!HASHITEM_EMPTY(hi))
13635 --todo;
13636 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
13637 if (first)
13639 n = i;
13640 first = FALSE;
13642 else if (domax ? i > n : i < n)
13643 n = i;
13648 else
13649 EMSG(_(e_listdictarg));
13650 rettv->vval.v_number = error ? 0 : n;
13654 * "max()" function
13656 static void
13657 f_max(argvars, rettv)
13658 typval_T *argvars;
13659 typval_T *rettv;
13661 max_min(argvars, rettv, TRUE);
13665 * "min()" function
13667 static void
13668 f_min(argvars, rettv)
13669 typval_T *argvars;
13670 typval_T *rettv;
13672 max_min(argvars, rettv, FALSE);
13675 static int mkdir_recurse __ARGS((char_u *dir, int prot));
13678 * Create the directory in which "dir" is located, and higher levels when
13679 * needed.
13681 static int
13682 mkdir_recurse(dir, prot)
13683 char_u *dir;
13684 int prot;
13686 char_u *p;
13687 char_u *updir;
13688 int r = FAIL;
13690 /* Get end of directory name in "dir".
13691 * We're done when it's "/" or "c:/". */
13692 p = gettail_sep(dir);
13693 if (p <= get_past_head(dir))
13694 return OK;
13696 /* If the directory exists we're done. Otherwise: create it.*/
13697 updir = vim_strnsave(dir, (int)(p - dir));
13698 if (updir == NULL)
13699 return FAIL;
13700 if (mch_isdir(updir))
13701 r = OK;
13702 else if (mkdir_recurse(updir, prot) == OK)
13703 r = vim_mkdir_emsg(updir, prot);
13704 vim_free(updir);
13705 return r;
13708 #ifdef vim_mkdir
13710 * "mkdir()" function
13712 static void
13713 f_mkdir(argvars, rettv)
13714 typval_T *argvars;
13715 typval_T *rettv;
13717 char_u *dir;
13718 char_u buf[NUMBUFLEN];
13719 int prot = 0755;
13721 rettv->vval.v_number = FAIL;
13722 if (check_restricted() || check_secure())
13723 return;
13725 dir = get_tv_string_buf(&argvars[0], buf);
13726 if (argvars[1].v_type != VAR_UNKNOWN)
13728 if (argvars[2].v_type != VAR_UNKNOWN)
13729 prot = get_tv_number_chk(&argvars[2], NULL);
13730 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
13731 mkdir_recurse(dir, prot);
13733 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
13735 #endif
13738 * "mode()" function
13740 /*ARGSUSED*/
13741 static void
13742 f_mode(argvars, rettv)
13743 typval_T *argvars;
13744 typval_T *rettv;
13746 char_u buf[3];
13748 buf[1] = NUL;
13749 buf[2] = NUL;
13751 #ifdef FEAT_VISUAL
13752 if (VIsual_active)
13754 if (VIsual_select)
13755 buf[0] = VIsual_mode + 's' - 'v';
13756 else
13757 buf[0] = VIsual_mode;
13759 else
13760 #endif
13761 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
13762 || State == CONFIRM)
13764 buf[0] = 'r';
13765 if (State == ASKMORE)
13766 buf[1] = 'm';
13767 else if (State == CONFIRM)
13768 buf[1] = '?';
13770 else if (State == EXTERNCMD)
13771 buf[0] = '!';
13772 else if (State & INSERT)
13774 #ifdef FEAT_VREPLACE
13775 if (State & VREPLACE_FLAG)
13777 buf[0] = 'R';
13778 buf[1] = 'v';
13780 else
13781 #endif
13782 if (State & REPLACE_FLAG)
13783 buf[0] = 'R';
13784 else
13785 buf[0] = 'i';
13787 else if (State & CMDLINE)
13789 buf[0] = 'c';
13790 if (exmode_active)
13791 buf[1] = 'v';
13793 else if (exmode_active)
13795 buf[0] = 'c';
13796 buf[1] = 'e';
13798 else
13800 buf[0] = 'n';
13801 if (finish_op)
13802 buf[1] = 'o';
13805 /* Clear out the minor mode when the argument is not a non-zero number or
13806 * non-empty string. */
13807 if (!non_zero_arg(&argvars[0]))
13808 buf[1] = NUL;
13810 rettv->vval.v_string = vim_strsave(buf);
13811 rettv->v_type = VAR_STRING;
13815 * "nextnonblank()" function
13817 static void
13818 f_nextnonblank(argvars, rettv)
13819 typval_T *argvars;
13820 typval_T *rettv;
13822 linenr_T lnum;
13824 for (lnum = get_tv_lnum(argvars); ; ++lnum)
13826 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
13828 lnum = 0;
13829 break;
13831 if (*skipwhite(ml_get(lnum)) != NUL)
13832 break;
13834 rettv->vval.v_number = lnum;
13838 * "nr2char()" function
13840 static void
13841 f_nr2char(argvars, rettv)
13842 typval_T *argvars;
13843 typval_T *rettv;
13845 char_u buf[NUMBUFLEN];
13847 #ifdef FEAT_MBYTE
13848 if (has_mbyte)
13849 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
13850 else
13851 #endif
13853 buf[0] = (char_u)get_tv_number(&argvars[0]);
13854 buf[1] = NUL;
13856 rettv->v_type = VAR_STRING;
13857 rettv->vval.v_string = vim_strsave(buf);
13861 * "pathshorten()" function
13863 static void
13864 f_pathshorten(argvars, rettv)
13865 typval_T *argvars;
13866 typval_T *rettv;
13868 char_u *p;
13870 rettv->v_type = VAR_STRING;
13871 p = get_tv_string_chk(&argvars[0]);
13872 if (p == NULL)
13873 rettv->vval.v_string = NULL;
13874 else
13876 p = vim_strsave(p);
13877 rettv->vval.v_string = p;
13878 if (p != NULL)
13879 shorten_dir(p);
13883 #ifdef FEAT_FLOAT
13885 * "pow()" function
13887 static void
13888 f_pow(argvars, rettv)
13889 typval_T *argvars;
13890 typval_T *rettv;
13892 float_T fx, fy;
13894 rettv->v_type = VAR_FLOAT;
13895 if (get_float_arg(argvars, &fx) == OK
13896 && get_float_arg(&argvars[1], &fy) == OK)
13897 rettv->vval.v_float = pow(fx, fy);
13898 else
13899 rettv->vval.v_float = 0.0;
13901 #endif
13904 * "prevnonblank()" function
13906 static void
13907 f_prevnonblank(argvars, rettv)
13908 typval_T *argvars;
13909 typval_T *rettv;
13911 linenr_T lnum;
13913 lnum = get_tv_lnum(argvars);
13914 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
13915 lnum = 0;
13916 else
13917 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
13918 --lnum;
13919 rettv->vval.v_number = lnum;
13922 #ifdef HAVE_STDARG_H
13923 /* This dummy va_list is here because:
13924 * - passing a NULL pointer doesn't work when va_list isn't a pointer
13925 * - locally in the function results in a "used before set" warning
13926 * - using va_start() to initialize it gives "function with fixed args" error */
13927 static va_list ap;
13928 #endif
13931 * "printf()" function
13933 static void
13934 f_printf(argvars, rettv)
13935 typval_T *argvars;
13936 typval_T *rettv;
13938 rettv->v_type = VAR_STRING;
13939 rettv->vval.v_string = NULL;
13940 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
13942 char_u buf[NUMBUFLEN];
13943 int len;
13944 char_u *s;
13945 int saved_did_emsg = did_emsg;
13946 char *fmt;
13948 /* Get the required length, allocate the buffer and do it for real. */
13949 did_emsg = FALSE;
13950 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
13951 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
13952 if (!did_emsg)
13954 s = alloc(len + 1);
13955 if (s != NULL)
13957 rettv->vval.v_string = s;
13958 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
13961 did_emsg |= saved_did_emsg;
13963 #endif
13967 * "pumvisible()" function
13969 /*ARGSUSED*/
13970 static void
13971 f_pumvisible(argvars, rettv)
13972 typval_T *argvars;
13973 typval_T *rettv;
13975 rettv->vval.v_number = 0;
13976 #ifdef FEAT_INS_EXPAND
13977 if (pum_visible())
13978 rettv->vval.v_number = 1;
13979 #endif
13983 * "range()" function
13985 static void
13986 f_range(argvars, rettv)
13987 typval_T *argvars;
13988 typval_T *rettv;
13990 long start;
13991 long end;
13992 long stride = 1;
13993 long i;
13994 int error = FALSE;
13996 start = get_tv_number_chk(&argvars[0], &error);
13997 if (argvars[1].v_type == VAR_UNKNOWN)
13999 end = start - 1;
14000 start = 0;
14002 else
14004 end = get_tv_number_chk(&argvars[1], &error);
14005 if (argvars[2].v_type != VAR_UNKNOWN)
14006 stride = get_tv_number_chk(&argvars[2], &error);
14009 rettv->vval.v_number = 0;
14010 if (error)
14011 return; /* type error; errmsg already given */
14012 if (stride == 0)
14013 EMSG(_("E726: Stride is zero"));
14014 else if (stride > 0 ? end + 1 < start : end - 1 > start)
14015 EMSG(_("E727: Start past end"));
14016 else
14018 if (rettv_list_alloc(rettv) == OK)
14019 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
14020 if (list_append_number(rettv->vval.v_list,
14021 (varnumber_T)i) == FAIL)
14022 break;
14027 * "readfile()" function
14029 static void
14030 f_readfile(argvars, rettv)
14031 typval_T *argvars;
14032 typval_T *rettv;
14034 int binary = FALSE;
14035 char_u *fname;
14036 FILE *fd;
14037 listitem_T *li;
14038 #define FREAD_SIZE 200 /* optimized for text lines */
14039 char_u buf[FREAD_SIZE];
14040 int readlen; /* size of last fread() */
14041 int buflen; /* nr of valid chars in buf[] */
14042 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
14043 int tolist; /* first byte in buf[] still to be put in list */
14044 int chop; /* how many CR to chop off */
14045 char_u *prev = NULL; /* previously read bytes, if any */
14046 int prevlen = 0; /* length of "prev" if not NULL */
14047 char_u *s;
14048 int len;
14049 long maxline = MAXLNUM;
14050 long cnt = 0;
14052 if (argvars[1].v_type != VAR_UNKNOWN)
14054 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
14055 binary = TRUE;
14056 if (argvars[2].v_type != VAR_UNKNOWN)
14057 maxline = get_tv_number(&argvars[2]);
14060 if (rettv_list_alloc(rettv) == FAIL)
14061 return;
14063 /* Always open the file in binary mode, library functions have a mind of
14064 * their own about CR-LF conversion. */
14065 fname = get_tv_string(&argvars[0]);
14066 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
14068 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
14069 return;
14072 filtd = 0;
14073 while (cnt < maxline || maxline < 0)
14075 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
14076 buflen = filtd + readlen;
14077 tolist = 0;
14078 for ( ; filtd < buflen || readlen <= 0; ++filtd)
14080 if (buf[filtd] == '\n' || readlen <= 0)
14082 /* Only when in binary mode add an empty list item when the
14083 * last line ends in a '\n'. */
14084 if (!binary && readlen == 0 && filtd == 0)
14085 break;
14087 /* Found end-of-line or end-of-file: add a text line to the
14088 * list. */
14089 chop = 0;
14090 if (!binary)
14091 while (filtd - chop - 1 >= tolist
14092 && buf[filtd - chop - 1] == '\r')
14093 ++chop;
14094 len = filtd - tolist - chop;
14095 if (prev == NULL)
14096 s = vim_strnsave(buf + tolist, len);
14097 else
14099 s = alloc((unsigned)(prevlen + len + 1));
14100 if (s != NULL)
14102 mch_memmove(s, prev, prevlen);
14103 vim_free(prev);
14104 prev = NULL;
14105 mch_memmove(s + prevlen, buf + tolist, len);
14106 s[prevlen + len] = NUL;
14109 tolist = filtd + 1;
14111 li = listitem_alloc();
14112 if (li == NULL)
14114 vim_free(s);
14115 break;
14117 li->li_tv.v_type = VAR_STRING;
14118 li->li_tv.v_lock = 0;
14119 li->li_tv.vval.v_string = s;
14120 list_append(rettv->vval.v_list, li);
14122 if (++cnt >= maxline && maxline >= 0)
14123 break;
14124 if (readlen <= 0)
14125 break;
14127 else if (buf[filtd] == NUL)
14128 buf[filtd] = '\n';
14130 if (readlen <= 0)
14131 break;
14133 if (tolist == 0)
14135 /* "buf" is full, need to move text to an allocated buffer */
14136 if (prev == NULL)
14138 prev = vim_strnsave(buf, buflen);
14139 prevlen = buflen;
14141 else
14143 s = alloc((unsigned)(prevlen + buflen));
14144 if (s != NULL)
14146 mch_memmove(s, prev, prevlen);
14147 mch_memmove(s + prevlen, buf, buflen);
14148 vim_free(prev);
14149 prev = s;
14150 prevlen += buflen;
14153 filtd = 0;
14155 else
14157 mch_memmove(buf, buf + tolist, buflen - tolist);
14158 filtd -= tolist;
14163 * For a negative line count use only the lines at the end of the file,
14164 * free the rest.
14166 if (maxline < 0)
14167 while (cnt > -maxline)
14169 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
14170 --cnt;
14173 vim_free(prev);
14174 fclose(fd);
14177 #if defined(FEAT_RELTIME)
14178 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
14181 * Convert a List to proftime_T.
14182 * Return FAIL when there is something wrong.
14184 static int
14185 list2proftime(arg, tm)
14186 typval_T *arg;
14187 proftime_T *tm;
14189 long n1, n2;
14190 int error = FALSE;
14192 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
14193 || arg->vval.v_list->lv_len != 2)
14194 return FAIL;
14195 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
14196 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
14197 # ifdef WIN3264
14198 tm->HighPart = n1;
14199 tm->LowPart = n2;
14200 # else
14201 tm->tv_sec = n1;
14202 tm->tv_usec = n2;
14203 # endif
14204 return error ? FAIL : OK;
14206 #endif /* FEAT_RELTIME */
14209 * "reltime()" function
14211 static void
14212 f_reltime(argvars, rettv)
14213 typval_T *argvars;
14214 typval_T *rettv;
14216 #ifdef FEAT_RELTIME
14217 proftime_T res;
14218 proftime_T start;
14220 if (argvars[0].v_type == VAR_UNKNOWN)
14222 /* No arguments: get current time. */
14223 profile_start(&res);
14225 else if (argvars[1].v_type == VAR_UNKNOWN)
14227 if (list2proftime(&argvars[0], &res) == FAIL)
14228 return;
14229 profile_end(&res);
14231 else
14233 /* Two arguments: compute the difference. */
14234 if (list2proftime(&argvars[0], &start) == FAIL
14235 || list2proftime(&argvars[1], &res) == FAIL)
14236 return;
14237 profile_sub(&res, &start);
14240 if (rettv_list_alloc(rettv) == OK)
14242 long n1, n2;
14244 # ifdef WIN3264
14245 n1 = res.HighPart;
14246 n2 = res.LowPart;
14247 # else
14248 n1 = res.tv_sec;
14249 n2 = res.tv_usec;
14250 # endif
14251 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
14252 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
14254 #endif
14258 * "reltimestr()" function
14260 static void
14261 f_reltimestr(argvars, rettv)
14262 typval_T *argvars;
14263 typval_T *rettv;
14265 #ifdef FEAT_RELTIME
14266 proftime_T tm;
14267 #endif
14269 rettv->v_type = VAR_STRING;
14270 rettv->vval.v_string = NULL;
14271 #ifdef FEAT_RELTIME
14272 if (list2proftime(&argvars[0], &tm) == OK)
14273 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
14274 #endif
14277 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
14278 static void make_connection __ARGS((void));
14279 static int check_connection __ARGS((void));
14281 static void
14282 make_connection()
14284 if (X_DISPLAY == NULL
14285 # ifdef FEAT_GUI
14286 && !gui.in_use
14287 # endif
14290 x_force_connect = TRUE;
14291 setup_term_clip();
14292 x_force_connect = FALSE;
14296 static int
14297 check_connection()
14299 make_connection();
14300 if (X_DISPLAY == NULL)
14302 EMSG(_("E240: No connection to Vim server"));
14303 return FAIL;
14305 return OK;
14307 #endif
14309 #ifdef FEAT_CLIENTSERVER
14310 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
14312 static void
14313 remote_common(argvars, rettv, expr)
14314 typval_T *argvars;
14315 typval_T *rettv;
14316 int expr;
14318 char_u *server_name;
14319 char_u *keys;
14320 char_u *r = NULL;
14321 char_u buf[NUMBUFLEN];
14322 # ifdef WIN32
14323 HWND w;
14324 # else
14325 Window w;
14326 # endif
14328 if (check_restricted() || check_secure())
14329 return;
14331 # ifdef FEAT_X11
14332 if (check_connection() == FAIL)
14333 return;
14334 # endif
14336 server_name = get_tv_string_chk(&argvars[0]);
14337 if (server_name == NULL)
14338 return; /* type error; errmsg already given */
14339 keys = get_tv_string_buf(&argvars[1], buf);
14340 # ifdef WIN32
14341 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14342 # else
14343 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
14344 < 0)
14345 # endif
14347 if (r != NULL)
14348 EMSG(r); /* sending worked but evaluation failed */
14349 else
14350 EMSG2(_("E241: Unable to send to %s"), server_name);
14351 return;
14354 rettv->vval.v_string = r;
14356 if (argvars[2].v_type != VAR_UNKNOWN)
14358 dictitem_T v;
14359 char_u str[30];
14360 char_u *idvar;
14362 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
14363 v.di_tv.v_type = VAR_STRING;
14364 v.di_tv.vval.v_string = vim_strsave(str);
14365 idvar = get_tv_string_chk(&argvars[2]);
14366 if (idvar != NULL)
14367 set_var(idvar, &v.di_tv, FALSE);
14368 vim_free(v.di_tv.vval.v_string);
14371 #endif
14374 * "remote_expr()" function
14376 /*ARGSUSED*/
14377 static void
14378 f_remote_expr(argvars, rettv)
14379 typval_T *argvars;
14380 typval_T *rettv;
14382 rettv->v_type = VAR_STRING;
14383 rettv->vval.v_string = NULL;
14384 #ifdef FEAT_CLIENTSERVER
14385 remote_common(argvars, rettv, TRUE);
14386 #endif
14390 * "remote_foreground()" function
14392 /*ARGSUSED*/
14393 static void
14394 f_remote_foreground(argvars, rettv)
14395 typval_T *argvars;
14396 typval_T *rettv;
14398 rettv->vval.v_number = 0;
14399 #ifdef FEAT_CLIENTSERVER
14400 # ifdef WIN32
14401 /* On Win32 it's done in this application. */
14403 char_u *server_name = get_tv_string_chk(&argvars[0]);
14405 if (server_name != NULL)
14406 serverForeground(server_name);
14408 # else
14409 /* Send a foreground() expression to the server. */
14410 argvars[1].v_type = VAR_STRING;
14411 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
14412 argvars[2].v_type = VAR_UNKNOWN;
14413 remote_common(argvars, rettv, TRUE);
14414 vim_free(argvars[1].vval.v_string);
14415 # endif
14416 #endif
14419 /*ARGSUSED*/
14420 static void
14421 f_remote_peek(argvars, rettv)
14422 typval_T *argvars;
14423 typval_T *rettv;
14425 #ifdef FEAT_CLIENTSERVER
14426 dictitem_T v;
14427 char_u *s = NULL;
14428 # ifdef WIN32
14429 long_u n = 0;
14430 # endif
14431 char_u *serverid;
14433 if (check_restricted() || check_secure())
14435 rettv->vval.v_number = -1;
14436 return;
14438 serverid = get_tv_string_chk(&argvars[0]);
14439 if (serverid == NULL)
14441 rettv->vval.v_number = -1;
14442 return; /* type error; errmsg already given */
14444 # ifdef WIN32
14445 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14446 if (n == 0)
14447 rettv->vval.v_number = -1;
14448 else
14450 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
14451 rettv->vval.v_number = (s != NULL);
14453 # else
14454 rettv->vval.v_number = 0;
14455 if (check_connection() == FAIL)
14456 return;
14458 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
14459 serverStrToWin(serverid), &s);
14460 # endif
14462 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
14464 char_u *retvar;
14466 v.di_tv.v_type = VAR_STRING;
14467 v.di_tv.vval.v_string = vim_strsave(s);
14468 retvar = get_tv_string_chk(&argvars[1]);
14469 if (retvar != NULL)
14470 set_var(retvar, &v.di_tv, FALSE);
14471 vim_free(v.di_tv.vval.v_string);
14473 #else
14474 rettv->vval.v_number = -1;
14475 #endif
14478 /*ARGSUSED*/
14479 static void
14480 f_remote_read(argvars, rettv)
14481 typval_T *argvars;
14482 typval_T *rettv;
14484 char_u *r = NULL;
14486 #ifdef FEAT_CLIENTSERVER
14487 char_u *serverid = get_tv_string_chk(&argvars[0]);
14489 if (serverid != NULL && !check_restricted() && !check_secure())
14491 # ifdef WIN32
14492 /* The server's HWND is encoded in the 'id' parameter */
14493 long_u n = 0;
14495 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14496 if (n != 0)
14497 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
14498 if (r == NULL)
14499 # else
14500 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
14501 serverStrToWin(serverid), &r, FALSE) < 0)
14502 # endif
14503 EMSG(_("E277: Unable to read a server reply"));
14505 #endif
14506 rettv->v_type = VAR_STRING;
14507 rettv->vval.v_string = r;
14511 * "remote_send()" function
14513 /*ARGSUSED*/
14514 static void
14515 f_remote_send(argvars, rettv)
14516 typval_T *argvars;
14517 typval_T *rettv;
14519 rettv->v_type = VAR_STRING;
14520 rettv->vval.v_string = NULL;
14521 #ifdef FEAT_CLIENTSERVER
14522 remote_common(argvars, rettv, FALSE);
14523 #endif
14527 * "remove()" function
14529 static void
14530 f_remove(argvars, rettv)
14531 typval_T *argvars;
14532 typval_T *rettv;
14534 list_T *l;
14535 listitem_T *item, *item2;
14536 listitem_T *li;
14537 long idx;
14538 long end;
14539 char_u *key;
14540 dict_T *d;
14541 dictitem_T *di;
14543 rettv->vval.v_number = 0;
14544 if (argvars[0].v_type == VAR_DICT)
14546 if (argvars[2].v_type != VAR_UNKNOWN)
14547 EMSG2(_(e_toomanyarg), "remove()");
14548 else if ((d = argvars[0].vval.v_dict) != NULL
14549 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
14551 key = get_tv_string_chk(&argvars[1]);
14552 if (key != NULL)
14554 di = dict_find(d, key, -1);
14555 if (di == NULL)
14556 EMSG2(_(e_dictkey), key);
14557 else
14559 *rettv = di->di_tv;
14560 init_tv(&di->di_tv);
14561 dictitem_remove(d, di);
14566 else if (argvars[0].v_type != VAR_LIST)
14567 EMSG2(_(e_listdictarg), "remove()");
14568 else if ((l = argvars[0].vval.v_list) != NULL
14569 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
14571 int error = FALSE;
14573 idx = get_tv_number_chk(&argvars[1], &error);
14574 if (error)
14575 ; /* type error: do nothing, errmsg already given */
14576 else if ((item = list_find(l, idx)) == NULL)
14577 EMSGN(_(e_listidx), idx);
14578 else
14580 if (argvars[2].v_type == VAR_UNKNOWN)
14582 /* Remove one item, return its value. */
14583 list_remove(l, item, item);
14584 *rettv = item->li_tv;
14585 vim_free(item);
14587 else
14589 /* Remove range of items, return list with values. */
14590 end = get_tv_number_chk(&argvars[2], &error);
14591 if (error)
14592 ; /* type error: do nothing */
14593 else if ((item2 = list_find(l, end)) == NULL)
14594 EMSGN(_(e_listidx), end);
14595 else
14597 int cnt = 0;
14599 for (li = item; li != NULL; li = li->li_next)
14601 ++cnt;
14602 if (li == item2)
14603 break;
14605 if (li == NULL) /* didn't find "item2" after "item" */
14606 EMSG(_(e_invrange));
14607 else
14609 list_remove(l, item, item2);
14610 if (rettv_list_alloc(rettv) == OK)
14612 l = rettv->vval.v_list;
14613 l->lv_first = item;
14614 l->lv_last = item2;
14615 item->li_prev = NULL;
14616 item2->li_next = NULL;
14617 l->lv_len = cnt;
14627 * "rename({from}, {to})" function
14629 static void
14630 f_rename(argvars, rettv)
14631 typval_T *argvars;
14632 typval_T *rettv;
14634 char_u buf[NUMBUFLEN];
14636 if (check_restricted() || check_secure())
14637 rettv->vval.v_number = -1;
14638 else
14639 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
14640 get_tv_string_buf(&argvars[1], buf));
14644 * "repeat()" function
14646 /*ARGSUSED*/
14647 static void
14648 f_repeat(argvars, rettv)
14649 typval_T *argvars;
14650 typval_T *rettv;
14652 char_u *p;
14653 int n;
14654 int slen;
14655 int len;
14656 char_u *r;
14657 int i;
14659 n = get_tv_number(&argvars[1]);
14660 if (argvars[0].v_type == VAR_LIST)
14662 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
14663 while (n-- > 0)
14664 if (list_extend(rettv->vval.v_list,
14665 argvars[0].vval.v_list, NULL) == FAIL)
14666 break;
14668 else
14670 p = get_tv_string(&argvars[0]);
14671 rettv->v_type = VAR_STRING;
14672 rettv->vval.v_string = NULL;
14674 slen = (int)STRLEN(p);
14675 len = slen * n;
14676 if (len <= 0)
14677 return;
14679 r = alloc(len + 1);
14680 if (r != NULL)
14682 for (i = 0; i < n; i++)
14683 mch_memmove(r + i * slen, p, (size_t)slen);
14684 r[len] = NUL;
14687 rettv->vval.v_string = r;
14692 * "resolve()" function
14694 static void
14695 f_resolve(argvars, rettv)
14696 typval_T *argvars;
14697 typval_T *rettv;
14699 char_u *p;
14701 p = get_tv_string(&argvars[0]);
14702 #ifdef FEAT_SHORTCUT
14704 char_u *v = NULL;
14706 v = mch_resolve_shortcut(p);
14707 if (v != NULL)
14708 rettv->vval.v_string = v;
14709 else
14710 rettv->vval.v_string = vim_strsave(p);
14712 #else
14713 # ifdef HAVE_READLINK
14715 char_u buf[MAXPATHL + 1];
14716 char_u *cpy;
14717 int len;
14718 char_u *remain = NULL;
14719 char_u *q;
14720 int is_relative_to_current = FALSE;
14721 int has_trailing_pathsep = FALSE;
14722 int limit = 100;
14724 p = vim_strsave(p);
14726 if (p[0] == '.' && (vim_ispathsep(p[1])
14727 || (p[1] == '.' && (vim_ispathsep(p[2])))))
14728 is_relative_to_current = TRUE;
14730 len = STRLEN(p);
14731 if (len > 0 && after_pathsep(p, p + len))
14732 has_trailing_pathsep = TRUE;
14734 q = getnextcomp(p);
14735 if (*q != NUL)
14737 /* Separate the first path component in "p", and keep the
14738 * remainder (beginning with the path separator). */
14739 remain = vim_strsave(q - 1);
14740 q[-1] = NUL;
14743 for (;;)
14745 for (;;)
14747 len = readlink((char *)p, (char *)buf, MAXPATHL);
14748 if (len <= 0)
14749 break;
14750 buf[len] = NUL;
14752 if (limit-- == 0)
14754 vim_free(p);
14755 vim_free(remain);
14756 EMSG(_("E655: Too many symbolic links (cycle?)"));
14757 rettv->vval.v_string = NULL;
14758 goto fail;
14761 /* Ensure that the result will have a trailing path separator
14762 * if the argument has one. */
14763 if (remain == NULL && has_trailing_pathsep)
14764 add_pathsep(buf);
14766 /* Separate the first path component in the link value and
14767 * concatenate the remainders. */
14768 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
14769 if (*q != NUL)
14771 if (remain == NULL)
14772 remain = vim_strsave(q - 1);
14773 else
14775 cpy = concat_str(q - 1, remain);
14776 if (cpy != NULL)
14778 vim_free(remain);
14779 remain = cpy;
14782 q[-1] = NUL;
14785 q = gettail(p);
14786 if (q > p && *q == NUL)
14788 /* Ignore trailing path separator. */
14789 q[-1] = NUL;
14790 q = gettail(p);
14792 if (q > p && !mch_isFullName(buf))
14794 /* symlink is relative to directory of argument */
14795 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
14796 if (cpy != NULL)
14798 STRCPY(cpy, p);
14799 STRCPY(gettail(cpy), buf);
14800 vim_free(p);
14801 p = cpy;
14804 else
14806 vim_free(p);
14807 p = vim_strsave(buf);
14811 if (remain == NULL)
14812 break;
14814 /* Append the first path component of "remain" to "p". */
14815 q = getnextcomp(remain + 1);
14816 len = q - remain - (*q != NUL);
14817 cpy = vim_strnsave(p, STRLEN(p) + len);
14818 if (cpy != NULL)
14820 STRNCAT(cpy, remain, len);
14821 vim_free(p);
14822 p = cpy;
14824 /* Shorten "remain". */
14825 if (*q != NUL)
14826 STRMOVE(remain, q - 1);
14827 else
14829 vim_free(remain);
14830 remain = NULL;
14834 /* If the result is a relative path name, make it explicitly relative to
14835 * the current directory if and only if the argument had this form. */
14836 if (!vim_ispathsep(*p))
14838 if (is_relative_to_current
14839 && *p != NUL
14840 && !(p[0] == '.'
14841 && (p[1] == NUL
14842 || vim_ispathsep(p[1])
14843 || (p[1] == '.'
14844 && (p[2] == NUL
14845 || vim_ispathsep(p[2]))))))
14847 /* Prepend "./". */
14848 cpy = concat_str((char_u *)"./", p);
14849 if (cpy != NULL)
14851 vim_free(p);
14852 p = cpy;
14855 else if (!is_relative_to_current)
14857 /* Strip leading "./". */
14858 q = p;
14859 while (q[0] == '.' && vim_ispathsep(q[1]))
14860 q += 2;
14861 if (q > p)
14862 STRMOVE(p, p + 2);
14866 /* Ensure that the result will have no trailing path separator
14867 * if the argument had none. But keep "/" or "//". */
14868 if (!has_trailing_pathsep)
14870 q = p + STRLEN(p);
14871 if (after_pathsep(p, q))
14872 *gettail_sep(p) = NUL;
14875 rettv->vval.v_string = p;
14877 # else
14878 rettv->vval.v_string = vim_strsave(p);
14879 # endif
14880 #endif
14882 simplify_filename(rettv->vval.v_string);
14884 #ifdef HAVE_READLINK
14885 fail:
14886 #endif
14887 rettv->v_type = VAR_STRING;
14891 * "reverse({list})" function
14893 static void
14894 f_reverse(argvars, rettv)
14895 typval_T *argvars;
14896 typval_T *rettv;
14898 list_T *l;
14899 listitem_T *li, *ni;
14901 rettv->vval.v_number = 0;
14902 if (argvars[0].v_type != VAR_LIST)
14903 EMSG2(_(e_listarg), "reverse()");
14904 else if ((l = argvars[0].vval.v_list) != NULL
14905 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
14907 li = l->lv_last;
14908 l->lv_first = l->lv_last = NULL;
14909 l->lv_len = 0;
14910 while (li != NULL)
14912 ni = li->li_prev;
14913 list_append(l, li);
14914 li = ni;
14916 rettv->vval.v_list = l;
14917 rettv->v_type = VAR_LIST;
14918 ++l->lv_refcount;
14919 l->lv_idx = l->lv_len - l->lv_idx - 1;
14923 #define SP_NOMOVE 0x01 /* don't move cursor */
14924 #define SP_REPEAT 0x02 /* repeat to find outer pair */
14925 #define SP_RETCOUNT 0x04 /* return matchcount */
14926 #define SP_SETPCMARK 0x08 /* set previous context mark */
14927 #define SP_START 0x10 /* accept match at start position */
14928 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
14929 #define SP_END 0x40 /* leave cursor at end of match */
14931 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
14934 * Get flags for a search function.
14935 * Possibly sets "p_ws".
14936 * Returns BACKWARD, FORWARD or zero (for an error).
14938 static int
14939 get_search_arg(varp, flagsp)
14940 typval_T *varp;
14941 int *flagsp;
14943 int dir = FORWARD;
14944 char_u *flags;
14945 char_u nbuf[NUMBUFLEN];
14946 int mask;
14948 if (varp->v_type != VAR_UNKNOWN)
14950 flags = get_tv_string_buf_chk(varp, nbuf);
14951 if (flags == NULL)
14952 return 0; /* type error; errmsg already given */
14953 while (*flags != NUL)
14955 switch (*flags)
14957 case 'b': dir = BACKWARD; break;
14958 case 'w': p_ws = TRUE; break;
14959 case 'W': p_ws = FALSE; break;
14960 default: mask = 0;
14961 if (flagsp != NULL)
14962 switch (*flags)
14964 case 'c': mask = SP_START; break;
14965 case 'e': mask = SP_END; break;
14966 case 'm': mask = SP_RETCOUNT; break;
14967 case 'n': mask = SP_NOMOVE; break;
14968 case 'p': mask = SP_SUBPAT; break;
14969 case 'r': mask = SP_REPEAT; break;
14970 case 's': mask = SP_SETPCMARK; break;
14972 if (mask == 0)
14974 EMSG2(_(e_invarg2), flags);
14975 dir = 0;
14977 else
14978 *flagsp |= mask;
14980 if (dir == 0)
14981 break;
14982 ++flags;
14985 return dir;
14989 * Shared by search() and searchpos() functions
14991 static int
14992 search_cmn(argvars, match_pos, flagsp)
14993 typval_T *argvars;
14994 pos_T *match_pos;
14995 int *flagsp;
14997 int flags;
14998 char_u *pat;
14999 pos_T pos;
15000 pos_T save_cursor;
15001 int save_p_ws = p_ws;
15002 int dir;
15003 int retval = 0; /* default: FAIL */
15004 long lnum_stop = 0;
15005 proftime_T tm;
15006 #ifdef FEAT_RELTIME
15007 long time_limit = 0;
15008 #endif
15009 int options = SEARCH_KEEP;
15010 int subpatnum;
15012 pat = get_tv_string(&argvars[0]);
15013 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
15014 if (dir == 0)
15015 goto theend;
15016 flags = *flagsp;
15017 if (flags & SP_START)
15018 options |= SEARCH_START;
15019 if (flags & SP_END)
15020 options |= SEARCH_END;
15022 /* Optional arguments: line number to stop searching and timeout. */
15023 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
15025 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
15026 if (lnum_stop < 0)
15027 goto theend;
15028 #ifdef FEAT_RELTIME
15029 if (argvars[3].v_type != VAR_UNKNOWN)
15031 time_limit = get_tv_number_chk(&argvars[3], NULL);
15032 if (time_limit < 0)
15033 goto theend;
15035 #endif
15038 #ifdef FEAT_RELTIME
15039 /* Set the time limit, if there is one. */
15040 profile_setlimit(time_limit, &tm);
15041 #endif
15044 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
15045 * Check to make sure only those flags are set.
15046 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
15047 * flags cannot be set. Check for that condition also.
15049 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
15050 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
15052 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
15053 goto theend;
15056 pos = save_cursor = curwin->w_cursor;
15057 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15058 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
15059 if (subpatnum != FAIL)
15061 if (flags & SP_SUBPAT)
15062 retval = subpatnum;
15063 else
15064 retval = pos.lnum;
15065 if (flags & SP_SETPCMARK)
15066 setpcmark();
15067 curwin->w_cursor = pos;
15068 if (match_pos != NULL)
15070 /* Store the match cursor position */
15071 match_pos->lnum = pos.lnum;
15072 match_pos->col = pos.col + 1;
15074 /* "/$" will put the cursor after the end of the line, may need to
15075 * correct that here */
15076 check_cursor();
15079 /* If 'n' flag is used: restore cursor position. */
15080 if (flags & SP_NOMOVE)
15081 curwin->w_cursor = save_cursor;
15082 else
15083 curwin->w_set_curswant = TRUE;
15084 theend:
15085 p_ws = save_p_ws;
15087 return retval;
15090 #ifdef FEAT_FLOAT
15092 * "round({float})" function
15094 static void
15095 f_round(argvars, rettv)
15096 typval_T *argvars;
15097 typval_T *rettv;
15099 float_T f;
15101 rettv->v_type = VAR_FLOAT;
15102 if (get_float_arg(argvars, &f) == OK)
15103 /* round() is not in C90, use ceil() or floor() instead. */
15104 rettv->vval.v_float = f > 0 ? floor(f + 0.5) : ceil(f - 0.5);
15105 else
15106 rettv->vval.v_float = 0.0;
15108 #endif
15111 * "search()" function
15113 static void
15114 f_search(argvars, rettv)
15115 typval_T *argvars;
15116 typval_T *rettv;
15118 int flags = 0;
15120 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
15124 * "searchdecl()" function
15126 static void
15127 f_searchdecl(argvars, rettv)
15128 typval_T *argvars;
15129 typval_T *rettv;
15131 int locally = 1;
15132 int thisblock = 0;
15133 int error = FALSE;
15134 char_u *name;
15136 rettv->vval.v_number = 1; /* default: FAIL */
15138 name = get_tv_string_chk(&argvars[0]);
15139 if (argvars[1].v_type != VAR_UNKNOWN)
15141 locally = get_tv_number_chk(&argvars[1], &error) == 0;
15142 if (!error && argvars[2].v_type != VAR_UNKNOWN)
15143 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
15145 if (!error && name != NULL)
15146 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
15147 locally, thisblock, SEARCH_KEEP) == FAIL;
15151 * Used by searchpair() and searchpairpos()
15153 static int
15154 searchpair_cmn(argvars, match_pos)
15155 typval_T *argvars;
15156 pos_T *match_pos;
15158 char_u *spat, *mpat, *epat;
15159 char_u *skip;
15160 int save_p_ws = p_ws;
15161 int dir;
15162 int flags = 0;
15163 char_u nbuf1[NUMBUFLEN];
15164 char_u nbuf2[NUMBUFLEN];
15165 char_u nbuf3[NUMBUFLEN];
15166 int retval = 0; /* default: FAIL */
15167 long lnum_stop = 0;
15168 long time_limit = 0;
15170 /* Get the three pattern arguments: start, middle, end. */
15171 spat = get_tv_string_chk(&argvars[0]);
15172 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
15173 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
15174 if (spat == NULL || mpat == NULL || epat == NULL)
15175 goto theend; /* type error */
15177 /* Handle the optional fourth argument: flags */
15178 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
15179 if (dir == 0)
15180 goto theend;
15182 /* Don't accept SP_END or SP_SUBPAT.
15183 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
15185 if ((flags & (SP_END | SP_SUBPAT)) != 0
15186 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
15188 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
15189 goto theend;
15192 /* Using 'r' implies 'W', otherwise it doesn't work. */
15193 if (flags & SP_REPEAT)
15194 p_ws = FALSE;
15196 /* Optional fifth argument: skip expression */
15197 if (argvars[3].v_type == VAR_UNKNOWN
15198 || argvars[4].v_type == VAR_UNKNOWN)
15199 skip = (char_u *)"";
15200 else
15202 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
15203 if (argvars[5].v_type != VAR_UNKNOWN)
15205 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
15206 if (lnum_stop < 0)
15207 goto theend;
15208 #ifdef FEAT_RELTIME
15209 if (argvars[6].v_type != VAR_UNKNOWN)
15211 time_limit = get_tv_number_chk(&argvars[6], NULL);
15212 if (time_limit < 0)
15213 goto theend;
15215 #endif
15218 if (skip == NULL)
15219 goto theend; /* type error */
15221 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
15222 match_pos, lnum_stop, time_limit);
15224 theend:
15225 p_ws = save_p_ws;
15227 return retval;
15231 * "searchpair()" function
15233 static void
15234 f_searchpair(argvars, rettv)
15235 typval_T *argvars;
15236 typval_T *rettv;
15238 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
15242 * "searchpairpos()" function
15244 static void
15245 f_searchpairpos(argvars, rettv)
15246 typval_T *argvars;
15247 typval_T *rettv;
15249 pos_T match_pos;
15250 int lnum = 0;
15251 int col = 0;
15253 rettv->vval.v_number = 0;
15255 if (rettv_list_alloc(rettv) == FAIL)
15256 return;
15258 if (searchpair_cmn(argvars, &match_pos) > 0)
15260 lnum = match_pos.lnum;
15261 col = match_pos.col;
15264 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15265 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15269 * Search for a start/middle/end thing.
15270 * Used by searchpair(), see its documentation for the details.
15271 * Returns 0 or -1 for no match,
15273 long
15274 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
15275 lnum_stop, time_limit)
15276 char_u *spat; /* start pattern */
15277 char_u *mpat; /* middle pattern */
15278 char_u *epat; /* end pattern */
15279 int dir; /* BACKWARD or FORWARD */
15280 char_u *skip; /* skip expression */
15281 int flags; /* SP_SETPCMARK and other SP_ values */
15282 pos_T *match_pos;
15283 linenr_T lnum_stop; /* stop at this line if not zero */
15284 long time_limit; /* stop after this many msec */
15286 char_u *save_cpo;
15287 char_u *pat, *pat2 = NULL, *pat3 = NULL;
15288 long retval = 0;
15289 pos_T pos;
15290 pos_T firstpos;
15291 pos_T foundpos;
15292 pos_T save_cursor;
15293 pos_T save_pos;
15294 int n;
15295 int r;
15296 int nest = 1;
15297 int err;
15298 int options = SEARCH_KEEP;
15299 proftime_T tm;
15301 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15302 save_cpo = p_cpo;
15303 p_cpo = empty_option;
15305 #ifdef FEAT_RELTIME
15306 /* Set the time limit, if there is one. */
15307 profile_setlimit(time_limit, &tm);
15308 #endif
15310 /* Make two search patterns: start/end (pat2, for in nested pairs) and
15311 * start/middle/end (pat3, for the top pair). */
15312 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
15313 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
15314 if (pat2 == NULL || pat3 == NULL)
15315 goto theend;
15316 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
15317 if (*mpat == NUL)
15318 STRCPY(pat3, pat2);
15319 else
15320 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
15321 spat, epat, mpat);
15322 if (flags & SP_START)
15323 options |= SEARCH_START;
15325 save_cursor = curwin->w_cursor;
15326 pos = curwin->w_cursor;
15327 clearpos(&firstpos);
15328 clearpos(&foundpos);
15329 pat = pat3;
15330 for (;;)
15332 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15333 options, RE_SEARCH, lnum_stop, &tm);
15334 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
15335 /* didn't find it or found the first match again: FAIL */
15336 break;
15338 if (firstpos.lnum == 0)
15339 firstpos = pos;
15340 if (equalpos(pos, foundpos))
15342 /* Found the same position again. Can happen with a pattern that
15343 * has "\zs" at the end and searching backwards. Advance one
15344 * character and try again. */
15345 if (dir == BACKWARD)
15346 decl(&pos);
15347 else
15348 incl(&pos);
15350 foundpos = pos;
15352 /* clear the start flag to avoid getting stuck here */
15353 options &= ~SEARCH_START;
15355 /* If the skip pattern matches, ignore this match. */
15356 if (*skip != NUL)
15358 save_pos = curwin->w_cursor;
15359 curwin->w_cursor = pos;
15360 r = eval_to_bool(skip, &err, NULL, FALSE);
15361 curwin->w_cursor = save_pos;
15362 if (err)
15364 /* Evaluating {skip} caused an error, break here. */
15365 curwin->w_cursor = save_cursor;
15366 retval = -1;
15367 break;
15369 if (r)
15370 continue;
15373 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
15375 /* Found end when searching backwards or start when searching
15376 * forward: nested pair. */
15377 ++nest;
15378 pat = pat2; /* nested, don't search for middle */
15380 else
15382 /* Found end when searching forward or start when searching
15383 * backward: end of (nested) pair; or found middle in outer pair. */
15384 if (--nest == 1)
15385 pat = pat3; /* outer level, search for middle */
15388 if (nest == 0)
15390 /* Found the match: return matchcount or line number. */
15391 if (flags & SP_RETCOUNT)
15392 ++retval;
15393 else
15394 retval = pos.lnum;
15395 if (flags & SP_SETPCMARK)
15396 setpcmark();
15397 curwin->w_cursor = pos;
15398 if (!(flags & SP_REPEAT))
15399 break;
15400 nest = 1; /* search for next unmatched */
15404 if (match_pos != NULL)
15406 /* Store the match cursor position */
15407 match_pos->lnum = curwin->w_cursor.lnum;
15408 match_pos->col = curwin->w_cursor.col + 1;
15411 /* If 'n' flag is used or search failed: restore cursor position. */
15412 if ((flags & SP_NOMOVE) || retval == 0)
15413 curwin->w_cursor = save_cursor;
15415 theend:
15416 vim_free(pat2);
15417 vim_free(pat3);
15418 if (p_cpo == empty_option)
15419 p_cpo = save_cpo;
15420 else
15421 /* Darn, evaluating the {skip} expression changed the value. */
15422 free_string_option(save_cpo);
15424 return retval;
15428 * "searchpos()" function
15430 static void
15431 f_searchpos(argvars, rettv)
15432 typval_T *argvars;
15433 typval_T *rettv;
15435 pos_T match_pos;
15436 int lnum = 0;
15437 int col = 0;
15438 int n;
15439 int flags = 0;
15441 rettv->vval.v_number = 0;
15443 if (rettv_list_alloc(rettv) == FAIL)
15444 return;
15446 n = search_cmn(argvars, &match_pos, &flags);
15447 if (n > 0)
15449 lnum = match_pos.lnum;
15450 col = match_pos.col;
15453 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15454 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15455 if (flags & SP_SUBPAT)
15456 list_append_number(rettv->vval.v_list, (varnumber_T)n);
15460 /*ARGSUSED*/
15461 static void
15462 f_server2client(argvars, rettv)
15463 typval_T *argvars;
15464 typval_T *rettv;
15466 #ifdef FEAT_CLIENTSERVER
15467 char_u buf[NUMBUFLEN];
15468 char_u *server = get_tv_string_chk(&argvars[0]);
15469 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
15471 rettv->vval.v_number = -1;
15472 if (server == NULL || reply == NULL)
15473 return;
15474 if (check_restricted() || check_secure())
15475 return;
15476 # ifdef FEAT_X11
15477 if (check_connection() == FAIL)
15478 return;
15479 # endif
15481 if (serverSendReply(server, reply) < 0)
15483 EMSG(_("E258: Unable to send to client"));
15484 return;
15486 rettv->vval.v_number = 0;
15487 #else
15488 rettv->vval.v_number = -1;
15489 #endif
15492 /*ARGSUSED*/
15493 static void
15494 f_serverlist(argvars, rettv)
15495 typval_T *argvars;
15496 typval_T *rettv;
15498 char_u *r = NULL;
15500 #ifdef FEAT_CLIENTSERVER
15501 # ifdef WIN32
15502 r = serverGetVimNames();
15503 # else
15504 make_connection();
15505 if (X_DISPLAY != NULL)
15506 r = serverGetVimNames(X_DISPLAY);
15507 # endif
15508 #endif
15509 rettv->v_type = VAR_STRING;
15510 rettv->vval.v_string = r;
15514 * "setbufvar()" function
15516 /*ARGSUSED*/
15517 static void
15518 f_setbufvar(argvars, rettv)
15519 typval_T *argvars;
15520 typval_T *rettv;
15522 buf_T *buf;
15523 aco_save_T aco;
15524 char_u *varname, *bufvarname;
15525 typval_T *varp;
15526 char_u nbuf[NUMBUFLEN];
15528 rettv->vval.v_number = 0;
15530 if (check_restricted() || check_secure())
15531 return;
15532 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
15533 varname = get_tv_string_chk(&argvars[1]);
15534 buf = get_buf_tv(&argvars[0]);
15535 varp = &argvars[2];
15537 if (buf != NULL && varname != NULL && varp != NULL)
15539 /* set curbuf to be our buf, temporarily */
15540 aucmd_prepbuf(&aco, buf);
15542 if (*varname == '&')
15544 long numval;
15545 char_u *strval;
15546 int error = FALSE;
15548 ++varname;
15549 numval = get_tv_number_chk(varp, &error);
15550 strval = get_tv_string_buf_chk(varp, nbuf);
15551 if (!error && strval != NULL)
15552 set_option_value(varname, numval, strval, OPT_LOCAL);
15554 else
15556 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
15557 if (bufvarname != NULL)
15559 STRCPY(bufvarname, "b:");
15560 STRCPY(bufvarname + 2, varname);
15561 set_var(bufvarname, varp, TRUE);
15562 vim_free(bufvarname);
15566 /* reset notion of buffer */
15567 aucmd_restbuf(&aco);
15572 * "setcmdpos()" function
15574 static void
15575 f_setcmdpos(argvars, rettv)
15576 typval_T *argvars;
15577 typval_T *rettv;
15579 int pos = (int)get_tv_number(&argvars[0]) - 1;
15581 if (pos >= 0)
15582 rettv->vval.v_number = set_cmdline_pos(pos);
15586 * "setline()" function
15588 static void
15589 f_setline(argvars, rettv)
15590 typval_T *argvars;
15591 typval_T *rettv;
15593 linenr_T lnum;
15594 char_u *line = NULL;
15595 list_T *l = NULL;
15596 listitem_T *li = NULL;
15597 long added = 0;
15598 linenr_T lcount = curbuf->b_ml.ml_line_count;
15600 lnum = get_tv_lnum(&argvars[0]);
15601 if (argvars[1].v_type == VAR_LIST)
15603 l = argvars[1].vval.v_list;
15604 li = l->lv_first;
15606 else
15607 line = get_tv_string_chk(&argvars[1]);
15609 rettv->vval.v_number = 0; /* OK */
15610 for (;;)
15612 if (l != NULL)
15614 /* list argument, get next string */
15615 if (li == NULL)
15616 break;
15617 line = get_tv_string_chk(&li->li_tv);
15618 li = li->li_next;
15621 rettv->vval.v_number = 1; /* FAIL */
15622 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
15623 break;
15624 if (lnum <= curbuf->b_ml.ml_line_count)
15626 /* existing line, replace it */
15627 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
15629 changed_bytes(lnum, 0);
15630 if (lnum == curwin->w_cursor.lnum)
15631 check_cursor_col();
15632 rettv->vval.v_number = 0; /* OK */
15635 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
15637 /* lnum is one past the last line, append the line */
15638 ++added;
15639 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
15640 rettv->vval.v_number = 0; /* OK */
15643 if (l == NULL) /* only one string argument */
15644 break;
15645 ++lnum;
15648 if (added > 0)
15649 appended_lines_mark(lcount, added);
15652 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
15655 * Used by "setqflist()" and "setloclist()" functions
15657 /*ARGSUSED*/
15658 static void
15659 set_qf_ll_list(wp, list_arg, action_arg, rettv)
15660 win_T *wp;
15661 typval_T *list_arg;
15662 typval_T *action_arg;
15663 typval_T *rettv;
15665 #ifdef FEAT_QUICKFIX
15666 char_u *act;
15667 int action = ' ';
15668 #endif
15670 rettv->vval.v_number = -1;
15672 #ifdef FEAT_QUICKFIX
15673 if (list_arg->v_type != VAR_LIST)
15674 EMSG(_(e_listreq));
15675 else
15677 list_T *l = list_arg->vval.v_list;
15679 if (action_arg->v_type == VAR_STRING)
15681 act = get_tv_string_chk(action_arg);
15682 if (act == NULL)
15683 return; /* type error; errmsg already given */
15684 if (*act == 'a' || *act == 'r')
15685 action = *act;
15688 if (l != NULL && set_errorlist(wp, l, action) == OK)
15689 rettv->vval.v_number = 0;
15691 #endif
15695 * "setloclist()" function
15697 /*ARGSUSED*/
15698 static void
15699 f_setloclist(argvars, rettv)
15700 typval_T *argvars;
15701 typval_T *rettv;
15703 win_T *win;
15705 rettv->vval.v_number = -1;
15707 win = find_win_by_nr(&argvars[0], NULL);
15708 if (win != NULL)
15709 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
15713 * "setmatches()" function
15715 static void
15716 f_setmatches(argvars, rettv)
15717 typval_T *argvars;
15718 typval_T *rettv;
15720 #ifdef FEAT_SEARCH_EXTRA
15721 list_T *l;
15722 listitem_T *li;
15723 dict_T *d;
15725 rettv->vval.v_number = -1;
15726 if (argvars[0].v_type != VAR_LIST)
15728 EMSG(_(e_listreq));
15729 return;
15731 if ((l = argvars[0].vval.v_list) != NULL)
15734 /* To some extent make sure that we are dealing with a list from
15735 * "getmatches()". */
15736 li = l->lv_first;
15737 while (li != NULL)
15739 if (li->li_tv.v_type != VAR_DICT
15740 || (d = li->li_tv.vval.v_dict) == NULL)
15742 EMSG(_(e_invarg));
15743 return;
15745 if (!(dict_find(d, (char_u *)"group", -1) != NULL
15746 && dict_find(d, (char_u *)"pattern", -1) != NULL
15747 && dict_find(d, (char_u *)"priority", -1) != NULL
15748 && dict_find(d, (char_u *)"id", -1) != NULL))
15750 EMSG(_(e_invarg));
15751 return;
15753 li = li->li_next;
15756 clear_matches(curwin);
15757 li = l->lv_first;
15758 while (li != NULL)
15760 d = li->li_tv.vval.v_dict;
15761 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
15762 get_dict_string(d, (char_u *)"pattern", FALSE),
15763 (int)get_dict_number(d, (char_u *)"priority"),
15764 (int)get_dict_number(d, (char_u *)"id"));
15765 li = li->li_next;
15767 rettv->vval.v_number = 0;
15769 #endif
15773 * "setpos()" function
15775 /*ARGSUSED*/
15776 static void
15777 f_setpos(argvars, rettv)
15778 typval_T *argvars;
15779 typval_T *rettv;
15781 pos_T pos;
15782 int fnum;
15783 char_u *name;
15785 rettv->vval.v_number = -1;
15786 name = get_tv_string_chk(argvars);
15787 if (name != NULL)
15789 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
15791 --pos.col;
15792 if (name[0] == '.' && name[1] == NUL)
15794 /* set cursor */
15795 if (fnum == curbuf->b_fnum)
15797 curwin->w_cursor = pos;
15798 check_cursor();
15799 rettv->vval.v_number = 0;
15801 else
15802 EMSG(_(e_invarg));
15804 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
15806 /* set mark */
15807 if (setmark_pos(name[1], &pos, fnum) == OK)
15808 rettv->vval.v_number = 0;
15810 else
15811 EMSG(_(e_invarg));
15817 * "setqflist()" function
15819 /*ARGSUSED*/
15820 static void
15821 f_setqflist(argvars, rettv)
15822 typval_T *argvars;
15823 typval_T *rettv;
15825 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
15829 * "setreg()" function
15831 static void
15832 f_setreg(argvars, rettv)
15833 typval_T *argvars;
15834 typval_T *rettv;
15836 int regname;
15837 char_u *strregname;
15838 char_u *stropt;
15839 char_u *strval;
15840 int append;
15841 char_u yank_type;
15842 long block_len;
15844 block_len = -1;
15845 yank_type = MAUTO;
15846 append = FALSE;
15848 strregname = get_tv_string_chk(argvars);
15849 rettv->vval.v_number = 1; /* FAIL is default */
15851 if (strregname == NULL)
15852 return; /* type error; errmsg already given */
15853 regname = *strregname;
15854 if (regname == 0 || regname == '@')
15855 regname = '"';
15856 else if (regname == '=')
15857 return;
15859 if (argvars[2].v_type != VAR_UNKNOWN)
15861 stropt = get_tv_string_chk(&argvars[2]);
15862 if (stropt == NULL)
15863 return; /* type error */
15864 for (; *stropt != NUL; ++stropt)
15865 switch (*stropt)
15867 case 'a': case 'A': /* append */
15868 append = TRUE;
15869 break;
15870 case 'v': case 'c': /* character-wise selection */
15871 yank_type = MCHAR;
15872 break;
15873 case 'V': case 'l': /* line-wise selection */
15874 yank_type = MLINE;
15875 break;
15876 #ifdef FEAT_VISUAL
15877 case 'b': case Ctrl_V: /* block-wise selection */
15878 yank_type = MBLOCK;
15879 if (VIM_ISDIGIT(stropt[1]))
15881 ++stropt;
15882 block_len = getdigits(&stropt) - 1;
15883 --stropt;
15885 break;
15886 #endif
15890 strval = get_tv_string_chk(&argvars[1]);
15891 if (strval != NULL)
15892 write_reg_contents_ex(regname, strval, -1,
15893 append, yank_type, block_len);
15894 rettv->vval.v_number = 0;
15898 * "settabwinvar()" function
15900 static void
15901 f_settabwinvar(argvars, rettv)
15902 typval_T *argvars;
15903 typval_T *rettv;
15905 setwinvar(argvars, rettv, 1);
15909 * "setwinvar()" function
15911 static void
15912 f_setwinvar(argvars, rettv)
15913 typval_T *argvars;
15914 typval_T *rettv;
15916 setwinvar(argvars, rettv, 0);
15920 * "setwinvar()" and "settabwinvar()" functions
15922 static void
15923 setwinvar(argvars, rettv, off)
15924 typval_T *argvars;
15925 typval_T *rettv;
15926 int off;
15928 win_T *win;
15929 #ifdef FEAT_WINDOWS
15930 win_T *save_curwin;
15931 tabpage_T *save_curtab;
15932 #endif
15933 char_u *varname, *winvarname;
15934 typval_T *varp;
15935 char_u nbuf[NUMBUFLEN];
15936 tabpage_T *tp;
15938 rettv->vval.v_number = 0;
15940 if (check_restricted() || check_secure())
15941 return;
15943 #ifdef FEAT_WINDOWS
15944 if (off == 1)
15945 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
15946 else
15947 tp = curtab;
15948 #endif
15949 win = find_win_by_nr(&argvars[off], tp);
15950 varname = get_tv_string_chk(&argvars[off + 1]);
15951 varp = &argvars[off + 2];
15953 if (win != NULL && varname != NULL && varp != NULL)
15955 #ifdef FEAT_WINDOWS
15956 /* set curwin to be our win, temporarily */
15957 save_curwin = curwin;
15958 save_curtab = curtab;
15959 goto_tabpage_tp(tp);
15960 if (!win_valid(win))
15961 return;
15962 curwin = win;
15963 curbuf = curwin->w_buffer;
15964 #endif
15966 if (*varname == '&')
15968 long numval;
15969 char_u *strval;
15970 int error = FALSE;
15972 ++varname;
15973 numval = get_tv_number_chk(varp, &error);
15974 strval = get_tv_string_buf_chk(varp, nbuf);
15975 if (!error && strval != NULL)
15976 set_option_value(varname, numval, strval, OPT_LOCAL);
15978 else
15980 winvarname = alloc((unsigned)STRLEN(varname) + 3);
15981 if (winvarname != NULL)
15983 STRCPY(winvarname, "w:");
15984 STRCPY(winvarname + 2, varname);
15985 set_var(winvarname, varp, TRUE);
15986 vim_free(winvarname);
15990 #ifdef FEAT_WINDOWS
15991 /* Restore current tabpage and window, if still valid (autocomands can
15992 * make them invalid). */
15993 if (valid_tabpage(save_curtab))
15994 goto_tabpage_tp(save_curtab);
15995 if (win_valid(save_curwin))
15997 curwin = save_curwin;
15998 curbuf = curwin->w_buffer;
16000 #endif
16005 * "shellescape({string})" function
16007 static void
16008 f_shellescape(argvars, rettv)
16009 typval_T *argvars;
16010 typval_T *rettv;
16012 rettv->vval.v_string = vim_strsave_shellescape(
16013 get_tv_string(&argvars[0]), non_zero_arg(&argvars[1]));
16014 rettv->v_type = VAR_STRING;
16018 * "simplify()" function
16020 static void
16021 f_simplify(argvars, rettv)
16022 typval_T *argvars;
16023 typval_T *rettv;
16025 char_u *p;
16027 p = get_tv_string(&argvars[0]);
16028 rettv->vval.v_string = vim_strsave(p);
16029 simplify_filename(rettv->vval.v_string); /* simplify in place */
16030 rettv->v_type = VAR_STRING;
16033 #ifdef FEAT_FLOAT
16035 * "sin()" function
16037 static void
16038 f_sin(argvars, rettv)
16039 typval_T *argvars;
16040 typval_T *rettv;
16042 float_T f;
16044 rettv->v_type = VAR_FLOAT;
16045 if (get_float_arg(argvars, &f) == OK)
16046 rettv->vval.v_float = sin(f);
16047 else
16048 rettv->vval.v_float = 0.0;
16050 #endif
16052 static int
16053 #ifdef __BORLANDC__
16054 _RTLENTRYF
16055 #endif
16056 item_compare __ARGS((const void *s1, const void *s2));
16057 static int
16058 #ifdef __BORLANDC__
16059 _RTLENTRYF
16060 #endif
16061 item_compare2 __ARGS((const void *s1, const void *s2));
16063 static int item_compare_ic;
16064 static char_u *item_compare_func;
16065 static int item_compare_func_err;
16066 #define ITEM_COMPARE_FAIL 999
16069 * Compare functions for f_sort() below.
16071 static int
16072 #ifdef __BORLANDC__
16073 _RTLENTRYF
16074 #endif
16075 item_compare(s1, s2)
16076 const void *s1;
16077 const void *s2;
16079 char_u *p1, *p2;
16080 char_u *tofree1, *tofree2;
16081 int res;
16082 char_u numbuf1[NUMBUFLEN];
16083 char_u numbuf2[NUMBUFLEN];
16085 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
16086 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
16087 if (p1 == NULL)
16088 p1 = (char_u *)"";
16089 if (p2 == NULL)
16090 p2 = (char_u *)"";
16091 if (item_compare_ic)
16092 res = STRICMP(p1, p2);
16093 else
16094 res = STRCMP(p1, p2);
16095 vim_free(tofree1);
16096 vim_free(tofree2);
16097 return res;
16100 static int
16101 #ifdef __BORLANDC__
16102 _RTLENTRYF
16103 #endif
16104 item_compare2(s1, s2)
16105 const void *s1;
16106 const void *s2;
16108 int res;
16109 typval_T rettv;
16110 typval_T argv[3];
16111 int dummy;
16113 /* shortcut after failure in previous call; compare all items equal */
16114 if (item_compare_func_err)
16115 return 0;
16117 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
16118 * in the copy without changing the original list items. */
16119 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
16120 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
16122 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
16123 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
16124 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
16125 clear_tv(&argv[0]);
16126 clear_tv(&argv[1]);
16128 if (res == FAIL)
16129 res = ITEM_COMPARE_FAIL;
16130 else
16131 res = get_tv_number_chk(&rettv, &item_compare_func_err);
16132 if (item_compare_func_err)
16133 res = ITEM_COMPARE_FAIL; /* return value has wrong type */
16134 clear_tv(&rettv);
16135 return res;
16139 * "sort({list})" function
16141 static void
16142 f_sort(argvars, rettv)
16143 typval_T *argvars;
16144 typval_T *rettv;
16146 list_T *l;
16147 listitem_T *li;
16148 listitem_T **ptrs;
16149 long len;
16150 long i;
16152 rettv->vval.v_number = 0;
16153 if (argvars[0].v_type != VAR_LIST)
16154 EMSG2(_(e_listarg), "sort()");
16155 else
16157 l = argvars[0].vval.v_list;
16158 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
16159 return;
16160 rettv->vval.v_list = l;
16161 rettv->v_type = VAR_LIST;
16162 ++l->lv_refcount;
16164 len = list_len(l);
16165 if (len <= 1)
16166 return; /* short list sorts pretty quickly */
16168 item_compare_ic = FALSE;
16169 item_compare_func = NULL;
16170 if (argvars[1].v_type != VAR_UNKNOWN)
16172 if (argvars[1].v_type == VAR_FUNC)
16173 item_compare_func = argvars[1].vval.v_string;
16174 else
16176 int error = FALSE;
16178 i = get_tv_number_chk(&argvars[1], &error);
16179 if (error)
16180 return; /* type error; errmsg already given */
16181 if (i == 1)
16182 item_compare_ic = TRUE;
16183 else
16184 item_compare_func = get_tv_string(&argvars[1]);
16188 /* Make an array with each entry pointing to an item in the List. */
16189 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
16190 if (ptrs == NULL)
16191 return;
16192 i = 0;
16193 for (li = l->lv_first; li != NULL; li = li->li_next)
16194 ptrs[i++] = li;
16196 item_compare_func_err = FALSE;
16197 /* test the compare function */
16198 if (item_compare_func != NULL
16199 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
16200 == ITEM_COMPARE_FAIL)
16201 EMSG(_("E702: Sort compare function failed"));
16202 else
16204 /* Sort the array with item pointers. */
16205 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
16206 item_compare_func == NULL ? item_compare : item_compare2);
16208 if (!item_compare_func_err)
16210 /* Clear the List and append the items in the sorted order. */
16211 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
16212 l->lv_len = 0;
16213 for (i = 0; i < len; ++i)
16214 list_append(l, ptrs[i]);
16218 vim_free(ptrs);
16223 * "soundfold({word})" function
16225 static void
16226 f_soundfold(argvars, rettv)
16227 typval_T *argvars;
16228 typval_T *rettv;
16230 char_u *s;
16232 rettv->v_type = VAR_STRING;
16233 s = get_tv_string(&argvars[0]);
16234 #ifdef FEAT_SPELL
16235 rettv->vval.v_string = eval_soundfold(s);
16236 #else
16237 rettv->vval.v_string = vim_strsave(s);
16238 #endif
16242 * "spellbadword()" function
16244 /* ARGSUSED */
16245 static void
16246 f_spellbadword(argvars, rettv)
16247 typval_T *argvars;
16248 typval_T *rettv;
16250 char_u *word = (char_u *)"";
16251 hlf_T attr = HLF_COUNT;
16252 int len = 0;
16254 if (rettv_list_alloc(rettv) == FAIL)
16255 return;
16257 #ifdef FEAT_SPELL
16258 if (argvars[0].v_type == VAR_UNKNOWN)
16260 /* Find the start and length of the badly spelled word. */
16261 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
16262 if (len != 0)
16263 word = ml_get_cursor();
16265 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16267 char_u *str = get_tv_string_chk(&argvars[0]);
16268 int capcol = -1;
16270 if (str != NULL)
16272 /* Check the argument for spelling. */
16273 while (*str != NUL)
16275 len = spell_check(curwin, str, &attr, &capcol, FALSE);
16276 if (attr != HLF_COUNT)
16278 word = str;
16279 break;
16281 str += len;
16285 #endif
16287 list_append_string(rettv->vval.v_list, word, len);
16288 list_append_string(rettv->vval.v_list, (char_u *)(
16289 attr == HLF_SPB ? "bad" :
16290 attr == HLF_SPR ? "rare" :
16291 attr == HLF_SPL ? "local" :
16292 attr == HLF_SPC ? "caps" :
16293 ""), -1);
16297 * "spellsuggest()" function
16299 /*ARGSUSED*/
16300 static void
16301 f_spellsuggest(argvars, rettv)
16302 typval_T *argvars;
16303 typval_T *rettv;
16305 #ifdef FEAT_SPELL
16306 char_u *str;
16307 int typeerr = FALSE;
16308 int maxcount;
16309 garray_T ga;
16310 int i;
16311 listitem_T *li;
16312 int need_capital = FALSE;
16313 #endif
16315 if (rettv_list_alloc(rettv) == FAIL)
16316 return;
16318 #ifdef FEAT_SPELL
16319 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16321 str = get_tv_string(&argvars[0]);
16322 if (argvars[1].v_type != VAR_UNKNOWN)
16324 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
16325 if (maxcount <= 0)
16326 return;
16327 if (argvars[2].v_type != VAR_UNKNOWN)
16329 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
16330 if (typeerr)
16331 return;
16334 else
16335 maxcount = 25;
16337 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
16339 for (i = 0; i < ga.ga_len; ++i)
16341 str = ((char_u **)ga.ga_data)[i];
16343 li = listitem_alloc();
16344 if (li == NULL)
16345 vim_free(str);
16346 else
16348 li->li_tv.v_type = VAR_STRING;
16349 li->li_tv.v_lock = 0;
16350 li->li_tv.vval.v_string = str;
16351 list_append(rettv->vval.v_list, li);
16354 ga_clear(&ga);
16356 #endif
16359 static void
16360 f_split(argvars, rettv)
16361 typval_T *argvars;
16362 typval_T *rettv;
16364 char_u *str;
16365 char_u *end;
16366 char_u *pat = NULL;
16367 regmatch_T regmatch;
16368 char_u patbuf[NUMBUFLEN];
16369 char_u *save_cpo;
16370 int match;
16371 colnr_T col = 0;
16372 int keepempty = FALSE;
16373 int typeerr = FALSE;
16375 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
16376 save_cpo = p_cpo;
16377 p_cpo = (char_u *)"";
16379 str = get_tv_string(&argvars[0]);
16380 if (argvars[1].v_type != VAR_UNKNOWN)
16382 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16383 if (pat == NULL)
16384 typeerr = TRUE;
16385 if (argvars[2].v_type != VAR_UNKNOWN)
16386 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
16388 if (pat == NULL || *pat == NUL)
16389 pat = (char_u *)"[\\x01- ]\\+";
16391 if (rettv_list_alloc(rettv) == FAIL)
16392 return;
16393 if (typeerr)
16394 return;
16396 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
16397 if (regmatch.regprog != NULL)
16399 regmatch.rm_ic = FALSE;
16400 while (*str != NUL || keepempty)
16402 if (*str == NUL)
16403 match = FALSE; /* empty item at the end */
16404 else
16405 match = vim_regexec_nl(&regmatch, str, col);
16406 if (match)
16407 end = regmatch.startp[0];
16408 else
16409 end = str + STRLEN(str);
16410 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
16411 && *str != NUL && match && end < regmatch.endp[0]))
16413 if (list_append_string(rettv->vval.v_list, str,
16414 (int)(end - str)) == FAIL)
16415 break;
16417 if (!match)
16418 break;
16419 /* Advance to just after the match. */
16420 if (regmatch.endp[0] > str)
16421 col = 0;
16422 else
16424 /* Don't get stuck at the same match. */
16425 #ifdef FEAT_MBYTE
16426 col = (*mb_ptr2len)(regmatch.endp[0]);
16427 #else
16428 col = 1;
16429 #endif
16431 str = regmatch.endp[0];
16434 vim_free(regmatch.regprog);
16437 p_cpo = save_cpo;
16440 #ifdef FEAT_FLOAT
16442 * "sqrt()" function
16444 static void
16445 f_sqrt(argvars, rettv)
16446 typval_T *argvars;
16447 typval_T *rettv;
16449 float_T f;
16451 rettv->v_type = VAR_FLOAT;
16452 if (get_float_arg(argvars, &f) == OK)
16453 rettv->vval.v_float = sqrt(f);
16454 else
16455 rettv->vval.v_float = 0.0;
16459 * "str2float()" function
16461 static void
16462 f_str2float(argvars, rettv)
16463 typval_T *argvars;
16464 typval_T *rettv;
16466 char_u *p = skipwhite(get_tv_string(&argvars[0]));
16468 if (*p == '+')
16469 p = skipwhite(p + 1);
16470 (void)string2float(p, &rettv->vval.v_float);
16471 rettv->v_type = VAR_FLOAT;
16473 #endif
16476 * "str2nr()" function
16478 static void
16479 f_str2nr(argvars, rettv)
16480 typval_T *argvars;
16481 typval_T *rettv;
16483 int base = 10;
16484 char_u *p;
16485 long n;
16487 if (argvars[1].v_type != VAR_UNKNOWN)
16489 base = get_tv_number(&argvars[1]);
16490 if (base != 8 && base != 10 && base != 16)
16492 EMSG(_(e_invarg));
16493 return;
16497 p = skipwhite(get_tv_string(&argvars[0]));
16498 if (*p == '+')
16499 p = skipwhite(p + 1);
16500 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
16501 rettv->vval.v_number = n;
16504 #ifdef HAVE_STRFTIME
16506 * "strftime({format}[, {time}])" function
16508 static void
16509 f_strftime(argvars, rettv)
16510 typval_T *argvars;
16511 typval_T *rettv;
16513 char_u result_buf[256];
16514 struct tm *curtime;
16515 time_t seconds;
16516 char_u *p;
16518 rettv->v_type = VAR_STRING;
16520 p = get_tv_string(&argvars[0]);
16521 if (argvars[1].v_type == VAR_UNKNOWN)
16522 seconds = time(NULL);
16523 else
16524 seconds = (time_t)get_tv_number(&argvars[1]);
16525 curtime = localtime(&seconds);
16526 /* MSVC returns NULL for an invalid value of seconds. */
16527 if (curtime == NULL)
16528 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
16529 else
16531 # ifdef FEAT_MBYTE
16532 vimconv_T conv;
16533 char_u *enc;
16535 conv.vc_type = CONV_NONE;
16536 enc = enc_locale();
16537 convert_setup(&conv, p_enc, enc);
16538 if (conv.vc_type != CONV_NONE)
16539 p = string_convert(&conv, p, NULL);
16540 # endif
16541 if (p != NULL)
16542 (void)strftime((char *)result_buf, sizeof(result_buf),
16543 (char *)p, curtime);
16544 else
16545 result_buf[0] = NUL;
16547 # ifdef FEAT_MBYTE
16548 if (conv.vc_type != CONV_NONE)
16549 vim_free(p);
16550 convert_setup(&conv, enc, p_enc);
16551 if (conv.vc_type != CONV_NONE)
16552 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
16553 else
16554 # endif
16555 rettv->vval.v_string = vim_strsave(result_buf);
16557 # ifdef FEAT_MBYTE
16558 /* Release conversion descriptors */
16559 convert_setup(&conv, NULL, NULL);
16560 vim_free(enc);
16561 # endif
16564 #endif
16567 * "stridx()" function
16569 static void
16570 f_stridx(argvars, rettv)
16571 typval_T *argvars;
16572 typval_T *rettv;
16574 char_u buf[NUMBUFLEN];
16575 char_u *needle;
16576 char_u *haystack;
16577 char_u *save_haystack;
16578 char_u *pos;
16579 int start_idx;
16581 needle = get_tv_string_chk(&argvars[1]);
16582 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
16583 rettv->vval.v_number = -1;
16584 if (needle == NULL || haystack == NULL)
16585 return; /* type error; errmsg already given */
16587 if (argvars[2].v_type != VAR_UNKNOWN)
16589 int error = FALSE;
16591 start_idx = get_tv_number_chk(&argvars[2], &error);
16592 if (error || start_idx >= (int)STRLEN(haystack))
16593 return;
16594 if (start_idx >= 0)
16595 haystack += start_idx;
16598 pos = (char_u *)strstr((char *)haystack, (char *)needle);
16599 if (pos != NULL)
16600 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
16604 * "string()" function
16606 static void
16607 f_string(argvars, rettv)
16608 typval_T *argvars;
16609 typval_T *rettv;
16611 char_u *tofree;
16612 char_u numbuf[NUMBUFLEN];
16614 rettv->v_type = VAR_STRING;
16615 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
16616 /* Make a copy if we have a value but it's not in allocated memory. */
16617 if (rettv->vval.v_string != NULL && tofree == NULL)
16618 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
16622 * "strlen()" function
16624 static void
16625 f_strlen(argvars, rettv)
16626 typval_T *argvars;
16627 typval_T *rettv;
16629 rettv->vval.v_number = (varnumber_T)(STRLEN(
16630 get_tv_string(&argvars[0])));
16634 * "strpart()" function
16636 static void
16637 f_strpart(argvars, rettv)
16638 typval_T *argvars;
16639 typval_T *rettv;
16641 char_u *p;
16642 int n;
16643 int len;
16644 int slen;
16645 int error = FALSE;
16647 p = get_tv_string(&argvars[0]);
16648 slen = (int)STRLEN(p);
16650 n = get_tv_number_chk(&argvars[1], &error);
16651 if (error)
16652 len = 0;
16653 else if (argvars[2].v_type != VAR_UNKNOWN)
16654 len = get_tv_number(&argvars[2]);
16655 else
16656 len = slen - n; /* default len: all bytes that are available. */
16659 * Only return the overlap between the specified part and the actual
16660 * string.
16662 if (n < 0)
16664 len += n;
16665 n = 0;
16667 else if (n > slen)
16668 n = slen;
16669 if (len < 0)
16670 len = 0;
16671 else if (n + len > slen)
16672 len = slen - n;
16674 rettv->v_type = VAR_STRING;
16675 rettv->vval.v_string = vim_strnsave(p + n, len);
16679 * "strridx()" function
16681 static void
16682 f_strridx(argvars, rettv)
16683 typval_T *argvars;
16684 typval_T *rettv;
16686 char_u buf[NUMBUFLEN];
16687 char_u *needle;
16688 char_u *haystack;
16689 char_u *rest;
16690 char_u *lastmatch = NULL;
16691 int haystack_len, end_idx;
16693 needle = get_tv_string_chk(&argvars[1]);
16694 haystack = get_tv_string_buf_chk(&argvars[0], buf);
16696 rettv->vval.v_number = -1;
16697 if (needle == NULL || haystack == NULL)
16698 return; /* type error; errmsg already given */
16700 haystack_len = (int)STRLEN(haystack);
16701 if (argvars[2].v_type != VAR_UNKNOWN)
16703 /* Third argument: upper limit for index */
16704 end_idx = get_tv_number_chk(&argvars[2], NULL);
16705 if (end_idx < 0)
16706 return; /* can never find a match */
16708 else
16709 end_idx = haystack_len;
16711 if (*needle == NUL)
16713 /* Empty string matches past the end. */
16714 lastmatch = haystack + end_idx;
16716 else
16718 for (rest = haystack; *rest != '\0'; ++rest)
16720 rest = (char_u *)strstr((char *)rest, (char *)needle);
16721 if (rest == NULL || rest > haystack + end_idx)
16722 break;
16723 lastmatch = rest;
16727 if (lastmatch == NULL)
16728 rettv->vval.v_number = -1;
16729 else
16730 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
16734 * "strtrans()" function
16736 static void
16737 f_strtrans(argvars, rettv)
16738 typval_T *argvars;
16739 typval_T *rettv;
16741 rettv->v_type = VAR_STRING;
16742 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
16746 * "submatch()" function
16748 static void
16749 f_submatch(argvars, rettv)
16750 typval_T *argvars;
16751 typval_T *rettv;
16753 rettv->v_type = VAR_STRING;
16754 rettv->vval.v_string =
16755 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
16759 * "substitute()" function
16761 static void
16762 f_substitute(argvars, rettv)
16763 typval_T *argvars;
16764 typval_T *rettv;
16766 char_u patbuf[NUMBUFLEN];
16767 char_u subbuf[NUMBUFLEN];
16768 char_u flagsbuf[NUMBUFLEN];
16770 char_u *str = get_tv_string_chk(&argvars[0]);
16771 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16772 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
16773 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
16775 rettv->v_type = VAR_STRING;
16776 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
16777 rettv->vval.v_string = NULL;
16778 else
16779 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
16783 * "synID(lnum, col, trans)" function
16785 /*ARGSUSED*/
16786 static void
16787 f_synID(argvars, rettv)
16788 typval_T *argvars;
16789 typval_T *rettv;
16791 int id = 0;
16792 #ifdef FEAT_SYN_HL
16793 long lnum;
16794 long col;
16795 int trans;
16796 int transerr = FALSE;
16798 lnum = get_tv_lnum(argvars); /* -1 on type error */
16799 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16800 trans = get_tv_number_chk(&argvars[2], &transerr);
16802 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16803 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
16804 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
16805 #endif
16807 rettv->vval.v_number = id;
16811 * "synIDattr(id, what [, mode])" function
16813 /*ARGSUSED*/
16814 static void
16815 f_synIDattr(argvars, rettv)
16816 typval_T *argvars;
16817 typval_T *rettv;
16819 char_u *p = NULL;
16820 #ifdef FEAT_SYN_HL
16821 int id;
16822 char_u *what;
16823 char_u *mode;
16824 char_u modebuf[NUMBUFLEN];
16825 int modec;
16827 id = get_tv_number(&argvars[0]);
16828 what = get_tv_string(&argvars[1]);
16829 if (argvars[2].v_type != VAR_UNKNOWN)
16831 mode = get_tv_string_buf(&argvars[2], modebuf);
16832 modec = TOLOWER_ASC(mode[0]);
16833 if (modec != 't' && modec != 'c'
16834 #ifdef FEAT_GUI
16835 && modec != 'g'
16836 #endif
16838 modec = 0; /* replace invalid with current */
16840 else
16842 #ifdef FEAT_GUI
16843 if (gui.in_use)
16844 modec = 'g';
16845 else
16846 #endif
16847 if (t_colors > 1)
16848 modec = 'c';
16849 else
16850 modec = 't';
16854 switch (TOLOWER_ASC(what[0]))
16856 case 'b':
16857 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
16858 p = highlight_color(id, what, modec);
16859 else /* bold */
16860 p = highlight_has_attr(id, HL_BOLD, modec);
16861 break;
16863 case 'f': /* fg[#] */
16864 p = highlight_color(id, what, modec);
16865 break;
16867 case 'i':
16868 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
16869 p = highlight_has_attr(id, HL_INVERSE, modec);
16870 else /* italic */
16871 p = highlight_has_attr(id, HL_ITALIC, modec);
16872 break;
16874 case 'n': /* name */
16875 p = get_highlight_name(NULL, id - 1);
16876 break;
16878 case 'r': /* reverse */
16879 p = highlight_has_attr(id, HL_INVERSE, modec);
16880 break;
16882 case 's':
16883 if (TOLOWER_ASC(what[1]) == 'p') /* sp[#] */
16884 p = highlight_color(id, what, modec);
16885 else /* standout */
16886 p = highlight_has_attr(id, HL_STANDOUT, modec);
16887 break;
16889 case 'u':
16890 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
16891 /* underline */
16892 p = highlight_has_attr(id, HL_UNDERLINE, modec);
16893 else
16894 /* undercurl */
16895 p = highlight_has_attr(id, HL_UNDERCURL, modec);
16896 break;
16899 if (p != NULL)
16900 p = vim_strsave(p);
16901 #endif
16902 rettv->v_type = VAR_STRING;
16903 rettv->vval.v_string = p;
16907 * "synIDtrans(id)" function
16909 /*ARGSUSED*/
16910 static void
16911 f_synIDtrans(argvars, rettv)
16912 typval_T *argvars;
16913 typval_T *rettv;
16915 int id;
16917 #ifdef FEAT_SYN_HL
16918 id = get_tv_number(&argvars[0]);
16920 if (id > 0)
16921 id = syn_get_final_id(id);
16922 else
16923 #endif
16924 id = 0;
16926 rettv->vval.v_number = id;
16930 * "synstack(lnum, col)" function
16932 /*ARGSUSED*/
16933 static void
16934 f_synstack(argvars, rettv)
16935 typval_T *argvars;
16936 typval_T *rettv;
16938 #ifdef FEAT_SYN_HL
16939 long lnum;
16940 long col;
16941 int i;
16942 int id;
16943 #endif
16945 rettv->v_type = VAR_LIST;
16946 rettv->vval.v_list = NULL;
16948 #ifdef FEAT_SYN_HL
16949 lnum = get_tv_lnum(argvars); /* -1 on type error */
16950 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16952 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16953 && col >= 0 && (col == 0 || col < (long)STRLEN(ml_get(lnum)))
16954 && rettv_list_alloc(rettv) != FAIL)
16956 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
16957 for (i = 0; ; ++i)
16959 id = syn_get_stack_item(i);
16960 if (id < 0)
16961 break;
16962 if (list_append_number(rettv->vval.v_list, id) == FAIL)
16963 break;
16966 #endif
16970 * "system()" function
16972 static void
16973 f_system(argvars, rettv)
16974 typval_T *argvars;
16975 typval_T *rettv;
16977 char_u *res = NULL;
16978 char_u *p;
16979 char_u *infile = NULL;
16980 char_u buf[NUMBUFLEN];
16981 int err = FALSE;
16982 FILE *fd;
16984 if (check_restricted() || check_secure())
16985 goto done;
16987 if (argvars[1].v_type != VAR_UNKNOWN)
16990 * Write the string to a temp file, to be used for input of the shell
16991 * command.
16993 if ((infile = vim_tempname('i')) == NULL)
16995 EMSG(_(e_notmp));
16996 goto done;
16999 fd = mch_fopen((char *)infile, WRITEBIN);
17000 if (fd == NULL)
17002 EMSG2(_(e_notopen), infile);
17003 goto done;
17005 p = get_tv_string_buf_chk(&argvars[1], buf);
17006 if (p == NULL)
17008 fclose(fd);
17009 goto done; /* type error; errmsg already given */
17011 if (fwrite(p, STRLEN(p), 1, fd) != 1)
17012 err = TRUE;
17013 if (fclose(fd) != 0)
17014 err = TRUE;
17015 if (err)
17017 EMSG(_("E677: Error writing temp file"));
17018 goto done;
17022 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
17023 SHELL_SILENT | SHELL_COOKED);
17025 #ifdef USE_CR
17026 /* translate <CR> into <NL> */
17027 if (res != NULL)
17029 char_u *s;
17031 for (s = res; *s; ++s)
17033 if (*s == CAR)
17034 *s = NL;
17037 #else
17038 # ifdef USE_CRNL
17039 /* translate <CR><NL> into <NL> */
17040 if (res != NULL)
17042 char_u *s, *d;
17044 d = res;
17045 for (s = res; *s; ++s)
17047 if (s[0] == CAR && s[1] == NL)
17048 ++s;
17049 *d++ = *s;
17051 *d = NUL;
17053 # endif
17054 #endif
17056 done:
17057 if (infile != NULL)
17059 mch_remove(infile);
17060 vim_free(infile);
17062 rettv->v_type = VAR_STRING;
17063 rettv->vval.v_string = res;
17067 * "tabpagebuflist()" function
17069 /* ARGSUSED */
17070 static void
17071 f_tabpagebuflist(argvars, rettv)
17072 typval_T *argvars;
17073 typval_T *rettv;
17075 #ifndef FEAT_WINDOWS
17076 rettv->vval.v_number = 0;
17077 #else
17078 tabpage_T *tp;
17079 win_T *wp = NULL;
17081 if (argvars[0].v_type == VAR_UNKNOWN)
17082 wp = firstwin;
17083 else
17085 tp = find_tabpage((int)get_tv_number(&argvars[0]));
17086 if (tp != NULL)
17087 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
17089 if (wp == NULL)
17090 rettv->vval.v_number = 0;
17091 else
17093 if (rettv_list_alloc(rettv) == FAIL)
17094 rettv->vval.v_number = 0;
17095 else
17097 for (; wp != NULL; wp = wp->w_next)
17098 if (list_append_number(rettv->vval.v_list,
17099 wp->w_buffer->b_fnum) == FAIL)
17100 break;
17103 #endif
17108 * "tabpagenr()" function
17110 /* ARGSUSED */
17111 static void
17112 f_tabpagenr(argvars, rettv)
17113 typval_T *argvars;
17114 typval_T *rettv;
17116 int nr = 1;
17117 #ifdef FEAT_WINDOWS
17118 char_u *arg;
17120 if (argvars[0].v_type != VAR_UNKNOWN)
17122 arg = get_tv_string_chk(&argvars[0]);
17123 nr = 0;
17124 if (arg != NULL)
17126 if (STRCMP(arg, "$") == 0)
17127 nr = tabpage_index(NULL) - 1;
17128 else
17129 EMSG2(_(e_invexpr2), arg);
17132 else
17133 nr = tabpage_index(curtab);
17134 #endif
17135 rettv->vval.v_number = nr;
17139 #ifdef FEAT_WINDOWS
17140 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
17143 * Common code for tabpagewinnr() and winnr().
17145 static int
17146 get_winnr(tp, argvar)
17147 tabpage_T *tp;
17148 typval_T *argvar;
17150 win_T *twin;
17151 int nr = 1;
17152 win_T *wp;
17153 char_u *arg;
17155 twin = (tp == curtab) ? curwin : tp->tp_curwin;
17156 if (argvar->v_type != VAR_UNKNOWN)
17158 arg = get_tv_string_chk(argvar);
17159 if (arg == NULL)
17160 nr = 0; /* type error; errmsg already given */
17161 else if (STRCMP(arg, "$") == 0)
17162 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
17163 else if (STRCMP(arg, "#") == 0)
17165 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
17166 if (twin == NULL)
17167 nr = 0;
17169 else
17171 EMSG2(_(e_invexpr2), arg);
17172 nr = 0;
17176 if (nr > 0)
17177 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
17178 wp != twin; wp = wp->w_next)
17180 if (wp == NULL)
17182 /* didn't find it in this tabpage */
17183 nr = 0;
17184 break;
17186 ++nr;
17188 return nr;
17190 #endif
17193 * "tabpagewinnr()" function
17195 /* ARGSUSED */
17196 static void
17197 f_tabpagewinnr(argvars, rettv)
17198 typval_T *argvars;
17199 typval_T *rettv;
17201 int nr = 1;
17202 #ifdef FEAT_WINDOWS
17203 tabpage_T *tp;
17205 tp = find_tabpage((int)get_tv_number(&argvars[0]));
17206 if (tp == NULL)
17207 nr = 0;
17208 else
17209 nr = get_winnr(tp, &argvars[1]);
17210 #endif
17211 rettv->vval.v_number = nr;
17216 * "tagfiles()" function
17218 /*ARGSUSED*/
17219 static void
17220 f_tagfiles(argvars, rettv)
17221 typval_T *argvars;
17222 typval_T *rettv;
17224 char_u fname[MAXPATHL + 1];
17225 tagname_T tn;
17226 int first;
17228 if (rettv_list_alloc(rettv) == FAIL)
17230 rettv->vval.v_number = 0;
17231 return;
17234 for (first = TRUE; ; first = FALSE)
17235 if (get_tagfname(&tn, first, fname) == FAIL
17236 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
17237 break;
17238 tagname_free(&tn);
17242 * "taglist()" function
17244 static void
17245 f_taglist(argvars, rettv)
17246 typval_T *argvars;
17247 typval_T *rettv;
17249 char_u *tag_pattern;
17251 tag_pattern = get_tv_string(&argvars[0]);
17253 rettv->vval.v_number = FALSE;
17254 if (*tag_pattern == NUL)
17255 return;
17257 if (rettv_list_alloc(rettv) == OK)
17258 (void)get_tags(rettv->vval.v_list, tag_pattern);
17262 * "tempname()" function
17264 /*ARGSUSED*/
17265 static void
17266 f_tempname(argvars, rettv)
17267 typval_T *argvars;
17268 typval_T *rettv;
17270 static int x = 'A';
17272 rettv->v_type = VAR_STRING;
17273 rettv->vval.v_string = vim_tempname(x);
17275 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
17276 * names. Skip 'I' and 'O', they are used for shell redirection. */
17279 if (x == 'Z')
17280 x = '0';
17281 else if (x == '9')
17282 x = 'A';
17283 else
17285 #ifdef EBCDIC
17286 if (x == 'I')
17287 x = 'J';
17288 else if (x == 'R')
17289 x = 'S';
17290 else
17291 #endif
17292 ++x;
17294 } while (x == 'I' || x == 'O');
17298 * "test(list)" function: Just checking the walls...
17300 /*ARGSUSED*/
17301 static void
17302 f_test(argvars, rettv)
17303 typval_T *argvars;
17304 typval_T *rettv;
17306 /* Used for unit testing. Change the code below to your liking. */
17307 #if 0
17308 listitem_T *li;
17309 list_T *l;
17310 char_u *bad, *good;
17312 if (argvars[0].v_type != VAR_LIST)
17313 return;
17314 l = argvars[0].vval.v_list;
17315 if (l == NULL)
17316 return;
17317 li = l->lv_first;
17318 if (li == NULL)
17319 return;
17320 bad = get_tv_string(&li->li_tv);
17321 li = li->li_next;
17322 if (li == NULL)
17323 return;
17324 good = get_tv_string(&li->li_tv);
17325 rettv->vval.v_number = test_edit_score(bad, good);
17326 #endif
17330 * "tolower(string)" function
17332 static void
17333 f_tolower(argvars, rettv)
17334 typval_T *argvars;
17335 typval_T *rettv;
17337 char_u *p;
17339 p = vim_strsave(get_tv_string(&argvars[0]));
17340 rettv->v_type = VAR_STRING;
17341 rettv->vval.v_string = p;
17343 if (p != NULL)
17344 while (*p != NUL)
17346 #ifdef FEAT_MBYTE
17347 int l;
17349 if (enc_utf8)
17351 int c, lc;
17353 c = utf_ptr2char(p);
17354 lc = utf_tolower(c);
17355 l = utf_ptr2len(p);
17356 /* TODO: reallocate string when byte count changes. */
17357 if (utf_char2len(lc) == l)
17358 utf_char2bytes(lc, p);
17359 p += l;
17361 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
17362 p += l; /* skip multi-byte character */
17363 else
17364 #endif
17366 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
17367 ++p;
17373 * "toupper(string)" function
17375 static void
17376 f_toupper(argvars, rettv)
17377 typval_T *argvars;
17378 typval_T *rettv;
17380 rettv->v_type = VAR_STRING;
17381 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
17385 * "tr(string, fromstr, tostr)" function
17387 static void
17388 f_tr(argvars, rettv)
17389 typval_T *argvars;
17390 typval_T *rettv;
17392 char_u *instr;
17393 char_u *fromstr;
17394 char_u *tostr;
17395 char_u *p;
17396 #ifdef FEAT_MBYTE
17397 int inlen;
17398 int fromlen;
17399 int tolen;
17400 int idx;
17401 char_u *cpstr;
17402 int cplen;
17403 int first = TRUE;
17404 #endif
17405 char_u buf[NUMBUFLEN];
17406 char_u buf2[NUMBUFLEN];
17407 garray_T ga;
17409 instr = get_tv_string(&argvars[0]);
17410 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
17411 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
17413 /* Default return value: empty string. */
17414 rettv->v_type = VAR_STRING;
17415 rettv->vval.v_string = NULL;
17416 if (fromstr == NULL || tostr == NULL)
17417 return; /* type error; errmsg already given */
17418 ga_init2(&ga, (int)sizeof(char), 80);
17420 #ifdef FEAT_MBYTE
17421 if (!has_mbyte)
17422 #endif
17423 /* not multi-byte: fromstr and tostr must be the same length */
17424 if (STRLEN(fromstr) != STRLEN(tostr))
17426 #ifdef FEAT_MBYTE
17427 error:
17428 #endif
17429 EMSG2(_(e_invarg2), fromstr);
17430 ga_clear(&ga);
17431 return;
17434 /* fromstr and tostr have to contain the same number of chars */
17435 while (*instr != NUL)
17437 #ifdef FEAT_MBYTE
17438 if (has_mbyte)
17440 inlen = (*mb_ptr2len)(instr);
17441 cpstr = instr;
17442 cplen = inlen;
17443 idx = 0;
17444 for (p = fromstr; *p != NUL; p += fromlen)
17446 fromlen = (*mb_ptr2len)(p);
17447 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
17449 for (p = tostr; *p != NUL; p += tolen)
17451 tolen = (*mb_ptr2len)(p);
17452 if (idx-- == 0)
17454 cplen = tolen;
17455 cpstr = p;
17456 break;
17459 if (*p == NUL) /* tostr is shorter than fromstr */
17460 goto error;
17461 break;
17463 ++idx;
17466 if (first && cpstr == instr)
17468 /* Check that fromstr and tostr have the same number of
17469 * (multi-byte) characters. Done only once when a character
17470 * of instr doesn't appear in fromstr. */
17471 first = FALSE;
17472 for (p = tostr; *p != NUL; p += tolen)
17474 tolen = (*mb_ptr2len)(p);
17475 --idx;
17477 if (idx != 0)
17478 goto error;
17481 ga_grow(&ga, cplen);
17482 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
17483 ga.ga_len += cplen;
17485 instr += inlen;
17487 else
17488 #endif
17490 /* When not using multi-byte chars we can do it faster. */
17491 p = vim_strchr(fromstr, *instr);
17492 if (p != NULL)
17493 ga_append(&ga, tostr[p - fromstr]);
17494 else
17495 ga_append(&ga, *instr);
17496 ++instr;
17500 /* add a terminating NUL */
17501 ga_grow(&ga, 1);
17502 ga_append(&ga, NUL);
17504 rettv->vval.v_string = ga.ga_data;
17507 #ifdef FEAT_FLOAT
17509 * "trunc({float})" function
17511 static void
17512 f_trunc(argvars, rettv)
17513 typval_T *argvars;
17514 typval_T *rettv;
17516 float_T f;
17518 rettv->v_type = VAR_FLOAT;
17519 if (get_float_arg(argvars, &f) == OK)
17520 /* trunc() is not in C90, use floor() or ceil() instead. */
17521 rettv->vval.v_float = f > 0 ? floor(f) : ceil(f);
17522 else
17523 rettv->vval.v_float = 0.0;
17525 #endif
17528 * "type(expr)" function
17530 static void
17531 f_type(argvars, rettv)
17532 typval_T *argvars;
17533 typval_T *rettv;
17535 int n;
17537 switch (argvars[0].v_type)
17539 case VAR_NUMBER: n = 0; break;
17540 case VAR_STRING: n = 1; break;
17541 case VAR_FUNC: n = 2; break;
17542 case VAR_LIST: n = 3; break;
17543 case VAR_DICT: n = 4; break;
17544 #ifdef FEAT_FLOAT
17545 case VAR_FLOAT: n = 5; break;
17546 #endif
17547 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
17549 rettv->vval.v_number = n;
17553 * "values(dict)" function
17555 static void
17556 f_values(argvars, rettv)
17557 typval_T *argvars;
17558 typval_T *rettv;
17560 dict_list(argvars, rettv, 1);
17564 * "virtcol(string)" function
17566 static void
17567 f_virtcol(argvars, rettv)
17568 typval_T *argvars;
17569 typval_T *rettv;
17571 colnr_T vcol = 0;
17572 pos_T *fp;
17573 int fnum = curbuf->b_fnum;
17575 fp = var2fpos(&argvars[0], FALSE, &fnum);
17576 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
17577 && fnum == curbuf->b_fnum)
17579 getvvcol(curwin, fp, NULL, NULL, &vcol);
17580 ++vcol;
17583 rettv->vval.v_number = vcol;
17587 * "visualmode()" function
17589 /*ARGSUSED*/
17590 static void
17591 f_visualmode(argvars, rettv)
17592 typval_T *argvars;
17593 typval_T *rettv;
17595 #ifdef FEAT_VISUAL
17596 char_u str[2];
17598 rettv->v_type = VAR_STRING;
17599 str[0] = curbuf->b_visual_mode_eval;
17600 str[1] = NUL;
17601 rettv->vval.v_string = vim_strsave(str);
17603 /* A non-zero number or non-empty string argument: reset mode. */
17604 if (non_zero_arg(&argvars[0]))
17605 curbuf->b_visual_mode_eval = NUL;
17606 #else
17607 rettv->vval.v_number = 0; /* return anything, it won't work anyway */
17608 #endif
17612 * "winbufnr(nr)" function
17614 static void
17615 f_winbufnr(argvars, rettv)
17616 typval_T *argvars;
17617 typval_T *rettv;
17619 win_T *wp;
17621 wp = find_win_by_nr(&argvars[0], NULL);
17622 if (wp == NULL)
17623 rettv->vval.v_number = -1;
17624 else
17625 rettv->vval.v_number = wp->w_buffer->b_fnum;
17629 * "wincol()" function
17631 /*ARGSUSED*/
17632 static void
17633 f_wincol(argvars, rettv)
17634 typval_T *argvars;
17635 typval_T *rettv;
17637 validate_cursor();
17638 rettv->vval.v_number = curwin->w_wcol + 1;
17642 * "winheight(nr)" function
17644 static void
17645 f_winheight(argvars, rettv)
17646 typval_T *argvars;
17647 typval_T *rettv;
17649 win_T *wp;
17651 wp = find_win_by_nr(&argvars[0], NULL);
17652 if (wp == NULL)
17653 rettv->vval.v_number = -1;
17654 else
17655 rettv->vval.v_number = wp->w_height;
17659 * "winline()" function
17661 /*ARGSUSED*/
17662 static void
17663 f_winline(argvars, rettv)
17664 typval_T *argvars;
17665 typval_T *rettv;
17667 validate_cursor();
17668 rettv->vval.v_number = curwin->w_wrow + 1;
17672 * "winnr()" function
17674 /* ARGSUSED */
17675 static void
17676 f_winnr(argvars, rettv)
17677 typval_T *argvars;
17678 typval_T *rettv;
17680 int nr = 1;
17682 #ifdef FEAT_WINDOWS
17683 nr = get_winnr(curtab, &argvars[0]);
17684 #endif
17685 rettv->vval.v_number = nr;
17689 * "winrestcmd()" function
17691 /* ARGSUSED */
17692 static void
17693 f_winrestcmd(argvars, rettv)
17694 typval_T *argvars;
17695 typval_T *rettv;
17697 #ifdef FEAT_WINDOWS
17698 win_T *wp;
17699 int winnr = 1;
17700 garray_T ga;
17701 char_u buf[50];
17703 ga_init2(&ga, (int)sizeof(char), 70);
17704 for (wp = firstwin; wp != NULL; wp = wp->w_next)
17706 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
17707 ga_concat(&ga, buf);
17708 # ifdef FEAT_VERTSPLIT
17709 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
17710 ga_concat(&ga, buf);
17711 # endif
17712 ++winnr;
17714 ga_append(&ga, NUL);
17716 rettv->vval.v_string = ga.ga_data;
17717 #else
17718 rettv->vval.v_string = NULL;
17719 #endif
17720 rettv->v_type = VAR_STRING;
17724 * "winrestview()" function
17726 /* ARGSUSED */
17727 static void
17728 f_winrestview(argvars, rettv)
17729 typval_T *argvars;
17730 typval_T *rettv;
17732 dict_T *dict;
17734 if (argvars[0].v_type != VAR_DICT
17735 || (dict = argvars[0].vval.v_dict) == NULL)
17736 EMSG(_(e_invarg));
17737 else
17739 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
17740 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
17741 #ifdef FEAT_VIRTUALEDIT
17742 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
17743 #endif
17744 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
17745 curwin->w_set_curswant = FALSE;
17747 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
17748 #ifdef FEAT_DIFF
17749 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
17750 #endif
17751 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
17752 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
17754 check_cursor();
17755 changed_cline_bef_curs();
17756 invalidate_botline();
17757 redraw_later(VALID);
17759 if (curwin->w_topline == 0)
17760 curwin->w_topline = 1;
17761 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
17762 curwin->w_topline = curbuf->b_ml.ml_line_count;
17763 #ifdef FEAT_DIFF
17764 check_topfill(curwin, TRUE);
17765 #endif
17770 * "winsaveview()" function
17772 /* ARGSUSED */
17773 static void
17774 f_winsaveview(argvars, rettv)
17775 typval_T *argvars;
17776 typval_T *rettv;
17778 dict_T *dict;
17780 dict = dict_alloc();
17781 if (dict == NULL)
17782 return;
17783 rettv->v_type = VAR_DICT;
17784 rettv->vval.v_dict = dict;
17785 ++dict->dv_refcount;
17787 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
17788 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
17789 #ifdef FEAT_VIRTUALEDIT
17790 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
17791 #endif
17792 update_curswant();
17793 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
17795 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
17796 #ifdef FEAT_DIFF
17797 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
17798 #endif
17799 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
17800 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
17804 * "winwidth(nr)" function
17806 static void
17807 f_winwidth(argvars, rettv)
17808 typval_T *argvars;
17809 typval_T *rettv;
17811 win_T *wp;
17813 wp = find_win_by_nr(&argvars[0], NULL);
17814 if (wp == NULL)
17815 rettv->vval.v_number = -1;
17816 else
17817 #ifdef FEAT_VERTSPLIT
17818 rettv->vval.v_number = wp->w_width;
17819 #else
17820 rettv->vval.v_number = Columns;
17821 #endif
17825 * "writefile()" function
17827 static void
17828 f_writefile(argvars, rettv)
17829 typval_T *argvars;
17830 typval_T *rettv;
17832 int binary = FALSE;
17833 char_u *fname;
17834 FILE *fd;
17835 listitem_T *li;
17836 char_u *s;
17837 int ret = 0;
17838 int c;
17840 if (check_restricted() || check_secure())
17841 return;
17843 if (argvars[0].v_type != VAR_LIST)
17845 EMSG2(_(e_listarg), "writefile()");
17846 return;
17848 if (argvars[0].vval.v_list == NULL)
17849 return;
17851 if (argvars[2].v_type != VAR_UNKNOWN
17852 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
17853 binary = TRUE;
17855 /* Always open the file in binary mode, library functions have a mind of
17856 * their own about CR-LF conversion. */
17857 fname = get_tv_string(&argvars[1]);
17858 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
17860 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
17861 ret = -1;
17863 else
17865 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
17866 li = li->li_next)
17868 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
17870 if (*s == '\n')
17871 c = putc(NUL, fd);
17872 else
17873 c = putc(*s, fd);
17874 if (c == EOF)
17876 ret = -1;
17877 break;
17880 if (!binary || li->li_next != NULL)
17881 if (putc('\n', fd) == EOF)
17883 ret = -1;
17884 break;
17886 if (ret < 0)
17888 EMSG(_(e_write));
17889 break;
17892 fclose(fd);
17895 rettv->vval.v_number = ret;
17899 * Translate a String variable into a position.
17900 * Returns NULL when there is an error.
17902 static pos_T *
17903 var2fpos(varp, dollar_lnum, fnum)
17904 typval_T *varp;
17905 int dollar_lnum; /* TRUE when $ is last line */
17906 int *fnum; /* set to fnum for '0, 'A, etc. */
17908 char_u *name;
17909 static pos_T pos;
17910 pos_T *pp;
17912 /* Argument can be [lnum, col, coladd]. */
17913 if (varp->v_type == VAR_LIST)
17915 list_T *l;
17916 int len;
17917 int error = FALSE;
17918 listitem_T *li;
17920 l = varp->vval.v_list;
17921 if (l == NULL)
17922 return NULL;
17924 /* Get the line number */
17925 pos.lnum = list_find_nr(l, 0L, &error);
17926 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
17927 return NULL; /* invalid line number */
17929 /* Get the column number */
17930 pos.col = list_find_nr(l, 1L, &error);
17931 if (error)
17932 return NULL;
17933 len = (long)STRLEN(ml_get(pos.lnum));
17935 /* We accept "$" for the column number: last column. */
17936 li = list_find(l, 1L);
17937 if (li != NULL && li->li_tv.v_type == VAR_STRING
17938 && li->li_tv.vval.v_string != NULL
17939 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
17940 pos.col = len + 1;
17942 /* Accept a position up to the NUL after the line. */
17943 if (pos.col == 0 || (int)pos.col > len + 1)
17944 return NULL; /* invalid column number */
17945 --pos.col;
17947 #ifdef FEAT_VIRTUALEDIT
17948 /* Get the virtual offset. Defaults to zero. */
17949 pos.coladd = list_find_nr(l, 2L, &error);
17950 if (error)
17951 pos.coladd = 0;
17952 #endif
17954 return &pos;
17957 name = get_tv_string_chk(varp);
17958 if (name == NULL)
17959 return NULL;
17960 if (name[0] == '.') /* cursor */
17961 return &curwin->w_cursor;
17962 #ifdef FEAT_VISUAL
17963 if (name[0] == 'v' && name[1] == NUL) /* Visual start */
17965 if (VIsual_active)
17966 return &VIsual;
17967 return &curwin->w_cursor;
17969 #endif
17970 if (name[0] == '\'') /* mark */
17972 pp = getmark_fnum(name[1], FALSE, fnum);
17973 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
17974 return NULL;
17975 return pp;
17978 #ifdef FEAT_VIRTUALEDIT
17979 pos.coladd = 0;
17980 #endif
17982 if (name[0] == 'w' && dollar_lnum)
17984 pos.col = 0;
17985 if (name[1] == '0') /* "w0": first visible line */
17987 update_topline();
17988 pos.lnum = curwin->w_topline;
17989 return &pos;
17991 else if (name[1] == '$') /* "w$": last visible line */
17993 validate_botline();
17994 pos.lnum = curwin->w_botline - 1;
17995 return &pos;
17998 else if (name[0] == '$') /* last column or line */
18000 if (dollar_lnum)
18002 pos.lnum = curbuf->b_ml.ml_line_count;
18003 pos.col = 0;
18005 else
18007 pos.lnum = curwin->w_cursor.lnum;
18008 pos.col = (colnr_T)STRLEN(ml_get_curline());
18010 return &pos;
18012 return NULL;
18016 * Convert list in "arg" into a position and optional file number.
18017 * When "fnump" is NULL there is no file number, only 3 items.
18018 * Note that the column is passed on as-is, the caller may want to decrement
18019 * it to use 1 for the first column.
18020 * Return FAIL when conversion is not possible, doesn't check the position for
18021 * validity.
18023 static int
18024 list2fpos(arg, posp, fnump)
18025 typval_T *arg;
18026 pos_T *posp;
18027 int *fnump;
18029 list_T *l = arg->vval.v_list;
18030 long i = 0;
18031 long n;
18033 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
18034 * when "fnump" isn't NULL and "coladd" is optional. */
18035 if (arg->v_type != VAR_LIST
18036 || l == NULL
18037 || l->lv_len < (fnump == NULL ? 2 : 3)
18038 || l->lv_len > (fnump == NULL ? 3 : 4))
18039 return FAIL;
18041 if (fnump != NULL)
18043 n = list_find_nr(l, i++, NULL); /* fnum */
18044 if (n < 0)
18045 return FAIL;
18046 if (n == 0)
18047 n = curbuf->b_fnum; /* current buffer */
18048 *fnump = n;
18051 n = list_find_nr(l, i++, NULL); /* lnum */
18052 if (n < 0)
18053 return FAIL;
18054 posp->lnum = n;
18056 n = list_find_nr(l, i++, NULL); /* col */
18057 if (n < 0)
18058 return FAIL;
18059 posp->col = n;
18061 #ifdef FEAT_VIRTUALEDIT
18062 n = list_find_nr(l, i, NULL);
18063 if (n < 0)
18064 posp->coladd = 0;
18065 else
18066 posp->coladd = n;
18067 #endif
18069 return OK;
18073 * Get the length of an environment variable name.
18074 * Advance "arg" to the first character after the name.
18075 * Return 0 for error.
18077 static int
18078 get_env_len(arg)
18079 char_u **arg;
18081 char_u *p;
18082 int len;
18084 for (p = *arg; vim_isIDc(*p); ++p)
18086 if (p == *arg) /* no name found */
18087 return 0;
18089 len = (int)(p - *arg);
18090 *arg = p;
18091 return len;
18095 * Get the length of the name of a function or internal variable.
18096 * "arg" is advanced to the first non-white character after the name.
18097 * Return 0 if something is wrong.
18099 static int
18100 get_id_len(arg)
18101 char_u **arg;
18103 char_u *p;
18104 int len;
18106 /* Find the end of the name. */
18107 for (p = *arg; eval_isnamec(*p); ++p)
18109 if (p == *arg) /* no name found */
18110 return 0;
18112 len = (int)(p - *arg);
18113 *arg = skipwhite(p);
18115 return len;
18119 * Get the length of the name of a variable or function.
18120 * Only the name is recognized, does not handle ".key" or "[idx]".
18121 * "arg" is advanced to the first non-white character after the name.
18122 * Return -1 if curly braces expansion failed.
18123 * Return 0 if something else is wrong.
18124 * If the name contains 'magic' {}'s, expand them and return the
18125 * expanded name in an allocated string via 'alias' - caller must free.
18127 static int
18128 get_name_len(arg, alias, evaluate, verbose)
18129 char_u **arg;
18130 char_u **alias;
18131 int evaluate;
18132 int verbose;
18134 int len;
18135 char_u *p;
18136 char_u *expr_start;
18137 char_u *expr_end;
18139 *alias = NULL; /* default to no alias */
18141 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
18142 && (*arg)[2] == (int)KE_SNR)
18144 /* hard coded <SNR>, already translated */
18145 *arg += 3;
18146 return get_id_len(arg) + 3;
18148 len = eval_fname_script(*arg);
18149 if (len > 0)
18151 /* literal "<SID>", "s:" or "<SNR>" */
18152 *arg += len;
18156 * Find the end of the name; check for {} construction.
18158 p = find_name_end(*arg, &expr_start, &expr_end,
18159 len > 0 ? 0 : FNE_CHECK_START);
18160 if (expr_start != NULL)
18162 char_u *temp_string;
18164 if (!evaluate)
18166 len += (int)(p - *arg);
18167 *arg = skipwhite(p);
18168 return len;
18172 * Include any <SID> etc in the expanded string:
18173 * Thus the -len here.
18175 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
18176 if (temp_string == NULL)
18177 return -1;
18178 *alias = temp_string;
18179 *arg = skipwhite(p);
18180 return (int)STRLEN(temp_string);
18183 len += get_id_len(arg);
18184 if (len == 0 && verbose)
18185 EMSG2(_(e_invexpr2), *arg);
18187 return len;
18191 * Find the end of a variable or function name, taking care of magic braces.
18192 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
18193 * start and end of the first magic braces item.
18194 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
18195 * Return a pointer to just after the name. Equal to "arg" if there is no
18196 * valid name.
18198 static char_u *
18199 find_name_end(arg, expr_start, expr_end, flags)
18200 char_u *arg;
18201 char_u **expr_start;
18202 char_u **expr_end;
18203 int flags;
18205 int mb_nest = 0;
18206 int br_nest = 0;
18207 char_u *p;
18209 if (expr_start != NULL)
18211 *expr_start = NULL;
18212 *expr_end = NULL;
18215 /* Quick check for valid starting character. */
18216 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
18217 return arg;
18219 for (p = arg; *p != NUL
18220 && (eval_isnamec(*p)
18221 || *p == '{'
18222 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
18223 || mb_nest != 0
18224 || br_nest != 0); mb_ptr_adv(p))
18226 if (*p == '\'')
18228 /* skip over 'string' to avoid counting [ and ] inside it. */
18229 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
18231 if (*p == NUL)
18232 break;
18234 else if (*p == '"')
18236 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
18237 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
18238 if (*p == '\\' && p[1] != NUL)
18239 ++p;
18240 if (*p == NUL)
18241 break;
18244 if (mb_nest == 0)
18246 if (*p == '[')
18247 ++br_nest;
18248 else if (*p == ']')
18249 --br_nest;
18252 if (br_nest == 0)
18254 if (*p == '{')
18256 mb_nest++;
18257 if (expr_start != NULL && *expr_start == NULL)
18258 *expr_start = p;
18260 else if (*p == '}')
18262 mb_nest--;
18263 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
18264 *expr_end = p;
18269 return p;
18273 * Expands out the 'magic' {}'s in a variable/function name.
18274 * Note that this can call itself recursively, to deal with
18275 * constructs like foo{bar}{baz}{bam}
18276 * The four pointer arguments point to "foo{expre}ss{ion}bar"
18277 * "in_start" ^
18278 * "expr_start" ^
18279 * "expr_end" ^
18280 * "in_end" ^
18282 * Returns a new allocated string, which the caller must free.
18283 * Returns NULL for failure.
18285 static char_u *
18286 make_expanded_name(in_start, expr_start, expr_end, in_end)
18287 char_u *in_start;
18288 char_u *expr_start;
18289 char_u *expr_end;
18290 char_u *in_end;
18292 char_u c1;
18293 char_u *retval = NULL;
18294 char_u *temp_result;
18295 char_u *nextcmd = NULL;
18297 if (expr_end == NULL || in_end == NULL)
18298 return NULL;
18299 *expr_start = NUL;
18300 *expr_end = NUL;
18301 c1 = *in_end;
18302 *in_end = NUL;
18304 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
18305 if (temp_result != NULL && nextcmd == NULL)
18307 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
18308 + (in_end - expr_end) + 1));
18309 if (retval != NULL)
18311 STRCPY(retval, in_start);
18312 STRCAT(retval, temp_result);
18313 STRCAT(retval, expr_end + 1);
18316 vim_free(temp_result);
18318 *in_end = c1; /* put char back for error messages */
18319 *expr_start = '{';
18320 *expr_end = '}';
18322 if (retval != NULL)
18324 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
18325 if (expr_start != NULL)
18327 /* Further expansion! */
18328 temp_result = make_expanded_name(retval, expr_start,
18329 expr_end, temp_result);
18330 vim_free(retval);
18331 retval = temp_result;
18335 return retval;
18339 * Return TRUE if character "c" can be used in a variable or function name.
18340 * Does not include '{' or '}' for magic braces.
18342 static int
18343 eval_isnamec(c)
18344 int c;
18346 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
18350 * Return TRUE if character "c" can be used as the first character in a
18351 * variable or function name (excluding '{' and '}').
18353 static int
18354 eval_isnamec1(c)
18355 int c;
18357 return (ASCII_ISALPHA(c) || c == '_');
18361 * Set number v: variable to "val".
18363 void
18364 set_vim_var_nr(idx, val)
18365 int idx;
18366 long val;
18368 vimvars[idx].vv_nr = val;
18372 * Get number v: variable value.
18374 long
18375 get_vim_var_nr(idx)
18376 int idx;
18378 return vimvars[idx].vv_nr;
18382 * Get string v: variable value. Uses a static buffer, can only be used once.
18384 char_u *
18385 get_vim_var_str(idx)
18386 int idx;
18388 return get_tv_string(&vimvars[idx].vv_tv);
18392 * Get List v: variable value. Caller must take care of reference count when
18393 * needed.
18395 list_T *
18396 get_vim_var_list(idx)
18397 int idx;
18399 return vimvars[idx].vv_list;
18403 * Set v:count to "count" and v:count1 to "count1".
18404 * When "set_prevcount" is TRUE first set v:prevcount from v:count.
18406 void
18407 set_vcount(count, count1, set_prevcount)
18408 long count;
18409 long count1;
18410 int set_prevcount;
18412 if (set_prevcount)
18413 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
18414 vimvars[VV_COUNT].vv_nr = count;
18415 vimvars[VV_COUNT1].vv_nr = count1;
18419 * Set string v: variable to a copy of "val".
18421 void
18422 set_vim_var_string(idx, val, len)
18423 int idx;
18424 char_u *val;
18425 int len; /* length of "val" to use or -1 (whole string) */
18427 /* Need to do this (at least) once, since we can't initialize a union.
18428 * Will always be invoked when "v:progname" is set. */
18429 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
18431 vim_free(vimvars[idx].vv_str);
18432 if (val == NULL)
18433 vimvars[idx].vv_str = NULL;
18434 else if (len == -1)
18435 vimvars[idx].vv_str = vim_strsave(val);
18436 else
18437 vimvars[idx].vv_str = vim_strnsave(val, len);
18441 * Set List v: variable to "val".
18443 void
18444 set_vim_var_list(idx, val)
18445 int idx;
18446 list_T *val;
18448 list_unref(vimvars[idx].vv_list);
18449 vimvars[idx].vv_list = val;
18450 if (val != NULL)
18451 ++val->lv_refcount;
18455 * Set v:register if needed.
18457 void
18458 set_reg_var(c)
18459 int c;
18461 char_u regname;
18463 if (c == 0 || c == ' ')
18464 regname = '"';
18465 else
18466 regname = c;
18467 /* Avoid free/alloc when the value is already right. */
18468 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
18469 set_vim_var_string(VV_REG, &regname, 1);
18473 * Get or set v:exception. If "oldval" == NULL, return the current value.
18474 * Otherwise, restore the value to "oldval" and return NULL.
18475 * Must always be called in pairs to save and restore v:exception! Does not
18476 * take care of memory allocations.
18478 char_u *
18479 v_exception(oldval)
18480 char_u *oldval;
18482 if (oldval == NULL)
18483 return vimvars[VV_EXCEPTION].vv_str;
18485 vimvars[VV_EXCEPTION].vv_str = oldval;
18486 return NULL;
18490 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
18491 * Otherwise, restore the value to "oldval" and return NULL.
18492 * Must always be called in pairs to save and restore v:throwpoint! Does not
18493 * take care of memory allocations.
18495 char_u *
18496 v_throwpoint(oldval)
18497 char_u *oldval;
18499 if (oldval == NULL)
18500 return vimvars[VV_THROWPOINT].vv_str;
18502 vimvars[VV_THROWPOINT].vv_str = oldval;
18503 return NULL;
18506 #if defined(FEAT_AUTOCMD) || defined(PROTO)
18508 * Set v:cmdarg.
18509 * If "eap" != NULL, use "eap" to generate the value and return the old value.
18510 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
18511 * Must always be called in pairs!
18513 char_u *
18514 set_cmdarg(eap, oldarg)
18515 exarg_T *eap;
18516 char_u *oldarg;
18518 char_u *oldval;
18519 char_u *newval;
18520 unsigned len;
18522 oldval = vimvars[VV_CMDARG].vv_str;
18523 if (eap == NULL)
18525 vim_free(oldval);
18526 vimvars[VV_CMDARG].vv_str = oldarg;
18527 return NULL;
18530 if (eap->force_bin == FORCE_BIN)
18531 len = 6;
18532 else if (eap->force_bin == FORCE_NOBIN)
18533 len = 8;
18534 else
18535 len = 0;
18537 if (eap->read_edit)
18538 len += 7;
18540 if (eap->force_ff != 0)
18541 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
18542 # ifdef FEAT_MBYTE
18543 if (eap->force_enc != 0)
18544 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
18545 if (eap->bad_char != 0)
18546 len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
18547 # endif
18549 newval = alloc(len + 1);
18550 if (newval == NULL)
18551 return NULL;
18553 if (eap->force_bin == FORCE_BIN)
18554 sprintf((char *)newval, " ++bin");
18555 else if (eap->force_bin == FORCE_NOBIN)
18556 sprintf((char *)newval, " ++nobin");
18557 else
18558 *newval = NUL;
18560 if (eap->read_edit)
18561 STRCAT(newval, " ++edit");
18563 if (eap->force_ff != 0)
18564 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
18565 eap->cmd + eap->force_ff);
18566 # ifdef FEAT_MBYTE
18567 if (eap->force_enc != 0)
18568 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
18569 eap->cmd + eap->force_enc);
18570 if (eap->bad_char != 0)
18571 sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
18572 eap->cmd + eap->bad_char);
18573 # endif
18574 vimvars[VV_CMDARG].vv_str = newval;
18575 return oldval;
18577 #endif
18580 * Get the value of internal variable "name".
18581 * Return OK or FAIL.
18583 static int
18584 get_var_tv(name, len, rettv, verbose)
18585 char_u *name;
18586 int len; /* length of "name" */
18587 typval_T *rettv; /* NULL when only checking existence */
18588 int verbose; /* may give error message */
18590 int ret = OK;
18591 typval_T *tv = NULL;
18592 typval_T atv;
18593 dictitem_T *v;
18594 int cc;
18596 /* truncate the name, so that we can use strcmp() */
18597 cc = name[len];
18598 name[len] = NUL;
18601 * Check for "b:changedtick".
18603 if (STRCMP(name, "b:changedtick") == 0)
18605 atv.v_type = VAR_NUMBER;
18606 atv.vval.v_number = curbuf->b_changedtick;
18607 tv = &atv;
18611 * Check for user-defined variables.
18613 else
18615 v = find_var(name, NULL);
18616 if (v != NULL)
18617 tv = &v->di_tv;
18620 if (tv == NULL)
18622 if (rettv != NULL && verbose)
18623 EMSG2(_(e_undefvar), name);
18624 ret = FAIL;
18626 else if (rettv != NULL)
18627 copy_tv(tv, rettv);
18629 name[len] = cc;
18631 return ret;
18635 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
18636 * Also handle function call with Funcref variable: func(expr)
18637 * Can all be combined: dict.func(expr)[idx]['func'](expr)
18639 static int
18640 handle_subscript(arg, rettv, evaluate, verbose)
18641 char_u **arg;
18642 typval_T *rettv;
18643 int evaluate; /* do more than finding the end */
18644 int verbose; /* give error messages */
18646 int ret = OK;
18647 dict_T *selfdict = NULL;
18648 char_u *s;
18649 int len;
18650 typval_T functv;
18652 while (ret == OK
18653 && (**arg == '['
18654 || (**arg == '.' && rettv->v_type == VAR_DICT)
18655 || (**arg == '(' && rettv->v_type == VAR_FUNC))
18656 && !vim_iswhite(*(*arg - 1)))
18658 if (**arg == '(')
18660 /* need to copy the funcref so that we can clear rettv */
18661 functv = *rettv;
18662 rettv->v_type = VAR_UNKNOWN;
18664 /* Invoke the function. Recursive! */
18665 s = functv.vval.v_string;
18666 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
18667 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
18668 &len, evaluate, selfdict);
18670 /* Clear the funcref afterwards, so that deleting it while
18671 * evaluating the arguments is possible (see test55). */
18672 clear_tv(&functv);
18674 /* Stop the expression evaluation when immediately aborting on
18675 * error, or when an interrupt occurred or an exception was thrown
18676 * but not caught. */
18677 if (aborting())
18679 if (ret == OK)
18680 clear_tv(rettv);
18681 ret = FAIL;
18683 dict_unref(selfdict);
18684 selfdict = NULL;
18686 else /* **arg == '[' || **arg == '.' */
18688 dict_unref(selfdict);
18689 if (rettv->v_type == VAR_DICT)
18691 selfdict = rettv->vval.v_dict;
18692 if (selfdict != NULL)
18693 ++selfdict->dv_refcount;
18695 else
18696 selfdict = NULL;
18697 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
18699 clear_tv(rettv);
18700 ret = FAIL;
18704 dict_unref(selfdict);
18705 return ret;
18709 * Allocate memory for a variable type-value, and make it empty (0 or NULL
18710 * value).
18712 static typval_T *
18713 alloc_tv()
18715 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
18719 * Allocate memory for a variable type-value, and assign a string to it.
18720 * The string "s" must have been allocated, it is consumed.
18721 * Return NULL for out of memory, the variable otherwise.
18723 static typval_T *
18724 alloc_string_tv(s)
18725 char_u *s;
18727 typval_T *rettv;
18729 rettv = alloc_tv();
18730 if (rettv != NULL)
18732 rettv->v_type = VAR_STRING;
18733 rettv->vval.v_string = s;
18735 else
18736 vim_free(s);
18737 return rettv;
18741 * Free the memory for a variable type-value.
18743 void
18744 free_tv(varp)
18745 typval_T *varp;
18747 if (varp != NULL)
18749 switch (varp->v_type)
18751 case VAR_FUNC:
18752 func_unref(varp->vval.v_string);
18753 /*FALLTHROUGH*/
18754 case VAR_STRING:
18755 vim_free(varp->vval.v_string);
18756 break;
18757 case VAR_LIST:
18758 list_unref(varp->vval.v_list);
18759 break;
18760 case VAR_DICT:
18761 dict_unref(varp->vval.v_dict);
18762 break;
18763 case VAR_NUMBER:
18764 #ifdef FEAT_FLOAT
18765 case VAR_FLOAT:
18766 #endif
18767 case VAR_UNKNOWN:
18768 break;
18769 default:
18770 EMSG2(_(e_intern2), "free_tv()");
18771 break;
18773 vim_free(varp);
18778 * Free the memory for a variable value and set the value to NULL or 0.
18780 void
18781 clear_tv(varp)
18782 typval_T *varp;
18784 if (varp != NULL)
18786 switch (varp->v_type)
18788 case VAR_FUNC:
18789 func_unref(varp->vval.v_string);
18790 /*FALLTHROUGH*/
18791 case VAR_STRING:
18792 vim_free(varp->vval.v_string);
18793 varp->vval.v_string = NULL;
18794 break;
18795 case VAR_LIST:
18796 list_unref(varp->vval.v_list);
18797 varp->vval.v_list = NULL;
18798 break;
18799 case VAR_DICT:
18800 dict_unref(varp->vval.v_dict);
18801 varp->vval.v_dict = NULL;
18802 break;
18803 case VAR_NUMBER:
18804 varp->vval.v_number = 0;
18805 break;
18806 #ifdef FEAT_FLOAT
18807 case VAR_FLOAT:
18808 varp->vval.v_float = 0.0;
18809 break;
18810 #endif
18811 case VAR_UNKNOWN:
18812 break;
18813 default:
18814 EMSG2(_(e_intern2), "clear_tv()");
18816 varp->v_lock = 0;
18821 * Set the value of a variable to NULL without freeing items.
18823 static void
18824 init_tv(varp)
18825 typval_T *varp;
18827 if (varp != NULL)
18828 vim_memset(varp, 0, sizeof(typval_T));
18832 * Get the number value of a variable.
18833 * If it is a String variable, uses vim_str2nr().
18834 * For incompatible types, return 0.
18835 * get_tv_number_chk() is similar to get_tv_number(), but informs the
18836 * caller of incompatible types: it sets *denote to TRUE if "denote"
18837 * is not NULL or returns -1 otherwise.
18839 static long
18840 get_tv_number(varp)
18841 typval_T *varp;
18843 int error = FALSE;
18845 return get_tv_number_chk(varp, &error); /* return 0L on error */
18848 long
18849 get_tv_number_chk(varp, denote)
18850 typval_T *varp;
18851 int *denote;
18853 long n = 0L;
18855 switch (varp->v_type)
18857 case VAR_NUMBER:
18858 return (long)(varp->vval.v_number);
18859 #ifdef FEAT_FLOAT
18860 case VAR_FLOAT:
18861 EMSG(_("E805: Using a Float as a Number"));
18862 break;
18863 #endif
18864 case VAR_FUNC:
18865 EMSG(_("E703: Using a Funcref as a Number"));
18866 break;
18867 case VAR_STRING:
18868 if (varp->vval.v_string != NULL)
18869 vim_str2nr(varp->vval.v_string, NULL, NULL,
18870 TRUE, TRUE, &n, NULL);
18871 return n;
18872 case VAR_LIST:
18873 EMSG(_("E745: Using a List as a Number"));
18874 break;
18875 case VAR_DICT:
18876 EMSG(_("E728: Using a Dictionary as a Number"));
18877 break;
18878 default:
18879 EMSG2(_(e_intern2), "get_tv_number()");
18880 break;
18882 if (denote == NULL) /* useful for values that must be unsigned */
18883 n = -1;
18884 else
18885 *denote = TRUE;
18886 return n;
18890 * Get the lnum from the first argument.
18891 * Also accepts ".", "$", etc., but that only works for the current buffer.
18892 * Returns -1 on error.
18894 static linenr_T
18895 get_tv_lnum(argvars)
18896 typval_T *argvars;
18898 typval_T rettv;
18899 linenr_T lnum;
18901 lnum = get_tv_number_chk(&argvars[0], NULL);
18902 if (lnum == 0) /* no valid number, try using line() */
18904 rettv.v_type = VAR_NUMBER;
18905 f_line(argvars, &rettv);
18906 lnum = rettv.vval.v_number;
18907 clear_tv(&rettv);
18909 return lnum;
18913 * Get the lnum from the first argument.
18914 * Also accepts "$", then "buf" is used.
18915 * Returns 0 on error.
18917 static linenr_T
18918 get_tv_lnum_buf(argvars, buf)
18919 typval_T *argvars;
18920 buf_T *buf;
18922 if (argvars[0].v_type == VAR_STRING
18923 && argvars[0].vval.v_string != NULL
18924 && argvars[0].vval.v_string[0] == '$'
18925 && buf != NULL)
18926 return buf->b_ml.ml_line_count;
18927 return get_tv_number_chk(&argvars[0], NULL);
18931 * Get the string value of a variable.
18932 * If it is a Number variable, the number is converted into a string.
18933 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
18934 * get_tv_string_buf() uses a given buffer.
18935 * If the String variable has never been set, return an empty string.
18936 * Never returns NULL;
18937 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
18938 * NULL on error.
18940 static char_u *
18941 get_tv_string(varp)
18942 typval_T *varp;
18944 static char_u mybuf[NUMBUFLEN];
18946 return get_tv_string_buf(varp, mybuf);
18949 static char_u *
18950 get_tv_string_buf(varp, buf)
18951 typval_T *varp;
18952 char_u *buf;
18954 char_u *res = get_tv_string_buf_chk(varp, buf);
18956 return res != NULL ? res : (char_u *)"";
18959 char_u *
18960 get_tv_string_chk(varp)
18961 typval_T *varp;
18963 static char_u mybuf[NUMBUFLEN];
18965 return get_tv_string_buf_chk(varp, mybuf);
18968 static char_u *
18969 get_tv_string_buf_chk(varp, buf)
18970 typval_T *varp;
18971 char_u *buf;
18973 switch (varp->v_type)
18975 case VAR_NUMBER:
18976 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
18977 return buf;
18978 case VAR_FUNC:
18979 EMSG(_("E729: using Funcref as a String"));
18980 break;
18981 case VAR_LIST:
18982 EMSG(_("E730: using List as a String"));
18983 break;
18984 case VAR_DICT:
18985 EMSG(_("E731: using Dictionary as a String"));
18986 break;
18987 #ifdef FEAT_FLOAT
18988 case VAR_FLOAT:
18989 EMSG(_("E806: using Float as a String"));
18990 break;
18991 #endif
18992 case VAR_STRING:
18993 if (varp->vval.v_string != NULL)
18994 return varp->vval.v_string;
18995 return (char_u *)"";
18996 default:
18997 EMSG2(_(e_intern2), "get_tv_string_buf()");
18998 break;
19000 return NULL;
19004 * Find variable "name" in the list of variables.
19005 * Return a pointer to it if found, NULL if not found.
19006 * Careful: "a:0" variables don't have a name.
19007 * When "htp" is not NULL we are writing to the variable, set "htp" to the
19008 * hashtab_T used.
19010 static dictitem_T *
19011 find_var(name, htp)
19012 char_u *name;
19013 hashtab_T **htp;
19015 char_u *varname;
19016 hashtab_T *ht;
19018 ht = find_var_ht(name, &varname);
19019 if (htp != NULL)
19020 *htp = ht;
19021 if (ht == NULL)
19022 return NULL;
19023 return find_var_in_ht(ht, varname, htp != NULL);
19027 * Find variable "varname" in hashtab "ht".
19028 * Returns NULL if not found.
19030 static dictitem_T *
19031 find_var_in_ht(ht, varname, writing)
19032 hashtab_T *ht;
19033 char_u *varname;
19034 int writing;
19036 hashitem_T *hi;
19038 if (*varname == NUL)
19040 /* Must be something like "s:", otherwise "ht" would be NULL. */
19041 switch (varname[-2])
19043 case 's': return &SCRIPT_SV(current_SID).sv_var;
19044 case 'g': return &globvars_var;
19045 case 'v': return &vimvars_var;
19046 case 'b': return &curbuf->b_bufvar;
19047 case 'w': return &curwin->w_winvar;
19048 #ifdef FEAT_WINDOWS
19049 case 't': return &curtab->tp_winvar;
19050 #endif
19051 case 'l': return current_funccal == NULL
19052 ? NULL : &current_funccal->l_vars_var;
19053 case 'a': return current_funccal == NULL
19054 ? NULL : &current_funccal->l_avars_var;
19056 return NULL;
19059 hi = hash_find(ht, varname);
19060 if (HASHITEM_EMPTY(hi))
19062 /* For global variables we may try auto-loading the script. If it
19063 * worked find the variable again. Don't auto-load a script if it was
19064 * loaded already, otherwise it would be loaded every time when
19065 * checking if a function name is a Funcref variable. */
19066 if (ht == &globvarht && !writing
19067 && script_autoload(varname, FALSE) && !aborting())
19068 hi = hash_find(ht, varname);
19069 if (HASHITEM_EMPTY(hi))
19070 return NULL;
19072 return HI2DI(hi);
19076 * Find the hashtab used for a variable name.
19077 * Set "varname" to the start of name without ':'.
19079 static hashtab_T *
19080 find_var_ht(name, varname)
19081 char_u *name;
19082 char_u **varname;
19084 hashitem_T *hi;
19086 if (name[1] != ':')
19088 /* The name must not start with a colon or #. */
19089 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
19090 return NULL;
19091 *varname = name;
19093 /* "version" is "v:version" in all scopes */
19094 hi = hash_find(&compat_hashtab, name);
19095 if (!HASHITEM_EMPTY(hi))
19096 return &compat_hashtab;
19098 if (current_funccal == NULL)
19099 return &globvarht; /* global variable */
19100 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
19102 *varname = name + 2;
19103 if (*name == 'g') /* global variable */
19104 return &globvarht;
19105 /* There must be no ':' or '#' in the rest of the name, unless g: is used
19107 if (vim_strchr(name + 2, ':') != NULL
19108 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
19109 return NULL;
19110 if (*name == 'b') /* buffer variable */
19111 return &curbuf->b_vars.dv_hashtab;
19112 if (*name == 'w') /* window variable */
19113 return &curwin->w_vars.dv_hashtab;
19114 #ifdef FEAT_WINDOWS
19115 if (*name == 't') /* tab page variable */
19116 return &curtab->tp_vars.dv_hashtab;
19117 #endif
19118 if (*name == 'v') /* v: variable */
19119 return &vimvarht;
19120 if (*name == 'a' && current_funccal != NULL) /* function argument */
19121 return &current_funccal->l_avars.dv_hashtab;
19122 if (*name == 'l' && current_funccal != NULL) /* local function variable */
19123 return &current_funccal->l_vars.dv_hashtab;
19124 if (*name == 's' /* script variable */
19125 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
19126 return &SCRIPT_VARS(current_SID);
19127 return NULL;
19131 * Get the string value of a (global/local) variable.
19132 * Returns NULL when it doesn't exist.
19134 char_u *
19135 get_var_value(name)
19136 char_u *name;
19138 dictitem_T *v;
19140 v = find_var(name, NULL);
19141 if (v == NULL)
19142 return NULL;
19143 return get_tv_string(&v->di_tv);
19147 * Allocate a new hashtab for a sourced script. It will be used while
19148 * sourcing this script and when executing functions defined in the script.
19150 void
19151 new_script_vars(id)
19152 scid_T id;
19154 int i;
19155 hashtab_T *ht;
19156 scriptvar_T *sv;
19158 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
19160 /* Re-allocating ga_data means that an ht_array pointing to
19161 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
19162 * at its init value. Also reset "v_dict", it's always the same. */
19163 for (i = 1; i <= ga_scripts.ga_len; ++i)
19165 ht = &SCRIPT_VARS(i);
19166 if (ht->ht_mask == HT_INIT_SIZE - 1)
19167 ht->ht_array = ht->ht_smallarray;
19168 sv = &SCRIPT_SV(i);
19169 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
19172 while (ga_scripts.ga_len < id)
19174 sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
19175 init_var_dict(&sv->sv_dict, &sv->sv_var);
19176 ++ga_scripts.ga_len;
19182 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
19183 * point to it.
19185 void
19186 init_var_dict(dict, dict_var)
19187 dict_T *dict;
19188 dictitem_T *dict_var;
19190 hash_init(&dict->dv_hashtab);
19191 dict->dv_refcount = DO_NOT_FREE_CNT;
19192 dict_var->di_tv.vval.v_dict = dict;
19193 dict_var->di_tv.v_type = VAR_DICT;
19194 dict_var->di_tv.v_lock = VAR_FIXED;
19195 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
19196 dict_var->di_key[0] = NUL;
19200 * Clean up a list of internal variables.
19201 * Frees all allocated variables and the value they contain.
19202 * Clears hashtab "ht", does not free it.
19204 void
19205 vars_clear(ht)
19206 hashtab_T *ht;
19208 vars_clear_ext(ht, TRUE);
19212 * Like vars_clear(), but only free the value if "free_val" is TRUE.
19214 static void
19215 vars_clear_ext(ht, free_val)
19216 hashtab_T *ht;
19217 int free_val;
19219 int todo;
19220 hashitem_T *hi;
19221 dictitem_T *v;
19223 hash_lock(ht);
19224 todo = (int)ht->ht_used;
19225 for (hi = ht->ht_array; todo > 0; ++hi)
19227 if (!HASHITEM_EMPTY(hi))
19229 --todo;
19231 /* Free the variable. Don't remove it from the hashtab,
19232 * ht_array might change then. hash_clear() takes care of it
19233 * later. */
19234 v = HI2DI(hi);
19235 if (free_val)
19236 clear_tv(&v->di_tv);
19237 if ((v->di_flags & DI_FLAGS_FIX) == 0)
19238 vim_free(v);
19241 hash_clear(ht);
19242 ht->ht_used = 0;
19246 * Delete a variable from hashtab "ht" at item "hi".
19247 * Clear the variable value and free the dictitem.
19249 static void
19250 delete_var(ht, hi)
19251 hashtab_T *ht;
19252 hashitem_T *hi;
19254 dictitem_T *di = HI2DI(hi);
19256 hash_remove(ht, hi);
19257 clear_tv(&di->di_tv);
19258 vim_free(di);
19262 * List the value of one internal variable.
19264 static void
19265 list_one_var(v, prefix, first)
19266 dictitem_T *v;
19267 char_u *prefix;
19268 int *first;
19270 char_u *tofree;
19271 char_u *s;
19272 char_u numbuf[NUMBUFLEN];
19274 s = echo_string(&v->di_tv, &tofree, numbuf, ++current_copyID);
19275 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
19276 s == NULL ? (char_u *)"" : s, first);
19277 vim_free(tofree);
19280 static void
19281 list_one_var_a(prefix, name, type, string, first)
19282 char_u *prefix;
19283 char_u *name;
19284 int type;
19285 char_u *string;
19286 int *first; /* when TRUE clear rest of screen and set to FALSE */
19288 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
19289 msg_start();
19290 msg_puts(prefix);
19291 if (name != NULL) /* "a:" vars don't have a name stored */
19292 msg_puts(name);
19293 msg_putchar(' ');
19294 msg_advance(22);
19295 if (type == VAR_NUMBER)
19296 msg_putchar('#');
19297 else if (type == VAR_FUNC)
19298 msg_putchar('*');
19299 else if (type == VAR_LIST)
19301 msg_putchar('[');
19302 if (*string == '[')
19303 ++string;
19305 else if (type == VAR_DICT)
19307 msg_putchar('{');
19308 if (*string == '{')
19309 ++string;
19311 else
19312 msg_putchar(' ');
19314 msg_outtrans(string);
19316 if (type == VAR_FUNC)
19317 msg_puts((char_u *)"()");
19318 if (*first)
19320 msg_clr_eos();
19321 *first = FALSE;
19326 * Set variable "name" to value in "tv".
19327 * If the variable already exists, the value is updated.
19328 * Otherwise the variable is created.
19330 static void
19331 set_var(name, tv, copy)
19332 char_u *name;
19333 typval_T *tv;
19334 int copy; /* make copy of value in "tv" */
19336 dictitem_T *v;
19337 char_u *varname;
19338 hashtab_T *ht;
19339 char_u *p;
19341 if (tv->v_type == VAR_FUNC)
19343 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
19344 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
19345 ? name[2] : name[0]))
19347 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
19348 return;
19350 if (function_exists(name))
19352 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
19353 name);
19354 return;
19358 ht = find_var_ht(name, &varname);
19359 if (ht == NULL || *varname == NUL)
19361 EMSG2(_(e_illvar), name);
19362 return;
19365 v = find_var_in_ht(ht, varname, TRUE);
19366 if (v != NULL)
19368 /* existing variable, need to clear the value */
19369 if (var_check_ro(v->di_flags, name)
19370 || tv_check_lock(v->di_tv.v_lock, name))
19371 return;
19372 if (v->di_tv.v_type != tv->v_type
19373 && !((v->di_tv.v_type == VAR_STRING
19374 || v->di_tv.v_type == VAR_NUMBER)
19375 && (tv->v_type == VAR_STRING
19376 || tv->v_type == VAR_NUMBER))
19377 #ifdef FEAT_FLOAT
19378 && !((v->di_tv.v_type == VAR_NUMBER
19379 || v->di_tv.v_type == VAR_FLOAT)
19380 && (tv->v_type == VAR_NUMBER
19381 || tv->v_type == VAR_FLOAT))
19382 #endif
19385 EMSG2(_("E706: Variable type mismatch for: %s"), name);
19386 return;
19390 * Handle setting internal v: variables separately: we don't change
19391 * the type.
19393 if (ht == &vimvarht)
19395 if (v->di_tv.v_type == VAR_STRING)
19397 vim_free(v->di_tv.vval.v_string);
19398 if (copy || tv->v_type != VAR_STRING)
19399 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
19400 else
19402 /* Take over the string to avoid an extra alloc/free. */
19403 v->di_tv.vval.v_string = tv->vval.v_string;
19404 tv->vval.v_string = NULL;
19407 else if (v->di_tv.v_type != VAR_NUMBER)
19408 EMSG2(_(e_intern2), "set_var()");
19409 else
19411 v->di_tv.vval.v_number = get_tv_number(tv);
19412 if (STRCMP(varname, "searchforward") == 0)
19413 set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
19415 return;
19418 clear_tv(&v->di_tv);
19420 else /* add a new variable */
19422 /* Can't add "v:" variable. */
19423 if (ht == &vimvarht)
19425 EMSG2(_(e_illvar), name);
19426 return;
19429 /* Make sure the variable name is valid. */
19430 for (p = varname; *p != NUL; ++p)
19431 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
19432 && *p != AUTOLOAD_CHAR)
19434 EMSG2(_(e_illvar), varname);
19435 return;
19438 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
19439 + STRLEN(varname)));
19440 if (v == NULL)
19441 return;
19442 STRCPY(v->di_key, varname);
19443 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
19445 vim_free(v);
19446 return;
19448 v->di_flags = 0;
19451 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
19452 copy_tv(tv, &v->di_tv);
19453 else
19455 v->di_tv = *tv;
19456 v->di_tv.v_lock = 0;
19457 init_tv(tv);
19462 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
19463 * Also give an error message.
19465 static int
19466 var_check_ro(flags, name)
19467 int flags;
19468 char_u *name;
19470 if (flags & DI_FLAGS_RO)
19472 EMSG2(_(e_readonlyvar), name);
19473 return TRUE;
19475 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
19477 EMSG2(_(e_readonlysbx), name);
19478 return TRUE;
19480 return FALSE;
19484 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
19485 * Also give an error message.
19487 static int
19488 var_check_fixed(flags, name)
19489 int flags;
19490 char_u *name;
19492 if (flags & DI_FLAGS_FIX)
19494 EMSG2(_("E795: Cannot delete variable %s"), name);
19495 return TRUE;
19497 return FALSE;
19501 * Return TRUE if typeval "tv" is set to be locked (immutable).
19502 * Also give an error message, using "name".
19504 static int
19505 tv_check_lock(lock, name)
19506 int lock;
19507 char_u *name;
19509 if (lock & VAR_LOCKED)
19511 EMSG2(_("E741: Value is locked: %s"),
19512 name == NULL ? (char_u *)_("Unknown") : name);
19513 return TRUE;
19515 if (lock & VAR_FIXED)
19517 EMSG2(_("E742: Cannot change value of %s"),
19518 name == NULL ? (char_u *)_("Unknown") : name);
19519 return TRUE;
19521 return FALSE;
19525 * Copy the values from typval_T "from" to typval_T "to".
19526 * When needed allocates string or increases reference count.
19527 * Does not make a copy of a list or dict but copies the reference!
19528 * It is OK for "from" and "to" to point to the same item. This is used to
19529 * make a copy later.
19531 static void
19532 copy_tv(from, to)
19533 typval_T *from;
19534 typval_T *to;
19536 to->v_type = from->v_type;
19537 to->v_lock = 0;
19538 switch (from->v_type)
19540 case VAR_NUMBER:
19541 to->vval.v_number = from->vval.v_number;
19542 break;
19543 #ifdef FEAT_FLOAT
19544 case VAR_FLOAT:
19545 to->vval.v_float = from->vval.v_float;
19546 break;
19547 #endif
19548 case VAR_STRING:
19549 case VAR_FUNC:
19550 if (from->vval.v_string == NULL)
19551 to->vval.v_string = NULL;
19552 else
19554 to->vval.v_string = vim_strsave(from->vval.v_string);
19555 if (from->v_type == VAR_FUNC)
19556 func_ref(to->vval.v_string);
19558 break;
19559 case VAR_LIST:
19560 if (from->vval.v_list == NULL)
19561 to->vval.v_list = NULL;
19562 else
19564 to->vval.v_list = from->vval.v_list;
19565 ++to->vval.v_list->lv_refcount;
19567 break;
19568 case VAR_DICT:
19569 if (from->vval.v_dict == NULL)
19570 to->vval.v_dict = NULL;
19571 else
19573 to->vval.v_dict = from->vval.v_dict;
19574 ++to->vval.v_dict->dv_refcount;
19576 break;
19577 default:
19578 EMSG2(_(e_intern2), "copy_tv()");
19579 break;
19584 * Make a copy of an item.
19585 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
19586 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
19587 * reference to an already copied list/dict can be used.
19588 * Returns FAIL or OK.
19590 static int
19591 item_copy(from, to, deep, copyID)
19592 typval_T *from;
19593 typval_T *to;
19594 int deep;
19595 int copyID;
19597 static int recurse = 0;
19598 int ret = OK;
19600 if (recurse >= DICT_MAXNEST)
19602 EMSG(_("E698: variable nested too deep for making a copy"));
19603 return FAIL;
19605 ++recurse;
19607 switch (from->v_type)
19609 case VAR_NUMBER:
19610 #ifdef FEAT_FLOAT
19611 case VAR_FLOAT:
19612 #endif
19613 case VAR_STRING:
19614 case VAR_FUNC:
19615 copy_tv(from, to);
19616 break;
19617 case VAR_LIST:
19618 to->v_type = VAR_LIST;
19619 to->v_lock = 0;
19620 if (from->vval.v_list == NULL)
19621 to->vval.v_list = NULL;
19622 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
19624 /* use the copy made earlier */
19625 to->vval.v_list = from->vval.v_list->lv_copylist;
19626 ++to->vval.v_list->lv_refcount;
19628 else
19629 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
19630 if (to->vval.v_list == NULL)
19631 ret = FAIL;
19632 break;
19633 case VAR_DICT:
19634 to->v_type = VAR_DICT;
19635 to->v_lock = 0;
19636 if (from->vval.v_dict == NULL)
19637 to->vval.v_dict = NULL;
19638 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
19640 /* use the copy made earlier */
19641 to->vval.v_dict = from->vval.v_dict->dv_copydict;
19642 ++to->vval.v_dict->dv_refcount;
19644 else
19645 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
19646 if (to->vval.v_dict == NULL)
19647 ret = FAIL;
19648 break;
19649 default:
19650 EMSG2(_(e_intern2), "item_copy()");
19651 ret = FAIL;
19653 --recurse;
19654 return ret;
19658 * ":echo expr1 ..." print each argument separated with a space, add a
19659 * newline at the end.
19660 * ":echon expr1 ..." print each argument plain.
19662 void
19663 ex_echo(eap)
19664 exarg_T *eap;
19666 char_u *arg = eap->arg;
19667 typval_T rettv;
19668 char_u *tofree;
19669 char_u *p;
19670 int needclr = TRUE;
19671 int atstart = TRUE;
19672 char_u numbuf[NUMBUFLEN];
19674 if (eap->skip)
19675 ++emsg_skip;
19676 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
19678 /* If eval1() causes an error message the text from the command may
19679 * still need to be cleared. E.g., "echo 22,44". */
19680 need_clr_eos = needclr;
19682 p = arg;
19683 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19686 * Report the invalid expression unless the expression evaluation
19687 * has been cancelled due to an aborting error, an interrupt, or an
19688 * exception.
19690 if (!aborting())
19691 EMSG2(_(e_invexpr2), p);
19692 need_clr_eos = FALSE;
19693 break;
19695 need_clr_eos = FALSE;
19697 if (!eap->skip)
19699 if (atstart)
19701 atstart = FALSE;
19702 /* Call msg_start() after eval1(), evaluating the expression
19703 * may cause a message to appear. */
19704 if (eap->cmdidx == CMD_echo)
19705 msg_start();
19707 else if (eap->cmdidx == CMD_echo)
19708 msg_puts_attr((char_u *)" ", echo_attr);
19709 p = echo_string(&rettv, &tofree, numbuf, ++current_copyID);
19710 if (p != NULL)
19711 for ( ; *p != NUL && !got_int; ++p)
19713 if (*p == '\n' || *p == '\r' || *p == TAB)
19715 if (*p != TAB && needclr)
19717 /* remove any text still there from the command */
19718 msg_clr_eos();
19719 needclr = FALSE;
19721 msg_putchar_attr(*p, echo_attr);
19723 else
19725 #ifdef FEAT_MBYTE
19726 if (has_mbyte)
19728 int i = (*mb_ptr2len)(p);
19730 (void)msg_outtrans_len_attr(p, i, echo_attr);
19731 p += i - 1;
19733 else
19734 #endif
19735 (void)msg_outtrans_len_attr(p, 1, echo_attr);
19738 vim_free(tofree);
19740 clear_tv(&rettv);
19741 arg = skipwhite(arg);
19743 eap->nextcmd = check_nextcmd(arg);
19745 if (eap->skip)
19746 --emsg_skip;
19747 else
19749 /* remove text that may still be there from the command */
19750 if (needclr)
19751 msg_clr_eos();
19752 if (eap->cmdidx == CMD_echo)
19753 msg_end();
19758 * ":echohl {name}".
19760 void
19761 ex_echohl(eap)
19762 exarg_T *eap;
19764 int id;
19766 id = syn_name2id(eap->arg);
19767 if (id == 0)
19768 echo_attr = 0;
19769 else
19770 echo_attr = syn_id2attr(id);
19774 * ":execute expr1 ..." execute the result of an expression.
19775 * ":echomsg expr1 ..." Print a message
19776 * ":echoerr expr1 ..." Print an error
19777 * Each gets spaces around each argument and a newline at the end for
19778 * echo commands
19780 void
19781 ex_execute(eap)
19782 exarg_T *eap;
19784 char_u *arg = eap->arg;
19785 typval_T rettv;
19786 int ret = OK;
19787 char_u *p;
19788 garray_T ga;
19789 int len;
19790 int save_did_emsg;
19792 ga_init2(&ga, 1, 80);
19794 if (eap->skip)
19795 ++emsg_skip;
19796 while (*arg != NUL && *arg != '|' && *arg != '\n')
19798 p = arg;
19799 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19802 * Report the invalid expression unless the expression evaluation
19803 * has been cancelled due to an aborting error, an interrupt, or an
19804 * exception.
19806 if (!aborting())
19807 EMSG2(_(e_invexpr2), p);
19808 ret = FAIL;
19809 break;
19812 if (!eap->skip)
19814 p = get_tv_string(&rettv);
19815 len = (int)STRLEN(p);
19816 if (ga_grow(&ga, len + 2) == FAIL)
19818 clear_tv(&rettv);
19819 ret = FAIL;
19820 break;
19822 if (ga.ga_len)
19823 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
19824 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
19825 ga.ga_len += len;
19828 clear_tv(&rettv);
19829 arg = skipwhite(arg);
19832 if (ret != FAIL && ga.ga_data != NULL)
19834 if (eap->cmdidx == CMD_echomsg)
19836 MSG_ATTR(ga.ga_data, echo_attr);
19837 out_flush();
19839 else if (eap->cmdidx == CMD_echoerr)
19841 /* We don't want to abort following commands, restore did_emsg. */
19842 save_did_emsg = did_emsg;
19843 EMSG((char_u *)ga.ga_data);
19844 if (!force_abort)
19845 did_emsg = save_did_emsg;
19847 else if (eap->cmdidx == CMD_execute)
19848 do_cmdline((char_u *)ga.ga_data,
19849 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
19852 ga_clear(&ga);
19854 if (eap->skip)
19855 --emsg_skip;
19857 eap->nextcmd = check_nextcmd(arg);
19861 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
19862 * "arg" points to the "&" or '+' when called, to "option" when returning.
19863 * Returns NULL when no option name found. Otherwise pointer to the char
19864 * after the option name.
19866 static char_u *
19867 find_option_end(arg, opt_flags)
19868 char_u **arg;
19869 int *opt_flags;
19871 char_u *p = *arg;
19873 ++p;
19874 if (*p == 'g' && p[1] == ':')
19876 *opt_flags = OPT_GLOBAL;
19877 p += 2;
19879 else if (*p == 'l' && p[1] == ':')
19881 *opt_flags = OPT_LOCAL;
19882 p += 2;
19884 else
19885 *opt_flags = 0;
19887 if (!ASCII_ISALPHA(*p))
19888 return NULL;
19889 *arg = p;
19891 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
19892 p += 4; /* termcap option */
19893 else
19894 while (ASCII_ISALPHA(*p))
19895 ++p;
19896 return p;
19900 * ":function"
19902 void
19903 ex_function(eap)
19904 exarg_T *eap;
19906 char_u *theline;
19907 int j;
19908 int c;
19909 int saved_did_emsg;
19910 char_u *name = NULL;
19911 char_u *p;
19912 char_u *arg;
19913 char_u *line_arg = NULL;
19914 garray_T newargs;
19915 garray_T newlines;
19916 int varargs = FALSE;
19917 int mustend = FALSE;
19918 int flags = 0;
19919 ufunc_T *fp;
19920 int indent;
19921 int nesting;
19922 char_u *skip_until = NULL;
19923 dictitem_T *v;
19924 funcdict_T fudi;
19925 static int func_nr = 0; /* number for nameless function */
19926 int paren;
19927 hashtab_T *ht;
19928 int todo;
19929 hashitem_T *hi;
19930 int sourcing_lnum_off;
19933 * ":function" without argument: list functions.
19935 if (ends_excmd(*eap->arg))
19937 if (!eap->skip)
19939 todo = (int)func_hashtab.ht_used;
19940 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19942 if (!HASHITEM_EMPTY(hi))
19944 --todo;
19945 fp = HI2UF(hi);
19946 if (!isdigit(*fp->uf_name))
19947 list_func_head(fp, FALSE);
19951 eap->nextcmd = check_nextcmd(eap->arg);
19952 return;
19956 * ":function /pat": list functions matching pattern.
19958 if (*eap->arg == '/')
19960 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
19961 if (!eap->skip)
19963 regmatch_T regmatch;
19965 c = *p;
19966 *p = NUL;
19967 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
19968 *p = c;
19969 if (regmatch.regprog != NULL)
19971 regmatch.rm_ic = p_ic;
19973 todo = (int)func_hashtab.ht_used;
19974 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19976 if (!HASHITEM_EMPTY(hi))
19978 --todo;
19979 fp = HI2UF(hi);
19980 if (!isdigit(*fp->uf_name)
19981 && vim_regexec(&regmatch, fp->uf_name, 0))
19982 list_func_head(fp, FALSE);
19987 if (*p == '/')
19988 ++p;
19989 eap->nextcmd = check_nextcmd(p);
19990 return;
19994 * Get the function name. There are these situations:
19995 * func normal function name
19996 * "name" == func, "fudi.fd_dict" == NULL
19997 * dict.func new dictionary entry
19998 * "name" == NULL, "fudi.fd_dict" set,
19999 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
20000 * dict.func existing dict entry with a Funcref
20001 * "name" == func, "fudi.fd_dict" set,
20002 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
20003 * dict.func existing dict entry that's not a Funcref
20004 * "name" == NULL, "fudi.fd_dict" set,
20005 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
20007 p = eap->arg;
20008 name = trans_function_name(&p, eap->skip, 0, &fudi);
20009 paren = (vim_strchr(p, '(') != NULL);
20010 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
20013 * Return on an invalid expression in braces, unless the expression
20014 * evaluation has been cancelled due to an aborting error, an
20015 * interrupt, or an exception.
20017 if (!aborting())
20019 if (!eap->skip && fudi.fd_newkey != NULL)
20020 EMSG2(_(e_dictkey), fudi.fd_newkey);
20021 vim_free(fudi.fd_newkey);
20022 return;
20024 else
20025 eap->skip = TRUE;
20028 /* An error in a function call during evaluation of an expression in magic
20029 * braces should not cause the function not to be defined. */
20030 saved_did_emsg = did_emsg;
20031 did_emsg = FALSE;
20034 * ":function func" with only function name: list function.
20036 if (!paren)
20038 if (!ends_excmd(*skipwhite(p)))
20040 EMSG(_(e_trailing));
20041 goto ret_free;
20043 eap->nextcmd = check_nextcmd(p);
20044 if (eap->nextcmd != NULL)
20045 *p = NUL;
20046 if (!eap->skip && !got_int)
20048 fp = find_func(name);
20049 if (fp != NULL)
20051 list_func_head(fp, TRUE);
20052 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
20054 if (FUNCLINE(fp, j) == NULL)
20055 continue;
20056 msg_putchar('\n');
20057 msg_outnum((long)(j + 1));
20058 if (j < 9)
20059 msg_putchar(' ');
20060 if (j < 99)
20061 msg_putchar(' ');
20062 msg_prt_line(FUNCLINE(fp, j), FALSE);
20063 out_flush(); /* show a line at a time */
20064 ui_breakcheck();
20066 if (!got_int)
20068 msg_putchar('\n');
20069 msg_puts((char_u *)" endfunction");
20072 else
20073 emsg_funcname("E123: Undefined function: %s", name);
20075 goto ret_free;
20079 * ":function name(arg1, arg2)" Define function.
20081 p = skipwhite(p);
20082 if (*p != '(')
20084 if (!eap->skip)
20086 EMSG2(_("E124: Missing '(': %s"), eap->arg);
20087 goto ret_free;
20089 /* attempt to continue by skipping some text */
20090 if (vim_strchr(p, '(') != NULL)
20091 p = vim_strchr(p, '(');
20093 p = skipwhite(p + 1);
20095 ga_init2(&newargs, (int)sizeof(char_u *), 3);
20096 ga_init2(&newlines, (int)sizeof(char_u *), 3);
20098 if (!eap->skip)
20100 /* Check the name of the function. Unless it's a dictionary function
20101 * (that we are overwriting). */
20102 if (name != NULL)
20103 arg = name;
20104 else
20105 arg = fudi.fd_newkey;
20106 if (arg != NULL && (fudi.fd_di == NULL
20107 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
20109 if (*arg == K_SPECIAL)
20110 j = 3;
20111 else
20112 j = 0;
20113 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
20114 : eval_isnamec(arg[j])))
20115 ++j;
20116 if (arg[j] != NUL)
20117 emsg_funcname(_(e_invarg2), arg);
20122 * Isolate the arguments: "arg1, arg2, ...)"
20124 while (*p != ')')
20126 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
20128 varargs = TRUE;
20129 p += 3;
20130 mustend = TRUE;
20132 else
20134 arg = p;
20135 while (ASCII_ISALNUM(*p) || *p == '_')
20136 ++p;
20137 if (arg == p || isdigit(*arg)
20138 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
20139 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
20141 if (!eap->skip)
20142 EMSG2(_("E125: Illegal argument: %s"), arg);
20143 break;
20145 if (ga_grow(&newargs, 1) == FAIL)
20146 goto erret;
20147 c = *p;
20148 *p = NUL;
20149 arg = vim_strsave(arg);
20150 if (arg == NULL)
20151 goto erret;
20152 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
20153 *p = c;
20154 newargs.ga_len++;
20155 if (*p == ',')
20156 ++p;
20157 else
20158 mustend = TRUE;
20160 p = skipwhite(p);
20161 if (mustend && *p != ')')
20163 if (!eap->skip)
20164 EMSG2(_(e_invarg2), eap->arg);
20165 break;
20168 ++p; /* skip the ')' */
20170 /* find extra arguments "range", "dict" and "abort" */
20171 for (;;)
20173 p = skipwhite(p);
20174 if (STRNCMP(p, "range", 5) == 0)
20176 flags |= FC_RANGE;
20177 p += 5;
20179 else if (STRNCMP(p, "dict", 4) == 0)
20181 flags |= FC_DICT;
20182 p += 4;
20184 else if (STRNCMP(p, "abort", 5) == 0)
20186 flags |= FC_ABORT;
20187 p += 5;
20189 else
20190 break;
20193 /* When there is a line break use what follows for the function body.
20194 * Makes 'exe "func Test()\n...\nendfunc"' work. */
20195 if (*p == '\n')
20196 line_arg = p + 1;
20197 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
20198 EMSG(_(e_trailing));
20201 * Read the body of the function, until ":endfunction" is found.
20203 if (KeyTyped)
20205 /* Check if the function already exists, don't let the user type the
20206 * whole function before telling him it doesn't work! For a script we
20207 * need to skip the body to be able to find what follows. */
20208 if (!eap->skip && !eap->forceit)
20210 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
20211 EMSG(_(e_funcdict));
20212 else if (name != NULL && find_func(name) != NULL)
20213 emsg_funcname(e_funcexts, name);
20216 if (!eap->skip && did_emsg)
20217 goto erret;
20219 msg_putchar('\n'); /* don't overwrite the function name */
20220 cmdline_row = msg_row;
20223 indent = 2;
20224 nesting = 0;
20225 for (;;)
20227 msg_scroll = TRUE;
20228 need_wait_return = FALSE;
20229 sourcing_lnum_off = sourcing_lnum;
20231 if (line_arg != NULL)
20233 /* Use eap->arg, split up in parts by line breaks. */
20234 theline = line_arg;
20235 p = vim_strchr(theline, '\n');
20236 if (p == NULL)
20237 line_arg += STRLEN(line_arg);
20238 else
20240 *p = NUL;
20241 line_arg = p + 1;
20244 else if (eap->getline == NULL)
20245 theline = getcmdline(':', 0L, indent);
20246 else
20247 theline = eap->getline(':', eap->cookie, indent);
20248 if (KeyTyped)
20249 lines_left = Rows - 1;
20250 if (theline == NULL)
20252 EMSG(_("E126: Missing :endfunction"));
20253 goto erret;
20256 /* Detect line continuation: sourcing_lnum increased more than one. */
20257 if (sourcing_lnum > sourcing_lnum_off + 1)
20258 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
20259 else
20260 sourcing_lnum_off = 0;
20262 if (skip_until != NULL)
20264 /* between ":append" and "." and between ":python <<EOF" and "EOF"
20265 * don't check for ":endfunc". */
20266 if (STRCMP(theline, skip_until) == 0)
20268 vim_free(skip_until);
20269 skip_until = NULL;
20272 else
20274 /* skip ':' and blanks*/
20275 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
20278 /* Check for "endfunction". */
20279 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
20281 if (line_arg == NULL)
20282 vim_free(theline);
20283 break;
20286 /* Increase indent inside "if", "while", "for" and "try", decrease
20287 * at "end". */
20288 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
20289 indent -= 2;
20290 else if (STRNCMP(p, "if", 2) == 0
20291 || STRNCMP(p, "wh", 2) == 0
20292 || STRNCMP(p, "for", 3) == 0
20293 || STRNCMP(p, "try", 3) == 0)
20294 indent += 2;
20296 /* Check for defining a function inside this function. */
20297 if (checkforcmd(&p, "function", 2))
20299 if (*p == '!')
20300 p = skipwhite(p + 1);
20301 p += eval_fname_script(p);
20302 if (ASCII_ISALPHA(*p))
20304 vim_free(trans_function_name(&p, TRUE, 0, NULL));
20305 if (*skipwhite(p) == '(')
20307 ++nesting;
20308 indent += 2;
20313 /* Check for ":append" or ":insert". */
20314 p = skip_range(p, NULL);
20315 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
20316 || (p[0] == 'i'
20317 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
20318 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
20319 skip_until = vim_strsave((char_u *)".");
20321 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
20322 arg = skipwhite(skiptowhite(p));
20323 if (arg[0] == '<' && arg[1] =='<'
20324 && ((p[0] == 'p' && p[1] == 'y'
20325 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
20326 || (p[0] == 'p' && p[1] == 'e'
20327 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
20328 || (p[0] == 't' && p[1] == 'c'
20329 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
20330 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
20331 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
20332 || (p[0] == 'm' && p[1] == 'z'
20333 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
20336 /* ":python <<" continues until a dot, like ":append" */
20337 p = skipwhite(arg + 2);
20338 if (*p == NUL)
20339 skip_until = vim_strsave((char_u *)".");
20340 else
20341 skip_until = vim_strsave(p);
20345 /* Add the line to the function. */
20346 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
20348 if (line_arg == NULL)
20349 vim_free(theline);
20350 goto erret;
20353 /* Copy the line to newly allocated memory. get_one_sourceline()
20354 * allocates 250 bytes per line, this saves 80% on average. The cost
20355 * is an extra alloc/free. */
20356 p = vim_strsave(theline);
20357 if (p != NULL)
20359 if (line_arg == NULL)
20360 vim_free(theline);
20361 theline = p;
20364 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
20366 /* Add NULL lines for continuation lines, so that the line count is
20367 * equal to the index in the growarray. */
20368 while (sourcing_lnum_off-- > 0)
20369 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
20371 /* Check for end of eap->arg. */
20372 if (line_arg != NULL && *line_arg == NUL)
20373 line_arg = NULL;
20376 /* Don't define the function when skipping commands or when an error was
20377 * detected. */
20378 if (eap->skip || did_emsg)
20379 goto erret;
20382 * If there are no errors, add the function
20384 if (fudi.fd_dict == NULL)
20386 v = find_var(name, &ht);
20387 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
20389 emsg_funcname("E707: Function name conflicts with variable: %s",
20390 name);
20391 goto erret;
20394 fp = find_func(name);
20395 if (fp != NULL)
20397 if (!eap->forceit)
20399 emsg_funcname(e_funcexts, name);
20400 goto erret;
20402 if (fp->uf_calls > 0)
20404 emsg_funcname("E127: Cannot redefine function %s: It is in use",
20405 name);
20406 goto erret;
20408 /* redefine existing function */
20409 ga_clear_strings(&(fp->uf_args));
20410 ga_clear_strings(&(fp->uf_lines));
20411 vim_free(name);
20412 name = NULL;
20415 else
20417 char numbuf[20];
20419 fp = NULL;
20420 if (fudi.fd_newkey == NULL && !eap->forceit)
20422 EMSG(_(e_funcdict));
20423 goto erret;
20425 if (fudi.fd_di == NULL)
20427 /* Can't add a function to a locked dictionary */
20428 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
20429 goto erret;
20431 /* Can't change an existing function if it is locked */
20432 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
20433 goto erret;
20435 /* Give the function a sequential number. Can only be used with a
20436 * Funcref! */
20437 vim_free(name);
20438 sprintf(numbuf, "%d", ++func_nr);
20439 name = vim_strsave((char_u *)numbuf);
20440 if (name == NULL)
20441 goto erret;
20444 if (fp == NULL)
20446 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
20448 int slen, plen;
20449 char_u *scriptname;
20451 /* Check that the autoload name matches the script name. */
20452 j = FAIL;
20453 if (sourcing_name != NULL)
20455 scriptname = autoload_name(name);
20456 if (scriptname != NULL)
20458 p = vim_strchr(scriptname, '/');
20459 plen = (int)STRLEN(p);
20460 slen = (int)STRLEN(sourcing_name);
20461 if (slen > plen && fnamecmp(p,
20462 sourcing_name + slen - plen) == 0)
20463 j = OK;
20464 vim_free(scriptname);
20467 if (j == FAIL)
20469 EMSG2(_("E746: Function name does not match script file name: %s"), name);
20470 goto erret;
20474 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
20475 if (fp == NULL)
20476 goto erret;
20478 if (fudi.fd_dict != NULL)
20480 if (fudi.fd_di == NULL)
20482 /* add new dict entry */
20483 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
20484 if (fudi.fd_di == NULL)
20486 vim_free(fp);
20487 goto erret;
20489 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
20491 vim_free(fudi.fd_di);
20492 vim_free(fp);
20493 goto erret;
20496 else
20497 /* overwrite existing dict entry */
20498 clear_tv(&fudi.fd_di->di_tv);
20499 fudi.fd_di->di_tv.v_type = VAR_FUNC;
20500 fudi.fd_di->di_tv.v_lock = 0;
20501 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
20502 fp->uf_refcount = 1;
20504 /* behave like "dict" was used */
20505 flags |= FC_DICT;
20508 /* insert the new function in the function list */
20509 STRCPY(fp->uf_name, name);
20510 hash_add(&func_hashtab, UF2HIKEY(fp));
20512 fp->uf_args = newargs;
20513 fp->uf_lines = newlines;
20514 #ifdef FEAT_PROFILE
20515 fp->uf_tml_count = NULL;
20516 fp->uf_tml_total = NULL;
20517 fp->uf_tml_self = NULL;
20518 fp->uf_profiling = FALSE;
20519 if (prof_def_func())
20520 func_do_profile(fp);
20521 #endif
20522 fp->uf_varargs = varargs;
20523 fp->uf_flags = flags;
20524 fp->uf_calls = 0;
20525 fp->uf_script_ID = current_SID;
20526 goto ret_free;
20528 erret:
20529 ga_clear_strings(&newargs);
20530 ga_clear_strings(&newlines);
20531 ret_free:
20532 vim_free(skip_until);
20533 vim_free(fudi.fd_newkey);
20534 vim_free(name);
20535 did_emsg |= saved_did_emsg;
20539 * Get a function name, translating "<SID>" and "<SNR>".
20540 * Also handles a Funcref in a List or Dictionary.
20541 * Returns the function name in allocated memory, or NULL for failure.
20542 * flags:
20543 * TFN_INT: internal function name OK
20544 * TFN_QUIET: be quiet
20545 * Advances "pp" to just after the function name (if no error).
20547 static char_u *
20548 trans_function_name(pp, skip, flags, fdp)
20549 char_u **pp;
20550 int skip; /* only find the end, don't evaluate */
20551 int flags;
20552 funcdict_T *fdp; /* return: info about dictionary used */
20554 char_u *name = NULL;
20555 char_u *start;
20556 char_u *end;
20557 int lead;
20558 char_u sid_buf[20];
20559 int len;
20560 lval_T lv;
20562 if (fdp != NULL)
20563 vim_memset(fdp, 0, sizeof(funcdict_T));
20564 start = *pp;
20566 /* Check for hard coded <SNR>: already translated function ID (from a user
20567 * command). */
20568 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
20569 && (*pp)[2] == (int)KE_SNR)
20571 *pp += 3;
20572 len = get_id_len(pp) + 3;
20573 return vim_strnsave(start, len);
20576 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
20577 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
20578 lead = eval_fname_script(start);
20579 if (lead > 2)
20580 start += lead;
20582 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
20583 lead > 2 ? 0 : FNE_CHECK_START);
20584 if (end == start)
20586 if (!skip)
20587 EMSG(_("E129: Function name required"));
20588 goto theend;
20590 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
20593 * Report an invalid expression in braces, unless the expression
20594 * evaluation has been cancelled due to an aborting error, an
20595 * interrupt, or an exception.
20597 if (!aborting())
20599 if (end != NULL)
20600 EMSG2(_(e_invarg2), start);
20602 else
20603 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
20604 goto theend;
20607 if (lv.ll_tv != NULL)
20609 if (fdp != NULL)
20611 fdp->fd_dict = lv.ll_dict;
20612 fdp->fd_newkey = lv.ll_newkey;
20613 lv.ll_newkey = NULL;
20614 fdp->fd_di = lv.ll_di;
20616 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
20618 name = vim_strsave(lv.ll_tv->vval.v_string);
20619 *pp = end;
20621 else
20623 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
20624 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
20625 EMSG(_(e_funcref));
20626 else
20627 *pp = end;
20628 name = NULL;
20630 goto theend;
20633 if (lv.ll_name == NULL)
20635 /* Error found, but continue after the function name. */
20636 *pp = end;
20637 goto theend;
20640 /* Check if the name is a Funcref. If so, use the value. */
20641 if (lv.ll_exp_name != NULL)
20643 len = (int)STRLEN(lv.ll_exp_name);
20644 name = deref_func_name(lv.ll_exp_name, &len);
20645 if (name == lv.ll_exp_name)
20646 name = NULL;
20648 else
20650 len = (int)(end - *pp);
20651 name = deref_func_name(*pp, &len);
20652 if (name == *pp)
20653 name = NULL;
20655 if (name != NULL)
20657 name = vim_strsave(name);
20658 *pp = end;
20659 goto theend;
20662 if (lv.ll_exp_name != NULL)
20664 len = (int)STRLEN(lv.ll_exp_name);
20665 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
20666 && STRNCMP(lv.ll_name, "s:", 2) == 0)
20668 /* When there was "s:" already or the name expanded to get a
20669 * leading "s:" then remove it. */
20670 lv.ll_name += 2;
20671 len -= 2;
20672 lead = 2;
20675 else
20677 if (lead == 2) /* skip over "s:" */
20678 lv.ll_name += 2;
20679 len = (int)(end - lv.ll_name);
20683 * Copy the function name to allocated memory.
20684 * Accept <SID>name() inside a script, translate into <SNR>123_name().
20685 * Accept <SNR>123_name() outside a script.
20687 if (skip)
20688 lead = 0; /* do nothing */
20689 else if (lead > 0)
20691 lead = 3;
20692 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
20693 || eval_fname_sid(*pp))
20695 /* It's "s:" or "<SID>" */
20696 if (current_SID <= 0)
20698 EMSG(_(e_usingsid));
20699 goto theend;
20701 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
20702 lead += (int)STRLEN(sid_buf);
20705 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
20707 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
20708 goto theend;
20710 name = alloc((unsigned)(len + lead + 1));
20711 if (name != NULL)
20713 if (lead > 0)
20715 name[0] = K_SPECIAL;
20716 name[1] = KS_EXTRA;
20717 name[2] = (int)KE_SNR;
20718 if (lead > 3) /* If it's "<SID>" */
20719 STRCPY(name + 3, sid_buf);
20721 mch_memmove(name + lead, lv.ll_name, (size_t)len);
20722 name[len + lead] = NUL;
20724 *pp = end;
20726 theend:
20727 clear_lval(&lv);
20728 return name;
20732 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
20733 * Return 2 if "p" starts with "s:".
20734 * Return 0 otherwise.
20736 static int
20737 eval_fname_script(p)
20738 char_u *p;
20740 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
20741 || STRNICMP(p + 1, "SNR>", 4) == 0))
20742 return 5;
20743 if (p[0] == 's' && p[1] == ':')
20744 return 2;
20745 return 0;
20749 * Return TRUE if "p" starts with "<SID>" or "s:".
20750 * Only works if eval_fname_script() returned non-zero for "p"!
20752 static int
20753 eval_fname_sid(p)
20754 char_u *p;
20756 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
20760 * List the head of the function: "name(arg1, arg2)".
20762 static void
20763 list_func_head(fp, indent)
20764 ufunc_T *fp;
20765 int indent;
20767 int j;
20769 msg_start();
20770 if (indent)
20771 MSG_PUTS(" ");
20772 MSG_PUTS("function ");
20773 if (fp->uf_name[0] == K_SPECIAL)
20775 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
20776 msg_puts(fp->uf_name + 3);
20778 else
20779 msg_puts(fp->uf_name);
20780 msg_putchar('(');
20781 for (j = 0; j < fp->uf_args.ga_len; ++j)
20783 if (j)
20784 MSG_PUTS(", ");
20785 msg_puts(FUNCARG(fp, j));
20787 if (fp->uf_varargs)
20789 if (j)
20790 MSG_PUTS(", ");
20791 MSG_PUTS("...");
20793 msg_putchar(')');
20794 msg_clr_eos();
20795 if (p_verbose > 0)
20796 last_set_msg(fp->uf_script_ID);
20800 * Find a function by name, return pointer to it in ufuncs.
20801 * Return NULL for unknown function.
20803 static ufunc_T *
20804 find_func(name)
20805 char_u *name;
20807 hashitem_T *hi;
20809 hi = hash_find(&func_hashtab, name);
20810 if (!HASHITEM_EMPTY(hi))
20811 return HI2UF(hi);
20812 return NULL;
20815 #if defined(EXITFREE) || defined(PROTO)
20816 void
20817 free_all_functions()
20819 hashitem_T *hi;
20821 /* Need to start all over every time, because func_free() may change the
20822 * hash table. */
20823 while (func_hashtab.ht_used > 0)
20824 for (hi = func_hashtab.ht_array; ; ++hi)
20825 if (!HASHITEM_EMPTY(hi))
20827 func_free(HI2UF(hi));
20828 break;
20831 #endif
20834 * Return TRUE if a function "name" exists.
20836 static int
20837 function_exists(name)
20838 char_u *name;
20840 char_u *nm = name;
20841 char_u *p;
20842 int n = FALSE;
20844 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
20845 nm = skipwhite(nm);
20847 /* Only accept "funcname", "funcname ", "funcname (..." and
20848 * "funcname(...", not "funcname!...". */
20849 if (p != NULL && (*nm == NUL || *nm == '('))
20851 if (builtin_function(p))
20852 n = (find_internal_func(p) >= 0);
20853 else
20854 n = (find_func(p) != NULL);
20856 vim_free(p);
20857 return n;
20861 * Return TRUE if "name" looks like a builtin function name: starts with a
20862 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
20864 static int
20865 builtin_function(name)
20866 char_u *name;
20868 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
20869 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
20872 #if defined(FEAT_PROFILE) || defined(PROTO)
20874 * Start profiling function "fp".
20876 static void
20877 func_do_profile(fp)
20878 ufunc_T *fp;
20880 fp->uf_tm_count = 0;
20881 profile_zero(&fp->uf_tm_self);
20882 profile_zero(&fp->uf_tm_total);
20883 if (fp->uf_tml_count == NULL)
20884 fp->uf_tml_count = (int *)alloc_clear((unsigned)
20885 (sizeof(int) * fp->uf_lines.ga_len));
20886 if (fp->uf_tml_total == NULL)
20887 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
20888 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20889 if (fp->uf_tml_self == NULL)
20890 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
20891 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20892 fp->uf_tml_idx = -1;
20893 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
20894 || fp->uf_tml_self == NULL)
20895 return; /* out of memory */
20897 fp->uf_profiling = TRUE;
20901 * Dump the profiling results for all functions in file "fd".
20903 void
20904 func_dump_profile(fd)
20905 FILE *fd;
20907 hashitem_T *hi;
20908 int todo;
20909 ufunc_T *fp;
20910 int i;
20911 ufunc_T **sorttab;
20912 int st_len = 0;
20914 todo = (int)func_hashtab.ht_used;
20915 if (todo == 0)
20916 return; /* nothing to dump */
20918 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
20920 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
20922 if (!HASHITEM_EMPTY(hi))
20924 --todo;
20925 fp = HI2UF(hi);
20926 if (fp->uf_profiling)
20928 if (sorttab != NULL)
20929 sorttab[st_len++] = fp;
20931 if (fp->uf_name[0] == K_SPECIAL)
20932 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
20933 else
20934 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
20935 if (fp->uf_tm_count == 1)
20936 fprintf(fd, "Called 1 time\n");
20937 else
20938 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
20939 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
20940 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
20941 fprintf(fd, "\n");
20942 fprintf(fd, "count total (s) self (s)\n");
20944 for (i = 0; i < fp->uf_lines.ga_len; ++i)
20946 if (FUNCLINE(fp, i) == NULL)
20947 continue;
20948 prof_func_line(fd, fp->uf_tml_count[i],
20949 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
20950 fprintf(fd, "%s\n", FUNCLINE(fp, i));
20952 fprintf(fd, "\n");
20957 if (sorttab != NULL && st_len > 0)
20959 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20960 prof_total_cmp);
20961 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
20962 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20963 prof_self_cmp);
20964 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
20967 vim_free(sorttab);
20970 static void
20971 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
20972 FILE *fd;
20973 ufunc_T **sorttab;
20974 int st_len;
20975 char *title;
20976 int prefer_self; /* when equal print only self time */
20978 int i;
20979 ufunc_T *fp;
20981 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
20982 fprintf(fd, "count total (s) self (s) function\n");
20983 for (i = 0; i < 20 && i < st_len; ++i)
20985 fp = sorttab[i];
20986 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
20987 prefer_self);
20988 if (fp->uf_name[0] == K_SPECIAL)
20989 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
20990 else
20991 fprintf(fd, " %s()\n", fp->uf_name);
20993 fprintf(fd, "\n");
20997 * Print the count and times for one function or function line.
20999 static void
21000 prof_func_line(fd, count, total, self, prefer_self)
21001 FILE *fd;
21002 int count;
21003 proftime_T *total;
21004 proftime_T *self;
21005 int prefer_self; /* when equal print only self time */
21007 if (count > 0)
21009 fprintf(fd, "%5d ", count);
21010 if (prefer_self && profile_equal(total, self))
21011 fprintf(fd, " ");
21012 else
21013 fprintf(fd, "%s ", profile_msg(total));
21014 if (!prefer_self && profile_equal(total, self))
21015 fprintf(fd, " ");
21016 else
21017 fprintf(fd, "%s ", profile_msg(self));
21019 else
21020 fprintf(fd, " ");
21024 * Compare function for total time sorting.
21026 static int
21027 #ifdef __BORLANDC__
21028 _RTLENTRYF
21029 #endif
21030 prof_total_cmp(s1, s2)
21031 const void *s1;
21032 const void *s2;
21034 ufunc_T *p1, *p2;
21036 p1 = *(ufunc_T **)s1;
21037 p2 = *(ufunc_T **)s2;
21038 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
21042 * Compare function for self time sorting.
21044 static int
21045 #ifdef __BORLANDC__
21046 _RTLENTRYF
21047 #endif
21048 prof_self_cmp(s1, s2)
21049 const void *s1;
21050 const void *s2;
21052 ufunc_T *p1, *p2;
21054 p1 = *(ufunc_T **)s1;
21055 p2 = *(ufunc_T **)s2;
21056 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
21059 #endif
21062 * If "name" has a package name try autoloading the script for it.
21063 * Return TRUE if a package was loaded.
21065 static int
21066 script_autoload(name, reload)
21067 char_u *name;
21068 int reload; /* load script again when already loaded */
21070 char_u *p;
21071 char_u *scriptname, *tofree;
21072 int ret = FALSE;
21073 int i;
21075 /* If there is no '#' after name[0] there is no package name. */
21076 p = vim_strchr(name, AUTOLOAD_CHAR);
21077 if (p == NULL || p == name)
21078 return FALSE;
21080 tofree = scriptname = autoload_name(name);
21082 /* Find the name in the list of previously loaded package names. Skip
21083 * "autoload/", it's always the same. */
21084 for (i = 0; i < ga_loaded.ga_len; ++i)
21085 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
21086 break;
21087 if (!reload && i < ga_loaded.ga_len)
21088 ret = FALSE; /* was loaded already */
21089 else
21091 /* Remember the name if it wasn't loaded already. */
21092 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
21094 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
21095 tofree = NULL;
21098 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
21099 if (source_runtime(scriptname, FALSE) == OK)
21100 ret = TRUE;
21103 vim_free(tofree);
21104 return ret;
21108 * Return the autoload script name for a function or variable name.
21109 * Returns NULL when out of memory.
21111 static char_u *
21112 autoload_name(name)
21113 char_u *name;
21115 char_u *p;
21116 char_u *scriptname;
21118 /* Get the script file name: replace '#' with '/', append ".vim". */
21119 scriptname = alloc((unsigned)(STRLEN(name) + 14));
21120 if (scriptname == NULL)
21121 return FALSE;
21122 STRCPY(scriptname, "autoload/");
21123 STRCAT(scriptname, name);
21124 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
21125 STRCAT(scriptname, ".vim");
21126 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
21127 *p = '/';
21128 return scriptname;
21131 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
21134 * Function given to ExpandGeneric() to obtain the list of user defined
21135 * function names.
21137 char_u *
21138 get_user_func_name(xp, idx)
21139 expand_T *xp;
21140 int idx;
21142 static long_u done;
21143 static hashitem_T *hi;
21144 ufunc_T *fp;
21146 if (idx == 0)
21148 done = 0;
21149 hi = func_hashtab.ht_array;
21151 if (done < func_hashtab.ht_used)
21153 if (done++ > 0)
21154 ++hi;
21155 while (HASHITEM_EMPTY(hi))
21156 ++hi;
21157 fp = HI2UF(hi);
21159 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
21160 return fp->uf_name; /* prevents overflow */
21162 cat_func_name(IObuff, fp);
21163 if (xp->xp_context != EXPAND_USER_FUNC)
21165 STRCAT(IObuff, "(");
21166 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
21167 STRCAT(IObuff, ")");
21169 return IObuff;
21171 return NULL;
21174 #endif /* FEAT_CMDL_COMPL */
21177 * Copy the function name of "fp" to buffer "buf".
21178 * "buf" must be able to hold the function name plus three bytes.
21179 * Takes care of script-local function names.
21181 static void
21182 cat_func_name(buf, fp)
21183 char_u *buf;
21184 ufunc_T *fp;
21186 if (fp->uf_name[0] == K_SPECIAL)
21188 STRCPY(buf, "<SNR>");
21189 STRCAT(buf, fp->uf_name + 3);
21191 else
21192 STRCPY(buf, fp->uf_name);
21196 * ":delfunction {name}"
21198 void
21199 ex_delfunction(eap)
21200 exarg_T *eap;
21202 ufunc_T *fp = NULL;
21203 char_u *p;
21204 char_u *name;
21205 funcdict_T fudi;
21207 p = eap->arg;
21208 name = trans_function_name(&p, eap->skip, 0, &fudi);
21209 vim_free(fudi.fd_newkey);
21210 if (name == NULL)
21212 if (fudi.fd_dict != NULL && !eap->skip)
21213 EMSG(_(e_funcref));
21214 return;
21216 if (!ends_excmd(*skipwhite(p)))
21218 vim_free(name);
21219 EMSG(_(e_trailing));
21220 return;
21222 eap->nextcmd = check_nextcmd(p);
21223 if (eap->nextcmd != NULL)
21224 *p = NUL;
21226 if (!eap->skip)
21227 fp = find_func(name);
21228 vim_free(name);
21230 if (!eap->skip)
21232 if (fp == NULL)
21234 EMSG2(_(e_nofunc), eap->arg);
21235 return;
21237 if (fp->uf_calls > 0)
21239 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
21240 return;
21243 if (fudi.fd_dict != NULL)
21245 /* Delete the dict item that refers to the function, it will
21246 * invoke func_unref() and possibly delete the function. */
21247 dictitem_remove(fudi.fd_dict, fudi.fd_di);
21249 else
21250 func_free(fp);
21255 * Free a function and remove it from the list of functions.
21257 static void
21258 func_free(fp)
21259 ufunc_T *fp;
21261 hashitem_T *hi;
21263 /* clear this function */
21264 ga_clear_strings(&(fp->uf_args));
21265 ga_clear_strings(&(fp->uf_lines));
21266 #ifdef FEAT_PROFILE
21267 vim_free(fp->uf_tml_count);
21268 vim_free(fp->uf_tml_total);
21269 vim_free(fp->uf_tml_self);
21270 #endif
21272 /* remove the function from the function hashtable */
21273 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
21274 if (HASHITEM_EMPTY(hi))
21275 EMSG2(_(e_intern2), "func_free()");
21276 else
21277 hash_remove(&func_hashtab, hi);
21279 vim_free(fp);
21283 * Unreference a Function: decrement the reference count and free it when it
21284 * becomes zero. Only for numbered functions.
21286 static void
21287 func_unref(name)
21288 char_u *name;
21290 ufunc_T *fp;
21292 if (name != NULL && isdigit(*name))
21294 fp = find_func(name);
21295 if (fp == NULL)
21296 EMSG2(_(e_intern2), "func_unref()");
21297 else if (--fp->uf_refcount <= 0)
21299 /* Only delete it when it's not being used. Otherwise it's done
21300 * when "uf_calls" becomes zero. */
21301 if (fp->uf_calls == 0)
21302 func_free(fp);
21308 * Count a reference to a Function.
21310 static void
21311 func_ref(name)
21312 char_u *name;
21314 ufunc_T *fp;
21316 if (name != NULL && isdigit(*name))
21318 fp = find_func(name);
21319 if (fp == NULL)
21320 EMSG2(_(e_intern2), "func_ref()");
21321 else
21322 ++fp->uf_refcount;
21327 * Call a user function.
21329 static void
21330 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
21331 ufunc_T *fp; /* pointer to function */
21332 int argcount; /* nr of args */
21333 typval_T *argvars; /* arguments */
21334 typval_T *rettv; /* return value */
21335 linenr_T firstline; /* first line of range */
21336 linenr_T lastline; /* last line of range */
21337 dict_T *selfdict; /* Dictionary for "self" */
21339 char_u *save_sourcing_name;
21340 linenr_T save_sourcing_lnum;
21341 scid_T save_current_SID;
21342 funccall_T *fc;
21343 int save_did_emsg;
21344 static int depth = 0;
21345 dictitem_T *v;
21346 int fixvar_idx = 0; /* index in fixvar[] */
21347 int i;
21348 int ai;
21349 char_u numbuf[NUMBUFLEN];
21350 char_u *name;
21351 #ifdef FEAT_PROFILE
21352 proftime_T wait_start;
21353 proftime_T call_start;
21354 #endif
21356 /* If depth of calling is getting too high, don't execute the function */
21357 if (depth >= p_mfd)
21359 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
21360 rettv->v_type = VAR_NUMBER;
21361 rettv->vval.v_number = -1;
21362 return;
21364 ++depth;
21366 line_breakcheck(); /* check for CTRL-C hit */
21368 fc = (funccall_T *)alloc(sizeof(funccall_T));
21369 fc->caller = current_funccal;
21370 current_funccal = fc;
21371 fc->func = fp;
21372 fc->rettv = rettv;
21373 rettv->vval.v_number = 0;
21374 fc->linenr = 0;
21375 fc->returned = FALSE;
21376 fc->level = ex_nesting_level;
21377 /* Check if this function has a breakpoint. */
21378 fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
21379 fc->dbg_tick = debug_tick;
21382 * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables
21383 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
21384 * each argument variable and saves a lot of time.
21387 * Init l: variables.
21389 init_var_dict(&fc->l_vars, &fc->l_vars_var);
21390 if (selfdict != NULL)
21392 /* Set l:self to "selfdict". Use "name" to avoid a warning from
21393 * some compiler that checks the destination size. */
21394 v = &fc->fixvar[fixvar_idx++].var;
21395 name = v->di_key;
21396 STRCPY(name, "self");
21397 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
21398 hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
21399 v->di_tv.v_type = VAR_DICT;
21400 v->di_tv.v_lock = 0;
21401 v->di_tv.vval.v_dict = selfdict;
21402 ++selfdict->dv_refcount;
21406 * Init a: variables.
21407 * Set a:0 to "argcount".
21408 * Set a:000 to a list with room for the "..." arguments.
21410 init_var_dict(&fc->l_avars, &fc->l_avars_var);
21411 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0",
21412 (varnumber_T)(argcount - fp->uf_args.ga_len));
21413 /* Use "name" to avoid a warning from some compiler that checks the
21414 * destination size. */
21415 v = &fc->fixvar[fixvar_idx++].var;
21416 name = v->di_key;
21417 STRCPY(name, "000");
21418 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21419 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21420 v->di_tv.v_type = VAR_LIST;
21421 v->di_tv.v_lock = VAR_FIXED;
21422 v->di_tv.vval.v_list = &fc->l_varlist;
21423 vim_memset(&fc->l_varlist, 0, sizeof(list_T));
21424 fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT;
21425 fc->l_varlist.lv_lock = VAR_FIXED;
21428 * Set a:firstline to "firstline" and a:lastline to "lastline".
21429 * Set a:name to named arguments.
21430 * Set a:N to the "..." arguments.
21432 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline",
21433 (varnumber_T)firstline);
21434 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline",
21435 (varnumber_T)lastline);
21436 for (i = 0; i < argcount; ++i)
21438 ai = i - fp->uf_args.ga_len;
21439 if (ai < 0)
21440 /* named argument a:name */
21441 name = FUNCARG(fp, i);
21442 else
21444 /* "..." argument a:1, a:2, etc. */
21445 sprintf((char *)numbuf, "%d", ai + 1);
21446 name = numbuf;
21448 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
21450 v = &fc->fixvar[fixvar_idx++].var;
21451 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21453 else
21455 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
21456 + STRLEN(name)));
21457 if (v == NULL)
21458 break;
21459 v->di_flags = DI_FLAGS_RO;
21461 STRCPY(v->di_key, name);
21462 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21464 /* Note: the values are copied directly to avoid alloc/free.
21465 * "argvars" must have VAR_FIXED for v_lock. */
21466 v->di_tv = argvars[i];
21467 v->di_tv.v_lock = VAR_FIXED;
21469 if (ai >= 0 && ai < MAX_FUNC_ARGS)
21471 list_append(&fc->l_varlist, &fc->l_listitems[ai]);
21472 fc->l_listitems[ai].li_tv = argvars[i];
21473 fc->l_listitems[ai].li_tv.v_lock = VAR_FIXED;
21477 /* Don't redraw while executing the function. */
21478 ++RedrawingDisabled;
21479 save_sourcing_name = sourcing_name;
21480 save_sourcing_lnum = sourcing_lnum;
21481 sourcing_lnum = 1;
21482 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
21483 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
21484 if (sourcing_name != NULL)
21486 if (save_sourcing_name != NULL
21487 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
21488 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
21489 else
21490 STRCPY(sourcing_name, "function ");
21491 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
21493 if (p_verbose >= 12)
21495 ++no_wait_return;
21496 verbose_enter_scroll();
21498 smsg((char_u *)_("calling %s"), sourcing_name);
21499 if (p_verbose >= 14)
21501 char_u buf[MSG_BUF_LEN];
21502 char_u numbuf2[NUMBUFLEN];
21503 char_u *tofree;
21504 char_u *s;
21506 msg_puts((char_u *)"(");
21507 for (i = 0; i < argcount; ++i)
21509 if (i > 0)
21510 msg_puts((char_u *)", ");
21511 if (argvars[i].v_type == VAR_NUMBER)
21512 msg_outnum((long)argvars[i].vval.v_number);
21513 else
21515 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
21516 if (s != NULL)
21518 trunc_string(s, buf, MSG_BUF_CLEN);
21519 msg_puts(buf);
21520 vim_free(tofree);
21524 msg_puts((char_u *)")");
21526 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21528 verbose_leave_scroll();
21529 --no_wait_return;
21532 #ifdef FEAT_PROFILE
21533 if (do_profiling == PROF_YES)
21535 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
21536 func_do_profile(fp);
21537 if (fp->uf_profiling
21538 || (fc->caller != NULL && fc->caller->func->uf_profiling))
21540 ++fp->uf_tm_count;
21541 profile_start(&call_start);
21542 profile_zero(&fp->uf_tm_children);
21544 script_prof_save(&wait_start);
21546 #endif
21548 save_current_SID = current_SID;
21549 current_SID = fp->uf_script_ID;
21550 save_did_emsg = did_emsg;
21551 did_emsg = FALSE;
21553 /* call do_cmdline() to execute the lines */
21554 do_cmdline(NULL, get_func_line, (void *)fc,
21555 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
21557 --RedrawingDisabled;
21559 /* when the function was aborted because of an error, return -1 */
21560 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
21562 clear_tv(rettv);
21563 rettv->v_type = VAR_NUMBER;
21564 rettv->vval.v_number = -1;
21567 #ifdef FEAT_PROFILE
21568 if (do_profiling == PROF_YES && (fp->uf_profiling
21569 || (fc->caller != NULL && fc->caller->func->uf_profiling)))
21571 profile_end(&call_start);
21572 profile_sub_wait(&wait_start, &call_start);
21573 profile_add(&fp->uf_tm_total, &call_start);
21574 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
21575 if (fc->caller != NULL && fc->caller->func->uf_profiling)
21577 profile_add(&fc->caller->func->uf_tm_children, &call_start);
21578 profile_add(&fc->caller->func->uf_tml_children, &call_start);
21581 #endif
21583 /* when being verbose, mention the return value */
21584 if (p_verbose >= 12)
21586 ++no_wait_return;
21587 verbose_enter_scroll();
21589 if (aborting())
21590 smsg((char_u *)_("%s aborted"), sourcing_name);
21591 else if (fc->rettv->v_type == VAR_NUMBER)
21592 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
21593 (long)fc->rettv->vval.v_number);
21594 else
21596 char_u buf[MSG_BUF_LEN];
21597 char_u numbuf2[NUMBUFLEN];
21598 char_u *tofree;
21599 char_u *s;
21601 /* The value may be very long. Skip the middle part, so that we
21602 * have some idea how it starts and ends. smsg() would always
21603 * truncate it at the end. */
21604 s = tv2string(fc->rettv, &tofree, numbuf2, 0);
21605 if (s != NULL)
21607 trunc_string(s, buf, MSG_BUF_CLEN);
21608 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
21609 vim_free(tofree);
21612 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21614 verbose_leave_scroll();
21615 --no_wait_return;
21618 vim_free(sourcing_name);
21619 sourcing_name = save_sourcing_name;
21620 sourcing_lnum = save_sourcing_lnum;
21621 current_SID = save_current_SID;
21622 #ifdef FEAT_PROFILE
21623 if (do_profiling == PROF_YES)
21624 script_prof_restore(&wait_start);
21625 #endif
21627 if (p_verbose >= 12 && sourcing_name != NULL)
21629 ++no_wait_return;
21630 verbose_enter_scroll();
21632 smsg((char_u *)_("continuing in %s"), sourcing_name);
21633 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21635 verbose_leave_scroll();
21636 --no_wait_return;
21639 did_emsg |= save_did_emsg;
21640 current_funccal = fc->caller;
21641 --depth;
21643 /* if the a:000 list and the a: dict are not referenced we can free the
21644 * funccall_T and what's in it. */
21645 if (fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
21646 && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
21647 && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT)
21649 free_funccal(fc, FALSE);
21651 else
21653 hashitem_T *hi;
21654 listitem_T *li;
21655 int todo;
21657 /* "fc" is still in use. This can happen when returning "a:000" or
21658 * assigning "l:" to a global variable.
21659 * Link "fc" in the list for garbage collection later. */
21660 fc->caller = previous_funccal;
21661 previous_funccal = fc;
21663 /* Make a copy of the a: variables, since we didn't do that above. */
21664 todo = (int)fc->l_avars.dv_hashtab.ht_used;
21665 for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi)
21667 if (!HASHITEM_EMPTY(hi))
21669 --todo;
21670 v = HI2DI(hi);
21671 copy_tv(&v->di_tv, &v->di_tv);
21675 /* Make a copy of the a:000 items, since we didn't do that above. */
21676 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21677 copy_tv(&li->li_tv, &li->li_tv);
21682 * Return TRUE if items in "fc" do not have "copyID". That means they are not
21683 * referenced from anywyere.
21685 static int
21686 can_free_funccal(fc, copyID)
21687 funccall_T *fc;
21688 int copyID;
21690 return (fc->l_varlist.lv_copyID != copyID
21691 && fc->l_vars.dv_copyID != copyID
21692 && fc->l_avars.dv_copyID != copyID);
21696 * Free "fc" and what it contains.
21698 static void
21699 free_funccal(fc, free_val)
21700 funccall_T *fc;
21701 int free_val; /* a: vars were allocated */
21703 listitem_T *li;
21705 /* The a: variables typevals may not have been allocated, only free the
21706 * allocated variables. */
21707 vars_clear_ext(&fc->l_avars.dv_hashtab, free_val);
21709 /* free all l: variables */
21710 vars_clear(&fc->l_vars.dv_hashtab);
21712 /* Free the a:000 variables if they were allocated. */
21713 if (free_val)
21714 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21715 clear_tv(&li->li_tv);
21717 vim_free(fc);
21721 * Add a number variable "name" to dict "dp" with value "nr".
21723 static void
21724 add_nr_var(dp, v, name, nr)
21725 dict_T *dp;
21726 dictitem_T *v;
21727 char *name;
21728 varnumber_T nr;
21730 STRCPY(v->di_key, name);
21731 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21732 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
21733 v->di_tv.v_type = VAR_NUMBER;
21734 v->di_tv.v_lock = VAR_FIXED;
21735 v->di_tv.vval.v_number = nr;
21739 * ":return [expr]"
21741 void
21742 ex_return(eap)
21743 exarg_T *eap;
21745 char_u *arg = eap->arg;
21746 typval_T rettv;
21747 int returning = FALSE;
21749 if (current_funccal == NULL)
21751 EMSG(_("E133: :return not inside a function"));
21752 return;
21755 if (eap->skip)
21756 ++emsg_skip;
21758 eap->nextcmd = NULL;
21759 if ((*arg != NUL && *arg != '|' && *arg != '\n')
21760 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
21762 if (!eap->skip)
21763 returning = do_return(eap, FALSE, TRUE, &rettv);
21764 else
21765 clear_tv(&rettv);
21767 /* It's safer to return also on error. */
21768 else if (!eap->skip)
21771 * Return unless the expression evaluation has been cancelled due to an
21772 * aborting error, an interrupt, or an exception.
21774 if (!aborting())
21775 returning = do_return(eap, FALSE, TRUE, NULL);
21778 /* When skipping or the return gets pending, advance to the next command
21779 * in this line (!returning). Otherwise, ignore the rest of the line.
21780 * Following lines will be ignored by get_func_line(). */
21781 if (returning)
21782 eap->nextcmd = NULL;
21783 else if (eap->nextcmd == NULL) /* no argument */
21784 eap->nextcmd = check_nextcmd(arg);
21786 if (eap->skip)
21787 --emsg_skip;
21791 * Return from a function. Possibly makes the return pending. Also called
21792 * for a pending return at the ":endtry" or after returning from an extra
21793 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
21794 * when called due to a ":return" command. "rettv" may point to a typval_T
21795 * with the return rettv. Returns TRUE when the return can be carried out,
21796 * FALSE when the return gets pending.
21799 do_return(eap, reanimate, is_cmd, rettv)
21800 exarg_T *eap;
21801 int reanimate;
21802 int is_cmd;
21803 void *rettv;
21805 int idx;
21806 struct condstack *cstack = eap->cstack;
21808 if (reanimate)
21809 /* Undo the return. */
21810 current_funccal->returned = FALSE;
21813 * Cleanup (and inactivate) conditionals, but stop when a try conditional
21814 * not in its finally clause (which then is to be executed next) is found.
21815 * In this case, make the ":return" pending for execution at the ":endtry".
21816 * Otherwise, return normally.
21818 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
21819 if (idx >= 0)
21821 cstack->cs_pending[idx] = CSTP_RETURN;
21823 if (!is_cmd && !reanimate)
21824 /* A pending return again gets pending. "rettv" points to an
21825 * allocated variable with the rettv of the original ":return"'s
21826 * argument if present or is NULL else. */
21827 cstack->cs_rettv[idx] = rettv;
21828 else
21830 /* When undoing a return in order to make it pending, get the stored
21831 * return rettv. */
21832 if (reanimate)
21833 rettv = current_funccal->rettv;
21835 if (rettv != NULL)
21837 /* Store the value of the pending return. */
21838 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
21839 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
21840 else
21841 EMSG(_(e_outofmem));
21843 else
21844 cstack->cs_rettv[idx] = NULL;
21846 if (reanimate)
21848 /* The pending return value could be overwritten by a ":return"
21849 * without argument in a finally clause; reset the default
21850 * return value. */
21851 current_funccal->rettv->v_type = VAR_NUMBER;
21852 current_funccal->rettv->vval.v_number = 0;
21855 report_make_pending(CSTP_RETURN, rettv);
21857 else
21859 current_funccal->returned = TRUE;
21861 /* If the return is carried out now, store the return value. For
21862 * a return immediately after reanimation, the value is already
21863 * there. */
21864 if (!reanimate && rettv != NULL)
21866 clear_tv(current_funccal->rettv);
21867 *current_funccal->rettv = *(typval_T *)rettv;
21868 if (!is_cmd)
21869 vim_free(rettv);
21873 return idx < 0;
21877 * Free the variable with a pending return value.
21879 void
21880 discard_pending_return(rettv)
21881 void *rettv;
21883 free_tv((typval_T *)rettv);
21887 * Generate a return command for producing the value of "rettv". The result
21888 * is an allocated string. Used by report_pending() for verbose messages.
21890 char_u *
21891 get_return_cmd(rettv)
21892 void *rettv;
21894 char_u *s = NULL;
21895 char_u *tofree = NULL;
21896 char_u numbuf[NUMBUFLEN];
21898 if (rettv != NULL)
21899 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
21900 if (s == NULL)
21901 s = (char_u *)"";
21903 STRCPY(IObuff, ":return ");
21904 STRNCPY(IObuff + 8, s, IOSIZE - 8);
21905 if (STRLEN(s) + 8 >= IOSIZE)
21906 STRCPY(IObuff + IOSIZE - 4, "...");
21907 vim_free(tofree);
21908 return vim_strsave(IObuff);
21912 * Get next function line.
21913 * Called by do_cmdline() to get the next line.
21914 * Returns allocated string, or NULL for end of function.
21916 /* ARGSUSED */
21917 char_u *
21918 get_func_line(c, cookie, indent)
21919 int c; /* not used */
21920 void *cookie;
21921 int indent; /* not used */
21923 funccall_T *fcp = (funccall_T *)cookie;
21924 ufunc_T *fp = fcp->func;
21925 char_u *retval;
21926 garray_T *gap; /* growarray with function lines */
21928 /* If breakpoints have been added/deleted need to check for it. */
21929 if (fcp->dbg_tick != debug_tick)
21931 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21932 sourcing_lnum);
21933 fcp->dbg_tick = debug_tick;
21935 #ifdef FEAT_PROFILE
21936 if (do_profiling == PROF_YES)
21937 func_line_end(cookie);
21938 #endif
21940 gap = &fp->uf_lines;
21941 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21942 || fcp->returned)
21943 retval = NULL;
21944 else
21946 /* Skip NULL lines (continuation lines). */
21947 while (fcp->linenr < gap->ga_len
21948 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
21949 ++fcp->linenr;
21950 if (fcp->linenr >= gap->ga_len)
21951 retval = NULL;
21952 else
21954 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
21955 sourcing_lnum = fcp->linenr;
21956 #ifdef FEAT_PROFILE
21957 if (do_profiling == PROF_YES)
21958 func_line_start(cookie);
21959 #endif
21963 /* Did we encounter a breakpoint? */
21964 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
21966 dbg_breakpoint(fp->uf_name, sourcing_lnum);
21967 /* Find next breakpoint. */
21968 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21969 sourcing_lnum);
21970 fcp->dbg_tick = debug_tick;
21973 return retval;
21976 #if defined(FEAT_PROFILE) || defined(PROTO)
21978 * Called when starting to read a function line.
21979 * "sourcing_lnum" must be correct!
21980 * When skipping lines it may not actually be executed, but we won't find out
21981 * until later and we need to store the time now.
21983 void
21984 func_line_start(cookie)
21985 void *cookie;
21987 funccall_T *fcp = (funccall_T *)cookie;
21988 ufunc_T *fp = fcp->func;
21990 if (fp->uf_profiling && sourcing_lnum >= 1
21991 && sourcing_lnum <= fp->uf_lines.ga_len)
21993 fp->uf_tml_idx = sourcing_lnum - 1;
21994 /* Skip continuation lines. */
21995 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
21996 --fp->uf_tml_idx;
21997 fp->uf_tml_execed = FALSE;
21998 profile_start(&fp->uf_tml_start);
21999 profile_zero(&fp->uf_tml_children);
22000 profile_get_wait(&fp->uf_tml_wait);
22005 * Called when actually executing a function line.
22007 void
22008 func_line_exec(cookie)
22009 void *cookie;
22011 funccall_T *fcp = (funccall_T *)cookie;
22012 ufunc_T *fp = fcp->func;
22014 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
22015 fp->uf_tml_execed = TRUE;
22019 * Called when done with a function line.
22021 void
22022 func_line_end(cookie)
22023 void *cookie;
22025 funccall_T *fcp = (funccall_T *)cookie;
22026 ufunc_T *fp = fcp->func;
22028 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
22030 if (fp->uf_tml_execed)
22032 ++fp->uf_tml_count[fp->uf_tml_idx];
22033 profile_end(&fp->uf_tml_start);
22034 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
22035 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
22036 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
22037 &fp->uf_tml_children);
22039 fp->uf_tml_idx = -1;
22042 #endif
22045 * Return TRUE if the currently active function should be ended, because a
22046 * return was encountered or an error occurred. Used inside a ":while".
22049 func_has_ended(cookie)
22050 void *cookie;
22052 funccall_T *fcp = (funccall_T *)cookie;
22054 /* Ignore the "abort" flag if the abortion behavior has been changed due to
22055 * an error inside a try conditional. */
22056 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
22057 || fcp->returned);
22061 * return TRUE if cookie indicates a function which "abort"s on errors.
22064 func_has_abort(cookie)
22065 void *cookie;
22067 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
22070 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
22071 typedef enum
22073 VAR_FLAVOUR_DEFAULT, /* doesn't start with uppercase */
22074 VAR_FLAVOUR_SESSION, /* starts with uppercase, some lower */
22075 VAR_FLAVOUR_VIMINFO /* all uppercase */
22076 } var_flavour_T;
22078 static var_flavour_T var_flavour __ARGS((char_u *varname));
22080 static var_flavour_T
22081 var_flavour(varname)
22082 char_u *varname;
22084 char_u *p = varname;
22086 if (ASCII_ISUPPER(*p))
22088 while (*(++p))
22089 if (ASCII_ISLOWER(*p))
22090 return VAR_FLAVOUR_SESSION;
22091 return VAR_FLAVOUR_VIMINFO;
22093 else
22094 return VAR_FLAVOUR_DEFAULT;
22096 #endif
22098 #if defined(FEAT_VIMINFO) || defined(PROTO)
22100 * Restore global vars that start with a capital from the viminfo file
22103 read_viminfo_varlist(virp, writing)
22104 vir_T *virp;
22105 int writing;
22107 char_u *tab;
22108 int type = VAR_NUMBER;
22109 typval_T tv;
22111 if (!writing && (find_viminfo_parameter('!') != NULL))
22113 tab = vim_strchr(virp->vir_line + 1, '\t');
22114 if (tab != NULL)
22116 *tab++ = '\0'; /* isolate the variable name */
22117 if (*tab == 'S') /* string var */
22118 type = VAR_STRING;
22119 #ifdef FEAT_FLOAT
22120 else if (*tab == 'F')
22121 type = VAR_FLOAT;
22122 #endif
22124 tab = vim_strchr(tab, '\t');
22125 if (tab != NULL)
22127 tv.v_type = type;
22128 if (type == VAR_STRING)
22129 tv.vval.v_string = viminfo_readstring(virp,
22130 (int)(tab - virp->vir_line + 1), TRUE);
22131 #ifdef FEAT_FLOAT
22132 else if (type == VAR_FLOAT)
22133 (void)string2float(tab + 1, &tv.vval.v_float);
22134 #endif
22135 else
22136 tv.vval.v_number = atol((char *)tab + 1);
22137 set_var(virp->vir_line + 1, &tv, FALSE);
22138 if (type == VAR_STRING)
22139 vim_free(tv.vval.v_string);
22144 return viminfo_readline(virp);
22148 * Write global vars that start with a capital to the viminfo file
22150 void
22151 write_viminfo_varlist(fp)
22152 FILE *fp;
22154 hashitem_T *hi;
22155 dictitem_T *this_var;
22156 int todo;
22157 char *s;
22158 char_u *p;
22159 char_u *tofree;
22160 char_u numbuf[NUMBUFLEN];
22162 if (find_viminfo_parameter('!') == NULL)
22163 return;
22165 fprintf(fp, _("\n# global variables:\n"));
22167 todo = (int)globvarht.ht_used;
22168 for (hi = globvarht.ht_array; todo > 0; ++hi)
22170 if (!HASHITEM_EMPTY(hi))
22172 --todo;
22173 this_var = HI2DI(hi);
22174 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
22176 switch (this_var->di_tv.v_type)
22178 case VAR_STRING: s = "STR"; break;
22179 case VAR_NUMBER: s = "NUM"; break;
22180 #ifdef FEAT_FLOAT
22181 case VAR_FLOAT: s = "FLO"; break;
22182 #endif
22183 default: continue;
22185 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
22186 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
22187 if (p != NULL)
22188 viminfo_writestring(fp, p);
22189 vim_free(tofree);
22194 #endif
22196 #if defined(FEAT_SESSION) || defined(PROTO)
22198 store_session_globals(fd)
22199 FILE *fd;
22201 hashitem_T *hi;
22202 dictitem_T *this_var;
22203 int todo;
22204 char_u *p, *t;
22206 todo = (int)globvarht.ht_used;
22207 for (hi = globvarht.ht_array; todo > 0; ++hi)
22209 if (!HASHITEM_EMPTY(hi))
22211 --todo;
22212 this_var = HI2DI(hi);
22213 if ((this_var->di_tv.v_type == VAR_NUMBER
22214 || this_var->di_tv.v_type == VAR_STRING)
22215 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22217 /* Escape special characters with a backslash. Turn a LF and
22218 * CR into \n and \r. */
22219 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
22220 (char_u *)"\\\"\n\r");
22221 if (p == NULL) /* out of memory */
22222 break;
22223 for (t = p; *t != NUL; ++t)
22224 if (*t == '\n')
22225 *t = 'n';
22226 else if (*t == '\r')
22227 *t = 'r';
22228 if ((fprintf(fd, "let %s = %c%s%c",
22229 this_var->di_key,
22230 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22231 : ' ',
22233 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22234 : ' ') < 0)
22235 || put_eol(fd) == FAIL)
22237 vim_free(p);
22238 return FAIL;
22240 vim_free(p);
22242 #ifdef FEAT_FLOAT
22243 else if (this_var->di_tv.v_type == VAR_FLOAT
22244 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22246 float_T f = this_var->di_tv.vval.v_float;
22247 int sign = ' ';
22249 if (f < 0)
22251 f = -f;
22252 sign = '-';
22254 if ((fprintf(fd, "let %s = %c&%f",
22255 this_var->di_key, sign, f) < 0)
22256 || put_eol(fd) == FAIL)
22257 return FAIL;
22259 #endif
22262 return OK;
22264 #endif
22267 * Display script name where an item was last set.
22268 * Should only be invoked when 'verbose' is non-zero.
22270 void
22271 last_set_msg(scriptID)
22272 scid_T scriptID;
22274 char_u *p;
22276 if (scriptID != 0)
22278 p = home_replace_save(NULL, get_scriptname(scriptID));
22279 if (p != NULL)
22281 verbose_enter();
22282 MSG_PUTS(_("\n\tLast set from "));
22283 MSG_PUTS(p);
22284 vim_free(p);
22285 verbose_leave();
22291 * List v:oldfiles in a nice way.
22293 /*ARGSUSED*/
22294 void
22295 ex_oldfiles(eap)
22296 exarg_T *eap;
22298 list_T *l = vimvars[VV_OLDFILES].vv_list;
22299 listitem_T *li;
22300 int nr = 0;
22302 if (l == NULL)
22303 msg((char_u *)_("No old files"));
22304 else
22306 msg_start();
22307 msg_scroll = TRUE;
22308 for (li = l->lv_first; li != NULL && !got_int; li = li->li_next)
22310 msg_outnum((long)++nr);
22311 MSG_PUTS(": ");
22312 msg_outtrans(get_tv_string(&li->li_tv));
22313 msg_putchar('\n');
22314 out_flush(); /* output one line at a time */
22315 ui_breakcheck();
22317 /* Assume "got_int" was set to truncate the listing. */
22318 got_int = FALSE;
22320 #ifdef FEAT_BROWSE_CMD
22321 if (cmdmod.browse)
22323 quit_more = FALSE;
22324 nr = prompt_for_number(FALSE);
22325 msg_starthere();
22326 if (nr > 0)
22328 char_u *p = list_find_str(get_vim_var_list(VV_OLDFILES),
22329 (long)nr);
22331 if (p != NULL)
22333 p = expand_env_save(p);
22334 eap->arg = p;
22335 eap->cmdidx = CMD_edit;
22336 cmdmod.browse = FALSE;
22337 do_exedit(eap, NULL);
22338 vim_free(p);
22342 #endif
22346 #endif /* FEAT_EVAL */
22349 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
22351 #ifdef WIN3264
22353 * Functions for ":8" filename modifier: get 8.3 version of a filename.
22355 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22356 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
22357 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22360 * Get the short path (8.3) for the filename in "fnamep".
22361 * Only works for a valid file name.
22362 * When the path gets longer "fnamep" is changed and the allocated buffer
22363 * is put in "bufp".
22364 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
22365 * Returns OK on success, FAIL on failure.
22367 static int
22368 get_short_pathname(fnamep, bufp, fnamelen)
22369 char_u **fnamep;
22370 char_u **bufp;
22371 int *fnamelen;
22373 int l, len;
22374 char_u *newbuf;
22376 len = *fnamelen;
22377 l = GetShortPathName(*fnamep, *fnamep, len);
22378 if (l > len - 1)
22380 /* If that doesn't work (not enough space), then save the string
22381 * and try again with a new buffer big enough. */
22382 newbuf = vim_strnsave(*fnamep, l);
22383 if (newbuf == NULL)
22384 return FAIL;
22386 vim_free(*bufp);
22387 *fnamep = *bufp = newbuf;
22389 /* Really should always succeed, as the buffer is big enough. */
22390 l = GetShortPathName(*fnamep, *fnamep, l+1);
22393 *fnamelen = l;
22394 return OK;
22398 * Get the short path (8.3) for the filename in "fname". The converted
22399 * path is returned in "bufp".
22401 * Some of the directories specified in "fname" may not exist. This function
22402 * will shorten the existing directories at the beginning of the path and then
22403 * append the remaining non-existing path.
22405 * fname - Pointer to the filename to shorten. On return, contains the
22406 * pointer to the shortened pathname
22407 * bufp - Pointer to an allocated buffer for the filename.
22408 * fnamelen - Length of the filename pointed to by fname
22410 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
22412 static int
22413 shortpath_for_invalid_fname(fname, bufp, fnamelen)
22414 char_u **fname;
22415 char_u **bufp;
22416 int *fnamelen;
22418 char_u *short_fname, *save_fname, *pbuf_unused;
22419 char_u *endp, *save_endp;
22420 char_u ch;
22421 int old_len, len;
22422 int new_len, sfx_len;
22423 int retval = OK;
22425 /* Make a copy */
22426 old_len = *fnamelen;
22427 save_fname = vim_strnsave(*fname, old_len);
22428 pbuf_unused = NULL;
22429 short_fname = NULL;
22431 endp = save_fname + old_len - 1; /* Find the end of the copy */
22432 save_endp = endp;
22435 * Try shortening the supplied path till it succeeds by removing one
22436 * directory at a time from the tail of the path.
22438 len = 0;
22439 for (;;)
22441 /* go back one path-separator */
22442 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
22443 --endp;
22444 if (endp <= save_fname)
22445 break; /* processed the complete path */
22448 * Replace the path separator with a NUL and try to shorten the
22449 * resulting path.
22451 ch = *endp;
22452 *endp = 0;
22453 short_fname = save_fname;
22454 len = (int)STRLEN(short_fname) + 1;
22455 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
22457 retval = FAIL;
22458 goto theend;
22460 *endp = ch; /* preserve the string */
22462 if (len > 0)
22463 break; /* successfully shortened the path */
22465 /* failed to shorten the path. Skip the path separator */
22466 --endp;
22469 if (len > 0)
22472 * Succeeded in shortening the path. Now concatenate the shortened
22473 * path with the remaining path at the tail.
22476 /* Compute the length of the new path. */
22477 sfx_len = (int)(save_endp - endp) + 1;
22478 new_len = len + sfx_len;
22480 *fnamelen = new_len;
22481 vim_free(*bufp);
22482 if (new_len > old_len)
22484 /* There is not enough space in the currently allocated string,
22485 * copy it to a buffer big enough. */
22486 *fname = *bufp = vim_strnsave(short_fname, new_len);
22487 if (*fname == NULL)
22489 retval = FAIL;
22490 goto theend;
22493 else
22495 /* Transfer short_fname to the main buffer (it's big enough),
22496 * unless get_short_pathname() did its work in-place. */
22497 *fname = *bufp = save_fname;
22498 if (short_fname != save_fname)
22499 vim_strncpy(save_fname, short_fname, len);
22500 save_fname = NULL;
22503 /* concat the not-shortened part of the path */
22504 vim_strncpy(*fname + len, endp, sfx_len);
22505 (*fname)[new_len] = NUL;
22508 theend:
22509 vim_free(pbuf_unused);
22510 vim_free(save_fname);
22512 return retval;
22516 * Get a pathname for a partial path.
22517 * Returns OK for success, FAIL for failure.
22519 static int
22520 shortpath_for_partial(fnamep, bufp, fnamelen)
22521 char_u **fnamep;
22522 char_u **bufp;
22523 int *fnamelen;
22525 int sepcount, len, tflen;
22526 char_u *p;
22527 char_u *pbuf, *tfname;
22528 int hasTilde;
22530 /* Count up the path separators from the RHS.. so we know which part
22531 * of the path to return. */
22532 sepcount = 0;
22533 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
22534 if (vim_ispathsep(*p))
22535 ++sepcount;
22537 /* Need full path first (use expand_env() to remove a "~/") */
22538 hasTilde = (**fnamep == '~');
22539 if (hasTilde)
22540 pbuf = tfname = expand_env_save(*fnamep);
22541 else
22542 pbuf = tfname = FullName_save(*fnamep, FALSE);
22544 len = tflen = (int)STRLEN(tfname);
22546 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
22547 return FAIL;
22549 if (len == 0)
22551 /* Don't have a valid filename, so shorten the rest of the
22552 * path if we can. This CAN give us invalid 8.3 filenames, but
22553 * there's not a lot of point in guessing what it might be.
22555 len = tflen;
22556 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
22557 return FAIL;
22560 /* Count the paths backward to find the beginning of the desired string. */
22561 for (p = tfname + len - 1; p >= tfname; --p)
22563 #ifdef FEAT_MBYTE
22564 if (has_mbyte)
22565 p -= mb_head_off(tfname, p);
22566 #endif
22567 if (vim_ispathsep(*p))
22569 if (sepcount == 0 || (hasTilde && sepcount == 1))
22570 break;
22571 else
22572 sepcount --;
22575 if (hasTilde)
22577 --p;
22578 if (p >= tfname)
22579 *p = '~';
22580 else
22581 return FAIL;
22583 else
22584 ++p;
22586 /* Copy in the string - p indexes into tfname - allocated at pbuf */
22587 vim_free(*bufp);
22588 *fnamelen = (int)STRLEN(p);
22589 *bufp = pbuf;
22590 *fnamep = p;
22592 return OK;
22594 #endif /* WIN3264 */
22597 * Adjust a filename, according to a string of modifiers.
22598 * *fnamep must be NUL terminated when called. When returning, the length is
22599 * determined by *fnamelen.
22600 * Returns VALID_ flags or -1 for failure.
22601 * When there is an error, *fnamep is set to NULL.
22604 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
22605 char_u *src; /* string with modifiers */
22606 int *usedlen; /* characters after src that are used */
22607 char_u **fnamep; /* file name so far */
22608 char_u **bufp; /* buffer for allocated file name or NULL */
22609 int *fnamelen; /* length of fnamep */
22611 int valid = 0;
22612 char_u *tail;
22613 char_u *s, *p, *pbuf;
22614 char_u dirname[MAXPATHL];
22615 int c;
22616 int has_fullname = 0;
22617 #ifdef WIN3264
22618 int has_shortname = 0;
22619 #endif
22621 repeat:
22622 /* ":p" - full path/file_name */
22623 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
22625 has_fullname = 1;
22627 valid |= VALID_PATH;
22628 *usedlen += 2;
22630 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
22631 if ((*fnamep)[0] == '~'
22632 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
22633 && ((*fnamep)[1] == '/'
22634 # ifdef BACKSLASH_IN_FILENAME
22635 || (*fnamep)[1] == '\\'
22636 # endif
22637 || (*fnamep)[1] == NUL)
22639 #endif
22642 *fnamep = expand_env_save(*fnamep);
22643 vim_free(*bufp); /* free any allocated file name */
22644 *bufp = *fnamep;
22645 if (*fnamep == NULL)
22646 return -1;
22649 /* When "/." or "/.." is used: force expansion to get rid of it. */
22650 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
22652 if (vim_ispathsep(*p)
22653 && p[1] == '.'
22654 && (p[2] == NUL
22655 || vim_ispathsep(p[2])
22656 || (p[2] == '.'
22657 && (p[3] == NUL || vim_ispathsep(p[3])))))
22658 break;
22661 /* FullName_save() is slow, don't use it when not needed. */
22662 if (*p != NUL || !vim_isAbsName(*fnamep))
22664 *fnamep = FullName_save(*fnamep, *p != NUL);
22665 vim_free(*bufp); /* free any allocated file name */
22666 *bufp = *fnamep;
22667 if (*fnamep == NULL)
22668 return -1;
22671 /* Append a path separator to a directory. */
22672 if (mch_isdir(*fnamep))
22674 /* Make room for one or two extra characters. */
22675 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
22676 vim_free(*bufp); /* free any allocated file name */
22677 *bufp = *fnamep;
22678 if (*fnamep == NULL)
22679 return -1;
22680 add_pathsep(*fnamep);
22684 /* ":." - path relative to the current directory */
22685 /* ":~" - path relative to the home directory */
22686 /* ":8" - shortname path - postponed till after */
22687 while (src[*usedlen] == ':'
22688 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
22690 *usedlen += 2;
22691 if (c == '8')
22693 #ifdef WIN3264
22694 has_shortname = 1; /* Postpone this. */
22695 #endif
22696 continue;
22698 pbuf = NULL;
22699 /* Need full path first (use expand_env() to remove a "~/") */
22700 if (!has_fullname)
22702 if (c == '.' && **fnamep == '~')
22703 p = pbuf = expand_env_save(*fnamep);
22704 else
22705 p = pbuf = FullName_save(*fnamep, FALSE);
22707 else
22708 p = *fnamep;
22710 has_fullname = 0;
22712 if (p != NULL)
22714 if (c == '.')
22716 mch_dirname(dirname, MAXPATHL);
22717 s = shorten_fname(p, dirname);
22718 if (s != NULL)
22720 *fnamep = s;
22721 if (pbuf != NULL)
22723 vim_free(*bufp); /* free any allocated file name */
22724 *bufp = pbuf;
22725 pbuf = NULL;
22729 else
22731 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
22732 /* Only replace it when it starts with '~' */
22733 if (*dirname == '~')
22735 s = vim_strsave(dirname);
22736 if (s != NULL)
22738 *fnamep = s;
22739 vim_free(*bufp);
22740 *bufp = s;
22744 vim_free(pbuf);
22748 tail = gettail(*fnamep);
22749 *fnamelen = (int)STRLEN(*fnamep);
22751 /* ":h" - head, remove "/file_name", can be repeated */
22752 /* Don't remove the first "/" or "c:\" */
22753 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
22755 valid |= VALID_HEAD;
22756 *usedlen += 2;
22757 s = get_past_head(*fnamep);
22758 while (tail > s && after_pathsep(s, tail))
22759 mb_ptr_back(*fnamep, tail);
22760 *fnamelen = (int)(tail - *fnamep);
22761 #ifdef VMS
22762 if (*fnamelen > 0)
22763 *fnamelen += 1; /* the path separator is part of the path */
22764 #endif
22765 if (*fnamelen == 0)
22767 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
22768 p = vim_strsave((char_u *)".");
22769 if (p == NULL)
22770 return -1;
22771 vim_free(*bufp);
22772 *bufp = *fnamep = tail = p;
22773 *fnamelen = 1;
22775 else
22777 while (tail > s && !after_pathsep(s, tail))
22778 mb_ptr_back(*fnamep, tail);
22782 /* ":8" - shortname */
22783 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
22785 *usedlen += 2;
22786 #ifdef WIN3264
22787 has_shortname = 1;
22788 #endif
22791 #ifdef WIN3264
22792 /* Check shortname after we have done 'heads' and before we do 'tails'
22794 if (has_shortname)
22796 pbuf = NULL;
22797 /* Copy the string if it is shortened by :h */
22798 if (*fnamelen < (int)STRLEN(*fnamep))
22800 p = vim_strnsave(*fnamep, *fnamelen);
22801 if (p == 0)
22802 return -1;
22803 vim_free(*bufp);
22804 *bufp = *fnamep = p;
22807 /* Split into two implementations - makes it easier. First is where
22808 * there isn't a full name already, second is where there is.
22810 if (!has_fullname && !vim_isAbsName(*fnamep))
22812 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
22813 return -1;
22815 else
22817 int l;
22819 /* Simple case, already have the full-name
22820 * Nearly always shorter, so try first time. */
22821 l = *fnamelen;
22822 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
22823 return -1;
22825 if (l == 0)
22827 /* Couldn't find the filename.. search the paths.
22829 l = *fnamelen;
22830 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
22831 return -1;
22833 *fnamelen = l;
22836 #endif /* WIN3264 */
22838 /* ":t" - tail, just the basename */
22839 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
22841 *usedlen += 2;
22842 *fnamelen -= (int)(tail - *fnamep);
22843 *fnamep = tail;
22846 /* ":e" - extension, can be repeated */
22847 /* ":r" - root, without extension, can be repeated */
22848 while (src[*usedlen] == ':'
22849 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
22851 /* find a '.' in the tail:
22852 * - for second :e: before the current fname
22853 * - otherwise: The last '.'
22855 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
22856 s = *fnamep - 2;
22857 else
22858 s = *fnamep + *fnamelen - 1;
22859 for ( ; s > tail; --s)
22860 if (s[0] == '.')
22861 break;
22862 if (src[*usedlen + 1] == 'e') /* :e */
22864 if (s > tail)
22866 *fnamelen += (int)(*fnamep - (s + 1));
22867 *fnamep = s + 1;
22868 #ifdef VMS
22869 /* cut version from the extension */
22870 s = *fnamep + *fnamelen - 1;
22871 for ( ; s > *fnamep; --s)
22872 if (s[0] == ';')
22873 break;
22874 if (s > *fnamep)
22875 *fnamelen = s - *fnamep;
22876 #endif
22878 else if (*fnamep <= tail)
22879 *fnamelen = 0;
22881 else /* :r */
22883 if (s > tail) /* remove one extension */
22884 *fnamelen = (int)(s - *fnamep);
22886 *usedlen += 2;
22889 /* ":s?pat?foo?" - substitute */
22890 /* ":gs?pat?foo?" - global substitute */
22891 if (src[*usedlen] == ':'
22892 && (src[*usedlen + 1] == 's'
22893 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
22895 char_u *str;
22896 char_u *pat;
22897 char_u *sub;
22898 int sep;
22899 char_u *flags;
22900 int didit = FALSE;
22902 flags = (char_u *)"";
22903 s = src + *usedlen + 2;
22904 if (src[*usedlen + 1] == 'g')
22906 flags = (char_u *)"g";
22907 ++s;
22910 sep = *s++;
22911 if (sep)
22913 /* find end of pattern */
22914 p = vim_strchr(s, sep);
22915 if (p != NULL)
22917 pat = vim_strnsave(s, (int)(p - s));
22918 if (pat != NULL)
22920 s = p + 1;
22921 /* find end of substitution */
22922 p = vim_strchr(s, sep);
22923 if (p != NULL)
22925 sub = vim_strnsave(s, (int)(p - s));
22926 str = vim_strnsave(*fnamep, *fnamelen);
22927 if (sub != NULL && str != NULL)
22929 *usedlen = (int)(p + 1 - src);
22930 s = do_string_sub(str, pat, sub, flags);
22931 if (s != NULL)
22933 *fnamep = s;
22934 *fnamelen = (int)STRLEN(s);
22935 vim_free(*bufp);
22936 *bufp = s;
22937 didit = TRUE;
22940 vim_free(sub);
22941 vim_free(str);
22943 vim_free(pat);
22946 /* after using ":s", repeat all the modifiers */
22947 if (didit)
22948 goto repeat;
22952 return valid;
22956 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
22957 * "flags" can be "g" to do a global substitute.
22958 * Returns an allocated string, NULL for error.
22960 char_u *
22961 do_string_sub(str, pat, sub, flags)
22962 char_u *str;
22963 char_u *pat;
22964 char_u *sub;
22965 char_u *flags;
22967 int sublen;
22968 regmatch_T regmatch;
22969 int i;
22970 int do_all;
22971 char_u *tail;
22972 garray_T ga;
22973 char_u *ret;
22974 char_u *save_cpo;
22976 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
22977 save_cpo = p_cpo;
22978 p_cpo = empty_option;
22980 ga_init2(&ga, 1, 200);
22982 do_all = (flags[0] == 'g');
22984 regmatch.rm_ic = p_ic;
22985 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
22986 if (regmatch.regprog != NULL)
22988 tail = str;
22989 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
22992 * Get some space for a temporary buffer to do the substitution
22993 * into. It will contain:
22994 * - The text up to where the match is.
22995 * - The substituted text.
22996 * - The text after the match.
22998 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
22999 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
23000 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
23002 ga_clear(&ga);
23003 break;
23006 /* copy the text up to where the match is */
23007 i = (int)(regmatch.startp[0] - tail);
23008 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
23009 /* add the substituted text */
23010 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
23011 + ga.ga_len + i, TRUE, TRUE, FALSE);
23012 ga.ga_len += i + sublen - 1;
23013 /* avoid getting stuck on a match with an empty string */
23014 if (tail == regmatch.endp[0])
23016 if (*tail == NUL)
23017 break;
23018 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
23019 ++ga.ga_len;
23021 else
23023 tail = regmatch.endp[0];
23024 if (*tail == NUL)
23025 break;
23027 if (!do_all)
23028 break;
23031 if (ga.ga_data != NULL)
23032 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
23034 vim_free(regmatch.regprog);
23037 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
23038 ga_clear(&ga);
23039 if (p_cpo == empty_option)
23040 p_cpo = save_cpo;
23041 else
23042 /* Darn, evaluating {sub} expression changed the value. */
23043 free_string_option(save_cpo);
23045 return ret;
23048 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */