Merge branch 'vim' into feat/float-point-ext
[vim_extended.git] / src / eval.c
blobe6f9ef007d1a7c70fc8cf727a86437cf618cd874
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_RUBY) || defined(FEAT_PYTHON) || defined(FEAT_MZSCHEME) \
5891 || defined(PROTO)
5893 * Return the dictitem that an entry in a hashtable points to.
5895 dictitem_T *
5896 dict_lookup(hi)
5897 hashitem_T *hi;
5899 return HI2DI(hi);
5901 #endif
5904 * Return TRUE when two dictionaries have exactly the same key/values.
5906 static int
5907 dict_equal(d1, d2, ic)
5908 dict_T *d1;
5909 dict_T *d2;
5910 int ic; /* ignore case for strings */
5912 hashitem_T *hi;
5913 dictitem_T *item2;
5914 int todo;
5916 if (d1 == NULL || d2 == NULL)
5917 return FALSE;
5918 if (d1 == d2)
5919 return TRUE;
5920 if (dict_len(d1) != dict_len(d2))
5921 return FALSE;
5923 todo = (int)d1->dv_hashtab.ht_used;
5924 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5926 if (!HASHITEM_EMPTY(hi))
5928 item2 = dict_find(d2, hi->hi_key, -1);
5929 if (item2 == NULL)
5930 return FALSE;
5931 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5932 return FALSE;
5933 --todo;
5936 return TRUE;
5940 * Return TRUE if "tv1" and "tv2" have the same value.
5941 * Compares the items just like "==" would compare them, but strings and
5942 * numbers are different. Floats and numbers are also different.
5944 static int
5945 tv_equal(tv1, tv2, ic)
5946 typval_T *tv1;
5947 typval_T *tv2;
5948 int ic; /* ignore case */
5950 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5951 char_u *s1, *s2;
5952 static int recursive = 0; /* cach recursive loops */
5953 int r;
5955 if (tv1->v_type != tv2->v_type)
5956 return FALSE;
5957 /* Catch lists and dicts that have an endless loop by limiting
5958 * recursiveness to 1000. We guess they are equal then. */
5959 if (recursive >= 1000)
5960 return TRUE;
5962 switch (tv1->v_type)
5964 case VAR_LIST:
5965 ++recursive;
5966 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5967 --recursive;
5968 return r;
5970 case VAR_DICT:
5971 ++recursive;
5972 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5973 --recursive;
5974 return r;
5976 case VAR_FUNC:
5977 return (tv1->vval.v_string != NULL
5978 && tv2->vval.v_string != NULL
5979 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5981 case VAR_NUMBER:
5982 return tv1->vval.v_number == tv2->vval.v_number;
5984 #ifdef FEAT_FLOAT
5985 case VAR_FLOAT:
5986 return tv1->vval.v_float == tv2->vval.v_float;
5987 #endif
5989 case VAR_STRING:
5990 s1 = get_tv_string_buf(tv1, buf1);
5991 s2 = get_tv_string_buf(tv2, buf2);
5992 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5995 EMSG2(_(e_intern2), "tv_equal()");
5996 return TRUE;
6000 * Locate item with index "n" in list "l" and return it.
6001 * A negative index is counted from the end; -1 is the last item.
6002 * Returns NULL when "n" is out of range.
6004 static listitem_T *
6005 list_find(l, n)
6006 list_T *l;
6007 long n;
6009 listitem_T *item;
6010 long idx;
6012 if (l == NULL)
6013 return NULL;
6015 /* Negative index is relative to the end. */
6016 if (n < 0)
6017 n = l->lv_len + n;
6019 /* Check for index out of range. */
6020 if (n < 0 || n >= l->lv_len)
6021 return NULL;
6023 /* When there is a cached index may start search from there. */
6024 if (l->lv_idx_item != NULL)
6026 if (n < l->lv_idx / 2)
6028 /* closest to the start of the list */
6029 item = l->lv_first;
6030 idx = 0;
6032 else if (n > (l->lv_idx + l->lv_len) / 2)
6034 /* closest to the end of the list */
6035 item = l->lv_last;
6036 idx = l->lv_len - 1;
6038 else
6040 /* closest to the cached index */
6041 item = l->lv_idx_item;
6042 idx = l->lv_idx;
6045 else
6047 if (n < l->lv_len / 2)
6049 /* closest to the start of the list */
6050 item = l->lv_first;
6051 idx = 0;
6053 else
6055 /* closest to the end of the list */
6056 item = l->lv_last;
6057 idx = l->lv_len - 1;
6061 while (n > idx)
6063 /* search forward */
6064 item = item->li_next;
6065 ++idx;
6067 while (n < idx)
6069 /* search backward */
6070 item = item->li_prev;
6071 --idx;
6074 /* cache the used index */
6075 l->lv_idx = idx;
6076 l->lv_idx_item = item;
6078 return item;
6082 * Get list item "l[idx]" as a number.
6084 static long
6085 list_find_nr(l, idx, errorp)
6086 list_T *l;
6087 long idx;
6088 int *errorp; /* set to TRUE when something wrong */
6090 listitem_T *li;
6092 li = list_find(l, idx);
6093 if (li == NULL)
6095 if (errorp != NULL)
6096 *errorp = TRUE;
6097 return -1L;
6099 return get_tv_number_chk(&li->li_tv, errorp);
6103 * Get list item "l[idx - 1]" as a string. Returns NULL for failure.
6105 char_u *
6106 list_find_str(l, idx)
6107 list_T *l;
6108 long idx;
6110 listitem_T *li;
6112 li = list_find(l, idx - 1);
6113 if (li == NULL)
6115 EMSGN(_(e_listidx), idx);
6116 return NULL;
6118 return get_tv_string(&li->li_tv);
6122 * Locate "item" list "l" and return its index.
6123 * Returns -1 when "item" is not in the list.
6125 static long
6126 list_idx_of_item(l, item)
6127 list_T *l;
6128 listitem_T *item;
6130 long idx = 0;
6131 listitem_T *li;
6133 if (l == NULL)
6134 return -1;
6135 idx = 0;
6136 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
6137 ++idx;
6138 if (li == NULL)
6139 return -1;
6140 return idx;
6144 * Append item "item" to the end of list "l".
6146 static void
6147 list_append(l, item)
6148 list_T *l;
6149 listitem_T *item;
6151 if (l->lv_last == NULL)
6153 /* empty list */
6154 l->lv_first = item;
6155 l->lv_last = item;
6156 item->li_prev = NULL;
6158 else
6160 l->lv_last->li_next = item;
6161 item->li_prev = l->lv_last;
6162 l->lv_last = item;
6164 ++l->lv_len;
6165 item->li_next = NULL;
6169 * Append typval_T "tv" to the end of list "l".
6170 * Return FAIL when out of memory.
6173 list_append_tv(l, tv)
6174 list_T *l;
6175 typval_T *tv;
6177 listitem_T *li = listitem_alloc();
6179 if (li == NULL)
6180 return FAIL;
6181 copy_tv(tv, &li->li_tv);
6182 list_append(l, li);
6183 return OK;
6187 * Add a dictionary to a list. Used by getqflist().
6188 * Return FAIL when out of memory.
6191 list_append_dict(list, dict)
6192 list_T *list;
6193 dict_T *dict;
6195 listitem_T *li = listitem_alloc();
6197 if (li == NULL)
6198 return FAIL;
6199 li->li_tv.v_type = VAR_DICT;
6200 li->li_tv.v_lock = 0;
6201 li->li_tv.vval.v_dict = dict;
6202 list_append(list, li);
6203 ++dict->dv_refcount;
6204 return OK;
6208 * Make a copy of "str" and append it as an item to list "l".
6209 * When "len" >= 0 use "str[len]".
6210 * Returns FAIL when out of memory.
6213 list_append_string(l, str, len)
6214 list_T *l;
6215 char_u *str;
6216 int len;
6218 listitem_T *li = listitem_alloc();
6220 if (li == NULL)
6221 return FAIL;
6222 list_append(l, li);
6223 li->li_tv.v_type = VAR_STRING;
6224 li->li_tv.v_lock = 0;
6225 if (str == NULL)
6226 li->li_tv.vval.v_string = NULL;
6227 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
6228 : vim_strsave(str))) == NULL)
6229 return FAIL;
6230 return OK;
6234 * Append "n" to list "l".
6235 * Returns FAIL when out of memory.
6237 static int
6238 list_append_number(l, n)
6239 list_T *l;
6240 varnumber_T n;
6242 listitem_T *li;
6244 li = listitem_alloc();
6245 if (li == NULL)
6246 return FAIL;
6247 li->li_tv.v_type = VAR_NUMBER;
6248 li->li_tv.v_lock = 0;
6249 li->li_tv.vval.v_number = n;
6250 list_append(l, li);
6251 return OK;
6255 * Insert typval_T "tv" in list "l" before "item".
6256 * If "item" is NULL append at the end.
6257 * Return FAIL when out of memory.
6259 static int
6260 list_insert_tv(l, tv, item)
6261 list_T *l;
6262 typval_T *tv;
6263 listitem_T *item;
6265 listitem_T *ni = listitem_alloc();
6267 if (ni == NULL)
6268 return FAIL;
6269 copy_tv(tv, &ni->li_tv);
6270 if (item == NULL)
6271 /* Append new item at end of list. */
6272 list_append(l, ni);
6273 else
6275 /* Insert new item before existing item. */
6276 ni->li_prev = item->li_prev;
6277 ni->li_next = item;
6278 if (item->li_prev == NULL)
6280 l->lv_first = ni;
6281 ++l->lv_idx;
6283 else
6285 item->li_prev->li_next = ni;
6286 l->lv_idx_item = NULL;
6288 item->li_prev = ni;
6289 ++l->lv_len;
6291 return OK;
6295 * Extend "l1" with "l2".
6296 * If "bef" is NULL append at the end, otherwise insert before this item.
6297 * Returns FAIL when out of memory.
6299 static int
6300 list_extend(l1, l2, bef)
6301 list_T *l1;
6302 list_T *l2;
6303 listitem_T *bef;
6305 listitem_T *item;
6306 int todo = l2->lv_len;
6308 /* We also quit the loop when we have inserted the original item count of
6309 * the list, avoid a hang when we extend a list with itself. */
6310 for (item = l2->lv_first; item != NULL && --todo >= 0; item = item->li_next)
6311 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
6312 return FAIL;
6313 return OK;
6317 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
6318 * Return FAIL when out of memory.
6320 static int
6321 list_concat(l1, l2, tv)
6322 list_T *l1;
6323 list_T *l2;
6324 typval_T *tv;
6326 list_T *l;
6328 if (l1 == NULL || l2 == NULL)
6329 return FAIL;
6331 /* make a copy of the first list. */
6332 l = list_copy(l1, FALSE, 0);
6333 if (l == NULL)
6334 return FAIL;
6335 tv->v_type = VAR_LIST;
6336 tv->vval.v_list = l;
6338 /* append all items from the second list */
6339 return list_extend(l, l2, NULL);
6343 * Make a copy of list "orig". Shallow if "deep" is FALSE.
6344 * The refcount of the new list is set to 1.
6345 * See item_copy() for "copyID".
6346 * Returns NULL when out of memory.
6348 static list_T *
6349 list_copy(orig, deep, copyID)
6350 list_T *orig;
6351 int deep;
6352 int copyID;
6354 list_T *copy;
6355 listitem_T *item;
6356 listitem_T *ni;
6358 if (orig == NULL)
6359 return NULL;
6361 copy = list_alloc();
6362 if (copy != NULL)
6364 if (copyID != 0)
6366 /* Do this before adding the items, because one of the items may
6367 * refer back to this list. */
6368 orig->lv_copyID = copyID;
6369 orig->lv_copylist = copy;
6371 for (item = orig->lv_first; item != NULL && !got_int;
6372 item = item->li_next)
6374 ni = listitem_alloc();
6375 if (ni == NULL)
6376 break;
6377 if (deep)
6379 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
6381 vim_free(ni);
6382 break;
6385 else
6386 copy_tv(&item->li_tv, &ni->li_tv);
6387 list_append(copy, ni);
6389 ++copy->lv_refcount;
6390 if (item != NULL)
6392 list_unref(copy);
6393 copy = NULL;
6397 return copy;
6401 * Remove items "item" to "item2" from list "l".
6402 * Does not free the listitem or the value!
6404 static void
6405 list_remove(l, item, item2)
6406 list_T *l;
6407 listitem_T *item;
6408 listitem_T *item2;
6410 listitem_T *ip;
6412 /* notify watchers */
6413 for (ip = item; ip != NULL; ip = ip->li_next)
6415 --l->lv_len;
6416 list_fix_watch(l, ip);
6417 if (ip == item2)
6418 break;
6421 if (item2->li_next == NULL)
6422 l->lv_last = item->li_prev;
6423 else
6424 item2->li_next->li_prev = item->li_prev;
6425 if (item->li_prev == NULL)
6426 l->lv_first = item2->li_next;
6427 else
6428 item->li_prev->li_next = item2->li_next;
6429 l->lv_idx_item = NULL;
6433 * Return an allocated string with the string representation of a list.
6434 * May return NULL.
6436 static char_u *
6437 list2string(tv, copyID)
6438 typval_T *tv;
6439 int copyID;
6441 garray_T ga;
6443 if (tv->vval.v_list == NULL)
6444 return NULL;
6445 ga_init2(&ga, (int)sizeof(char), 80);
6446 ga_append(&ga, '[');
6447 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6449 vim_free(ga.ga_data);
6450 return NULL;
6452 ga_append(&ga, ']');
6453 ga_append(&ga, NUL);
6454 return (char_u *)ga.ga_data;
6458 * Join list "l" into a string in "*gap", using separator "sep".
6459 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6460 * Return FAIL or OK.
6462 static int
6463 list_join(gap, l, sep, echo, copyID)
6464 garray_T *gap;
6465 list_T *l;
6466 char_u *sep;
6467 int echo;
6468 int copyID;
6470 int first = TRUE;
6471 char_u *tofree;
6472 char_u numbuf[NUMBUFLEN];
6473 listitem_T *item;
6474 char_u *s;
6476 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6478 if (first)
6479 first = FALSE;
6480 else
6481 ga_concat(gap, sep);
6483 if (echo)
6484 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6485 else
6486 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6487 if (s != NULL)
6488 ga_concat(gap, s);
6489 vim_free(tofree);
6490 if (s == NULL)
6491 return FAIL;
6492 line_breakcheck();
6494 return OK;
6498 * Garbage collection for lists and dictionaries.
6500 * We use reference counts to be able to free most items right away when they
6501 * are no longer used. But for composite items it's possible that it becomes
6502 * unused while the reference count is > 0: When there is a recursive
6503 * reference. Example:
6504 * :let l = [1, 2, 3]
6505 * :let d = {9: l}
6506 * :let l[1] = d
6508 * Since this is quite unusual we handle this with garbage collection: every
6509 * once in a while find out which lists and dicts are not referenced from any
6510 * variable.
6512 * Here is a good reference text about garbage collection (refers to Python
6513 * but it applies to all reference-counting mechanisms):
6514 * http://python.ca/nas/python/gc/
6518 * Do garbage collection for lists and dicts.
6519 * Return TRUE if some memory was freed.
6522 garbage_collect()
6524 int copyID;
6525 buf_T *buf;
6526 win_T *wp;
6527 int i;
6528 funccall_T *fc, **pfc;
6529 int did_free;
6530 int did_free_funccal = FALSE;
6531 #ifdef FEAT_WINDOWS
6532 tabpage_T *tp;
6533 #endif
6535 /* Only do this once. */
6536 want_garbage_collect = FALSE;
6537 may_garbage_collect = FALSE;
6538 garbage_collect_at_exit = FALSE;
6540 /* We advance by two because we add one for items referenced through
6541 * previous_funccal. */
6542 current_copyID += COPYID_INC;
6543 copyID = current_copyID;
6546 * 1. Go through all accessible variables and mark all lists and dicts
6547 * with copyID.
6550 /* Don't free variables in the previous_funccal list unless they are only
6551 * referenced through previous_funccal. This must be first, because if
6552 * the item is referenced elsewhere the funccal must not be freed. */
6553 for (fc = previous_funccal; fc != NULL; fc = fc->caller)
6555 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1);
6556 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1);
6559 /* script-local variables */
6560 for (i = 1; i <= ga_scripts.ga_len; ++i)
6561 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6563 /* buffer-local variables */
6564 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6565 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6567 /* window-local variables */
6568 FOR_ALL_TAB_WINDOWS(tp, wp)
6569 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6571 #ifdef FEAT_WINDOWS
6572 /* tabpage-local variables */
6573 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6574 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6575 #endif
6577 /* global variables */
6578 set_ref_in_ht(&globvarht, copyID);
6580 /* function-local variables */
6581 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6583 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6584 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6587 /* v: vars */
6588 set_ref_in_ht(&vimvarht, copyID);
6591 * 2. Free lists and dictionaries that are not referenced.
6593 did_free = free_unref_items(copyID);
6596 * 3. Check if any funccal can be freed now.
6598 for (pfc = &previous_funccal; *pfc != NULL; )
6600 if (can_free_funccal(*pfc, copyID))
6602 fc = *pfc;
6603 *pfc = fc->caller;
6604 free_funccal(fc, TRUE);
6605 did_free = TRUE;
6606 did_free_funccal = TRUE;
6608 else
6609 pfc = &(*pfc)->caller;
6611 if (did_free_funccal)
6612 /* When a funccal was freed some more items might be garbage
6613 * collected, so run again. */
6614 (void)garbage_collect();
6616 return did_free;
6620 * Free lists and dictionaries that are no longer referenced.
6622 static int
6623 free_unref_items(copyID)
6624 int copyID;
6626 dict_T *dd;
6627 list_T *ll;
6628 int did_free = FALSE;
6631 * Go through the list of dicts and free items without the copyID.
6633 for (dd = first_dict; dd != NULL; )
6634 if ((dd->dv_copyID & COPYID_MASK) != (copyID & COPYID_MASK))
6636 /* Free the Dictionary and ordinary items it contains, but don't
6637 * recurse into Lists and Dictionaries, they will be in the list
6638 * of dicts or list of lists. */
6639 dict_free(dd, FALSE);
6640 did_free = TRUE;
6642 /* restart, next dict may also have been freed */
6643 dd = first_dict;
6645 else
6646 dd = dd->dv_used_next;
6649 * Go through the list of lists and free items without the copyID.
6650 * But don't free a list that has a watcher (used in a for loop), these
6651 * are not referenced anywhere.
6653 for (ll = first_list; ll != NULL; )
6654 if ((ll->lv_copyID & COPYID_MASK) != (copyID & COPYID_MASK)
6655 && ll->lv_watch == NULL)
6657 /* Free the List and ordinary items it contains, but don't recurse
6658 * into Lists and Dictionaries, they will be in the list of dicts
6659 * or list of lists. */
6660 list_free(ll, FALSE);
6661 did_free = TRUE;
6663 /* restart, next list may also have been freed */
6664 ll = first_list;
6666 else
6667 ll = ll->lv_used_next;
6669 return did_free;
6673 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6675 static void
6676 set_ref_in_ht(ht, copyID)
6677 hashtab_T *ht;
6678 int copyID;
6680 int todo;
6681 hashitem_T *hi;
6683 todo = (int)ht->ht_used;
6684 for (hi = ht->ht_array; todo > 0; ++hi)
6685 if (!HASHITEM_EMPTY(hi))
6687 --todo;
6688 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6693 * Mark all lists and dicts referenced through list "l" with "copyID".
6695 static void
6696 set_ref_in_list(l, copyID)
6697 list_T *l;
6698 int copyID;
6700 listitem_T *li;
6702 for (li = l->lv_first; li != NULL; li = li->li_next)
6703 set_ref_in_item(&li->li_tv, copyID);
6707 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6709 static void
6710 set_ref_in_item(tv, copyID)
6711 typval_T *tv;
6712 int copyID;
6714 dict_T *dd;
6715 list_T *ll;
6717 switch (tv->v_type)
6719 case VAR_DICT:
6720 dd = tv->vval.v_dict;
6721 if (dd != NULL && dd->dv_copyID != copyID)
6723 /* Didn't see this dict yet. */
6724 dd->dv_copyID = copyID;
6725 set_ref_in_ht(&dd->dv_hashtab, copyID);
6727 break;
6729 case VAR_LIST:
6730 ll = tv->vval.v_list;
6731 if (ll != NULL && ll->lv_copyID != copyID)
6733 /* Didn't see this list yet. */
6734 ll->lv_copyID = copyID;
6735 set_ref_in_list(ll, copyID);
6737 break;
6739 return;
6743 * Allocate an empty header for a dictionary.
6745 dict_T *
6746 dict_alloc()
6748 dict_T *d;
6750 d = (dict_T *)alloc(sizeof(dict_T));
6751 if (d != NULL)
6753 /* Add the list to the list of dicts for garbage collection. */
6754 if (first_dict != NULL)
6755 first_dict->dv_used_prev = d;
6756 d->dv_used_next = first_dict;
6757 d->dv_used_prev = NULL;
6758 first_dict = d;
6760 hash_init(&d->dv_hashtab);
6761 d->dv_lock = 0;
6762 d->dv_refcount = 0;
6763 d->dv_copyID = 0;
6765 return d;
6769 * Unreference a Dictionary: decrement the reference count and free it when it
6770 * becomes zero.
6772 static void
6773 dict_unref(d)
6774 dict_T *d;
6776 if (d != NULL && --d->dv_refcount <= 0)
6777 dict_free(d, TRUE);
6781 * Free a Dictionary, including all items it contains.
6782 * Ignores the reference count.
6784 static void
6785 dict_free(d, recurse)
6786 dict_T *d;
6787 int recurse; /* Free Lists and Dictionaries recursively. */
6789 int todo;
6790 hashitem_T *hi;
6791 dictitem_T *di;
6793 /* Remove the dict from the list of dicts for garbage collection. */
6794 if (d->dv_used_prev == NULL)
6795 first_dict = d->dv_used_next;
6796 else
6797 d->dv_used_prev->dv_used_next = d->dv_used_next;
6798 if (d->dv_used_next != NULL)
6799 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6801 /* Lock the hashtab, we don't want it to resize while freeing items. */
6802 hash_lock(&d->dv_hashtab);
6803 todo = (int)d->dv_hashtab.ht_used;
6804 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6806 if (!HASHITEM_EMPTY(hi))
6808 /* Remove the item before deleting it, just in case there is
6809 * something recursive causing trouble. */
6810 di = HI2DI(hi);
6811 hash_remove(&d->dv_hashtab, hi);
6812 if (recurse || (di->di_tv.v_type != VAR_LIST
6813 && di->di_tv.v_type != VAR_DICT))
6814 clear_tv(&di->di_tv);
6815 vim_free(di);
6816 --todo;
6819 hash_clear(&d->dv_hashtab);
6820 vim_free(d);
6824 * Allocate a Dictionary item.
6825 * The "key" is copied to the new item.
6826 * Note that the value of the item "di_tv" still needs to be initialized!
6827 * Returns NULL when out of memory.
6829 dictitem_T *
6830 dictitem_alloc(key)
6831 char_u *key;
6833 dictitem_T *di;
6835 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6836 if (di != NULL)
6838 STRCPY(di->di_key, key);
6839 di->di_flags = 0;
6841 return di;
6845 * Make a copy of a Dictionary item.
6847 static dictitem_T *
6848 dictitem_copy(org)
6849 dictitem_T *org;
6851 dictitem_T *di;
6853 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6854 + STRLEN(org->di_key)));
6855 if (di != NULL)
6857 STRCPY(di->di_key, org->di_key);
6858 di->di_flags = 0;
6859 copy_tv(&org->di_tv, &di->di_tv);
6861 return di;
6865 * Remove item "item" from Dictionary "dict" and free it.
6867 static void
6868 dictitem_remove(dict, item)
6869 dict_T *dict;
6870 dictitem_T *item;
6872 hashitem_T *hi;
6874 hi = hash_find(&dict->dv_hashtab, item->di_key);
6875 if (HASHITEM_EMPTY(hi))
6876 EMSG2(_(e_intern2), "dictitem_remove()");
6877 else
6878 hash_remove(&dict->dv_hashtab, hi);
6879 dictitem_free(item);
6883 * Free a dict item. Also clears the value.
6885 void
6886 dictitem_free(item)
6887 dictitem_T *item;
6889 clear_tv(&item->di_tv);
6890 vim_free(item);
6894 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6895 * The refcount of the new dict is set to 1.
6896 * See item_copy() for "copyID".
6897 * Returns NULL when out of memory.
6899 static dict_T *
6900 dict_copy(orig, deep, copyID)
6901 dict_T *orig;
6902 int deep;
6903 int copyID;
6905 dict_T *copy;
6906 dictitem_T *di;
6907 int todo;
6908 hashitem_T *hi;
6910 if (orig == NULL)
6911 return NULL;
6913 copy = dict_alloc();
6914 if (copy != NULL)
6916 if (copyID != 0)
6918 orig->dv_copyID = copyID;
6919 orig->dv_copydict = copy;
6921 todo = (int)orig->dv_hashtab.ht_used;
6922 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6924 if (!HASHITEM_EMPTY(hi))
6926 --todo;
6928 di = dictitem_alloc(hi->hi_key);
6929 if (di == NULL)
6930 break;
6931 if (deep)
6933 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6934 copyID) == FAIL)
6936 vim_free(di);
6937 break;
6940 else
6941 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6942 if (dict_add(copy, di) == FAIL)
6944 dictitem_free(di);
6945 break;
6950 ++copy->dv_refcount;
6951 if (todo > 0)
6953 dict_unref(copy);
6954 copy = NULL;
6958 return copy;
6962 * Add item "item" to Dictionary "d".
6963 * Returns FAIL when out of memory and when key already existed.
6966 dict_add(d, item)
6967 dict_T *d;
6968 dictitem_T *item;
6970 return hash_add(&d->dv_hashtab, item->di_key);
6974 * Add a number or string entry to dictionary "d".
6975 * When "str" is NULL use number "nr", otherwise use "str".
6976 * Returns FAIL when out of memory and when key already exists.
6979 dict_add_nr_str(d, key, nr, str)
6980 dict_T *d;
6981 char *key;
6982 long nr;
6983 char_u *str;
6985 dictitem_T *item;
6987 item = dictitem_alloc((char_u *)key);
6988 if (item == NULL)
6989 return FAIL;
6990 item->di_tv.v_lock = 0;
6991 if (str == NULL)
6993 item->di_tv.v_type = VAR_NUMBER;
6994 item->di_tv.vval.v_number = nr;
6996 else
6998 item->di_tv.v_type = VAR_STRING;
6999 item->di_tv.vval.v_string = vim_strsave(str);
7001 if (dict_add(d, item) == FAIL)
7003 dictitem_free(item);
7004 return FAIL;
7006 return OK;
7010 * Get the number of items in a Dictionary.
7012 static long
7013 dict_len(d)
7014 dict_T *d;
7016 if (d == NULL)
7017 return 0L;
7018 return (long)d->dv_hashtab.ht_used;
7022 * Find item "key[len]" in Dictionary "d".
7023 * If "len" is negative use strlen(key).
7024 * Returns NULL when not found.
7026 static dictitem_T *
7027 dict_find(d, key, len)
7028 dict_T *d;
7029 char_u *key;
7030 int len;
7032 #define AKEYLEN 200
7033 char_u buf[AKEYLEN];
7034 char_u *akey;
7035 char_u *tofree = NULL;
7036 hashitem_T *hi;
7038 if (len < 0)
7039 akey = key;
7040 else if (len >= AKEYLEN)
7042 tofree = akey = vim_strnsave(key, len);
7043 if (akey == NULL)
7044 return NULL;
7046 else
7048 /* Avoid a malloc/free by using buf[]. */
7049 vim_strncpy(buf, key, len);
7050 akey = buf;
7053 hi = hash_find(&d->dv_hashtab, akey);
7054 vim_free(tofree);
7055 if (HASHITEM_EMPTY(hi))
7056 return NULL;
7057 return HI2DI(hi);
7061 * Get a string item from a dictionary.
7062 * When "save" is TRUE allocate memory for it.
7063 * Returns NULL if the entry doesn't exist or out of memory.
7065 char_u *
7066 get_dict_string(d, key, save)
7067 dict_T *d;
7068 char_u *key;
7069 int save;
7071 dictitem_T *di;
7072 char_u *s;
7074 di = dict_find(d, key, -1);
7075 if (di == NULL)
7076 return NULL;
7077 s = get_tv_string(&di->di_tv);
7078 if (save && s != NULL)
7079 s = vim_strsave(s);
7080 return s;
7084 * Get a number item from a dictionary.
7085 * Returns 0 if the entry doesn't exist or out of memory.
7087 long
7088 get_dict_number(d, key)
7089 dict_T *d;
7090 char_u *key;
7092 dictitem_T *di;
7094 di = dict_find(d, key, -1);
7095 if (di == NULL)
7096 return 0;
7097 return get_tv_number(&di->di_tv);
7101 * Return an allocated string with the string representation of a Dictionary.
7102 * May return NULL.
7104 static char_u *
7105 dict2string(tv, copyID)
7106 typval_T *tv;
7107 int copyID;
7109 garray_T ga;
7110 int first = TRUE;
7111 char_u *tofree;
7112 char_u numbuf[NUMBUFLEN];
7113 hashitem_T *hi;
7114 char_u *s;
7115 dict_T *d;
7116 int todo;
7118 if ((d = tv->vval.v_dict) == NULL)
7119 return NULL;
7120 ga_init2(&ga, (int)sizeof(char), 80);
7121 ga_append(&ga, '{');
7123 todo = (int)d->dv_hashtab.ht_used;
7124 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
7126 if (!HASHITEM_EMPTY(hi))
7128 --todo;
7130 if (first)
7131 first = FALSE;
7132 else
7133 ga_concat(&ga, (char_u *)", ");
7135 tofree = string_quote(hi->hi_key, FALSE);
7136 if (tofree != NULL)
7138 ga_concat(&ga, tofree);
7139 vim_free(tofree);
7141 ga_concat(&ga, (char_u *)": ");
7142 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
7143 if (s != NULL)
7144 ga_concat(&ga, s);
7145 vim_free(tofree);
7146 if (s == NULL)
7147 break;
7150 if (todo > 0)
7152 vim_free(ga.ga_data);
7153 return NULL;
7156 ga_append(&ga, '}');
7157 ga_append(&ga, NUL);
7158 return (char_u *)ga.ga_data;
7162 * Allocate a variable for a Dictionary and fill it from "*arg".
7163 * Return OK or FAIL. Returns NOTDONE for {expr}.
7165 static int
7166 get_dict_tv(arg, rettv, evaluate)
7167 char_u **arg;
7168 typval_T *rettv;
7169 int evaluate;
7171 dict_T *d = NULL;
7172 typval_T tvkey;
7173 typval_T tv;
7174 char_u *key = NULL;
7175 dictitem_T *item;
7176 char_u *start = skipwhite(*arg + 1);
7177 char_u buf[NUMBUFLEN];
7180 * First check if it's not a curly-braces thing: {expr}.
7181 * Must do this without evaluating, otherwise a function may be called
7182 * twice. Unfortunately this means we need to call eval1() twice for the
7183 * first item.
7184 * But {} is an empty Dictionary.
7186 if (*start != '}')
7188 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
7189 return FAIL;
7190 if (*start == '}')
7191 return NOTDONE;
7194 if (evaluate)
7196 d = dict_alloc();
7197 if (d == NULL)
7198 return FAIL;
7200 tvkey.v_type = VAR_UNKNOWN;
7201 tv.v_type = VAR_UNKNOWN;
7203 *arg = skipwhite(*arg + 1);
7204 while (**arg != '}' && **arg != NUL)
7206 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
7207 goto failret;
7208 if (**arg != ':')
7210 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
7211 clear_tv(&tvkey);
7212 goto failret;
7214 if (evaluate)
7216 key = get_tv_string_buf_chk(&tvkey, buf);
7217 if (key == NULL || *key == NUL)
7219 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
7220 if (key != NULL)
7221 EMSG(_(e_emptykey));
7222 clear_tv(&tvkey);
7223 goto failret;
7227 *arg = skipwhite(*arg + 1);
7228 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
7230 if (evaluate)
7231 clear_tv(&tvkey);
7232 goto failret;
7234 if (evaluate)
7236 item = dict_find(d, key, -1);
7237 if (item != NULL)
7239 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
7240 clear_tv(&tvkey);
7241 clear_tv(&tv);
7242 goto failret;
7244 item = dictitem_alloc(key);
7245 clear_tv(&tvkey);
7246 if (item != NULL)
7248 item->di_tv = tv;
7249 item->di_tv.v_lock = 0;
7250 if (dict_add(d, item) == FAIL)
7251 dictitem_free(item);
7255 if (**arg == '}')
7256 break;
7257 if (**arg != ',')
7259 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
7260 goto failret;
7262 *arg = skipwhite(*arg + 1);
7265 if (**arg != '}')
7267 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
7268 failret:
7269 if (evaluate)
7270 dict_free(d, TRUE);
7271 return FAIL;
7274 *arg = skipwhite(*arg + 1);
7275 if (evaluate)
7277 rettv->v_type = VAR_DICT;
7278 rettv->vval.v_dict = d;
7279 ++d->dv_refcount;
7282 return OK;
7286 * Return a string with the string representation of a variable.
7287 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7288 * "numbuf" is used for a number.
7289 * Does not put quotes around strings, as ":echo" displays values.
7290 * When "copyID" is not NULL replace recursive lists and dicts with "...".
7291 * May return NULL.
7293 static char_u *
7294 echo_string(tv, tofree, numbuf, copyID)
7295 typval_T *tv;
7296 char_u **tofree;
7297 char_u *numbuf;
7298 int copyID;
7300 static int recurse = 0;
7301 char_u *r = NULL;
7303 if (recurse >= DICT_MAXNEST)
7305 EMSG(_("E724: variable nested too deep for displaying"));
7306 *tofree = NULL;
7307 return NULL;
7309 ++recurse;
7311 switch (tv->v_type)
7313 case VAR_FUNC:
7314 *tofree = NULL;
7315 r = tv->vval.v_string;
7316 break;
7318 case VAR_LIST:
7319 if (tv->vval.v_list == NULL)
7321 *tofree = NULL;
7322 r = NULL;
7324 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
7326 *tofree = NULL;
7327 r = (char_u *)"[...]";
7329 else
7331 tv->vval.v_list->lv_copyID = copyID;
7332 *tofree = list2string(tv, copyID);
7333 r = *tofree;
7335 break;
7337 case VAR_DICT:
7338 if (tv->vval.v_dict == NULL)
7340 *tofree = NULL;
7341 r = NULL;
7343 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
7345 *tofree = NULL;
7346 r = (char_u *)"{...}";
7348 else
7350 tv->vval.v_dict->dv_copyID = copyID;
7351 *tofree = dict2string(tv, copyID);
7352 r = *tofree;
7354 break;
7356 case VAR_STRING:
7357 case VAR_NUMBER:
7358 *tofree = NULL;
7359 r = get_tv_string_buf(tv, numbuf);
7360 break;
7362 #ifdef FEAT_FLOAT
7363 case VAR_FLOAT:
7364 *tofree = NULL;
7365 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
7366 r = numbuf;
7367 break;
7368 #endif
7370 default:
7371 EMSG2(_(e_intern2), "echo_string()");
7372 *tofree = NULL;
7375 --recurse;
7376 return r;
7380 * Return a string with the string representation of a variable.
7381 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7382 * "numbuf" is used for a number.
7383 * Puts quotes around strings, so that they can be parsed back by eval().
7384 * May return NULL.
7386 static char_u *
7387 tv2string(tv, tofree, numbuf, copyID)
7388 typval_T *tv;
7389 char_u **tofree;
7390 char_u *numbuf;
7391 int copyID;
7393 switch (tv->v_type)
7395 case VAR_FUNC:
7396 *tofree = string_quote(tv->vval.v_string, TRUE);
7397 return *tofree;
7398 case VAR_STRING:
7399 *tofree = string_quote(tv->vval.v_string, FALSE);
7400 return *tofree;
7401 #ifdef FEAT_FLOAT
7402 case VAR_FLOAT:
7403 *tofree = NULL;
7404 vim_snprintf((char *)numbuf, NUMBUFLEN - 1, "%g", tv->vval.v_float);
7405 return numbuf;
7406 #endif
7407 case VAR_NUMBER:
7408 case VAR_LIST:
7409 case VAR_DICT:
7410 break;
7411 default:
7412 EMSG2(_(e_intern2), "tv2string()");
7414 return echo_string(tv, tofree, numbuf, copyID);
7418 * Return string "str" in ' quotes, doubling ' characters.
7419 * If "str" is NULL an empty string is assumed.
7420 * If "function" is TRUE make it function('string').
7422 static char_u *
7423 string_quote(str, function)
7424 char_u *str;
7425 int function;
7427 unsigned len;
7428 char_u *p, *r, *s;
7430 len = (function ? 13 : 3);
7431 if (str != NULL)
7433 len += (unsigned)STRLEN(str);
7434 for (p = str; *p != NUL; mb_ptr_adv(p))
7435 if (*p == '\'')
7436 ++len;
7438 s = r = alloc(len);
7439 if (r != NULL)
7441 if (function)
7443 STRCPY(r, "function('");
7444 r += 10;
7446 else
7447 *r++ = '\'';
7448 if (str != NULL)
7449 for (p = str; *p != NUL; )
7451 if (*p == '\'')
7452 *r++ = '\'';
7453 MB_COPY_CHAR(p, r);
7455 *r++ = '\'';
7456 if (function)
7457 *r++ = ')';
7458 *r++ = NUL;
7460 return s;
7463 #ifdef FEAT_FLOAT
7465 * Convert the string "text" to a floating point number.
7466 * This uses strtod(). setlocale(LC_NUMERIC, "C") has been used to make sure
7467 * this always uses a decimal point.
7468 * Returns the length of the text that was consumed.
7470 static int
7471 string2float(text, value)
7472 char_u *text;
7473 float_T *value; /* result stored here */
7475 char *s = (char *)text;
7476 float_T f;
7478 f = strtod(s, &s);
7479 *value = f;
7480 return (int)((char_u *)s - text);
7482 #endif
7485 * Get the value of an environment variable.
7486 * "arg" is pointing to the '$'. It is advanced to after the name.
7487 * If the environment variable was not set, silently assume it is empty.
7488 * Always return OK.
7490 static int
7491 get_env_tv(arg, rettv, evaluate)
7492 char_u **arg;
7493 typval_T *rettv;
7494 int evaluate;
7496 char_u *string = NULL;
7497 int len;
7498 int cc;
7499 char_u *name;
7500 int mustfree = FALSE;
7502 ++*arg;
7503 name = *arg;
7504 len = get_env_len(arg);
7505 if (evaluate)
7507 if (len != 0)
7509 cc = name[len];
7510 name[len] = NUL;
7511 /* first try vim_getenv(), fast for normal environment vars */
7512 string = vim_getenv(name, &mustfree);
7513 if (string != NULL && *string != NUL)
7515 if (!mustfree)
7516 string = vim_strsave(string);
7518 else
7520 if (mustfree)
7521 vim_free(string);
7523 /* next try expanding things like $VIM and ${HOME} */
7524 string = expand_env_save(name - 1);
7525 if (string != NULL && *string == '$')
7527 vim_free(string);
7528 string = NULL;
7531 name[len] = cc;
7533 rettv->v_type = VAR_STRING;
7534 rettv->vval.v_string = string;
7537 return OK;
7541 * Array with names and number of arguments of all internal functions
7542 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7544 static struct fst
7546 char *f_name; /* function name */
7547 char f_min_argc; /* minimal number of arguments */
7548 char f_max_argc; /* maximal number of arguments */
7549 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7550 /* implementation of function */
7551 } functions[] =
7553 #ifdef FEAT_FLOAT
7554 {"abs", 1, 1, f_abs},
7555 {"acos", 1, 1, f_acos}, /* WJMc */
7556 #endif
7557 {"add", 2, 2, f_add},
7558 {"append", 2, 2, f_append},
7559 {"argc", 0, 0, f_argc},
7560 {"argidx", 0, 0, f_argidx},
7561 {"argv", 0, 1, f_argv},
7562 #ifdef FEAT_FLOAT
7563 {"asin", 1, 1, f_asin}, /* WJMc */
7564 {"atan", 1, 1, f_atan},
7565 {"atan2", 2, 2, f_atan2}, /* WJMc */
7566 #endif
7567 {"browse", 4, 4, f_browse},
7568 {"browsedir", 2, 2, f_browsedir},
7569 {"bufexists", 1, 1, f_bufexists},
7570 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7571 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7572 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7573 {"buflisted", 1, 1, f_buflisted},
7574 {"bufloaded", 1, 1, f_bufloaded},
7575 {"bufname", 1, 1, f_bufname},
7576 {"bufnr", 1, 2, f_bufnr},
7577 {"bufwinnr", 1, 1, f_bufwinnr},
7578 {"byte2line", 1, 1, f_byte2line},
7579 {"byteidx", 2, 2, f_byteidx},
7580 {"call", 2, 3, f_call},
7581 #ifdef FEAT_FLOAT
7582 {"ceil", 1, 1, f_ceil},
7583 #endif
7584 {"changenr", 0, 0, f_changenr},
7585 {"char2nr", 1, 1, f_char2nr},
7586 {"cindent", 1, 1, f_cindent},
7587 {"clearmatches", 0, 0, f_clearmatches},
7588 {"col", 1, 1, f_col},
7589 #if defined(FEAT_INS_EXPAND)
7590 {"complete", 2, 2, f_complete},
7591 {"complete_add", 1, 1, f_complete_add},
7592 {"complete_check", 0, 0, f_complete_check},
7593 #endif
7594 {"confirm", 1, 4, f_confirm},
7595 {"copy", 1, 1, f_copy},
7596 #ifdef FEAT_FLOAT
7597 {"cos", 1, 1, f_cos},
7598 {"cosh", 1, 1, f_cosh}, /* WJMc */
7599 #endif
7600 {"count", 2, 4, f_count},
7601 {"cscope_connection",0,3, f_cscope_connection},
7602 {"cursor", 1, 3, f_cursor},
7603 {"deepcopy", 1, 2, f_deepcopy},
7604 {"delete", 1, 1, f_delete},
7605 {"did_filetype", 0, 0, f_did_filetype},
7606 {"diff_filler", 1, 1, f_diff_filler},
7607 {"diff_hlID", 2, 2, f_diff_hlID},
7608 {"empty", 1, 1, f_empty},
7609 {"escape", 2, 2, f_escape},
7610 {"eval", 1, 1, f_eval},
7611 {"eventhandler", 0, 0, f_eventhandler},
7612 {"executable", 1, 1, f_executable},
7613 {"exists", 1, 1, f_exists},
7614 #ifdef FEAT_FLOAT
7615 {"exp", 1, 1, f_exp}, /* WJMc */
7616 #endif
7617 {"expand", 1, 2, f_expand},
7618 {"extend", 2, 3, f_extend},
7619 {"feedkeys", 1, 2, f_feedkeys},
7620 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7621 {"filereadable", 1, 1, f_filereadable},
7622 {"filewritable", 1, 1, f_filewritable},
7623 {"filter", 2, 2, f_filter},
7624 {"finddir", 1, 3, f_finddir},
7625 {"findfile", 1, 3, f_findfile},
7626 #ifdef FEAT_FLOAT
7627 {"float2nr", 1, 1, f_float2nr},
7628 {"floor", 1, 1, f_floor},
7629 {"fmod", 2, 2, f_fmod}, /* WJMc */
7630 #endif
7631 {"fnameescape", 1, 1, f_fnameescape},
7632 {"fnamemodify", 2, 2, f_fnamemodify},
7633 {"foldclosed", 1, 1, f_foldclosed},
7634 {"foldclosedend", 1, 1, f_foldclosedend},
7635 {"foldlevel", 1, 1, f_foldlevel},
7636 {"foldtext", 0, 0, f_foldtext},
7637 {"foldtextresult", 1, 1, f_foldtextresult},
7638 {"foreground", 0, 0, f_foreground},
7639 {"function", 1, 1, f_function},
7640 {"garbagecollect", 0, 1, f_garbagecollect},
7641 {"get", 2, 3, f_get},
7642 {"getbufline", 2, 3, f_getbufline},
7643 {"getbufvar", 2, 2, f_getbufvar},
7644 {"getchar", 0, 1, f_getchar},
7645 {"getcharmod", 0, 0, f_getcharmod},
7646 {"getcmdline", 0, 0, f_getcmdline},
7647 {"getcmdpos", 0, 0, f_getcmdpos},
7648 {"getcmdtype", 0, 0, f_getcmdtype},
7649 {"getcwd", 0, 0, f_getcwd},
7650 {"getfontname", 0, 1, f_getfontname},
7651 {"getfperm", 1, 1, f_getfperm},
7652 {"getfsize", 1, 1, f_getfsize},
7653 {"getftime", 1, 1, f_getftime},
7654 {"getftype", 1, 1, f_getftype},
7655 {"getline", 1, 2, f_getline},
7656 {"getloclist", 1, 1, f_getqflist},
7657 {"getmatches", 0, 0, f_getmatches},
7658 {"getpid", 0, 0, f_getpid},
7659 {"getpos", 1, 1, f_getpos},
7660 {"getqflist", 0, 0, f_getqflist},
7661 {"getreg", 0, 2, f_getreg},
7662 {"getregtype", 0, 1, f_getregtype},
7663 {"gettabwinvar", 3, 3, f_gettabwinvar},
7664 {"getwinposx", 0, 0, f_getwinposx},
7665 {"getwinposy", 0, 0, f_getwinposy},
7666 {"getwinvar", 2, 2, f_getwinvar},
7667 {"glob", 1, 2, f_glob},
7668 {"globpath", 2, 3, f_globpath},
7669 {"has", 1, 1, f_has},
7670 {"has_key", 2, 2, f_has_key},
7671 {"haslocaldir", 0, 0, f_haslocaldir},
7672 {"hasmapto", 1, 3, f_hasmapto},
7673 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7674 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7675 {"histadd", 2, 2, f_histadd},
7676 {"histdel", 1, 2, f_histdel},
7677 {"histget", 1, 2, f_histget},
7678 {"histnr", 1, 1, f_histnr},
7679 {"hlID", 1, 1, f_hlID},
7680 {"hlexists", 1, 1, f_hlexists},
7681 {"hostname", 0, 0, f_hostname},
7682 {"iconv", 3, 3, f_iconv},
7683 {"indent", 1, 1, f_indent},
7684 {"index", 2, 4, f_index},
7685 {"input", 1, 3, f_input},
7686 {"inputdialog", 1, 3, f_inputdialog},
7687 {"inputlist", 1, 1, f_inputlist},
7688 {"inputrestore", 0, 0, f_inputrestore},
7689 {"inputsave", 0, 0, f_inputsave},
7690 {"inputsecret", 1, 2, f_inputsecret},
7691 {"insert", 2, 3, f_insert},
7692 {"isdirectory", 1, 1, f_isdirectory},
7693 {"islocked", 1, 1, f_islocked},
7694 {"items", 1, 1, f_items},
7695 {"join", 1, 2, f_join},
7696 {"keys", 1, 1, f_keys},
7697 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7698 {"len", 1, 1, f_len},
7699 {"libcall", 3, 3, f_libcall},
7700 {"libcallnr", 3, 3, f_libcallnr},
7701 {"line", 1, 1, f_line},
7702 {"line2byte", 1, 1, f_line2byte},
7703 {"lispindent", 1, 1, f_lispindent},
7704 {"localtime", 0, 0, f_localtime},
7705 #ifdef FEAT_FLOAT
7706 {"log", 1, 1, f_log}, /* WJMc */
7707 {"log10", 1, 1, f_log10},
7708 #endif
7709 {"map", 2, 2, f_map},
7710 {"maparg", 1, 3, f_maparg},
7711 {"mapcheck", 1, 3, f_mapcheck},
7712 {"match", 2, 4, f_match},
7713 {"matchadd", 2, 4, f_matchadd},
7714 {"matcharg", 1, 1, f_matcharg},
7715 {"matchdelete", 1, 1, f_matchdelete},
7716 {"matchend", 2, 4, f_matchend},
7717 {"matchlist", 2, 4, f_matchlist},
7718 {"matchstr", 2, 4, f_matchstr},
7719 {"max", 1, 1, f_max},
7720 {"min", 1, 1, f_min},
7721 #ifdef vim_mkdir
7722 {"mkdir", 1, 3, f_mkdir},
7723 #endif
7724 {"mode", 0, 1, f_mode},
7725 #ifdef FEAT_MZSCHEME
7726 {"mzeval", 1, 1, f_mzeval},
7727 #endif
7728 {"nextnonblank", 1, 1, f_nextnonblank},
7729 {"nr2char", 1, 1, f_nr2char},
7730 {"pathshorten", 1, 1, f_pathshorten},
7731 #ifdef FEAT_FLOAT
7732 {"pow", 2, 2, f_pow},
7733 #endif
7734 {"prevnonblank", 1, 1, f_prevnonblank},
7735 {"printf", 2, 19, f_printf},
7736 {"pumvisible", 0, 0, f_pumvisible},
7737 {"range", 1, 3, f_range},
7738 {"readfile", 1, 3, f_readfile},
7739 {"reltime", 0, 2, f_reltime},
7740 {"reltimestr", 1, 1, f_reltimestr},
7741 {"remote_expr", 2, 3, f_remote_expr},
7742 {"remote_foreground", 1, 1, f_remote_foreground},
7743 {"remote_peek", 1, 2, f_remote_peek},
7744 {"remote_read", 1, 1, f_remote_read},
7745 {"remote_send", 2, 3, f_remote_send},
7746 {"remove", 2, 3, f_remove},
7747 {"rename", 2, 2, f_rename},
7748 {"repeat", 2, 2, f_repeat},
7749 {"resolve", 1, 1, f_resolve},
7750 {"reverse", 1, 1, f_reverse},
7751 #ifdef FEAT_FLOAT
7752 {"round", 1, 1, f_round},
7753 #endif
7754 {"search", 1, 4, f_search},
7755 {"searchdecl", 1, 3, f_searchdecl},
7756 {"searchpair", 3, 7, f_searchpair},
7757 {"searchpairpos", 3, 7, f_searchpairpos},
7758 {"searchpos", 1, 4, f_searchpos},
7759 {"server2client", 2, 2, f_server2client},
7760 {"serverlist", 0, 0, f_serverlist},
7761 {"setbufvar", 3, 3, f_setbufvar},
7762 {"setcmdpos", 1, 1, f_setcmdpos},
7763 {"setline", 2, 2, f_setline},
7764 {"setloclist", 2, 3, f_setloclist},
7765 {"setmatches", 1, 1, f_setmatches},
7766 {"setpos", 2, 2, f_setpos},
7767 {"setqflist", 1, 2, f_setqflist},
7768 {"setreg", 2, 3, f_setreg},
7769 {"settabwinvar", 4, 4, f_settabwinvar},
7770 {"setwinvar", 3, 3, f_setwinvar},
7771 {"shellescape", 1, 2, f_shellescape},
7772 {"simplify", 1, 1, f_simplify},
7773 #ifdef FEAT_FLOAT
7774 {"sin", 1, 1, f_sin},
7775 {"sinh", 1, 1, f_sinh}, /* WJMc */
7776 #endif
7777 {"sort", 1, 2, f_sort},
7778 {"soundfold", 1, 1, f_soundfold},
7779 {"spellbadword", 0, 1, f_spellbadword},
7780 {"spellsuggest", 1, 3, f_spellsuggest},
7781 {"split", 1, 3, f_split},
7782 #ifdef FEAT_FLOAT
7783 {"sqrt", 1, 1, f_sqrt},
7784 {"str2float", 1, 1, f_str2float},
7785 #endif
7786 {"str2nr", 1, 2, f_str2nr},
7787 #ifdef HAVE_STRFTIME
7788 {"strftime", 1, 2, f_strftime},
7789 #endif
7790 {"stridx", 2, 3, f_stridx},
7791 {"string", 1, 1, f_string},
7792 {"strlen", 1, 1, f_strlen},
7793 {"strpart", 2, 3, f_strpart},
7794 {"strridx", 2, 3, f_strridx},
7795 {"strtrans", 1, 1, f_strtrans},
7796 {"submatch", 1, 1, f_submatch},
7797 {"substitute", 4, 4, f_substitute},
7798 {"synID", 3, 3, f_synID},
7799 {"synIDattr", 2, 3, f_synIDattr},
7800 {"synIDtrans", 1, 1, f_synIDtrans},
7801 {"synstack", 2, 2, f_synstack},
7802 {"system", 1, 2, f_system},
7803 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7804 {"tabpagenr", 0, 1, f_tabpagenr},
7805 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7806 {"tagfiles", 0, 0, f_tagfiles},
7807 {"taglist", 1, 1, f_taglist},
7808 {"tan", 1, 1, f_tan}, /* WJMc */
7809 {"tanh", 1, 1, f_tanh}, /* WJMc */
7810 {"tempname", 0, 0, f_tempname},
7811 {"test", 1, 1, f_test},
7812 {"tolower", 1, 1, f_tolower},
7813 {"toupper", 1, 1, f_toupper},
7814 {"tr", 3, 3, f_tr},
7815 #ifdef FEAT_FLOAT
7816 {"trunc", 1, 1, f_trunc},
7817 #endif
7818 {"type", 1, 1, f_type},
7819 {"values", 1, 1, f_values},
7820 {"virtcol", 1, 1, f_virtcol},
7821 {"visualmode", 0, 1, f_visualmode},
7822 {"winbufnr", 1, 1, f_winbufnr},
7823 {"wincol", 0, 0, f_wincol},
7824 {"winheight", 1, 1, f_winheight},
7825 {"winline", 0, 0, f_winline},
7826 {"winnr", 0, 1, f_winnr},
7827 {"winrestcmd", 0, 0, f_winrestcmd},
7828 {"winrestview", 1, 1, f_winrestview},
7829 {"winsaveview", 0, 0, f_winsaveview},
7830 {"winwidth", 1, 1, f_winwidth},
7831 {"writefile", 2, 3, f_writefile},
7834 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7837 * Function given to ExpandGeneric() to obtain the list of internal
7838 * or user defined function names.
7840 char_u *
7841 get_function_name(xp, idx)
7842 expand_T *xp;
7843 int idx;
7845 static int intidx = -1;
7846 char_u *name;
7848 if (idx == 0)
7849 intidx = -1;
7850 if (intidx < 0)
7852 name = get_user_func_name(xp, idx);
7853 if (name != NULL)
7854 return name;
7856 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7858 STRCPY(IObuff, functions[intidx].f_name);
7859 STRCAT(IObuff, "(");
7860 if (functions[intidx].f_max_argc == 0)
7861 STRCAT(IObuff, ")");
7862 return IObuff;
7865 return NULL;
7869 * Function given to ExpandGeneric() to obtain the list of internal or
7870 * user defined variable or function names.
7872 char_u *
7873 get_expr_name(xp, idx)
7874 expand_T *xp;
7875 int idx;
7877 static int intidx = -1;
7878 char_u *name;
7880 if (idx == 0)
7881 intidx = -1;
7882 if (intidx < 0)
7884 name = get_function_name(xp, idx);
7885 if (name != NULL)
7886 return name;
7888 return get_user_var_name(xp, ++intidx);
7891 #endif /* FEAT_CMDL_COMPL */
7894 * Find internal function in table above.
7895 * Return index, or -1 if not found
7897 static int
7898 find_internal_func(name)
7899 char_u *name; /* name of the function */
7901 int first = 0;
7902 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7903 int cmp;
7904 int x;
7907 * Find the function name in the table. Binary search.
7909 while (first <= last)
7911 x = first + ((unsigned)(last - first) >> 1);
7912 cmp = STRCMP(name, functions[x].f_name);
7913 if (cmp < 0)
7914 last = x - 1;
7915 else if (cmp > 0)
7916 first = x + 1;
7917 else
7918 return x;
7920 return -1;
7924 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7925 * name it contains, otherwise return "name".
7927 static char_u *
7928 deref_func_name(name, lenp)
7929 char_u *name;
7930 int *lenp;
7932 dictitem_T *v;
7933 int cc;
7935 cc = name[*lenp];
7936 name[*lenp] = NUL;
7937 v = find_var(name, NULL);
7938 name[*lenp] = cc;
7939 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7941 if (v->di_tv.vval.v_string == NULL)
7943 *lenp = 0;
7944 return (char_u *)""; /* just in case */
7946 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7947 return v->di_tv.vval.v_string;
7950 return name;
7954 * Allocate a variable for the result of a function.
7955 * Return OK or FAIL.
7957 static int
7958 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7959 evaluate, selfdict)
7960 char_u *name; /* name of the function */
7961 int len; /* length of "name" */
7962 typval_T *rettv;
7963 char_u **arg; /* argument, pointing to the '(' */
7964 linenr_T firstline; /* first line of range */
7965 linenr_T lastline; /* last line of range */
7966 int *doesrange; /* return: function handled range */
7967 int evaluate;
7968 dict_T *selfdict; /* Dictionary for "self" */
7970 char_u *argp;
7971 int ret = OK;
7972 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7973 int argcount = 0; /* number of arguments found */
7976 * Get the arguments.
7978 argp = *arg;
7979 while (argcount < MAX_FUNC_ARGS)
7981 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7982 if (*argp == ')' || *argp == ',' || *argp == NUL)
7983 break;
7984 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7986 ret = FAIL;
7987 break;
7989 ++argcount;
7990 if (*argp != ',')
7991 break;
7993 if (*argp == ')')
7994 ++argp;
7995 else
7996 ret = FAIL;
7998 if (ret == OK)
7999 ret = call_func(name, len, rettv, argcount, argvars,
8000 firstline, lastline, doesrange, evaluate, selfdict);
8001 else if (!aborting())
8003 if (argcount == MAX_FUNC_ARGS)
8004 emsg_funcname(N_("E740: Too many arguments for function %s"), name);
8005 else
8006 emsg_funcname(N_("E116: Invalid arguments for function %s"), name);
8009 while (--argcount >= 0)
8010 clear_tv(&argvars[argcount]);
8012 *arg = skipwhite(argp);
8013 return ret;
8018 * Call a function with its resolved parameters
8019 * Return OK when the function can't be called, FAIL otherwise.
8020 * Also returns OK when an error was encountered while executing the function.
8022 static int
8023 call_func(name, len, rettv, argcount, argvars, firstline, lastline,
8024 doesrange, evaluate, selfdict)
8025 char_u *name; /* name of the function */
8026 int len; /* length of "name" */
8027 typval_T *rettv; /* return value goes here */
8028 int argcount; /* number of "argvars" */
8029 typval_T *argvars; /* vars for arguments, must have "argcount"
8030 PLUS ONE elements! */
8031 linenr_T firstline; /* first line of range */
8032 linenr_T lastline; /* last line of range */
8033 int *doesrange; /* return: function handled range */
8034 int evaluate;
8035 dict_T *selfdict; /* Dictionary for "self" */
8037 int ret = FAIL;
8038 #define ERROR_UNKNOWN 0
8039 #define ERROR_TOOMANY 1
8040 #define ERROR_TOOFEW 2
8041 #define ERROR_SCRIPT 3
8042 #define ERROR_DICT 4
8043 #define ERROR_NONE 5
8044 #define ERROR_OTHER 6
8045 int error = ERROR_NONE;
8046 int i;
8047 int llen;
8048 ufunc_T *fp;
8049 int cc;
8050 #define FLEN_FIXED 40
8051 char_u fname_buf[FLEN_FIXED + 1];
8052 char_u *fname;
8055 * In a script change <SID>name() and s:name() to K_SNR 123_name().
8056 * Change <SNR>123_name() to K_SNR 123_name().
8057 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
8059 cc = name[len];
8060 name[len] = NUL;
8061 llen = eval_fname_script(name);
8062 if (llen > 0)
8064 fname_buf[0] = K_SPECIAL;
8065 fname_buf[1] = KS_EXTRA;
8066 fname_buf[2] = (int)KE_SNR;
8067 i = 3;
8068 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
8070 if (current_SID <= 0)
8071 error = ERROR_SCRIPT;
8072 else
8074 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
8075 i = (int)STRLEN(fname_buf);
8078 if (i + STRLEN(name + llen) < FLEN_FIXED)
8080 STRCPY(fname_buf + i, name + llen);
8081 fname = fname_buf;
8083 else
8085 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
8086 if (fname == NULL)
8087 error = ERROR_OTHER;
8088 else
8090 mch_memmove(fname, fname_buf, (size_t)i);
8091 STRCPY(fname + i, name + llen);
8095 else
8096 fname = name;
8098 *doesrange = FALSE;
8101 /* execute the function if no errors detected and executing */
8102 if (evaluate && error == ERROR_NONE)
8104 rettv->v_type = VAR_NUMBER; /* default rettv is number zero */
8105 rettv->vval.v_number = 0;
8106 error = ERROR_UNKNOWN;
8108 if (!builtin_function(fname))
8111 * User defined function.
8113 fp = find_func(fname);
8115 #ifdef FEAT_AUTOCMD
8116 /* Trigger FuncUndefined event, may load the function. */
8117 if (fp == NULL
8118 && apply_autocmds(EVENT_FUNCUNDEFINED,
8119 fname, fname, TRUE, NULL)
8120 && !aborting())
8122 /* executed an autocommand, search for the function again */
8123 fp = find_func(fname);
8125 #endif
8126 /* Try loading a package. */
8127 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
8129 /* loaded a package, search for the function again */
8130 fp = find_func(fname);
8133 if (fp != NULL)
8135 if (fp->uf_flags & FC_RANGE)
8136 *doesrange = TRUE;
8137 if (argcount < fp->uf_args.ga_len)
8138 error = ERROR_TOOFEW;
8139 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
8140 error = ERROR_TOOMANY;
8141 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
8142 error = ERROR_DICT;
8143 else
8146 * Call the user function.
8147 * Save and restore search patterns, script variables and
8148 * redo buffer.
8150 save_search_patterns();
8151 saveRedobuff();
8152 ++fp->uf_calls;
8153 call_user_func(fp, argcount, argvars, rettv,
8154 firstline, lastline,
8155 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
8156 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
8157 && fp->uf_refcount <= 0)
8158 /* Function was unreferenced while being used, free it
8159 * now. */
8160 func_free(fp);
8161 restoreRedobuff();
8162 restore_search_patterns();
8163 error = ERROR_NONE;
8167 else
8170 * Find the function name in the table, call its implementation.
8172 i = find_internal_func(fname);
8173 if (i >= 0)
8175 if (argcount < functions[i].f_min_argc)
8176 error = ERROR_TOOFEW;
8177 else if (argcount > functions[i].f_max_argc)
8178 error = ERROR_TOOMANY;
8179 else
8181 argvars[argcount].v_type = VAR_UNKNOWN;
8182 functions[i].f_func(argvars, rettv);
8183 error = ERROR_NONE;
8188 * The function call (or "FuncUndefined" autocommand sequence) might
8189 * have been aborted by an error, an interrupt, or an explicitly thrown
8190 * exception that has not been caught so far. This situation can be
8191 * tested for by calling aborting(). For an error in an internal
8192 * function or for the "E132" error in call_user_func(), however, the
8193 * throw point at which the "force_abort" flag (temporarily reset by
8194 * emsg()) is normally updated has not been reached yet. We need to
8195 * update that flag first to make aborting() reliable.
8197 update_force_abort();
8199 if (error == ERROR_NONE)
8200 ret = OK;
8203 * Report an error unless the argument evaluation or function call has been
8204 * cancelled due to an aborting error, an interrupt, or an exception.
8206 if (!aborting())
8208 switch (error)
8210 case ERROR_UNKNOWN:
8211 emsg_funcname(N_("E117: Unknown function: %s"), name);
8212 break;
8213 case ERROR_TOOMANY:
8214 emsg_funcname(e_toomanyarg, name);
8215 break;
8216 case ERROR_TOOFEW:
8217 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
8218 name);
8219 break;
8220 case ERROR_SCRIPT:
8221 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
8222 name);
8223 break;
8224 case ERROR_DICT:
8225 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
8226 name);
8227 break;
8231 name[len] = cc;
8232 if (fname != name && fname != fname_buf)
8233 vim_free(fname);
8235 return ret;
8239 * Give an error message with a function name. Handle <SNR> things.
8240 * "ermsg" is to be passed without translation, use N_() instead of _().
8242 static void
8243 emsg_funcname(ermsg, name)
8244 char *ermsg;
8245 char_u *name;
8247 char_u *p;
8249 if (*name == K_SPECIAL)
8250 p = concat_str((char_u *)"<SNR>", name + 3);
8251 else
8252 p = name;
8253 EMSG2(_(ermsg), p);
8254 if (p != name)
8255 vim_free(p);
8259 * Return TRUE for a non-zero Number and a non-empty String.
8261 static int
8262 non_zero_arg(argvars)
8263 typval_T *argvars;
8265 return ((argvars[0].v_type == VAR_NUMBER
8266 && argvars[0].vval.v_number != 0)
8267 || (argvars[0].v_type == VAR_STRING
8268 && argvars[0].vval.v_string != NULL
8269 && *argvars[0].vval.v_string != NUL));
8272 /*********************************************
8273 * Implementation of the built-in functions
8276 #ifdef FEAT_FLOAT
8278 * "abs(expr)" function
8280 static void
8281 f_abs(argvars, rettv)
8282 typval_T *argvars;
8283 typval_T *rettv;
8285 if (argvars[0].v_type == VAR_FLOAT)
8287 rettv->v_type = VAR_FLOAT;
8288 rettv->vval.v_float = fabs(argvars[0].vval.v_float);
8290 else
8292 varnumber_T n;
8293 int error = FALSE;
8295 n = get_tv_number_chk(&argvars[0], &error);
8296 if (error)
8297 rettv->vval.v_number = -1;
8298 else if (n > 0)
8299 rettv->vval.v_number = n;
8300 else
8301 rettv->vval.v_number = -n;
8304 #endif
8307 * "add(list, item)" function
8309 static void
8310 f_add(argvars, rettv)
8311 typval_T *argvars;
8312 typval_T *rettv;
8314 list_T *l;
8316 rettv->vval.v_number = 1; /* Default: Failed */
8317 if (argvars[0].v_type == VAR_LIST)
8319 if ((l = argvars[0].vval.v_list) != NULL
8320 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
8321 && list_append_tv(l, &argvars[1]) == OK)
8322 copy_tv(&argvars[0], rettv);
8324 else
8325 EMSG(_(e_listreq));
8329 * "append(lnum, string/list)" function
8331 static void
8332 f_append(argvars, rettv)
8333 typval_T *argvars;
8334 typval_T *rettv;
8336 long lnum;
8337 char_u *line;
8338 list_T *l = NULL;
8339 listitem_T *li = NULL;
8340 typval_T *tv;
8341 long added = 0;
8343 lnum = get_tv_lnum(argvars);
8344 if (lnum >= 0
8345 && lnum <= curbuf->b_ml.ml_line_count
8346 && u_save(lnum, lnum + 1) == OK)
8348 if (argvars[1].v_type == VAR_LIST)
8350 l = argvars[1].vval.v_list;
8351 if (l == NULL)
8352 return;
8353 li = l->lv_first;
8355 for (;;)
8357 if (l == NULL)
8358 tv = &argvars[1]; /* append a string */
8359 else if (li == NULL)
8360 break; /* end of list */
8361 else
8362 tv = &li->li_tv; /* append item from list */
8363 line = get_tv_string_chk(tv);
8364 if (line == NULL) /* type error */
8366 rettv->vval.v_number = 1; /* Failed */
8367 break;
8369 ml_append(lnum + added, line, (colnr_T)0, FALSE);
8370 ++added;
8371 if (l == NULL)
8372 break;
8373 li = li->li_next;
8376 appended_lines_mark(lnum, added);
8377 if (curwin->w_cursor.lnum > lnum)
8378 curwin->w_cursor.lnum += added;
8380 else
8381 rettv->vval.v_number = 1; /* Failed */
8385 * "argc()" function
8387 static void
8388 f_argc(argvars, rettv)
8389 typval_T *argvars UNUSED;
8390 typval_T *rettv;
8392 rettv->vval.v_number = ARGCOUNT;
8396 * "argidx()" function
8398 static void
8399 f_argidx(argvars, rettv)
8400 typval_T *argvars UNUSED;
8401 typval_T *rettv;
8403 rettv->vval.v_number = curwin->w_arg_idx;
8407 * "argv(nr)" function
8409 static void
8410 f_argv(argvars, rettv)
8411 typval_T *argvars;
8412 typval_T *rettv;
8414 int idx;
8416 if (argvars[0].v_type != VAR_UNKNOWN)
8418 idx = get_tv_number_chk(&argvars[0], NULL);
8419 if (idx >= 0 && idx < ARGCOUNT)
8420 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
8421 else
8422 rettv->vval.v_string = NULL;
8423 rettv->v_type = VAR_STRING;
8425 else if (rettv_list_alloc(rettv) == OK)
8426 for (idx = 0; idx < ARGCOUNT; ++idx)
8427 list_append_string(rettv->vval.v_list,
8428 alist_name(&ARGLIST[idx]), -1);
8431 #ifdef FEAT_FLOAT
8432 static int get_float_arg __ARGS((typval_T *argvars, float_T *f));
8435 * Get the float value of "argvars[0]" into "f".
8436 * Returns FAIL when the argument is not a Number or Float.
8438 static int
8439 get_float_arg(argvars, f)
8440 typval_T *argvars;
8441 float_T *f;
8443 if (argvars[0].v_type == VAR_FLOAT)
8445 *f = argvars[0].vval.v_float;
8446 return OK;
8448 if (argvars[0].v_type == VAR_NUMBER)
8450 *f = (float_T)argvars[0].vval.v_number;
8451 return OK;
8453 EMSG(_("E808: Number or Float required"));
8454 return FAIL;
8457 /* The 10 added FP functions are defined immediately before atan() - WJMc */
8460 * "acos()" function
8462 static void
8463 f_acos(argvars, rettv)
8464 typval_T *argvars;
8465 typval_T *rettv;
8467 float_T f;
8469 rettv->v_type = VAR_FLOAT;
8470 if (get_float_arg(argvars, &f) == OK)
8471 rettv->vval.v_float = acos(f);
8472 else
8473 rettv->vval.v_float = 0.0;
8477 * "asin()" function
8479 static void
8480 f_asin(argvars, rettv)
8481 typval_T *argvars;
8482 typval_T *rettv;
8484 float_T f;
8486 rettv->v_type = VAR_FLOAT;
8487 if (get_float_arg(argvars, &f) == OK)
8488 rettv->vval.v_float = asin(f);
8489 else
8490 rettv->vval.v_float = 0.0;
8494 * "atan2()" function
8496 static void
8497 f_atan2(argvars, rettv)
8498 typval_T *argvars;
8499 typval_T *rettv;
8501 float_T fx, fy;
8503 rettv->v_type = VAR_FLOAT;
8504 if (get_float_arg(argvars, &fx) == OK
8505 && get_float_arg(&argvars[1], &fy) == OK)
8506 rettv->vval.v_float = atan2(fx, fy);
8507 else
8508 rettv->vval.v_float = 0.0;
8512 * "cosh()" function
8514 static void
8515 f_cosh(argvars, rettv)
8516 typval_T *argvars;
8517 typval_T *rettv;
8519 float_T f;
8521 rettv->v_type = VAR_FLOAT;
8522 if (get_float_arg(argvars, &f) == OK)
8523 rettv->vval.v_float = cosh(f);
8524 else
8525 rettv->vval.v_float = 0.0;
8529 * "exp()" function
8531 static void
8532 f_exp(argvars, rettv)
8533 typval_T *argvars;
8534 typval_T *rettv;
8536 float_T f;
8538 rettv->v_type = VAR_FLOAT;
8539 if (get_float_arg(argvars, &f) == OK)
8540 rettv->vval.v_float = exp(f);
8541 else
8542 rettv->vval.v_float = 0.0;
8546 * "fmod()" function
8548 static void
8549 f_fmod(argvars, rettv)
8550 typval_T *argvars;
8551 typval_T *rettv;
8553 float_T fx, fy;
8555 rettv->v_type = VAR_FLOAT;
8556 if (get_float_arg(argvars, &fx) == OK
8557 && get_float_arg(&argvars[1], &fy) == OK)
8558 rettv->vval.v_float = fmod(fx, fy);
8559 else
8560 rettv->vval.v_float = 0.0;
8564 * "log()" function
8566 static void
8567 f_log(argvars, rettv)
8568 typval_T *argvars;
8569 typval_T *rettv;
8571 float_T f;
8573 rettv->v_type = VAR_FLOAT;
8574 if (get_float_arg(argvars, &f) == OK)
8575 rettv->vval.v_float = log(f);
8576 else
8577 rettv->vval.v_float = 0.0;
8581 * "sinh()" function
8583 static void
8584 f_sinh(argvars, rettv)
8585 typval_T *argvars;
8586 typval_T *rettv;
8588 float_T f;
8590 rettv->v_type = VAR_FLOAT;
8591 if (get_float_arg(argvars, &f) == OK)
8592 rettv->vval.v_float = sinh(f);
8593 else
8594 rettv->vval.v_float = 0.0;
8598 * "tan()" function
8600 static void
8601 f_tan(argvars, rettv)
8602 typval_T *argvars;
8603 typval_T *rettv;
8605 float_T f;
8607 rettv->v_type = VAR_FLOAT;
8608 if (get_float_arg(argvars, &f) == OK)
8609 rettv->vval.v_float = tan(f);
8610 else
8611 rettv->vval.v_float = 0.0;
8615 * "tanh()" function
8617 static void
8618 f_tanh(argvars, rettv)
8619 typval_T *argvars;
8620 typval_T *rettv;
8622 float_T f;
8624 rettv->v_type = VAR_FLOAT;
8625 if (get_float_arg(argvars, &f) == OK)
8626 rettv->vval.v_float = tanh(f);
8627 else
8628 rettv->vval.v_float = 0.0;
8631 /* End of the 10 added FP functions - WJMc */
8634 * "atan()" function
8636 static void
8637 f_atan(argvars, rettv)
8638 typval_T *argvars;
8639 typval_T *rettv;
8641 float_T f;
8643 rettv->v_type = VAR_FLOAT;
8644 if (get_float_arg(argvars, &f) == OK)
8645 rettv->vval.v_float = atan(f);
8646 else
8647 rettv->vval.v_float = 0.0;
8649 #endif
8652 * "browse(save, title, initdir, default)" function
8654 static void
8655 f_browse(argvars, rettv)
8656 typval_T *argvars UNUSED;
8657 typval_T *rettv;
8659 #ifdef FEAT_BROWSE
8660 int save;
8661 char_u *title;
8662 char_u *initdir;
8663 char_u *defname;
8664 char_u buf[NUMBUFLEN];
8665 char_u buf2[NUMBUFLEN];
8666 int error = FALSE;
8668 save = get_tv_number_chk(&argvars[0], &error);
8669 title = get_tv_string_chk(&argvars[1]);
8670 initdir = get_tv_string_buf_chk(&argvars[2], buf);
8671 defname = get_tv_string_buf_chk(&argvars[3], buf2);
8673 if (error || title == NULL || initdir == NULL || defname == NULL)
8674 rettv->vval.v_string = NULL;
8675 else
8676 rettv->vval.v_string =
8677 do_browse(save ? BROWSE_SAVE : 0,
8678 title, defname, NULL, initdir, NULL, curbuf);
8679 #else
8680 rettv->vval.v_string = NULL;
8681 #endif
8682 rettv->v_type = VAR_STRING;
8686 * "browsedir(title, initdir)" function
8688 static void
8689 f_browsedir(argvars, rettv)
8690 typval_T *argvars UNUSED;
8691 typval_T *rettv;
8693 #ifdef FEAT_BROWSE
8694 char_u *title;
8695 char_u *initdir;
8696 char_u buf[NUMBUFLEN];
8698 title = get_tv_string_chk(&argvars[0]);
8699 initdir = get_tv_string_buf_chk(&argvars[1], buf);
8701 if (title == NULL || initdir == NULL)
8702 rettv->vval.v_string = NULL;
8703 else
8704 rettv->vval.v_string = do_browse(BROWSE_DIR,
8705 title, NULL, NULL, initdir, NULL, curbuf);
8706 #else
8707 rettv->vval.v_string = NULL;
8708 #endif
8709 rettv->v_type = VAR_STRING;
8712 static buf_T *find_buffer __ARGS((typval_T *avar));
8715 * Find a buffer by number or exact name.
8717 static buf_T *
8718 find_buffer(avar)
8719 typval_T *avar;
8721 buf_T *buf = NULL;
8723 if (avar->v_type == VAR_NUMBER)
8724 buf = buflist_findnr((int)avar->vval.v_number);
8725 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
8727 buf = buflist_findname_exp(avar->vval.v_string);
8728 if (buf == NULL)
8730 /* No full path name match, try a match with a URL or a "nofile"
8731 * buffer, these don't use the full path. */
8732 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8733 if (buf->b_fname != NULL
8734 && (path_with_url(buf->b_fname)
8735 #ifdef FEAT_QUICKFIX
8736 || bt_nofile(buf)
8737 #endif
8739 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
8740 break;
8743 return buf;
8747 * "bufexists(expr)" function
8749 static void
8750 f_bufexists(argvars, rettv)
8751 typval_T *argvars;
8752 typval_T *rettv;
8754 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
8758 * "buflisted(expr)" function
8760 static void
8761 f_buflisted(argvars, rettv)
8762 typval_T *argvars;
8763 typval_T *rettv;
8765 buf_T *buf;
8767 buf = find_buffer(&argvars[0]);
8768 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
8772 * "bufloaded(expr)" function
8774 static void
8775 f_bufloaded(argvars, rettv)
8776 typval_T *argvars;
8777 typval_T *rettv;
8779 buf_T *buf;
8781 buf = find_buffer(&argvars[0]);
8782 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
8785 static buf_T *get_buf_tv __ARGS((typval_T *tv));
8788 * Get buffer by number or pattern.
8790 static buf_T *
8791 get_buf_tv(tv)
8792 typval_T *tv;
8794 char_u *name = tv->vval.v_string;
8795 int save_magic;
8796 char_u *save_cpo;
8797 buf_T *buf;
8799 if (tv->v_type == VAR_NUMBER)
8800 return buflist_findnr((int)tv->vval.v_number);
8801 if (tv->v_type != VAR_STRING)
8802 return NULL;
8803 if (name == NULL || *name == NUL)
8804 return curbuf;
8805 if (name[0] == '$' && name[1] == NUL)
8806 return lastbuf;
8808 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
8809 save_magic = p_magic;
8810 p_magic = TRUE;
8811 save_cpo = p_cpo;
8812 p_cpo = (char_u *)"";
8814 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8815 TRUE, FALSE));
8817 p_magic = save_magic;
8818 p_cpo = save_cpo;
8820 /* If not found, try expanding the name, like done for bufexists(). */
8821 if (buf == NULL)
8822 buf = find_buffer(tv);
8824 return buf;
8828 * "bufname(expr)" function
8830 static void
8831 f_bufname(argvars, rettv)
8832 typval_T *argvars;
8833 typval_T *rettv;
8835 buf_T *buf;
8837 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8838 ++emsg_off;
8839 buf = get_buf_tv(&argvars[0]);
8840 rettv->v_type = VAR_STRING;
8841 if (buf != NULL && buf->b_fname != NULL)
8842 rettv->vval.v_string = vim_strsave(buf->b_fname);
8843 else
8844 rettv->vval.v_string = NULL;
8845 --emsg_off;
8849 * "bufnr(expr)" function
8851 static void
8852 f_bufnr(argvars, rettv)
8853 typval_T *argvars;
8854 typval_T *rettv;
8856 buf_T *buf;
8857 int error = FALSE;
8858 char_u *name;
8860 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8861 ++emsg_off;
8862 buf = get_buf_tv(&argvars[0]);
8863 --emsg_off;
8865 /* If the buffer isn't found and the second argument is not zero create a
8866 * new buffer. */
8867 if (buf == NULL
8868 && argvars[1].v_type != VAR_UNKNOWN
8869 && get_tv_number_chk(&argvars[1], &error) != 0
8870 && !error
8871 && (name = get_tv_string_chk(&argvars[0])) != NULL
8872 && !error)
8873 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8875 if (buf != NULL)
8876 rettv->vval.v_number = buf->b_fnum;
8877 else
8878 rettv->vval.v_number = -1;
8882 * "bufwinnr(nr)" function
8884 static void
8885 f_bufwinnr(argvars, rettv)
8886 typval_T *argvars;
8887 typval_T *rettv;
8889 #ifdef FEAT_WINDOWS
8890 win_T *wp;
8891 int winnr = 0;
8892 #endif
8893 buf_T *buf;
8895 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8896 ++emsg_off;
8897 buf = get_buf_tv(&argvars[0]);
8898 #ifdef FEAT_WINDOWS
8899 for (wp = firstwin; wp; wp = wp->w_next)
8901 ++winnr;
8902 if (wp->w_buffer == buf)
8903 break;
8905 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8906 #else
8907 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8908 #endif
8909 --emsg_off;
8913 * "byte2line(byte)" function
8915 static void
8916 f_byte2line(argvars, rettv)
8917 typval_T *argvars UNUSED;
8918 typval_T *rettv;
8920 #ifndef FEAT_BYTEOFF
8921 rettv->vval.v_number = -1;
8922 #else
8923 long boff = 0;
8925 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8926 if (boff < 0)
8927 rettv->vval.v_number = -1;
8928 else
8929 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8930 (linenr_T)0, &boff);
8931 #endif
8935 * "byteidx()" function
8937 static void
8938 f_byteidx(argvars, rettv)
8939 typval_T *argvars;
8940 typval_T *rettv;
8942 #ifdef FEAT_MBYTE
8943 char_u *t;
8944 #endif
8945 char_u *str;
8946 long idx;
8948 str = get_tv_string_chk(&argvars[0]);
8949 idx = get_tv_number_chk(&argvars[1], NULL);
8950 rettv->vval.v_number = -1;
8951 if (str == NULL || idx < 0)
8952 return;
8954 #ifdef FEAT_MBYTE
8955 t = str;
8956 for ( ; idx > 0; idx--)
8958 if (*t == NUL) /* EOL reached */
8959 return;
8960 t += (*mb_ptr2len)(t);
8962 rettv->vval.v_number = (varnumber_T)(t - str);
8963 #else
8964 if ((size_t)idx <= STRLEN(str))
8965 rettv->vval.v_number = idx;
8966 #endif
8970 * "call(func, arglist)" function
8972 static void
8973 f_call(argvars, rettv)
8974 typval_T *argvars;
8975 typval_T *rettv;
8977 char_u *func;
8978 typval_T argv[MAX_FUNC_ARGS + 1];
8979 int argc = 0;
8980 listitem_T *item;
8981 int dummy;
8982 dict_T *selfdict = NULL;
8984 if (argvars[1].v_type != VAR_LIST)
8986 EMSG(_(e_listreq));
8987 return;
8989 if (argvars[1].vval.v_list == NULL)
8990 return;
8992 if (argvars[0].v_type == VAR_FUNC)
8993 func = argvars[0].vval.v_string;
8994 else
8995 func = get_tv_string(&argvars[0]);
8996 if (*func == NUL)
8997 return; /* type error or empty name */
8999 if (argvars[2].v_type != VAR_UNKNOWN)
9001 if (argvars[2].v_type != VAR_DICT)
9003 EMSG(_(e_dictreq));
9004 return;
9006 selfdict = argvars[2].vval.v_dict;
9009 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
9010 item = item->li_next)
9012 if (argc == MAX_FUNC_ARGS)
9014 EMSG(_("E699: Too many arguments"));
9015 break;
9017 /* Make a copy of each argument. This is needed to be able to set
9018 * v_lock to VAR_FIXED in the copy without changing the original list.
9020 copy_tv(&item->li_tv, &argv[argc++]);
9023 if (item == NULL)
9024 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
9025 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
9026 &dummy, TRUE, selfdict);
9028 /* Free the arguments. */
9029 while (argc > 0)
9030 clear_tv(&argv[--argc]);
9033 #ifdef FEAT_FLOAT
9035 * "ceil({float})" function
9037 static void
9038 f_ceil(argvars, rettv)
9039 typval_T *argvars;
9040 typval_T *rettv;
9042 float_T f;
9044 rettv->v_type = VAR_FLOAT;
9045 if (get_float_arg(argvars, &f) == OK)
9046 rettv->vval.v_float = ceil(f);
9047 else
9048 rettv->vval.v_float = 0.0;
9050 #endif
9053 * "changenr()" function
9055 static void
9056 f_changenr(argvars, rettv)
9057 typval_T *argvars UNUSED;
9058 typval_T *rettv;
9060 rettv->vval.v_number = curbuf->b_u_seq_cur;
9064 * "char2nr(string)" function
9066 static void
9067 f_char2nr(argvars, rettv)
9068 typval_T *argvars;
9069 typval_T *rettv;
9071 #ifdef FEAT_MBYTE
9072 if (has_mbyte)
9073 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
9074 else
9075 #endif
9076 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
9080 * "cindent(lnum)" function
9082 static void
9083 f_cindent(argvars, rettv)
9084 typval_T *argvars;
9085 typval_T *rettv;
9087 #ifdef FEAT_CINDENT
9088 pos_T pos;
9089 linenr_T lnum;
9091 pos = curwin->w_cursor;
9092 lnum = get_tv_lnum(argvars);
9093 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9095 curwin->w_cursor.lnum = lnum;
9096 rettv->vval.v_number = get_c_indent();
9097 curwin->w_cursor = pos;
9099 else
9100 #endif
9101 rettv->vval.v_number = -1;
9105 * "clearmatches()" function
9107 static void
9108 f_clearmatches(argvars, rettv)
9109 typval_T *argvars UNUSED;
9110 typval_T *rettv UNUSED;
9112 #ifdef FEAT_SEARCH_EXTRA
9113 clear_matches(curwin);
9114 #endif
9118 * "col(string)" function
9120 static void
9121 f_col(argvars, rettv)
9122 typval_T *argvars;
9123 typval_T *rettv;
9125 colnr_T col = 0;
9126 pos_T *fp;
9127 int fnum = curbuf->b_fnum;
9129 fp = var2fpos(&argvars[0], FALSE, &fnum);
9130 if (fp != NULL && fnum == curbuf->b_fnum)
9132 if (fp->col == MAXCOL)
9134 /* '> can be MAXCOL, get the length of the line then */
9135 if (fp->lnum <= curbuf->b_ml.ml_line_count)
9136 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
9137 else
9138 col = MAXCOL;
9140 else
9142 col = fp->col + 1;
9143 #ifdef FEAT_VIRTUALEDIT
9144 /* col(".") when the cursor is on the NUL at the end of the line
9145 * because of "coladd" can be seen as an extra column. */
9146 if (virtual_active() && fp == &curwin->w_cursor)
9148 char_u *p = ml_get_cursor();
9150 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
9151 curwin->w_virtcol - curwin->w_cursor.coladd))
9153 # ifdef FEAT_MBYTE
9154 int l;
9156 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
9157 col += l;
9158 # else
9159 if (*p != NUL && p[1] == NUL)
9160 ++col;
9161 # endif
9164 #endif
9167 rettv->vval.v_number = col;
9170 #if defined(FEAT_INS_EXPAND)
9172 * "complete()" function
9174 static void
9175 f_complete(argvars, rettv)
9176 typval_T *argvars;
9177 typval_T *rettv UNUSED;
9179 int startcol;
9181 if ((State & INSERT) == 0)
9183 EMSG(_("E785: complete() can only be used in Insert mode"));
9184 return;
9187 /* Check for undo allowed here, because if something was already inserted
9188 * the line was already saved for undo and this check isn't done. */
9189 if (!undo_allowed())
9190 return;
9192 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
9194 EMSG(_(e_invarg));
9195 return;
9198 startcol = get_tv_number_chk(&argvars[0], NULL);
9199 if (startcol <= 0)
9200 return;
9202 set_completion(startcol - 1, argvars[1].vval.v_list);
9206 * "complete_add()" function
9208 static void
9209 f_complete_add(argvars, rettv)
9210 typval_T *argvars;
9211 typval_T *rettv;
9213 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
9217 * "complete_check()" function
9219 static void
9220 f_complete_check(argvars, rettv)
9221 typval_T *argvars UNUSED;
9222 typval_T *rettv;
9224 int saved = RedrawingDisabled;
9226 RedrawingDisabled = 0;
9227 ins_compl_check_keys(0);
9228 rettv->vval.v_number = compl_interrupted;
9229 RedrawingDisabled = saved;
9231 #endif
9234 * "confirm(message, buttons[, default [, type]])" function
9236 static void
9237 f_confirm(argvars, rettv)
9238 typval_T *argvars UNUSED;
9239 typval_T *rettv UNUSED;
9241 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
9242 char_u *message;
9243 char_u *buttons = NULL;
9244 char_u buf[NUMBUFLEN];
9245 char_u buf2[NUMBUFLEN];
9246 int def = 1;
9247 int type = VIM_GENERIC;
9248 char_u *typestr;
9249 int error = FALSE;
9251 message = get_tv_string_chk(&argvars[0]);
9252 if (message == NULL)
9253 error = TRUE;
9254 if (argvars[1].v_type != VAR_UNKNOWN)
9256 buttons = get_tv_string_buf_chk(&argvars[1], buf);
9257 if (buttons == NULL)
9258 error = TRUE;
9259 if (argvars[2].v_type != VAR_UNKNOWN)
9261 def = get_tv_number_chk(&argvars[2], &error);
9262 if (argvars[3].v_type != VAR_UNKNOWN)
9264 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
9265 if (typestr == NULL)
9266 error = TRUE;
9267 else
9269 switch (TOUPPER_ASC(*typestr))
9271 case 'E': type = VIM_ERROR; break;
9272 case 'Q': type = VIM_QUESTION; break;
9273 case 'I': type = VIM_INFO; break;
9274 case 'W': type = VIM_WARNING; break;
9275 case 'G': type = VIM_GENERIC; break;
9282 if (buttons == NULL || *buttons == NUL)
9283 buttons = (char_u *)_("&Ok");
9285 if (!error)
9286 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
9287 def, NULL);
9288 #endif
9292 * "copy()" function
9294 static void
9295 f_copy(argvars, rettv)
9296 typval_T *argvars;
9297 typval_T *rettv;
9299 item_copy(&argvars[0], rettv, FALSE, 0);
9302 #ifdef FEAT_FLOAT
9304 * "cos()" function
9306 static void
9307 f_cos(argvars, rettv)
9308 typval_T *argvars;
9309 typval_T *rettv;
9311 float_T f;
9313 rettv->v_type = VAR_FLOAT;
9314 if (get_float_arg(argvars, &f) == OK)
9315 rettv->vval.v_float = cos(f);
9316 else
9317 rettv->vval.v_float = 0.0;
9319 #endif
9322 * "count()" function
9324 static void
9325 f_count(argvars, rettv)
9326 typval_T *argvars;
9327 typval_T *rettv;
9329 long n = 0;
9330 int ic = FALSE;
9332 if (argvars[0].v_type == VAR_LIST)
9334 listitem_T *li;
9335 list_T *l;
9336 long idx;
9338 if ((l = argvars[0].vval.v_list) != NULL)
9340 li = l->lv_first;
9341 if (argvars[2].v_type != VAR_UNKNOWN)
9343 int error = FALSE;
9345 ic = get_tv_number_chk(&argvars[2], &error);
9346 if (argvars[3].v_type != VAR_UNKNOWN)
9348 idx = get_tv_number_chk(&argvars[3], &error);
9349 if (!error)
9351 li = list_find(l, idx);
9352 if (li == NULL)
9353 EMSGN(_(e_listidx), idx);
9356 if (error)
9357 li = NULL;
9360 for ( ; li != NULL; li = li->li_next)
9361 if (tv_equal(&li->li_tv, &argvars[1], ic))
9362 ++n;
9365 else if (argvars[0].v_type == VAR_DICT)
9367 int todo;
9368 dict_T *d;
9369 hashitem_T *hi;
9371 if ((d = argvars[0].vval.v_dict) != NULL)
9373 int error = FALSE;
9375 if (argvars[2].v_type != VAR_UNKNOWN)
9377 ic = get_tv_number_chk(&argvars[2], &error);
9378 if (argvars[3].v_type != VAR_UNKNOWN)
9379 EMSG(_(e_invarg));
9382 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
9383 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
9385 if (!HASHITEM_EMPTY(hi))
9387 --todo;
9388 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
9389 ++n;
9394 else
9395 EMSG2(_(e_listdictarg), "count()");
9396 rettv->vval.v_number = n;
9400 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
9402 * Checks the existence of a cscope connection.
9404 static void
9405 f_cscope_connection(argvars, rettv)
9406 typval_T *argvars UNUSED;
9407 typval_T *rettv UNUSED;
9409 #ifdef FEAT_CSCOPE
9410 int num = 0;
9411 char_u *dbpath = NULL;
9412 char_u *prepend = NULL;
9413 char_u buf[NUMBUFLEN];
9415 if (argvars[0].v_type != VAR_UNKNOWN
9416 && argvars[1].v_type != VAR_UNKNOWN)
9418 num = (int)get_tv_number(&argvars[0]);
9419 dbpath = get_tv_string(&argvars[1]);
9420 if (argvars[2].v_type != VAR_UNKNOWN)
9421 prepend = get_tv_string_buf(&argvars[2], buf);
9424 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
9425 #endif
9429 * "cursor(lnum, col)" function
9431 * Moves the cursor to the specified line and column.
9432 * Returns 0 when the position could be set, -1 otherwise.
9434 static void
9435 f_cursor(argvars, rettv)
9436 typval_T *argvars;
9437 typval_T *rettv;
9439 long line, col;
9440 #ifdef FEAT_VIRTUALEDIT
9441 long coladd = 0;
9442 #endif
9444 rettv->vval.v_number = -1;
9445 if (argvars[1].v_type == VAR_UNKNOWN)
9447 pos_T pos;
9449 if (list2fpos(argvars, &pos, NULL) == FAIL)
9450 return;
9451 line = pos.lnum;
9452 col = pos.col;
9453 #ifdef FEAT_VIRTUALEDIT
9454 coladd = pos.coladd;
9455 #endif
9457 else
9459 line = get_tv_lnum(argvars);
9460 col = get_tv_number_chk(&argvars[1], NULL);
9461 #ifdef FEAT_VIRTUALEDIT
9462 if (argvars[2].v_type != VAR_UNKNOWN)
9463 coladd = get_tv_number_chk(&argvars[2], NULL);
9464 #endif
9466 if (line < 0 || col < 0
9467 #ifdef FEAT_VIRTUALEDIT
9468 || coladd < 0
9469 #endif
9471 return; /* type error; errmsg already given */
9472 if (line > 0)
9473 curwin->w_cursor.lnum = line;
9474 if (col > 0)
9475 curwin->w_cursor.col = col - 1;
9476 #ifdef FEAT_VIRTUALEDIT
9477 curwin->w_cursor.coladd = coladd;
9478 #endif
9480 /* Make sure the cursor is in a valid position. */
9481 check_cursor();
9482 #ifdef FEAT_MBYTE
9483 /* Correct cursor for multi-byte character. */
9484 if (has_mbyte)
9485 mb_adjust_cursor();
9486 #endif
9488 curwin->w_set_curswant = TRUE;
9489 rettv->vval.v_number = 0;
9493 * "deepcopy()" function
9495 static void
9496 f_deepcopy(argvars, rettv)
9497 typval_T *argvars;
9498 typval_T *rettv;
9500 int noref = 0;
9502 if (argvars[1].v_type != VAR_UNKNOWN)
9503 noref = get_tv_number_chk(&argvars[1], NULL);
9504 if (noref < 0 || noref > 1)
9505 EMSG(_(e_invarg));
9506 else
9508 current_copyID += COPYID_INC;
9509 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? current_copyID : 0);
9514 * "delete()" function
9516 static void
9517 f_delete(argvars, rettv)
9518 typval_T *argvars;
9519 typval_T *rettv;
9521 if (check_restricted() || check_secure())
9522 rettv->vval.v_number = -1;
9523 else
9524 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
9528 * "did_filetype()" function
9530 static void
9531 f_did_filetype(argvars, rettv)
9532 typval_T *argvars UNUSED;
9533 typval_T *rettv UNUSED;
9535 #ifdef FEAT_AUTOCMD
9536 rettv->vval.v_number = did_filetype;
9537 #endif
9541 * "diff_filler()" function
9543 static void
9544 f_diff_filler(argvars, rettv)
9545 typval_T *argvars UNUSED;
9546 typval_T *rettv UNUSED;
9548 #ifdef FEAT_DIFF
9549 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
9550 #endif
9554 * "diff_hlID()" function
9556 static void
9557 f_diff_hlID(argvars, rettv)
9558 typval_T *argvars UNUSED;
9559 typval_T *rettv UNUSED;
9561 #ifdef FEAT_DIFF
9562 linenr_T lnum = get_tv_lnum(argvars);
9563 static linenr_T prev_lnum = 0;
9564 static int changedtick = 0;
9565 static int fnum = 0;
9566 static int change_start = 0;
9567 static int change_end = 0;
9568 static hlf_T hlID = (hlf_T)0;
9569 int filler_lines;
9570 int col;
9572 if (lnum < 0) /* ignore type error in {lnum} arg */
9573 lnum = 0;
9574 if (lnum != prev_lnum
9575 || changedtick != curbuf->b_changedtick
9576 || fnum != curbuf->b_fnum)
9578 /* New line, buffer, change: need to get the values. */
9579 filler_lines = diff_check(curwin, lnum);
9580 if (filler_lines < 0)
9582 if (filler_lines == -1)
9584 change_start = MAXCOL;
9585 change_end = -1;
9586 if (diff_find_change(curwin, lnum, &change_start, &change_end))
9587 hlID = HLF_ADD; /* added line */
9588 else
9589 hlID = HLF_CHD; /* changed line */
9591 else
9592 hlID = HLF_ADD; /* added line */
9594 else
9595 hlID = (hlf_T)0;
9596 prev_lnum = lnum;
9597 changedtick = curbuf->b_changedtick;
9598 fnum = curbuf->b_fnum;
9601 if (hlID == HLF_CHD || hlID == HLF_TXD)
9603 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
9604 if (col >= change_start && col <= change_end)
9605 hlID = HLF_TXD; /* changed text */
9606 else
9607 hlID = HLF_CHD; /* changed line */
9609 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
9610 #endif
9614 * "empty({expr})" function
9616 static void
9617 f_empty(argvars, rettv)
9618 typval_T *argvars;
9619 typval_T *rettv;
9621 int n;
9623 switch (argvars[0].v_type)
9625 case VAR_STRING:
9626 case VAR_FUNC:
9627 n = argvars[0].vval.v_string == NULL
9628 || *argvars[0].vval.v_string == NUL;
9629 break;
9630 case VAR_NUMBER:
9631 n = argvars[0].vval.v_number == 0;
9632 break;
9633 #ifdef FEAT_FLOAT
9634 case VAR_FLOAT:
9635 n = argvars[0].vval.v_float == 0.0;
9636 break;
9637 #endif
9638 case VAR_LIST:
9639 n = argvars[0].vval.v_list == NULL
9640 || argvars[0].vval.v_list->lv_first == NULL;
9641 break;
9642 case VAR_DICT:
9643 n = argvars[0].vval.v_dict == NULL
9644 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
9645 break;
9646 default:
9647 EMSG2(_(e_intern2), "f_empty()");
9648 n = 0;
9651 rettv->vval.v_number = n;
9655 * "escape({string}, {chars})" function
9657 static void
9658 f_escape(argvars, rettv)
9659 typval_T *argvars;
9660 typval_T *rettv;
9662 char_u buf[NUMBUFLEN];
9664 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
9665 get_tv_string_buf(&argvars[1], buf));
9666 rettv->v_type = VAR_STRING;
9670 * "eval()" function
9672 static void
9673 f_eval(argvars, rettv)
9674 typval_T *argvars;
9675 typval_T *rettv;
9677 char_u *s;
9679 s = get_tv_string_chk(&argvars[0]);
9680 if (s != NULL)
9681 s = skipwhite(s);
9683 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
9685 rettv->v_type = VAR_NUMBER;
9686 rettv->vval.v_number = 0;
9688 else if (*s != NUL)
9689 EMSG(_(e_trailing));
9693 * "eventhandler()" function
9695 static void
9696 f_eventhandler(argvars, rettv)
9697 typval_T *argvars UNUSED;
9698 typval_T *rettv;
9700 rettv->vval.v_number = vgetc_busy;
9704 * "executable()" function
9706 static void
9707 f_executable(argvars, rettv)
9708 typval_T *argvars;
9709 typval_T *rettv;
9711 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
9715 * "exists()" function
9717 static void
9718 f_exists(argvars, rettv)
9719 typval_T *argvars;
9720 typval_T *rettv;
9722 char_u *p;
9723 char_u *name;
9724 int n = FALSE;
9725 int len = 0;
9727 p = get_tv_string(&argvars[0]);
9728 if (*p == '$') /* environment variable */
9730 /* first try "normal" environment variables (fast) */
9731 if (mch_getenv(p + 1) != NULL)
9732 n = TRUE;
9733 else
9735 /* try expanding things like $VIM and ${HOME} */
9736 p = expand_env_save(p);
9737 if (p != NULL && *p != '$')
9738 n = TRUE;
9739 vim_free(p);
9742 else if (*p == '&' || *p == '+') /* option */
9744 n = (get_option_tv(&p, NULL, TRUE) == OK);
9745 if (*skipwhite(p) != NUL)
9746 n = FALSE; /* trailing garbage */
9748 else if (*p == '*') /* internal or user defined function */
9750 n = function_exists(p + 1);
9752 else if (*p == ':')
9754 n = cmd_exists(p + 1);
9756 else if (*p == '#')
9758 #ifdef FEAT_AUTOCMD
9759 if (p[1] == '#')
9760 n = autocmd_supported(p + 2);
9761 else
9762 n = au_exists(p + 1);
9763 #endif
9765 else /* internal variable */
9767 char_u *tofree;
9768 typval_T tv;
9770 /* get_name_len() takes care of expanding curly braces */
9771 name = p;
9772 len = get_name_len(&p, &tofree, TRUE, FALSE);
9773 if (len > 0)
9775 if (tofree != NULL)
9776 name = tofree;
9777 n = (get_var_tv(name, len, &tv, FALSE) == OK);
9778 if (n)
9780 /* handle d.key, l[idx], f(expr) */
9781 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
9782 if (n)
9783 clear_tv(&tv);
9786 if (*p != NUL)
9787 n = FALSE;
9789 vim_free(tofree);
9792 rettv->vval.v_number = n;
9796 * "expand()" function
9798 static void
9799 f_expand(argvars, rettv)
9800 typval_T *argvars;
9801 typval_T *rettv;
9803 char_u *s;
9804 int len;
9805 char_u *errormsg;
9806 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
9807 expand_T xpc;
9808 int error = FALSE;
9810 rettv->v_type = VAR_STRING;
9811 s = get_tv_string(&argvars[0]);
9812 if (*s == '%' || *s == '#' || *s == '<')
9814 ++emsg_off;
9815 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
9816 --emsg_off;
9818 else
9820 /* When the optional second argument is non-zero, don't remove matches
9821 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
9822 if (argvars[1].v_type != VAR_UNKNOWN
9823 && get_tv_number_chk(&argvars[1], &error))
9824 flags |= WILD_KEEP_ALL;
9825 if (!error)
9827 ExpandInit(&xpc);
9828 xpc.xp_context = EXPAND_FILES;
9829 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
9831 else
9832 rettv->vval.v_string = NULL;
9837 * "extend(list, list [, idx])" function
9838 * "extend(dict, dict [, action])" function
9840 static void
9841 f_extend(argvars, rettv)
9842 typval_T *argvars;
9843 typval_T *rettv;
9845 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9847 list_T *l1, *l2;
9848 listitem_T *item;
9849 long before;
9850 int error = FALSE;
9852 l1 = argvars[0].vval.v_list;
9853 l2 = argvars[1].vval.v_list;
9854 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9855 && l2 != NULL)
9857 if (argvars[2].v_type != VAR_UNKNOWN)
9859 before = get_tv_number_chk(&argvars[2], &error);
9860 if (error)
9861 return; /* type error; errmsg already given */
9863 if (before == l1->lv_len)
9864 item = NULL;
9865 else
9867 item = list_find(l1, before);
9868 if (item == NULL)
9870 EMSGN(_(e_listidx), before);
9871 return;
9875 else
9876 item = NULL;
9877 list_extend(l1, l2, item);
9879 copy_tv(&argvars[0], rettv);
9882 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9884 dict_T *d1, *d2;
9885 dictitem_T *di1;
9886 char_u *action;
9887 int i;
9888 hashitem_T *hi2;
9889 int todo;
9891 d1 = argvars[0].vval.v_dict;
9892 d2 = argvars[1].vval.v_dict;
9893 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9894 && d2 != NULL)
9896 /* Check the third argument. */
9897 if (argvars[2].v_type != VAR_UNKNOWN)
9899 static char *(av[]) = {"keep", "force", "error"};
9901 action = get_tv_string_chk(&argvars[2]);
9902 if (action == NULL)
9903 return; /* type error; errmsg already given */
9904 for (i = 0; i < 3; ++i)
9905 if (STRCMP(action, av[i]) == 0)
9906 break;
9907 if (i == 3)
9909 EMSG2(_(e_invarg2), action);
9910 return;
9913 else
9914 action = (char_u *)"force";
9916 /* Go over all entries in the second dict and add them to the
9917 * first dict. */
9918 todo = (int)d2->dv_hashtab.ht_used;
9919 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9921 if (!HASHITEM_EMPTY(hi2))
9923 --todo;
9924 di1 = dict_find(d1, hi2->hi_key, -1);
9925 if (di1 == NULL)
9927 di1 = dictitem_copy(HI2DI(hi2));
9928 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9929 dictitem_free(di1);
9931 else if (*action == 'e')
9933 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9934 break;
9936 else if (*action == 'f')
9938 clear_tv(&di1->di_tv);
9939 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9944 copy_tv(&argvars[0], rettv);
9947 else
9948 EMSG2(_(e_listdictarg), "extend()");
9952 * "feedkeys()" function
9954 static void
9955 f_feedkeys(argvars, rettv)
9956 typval_T *argvars;
9957 typval_T *rettv UNUSED;
9959 int remap = TRUE;
9960 char_u *keys, *flags;
9961 char_u nbuf[NUMBUFLEN];
9962 int typed = FALSE;
9963 char_u *keys_esc;
9965 /* This is not allowed in the sandbox. If the commands would still be
9966 * executed in the sandbox it would be OK, but it probably happens later,
9967 * when "sandbox" is no longer set. */
9968 if (check_secure())
9969 return;
9971 keys = get_tv_string(&argvars[0]);
9972 if (*keys != NUL)
9974 if (argvars[1].v_type != VAR_UNKNOWN)
9976 flags = get_tv_string_buf(&argvars[1], nbuf);
9977 for ( ; *flags != NUL; ++flags)
9979 switch (*flags)
9981 case 'n': remap = FALSE; break;
9982 case 'm': remap = TRUE; break;
9983 case 't': typed = TRUE; break;
9988 /* Need to escape K_SPECIAL and CSI before putting the string in the
9989 * typeahead buffer. */
9990 keys_esc = vim_strsave_escape_csi(keys);
9991 if (keys_esc != NULL)
9993 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
9994 typebuf.tb_len, !typed, FALSE);
9995 vim_free(keys_esc);
9996 if (vgetc_busy)
9997 typebuf_was_filled = TRUE;
10003 * "filereadable()" function
10005 static void
10006 f_filereadable(argvars, rettv)
10007 typval_T *argvars;
10008 typval_T *rettv;
10010 int fd;
10011 char_u *p;
10012 int n;
10014 #ifndef O_NONBLOCK
10015 # define O_NONBLOCK 0
10016 #endif
10017 p = get_tv_string(&argvars[0]);
10018 if (*p && !mch_isdir(p) && (fd = mch_open((char *)p,
10019 O_RDONLY | O_NONBLOCK, 0)) >= 0)
10021 n = TRUE;
10022 close(fd);
10024 else
10025 n = FALSE;
10027 rettv->vval.v_number = n;
10031 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
10032 * rights to write into.
10034 static void
10035 f_filewritable(argvars, rettv)
10036 typval_T *argvars;
10037 typval_T *rettv;
10039 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
10042 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
10044 static void
10045 findfilendir(argvars, rettv, find_what)
10046 typval_T *argvars;
10047 typval_T *rettv;
10048 int find_what;
10050 #ifdef FEAT_SEARCHPATH
10051 char_u *fname;
10052 char_u *fresult = NULL;
10053 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
10054 char_u *p;
10055 char_u pathbuf[NUMBUFLEN];
10056 int count = 1;
10057 int first = TRUE;
10058 int error = FALSE;
10059 #endif
10061 rettv->vval.v_string = NULL;
10062 rettv->v_type = VAR_STRING;
10064 #ifdef FEAT_SEARCHPATH
10065 fname = get_tv_string(&argvars[0]);
10067 if (argvars[1].v_type != VAR_UNKNOWN)
10069 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
10070 if (p == NULL)
10071 error = TRUE;
10072 else
10074 if (*p != NUL)
10075 path = p;
10077 if (argvars[2].v_type != VAR_UNKNOWN)
10078 count = get_tv_number_chk(&argvars[2], &error);
10082 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
10083 error = TRUE;
10085 if (*fname != NUL && !error)
10089 if (rettv->v_type == VAR_STRING)
10090 vim_free(fresult);
10091 fresult = find_file_in_path_option(first ? fname : NULL,
10092 first ? (int)STRLEN(fname) : 0,
10093 0, first, path,
10094 find_what,
10095 curbuf->b_ffname,
10096 find_what == FINDFILE_DIR
10097 ? (char_u *)"" : curbuf->b_p_sua);
10098 first = FALSE;
10100 if (fresult != NULL && rettv->v_type == VAR_LIST)
10101 list_append_string(rettv->vval.v_list, fresult, -1);
10103 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
10106 if (rettv->v_type == VAR_STRING)
10107 rettv->vval.v_string = fresult;
10108 #endif
10111 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
10112 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
10115 * Implementation of map() and filter().
10117 static void
10118 filter_map(argvars, rettv, map)
10119 typval_T *argvars;
10120 typval_T *rettv;
10121 int map;
10123 char_u buf[NUMBUFLEN];
10124 char_u *expr;
10125 listitem_T *li, *nli;
10126 list_T *l = NULL;
10127 dictitem_T *di;
10128 hashtab_T *ht;
10129 hashitem_T *hi;
10130 dict_T *d = NULL;
10131 typval_T save_val;
10132 typval_T save_key;
10133 int rem;
10134 int todo;
10135 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
10136 int save_did_emsg;
10137 int index = 0;
10139 if (argvars[0].v_type == VAR_LIST)
10141 if ((l = argvars[0].vval.v_list) == NULL
10142 || (map && tv_check_lock(l->lv_lock, ermsg)))
10143 return;
10145 else if (argvars[0].v_type == VAR_DICT)
10147 if ((d = argvars[0].vval.v_dict) == NULL
10148 || (map && tv_check_lock(d->dv_lock, ermsg)))
10149 return;
10151 else
10153 EMSG2(_(e_listdictarg), ermsg);
10154 return;
10157 expr = get_tv_string_buf_chk(&argvars[1], buf);
10158 /* On type errors, the preceding call has already displayed an error
10159 * message. Avoid a misleading error message for an empty string that
10160 * was not passed as argument. */
10161 if (expr != NULL)
10163 prepare_vimvar(VV_VAL, &save_val);
10164 expr = skipwhite(expr);
10166 /* We reset "did_emsg" to be able to detect whether an error
10167 * occurred during evaluation of the expression. */
10168 save_did_emsg = did_emsg;
10169 did_emsg = FALSE;
10171 prepare_vimvar(VV_KEY, &save_key);
10172 if (argvars[0].v_type == VAR_DICT)
10174 vimvars[VV_KEY].vv_type = VAR_STRING;
10176 ht = &d->dv_hashtab;
10177 hash_lock(ht);
10178 todo = (int)ht->ht_used;
10179 for (hi = ht->ht_array; todo > 0; ++hi)
10181 if (!HASHITEM_EMPTY(hi))
10183 --todo;
10184 di = HI2DI(hi);
10185 if (tv_check_lock(di->di_tv.v_lock, ermsg))
10186 break;
10187 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
10188 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
10189 || did_emsg)
10190 break;
10191 if (!map && rem)
10192 dictitem_remove(d, di);
10193 clear_tv(&vimvars[VV_KEY].vv_tv);
10196 hash_unlock(ht);
10198 else
10200 vimvars[VV_KEY].vv_type = VAR_NUMBER;
10202 for (li = l->lv_first; li != NULL; li = nli)
10204 if (tv_check_lock(li->li_tv.v_lock, ermsg))
10205 break;
10206 nli = li->li_next;
10207 vimvars[VV_KEY].vv_nr = index;
10208 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
10209 || did_emsg)
10210 break;
10211 if (!map && rem)
10212 listitem_remove(l, li);
10213 ++index;
10217 restore_vimvar(VV_KEY, &save_key);
10218 restore_vimvar(VV_VAL, &save_val);
10220 did_emsg |= save_did_emsg;
10223 copy_tv(&argvars[0], rettv);
10226 static int
10227 filter_map_one(tv, expr, map, remp)
10228 typval_T *tv;
10229 char_u *expr;
10230 int map;
10231 int *remp;
10233 typval_T rettv;
10234 char_u *s;
10235 int retval = FAIL;
10237 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
10238 s = expr;
10239 if (eval1(&s, &rettv, TRUE) == FAIL)
10240 goto theend;
10241 if (*s != NUL) /* check for trailing chars after expr */
10243 EMSG2(_(e_invexpr2), s);
10244 goto theend;
10246 if (map)
10248 /* map(): replace the list item value */
10249 clear_tv(tv);
10250 rettv.v_lock = 0;
10251 *tv = rettv;
10253 else
10255 int error = FALSE;
10257 /* filter(): when expr is zero remove the item */
10258 *remp = (get_tv_number_chk(&rettv, &error) == 0);
10259 clear_tv(&rettv);
10260 /* On type error, nothing has been removed; return FAIL to stop the
10261 * loop. The error message was given by get_tv_number_chk(). */
10262 if (error)
10263 goto theend;
10265 retval = OK;
10266 theend:
10267 clear_tv(&vimvars[VV_VAL].vv_tv);
10268 return retval;
10272 * "filter()" function
10274 static void
10275 f_filter(argvars, rettv)
10276 typval_T *argvars;
10277 typval_T *rettv;
10279 filter_map(argvars, rettv, FALSE);
10283 * "finddir({fname}[, {path}[, {count}]])" function
10285 static void
10286 f_finddir(argvars, rettv)
10287 typval_T *argvars;
10288 typval_T *rettv;
10290 findfilendir(argvars, rettv, FINDFILE_DIR);
10294 * "findfile({fname}[, {path}[, {count}]])" function
10296 static void
10297 f_findfile(argvars, rettv)
10298 typval_T *argvars;
10299 typval_T *rettv;
10301 findfilendir(argvars, rettv, FINDFILE_FILE);
10304 #ifdef FEAT_FLOAT
10306 * "float2nr({float})" function
10308 static void
10309 f_float2nr(argvars, rettv)
10310 typval_T *argvars;
10311 typval_T *rettv;
10313 float_T f;
10315 if (get_float_arg(argvars, &f) == OK)
10317 if (f < -0x7fffffff)
10318 rettv->vval.v_number = -0x7fffffff;
10319 else if (f > 0x7fffffff)
10320 rettv->vval.v_number = 0x7fffffff;
10321 else
10322 rettv->vval.v_number = (varnumber_T)f;
10327 * "floor({float})" function
10329 static void
10330 f_floor(argvars, rettv)
10331 typval_T *argvars;
10332 typval_T *rettv;
10334 float_T f;
10336 rettv->v_type = VAR_FLOAT;
10337 if (get_float_arg(argvars, &f) == OK)
10338 rettv->vval.v_float = floor(f);
10339 else
10340 rettv->vval.v_float = 0.0;
10342 #endif
10345 * "fnameescape({string})" function
10347 static void
10348 f_fnameescape(argvars, rettv)
10349 typval_T *argvars;
10350 typval_T *rettv;
10352 rettv->vval.v_string = vim_strsave_fnameescape(
10353 get_tv_string(&argvars[0]), FALSE);
10354 rettv->v_type = VAR_STRING;
10358 * "fnamemodify({fname}, {mods})" function
10360 static void
10361 f_fnamemodify(argvars, rettv)
10362 typval_T *argvars;
10363 typval_T *rettv;
10365 char_u *fname;
10366 char_u *mods;
10367 int usedlen = 0;
10368 int len;
10369 char_u *fbuf = NULL;
10370 char_u buf[NUMBUFLEN];
10372 fname = get_tv_string_chk(&argvars[0]);
10373 mods = get_tv_string_buf_chk(&argvars[1], buf);
10374 if (fname == NULL || mods == NULL)
10375 fname = NULL;
10376 else
10378 len = (int)STRLEN(fname);
10379 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
10382 rettv->v_type = VAR_STRING;
10383 if (fname == NULL)
10384 rettv->vval.v_string = NULL;
10385 else
10386 rettv->vval.v_string = vim_strnsave(fname, len);
10387 vim_free(fbuf);
10390 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
10393 * "foldclosed()" function
10395 static void
10396 foldclosed_both(argvars, rettv, end)
10397 typval_T *argvars;
10398 typval_T *rettv;
10399 int end;
10401 #ifdef FEAT_FOLDING
10402 linenr_T lnum;
10403 linenr_T first, last;
10405 lnum = get_tv_lnum(argvars);
10406 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10408 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
10410 if (end)
10411 rettv->vval.v_number = (varnumber_T)last;
10412 else
10413 rettv->vval.v_number = (varnumber_T)first;
10414 return;
10417 #endif
10418 rettv->vval.v_number = -1;
10422 * "foldclosed()" function
10424 static void
10425 f_foldclosed(argvars, rettv)
10426 typval_T *argvars;
10427 typval_T *rettv;
10429 foldclosed_both(argvars, rettv, FALSE);
10433 * "foldclosedend()" function
10435 static void
10436 f_foldclosedend(argvars, rettv)
10437 typval_T *argvars;
10438 typval_T *rettv;
10440 foldclosed_both(argvars, rettv, TRUE);
10444 * "foldlevel()" function
10446 static void
10447 f_foldlevel(argvars, rettv)
10448 typval_T *argvars;
10449 typval_T *rettv;
10451 #ifdef FEAT_FOLDING
10452 linenr_T lnum;
10454 lnum = get_tv_lnum(argvars);
10455 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10456 rettv->vval.v_number = foldLevel(lnum);
10457 #endif
10461 * "foldtext()" function
10463 static void
10464 f_foldtext(argvars, rettv)
10465 typval_T *argvars UNUSED;
10466 typval_T *rettv;
10468 #ifdef FEAT_FOLDING
10469 linenr_T lnum;
10470 char_u *s;
10471 char_u *r;
10472 int len;
10473 char *txt;
10474 #endif
10476 rettv->v_type = VAR_STRING;
10477 rettv->vval.v_string = NULL;
10478 #ifdef FEAT_FOLDING
10479 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
10480 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
10481 <= curbuf->b_ml.ml_line_count
10482 && vimvars[VV_FOLDDASHES].vv_str != NULL)
10484 /* Find first non-empty line in the fold. */
10485 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
10486 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10488 if (!linewhite(lnum))
10489 break;
10490 ++lnum;
10493 /* Find interesting text in this line. */
10494 s = skipwhite(ml_get(lnum));
10495 /* skip C comment-start */
10496 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
10498 s = skipwhite(s + 2);
10499 if (*skipwhite(s) == NUL
10500 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10502 s = skipwhite(ml_get(lnum + 1));
10503 if (*s == '*')
10504 s = skipwhite(s + 1);
10507 txt = _("+-%s%3ld lines: ");
10508 r = alloc((unsigned)(STRLEN(txt)
10509 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
10510 + 20 /* for %3ld */
10511 + STRLEN(s))); /* concatenated */
10512 if (r != NULL)
10514 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
10515 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
10516 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
10517 len = (int)STRLEN(r);
10518 STRCAT(r, s);
10519 /* remove 'foldmarker' and 'commentstring' */
10520 foldtext_cleanup(r + len);
10521 rettv->vval.v_string = r;
10524 #endif
10528 * "foldtextresult(lnum)" function
10530 static void
10531 f_foldtextresult(argvars, rettv)
10532 typval_T *argvars UNUSED;
10533 typval_T *rettv;
10535 #ifdef FEAT_FOLDING
10536 linenr_T lnum;
10537 char_u *text;
10538 char_u buf[51];
10539 foldinfo_T foldinfo;
10540 int fold_count;
10541 #endif
10543 rettv->v_type = VAR_STRING;
10544 rettv->vval.v_string = NULL;
10545 #ifdef FEAT_FOLDING
10546 lnum = get_tv_lnum(argvars);
10547 /* treat illegal types and illegal string values for {lnum} the same */
10548 if (lnum < 0)
10549 lnum = 0;
10550 fold_count = foldedCount(curwin, lnum, &foldinfo);
10551 if (fold_count > 0)
10553 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
10554 &foldinfo, buf);
10555 if (text == buf)
10556 text = vim_strsave(text);
10557 rettv->vval.v_string = text;
10559 #endif
10563 * "foreground()" function
10565 static void
10566 f_foreground(argvars, rettv)
10567 typval_T *argvars UNUSED;
10568 typval_T *rettv UNUSED;
10570 #ifdef FEAT_GUI
10571 if (gui.in_use)
10572 gui_mch_set_foreground();
10573 #else
10574 # ifdef WIN32
10575 win32_set_foreground();
10576 # endif
10577 #endif
10581 * "function()" function
10583 static void
10584 f_function(argvars, rettv)
10585 typval_T *argvars;
10586 typval_T *rettv;
10588 char_u *s;
10590 s = get_tv_string(&argvars[0]);
10591 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
10592 EMSG2(_(e_invarg2), s);
10593 /* Don't check an autoload name for existence here. */
10594 else if (vim_strchr(s, AUTOLOAD_CHAR) == NULL && !function_exists(s))
10595 EMSG2(_("E700: Unknown function: %s"), s);
10596 else
10598 rettv->vval.v_string = vim_strsave(s);
10599 rettv->v_type = VAR_FUNC;
10604 * "garbagecollect()" function
10606 static void
10607 f_garbagecollect(argvars, rettv)
10608 typval_T *argvars;
10609 typval_T *rettv UNUSED;
10611 /* This is postponed until we are back at the toplevel, because we may be
10612 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
10613 want_garbage_collect = TRUE;
10615 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
10616 garbage_collect_at_exit = TRUE;
10620 * "get()" function
10622 static void
10623 f_get(argvars, rettv)
10624 typval_T *argvars;
10625 typval_T *rettv;
10627 listitem_T *li;
10628 list_T *l;
10629 dictitem_T *di;
10630 dict_T *d;
10631 typval_T *tv = NULL;
10633 if (argvars[0].v_type == VAR_LIST)
10635 if ((l = argvars[0].vval.v_list) != NULL)
10637 int error = FALSE;
10639 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
10640 if (!error && li != NULL)
10641 tv = &li->li_tv;
10644 else if (argvars[0].v_type == VAR_DICT)
10646 if ((d = argvars[0].vval.v_dict) != NULL)
10648 di = dict_find(d, get_tv_string(&argvars[1]), -1);
10649 if (di != NULL)
10650 tv = &di->di_tv;
10653 else
10654 EMSG2(_(e_listdictarg), "get()");
10656 if (tv == NULL)
10658 if (argvars[2].v_type != VAR_UNKNOWN)
10659 copy_tv(&argvars[2], rettv);
10661 else
10662 copy_tv(tv, rettv);
10665 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
10668 * Get line or list of lines from buffer "buf" into "rettv".
10669 * Return a range (from start to end) of lines in rettv from the specified
10670 * buffer.
10671 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
10673 static void
10674 get_buffer_lines(buf, start, end, retlist, rettv)
10675 buf_T *buf;
10676 linenr_T start;
10677 linenr_T end;
10678 int retlist;
10679 typval_T *rettv;
10681 char_u *p;
10683 if (retlist && rettv_list_alloc(rettv) == FAIL)
10684 return;
10686 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
10687 return;
10689 if (!retlist)
10691 if (start >= 1 && start <= buf->b_ml.ml_line_count)
10692 p = ml_get_buf(buf, start, FALSE);
10693 else
10694 p = (char_u *)"";
10696 rettv->v_type = VAR_STRING;
10697 rettv->vval.v_string = vim_strsave(p);
10699 else
10701 if (end < start)
10702 return;
10704 if (start < 1)
10705 start = 1;
10706 if (end > buf->b_ml.ml_line_count)
10707 end = buf->b_ml.ml_line_count;
10708 while (start <= end)
10709 if (list_append_string(rettv->vval.v_list,
10710 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
10711 break;
10716 * "getbufline()" function
10718 static void
10719 f_getbufline(argvars, rettv)
10720 typval_T *argvars;
10721 typval_T *rettv;
10723 linenr_T lnum;
10724 linenr_T end;
10725 buf_T *buf;
10727 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10728 ++emsg_off;
10729 buf = get_buf_tv(&argvars[0]);
10730 --emsg_off;
10732 lnum = get_tv_lnum_buf(&argvars[1], buf);
10733 if (argvars[2].v_type == VAR_UNKNOWN)
10734 end = lnum;
10735 else
10736 end = get_tv_lnum_buf(&argvars[2], buf);
10738 get_buffer_lines(buf, lnum, end, TRUE, rettv);
10742 * "getbufvar()" function
10744 static void
10745 f_getbufvar(argvars, rettv)
10746 typval_T *argvars;
10747 typval_T *rettv;
10749 buf_T *buf;
10750 buf_T *save_curbuf;
10751 char_u *varname;
10752 dictitem_T *v;
10754 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10755 varname = get_tv_string_chk(&argvars[1]);
10756 ++emsg_off;
10757 buf = get_buf_tv(&argvars[0]);
10759 rettv->v_type = VAR_STRING;
10760 rettv->vval.v_string = NULL;
10762 if (buf != NULL && varname != NULL)
10764 /* set curbuf to be our buf, temporarily */
10765 save_curbuf = curbuf;
10766 curbuf = buf;
10768 if (*varname == '&') /* buffer-local-option */
10769 get_option_tv(&varname, rettv, TRUE);
10770 else
10772 if (*varname == NUL)
10773 /* let getbufvar({nr}, "") return the "b:" dictionary. The
10774 * scope prefix before the NUL byte is required by
10775 * find_var_in_ht(). */
10776 varname = (char_u *)"b:" + 2;
10777 /* look up the variable */
10778 v = find_var_in_ht(&curbuf->b_vars.dv_hashtab, varname, FALSE);
10779 if (v != NULL)
10780 copy_tv(&v->di_tv, rettv);
10783 /* restore previous notion of curbuf */
10784 curbuf = save_curbuf;
10787 --emsg_off;
10791 * "getchar()" function
10793 static void
10794 f_getchar(argvars, rettv)
10795 typval_T *argvars;
10796 typval_T *rettv;
10798 varnumber_T n;
10799 int error = FALSE;
10801 /* Position the cursor. Needed after a message that ends in a space. */
10802 windgoto(msg_row, msg_col);
10804 ++no_mapping;
10805 ++allow_keys;
10806 for (;;)
10808 if (argvars[0].v_type == VAR_UNKNOWN)
10809 /* getchar(): blocking wait. */
10810 n = safe_vgetc();
10811 else if (get_tv_number_chk(&argvars[0], &error) == 1)
10812 /* getchar(1): only check if char avail */
10813 n = vpeekc();
10814 else if (error || vpeekc() == NUL)
10815 /* illegal argument or getchar(0) and no char avail: return zero */
10816 n = 0;
10817 else
10818 /* getchar(0) and char avail: return char */
10819 n = safe_vgetc();
10820 if (n == K_IGNORE)
10821 continue;
10822 break;
10824 --no_mapping;
10825 --allow_keys;
10827 vimvars[VV_MOUSE_WIN].vv_nr = 0;
10828 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
10829 vimvars[VV_MOUSE_COL].vv_nr = 0;
10831 rettv->vval.v_number = n;
10832 if (IS_SPECIAL(n) || mod_mask != 0)
10834 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
10835 int i = 0;
10837 /* Turn a special key into three bytes, plus modifier. */
10838 if (mod_mask != 0)
10840 temp[i++] = K_SPECIAL;
10841 temp[i++] = KS_MODIFIER;
10842 temp[i++] = mod_mask;
10844 if (IS_SPECIAL(n))
10846 temp[i++] = K_SPECIAL;
10847 temp[i++] = K_SECOND(n);
10848 temp[i++] = K_THIRD(n);
10850 #ifdef FEAT_MBYTE
10851 else if (has_mbyte)
10852 i += (*mb_char2bytes)(n, temp + i);
10853 #endif
10854 else
10855 temp[i++] = n;
10856 temp[i++] = NUL;
10857 rettv->v_type = VAR_STRING;
10858 rettv->vval.v_string = vim_strsave(temp);
10860 #ifdef FEAT_MOUSE
10861 if (n == K_LEFTMOUSE
10862 || n == K_LEFTMOUSE_NM
10863 || n == K_LEFTDRAG
10864 || n == K_LEFTRELEASE
10865 || n == K_LEFTRELEASE_NM
10866 || n == K_MIDDLEMOUSE
10867 || n == K_MIDDLEDRAG
10868 || n == K_MIDDLERELEASE
10869 || n == K_RIGHTMOUSE
10870 || n == K_RIGHTDRAG
10871 || n == K_RIGHTRELEASE
10872 || n == K_X1MOUSE
10873 || n == K_X1DRAG
10874 || n == K_X1RELEASE
10875 || n == K_X2MOUSE
10876 || n == K_X2DRAG
10877 || n == K_X2RELEASE
10878 || n == K_MOUSEDOWN
10879 || n == K_MOUSEUP)
10881 int row = mouse_row;
10882 int col = mouse_col;
10883 win_T *win;
10884 linenr_T lnum;
10885 # ifdef FEAT_WINDOWS
10886 win_T *wp;
10887 # endif
10888 int winnr = 1;
10890 if (row >= 0 && col >= 0)
10892 /* Find the window at the mouse coordinates and compute the
10893 * text position. */
10894 win = mouse_find_win(&row, &col);
10895 (void)mouse_comp_pos(win, &row, &col, &lnum);
10896 # ifdef FEAT_WINDOWS
10897 for (wp = firstwin; wp != win; wp = wp->w_next)
10898 ++winnr;
10899 # endif
10900 vimvars[VV_MOUSE_WIN].vv_nr = winnr;
10901 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
10902 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
10905 #endif
10910 * "getcharmod()" function
10912 static void
10913 f_getcharmod(argvars, rettv)
10914 typval_T *argvars UNUSED;
10915 typval_T *rettv;
10917 rettv->vval.v_number = mod_mask;
10921 * "getcmdline()" function
10923 static void
10924 f_getcmdline(argvars, rettv)
10925 typval_T *argvars UNUSED;
10926 typval_T *rettv;
10928 rettv->v_type = VAR_STRING;
10929 rettv->vval.v_string = get_cmdline_str();
10933 * "getcmdpos()" function
10935 static void
10936 f_getcmdpos(argvars, rettv)
10937 typval_T *argvars UNUSED;
10938 typval_T *rettv;
10940 rettv->vval.v_number = get_cmdline_pos() + 1;
10944 * "getcmdtype()" function
10946 static void
10947 f_getcmdtype(argvars, rettv)
10948 typval_T *argvars UNUSED;
10949 typval_T *rettv;
10951 rettv->v_type = VAR_STRING;
10952 rettv->vval.v_string = alloc(2);
10953 if (rettv->vval.v_string != NULL)
10955 rettv->vval.v_string[0] = get_cmdline_type();
10956 rettv->vval.v_string[1] = NUL;
10961 * "getcwd()" function
10963 static void
10964 f_getcwd(argvars, rettv)
10965 typval_T *argvars UNUSED;
10966 typval_T *rettv;
10968 char_u cwd[MAXPATHL];
10970 rettv->v_type = VAR_STRING;
10971 if (mch_dirname(cwd, MAXPATHL) == FAIL)
10972 rettv->vval.v_string = NULL;
10973 else
10975 rettv->vval.v_string = vim_strsave(cwd);
10976 #ifdef BACKSLASH_IN_FILENAME
10977 if (rettv->vval.v_string != NULL)
10978 slash_adjust(rettv->vval.v_string);
10979 #endif
10984 * "getfontname()" function
10986 static void
10987 f_getfontname(argvars, rettv)
10988 typval_T *argvars UNUSED;
10989 typval_T *rettv;
10991 rettv->v_type = VAR_STRING;
10992 rettv->vval.v_string = NULL;
10993 #ifdef FEAT_GUI
10994 if (gui.in_use)
10996 GuiFont font;
10997 char_u *name = NULL;
10999 if (argvars[0].v_type == VAR_UNKNOWN)
11001 /* Get the "Normal" font. Either the name saved by
11002 * hl_set_font_name() or from the font ID. */
11003 font = gui.norm_font;
11004 name = hl_get_font_name();
11006 else
11008 name = get_tv_string(&argvars[0]);
11009 if (STRCMP(name, "*") == 0) /* don't use font dialog */
11010 return;
11011 font = gui_mch_get_font(name, FALSE);
11012 if (font == NOFONT)
11013 return; /* Invalid font name, return empty string. */
11015 rettv->vval.v_string = gui_mch_get_fontname(font, name);
11016 if (argvars[0].v_type != VAR_UNKNOWN)
11017 gui_mch_free_font(font);
11019 #endif
11023 * "getfperm({fname})" function
11025 static void
11026 f_getfperm(argvars, rettv)
11027 typval_T *argvars;
11028 typval_T *rettv;
11030 char_u *fname;
11031 struct stat st;
11032 char_u *perm = NULL;
11033 char_u flags[] = "rwx";
11034 int i;
11036 fname = get_tv_string(&argvars[0]);
11038 rettv->v_type = VAR_STRING;
11039 if (mch_stat((char *)fname, &st) >= 0)
11041 perm = vim_strsave((char_u *)"---------");
11042 if (perm != NULL)
11044 for (i = 0; i < 9; i++)
11046 if (st.st_mode & (1 << (8 - i)))
11047 perm[i] = flags[i % 3];
11051 rettv->vval.v_string = perm;
11055 * "getfsize({fname})" function
11057 static void
11058 f_getfsize(argvars, rettv)
11059 typval_T *argvars;
11060 typval_T *rettv;
11062 char_u *fname;
11063 struct stat st;
11065 fname = get_tv_string(&argvars[0]);
11067 rettv->v_type = VAR_NUMBER;
11069 if (mch_stat((char *)fname, &st) >= 0)
11071 if (mch_isdir(fname))
11072 rettv->vval.v_number = 0;
11073 else
11075 rettv->vval.v_number = (varnumber_T)st.st_size;
11077 /* non-perfect check for overflow */
11078 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
11079 rettv->vval.v_number = -2;
11082 else
11083 rettv->vval.v_number = -1;
11087 * "getftime({fname})" function
11089 static void
11090 f_getftime(argvars, rettv)
11091 typval_T *argvars;
11092 typval_T *rettv;
11094 char_u *fname;
11095 struct stat st;
11097 fname = get_tv_string(&argvars[0]);
11099 if (mch_stat((char *)fname, &st) >= 0)
11100 rettv->vval.v_number = (varnumber_T)st.st_mtime;
11101 else
11102 rettv->vval.v_number = -1;
11106 * "getftype({fname})" function
11108 static void
11109 f_getftype(argvars, rettv)
11110 typval_T *argvars;
11111 typval_T *rettv;
11113 char_u *fname;
11114 struct stat st;
11115 char_u *type = NULL;
11116 char *t;
11118 fname = get_tv_string(&argvars[0]);
11120 rettv->v_type = VAR_STRING;
11121 if (mch_lstat((char *)fname, &st) >= 0)
11123 #ifdef S_ISREG
11124 if (S_ISREG(st.st_mode))
11125 t = "file";
11126 else if (S_ISDIR(st.st_mode))
11127 t = "dir";
11128 # ifdef S_ISLNK
11129 else if (S_ISLNK(st.st_mode))
11130 t = "link";
11131 # endif
11132 # ifdef S_ISBLK
11133 else if (S_ISBLK(st.st_mode))
11134 t = "bdev";
11135 # endif
11136 # ifdef S_ISCHR
11137 else if (S_ISCHR(st.st_mode))
11138 t = "cdev";
11139 # endif
11140 # ifdef S_ISFIFO
11141 else if (S_ISFIFO(st.st_mode))
11142 t = "fifo";
11143 # endif
11144 # ifdef S_ISSOCK
11145 else if (S_ISSOCK(st.st_mode))
11146 t = "fifo";
11147 # endif
11148 else
11149 t = "other";
11150 #else
11151 # ifdef S_IFMT
11152 switch (st.st_mode & S_IFMT)
11154 case S_IFREG: t = "file"; break;
11155 case S_IFDIR: t = "dir"; break;
11156 # ifdef S_IFLNK
11157 case S_IFLNK: t = "link"; break;
11158 # endif
11159 # ifdef S_IFBLK
11160 case S_IFBLK: t = "bdev"; break;
11161 # endif
11162 # ifdef S_IFCHR
11163 case S_IFCHR: t = "cdev"; break;
11164 # endif
11165 # ifdef S_IFIFO
11166 case S_IFIFO: t = "fifo"; break;
11167 # endif
11168 # ifdef S_IFSOCK
11169 case S_IFSOCK: t = "socket"; break;
11170 # endif
11171 default: t = "other";
11173 # else
11174 if (mch_isdir(fname))
11175 t = "dir";
11176 else
11177 t = "file";
11178 # endif
11179 #endif
11180 type = vim_strsave((char_u *)t);
11182 rettv->vval.v_string = type;
11186 * "getline(lnum, [end])" function
11188 static void
11189 f_getline(argvars, rettv)
11190 typval_T *argvars;
11191 typval_T *rettv;
11193 linenr_T lnum;
11194 linenr_T end;
11195 int retlist;
11197 lnum = get_tv_lnum(argvars);
11198 if (argvars[1].v_type == VAR_UNKNOWN)
11200 end = 0;
11201 retlist = FALSE;
11203 else
11205 end = get_tv_lnum(&argvars[1]);
11206 retlist = TRUE;
11209 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
11213 * "getmatches()" function
11215 static void
11216 f_getmatches(argvars, rettv)
11217 typval_T *argvars UNUSED;
11218 typval_T *rettv;
11220 #ifdef FEAT_SEARCH_EXTRA
11221 dict_T *dict;
11222 matchitem_T *cur = curwin->w_match_head;
11224 if (rettv_list_alloc(rettv) == OK)
11226 while (cur != NULL)
11228 dict = dict_alloc();
11229 if (dict == NULL)
11230 return;
11231 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
11232 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
11233 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
11234 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
11235 list_append_dict(rettv->vval.v_list, dict);
11236 cur = cur->next;
11239 #endif
11243 * "getpid()" function
11245 static void
11246 f_getpid(argvars, rettv)
11247 typval_T *argvars UNUSED;
11248 typval_T *rettv;
11250 rettv->vval.v_number = mch_get_pid();
11254 * "getpos(string)" function
11256 static void
11257 f_getpos(argvars, rettv)
11258 typval_T *argvars;
11259 typval_T *rettv;
11261 pos_T *fp;
11262 list_T *l;
11263 int fnum = -1;
11265 if (rettv_list_alloc(rettv) == OK)
11267 l = rettv->vval.v_list;
11268 fp = var2fpos(&argvars[0], TRUE, &fnum);
11269 if (fnum != -1)
11270 list_append_number(l, (varnumber_T)fnum);
11271 else
11272 list_append_number(l, (varnumber_T)0);
11273 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
11274 : (varnumber_T)0);
11275 list_append_number(l, (fp != NULL)
11276 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
11277 : (varnumber_T)0);
11278 list_append_number(l,
11279 #ifdef FEAT_VIRTUALEDIT
11280 (fp != NULL) ? (varnumber_T)fp->coladd :
11281 #endif
11282 (varnumber_T)0);
11284 else
11285 rettv->vval.v_number = FALSE;
11289 * "getqflist()" and "getloclist()" functions
11291 static void
11292 f_getqflist(argvars, rettv)
11293 typval_T *argvars UNUSED;
11294 typval_T *rettv UNUSED;
11296 #ifdef FEAT_QUICKFIX
11297 win_T *wp;
11298 #endif
11300 #ifdef FEAT_QUICKFIX
11301 if (rettv_list_alloc(rettv) == OK)
11303 wp = NULL;
11304 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
11306 wp = find_win_by_nr(&argvars[0], NULL);
11307 if (wp == NULL)
11308 return;
11311 (void)get_errorlist(wp, rettv->vval.v_list);
11313 #endif
11317 * "getreg()" function
11319 static void
11320 f_getreg(argvars, rettv)
11321 typval_T *argvars;
11322 typval_T *rettv;
11324 char_u *strregname;
11325 int regname;
11326 int arg2 = FALSE;
11327 int error = FALSE;
11329 if (argvars[0].v_type != VAR_UNKNOWN)
11331 strregname = get_tv_string_chk(&argvars[0]);
11332 error = strregname == NULL;
11333 if (argvars[1].v_type != VAR_UNKNOWN)
11334 arg2 = get_tv_number_chk(&argvars[1], &error);
11336 else
11337 strregname = vimvars[VV_REG].vv_str;
11338 regname = (strregname == NULL ? '"' : *strregname);
11339 if (regname == 0)
11340 regname = '"';
11342 rettv->v_type = VAR_STRING;
11343 rettv->vval.v_string = error ? NULL :
11344 get_reg_contents(regname, TRUE, arg2);
11348 * "getregtype()" function
11350 static void
11351 f_getregtype(argvars, rettv)
11352 typval_T *argvars;
11353 typval_T *rettv;
11355 char_u *strregname;
11356 int regname;
11357 char_u buf[NUMBUFLEN + 2];
11358 long reglen = 0;
11360 if (argvars[0].v_type != VAR_UNKNOWN)
11362 strregname = get_tv_string_chk(&argvars[0]);
11363 if (strregname == NULL) /* type error; errmsg already given */
11365 rettv->v_type = VAR_STRING;
11366 rettv->vval.v_string = NULL;
11367 return;
11370 else
11371 /* Default to v:register */
11372 strregname = vimvars[VV_REG].vv_str;
11374 regname = (strregname == NULL ? '"' : *strregname);
11375 if (regname == 0)
11376 regname = '"';
11378 buf[0] = NUL;
11379 buf[1] = NUL;
11380 switch (get_reg_type(regname, &reglen))
11382 case MLINE: buf[0] = 'V'; break;
11383 case MCHAR: buf[0] = 'v'; break;
11384 #ifdef FEAT_VISUAL
11385 case MBLOCK:
11386 buf[0] = Ctrl_V;
11387 sprintf((char *)buf + 1, "%ld", reglen + 1);
11388 break;
11389 #endif
11391 rettv->v_type = VAR_STRING;
11392 rettv->vval.v_string = vim_strsave(buf);
11396 * "gettabwinvar()" function
11398 static void
11399 f_gettabwinvar(argvars, rettv)
11400 typval_T *argvars;
11401 typval_T *rettv;
11403 getwinvar(argvars, rettv, 1);
11407 * "getwinposx()" function
11409 static void
11410 f_getwinposx(argvars, rettv)
11411 typval_T *argvars UNUSED;
11412 typval_T *rettv;
11414 rettv->vval.v_number = -1;
11415 #ifdef FEAT_GUI
11416 if (gui.in_use)
11418 int x, y;
11420 if (gui_mch_get_winpos(&x, &y) == OK)
11421 rettv->vval.v_number = x;
11423 #endif
11427 * "getwinposy()" function
11429 static void
11430 f_getwinposy(argvars, rettv)
11431 typval_T *argvars UNUSED;
11432 typval_T *rettv;
11434 rettv->vval.v_number = -1;
11435 #ifdef FEAT_GUI
11436 if (gui.in_use)
11438 int x, y;
11440 if (gui_mch_get_winpos(&x, &y) == OK)
11441 rettv->vval.v_number = y;
11443 #endif
11447 * Find window specified by "vp" in tabpage "tp".
11449 static win_T *
11450 find_win_by_nr(vp, tp)
11451 typval_T *vp;
11452 tabpage_T *tp; /* NULL for current tab page */
11454 #ifdef FEAT_WINDOWS
11455 win_T *wp;
11456 #endif
11457 int nr;
11459 nr = get_tv_number_chk(vp, NULL);
11461 #ifdef FEAT_WINDOWS
11462 if (nr < 0)
11463 return NULL;
11464 if (nr == 0)
11465 return curwin;
11467 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
11468 wp != NULL; wp = wp->w_next)
11469 if (--nr <= 0)
11470 break;
11471 return wp;
11472 #else
11473 if (nr == 0 || nr == 1)
11474 return curwin;
11475 return NULL;
11476 #endif
11480 * "getwinvar()" function
11482 static void
11483 f_getwinvar(argvars, rettv)
11484 typval_T *argvars;
11485 typval_T *rettv;
11487 getwinvar(argvars, rettv, 0);
11491 * getwinvar() and gettabwinvar()
11493 static void
11494 getwinvar(argvars, rettv, off)
11495 typval_T *argvars;
11496 typval_T *rettv;
11497 int off; /* 1 for gettabwinvar() */
11499 win_T *win, *oldcurwin;
11500 char_u *varname;
11501 dictitem_T *v;
11502 tabpage_T *tp;
11504 #ifdef FEAT_WINDOWS
11505 if (off == 1)
11506 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
11507 else
11508 tp = curtab;
11509 #endif
11510 win = find_win_by_nr(&argvars[off], tp);
11511 varname = get_tv_string_chk(&argvars[off + 1]);
11512 ++emsg_off;
11514 rettv->v_type = VAR_STRING;
11515 rettv->vval.v_string = NULL;
11517 if (win != NULL && varname != NULL)
11519 /* Set curwin to be our win, temporarily. Also set curbuf, so
11520 * that we can get buffer-local options. */
11521 oldcurwin = curwin;
11522 curwin = win;
11523 curbuf = win->w_buffer;
11525 if (*varname == '&') /* window-local-option */
11526 get_option_tv(&varname, rettv, 1);
11527 else
11529 if (*varname == NUL)
11530 /* let getwinvar({nr}, "") return the "w:" dictionary. The
11531 * scope prefix before the NUL byte is required by
11532 * find_var_in_ht(). */
11533 varname = (char_u *)"w:" + 2;
11534 /* look up the variable */
11535 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
11536 if (v != NULL)
11537 copy_tv(&v->di_tv, rettv);
11540 /* restore previous notion of curwin */
11541 curwin = oldcurwin;
11542 curbuf = curwin->w_buffer;
11545 --emsg_off;
11549 * "glob()" function
11551 static void
11552 f_glob(argvars, rettv)
11553 typval_T *argvars;
11554 typval_T *rettv;
11556 int flags = WILD_SILENT|WILD_USE_NL;
11557 expand_T xpc;
11558 int error = FALSE;
11560 /* When the optional second argument is non-zero, don't remove matches
11561 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11562 if (argvars[1].v_type != VAR_UNKNOWN
11563 && get_tv_number_chk(&argvars[1], &error))
11564 flags |= WILD_KEEP_ALL;
11565 rettv->v_type = VAR_STRING;
11566 if (!error)
11568 ExpandInit(&xpc);
11569 xpc.xp_context = EXPAND_FILES;
11570 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
11571 NULL, flags, WILD_ALL);
11573 else
11574 rettv->vval.v_string = NULL;
11578 * "globpath()" function
11580 static void
11581 f_globpath(argvars, rettv)
11582 typval_T *argvars;
11583 typval_T *rettv;
11585 int flags = 0;
11586 char_u buf1[NUMBUFLEN];
11587 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
11588 int error = FALSE;
11590 /* When the optional second argument is non-zero, don't remove matches
11591 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11592 if (argvars[2].v_type != VAR_UNKNOWN
11593 && get_tv_number_chk(&argvars[2], &error))
11594 flags |= WILD_KEEP_ALL;
11595 rettv->v_type = VAR_STRING;
11596 if (file == NULL || error)
11597 rettv->vval.v_string = NULL;
11598 else
11599 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file,
11600 flags);
11604 * "has()" function
11606 static void
11607 f_has(argvars, rettv)
11608 typval_T *argvars;
11609 typval_T *rettv;
11611 int i;
11612 char_u *name;
11613 int n = FALSE;
11614 static char *(has_list[]) =
11616 #ifdef AMIGA
11617 "amiga",
11618 # ifdef FEAT_ARP
11619 "arp",
11620 # endif
11621 #endif
11622 #ifdef __BEOS__
11623 "beos",
11624 #endif
11625 #ifdef MSDOS
11626 # ifdef DJGPP
11627 "dos32",
11628 # else
11629 "dos16",
11630 # endif
11631 #endif
11632 #ifdef MACOS
11633 "mac",
11634 #endif
11635 #if defined(MACOS_X_UNIX)
11636 "macunix",
11637 #endif
11638 #ifdef OS2
11639 "os2",
11640 #endif
11641 #ifdef __QNX__
11642 "qnx",
11643 #endif
11644 #ifdef RISCOS
11645 "riscos",
11646 #endif
11647 #ifdef UNIX
11648 "unix",
11649 #endif
11650 #ifdef VMS
11651 "vms",
11652 #endif
11653 #ifdef WIN16
11654 "win16",
11655 #endif
11656 #ifdef WIN32
11657 "win32",
11658 #endif
11659 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
11660 "win32unix",
11661 #endif
11662 #if defined(WIN64) || defined(_WIN64)
11663 "win64",
11664 #endif
11665 #ifdef EBCDIC
11666 "ebcdic",
11667 #endif
11668 #ifndef CASE_INSENSITIVE_FILENAME
11669 "fname_case",
11670 #endif
11671 #ifdef FEAT_ARABIC
11672 "arabic",
11673 #endif
11674 #ifdef FEAT_AUTOCMD
11675 "autocmd",
11676 #endif
11677 #ifdef FEAT_BEVAL
11678 "balloon_eval",
11679 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
11680 "balloon_multiline",
11681 # endif
11682 #endif
11683 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
11684 "builtin_terms",
11685 # ifdef ALL_BUILTIN_TCAPS
11686 "all_builtin_terms",
11687 # endif
11688 #endif
11689 #ifdef FEAT_BYTEOFF
11690 "byte_offset",
11691 #endif
11692 #ifdef FEAT_CINDENT
11693 "cindent",
11694 #endif
11695 #ifdef FEAT_CLIENTSERVER
11696 "clientserver",
11697 #endif
11698 #ifdef FEAT_CLIPBOARD
11699 "clipboard",
11700 #endif
11701 #ifdef FEAT_CMDL_COMPL
11702 "cmdline_compl",
11703 #endif
11704 #ifdef FEAT_CMDHIST
11705 "cmdline_hist",
11706 #endif
11707 #ifdef FEAT_COMMENTS
11708 "comments",
11709 #endif
11710 #ifdef FEAT_CRYPT
11711 "cryptv",
11712 #endif
11713 #ifdef FEAT_CSCOPE
11714 "cscope",
11715 #endif
11716 #ifdef CURSOR_SHAPE
11717 "cursorshape",
11718 #endif
11719 #ifdef DEBUG
11720 "debug",
11721 #endif
11722 #ifdef FEAT_CON_DIALOG
11723 "dialog_con",
11724 #endif
11725 #ifdef FEAT_GUI_DIALOG
11726 "dialog_gui",
11727 #endif
11728 #ifdef FEAT_DIFF
11729 "diff",
11730 #endif
11731 #ifdef FEAT_DIGRAPHS
11732 "digraphs",
11733 #endif
11734 #ifdef FEAT_DND
11735 "dnd",
11736 #endif
11737 #ifdef FEAT_EMACS_TAGS
11738 "emacs_tags",
11739 #endif
11740 "eval", /* always present, of course! */
11741 #ifdef FEAT_EX_EXTRA
11742 "ex_extra",
11743 #endif
11744 #ifdef FEAT_SEARCH_EXTRA
11745 "extra_search",
11746 #endif
11747 #ifdef FEAT_FKMAP
11748 "farsi",
11749 #endif
11750 #ifdef FEAT_SEARCHPATH
11751 "file_in_path",
11752 #endif
11753 #if defined(UNIX) && !defined(USE_SYSTEM)
11754 "filterpipe",
11755 #endif
11756 #ifdef FEAT_FIND_ID
11757 "find_in_path",
11758 #endif
11759 #ifdef FEAT_FLOAT
11760 "float",
11761 #endif
11762 #ifdef FEAT_FOLDING
11763 "folding",
11764 #endif
11765 #ifdef FEAT_FOOTER
11766 "footer",
11767 #endif
11768 #if !defined(USE_SYSTEM) && defined(UNIX)
11769 "fork",
11770 #endif
11771 #ifdef FEAT_GETTEXT
11772 "gettext",
11773 #endif
11774 #ifdef FEAT_GUI
11775 "gui",
11776 #endif
11777 #ifdef FEAT_GUI_ATHENA
11778 # ifdef FEAT_GUI_NEXTAW
11779 "gui_neXtaw",
11780 # else
11781 "gui_athena",
11782 # endif
11783 #endif
11784 #ifdef FEAT_GUI_GTK
11785 "gui_gtk",
11786 # ifdef HAVE_GTK2
11787 "gui_gtk2",
11788 # endif
11789 #endif
11790 #ifdef FEAT_GUI_GNOME
11791 "gui_gnome",
11792 #endif
11793 #ifdef FEAT_GUI_MAC
11794 "gui_mac",
11795 #endif
11796 #ifdef FEAT_GUI_MOTIF
11797 "gui_motif",
11798 #endif
11799 #ifdef FEAT_GUI_PHOTON
11800 "gui_photon",
11801 #endif
11802 #ifdef FEAT_GUI_W16
11803 "gui_win16",
11804 #endif
11805 #ifdef FEAT_GUI_W32
11806 "gui_win32",
11807 #endif
11808 #ifdef FEAT_HANGULIN
11809 "hangul_input",
11810 #endif
11811 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
11812 "iconv",
11813 #endif
11814 #ifdef FEAT_INS_EXPAND
11815 "insert_expand",
11816 #endif
11817 #ifdef FEAT_JUMPLIST
11818 "jumplist",
11819 #endif
11820 #ifdef FEAT_KEYMAP
11821 "keymap",
11822 #endif
11823 #ifdef FEAT_LANGMAP
11824 "langmap",
11825 #endif
11826 #ifdef FEAT_LIBCALL
11827 "libcall",
11828 #endif
11829 #ifdef FEAT_LINEBREAK
11830 "linebreak",
11831 #endif
11832 #ifdef FEAT_LISP
11833 "lispindent",
11834 #endif
11835 #ifdef FEAT_LISTCMDS
11836 "listcmds",
11837 #endif
11838 #ifdef FEAT_LOCALMAP
11839 "localmap",
11840 #endif
11841 #ifdef FEAT_MENU
11842 "menu",
11843 #endif
11844 #ifdef FEAT_SESSION
11845 "mksession",
11846 #endif
11847 #ifdef FEAT_MODIFY_FNAME
11848 "modify_fname",
11849 #endif
11850 #ifdef FEAT_MOUSE
11851 "mouse",
11852 #endif
11853 #ifdef FEAT_MOUSESHAPE
11854 "mouseshape",
11855 #endif
11856 #if defined(UNIX) || defined(VMS)
11857 # ifdef FEAT_MOUSE_DEC
11858 "mouse_dec",
11859 # endif
11860 # ifdef FEAT_MOUSE_GPM
11861 "mouse_gpm",
11862 # endif
11863 # ifdef FEAT_MOUSE_JSB
11864 "mouse_jsbterm",
11865 # endif
11866 # ifdef FEAT_MOUSE_NET
11867 "mouse_netterm",
11868 # endif
11869 # ifdef FEAT_MOUSE_PTERM
11870 "mouse_pterm",
11871 # endif
11872 # ifdef FEAT_SYSMOUSE
11873 "mouse_sysmouse",
11874 # endif
11875 # ifdef FEAT_MOUSE_XTERM
11876 "mouse_xterm",
11877 # endif
11878 #endif
11879 #ifdef FEAT_MBYTE
11880 "multi_byte",
11881 #endif
11882 #ifdef FEAT_MBYTE_IME
11883 "multi_byte_ime",
11884 #endif
11885 #ifdef FEAT_MULTI_LANG
11886 "multi_lang",
11887 #endif
11888 #ifdef FEAT_MZSCHEME
11889 #ifndef DYNAMIC_MZSCHEME
11890 "mzscheme",
11891 #endif
11892 #endif
11893 #ifdef FEAT_OLE
11894 "ole",
11895 #endif
11896 #ifdef FEAT_OSFILETYPE
11897 "osfiletype",
11898 #endif
11899 #ifdef FEAT_PATH_EXTRA
11900 "path_extra",
11901 #endif
11902 #ifdef FEAT_PERL
11903 #ifndef DYNAMIC_PERL
11904 "perl",
11905 #endif
11906 #endif
11907 #ifdef FEAT_PYTHON
11908 #ifndef DYNAMIC_PYTHON
11909 "python",
11910 #endif
11911 #endif
11912 #ifdef FEAT_POSTSCRIPT
11913 "postscript",
11914 #endif
11915 #ifdef FEAT_PRINTER
11916 "printer",
11917 #endif
11918 #ifdef FEAT_PROFILE
11919 "profile",
11920 #endif
11921 #ifdef FEAT_RELTIME
11922 "reltime",
11923 #endif
11924 #ifdef FEAT_QUICKFIX
11925 "quickfix",
11926 #endif
11927 #ifdef FEAT_RIGHTLEFT
11928 "rightleft",
11929 #endif
11930 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11931 "ruby",
11932 #endif
11933 #ifdef FEAT_SCROLLBIND
11934 "scrollbind",
11935 #endif
11936 #ifdef FEAT_CMDL_INFO
11937 "showcmd",
11938 "cmdline_info",
11939 #endif
11940 #ifdef FEAT_SIGNS
11941 "signs",
11942 #endif
11943 #ifdef FEAT_SMARTINDENT
11944 "smartindent",
11945 #endif
11946 #ifdef FEAT_SNIFF
11947 "sniff",
11948 #endif
11949 #ifdef STARTUPTIME
11950 "startuptime",
11951 #endif
11952 #ifdef FEAT_STL_OPT
11953 "statusline",
11954 #endif
11955 #ifdef FEAT_SUN_WORKSHOP
11956 "sun_workshop",
11957 #endif
11958 #ifdef FEAT_NETBEANS_INTG
11959 "netbeans_intg",
11960 #endif
11961 #ifdef FEAT_SPELL
11962 "spell",
11963 #endif
11964 #ifdef FEAT_SYN_HL
11965 "syntax",
11966 #endif
11967 #if defined(USE_SYSTEM) || !defined(UNIX)
11968 "system",
11969 #endif
11970 #ifdef FEAT_TAG_BINS
11971 "tag_binary",
11972 #endif
11973 #ifdef FEAT_TAG_OLDSTATIC
11974 "tag_old_static",
11975 #endif
11976 #ifdef FEAT_TAG_ANYWHITE
11977 "tag_any_white",
11978 #endif
11979 #ifdef FEAT_TCL
11980 # ifndef DYNAMIC_TCL
11981 "tcl",
11982 # endif
11983 #endif
11984 #ifdef TERMINFO
11985 "terminfo",
11986 #endif
11987 #ifdef FEAT_TERMRESPONSE
11988 "termresponse",
11989 #endif
11990 #ifdef FEAT_TEXTOBJ
11991 "textobjects",
11992 #endif
11993 #ifdef HAVE_TGETENT
11994 "tgetent",
11995 #endif
11996 #ifdef FEAT_TITLE
11997 "title",
11998 #endif
11999 #ifdef FEAT_TOOLBAR
12000 "toolbar",
12001 #endif
12002 #ifdef FEAT_USR_CMDS
12003 "user-commands", /* was accidentally included in 5.4 */
12004 "user_commands",
12005 #endif
12006 #ifdef FEAT_VIMINFO
12007 "viminfo",
12008 #endif
12009 #ifdef FEAT_VERTSPLIT
12010 "vertsplit",
12011 #endif
12012 #ifdef FEAT_VIRTUALEDIT
12013 "virtualedit",
12014 #endif
12015 #ifdef FEAT_VISUAL
12016 "visual",
12017 #endif
12018 #ifdef FEAT_VISUALEXTRA
12019 "visualextra",
12020 #endif
12021 #ifdef FEAT_VREPLACE
12022 "vreplace",
12023 #endif
12024 #ifdef FEAT_WILDIGN
12025 "wildignore",
12026 #endif
12027 #ifdef FEAT_WILDMENU
12028 "wildmenu",
12029 #endif
12030 #ifdef FEAT_WINDOWS
12031 "windows",
12032 #endif
12033 #ifdef FEAT_WAK
12034 "winaltkeys",
12035 #endif
12036 #ifdef FEAT_WRITEBACKUP
12037 "writebackup",
12038 #endif
12039 #ifdef FEAT_XIM
12040 "xim",
12041 #endif
12042 #ifdef FEAT_XFONTSET
12043 "xfontset",
12044 #endif
12045 #ifdef USE_XSMP
12046 "xsmp",
12047 #endif
12048 #ifdef USE_XSMP_INTERACT
12049 "xsmp_interact",
12050 #endif
12051 #ifdef FEAT_XCLIPBOARD
12052 "xterm_clipboard",
12053 #endif
12054 #ifdef FEAT_XTERM_SAVE
12055 "xterm_save",
12056 #endif
12057 #if defined(UNIX) && defined(FEAT_X11)
12058 "X11",
12059 #endif
12060 NULL
12063 name = get_tv_string(&argvars[0]);
12064 for (i = 0; has_list[i] != NULL; ++i)
12065 if (STRICMP(name, has_list[i]) == 0)
12067 n = TRUE;
12068 break;
12071 if (n == FALSE)
12073 if (STRNICMP(name, "patch", 5) == 0)
12074 n = has_patch(atoi((char *)name + 5));
12075 else if (STRICMP(name, "vim_starting") == 0)
12076 n = (starting != 0);
12077 #ifdef FEAT_MBYTE
12078 else if (STRICMP(name, "multi_byte_encoding") == 0)
12079 n = has_mbyte;
12080 #endif
12081 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
12082 else if (STRICMP(name, "balloon_multiline") == 0)
12083 n = multiline_balloon_available();
12084 #endif
12085 #ifdef DYNAMIC_TCL
12086 else if (STRICMP(name, "tcl") == 0)
12087 n = tcl_enabled(FALSE);
12088 #endif
12089 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
12090 else if (STRICMP(name, "iconv") == 0)
12091 n = iconv_enabled(FALSE);
12092 #endif
12093 #ifdef DYNAMIC_MZSCHEME
12094 else if (STRICMP(name, "mzscheme") == 0)
12095 n = mzscheme_enabled(FALSE);
12096 #endif
12097 #ifdef DYNAMIC_RUBY
12098 else if (STRICMP(name, "ruby") == 0)
12099 n = ruby_enabled(FALSE);
12100 #endif
12101 #ifdef DYNAMIC_PYTHON
12102 else if (STRICMP(name, "python") == 0)
12103 n = python_enabled(FALSE);
12104 #endif
12105 #ifdef DYNAMIC_PERL
12106 else if (STRICMP(name, "perl") == 0)
12107 n = perl_enabled(FALSE);
12108 #endif
12109 #ifdef FEAT_GUI
12110 else if (STRICMP(name, "gui_running") == 0)
12111 n = (gui.in_use || gui.starting);
12112 # ifdef FEAT_GUI_W32
12113 else if (STRICMP(name, "gui_win32s") == 0)
12114 n = gui_is_win32s();
12115 # endif
12116 # ifdef FEAT_BROWSE
12117 else if (STRICMP(name, "browse") == 0)
12118 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
12119 # endif
12120 #endif
12121 #ifdef FEAT_SYN_HL
12122 else if (STRICMP(name, "syntax_items") == 0)
12123 n = syntax_present(curbuf);
12124 #endif
12125 #if defined(WIN3264)
12126 else if (STRICMP(name, "win95") == 0)
12127 n = mch_windows95();
12128 #endif
12129 #ifdef FEAT_NETBEANS_INTG
12130 else if (STRICMP(name, "netbeans_enabled") == 0)
12131 n = usingNetbeans;
12132 #endif
12135 rettv->vval.v_number = n;
12139 * "has_key()" function
12141 static void
12142 f_has_key(argvars, rettv)
12143 typval_T *argvars;
12144 typval_T *rettv;
12146 if (argvars[0].v_type != VAR_DICT)
12148 EMSG(_(e_dictreq));
12149 return;
12151 if (argvars[0].vval.v_dict == NULL)
12152 return;
12154 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
12155 get_tv_string(&argvars[1]), -1) != NULL;
12159 * "haslocaldir()" function
12161 static void
12162 f_haslocaldir(argvars, rettv)
12163 typval_T *argvars UNUSED;
12164 typval_T *rettv;
12166 rettv->vval.v_number = (curwin->w_localdir != NULL);
12170 * "hasmapto()" function
12172 static void
12173 f_hasmapto(argvars, rettv)
12174 typval_T *argvars;
12175 typval_T *rettv;
12177 char_u *name;
12178 char_u *mode;
12179 char_u buf[NUMBUFLEN];
12180 int abbr = FALSE;
12182 name = get_tv_string(&argvars[0]);
12183 if (argvars[1].v_type == VAR_UNKNOWN)
12184 mode = (char_u *)"nvo";
12185 else
12187 mode = get_tv_string_buf(&argvars[1], buf);
12188 if (argvars[2].v_type != VAR_UNKNOWN)
12189 abbr = get_tv_number(&argvars[2]);
12192 if (map_to_exists(name, mode, abbr))
12193 rettv->vval.v_number = TRUE;
12194 else
12195 rettv->vval.v_number = FALSE;
12199 * "histadd()" function
12201 static void
12202 f_histadd(argvars, rettv)
12203 typval_T *argvars UNUSED;
12204 typval_T *rettv;
12206 #ifdef FEAT_CMDHIST
12207 int histype;
12208 char_u *str;
12209 char_u buf[NUMBUFLEN];
12210 #endif
12212 rettv->vval.v_number = FALSE;
12213 if (check_restricted() || check_secure())
12214 return;
12215 #ifdef FEAT_CMDHIST
12216 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12217 histype = str != NULL ? get_histtype(str) : -1;
12218 if (histype >= 0)
12220 str = get_tv_string_buf(&argvars[1], buf);
12221 if (*str != NUL)
12223 init_history();
12224 add_to_history(histype, str, FALSE, NUL);
12225 rettv->vval.v_number = TRUE;
12226 return;
12229 #endif
12233 * "histdel()" function
12235 static void
12236 f_histdel(argvars, rettv)
12237 typval_T *argvars UNUSED;
12238 typval_T *rettv UNUSED;
12240 #ifdef FEAT_CMDHIST
12241 int n;
12242 char_u buf[NUMBUFLEN];
12243 char_u *str;
12245 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12246 if (str == NULL)
12247 n = 0;
12248 else if (argvars[1].v_type == VAR_UNKNOWN)
12249 /* only one argument: clear entire history */
12250 n = clr_history(get_histtype(str));
12251 else if (argvars[1].v_type == VAR_NUMBER)
12252 /* index given: remove that entry */
12253 n = del_history_idx(get_histtype(str),
12254 (int)get_tv_number(&argvars[1]));
12255 else
12256 /* string given: remove all matching entries */
12257 n = del_history_entry(get_histtype(str),
12258 get_tv_string_buf(&argvars[1], buf));
12259 rettv->vval.v_number = n;
12260 #endif
12264 * "histget()" function
12266 static void
12267 f_histget(argvars, rettv)
12268 typval_T *argvars UNUSED;
12269 typval_T *rettv;
12271 #ifdef FEAT_CMDHIST
12272 int type;
12273 int idx;
12274 char_u *str;
12276 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12277 if (str == NULL)
12278 rettv->vval.v_string = NULL;
12279 else
12281 type = get_histtype(str);
12282 if (argvars[1].v_type == VAR_UNKNOWN)
12283 idx = get_history_idx(type);
12284 else
12285 idx = (int)get_tv_number_chk(&argvars[1], NULL);
12286 /* -1 on type error */
12287 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
12289 #else
12290 rettv->vval.v_string = NULL;
12291 #endif
12292 rettv->v_type = VAR_STRING;
12296 * "histnr()" function
12298 static void
12299 f_histnr(argvars, rettv)
12300 typval_T *argvars UNUSED;
12301 typval_T *rettv;
12303 int i;
12305 #ifdef FEAT_CMDHIST
12306 char_u *history = get_tv_string_chk(&argvars[0]);
12308 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
12309 if (i >= HIST_CMD && i < HIST_COUNT)
12310 i = get_history_idx(i);
12311 else
12312 #endif
12313 i = -1;
12314 rettv->vval.v_number = i;
12318 * "highlightID(name)" function
12320 static void
12321 f_hlID(argvars, rettv)
12322 typval_T *argvars;
12323 typval_T *rettv;
12325 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
12329 * "highlight_exists()" function
12331 static void
12332 f_hlexists(argvars, rettv)
12333 typval_T *argvars;
12334 typval_T *rettv;
12336 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
12340 * "hostname()" function
12342 static void
12343 f_hostname(argvars, rettv)
12344 typval_T *argvars UNUSED;
12345 typval_T *rettv;
12347 char_u hostname[256];
12349 mch_get_host_name(hostname, 256);
12350 rettv->v_type = VAR_STRING;
12351 rettv->vval.v_string = vim_strsave(hostname);
12355 * iconv() function
12357 static void
12358 f_iconv(argvars, rettv)
12359 typval_T *argvars UNUSED;
12360 typval_T *rettv;
12362 #ifdef FEAT_MBYTE
12363 char_u buf1[NUMBUFLEN];
12364 char_u buf2[NUMBUFLEN];
12365 char_u *from, *to, *str;
12366 vimconv_T vimconv;
12367 #endif
12369 rettv->v_type = VAR_STRING;
12370 rettv->vval.v_string = NULL;
12372 #ifdef FEAT_MBYTE
12373 str = get_tv_string(&argvars[0]);
12374 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
12375 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
12376 vimconv.vc_type = CONV_NONE;
12377 convert_setup(&vimconv, from, to);
12379 /* If the encodings are equal, no conversion needed. */
12380 if (vimconv.vc_type == CONV_NONE)
12381 rettv->vval.v_string = vim_strsave(str);
12382 else
12383 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
12385 convert_setup(&vimconv, NULL, NULL);
12386 vim_free(from);
12387 vim_free(to);
12388 #endif
12392 * "indent()" function
12394 static void
12395 f_indent(argvars, rettv)
12396 typval_T *argvars;
12397 typval_T *rettv;
12399 linenr_T lnum;
12401 lnum = get_tv_lnum(argvars);
12402 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12403 rettv->vval.v_number = get_indent_lnum(lnum);
12404 else
12405 rettv->vval.v_number = -1;
12409 * "index()" function
12411 static void
12412 f_index(argvars, rettv)
12413 typval_T *argvars;
12414 typval_T *rettv;
12416 list_T *l;
12417 listitem_T *item;
12418 long idx = 0;
12419 int ic = FALSE;
12421 rettv->vval.v_number = -1;
12422 if (argvars[0].v_type != VAR_LIST)
12424 EMSG(_(e_listreq));
12425 return;
12427 l = argvars[0].vval.v_list;
12428 if (l != NULL)
12430 item = l->lv_first;
12431 if (argvars[2].v_type != VAR_UNKNOWN)
12433 int error = FALSE;
12435 /* Start at specified item. Use the cached index that list_find()
12436 * sets, so that a negative number also works. */
12437 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
12438 idx = l->lv_idx;
12439 if (argvars[3].v_type != VAR_UNKNOWN)
12440 ic = get_tv_number_chk(&argvars[3], &error);
12441 if (error)
12442 item = NULL;
12445 for ( ; item != NULL; item = item->li_next, ++idx)
12446 if (tv_equal(&item->li_tv, &argvars[1], ic))
12448 rettv->vval.v_number = idx;
12449 break;
12454 static int inputsecret_flag = 0;
12456 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
12459 * This function is used by f_input() and f_inputdialog() functions. The third
12460 * argument to f_input() specifies the type of completion to use at the
12461 * prompt. The third argument to f_inputdialog() specifies the value to return
12462 * when the user cancels the prompt.
12464 static void
12465 get_user_input(argvars, rettv, inputdialog)
12466 typval_T *argvars;
12467 typval_T *rettv;
12468 int inputdialog;
12470 char_u *prompt = get_tv_string_chk(&argvars[0]);
12471 char_u *p = NULL;
12472 int c;
12473 char_u buf[NUMBUFLEN];
12474 int cmd_silent_save = cmd_silent;
12475 char_u *defstr = (char_u *)"";
12476 int xp_type = EXPAND_NOTHING;
12477 char_u *xp_arg = NULL;
12479 rettv->v_type = VAR_STRING;
12480 rettv->vval.v_string = NULL;
12482 #ifdef NO_CONSOLE_INPUT
12483 /* While starting up, there is no place to enter text. */
12484 if (no_console_input())
12485 return;
12486 #endif
12488 cmd_silent = FALSE; /* Want to see the prompt. */
12489 if (prompt != NULL)
12491 /* Only the part of the message after the last NL is considered as
12492 * prompt for the command line */
12493 p = vim_strrchr(prompt, '\n');
12494 if (p == NULL)
12495 p = prompt;
12496 else
12498 ++p;
12499 c = *p;
12500 *p = NUL;
12501 msg_start();
12502 msg_clr_eos();
12503 msg_puts_attr(prompt, echo_attr);
12504 msg_didout = FALSE;
12505 msg_starthere();
12506 *p = c;
12508 cmdline_row = msg_row;
12510 if (argvars[1].v_type != VAR_UNKNOWN)
12512 defstr = get_tv_string_buf_chk(&argvars[1], buf);
12513 if (defstr != NULL)
12514 stuffReadbuffSpec(defstr);
12516 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
12518 char_u *xp_name;
12519 int xp_namelen;
12520 long argt;
12522 rettv->vval.v_string = NULL;
12524 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
12525 if (xp_name == NULL)
12526 return;
12528 xp_namelen = (int)STRLEN(xp_name);
12530 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
12531 &xp_arg) == FAIL)
12532 return;
12536 if (defstr != NULL)
12537 rettv->vval.v_string =
12538 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
12539 xp_type, xp_arg);
12541 vim_free(xp_arg);
12543 /* since the user typed this, no need to wait for return */
12544 need_wait_return = FALSE;
12545 msg_didout = FALSE;
12547 cmd_silent = cmd_silent_save;
12551 * "input()" function
12552 * Also handles inputsecret() when inputsecret is set.
12554 static void
12555 f_input(argvars, rettv)
12556 typval_T *argvars;
12557 typval_T *rettv;
12559 get_user_input(argvars, rettv, FALSE);
12563 * "inputdialog()" function
12565 static void
12566 f_inputdialog(argvars, rettv)
12567 typval_T *argvars;
12568 typval_T *rettv;
12570 #if defined(FEAT_GUI_TEXTDIALOG)
12571 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
12572 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
12574 char_u *message;
12575 char_u buf[NUMBUFLEN];
12576 char_u *defstr = (char_u *)"";
12578 message = get_tv_string_chk(&argvars[0]);
12579 if (argvars[1].v_type != VAR_UNKNOWN
12580 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
12581 vim_strncpy(IObuff, defstr, IOSIZE - 1);
12582 else
12583 IObuff[0] = NUL;
12584 if (message != NULL && defstr != NULL
12585 && do_dialog(VIM_QUESTION, NULL, message,
12586 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
12587 rettv->vval.v_string = vim_strsave(IObuff);
12588 else
12590 if (message != NULL && defstr != NULL
12591 && argvars[1].v_type != VAR_UNKNOWN
12592 && argvars[2].v_type != VAR_UNKNOWN)
12593 rettv->vval.v_string = vim_strsave(
12594 get_tv_string_buf(&argvars[2], buf));
12595 else
12596 rettv->vval.v_string = NULL;
12598 rettv->v_type = VAR_STRING;
12600 else
12601 #endif
12602 get_user_input(argvars, rettv, TRUE);
12606 * "inputlist()" function
12608 static void
12609 f_inputlist(argvars, rettv)
12610 typval_T *argvars;
12611 typval_T *rettv;
12613 listitem_T *li;
12614 int selected;
12615 int mouse_used;
12617 #ifdef NO_CONSOLE_INPUT
12618 /* While starting up, there is no place to enter text. */
12619 if (no_console_input())
12620 return;
12621 #endif
12622 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
12624 EMSG2(_(e_listarg), "inputlist()");
12625 return;
12628 msg_start();
12629 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
12630 lines_left = Rows; /* avoid more prompt */
12631 msg_scroll = TRUE;
12632 msg_clr_eos();
12634 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
12636 msg_puts(get_tv_string(&li->li_tv));
12637 msg_putchar('\n');
12640 /* Ask for choice. */
12641 selected = prompt_for_number(&mouse_used);
12642 if (mouse_used)
12643 selected -= lines_left;
12645 rettv->vval.v_number = selected;
12649 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
12652 * "inputrestore()" function
12654 static void
12655 f_inputrestore(argvars, rettv)
12656 typval_T *argvars UNUSED;
12657 typval_T *rettv;
12659 if (ga_userinput.ga_len > 0)
12661 --ga_userinput.ga_len;
12662 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
12663 + ga_userinput.ga_len);
12664 /* default return is zero == OK */
12666 else if (p_verbose > 1)
12668 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
12669 rettv->vval.v_number = 1; /* Failed */
12674 * "inputsave()" function
12676 static void
12677 f_inputsave(argvars, rettv)
12678 typval_T *argvars UNUSED;
12679 typval_T *rettv;
12681 /* Add an entry to the stack of typeahead storage. */
12682 if (ga_grow(&ga_userinput, 1) == OK)
12684 save_typeahead((tasave_T *)(ga_userinput.ga_data)
12685 + ga_userinput.ga_len);
12686 ++ga_userinput.ga_len;
12687 /* default return is zero == OK */
12689 else
12690 rettv->vval.v_number = 1; /* Failed */
12694 * "inputsecret()" function
12696 static void
12697 f_inputsecret(argvars, rettv)
12698 typval_T *argvars;
12699 typval_T *rettv;
12701 ++cmdline_star;
12702 ++inputsecret_flag;
12703 f_input(argvars, rettv);
12704 --cmdline_star;
12705 --inputsecret_flag;
12709 * "insert()" function
12711 static void
12712 f_insert(argvars, rettv)
12713 typval_T *argvars;
12714 typval_T *rettv;
12716 long before = 0;
12717 listitem_T *item;
12718 list_T *l;
12719 int error = FALSE;
12721 if (argvars[0].v_type != VAR_LIST)
12722 EMSG2(_(e_listarg), "insert()");
12723 else if ((l = argvars[0].vval.v_list) != NULL
12724 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
12726 if (argvars[2].v_type != VAR_UNKNOWN)
12727 before = get_tv_number_chk(&argvars[2], &error);
12728 if (error)
12729 return; /* type error; errmsg already given */
12731 if (before == l->lv_len)
12732 item = NULL;
12733 else
12735 item = list_find(l, before);
12736 if (item == NULL)
12738 EMSGN(_(e_listidx), before);
12739 l = NULL;
12742 if (l != NULL)
12744 list_insert_tv(l, &argvars[1], item);
12745 copy_tv(&argvars[0], rettv);
12751 * "isdirectory()" function
12753 static void
12754 f_isdirectory(argvars, rettv)
12755 typval_T *argvars;
12756 typval_T *rettv;
12758 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
12762 * "islocked()" function
12764 static void
12765 f_islocked(argvars, rettv)
12766 typval_T *argvars;
12767 typval_T *rettv;
12769 lval_T lv;
12770 char_u *end;
12771 dictitem_T *di;
12773 rettv->vval.v_number = -1;
12774 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
12775 FNE_CHECK_START);
12776 if (end != NULL && lv.ll_name != NULL)
12778 if (*end != NUL)
12779 EMSG(_(e_trailing));
12780 else
12782 if (lv.ll_tv == NULL)
12784 if (check_changedtick(lv.ll_name))
12785 rettv->vval.v_number = 1; /* always locked */
12786 else
12788 di = find_var(lv.ll_name, NULL);
12789 if (di != NULL)
12791 /* Consider a variable locked when:
12792 * 1. the variable itself is locked
12793 * 2. the value of the variable is locked.
12794 * 3. the List or Dict value is locked.
12796 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
12797 || tv_islocked(&di->di_tv));
12801 else if (lv.ll_range)
12802 EMSG(_("E786: Range not allowed"));
12803 else if (lv.ll_newkey != NULL)
12804 EMSG2(_(e_dictkey), lv.ll_newkey);
12805 else if (lv.ll_list != NULL)
12806 /* List item. */
12807 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
12808 else
12809 /* Dictionary item. */
12810 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
12814 clear_lval(&lv);
12817 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
12820 * Turn a dict into a list:
12821 * "what" == 0: list of keys
12822 * "what" == 1: list of values
12823 * "what" == 2: list of items
12825 static void
12826 dict_list(argvars, rettv, what)
12827 typval_T *argvars;
12828 typval_T *rettv;
12829 int what;
12831 list_T *l2;
12832 dictitem_T *di;
12833 hashitem_T *hi;
12834 listitem_T *li;
12835 listitem_T *li2;
12836 dict_T *d;
12837 int todo;
12839 if (argvars[0].v_type != VAR_DICT)
12841 EMSG(_(e_dictreq));
12842 return;
12844 if ((d = argvars[0].vval.v_dict) == NULL)
12845 return;
12847 if (rettv_list_alloc(rettv) == FAIL)
12848 return;
12850 todo = (int)d->dv_hashtab.ht_used;
12851 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12853 if (!HASHITEM_EMPTY(hi))
12855 --todo;
12856 di = HI2DI(hi);
12858 li = listitem_alloc();
12859 if (li == NULL)
12860 break;
12861 list_append(rettv->vval.v_list, li);
12863 if (what == 0)
12865 /* keys() */
12866 li->li_tv.v_type = VAR_STRING;
12867 li->li_tv.v_lock = 0;
12868 li->li_tv.vval.v_string = vim_strsave(di->di_key);
12870 else if (what == 1)
12872 /* values() */
12873 copy_tv(&di->di_tv, &li->li_tv);
12875 else
12877 /* items() */
12878 l2 = list_alloc();
12879 li->li_tv.v_type = VAR_LIST;
12880 li->li_tv.v_lock = 0;
12881 li->li_tv.vval.v_list = l2;
12882 if (l2 == NULL)
12883 break;
12884 ++l2->lv_refcount;
12886 li2 = listitem_alloc();
12887 if (li2 == NULL)
12888 break;
12889 list_append(l2, li2);
12890 li2->li_tv.v_type = VAR_STRING;
12891 li2->li_tv.v_lock = 0;
12892 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12894 li2 = listitem_alloc();
12895 if (li2 == NULL)
12896 break;
12897 list_append(l2, li2);
12898 copy_tv(&di->di_tv, &li2->li_tv);
12905 * "items(dict)" function
12907 static void
12908 f_items(argvars, rettv)
12909 typval_T *argvars;
12910 typval_T *rettv;
12912 dict_list(argvars, rettv, 2);
12916 * "join()" function
12918 static void
12919 f_join(argvars, rettv)
12920 typval_T *argvars;
12921 typval_T *rettv;
12923 garray_T ga;
12924 char_u *sep;
12926 if (argvars[0].v_type != VAR_LIST)
12928 EMSG(_(e_listreq));
12929 return;
12931 if (argvars[0].vval.v_list == NULL)
12932 return;
12933 if (argvars[1].v_type == VAR_UNKNOWN)
12934 sep = (char_u *)" ";
12935 else
12936 sep = get_tv_string_chk(&argvars[1]);
12938 rettv->v_type = VAR_STRING;
12940 if (sep != NULL)
12942 ga_init2(&ga, (int)sizeof(char), 80);
12943 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12944 ga_append(&ga, NUL);
12945 rettv->vval.v_string = (char_u *)ga.ga_data;
12947 else
12948 rettv->vval.v_string = NULL;
12952 * "keys()" function
12954 static void
12955 f_keys(argvars, rettv)
12956 typval_T *argvars;
12957 typval_T *rettv;
12959 dict_list(argvars, rettv, 0);
12963 * "last_buffer_nr()" function.
12965 static void
12966 f_last_buffer_nr(argvars, rettv)
12967 typval_T *argvars UNUSED;
12968 typval_T *rettv;
12970 int n = 0;
12971 buf_T *buf;
12973 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12974 if (n < buf->b_fnum)
12975 n = buf->b_fnum;
12977 rettv->vval.v_number = n;
12981 * "len()" function
12983 static void
12984 f_len(argvars, rettv)
12985 typval_T *argvars;
12986 typval_T *rettv;
12988 switch (argvars[0].v_type)
12990 case VAR_STRING:
12991 case VAR_NUMBER:
12992 rettv->vval.v_number = (varnumber_T)STRLEN(
12993 get_tv_string(&argvars[0]));
12994 break;
12995 case VAR_LIST:
12996 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
12997 break;
12998 case VAR_DICT:
12999 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
13000 break;
13001 default:
13002 EMSG(_("E701: Invalid type for len()"));
13003 break;
13007 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
13009 static void
13010 libcall_common(argvars, rettv, type)
13011 typval_T *argvars;
13012 typval_T *rettv;
13013 int type;
13015 #ifdef FEAT_LIBCALL
13016 char_u *string_in;
13017 char_u **string_result;
13018 int nr_result;
13019 #endif
13021 rettv->v_type = type;
13022 if (type != VAR_NUMBER)
13023 rettv->vval.v_string = NULL;
13025 if (check_restricted() || check_secure())
13026 return;
13028 #ifdef FEAT_LIBCALL
13029 /* The first two args must be strings, otherwise its meaningless */
13030 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
13032 string_in = NULL;
13033 if (argvars[2].v_type == VAR_STRING)
13034 string_in = argvars[2].vval.v_string;
13035 if (type == VAR_NUMBER)
13036 string_result = NULL;
13037 else
13038 string_result = &rettv->vval.v_string;
13039 if (mch_libcall(argvars[0].vval.v_string,
13040 argvars[1].vval.v_string,
13041 string_in,
13042 argvars[2].vval.v_number,
13043 string_result,
13044 &nr_result) == OK
13045 && type == VAR_NUMBER)
13046 rettv->vval.v_number = nr_result;
13048 #endif
13052 * "libcall()" function
13054 static void
13055 f_libcall(argvars, rettv)
13056 typval_T *argvars;
13057 typval_T *rettv;
13059 libcall_common(argvars, rettv, VAR_STRING);
13063 * "libcallnr()" function
13065 static void
13066 f_libcallnr(argvars, rettv)
13067 typval_T *argvars;
13068 typval_T *rettv;
13070 libcall_common(argvars, rettv, VAR_NUMBER);
13074 * "line(string)" function
13076 static void
13077 f_line(argvars, rettv)
13078 typval_T *argvars;
13079 typval_T *rettv;
13081 linenr_T lnum = 0;
13082 pos_T *fp;
13083 int fnum;
13085 fp = var2fpos(&argvars[0], TRUE, &fnum);
13086 if (fp != NULL)
13087 lnum = fp->lnum;
13088 rettv->vval.v_number = lnum;
13092 * "line2byte(lnum)" function
13094 static void
13095 f_line2byte(argvars, rettv)
13096 typval_T *argvars UNUSED;
13097 typval_T *rettv;
13099 #ifndef FEAT_BYTEOFF
13100 rettv->vval.v_number = -1;
13101 #else
13102 linenr_T lnum;
13104 lnum = get_tv_lnum(argvars);
13105 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
13106 rettv->vval.v_number = -1;
13107 else
13108 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
13109 if (rettv->vval.v_number >= 0)
13110 ++rettv->vval.v_number;
13111 #endif
13115 * "lispindent(lnum)" function
13117 static void
13118 f_lispindent(argvars, rettv)
13119 typval_T *argvars;
13120 typval_T *rettv;
13122 #ifdef FEAT_LISP
13123 pos_T pos;
13124 linenr_T lnum;
13126 pos = curwin->w_cursor;
13127 lnum = get_tv_lnum(argvars);
13128 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
13130 curwin->w_cursor.lnum = lnum;
13131 rettv->vval.v_number = get_lisp_indent();
13132 curwin->w_cursor = pos;
13134 else
13135 #endif
13136 rettv->vval.v_number = -1;
13140 * "localtime()" function
13142 static void
13143 f_localtime(argvars, rettv)
13144 typval_T *argvars UNUSED;
13145 typval_T *rettv;
13147 rettv->vval.v_number = (varnumber_T)time(NULL);
13150 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
13152 static void
13153 get_maparg(argvars, rettv, exact)
13154 typval_T *argvars;
13155 typval_T *rettv;
13156 int exact;
13158 char_u *keys;
13159 char_u *which;
13160 char_u buf[NUMBUFLEN];
13161 char_u *keys_buf = NULL;
13162 char_u *rhs;
13163 int mode;
13164 garray_T ga;
13165 int abbr = FALSE;
13167 /* return empty string for failure */
13168 rettv->v_type = VAR_STRING;
13169 rettv->vval.v_string = NULL;
13171 keys = get_tv_string(&argvars[0]);
13172 if (*keys == NUL)
13173 return;
13175 if (argvars[1].v_type != VAR_UNKNOWN)
13177 which = get_tv_string_buf_chk(&argvars[1], buf);
13178 if (argvars[2].v_type != VAR_UNKNOWN)
13179 abbr = get_tv_number(&argvars[2]);
13181 else
13182 which = (char_u *)"";
13183 if (which == NULL)
13184 return;
13186 mode = get_map_mode(&which, 0);
13188 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
13189 rhs = check_map(keys, mode, exact, FALSE, abbr);
13190 vim_free(keys_buf);
13191 if (rhs != NULL)
13193 ga_init(&ga);
13194 ga.ga_itemsize = 1;
13195 ga.ga_growsize = 40;
13197 while (*rhs != NUL)
13198 ga_concat(&ga, str2special(&rhs, FALSE));
13200 ga_append(&ga, NUL);
13201 rettv->vval.v_string = (char_u *)ga.ga_data;
13205 #ifdef FEAT_FLOAT
13207 * "log10()" function
13209 static void
13210 f_log10(argvars, rettv)
13211 typval_T *argvars;
13212 typval_T *rettv;
13214 float_T f;
13216 rettv->v_type = VAR_FLOAT;
13217 if (get_float_arg(argvars, &f) == OK)
13218 rettv->vval.v_float = log10(f);
13219 else
13220 rettv->vval.v_float = 0.0;
13222 #endif
13225 * "map()" function
13227 static void
13228 f_map(argvars, rettv)
13229 typval_T *argvars;
13230 typval_T *rettv;
13232 filter_map(argvars, rettv, TRUE);
13236 * "maparg()" function
13238 static void
13239 f_maparg(argvars, rettv)
13240 typval_T *argvars;
13241 typval_T *rettv;
13243 get_maparg(argvars, rettv, TRUE);
13247 * "mapcheck()" function
13249 static void
13250 f_mapcheck(argvars, rettv)
13251 typval_T *argvars;
13252 typval_T *rettv;
13254 get_maparg(argvars, rettv, FALSE);
13257 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
13259 static void
13260 find_some_match(argvars, rettv, type)
13261 typval_T *argvars;
13262 typval_T *rettv;
13263 int type;
13265 char_u *str = NULL;
13266 char_u *expr = NULL;
13267 char_u *pat;
13268 regmatch_T regmatch;
13269 char_u patbuf[NUMBUFLEN];
13270 char_u strbuf[NUMBUFLEN];
13271 char_u *save_cpo;
13272 long start = 0;
13273 long nth = 1;
13274 colnr_T startcol = 0;
13275 int match = 0;
13276 list_T *l = NULL;
13277 listitem_T *li = NULL;
13278 long idx = 0;
13279 char_u *tofree = NULL;
13281 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
13282 save_cpo = p_cpo;
13283 p_cpo = (char_u *)"";
13285 rettv->vval.v_number = -1;
13286 if (type == 3)
13288 /* return empty list when there are no matches */
13289 if (rettv_list_alloc(rettv) == FAIL)
13290 goto theend;
13292 else if (type == 2)
13294 rettv->v_type = VAR_STRING;
13295 rettv->vval.v_string = NULL;
13298 if (argvars[0].v_type == VAR_LIST)
13300 if ((l = argvars[0].vval.v_list) == NULL)
13301 goto theend;
13302 li = l->lv_first;
13304 else
13305 expr = str = get_tv_string(&argvars[0]);
13307 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
13308 if (pat == NULL)
13309 goto theend;
13311 if (argvars[2].v_type != VAR_UNKNOWN)
13313 int error = FALSE;
13315 start = get_tv_number_chk(&argvars[2], &error);
13316 if (error)
13317 goto theend;
13318 if (l != NULL)
13320 li = list_find(l, start);
13321 if (li == NULL)
13322 goto theend;
13323 idx = l->lv_idx; /* use the cached index */
13325 else
13327 if (start < 0)
13328 start = 0;
13329 if (start > (long)STRLEN(str))
13330 goto theend;
13331 /* When "count" argument is there ignore matches before "start",
13332 * otherwise skip part of the string. Differs when pattern is "^"
13333 * or "\<". */
13334 if (argvars[3].v_type != VAR_UNKNOWN)
13335 startcol = start;
13336 else
13337 str += start;
13340 if (argvars[3].v_type != VAR_UNKNOWN)
13341 nth = get_tv_number_chk(&argvars[3], &error);
13342 if (error)
13343 goto theend;
13346 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
13347 if (regmatch.regprog != NULL)
13349 regmatch.rm_ic = p_ic;
13351 for (;;)
13353 if (l != NULL)
13355 if (li == NULL)
13357 match = FALSE;
13358 break;
13360 vim_free(tofree);
13361 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
13362 if (str == NULL)
13363 break;
13366 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
13368 if (match && --nth <= 0)
13369 break;
13370 if (l == NULL && !match)
13371 break;
13373 /* Advance to just after the match. */
13374 if (l != NULL)
13376 li = li->li_next;
13377 ++idx;
13379 else
13381 #ifdef FEAT_MBYTE
13382 startcol = (colnr_T)(regmatch.startp[0]
13383 + (*mb_ptr2len)(regmatch.startp[0]) - str);
13384 #else
13385 startcol = regmatch.startp[0] + 1 - str;
13386 #endif
13390 if (match)
13392 if (type == 3)
13394 int i;
13396 /* return list with matched string and submatches */
13397 for (i = 0; i < NSUBEXP; ++i)
13399 if (regmatch.endp[i] == NULL)
13401 if (list_append_string(rettv->vval.v_list,
13402 (char_u *)"", 0) == FAIL)
13403 break;
13405 else if (list_append_string(rettv->vval.v_list,
13406 regmatch.startp[i],
13407 (int)(regmatch.endp[i] - regmatch.startp[i]))
13408 == FAIL)
13409 break;
13412 else if (type == 2)
13414 /* return matched string */
13415 if (l != NULL)
13416 copy_tv(&li->li_tv, rettv);
13417 else
13418 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
13419 (int)(regmatch.endp[0] - regmatch.startp[0]));
13421 else if (l != NULL)
13422 rettv->vval.v_number = idx;
13423 else
13425 if (type != 0)
13426 rettv->vval.v_number =
13427 (varnumber_T)(regmatch.startp[0] - str);
13428 else
13429 rettv->vval.v_number =
13430 (varnumber_T)(regmatch.endp[0] - str);
13431 rettv->vval.v_number += (varnumber_T)(str - expr);
13434 vim_free(regmatch.regprog);
13437 theend:
13438 vim_free(tofree);
13439 p_cpo = save_cpo;
13443 * "match()" function
13445 static void
13446 f_match(argvars, rettv)
13447 typval_T *argvars;
13448 typval_T *rettv;
13450 find_some_match(argvars, rettv, 1);
13454 * "matchadd()" function
13456 static void
13457 f_matchadd(argvars, rettv)
13458 typval_T *argvars;
13459 typval_T *rettv;
13461 #ifdef FEAT_SEARCH_EXTRA
13462 char_u buf[NUMBUFLEN];
13463 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
13464 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
13465 int prio = 10; /* default priority */
13466 int id = -1;
13467 int error = FALSE;
13469 rettv->vval.v_number = -1;
13471 if (grp == NULL || pat == NULL)
13472 return;
13473 if (argvars[2].v_type != VAR_UNKNOWN)
13475 prio = get_tv_number_chk(&argvars[2], &error);
13476 if (argvars[3].v_type != VAR_UNKNOWN)
13477 id = get_tv_number_chk(&argvars[3], &error);
13479 if (error == TRUE)
13480 return;
13481 if (id >= 1 && id <= 3)
13483 EMSGN("E798: ID is reserved for \":match\": %ld", id);
13484 return;
13487 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
13488 #endif
13492 * "matcharg()" function
13494 static void
13495 f_matcharg(argvars, rettv)
13496 typval_T *argvars;
13497 typval_T *rettv;
13499 if (rettv_list_alloc(rettv) == OK)
13501 #ifdef FEAT_SEARCH_EXTRA
13502 int id = get_tv_number(&argvars[0]);
13503 matchitem_T *m;
13505 if (id >= 1 && id <= 3)
13507 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
13509 list_append_string(rettv->vval.v_list,
13510 syn_id2name(m->hlg_id), -1);
13511 list_append_string(rettv->vval.v_list, m->pattern, -1);
13513 else
13515 list_append_string(rettv->vval.v_list, NUL, -1);
13516 list_append_string(rettv->vval.v_list, NUL, -1);
13519 #endif
13524 * "matchdelete()" function
13526 static void
13527 f_matchdelete(argvars, rettv)
13528 typval_T *argvars;
13529 typval_T *rettv;
13531 #ifdef FEAT_SEARCH_EXTRA
13532 rettv->vval.v_number = match_delete(curwin,
13533 (int)get_tv_number(&argvars[0]), TRUE);
13534 #endif
13538 * "matchend()" function
13540 static void
13541 f_matchend(argvars, rettv)
13542 typval_T *argvars;
13543 typval_T *rettv;
13545 find_some_match(argvars, rettv, 0);
13549 * "matchlist()" function
13551 static void
13552 f_matchlist(argvars, rettv)
13553 typval_T *argvars;
13554 typval_T *rettv;
13556 find_some_match(argvars, rettv, 3);
13560 * "matchstr()" function
13562 static void
13563 f_matchstr(argvars, rettv)
13564 typval_T *argvars;
13565 typval_T *rettv;
13567 find_some_match(argvars, rettv, 2);
13570 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
13572 static void
13573 max_min(argvars, rettv, domax)
13574 typval_T *argvars;
13575 typval_T *rettv;
13576 int domax;
13578 long n = 0;
13579 long i;
13580 int error = FALSE;
13582 if (argvars[0].v_type == VAR_LIST)
13584 list_T *l;
13585 listitem_T *li;
13587 l = argvars[0].vval.v_list;
13588 if (l != NULL)
13590 li = l->lv_first;
13591 if (li != NULL)
13593 n = get_tv_number_chk(&li->li_tv, &error);
13594 for (;;)
13596 li = li->li_next;
13597 if (li == NULL)
13598 break;
13599 i = get_tv_number_chk(&li->li_tv, &error);
13600 if (domax ? i > n : i < n)
13601 n = i;
13606 else if (argvars[0].v_type == VAR_DICT)
13608 dict_T *d;
13609 int first = TRUE;
13610 hashitem_T *hi;
13611 int todo;
13613 d = argvars[0].vval.v_dict;
13614 if (d != NULL)
13616 todo = (int)d->dv_hashtab.ht_used;
13617 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13619 if (!HASHITEM_EMPTY(hi))
13621 --todo;
13622 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
13623 if (first)
13625 n = i;
13626 first = FALSE;
13628 else if (domax ? i > n : i < n)
13629 n = i;
13634 else
13635 EMSG(_(e_listdictarg));
13636 rettv->vval.v_number = error ? 0 : n;
13640 * "max()" function
13642 static void
13643 f_max(argvars, rettv)
13644 typval_T *argvars;
13645 typval_T *rettv;
13647 max_min(argvars, rettv, TRUE);
13651 * "min()" function
13653 static void
13654 f_min(argvars, rettv)
13655 typval_T *argvars;
13656 typval_T *rettv;
13658 max_min(argvars, rettv, FALSE);
13661 static int mkdir_recurse __ARGS((char_u *dir, int prot));
13664 * Create the directory in which "dir" is located, and higher levels when
13665 * needed.
13667 static int
13668 mkdir_recurse(dir, prot)
13669 char_u *dir;
13670 int prot;
13672 char_u *p;
13673 char_u *updir;
13674 int r = FAIL;
13676 /* Get end of directory name in "dir".
13677 * We're done when it's "/" or "c:/". */
13678 p = gettail_sep(dir);
13679 if (p <= get_past_head(dir))
13680 return OK;
13682 /* If the directory exists we're done. Otherwise: create it.*/
13683 updir = vim_strnsave(dir, (int)(p - dir));
13684 if (updir == NULL)
13685 return FAIL;
13686 if (mch_isdir(updir))
13687 r = OK;
13688 else if (mkdir_recurse(updir, prot) == OK)
13689 r = vim_mkdir_emsg(updir, prot);
13690 vim_free(updir);
13691 return r;
13694 #ifdef vim_mkdir
13696 * "mkdir()" function
13698 static void
13699 f_mkdir(argvars, rettv)
13700 typval_T *argvars;
13701 typval_T *rettv;
13703 char_u *dir;
13704 char_u buf[NUMBUFLEN];
13705 int prot = 0755;
13707 rettv->vval.v_number = FAIL;
13708 if (check_restricted() || check_secure())
13709 return;
13711 dir = get_tv_string_buf(&argvars[0], buf);
13712 if (argvars[1].v_type != VAR_UNKNOWN)
13714 if (argvars[2].v_type != VAR_UNKNOWN)
13715 prot = get_tv_number_chk(&argvars[2], NULL);
13716 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
13717 mkdir_recurse(dir, prot);
13719 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
13721 #endif
13724 * "mode()" function
13726 static void
13727 f_mode(argvars, rettv)
13728 typval_T *argvars;
13729 typval_T *rettv;
13731 char_u buf[3];
13733 buf[1] = NUL;
13734 buf[2] = NUL;
13736 #ifdef FEAT_VISUAL
13737 if (VIsual_active)
13739 if (VIsual_select)
13740 buf[0] = VIsual_mode + 's' - 'v';
13741 else
13742 buf[0] = VIsual_mode;
13744 else
13745 #endif
13746 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
13747 || State == CONFIRM)
13749 buf[0] = 'r';
13750 if (State == ASKMORE)
13751 buf[1] = 'm';
13752 else if (State == CONFIRM)
13753 buf[1] = '?';
13755 else if (State == EXTERNCMD)
13756 buf[0] = '!';
13757 else if (State & INSERT)
13759 #ifdef FEAT_VREPLACE
13760 if (State & VREPLACE_FLAG)
13762 buf[0] = 'R';
13763 buf[1] = 'v';
13765 else
13766 #endif
13767 if (State & REPLACE_FLAG)
13768 buf[0] = 'R';
13769 else
13770 buf[0] = 'i';
13772 else if (State & CMDLINE)
13774 buf[0] = 'c';
13775 if (exmode_active)
13776 buf[1] = 'v';
13778 else if (exmode_active)
13780 buf[0] = 'c';
13781 buf[1] = 'e';
13783 else
13785 buf[0] = 'n';
13786 if (finish_op)
13787 buf[1] = 'o';
13790 /* Clear out the minor mode when the argument is not a non-zero number or
13791 * non-empty string. */
13792 if (!non_zero_arg(&argvars[0]))
13793 buf[1] = NUL;
13795 rettv->vval.v_string = vim_strsave(buf);
13796 rettv->v_type = VAR_STRING;
13799 #ifdef FEAT_MZSCHEME
13801 * "mzeval()" function
13803 static void
13804 f_mzeval(argvars, rettv)
13805 typval_T *argvars;
13806 typval_T *rettv;
13808 char_u *str;
13809 char_u buf[NUMBUFLEN];
13811 str = get_tv_string_buf(&argvars[0], buf);
13812 do_mzeval(str, rettv);
13814 #endif
13817 * "nextnonblank()" function
13819 static void
13820 f_nextnonblank(argvars, rettv)
13821 typval_T *argvars;
13822 typval_T *rettv;
13824 linenr_T lnum;
13826 for (lnum = get_tv_lnum(argvars); ; ++lnum)
13828 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
13830 lnum = 0;
13831 break;
13833 if (*skipwhite(ml_get(lnum)) != NUL)
13834 break;
13836 rettv->vval.v_number = lnum;
13840 * "nr2char()" function
13842 static void
13843 f_nr2char(argvars, rettv)
13844 typval_T *argvars;
13845 typval_T *rettv;
13847 char_u buf[NUMBUFLEN];
13849 #ifdef FEAT_MBYTE
13850 if (has_mbyte)
13851 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
13852 else
13853 #endif
13855 buf[0] = (char_u)get_tv_number(&argvars[0]);
13856 buf[1] = NUL;
13858 rettv->v_type = VAR_STRING;
13859 rettv->vval.v_string = vim_strsave(buf);
13863 * "pathshorten()" function
13865 static void
13866 f_pathshorten(argvars, rettv)
13867 typval_T *argvars;
13868 typval_T *rettv;
13870 char_u *p;
13872 rettv->v_type = VAR_STRING;
13873 p = get_tv_string_chk(&argvars[0]);
13874 if (p == NULL)
13875 rettv->vval.v_string = NULL;
13876 else
13878 p = vim_strsave(p);
13879 rettv->vval.v_string = p;
13880 if (p != NULL)
13881 shorten_dir(p);
13885 #ifdef FEAT_FLOAT
13887 * "pow()" function
13889 static void
13890 f_pow(argvars, rettv)
13891 typval_T *argvars;
13892 typval_T *rettv;
13894 float_T fx, fy;
13896 rettv->v_type = VAR_FLOAT;
13897 if (get_float_arg(argvars, &fx) == OK
13898 && get_float_arg(&argvars[1], &fy) == OK)
13899 rettv->vval.v_float = pow(fx, fy);
13900 else
13901 rettv->vval.v_float = 0.0;
13903 #endif
13906 * "prevnonblank()" function
13908 static void
13909 f_prevnonblank(argvars, rettv)
13910 typval_T *argvars;
13911 typval_T *rettv;
13913 linenr_T lnum;
13915 lnum = get_tv_lnum(argvars);
13916 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
13917 lnum = 0;
13918 else
13919 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
13920 --lnum;
13921 rettv->vval.v_number = lnum;
13924 #ifdef HAVE_STDARG_H
13925 /* This dummy va_list is here because:
13926 * - passing a NULL pointer doesn't work when va_list isn't a pointer
13927 * - locally in the function results in a "used before set" warning
13928 * - using va_start() to initialize it gives "function with fixed args" error */
13929 static va_list ap;
13930 #endif
13933 * "printf()" function
13935 static void
13936 f_printf(argvars, rettv)
13937 typval_T *argvars;
13938 typval_T *rettv;
13940 rettv->v_type = VAR_STRING;
13941 rettv->vval.v_string = NULL;
13942 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
13944 char_u buf[NUMBUFLEN];
13945 int len;
13946 char_u *s;
13947 int saved_did_emsg = did_emsg;
13948 char *fmt;
13950 /* Get the required length, allocate the buffer and do it for real. */
13951 did_emsg = FALSE;
13952 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
13953 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
13954 if (!did_emsg)
13956 s = alloc(len + 1);
13957 if (s != NULL)
13959 rettv->vval.v_string = s;
13960 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
13963 did_emsg |= saved_did_emsg;
13965 #endif
13969 * "pumvisible()" function
13971 static void
13972 f_pumvisible(argvars, rettv)
13973 typval_T *argvars UNUSED;
13974 typval_T *rettv UNUSED;
13976 #ifdef FEAT_INS_EXPAND
13977 if (pum_visible())
13978 rettv->vval.v_number = 1;
13979 #endif
13983 * "range()" function
13985 static void
13986 f_range(argvars, rettv)
13987 typval_T *argvars;
13988 typval_T *rettv;
13990 long start;
13991 long end;
13992 long stride = 1;
13993 long i;
13994 int error = FALSE;
13996 start = get_tv_number_chk(&argvars[0], &error);
13997 if (argvars[1].v_type == VAR_UNKNOWN)
13999 end = start - 1;
14000 start = 0;
14002 else
14004 end = get_tv_number_chk(&argvars[1], &error);
14005 if (argvars[2].v_type != VAR_UNKNOWN)
14006 stride = get_tv_number_chk(&argvars[2], &error);
14009 if (error)
14010 return; /* type error; errmsg already given */
14011 if (stride == 0)
14012 EMSG(_("E726: Stride is zero"));
14013 else if (stride > 0 ? end + 1 < start : end - 1 > start)
14014 EMSG(_("E727: Start past end"));
14015 else
14017 if (rettv_list_alloc(rettv) == OK)
14018 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
14019 if (list_append_number(rettv->vval.v_list,
14020 (varnumber_T)i) == FAIL)
14021 break;
14026 * "readfile()" function
14028 static void
14029 f_readfile(argvars, rettv)
14030 typval_T *argvars;
14031 typval_T *rettv;
14033 int binary = FALSE;
14034 char_u *fname;
14035 FILE *fd;
14036 listitem_T *li;
14037 #define FREAD_SIZE 200 /* optimized for text lines */
14038 char_u buf[FREAD_SIZE];
14039 int readlen; /* size of last fread() */
14040 int buflen; /* nr of valid chars in buf[] */
14041 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
14042 int tolist; /* first byte in buf[] still to be put in list */
14043 int chop; /* how many CR to chop off */
14044 char_u *prev = NULL; /* previously read bytes, if any */
14045 int prevlen = 0; /* length of "prev" if not NULL */
14046 char_u *s;
14047 int len;
14048 long maxline = MAXLNUM;
14049 long cnt = 0;
14051 if (argvars[1].v_type != VAR_UNKNOWN)
14053 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
14054 binary = TRUE;
14055 if (argvars[2].v_type != VAR_UNKNOWN)
14056 maxline = get_tv_number(&argvars[2]);
14059 if (rettv_list_alloc(rettv) == FAIL)
14060 return;
14062 /* Always open the file in binary mode, library functions have a mind of
14063 * their own about CR-LF conversion. */
14064 fname = get_tv_string(&argvars[0]);
14065 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
14067 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
14068 return;
14071 filtd = 0;
14072 while (cnt < maxline || maxline < 0)
14074 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
14075 buflen = filtd + readlen;
14076 tolist = 0;
14077 for ( ; filtd < buflen || readlen <= 0; ++filtd)
14079 if (buf[filtd] == '\n' || readlen <= 0)
14081 /* Only when in binary mode add an empty list item when the
14082 * last line ends in a '\n'. */
14083 if (!binary && readlen == 0 && filtd == 0)
14084 break;
14086 /* Found end-of-line or end-of-file: add a text line to the
14087 * list. */
14088 chop = 0;
14089 if (!binary)
14090 while (filtd - chop - 1 >= tolist
14091 && buf[filtd - chop - 1] == '\r')
14092 ++chop;
14093 len = filtd - tolist - chop;
14094 if (prev == NULL)
14095 s = vim_strnsave(buf + tolist, len);
14096 else
14098 s = alloc((unsigned)(prevlen + len + 1));
14099 if (s != NULL)
14101 mch_memmove(s, prev, prevlen);
14102 vim_free(prev);
14103 prev = NULL;
14104 mch_memmove(s + prevlen, buf + tolist, len);
14105 s[prevlen + len] = NUL;
14108 tolist = filtd + 1;
14110 li = listitem_alloc();
14111 if (li == NULL)
14113 vim_free(s);
14114 break;
14116 li->li_tv.v_type = VAR_STRING;
14117 li->li_tv.v_lock = 0;
14118 li->li_tv.vval.v_string = s;
14119 list_append(rettv->vval.v_list, li);
14121 if (++cnt >= maxline && maxline >= 0)
14122 break;
14123 if (readlen <= 0)
14124 break;
14126 else if (buf[filtd] == NUL)
14127 buf[filtd] = '\n';
14129 if (readlen <= 0)
14130 break;
14132 if (tolist == 0)
14134 /* "buf" is full, need to move text to an allocated buffer */
14135 if (prev == NULL)
14137 prev = vim_strnsave(buf, buflen);
14138 prevlen = buflen;
14140 else
14142 s = alloc((unsigned)(prevlen + buflen));
14143 if (s != NULL)
14145 mch_memmove(s, prev, prevlen);
14146 mch_memmove(s + prevlen, buf, buflen);
14147 vim_free(prev);
14148 prev = s;
14149 prevlen += buflen;
14152 filtd = 0;
14154 else
14156 mch_memmove(buf, buf + tolist, buflen - tolist);
14157 filtd -= tolist;
14162 * For a negative line count use only the lines at the end of the file,
14163 * free the rest.
14165 if (maxline < 0)
14166 while (cnt > -maxline)
14168 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
14169 --cnt;
14172 vim_free(prev);
14173 fclose(fd);
14176 #if defined(FEAT_RELTIME)
14177 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
14180 * Convert a List to proftime_T.
14181 * Return FAIL when there is something wrong.
14183 static int
14184 list2proftime(arg, tm)
14185 typval_T *arg;
14186 proftime_T *tm;
14188 long n1, n2;
14189 int error = FALSE;
14191 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
14192 || arg->vval.v_list->lv_len != 2)
14193 return FAIL;
14194 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
14195 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
14196 # ifdef WIN3264
14197 tm->HighPart = n1;
14198 tm->LowPart = n2;
14199 # else
14200 tm->tv_sec = n1;
14201 tm->tv_usec = n2;
14202 # endif
14203 return error ? FAIL : OK;
14205 #endif /* FEAT_RELTIME */
14208 * "reltime()" function
14210 static void
14211 f_reltime(argvars, rettv)
14212 typval_T *argvars;
14213 typval_T *rettv;
14215 #ifdef FEAT_RELTIME
14216 proftime_T res;
14217 proftime_T start;
14219 if (argvars[0].v_type == VAR_UNKNOWN)
14221 /* No arguments: get current time. */
14222 profile_start(&res);
14224 else if (argvars[1].v_type == VAR_UNKNOWN)
14226 if (list2proftime(&argvars[0], &res) == FAIL)
14227 return;
14228 profile_end(&res);
14230 else
14232 /* Two arguments: compute the difference. */
14233 if (list2proftime(&argvars[0], &start) == FAIL
14234 || list2proftime(&argvars[1], &res) == FAIL)
14235 return;
14236 profile_sub(&res, &start);
14239 if (rettv_list_alloc(rettv) == OK)
14241 long n1, n2;
14243 # ifdef WIN3264
14244 n1 = res.HighPart;
14245 n2 = res.LowPart;
14246 # else
14247 n1 = res.tv_sec;
14248 n2 = res.tv_usec;
14249 # endif
14250 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
14251 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
14253 #endif
14257 * "reltimestr()" function
14259 static void
14260 f_reltimestr(argvars, rettv)
14261 typval_T *argvars;
14262 typval_T *rettv;
14264 #ifdef FEAT_RELTIME
14265 proftime_T tm;
14266 #endif
14268 rettv->v_type = VAR_STRING;
14269 rettv->vval.v_string = NULL;
14270 #ifdef FEAT_RELTIME
14271 if (list2proftime(&argvars[0], &tm) == OK)
14272 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
14273 #endif
14276 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
14277 static void make_connection __ARGS((void));
14278 static int check_connection __ARGS((void));
14280 static void
14281 make_connection()
14283 if (X_DISPLAY == NULL
14284 # ifdef FEAT_GUI
14285 && !gui.in_use
14286 # endif
14289 x_force_connect = TRUE;
14290 setup_term_clip();
14291 x_force_connect = FALSE;
14295 static int
14296 check_connection()
14298 make_connection();
14299 if (X_DISPLAY == NULL)
14301 EMSG(_("E240: No connection to Vim server"));
14302 return FAIL;
14304 return OK;
14306 #endif
14308 #ifdef FEAT_CLIENTSERVER
14309 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
14311 static void
14312 remote_common(argvars, rettv, expr)
14313 typval_T *argvars;
14314 typval_T *rettv;
14315 int expr;
14317 char_u *server_name;
14318 char_u *keys;
14319 char_u *r = NULL;
14320 char_u buf[NUMBUFLEN];
14321 # ifdef WIN32
14322 HWND w;
14323 # else
14324 Window w;
14325 # endif
14327 if (check_restricted() || check_secure())
14328 return;
14330 # ifdef FEAT_X11
14331 if (check_connection() == FAIL)
14332 return;
14333 # endif
14335 server_name = get_tv_string_chk(&argvars[0]);
14336 if (server_name == NULL)
14337 return; /* type error; errmsg already given */
14338 keys = get_tv_string_buf(&argvars[1], buf);
14339 # ifdef WIN32
14340 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14341 # else
14342 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
14343 < 0)
14344 # endif
14346 if (r != NULL)
14347 EMSG(r); /* sending worked but evaluation failed */
14348 else
14349 EMSG2(_("E241: Unable to send to %s"), server_name);
14350 return;
14353 rettv->vval.v_string = r;
14355 if (argvars[2].v_type != VAR_UNKNOWN)
14357 dictitem_T v;
14358 char_u str[30];
14359 char_u *idvar;
14361 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
14362 v.di_tv.v_type = VAR_STRING;
14363 v.di_tv.vval.v_string = vim_strsave(str);
14364 idvar = get_tv_string_chk(&argvars[2]);
14365 if (idvar != NULL)
14366 set_var(idvar, &v.di_tv, FALSE);
14367 vim_free(v.di_tv.vval.v_string);
14370 #endif
14373 * "remote_expr()" function
14375 static void
14376 f_remote_expr(argvars, rettv)
14377 typval_T *argvars UNUSED;
14378 typval_T *rettv;
14380 rettv->v_type = VAR_STRING;
14381 rettv->vval.v_string = NULL;
14382 #ifdef FEAT_CLIENTSERVER
14383 remote_common(argvars, rettv, TRUE);
14384 #endif
14388 * "remote_foreground()" function
14390 static void
14391 f_remote_foreground(argvars, rettv)
14392 typval_T *argvars UNUSED;
14393 typval_T *rettv UNUSED;
14395 #ifdef FEAT_CLIENTSERVER
14396 # ifdef WIN32
14397 /* On Win32 it's done in this application. */
14399 char_u *server_name = get_tv_string_chk(&argvars[0]);
14401 if (server_name != NULL)
14402 serverForeground(server_name);
14404 # else
14405 /* Send a foreground() expression to the server. */
14406 argvars[1].v_type = VAR_STRING;
14407 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
14408 argvars[2].v_type = VAR_UNKNOWN;
14409 remote_common(argvars, rettv, TRUE);
14410 vim_free(argvars[1].vval.v_string);
14411 # endif
14412 #endif
14415 static void
14416 f_remote_peek(argvars, rettv)
14417 typval_T *argvars UNUSED;
14418 typval_T *rettv;
14420 #ifdef FEAT_CLIENTSERVER
14421 dictitem_T v;
14422 char_u *s = NULL;
14423 # ifdef WIN32
14424 long_u n = 0;
14425 # endif
14426 char_u *serverid;
14428 if (check_restricted() || check_secure())
14430 rettv->vval.v_number = -1;
14431 return;
14433 serverid = get_tv_string_chk(&argvars[0]);
14434 if (serverid == NULL)
14436 rettv->vval.v_number = -1;
14437 return; /* type error; errmsg already given */
14439 # ifdef WIN32
14440 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14441 if (n == 0)
14442 rettv->vval.v_number = -1;
14443 else
14445 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
14446 rettv->vval.v_number = (s != NULL);
14448 # else
14449 if (check_connection() == FAIL)
14450 return;
14452 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
14453 serverStrToWin(serverid), &s);
14454 # endif
14456 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
14458 char_u *retvar;
14460 v.di_tv.v_type = VAR_STRING;
14461 v.di_tv.vval.v_string = vim_strsave(s);
14462 retvar = get_tv_string_chk(&argvars[1]);
14463 if (retvar != NULL)
14464 set_var(retvar, &v.di_tv, FALSE);
14465 vim_free(v.di_tv.vval.v_string);
14467 #else
14468 rettv->vval.v_number = -1;
14469 #endif
14472 static void
14473 f_remote_read(argvars, rettv)
14474 typval_T *argvars UNUSED;
14475 typval_T *rettv;
14477 char_u *r = NULL;
14479 #ifdef FEAT_CLIENTSERVER
14480 char_u *serverid = get_tv_string_chk(&argvars[0]);
14482 if (serverid != NULL && !check_restricted() && !check_secure())
14484 # ifdef WIN32
14485 /* The server's HWND is encoded in the 'id' parameter */
14486 long_u n = 0;
14488 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14489 if (n != 0)
14490 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
14491 if (r == NULL)
14492 # else
14493 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
14494 serverStrToWin(serverid), &r, FALSE) < 0)
14495 # endif
14496 EMSG(_("E277: Unable to read a server reply"));
14498 #endif
14499 rettv->v_type = VAR_STRING;
14500 rettv->vval.v_string = r;
14504 * "remote_send()" function
14506 static void
14507 f_remote_send(argvars, rettv)
14508 typval_T *argvars UNUSED;
14509 typval_T *rettv;
14511 rettv->v_type = VAR_STRING;
14512 rettv->vval.v_string = NULL;
14513 #ifdef FEAT_CLIENTSERVER
14514 remote_common(argvars, rettv, FALSE);
14515 #endif
14519 * "remove()" function
14521 static void
14522 f_remove(argvars, rettv)
14523 typval_T *argvars;
14524 typval_T *rettv;
14526 list_T *l;
14527 listitem_T *item, *item2;
14528 listitem_T *li;
14529 long idx;
14530 long end;
14531 char_u *key;
14532 dict_T *d;
14533 dictitem_T *di;
14535 if (argvars[0].v_type == VAR_DICT)
14537 if (argvars[2].v_type != VAR_UNKNOWN)
14538 EMSG2(_(e_toomanyarg), "remove()");
14539 else if ((d = argvars[0].vval.v_dict) != NULL
14540 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
14542 key = get_tv_string_chk(&argvars[1]);
14543 if (key != NULL)
14545 di = dict_find(d, key, -1);
14546 if (di == NULL)
14547 EMSG2(_(e_dictkey), key);
14548 else
14550 *rettv = di->di_tv;
14551 init_tv(&di->di_tv);
14552 dictitem_remove(d, di);
14557 else if (argvars[0].v_type != VAR_LIST)
14558 EMSG2(_(e_listdictarg), "remove()");
14559 else if ((l = argvars[0].vval.v_list) != NULL
14560 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
14562 int error = FALSE;
14564 idx = get_tv_number_chk(&argvars[1], &error);
14565 if (error)
14566 ; /* type error: do nothing, errmsg already given */
14567 else if ((item = list_find(l, idx)) == NULL)
14568 EMSGN(_(e_listidx), idx);
14569 else
14571 if (argvars[2].v_type == VAR_UNKNOWN)
14573 /* Remove one item, return its value. */
14574 list_remove(l, item, item);
14575 *rettv = item->li_tv;
14576 vim_free(item);
14578 else
14580 /* Remove range of items, return list with values. */
14581 end = get_tv_number_chk(&argvars[2], &error);
14582 if (error)
14583 ; /* type error: do nothing */
14584 else if ((item2 = list_find(l, end)) == NULL)
14585 EMSGN(_(e_listidx), end);
14586 else
14588 int cnt = 0;
14590 for (li = item; li != NULL; li = li->li_next)
14592 ++cnt;
14593 if (li == item2)
14594 break;
14596 if (li == NULL) /* didn't find "item2" after "item" */
14597 EMSG(_(e_invrange));
14598 else
14600 list_remove(l, item, item2);
14601 if (rettv_list_alloc(rettv) == OK)
14603 l = rettv->vval.v_list;
14604 l->lv_first = item;
14605 l->lv_last = item2;
14606 item->li_prev = NULL;
14607 item2->li_next = NULL;
14608 l->lv_len = cnt;
14618 * "rename({from}, {to})" function
14620 static void
14621 f_rename(argvars, rettv)
14622 typval_T *argvars;
14623 typval_T *rettv;
14625 char_u buf[NUMBUFLEN];
14627 if (check_restricted() || check_secure())
14628 rettv->vval.v_number = -1;
14629 else
14630 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
14631 get_tv_string_buf(&argvars[1], buf));
14635 * "repeat()" function
14637 static void
14638 f_repeat(argvars, rettv)
14639 typval_T *argvars;
14640 typval_T *rettv;
14642 char_u *p;
14643 int n;
14644 int slen;
14645 int len;
14646 char_u *r;
14647 int i;
14649 n = get_tv_number(&argvars[1]);
14650 if (argvars[0].v_type == VAR_LIST)
14652 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
14653 while (n-- > 0)
14654 if (list_extend(rettv->vval.v_list,
14655 argvars[0].vval.v_list, NULL) == FAIL)
14656 break;
14658 else
14660 p = get_tv_string(&argvars[0]);
14661 rettv->v_type = VAR_STRING;
14662 rettv->vval.v_string = NULL;
14664 slen = (int)STRLEN(p);
14665 len = slen * n;
14666 if (len <= 0)
14667 return;
14669 r = alloc(len + 1);
14670 if (r != NULL)
14672 for (i = 0; i < n; i++)
14673 mch_memmove(r + i * slen, p, (size_t)slen);
14674 r[len] = NUL;
14677 rettv->vval.v_string = r;
14682 * "resolve()" function
14684 static void
14685 f_resolve(argvars, rettv)
14686 typval_T *argvars;
14687 typval_T *rettv;
14689 char_u *p;
14691 p = get_tv_string(&argvars[0]);
14692 #ifdef FEAT_SHORTCUT
14694 char_u *v = NULL;
14696 v = mch_resolve_shortcut(p);
14697 if (v != NULL)
14698 rettv->vval.v_string = v;
14699 else
14700 rettv->vval.v_string = vim_strsave(p);
14702 #else
14703 # ifdef HAVE_READLINK
14705 char_u buf[MAXPATHL + 1];
14706 char_u *cpy;
14707 int len;
14708 char_u *remain = NULL;
14709 char_u *q;
14710 int is_relative_to_current = FALSE;
14711 int has_trailing_pathsep = FALSE;
14712 int limit = 100;
14714 p = vim_strsave(p);
14716 if (p[0] == '.' && (vim_ispathsep(p[1])
14717 || (p[1] == '.' && (vim_ispathsep(p[2])))))
14718 is_relative_to_current = TRUE;
14720 len = STRLEN(p);
14721 if (len > 0 && after_pathsep(p, p + len))
14722 has_trailing_pathsep = TRUE;
14724 q = getnextcomp(p);
14725 if (*q != NUL)
14727 /* Separate the first path component in "p", and keep the
14728 * remainder (beginning with the path separator). */
14729 remain = vim_strsave(q - 1);
14730 q[-1] = NUL;
14733 for (;;)
14735 for (;;)
14737 len = readlink((char *)p, (char *)buf, MAXPATHL);
14738 if (len <= 0)
14739 break;
14740 buf[len] = NUL;
14742 if (limit-- == 0)
14744 vim_free(p);
14745 vim_free(remain);
14746 EMSG(_("E655: Too many symbolic links (cycle?)"));
14747 rettv->vval.v_string = NULL;
14748 goto fail;
14751 /* Ensure that the result will have a trailing path separator
14752 * if the argument has one. */
14753 if (remain == NULL && has_trailing_pathsep)
14754 add_pathsep(buf);
14756 /* Separate the first path component in the link value and
14757 * concatenate the remainders. */
14758 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
14759 if (*q != NUL)
14761 if (remain == NULL)
14762 remain = vim_strsave(q - 1);
14763 else
14765 cpy = concat_str(q - 1, remain);
14766 if (cpy != NULL)
14768 vim_free(remain);
14769 remain = cpy;
14772 q[-1] = NUL;
14775 q = gettail(p);
14776 if (q > p && *q == NUL)
14778 /* Ignore trailing path separator. */
14779 q[-1] = NUL;
14780 q = gettail(p);
14782 if (q > p && !mch_isFullName(buf))
14784 /* symlink is relative to directory of argument */
14785 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
14786 if (cpy != NULL)
14788 STRCPY(cpy, p);
14789 STRCPY(gettail(cpy), buf);
14790 vim_free(p);
14791 p = cpy;
14794 else
14796 vim_free(p);
14797 p = vim_strsave(buf);
14801 if (remain == NULL)
14802 break;
14804 /* Append the first path component of "remain" to "p". */
14805 q = getnextcomp(remain + 1);
14806 len = q - remain - (*q != NUL);
14807 cpy = vim_strnsave(p, STRLEN(p) + len);
14808 if (cpy != NULL)
14810 STRNCAT(cpy, remain, len);
14811 vim_free(p);
14812 p = cpy;
14814 /* Shorten "remain". */
14815 if (*q != NUL)
14816 STRMOVE(remain, q - 1);
14817 else
14819 vim_free(remain);
14820 remain = NULL;
14824 /* If the result is a relative path name, make it explicitly relative to
14825 * the current directory if and only if the argument had this form. */
14826 if (!vim_ispathsep(*p))
14828 if (is_relative_to_current
14829 && *p != NUL
14830 && !(p[0] == '.'
14831 && (p[1] == NUL
14832 || vim_ispathsep(p[1])
14833 || (p[1] == '.'
14834 && (p[2] == NUL
14835 || vim_ispathsep(p[2]))))))
14837 /* Prepend "./". */
14838 cpy = concat_str((char_u *)"./", p);
14839 if (cpy != NULL)
14841 vim_free(p);
14842 p = cpy;
14845 else if (!is_relative_to_current)
14847 /* Strip leading "./". */
14848 q = p;
14849 while (q[0] == '.' && vim_ispathsep(q[1]))
14850 q += 2;
14851 if (q > p)
14852 STRMOVE(p, p + 2);
14856 /* Ensure that the result will have no trailing path separator
14857 * if the argument had none. But keep "/" or "//". */
14858 if (!has_trailing_pathsep)
14860 q = p + STRLEN(p);
14861 if (after_pathsep(p, q))
14862 *gettail_sep(p) = NUL;
14865 rettv->vval.v_string = p;
14867 # else
14868 rettv->vval.v_string = vim_strsave(p);
14869 # endif
14870 #endif
14872 simplify_filename(rettv->vval.v_string);
14874 #ifdef HAVE_READLINK
14875 fail:
14876 #endif
14877 rettv->v_type = VAR_STRING;
14881 * "reverse({list})" function
14883 static void
14884 f_reverse(argvars, rettv)
14885 typval_T *argvars;
14886 typval_T *rettv;
14888 list_T *l;
14889 listitem_T *li, *ni;
14891 if (argvars[0].v_type != VAR_LIST)
14892 EMSG2(_(e_listarg), "reverse()");
14893 else if ((l = argvars[0].vval.v_list) != NULL
14894 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
14896 li = l->lv_last;
14897 l->lv_first = l->lv_last = NULL;
14898 l->lv_len = 0;
14899 while (li != NULL)
14901 ni = li->li_prev;
14902 list_append(l, li);
14903 li = ni;
14905 rettv->vval.v_list = l;
14906 rettv->v_type = VAR_LIST;
14907 ++l->lv_refcount;
14908 l->lv_idx = l->lv_len - l->lv_idx - 1;
14912 #define SP_NOMOVE 0x01 /* don't move cursor */
14913 #define SP_REPEAT 0x02 /* repeat to find outer pair */
14914 #define SP_RETCOUNT 0x04 /* return matchcount */
14915 #define SP_SETPCMARK 0x08 /* set previous context mark */
14916 #define SP_START 0x10 /* accept match at start position */
14917 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
14918 #define SP_END 0x40 /* leave cursor at end of match */
14920 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
14923 * Get flags for a search function.
14924 * Possibly sets "p_ws".
14925 * Returns BACKWARD, FORWARD or zero (for an error).
14927 static int
14928 get_search_arg(varp, flagsp)
14929 typval_T *varp;
14930 int *flagsp;
14932 int dir = FORWARD;
14933 char_u *flags;
14934 char_u nbuf[NUMBUFLEN];
14935 int mask;
14937 if (varp->v_type != VAR_UNKNOWN)
14939 flags = get_tv_string_buf_chk(varp, nbuf);
14940 if (flags == NULL)
14941 return 0; /* type error; errmsg already given */
14942 while (*flags != NUL)
14944 switch (*flags)
14946 case 'b': dir = BACKWARD; break;
14947 case 'w': p_ws = TRUE; break;
14948 case 'W': p_ws = FALSE; break;
14949 default: mask = 0;
14950 if (flagsp != NULL)
14951 switch (*flags)
14953 case 'c': mask = SP_START; break;
14954 case 'e': mask = SP_END; break;
14955 case 'm': mask = SP_RETCOUNT; break;
14956 case 'n': mask = SP_NOMOVE; break;
14957 case 'p': mask = SP_SUBPAT; break;
14958 case 'r': mask = SP_REPEAT; break;
14959 case 's': mask = SP_SETPCMARK; break;
14961 if (mask == 0)
14963 EMSG2(_(e_invarg2), flags);
14964 dir = 0;
14966 else
14967 *flagsp |= mask;
14969 if (dir == 0)
14970 break;
14971 ++flags;
14974 return dir;
14978 * Shared by search() and searchpos() functions
14980 static int
14981 search_cmn(argvars, match_pos, flagsp)
14982 typval_T *argvars;
14983 pos_T *match_pos;
14984 int *flagsp;
14986 int flags;
14987 char_u *pat;
14988 pos_T pos;
14989 pos_T save_cursor;
14990 int save_p_ws = p_ws;
14991 int dir;
14992 int retval = 0; /* default: FAIL */
14993 long lnum_stop = 0;
14994 proftime_T tm;
14995 #ifdef FEAT_RELTIME
14996 long time_limit = 0;
14997 #endif
14998 int options = SEARCH_KEEP;
14999 int subpatnum;
15001 pat = get_tv_string(&argvars[0]);
15002 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
15003 if (dir == 0)
15004 goto theend;
15005 flags = *flagsp;
15006 if (flags & SP_START)
15007 options |= SEARCH_START;
15008 if (flags & SP_END)
15009 options |= SEARCH_END;
15011 /* Optional arguments: line number to stop searching and timeout. */
15012 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
15014 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
15015 if (lnum_stop < 0)
15016 goto theend;
15017 #ifdef FEAT_RELTIME
15018 if (argvars[3].v_type != VAR_UNKNOWN)
15020 time_limit = get_tv_number_chk(&argvars[3], NULL);
15021 if (time_limit < 0)
15022 goto theend;
15024 #endif
15027 #ifdef FEAT_RELTIME
15028 /* Set the time limit, if there is one. */
15029 profile_setlimit(time_limit, &tm);
15030 #endif
15033 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
15034 * Check to make sure only those flags are set.
15035 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
15036 * flags cannot be set. Check for that condition also.
15038 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
15039 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
15041 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
15042 goto theend;
15045 pos = save_cursor = curwin->w_cursor;
15046 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15047 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
15048 if (subpatnum != FAIL)
15050 if (flags & SP_SUBPAT)
15051 retval = subpatnum;
15052 else
15053 retval = pos.lnum;
15054 if (flags & SP_SETPCMARK)
15055 setpcmark();
15056 curwin->w_cursor = pos;
15057 if (match_pos != NULL)
15059 /* Store the match cursor position */
15060 match_pos->lnum = pos.lnum;
15061 match_pos->col = pos.col + 1;
15063 /* "/$" will put the cursor after the end of the line, may need to
15064 * correct that here */
15065 check_cursor();
15068 /* If 'n' flag is used: restore cursor position. */
15069 if (flags & SP_NOMOVE)
15070 curwin->w_cursor = save_cursor;
15071 else
15072 curwin->w_set_curswant = TRUE;
15073 theend:
15074 p_ws = save_p_ws;
15076 return retval;
15079 #ifdef FEAT_FLOAT
15081 * "round({float})" function
15083 static void
15084 f_round(argvars, rettv)
15085 typval_T *argvars;
15086 typval_T *rettv;
15088 float_T f;
15090 rettv->v_type = VAR_FLOAT;
15091 if (get_float_arg(argvars, &f) == OK)
15092 /* round() is not in C90, use ceil() or floor() instead. */
15093 rettv->vval.v_float = f > 0 ? floor(f + 0.5) : ceil(f - 0.5);
15094 else
15095 rettv->vval.v_float = 0.0;
15097 #endif
15100 * "search()" function
15102 static void
15103 f_search(argvars, rettv)
15104 typval_T *argvars;
15105 typval_T *rettv;
15107 int flags = 0;
15109 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
15113 * "searchdecl()" function
15115 static void
15116 f_searchdecl(argvars, rettv)
15117 typval_T *argvars;
15118 typval_T *rettv;
15120 int locally = 1;
15121 int thisblock = 0;
15122 int error = FALSE;
15123 char_u *name;
15125 rettv->vval.v_number = 1; /* default: FAIL */
15127 name = get_tv_string_chk(&argvars[0]);
15128 if (argvars[1].v_type != VAR_UNKNOWN)
15130 locally = get_tv_number_chk(&argvars[1], &error) == 0;
15131 if (!error && argvars[2].v_type != VAR_UNKNOWN)
15132 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
15134 if (!error && name != NULL)
15135 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
15136 locally, thisblock, SEARCH_KEEP) == FAIL;
15140 * Used by searchpair() and searchpairpos()
15142 static int
15143 searchpair_cmn(argvars, match_pos)
15144 typval_T *argvars;
15145 pos_T *match_pos;
15147 char_u *spat, *mpat, *epat;
15148 char_u *skip;
15149 int save_p_ws = p_ws;
15150 int dir;
15151 int flags = 0;
15152 char_u nbuf1[NUMBUFLEN];
15153 char_u nbuf2[NUMBUFLEN];
15154 char_u nbuf3[NUMBUFLEN];
15155 int retval = 0; /* default: FAIL */
15156 long lnum_stop = 0;
15157 long time_limit = 0;
15159 /* Get the three pattern arguments: start, middle, end. */
15160 spat = get_tv_string_chk(&argvars[0]);
15161 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
15162 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
15163 if (spat == NULL || mpat == NULL || epat == NULL)
15164 goto theend; /* type error */
15166 /* Handle the optional fourth argument: flags */
15167 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
15168 if (dir == 0)
15169 goto theend;
15171 /* Don't accept SP_END or SP_SUBPAT.
15172 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
15174 if ((flags & (SP_END | SP_SUBPAT)) != 0
15175 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
15177 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
15178 goto theend;
15181 /* Using 'r' implies 'W', otherwise it doesn't work. */
15182 if (flags & SP_REPEAT)
15183 p_ws = FALSE;
15185 /* Optional fifth argument: skip expression */
15186 if (argvars[3].v_type == VAR_UNKNOWN
15187 || argvars[4].v_type == VAR_UNKNOWN)
15188 skip = (char_u *)"";
15189 else
15191 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
15192 if (argvars[5].v_type != VAR_UNKNOWN)
15194 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
15195 if (lnum_stop < 0)
15196 goto theend;
15197 #ifdef FEAT_RELTIME
15198 if (argvars[6].v_type != VAR_UNKNOWN)
15200 time_limit = get_tv_number_chk(&argvars[6], NULL);
15201 if (time_limit < 0)
15202 goto theend;
15204 #endif
15207 if (skip == NULL)
15208 goto theend; /* type error */
15210 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
15211 match_pos, lnum_stop, time_limit);
15213 theend:
15214 p_ws = save_p_ws;
15216 return retval;
15220 * "searchpair()" function
15222 static void
15223 f_searchpair(argvars, rettv)
15224 typval_T *argvars;
15225 typval_T *rettv;
15227 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
15231 * "searchpairpos()" function
15233 static void
15234 f_searchpairpos(argvars, rettv)
15235 typval_T *argvars;
15236 typval_T *rettv;
15238 pos_T match_pos;
15239 int lnum = 0;
15240 int col = 0;
15242 if (rettv_list_alloc(rettv) == FAIL)
15243 return;
15245 if (searchpair_cmn(argvars, &match_pos) > 0)
15247 lnum = match_pos.lnum;
15248 col = match_pos.col;
15251 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15252 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15256 * Search for a start/middle/end thing.
15257 * Used by searchpair(), see its documentation for the details.
15258 * Returns 0 or -1 for no match,
15260 long
15261 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
15262 lnum_stop, time_limit)
15263 char_u *spat; /* start pattern */
15264 char_u *mpat; /* middle pattern */
15265 char_u *epat; /* end pattern */
15266 int dir; /* BACKWARD or FORWARD */
15267 char_u *skip; /* skip expression */
15268 int flags; /* SP_SETPCMARK and other SP_ values */
15269 pos_T *match_pos;
15270 linenr_T lnum_stop; /* stop at this line if not zero */
15271 long time_limit; /* stop after this many msec */
15273 char_u *save_cpo;
15274 char_u *pat, *pat2 = NULL, *pat3 = NULL;
15275 long retval = 0;
15276 pos_T pos;
15277 pos_T firstpos;
15278 pos_T foundpos;
15279 pos_T save_cursor;
15280 pos_T save_pos;
15281 int n;
15282 int r;
15283 int nest = 1;
15284 int err;
15285 int options = SEARCH_KEEP;
15286 proftime_T tm;
15288 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15289 save_cpo = p_cpo;
15290 p_cpo = empty_option;
15292 #ifdef FEAT_RELTIME
15293 /* Set the time limit, if there is one. */
15294 profile_setlimit(time_limit, &tm);
15295 #endif
15297 /* Make two search patterns: start/end (pat2, for in nested pairs) and
15298 * start/middle/end (pat3, for the top pair). */
15299 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
15300 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
15301 if (pat2 == NULL || pat3 == NULL)
15302 goto theend;
15303 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
15304 if (*mpat == NUL)
15305 STRCPY(pat3, pat2);
15306 else
15307 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
15308 spat, epat, mpat);
15309 if (flags & SP_START)
15310 options |= SEARCH_START;
15312 save_cursor = curwin->w_cursor;
15313 pos = curwin->w_cursor;
15314 clearpos(&firstpos);
15315 clearpos(&foundpos);
15316 pat = pat3;
15317 for (;;)
15319 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15320 options, RE_SEARCH, lnum_stop, &tm);
15321 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
15322 /* didn't find it or found the first match again: FAIL */
15323 break;
15325 if (firstpos.lnum == 0)
15326 firstpos = pos;
15327 if (equalpos(pos, foundpos))
15329 /* Found the same position again. Can happen with a pattern that
15330 * has "\zs" at the end and searching backwards. Advance one
15331 * character and try again. */
15332 if (dir == BACKWARD)
15333 decl(&pos);
15334 else
15335 incl(&pos);
15337 foundpos = pos;
15339 /* clear the start flag to avoid getting stuck here */
15340 options &= ~SEARCH_START;
15342 /* If the skip pattern matches, ignore this match. */
15343 if (*skip != NUL)
15345 save_pos = curwin->w_cursor;
15346 curwin->w_cursor = pos;
15347 r = eval_to_bool(skip, &err, NULL, FALSE);
15348 curwin->w_cursor = save_pos;
15349 if (err)
15351 /* Evaluating {skip} caused an error, break here. */
15352 curwin->w_cursor = save_cursor;
15353 retval = -1;
15354 break;
15356 if (r)
15357 continue;
15360 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
15362 /* Found end when searching backwards or start when searching
15363 * forward: nested pair. */
15364 ++nest;
15365 pat = pat2; /* nested, don't search for middle */
15367 else
15369 /* Found end when searching forward or start when searching
15370 * backward: end of (nested) pair; or found middle in outer pair. */
15371 if (--nest == 1)
15372 pat = pat3; /* outer level, search for middle */
15375 if (nest == 0)
15377 /* Found the match: return matchcount or line number. */
15378 if (flags & SP_RETCOUNT)
15379 ++retval;
15380 else
15381 retval = pos.lnum;
15382 if (flags & SP_SETPCMARK)
15383 setpcmark();
15384 curwin->w_cursor = pos;
15385 if (!(flags & SP_REPEAT))
15386 break;
15387 nest = 1; /* search for next unmatched */
15391 if (match_pos != NULL)
15393 /* Store the match cursor position */
15394 match_pos->lnum = curwin->w_cursor.lnum;
15395 match_pos->col = curwin->w_cursor.col + 1;
15398 /* If 'n' flag is used or search failed: restore cursor position. */
15399 if ((flags & SP_NOMOVE) || retval == 0)
15400 curwin->w_cursor = save_cursor;
15402 theend:
15403 vim_free(pat2);
15404 vim_free(pat3);
15405 if (p_cpo == empty_option)
15406 p_cpo = save_cpo;
15407 else
15408 /* Darn, evaluating the {skip} expression changed the value. */
15409 free_string_option(save_cpo);
15411 return retval;
15415 * "searchpos()" function
15417 static void
15418 f_searchpos(argvars, rettv)
15419 typval_T *argvars;
15420 typval_T *rettv;
15422 pos_T match_pos;
15423 int lnum = 0;
15424 int col = 0;
15425 int n;
15426 int flags = 0;
15428 if (rettv_list_alloc(rettv) == FAIL)
15429 return;
15431 n = search_cmn(argvars, &match_pos, &flags);
15432 if (n > 0)
15434 lnum = match_pos.lnum;
15435 col = match_pos.col;
15438 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15439 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15440 if (flags & SP_SUBPAT)
15441 list_append_number(rettv->vval.v_list, (varnumber_T)n);
15445 static void
15446 f_server2client(argvars, rettv)
15447 typval_T *argvars UNUSED;
15448 typval_T *rettv;
15450 #ifdef FEAT_CLIENTSERVER
15451 char_u buf[NUMBUFLEN];
15452 char_u *server = get_tv_string_chk(&argvars[0]);
15453 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
15455 rettv->vval.v_number = -1;
15456 if (server == NULL || reply == NULL)
15457 return;
15458 if (check_restricted() || check_secure())
15459 return;
15460 # ifdef FEAT_X11
15461 if (check_connection() == FAIL)
15462 return;
15463 # endif
15465 if (serverSendReply(server, reply) < 0)
15467 EMSG(_("E258: Unable to send to client"));
15468 return;
15470 rettv->vval.v_number = 0;
15471 #else
15472 rettv->vval.v_number = -1;
15473 #endif
15476 static void
15477 f_serverlist(argvars, rettv)
15478 typval_T *argvars UNUSED;
15479 typval_T *rettv;
15481 char_u *r = NULL;
15483 #ifdef FEAT_CLIENTSERVER
15484 # ifdef WIN32
15485 r = serverGetVimNames();
15486 # else
15487 make_connection();
15488 if (X_DISPLAY != NULL)
15489 r = serverGetVimNames(X_DISPLAY);
15490 # endif
15491 #endif
15492 rettv->v_type = VAR_STRING;
15493 rettv->vval.v_string = r;
15497 * "setbufvar()" function
15499 static void
15500 f_setbufvar(argvars, rettv)
15501 typval_T *argvars;
15502 typval_T *rettv UNUSED;
15504 buf_T *buf;
15505 aco_save_T aco;
15506 char_u *varname, *bufvarname;
15507 typval_T *varp;
15508 char_u nbuf[NUMBUFLEN];
15510 if (check_restricted() || check_secure())
15511 return;
15512 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
15513 varname = get_tv_string_chk(&argvars[1]);
15514 buf = get_buf_tv(&argvars[0]);
15515 varp = &argvars[2];
15517 if (buf != NULL && varname != NULL && varp != NULL)
15519 /* set curbuf to be our buf, temporarily */
15520 aucmd_prepbuf(&aco, buf);
15522 if (*varname == '&')
15524 long numval;
15525 char_u *strval;
15526 int error = FALSE;
15528 ++varname;
15529 numval = get_tv_number_chk(varp, &error);
15530 strval = get_tv_string_buf_chk(varp, nbuf);
15531 if (!error && strval != NULL)
15532 set_option_value(varname, numval, strval, OPT_LOCAL);
15534 else
15536 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
15537 if (bufvarname != NULL)
15539 STRCPY(bufvarname, "b:");
15540 STRCPY(bufvarname + 2, varname);
15541 set_var(bufvarname, varp, TRUE);
15542 vim_free(bufvarname);
15546 /* reset notion of buffer */
15547 aucmd_restbuf(&aco);
15552 * "setcmdpos()" function
15554 static void
15555 f_setcmdpos(argvars, rettv)
15556 typval_T *argvars;
15557 typval_T *rettv;
15559 int pos = (int)get_tv_number(&argvars[0]) - 1;
15561 if (pos >= 0)
15562 rettv->vval.v_number = set_cmdline_pos(pos);
15566 * "setline()" function
15568 static void
15569 f_setline(argvars, rettv)
15570 typval_T *argvars;
15571 typval_T *rettv;
15573 linenr_T lnum;
15574 char_u *line = NULL;
15575 list_T *l = NULL;
15576 listitem_T *li = NULL;
15577 long added = 0;
15578 linenr_T lcount = curbuf->b_ml.ml_line_count;
15580 lnum = get_tv_lnum(&argvars[0]);
15581 if (argvars[1].v_type == VAR_LIST)
15583 l = argvars[1].vval.v_list;
15584 li = l->lv_first;
15586 else
15587 line = get_tv_string_chk(&argvars[1]);
15589 /* default result is zero == OK */
15590 for (;;)
15592 if (l != NULL)
15594 /* list argument, get next string */
15595 if (li == NULL)
15596 break;
15597 line = get_tv_string_chk(&li->li_tv);
15598 li = li->li_next;
15601 rettv->vval.v_number = 1; /* FAIL */
15602 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
15603 break;
15604 if (lnum <= curbuf->b_ml.ml_line_count)
15606 /* existing line, replace it */
15607 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
15609 changed_bytes(lnum, 0);
15610 if (lnum == curwin->w_cursor.lnum)
15611 check_cursor_col();
15612 rettv->vval.v_number = 0; /* OK */
15615 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
15617 /* lnum is one past the last line, append the line */
15618 ++added;
15619 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
15620 rettv->vval.v_number = 0; /* OK */
15623 if (l == NULL) /* only one string argument */
15624 break;
15625 ++lnum;
15628 if (added > 0)
15629 appended_lines_mark(lcount, added);
15632 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
15635 * Used by "setqflist()" and "setloclist()" functions
15637 static void
15638 set_qf_ll_list(wp, list_arg, action_arg, rettv)
15639 win_T *wp UNUSED;
15640 typval_T *list_arg UNUSED;
15641 typval_T *action_arg UNUSED;
15642 typval_T *rettv;
15644 #ifdef FEAT_QUICKFIX
15645 char_u *act;
15646 int action = ' ';
15647 #endif
15649 rettv->vval.v_number = -1;
15651 #ifdef FEAT_QUICKFIX
15652 if (list_arg->v_type != VAR_LIST)
15653 EMSG(_(e_listreq));
15654 else
15656 list_T *l = list_arg->vval.v_list;
15658 if (action_arg->v_type == VAR_STRING)
15660 act = get_tv_string_chk(action_arg);
15661 if (act == NULL)
15662 return; /* type error; errmsg already given */
15663 if (*act == 'a' || *act == 'r')
15664 action = *act;
15667 if (l != NULL && set_errorlist(wp, l, action) == OK)
15668 rettv->vval.v_number = 0;
15670 #endif
15674 * "setloclist()" function
15676 static void
15677 f_setloclist(argvars, rettv)
15678 typval_T *argvars;
15679 typval_T *rettv;
15681 win_T *win;
15683 rettv->vval.v_number = -1;
15685 win = find_win_by_nr(&argvars[0], NULL);
15686 if (win != NULL)
15687 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
15691 * "setmatches()" function
15693 static void
15694 f_setmatches(argvars, rettv)
15695 typval_T *argvars;
15696 typval_T *rettv;
15698 #ifdef FEAT_SEARCH_EXTRA
15699 list_T *l;
15700 listitem_T *li;
15701 dict_T *d;
15703 rettv->vval.v_number = -1;
15704 if (argvars[0].v_type != VAR_LIST)
15706 EMSG(_(e_listreq));
15707 return;
15709 if ((l = argvars[0].vval.v_list) != NULL)
15712 /* To some extent make sure that we are dealing with a list from
15713 * "getmatches()". */
15714 li = l->lv_first;
15715 while (li != NULL)
15717 if (li->li_tv.v_type != VAR_DICT
15718 || (d = li->li_tv.vval.v_dict) == NULL)
15720 EMSG(_(e_invarg));
15721 return;
15723 if (!(dict_find(d, (char_u *)"group", -1) != NULL
15724 && dict_find(d, (char_u *)"pattern", -1) != NULL
15725 && dict_find(d, (char_u *)"priority", -1) != NULL
15726 && dict_find(d, (char_u *)"id", -1) != NULL))
15728 EMSG(_(e_invarg));
15729 return;
15731 li = li->li_next;
15734 clear_matches(curwin);
15735 li = l->lv_first;
15736 while (li != NULL)
15738 d = li->li_tv.vval.v_dict;
15739 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
15740 get_dict_string(d, (char_u *)"pattern", FALSE),
15741 (int)get_dict_number(d, (char_u *)"priority"),
15742 (int)get_dict_number(d, (char_u *)"id"));
15743 li = li->li_next;
15745 rettv->vval.v_number = 0;
15747 #endif
15751 * "setpos()" function
15753 static void
15754 f_setpos(argvars, rettv)
15755 typval_T *argvars;
15756 typval_T *rettv;
15758 pos_T pos;
15759 int fnum;
15760 char_u *name;
15762 rettv->vval.v_number = -1;
15763 name = get_tv_string_chk(argvars);
15764 if (name != NULL)
15766 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
15768 if (--pos.col < 0)
15769 pos.col = 0;
15770 if (name[0] == '.' && name[1] == NUL)
15772 /* set cursor */
15773 if (fnum == curbuf->b_fnum)
15775 curwin->w_cursor = pos;
15776 check_cursor();
15777 rettv->vval.v_number = 0;
15779 else
15780 EMSG(_(e_invarg));
15782 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
15784 /* set mark */
15785 if (setmark_pos(name[1], &pos, fnum) == OK)
15786 rettv->vval.v_number = 0;
15788 else
15789 EMSG(_(e_invarg));
15795 * "setqflist()" function
15797 static void
15798 f_setqflist(argvars, rettv)
15799 typval_T *argvars;
15800 typval_T *rettv;
15802 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
15806 * "setreg()" function
15808 static void
15809 f_setreg(argvars, rettv)
15810 typval_T *argvars;
15811 typval_T *rettv;
15813 int regname;
15814 char_u *strregname;
15815 char_u *stropt;
15816 char_u *strval;
15817 int append;
15818 char_u yank_type;
15819 long block_len;
15821 block_len = -1;
15822 yank_type = MAUTO;
15823 append = FALSE;
15825 strregname = get_tv_string_chk(argvars);
15826 rettv->vval.v_number = 1; /* FAIL is default */
15828 if (strregname == NULL)
15829 return; /* type error; errmsg already given */
15830 regname = *strregname;
15831 if (regname == 0 || regname == '@')
15832 regname = '"';
15833 else if (regname == '=')
15834 return;
15836 if (argvars[2].v_type != VAR_UNKNOWN)
15838 stropt = get_tv_string_chk(&argvars[2]);
15839 if (stropt == NULL)
15840 return; /* type error */
15841 for (; *stropt != NUL; ++stropt)
15842 switch (*stropt)
15844 case 'a': case 'A': /* append */
15845 append = TRUE;
15846 break;
15847 case 'v': case 'c': /* character-wise selection */
15848 yank_type = MCHAR;
15849 break;
15850 case 'V': case 'l': /* line-wise selection */
15851 yank_type = MLINE;
15852 break;
15853 #ifdef FEAT_VISUAL
15854 case 'b': case Ctrl_V: /* block-wise selection */
15855 yank_type = MBLOCK;
15856 if (VIM_ISDIGIT(stropt[1]))
15858 ++stropt;
15859 block_len = getdigits(&stropt) - 1;
15860 --stropt;
15862 break;
15863 #endif
15867 strval = get_tv_string_chk(&argvars[1]);
15868 if (strval != NULL)
15869 write_reg_contents_ex(regname, strval, -1,
15870 append, yank_type, block_len);
15871 rettv->vval.v_number = 0;
15875 * "settabwinvar()" function
15877 static void
15878 f_settabwinvar(argvars, rettv)
15879 typval_T *argvars;
15880 typval_T *rettv;
15882 setwinvar(argvars, rettv, 1);
15886 * "setwinvar()" function
15888 static void
15889 f_setwinvar(argvars, rettv)
15890 typval_T *argvars;
15891 typval_T *rettv;
15893 setwinvar(argvars, rettv, 0);
15897 * "setwinvar()" and "settabwinvar()" functions
15899 static void
15900 setwinvar(argvars, rettv, off)
15901 typval_T *argvars;
15902 typval_T *rettv UNUSED;
15903 int off;
15905 win_T *win;
15906 #ifdef FEAT_WINDOWS
15907 win_T *save_curwin;
15908 tabpage_T *save_curtab;
15909 #endif
15910 char_u *varname, *winvarname;
15911 typval_T *varp;
15912 char_u nbuf[NUMBUFLEN];
15913 tabpage_T *tp;
15915 if (check_restricted() || check_secure())
15916 return;
15918 #ifdef FEAT_WINDOWS
15919 if (off == 1)
15920 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
15921 else
15922 tp = curtab;
15923 #endif
15924 win = find_win_by_nr(&argvars[off], tp);
15925 varname = get_tv_string_chk(&argvars[off + 1]);
15926 varp = &argvars[off + 2];
15928 if (win != NULL && varname != NULL && varp != NULL)
15930 #ifdef FEAT_WINDOWS
15931 /* set curwin to be our win, temporarily */
15932 save_curwin = curwin;
15933 save_curtab = curtab;
15934 goto_tabpage_tp(tp);
15935 if (!win_valid(win))
15936 return;
15937 curwin = win;
15938 curbuf = curwin->w_buffer;
15939 #endif
15941 if (*varname == '&')
15943 long numval;
15944 char_u *strval;
15945 int error = FALSE;
15947 ++varname;
15948 numval = get_tv_number_chk(varp, &error);
15949 strval = get_tv_string_buf_chk(varp, nbuf);
15950 if (!error && strval != NULL)
15951 set_option_value(varname, numval, strval, OPT_LOCAL);
15953 else
15955 winvarname = alloc((unsigned)STRLEN(varname) + 3);
15956 if (winvarname != NULL)
15958 STRCPY(winvarname, "w:");
15959 STRCPY(winvarname + 2, varname);
15960 set_var(winvarname, varp, TRUE);
15961 vim_free(winvarname);
15965 #ifdef FEAT_WINDOWS
15966 /* Restore current tabpage and window, if still valid (autocomands can
15967 * make them invalid). */
15968 if (valid_tabpage(save_curtab))
15969 goto_tabpage_tp(save_curtab);
15970 if (win_valid(save_curwin))
15972 curwin = save_curwin;
15973 curbuf = curwin->w_buffer;
15975 #endif
15980 * "shellescape({string})" function
15982 static void
15983 f_shellescape(argvars, rettv)
15984 typval_T *argvars;
15985 typval_T *rettv;
15987 rettv->vval.v_string = vim_strsave_shellescape(
15988 get_tv_string(&argvars[0]), non_zero_arg(&argvars[1]));
15989 rettv->v_type = VAR_STRING;
15993 * "simplify()" function
15995 static void
15996 f_simplify(argvars, rettv)
15997 typval_T *argvars;
15998 typval_T *rettv;
16000 char_u *p;
16002 p = get_tv_string(&argvars[0]);
16003 rettv->vval.v_string = vim_strsave(p);
16004 simplify_filename(rettv->vval.v_string); /* simplify in place */
16005 rettv->v_type = VAR_STRING;
16008 #ifdef FEAT_FLOAT
16010 * "sin()" function
16012 static void
16013 f_sin(argvars, rettv)
16014 typval_T *argvars;
16015 typval_T *rettv;
16017 float_T f;
16019 rettv->v_type = VAR_FLOAT;
16020 if (get_float_arg(argvars, &f) == OK)
16021 rettv->vval.v_float = sin(f);
16022 else
16023 rettv->vval.v_float = 0.0;
16025 #endif
16027 static int
16028 #ifdef __BORLANDC__
16029 _RTLENTRYF
16030 #endif
16031 item_compare __ARGS((const void *s1, const void *s2));
16032 static int
16033 #ifdef __BORLANDC__
16034 _RTLENTRYF
16035 #endif
16036 item_compare2 __ARGS((const void *s1, const void *s2));
16038 static int item_compare_ic;
16039 static char_u *item_compare_func;
16040 static int item_compare_func_err;
16041 #define ITEM_COMPARE_FAIL 999
16044 * Compare functions for f_sort() below.
16046 static int
16047 #ifdef __BORLANDC__
16048 _RTLENTRYF
16049 #endif
16050 item_compare(s1, s2)
16051 const void *s1;
16052 const void *s2;
16054 char_u *p1, *p2;
16055 char_u *tofree1, *tofree2;
16056 int res;
16057 char_u numbuf1[NUMBUFLEN];
16058 char_u numbuf2[NUMBUFLEN];
16060 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
16061 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
16062 if (p1 == NULL)
16063 p1 = (char_u *)"";
16064 if (p2 == NULL)
16065 p2 = (char_u *)"";
16066 if (item_compare_ic)
16067 res = STRICMP(p1, p2);
16068 else
16069 res = STRCMP(p1, p2);
16070 vim_free(tofree1);
16071 vim_free(tofree2);
16072 return res;
16075 static int
16076 #ifdef __BORLANDC__
16077 _RTLENTRYF
16078 #endif
16079 item_compare2(s1, s2)
16080 const void *s1;
16081 const void *s2;
16083 int res;
16084 typval_T rettv;
16085 typval_T argv[3];
16086 int dummy;
16088 /* shortcut after failure in previous call; compare all items equal */
16089 if (item_compare_func_err)
16090 return 0;
16092 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
16093 * in the copy without changing the original list items. */
16094 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
16095 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
16097 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
16098 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
16099 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
16100 clear_tv(&argv[0]);
16101 clear_tv(&argv[1]);
16103 if (res == FAIL)
16104 res = ITEM_COMPARE_FAIL;
16105 else
16106 res = get_tv_number_chk(&rettv, &item_compare_func_err);
16107 if (item_compare_func_err)
16108 res = ITEM_COMPARE_FAIL; /* return value has wrong type */
16109 clear_tv(&rettv);
16110 return res;
16114 * "sort({list})" function
16116 static void
16117 f_sort(argvars, rettv)
16118 typval_T *argvars;
16119 typval_T *rettv;
16121 list_T *l;
16122 listitem_T *li;
16123 listitem_T **ptrs;
16124 long len;
16125 long i;
16127 if (argvars[0].v_type != VAR_LIST)
16128 EMSG2(_(e_listarg), "sort()");
16129 else
16131 l = argvars[0].vval.v_list;
16132 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
16133 return;
16134 rettv->vval.v_list = l;
16135 rettv->v_type = VAR_LIST;
16136 ++l->lv_refcount;
16138 len = list_len(l);
16139 if (len <= 1)
16140 return; /* short list sorts pretty quickly */
16142 item_compare_ic = FALSE;
16143 item_compare_func = NULL;
16144 if (argvars[1].v_type != VAR_UNKNOWN)
16146 if (argvars[1].v_type == VAR_FUNC)
16147 item_compare_func = argvars[1].vval.v_string;
16148 else
16150 int error = FALSE;
16152 i = get_tv_number_chk(&argvars[1], &error);
16153 if (error)
16154 return; /* type error; errmsg already given */
16155 if (i == 1)
16156 item_compare_ic = TRUE;
16157 else
16158 item_compare_func = get_tv_string(&argvars[1]);
16162 /* Make an array with each entry pointing to an item in the List. */
16163 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
16164 if (ptrs == NULL)
16165 return;
16166 i = 0;
16167 for (li = l->lv_first; li != NULL; li = li->li_next)
16168 ptrs[i++] = li;
16170 item_compare_func_err = FALSE;
16171 /* test the compare function */
16172 if (item_compare_func != NULL
16173 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
16174 == ITEM_COMPARE_FAIL)
16175 EMSG(_("E702: Sort compare function failed"));
16176 else
16178 /* Sort the array with item pointers. */
16179 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
16180 item_compare_func == NULL ? item_compare : item_compare2);
16182 if (!item_compare_func_err)
16184 /* Clear the List and append the items in the sorted order. */
16185 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
16186 l->lv_len = 0;
16187 for (i = 0; i < len; ++i)
16188 list_append(l, ptrs[i]);
16192 vim_free(ptrs);
16197 * "soundfold({word})" function
16199 static void
16200 f_soundfold(argvars, rettv)
16201 typval_T *argvars;
16202 typval_T *rettv;
16204 char_u *s;
16206 rettv->v_type = VAR_STRING;
16207 s = get_tv_string(&argvars[0]);
16208 #ifdef FEAT_SPELL
16209 rettv->vval.v_string = eval_soundfold(s);
16210 #else
16211 rettv->vval.v_string = vim_strsave(s);
16212 #endif
16216 * "spellbadword()" function
16218 static void
16219 f_spellbadword(argvars, rettv)
16220 typval_T *argvars UNUSED;
16221 typval_T *rettv;
16223 char_u *word = (char_u *)"";
16224 hlf_T attr = HLF_COUNT;
16225 int len = 0;
16227 if (rettv_list_alloc(rettv) == FAIL)
16228 return;
16230 #ifdef FEAT_SPELL
16231 if (argvars[0].v_type == VAR_UNKNOWN)
16233 /* Find the start and length of the badly spelled word. */
16234 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
16235 if (len != 0)
16236 word = ml_get_cursor();
16238 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16240 char_u *str = get_tv_string_chk(&argvars[0]);
16241 int capcol = -1;
16243 if (str != NULL)
16245 /* Check the argument for spelling. */
16246 while (*str != NUL)
16248 len = spell_check(curwin, str, &attr, &capcol, FALSE);
16249 if (attr != HLF_COUNT)
16251 word = str;
16252 break;
16254 str += len;
16258 #endif
16260 list_append_string(rettv->vval.v_list, word, len);
16261 list_append_string(rettv->vval.v_list, (char_u *)(
16262 attr == HLF_SPB ? "bad" :
16263 attr == HLF_SPR ? "rare" :
16264 attr == HLF_SPL ? "local" :
16265 attr == HLF_SPC ? "caps" :
16266 ""), -1);
16270 * "spellsuggest()" function
16272 static void
16273 f_spellsuggest(argvars, rettv)
16274 typval_T *argvars UNUSED;
16275 typval_T *rettv;
16277 #ifdef FEAT_SPELL
16278 char_u *str;
16279 int typeerr = FALSE;
16280 int maxcount;
16281 garray_T ga;
16282 int i;
16283 listitem_T *li;
16284 int need_capital = FALSE;
16285 #endif
16287 if (rettv_list_alloc(rettv) == FAIL)
16288 return;
16290 #ifdef FEAT_SPELL
16291 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16293 str = get_tv_string(&argvars[0]);
16294 if (argvars[1].v_type != VAR_UNKNOWN)
16296 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
16297 if (maxcount <= 0)
16298 return;
16299 if (argvars[2].v_type != VAR_UNKNOWN)
16301 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
16302 if (typeerr)
16303 return;
16306 else
16307 maxcount = 25;
16309 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
16311 for (i = 0; i < ga.ga_len; ++i)
16313 str = ((char_u **)ga.ga_data)[i];
16315 li = listitem_alloc();
16316 if (li == NULL)
16317 vim_free(str);
16318 else
16320 li->li_tv.v_type = VAR_STRING;
16321 li->li_tv.v_lock = 0;
16322 li->li_tv.vval.v_string = str;
16323 list_append(rettv->vval.v_list, li);
16326 ga_clear(&ga);
16328 #endif
16331 static void
16332 f_split(argvars, rettv)
16333 typval_T *argvars;
16334 typval_T *rettv;
16336 char_u *str;
16337 char_u *end;
16338 char_u *pat = NULL;
16339 regmatch_T regmatch;
16340 char_u patbuf[NUMBUFLEN];
16341 char_u *save_cpo;
16342 int match;
16343 colnr_T col = 0;
16344 int keepempty = FALSE;
16345 int typeerr = FALSE;
16347 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
16348 save_cpo = p_cpo;
16349 p_cpo = (char_u *)"";
16351 str = get_tv_string(&argvars[0]);
16352 if (argvars[1].v_type != VAR_UNKNOWN)
16354 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16355 if (pat == NULL)
16356 typeerr = TRUE;
16357 if (argvars[2].v_type != VAR_UNKNOWN)
16358 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
16360 if (pat == NULL || *pat == NUL)
16361 pat = (char_u *)"[\\x01- ]\\+";
16363 if (rettv_list_alloc(rettv) == FAIL)
16364 return;
16365 if (typeerr)
16366 return;
16368 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
16369 if (regmatch.regprog != NULL)
16371 regmatch.rm_ic = FALSE;
16372 while (*str != NUL || keepempty)
16374 if (*str == NUL)
16375 match = FALSE; /* empty item at the end */
16376 else
16377 match = vim_regexec_nl(&regmatch, str, col);
16378 if (match)
16379 end = regmatch.startp[0];
16380 else
16381 end = str + STRLEN(str);
16382 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
16383 && *str != NUL && match && end < regmatch.endp[0]))
16385 if (list_append_string(rettv->vval.v_list, str,
16386 (int)(end - str)) == FAIL)
16387 break;
16389 if (!match)
16390 break;
16391 /* Advance to just after the match. */
16392 if (regmatch.endp[0] > str)
16393 col = 0;
16394 else
16396 /* Don't get stuck at the same match. */
16397 #ifdef FEAT_MBYTE
16398 col = (*mb_ptr2len)(regmatch.endp[0]);
16399 #else
16400 col = 1;
16401 #endif
16403 str = regmatch.endp[0];
16406 vim_free(regmatch.regprog);
16409 p_cpo = save_cpo;
16412 #ifdef FEAT_FLOAT
16414 * "sqrt()" function
16416 static void
16417 f_sqrt(argvars, rettv)
16418 typval_T *argvars;
16419 typval_T *rettv;
16421 float_T f;
16423 rettv->v_type = VAR_FLOAT;
16424 if (get_float_arg(argvars, &f) == OK)
16425 rettv->vval.v_float = sqrt(f);
16426 else
16427 rettv->vval.v_float = 0.0;
16431 * "str2float()" function
16433 static void
16434 f_str2float(argvars, rettv)
16435 typval_T *argvars;
16436 typval_T *rettv;
16438 char_u *p = skipwhite(get_tv_string(&argvars[0]));
16440 if (*p == '+')
16441 p = skipwhite(p + 1);
16442 (void)string2float(p, &rettv->vval.v_float);
16443 rettv->v_type = VAR_FLOAT;
16445 #endif
16448 * "str2nr()" function
16450 static void
16451 f_str2nr(argvars, rettv)
16452 typval_T *argvars;
16453 typval_T *rettv;
16455 int base = 10;
16456 char_u *p;
16457 long n;
16459 if (argvars[1].v_type != VAR_UNKNOWN)
16461 base = get_tv_number(&argvars[1]);
16462 if (base != 8 && base != 10 && base != 16)
16464 EMSG(_(e_invarg));
16465 return;
16469 p = skipwhite(get_tv_string(&argvars[0]));
16470 if (*p == '+')
16471 p = skipwhite(p + 1);
16472 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
16473 rettv->vval.v_number = n;
16476 #ifdef HAVE_STRFTIME
16478 * "strftime({format}[, {time}])" function
16480 static void
16481 f_strftime(argvars, rettv)
16482 typval_T *argvars;
16483 typval_T *rettv;
16485 char_u result_buf[256];
16486 struct tm *curtime;
16487 time_t seconds;
16488 char_u *p;
16490 rettv->v_type = VAR_STRING;
16492 p = get_tv_string(&argvars[0]);
16493 if (argvars[1].v_type == VAR_UNKNOWN)
16494 seconds = time(NULL);
16495 else
16496 seconds = (time_t)get_tv_number(&argvars[1]);
16497 curtime = localtime(&seconds);
16498 /* MSVC returns NULL for an invalid value of seconds. */
16499 if (curtime == NULL)
16500 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
16501 else
16503 # ifdef FEAT_MBYTE
16504 vimconv_T conv;
16505 char_u *enc;
16507 conv.vc_type = CONV_NONE;
16508 enc = enc_locale();
16509 convert_setup(&conv, p_enc, enc);
16510 if (conv.vc_type != CONV_NONE)
16511 p = string_convert(&conv, p, NULL);
16512 # endif
16513 if (p != NULL)
16514 (void)strftime((char *)result_buf, sizeof(result_buf),
16515 (char *)p, curtime);
16516 else
16517 result_buf[0] = NUL;
16519 # ifdef FEAT_MBYTE
16520 if (conv.vc_type != CONV_NONE)
16521 vim_free(p);
16522 convert_setup(&conv, enc, p_enc);
16523 if (conv.vc_type != CONV_NONE)
16524 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
16525 else
16526 # endif
16527 rettv->vval.v_string = vim_strsave(result_buf);
16529 # ifdef FEAT_MBYTE
16530 /* Release conversion descriptors */
16531 convert_setup(&conv, NULL, NULL);
16532 vim_free(enc);
16533 # endif
16536 #endif
16539 * "stridx()" function
16541 static void
16542 f_stridx(argvars, rettv)
16543 typval_T *argvars;
16544 typval_T *rettv;
16546 char_u buf[NUMBUFLEN];
16547 char_u *needle;
16548 char_u *haystack;
16549 char_u *save_haystack;
16550 char_u *pos;
16551 int start_idx;
16553 needle = get_tv_string_chk(&argvars[1]);
16554 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
16555 rettv->vval.v_number = -1;
16556 if (needle == NULL || haystack == NULL)
16557 return; /* type error; errmsg already given */
16559 if (argvars[2].v_type != VAR_UNKNOWN)
16561 int error = FALSE;
16563 start_idx = get_tv_number_chk(&argvars[2], &error);
16564 if (error || start_idx >= (int)STRLEN(haystack))
16565 return;
16566 if (start_idx >= 0)
16567 haystack += start_idx;
16570 pos = (char_u *)strstr((char *)haystack, (char *)needle);
16571 if (pos != NULL)
16572 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
16576 * "string()" function
16578 static void
16579 f_string(argvars, rettv)
16580 typval_T *argvars;
16581 typval_T *rettv;
16583 char_u *tofree;
16584 char_u numbuf[NUMBUFLEN];
16586 rettv->v_type = VAR_STRING;
16587 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
16588 /* Make a copy if we have a value but it's not in allocated memory. */
16589 if (rettv->vval.v_string != NULL && tofree == NULL)
16590 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
16594 * "strlen()" function
16596 static void
16597 f_strlen(argvars, rettv)
16598 typval_T *argvars;
16599 typval_T *rettv;
16601 rettv->vval.v_number = (varnumber_T)(STRLEN(
16602 get_tv_string(&argvars[0])));
16606 * "strpart()" function
16608 static void
16609 f_strpart(argvars, rettv)
16610 typval_T *argvars;
16611 typval_T *rettv;
16613 char_u *p;
16614 int n;
16615 int len;
16616 int slen;
16617 int error = FALSE;
16619 p = get_tv_string(&argvars[0]);
16620 slen = (int)STRLEN(p);
16622 n = get_tv_number_chk(&argvars[1], &error);
16623 if (error)
16624 len = 0;
16625 else if (argvars[2].v_type != VAR_UNKNOWN)
16626 len = get_tv_number(&argvars[2]);
16627 else
16628 len = slen - n; /* default len: all bytes that are available. */
16631 * Only return the overlap between the specified part and the actual
16632 * string.
16634 if (n < 0)
16636 len += n;
16637 n = 0;
16639 else if (n > slen)
16640 n = slen;
16641 if (len < 0)
16642 len = 0;
16643 else if (n + len > slen)
16644 len = slen - n;
16646 rettv->v_type = VAR_STRING;
16647 rettv->vval.v_string = vim_strnsave(p + n, len);
16651 * "strridx()" function
16653 static void
16654 f_strridx(argvars, rettv)
16655 typval_T *argvars;
16656 typval_T *rettv;
16658 char_u buf[NUMBUFLEN];
16659 char_u *needle;
16660 char_u *haystack;
16661 char_u *rest;
16662 char_u *lastmatch = NULL;
16663 int haystack_len, end_idx;
16665 needle = get_tv_string_chk(&argvars[1]);
16666 haystack = get_tv_string_buf_chk(&argvars[0], buf);
16668 rettv->vval.v_number = -1;
16669 if (needle == NULL || haystack == NULL)
16670 return; /* type error; errmsg already given */
16672 haystack_len = (int)STRLEN(haystack);
16673 if (argvars[2].v_type != VAR_UNKNOWN)
16675 /* Third argument: upper limit for index */
16676 end_idx = get_tv_number_chk(&argvars[2], NULL);
16677 if (end_idx < 0)
16678 return; /* can never find a match */
16680 else
16681 end_idx = haystack_len;
16683 if (*needle == NUL)
16685 /* Empty string matches past the end. */
16686 lastmatch = haystack + end_idx;
16688 else
16690 for (rest = haystack; *rest != '\0'; ++rest)
16692 rest = (char_u *)strstr((char *)rest, (char *)needle);
16693 if (rest == NULL || rest > haystack + end_idx)
16694 break;
16695 lastmatch = rest;
16699 if (lastmatch == NULL)
16700 rettv->vval.v_number = -1;
16701 else
16702 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
16706 * "strtrans()" function
16708 static void
16709 f_strtrans(argvars, rettv)
16710 typval_T *argvars;
16711 typval_T *rettv;
16713 rettv->v_type = VAR_STRING;
16714 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
16718 * "submatch()" function
16720 static void
16721 f_submatch(argvars, rettv)
16722 typval_T *argvars;
16723 typval_T *rettv;
16725 rettv->v_type = VAR_STRING;
16726 rettv->vval.v_string =
16727 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
16731 * "substitute()" function
16733 static void
16734 f_substitute(argvars, rettv)
16735 typval_T *argvars;
16736 typval_T *rettv;
16738 char_u patbuf[NUMBUFLEN];
16739 char_u subbuf[NUMBUFLEN];
16740 char_u flagsbuf[NUMBUFLEN];
16742 char_u *str = get_tv_string_chk(&argvars[0]);
16743 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16744 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
16745 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
16747 rettv->v_type = VAR_STRING;
16748 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
16749 rettv->vval.v_string = NULL;
16750 else
16751 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
16755 * "synID(lnum, col, trans)" function
16757 static void
16758 f_synID(argvars, rettv)
16759 typval_T *argvars UNUSED;
16760 typval_T *rettv;
16762 int id = 0;
16763 #ifdef FEAT_SYN_HL
16764 long lnum;
16765 long col;
16766 int trans;
16767 int transerr = FALSE;
16769 lnum = get_tv_lnum(argvars); /* -1 on type error */
16770 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16771 trans = get_tv_number_chk(&argvars[2], &transerr);
16773 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16774 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
16775 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
16776 #endif
16778 rettv->vval.v_number = id;
16782 * "synIDattr(id, what [, mode])" function
16784 static void
16785 f_synIDattr(argvars, rettv)
16786 typval_T *argvars UNUSED;
16787 typval_T *rettv;
16789 char_u *p = NULL;
16790 #ifdef FEAT_SYN_HL
16791 int id;
16792 char_u *what;
16793 char_u *mode;
16794 char_u modebuf[NUMBUFLEN];
16795 int modec;
16797 id = get_tv_number(&argvars[0]);
16798 what = get_tv_string(&argvars[1]);
16799 if (argvars[2].v_type != VAR_UNKNOWN)
16801 mode = get_tv_string_buf(&argvars[2], modebuf);
16802 modec = TOLOWER_ASC(mode[0]);
16803 if (modec != 't' && modec != 'c'
16804 #ifdef FEAT_GUI
16805 && modec != 'g'
16806 #endif
16808 modec = 0; /* replace invalid with current */
16810 else
16812 #ifdef FEAT_GUI
16813 if (gui.in_use)
16814 modec = 'g';
16815 else
16816 #endif
16817 if (t_colors > 1)
16818 modec = 'c';
16819 else
16820 modec = 't';
16824 switch (TOLOWER_ASC(what[0]))
16826 case 'b':
16827 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
16828 p = highlight_color(id, what, modec);
16829 else /* bold */
16830 p = highlight_has_attr(id, HL_BOLD, modec);
16831 break;
16833 case 'f': /* fg[#] or font */
16834 p = highlight_color(id, what, modec);
16835 break;
16837 case 'i':
16838 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
16839 p = highlight_has_attr(id, HL_INVERSE, modec);
16840 else /* italic */
16841 p = highlight_has_attr(id, HL_ITALIC, modec);
16842 break;
16844 case 'n': /* name */
16845 p = get_highlight_name(NULL, id - 1);
16846 break;
16848 case 'r': /* reverse */
16849 p = highlight_has_attr(id, HL_INVERSE, modec);
16850 break;
16852 case 's':
16853 if (TOLOWER_ASC(what[1]) == 'p') /* sp[#] */
16854 p = highlight_color(id, what, modec);
16855 else /* standout */
16856 p = highlight_has_attr(id, HL_STANDOUT, modec);
16857 break;
16859 case 'u':
16860 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
16861 /* underline */
16862 p = highlight_has_attr(id, HL_UNDERLINE, modec);
16863 else
16864 /* undercurl */
16865 p = highlight_has_attr(id, HL_UNDERCURL, modec);
16866 break;
16869 if (p != NULL)
16870 p = vim_strsave(p);
16871 #endif
16872 rettv->v_type = VAR_STRING;
16873 rettv->vval.v_string = p;
16877 * "synIDtrans(id)" function
16879 static void
16880 f_synIDtrans(argvars, rettv)
16881 typval_T *argvars UNUSED;
16882 typval_T *rettv;
16884 int id;
16886 #ifdef FEAT_SYN_HL
16887 id = get_tv_number(&argvars[0]);
16889 if (id > 0)
16890 id = syn_get_final_id(id);
16891 else
16892 #endif
16893 id = 0;
16895 rettv->vval.v_number = id;
16899 * "synstack(lnum, col)" function
16901 static void
16902 f_synstack(argvars, rettv)
16903 typval_T *argvars UNUSED;
16904 typval_T *rettv;
16906 #ifdef FEAT_SYN_HL
16907 long lnum;
16908 long col;
16909 int i;
16910 int id;
16911 #endif
16913 rettv->v_type = VAR_LIST;
16914 rettv->vval.v_list = NULL;
16916 #ifdef FEAT_SYN_HL
16917 lnum = get_tv_lnum(argvars); /* -1 on type error */
16918 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16920 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16921 && col >= 0 && (col == 0 || col < (long)STRLEN(ml_get(lnum)))
16922 && rettv_list_alloc(rettv) != FAIL)
16924 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
16925 for (i = 0; ; ++i)
16927 id = syn_get_stack_item(i);
16928 if (id < 0)
16929 break;
16930 if (list_append_number(rettv->vval.v_list, id) == FAIL)
16931 break;
16934 #endif
16938 * "system()" function
16940 static void
16941 f_system(argvars, rettv)
16942 typval_T *argvars;
16943 typval_T *rettv;
16945 char_u *res = NULL;
16946 char_u *p;
16947 char_u *infile = NULL;
16948 char_u buf[NUMBUFLEN];
16949 int err = FALSE;
16950 FILE *fd;
16952 if (check_restricted() || check_secure())
16953 goto done;
16955 if (argvars[1].v_type != VAR_UNKNOWN)
16958 * Write the string to a temp file, to be used for input of the shell
16959 * command.
16961 if ((infile = vim_tempname('i')) == NULL)
16963 EMSG(_(e_notmp));
16964 goto done;
16967 fd = mch_fopen((char *)infile, WRITEBIN);
16968 if (fd == NULL)
16970 EMSG2(_(e_notopen), infile);
16971 goto done;
16973 p = get_tv_string_buf_chk(&argvars[1], buf);
16974 if (p == NULL)
16976 fclose(fd);
16977 goto done; /* type error; errmsg already given */
16979 if (fwrite(p, STRLEN(p), 1, fd) != 1)
16980 err = TRUE;
16981 if (fclose(fd) != 0)
16982 err = TRUE;
16983 if (err)
16985 EMSG(_("E677: Error writing temp file"));
16986 goto done;
16990 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
16991 SHELL_SILENT | SHELL_COOKED);
16993 #ifdef USE_CR
16994 /* translate <CR> into <NL> */
16995 if (res != NULL)
16997 char_u *s;
16999 for (s = res; *s; ++s)
17001 if (*s == CAR)
17002 *s = NL;
17005 #else
17006 # ifdef USE_CRNL
17007 /* translate <CR><NL> into <NL> */
17008 if (res != NULL)
17010 char_u *s, *d;
17012 d = res;
17013 for (s = res; *s; ++s)
17015 if (s[0] == CAR && s[1] == NL)
17016 ++s;
17017 *d++ = *s;
17019 *d = NUL;
17021 # endif
17022 #endif
17024 done:
17025 if (infile != NULL)
17027 mch_remove(infile);
17028 vim_free(infile);
17030 rettv->v_type = VAR_STRING;
17031 rettv->vval.v_string = res;
17035 * "tabpagebuflist()" function
17037 static void
17038 f_tabpagebuflist(argvars, rettv)
17039 typval_T *argvars UNUSED;
17040 typval_T *rettv UNUSED;
17042 #ifdef FEAT_WINDOWS
17043 tabpage_T *tp;
17044 win_T *wp = NULL;
17046 if (argvars[0].v_type == VAR_UNKNOWN)
17047 wp = firstwin;
17048 else
17050 tp = find_tabpage((int)get_tv_number(&argvars[0]));
17051 if (tp != NULL)
17052 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
17054 if (wp != NULL && rettv_list_alloc(rettv) != FAIL)
17056 for (; wp != NULL; wp = wp->w_next)
17057 if (list_append_number(rettv->vval.v_list,
17058 wp->w_buffer->b_fnum) == FAIL)
17059 break;
17061 #endif
17066 * "tabpagenr()" function
17068 static void
17069 f_tabpagenr(argvars, rettv)
17070 typval_T *argvars UNUSED;
17071 typval_T *rettv;
17073 int nr = 1;
17074 #ifdef FEAT_WINDOWS
17075 char_u *arg;
17077 if (argvars[0].v_type != VAR_UNKNOWN)
17079 arg = get_tv_string_chk(&argvars[0]);
17080 nr = 0;
17081 if (arg != NULL)
17083 if (STRCMP(arg, "$") == 0)
17084 nr = tabpage_index(NULL) - 1;
17085 else
17086 EMSG2(_(e_invexpr2), arg);
17089 else
17090 nr = tabpage_index(curtab);
17091 #endif
17092 rettv->vval.v_number = nr;
17096 #ifdef FEAT_WINDOWS
17097 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
17100 * Common code for tabpagewinnr() and winnr().
17102 static int
17103 get_winnr(tp, argvar)
17104 tabpage_T *tp;
17105 typval_T *argvar;
17107 win_T *twin;
17108 int nr = 1;
17109 win_T *wp;
17110 char_u *arg;
17112 twin = (tp == curtab) ? curwin : tp->tp_curwin;
17113 if (argvar->v_type != VAR_UNKNOWN)
17115 arg = get_tv_string_chk(argvar);
17116 if (arg == NULL)
17117 nr = 0; /* type error; errmsg already given */
17118 else if (STRCMP(arg, "$") == 0)
17119 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
17120 else if (STRCMP(arg, "#") == 0)
17122 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
17123 if (twin == NULL)
17124 nr = 0;
17126 else
17128 EMSG2(_(e_invexpr2), arg);
17129 nr = 0;
17133 if (nr > 0)
17134 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
17135 wp != twin; wp = wp->w_next)
17137 if (wp == NULL)
17139 /* didn't find it in this tabpage */
17140 nr = 0;
17141 break;
17143 ++nr;
17145 return nr;
17147 #endif
17150 * "tabpagewinnr()" function
17152 static void
17153 f_tabpagewinnr(argvars, rettv)
17154 typval_T *argvars UNUSED;
17155 typval_T *rettv;
17157 int nr = 1;
17158 #ifdef FEAT_WINDOWS
17159 tabpage_T *tp;
17161 tp = find_tabpage((int)get_tv_number(&argvars[0]));
17162 if (tp == NULL)
17163 nr = 0;
17164 else
17165 nr = get_winnr(tp, &argvars[1]);
17166 #endif
17167 rettv->vval.v_number = nr;
17172 * "tagfiles()" function
17174 static void
17175 f_tagfiles(argvars, rettv)
17176 typval_T *argvars UNUSED;
17177 typval_T *rettv;
17179 char_u fname[MAXPATHL + 1];
17180 tagname_T tn;
17181 int first;
17183 if (rettv_list_alloc(rettv) == FAIL)
17184 return;
17186 for (first = TRUE; ; first = FALSE)
17187 if (get_tagfname(&tn, first, fname) == FAIL
17188 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
17189 break;
17190 tagname_free(&tn);
17194 * "taglist()" function
17196 static void
17197 f_taglist(argvars, rettv)
17198 typval_T *argvars;
17199 typval_T *rettv;
17201 char_u *tag_pattern;
17203 tag_pattern = get_tv_string(&argvars[0]);
17205 rettv->vval.v_number = FALSE;
17206 if (*tag_pattern == NUL)
17207 return;
17209 if (rettv_list_alloc(rettv) == OK)
17210 (void)get_tags(rettv->vval.v_list, tag_pattern);
17214 * "tempname()" function
17216 static void
17217 f_tempname(argvars, rettv)
17218 typval_T *argvars UNUSED;
17219 typval_T *rettv;
17221 static int x = 'A';
17223 rettv->v_type = VAR_STRING;
17224 rettv->vval.v_string = vim_tempname(x);
17226 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
17227 * names. Skip 'I' and 'O', they are used for shell redirection. */
17230 if (x == 'Z')
17231 x = '0';
17232 else if (x == '9')
17233 x = 'A';
17234 else
17236 #ifdef EBCDIC
17237 if (x == 'I')
17238 x = 'J';
17239 else if (x == 'R')
17240 x = 'S';
17241 else
17242 #endif
17243 ++x;
17245 } while (x == 'I' || x == 'O');
17249 * "test(list)" function: Just checking the walls...
17251 static void
17252 f_test(argvars, rettv)
17253 typval_T *argvars UNUSED;
17254 typval_T *rettv UNUSED;
17256 /* Used for unit testing. Change the code below to your liking. */
17257 #if 0
17258 listitem_T *li;
17259 list_T *l;
17260 char_u *bad, *good;
17262 if (argvars[0].v_type != VAR_LIST)
17263 return;
17264 l = argvars[0].vval.v_list;
17265 if (l == NULL)
17266 return;
17267 li = l->lv_first;
17268 if (li == NULL)
17269 return;
17270 bad = get_tv_string(&li->li_tv);
17271 li = li->li_next;
17272 if (li == NULL)
17273 return;
17274 good = get_tv_string(&li->li_tv);
17275 rettv->vval.v_number = test_edit_score(bad, good);
17276 #endif
17280 * "tolower(string)" function
17282 static void
17283 f_tolower(argvars, rettv)
17284 typval_T *argvars;
17285 typval_T *rettv;
17287 char_u *p;
17289 p = vim_strsave(get_tv_string(&argvars[0]));
17290 rettv->v_type = VAR_STRING;
17291 rettv->vval.v_string = p;
17293 if (p != NULL)
17294 while (*p != NUL)
17296 #ifdef FEAT_MBYTE
17297 int l;
17299 if (enc_utf8)
17301 int c, lc;
17303 c = utf_ptr2char(p);
17304 lc = utf_tolower(c);
17305 l = utf_ptr2len(p);
17306 /* TODO: reallocate string when byte count changes. */
17307 if (utf_char2len(lc) == l)
17308 utf_char2bytes(lc, p);
17309 p += l;
17311 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
17312 p += l; /* skip multi-byte character */
17313 else
17314 #endif
17316 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
17317 ++p;
17323 * "toupper(string)" function
17325 static void
17326 f_toupper(argvars, rettv)
17327 typval_T *argvars;
17328 typval_T *rettv;
17330 rettv->v_type = VAR_STRING;
17331 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
17335 * "tr(string, fromstr, tostr)" function
17337 static void
17338 f_tr(argvars, rettv)
17339 typval_T *argvars;
17340 typval_T *rettv;
17342 char_u *instr;
17343 char_u *fromstr;
17344 char_u *tostr;
17345 char_u *p;
17346 #ifdef FEAT_MBYTE
17347 int inlen;
17348 int fromlen;
17349 int tolen;
17350 int idx;
17351 char_u *cpstr;
17352 int cplen;
17353 int first = TRUE;
17354 #endif
17355 char_u buf[NUMBUFLEN];
17356 char_u buf2[NUMBUFLEN];
17357 garray_T ga;
17359 instr = get_tv_string(&argvars[0]);
17360 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
17361 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
17363 /* Default return value: empty string. */
17364 rettv->v_type = VAR_STRING;
17365 rettv->vval.v_string = NULL;
17366 if (fromstr == NULL || tostr == NULL)
17367 return; /* type error; errmsg already given */
17368 ga_init2(&ga, (int)sizeof(char), 80);
17370 #ifdef FEAT_MBYTE
17371 if (!has_mbyte)
17372 #endif
17373 /* not multi-byte: fromstr and tostr must be the same length */
17374 if (STRLEN(fromstr) != STRLEN(tostr))
17376 #ifdef FEAT_MBYTE
17377 error:
17378 #endif
17379 EMSG2(_(e_invarg2), fromstr);
17380 ga_clear(&ga);
17381 return;
17384 /* fromstr and tostr have to contain the same number of chars */
17385 while (*instr != NUL)
17387 #ifdef FEAT_MBYTE
17388 if (has_mbyte)
17390 inlen = (*mb_ptr2len)(instr);
17391 cpstr = instr;
17392 cplen = inlen;
17393 idx = 0;
17394 for (p = fromstr; *p != NUL; p += fromlen)
17396 fromlen = (*mb_ptr2len)(p);
17397 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
17399 for (p = tostr; *p != NUL; p += tolen)
17401 tolen = (*mb_ptr2len)(p);
17402 if (idx-- == 0)
17404 cplen = tolen;
17405 cpstr = p;
17406 break;
17409 if (*p == NUL) /* tostr is shorter than fromstr */
17410 goto error;
17411 break;
17413 ++idx;
17416 if (first && cpstr == instr)
17418 /* Check that fromstr and tostr have the same number of
17419 * (multi-byte) characters. Done only once when a character
17420 * of instr doesn't appear in fromstr. */
17421 first = FALSE;
17422 for (p = tostr; *p != NUL; p += tolen)
17424 tolen = (*mb_ptr2len)(p);
17425 --idx;
17427 if (idx != 0)
17428 goto error;
17431 ga_grow(&ga, cplen);
17432 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
17433 ga.ga_len += cplen;
17435 instr += inlen;
17437 else
17438 #endif
17440 /* When not using multi-byte chars we can do it faster. */
17441 p = vim_strchr(fromstr, *instr);
17442 if (p != NULL)
17443 ga_append(&ga, tostr[p - fromstr]);
17444 else
17445 ga_append(&ga, *instr);
17446 ++instr;
17450 /* add a terminating NUL */
17451 ga_grow(&ga, 1);
17452 ga_append(&ga, NUL);
17454 rettv->vval.v_string = ga.ga_data;
17457 #ifdef FEAT_FLOAT
17459 * "trunc({float})" function
17461 static void
17462 f_trunc(argvars, rettv)
17463 typval_T *argvars;
17464 typval_T *rettv;
17466 float_T f;
17468 rettv->v_type = VAR_FLOAT;
17469 if (get_float_arg(argvars, &f) == OK)
17470 /* trunc() is not in C90, use floor() or ceil() instead. */
17471 rettv->vval.v_float = f > 0 ? floor(f) : ceil(f);
17472 else
17473 rettv->vval.v_float = 0.0;
17475 #endif
17478 * "type(expr)" function
17480 static void
17481 f_type(argvars, rettv)
17482 typval_T *argvars;
17483 typval_T *rettv;
17485 int n;
17487 switch (argvars[0].v_type)
17489 case VAR_NUMBER: n = 0; break;
17490 case VAR_STRING: n = 1; break;
17491 case VAR_FUNC: n = 2; break;
17492 case VAR_LIST: n = 3; break;
17493 case VAR_DICT: n = 4; break;
17494 #ifdef FEAT_FLOAT
17495 case VAR_FLOAT: n = 5; break;
17496 #endif
17497 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
17499 rettv->vval.v_number = n;
17503 * "values(dict)" function
17505 static void
17506 f_values(argvars, rettv)
17507 typval_T *argvars;
17508 typval_T *rettv;
17510 dict_list(argvars, rettv, 1);
17514 * "virtcol(string)" function
17516 static void
17517 f_virtcol(argvars, rettv)
17518 typval_T *argvars;
17519 typval_T *rettv;
17521 colnr_T vcol = 0;
17522 pos_T *fp;
17523 int fnum = curbuf->b_fnum;
17525 fp = var2fpos(&argvars[0], FALSE, &fnum);
17526 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
17527 && fnum == curbuf->b_fnum)
17529 getvvcol(curwin, fp, NULL, NULL, &vcol);
17530 ++vcol;
17533 rettv->vval.v_number = vcol;
17537 * "visualmode()" function
17539 static void
17540 f_visualmode(argvars, rettv)
17541 typval_T *argvars UNUSED;
17542 typval_T *rettv UNUSED;
17544 #ifdef FEAT_VISUAL
17545 char_u str[2];
17547 rettv->v_type = VAR_STRING;
17548 str[0] = curbuf->b_visual_mode_eval;
17549 str[1] = NUL;
17550 rettv->vval.v_string = vim_strsave(str);
17552 /* A non-zero number or non-empty string argument: reset mode. */
17553 if (non_zero_arg(&argvars[0]))
17554 curbuf->b_visual_mode_eval = NUL;
17555 #endif
17559 * "winbufnr(nr)" function
17561 static void
17562 f_winbufnr(argvars, rettv)
17563 typval_T *argvars;
17564 typval_T *rettv;
17566 win_T *wp;
17568 wp = find_win_by_nr(&argvars[0], NULL);
17569 if (wp == NULL)
17570 rettv->vval.v_number = -1;
17571 else
17572 rettv->vval.v_number = wp->w_buffer->b_fnum;
17576 * "wincol()" function
17578 static void
17579 f_wincol(argvars, rettv)
17580 typval_T *argvars UNUSED;
17581 typval_T *rettv;
17583 validate_cursor();
17584 rettv->vval.v_number = curwin->w_wcol + 1;
17588 * "winheight(nr)" function
17590 static void
17591 f_winheight(argvars, rettv)
17592 typval_T *argvars;
17593 typval_T *rettv;
17595 win_T *wp;
17597 wp = find_win_by_nr(&argvars[0], NULL);
17598 if (wp == NULL)
17599 rettv->vval.v_number = -1;
17600 else
17601 rettv->vval.v_number = wp->w_height;
17605 * "winline()" function
17607 static void
17608 f_winline(argvars, rettv)
17609 typval_T *argvars UNUSED;
17610 typval_T *rettv;
17612 validate_cursor();
17613 rettv->vval.v_number = curwin->w_wrow + 1;
17617 * "winnr()" function
17619 static void
17620 f_winnr(argvars, rettv)
17621 typval_T *argvars UNUSED;
17622 typval_T *rettv;
17624 int nr = 1;
17626 #ifdef FEAT_WINDOWS
17627 nr = get_winnr(curtab, &argvars[0]);
17628 #endif
17629 rettv->vval.v_number = nr;
17633 * "winrestcmd()" function
17635 static void
17636 f_winrestcmd(argvars, rettv)
17637 typval_T *argvars UNUSED;
17638 typval_T *rettv;
17640 #ifdef FEAT_WINDOWS
17641 win_T *wp;
17642 int winnr = 1;
17643 garray_T ga;
17644 char_u buf[50];
17646 ga_init2(&ga, (int)sizeof(char), 70);
17647 for (wp = firstwin; wp != NULL; wp = wp->w_next)
17649 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
17650 ga_concat(&ga, buf);
17651 # ifdef FEAT_VERTSPLIT
17652 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
17653 ga_concat(&ga, buf);
17654 # endif
17655 ++winnr;
17657 ga_append(&ga, NUL);
17659 rettv->vval.v_string = ga.ga_data;
17660 #else
17661 rettv->vval.v_string = NULL;
17662 #endif
17663 rettv->v_type = VAR_STRING;
17667 * "winrestview()" function
17669 static void
17670 f_winrestview(argvars, rettv)
17671 typval_T *argvars;
17672 typval_T *rettv UNUSED;
17674 dict_T *dict;
17676 if (argvars[0].v_type != VAR_DICT
17677 || (dict = argvars[0].vval.v_dict) == NULL)
17678 EMSG(_(e_invarg));
17679 else
17681 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
17682 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
17683 #ifdef FEAT_VIRTUALEDIT
17684 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
17685 #endif
17686 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
17687 curwin->w_set_curswant = FALSE;
17689 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
17690 #ifdef FEAT_DIFF
17691 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
17692 #endif
17693 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
17694 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
17696 check_cursor();
17697 changed_cline_bef_curs();
17698 invalidate_botline();
17699 redraw_later(VALID);
17701 if (curwin->w_topline == 0)
17702 curwin->w_topline = 1;
17703 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
17704 curwin->w_topline = curbuf->b_ml.ml_line_count;
17705 #ifdef FEAT_DIFF
17706 check_topfill(curwin, TRUE);
17707 #endif
17712 * "winsaveview()" function
17714 static void
17715 f_winsaveview(argvars, rettv)
17716 typval_T *argvars UNUSED;
17717 typval_T *rettv;
17719 dict_T *dict;
17721 dict = dict_alloc();
17722 if (dict == NULL)
17723 return;
17724 rettv->v_type = VAR_DICT;
17725 rettv->vval.v_dict = dict;
17726 ++dict->dv_refcount;
17728 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
17729 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
17730 #ifdef FEAT_VIRTUALEDIT
17731 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
17732 #endif
17733 update_curswant();
17734 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
17736 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
17737 #ifdef FEAT_DIFF
17738 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
17739 #endif
17740 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
17741 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
17745 * "winwidth(nr)" function
17747 static void
17748 f_winwidth(argvars, rettv)
17749 typval_T *argvars;
17750 typval_T *rettv;
17752 win_T *wp;
17754 wp = find_win_by_nr(&argvars[0], NULL);
17755 if (wp == NULL)
17756 rettv->vval.v_number = -1;
17757 else
17758 #ifdef FEAT_VERTSPLIT
17759 rettv->vval.v_number = wp->w_width;
17760 #else
17761 rettv->vval.v_number = Columns;
17762 #endif
17766 * "writefile()" function
17768 static void
17769 f_writefile(argvars, rettv)
17770 typval_T *argvars;
17771 typval_T *rettv;
17773 int binary = FALSE;
17774 char_u *fname;
17775 FILE *fd;
17776 listitem_T *li;
17777 char_u *s;
17778 int ret = 0;
17779 int c;
17781 if (check_restricted() || check_secure())
17782 return;
17784 if (argvars[0].v_type != VAR_LIST)
17786 EMSG2(_(e_listarg), "writefile()");
17787 return;
17789 if (argvars[0].vval.v_list == NULL)
17790 return;
17792 if (argvars[2].v_type != VAR_UNKNOWN
17793 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
17794 binary = TRUE;
17796 /* Always open the file in binary mode, library functions have a mind of
17797 * their own about CR-LF conversion. */
17798 fname = get_tv_string(&argvars[1]);
17799 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
17801 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
17802 ret = -1;
17804 else
17806 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
17807 li = li->li_next)
17809 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
17811 if (*s == '\n')
17812 c = putc(NUL, fd);
17813 else
17814 c = putc(*s, fd);
17815 if (c == EOF)
17817 ret = -1;
17818 break;
17821 if (!binary || li->li_next != NULL)
17822 if (putc('\n', fd) == EOF)
17824 ret = -1;
17825 break;
17827 if (ret < 0)
17829 EMSG(_(e_write));
17830 break;
17833 fclose(fd);
17836 rettv->vval.v_number = ret;
17840 * Translate a String variable into a position.
17841 * Returns NULL when there is an error.
17843 static pos_T *
17844 var2fpos(varp, dollar_lnum, fnum)
17845 typval_T *varp;
17846 int dollar_lnum; /* TRUE when $ is last line */
17847 int *fnum; /* set to fnum for '0, 'A, etc. */
17849 char_u *name;
17850 static pos_T pos;
17851 pos_T *pp;
17853 /* Argument can be [lnum, col, coladd]. */
17854 if (varp->v_type == VAR_LIST)
17856 list_T *l;
17857 int len;
17858 int error = FALSE;
17859 listitem_T *li;
17861 l = varp->vval.v_list;
17862 if (l == NULL)
17863 return NULL;
17865 /* Get the line number */
17866 pos.lnum = list_find_nr(l, 0L, &error);
17867 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
17868 return NULL; /* invalid line number */
17870 /* Get the column number */
17871 pos.col = list_find_nr(l, 1L, &error);
17872 if (error)
17873 return NULL;
17874 len = (long)STRLEN(ml_get(pos.lnum));
17876 /* We accept "$" for the column number: last column. */
17877 li = list_find(l, 1L);
17878 if (li != NULL && li->li_tv.v_type == VAR_STRING
17879 && li->li_tv.vval.v_string != NULL
17880 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
17881 pos.col = len + 1;
17883 /* Accept a position up to the NUL after the line. */
17884 if (pos.col == 0 || (int)pos.col > len + 1)
17885 return NULL; /* invalid column number */
17886 --pos.col;
17888 #ifdef FEAT_VIRTUALEDIT
17889 /* Get the virtual offset. Defaults to zero. */
17890 pos.coladd = list_find_nr(l, 2L, &error);
17891 if (error)
17892 pos.coladd = 0;
17893 #endif
17895 return &pos;
17898 name = get_tv_string_chk(varp);
17899 if (name == NULL)
17900 return NULL;
17901 if (name[0] == '.') /* cursor */
17902 return &curwin->w_cursor;
17903 #ifdef FEAT_VISUAL
17904 if (name[0] == 'v' && name[1] == NUL) /* Visual start */
17906 if (VIsual_active)
17907 return &VIsual;
17908 return &curwin->w_cursor;
17910 #endif
17911 if (name[0] == '\'') /* mark */
17913 pp = getmark_fnum(name[1], FALSE, fnum);
17914 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
17915 return NULL;
17916 return pp;
17919 #ifdef FEAT_VIRTUALEDIT
17920 pos.coladd = 0;
17921 #endif
17923 if (name[0] == 'w' && dollar_lnum)
17925 pos.col = 0;
17926 if (name[1] == '0') /* "w0": first visible line */
17928 update_topline();
17929 pos.lnum = curwin->w_topline;
17930 return &pos;
17932 else if (name[1] == '$') /* "w$": last visible line */
17934 validate_botline();
17935 pos.lnum = curwin->w_botline - 1;
17936 return &pos;
17939 else if (name[0] == '$') /* last column or line */
17941 if (dollar_lnum)
17943 pos.lnum = curbuf->b_ml.ml_line_count;
17944 pos.col = 0;
17946 else
17948 pos.lnum = curwin->w_cursor.lnum;
17949 pos.col = (colnr_T)STRLEN(ml_get_curline());
17951 return &pos;
17953 return NULL;
17957 * Convert list in "arg" into a position and optional file number.
17958 * When "fnump" is NULL there is no file number, only 3 items.
17959 * Note that the column is passed on as-is, the caller may want to decrement
17960 * it to use 1 for the first column.
17961 * Return FAIL when conversion is not possible, doesn't check the position for
17962 * validity.
17964 static int
17965 list2fpos(arg, posp, fnump)
17966 typval_T *arg;
17967 pos_T *posp;
17968 int *fnump;
17970 list_T *l = arg->vval.v_list;
17971 long i = 0;
17972 long n;
17974 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
17975 * when "fnump" isn't NULL and "coladd" is optional. */
17976 if (arg->v_type != VAR_LIST
17977 || l == NULL
17978 || l->lv_len < (fnump == NULL ? 2 : 3)
17979 || l->lv_len > (fnump == NULL ? 3 : 4))
17980 return FAIL;
17982 if (fnump != NULL)
17984 n = list_find_nr(l, i++, NULL); /* fnum */
17985 if (n < 0)
17986 return FAIL;
17987 if (n == 0)
17988 n = curbuf->b_fnum; /* current buffer */
17989 *fnump = n;
17992 n = list_find_nr(l, i++, NULL); /* lnum */
17993 if (n < 0)
17994 return FAIL;
17995 posp->lnum = n;
17997 n = list_find_nr(l, i++, NULL); /* col */
17998 if (n < 0)
17999 return FAIL;
18000 posp->col = n;
18002 #ifdef FEAT_VIRTUALEDIT
18003 n = list_find_nr(l, i, NULL);
18004 if (n < 0)
18005 posp->coladd = 0;
18006 else
18007 posp->coladd = n;
18008 #endif
18010 return OK;
18014 * Get the length of an environment variable name.
18015 * Advance "arg" to the first character after the name.
18016 * Return 0 for error.
18018 static int
18019 get_env_len(arg)
18020 char_u **arg;
18022 char_u *p;
18023 int len;
18025 for (p = *arg; vim_isIDc(*p); ++p)
18027 if (p == *arg) /* no name found */
18028 return 0;
18030 len = (int)(p - *arg);
18031 *arg = p;
18032 return len;
18036 * Get the length of the name of a function or internal variable.
18037 * "arg" is advanced to the first non-white character after the name.
18038 * Return 0 if something is wrong.
18040 static int
18041 get_id_len(arg)
18042 char_u **arg;
18044 char_u *p;
18045 int len;
18047 /* Find the end of the name. */
18048 for (p = *arg; eval_isnamec(*p); ++p)
18050 if (p == *arg) /* no name found */
18051 return 0;
18053 len = (int)(p - *arg);
18054 *arg = skipwhite(p);
18056 return len;
18060 * Get the length of the name of a variable or function.
18061 * Only the name is recognized, does not handle ".key" or "[idx]".
18062 * "arg" is advanced to the first non-white character after the name.
18063 * Return -1 if curly braces expansion failed.
18064 * Return 0 if something else is wrong.
18065 * If the name contains 'magic' {}'s, expand them and return the
18066 * expanded name in an allocated string via 'alias' - caller must free.
18068 static int
18069 get_name_len(arg, alias, evaluate, verbose)
18070 char_u **arg;
18071 char_u **alias;
18072 int evaluate;
18073 int verbose;
18075 int len;
18076 char_u *p;
18077 char_u *expr_start;
18078 char_u *expr_end;
18080 *alias = NULL; /* default to no alias */
18082 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
18083 && (*arg)[2] == (int)KE_SNR)
18085 /* hard coded <SNR>, already translated */
18086 *arg += 3;
18087 return get_id_len(arg) + 3;
18089 len = eval_fname_script(*arg);
18090 if (len > 0)
18092 /* literal "<SID>", "s:" or "<SNR>" */
18093 *arg += len;
18097 * Find the end of the name; check for {} construction.
18099 p = find_name_end(*arg, &expr_start, &expr_end,
18100 len > 0 ? 0 : FNE_CHECK_START);
18101 if (expr_start != NULL)
18103 char_u *temp_string;
18105 if (!evaluate)
18107 len += (int)(p - *arg);
18108 *arg = skipwhite(p);
18109 return len;
18113 * Include any <SID> etc in the expanded string:
18114 * Thus the -len here.
18116 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
18117 if (temp_string == NULL)
18118 return -1;
18119 *alias = temp_string;
18120 *arg = skipwhite(p);
18121 return (int)STRLEN(temp_string);
18124 len += get_id_len(arg);
18125 if (len == 0 && verbose)
18126 EMSG2(_(e_invexpr2), *arg);
18128 return len;
18132 * Find the end of a variable or function name, taking care of magic braces.
18133 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
18134 * start and end of the first magic braces item.
18135 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
18136 * Return a pointer to just after the name. Equal to "arg" if there is no
18137 * valid name.
18139 static char_u *
18140 find_name_end(arg, expr_start, expr_end, flags)
18141 char_u *arg;
18142 char_u **expr_start;
18143 char_u **expr_end;
18144 int flags;
18146 int mb_nest = 0;
18147 int br_nest = 0;
18148 char_u *p;
18150 if (expr_start != NULL)
18152 *expr_start = NULL;
18153 *expr_end = NULL;
18156 /* Quick check for valid starting character. */
18157 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
18158 return arg;
18160 for (p = arg; *p != NUL
18161 && (eval_isnamec(*p)
18162 || *p == '{'
18163 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
18164 || mb_nest != 0
18165 || br_nest != 0); mb_ptr_adv(p))
18167 if (*p == '\'')
18169 /* skip over 'string' to avoid counting [ and ] inside it. */
18170 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
18172 if (*p == NUL)
18173 break;
18175 else if (*p == '"')
18177 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
18178 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
18179 if (*p == '\\' && p[1] != NUL)
18180 ++p;
18181 if (*p == NUL)
18182 break;
18185 if (mb_nest == 0)
18187 if (*p == '[')
18188 ++br_nest;
18189 else if (*p == ']')
18190 --br_nest;
18193 if (br_nest == 0)
18195 if (*p == '{')
18197 mb_nest++;
18198 if (expr_start != NULL && *expr_start == NULL)
18199 *expr_start = p;
18201 else if (*p == '}')
18203 mb_nest--;
18204 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
18205 *expr_end = p;
18210 return p;
18214 * Expands out the 'magic' {}'s in a variable/function name.
18215 * Note that this can call itself recursively, to deal with
18216 * constructs like foo{bar}{baz}{bam}
18217 * The four pointer arguments point to "foo{expre}ss{ion}bar"
18218 * "in_start" ^
18219 * "expr_start" ^
18220 * "expr_end" ^
18221 * "in_end" ^
18223 * Returns a new allocated string, which the caller must free.
18224 * Returns NULL for failure.
18226 static char_u *
18227 make_expanded_name(in_start, expr_start, expr_end, in_end)
18228 char_u *in_start;
18229 char_u *expr_start;
18230 char_u *expr_end;
18231 char_u *in_end;
18233 char_u c1;
18234 char_u *retval = NULL;
18235 char_u *temp_result;
18236 char_u *nextcmd = NULL;
18238 if (expr_end == NULL || in_end == NULL)
18239 return NULL;
18240 *expr_start = NUL;
18241 *expr_end = NUL;
18242 c1 = *in_end;
18243 *in_end = NUL;
18245 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
18246 if (temp_result != NULL && nextcmd == NULL)
18248 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
18249 + (in_end - expr_end) + 1));
18250 if (retval != NULL)
18252 STRCPY(retval, in_start);
18253 STRCAT(retval, temp_result);
18254 STRCAT(retval, expr_end + 1);
18257 vim_free(temp_result);
18259 *in_end = c1; /* put char back for error messages */
18260 *expr_start = '{';
18261 *expr_end = '}';
18263 if (retval != NULL)
18265 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
18266 if (expr_start != NULL)
18268 /* Further expansion! */
18269 temp_result = make_expanded_name(retval, expr_start,
18270 expr_end, temp_result);
18271 vim_free(retval);
18272 retval = temp_result;
18276 return retval;
18280 * Return TRUE if character "c" can be used in a variable or function name.
18281 * Does not include '{' or '}' for magic braces.
18283 static int
18284 eval_isnamec(c)
18285 int c;
18287 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
18291 * Return TRUE if character "c" can be used as the first character in a
18292 * variable or function name (excluding '{' and '}').
18294 static int
18295 eval_isnamec1(c)
18296 int c;
18298 return (ASCII_ISALPHA(c) || c == '_');
18302 * Set number v: variable to "val".
18304 void
18305 set_vim_var_nr(idx, val)
18306 int idx;
18307 long val;
18309 vimvars[idx].vv_nr = val;
18313 * Get number v: variable value.
18315 long
18316 get_vim_var_nr(idx)
18317 int idx;
18319 return vimvars[idx].vv_nr;
18323 * Get string v: variable value. Uses a static buffer, can only be used once.
18325 char_u *
18326 get_vim_var_str(idx)
18327 int idx;
18329 return get_tv_string(&vimvars[idx].vv_tv);
18333 * Get List v: variable value. Caller must take care of reference count when
18334 * needed.
18336 list_T *
18337 get_vim_var_list(idx)
18338 int idx;
18340 return vimvars[idx].vv_list;
18344 * Set v:char to character "c".
18346 void
18347 set_vim_var_char(c)
18348 int c;
18350 #ifdef FEAT_MBYTE
18351 char_u buf[MB_MAXBYTES];
18352 #else
18353 char_u buf[2];
18354 #endif
18356 #ifdef FEAT_MBYTE
18357 if (has_mbyte)
18358 buf[(*mb_char2bytes)(c, buf)] = NUL;
18359 else
18360 #endif
18362 buf[0] = c;
18363 buf[1] = NUL;
18365 set_vim_var_string(VV_CHAR, buf, -1);
18369 * Set v:count to "count" and v:count1 to "count1".
18370 * When "set_prevcount" is TRUE first set v:prevcount from v:count.
18372 void
18373 set_vcount(count, count1, set_prevcount)
18374 long count;
18375 long count1;
18376 int set_prevcount;
18378 if (set_prevcount)
18379 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
18380 vimvars[VV_COUNT].vv_nr = count;
18381 vimvars[VV_COUNT1].vv_nr = count1;
18385 * Set string v: variable to a copy of "val".
18387 void
18388 set_vim_var_string(idx, val, len)
18389 int idx;
18390 char_u *val;
18391 int len; /* length of "val" to use or -1 (whole string) */
18393 /* Need to do this (at least) once, since we can't initialize a union.
18394 * Will always be invoked when "v:progname" is set. */
18395 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
18397 vim_free(vimvars[idx].vv_str);
18398 if (val == NULL)
18399 vimvars[idx].vv_str = NULL;
18400 else if (len == -1)
18401 vimvars[idx].vv_str = vim_strsave(val);
18402 else
18403 vimvars[idx].vv_str = vim_strnsave(val, len);
18407 * Set List v: variable to "val".
18409 void
18410 set_vim_var_list(idx, val)
18411 int idx;
18412 list_T *val;
18414 list_unref(vimvars[idx].vv_list);
18415 vimvars[idx].vv_list = val;
18416 if (val != NULL)
18417 ++val->lv_refcount;
18421 * Set v:register if needed.
18423 void
18424 set_reg_var(c)
18425 int c;
18427 char_u regname;
18429 if (c == 0 || c == ' ')
18430 regname = '"';
18431 else
18432 regname = c;
18433 /* Avoid free/alloc when the value is already right. */
18434 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
18435 set_vim_var_string(VV_REG, &regname, 1);
18439 * Get or set v:exception. If "oldval" == NULL, return the current value.
18440 * Otherwise, restore the value to "oldval" and return NULL.
18441 * Must always be called in pairs to save and restore v:exception! Does not
18442 * take care of memory allocations.
18444 char_u *
18445 v_exception(oldval)
18446 char_u *oldval;
18448 if (oldval == NULL)
18449 return vimvars[VV_EXCEPTION].vv_str;
18451 vimvars[VV_EXCEPTION].vv_str = oldval;
18452 return NULL;
18456 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
18457 * Otherwise, restore the value to "oldval" and return NULL.
18458 * Must always be called in pairs to save and restore v:throwpoint! Does not
18459 * take care of memory allocations.
18461 char_u *
18462 v_throwpoint(oldval)
18463 char_u *oldval;
18465 if (oldval == NULL)
18466 return vimvars[VV_THROWPOINT].vv_str;
18468 vimvars[VV_THROWPOINT].vv_str = oldval;
18469 return NULL;
18472 #if defined(FEAT_AUTOCMD) || defined(PROTO)
18474 * Set v:cmdarg.
18475 * If "eap" != NULL, use "eap" to generate the value and return the old value.
18476 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
18477 * Must always be called in pairs!
18479 char_u *
18480 set_cmdarg(eap, oldarg)
18481 exarg_T *eap;
18482 char_u *oldarg;
18484 char_u *oldval;
18485 char_u *newval;
18486 unsigned len;
18488 oldval = vimvars[VV_CMDARG].vv_str;
18489 if (eap == NULL)
18491 vim_free(oldval);
18492 vimvars[VV_CMDARG].vv_str = oldarg;
18493 return NULL;
18496 if (eap->force_bin == FORCE_BIN)
18497 len = 6;
18498 else if (eap->force_bin == FORCE_NOBIN)
18499 len = 8;
18500 else
18501 len = 0;
18503 if (eap->read_edit)
18504 len += 7;
18506 if (eap->force_ff != 0)
18507 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
18508 # ifdef FEAT_MBYTE
18509 if (eap->force_enc != 0)
18510 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
18511 if (eap->bad_char != 0)
18512 len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
18513 # endif
18515 newval = alloc(len + 1);
18516 if (newval == NULL)
18517 return NULL;
18519 if (eap->force_bin == FORCE_BIN)
18520 sprintf((char *)newval, " ++bin");
18521 else if (eap->force_bin == FORCE_NOBIN)
18522 sprintf((char *)newval, " ++nobin");
18523 else
18524 *newval = NUL;
18526 if (eap->read_edit)
18527 STRCAT(newval, " ++edit");
18529 if (eap->force_ff != 0)
18530 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
18531 eap->cmd + eap->force_ff);
18532 # ifdef FEAT_MBYTE
18533 if (eap->force_enc != 0)
18534 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
18535 eap->cmd + eap->force_enc);
18536 if (eap->bad_char != 0)
18537 sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
18538 eap->cmd + eap->bad_char);
18539 # endif
18540 vimvars[VV_CMDARG].vv_str = newval;
18541 return oldval;
18543 #endif
18546 * Get the value of internal variable "name".
18547 * Return OK or FAIL.
18549 static int
18550 get_var_tv(name, len, rettv, verbose)
18551 char_u *name;
18552 int len; /* length of "name" */
18553 typval_T *rettv; /* NULL when only checking existence */
18554 int verbose; /* may give error message */
18556 int ret = OK;
18557 typval_T *tv = NULL;
18558 typval_T atv;
18559 dictitem_T *v;
18560 int cc;
18562 /* truncate the name, so that we can use strcmp() */
18563 cc = name[len];
18564 name[len] = NUL;
18567 * Check for "b:changedtick".
18569 if (STRCMP(name, "b:changedtick") == 0)
18571 atv.v_type = VAR_NUMBER;
18572 atv.vval.v_number = curbuf->b_changedtick;
18573 tv = &atv;
18577 * Check for user-defined variables.
18579 else
18581 v = find_var(name, NULL);
18582 if (v != NULL)
18583 tv = &v->di_tv;
18586 if (tv == NULL)
18588 if (rettv != NULL && verbose)
18589 EMSG2(_(e_undefvar), name);
18590 ret = FAIL;
18592 else if (rettv != NULL)
18593 copy_tv(tv, rettv);
18595 name[len] = cc;
18597 return ret;
18601 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
18602 * Also handle function call with Funcref variable: func(expr)
18603 * Can all be combined: dict.func(expr)[idx]['func'](expr)
18605 static int
18606 handle_subscript(arg, rettv, evaluate, verbose)
18607 char_u **arg;
18608 typval_T *rettv;
18609 int evaluate; /* do more than finding the end */
18610 int verbose; /* give error messages */
18612 int ret = OK;
18613 dict_T *selfdict = NULL;
18614 char_u *s;
18615 int len;
18616 typval_T functv;
18618 while (ret == OK
18619 && (**arg == '['
18620 || (**arg == '.' && rettv->v_type == VAR_DICT)
18621 || (**arg == '(' && rettv->v_type == VAR_FUNC))
18622 && !vim_iswhite(*(*arg - 1)))
18624 if (**arg == '(')
18626 /* need to copy the funcref so that we can clear rettv */
18627 functv = *rettv;
18628 rettv->v_type = VAR_UNKNOWN;
18630 /* Invoke the function. Recursive! */
18631 s = functv.vval.v_string;
18632 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
18633 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
18634 &len, evaluate, selfdict);
18636 /* Clear the funcref afterwards, so that deleting it while
18637 * evaluating the arguments is possible (see test55). */
18638 clear_tv(&functv);
18640 /* Stop the expression evaluation when immediately aborting on
18641 * error, or when an interrupt occurred or an exception was thrown
18642 * but not caught. */
18643 if (aborting())
18645 if (ret == OK)
18646 clear_tv(rettv);
18647 ret = FAIL;
18649 dict_unref(selfdict);
18650 selfdict = NULL;
18652 else /* **arg == '[' || **arg == '.' */
18654 dict_unref(selfdict);
18655 if (rettv->v_type == VAR_DICT)
18657 selfdict = rettv->vval.v_dict;
18658 if (selfdict != NULL)
18659 ++selfdict->dv_refcount;
18661 else
18662 selfdict = NULL;
18663 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
18665 clear_tv(rettv);
18666 ret = FAIL;
18670 dict_unref(selfdict);
18671 return ret;
18675 * Allocate memory for a variable type-value, and make it empty (0 or NULL
18676 * value).
18678 static typval_T *
18679 alloc_tv()
18681 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
18685 * Allocate memory for a variable type-value, and assign a string to it.
18686 * The string "s" must have been allocated, it is consumed.
18687 * Return NULL for out of memory, the variable otherwise.
18689 static typval_T *
18690 alloc_string_tv(s)
18691 char_u *s;
18693 typval_T *rettv;
18695 rettv = alloc_tv();
18696 if (rettv != NULL)
18698 rettv->v_type = VAR_STRING;
18699 rettv->vval.v_string = s;
18701 else
18702 vim_free(s);
18703 return rettv;
18707 * Free the memory for a variable type-value.
18709 void
18710 free_tv(varp)
18711 typval_T *varp;
18713 if (varp != NULL)
18715 switch (varp->v_type)
18717 case VAR_FUNC:
18718 func_unref(varp->vval.v_string);
18719 /*FALLTHROUGH*/
18720 case VAR_STRING:
18721 vim_free(varp->vval.v_string);
18722 break;
18723 case VAR_LIST:
18724 list_unref(varp->vval.v_list);
18725 break;
18726 case VAR_DICT:
18727 dict_unref(varp->vval.v_dict);
18728 break;
18729 case VAR_NUMBER:
18730 #ifdef FEAT_FLOAT
18731 case VAR_FLOAT:
18732 #endif
18733 case VAR_UNKNOWN:
18734 break;
18735 default:
18736 EMSG2(_(e_intern2), "free_tv()");
18737 break;
18739 vim_free(varp);
18744 * Free the memory for a variable value and set the value to NULL or 0.
18746 void
18747 clear_tv(varp)
18748 typval_T *varp;
18750 if (varp != NULL)
18752 switch (varp->v_type)
18754 case VAR_FUNC:
18755 func_unref(varp->vval.v_string);
18756 /*FALLTHROUGH*/
18757 case VAR_STRING:
18758 vim_free(varp->vval.v_string);
18759 varp->vval.v_string = NULL;
18760 break;
18761 case VAR_LIST:
18762 list_unref(varp->vval.v_list);
18763 varp->vval.v_list = NULL;
18764 break;
18765 case VAR_DICT:
18766 dict_unref(varp->vval.v_dict);
18767 varp->vval.v_dict = NULL;
18768 break;
18769 case VAR_NUMBER:
18770 varp->vval.v_number = 0;
18771 break;
18772 #ifdef FEAT_FLOAT
18773 case VAR_FLOAT:
18774 varp->vval.v_float = 0.0;
18775 break;
18776 #endif
18777 case VAR_UNKNOWN:
18778 break;
18779 default:
18780 EMSG2(_(e_intern2), "clear_tv()");
18782 varp->v_lock = 0;
18787 * Set the value of a variable to NULL without freeing items.
18789 static void
18790 init_tv(varp)
18791 typval_T *varp;
18793 if (varp != NULL)
18794 vim_memset(varp, 0, sizeof(typval_T));
18798 * Get the number value of a variable.
18799 * If it is a String variable, uses vim_str2nr().
18800 * For incompatible types, return 0.
18801 * get_tv_number_chk() is similar to get_tv_number(), but informs the
18802 * caller of incompatible types: it sets *denote to TRUE if "denote"
18803 * is not NULL or returns -1 otherwise.
18805 static long
18806 get_tv_number(varp)
18807 typval_T *varp;
18809 int error = FALSE;
18811 return get_tv_number_chk(varp, &error); /* return 0L on error */
18814 long
18815 get_tv_number_chk(varp, denote)
18816 typval_T *varp;
18817 int *denote;
18819 long n = 0L;
18821 switch (varp->v_type)
18823 case VAR_NUMBER:
18824 return (long)(varp->vval.v_number);
18825 #ifdef FEAT_FLOAT
18826 case VAR_FLOAT:
18827 EMSG(_("E805: Using a Float as a Number"));
18828 break;
18829 #endif
18830 case VAR_FUNC:
18831 EMSG(_("E703: Using a Funcref as a Number"));
18832 break;
18833 case VAR_STRING:
18834 if (varp->vval.v_string != NULL)
18835 vim_str2nr(varp->vval.v_string, NULL, NULL,
18836 TRUE, TRUE, &n, NULL);
18837 return n;
18838 case VAR_LIST:
18839 EMSG(_("E745: Using a List as a Number"));
18840 break;
18841 case VAR_DICT:
18842 EMSG(_("E728: Using a Dictionary as a Number"));
18843 break;
18844 default:
18845 EMSG2(_(e_intern2), "get_tv_number()");
18846 break;
18848 if (denote == NULL) /* useful for values that must be unsigned */
18849 n = -1;
18850 else
18851 *denote = TRUE;
18852 return n;
18856 * Get the lnum from the first argument.
18857 * Also accepts ".", "$", etc., but that only works for the current buffer.
18858 * Returns -1 on error.
18860 static linenr_T
18861 get_tv_lnum(argvars)
18862 typval_T *argvars;
18864 typval_T rettv;
18865 linenr_T lnum;
18867 lnum = get_tv_number_chk(&argvars[0], NULL);
18868 if (lnum == 0) /* no valid number, try using line() */
18870 rettv.v_type = VAR_NUMBER;
18871 f_line(argvars, &rettv);
18872 lnum = rettv.vval.v_number;
18873 clear_tv(&rettv);
18875 return lnum;
18879 * Get the lnum from the first argument.
18880 * Also accepts "$", then "buf" is used.
18881 * Returns 0 on error.
18883 static linenr_T
18884 get_tv_lnum_buf(argvars, buf)
18885 typval_T *argvars;
18886 buf_T *buf;
18888 if (argvars[0].v_type == VAR_STRING
18889 && argvars[0].vval.v_string != NULL
18890 && argvars[0].vval.v_string[0] == '$'
18891 && buf != NULL)
18892 return buf->b_ml.ml_line_count;
18893 return get_tv_number_chk(&argvars[0], NULL);
18897 * Get the string value of a variable.
18898 * If it is a Number variable, the number is converted into a string.
18899 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
18900 * get_tv_string_buf() uses a given buffer.
18901 * If the String variable has never been set, return an empty string.
18902 * Never returns NULL;
18903 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
18904 * NULL on error.
18906 static char_u *
18907 get_tv_string(varp)
18908 typval_T *varp;
18910 static char_u mybuf[NUMBUFLEN];
18912 return get_tv_string_buf(varp, mybuf);
18915 static char_u *
18916 get_tv_string_buf(varp, buf)
18917 typval_T *varp;
18918 char_u *buf;
18920 char_u *res = get_tv_string_buf_chk(varp, buf);
18922 return res != NULL ? res : (char_u *)"";
18925 char_u *
18926 get_tv_string_chk(varp)
18927 typval_T *varp;
18929 static char_u mybuf[NUMBUFLEN];
18931 return get_tv_string_buf_chk(varp, mybuf);
18934 static char_u *
18935 get_tv_string_buf_chk(varp, buf)
18936 typval_T *varp;
18937 char_u *buf;
18939 switch (varp->v_type)
18941 case VAR_NUMBER:
18942 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
18943 return buf;
18944 case VAR_FUNC:
18945 EMSG(_("E729: using Funcref as a String"));
18946 break;
18947 case VAR_LIST:
18948 EMSG(_("E730: using List as a String"));
18949 break;
18950 case VAR_DICT:
18951 EMSG(_("E731: using Dictionary as a String"));
18952 break;
18953 #ifdef FEAT_FLOAT
18954 case VAR_FLOAT:
18955 EMSG(_("E806: using Float as a String"));
18956 break;
18957 #endif
18958 case VAR_STRING:
18959 if (varp->vval.v_string != NULL)
18960 return varp->vval.v_string;
18961 return (char_u *)"";
18962 default:
18963 EMSG2(_(e_intern2), "get_tv_string_buf()");
18964 break;
18966 return NULL;
18970 * Find variable "name" in the list of variables.
18971 * Return a pointer to it if found, NULL if not found.
18972 * Careful: "a:0" variables don't have a name.
18973 * When "htp" is not NULL we are writing to the variable, set "htp" to the
18974 * hashtab_T used.
18976 static dictitem_T *
18977 find_var(name, htp)
18978 char_u *name;
18979 hashtab_T **htp;
18981 char_u *varname;
18982 hashtab_T *ht;
18984 ht = find_var_ht(name, &varname);
18985 if (htp != NULL)
18986 *htp = ht;
18987 if (ht == NULL)
18988 return NULL;
18989 return find_var_in_ht(ht, varname, htp != NULL);
18993 * Find variable "varname" in hashtab "ht".
18994 * Returns NULL if not found.
18996 static dictitem_T *
18997 find_var_in_ht(ht, varname, writing)
18998 hashtab_T *ht;
18999 char_u *varname;
19000 int writing;
19002 hashitem_T *hi;
19004 if (*varname == NUL)
19006 /* Must be something like "s:", otherwise "ht" would be NULL. */
19007 switch (varname[-2])
19009 case 's': return &SCRIPT_SV(current_SID).sv_var;
19010 case 'g': return &globvars_var;
19011 case 'v': return &vimvars_var;
19012 case 'b': return &curbuf->b_bufvar;
19013 case 'w': return &curwin->w_winvar;
19014 #ifdef FEAT_WINDOWS
19015 case 't': return &curtab->tp_winvar;
19016 #endif
19017 case 'l': return current_funccal == NULL
19018 ? NULL : &current_funccal->l_vars_var;
19019 case 'a': return current_funccal == NULL
19020 ? NULL : &current_funccal->l_avars_var;
19022 return NULL;
19025 hi = hash_find(ht, varname);
19026 if (HASHITEM_EMPTY(hi))
19028 /* For global variables we may try auto-loading the script. If it
19029 * worked find the variable again. Don't auto-load a script if it was
19030 * loaded already, otherwise it would be loaded every time when
19031 * checking if a function name is a Funcref variable. */
19032 if (ht == &globvarht && !writing
19033 && script_autoload(varname, FALSE) && !aborting())
19034 hi = hash_find(ht, varname);
19035 if (HASHITEM_EMPTY(hi))
19036 return NULL;
19038 return HI2DI(hi);
19042 * Find the hashtab used for a variable name.
19043 * Set "varname" to the start of name without ':'.
19045 static hashtab_T *
19046 find_var_ht(name, varname)
19047 char_u *name;
19048 char_u **varname;
19050 hashitem_T *hi;
19052 if (name[1] != ':')
19054 /* The name must not start with a colon or #. */
19055 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
19056 return NULL;
19057 *varname = name;
19059 /* "version" is "v:version" in all scopes */
19060 hi = hash_find(&compat_hashtab, name);
19061 if (!HASHITEM_EMPTY(hi))
19062 return &compat_hashtab;
19064 if (current_funccal == NULL)
19065 return &globvarht; /* global variable */
19066 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
19068 *varname = name + 2;
19069 if (*name == 'g') /* global variable */
19070 return &globvarht;
19071 /* There must be no ':' or '#' in the rest of the name, unless g: is used
19073 if (vim_strchr(name + 2, ':') != NULL
19074 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
19075 return NULL;
19076 if (*name == 'b') /* buffer variable */
19077 return &curbuf->b_vars.dv_hashtab;
19078 if (*name == 'w') /* window variable */
19079 return &curwin->w_vars.dv_hashtab;
19080 #ifdef FEAT_WINDOWS
19081 if (*name == 't') /* tab page variable */
19082 return &curtab->tp_vars.dv_hashtab;
19083 #endif
19084 if (*name == 'v') /* v: variable */
19085 return &vimvarht;
19086 if (*name == 'a' && current_funccal != NULL) /* function argument */
19087 return &current_funccal->l_avars.dv_hashtab;
19088 if (*name == 'l' && current_funccal != NULL) /* local function variable */
19089 return &current_funccal->l_vars.dv_hashtab;
19090 if (*name == 's' /* script variable */
19091 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
19092 return &SCRIPT_VARS(current_SID);
19093 return NULL;
19097 * Get the string value of a (global/local) variable.
19098 * Returns NULL when it doesn't exist.
19100 char_u *
19101 get_var_value(name)
19102 char_u *name;
19104 dictitem_T *v;
19106 v = find_var(name, NULL);
19107 if (v == NULL)
19108 return NULL;
19109 return get_tv_string(&v->di_tv);
19113 * Allocate a new hashtab for a sourced script. It will be used while
19114 * sourcing this script and when executing functions defined in the script.
19116 void
19117 new_script_vars(id)
19118 scid_T id;
19120 int i;
19121 hashtab_T *ht;
19122 scriptvar_T *sv;
19124 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
19126 /* Re-allocating ga_data means that an ht_array pointing to
19127 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
19128 * at its init value. Also reset "v_dict", it's always the same. */
19129 for (i = 1; i <= ga_scripts.ga_len; ++i)
19131 ht = &SCRIPT_VARS(i);
19132 if (ht->ht_mask == HT_INIT_SIZE - 1)
19133 ht->ht_array = ht->ht_smallarray;
19134 sv = &SCRIPT_SV(i);
19135 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
19138 while (ga_scripts.ga_len < id)
19140 sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
19141 init_var_dict(&sv->sv_dict, &sv->sv_var);
19142 ++ga_scripts.ga_len;
19148 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
19149 * point to it.
19151 void
19152 init_var_dict(dict, dict_var)
19153 dict_T *dict;
19154 dictitem_T *dict_var;
19156 hash_init(&dict->dv_hashtab);
19157 dict->dv_refcount = DO_NOT_FREE_CNT;
19158 dict->dv_copyID = 0;
19159 dict_var->di_tv.vval.v_dict = dict;
19160 dict_var->di_tv.v_type = VAR_DICT;
19161 dict_var->di_tv.v_lock = VAR_FIXED;
19162 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
19163 dict_var->di_key[0] = NUL;
19167 * Clean up a list of internal variables.
19168 * Frees all allocated variables and the value they contain.
19169 * Clears hashtab "ht", does not free it.
19171 void
19172 vars_clear(ht)
19173 hashtab_T *ht;
19175 vars_clear_ext(ht, TRUE);
19179 * Like vars_clear(), but only free the value if "free_val" is TRUE.
19181 static void
19182 vars_clear_ext(ht, free_val)
19183 hashtab_T *ht;
19184 int free_val;
19186 int todo;
19187 hashitem_T *hi;
19188 dictitem_T *v;
19190 hash_lock(ht);
19191 todo = (int)ht->ht_used;
19192 for (hi = ht->ht_array; todo > 0; ++hi)
19194 if (!HASHITEM_EMPTY(hi))
19196 --todo;
19198 /* Free the variable. Don't remove it from the hashtab,
19199 * ht_array might change then. hash_clear() takes care of it
19200 * later. */
19201 v = HI2DI(hi);
19202 if (free_val)
19203 clear_tv(&v->di_tv);
19204 if ((v->di_flags & DI_FLAGS_FIX) == 0)
19205 vim_free(v);
19208 hash_clear(ht);
19209 ht->ht_used = 0;
19213 * Delete a variable from hashtab "ht" at item "hi".
19214 * Clear the variable value and free the dictitem.
19216 static void
19217 delete_var(ht, hi)
19218 hashtab_T *ht;
19219 hashitem_T *hi;
19221 dictitem_T *di = HI2DI(hi);
19223 hash_remove(ht, hi);
19224 clear_tv(&di->di_tv);
19225 vim_free(di);
19229 * List the value of one internal variable.
19231 static void
19232 list_one_var(v, prefix, first)
19233 dictitem_T *v;
19234 char_u *prefix;
19235 int *first;
19237 char_u *tofree;
19238 char_u *s;
19239 char_u numbuf[NUMBUFLEN];
19241 current_copyID += COPYID_INC;
19242 s = echo_string(&v->di_tv, &tofree, numbuf, current_copyID);
19243 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
19244 s == NULL ? (char_u *)"" : s, first);
19245 vim_free(tofree);
19248 static void
19249 list_one_var_a(prefix, name, type, string, first)
19250 char_u *prefix;
19251 char_u *name;
19252 int type;
19253 char_u *string;
19254 int *first; /* when TRUE clear rest of screen and set to FALSE */
19256 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
19257 msg_start();
19258 msg_puts(prefix);
19259 if (name != NULL) /* "a:" vars don't have a name stored */
19260 msg_puts(name);
19261 msg_putchar(' ');
19262 msg_advance(22);
19263 if (type == VAR_NUMBER)
19264 msg_putchar('#');
19265 else if (type == VAR_FUNC)
19266 msg_putchar('*');
19267 else if (type == VAR_LIST)
19269 msg_putchar('[');
19270 if (*string == '[')
19271 ++string;
19273 else if (type == VAR_DICT)
19275 msg_putchar('{');
19276 if (*string == '{')
19277 ++string;
19279 else
19280 msg_putchar(' ');
19282 msg_outtrans(string);
19284 if (type == VAR_FUNC)
19285 msg_puts((char_u *)"()");
19286 if (*first)
19288 msg_clr_eos();
19289 *first = FALSE;
19294 * Set variable "name" to value in "tv".
19295 * If the variable already exists, the value is updated.
19296 * Otherwise the variable is created.
19298 static void
19299 set_var(name, tv, copy)
19300 char_u *name;
19301 typval_T *tv;
19302 int copy; /* make copy of value in "tv" */
19304 dictitem_T *v;
19305 char_u *varname;
19306 hashtab_T *ht;
19307 char_u *p;
19309 ht = find_var_ht(name, &varname);
19310 if (ht == NULL || *varname == NUL)
19312 EMSG2(_(e_illvar), name);
19313 return;
19315 v = find_var_in_ht(ht, varname, TRUE);
19317 if (tv->v_type == VAR_FUNC)
19319 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
19320 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
19321 ? name[2] : name[0]))
19323 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
19324 return;
19326 /* Don't allow hiding a function. When "v" is not NULL we migth be
19327 * assigning another function to the same var, the type is checked
19328 * below. */
19329 if (v == NULL && function_exists(name))
19331 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
19332 name);
19333 return;
19337 if (v != NULL)
19339 /* existing variable, need to clear the value */
19340 if (var_check_ro(v->di_flags, name)
19341 || tv_check_lock(v->di_tv.v_lock, name))
19342 return;
19343 if (v->di_tv.v_type != tv->v_type
19344 && !((v->di_tv.v_type == VAR_STRING
19345 || v->di_tv.v_type == VAR_NUMBER)
19346 && (tv->v_type == VAR_STRING
19347 || tv->v_type == VAR_NUMBER))
19348 #ifdef FEAT_FLOAT
19349 && !((v->di_tv.v_type == VAR_NUMBER
19350 || v->di_tv.v_type == VAR_FLOAT)
19351 && (tv->v_type == VAR_NUMBER
19352 || tv->v_type == VAR_FLOAT))
19353 #endif
19356 EMSG2(_("E706: Variable type mismatch for: %s"), name);
19357 return;
19361 * Handle setting internal v: variables separately: we don't change
19362 * the type.
19364 if (ht == &vimvarht)
19366 if (v->di_tv.v_type == VAR_STRING)
19368 vim_free(v->di_tv.vval.v_string);
19369 if (copy || tv->v_type != VAR_STRING)
19370 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
19371 else
19373 /* Take over the string to avoid an extra alloc/free. */
19374 v->di_tv.vval.v_string = tv->vval.v_string;
19375 tv->vval.v_string = NULL;
19378 else if (v->di_tv.v_type != VAR_NUMBER)
19379 EMSG2(_(e_intern2), "set_var()");
19380 else
19382 v->di_tv.vval.v_number = get_tv_number(tv);
19383 if (STRCMP(varname, "searchforward") == 0)
19384 set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
19386 return;
19389 clear_tv(&v->di_tv);
19391 else /* add a new variable */
19393 /* Can't add "v:" variable. */
19394 if (ht == &vimvarht)
19396 EMSG2(_(e_illvar), name);
19397 return;
19400 /* Make sure the variable name is valid. */
19401 for (p = varname; *p != NUL; ++p)
19402 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
19403 && *p != AUTOLOAD_CHAR)
19405 EMSG2(_(e_illvar), varname);
19406 return;
19409 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
19410 + STRLEN(varname)));
19411 if (v == NULL)
19412 return;
19413 STRCPY(v->di_key, varname);
19414 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
19416 vim_free(v);
19417 return;
19419 v->di_flags = 0;
19422 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
19423 copy_tv(tv, &v->di_tv);
19424 else
19426 v->di_tv = *tv;
19427 v->di_tv.v_lock = 0;
19428 init_tv(tv);
19433 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
19434 * Also give an error message.
19436 static int
19437 var_check_ro(flags, name)
19438 int flags;
19439 char_u *name;
19441 if (flags & DI_FLAGS_RO)
19443 EMSG2(_(e_readonlyvar), name);
19444 return TRUE;
19446 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
19448 EMSG2(_(e_readonlysbx), name);
19449 return TRUE;
19451 return FALSE;
19455 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
19456 * Also give an error message.
19458 static int
19459 var_check_fixed(flags, name)
19460 int flags;
19461 char_u *name;
19463 if (flags & DI_FLAGS_FIX)
19465 EMSG2(_("E795: Cannot delete variable %s"), name);
19466 return TRUE;
19468 return FALSE;
19472 * Return TRUE if typeval "tv" is set to be locked (immutable).
19473 * Also give an error message, using "name".
19475 static int
19476 tv_check_lock(lock, name)
19477 int lock;
19478 char_u *name;
19480 if (lock & VAR_LOCKED)
19482 EMSG2(_("E741: Value is locked: %s"),
19483 name == NULL ? (char_u *)_("Unknown") : name);
19484 return TRUE;
19486 if (lock & VAR_FIXED)
19488 EMSG2(_("E742: Cannot change value of %s"),
19489 name == NULL ? (char_u *)_("Unknown") : name);
19490 return TRUE;
19492 return FALSE;
19496 * Copy the values from typval_T "from" to typval_T "to".
19497 * When needed allocates string or increases reference count.
19498 * Does not make a copy of a list or dict but copies the reference!
19499 * It is OK for "from" and "to" to point to the same item. This is used to
19500 * make a copy later.
19502 void
19503 copy_tv(from, to)
19504 typval_T *from;
19505 typval_T *to;
19507 to->v_type = from->v_type;
19508 to->v_lock = 0;
19509 switch (from->v_type)
19511 case VAR_NUMBER:
19512 to->vval.v_number = from->vval.v_number;
19513 break;
19514 #ifdef FEAT_FLOAT
19515 case VAR_FLOAT:
19516 to->vval.v_float = from->vval.v_float;
19517 break;
19518 #endif
19519 case VAR_STRING:
19520 case VAR_FUNC:
19521 if (from->vval.v_string == NULL)
19522 to->vval.v_string = NULL;
19523 else
19525 to->vval.v_string = vim_strsave(from->vval.v_string);
19526 if (from->v_type == VAR_FUNC)
19527 func_ref(to->vval.v_string);
19529 break;
19530 case VAR_LIST:
19531 if (from->vval.v_list == NULL)
19532 to->vval.v_list = NULL;
19533 else
19535 to->vval.v_list = from->vval.v_list;
19536 ++to->vval.v_list->lv_refcount;
19538 break;
19539 case VAR_DICT:
19540 if (from->vval.v_dict == NULL)
19541 to->vval.v_dict = NULL;
19542 else
19544 to->vval.v_dict = from->vval.v_dict;
19545 ++to->vval.v_dict->dv_refcount;
19547 break;
19548 default:
19549 EMSG2(_(e_intern2), "copy_tv()");
19550 break;
19555 * Make a copy of an item.
19556 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
19557 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
19558 * reference to an already copied list/dict can be used.
19559 * Returns FAIL or OK.
19561 static int
19562 item_copy(from, to, deep, copyID)
19563 typval_T *from;
19564 typval_T *to;
19565 int deep;
19566 int copyID;
19568 static int recurse = 0;
19569 int ret = OK;
19571 if (recurse >= DICT_MAXNEST)
19573 EMSG(_("E698: variable nested too deep for making a copy"));
19574 return FAIL;
19576 ++recurse;
19578 switch (from->v_type)
19580 case VAR_NUMBER:
19581 #ifdef FEAT_FLOAT
19582 case VAR_FLOAT:
19583 #endif
19584 case VAR_STRING:
19585 case VAR_FUNC:
19586 copy_tv(from, to);
19587 break;
19588 case VAR_LIST:
19589 to->v_type = VAR_LIST;
19590 to->v_lock = 0;
19591 if (from->vval.v_list == NULL)
19592 to->vval.v_list = NULL;
19593 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
19595 /* use the copy made earlier */
19596 to->vval.v_list = from->vval.v_list->lv_copylist;
19597 ++to->vval.v_list->lv_refcount;
19599 else
19600 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
19601 if (to->vval.v_list == NULL)
19602 ret = FAIL;
19603 break;
19604 case VAR_DICT:
19605 to->v_type = VAR_DICT;
19606 to->v_lock = 0;
19607 if (from->vval.v_dict == NULL)
19608 to->vval.v_dict = NULL;
19609 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
19611 /* use the copy made earlier */
19612 to->vval.v_dict = from->vval.v_dict->dv_copydict;
19613 ++to->vval.v_dict->dv_refcount;
19615 else
19616 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
19617 if (to->vval.v_dict == NULL)
19618 ret = FAIL;
19619 break;
19620 default:
19621 EMSG2(_(e_intern2), "item_copy()");
19622 ret = FAIL;
19624 --recurse;
19625 return ret;
19629 * ":echo expr1 ..." print each argument separated with a space, add a
19630 * newline at the end.
19631 * ":echon expr1 ..." print each argument plain.
19633 void
19634 ex_echo(eap)
19635 exarg_T *eap;
19637 char_u *arg = eap->arg;
19638 typval_T rettv;
19639 char_u *tofree;
19640 char_u *p;
19641 int needclr = TRUE;
19642 int atstart = TRUE;
19643 char_u numbuf[NUMBUFLEN];
19645 if (eap->skip)
19646 ++emsg_skip;
19647 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
19649 /* If eval1() causes an error message the text from the command may
19650 * still need to be cleared. E.g., "echo 22,44". */
19651 need_clr_eos = needclr;
19653 p = arg;
19654 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19657 * Report the invalid expression unless the expression evaluation
19658 * has been cancelled due to an aborting error, an interrupt, or an
19659 * exception.
19661 if (!aborting())
19662 EMSG2(_(e_invexpr2), p);
19663 need_clr_eos = FALSE;
19664 break;
19666 need_clr_eos = FALSE;
19668 if (!eap->skip)
19670 if (atstart)
19672 atstart = FALSE;
19673 /* Call msg_start() after eval1(), evaluating the expression
19674 * may cause a message to appear. */
19675 if (eap->cmdidx == CMD_echo)
19676 msg_start();
19678 else if (eap->cmdidx == CMD_echo)
19679 msg_puts_attr((char_u *)" ", echo_attr);
19680 current_copyID += COPYID_INC;
19681 p = echo_string(&rettv, &tofree, numbuf, current_copyID);
19682 if (p != NULL)
19683 for ( ; *p != NUL && !got_int; ++p)
19685 if (*p == '\n' || *p == '\r' || *p == TAB)
19687 if (*p != TAB && needclr)
19689 /* remove any text still there from the command */
19690 msg_clr_eos();
19691 needclr = FALSE;
19693 msg_putchar_attr(*p, echo_attr);
19695 else
19697 #ifdef FEAT_MBYTE
19698 if (has_mbyte)
19700 int i = (*mb_ptr2len)(p);
19702 (void)msg_outtrans_len_attr(p, i, echo_attr);
19703 p += i - 1;
19705 else
19706 #endif
19707 (void)msg_outtrans_len_attr(p, 1, echo_attr);
19710 vim_free(tofree);
19712 clear_tv(&rettv);
19713 arg = skipwhite(arg);
19715 eap->nextcmd = check_nextcmd(arg);
19717 if (eap->skip)
19718 --emsg_skip;
19719 else
19721 /* remove text that may still be there from the command */
19722 if (needclr)
19723 msg_clr_eos();
19724 if (eap->cmdidx == CMD_echo)
19725 msg_end();
19730 * ":echohl {name}".
19732 void
19733 ex_echohl(eap)
19734 exarg_T *eap;
19736 int id;
19738 id = syn_name2id(eap->arg);
19739 if (id == 0)
19740 echo_attr = 0;
19741 else
19742 echo_attr = syn_id2attr(id);
19746 * ":execute expr1 ..." execute the result of an expression.
19747 * ":echomsg expr1 ..." Print a message
19748 * ":echoerr expr1 ..." Print an error
19749 * Each gets spaces around each argument and a newline at the end for
19750 * echo commands
19752 void
19753 ex_execute(eap)
19754 exarg_T *eap;
19756 char_u *arg = eap->arg;
19757 typval_T rettv;
19758 int ret = OK;
19759 char_u *p;
19760 garray_T ga;
19761 int len;
19762 int save_did_emsg;
19764 ga_init2(&ga, 1, 80);
19766 if (eap->skip)
19767 ++emsg_skip;
19768 while (*arg != NUL && *arg != '|' && *arg != '\n')
19770 p = arg;
19771 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19774 * Report the invalid expression unless the expression evaluation
19775 * has been cancelled due to an aborting error, an interrupt, or an
19776 * exception.
19778 if (!aborting())
19779 EMSG2(_(e_invexpr2), p);
19780 ret = FAIL;
19781 break;
19784 if (!eap->skip)
19786 p = get_tv_string(&rettv);
19787 len = (int)STRLEN(p);
19788 if (ga_grow(&ga, len + 2) == FAIL)
19790 clear_tv(&rettv);
19791 ret = FAIL;
19792 break;
19794 if (ga.ga_len)
19795 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
19796 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
19797 ga.ga_len += len;
19800 clear_tv(&rettv);
19801 arg = skipwhite(arg);
19804 if (ret != FAIL && ga.ga_data != NULL)
19806 if (eap->cmdidx == CMD_echomsg)
19808 MSG_ATTR(ga.ga_data, echo_attr);
19809 out_flush();
19811 else if (eap->cmdidx == CMD_echoerr)
19813 /* We don't want to abort following commands, restore did_emsg. */
19814 save_did_emsg = did_emsg;
19815 EMSG((char_u *)ga.ga_data);
19816 if (!force_abort)
19817 did_emsg = save_did_emsg;
19819 else if (eap->cmdidx == CMD_execute)
19820 do_cmdline((char_u *)ga.ga_data,
19821 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
19824 ga_clear(&ga);
19826 if (eap->skip)
19827 --emsg_skip;
19829 eap->nextcmd = check_nextcmd(arg);
19833 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
19834 * "arg" points to the "&" or '+' when called, to "option" when returning.
19835 * Returns NULL when no option name found. Otherwise pointer to the char
19836 * after the option name.
19838 static char_u *
19839 find_option_end(arg, opt_flags)
19840 char_u **arg;
19841 int *opt_flags;
19843 char_u *p = *arg;
19845 ++p;
19846 if (*p == 'g' && p[1] == ':')
19848 *opt_flags = OPT_GLOBAL;
19849 p += 2;
19851 else if (*p == 'l' && p[1] == ':')
19853 *opt_flags = OPT_LOCAL;
19854 p += 2;
19856 else
19857 *opt_flags = 0;
19859 if (!ASCII_ISALPHA(*p))
19860 return NULL;
19861 *arg = p;
19863 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
19864 p += 4; /* termcap option */
19865 else
19866 while (ASCII_ISALPHA(*p))
19867 ++p;
19868 return p;
19872 * ":function"
19874 void
19875 ex_function(eap)
19876 exarg_T *eap;
19878 char_u *theline;
19879 int j;
19880 int c;
19881 int saved_did_emsg;
19882 char_u *name = NULL;
19883 char_u *p;
19884 char_u *arg;
19885 char_u *line_arg = NULL;
19886 garray_T newargs;
19887 garray_T newlines;
19888 int varargs = FALSE;
19889 int mustend = FALSE;
19890 int flags = 0;
19891 ufunc_T *fp;
19892 int indent;
19893 int nesting;
19894 char_u *skip_until = NULL;
19895 dictitem_T *v;
19896 funcdict_T fudi;
19897 static int func_nr = 0; /* number for nameless function */
19898 int paren;
19899 hashtab_T *ht;
19900 int todo;
19901 hashitem_T *hi;
19902 int sourcing_lnum_off;
19905 * ":function" without argument: list functions.
19907 if (ends_excmd(*eap->arg))
19909 if (!eap->skip)
19911 todo = (int)func_hashtab.ht_used;
19912 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19914 if (!HASHITEM_EMPTY(hi))
19916 --todo;
19917 fp = HI2UF(hi);
19918 if (!isdigit(*fp->uf_name))
19919 list_func_head(fp, FALSE);
19923 eap->nextcmd = check_nextcmd(eap->arg);
19924 return;
19928 * ":function /pat": list functions matching pattern.
19930 if (*eap->arg == '/')
19932 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
19933 if (!eap->skip)
19935 regmatch_T regmatch;
19937 c = *p;
19938 *p = NUL;
19939 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
19940 *p = c;
19941 if (regmatch.regprog != NULL)
19943 regmatch.rm_ic = p_ic;
19945 todo = (int)func_hashtab.ht_used;
19946 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19948 if (!HASHITEM_EMPTY(hi))
19950 --todo;
19951 fp = HI2UF(hi);
19952 if (!isdigit(*fp->uf_name)
19953 && vim_regexec(&regmatch, fp->uf_name, 0))
19954 list_func_head(fp, FALSE);
19957 vim_free(regmatch.regprog);
19960 if (*p == '/')
19961 ++p;
19962 eap->nextcmd = check_nextcmd(p);
19963 return;
19967 * Get the function name. There are these situations:
19968 * func normal function name
19969 * "name" == func, "fudi.fd_dict" == NULL
19970 * dict.func new dictionary entry
19971 * "name" == NULL, "fudi.fd_dict" set,
19972 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
19973 * dict.func existing dict entry with a Funcref
19974 * "name" == func, "fudi.fd_dict" set,
19975 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19976 * dict.func existing dict entry that's not a Funcref
19977 * "name" == NULL, "fudi.fd_dict" set,
19978 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19980 p = eap->arg;
19981 name = trans_function_name(&p, eap->skip, 0, &fudi);
19982 paren = (vim_strchr(p, '(') != NULL);
19983 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
19986 * Return on an invalid expression in braces, unless the expression
19987 * evaluation has been cancelled due to an aborting error, an
19988 * interrupt, or an exception.
19990 if (!aborting())
19992 if (!eap->skip && fudi.fd_newkey != NULL)
19993 EMSG2(_(e_dictkey), fudi.fd_newkey);
19994 vim_free(fudi.fd_newkey);
19995 return;
19997 else
19998 eap->skip = TRUE;
20001 /* An error in a function call during evaluation of an expression in magic
20002 * braces should not cause the function not to be defined. */
20003 saved_did_emsg = did_emsg;
20004 did_emsg = FALSE;
20007 * ":function func" with only function name: list function.
20009 if (!paren)
20011 if (!ends_excmd(*skipwhite(p)))
20013 EMSG(_(e_trailing));
20014 goto ret_free;
20016 eap->nextcmd = check_nextcmd(p);
20017 if (eap->nextcmd != NULL)
20018 *p = NUL;
20019 if (!eap->skip && !got_int)
20021 fp = find_func(name);
20022 if (fp != NULL)
20024 list_func_head(fp, TRUE);
20025 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
20027 if (FUNCLINE(fp, j) == NULL)
20028 continue;
20029 msg_putchar('\n');
20030 msg_outnum((long)(j + 1));
20031 if (j < 9)
20032 msg_putchar(' ');
20033 if (j < 99)
20034 msg_putchar(' ');
20035 msg_prt_line(FUNCLINE(fp, j), FALSE);
20036 out_flush(); /* show a line at a time */
20037 ui_breakcheck();
20039 if (!got_int)
20041 msg_putchar('\n');
20042 msg_puts((char_u *)" endfunction");
20045 else
20046 emsg_funcname(N_("E123: Undefined function: %s"), name);
20048 goto ret_free;
20052 * ":function name(arg1, arg2)" Define function.
20054 p = skipwhite(p);
20055 if (*p != '(')
20057 if (!eap->skip)
20059 EMSG2(_("E124: Missing '(': %s"), eap->arg);
20060 goto ret_free;
20062 /* attempt to continue by skipping some text */
20063 if (vim_strchr(p, '(') != NULL)
20064 p = vim_strchr(p, '(');
20066 p = skipwhite(p + 1);
20068 ga_init2(&newargs, (int)sizeof(char_u *), 3);
20069 ga_init2(&newlines, (int)sizeof(char_u *), 3);
20071 if (!eap->skip)
20073 /* Check the name of the function. Unless it's a dictionary function
20074 * (that we are overwriting). */
20075 if (name != NULL)
20076 arg = name;
20077 else
20078 arg = fudi.fd_newkey;
20079 if (arg != NULL && (fudi.fd_di == NULL
20080 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
20082 if (*arg == K_SPECIAL)
20083 j = 3;
20084 else
20085 j = 0;
20086 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
20087 : eval_isnamec(arg[j])))
20088 ++j;
20089 if (arg[j] != NUL)
20090 emsg_funcname((char *)e_invarg2, arg);
20095 * Isolate the arguments: "arg1, arg2, ...)"
20097 while (*p != ')')
20099 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
20101 varargs = TRUE;
20102 p += 3;
20103 mustend = TRUE;
20105 else
20107 arg = p;
20108 while (ASCII_ISALNUM(*p) || *p == '_')
20109 ++p;
20110 if (arg == p || isdigit(*arg)
20111 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
20112 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
20114 if (!eap->skip)
20115 EMSG2(_("E125: Illegal argument: %s"), arg);
20116 break;
20118 if (ga_grow(&newargs, 1) == FAIL)
20119 goto erret;
20120 c = *p;
20121 *p = NUL;
20122 arg = vim_strsave(arg);
20123 if (arg == NULL)
20124 goto erret;
20125 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
20126 *p = c;
20127 newargs.ga_len++;
20128 if (*p == ',')
20129 ++p;
20130 else
20131 mustend = TRUE;
20133 p = skipwhite(p);
20134 if (mustend && *p != ')')
20136 if (!eap->skip)
20137 EMSG2(_(e_invarg2), eap->arg);
20138 break;
20141 ++p; /* skip the ')' */
20143 /* find extra arguments "range", "dict" and "abort" */
20144 for (;;)
20146 p = skipwhite(p);
20147 if (STRNCMP(p, "range", 5) == 0)
20149 flags |= FC_RANGE;
20150 p += 5;
20152 else if (STRNCMP(p, "dict", 4) == 0)
20154 flags |= FC_DICT;
20155 p += 4;
20157 else if (STRNCMP(p, "abort", 5) == 0)
20159 flags |= FC_ABORT;
20160 p += 5;
20162 else
20163 break;
20166 /* When there is a line break use what follows for the function body.
20167 * Makes 'exe "func Test()\n...\nendfunc"' work. */
20168 if (*p == '\n')
20169 line_arg = p + 1;
20170 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
20171 EMSG(_(e_trailing));
20174 * Read the body of the function, until ":endfunction" is found.
20176 if (KeyTyped)
20178 /* Check if the function already exists, don't let the user type the
20179 * whole function before telling him it doesn't work! For a script we
20180 * need to skip the body to be able to find what follows. */
20181 if (!eap->skip && !eap->forceit)
20183 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
20184 EMSG(_(e_funcdict));
20185 else if (name != NULL && find_func(name) != NULL)
20186 emsg_funcname(e_funcexts, name);
20189 if (!eap->skip && did_emsg)
20190 goto erret;
20192 msg_putchar('\n'); /* don't overwrite the function name */
20193 cmdline_row = msg_row;
20196 indent = 2;
20197 nesting = 0;
20198 for (;;)
20200 msg_scroll = TRUE;
20201 need_wait_return = FALSE;
20202 sourcing_lnum_off = sourcing_lnum;
20204 if (line_arg != NULL)
20206 /* Use eap->arg, split up in parts by line breaks. */
20207 theline = line_arg;
20208 p = vim_strchr(theline, '\n');
20209 if (p == NULL)
20210 line_arg += STRLEN(line_arg);
20211 else
20213 *p = NUL;
20214 line_arg = p + 1;
20217 else if (eap->getline == NULL)
20218 theline = getcmdline(':', 0L, indent);
20219 else
20220 theline = eap->getline(':', eap->cookie, indent);
20221 if (KeyTyped)
20222 lines_left = Rows - 1;
20223 if (theline == NULL)
20225 EMSG(_("E126: Missing :endfunction"));
20226 goto erret;
20229 /* Detect line continuation: sourcing_lnum increased more than one. */
20230 if (sourcing_lnum > sourcing_lnum_off + 1)
20231 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
20232 else
20233 sourcing_lnum_off = 0;
20235 if (skip_until != NULL)
20237 /* between ":append" and "." and between ":python <<EOF" and "EOF"
20238 * don't check for ":endfunc". */
20239 if (STRCMP(theline, skip_until) == 0)
20241 vim_free(skip_until);
20242 skip_until = NULL;
20245 else
20247 /* skip ':' and blanks*/
20248 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
20251 /* Check for "endfunction". */
20252 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
20254 if (line_arg == NULL)
20255 vim_free(theline);
20256 break;
20259 /* Increase indent inside "if", "while", "for" and "try", decrease
20260 * at "end". */
20261 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
20262 indent -= 2;
20263 else if (STRNCMP(p, "if", 2) == 0
20264 || STRNCMP(p, "wh", 2) == 0
20265 || STRNCMP(p, "for", 3) == 0
20266 || STRNCMP(p, "try", 3) == 0)
20267 indent += 2;
20269 /* Check for defining a function inside this function. */
20270 if (checkforcmd(&p, "function", 2))
20272 if (*p == '!')
20273 p = skipwhite(p + 1);
20274 p += eval_fname_script(p);
20275 if (ASCII_ISALPHA(*p))
20277 vim_free(trans_function_name(&p, TRUE, 0, NULL));
20278 if (*skipwhite(p) == '(')
20280 ++nesting;
20281 indent += 2;
20286 /* Check for ":append" or ":insert". */
20287 p = skip_range(p, NULL);
20288 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
20289 || (p[0] == 'i'
20290 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
20291 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
20292 skip_until = vim_strsave((char_u *)".");
20294 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
20295 arg = skipwhite(skiptowhite(p));
20296 if (arg[0] == '<' && arg[1] =='<'
20297 && ((p[0] == 'p' && p[1] == 'y'
20298 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
20299 || (p[0] == 'p' && p[1] == 'e'
20300 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
20301 || (p[0] == 't' && p[1] == 'c'
20302 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
20303 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
20304 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
20305 || (p[0] == 'm' && p[1] == 'z'
20306 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
20309 /* ":python <<" continues until a dot, like ":append" */
20310 p = skipwhite(arg + 2);
20311 if (*p == NUL)
20312 skip_until = vim_strsave((char_u *)".");
20313 else
20314 skip_until = vim_strsave(p);
20318 /* Add the line to the function. */
20319 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
20321 if (line_arg == NULL)
20322 vim_free(theline);
20323 goto erret;
20326 /* Copy the line to newly allocated memory. get_one_sourceline()
20327 * allocates 250 bytes per line, this saves 80% on average. The cost
20328 * is an extra alloc/free. */
20329 p = vim_strsave(theline);
20330 if (p != NULL)
20332 if (line_arg == NULL)
20333 vim_free(theline);
20334 theline = p;
20337 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
20339 /* Add NULL lines for continuation lines, so that the line count is
20340 * equal to the index in the growarray. */
20341 while (sourcing_lnum_off-- > 0)
20342 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
20344 /* Check for end of eap->arg. */
20345 if (line_arg != NULL && *line_arg == NUL)
20346 line_arg = NULL;
20349 /* Don't define the function when skipping commands or when an error was
20350 * detected. */
20351 if (eap->skip || did_emsg)
20352 goto erret;
20355 * If there are no errors, add the function
20357 if (fudi.fd_dict == NULL)
20359 v = find_var(name, &ht);
20360 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
20362 emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
20363 name);
20364 goto erret;
20367 fp = find_func(name);
20368 if (fp != NULL)
20370 if (!eap->forceit)
20372 emsg_funcname(e_funcexts, name);
20373 goto erret;
20375 if (fp->uf_calls > 0)
20377 emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"),
20378 name);
20379 goto erret;
20381 /* redefine existing function */
20382 ga_clear_strings(&(fp->uf_args));
20383 ga_clear_strings(&(fp->uf_lines));
20384 vim_free(name);
20385 name = NULL;
20388 else
20390 char numbuf[20];
20392 fp = NULL;
20393 if (fudi.fd_newkey == NULL && !eap->forceit)
20395 EMSG(_(e_funcdict));
20396 goto erret;
20398 if (fudi.fd_di == NULL)
20400 /* Can't add a function to a locked dictionary */
20401 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
20402 goto erret;
20404 /* Can't change an existing function if it is locked */
20405 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
20406 goto erret;
20408 /* Give the function a sequential number. Can only be used with a
20409 * Funcref! */
20410 vim_free(name);
20411 sprintf(numbuf, "%d", ++func_nr);
20412 name = vim_strsave((char_u *)numbuf);
20413 if (name == NULL)
20414 goto erret;
20417 if (fp == NULL)
20419 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
20421 int slen, plen;
20422 char_u *scriptname;
20424 /* Check that the autoload name matches the script name. */
20425 j = FAIL;
20426 if (sourcing_name != NULL)
20428 scriptname = autoload_name(name);
20429 if (scriptname != NULL)
20431 p = vim_strchr(scriptname, '/');
20432 plen = (int)STRLEN(p);
20433 slen = (int)STRLEN(sourcing_name);
20434 if (slen > plen && fnamecmp(p,
20435 sourcing_name + slen - plen) == 0)
20436 j = OK;
20437 vim_free(scriptname);
20440 if (j == FAIL)
20442 EMSG2(_("E746: Function name does not match script file name: %s"), name);
20443 goto erret;
20447 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
20448 if (fp == NULL)
20449 goto erret;
20451 if (fudi.fd_dict != NULL)
20453 if (fudi.fd_di == NULL)
20455 /* add new dict entry */
20456 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
20457 if (fudi.fd_di == NULL)
20459 vim_free(fp);
20460 goto erret;
20462 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
20464 vim_free(fudi.fd_di);
20465 vim_free(fp);
20466 goto erret;
20469 else
20470 /* overwrite existing dict entry */
20471 clear_tv(&fudi.fd_di->di_tv);
20472 fudi.fd_di->di_tv.v_type = VAR_FUNC;
20473 fudi.fd_di->di_tv.v_lock = 0;
20474 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
20475 fp->uf_refcount = 1;
20477 /* behave like "dict" was used */
20478 flags |= FC_DICT;
20481 /* insert the new function in the function list */
20482 STRCPY(fp->uf_name, name);
20483 hash_add(&func_hashtab, UF2HIKEY(fp));
20485 fp->uf_args = newargs;
20486 fp->uf_lines = newlines;
20487 #ifdef FEAT_PROFILE
20488 fp->uf_tml_count = NULL;
20489 fp->uf_tml_total = NULL;
20490 fp->uf_tml_self = NULL;
20491 fp->uf_profiling = FALSE;
20492 if (prof_def_func())
20493 func_do_profile(fp);
20494 #endif
20495 fp->uf_varargs = varargs;
20496 fp->uf_flags = flags;
20497 fp->uf_calls = 0;
20498 fp->uf_script_ID = current_SID;
20499 goto ret_free;
20501 erret:
20502 ga_clear_strings(&newargs);
20503 ga_clear_strings(&newlines);
20504 ret_free:
20505 vim_free(skip_until);
20506 vim_free(fudi.fd_newkey);
20507 vim_free(name);
20508 did_emsg |= saved_did_emsg;
20512 * Get a function name, translating "<SID>" and "<SNR>".
20513 * Also handles a Funcref in a List or Dictionary.
20514 * Returns the function name in allocated memory, or NULL for failure.
20515 * flags:
20516 * TFN_INT: internal function name OK
20517 * TFN_QUIET: be quiet
20518 * Advances "pp" to just after the function name (if no error).
20520 static char_u *
20521 trans_function_name(pp, skip, flags, fdp)
20522 char_u **pp;
20523 int skip; /* only find the end, don't evaluate */
20524 int flags;
20525 funcdict_T *fdp; /* return: info about dictionary used */
20527 char_u *name = NULL;
20528 char_u *start;
20529 char_u *end;
20530 int lead;
20531 char_u sid_buf[20];
20532 int len;
20533 lval_T lv;
20535 if (fdp != NULL)
20536 vim_memset(fdp, 0, sizeof(funcdict_T));
20537 start = *pp;
20539 /* Check for hard coded <SNR>: already translated function ID (from a user
20540 * command). */
20541 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
20542 && (*pp)[2] == (int)KE_SNR)
20544 *pp += 3;
20545 len = get_id_len(pp) + 3;
20546 return vim_strnsave(start, len);
20549 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
20550 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
20551 lead = eval_fname_script(start);
20552 if (lead > 2)
20553 start += lead;
20555 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
20556 lead > 2 ? 0 : FNE_CHECK_START);
20557 if (end == start)
20559 if (!skip)
20560 EMSG(_("E129: Function name required"));
20561 goto theend;
20563 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
20566 * Report an invalid expression in braces, unless the expression
20567 * evaluation has been cancelled due to an aborting error, an
20568 * interrupt, or an exception.
20570 if (!aborting())
20572 if (end != NULL)
20573 EMSG2(_(e_invarg2), start);
20575 else
20576 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
20577 goto theend;
20580 if (lv.ll_tv != NULL)
20582 if (fdp != NULL)
20584 fdp->fd_dict = lv.ll_dict;
20585 fdp->fd_newkey = lv.ll_newkey;
20586 lv.ll_newkey = NULL;
20587 fdp->fd_di = lv.ll_di;
20589 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
20591 name = vim_strsave(lv.ll_tv->vval.v_string);
20592 *pp = end;
20594 else
20596 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
20597 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
20598 EMSG(_(e_funcref));
20599 else
20600 *pp = end;
20601 name = NULL;
20603 goto theend;
20606 if (lv.ll_name == NULL)
20608 /* Error found, but continue after the function name. */
20609 *pp = end;
20610 goto theend;
20613 /* Check if the name is a Funcref. If so, use the value. */
20614 if (lv.ll_exp_name != NULL)
20616 len = (int)STRLEN(lv.ll_exp_name);
20617 name = deref_func_name(lv.ll_exp_name, &len);
20618 if (name == lv.ll_exp_name)
20619 name = NULL;
20621 else
20623 len = (int)(end - *pp);
20624 name = deref_func_name(*pp, &len);
20625 if (name == *pp)
20626 name = NULL;
20628 if (name != NULL)
20630 name = vim_strsave(name);
20631 *pp = end;
20632 goto theend;
20635 if (lv.ll_exp_name != NULL)
20637 len = (int)STRLEN(lv.ll_exp_name);
20638 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
20639 && STRNCMP(lv.ll_name, "s:", 2) == 0)
20641 /* When there was "s:" already or the name expanded to get a
20642 * leading "s:" then remove it. */
20643 lv.ll_name += 2;
20644 len -= 2;
20645 lead = 2;
20648 else
20650 if (lead == 2) /* skip over "s:" */
20651 lv.ll_name += 2;
20652 len = (int)(end - lv.ll_name);
20656 * Copy the function name to allocated memory.
20657 * Accept <SID>name() inside a script, translate into <SNR>123_name().
20658 * Accept <SNR>123_name() outside a script.
20660 if (skip)
20661 lead = 0; /* do nothing */
20662 else if (lead > 0)
20664 lead = 3;
20665 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
20666 || eval_fname_sid(*pp))
20668 /* It's "s:" or "<SID>" */
20669 if (current_SID <= 0)
20671 EMSG(_(e_usingsid));
20672 goto theend;
20674 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
20675 lead += (int)STRLEN(sid_buf);
20678 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
20680 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
20681 goto theend;
20683 name = alloc((unsigned)(len + lead + 1));
20684 if (name != NULL)
20686 if (lead > 0)
20688 name[0] = K_SPECIAL;
20689 name[1] = KS_EXTRA;
20690 name[2] = (int)KE_SNR;
20691 if (lead > 3) /* If it's "<SID>" */
20692 STRCPY(name + 3, sid_buf);
20694 mch_memmove(name + lead, lv.ll_name, (size_t)len);
20695 name[len + lead] = NUL;
20697 *pp = end;
20699 theend:
20700 clear_lval(&lv);
20701 return name;
20705 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
20706 * Return 2 if "p" starts with "s:".
20707 * Return 0 otherwise.
20709 static int
20710 eval_fname_script(p)
20711 char_u *p;
20713 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
20714 || STRNICMP(p + 1, "SNR>", 4) == 0))
20715 return 5;
20716 if (p[0] == 's' && p[1] == ':')
20717 return 2;
20718 return 0;
20722 * Return TRUE if "p" starts with "<SID>" or "s:".
20723 * Only works if eval_fname_script() returned non-zero for "p"!
20725 static int
20726 eval_fname_sid(p)
20727 char_u *p;
20729 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
20733 * List the head of the function: "name(arg1, arg2)".
20735 static void
20736 list_func_head(fp, indent)
20737 ufunc_T *fp;
20738 int indent;
20740 int j;
20742 msg_start();
20743 if (indent)
20744 MSG_PUTS(" ");
20745 MSG_PUTS("function ");
20746 if (fp->uf_name[0] == K_SPECIAL)
20748 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
20749 msg_puts(fp->uf_name + 3);
20751 else
20752 msg_puts(fp->uf_name);
20753 msg_putchar('(');
20754 for (j = 0; j < fp->uf_args.ga_len; ++j)
20756 if (j)
20757 MSG_PUTS(", ");
20758 msg_puts(FUNCARG(fp, j));
20760 if (fp->uf_varargs)
20762 if (j)
20763 MSG_PUTS(", ");
20764 MSG_PUTS("...");
20766 msg_putchar(')');
20767 msg_clr_eos();
20768 if (p_verbose > 0)
20769 last_set_msg(fp->uf_script_ID);
20773 * Find a function by name, return pointer to it in ufuncs.
20774 * Return NULL for unknown function.
20776 static ufunc_T *
20777 find_func(name)
20778 char_u *name;
20780 hashitem_T *hi;
20782 hi = hash_find(&func_hashtab, name);
20783 if (!HASHITEM_EMPTY(hi))
20784 return HI2UF(hi);
20785 return NULL;
20788 #if defined(EXITFREE) || defined(PROTO)
20789 void
20790 free_all_functions()
20792 hashitem_T *hi;
20794 /* Need to start all over every time, because func_free() may change the
20795 * hash table. */
20796 while (func_hashtab.ht_used > 0)
20797 for (hi = func_hashtab.ht_array; ; ++hi)
20798 if (!HASHITEM_EMPTY(hi))
20800 func_free(HI2UF(hi));
20801 break;
20804 #endif
20807 * Return TRUE if a function "name" exists.
20809 static int
20810 function_exists(name)
20811 char_u *name;
20813 char_u *nm = name;
20814 char_u *p;
20815 int n = FALSE;
20817 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
20818 nm = skipwhite(nm);
20820 /* Only accept "funcname", "funcname ", "funcname (..." and
20821 * "funcname(...", not "funcname!...". */
20822 if (p != NULL && (*nm == NUL || *nm == '('))
20824 if (builtin_function(p))
20825 n = (find_internal_func(p) >= 0);
20826 else
20827 n = (find_func(p) != NULL);
20829 vim_free(p);
20830 return n;
20834 * Return TRUE if "name" looks like a builtin function name: starts with a
20835 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
20837 static int
20838 builtin_function(name)
20839 char_u *name;
20841 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
20842 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
20845 #if defined(FEAT_PROFILE) || defined(PROTO)
20847 * Start profiling function "fp".
20849 static void
20850 func_do_profile(fp)
20851 ufunc_T *fp;
20853 fp->uf_tm_count = 0;
20854 profile_zero(&fp->uf_tm_self);
20855 profile_zero(&fp->uf_tm_total);
20856 if (fp->uf_tml_count == NULL)
20857 fp->uf_tml_count = (int *)alloc_clear((unsigned)
20858 (sizeof(int) * fp->uf_lines.ga_len));
20859 if (fp->uf_tml_total == NULL)
20860 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
20861 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20862 if (fp->uf_tml_self == NULL)
20863 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
20864 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20865 fp->uf_tml_idx = -1;
20866 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
20867 || fp->uf_tml_self == NULL)
20868 return; /* out of memory */
20870 fp->uf_profiling = TRUE;
20874 * Dump the profiling results for all functions in file "fd".
20876 void
20877 func_dump_profile(fd)
20878 FILE *fd;
20880 hashitem_T *hi;
20881 int todo;
20882 ufunc_T *fp;
20883 int i;
20884 ufunc_T **sorttab;
20885 int st_len = 0;
20887 todo = (int)func_hashtab.ht_used;
20888 if (todo == 0)
20889 return; /* nothing to dump */
20891 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
20893 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
20895 if (!HASHITEM_EMPTY(hi))
20897 --todo;
20898 fp = HI2UF(hi);
20899 if (fp->uf_profiling)
20901 if (sorttab != NULL)
20902 sorttab[st_len++] = fp;
20904 if (fp->uf_name[0] == K_SPECIAL)
20905 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
20906 else
20907 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
20908 if (fp->uf_tm_count == 1)
20909 fprintf(fd, "Called 1 time\n");
20910 else
20911 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
20912 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
20913 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
20914 fprintf(fd, "\n");
20915 fprintf(fd, "count total (s) self (s)\n");
20917 for (i = 0; i < fp->uf_lines.ga_len; ++i)
20919 if (FUNCLINE(fp, i) == NULL)
20920 continue;
20921 prof_func_line(fd, fp->uf_tml_count[i],
20922 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
20923 fprintf(fd, "%s\n", FUNCLINE(fp, i));
20925 fprintf(fd, "\n");
20930 if (sorttab != NULL && st_len > 0)
20932 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20933 prof_total_cmp);
20934 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
20935 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20936 prof_self_cmp);
20937 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
20940 vim_free(sorttab);
20943 static void
20944 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
20945 FILE *fd;
20946 ufunc_T **sorttab;
20947 int st_len;
20948 char *title;
20949 int prefer_self; /* when equal print only self time */
20951 int i;
20952 ufunc_T *fp;
20954 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
20955 fprintf(fd, "count total (s) self (s) function\n");
20956 for (i = 0; i < 20 && i < st_len; ++i)
20958 fp = sorttab[i];
20959 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
20960 prefer_self);
20961 if (fp->uf_name[0] == K_SPECIAL)
20962 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
20963 else
20964 fprintf(fd, " %s()\n", fp->uf_name);
20966 fprintf(fd, "\n");
20970 * Print the count and times for one function or function line.
20972 static void
20973 prof_func_line(fd, count, total, self, prefer_self)
20974 FILE *fd;
20975 int count;
20976 proftime_T *total;
20977 proftime_T *self;
20978 int prefer_self; /* when equal print only self time */
20980 if (count > 0)
20982 fprintf(fd, "%5d ", count);
20983 if (prefer_self && profile_equal(total, self))
20984 fprintf(fd, " ");
20985 else
20986 fprintf(fd, "%s ", profile_msg(total));
20987 if (!prefer_self && profile_equal(total, self))
20988 fprintf(fd, " ");
20989 else
20990 fprintf(fd, "%s ", profile_msg(self));
20992 else
20993 fprintf(fd, " ");
20997 * Compare function for total time sorting.
20999 static int
21000 #ifdef __BORLANDC__
21001 _RTLENTRYF
21002 #endif
21003 prof_total_cmp(s1, s2)
21004 const void *s1;
21005 const void *s2;
21007 ufunc_T *p1, *p2;
21009 p1 = *(ufunc_T **)s1;
21010 p2 = *(ufunc_T **)s2;
21011 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
21015 * Compare function for self time sorting.
21017 static int
21018 #ifdef __BORLANDC__
21019 _RTLENTRYF
21020 #endif
21021 prof_self_cmp(s1, s2)
21022 const void *s1;
21023 const void *s2;
21025 ufunc_T *p1, *p2;
21027 p1 = *(ufunc_T **)s1;
21028 p2 = *(ufunc_T **)s2;
21029 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
21032 #endif
21035 * If "name" has a package name try autoloading the script for it.
21036 * Return TRUE if a package was loaded.
21038 static int
21039 script_autoload(name, reload)
21040 char_u *name;
21041 int reload; /* load script again when already loaded */
21043 char_u *p;
21044 char_u *scriptname, *tofree;
21045 int ret = FALSE;
21046 int i;
21048 /* If there is no '#' after name[0] there is no package name. */
21049 p = vim_strchr(name, AUTOLOAD_CHAR);
21050 if (p == NULL || p == name)
21051 return FALSE;
21053 tofree = scriptname = autoload_name(name);
21055 /* Find the name in the list of previously loaded package names. Skip
21056 * "autoload/", it's always the same. */
21057 for (i = 0; i < ga_loaded.ga_len; ++i)
21058 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
21059 break;
21060 if (!reload && i < ga_loaded.ga_len)
21061 ret = FALSE; /* was loaded already */
21062 else
21064 /* Remember the name if it wasn't loaded already. */
21065 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
21067 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
21068 tofree = NULL;
21071 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
21072 if (source_runtime(scriptname, FALSE) == OK)
21073 ret = TRUE;
21076 vim_free(tofree);
21077 return ret;
21081 * Return the autoload script name for a function or variable name.
21082 * Returns NULL when out of memory.
21084 static char_u *
21085 autoload_name(name)
21086 char_u *name;
21088 char_u *p;
21089 char_u *scriptname;
21091 /* Get the script file name: replace '#' with '/', append ".vim". */
21092 scriptname = alloc((unsigned)(STRLEN(name) + 14));
21093 if (scriptname == NULL)
21094 return FALSE;
21095 STRCPY(scriptname, "autoload/");
21096 STRCAT(scriptname, name);
21097 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
21098 STRCAT(scriptname, ".vim");
21099 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
21100 *p = '/';
21101 return scriptname;
21104 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
21107 * Function given to ExpandGeneric() to obtain the list of user defined
21108 * function names.
21110 char_u *
21111 get_user_func_name(xp, idx)
21112 expand_T *xp;
21113 int idx;
21115 static long_u done;
21116 static hashitem_T *hi;
21117 ufunc_T *fp;
21119 if (idx == 0)
21121 done = 0;
21122 hi = func_hashtab.ht_array;
21124 if (done < func_hashtab.ht_used)
21126 if (done++ > 0)
21127 ++hi;
21128 while (HASHITEM_EMPTY(hi))
21129 ++hi;
21130 fp = HI2UF(hi);
21132 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
21133 return fp->uf_name; /* prevents overflow */
21135 cat_func_name(IObuff, fp);
21136 if (xp->xp_context != EXPAND_USER_FUNC)
21138 STRCAT(IObuff, "(");
21139 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
21140 STRCAT(IObuff, ")");
21142 return IObuff;
21144 return NULL;
21147 #endif /* FEAT_CMDL_COMPL */
21150 * Copy the function name of "fp" to buffer "buf".
21151 * "buf" must be able to hold the function name plus three bytes.
21152 * Takes care of script-local function names.
21154 static void
21155 cat_func_name(buf, fp)
21156 char_u *buf;
21157 ufunc_T *fp;
21159 if (fp->uf_name[0] == K_SPECIAL)
21161 STRCPY(buf, "<SNR>");
21162 STRCAT(buf, fp->uf_name + 3);
21164 else
21165 STRCPY(buf, fp->uf_name);
21169 * ":delfunction {name}"
21171 void
21172 ex_delfunction(eap)
21173 exarg_T *eap;
21175 ufunc_T *fp = NULL;
21176 char_u *p;
21177 char_u *name;
21178 funcdict_T fudi;
21180 p = eap->arg;
21181 name = trans_function_name(&p, eap->skip, 0, &fudi);
21182 vim_free(fudi.fd_newkey);
21183 if (name == NULL)
21185 if (fudi.fd_dict != NULL && !eap->skip)
21186 EMSG(_(e_funcref));
21187 return;
21189 if (!ends_excmd(*skipwhite(p)))
21191 vim_free(name);
21192 EMSG(_(e_trailing));
21193 return;
21195 eap->nextcmd = check_nextcmd(p);
21196 if (eap->nextcmd != NULL)
21197 *p = NUL;
21199 if (!eap->skip)
21200 fp = find_func(name);
21201 vim_free(name);
21203 if (!eap->skip)
21205 if (fp == NULL)
21207 EMSG2(_(e_nofunc), eap->arg);
21208 return;
21210 if (fp->uf_calls > 0)
21212 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
21213 return;
21216 if (fudi.fd_dict != NULL)
21218 /* Delete the dict item that refers to the function, it will
21219 * invoke func_unref() and possibly delete the function. */
21220 dictitem_remove(fudi.fd_dict, fudi.fd_di);
21222 else
21223 func_free(fp);
21228 * Free a function and remove it from the list of functions.
21230 static void
21231 func_free(fp)
21232 ufunc_T *fp;
21234 hashitem_T *hi;
21236 /* clear this function */
21237 ga_clear_strings(&(fp->uf_args));
21238 ga_clear_strings(&(fp->uf_lines));
21239 #ifdef FEAT_PROFILE
21240 vim_free(fp->uf_tml_count);
21241 vim_free(fp->uf_tml_total);
21242 vim_free(fp->uf_tml_self);
21243 #endif
21245 /* remove the function from the function hashtable */
21246 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
21247 if (HASHITEM_EMPTY(hi))
21248 EMSG2(_(e_intern2), "func_free()");
21249 else
21250 hash_remove(&func_hashtab, hi);
21252 vim_free(fp);
21256 * Unreference a Function: decrement the reference count and free it when it
21257 * becomes zero. Only for numbered functions.
21259 static void
21260 func_unref(name)
21261 char_u *name;
21263 ufunc_T *fp;
21265 if (name != NULL && isdigit(*name))
21267 fp = find_func(name);
21268 if (fp == NULL)
21269 EMSG2(_(e_intern2), "func_unref()");
21270 else if (--fp->uf_refcount <= 0)
21272 /* Only delete it when it's not being used. Otherwise it's done
21273 * when "uf_calls" becomes zero. */
21274 if (fp->uf_calls == 0)
21275 func_free(fp);
21281 * Count a reference to a Function.
21283 static void
21284 func_ref(name)
21285 char_u *name;
21287 ufunc_T *fp;
21289 if (name != NULL && isdigit(*name))
21291 fp = find_func(name);
21292 if (fp == NULL)
21293 EMSG2(_(e_intern2), "func_ref()");
21294 else
21295 ++fp->uf_refcount;
21300 * Call a user function.
21302 static void
21303 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
21304 ufunc_T *fp; /* pointer to function */
21305 int argcount; /* nr of args */
21306 typval_T *argvars; /* arguments */
21307 typval_T *rettv; /* return value */
21308 linenr_T firstline; /* first line of range */
21309 linenr_T lastline; /* last line of range */
21310 dict_T *selfdict; /* Dictionary for "self" */
21312 char_u *save_sourcing_name;
21313 linenr_T save_sourcing_lnum;
21314 scid_T save_current_SID;
21315 funccall_T *fc;
21316 int save_did_emsg;
21317 static int depth = 0;
21318 dictitem_T *v;
21319 int fixvar_idx = 0; /* index in fixvar[] */
21320 int i;
21321 int ai;
21322 char_u numbuf[NUMBUFLEN];
21323 char_u *name;
21324 #ifdef FEAT_PROFILE
21325 proftime_T wait_start;
21326 proftime_T call_start;
21327 #endif
21329 /* If depth of calling is getting too high, don't execute the function */
21330 if (depth >= p_mfd)
21332 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
21333 rettv->v_type = VAR_NUMBER;
21334 rettv->vval.v_number = -1;
21335 return;
21337 ++depth;
21339 line_breakcheck(); /* check for CTRL-C hit */
21341 fc = (funccall_T *)alloc(sizeof(funccall_T));
21342 fc->caller = current_funccal;
21343 current_funccal = fc;
21344 fc->func = fp;
21345 fc->rettv = rettv;
21346 rettv->vval.v_number = 0;
21347 fc->linenr = 0;
21348 fc->returned = FALSE;
21349 fc->level = ex_nesting_level;
21350 /* Check if this function has a breakpoint. */
21351 fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
21352 fc->dbg_tick = debug_tick;
21355 * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables
21356 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
21357 * each argument variable and saves a lot of time.
21360 * Init l: variables.
21362 init_var_dict(&fc->l_vars, &fc->l_vars_var);
21363 if (selfdict != NULL)
21365 /* Set l:self to "selfdict". Use "name" to avoid a warning from
21366 * some compiler that checks the destination size. */
21367 v = &fc->fixvar[fixvar_idx++].var;
21368 name = v->di_key;
21369 STRCPY(name, "self");
21370 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
21371 hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
21372 v->di_tv.v_type = VAR_DICT;
21373 v->di_tv.v_lock = 0;
21374 v->di_tv.vval.v_dict = selfdict;
21375 ++selfdict->dv_refcount;
21379 * Init a: variables.
21380 * Set a:0 to "argcount".
21381 * Set a:000 to a list with room for the "..." arguments.
21383 init_var_dict(&fc->l_avars, &fc->l_avars_var);
21384 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0",
21385 (varnumber_T)(argcount - fp->uf_args.ga_len));
21386 /* Use "name" to avoid a warning from some compiler that checks the
21387 * destination size. */
21388 v = &fc->fixvar[fixvar_idx++].var;
21389 name = v->di_key;
21390 STRCPY(name, "000");
21391 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21392 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21393 v->di_tv.v_type = VAR_LIST;
21394 v->di_tv.v_lock = VAR_FIXED;
21395 v->di_tv.vval.v_list = &fc->l_varlist;
21396 vim_memset(&fc->l_varlist, 0, sizeof(list_T));
21397 fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT;
21398 fc->l_varlist.lv_lock = VAR_FIXED;
21401 * Set a:firstline to "firstline" and a:lastline to "lastline".
21402 * Set a:name to named arguments.
21403 * Set a:N to the "..." arguments.
21405 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline",
21406 (varnumber_T)firstline);
21407 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline",
21408 (varnumber_T)lastline);
21409 for (i = 0; i < argcount; ++i)
21411 ai = i - fp->uf_args.ga_len;
21412 if (ai < 0)
21413 /* named argument a:name */
21414 name = FUNCARG(fp, i);
21415 else
21417 /* "..." argument a:1, a:2, etc. */
21418 sprintf((char *)numbuf, "%d", ai + 1);
21419 name = numbuf;
21421 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
21423 v = &fc->fixvar[fixvar_idx++].var;
21424 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21426 else
21428 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
21429 + STRLEN(name)));
21430 if (v == NULL)
21431 break;
21432 v->di_flags = DI_FLAGS_RO;
21434 STRCPY(v->di_key, name);
21435 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21437 /* Note: the values are copied directly to avoid alloc/free.
21438 * "argvars" must have VAR_FIXED for v_lock. */
21439 v->di_tv = argvars[i];
21440 v->di_tv.v_lock = VAR_FIXED;
21442 if (ai >= 0 && ai < MAX_FUNC_ARGS)
21444 list_append(&fc->l_varlist, &fc->l_listitems[ai]);
21445 fc->l_listitems[ai].li_tv = argvars[i];
21446 fc->l_listitems[ai].li_tv.v_lock = VAR_FIXED;
21450 /* Don't redraw while executing the function. */
21451 ++RedrawingDisabled;
21452 save_sourcing_name = sourcing_name;
21453 save_sourcing_lnum = sourcing_lnum;
21454 sourcing_lnum = 1;
21455 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
21456 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
21457 if (sourcing_name != NULL)
21459 if (save_sourcing_name != NULL
21460 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
21461 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
21462 else
21463 STRCPY(sourcing_name, "function ");
21464 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
21466 if (p_verbose >= 12)
21468 ++no_wait_return;
21469 verbose_enter_scroll();
21471 smsg((char_u *)_("calling %s"), sourcing_name);
21472 if (p_verbose >= 14)
21474 char_u buf[MSG_BUF_LEN];
21475 char_u numbuf2[NUMBUFLEN];
21476 char_u *tofree;
21477 char_u *s;
21479 msg_puts((char_u *)"(");
21480 for (i = 0; i < argcount; ++i)
21482 if (i > 0)
21483 msg_puts((char_u *)", ");
21484 if (argvars[i].v_type == VAR_NUMBER)
21485 msg_outnum((long)argvars[i].vval.v_number);
21486 else
21488 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
21489 if (s != NULL)
21491 trunc_string(s, buf, MSG_BUF_CLEN);
21492 msg_puts(buf);
21493 vim_free(tofree);
21497 msg_puts((char_u *)")");
21499 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21501 verbose_leave_scroll();
21502 --no_wait_return;
21505 #ifdef FEAT_PROFILE
21506 if (do_profiling == PROF_YES)
21508 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
21509 func_do_profile(fp);
21510 if (fp->uf_profiling
21511 || (fc->caller != NULL && fc->caller->func->uf_profiling))
21513 ++fp->uf_tm_count;
21514 profile_start(&call_start);
21515 profile_zero(&fp->uf_tm_children);
21517 script_prof_save(&wait_start);
21519 #endif
21521 save_current_SID = current_SID;
21522 current_SID = fp->uf_script_ID;
21523 save_did_emsg = did_emsg;
21524 did_emsg = FALSE;
21526 /* call do_cmdline() to execute the lines */
21527 do_cmdline(NULL, get_func_line, (void *)fc,
21528 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
21530 --RedrawingDisabled;
21532 /* when the function was aborted because of an error, return -1 */
21533 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
21535 clear_tv(rettv);
21536 rettv->v_type = VAR_NUMBER;
21537 rettv->vval.v_number = -1;
21540 #ifdef FEAT_PROFILE
21541 if (do_profiling == PROF_YES && (fp->uf_profiling
21542 || (fc->caller != NULL && fc->caller->func->uf_profiling)))
21544 profile_end(&call_start);
21545 profile_sub_wait(&wait_start, &call_start);
21546 profile_add(&fp->uf_tm_total, &call_start);
21547 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
21548 if (fc->caller != NULL && fc->caller->func->uf_profiling)
21550 profile_add(&fc->caller->func->uf_tm_children, &call_start);
21551 profile_add(&fc->caller->func->uf_tml_children, &call_start);
21554 #endif
21556 /* when being verbose, mention the return value */
21557 if (p_verbose >= 12)
21559 ++no_wait_return;
21560 verbose_enter_scroll();
21562 if (aborting())
21563 smsg((char_u *)_("%s aborted"), sourcing_name);
21564 else if (fc->rettv->v_type == VAR_NUMBER)
21565 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
21566 (long)fc->rettv->vval.v_number);
21567 else
21569 char_u buf[MSG_BUF_LEN];
21570 char_u numbuf2[NUMBUFLEN];
21571 char_u *tofree;
21572 char_u *s;
21574 /* The value may be very long. Skip the middle part, so that we
21575 * have some idea how it starts and ends. smsg() would always
21576 * truncate it at the end. */
21577 s = tv2string(fc->rettv, &tofree, numbuf2, 0);
21578 if (s != NULL)
21580 trunc_string(s, buf, MSG_BUF_CLEN);
21581 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
21582 vim_free(tofree);
21585 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21587 verbose_leave_scroll();
21588 --no_wait_return;
21591 vim_free(sourcing_name);
21592 sourcing_name = save_sourcing_name;
21593 sourcing_lnum = save_sourcing_lnum;
21594 current_SID = save_current_SID;
21595 #ifdef FEAT_PROFILE
21596 if (do_profiling == PROF_YES)
21597 script_prof_restore(&wait_start);
21598 #endif
21600 if (p_verbose >= 12 && sourcing_name != NULL)
21602 ++no_wait_return;
21603 verbose_enter_scroll();
21605 smsg((char_u *)_("continuing in %s"), sourcing_name);
21606 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21608 verbose_leave_scroll();
21609 --no_wait_return;
21612 did_emsg |= save_did_emsg;
21613 current_funccal = fc->caller;
21614 --depth;
21616 /* If the a:000 list and the l: and a: dicts are not referenced we can
21617 * free the funccall_T and what's in it. */
21618 if (fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
21619 && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
21620 && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT)
21622 free_funccal(fc, FALSE);
21624 else
21626 hashitem_T *hi;
21627 listitem_T *li;
21628 int todo;
21630 /* "fc" is still in use. This can happen when returning "a:000" or
21631 * assigning "l:" to a global variable.
21632 * Link "fc" in the list for garbage collection later. */
21633 fc->caller = previous_funccal;
21634 previous_funccal = fc;
21636 /* Make a copy of the a: variables, since we didn't do that above. */
21637 todo = (int)fc->l_avars.dv_hashtab.ht_used;
21638 for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi)
21640 if (!HASHITEM_EMPTY(hi))
21642 --todo;
21643 v = HI2DI(hi);
21644 copy_tv(&v->di_tv, &v->di_tv);
21648 /* Make a copy of the a:000 items, since we didn't do that above. */
21649 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21650 copy_tv(&li->li_tv, &li->li_tv);
21655 * Return TRUE if items in "fc" do not have "copyID". That means they are not
21656 * referenced from anywhere that is in use.
21658 static int
21659 can_free_funccal(fc, copyID)
21660 funccall_T *fc;
21661 int copyID;
21663 return (fc->l_varlist.lv_copyID != copyID
21664 && fc->l_vars.dv_copyID != copyID
21665 && fc->l_avars.dv_copyID != copyID);
21669 * Free "fc" and what it contains.
21671 static void
21672 free_funccal(fc, free_val)
21673 funccall_T *fc;
21674 int free_val; /* a: vars were allocated */
21676 listitem_T *li;
21678 /* The a: variables typevals may not have been allocated, only free the
21679 * allocated variables. */
21680 vars_clear_ext(&fc->l_avars.dv_hashtab, free_val);
21682 /* free all l: variables */
21683 vars_clear(&fc->l_vars.dv_hashtab);
21685 /* Free the a:000 variables if they were allocated. */
21686 if (free_val)
21687 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21688 clear_tv(&li->li_tv);
21690 vim_free(fc);
21694 * Add a number variable "name" to dict "dp" with value "nr".
21696 static void
21697 add_nr_var(dp, v, name, nr)
21698 dict_T *dp;
21699 dictitem_T *v;
21700 char *name;
21701 varnumber_T nr;
21703 STRCPY(v->di_key, name);
21704 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21705 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
21706 v->di_tv.v_type = VAR_NUMBER;
21707 v->di_tv.v_lock = VAR_FIXED;
21708 v->di_tv.vval.v_number = nr;
21712 * ":return [expr]"
21714 void
21715 ex_return(eap)
21716 exarg_T *eap;
21718 char_u *arg = eap->arg;
21719 typval_T rettv;
21720 int returning = FALSE;
21722 if (current_funccal == NULL)
21724 EMSG(_("E133: :return not inside a function"));
21725 return;
21728 if (eap->skip)
21729 ++emsg_skip;
21731 eap->nextcmd = NULL;
21732 if ((*arg != NUL && *arg != '|' && *arg != '\n')
21733 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
21735 if (!eap->skip)
21736 returning = do_return(eap, FALSE, TRUE, &rettv);
21737 else
21738 clear_tv(&rettv);
21740 /* It's safer to return also on error. */
21741 else if (!eap->skip)
21744 * Return unless the expression evaluation has been cancelled due to an
21745 * aborting error, an interrupt, or an exception.
21747 if (!aborting())
21748 returning = do_return(eap, FALSE, TRUE, NULL);
21751 /* When skipping or the return gets pending, advance to the next command
21752 * in this line (!returning). Otherwise, ignore the rest of the line.
21753 * Following lines will be ignored by get_func_line(). */
21754 if (returning)
21755 eap->nextcmd = NULL;
21756 else if (eap->nextcmd == NULL) /* no argument */
21757 eap->nextcmd = check_nextcmd(arg);
21759 if (eap->skip)
21760 --emsg_skip;
21764 * Return from a function. Possibly makes the return pending. Also called
21765 * for a pending return at the ":endtry" or after returning from an extra
21766 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
21767 * when called due to a ":return" command. "rettv" may point to a typval_T
21768 * with the return rettv. Returns TRUE when the return can be carried out,
21769 * FALSE when the return gets pending.
21772 do_return(eap, reanimate, is_cmd, rettv)
21773 exarg_T *eap;
21774 int reanimate;
21775 int is_cmd;
21776 void *rettv;
21778 int idx;
21779 struct condstack *cstack = eap->cstack;
21781 if (reanimate)
21782 /* Undo the return. */
21783 current_funccal->returned = FALSE;
21786 * Cleanup (and inactivate) conditionals, but stop when a try conditional
21787 * not in its finally clause (which then is to be executed next) is found.
21788 * In this case, make the ":return" pending for execution at the ":endtry".
21789 * Otherwise, return normally.
21791 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
21792 if (idx >= 0)
21794 cstack->cs_pending[idx] = CSTP_RETURN;
21796 if (!is_cmd && !reanimate)
21797 /* A pending return again gets pending. "rettv" points to an
21798 * allocated variable with the rettv of the original ":return"'s
21799 * argument if present or is NULL else. */
21800 cstack->cs_rettv[idx] = rettv;
21801 else
21803 /* When undoing a return in order to make it pending, get the stored
21804 * return rettv. */
21805 if (reanimate)
21806 rettv = current_funccal->rettv;
21808 if (rettv != NULL)
21810 /* Store the value of the pending return. */
21811 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
21812 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
21813 else
21814 EMSG(_(e_outofmem));
21816 else
21817 cstack->cs_rettv[idx] = NULL;
21819 if (reanimate)
21821 /* The pending return value could be overwritten by a ":return"
21822 * without argument in a finally clause; reset the default
21823 * return value. */
21824 current_funccal->rettv->v_type = VAR_NUMBER;
21825 current_funccal->rettv->vval.v_number = 0;
21828 report_make_pending(CSTP_RETURN, rettv);
21830 else
21832 current_funccal->returned = TRUE;
21834 /* If the return is carried out now, store the return value. For
21835 * a return immediately after reanimation, the value is already
21836 * there. */
21837 if (!reanimate && rettv != NULL)
21839 clear_tv(current_funccal->rettv);
21840 *current_funccal->rettv = *(typval_T *)rettv;
21841 if (!is_cmd)
21842 vim_free(rettv);
21846 return idx < 0;
21850 * Free the variable with a pending return value.
21852 void
21853 discard_pending_return(rettv)
21854 void *rettv;
21856 free_tv((typval_T *)rettv);
21860 * Generate a return command for producing the value of "rettv". The result
21861 * is an allocated string. Used by report_pending() for verbose messages.
21863 char_u *
21864 get_return_cmd(rettv)
21865 void *rettv;
21867 char_u *s = NULL;
21868 char_u *tofree = NULL;
21869 char_u numbuf[NUMBUFLEN];
21871 if (rettv != NULL)
21872 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
21873 if (s == NULL)
21874 s = (char_u *)"";
21876 STRCPY(IObuff, ":return ");
21877 STRNCPY(IObuff + 8, s, IOSIZE - 8);
21878 if (STRLEN(s) + 8 >= IOSIZE)
21879 STRCPY(IObuff + IOSIZE - 4, "...");
21880 vim_free(tofree);
21881 return vim_strsave(IObuff);
21885 * Get next function line.
21886 * Called by do_cmdline() to get the next line.
21887 * Returns allocated string, or NULL for end of function.
21889 char_u *
21890 get_func_line(c, cookie, indent)
21891 int c UNUSED;
21892 void *cookie;
21893 int indent UNUSED;
21895 funccall_T *fcp = (funccall_T *)cookie;
21896 ufunc_T *fp = fcp->func;
21897 char_u *retval;
21898 garray_T *gap; /* growarray with function lines */
21900 /* If breakpoints have been added/deleted need to check for it. */
21901 if (fcp->dbg_tick != debug_tick)
21903 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21904 sourcing_lnum);
21905 fcp->dbg_tick = debug_tick;
21907 #ifdef FEAT_PROFILE
21908 if (do_profiling == PROF_YES)
21909 func_line_end(cookie);
21910 #endif
21912 gap = &fp->uf_lines;
21913 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21914 || fcp->returned)
21915 retval = NULL;
21916 else
21918 /* Skip NULL lines (continuation lines). */
21919 while (fcp->linenr < gap->ga_len
21920 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
21921 ++fcp->linenr;
21922 if (fcp->linenr >= gap->ga_len)
21923 retval = NULL;
21924 else
21926 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
21927 sourcing_lnum = fcp->linenr;
21928 #ifdef FEAT_PROFILE
21929 if (do_profiling == PROF_YES)
21930 func_line_start(cookie);
21931 #endif
21935 /* Did we encounter a breakpoint? */
21936 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
21938 dbg_breakpoint(fp->uf_name, sourcing_lnum);
21939 /* Find next breakpoint. */
21940 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21941 sourcing_lnum);
21942 fcp->dbg_tick = debug_tick;
21945 return retval;
21948 #if defined(FEAT_PROFILE) || defined(PROTO)
21950 * Called when starting to read a function line.
21951 * "sourcing_lnum" must be correct!
21952 * When skipping lines it may not actually be executed, but we won't find out
21953 * until later and we need to store the time now.
21955 void
21956 func_line_start(cookie)
21957 void *cookie;
21959 funccall_T *fcp = (funccall_T *)cookie;
21960 ufunc_T *fp = fcp->func;
21962 if (fp->uf_profiling && sourcing_lnum >= 1
21963 && sourcing_lnum <= fp->uf_lines.ga_len)
21965 fp->uf_tml_idx = sourcing_lnum - 1;
21966 /* Skip continuation lines. */
21967 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
21968 --fp->uf_tml_idx;
21969 fp->uf_tml_execed = FALSE;
21970 profile_start(&fp->uf_tml_start);
21971 profile_zero(&fp->uf_tml_children);
21972 profile_get_wait(&fp->uf_tml_wait);
21977 * Called when actually executing a function line.
21979 void
21980 func_line_exec(cookie)
21981 void *cookie;
21983 funccall_T *fcp = (funccall_T *)cookie;
21984 ufunc_T *fp = fcp->func;
21986 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21987 fp->uf_tml_execed = TRUE;
21991 * Called when done with a function line.
21993 void
21994 func_line_end(cookie)
21995 void *cookie;
21997 funccall_T *fcp = (funccall_T *)cookie;
21998 ufunc_T *fp = fcp->func;
22000 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
22002 if (fp->uf_tml_execed)
22004 ++fp->uf_tml_count[fp->uf_tml_idx];
22005 profile_end(&fp->uf_tml_start);
22006 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
22007 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
22008 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
22009 &fp->uf_tml_children);
22011 fp->uf_tml_idx = -1;
22014 #endif
22017 * Return TRUE if the currently active function should be ended, because a
22018 * return was encountered or an error occurred. Used inside a ":while".
22021 func_has_ended(cookie)
22022 void *cookie;
22024 funccall_T *fcp = (funccall_T *)cookie;
22026 /* Ignore the "abort" flag if the abortion behavior has been changed due to
22027 * an error inside a try conditional. */
22028 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
22029 || fcp->returned);
22033 * return TRUE if cookie indicates a function which "abort"s on errors.
22036 func_has_abort(cookie)
22037 void *cookie;
22039 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
22042 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
22043 typedef enum
22045 VAR_FLAVOUR_DEFAULT, /* doesn't start with uppercase */
22046 VAR_FLAVOUR_SESSION, /* starts with uppercase, some lower */
22047 VAR_FLAVOUR_VIMINFO /* all uppercase */
22048 } var_flavour_T;
22050 static var_flavour_T var_flavour __ARGS((char_u *varname));
22052 static var_flavour_T
22053 var_flavour(varname)
22054 char_u *varname;
22056 char_u *p = varname;
22058 if (ASCII_ISUPPER(*p))
22060 while (*(++p))
22061 if (ASCII_ISLOWER(*p))
22062 return VAR_FLAVOUR_SESSION;
22063 return VAR_FLAVOUR_VIMINFO;
22065 else
22066 return VAR_FLAVOUR_DEFAULT;
22068 #endif
22070 #if defined(FEAT_VIMINFO) || defined(PROTO)
22072 * Restore global vars that start with a capital from the viminfo file
22075 read_viminfo_varlist(virp, writing)
22076 vir_T *virp;
22077 int writing;
22079 char_u *tab;
22080 int type = VAR_NUMBER;
22081 typval_T tv;
22083 if (!writing && (find_viminfo_parameter('!') != NULL))
22085 tab = vim_strchr(virp->vir_line + 1, '\t');
22086 if (tab != NULL)
22088 *tab++ = '\0'; /* isolate the variable name */
22089 if (*tab == 'S') /* string var */
22090 type = VAR_STRING;
22091 #ifdef FEAT_FLOAT
22092 else if (*tab == 'F')
22093 type = VAR_FLOAT;
22094 #endif
22096 tab = vim_strchr(tab, '\t');
22097 if (tab != NULL)
22099 tv.v_type = type;
22100 if (type == VAR_STRING)
22101 tv.vval.v_string = viminfo_readstring(virp,
22102 (int)(tab - virp->vir_line + 1), TRUE);
22103 #ifdef FEAT_FLOAT
22104 else if (type == VAR_FLOAT)
22105 (void)string2float(tab + 1, &tv.vval.v_float);
22106 #endif
22107 else
22108 tv.vval.v_number = atol((char *)tab + 1);
22109 set_var(virp->vir_line + 1, &tv, FALSE);
22110 if (type == VAR_STRING)
22111 vim_free(tv.vval.v_string);
22116 return viminfo_readline(virp);
22120 * Write global vars that start with a capital to the viminfo file
22122 void
22123 write_viminfo_varlist(fp)
22124 FILE *fp;
22126 hashitem_T *hi;
22127 dictitem_T *this_var;
22128 int todo;
22129 char *s;
22130 char_u *p;
22131 char_u *tofree;
22132 char_u numbuf[NUMBUFLEN];
22134 if (find_viminfo_parameter('!') == NULL)
22135 return;
22137 fprintf(fp, _("\n# global variables:\n"));
22139 todo = (int)globvarht.ht_used;
22140 for (hi = globvarht.ht_array; todo > 0; ++hi)
22142 if (!HASHITEM_EMPTY(hi))
22144 --todo;
22145 this_var = HI2DI(hi);
22146 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
22148 switch (this_var->di_tv.v_type)
22150 case VAR_STRING: s = "STR"; break;
22151 case VAR_NUMBER: s = "NUM"; break;
22152 #ifdef FEAT_FLOAT
22153 case VAR_FLOAT: s = "FLO"; break;
22154 #endif
22155 default: continue;
22157 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
22158 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
22159 if (p != NULL)
22160 viminfo_writestring(fp, p);
22161 vim_free(tofree);
22166 #endif
22168 #if defined(FEAT_SESSION) || defined(PROTO)
22170 store_session_globals(fd)
22171 FILE *fd;
22173 hashitem_T *hi;
22174 dictitem_T *this_var;
22175 int todo;
22176 char_u *p, *t;
22178 todo = (int)globvarht.ht_used;
22179 for (hi = globvarht.ht_array; todo > 0; ++hi)
22181 if (!HASHITEM_EMPTY(hi))
22183 --todo;
22184 this_var = HI2DI(hi);
22185 if ((this_var->di_tv.v_type == VAR_NUMBER
22186 || this_var->di_tv.v_type == VAR_STRING)
22187 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22189 /* Escape special characters with a backslash. Turn a LF and
22190 * CR into \n and \r. */
22191 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
22192 (char_u *)"\\\"\n\r");
22193 if (p == NULL) /* out of memory */
22194 break;
22195 for (t = p; *t != NUL; ++t)
22196 if (*t == '\n')
22197 *t = 'n';
22198 else if (*t == '\r')
22199 *t = 'r';
22200 if ((fprintf(fd, "let %s = %c%s%c",
22201 this_var->di_key,
22202 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22203 : ' ',
22205 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22206 : ' ') < 0)
22207 || put_eol(fd) == FAIL)
22209 vim_free(p);
22210 return FAIL;
22212 vim_free(p);
22214 #ifdef FEAT_FLOAT
22215 else if (this_var->di_tv.v_type == VAR_FLOAT
22216 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22218 float_T f = this_var->di_tv.vval.v_float;
22219 int sign = ' ';
22221 if (f < 0)
22223 f = -f;
22224 sign = '-';
22226 if ((fprintf(fd, "let %s = %c&%f",
22227 this_var->di_key, sign, f) < 0)
22228 || put_eol(fd) == FAIL)
22229 return FAIL;
22231 #endif
22234 return OK;
22236 #endif
22239 * Display script name where an item was last set.
22240 * Should only be invoked when 'verbose' is non-zero.
22242 void
22243 last_set_msg(scriptID)
22244 scid_T scriptID;
22246 char_u *p;
22248 if (scriptID != 0)
22250 p = home_replace_save(NULL, get_scriptname(scriptID));
22251 if (p != NULL)
22253 verbose_enter();
22254 MSG_PUTS(_("\n\tLast set from "));
22255 MSG_PUTS(p);
22256 vim_free(p);
22257 verbose_leave();
22263 * List v:oldfiles in a nice way.
22265 void
22266 ex_oldfiles(eap)
22267 exarg_T *eap UNUSED;
22269 list_T *l = vimvars[VV_OLDFILES].vv_list;
22270 listitem_T *li;
22271 int nr = 0;
22273 if (l == NULL)
22274 msg((char_u *)_("No old files"));
22275 else
22277 msg_start();
22278 msg_scroll = TRUE;
22279 for (li = l->lv_first; li != NULL && !got_int; li = li->li_next)
22281 msg_outnum((long)++nr);
22282 MSG_PUTS(": ");
22283 msg_outtrans(get_tv_string(&li->li_tv));
22284 msg_putchar('\n');
22285 out_flush(); /* output one line at a time */
22286 ui_breakcheck();
22288 /* Assume "got_int" was set to truncate the listing. */
22289 got_int = FALSE;
22291 #ifdef FEAT_BROWSE_CMD
22292 if (cmdmod.browse)
22294 quit_more = FALSE;
22295 nr = prompt_for_number(FALSE);
22296 msg_starthere();
22297 if (nr > 0)
22299 char_u *p = list_find_str(get_vim_var_list(VV_OLDFILES),
22300 (long)nr);
22302 if (p != NULL)
22304 p = expand_env_save(p);
22305 eap->arg = p;
22306 eap->cmdidx = CMD_edit;
22307 cmdmod.browse = FALSE;
22308 do_exedit(eap, NULL);
22309 vim_free(p);
22313 #endif
22317 #endif /* FEAT_EVAL */
22320 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
22322 #ifdef WIN3264
22324 * Functions for ":8" filename modifier: get 8.3 version of a filename.
22326 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22327 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
22328 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22331 * Get the short path (8.3) for the filename in "fnamep".
22332 * Only works for a valid file name.
22333 * When the path gets longer "fnamep" is changed and the allocated buffer
22334 * is put in "bufp".
22335 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
22336 * Returns OK on success, FAIL on failure.
22338 static int
22339 get_short_pathname(fnamep, bufp, fnamelen)
22340 char_u **fnamep;
22341 char_u **bufp;
22342 int *fnamelen;
22344 int l, len;
22345 char_u *newbuf;
22347 len = *fnamelen;
22348 l = GetShortPathName(*fnamep, *fnamep, len);
22349 if (l > len - 1)
22351 /* If that doesn't work (not enough space), then save the string
22352 * and try again with a new buffer big enough. */
22353 newbuf = vim_strnsave(*fnamep, l);
22354 if (newbuf == NULL)
22355 return FAIL;
22357 vim_free(*bufp);
22358 *fnamep = *bufp = newbuf;
22360 /* Really should always succeed, as the buffer is big enough. */
22361 l = GetShortPathName(*fnamep, *fnamep, l+1);
22364 *fnamelen = l;
22365 return OK;
22369 * Get the short path (8.3) for the filename in "fname". The converted
22370 * path is returned in "bufp".
22372 * Some of the directories specified in "fname" may not exist. This function
22373 * will shorten the existing directories at the beginning of the path and then
22374 * append the remaining non-existing path.
22376 * fname - Pointer to the filename to shorten. On return, contains the
22377 * pointer to the shortened pathname
22378 * bufp - Pointer to an allocated buffer for the filename.
22379 * fnamelen - Length of the filename pointed to by fname
22381 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
22383 static int
22384 shortpath_for_invalid_fname(fname, bufp, fnamelen)
22385 char_u **fname;
22386 char_u **bufp;
22387 int *fnamelen;
22389 char_u *short_fname, *save_fname, *pbuf_unused;
22390 char_u *endp, *save_endp;
22391 char_u ch;
22392 int old_len, len;
22393 int new_len, sfx_len;
22394 int retval = OK;
22396 /* Make a copy */
22397 old_len = *fnamelen;
22398 save_fname = vim_strnsave(*fname, old_len);
22399 pbuf_unused = NULL;
22400 short_fname = NULL;
22402 endp = save_fname + old_len - 1; /* Find the end of the copy */
22403 save_endp = endp;
22406 * Try shortening the supplied path till it succeeds by removing one
22407 * directory at a time from the tail of the path.
22409 len = 0;
22410 for (;;)
22412 /* go back one path-separator */
22413 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
22414 --endp;
22415 if (endp <= save_fname)
22416 break; /* processed the complete path */
22419 * Replace the path separator with a NUL and try to shorten the
22420 * resulting path.
22422 ch = *endp;
22423 *endp = 0;
22424 short_fname = save_fname;
22425 len = (int)STRLEN(short_fname) + 1;
22426 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
22428 retval = FAIL;
22429 goto theend;
22431 *endp = ch; /* preserve the string */
22433 if (len > 0)
22434 break; /* successfully shortened the path */
22436 /* failed to shorten the path. Skip the path separator */
22437 --endp;
22440 if (len > 0)
22443 * Succeeded in shortening the path. Now concatenate the shortened
22444 * path with the remaining path at the tail.
22447 /* Compute the length of the new path. */
22448 sfx_len = (int)(save_endp - endp) + 1;
22449 new_len = len + sfx_len;
22451 *fnamelen = new_len;
22452 vim_free(*bufp);
22453 if (new_len > old_len)
22455 /* There is not enough space in the currently allocated string,
22456 * copy it to a buffer big enough. */
22457 *fname = *bufp = vim_strnsave(short_fname, new_len);
22458 if (*fname == NULL)
22460 retval = FAIL;
22461 goto theend;
22464 else
22466 /* Transfer short_fname to the main buffer (it's big enough),
22467 * unless get_short_pathname() did its work in-place. */
22468 *fname = *bufp = save_fname;
22469 if (short_fname != save_fname)
22470 vim_strncpy(save_fname, short_fname, len);
22471 save_fname = NULL;
22474 /* concat the not-shortened part of the path */
22475 vim_strncpy(*fname + len, endp, sfx_len);
22476 (*fname)[new_len] = NUL;
22479 theend:
22480 vim_free(pbuf_unused);
22481 vim_free(save_fname);
22483 return retval;
22487 * Get a pathname for a partial path.
22488 * Returns OK for success, FAIL for failure.
22490 static int
22491 shortpath_for_partial(fnamep, bufp, fnamelen)
22492 char_u **fnamep;
22493 char_u **bufp;
22494 int *fnamelen;
22496 int sepcount, len, tflen;
22497 char_u *p;
22498 char_u *pbuf, *tfname;
22499 int hasTilde;
22501 /* Count up the path separators from the RHS.. so we know which part
22502 * of the path to return. */
22503 sepcount = 0;
22504 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
22505 if (vim_ispathsep(*p))
22506 ++sepcount;
22508 /* Need full path first (use expand_env() to remove a "~/") */
22509 hasTilde = (**fnamep == '~');
22510 if (hasTilde)
22511 pbuf = tfname = expand_env_save(*fnamep);
22512 else
22513 pbuf = tfname = FullName_save(*fnamep, FALSE);
22515 len = tflen = (int)STRLEN(tfname);
22517 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
22518 return FAIL;
22520 if (len == 0)
22522 /* Don't have a valid filename, so shorten the rest of the
22523 * path if we can. This CAN give us invalid 8.3 filenames, but
22524 * there's not a lot of point in guessing what it might be.
22526 len = tflen;
22527 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
22528 return FAIL;
22531 /* Count the paths backward to find the beginning of the desired string. */
22532 for (p = tfname + len - 1; p >= tfname; --p)
22534 #ifdef FEAT_MBYTE
22535 if (has_mbyte)
22536 p -= mb_head_off(tfname, p);
22537 #endif
22538 if (vim_ispathsep(*p))
22540 if (sepcount == 0 || (hasTilde && sepcount == 1))
22541 break;
22542 else
22543 sepcount --;
22546 if (hasTilde)
22548 --p;
22549 if (p >= tfname)
22550 *p = '~';
22551 else
22552 return FAIL;
22554 else
22555 ++p;
22557 /* Copy in the string - p indexes into tfname - allocated at pbuf */
22558 vim_free(*bufp);
22559 *fnamelen = (int)STRLEN(p);
22560 *bufp = pbuf;
22561 *fnamep = p;
22563 return OK;
22565 #endif /* WIN3264 */
22568 * Adjust a filename, according to a string of modifiers.
22569 * *fnamep must be NUL terminated when called. When returning, the length is
22570 * determined by *fnamelen.
22571 * Returns VALID_ flags or -1 for failure.
22572 * When there is an error, *fnamep is set to NULL.
22575 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
22576 char_u *src; /* string with modifiers */
22577 int *usedlen; /* characters after src that are used */
22578 char_u **fnamep; /* file name so far */
22579 char_u **bufp; /* buffer for allocated file name or NULL */
22580 int *fnamelen; /* length of fnamep */
22582 int valid = 0;
22583 char_u *tail;
22584 char_u *s, *p, *pbuf;
22585 char_u dirname[MAXPATHL];
22586 int c;
22587 int has_fullname = 0;
22588 #ifdef WIN3264
22589 int has_shortname = 0;
22590 #endif
22592 repeat:
22593 /* ":p" - full path/file_name */
22594 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
22596 has_fullname = 1;
22598 valid |= VALID_PATH;
22599 *usedlen += 2;
22601 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
22602 if ((*fnamep)[0] == '~'
22603 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
22604 && ((*fnamep)[1] == '/'
22605 # ifdef BACKSLASH_IN_FILENAME
22606 || (*fnamep)[1] == '\\'
22607 # endif
22608 || (*fnamep)[1] == NUL)
22610 #endif
22613 *fnamep = expand_env_save(*fnamep);
22614 vim_free(*bufp); /* free any allocated file name */
22615 *bufp = *fnamep;
22616 if (*fnamep == NULL)
22617 return -1;
22620 /* When "/." or "/.." is used: force expansion to get rid of it. */
22621 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
22623 if (vim_ispathsep(*p)
22624 && p[1] == '.'
22625 && (p[2] == NUL
22626 || vim_ispathsep(p[2])
22627 || (p[2] == '.'
22628 && (p[3] == NUL || vim_ispathsep(p[3])))))
22629 break;
22632 /* FullName_save() is slow, don't use it when not needed. */
22633 if (*p != NUL || !vim_isAbsName(*fnamep))
22635 *fnamep = FullName_save(*fnamep, *p != NUL);
22636 vim_free(*bufp); /* free any allocated file name */
22637 *bufp = *fnamep;
22638 if (*fnamep == NULL)
22639 return -1;
22642 /* Append a path separator to a directory. */
22643 if (mch_isdir(*fnamep))
22645 /* Make room for one or two extra characters. */
22646 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
22647 vim_free(*bufp); /* free any allocated file name */
22648 *bufp = *fnamep;
22649 if (*fnamep == NULL)
22650 return -1;
22651 add_pathsep(*fnamep);
22655 /* ":." - path relative to the current directory */
22656 /* ":~" - path relative to the home directory */
22657 /* ":8" - shortname path - postponed till after */
22658 while (src[*usedlen] == ':'
22659 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
22661 *usedlen += 2;
22662 if (c == '8')
22664 #ifdef WIN3264
22665 has_shortname = 1; /* Postpone this. */
22666 #endif
22667 continue;
22669 pbuf = NULL;
22670 /* Need full path first (use expand_env() to remove a "~/") */
22671 if (!has_fullname)
22673 if (c == '.' && **fnamep == '~')
22674 p = pbuf = expand_env_save(*fnamep);
22675 else
22676 p = pbuf = FullName_save(*fnamep, FALSE);
22678 else
22679 p = *fnamep;
22681 has_fullname = 0;
22683 if (p != NULL)
22685 if (c == '.')
22687 mch_dirname(dirname, MAXPATHL);
22688 s = shorten_fname(p, dirname);
22689 if (s != NULL)
22691 *fnamep = s;
22692 if (pbuf != NULL)
22694 vim_free(*bufp); /* free any allocated file name */
22695 *bufp = pbuf;
22696 pbuf = NULL;
22700 else
22702 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
22703 /* Only replace it when it starts with '~' */
22704 if (*dirname == '~')
22706 s = vim_strsave(dirname);
22707 if (s != NULL)
22709 *fnamep = s;
22710 vim_free(*bufp);
22711 *bufp = s;
22715 vim_free(pbuf);
22719 tail = gettail(*fnamep);
22720 *fnamelen = (int)STRLEN(*fnamep);
22722 /* ":h" - head, remove "/file_name", can be repeated */
22723 /* Don't remove the first "/" or "c:\" */
22724 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
22726 valid |= VALID_HEAD;
22727 *usedlen += 2;
22728 s = get_past_head(*fnamep);
22729 while (tail > s && after_pathsep(s, tail))
22730 mb_ptr_back(*fnamep, tail);
22731 *fnamelen = (int)(tail - *fnamep);
22732 #ifdef VMS
22733 if (*fnamelen > 0)
22734 *fnamelen += 1; /* the path separator is part of the path */
22735 #endif
22736 if (*fnamelen == 0)
22738 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
22739 p = vim_strsave((char_u *)".");
22740 if (p == NULL)
22741 return -1;
22742 vim_free(*bufp);
22743 *bufp = *fnamep = tail = p;
22744 *fnamelen = 1;
22746 else
22748 while (tail > s && !after_pathsep(s, tail))
22749 mb_ptr_back(*fnamep, tail);
22753 /* ":8" - shortname */
22754 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
22756 *usedlen += 2;
22757 #ifdef WIN3264
22758 has_shortname = 1;
22759 #endif
22762 #ifdef WIN3264
22763 /* Check shortname after we have done 'heads' and before we do 'tails'
22765 if (has_shortname)
22767 pbuf = NULL;
22768 /* Copy the string if it is shortened by :h */
22769 if (*fnamelen < (int)STRLEN(*fnamep))
22771 p = vim_strnsave(*fnamep, *fnamelen);
22772 if (p == 0)
22773 return -1;
22774 vim_free(*bufp);
22775 *bufp = *fnamep = p;
22778 /* Split into two implementations - makes it easier. First is where
22779 * there isn't a full name already, second is where there is.
22781 if (!has_fullname && !vim_isAbsName(*fnamep))
22783 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
22784 return -1;
22786 else
22788 int l;
22790 /* Simple case, already have the full-name
22791 * Nearly always shorter, so try first time. */
22792 l = *fnamelen;
22793 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
22794 return -1;
22796 if (l == 0)
22798 /* Couldn't find the filename.. search the paths.
22800 l = *fnamelen;
22801 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
22802 return -1;
22804 *fnamelen = l;
22807 #endif /* WIN3264 */
22809 /* ":t" - tail, just the basename */
22810 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
22812 *usedlen += 2;
22813 *fnamelen -= (int)(tail - *fnamep);
22814 *fnamep = tail;
22817 /* ":e" - extension, can be repeated */
22818 /* ":r" - root, without extension, can be repeated */
22819 while (src[*usedlen] == ':'
22820 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
22822 /* find a '.' in the tail:
22823 * - for second :e: before the current fname
22824 * - otherwise: The last '.'
22826 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
22827 s = *fnamep - 2;
22828 else
22829 s = *fnamep + *fnamelen - 1;
22830 for ( ; s > tail; --s)
22831 if (s[0] == '.')
22832 break;
22833 if (src[*usedlen + 1] == 'e') /* :e */
22835 if (s > tail)
22837 *fnamelen += (int)(*fnamep - (s + 1));
22838 *fnamep = s + 1;
22839 #ifdef VMS
22840 /* cut version from the extension */
22841 s = *fnamep + *fnamelen - 1;
22842 for ( ; s > *fnamep; --s)
22843 if (s[0] == ';')
22844 break;
22845 if (s > *fnamep)
22846 *fnamelen = s - *fnamep;
22847 #endif
22849 else if (*fnamep <= tail)
22850 *fnamelen = 0;
22852 else /* :r */
22854 if (s > tail) /* remove one extension */
22855 *fnamelen = (int)(s - *fnamep);
22857 *usedlen += 2;
22860 /* ":s?pat?foo?" - substitute */
22861 /* ":gs?pat?foo?" - global substitute */
22862 if (src[*usedlen] == ':'
22863 && (src[*usedlen + 1] == 's'
22864 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
22866 char_u *str;
22867 char_u *pat;
22868 char_u *sub;
22869 int sep;
22870 char_u *flags;
22871 int didit = FALSE;
22873 flags = (char_u *)"";
22874 s = src + *usedlen + 2;
22875 if (src[*usedlen + 1] == 'g')
22877 flags = (char_u *)"g";
22878 ++s;
22881 sep = *s++;
22882 if (sep)
22884 /* find end of pattern */
22885 p = vim_strchr(s, sep);
22886 if (p != NULL)
22888 pat = vim_strnsave(s, (int)(p - s));
22889 if (pat != NULL)
22891 s = p + 1;
22892 /* find end of substitution */
22893 p = vim_strchr(s, sep);
22894 if (p != NULL)
22896 sub = vim_strnsave(s, (int)(p - s));
22897 str = vim_strnsave(*fnamep, *fnamelen);
22898 if (sub != NULL && str != NULL)
22900 *usedlen = (int)(p + 1 - src);
22901 s = do_string_sub(str, pat, sub, flags);
22902 if (s != NULL)
22904 *fnamep = s;
22905 *fnamelen = (int)STRLEN(s);
22906 vim_free(*bufp);
22907 *bufp = s;
22908 didit = TRUE;
22911 vim_free(sub);
22912 vim_free(str);
22914 vim_free(pat);
22917 /* after using ":s", repeat all the modifiers */
22918 if (didit)
22919 goto repeat;
22923 return valid;
22927 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
22928 * "flags" can be "g" to do a global substitute.
22929 * Returns an allocated string, NULL for error.
22931 char_u *
22932 do_string_sub(str, pat, sub, flags)
22933 char_u *str;
22934 char_u *pat;
22935 char_u *sub;
22936 char_u *flags;
22938 int sublen;
22939 regmatch_T regmatch;
22940 int i;
22941 int do_all;
22942 char_u *tail;
22943 garray_T ga;
22944 char_u *ret;
22945 char_u *save_cpo;
22947 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
22948 save_cpo = p_cpo;
22949 p_cpo = empty_option;
22951 ga_init2(&ga, 1, 200);
22953 do_all = (flags[0] == 'g');
22955 regmatch.rm_ic = p_ic;
22956 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
22957 if (regmatch.regprog != NULL)
22959 tail = str;
22960 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
22963 * Get some space for a temporary buffer to do the substitution
22964 * into. It will contain:
22965 * - The text up to where the match is.
22966 * - The substituted text.
22967 * - The text after the match.
22969 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
22970 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
22971 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
22973 ga_clear(&ga);
22974 break;
22977 /* copy the text up to where the match is */
22978 i = (int)(regmatch.startp[0] - tail);
22979 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
22980 /* add the substituted text */
22981 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
22982 + ga.ga_len + i, TRUE, TRUE, FALSE);
22983 ga.ga_len += i + sublen - 1;
22984 /* avoid getting stuck on a match with an empty string */
22985 if (tail == regmatch.endp[0])
22987 if (*tail == NUL)
22988 break;
22989 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
22990 ++ga.ga_len;
22992 else
22994 tail = regmatch.endp[0];
22995 if (*tail == NUL)
22996 break;
22998 if (!do_all)
22999 break;
23002 if (ga.ga_data != NULL)
23003 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
23005 vim_free(regmatch.regprog);
23008 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
23009 ga_clear(&ga);
23010 if (p_cpo == empty_option)
23011 p_cpo = save_cpo;
23012 else
23013 /* Darn, evaluating {sub} expression changed the value. */
23014 free_string_option(save_cpo);
23016 return ret;
23019 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */