Merge branch 'vim' into feat/float-point-ext
[vim_extended.git] / src / eval.c
blob335be6786e4ef1e4b5ec17e8553f6545cfe45e64
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.
132 * The last bit is used for previous_funccal, ignored when comparing.
134 static int current_copyID = 0;
135 #define COPYID_INC 2
136 #define COPYID_MASK (~0x1)
139 * Array to hold the hashtab with variables local to each sourced script.
140 * Each item holds a variable (nameless) that points to the dict_T.
142 typedef struct
144 dictitem_T sv_var;
145 dict_T sv_dict;
146 } scriptvar_T;
148 static garray_T ga_scripts = {0, 0, sizeof(scriptvar_T), 4, NULL};
149 #define SCRIPT_SV(id) (((scriptvar_T *)ga_scripts.ga_data)[(id) - 1])
150 #define SCRIPT_VARS(id) (SCRIPT_SV(id).sv_dict.dv_hashtab)
152 static int echo_attr = 0; /* attributes used for ":echo" */
154 /* Values for trans_function_name() argument: */
155 #define TFN_INT 1 /* internal function name OK */
156 #define TFN_QUIET 2 /* no error messages */
159 * Structure to hold info for a user function.
161 typedef struct ufunc ufunc_T;
163 struct ufunc
165 int uf_varargs; /* variable nr of arguments */
166 int uf_flags;
167 int uf_calls; /* nr of active calls */
168 garray_T uf_args; /* arguments */
169 garray_T uf_lines; /* function lines */
170 #ifdef FEAT_PROFILE
171 int uf_profiling; /* TRUE when func is being profiled */
172 /* profiling the function as a whole */
173 int uf_tm_count; /* nr of calls */
174 proftime_T uf_tm_total; /* time spent in function + children */
175 proftime_T uf_tm_self; /* time spent in function itself */
176 proftime_T uf_tm_children; /* time spent in children this call */
177 /* profiling the function per line */
178 int *uf_tml_count; /* nr of times line was executed */
179 proftime_T *uf_tml_total; /* time spent in a line + children */
180 proftime_T *uf_tml_self; /* time spent in a line itself */
181 proftime_T uf_tml_start; /* start time for current line */
182 proftime_T uf_tml_children; /* time spent in children for this line */
183 proftime_T uf_tml_wait; /* start wait time for current line */
184 int uf_tml_idx; /* index of line being timed; -1 if none */
185 int uf_tml_execed; /* line being timed was executed */
186 #endif
187 scid_T uf_script_ID; /* ID of script where function was defined,
188 used for s: variables */
189 int uf_refcount; /* for numbered function: reference count */
190 char_u uf_name[1]; /* name of function (actually longer); can
191 start with <SNR>123_ (<SNR> is K_SPECIAL
192 KS_EXTRA KE_SNR) */
195 /* function flags */
196 #define FC_ABORT 1 /* abort function on error */
197 #define FC_RANGE 2 /* function accepts range */
198 #define FC_DICT 4 /* Dict function, uses "self" */
201 * All user-defined functions are found in this hashtable.
203 static hashtab_T func_hashtab;
205 /* The names of packages that once were loaded are remembered. */
206 static garray_T ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
208 /* list heads for garbage collection */
209 static dict_T *first_dict = NULL; /* list of all dicts */
210 static list_T *first_list = NULL; /* list of all lists */
212 /* From user function to hashitem and back. */
213 static ufunc_T dumuf;
214 #define UF2HIKEY(fp) ((fp)->uf_name)
215 #define HIKEY2UF(p) ((ufunc_T *)(p - (dumuf.uf_name - (char_u *)&dumuf)))
216 #define HI2UF(hi) HIKEY2UF((hi)->hi_key)
218 #define FUNCARG(fp, j) ((char_u **)(fp->uf_args.ga_data))[j]
219 #define FUNCLINE(fp, j) ((char_u **)(fp->uf_lines.ga_data))[j]
221 #define MAX_FUNC_ARGS 20 /* maximum number of function arguments */
222 #define VAR_SHORT_LEN 20 /* short variable name length */
223 #define FIXVAR_CNT 12 /* number of fixed variables */
225 /* structure to hold info for a function that is currently being executed. */
226 typedef struct funccall_S funccall_T;
228 struct funccall_S
230 ufunc_T *func; /* function being called */
231 int linenr; /* next line to be executed */
232 int returned; /* ":return" used */
233 struct /* fixed variables for arguments */
235 dictitem_T var; /* variable (without room for name) */
236 char_u room[VAR_SHORT_LEN]; /* room for the name */
237 } fixvar[FIXVAR_CNT];
238 dict_T l_vars; /* l: local function variables */
239 dictitem_T l_vars_var; /* variable for l: scope */
240 dict_T l_avars; /* a: argument variables */
241 dictitem_T l_avars_var; /* variable for a: scope */
242 list_T l_varlist; /* list for a:000 */
243 listitem_T l_listitems[MAX_FUNC_ARGS]; /* listitems for a:000 */
244 typval_T *rettv; /* return value */
245 linenr_T breakpoint; /* next line with breakpoint or zero */
246 int dbg_tick; /* debug_tick when breakpoint was set */
247 int level; /* top nesting level of executed function */
248 #ifdef FEAT_PROFILE
249 proftime_T prof_child; /* time spent in a child */
250 #endif
251 funccall_T *caller; /* calling function or NULL */
255 * Info used by a ":for" loop.
257 typedef struct
259 int fi_semicolon; /* TRUE if ending in '; var]' */
260 int fi_varcount; /* nr of variables in the list */
261 listwatch_T fi_lw; /* keep an eye on the item used. */
262 list_T *fi_list; /* list being used */
263 } forinfo_T;
266 * Struct used by trans_function_name()
268 typedef struct
270 dict_T *fd_dict; /* Dictionary used */
271 char_u *fd_newkey; /* new key in "dict" in allocated memory */
272 dictitem_T *fd_di; /* Dictionary item used */
273 } funcdict_T;
277 * Array to hold the value of v: variables.
278 * The value is in a dictitem, so that it can also be used in the v: scope.
279 * The reason to use this table anyway is for very quick access to the
280 * variables with the VV_ defines.
282 #include "version.h"
284 /* values for vv_flags: */
285 #define VV_COMPAT 1 /* compatible, also used without "v:" */
286 #define VV_RO 2 /* read-only */
287 #define VV_RO_SBX 4 /* read-only in the sandbox */
289 #define VV_NAME(s, t) s, {{t, 0, {0}}, 0, {0}}, {0}
291 static struct vimvar
293 char *vv_name; /* name of variable, without v: */
294 dictitem_T vv_di; /* value and name for key */
295 char vv_filler[16]; /* space for LONGEST name below!!! */
296 char vv_flags; /* VV_COMPAT, VV_RO, VV_RO_SBX */
297 } vimvars[VV_LEN] =
300 * The order here must match the VV_ defines in vim.h!
301 * Initializing a union does not work, leave tv.vval empty to get zero's.
303 {VV_NAME("count", VAR_NUMBER), VV_COMPAT+VV_RO},
304 {VV_NAME("count1", VAR_NUMBER), VV_RO},
305 {VV_NAME("prevcount", VAR_NUMBER), VV_RO},
306 {VV_NAME("errmsg", VAR_STRING), VV_COMPAT},
307 {VV_NAME("warningmsg", VAR_STRING), 0},
308 {VV_NAME("statusmsg", VAR_STRING), 0},
309 {VV_NAME("shell_error", VAR_NUMBER), VV_COMPAT+VV_RO},
310 {VV_NAME("this_session", VAR_STRING), VV_COMPAT},
311 {VV_NAME("version", VAR_NUMBER), VV_COMPAT+VV_RO},
312 {VV_NAME("lnum", VAR_NUMBER), VV_RO_SBX},
313 {VV_NAME("termresponse", VAR_STRING), VV_RO},
314 {VV_NAME("fname", VAR_STRING), VV_RO},
315 {VV_NAME("lang", VAR_STRING), VV_RO},
316 {VV_NAME("lc_time", VAR_STRING), VV_RO},
317 {VV_NAME("ctype", VAR_STRING), VV_RO},
318 {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
319 {VV_NAME("charconvert_to", VAR_STRING), VV_RO},
320 {VV_NAME("fname_in", VAR_STRING), VV_RO},
321 {VV_NAME("fname_out", VAR_STRING), VV_RO},
322 {VV_NAME("fname_new", VAR_STRING), VV_RO},
323 {VV_NAME("fname_diff", VAR_STRING), VV_RO},
324 {VV_NAME("cmdarg", VAR_STRING), VV_RO},
325 {VV_NAME("foldstart", VAR_NUMBER), VV_RO_SBX},
326 {VV_NAME("foldend", VAR_NUMBER), VV_RO_SBX},
327 {VV_NAME("folddashes", VAR_STRING), VV_RO_SBX},
328 {VV_NAME("foldlevel", VAR_NUMBER), VV_RO_SBX},
329 {VV_NAME("progname", VAR_STRING), VV_RO},
330 {VV_NAME("servername", VAR_STRING), VV_RO},
331 {VV_NAME("dying", VAR_NUMBER), VV_RO},
332 {VV_NAME("exception", VAR_STRING), VV_RO},
333 {VV_NAME("throwpoint", VAR_STRING), VV_RO},
334 {VV_NAME("register", VAR_STRING), VV_RO},
335 {VV_NAME("cmdbang", VAR_NUMBER), VV_RO},
336 {VV_NAME("insertmode", VAR_STRING), VV_RO},
337 {VV_NAME("val", VAR_UNKNOWN), VV_RO},
338 {VV_NAME("key", VAR_UNKNOWN), VV_RO},
339 {VV_NAME("profiling", VAR_NUMBER), VV_RO},
340 {VV_NAME("fcs_reason", VAR_STRING), VV_RO},
341 {VV_NAME("fcs_choice", VAR_STRING), 0},
342 {VV_NAME("beval_bufnr", VAR_NUMBER), VV_RO},
343 {VV_NAME("beval_winnr", VAR_NUMBER), VV_RO},
344 {VV_NAME("beval_lnum", VAR_NUMBER), VV_RO},
345 {VV_NAME("beval_col", VAR_NUMBER), VV_RO},
346 {VV_NAME("beval_text", VAR_STRING), VV_RO},
347 {VV_NAME("scrollstart", VAR_STRING), 0},
348 {VV_NAME("swapname", VAR_STRING), VV_RO},
349 {VV_NAME("swapchoice", VAR_STRING), 0},
350 {VV_NAME("swapcommand", VAR_STRING), VV_RO},
351 {VV_NAME("char", VAR_STRING), VV_RO},
352 {VV_NAME("mouse_win", VAR_NUMBER), 0},
353 {VV_NAME("mouse_lnum", VAR_NUMBER), 0},
354 {VV_NAME("mouse_col", VAR_NUMBER), 0},
355 {VV_NAME("operator", VAR_STRING), VV_RO},
356 {VV_NAME("searchforward", VAR_NUMBER), 0},
357 {VV_NAME("oldfiles", VAR_LIST), 0},
360 /* shorthand */
361 #define vv_type vv_di.di_tv.v_type
362 #define vv_nr vv_di.di_tv.vval.v_number
363 #define vv_float vv_di.di_tv.vval.v_float
364 #define vv_str vv_di.di_tv.vval.v_string
365 #define vv_list vv_di.di_tv.vval.v_list
366 #define vv_tv vv_di.di_tv
369 * The v: variables are stored in dictionary "vimvardict".
370 * "vimvars_var" is the variable that is used for the "l:" scope.
372 static dict_T vimvardict;
373 static dictitem_T vimvars_var;
374 #define vimvarht vimvardict.dv_hashtab
376 static void prepare_vimvar __ARGS((int idx, typval_T *save_tv));
377 static void restore_vimvar __ARGS((int idx, typval_T *save_tv));
378 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
379 static int call_vim_function __ARGS((char_u *func, int argc, char_u **argv, int safe, typval_T *rettv));
380 #endif
381 static int ex_let_vars __ARGS((char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars));
382 static char_u *skip_var_list __ARGS((char_u *arg, int *var_count, int *semicolon));
383 static char_u *skip_var_one __ARGS((char_u *arg));
384 static void list_hashtable_vars __ARGS((hashtab_T *ht, char_u *prefix, int empty, int *first));
385 static void list_glob_vars __ARGS((int *first));
386 static void list_buf_vars __ARGS((int *first));
387 static void list_win_vars __ARGS((int *first));
388 #ifdef FEAT_WINDOWS
389 static void list_tab_vars __ARGS((int *first));
390 #endif
391 static void list_vim_vars __ARGS((int *first));
392 static void list_script_vars __ARGS((int *first));
393 static void list_func_vars __ARGS((int *first));
394 static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg, int *first));
395 static char_u *ex_let_one __ARGS((char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op));
396 static int check_changedtick __ARGS((char_u *arg));
397 static char_u *get_lval __ARGS((char_u *name, typval_T *rettv, lval_T *lp, int unlet, int skip, int quiet, int fne_flags));
398 static void clear_lval __ARGS((lval_T *lp));
399 static void set_var_lval __ARGS((lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op));
400 static int tv_op __ARGS((typval_T *tv1, typval_T *tv2, char_u *op));
401 static void list_add_watch __ARGS((list_T *l, listwatch_T *lw));
402 static void list_rem_watch __ARGS((list_T *l, listwatch_T *lwrem));
403 static void list_fix_watch __ARGS((list_T *l, listitem_T *item));
404 static void ex_unletlock __ARGS((exarg_T *eap, char_u *argstart, int deep));
405 static int do_unlet_var __ARGS((lval_T *lp, char_u *name_end, int forceit));
406 static int do_lock_var __ARGS((lval_T *lp, char_u *name_end, int deep, int lock));
407 static void item_lock __ARGS((typval_T *tv, int deep, int lock));
408 static int tv_islocked __ARGS((typval_T *tv));
410 static int eval0 __ARGS((char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate));
411 static int eval1 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
412 static int eval2 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
413 static int eval3 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
414 static int eval4 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
415 static int eval5 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
416 static int eval6 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
417 static int eval7 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
419 static int eval_index __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
420 static int get_option_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
421 static int get_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
422 static int get_lit_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
423 static int get_list_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
424 static int rettv_list_alloc __ARGS((typval_T *rettv));
425 static listitem_T *listitem_alloc __ARGS((void));
426 static void listitem_free __ARGS((listitem_T *item));
427 static void listitem_remove __ARGS((list_T *l, listitem_T *item));
428 static long list_len __ARGS((list_T *l));
429 static int list_equal __ARGS((list_T *l1, list_T *l2, int ic));
430 static int dict_equal __ARGS((dict_T *d1, dict_T *d2, int ic));
431 static int tv_equal __ARGS((typval_T *tv1, typval_T *tv2, int ic));
432 static listitem_T *list_find __ARGS((list_T *l, long n));
433 static long list_find_nr __ARGS((list_T *l, long idx, int *errorp));
434 static long list_idx_of_item __ARGS((list_T *l, listitem_T *item));
435 static void list_append __ARGS((list_T *l, listitem_T *item));
436 static int list_append_number __ARGS((list_T *l, varnumber_T n));
437 static int list_insert_tv __ARGS((list_T *l, typval_T *tv, listitem_T *item));
438 static int list_extend __ARGS((list_T *l1, list_T *l2, listitem_T *bef));
439 static int list_concat __ARGS((list_T *l1, list_T *l2, typval_T *tv));
440 static list_T *list_copy __ARGS((list_T *orig, int deep, int copyID));
441 static void list_remove __ARGS((list_T *l, listitem_T *item, listitem_T *item2));
442 static char_u *list2string __ARGS((typval_T *tv, int copyID));
443 static int list_join __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo, int copyID));
444 static int free_unref_items __ARGS((int copyID));
445 static void set_ref_in_ht __ARGS((hashtab_T *ht, int copyID));
446 static void set_ref_in_list __ARGS((list_T *l, int copyID));
447 static void set_ref_in_item __ARGS((typval_T *tv, int copyID));
448 static void dict_unref __ARGS((dict_T *d));
449 static void dict_free __ARGS((dict_T *d, int recurse));
450 static dictitem_T *dictitem_copy __ARGS((dictitem_T *org));
451 static void dictitem_remove __ARGS((dict_T *dict, dictitem_T *item));
452 static dict_T *dict_copy __ARGS((dict_T *orig, int deep, int copyID));
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 #ifdef FEAT_MZSCHEME
643 static void f_mzeval __ARGS((typval_T *argvars, typval_T *rettv));
644 #endif
645 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
646 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
647 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
648 #ifdef FEAT_FLOAT
649 static void f_pow __ARGS((typval_T *argvars, typval_T *rettv));
650 #endif
651 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
652 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
653 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
654 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
655 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
656 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
657 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
667 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
668 #ifdef FEAT_FLOAT
669 static void f_round __ARGS((typval_T *argvars, typval_T *rettv));
670 #endif
671 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
672 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
673 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
674 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
675 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
676 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
677 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
678 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
679 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
680 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
681 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
682 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
683 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
684 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
685 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
686 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
687 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
688 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
689 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
690 #ifdef FEAT_FLOAT
691 static void f_sin __ARGS((typval_T *argvars, typval_T *rettv));
692 #endif
693 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
694 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
695 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
696 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
697 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
698 #ifdef FEAT_FLOAT
699 static void f_sqrt __ARGS((typval_T *argvars, typval_T *rettv));
700 static void f_str2float __ARGS((typval_T *argvars, typval_T *rettv));
701 #endif
702 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
703 #ifdef HAVE_STRFTIME
704 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
705 #endif
706 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
707 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
708 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
709 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
710 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
711 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
712 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
713 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
714 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
715 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
716 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
717 static void f_synstack __ARGS((typval_T *argvars, typval_T *rettv));
718 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
719 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
720 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
721 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
722 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
723 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
724 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
725 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
726 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
727 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
728 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
729 #ifdef FEAT_FLOAT
730 static void f_trunc __ARGS((typval_T *argvars, typval_T *rettv));
731 #endif
732 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
733 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
734 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
735 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
736 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
737 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
738 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
739 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
740 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
741 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
742 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
743 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
744 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
745 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
747 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
748 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
749 static int get_env_len __ARGS((char_u **arg));
750 static int get_id_len __ARGS((char_u **arg));
751 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
752 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
753 #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */
754 #define FNE_CHECK_START 2 /* find_name_end(): check name starts with
755 valid character */
756 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
757 static int eval_isnamec __ARGS((int c));
758 static int eval_isnamec1 __ARGS((int c));
759 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
760 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
761 static typval_T *alloc_tv __ARGS((void));
762 static typval_T *alloc_string_tv __ARGS((char_u *string));
763 static void init_tv __ARGS((typval_T *varp));
764 static long get_tv_number __ARGS((typval_T *varp));
765 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
766 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
767 static char_u *get_tv_string __ARGS((typval_T *varp));
768 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
769 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
770 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
771 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
772 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
773 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
774 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
775 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
776 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
777 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
778 static int var_check_ro __ARGS((int flags, char_u *name));
779 static int var_check_fixed __ARGS((int flags, char_u *name));
780 static int tv_check_lock __ARGS((int lock, char_u *name));
781 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
782 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
783 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
784 static int eval_fname_script __ARGS((char_u *p));
785 static int eval_fname_sid __ARGS((char_u *p));
786 static void list_func_head __ARGS((ufunc_T *fp, int indent));
787 static ufunc_T *find_func __ARGS((char_u *name));
788 static int function_exists __ARGS((char_u *name));
789 static int builtin_function __ARGS((char_u *name));
790 #ifdef FEAT_PROFILE
791 static void func_do_profile __ARGS((ufunc_T *fp));
792 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
793 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
794 static int
795 # ifdef __BORLANDC__
796 _RTLENTRYF
797 # endif
798 prof_total_cmp __ARGS((const void *s1, const void *s2));
799 static int
800 # ifdef __BORLANDC__
801 _RTLENTRYF
802 # endif
803 prof_self_cmp __ARGS((const void *s1, const void *s2));
804 #endif
805 static int script_autoload __ARGS((char_u *name, int reload));
806 static char_u *autoload_name __ARGS((char_u *name));
807 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
808 static void func_free __ARGS((ufunc_T *fp));
809 static void func_unref __ARGS((char_u *name));
810 static void func_ref __ARGS((char_u *name));
811 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));
812 static int can_free_funccal __ARGS((funccall_T *fc, int copyID)) ;
813 static void free_funccal __ARGS((funccall_T *fc, int free_val));
814 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
815 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
816 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
817 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
818 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
819 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
821 /* Character used as separated in autoload function/variable names. */
822 #define AUTOLOAD_CHAR '#'
825 * Initialize the global and v: variables.
827 void
828 eval_init()
830 int i;
831 struct vimvar *p;
833 init_var_dict(&globvardict, &globvars_var);
834 init_var_dict(&vimvardict, &vimvars_var);
835 hash_init(&compat_hashtab);
836 hash_init(&func_hashtab);
838 for (i = 0; i < VV_LEN; ++i)
840 p = &vimvars[i];
841 STRCPY(p->vv_di.di_key, p->vv_name);
842 if (p->vv_flags & VV_RO)
843 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
844 else if (p->vv_flags & VV_RO_SBX)
845 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
846 else
847 p->vv_di.di_flags = DI_FLAGS_FIX;
849 /* add to v: scope dict, unless the value is not always available */
850 if (p->vv_type != VAR_UNKNOWN)
851 hash_add(&vimvarht, p->vv_di.di_key);
852 if (p->vv_flags & VV_COMPAT)
853 /* add to compat scope dict */
854 hash_add(&compat_hashtab, p->vv_di.di_key);
856 set_vim_var_nr(VV_SEARCHFORWARD, 1L);
859 #if defined(EXITFREE) || defined(PROTO)
860 void
861 eval_clear()
863 int i;
864 struct vimvar *p;
866 for (i = 0; i < VV_LEN; ++i)
868 p = &vimvars[i];
869 if (p->vv_di.di_tv.v_type == VAR_STRING)
871 vim_free(p->vv_str);
872 p->vv_str = NULL;
874 else if (p->vv_di.di_tv.v_type == VAR_LIST)
876 list_unref(p->vv_list);
877 p->vv_list = NULL;
880 hash_clear(&vimvarht);
881 hash_init(&vimvarht); /* garbage_collect() will access it */
882 hash_clear(&compat_hashtab);
884 /* script-local variables */
885 for (i = 1; i <= ga_scripts.ga_len; ++i)
886 vars_clear(&SCRIPT_VARS(i));
887 ga_clear(&ga_scripts);
888 free_scriptnames();
890 /* global variables */
891 vars_clear(&globvarht);
893 /* autoloaded script names */
894 ga_clear_strings(&ga_loaded);
896 /* unreferenced lists and dicts */
897 (void)garbage_collect();
899 /* functions */
900 free_all_functions();
901 hash_clear(&func_hashtab);
903 #endif
906 * Return the name of the executed function.
908 char_u *
909 func_name(cookie)
910 void *cookie;
912 return ((funccall_T *)cookie)->func->uf_name;
916 * Return the address holding the next breakpoint line for a funccall cookie.
918 linenr_T *
919 func_breakpoint(cookie)
920 void *cookie;
922 return &((funccall_T *)cookie)->breakpoint;
926 * Return the address holding the debug tick for a funccall cookie.
928 int *
929 func_dbg_tick(cookie)
930 void *cookie;
932 return &((funccall_T *)cookie)->dbg_tick;
936 * Return the nesting level for a funccall cookie.
939 func_level(cookie)
940 void *cookie;
942 return ((funccall_T *)cookie)->level;
945 /* pointer to funccal for currently active function */
946 funccall_T *current_funccal = NULL;
948 /* pointer to list of previously used funccal, still around because some
949 * item in it is still being used. */
950 funccall_T *previous_funccal = NULL;
953 * Return TRUE when a function was ended by a ":return" command.
956 current_func_returned()
958 return current_funccal->returned;
963 * Set an internal variable to a string value. Creates the variable if it does
964 * not already exist.
966 void
967 set_internal_string_var(name, value)
968 char_u *name;
969 char_u *value;
971 char_u *val;
972 typval_T *tvp;
974 val = vim_strsave(value);
975 if (val != NULL)
977 tvp = alloc_string_tv(val);
978 if (tvp != NULL)
980 set_var(name, tvp, FALSE);
981 free_tv(tvp);
986 static lval_T *redir_lval = NULL;
987 static garray_T redir_ga; /* only valid when redir_lval is not NULL */
988 static char_u *redir_endp = NULL;
989 static char_u *redir_varname = NULL;
992 * Start recording command output to a variable
993 * Returns OK if successfully completed the setup. FAIL otherwise.
996 var_redir_start(name, append)
997 char_u *name;
998 int append; /* append to an existing variable */
1000 int save_emsg;
1001 int err;
1002 typval_T tv;
1004 /* Catch a bad name early. */
1005 if (!eval_isnamec1(*name))
1007 EMSG(_(e_invarg));
1008 return FAIL;
1011 /* Make a copy of the name, it is used in redir_lval until redir ends. */
1012 redir_varname = vim_strsave(name);
1013 if (redir_varname == NULL)
1014 return FAIL;
1016 redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
1017 if (redir_lval == NULL)
1019 var_redir_stop();
1020 return FAIL;
1023 /* The output is stored in growarray "redir_ga" until redirection ends. */
1024 ga_init2(&redir_ga, (int)sizeof(char), 500);
1026 /* Parse the variable name (can be a dict or list entry). */
1027 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
1028 FNE_CHECK_START);
1029 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
1031 if (redir_endp != NULL && *redir_endp != NUL)
1032 /* Trailing characters are present after the variable name */
1033 EMSG(_(e_trailing));
1034 else
1035 EMSG(_(e_invarg));
1036 redir_endp = NULL; /* don't store a value, only cleanup */
1037 var_redir_stop();
1038 return FAIL;
1041 /* check if we can write to the variable: set it to or append an empty
1042 * string */
1043 save_emsg = did_emsg;
1044 did_emsg = FALSE;
1045 tv.v_type = VAR_STRING;
1046 tv.vval.v_string = (char_u *)"";
1047 if (append)
1048 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
1049 else
1050 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
1051 err = did_emsg;
1052 did_emsg |= save_emsg;
1053 if (err)
1055 redir_endp = NULL; /* don't store a value, only cleanup */
1056 var_redir_stop();
1057 return FAIL;
1059 if (redir_lval->ll_newkey != NULL)
1061 /* Dictionary item was created, don't do it again. */
1062 vim_free(redir_lval->ll_newkey);
1063 redir_lval->ll_newkey = NULL;
1066 return OK;
1070 * Append "value[value_len]" to the variable set by var_redir_start().
1071 * The actual appending is postponed until redirection ends, because the value
1072 * appended may in fact be the string we write to, changing it may cause freed
1073 * memory to be used:
1074 * :redir => foo
1075 * :let foo
1076 * :redir END
1078 void
1079 var_redir_str(value, value_len)
1080 char_u *value;
1081 int value_len;
1083 int len;
1085 if (redir_lval == NULL)
1086 return;
1088 if (value_len == -1)
1089 len = (int)STRLEN(value); /* Append the entire string */
1090 else
1091 len = value_len; /* Append only "value_len" characters */
1093 if (ga_grow(&redir_ga, len) == OK)
1095 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1096 redir_ga.ga_len += len;
1098 else
1099 var_redir_stop();
1103 * Stop redirecting command output to a variable.
1104 * Frees the allocated memory.
1106 void
1107 var_redir_stop()
1109 typval_T tv;
1111 if (redir_lval != NULL)
1113 /* If there was no error: assign the text to the variable. */
1114 if (redir_endp != NULL)
1116 ga_append(&redir_ga, NUL); /* Append the trailing NUL. */
1117 tv.v_type = VAR_STRING;
1118 tv.vval.v_string = redir_ga.ga_data;
1119 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1122 /* free the collected output */
1123 vim_free(redir_ga.ga_data);
1124 redir_ga.ga_data = NULL;
1126 clear_lval(redir_lval);
1127 vim_free(redir_lval);
1128 redir_lval = NULL;
1130 vim_free(redir_varname);
1131 redir_varname = NULL;
1134 # if defined(FEAT_MBYTE) || defined(PROTO)
1136 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1137 char_u *enc_from;
1138 char_u *enc_to;
1139 char_u *fname_from;
1140 char_u *fname_to;
1142 int err = FALSE;
1144 set_vim_var_string(VV_CC_FROM, enc_from, -1);
1145 set_vim_var_string(VV_CC_TO, enc_to, -1);
1146 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1147 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1148 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1149 err = TRUE;
1150 set_vim_var_string(VV_CC_FROM, NULL, -1);
1151 set_vim_var_string(VV_CC_TO, NULL, -1);
1152 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1153 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1155 if (err)
1156 return FAIL;
1157 return OK;
1159 # endif
1161 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1163 eval_printexpr(fname, args)
1164 char_u *fname;
1165 char_u *args;
1167 int err = FALSE;
1169 set_vim_var_string(VV_FNAME_IN, fname, -1);
1170 set_vim_var_string(VV_CMDARG, args, -1);
1171 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1172 err = TRUE;
1173 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1174 set_vim_var_string(VV_CMDARG, NULL, -1);
1176 if (err)
1178 mch_remove(fname);
1179 return FAIL;
1181 return OK;
1183 # endif
1185 # if defined(FEAT_DIFF) || defined(PROTO)
1186 void
1187 eval_diff(origfile, newfile, outfile)
1188 char_u *origfile;
1189 char_u *newfile;
1190 char_u *outfile;
1192 int err = FALSE;
1194 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1195 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1196 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1197 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1198 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1199 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1200 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1203 void
1204 eval_patch(origfile, difffile, outfile)
1205 char_u *origfile;
1206 char_u *difffile;
1207 char_u *outfile;
1209 int err;
1211 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1212 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1213 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1214 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1215 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1216 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1217 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1219 # endif
1222 * Top level evaluation function, returning a boolean.
1223 * Sets "error" to TRUE if there was an error.
1224 * Return TRUE or FALSE.
1227 eval_to_bool(arg, error, nextcmd, skip)
1228 char_u *arg;
1229 int *error;
1230 char_u **nextcmd;
1231 int skip; /* only parse, don't execute */
1233 typval_T tv;
1234 int retval = FALSE;
1236 if (skip)
1237 ++emsg_skip;
1238 if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1239 *error = TRUE;
1240 else
1242 *error = FALSE;
1243 if (!skip)
1245 retval = (get_tv_number_chk(&tv, error) != 0);
1246 clear_tv(&tv);
1249 if (skip)
1250 --emsg_skip;
1252 return retval;
1256 * Top level evaluation function, returning a string. If "skip" is TRUE,
1257 * only parsing to "nextcmd" is done, without reporting errors. Return
1258 * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1260 char_u *
1261 eval_to_string_skip(arg, nextcmd, skip)
1262 char_u *arg;
1263 char_u **nextcmd;
1264 int skip; /* only parse, don't execute */
1266 typval_T tv;
1267 char_u *retval;
1269 if (skip)
1270 ++emsg_skip;
1271 if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1272 retval = NULL;
1273 else
1275 retval = vim_strsave(get_tv_string(&tv));
1276 clear_tv(&tv);
1278 if (skip)
1279 --emsg_skip;
1281 return retval;
1285 * Skip over an expression at "*pp".
1286 * Return FAIL for an error, OK otherwise.
1289 skip_expr(pp)
1290 char_u **pp;
1292 typval_T rettv;
1294 *pp = skipwhite(*pp);
1295 return eval1(pp, &rettv, FALSE);
1299 * Top level evaluation function, returning a string.
1300 * When "convert" is TRUE convert a List into a sequence of lines and convert
1301 * a Float to a String.
1302 * Return pointer to allocated memory, or NULL for failure.
1304 char_u *
1305 eval_to_string(arg, nextcmd, convert)
1306 char_u *arg;
1307 char_u **nextcmd;
1308 int convert;
1310 typval_T tv;
1311 char_u *retval;
1312 garray_T ga;
1313 #ifdef FEAT_FLOAT
1314 char_u numbuf[NUMBUFLEN];
1315 #endif
1317 if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1318 retval = NULL;
1319 else
1321 if (convert && tv.v_type == VAR_LIST)
1323 ga_init2(&ga, (int)sizeof(char), 80);
1324 if (tv.vval.v_list != NULL)
1325 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1326 ga_append(&ga, NUL);
1327 retval = (char_u *)ga.ga_data;
1329 #ifdef FEAT_FLOAT
1330 else if (convert && tv.v_type == VAR_FLOAT)
1332 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv.vval.v_float);
1333 retval = vim_strsave(numbuf);
1335 #endif
1336 else
1337 retval = vim_strsave(get_tv_string(&tv));
1338 clear_tv(&tv);
1341 return retval;
1345 * Call eval_to_string() without using current local variables and using
1346 * textlock. When "use_sandbox" is TRUE use the sandbox.
1348 char_u *
1349 eval_to_string_safe(arg, nextcmd, use_sandbox)
1350 char_u *arg;
1351 char_u **nextcmd;
1352 int use_sandbox;
1354 char_u *retval;
1355 void *save_funccalp;
1357 save_funccalp = save_funccal();
1358 if (use_sandbox)
1359 ++sandbox;
1360 ++textlock;
1361 retval = eval_to_string(arg, nextcmd, FALSE);
1362 if (use_sandbox)
1363 --sandbox;
1364 --textlock;
1365 restore_funccal(save_funccalp);
1366 return retval;
1370 * Top level evaluation function, returning a number.
1371 * Evaluates "expr" silently.
1372 * Returns -1 for an error.
1375 eval_to_number(expr)
1376 char_u *expr;
1378 typval_T rettv;
1379 int retval;
1380 char_u *p = skipwhite(expr);
1382 ++emsg_off;
1384 if (eval1(&p, &rettv, TRUE) == FAIL)
1385 retval = -1;
1386 else
1388 retval = get_tv_number_chk(&rettv, NULL);
1389 clear_tv(&rettv);
1391 --emsg_off;
1393 return retval;
1397 * Prepare v: variable "idx" to be used.
1398 * Save the current typeval in "save_tv".
1399 * When not used yet add the variable to the v: hashtable.
1401 static void
1402 prepare_vimvar(idx, save_tv)
1403 int idx;
1404 typval_T *save_tv;
1406 *save_tv = vimvars[idx].vv_tv;
1407 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1408 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1412 * Restore v: variable "idx" to typeval "save_tv".
1413 * When no longer defined, remove the variable from the v: hashtable.
1415 static void
1416 restore_vimvar(idx, save_tv)
1417 int idx;
1418 typval_T *save_tv;
1420 hashitem_T *hi;
1422 vimvars[idx].vv_tv = *save_tv;
1423 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1425 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1426 if (HASHITEM_EMPTY(hi))
1427 EMSG2(_(e_intern2), "restore_vimvar()");
1428 else
1429 hash_remove(&vimvarht, hi);
1433 #if defined(FEAT_SPELL) || defined(PROTO)
1435 * Evaluate an expression to a list with suggestions.
1436 * For the "expr:" part of 'spellsuggest'.
1437 * Returns NULL when there is an error.
1439 list_T *
1440 eval_spell_expr(badword, expr)
1441 char_u *badword;
1442 char_u *expr;
1444 typval_T save_val;
1445 typval_T rettv;
1446 list_T *list = NULL;
1447 char_u *p = skipwhite(expr);
1449 /* Set "v:val" to the bad word. */
1450 prepare_vimvar(VV_VAL, &save_val);
1451 vimvars[VV_VAL].vv_type = VAR_STRING;
1452 vimvars[VV_VAL].vv_str = badword;
1453 if (p_verbose == 0)
1454 ++emsg_off;
1456 if (eval1(&p, &rettv, TRUE) == OK)
1458 if (rettv.v_type != VAR_LIST)
1459 clear_tv(&rettv);
1460 else
1461 list = rettv.vval.v_list;
1464 if (p_verbose == 0)
1465 --emsg_off;
1466 restore_vimvar(VV_VAL, &save_val);
1468 return list;
1472 * "list" is supposed to contain two items: a word and a number. Return the
1473 * word in "pp" and the number as the return value.
1474 * Return -1 if anything isn't right.
1475 * Used to get the good word and score from the eval_spell_expr() result.
1478 get_spellword(list, pp)
1479 list_T *list;
1480 char_u **pp;
1482 listitem_T *li;
1484 li = list->lv_first;
1485 if (li == NULL)
1486 return -1;
1487 *pp = get_tv_string(&li->li_tv);
1489 li = li->li_next;
1490 if (li == NULL)
1491 return -1;
1492 return get_tv_number(&li->li_tv);
1494 #endif
1497 * Top level evaluation function.
1498 * Returns an allocated typval_T with the result.
1499 * Returns NULL when there is an error.
1501 typval_T *
1502 eval_expr(arg, nextcmd)
1503 char_u *arg;
1504 char_u **nextcmd;
1506 typval_T *tv;
1508 tv = (typval_T *)alloc(sizeof(typval_T));
1509 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1511 vim_free(tv);
1512 tv = NULL;
1515 return tv;
1519 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1520 || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1522 * Call some vimL function and return the result in "*rettv".
1523 * Uses argv[argc] for the function arguments. Only Number and String
1524 * arguments are currently supported.
1525 * Returns OK or FAIL.
1527 static int
1528 call_vim_function(func, argc, argv, safe, rettv)
1529 char_u *func;
1530 int argc;
1531 char_u **argv;
1532 int safe; /* use the sandbox */
1533 typval_T *rettv;
1535 typval_T *argvars;
1536 long n;
1537 int len;
1538 int i;
1539 int doesrange;
1540 void *save_funccalp = NULL;
1541 int ret;
1543 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1544 if (argvars == NULL)
1545 return FAIL;
1547 for (i = 0; i < argc; i++)
1549 /* Pass a NULL or empty argument as an empty string */
1550 if (argv[i] == NULL || *argv[i] == NUL)
1552 argvars[i].v_type = VAR_STRING;
1553 argvars[i].vval.v_string = (char_u *)"";
1554 continue;
1557 /* Recognize a number argument, the others must be strings. */
1558 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1559 if (len != 0 && len == (int)STRLEN(argv[i]))
1561 argvars[i].v_type = VAR_NUMBER;
1562 argvars[i].vval.v_number = n;
1564 else
1566 argvars[i].v_type = VAR_STRING;
1567 argvars[i].vval.v_string = argv[i];
1571 if (safe)
1573 save_funccalp = save_funccal();
1574 ++sandbox;
1577 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1578 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1579 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1580 &doesrange, TRUE, NULL);
1581 if (safe)
1583 --sandbox;
1584 restore_funccal(save_funccalp);
1586 vim_free(argvars);
1588 if (ret == FAIL)
1589 clear_tv(rettv);
1591 return ret;
1594 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1596 * Call vimL function "func" and return the result as a string.
1597 * Returns NULL when calling the function fails.
1598 * Uses argv[argc] for the function arguments.
1600 void *
1601 call_func_retstr(func, argc, argv, safe)
1602 char_u *func;
1603 int argc;
1604 char_u **argv;
1605 int safe; /* use the sandbox */
1607 typval_T rettv;
1608 char_u *retval;
1610 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1611 return NULL;
1613 retval = vim_strsave(get_tv_string(&rettv));
1614 clear_tv(&rettv);
1615 return retval;
1617 # endif
1619 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1621 * Call vimL function "func" and return the result as a number.
1622 * Returns -1 when calling the function fails.
1623 * Uses argv[argc] for the function arguments.
1625 long
1626 call_func_retnr(func, argc, argv, safe)
1627 char_u *func;
1628 int argc;
1629 char_u **argv;
1630 int safe; /* use the sandbox */
1632 typval_T rettv;
1633 long retval;
1635 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1636 return -1;
1638 retval = get_tv_number_chk(&rettv, NULL);
1639 clear_tv(&rettv);
1640 return retval;
1642 # endif
1645 * Call vimL function "func" and return the result as a List.
1646 * Uses argv[argc] for the function arguments.
1647 * Returns NULL when there is something wrong.
1649 void *
1650 call_func_retlist(func, argc, argv, safe)
1651 char_u *func;
1652 int argc;
1653 char_u **argv;
1654 int safe; /* use the sandbox */
1656 typval_T rettv;
1658 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1659 return NULL;
1661 if (rettv.v_type != VAR_LIST)
1663 clear_tv(&rettv);
1664 return NULL;
1667 return rettv.vval.v_list;
1669 #endif
1673 * Save the current function call pointer, and set it to NULL.
1674 * Used when executing autocommands and for ":source".
1676 void *
1677 save_funccal()
1679 funccall_T *fc = current_funccal;
1681 current_funccal = NULL;
1682 return (void *)fc;
1685 void
1686 restore_funccal(vfc)
1687 void *vfc;
1689 funccall_T *fc = (funccall_T *)vfc;
1691 current_funccal = fc;
1694 #if defined(FEAT_PROFILE) || defined(PROTO)
1696 * Prepare profiling for entering a child or something else that is not
1697 * counted for the script/function itself.
1698 * Should always be called in pair with prof_child_exit().
1700 void
1701 prof_child_enter(tm)
1702 proftime_T *tm; /* place to store waittime */
1704 funccall_T *fc = current_funccal;
1706 if (fc != NULL && fc->func->uf_profiling)
1707 profile_start(&fc->prof_child);
1708 script_prof_save(tm);
1712 * Take care of time spent in a child.
1713 * Should always be called after prof_child_enter().
1715 void
1716 prof_child_exit(tm)
1717 proftime_T *tm; /* where waittime was stored */
1719 funccall_T *fc = current_funccal;
1721 if (fc != NULL && fc->func->uf_profiling)
1723 profile_end(&fc->prof_child);
1724 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1725 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1726 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1728 script_prof_restore(tm);
1730 #endif
1733 #ifdef FEAT_FOLDING
1735 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1736 * it in "*cp". Doesn't give error messages.
1739 eval_foldexpr(arg, cp)
1740 char_u *arg;
1741 int *cp;
1743 typval_T tv;
1744 int retval;
1745 char_u *s;
1746 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1747 OPT_LOCAL);
1749 ++emsg_off;
1750 if (use_sandbox)
1751 ++sandbox;
1752 ++textlock;
1753 *cp = NUL;
1754 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1755 retval = 0;
1756 else
1758 /* If the result is a number, just return the number. */
1759 if (tv.v_type == VAR_NUMBER)
1760 retval = tv.vval.v_number;
1761 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1762 retval = 0;
1763 else
1765 /* If the result is a string, check if there is a non-digit before
1766 * the number. */
1767 s = tv.vval.v_string;
1768 if (!VIM_ISDIGIT(*s) && *s != '-')
1769 *cp = *s++;
1770 retval = atol((char *)s);
1772 clear_tv(&tv);
1774 --emsg_off;
1775 if (use_sandbox)
1776 --sandbox;
1777 --textlock;
1779 return retval;
1781 #endif
1784 * ":let" list all variable values
1785 * ":let var1 var2" list variable values
1786 * ":let var = expr" assignment command.
1787 * ":let var += expr" assignment command.
1788 * ":let var -= expr" assignment command.
1789 * ":let var .= expr" assignment command.
1790 * ":let [var1, var2] = expr" unpack list.
1792 void
1793 ex_let(eap)
1794 exarg_T *eap;
1796 char_u *arg = eap->arg;
1797 char_u *expr = NULL;
1798 typval_T rettv;
1799 int i;
1800 int var_count = 0;
1801 int semicolon = 0;
1802 char_u op[2];
1803 char_u *argend;
1804 int first = TRUE;
1806 argend = skip_var_list(arg, &var_count, &semicolon);
1807 if (argend == NULL)
1808 return;
1809 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1810 --argend;
1811 expr = vim_strchr(argend, '=');
1812 if (expr == NULL)
1815 * ":let" without "=": list variables
1817 if (*arg == '[')
1818 EMSG(_(e_invarg));
1819 else if (!ends_excmd(*arg))
1820 /* ":let var1 var2" */
1821 arg = list_arg_vars(eap, arg, &first);
1822 else if (!eap->skip)
1824 /* ":let" */
1825 list_glob_vars(&first);
1826 list_buf_vars(&first);
1827 list_win_vars(&first);
1828 #ifdef FEAT_WINDOWS
1829 list_tab_vars(&first);
1830 #endif
1831 list_script_vars(&first);
1832 list_func_vars(&first);
1833 list_vim_vars(&first);
1835 eap->nextcmd = check_nextcmd(arg);
1837 else
1839 op[0] = '=';
1840 op[1] = NUL;
1841 if (expr > argend)
1843 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1844 op[0] = expr[-1]; /* +=, -= or .= */
1846 expr = skipwhite(expr + 1);
1848 if (eap->skip)
1849 ++emsg_skip;
1850 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1851 if (eap->skip)
1853 if (i != FAIL)
1854 clear_tv(&rettv);
1855 --emsg_skip;
1857 else if (i != FAIL)
1859 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1860 op);
1861 clear_tv(&rettv);
1867 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1868 * Handles both "var" with any type and "[var, var; var]" with a list type.
1869 * When "nextchars" is not NULL it points to a string with characters that
1870 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1871 * or concatenate.
1872 * Returns OK or FAIL;
1874 static int
1875 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1876 char_u *arg_start;
1877 typval_T *tv;
1878 int copy; /* copy values from "tv", don't move */
1879 int semicolon; /* from skip_var_list() */
1880 int var_count; /* from skip_var_list() */
1881 char_u *nextchars;
1883 char_u *arg = arg_start;
1884 list_T *l;
1885 int i;
1886 listitem_T *item;
1887 typval_T ltv;
1889 if (*arg != '[')
1892 * ":let var = expr" or ":for var in list"
1894 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1895 return FAIL;
1896 return OK;
1900 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1902 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1904 EMSG(_(e_listreq));
1905 return FAIL;
1908 i = list_len(l);
1909 if (semicolon == 0 && var_count < i)
1911 EMSG(_("E687: Less targets than List items"));
1912 return FAIL;
1914 if (var_count - semicolon > i)
1916 EMSG(_("E688: More targets than List items"));
1917 return FAIL;
1920 item = l->lv_first;
1921 while (*arg != ']')
1923 arg = skipwhite(arg + 1);
1924 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1925 item = item->li_next;
1926 if (arg == NULL)
1927 return FAIL;
1929 arg = skipwhite(arg);
1930 if (*arg == ';')
1932 /* Put the rest of the list (may be empty) in the var after ';'.
1933 * Create a new list for this. */
1934 l = list_alloc();
1935 if (l == NULL)
1936 return FAIL;
1937 while (item != NULL)
1939 list_append_tv(l, &item->li_tv);
1940 item = item->li_next;
1943 ltv.v_type = VAR_LIST;
1944 ltv.v_lock = 0;
1945 ltv.vval.v_list = l;
1946 l->lv_refcount = 1;
1948 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1949 (char_u *)"]", nextchars);
1950 clear_tv(&ltv);
1951 if (arg == NULL)
1952 return FAIL;
1953 break;
1955 else if (*arg != ',' && *arg != ']')
1957 EMSG2(_(e_intern2), "ex_let_vars()");
1958 return FAIL;
1962 return OK;
1966 * Skip over assignable variable "var" or list of variables "[var, var]".
1967 * Used for ":let varvar = expr" and ":for varvar in expr".
1968 * For "[var, var]" increment "*var_count" for each variable.
1969 * for "[var, var; var]" set "semicolon".
1970 * Return NULL for an error.
1972 static char_u *
1973 skip_var_list(arg, var_count, semicolon)
1974 char_u *arg;
1975 int *var_count;
1976 int *semicolon;
1978 char_u *p, *s;
1980 if (*arg == '[')
1982 /* "[var, var]": find the matching ']'. */
1983 p = arg;
1984 for (;;)
1986 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
1987 s = skip_var_one(p);
1988 if (s == p)
1990 EMSG2(_(e_invarg2), p);
1991 return NULL;
1993 ++*var_count;
1995 p = skipwhite(s);
1996 if (*p == ']')
1997 break;
1998 else if (*p == ';')
2000 if (*semicolon == 1)
2002 EMSG(_("Double ; in list of variables"));
2003 return NULL;
2005 *semicolon = 1;
2007 else if (*p != ',')
2009 EMSG2(_(e_invarg2), p);
2010 return NULL;
2013 return p + 1;
2015 else
2016 return skip_var_one(arg);
2020 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
2021 * l[idx].
2023 static char_u *
2024 skip_var_one(arg)
2025 char_u *arg;
2027 if (*arg == '@' && arg[1] != NUL)
2028 return arg + 2;
2029 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
2030 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2034 * List variables for hashtab "ht" with prefix "prefix".
2035 * If "empty" is TRUE also list NULL strings as empty strings.
2037 static void
2038 list_hashtable_vars(ht, prefix, empty, first)
2039 hashtab_T *ht;
2040 char_u *prefix;
2041 int empty;
2042 int *first;
2044 hashitem_T *hi;
2045 dictitem_T *di;
2046 int todo;
2048 todo = (int)ht->ht_used;
2049 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
2051 if (!HASHITEM_EMPTY(hi))
2053 --todo;
2054 di = HI2DI(hi);
2055 if (empty || di->di_tv.v_type != VAR_STRING
2056 || di->di_tv.vval.v_string != NULL)
2057 list_one_var(di, prefix, first);
2063 * List global variables.
2065 static void
2066 list_glob_vars(first)
2067 int *first;
2069 list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
2073 * List buffer variables.
2075 static void
2076 list_buf_vars(first)
2077 int *first;
2079 char_u numbuf[NUMBUFLEN];
2081 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:",
2082 TRUE, first);
2084 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
2085 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
2086 numbuf, first);
2090 * List window variables.
2092 static void
2093 list_win_vars(first)
2094 int *first;
2096 list_hashtable_vars(&curwin->w_vars.dv_hashtab,
2097 (char_u *)"w:", TRUE, first);
2100 #ifdef FEAT_WINDOWS
2102 * List tab page variables.
2104 static void
2105 list_tab_vars(first)
2106 int *first;
2108 list_hashtable_vars(&curtab->tp_vars.dv_hashtab,
2109 (char_u *)"t:", TRUE, first);
2111 #endif
2114 * List Vim variables.
2116 static void
2117 list_vim_vars(first)
2118 int *first;
2120 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2124 * List script-local variables, if there is a script.
2126 static void
2127 list_script_vars(first)
2128 int *first;
2130 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2131 list_hashtable_vars(&SCRIPT_VARS(current_SID),
2132 (char_u *)"s:", FALSE, first);
2136 * List function variables, if there is a function.
2138 static void
2139 list_func_vars(first)
2140 int *first;
2142 if (current_funccal != NULL)
2143 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2144 (char_u *)"l:", FALSE, first);
2148 * List variables in "arg".
2150 static char_u *
2151 list_arg_vars(eap, arg, first)
2152 exarg_T *eap;
2153 char_u *arg;
2154 int *first;
2156 int error = FALSE;
2157 int len;
2158 char_u *name;
2159 char_u *name_start;
2160 char_u *arg_subsc;
2161 char_u *tofree;
2162 typval_T tv;
2164 while (!ends_excmd(*arg) && !got_int)
2166 if (error || eap->skip)
2168 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2169 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2171 emsg_severe = TRUE;
2172 EMSG(_(e_trailing));
2173 break;
2176 else
2178 /* get_name_len() takes care of expanding curly braces */
2179 name_start = name = arg;
2180 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2181 if (len <= 0)
2183 /* This is mainly to keep test 49 working: when expanding
2184 * curly braces fails overrule the exception error message. */
2185 if (len < 0 && !aborting())
2187 emsg_severe = TRUE;
2188 EMSG2(_(e_invarg2), arg);
2189 break;
2191 error = TRUE;
2193 else
2195 if (tofree != NULL)
2196 name = tofree;
2197 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2198 error = TRUE;
2199 else
2201 /* handle d.key, l[idx], f(expr) */
2202 arg_subsc = arg;
2203 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2204 error = TRUE;
2205 else
2207 if (arg == arg_subsc && len == 2 && name[1] == ':')
2209 switch (*name)
2211 case 'g': list_glob_vars(first); break;
2212 case 'b': list_buf_vars(first); break;
2213 case 'w': list_win_vars(first); break;
2214 #ifdef FEAT_WINDOWS
2215 case 't': list_tab_vars(first); break;
2216 #endif
2217 case 'v': list_vim_vars(first); break;
2218 case 's': list_script_vars(first); break;
2219 case 'l': list_func_vars(first); break;
2220 default:
2221 EMSG2(_("E738: Can't list variables for %s"), name);
2224 else
2226 char_u numbuf[NUMBUFLEN];
2227 char_u *tf;
2228 int c;
2229 char_u *s;
2231 s = echo_string(&tv, &tf, numbuf, 0);
2232 c = *arg;
2233 *arg = NUL;
2234 list_one_var_a((char_u *)"",
2235 arg == arg_subsc ? name : name_start,
2236 tv.v_type,
2237 s == NULL ? (char_u *)"" : s,
2238 first);
2239 *arg = c;
2240 vim_free(tf);
2242 clear_tv(&tv);
2247 vim_free(tofree);
2250 arg = skipwhite(arg);
2253 return arg;
2257 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2258 * Returns a pointer to the char just after the var name.
2259 * Returns NULL if there is an error.
2261 static char_u *
2262 ex_let_one(arg, tv, copy, endchars, op)
2263 char_u *arg; /* points to variable name */
2264 typval_T *tv; /* value to assign to variable */
2265 int copy; /* copy value from "tv" */
2266 char_u *endchars; /* valid chars after variable name or NULL */
2267 char_u *op; /* "+", "-", "." or NULL*/
2269 int c1;
2270 char_u *name;
2271 char_u *p;
2272 char_u *arg_end = NULL;
2273 int len;
2274 int opt_flags;
2275 char_u *tofree = NULL;
2278 * ":let $VAR = expr": Set environment variable.
2280 if (*arg == '$')
2282 /* Find the end of the name. */
2283 ++arg;
2284 name = arg;
2285 len = get_env_len(&arg);
2286 if (len == 0)
2287 EMSG2(_(e_invarg2), name - 1);
2288 else
2290 if (op != NULL && (*op == '+' || *op == '-'))
2291 EMSG2(_(e_letwrong), op);
2292 else if (endchars != NULL
2293 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2294 EMSG(_(e_letunexp));
2295 else
2297 c1 = name[len];
2298 name[len] = NUL;
2299 p = get_tv_string_chk(tv);
2300 if (p != NULL && op != NULL && *op == '.')
2302 int mustfree = FALSE;
2303 char_u *s = vim_getenv(name, &mustfree);
2305 if (s != NULL)
2307 p = tofree = concat_str(s, p);
2308 if (mustfree)
2309 vim_free(s);
2312 if (p != NULL)
2314 vim_setenv(name, p);
2315 if (STRICMP(name, "HOME") == 0)
2316 init_homedir();
2317 else if (didset_vim && STRICMP(name, "VIM") == 0)
2318 didset_vim = FALSE;
2319 else if (didset_vimruntime
2320 && STRICMP(name, "VIMRUNTIME") == 0)
2321 didset_vimruntime = FALSE;
2322 arg_end = arg;
2324 name[len] = c1;
2325 vim_free(tofree);
2331 * ":let &option = expr": Set option value.
2332 * ":let &l:option = expr": Set local option value.
2333 * ":let &g:option = expr": Set global option value.
2335 else if (*arg == '&')
2337 /* Find the end of the name. */
2338 p = find_option_end(&arg, &opt_flags);
2339 if (p == NULL || (endchars != NULL
2340 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2341 EMSG(_(e_letunexp));
2342 else
2344 long n;
2345 int opt_type;
2346 long numval;
2347 char_u *stringval = NULL;
2348 char_u *s;
2350 c1 = *p;
2351 *p = NUL;
2353 n = get_tv_number(tv);
2354 s = get_tv_string_chk(tv); /* != NULL if number or string */
2355 if (s != NULL && op != NULL && *op != '=')
2357 opt_type = get_option_value(arg, &numval,
2358 &stringval, opt_flags);
2359 if ((opt_type == 1 && *op == '.')
2360 || (opt_type == 0 && *op != '.'))
2361 EMSG2(_(e_letwrong), op);
2362 else
2364 if (opt_type == 1) /* number */
2366 if (*op == '+')
2367 n = numval + n;
2368 else
2369 n = numval - n;
2371 else if (opt_type == 0 && stringval != NULL) /* string */
2373 s = concat_str(stringval, s);
2374 vim_free(stringval);
2375 stringval = s;
2379 if (s != NULL)
2381 set_option_value(arg, n, s, opt_flags);
2382 arg_end = p;
2384 *p = c1;
2385 vim_free(stringval);
2390 * ":let @r = expr": Set register contents.
2392 else if (*arg == '@')
2394 ++arg;
2395 if (op != NULL && (*op == '+' || *op == '-'))
2396 EMSG2(_(e_letwrong), op);
2397 else if (endchars != NULL
2398 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2399 EMSG(_(e_letunexp));
2400 else
2402 char_u *ptofree = NULL;
2403 char_u *s;
2405 p = get_tv_string_chk(tv);
2406 if (p != NULL && op != NULL && *op == '.')
2408 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2409 if (s != NULL)
2411 p = ptofree = concat_str(s, p);
2412 vim_free(s);
2415 if (p != NULL)
2417 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2418 arg_end = arg + 1;
2420 vim_free(ptofree);
2425 * ":let var = expr": Set internal variable.
2426 * ":let {expr} = expr": Idem, name made with curly braces
2428 else if (eval_isnamec1(*arg) || *arg == '{')
2430 lval_T lv;
2432 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2433 if (p != NULL && lv.ll_name != NULL)
2435 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2436 EMSG(_(e_letunexp));
2437 else
2439 set_var_lval(&lv, p, tv, copy, op);
2440 arg_end = p;
2443 clear_lval(&lv);
2446 else
2447 EMSG2(_(e_invarg2), arg);
2449 return arg_end;
2453 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2455 static int
2456 check_changedtick(arg)
2457 char_u *arg;
2459 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2461 EMSG2(_(e_readonlyvar), arg);
2462 return TRUE;
2464 return FALSE;
2468 * Get an lval: variable, Dict item or List item that can be assigned a value
2469 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2470 * "name.key", "name.key[expr]" etc.
2471 * Indexing only works if "name" is an existing List or Dictionary.
2472 * "name" points to the start of the name.
2473 * If "rettv" is not NULL it points to the value to be assigned.
2474 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2475 * wrong; must end in space or cmd separator.
2477 * Returns a pointer to just after the name, including indexes.
2478 * When an evaluation error occurs "lp->ll_name" is NULL;
2479 * Returns NULL for a parsing error. Still need to free items in "lp"!
2481 static char_u *
2482 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2483 char_u *name;
2484 typval_T *rettv;
2485 lval_T *lp;
2486 int unlet;
2487 int skip;
2488 int quiet; /* don't give error messages */
2489 int fne_flags; /* flags for find_name_end() */
2491 char_u *p;
2492 char_u *expr_start, *expr_end;
2493 int cc;
2494 dictitem_T *v;
2495 typval_T var1;
2496 typval_T var2;
2497 int empty1 = FALSE;
2498 listitem_T *ni;
2499 char_u *key = NULL;
2500 int len;
2501 hashtab_T *ht;
2503 /* Clear everything in "lp". */
2504 vim_memset(lp, 0, sizeof(lval_T));
2506 if (skip)
2508 /* When skipping just find the end of the name. */
2509 lp->ll_name = name;
2510 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2513 /* Find the end of the name. */
2514 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2515 if (expr_start != NULL)
2517 /* Don't expand the name when we already know there is an error. */
2518 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2519 && *p != '[' && *p != '.')
2521 EMSG(_(e_trailing));
2522 return NULL;
2525 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2526 if (lp->ll_exp_name == NULL)
2528 /* Report an invalid expression in braces, unless the
2529 * expression evaluation has been cancelled due to an
2530 * aborting error, an interrupt, or an exception. */
2531 if (!aborting() && !quiet)
2533 emsg_severe = TRUE;
2534 EMSG2(_(e_invarg2), name);
2535 return NULL;
2538 lp->ll_name = lp->ll_exp_name;
2540 else
2541 lp->ll_name = name;
2543 /* Without [idx] or .key we are done. */
2544 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2545 return p;
2547 cc = *p;
2548 *p = NUL;
2549 v = find_var(lp->ll_name, &ht);
2550 if (v == NULL && !quiet)
2551 EMSG2(_(e_undefvar), lp->ll_name);
2552 *p = cc;
2553 if (v == NULL)
2554 return NULL;
2557 * Loop until no more [idx] or .key is following.
2559 lp->ll_tv = &v->di_tv;
2560 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2562 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2563 && !(lp->ll_tv->v_type == VAR_DICT
2564 && lp->ll_tv->vval.v_dict != NULL))
2566 if (!quiet)
2567 EMSG(_("E689: Can only index a List or Dictionary"));
2568 return NULL;
2570 if (lp->ll_range)
2572 if (!quiet)
2573 EMSG(_("E708: [:] must come last"));
2574 return NULL;
2577 len = -1;
2578 if (*p == '.')
2580 key = p + 1;
2581 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2583 if (len == 0)
2585 if (!quiet)
2586 EMSG(_(e_emptykey));
2587 return NULL;
2589 p = key + len;
2591 else
2593 /* Get the index [expr] or the first index [expr: ]. */
2594 p = skipwhite(p + 1);
2595 if (*p == ':')
2596 empty1 = TRUE;
2597 else
2599 empty1 = FALSE;
2600 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2601 return NULL;
2602 if (get_tv_string_chk(&var1) == NULL)
2604 /* not a number or string */
2605 clear_tv(&var1);
2606 return NULL;
2610 /* Optionally get the second index [ :expr]. */
2611 if (*p == ':')
2613 if (lp->ll_tv->v_type == VAR_DICT)
2615 if (!quiet)
2616 EMSG(_(e_dictrange));
2617 if (!empty1)
2618 clear_tv(&var1);
2619 return NULL;
2621 if (rettv != NULL && (rettv->v_type != VAR_LIST
2622 || rettv->vval.v_list == NULL))
2624 if (!quiet)
2625 EMSG(_("E709: [:] requires a List value"));
2626 if (!empty1)
2627 clear_tv(&var1);
2628 return NULL;
2630 p = skipwhite(p + 1);
2631 if (*p == ']')
2632 lp->ll_empty2 = TRUE;
2633 else
2635 lp->ll_empty2 = FALSE;
2636 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2638 if (!empty1)
2639 clear_tv(&var1);
2640 return NULL;
2642 if (get_tv_string_chk(&var2) == NULL)
2644 /* not a number or string */
2645 if (!empty1)
2646 clear_tv(&var1);
2647 clear_tv(&var2);
2648 return NULL;
2651 lp->ll_range = TRUE;
2653 else
2654 lp->ll_range = FALSE;
2656 if (*p != ']')
2658 if (!quiet)
2659 EMSG(_(e_missbrac));
2660 if (!empty1)
2661 clear_tv(&var1);
2662 if (lp->ll_range && !lp->ll_empty2)
2663 clear_tv(&var2);
2664 return NULL;
2667 /* Skip to past ']'. */
2668 ++p;
2671 if (lp->ll_tv->v_type == VAR_DICT)
2673 if (len == -1)
2675 /* "[key]": get key from "var1" */
2676 key = get_tv_string(&var1); /* is number or string */
2677 if (*key == NUL)
2679 if (!quiet)
2680 EMSG(_(e_emptykey));
2681 clear_tv(&var1);
2682 return NULL;
2685 lp->ll_list = NULL;
2686 lp->ll_dict = lp->ll_tv->vval.v_dict;
2687 lp->ll_di = dict_find(lp->ll_dict, key, len);
2688 if (lp->ll_di == NULL)
2690 /* Key does not exist in dict: may need to add it. */
2691 if (*p == '[' || *p == '.' || unlet)
2693 if (!quiet)
2694 EMSG2(_(e_dictkey), key);
2695 if (len == -1)
2696 clear_tv(&var1);
2697 return NULL;
2699 if (len == -1)
2700 lp->ll_newkey = vim_strsave(key);
2701 else
2702 lp->ll_newkey = vim_strnsave(key, len);
2703 if (len == -1)
2704 clear_tv(&var1);
2705 if (lp->ll_newkey == NULL)
2706 p = NULL;
2707 break;
2709 if (len == -1)
2710 clear_tv(&var1);
2711 lp->ll_tv = &lp->ll_di->di_tv;
2713 else
2716 * Get the number and item for the only or first index of the List.
2718 if (empty1)
2719 lp->ll_n1 = 0;
2720 else
2722 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2723 clear_tv(&var1);
2725 lp->ll_dict = NULL;
2726 lp->ll_list = lp->ll_tv->vval.v_list;
2727 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2728 if (lp->ll_li == NULL)
2730 if (lp->ll_n1 < 0)
2732 lp->ll_n1 = 0;
2733 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2736 if (lp->ll_li == NULL)
2738 if (lp->ll_range && !lp->ll_empty2)
2739 clear_tv(&var2);
2740 return NULL;
2744 * May need to find the item or absolute index for the second
2745 * index of a range.
2746 * When no index given: "lp->ll_empty2" is TRUE.
2747 * Otherwise "lp->ll_n2" is set to the second index.
2749 if (lp->ll_range && !lp->ll_empty2)
2751 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2752 clear_tv(&var2);
2753 if (lp->ll_n2 < 0)
2755 ni = list_find(lp->ll_list, lp->ll_n2);
2756 if (ni == NULL)
2757 return NULL;
2758 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2761 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2762 if (lp->ll_n1 < 0)
2763 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2764 if (lp->ll_n2 < lp->ll_n1)
2765 return NULL;
2768 lp->ll_tv = &lp->ll_li->li_tv;
2772 return p;
2776 * Clear lval "lp" that was filled by get_lval().
2778 static void
2779 clear_lval(lp)
2780 lval_T *lp;
2782 vim_free(lp->ll_exp_name);
2783 vim_free(lp->ll_newkey);
2787 * Set a variable that was parsed by get_lval() to "rettv".
2788 * "endp" points to just after the parsed name.
2789 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2791 static void
2792 set_var_lval(lp, endp, rettv, copy, op)
2793 lval_T *lp;
2794 char_u *endp;
2795 typval_T *rettv;
2796 int copy;
2797 char_u *op;
2799 int cc;
2800 listitem_T *ri;
2801 dictitem_T *di;
2803 if (lp->ll_tv == NULL)
2805 if (!check_changedtick(lp->ll_name))
2807 cc = *endp;
2808 *endp = NUL;
2809 if (op != NULL && *op != '=')
2811 typval_T tv;
2813 /* handle +=, -= and .= */
2814 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2815 &tv, TRUE) == OK)
2817 if (tv_op(&tv, rettv, op) == OK)
2818 set_var(lp->ll_name, &tv, FALSE);
2819 clear_tv(&tv);
2822 else
2823 set_var(lp->ll_name, rettv, copy);
2824 *endp = cc;
2827 else if (tv_check_lock(lp->ll_newkey == NULL
2828 ? lp->ll_tv->v_lock
2829 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2831 else if (lp->ll_range)
2834 * Assign the List values to the list items.
2836 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2838 if (op != NULL && *op != '=')
2839 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2840 else
2842 clear_tv(&lp->ll_li->li_tv);
2843 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2845 ri = ri->li_next;
2846 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2847 break;
2848 if (lp->ll_li->li_next == NULL)
2850 /* Need to add an empty item. */
2851 if (list_append_number(lp->ll_list, 0) == FAIL)
2853 ri = NULL;
2854 break;
2857 lp->ll_li = lp->ll_li->li_next;
2858 ++lp->ll_n1;
2860 if (ri != NULL)
2861 EMSG(_("E710: List value has more items than target"));
2862 else if (lp->ll_empty2
2863 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2864 : lp->ll_n1 != lp->ll_n2)
2865 EMSG(_("E711: List value has not enough items"));
2867 else
2870 * Assign to a List or Dictionary item.
2872 if (lp->ll_newkey != NULL)
2874 if (op != NULL && *op != '=')
2876 EMSG2(_(e_letwrong), op);
2877 return;
2880 /* Need to add an item to the Dictionary. */
2881 di = dictitem_alloc(lp->ll_newkey);
2882 if (di == NULL)
2883 return;
2884 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2886 vim_free(di);
2887 return;
2889 lp->ll_tv = &di->di_tv;
2891 else if (op != NULL && *op != '=')
2893 tv_op(lp->ll_tv, rettv, op);
2894 return;
2896 else
2897 clear_tv(lp->ll_tv);
2900 * Assign the value to the variable or list item.
2902 if (copy)
2903 copy_tv(rettv, lp->ll_tv);
2904 else
2906 *lp->ll_tv = *rettv;
2907 lp->ll_tv->v_lock = 0;
2908 init_tv(rettv);
2914 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2915 * Returns OK or FAIL.
2917 static int
2918 tv_op(tv1, tv2, op)
2919 typval_T *tv1;
2920 typval_T *tv2;
2921 char_u *op;
2923 long n;
2924 char_u numbuf[NUMBUFLEN];
2925 char_u *s;
2927 /* Can't do anything with a Funcref or a Dict on the right. */
2928 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2930 switch (tv1->v_type)
2932 case VAR_DICT:
2933 case VAR_FUNC:
2934 break;
2936 case VAR_LIST:
2937 if (*op != '+' || tv2->v_type != VAR_LIST)
2938 break;
2939 /* List += List */
2940 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2941 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2942 return OK;
2944 case VAR_NUMBER:
2945 case VAR_STRING:
2946 if (tv2->v_type == VAR_LIST)
2947 break;
2948 if (*op == '+' || *op == '-')
2950 /* nr += nr or nr -= nr*/
2951 n = get_tv_number(tv1);
2952 #ifdef FEAT_FLOAT
2953 if (tv2->v_type == VAR_FLOAT)
2955 float_T f = n;
2957 if (*op == '+')
2958 f += tv2->vval.v_float;
2959 else
2960 f -= tv2->vval.v_float;
2961 clear_tv(tv1);
2962 tv1->v_type = VAR_FLOAT;
2963 tv1->vval.v_float = f;
2965 else
2966 #endif
2968 if (*op == '+')
2969 n += get_tv_number(tv2);
2970 else
2971 n -= get_tv_number(tv2);
2972 clear_tv(tv1);
2973 tv1->v_type = VAR_NUMBER;
2974 tv1->vval.v_number = n;
2977 else
2979 if (tv2->v_type == VAR_FLOAT)
2980 break;
2982 /* str .= str */
2983 s = get_tv_string(tv1);
2984 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2985 clear_tv(tv1);
2986 tv1->v_type = VAR_STRING;
2987 tv1->vval.v_string = s;
2989 return OK;
2991 #ifdef FEAT_FLOAT
2992 case VAR_FLOAT:
2994 float_T f;
2996 if (*op == '.' || (tv2->v_type != VAR_FLOAT
2997 && tv2->v_type != VAR_NUMBER
2998 && tv2->v_type != VAR_STRING))
2999 break;
3000 if (tv2->v_type == VAR_FLOAT)
3001 f = tv2->vval.v_float;
3002 else
3003 f = get_tv_number(tv2);
3004 if (*op == '+')
3005 tv1->vval.v_float += f;
3006 else
3007 tv1->vval.v_float -= f;
3009 return OK;
3010 #endif
3014 EMSG2(_(e_letwrong), op);
3015 return FAIL;
3019 * Add a watcher to a list.
3021 static void
3022 list_add_watch(l, lw)
3023 list_T *l;
3024 listwatch_T *lw;
3026 lw->lw_next = l->lv_watch;
3027 l->lv_watch = lw;
3031 * Remove a watcher from a list.
3032 * No warning when it isn't found...
3034 static void
3035 list_rem_watch(l, lwrem)
3036 list_T *l;
3037 listwatch_T *lwrem;
3039 listwatch_T *lw, **lwp;
3041 lwp = &l->lv_watch;
3042 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3044 if (lw == lwrem)
3046 *lwp = lw->lw_next;
3047 break;
3049 lwp = &lw->lw_next;
3054 * Just before removing an item from a list: advance watchers to the next
3055 * item.
3057 static void
3058 list_fix_watch(l, item)
3059 list_T *l;
3060 listitem_T *item;
3062 listwatch_T *lw;
3064 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3065 if (lw->lw_item == item)
3066 lw->lw_item = item->li_next;
3070 * Evaluate the expression used in a ":for var in expr" command.
3071 * "arg" points to "var".
3072 * Set "*errp" to TRUE for an error, FALSE otherwise;
3073 * Return a pointer that holds the info. Null when there is an error.
3075 void *
3076 eval_for_line(arg, errp, nextcmdp, skip)
3077 char_u *arg;
3078 int *errp;
3079 char_u **nextcmdp;
3080 int skip;
3082 forinfo_T *fi;
3083 char_u *expr;
3084 typval_T tv;
3085 list_T *l;
3087 *errp = TRUE; /* default: there is an error */
3089 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
3090 if (fi == NULL)
3091 return NULL;
3093 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
3094 if (expr == NULL)
3095 return fi;
3097 expr = skipwhite(expr);
3098 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
3100 EMSG(_("E690: Missing \"in\" after :for"));
3101 return fi;
3104 if (skip)
3105 ++emsg_skip;
3106 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
3108 *errp = FALSE;
3109 if (!skip)
3111 l = tv.vval.v_list;
3112 if (tv.v_type != VAR_LIST || l == NULL)
3114 EMSG(_(e_listreq));
3115 clear_tv(&tv);
3117 else
3119 /* No need to increment the refcount, it's already set for the
3120 * list being used in "tv". */
3121 fi->fi_list = l;
3122 list_add_watch(l, &fi->fi_lw);
3123 fi->fi_lw.lw_item = l->lv_first;
3127 if (skip)
3128 --emsg_skip;
3130 return fi;
3134 * Use the first item in a ":for" list. Advance to the next.
3135 * Assign the values to the variable (list). "arg" points to the first one.
3136 * Return TRUE when a valid item was found, FALSE when at end of list or
3137 * something wrong.
3140 next_for_item(fi_void, arg)
3141 void *fi_void;
3142 char_u *arg;
3144 forinfo_T *fi = (forinfo_T *)fi_void;
3145 int result;
3146 listitem_T *item;
3148 item = fi->fi_lw.lw_item;
3149 if (item == NULL)
3150 result = FALSE;
3151 else
3153 fi->fi_lw.lw_item = item->li_next;
3154 result = (ex_let_vars(arg, &item->li_tv, TRUE,
3155 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3157 return result;
3161 * Free the structure used to store info used by ":for".
3163 void
3164 free_for_info(fi_void)
3165 void *fi_void;
3167 forinfo_T *fi = (forinfo_T *)fi_void;
3169 if (fi != NULL && fi->fi_list != NULL)
3171 list_rem_watch(fi->fi_list, &fi->fi_lw);
3172 list_unref(fi->fi_list);
3174 vim_free(fi);
3177 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3179 void
3180 set_context_for_expression(xp, arg, cmdidx)
3181 expand_T *xp;
3182 char_u *arg;
3183 cmdidx_T cmdidx;
3185 int got_eq = FALSE;
3186 int c;
3187 char_u *p;
3189 if (cmdidx == CMD_let)
3191 xp->xp_context = EXPAND_USER_VARS;
3192 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3194 /* ":let var1 var2 ...": find last space. */
3195 for (p = arg + STRLEN(arg); p >= arg; )
3197 xp->xp_pattern = p;
3198 mb_ptr_back(arg, p);
3199 if (vim_iswhite(*p))
3200 break;
3202 return;
3205 else
3206 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3207 : EXPAND_EXPRESSION;
3208 while ((xp->xp_pattern = vim_strpbrk(arg,
3209 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3211 c = *xp->xp_pattern;
3212 if (c == '&')
3214 c = xp->xp_pattern[1];
3215 if (c == '&')
3217 ++xp->xp_pattern;
3218 xp->xp_context = cmdidx != CMD_let || got_eq
3219 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3221 else if (c != ' ')
3223 xp->xp_context = EXPAND_SETTINGS;
3224 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3225 xp->xp_pattern += 2;
3229 else if (c == '$')
3231 /* environment variable */
3232 xp->xp_context = EXPAND_ENV_VARS;
3234 else if (c == '=')
3236 got_eq = TRUE;
3237 xp->xp_context = EXPAND_EXPRESSION;
3239 else if (c == '<'
3240 && xp->xp_context == EXPAND_FUNCTIONS
3241 && vim_strchr(xp->xp_pattern, '(') == NULL)
3243 /* Function name can start with "<SNR>" */
3244 break;
3246 else if (cmdidx != CMD_let || got_eq)
3248 if (c == '"') /* string */
3250 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3251 if (c == '\\' && xp->xp_pattern[1] != NUL)
3252 ++xp->xp_pattern;
3253 xp->xp_context = EXPAND_NOTHING;
3255 else if (c == '\'') /* literal string */
3257 /* Trick: '' is like stopping and starting a literal string. */
3258 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3259 /* skip */ ;
3260 xp->xp_context = EXPAND_NOTHING;
3262 else if (c == '|')
3264 if (xp->xp_pattern[1] == '|')
3266 ++xp->xp_pattern;
3267 xp->xp_context = EXPAND_EXPRESSION;
3269 else
3270 xp->xp_context = EXPAND_COMMANDS;
3272 else
3273 xp->xp_context = EXPAND_EXPRESSION;
3275 else
3276 /* Doesn't look like something valid, expand as an expression
3277 * anyway. */
3278 xp->xp_context = EXPAND_EXPRESSION;
3279 arg = xp->xp_pattern;
3280 if (*arg != NUL)
3281 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3282 /* skip */ ;
3284 xp->xp_pattern = arg;
3287 #endif /* FEAT_CMDL_COMPL */
3290 * ":1,25call func(arg1, arg2)" function call.
3292 void
3293 ex_call(eap)
3294 exarg_T *eap;
3296 char_u *arg = eap->arg;
3297 char_u *startarg;
3298 char_u *name;
3299 char_u *tofree;
3300 int len;
3301 typval_T rettv;
3302 linenr_T lnum;
3303 int doesrange;
3304 int failed = FALSE;
3305 funcdict_T fudi;
3307 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3308 if (fudi.fd_newkey != NULL)
3310 /* Still need to give an error message for missing key. */
3311 EMSG2(_(e_dictkey), fudi.fd_newkey);
3312 vim_free(fudi.fd_newkey);
3314 if (tofree == NULL)
3315 return;
3317 /* Increase refcount on dictionary, it could get deleted when evaluating
3318 * the arguments. */
3319 if (fudi.fd_dict != NULL)
3320 ++fudi.fd_dict->dv_refcount;
3322 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3323 len = (int)STRLEN(tofree);
3324 name = deref_func_name(tofree, &len);
3326 /* Skip white space to allow ":call func ()". Not good, but required for
3327 * backward compatibility. */
3328 startarg = skipwhite(arg);
3329 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3331 if (*startarg != '(')
3333 EMSG2(_("E107: Missing parentheses: %s"), eap->arg);
3334 goto end;
3338 * When skipping, evaluate the function once, to find the end of the
3339 * arguments.
3340 * When the function takes a range, this is discovered after the first
3341 * call, and the loop is broken.
3343 if (eap->skip)
3345 ++emsg_skip;
3346 lnum = eap->line2; /* do it once, also with an invalid range */
3348 else
3349 lnum = eap->line1;
3350 for ( ; lnum <= eap->line2; ++lnum)
3352 if (!eap->skip && eap->addr_count > 0)
3354 curwin->w_cursor.lnum = lnum;
3355 curwin->w_cursor.col = 0;
3357 arg = startarg;
3358 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3359 eap->line1, eap->line2, &doesrange,
3360 !eap->skip, fudi.fd_dict) == FAIL)
3362 failed = TRUE;
3363 break;
3366 /* Handle a function returning a Funcref, Dictionary or List. */
3367 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3369 failed = TRUE;
3370 break;
3373 clear_tv(&rettv);
3374 if (doesrange || eap->skip)
3375 break;
3377 /* Stop when immediately aborting on error, or when an interrupt
3378 * occurred or an exception was thrown but not caught.
3379 * get_func_tv() returned OK, so that the check for trailing
3380 * characters below is executed. */
3381 if (aborting())
3382 break;
3384 if (eap->skip)
3385 --emsg_skip;
3387 if (!failed)
3389 /* Check for trailing illegal characters and a following command. */
3390 if (!ends_excmd(*arg))
3392 emsg_severe = TRUE;
3393 EMSG(_(e_trailing));
3395 else
3396 eap->nextcmd = check_nextcmd(arg);
3399 end:
3400 dict_unref(fudi.fd_dict);
3401 vim_free(tofree);
3405 * ":unlet[!] var1 ... " command.
3407 void
3408 ex_unlet(eap)
3409 exarg_T *eap;
3411 ex_unletlock(eap, eap->arg, 0);
3415 * ":lockvar" and ":unlockvar" commands
3417 void
3418 ex_lockvar(eap)
3419 exarg_T *eap;
3421 char_u *arg = eap->arg;
3422 int deep = 2;
3424 if (eap->forceit)
3425 deep = -1;
3426 else if (vim_isdigit(*arg))
3428 deep = getdigits(&arg);
3429 arg = skipwhite(arg);
3432 ex_unletlock(eap, arg, deep);
3436 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3438 static void
3439 ex_unletlock(eap, argstart, deep)
3440 exarg_T *eap;
3441 char_u *argstart;
3442 int deep;
3444 char_u *arg = argstart;
3445 char_u *name_end;
3446 int error = FALSE;
3447 lval_T lv;
3451 /* Parse the name and find the end. */
3452 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3453 FNE_CHECK_START);
3454 if (lv.ll_name == NULL)
3455 error = TRUE; /* error but continue parsing */
3456 if (name_end == NULL || (!vim_iswhite(*name_end)
3457 && !ends_excmd(*name_end)))
3459 if (name_end != NULL)
3461 emsg_severe = TRUE;
3462 EMSG(_(e_trailing));
3464 if (!(eap->skip || error))
3465 clear_lval(&lv);
3466 break;
3469 if (!error && !eap->skip)
3471 if (eap->cmdidx == CMD_unlet)
3473 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3474 error = TRUE;
3476 else
3478 if (do_lock_var(&lv, name_end, deep,
3479 eap->cmdidx == CMD_lockvar) == FAIL)
3480 error = TRUE;
3484 if (!eap->skip)
3485 clear_lval(&lv);
3487 arg = skipwhite(name_end);
3488 } while (!ends_excmd(*arg));
3490 eap->nextcmd = check_nextcmd(arg);
3493 static int
3494 do_unlet_var(lp, name_end, forceit)
3495 lval_T *lp;
3496 char_u *name_end;
3497 int forceit;
3499 int ret = OK;
3500 int cc;
3502 if (lp->ll_tv == NULL)
3504 cc = *name_end;
3505 *name_end = NUL;
3507 /* Normal name or expanded name. */
3508 if (check_changedtick(lp->ll_name))
3509 ret = FAIL;
3510 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3511 ret = FAIL;
3512 *name_end = cc;
3514 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3515 return FAIL;
3516 else if (lp->ll_range)
3518 listitem_T *li;
3520 /* Delete a range of List items. */
3521 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3523 li = lp->ll_li->li_next;
3524 listitem_remove(lp->ll_list, lp->ll_li);
3525 lp->ll_li = li;
3526 ++lp->ll_n1;
3529 else
3531 if (lp->ll_list != NULL)
3532 /* unlet a List item. */
3533 listitem_remove(lp->ll_list, lp->ll_li);
3534 else
3535 /* unlet a Dictionary item. */
3536 dictitem_remove(lp->ll_dict, lp->ll_di);
3539 return ret;
3543 * "unlet" a variable. Return OK if it existed, FAIL if not.
3544 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3547 do_unlet(name, forceit)
3548 char_u *name;
3549 int forceit;
3551 hashtab_T *ht;
3552 hashitem_T *hi;
3553 char_u *varname;
3554 dictitem_T *di;
3556 ht = find_var_ht(name, &varname);
3557 if (ht != NULL && *varname != NUL)
3559 hi = hash_find(ht, varname);
3560 if (!HASHITEM_EMPTY(hi))
3562 di = HI2DI(hi);
3563 if (var_check_fixed(di->di_flags, name)
3564 || var_check_ro(di->di_flags, name))
3565 return FAIL;
3566 delete_var(ht, hi);
3567 return OK;
3570 if (forceit)
3571 return OK;
3572 EMSG2(_("E108: No such variable: \"%s\""), name);
3573 return FAIL;
3577 * Lock or unlock variable indicated by "lp".
3578 * "deep" is the levels to go (-1 for unlimited);
3579 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3581 static int
3582 do_lock_var(lp, name_end, deep, lock)
3583 lval_T *lp;
3584 char_u *name_end;
3585 int deep;
3586 int lock;
3588 int ret = OK;
3589 int cc;
3590 dictitem_T *di;
3592 if (deep == 0) /* nothing to do */
3593 return OK;
3595 if (lp->ll_tv == NULL)
3597 cc = *name_end;
3598 *name_end = NUL;
3600 /* Normal name or expanded name. */
3601 if (check_changedtick(lp->ll_name))
3602 ret = FAIL;
3603 else
3605 di = find_var(lp->ll_name, NULL);
3606 if (di == NULL)
3607 ret = FAIL;
3608 else
3610 if (lock)
3611 di->di_flags |= DI_FLAGS_LOCK;
3612 else
3613 di->di_flags &= ~DI_FLAGS_LOCK;
3614 item_lock(&di->di_tv, deep, lock);
3617 *name_end = cc;
3619 else if (lp->ll_range)
3621 listitem_T *li = lp->ll_li;
3623 /* (un)lock a range of List items. */
3624 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3626 item_lock(&li->li_tv, deep, lock);
3627 li = li->li_next;
3628 ++lp->ll_n1;
3631 else if (lp->ll_list != NULL)
3632 /* (un)lock a List item. */
3633 item_lock(&lp->ll_li->li_tv, deep, lock);
3634 else
3635 /* un(lock) a Dictionary item. */
3636 item_lock(&lp->ll_di->di_tv, deep, lock);
3638 return ret;
3642 * Lock or unlock an item. "deep" is nr of levels to go.
3644 static void
3645 item_lock(tv, deep, lock)
3646 typval_T *tv;
3647 int deep;
3648 int lock;
3650 static int recurse = 0;
3651 list_T *l;
3652 listitem_T *li;
3653 dict_T *d;
3654 hashitem_T *hi;
3655 int todo;
3657 if (recurse >= DICT_MAXNEST)
3659 EMSG(_("E743: variable nested too deep for (un)lock"));
3660 return;
3662 if (deep == 0)
3663 return;
3664 ++recurse;
3666 /* lock/unlock the item itself */
3667 if (lock)
3668 tv->v_lock |= VAR_LOCKED;
3669 else
3670 tv->v_lock &= ~VAR_LOCKED;
3672 switch (tv->v_type)
3674 case VAR_LIST:
3675 if ((l = tv->vval.v_list) != NULL)
3677 if (lock)
3678 l->lv_lock |= VAR_LOCKED;
3679 else
3680 l->lv_lock &= ~VAR_LOCKED;
3681 if (deep < 0 || deep > 1)
3682 /* recursive: lock/unlock the items the List contains */
3683 for (li = l->lv_first; li != NULL; li = li->li_next)
3684 item_lock(&li->li_tv, deep - 1, lock);
3686 break;
3687 case VAR_DICT:
3688 if ((d = tv->vval.v_dict) != NULL)
3690 if (lock)
3691 d->dv_lock |= VAR_LOCKED;
3692 else
3693 d->dv_lock &= ~VAR_LOCKED;
3694 if (deep < 0 || deep > 1)
3696 /* recursive: lock/unlock the items the List contains */
3697 todo = (int)d->dv_hashtab.ht_used;
3698 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3700 if (!HASHITEM_EMPTY(hi))
3702 --todo;
3703 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3709 --recurse;
3713 * Return TRUE if typeval "tv" is locked: Either that value is locked itself
3714 * or it refers to a List or Dictionary that is locked.
3716 static int
3717 tv_islocked(tv)
3718 typval_T *tv;
3720 return (tv->v_lock & VAR_LOCKED)
3721 || (tv->v_type == VAR_LIST
3722 && tv->vval.v_list != NULL
3723 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3724 || (tv->v_type == VAR_DICT
3725 && tv->vval.v_dict != NULL
3726 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3729 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3731 * Delete all "menutrans_" variables.
3733 void
3734 del_menutrans_vars()
3736 hashitem_T *hi;
3737 int todo;
3739 hash_lock(&globvarht);
3740 todo = (int)globvarht.ht_used;
3741 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3743 if (!HASHITEM_EMPTY(hi))
3745 --todo;
3746 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3747 delete_var(&globvarht, hi);
3750 hash_unlock(&globvarht);
3752 #endif
3754 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3757 * Local string buffer for the next two functions to store a variable name
3758 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3759 * get_user_var_name().
3762 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3764 static char_u *varnamebuf = NULL;
3765 static int varnamebuflen = 0;
3768 * Function to concatenate a prefix and a variable name.
3770 static char_u *
3771 cat_prefix_varname(prefix, name)
3772 int prefix;
3773 char_u *name;
3775 int len;
3777 len = (int)STRLEN(name) + 3;
3778 if (len > varnamebuflen)
3780 vim_free(varnamebuf);
3781 len += 10; /* some additional space */
3782 varnamebuf = alloc(len);
3783 if (varnamebuf == NULL)
3785 varnamebuflen = 0;
3786 return NULL;
3788 varnamebuflen = len;
3790 *varnamebuf = prefix;
3791 varnamebuf[1] = ':';
3792 STRCPY(varnamebuf + 2, name);
3793 return varnamebuf;
3797 * Function given to ExpandGeneric() to obtain the list of user defined
3798 * (global/buffer/window/built-in) variable names.
3800 char_u *
3801 get_user_var_name(xp, idx)
3802 expand_T *xp;
3803 int idx;
3805 static long_u gdone;
3806 static long_u bdone;
3807 static long_u wdone;
3808 #ifdef FEAT_WINDOWS
3809 static long_u tdone;
3810 #endif
3811 static int vidx;
3812 static hashitem_T *hi;
3813 hashtab_T *ht;
3815 if (idx == 0)
3817 gdone = bdone = wdone = vidx = 0;
3818 #ifdef FEAT_WINDOWS
3819 tdone = 0;
3820 #endif
3823 /* Global variables */
3824 if (gdone < globvarht.ht_used)
3826 if (gdone++ == 0)
3827 hi = globvarht.ht_array;
3828 else
3829 ++hi;
3830 while (HASHITEM_EMPTY(hi))
3831 ++hi;
3832 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3833 return cat_prefix_varname('g', hi->hi_key);
3834 return hi->hi_key;
3837 /* b: variables */
3838 ht = &curbuf->b_vars.dv_hashtab;
3839 if (bdone < ht->ht_used)
3841 if (bdone++ == 0)
3842 hi = ht->ht_array;
3843 else
3844 ++hi;
3845 while (HASHITEM_EMPTY(hi))
3846 ++hi;
3847 return cat_prefix_varname('b', hi->hi_key);
3849 if (bdone == ht->ht_used)
3851 ++bdone;
3852 return (char_u *)"b:changedtick";
3855 /* w: variables */
3856 ht = &curwin->w_vars.dv_hashtab;
3857 if (wdone < ht->ht_used)
3859 if (wdone++ == 0)
3860 hi = ht->ht_array;
3861 else
3862 ++hi;
3863 while (HASHITEM_EMPTY(hi))
3864 ++hi;
3865 return cat_prefix_varname('w', hi->hi_key);
3868 #ifdef FEAT_WINDOWS
3869 /* t: variables */
3870 ht = &curtab->tp_vars.dv_hashtab;
3871 if (tdone < ht->ht_used)
3873 if (tdone++ == 0)
3874 hi = ht->ht_array;
3875 else
3876 ++hi;
3877 while (HASHITEM_EMPTY(hi))
3878 ++hi;
3879 return cat_prefix_varname('t', hi->hi_key);
3881 #endif
3883 /* v: variables */
3884 if (vidx < VV_LEN)
3885 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3887 vim_free(varnamebuf);
3888 varnamebuf = NULL;
3889 varnamebuflen = 0;
3890 return NULL;
3893 #endif /* FEAT_CMDL_COMPL */
3896 * types for expressions.
3898 typedef enum
3900 TYPE_UNKNOWN = 0
3901 , TYPE_EQUAL /* == */
3902 , TYPE_NEQUAL /* != */
3903 , TYPE_GREATER /* > */
3904 , TYPE_GEQUAL /* >= */
3905 , TYPE_SMALLER /* < */
3906 , TYPE_SEQUAL /* <= */
3907 , TYPE_MATCH /* =~ */
3908 , TYPE_NOMATCH /* !~ */
3909 } exptype_T;
3912 * The "evaluate" argument: When FALSE, the argument is only parsed but not
3913 * executed. The function may return OK, but the rettv will be of type
3914 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
3918 * Handle zero level expression.
3919 * This calls eval1() and handles error message and nextcmd.
3920 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3921 * Note: "rettv.v_lock" is not set.
3922 * Return OK or FAIL.
3924 static int
3925 eval0(arg, rettv, nextcmd, evaluate)
3926 char_u *arg;
3927 typval_T *rettv;
3928 char_u **nextcmd;
3929 int evaluate;
3931 int ret;
3932 char_u *p;
3934 p = skipwhite(arg);
3935 ret = eval1(&p, rettv, evaluate);
3936 if (ret == FAIL || !ends_excmd(*p))
3938 if (ret != FAIL)
3939 clear_tv(rettv);
3941 * Report the invalid expression unless the expression evaluation has
3942 * been cancelled due to an aborting error, an interrupt, or an
3943 * exception.
3945 if (!aborting())
3946 EMSG2(_(e_invexpr2), arg);
3947 ret = FAIL;
3949 if (nextcmd != NULL)
3950 *nextcmd = check_nextcmd(p);
3952 return ret;
3956 * Handle top level expression:
3957 * expr2 ? expr1 : expr1
3959 * "arg" must point to the first non-white of the expression.
3960 * "arg" is advanced to the next non-white after the recognized expression.
3962 * Note: "rettv.v_lock" is not set.
3964 * Return OK or FAIL.
3966 static int
3967 eval1(arg, rettv, evaluate)
3968 char_u **arg;
3969 typval_T *rettv;
3970 int evaluate;
3972 int result;
3973 typval_T var2;
3976 * Get the first variable.
3978 if (eval2(arg, rettv, evaluate) == FAIL)
3979 return FAIL;
3981 if ((*arg)[0] == '?')
3983 result = FALSE;
3984 if (evaluate)
3986 int error = FALSE;
3988 if (get_tv_number_chk(rettv, &error) != 0)
3989 result = TRUE;
3990 clear_tv(rettv);
3991 if (error)
3992 return FAIL;
3996 * Get the second variable.
3998 *arg = skipwhite(*arg + 1);
3999 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
4000 return FAIL;
4003 * Check for the ":".
4005 if ((*arg)[0] != ':')
4007 EMSG(_("E109: Missing ':' after '?'"));
4008 if (evaluate && result)
4009 clear_tv(rettv);
4010 return FAIL;
4014 * Get the third variable.
4016 *arg = skipwhite(*arg + 1);
4017 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
4019 if (evaluate && result)
4020 clear_tv(rettv);
4021 return FAIL;
4023 if (evaluate && !result)
4024 *rettv = var2;
4027 return OK;
4031 * Handle first level expression:
4032 * expr2 || expr2 || expr2 logical OR
4034 * "arg" must point to the first non-white of the expression.
4035 * "arg" is advanced to the next non-white after the recognized expression.
4037 * Return OK or FAIL.
4039 static int
4040 eval2(arg, rettv, evaluate)
4041 char_u **arg;
4042 typval_T *rettv;
4043 int evaluate;
4045 typval_T var2;
4046 long result;
4047 int first;
4048 int error = FALSE;
4051 * Get the first variable.
4053 if (eval3(arg, rettv, evaluate) == FAIL)
4054 return FAIL;
4057 * Repeat until there is no following "||".
4059 first = TRUE;
4060 result = FALSE;
4061 while ((*arg)[0] == '|' && (*arg)[1] == '|')
4063 if (evaluate && first)
4065 if (get_tv_number_chk(rettv, &error) != 0)
4066 result = TRUE;
4067 clear_tv(rettv);
4068 if (error)
4069 return FAIL;
4070 first = FALSE;
4074 * Get the second variable.
4076 *arg = skipwhite(*arg + 2);
4077 if (eval3(arg, &var2, evaluate && !result) == FAIL)
4078 return FAIL;
4081 * Compute the result.
4083 if (evaluate && !result)
4085 if (get_tv_number_chk(&var2, &error) != 0)
4086 result = TRUE;
4087 clear_tv(&var2);
4088 if (error)
4089 return FAIL;
4091 if (evaluate)
4093 rettv->v_type = VAR_NUMBER;
4094 rettv->vval.v_number = result;
4098 return OK;
4102 * Handle second level expression:
4103 * expr3 && expr3 && expr3 logical AND
4105 * "arg" must point to the first non-white of the expression.
4106 * "arg" is advanced to the next non-white after the recognized expression.
4108 * Return OK or FAIL.
4110 static int
4111 eval3(arg, rettv, evaluate)
4112 char_u **arg;
4113 typval_T *rettv;
4114 int evaluate;
4116 typval_T var2;
4117 long result;
4118 int first;
4119 int error = FALSE;
4122 * Get the first variable.
4124 if (eval4(arg, rettv, evaluate) == FAIL)
4125 return FAIL;
4128 * Repeat until there is no following "&&".
4130 first = TRUE;
4131 result = TRUE;
4132 while ((*arg)[0] == '&' && (*arg)[1] == '&')
4134 if (evaluate && first)
4136 if (get_tv_number_chk(rettv, &error) == 0)
4137 result = FALSE;
4138 clear_tv(rettv);
4139 if (error)
4140 return FAIL;
4141 first = FALSE;
4145 * Get the second variable.
4147 *arg = skipwhite(*arg + 2);
4148 if (eval4(arg, &var2, evaluate && result) == FAIL)
4149 return FAIL;
4152 * Compute the result.
4154 if (evaluate && result)
4156 if (get_tv_number_chk(&var2, &error) == 0)
4157 result = FALSE;
4158 clear_tv(&var2);
4159 if (error)
4160 return FAIL;
4162 if (evaluate)
4164 rettv->v_type = VAR_NUMBER;
4165 rettv->vval.v_number = result;
4169 return OK;
4173 * Handle third level expression:
4174 * var1 == var2
4175 * var1 =~ var2
4176 * var1 != var2
4177 * var1 !~ var2
4178 * var1 > var2
4179 * var1 >= var2
4180 * var1 < var2
4181 * var1 <= var2
4182 * var1 is var2
4183 * var1 isnot var2
4185 * "arg" must point to the first non-white of the expression.
4186 * "arg" is advanced to the next non-white after the recognized expression.
4188 * Return OK or FAIL.
4190 static int
4191 eval4(arg, rettv, evaluate)
4192 char_u **arg;
4193 typval_T *rettv;
4194 int evaluate;
4196 typval_T var2;
4197 char_u *p;
4198 int i;
4199 exptype_T type = TYPE_UNKNOWN;
4200 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4201 int len = 2;
4202 long n1, n2;
4203 char_u *s1, *s2;
4204 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4205 regmatch_T regmatch;
4206 int ic;
4207 char_u *save_cpo;
4210 * Get the first variable.
4212 if (eval5(arg, rettv, evaluate) == FAIL)
4213 return FAIL;
4215 p = *arg;
4216 switch (p[0])
4218 case '=': if (p[1] == '=')
4219 type = TYPE_EQUAL;
4220 else if (p[1] == '~')
4221 type = TYPE_MATCH;
4222 break;
4223 case '!': if (p[1] == '=')
4224 type = TYPE_NEQUAL;
4225 else if (p[1] == '~')
4226 type = TYPE_NOMATCH;
4227 break;
4228 case '>': if (p[1] != '=')
4230 type = TYPE_GREATER;
4231 len = 1;
4233 else
4234 type = TYPE_GEQUAL;
4235 break;
4236 case '<': if (p[1] != '=')
4238 type = TYPE_SMALLER;
4239 len = 1;
4241 else
4242 type = TYPE_SEQUAL;
4243 break;
4244 case 'i': if (p[1] == 's')
4246 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4247 len = 5;
4248 if (!vim_isIDc(p[len]))
4250 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4251 type_is = TRUE;
4254 break;
4258 * If there is a comparative operator, use it.
4260 if (type != TYPE_UNKNOWN)
4262 /* extra question mark appended: ignore case */
4263 if (p[len] == '?')
4265 ic = TRUE;
4266 ++len;
4268 /* extra '#' appended: match case */
4269 else if (p[len] == '#')
4271 ic = FALSE;
4272 ++len;
4274 /* nothing appended: use 'ignorecase' */
4275 else
4276 ic = p_ic;
4279 * Get the second variable.
4281 *arg = skipwhite(p + len);
4282 if (eval5(arg, &var2, evaluate) == FAIL)
4284 clear_tv(rettv);
4285 return FAIL;
4288 if (evaluate)
4290 if (type_is && rettv->v_type != var2.v_type)
4292 /* For "is" a different type always means FALSE, for "notis"
4293 * it means TRUE. */
4294 n1 = (type == TYPE_NEQUAL);
4296 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4298 if (type_is)
4300 n1 = (rettv->v_type == var2.v_type
4301 && rettv->vval.v_list == var2.vval.v_list);
4302 if (type == TYPE_NEQUAL)
4303 n1 = !n1;
4305 else if (rettv->v_type != var2.v_type
4306 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4308 if (rettv->v_type != var2.v_type)
4309 EMSG(_("E691: Can only compare List with List"));
4310 else
4311 EMSG(_("E692: Invalid operation for Lists"));
4312 clear_tv(rettv);
4313 clear_tv(&var2);
4314 return FAIL;
4316 else
4318 /* Compare two Lists for being equal or unequal. */
4319 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
4320 if (type == TYPE_NEQUAL)
4321 n1 = !n1;
4325 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4327 if (type_is)
4329 n1 = (rettv->v_type == var2.v_type
4330 && rettv->vval.v_dict == var2.vval.v_dict);
4331 if (type == TYPE_NEQUAL)
4332 n1 = !n1;
4334 else if (rettv->v_type != var2.v_type
4335 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4337 if (rettv->v_type != var2.v_type)
4338 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4339 else
4340 EMSG(_("E736: Invalid operation for Dictionary"));
4341 clear_tv(rettv);
4342 clear_tv(&var2);
4343 return FAIL;
4345 else
4347 /* Compare two Dictionaries for being equal or unequal. */
4348 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4349 if (type == TYPE_NEQUAL)
4350 n1 = !n1;
4354 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4356 if (rettv->v_type != var2.v_type
4357 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4359 if (rettv->v_type != var2.v_type)
4360 EMSG(_("E693: Can only compare Funcref with Funcref"));
4361 else
4362 EMSG(_("E694: Invalid operation for Funcrefs"));
4363 clear_tv(rettv);
4364 clear_tv(&var2);
4365 return FAIL;
4367 else
4369 /* Compare two Funcrefs for being equal or unequal. */
4370 if (rettv->vval.v_string == NULL
4371 || var2.vval.v_string == NULL)
4372 n1 = FALSE;
4373 else
4374 n1 = STRCMP(rettv->vval.v_string,
4375 var2.vval.v_string) == 0;
4376 if (type == TYPE_NEQUAL)
4377 n1 = !n1;
4381 #ifdef FEAT_FLOAT
4383 * If one of the two variables is a float, compare as a float.
4384 * When using "=~" or "!~", always compare as string.
4386 else if ((rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4387 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4389 float_T f1, f2;
4391 if (rettv->v_type == VAR_FLOAT)
4392 f1 = rettv->vval.v_float;
4393 else
4394 f1 = get_tv_number(rettv);
4395 if (var2.v_type == VAR_FLOAT)
4396 f2 = var2.vval.v_float;
4397 else
4398 f2 = get_tv_number(&var2);
4399 n1 = FALSE;
4400 switch (type)
4402 case TYPE_EQUAL: n1 = (f1 == f2); break;
4403 case TYPE_NEQUAL: n1 = (f1 != f2); break;
4404 case TYPE_GREATER: n1 = (f1 > f2); break;
4405 case TYPE_GEQUAL: n1 = (f1 >= f2); break;
4406 case TYPE_SMALLER: n1 = (f1 < f2); break;
4407 case TYPE_SEQUAL: n1 = (f1 <= f2); break;
4408 case TYPE_UNKNOWN:
4409 case TYPE_MATCH:
4410 case TYPE_NOMATCH: break; /* avoid gcc warning */
4413 #endif
4416 * If one of the two variables is a number, compare as a number.
4417 * When using "=~" or "!~", always compare as string.
4419 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4420 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4422 n1 = get_tv_number(rettv);
4423 n2 = get_tv_number(&var2);
4424 switch (type)
4426 case TYPE_EQUAL: n1 = (n1 == n2); break;
4427 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4428 case TYPE_GREATER: n1 = (n1 > n2); break;
4429 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4430 case TYPE_SMALLER: n1 = (n1 < n2); break;
4431 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4432 case TYPE_UNKNOWN:
4433 case TYPE_MATCH:
4434 case TYPE_NOMATCH: break; /* avoid gcc warning */
4437 else
4439 s1 = get_tv_string_buf(rettv, buf1);
4440 s2 = get_tv_string_buf(&var2, buf2);
4441 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4442 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4443 else
4444 i = 0;
4445 n1 = FALSE;
4446 switch (type)
4448 case TYPE_EQUAL: n1 = (i == 0); break;
4449 case TYPE_NEQUAL: n1 = (i != 0); break;
4450 case TYPE_GREATER: n1 = (i > 0); break;
4451 case TYPE_GEQUAL: n1 = (i >= 0); break;
4452 case TYPE_SMALLER: n1 = (i < 0); break;
4453 case TYPE_SEQUAL: n1 = (i <= 0); break;
4455 case TYPE_MATCH:
4456 case TYPE_NOMATCH:
4457 /* avoid 'l' flag in 'cpoptions' */
4458 save_cpo = p_cpo;
4459 p_cpo = (char_u *)"";
4460 regmatch.regprog = vim_regcomp(s2,
4461 RE_MAGIC + RE_STRING);
4462 regmatch.rm_ic = ic;
4463 if (regmatch.regprog != NULL)
4465 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4466 vim_free(regmatch.regprog);
4467 if (type == TYPE_NOMATCH)
4468 n1 = !n1;
4470 p_cpo = save_cpo;
4471 break;
4473 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4476 clear_tv(rettv);
4477 clear_tv(&var2);
4478 rettv->v_type = VAR_NUMBER;
4479 rettv->vval.v_number = n1;
4483 return OK;
4487 * Handle fourth level expression:
4488 * + number addition
4489 * - number subtraction
4490 * . string concatenation
4492 * "arg" must point to the first non-white of the expression.
4493 * "arg" is advanced to the next non-white after the recognized expression.
4495 * Return OK or FAIL.
4497 static int
4498 eval5(arg, rettv, evaluate)
4499 char_u **arg;
4500 typval_T *rettv;
4501 int evaluate;
4503 typval_T var2;
4504 typval_T var3;
4505 int op;
4506 long n1, n2;
4507 #ifdef FEAT_FLOAT
4508 float_T f1 = 0, f2 = 0;
4509 #endif
4510 char_u *s1, *s2;
4511 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4512 char_u *p;
4515 * Get the first variable.
4517 if (eval6(arg, rettv, evaluate, FALSE) == FAIL)
4518 return FAIL;
4521 * Repeat computing, until no '+', '-' or '.' is following.
4523 for (;;)
4525 op = **arg;
4526 if (op != '+' && op != '-' && op != '.')
4527 break;
4529 if ((op != '+' || rettv->v_type != VAR_LIST)
4530 #ifdef FEAT_FLOAT
4531 && (op == '.' || rettv->v_type != VAR_FLOAT)
4532 #endif
4535 /* For "list + ...", an illegal use of the first operand as
4536 * a number cannot be determined before evaluating the 2nd
4537 * operand: if this is also a list, all is ok.
4538 * For "something . ...", "something - ..." or "non-list + ...",
4539 * we know that the first operand needs to be a string or number
4540 * without evaluating the 2nd operand. So check before to avoid
4541 * side effects after an error. */
4542 if (evaluate && get_tv_string_chk(rettv) == NULL)
4544 clear_tv(rettv);
4545 return FAIL;
4550 * Get the second variable.
4552 *arg = skipwhite(*arg + 1);
4553 if (eval6(arg, &var2, evaluate, op == '.') == FAIL)
4555 clear_tv(rettv);
4556 return FAIL;
4559 if (evaluate)
4562 * Compute the result.
4564 if (op == '.')
4566 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4567 s2 = get_tv_string_buf_chk(&var2, buf2);
4568 if (s2 == NULL) /* type error ? */
4570 clear_tv(rettv);
4571 clear_tv(&var2);
4572 return FAIL;
4574 p = concat_str(s1, s2);
4575 clear_tv(rettv);
4576 rettv->v_type = VAR_STRING;
4577 rettv->vval.v_string = p;
4579 else if (op == '+' && rettv->v_type == VAR_LIST
4580 && var2.v_type == VAR_LIST)
4582 /* concatenate Lists */
4583 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4584 &var3) == FAIL)
4586 clear_tv(rettv);
4587 clear_tv(&var2);
4588 return FAIL;
4590 clear_tv(rettv);
4591 *rettv = var3;
4593 else
4595 int error = FALSE;
4597 #ifdef FEAT_FLOAT
4598 if (rettv->v_type == VAR_FLOAT)
4600 f1 = rettv->vval.v_float;
4601 n1 = 0;
4603 else
4604 #endif
4606 n1 = get_tv_number_chk(rettv, &error);
4607 if (error)
4609 /* This can only happen for "list + non-list". For
4610 * "non-list + ..." or "something - ...", we returned
4611 * before evaluating the 2nd operand. */
4612 clear_tv(rettv);
4613 return FAIL;
4615 #ifdef FEAT_FLOAT
4616 if (var2.v_type == VAR_FLOAT)
4617 f1 = n1;
4618 #endif
4620 #ifdef FEAT_FLOAT
4621 if (var2.v_type == VAR_FLOAT)
4623 f2 = var2.vval.v_float;
4624 n2 = 0;
4626 else
4627 #endif
4629 n2 = get_tv_number_chk(&var2, &error);
4630 if (error)
4632 clear_tv(rettv);
4633 clear_tv(&var2);
4634 return FAIL;
4636 #ifdef FEAT_FLOAT
4637 if (rettv->v_type == VAR_FLOAT)
4638 f2 = n2;
4639 #endif
4641 clear_tv(rettv);
4643 #ifdef FEAT_FLOAT
4644 /* If there is a float on either side the result is a float. */
4645 if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4647 if (op == '+')
4648 f1 = f1 + f2;
4649 else
4650 f1 = f1 - f2;
4651 rettv->v_type = VAR_FLOAT;
4652 rettv->vval.v_float = f1;
4654 else
4655 #endif
4657 if (op == '+')
4658 n1 = n1 + n2;
4659 else
4660 n1 = n1 - n2;
4661 rettv->v_type = VAR_NUMBER;
4662 rettv->vval.v_number = n1;
4665 clear_tv(&var2);
4668 return OK;
4672 * Handle fifth level expression:
4673 * * number multiplication
4674 * / number division
4675 * % number modulo
4677 * "arg" must point to the first non-white of the expression.
4678 * "arg" is advanced to the next non-white after the recognized expression.
4680 * Return OK or FAIL.
4682 static int
4683 eval6(arg, rettv, evaluate, want_string)
4684 char_u **arg;
4685 typval_T *rettv;
4686 int evaluate;
4687 int want_string; /* after "." operator */
4689 typval_T var2;
4690 int op;
4691 long n1, n2;
4692 #ifdef FEAT_FLOAT
4693 int use_float = FALSE;
4694 float_T f1 = 0, f2;
4695 #endif
4696 int error = FALSE;
4699 * Get the first variable.
4701 if (eval7(arg, rettv, evaluate, want_string) == FAIL)
4702 return FAIL;
4705 * Repeat computing, until no '*', '/' or '%' is following.
4707 for (;;)
4709 op = **arg;
4710 if (op != '*' && op != '/' && op != '%')
4711 break;
4713 if (evaluate)
4715 #ifdef FEAT_FLOAT
4716 if (rettv->v_type == VAR_FLOAT)
4718 f1 = rettv->vval.v_float;
4719 use_float = TRUE;
4720 n1 = 0;
4722 else
4723 #endif
4724 n1 = get_tv_number_chk(rettv, &error);
4725 clear_tv(rettv);
4726 if (error)
4727 return FAIL;
4729 else
4730 n1 = 0;
4733 * Get the second variable.
4735 *arg = skipwhite(*arg + 1);
4736 if (eval7(arg, &var2, evaluate, FALSE) == FAIL)
4737 return FAIL;
4739 if (evaluate)
4741 #ifdef FEAT_FLOAT
4742 if (var2.v_type == VAR_FLOAT)
4744 if (!use_float)
4746 f1 = n1;
4747 use_float = TRUE;
4749 f2 = var2.vval.v_float;
4750 n2 = 0;
4752 else
4753 #endif
4755 n2 = get_tv_number_chk(&var2, &error);
4756 clear_tv(&var2);
4757 if (error)
4758 return FAIL;
4759 #ifdef FEAT_FLOAT
4760 if (use_float)
4761 f2 = n2;
4762 #endif
4766 * Compute the result.
4767 * When either side is a float the result is a float.
4769 #ifdef FEAT_FLOAT
4770 if (use_float)
4772 if (op == '*')
4773 f1 = f1 * f2;
4774 else if (op == '/')
4776 /* We rely on the floating point library to handle divide
4777 * by zero to result in "inf" and not a crash. */
4778 f1 = f1 / f2;
4780 else
4782 EMSG(_("E804: Cannot use '%' with Float"));
4783 return FAIL;
4785 rettv->v_type = VAR_FLOAT;
4786 rettv->vval.v_float = f1;
4788 else
4789 #endif
4791 if (op == '*')
4792 n1 = n1 * n2;
4793 else if (op == '/')
4795 if (n2 == 0) /* give an error message? */
4797 if (n1 == 0)
4798 n1 = -0x7fffffffL - 1L; /* similar to NaN */
4799 else if (n1 < 0)
4800 n1 = -0x7fffffffL;
4801 else
4802 n1 = 0x7fffffffL;
4804 else
4805 n1 = n1 / n2;
4807 else
4809 if (n2 == 0) /* give an error message? */
4810 n1 = 0;
4811 else
4812 n1 = n1 % n2;
4814 rettv->v_type = VAR_NUMBER;
4815 rettv->vval.v_number = n1;
4820 return OK;
4824 * Handle sixth level expression:
4825 * number number constant
4826 * "string" string constant
4827 * 'string' literal string constant
4828 * &option-name option value
4829 * @r register contents
4830 * identifier variable value
4831 * function() function call
4832 * $VAR environment variable
4833 * (expression) nested expression
4834 * [expr, expr] List
4835 * {key: val, key: val} Dictionary
4837 * Also handle:
4838 * ! in front logical NOT
4839 * - in front unary minus
4840 * + in front unary plus (ignored)
4841 * trailing [] subscript in String or List
4842 * trailing .name entry in Dictionary
4844 * "arg" must point to the first non-white of the expression.
4845 * "arg" is advanced to the next non-white after the recognized expression.
4847 * Return OK or FAIL.
4849 static int
4850 eval7(arg, rettv, evaluate, want_string)
4851 char_u **arg;
4852 typval_T *rettv;
4853 int evaluate;
4854 int want_string; /* after "." operator */
4856 long n;
4857 int len;
4858 char_u *s;
4859 char_u *start_leader, *end_leader;
4860 int ret = OK;
4861 char_u *alias;
4864 * Initialise variable so that clear_tv() can't mistake this for a
4865 * string and free a string that isn't there.
4867 rettv->v_type = VAR_UNKNOWN;
4870 * Skip '!' and '-' characters. They are handled later.
4872 start_leader = *arg;
4873 while (**arg == '!' || **arg == '-' || **arg == '+')
4874 *arg = skipwhite(*arg + 1);
4875 end_leader = *arg;
4877 switch (**arg)
4880 * Number constant.
4882 case '0':
4883 case '1':
4884 case '2':
4885 case '3':
4886 case '4':
4887 case '5':
4888 case '6':
4889 case '7':
4890 case '8':
4891 case '9':
4893 #ifdef FEAT_FLOAT
4894 char_u *p = skipdigits(*arg + 1);
4895 int get_float = FALSE;
4897 /* We accept a float when the format matches
4898 * "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?". This is very
4899 * strict to avoid backwards compatibility problems.
4900 * Don't look for a float after the "." operator, so that
4901 * ":let vers = 1.2.3" doesn't fail. */
4902 if (!want_string && p[0] == '.' && vim_isdigit(p[1]))
4904 get_float = TRUE;
4905 p = skipdigits(p + 2);
4906 if (*p == 'e' || *p == 'E')
4908 ++p;
4909 if (*p == '-' || *p == '+')
4910 ++p;
4911 if (!vim_isdigit(*p))
4912 get_float = FALSE;
4913 else
4914 p = skipdigits(p + 1);
4916 if (ASCII_ISALPHA(*p) || *p == '.')
4917 get_float = FALSE;
4919 if (get_float)
4921 float_T f;
4923 *arg += string2float(*arg, &f);
4924 if (evaluate)
4926 rettv->v_type = VAR_FLOAT;
4927 rettv->vval.v_float = f;
4930 else
4931 #endif
4933 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4934 *arg += len;
4935 if (evaluate)
4937 rettv->v_type = VAR_NUMBER;
4938 rettv->vval.v_number = n;
4941 break;
4945 * String constant: "string".
4947 case '"': ret = get_string_tv(arg, rettv, evaluate);
4948 break;
4951 * Literal string constant: 'str''ing'.
4953 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
4954 break;
4957 * List: [expr, expr]
4959 case '[': ret = get_list_tv(arg, rettv, evaluate);
4960 break;
4963 * Dictionary: {key: val, key: val}
4965 case '{': ret = get_dict_tv(arg, rettv, evaluate);
4966 break;
4969 * Option value: &name
4971 case '&': ret = get_option_tv(arg, rettv, evaluate);
4972 break;
4975 * Environment variable: $VAR.
4977 case '$': ret = get_env_tv(arg, rettv, evaluate);
4978 break;
4981 * Register contents: @r.
4983 case '@': ++*arg;
4984 if (evaluate)
4986 rettv->v_type = VAR_STRING;
4987 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4989 if (**arg != NUL)
4990 ++*arg;
4991 break;
4994 * nested expression: (expression).
4996 case '(': *arg = skipwhite(*arg + 1);
4997 ret = eval1(arg, rettv, evaluate); /* recursive! */
4998 if (**arg == ')')
4999 ++*arg;
5000 else if (ret == OK)
5002 EMSG(_("E110: Missing ')'"));
5003 clear_tv(rettv);
5004 ret = FAIL;
5006 break;
5008 default: ret = NOTDONE;
5009 break;
5012 if (ret == NOTDONE)
5015 * Must be a variable or function name.
5016 * Can also be a curly-braces kind of name: {expr}.
5018 s = *arg;
5019 len = get_name_len(arg, &alias, evaluate, TRUE);
5020 if (alias != NULL)
5021 s = alias;
5023 if (len <= 0)
5024 ret = FAIL;
5025 else
5027 if (**arg == '(') /* recursive! */
5029 /* If "s" is the name of a variable of type VAR_FUNC
5030 * use its contents. */
5031 s = deref_func_name(s, &len);
5033 /* Invoke the function. */
5034 ret = get_func_tv(s, len, rettv, arg,
5035 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
5036 &len, evaluate, NULL);
5037 /* Stop the expression evaluation when immediately
5038 * aborting on error, or when an interrupt occurred or
5039 * an exception was thrown but not caught. */
5040 if (aborting())
5042 if (ret == OK)
5043 clear_tv(rettv);
5044 ret = FAIL;
5047 else if (evaluate)
5048 ret = get_var_tv(s, len, rettv, TRUE);
5049 else
5050 ret = OK;
5053 if (alias != NULL)
5054 vim_free(alias);
5057 *arg = skipwhite(*arg);
5059 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
5060 * expr(expr). */
5061 if (ret == OK)
5062 ret = handle_subscript(arg, rettv, evaluate, TRUE);
5065 * Apply logical NOT and unary '-', from right to left, ignore '+'.
5067 if (ret == OK && evaluate && end_leader > start_leader)
5069 int error = FALSE;
5070 int val = 0;
5071 #ifdef FEAT_FLOAT
5072 float_T f = 0.0;
5074 if (rettv->v_type == VAR_FLOAT)
5075 f = rettv->vval.v_float;
5076 else
5077 #endif
5078 val = get_tv_number_chk(rettv, &error);
5079 if (error)
5081 clear_tv(rettv);
5082 ret = FAIL;
5084 else
5086 while (end_leader > start_leader)
5088 --end_leader;
5089 if (*end_leader == '!')
5091 #ifdef FEAT_FLOAT
5092 if (rettv->v_type == VAR_FLOAT)
5093 f = !f;
5094 else
5095 #endif
5096 val = !val;
5098 else if (*end_leader == '-')
5100 #ifdef FEAT_FLOAT
5101 if (rettv->v_type == VAR_FLOAT)
5102 f = -f;
5103 else
5104 #endif
5105 val = -val;
5108 #ifdef FEAT_FLOAT
5109 if (rettv->v_type == VAR_FLOAT)
5111 clear_tv(rettv);
5112 rettv->vval.v_float = f;
5114 else
5115 #endif
5117 clear_tv(rettv);
5118 rettv->v_type = VAR_NUMBER;
5119 rettv->vval.v_number = val;
5124 return ret;
5128 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
5129 * "*arg" points to the '[' or '.'.
5130 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
5132 static int
5133 eval_index(arg, rettv, evaluate, verbose)
5134 char_u **arg;
5135 typval_T *rettv;
5136 int evaluate;
5137 int verbose; /* give error messages */
5139 int empty1 = FALSE, empty2 = FALSE;
5140 typval_T var1, var2;
5141 long n1, n2 = 0;
5142 long len = -1;
5143 int range = FALSE;
5144 char_u *s;
5145 char_u *key = NULL;
5147 if (rettv->v_type == VAR_FUNC
5148 #ifdef FEAT_FLOAT
5149 || rettv->v_type == VAR_FLOAT
5150 #endif
5153 if (verbose)
5154 EMSG(_("E695: Cannot index a Funcref"));
5155 return FAIL;
5158 if (**arg == '.')
5161 * dict.name
5163 key = *arg + 1;
5164 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
5166 if (len == 0)
5167 return FAIL;
5168 *arg = skipwhite(key + len);
5170 else
5173 * something[idx]
5175 * Get the (first) variable from inside the [].
5177 *arg = skipwhite(*arg + 1);
5178 if (**arg == ':')
5179 empty1 = TRUE;
5180 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
5181 return FAIL;
5182 else if (evaluate && get_tv_string_chk(&var1) == NULL)
5184 /* not a number or string */
5185 clear_tv(&var1);
5186 return FAIL;
5190 * Get the second variable from inside the [:].
5192 if (**arg == ':')
5194 range = TRUE;
5195 *arg = skipwhite(*arg + 1);
5196 if (**arg == ']')
5197 empty2 = TRUE;
5198 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
5200 if (!empty1)
5201 clear_tv(&var1);
5202 return FAIL;
5204 else if (evaluate && get_tv_string_chk(&var2) == NULL)
5206 /* not a number or string */
5207 if (!empty1)
5208 clear_tv(&var1);
5209 clear_tv(&var2);
5210 return FAIL;
5214 /* Check for the ']'. */
5215 if (**arg != ']')
5217 if (verbose)
5218 EMSG(_(e_missbrac));
5219 clear_tv(&var1);
5220 if (range)
5221 clear_tv(&var2);
5222 return FAIL;
5224 *arg = skipwhite(*arg + 1); /* skip the ']' */
5227 if (evaluate)
5229 n1 = 0;
5230 if (!empty1 && rettv->v_type != VAR_DICT)
5232 n1 = get_tv_number(&var1);
5233 clear_tv(&var1);
5235 if (range)
5237 if (empty2)
5238 n2 = -1;
5239 else
5241 n2 = get_tv_number(&var2);
5242 clear_tv(&var2);
5246 switch (rettv->v_type)
5248 case VAR_NUMBER:
5249 case VAR_STRING:
5250 s = get_tv_string(rettv);
5251 len = (long)STRLEN(s);
5252 if (range)
5254 /* The resulting variable is a substring. If the indexes
5255 * are out of range the result is empty. */
5256 if (n1 < 0)
5258 n1 = len + n1;
5259 if (n1 < 0)
5260 n1 = 0;
5262 if (n2 < 0)
5263 n2 = len + n2;
5264 else if (n2 >= len)
5265 n2 = len;
5266 if (n1 >= len || n2 < 0 || n1 > n2)
5267 s = NULL;
5268 else
5269 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
5271 else
5273 /* The resulting variable is a string of a single
5274 * character. If the index is too big or negative the
5275 * result is empty. */
5276 if (n1 >= len || n1 < 0)
5277 s = NULL;
5278 else
5279 s = vim_strnsave(s + n1, 1);
5281 clear_tv(rettv);
5282 rettv->v_type = VAR_STRING;
5283 rettv->vval.v_string = s;
5284 break;
5286 case VAR_LIST:
5287 len = list_len(rettv->vval.v_list);
5288 if (n1 < 0)
5289 n1 = len + n1;
5290 if (!empty1 && (n1 < 0 || n1 >= len))
5292 /* For a range we allow invalid values and return an empty
5293 * list. A list index out of range is an error. */
5294 if (!range)
5296 if (verbose)
5297 EMSGN(_(e_listidx), n1);
5298 return FAIL;
5300 n1 = len;
5302 if (range)
5304 list_T *l;
5305 listitem_T *item;
5307 if (n2 < 0)
5308 n2 = len + n2;
5309 else if (n2 >= len)
5310 n2 = len - 1;
5311 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
5312 n2 = -1;
5313 l = list_alloc();
5314 if (l == NULL)
5315 return FAIL;
5316 for (item = list_find(rettv->vval.v_list, n1);
5317 n1 <= n2; ++n1)
5319 if (list_append_tv(l, &item->li_tv) == FAIL)
5321 list_free(l, TRUE);
5322 return FAIL;
5324 item = item->li_next;
5326 clear_tv(rettv);
5327 rettv->v_type = VAR_LIST;
5328 rettv->vval.v_list = l;
5329 ++l->lv_refcount;
5331 else
5333 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
5334 clear_tv(rettv);
5335 *rettv = var1;
5337 break;
5339 case VAR_DICT:
5340 if (range)
5342 if (verbose)
5343 EMSG(_(e_dictrange));
5344 if (len == -1)
5345 clear_tv(&var1);
5346 return FAIL;
5349 dictitem_T *item;
5351 if (len == -1)
5353 key = get_tv_string(&var1);
5354 if (*key == NUL)
5356 if (verbose)
5357 EMSG(_(e_emptykey));
5358 clear_tv(&var1);
5359 return FAIL;
5363 item = dict_find(rettv->vval.v_dict, key, (int)len);
5365 if (item == NULL && verbose)
5366 EMSG2(_(e_dictkey), key);
5367 if (len == -1)
5368 clear_tv(&var1);
5369 if (item == NULL)
5370 return FAIL;
5372 copy_tv(&item->di_tv, &var1);
5373 clear_tv(rettv);
5374 *rettv = var1;
5376 break;
5380 return OK;
5384 * Get an option value.
5385 * "arg" points to the '&' or '+' before the option name.
5386 * "arg" is advanced to character after the option name.
5387 * Return OK or FAIL.
5389 static int
5390 get_option_tv(arg, rettv, evaluate)
5391 char_u **arg;
5392 typval_T *rettv; /* when NULL, only check if option exists */
5393 int evaluate;
5395 char_u *option_end;
5396 long numval;
5397 char_u *stringval;
5398 int opt_type;
5399 int c;
5400 int working = (**arg == '+'); /* has("+option") */
5401 int ret = OK;
5402 int opt_flags;
5405 * Isolate the option name and find its value.
5407 option_end = find_option_end(arg, &opt_flags);
5408 if (option_end == NULL)
5410 if (rettv != NULL)
5411 EMSG2(_("E112: Option name missing: %s"), *arg);
5412 return FAIL;
5415 if (!evaluate)
5417 *arg = option_end;
5418 return OK;
5421 c = *option_end;
5422 *option_end = NUL;
5423 opt_type = get_option_value(*arg, &numval,
5424 rettv == NULL ? NULL : &stringval, opt_flags);
5426 if (opt_type == -3) /* invalid name */
5428 if (rettv != NULL)
5429 EMSG2(_("E113: Unknown option: %s"), *arg);
5430 ret = FAIL;
5432 else if (rettv != NULL)
5434 if (opt_type == -2) /* hidden string option */
5436 rettv->v_type = VAR_STRING;
5437 rettv->vval.v_string = NULL;
5439 else if (opt_type == -1) /* hidden number option */
5441 rettv->v_type = VAR_NUMBER;
5442 rettv->vval.v_number = 0;
5444 else if (opt_type == 1) /* number option */
5446 rettv->v_type = VAR_NUMBER;
5447 rettv->vval.v_number = numval;
5449 else /* string option */
5451 rettv->v_type = VAR_STRING;
5452 rettv->vval.v_string = stringval;
5455 else if (working && (opt_type == -2 || opt_type == -1))
5456 ret = FAIL;
5458 *option_end = c; /* put back for error messages */
5459 *arg = option_end;
5461 return ret;
5465 * Allocate a variable for a string constant.
5466 * Return OK or FAIL.
5468 static int
5469 get_string_tv(arg, rettv, evaluate)
5470 char_u **arg;
5471 typval_T *rettv;
5472 int evaluate;
5474 char_u *p;
5475 char_u *name;
5476 int extra = 0;
5479 * Find the end of the string, skipping backslashed characters.
5481 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5483 if (*p == '\\' && p[1] != NUL)
5485 ++p;
5486 /* A "\<x>" form occupies at least 4 characters, and produces up
5487 * to 6 characters: reserve space for 2 extra */
5488 if (*p == '<')
5489 extra += 2;
5493 if (*p != '"')
5495 EMSG2(_("E114: Missing quote: %s"), *arg);
5496 return FAIL;
5499 /* If only parsing, set *arg and return here */
5500 if (!evaluate)
5502 *arg = p + 1;
5503 return OK;
5507 * Copy the string into allocated memory, handling backslashed
5508 * characters.
5510 name = alloc((unsigned)(p - *arg + extra));
5511 if (name == NULL)
5512 return FAIL;
5513 rettv->v_type = VAR_STRING;
5514 rettv->vval.v_string = name;
5516 for (p = *arg + 1; *p != NUL && *p != '"'; )
5518 if (*p == '\\')
5520 switch (*++p)
5522 case 'b': *name++ = BS; ++p; break;
5523 case 'e': *name++ = ESC; ++p; break;
5524 case 'f': *name++ = FF; ++p; break;
5525 case 'n': *name++ = NL; ++p; break;
5526 case 'r': *name++ = CAR; ++p; break;
5527 case 't': *name++ = TAB; ++p; break;
5529 case 'X': /* hex: "\x1", "\x12" */
5530 case 'x':
5531 case 'u': /* Unicode: "\u0023" */
5532 case 'U':
5533 if (vim_isxdigit(p[1]))
5535 int n, nr;
5536 int c = toupper(*p);
5538 if (c == 'X')
5539 n = 2;
5540 else
5541 n = 4;
5542 nr = 0;
5543 while (--n >= 0 && vim_isxdigit(p[1]))
5545 ++p;
5546 nr = (nr << 4) + hex2nr(*p);
5548 ++p;
5549 #ifdef FEAT_MBYTE
5550 /* For "\u" store the number according to
5551 * 'encoding'. */
5552 if (c != 'X')
5553 name += (*mb_char2bytes)(nr, name);
5554 else
5555 #endif
5556 *name++ = nr;
5558 break;
5560 /* octal: "\1", "\12", "\123" */
5561 case '0':
5562 case '1':
5563 case '2':
5564 case '3':
5565 case '4':
5566 case '5':
5567 case '6':
5568 case '7': *name = *p++ - '0';
5569 if (*p >= '0' && *p <= '7')
5571 *name = (*name << 3) + *p++ - '0';
5572 if (*p >= '0' && *p <= '7')
5573 *name = (*name << 3) + *p++ - '0';
5575 ++name;
5576 break;
5578 /* Special key, e.g.: "\<C-W>" */
5579 case '<': extra = trans_special(&p, name, TRUE);
5580 if (extra != 0)
5582 name += extra;
5583 break;
5585 /* FALLTHROUGH */
5587 default: MB_COPY_CHAR(p, name);
5588 break;
5591 else
5592 MB_COPY_CHAR(p, name);
5595 *name = NUL;
5596 *arg = p + 1;
5598 return OK;
5602 * Allocate a variable for a 'str''ing' constant.
5603 * Return OK or FAIL.
5605 static int
5606 get_lit_string_tv(arg, rettv, evaluate)
5607 char_u **arg;
5608 typval_T *rettv;
5609 int evaluate;
5611 char_u *p;
5612 char_u *str;
5613 int reduce = 0;
5616 * Find the end of the string, skipping ''.
5618 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5620 if (*p == '\'')
5622 if (p[1] != '\'')
5623 break;
5624 ++reduce;
5625 ++p;
5629 if (*p != '\'')
5631 EMSG2(_("E115: Missing quote: %s"), *arg);
5632 return FAIL;
5635 /* If only parsing return after setting "*arg" */
5636 if (!evaluate)
5638 *arg = p + 1;
5639 return OK;
5643 * Copy the string into allocated memory, handling '' to ' reduction.
5645 str = alloc((unsigned)((p - *arg) - reduce));
5646 if (str == NULL)
5647 return FAIL;
5648 rettv->v_type = VAR_STRING;
5649 rettv->vval.v_string = str;
5651 for (p = *arg + 1; *p != NUL; )
5653 if (*p == '\'')
5655 if (p[1] != '\'')
5656 break;
5657 ++p;
5659 MB_COPY_CHAR(p, str);
5661 *str = NUL;
5662 *arg = p + 1;
5664 return OK;
5668 * Allocate a variable for a List and fill it from "*arg".
5669 * Return OK or FAIL.
5671 static int
5672 get_list_tv(arg, rettv, evaluate)
5673 char_u **arg;
5674 typval_T *rettv;
5675 int evaluate;
5677 list_T *l = NULL;
5678 typval_T tv;
5679 listitem_T *item;
5681 if (evaluate)
5683 l = list_alloc();
5684 if (l == NULL)
5685 return FAIL;
5688 *arg = skipwhite(*arg + 1);
5689 while (**arg != ']' && **arg != NUL)
5691 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5692 goto failret;
5693 if (evaluate)
5695 item = listitem_alloc();
5696 if (item != NULL)
5698 item->li_tv = tv;
5699 item->li_tv.v_lock = 0;
5700 list_append(l, item);
5702 else
5703 clear_tv(&tv);
5706 if (**arg == ']')
5707 break;
5708 if (**arg != ',')
5710 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5711 goto failret;
5713 *arg = skipwhite(*arg + 1);
5716 if (**arg != ']')
5718 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5719 failret:
5720 if (evaluate)
5721 list_free(l, TRUE);
5722 return FAIL;
5725 *arg = skipwhite(*arg + 1);
5726 if (evaluate)
5728 rettv->v_type = VAR_LIST;
5729 rettv->vval.v_list = l;
5730 ++l->lv_refcount;
5733 return OK;
5737 * Allocate an empty header for a list.
5738 * Caller should take care of the reference count.
5740 list_T *
5741 list_alloc()
5743 list_T *l;
5745 l = (list_T *)alloc_clear(sizeof(list_T));
5746 if (l != NULL)
5748 /* Prepend the list to the list of lists for garbage collection. */
5749 if (first_list != NULL)
5750 first_list->lv_used_prev = l;
5751 l->lv_used_prev = NULL;
5752 l->lv_used_next = first_list;
5753 first_list = l;
5755 return l;
5759 * Allocate an empty list for a return value.
5760 * Returns OK or FAIL.
5762 static int
5763 rettv_list_alloc(rettv)
5764 typval_T *rettv;
5766 list_T *l = list_alloc();
5768 if (l == NULL)
5769 return FAIL;
5771 rettv->vval.v_list = l;
5772 rettv->v_type = VAR_LIST;
5773 ++l->lv_refcount;
5774 return OK;
5778 * Unreference a list: decrement the reference count and free it when it
5779 * becomes zero.
5781 void
5782 list_unref(l)
5783 list_T *l;
5785 if (l != NULL && --l->lv_refcount <= 0)
5786 list_free(l, TRUE);
5790 * Free a list, including all items it points to.
5791 * Ignores the reference count.
5793 void
5794 list_free(l, recurse)
5795 list_T *l;
5796 int recurse; /* Free Lists and Dictionaries recursively. */
5798 listitem_T *item;
5800 /* Remove the list from the list of lists for garbage collection. */
5801 if (l->lv_used_prev == NULL)
5802 first_list = l->lv_used_next;
5803 else
5804 l->lv_used_prev->lv_used_next = l->lv_used_next;
5805 if (l->lv_used_next != NULL)
5806 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5808 for (item = l->lv_first; item != NULL; item = l->lv_first)
5810 /* Remove the item before deleting it. */
5811 l->lv_first = item->li_next;
5812 if (recurse || (item->li_tv.v_type != VAR_LIST
5813 && item->li_tv.v_type != VAR_DICT))
5814 clear_tv(&item->li_tv);
5815 vim_free(item);
5817 vim_free(l);
5821 * Allocate a list item.
5823 static listitem_T *
5824 listitem_alloc()
5826 return (listitem_T *)alloc(sizeof(listitem_T));
5830 * Free a list item. Also clears the value. Does not notify watchers.
5832 static void
5833 listitem_free(item)
5834 listitem_T *item;
5836 clear_tv(&item->li_tv);
5837 vim_free(item);
5841 * Remove a list item from a List and free it. Also clears the value.
5843 static void
5844 listitem_remove(l, item)
5845 list_T *l;
5846 listitem_T *item;
5848 list_remove(l, item, item);
5849 listitem_free(item);
5853 * Get the number of items in a list.
5855 static long
5856 list_len(l)
5857 list_T *l;
5859 if (l == NULL)
5860 return 0L;
5861 return l->lv_len;
5865 * Return TRUE when two lists have exactly the same values.
5867 static int
5868 list_equal(l1, l2, ic)
5869 list_T *l1;
5870 list_T *l2;
5871 int ic; /* ignore case for strings */
5873 listitem_T *item1, *item2;
5875 if (l1 == NULL || l2 == NULL)
5876 return FALSE;
5877 if (l1 == l2)
5878 return TRUE;
5879 if (list_len(l1) != list_len(l2))
5880 return FALSE;
5882 for (item1 = l1->lv_first, item2 = l2->lv_first;
5883 item1 != NULL && item2 != NULL;
5884 item1 = item1->li_next, item2 = item2->li_next)
5885 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5886 return FALSE;
5887 return item1 == NULL && item2 == NULL;
5890 #if defined(FEAT_PYTHON) || defined(FEAT_MZSCHEME) || defined(PROTO)
5892 * Return the dictitem that an entry in a hashtable points to.
5894 dictitem_T *
5895 dict_lookup(hi)
5896 hashitem_T *hi;
5898 return HI2DI(hi);
5900 #endif
5903 * Return TRUE when two dictionaries have exactly the same key/values.
5905 static int
5906 dict_equal(d1, d2, ic)
5907 dict_T *d1;
5908 dict_T *d2;
5909 int ic; /* ignore case for strings */
5911 hashitem_T *hi;
5912 dictitem_T *item2;
5913 int todo;
5915 if (d1 == NULL || d2 == NULL)
5916 return FALSE;
5917 if (d1 == d2)
5918 return TRUE;
5919 if (dict_len(d1) != dict_len(d2))
5920 return FALSE;
5922 todo = (int)d1->dv_hashtab.ht_used;
5923 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5925 if (!HASHITEM_EMPTY(hi))
5927 item2 = dict_find(d2, hi->hi_key, -1);
5928 if (item2 == NULL)
5929 return FALSE;
5930 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5931 return FALSE;
5932 --todo;
5935 return TRUE;
5939 * Return TRUE if "tv1" and "tv2" have the same value.
5940 * Compares the items just like "==" would compare them, but strings and
5941 * numbers are different. Floats and numbers are also different.
5943 static int
5944 tv_equal(tv1, tv2, ic)
5945 typval_T *tv1;
5946 typval_T *tv2;
5947 int ic; /* ignore case */
5949 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5950 char_u *s1, *s2;
5951 static int recursive = 0; /* cach recursive loops */
5952 int r;
5954 if (tv1->v_type != tv2->v_type)
5955 return FALSE;
5956 /* Catch lists and dicts that have an endless loop by limiting
5957 * recursiveness to 1000. We guess they are equal then. */
5958 if (recursive >= 1000)
5959 return TRUE;
5961 switch (tv1->v_type)
5963 case VAR_LIST:
5964 ++recursive;
5965 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5966 --recursive;
5967 return r;
5969 case VAR_DICT:
5970 ++recursive;
5971 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5972 --recursive;
5973 return r;
5975 case VAR_FUNC:
5976 return (tv1->vval.v_string != NULL
5977 && tv2->vval.v_string != NULL
5978 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5980 case VAR_NUMBER:
5981 return tv1->vval.v_number == tv2->vval.v_number;
5983 #ifdef FEAT_FLOAT
5984 case VAR_FLOAT:
5985 return tv1->vval.v_float == tv2->vval.v_float;
5986 #endif
5988 case VAR_STRING:
5989 s1 = get_tv_string_buf(tv1, buf1);
5990 s2 = get_tv_string_buf(tv2, buf2);
5991 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5994 EMSG2(_(e_intern2), "tv_equal()");
5995 return TRUE;
5999 * Locate item with index "n" in list "l" and return it.
6000 * A negative index is counted from the end; -1 is the last item.
6001 * Returns NULL when "n" is out of range.
6003 static listitem_T *
6004 list_find(l, n)
6005 list_T *l;
6006 long n;
6008 listitem_T *item;
6009 long idx;
6011 if (l == NULL)
6012 return NULL;
6014 /* Negative index is relative to the end. */
6015 if (n < 0)
6016 n = l->lv_len + n;
6018 /* Check for index out of range. */
6019 if (n < 0 || n >= l->lv_len)
6020 return NULL;
6022 /* When there is a cached index may start search from there. */
6023 if (l->lv_idx_item != NULL)
6025 if (n < l->lv_idx / 2)
6027 /* closest to the start of the list */
6028 item = l->lv_first;
6029 idx = 0;
6031 else if (n > (l->lv_idx + l->lv_len) / 2)
6033 /* closest to the end of the list */
6034 item = l->lv_last;
6035 idx = l->lv_len - 1;
6037 else
6039 /* closest to the cached index */
6040 item = l->lv_idx_item;
6041 idx = l->lv_idx;
6044 else
6046 if (n < l->lv_len / 2)
6048 /* closest to the start of the list */
6049 item = l->lv_first;
6050 idx = 0;
6052 else
6054 /* closest to the end of the list */
6055 item = l->lv_last;
6056 idx = l->lv_len - 1;
6060 while (n > idx)
6062 /* search forward */
6063 item = item->li_next;
6064 ++idx;
6066 while (n < idx)
6068 /* search backward */
6069 item = item->li_prev;
6070 --idx;
6073 /* cache the used index */
6074 l->lv_idx = idx;
6075 l->lv_idx_item = item;
6077 return item;
6081 * Get list item "l[idx]" as a number.
6083 static long
6084 list_find_nr(l, idx, errorp)
6085 list_T *l;
6086 long idx;
6087 int *errorp; /* set to TRUE when something wrong */
6089 listitem_T *li;
6091 li = list_find(l, idx);
6092 if (li == NULL)
6094 if (errorp != NULL)
6095 *errorp = TRUE;
6096 return -1L;
6098 return get_tv_number_chk(&li->li_tv, errorp);
6102 * Get list item "l[idx - 1]" as a string. Returns NULL for failure.
6104 char_u *
6105 list_find_str(l, idx)
6106 list_T *l;
6107 long idx;
6109 listitem_T *li;
6111 li = list_find(l, idx - 1);
6112 if (li == NULL)
6114 EMSGN(_(e_listidx), idx);
6115 return NULL;
6117 return get_tv_string(&li->li_tv);
6121 * Locate "item" list "l" and return its index.
6122 * Returns -1 when "item" is not in the list.
6124 static long
6125 list_idx_of_item(l, item)
6126 list_T *l;
6127 listitem_T *item;
6129 long idx = 0;
6130 listitem_T *li;
6132 if (l == NULL)
6133 return -1;
6134 idx = 0;
6135 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
6136 ++idx;
6137 if (li == NULL)
6138 return -1;
6139 return idx;
6143 * Append item "item" to the end of list "l".
6145 static void
6146 list_append(l, item)
6147 list_T *l;
6148 listitem_T *item;
6150 if (l->lv_last == NULL)
6152 /* empty list */
6153 l->lv_first = item;
6154 l->lv_last = item;
6155 item->li_prev = NULL;
6157 else
6159 l->lv_last->li_next = item;
6160 item->li_prev = l->lv_last;
6161 l->lv_last = item;
6163 ++l->lv_len;
6164 item->li_next = NULL;
6168 * Append typval_T "tv" to the end of list "l".
6169 * Return FAIL when out of memory.
6172 list_append_tv(l, tv)
6173 list_T *l;
6174 typval_T *tv;
6176 listitem_T *li = listitem_alloc();
6178 if (li == NULL)
6179 return FAIL;
6180 copy_tv(tv, &li->li_tv);
6181 list_append(l, li);
6182 return OK;
6186 * Add a dictionary to a list. Used by getqflist().
6187 * Return FAIL when out of memory.
6190 list_append_dict(list, dict)
6191 list_T *list;
6192 dict_T *dict;
6194 listitem_T *li = listitem_alloc();
6196 if (li == NULL)
6197 return FAIL;
6198 li->li_tv.v_type = VAR_DICT;
6199 li->li_tv.v_lock = 0;
6200 li->li_tv.vval.v_dict = dict;
6201 list_append(list, li);
6202 ++dict->dv_refcount;
6203 return OK;
6207 * Make a copy of "str" and append it as an item to list "l".
6208 * When "len" >= 0 use "str[len]".
6209 * Returns FAIL when out of memory.
6212 list_append_string(l, str, len)
6213 list_T *l;
6214 char_u *str;
6215 int len;
6217 listitem_T *li = listitem_alloc();
6219 if (li == NULL)
6220 return FAIL;
6221 list_append(l, li);
6222 li->li_tv.v_type = VAR_STRING;
6223 li->li_tv.v_lock = 0;
6224 if (str == NULL)
6225 li->li_tv.vval.v_string = NULL;
6226 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
6227 : vim_strsave(str))) == NULL)
6228 return FAIL;
6229 return OK;
6233 * Append "n" to list "l".
6234 * Returns FAIL when out of memory.
6236 static int
6237 list_append_number(l, n)
6238 list_T *l;
6239 varnumber_T n;
6241 listitem_T *li;
6243 li = listitem_alloc();
6244 if (li == NULL)
6245 return FAIL;
6246 li->li_tv.v_type = VAR_NUMBER;
6247 li->li_tv.v_lock = 0;
6248 li->li_tv.vval.v_number = n;
6249 list_append(l, li);
6250 return OK;
6254 * Insert typval_T "tv" in list "l" before "item".
6255 * If "item" is NULL append at the end.
6256 * Return FAIL when out of memory.
6258 static int
6259 list_insert_tv(l, tv, item)
6260 list_T *l;
6261 typval_T *tv;
6262 listitem_T *item;
6264 listitem_T *ni = listitem_alloc();
6266 if (ni == NULL)
6267 return FAIL;
6268 copy_tv(tv, &ni->li_tv);
6269 if (item == NULL)
6270 /* Append new item at end of list. */
6271 list_append(l, ni);
6272 else
6274 /* Insert new item before existing item. */
6275 ni->li_prev = item->li_prev;
6276 ni->li_next = item;
6277 if (item->li_prev == NULL)
6279 l->lv_first = ni;
6280 ++l->lv_idx;
6282 else
6284 item->li_prev->li_next = ni;
6285 l->lv_idx_item = NULL;
6287 item->li_prev = ni;
6288 ++l->lv_len;
6290 return OK;
6294 * Extend "l1" with "l2".
6295 * If "bef" is NULL append at the end, otherwise insert before this item.
6296 * Returns FAIL when out of memory.
6298 static int
6299 list_extend(l1, l2, bef)
6300 list_T *l1;
6301 list_T *l2;
6302 listitem_T *bef;
6304 listitem_T *item;
6305 int todo = l2->lv_len;
6307 /* We also quit the loop when we have inserted the original item count of
6308 * the list, avoid a hang when we extend a list with itself. */
6309 for (item = l2->lv_first; item != NULL && --todo >= 0; item = item->li_next)
6310 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
6311 return FAIL;
6312 return OK;
6316 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
6317 * Return FAIL when out of memory.
6319 static int
6320 list_concat(l1, l2, tv)
6321 list_T *l1;
6322 list_T *l2;
6323 typval_T *tv;
6325 list_T *l;
6327 if (l1 == NULL || l2 == NULL)
6328 return FAIL;
6330 /* make a copy of the first list. */
6331 l = list_copy(l1, FALSE, 0);
6332 if (l == NULL)
6333 return FAIL;
6334 tv->v_type = VAR_LIST;
6335 tv->vval.v_list = l;
6337 /* append all items from the second list */
6338 return list_extend(l, l2, NULL);
6342 * Make a copy of list "orig". Shallow if "deep" is FALSE.
6343 * The refcount of the new list is set to 1.
6344 * See item_copy() for "copyID".
6345 * Returns NULL when out of memory.
6347 static list_T *
6348 list_copy(orig, deep, copyID)
6349 list_T *orig;
6350 int deep;
6351 int copyID;
6353 list_T *copy;
6354 listitem_T *item;
6355 listitem_T *ni;
6357 if (orig == NULL)
6358 return NULL;
6360 copy = list_alloc();
6361 if (copy != NULL)
6363 if (copyID != 0)
6365 /* Do this before adding the items, because one of the items may
6366 * refer back to this list. */
6367 orig->lv_copyID = copyID;
6368 orig->lv_copylist = copy;
6370 for (item = orig->lv_first; item != NULL && !got_int;
6371 item = item->li_next)
6373 ni = listitem_alloc();
6374 if (ni == NULL)
6375 break;
6376 if (deep)
6378 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
6380 vim_free(ni);
6381 break;
6384 else
6385 copy_tv(&item->li_tv, &ni->li_tv);
6386 list_append(copy, ni);
6388 ++copy->lv_refcount;
6389 if (item != NULL)
6391 list_unref(copy);
6392 copy = NULL;
6396 return copy;
6400 * Remove items "item" to "item2" from list "l".
6401 * Does not free the listitem or the value!
6403 static void
6404 list_remove(l, item, item2)
6405 list_T *l;
6406 listitem_T *item;
6407 listitem_T *item2;
6409 listitem_T *ip;
6411 /* notify watchers */
6412 for (ip = item; ip != NULL; ip = ip->li_next)
6414 --l->lv_len;
6415 list_fix_watch(l, ip);
6416 if (ip == item2)
6417 break;
6420 if (item2->li_next == NULL)
6421 l->lv_last = item->li_prev;
6422 else
6423 item2->li_next->li_prev = item->li_prev;
6424 if (item->li_prev == NULL)
6425 l->lv_first = item2->li_next;
6426 else
6427 item->li_prev->li_next = item2->li_next;
6428 l->lv_idx_item = NULL;
6432 * Return an allocated string with the string representation of a list.
6433 * May return NULL.
6435 static char_u *
6436 list2string(tv, copyID)
6437 typval_T *tv;
6438 int copyID;
6440 garray_T ga;
6442 if (tv->vval.v_list == NULL)
6443 return NULL;
6444 ga_init2(&ga, (int)sizeof(char), 80);
6445 ga_append(&ga, '[');
6446 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6448 vim_free(ga.ga_data);
6449 return NULL;
6451 ga_append(&ga, ']');
6452 ga_append(&ga, NUL);
6453 return (char_u *)ga.ga_data;
6457 * Join list "l" into a string in "*gap", using separator "sep".
6458 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6459 * Return FAIL or OK.
6461 static int
6462 list_join(gap, l, sep, echo, copyID)
6463 garray_T *gap;
6464 list_T *l;
6465 char_u *sep;
6466 int echo;
6467 int copyID;
6469 int first = TRUE;
6470 char_u *tofree;
6471 char_u numbuf[NUMBUFLEN];
6472 listitem_T *item;
6473 char_u *s;
6475 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6477 if (first)
6478 first = FALSE;
6479 else
6480 ga_concat(gap, sep);
6482 if (echo)
6483 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6484 else
6485 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6486 if (s != NULL)
6487 ga_concat(gap, s);
6488 vim_free(tofree);
6489 if (s == NULL)
6490 return FAIL;
6491 line_breakcheck();
6493 return OK;
6497 * Garbage collection for lists and dictionaries.
6499 * We use reference counts to be able to free most items right away when they
6500 * are no longer used. But for composite items it's possible that it becomes
6501 * unused while the reference count is > 0: When there is a recursive
6502 * reference. Example:
6503 * :let l = [1, 2, 3]
6504 * :let d = {9: l}
6505 * :let l[1] = d
6507 * Since this is quite unusual we handle this with garbage collection: every
6508 * once in a while find out which lists and dicts are not referenced from any
6509 * variable.
6511 * Here is a good reference text about garbage collection (refers to Python
6512 * but it applies to all reference-counting mechanisms):
6513 * http://python.ca/nas/python/gc/
6517 * Do garbage collection for lists and dicts.
6518 * Return TRUE if some memory was freed.
6521 garbage_collect()
6523 int copyID;
6524 buf_T *buf;
6525 win_T *wp;
6526 int i;
6527 funccall_T *fc, **pfc;
6528 int did_free;
6529 int did_free_funccal = FALSE;
6530 #ifdef FEAT_WINDOWS
6531 tabpage_T *tp;
6532 #endif
6534 /* Only do this once. */
6535 want_garbage_collect = FALSE;
6536 may_garbage_collect = FALSE;
6537 garbage_collect_at_exit = FALSE;
6539 /* We advance by two because we add one for items referenced through
6540 * previous_funccal. */
6541 current_copyID += COPYID_INC;
6542 copyID = current_copyID;
6545 * 1. Go through all accessible variables and mark all lists and dicts
6546 * with copyID.
6549 /* Don't free variables in the previous_funccal list unless they are only
6550 * referenced through previous_funccal. This must be first, because if
6551 * the item is referenced elsewhere the funccal must not be freed. */
6552 for (fc = previous_funccal; fc != NULL; fc = fc->caller)
6554 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1);
6555 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1);
6558 /* script-local variables */
6559 for (i = 1; i <= ga_scripts.ga_len; ++i)
6560 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6562 /* buffer-local variables */
6563 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6564 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6566 /* window-local variables */
6567 FOR_ALL_TAB_WINDOWS(tp, wp)
6568 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6570 #ifdef FEAT_WINDOWS
6571 /* tabpage-local variables */
6572 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6573 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6574 #endif
6576 /* global variables */
6577 set_ref_in_ht(&globvarht, copyID);
6579 /* function-local variables */
6580 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6582 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6583 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6586 /* v: vars */
6587 set_ref_in_ht(&vimvarht, copyID);
6590 * 2. Free lists and dictionaries that are not referenced.
6592 did_free = free_unref_items(copyID);
6595 * 3. Check if any funccal can be freed now.
6597 for (pfc = &previous_funccal; *pfc != NULL; )
6599 if (can_free_funccal(*pfc, copyID))
6601 fc = *pfc;
6602 *pfc = fc->caller;
6603 free_funccal(fc, TRUE);
6604 did_free = TRUE;
6605 did_free_funccal = TRUE;
6607 else
6608 pfc = &(*pfc)->caller;
6610 if (did_free_funccal)
6611 /* When a funccal was freed some more items might be garbage
6612 * collected, so run again. */
6613 (void)garbage_collect();
6615 return did_free;
6619 * Free lists and dictionaries that are no longer referenced.
6621 static int
6622 free_unref_items(copyID)
6623 int copyID;
6625 dict_T *dd;
6626 list_T *ll;
6627 int did_free = FALSE;
6630 * Go through the list of dicts and free items without the copyID.
6632 for (dd = first_dict; dd != NULL; )
6633 if ((dd->dv_copyID & COPYID_MASK) != (copyID & COPYID_MASK))
6635 /* Free the Dictionary and ordinary items it contains, but don't
6636 * recurse into Lists and Dictionaries, they will be in the list
6637 * of dicts or list of lists. */
6638 dict_free(dd, FALSE);
6639 did_free = TRUE;
6641 /* restart, next dict may also have been freed */
6642 dd = first_dict;
6644 else
6645 dd = dd->dv_used_next;
6648 * Go through the list of lists and free items without the copyID.
6649 * But don't free a list that has a watcher (used in a for loop), these
6650 * are not referenced anywhere.
6652 for (ll = first_list; ll != NULL; )
6653 if ((ll->lv_copyID & COPYID_MASK) != (copyID & COPYID_MASK)
6654 && ll->lv_watch == NULL)
6656 /* Free the List and ordinary items it contains, but don't recurse
6657 * into Lists and Dictionaries, they will be in the list of dicts
6658 * or list of lists. */
6659 list_free(ll, FALSE);
6660 did_free = TRUE;
6662 /* restart, next list may also have been freed */
6663 ll = first_list;
6665 else
6666 ll = ll->lv_used_next;
6668 return did_free;
6672 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6674 static void
6675 set_ref_in_ht(ht, copyID)
6676 hashtab_T *ht;
6677 int copyID;
6679 int todo;
6680 hashitem_T *hi;
6682 todo = (int)ht->ht_used;
6683 for (hi = ht->ht_array; todo > 0; ++hi)
6684 if (!HASHITEM_EMPTY(hi))
6686 --todo;
6687 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6692 * Mark all lists and dicts referenced through list "l" with "copyID".
6694 static void
6695 set_ref_in_list(l, copyID)
6696 list_T *l;
6697 int copyID;
6699 listitem_T *li;
6701 for (li = l->lv_first; li != NULL; li = li->li_next)
6702 set_ref_in_item(&li->li_tv, copyID);
6706 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6708 static void
6709 set_ref_in_item(tv, copyID)
6710 typval_T *tv;
6711 int copyID;
6713 dict_T *dd;
6714 list_T *ll;
6716 switch (tv->v_type)
6718 case VAR_DICT:
6719 dd = tv->vval.v_dict;
6720 if (dd != NULL && dd->dv_copyID != copyID)
6722 /* Didn't see this dict yet. */
6723 dd->dv_copyID = copyID;
6724 set_ref_in_ht(&dd->dv_hashtab, copyID);
6726 break;
6728 case VAR_LIST:
6729 ll = tv->vval.v_list;
6730 if (ll != NULL && ll->lv_copyID != copyID)
6732 /* Didn't see this list yet. */
6733 ll->lv_copyID = copyID;
6734 set_ref_in_list(ll, copyID);
6736 break;
6738 return;
6742 * Allocate an empty header for a dictionary.
6744 dict_T *
6745 dict_alloc()
6747 dict_T *d;
6749 d = (dict_T *)alloc(sizeof(dict_T));
6750 if (d != NULL)
6752 /* Add the list to the list of dicts for garbage collection. */
6753 if (first_dict != NULL)
6754 first_dict->dv_used_prev = d;
6755 d->dv_used_next = first_dict;
6756 d->dv_used_prev = NULL;
6757 first_dict = d;
6759 hash_init(&d->dv_hashtab);
6760 d->dv_lock = 0;
6761 d->dv_refcount = 0;
6762 d->dv_copyID = 0;
6764 return d;
6768 * Unreference a Dictionary: decrement the reference count and free it when it
6769 * becomes zero.
6771 static void
6772 dict_unref(d)
6773 dict_T *d;
6775 if (d != NULL && --d->dv_refcount <= 0)
6776 dict_free(d, TRUE);
6780 * Free a Dictionary, including all items it contains.
6781 * Ignores the reference count.
6783 static void
6784 dict_free(d, recurse)
6785 dict_T *d;
6786 int recurse; /* Free Lists and Dictionaries recursively. */
6788 int todo;
6789 hashitem_T *hi;
6790 dictitem_T *di;
6792 /* Remove the dict from the list of dicts for garbage collection. */
6793 if (d->dv_used_prev == NULL)
6794 first_dict = d->dv_used_next;
6795 else
6796 d->dv_used_prev->dv_used_next = d->dv_used_next;
6797 if (d->dv_used_next != NULL)
6798 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6800 /* Lock the hashtab, we don't want it to resize while freeing items. */
6801 hash_lock(&d->dv_hashtab);
6802 todo = (int)d->dv_hashtab.ht_used;
6803 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6805 if (!HASHITEM_EMPTY(hi))
6807 /* Remove the item before deleting it, just in case there is
6808 * something recursive causing trouble. */
6809 di = HI2DI(hi);
6810 hash_remove(&d->dv_hashtab, hi);
6811 if (recurse || (di->di_tv.v_type != VAR_LIST
6812 && di->di_tv.v_type != VAR_DICT))
6813 clear_tv(&di->di_tv);
6814 vim_free(di);
6815 --todo;
6818 hash_clear(&d->dv_hashtab);
6819 vim_free(d);
6823 * Allocate a Dictionary item.
6824 * The "key" is copied to the new item.
6825 * Note that the value of the item "di_tv" still needs to be initialized!
6826 * Returns NULL when out of memory.
6828 dictitem_T *
6829 dictitem_alloc(key)
6830 char_u *key;
6832 dictitem_T *di;
6834 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6835 if (di != NULL)
6837 STRCPY(di->di_key, key);
6838 di->di_flags = 0;
6840 return di;
6844 * Make a copy of a Dictionary item.
6846 static dictitem_T *
6847 dictitem_copy(org)
6848 dictitem_T *org;
6850 dictitem_T *di;
6852 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6853 + STRLEN(org->di_key)));
6854 if (di != NULL)
6856 STRCPY(di->di_key, org->di_key);
6857 di->di_flags = 0;
6858 copy_tv(&org->di_tv, &di->di_tv);
6860 return di;
6864 * Remove item "item" from Dictionary "dict" and free it.
6866 static void
6867 dictitem_remove(dict, item)
6868 dict_T *dict;
6869 dictitem_T *item;
6871 hashitem_T *hi;
6873 hi = hash_find(&dict->dv_hashtab, item->di_key);
6874 if (HASHITEM_EMPTY(hi))
6875 EMSG2(_(e_intern2), "dictitem_remove()");
6876 else
6877 hash_remove(&dict->dv_hashtab, hi);
6878 dictitem_free(item);
6882 * Free a dict item. Also clears the value.
6884 void
6885 dictitem_free(item)
6886 dictitem_T *item;
6888 clear_tv(&item->di_tv);
6889 vim_free(item);
6893 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6894 * The refcount of the new dict is set to 1.
6895 * See item_copy() for "copyID".
6896 * Returns NULL when out of memory.
6898 static dict_T *
6899 dict_copy(orig, deep, copyID)
6900 dict_T *orig;
6901 int deep;
6902 int copyID;
6904 dict_T *copy;
6905 dictitem_T *di;
6906 int todo;
6907 hashitem_T *hi;
6909 if (orig == NULL)
6910 return NULL;
6912 copy = dict_alloc();
6913 if (copy != NULL)
6915 if (copyID != 0)
6917 orig->dv_copyID = copyID;
6918 orig->dv_copydict = copy;
6920 todo = (int)orig->dv_hashtab.ht_used;
6921 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6923 if (!HASHITEM_EMPTY(hi))
6925 --todo;
6927 di = dictitem_alloc(hi->hi_key);
6928 if (di == NULL)
6929 break;
6930 if (deep)
6932 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6933 copyID) == FAIL)
6935 vim_free(di);
6936 break;
6939 else
6940 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6941 if (dict_add(copy, di) == FAIL)
6943 dictitem_free(di);
6944 break;
6949 ++copy->dv_refcount;
6950 if (todo > 0)
6952 dict_unref(copy);
6953 copy = NULL;
6957 return copy;
6961 * Add item "item" to Dictionary "d".
6962 * Returns FAIL when out of memory and when key already existed.
6965 dict_add(d, item)
6966 dict_T *d;
6967 dictitem_T *item;
6969 return hash_add(&d->dv_hashtab, item->di_key);
6973 * Add a number or string entry to dictionary "d".
6974 * When "str" is NULL use number "nr", otherwise use "str".
6975 * Returns FAIL when out of memory and when key already exists.
6978 dict_add_nr_str(d, key, nr, str)
6979 dict_T *d;
6980 char *key;
6981 long nr;
6982 char_u *str;
6984 dictitem_T *item;
6986 item = dictitem_alloc((char_u *)key);
6987 if (item == NULL)
6988 return FAIL;
6989 item->di_tv.v_lock = 0;
6990 if (str == NULL)
6992 item->di_tv.v_type = VAR_NUMBER;
6993 item->di_tv.vval.v_number = nr;
6995 else
6997 item->di_tv.v_type = VAR_STRING;
6998 item->di_tv.vval.v_string = vim_strsave(str);
7000 if (dict_add(d, item) == FAIL)
7002 dictitem_free(item);
7003 return FAIL;
7005 return OK;
7009 * Get the number of items in a Dictionary.
7011 static long
7012 dict_len(d)
7013 dict_T *d;
7015 if (d == NULL)
7016 return 0L;
7017 return (long)d->dv_hashtab.ht_used;
7021 * Find item "key[len]" in Dictionary "d".
7022 * If "len" is negative use strlen(key).
7023 * Returns NULL when not found.
7025 static dictitem_T *
7026 dict_find(d, key, len)
7027 dict_T *d;
7028 char_u *key;
7029 int len;
7031 #define AKEYLEN 200
7032 char_u buf[AKEYLEN];
7033 char_u *akey;
7034 char_u *tofree = NULL;
7035 hashitem_T *hi;
7037 if (len < 0)
7038 akey = key;
7039 else if (len >= AKEYLEN)
7041 tofree = akey = vim_strnsave(key, len);
7042 if (akey == NULL)
7043 return NULL;
7045 else
7047 /* Avoid a malloc/free by using buf[]. */
7048 vim_strncpy(buf, key, len);
7049 akey = buf;
7052 hi = hash_find(&d->dv_hashtab, akey);
7053 vim_free(tofree);
7054 if (HASHITEM_EMPTY(hi))
7055 return NULL;
7056 return HI2DI(hi);
7060 * Get a string item from a dictionary.
7061 * When "save" is TRUE allocate memory for it.
7062 * Returns NULL if the entry doesn't exist or out of memory.
7064 char_u *
7065 get_dict_string(d, key, save)
7066 dict_T *d;
7067 char_u *key;
7068 int save;
7070 dictitem_T *di;
7071 char_u *s;
7073 di = dict_find(d, key, -1);
7074 if (di == NULL)
7075 return NULL;
7076 s = get_tv_string(&di->di_tv);
7077 if (save && s != NULL)
7078 s = vim_strsave(s);
7079 return s;
7083 * Get a number item from a dictionary.
7084 * Returns 0 if the entry doesn't exist or out of memory.
7086 long
7087 get_dict_number(d, key)
7088 dict_T *d;
7089 char_u *key;
7091 dictitem_T *di;
7093 di = dict_find(d, key, -1);
7094 if (di == NULL)
7095 return 0;
7096 return get_tv_number(&di->di_tv);
7100 * Return an allocated string with the string representation of a Dictionary.
7101 * May return NULL.
7103 static char_u *
7104 dict2string(tv, copyID)
7105 typval_T *tv;
7106 int copyID;
7108 garray_T ga;
7109 int first = TRUE;
7110 char_u *tofree;
7111 char_u numbuf[NUMBUFLEN];
7112 hashitem_T *hi;
7113 char_u *s;
7114 dict_T *d;
7115 int todo;
7117 if ((d = tv->vval.v_dict) == NULL)
7118 return NULL;
7119 ga_init2(&ga, (int)sizeof(char), 80);
7120 ga_append(&ga, '{');
7122 todo = (int)d->dv_hashtab.ht_used;
7123 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
7125 if (!HASHITEM_EMPTY(hi))
7127 --todo;
7129 if (first)
7130 first = FALSE;
7131 else
7132 ga_concat(&ga, (char_u *)", ");
7134 tofree = string_quote(hi->hi_key, FALSE);
7135 if (tofree != NULL)
7137 ga_concat(&ga, tofree);
7138 vim_free(tofree);
7140 ga_concat(&ga, (char_u *)": ");
7141 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
7142 if (s != NULL)
7143 ga_concat(&ga, s);
7144 vim_free(tofree);
7145 if (s == NULL)
7146 break;
7149 if (todo > 0)
7151 vim_free(ga.ga_data);
7152 return NULL;
7155 ga_append(&ga, '}');
7156 ga_append(&ga, NUL);
7157 return (char_u *)ga.ga_data;
7161 * Allocate a variable for a Dictionary and fill it from "*arg".
7162 * Return OK or FAIL. Returns NOTDONE for {expr}.
7164 static int
7165 get_dict_tv(arg, rettv, evaluate)
7166 char_u **arg;
7167 typval_T *rettv;
7168 int evaluate;
7170 dict_T *d = NULL;
7171 typval_T tvkey;
7172 typval_T tv;
7173 char_u *key = NULL;
7174 dictitem_T *item;
7175 char_u *start = skipwhite(*arg + 1);
7176 char_u buf[NUMBUFLEN];
7179 * First check if it's not a curly-braces thing: {expr}.
7180 * Must do this without evaluating, otherwise a function may be called
7181 * twice. Unfortunately this means we need to call eval1() twice for the
7182 * first item.
7183 * But {} is an empty Dictionary.
7185 if (*start != '}')
7187 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
7188 return FAIL;
7189 if (*start == '}')
7190 return NOTDONE;
7193 if (evaluate)
7195 d = dict_alloc();
7196 if (d == NULL)
7197 return FAIL;
7199 tvkey.v_type = VAR_UNKNOWN;
7200 tv.v_type = VAR_UNKNOWN;
7202 *arg = skipwhite(*arg + 1);
7203 while (**arg != '}' && **arg != NUL)
7205 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
7206 goto failret;
7207 if (**arg != ':')
7209 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
7210 clear_tv(&tvkey);
7211 goto failret;
7213 if (evaluate)
7215 key = get_tv_string_buf_chk(&tvkey, buf);
7216 if (key == NULL || *key == NUL)
7218 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
7219 if (key != NULL)
7220 EMSG(_(e_emptykey));
7221 clear_tv(&tvkey);
7222 goto failret;
7226 *arg = skipwhite(*arg + 1);
7227 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
7229 if (evaluate)
7230 clear_tv(&tvkey);
7231 goto failret;
7233 if (evaluate)
7235 item = dict_find(d, key, -1);
7236 if (item != NULL)
7238 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
7239 clear_tv(&tvkey);
7240 clear_tv(&tv);
7241 goto failret;
7243 item = dictitem_alloc(key);
7244 clear_tv(&tvkey);
7245 if (item != NULL)
7247 item->di_tv = tv;
7248 item->di_tv.v_lock = 0;
7249 if (dict_add(d, item) == FAIL)
7250 dictitem_free(item);
7254 if (**arg == '}')
7255 break;
7256 if (**arg != ',')
7258 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
7259 goto failret;
7261 *arg = skipwhite(*arg + 1);
7264 if (**arg != '}')
7266 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
7267 failret:
7268 if (evaluate)
7269 dict_free(d, TRUE);
7270 return FAIL;
7273 *arg = skipwhite(*arg + 1);
7274 if (evaluate)
7276 rettv->v_type = VAR_DICT;
7277 rettv->vval.v_dict = d;
7278 ++d->dv_refcount;
7281 return OK;
7285 * Return a string with the string representation of a variable.
7286 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7287 * "numbuf" is used for a number.
7288 * Does not put quotes around strings, as ":echo" displays values.
7289 * When "copyID" is not NULL replace recursive lists and dicts with "...".
7290 * May return NULL.
7292 static char_u *
7293 echo_string(tv, tofree, numbuf, copyID)
7294 typval_T *tv;
7295 char_u **tofree;
7296 char_u *numbuf;
7297 int copyID;
7299 static int recurse = 0;
7300 char_u *r = NULL;
7302 if (recurse >= DICT_MAXNEST)
7304 EMSG(_("E724: variable nested too deep for displaying"));
7305 *tofree = NULL;
7306 return NULL;
7308 ++recurse;
7310 switch (tv->v_type)
7312 case VAR_FUNC:
7313 *tofree = NULL;
7314 r = tv->vval.v_string;
7315 break;
7317 case VAR_LIST:
7318 if (tv->vval.v_list == NULL)
7320 *tofree = NULL;
7321 r = NULL;
7323 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
7325 *tofree = NULL;
7326 r = (char_u *)"[...]";
7328 else
7330 tv->vval.v_list->lv_copyID = copyID;
7331 *tofree = list2string(tv, copyID);
7332 r = *tofree;
7334 break;
7336 case VAR_DICT:
7337 if (tv->vval.v_dict == NULL)
7339 *tofree = NULL;
7340 r = NULL;
7342 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
7344 *tofree = NULL;
7345 r = (char_u *)"{...}";
7347 else
7349 tv->vval.v_dict->dv_copyID = copyID;
7350 *tofree = dict2string(tv, copyID);
7351 r = *tofree;
7353 break;
7355 case VAR_STRING:
7356 case VAR_NUMBER:
7357 *tofree = NULL;
7358 r = get_tv_string_buf(tv, numbuf);
7359 break;
7361 #ifdef FEAT_FLOAT
7362 case VAR_FLOAT:
7363 *tofree = NULL;
7364 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
7365 r = numbuf;
7366 break;
7367 #endif
7369 default:
7370 EMSG2(_(e_intern2), "echo_string()");
7371 *tofree = NULL;
7374 --recurse;
7375 return r;
7379 * Return a string with the string representation of a variable.
7380 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7381 * "numbuf" is used for a number.
7382 * Puts quotes around strings, so that they can be parsed back by eval().
7383 * May return NULL.
7385 static char_u *
7386 tv2string(tv, tofree, numbuf, copyID)
7387 typval_T *tv;
7388 char_u **tofree;
7389 char_u *numbuf;
7390 int copyID;
7392 switch (tv->v_type)
7394 case VAR_FUNC:
7395 *tofree = string_quote(tv->vval.v_string, TRUE);
7396 return *tofree;
7397 case VAR_STRING:
7398 *tofree = string_quote(tv->vval.v_string, FALSE);
7399 return *tofree;
7400 #ifdef FEAT_FLOAT
7401 case VAR_FLOAT:
7402 *tofree = NULL;
7403 vim_snprintf((char *)numbuf, NUMBUFLEN - 1, "%g", tv->vval.v_float);
7404 return numbuf;
7405 #endif
7406 case VAR_NUMBER:
7407 case VAR_LIST:
7408 case VAR_DICT:
7409 break;
7410 default:
7411 EMSG2(_(e_intern2), "tv2string()");
7413 return echo_string(tv, tofree, numbuf, copyID);
7417 * Return string "str" in ' quotes, doubling ' characters.
7418 * If "str" is NULL an empty string is assumed.
7419 * If "function" is TRUE make it function('string').
7421 static char_u *
7422 string_quote(str, function)
7423 char_u *str;
7424 int function;
7426 unsigned len;
7427 char_u *p, *r, *s;
7429 len = (function ? 13 : 3);
7430 if (str != NULL)
7432 len += (unsigned)STRLEN(str);
7433 for (p = str; *p != NUL; mb_ptr_adv(p))
7434 if (*p == '\'')
7435 ++len;
7437 s = r = alloc(len);
7438 if (r != NULL)
7440 if (function)
7442 STRCPY(r, "function('");
7443 r += 10;
7445 else
7446 *r++ = '\'';
7447 if (str != NULL)
7448 for (p = str; *p != NUL; )
7450 if (*p == '\'')
7451 *r++ = '\'';
7452 MB_COPY_CHAR(p, r);
7454 *r++ = '\'';
7455 if (function)
7456 *r++ = ')';
7457 *r++ = NUL;
7459 return s;
7462 #ifdef FEAT_FLOAT
7464 * Convert the string "text" to a floating point number.
7465 * This uses strtod(). setlocale(LC_NUMERIC, "C") has been used to make sure
7466 * this always uses a decimal point.
7467 * Returns the length of the text that was consumed.
7469 static int
7470 string2float(text, value)
7471 char_u *text;
7472 float_T *value; /* result stored here */
7474 char *s = (char *)text;
7475 float_T f;
7477 f = strtod(s, &s);
7478 *value = f;
7479 return (int)((char_u *)s - text);
7481 #endif
7484 * Get the value of an environment variable.
7485 * "arg" is pointing to the '$'. It is advanced to after the name.
7486 * If the environment variable was not set, silently assume it is empty.
7487 * Always return OK.
7489 static int
7490 get_env_tv(arg, rettv, evaluate)
7491 char_u **arg;
7492 typval_T *rettv;
7493 int evaluate;
7495 char_u *string = NULL;
7496 int len;
7497 int cc;
7498 char_u *name;
7499 int mustfree = FALSE;
7501 ++*arg;
7502 name = *arg;
7503 len = get_env_len(arg);
7504 if (evaluate)
7506 if (len != 0)
7508 cc = name[len];
7509 name[len] = NUL;
7510 /* first try vim_getenv(), fast for normal environment vars */
7511 string = vim_getenv(name, &mustfree);
7512 if (string != NULL && *string != NUL)
7514 if (!mustfree)
7515 string = vim_strsave(string);
7517 else
7519 if (mustfree)
7520 vim_free(string);
7522 /* next try expanding things like $VIM and ${HOME} */
7523 string = expand_env_save(name - 1);
7524 if (string != NULL && *string == '$')
7526 vim_free(string);
7527 string = NULL;
7530 name[len] = cc;
7532 rettv->v_type = VAR_STRING;
7533 rettv->vval.v_string = string;
7536 return OK;
7540 * Array with names and number of arguments of all internal functions
7541 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7543 static struct fst
7545 char *f_name; /* function name */
7546 char f_min_argc; /* minimal number of arguments */
7547 char f_max_argc; /* maximal number of arguments */
7548 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7549 /* implementation of function */
7550 } functions[] =
7552 #ifdef FEAT_FLOAT
7553 {"abs", 1, 1, f_abs},
7554 {"acos", 1, 1, f_acos}, /* WJMc */
7555 #endif
7556 {"add", 2, 2, f_add},
7557 {"append", 2, 2, f_append},
7558 {"argc", 0, 0, f_argc},
7559 {"argidx", 0, 0, f_argidx},
7560 {"argv", 0, 1, f_argv},
7561 #ifdef FEAT_FLOAT
7562 {"asin", 1, 1, f_asin}, /* WJMc */
7563 {"atan", 1, 1, f_atan},
7564 {"atan2", 2, 2, f_atan2}, /* WJMc */
7565 #endif
7566 {"browse", 4, 4, f_browse},
7567 {"browsedir", 2, 2, f_browsedir},
7568 {"bufexists", 1, 1, f_bufexists},
7569 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7570 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7571 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7572 {"buflisted", 1, 1, f_buflisted},
7573 {"bufloaded", 1, 1, f_bufloaded},
7574 {"bufname", 1, 1, f_bufname},
7575 {"bufnr", 1, 2, f_bufnr},
7576 {"bufwinnr", 1, 1, f_bufwinnr},
7577 {"byte2line", 1, 1, f_byte2line},
7578 {"byteidx", 2, 2, f_byteidx},
7579 {"call", 2, 3, f_call},
7580 #ifdef FEAT_FLOAT
7581 {"ceil", 1, 1, f_ceil},
7582 #endif
7583 {"changenr", 0, 0, f_changenr},
7584 {"char2nr", 1, 1, f_char2nr},
7585 {"cindent", 1, 1, f_cindent},
7586 {"clearmatches", 0, 0, f_clearmatches},
7587 {"col", 1, 1, f_col},
7588 #if defined(FEAT_INS_EXPAND)
7589 {"complete", 2, 2, f_complete},
7590 {"complete_add", 1, 1, f_complete_add},
7591 {"complete_check", 0, 0, f_complete_check},
7592 #endif
7593 {"confirm", 1, 4, f_confirm},
7594 {"copy", 1, 1, f_copy},
7595 #ifdef FEAT_FLOAT
7596 {"cos", 1, 1, f_cos},
7597 {"cosh", 1, 1, f_cosh}, /* WJMc */
7598 #endif
7599 {"count", 2, 4, f_count},
7600 {"cscope_connection",0,3, f_cscope_connection},
7601 {"cursor", 1, 3, f_cursor},
7602 {"deepcopy", 1, 2, f_deepcopy},
7603 {"delete", 1, 1, f_delete},
7604 {"did_filetype", 0, 0, f_did_filetype},
7605 {"diff_filler", 1, 1, f_diff_filler},
7606 {"diff_hlID", 2, 2, f_diff_hlID},
7607 {"empty", 1, 1, f_empty},
7608 {"escape", 2, 2, f_escape},
7609 {"eval", 1, 1, f_eval},
7610 {"eventhandler", 0, 0, f_eventhandler},
7611 {"executable", 1, 1, f_executable},
7612 {"exists", 1, 1, f_exists},
7613 #ifdef FEAT_FLOAT
7614 {"exp", 1, 1, f_exp}, /* WJMc */
7615 #endif
7616 {"expand", 1, 2, f_expand},
7617 {"extend", 2, 3, f_extend},
7618 {"feedkeys", 1, 2, f_feedkeys},
7619 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7620 {"filereadable", 1, 1, f_filereadable},
7621 {"filewritable", 1, 1, f_filewritable},
7622 {"filter", 2, 2, f_filter},
7623 {"finddir", 1, 3, f_finddir},
7624 {"findfile", 1, 3, f_findfile},
7625 #ifdef FEAT_FLOAT
7626 {"float2nr", 1, 1, f_float2nr},
7627 {"floor", 1, 1, f_floor},
7628 {"fmod", 2, 2, f_fmod}, /* WJMc */
7629 #endif
7630 {"fnameescape", 1, 1, f_fnameescape},
7631 {"fnamemodify", 2, 2, f_fnamemodify},
7632 {"foldclosed", 1, 1, f_foldclosed},
7633 {"foldclosedend", 1, 1, f_foldclosedend},
7634 {"foldlevel", 1, 1, f_foldlevel},
7635 {"foldtext", 0, 0, f_foldtext},
7636 {"foldtextresult", 1, 1, f_foldtextresult},
7637 {"foreground", 0, 0, f_foreground},
7638 {"function", 1, 1, f_function},
7639 {"garbagecollect", 0, 1, f_garbagecollect},
7640 {"get", 2, 3, f_get},
7641 {"getbufline", 2, 3, f_getbufline},
7642 {"getbufvar", 2, 2, f_getbufvar},
7643 {"getchar", 0, 1, f_getchar},
7644 {"getcharmod", 0, 0, f_getcharmod},
7645 {"getcmdline", 0, 0, f_getcmdline},
7646 {"getcmdpos", 0, 0, f_getcmdpos},
7647 {"getcmdtype", 0, 0, f_getcmdtype},
7648 {"getcwd", 0, 0, f_getcwd},
7649 {"getfontname", 0, 1, f_getfontname},
7650 {"getfperm", 1, 1, f_getfperm},
7651 {"getfsize", 1, 1, f_getfsize},
7652 {"getftime", 1, 1, f_getftime},
7653 {"getftype", 1, 1, f_getftype},
7654 {"getline", 1, 2, f_getline},
7655 {"getloclist", 1, 1, f_getqflist},
7656 {"getmatches", 0, 0, f_getmatches},
7657 {"getpid", 0, 0, f_getpid},
7658 {"getpos", 1, 1, f_getpos},
7659 {"getqflist", 0, 0, f_getqflist},
7660 {"getreg", 0, 2, f_getreg},
7661 {"getregtype", 0, 1, f_getregtype},
7662 {"gettabwinvar", 3, 3, f_gettabwinvar},
7663 {"getwinposx", 0, 0, f_getwinposx},
7664 {"getwinposy", 0, 0, f_getwinposy},
7665 {"getwinvar", 2, 2, f_getwinvar},
7666 {"glob", 1, 2, f_glob},
7667 {"globpath", 2, 3, f_globpath},
7668 {"has", 1, 1, f_has},
7669 {"has_key", 2, 2, f_has_key},
7670 {"haslocaldir", 0, 0, f_haslocaldir},
7671 {"hasmapto", 1, 3, f_hasmapto},
7672 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7673 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7674 {"histadd", 2, 2, f_histadd},
7675 {"histdel", 1, 2, f_histdel},
7676 {"histget", 1, 2, f_histget},
7677 {"histnr", 1, 1, f_histnr},
7678 {"hlID", 1, 1, f_hlID},
7679 {"hlexists", 1, 1, f_hlexists},
7680 {"hostname", 0, 0, f_hostname},
7681 {"iconv", 3, 3, f_iconv},
7682 {"indent", 1, 1, f_indent},
7683 {"index", 2, 4, f_index},
7684 {"input", 1, 3, f_input},
7685 {"inputdialog", 1, 3, f_inputdialog},
7686 {"inputlist", 1, 1, f_inputlist},
7687 {"inputrestore", 0, 0, f_inputrestore},
7688 {"inputsave", 0, 0, f_inputsave},
7689 {"inputsecret", 1, 2, f_inputsecret},
7690 {"insert", 2, 3, f_insert},
7691 {"isdirectory", 1, 1, f_isdirectory},
7692 {"islocked", 1, 1, f_islocked},
7693 {"items", 1, 1, f_items},
7694 {"join", 1, 2, f_join},
7695 {"keys", 1, 1, f_keys},
7696 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7697 {"len", 1, 1, f_len},
7698 {"libcall", 3, 3, f_libcall},
7699 {"libcallnr", 3, 3, f_libcallnr},
7700 {"line", 1, 1, f_line},
7701 {"line2byte", 1, 1, f_line2byte},
7702 {"lispindent", 1, 1, f_lispindent},
7703 {"localtime", 0, 0, f_localtime},
7704 #ifdef FEAT_FLOAT
7705 {"log", 1, 1, f_log}, /* WJMc */
7706 {"log10", 1, 1, f_log10},
7707 #endif
7708 {"map", 2, 2, f_map},
7709 {"maparg", 1, 3, f_maparg},
7710 {"mapcheck", 1, 3, f_mapcheck},
7711 {"match", 2, 4, f_match},
7712 {"matchadd", 2, 4, f_matchadd},
7713 {"matcharg", 1, 1, f_matcharg},
7714 {"matchdelete", 1, 1, f_matchdelete},
7715 {"matchend", 2, 4, f_matchend},
7716 {"matchlist", 2, 4, f_matchlist},
7717 {"matchstr", 2, 4, f_matchstr},
7718 {"max", 1, 1, f_max},
7719 {"min", 1, 1, f_min},
7720 #ifdef vim_mkdir
7721 {"mkdir", 1, 3, f_mkdir},
7722 #endif
7723 {"mode", 0, 1, f_mode},
7724 #ifdef FEAT_MZSCHEME
7725 {"mzeval", 1, 1, f_mzeval},
7726 #endif
7727 {"nextnonblank", 1, 1, f_nextnonblank},
7728 {"nr2char", 1, 1, f_nr2char},
7729 {"pathshorten", 1, 1, f_pathshorten},
7730 #ifdef FEAT_FLOAT
7731 {"pow", 2, 2, f_pow},
7732 #endif
7733 {"prevnonblank", 1, 1, f_prevnonblank},
7734 {"printf", 2, 19, f_printf},
7735 {"pumvisible", 0, 0, f_pumvisible},
7736 {"range", 1, 3, f_range},
7737 {"readfile", 1, 3, f_readfile},
7738 {"reltime", 0, 2, f_reltime},
7739 {"reltimestr", 1, 1, f_reltimestr},
7740 {"remote_expr", 2, 3, f_remote_expr},
7741 {"remote_foreground", 1, 1, f_remote_foreground},
7742 {"remote_peek", 1, 2, f_remote_peek},
7743 {"remote_read", 1, 1, f_remote_read},
7744 {"remote_send", 2, 3, f_remote_send},
7745 {"remove", 2, 3, f_remove},
7746 {"rename", 2, 2, f_rename},
7747 {"repeat", 2, 2, f_repeat},
7748 {"resolve", 1, 1, f_resolve},
7749 {"reverse", 1, 1, f_reverse},
7750 #ifdef FEAT_FLOAT
7751 {"round", 1, 1, f_round},
7752 #endif
7753 {"search", 1, 4, f_search},
7754 {"searchdecl", 1, 3, f_searchdecl},
7755 {"searchpair", 3, 7, f_searchpair},
7756 {"searchpairpos", 3, 7, f_searchpairpos},
7757 {"searchpos", 1, 4, f_searchpos},
7758 {"server2client", 2, 2, f_server2client},
7759 {"serverlist", 0, 0, f_serverlist},
7760 {"setbufvar", 3, 3, f_setbufvar},
7761 {"setcmdpos", 1, 1, f_setcmdpos},
7762 {"setline", 2, 2, f_setline},
7763 {"setloclist", 2, 3, f_setloclist},
7764 {"setmatches", 1, 1, f_setmatches},
7765 {"setpos", 2, 2, f_setpos},
7766 {"setqflist", 1, 2, f_setqflist},
7767 {"setreg", 2, 3, f_setreg},
7768 {"settabwinvar", 4, 4, f_settabwinvar},
7769 {"setwinvar", 3, 3, f_setwinvar},
7770 {"shellescape", 1, 2, f_shellescape},
7771 {"simplify", 1, 1, f_simplify},
7772 #ifdef FEAT_FLOAT
7773 {"sin", 1, 1, f_sin},
7774 {"sinh", 1, 1, f_sinh}, /* WJMc */
7775 #endif
7776 {"sort", 1, 2, f_sort},
7777 {"soundfold", 1, 1, f_soundfold},
7778 {"spellbadword", 0, 1, f_spellbadword},
7779 {"spellsuggest", 1, 3, f_spellsuggest},
7780 {"split", 1, 3, f_split},
7781 #ifdef FEAT_FLOAT
7782 {"sqrt", 1, 1, f_sqrt},
7783 {"str2float", 1, 1, f_str2float},
7784 #endif
7785 {"str2nr", 1, 2, f_str2nr},
7786 #ifdef HAVE_STRFTIME
7787 {"strftime", 1, 2, f_strftime},
7788 #endif
7789 {"stridx", 2, 3, f_stridx},
7790 {"string", 1, 1, f_string},
7791 {"strlen", 1, 1, f_strlen},
7792 {"strpart", 2, 3, f_strpart},
7793 {"strridx", 2, 3, f_strridx},
7794 {"strtrans", 1, 1, f_strtrans},
7795 {"submatch", 1, 1, f_submatch},
7796 {"substitute", 4, 4, f_substitute},
7797 {"synID", 3, 3, f_synID},
7798 {"synIDattr", 2, 3, f_synIDattr},
7799 {"synIDtrans", 1, 1, f_synIDtrans},
7800 {"synstack", 2, 2, f_synstack},
7801 {"system", 1, 2, f_system},
7802 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7803 {"tabpagenr", 0, 1, f_tabpagenr},
7804 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7805 {"tagfiles", 0, 0, f_tagfiles},
7806 {"taglist", 1, 1, f_taglist},
7807 {"tan", 1, 1, f_tan}, /* WJMc */
7808 {"tanh", 1, 1, f_tanh}, /* WJMc */
7809 {"tempname", 0, 0, f_tempname},
7810 {"test", 1, 1, f_test},
7811 {"tolower", 1, 1, f_tolower},
7812 {"toupper", 1, 1, f_toupper},
7813 {"tr", 3, 3, f_tr},
7814 #ifdef FEAT_FLOAT
7815 {"trunc", 1, 1, f_trunc},
7816 #endif
7817 {"type", 1, 1, f_type},
7818 {"values", 1, 1, f_values},
7819 {"virtcol", 1, 1, f_virtcol},
7820 {"visualmode", 0, 1, f_visualmode},
7821 {"winbufnr", 1, 1, f_winbufnr},
7822 {"wincol", 0, 0, f_wincol},
7823 {"winheight", 1, 1, f_winheight},
7824 {"winline", 0, 0, f_winline},
7825 {"winnr", 0, 1, f_winnr},
7826 {"winrestcmd", 0, 0, f_winrestcmd},
7827 {"winrestview", 1, 1, f_winrestview},
7828 {"winsaveview", 0, 0, f_winsaveview},
7829 {"winwidth", 1, 1, f_winwidth},
7830 {"writefile", 2, 3, f_writefile},
7833 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7836 * Function given to ExpandGeneric() to obtain the list of internal
7837 * or user defined function names.
7839 char_u *
7840 get_function_name(xp, idx)
7841 expand_T *xp;
7842 int idx;
7844 static int intidx = -1;
7845 char_u *name;
7847 if (idx == 0)
7848 intidx = -1;
7849 if (intidx < 0)
7851 name = get_user_func_name(xp, idx);
7852 if (name != NULL)
7853 return name;
7855 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7857 STRCPY(IObuff, functions[intidx].f_name);
7858 STRCAT(IObuff, "(");
7859 if (functions[intidx].f_max_argc == 0)
7860 STRCAT(IObuff, ")");
7861 return IObuff;
7864 return NULL;
7868 * Function given to ExpandGeneric() to obtain the list of internal or
7869 * user defined variable or function names.
7871 char_u *
7872 get_expr_name(xp, idx)
7873 expand_T *xp;
7874 int idx;
7876 static int intidx = -1;
7877 char_u *name;
7879 if (idx == 0)
7880 intidx = -1;
7881 if (intidx < 0)
7883 name = get_function_name(xp, idx);
7884 if (name != NULL)
7885 return name;
7887 return get_user_var_name(xp, ++intidx);
7890 #endif /* FEAT_CMDL_COMPL */
7893 * Find internal function in table above.
7894 * Return index, or -1 if not found
7896 static int
7897 find_internal_func(name)
7898 char_u *name; /* name of the function */
7900 int first = 0;
7901 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7902 int cmp;
7903 int x;
7906 * Find the function name in the table. Binary search.
7908 while (first <= last)
7910 x = first + ((unsigned)(last - first) >> 1);
7911 cmp = STRCMP(name, functions[x].f_name);
7912 if (cmp < 0)
7913 last = x - 1;
7914 else if (cmp > 0)
7915 first = x + 1;
7916 else
7917 return x;
7919 return -1;
7923 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7924 * name it contains, otherwise return "name".
7926 static char_u *
7927 deref_func_name(name, lenp)
7928 char_u *name;
7929 int *lenp;
7931 dictitem_T *v;
7932 int cc;
7934 cc = name[*lenp];
7935 name[*lenp] = NUL;
7936 v = find_var(name, NULL);
7937 name[*lenp] = cc;
7938 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7940 if (v->di_tv.vval.v_string == NULL)
7942 *lenp = 0;
7943 return (char_u *)""; /* just in case */
7945 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7946 return v->di_tv.vval.v_string;
7949 return name;
7953 * Allocate a variable for the result of a function.
7954 * Return OK or FAIL.
7956 static int
7957 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7958 evaluate, selfdict)
7959 char_u *name; /* name of the function */
7960 int len; /* length of "name" */
7961 typval_T *rettv;
7962 char_u **arg; /* argument, pointing to the '(' */
7963 linenr_T firstline; /* first line of range */
7964 linenr_T lastline; /* last line of range */
7965 int *doesrange; /* return: function handled range */
7966 int evaluate;
7967 dict_T *selfdict; /* Dictionary for "self" */
7969 char_u *argp;
7970 int ret = OK;
7971 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7972 int argcount = 0; /* number of arguments found */
7975 * Get the arguments.
7977 argp = *arg;
7978 while (argcount < MAX_FUNC_ARGS)
7980 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7981 if (*argp == ')' || *argp == ',' || *argp == NUL)
7982 break;
7983 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7985 ret = FAIL;
7986 break;
7988 ++argcount;
7989 if (*argp != ',')
7990 break;
7992 if (*argp == ')')
7993 ++argp;
7994 else
7995 ret = FAIL;
7997 if (ret == OK)
7998 ret = call_func(name, len, rettv, argcount, argvars,
7999 firstline, lastline, doesrange, evaluate, selfdict);
8000 else if (!aborting())
8002 if (argcount == MAX_FUNC_ARGS)
8003 emsg_funcname(N_("E740: Too many arguments for function %s"), name);
8004 else
8005 emsg_funcname(N_("E116: Invalid arguments for function %s"), name);
8008 while (--argcount >= 0)
8009 clear_tv(&argvars[argcount]);
8011 *arg = skipwhite(argp);
8012 return ret;
8017 * Call a function with its resolved parameters
8018 * Return OK when the function can't be called, FAIL otherwise.
8019 * Also returns OK when an error was encountered while executing the function.
8021 static int
8022 call_func(name, len, rettv, argcount, argvars, firstline, lastline,
8023 doesrange, evaluate, selfdict)
8024 char_u *name; /* name of the function */
8025 int len; /* length of "name" */
8026 typval_T *rettv; /* return value goes here */
8027 int argcount; /* number of "argvars" */
8028 typval_T *argvars; /* vars for arguments, must have "argcount"
8029 PLUS ONE elements! */
8030 linenr_T firstline; /* first line of range */
8031 linenr_T lastline; /* last line of range */
8032 int *doesrange; /* return: function handled range */
8033 int evaluate;
8034 dict_T *selfdict; /* Dictionary for "self" */
8036 int ret = FAIL;
8037 #define ERROR_UNKNOWN 0
8038 #define ERROR_TOOMANY 1
8039 #define ERROR_TOOFEW 2
8040 #define ERROR_SCRIPT 3
8041 #define ERROR_DICT 4
8042 #define ERROR_NONE 5
8043 #define ERROR_OTHER 6
8044 int error = ERROR_NONE;
8045 int i;
8046 int llen;
8047 ufunc_T *fp;
8048 int cc;
8049 #define FLEN_FIXED 40
8050 char_u fname_buf[FLEN_FIXED + 1];
8051 char_u *fname;
8054 * In a script change <SID>name() and s:name() to K_SNR 123_name().
8055 * Change <SNR>123_name() to K_SNR 123_name().
8056 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
8058 cc = name[len];
8059 name[len] = NUL;
8060 llen = eval_fname_script(name);
8061 if (llen > 0)
8063 fname_buf[0] = K_SPECIAL;
8064 fname_buf[1] = KS_EXTRA;
8065 fname_buf[2] = (int)KE_SNR;
8066 i = 3;
8067 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
8069 if (current_SID <= 0)
8070 error = ERROR_SCRIPT;
8071 else
8073 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
8074 i = (int)STRLEN(fname_buf);
8077 if (i + STRLEN(name + llen) < FLEN_FIXED)
8079 STRCPY(fname_buf + i, name + llen);
8080 fname = fname_buf;
8082 else
8084 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
8085 if (fname == NULL)
8086 error = ERROR_OTHER;
8087 else
8089 mch_memmove(fname, fname_buf, (size_t)i);
8090 STRCPY(fname + i, name + llen);
8094 else
8095 fname = name;
8097 *doesrange = FALSE;
8100 /* execute the function if no errors detected and executing */
8101 if (evaluate && error == ERROR_NONE)
8103 rettv->v_type = VAR_NUMBER; /* default rettv is number zero */
8104 rettv->vval.v_number = 0;
8105 error = ERROR_UNKNOWN;
8107 if (!builtin_function(fname))
8110 * User defined function.
8112 fp = find_func(fname);
8114 #ifdef FEAT_AUTOCMD
8115 /* Trigger FuncUndefined event, may load the function. */
8116 if (fp == NULL
8117 && apply_autocmds(EVENT_FUNCUNDEFINED,
8118 fname, fname, TRUE, NULL)
8119 && !aborting())
8121 /* executed an autocommand, search for the function again */
8122 fp = find_func(fname);
8124 #endif
8125 /* Try loading a package. */
8126 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
8128 /* loaded a package, search for the function again */
8129 fp = find_func(fname);
8132 if (fp != NULL)
8134 if (fp->uf_flags & FC_RANGE)
8135 *doesrange = TRUE;
8136 if (argcount < fp->uf_args.ga_len)
8137 error = ERROR_TOOFEW;
8138 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
8139 error = ERROR_TOOMANY;
8140 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
8141 error = ERROR_DICT;
8142 else
8145 * Call the user function.
8146 * Save and restore search patterns, script variables and
8147 * redo buffer.
8149 save_search_patterns();
8150 saveRedobuff();
8151 ++fp->uf_calls;
8152 call_user_func(fp, argcount, argvars, rettv,
8153 firstline, lastline,
8154 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
8155 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
8156 && fp->uf_refcount <= 0)
8157 /* Function was unreferenced while being used, free it
8158 * now. */
8159 func_free(fp);
8160 restoreRedobuff();
8161 restore_search_patterns();
8162 error = ERROR_NONE;
8166 else
8169 * Find the function name in the table, call its implementation.
8171 i = find_internal_func(fname);
8172 if (i >= 0)
8174 if (argcount < functions[i].f_min_argc)
8175 error = ERROR_TOOFEW;
8176 else if (argcount > functions[i].f_max_argc)
8177 error = ERROR_TOOMANY;
8178 else
8180 argvars[argcount].v_type = VAR_UNKNOWN;
8181 functions[i].f_func(argvars, rettv);
8182 error = ERROR_NONE;
8187 * The function call (or "FuncUndefined" autocommand sequence) might
8188 * have been aborted by an error, an interrupt, or an explicitly thrown
8189 * exception that has not been caught so far. This situation can be
8190 * tested for by calling aborting(). For an error in an internal
8191 * function or for the "E132" error in call_user_func(), however, the
8192 * throw point at which the "force_abort" flag (temporarily reset by
8193 * emsg()) is normally updated has not been reached yet. We need to
8194 * update that flag first to make aborting() reliable.
8196 update_force_abort();
8198 if (error == ERROR_NONE)
8199 ret = OK;
8202 * Report an error unless the argument evaluation or function call has been
8203 * cancelled due to an aborting error, an interrupt, or an exception.
8205 if (!aborting())
8207 switch (error)
8209 case ERROR_UNKNOWN:
8210 emsg_funcname(N_("E117: Unknown function: %s"), name);
8211 break;
8212 case ERROR_TOOMANY:
8213 emsg_funcname(e_toomanyarg, name);
8214 break;
8215 case ERROR_TOOFEW:
8216 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
8217 name);
8218 break;
8219 case ERROR_SCRIPT:
8220 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
8221 name);
8222 break;
8223 case ERROR_DICT:
8224 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
8225 name);
8226 break;
8230 name[len] = cc;
8231 if (fname != name && fname != fname_buf)
8232 vim_free(fname);
8234 return ret;
8238 * Give an error message with a function name. Handle <SNR> things.
8239 * "ermsg" is to be passed without translation, use N_() instead of _().
8241 static void
8242 emsg_funcname(ermsg, name)
8243 char *ermsg;
8244 char_u *name;
8246 char_u *p;
8248 if (*name == K_SPECIAL)
8249 p = concat_str((char_u *)"<SNR>", name + 3);
8250 else
8251 p = name;
8252 EMSG2(_(ermsg), p);
8253 if (p != name)
8254 vim_free(p);
8258 * Return TRUE for a non-zero Number and a non-empty String.
8260 static int
8261 non_zero_arg(argvars)
8262 typval_T *argvars;
8264 return ((argvars[0].v_type == VAR_NUMBER
8265 && argvars[0].vval.v_number != 0)
8266 || (argvars[0].v_type == VAR_STRING
8267 && argvars[0].vval.v_string != NULL
8268 && *argvars[0].vval.v_string != NUL));
8271 /*********************************************
8272 * Implementation of the built-in functions
8275 #ifdef FEAT_FLOAT
8277 * "abs(expr)" function
8279 static void
8280 f_abs(argvars, rettv)
8281 typval_T *argvars;
8282 typval_T *rettv;
8284 if (argvars[0].v_type == VAR_FLOAT)
8286 rettv->v_type = VAR_FLOAT;
8287 rettv->vval.v_float = fabs(argvars[0].vval.v_float);
8289 else
8291 varnumber_T n;
8292 int error = FALSE;
8294 n = get_tv_number_chk(&argvars[0], &error);
8295 if (error)
8296 rettv->vval.v_number = -1;
8297 else if (n > 0)
8298 rettv->vval.v_number = n;
8299 else
8300 rettv->vval.v_number = -n;
8303 #endif
8306 * "add(list, item)" function
8308 static void
8309 f_add(argvars, rettv)
8310 typval_T *argvars;
8311 typval_T *rettv;
8313 list_T *l;
8315 rettv->vval.v_number = 1; /* Default: Failed */
8316 if (argvars[0].v_type == VAR_LIST)
8318 if ((l = argvars[0].vval.v_list) != NULL
8319 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
8320 && list_append_tv(l, &argvars[1]) == OK)
8321 copy_tv(&argvars[0], rettv);
8323 else
8324 EMSG(_(e_listreq));
8328 * "append(lnum, string/list)" function
8330 static void
8331 f_append(argvars, rettv)
8332 typval_T *argvars;
8333 typval_T *rettv;
8335 long lnum;
8336 char_u *line;
8337 list_T *l = NULL;
8338 listitem_T *li = NULL;
8339 typval_T *tv;
8340 long added = 0;
8342 lnum = get_tv_lnum(argvars);
8343 if (lnum >= 0
8344 && lnum <= curbuf->b_ml.ml_line_count
8345 && u_save(lnum, lnum + 1) == OK)
8347 if (argvars[1].v_type == VAR_LIST)
8349 l = argvars[1].vval.v_list;
8350 if (l == NULL)
8351 return;
8352 li = l->lv_first;
8354 for (;;)
8356 if (l == NULL)
8357 tv = &argvars[1]; /* append a string */
8358 else if (li == NULL)
8359 break; /* end of list */
8360 else
8361 tv = &li->li_tv; /* append item from list */
8362 line = get_tv_string_chk(tv);
8363 if (line == NULL) /* type error */
8365 rettv->vval.v_number = 1; /* Failed */
8366 break;
8368 ml_append(lnum + added, line, (colnr_T)0, FALSE);
8369 ++added;
8370 if (l == NULL)
8371 break;
8372 li = li->li_next;
8375 appended_lines_mark(lnum, added);
8376 if (curwin->w_cursor.lnum > lnum)
8377 curwin->w_cursor.lnum += added;
8379 else
8380 rettv->vval.v_number = 1; /* Failed */
8384 * "argc()" function
8386 static void
8387 f_argc(argvars, rettv)
8388 typval_T *argvars UNUSED;
8389 typval_T *rettv;
8391 rettv->vval.v_number = ARGCOUNT;
8395 * "argidx()" function
8397 static void
8398 f_argidx(argvars, rettv)
8399 typval_T *argvars UNUSED;
8400 typval_T *rettv;
8402 rettv->vval.v_number = curwin->w_arg_idx;
8406 * "argv(nr)" function
8408 static void
8409 f_argv(argvars, rettv)
8410 typval_T *argvars;
8411 typval_T *rettv;
8413 int idx;
8415 if (argvars[0].v_type != VAR_UNKNOWN)
8417 idx = get_tv_number_chk(&argvars[0], NULL);
8418 if (idx >= 0 && idx < ARGCOUNT)
8419 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
8420 else
8421 rettv->vval.v_string = NULL;
8422 rettv->v_type = VAR_STRING;
8424 else if (rettv_list_alloc(rettv) == OK)
8425 for (idx = 0; idx < ARGCOUNT; ++idx)
8426 list_append_string(rettv->vval.v_list,
8427 alist_name(&ARGLIST[idx]), -1);
8430 #ifdef FEAT_FLOAT
8431 static int get_float_arg __ARGS((typval_T *argvars, float_T *f));
8434 * Get the float value of "argvars[0]" into "f".
8435 * Returns FAIL when the argument is not a Number or Float.
8437 static int
8438 get_float_arg(argvars, f)
8439 typval_T *argvars;
8440 float_T *f;
8442 if (argvars[0].v_type == VAR_FLOAT)
8444 *f = argvars[0].vval.v_float;
8445 return OK;
8447 if (argvars[0].v_type == VAR_NUMBER)
8449 *f = (float_T)argvars[0].vval.v_number;
8450 return OK;
8452 EMSG(_("E808: Number or Float required"));
8453 return FAIL;
8456 /* The 10 added FP functions are defined immediately before atan() - WJMc */
8459 * "acos()" function
8461 static void
8462 f_acos(argvars, rettv)
8463 typval_T *argvars;
8464 typval_T *rettv;
8466 float_T f;
8468 rettv->v_type = VAR_FLOAT;
8469 if (get_float_arg(argvars, &f) == OK)
8470 rettv->vval.v_float = acos(f);
8471 else
8472 rettv->vval.v_float = 0.0;
8476 * "asin()" function
8478 static void
8479 f_asin(argvars, rettv)
8480 typval_T *argvars;
8481 typval_T *rettv;
8483 float_T f;
8485 rettv->v_type = VAR_FLOAT;
8486 if (get_float_arg(argvars, &f) == OK)
8487 rettv->vval.v_float = asin(f);
8488 else
8489 rettv->vval.v_float = 0.0;
8493 * "atan2()" function
8495 static void
8496 f_atan2(argvars, rettv)
8497 typval_T *argvars;
8498 typval_T *rettv;
8500 float_T fx, fy;
8502 rettv->v_type = VAR_FLOAT;
8503 if (get_float_arg(argvars, &fx) == OK
8504 && get_float_arg(&argvars[1], &fy) == OK)
8505 rettv->vval.v_float = atan2(fx, fy);
8506 else
8507 rettv->vval.v_float = 0.0;
8511 * "cosh()" function
8513 static void
8514 f_cosh(argvars, rettv)
8515 typval_T *argvars;
8516 typval_T *rettv;
8518 float_T f;
8520 rettv->v_type = VAR_FLOAT;
8521 if (get_float_arg(argvars, &f) == OK)
8522 rettv->vval.v_float = cosh(f);
8523 else
8524 rettv->vval.v_float = 0.0;
8528 * "exp()" function
8530 static void
8531 f_exp(argvars, rettv)
8532 typval_T *argvars;
8533 typval_T *rettv;
8535 float_T f;
8537 rettv->v_type = VAR_FLOAT;
8538 if (get_float_arg(argvars, &f) == OK)
8539 rettv->vval.v_float = exp(f);
8540 else
8541 rettv->vval.v_float = 0.0;
8545 * "fmod()" function
8547 static void
8548 f_fmod(argvars, rettv)
8549 typval_T *argvars;
8550 typval_T *rettv;
8552 float_T fx, fy;
8554 rettv->v_type = VAR_FLOAT;
8555 if (get_float_arg(argvars, &fx) == OK
8556 && get_float_arg(&argvars[1], &fy) == OK)
8557 rettv->vval.v_float = fmod(fx, fy);
8558 else
8559 rettv->vval.v_float = 0.0;
8563 * "log()" function
8565 static void
8566 f_log(argvars, rettv)
8567 typval_T *argvars;
8568 typval_T *rettv;
8570 float_T f;
8572 rettv->v_type = VAR_FLOAT;
8573 if (get_float_arg(argvars, &f) == OK)
8574 rettv->vval.v_float = log(f);
8575 else
8576 rettv->vval.v_float = 0.0;
8580 * "sinh()" function
8582 static void
8583 f_sinh(argvars, rettv)
8584 typval_T *argvars;
8585 typval_T *rettv;
8587 float_T f;
8589 rettv->v_type = VAR_FLOAT;
8590 if (get_float_arg(argvars, &f) == OK)
8591 rettv->vval.v_float = sinh(f);
8592 else
8593 rettv->vval.v_float = 0.0;
8597 * "tan()" function
8599 static void
8600 f_tan(argvars, rettv)
8601 typval_T *argvars;
8602 typval_T *rettv;
8604 float_T f;
8606 rettv->v_type = VAR_FLOAT;
8607 if (get_float_arg(argvars, &f) == OK)
8608 rettv->vval.v_float = tan(f);
8609 else
8610 rettv->vval.v_float = 0.0;
8614 * "tanh()" function
8616 static void
8617 f_tanh(argvars, rettv)
8618 typval_T *argvars;
8619 typval_T *rettv;
8621 float_T f;
8623 rettv->v_type = VAR_FLOAT;
8624 if (get_float_arg(argvars, &f) == OK)
8625 rettv->vval.v_float = tanh(f);
8626 else
8627 rettv->vval.v_float = 0.0;
8630 /* End of the 10 added FP functions - WJMc */
8633 * "atan()" function
8635 static void
8636 f_atan(argvars, rettv)
8637 typval_T *argvars;
8638 typval_T *rettv;
8640 float_T f;
8642 rettv->v_type = VAR_FLOAT;
8643 if (get_float_arg(argvars, &f) == OK)
8644 rettv->vval.v_float = atan(f);
8645 else
8646 rettv->vval.v_float = 0.0;
8648 #endif
8651 * "browse(save, title, initdir, default)" function
8653 static void
8654 f_browse(argvars, rettv)
8655 typval_T *argvars UNUSED;
8656 typval_T *rettv;
8658 #ifdef FEAT_BROWSE
8659 int save;
8660 char_u *title;
8661 char_u *initdir;
8662 char_u *defname;
8663 char_u buf[NUMBUFLEN];
8664 char_u buf2[NUMBUFLEN];
8665 int error = FALSE;
8667 save = get_tv_number_chk(&argvars[0], &error);
8668 title = get_tv_string_chk(&argvars[1]);
8669 initdir = get_tv_string_buf_chk(&argvars[2], buf);
8670 defname = get_tv_string_buf_chk(&argvars[3], buf2);
8672 if (error || title == NULL || initdir == NULL || defname == NULL)
8673 rettv->vval.v_string = NULL;
8674 else
8675 rettv->vval.v_string =
8676 do_browse(save ? BROWSE_SAVE : 0,
8677 title, defname, NULL, initdir, NULL, curbuf);
8678 #else
8679 rettv->vval.v_string = NULL;
8680 #endif
8681 rettv->v_type = VAR_STRING;
8685 * "browsedir(title, initdir)" function
8687 static void
8688 f_browsedir(argvars, rettv)
8689 typval_T *argvars UNUSED;
8690 typval_T *rettv;
8692 #ifdef FEAT_BROWSE
8693 char_u *title;
8694 char_u *initdir;
8695 char_u buf[NUMBUFLEN];
8697 title = get_tv_string_chk(&argvars[0]);
8698 initdir = get_tv_string_buf_chk(&argvars[1], buf);
8700 if (title == NULL || initdir == NULL)
8701 rettv->vval.v_string = NULL;
8702 else
8703 rettv->vval.v_string = do_browse(BROWSE_DIR,
8704 title, NULL, NULL, initdir, NULL, curbuf);
8705 #else
8706 rettv->vval.v_string = NULL;
8707 #endif
8708 rettv->v_type = VAR_STRING;
8711 static buf_T *find_buffer __ARGS((typval_T *avar));
8714 * Find a buffer by number or exact name.
8716 static buf_T *
8717 find_buffer(avar)
8718 typval_T *avar;
8720 buf_T *buf = NULL;
8722 if (avar->v_type == VAR_NUMBER)
8723 buf = buflist_findnr((int)avar->vval.v_number);
8724 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
8726 buf = buflist_findname_exp(avar->vval.v_string);
8727 if (buf == NULL)
8729 /* No full path name match, try a match with a URL or a "nofile"
8730 * buffer, these don't use the full path. */
8731 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8732 if (buf->b_fname != NULL
8733 && (path_with_url(buf->b_fname)
8734 #ifdef FEAT_QUICKFIX
8735 || bt_nofile(buf)
8736 #endif
8738 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
8739 break;
8742 return buf;
8746 * "bufexists(expr)" function
8748 static void
8749 f_bufexists(argvars, rettv)
8750 typval_T *argvars;
8751 typval_T *rettv;
8753 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
8757 * "buflisted(expr)" function
8759 static void
8760 f_buflisted(argvars, rettv)
8761 typval_T *argvars;
8762 typval_T *rettv;
8764 buf_T *buf;
8766 buf = find_buffer(&argvars[0]);
8767 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
8771 * "bufloaded(expr)" function
8773 static void
8774 f_bufloaded(argvars, rettv)
8775 typval_T *argvars;
8776 typval_T *rettv;
8778 buf_T *buf;
8780 buf = find_buffer(&argvars[0]);
8781 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
8784 static buf_T *get_buf_tv __ARGS((typval_T *tv));
8787 * Get buffer by number or pattern.
8789 static buf_T *
8790 get_buf_tv(tv)
8791 typval_T *tv;
8793 char_u *name = tv->vval.v_string;
8794 int save_magic;
8795 char_u *save_cpo;
8796 buf_T *buf;
8798 if (tv->v_type == VAR_NUMBER)
8799 return buflist_findnr((int)tv->vval.v_number);
8800 if (tv->v_type != VAR_STRING)
8801 return NULL;
8802 if (name == NULL || *name == NUL)
8803 return curbuf;
8804 if (name[0] == '$' && name[1] == NUL)
8805 return lastbuf;
8807 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
8808 save_magic = p_magic;
8809 p_magic = TRUE;
8810 save_cpo = p_cpo;
8811 p_cpo = (char_u *)"";
8813 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8814 TRUE, FALSE));
8816 p_magic = save_magic;
8817 p_cpo = save_cpo;
8819 /* If not found, try expanding the name, like done for bufexists(). */
8820 if (buf == NULL)
8821 buf = find_buffer(tv);
8823 return buf;
8827 * "bufname(expr)" function
8829 static void
8830 f_bufname(argvars, rettv)
8831 typval_T *argvars;
8832 typval_T *rettv;
8834 buf_T *buf;
8836 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8837 ++emsg_off;
8838 buf = get_buf_tv(&argvars[0]);
8839 rettv->v_type = VAR_STRING;
8840 if (buf != NULL && buf->b_fname != NULL)
8841 rettv->vval.v_string = vim_strsave(buf->b_fname);
8842 else
8843 rettv->vval.v_string = NULL;
8844 --emsg_off;
8848 * "bufnr(expr)" function
8850 static void
8851 f_bufnr(argvars, rettv)
8852 typval_T *argvars;
8853 typval_T *rettv;
8855 buf_T *buf;
8856 int error = FALSE;
8857 char_u *name;
8859 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8860 ++emsg_off;
8861 buf = get_buf_tv(&argvars[0]);
8862 --emsg_off;
8864 /* If the buffer isn't found and the second argument is not zero create a
8865 * new buffer. */
8866 if (buf == NULL
8867 && argvars[1].v_type != VAR_UNKNOWN
8868 && get_tv_number_chk(&argvars[1], &error) != 0
8869 && !error
8870 && (name = get_tv_string_chk(&argvars[0])) != NULL
8871 && !error)
8872 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8874 if (buf != NULL)
8875 rettv->vval.v_number = buf->b_fnum;
8876 else
8877 rettv->vval.v_number = -1;
8881 * "bufwinnr(nr)" function
8883 static void
8884 f_bufwinnr(argvars, rettv)
8885 typval_T *argvars;
8886 typval_T *rettv;
8888 #ifdef FEAT_WINDOWS
8889 win_T *wp;
8890 int winnr = 0;
8891 #endif
8892 buf_T *buf;
8894 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8895 ++emsg_off;
8896 buf = get_buf_tv(&argvars[0]);
8897 #ifdef FEAT_WINDOWS
8898 for (wp = firstwin; wp; wp = wp->w_next)
8900 ++winnr;
8901 if (wp->w_buffer == buf)
8902 break;
8904 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8905 #else
8906 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8907 #endif
8908 --emsg_off;
8912 * "byte2line(byte)" function
8914 static void
8915 f_byte2line(argvars, rettv)
8916 typval_T *argvars UNUSED;
8917 typval_T *rettv;
8919 #ifndef FEAT_BYTEOFF
8920 rettv->vval.v_number = -1;
8921 #else
8922 long boff = 0;
8924 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8925 if (boff < 0)
8926 rettv->vval.v_number = -1;
8927 else
8928 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8929 (linenr_T)0, &boff);
8930 #endif
8934 * "byteidx()" function
8936 static void
8937 f_byteidx(argvars, rettv)
8938 typval_T *argvars;
8939 typval_T *rettv;
8941 #ifdef FEAT_MBYTE
8942 char_u *t;
8943 #endif
8944 char_u *str;
8945 long idx;
8947 str = get_tv_string_chk(&argvars[0]);
8948 idx = get_tv_number_chk(&argvars[1], NULL);
8949 rettv->vval.v_number = -1;
8950 if (str == NULL || idx < 0)
8951 return;
8953 #ifdef FEAT_MBYTE
8954 t = str;
8955 for ( ; idx > 0; idx--)
8957 if (*t == NUL) /* EOL reached */
8958 return;
8959 t += (*mb_ptr2len)(t);
8961 rettv->vval.v_number = (varnumber_T)(t - str);
8962 #else
8963 if ((size_t)idx <= STRLEN(str))
8964 rettv->vval.v_number = idx;
8965 #endif
8969 * "call(func, arglist)" function
8971 static void
8972 f_call(argvars, rettv)
8973 typval_T *argvars;
8974 typval_T *rettv;
8976 char_u *func;
8977 typval_T argv[MAX_FUNC_ARGS + 1];
8978 int argc = 0;
8979 listitem_T *item;
8980 int dummy;
8981 dict_T *selfdict = NULL;
8983 if (argvars[1].v_type != VAR_LIST)
8985 EMSG(_(e_listreq));
8986 return;
8988 if (argvars[1].vval.v_list == NULL)
8989 return;
8991 if (argvars[0].v_type == VAR_FUNC)
8992 func = argvars[0].vval.v_string;
8993 else
8994 func = get_tv_string(&argvars[0]);
8995 if (*func == NUL)
8996 return; /* type error or empty name */
8998 if (argvars[2].v_type != VAR_UNKNOWN)
9000 if (argvars[2].v_type != VAR_DICT)
9002 EMSG(_(e_dictreq));
9003 return;
9005 selfdict = argvars[2].vval.v_dict;
9008 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
9009 item = item->li_next)
9011 if (argc == MAX_FUNC_ARGS)
9013 EMSG(_("E699: Too many arguments"));
9014 break;
9016 /* Make a copy of each argument. This is needed to be able to set
9017 * v_lock to VAR_FIXED in the copy without changing the original list.
9019 copy_tv(&item->li_tv, &argv[argc++]);
9022 if (item == NULL)
9023 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
9024 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
9025 &dummy, TRUE, selfdict);
9027 /* Free the arguments. */
9028 while (argc > 0)
9029 clear_tv(&argv[--argc]);
9032 #ifdef FEAT_FLOAT
9034 * "ceil({float})" function
9036 static void
9037 f_ceil(argvars, rettv)
9038 typval_T *argvars;
9039 typval_T *rettv;
9041 float_T f;
9043 rettv->v_type = VAR_FLOAT;
9044 if (get_float_arg(argvars, &f) == OK)
9045 rettv->vval.v_float = ceil(f);
9046 else
9047 rettv->vval.v_float = 0.0;
9049 #endif
9052 * "changenr()" function
9054 static void
9055 f_changenr(argvars, rettv)
9056 typval_T *argvars UNUSED;
9057 typval_T *rettv;
9059 rettv->vval.v_number = curbuf->b_u_seq_cur;
9063 * "char2nr(string)" function
9065 static void
9066 f_char2nr(argvars, rettv)
9067 typval_T *argvars;
9068 typval_T *rettv;
9070 #ifdef FEAT_MBYTE
9071 if (has_mbyte)
9072 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
9073 else
9074 #endif
9075 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
9079 * "cindent(lnum)" function
9081 static void
9082 f_cindent(argvars, rettv)
9083 typval_T *argvars;
9084 typval_T *rettv;
9086 #ifdef FEAT_CINDENT
9087 pos_T pos;
9088 linenr_T lnum;
9090 pos = curwin->w_cursor;
9091 lnum = get_tv_lnum(argvars);
9092 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9094 curwin->w_cursor.lnum = lnum;
9095 rettv->vval.v_number = get_c_indent();
9096 curwin->w_cursor = pos;
9098 else
9099 #endif
9100 rettv->vval.v_number = -1;
9104 * "clearmatches()" function
9106 static void
9107 f_clearmatches(argvars, rettv)
9108 typval_T *argvars UNUSED;
9109 typval_T *rettv UNUSED;
9111 #ifdef FEAT_SEARCH_EXTRA
9112 clear_matches(curwin);
9113 #endif
9117 * "col(string)" function
9119 static void
9120 f_col(argvars, rettv)
9121 typval_T *argvars;
9122 typval_T *rettv;
9124 colnr_T col = 0;
9125 pos_T *fp;
9126 int fnum = curbuf->b_fnum;
9128 fp = var2fpos(&argvars[0], FALSE, &fnum);
9129 if (fp != NULL && fnum == curbuf->b_fnum)
9131 if (fp->col == MAXCOL)
9133 /* '> can be MAXCOL, get the length of the line then */
9134 if (fp->lnum <= curbuf->b_ml.ml_line_count)
9135 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
9136 else
9137 col = MAXCOL;
9139 else
9141 col = fp->col + 1;
9142 #ifdef FEAT_VIRTUALEDIT
9143 /* col(".") when the cursor is on the NUL at the end of the line
9144 * because of "coladd" can be seen as an extra column. */
9145 if (virtual_active() && fp == &curwin->w_cursor)
9147 char_u *p = ml_get_cursor();
9149 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
9150 curwin->w_virtcol - curwin->w_cursor.coladd))
9152 # ifdef FEAT_MBYTE
9153 int l;
9155 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
9156 col += l;
9157 # else
9158 if (*p != NUL && p[1] == NUL)
9159 ++col;
9160 # endif
9163 #endif
9166 rettv->vval.v_number = col;
9169 #if defined(FEAT_INS_EXPAND)
9171 * "complete()" function
9173 static void
9174 f_complete(argvars, rettv)
9175 typval_T *argvars;
9176 typval_T *rettv UNUSED;
9178 int startcol;
9180 if ((State & INSERT) == 0)
9182 EMSG(_("E785: complete() can only be used in Insert mode"));
9183 return;
9186 /* Check for undo allowed here, because if something was already inserted
9187 * the line was already saved for undo and this check isn't done. */
9188 if (!undo_allowed())
9189 return;
9191 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
9193 EMSG(_(e_invarg));
9194 return;
9197 startcol = get_tv_number_chk(&argvars[0], NULL);
9198 if (startcol <= 0)
9199 return;
9201 set_completion(startcol - 1, argvars[1].vval.v_list);
9205 * "complete_add()" function
9207 static void
9208 f_complete_add(argvars, rettv)
9209 typval_T *argvars;
9210 typval_T *rettv;
9212 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
9216 * "complete_check()" function
9218 static void
9219 f_complete_check(argvars, rettv)
9220 typval_T *argvars UNUSED;
9221 typval_T *rettv;
9223 int saved = RedrawingDisabled;
9225 RedrawingDisabled = 0;
9226 ins_compl_check_keys(0);
9227 rettv->vval.v_number = compl_interrupted;
9228 RedrawingDisabled = saved;
9230 #endif
9233 * "confirm(message, buttons[, default [, type]])" function
9235 static void
9236 f_confirm(argvars, rettv)
9237 typval_T *argvars UNUSED;
9238 typval_T *rettv UNUSED;
9240 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
9241 char_u *message;
9242 char_u *buttons = NULL;
9243 char_u buf[NUMBUFLEN];
9244 char_u buf2[NUMBUFLEN];
9245 int def = 1;
9246 int type = VIM_GENERIC;
9247 char_u *typestr;
9248 int error = FALSE;
9250 message = get_tv_string_chk(&argvars[0]);
9251 if (message == NULL)
9252 error = TRUE;
9253 if (argvars[1].v_type != VAR_UNKNOWN)
9255 buttons = get_tv_string_buf_chk(&argvars[1], buf);
9256 if (buttons == NULL)
9257 error = TRUE;
9258 if (argvars[2].v_type != VAR_UNKNOWN)
9260 def = get_tv_number_chk(&argvars[2], &error);
9261 if (argvars[3].v_type != VAR_UNKNOWN)
9263 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
9264 if (typestr == NULL)
9265 error = TRUE;
9266 else
9268 switch (TOUPPER_ASC(*typestr))
9270 case 'E': type = VIM_ERROR; break;
9271 case 'Q': type = VIM_QUESTION; break;
9272 case 'I': type = VIM_INFO; break;
9273 case 'W': type = VIM_WARNING; break;
9274 case 'G': type = VIM_GENERIC; break;
9281 if (buttons == NULL || *buttons == NUL)
9282 buttons = (char_u *)_("&Ok");
9284 if (!error)
9285 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
9286 def, NULL);
9287 #endif
9291 * "copy()" function
9293 static void
9294 f_copy(argvars, rettv)
9295 typval_T *argvars;
9296 typval_T *rettv;
9298 item_copy(&argvars[0], rettv, FALSE, 0);
9301 #ifdef FEAT_FLOAT
9303 * "cos()" function
9305 static void
9306 f_cos(argvars, rettv)
9307 typval_T *argvars;
9308 typval_T *rettv;
9310 float_T f;
9312 rettv->v_type = VAR_FLOAT;
9313 if (get_float_arg(argvars, &f) == OK)
9314 rettv->vval.v_float = cos(f);
9315 else
9316 rettv->vval.v_float = 0.0;
9318 #endif
9321 * "count()" function
9323 static void
9324 f_count(argvars, rettv)
9325 typval_T *argvars;
9326 typval_T *rettv;
9328 long n = 0;
9329 int ic = FALSE;
9331 if (argvars[0].v_type == VAR_LIST)
9333 listitem_T *li;
9334 list_T *l;
9335 long idx;
9337 if ((l = argvars[0].vval.v_list) != NULL)
9339 li = l->lv_first;
9340 if (argvars[2].v_type != VAR_UNKNOWN)
9342 int error = FALSE;
9344 ic = get_tv_number_chk(&argvars[2], &error);
9345 if (argvars[3].v_type != VAR_UNKNOWN)
9347 idx = get_tv_number_chk(&argvars[3], &error);
9348 if (!error)
9350 li = list_find(l, idx);
9351 if (li == NULL)
9352 EMSGN(_(e_listidx), idx);
9355 if (error)
9356 li = NULL;
9359 for ( ; li != NULL; li = li->li_next)
9360 if (tv_equal(&li->li_tv, &argvars[1], ic))
9361 ++n;
9364 else if (argvars[0].v_type == VAR_DICT)
9366 int todo;
9367 dict_T *d;
9368 hashitem_T *hi;
9370 if ((d = argvars[0].vval.v_dict) != NULL)
9372 int error = FALSE;
9374 if (argvars[2].v_type != VAR_UNKNOWN)
9376 ic = get_tv_number_chk(&argvars[2], &error);
9377 if (argvars[3].v_type != VAR_UNKNOWN)
9378 EMSG(_(e_invarg));
9381 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
9382 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
9384 if (!HASHITEM_EMPTY(hi))
9386 --todo;
9387 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
9388 ++n;
9393 else
9394 EMSG2(_(e_listdictarg), "count()");
9395 rettv->vval.v_number = n;
9399 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
9401 * Checks the existence of a cscope connection.
9403 static void
9404 f_cscope_connection(argvars, rettv)
9405 typval_T *argvars UNUSED;
9406 typval_T *rettv UNUSED;
9408 #ifdef FEAT_CSCOPE
9409 int num = 0;
9410 char_u *dbpath = NULL;
9411 char_u *prepend = NULL;
9412 char_u buf[NUMBUFLEN];
9414 if (argvars[0].v_type != VAR_UNKNOWN
9415 && argvars[1].v_type != VAR_UNKNOWN)
9417 num = (int)get_tv_number(&argvars[0]);
9418 dbpath = get_tv_string(&argvars[1]);
9419 if (argvars[2].v_type != VAR_UNKNOWN)
9420 prepend = get_tv_string_buf(&argvars[2], buf);
9423 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
9424 #endif
9428 * "cursor(lnum, col)" function
9430 * Moves the cursor to the specified line and column.
9431 * Returns 0 when the position could be set, -1 otherwise.
9433 static void
9434 f_cursor(argvars, rettv)
9435 typval_T *argvars;
9436 typval_T *rettv;
9438 long line, col;
9439 #ifdef FEAT_VIRTUALEDIT
9440 long coladd = 0;
9441 #endif
9443 rettv->vval.v_number = -1;
9444 if (argvars[1].v_type == VAR_UNKNOWN)
9446 pos_T pos;
9448 if (list2fpos(argvars, &pos, NULL) == FAIL)
9449 return;
9450 line = pos.lnum;
9451 col = pos.col;
9452 #ifdef FEAT_VIRTUALEDIT
9453 coladd = pos.coladd;
9454 #endif
9456 else
9458 line = get_tv_lnum(argvars);
9459 col = get_tv_number_chk(&argvars[1], NULL);
9460 #ifdef FEAT_VIRTUALEDIT
9461 if (argvars[2].v_type != VAR_UNKNOWN)
9462 coladd = get_tv_number_chk(&argvars[2], NULL);
9463 #endif
9465 if (line < 0 || col < 0
9466 #ifdef FEAT_VIRTUALEDIT
9467 || coladd < 0
9468 #endif
9470 return; /* type error; errmsg already given */
9471 if (line > 0)
9472 curwin->w_cursor.lnum = line;
9473 if (col > 0)
9474 curwin->w_cursor.col = col - 1;
9475 #ifdef FEAT_VIRTUALEDIT
9476 curwin->w_cursor.coladd = coladd;
9477 #endif
9479 /* Make sure the cursor is in a valid position. */
9480 check_cursor();
9481 #ifdef FEAT_MBYTE
9482 /* Correct cursor for multi-byte character. */
9483 if (has_mbyte)
9484 mb_adjust_cursor();
9485 #endif
9487 curwin->w_set_curswant = TRUE;
9488 rettv->vval.v_number = 0;
9492 * "deepcopy()" function
9494 static void
9495 f_deepcopy(argvars, rettv)
9496 typval_T *argvars;
9497 typval_T *rettv;
9499 int noref = 0;
9501 if (argvars[1].v_type != VAR_UNKNOWN)
9502 noref = get_tv_number_chk(&argvars[1], NULL);
9503 if (noref < 0 || noref > 1)
9504 EMSG(_(e_invarg));
9505 else
9507 current_copyID += COPYID_INC;
9508 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? current_copyID : 0);
9513 * "delete()" function
9515 static void
9516 f_delete(argvars, rettv)
9517 typval_T *argvars;
9518 typval_T *rettv;
9520 if (check_restricted() || check_secure())
9521 rettv->vval.v_number = -1;
9522 else
9523 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
9527 * "did_filetype()" function
9529 static void
9530 f_did_filetype(argvars, rettv)
9531 typval_T *argvars UNUSED;
9532 typval_T *rettv UNUSED;
9534 #ifdef FEAT_AUTOCMD
9535 rettv->vval.v_number = did_filetype;
9536 #endif
9540 * "diff_filler()" function
9542 static void
9543 f_diff_filler(argvars, rettv)
9544 typval_T *argvars UNUSED;
9545 typval_T *rettv UNUSED;
9547 #ifdef FEAT_DIFF
9548 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
9549 #endif
9553 * "diff_hlID()" function
9555 static void
9556 f_diff_hlID(argvars, rettv)
9557 typval_T *argvars UNUSED;
9558 typval_T *rettv UNUSED;
9560 #ifdef FEAT_DIFF
9561 linenr_T lnum = get_tv_lnum(argvars);
9562 static linenr_T prev_lnum = 0;
9563 static int changedtick = 0;
9564 static int fnum = 0;
9565 static int change_start = 0;
9566 static int change_end = 0;
9567 static hlf_T hlID = (hlf_T)0;
9568 int filler_lines;
9569 int col;
9571 if (lnum < 0) /* ignore type error in {lnum} arg */
9572 lnum = 0;
9573 if (lnum != prev_lnum
9574 || changedtick != curbuf->b_changedtick
9575 || fnum != curbuf->b_fnum)
9577 /* New line, buffer, change: need to get the values. */
9578 filler_lines = diff_check(curwin, lnum);
9579 if (filler_lines < 0)
9581 if (filler_lines == -1)
9583 change_start = MAXCOL;
9584 change_end = -1;
9585 if (diff_find_change(curwin, lnum, &change_start, &change_end))
9586 hlID = HLF_ADD; /* added line */
9587 else
9588 hlID = HLF_CHD; /* changed line */
9590 else
9591 hlID = HLF_ADD; /* added line */
9593 else
9594 hlID = (hlf_T)0;
9595 prev_lnum = lnum;
9596 changedtick = curbuf->b_changedtick;
9597 fnum = curbuf->b_fnum;
9600 if (hlID == HLF_CHD || hlID == HLF_TXD)
9602 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
9603 if (col >= change_start && col <= change_end)
9604 hlID = HLF_TXD; /* changed text */
9605 else
9606 hlID = HLF_CHD; /* changed line */
9608 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
9609 #endif
9613 * "empty({expr})" function
9615 static void
9616 f_empty(argvars, rettv)
9617 typval_T *argvars;
9618 typval_T *rettv;
9620 int n;
9622 switch (argvars[0].v_type)
9624 case VAR_STRING:
9625 case VAR_FUNC:
9626 n = argvars[0].vval.v_string == NULL
9627 || *argvars[0].vval.v_string == NUL;
9628 break;
9629 case VAR_NUMBER:
9630 n = argvars[0].vval.v_number == 0;
9631 break;
9632 #ifdef FEAT_FLOAT
9633 case VAR_FLOAT:
9634 n = argvars[0].vval.v_float == 0.0;
9635 break;
9636 #endif
9637 case VAR_LIST:
9638 n = argvars[0].vval.v_list == NULL
9639 || argvars[0].vval.v_list->lv_first == NULL;
9640 break;
9641 case VAR_DICT:
9642 n = argvars[0].vval.v_dict == NULL
9643 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
9644 break;
9645 default:
9646 EMSG2(_(e_intern2), "f_empty()");
9647 n = 0;
9650 rettv->vval.v_number = n;
9654 * "escape({string}, {chars})" function
9656 static void
9657 f_escape(argvars, rettv)
9658 typval_T *argvars;
9659 typval_T *rettv;
9661 char_u buf[NUMBUFLEN];
9663 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
9664 get_tv_string_buf(&argvars[1], buf));
9665 rettv->v_type = VAR_STRING;
9669 * "eval()" function
9671 static void
9672 f_eval(argvars, rettv)
9673 typval_T *argvars;
9674 typval_T *rettv;
9676 char_u *s;
9678 s = get_tv_string_chk(&argvars[0]);
9679 if (s != NULL)
9680 s = skipwhite(s);
9682 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
9684 rettv->v_type = VAR_NUMBER;
9685 rettv->vval.v_number = 0;
9687 else if (*s != NUL)
9688 EMSG(_(e_trailing));
9692 * "eventhandler()" function
9694 static void
9695 f_eventhandler(argvars, rettv)
9696 typval_T *argvars UNUSED;
9697 typval_T *rettv;
9699 rettv->vval.v_number = vgetc_busy;
9703 * "executable()" function
9705 static void
9706 f_executable(argvars, rettv)
9707 typval_T *argvars;
9708 typval_T *rettv;
9710 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
9714 * "exists()" function
9716 static void
9717 f_exists(argvars, rettv)
9718 typval_T *argvars;
9719 typval_T *rettv;
9721 char_u *p;
9722 char_u *name;
9723 int n = FALSE;
9724 int len = 0;
9726 p = get_tv_string(&argvars[0]);
9727 if (*p == '$') /* environment variable */
9729 /* first try "normal" environment variables (fast) */
9730 if (mch_getenv(p + 1) != NULL)
9731 n = TRUE;
9732 else
9734 /* try expanding things like $VIM and ${HOME} */
9735 p = expand_env_save(p);
9736 if (p != NULL && *p != '$')
9737 n = TRUE;
9738 vim_free(p);
9741 else if (*p == '&' || *p == '+') /* option */
9743 n = (get_option_tv(&p, NULL, TRUE) == OK);
9744 if (*skipwhite(p) != NUL)
9745 n = FALSE; /* trailing garbage */
9747 else if (*p == '*') /* internal or user defined function */
9749 n = function_exists(p + 1);
9751 else if (*p == ':')
9753 n = cmd_exists(p + 1);
9755 else if (*p == '#')
9757 #ifdef FEAT_AUTOCMD
9758 if (p[1] == '#')
9759 n = autocmd_supported(p + 2);
9760 else
9761 n = au_exists(p + 1);
9762 #endif
9764 else /* internal variable */
9766 char_u *tofree;
9767 typval_T tv;
9769 /* get_name_len() takes care of expanding curly braces */
9770 name = p;
9771 len = get_name_len(&p, &tofree, TRUE, FALSE);
9772 if (len > 0)
9774 if (tofree != NULL)
9775 name = tofree;
9776 n = (get_var_tv(name, len, &tv, FALSE) == OK);
9777 if (n)
9779 /* handle d.key, l[idx], f(expr) */
9780 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
9781 if (n)
9782 clear_tv(&tv);
9785 if (*p != NUL)
9786 n = FALSE;
9788 vim_free(tofree);
9791 rettv->vval.v_number = n;
9795 * "expand()" function
9797 static void
9798 f_expand(argvars, rettv)
9799 typval_T *argvars;
9800 typval_T *rettv;
9802 char_u *s;
9803 int len;
9804 char_u *errormsg;
9805 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
9806 expand_T xpc;
9807 int error = FALSE;
9809 rettv->v_type = VAR_STRING;
9810 s = get_tv_string(&argvars[0]);
9811 if (*s == '%' || *s == '#' || *s == '<')
9813 ++emsg_off;
9814 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
9815 --emsg_off;
9817 else
9819 /* When the optional second argument is non-zero, don't remove matches
9820 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
9821 if (argvars[1].v_type != VAR_UNKNOWN
9822 && get_tv_number_chk(&argvars[1], &error))
9823 flags |= WILD_KEEP_ALL;
9824 if (!error)
9826 ExpandInit(&xpc);
9827 xpc.xp_context = EXPAND_FILES;
9828 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
9830 else
9831 rettv->vval.v_string = NULL;
9836 * "extend(list, list [, idx])" function
9837 * "extend(dict, dict [, action])" function
9839 static void
9840 f_extend(argvars, rettv)
9841 typval_T *argvars;
9842 typval_T *rettv;
9844 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9846 list_T *l1, *l2;
9847 listitem_T *item;
9848 long before;
9849 int error = FALSE;
9851 l1 = argvars[0].vval.v_list;
9852 l2 = argvars[1].vval.v_list;
9853 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9854 && l2 != NULL)
9856 if (argvars[2].v_type != VAR_UNKNOWN)
9858 before = get_tv_number_chk(&argvars[2], &error);
9859 if (error)
9860 return; /* type error; errmsg already given */
9862 if (before == l1->lv_len)
9863 item = NULL;
9864 else
9866 item = list_find(l1, before);
9867 if (item == NULL)
9869 EMSGN(_(e_listidx), before);
9870 return;
9874 else
9875 item = NULL;
9876 list_extend(l1, l2, item);
9878 copy_tv(&argvars[0], rettv);
9881 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9883 dict_T *d1, *d2;
9884 dictitem_T *di1;
9885 char_u *action;
9886 int i;
9887 hashitem_T *hi2;
9888 int todo;
9890 d1 = argvars[0].vval.v_dict;
9891 d2 = argvars[1].vval.v_dict;
9892 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9893 && d2 != NULL)
9895 /* Check the third argument. */
9896 if (argvars[2].v_type != VAR_UNKNOWN)
9898 static char *(av[]) = {"keep", "force", "error"};
9900 action = get_tv_string_chk(&argvars[2]);
9901 if (action == NULL)
9902 return; /* type error; errmsg already given */
9903 for (i = 0; i < 3; ++i)
9904 if (STRCMP(action, av[i]) == 0)
9905 break;
9906 if (i == 3)
9908 EMSG2(_(e_invarg2), action);
9909 return;
9912 else
9913 action = (char_u *)"force";
9915 /* Go over all entries in the second dict and add them to the
9916 * first dict. */
9917 todo = (int)d2->dv_hashtab.ht_used;
9918 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9920 if (!HASHITEM_EMPTY(hi2))
9922 --todo;
9923 di1 = dict_find(d1, hi2->hi_key, -1);
9924 if (di1 == NULL)
9926 di1 = dictitem_copy(HI2DI(hi2));
9927 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9928 dictitem_free(di1);
9930 else if (*action == 'e')
9932 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9933 break;
9935 else if (*action == 'f')
9937 clear_tv(&di1->di_tv);
9938 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9943 copy_tv(&argvars[0], rettv);
9946 else
9947 EMSG2(_(e_listdictarg), "extend()");
9951 * "feedkeys()" function
9953 static void
9954 f_feedkeys(argvars, rettv)
9955 typval_T *argvars;
9956 typval_T *rettv UNUSED;
9958 int remap = TRUE;
9959 char_u *keys, *flags;
9960 char_u nbuf[NUMBUFLEN];
9961 int typed = FALSE;
9962 char_u *keys_esc;
9964 /* This is not allowed in the sandbox. If the commands would still be
9965 * executed in the sandbox it would be OK, but it probably happens later,
9966 * when "sandbox" is no longer set. */
9967 if (check_secure())
9968 return;
9970 keys = get_tv_string(&argvars[0]);
9971 if (*keys != NUL)
9973 if (argvars[1].v_type != VAR_UNKNOWN)
9975 flags = get_tv_string_buf(&argvars[1], nbuf);
9976 for ( ; *flags != NUL; ++flags)
9978 switch (*flags)
9980 case 'n': remap = FALSE; break;
9981 case 'm': remap = TRUE; break;
9982 case 't': typed = TRUE; break;
9987 /* Need to escape K_SPECIAL and CSI before putting the string in the
9988 * typeahead buffer. */
9989 keys_esc = vim_strsave_escape_csi(keys);
9990 if (keys_esc != NULL)
9992 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
9993 typebuf.tb_len, !typed, FALSE);
9994 vim_free(keys_esc);
9995 if (vgetc_busy)
9996 typebuf_was_filled = TRUE;
10002 * "filereadable()" function
10004 static void
10005 f_filereadable(argvars, rettv)
10006 typval_T *argvars;
10007 typval_T *rettv;
10009 int fd;
10010 char_u *p;
10011 int n;
10013 #ifndef O_NONBLOCK
10014 # define O_NONBLOCK 0
10015 #endif
10016 p = get_tv_string(&argvars[0]);
10017 if (*p && !mch_isdir(p) && (fd = mch_open((char *)p,
10018 O_RDONLY | O_NONBLOCK, 0)) >= 0)
10020 n = TRUE;
10021 close(fd);
10023 else
10024 n = FALSE;
10026 rettv->vval.v_number = n;
10030 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
10031 * rights to write into.
10033 static void
10034 f_filewritable(argvars, rettv)
10035 typval_T *argvars;
10036 typval_T *rettv;
10038 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
10041 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
10043 static void
10044 findfilendir(argvars, rettv, find_what)
10045 typval_T *argvars;
10046 typval_T *rettv;
10047 int find_what;
10049 #ifdef FEAT_SEARCHPATH
10050 char_u *fname;
10051 char_u *fresult = NULL;
10052 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
10053 char_u *p;
10054 char_u pathbuf[NUMBUFLEN];
10055 int count = 1;
10056 int first = TRUE;
10057 int error = FALSE;
10058 #endif
10060 rettv->vval.v_string = NULL;
10061 rettv->v_type = VAR_STRING;
10063 #ifdef FEAT_SEARCHPATH
10064 fname = get_tv_string(&argvars[0]);
10066 if (argvars[1].v_type != VAR_UNKNOWN)
10068 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
10069 if (p == NULL)
10070 error = TRUE;
10071 else
10073 if (*p != NUL)
10074 path = p;
10076 if (argvars[2].v_type != VAR_UNKNOWN)
10077 count = get_tv_number_chk(&argvars[2], &error);
10081 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
10082 error = TRUE;
10084 if (*fname != NUL && !error)
10088 if (rettv->v_type == VAR_STRING)
10089 vim_free(fresult);
10090 fresult = find_file_in_path_option(first ? fname : NULL,
10091 first ? (int)STRLEN(fname) : 0,
10092 0, first, path,
10093 find_what,
10094 curbuf->b_ffname,
10095 find_what == FINDFILE_DIR
10096 ? (char_u *)"" : curbuf->b_p_sua);
10097 first = FALSE;
10099 if (fresult != NULL && rettv->v_type == VAR_LIST)
10100 list_append_string(rettv->vval.v_list, fresult, -1);
10102 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
10105 if (rettv->v_type == VAR_STRING)
10106 rettv->vval.v_string = fresult;
10107 #endif
10110 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
10111 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
10114 * Implementation of map() and filter().
10116 static void
10117 filter_map(argvars, rettv, map)
10118 typval_T *argvars;
10119 typval_T *rettv;
10120 int map;
10122 char_u buf[NUMBUFLEN];
10123 char_u *expr;
10124 listitem_T *li, *nli;
10125 list_T *l = NULL;
10126 dictitem_T *di;
10127 hashtab_T *ht;
10128 hashitem_T *hi;
10129 dict_T *d = NULL;
10130 typval_T save_val;
10131 typval_T save_key;
10132 int rem;
10133 int todo;
10134 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
10135 int save_did_emsg;
10136 int index = 0;
10138 if (argvars[0].v_type == VAR_LIST)
10140 if ((l = argvars[0].vval.v_list) == NULL
10141 || (map && tv_check_lock(l->lv_lock, ermsg)))
10142 return;
10144 else if (argvars[0].v_type == VAR_DICT)
10146 if ((d = argvars[0].vval.v_dict) == NULL
10147 || (map && tv_check_lock(d->dv_lock, ermsg)))
10148 return;
10150 else
10152 EMSG2(_(e_listdictarg), ermsg);
10153 return;
10156 expr = get_tv_string_buf_chk(&argvars[1], buf);
10157 /* On type errors, the preceding call has already displayed an error
10158 * message. Avoid a misleading error message for an empty string that
10159 * was not passed as argument. */
10160 if (expr != NULL)
10162 prepare_vimvar(VV_VAL, &save_val);
10163 expr = skipwhite(expr);
10165 /* We reset "did_emsg" to be able to detect whether an error
10166 * occurred during evaluation of the expression. */
10167 save_did_emsg = did_emsg;
10168 did_emsg = FALSE;
10170 prepare_vimvar(VV_KEY, &save_key);
10171 if (argvars[0].v_type == VAR_DICT)
10173 vimvars[VV_KEY].vv_type = VAR_STRING;
10175 ht = &d->dv_hashtab;
10176 hash_lock(ht);
10177 todo = (int)ht->ht_used;
10178 for (hi = ht->ht_array; todo > 0; ++hi)
10180 if (!HASHITEM_EMPTY(hi))
10182 --todo;
10183 di = HI2DI(hi);
10184 if (tv_check_lock(di->di_tv.v_lock, ermsg))
10185 break;
10186 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
10187 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
10188 || did_emsg)
10189 break;
10190 if (!map && rem)
10191 dictitem_remove(d, di);
10192 clear_tv(&vimvars[VV_KEY].vv_tv);
10195 hash_unlock(ht);
10197 else
10199 vimvars[VV_KEY].vv_type = VAR_NUMBER;
10201 for (li = l->lv_first; li != NULL; li = nli)
10203 if (tv_check_lock(li->li_tv.v_lock, ermsg))
10204 break;
10205 nli = li->li_next;
10206 vimvars[VV_KEY].vv_nr = index;
10207 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
10208 || did_emsg)
10209 break;
10210 if (!map && rem)
10211 listitem_remove(l, li);
10212 ++index;
10216 restore_vimvar(VV_KEY, &save_key);
10217 restore_vimvar(VV_VAL, &save_val);
10219 did_emsg |= save_did_emsg;
10222 copy_tv(&argvars[0], rettv);
10225 static int
10226 filter_map_one(tv, expr, map, remp)
10227 typval_T *tv;
10228 char_u *expr;
10229 int map;
10230 int *remp;
10232 typval_T rettv;
10233 char_u *s;
10234 int retval = FAIL;
10236 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
10237 s = expr;
10238 if (eval1(&s, &rettv, TRUE) == FAIL)
10239 goto theend;
10240 if (*s != NUL) /* check for trailing chars after expr */
10242 EMSG2(_(e_invexpr2), s);
10243 goto theend;
10245 if (map)
10247 /* map(): replace the list item value */
10248 clear_tv(tv);
10249 rettv.v_lock = 0;
10250 *tv = rettv;
10252 else
10254 int error = FALSE;
10256 /* filter(): when expr is zero remove the item */
10257 *remp = (get_tv_number_chk(&rettv, &error) == 0);
10258 clear_tv(&rettv);
10259 /* On type error, nothing has been removed; return FAIL to stop the
10260 * loop. The error message was given by get_tv_number_chk(). */
10261 if (error)
10262 goto theend;
10264 retval = OK;
10265 theend:
10266 clear_tv(&vimvars[VV_VAL].vv_tv);
10267 return retval;
10271 * "filter()" function
10273 static void
10274 f_filter(argvars, rettv)
10275 typval_T *argvars;
10276 typval_T *rettv;
10278 filter_map(argvars, rettv, FALSE);
10282 * "finddir({fname}[, {path}[, {count}]])" function
10284 static void
10285 f_finddir(argvars, rettv)
10286 typval_T *argvars;
10287 typval_T *rettv;
10289 findfilendir(argvars, rettv, FINDFILE_DIR);
10293 * "findfile({fname}[, {path}[, {count}]])" function
10295 static void
10296 f_findfile(argvars, rettv)
10297 typval_T *argvars;
10298 typval_T *rettv;
10300 findfilendir(argvars, rettv, FINDFILE_FILE);
10303 #ifdef FEAT_FLOAT
10305 * "float2nr({float})" function
10307 static void
10308 f_float2nr(argvars, rettv)
10309 typval_T *argvars;
10310 typval_T *rettv;
10312 float_T f;
10314 if (get_float_arg(argvars, &f) == OK)
10316 if (f < -0x7fffffff)
10317 rettv->vval.v_number = -0x7fffffff;
10318 else if (f > 0x7fffffff)
10319 rettv->vval.v_number = 0x7fffffff;
10320 else
10321 rettv->vval.v_number = (varnumber_T)f;
10326 * "floor({float})" function
10328 static void
10329 f_floor(argvars, rettv)
10330 typval_T *argvars;
10331 typval_T *rettv;
10333 float_T f;
10335 rettv->v_type = VAR_FLOAT;
10336 if (get_float_arg(argvars, &f) == OK)
10337 rettv->vval.v_float = floor(f);
10338 else
10339 rettv->vval.v_float = 0.0;
10341 #endif
10344 * "fnameescape({string})" function
10346 static void
10347 f_fnameescape(argvars, rettv)
10348 typval_T *argvars;
10349 typval_T *rettv;
10351 rettv->vval.v_string = vim_strsave_fnameescape(
10352 get_tv_string(&argvars[0]), FALSE);
10353 rettv->v_type = VAR_STRING;
10357 * "fnamemodify({fname}, {mods})" function
10359 static void
10360 f_fnamemodify(argvars, rettv)
10361 typval_T *argvars;
10362 typval_T *rettv;
10364 char_u *fname;
10365 char_u *mods;
10366 int usedlen = 0;
10367 int len;
10368 char_u *fbuf = NULL;
10369 char_u buf[NUMBUFLEN];
10371 fname = get_tv_string_chk(&argvars[0]);
10372 mods = get_tv_string_buf_chk(&argvars[1], buf);
10373 if (fname == NULL || mods == NULL)
10374 fname = NULL;
10375 else
10377 len = (int)STRLEN(fname);
10378 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
10381 rettv->v_type = VAR_STRING;
10382 if (fname == NULL)
10383 rettv->vval.v_string = NULL;
10384 else
10385 rettv->vval.v_string = vim_strnsave(fname, len);
10386 vim_free(fbuf);
10389 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
10392 * "foldclosed()" function
10394 static void
10395 foldclosed_both(argvars, rettv, end)
10396 typval_T *argvars;
10397 typval_T *rettv;
10398 int end;
10400 #ifdef FEAT_FOLDING
10401 linenr_T lnum;
10402 linenr_T first, last;
10404 lnum = get_tv_lnum(argvars);
10405 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10407 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
10409 if (end)
10410 rettv->vval.v_number = (varnumber_T)last;
10411 else
10412 rettv->vval.v_number = (varnumber_T)first;
10413 return;
10416 #endif
10417 rettv->vval.v_number = -1;
10421 * "foldclosed()" function
10423 static void
10424 f_foldclosed(argvars, rettv)
10425 typval_T *argvars;
10426 typval_T *rettv;
10428 foldclosed_both(argvars, rettv, FALSE);
10432 * "foldclosedend()" function
10434 static void
10435 f_foldclosedend(argvars, rettv)
10436 typval_T *argvars;
10437 typval_T *rettv;
10439 foldclosed_both(argvars, rettv, TRUE);
10443 * "foldlevel()" function
10445 static void
10446 f_foldlevel(argvars, rettv)
10447 typval_T *argvars;
10448 typval_T *rettv;
10450 #ifdef FEAT_FOLDING
10451 linenr_T lnum;
10453 lnum = get_tv_lnum(argvars);
10454 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10455 rettv->vval.v_number = foldLevel(lnum);
10456 #endif
10460 * "foldtext()" function
10462 static void
10463 f_foldtext(argvars, rettv)
10464 typval_T *argvars UNUSED;
10465 typval_T *rettv;
10467 #ifdef FEAT_FOLDING
10468 linenr_T lnum;
10469 char_u *s;
10470 char_u *r;
10471 int len;
10472 char *txt;
10473 #endif
10475 rettv->v_type = VAR_STRING;
10476 rettv->vval.v_string = NULL;
10477 #ifdef FEAT_FOLDING
10478 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
10479 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
10480 <= curbuf->b_ml.ml_line_count
10481 && vimvars[VV_FOLDDASHES].vv_str != NULL)
10483 /* Find first non-empty line in the fold. */
10484 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
10485 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10487 if (!linewhite(lnum))
10488 break;
10489 ++lnum;
10492 /* Find interesting text in this line. */
10493 s = skipwhite(ml_get(lnum));
10494 /* skip C comment-start */
10495 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
10497 s = skipwhite(s + 2);
10498 if (*skipwhite(s) == NUL
10499 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10501 s = skipwhite(ml_get(lnum + 1));
10502 if (*s == '*')
10503 s = skipwhite(s + 1);
10506 txt = _("+-%s%3ld lines: ");
10507 r = alloc((unsigned)(STRLEN(txt)
10508 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
10509 + 20 /* for %3ld */
10510 + STRLEN(s))); /* concatenated */
10511 if (r != NULL)
10513 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
10514 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
10515 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
10516 len = (int)STRLEN(r);
10517 STRCAT(r, s);
10518 /* remove 'foldmarker' and 'commentstring' */
10519 foldtext_cleanup(r + len);
10520 rettv->vval.v_string = r;
10523 #endif
10527 * "foldtextresult(lnum)" function
10529 static void
10530 f_foldtextresult(argvars, rettv)
10531 typval_T *argvars UNUSED;
10532 typval_T *rettv;
10534 #ifdef FEAT_FOLDING
10535 linenr_T lnum;
10536 char_u *text;
10537 char_u buf[51];
10538 foldinfo_T foldinfo;
10539 int fold_count;
10540 #endif
10542 rettv->v_type = VAR_STRING;
10543 rettv->vval.v_string = NULL;
10544 #ifdef FEAT_FOLDING
10545 lnum = get_tv_lnum(argvars);
10546 /* treat illegal types and illegal string values for {lnum} the same */
10547 if (lnum < 0)
10548 lnum = 0;
10549 fold_count = foldedCount(curwin, lnum, &foldinfo);
10550 if (fold_count > 0)
10552 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
10553 &foldinfo, buf);
10554 if (text == buf)
10555 text = vim_strsave(text);
10556 rettv->vval.v_string = text;
10558 #endif
10562 * "foreground()" function
10564 static void
10565 f_foreground(argvars, rettv)
10566 typval_T *argvars UNUSED;
10567 typval_T *rettv UNUSED;
10569 #ifdef FEAT_GUI
10570 if (gui.in_use)
10571 gui_mch_set_foreground();
10572 #else
10573 # ifdef WIN32
10574 win32_set_foreground();
10575 # endif
10576 #endif
10580 * "function()" function
10582 static void
10583 f_function(argvars, rettv)
10584 typval_T *argvars;
10585 typval_T *rettv;
10587 char_u *s;
10589 s = get_tv_string(&argvars[0]);
10590 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
10591 EMSG2(_(e_invarg2), s);
10592 /* Don't check an autoload name for existence here. */
10593 else if (vim_strchr(s, AUTOLOAD_CHAR) == NULL && !function_exists(s))
10594 EMSG2(_("E700: Unknown function: %s"), s);
10595 else
10597 rettv->vval.v_string = vim_strsave(s);
10598 rettv->v_type = VAR_FUNC;
10603 * "garbagecollect()" function
10605 static void
10606 f_garbagecollect(argvars, rettv)
10607 typval_T *argvars;
10608 typval_T *rettv UNUSED;
10610 /* This is postponed until we are back at the toplevel, because we may be
10611 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
10612 want_garbage_collect = TRUE;
10614 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
10615 garbage_collect_at_exit = TRUE;
10619 * "get()" function
10621 static void
10622 f_get(argvars, rettv)
10623 typval_T *argvars;
10624 typval_T *rettv;
10626 listitem_T *li;
10627 list_T *l;
10628 dictitem_T *di;
10629 dict_T *d;
10630 typval_T *tv = NULL;
10632 if (argvars[0].v_type == VAR_LIST)
10634 if ((l = argvars[0].vval.v_list) != NULL)
10636 int error = FALSE;
10638 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
10639 if (!error && li != NULL)
10640 tv = &li->li_tv;
10643 else if (argvars[0].v_type == VAR_DICT)
10645 if ((d = argvars[0].vval.v_dict) != NULL)
10647 di = dict_find(d, get_tv_string(&argvars[1]), -1);
10648 if (di != NULL)
10649 tv = &di->di_tv;
10652 else
10653 EMSG2(_(e_listdictarg), "get()");
10655 if (tv == NULL)
10657 if (argvars[2].v_type != VAR_UNKNOWN)
10658 copy_tv(&argvars[2], rettv);
10660 else
10661 copy_tv(tv, rettv);
10664 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
10667 * Get line or list of lines from buffer "buf" into "rettv".
10668 * Return a range (from start to end) of lines in rettv from the specified
10669 * buffer.
10670 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
10672 static void
10673 get_buffer_lines(buf, start, end, retlist, rettv)
10674 buf_T *buf;
10675 linenr_T start;
10676 linenr_T end;
10677 int retlist;
10678 typval_T *rettv;
10680 char_u *p;
10682 if (retlist && rettv_list_alloc(rettv) == FAIL)
10683 return;
10685 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
10686 return;
10688 if (!retlist)
10690 if (start >= 1 && start <= buf->b_ml.ml_line_count)
10691 p = ml_get_buf(buf, start, FALSE);
10692 else
10693 p = (char_u *)"";
10695 rettv->v_type = VAR_STRING;
10696 rettv->vval.v_string = vim_strsave(p);
10698 else
10700 if (end < start)
10701 return;
10703 if (start < 1)
10704 start = 1;
10705 if (end > buf->b_ml.ml_line_count)
10706 end = buf->b_ml.ml_line_count;
10707 while (start <= end)
10708 if (list_append_string(rettv->vval.v_list,
10709 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
10710 break;
10715 * "getbufline()" function
10717 static void
10718 f_getbufline(argvars, rettv)
10719 typval_T *argvars;
10720 typval_T *rettv;
10722 linenr_T lnum;
10723 linenr_T end;
10724 buf_T *buf;
10726 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10727 ++emsg_off;
10728 buf = get_buf_tv(&argvars[0]);
10729 --emsg_off;
10731 lnum = get_tv_lnum_buf(&argvars[1], buf);
10732 if (argvars[2].v_type == VAR_UNKNOWN)
10733 end = lnum;
10734 else
10735 end = get_tv_lnum_buf(&argvars[2], buf);
10737 get_buffer_lines(buf, lnum, end, TRUE, rettv);
10741 * "getbufvar()" function
10743 static void
10744 f_getbufvar(argvars, rettv)
10745 typval_T *argvars;
10746 typval_T *rettv;
10748 buf_T *buf;
10749 buf_T *save_curbuf;
10750 char_u *varname;
10751 dictitem_T *v;
10753 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10754 varname = get_tv_string_chk(&argvars[1]);
10755 ++emsg_off;
10756 buf = get_buf_tv(&argvars[0]);
10758 rettv->v_type = VAR_STRING;
10759 rettv->vval.v_string = NULL;
10761 if (buf != NULL && varname != NULL)
10763 /* set curbuf to be our buf, temporarily */
10764 save_curbuf = curbuf;
10765 curbuf = buf;
10767 if (*varname == '&') /* buffer-local-option */
10768 get_option_tv(&varname, rettv, TRUE);
10769 else
10771 if (*varname == NUL)
10772 /* let getbufvar({nr}, "") return the "b:" dictionary. The
10773 * scope prefix before the NUL byte is required by
10774 * find_var_in_ht(). */
10775 varname = (char_u *)"b:" + 2;
10776 /* look up the variable */
10777 v = find_var_in_ht(&curbuf->b_vars.dv_hashtab, varname, FALSE);
10778 if (v != NULL)
10779 copy_tv(&v->di_tv, rettv);
10782 /* restore previous notion of curbuf */
10783 curbuf = save_curbuf;
10786 --emsg_off;
10790 * "getchar()" function
10792 static void
10793 f_getchar(argvars, rettv)
10794 typval_T *argvars;
10795 typval_T *rettv;
10797 varnumber_T n;
10798 int error = FALSE;
10800 /* Position the cursor. Needed after a message that ends in a space. */
10801 windgoto(msg_row, msg_col);
10803 ++no_mapping;
10804 ++allow_keys;
10805 for (;;)
10807 if (argvars[0].v_type == VAR_UNKNOWN)
10808 /* getchar(): blocking wait. */
10809 n = safe_vgetc();
10810 else if (get_tv_number_chk(&argvars[0], &error) == 1)
10811 /* getchar(1): only check if char avail */
10812 n = vpeekc();
10813 else if (error || vpeekc() == NUL)
10814 /* illegal argument or getchar(0) and no char avail: return zero */
10815 n = 0;
10816 else
10817 /* getchar(0) and char avail: return char */
10818 n = safe_vgetc();
10819 if (n == K_IGNORE)
10820 continue;
10821 break;
10823 --no_mapping;
10824 --allow_keys;
10826 vimvars[VV_MOUSE_WIN].vv_nr = 0;
10827 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
10828 vimvars[VV_MOUSE_COL].vv_nr = 0;
10830 rettv->vval.v_number = n;
10831 if (IS_SPECIAL(n) || mod_mask != 0)
10833 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
10834 int i = 0;
10836 /* Turn a special key into three bytes, plus modifier. */
10837 if (mod_mask != 0)
10839 temp[i++] = K_SPECIAL;
10840 temp[i++] = KS_MODIFIER;
10841 temp[i++] = mod_mask;
10843 if (IS_SPECIAL(n))
10845 temp[i++] = K_SPECIAL;
10846 temp[i++] = K_SECOND(n);
10847 temp[i++] = K_THIRD(n);
10849 #ifdef FEAT_MBYTE
10850 else if (has_mbyte)
10851 i += (*mb_char2bytes)(n, temp + i);
10852 #endif
10853 else
10854 temp[i++] = n;
10855 temp[i++] = NUL;
10856 rettv->v_type = VAR_STRING;
10857 rettv->vval.v_string = vim_strsave(temp);
10859 #ifdef FEAT_MOUSE
10860 if (n == K_LEFTMOUSE
10861 || n == K_LEFTMOUSE_NM
10862 || n == K_LEFTDRAG
10863 || n == K_LEFTRELEASE
10864 || n == K_LEFTRELEASE_NM
10865 || n == K_MIDDLEMOUSE
10866 || n == K_MIDDLEDRAG
10867 || n == K_MIDDLERELEASE
10868 || n == K_RIGHTMOUSE
10869 || n == K_RIGHTDRAG
10870 || n == K_RIGHTRELEASE
10871 || n == K_X1MOUSE
10872 || n == K_X1DRAG
10873 || n == K_X1RELEASE
10874 || n == K_X2MOUSE
10875 || n == K_X2DRAG
10876 || n == K_X2RELEASE
10877 || n == K_MOUSEDOWN
10878 || n == K_MOUSEUP)
10880 int row = mouse_row;
10881 int col = mouse_col;
10882 win_T *win;
10883 linenr_T lnum;
10884 # ifdef FEAT_WINDOWS
10885 win_T *wp;
10886 # endif
10887 int winnr = 1;
10889 if (row >= 0 && col >= 0)
10891 /* Find the window at the mouse coordinates and compute the
10892 * text position. */
10893 win = mouse_find_win(&row, &col);
10894 (void)mouse_comp_pos(win, &row, &col, &lnum);
10895 # ifdef FEAT_WINDOWS
10896 for (wp = firstwin; wp != win; wp = wp->w_next)
10897 ++winnr;
10898 # endif
10899 vimvars[VV_MOUSE_WIN].vv_nr = winnr;
10900 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
10901 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
10904 #endif
10909 * "getcharmod()" function
10911 static void
10912 f_getcharmod(argvars, rettv)
10913 typval_T *argvars UNUSED;
10914 typval_T *rettv;
10916 rettv->vval.v_number = mod_mask;
10920 * "getcmdline()" function
10922 static void
10923 f_getcmdline(argvars, rettv)
10924 typval_T *argvars UNUSED;
10925 typval_T *rettv;
10927 rettv->v_type = VAR_STRING;
10928 rettv->vval.v_string = get_cmdline_str();
10932 * "getcmdpos()" function
10934 static void
10935 f_getcmdpos(argvars, rettv)
10936 typval_T *argvars UNUSED;
10937 typval_T *rettv;
10939 rettv->vval.v_number = get_cmdline_pos() + 1;
10943 * "getcmdtype()" function
10945 static void
10946 f_getcmdtype(argvars, rettv)
10947 typval_T *argvars UNUSED;
10948 typval_T *rettv;
10950 rettv->v_type = VAR_STRING;
10951 rettv->vval.v_string = alloc(2);
10952 if (rettv->vval.v_string != NULL)
10954 rettv->vval.v_string[0] = get_cmdline_type();
10955 rettv->vval.v_string[1] = NUL;
10960 * "getcwd()" function
10962 static void
10963 f_getcwd(argvars, rettv)
10964 typval_T *argvars UNUSED;
10965 typval_T *rettv;
10967 char_u cwd[MAXPATHL];
10969 rettv->v_type = VAR_STRING;
10970 if (mch_dirname(cwd, MAXPATHL) == FAIL)
10971 rettv->vval.v_string = NULL;
10972 else
10974 rettv->vval.v_string = vim_strsave(cwd);
10975 #ifdef BACKSLASH_IN_FILENAME
10976 if (rettv->vval.v_string != NULL)
10977 slash_adjust(rettv->vval.v_string);
10978 #endif
10983 * "getfontname()" function
10985 static void
10986 f_getfontname(argvars, rettv)
10987 typval_T *argvars UNUSED;
10988 typval_T *rettv;
10990 rettv->v_type = VAR_STRING;
10991 rettv->vval.v_string = NULL;
10992 #ifdef FEAT_GUI
10993 if (gui.in_use)
10995 GuiFont font;
10996 char_u *name = NULL;
10998 if (argvars[0].v_type == VAR_UNKNOWN)
11000 /* Get the "Normal" font. Either the name saved by
11001 * hl_set_font_name() or from the font ID. */
11002 font = gui.norm_font;
11003 name = hl_get_font_name();
11005 else
11007 name = get_tv_string(&argvars[0]);
11008 if (STRCMP(name, "*") == 0) /* don't use font dialog */
11009 return;
11010 font = gui_mch_get_font(name, FALSE);
11011 if (font == NOFONT)
11012 return; /* Invalid font name, return empty string. */
11014 rettv->vval.v_string = gui_mch_get_fontname(font, name);
11015 if (argvars[0].v_type != VAR_UNKNOWN)
11016 gui_mch_free_font(font);
11018 #endif
11022 * "getfperm({fname})" function
11024 static void
11025 f_getfperm(argvars, rettv)
11026 typval_T *argvars;
11027 typval_T *rettv;
11029 char_u *fname;
11030 struct stat st;
11031 char_u *perm = NULL;
11032 char_u flags[] = "rwx";
11033 int i;
11035 fname = get_tv_string(&argvars[0]);
11037 rettv->v_type = VAR_STRING;
11038 if (mch_stat((char *)fname, &st) >= 0)
11040 perm = vim_strsave((char_u *)"---------");
11041 if (perm != NULL)
11043 for (i = 0; i < 9; i++)
11045 if (st.st_mode & (1 << (8 - i)))
11046 perm[i] = flags[i % 3];
11050 rettv->vval.v_string = perm;
11054 * "getfsize({fname})" function
11056 static void
11057 f_getfsize(argvars, rettv)
11058 typval_T *argvars;
11059 typval_T *rettv;
11061 char_u *fname;
11062 struct stat st;
11064 fname = get_tv_string(&argvars[0]);
11066 rettv->v_type = VAR_NUMBER;
11068 if (mch_stat((char *)fname, &st) >= 0)
11070 if (mch_isdir(fname))
11071 rettv->vval.v_number = 0;
11072 else
11074 rettv->vval.v_number = (varnumber_T)st.st_size;
11076 /* non-perfect check for overflow */
11077 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
11078 rettv->vval.v_number = -2;
11081 else
11082 rettv->vval.v_number = -1;
11086 * "getftime({fname})" function
11088 static void
11089 f_getftime(argvars, rettv)
11090 typval_T *argvars;
11091 typval_T *rettv;
11093 char_u *fname;
11094 struct stat st;
11096 fname = get_tv_string(&argvars[0]);
11098 if (mch_stat((char *)fname, &st) >= 0)
11099 rettv->vval.v_number = (varnumber_T)st.st_mtime;
11100 else
11101 rettv->vval.v_number = -1;
11105 * "getftype({fname})" function
11107 static void
11108 f_getftype(argvars, rettv)
11109 typval_T *argvars;
11110 typval_T *rettv;
11112 char_u *fname;
11113 struct stat st;
11114 char_u *type = NULL;
11115 char *t;
11117 fname = get_tv_string(&argvars[0]);
11119 rettv->v_type = VAR_STRING;
11120 if (mch_lstat((char *)fname, &st) >= 0)
11122 #ifdef S_ISREG
11123 if (S_ISREG(st.st_mode))
11124 t = "file";
11125 else if (S_ISDIR(st.st_mode))
11126 t = "dir";
11127 # ifdef S_ISLNK
11128 else if (S_ISLNK(st.st_mode))
11129 t = "link";
11130 # endif
11131 # ifdef S_ISBLK
11132 else if (S_ISBLK(st.st_mode))
11133 t = "bdev";
11134 # endif
11135 # ifdef S_ISCHR
11136 else if (S_ISCHR(st.st_mode))
11137 t = "cdev";
11138 # endif
11139 # ifdef S_ISFIFO
11140 else if (S_ISFIFO(st.st_mode))
11141 t = "fifo";
11142 # endif
11143 # ifdef S_ISSOCK
11144 else if (S_ISSOCK(st.st_mode))
11145 t = "fifo";
11146 # endif
11147 else
11148 t = "other";
11149 #else
11150 # ifdef S_IFMT
11151 switch (st.st_mode & S_IFMT)
11153 case S_IFREG: t = "file"; break;
11154 case S_IFDIR: t = "dir"; break;
11155 # ifdef S_IFLNK
11156 case S_IFLNK: t = "link"; break;
11157 # endif
11158 # ifdef S_IFBLK
11159 case S_IFBLK: t = "bdev"; break;
11160 # endif
11161 # ifdef S_IFCHR
11162 case S_IFCHR: t = "cdev"; break;
11163 # endif
11164 # ifdef S_IFIFO
11165 case S_IFIFO: t = "fifo"; break;
11166 # endif
11167 # ifdef S_IFSOCK
11168 case S_IFSOCK: t = "socket"; break;
11169 # endif
11170 default: t = "other";
11172 # else
11173 if (mch_isdir(fname))
11174 t = "dir";
11175 else
11176 t = "file";
11177 # endif
11178 #endif
11179 type = vim_strsave((char_u *)t);
11181 rettv->vval.v_string = type;
11185 * "getline(lnum, [end])" function
11187 static void
11188 f_getline(argvars, rettv)
11189 typval_T *argvars;
11190 typval_T *rettv;
11192 linenr_T lnum;
11193 linenr_T end;
11194 int retlist;
11196 lnum = get_tv_lnum(argvars);
11197 if (argvars[1].v_type == VAR_UNKNOWN)
11199 end = 0;
11200 retlist = FALSE;
11202 else
11204 end = get_tv_lnum(&argvars[1]);
11205 retlist = TRUE;
11208 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
11212 * "getmatches()" function
11214 static void
11215 f_getmatches(argvars, rettv)
11216 typval_T *argvars UNUSED;
11217 typval_T *rettv;
11219 #ifdef FEAT_SEARCH_EXTRA
11220 dict_T *dict;
11221 matchitem_T *cur = curwin->w_match_head;
11223 if (rettv_list_alloc(rettv) == OK)
11225 while (cur != NULL)
11227 dict = dict_alloc();
11228 if (dict == NULL)
11229 return;
11230 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
11231 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
11232 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
11233 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
11234 list_append_dict(rettv->vval.v_list, dict);
11235 cur = cur->next;
11238 #endif
11242 * "getpid()" function
11244 static void
11245 f_getpid(argvars, rettv)
11246 typval_T *argvars UNUSED;
11247 typval_T *rettv;
11249 rettv->vval.v_number = mch_get_pid();
11253 * "getpos(string)" function
11255 static void
11256 f_getpos(argvars, rettv)
11257 typval_T *argvars;
11258 typval_T *rettv;
11260 pos_T *fp;
11261 list_T *l;
11262 int fnum = -1;
11264 if (rettv_list_alloc(rettv) == OK)
11266 l = rettv->vval.v_list;
11267 fp = var2fpos(&argvars[0], TRUE, &fnum);
11268 if (fnum != -1)
11269 list_append_number(l, (varnumber_T)fnum);
11270 else
11271 list_append_number(l, (varnumber_T)0);
11272 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
11273 : (varnumber_T)0);
11274 list_append_number(l, (fp != NULL)
11275 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
11276 : (varnumber_T)0);
11277 list_append_number(l,
11278 #ifdef FEAT_VIRTUALEDIT
11279 (fp != NULL) ? (varnumber_T)fp->coladd :
11280 #endif
11281 (varnumber_T)0);
11283 else
11284 rettv->vval.v_number = FALSE;
11288 * "getqflist()" and "getloclist()" functions
11290 static void
11291 f_getqflist(argvars, rettv)
11292 typval_T *argvars UNUSED;
11293 typval_T *rettv UNUSED;
11295 #ifdef FEAT_QUICKFIX
11296 win_T *wp;
11297 #endif
11299 #ifdef FEAT_QUICKFIX
11300 if (rettv_list_alloc(rettv) == OK)
11302 wp = NULL;
11303 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
11305 wp = find_win_by_nr(&argvars[0], NULL);
11306 if (wp == NULL)
11307 return;
11310 (void)get_errorlist(wp, rettv->vval.v_list);
11312 #endif
11316 * "getreg()" function
11318 static void
11319 f_getreg(argvars, rettv)
11320 typval_T *argvars;
11321 typval_T *rettv;
11323 char_u *strregname;
11324 int regname;
11325 int arg2 = FALSE;
11326 int error = FALSE;
11328 if (argvars[0].v_type != VAR_UNKNOWN)
11330 strregname = get_tv_string_chk(&argvars[0]);
11331 error = strregname == NULL;
11332 if (argvars[1].v_type != VAR_UNKNOWN)
11333 arg2 = get_tv_number_chk(&argvars[1], &error);
11335 else
11336 strregname = vimvars[VV_REG].vv_str;
11337 regname = (strregname == NULL ? '"' : *strregname);
11338 if (regname == 0)
11339 regname = '"';
11341 rettv->v_type = VAR_STRING;
11342 rettv->vval.v_string = error ? NULL :
11343 get_reg_contents(regname, TRUE, arg2);
11347 * "getregtype()" function
11349 static void
11350 f_getregtype(argvars, rettv)
11351 typval_T *argvars;
11352 typval_T *rettv;
11354 char_u *strregname;
11355 int regname;
11356 char_u buf[NUMBUFLEN + 2];
11357 long reglen = 0;
11359 if (argvars[0].v_type != VAR_UNKNOWN)
11361 strregname = get_tv_string_chk(&argvars[0]);
11362 if (strregname == NULL) /* type error; errmsg already given */
11364 rettv->v_type = VAR_STRING;
11365 rettv->vval.v_string = NULL;
11366 return;
11369 else
11370 /* Default to v:register */
11371 strregname = vimvars[VV_REG].vv_str;
11373 regname = (strregname == NULL ? '"' : *strregname);
11374 if (regname == 0)
11375 regname = '"';
11377 buf[0] = NUL;
11378 buf[1] = NUL;
11379 switch (get_reg_type(regname, &reglen))
11381 case MLINE: buf[0] = 'V'; break;
11382 case MCHAR: buf[0] = 'v'; break;
11383 #ifdef FEAT_VISUAL
11384 case MBLOCK:
11385 buf[0] = Ctrl_V;
11386 sprintf((char *)buf + 1, "%ld", reglen + 1);
11387 break;
11388 #endif
11390 rettv->v_type = VAR_STRING;
11391 rettv->vval.v_string = vim_strsave(buf);
11395 * "gettabwinvar()" function
11397 static void
11398 f_gettabwinvar(argvars, rettv)
11399 typval_T *argvars;
11400 typval_T *rettv;
11402 getwinvar(argvars, rettv, 1);
11406 * "getwinposx()" function
11408 static void
11409 f_getwinposx(argvars, rettv)
11410 typval_T *argvars UNUSED;
11411 typval_T *rettv;
11413 rettv->vval.v_number = -1;
11414 #ifdef FEAT_GUI
11415 if (gui.in_use)
11417 int x, y;
11419 if (gui_mch_get_winpos(&x, &y) == OK)
11420 rettv->vval.v_number = x;
11422 #endif
11426 * "getwinposy()" function
11428 static void
11429 f_getwinposy(argvars, rettv)
11430 typval_T *argvars UNUSED;
11431 typval_T *rettv;
11433 rettv->vval.v_number = -1;
11434 #ifdef FEAT_GUI
11435 if (gui.in_use)
11437 int x, y;
11439 if (gui_mch_get_winpos(&x, &y) == OK)
11440 rettv->vval.v_number = y;
11442 #endif
11446 * Find window specified by "vp" in tabpage "tp".
11448 static win_T *
11449 find_win_by_nr(vp, tp)
11450 typval_T *vp;
11451 tabpage_T *tp; /* NULL for current tab page */
11453 #ifdef FEAT_WINDOWS
11454 win_T *wp;
11455 #endif
11456 int nr;
11458 nr = get_tv_number_chk(vp, NULL);
11460 #ifdef FEAT_WINDOWS
11461 if (nr < 0)
11462 return NULL;
11463 if (nr == 0)
11464 return curwin;
11466 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
11467 wp != NULL; wp = wp->w_next)
11468 if (--nr <= 0)
11469 break;
11470 return wp;
11471 #else
11472 if (nr == 0 || nr == 1)
11473 return curwin;
11474 return NULL;
11475 #endif
11479 * "getwinvar()" function
11481 static void
11482 f_getwinvar(argvars, rettv)
11483 typval_T *argvars;
11484 typval_T *rettv;
11486 getwinvar(argvars, rettv, 0);
11490 * getwinvar() and gettabwinvar()
11492 static void
11493 getwinvar(argvars, rettv, off)
11494 typval_T *argvars;
11495 typval_T *rettv;
11496 int off; /* 1 for gettabwinvar() */
11498 win_T *win, *oldcurwin;
11499 char_u *varname;
11500 dictitem_T *v;
11501 tabpage_T *tp;
11503 #ifdef FEAT_WINDOWS
11504 if (off == 1)
11505 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
11506 else
11507 tp = curtab;
11508 #endif
11509 win = find_win_by_nr(&argvars[off], tp);
11510 varname = get_tv_string_chk(&argvars[off + 1]);
11511 ++emsg_off;
11513 rettv->v_type = VAR_STRING;
11514 rettv->vval.v_string = NULL;
11516 if (win != NULL && varname != NULL)
11518 /* Set curwin to be our win, temporarily. Also set curbuf, so
11519 * that we can get buffer-local options. */
11520 oldcurwin = curwin;
11521 curwin = win;
11522 curbuf = win->w_buffer;
11524 if (*varname == '&') /* window-local-option */
11525 get_option_tv(&varname, rettv, 1);
11526 else
11528 if (*varname == NUL)
11529 /* let getwinvar({nr}, "") return the "w:" dictionary. The
11530 * scope prefix before the NUL byte is required by
11531 * find_var_in_ht(). */
11532 varname = (char_u *)"w:" + 2;
11533 /* look up the variable */
11534 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
11535 if (v != NULL)
11536 copy_tv(&v->di_tv, rettv);
11539 /* restore previous notion of curwin */
11540 curwin = oldcurwin;
11541 curbuf = curwin->w_buffer;
11544 --emsg_off;
11548 * "glob()" function
11550 static void
11551 f_glob(argvars, rettv)
11552 typval_T *argvars;
11553 typval_T *rettv;
11555 int flags = WILD_SILENT|WILD_USE_NL;
11556 expand_T xpc;
11557 int error = FALSE;
11559 /* When the optional second argument is non-zero, don't remove matches
11560 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11561 if (argvars[1].v_type != VAR_UNKNOWN
11562 && get_tv_number_chk(&argvars[1], &error))
11563 flags |= WILD_KEEP_ALL;
11564 rettv->v_type = VAR_STRING;
11565 if (!error)
11567 ExpandInit(&xpc);
11568 xpc.xp_context = EXPAND_FILES;
11569 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
11570 NULL, flags, WILD_ALL);
11572 else
11573 rettv->vval.v_string = NULL;
11577 * "globpath()" function
11579 static void
11580 f_globpath(argvars, rettv)
11581 typval_T *argvars;
11582 typval_T *rettv;
11584 int flags = 0;
11585 char_u buf1[NUMBUFLEN];
11586 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
11587 int error = FALSE;
11589 /* When the optional second argument is non-zero, don't remove matches
11590 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11591 if (argvars[2].v_type != VAR_UNKNOWN
11592 && get_tv_number_chk(&argvars[2], &error))
11593 flags |= WILD_KEEP_ALL;
11594 rettv->v_type = VAR_STRING;
11595 if (file == NULL || error)
11596 rettv->vval.v_string = NULL;
11597 else
11598 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file,
11599 flags);
11603 * "has()" function
11605 static void
11606 f_has(argvars, rettv)
11607 typval_T *argvars;
11608 typval_T *rettv;
11610 int i;
11611 char_u *name;
11612 int n = FALSE;
11613 static char *(has_list[]) =
11615 #ifdef AMIGA
11616 "amiga",
11617 # ifdef FEAT_ARP
11618 "arp",
11619 # endif
11620 #endif
11621 #ifdef __BEOS__
11622 "beos",
11623 #endif
11624 #ifdef MSDOS
11625 # ifdef DJGPP
11626 "dos32",
11627 # else
11628 "dos16",
11629 # endif
11630 #endif
11631 #ifdef MACOS
11632 "mac",
11633 #endif
11634 #if defined(MACOS_X_UNIX)
11635 "macunix",
11636 #endif
11637 #ifdef OS2
11638 "os2",
11639 #endif
11640 #ifdef __QNX__
11641 "qnx",
11642 #endif
11643 #ifdef RISCOS
11644 "riscos",
11645 #endif
11646 #ifdef UNIX
11647 "unix",
11648 #endif
11649 #ifdef VMS
11650 "vms",
11651 #endif
11652 #ifdef WIN16
11653 "win16",
11654 #endif
11655 #ifdef WIN32
11656 "win32",
11657 #endif
11658 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
11659 "win32unix",
11660 #endif
11661 #if defined(WIN64) || defined(_WIN64)
11662 "win64",
11663 #endif
11664 #ifdef EBCDIC
11665 "ebcdic",
11666 #endif
11667 #ifndef CASE_INSENSITIVE_FILENAME
11668 "fname_case",
11669 #endif
11670 #ifdef FEAT_ARABIC
11671 "arabic",
11672 #endif
11673 #ifdef FEAT_AUTOCMD
11674 "autocmd",
11675 #endif
11676 #ifdef FEAT_BEVAL
11677 "balloon_eval",
11678 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
11679 "balloon_multiline",
11680 # endif
11681 #endif
11682 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
11683 "builtin_terms",
11684 # ifdef ALL_BUILTIN_TCAPS
11685 "all_builtin_terms",
11686 # endif
11687 #endif
11688 #ifdef FEAT_BYTEOFF
11689 "byte_offset",
11690 #endif
11691 #ifdef FEAT_CINDENT
11692 "cindent",
11693 #endif
11694 #ifdef FEAT_CLIENTSERVER
11695 "clientserver",
11696 #endif
11697 #ifdef FEAT_CLIPBOARD
11698 "clipboard",
11699 #endif
11700 #ifdef FEAT_CMDL_COMPL
11701 "cmdline_compl",
11702 #endif
11703 #ifdef FEAT_CMDHIST
11704 "cmdline_hist",
11705 #endif
11706 #ifdef FEAT_COMMENTS
11707 "comments",
11708 #endif
11709 #ifdef FEAT_CRYPT
11710 "cryptv",
11711 #endif
11712 #ifdef FEAT_CSCOPE
11713 "cscope",
11714 #endif
11715 #ifdef CURSOR_SHAPE
11716 "cursorshape",
11717 #endif
11718 #ifdef DEBUG
11719 "debug",
11720 #endif
11721 #ifdef FEAT_CON_DIALOG
11722 "dialog_con",
11723 #endif
11724 #ifdef FEAT_GUI_DIALOG
11725 "dialog_gui",
11726 #endif
11727 #ifdef FEAT_DIFF
11728 "diff",
11729 #endif
11730 #ifdef FEAT_DIGRAPHS
11731 "digraphs",
11732 #endif
11733 #ifdef FEAT_DND
11734 "dnd",
11735 #endif
11736 #ifdef FEAT_EMACS_TAGS
11737 "emacs_tags",
11738 #endif
11739 "eval", /* always present, of course! */
11740 #ifdef FEAT_EX_EXTRA
11741 "ex_extra",
11742 #endif
11743 #ifdef FEAT_SEARCH_EXTRA
11744 "extra_search",
11745 #endif
11746 #ifdef FEAT_FKMAP
11747 "farsi",
11748 #endif
11749 #ifdef FEAT_SEARCHPATH
11750 "file_in_path",
11751 #endif
11752 #if defined(UNIX) && !defined(USE_SYSTEM)
11753 "filterpipe",
11754 #endif
11755 #ifdef FEAT_FIND_ID
11756 "find_in_path",
11757 #endif
11758 #ifdef FEAT_FLOAT
11759 "float",
11760 #endif
11761 #ifdef FEAT_FOLDING
11762 "folding",
11763 #endif
11764 #ifdef FEAT_FOOTER
11765 "footer",
11766 #endif
11767 #if !defined(USE_SYSTEM) && defined(UNIX)
11768 "fork",
11769 #endif
11770 #ifdef FEAT_GETTEXT
11771 "gettext",
11772 #endif
11773 #ifdef FEAT_GUI
11774 "gui",
11775 #endif
11776 #ifdef FEAT_GUI_ATHENA
11777 # ifdef FEAT_GUI_NEXTAW
11778 "gui_neXtaw",
11779 # else
11780 "gui_athena",
11781 # endif
11782 #endif
11783 #ifdef FEAT_GUI_GTK
11784 "gui_gtk",
11785 # ifdef HAVE_GTK2
11786 "gui_gtk2",
11787 # endif
11788 #endif
11789 #ifdef FEAT_GUI_GNOME
11790 "gui_gnome",
11791 #endif
11792 #ifdef FEAT_GUI_MAC
11793 "gui_mac",
11794 #endif
11795 #ifdef FEAT_GUI_MOTIF
11796 "gui_motif",
11797 #endif
11798 #ifdef FEAT_GUI_PHOTON
11799 "gui_photon",
11800 #endif
11801 #ifdef FEAT_GUI_W16
11802 "gui_win16",
11803 #endif
11804 #ifdef FEAT_GUI_W32
11805 "gui_win32",
11806 #endif
11807 #ifdef FEAT_HANGULIN
11808 "hangul_input",
11809 #endif
11810 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
11811 "iconv",
11812 #endif
11813 #ifdef FEAT_INS_EXPAND
11814 "insert_expand",
11815 #endif
11816 #ifdef FEAT_JUMPLIST
11817 "jumplist",
11818 #endif
11819 #ifdef FEAT_KEYMAP
11820 "keymap",
11821 #endif
11822 #ifdef FEAT_LANGMAP
11823 "langmap",
11824 #endif
11825 #ifdef FEAT_LIBCALL
11826 "libcall",
11827 #endif
11828 #ifdef FEAT_LINEBREAK
11829 "linebreak",
11830 #endif
11831 #ifdef FEAT_LISP
11832 "lispindent",
11833 #endif
11834 #ifdef FEAT_LISTCMDS
11835 "listcmds",
11836 #endif
11837 #ifdef FEAT_LOCALMAP
11838 "localmap",
11839 #endif
11840 #ifdef FEAT_MENU
11841 "menu",
11842 #endif
11843 #ifdef FEAT_SESSION
11844 "mksession",
11845 #endif
11846 #ifdef FEAT_MODIFY_FNAME
11847 "modify_fname",
11848 #endif
11849 #ifdef FEAT_MOUSE
11850 "mouse",
11851 #endif
11852 #ifdef FEAT_MOUSESHAPE
11853 "mouseshape",
11854 #endif
11855 #if defined(UNIX) || defined(VMS)
11856 # ifdef FEAT_MOUSE_DEC
11857 "mouse_dec",
11858 # endif
11859 # ifdef FEAT_MOUSE_GPM
11860 "mouse_gpm",
11861 # endif
11862 # ifdef FEAT_MOUSE_JSB
11863 "mouse_jsbterm",
11864 # endif
11865 # ifdef FEAT_MOUSE_NET
11866 "mouse_netterm",
11867 # endif
11868 # ifdef FEAT_MOUSE_PTERM
11869 "mouse_pterm",
11870 # endif
11871 # ifdef FEAT_SYSMOUSE
11872 "mouse_sysmouse",
11873 # endif
11874 # ifdef FEAT_MOUSE_XTERM
11875 "mouse_xterm",
11876 # endif
11877 #endif
11878 #ifdef FEAT_MBYTE
11879 "multi_byte",
11880 #endif
11881 #ifdef FEAT_MBYTE_IME
11882 "multi_byte_ime",
11883 #endif
11884 #ifdef FEAT_MULTI_LANG
11885 "multi_lang",
11886 #endif
11887 #ifdef FEAT_MZSCHEME
11888 #ifndef DYNAMIC_MZSCHEME
11889 "mzscheme",
11890 #endif
11891 #endif
11892 #ifdef FEAT_OLE
11893 "ole",
11894 #endif
11895 #ifdef FEAT_OSFILETYPE
11896 "osfiletype",
11897 #endif
11898 #ifdef FEAT_PATH_EXTRA
11899 "path_extra",
11900 #endif
11901 #ifdef FEAT_PERL
11902 #ifndef DYNAMIC_PERL
11903 "perl",
11904 #endif
11905 #endif
11906 #ifdef FEAT_PYTHON
11907 #ifndef DYNAMIC_PYTHON
11908 "python",
11909 #endif
11910 #endif
11911 #ifdef FEAT_POSTSCRIPT
11912 "postscript",
11913 #endif
11914 #ifdef FEAT_PRINTER
11915 "printer",
11916 #endif
11917 #ifdef FEAT_PROFILE
11918 "profile",
11919 #endif
11920 #ifdef FEAT_RELTIME
11921 "reltime",
11922 #endif
11923 #ifdef FEAT_QUICKFIX
11924 "quickfix",
11925 #endif
11926 #ifdef FEAT_RIGHTLEFT
11927 "rightleft",
11928 #endif
11929 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11930 "ruby",
11931 #endif
11932 #ifdef FEAT_SCROLLBIND
11933 "scrollbind",
11934 #endif
11935 #ifdef FEAT_CMDL_INFO
11936 "showcmd",
11937 "cmdline_info",
11938 #endif
11939 #ifdef FEAT_SIGNS
11940 "signs",
11941 #endif
11942 #ifdef FEAT_SMARTINDENT
11943 "smartindent",
11944 #endif
11945 #ifdef FEAT_SNIFF
11946 "sniff",
11947 #endif
11948 #ifdef STARTUPTIME
11949 "startuptime",
11950 #endif
11951 #ifdef FEAT_STL_OPT
11952 "statusline",
11953 #endif
11954 #ifdef FEAT_SUN_WORKSHOP
11955 "sun_workshop",
11956 #endif
11957 #ifdef FEAT_NETBEANS_INTG
11958 "netbeans_intg",
11959 #endif
11960 #ifdef FEAT_SPELL
11961 "spell",
11962 #endif
11963 #ifdef FEAT_SYN_HL
11964 "syntax",
11965 #endif
11966 #if defined(USE_SYSTEM) || !defined(UNIX)
11967 "system",
11968 #endif
11969 #ifdef FEAT_TAG_BINS
11970 "tag_binary",
11971 #endif
11972 #ifdef FEAT_TAG_OLDSTATIC
11973 "tag_old_static",
11974 #endif
11975 #ifdef FEAT_TAG_ANYWHITE
11976 "tag_any_white",
11977 #endif
11978 #ifdef FEAT_TCL
11979 # ifndef DYNAMIC_TCL
11980 "tcl",
11981 # endif
11982 #endif
11983 #ifdef TERMINFO
11984 "terminfo",
11985 #endif
11986 #ifdef FEAT_TERMRESPONSE
11987 "termresponse",
11988 #endif
11989 #ifdef FEAT_TEXTOBJ
11990 "textobjects",
11991 #endif
11992 #ifdef HAVE_TGETENT
11993 "tgetent",
11994 #endif
11995 #ifdef FEAT_TITLE
11996 "title",
11997 #endif
11998 #ifdef FEAT_TOOLBAR
11999 "toolbar",
12000 #endif
12001 #ifdef FEAT_USR_CMDS
12002 "user-commands", /* was accidentally included in 5.4 */
12003 "user_commands",
12004 #endif
12005 #ifdef FEAT_VIMINFO
12006 "viminfo",
12007 #endif
12008 #ifdef FEAT_VERTSPLIT
12009 "vertsplit",
12010 #endif
12011 #ifdef FEAT_VIRTUALEDIT
12012 "virtualedit",
12013 #endif
12014 #ifdef FEAT_VISUAL
12015 "visual",
12016 #endif
12017 #ifdef FEAT_VISUALEXTRA
12018 "visualextra",
12019 #endif
12020 #ifdef FEAT_VREPLACE
12021 "vreplace",
12022 #endif
12023 #ifdef FEAT_WILDIGN
12024 "wildignore",
12025 #endif
12026 #ifdef FEAT_WILDMENU
12027 "wildmenu",
12028 #endif
12029 #ifdef FEAT_WINDOWS
12030 "windows",
12031 #endif
12032 #ifdef FEAT_WAK
12033 "winaltkeys",
12034 #endif
12035 #ifdef FEAT_WRITEBACKUP
12036 "writebackup",
12037 #endif
12038 #ifdef FEAT_XIM
12039 "xim",
12040 #endif
12041 #ifdef FEAT_XFONTSET
12042 "xfontset",
12043 #endif
12044 #ifdef USE_XSMP
12045 "xsmp",
12046 #endif
12047 #ifdef USE_XSMP_INTERACT
12048 "xsmp_interact",
12049 #endif
12050 #ifdef FEAT_XCLIPBOARD
12051 "xterm_clipboard",
12052 #endif
12053 #ifdef FEAT_XTERM_SAVE
12054 "xterm_save",
12055 #endif
12056 #if defined(UNIX) && defined(FEAT_X11)
12057 "X11",
12058 #endif
12059 NULL
12062 name = get_tv_string(&argvars[0]);
12063 for (i = 0; has_list[i] != NULL; ++i)
12064 if (STRICMP(name, has_list[i]) == 0)
12066 n = TRUE;
12067 break;
12070 if (n == FALSE)
12072 if (STRNICMP(name, "patch", 5) == 0)
12073 n = has_patch(atoi((char *)name + 5));
12074 else if (STRICMP(name, "vim_starting") == 0)
12075 n = (starting != 0);
12076 #ifdef FEAT_MBYTE
12077 else if (STRICMP(name, "multi_byte_encoding") == 0)
12078 n = has_mbyte;
12079 #endif
12080 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
12081 else if (STRICMP(name, "balloon_multiline") == 0)
12082 n = multiline_balloon_available();
12083 #endif
12084 #ifdef DYNAMIC_TCL
12085 else if (STRICMP(name, "tcl") == 0)
12086 n = tcl_enabled(FALSE);
12087 #endif
12088 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
12089 else if (STRICMP(name, "iconv") == 0)
12090 n = iconv_enabled(FALSE);
12091 #endif
12092 #ifdef DYNAMIC_MZSCHEME
12093 else if (STRICMP(name, "mzscheme") == 0)
12094 n = mzscheme_enabled(FALSE);
12095 #endif
12096 #ifdef DYNAMIC_RUBY
12097 else if (STRICMP(name, "ruby") == 0)
12098 n = ruby_enabled(FALSE);
12099 #endif
12100 #ifdef DYNAMIC_PYTHON
12101 else if (STRICMP(name, "python") == 0)
12102 n = python_enabled(FALSE);
12103 #endif
12104 #ifdef DYNAMIC_PERL
12105 else if (STRICMP(name, "perl") == 0)
12106 n = perl_enabled(FALSE);
12107 #endif
12108 #ifdef FEAT_GUI
12109 else if (STRICMP(name, "gui_running") == 0)
12110 n = (gui.in_use || gui.starting);
12111 # ifdef FEAT_GUI_W32
12112 else if (STRICMP(name, "gui_win32s") == 0)
12113 n = gui_is_win32s();
12114 # endif
12115 # ifdef FEAT_BROWSE
12116 else if (STRICMP(name, "browse") == 0)
12117 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
12118 # endif
12119 #endif
12120 #ifdef FEAT_SYN_HL
12121 else if (STRICMP(name, "syntax_items") == 0)
12122 n = syntax_present(curbuf);
12123 #endif
12124 #if defined(WIN3264)
12125 else if (STRICMP(name, "win95") == 0)
12126 n = mch_windows95();
12127 #endif
12128 #ifdef FEAT_NETBEANS_INTG
12129 else if (STRICMP(name, "netbeans_enabled") == 0)
12130 n = usingNetbeans;
12131 #endif
12134 rettv->vval.v_number = n;
12138 * "has_key()" function
12140 static void
12141 f_has_key(argvars, rettv)
12142 typval_T *argvars;
12143 typval_T *rettv;
12145 if (argvars[0].v_type != VAR_DICT)
12147 EMSG(_(e_dictreq));
12148 return;
12150 if (argvars[0].vval.v_dict == NULL)
12151 return;
12153 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
12154 get_tv_string(&argvars[1]), -1) != NULL;
12158 * "haslocaldir()" function
12160 static void
12161 f_haslocaldir(argvars, rettv)
12162 typval_T *argvars UNUSED;
12163 typval_T *rettv;
12165 rettv->vval.v_number = (curwin->w_localdir != NULL);
12169 * "hasmapto()" function
12171 static void
12172 f_hasmapto(argvars, rettv)
12173 typval_T *argvars;
12174 typval_T *rettv;
12176 char_u *name;
12177 char_u *mode;
12178 char_u buf[NUMBUFLEN];
12179 int abbr = FALSE;
12181 name = get_tv_string(&argvars[0]);
12182 if (argvars[1].v_type == VAR_UNKNOWN)
12183 mode = (char_u *)"nvo";
12184 else
12186 mode = get_tv_string_buf(&argvars[1], buf);
12187 if (argvars[2].v_type != VAR_UNKNOWN)
12188 abbr = get_tv_number(&argvars[2]);
12191 if (map_to_exists(name, mode, abbr))
12192 rettv->vval.v_number = TRUE;
12193 else
12194 rettv->vval.v_number = FALSE;
12198 * "histadd()" function
12200 static void
12201 f_histadd(argvars, rettv)
12202 typval_T *argvars UNUSED;
12203 typval_T *rettv;
12205 #ifdef FEAT_CMDHIST
12206 int histype;
12207 char_u *str;
12208 char_u buf[NUMBUFLEN];
12209 #endif
12211 rettv->vval.v_number = FALSE;
12212 if (check_restricted() || check_secure())
12213 return;
12214 #ifdef FEAT_CMDHIST
12215 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12216 histype = str != NULL ? get_histtype(str) : -1;
12217 if (histype >= 0)
12219 str = get_tv_string_buf(&argvars[1], buf);
12220 if (*str != NUL)
12222 init_history();
12223 add_to_history(histype, str, FALSE, NUL);
12224 rettv->vval.v_number = TRUE;
12225 return;
12228 #endif
12232 * "histdel()" function
12234 static void
12235 f_histdel(argvars, rettv)
12236 typval_T *argvars UNUSED;
12237 typval_T *rettv UNUSED;
12239 #ifdef FEAT_CMDHIST
12240 int n;
12241 char_u buf[NUMBUFLEN];
12242 char_u *str;
12244 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12245 if (str == NULL)
12246 n = 0;
12247 else if (argvars[1].v_type == VAR_UNKNOWN)
12248 /* only one argument: clear entire history */
12249 n = clr_history(get_histtype(str));
12250 else if (argvars[1].v_type == VAR_NUMBER)
12251 /* index given: remove that entry */
12252 n = del_history_idx(get_histtype(str),
12253 (int)get_tv_number(&argvars[1]));
12254 else
12255 /* string given: remove all matching entries */
12256 n = del_history_entry(get_histtype(str),
12257 get_tv_string_buf(&argvars[1], buf));
12258 rettv->vval.v_number = n;
12259 #endif
12263 * "histget()" function
12265 static void
12266 f_histget(argvars, rettv)
12267 typval_T *argvars UNUSED;
12268 typval_T *rettv;
12270 #ifdef FEAT_CMDHIST
12271 int type;
12272 int idx;
12273 char_u *str;
12275 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12276 if (str == NULL)
12277 rettv->vval.v_string = NULL;
12278 else
12280 type = get_histtype(str);
12281 if (argvars[1].v_type == VAR_UNKNOWN)
12282 idx = get_history_idx(type);
12283 else
12284 idx = (int)get_tv_number_chk(&argvars[1], NULL);
12285 /* -1 on type error */
12286 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
12288 #else
12289 rettv->vval.v_string = NULL;
12290 #endif
12291 rettv->v_type = VAR_STRING;
12295 * "histnr()" function
12297 static void
12298 f_histnr(argvars, rettv)
12299 typval_T *argvars UNUSED;
12300 typval_T *rettv;
12302 int i;
12304 #ifdef FEAT_CMDHIST
12305 char_u *history = get_tv_string_chk(&argvars[0]);
12307 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
12308 if (i >= HIST_CMD && i < HIST_COUNT)
12309 i = get_history_idx(i);
12310 else
12311 #endif
12312 i = -1;
12313 rettv->vval.v_number = i;
12317 * "highlightID(name)" function
12319 static void
12320 f_hlID(argvars, rettv)
12321 typval_T *argvars;
12322 typval_T *rettv;
12324 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
12328 * "highlight_exists()" function
12330 static void
12331 f_hlexists(argvars, rettv)
12332 typval_T *argvars;
12333 typval_T *rettv;
12335 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
12339 * "hostname()" function
12341 static void
12342 f_hostname(argvars, rettv)
12343 typval_T *argvars UNUSED;
12344 typval_T *rettv;
12346 char_u hostname[256];
12348 mch_get_host_name(hostname, 256);
12349 rettv->v_type = VAR_STRING;
12350 rettv->vval.v_string = vim_strsave(hostname);
12354 * iconv() function
12356 static void
12357 f_iconv(argvars, rettv)
12358 typval_T *argvars UNUSED;
12359 typval_T *rettv;
12361 #ifdef FEAT_MBYTE
12362 char_u buf1[NUMBUFLEN];
12363 char_u buf2[NUMBUFLEN];
12364 char_u *from, *to, *str;
12365 vimconv_T vimconv;
12366 #endif
12368 rettv->v_type = VAR_STRING;
12369 rettv->vval.v_string = NULL;
12371 #ifdef FEAT_MBYTE
12372 str = get_tv_string(&argvars[0]);
12373 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
12374 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
12375 vimconv.vc_type = CONV_NONE;
12376 convert_setup(&vimconv, from, to);
12378 /* If the encodings are equal, no conversion needed. */
12379 if (vimconv.vc_type == CONV_NONE)
12380 rettv->vval.v_string = vim_strsave(str);
12381 else
12382 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
12384 convert_setup(&vimconv, NULL, NULL);
12385 vim_free(from);
12386 vim_free(to);
12387 #endif
12391 * "indent()" function
12393 static void
12394 f_indent(argvars, rettv)
12395 typval_T *argvars;
12396 typval_T *rettv;
12398 linenr_T lnum;
12400 lnum = get_tv_lnum(argvars);
12401 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12402 rettv->vval.v_number = get_indent_lnum(lnum);
12403 else
12404 rettv->vval.v_number = -1;
12408 * "index()" function
12410 static void
12411 f_index(argvars, rettv)
12412 typval_T *argvars;
12413 typval_T *rettv;
12415 list_T *l;
12416 listitem_T *item;
12417 long idx = 0;
12418 int ic = FALSE;
12420 rettv->vval.v_number = -1;
12421 if (argvars[0].v_type != VAR_LIST)
12423 EMSG(_(e_listreq));
12424 return;
12426 l = argvars[0].vval.v_list;
12427 if (l != NULL)
12429 item = l->lv_first;
12430 if (argvars[2].v_type != VAR_UNKNOWN)
12432 int error = FALSE;
12434 /* Start at specified item. Use the cached index that list_find()
12435 * sets, so that a negative number also works. */
12436 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
12437 idx = l->lv_idx;
12438 if (argvars[3].v_type != VAR_UNKNOWN)
12439 ic = get_tv_number_chk(&argvars[3], &error);
12440 if (error)
12441 item = NULL;
12444 for ( ; item != NULL; item = item->li_next, ++idx)
12445 if (tv_equal(&item->li_tv, &argvars[1], ic))
12447 rettv->vval.v_number = idx;
12448 break;
12453 static int inputsecret_flag = 0;
12455 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
12458 * This function is used by f_input() and f_inputdialog() functions. The third
12459 * argument to f_input() specifies the type of completion to use at the
12460 * prompt. The third argument to f_inputdialog() specifies the value to return
12461 * when the user cancels the prompt.
12463 static void
12464 get_user_input(argvars, rettv, inputdialog)
12465 typval_T *argvars;
12466 typval_T *rettv;
12467 int inputdialog;
12469 char_u *prompt = get_tv_string_chk(&argvars[0]);
12470 char_u *p = NULL;
12471 int c;
12472 char_u buf[NUMBUFLEN];
12473 int cmd_silent_save = cmd_silent;
12474 char_u *defstr = (char_u *)"";
12475 int xp_type = EXPAND_NOTHING;
12476 char_u *xp_arg = NULL;
12478 rettv->v_type = VAR_STRING;
12479 rettv->vval.v_string = NULL;
12481 #ifdef NO_CONSOLE_INPUT
12482 /* While starting up, there is no place to enter text. */
12483 if (no_console_input())
12484 return;
12485 #endif
12487 cmd_silent = FALSE; /* Want to see the prompt. */
12488 if (prompt != NULL)
12490 /* Only the part of the message after the last NL is considered as
12491 * prompt for the command line */
12492 p = vim_strrchr(prompt, '\n');
12493 if (p == NULL)
12494 p = prompt;
12495 else
12497 ++p;
12498 c = *p;
12499 *p = NUL;
12500 msg_start();
12501 msg_clr_eos();
12502 msg_puts_attr(prompt, echo_attr);
12503 msg_didout = FALSE;
12504 msg_starthere();
12505 *p = c;
12507 cmdline_row = msg_row;
12509 if (argvars[1].v_type != VAR_UNKNOWN)
12511 defstr = get_tv_string_buf_chk(&argvars[1], buf);
12512 if (defstr != NULL)
12513 stuffReadbuffSpec(defstr);
12515 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
12517 char_u *xp_name;
12518 int xp_namelen;
12519 long argt;
12521 rettv->vval.v_string = NULL;
12523 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
12524 if (xp_name == NULL)
12525 return;
12527 xp_namelen = (int)STRLEN(xp_name);
12529 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
12530 &xp_arg) == FAIL)
12531 return;
12535 if (defstr != NULL)
12536 rettv->vval.v_string =
12537 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
12538 xp_type, xp_arg);
12540 vim_free(xp_arg);
12542 /* since the user typed this, no need to wait for return */
12543 need_wait_return = FALSE;
12544 msg_didout = FALSE;
12546 cmd_silent = cmd_silent_save;
12550 * "input()" function
12551 * Also handles inputsecret() when inputsecret is set.
12553 static void
12554 f_input(argvars, rettv)
12555 typval_T *argvars;
12556 typval_T *rettv;
12558 get_user_input(argvars, rettv, FALSE);
12562 * "inputdialog()" function
12564 static void
12565 f_inputdialog(argvars, rettv)
12566 typval_T *argvars;
12567 typval_T *rettv;
12569 #if defined(FEAT_GUI_TEXTDIALOG)
12570 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
12571 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
12573 char_u *message;
12574 char_u buf[NUMBUFLEN];
12575 char_u *defstr = (char_u *)"";
12577 message = get_tv_string_chk(&argvars[0]);
12578 if (argvars[1].v_type != VAR_UNKNOWN
12579 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
12580 vim_strncpy(IObuff, defstr, IOSIZE - 1);
12581 else
12582 IObuff[0] = NUL;
12583 if (message != NULL && defstr != NULL
12584 && do_dialog(VIM_QUESTION, NULL, message,
12585 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
12586 rettv->vval.v_string = vim_strsave(IObuff);
12587 else
12589 if (message != NULL && defstr != NULL
12590 && argvars[1].v_type != VAR_UNKNOWN
12591 && argvars[2].v_type != VAR_UNKNOWN)
12592 rettv->vval.v_string = vim_strsave(
12593 get_tv_string_buf(&argvars[2], buf));
12594 else
12595 rettv->vval.v_string = NULL;
12597 rettv->v_type = VAR_STRING;
12599 else
12600 #endif
12601 get_user_input(argvars, rettv, TRUE);
12605 * "inputlist()" function
12607 static void
12608 f_inputlist(argvars, rettv)
12609 typval_T *argvars;
12610 typval_T *rettv;
12612 listitem_T *li;
12613 int selected;
12614 int mouse_used;
12616 #ifdef NO_CONSOLE_INPUT
12617 /* While starting up, there is no place to enter text. */
12618 if (no_console_input())
12619 return;
12620 #endif
12621 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
12623 EMSG2(_(e_listarg), "inputlist()");
12624 return;
12627 msg_start();
12628 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
12629 lines_left = Rows; /* avoid more prompt */
12630 msg_scroll = TRUE;
12631 msg_clr_eos();
12633 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
12635 msg_puts(get_tv_string(&li->li_tv));
12636 msg_putchar('\n');
12639 /* Ask for choice. */
12640 selected = prompt_for_number(&mouse_used);
12641 if (mouse_used)
12642 selected -= lines_left;
12644 rettv->vval.v_number = selected;
12648 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
12651 * "inputrestore()" function
12653 static void
12654 f_inputrestore(argvars, rettv)
12655 typval_T *argvars UNUSED;
12656 typval_T *rettv;
12658 if (ga_userinput.ga_len > 0)
12660 --ga_userinput.ga_len;
12661 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
12662 + ga_userinput.ga_len);
12663 /* default return is zero == OK */
12665 else if (p_verbose > 1)
12667 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
12668 rettv->vval.v_number = 1; /* Failed */
12673 * "inputsave()" function
12675 static void
12676 f_inputsave(argvars, rettv)
12677 typval_T *argvars UNUSED;
12678 typval_T *rettv;
12680 /* Add an entry to the stack of typeahead storage. */
12681 if (ga_grow(&ga_userinput, 1) == OK)
12683 save_typeahead((tasave_T *)(ga_userinput.ga_data)
12684 + ga_userinput.ga_len);
12685 ++ga_userinput.ga_len;
12686 /* default return is zero == OK */
12688 else
12689 rettv->vval.v_number = 1; /* Failed */
12693 * "inputsecret()" function
12695 static void
12696 f_inputsecret(argvars, rettv)
12697 typval_T *argvars;
12698 typval_T *rettv;
12700 ++cmdline_star;
12701 ++inputsecret_flag;
12702 f_input(argvars, rettv);
12703 --cmdline_star;
12704 --inputsecret_flag;
12708 * "insert()" function
12710 static void
12711 f_insert(argvars, rettv)
12712 typval_T *argvars;
12713 typval_T *rettv;
12715 long before = 0;
12716 listitem_T *item;
12717 list_T *l;
12718 int error = FALSE;
12720 if (argvars[0].v_type != VAR_LIST)
12721 EMSG2(_(e_listarg), "insert()");
12722 else if ((l = argvars[0].vval.v_list) != NULL
12723 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
12725 if (argvars[2].v_type != VAR_UNKNOWN)
12726 before = get_tv_number_chk(&argvars[2], &error);
12727 if (error)
12728 return; /* type error; errmsg already given */
12730 if (before == l->lv_len)
12731 item = NULL;
12732 else
12734 item = list_find(l, before);
12735 if (item == NULL)
12737 EMSGN(_(e_listidx), before);
12738 l = NULL;
12741 if (l != NULL)
12743 list_insert_tv(l, &argvars[1], item);
12744 copy_tv(&argvars[0], rettv);
12750 * "isdirectory()" function
12752 static void
12753 f_isdirectory(argvars, rettv)
12754 typval_T *argvars;
12755 typval_T *rettv;
12757 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
12761 * "islocked()" function
12763 static void
12764 f_islocked(argvars, rettv)
12765 typval_T *argvars;
12766 typval_T *rettv;
12768 lval_T lv;
12769 char_u *end;
12770 dictitem_T *di;
12772 rettv->vval.v_number = -1;
12773 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
12774 FNE_CHECK_START);
12775 if (end != NULL && lv.ll_name != NULL)
12777 if (*end != NUL)
12778 EMSG(_(e_trailing));
12779 else
12781 if (lv.ll_tv == NULL)
12783 if (check_changedtick(lv.ll_name))
12784 rettv->vval.v_number = 1; /* always locked */
12785 else
12787 di = find_var(lv.ll_name, NULL);
12788 if (di != NULL)
12790 /* Consider a variable locked when:
12791 * 1. the variable itself is locked
12792 * 2. the value of the variable is locked.
12793 * 3. the List or Dict value is locked.
12795 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
12796 || tv_islocked(&di->di_tv));
12800 else if (lv.ll_range)
12801 EMSG(_("E786: Range not allowed"));
12802 else if (lv.ll_newkey != NULL)
12803 EMSG2(_(e_dictkey), lv.ll_newkey);
12804 else if (lv.ll_list != NULL)
12805 /* List item. */
12806 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
12807 else
12808 /* Dictionary item. */
12809 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
12813 clear_lval(&lv);
12816 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
12819 * Turn a dict into a list:
12820 * "what" == 0: list of keys
12821 * "what" == 1: list of values
12822 * "what" == 2: list of items
12824 static void
12825 dict_list(argvars, rettv, what)
12826 typval_T *argvars;
12827 typval_T *rettv;
12828 int what;
12830 list_T *l2;
12831 dictitem_T *di;
12832 hashitem_T *hi;
12833 listitem_T *li;
12834 listitem_T *li2;
12835 dict_T *d;
12836 int todo;
12838 if (argvars[0].v_type != VAR_DICT)
12840 EMSG(_(e_dictreq));
12841 return;
12843 if ((d = argvars[0].vval.v_dict) == NULL)
12844 return;
12846 if (rettv_list_alloc(rettv) == FAIL)
12847 return;
12849 todo = (int)d->dv_hashtab.ht_used;
12850 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12852 if (!HASHITEM_EMPTY(hi))
12854 --todo;
12855 di = HI2DI(hi);
12857 li = listitem_alloc();
12858 if (li == NULL)
12859 break;
12860 list_append(rettv->vval.v_list, li);
12862 if (what == 0)
12864 /* keys() */
12865 li->li_tv.v_type = VAR_STRING;
12866 li->li_tv.v_lock = 0;
12867 li->li_tv.vval.v_string = vim_strsave(di->di_key);
12869 else if (what == 1)
12871 /* values() */
12872 copy_tv(&di->di_tv, &li->li_tv);
12874 else
12876 /* items() */
12877 l2 = list_alloc();
12878 li->li_tv.v_type = VAR_LIST;
12879 li->li_tv.v_lock = 0;
12880 li->li_tv.vval.v_list = l2;
12881 if (l2 == NULL)
12882 break;
12883 ++l2->lv_refcount;
12885 li2 = listitem_alloc();
12886 if (li2 == NULL)
12887 break;
12888 list_append(l2, li2);
12889 li2->li_tv.v_type = VAR_STRING;
12890 li2->li_tv.v_lock = 0;
12891 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12893 li2 = listitem_alloc();
12894 if (li2 == NULL)
12895 break;
12896 list_append(l2, li2);
12897 copy_tv(&di->di_tv, &li2->li_tv);
12904 * "items(dict)" function
12906 static void
12907 f_items(argvars, rettv)
12908 typval_T *argvars;
12909 typval_T *rettv;
12911 dict_list(argvars, rettv, 2);
12915 * "join()" function
12917 static void
12918 f_join(argvars, rettv)
12919 typval_T *argvars;
12920 typval_T *rettv;
12922 garray_T ga;
12923 char_u *sep;
12925 if (argvars[0].v_type != VAR_LIST)
12927 EMSG(_(e_listreq));
12928 return;
12930 if (argvars[0].vval.v_list == NULL)
12931 return;
12932 if (argvars[1].v_type == VAR_UNKNOWN)
12933 sep = (char_u *)" ";
12934 else
12935 sep = get_tv_string_chk(&argvars[1]);
12937 rettv->v_type = VAR_STRING;
12939 if (sep != NULL)
12941 ga_init2(&ga, (int)sizeof(char), 80);
12942 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12943 ga_append(&ga, NUL);
12944 rettv->vval.v_string = (char_u *)ga.ga_data;
12946 else
12947 rettv->vval.v_string = NULL;
12951 * "keys()" function
12953 static void
12954 f_keys(argvars, rettv)
12955 typval_T *argvars;
12956 typval_T *rettv;
12958 dict_list(argvars, rettv, 0);
12962 * "last_buffer_nr()" function.
12964 static void
12965 f_last_buffer_nr(argvars, rettv)
12966 typval_T *argvars UNUSED;
12967 typval_T *rettv;
12969 int n = 0;
12970 buf_T *buf;
12972 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12973 if (n < buf->b_fnum)
12974 n = buf->b_fnum;
12976 rettv->vval.v_number = n;
12980 * "len()" function
12982 static void
12983 f_len(argvars, rettv)
12984 typval_T *argvars;
12985 typval_T *rettv;
12987 switch (argvars[0].v_type)
12989 case VAR_STRING:
12990 case VAR_NUMBER:
12991 rettv->vval.v_number = (varnumber_T)STRLEN(
12992 get_tv_string(&argvars[0]));
12993 break;
12994 case VAR_LIST:
12995 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
12996 break;
12997 case VAR_DICT:
12998 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
12999 break;
13000 default:
13001 EMSG(_("E701: Invalid type for len()"));
13002 break;
13006 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
13008 static void
13009 libcall_common(argvars, rettv, type)
13010 typval_T *argvars;
13011 typval_T *rettv;
13012 int type;
13014 #ifdef FEAT_LIBCALL
13015 char_u *string_in;
13016 char_u **string_result;
13017 int nr_result;
13018 #endif
13020 rettv->v_type = type;
13021 if (type != VAR_NUMBER)
13022 rettv->vval.v_string = NULL;
13024 if (check_restricted() || check_secure())
13025 return;
13027 #ifdef FEAT_LIBCALL
13028 /* The first two args must be strings, otherwise its meaningless */
13029 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
13031 string_in = NULL;
13032 if (argvars[2].v_type == VAR_STRING)
13033 string_in = argvars[2].vval.v_string;
13034 if (type == VAR_NUMBER)
13035 string_result = NULL;
13036 else
13037 string_result = &rettv->vval.v_string;
13038 if (mch_libcall(argvars[0].vval.v_string,
13039 argvars[1].vval.v_string,
13040 string_in,
13041 argvars[2].vval.v_number,
13042 string_result,
13043 &nr_result) == OK
13044 && type == VAR_NUMBER)
13045 rettv->vval.v_number = nr_result;
13047 #endif
13051 * "libcall()" function
13053 static void
13054 f_libcall(argvars, rettv)
13055 typval_T *argvars;
13056 typval_T *rettv;
13058 libcall_common(argvars, rettv, VAR_STRING);
13062 * "libcallnr()" function
13064 static void
13065 f_libcallnr(argvars, rettv)
13066 typval_T *argvars;
13067 typval_T *rettv;
13069 libcall_common(argvars, rettv, VAR_NUMBER);
13073 * "line(string)" function
13075 static void
13076 f_line(argvars, rettv)
13077 typval_T *argvars;
13078 typval_T *rettv;
13080 linenr_T lnum = 0;
13081 pos_T *fp;
13082 int fnum;
13084 fp = var2fpos(&argvars[0], TRUE, &fnum);
13085 if (fp != NULL)
13086 lnum = fp->lnum;
13087 rettv->vval.v_number = lnum;
13091 * "line2byte(lnum)" function
13093 static void
13094 f_line2byte(argvars, rettv)
13095 typval_T *argvars UNUSED;
13096 typval_T *rettv;
13098 #ifndef FEAT_BYTEOFF
13099 rettv->vval.v_number = -1;
13100 #else
13101 linenr_T lnum;
13103 lnum = get_tv_lnum(argvars);
13104 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
13105 rettv->vval.v_number = -1;
13106 else
13107 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
13108 if (rettv->vval.v_number >= 0)
13109 ++rettv->vval.v_number;
13110 #endif
13114 * "lispindent(lnum)" function
13116 static void
13117 f_lispindent(argvars, rettv)
13118 typval_T *argvars;
13119 typval_T *rettv;
13121 #ifdef FEAT_LISP
13122 pos_T pos;
13123 linenr_T lnum;
13125 pos = curwin->w_cursor;
13126 lnum = get_tv_lnum(argvars);
13127 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
13129 curwin->w_cursor.lnum = lnum;
13130 rettv->vval.v_number = get_lisp_indent();
13131 curwin->w_cursor = pos;
13133 else
13134 #endif
13135 rettv->vval.v_number = -1;
13139 * "localtime()" function
13141 static void
13142 f_localtime(argvars, rettv)
13143 typval_T *argvars UNUSED;
13144 typval_T *rettv;
13146 rettv->vval.v_number = (varnumber_T)time(NULL);
13149 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
13151 static void
13152 get_maparg(argvars, rettv, exact)
13153 typval_T *argvars;
13154 typval_T *rettv;
13155 int exact;
13157 char_u *keys;
13158 char_u *which;
13159 char_u buf[NUMBUFLEN];
13160 char_u *keys_buf = NULL;
13161 char_u *rhs;
13162 int mode;
13163 garray_T ga;
13164 int abbr = FALSE;
13166 /* return empty string for failure */
13167 rettv->v_type = VAR_STRING;
13168 rettv->vval.v_string = NULL;
13170 keys = get_tv_string(&argvars[0]);
13171 if (*keys == NUL)
13172 return;
13174 if (argvars[1].v_type != VAR_UNKNOWN)
13176 which = get_tv_string_buf_chk(&argvars[1], buf);
13177 if (argvars[2].v_type != VAR_UNKNOWN)
13178 abbr = get_tv_number(&argvars[2]);
13180 else
13181 which = (char_u *)"";
13182 if (which == NULL)
13183 return;
13185 mode = get_map_mode(&which, 0);
13187 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
13188 rhs = check_map(keys, mode, exact, FALSE, abbr);
13189 vim_free(keys_buf);
13190 if (rhs != NULL)
13192 ga_init(&ga);
13193 ga.ga_itemsize = 1;
13194 ga.ga_growsize = 40;
13196 while (*rhs != NUL)
13197 ga_concat(&ga, str2special(&rhs, FALSE));
13199 ga_append(&ga, NUL);
13200 rettv->vval.v_string = (char_u *)ga.ga_data;
13204 #ifdef FEAT_FLOAT
13206 * "log10()" function
13208 static void
13209 f_log10(argvars, rettv)
13210 typval_T *argvars;
13211 typval_T *rettv;
13213 float_T f;
13215 rettv->v_type = VAR_FLOAT;
13216 if (get_float_arg(argvars, &f) == OK)
13217 rettv->vval.v_float = log10(f);
13218 else
13219 rettv->vval.v_float = 0.0;
13221 #endif
13224 * "map()" function
13226 static void
13227 f_map(argvars, rettv)
13228 typval_T *argvars;
13229 typval_T *rettv;
13231 filter_map(argvars, rettv, TRUE);
13235 * "maparg()" function
13237 static void
13238 f_maparg(argvars, rettv)
13239 typval_T *argvars;
13240 typval_T *rettv;
13242 get_maparg(argvars, rettv, TRUE);
13246 * "mapcheck()" function
13248 static void
13249 f_mapcheck(argvars, rettv)
13250 typval_T *argvars;
13251 typval_T *rettv;
13253 get_maparg(argvars, rettv, FALSE);
13256 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
13258 static void
13259 find_some_match(argvars, rettv, type)
13260 typval_T *argvars;
13261 typval_T *rettv;
13262 int type;
13264 char_u *str = NULL;
13265 char_u *expr = NULL;
13266 char_u *pat;
13267 regmatch_T regmatch;
13268 char_u patbuf[NUMBUFLEN];
13269 char_u strbuf[NUMBUFLEN];
13270 char_u *save_cpo;
13271 long start = 0;
13272 long nth = 1;
13273 colnr_T startcol = 0;
13274 int match = 0;
13275 list_T *l = NULL;
13276 listitem_T *li = NULL;
13277 long idx = 0;
13278 char_u *tofree = NULL;
13280 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
13281 save_cpo = p_cpo;
13282 p_cpo = (char_u *)"";
13284 rettv->vval.v_number = -1;
13285 if (type == 3)
13287 /* return empty list when there are no matches */
13288 if (rettv_list_alloc(rettv) == FAIL)
13289 goto theend;
13291 else if (type == 2)
13293 rettv->v_type = VAR_STRING;
13294 rettv->vval.v_string = NULL;
13297 if (argvars[0].v_type == VAR_LIST)
13299 if ((l = argvars[0].vval.v_list) == NULL)
13300 goto theend;
13301 li = l->lv_first;
13303 else
13304 expr = str = get_tv_string(&argvars[0]);
13306 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
13307 if (pat == NULL)
13308 goto theend;
13310 if (argvars[2].v_type != VAR_UNKNOWN)
13312 int error = FALSE;
13314 start = get_tv_number_chk(&argvars[2], &error);
13315 if (error)
13316 goto theend;
13317 if (l != NULL)
13319 li = list_find(l, start);
13320 if (li == NULL)
13321 goto theend;
13322 idx = l->lv_idx; /* use the cached index */
13324 else
13326 if (start < 0)
13327 start = 0;
13328 if (start > (long)STRLEN(str))
13329 goto theend;
13330 /* When "count" argument is there ignore matches before "start",
13331 * otherwise skip part of the string. Differs when pattern is "^"
13332 * or "\<". */
13333 if (argvars[3].v_type != VAR_UNKNOWN)
13334 startcol = start;
13335 else
13336 str += start;
13339 if (argvars[3].v_type != VAR_UNKNOWN)
13340 nth = get_tv_number_chk(&argvars[3], &error);
13341 if (error)
13342 goto theend;
13345 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
13346 if (regmatch.regprog != NULL)
13348 regmatch.rm_ic = p_ic;
13350 for (;;)
13352 if (l != NULL)
13354 if (li == NULL)
13356 match = FALSE;
13357 break;
13359 vim_free(tofree);
13360 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
13361 if (str == NULL)
13362 break;
13365 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
13367 if (match && --nth <= 0)
13368 break;
13369 if (l == NULL && !match)
13370 break;
13372 /* Advance to just after the match. */
13373 if (l != NULL)
13375 li = li->li_next;
13376 ++idx;
13378 else
13380 #ifdef FEAT_MBYTE
13381 startcol = (colnr_T)(regmatch.startp[0]
13382 + (*mb_ptr2len)(regmatch.startp[0]) - str);
13383 #else
13384 startcol = regmatch.startp[0] + 1 - str;
13385 #endif
13389 if (match)
13391 if (type == 3)
13393 int i;
13395 /* return list with matched string and submatches */
13396 for (i = 0; i < NSUBEXP; ++i)
13398 if (regmatch.endp[i] == NULL)
13400 if (list_append_string(rettv->vval.v_list,
13401 (char_u *)"", 0) == FAIL)
13402 break;
13404 else if (list_append_string(rettv->vval.v_list,
13405 regmatch.startp[i],
13406 (int)(regmatch.endp[i] - regmatch.startp[i]))
13407 == FAIL)
13408 break;
13411 else if (type == 2)
13413 /* return matched string */
13414 if (l != NULL)
13415 copy_tv(&li->li_tv, rettv);
13416 else
13417 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
13418 (int)(regmatch.endp[0] - regmatch.startp[0]));
13420 else if (l != NULL)
13421 rettv->vval.v_number = idx;
13422 else
13424 if (type != 0)
13425 rettv->vval.v_number =
13426 (varnumber_T)(regmatch.startp[0] - str);
13427 else
13428 rettv->vval.v_number =
13429 (varnumber_T)(regmatch.endp[0] - str);
13430 rettv->vval.v_number += (varnumber_T)(str - expr);
13433 vim_free(regmatch.regprog);
13436 theend:
13437 vim_free(tofree);
13438 p_cpo = save_cpo;
13442 * "match()" function
13444 static void
13445 f_match(argvars, rettv)
13446 typval_T *argvars;
13447 typval_T *rettv;
13449 find_some_match(argvars, rettv, 1);
13453 * "matchadd()" function
13455 static void
13456 f_matchadd(argvars, rettv)
13457 typval_T *argvars;
13458 typval_T *rettv;
13460 #ifdef FEAT_SEARCH_EXTRA
13461 char_u buf[NUMBUFLEN];
13462 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
13463 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
13464 int prio = 10; /* default priority */
13465 int id = -1;
13466 int error = FALSE;
13468 rettv->vval.v_number = -1;
13470 if (grp == NULL || pat == NULL)
13471 return;
13472 if (argvars[2].v_type != VAR_UNKNOWN)
13474 prio = get_tv_number_chk(&argvars[2], &error);
13475 if (argvars[3].v_type != VAR_UNKNOWN)
13476 id = get_tv_number_chk(&argvars[3], &error);
13478 if (error == TRUE)
13479 return;
13480 if (id >= 1 && id <= 3)
13482 EMSGN("E798: ID is reserved for \":match\": %ld", id);
13483 return;
13486 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
13487 #endif
13491 * "matcharg()" function
13493 static void
13494 f_matcharg(argvars, rettv)
13495 typval_T *argvars;
13496 typval_T *rettv;
13498 if (rettv_list_alloc(rettv) == OK)
13500 #ifdef FEAT_SEARCH_EXTRA
13501 int id = get_tv_number(&argvars[0]);
13502 matchitem_T *m;
13504 if (id >= 1 && id <= 3)
13506 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
13508 list_append_string(rettv->vval.v_list,
13509 syn_id2name(m->hlg_id), -1);
13510 list_append_string(rettv->vval.v_list, m->pattern, -1);
13512 else
13514 list_append_string(rettv->vval.v_list, NUL, -1);
13515 list_append_string(rettv->vval.v_list, NUL, -1);
13518 #endif
13523 * "matchdelete()" function
13525 static void
13526 f_matchdelete(argvars, rettv)
13527 typval_T *argvars;
13528 typval_T *rettv;
13530 #ifdef FEAT_SEARCH_EXTRA
13531 rettv->vval.v_number = match_delete(curwin,
13532 (int)get_tv_number(&argvars[0]), TRUE);
13533 #endif
13537 * "matchend()" function
13539 static void
13540 f_matchend(argvars, rettv)
13541 typval_T *argvars;
13542 typval_T *rettv;
13544 find_some_match(argvars, rettv, 0);
13548 * "matchlist()" function
13550 static void
13551 f_matchlist(argvars, rettv)
13552 typval_T *argvars;
13553 typval_T *rettv;
13555 find_some_match(argvars, rettv, 3);
13559 * "matchstr()" function
13561 static void
13562 f_matchstr(argvars, rettv)
13563 typval_T *argvars;
13564 typval_T *rettv;
13566 find_some_match(argvars, rettv, 2);
13569 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
13571 static void
13572 max_min(argvars, rettv, domax)
13573 typval_T *argvars;
13574 typval_T *rettv;
13575 int domax;
13577 long n = 0;
13578 long i;
13579 int error = FALSE;
13581 if (argvars[0].v_type == VAR_LIST)
13583 list_T *l;
13584 listitem_T *li;
13586 l = argvars[0].vval.v_list;
13587 if (l != NULL)
13589 li = l->lv_first;
13590 if (li != NULL)
13592 n = get_tv_number_chk(&li->li_tv, &error);
13593 for (;;)
13595 li = li->li_next;
13596 if (li == NULL)
13597 break;
13598 i = get_tv_number_chk(&li->li_tv, &error);
13599 if (domax ? i > n : i < n)
13600 n = i;
13605 else if (argvars[0].v_type == VAR_DICT)
13607 dict_T *d;
13608 int first = TRUE;
13609 hashitem_T *hi;
13610 int todo;
13612 d = argvars[0].vval.v_dict;
13613 if (d != NULL)
13615 todo = (int)d->dv_hashtab.ht_used;
13616 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13618 if (!HASHITEM_EMPTY(hi))
13620 --todo;
13621 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
13622 if (first)
13624 n = i;
13625 first = FALSE;
13627 else if (domax ? i > n : i < n)
13628 n = i;
13633 else
13634 EMSG(_(e_listdictarg));
13635 rettv->vval.v_number = error ? 0 : n;
13639 * "max()" function
13641 static void
13642 f_max(argvars, rettv)
13643 typval_T *argvars;
13644 typval_T *rettv;
13646 max_min(argvars, rettv, TRUE);
13650 * "min()" function
13652 static void
13653 f_min(argvars, rettv)
13654 typval_T *argvars;
13655 typval_T *rettv;
13657 max_min(argvars, rettv, FALSE);
13660 static int mkdir_recurse __ARGS((char_u *dir, int prot));
13663 * Create the directory in which "dir" is located, and higher levels when
13664 * needed.
13666 static int
13667 mkdir_recurse(dir, prot)
13668 char_u *dir;
13669 int prot;
13671 char_u *p;
13672 char_u *updir;
13673 int r = FAIL;
13675 /* Get end of directory name in "dir".
13676 * We're done when it's "/" or "c:/". */
13677 p = gettail_sep(dir);
13678 if (p <= get_past_head(dir))
13679 return OK;
13681 /* If the directory exists we're done. Otherwise: create it.*/
13682 updir = vim_strnsave(dir, (int)(p - dir));
13683 if (updir == NULL)
13684 return FAIL;
13685 if (mch_isdir(updir))
13686 r = OK;
13687 else if (mkdir_recurse(updir, prot) == OK)
13688 r = vim_mkdir_emsg(updir, prot);
13689 vim_free(updir);
13690 return r;
13693 #ifdef vim_mkdir
13695 * "mkdir()" function
13697 static void
13698 f_mkdir(argvars, rettv)
13699 typval_T *argvars;
13700 typval_T *rettv;
13702 char_u *dir;
13703 char_u buf[NUMBUFLEN];
13704 int prot = 0755;
13706 rettv->vval.v_number = FAIL;
13707 if (check_restricted() || check_secure())
13708 return;
13710 dir = get_tv_string_buf(&argvars[0], buf);
13711 if (argvars[1].v_type != VAR_UNKNOWN)
13713 if (argvars[2].v_type != VAR_UNKNOWN)
13714 prot = get_tv_number_chk(&argvars[2], NULL);
13715 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
13716 mkdir_recurse(dir, prot);
13718 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
13720 #endif
13723 * "mode()" function
13725 static void
13726 f_mode(argvars, rettv)
13727 typval_T *argvars;
13728 typval_T *rettv;
13730 char_u buf[3];
13732 buf[1] = NUL;
13733 buf[2] = NUL;
13735 #ifdef FEAT_VISUAL
13736 if (VIsual_active)
13738 if (VIsual_select)
13739 buf[0] = VIsual_mode + 's' - 'v';
13740 else
13741 buf[0] = VIsual_mode;
13743 else
13744 #endif
13745 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
13746 || State == CONFIRM)
13748 buf[0] = 'r';
13749 if (State == ASKMORE)
13750 buf[1] = 'm';
13751 else if (State == CONFIRM)
13752 buf[1] = '?';
13754 else if (State == EXTERNCMD)
13755 buf[0] = '!';
13756 else if (State & INSERT)
13758 #ifdef FEAT_VREPLACE
13759 if (State & VREPLACE_FLAG)
13761 buf[0] = 'R';
13762 buf[1] = 'v';
13764 else
13765 #endif
13766 if (State & REPLACE_FLAG)
13767 buf[0] = 'R';
13768 else
13769 buf[0] = 'i';
13771 else if (State & CMDLINE)
13773 buf[0] = 'c';
13774 if (exmode_active)
13775 buf[1] = 'v';
13777 else if (exmode_active)
13779 buf[0] = 'c';
13780 buf[1] = 'e';
13782 else
13784 buf[0] = 'n';
13785 if (finish_op)
13786 buf[1] = 'o';
13789 /* Clear out the minor mode when the argument is not a non-zero number or
13790 * non-empty string. */
13791 if (!non_zero_arg(&argvars[0]))
13792 buf[1] = NUL;
13794 rettv->vval.v_string = vim_strsave(buf);
13795 rettv->v_type = VAR_STRING;
13798 #ifdef FEAT_MZSCHEME
13800 * "mzeval()" function
13802 static void
13803 f_mzeval(argvars, rettv)
13804 typval_T *argvars;
13805 typval_T *rettv;
13807 char_u *str;
13808 char_u buf[NUMBUFLEN];
13810 str = get_tv_string_buf(&argvars[0], buf);
13811 do_mzeval(str, rettv);
13813 #endif
13816 * "nextnonblank()" function
13818 static void
13819 f_nextnonblank(argvars, rettv)
13820 typval_T *argvars;
13821 typval_T *rettv;
13823 linenr_T lnum;
13825 for (lnum = get_tv_lnum(argvars); ; ++lnum)
13827 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
13829 lnum = 0;
13830 break;
13832 if (*skipwhite(ml_get(lnum)) != NUL)
13833 break;
13835 rettv->vval.v_number = lnum;
13839 * "nr2char()" function
13841 static void
13842 f_nr2char(argvars, rettv)
13843 typval_T *argvars;
13844 typval_T *rettv;
13846 char_u buf[NUMBUFLEN];
13848 #ifdef FEAT_MBYTE
13849 if (has_mbyte)
13850 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
13851 else
13852 #endif
13854 buf[0] = (char_u)get_tv_number(&argvars[0]);
13855 buf[1] = NUL;
13857 rettv->v_type = VAR_STRING;
13858 rettv->vval.v_string = vim_strsave(buf);
13862 * "pathshorten()" function
13864 static void
13865 f_pathshorten(argvars, rettv)
13866 typval_T *argvars;
13867 typval_T *rettv;
13869 char_u *p;
13871 rettv->v_type = VAR_STRING;
13872 p = get_tv_string_chk(&argvars[0]);
13873 if (p == NULL)
13874 rettv->vval.v_string = NULL;
13875 else
13877 p = vim_strsave(p);
13878 rettv->vval.v_string = p;
13879 if (p != NULL)
13880 shorten_dir(p);
13884 #ifdef FEAT_FLOAT
13886 * "pow()" function
13888 static void
13889 f_pow(argvars, rettv)
13890 typval_T *argvars;
13891 typval_T *rettv;
13893 float_T fx, fy;
13895 rettv->v_type = VAR_FLOAT;
13896 if (get_float_arg(argvars, &fx) == OK
13897 && get_float_arg(&argvars[1], &fy) == OK)
13898 rettv->vval.v_float = pow(fx, fy);
13899 else
13900 rettv->vval.v_float = 0.0;
13902 #endif
13905 * "prevnonblank()" function
13907 static void
13908 f_prevnonblank(argvars, rettv)
13909 typval_T *argvars;
13910 typval_T *rettv;
13912 linenr_T lnum;
13914 lnum = get_tv_lnum(argvars);
13915 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
13916 lnum = 0;
13917 else
13918 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
13919 --lnum;
13920 rettv->vval.v_number = lnum;
13923 #ifdef HAVE_STDARG_H
13924 /* This dummy va_list is here because:
13925 * - passing a NULL pointer doesn't work when va_list isn't a pointer
13926 * - locally in the function results in a "used before set" warning
13927 * - using va_start() to initialize it gives "function with fixed args" error */
13928 static va_list ap;
13929 #endif
13932 * "printf()" function
13934 static void
13935 f_printf(argvars, rettv)
13936 typval_T *argvars;
13937 typval_T *rettv;
13939 rettv->v_type = VAR_STRING;
13940 rettv->vval.v_string = NULL;
13941 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
13943 char_u buf[NUMBUFLEN];
13944 int len;
13945 char_u *s;
13946 int saved_did_emsg = did_emsg;
13947 char *fmt;
13949 /* Get the required length, allocate the buffer and do it for real. */
13950 did_emsg = FALSE;
13951 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
13952 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
13953 if (!did_emsg)
13955 s = alloc(len + 1);
13956 if (s != NULL)
13958 rettv->vval.v_string = s;
13959 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
13962 did_emsg |= saved_did_emsg;
13964 #endif
13968 * "pumvisible()" function
13970 static void
13971 f_pumvisible(argvars, rettv)
13972 typval_T *argvars UNUSED;
13973 typval_T *rettv UNUSED;
13975 #ifdef FEAT_INS_EXPAND
13976 if (pum_visible())
13977 rettv->vval.v_number = 1;
13978 #endif
13982 * "range()" function
13984 static void
13985 f_range(argvars, rettv)
13986 typval_T *argvars;
13987 typval_T *rettv;
13989 long start;
13990 long end;
13991 long stride = 1;
13992 long i;
13993 int error = FALSE;
13995 start = get_tv_number_chk(&argvars[0], &error);
13996 if (argvars[1].v_type == VAR_UNKNOWN)
13998 end = start - 1;
13999 start = 0;
14001 else
14003 end = get_tv_number_chk(&argvars[1], &error);
14004 if (argvars[2].v_type != VAR_UNKNOWN)
14005 stride = get_tv_number_chk(&argvars[2], &error);
14008 if (error)
14009 return; /* type error; errmsg already given */
14010 if (stride == 0)
14011 EMSG(_("E726: Stride is zero"));
14012 else if (stride > 0 ? end + 1 < start : end - 1 > start)
14013 EMSG(_("E727: Start past end"));
14014 else
14016 if (rettv_list_alloc(rettv) == OK)
14017 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
14018 if (list_append_number(rettv->vval.v_list,
14019 (varnumber_T)i) == FAIL)
14020 break;
14025 * "readfile()" function
14027 static void
14028 f_readfile(argvars, rettv)
14029 typval_T *argvars;
14030 typval_T *rettv;
14032 int binary = FALSE;
14033 char_u *fname;
14034 FILE *fd;
14035 listitem_T *li;
14036 #define FREAD_SIZE 200 /* optimized for text lines */
14037 char_u buf[FREAD_SIZE];
14038 int readlen; /* size of last fread() */
14039 int buflen; /* nr of valid chars in buf[] */
14040 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
14041 int tolist; /* first byte in buf[] still to be put in list */
14042 int chop; /* how many CR to chop off */
14043 char_u *prev = NULL; /* previously read bytes, if any */
14044 int prevlen = 0; /* length of "prev" if not NULL */
14045 char_u *s;
14046 int len;
14047 long maxline = MAXLNUM;
14048 long cnt = 0;
14050 if (argvars[1].v_type != VAR_UNKNOWN)
14052 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
14053 binary = TRUE;
14054 if (argvars[2].v_type != VAR_UNKNOWN)
14055 maxline = get_tv_number(&argvars[2]);
14058 if (rettv_list_alloc(rettv) == FAIL)
14059 return;
14061 /* Always open the file in binary mode, library functions have a mind of
14062 * their own about CR-LF conversion. */
14063 fname = get_tv_string(&argvars[0]);
14064 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
14066 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
14067 return;
14070 filtd = 0;
14071 while (cnt < maxline || maxline < 0)
14073 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
14074 buflen = filtd + readlen;
14075 tolist = 0;
14076 for ( ; filtd < buflen || readlen <= 0; ++filtd)
14078 if (buf[filtd] == '\n' || readlen <= 0)
14080 /* Only when in binary mode add an empty list item when the
14081 * last line ends in a '\n'. */
14082 if (!binary && readlen == 0 && filtd == 0)
14083 break;
14085 /* Found end-of-line or end-of-file: add a text line to the
14086 * list. */
14087 chop = 0;
14088 if (!binary)
14089 while (filtd - chop - 1 >= tolist
14090 && buf[filtd - chop - 1] == '\r')
14091 ++chop;
14092 len = filtd - tolist - chop;
14093 if (prev == NULL)
14094 s = vim_strnsave(buf + tolist, len);
14095 else
14097 s = alloc((unsigned)(prevlen + len + 1));
14098 if (s != NULL)
14100 mch_memmove(s, prev, prevlen);
14101 vim_free(prev);
14102 prev = NULL;
14103 mch_memmove(s + prevlen, buf + tolist, len);
14104 s[prevlen + len] = NUL;
14107 tolist = filtd + 1;
14109 li = listitem_alloc();
14110 if (li == NULL)
14112 vim_free(s);
14113 break;
14115 li->li_tv.v_type = VAR_STRING;
14116 li->li_tv.v_lock = 0;
14117 li->li_tv.vval.v_string = s;
14118 list_append(rettv->vval.v_list, li);
14120 if (++cnt >= maxline && maxline >= 0)
14121 break;
14122 if (readlen <= 0)
14123 break;
14125 else if (buf[filtd] == NUL)
14126 buf[filtd] = '\n';
14128 if (readlen <= 0)
14129 break;
14131 if (tolist == 0)
14133 /* "buf" is full, need to move text to an allocated buffer */
14134 if (prev == NULL)
14136 prev = vim_strnsave(buf, buflen);
14137 prevlen = buflen;
14139 else
14141 s = alloc((unsigned)(prevlen + buflen));
14142 if (s != NULL)
14144 mch_memmove(s, prev, prevlen);
14145 mch_memmove(s + prevlen, buf, buflen);
14146 vim_free(prev);
14147 prev = s;
14148 prevlen += buflen;
14151 filtd = 0;
14153 else
14155 mch_memmove(buf, buf + tolist, buflen - tolist);
14156 filtd -= tolist;
14161 * For a negative line count use only the lines at the end of the file,
14162 * free the rest.
14164 if (maxline < 0)
14165 while (cnt > -maxline)
14167 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
14168 --cnt;
14171 vim_free(prev);
14172 fclose(fd);
14175 #if defined(FEAT_RELTIME)
14176 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
14179 * Convert a List to proftime_T.
14180 * Return FAIL when there is something wrong.
14182 static int
14183 list2proftime(arg, tm)
14184 typval_T *arg;
14185 proftime_T *tm;
14187 long n1, n2;
14188 int error = FALSE;
14190 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
14191 || arg->vval.v_list->lv_len != 2)
14192 return FAIL;
14193 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
14194 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
14195 # ifdef WIN3264
14196 tm->HighPart = n1;
14197 tm->LowPart = n2;
14198 # else
14199 tm->tv_sec = n1;
14200 tm->tv_usec = n2;
14201 # endif
14202 return error ? FAIL : OK;
14204 #endif /* FEAT_RELTIME */
14207 * "reltime()" function
14209 static void
14210 f_reltime(argvars, rettv)
14211 typval_T *argvars;
14212 typval_T *rettv;
14214 #ifdef FEAT_RELTIME
14215 proftime_T res;
14216 proftime_T start;
14218 if (argvars[0].v_type == VAR_UNKNOWN)
14220 /* No arguments: get current time. */
14221 profile_start(&res);
14223 else if (argvars[1].v_type == VAR_UNKNOWN)
14225 if (list2proftime(&argvars[0], &res) == FAIL)
14226 return;
14227 profile_end(&res);
14229 else
14231 /* Two arguments: compute the difference. */
14232 if (list2proftime(&argvars[0], &start) == FAIL
14233 || list2proftime(&argvars[1], &res) == FAIL)
14234 return;
14235 profile_sub(&res, &start);
14238 if (rettv_list_alloc(rettv) == OK)
14240 long n1, n2;
14242 # ifdef WIN3264
14243 n1 = res.HighPart;
14244 n2 = res.LowPart;
14245 # else
14246 n1 = res.tv_sec;
14247 n2 = res.tv_usec;
14248 # endif
14249 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
14250 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
14252 #endif
14256 * "reltimestr()" function
14258 static void
14259 f_reltimestr(argvars, rettv)
14260 typval_T *argvars;
14261 typval_T *rettv;
14263 #ifdef FEAT_RELTIME
14264 proftime_T tm;
14265 #endif
14267 rettv->v_type = VAR_STRING;
14268 rettv->vval.v_string = NULL;
14269 #ifdef FEAT_RELTIME
14270 if (list2proftime(&argvars[0], &tm) == OK)
14271 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
14272 #endif
14275 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
14276 static void make_connection __ARGS((void));
14277 static int check_connection __ARGS((void));
14279 static void
14280 make_connection()
14282 if (X_DISPLAY == NULL
14283 # ifdef FEAT_GUI
14284 && !gui.in_use
14285 # endif
14288 x_force_connect = TRUE;
14289 setup_term_clip();
14290 x_force_connect = FALSE;
14294 static int
14295 check_connection()
14297 make_connection();
14298 if (X_DISPLAY == NULL)
14300 EMSG(_("E240: No connection to Vim server"));
14301 return FAIL;
14303 return OK;
14305 #endif
14307 #ifdef FEAT_CLIENTSERVER
14308 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
14310 static void
14311 remote_common(argvars, rettv, expr)
14312 typval_T *argvars;
14313 typval_T *rettv;
14314 int expr;
14316 char_u *server_name;
14317 char_u *keys;
14318 char_u *r = NULL;
14319 char_u buf[NUMBUFLEN];
14320 # ifdef WIN32
14321 HWND w;
14322 # else
14323 Window w;
14324 # endif
14326 if (check_restricted() || check_secure())
14327 return;
14329 # ifdef FEAT_X11
14330 if (check_connection() == FAIL)
14331 return;
14332 # endif
14334 server_name = get_tv_string_chk(&argvars[0]);
14335 if (server_name == NULL)
14336 return; /* type error; errmsg already given */
14337 keys = get_tv_string_buf(&argvars[1], buf);
14338 # ifdef WIN32
14339 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14340 # else
14341 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
14342 < 0)
14343 # endif
14345 if (r != NULL)
14346 EMSG(r); /* sending worked but evaluation failed */
14347 else
14348 EMSG2(_("E241: Unable to send to %s"), server_name);
14349 return;
14352 rettv->vval.v_string = r;
14354 if (argvars[2].v_type != VAR_UNKNOWN)
14356 dictitem_T v;
14357 char_u str[30];
14358 char_u *idvar;
14360 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
14361 v.di_tv.v_type = VAR_STRING;
14362 v.di_tv.vval.v_string = vim_strsave(str);
14363 idvar = get_tv_string_chk(&argvars[2]);
14364 if (idvar != NULL)
14365 set_var(idvar, &v.di_tv, FALSE);
14366 vim_free(v.di_tv.vval.v_string);
14369 #endif
14372 * "remote_expr()" function
14374 static void
14375 f_remote_expr(argvars, rettv)
14376 typval_T *argvars UNUSED;
14377 typval_T *rettv;
14379 rettv->v_type = VAR_STRING;
14380 rettv->vval.v_string = NULL;
14381 #ifdef FEAT_CLIENTSERVER
14382 remote_common(argvars, rettv, TRUE);
14383 #endif
14387 * "remote_foreground()" function
14389 static void
14390 f_remote_foreground(argvars, rettv)
14391 typval_T *argvars UNUSED;
14392 typval_T *rettv UNUSED;
14394 #ifdef FEAT_CLIENTSERVER
14395 # ifdef WIN32
14396 /* On Win32 it's done in this application. */
14398 char_u *server_name = get_tv_string_chk(&argvars[0]);
14400 if (server_name != NULL)
14401 serverForeground(server_name);
14403 # else
14404 /* Send a foreground() expression to the server. */
14405 argvars[1].v_type = VAR_STRING;
14406 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
14407 argvars[2].v_type = VAR_UNKNOWN;
14408 remote_common(argvars, rettv, TRUE);
14409 vim_free(argvars[1].vval.v_string);
14410 # endif
14411 #endif
14414 static void
14415 f_remote_peek(argvars, rettv)
14416 typval_T *argvars UNUSED;
14417 typval_T *rettv;
14419 #ifdef FEAT_CLIENTSERVER
14420 dictitem_T v;
14421 char_u *s = NULL;
14422 # ifdef WIN32
14423 long_u n = 0;
14424 # endif
14425 char_u *serverid;
14427 if (check_restricted() || check_secure())
14429 rettv->vval.v_number = -1;
14430 return;
14432 serverid = get_tv_string_chk(&argvars[0]);
14433 if (serverid == NULL)
14435 rettv->vval.v_number = -1;
14436 return; /* type error; errmsg already given */
14438 # ifdef WIN32
14439 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14440 if (n == 0)
14441 rettv->vval.v_number = -1;
14442 else
14444 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
14445 rettv->vval.v_number = (s != NULL);
14447 # else
14448 if (check_connection() == FAIL)
14449 return;
14451 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
14452 serverStrToWin(serverid), &s);
14453 # endif
14455 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
14457 char_u *retvar;
14459 v.di_tv.v_type = VAR_STRING;
14460 v.di_tv.vval.v_string = vim_strsave(s);
14461 retvar = get_tv_string_chk(&argvars[1]);
14462 if (retvar != NULL)
14463 set_var(retvar, &v.di_tv, FALSE);
14464 vim_free(v.di_tv.vval.v_string);
14466 #else
14467 rettv->vval.v_number = -1;
14468 #endif
14471 static void
14472 f_remote_read(argvars, rettv)
14473 typval_T *argvars UNUSED;
14474 typval_T *rettv;
14476 char_u *r = NULL;
14478 #ifdef FEAT_CLIENTSERVER
14479 char_u *serverid = get_tv_string_chk(&argvars[0]);
14481 if (serverid != NULL && !check_restricted() && !check_secure())
14483 # ifdef WIN32
14484 /* The server's HWND is encoded in the 'id' parameter */
14485 long_u n = 0;
14487 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14488 if (n != 0)
14489 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
14490 if (r == NULL)
14491 # else
14492 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
14493 serverStrToWin(serverid), &r, FALSE) < 0)
14494 # endif
14495 EMSG(_("E277: Unable to read a server reply"));
14497 #endif
14498 rettv->v_type = VAR_STRING;
14499 rettv->vval.v_string = r;
14503 * "remote_send()" function
14505 static void
14506 f_remote_send(argvars, rettv)
14507 typval_T *argvars UNUSED;
14508 typval_T *rettv;
14510 rettv->v_type = VAR_STRING;
14511 rettv->vval.v_string = NULL;
14512 #ifdef FEAT_CLIENTSERVER
14513 remote_common(argvars, rettv, FALSE);
14514 #endif
14518 * "remove()" function
14520 static void
14521 f_remove(argvars, rettv)
14522 typval_T *argvars;
14523 typval_T *rettv;
14525 list_T *l;
14526 listitem_T *item, *item2;
14527 listitem_T *li;
14528 long idx;
14529 long end;
14530 char_u *key;
14531 dict_T *d;
14532 dictitem_T *di;
14534 if (argvars[0].v_type == VAR_DICT)
14536 if (argvars[2].v_type != VAR_UNKNOWN)
14537 EMSG2(_(e_toomanyarg), "remove()");
14538 else if ((d = argvars[0].vval.v_dict) != NULL
14539 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
14541 key = get_tv_string_chk(&argvars[1]);
14542 if (key != NULL)
14544 di = dict_find(d, key, -1);
14545 if (di == NULL)
14546 EMSG2(_(e_dictkey), key);
14547 else
14549 *rettv = di->di_tv;
14550 init_tv(&di->di_tv);
14551 dictitem_remove(d, di);
14556 else if (argvars[0].v_type != VAR_LIST)
14557 EMSG2(_(e_listdictarg), "remove()");
14558 else if ((l = argvars[0].vval.v_list) != NULL
14559 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
14561 int error = FALSE;
14563 idx = get_tv_number_chk(&argvars[1], &error);
14564 if (error)
14565 ; /* type error: do nothing, errmsg already given */
14566 else if ((item = list_find(l, idx)) == NULL)
14567 EMSGN(_(e_listidx), idx);
14568 else
14570 if (argvars[2].v_type == VAR_UNKNOWN)
14572 /* Remove one item, return its value. */
14573 list_remove(l, item, item);
14574 *rettv = item->li_tv;
14575 vim_free(item);
14577 else
14579 /* Remove range of items, return list with values. */
14580 end = get_tv_number_chk(&argvars[2], &error);
14581 if (error)
14582 ; /* type error: do nothing */
14583 else if ((item2 = list_find(l, end)) == NULL)
14584 EMSGN(_(e_listidx), end);
14585 else
14587 int cnt = 0;
14589 for (li = item; li != NULL; li = li->li_next)
14591 ++cnt;
14592 if (li == item2)
14593 break;
14595 if (li == NULL) /* didn't find "item2" after "item" */
14596 EMSG(_(e_invrange));
14597 else
14599 list_remove(l, item, item2);
14600 if (rettv_list_alloc(rettv) == OK)
14602 l = rettv->vval.v_list;
14603 l->lv_first = item;
14604 l->lv_last = item2;
14605 item->li_prev = NULL;
14606 item2->li_next = NULL;
14607 l->lv_len = cnt;
14617 * "rename({from}, {to})" function
14619 static void
14620 f_rename(argvars, rettv)
14621 typval_T *argvars;
14622 typval_T *rettv;
14624 char_u buf[NUMBUFLEN];
14626 if (check_restricted() || check_secure())
14627 rettv->vval.v_number = -1;
14628 else
14629 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
14630 get_tv_string_buf(&argvars[1], buf));
14634 * "repeat()" function
14636 static void
14637 f_repeat(argvars, rettv)
14638 typval_T *argvars;
14639 typval_T *rettv;
14641 char_u *p;
14642 int n;
14643 int slen;
14644 int len;
14645 char_u *r;
14646 int i;
14648 n = get_tv_number(&argvars[1]);
14649 if (argvars[0].v_type == VAR_LIST)
14651 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
14652 while (n-- > 0)
14653 if (list_extend(rettv->vval.v_list,
14654 argvars[0].vval.v_list, NULL) == FAIL)
14655 break;
14657 else
14659 p = get_tv_string(&argvars[0]);
14660 rettv->v_type = VAR_STRING;
14661 rettv->vval.v_string = NULL;
14663 slen = (int)STRLEN(p);
14664 len = slen * n;
14665 if (len <= 0)
14666 return;
14668 r = alloc(len + 1);
14669 if (r != NULL)
14671 for (i = 0; i < n; i++)
14672 mch_memmove(r + i * slen, p, (size_t)slen);
14673 r[len] = NUL;
14676 rettv->vval.v_string = r;
14681 * "resolve()" function
14683 static void
14684 f_resolve(argvars, rettv)
14685 typval_T *argvars;
14686 typval_T *rettv;
14688 char_u *p;
14690 p = get_tv_string(&argvars[0]);
14691 #ifdef FEAT_SHORTCUT
14693 char_u *v = NULL;
14695 v = mch_resolve_shortcut(p);
14696 if (v != NULL)
14697 rettv->vval.v_string = v;
14698 else
14699 rettv->vval.v_string = vim_strsave(p);
14701 #else
14702 # ifdef HAVE_READLINK
14704 char_u buf[MAXPATHL + 1];
14705 char_u *cpy;
14706 int len;
14707 char_u *remain = NULL;
14708 char_u *q;
14709 int is_relative_to_current = FALSE;
14710 int has_trailing_pathsep = FALSE;
14711 int limit = 100;
14713 p = vim_strsave(p);
14715 if (p[0] == '.' && (vim_ispathsep(p[1])
14716 || (p[1] == '.' && (vim_ispathsep(p[2])))))
14717 is_relative_to_current = TRUE;
14719 len = STRLEN(p);
14720 if (len > 0 && after_pathsep(p, p + len))
14721 has_trailing_pathsep = TRUE;
14723 q = getnextcomp(p);
14724 if (*q != NUL)
14726 /* Separate the first path component in "p", and keep the
14727 * remainder (beginning with the path separator). */
14728 remain = vim_strsave(q - 1);
14729 q[-1] = NUL;
14732 for (;;)
14734 for (;;)
14736 len = readlink((char *)p, (char *)buf, MAXPATHL);
14737 if (len <= 0)
14738 break;
14739 buf[len] = NUL;
14741 if (limit-- == 0)
14743 vim_free(p);
14744 vim_free(remain);
14745 EMSG(_("E655: Too many symbolic links (cycle?)"));
14746 rettv->vval.v_string = NULL;
14747 goto fail;
14750 /* Ensure that the result will have a trailing path separator
14751 * if the argument has one. */
14752 if (remain == NULL && has_trailing_pathsep)
14753 add_pathsep(buf);
14755 /* Separate the first path component in the link value and
14756 * concatenate the remainders. */
14757 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
14758 if (*q != NUL)
14760 if (remain == NULL)
14761 remain = vim_strsave(q - 1);
14762 else
14764 cpy = concat_str(q - 1, remain);
14765 if (cpy != NULL)
14767 vim_free(remain);
14768 remain = cpy;
14771 q[-1] = NUL;
14774 q = gettail(p);
14775 if (q > p && *q == NUL)
14777 /* Ignore trailing path separator. */
14778 q[-1] = NUL;
14779 q = gettail(p);
14781 if (q > p && !mch_isFullName(buf))
14783 /* symlink is relative to directory of argument */
14784 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
14785 if (cpy != NULL)
14787 STRCPY(cpy, p);
14788 STRCPY(gettail(cpy), buf);
14789 vim_free(p);
14790 p = cpy;
14793 else
14795 vim_free(p);
14796 p = vim_strsave(buf);
14800 if (remain == NULL)
14801 break;
14803 /* Append the first path component of "remain" to "p". */
14804 q = getnextcomp(remain + 1);
14805 len = q - remain - (*q != NUL);
14806 cpy = vim_strnsave(p, STRLEN(p) + len);
14807 if (cpy != NULL)
14809 STRNCAT(cpy, remain, len);
14810 vim_free(p);
14811 p = cpy;
14813 /* Shorten "remain". */
14814 if (*q != NUL)
14815 STRMOVE(remain, q - 1);
14816 else
14818 vim_free(remain);
14819 remain = NULL;
14823 /* If the result is a relative path name, make it explicitly relative to
14824 * the current directory if and only if the argument had this form. */
14825 if (!vim_ispathsep(*p))
14827 if (is_relative_to_current
14828 && *p != NUL
14829 && !(p[0] == '.'
14830 && (p[1] == NUL
14831 || vim_ispathsep(p[1])
14832 || (p[1] == '.'
14833 && (p[2] == NUL
14834 || vim_ispathsep(p[2]))))))
14836 /* Prepend "./". */
14837 cpy = concat_str((char_u *)"./", p);
14838 if (cpy != NULL)
14840 vim_free(p);
14841 p = cpy;
14844 else if (!is_relative_to_current)
14846 /* Strip leading "./". */
14847 q = p;
14848 while (q[0] == '.' && vim_ispathsep(q[1]))
14849 q += 2;
14850 if (q > p)
14851 STRMOVE(p, p + 2);
14855 /* Ensure that the result will have no trailing path separator
14856 * if the argument had none. But keep "/" or "//". */
14857 if (!has_trailing_pathsep)
14859 q = p + STRLEN(p);
14860 if (after_pathsep(p, q))
14861 *gettail_sep(p) = NUL;
14864 rettv->vval.v_string = p;
14866 # else
14867 rettv->vval.v_string = vim_strsave(p);
14868 # endif
14869 #endif
14871 simplify_filename(rettv->vval.v_string);
14873 #ifdef HAVE_READLINK
14874 fail:
14875 #endif
14876 rettv->v_type = VAR_STRING;
14880 * "reverse({list})" function
14882 static void
14883 f_reverse(argvars, rettv)
14884 typval_T *argvars;
14885 typval_T *rettv;
14887 list_T *l;
14888 listitem_T *li, *ni;
14890 if (argvars[0].v_type != VAR_LIST)
14891 EMSG2(_(e_listarg), "reverse()");
14892 else if ((l = argvars[0].vval.v_list) != NULL
14893 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
14895 li = l->lv_last;
14896 l->lv_first = l->lv_last = NULL;
14897 l->lv_len = 0;
14898 while (li != NULL)
14900 ni = li->li_prev;
14901 list_append(l, li);
14902 li = ni;
14904 rettv->vval.v_list = l;
14905 rettv->v_type = VAR_LIST;
14906 ++l->lv_refcount;
14907 l->lv_idx = l->lv_len - l->lv_idx - 1;
14911 #define SP_NOMOVE 0x01 /* don't move cursor */
14912 #define SP_REPEAT 0x02 /* repeat to find outer pair */
14913 #define SP_RETCOUNT 0x04 /* return matchcount */
14914 #define SP_SETPCMARK 0x08 /* set previous context mark */
14915 #define SP_START 0x10 /* accept match at start position */
14916 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
14917 #define SP_END 0x40 /* leave cursor at end of match */
14919 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
14922 * Get flags for a search function.
14923 * Possibly sets "p_ws".
14924 * Returns BACKWARD, FORWARD or zero (for an error).
14926 static int
14927 get_search_arg(varp, flagsp)
14928 typval_T *varp;
14929 int *flagsp;
14931 int dir = FORWARD;
14932 char_u *flags;
14933 char_u nbuf[NUMBUFLEN];
14934 int mask;
14936 if (varp->v_type != VAR_UNKNOWN)
14938 flags = get_tv_string_buf_chk(varp, nbuf);
14939 if (flags == NULL)
14940 return 0; /* type error; errmsg already given */
14941 while (*flags != NUL)
14943 switch (*flags)
14945 case 'b': dir = BACKWARD; break;
14946 case 'w': p_ws = TRUE; break;
14947 case 'W': p_ws = FALSE; break;
14948 default: mask = 0;
14949 if (flagsp != NULL)
14950 switch (*flags)
14952 case 'c': mask = SP_START; break;
14953 case 'e': mask = SP_END; break;
14954 case 'm': mask = SP_RETCOUNT; break;
14955 case 'n': mask = SP_NOMOVE; break;
14956 case 'p': mask = SP_SUBPAT; break;
14957 case 'r': mask = SP_REPEAT; break;
14958 case 's': mask = SP_SETPCMARK; break;
14960 if (mask == 0)
14962 EMSG2(_(e_invarg2), flags);
14963 dir = 0;
14965 else
14966 *flagsp |= mask;
14968 if (dir == 0)
14969 break;
14970 ++flags;
14973 return dir;
14977 * Shared by search() and searchpos() functions
14979 static int
14980 search_cmn(argvars, match_pos, flagsp)
14981 typval_T *argvars;
14982 pos_T *match_pos;
14983 int *flagsp;
14985 int flags;
14986 char_u *pat;
14987 pos_T pos;
14988 pos_T save_cursor;
14989 int save_p_ws = p_ws;
14990 int dir;
14991 int retval = 0; /* default: FAIL */
14992 long lnum_stop = 0;
14993 proftime_T tm;
14994 #ifdef FEAT_RELTIME
14995 long time_limit = 0;
14996 #endif
14997 int options = SEARCH_KEEP;
14998 int subpatnum;
15000 pat = get_tv_string(&argvars[0]);
15001 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
15002 if (dir == 0)
15003 goto theend;
15004 flags = *flagsp;
15005 if (flags & SP_START)
15006 options |= SEARCH_START;
15007 if (flags & SP_END)
15008 options |= SEARCH_END;
15010 /* Optional arguments: line number to stop searching and timeout. */
15011 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
15013 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
15014 if (lnum_stop < 0)
15015 goto theend;
15016 #ifdef FEAT_RELTIME
15017 if (argvars[3].v_type != VAR_UNKNOWN)
15019 time_limit = get_tv_number_chk(&argvars[3], NULL);
15020 if (time_limit < 0)
15021 goto theend;
15023 #endif
15026 #ifdef FEAT_RELTIME
15027 /* Set the time limit, if there is one. */
15028 profile_setlimit(time_limit, &tm);
15029 #endif
15032 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
15033 * Check to make sure only those flags are set.
15034 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
15035 * flags cannot be set. Check for that condition also.
15037 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
15038 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
15040 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
15041 goto theend;
15044 pos = save_cursor = curwin->w_cursor;
15045 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15046 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
15047 if (subpatnum != FAIL)
15049 if (flags & SP_SUBPAT)
15050 retval = subpatnum;
15051 else
15052 retval = pos.lnum;
15053 if (flags & SP_SETPCMARK)
15054 setpcmark();
15055 curwin->w_cursor = pos;
15056 if (match_pos != NULL)
15058 /* Store the match cursor position */
15059 match_pos->lnum = pos.lnum;
15060 match_pos->col = pos.col + 1;
15062 /* "/$" will put the cursor after the end of the line, may need to
15063 * correct that here */
15064 check_cursor();
15067 /* If 'n' flag is used: restore cursor position. */
15068 if (flags & SP_NOMOVE)
15069 curwin->w_cursor = save_cursor;
15070 else
15071 curwin->w_set_curswant = TRUE;
15072 theend:
15073 p_ws = save_p_ws;
15075 return retval;
15078 #ifdef FEAT_FLOAT
15080 * "round({float})" function
15082 static void
15083 f_round(argvars, rettv)
15084 typval_T *argvars;
15085 typval_T *rettv;
15087 float_T f;
15089 rettv->v_type = VAR_FLOAT;
15090 if (get_float_arg(argvars, &f) == OK)
15091 /* round() is not in C90, use ceil() or floor() instead. */
15092 rettv->vval.v_float = f > 0 ? floor(f + 0.5) : ceil(f - 0.5);
15093 else
15094 rettv->vval.v_float = 0.0;
15096 #endif
15099 * "search()" function
15101 static void
15102 f_search(argvars, rettv)
15103 typval_T *argvars;
15104 typval_T *rettv;
15106 int flags = 0;
15108 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
15112 * "searchdecl()" function
15114 static void
15115 f_searchdecl(argvars, rettv)
15116 typval_T *argvars;
15117 typval_T *rettv;
15119 int locally = 1;
15120 int thisblock = 0;
15121 int error = FALSE;
15122 char_u *name;
15124 rettv->vval.v_number = 1; /* default: FAIL */
15126 name = get_tv_string_chk(&argvars[0]);
15127 if (argvars[1].v_type != VAR_UNKNOWN)
15129 locally = get_tv_number_chk(&argvars[1], &error) == 0;
15130 if (!error && argvars[2].v_type != VAR_UNKNOWN)
15131 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
15133 if (!error && name != NULL)
15134 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
15135 locally, thisblock, SEARCH_KEEP) == FAIL;
15139 * Used by searchpair() and searchpairpos()
15141 static int
15142 searchpair_cmn(argvars, match_pos)
15143 typval_T *argvars;
15144 pos_T *match_pos;
15146 char_u *spat, *mpat, *epat;
15147 char_u *skip;
15148 int save_p_ws = p_ws;
15149 int dir;
15150 int flags = 0;
15151 char_u nbuf1[NUMBUFLEN];
15152 char_u nbuf2[NUMBUFLEN];
15153 char_u nbuf3[NUMBUFLEN];
15154 int retval = 0; /* default: FAIL */
15155 long lnum_stop = 0;
15156 long time_limit = 0;
15158 /* Get the three pattern arguments: start, middle, end. */
15159 spat = get_tv_string_chk(&argvars[0]);
15160 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
15161 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
15162 if (spat == NULL || mpat == NULL || epat == NULL)
15163 goto theend; /* type error */
15165 /* Handle the optional fourth argument: flags */
15166 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
15167 if (dir == 0)
15168 goto theend;
15170 /* Don't accept SP_END or SP_SUBPAT.
15171 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
15173 if ((flags & (SP_END | SP_SUBPAT)) != 0
15174 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
15176 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
15177 goto theend;
15180 /* Using 'r' implies 'W', otherwise it doesn't work. */
15181 if (flags & SP_REPEAT)
15182 p_ws = FALSE;
15184 /* Optional fifth argument: skip expression */
15185 if (argvars[3].v_type == VAR_UNKNOWN
15186 || argvars[4].v_type == VAR_UNKNOWN)
15187 skip = (char_u *)"";
15188 else
15190 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
15191 if (argvars[5].v_type != VAR_UNKNOWN)
15193 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
15194 if (lnum_stop < 0)
15195 goto theend;
15196 #ifdef FEAT_RELTIME
15197 if (argvars[6].v_type != VAR_UNKNOWN)
15199 time_limit = get_tv_number_chk(&argvars[6], NULL);
15200 if (time_limit < 0)
15201 goto theend;
15203 #endif
15206 if (skip == NULL)
15207 goto theend; /* type error */
15209 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
15210 match_pos, lnum_stop, time_limit);
15212 theend:
15213 p_ws = save_p_ws;
15215 return retval;
15219 * "searchpair()" function
15221 static void
15222 f_searchpair(argvars, rettv)
15223 typval_T *argvars;
15224 typval_T *rettv;
15226 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
15230 * "searchpairpos()" function
15232 static void
15233 f_searchpairpos(argvars, rettv)
15234 typval_T *argvars;
15235 typval_T *rettv;
15237 pos_T match_pos;
15238 int lnum = 0;
15239 int col = 0;
15241 if (rettv_list_alloc(rettv) == FAIL)
15242 return;
15244 if (searchpair_cmn(argvars, &match_pos) > 0)
15246 lnum = match_pos.lnum;
15247 col = match_pos.col;
15250 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15251 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15255 * Search for a start/middle/end thing.
15256 * Used by searchpair(), see its documentation for the details.
15257 * Returns 0 or -1 for no match,
15259 long
15260 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
15261 lnum_stop, time_limit)
15262 char_u *spat; /* start pattern */
15263 char_u *mpat; /* middle pattern */
15264 char_u *epat; /* end pattern */
15265 int dir; /* BACKWARD or FORWARD */
15266 char_u *skip; /* skip expression */
15267 int flags; /* SP_SETPCMARK and other SP_ values */
15268 pos_T *match_pos;
15269 linenr_T lnum_stop; /* stop at this line if not zero */
15270 long time_limit; /* stop after this many msec */
15272 char_u *save_cpo;
15273 char_u *pat, *pat2 = NULL, *pat3 = NULL;
15274 long retval = 0;
15275 pos_T pos;
15276 pos_T firstpos;
15277 pos_T foundpos;
15278 pos_T save_cursor;
15279 pos_T save_pos;
15280 int n;
15281 int r;
15282 int nest = 1;
15283 int err;
15284 int options = SEARCH_KEEP;
15285 proftime_T tm;
15287 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15288 save_cpo = p_cpo;
15289 p_cpo = empty_option;
15291 #ifdef FEAT_RELTIME
15292 /* Set the time limit, if there is one. */
15293 profile_setlimit(time_limit, &tm);
15294 #endif
15296 /* Make two search patterns: start/end (pat2, for in nested pairs) and
15297 * start/middle/end (pat3, for the top pair). */
15298 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
15299 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
15300 if (pat2 == NULL || pat3 == NULL)
15301 goto theend;
15302 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
15303 if (*mpat == NUL)
15304 STRCPY(pat3, pat2);
15305 else
15306 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
15307 spat, epat, mpat);
15308 if (flags & SP_START)
15309 options |= SEARCH_START;
15311 save_cursor = curwin->w_cursor;
15312 pos = curwin->w_cursor;
15313 clearpos(&firstpos);
15314 clearpos(&foundpos);
15315 pat = pat3;
15316 for (;;)
15318 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15319 options, RE_SEARCH, lnum_stop, &tm);
15320 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
15321 /* didn't find it or found the first match again: FAIL */
15322 break;
15324 if (firstpos.lnum == 0)
15325 firstpos = pos;
15326 if (equalpos(pos, foundpos))
15328 /* Found the same position again. Can happen with a pattern that
15329 * has "\zs" at the end and searching backwards. Advance one
15330 * character and try again. */
15331 if (dir == BACKWARD)
15332 decl(&pos);
15333 else
15334 incl(&pos);
15336 foundpos = pos;
15338 /* clear the start flag to avoid getting stuck here */
15339 options &= ~SEARCH_START;
15341 /* If the skip pattern matches, ignore this match. */
15342 if (*skip != NUL)
15344 save_pos = curwin->w_cursor;
15345 curwin->w_cursor = pos;
15346 r = eval_to_bool(skip, &err, NULL, FALSE);
15347 curwin->w_cursor = save_pos;
15348 if (err)
15350 /* Evaluating {skip} caused an error, break here. */
15351 curwin->w_cursor = save_cursor;
15352 retval = -1;
15353 break;
15355 if (r)
15356 continue;
15359 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
15361 /* Found end when searching backwards or start when searching
15362 * forward: nested pair. */
15363 ++nest;
15364 pat = pat2; /* nested, don't search for middle */
15366 else
15368 /* Found end when searching forward or start when searching
15369 * backward: end of (nested) pair; or found middle in outer pair. */
15370 if (--nest == 1)
15371 pat = pat3; /* outer level, search for middle */
15374 if (nest == 0)
15376 /* Found the match: return matchcount or line number. */
15377 if (flags & SP_RETCOUNT)
15378 ++retval;
15379 else
15380 retval = pos.lnum;
15381 if (flags & SP_SETPCMARK)
15382 setpcmark();
15383 curwin->w_cursor = pos;
15384 if (!(flags & SP_REPEAT))
15385 break;
15386 nest = 1; /* search for next unmatched */
15390 if (match_pos != NULL)
15392 /* Store the match cursor position */
15393 match_pos->lnum = curwin->w_cursor.lnum;
15394 match_pos->col = curwin->w_cursor.col + 1;
15397 /* If 'n' flag is used or search failed: restore cursor position. */
15398 if ((flags & SP_NOMOVE) || retval == 0)
15399 curwin->w_cursor = save_cursor;
15401 theend:
15402 vim_free(pat2);
15403 vim_free(pat3);
15404 if (p_cpo == empty_option)
15405 p_cpo = save_cpo;
15406 else
15407 /* Darn, evaluating the {skip} expression changed the value. */
15408 free_string_option(save_cpo);
15410 return retval;
15414 * "searchpos()" function
15416 static void
15417 f_searchpos(argvars, rettv)
15418 typval_T *argvars;
15419 typval_T *rettv;
15421 pos_T match_pos;
15422 int lnum = 0;
15423 int col = 0;
15424 int n;
15425 int flags = 0;
15427 if (rettv_list_alloc(rettv) == FAIL)
15428 return;
15430 n = search_cmn(argvars, &match_pos, &flags);
15431 if (n > 0)
15433 lnum = match_pos.lnum;
15434 col = match_pos.col;
15437 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15438 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15439 if (flags & SP_SUBPAT)
15440 list_append_number(rettv->vval.v_list, (varnumber_T)n);
15444 static void
15445 f_server2client(argvars, rettv)
15446 typval_T *argvars UNUSED;
15447 typval_T *rettv;
15449 #ifdef FEAT_CLIENTSERVER
15450 char_u buf[NUMBUFLEN];
15451 char_u *server = get_tv_string_chk(&argvars[0]);
15452 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
15454 rettv->vval.v_number = -1;
15455 if (server == NULL || reply == NULL)
15456 return;
15457 if (check_restricted() || check_secure())
15458 return;
15459 # ifdef FEAT_X11
15460 if (check_connection() == FAIL)
15461 return;
15462 # endif
15464 if (serverSendReply(server, reply) < 0)
15466 EMSG(_("E258: Unable to send to client"));
15467 return;
15469 rettv->vval.v_number = 0;
15470 #else
15471 rettv->vval.v_number = -1;
15472 #endif
15475 static void
15476 f_serverlist(argvars, rettv)
15477 typval_T *argvars UNUSED;
15478 typval_T *rettv;
15480 char_u *r = NULL;
15482 #ifdef FEAT_CLIENTSERVER
15483 # ifdef WIN32
15484 r = serverGetVimNames();
15485 # else
15486 make_connection();
15487 if (X_DISPLAY != NULL)
15488 r = serverGetVimNames(X_DISPLAY);
15489 # endif
15490 #endif
15491 rettv->v_type = VAR_STRING;
15492 rettv->vval.v_string = r;
15496 * "setbufvar()" function
15498 static void
15499 f_setbufvar(argvars, rettv)
15500 typval_T *argvars;
15501 typval_T *rettv UNUSED;
15503 buf_T *buf;
15504 aco_save_T aco;
15505 char_u *varname, *bufvarname;
15506 typval_T *varp;
15507 char_u nbuf[NUMBUFLEN];
15509 if (check_restricted() || check_secure())
15510 return;
15511 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
15512 varname = get_tv_string_chk(&argvars[1]);
15513 buf = get_buf_tv(&argvars[0]);
15514 varp = &argvars[2];
15516 if (buf != NULL && varname != NULL && varp != NULL)
15518 /* set curbuf to be our buf, temporarily */
15519 aucmd_prepbuf(&aco, buf);
15521 if (*varname == '&')
15523 long numval;
15524 char_u *strval;
15525 int error = FALSE;
15527 ++varname;
15528 numval = get_tv_number_chk(varp, &error);
15529 strval = get_tv_string_buf_chk(varp, nbuf);
15530 if (!error && strval != NULL)
15531 set_option_value(varname, numval, strval, OPT_LOCAL);
15533 else
15535 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
15536 if (bufvarname != NULL)
15538 STRCPY(bufvarname, "b:");
15539 STRCPY(bufvarname + 2, varname);
15540 set_var(bufvarname, varp, TRUE);
15541 vim_free(bufvarname);
15545 /* reset notion of buffer */
15546 aucmd_restbuf(&aco);
15551 * "setcmdpos()" function
15553 static void
15554 f_setcmdpos(argvars, rettv)
15555 typval_T *argvars;
15556 typval_T *rettv;
15558 int pos = (int)get_tv_number(&argvars[0]) - 1;
15560 if (pos >= 0)
15561 rettv->vval.v_number = set_cmdline_pos(pos);
15565 * "setline()" function
15567 static void
15568 f_setline(argvars, rettv)
15569 typval_T *argvars;
15570 typval_T *rettv;
15572 linenr_T lnum;
15573 char_u *line = NULL;
15574 list_T *l = NULL;
15575 listitem_T *li = NULL;
15576 long added = 0;
15577 linenr_T lcount = curbuf->b_ml.ml_line_count;
15579 lnum = get_tv_lnum(&argvars[0]);
15580 if (argvars[1].v_type == VAR_LIST)
15582 l = argvars[1].vval.v_list;
15583 li = l->lv_first;
15585 else
15586 line = get_tv_string_chk(&argvars[1]);
15588 /* default result is zero == OK */
15589 for (;;)
15591 if (l != NULL)
15593 /* list argument, get next string */
15594 if (li == NULL)
15595 break;
15596 line = get_tv_string_chk(&li->li_tv);
15597 li = li->li_next;
15600 rettv->vval.v_number = 1; /* FAIL */
15601 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
15602 break;
15603 if (lnum <= curbuf->b_ml.ml_line_count)
15605 /* existing line, replace it */
15606 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
15608 changed_bytes(lnum, 0);
15609 if (lnum == curwin->w_cursor.lnum)
15610 check_cursor_col();
15611 rettv->vval.v_number = 0; /* OK */
15614 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
15616 /* lnum is one past the last line, append the line */
15617 ++added;
15618 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
15619 rettv->vval.v_number = 0; /* OK */
15622 if (l == NULL) /* only one string argument */
15623 break;
15624 ++lnum;
15627 if (added > 0)
15628 appended_lines_mark(lcount, added);
15631 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
15634 * Used by "setqflist()" and "setloclist()" functions
15636 static void
15637 set_qf_ll_list(wp, list_arg, action_arg, rettv)
15638 win_T *wp UNUSED;
15639 typval_T *list_arg UNUSED;
15640 typval_T *action_arg UNUSED;
15641 typval_T *rettv;
15643 #ifdef FEAT_QUICKFIX
15644 char_u *act;
15645 int action = ' ';
15646 #endif
15648 rettv->vval.v_number = -1;
15650 #ifdef FEAT_QUICKFIX
15651 if (list_arg->v_type != VAR_LIST)
15652 EMSG(_(e_listreq));
15653 else
15655 list_T *l = list_arg->vval.v_list;
15657 if (action_arg->v_type == VAR_STRING)
15659 act = get_tv_string_chk(action_arg);
15660 if (act == NULL)
15661 return; /* type error; errmsg already given */
15662 if (*act == 'a' || *act == 'r')
15663 action = *act;
15666 if (l != NULL && set_errorlist(wp, l, action) == OK)
15667 rettv->vval.v_number = 0;
15669 #endif
15673 * "setloclist()" function
15675 static void
15676 f_setloclist(argvars, rettv)
15677 typval_T *argvars;
15678 typval_T *rettv;
15680 win_T *win;
15682 rettv->vval.v_number = -1;
15684 win = find_win_by_nr(&argvars[0], NULL);
15685 if (win != NULL)
15686 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
15690 * "setmatches()" function
15692 static void
15693 f_setmatches(argvars, rettv)
15694 typval_T *argvars;
15695 typval_T *rettv;
15697 #ifdef FEAT_SEARCH_EXTRA
15698 list_T *l;
15699 listitem_T *li;
15700 dict_T *d;
15702 rettv->vval.v_number = -1;
15703 if (argvars[0].v_type != VAR_LIST)
15705 EMSG(_(e_listreq));
15706 return;
15708 if ((l = argvars[0].vval.v_list) != NULL)
15711 /* To some extent make sure that we are dealing with a list from
15712 * "getmatches()". */
15713 li = l->lv_first;
15714 while (li != NULL)
15716 if (li->li_tv.v_type != VAR_DICT
15717 || (d = li->li_tv.vval.v_dict) == NULL)
15719 EMSG(_(e_invarg));
15720 return;
15722 if (!(dict_find(d, (char_u *)"group", -1) != NULL
15723 && dict_find(d, (char_u *)"pattern", -1) != NULL
15724 && dict_find(d, (char_u *)"priority", -1) != NULL
15725 && dict_find(d, (char_u *)"id", -1) != NULL))
15727 EMSG(_(e_invarg));
15728 return;
15730 li = li->li_next;
15733 clear_matches(curwin);
15734 li = l->lv_first;
15735 while (li != NULL)
15737 d = li->li_tv.vval.v_dict;
15738 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
15739 get_dict_string(d, (char_u *)"pattern", FALSE),
15740 (int)get_dict_number(d, (char_u *)"priority"),
15741 (int)get_dict_number(d, (char_u *)"id"));
15742 li = li->li_next;
15744 rettv->vval.v_number = 0;
15746 #endif
15750 * "setpos()" function
15752 static void
15753 f_setpos(argvars, rettv)
15754 typval_T *argvars;
15755 typval_T *rettv;
15757 pos_T pos;
15758 int fnum;
15759 char_u *name;
15761 rettv->vval.v_number = -1;
15762 name = get_tv_string_chk(argvars);
15763 if (name != NULL)
15765 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
15767 if (--pos.col < 0)
15768 pos.col = 0;
15769 if (name[0] == '.' && name[1] == NUL)
15771 /* set cursor */
15772 if (fnum == curbuf->b_fnum)
15774 curwin->w_cursor = pos;
15775 check_cursor();
15776 rettv->vval.v_number = 0;
15778 else
15779 EMSG(_(e_invarg));
15781 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
15783 /* set mark */
15784 if (setmark_pos(name[1], &pos, fnum) == OK)
15785 rettv->vval.v_number = 0;
15787 else
15788 EMSG(_(e_invarg));
15794 * "setqflist()" function
15796 static void
15797 f_setqflist(argvars, rettv)
15798 typval_T *argvars;
15799 typval_T *rettv;
15801 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
15805 * "setreg()" function
15807 static void
15808 f_setreg(argvars, rettv)
15809 typval_T *argvars;
15810 typval_T *rettv;
15812 int regname;
15813 char_u *strregname;
15814 char_u *stropt;
15815 char_u *strval;
15816 int append;
15817 char_u yank_type;
15818 long block_len;
15820 block_len = -1;
15821 yank_type = MAUTO;
15822 append = FALSE;
15824 strregname = get_tv_string_chk(argvars);
15825 rettv->vval.v_number = 1; /* FAIL is default */
15827 if (strregname == NULL)
15828 return; /* type error; errmsg already given */
15829 regname = *strregname;
15830 if (regname == 0 || regname == '@')
15831 regname = '"';
15832 else if (regname == '=')
15833 return;
15835 if (argvars[2].v_type != VAR_UNKNOWN)
15837 stropt = get_tv_string_chk(&argvars[2]);
15838 if (stropt == NULL)
15839 return; /* type error */
15840 for (; *stropt != NUL; ++stropt)
15841 switch (*stropt)
15843 case 'a': case 'A': /* append */
15844 append = TRUE;
15845 break;
15846 case 'v': case 'c': /* character-wise selection */
15847 yank_type = MCHAR;
15848 break;
15849 case 'V': case 'l': /* line-wise selection */
15850 yank_type = MLINE;
15851 break;
15852 #ifdef FEAT_VISUAL
15853 case 'b': case Ctrl_V: /* block-wise selection */
15854 yank_type = MBLOCK;
15855 if (VIM_ISDIGIT(stropt[1]))
15857 ++stropt;
15858 block_len = getdigits(&stropt) - 1;
15859 --stropt;
15861 break;
15862 #endif
15866 strval = get_tv_string_chk(&argvars[1]);
15867 if (strval != NULL)
15868 write_reg_contents_ex(regname, strval, -1,
15869 append, yank_type, block_len);
15870 rettv->vval.v_number = 0;
15874 * "settabwinvar()" function
15876 static void
15877 f_settabwinvar(argvars, rettv)
15878 typval_T *argvars;
15879 typval_T *rettv;
15881 setwinvar(argvars, rettv, 1);
15885 * "setwinvar()" function
15887 static void
15888 f_setwinvar(argvars, rettv)
15889 typval_T *argvars;
15890 typval_T *rettv;
15892 setwinvar(argvars, rettv, 0);
15896 * "setwinvar()" and "settabwinvar()" functions
15898 static void
15899 setwinvar(argvars, rettv, off)
15900 typval_T *argvars;
15901 typval_T *rettv UNUSED;
15902 int off;
15904 win_T *win;
15905 #ifdef FEAT_WINDOWS
15906 win_T *save_curwin;
15907 tabpage_T *save_curtab;
15908 #endif
15909 char_u *varname, *winvarname;
15910 typval_T *varp;
15911 char_u nbuf[NUMBUFLEN];
15912 tabpage_T *tp;
15914 if (check_restricted() || check_secure())
15915 return;
15917 #ifdef FEAT_WINDOWS
15918 if (off == 1)
15919 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
15920 else
15921 tp = curtab;
15922 #endif
15923 win = find_win_by_nr(&argvars[off], tp);
15924 varname = get_tv_string_chk(&argvars[off + 1]);
15925 varp = &argvars[off + 2];
15927 if (win != NULL && varname != NULL && varp != NULL)
15929 #ifdef FEAT_WINDOWS
15930 /* set curwin to be our win, temporarily */
15931 save_curwin = curwin;
15932 save_curtab = curtab;
15933 goto_tabpage_tp(tp);
15934 if (!win_valid(win))
15935 return;
15936 curwin = win;
15937 curbuf = curwin->w_buffer;
15938 #endif
15940 if (*varname == '&')
15942 long numval;
15943 char_u *strval;
15944 int error = FALSE;
15946 ++varname;
15947 numval = get_tv_number_chk(varp, &error);
15948 strval = get_tv_string_buf_chk(varp, nbuf);
15949 if (!error && strval != NULL)
15950 set_option_value(varname, numval, strval, OPT_LOCAL);
15952 else
15954 winvarname = alloc((unsigned)STRLEN(varname) + 3);
15955 if (winvarname != NULL)
15957 STRCPY(winvarname, "w:");
15958 STRCPY(winvarname + 2, varname);
15959 set_var(winvarname, varp, TRUE);
15960 vim_free(winvarname);
15964 #ifdef FEAT_WINDOWS
15965 /* Restore current tabpage and window, if still valid (autocomands can
15966 * make them invalid). */
15967 if (valid_tabpage(save_curtab))
15968 goto_tabpage_tp(save_curtab);
15969 if (win_valid(save_curwin))
15971 curwin = save_curwin;
15972 curbuf = curwin->w_buffer;
15974 #endif
15979 * "shellescape({string})" function
15981 static void
15982 f_shellescape(argvars, rettv)
15983 typval_T *argvars;
15984 typval_T *rettv;
15986 rettv->vval.v_string = vim_strsave_shellescape(
15987 get_tv_string(&argvars[0]), non_zero_arg(&argvars[1]));
15988 rettv->v_type = VAR_STRING;
15992 * "simplify()" function
15994 static void
15995 f_simplify(argvars, rettv)
15996 typval_T *argvars;
15997 typval_T *rettv;
15999 char_u *p;
16001 p = get_tv_string(&argvars[0]);
16002 rettv->vval.v_string = vim_strsave(p);
16003 simplify_filename(rettv->vval.v_string); /* simplify in place */
16004 rettv->v_type = VAR_STRING;
16007 #ifdef FEAT_FLOAT
16009 * "sin()" function
16011 static void
16012 f_sin(argvars, rettv)
16013 typval_T *argvars;
16014 typval_T *rettv;
16016 float_T f;
16018 rettv->v_type = VAR_FLOAT;
16019 if (get_float_arg(argvars, &f) == OK)
16020 rettv->vval.v_float = sin(f);
16021 else
16022 rettv->vval.v_float = 0.0;
16024 #endif
16026 static int
16027 #ifdef __BORLANDC__
16028 _RTLENTRYF
16029 #endif
16030 item_compare __ARGS((const void *s1, const void *s2));
16031 static int
16032 #ifdef __BORLANDC__
16033 _RTLENTRYF
16034 #endif
16035 item_compare2 __ARGS((const void *s1, const void *s2));
16037 static int item_compare_ic;
16038 static char_u *item_compare_func;
16039 static int item_compare_func_err;
16040 #define ITEM_COMPARE_FAIL 999
16043 * Compare functions for f_sort() below.
16045 static int
16046 #ifdef __BORLANDC__
16047 _RTLENTRYF
16048 #endif
16049 item_compare(s1, s2)
16050 const void *s1;
16051 const void *s2;
16053 char_u *p1, *p2;
16054 char_u *tofree1, *tofree2;
16055 int res;
16056 char_u numbuf1[NUMBUFLEN];
16057 char_u numbuf2[NUMBUFLEN];
16059 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
16060 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
16061 if (p1 == NULL)
16062 p1 = (char_u *)"";
16063 if (p2 == NULL)
16064 p2 = (char_u *)"";
16065 if (item_compare_ic)
16066 res = STRICMP(p1, p2);
16067 else
16068 res = STRCMP(p1, p2);
16069 vim_free(tofree1);
16070 vim_free(tofree2);
16071 return res;
16074 static int
16075 #ifdef __BORLANDC__
16076 _RTLENTRYF
16077 #endif
16078 item_compare2(s1, s2)
16079 const void *s1;
16080 const void *s2;
16082 int res;
16083 typval_T rettv;
16084 typval_T argv[3];
16085 int dummy;
16087 /* shortcut after failure in previous call; compare all items equal */
16088 if (item_compare_func_err)
16089 return 0;
16091 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
16092 * in the copy without changing the original list items. */
16093 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
16094 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
16096 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
16097 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
16098 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
16099 clear_tv(&argv[0]);
16100 clear_tv(&argv[1]);
16102 if (res == FAIL)
16103 res = ITEM_COMPARE_FAIL;
16104 else
16105 res = get_tv_number_chk(&rettv, &item_compare_func_err);
16106 if (item_compare_func_err)
16107 res = ITEM_COMPARE_FAIL; /* return value has wrong type */
16108 clear_tv(&rettv);
16109 return res;
16113 * "sort({list})" function
16115 static void
16116 f_sort(argvars, rettv)
16117 typval_T *argvars;
16118 typval_T *rettv;
16120 list_T *l;
16121 listitem_T *li;
16122 listitem_T **ptrs;
16123 long len;
16124 long i;
16126 if (argvars[0].v_type != VAR_LIST)
16127 EMSG2(_(e_listarg), "sort()");
16128 else
16130 l = argvars[0].vval.v_list;
16131 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
16132 return;
16133 rettv->vval.v_list = l;
16134 rettv->v_type = VAR_LIST;
16135 ++l->lv_refcount;
16137 len = list_len(l);
16138 if (len <= 1)
16139 return; /* short list sorts pretty quickly */
16141 item_compare_ic = FALSE;
16142 item_compare_func = NULL;
16143 if (argvars[1].v_type != VAR_UNKNOWN)
16145 if (argvars[1].v_type == VAR_FUNC)
16146 item_compare_func = argvars[1].vval.v_string;
16147 else
16149 int error = FALSE;
16151 i = get_tv_number_chk(&argvars[1], &error);
16152 if (error)
16153 return; /* type error; errmsg already given */
16154 if (i == 1)
16155 item_compare_ic = TRUE;
16156 else
16157 item_compare_func = get_tv_string(&argvars[1]);
16161 /* Make an array with each entry pointing to an item in the List. */
16162 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
16163 if (ptrs == NULL)
16164 return;
16165 i = 0;
16166 for (li = l->lv_first; li != NULL; li = li->li_next)
16167 ptrs[i++] = li;
16169 item_compare_func_err = FALSE;
16170 /* test the compare function */
16171 if (item_compare_func != NULL
16172 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
16173 == ITEM_COMPARE_FAIL)
16174 EMSG(_("E702: Sort compare function failed"));
16175 else
16177 /* Sort the array with item pointers. */
16178 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
16179 item_compare_func == NULL ? item_compare : item_compare2);
16181 if (!item_compare_func_err)
16183 /* Clear the List and append the items in the sorted order. */
16184 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
16185 l->lv_len = 0;
16186 for (i = 0; i < len; ++i)
16187 list_append(l, ptrs[i]);
16191 vim_free(ptrs);
16196 * "soundfold({word})" function
16198 static void
16199 f_soundfold(argvars, rettv)
16200 typval_T *argvars;
16201 typval_T *rettv;
16203 char_u *s;
16205 rettv->v_type = VAR_STRING;
16206 s = get_tv_string(&argvars[0]);
16207 #ifdef FEAT_SPELL
16208 rettv->vval.v_string = eval_soundfold(s);
16209 #else
16210 rettv->vval.v_string = vim_strsave(s);
16211 #endif
16215 * "spellbadword()" function
16217 static void
16218 f_spellbadword(argvars, rettv)
16219 typval_T *argvars UNUSED;
16220 typval_T *rettv;
16222 char_u *word = (char_u *)"";
16223 hlf_T attr = HLF_COUNT;
16224 int len = 0;
16226 if (rettv_list_alloc(rettv) == FAIL)
16227 return;
16229 #ifdef FEAT_SPELL
16230 if (argvars[0].v_type == VAR_UNKNOWN)
16232 /* Find the start and length of the badly spelled word. */
16233 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
16234 if (len != 0)
16235 word = ml_get_cursor();
16237 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16239 char_u *str = get_tv_string_chk(&argvars[0]);
16240 int capcol = -1;
16242 if (str != NULL)
16244 /* Check the argument for spelling. */
16245 while (*str != NUL)
16247 len = spell_check(curwin, str, &attr, &capcol, FALSE);
16248 if (attr != HLF_COUNT)
16250 word = str;
16251 break;
16253 str += len;
16257 #endif
16259 list_append_string(rettv->vval.v_list, word, len);
16260 list_append_string(rettv->vval.v_list, (char_u *)(
16261 attr == HLF_SPB ? "bad" :
16262 attr == HLF_SPR ? "rare" :
16263 attr == HLF_SPL ? "local" :
16264 attr == HLF_SPC ? "caps" :
16265 ""), -1);
16269 * "spellsuggest()" function
16271 static void
16272 f_spellsuggest(argvars, rettv)
16273 typval_T *argvars UNUSED;
16274 typval_T *rettv;
16276 #ifdef FEAT_SPELL
16277 char_u *str;
16278 int typeerr = FALSE;
16279 int maxcount;
16280 garray_T ga;
16281 int i;
16282 listitem_T *li;
16283 int need_capital = FALSE;
16284 #endif
16286 if (rettv_list_alloc(rettv) == FAIL)
16287 return;
16289 #ifdef FEAT_SPELL
16290 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16292 str = get_tv_string(&argvars[0]);
16293 if (argvars[1].v_type != VAR_UNKNOWN)
16295 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
16296 if (maxcount <= 0)
16297 return;
16298 if (argvars[2].v_type != VAR_UNKNOWN)
16300 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
16301 if (typeerr)
16302 return;
16305 else
16306 maxcount = 25;
16308 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
16310 for (i = 0; i < ga.ga_len; ++i)
16312 str = ((char_u **)ga.ga_data)[i];
16314 li = listitem_alloc();
16315 if (li == NULL)
16316 vim_free(str);
16317 else
16319 li->li_tv.v_type = VAR_STRING;
16320 li->li_tv.v_lock = 0;
16321 li->li_tv.vval.v_string = str;
16322 list_append(rettv->vval.v_list, li);
16325 ga_clear(&ga);
16327 #endif
16330 static void
16331 f_split(argvars, rettv)
16332 typval_T *argvars;
16333 typval_T *rettv;
16335 char_u *str;
16336 char_u *end;
16337 char_u *pat = NULL;
16338 regmatch_T regmatch;
16339 char_u patbuf[NUMBUFLEN];
16340 char_u *save_cpo;
16341 int match;
16342 colnr_T col = 0;
16343 int keepempty = FALSE;
16344 int typeerr = FALSE;
16346 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
16347 save_cpo = p_cpo;
16348 p_cpo = (char_u *)"";
16350 str = get_tv_string(&argvars[0]);
16351 if (argvars[1].v_type != VAR_UNKNOWN)
16353 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16354 if (pat == NULL)
16355 typeerr = TRUE;
16356 if (argvars[2].v_type != VAR_UNKNOWN)
16357 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
16359 if (pat == NULL || *pat == NUL)
16360 pat = (char_u *)"[\\x01- ]\\+";
16362 if (rettv_list_alloc(rettv) == FAIL)
16363 return;
16364 if (typeerr)
16365 return;
16367 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
16368 if (regmatch.regprog != NULL)
16370 regmatch.rm_ic = FALSE;
16371 while (*str != NUL || keepempty)
16373 if (*str == NUL)
16374 match = FALSE; /* empty item at the end */
16375 else
16376 match = vim_regexec_nl(&regmatch, str, col);
16377 if (match)
16378 end = regmatch.startp[0];
16379 else
16380 end = str + STRLEN(str);
16381 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
16382 && *str != NUL && match && end < regmatch.endp[0]))
16384 if (list_append_string(rettv->vval.v_list, str,
16385 (int)(end - str)) == FAIL)
16386 break;
16388 if (!match)
16389 break;
16390 /* Advance to just after the match. */
16391 if (regmatch.endp[0] > str)
16392 col = 0;
16393 else
16395 /* Don't get stuck at the same match. */
16396 #ifdef FEAT_MBYTE
16397 col = (*mb_ptr2len)(regmatch.endp[0]);
16398 #else
16399 col = 1;
16400 #endif
16402 str = regmatch.endp[0];
16405 vim_free(regmatch.regprog);
16408 p_cpo = save_cpo;
16411 #ifdef FEAT_FLOAT
16413 * "sqrt()" function
16415 static void
16416 f_sqrt(argvars, rettv)
16417 typval_T *argvars;
16418 typval_T *rettv;
16420 float_T f;
16422 rettv->v_type = VAR_FLOAT;
16423 if (get_float_arg(argvars, &f) == OK)
16424 rettv->vval.v_float = sqrt(f);
16425 else
16426 rettv->vval.v_float = 0.0;
16430 * "str2float()" function
16432 static void
16433 f_str2float(argvars, rettv)
16434 typval_T *argvars;
16435 typval_T *rettv;
16437 char_u *p = skipwhite(get_tv_string(&argvars[0]));
16439 if (*p == '+')
16440 p = skipwhite(p + 1);
16441 (void)string2float(p, &rettv->vval.v_float);
16442 rettv->v_type = VAR_FLOAT;
16444 #endif
16447 * "str2nr()" function
16449 static void
16450 f_str2nr(argvars, rettv)
16451 typval_T *argvars;
16452 typval_T *rettv;
16454 int base = 10;
16455 char_u *p;
16456 long n;
16458 if (argvars[1].v_type != VAR_UNKNOWN)
16460 base = get_tv_number(&argvars[1]);
16461 if (base != 8 && base != 10 && base != 16)
16463 EMSG(_(e_invarg));
16464 return;
16468 p = skipwhite(get_tv_string(&argvars[0]));
16469 if (*p == '+')
16470 p = skipwhite(p + 1);
16471 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
16472 rettv->vval.v_number = n;
16475 #ifdef HAVE_STRFTIME
16477 * "strftime({format}[, {time}])" function
16479 static void
16480 f_strftime(argvars, rettv)
16481 typval_T *argvars;
16482 typval_T *rettv;
16484 char_u result_buf[256];
16485 struct tm *curtime;
16486 time_t seconds;
16487 char_u *p;
16489 rettv->v_type = VAR_STRING;
16491 p = get_tv_string(&argvars[0]);
16492 if (argvars[1].v_type == VAR_UNKNOWN)
16493 seconds = time(NULL);
16494 else
16495 seconds = (time_t)get_tv_number(&argvars[1]);
16496 curtime = localtime(&seconds);
16497 /* MSVC returns NULL for an invalid value of seconds. */
16498 if (curtime == NULL)
16499 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
16500 else
16502 # ifdef FEAT_MBYTE
16503 vimconv_T conv;
16504 char_u *enc;
16506 conv.vc_type = CONV_NONE;
16507 enc = enc_locale();
16508 convert_setup(&conv, p_enc, enc);
16509 if (conv.vc_type != CONV_NONE)
16510 p = string_convert(&conv, p, NULL);
16511 # endif
16512 if (p != NULL)
16513 (void)strftime((char *)result_buf, sizeof(result_buf),
16514 (char *)p, curtime);
16515 else
16516 result_buf[0] = NUL;
16518 # ifdef FEAT_MBYTE
16519 if (conv.vc_type != CONV_NONE)
16520 vim_free(p);
16521 convert_setup(&conv, enc, p_enc);
16522 if (conv.vc_type != CONV_NONE)
16523 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
16524 else
16525 # endif
16526 rettv->vval.v_string = vim_strsave(result_buf);
16528 # ifdef FEAT_MBYTE
16529 /* Release conversion descriptors */
16530 convert_setup(&conv, NULL, NULL);
16531 vim_free(enc);
16532 # endif
16535 #endif
16538 * "stridx()" function
16540 static void
16541 f_stridx(argvars, rettv)
16542 typval_T *argvars;
16543 typval_T *rettv;
16545 char_u buf[NUMBUFLEN];
16546 char_u *needle;
16547 char_u *haystack;
16548 char_u *save_haystack;
16549 char_u *pos;
16550 int start_idx;
16552 needle = get_tv_string_chk(&argvars[1]);
16553 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
16554 rettv->vval.v_number = -1;
16555 if (needle == NULL || haystack == NULL)
16556 return; /* type error; errmsg already given */
16558 if (argvars[2].v_type != VAR_UNKNOWN)
16560 int error = FALSE;
16562 start_idx = get_tv_number_chk(&argvars[2], &error);
16563 if (error || start_idx >= (int)STRLEN(haystack))
16564 return;
16565 if (start_idx >= 0)
16566 haystack += start_idx;
16569 pos = (char_u *)strstr((char *)haystack, (char *)needle);
16570 if (pos != NULL)
16571 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
16575 * "string()" function
16577 static void
16578 f_string(argvars, rettv)
16579 typval_T *argvars;
16580 typval_T *rettv;
16582 char_u *tofree;
16583 char_u numbuf[NUMBUFLEN];
16585 rettv->v_type = VAR_STRING;
16586 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
16587 /* Make a copy if we have a value but it's not in allocated memory. */
16588 if (rettv->vval.v_string != NULL && tofree == NULL)
16589 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
16593 * "strlen()" function
16595 static void
16596 f_strlen(argvars, rettv)
16597 typval_T *argvars;
16598 typval_T *rettv;
16600 rettv->vval.v_number = (varnumber_T)(STRLEN(
16601 get_tv_string(&argvars[0])));
16605 * "strpart()" function
16607 static void
16608 f_strpart(argvars, rettv)
16609 typval_T *argvars;
16610 typval_T *rettv;
16612 char_u *p;
16613 int n;
16614 int len;
16615 int slen;
16616 int error = FALSE;
16618 p = get_tv_string(&argvars[0]);
16619 slen = (int)STRLEN(p);
16621 n = get_tv_number_chk(&argvars[1], &error);
16622 if (error)
16623 len = 0;
16624 else if (argvars[2].v_type != VAR_UNKNOWN)
16625 len = get_tv_number(&argvars[2]);
16626 else
16627 len = slen - n; /* default len: all bytes that are available. */
16630 * Only return the overlap between the specified part and the actual
16631 * string.
16633 if (n < 0)
16635 len += n;
16636 n = 0;
16638 else if (n > slen)
16639 n = slen;
16640 if (len < 0)
16641 len = 0;
16642 else if (n + len > slen)
16643 len = slen - n;
16645 rettv->v_type = VAR_STRING;
16646 rettv->vval.v_string = vim_strnsave(p + n, len);
16650 * "strridx()" function
16652 static void
16653 f_strridx(argvars, rettv)
16654 typval_T *argvars;
16655 typval_T *rettv;
16657 char_u buf[NUMBUFLEN];
16658 char_u *needle;
16659 char_u *haystack;
16660 char_u *rest;
16661 char_u *lastmatch = NULL;
16662 int haystack_len, end_idx;
16664 needle = get_tv_string_chk(&argvars[1]);
16665 haystack = get_tv_string_buf_chk(&argvars[0], buf);
16667 rettv->vval.v_number = -1;
16668 if (needle == NULL || haystack == NULL)
16669 return; /* type error; errmsg already given */
16671 haystack_len = (int)STRLEN(haystack);
16672 if (argvars[2].v_type != VAR_UNKNOWN)
16674 /* Third argument: upper limit for index */
16675 end_idx = get_tv_number_chk(&argvars[2], NULL);
16676 if (end_idx < 0)
16677 return; /* can never find a match */
16679 else
16680 end_idx = haystack_len;
16682 if (*needle == NUL)
16684 /* Empty string matches past the end. */
16685 lastmatch = haystack + end_idx;
16687 else
16689 for (rest = haystack; *rest != '\0'; ++rest)
16691 rest = (char_u *)strstr((char *)rest, (char *)needle);
16692 if (rest == NULL || rest > haystack + end_idx)
16693 break;
16694 lastmatch = rest;
16698 if (lastmatch == NULL)
16699 rettv->vval.v_number = -1;
16700 else
16701 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
16705 * "strtrans()" function
16707 static void
16708 f_strtrans(argvars, rettv)
16709 typval_T *argvars;
16710 typval_T *rettv;
16712 rettv->v_type = VAR_STRING;
16713 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
16717 * "submatch()" function
16719 static void
16720 f_submatch(argvars, rettv)
16721 typval_T *argvars;
16722 typval_T *rettv;
16724 rettv->v_type = VAR_STRING;
16725 rettv->vval.v_string =
16726 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
16730 * "substitute()" function
16732 static void
16733 f_substitute(argvars, rettv)
16734 typval_T *argvars;
16735 typval_T *rettv;
16737 char_u patbuf[NUMBUFLEN];
16738 char_u subbuf[NUMBUFLEN];
16739 char_u flagsbuf[NUMBUFLEN];
16741 char_u *str = get_tv_string_chk(&argvars[0]);
16742 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16743 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
16744 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
16746 rettv->v_type = VAR_STRING;
16747 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
16748 rettv->vval.v_string = NULL;
16749 else
16750 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
16754 * "synID(lnum, col, trans)" function
16756 static void
16757 f_synID(argvars, rettv)
16758 typval_T *argvars UNUSED;
16759 typval_T *rettv;
16761 int id = 0;
16762 #ifdef FEAT_SYN_HL
16763 long lnum;
16764 long col;
16765 int trans;
16766 int transerr = FALSE;
16768 lnum = get_tv_lnum(argvars); /* -1 on type error */
16769 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16770 trans = get_tv_number_chk(&argvars[2], &transerr);
16772 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16773 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
16774 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
16775 #endif
16777 rettv->vval.v_number = id;
16781 * "synIDattr(id, what [, mode])" function
16783 static void
16784 f_synIDattr(argvars, rettv)
16785 typval_T *argvars UNUSED;
16786 typval_T *rettv;
16788 char_u *p = NULL;
16789 #ifdef FEAT_SYN_HL
16790 int id;
16791 char_u *what;
16792 char_u *mode;
16793 char_u modebuf[NUMBUFLEN];
16794 int modec;
16796 id = get_tv_number(&argvars[0]);
16797 what = get_tv_string(&argvars[1]);
16798 if (argvars[2].v_type != VAR_UNKNOWN)
16800 mode = get_tv_string_buf(&argvars[2], modebuf);
16801 modec = TOLOWER_ASC(mode[0]);
16802 if (modec != 't' && modec != 'c'
16803 #ifdef FEAT_GUI
16804 && modec != 'g'
16805 #endif
16807 modec = 0; /* replace invalid with current */
16809 else
16811 #ifdef FEAT_GUI
16812 if (gui.in_use)
16813 modec = 'g';
16814 else
16815 #endif
16816 if (t_colors > 1)
16817 modec = 'c';
16818 else
16819 modec = 't';
16823 switch (TOLOWER_ASC(what[0]))
16825 case 'b':
16826 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
16827 p = highlight_color(id, what, modec);
16828 else /* bold */
16829 p = highlight_has_attr(id, HL_BOLD, modec);
16830 break;
16832 case 'f': /* fg[#] */
16833 p = highlight_color(id, what, modec);
16834 break;
16836 case 'i':
16837 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
16838 p = highlight_has_attr(id, HL_INVERSE, modec);
16839 else /* italic */
16840 p = highlight_has_attr(id, HL_ITALIC, modec);
16841 break;
16843 case 'n': /* name */
16844 p = get_highlight_name(NULL, id - 1);
16845 break;
16847 case 'r': /* reverse */
16848 p = highlight_has_attr(id, HL_INVERSE, modec);
16849 break;
16851 case 's':
16852 if (TOLOWER_ASC(what[1]) == 'p') /* sp[#] */
16853 p = highlight_color(id, what, modec);
16854 else /* standout */
16855 p = highlight_has_attr(id, HL_STANDOUT, modec);
16856 break;
16858 case 'u':
16859 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
16860 /* underline */
16861 p = highlight_has_attr(id, HL_UNDERLINE, modec);
16862 else
16863 /* undercurl */
16864 p = highlight_has_attr(id, HL_UNDERCURL, modec);
16865 break;
16868 if (p != NULL)
16869 p = vim_strsave(p);
16870 #endif
16871 rettv->v_type = VAR_STRING;
16872 rettv->vval.v_string = p;
16876 * "synIDtrans(id)" function
16878 static void
16879 f_synIDtrans(argvars, rettv)
16880 typval_T *argvars UNUSED;
16881 typval_T *rettv;
16883 int id;
16885 #ifdef FEAT_SYN_HL
16886 id = get_tv_number(&argvars[0]);
16888 if (id > 0)
16889 id = syn_get_final_id(id);
16890 else
16891 #endif
16892 id = 0;
16894 rettv->vval.v_number = id;
16898 * "synstack(lnum, col)" function
16900 static void
16901 f_synstack(argvars, rettv)
16902 typval_T *argvars UNUSED;
16903 typval_T *rettv;
16905 #ifdef FEAT_SYN_HL
16906 long lnum;
16907 long col;
16908 int i;
16909 int id;
16910 #endif
16912 rettv->v_type = VAR_LIST;
16913 rettv->vval.v_list = NULL;
16915 #ifdef FEAT_SYN_HL
16916 lnum = get_tv_lnum(argvars); /* -1 on type error */
16917 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16919 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16920 && col >= 0 && (col == 0 || col < (long)STRLEN(ml_get(lnum)))
16921 && rettv_list_alloc(rettv) != FAIL)
16923 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
16924 for (i = 0; ; ++i)
16926 id = syn_get_stack_item(i);
16927 if (id < 0)
16928 break;
16929 if (list_append_number(rettv->vval.v_list, id) == FAIL)
16930 break;
16933 #endif
16937 * "system()" function
16939 static void
16940 f_system(argvars, rettv)
16941 typval_T *argvars;
16942 typval_T *rettv;
16944 char_u *res = NULL;
16945 char_u *p;
16946 char_u *infile = NULL;
16947 char_u buf[NUMBUFLEN];
16948 int err = FALSE;
16949 FILE *fd;
16951 if (check_restricted() || check_secure())
16952 goto done;
16954 if (argvars[1].v_type != VAR_UNKNOWN)
16957 * Write the string to a temp file, to be used for input of the shell
16958 * command.
16960 if ((infile = vim_tempname('i')) == NULL)
16962 EMSG(_(e_notmp));
16963 goto done;
16966 fd = mch_fopen((char *)infile, WRITEBIN);
16967 if (fd == NULL)
16969 EMSG2(_(e_notopen), infile);
16970 goto done;
16972 p = get_tv_string_buf_chk(&argvars[1], buf);
16973 if (p == NULL)
16975 fclose(fd);
16976 goto done; /* type error; errmsg already given */
16978 if (fwrite(p, STRLEN(p), 1, fd) != 1)
16979 err = TRUE;
16980 if (fclose(fd) != 0)
16981 err = TRUE;
16982 if (err)
16984 EMSG(_("E677: Error writing temp file"));
16985 goto done;
16989 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
16990 SHELL_SILENT | SHELL_COOKED);
16992 #ifdef USE_CR
16993 /* translate <CR> into <NL> */
16994 if (res != NULL)
16996 char_u *s;
16998 for (s = res; *s; ++s)
17000 if (*s == CAR)
17001 *s = NL;
17004 #else
17005 # ifdef USE_CRNL
17006 /* translate <CR><NL> into <NL> */
17007 if (res != NULL)
17009 char_u *s, *d;
17011 d = res;
17012 for (s = res; *s; ++s)
17014 if (s[0] == CAR && s[1] == NL)
17015 ++s;
17016 *d++ = *s;
17018 *d = NUL;
17020 # endif
17021 #endif
17023 done:
17024 if (infile != NULL)
17026 mch_remove(infile);
17027 vim_free(infile);
17029 rettv->v_type = VAR_STRING;
17030 rettv->vval.v_string = res;
17034 * "tabpagebuflist()" function
17036 static void
17037 f_tabpagebuflist(argvars, rettv)
17038 typval_T *argvars UNUSED;
17039 typval_T *rettv UNUSED;
17041 #ifdef FEAT_WINDOWS
17042 tabpage_T *tp;
17043 win_T *wp = NULL;
17045 if (argvars[0].v_type == VAR_UNKNOWN)
17046 wp = firstwin;
17047 else
17049 tp = find_tabpage((int)get_tv_number(&argvars[0]));
17050 if (tp != NULL)
17051 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
17053 if (wp != NULL && rettv_list_alloc(rettv) != FAIL)
17055 for (; wp != NULL; wp = wp->w_next)
17056 if (list_append_number(rettv->vval.v_list,
17057 wp->w_buffer->b_fnum) == FAIL)
17058 break;
17060 #endif
17065 * "tabpagenr()" function
17067 static void
17068 f_tabpagenr(argvars, rettv)
17069 typval_T *argvars UNUSED;
17070 typval_T *rettv;
17072 int nr = 1;
17073 #ifdef FEAT_WINDOWS
17074 char_u *arg;
17076 if (argvars[0].v_type != VAR_UNKNOWN)
17078 arg = get_tv_string_chk(&argvars[0]);
17079 nr = 0;
17080 if (arg != NULL)
17082 if (STRCMP(arg, "$") == 0)
17083 nr = tabpage_index(NULL) - 1;
17084 else
17085 EMSG2(_(e_invexpr2), arg);
17088 else
17089 nr = tabpage_index(curtab);
17090 #endif
17091 rettv->vval.v_number = nr;
17095 #ifdef FEAT_WINDOWS
17096 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
17099 * Common code for tabpagewinnr() and winnr().
17101 static int
17102 get_winnr(tp, argvar)
17103 tabpage_T *tp;
17104 typval_T *argvar;
17106 win_T *twin;
17107 int nr = 1;
17108 win_T *wp;
17109 char_u *arg;
17111 twin = (tp == curtab) ? curwin : tp->tp_curwin;
17112 if (argvar->v_type != VAR_UNKNOWN)
17114 arg = get_tv_string_chk(argvar);
17115 if (arg == NULL)
17116 nr = 0; /* type error; errmsg already given */
17117 else if (STRCMP(arg, "$") == 0)
17118 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
17119 else if (STRCMP(arg, "#") == 0)
17121 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
17122 if (twin == NULL)
17123 nr = 0;
17125 else
17127 EMSG2(_(e_invexpr2), arg);
17128 nr = 0;
17132 if (nr > 0)
17133 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
17134 wp != twin; wp = wp->w_next)
17136 if (wp == NULL)
17138 /* didn't find it in this tabpage */
17139 nr = 0;
17140 break;
17142 ++nr;
17144 return nr;
17146 #endif
17149 * "tabpagewinnr()" function
17151 static void
17152 f_tabpagewinnr(argvars, rettv)
17153 typval_T *argvars UNUSED;
17154 typval_T *rettv;
17156 int nr = 1;
17157 #ifdef FEAT_WINDOWS
17158 tabpage_T *tp;
17160 tp = find_tabpage((int)get_tv_number(&argvars[0]));
17161 if (tp == NULL)
17162 nr = 0;
17163 else
17164 nr = get_winnr(tp, &argvars[1]);
17165 #endif
17166 rettv->vval.v_number = nr;
17171 * "tagfiles()" function
17173 static void
17174 f_tagfiles(argvars, rettv)
17175 typval_T *argvars UNUSED;
17176 typval_T *rettv;
17178 char_u fname[MAXPATHL + 1];
17179 tagname_T tn;
17180 int first;
17182 if (rettv_list_alloc(rettv) == FAIL)
17183 return;
17185 for (first = TRUE; ; first = FALSE)
17186 if (get_tagfname(&tn, first, fname) == FAIL
17187 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
17188 break;
17189 tagname_free(&tn);
17193 * "taglist()" function
17195 static void
17196 f_taglist(argvars, rettv)
17197 typval_T *argvars;
17198 typval_T *rettv;
17200 char_u *tag_pattern;
17202 tag_pattern = get_tv_string(&argvars[0]);
17204 rettv->vval.v_number = FALSE;
17205 if (*tag_pattern == NUL)
17206 return;
17208 if (rettv_list_alloc(rettv) == OK)
17209 (void)get_tags(rettv->vval.v_list, tag_pattern);
17213 * "tempname()" function
17215 static void
17216 f_tempname(argvars, rettv)
17217 typval_T *argvars UNUSED;
17218 typval_T *rettv;
17220 static int x = 'A';
17222 rettv->v_type = VAR_STRING;
17223 rettv->vval.v_string = vim_tempname(x);
17225 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
17226 * names. Skip 'I' and 'O', they are used for shell redirection. */
17229 if (x == 'Z')
17230 x = '0';
17231 else if (x == '9')
17232 x = 'A';
17233 else
17235 #ifdef EBCDIC
17236 if (x == 'I')
17237 x = 'J';
17238 else if (x == 'R')
17239 x = 'S';
17240 else
17241 #endif
17242 ++x;
17244 } while (x == 'I' || x == 'O');
17248 * "test(list)" function: Just checking the walls...
17250 static void
17251 f_test(argvars, rettv)
17252 typval_T *argvars UNUSED;
17253 typval_T *rettv UNUSED;
17255 /* Used for unit testing. Change the code below to your liking. */
17256 #if 0
17257 listitem_T *li;
17258 list_T *l;
17259 char_u *bad, *good;
17261 if (argvars[0].v_type != VAR_LIST)
17262 return;
17263 l = argvars[0].vval.v_list;
17264 if (l == NULL)
17265 return;
17266 li = l->lv_first;
17267 if (li == NULL)
17268 return;
17269 bad = get_tv_string(&li->li_tv);
17270 li = li->li_next;
17271 if (li == NULL)
17272 return;
17273 good = get_tv_string(&li->li_tv);
17274 rettv->vval.v_number = test_edit_score(bad, good);
17275 #endif
17279 * "tolower(string)" function
17281 static void
17282 f_tolower(argvars, rettv)
17283 typval_T *argvars;
17284 typval_T *rettv;
17286 char_u *p;
17288 p = vim_strsave(get_tv_string(&argvars[0]));
17289 rettv->v_type = VAR_STRING;
17290 rettv->vval.v_string = p;
17292 if (p != NULL)
17293 while (*p != NUL)
17295 #ifdef FEAT_MBYTE
17296 int l;
17298 if (enc_utf8)
17300 int c, lc;
17302 c = utf_ptr2char(p);
17303 lc = utf_tolower(c);
17304 l = utf_ptr2len(p);
17305 /* TODO: reallocate string when byte count changes. */
17306 if (utf_char2len(lc) == l)
17307 utf_char2bytes(lc, p);
17308 p += l;
17310 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
17311 p += l; /* skip multi-byte character */
17312 else
17313 #endif
17315 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
17316 ++p;
17322 * "toupper(string)" function
17324 static void
17325 f_toupper(argvars, rettv)
17326 typval_T *argvars;
17327 typval_T *rettv;
17329 rettv->v_type = VAR_STRING;
17330 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
17334 * "tr(string, fromstr, tostr)" function
17336 static void
17337 f_tr(argvars, rettv)
17338 typval_T *argvars;
17339 typval_T *rettv;
17341 char_u *instr;
17342 char_u *fromstr;
17343 char_u *tostr;
17344 char_u *p;
17345 #ifdef FEAT_MBYTE
17346 int inlen;
17347 int fromlen;
17348 int tolen;
17349 int idx;
17350 char_u *cpstr;
17351 int cplen;
17352 int first = TRUE;
17353 #endif
17354 char_u buf[NUMBUFLEN];
17355 char_u buf2[NUMBUFLEN];
17356 garray_T ga;
17358 instr = get_tv_string(&argvars[0]);
17359 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
17360 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
17362 /* Default return value: empty string. */
17363 rettv->v_type = VAR_STRING;
17364 rettv->vval.v_string = NULL;
17365 if (fromstr == NULL || tostr == NULL)
17366 return; /* type error; errmsg already given */
17367 ga_init2(&ga, (int)sizeof(char), 80);
17369 #ifdef FEAT_MBYTE
17370 if (!has_mbyte)
17371 #endif
17372 /* not multi-byte: fromstr and tostr must be the same length */
17373 if (STRLEN(fromstr) != STRLEN(tostr))
17375 #ifdef FEAT_MBYTE
17376 error:
17377 #endif
17378 EMSG2(_(e_invarg2), fromstr);
17379 ga_clear(&ga);
17380 return;
17383 /* fromstr and tostr have to contain the same number of chars */
17384 while (*instr != NUL)
17386 #ifdef FEAT_MBYTE
17387 if (has_mbyte)
17389 inlen = (*mb_ptr2len)(instr);
17390 cpstr = instr;
17391 cplen = inlen;
17392 idx = 0;
17393 for (p = fromstr; *p != NUL; p += fromlen)
17395 fromlen = (*mb_ptr2len)(p);
17396 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
17398 for (p = tostr; *p != NUL; p += tolen)
17400 tolen = (*mb_ptr2len)(p);
17401 if (idx-- == 0)
17403 cplen = tolen;
17404 cpstr = p;
17405 break;
17408 if (*p == NUL) /* tostr is shorter than fromstr */
17409 goto error;
17410 break;
17412 ++idx;
17415 if (first && cpstr == instr)
17417 /* Check that fromstr and tostr have the same number of
17418 * (multi-byte) characters. Done only once when a character
17419 * of instr doesn't appear in fromstr. */
17420 first = FALSE;
17421 for (p = tostr; *p != NUL; p += tolen)
17423 tolen = (*mb_ptr2len)(p);
17424 --idx;
17426 if (idx != 0)
17427 goto error;
17430 ga_grow(&ga, cplen);
17431 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
17432 ga.ga_len += cplen;
17434 instr += inlen;
17436 else
17437 #endif
17439 /* When not using multi-byte chars we can do it faster. */
17440 p = vim_strchr(fromstr, *instr);
17441 if (p != NULL)
17442 ga_append(&ga, tostr[p - fromstr]);
17443 else
17444 ga_append(&ga, *instr);
17445 ++instr;
17449 /* add a terminating NUL */
17450 ga_grow(&ga, 1);
17451 ga_append(&ga, NUL);
17453 rettv->vval.v_string = ga.ga_data;
17456 #ifdef FEAT_FLOAT
17458 * "trunc({float})" function
17460 static void
17461 f_trunc(argvars, rettv)
17462 typval_T *argvars;
17463 typval_T *rettv;
17465 float_T f;
17467 rettv->v_type = VAR_FLOAT;
17468 if (get_float_arg(argvars, &f) == OK)
17469 /* trunc() is not in C90, use floor() or ceil() instead. */
17470 rettv->vval.v_float = f > 0 ? floor(f) : ceil(f);
17471 else
17472 rettv->vval.v_float = 0.0;
17474 #endif
17477 * "type(expr)" function
17479 static void
17480 f_type(argvars, rettv)
17481 typval_T *argvars;
17482 typval_T *rettv;
17484 int n;
17486 switch (argvars[0].v_type)
17488 case VAR_NUMBER: n = 0; break;
17489 case VAR_STRING: n = 1; break;
17490 case VAR_FUNC: n = 2; break;
17491 case VAR_LIST: n = 3; break;
17492 case VAR_DICT: n = 4; break;
17493 #ifdef FEAT_FLOAT
17494 case VAR_FLOAT: n = 5; break;
17495 #endif
17496 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
17498 rettv->vval.v_number = n;
17502 * "values(dict)" function
17504 static void
17505 f_values(argvars, rettv)
17506 typval_T *argvars;
17507 typval_T *rettv;
17509 dict_list(argvars, rettv, 1);
17513 * "virtcol(string)" function
17515 static void
17516 f_virtcol(argvars, rettv)
17517 typval_T *argvars;
17518 typval_T *rettv;
17520 colnr_T vcol = 0;
17521 pos_T *fp;
17522 int fnum = curbuf->b_fnum;
17524 fp = var2fpos(&argvars[0], FALSE, &fnum);
17525 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
17526 && fnum == curbuf->b_fnum)
17528 getvvcol(curwin, fp, NULL, NULL, &vcol);
17529 ++vcol;
17532 rettv->vval.v_number = vcol;
17536 * "visualmode()" function
17538 static void
17539 f_visualmode(argvars, rettv)
17540 typval_T *argvars UNUSED;
17541 typval_T *rettv UNUSED;
17543 #ifdef FEAT_VISUAL
17544 char_u str[2];
17546 rettv->v_type = VAR_STRING;
17547 str[0] = curbuf->b_visual_mode_eval;
17548 str[1] = NUL;
17549 rettv->vval.v_string = vim_strsave(str);
17551 /* A non-zero number or non-empty string argument: reset mode. */
17552 if (non_zero_arg(&argvars[0]))
17553 curbuf->b_visual_mode_eval = NUL;
17554 #endif
17558 * "winbufnr(nr)" function
17560 static void
17561 f_winbufnr(argvars, rettv)
17562 typval_T *argvars;
17563 typval_T *rettv;
17565 win_T *wp;
17567 wp = find_win_by_nr(&argvars[0], NULL);
17568 if (wp == NULL)
17569 rettv->vval.v_number = -1;
17570 else
17571 rettv->vval.v_number = wp->w_buffer->b_fnum;
17575 * "wincol()" function
17577 static void
17578 f_wincol(argvars, rettv)
17579 typval_T *argvars UNUSED;
17580 typval_T *rettv;
17582 validate_cursor();
17583 rettv->vval.v_number = curwin->w_wcol + 1;
17587 * "winheight(nr)" function
17589 static void
17590 f_winheight(argvars, rettv)
17591 typval_T *argvars;
17592 typval_T *rettv;
17594 win_T *wp;
17596 wp = find_win_by_nr(&argvars[0], NULL);
17597 if (wp == NULL)
17598 rettv->vval.v_number = -1;
17599 else
17600 rettv->vval.v_number = wp->w_height;
17604 * "winline()" function
17606 static void
17607 f_winline(argvars, rettv)
17608 typval_T *argvars UNUSED;
17609 typval_T *rettv;
17611 validate_cursor();
17612 rettv->vval.v_number = curwin->w_wrow + 1;
17616 * "winnr()" function
17618 static void
17619 f_winnr(argvars, rettv)
17620 typval_T *argvars UNUSED;
17621 typval_T *rettv;
17623 int nr = 1;
17625 #ifdef FEAT_WINDOWS
17626 nr = get_winnr(curtab, &argvars[0]);
17627 #endif
17628 rettv->vval.v_number = nr;
17632 * "winrestcmd()" function
17634 static void
17635 f_winrestcmd(argvars, rettv)
17636 typval_T *argvars UNUSED;
17637 typval_T *rettv;
17639 #ifdef FEAT_WINDOWS
17640 win_T *wp;
17641 int winnr = 1;
17642 garray_T ga;
17643 char_u buf[50];
17645 ga_init2(&ga, (int)sizeof(char), 70);
17646 for (wp = firstwin; wp != NULL; wp = wp->w_next)
17648 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
17649 ga_concat(&ga, buf);
17650 # ifdef FEAT_VERTSPLIT
17651 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
17652 ga_concat(&ga, buf);
17653 # endif
17654 ++winnr;
17656 ga_append(&ga, NUL);
17658 rettv->vval.v_string = ga.ga_data;
17659 #else
17660 rettv->vval.v_string = NULL;
17661 #endif
17662 rettv->v_type = VAR_STRING;
17666 * "winrestview()" function
17668 static void
17669 f_winrestview(argvars, rettv)
17670 typval_T *argvars;
17671 typval_T *rettv UNUSED;
17673 dict_T *dict;
17675 if (argvars[0].v_type != VAR_DICT
17676 || (dict = argvars[0].vval.v_dict) == NULL)
17677 EMSG(_(e_invarg));
17678 else
17680 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
17681 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
17682 #ifdef FEAT_VIRTUALEDIT
17683 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
17684 #endif
17685 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
17686 curwin->w_set_curswant = FALSE;
17688 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
17689 #ifdef FEAT_DIFF
17690 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
17691 #endif
17692 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
17693 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
17695 check_cursor();
17696 changed_cline_bef_curs();
17697 invalidate_botline();
17698 redraw_later(VALID);
17700 if (curwin->w_topline == 0)
17701 curwin->w_topline = 1;
17702 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
17703 curwin->w_topline = curbuf->b_ml.ml_line_count;
17704 #ifdef FEAT_DIFF
17705 check_topfill(curwin, TRUE);
17706 #endif
17711 * "winsaveview()" function
17713 static void
17714 f_winsaveview(argvars, rettv)
17715 typval_T *argvars UNUSED;
17716 typval_T *rettv;
17718 dict_T *dict;
17720 dict = dict_alloc();
17721 if (dict == NULL)
17722 return;
17723 rettv->v_type = VAR_DICT;
17724 rettv->vval.v_dict = dict;
17725 ++dict->dv_refcount;
17727 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
17728 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
17729 #ifdef FEAT_VIRTUALEDIT
17730 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
17731 #endif
17732 update_curswant();
17733 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
17735 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
17736 #ifdef FEAT_DIFF
17737 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
17738 #endif
17739 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
17740 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
17744 * "winwidth(nr)" function
17746 static void
17747 f_winwidth(argvars, rettv)
17748 typval_T *argvars;
17749 typval_T *rettv;
17751 win_T *wp;
17753 wp = find_win_by_nr(&argvars[0], NULL);
17754 if (wp == NULL)
17755 rettv->vval.v_number = -1;
17756 else
17757 #ifdef FEAT_VERTSPLIT
17758 rettv->vval.v_number = wp->w_width;
17759 #else
17760 rettv->vval.v_number = Columns;
17761 #endif
17765 * "writefile()" function
17767 static void
17768 f_writefile(argvars, rettv)
17769 typval_T *argvars;
17770 typval_T *rettv;
17772 int binary = FALSE;
17773 char_u *fname;
17774 FILE *fd;
17775 listitem_T *li;
17776 char_u *s;
17777 int ret = 0;
17778 int c;
17780 if (check_restricted() || check_secure())
17781 return;
17783 if (argvars[0].v_type != VAR_LIST)
17785 EMSG2(_(e_listarg), "writefile()");
17786 return;
17788 if (argvars[0].vval.v_list == NULL)
17789 return;
17791 if (argvars[2].v_type != VAR_UNKNOWN
17792 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
17793 binary = TRUE;
17795 /* Always open the file in binary mode, library functions have a mind of
17796 * their own about CR-LF conversion. */
17797 fname = get_tv_string(&argvars[1]);
17798 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
17800 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
17801 ret = -1;
17803 else
17805 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
17806 li = li->li_next)
17808 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
17810 if (*s == '\n')
17811 c = putc(NUL, fd);
17812 else
17813 c = putc(*s, fd);
17814 if (c == EOF)
17816 ret = -1;
17817 break;
17820 if (!binary || li->li_next != NULL)
17821 if (putc('\n', fd) == EOF)
17823 ret = -1;
17824 break;
17826 if (ret < 0)
17828 EMSG(_(e_write));
17829 break;
17832 fclose(fd);
17835 rettv->vval.v_number = ret;
17839 * Translate a String variable into a position.
17840 * Returns NULL when there is an error.
17842 static pos_T *
17843 var2fpos(varp, dollar_lnum, fnum)
17844 typval_T *varp;
17845 int dollar_lnum; /* TRUE when $ is last line */
17846 int *fnum; /* set to fnum for '0, 'A, etc. */
17848 char_u *name;
17849 static pos_T pos;
17850 pos_T *pp;
17852 /* Argument can be [lnum, col, coladd]. */
17853 if (varp->v_type == VAR_LIST)
17855 list_T *l;
17856 int len;
17857 int error = FALSE;
17858 listitem_T *li;
17860 l = varp->vval.v_list;
17861 if (l == NULL)
17862 return NULL;
17864 /* Get the line number */
17865 pos.lnum = list_find_nr(l, 0L, &error);
17866 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
17867 return NULL; /* invalid line number */
17869 /* Get the column number */
17870 pos.col = list_find_nr(l, 1L, &error);
17871 if (error)
17872 return NULL;
17873 len = (long)STRLEN(ml_get(pos.lnum));
17875 /* We accept "$" for the column number: last column. */
17876 li = list_find(l, 1L);
17877 if (li != NULL && li->li_tv.v_type == VAR_STRING
17878 && li->li_tv.vval.v_string != NULL
17879 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
17880 pos.col = len + 1;
17882 /* Accept a position up to the NUL after the line. */
17883 if (pos.col == 0 || (int)pos.col > len + 1)
17884 return NULL; /* invalid column number */
17885 --pos.col;
17887 #ifdef FEAT_VIRTUALEDIT
17888 /* Get the virtual offset. Defaults to zero. */
17889 pos.coladd = list_find_nr(l, 2L, &error);
17890 if (error)
17891 pos.coladd = 0;
17892 #endif
17894 return &pos;
17897 name = get_tv_string_chk(varp);
17898 if (name == NULL)
17899 return NULL;
17900 if (name[0] == '.') /* cursor */
17901 return &curwin->w_cursor;
17902 #ifdef FEAT_VISUAL
17903 if (name[0] == 'v' && name[1] == NUL) /* Visual start */
17905 if (VIsual_active)
17906 return &VIsual;
17907 return &curwin->w_cursor;
17909 #endif
17910 if (name[0] == '\'') /* mark */
17912 pp = getmark_fnum(name[1], FALSE, fnum);
17913 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
17914 return NULL;
17915 return pp;
17918 #ifdef FEAT_VIRTUALEDIT
17919 pos.coladd = 0;
17920 #endif
17922 if (name[0] == 'w' && dollar_lnum)
17924 pos.col = 0;
17925 if (name[1] == '0') /* "w0": first visible line */
17927 update_topline();
17928 pos.lnum = curwin->w_topline;
17929 return &pos;
17931 else if (name[1] == '$') /* "w$": last visible line */
17933 validate_botline();
17934 pos.lnum = curwin->w_botline - 1;
17935 return &pos;
17938 else if (name[0] == '$') /* last column or line */
17940 if (dollar_lnum)
17942 pos.lnum = curbuf->b_ml.ml_line_count;
17943 pos.col = 0;
17945 else
17947 pos.lnum = curwin->w_cursor.lnum;
17948 pos.col = (colnr_T)STRLEN(ml_get_curline());
17950 return &pos;
17952 return NULL;
17956 * Convert list in "arg" into a position and optional file number.
17957 * When "fnump" is NULL there is no file number, only 3 items.
17958 * Note that the column is passed on as-is, the caller may want to decrement
17959 * it to use 1 for the first column.
17960 * Return FAIL when conversion is not possible, doesn't check the position for
17961 * validity.
17963 static int
17964 list2fpos(arg, posp, fnump)
17965 typval_T *arg;
17966 pos_T *posp;
17967 int *fnump;
17969 list_T *l = arg->vval.v_list;
17970 long i = 0;
17971 long n;
17973 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
17974 * when "fnump" isn't NULL and "coladd" is optional. */
17975 if (arg->v_type != VAR_LIST
17976 || l == NULL
17977 || l->lv_len < (fnump == NULL ? 2 : 3)
17978 || l->lv_len > (fnump == NULL ? 3 : 4))
17979 return FAIL;
17981 if (fnump != NULL)
17983 n = list_find_nr(l, i++, NULL); /* fnum */
17984 if (n < 0)
17985 return FAIL;
17986 if (n == 0)
17987 n = curbuf->b_fnum; /* current buffer */
17988 *fnump = n;
17991 n = list_find_nr(l, i++, NULL); /* lnum */
17992 if (n < 0)
17993 return FAIL;
17994 posp->lnum = n;
17996 n = list_find_nr(l, i++, NULL); /* col */
17997 if (n < 0)
17998 return FAIL;
17999 posp->col = n;
18001 #ifdef FEAT_VIRTUALEDIT
18002 n = list_find_nr(l, i, NULL);
18003 if (n < 0)
18004 posp->coladd = 0;
18005 else
18006 posp->coladd = n;
18007 #endif
18009 return OK;
18013 * Get the length of an environment variable name.
18014 * Advance "arg" to the first character after the name.
18015 * Return 0 for error.
18017 static int
18018 get_env_len(arg)
18019 char_u **arg;
18021 char_u *p;
18022 int len;
18024 for (p = *arg; vim_isIDc(*p); ++p)
18026 if (p == *arg) /* no name found */
18027 return 0;
18029 len = (int)(p - *arg);
18030 *arg = p;
18031 return len;
18035 * Get the length of the name of a function or internal variable.
18036 * "arg" is advanced to the first non-white character after the name.
18037 * Return 0 if something is wrong.
18039 static int
18040 get_id_len(arg)
18041 char_u **arg;
18043 char_u *p;
18044 int len;
18046 /* Find the end of the name. */
18047 for (p = *arg; eval_isnamec(*p); ++p)
18049 if (p == *arg) /* no name found */
18050 return 0;
18052 len = (int)(p - *arg);
18053 *arg = skipwhite(p);
18055 return len;
18059 * Get the length of the name of a variable or function.
18060 * Only the name is recognized, does not handle ".key" or "[idx]".
18061 * "arg" is advanced to the first non-white character after the name.
18062 * Return -1 if curly braces expansion failed.
18063 * Return 0 if something else is wrong.
18064 * If the name contains 'magic' {}'s, expand them and return the
18065 * expanded name in an allocated string via 'alias' - caller must free.
18067 static int
18068 get_name_len(arg, alias, evaluate, verbose)
18069 char_u **arg;
18070 char_u **alias;
18071 int evaluate;
18072 int verbose;
18074 int len;
18075 char_u *p;
18076 char_u *expr_start;
18077 char_u *expr_end;
18079 *alias = NULL; /* default to no alias */
18081 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
18082 && (*arg)[2] == (int)KE_SNR)
18084 /* hard coded <SNR>, already translated */
18085 *arg += 3;
18086 return get_id_len(arg) + 3;
18088 len = eval_fname_script(*arg);
18089 if (len > 0)
18091 /* literal "<SID>", "s:" or "<SNR>" */
18092 *arg += len;
18096 * Find the end of the name; check for {} construction.
18098 p = find_name_end(*arg, &expr_start, &expr_end,
18099 len > 0 ? 0 : FNE_CHECK_START);
18100 if (expr_start != NULL)
18102 char_u *temp_string;
18104 if (!evaluate)
18106 len += (int)(p - *arg);
18107 *arg = skipwhite(p);
18108 return len;
18112 * Include any <SID> etc in the expanded string:
18113 * Thus the -len here.
18115 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
18116 if (temp_string == NULL)
18117 return -1;
18118 *alias = temp_string;
18119 *arg = skipwhite(p);
18120 return (int)STRLEN(temp_string);
18123 len += get_id_len(arg);
18124 if (len == 0 && verbose)
18125 EMSG2(_(e_invexpr2), *arg);
18127 return len;
18131 * Find the end of a variable or function name, taking care of magic braces.
18132 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
18133 * start and end of the first magic braces item.
18134 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
18135 * Return a pointer to just after the name. Equal to "arg" if there is no
18136 * valid name.
18138 static char_u *
18139 find_name_end(arg, expr_start, expr_end, flags)
18140 char_u *arg;
18141 char_u **expr_start;
18142 char_u **expr_end;
18143 int flags;
18145 int mb_nest = 0;
18146 int br_nest = 0;
18147 char_u *p;
18149 if (expr_start != NULL)
18151 *expr_start = NULL;
18152 *expr_end = NULL;
18155 /* Quick check for valid starting character. */
18156 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
18157 return arg;
18159 for (p = arg; *p != NUL
18160 && (eval_isnamec(*p)
18161 || *p == '{'
18162 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
18163 || mb_nest != 0
18164 || br_nest != 0); mb_ptr_adv(p))
18166 if (*p == '\'')
18168 /* skip over 'string' to avoid counting [ and ] inside it. */
18169 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
18171 if (*p == NUL)
18172 break;
18174 else if (*p == '"')
18176 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
18177 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
18178 if (*p == '\\' && p[1] != NUL)
18179 ++p;
18180 if (*p == NUL)
18181 break;
18184 if (mb_nest == 0)
18186 if (*p == '[')
18187 ++br_nest;
18188 else if (*p == ']')
18189 --br_nest;
18192 if (br_nest == 0)
18194 if (*p == '{')
18196 mb_nest++;
18197 if (expr_start != NULL && *expr_start == NULL)
18198 *expr_start = p;
18200 else if (*p == '}')
18202 mb_nest--;
18203 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
18204 *expr_end = p;
18209 return p;
18213 * Expands out the 'magic' {}'s in a variable/function name.
18214 * Note that this can call itself recursively, to deal with
18215 * constructs like foo{bar}{baz}{bam}
18216 * The four pointer arguments point to "foo{expre}ss{ion}bar"
18217 * "in_start" ^
18218 * "expr_start" ^
18219 * "expr_end" ^
18220 * "in_end" ^
18222 * Returns a new allocated string, which the caller must free.
18223 * Returns NULL for failure.
18225 static char_u *
18226 make_expanded_name(in_start, expr_start, expr_end, in_end)
18227 char_u *in_start;
18228 char_u *expr_start;
18229 char_u *expr_end;
18230 char_u *in_end;
18232 char_u c1;
18233 char_u *retval = NULL;
18234 char_u *temp_result;
18235 char_u *nextcmd = NULL;
18237 if (expr_end == NULL || in_end == NULL)
18238 return NULL;
18239 *expr_start = NUL;
18240 *expr_end = NUL;
18241 c1 = *in_end;
18242 *in_end = NUL;
18244 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
18245 if (temp_result != NULL && nextcmd == NULL)
18247 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
18248 + (in_end - expr_end) + 1));
18249 if (retval != NULL)
18251 STRCPY(retval, in_start);
18252 STRCAT(retval, temp_result);
18253 STRCAT(retval, expr_end + 1);
18256 vim_free(temp_result);
18258 *in_end = c1; /* put char back for error messages */
18259 *expr_start = '{';
18260 *expr_end = '}';
18262 if (retval != NULL)
18264 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
18265 if (expr_start != NULL)
18267 /* Further expansion! */
18268 temp_result = make_expanded_name(retval, expr_start,
18269 expr_end, temp_result);
18270 vim_free(retval);
18271 retval = temp_result;
18275 return retval;
18279 * Return TRUE if character "c" can be used in a variable or function name.
18280 * Does not include '{' or '}' for magic braces.
18282 static int
18283 eval_isnamec(c)
18284 int c;
18286 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
18290 * Return TRUE if character "c" can be used as the first character in a
18291 * variable or function name (excluding '{' and '}').
18293 static int
18294 eval_isnamec1(c)
18295 int c;
18297 return (ASCII_ISALPHA(c) || c == '_');
18301 * Set number v: variable to "val".
18303 void
18304 set_vim_var_nr(idx, val)
18305 int idx;
18306 long val;
18308 vimvars[idx].vv_nr = val;
18312 * Get number v: variable value.
18314 long
18315 get_vim_var_nr(idx)
18316 int idx;
18318 return vimvars[idx].vv_nr;
18322 * Get string v: variable value. Uses a static buffer, can only be used once.
18324 char_u *
18325 get_vim_var_str(idx)
18326 int idx;
18328 return get_tv_string(&vimvars[idx].vv_tv);
18332 * Get List v: variable value. Caller must take care of reference count when
18333 * needed.
18335 list_T *
18336 get_vim_var_list(idx)
18337 int idx;
18339 return vimvars[idx].vv_list;
18343 * Set v:char to character "c".
18345 void
18346 set_vim_var_char(c)
18347 int c;
18349 #ifdef FEAT_MBYTE
18350 char_u buf[MB_MAXBYTES];
18351 #else
18352 char_u buf[2];
18353 #endif
18355 #ifdef FEAT_MBYTE
18356 if (has_mbyte)
18357 buf[(*mb_char2bytes)(c, buf)] = NUL;
18358 else
18359 #endif
18361 buf[0] = c;
18362 buf[1] = NUL;
18364 set_vim_var_string(VV_CHAR, buf, -1);
18368 * Set v:count to "count" and v:count1 to "count1".
18369 * When "set_prevcount" is TRUE first set v:prevcount from v:count.
18371 void
18372 set_vcount(count, count1, set_prevcount)
18373 long count;
18374 long count1;
18375 int set_prevcount;
18377 if (set_prevcount)
18378 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
18379 vimvars[VV_COUNT].vv_nr = count;
18380 vimvars[VV_COUNT1].vv_nr = count1;
18384 * Set string v: variable to a copy of "val".
18386 void
18387 set_vim_var_string(idx, val, len)
18388 int idx;
18389 char_u *val;
18390 int len; /* length of "val" to use or -1 (whole string) */
18392 /* Need to do this (at least) once, since we can't initialize a union.
18393 * Will always be invoked when "v:progname" is set. */
18394 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
18396 vim_free(vimvars[idx].vv_str);
18397 if (val == NULL)
18398 vimvars[idx].vv_str = NULL;
18399 else if (len == -1)
18400 vimvars[idx].vv_str = vim_strsave(val);
18401 else
18402 vimvars[idx].vv_str = vim_strnsave(val, len);
18406 * Set List v: variable to "val".
18408 void
18409 set_vim_var_list(idx, val)
18410 int idx;
18411 list_T *val;
18413 list_unref(vimvars[idx].vv_list);
18414 vimvars[idx].vv_list = val;
18415 if (val != NULL)
18416 ++val->lv_refcount;
18420 * Set v:register if needed.
18422 void
18423 set_reg_var(c)
18424 int c;
18426 char_u regname;
18428 if (c == 0 || c == ' ')
18429 regname = '"';
18430 else
18431 regname = c;
18432 /* Avoid free/alloc when the value is already right. */
18433 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
18434 set_vim_var_string(VV_REG, &regname, 1);
18438 * Get or set v:exception. If "oldval" == NULL, return the current value.
18439 * Otherwise, restore the value to "oldval" and return NULL.
18440 * Must always be called in pairs to save and restore v:exception! Does not
18441 * take care of memory allocations.
18443 char_u *
18444 v_exception(oldval)
18445 char_u *oldval;
18447 if (oldval == NULL)
18448 return vimvars[VV_EXCEPTION].vv_str;
18450 vimvars[VV_EXCEPTION].vv_str = oldval;
18451 return NULL;
18455 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
18456 * Otherwise, restore the value to "oldval" and return NULL.
18457 * Must always be called in pairs to save and restore v:throwpoint! Does not
18458 * take care of memory allocations.
18460 char_u *
18461 v_throwpoint(oldval)
18462 char_u *oldval;
18464 if (oldval == NULL)
18465 return vimvars[VV_THROWPOINT].vv_str;
18467 vimvars[VV_THROWPOINT].vv_str = oldval;
18468 return NULL;
18471 #if defined(FEAT_AUTOCMD) || defined(PROTO)
18473 * Set v:cmdarg.
18474 * If "eap" != NULL, use "eap" to generate the value and return the old value.
18475 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
18476 * Must always be called in pairs!
18478 char_u *
18479 set_cmdarg(eap, oldarg)
18480 exarg_T *eap;
18481 char_u *oldarg;
18483 char_u *oldval;
18484 char_u *newval;
18485 unsigned len;
18487 oldval = vimvars[VV_CMDARG].vv_str;
18488 if (eap == NULL)
18490 vim_free(oldval);
18491 vimvars[VV_CMDARG].vv_str = oldarg;
18492 return NULL;
18495 if (eap->force_bin == FORCE_BIN)
18496 len = 6;
18497 else if (eap->force_bin == FORCE_NOBIN)
18498 len = 8;
18499 else
18500 len = 0;
18502 if (eap->read_edit)
18503 len += 7;
18505 if (eap->force_ff != 0)
18506 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
18507 # ifdef FEAT_MBYTE
18508 if (eap->force_enc != 0)
18509 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
18510 if (eap->bad_char != 0)
18511 len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
18512 # endif
18514 newval = alloc(len + 1);
18515 if (newval == NULL)
18516 return NULL;
18518 if (eap->force_bin == FORCE_BIN)
18519 sprintf((char *)newval, " ++bin");
18520 else if (eap->force_bin == FORCE_NOBIN)
18521 sprintf((char *)newval, " ++nobin");
18522 else
18523 *newval = NUL;
18525 if (eap->read_edit)
18526 STRCAT(newval, " ++edit");
18528 if (eap->force_ff != 0)
18529 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
18530 eap->cmd + eap->force_ff);
18531 # ifdef FEAT_MBYTE
18532 if (eap->force_enc != 0)
18533 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
18534 eap->cmd + eap->force_enc);
18535 if (eap->bad_char != 0)
18536 sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
18537 eap->cmd + eap->bad_char);
18538 # endif
18539 vimvars[VV_CMDARG].vv_str = newval;
18540 return oldval;
18542 #endif
18545 * Get the value of internal variable "name".
18546 * Return OK or FAIL.
18548 static int
18549 get_var_tv(name, len, rettv, verbose)
18550 char_u *name;
18551 int len; /* length of "name" */
18552 typval_T *rettv; /* NULL when only checking existence */
18553 int verbose; /* may give error message */
18555 int ret = OK;
18556 typval_T *tv = NULL;
18557 typval_T atv;
18558 dictitem_T *v;
18559 int cc;
18561 /* truncate the name, so that we can use strcmp() */
18562 cc = name[len];
18563 name[len] = NUL;
18566 * Check for "b:changedtick".
18568 if (STRCMP(name, "b:changedtick") == 0)
18570 atv.v_type = VAR_NUMBER;
18571 atv.vval.v_number = curbuf->b_changedtick;
18572 tv = &atv;
18576 * Check for user-defined variables.
18578 else
18580 v = find_var(name, NULL);
18581 if (v != NULL)
18582 tv = &v->di_tv;
18585 if (tv == NULL)
18587 if (rettv != NULL && verbose)
18588 EMSG2(_(e_undefvar), name);
18589 ret = FAIL;
18591 else if (rettv != NULL)
18592 copy_tv(tv, rettv);
18594 name[len] = cc;
18596 return ret;
18600 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
18601 * Also handle function call with Funcref variable: func(expr)
18602 * Can all be combined: dict.func(expr)[idx]['func'](expr)
18604 static int
18605 handle_subscript(arg, rettv, evaluate, verbose)
18606 char_u **arg;
18607 typval_T *rettv;
18608 int evaluate; /* do more than finding the end */
18609 int verbose; /* give error messages */
18611 int ret = OK;
18612 dict_T *selfdict = NULL;
18613 char_u *s;
18614 int len;
18615 typval_T functv;
18617 while (ret == OK
18618 && (**arg == '['
18619 || (**arg == '.' && rettv->v_type == VAR_DICT)
18620 || (**arg == '(' && rettv->v_type == VAR_FUNC))
18621 && !vim_iswhite(*(*arg - 1)))
18623 if (**arg == '(')
18625 /* need to copy the funcref so that we can clear rettv */
18626 functv = *rettv;
18627 rettv->v_type = VAR_UNKNOWN;
18629 /* Invoke the function. Recursive! */
18630 s = functv.vval.v_string;
18631 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
18632 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
18633 &len, evaluate, selfdict);
18635 /* Clear the funcref afterwards, so that deleting it while
18636 * evaluating the arguments is possible (see test55). */
18637 clear_tv(&functv);
18639 /* Stop the expression evaluation when immediately aborting on
18640 * error, or when an interrupt occurred or an exception was thrown
18641 * but not caught. */
18642 if (aborting())
18644 if (ret == OK)
18645 clear_tv(rettv);
18646 ret = FAIL;
18648 dict_unref(selfdict);
18649 selfdict = NULL;
18651 else /* **arg == '[' || **arg == '.' */
18653 dict_unref(selfdict);
18654 if (rettv->v_type == VAR_DICT)
18656 selfdict = rettv->vval.v_dict;
18657 if (selfdict != NULL)
18658 ++selfdict->dv_refcount;
18660 else
18661 selfdict = NULL;
18662 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
18664 clear_tv(rettv);
18665 ret = FAIL;
18669 dict_unref(selfdict);
18670 return ret;
18674 * Allocate memory for a variable type-value, and make it empty (0 or NULL
18675 * value).
18677 static typval_T *
18678 alloc_tv()
18680 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
18684 * Allocate memory for a variable type-value, and assign a string to it.
18685 * The string "s" must have been allocated, it is consumed.
18686 * Return NULL for out of memory, the variable otherwise.
18688 static typval_T *
18689 alloc_string_tv(s)
18690 char_u *s;
18692 typval_T *rettv;
18694 rettv = alloc_tv();
18695 if (rettv != NULL)
18697 rettv->v_type = VAR_STRING;
18698 rettv->vval.v_string = s;
18700 else
18701 vim_free(s);
18702 return rettv;
18706 * Free the memory for a variable type-value.
18708 void
18709 free_tv(varp)
18710 typval_T *varp;
18712 if (varp != NULL)
18714 switch (varp->v_type)
18716 case VAR_FUNC:
18717 func_unref(varp->vval.v_string);
18718 /*FALLTHROUGH*/
18719 case VAR_STRING:
18720 vim_free(varp->vval.v_string);
18721 break;
18722 case VAR_LIST:
18723 list_unref(varp->vval.v_list);
18724 break;
18725 case VAR_DICT:
18726 dict_unref(varp->vval.v_dict);
18727 break;
18728 case VAR_NUMBER:
18729 #ifdef FEAT_FLOAT
18730 case VAR_FLOAT:
18731 #endif
18732 case VAR_UNKNOWN:
18733 break;
18734 default:
18735 EMSG2(_(e_intern2), "free_tv()");
18736 break;
18738 vim_free(varp);
18743 * Free the memory for a variable value and set the value to NULL or 0.
18745 void
18746 clear_tv(varp)
18747 typval_T *varp;
18749 if (varp != NULL)
18751 switch (varp->v_type)
18753 case VAR_FUNC:
18754 func_unref(varp->vval.v_string);
18755 /*FALLTHROUGH*/
18756 case VAR_STRING:
18757 vim_free(varp->vval.v_string);
18758 varp->vval.v_string = NULL;
18759 break;
18760 case VAR_LIST:
18761 list_unref(varp->vval.v_list);
18762 varp->vval.v_list = NULL;
18763 break;
18764 case VAR_DICT:
18765 dict_unref(varp->vval.v_dict);
18766 varp->vval.v_dict = NULL;
18767 break;
18768 case VAR_NUMBER:
18769 varp->vval.v_number = 0;
18770 break;
18771 #ifdef FEAT_FLOAT
18772 case VAR_FLOAT:
18773 varp->vval.v_float = 0.0;
18774 break;
18775 #endif
18776 case VAR_UNKNOWN:
18777 break;
18778 default:
18779 EMSG2(_(e_intern2), "clear_tv()");
18781 varp->v_lock = 0;
18786 * Set the value of a variable to NULL without freeing items.
18788 static void
18789 init_tv(varp)
18790 typval_T *varp;
18792 if (varp != NULL)
18793 vim_memset(varp, 0, sizeof(typval_T));
18797 * Get the number value of a variable.
18798 * If it is a String variable, uses vim_str2nr().
18799 * For incompatible types, return 0.
18800 * get_tv_number_chk() is similar to get_tv_number(), but informs the
18801 * caller of incompatible types: it sets *denote to TRUE if "denote"
18802 * is not NULL or returns -1 otherwise.
18804 static long
18805 get_tv_number(varp)
18806 typval_T *varp;
18808 int error = FALSE;
18810 return get_tv_number_chk(varp, &error); /* return 0L on error */
18813 long
18814 get_tv_number_chk(varp, denote)
18815 typval_T *varp;
18816 int *denote;
18818 long n = 0L;
18820 switch (varp->v_type)
18822 case VAR_NUMBER:
18823 return (long)(varp->vval.v_number);
18824 #ifdef FEAT_FLOAT
18825 case VAR_FLOAT:
18826 EMSG(_("E805: Using a Float as a Number"));
18827 break;
18828 #endif
18829 case VAR_FUNC:
18830 EMSG(_("E703: Using a Funcref as a Number"));
18831 break;
18832 case VAR_STRING:
18833 if (varp->vval.v_string != NULL)
18834 vim_str2nr(varp->vval.v_string, NULL, NULL,
18835 TRUE, TRUE, &n, NULL);
18836 return n;
18837 case VAR_LIST:
18838 EMSG(_("E745: Using a List as a Number"));
18839 break;
18840 case VAR_DICT:
18841 EMSG(_("E728: Using a Dictionary as a Number"));
18842 break;
18843 default:
18844 EMSG2(_(e_intern2), "get_tv_number()");
18845 break;
18847 if (denote == NULL) /* useful for values that must be unsigned */
18848 n = -1;
18849 else
18850 *denote = TRUE;
18851 return n;
18855 * Get the lnum from the first argument.
18856 * Also accepts ".", "$", etc., but that only works for the current buffer.
18857 * Returns -1 on error.
18859 static linenr_T
18860 get_tv_lnum(argvars)
18861 typval_T *argvars;
18863 typval_T rettv;
18864 linenr_T lnum;
18866 lnum = get_tv_number_chk(&argvars[0], NULL);
18867 if (lnum == 0) /* no valid number, try using line() */
18869 rettv.v_type = VAR_NUMBER;
18870 f_line(argvars, &rettv);
18871 lnum = rettv.vval.v_number;
18872 clear_tv(&rettv);
18874 return lnum;
18878 * Get the lnum from the first argument.
18879 * Also accepts "$", then "buf" is used.
18880 * Returns 0 on error.
18882 static linenr_T
18883 get_tv_lnum_buf(argvars, buf)
18884 typval_T *argvars;
18885 buf_T *buf;
18887 if (argvars[0].v_type == VAR_STRING
18888 && argvars[0].vval.v_string != NULL
18889 && argvars[0].vval.v_string[0] == '$'
18890 && buf != NULL)
18891 return buf->b_ml.ml_line_count;
18892 return get_tv_number_chk(&argvars[0], NULL);
18896 * Get the string value of a variable.
18897 * If it is a Number variable, the number is converted into a string.
18898 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
18899 * get_tv_string_buf() uses a given buffer.
18900 * If the String variable has never been set, return an empty string.
18901 * Never returns NULL;
18902 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
18903 * NULL on error.
18905 static char_u *
18906 get_tv_string(varp)
18907 typval_T *varp;
18909 static char_u mybuf[NUMBUFLEN];
18911 return get_tv_string_buf(varp, mybuf);
18914 static char_u *
18915 get_tv_string_buf(varp, buf)
18916 typval_T *varp;
18917 char_u *buf;
18919 char_u *res = get_tv_string_buf_chk(varp, buf);
18921 return res != NULL ? res : (char_u *)"";
18924 char_u *
18925 get_tv_string_chk(varp)
18926 typval_T *varp;
18928 static char_u mybuf[NUMBUFLEN];
18930 return get_tv_string_buf_chk(varp, mybuf);
18933 static char_u *
18934 get_tv_string_buf_chk(varp, buf)
18935 typval_T *varp;
18936 char_u *buf;
18938 switch (varp->v_type)
18940 case VAR_NUMBER:
18941 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
18942 return buf;
18943 case VAR_FUNC:
18944 EMSG(_("E729: using Funcref as a String"));
18945 break;
18946 case VAR_LIST:
18947 EMSG(_("E730: using List as a String"));
18948 break;
18949 case VAR_DICT:
18950 EMSG(_("E731: using Dictionary as a String"));
18951 break;
18952 #ifdef FEAT_FLOAT
18953 case VAR_FLOAT:
18954 EMSG(_("E806: using Float as a String"));
18955 break;
18956 #endif
18957 case VAR_STRING:
18958 if (varp->vval.v_string != NULL)
18959 return varp->vval.v_string;
18960 return (char_u *)"";
18961 default:
18962 EMSG2(_(e_intern2), "get_tv_string_buf()");
18963 break;
18965 return NULL;
18969 * Find variable "name" in the list of variables.
18970 * Return a pointer to it if found, NULL if not found.
18971 * Careful: "a:0" variables don't have a name.
18972 * When "htp" is not NULL we are writing to the variable, set "htp" to the
18973 * hashtab_T used.
18975 static dictitem_T *
18976 find_var(name, htp)
18977 char_u *name;
18978 hashtab_T **htp;
18980 char_u *varname;
18981 hashtab_T *ht;
18983 ht = find_var_ht(name, &varname);
18984 if (htp != NULL)
18985 *htp = ht;
18986 if (ht == NULL)
18987 return NULL;
18988 return find_var_in_ht(ht, varname, htp != NULL);
18992 * Find variable "varname" in hashtab "ht".
18993 * Returns NULL if not found.
18995 static dictitem_T *
18996 find_var_in_ht(ht, varname, writing)
18997 hashtab_T *ht;
18998 char_u *varname;
18999 int writing;
19001 hashitem_T *hi;
19003 if (*varname == NUL)
19005 /* Must be something like "s:", otherwise "ht" would be NULL. */
19006 switch (varname[-2])
19008 case 's': return &SCRIPT_SV(current_SID).sv_var;
19009 case 'g': return &globvars_var;
19010 case 'v': return &vimvars_var;
19011 case 'b': return &curbuf->b_bufvar;
19012 case 'w': return &curwin->w_winvar;
19013 #ifdef FEAT_WINDOWS
19014 case 't': return &curtab->tp_winvar;
19015 #endif
19016 case 'l': return current_funccal == NULL
19017 ? NULL : &current_funccal->l_vars_var;
19018 case 'a': return current_funccal == NULL
19019 ? NULL : &current_funccal->l_avars_var;
19021 return NULL;
19024 hi = hash_find(ht, varname);
19025 if (HASHITEM_EMPTY(hi))
19027 /* For global variables we may try auto-loading the script. If it
19028 * worked find the variable again. Don't auto-load a script if it was
19029 * loaded already, otherwise it would be loaded every time when
19030 * checking if a function name is a Funcref variable. */
19031 if (ht == &globvarht && !writing
19032 && script_autoload(varname, FALSE) && !aborting())
19033 hi = hash_find(ht, varname);
19034 if (HASHITEM_EMPTY(hi))
19035 return NULL;
19037 return HI2DI(hi);
19041 * Find the hashtab used for a variable name.
19042 * Set "varname" to the start of name without ':'.
19044 static hashtab_T *
19045 find_var_ht(name, varname)
19046 char_u *name;
19047 char_u **varname;
19049 hashitem_T *hi;
19051 if (name[1] != ':')
19053 /* The name must not start with a colon or #. */
19054 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
19055 return NULL;
19056 *varname = name;
19058 /* "version" is "v:version" in all scopes */
19059 hi = hash_find(&compat_hashtab, name);
19060 if (!HASHITEM_EMPTY(hi))
19061 return &compat_hashtab;
19063 if (current_funccal == NULL)
19064 return &globvarht; /* global variable */
19065 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
19067 *varname = name + 2;
19068 if (*name == 'g') /* global variable */
19069 return &globvarht;
19070 /* There must be no ':' or '#' in the rest of the name, unless g: is used
19072 if (vim_strchr(name + 2, ':') != NULL
19073 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
19074 return NULL;
19075 if (*name == 'b') /* buffer variable */
19076 return &curbuf->b_vars.dv_hashtab;
19077 if (*name == 'w') /* window variable */
19078 return &curwin->w_vars.dv_hashtab;
19079 #ifdef FEAT_WINDOWS
19080 if (*name == 't') /* tab page variable */
19081 return &curtab->tp_vars.dv_hashtab;
19082 #endif
19083 if (*name == 'v') /* v: variable */
19084 return &vimvarht;
19085 if (*name == 'a' && current_funccal != NULL) /* function argument */
19086 return &current_funccal->l_avars.dv_hashtab;
19087 if (*name == 'l' && current_funccal != NULL) /* local function variable */
19088 return &current_funccal->l_vars.dv_hashtab;
19089 if (*name == 's' /* script variable */
19090 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
19091 return &SCRIPT_VARS(current_SID);
19092 return NULL;
19096 * Get the string value of a (global/local) variable.
19097 * Returns NULL when it doesn't exist.
19099 char_u *
19100 get_var_value(name)
19101 char_u *name;
19103 dictitem_T *v;
19105 v = find_var(name, NULL);
19106 if (v == NULL)
19107 return NULL;
19108 return get_tv_string(&v->di_tv);
19112 * Allocate a new hashtab for a sourced script. It will be used while
19113 * sourcing this script and when executing functions defined in the script.
19115 void
19116 new_script_vars(id)
19117 scid_T id;
19119 int i;
19120 hashtab_T *ht;
19121 scriptvar_T *sv;
19123 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
19125 /* Re-allocating ga_data means that an ht_array pointing to
19126 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
19127 * at its init value. Also reset "v_dict", it's always the same. */
19128 for (i = 1; i <= ga_scripts.ga_len; ++i)
19130 ht = &SCRIPT_VARS(i);
19131 if (ht->ht_mask == HT_INIT_SIZE - 1)
19132 ht->ht_array = ht->ht_smallarray;
19133 sv = &SCRIPT_SV(i);
19134 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
19137 while (ga_scripts.ga_len < id)
19139 sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
19140 init_var_dict(&sv->sv_dict, &sv->sv_var);
19141 ++ga_scripts.ga_len;
19147 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
19148 * point to it.
19150 void
19151 init_var_dict(dict, dict_var)
19152 dict_T *dict;
19153 dictitem_T *dict_var;
19155 hash_init(&dict->dv_hashtab);
19156 dict->dv_refcount = DO_NOT_FREE_CNT;
19157 dict->dv_copyID = 0;
19158 dict_var->di_tv.vval.v_dict = dict;
19159 dict_var->di_tv.v_type = VAR_DICT;
19160 dict_var->di_tv.v_lock = VAR_FIXED;
19161 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
19162 dict_var->di_key[0] = NUL;
19166 * Clean up a list of internal variables.
19167 * Frees all allocated variables and the value they contain.
19168 * Clears hashtab "ht", does not free it.
19170 void
19171 vars_clear(ht)
19172 hashtab_T *ht;
19174 vars_clear_ext(ht, TRUE);
19178 * Like vars_clear(), but only free the value if "free_val" is TRUE.
19180 static void
19181 vars_clear_ext(ht, free_val)
19182 hashtab_T *ht;
19183 int free_val;
19185 int todo;
19186 hashitem_T *hi;
19187 dictitem_T *v;
19189 hash_lock(ht);
19190 todo = (int)ht->ht_used;
19191 for (hi = ht->ht_array; todo > 0; ++hi)
19193 if (!HASHITEM_EMPTY(hi))
19195 --todo;
19197 /* Free the variable. Don't remove it from the hashtab,
19198 * ht_array might change then. hash_clear() takes care of it
19199 * later. */
19200 v = HI2DI(hi);
19201 if (free_val)
19202 clear_tv(&v->di_tv);
19203 if ((v->di_flags & DI_FLAGS_FIX) == 0)
19204 vim_free(v);
19207 hash_clear(ht);
19208 ht->ht_used = 0;
19212 * Delete a variable from hashtab "ht" at item "hi".
19213 * Clear the variable value and free the dictitem.
19215 static void
19216 delete_var(ht, hi)
19217 hashtab_T *ht;
19218 hashitem_T *hi;
19220 dictitem_T *di = HI2DI(hi);
19222 hash_remove(ht, hi);
19223 clear_tv(&di->di_tv);
19224 vim_free(di);
19228 * List the value of one internal variable.
19230 static void
19231 list_one_var(v, prefix, first)
19232 dictitem_T *v;
19233 char_u *prefix;
19234 int *first;
19236 char_u *tofree;
19237 char_u *s;
19238 char_u numbuf[NUMBUFLEN];
19240 current_copyID += COPYID_INC;
19241 s = echo_string(&v->di_tv, &tofree, numbuf, current_copyID);
19242 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
19243 s == NULL ? (char_u *)"" : s, first);
19244 vim_free(tofree);
19247 static void
19248 list_one_var_a(prefix, name, type, string, first)
19249 char_u *prefix;
19250 char_u *name;
19251 int type;
19252 char_u *string;
19253 int *first; /* when TRUE clear rest of screen and set to FALSE */
19255 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
19256 msg_start();
19257 msg_puts(prefix);
19258 if (name != NULL) /* "a:" vars don't have a name stored */
19259 msg_puts(name);
19260 msg_putchar(' ');
19261 msg_advance(22);
19262 if (type == VAR_NUMBER)
19263 msg_putchar('#');
19264 else if (type == VAR_FUNC)
19265 msg_putchar('*');
19266 else if (type == VAR_LIST)
19268 msg_putchar('[');
19269 if (*string == '[')
19270 ++string;
19272 else if (type == VAR_DICT)
19274 msg_putchar('{');
19275 if (*string == '{')
19276 ++string;
19278 else
19279 msg_putchar(' ');
19281 msg_outtrans(string);
19283 if (type == VAR_FUNC)
19284 msg_puts((char_u *)"()");
19285 if (*first)
19287 msg_clr_eos();
19288 *first = FALSE;
19293 * Set variable "name" to value in "tv".
19294 * If the variable already exists, the value is updated.
19295 * Otherwise the variable is created.
19297 static void
19298 set_var(name, tv, copy)
19299 char_u *name;
19300 typval_T *tv;
19301 int copy; /* make copy of value in "tv" */
19303 dictitem_T *v;
19304 char_u *varname;
19305 hashtab_T *ht;
19306 char_u *p;
19308 if (tv->v_type == VAR_FUNC)
19310 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
19311 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
19312 ? name[2] : name[0]))
19314 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
19315 return;
19317 if (function_exists(name))
19319 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
19320 name);
19321 return;
19325 ht = find_var_ht(name, &varname);
19326 if (ht == NULL || *varname == NUL)
19328 EMSG2(_(e_illvar), name);
19329 return;
19332 v = find_var_in_ht(ht, varname, TRUE);
19333 if (v != NULL)
19335 /* existing variable, need to clear the value */
19336 if (var_check_ro(v->di_flags, name)
19337 || tv_check_lock(v->di_tv.v_lock, name))
19338 return;
19339 if (v->di_tv.v_type != tv->v_type
19340 && !((v->di_tv.v_type == VAR_STRING
19341 || v->di_tv.v_type == VAR_NUMBER)
19342 && (tv->v_type == VAR_STRING
19343 || tv->v_type == VAR_NUMBER))
19344 #ifdef FEAT_FLOAT
19345 && !((v->di_tv.v_type == VAR_NUMBER
19346 || v->di_tv.v_type == VAR_FLOAT)
19347 && (tv->v_type == VAR_NUMBER
19348 || tv->v_type == VAR_FLOAT))
19349 #endif
19352 EMSG2(_("E706: Variable type mismatch for: %s"), name);
19353 return;
19357 * Handle setting internal v: variables separately: we don't change
19358 * the type.
19360 if (ht == &vimvarht)
19362 if (v->di_tv.v_type == VAR_STRING)
19364 vim_free(v->di_tv.vval.v_string);
19365 if (copy || tv->v_type != VAR_STRING)
19366 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
19367 else
19369 /* Take over the string to avoid an extra alloc/free. */
19370 v->di_tv.vval.v_string = tv->vval.v_string;
19371 tv->vval.v_string = NULL;
19374 else if (v->di_tv.v_type != VAR_NUMBER)
19375 EMSG2(_(e_intern2), "set_var()");
19376 else
19378 v->di_tv.vval.v_number = get_tv_number(tv);
19379 if (STRCMP(varname, "searchforward") == 0)
19380 set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
19382 return;
19385 clear_tv(&v->di_tv);
19387 else /* add a new variable */
19389 /* Can't add "v:" variable. */
19390 if (ht == &vimvarht)
19392 EMSG2(_(e_illvar), name);
19393 return;
19396 /* Make sure the variable name is valid. */
19397 for (p = varname; *p != NUL; ++p)
19398 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
19399 && *p != AUTOLOAD_CHAR)
19401 EMSG2(_(e_illvar), varname);
19402 return;
19405 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
19406 + STRLEN(varname)));
19407 if (v == NULL)
19408 return;
19409 STRCPY(v->di_key, varname);
19410 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
19412 vim_free(v);
19413 return;
19415 v->di_flags = 0;
19418 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
19419 copy_tv(tv, &v->di_tv);
19420 else
19422 v->di_tv = *tv;
19423 v->di_tv.v_lock = 0;
19424 init_tv(tv);
19429 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
19430 * Also give an error message.
19432 static int
19433 var_check_ro(flags, name)
19434 int flags;
19435 char_u *name;
19437 if (flags & DI_FLAGS_RO)
19439 EMSG2(_(e_readonlyvar), name);
19440 return TRUE;
19442 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
19444 EMSG2(_(e_readonlysbx), name);
19445 return TRUE;
19447 return FALSE;
19451 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
19452 * Also give an error message.
19454 static int
19455 var_check_fixed(flags, name)
19456 int flags;
19457 char_u *name;
19459 if (flags & DI_FLAGS_FIX)
19461 EMSG2(_("E795: Cannot delete variable %s"), name);
19462 return TRUE;
19464 return FALSE;
19468 * Return TRUE if typeval "tv" is set to be locked (immutable).
19469 * Also give an error message, using "name".
19471 static int
19472 tv_check_lock(lock, name)
19473 int lock;
19474 char_u *name;
19476 if (lock & VAR_LOCKED)
19478 EMSG2(_("E741: Value is locked: %s"),
19479 name == NULL ? (char_u *)_("Unknown") : name);
19480 return TRUE;
19482 if (lock & VAR_FIXED)
19484 EMSG2(_("E742: Cannot change value of %s"),
19485 name == NULL ? (char_u *)_("Unknown") : name);
19486 return TRUE;
19488 return FALSE;
19492 * Copy the values from typval_T "from" to typval_T "to".
19493 * When needed allocates string or increases reference count.
19494 * Does not make a copy of a list or dict but copies the reference!
19495 * It is OK for "from" and "to" to point to the same item. This is used to
19496 * make a copy later.
19498 void
19499 copy_tv(from, to)
19500 typval_T *from;
19501 typval_T *to;
19503 to->v_type = from->v_type;
19504 to->v_lock = 0;
19505 switch (from->v_type)
19507 case VAR_NUMBER:
19508 to->vval.v_number = from->vval.v_number;
19509 break;
19510 #ifdef FEAT_FLOAT
19511 case VAR_FLOAT:
19512 to->vval.v_float = from->vval.v_float;
19513 break;
19514 #endif
19515 case VAR_STRING:
19516 case VAR_FUNC:
19517 if (from->vval.v_string == NULL)
19518 to->vval.v_string = NULL;
19519 else
19521 to->vval.v_string = vim_strsave(from->vval.v_string);
19522 if (from->v_type == VAR_FUNC)
19523 func_ref(to->vval.v_string);
19525 break;
19526 case VAR_LIST:
19527 if (from->vval.v_list == NULL)
19528 to->vval.v_list = NULL;
19529 else
19531 to->vval.v_list = from->vval.v_list;
19532 ++to->vval.v_list->lv_refcount;
19534 break;
19535 case VAR_DICT:
19536 if (from->vval.v_dict == NULL)
19537 to->vval.v_dict = NULL;
19538 else
19540 to->vval.v_dict = from->vval.v_dict;
19541 ++to->vval.v_dict->dv_refcount;
19543 break;
19544 default:
19545 EMSG2(_(e_intern2), "copy_tv()");
19546 break;
19551 * Make a copy of an item.
19552 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
19553 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
19554 * reference to an already copied list/dict can be used.
19555 * Returns FAIL or OK.
19557 static int
19558 item_copy(from, to, deep, copyID)
19559 typval_T *from;
19560 typval_T *to;
19561 int deep;
19562 int copyID;
19564 static int recurse = 0;
19565 int ret = OK;
19567 if (recurse >= DICT_MAXNEST)
19569 EMSG(_("E698: variable nested too deep for making a copy"));
19570 return FAIL;
19572 ++recurse;
19574 switch (from->v_type)
19576 case VAR_NUMBER:
19577 #ifdef FEAT_FLOAT
19578 case VAR_FLOAT:
19579 #endif
19580 case VAR_STRING:
19581 case VAR_FUNC:
19582 copy_tv(from, to);
19583 break;
19584 case VAR_LIST:
19585 to->v_type = VAR_LIST;
19586 to->v_lock = 0;
19587 if (from->vval.v_list == NULL)
19588 to->vval.v_list = NULL;
19589 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
19591 /* use the copy made earlier */
19592 to->vval.v_list = from->vval.v_list->lv_copylist;
19593 ++to->vval.v_list->lv_refcount;
19595 else
19596 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
19597 if (to->vval.v_list == NULL)
19598 ret = FAIL;
19599 break;
19600 case VAR_DICT:
19601 to->v_type = VAR_DICT;
19602 to->v_lock = 0;
19603 if (from->vval.v_dict == NULL)
19604 to->vval.v_dict = NULL;
19605 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
19607 /* use the copy made earlier */
19608 to->vval.v_dict = from->vval.v_dict->dv_copydict;
19609 ++to->vval.v_dict->dv_refcount;
19611 else
19612 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
19613 if (to->vval.v_dict == NULL)
19614 ret = FAIL;
19615 break;
19616 default:
19617 EMSG2(_(e_intern2), "item_copy()");
19618 ret = FAIL;
19620 --recurse;
19621 return ret;
19625 * ":echo expr1 ..." print each argument separated with a space, add a
19626 * newline at the end.
19627 * ":echon expr1 ..." print each argument plain.
19629 void
19630 ex_echo(eap)
19631 exarg_T *eap;
19633 char_u *arg = eap->arg;
19634 typval_T rettv;
19635 char_u *tofree;
19636 char_u *p;
19637 int needclr = TRUE;
19638 int atstart = TRUE;
19639 char_u numbuf[NUMBUFLEN];
19641 if (eap->skip)
19642 ++emsg_skip;
19643 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
19645 /* If eval1() causes an error message the text from the command may
19646 * still need to be cleared. E.g., "echo 22,44". */
19647 need_clr_eos = needclr;
19649 p = arg;
19650 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19653 * Report the invalid expression unless the expression evaluation
19654 * has been cancelled due to an aborting error, an interrupt, or an
19655 * exception.
19657 if (!aborting())
19658 EMSG2(_(e_invexpr2), p);
19659 need_clr_eos = FALSE;
19660 break;
19662 need_clr_eos = FALSE;
19664 if (!eap->skip)
19666 if (atstart)
19668 atstart = FALSE;
19669 /* Call msg_start() after eval1(), evaluating the expression
19670 * may cause a message to appear. */
19671 if (eap->cmdidx == CMD_echo)
19672 msg_start();
19674 else if (eap->cmdidx == CMD_echo)
19675 msg_puts_attr((char_u *)" ", echo_attr);
19676 current_copyID += COPYID_INC;
19677 p = echo_string(&rettv, &tofree, numbuf, current_copyID);
19678 if (p != NULL)
19679 for ( ; *p != NUL && !got_int; ++p)
19681 if (*p == '\n' || *p == '\r' || *p == TAB)
19683 if (*p != TAB && needclr)
19685 /* remove any text still there from the command */
19686 msg_clr_eos();
19687 needclr = FALSE;
19689 msg_putchar_attr(*p, echo_attr);
19691 else
19693 #ifdef FEAT_MBYTE
19694 if (has_mbyte)
19696 int i = (*mb_ptr2len)(p);
19698 (void)msg_outtrans_len_attr(p, i, echo_attr);
19699 p += i - 1;
19701 else
19702 #endif
19703 (void)msg_outtrans_len_attr(p, 1, echo_attr);
19706 vim_free(tofree);
19708 clear_tv(&rettv);
19709 arg = skipwhite(arg);
19711 eap->nextcmd = check_nextcmd(arg);
19713 if (eap->skip)
19714 --emsg_skip;
19715 else
19717 /* remove text that may still be there from the command */
19718 if (needclr)
19719 msg_clr_eos();
19720 if (eap->cmdidx == CMD_echo)
19721 msg_end();
19726 * ":echohl {name}".
19728 void
19729 ex_echohl(eap)
19730 exarg_T *eap;
19732 int id;
19734 id = syn_name2id(eap->arg);
19735 if (id == 0)
19736 echo_attr = 0;
19737 else
19738 echo_attr = syn_id2attr(id);
19742 * ":execute expr1 ..." execute the result of an expression.
19743 * ":echomsg expr1 ..." Print a message
19744 * ":echoerr expr1 ..." Print an error
19745 * Each gets spaces around each argument and a newline at the end for
19746 * echo commands
19748 void
19749 ex_execute(eap)
19750 exarg_T *eap;
19752 char_u *arg = eap->arg;
19753 typval_T rettv;
19754 int ret = OK;
19755 char_u *p;
19756 garray_T ga;
19757 int len;
19758 int save_did_emsg;
19760 ga_init2(&ga, 1, 80);
19762 if (eap->skip)
19763 ++emsg_skip;
19764 while (*arg != NUL && *arg != '|' && *arg != '\n')
19766 p = arg;
19767 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19770 * Report the invalid expression unless the expression evaluation
19771 * has been cancelled due to an aborting error, an interrupt, or an
19772 * exception.
19774 if (!aborting())
19775 EMSG2(_(e_invexpr2), p);
19776 ret = FAIL;
19777 break;
19780 if (!eap->skip)
19782 p = get_tv_string(&rettv);
19783 len = (int)STRLEN(p);
19784 if (ga_grow(&ga, len + 2) == FAIL)
19786 clear_tv(&rettv);
19787 ret = FAIL;
19788 break;
19790 if (ga.ga_len)
19791 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
19792 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
19793 ga.ga_len += len;
19796 clear_tv(&rettv);
19797 arg = skipwhite(arg);
19800 if (ret != FAIL && ga.ga_data != NULL)
19802 if (eap->cmdidx == CMD_echomsg)
19804 MSG_ATTR(ga.ga_data, echo_attr);
19805 out_flush();
19807 else if (eap->cmdidx == CMD_echoerr)
19809 /* We don't want to abort following commands, restore did_emsg. */
19810 save_did_emsg = did_emsg;
19811 EMSG((char_u *)ga.ga_data);
19812 if (!force_abort)
19813 did_emsg = save_did_emsg;
19815 else if (eap->cmdidx == CMD_execute)
19816 do_cmdline((char_u *)ga.ga_data,
19817 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
19820 ga_clear(&ga);
19822 if (eap->skip)
19823 --emsg_skip;
19825 eap->nextcmd = check_nextcmd(arg);
19829 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
19830 * "arg" points to the "&" or '+' when called, to "option" when returning.
19831 * Returns NULL when no option name found. Otherwise pointer to the char
19832 * after the option name.
19834 static char_u *
19835 find_option_end(arg, opt_flags)
19836 char_u **arg;
19837 int *opt_flags;
19839 char_u *p = *arg;
19841 ++p;
19842 if (*p == 'g' && p[1] == ':')
19844 *opt_flags = OPT_GLOBAL;
19845 p += 2;
19847 else if (*p == 'l' && p[1] == ':')
19849 *opt_flags = OPT_LOCAL;
19850 p += 2;
19852 else
19853 *opt_flags = 0;
19855 if (!ASCII_ISALPHA(*p))
19856 return NULL;
19857 *arg = p;
19859 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
19860 p += 4; /* termcap option */
19861 else
19862 while (ASCII_ISALPHA(*p))
19863 ++p;
19864 return p;
19868 * ":function"
19870 void
19871 ex_function(eap)
19872 exarg_T *eap;
19874 char_u *theline;
19875 int j;
19876 int c;
19877 int saved_did_emsg;
19878 char_u *name = NULL;
19879 char_u *p;
19880 char_u *arg;
19881 char_u *line_arg = NULL;
19882 garray_T newargs;
19883 garray_T newlines;
19884 int varargs = FALSE;
19885 int mustend = FALSE;
19886 int flags = 0;
19887 ufunc_T *fp;
19888 int indent;
19889 int nesting;
19890 char_u *skip_until = NULL;
19891 dictitem_T *v;
19892 funcdict_T fudi;
19893 static int func_nr = 0; /* number for nameless function */
19894 int paren;
19895 hashtab_T *ht;
19896 int todo;
19897 hashitem_T *hi;
19898 int sourcing_lnum_off;
19901 * ":function" without argument: list functions.
19903 if (ends_excmd(*eap->arg))
19905 if (!eap->skip)
19907 todo = (int)func_hashtab.ht_used;
19908 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19910 if (!HASHITEM_EMPTY(hi))
19912 --todo;
19913 fp = HI2UF(hi);
19914 if (!isdigit(*fp->uf_name))
19915 list_func_head(fp, FALSE);
19919 eap->nextcmd = check_nextcmd(eap->arg);
19920 return;
19924 * ":function /pat": list functions matching pattern.
19926 if (*eap->arg == '/')
19928 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
19929 if (!eap->skip)
19931 regmatch_T regmatch;
19933 c = *p;
19934 *p = NUL;
19935 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
19936 *p = c;
19937 if (regmatch.regprog != NULL)
19939 regmatch.rm_ic = p_ic;
19941 todo = (int)func_hashtab.ht_used;
19942 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19944 if (!HASHITEM_EMPTY(hi))
19946 --todo;
19947 fp = HI2UF(hi);
19948 if (!isdigit(*fp->uf_name)
19949 && vim_regexec(&regmatch, fp->uf_name, 0))
19950 list_func_head(fp, FALSE);
19953 vim_free(regmatch.regprog);
19956 if (*p == '/')
19957 ++p;
19958 eap->nextcmd = check_nextcmd(p);
19959 return;
19963 * Get the function name. There are these situations:
19964 * func normal function name
19965 * "name" == func, "fudi.fd_dict" == NULL
19966 * dict.func new dictionary entry
19967 * "name" == NULL, "fudi.fd_dict" set,
19968 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
19969 * dict.func existing dict entry with a Funcref
19970 * "name" == func, "fudi.fd_dict" set,
19971 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19972 * dict.func existing dict entry that's not a Funcref
19973 * "name" == NULL, "fudi.fd_dict" set,
19974 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19976 p = eap->arg;
19977 name = trans_function_name(&p, eap->skip, 0, &fudi);
19978 paren = (vim_strchr(p, '(') != NULL);
19979 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
19982 * Return on an invalid expression in braces, unless the expression
19983 * evaluation has been cancelled due to an aborting error, an
19984 * interrupt, or an exception.
19986 if (!aborting())
19988 if (!eap->skip && fudi.fd_newkey != NULL)
19989 EMSG2(_(e_dictkey), fudi.fd_newkey);
19990 vim_free(fudi.fd_newkey);
19991 return;
19993 else
19994 eap->skip = TRUE;
19997 /* An error in a function call during evaluation of an expression in magic
19998 * braces should not cause the function not to be defined. */
19999 saved_did_emsg = did_emsg;
20000 did_emsg = FALSE;
20003 * ":function func" with only function name: list function.
20005 if (!paren)
20007 if (!ends_excmd(*skipwhite(p)))
20009 EMSG(_(e_trailing));
20010 goto ret_free;
20012 eap->nextcmd = check_nextcmd(p);
20013 if (eap->nextcmd != NULL)
20014 *p = NUL;
20015 if (!eap->skip && !got_int)
20017 fp = find_func(name);
20018 if (fp != NULL)
20020 list_func_head(fp, TRUE);
20021 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
20023 if (FUNCLINE(fp, j) == NULL)
20024 continue;
20025 msg_putchar('\n');
20026 msg_outnum((long)(j + 1));
20027 if (j < 9)
20028 msg_putchar(' ');
20029 if (j < 99)
20030 msg_putchar(' ');
20031 msg_prt_line(FUNCLINE(fp, j), FALSE);
20032 out_flush(); /* show a line at a time */
20033 ui_breakcheck();
20035 if (!got_int)
20037 msg_putchar('\n');
20038 msg_puts((char_u *)" endfunction");
20041 else
20042 emsg_funcname(N_("E123: Undefined function: %s"), name);
20044 goto ret_free;
20048 * ":function name(arg1, arg2)" Define function.
20050 p = skipwhite(p);
20051 if (*p != '(')
20053 if (!eap->skip)
20055 EMSG2(_("E124: Missing '(': %s"), eap->arg);
20056 goto ret_free;
20058 /* attempt to continue by skipping some text */
20059 if (vim_strchr(p, '(') != NULL)
20060 p = vim_strchr(p, '(');
20062 p = skipwhite(p + 1);
20064 ga_init2(&newargs, (int)sizeof(char_u *), 3);
20065 ga_init2(&newlines, (int)sizeof(char_u *), 3);
20067 if (!eap->skip)
20069 /* Check the name of the function. Unless it's a dictionary function
20070 * (that we are overwriting). */
20071 if (name != NULL)
20072 arg = name;
20073 else
20074 arg = fudi.fd_newkey;
20075 if (arg != NULL && (fudi.fd_di == NULL
20076 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
20078 if (*arg == K_SPECIAL)
20079 j = 3;
20080 else
20081 j = 0;
20082 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
20083 : eval_isnamec(arg[j])))
20084 ++j;
20085 if (arg[j] != NUL)
20086 emsg_funcname((char *)e_invarg2, arg);
20091 * Isolate the arguments: "arg1, arg2, ...)"
20093 while (*p != ')')
20095 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
20097 varargs = TRUE;
20098 p += 3;
20099 mustend = TRUE;
20101 else
20103 arg = p;
20104 while (ASCII_ISALNUM(*p) || *p == '_')
20105 ++p;
20106 if (arg == p || isdigit(*arg)
20107 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
20108 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
20110 if (!eap->skip)
20111 EMSG2(_("E125: Illegal argument: %s"), arg);
20112 break;
20114 if (ga_grow(&newargs, 1) == FAIL)
20115 goto erret;
20116 c = *p;
20117 *p = NUL;
20118 arg = vim_strsave(arg);
20119 if (arg == NULL)
20120 goto erret;
20121 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
20122 *p = c;
20123 newargs.ga_len++;
20124 if (*p == ',')
20125 ++p;
20126 else
20127 mustend = TRUE;
20129 p = skipwhite(p);
20130 if (mustend && *p != ')')
20132 if (!eap->skip)
20133 EMSG2(_(e_invarg2), eap->arg);
20134 break;
20137 ++p; /* skip the ')' */
20139 /* find extra arguments "range", "dict" and "abort" */
20140 for (;;)
20142 p = skipwhite(p);
20143 if (STRNCMP(p, "range", 5) == 0)
20145 flags |= FC_RANGE;
20146 p += 5;
20148 else if (STRNCMP(p, "dict", 4) == 0)
20150 flags |= FC_DICT;
20151 p += 4;
20153 else if (STRNCMP(p, "abort", 5) == 0)
20155 flags |= FC_ABORT;
20156 p += 5;
20158 else
20159 break;
20162 /* When there is a line break use what follows for the function body.
20163 * Makes 'exe "func Test()\n...\nendfunc"' work. */
20164 if (*p == '\n')
20165 line_arg = p + 1;
20166 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
20167 EMSG(_(e_trailing));
20170 * Read the body of the function, until ":endfunction" is found.
20172 if (KeyTyped)
20174 /* Check if the function already exists, don't let the user type the
20175 * whole function before telling him it doesn't work! For a script we
20176 * need to skip the body to be able to find what follows. */
20177 if (!eap->skip && !eap->forceit)
20179 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
20180 EMSG(_(e_funcdict));
20181 else if (name != NULL && find_func(name) != NULL)
20182 emsg_funcname(e_funcexts, name);
20185 if (!eap->skip && did_emsg)
20186 goto erret;
20188 msg_putchar('\n'); /* don't overwrite the function name */
20189 cmdline_row = msg_row;
20192 indent = 2;
20193 nesting = 0;
20194 for (;;)
20196 msg_scroll = TRUE;
20197 need_wait_return = FALSE;
20198 sourcing_lnum_off = sourcing_lnum;
20200 if (line_arg != NULL)
20202 /* Use eap->arg, split up in parts by line breaks. */
20203 theline = line_arg;
20204 p = vim_strchr(theline, '\n');
20205 if (p == NULL)
20206 line_arg += STRLEN(line_arg);
20207 else
20209 *p = NUL;
20210 line_arg = p + 1;
20213 else if (eap->getline == NULL)
20214 theline = getcmdline(':', 0L, indent);
20215 else
20216 theline = eap->getline(':', eap->cookie, indent);
20217 if (KeyTyped)
20218 lines_left = Rows - 1;
20219 if (theline == NULL)
20221 EMSG(_("E126: Missing :endfunction"));
20222 goto erret;
20225 /* Detect line continuation: sourcing_lnum increased more than one. */
20226 if (sourcing_lnum > sourcing_lnum_off + 1)
20227 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
20228 else
20229 sourcing_lnum_off = 0;
20231 if (skip_until != NULL)
20233 /* between ":append" and "." and between ":python <<EOF" and "EOF"
20234 * don't check for ":endfunc". */
20235 if (STRCMP(theline, skip_until) == 0)
20237 vim_free(skip_until);
20238 skip_until = NULL;
20241 else
20243 /* skip ':' and blanks*/
20244 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
20247 /* Check for "endfunction". */
20248 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
20250 if (line_arg == NULL)
20251 vim_free(theline);
20252 break;
20255 /* Increase indent inside "if", "while", "for" and "try", decrease
20256 * at "end". */
20257 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
20258 indent -= 2;
20259 else if (STRNCMP(p, "if", 2) == 0
20260 || STRNCMP(p, "wh", 2) == 0
20261 || STRNCMP(p, "for", 3) == 0
20262 || STRNCMP(p, "try", 3) == 0)
20263 indent += 2;
20265 /* Check for defining a function inside this function. */
20266 if (checkforcmd(&p, "function", 2))
20268 if (*p == '!')
20269 p = skipwhite(p + 1);
20270 p += eval_fname_script(p);
20271 if (ASCII_ISALPHA(*p))
20273 vim_free(trans_function_name(&p, TRUE, 0, NULL));
20274 if (*skipwhite(p) == '(')
20276 ++nesting;
20277 indent += 2;
20282 /* Check for ":append" or ":insert". */
20283 p = skip_range(p, NULL);
20284 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
20285 || (p[0] == 'i'
20286 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
20287 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
20288 skip_until = vim_strsave((char_u *)".");
20290 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
20291 arg = skipwhite(skiptowhite(p));
20292 if (arg[0] == '<' && arg[1] =='<'
20293 && ((p[0] == 'p' && p[1] == 'y'
20294 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
20295 || (p[0] == 'p' && p[1] == 'e'
20296 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
20297 || (p[0] == 't' && p[1] == 'c'
20298 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
20299 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
20300 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
20301 || (p[0] == 'm' && p[1] == 'z'
20302 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
20305 /* ":python <<" continues until a dot, like ":append" */
20306 p = skipwhite(arg + 2);
20307 if (*p == NUL)
20308 skip_until = vim_strsave((char_u *)".");
20309 else
20310 skip_until = vim_strsave(p);
20314 /* Add the line to the function. */
20315 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
20317 if (line_arg == NULL)
20318 vim_free(theline);
20319 goto erret;
20322 /* Copy the line to newly allocated memory. get_one_sourceline()
20323 * allocates 250 bytes per line, this saves 80% on average. The cost
20324 * is an extra alloc/free. */
20325 p = vim_strsave(theline);
20326 if (p != NULL)
20328 if (line_arg == NULL)
20329 vim_free(theline);
20330 theline = p;
20333 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
20335 /* Add NULL lines for continuation lines, so that the line count is
20336 * equal to the index in the growarray. */
20337 while (sourcing_lnum_off-- > 0)
20338 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
20340 /* Check for end of eap->arg. */
20341 if (line_arg != NULL && *line_arg == NUL)
20342 line_arg = NULL;
20345 /* Don't define the function when skipping commands or when an error was
20346 * detected. */
20347 if (eap->skip || did_emsg)
20348 goto erret;
20351 * If there are no errors, add the function
20353 if (fudi.fd_dict == NULL)
20355 v = find_var(name, &ht);
20356 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
20358 emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
20359 name);
20360 goto erret;
20363 fp = find_func(name);
20364 if (fp != NULL)
20366 if (!eap->forceit)
20368 emsg_funcname(e_funcexts, name);
20369 goto erret;
20371 if (fp->uf_calls > 0)
20373 emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"),
20374 name);
20375 goto erret;
20377 /* redefine existing function */
20378 ga_clear_strings(&(fp->uf_args));
20379 ga_clear_strings(&(fp->uf_lines));
20380 vim_free(name);
20381 name = NULL;
20384 else
20386 char numbuf[20];
20388 fp = NULL;
20389 if (fudi.fd_newkey == NULL && !eap->forceit)
20391 EMSG(_(e_funcdict));
20392 goto erret;
20394 if (fudi.fd_di == NULL)
20396 /* Can't add a function to a locked dictionary */
20397 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
20398 goto erret;
20400 /* Can't change an existing function if it is locked */
20401 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
20402 goto erret;
20404 /* Give the function a sequential number. Can only be used with a
20405 * Funcref! */
20406 vim_free(name);
20407 sprintf(numbuf, "%d", ++func_nr);
20408 name = vim_strsave((char_u *)numbuf);
20409 if (name == NULL)
20410 goto erret;
20413 if (fp == NULL)
20415 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
20417 int slen, plen;
20418 char_u *scriptname;
20420 /* Check that the autoload name matches the script name. */
20421 j = FAIL;
20422 if (sourcing_name != NULL)
20424 scriptname = autoload_name(name);
20425 if (scriptname != NULL)
20427 p = vim_strchr(scriptname, '/');
20428 plen = (int)STRLEN(p);
20429 slen = (int)STRLEN(sourcing_name);
20430 if (slen > plen && fnamecmp(p,
20431 sourcing_name + slen - plen) == 0)
20432 j = OK;
20433 vim_free(scriptname);
20436 if (j == FAIL)
20438 EMSG2(_("E746: Function name does not match script file name: %s"), name);
20439 goto erret;
20443 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
20444 if (fp == NULL)
20445 goto erret;
20447 if (fudi.fd_dict != NULL)
20449 if (fudi.fd_di == NULL)
20451 /* add new dict entry */
20452 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
20453 if (fudi.fd_di == NULL)
20455 vim_free(fp);
20456 goto erret;
20458 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
20460 vim_free(fudi.fd_di);
20461 vim_free(fp);
20462 goto erret;
20465 else
20466 /* overwrite existing dict entry */
20467 clear_tv(&fudi.fd_di->di_tv);
20468 fudi.fd_di->di_tv.v_type = VAR_FUNC;
20469 fudi.fd_di->di_tv.v_lock = 0;
20470 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
20471 fp->uf_refcount = 1;
20473 /* behave like "dict" was used */
20474 flags |= FC_DICT;
20477 /* insert the new function in the function list */
20478 STRCPY(fp->uf_name, name);
20479 hash_add(&func_hashtab, UF2HIKEY(fp));
20481 fp->uf_args = newargs;
20482 fp->uf_lines = newlines;
20483 #ifdef FEAT_PROFILE
20484 fp->uf_tml_count = NULL;
20485 fp->uf_tml_total = NULL;
20486 fp->uf_tml_self = NULL;
20487 fp->uf_profiling = FALSE;
20488 if (prof_def_func())
20489 func_do_profile(fp);
20490 #endif
20491 fp->uf_varargs = varargs;
20492 fp->uf_flags = flags;
20493 fp->uf_calls = 0;
20494 fp->uf_script_ID = current_SID;
20495 goto ret_free;
20497 erret:
20498 ga_clear_strings(&newargs);
20499 ga_clear_strings(&newlines);
20500 ret_free:
20501 vim_free(skip_until);
20502 vim_free(fudi.fd_newkey);
20503 vim_free(name);
20504 did_emsg |= saved_did_emsg;
20508 * Get a function name, translating "<SID>" and "<SNR>".
20509 * Also handles a Funcref in a List or Dictionary.
20510 * Returns the function name in allocated memory, or NULL for failure.
20511 * flags:
20512 * TFN_INT: internal function name OK
20513 * TFN_QUIET: be quiet
20514 * Advances "pp" to just after the function name (if no error).
20516 static char_u *
20517 trans_function_name(pp, skip, flags, fdp)
20518 char_u **pp;
20519 int skip; /* only find the end, don't evaluate */
20520 int flags;
20521 funcdict_T *fdp; /* return: info about dictionary used */
20523 char_u *name = NULL;
20524 char_u *start;
20525 char_u *end;
20526 int lead;
20527 char_u sid_buf[20];
20528 int len;
20529 lval_T lv;
20531 if (fdp != NULL)
20532 vim_memset(fdp, 0, sizeof(funcdict_T));
20533 start = *pp;
20535 /* Check for hard coded <SNR>: already translated function ID (from a user
20536 * command). */
20537 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
20538 && (*pp)[2] == (int)KE_SNR)
20540 *pp += 3;
20541 len = get_id_len(pp) + 3;
20542 return vim_strnsave(start, len);
20545 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
20546 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
20547 lead = eval_fname_script(start);
20548 if (lead > 2)
20549 start += lead;
20551 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
20552 lead > 2 ? 0 : FNE_CHECK_START);
20553 if (end == start)
20555 if (!skip)
20556 EMSG(_("E129: Function name required"));
20557 goto theend;
20559 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
20562 * Report an invalid expression in braces, unless the expression
20563 * evaluation has been cancelled due to an aborting error, an
20564 * interrupt, or an exception.
20566 if (!aborting())
20568 if (end != NULL)
20569 EMSG2(_(e_invarg2), start);
20571 else
20572 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
20573 goto theend;
20576 if (lv.ll_tv != NULL)
20578 if (fdp != NULL)
20580 fdp->fd_dict = lv.ll_dict;
20581 fdp->fd_newkey = lv.ll_newkey;
20582 lv.ll_newkey = NULL;
20583 fdp->fd_di = lv.ll_di;
20585 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
20587 name = vim_strsave(lv.ll_tv->vval.v_string);
20588 *pp = end;
20590 else
20592 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
20593 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
20594 EMSG(_(e_funcref));
20595 else
20596 *pp = end;
20597 name = NULL;
20599 goto theend;
20602 if (lv.ll_name == NULL)
20604 /* Error found, but continue after the function name. */
20605 *pp = end;
20606 goto theend;
20609 /* Check if the name is a Funcref. If so, use the value. */
20610 if (lv.ll_exp_name != NULL)
20612 len = (int)STRLEN(lv.ll_exp_name);
20613 name = deref_func_name(lv.ll_exp_name, &len);
20614 if (name == lv.ll_exp_name)
20615 name = NULL;
20617 else
20619 len = (int)(end - *pp);
20620 name = deref_func_name(*pp, &len);
20621 if (name == *pp)
20622 name = NULL;
20624 if (name != NULL)
20626 name = vim_strsave(name);
20627 *pp = end;
20628 goto theend;
20631 if (lv.ll_exp_name != NULL)
20633 len = (int)STRLEN(lv.ll_exp_name);
20634 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
20635 && STRNCMP(lv.ll_name, "s:", 2) == 0)
20637 /* When there was "s:" already or the name expanded to get a
20638 * leading "s:" then remove it. */
20639 lv.ll_name += 2;
20640 len -= 2;
20641 lead = 2;
20644 else
20646 if (lead == 2) /* skip over "s:" */
20647 lv.ll_name += 2;
20648 len = (int)(end - lv.ll_name);
20652 * Copy the function name to allocated memory.
20653 * Accept <SID>name() inside a script, translate into <SNR>123_name().
20654 * Accept <SNR>123_name() outside a script.
20656 if (skip)
20657 lead = 0; /* do nothing */
20658 else if (lead > 0)
20660 lead = 3;
20661 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
20662 || eval_fname_sid(*pp))
20664 /* It's "s:" or "<SID>" */
20665 if (current_SID <= 0)
20667 EMSG(_(e_usingsid));
20668 goto theend;
20670 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
20671 lead += (int)STRLEN(sid_buf);
20674 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
20676 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
20677 goto theend;
20679 name = alloc((unsigned)(len + lead + 1));
20680 if (name != NULL)
20682 if (lead > 0)
20684 name[0] = K_SPECIAL;
20685 name[1] = KS_EXTRA;
20686 name[2] = (int)KE_SNR;
20687 if (lead > 3) /* If it's "<SID>" */
20688 STRCPY(name + 3, sid_buf);
20690 mch_memmove(name + lead, lv.ll_name, (size_t)len);
20691 name[len + lead] = NUL;
20693 *pp = end;
20695 theend:
20696 clear_lval(&lv);
20697 return name;
20701 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
20702 * Return 2 if "p" starts with "s:".
20703 * Return 0 otherwise.
20705 static int
20706 eval_fname_script(p)
20707 char_u *p;
20709 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
20710 || STRNICMP(p + 1, "SNR>", 4) == 0))
20711 return 5;
20712 if (p[0] == 's' && p[1] == ':')
20713 return 2;
20714 return 0;
20718 * Return TRUE if "p" starts with "<SID>" or "s:".
20719 * Only works if eval_fname_script() returned non-zero for "p"!
20721 static int
20722 eval_fname_sid(p)
20723 char_u *p;
20725 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
20729 * List the head of the function: "name(arg1, arg2)".
20731 static void
20732 list_func_head(fp, indent)
20733 ufunc_T *fp;
20734 int indent;
20736 int j;
20738 msg_start();
20739 if (indent)
20740 MSG_PUTS(" ");
20741 MSG_PUTS("function ");
20742 if (fp->uf_name[0] == K_SPECIAL)
20744 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
20745 msg_puts(fp->uf_name + 3);
20747 else
20748 msg_puts(fp->uf_name);
20749 msg_putchar('(');
20750 for (j = 0; j < fp->uf_args.ga_len; ++j)
20752 if (j)
20753 MSG_PUTS(", ");
20754 msg_puts(FUNCARG(fp, j));
20756 if (fp->uf_varargs)
20758 if (j)
20759 MSG_PUTS(", ");
20760 MSG_PUTS("...");
20762 msg_putchar(')');
20763 msg_clr_eos();
20764 if (p_verbose > 0)
20765 last_set_msg(fp->uf_script_ID);
20769 * Find a function by name, return pointer to it in ufuncs.
20770 * Return NULL for unknown function.
20772 static ufunc_T *
20773 find_func(name)
20774 char_u *name;
20776 hashitem_T *hi;
20778 hi = hash_find(&func_hashtab, name);
20779 if (!HASHITEM_EMPTY(hi))
20780 return HI2UF(hi);
20781 return NULL;
20784 #if defined(EXITFREE) || defined(PROTO)
20785 void
20786 free_all_functions()
20788 hashitem_T *hi;
20790 /* Need to start all over every time, because func_free() may change the
20791 * hash table. */
20792 while (func_hashtab.ht_used > 0)
20793 for (hi = func_hashtab.ht_array; ; ++hi)
20794 if (!HASHITEM_EMPTY(hi))
20796 func_free(HI2UF(hi));
20797 break;
20800 #endif
20803 * Return TRUE if a function "name" exists.
20805 static int
20806 function_exists(name)
20807 char_u *name;
20809 char_u *nm = name;
20810 char_u *p;
20811 int n = FALSE;
20813 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
20814 nm = skipwhite(nm);
20816 /* Only accept "funcname", "funcname ", "funcname (..." and
20817 * "funcname(...", not "funcname!...". */
20818 if (p != NULL && (*nm == NUL || *nm == '('))
20820 if (builtin_function(p))
20821 n = (find_internal_func(p) >= 0);
20822 else
20823 n = (find_func(p) != NULL);
20825 vim_free(p);
20826 return n;
20830 * Return TRUE if "name" looks like a builtin function name: starts with a
20831 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
20833 static int
20834 builtin_function(name)
20835 char_u *name;
20837 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
20838 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
20841 #if defined(FEAT_PROFILE) || defined(PROTO)
20843 * Start profiling function "fp".
20845 static void
20846 func_do_profile(fp)
20847 ufunc_T *fp;
20849 fp->uf_tm_count = 0;
20850 profile_zero(&fp->uf_tm_self);
20851 profile_zero(&fp->uf_tm_total);
20852 if (fp->uf_tml_count == NULL)
20853 fp->uf_tml_count = (int *)alloc_clear((unsigned)
20854 (sizeof(int) * fp->uf_lines.ga_len));
20855 if (fp->uf_tml_total == NULL)
20856 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
20857 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20858 if (fp->uf_tml_self == NULL)
20859 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
20860 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20861 fp->uf_tml_idx = -1;
20862 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
20863 || fp->uf_tml_self == NULL)
20864 return; /* out of memory */
20866 fp->uf_profiling = TRUE;
20870 * Dump the profiling results for all functions in file "fd".
20872 void
20873 func_dump_profile(fd)
20874 FILE *fd;
20876 hashitem_T *hi;
20877 int todo;
20878 ufunc_T *fp;
20879 int i;
20880 ufunc_T **sorttab;
20881 int st_len = 0;
20883 todo = (int)func_hashtab.ht_used;
20884 if (todo == 0)
20885 return; /* nothing to dump */
20887 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
20889 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
20891 if (!HASHITEM_EMPTY(hi))
20893 --todo;
20894 fp = HI2UF(hi);
20895 if (fp->uf_profiling)
20897 if (sorttab != NULL)
20898 sorttab[st_len++] = fp;
20900 if (fp->uf_name[0] == K_SPECIAL)
20901 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
20902 else
20903 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
20904 if (fp->uf_tm_count == 1)
20905 fprintf(fd, "Called 1 time\n");
20906 else
20907 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
20908 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
20909 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
20910 fprintf(fd, "\n");
20911 fprintf(fd, "count total (s) self (s)\n");
20913 for (i = 0; i < fp->uf_lines.ga_len; ++i)
20915 if (FUNCLINE(fp, i) == NULL)
20916 continue;
20917 prof_func_line(fd, fp->uf_tml_count[i],
20918 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
20919 fprintf(fd, "%s\n", FUNCLINE(fp, i));
20921 fprintf(fd, "\n");
20926 if (sorttab != NULL && st_len > 0)
20928 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20929 prof_total_cmp);
20930 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
20931 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20932 prof_self_cmp);
20933 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
20936 vim_free(sorttab);
20939 static void
20940 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
20941 FILE *fd;
20942 ufunc_T **sorttab;
20943 int st_len;
20944 char *title;
20945 int prefer_self; /* when equal print only self time */
20947 int i;
20948 ufunc_T *fp;
20950 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
20951 fprintf(fd, "count total (s) self (s) function\n");
20952 for (i = 0; i < 20 && i < st_len; ++i)
20954 fp = sorttab[i];
20955 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
20956 prefer_self);
20957 if (fp->uf_name[0] == K_SPECIAL)
20958 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
20959 else
20960 fprintf(fd, " %s()\n", fp->uf_name);
20962 fprintf(fd, "\n");
20966 * Print the count and times for one function or function line.
20968 static void
20969 prof_func_line(fd, count, total, self, prefer_self)
20970 FILE *fd;
20971 int count;
20972 proftime_T *total;
20973 proftime_T *self;
20974 int prefer_self; /* when equal print only self time */
20976 if (count > 0)
20978 fprintf(fd, "%5d ", count);
20979 if (prefer_self && profile_equal(total, self))
20980 fprintf(fd, " ");
20981 else
20982 fprintf(fd, "%s ", profile_msg(total));
20983 if (!prefer_self && profile_equal(total, self))
20984 fprintf(fd, " ");
20985 else
20986 fprintf(fd, "%s ", profile_msg(self));
20988 else
20989 fprintf(fd, " ");
20993 * Compare function for total time sorting.
20995 static int
20996 #ifdef __BORLANDC__
20997 _RTLENTRYF
20998 #endif
20999 prof_total_cmp(s1, s2)
21000 const void *s1;
21001 const void *s2;
21003 ufunc_T *p1, *p2;
21005 p1 = *(ufunc_T **)s1;
21006 p2 = *(ufunc_T **)s2;
21007 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
21011 * Compare function for self time sorting.
21013 static int
21014 #ifdef __BORLANDC__
21015 _RTLENTRYF
21016 #endif
21017 prof_self_cmp(s1, s2)
21018 const void *s1;
21019 const void *s2;
21021 ufunc_T *p1, *p2;
21023 p1 = *(ufunc_T **)s1;
21024 p2 = *(ufunc_T **)s2;
21025 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
21028 #endif
21031 * If "name" has a package name try autoloading the script for it.
21032 * Return TRUE if a package was loaded.
21034 static int
21035 script_autoload(name, reload)
21036 char_u *name;
21037 int reload; /* load script again when already loaded */
21039 char_u *p;
21040 char_u *scriptname, *tofree;
21041 int ret = FALSE;
21042 int i;
21044 /* If there is no '#' after name[0] there is no package name. */
21045 p = vim_strchr(name, AUTOLOAD_CHAR);
21046 if (p == NULL || p == name)
21047 return FALSE;
21049 tofree = scriptname = autoload_name(name);
21051 /* Find the name in the list of previously loaded package names. Skip
21052 * "autoload/", it's always the same. */
21053 for (i = 0; i < ga_loaded.ga_len; ++i)
21054 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
21055 break;
21056 if (!reload && i < ga_loaded.ga_len)
21057 ret = FALSE; /* was loaded already */
21058 else
21060 /* Remember the name if it wasn't loaded already. */
21061 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
21063 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
21064 tofree = NULL;
21067 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
21068 if (source_runtime(scriptname, FALSE) == OK)
21069 ret = TRUE;
21072 vim_free(tofree);
21073 return ret;
21077 * Return the autoload script name for a function or variable name.
21078 * Returns NULL when out of memory.
21080 static char_u *
21081 autoload_name(name)
21082 char_u *name;
21084 char_u *p;
21085 char_u *scriptname;
21087 /* Get the script file name: replace '#' with '/', append ".vim". */
21088 scriptname = alloc((unsigned)(STRLEN(name) + 14));
21089 if (scriptname == NULL)
21090 return FALSE;
21091 STRCPY(scriptname, "autoload/");
21092 STRCAT(scriptname, name);
21093 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
21094 STRCAT(scriptname, ".vim");
21095 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
21096 *p = '/';
21097 return scriptname;
21100 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
21103 * Function given to ExpandGeneric() to obtain the list of user defined
21104 * function names.
21106 char_u *
21107 get_user_func_name(xp, idx)
21108 expand_T *xp;
21109 int idx;
21111 static long_u done;
21112 static hashitem_T *hi;
21113 ufunc_T *fp;
21115 if (idx == 0)
21117 done = 0;
21118 hi = func_hashtab.ht_array;
21120 if (done < func_hashtab.ht_used)
21122 if (done++ > 0)
21123 ++hi;
21124 while (HASHITEM_EMPTY(hi))
21125 ++hi;
21126 fp = HI2UF(hi);
21128 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
21129 return fp->uf_name; /* prevents overflow */
21131 cat_func_name(IObuff, fp);
21132 if (xp->xp_context != EXPAND_USER_FUNC)
21134 STRCAT(IObuff, "(");
21135 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
21136 STRCAT(IObuff, ")");
21138 return IObuff;
21140 return NULL;
21143 #endif /* FEAT_CMDL_COMPL */
21146 * Copy the function name of "fp" to buffer "buf".
21147 * "buf" must be able to hold the function name plus three bytes.
21148 * Takes care of script-local function names.
21150 static void
21151 cat_func_name(buf, fp)
21152 char_u *buf;
21153 ufunc_T *fp;
21155 if (fp->uf_name[0] == K_SPECIAL)
21157 STRCPY(buf, "<SNR>");
21158 STRCAT(buf, fp->uf_name + 3);
21160 else
21161 STRCPY(buf, fp->uf_name);
21165 * ":delfunction {name}"
21167 void
21168 ex_delfunction(eap)
21169 exarg_T *eap;
21171 ufunc_T *fp = NULL;
21172 char_u *p;
21173 char_u *name;
21174 funcdict_T fudi;
21176 p = eap->arg;
21177 name = trans_function_name(&p, eap->skip, 0, &fudi);
21178 vim_free(fudi.fd_newkey);
21179 if (name == NULL)
21181 if (fudi.fd_dict != NULL && !eap->skip)
21182 EMSG(_(e_funcref));
21183 return;
21185 if (!ends_excmd(*skipwhite(p)))
21187 vim_free(name);
21188 EMSG(_(e_trailing));
21189 return;
21191 eap->nextcmd = check_nextcmd(p);
21192 if (eap->nextcmd != NULL)
21193 *p = NUL;
21195 if (!eap->skip)
21196 fp = find_func(name);
21197 vim_free(name);
21199 if (!eap->skip)
21201 if (fp == NULL)
21203 EMSG2(_(e_nofunc), eap->arg);
21204 return;
21206 if (fp->uf_calls > 0)
21208 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
21209 return;
21212 if (fudi.fd_dict != NULL)
21214 /* Delete the dict item that refers to the function, it will
21215 * invoke func_unref() and possibly delete the function. */
21216 dictitem_remove(fudi.fd_dict, fudi.fd_di);
21218 else
21219 func_free(fp);
21224 * Free a function and remove it from the list of functions.
21226 static void
21227 func_free(fp)
21228 ufunc_T *fp;
21230 hashitem_T *hi;
21232 /* clear this function */
21233 ga_clear_strings(&(fp->uf_args));
21234 ga_clear_strings(&(fp->uf_lines));
21235 #ifdef FEAT_PROFILE
21236 vim_free(fp->uf_tml_count);
21237 vim_free(fp->uf_tml_total);
21238 vim_free(fp->uf_tml_self);
21239 #endif
21241 /* remove the function from the function hashtable */
21242 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
21243 if (HASHITEM_EMPTY(hi))
21244 EMSG2(_(e_intern2), "func_free()");
21245 else
21246 hash_remove(&func_hashtab, hi);
21248 vim_free(fp);
21252 * Unreference a Function: decrement the reference count and free it when it
21253 * becomes zero. Only for numbered functions.
21255 static void
21256 func_unref(name)
21257 char_u *name;
21259 ufunc_T *fp;
21261 if (name != NULL && isdigit(*name))
21263 fp = find_func(name);
21264 if (fp == NULL)
21265 EMSG2(_(e_intern2), "func_unref()");
21266 else if (--fp->uf_refcount <= 0)
21268 /* Only delete it when it's not being used. Otherwise it's done
21269 * when "uf_calls" becomes zero. */
21270 if (fp->uf_calls == 0)
21271 func_free(fp);
21277 * Count a reference to a Function.
21279 static void
21280 func_ref(name)
21281 char_u *name;
21283 ufunc_T *fp;
21285 if (name != NULL && isdigit(*name))
21287 fp = find_func(name);
21288 if (fp == NULL)
21289 EMSG2(_(e_intern2), "func_ref()");
21290 else
21291 ++fp->uf_refcount;
21296 * Call a user function.
21298 static void
21299 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
21300 ufunc_T *fp; /* pointer to function */
21301 int argcount; /* nr of args */
21302 typval_T *argvars; /* arguments */
21303 typval_T *rettv; /* return value */
21304 linenr_T firstline; /* first line of range */
21305 linenr_T lastline; /* last line of range */
21306 dict_T *selfdict; /* Dictionary for "self" */
21308 char_u *save_sourcing_name;
21309 linenr_T save_sourcing_lnum;
21310 scid_T save_current_SID;
21311 funccall_T *fc;
21312 int save_did_emsg;
21313 static int depth = 0;
21314 dictitem_T *v;
21315 int fixvar_idx = 0; /* index in fixvar[] */
21316 int i;
21317 int ai;
21318 char_u numbuf[NUMBUFLEN];
21319 char_u *name;
21320 #ifdef FEAT_PROFILE
21321 proftime_T wait_start;
21322 proftime_T call_start;
21323 #endif
21325 /* If depth of calling is getting too high, don't execute the function */
21326 if (depth >= p_mfd)
21328 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
21329 rettv->v_type = VAR_NUMBER;
21330 rettv->vval.v_number = -1;
21331 return;
21333 ++depth;
21335 line_breakcheck(); /* check for CTRL-C hit */
21337 fc = (funccall_T *)alloc(sizeof(funccall_T));
21338 fc->caller = current_funccal;
21339 current_funccal = fc;
21340 fc->func = fp;
21341 fc->rettv = rettv;
21342 rettv->vval.v_number = 0;
21343 fc->linenr = 0;
21344 fc->returned = FALSE;
21345 fc->level = ex_nesting_level;
21346 /* Check if this function has a breakpoint. */
21347 fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
21348 fc->dbg_tick = debug_tick;
21351 * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables
21352 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
21353 * each argument variable and saves a lot of time.
21356 * Init l: variables.
21358 init_var_dict(&fc->l_vars, &fc->l_vars_var);
21359 if (selfdict != NULL)
21361 /* Set l:self to "selfdict". Use "name" to avoid a warning from
21362 * some compiler that checks the destination size. */
21363 v = &fc->fixvar[fixvar_idx++].var;
21364 name = v->di_key;
21365 STRCPY(name, "self");
21366 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
21367 hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
21368 v->di_tv.v_type = VAR_DICT;
21369 v->di_tv.v_lock = 0;
21370 v->di_tv.vval.v_dict = selfdict;
21371 ++selfdict->dv_refcount;
21375 * Init a: variables.
21376 * Set a:0 to "argcount".
21377 * Set a:000 to a list with room for the "..." arguments.
21379 init_var_dict(&fc->l_avars, &fc->l_avars_var);
21380 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0",
21381 (varnumber_T)(argcount - fp->uf_args.ga_len));
21382 /* Use "name" to avoid a warning from some compiler that checks the
21383 * destination size. */
21384 v = &fc->fixvar[fixvar_idx++].var;
21385 name = v->di_key;
21386 STRCPY(name, "000");
21387 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21388 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21389 v->di_tv.v_type = VAR_LIST;
21390 v->di_tv.v_lock = VAR_FIXED;
21391 v->di_tv.vval.v_list = &fc->l_varlist;
21392 vim_memset(&fc->l_varlist, 0, sizeof(list_T));
21393 fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT;
21394 fc->l_varlist.lv_lock = VAR_FIXED;
21397 * Set a:firstline to "firstline" and a:lastline to "lastline".
21398 * Set a:name to named arguments.
21399 * Set a:N to the "..." arguments.
21401 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline",
21402 (varnumber_T)firstline);
21403 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline",
21404 (varnumber_T)lastline);
21405 for (i = 0; i < argcount; ++i)
21407 ai = i - fp->uf_args.ga_len;
21408 if (ai < 0)
21409 /* named argument a:name */
21410 name = FUNCARG(fp, i);
21411 else
21413 /* "..." argument a:1, a:2, etc. */
21414 sprintf((char *)numbuf, "%d", ai + 1);
21415 name = numbuf;
21417 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
21419 v = &fc->fixvar[fixvar_idx++].var;
21420 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21422 else
21424 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
21425 + STRLEN(name)));
21426 if (v == NULL)
21427 break;
21428 v->di_flags = DI_FLAGS_RO;
21430 STRCPY(v->di_key, name);
21431 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21433 /* Note: the values are copied directly to avoid alloc/free.
21434 * "argvars" must have VAR_FIXED for v_lock. */
21435 v->di_tv = argvars[i];
21436 v->di_tv.v_lock = VAR_FIXED;
21438 if (ai >= 0 && ai < MAX_FUNC_ARGS)
21440 list_append(&fc->l_varlist, &fc->l_listitems[ai]);
21441 fc->l_listitems[ai].li_tv = argvars[i];
21442 fc->l_listitems[ai].li_tv.v_lock = VAR_FIXED;
21446 /* Don't redraw while executing the function. */
21447 ++RedrawingDisabled;
21448 save_sourcing_name = sourcing_name;
21449 save_sourcing_lnum = sourcing_lnum;
21450 sourcing_lnum = 1;
21451 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
21452 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
21453 if (sourcing_name != NULL)
21455 if (save_sourcing_name != NULL
21456 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
21457 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
21458 else
21459 STRCPY(sourcing_name, "function ");
21460 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
21462 if (p_verbose >= 12)
21464 ++no_wait_return;
21465 verbose_enter_scroll();
21467 smsg((char_u *)_("calling %s"), sourcing_name);
21468 if (p_verbose >= 14)
21470 char_u buf[MSG_BUF_LEN];
21471 char_u numbuf2[NUMBUFLEN];
21472 char_u *tofree;
21473 char_u *s;
21475 msg_puts((char_u *)"(");
21476 for (i = 0; i < argcount; ++i)
21478 if (i > 0)
21479 msg_puts((char_u *)", ");
21480 if (argvars[i].v_type == VAR_NUMBER)
21481 msg_outnum((long)argvars[i].vval.v_number);
21482 else
21484 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
21485 if (s != NULL)
21487 trunc_string(s, buf, MSG_BUF_CLEN);
21488 msg_puts(buf);
21489 vim_free(tofree);
21493 msg_puts((char_u *)")");
21495 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21497 verbose_leave_scroll();
21498 --no_wait_return;
21501 #ifdef FEAT_PROFILE
21502 if (do_profiling == PROF_YES)
21504 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
21505 func_do_profile(fp);
21506 if (fp->uf_profiling
21507 || (fc->caller != NULL && fc->caller->func->uf_profiling))
21509 ++fp->uf_tm_count;
21510 profile_start(&call_start);
21511 profile_zero(&fp->uf_tm_children);
21513 script_prof_save(&wait_start);
21515 #endif
21517 save_current_SID = current_SID;
21518 current_SID = fp->uf_script_ID;
21519 save_did_emsg = did_emsg;
21520 did_emsg = FALSE;
21522 /* call do_cmdline() to execute the lines */
21523 do_cmdline(NULL, get_func_line, (void *)fc,
21524 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
21526 --RedrawingDisabled;
21528 /* when the function was aborted because of an error, return -1 */
21529 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
21531 clear_tv(rettv);
21532 rettv->v_type = VAR_NUMBER;
21533 rettv->vval.v_number = -1;
21536 #ifdef FEAT_PROFILE
21537 if (do_profiling == PROF_YES && (fp->uf_profiling
21538 || (fc->caller != NULL && fc->caller->func->uf_profiling)))
21540 profile_end(&call_start);
21541 profile_sub_wait(&wait_start, &call_start);
21542 profile_add(&fp->uf_tm_total, &call_start);
21543 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
21544 if (fc->caller != NULL && fc->caller->func->uf_profiling)
21546 profile_add(&fc->caller->func->uf_tm_children, &call_start);
21547 profile_add(&fc->caller->func->uf_tml_children, &call_start);
21550 #endif
21552 /* when being verbose, mention the return value */
21553 if (p_verbose >= 12)
21555 ++no_wait_return;
21556 verbose_enter_scroll();
21558 if (aborting())
21559 smsg((char_u *)_("%s aborted"), sourcing_name);
21560 else if (fc->rettv->v_type == VAR_NUMBER)
21561 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
21562 (long)fc->rettv->vval.v_number);
21563 else
21565 char_u buf[MSG_BUF_LEN];
21566 char_u numbuf2[NUMBUFLEN];
21567 char_u *tofree;
21568 char_u *s;
21570 /* The value may be very long. Skip the middle part, so that we
21571 * have some idea how it starts and ends. smsg() would always
21572 * truncate it at the end. */
21573 s = tv2string(fc->rettv, &tofree, numbuf2, 0);
21574 if (s != NULL)
21576 trunc_string(s, buf, MSG_BUF_CLEN);
21577 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
21578 vim_free(tofree);
21581 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21583 verbose_leave_scroll();
21584 --no_wait_return;
21587 vim_free(sourcing_name);
21588 sourcing_name = save_sourcing_name;
21589 sourcing_lnum = save_sourcing_lnum;
21590 current_SID = save_current_SID;
21591 #ifdef FEAT_PROFILE
21592 if (do_profiling == PROF_YES)
21593 script_prof_restore(&wait_start);
21594 #endif
21596 if (p_verbose >= 12 && sourcing_name != NULL)
21598 ++no_wait_return;
21599 verbose_enter_scroll();
21601 smsg((char_u *)_("continuing in %s"), sourcing_name);
21602 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21604 verbose_leave_scroll();
21605 --no_wait_return;
21608 did_emsg |= save_did_emsg;
21609 current_funccal = fc->caller;
21610 --depth;
21612 /* If the a:000 list and the l: and a: dicts are not referenced we can
21613 * free the funccall_T and what's in it. */
21614 if (fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
21615 && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
21616 && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT)
21618 free_funccal(fc, FALSE);
21620 else
21622 hashitem_T *hi;
21623 listitem_T *li;
21624 int todo;
21626 /* "fc" is still in use. This can happen when returning "a:000" or
21627 * assigning "l:" to a global variable.
21628 * Link "fc" in the list for garbage collection later. */
21629 fc->caller = previous_funccal;
21630 previous_funccal = fc;
21632 /* Make a copy of the a: variables, since we didn't do that above. */
21633 todo = (int)fc->l_avars.dv_hashtab.ht_used;
21634 for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi)
21636 if (!HASHITEM_EMPTY(hi))
21638 --todo;
21639 v = HI2DI(hi);
21640 copy_tv(&v->di_tv, &v->di_tv);
21644 /* Make a copy of the a:000 items, since we didn't do that above. */
21645 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21646 copy_tv(&li->li_tv, &li->li_tv);
21651 * Return TRUE if items in "fc" do not have "copyID". That means they are not
21652 * referenced from anywhere that is in use.
21654 static int
21655 can_free_funccal(fc, copyID)
21656 funccall_T *fc;
21657 int copyID;
21659 return (fc->l_varlist.lv_copyID != copyID
21660 && fc->l_vars.dv_copyID != copyID
21661 && fc->l_avars.dv_copyID != copyID);
21665 * Free "fc" and what it contains.
21667 static void
21668 free_funccal(fc, free_val)
21669 funccall_T *fc;
21670 int free_val; /* a: vars were allocated */
21672 listitem_T *li;
21674 /* The a: variables typevals may not have been allocated, only free the
21675 * allocated variables. */
21676 vars_clear_ext(&fc->l_avars.dv_hashtab, free_val);
21678 /* free all l: variables */
21679 vars_clear(&fc->l_vars.dv_hashtab);
21681 /* Free the a:000 variables if they were allocated. */
21682 if (free_val)
21683 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21684 clear_tv(&li->li_tv);
21686 vim_free(fc);
21690 * Add a number variable "name" to dict "dp" with value "nr".
21692 static void
21693 add_nr_var(dp, v, name, nr)
21694 dict_T *dp;
21695 dictitem_T *v;
21696 char *name;
21697 varnumber_T nr;
21699 STRCPY(v->di_key, name);
21700 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21701 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
21702 v->di_tv.v_type = VAR_NUMBER;
21703 v->di_tv.v_lock = VAR_FIXED;
21704 v->di_tv.vval.v_number = nr;
21708 * ":return [expr]"
21710 void
21711 ex_return(eap)
21712 exarg_T *eap;
21714 char_u *arg = eap->arg;
21715 typval_T rettv;
21716 int returning = FALSE;
21718 if (current_funccal == NULL)
21720 EMSG(_("E133: :return not inside a function"));
21721 return;
21724 if (eap->skip)
21725 ++emsg_skip;
21727 eap->nextcmd = NULL;
21728 if ((*arg != NUL && *arg != '|' && *arg != '\n')
21729 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
21731 if (!eap->skip)
21732 returning = do_return(eap, FALSE, TRUE, &rettv);
21733 else
21734 clear_tv(&rettv);
21736 /* It's safer to return also on error. */
21737 else if (!eap->skip)
21740 * Return unless the expression evaluation has been cancelled due to an
21741 * aborting error, an interrupt, or an exception.
21743 if (!aborting())
21744 returning = do_return(eap, FALSE, TRUE, NULL);
21747 /* When skipping or the return gets pending, advance to the next command
21748 * in this line (!returning). Otherwise, ignore the rest of the line.
21749 * Following lines will be ignored by get_func_line(). */
21750 if (returning)
21751 eap->nextcmd = NULL;
21752 else if (eap->nextcmd == NULL) /* no argument */
21753 eap->nextcmd = check_nextcmd(arg);
21755 if (eap->skip)
21756 --emsg_skip;
21760 * Return from a function. Possibly makes the return pending. Also called
21761 * for a pending return at the ":endtry" or after returning from an extra
21762 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
21763 * when called due to a ":return" command. "rettv" may point to a typval_T
21764 * with the return rettv. Returns TRUE when the return can be carried out,
21765 * FALSE when the return gets pending.
21768 do_return(eap, reanimate, is_cmd, rettv)
21769 exarg_T *eap;
21770 int reanimate;
21771 int is_cmd;
21772 void *rettv;
21774 int idx;
21775 struct condstack *cstack = eap->cstack;
21777 if (reanimate)
21778 /* Undo the return. */
21779 current_funccal->returned = FALSE;
21782 * Cleanup (and inactivate) conditionals, but stop when a try conditional
21783 * not in its finally clause (which then is to be executed next) is found.
21784 * In this case, make the ":return" pending for execution at the ":endtry".
21785 * Otherwise, return normally.
21787 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
21788 if (idx >= 0)
21790 cstack->cs_pending[idx] = CSTP_RETURN;
21792 if (!is_cmd && !reanimate)
21793 /* A pending return again gets pending. "rettv" points to an
21794 * allocated variable with the rettv of the original ":return"'s
21795 * argument if present or is NULL else. */
21796 cstack->cs_rettv[idx] = rettv;
21797 else
21799 /* When undoing a return in order to make it pending, get the stored
21800 * return rettv. */
21801 if (reanimate)
21802 rettv = current_funccal->rettv;
21804 if (rettv != NULL)
21806 /* Store the value of the pending return. */
21807 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
21808 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
21809 else
21810 EMSG(_(e_outofmem));
21812 else
21813 cstack->cs_rettv[idx] = NULL;
21815 if (reanimate)
21817 /* The pending return value could be overwritten by a ":return"
21818 * without argument in a finally clause; reset the default
21819 * return value. */
21820 current_funccal->rettv->v_type = VAR_NUMBER;
21821 current_funccal->rettv->vval.v_number = 0;
21824 report_make_pending(CSTP_RETURN, rettv);
21826 else
21828 current_funccal->returned = TRUE;
21830 /* If the return is carried out now, store the return value. For
21831 * a return immediately after reanimation, the value is already
21832 * there. */
21833 if (!reanimate && rettv != NULL)
21835 clear_tv(current_funccal->rettv);
21836 *current_funccal->rettv = *(typval_T *)rettv;
21837 if (!is_cmd)
21838 vim_free(rettv);
21842 return idx < 0;
21846 * Free the variable with a pending return value.
21848 void
21849 discard_pending_return(rettv)
21850 void *rettv;
21852 free_tv((typval_T *)rettv);
21856 * Generate a return command for producing the value of "rettv". The result
21857 * is an allocated string. Used by report_pending() for verbose messages.
21859 char_u *
21860 get_return_cmd(rettv)
21861 void *rettv;
21863 char_u *s = NULL;
21864 char_u *tofree = NULL;
21865 char_u numbuf[NUMBUFLEN];
21867 if (rettv != NULL)
21868 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
21869 if (s == NULL)
21870 s = (char_u *)"";
21872 STRCPY(IObuff, ":return ");
21873 STRNCPY(IObuff + 8, s, IOSIZE - 8);
21874 if (STRLEN(s) + 8 >= IOSIZE)
21875 STRCPY(IObuff + IOSIZE - 4, "...");
21876 vim_free(tofree);
21877 return vim_strsave(IObuff);
21881 * Get next function line.
21882 * Called by do_cmdline() to get the next line.
21883 * Returns allocated string, or NULL for end of function.
21885 char_u *
21886 get_func_line(c, cookie, indent)
21887 int c UNUSED;
21888 void *cookie;
21889 int indent UNUSED;
21891 funccall_T *fcp = (funccall_T *)cookie;
21892 ufunc_T *fp = fcp->func;
21893 char_u *retval;
21894 garray_T *gap; /* growarray with function lines */
21896 /* If breakpoints have been added/deleted need to check for it. */
21897 if (fcp->dbg_tick != debug_tick)
21899 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21900 sourcing_lnum);
21901 fcp->dbg_tick = debug_tick;
21903 #ifdef FEAT_PROFILE
21904 if (do_profiling == PROF_YES)
21905 func_line_end(cookie);
21906 #endif
21908 gap = &fp->uf_lines;
21909 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21910 || fcp->returned)
21911 retval = NULL;
21912 else
21914 /* Skip NULL lines (continuation lines). */
21915 while (fcp->linenr < gap->ga_len
21916 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
21917 ++fcp->linenr;
21918 if (fcp->linenr >= gap->ga_len)
21919 retval = NULL;
21920 else
21922 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
21923 sourcing_lnum = fcp->linenr;
21924 #ifdef FEAT_PROFILE
21925 if (do_profiling == PROF_YES)
21926 func_line_start(cookie);
21927 #endif
21931 /* Did we encounter a breakpoint? */
21932 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
21934 dbg_breakpoint(fp->uf_name, sourcing_lnum);
21935 /* Find next breakpoint. */
21936 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21937 sourcing_lnum);
21938 fcp->dbg_tick = debug_tick;
21941 return retval;
21944 #if defined(FEAT_PROFILE) || defined(PROTO)
21946 * Called when starting to read a function line.
21947 * "sourcing_lnum" must be correct!
21948 * When skipping lines it may not actually be executed, but we won't find out
21949 * until later and we need to store the time now.
21951 void
21952 func_line_start(cookie)
21953 void *cookie;
21955 funccall_T *fcp = (funccall_T *)cookie;
21956 ufunc_T *fp = fcp->func;
21958 if (fp->uf_profiling && sourcing_lnum >= 1
21959 && sourcing_lnum <= fp->uf_lines.ga_len)
21961 fp->uf_tml_idx = sourcing_lnum - 1;
21962 /* Skip continuation lines. */
21963 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
21964 --fp->uf_tml_idx;
21965 fp->uf_tml_execed = FALSE;
21966 profile_start(&fp->uf_tml_start);
21967 profile_zero(&fp->uf_tml_children);
21968 profile_get_wait(&fp->uf_tml_wait);
21973 * Called when actually executing a function line.
21975 void
21976 func_line_exec(cookie)
21977 void *cookie;
21979 funccall_T *fcp = (funccall_T *)cookie;
21980 ufunc_T *fp = fcp->func;
21982 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21983 fp->uf_tml_execed = TRUE;
21987 * Called when done with a function line.
21989 void
21990 func_line_end(cookie)
21991 void *cookie;
21993 funccall_T *fcp = (funccall_T *)cookie;
21994 ufunc_T *fp = fcp->func;
21996 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21998 if (fp->uf_tml_execed)
22000 ++fp->uf_tml_count[fp->uf_tml_idx];
22001 profile_end(&fp->uf_tml_start);
22002 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
22003 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
22004 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
22005 &fp->uf_tml_children);
22007 fp->uf_tml_idx = -1;
22010 #endif
22013 * Return TRUE if the currently active function should be ended, because a
22014 * return was encountered or an error occurred. Used inside a ":while".
22017 func_has_ended(cookie)
22018 void *cookie;
22020 funccall_T *fcp = (funccall_T *)cookie;
22022 /* Ignore the "abort" flag if the abortion behavior has been changed due to
22023 * an error inside a try conditional. */
22024 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
22025 || fcp->returned);
22029 * return TRUE if cookie indicates a function which "abort"s on errors.
22032 func_has_abort(cookie)
22033 void *cookie;
22035 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
22038 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
22039 typedef enum
22041 VAR_FLAVOUR_DEFAULT, /* doesn't start with uppercase */
22042 VAR_FLAVOUR_SESSION, /* starts with uppercase, some lower */
22043 VAR_FLAVOUR_VIMINFO /* all uppercase */
22044 } var_flavour_T;
22046 static var_flavour_T var_flavour __ARGS((char_u *varname));
22048 static var_flavour_T
22049 var_flavour(varname)
22050 char_u *varname;
22052 char_u *p = varname;
22054 if (ASCII_ISUPPER(*p))
22056 while (*(++p))
22057 if (ASCII_ISLOWER(*p))
22058 return VAR_FLAVOUR_SESSION;
22059 return VAR_FLAVOUR_VIMINFO;
22061 else
22062 return VAR_FLAVOUR_DEFAULT;
22064 #endif
22066 #if defined(FEAT_VIMINFO) || defined(PROTO)
22068 * Restore global vars that start with a capital from the viminfo file
22071 read_viminfo_varlist(virp, writing)
22072 vir_T *virp;
22073 int writing;
22075 char_u *tab;
22076 int type = VAR_NUMBER;
22077 typval_T tv;
22079 if (!writing && (find_viminfo_parameter('!') != NULL))
22081 tab = vim_strchr(virp->vir_line + 1, '\t');
22082 if (tab != NULL)
22084 *tab++ = '\0'; /* isolate the variable name */
22085 if (*tab == 'S') /* string var */
22086 type = VAR_STRING;
22087 #ifdef FEAT_FLOAT
22088 else if (*tab == 'F')
22089 type = VAR_FLOAT;
22090 #endif
22092 tab = vim_strchr(tab, '\t');
22093 if (tab != NULL)
22095 tv.v_type = type;
22096 if (type == VAR_STRING)
22097 tv.vval.v_string = viminfo_readstring(virp,
22098 (int)(tab - virp->vir_line + 1), TRUE);
22099 #ifdef FEAT_FLOAT
22100 else if (type == VAR_FLOAT)
22101 (void)string2float(tab + 1, &tv.vval.v_float);
22102 #endif
22103 else
22104 tv.vval.v_number = atol((char *)tab + 1);
22105 set_var(virp->vir_line + 1, &tv, FALSE);
22106 if (type == VAR_STRING)
22107 vim_free(tv.vval.v_string);
22112 return viminfo_readline(virp);
22116 * Write global vars that start with a capital to the viminfo file
22118 void
22119 write_viminfo_varlist(fp)
22120 FILE *fp;
22122 hashitem_T *hi;
22123 dictitem_T *this_var;
22124 int todo;
22125 char *s;
22126 char_u *p;
22127 char_u *tofree;
22128 char_u numbuf[NUMBUFLEN];
22130 if (find_viminfo_parameter('!') == NULL)
22131 return;
22133 fprintf(fp, _("\n# global variables:\n"));
22135 todo = (int)globvarht.ht_used;
22136 for (hi = globvarht.ht_array; todo > 0; ++hi)
22138 if (!HASHITEM_EMPTY(hi))
22140 --todo;
22141 this_var = HI2DI(hi);
22142 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
22144 switch (this_var->di_tv.v_type)
22146 case VAR_STRING: s = "STR"; break;
22147 case VAR_NUMBER: s = "NUM"; break;
22148 #ifdef FEAT_FLOAT
22149 case VAR_FLOAT: s = "FLO"; break;
22150 #endif
22151 default: continue;
22153 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
22154 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
22155 if (p != NULL)
22156 viminfo_writestring(fp, p);
22157 vim_free(tofree);
22162 #endif
22164 #if defined(FEAT_SESSION) || defined(PROTO)
22166 store_session_globals(fd)
22167 FILE *fd;
22169 hashitem_T *hi;
22170 dictitem_T *this_var;
22171 int todo;
22172 char_u *p, *t;
22174 todo = (int)globvarht.ht_used;
22175 for (hi = globvarht.ht_array; todo > 0; ++hi)
22177 if (!HASHITEM_EMPTY(hi))
22179 --todo;
22180 this_var = HI2DI(hi);
22181 if ((this_var->di_tv.v_type == VAR_NUMBER
22182 || this_var->di_tv.v_type == VAR_STRING)
22183 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22185 /* Escape special characters with a backslash. Turn a LF and
22186 * CR into \n and \r. */
22187 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
22188 (char_u *)"\\\"\n\r");
22189 if (p == NULL) /* out of memory */
22190 break;
22191 for (t = p; *t != NUL; ++t)
22192 if (*t == '\n')
22193 *t = 'n';
22194 else if (*t == '\r')
22195 *t = 'r';
22196 if ((fprintf(fd, "let %s = %c%s%c",
22197 this_var->di_key,
22198 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22199 : ' ',
22201 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22202 : ' ') < 0)
22203 || put_eol(fd) == FAIL)
22205 vim_free(p);
22206 return FAIL;
22208 vim_free(p);
22210 #ifdef FEAT_FLOAT
22211 else if (this_var->di_tv.v_type == VAR_FLOAT
22212 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22214 float_T f = this_var->di_tv.vval.v_float;
22215 int sign = ' ';
22217 if (f < 0)
22219 f = -f;
22220 sign = '-';
22222 if ((fprintf(fd, "let %s = %c&%f",
22223 this_var->di_key, sign, f) < 0)
22224 || put_eol(fd) == FAIL)
22225 return FAIL;
22227 #endif
22230 return OK;
22232 #endif
22235 * Display script name where an item was last set.
22236 * Should only be invoked when 'verbose' is non-zero.
22238 void
22239 last_set_msg(scriptID)
22240 scid_T scriptID;
22242 char_u *p;
22244 if (scriptID != 0)
22246 p = home_replace_save(NULL, get_scriptname(scriptID));
22247 if (p != NULL)
22249 verbose_enter();
22250 MSG_PUTS(_("\n\tLast set from "));
22251 MSG_PUTS(p);
22252 vim_free(p);
22253 verbose_leave();
22259 * List v:oldfiles in a nice way.
22261 void
22262 ex_oldfiles(eap)
22263 exarg_T *eap UNUSED;
22265 list_T *l = vimvars[VV_OLDFILES].vv_list;
22266 listitem_T *li;
22267 int nr = 0;
22269 if (l == NULL)
22270 msg((char_u *)_("No old files"));
22271 else
22273 msg_start();
22274 msg_scroll = TRUE;
22275 for (li = l->lv_first; li != NULL && !got_int; li = li->li_next)
22277 msg_outnum((long)++nr);
22278 MSG_PUTS(": ");
22279 msg_outtrans(get_tv_string(&li->li_tv));
22280 msg_putchar('\n');
22281 out_flush(); /* output one line at a time */
22282 ui_breakcheck();
22284 /* Assume "got_int" was set to truncate the listing. */
22285 got_int = FALSE;
22287 #ifdef FEAT_BROWSE_CMD
22288 if (cmdmod.browse)
22290 quit_more = FALSE;
22291 nr = prompt_for_number(FALSE);
22292 msg_starthere();
22293 if (nr > 0)
22295 char_u *p = list_find_str(get_vim_var_list(VV_OLDFILES),
22296 (long)nr);
22298 if (p != NULL)
22300 p = expand_env_save(p);
22301 eap->arg = p;
22302 eap->cmdidx = CMD_edit;
22303 cmdmod.browse = FALSE;
22304 do_exedit(eap, NULL);
22305 vim_free(p);
22309 #endif
22313 #endif /* FEAT_EVAL */
22316 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
22318 #ifdef WIN3264
22320 * Functions for ":8" filename modifier: get 8.3 version of a filename.
22322 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22323 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
22324 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22327 * Get the short path (8.3) for the filename in "fnamep".
22328 * Only works for a valid file name.
22329 * When the path gets longer "fnamep" is changed and the allocated buffer
22330 * is put in "bufp".
22331 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
22332 * Returns OK on success, FAIL on failure.
22334 static int
22335 get_short_pathname(fnamep, bufp, fnamelen)
22336 char_u **fnamep;
22337 char_u **bufp;
22338 int *fnamelen;
22340 int l, len;
22341 char_u *newbuf;
22343 len = *fnamelen;
22344 l = GetShortPathName(*fnamep, *fnamep, len);
22345 if (l > len - 1)
22347 /* If that doesn't work (not enough space), then save the string
22348 * and try again with a new buffer big enough. */
22349 newbuf = vim_strnsave(*fnamep, l);
22350 if (newbuf == NULL)
22351 return FAIL;
22353 vim_free(*bufp);
22354 *fnamep = *bufp = newbuf;
22356 /* Really should always succeed, as the buffer is big enough. */
22357 l = GetShortPathName(*fnamep, *fnamep, l+1);
22360 *fnamelen = l;
22361 return OK;
22365 * Get the short path (8.3) for the filename in "fname". The converted
22366 * path is returned in "bufp".
22368 * Some of the directories specified in "fname" may not exist. This function
22369 * will shorten the existing directories at the beginning of the path and then
22370 * append the remaining non-existing path.
22372 * fname - Pointer to the filename to shorten. On return, contains the
22373 * pointer to the shortened pathname
22374 * bufp - Pointer to an allocated buffer for the filename.
22375 * fnamelen - Length of the filename pointed to by fname
22377 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
22379 static int
22380 shortpath_for_invalid_fname(fname, bufp, fnamelen)
22381 char_u **fname;
22382 char_u **bufp;
22383 int *fnamelen;
22385 char_u *short_fname, *save_fname, *pbuf_unused;
22386 char_u *endp, *save_endp;
22387 char_u ch;
22388 int old_len, len;
22389 int new_len, sfx_len;
22390 int retval = OK;
22392 /* Make a copy */
22393 old_len = *fnamelen;
22394 save_fname = vim_strnsave(*fname, old_len);
22395 pbuf_unused = NULL;
22396 short_fname = NULL;
22398 endp = save_fname + old_len - 1; /* Find the end of the copy */
22399 save_endp = endp;
22402 * Try shortening the supplied path till it succeeds by removing one
22403 * directory at a time from the tail of the path.
22405 len = 0;
22406 for (;;)
22408 /* go back one path-separator */
22409 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
22410 --endp;
22411 if (endp <= save_fname)
22412 break; /* processed the complete path */
22415 * Replace the path separator with a NUL and try to shorten the
22416 * resulting path.
22418 ch = *endp;
22419 *endp = 0;
22420 short_fname = save_fname;
22421 len = (int)STRLEN(short_fname) + 1;
22422 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
22424 retval = FAIL;
22425 goto theend;
22427 *endp = ch; /* preserve the string */
22429 if (len > 0)
22430 break; /* successfully shortened the path */
22432 /* failed to shorten the path. Skip the path separator */
22433 --endp;
22436 if (len > 0)
22439 * Succeeded in shortening the path. Now concatenate the shortened
22440 * path with the remaining path at the tail.
22443 /* Compute the length of the new path. */
22444 sfx_len = (int)(save_endp - endp) + 1;
22445 new_len = len + sfx_len;
22447 *fnamelen = new_len;
22448 vim_free(*bufp);
22449 if (new_len > old_len)
22451 /* There is not enough space in the currently allocated string,
22452 * copy it to a buffer big enough. */
22453 *fname = *bufp = vim_strnsave(short_fname, new_len);
22454 if (*fname == NULL)
22456 retval = FAIL;
22457 goto theend;
22460 else
22462 /* Transfer short_fname to the main buffer (it's big enough),
22463 * unless get_short_pathname() did its work in-place. */
22464 *fname = *bufp = save_fname;
22465 if (short_fname != save_fname)
22466 vim_strncpy(save_fname, short_fname, len);
22467 save_fname = NULL;
22470 /* concat the not-shortened part of the path */
22471 vim_strncpy(*fname + len, endp, sfx_len);
22472 (*fname)[new_len] = NUL;
22475 theend:
22476 vim_free(pbuf_unused);
22477 vim_free(save_fname);
22479 return retval;
22483 * Get a pathname for a partial path.
22484 * Returns OK for success, FAIL for failure.
22486 static int
22487 shortpath_for_partial(fnamep, bufp, fnamelen)
22488 char_u **fnamep;
22489 char_u **bufp;
22490 int *fnamelen;
22492 int sepcount, len, tflen;
22493 char_u *p;
22494 char_u *pbuf, *tfname;
22495 int hasTilde;
22497 /* Count up the path separators from the RHS.. so we know which part
22498 * of the path to return. */
22499 sepcount = 0;
22500 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
22501 if (vim_ispathsep(*p))
22502 ++sepcount;
22504 /* Need full path first (use expand_env() to remove a "~/") */
22505 hasTilde = (**fnamep == '~');
22506 if (hasTilde)
22507 pbuf = tfname = expand_env_save(*fnamep);
22508 else
22509 pbuf = tfname = FullName_save(*fnamep, FALSE);
22511 len = tflen = (int)STRLEN(tfname);
22513 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
22514 return FAIL;
22516 if (len == 0)
22518 /* Don't have a valid filename, so shorten the rest of the
22519 * path if we can. This CAN give us invalid 8.3 filenames, but
22520 * there's not a lot of point in guessing what it might be.
22522 len = tflen;
22523 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
22524 return FAIL;
22527 /* Count the paths backward to find the beginning of the desired string. */
22528 for (p = tfname + len - 1; p >= tfname; --p)
22530 #ifdef FEAT_MBYTE
22531 if (has_mbyte)
22532 p -= mb_head_off(tfname, p);
22533 #endif
22534 if (vim_ispathsep(*p))
22536 if (sepcount == 0 || (hasTilde && sepcount == 1))
22537 break;
22538 else
22539 sepcount --;
22542 if (hasTilde)
22544 --p;
22545 if (p >= tfname)
22546 *p = '~';
22547 else
22548 return FAIL;
22550 else
22551 ++p;
22553 /* Copy in the string - p indexes into tfname - allocated at pbuf */
22554 vim_free(*bufp);
22555 *fnamelen = (int)STRLEN(p);
22556 *bufp = pbuf;
22557 *fnamep = p;
22559 return OK;
22561 #endif /* WIN3264 */
22564 * Adjust a filename, according to a string of modifiers.
22565 * *fnamep must be NUL terminated when called. When returning, the length is
22566 * determined by *fnamelen.
22567 * Returns VALID_ flags or -1 for failure.
22568 * When there is an error, *fnamep is set to NULL.
22571 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
22572 char_u *src; /* string with modifiers */
22573 int *usedlen; /* characters after src that are used */
22574 char_u **fnamep; /* file name so far */
22575 char_u **bufp; /* buffer for allocated file name or NULL */
22576 int *fnamelen; /* length of fnamep */
22578 int valid = 0;
22579 char_u *tail;
22580 char_u *s, *p, *pbuf;
22581 char_u dirname[MAXPATHL];
22582 int c;
22583 int has_fullname = 0;
22584 #ifdef WIN3264
22585 int has_shortname = 0;
22586 #endif
22588 repeat:
22589 /* ":p" - full path/file_name */
22590 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
22592 has_fullname = 1;
22594 valid |= VALID_PATH;
22595 *usedlen += 2;
22597 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
22598 if ((*fnamep)[0] == '~'
22599 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
22600 && ((*fnamep)[1] == '/'
22601 # ifdef BACKSLASH_IN_FILENAME
22602 || (*fnamep)[1] == '\\'
22603 # endif
22604 || (*fnamep)[1] == NUL)
22606 #endif
22609 *fnamep = expand_env_save(*fnamep);
22610 vim_free(*bufp); /* free any allocated file name */
22611 *bufp = *fnamep;
22612 if (*fnamep == NULL)
22613 return -1;
22616 /* When "/." or "/.." is used: force expansion to get rid of it. */
22617 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
22619 if (vim_ispathsep(*p)
22620 && p[1] == '.'
22621 && (p[2] == NUL
22622 || vim_ispathsep(p[2])
22623 || (p[2] == '.'
22624 && (p[3] == NUL || vim_ispathsep(p[3])))))
22625 break;
22628 /* FullName_save() is slow, don't use it when not needed. */
22629 if (*p != NUL || !vim_isAbsName(*fnamep))
22631 *fnamep = FullName_save(*fnamep, *p != NUL);
22632 vim_free(*bufp); /* free any allocated file name */
22633 *bufp = *fnamep;
22634 if (*fnamep == NULL)
22635 return -1;
22638 /* Append a path separator to a directory. */
22639 if (mch_isdir(*fnamep))
22641 /* Make room for one or two extra characters. */
22642 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
22643 vim_free(*bufp); /* free any allocated file name */
22644 *bufp = *fnamep;
22645 if (*fnamep == NULL)
22646 return -1;
22647 add_pathsep(*fnamep);
22651 /* ":." - path relative to the current directory */
22652 /* ":~" - path relative to the home directory */
22653 /* ":8" - shortname path - postponed till after */
22654 while (src[*usedlen] == ':'
22655 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
22657 *usedlen += 2;
22658 if (c == '8')
22660 #ifdef WIN3264
22661 has_shortname = 1; /* Postpone this. */
22662 #endif
22663 continue;
22665 pbuf = NULL;
22666 /* Need full path first (use expand_env() to remove a "~/") */
22667 if (!has_fullname)
22669 if (c == '.' && **fnamep == '~')
22670 p = pbuf = expand_env_save(*fnamep);
22671 else
22672 p = pbuf = FullName_save(*fnamep, FALSE);
22674 else
22675 p = *fnamep;
22677 has_fullname = 0;
22679 if (p != NULL)
22681 if (c == '.')
22683 mch_dirname(dirname, MAXPATHL);
22684 s = shorten_fname(p, dirname);
22685 if (s != NULL)
22687 *fnamep = s;
22688 if (pbuf != NULL)
22690 vim_free(*bufp); /* free any allocated file name */
22691 *bufp = pbuf;
22692 pbuf = NULL;
22696 else
22698 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
22699 /* Only replace it when it starts with '~' */
22700 if (*dirname == '~')
22702 s = vim_strsave(dirname);
22703 if (s != NULL)
22705 *fnamep = s;
22706 vim_free(*bufp);
22707 *bufp = s;
22711 vim_free(pbuf);
22715 tail = gettail(*fnamep);
22716 *fnamelen = (int)STRLEN(*fnamep);
22718 /* ":h" - head, remove "/file_name", can be repeated */
22719 /* Don't remove the first "/" or "c:\" */
22720 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
22722 valid |= VALID_HEAD;
22723 *usedlen += 2;
22724 s = get_past_head(*fnamep);
22725 while (tail > s && after_pathsep(s, tail))
22726 mb_ptr_back(*fnamep, tail);
22727 *fnamelen = (int)(tail - *fnamep);
22728 #ifdef VMS
22729 if (*fnamelen > 0)
22730 *fnamelen += 1; /* the path separator is part of the path */
22731 #endif
22732 if (*fnamelen == 0)
22734 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
22735 p = vim_strsave((char_u *)".");
22736 if (p == NULL)
22737 return -1;
22738 vim_free(*bufp);
22739 *bufp = *fnamep = tail = p;
22740 *fnamelen = 1;
22742 else
22744 while (tail > s && !after_pathsep(s, tail))
22745 mb_ptr_back(*fnamep, tail);
22749 /* ":8" - shortname */
22750 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
22752 *usedlen += 2;
22753 #ifdef WIN3264
22754 has_shortname = 1;
22755 #endif
22758 #ifdef WIN3264
22759 /* Check shortname after we have done 'heads' and before we do 'tails'
22761 if (has_shortname)
22763 pbuf = NULL;
22764 /* Copy the string if it is shortened by :h */
22765 if (*fnamelen < (int)STRLEN(*fnamep))
22767 p = vim_strnsave(*fnamep, *fnamelen);
22768 if (p == 0)
22769 return -1;
22770 vim_free(*bufp);
22771 *bufp = *fnamep = p;
22774 /* Split into two implementations - makes it easier. First is where
22775 * there isn't a full name already, second is where there is.
22777 if (!has_fullname && !vim_isAbsName(*fnamep))
22779 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
22780 return -1;
22782 else
22784 int l;
22786 /* Simple case, already have the full-name
22787 * Nearly always shorter, so try first time. */
22788 l = *fnamelen;
22789 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
22790 return -1;
22792 if (l == 0)
22794 /* Couldn't find the filename.. search the paths.
22796 l = *fnamelen;
22797 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
22798 return -1;
22800 *fnamelen = l;
22803 #endif /* WIN3264 */
22805 /* ":t" - tail, just the basename */
22806 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
22808 *usedlen += 2;
22809 *fnamelen -= (int)(tail - *fnamep);
22810 *fnamep = tail;
22813 /* ":e" - extension, can be repeated */
22814 /* ":r" - root, without extension, can be repeated */
22815 while (src[*usedlen] == ':'
22816 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
22818 /* find a '.' in the tail:
22819 * - for second :e: before the current fname
22820 * - otherwise: The last '.'
22822 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
22823 s = *fnamep - 2;
22824 else
22825 s = *fnamep + *fnamelen - 1;
22826 for ( ; s > tail; --s)
22827 if (s[0] == '.')
22828 break;
22829 if (src[*usedlen + 1] == 'e') /* :e */
22831 if (s > tail)
22833 *fnamelen += (int)(*fnamep - (s + 1));
22834 *fnamep = s + 1;
22835 #ifdef VMS
22836 /* cut version from the extension */
22837 s = *fnamep + *fnamelen - 1;
22838 for ( ; s > *fnamep; --s)
22839 if (s[0] == ';')
22840 break;
22841 if (s > *fnamep)
22842 *fnamelen = s - *fnamep;
22843 #endif
22845 else if (*fnamep <= tail)
22846 *fnamelen = 0;
22848 else /* :r */
22850 if (s > tail) /* remove one extension */
22851 *fnamelen = (int)(s - *fnamep);
22853 *usedlen += 2;
22856 /* ":s?pat?foo?" - substitute */
22857 /* ":gs?pat?foo?" - global substitute */
22858 if (src[*usedlen] == ':'
22859 && (src[*usedlen + 1] == 's'
22860 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
22862 char_u *str;
22863 char_u *pat;
22864 char_u *sub;
22865 int sep;
22866 char_u *flags;
22867 int didit = FALSE;
22869 flags = (char_u *)"";
22870 s = src + *usedlen + 2;
22871 if (src[*usedlen + 1] == 'g')
22873 flags = (char_u *)"g";
22874 ++s;
22877 sep = *s++;
22878 if (sep)
22880 /* find end of pattern */
22881 p = vim_strchr(s, sep);
22882 if (p != NULL)
22884 pat = vim_strnsave(s, (int)(p - s));
22885 if (pat != NULL)
22887 s = p + 1;
22888 /* find end of substitution */
22889 p = vim_strchr(s, sep);
22890 if (p != NULL)
22892 sub = vim_strnsave(s, (int)(p - s));
22893 str = vim_strnsave(*fnamep, *fnamelen);
22894 if (sub != NULL && str != NULL)
22896 *usedlen = (int)(p + 1 - src);
22897 s = do_string_sub(str, pat, sub, flags);
22898 if (s != NULL)
22900 *fnamep = s;
22901 *fnamelen = (int)STRLEN(s);
22902 vim_free(*bufp);
22903 *bufp = s;
22904 didit = TRUE;
22907 vim_free(sub);
22908 vim_free(str);
22910 vim_free(pat);
22913 /* after using ":s", repeat all the modifiers */
22914 if (didit)
22915 goto repeat;
22919 return valid;
22923 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
22924 * "flags" can be "g" to do a global substitute.
22925 * Returns an allocated string, NULL for error.
22927 char_u *
22928 do_string_sub(str, pat, sub, flags)
22929 char_u *str;
22930 char_u *pat;
22931 char_u *sub;
22932 char_u *flags;
22934 int sublen;
22935 regmatch_T regmatch;
22936 int i;
22937 int do_all;
22938 char_u *tail;
22939 garray_T ga;
22940 char_u *ret;
22941 char_u *save_cpo;
22943 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
22944 save_cpo = p_cpo;
22945 p_cpo = empty_option;
22947 ga_init2(&ga, 1, 200);
22949 do_all = (flags[0] == 'g');
22951 regmatch.rm_ic = p_ic;
22952 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
22953 if (regmatch.regprog != NULL)
22955 tail = str;
22956 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
22959 * Get some space for a temporary buffer to do the substitution
22960 * into. It will contain:
22961 * - The text up to where the match is.
22962 * - The substituted text.
22963 * - The text after the match.
22965 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
22966 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
22967 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
22969 ga_clear(&ga);
22970 break;
22973 /* copy the text up to where the match is */
22974 i = (int)(regmatch.startp[0] - tail);
22975 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
22976 /* add the substituted text */
22977 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
22978 + ga.ga_len + i, TRUE, TRUE, FALSE);
22979 ga.ga_len += i + sublen - 1;
22980 /* avoid getting stuck on a match with an empty string */
22981 if (tail == regmatch.endp[0])
22983 if (*tail == NUL)
22984 break;
22985 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
22986 ++ga.ga_len;
22988 else
22990 tail = regmatch.endp[0];
22991 if (*tail == NUL)
22992 break;
22994 if (!do_all)
22995 break;
22998 if (ga.ga_data != NULL)
22999 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
23001 vim_free(regmatch.regprog);
23004 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
23005 ga_clear(&ga);
23006 if (p_cpo == empty_option)
23007 p_cpo = save_cpo;
23008 else
23009 /* Darn, evaluating {sub} expression changed the value. */
23010 free_string_option(save_cpo);
23012 return ret;
23015 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */