vim72-20100325-kaoriya-w64j.zip
[MacVim/KaoriYa.git] / src / eval.c
blob24852a45ff145fd1f967c3f5de38e57a3551e538
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));
473 #endif
474 static void f_add __ARGS((typval_T *argvars, typval_T *rettv));
475 static void f_append __ARGS((typval_T *argvars, typval_T *rettv));
476 static void f_argc __ARGS((typval_T *argvars, typval_T *rettv));
477 static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv));
478 static void f_argv __ARGS((typval_T *argvars, typval_T *rettv));
479 #ifdef FEAT_FLOAT
480 static void f_atan __ARGS((typval_T *argvars, typval_T *rettv));
481 #endif
482 static void f_browse __ARGS((typval_T *argvars, typval_T *rettv));
483 static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv));
484 static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv));
485 static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv));
486 static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv));
487 static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv));
488 static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv));
489 static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv));
490 static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv));
491 static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv));
492 static void f_call __ARGS((typval_T *argvars, typval_T *rettv));
493 #ifdef FEAT_FLOAT
494 static void f_ceil __ARGS((typval_T *argvars, typval_T *rettv));
495 #endif
496 static void f_changenr __ARGS((typval_T *argvars, typval_T *rettv));
497 static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv));
498 static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv));
499 static void f_clearmatches __ARGS((typval_T *argvars, typval_T *rettv));
500 static void f_col __ARGS((typval_T *argvars, typval_T *rettv));
501 #if defined(FEAT_INS_EXPAND)
502 static void f_complete __ARGS((typval_T *argvars, typval_T *rettv));
503 static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv));
504 static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv));
505 #endif
506 static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv));
507 static void f_copy __ARGS((typval_T *argvars, typval_T *rettv));
508 #ifdef FEAT_FLOAT
509 static void f_cos __ARGS((typval_T *argvars, typval_T *rettv));
510 #endif
511 static void f_count __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv));
513 static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv));
514 static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_delete __ARGS((typval_T *argvars, typval_T *rettv));
516 static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv));
517 static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_empty __ARGS((typval_T *argvars, typval_T *rettv));
520 static void f_escape __ARGS((typval_T *argvars, typval_T *rettv));
521 static void f_eval __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv));
523 static void f_executable __ARGS((typval_T *argvars, typval_T *rettv));
524 static void f_exists __ARGS((typval_T *argvars, typval_T *rettv));
525 static void f_expand __ARGS((typval_T *argvars, typval_T *rettv));
526 static void f_extend __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_feedkeys __ARGS((typval_T *argvars, typval_T *rettv));
528 static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv));
529 static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_filter __ARGS((typval_T *argvars, typval_T *rettv));
531 static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv));
532 static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv));
533 #ifdef FEAT_FLOAT
534 static void f_float2nr __ARGS((typval_T *argvars, typval_T *rettv));
535 static void f_floor __ARGS((typval_T *argvars, typval_T *rettv));
536 #endif
537 static void f_fnameescape __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
542 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
546 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
547 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
548 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
549 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
551 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
552 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_getpid __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
590 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
591 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
592 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
593 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
594 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
595 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
596 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
603 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
604 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
605 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
606 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
607 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
608 #ifdef FEAT_FLOAT
609 static void f_log10 __ARGS((typval_T *argvars, typval_T *rettv));
610 #endif
611 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv));
618 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
619 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
620 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
621 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
622 static void f_migemo __ARGS((typval_T *argvars, typval_T *rettv));
623 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
624 #ifdef vim_mkdir
625 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
626 #endif
627 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
628 #ifdef FEAT_MZSCHEME
629 static void f_mzeval __ARGS((typval_T *argvars, typval_T *rettv));
630 #endif
631 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
632 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
633 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
634 #ifdef FEAT_FLOAT
635 static void f_pow __ARGS((typval_T *argvars, typval_T *rettv));
636 #endif
637 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
638 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
639 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
640 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
641 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
642 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
643 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
644 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
645 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
646 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
647 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
648 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
649 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
650 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
651 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
652 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
653 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
654 #ifdef FEAT_FLOAT
655 static void f_round __ARGS((typval_T *argvars, typval_T *rettv));
656 #endif
657 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
667 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
668 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
669 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
670 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
671 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
672 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
673 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
674 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
675 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
676 #ifdef FEAT_FLOAT
677 static void f_sin __ARGS((typval_T *argvars, typval_T *rettv));
678 #endif
679 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
680 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
681 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
682 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
683 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
684 #ifdef FEAT_FLOAT
685 static void f_sqrt __ARGS((typval_T *argvars, typval_T *rettv));
686 static void f_str2float __ARGS((typval_T *argvars, typval_T *rettv));
687 #endif
688 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
689 #ifdef HAVE_STRFTIME
690 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
691 #endif
692 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
693 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
694 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
695 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
696 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
697 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
698 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
699 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
700 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
701 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
702 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
703 static void f_synstack __ARGS((typval_T *argvars, typval_T *rettv));
704 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
705 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
706 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
707 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
708 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
709 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
710 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
711 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
712 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
713 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
714 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
715 #ifdef FEAT_FLOAT
716 static void f_trunc __ARGS((typval_T *argvars, typval_T *rettv));
717 #endif
718 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
719 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
720 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
721 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
722 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
723 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
724 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
725 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
726 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
727 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
728 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
729 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
730 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
731 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
733 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
734 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
735 static int get_env_len __ARGS((char_u **arg));
736 static int get_id_len __ARGS((char_u **arg));
737 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
738 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
739 #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */
740 #define FNE_CHECK_START 2 /* find_name_end(): check name starts with
741 valid character */
742 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
743 static int eval_isnamec __ARGS((int c));
744 static int eval_isnamec1 __ARGS((int c));
745 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
746 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
747 static typval_T *alloc_tv __ARGS((void));
748 static typval_T *alloc_string_tv __ARGS((char_u *string));
749 static void init_tv __ARGS((typval_T *varp));
750 static long get_tv_number __ARGS((typval_T *varp));
751 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
752 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
753 static char_u *get_tv_string __ARGS((typval_T *varp));
754 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
755 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
756 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
757 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
758 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
759 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
760 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
761 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
762 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
763 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
764 static int var_check_ro __ARGS((int flags, char_u *name));
765 static int var_check_fixed __ARGS((int flags, char_u *name));
766 static int tv_check_lock __ARGS((int lock, char_u *name));
767 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
768 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
769 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
770 static int eval_fname_script __ARGS((char_u *p));
771 static int eval_fname_sid __ARGS((char_u *p));
772 static void list_func_head __ARGS((ufunc_T *fp, int indent));
773 static ufunc_T *find_func __ARGS((char_u *name));
774 static int function_exists __ARGS((char_u *name));
775 static int builtin_function __ARGS((char_u *name));
776 #ifdef FEAT_PROFILE
777 static void func_do_profile __ARGS((ufunc_T *fp));
778 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
779 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
780 static int
781 # ifdef __BORLANDC__
782 _RTLENTRYF
783 # endif
784 prof_total_cmp __ARGS((const void *s1, const void *s2));
785 static int
786 # ifdef __BORLANDC__
787 _RTLENTRYF
788 # endif
789 prof_self_cmp __ARGS((const void *s1, const void *s2));
790 #endif
791 static int script_autoload __ARGS((char_u *name, int reload));
792 static char_u *autoload_name __ARGS((char_u *name));
793 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
794 static void func_free __ARGS((ufunc_T *fp));
795 static void func_unref __ARGS((char_u *name));
796 static void func_ref __ARGS((char_u *name));
797 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));
798 static int can_free_funccal __ARGS((funccall_T *fc, int copyID)) ;
799 static void free_funccal __ARGS((funccall_T *fc, int free_val));
800 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
801 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
802 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
803 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
804 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
805 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
807 /* Character used as separated in autoload function/variable names. */
808 #define AUTOLOAD_CHAR '#'
811 * Initialize the global and v: variables.
813 void
814 eval_init()
816 int i;
817 struct vimvar *p;
819 init_var_dict(&globvardict, &globvars_var);
820 init_var_dict(&vimvardict, &vimvars_var);
821 hash_init(&compat_hashtab);
822 hash_init(&func_hashtab);
824 for (i = 0; i < VV_LEN; ++i)
826 p = &vimvars[i];
827 STRCPY(p->vv_di.di_key, p->vv_name);
828 if (p->vv_flags & VV_RO)
829 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
830 else if (p->vv_flags & VV_RO_SBX)
831 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
832 else
833 p->vv_di.di_flags = DI_FLAGS_FIX;
835 /* add to v: scope dict, unless the value is not always available */
836 if (p->vv_type != VAR_UNKNOWN)
837 hash_add(&vimvarht, p->vv_di.di_key);
838 if (p->vv_flags & VV_COMPAT)
839 /* add to compat scope dict */
840 hash_add(&compat_hashtab, p->vv_di.di_key);
842 set_vim_var_nr(VV_SEARCHFORWARD, 1L);
845 #if defined(EXITFREE) || defined(PROTO)
846 void
847 eval_clear()
849 int i;
850 struct vimvar *p;
852 for (i = 0; i < VV_LEN; ++i)
854 p = &vimvars[i];
855 if (p->vv_di.di_tv.v_type == VAR_STRING)
857 vim_free(p->vv_str);
858 p->vv_str = NULL;
860 else if (p->vv_di.di_tv.v_type == VAR_LIST)
862 list_unref(p->vv_list);
863 p->vv_list = NULL;
866 hash_clear(&vimvarht);
867 hash_init(&vimvarht); /* garbage_collect() will access it */
868 hash_clear(&compat_hashtab);
870 /* script-local variables */
871 for (i = 1; i <= ga_scripts.ga_len; ++i)
872 vars_clear(&SCRIPT_VARS(i));
873 ga_clear(&ga_scripts);
874 free_scriptnames();
876 /* global variables */
877 vars_clear(&globvarht);
879 /* autoloaded script names */
880 ga_clear_strings(&ga_loaded);
882 /* unreferenced lists and dicts */
883 (void)garbage_collect();
885 /* functions */
886 free_all_functions();
887 hash_clear(&func_hashtab);
889 #endif
892 * Return the name of the executed function.
894 char_u *
895 func_name(cookie)
896 void *cookie;
898 return ((funccall_T *)cookie)->func->uf_name;
902 * Return the address holding the next breakpoint line for a funccall cookie.
904 linenr_T *
905 func_breakpoint(cookie)
906 void *cookie;
908 return &((funccall_T *)cookie)->breakpoint;
912 * Return the address holding the debug tick for a funccall cookie.
914 int *
915 func_dbg_tick(cookie)
916 void *cookie;
918 return &((funccall_T *)cookie)->dbg_tick;
922 * Return the nesting level for a funccall cookie.
925 func_level(cookie)
926 void *cookie;
928 return ((funccall_T *)cookie)->level;
931 /* pointer to funccal for currently active function */
932 funccall_T *current_funccal = NULL;
934 /* pointer to list of previously used funccal, still around because some
935 * item in it is still being used. */
936 funccall_T *previous_funccal = NULL;
939 * Return TRUE when a function was ended by a ":return" command.
942 current_func_returned()
944 return current_funccal->returned;
949 * Set an internal variable to a string value. Creates the variable if it does
950 * not already exist.
952 void
953 set_internal_string_var(name, value)
954 char_u *name;
955 char_u *value;
957 char_u *val;
958 typval_T *tvp;
960 val = vim_strsave(value);
961 if (val != NULL)
963 tvp = alloc_string_tv(val);
964 if (tvp != NULL)
966 set_var(name, tvp, FALSE);
967 free_tv(tvp);
972 static lval_T *redir_lval = NULL;
973 static garray_T redir_ga; /* only valid when redir_lval is not NULL */
974 static char_u *redir_endp = NULL;
975 static char_u *redir_varname = NULL;
978 * Start recording command output to a variable
979 * Returns OK if successfully completed the setup. FAIL otherwise.
982 var_redir_start(name, append)
983 char_u *name;
984 int append; /* append to an existing variable */
986 int save_emsg;
987 int err;
988 typval_T tv;
990 /* Catch a bad name early. */
991 if (!eval_isnamec1(*name))
993 EMSG(_(e_invarg));
994 return FAIL;
997 /* Make a copy of the name, it is used in redir_lval until redir ends. */
998 redir_varname = vim_strsave(name);
999 if (redir_varname == NULL)
1000 return FAIL;
1002 redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
1003 if (redir_lval == NULL)
1005 var_redir_stop();
1006 return FAIL;
1009 /* The output is stored in growarray "redir_ga" until redirection ends. */
1010 ga_init2(&redir_ga, (int)sizeof(char), 500);
1012 /* Parse the variable name (can be a dict or list entry). */
1013 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
1014 FNE_CHECK_START);
1015 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
1017 if (redir_endp != NULL && *redir_endp != NUL)
1018 /* Trailing characters are present after the variable name */
1019 EMSG(_(e_trailing));
1020 else
1021 EMSG(_(e_invarg));
1022 redir_endp = NULL; /* don't store a value, only cleanup */
1023 var_redir_stop();
1024 return FAIL;
1027 /* check if we can write to the variable: set it to or append an empty
1028 * string */
1029 save_emsg = did_emsg;
1030 did_emsg = FALSE;
1031 tv.v_type = VAR_STRING;
1032 tv.vval.v_string = (char_u *)"";
1033 if (append)
1034 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
1035 else
1036 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
1037 err = did_emsg;
1038 did_emsg |= save_emsg;
1039 if (err)
1041 redir_endp = NULL; /* don't store a value, only cleanup */
1042 var_redir_stop();
1043 return FAIL;
1045 if (redir_lval->ll_newkey != NULL)
1047 /* Dictionary item was created, don't do it again. */
1048 vim_free(redir_lval->ll_newkey);
1049 redir_lval->ll_newkey = NULL;
1052 return OK;
1056 * Append "value[value_len]" to the variable set by var_redir_start().
1057 * The actual appending is postponed until redirection ends, because the value
1058 * appended may in fact be the string we write to, changing it may cause freed
1059 * memory to be used:
1060 * :redir => foo
1061 * :let foo
1062 * :redir END
1064 void
1065 var_redir_str(value, value_len)
1066 char_u *value;
1067 int value_len;
1069 int len;
1071 if (redir_lval == NULL)
1072 return;
1074 if (value_len == -1)
1075 len = (int)STRLEN(value); /* Append the entire string */
1076 else
1077 len = value_len; /* Append only "value_len" characters */
1079 if (ga_grow(&redir_ga, len) == OK)
1081 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1082 redir_ga.ga_len += len;
1084 else
1085 var_redir_stop();
1089 * Stop redirecting command output to a variable.
1090 * Frees the allocated memory.
1092 void
1093 var_redir_stop()
1095 typval_T tv;
1097 if (redir_lval != NULL)
1099 /* If there was no error: assign the text to the variable. */
1100 if (redir_endp != NULL)
1102 ga_append(&redir_ga, NUL); /* Append the trailing NUL. */
1103 tv.v_type = VAR_STRING;
1104 tv.vval.v_string = redir_ga.ga_data;
1105 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1108 /* free the collected output */
1109 vim_free(redir_ga.ga_data);
1110 redir_ga.ga_data = NULL;
1112 clear_lval(redir_lval);
1113 vim_free(redir_lval);
1114 redir_lval = NULL;
1116 vim_free(redir_varname);
1117 redir_varname = NULL;
1120 # if defined(FEAT_MBYTE) || defined(PROTO)
1122 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1123 char_u *enc_from;
1124 char_u *enc_to;
1125 char_u *fname_from;
1126 char_u *fname_to;
1128 int err = FALSE;
1130 set_vim_var_string(VV_CC_FROM, enc_from, -1);
1131 set_vim_var_string(VV_CC_TO, enc_to, -1);
1132 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1133 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1134 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1135 err = TRUE;
1136 set_vim_var_string(VV_CC_FROM, NULL, -1);
1137 set_vim_var_string(VV_CC_TO, NULL, -1);
1138 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1139 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1141 if (err)
1142 return FAIL;
1143 return OK;
1145 # endif
1147 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1149 eval_printexpr(fname, args)
1150 char_u *fname;
1151 char_u *args;
1153 int err = FALSE;
1155 set_vim_var_string(VV_FNAME_IN, fname, -1);
1156 set_vim_var_string(VV_CMDARG, args, -1);
1157 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1158 err = TRUE;
1159 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1160 set_vim_var_string(VV_CMDARG, NULL, -1);
1162 if (err)
1164 mch_remove(fname);
1165 return FAIL;
1167 return OK;
1169 # endif
1171 # if defined(FEAT_DIFF) || defined(PROTO)
1172 void
1173 eval_diff(origfile, newfile, outfile)
1174 char_u *origfile;
1175 char_u *newfile;
1176 char_u *outfile;
1178 int err = FALSE;
1180 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1181 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1182 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1183 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1184 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1185 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1186 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1189 void
1190 eval_patch(origfile, difffile, outfile)
1191 char_u *origfile;
1192 char_u *difffile;
1193 char_u *outfile;
1195 int err;
1197 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1198 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1199 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1200 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1201 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1202 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1203 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1205 # endif
1208 * Top level evaluation function, returning a boolean.
1209 * Sets "error" to TRUE if there was an error.
1210 * Return TRUE or FALSE.
1213 eval_to_bool(arg, error, nextcmd, skip)
1214 char_u *arg;
1215 int *error;
1216 char_u **nextcmd;
1217 int skip; /* only parse, don't execute */
1219 typval_T tv;
1220 int retval = FALSE;
1222 if (skip)
1223 ++emsg_skip;
1224 if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1225 *error = TRUE;
1226 else
1228 *error = FALSE;
1229 if (!skip)
1231 retval = (get_tv_number_chk(&tv, error) != 0);
1232 clear_tv(&tv);
1235 if (skip)
1236 --emsg_skip;
1238 return retval;
1242 * Top level evaluation function, returning a string. If "skip" is TRUE,
1243 * only parsing to "nextcmd" is done, without reporting errors. Return
1244 * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1246 char_u *
1247 eval_to_string_skip(arg, nextcmd, skip)
1248 char_u *arg;
1249 char_u **nextcmd;
1250 int skip; /* only parse, don't execute */
1252 typval_T tv;
1253 char_u *retval;
1255 if (skip)
1256 ++emsg_skip;
1257 if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1258 retval = NULL;
1259 else
1261 retval = vim_strsave(get_tv_string(&tv));
1262 clear_tv(&tv);
1264 if (skip)
1265 --emsg_skip;
1267 return retval;
1271 * Skip over an expression at "*pp".
1272 * Return FAIL for an error, OK otherwise.
1275 skip_expr(pp)
1276 char_u **pp;
1278 typval_T rettv;
1280 *pp = skipwhite(*pp);
1281 return eval1(pp, &rettv, FALSE);
1285 * Top level evaluation function, returning a string.
1286 * When "convert" is TRUE convert a List into a sequence of lines and convert
1287 * a Float to a String.
1288 * Return pointer to allocated memory, or NULL for failure.
1290 char_u *
1291 eval_to_string(arg, nextcmd, convert)
1292 char_u *arg;
1293 char_u **nextcmd;
1294 int convert;
1296 typval_T tv;
1297 char_u *retval;
1298 garray_T ga;
1299 #ifdef FEAT_FLOAT
1300 char_u numbuf[NUMBUFLEN];
1301 #endif
1303 if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1304 retval = NULL;
1305 else
1307 if (convert && tv.v_type == VAR_LIST)
1309 ga_init2(&ga, (int)sizeof(char), 80);
1310 if (tv.vval.v_list != NULL)
1311 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1312 ga_append(&ga, NUL);
1313 retval = (char_u *)ga.ga_data;
1315 #ifdef FEAT_FLOAT
1316 else if (convert && tv.v_type == VAR_FLOAT)
1318 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv.vval.v_float);
1319 retval = vim_strsave(numbuf);
1321 #endif
1322 else
1323 retval = vim_strsave(get_tv_string(&tv));
1324 clear_tv(&tv);
1327 return retval;
1331 * Call eval_to_string() without using current local variables and using
1332 * textlock. When "use_sandbox" is TRUE use the sandbox.
1334 char_u *
1335 eval_to_string_safe(arg, nextcmd, use_sandbox)
1336 char_u *arg;
1337 char_u **nextcmd;
1338 int use_sandbox;
1340 char_u *retval;
1341 void *save_funccalp;
1343 save_funccalp = save_funccal();
1344 if (use_sandbox)
1345 ++sandbox;
1346 ++textlock;
1347 retval = eval_to_string(arg, nextcmd, FALSE);
1348 if (use_sandbox)
1349 --sandbox;
1350 --textlock;
1351 restore_funccal(save_funccalp);
1352 return retval;
1356 * Top level evaluation function, returning a number.
1357 * Evaluates "expr" silently.
1358 * Returns -1 for an error.
1361 eval_to_number(expr)
1362 char_u *expr;
1364 typval_T rettv;
1365 int retval;
1366 char_u *p = skipwhite(expr);
1368 ++emsg_off;
1370 if (eval1(&p, &rettv, TRUE) == FAIL)
1371 retval = -1;
1372 else
1374 retval = get_tv_number_chk(&rettv, NULL);
1375 clear_tv(&rettv);
1377 --emsg_off;
1379 return retval;
1383 * Prepare v: variable "idx" to be used.
1384 * Save the current typeval in "save_tv".
1385 * When not used yet add the variable to the v: hashtable.
1387 static void
1388 prepare_vimvar(idx, save_tv)
1389 int idx;
1390 typval_T *save_tv;
1392 *save_tv = vimvars[idx].vv_tv;
1393 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1394 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1398 * Restore v: variable "idx" to typeval "save_tv".
1399 * When no longer defined, remove the variable from the v: hashtable.
1401 static void
1402 restore_vimvar(idx, save_tv)
1403 int idx;
1404 typval_T *save_tv;
1406 hashitem_T *hi;
1408 vimvars[idx].vv_tv = *save_tv;
1409 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1411 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1412 if (HASHITEM_EMPTY(hi))
1413 EMSG2(_(e_intern2), "restore_vimvar()");
1414 else
1415 hash_remove(&vimvarht, hi);
1419 #if defined(FEAT_SPELL) || defined(PROTO)
1421 * Evaluate an expression to a list with suggestions.
1422 * For the "expr:" part of 'spellsuggest'.
1423 * Returns NULL when there is an error.
1425 list_T *
1426 eval_spell_expr(badword, expr)
1427 char_u *badword;
1428 char_u *expr;
1430 typval_T save_val;
1431 typval_T rettv;
1432 list_T *list = NULL;
1433 char_u *p = skipwhite(expr);
1435 /* Set "v:val" to the bad word. */
1436 prepare_vimvar(VV_VAL, &save_val);
1437 vimvars[VV_VAL].vv_type = VAR_STRING;
1438 vimvars[VV_VAL].vv_str = badword;
1439 if (p_verbose == 0)
1440 ++emsg_off;
1442 if (eval1(&p, &rettv, TRUE) == OK)
1444 if (rettv.v_type != VAR_LIST)
1445 clear_tv(&rettv);
1446 else
1447 list = rettv.vval.v_list;
1450 if (p_verbose == 0)
1451 --emsg_off;
1452 restore_vimvar(VV_VAL, &save_val);
1454 return list;
1458 * "list" is supposed to contain two items: a word and a number. Return the
1459 * word in "pp" and the number as the return value.
1460 * Return -1 if anything isn't right.
1461 * Used to get the good word and score from the eval_spell_expr() result.
1464 get_spellword(list, pp)
1465 list_T *list;
1466 char_u **pp;
1468 listitem_T *li;
1470 li = list->lv_first;
1471 if (li == NULL)
1472 return -1;
1473 *pp = get_tv_string(&li->li_tv);
1475 li = li->li_next;
1476 if (li == NULL)
1477 return -1;
1478 return get_tv_number(&li->li_tv);
1480 #endif
1483 * Top level evaluation function.
1484 * Returns an allocated typval_T with the result.
1485 * Returns NULL when there is an error.
1487 typval_T *
1488 eval_expr(arg, nextcmd)
1489 char_u *arg;
1490 char_u **nextcmd;
1492 typval_T *tv;
1494 tv = (typval_T *)alloc(sizeof(typval_T));
1495 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1497 vim_free(tv);
1498 tv = NULL;
1501 return tv;
1505 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1506 || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1508 * Call some vimL function and return the result in "*rettv".
1509 * Uses argv[argc] for the function arguments. Only Number and String
1510 * arguments are currently supported.
1511 * Returns OK or FAIL.
1513 static int
1514 call_vim_function(func, argc, argv, safe, rettv)
1515 char_u *func;
1516 int argc;
1517 char_u **argv;
1518 int safe; /* use the sandbox */
1519 typval_T *rettv;
1521 typval_T *argvars;
1522 long n;
1523 int len;
1524 int i;
1525 int doesrange;
1526 void *save_funccalp = NULL;
1527 int ret;
1529 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1530 if (argvars == NULL)
1531 return FAIL;
1533 for (i = 0; i < argc; i++)
1535 /* Pass a NULL or empty argument as an empty string */
1536 if (argv[i] == NULL || *argv[i] == NUL)
1538 argvars[i].v_type = VAR_STRING;
1539 argvars[i].vval.v_string = (char_u *)"";
1540 continue;
1543 /* Recognize a number argument, the others must be strings. */
1544 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1545 if (len != 0 && len == (int)STRLEN(argv[i]))
1547 argvars[i].v_type = VAR_NUMBER;
1548 argvars[i].vval.v_number = n;
1550 else
1552 argvars[i].v_type = VAR_STRING;
1553 argvars[i].vval.v_string = argv[i];
1557 if (safe)
1559 save_funccalp = save_funccal();
1560 ++sandbox;
1563 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1564 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1565 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1566 &doesrange, TRUE, NULL);
1567 if (safe)
1569 --sandbox;
1570 restore_funccal(save_funccalp);
1572 vim_free(argvars);
1574 if (ret == FAIL)
1575 clear_tv(rettv);
1577 return ret;
1580 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1582 * Call vimL function "func" and return the result as a string.
1583 * Returns NULL when calling the function fails.
1584 * Uses argv[argc] for the function arguments.
1586 void *
1587 call_func_retstr(func, argc, argv, safe)
1588 char_u *func;
1589 int argc;
1590 char_u **argv;
1591 int safe; /* use the sandbox */
1593 typval_T rettv;
1594 char_u *retval;
1596 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1597 return NULL;
1599 retval = vim_strsave(get_tv_string(&rettv));
1600 clear_tv(&rettv);
1601 return retval;
1603 # endif
1605 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1607 * Call vimL function "func" and return the result as a number.
1608 * Returns -1 when calling the function fails.
1609 * Uses argv[argc] for the function arguments.
1611 long
1612 call_func_retnr(func, argc, argv, safe)
1613 char_u *func;
1614 int argc;
1615 char_u **argv;
1616 int safe; /* use the sandbox */
1618 typval_T rettv;
1619 long retval;
1621 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1622 return -1;
1624 retval = get_tv_number_chk(&rettv, NULL);
1625 clear_tv(&rettv);
1626 return retval;
1628 # endif
1631 * Call vimL function "func" and return the result as a List.
1632 * Uses argv[argc] for the function arguments.
1633 * Returns NULL when there is something wrong.
1635 void *
1636 call_func_retlist(func, argc, argv, safe)
1637 char_u *func;
1638 int argc;
1639 char_u **argv;
1640 int safe; /* use the sandbox */
1642 typval_T rettv;
1644 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1645 return NULL;
1647 if (rettv.v_type != VAR_LIST)
1649 clear_tv(&rettv);
1650 return NULL;
1653 return rettv.vval.v_list;
1655 #endif
1659 * Save the current function call pointer, and set it to NULL.
1660 * Used when executing autocommands and for ":source".
1662 void *
1663 save_funccal()
1665 funccall_T *fc = current_funccal;
1667 current_funccal = NULL;
1668 return (void *)fc;
1671 void
1672 restore_funccal(vfc)
1673 void *vfc;
1675 funccall_T *fc = (funccall_T *)vfc;
1677 current_funccal = fc;
1680 #if defined(FEAT_PROFILE) || defined(PROTO)
1682 * Prepare profiling for entering a child or something else that is not
1683 * counted for the script/function itself.
1684 * Should always be called in pair with prof_child_exit().
1686 void
1687 prof_child_enter(tm)
1688 proftime_T *tm; /* place to store waittime */
1690 funccall_T *fc = current_funccal;
1692 if (fc != NULL && fc->func->uf_profiling)
1693 profile_start(&fc->prof_child);
1694 script_prof_save(tm);
1698 * Take care of time spent in a child.
1699 * Should always be called after prof_child_enter().
1701 void
1702 prof_child_exit(tm)
1703 proftime_T *tm; /* where waittime was stored */
1705 funccall_T *fc = current_funccal;
1707 if (fc != NULL && fc->func->uf_profiling)
1709 profile_end(&fc->prof_child);
1710 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1711 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1712 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1714 script_prof_restore(tm);
1716 #endif
1719 #ifdef FEAT_FOLDING
1721 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1722 * it in "*cp". Doesn't give error messages.
1725 eval_foldexpr(arg, cp)
1726 char_u *arg;
1727 int *cp;
1729 typval_T tv;
1730 int retval;
1731 char_u *s;
1732 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1733 OPT_LOCAL);
1735 ++emsg_off;
1736 if (use_sandbox)
1737 ++sandbox;
1738 ++textlock;
1739 *cp = NUL;
1740 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1741 retval = 0;
1742 else
1744 /* If the result is a number, just return the number. */
1745 if (tv.v_type == VAR_NUMBER)
1746 retval = tv.vval.v_number;
1747 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1748 retval = 0;
1749 else
1751 /* If the result is a string, check if there is a non-digit before
1752 * the number. */
1753 s = tv.vval.v_string;
1754 if (!VIM_ISDIGIT(*s) && *s != '-')
1755 *cp = *s++;
1756 retval = atol((char *)s);
1758 clear_tv(&tv);
1760 --emsg_off;
1761 if (use_sandbox)
1762 --sandbox;
1763 --textlock;
1765 return retval;
1767 #endif
1770 * ":let" list all variable values
1771 * ":let var1 var2" list variable values
1772 * ":let var = expr" assignment command.
1773 * ":let var += expr" assignment command.
1774 * ":let var -= expr" assignment command.
1775 * ":let var .= expr" assignment command.
1776 * ":let [var1, var2] = expr" unpack list.
1778 void
1779 ex_let(eap)
1780 exarg_T *eap;
1782 char_u *arg = eap->arg;
1783 char_u *expr = NULL;
1784 typval_T rettv;
1785 int i;
1786 int var_count = 0;
1787 int semicolon = 0;
1788 char_u op[2];
1789 char_u *argend;
1790 int first = TRUE;
1792 argend = skip_var_list(arg, &var_count, &semicolon);
1793 if (argend == NULL)
1794 return;
1795 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1796 --argend;
1797 expr = vim_strchr(argend, '=');
1798 if (expr == NULL)
1801 * ":let" without "=": list variables
1803 if (*arg == '[')
1804 EMSG(_(e_invarg));
1805 else if (!ends_excmd(*arg))
1806 /* ":let var1 var2" */
1807 arg = list_arg_vars(eap, arg, &first);
1808 else if (!eap->skip)
1810 /* ":let" */
1811 list_glob_vars(&first);
1812 list_buf_vars(&first);
1813 list_win_vars(&first);
1814 #ifdef FEAT_WINDOWS
1815 list_tab_vars(&first);
1816 #endif
1817 list_script_vars(&first);
1818 list_func_vars(&first);
1819 list_vim_vars(&first);
1821 eap->nextcmd = check_nextcmd(arg);
1823 else
1825 op[0] = '=';
1826 op[1] = NUL;
1827 if (expr > argend)
1829 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1830 op[0] = expr[-1]; /* +=, -= or .= */
1832 expr = skipwhite(expr + 1);
1834 if (eap->skip)
1835 ++emsg_skip;
1836 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1837 if (eap->skip)
1839 if (i != FAIL)
1840 clear_tv(&rettv);
1841 --emsg_skip;
1843 else if (i != FAIL)
1845 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1846 op);
1847 clear_tv(&rettv);
1853 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1854 * Handles both "var" with any type and "[var, var; var]" with a list type.
1855 * When "nextchars" is not NULL it points to a string with characters that
1856 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1857 * or concatenate.
1858 * Returns OK or FAIL;
1860 static int
1861 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1862 char_u *arg_start;
1863 typval_T *tv;
1864 int copy; /* copy values from "tv", don't move */
1865 int semicolon; /* from skip_var_list() */
1866 int var_count; /* from skip_var_list() */
1867 char_u *nextchars;
1869 char_u *arg = arg_start;
1870 list_T *l;
1871 int i;
1872 listitem_T *item;
1873 typval_T ltv;
1875 if (*arg != '[')
1878 * ":let var = expr" or ":for var in list"
1880 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1881 return FAIL;
1882 return OK;
1886 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1888 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1890 EMSG(_(e_listreq));
1891 return FAIL;
1894 i = list_len(l);
1895 if (semicolon == 0 && var_count < i)
1897 EMSG(_("E687: Less targets than List items"));
1898 return FAIL;
1900 if (var_count - semicolon > i)
1902 EMSG(_("E688: More targets than List items"));
1903 return FAIL;
1906 item = l->lv_first;
1907 while (*arg != ']')
1909 arg = skipwhite(arg + 1);
1910 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1911 item = item->li_next;
1912 if (arg == NULL)
1913 return FAIL;
1915 arg = skipwhite(arg);
1916 if (*arg == ';')
1918 /* Put the rest of the list (may be empty) in the var after ';'.
1919 * Create a new list for this. */
1920 l = list_alloc();
1921 if (l == NULL)
1922 return FAIL;
1923 while (item != NULL)
1925 list_append_tv(l, &item->li_tv);
1926 item = item->li_next;
1929 ltv.v_type = VAR_LIST;
1930 ltv.v_lock = 0;
1931 ltv.vval.v_list = l;
1932 l->lv_refcount = 1;
1934 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1935 (char_u *)"]", nextchars);
1936 clear_tv(&ltv);
1937 if (arg == NULL)
1938 return FAIL;
1939 break;
1941 else if (*arg != ',' && *arg != ']')
1943 EMSG2(_(e_intern2), "ex_let_vars()");
1944 return FAIL;
1948 return OK;
1952 * Skip over assignable variable "var" or list of variables "[var, var]".
1953 * Used for ":let varvar = expr" and ":for varvar in expr".
1954 * For "[var, var]" increment "*var_count" for each variable.
1955 * for "[var, var; var]" set "semicolon".
1956 * Return NULL for an error.
1958 static char_u *
1959 skip_var_list(arg, var_count, semicolon)
1960 char_u *arg;
1961 int *var_count;
1962 int *semicolon;
1964 char_u *p, *s;
1966 if (*arg == '[')
1968 /* "[var, var]": find the matching ']'. */
1969 p = arg;
1970 for (;;)
1972 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
1973 s = skip_var_one(p);
1974 if (s == p)
1976 EMSG2(_(e_invarg2), p);
1977 return NULL;
1979 ++*var_count;
1981 p = skipwhite(s);
1982 if (*p == ']')
1983 break;
1984 else if (*p == ';')
1986 if (*semicolon == 1)
1988 EMSG(_("Double ; in list of variables"));
1989 return NULL;
1991 *semicolon = 1;
1993 else if (*p != ',')
1995 EMSG2(_(e_invarg2), p);
1996 return NULL;
1999 return p + 1;
2001 else
2002 return skip_var_one(arg);
2006 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
2007 * l[idx].
2009 static char_u *
2010 skip_var_one(arg)
2011 char_u *arg;
2013 if (*arg == '@' && arg[1] != NUL)
2014 return arg + 2;
2015 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
2016 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2020 * List variables for hashtab "ht" with prefix "prefix".
2021 * If "empty" is TRUE also list NULL strings as empty strings.
2023 static void
2024 list_hashtable_vars(ht, prefix, empty, first)
2025 hashtab_T *ht;
2026 char_u *prefix;
2027 int empty;
2028 int *first;
2030 hashitem_T *hi;
2031 dictitem_T *di;
2032 int todo;
2034 todo = (int)ht->ht_used;
2035 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
2037 if (!HASHITEM_EMPTY(hi))
2039 --todo;
2040 di = HI2DI(hi);
2041 if (empty || di->di_tv.v_type != VAR_STRING
2042 || di->di_tv.vval.v_string != NULL)
2043 list_one_var(di, prefix, first);
2049 * List global variables.
2051 static void
2052 list_glob_vars(first)
2053 int *first;
2055 list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
2059 * List buffer variables.
2061 static void
2062 list_buf_vars(first)
2063 int *first;
2065 char_u numbuf[NUMBUFLEN];
2067 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:",
2068 TRUE, first);
2070 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
2071 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
2072 numbuf, first);
2076 * List window variables.
2078 static void
2079 list_win_vars(first)
2080 int *first;
2082 list_hashtable_vars(&curwin->w_vars.dv_hashtab,
2083 (char_u *)"w:", TRUE, first);
2086 #ifdef FEAT_WINDOWS
2088 * List tab page variables.
2090 static void
2091 list_tab_vars(first)
2092 int *first;
2094 list_hashtable_vars(&curtab->tp_vars.dv_hashtab,
2095 (char_u *)"t:", TRUE, first);
2097 #endif
2100 * List Vim variables.
2102 static void
2103 list_vim_vars(first)
2104 int *first;
2106 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2110 * List script-local variables, if there is a script.
2112 static void
2113 list_script_vars(first)
2114 int *first;
2116 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2117 list_hashtable_vars(&SCRIPT_VARS(current_SID),
2118 (char_u *)"s:", FALSE, first);
2122 * List function variables, if there is a function.
2124 static void
2125 list_func_vars(first)
2126 int *first;
2128 if (current_funccal != NULL)
2129 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2130 (char_u *)"l:", FALSE, first);
2134 * List variables in "arg".
2136 static char_u *
2137 list_arg_vars(eap, arg, first)
2138 exarg_T *eap;
2139 char_u *arg;
2140 int *first;
2142 int error = FALSE;
2143 int len;
2144 char_u *name;
2145 char_u *name_start;
2146 char_u *arg_subsc;
2147 char_u *tofree;
2148 typval_T tv;
2150 while (!ends_excmd(*arg) && !got_int)
2152 if (error || eap->skip)
2154 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2155 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2157 emsg_severe = TRUE;
2158 EMSG(_(e_trailing));
2159 break;
2162 else
2164 /* get_name_len() takes care of expanding curly braces */
2165 name_start = name = arg;
2166 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2167 if (len <= 0)
2169 /* This is mainly to keep test 49 working: when expanding
2170 * curly braces fails overrule the exception error message. */
2171 if (len < 0 && !aborting())
2173 emsg_severe = TRUE;
2174 EMSG2(_(e_invarg2), arg);
2175 break;
2177 error = TRUE;
2179 else
2181 if (tofree != NULL)
2182 name = tofree;
2183 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2184 error = TRUE;
2185 else
2187 /* handle d.key, l[idx], f(expr) */
2188 arg_subsc = arg;
2189 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2190 error = TRUE;
2191 else
2193 if (arg == arg_subsc && len == 2 && name[1] == ':')
2195 switch (*name)
2197 case 'g': list_glob_vars(first); break;
2198 case 'b': list_buf_vars(first); break;
2199 case 'w': list_win_vars(first); break;
2200 #ifdef FEAT_WINDOWS
2201 case 't': list_tab_vars(first); break;
2202 #endif
2203 case 'v': list_vim_vars(first); break;
2204 case 's': list_script_vars(first); break;
2205 case 'l': list_func_vars(first); break;
2206 default:
2207 EMSG2(_("E738: Can't list variables for %s"), name);
2210 else
2212 char_u numbuf[NUMBUFLEN];
2213 char_u *tf;
2214 int c;
2215 char_u *s;
2217 s = echo_string(&tv, &tf, numbuf, 0);
2218 c = *arg;
2219 *arg = NUL;
2220 list_one_var_a((char_u *)"",
2221 arg == arg_subsc ? name : name_start,
2222 tv.v_type,
2223 s == NULL ? (char_u *)"" : s,
2224 first);
2225 *arg = c;
2226 vim_free(tf);
2228 clear_tv(&tv);
2233 vim_free(tofree);
2236 arg = skipwhite(arg);
2239 return arg;
2243 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2244 * Returns a pointer to the char just after the var name.
2245 * Returns NULL if there is an error.
2247 static char_u *
2248 ex_let_one(arg, tv, copy, endchars, op)
2249 char_u *arg; /* points to variable name */
2250 typval_T *tv; /* value to assign to variable */
2251 int copy; /* copy value from "tv" */
2252 char_u *endchars; /* valid chars after variable name or NULL */
2253 char_u *op; /* "+", "-", "." or NULL*/
2255 int c1;
2256 char_u *name;
2257 char_u *p;
2258 char_u *arg_end = NULL;
2259 int len;
2260 int opt_flags;
2261 char_u *tofree = NULL;
2264 * ":let $VAR = expr": Set environment variable.
2266 if (*arg == '$')
2268 /* Find the end of the name. */
2269 ++arg;
2270 name = arg;
2271 len = get_env_len(&arg);
2272 if (len == 0)
2273 EMSG2(_(e_invarg2), name - 1);
2274 else
2276 if (op != NULL && (*op == '+' || *op == '-'))
2277 EMSG2(_(e_letwrong), op);
2278 else if (endchars != NULL
2279 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2280 EMSG(_(e_letunexp));
2281 else
2283 c1 = name[len];
2284 name[len] = NUL;
2285 p = get_tv_string_chk(tv);
2286 if (p != NULL && op != NULL && *op == '.')
2288 int mustfree = FALSE;
2289 char_u *s = vim_getenv(name, &mustfree);
2291 if (s != NULL)
2293 p = tofree = concat_str(s, p);
2294 if (mustfree)
2295 vim_free(s);
2298 if (p != NULL)
2300 vim_setenv(name, p);
2301 if (STRICMP(name, "HOME") == 0)
2302 init_homedir();
2303 else if (didset_vim && STRICMP(name, "VIM") == 0)
2304 didset_vim = FALSE;
2305 else if (didset_vimruntime
2306 && STRICMP(name, "VIMRUNTIME") == 0)
2307 didset_vimruntime = FALSE;
2308 arg_end = arg;
2310 name[len] = c1;
2311 vim_free(tofree);
2317 * ":let &option = expr": Set option value.
2318 * ":let &l:option = expr": Set local option value.
2319 * ":let &g:option = expr": Set global option value.
2321 else if (*arg == '&')
2323 /* Find the end of the name. */
2324 p = find_option_end(&arg, &opt_flags);
2325 if (p == NULL || (endchars != NULL
2326 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2327 EMSG(_(e_letunexp));
2328 else
2330 long n;
2331 int opt_type;
2332 long numval;
2333 char_u *stringval = NULL;
2334 char_u *s;
2336 c1 = *p;
2337 *p = NUL;
2339 n = get_tv_number(tv);
2340 s = get_tv_string_chk(tv); /* != NULL if number or string */
2341 if (s != NULL && op != NULL && *op != '=')
2343 opt_type = get_option_value(arg, &numval,
2344 &stringval, opt_flags);
2345 if ((opt_type == 1 && *op == '.')
2346 || (opt_type == 0 && *op != '.'))
2347 EMSG2(_(e_letwrong), op);
2348 else
2350 if (opt_type == 1) /* number */
2352 if (*op == '+')
2353 n = numval + n;
2354 else
2355 n = numval - n;
2357 else if (opt_type == 0 && stringval != NULL) /* string */
2359 s = concat_str(stringval, s);
2360 vim_free(stringval);
2361 stringval = s;
2365 if (s != NULL)
2367 set_option_value(arg, n, s, opt_flags);
2368 arg_end = p;
2370 *p = c1;
2371 vim_free(stringval);
2376 * ":let @r = expr": Set register contents.
2378 else if (*arg == '@')
2380 ++arg;
2381 if (op != NULL && (*op == '+' || *op == '-'))
2382 EMSG2(_(e_letwrong), op);
2383 else if (endchars != NULL
2384 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2385 EMSG(_(e_letunexp));
2386 else
2388 char_u *ptofree = NULL;
2389 char_u *s;
2391 p = get_tv_string_chk(tv);
2392 if (p != NULL && op != NULL && *op == '.')
2394 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2395 if (s != NULL)
2397 p = ptofree = concat_str(s, p);
2398 vim_free(s);
2401 if (p != NULL)
2403 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2404 arg_end = arg + 1;
2406 vim_free(ptofree);
2411 * ":let var = expr": Set internal variable.
2412 * ":let {expr} = expr": Idem, name made with curly braces
2414 else if (eval_isnamec1(*arg) || *arg == '{')
2416 lval_T lv;
2418 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2419 if (p != NULL && lv.ll_name != NULL)
2421 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2422 EMSG(_(e_letunexp));
2423 else
2425 set_var_lval(&lv, p, tv, copy, op);
2426 arg_end = p;
2429 clear_lval(&lv);
2432 else
2433 EMSG2(_(e_invarg2), arg);
2435 return arg_end;
2439 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2441 static int
2442 check_changedtick(arg)
2443 char_u *arg;
2445 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2447 EMSG2(_(e_readonlyvar), arg);
2448 return TRUE;
2450 return FALSE;
2454 * Get an lval: variable, Dict item or List item that can be assigned a value
2455 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2456 * "name.key", "name.key[expr]" etc.
2457 * Indexing only works if "name" is an existing List or Dictionary.
2458 * "name" points to the start of the name.
2459 * If "rettv" is not NULL it points to the value to be assigned.
2460 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2461 * wrong; must end in space or cmd separator.
2463 * Returns a pointer to just after the name, including indexes.
2464 * When an evaluation error occurs "lp->ll_name" is NULL;
2465 * Returns NULL for a parsing error. Still need to free items in "lp"!
2467 static char_u *
2468 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2469 char_u *name;
2470 typval_T *rettv;
2471 lval_T *lp;
2472 int unlet;
2473 int skip;
2474 int quiet; /* don't give error messages */
2475 int fne_flags; /* flags for find_name_end() */
2477 char_u *p;
2478 char_u *expr_start, *expr_end;
2479 int cc;
2480 dictitem_T *v;
2481 typval_T var1;
2482 typval_T var2;
2483 int empty1 = FALSE;
2484 listitem_T *ni;
2485 char_u *key = NULL;
2486 int len;
2487 hashtab_T *ht;
2489 /* Clear everything in "lp". */
2490 vim_memset(lp, 0, sizeof(lval_T));
2492 if (skip)
2494 /* When skipping just find the end of the name. */
2495 lp->ll_name = name;
2496 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2499 /* Find the end of the name. */
2500 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2501 if (expr_start != NULL)
2503 /* Don't expand the name when we already know there is an error. */
2504 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2505 && *p != '[' && *p != '.')
2507 EMSG(_(e_trailing));
2508 return NULL;
2511 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2512 if (lp->ll_exp_name == NULL)
2514 /* Report an invalid expression in braces, unless the
2515 * expression evaluation has been cancelled due to an
2516 * aborting error, an interrupt, or an exception. */
2517 if (!aborting() && !quiet)
2519 emsg_severe = TRUE;
2520 EMSG2(_(e_invarg2), name);
2521 return NULL;
2524 lp->ll_name = lp->ll_exp_name;
2526 else
2527 lp->ll_name = name;
2529 /* Without [idx] or .key we are done. */
2530 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2531 return p;
2533 cc = *p;
2534 *p = NUL;
2535 v = find_var(lp->ll_name, &ht);
2536 if (v == NULL && !quiet)
2537 EMSG2(_(e_undefvar), lp->ll_name);
2538 *p = cc;
2539 if (v == NULL)
2540 return NULL;
2543 * Loop until no more [idx] or .key is following.
2545 lp->ll_tv = &v->di_tv;
2546 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2548 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2549 && !(lp->ll_tv->v_type == VAR_DICT
2550 && lp->ll_tv->vval.v_dict != NULL))
2552 if (!quiet)
2553 EMSG(_("E689: Can only index a List or Dictionary"));
2554 return NULL;
2556 if (lp->ll_range)
2558 if (!quiet)
2559 EMSG(_("E708: [:] must come last"));
2560 return NULL;
2563 len = -1;
2564 if (*p == '.')
2566 key = p + 1;
2567 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2569 if (len == 0)
2571 if (!quiet)
2572 EMSG(_(e_emptykey));
2573 return NULL;
2575 p = key + len;
2577 else
2579 /* Get the index [expr] or the first index [expr: ]. */
2580 p = skipwhite(p + 1);
2581 if (*p == ':')
2582 empty1 = TRUE;
2583 else
2585 empty1 = FALSE;
2586 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2587 return NULL;
2588 if (get_tv_string_chk(&var1) == NULL)
2590 /* not a number or string */
2591 clear_tv(&var1);
2592 return NULL;
2596 /* Optionally get the second index [ :expr]. */
2597 if (*p == ':')
2599 if (lp->ll_tv->v_type == VAR_DICT)
2601 if (!quiet)
2602 EMSG(_(e_dictrange));
2603 if (!empty1)
2604 clear_tv(&var1);
2605 return NULL;
2607 if (rettv != NULL && (rettv->v_type != VAR_LIST
2608 || rettv->vval.v_list == NULL))
2610 if (!quiet)
2611 EMSG(_("E709: [:] requires a List value"));
2612 if (!empty1)
2613 clear_tv(&var1);
2614 return NULL;
2616 p = skipwhite(p + 1);
2617 if (*p == ']')
2618 lp->ll_empty2 = TRUE;
2619 else
2621 lp->ll_empty2 = FALSE;
2622 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2624 if (!empty1)
2625 clear_tv(&var1);
2626 return NULL;
2628 if (get_tv_string_chk(&var2) == NULL)
2630 /* not a number or string */
2631 if (!empty1)
2632 clear_tv(&var1);
2633 clear_tv(&var2);
2634 return NULL;
2637 lp->ll_range = TRUE;
2639 else
2640 lp->ll_range = FALSE;
2642 if (*p != ']')
2644 if (!quiet)
2645 EMSG(_(e_missbrac));
2646 if (!empty1)
2647 clear_tv(&var1);
2648 if (lp->ll_range && !lp->ll_empty2)
2649 clear_tv(&var2);
2650 return NULL;
2653 /* Skip to past ']'. */
2654 ++p;
2657 if (lp->ll_tv->v_type == VAR_DICT)
2659 if (len == -1)
2661 /* "[key]": get key from "var1" */
2662 key = get_tv_string(&var1); /* is number or string */
2663 if (*key == NUL)
2665 if (!quiet)
2666 EMSG(_(e_emptykey));
2667 clear_tv(&var1);
2668 return NULL;
2671 lp->ll_list = NULL;
2672 lp->ll_dict = lp->ll_tv->vval.v_dict;
2673 lp->ll_di = dict_find(lp->ll_dict, key, len);
2674 if (lp->ll_di == NULL)
2676 /* Key does not exist in dict: may need to add it. */
2677 if (*p == '[' || *p == '.' || unlet)
2679 if (!quiet)
2680 EMSG2(_(e_dictkey), key);
2681 if (len == -1)
2682 clear_tv(&var1);
2683 return NULL;
2685 if (len == -1)
2686 lp->ll_newkey = vim_strsave(key);
2687 else
2688 lp->ll_newkey = vim_strnsave(key, len);
2689 if (len == -1)
2690 clear_tv(&var1);
2691 if (lp->ll_newkey == NULL)
2692 p = NULL;
2693 break;
2695 if (len == -1)
2696 clear_tv(&var1);
2697 lp->ll_tv = &lp->ll_di->di_tv;
2699 else
2702 * Get the number and item for the only or first index of the List.
2704 if (empty1)
2705 lp->ll_n1 = 0;
2706 else
2708 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2709 clear_tv(&var1);
2711 lp->ll_dict = NULL;
2712 lp->ll_list = lp->ll_tv->vval.v_list;
2713 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2714 if (lp->ll_li == NULL)
2716 if (lp->ll_n1 < 0)
2718 lp->ll_n1 = 0;
2719 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2722 if (lp->ll_li == NULL)
2724 if (lp->ll_range && !lp->ll_empty2)
2725 clear_tv(&var2);
2726 return NULL;
2730 * May need to find the item or absolute index for the second
2731 * index of a range.
2732 * When no index given: "lp->ll_empty2" is TRUE.
2733 * Otherwise "lp->ll_n2" is set to the second index.
2735 if (lp->ll_range && !lp->ll_empty2)
2737 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2738 clear_tv(&var2);
2739 if (lp->ll_n2 < 0)
2741 ni = list_find(lp->ll_list, lp->ll_n2);
2742 if (ni == NULL)
2743 return NULL;
2744 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2747 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2748 if (lp->ll_n1 < 0)
2749 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2750 if (lp->ll_n2 < lp->ll_n1)
2751 return NULL;
2754 lp->ll_tv = &lp->ll_li->li_tv;
2758 return p;
2762 * Clear lval "lp" that was filled by get_lval().
2764 static void
2765 clear_lval(lp)
2766 lval_T *lp;
2768 vim_free(lp->ll_exp_name);
2769 vim_free(lp->ll_newkey);
2773 * Set a variable that was parsed by get_lval() to "rettv".
2774 * "endp" points to just after the parsed name.
2775 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2777 static void
2778 set_var_lval(lp, endp, rettv, copy, op)
2779 lval_T *lp;
2780 char_u *endp;
2781 typval_T *rettv;
2782 int copy;
2783 char_u *op;
2785 int cc;
2786 listitem_T *ri;
2787 dictitem_T *di;
2789 if (lp->ll_tv == NULL)
2791 if (!check_changedtick(lp->ll_name))
2793 cc = *endp;
2794 *endp = NUL;
2795 if (op != NULL && *op != '=')
2797 typval_T tv;
2799 /* handle +=, -= and .= */
2800 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2801 &tv, TRUE) == OK)
2803 if (tv_op(&tv, rettv, op) == OK)
2804 set_var(lp->ll_name, &tv, FALSE);
2805 clear_tv(&tv);
2808 else
2809 set_var(lp->ll_name, rettv, copy);
2810 *endp = cc;
2813 else if (tv_check_lock(lp->ll_newkey == NULL
2814 ? lp->ll_tv->v_lock
2815 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2817 else if (lp->ll_range)
2820 * Assign the List values to the list items.
2822 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2824 if (op != NULL && *op != '=')
2825 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2826 else
2828 clear_tv(&lp->ll_li->li_tv);
2829 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2831 ri = ri->li_next;
2832 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2833 break;
2834 if (lp->ll_li->li_next == NULL)
2836 /* Need to add an empty item. */
2837 if (list_append_number(lp->ll_list, 0) == FAIL)
2839 ri = NULL;
2840 break;
2843 lp->ll_li = lp->ll_li->li_next;
2844 ++lp->ll_n1;
2846 if (ri != NULL)
2847 EMSG(_("E710: List value has more items than target"));
2848 else if (lp->ll_empty2
2849 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2850 : lp->ll_n1 != lp->ll_n2)
2851 EMSG(_("E711: List value has not enough items"));
2853 else
2856 * Assign to a List or Dictionary item.
2858 if (lp->ll_newkey != NULL)
2860 if (op != NULL && *op != '=')
2862 EMSG2(_(e_letwrong), op);
2863 return;
2866 /* Need to add an item to the Dictionary. */
2867 di = dictitem_alloc(lp->ll_newkey);
2868 if (di == NULL)
2869 return;
2870 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2872 vim_free(di);
2873 return;
2875 lp->ll_tv = &di->di_tv;
2877 else if (op != NULL && *op != '=')
2879 tv_op(lp->ll_tv, rettv, op);
2880 return;
2882 else
2883 clear_tv(lp->ll_tv);
2886 * Assign the value to the variable or list item.
2888 if (copy)
2889 copy_tv(rettv, lp->ll_tv);
2890 else
2892 *lp->ll_tv = *rettv;
2893 lp->ll_tv->v_lock = 0;
2894 init_tv(rettv);
2900 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2901 * Returns OK or FAIL.
2903 static int
2904 tv_op(tv1, tv2, op)
2905 typval_T *tv1;
2906 typval_T *tv2;
2907 char_u *op;
2909 long n;
2910 char_u numbuf[NUMBUFLEN];
2911 char_u *s;
2913 /* Can't do anything with a Funcref or a Dict on the right. */
2914 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2916 switch (tv1->v_type)
2918 case VAR_DICT:
2919 case VAR_FUNC:
2920 break;
2922 case VAR_LIST:
2923 if (*op != '+' || tv2->v_type != VAR_LIST)
2924 break;
2925 /* List += List */
2926 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2927 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2928 return OK;
2930 case VAR_NUMBER:
2931 case VAR_STRING:
2932 if (tv2->v_type == VAR_LIST)
2933 break;
2934 if (*op == '+' || *op == '-')
2936 /* nr += nr or nr -= nr*/
2937 n = get_tv_number(tv1);
2938 #ifdef FEAT_FLOAT
2939 if (tv2->v_type == VAR_FLOAT)
2941 float_T f = n;
2943 if (*op == '+')
2944 f += tv2->vval.v_float;
2945 else
2946 f -= tv2->vval.v_float;
2947 clear_tv(tv1);
2948 tv1->v_type = VAR_FLOAT;
2949 tv1->vval.v_float = f;
2951 else
2952 #endif
2954 if (*op == '+')
2955 n += get_tv_number(tv2);
2956 else
2957 n -= get_tv_number(tv2);
2958 clear_tv(tv1);
2959 tv1->v_type = VAR_NUMBER;
2960 tv1->vval.v_number = n;
2963 else
2965 if (tv2->v_type == VAR_FLOAT)
2966 break;
2968 /* str .= str */
2969 s = get_tv_string(tv1);
2970 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2971 clear_tv(tv1);
2972 tv1->v_type = VAR_STRING;
2973 tv1->vval.v_string = s;
2975 return OK;
2977 #ifdef FEAT_FLOAT
2978 case VAR_FLOAT:
2980 float_T f;
2982 if (*op == '.' || (tv2->v_type != VAR_FLOAT
2983 && tv2->v_type != VAR_NUMBER
2984 && tv2->v_type != VAR_STRING))
2985 break;
2986 if (tv2->v_type == VAR_FLOAT)
2987 f = tv2->vval.v_float;
2988 else
2989 f = get_tv_number(tv2);
2990 if (*op == '+')
2991 tv1->vval.v_float += f;
2992 else
2993 tv1->vval.v_float -= f;
2995 return OK;
2996 #endif
3000 EMSG2(_(e_letwrong), op);
3001 return FAIL;
3005 * Add a watcher to a list.
3007 static void
3008 list_add_watch(l, lw)
3009 list_T *l;
3010 listwatch_T *lw;
3012 lw->lw_next = l->lv_watch;
3013 l->lv_watch = lw;
3017 * Remove a watcher from a list.
3018 * No warning when it isn't found...
3020 static void
3021 list_rem_watch(l, lwrem)
3022 list_T *l;
3023 listwatch_T *lwrem;
3025 listwatch_T *lw, **lwp;
3027 lwp = &l->lv_watch;
3028 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3030 if (lw == lwrem)
3032 *lwp = lw->lw_next;
3033 break;
3035 lwp = &lw->lw_next;
3040 * Just before removing an item from a list: advance watchers to the next
3041 * item.
3043 static void
3044 list_fix_watch(l, item)
3045 list_T *l;
3046 listitem_T *item;
3048 listwatch_T *lw;
3050 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3051 if (lw->lw_item == item)
3052 lw->lw_item = item->li_next;
3056 * Evaluate the expression used in a ":for var in expr" command.
3057 * "arg" points to "var".
3058 * Set "*errp" to TRUE for an error, FALSE otherwise;
3059 * Return a pointer that holds the info. Null when there is an error.
3061 void *
3062 eval_for_line(arg, errp, nextcmdp, skip)
3063 char_u *arg;
3064 int *errp;
3065 char_u **nextcmdp;
3066 int skip;
3068 forinfo_T *fi;
3069 char_u *expr;
3070 typval_T tv;
3071 list_T *l;
3073 *errp = TRUE; /* default: there is an error */
3075 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
3076 if (fi == NULL)
3077 return NULL;
3079 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
3080 if (expr == NULL)
3081 return fi;
3083 expr = skipwhite(expr);
3084 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
3086 EMSG(_("E690: Missing \"in\" after :for"));
3087 return fi;
3090 if (skip)
3091 ++emsg_skip;
3092 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
3094 *errp = FALSE;
3095 if (!skip)
3097 l = tv.vval.v_list;
3098 if (tv.v_type != VAR_LIST || l == NULL)
3100 EMSG(_(e_listreq));
3101 clear_tv(&tv);
3103 else
3105 /* No need to increment the refcount, it's already set for the
3106 * list being used in "tv". */
3107 fi->fi_list = l;
3108 list_add_watch(l, &fi->fi_lw);
3109 fi->fi_lw.lw_item = l->lv_first;
3113 if (skip)
3114 --emsg_skip;
3116 return fi;
3120 * Use the first item in a ":for" list. Advance to the next.
3121 * Assign the values to the variable (list). "arg" points to the first one.
3122 * Return TRUE when a valid item was found, FALSE when at end of list or
3123 * something wrong.
3126 next_for_item(fi_void, arg)
3127 void *fi_void;
3128 char_u *arg;
3130 forinfo_T *fi = (forinfo_T *)fi_void;
3131 int result;
3132 listitem_T *item;
3134 item = fi->fi_lw.lw_item;
3135 if (item == NULL)
3136 result = FALSE;
3137 else
3139 fi->fi_lw.lw_item = item->li_next;
3140 result = (ex_let_vars(arg, &item->li_tv, TRUE,
3141 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3143 return result;
3147 * Free the structure used to store info used by ":for".
3149 void
3150 free_for_info(fi_void)
3151 void *fi_void;
3153 forinfo_T *fi = (forinfo_T *)fi_void;
3155 if (fi != NULL && fi->fi_list != NULL)
3157 list_rem_watch(fi->fi_list, &fi->fi_lw);
3158 list_unref(fi->fi_list);
3160 vim_free(fi);
3163 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3165 void
3166 set_context_for_expression(xp, arg, cmdidx)
3167 expand_T *xp;
3168 char_u *arg;
3169 cmdidx_T cmdidx;
3171 int got_eq = FALSE;
3172 int c;
3173 char_u *p;
3175 if (cmdidx == CMD_let)
3177 xp->xp_context = EXPAND_USER_VARS;
3178 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3180 /* ":let var1 var2 ...": find last space. */
3181 for (p = arg + STRLEN(arg); p >= arg; )
3183 xp->xp_pattern = p;
3184 mb_ptr_back(arg, p);
3185 if (vim_iswhite(*p))
3186 break;
3188 return;
3191 else
3192 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3193 : EXPAND_EXPRESSION;
3194 while ((xp->xp_pattern = vim_strpbrk(arg,
3195 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3197 c = *xp->xp_pattern;
3198 if (c == '&')
3200 c = xp->xp_pattern[1];
3201 if (c == '&')
3203 ++xp->xp_pattern;
3204 xp->xp_context = cmdidx != CMD_let || got_eq
3205 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3207 else if (c != ' ')
3209 xp->xp_context = EXPAND_SETTINGS;
3210 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3211 xp->xp_pattern += 2;
3215 else if (c == '$')
3217 /* environment variable */
3218 xp->xp_context = EXPAND_ENV_VARS;
3220 else if (c == '=')
3222 got_eq = TRUE;
3223 xp->xp_context = EXPAND_EXPRESSION;
3225 else if (c == '<'
3226 && xp->xp_context == EXPAND_FUNCTIONS
3227 && vim_strchr(xp->xp_pattern, '(') == NULL)
3229 /* Function name can start with "<SNR>" */
3230 break;
3232 else if (cmdidx != CMD_let || got_eq)
3234 if (c == '"') /* string */
3236 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3237 if (c == '\\' && xp->xp_pattern[1] != NUL)
3238 ++xp->xp_pattern;
3239 xp->xp_context = EXPAND_NOTHING;
3241 else if (c == '\'') /* literal string */
3243 /* Trick: '' is like stopping and starting a literal string. */
3244 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3245 /* skip */ ;
3246 xp->xp_context = EXPAND_NOTHING;
3248 else if (c == '|')
3250 if (xp->xp_pattern[1] == '|')
3252 ++xp->xp_pattern;
3253 xp->xp_context = EXPAND_EXPRESSION;
3255 else
3256 xp->xp_context = EXPAND_COMMANDS;
3258 else
3259 xp->xp_context = EXPAND_EXPRESSION;
3261 else
3262 /* Doesn't look like something valid, expand as an expression
3263 * anyway. */
3264 xp->xp_context = EXPAND_EXPRESSION;
3265 arg = xp->xp_pattern;
3266 if (*arg != NUL)
3267 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3268 /* skip */ ;
3270 xp->xp_pattern = arg;
3273 #endif /* FEAT_CMDL_COMPL */
3276 * ":1,25call func(arg1, arg2)" function call.
3278 void
3279 ex_call(eap)
3280 exarg_T *eap;
3282 char_u *arg = eap->arg;
3283 char_u *startarg;
3284 char_u *name;
3285 char_u *tofree;
3286 int len;
3287 typval_T rettv;
3288 linenr_T lnum;
3289 int doesrange;
3290 int failed = FALSE;
3291 funcdict_T fudi;
3293 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3294 if (fudi.fd_newkey != NULL)
3296 /* Still need to give an error message for missing key. */
3297 EMSG2(_(e_dictkey), fudi.fd_newkey);
3298 vim_free(fudi.fd_newkey);
3300 if (tofree == NULL)
3301 return;
3303 /* Increase refcount on dictionary, it could get deleted when evaluating
3304 * the arguments. */
3305 if (fudi.fd_dict != NULL)
3306 ++fudi.fd_dict->dv_refcount;
3308 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3309 len = (int)STRLEN(tofree);
3310 name = deref_func_name(tofree, &len);
3312 /* Skip white space to allow ":call func ()". Not good, but required for
3313 * backward compatibility. */
3314 startarg = skipwhite(arg);
3315 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3317 if (*startarg != '(')
3319 EMSG2(_("E107: Missing parentheses: %s"), eap->arg);
3320 goto end;
3324 * When skipping, evaluate the function once, to find the end of the
3325 * arguments.
3326 * When the function takes a range, this is discovered after the first
3327 * call, and the loop is broken.
3329 if (eap->skip)
3331 ++emsg_skip;
3332 lnum = eap->line2; /* do it once, also with an invalid range */
3334 else
3335 lnum = eap->line1;
3336 for ( ; lnum <= eap->line2; ++lnum)
3338 if (!eap->skip && eap->addr_count > 0)
3340 curwin->w_cursor.lnum = lnum;
3341 curwin->w_cursor.col = 0;
3343 arg = startarg;
3344 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3345 eap->line1, eap->line2, &doesrange,
3346 !eap->skip, fudi.fd_dict) == FAIL)
3348 failed = TRUE;
3349 break;
3352 /* Handle a function returning a Funcref, Dictionary or List. */
3353 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3355 failed = TRUE;
3356 break;
3359 clear_tv(&rettv);
3360 if (doesrange || eap->skip)
3361 break;
3363 /* Stop when immediately aborting on error, or when an interrupt
3364 * occurred or an exception was thrown but not caught.
3365 * get_func_tv() returned OK, so that the check for trailing
3366 * characters below is executed. */
3367 if (aborting())
3368 break;
3370 if (eap->skip)
3371 --emsg_skip;
3373 if (!failed)
3375 /* Check for trailing illegal characters and a following command. */
3376 if (!ends_excmd(*arg))
3378 emsg_severe = TRUE;
3379 EMSG(_(e_trailing));
3381 else
3382 eap->nextcmd = check_nextcmd(arg);
3385 end:
3386 dict_unref(fudi.fd_dict);
3387 vim_free(tofree);
3391 * ":unlet[!] var1 ... " command.
3393 void
3394 ex_unlet(eap)
3395 exarg_T *eap;
3397 ex_unletlock(eap, eap->arg, 0);
3401 * ":lockvar" and ":unlockvar" commands
3403 void
3404 ex_lockvar(eap)
3405 exarg_T *eap;
3407 char_u *arg = eap->arg;
3408 int deep = 2;
3410 if (eap->forceit)
3411 deep = -1;
3412 else if (vim_isdigit(*arg))
3414 deep = getdigits(&arg);
3415 arg = skipwhite(arg);
3418 ex_unletlock(eap, arg, deep);
3422 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3424 static void
3425 ex_unletlock(eap, argstart, deep)
3426 exarg_T *eap;
3427 char_u *argstart;
3428 int deep;
3430 char_u *arg = argstart;
3431 char_u *name_end;
3432 int error = FALSE;
3433 lval_T lv;
3437 /* Parse the name and find the end. */
3438 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3439 FNE_CHECK_START);
3440 if (lv.ll_name == NULL)
3441 error = TRUE; /* error but continue parsing */
3442 if (name_end == NULL || (!vim_iswhite(*name_end)
3443 && !ends_excmd(*name_end)))
3445 if (name_end != NULL)
3447 emsg_severe = TRUE;
3448 EMSG(_(e_trailing));
3450 if (!(eap->skip || error))
3451 clear_lval(&lv);
3452 break;
3455 if (!error && !eap->skip)
3457 if (eap->cmdidx == CMD_unlet)
3459 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3460 error = TRUE;
3462 else
3464 if (do_lock_var(&lv, name_end, deep,
3465 eap->cmdidx == CMD_lockvar) == FAIL)
3466 error = TRUE;
3470 if (!eap->skip)
3471 clear_lval(&lv);
3473 arg = skipwhite(name_end);
3474 } while (!ends_excmd(*arg));
3476 eap->nextcmd = check_nextcmd(arg);
3479 static int
3480 do_unlet_var(lp, name_end, forceit)
3481 lval_T *lp;
3482 char_u *name_end;
3483 int forceit;
3485 int ret = OK;
3486 int cc;
3488 if (lp->ll_tv == NULL)
3490 cc = *name_end;
3491 *name_end = NUL;
3493 /* Normal name or expanded name. */
3494 if (check_changedtick(lp->ll_name))
3495 ret = FAIL;
3496 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3497 ret = FAIL;
3498 *name_end = cc;
3500 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3501 return FAIL;
3502 else if (lp->ll_range)
3504 listitem_T *li;
3506 /* Delete a range of List items. */
3507 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3509 li = lp->ll_li->li_next;
3510 listitem_remove(lp->ll_list, lp->ll_li);
3511 lp->ll_li = li;
3512 ++lp->ll_n1;
3515 else
3517 if (lp->ll_list != NULL)
3518 /* unlet a List item. */
3519 listitem_remove(lp->ll_list, lp->ll_li);
3520 else
3521 /* unlet a Dictionary item. */
3522 dictitem_remove(lp->ll_dict, lp->ll_di);
3525 return ret;
3529 * "unlet" a variable. Return OK if it existed, FAIL if not.
3530 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3533 do_unlet(name, forceit)
3534 char_u *name;
3535 int forceit;
3537 hashtab_T *ht;
3538 hashitem_T *hi;
3539 char_u *varname;
3540 dictitem_T *di;
3542 ht = find_var_ht(name, &varname);
3543 if (ht != NULL && *varname != NUL)
3545 hi = hash_find(ht, varname);
3546 if (!HASHITEM_EMPTY(hi))
3548 di = HI2DI(hi);
3549 if (var_check_fixed(di->di_flags, name)
3550 || var_check_ro(di->di_flags, name))
3551 return FAIL;
3552 delete_var(ht, hi);
3553 return OK;
3556 if (forceit)
3557 return OK;
3558 EMSG2(_("E108: No such variable: \"%s\""), name);
3559 return FAIL;
3563 * Lock or unlock variable indicated by "lp".
3564 * "deep" is the levels to go (-1 for unlimited);
3565 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3567 static int
3568 do_lock_var(lp, name_end, deep, lock)
3569 lval_T *lp;
3570 char_u *name_end;
3571 int deep;
3572 int lock;
3574 int ret = OK;
3575 int cc;
3576 dictitem_T *di;
3578 if (deep == 0) /* nothing to do */
3579 return OK;
3581 if (lp->ll_tv == NULL)
3583 cc = *name_end;
3584 *name_end = NUL;
3586 /* Normal name or expanded name. */
3587 if (check_changedtick(lp->ll_name))
3588 ret = FAIL;
3589 else
3591 di = find_var(lp->ll_name, NULL);
3592 if (di == NULL)
3593 ret = FAIL;
3594 else
3596 if (lock)
3597 di->di_flags |= DI_FLAGS_LOCK;
3598 else
3599 di->di_flags &= ~DI_FLAGS_LOCK;
3600 item_lock(&di->di_tv, deep, lock);
3603 *name_end = cc;
3605 else if (lp->ll_range)
3607 listitem_T *li = lp->ll_li;
3609 /* (un)lock a range of List items. */
3610 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3612 item_lock(&li->li_tv, deep, lock);
3613 li = li->li_next;
3614 ++lp->ll_n1;
3617 else if (lp->ll_list != NULL)
3618 /* (un)lock a List item. */
3619 item_lock(&lp->ll_li->li_tv, deep, lock);
3620 else
3621 /* un(lock) a Dictionary item. */
3622 item_lock(&lp->ll_di->di_tv, deep, lock);
3624 return ret;
3628 * Lock or unlock an item. "deep" is nr of levels to go.
3630 static void
3631 item_lock(tv, deep, lock)
3632 typval_T *tv;
3633 int deep;
3634 int lock;
3636 static int recurse = 0;
3637 list_T *l;
3638 listitem_T *li;
3639 dict_T *d;
3640 hashitem_T *hi;
3641 int todo;
3643 if (recurse >= DICT_MAXNEST)
3645 EMSG(_("E743: variable nested too deep for (un)lock"));
3646 return;
3648 if (deep == 0)
3649 return;
3650 ++recurse;
3652 /* lock/unlock the item itself */
3653 if (lock)
3654 tv->v_lock |= VAR_LOCKED;
3655 else
3656 tv->v_lock &= ~VAR_LOCKED;
3658 switch (tv->v_type)
3660 case VAR_LIST:
3661 if ((l = tv->vval.v_list) != NULL)
3663 if (lock)
3664 l->lv_lock |= VAR_LOCKED;
3665 else
3666 l->lv_lock &= ~VAR_LOCKED;
3667 if (deep < 0 || deep > 1)
3668 /* recursive: lock/unlock the items the List contains */
3669 for (li = l->lv_first; li != NULL; li = li->li_next)
3670 item_lock(&li->li_tv, deep - 1, lock);
3672 break;
3673 case VAR_DICT:
3674 if ((d = tv->vval.v_dict) != NULL)
3676 if (lock)
3677 d->dv_lock |= VAR_LOCKED;
3678 else
3679 d->dv_lock &= ~VAR_LOCKED;
3680 if (deep < 0 || deep > 1)
3682 /* recursive: lock/unlock the items the List contains */
3683 todo = (int)d->dv_hashtab.ht_used;
3684 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3686 if (!HASHITEM_EMPTY(hi))
3688 --todo;
3689 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3695 --recurse;
3699 * Return TRUE if typeval "tv" is locked: Either that value is locked itself
3700 * or it refers to a List or Dictionary that is locked.
3702 static int
3703 tv_islocked(tv)
3704 typval_T *tv;
3706 return (tv->v_lock & VAR_LOCKED)
3707 || (tv->v_type == VAR_LIST
3708 && tv->vval.v_list != NULL
3709 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3710 || (tv->v_type == VAR_DICT
3711 && tv->vval.v_dict != NULL
3712 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3715 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3717 * Delete all "menutrans_" variables.
3719 void
3720 del_menutrans_vars()
3722 hashitem_T *hi;
3723 int todo;
3725 hash_lock(&globvarht);
3726 todo = (int)globvarht.ht_used;
3727 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3729 if (!HASHITEM_EMPTY(hi))
3731 --todo;
3732 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3733 delete_var(&globvarht, hi);
3736 hash_unlock(&globvarht);
3738 #endif
3740 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3743 * Local string buffer for the next two functions to store a variable name
3744 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3745 * get_user_var_name().
3748 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3750 static char_u *varnamebuf = NULL;
3751 static int varnamebuflen = 0;
3754 * Function to concatenate a prefix and a variable name.
3756 static char_u *
3757 cat_prefix_varname(prefix, name)
3758 int prefix;
3759 char_u *name;
3761 int len;
3763 len = (int)STRLEN(name) + 3;
3764 if (len > varnamebuflen)
3766 vim_free(varnamebuf);
3767 len += 10; /* some additional space */
3768 varnamebuf = alloc(len);
3769 if (varnamebuf == NULL)
3771 varnamebuflen = 0;
3772 return NULL;
3774 varnamebuflen = len;
3776 *varnamebuf = prefix;
3777 varnamebuf[1] = ':';
3778 STRCPY(varnamebuf + 2, name);
3779 return varnamebuf;
3783 * Function given to ExpandGeneric() to obtain the list of user defined
3784 * (global/buffer/window/built-in) variable names.
3786 char_u *
3787 get_user_var_name(xp, idx)
3788 expand_T *xp;
3789 int idx;
3791 static long_u gdone;
3792 static long_u bdone;
3793 static long_u wdone;
3794 #ifdef FEAT_WINDOWS
3795 static long_u tdone;
3796 #endif
3797 static int vidx;
3798 static hashitem_T *hi;
3799 hashtab_T *ht;
3801 if (idx == 0)
3803 gdone = bdone = wdone = vidx = 0;
3804 #ifdef FEAT_WINDOWS
3805 tdone = 0;
3806 #endif
3809 /* Global variables */
3810 if (gdone < globvarht.ht_used)
3812 if (gdone++ == 0)
3813 hi = globvarht.ht_array;
3814 else
3815 ++hi;
3816 while (HASHITEM_EMPTY(hi))
3817 ++hi;
3818 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3819 return cat_prefix_varname('g', hi->hi_key);
3820 return hi->hi_key;
3823 /* b: variables */
3824 ht = &curbuf->b_vars.dv_hashtab;
3825 if (bdone < ht->ht_used)
3827 if (bdone++ == 0)
3828 hi = ht->ht_array;
3829 else
3830 ++hi;
3831 while (HASHITEM_EMPTY(hi))
3832 ++hi;
3833 return cat_prefix_varname('b', hi->hi_key);
3835 if (bdone == ht->ht_used)
3837 ++bdone;
3838 return (char_u *)"b:changedtick";
3841 /* w: variables */
3842 ht = &curwin->w_vars.dv_hashtab;
3843 if (wdone < ht->ht_used)
3845 if (wdone++ == 0)
3846 hi = ht->ht_array;
3847 else
3848 ++hi;
3849 while (HASHITEM_EMPTY(hi))
3850 ++hi;
3851 return cat_prefix_varname('w', hi->hi_key);
3854 #ifdef FEAT_WINDOWS
3855 /* t: variables */
3856 ht = &curtab->tp_vars.dv_hashtab;
3857 if (tdone < ht->ht_used)
3859 if (tdone++ == 0)
3860 hi = ht->ht_array;
3861 else
3862 ++hi;
3863 while (HASHITEM_EMPTY(hi))
3864 ++hi;
3865 return cat_prefix_varname('t', hi->hi_key);
3867 #endif
3869 /* v: variables */
3870 if (vidx < VV_LEN)
3871 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3873 vim_free(varnamebuf);
3874 varnamebuf = NULL;
3875 varnamebuflen = 0;
3876 return NULL;
3879 #endif /* FEAT_CMDL_COMPL */
3882 * types for expressions.
3884 typedef enum
3886 TYPE_UNKNOWN = 0
3887 , TYPE_EQUAL /* == */
3888 , TYPE_NEQUAL /* != */
3889 , TYPE_GREATER /* > */
3890 , TYPE_GEQUAL /* >= */
3891 , TYPE_SMALLER /* < */
3892 , TYPE_SEQUAL /* <= */
3893 , TYPE_MATCH /* =~ */
3894 , TYPE_NOMATCH /* !~ */
3895 } exptype_T;
3898 * The "evaluate" argument: When FALSE, the argument is only parsed but not
3899 * executed. The function may return OK, but the rettv will be of type
3900 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
3904 * Handle zero level expression.
3905 * This calls eval1() and handles error message and nextcmd.
3906 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3907 * Note: "rettv.v_lock" is not set.
3908 * Return OK or FAIL.
3910 static int
3911 eval0(arg, rettv, nextcmd, evaluate)
3912 char_u *arg;
3913 typval_T *rettv;
3914 char_u **nextcmd;
3915 int evaluate;
3917 int ret;
3918 char_u *p;
3920 p = skipwhite(arg);
3921 ret = eval1(&p, rettv, evaluate);
3922 if (ret == FAIL || !ends_excmd(*p))
3924 if (ret != FAIL)
3925 clear_tv(rettv);
3927 * Report the invalid expression unless the expression evaluation has
3928 * been cancelled due to an aborting error, an interrupt, or an
3929 * exception.
3931 if (!aborting())
3932 EMSG2(_(e_invexpr2), arg);
3933 ret = FAIL;
3935 if (nextcmd != NULL)
3936 *nextcmd = check_nextcmd(p);
3938 return ret;
3942 * Handle top level expression:
3943 * expr2 ? expr1 : expr1
3945 * "arg" must point to the first non-white of the expression.
3946 * "arg" is advanced to the next non-white after the recognized expression.
3948 * Note: "rettv.v_lock" is not set.
3950 * Return OK or FAIL.
3952 static int
3953 eval1(arg, rettv, evaluate)
3954 char_u **arg;
3955 typval_T *rettv;
3956 int evaluate;
3958 int result;
3959 typval_T var2;
3962 * Get the first variable.
3964 if (eval2(arg, rettv, evaluate) == FAIL)
3965 return FAIL;
3967 if ((*arg)[0] == '?')
3969 result = FALSE;
3970 if (evaluate)
3972 int error = FALSE;
3974 if (get_tv_number_chk(rettv, &error) != 0)
3975 result = TRUE;
3976 clear_tv(rettv);
3977 if (error)
3978 return FAIL;
3982 * Get the second variable.
3984 *arg = skipwhite(*arg + 1);
3985 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
3986 return FAIL;
3989 * Check for the ":".
3991 if ((*arg)[0] != ':')
3993 EMSG(_("E109: Missing ':' after '?'"));
3994 if (evaluate && result)
3995 clear_tv(rettv);
3996 return FAIL;
4000 * Get the third variable.
4002 *arg = skipwhite(*arg + 1);
4003 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
4005 if (evaluate && result)
4006 clear_tv(rettv);
4007 return FAIL;
4009 if (evaluate && !result)
4010 *rettv = var2;
4013 return OK;
4017 * Handle first level expression:
4018 * expr2 || expr2 || expr2 logical OR
4020 * "arg" must point to the first non-white of the expression.
4021 * "arg" is advanced to the next non-white after the recognized expression.
4023 * Return OK or FAIL.
4025 static int
4026 eval2(arg, rettv, evaluate)
4027 char_u **arg;
4028 typval_T *rettv;
4029 int evaluate;
4031 typval_T var2;
4032 long result;
4033 int first;
4034 int error = FALSE;
4037 * Get the first variable.
4039 if (eval3(arg, rettv, evaluate) == FAIL)
4040 return FAIL;
4043 * Repeat until there is no following "||".
4045 first = TRUE;
4046 result = FALSE;
4047 while ((*arg)[0] == '|' && (*arg)[1] == '|')
4049 if (evaluate && first)
4051 if (get_tv_number_chk(rettv, &error) != 0)
4052 result = TRUE;
4053 clear_tv(rettv);
4054 if (error)
4055 return FAIL;
4056 first = FALSE;
4060 * Get the second variable.
4062 *arg = skipwhite(*arg + 2);
4063 if (eval3(arg, &var2, evaluate && !result) == FAIL)
4064 return FAIL;
4067 * Compute the result.
4069 if (evaluate && !result)
4071 if (get_tv_number_chk(&var2, &error) != 0)
4072 result = TRUE;
4073 clear_tv(&var2);
4074 if (error)
4075 return FAIL;
4077 if (evaluate)
4079 rettv->v_type = VAR_NUMBER;
4080 rettv->vval.v_number = result;
4084 return OK;
4088 * Handle second level expression:
4089 * expr3 && expr3 && expr3 logical AND
4091 * "arg" must point to the first non-white of the expression.
4092 * "arg" is advanced to the next non-white after the recognized expression.
4094 * Return OK or FAIL.
4096 static int
4097 eval3(arg, rettv, evaluate)
4098 char_u **arg;
4099 typval_T *rettv;
4100 int evaluate;
4102 typval_T var2;
4103 long result;
4104 int first;
4105 int error = FALSE;
4108 * Get the first variable.
4110 if (eval4(arg, rettv, evaluate) == FAIL)
4111 return FAIL;
4114 * Repeat until there is no following "&&".
4116 first = TRUE;
4117 result = TRUE;
4118 while ((*arg)[0] == '&' && (*arg)[1] == '&')
4120 if (evaluate && first)
4122 if (get_tv_number_chk(rettv, &error) == 0)
4123 result = FALSE;
4124 clear_tv(rettv);
4125 if (error)
4126 return FAIL;
4127 first = FALSE;
4131 * Get the second variable.
4133 *arg = skipwhite(*arg + 2);
4134 if (eval4(arg, &var2, evaluate && result) == FAIL)
4135 return FAIL;
4138 * Compute the result.
4140 if (evaluate && result)
4142 if (get_tv_number_chk(&var2, &error) == 0)
4143 result = FALSE;
4144 clear_tv(&var2);
4145 if (error)
4146 return FAIL;
4148 if (evaluate)
4150 rettv->v_type = VAR_NUMBER;
4151 rettv->vval.v_number = result;
4155 return OK;
4159 * Handle third level expression:
4160 * var1 == var2
4161 * var1 =~ var2
4162 * var1 != var2
4163 * var1 !~ var2
4164 * var1 > var2
4165 * var1 >= var2
4166 * var1 < var2
4167 * var1 <= var2
4168 * var1 is var2
4169 * var1 isnot var2
4171 * "arg" must point to the first non-white of the expression.
4172 * "arg" is advanced to the next non-white after the recognized expression.
4174 * Return OK or FAIL.
4176 static int
4177 eval4(arg, rettv, evaluate)
4178 char_u **arg;
4179 typval_T *rettv;
4180 int evaluate;
4182 typval_T var2;
4183 char_u *p;
4184 int i;
4185 exptype_T type = TYPE_UNKNOWN;
4186 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4187 int len = 2;
4188 long n1, n2;
4189 char_u *s1, *s2;
4190 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4191 regmatch_T regmatch;
4192 int ic;
4193 char_u *save_cpo;
4196 * Get the first variable.
4198 if (eval5(arg, rettv, evaluate) == FAIL)
4199 return FAIL;
4201 p = *arg;
4202 switch (p[0])
4204 case '=': if (p[1] == '=')
4205 type = TYPE_EQUAL;
4206 else if (p[1] == '~')
4207 type = TYPE_MATCH;
4208 break;
4209 case '!': if (p[1] == '=')
4210 type = TYPE_NEQUAL;
4211 else if (p[1] == '~')
4212 type = TYPE_NOMATCH;
4213 break;
4214 case '>': if (p[1] != '=')
4216 type = TYPE_GREATER;
4217 len = 1;
4219 else
4220 type = TYPE_GEQUAL;
4221 break;
4222 case '<': if (p[1] != '=')
4224 type = TYPE_SMALLER;
4225 len = 1;
4227 else
4228 type = TYPE_SEQUAL;
4229 break;
4230 case 'i': if (p[1] == 's')
4232 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4233 len = 5;
4234 if (!vim_isIDc(p[len]))
4236 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4237 type_is = TRUE;
4240 break;
4244 * If there is a comparative operator, use it.
4246 if (type != TYPE_UNKNOWN)
4248 /* extra question mark appended: ignore case */
4249 if (p[len] == '?')
4251 ic = TRUE;
4252 ++len;
4254 /* extra '#' appended: match case */
4255 else if (p[len] == '#')
4257 ic = FALSE;
4258 ++len;
4260 /* nothing appended: use 'ignorecase' */
4261 else
4262 ic = p_ic;
4265 * Get the second variable.
4267 *arg = skipwhite(p + len);
4268 if (eval5(arg, &var2, evaluate) == FAIL)
4270 clear_tv(rettv);
4271 return FAIL;
4274 if (evaluate)
4276 if (type_is && rettv->v_type != var2.v_type)
4278 /* For "is" a different type always means FALSE, for "notis"
4279 * it means TRUE. */
4280 n1 = (type == TYPE_NEQUAL);
4282 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4284 if (type_is)
4286 n1 = (rettv->v_type == var2.v_type
4287 && rettv->vval.v_list == var2.vval.v_list);
4288 if (type == TYPE_NEQUAL)
4289 n1 = !n1;
4291 else if (rettv->v_type != var2.v_type
4292 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4294 if (rettv->v_type != var2.v_type)
4295 EMSG(_("E691: Can only compare List with List"));
4296 else
4297 EMSG(_("E692: Invalid operation for Lists"));
4298 clear_tv(rettv);
4299 clear_tv(&var2);
4300 return FAIL;
4302 else
4304 /* Compare two Lists for being equal or unequal. */
4305 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
4306 if (type == TYPE_NEQUAL)
4307 n1 = !n1;
4311 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4313 if (type_is)
4315 n1 = (rettv->v_type == var2.v_type
4316 && rettv->vval.v_dict == var2.vval.v_dict);
4317 if (type == TYPE_NEQUAL)
4318 n1 = !n1;
4320 else if (rettv->v_type != var2.v_type
4321 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4323 if (rettv->v_type != var2.v_type)
4324 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4325 else
4326 EMSG(_("E736: Invalid operation for Dictionary"));
4327 clear_tv(rettv);
4328 clear_tv(&var2);
4329 return FAIL;
4331 else
4333 /* Compare two Dictionaries for being equal or unequal. */
4334 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4335 if (type == TYPE_NEQUAL)
4336 n1 = !n1;
4340 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4342 if (rettv->v_type != var2.v_type
4343 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4345 if (rettv->v_type != var2.v_type)
4346 EMSG(_("E693: Can only compare Funcref with Funcref"));
4347 else
4348 EMSG(_("E694: Invalid operation for Funcrefs"));
4349 clear_tv(rettv);
4350 clear_tv(&var2);
4351 return FAIL;
4353 else
4355 /* Compare two Funcrefs for being equal or unequal. */
4356 if (rettv->vval.v_string == NULL
4357 || var2.vval.v_string == NULL)
4358 n1 = FALSE;
4359 else
4360 n1 = STRCMP(rettv->vval.v_string,
4361 var2.vval.v_string) == 0;
4362 if (type == TYPE_NEQUAL)
4363 n1 = !n1;
4367 #ifdef FEAT_FLOAT
4369 * If one of the two variables is a float, compare as a float.
4370 * When using "=~" or "!~", always compare as string.
4372 else if ((rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4373 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4375 float_T f1, f2;
4377 if (rettv->v_type == VAR_FLOAT)
4378 f1 = rettv->vval.v_float;
4379 else
4380 f1 = get_tv_number(rettv);
4381 if (var2.v_type == VAR_FLOAT)
4382 f2 = var2.vval.v_float;
4383 else
4384 f2 = get_tv_number(&var2);
4385 n1 = FALSE;
4386 switch (type)
4388 case TYPE_EQUAL: n1 = (f1 == f2); break;
4389 case TYPE_NEQUAL: n1 = (f1 != f2); break;
4390 case TYPE_GREATER: n1 = (f1 > f2); break;
4391 case TYPE_GEQUAL: n1 = (f1 >= f2); break;
4392 case TYPE_SMALLER: n1 = (f1 < f2); break;
4393 case TYPE_SEQUAL: n1 = (f1 <= f2); break;
4394 case TYPE_UNKNOWN:
4395 case TYPE_MATCH:
4396 case TYPE_NOMATCH: break; /* avoid gcc warning */
4399 #endif
4402 * If one of the two variables is a number, compare as a number.
4403 * When using "=~" or "!~", always compare as string.
4405 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4406 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4408 n1 = get_tv_number(rettv);
4409 n2 = get_tv_number(&var2);
4410 switch (type)
4412 case TYPE_EQUAL: n1 = (n1 == n2); break;
4413 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4414 case TYPE_GREATER: n1 = (n1 > n2); break;
4415 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4416 case TYPE_SMALLER: n1 = (n1 < n2); break;
4417 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4418 case TYPE_UNKNOWN:
4419 case TYPE_MATCH:
4420 case TYPE_NOMATCH: break; /* avoid gcc warning */
4423 else
4425 s1 = get_tv_string_buf(rettv, buf1);
4426 s2 = get_tv_string_buf(&var2, buf2);
4427 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4428 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4429 else
4430 i = 0;
4431 n1 = FALSE;
4432 switch (type)
4434 case TYPE_EQUAL: n1 = (i == 0); break;
4435 case TYPE_NEQUAL: n1 = (i != 0); break;
4436 case TYPE_GREATER: n1 = (i > 0); break;
4437 case TYPE_GEQUAL: n1 = (i >= 0); break;
4438 case TYPE_SMALLER: n1 = (i < 0); break;
4439 case TYPE_SEQUAL: n1 = (i <= 0); break;
4441 case TYPE_MATCH:
4442 case TYPE_NOMATCH:
4443 /* avoid 'l' flag in 'cpoptions' */
4444 save_cpo = p_cpo;
4445 p_cpo = (char_u *)"";
4446 regmatch.regprog = vim_regcomp(s2,
4447 RE_MAGIC + RE_STRING);
4448 regmatch.rm_ic = ic;
4449 if (regmatch.regprog != NULL)
4451 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4452 vim_free(regmatch.regprog);
4453 if (type == TYPE_NOMATCH)
4454 n1 = !n1;
4456 p_cpo = save_cpo;
4457 break;
4459 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4462 clear_tv(rettv);
4463 clear_tv(&var2);
4464 rettv->v_type = VAR_NUMBER;
4465 rettv->vval.v_number = n1;
4469 return OK;
4473 * Handle fourth level expression:
4474 * + number addition
4475 * - number subtraction
4476 * . string concatenation
4478 * "arg" must point to the first non-white of the expression.
4479 * "arg" is advanced to the next non-white after the recognized expression.
4481 * Return OK or FAIL.
4483 static int
4484 eval5(arg, rettv, evaluate)
4485 char_u **arg;
4486 typval_T *rettv;
4487 int evaluate;
4489 typval_T var2;
4490 typval_T var3;
4491 int op;
4492 long n1, n2;
4493 #ifdef FEAT_FLOAT
4494 float_T f1 = 0, f2 = 0;
4495 #endif
4496 char_u *s1, *s2;
4497 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4498 char_u *p;
4501 * Get the first variable.
4503 if (eval6(arg, rettv, evaluate, FALSE) == FAIL)
4504 return FAIL;
4507 * Repeat computing, until no '+', '-' or '.' is following.
4509 for (;;)
4511 op = **arg;
4512 if (op != '+' && op != '-' && op != '.')
4513 break;
4515 if ((op != '+' || rettv->v_type != VAR_LIST)
4516 #ifdef FEAT_FLOAT
4517 && (op == '.' || rettv->v_type != VAR_FLOAT)
4518 #endif
4521 /* For "list + ...", an illegal use of the first operand as
4522 * a number cannot be determined before evaluating the 2nd
4523 * operand: if this is also a list, all is ok.
4524 * For "something . ...", "something - ..." or "non-list + ...",
4525 * we know that the first operand needs to be a string or number
4526 * without evaluating the 2nd operand. So check before to avoid
4527 * side effects after an error. */
4528 if (evaluate && get_tv_string_chk(rettv) == NULL)
4530 clear_tv(rettv);
4531 return FAIL;
4536 * Get the second variable.
4538 *arg = skipwhite(*arg + 1);
4539 if (eval6(arg, &var2, evaluate, op == '.') == FAIL)
4541 clear_tv(rettv);
4542 return FAIL;
4545 if (evaluate)
4548 * Compute the result.
4550 if (op == '.')
4552 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4553 s2 = get_tv_string_buf_chk(&var2, buf2);
4554 if (s2 == NULL) /* type error ? */
4556 clear_tv(rettv);
4557 clear_tv(&var2);
4558 return FAIL;
4560 p = concat_str(s1, s2);
4561 clear_tv(rettv);
4562 rettv->v_type = VAR_STRING;
4563 rettv->vval.v_string = p;
4565 else if (op == '+' && rettv->v_type == VAR_LIST
4566 && var2.v_type == VAR_LIST)
4568 /* concatenate Lists */
4569 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4570 &var3) == FAIL)
4572 clear_tv(rettv);
4573 clear_tv(&var2);
4574 return FAIL;
4576 clear_tv(rettv);
4577 *rettv = var3;
4579 else
4581 int error = FALSE;
4583 #ifdef FEAT_FLOAT
4584 if (rettv->v_type == VAR_FLOAT)
4586 f1 = rettv->vval.v_float;
4587 n1 = 0;
4589 else
4590 #endif
4592 n1 = get_tv_number_chk(rettv, &error);
4593 if (error)
4595 /* This can only happen for "list + non-list". For
4596 * "non-list + ..." or "something - ...", we returned
4597 * before evaluating the 2nd operand. */
4598 clear_tv(rettv);
4599 return FAIL;
4601 #ifdef FEAT_FLOAT
4602 if (var2.v_type == VAR_FLOAT)
4603 f1 = n1;
4604 #endif
4606 #ifdef FEAT_FLOAT
4607 if (var2.v_type == VAR_FLOAT)
4609 f2 = var2.vval.v_float;
4610 n2 = 0;
4612 else
4613 #endif
4615 n2 = get_tv_number_chk(&var2, &error);
4616 if (error)
4618 clear_tv(rettv);
4619 clear_tv(&var2);
4620 return FAIL;
4622 #ifdef FEAT_FLOAT
4623 if (rettv->v_type == VAR_FLOAT)
4624 f2 = n2;
4625 #endif
4627 clear_tv(rettv);
4629 #ifdef FEAT_FLOAT
4630 /* If there is a float on either side the result is a float. */
4631 if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4633 if (op == '+')
4634 f1 = f1 + f2;
4635 else
4636 f1 = f1 - f2;
4637 rettv->v_type = VAR_FLOAT;
4638 rettv->vval.v_float = f1;
4640 else
4641 #endif
4643 if (op == '+')
4644 n1 = n1 + n2;
4645 else
4646 n1 = n1 - n2;
4647 rettv->v_type = VAR_NUMBER;
4648 rettv->vval.v_number = n1;
4651 clear_tv(&var2);
4654 return OK;
4658 * Handle fifth level expression:
4659 * * number multiplication
4660 * / number division
4661 * % number modulo
4663 * "arg" must point to the first non-white of the expression.
4664 * "arg" is advanced to the next non-white after the recognized expression.
4666 * Return OK or FAIL.
4668 static int
4669 eval6(arg, rettv, evaluate, want_string)
4670 char_u **arg;
4671 typval_T *rettv;
4672 int evaluate;
4673 int want_string; /* after "." operator */
4675 typval_T var2;
4676 int op;
4677 long n1, n2;
4678 #ifdef FEAT_FLOAT
4679 int use_float = FALSE;
4680 float_T f1 = 0, f2;
4681 #endif
4682 int error = FALSE;
4685 * Get the first variable.
4687 if (eval7(arg, rettv, evaluate, want_string) == FAIL)
4688 return FAIL;
4691 * Repeat computing, until no '*', '/' or '%' is following.
4693 for (;;)
4695 op = **arg;
4696 if (op != '*' && op != '/' && op != '%')
4697 break;
4699 if (evaluate)
4701 #ifdef FEAT_FLOAT
4702 if (rettv->v_type == VAR_FLOAT)
4704 f1 = rettv->vval.v_float;
4705 use_float = TRUE;
4706 n1 = 0;
4708 else
4709 #endif
4710 n1 = get_tv_number_chk(rettv, &error);
4711 clear_tv(rettv);
4712 if (error)
4713 return FAIL;
4715 else
4716 n1 = 0;
4719 * Get the second variable.
4721 *arg = skipwhite(*arg + 1);
4722 if (eval7(arg, &var2, evaluate, FALSE) == FAIL)
4723 return FAIL;
4725 if (evaluate)
4727 #ifdef FEAT_FLOAT
4728 if (var2.v_type == VAR_FLOAT)
4730 if (!use_float)
4732 f1 = n1;
4733 use_float = TRUE;
4735 f2 = var2.vval.v_float;
4736 n2 = 0;
4738 else
4739 #endif
4741 n2 = get_tv_number_chk(&var2, &error);
4742 clear_tv(&var2);
4743 if (error)
4744 return FAIL;
4745 #ifdef FEAT_FLOAT
4746 if (use_float)
4747 f2 = n2;
4748 #endif
4752 * Compute the result.
4753 * When either side is a float the result is a float.
4755 #ifdef FEAT_FLOAT
4756 if (use_float)
4758 if (op == '*')
4759 f1 = f1 * f2;
4760 else if (op == '/')
4762 /* We rely on the floating point library to handle divide
4763 * by zero to result in "inf" and not a crash. */
4764 f1 = f1 / f2;
4766 else
4768 EMSG(_("E804: Cannot use '%' with Float"));
4769 return FAIL;
4771 rettv->v_type = VAR_FLOAT;
4772 rettv->vval.v_float = f1;
4774 else
4775 #endif
4777 if (op == '*')
4778 n1 = n1 * n2;
4779 else if (op == '/')
4781 if (n2 == 0) /* give an error message? */
4783 if (n1 == 0)
4784 n1 = -0x7fffffffL - 1L; /* similar to NaN */
4785 else if (n1 < 0)
4786 n1 = -0x7fffffffL;
4787 else
4788 n1 = 0x7fffffffL;
4790 else
4791 n1 = n1 / n2;
4793 else
4795 if (n2 == 0) /* give an error message? */
4796 n1 = 0;
4797 else
4798 n1 = n1 % n2;
4800 rettv->v_type = VAR_NUMBER;
4801 rettv->vval.v_number = n1;
4806 return OK;
4810 * Handle sixth level expression:
4811 * number number constant
4812 * "string" string constant
4813 * 'string' literal string constant
4814 * &option-name option value
4815 * @r register contents
4816 * identifier variable value
4817 * function() function call
4818 * $VAR environment variable
4819 * (expression) nested expression
4820 * [expr, expr] List
4821 * {key: val, key: val} Dictionary
4823 * Also handle:
4824 * ! in front logical NOT
4825 * - in front unary minus
4826 * + in front unary plus (ignored)
4827 * trailing [] subscript in String or List
4828 * trailing .name entry in Dictionary
4830 * "arg" must point to the first non-white of the expression.
4831 * "arg" is advanced to the next non-white after the recognized expression.
4833 * Return OK or FAIL.
4835 static int
4836 eval7(arg, rettv, evaluate, want_string)
4837 char_u **arg;
4838 typval_T *rettv;
4839 int evaluate;
4840 int want_string; /* after "." operator */
4842 long n;
4843 int len;
4844 char_u *s;
4845 char_u *start_leader, *end_leader;
4846 int ret = OK;
4847 char_u *alias;
4850 * Initialise variable so that clear_tv() can't mistake this for a
4851 * string and free a string that isn't there.
4853 rettv->v_type = VAR_UNKNOWN;
4856 * Skip '!' and '-' characters. They are handled later.
4858 start_leader = *arg;
4859 while (**arg == '!' || **arg == '-' || **arg == '+')
4860 *arg = skipwhite(*arg + 1);
4861 end_leader = *arg;
4863 switch (**arg)
4866 * Number constant.
4868 case '0':
4869 case '1':
4870 case '2':
4871 case '3':
4872 case '4':
4873 case '5':
4874 case '6':
4875 case '7':
4876 case '8':
4877 case '9':
4879 #ifdef FEAT_FLOAT
4880 char_u *p = skipdigits(*arg + 1);
4881 int get_float = FALSE;
4883 /* We accept a float when the format matches
4884 * "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?". This is very
4885 * strict to avoid backwards compatibility problems.
4886 * Don't look for a float after the "." operator, so that
4887 * ":let vers = 1.2.3" doesn't fail. */
4888 if (!want_string && p[0] == '.' && vim_isdigit(p[1]))
4890 get_float = TRUE;
4891 p = skipdigits(p + 2);
4892 if (*p == 'e' || *p == 'E')
4894 ++p;
4895 if (*p == '-' || *p == '+')
4896 ++p;
4897 if (!vim_isdigit(*p))
4898 get_float = FALSE;
4899 else
4900 p = skipdigits(p + 1);
4902 if (ASCII_ISALPHA(*p) || *p == '.')
4903 get_float = FALSE;
4905 if (get_float)
4907 float_T f;
4909 *arg += string2float(*arg, &f);
4910 if (evaluate)
4912 rettv->v_type = VAR_FLOAT;
4913 rettv->vval.v_float = f;
4916 else
4917 #endif
4919 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4920 *arg += len;
4921 if (evaluate)
4923 rettv->v_type = VAR_NUMBER;
4924 rettv->vval.v_number = n;
4927 break;
4931 * String constant: "string".
4933 case '"': ret = get_string_tv(arg, rettv, evaluate);
4934 break;
4937 * Literal string constant: 'str''ing'.
4939 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
4940 break;
4943 * List: [expr, expr]
4945 case '[': ret = get_list_tv(arg, rettv, evaluate);
4946 break;
4949 * Dictionary: {key: val, key: val}
4951 case '{': ret = get_dict_tv(arg, rettv, evaluate);
4952 break;
4955 * Option value: &name
4957 case '&': ret = get_option_tv(arg, rettv, evaluate);
4958 break;
4961 * Environment variable: $VAR.
4963 case '$': ret = get_env_tv(arg, rettv, evaluate);
4964 break;
4967 * Register contents: @r.
4969 case '@': ++*arg;
4970 if (evaluate)
4972 rettv->v_type = VAR_STRING;
4973 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4975 if (**arg != NUL)
4976 ++*arg;
4977 break;
4980 * nested expression: (expression).
4982 case '(': *arg = skipwhite(*arg + 1);
4983 ret = eval1(arg, rettv, evaluate); /* recursive! */
4984 if (**arg == ')')
4985 ++*arg;
4986 else if (ret == OK)
4988 EMSG(_("E110: Missing ')'"));
4989 clear_tv(rettv);
4990 ret = FAIL;
4992 break;
4994 default: ret = NOTDONE;
4995 break;
4998 if (ret == NOTDONE)
5001 * Must be a variable or function name.
5002 * Can also be a curly-braces kind of name: {expr}.
5004 s = *arg;
5005 len = get_name_len(arg, &alias, evaluate, TRUE);
5006 if (alias != NULL)
5007 s = alias;
5009 if (len <= 0)
5010 ret = FAIL;
5011 else
5013 if (**arg == '(') /* recursive! */
5015 /* If "s" is the name of a variable of type VAR_FUNC
5016 * use its contents. */
5017 s = deref_func_name(s, &len);
5019 /* Invoke the function. */
5020 ret = get_func_tv(s, len, rettv, arg,
5021 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
5022 &len, evaluate, NULL);
5023 /* Stop the expression evaluation when immediately
5024 * aborting on error, or when an interrupt occurred or
5025 * an exception was thrown but not caught. */
5026 if (aborting())
5028 if (ret == OK)
5029 clear_tv(rettv);
5030 ret = FAIL;
5033 else if (evaluate)
5034 ret = get_var_tv(s, len, rettv, TRUE);
5035 else
5036 ret = OK;
5039 if (alias != NULL)
5040 vim_free(alias);
5043 *arg = skipwhite(*arg);
5045 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
5046 * expr(expr). */
5047 if (ret == OK)
5048 ret = handle_subscript(arg, rettv, evaluate, TRUE);
5051 * Apply logical NOT and unary '-', from right to left, ignore '+'.
5053 if (ret == OK && evaluate && end_leader > start_leader)
5055 int error = FALSE;
5056 int val = 0;
5057 #ifdef FEAT_FLOAT
5058 float_T f = 0.0;
5060 if (rettv->v_type == VAR_FLOAT)
5061 f = rettv->vval.v_float;
5062 else
5063 #endif
5064 val = get_tv_number_chk(rettv, &error);
5065 if (error)
5067 clear_tv(rettv);
5068 ret = FAIL;
5070 else
5072 while (end_leader > start_leader)
5074 --end_leader;
5075 if (*end_leader == '!')
5077 #ifdef FEAT_FLOAT
5078 if (rettv->v_type == VAR_FLOAT)
5079 f = !f;
5080 else
5081 #endif
5082 val = !val;
5084 else if (*end_leader == '-')
5086 #ifdef FEAT_FLOAT
5087 if (rettv->v_type == VAR_FLOAT)
5088 f = -f;
5089 else
5090 #endif
5091 val = -val;
5094 #ifdef FEAT_FLOAT
5095 if (rettv->v_type == VAR_FLOAT)
5097 clear_tv(rettv);
5098 rettv->vval.v_float = f;
5100 else
5101 #endif
5103 clear_tv(rettv);
5104 rettv->v_type = VAR_NUMBER;
5105 rettv->vval.v_number = val;
5110 return ret;
5114 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
5115 * "*arg" points to the '[' or '.'.
5116 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
5118 static int
5119 eval_index(arg, rettv, evaluate, verbose)
5120 char_u **arg;
5121 typval_T *rettv;
5122 int evaluate;
5123 int verbose; /* give error messages */
5125 int empty1 = FALSE, empty2 = FALSE;
5126 typval_T var1, var2;
5127 long n1, n2 = 0;
5128 long len = -1;
5129 int range = FALSE;
5130 char_u *s;
5131 char_u *key = NULL;
5133 if (rettv->v_type == VAR_FUNC
5134 #ifdef FEAT_FLOAT
5135 || rettv->v_type == VAR_FLOAT
5136 #endif
5139 if (verbose)
5140 EMSG(_("E695: Cannot index a Funcref"));
5141 return FAIL;
5144 if (**arg == '.')
5147 * dict.name
5149 key = *arg + 1;
5150 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
5152 if (len == 0)
5153 return FAIL;
5154 *arg = skipwhite(key + len);
5156 else
5159 * something[idx]
5161 * Get the (first) variable from inside the [].
5163 *arg = skipwhite(*arg + 1);
5164 if (**arg == ':')
5165 empty1 = TRUE;
5166 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
5167 return FAIL;
5168 else if (evaluate && get_tv_string_chk(&var1) == NULL)
5170 /* not a number or string */
5171 clear_tv(&var1);
5172 return FAIL;
5176 * Get the second variable from inside the [:].
5178 if (**arg == ':')
5180 range = TRUE;
5181 *arg = skipwhite(*arg + 1);
5182 if (**arg == ']')
5183 empty2 = TRUE;
5184 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
5186 if (!empty1)
5187 clear_tv(&var1);
5188 return FAIL;
5190 else if (evaluate && get_tv_string_chk(&var2) == NULL)
5192 /* not a number or string */
5193 if (!empty1)
5194 clear_tv(&var1);
5195 clear_tv(&var2);
5196 return FAIL;
5200 /* Check for the ']'. */
5201 if (**arg != ']')
5203 if (verbose)
5204 EMSG(_(e_missbrac));
5205 clear_tv(&var1);
5206 if (range)
5207 clear_tv(&var2);
5208 return FAIL;
5210 *arg = skipwhite(*arg + 1); /* skip the ']' */
5213 if (evaluate)
5215 n1 = 0;
5216 if (!empty1 && rettv->v_type != VAR_DICT)
5218 n1 = get_tv_number(&var1);
5219 clear_tv(&var1);
5221 if (range)
5223 if (empty2)
5224 n2 = -1;
5225 else
5227 n2 = get_tv_number(&var2);
5228 clear_tv(&var2);
5232 switch (rettv->v_type)
5234 case VAR_NUMBER:
5235 case VAR_STRING:
5236 s = get_tv_string(rettv);
5237 len = (long)STRLEN(s);
5238 if (range)
5240 /* The resulting variable is a substring. If the indexes
5241 * are out of range the result is empty. */
5242 if (n1 < 0)
5244 n1 = len + n1;
5245 if (n1 < 0)
5246 n1 = 0;
5248 if (n2 < 0)
5249 n2 = len + n2;
5250 else if (n2 >= len)
5251 n2 = len;
5252 if (n1 >= len || n2 < 0 || n1 > n2)
5253 s = NULL;
5254 else
5255 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
5257 else
5259 /* The resulting variable is a string of a single
5260 * character. If the index is too big or negative the
5261 * result is empty. */
5262 if (n1 >= len || n1 < 0)
5263 s = NULL;
5264 else
5265 s = vim_strnsave(s + n1, 1);
5267 clear_tv(rettv);
5268 rettv->v_type = VAR_STRING;
5269 rettv->vval.v_string = s;
5270 break;
5272 case VAR_LIST:
5273 len = list_len(rettv->vval.v_list);
5274 if (n1 < 0)
5275 n1 = len + n1;
5276 if (!empty1 && (n1 < 0 || n1 >= len))
5278 /* For a range we allow invalid values and return an empty
5279 * list. A list index out of range is an error. */
5280 if (!range)
5282 if (verbose)
5283 EMSGN(_(e_listidx), n1);
5284 return FAIL;
5286 n1 = len;
5288 if (range)
5290 list_T *l;
5291 listitem_T *item;
5293 if (n2 < 0)
5294 n2 = len + n2;
5295 else if (n2 >= len)
5296 n2 = len - 1;
5297 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
5298 n2 = -1;
5299 l = list_alloc();
5300 if (l == NULL)
5301 return FAIL;
5302 for (item = list_find(rettv->vval.v_list, n1);
5303 n1 <= n2; ++n1)
5305 if (list_append_tv(l, &item->li_tv) == FAIL)
5307 list_free(l, TRUE);
5308 return FAIL;
5310 item = item->li_next;
5312 clear_tv(rettv);
5313 rettv->v_type = VAR_LIST;
5314 rettv->vval.v_list = l;
5315 ++l->lv_refcount;
5317 else
5319 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
5320 clear_tv(rettv);
5321 *rettv = var1;
5323 break;
5325 case VAR_DICT:
5326 if (range)
5328 if (verbose)
5329 EMSG(_(e_dictrange));
5330 if (len == -1)
5331 clear_tv(&var1);
5332 return FAIL;
5335 dictitem_T *item;
5337 if (len == -1)
5339 key = get_tv_string(&var1);
5340 if (*key == NUL)
5342 if (verbose)
5343 EMSG(_(e_emptykey));
5344 clear_tv(&var1);
5345 return FAIL;
5349 item = dict_find(rettv->vval.v_dict, key, (int)len);
5351 if (item == NULL && verbose)
5352 EMSG2(_(e_dictkey), key);
5353 if (len == -1)
5354 clear_tv(&var1);
5355 if (item == NULL)
5356 return FAIL;
5358 copy_tv(&item->di_tv, &var1);
5359 clear_tv(rettv);
5360 *rettv = var1;
5362 break;
5366 return OK;
5370 * Get an option value.
5371 * "arg" points to the '&' or '+' before the option name.
5372 * "arg" is advanced to character after the option name.
5373 * Return OK or FAIL.
5375 static int
5376 get_option_tv(arg, rettv, evaluate)
5377 char_u **arg;
5378 typval_T *rettv; /* when NULL, only check if option exists */
5379 int evaluate;
5381 char_u *option_end;
5382 long numval;
5383 char_u *stringval;
5384 int opt_type;
5385 int c;
5386 int working = (**arg == '+'); /* has("+option") */
5387 int ret = OK;
5388 int opt_flags;
5391 * Isolate the option name and find its value.
5393 option_end = find_option_end(arg, &opt_flags);
5394 if (option_end == NULL)
5396 if (rettv != NULL)
5397 EMSG2(_("E112: Option name missing: %s"), *arg);
5398 return FAIL;
5401 if (!evaluate)
5403 *arg = option_end;
5404 return OK;
5407 c = *option_end;
5408 *option_end = NUL;
5409 opt_type = get_option_value(*arg, &numval,
5410 rettv == NULL ? NULL : &stringval, opt_flags);
5412 if (opt_type == -3) /* invalid name */
5414 if (rettv != NULL)
5415 EMSG2(_("E113: Unknown option: %s"), *arg);
5416 ret = FAIL;
5418 else if (rettv != NULL)
5420 if (opt_type == -2) /* hidden string option */
5422 rettv->v_type = VAR_STRING;
5423 rettv->vval.v_string = NULL;
5425 else if (opt_type == -1) /* hidden number option */
5427 rettv->v_type = VAR_NUMBER;
5428 rettv->vval.v_number = 0;
5430 else if (opt_type == 1) /* number option */
5432 rettv->v_type = VAR_NUMBER;
5433 rettv->vval.v_number = numval;
5435 else /* string option */
5437 rettv->v_type = VAR_STRING;
5438 rettv->vval.v_string = stringval;
5441 else if (working && (opt_type == -2 || opt_type == -1))
5442 ret = FAIL;
5444 *option_end = c; /* put back for error messages */
5445 *arg = option_end;
5447 return ret;
5451 * Allocate a variable for a string constant.
5452 * Return OK or FAIL.
5454 static int
5455 get_string_tv(arg, rettv, evaluate)
5456 char_u **arg;
5457 typval_T *rettv;
5458 int evaluate;
5460 char_u *p;
5461 char_u *name;
5462 int extra = 0;
5465 * Find the end of the string, skipping backslashed characters.
5467 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5469 if (*p == '\\' && p[1] != NUL)
5471 ++p;
5472 /* A "\<x>" form occupies at least 4 characters, and produces up
5473 * to 6 characters: reserve space for 2 extra */
5474 if (*p == '<')
5475 extra += 2;
5479 if (*p != '"')
5481 EMSG2(_("E114: Missing quote: %s"), *arg);
5482 return FAIL;
5485 /* If only parsing, set *arg and return here */
5486 if (!evaluate)
5488 *arg = p + 1;
5489 return OK;
5493 * Copy the string into allocated memory, handling backslashed
5494 * characters.
5496 name = alloc((unsigned)(p - *arg + extra));
5497 if (name == NULL)
5498 return FAIL;
5499 rettv->v_type = VAR_STRING;
5500 rettv->vval.v_string = name;
5502 for (p = *arg + 1; *p != NUL && *p != '"'; )
5504 if (*p == '\\')
5506 switch (*++p)
5508 case 'b': *name++ = BS; ++p; break;
5509 case 'e': *name++ = ESC; ++p; break;
5510 case 'f': *name++ = FF; ++p; break;
5511 case 'n': *name++ = NL; ++p; break;
5512 case 'r': *name++ = CAR; ++p; break;
5513 case 't': *name++ = TAB; ++p; break;
5515 case 'X': /* hex: "\x1", "\x12" */
5516 case 'x':
5517 case 'u': /* Unicode: "\u0023" */
5518 case 'U':
5519 if (vim_isxdigit(p[1]))
5521 int n, nr;
5522 int c = toupper(*p);
5524 if (c == 'X')
5525 n = 2;
5526 else
5527 n = 4;
5528 nr = 0;
5529 while (--n >= 0 && vim_isxdigit(p[1]))
5531 ++p;
5532 nr = (nr << 4) + hex2nr(*p);
5534 ++p;
5535 #ifdef FEAT_MBYTE
5536 /* For "\u" store the number according to
5537 * 'encoding'. */
5538 if (c != 'X')
5539 name += (*mb_char2bytes)(nr, name);
5540 else
5541 #endif
5542 *name++ = nr;
5544 break;
5546 /* octal: "\1", "\12", "\123" */
5547 case '0':
5548 case '1':
5549 case '2':
5550 case '3':
5551 case '4':
5552 case '5':
5553 case '6':
5554 case '7': *name = *p++ - '0';
5555 if (*p >= '0' && *p <= '7')
5557 *name = (*name << 3) + *p++ - '0';
5558 if (*p >= '0' && *p <= '7')
5559 *name = (*name << 3) + *p++ - '0';
5561 ++name;
5562 break;
5564 /* Special key, e.g.: "\<C-W>" */
5565 case '<': extra = trans_special(&p, name, TRUE);
5566 if (extra != 0)
5568 name += extra;
5569 break;
5571 /* FALLTHROUGH */
5573 default: MB_COPY_CHAR(p, name);
5574 break;
5577 else
5578 MB_COPY_CHAR(p, name);
5581 *name = NUL;
5582 *arg = p + 1;
5584 return OK;
5588 * Allocate a variable for a 'str''ing' constant.
5589 * Return OK or FAIL.
5591 static int
5592 get_lit_string_tv(arg, rettv, evaluate)
5593 char_u **arg;
5594 typval_T *rettv;
5595 int evaluate;
5597 char_u *p;
5598 char_u *str;
5599 int reduce = 0;
5602 * Find the end of the string, skipping ''.
5604 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5606 if (*p == '\'')
5608 if (p[1] != '\'')
5609 break;
5610 ++reduce;
5611 ++p;
5615 if (*p != '\'')
5617 EMSG2(_("E115: Missing quote: %s"), *arg);
5618 return FAIL;
5621 /* If only parsing return after setting "*arg" */
5622 if (!evaluate)
5624 *arg = p + 1;
5625 return OK;
5629 * Copy the string into allocated memory, handling '' to ' reduction.
5631 str = alloc((unsigned)((p - *arg) - reduce));
5632 if (str == NULL)
5633 return FAIL;
5634 rettv->v_type = VAR_STRING;
5635 rettv->vval.v_string = str;
5637 for (p = *arg + 1; *p != NUL; )
5639 if (*p == '\'')
5641 if (p[1] != '\'')
5642 break;
5643 ++p;
5645 MB_COPY_CHAR(p, str);
5647 *str = NUL;
5648 *arg = p + 1;
5650 return OK;
5654 * Allocate a variable for a List and fill it from "*arg".
5655 * Return OK or FAIL.
5657 static int
5658 get_list_tv(arg, rettv, evaluate)
5659 char_u **arg;
5660 typval_T *rettv;
5661 int evaluate;
5663 list_T *l = NULL;
5664 typval_T tv;
5665 listitem_T *item;
5667 if (evaluate)
5669 l = list_alloc();
5670 if (l == NULL)
5671 return FAIL;
5674 *arg = skipwhite(*arg + 1);
5675 while (**arg != ']' && **arg != NUL)
5677 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5678 goto failret;
5679 if (evaluate)
5681 item = listitem_alloc();
5682 if (item != NULL)
5684 item->li_tv = tv;
5685 item->li_tv.v_lock = 0;
5686 list_append(l, item);
5688 else
5689 clear_tv(&tv);
5692 if (**arg == ']')
5693 break;
5694 if (**arg != ',')
5696 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5697 goto failret;
5699 *arg = skipwhite(*arg + 1);
5702 if (**arg != ']')
5704 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5705 failret:
5706 if (evaluate)
5707 list_free(l, TRUE);
5708 return FAIL;
5711 *arg = skipwhite(*arg + 1);
5712 if (evaluate)
5714 rettv->v_type = VAR_LIST;
5715 rettv->vval.v_list = l;
5716 ++l->lv_refcount;
5719 return OK;
5723 * Allocate an empty header for a list.
5724 * Caller should take care of the reference count.
5726 list_T *
5727 list_alloc()
5729 list_T *l;
5731 l = (list_T *)alloc_clear(sizeof(list_T));
5732 if (l != NULL)
5734 /* Prepend the list to the list of lists for garbage collection. */
5735 if (first_list != NULL)
5736 first_list->lv_used_prev = l;
5737 l->lv_used_prev = NULL;
5738 l->lv_used_next = first_list;
5739 first_list = l;
5741 return l;
5745 * Allocate an empty list for a return value.
5746 * Returns OK or FAIL.
5748 static int
5749 rettv_list_alloc(rettv)
5750 typval_T *rettv;
5752 list_T *l = list_alloc();
5754 if (l == NULL)
5755 return FAIL;
5757 rettv->vval.v_list = l;
5758 rettv->v_type = VAR_LIST;
5759 ++l->lv_refcount;
5760 return OK;
5764 * Unreference a list: decrement the reference count and free it when it
5765 * becomes zero.
5767 void
5768 list_unref(l)
5769 list_T *l;
5771 if (l != NULL && --l->lv_refcount <= 0)
5772 list_free(l, TRUE);
5776 * Free a list, including all items it points to.
5777 * Ignores the reference count.
5779 void
5780 list_free(l, recurse)
5781 list_T *l;
5782 int recurse; /* Free Lists and Dictionaries recursively. */
5784 listitem_T *item;
5786 /* Remove the list from the list of lists for garbage collection. */
5787 if (l->lv_used_prev == NULL)
5788 first_list = l->lv_used_next;
5789 else
5790 l->lv_used_prev->lv_used_next = l->lv_used_next;
5791 if (l->lv_used_next != NULL)
5792 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5794 for (item = l->lv_first; item != NULL; item = l->lv_first)
5796 /* Remove the item before deleting it. */
5797 l->lv_first = item->li_next;
5798 if (recurse || (item->li_tv.v_type != VAR_LIST
5799 && item->li_tv.v_type != VAR_DICT))
5800 clear_tv(&item->li_tv);
5801 vim_free(item);
5803 vim_free(l);
5807 * Allocate a list item.
5809 static listitem_T *
5810 listitem_alloc()
5812 return (listitem_T *)alloc(sizeof(listitem_T));
5816 * Free a list item. Also clears the value. Does not notify watchers.
5818 static void
5819 listitem_free(item)
5820 listitem_T *item;
5822 clear_tv(&item->li_tv);
5823 vim_free(item);
5827 * Remove a list item from a List and free it. Also clears the value.
5829 static void
5830 listitem_remove(l, item)
5831 list_T *l;
5832 listitem_T *item;
5834 list_remove(l, item, item);
5835 listitem_free(item);
5839 * Get the number of items in a list.
5841 static long
5842 list_len(l)
5843 list_T *l;
5845 if (l == NULL)
5846 return 0L;
5847 return l->lv_len;
5851 * Return TRUE when two lists have exactly the same values.
5853 static int
5854 list_equal(l1, l2, ic)
5855 list_T *l1;
5856 list_T *l2;
5857 int ic; /* ignore case for strings */
5859 listitem_T *item1, *item2;
5861 if (l1 == NULL || l2 == NULL)
5862 return FALSE;
5863 if (l1 == l2)
5864 return TRUE;
5865 if (list_len(l1) != list_len(l2))
5866 return FALSE;
5868 for (item1 = l1->lv_first, item2 = l2->lv_first;
5869 item1 != NULL && item2 != NULL;
5870 item1 = item1->li_next, item2 = item2->li_next)
5871 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5872 return FALSE;
5873 return item1 == NULL && item2 == NULL;
5876 #if defined(FEAT_RUBY) || defined(FEAT_PYTHON) || defined(FEAT_MZSCHEME) \
5877 || defined(PROTO)
5879 * Return the dictitem that an entry in a hashtable points to.
5881 dictitem_T *
5882 dict_lookup(hi)
5883 hashitem_T *hi;
5885 return HI2DI(hi);
5887 #endif
5890 * Return TRUE when two dictionaries have exactly the same key/values.
5892 static int
5893 dict_equal(d1, d2, ic)
5894 dict_T *d1;
5895 dict_T *d2;
5896 int ic; /* ignore case for strings */
5898 hashitem_T *hi;
5899 dictitem_T *item2;
5900 int todo;
5902 if (d1 == NULL || d2 == NULL)
5903 return FALSE;
5904 if (d1 == d2)
5905 return TRUE;
5906 if (dict_len(d1) != dict_len(d2))
5907 return FALSE;
5909 todo = (int)d1->dv_hashtab.ht_used;
5910 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5912 if (!HASHITEM_EMPTY(hi))
5914 item2 = dict_find(d2, hi->hi_key, -1);
5915 if (item2 == NULL)
5916 return FALSE;
5917 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5918 return FALSE;
5919 --todo;
5922 return TRUE;
5926 * Return TRUE if "tv1" and "tv2" have the same value.
5927 * Compares the items just like "==" would compare them, but strings and
5928 * numbers are different. Floats and numbers are also different.
5930 static int
5931 tv_equal(tv1, tv2, ic)
5932 typval_T *tv1;
5933 typval_T *tv2;
5934 int ic; /* ignore case */
5936 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5937 char_u *s1, *s2;
5938 static int recursive = 0; /* cach recursive loops */
5939 int r;
5941 if (tv1->v_type != tv2->v_type)
5942 return FALSE;
5943 /* Catch lists and dicts that have an endless loop by limiting
5944 * recursiveness to 1000. We guess they are equal then. */
5945 if (recursive >= 1000)
5946 return TRUE;
5948 switch (tv1->v_type)
5950 case VAR_LIST:
5951 ++recursive;
5952 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5953 --recursive;
5954 return r;
5956 case VAR_DICT:
5957 ++recursive;
5958 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5959 --recursive;
5960 return r;
5962 case VAR_FUNC:
5963 return (tv1->vval.v_string != NULL
5964 && tv2->vval.v_string != NULL
5965 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5967 case VAR_NUMBER:
5968 return tv1->vval.v_number == tv2->vval.v_number;
5970 #ifdef FEAT_FLOAT
5971 case VAR_FLOAT:
5972 return tv1->vval.v_float == tv2->vval.v_float;
5973 #endif
5975 case VAR_STRING:
5976 s1 = get_tv_string_buf(tv1, buf1);
5977 s2 = get_tv_string_buf(tv2, buf2);
5978 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5981 EMSG2(_(e_intern2), "tv_equal()");
5982 return TRUE;
5986 * Locate item with index "n" in list "l" and return it.
5987 * A negative index is counted from the end; -1 is the last item.
5988 * Returns NULL when "n" is out of range.
5990 static listitem_T *
5991 list_find(l, n)
5992 list_T *l;
5993 long n;
5995 listitem_T *item;
5996 long idx;
5998 if (l == NULL)
5999 return NULL;
6001 /* Negative index is relative to the end. */
6002 if (n < 0)
6003 n = l->lv_len + n;
6005 /* Check for index out of range. */
6006 if (n < 0 || n >= l->lv_len)
6007 return NULL;
6009 /* When there is a cached index may start search from there. */
6010 if (l->lv_idx_item != NULL)
6012 if (n < l->lv_idx / 2)
6014 /* closest to the start of the list */
6015 item = l->lv_first;
6016 idx = 0;
6018 else if (n > (l->lv_idx + l->lv_len) / 2)
6020 /* closest to the end of the list */
6021 item = l->lv_last;
6022 idx = l->lv_len - 1;
6024 else
6026 /* closest to the cached index */
6027 item = l->lv_idx_item;
6028 idx = l->lv_idx;
6031 else
6033 if (n < l->lv_len / 2)
6035 /* closest to the start of the list */
6036 item = l->lv_first;
6037 idx = 0;
6039 else
6041 /* closest to the end of the list */
6042 item = l->lv_last;
6043 idx = l->lv_len - 1;
6047 while (n > idx)
6049 /* search forward */
6050 item = item->li_next;
6051 ++idx;
6053 while (n < idx)
6055 /* search backward */
6056 item = item->li_prev;
6057 --idx;
6060 /* cache the used index */
6061 l->lv_idx = idx;
6062 l->lv_idx_item = item;
6064 return item;
6068 * Get list item "l[idx]" as a number.
6070 static long
6071 list_find_nr(l, idx, errorp)
6072 list_T *l;
6073 long idx;
6074 int *errorp; /* set to TRUE when something wrong */
6076 listitem_T *li;
6078 li = list_find(l, idx);
6079 if (li == NULL)
6081 if (errorp != NULL)
6082 *errorp = TRUE;
6083 return -1L;
6085 return get_tv_number_chk(&li->li_tv, errorp);
6089 * Get list item "l[idx - 1]" as a string. Returns NULL for failure.
6091 char_u *
6092 list_find_str(l, idx)
6093 list_T *l;
6094 long idx;
6096 listitem_T *li;
6098 li = list_find(l, idx - 1);
6099 if (li == NULL)
6101 EMSGN(_(e_listidx), idx);
6102 return NULL;
6104 return get_tv_string(&li->li_tv);
6108 * Locate "item" list "l" and return its index.
6109 * Returns -1 when "item" is not in the list.
6111 static long
6112 list_idx_of_item(l, item)
6113 list_T *l;
6114 listitem_T *item;
6116 long idx = 0;
6117 listitem_T *li;
6119 if (l == NULL)
6120 return -1;
6121 idx = 0;
6122 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
6123 ++idx;
6124 if (li == NULL)
6125 return -1;
6126 return idx;
6130 * Append item "item" to the end of list "l".
6132 static void
6133 list_append(l, item)
6134 list_T *l;
6135 listitem_T *item;
6137 if (l->lv_last == NULL)
6139 /* empty list */
6140 l->lv_first = item;
6141 l->lv_last = item;
6142 item->li_prev = NULL;
6144 else
6146 l->lv_last->li_next = item;
6147 item->li_prev = l->lv_last;
6148 l->lv_last = item;
6150 ++l->lv_len;
6151 item->li_next = NULL;
6155 * Append typval_T "tv" to the end of list "l".
6156 * Return FAIL when out of memory.
6159 list_append_tv(l, tv)
6160 list_T *l;
6161 typval_T *tv;
6163 listitem_T *li = listitem_alloc();
6165 if (li == NULL)
6166 return FAIL;
6167 copy_tv(tv, &li->li_tv);
6168 list_append(l, li);
6169 return OK;
6173 * Add a dictionary to a list. Used by getqflist().
6174 * Return FAIL when out of memory.
6177 list_append_dict(list, dict)
6178 list_T *list;
6179 dict_T *dict;
6181 listitem_T *li = listitem_alloc();
6183 if (li == NULL)
6184 return FAIL;
6185 li->li_tv.v_type = VAR_DICT;
6186 li->li_tv.v_lock = 0;
6187 li->li_tv.vval.v_dict = dict;
6188 list_append(list, li);
6189 ++dict->dv_refcount;
6190 return OK;
6194 * Make a copy of "str" and append it as an item to list "l".
6195 * When "len" >= 0 use "str[len]".
6196 * Returns FAIL when out of memory.
6199 list_append_string(l, str, len)
6200 list_T *l;
6201 char_u *str;
6202 int len;
6204 listitem_T *li = listitem_alloc();
6206 if (li == NULL)
6207 return FAIL;
6208 list_append(l, li);
6209 li->li_tv.v_type = VAR_STRING;
6210 li->li_tv.v_lock = 0;
6211 if (str == NULL)
6212 li->li_tv.vval.v_string = NULL;
6213 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
6214 : vim_strsave(str))) == NULL)
6215 return FAIL;
6216 return OK;
6220 * Append "n" to list "l".
6221 * Returns FAIL when out of memory.
6223 static int
6224 list_append_number(l, n)
6225 list_T *l;
6226 varnumber_T n;
6228 listitem_T *li;
6230 li = listitem_alloc();
6231 if (li == NULL)
6232 return FAIL;
6233 li->li_tv.v_type = VAR_NUMBER;
6234 li->li_tv.v_lock = 0;
6235 li->li_tv.vval.v_number = n;
6236 list_append(l, li);
6237 return OK;
6241 * Insert typval_T "tv" in list "l" before "item".
6242 * If "item" is NULL append at the end.
6243 * Return FAIL when out of memory.
6245 static int
6246 list_insert_tv(l, tv, item)
6247 list_T *l;
6248 typval_T *tv;
6249 listitem_T *item;
6251 listitem_T *ni = listitem_alloc();
6253 if (ni == NULL)
6254 return FAIL;
6255 copy_tv(tv, &ni->li_tv);
6256 if (item == NULL)
6257 /* Append new item at end of list. */
6258 list_append(l, ni);
6259 else
6261 /* Insert new item before existing item. */
6262 ni->li_prev = item->li_prev;
6263 ni->li_next = item;
6264 if (item->li_prev == NULL)
6266 l->lv_first = ni;
6267 ++l->lv_idx;
6269 else
6271 item->li_prev->li_next = ni;
6272 l->lv_idx_item = NULL;
6274 item->li_prev = ni;
6275 ++l->lv_len;
6277 return OK;
6281 * Extend "l1" with "l2".
6282 * If "bef" is NULL append at the end, otherwise insert before this item.
6283 * Returns FAIL when out of memory.
6285 static int
6286 list_extend(l1, l2, bef)
6287 list_T *l1;
6288 list_T *l2;
6289 listitem_T *bef;
6291 listitem_T *item;
6292 int todo = l2->lv_len;
6294 /* We also quit the loop when we have inserted the original item count of
6295 * the list, avoid a hang when we extend a list with itself. */
6296 for (item = l2->lv_first; item != NULL && --todo >= 0; item = item->li_next)
6297 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
6298 return FAIL;
6299 return OK;
6303 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
6304 * Return FAIL when out of memory.
6306 static int
6307 list_concat(l1, l2, tv)
6308 list_T *l1;
6309 list_T *l2;
6310 typval_T *tv;
6312 list_T *l;
6314 if (l1 == NULL || l2 == NULL)
6315 return FAIL;
6317 /* make a copy of the first list. */
6318 l = list_copy(l1, FALSE, 0);
6319 if (l == NULL)
6320 return FAIL;
6321 tv->v_type = VAR_LIST;
6322 tv->vval.v_list = l;
6324 /* append all items from the second list */
6325 return list_extend(l, l2, NULL);
6329 * Make a copy of list "orig". Shallow if "deep" is FALSE.
6330 * The refcount of the new list is set to 1.
6331 * See item_copy() for "copyID".
6332 * Returns NULL when out of memory.
6334 static list_T *
6335 list_copy(orig, deep, copyID)
6336 list_T *orig;
6337 int deep;
6338 int copyID;
6340 list_T *copy;
6341 listitem_T *item;
6342 listitem_T *ni;
6344 if (orig == NULL)
6345 return NULL;
6347 copy = list_alloc();
6348 if (copy != NULL)
6350 if (copyID != 0)
6352 /* Do this before adding the items, because one of the items may
6353 * refer back to this list. */
6354 orig->lv_copyID = copyID;
6355 orig->lv_copylist = copy;
6357 for (item = orig->lv_first; item != NULL && !got_int;
6358 item = item->li_next)
6360 ni = listitem_alloc();
6361 if (ni == NULL)
6362 break;
6363 if (deep)
6365 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
6367 vim_free(ni);
6368 break;
6371 else
6372 copy_tv(&item->li_tv, &ni->li_tv);
6373 list_append(copy, ni);
6375 ++copy->lv_refcount;
6376 if (item != NULL)
6378 list_unref(copy);
6379 copy = NULL;
6383 return copy;
6387 * Remove items "item" to "item2" from list "l".
6388 * Does not free the listitem or the value!
6390 static void
6391 list_remove(l, item, item2)
6392 list_T *l;
6393 listitem_T *item;
6394 listitem_T *item2;
6396 listitem_T *ip;
6398 /* notify watchers */
6399 for (ip = item; ip != NULL; ip = ip->li_next)
6401 --l->lv_len;
6402 list_fix_watch(l, ip);
6403 if (ip == item2)
6404 break;
6407 if (item2->li_next == NULL)
6408 l->lv_last = item->li_prev;
6409 else
6410 item2->li_next->li_prev = item->li_prev;
6411 if (item->li_prev == NULL)
6412 l->lv_first = item2->li_next;
6413 else
6414 item->li_prev->li_next = item2->li_next;
6415 l->lv_idx_item = NULL;
6419 * Return an allocated string with the string representation of a list.
6420 * May return NULL.
6422 static char_u *
6423 list2string(tv, copyID)
6424 typval_T *tv;
6425 int copyID;
6427 garray_T ga;
6429 if (tv->vval.v_list == NULL)
6430 return NULL;
6431 ga_init2(&ga, (int)sizeof(char), 80);
6432 ga_append(&ga, '[');
6433 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6435 vim_free(ga.ga_data);
6436 return NULL;
6438 ga_append(&ga, ']');
6439 ga_append(&ga, NUL);
6440 return (char_u *)ga.ga_data;
6444 * Join list "l" into a string in "*gap", using separator "sep".
6445 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6446 * Return FAIL or OK.
6448 static int
6449 list_join(gap, l, sep, echo, copyID)
6450 garray_T *gap;
6451 list_T *l;
6452 char_u *sep;
6453 int echo;
6454 int copyID;
6456 int first = TRUE;
6457 char_u *tofree;
6458 char_u numbuf[NUMBUFLEN];
6459 listitem_T *item;
6460 char_u *s;
6462 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6464 if (first)
6465 first = FALSE;
6466 else
6467 ga_concat(gap, sep);
6469 if (echo)
6470 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6471 else
6472 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6473 if (s != NULL)
6474 ga_concat(gap, s);
6475 vim_free(tofree);
6476 if (s == NULL)
6477 return FAIL;
6478 line_breakcheck();
6480 return OK;
6484 * Garbage collection for lists and dictionaries.
6486 * We use reference counts to be able to free most items right away when they
6487 * are no longer used. But for composite items it's possible that it becomes
6488 * unused while the reference count is > 0: When there is a recursive
6489 * reference. Example:
6490 * :let l = [1, 2, 3]
6491 * :let d = {9: l}
6492 * :let l[1] = d
6494 * Since this is quite unusual we handle this with garbage collection: every
6495 * once in a while find out which lists and dicts are not referenced from any
6496 * variable.
6498 * Here is a good reference text about garbage collection (refers to Python
6499 * but it applies to all reference-counting mechanisms):
6500 * http://python.ca/nas/python/gc/
6504 * Do garbage collection for lists and dicts.
6505 * Return TRUE if some memory was freed.
6508 garbage_collect()
6510 int copyID;
6511 buf_T *buf;
6512 win_T *wp;
6513 int i;
6514 funccall_T *fc, **pfc;
6515 int did_free;
6516 int did_free_funccal = FALSE;
6517 #ifdef FEAT_WINDOWS
6518 tabpage_T *tp;
6519 #endif
6521 /* Only do this once. */
6522 want_garbage_collect = FALSE;
6523 may_garbage_collect = FALSE;
6524 garbage_collect_at_exit = FALSE;
6526 /* We advance by two because we add one for items referenced through
6527 * previous_funccal. */
6528 current_copyID += COPYID_INC;
6529 copyID = current_copyID;
6532 * 1. Go through all accessible variables and mark all lists and dicts
6533 * with copyID.
6536 /* Don't free variables in the previous_funccal list unless they are only
6537 * referenced through previous_funccal. This must be first, because if
6538 * the item is referenced elsewhere the funccal must not be freed. */
6539 for (fc = previous_funccal; fc != NULL; fc = fc->caller)
6541 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1);
6542 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1);
6545 /* script-local variables */
6546 for (i = 1; i <= ga_scripts.ga_len; ++i)
6547 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6549 /* buffer-local variables */
6550 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6551 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6553 /* window-local variables */
6554 FOR_ALL_TAB_WINDOWS(tp, wp)
6555 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6557 #ifdef FEAT_WINDOWS
6558 /* tabpage-local variables */
6559 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6560 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6561 #endif
6563 /* global variables */
6564 set_ref_in_ht(&globvarht, copyID);
6566 /* function-local variables */
6567 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6569 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6570 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6573 /* v: vars */
6574 set_ref_in_ht(&vimvarht, copyID);
6577 * 2. Free lists and dictionaries that are not referenced.
6579 did_free = free_unref_items(copyID);
6582 * 3. Check if any funccal can be freed now.
6584 for (pfc = &previous_funccal; *pfc != NULL; )
6586 if (can_free_funccal(*pfc, copyID))
6588 fc = *pfc;
6589 *pfc = fc->caller;
6590 free_funccal(fc, TRUE);
6591 did_free = TRUE;
6592 did_free_funccal = TRUE;
6594 else
6595 pfc = &(*pfc)->caller;
6597 if (did_free_funccal)
6598 /* When a funccal was freed some more items might be garbage
6599 * collected, so run again. */
6600 (void)garbage_collect();
6602 return did_free;
6606 * Free lists and dictionaries that are no longer referenced.
6608 static int
6609 free_unref_items(copyID)
6610 int copyID;
6612 dict_T *dd;
6613 list_T *ll;
6614 int did_free = FALSE;
6617 * Go through the list of dicts and free items without the copyID.
6619 for (dd = first_dict; dd != NULL; )
6620 if ((dd->dv_copyID & COPYID_MASK) != (copyID & COPYID_MASK))
6622 /* Free the Dictionary and ordinary items it contains, but don't
6623 * recurse into Lists and Dictionaries, they will be in the list
6624 * of dicts or list of lists. */
6625 dict_free(dd, FALSE);
6626 did_free = TRUE;
6628 /* restart, next dict may also have been freed */
6629 dd = first_dict;
6631 else
6632 dd = dd->dv_used_next;
6635 * Go through the list of lists and free items without the copyID.
6636 * But don't free a list that has a watcher (used in a for loop), these
6637 * are not referenced anywhere.
6639 for (ll = first_list; ll != NULL; )
6640 if ((ll->lv_copyID & COPYID_MASK) != (copyID & COPYID_MASK)
6641 && ll->lv_watch == NULL)
6643 /* Free the List and ordinary items it contains, but don't recurse
6644 * into Lists and Dictionaries, they will be in the list of dicts
6645 * or list of lists. */
6646 list_free(ll, FALSE);
6647 did_free = TRUE;
6649 /* restart, next list may also have been freed */
6650 ll = first_list;
6652 else
6653 ll = ll->lv_used_next;
6655 return did_free;
6659 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6661 static void
6662 set_ref_in_ht(ht, copyID)
6663 hashtab_T *ht;
6664 int copyID;
6666 int todo;
6667 hashitem_T *hi;
6669 todo = (int)ht->ht_used;
6670 for (hi = ht->ht_array; todo > 0; ++hi)
6671 if (!HASHITEM_EMPTY(hi))
6673 --todo;
6674 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6679 * Mark all lists and dicts referenced through list "l" with "copyID".
6681 static void
6682 set_ref_in_list(l, copyID)
6683 list_T *l;
6684 int copyID;
6686 listitem_T *li;
6688 for (li = l->lv_first; li != NULL; li = li->li_next)
6689 set_ref_in_item(&li->li_tv, copyID);
6693 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6695 static void
6696 set_ref_in_item(tv, copyID)
6697 typval_T *tv;
6698 int copyID;
6700 dict_T *dd;
6701 list_T *ll;
6703 switch (tv->v_type)
6705 case VAR_DICT:
6706 dd = tv->vval.v_dict;
6707 if (dd != NULL && dd->dv_copyID != copyID)
6709 /* Didn't see this dict yet. */
6710 dd->dv_copyID = copyID;
6711 set_ref_in_ht(&dd->dv_hashtab, copyID);
6713 break;
6715 case VAR_LIST:
6716 ll = tv->vval.v_list;
6717 if (ll != NULL && ll->lv_copyID != copyID)
6719 /* Didn't see this list yet. */
6720 ll->lv_copyID = copyID;
6721 set_ref_in_list(ll, copyID);
6723 break;
6725 return;
6729 * Allocate an empty header for a dictionary.
6731 dict_T *
6732 dict_alloc()
6734 dict_T *d;
6736 d = (dict_T *)alloc(sizeof(dict_T));
6737 if (d != NULL)
6739 /* Add the list to the list of dicts for garbage collection. */
6740 if (first_dict != NULL)
6741 first_dict->dv_used_prev = d;
6742 d->dv_used_next = first_dict;
6743 d->dv_used_prev = NULL;
6744 first_dict = d;
6746 hash_init(&d->dv_hashtab);
6747 d->dv_lock = 0;
6748 d->dv_refcount = 0;
6749 d->dv_copyID = 0;
6751 return d;
6755 * Unreference a Dictionary: decrement the reference count and free it when it
6756 * becomes zero.
6758 static void
6759 dict_unref(d)
6760 dict_T *d;
6762 if (d != NULL && --d->dv_refcount <= 0)
6763 dict_free(d, TRUE);
6767 * Free a Dictionary, including all items it contains.
6768 * Ignores the reference count.
6770 static void
6771 dict_free(d, recurse)
6772 dict_T *d;
6773 int recurse; /* Free Lists and Dictionaries recursively. */
6775 int todo;
6776 hashitem_T *hi;
6777 dictitem_T *di;
6779 /* Remove the dict from the list of dicts for garbage collection. */
6780 if (d->dv_used_prev == NULL)
6781 first_dict = d->dv_used_next;
6782 else
6783 d->dv_used_prev->dv_used_next = d->dv_used_next;
6784 if (d->dv_used_next != NULL)
6785 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6787 /* Lock the hashtab, we don't want it to resize while freeing items. */
6788 hash_lock(&d->dv_hashtab);
6789 todo = (int)d->dv_hashtab.ht_used;
6790 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6792 if (!HASHITEM_EMPTY(hi))
6794 /* Remove the item before deleting it, just in case there is
6795 * something recursive causing trouble. */
6796 di = HI2DI(hi);
6797 hash_remove(&d->dv_hashtab, hi);
6798 if (recurse || (di->di_tv.v_type != VAR_LIST
6799 && di->di_tv.v_type != VAR_DICT))
6800 clear_tv(&di->di_tv);
6801 vim_free(di);
6802 --todo;
6805 hash_clear(&d->dv_hashtab);
6806 vim_free(d);
6810 * Allocate a Dictionary item.
6811 * The "key" is copied to the new item.
6812 * Note that the value of the item "di_tv" still needs to be initialized!
6813 * Returns NULL when out of memory.
6815 dictitem_T *
6816 dictitem_alloc(key)
6817 char_u *key;
6819 dictitem_T *di;
6821 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6822 if (di != NULL)
6824 STRCPY(di->di_key, key);
6825 di->di_flags = 0;
6827 return di;
6831 * Make a copy of a Dictionary item.
6833 static dictitem_T *
6834 dictitem_copy(org)
6835 dictitem_T *org;
6837 dictitem_T *di;
6839 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6840 + STRLEN(org->di_key)));
6841 if (di != NULL)
6843 STRCPY(di->di_key, org->di_key);
6844 di->di_flags = 0;
6845 copy_tv(&org->di_tv, &di->di_tv);
6847 return di;
6851 * Remove item "item" from Dictionary "dict" and free it.
6853 static void
6854 dictitem_remove(dict, item)
6855 dict_T *dict;
6856 dictitem_T *item;
6858 hashitem_T *hi;
6860 hi = hash_find(&dict->dv_hashtab, item->di_key);
6861 if (HASHITEM_EMPTY(hi))
6862 EMSG2(_(e_intern2), "dictitem_remove()");
6863 else
6864 hash_remove(&dict->dv_hashtab, hi);
6865 dictitem_free(item);
6869 * Free a dict item. Also clears the value.
6871 void
6872 dictitem_free(item)
6873 dictitem_T *item;
6875 clear_tv(&item->di_tv);
6876 vim_free(item);
6880 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6881 * The refcount of the new dict is set to 1.
6882 * See item_copy() for "copyID".
6883 * Returns NULL when out of memory.
6885 static dict_T *
6886 dict_copy(orig, deep, copyID)
6887 dict_T *orig;
6888 int deep;
6889 int copyID;
6891 dict_T *copy;
6892 dictitem_T *di;
6893 int todo;
6894 hashitem_T *hi;
6896 if (orig == NULL)
6897 return NULL;
6899 copy = dict_alloc();
6900 if (copy != NULL)
6902 if (copyID != 0)
6904 orig->dv_copyID = copyID;
6905 orig->dv_copydict = copy;
6907 todo = (int)orig->dv_hashtab.ht_used;
6908 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6910 if (!HASHITEM_EMPTY(hi))
6912 --todo;
6914 di = dictitem_alloc(hi->hi_key);
6915 if (di == NULL)
6916 break;
6917 if (deep)
6919 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6920 copyID) == FAIL)
6922 vim_free(di);
6923 break;
6926 else
6927 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6928 if (dict_add(copy, di) == FAIL)
6930 dictitem_free(di);
6931 break;
6936 ++copy->dv_refcount;
6937 if (todo > 0)
6939 dict_unref(copy);
6940 copy = NULL;
6944 return copy;
6948 * Add item "item" to Dictionary "d".
6949 * Returns FAIL when out of memory and when key already existed.
6952 dict_add(d, item)
6953 dict_T *d;
6954 dictitem_T *item;
6956 return hash_add(&d->dv_hashtab, item->di_key);
6960 * Add a number or string entry to dictionary "d".
6961 * When "str" is NULL use number "nr", otherwise use "str".
6962 * Returns FAIL when out of memory and when key already exists.
6965 dict_add_nr_str(d, key, nr, str)
6966 dict_T *d;
6967 char *key;
6968 long nr;
6969 char_u *str;
6971 dictitem_T *item;
6973 item = dictitem_alloc((char_u *)key);
6974 if (item == NULL)
6975 return FAIL;
6976 item->di_tv.v_lock = 0;
6977 if (str == NULL)
6979 item->di_tv.v_type = VAR_NUMBER;
6980 item->di_tv.vval.v_number = nr;
6982 else
6984 item->di_tv.v_type = VAR_STRING;
6985 item->di_tv.vval.v_string = vim_strsave(str);
6987 if (dict_add(d, item) == FAIL)
6989 dictitem_free(item);
6990 return FAIL;
6992 return OK;
6996 * Get the number of items in a Dictionary.
6998 static long
6999 dict_len(d)
7000 dict_T *d;
7002 if (d == NULL)
7003 return 0L;
7004 return (long)d->dv_hashtab.ht_used;
7008 * Find item "key[len]" in Dictionary "d".
7009 * If "len" is negative use strlen(key).
7010 * Returns NULL when not found.
7012 static dictitem_T *
7013 dict_find(d, key, len)
7014 dict_T *d;
7015 char_u *key;
7016 int len;
7018 #define AKEYLEN 200
7019 char_u buf[AKEYLEN];
7020 char_u *akey;
7021 char_u *tofree = NULL;
7022 hashitem_T *hi;
7024 if (len < 0)
7025 akey = key;
7026 else if (len >= AKEYLEN)
7028 tofree = akey = vim_strnsave(key, len);
7029 if (akey == NULL)
7030 return NULL;
7032 else
7034 /* Avoid a malloc/free by using buf[]. */
7035 vim_strncpy(buf, key, len);
7036 akey = buf;
7039 hi = hash_find(&d->dv_hashtab, akey);
7040 vim_free(tofree);
7041 if (HASHITEM_EMPTY(hi))
7042 return NULL;
7043 return HI2DI(hi);
7047 * Get a string item from a dictionary.
7048 * When "save" is TRUE allocate memory for it.
7049 * Returns NULL if the entry doesn't exist or out of memory.
7051 char_u *
7052 get_dict_string(d, key, save)
7053 dict_T *d;
7054 char_u *key;
7055 int save;
7057 dictitem_T *di;
7058 char_u *s;
7060 di = dict_find(d, key, -1);
7061 if (di == NULL)
7062 return NULL;
7063 s = get_tv_string(&di->di_tv);
7064 if (save && s != NULL)
7065 s = vim_strsave(s);
7066 return s;
7070 * Get a number item from a dictionary.
7071 * Returns 0 if the entry doesn't exist or out of memory.
7073 long
7074 get_dict_number(d, key)
7075 dict_T *d;
7076 char_u *key;
7078 dictitem_T *di;
7080 di = dict_find(d, key, -1);
7081 if (di == NULL)
7082 return 0;
7083 return get_tv_number(&di->di_tv);
7087 * Return an allocated string with the string representation of a Dictionary.
7088 * May return NULL.
7090 static char_u *
7091 dict2string(tv, copyID)
7092 typval_T *tv;
7093 int copyID;
7095 garray_T ga;
7096 int first = TRUE;
7097 char_u *tofree;
7098 char_u numbuf[NUMBUFLEN];
7099 hashitem_T *hi;
7100 char_u *s;
7101 dict_T *d;
7102 int todo;
7104 if ((d = tv->vval.v_dict) == NULL)
7105 return NULL;
7106 ga_init2(&ga, (int)sizeof(char), 80);
7107 ga_append(&ga, '{');
7109 todo = (int)d->dv_hashtab.ht_used;
7110 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
7112 if (!HASHITEM_EMPTY(hi))
7114 --todo;
7116 if (first)
7117 first = FALSE;
7118 else
7119 ga_concat(&ga, (char_u *)", ");
7121 tofree = string_quote(hi->hi_key, FALSE);
7122 if (tofree != NULL)
7124 ga_concat(&ga, tofree);
7125 vim_free(tofree);
7127 ga_concat(&ga, (char_u *)": ");
7128 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
7129 if (s != NULL)
7130 ga_concat(&ga, s);
7131 vim_free(tofree);
7132 if (s == NULL)
7133 break;
7136 if (todo > 0)
7138 vim_free(ga.ga_data);
7139 return NULL;
7142 ga_append(&ga, '}');
7143 ga_append(&ga, NUL);
7144 return (char_u *)ga.ga_data;
7148 * Allocate a variable for a Dictionary and fill it from "*arg".
7149 * Return OK or FAIL. Returns NOTDONE for {expr}.
7151 static int
7152 get_dict_tv(arg, rettv, evaluate)
7153 char_u **arg;
7154 typval_T *rettv;
7155 int evaluate;
7157 dict_T *d = NULL;
7158 typval_T tvkey;
7159 typval_T tv;
7160 char_u *key = NULL;
7161 dictitem_T *item;
7162 char_u *start = skipwhite(*arg + 1);
7163 char_u buf[NUMBUFLEN];
7166 * First check if it's not a curly-braces thing: {expr}.
7167 * Must do this without evaluating, otherwise a function may be called
7168 * twice. Unfortunately this means we need to call eval1() twice for the
7169 * first item.
7170 * But {} is an empty Dictionary.
7172 if (*start != '}')
7174 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
7175 return FAIL;
7176 if (*start == '}')
7177 return NOTDONE;
7180 if (evaluate)
7182 d = dict_alloc();
7183 if (d == NULL)
7184 return FAIL;
7186 tvkey.v_type = VAR_UNKNOWN;
7187 tv.v_type = VAR_UNKNOWN;
7189 *arg = skipwhite(*arg + 1);
7190 while (**arg != '}' && **arg != NUL)
7192 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
7193 goto failret;
7194 if (**arg != ':')
7196 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
7197 clear_tv(&tvkey);
7198 goto failret;
7200 if (evaluate)
7202 key = get_tv_string_buf_chk(&tvkey, buf);
7203 if (key == NULL || *key == NUL)
7205 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
7206 if (key != NULL)
7207 EMSG(_(e_emptykey));
7208 clear_tv(&tvkey);
7209 goto failret;
7213 *arg = skipwhite(*arg + 1);
7214 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
7216 if (evaluate)
7217 clear_tv(&tvkey);
7218 goto failret;
7220 if (evaluate)
7222 item = dict_find(d, key, -1);
7223 if (item != NULL)
7225 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
7226 clear_tv(&tvkey);
7227 clear_tv(&tv);
7228 goto failret;
7230 item = dictitem_alloc(key);
7231 clear_tv(&tvkey);
7232 if (item != NULL)
7234 item->di_tv = tv;
7235 item->di_tv.v_lock = 0;
7236 if (dict_add(d, item) == FAIL)
7237 dictitem_free(item);
7241 if (**arg == '}')
7242 break;
7243 if (**arg != ',')
7245 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
7246 goto failret;
7248 *arg = skipwhite(*arg + 1);
7251 if (**arg != '}')
7253 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
7254 failret:
7255 if (evaluate)
7256 dict_free(d, TRUE);
7257 return FAIL;
7260 *arg = skipwhite(*arg + 1);
7261 if (evaluate)
7263 rettv->v_type = VAR_DICT;
7264 rettv->vval.v_dict = d;
7265 ++d->dv_refcount;
7268 return OK;
7272 * Return a string with the string representation of a variable.
7273 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7274 * "numbuf" is used for a number.
7275 * Does not put quotes around strings, as ":echo" displays values.
7276 * When "copyID" is not NULL replace recursive lists and dicts with "...".
7277 * May return NULL.
7279 static char_u *
7280 echo_string(tv, tofree, numbuf, copyID)
7281 typval_T *tv;
7282 char_u **tofree;
7283 char_u *numbuf;
7284 int copyID;
7286 static int recurse = 0;
7287 char_u *r = NULL;
7289 if (recurse >= DICT_MAXNEST)
7291 EMSG(_("E724: variable nested too deep for displaying"));
7292 *tofree = NULL;
7293 return NULL;
7295 ++recurse;
7297 switch (tv->v_type)
7299 case VAR_FUNC:
7300 *tofree = NULL;
7301 r = tv->vval.v_string;
7302 break;
7304 case VAR_LIST:
7305 if (tv->vval.v_list == NULL)
7307 *tofree = NULL;
7308 r = NULL;
7310 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
7312 *tofree = NULL;
7313 r = (char_u *)"[...]";
7315 else
7317 tv->vval.v_list->lv_copyID = copyID;
7318 *tofree = list2string(tv, copyID);
7319 r = *tofree;
7321 break;
7323 case VAR_DICT:
7324 if (tv->vval.v_dict == NULL)
7326 *tofree = NULL;
7327 r = NULL;
7329 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
7331 *tofree = NULL;
7332 r = (char_u *)"{...}";
7334 else
7336 tv->vval.v_dict->dv_copyID = copyID;
7337 *tofree = dict2string(tv, copyID);
7338 r = *tofree;
7340 break;
7342 case VAR_STRING:
7343 case VAR_NUMBER:
7344 *tofree = NULL;
7345 r = get_tv_string_buf(tv, numbuf);
7346 break;
7348 #ifdef FEAT_FLOAT
7349 case VAR_FLOAT:
7350 *tofree = NULL;
7351 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
7352 r = numbuf;
7353 break;
7354 #endif
7356 default:
7357 EMSG2(_(e_intern2), "echo_string()");
7358 *tofree = NULL;
7361 --recurse;
7362 return r;
7366 * Return a string with the string representation of a variable.
7367 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7368 * "numbuf" is used for a number.
7369 * Puts quotes around strings, so that they can be parsed back by eval().
7370 * May return NULL.
7372 static char_u *
7373 tv2string(tv, tofree, numbuf, copyID)
7374 typval_T *tv;
7375 char_u **tofree;
7376 char_u *numbuf;
7377 int copyID;
7379 switch (tv->v_type)
7381 case VAR_FUNC:
7382 *tofree = string_quote(tv->vval.v_string, TRUE);
7383 return *tofree;
7384 case VAR_STRING:
7385 *tofree = string_quote(tv->vval.v_string, FALSE);
7386 return *tofree;
7387 #ifdef FEAT_FLOAT
7388 case VAR_FLOAT:
7389 *tofree = NULL;
7390 vim_snprintf((char *)numbuf, NUMBUFLEN - 1, "%g", tv->vval.v_float);
7391 return numbuf;
7392 #endif
7393 case VAR_NUMBER:
7394 case VAR_LIST:
7395 case VAR_DICT:
7396 break;
7397 default:
7398 EMSG2(_(e_intern2), "tv2string()");
7400 return echo_string(tv, tofree, numbuf, copyID);
7404 * Return string "str" in ' quotes, doubling ' characters.
7405 * If "str" is NULL an empty string is assumed.
7406 * If "function" is TRUE make it function('string').
7408 static char_u *
7409 string_quote(str, function)
7410 char_u *str;
7411 int function;
7413 unsigned len;
7414 char_u *p, *r, *s;
7416 len = (function ? 13 : 3);
7417 if (str != NULL)
7419 len += (unsigned)STRLEN(str);
7420 for (p = str; *p != NUL; mb_ptr_adv(p))
7421 if (*p == '\'')
7422 ++len;
7424 s = r = alloc(len);
7425 if (r != NULL)
7427 if (function)
7429 STRCPY(r, "function('");
7430 r += 10;
7432 else
7433 *r++ = '\'';
7434 if (str != NULL)
7435 for (p = str; *p != NUL; )
7437 if (*p == '\'')
7438 *r++ = '\'';
7439 MB_COPY_CHAR(p, r);
7441 *r++ = '\'';
7442 if (function)
7443 *r++ = ')';
7444 *r++ = NUL;
7446 return s;
7449 #ifdef FEAT_FLOAT
7451 * Convert the string "text" to a floating point number.
7452 * This uses strtod(). setlocale(LC_NUMERIC, "C") has been used to make sure
7453 * this always uses a decimal point.
7454 * Returns the length of the text that was consumed.
7456 static int
7457 string2float(text, value)
7458 char_u *text;
7459 float_T *value; /* result stored here */
7461 char *s = (char *)text;
7462 float_T f;
7464 f = strtod(s, &s);
7465 *value = f;
7466 return (int)((char_u *)s - text);
7468 #endif
7471 * Get the value of an environment variable.
7472 * "arg" is pointing to the '$'. It is advanced to after the name.
7473 * If the environment variable was not set, silently assume it is empty.
7474 * Always return OK.
7476 static int
7477 get_env_tv(arg, rettv, evaluate)
7478 char_u **arg;
7479 typval_T *rettv;
7480 int evaluate;
7482 char_u *string = NULL;
7483 int len;
7484 int cc;
7485 char_u *name;
7486 int mustfree = FALSE;
7488 ++*arg;
7489 name = *arg;
7490 len = get_env_len(arg);
7491 if (evaluate)
7493 if (len != 0)
7495 cc = name[len];
7496 name[len] = NUL;
7497 /* first try vim_getenv(), fast for normal environment vars */
7498 string = vim_getenv(name, &mustfree);
7499 if (string != NULL && *string != NUL)
7501 if (!mustfree)
7502 string = vim_strsave(string);
7504 else
7506 if (mustfree)
7507 vim_free(string);
7509 /* next try expanding things like $VIM and ${HOME} */
7510 string = expand_env_save(name - 1);
7511 if (string != NULL && *string == '$')
7513 vim_free(string);
7514 string = NULL;
7517 name[len] = cc;
7519 rettv->v_type = VAR_STRING;
7520 rettv->vval.v_string = string;
7523 return OK;
7527 * Array with names and number of arguments of all internal functions
7528 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7530 static struct fst
7532 char *f_name; /* function name */
7533 char f_min_argc; /* minimal number of arguments */
7534 char f_max_argc; /* maximal number of arguments */
7535 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7536 /* implementation of function */
7537 } functions[] =
7539 #ifdef FEAT_FLOAT
7540 {"abs", 1, 1, f_abs},
7541 #endif
7542 {"add", 2, 2, f_add},
7543 {"append", 2, 2, f_append},
7544 {"argc", 0, 0, f_argc},
7545 {"argidx", 0, 0, f_argidx},
7546 {"argv", 0, 1, f_argv},
7547 #ifdef FEAT_FLOAT
7548 {"atan", 1, 1, f_atan},
7549 #endif
7550 {"browse", 4, 4, f_browse},
7551 {"browsedir", 2, 2, f_browsedir},
7552 {"bufexists", 1, 1, f_bufexists},
7553 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7554 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7555 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7556 {"buflisted", 1, 1, f_buflisted},
7557 {"bufloaded", 1, 1, f_bufloaded},
7558 {"bufname", 1, 1, f_bufname},
7559 {"bufnr", 1, 2, f_bufnr},
7560 {"bufwinnr", 1, 1, f_bufwinnr},
7561 {"byte2line", 1, 1, f_byte2line},
7562 {"byteidx", 2, 2, f_byteidx},
7563 {"call", 2, 3, f_call},
7564 #ifdef FEAT_FLOAT
7565 {"ceil", 1, 1, f_ceil},
7566 #endif
7567 {"changenr", 0, 0, f_changenr},
7568 {"char2nr", 1, 1, f_char2nr},
7569 {"cindent", 1, 1, f_cindent},
7570 {"clearmatches", 0, 0, f_clearmatches},
7571 {"col", 1, 1, f_col},
7572 #if defined(FEAT_INS_EXPAND)
7573 {"complete", 2, 2, f_complete},
7574 {"complete_add", 1, 1, f_complete_add},
7575 {"complete_check", 0, 0, f_complete_check},
7576 #endif
7577 {"confirm", 1, 4, f_confirm},
7578 {"copy", 1, 1, f_copy},
7579 #ifdef FEAT_FLOAT
7580 {"cos", 1, 1, f_cos},
7581 #endif
7582 {"count", 2, 4, f_count},
7583 {"cscope_connection",0,3, f_cscope_connection},
7584 {"cursor", 1, 3, f_cursor},
7585 {"deepcopy", 1, 2, f_deepcopy},
7586 {"delete", 1, 1, f_delete},
7587 {"did_filetype", 0, 0, f_did_filetype},
7588 {"diff_filler", 1, 1, f_diff_filler},
7589 {"diff_hlID", 2, 2, f_diff_hlID},
7590 {"empty", 1, 1, f_empty},
7591 {"escape", 2, 2, f_escape},
7592 {"eval", 1, 1, f_eval},
7593 {"eventhandler", 0, 0, f_eventhandler},
7594 {"executable", 1, 1, f_executable},
7595 {"exists", 1, 1, f_exists},
7596 {"expand", 1, 2, f_expand},
7597 {"extend", 2, 3, f_extend},
7598 {"feedkeys", 1, 2, f_feedkeys},
7599 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7600 {"filereadable", 1, 1, f_filereadable},
7601 {"filewritable", 1, 1, f_filewritable},
7602 {"filter", 2, 2, f_filter},
7603 {"finddir", 1, 3, f_finddir},
7604 {"findfile", 1, 3, f_findfile},
7605 #ifdef FEAT_FLOAT
7606 {"float2nr", 1, 1, f_float2nr},
7607 {"floor", 1, 1, f_floor},
7608 #endif
7609 {"fnameescape", 1, 1, f_fnameescape},
7610 {"fnamemodify", 2, 2, f_fnamemodify},
7611 {"foldclosed", 1, 1, f_foldclosed},
7612 {"foldclosedend", 1, 1, f_foldclosedend},
7613 {"foldlevel", 1, 1, f_foldlevel},
7614 {"foldtext", 0, 0, f_foldtext},
7615 {"foldtextresult", 1, 1, f_foldtextresult},
7616 {"foreground", 0, 0, f_foreground},
7617 {"function", 1, 1, f_function},
7618 {"garbagecollect", 0, 1, f_garbagecollect},
7619 {"get", 2, 3, f_get},
7620 {"getbufline", 2, 3, f_getbufline},
7621 {"getbufvar", 2, 2, f_getbufvar},
7622 {"getchar", 0, 1, f_getchar},
7623 {"getcharmod", 0, 0, f_getcharmod},
7624 {"getcmdline", 0, 0, f_getcmdline},
7625 {"getcmdpos", 0, 0, f_getcmdpos},
7626 {"getcmdtype", 0, 0, f_getcmdtype},
7627 {"getcwd", 0, 0, f_getcwd},
7628 {"getfontname", 0, 1, f_getfontname},
7629 {"getfperm", 1, 1, f_getfperm},
7630 {"getfsize", 1, 1, f_getfsize},
7631 {"getftime", 1, 1, f_getftime},
7632 {"getftype", 1, 1, f_getftype},
7633 {"getline", 1, 2, f_getline},
7634 {"getloclist", 1, 1, f_getqflist},
7635 {"getmatches", 0, 0, f_getmatches},
7636 {"getpid", 0, 0, f_getpid},
7637 {"getpos", 1, 1, f_getpos},
7638 {"getqflist", 0, 0, f_getqflist},
7639 {"getreg", 0, 2, f_getreg},
7640 {"getregtype", 0, 1, f_getregtype},
7641 {"gettabwinvar", 3, 3, f_gettabwinvar},
7642 {"getwinposx", 0, 0, f_getwinposx},
7643 {"getwinposy", 0, 0, f_getwinposy},
7644 {"getwinvar", 2, 2, f_getwinvar},
7645 {"glob", 1, 2, f_glob},
7646 {"globpath", 2, 3, f_globpath},
7647 {"has", 1, 1, f_has},
7648 {"has_key", 2, 2, f_has_key},
7649 {"haslocaldir", 0, 0, f_haslocaldir},
7650 {"hasmapto", 1, 3, f_hasmapto},
7651 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7652 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7653 {"histadd", 2, 2, f_histadd},
7654 {"histdel", 1, 2, f_histdel},
7655 {"histget", 1, 2, f_histget},
7656 {"histnr", 1, 1, f_histnr},
7657 {"hlID", 1, 1, f_hlID},
7658 {"hlexists", 1, 1, f_hlexists},
7659 {"hostname", 0, 0, f_hostname},
7660 {"iconv", 3, 3, f_iconv},
7661 {"indent", 1, 1, f_indent},
7662 {"index", 2, 4, f_index},
7663 {"input", 1, 3, f_input},
7664 {"inputdialog", 1, 3, f_inputdialog},
7665 {"inputlist", 1, 1, f_inputlist},
7666 {"inputrestore", 0, 0, f_inputrestore},
7667 {"inputsave", 0, 0, f_inputsave},
7668 {"inputsecret", 1, 2, f_inputsecret},
7669 {"insert", 2, 3, f_insert},
7670 {"isdirectory", 1, 1, f_isdirectory},
7671 {"islocked", 1, 1, f_islocked},
7672 {"items", 1, 1, f_items},
7673 {"join", 1, 2, f_join},
7674 {"keys", 1, 1, f_keys},
7675 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7676 {"len", 1, 1, f_len},
7677 {"libcall", 3, 3, f_libcall},
7678 {"libcallnr", 3, 3, f_libcallnr},
7679 {"line", 1, 1, f_line},
7680 {"line2byte", 1, 1, f_line2byte},
7681 {"lispindent", 1, 1, f_lispindent},
7682 {"localtime", 0, 0, f_localtime},
7683 #ifdef FEAT_FLOAT
7684 {"log10", 1, 1, f_log10},
7685 #endif
7686 {"map", 2, 2, f_map},
7687 {"maparg", 1, 3, f_maparg},
7688 {"mapcheck", 1, 3, f_mapcheck},
7689 {"match", 2, 4, f_match},
7690 {"matchadd", 2, 4, f_matchadd},
7691 {"matcharg", 1, 1, f_matcharg},
7692 {"matchdelete", 1, 1, f_matchdelete},
7693 {"matchend", 2, 4, f_matchend},
7694 {"matchlist", 2, 4, f_matchlist},
7695 {"matchstr", 2, 4, f_matchstr},
7696 {"max", 1, 1, f_max},
7697 {"migemo", 1, 1, f_migemo},
7698 {"min", 1, 1, f_min},
7699 #ifdef vim_mkdir
7700 {"mkdir", 1, 3, f_mkdir},
7701 #endif
7702 {"mode", 0, 1, f_mode},
7703 #ifdef FEAT_MZSCHEME
7704 {"mzeval", 1, 1, f_mzeval},
7705 #endif
7706 {"nextnonblank", 1, 1, f_nextnonblank},
7707 {"nr2char", 1, 1, f_nr2char},
7708 {"pathshorten", 1, 1, f_pathshorten},
7709 #ifdef FEAT_FLOAT
7710 {"pow", 2, 2, f_pow},
7711 #endif
7712 {"prevnonblank", 1, 1, f_prevnonblank},
7713 {"printf", 2, 19, f_printf},
7714 {"pumvisible", 0, 0, f_pumvisible},
7715 {"range", 1, 3, f_range},
7716 {"readfile", 1, 3, f_readfile},
7717 {"reltime", 0, 2, f_reltime},
7718 {"reltimestr", 1, 1, f_reltimestr},
7719 {"remote_expr", 2, 3, f_remote_expr},
7720 {"remote_foreground", 1, 1, f_remote_foreground},
7721 {"remote_peek", 1, 2, f_remote_peek},
7722 {"remote_read", 1, 1, f_remote_read},
7723 {"remote_send", 2, 3, f_remote_send},
7724 {"remove", 2, 3, f_remove},
7725 {"rename", 2, 2, f_rename},
7726 {"repeat", 2, 2, f_repeat},
7727 {"resolve", 1, 1, f_resolve},
7728 {"reverse", 1, 1, f_reverse},
7729 #ifdef FEAT_FLOAT
7730 {"round", 1, 1, f_round},
7731 #endif
7732 {"search", 1, 4, f_search},
7733 {"searchdecl", 1, 3, f_searchdecl},
7734 {"searchpair", 3, 7, f_searchpair},
7735 {"searchpairpos", 3, 7, f_searchpairpos},
7736 {"searchpos", 1, 4, f_searchpos},
7737 {"server2client", 2, 2, f_server2client},
7738 {"serverlist", 0, 0, f_serverlist},
7739 {"setbufvar", 3, 3, f_setbufvar},
7740 {"setcmdpos", 1, 1, f_setcmdpos},
7741 {"setline", 2, 2, f_setline},
7742 {"setloclist", 2, 3, f_setloclist},
7743 {"setmatches", 1, 1, f_setmatches},
7744 {"setpos", 2, 2, f_setpos},
7745 {"setqflist", 1, 2, f_setqflist},
7746 {"setreg", 2, 3, f_setreg},
7747 {"settabwinvar", 4, 4, f_settabwinvar},
7748 {"setwinvar", 3, 3, f_setwinvar},
7749 {"shellescape", 1, 2, f_shellescape},
7750 {"simplify", 1, 1, f_simplify},
7751 #ifdef FEAT_FLOAT
7752 {"sin", 1, 1, f_sin},
7753 #endif
7754 {"sort", 1, 2, f_sort},
7755 {"soundfold", 1, 1, f_soundfold},
7756 {"spellbadword", 0, 1, f_spellbadword},
7757 {"spellsuggest", 1, 3, f_spellsuggest},
7758 {"split", 1, 3, f_split},
7759 #ifdef FEAT_FLOAT
7760 {"sqrt", 1, 1, f_sqrt},
7761 {"str2float", 1, 1, f_str2float},
7762 #endif
7763 {"str2nr", 1, 2, f_str2nr},
7764 #ifdef HAVE_STRFTIME
7765 {"strftime", 1, 2, f_strftime},
7766 #endif
7767 {"stridx", 2, 3, f_stridx},
7768 {"string", 1, 1, f_string},
7769 {"strlen", 1, 1, f_strlen},
7770 {"strpart", 2, 3, f_strpart},
7771 {"strridx", 2, 3, f_strridx},
7772 {"strtrans", 1, 1, f_strtrans},
7773 {"submatch", 1, 1, f_submatch},
7774 {"substitute", 4, 4, f_substitute},
7775 {"synID", 3, 3, f_synID},
7776 {"synIDattr", 2, 3, f_synIDattr},
7777 {"synIDtrans", 1, 1, f_synIDtrans},
7778 {"synstack", 2, 2, f_synstack},
7779 {"system", 1, 2, f_system},
7780 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7781 {"tabpagenr", 0, 1, f_tabpagenr},
7782 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7783 {"tagfiles", 0, 0, f_tagfiles},
7784 {"taglist", 1, 1, f_taglist},
7785 {"tempname", 0, 0, f_tempname},
7786 {"test", 1, 1, f_test},
7787 {"tolower", 1, 1, f_tolower},
7788 {"toupper", 1, 1, f_toupper},
7789 {"tr", 3, 3, f_tr},
7790 #ifdef FEAT_FLOAT
7791 {"trunc", 1, 1, f_trunc},
7792 #endif
7793 {"type", 1, 1, f_type},
7794 {"values", 1, 1, f_values},
7795 {"virtcol", 1, 1, f_virtcol},
7796 {"visualmode", 0, 1, f_visualmode},
7797 {"winbufnr", 1, 1, f_winbufnr},
7798 {"wincol", 0, 0, f_wincol},
7799 {"winheight", 1, 1, f_winheight},
7800 {"winline", 0, 0, f_winline},
7801 {"winnr", 0, 1, f_winnr},
7802 {"winrestcmd", 0, 0, f_winrestcmd},
7803 {"winrestview", 1, 1, f_winrestview},
7804 {"winsaveview", 0, 0, f_winsaveview},
7805 {"winwidth", 1, 1, f_winwidth},
7806 {"writefile", 2, 3, f_writefile},
7809 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7812 * Function given to ExpandGeneric() to obtain the list of internal
7813 * or user defined function names.
7815 char_u *
7816 get_function_name(xp, idx)
7817 expand_T *xp;
7818 int idx;
7820 static int intidx = -1;
7821 char_u *name;
7823 if (idx == 0)
7824 intidx = -1;
7825 if (intidx < 0)
7827 name = get_user_func_name(xp, idx);
7828 if (name != NULL)
7829 return name;
7831 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7833 STRCPY(IObuff, functions[intidx].f_name);
7834 STRCAT(IObuff, "(");
7835 if (functions[intidx].f_max_argc == 0)
7836 STRCAT(IObuff, ")");
7837 return IObuff;
7840 return NULL;
7844 * Function given to ExpandGeneric() to obtain the list of internal or
7845 * user defined variable or function names.
7847 char_u *
7848 get_expr_name(xp, idx)
7849 expand_T *xp;
7850 int idx;
7852 static int intidx = -1;
7853 char_u *name;
7855 if (idx == 0)
7856 intidx = -1;
7857 if (intidx < 0)
7859 name = get_function_name(xp, idx);
7860 if (name != NULL)
7861 return name;
7863 return get_user_var_name(xp, ++intidx);
7866 #endif /* FEAT_CMDL_COMPL */
7869 * Find internal function in table above.
7870 * Return index, or -1 if not found
7872 static int
7873 find_internal_func(name)
7874 char_u *name; /* name of the function */
7876 int first = 0;
7877 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7878 int cmp;
7879 int x;
7882 * Find the function name in the table. Binary search.
7884 while (first <= last)
7886 x = first + ((unsigned)(last - first) >> 1);
7887 cmp = STRCMP(name, functions[x].f_name);
7888 if (cmp < 0)
7889 last = x - 1;
7890 else if (cmp > 0)
7891 first = x + 1;
7892 else
7893 return x;
7895 return -1;
7899 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7900 * name it contains, otherwise return "name".
7902 static char_u *
7903 deref_func_name(name, lenp)
7904 char_u *name;
7905 int *lenp;
7907 dictitem_T *v;
7908 int cc;
7910 cc = name[*lenp];
7911 name[*lenp] = NUL;
7912 v = find_var(name, NULL);
7913 name[*lenp] = cc;
7914 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7916 if (v->di_tv.vval.v_string == NULL)
7918 *lenp = 0;
7919 return (char_u *)""; /* just in case */
7921 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7922 return v->di_tv.vval.v_string;
7925 return name;
7929 * Allocate a variable for the result of a function.
7930 * Return OK or FAIL.
7932 static int
7933 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7934 evaluate, selfdict)
7935 char_u *name; /* name of the function */
7936 int len; /* length of "name" */
7937 typval_T *rettv;
7938 char_u **arg; /* argument, pointing to the '(' */
7939 linenr_T firstline; /* first line of range */
7940 linenr_T lastline; /* last line of range */
7941 int *doesrange; /* return: function handled range */
7942 int evaluate;
7943 dict_T *selfdict; /* Dictionary for "self" */
7945 char_u *argp;
7946 int ret = OK;
7947 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7948 int argcount = 0; /* number of arguments found */
7951 * Get the arguments.
7953 argp = *arg;
7954 while (argcount < MAX_FUNC_ARGS)
7956 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7957 if (*argp == ')' || *argp == ',' || *argp == NUL)
7958 break;
7959 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7961 ret = FAIL;
7962 break;
7964 ++argcount;
7965 if (*argp != ',')
7966 break;
7968 if (*argp == ')')
7969 ++argp;
7970 else
7971 ret = FAIL;
7973 if (ret == OK)
7974 ret = call_func(name, len, rettv, argcount, argvars,
7975 firstline, lastline, doesrange, evaluate, selfdict);
7976 else if (!aborting())
7978 if (argcount == MAX_FUNC_ARGS)
7979 emsg_funcname(N_("E740: Too many arguments for function %s"), name);
7980 else
7981 emsg_funcname(N_("E116: Invalid arguments for function %s"), name);
7984 while (--argcount >= 0)
7985 clear_tv(&argvars[argcount]);
7987 *arg = skipwhite(argp);
7988 return ret;
7993 * Call a function with its resolved parameters
7994 * Return OK when the function can't be called, FAIL otherwise.
7995 * Also returns OK when an error was encountered while executing the function.
7997 static int
7998 call_func(name, len, rettv, argcount, argvars, firstline, lastline,
7999 doesrange, evaluate, selfdict)
8000 char_u *name; /* name of the function */
8001 int len; /* length of "name" */
8002 typval_T *rettv; /* return value goes here */
8003 int argcount; /* number of "argvars" */
8004 typval_T *argvars; /* vars for arguments, must have "argcount"
8005 PLUS ONE elements! */
8006 linenr_T firstline; /* first line of range */
8007 linenr_T lastline; /* last line of range */
8008 int *doesrange; /* return: function handled range */
8009 int evaluate;
8010 dict_T *selfdict; /* Dictionary for "self" */
8012 int ret = FAIL;
8013 #define ERROR_UNKNOWN 0
8014 #define ERROR_TOOMANY 1
8015 #define ERROR_TOOFEW 2
8016 #define ERROR_SCRIPT 3
8017 #define ERROR_DICT 4
8018 #define ERROR_NONE 5
8019 #define ERROR_OTHER 6
8020 int error = ERROR_NONE;
8021 int i;
8022 int llen;
8023 ufunc_T *fp;
8024 int cc;
8025 #define FLEN_FIXED 40
8026 char_u fname_buf[FLEN_FIXED + 1];
8027 char_u *fname;
8030 * In a script change <SID>name() and s:name() to K_SNR 123_name().
8031 * Change <SNR>123_name() to K_SNR 123_name().
8032 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
8034 cc = name[len];
8035 name[len] = NUL;
8036 llen = eval_fname_script(name);
8037 if (llen > 0)
8039 fname_buf[0] = K_SPECIAL;
8040 fname_buf[1] = KS_EXTRA;
8041 fname_buf[2] = (int)KE_SNR;
8042 i = 3;
8043 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
8045 if (current_SID <= 0)
8046 error = ERROR_SCRIPT;
8047 else
8049 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
8050 i = (int)STRLEN(fname_buf);
8053 if (i + STRLEN(name + llen) < FLEN_FIXED)
8055 STRCPY(fname_buf + i, name + llen);
8056 fname = fname_buf;
8058 else
8060 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
8061 if (fname == NULL)
8062 error = ERROR_OTHER;
8063 else
8065 mch_memmove(fname, fname_buf, (size_t)i);
8066 STRCPY(fname + i, name + llen);
8070 else
8071 fname = name;
8073 *doesrange = FALSE;
8076 /* execute the function if no errors detected and executing */
8077 if (evaluate && error == ERROR_NONE)
8079 rettv->v_type = VAR_NUMBER; /* default rettv is number zero */
8080 rettv->vval.v_number = 0;
8081 error = ERROR_UNKNOWN;
8083 if (!builtin_function(fname))
8086 * User defined function.
8088 fp = find_func(fname);
8090 #ifdef FEAT_AUTOCMD
8091 /* Trigger FuncUndefined event, may load the function. */
8092 if (fp == NULL
8093 && apply_autocmds(EVENT_FUNCUNDEFINED,
8094 fname, fname, TRUE, NULL)
8095 && !aborting())
8097 /* executed an autocommand, search for the function again */
8098 fp = find_func(fname);
8100 #endif
8101 /* Try loading a package. */
8102 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
8104 /* loaded a package, search for the function again */
8105 fp = find_func(fname);
8108 if (fp != NULL)
8110 if (fp->uf_flags & FC_RANGE)
8111 *doesrange = TRUE;
8112 if (argcount < fp->uf_args.ga_len)
8113 error = ERROR_TOOFEW;
8114 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
8115 error = ERROR_TOOMANY;
8116 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
8117 error = ERROR_DICT;
8118 else
8121 * Call the user function.
8122 * Save and restore search patterns, script variables and
8123 * redo buffer.
8125 save_search_patterns();
8126 saveRedobuff();
8127 ++fp->uf_calls;
8128 call_user_func(fp, argcount, argvars, rettv,
8129 firstline, lastline,
8130 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
8131 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
8132 && fp->uf_refcount <= 0)
8133 /* Function was unreferenced while being used, free it
8134 * now. */
8135 func_free(fp);
8136 restoreRedobuff();
8137 restore_search_patterns();
8138 error = ERROR_NONE;
8142 else
8145 * Find the function name in the table, call its implementation.
8147 i = find_internal_func(fname);
8148 if (i >= 0)
8150 if (argcount < functions[i].f_min_argc)
8151 error = ERROR_TOOFEW;
8152 else if (argcount > functions[i].f_max_argc)
8153 error = ERROR_TOOMANY;
8154 else
8156 argvars[argcount].v_type = VAR_UNKNOWN;
8157 functions[i].f_func(argvars, rettv);
8158 error = ERROR_NONE;
8163 * The function call (or "FuncUndefined" autocommand sequence) might
8164 * have been aborted by an error, an interrupt, or an explicitly thrown
8165 * exception that has not been caught so far. This situation can be
8166 * tested for by calling aborting(). For an error in an internal
8167 * function or for the "E132" error in call_user_func(), however, the
8168 * throw point at which the "force_abort" flag (temporarily reset by
8169 * emsg()) is normally updated has not been reached yet. We need to
8170 * update that flag first to make aborting() reliable.
8172 update_force_abort();
8174 if (error == ERROR_NONE)
8175 ret = OK;
8178 * Report an error unless the argument evaluation or function call has been
8179 * cancelled due to an aborting error, an interrupt, or an exception.
8181 if (!aborting())
8183 switch (error)
8185 case ERROR_UNKNOWN:
8186 emsg_funcname(N_("E117: Unknown function: %s"), name);
8187 break;
8188 case ERROR_TOOMANY:
8189 emsg_funcname(e_toomanyarg, name);
8190 break;
8191 case ERROR_TOOFEW:
8192 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
8193 name);
8194 break;
8195 case ERROR_SCRIPT:
8196 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
8197 name);
8198 break;
8199 case ERROR_DICT:
8200 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
8201 name);
8202 break;
8206 name[len] = cc;
8207 if (fname != name && fname != fname_buf)
8208 vim_free(fname);
8210 return ret;
8214 * Give an error message with a function name. Handle <SNR> things.
8215 * "ermsg" is to be passed without translation, use N_() instead of _().
8217 static void
8218 emsg_funcname(ermsg, name)
8219 char *ermsg;
8220 char_u *name;
8222 char_u *p;
8224 if (*name == K_SPECIAL)
8225 p = concat_str((char_u *)"<SNR>", name + 3);
8226 else
8227 p = name;
8228 EMSG2(_(ermsg), p);
8229 if (p != name)
8230 vim_free(p);
8234 * Return TRUE for a non-zero Number and a non-empty String.
8236 static int
8237 non_zero_arg(argvars)
8238 typval_T *argvars;
8240 return ((argvars[0].v_type == VAR_NUMBER
8241 && argvars[0].vval.v_number != 0)
8242 || (argvars[0].v_type == VAR_STRING
8243 && argvars[0].vval.v_string != NULL
8244 && *argvars[0].vval.v_string != NUL));
8247 /*********************************************
8248 * Implementation of the built-in functions
8251 #ifdef FEAT_FLOAT
8253 * "abs(expr)" function
8255 static void
8256 f_abs(argvars, rettv)
8257 typval_T *argvars;
8258 typval_T *rettv;
8260 if (argvars[0].v_type == VAR_FLOAT)
8262 rettv->v_type = VAR_FLOAT;
8263 rettv->vval.v_float = fabs(argvars[0].vval.v_float);
8265 else
8267 varnumber_T n;
8268 int error = FALSE;
8270 n = get_tv_number_chk(&argvars[0], &error);
8271 if (error)
8272 rettv->vval.v_number = -1;
8273 else if (n > 0)
8274 rettv->vval.v_number = n;
8275 else
8276 rettv->vval.v_number = -n;
8279 #endif
8282 * "add(list, item)" function
8284 static void
8285 f_add(argvars, rettv)
8286 typval_T *argvars;
8287 typval_T *rettv;
8289 list_T *l;
8291 rettv->vval.v_number = 1; /* Default: Failed */
8292 if (argvars[0].v_type == VAR_LIST)
8294 if ((l = argvars[0].vval.v_list) != NULL
8295 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
8296 && list_append_tv(l, &argvars[1]) == OK)
8297 copy_tv(&argvars[0], rettv);
8299 else
8300 EMSG(_(e_listreq));
8304 * "append(lnum, string/list)" function
8306 static void
8307 f_append(argvars, rettv)
8308 typval_T *argvars;
8309 typval_T *rettv;
8311 long lnum;
8312 char_u *line;
8313 list_T *l = NULL;
8314 listitem_T *li = NULL;
8315 typval_T *tv;
8316 long added = 0;
8318 lnum = get_tv_lnum(argvars);
8319 if (lnum >= 0
8320 && lnum <= curbuf->b_ml.ml_line_count
8321 && u_save(lnum, lnum + 1) == OK)
8323 if (argvars[1].v_type == VAR_LIST)
8325 l = argvars[1].vval.v_list;
8326 if (l == NULL)
8327 return;
8328 li = l->lv_first;
8330 for (;;)
8332 if (l == NULL)
8333 tv = &argvars[1]; /* append a string */
8334 else if (li == NULL)
8335 break; /* end of list */
8336 else
8337 tv = &li->li_tv; /* append item from list */
8338 line = get_tv_string_chk(tv);
8339 if (line == NULL) /* type error */
8341 rettv->vval.v_number = 1; /* Failed */
8342 break;
8344 ml_append(lnum + added, line, (colnr_T)0, FALSE);
8345 ++added;
8346 if (l == NULL)
8347 break;
8348 li = li->li_next;
8351 appended_lines_mark(lnum, added);
8352 if (curwin->w_cursor.lnum > lnum)
8353 curwin->w_cursor.lnum += added;
8355 else
8356 rettv->vval.v_number = 1; /* Failed */
8360 * "argc()" function
8362 static void
8363 f_argc(argvars, rettv)
8364 typval_T *argvars UNUSED;
8365 typval_T *rettv;
8367 rettv->vval.v_number = ARGCOUNT;
8371 * "argidx()" function
8373 static void
8374 f_argidx(argvars, rettv)
8375 typval_T *argvars UNUSED;
8376 typval_T *rettv;
8378 rettv->vval.v_number = curwin->w_arg_idx;
8382 * "argv(nr)" function
8384 static void
8385 f_argv(argvars, rettv)
8386 typval_T *argvars;
8387 typval_T *rettv;
8389 int idx;
8391 if (argvars[0].v_type != VAR_UNKNOWN)
8393 idx = get_tv_number_chk(&argvars[0], NULL);
8394 if (idx >= 0 && idx < ARGCOUNT)
8395 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
8396 else
8397 rettv->vval.v_string = NULL;
8398 rettv->v_type = VAR_STRING;
8400 else if (rettv_list_alloc(rettv) == OK)
8401 for (idx = 0; idx < ARGCOUNT; ++idx)
8402 list_append_string(rettv->vval.v_list,
8403 alist_name(&ARGLIST[idx]), -1);
8406 #ifdef FEAT_FLOAT
8407 static int get_float_arg __ARGS((typval_T *argvars, float_T *f));
8410 * Get the float value of "argvars[0]" into "f".
8411 * Returns FAIL when the argument is not a Number or Float.
8413 static int
8414 get_float_arg(argvars, f)
8415 typval_T *argvars;
8416 float_T *f;
8418 if (argvars[0].v_type == VAR_FLOAT)
8420 *f = argvars[0].vval.v_float;
8421 return OK;
8423 if (argvars[0].v_type == VAR_NUMBER)
8425 *f = (float_T)argvars[0].vval.v_number;
8426 return OK;
8428 EMSG(_("E808: Number or Float required"));
8429 return FAIL;
8433 * "atan()" function
8435 static void
8436 f_atan(argvars, rettv)
8437 typval_T *argvars;
8438 typval_T *rettv;
8440 float_T f;
8442 rettv->v_type = VAR_FLOAT;
8443 if (get_float_arg(argvars, &f) == OK)
8444 rettv->vval.v_float = atan(f);
8445 else
8446 rettv->vval.v_float = 0.0;
8448 #endif
8451 * "browse(save, title, initdir, default)" function
8453 static void
8454 f_browse(argvars, rettv)
8455 typval_T *argvars UNUSED;
8456 typval_T *rettv;
8458 #ifdef FEAT_BROWSE
8459 int save;
8460 char_u *title;
8461 char_u *initdir;
8462 char_u *defname;
8463 char_u buf[NUMBUFLEN];
8464 char_u buf2[NUMBUFLEN];
8465 int error = FALSE;
8467 save = get_tv_number_chk(&argvars[0], &error);
8468 title = get_tv_string_chk(&argvars[1]);
8469 initdir = get_tv_string_buf_chk(&argvars[2], buf);
8470 defname = get_tv_string_buf_chk(&argvars[3], buf2);
8472 if (error || title == NULL || initdir == NULL || defname == NULL)
8473 rettv->vval.v_string = NULL;
8474 else
8475 rettv->vval.v_string =
8476 do_browse(save ? BROWSE_SAVE : 0,
8477 title, defname, NULL, initdir, NULL, curbuf);
8478 #else
8479 rettv->vval.v_string = NULL;
8480 #endif
8481 rettv->v_type = VAR_STRING;
8485 * "browsedir(title, initdir)" function
8487 static void
8488 f_browsedir(argvars, rettv)
8489 typval_T *argvars UNUSED;
8490 typval_T *rettv;
8492 #ifdef FEAT_BROWSE
8493 char_u *title;
8494 char_u *initdir;
8495 char_u buf[NUMBUFLEN];
8497 title = get_tv_string_chk(&argvars[0]);
8498 initdir = get_tv_string_buf_chk(&argvars[1], buf);
8500 if (title == NULL || initdir == NULL)
8501 rettv->vval.v_string = NULL;
8502 else
8503 rettv->vval.v_string = do_browse(BROWSE_DIR,
8504 title, NULL, NULL, initdir, NULL, curbuf);
8505 #else
8506 rettv->vval.v_string = NULL;
8507 #endif
8508 rettv->v_type = VAR_STRING;
8511 static buf_T *find_buffer __ARGS((typval_T *avar));
8514 * Find a buffer by number or exact name.
8516 static buf_T *
8517 find_buffer(avar)
8518 typval_T *avar;
8520 buf_T *buf = NULL;
8522 if (avar->v_type == VAR_NUMBER)
8523 buf = buflist_findnr((int)avar->vval.v_number);
8524 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
8526 buf = buflist_findname_exp(avar->vval.v_string);
8527 if (buf == NULL)
8529 /* No full path name match, try a match with a URL or a "nofile"
8530 * buffer, these don't use the full path. */
8531 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8532 if (buf->b_fname != NULL
8533 && (path_with_url(buf->b_fname)
8534 #ifdef FEAT_QUICKFIX
8535 || bt_nofile(buf)
8536 #endif
8538 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
8539 break;
8542 return buf;
8546 * "bufexists(expr)" function
8548 static void
8549 f_bufexists(argvars, rettv)
8550 typval_T *argvars;
8551 typval_T *rettv;
8553 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
8557 * "buflisted(expr)" function
8559 static void
8560 f_buflisted(argvars, rettv)
8561 typval_T *argvars;
8562 typval_T *rettv;
8564 buf_T *buf;
8566 buf = find_buffer(&argvars[0]);
8567 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
8571 * "bufloaded(expr)" function
8573 static void
8574 f_bufloaded(argvars, rettv)
8575 typval_T *argvars;
8576 typval_T *rettv;
8578 buf_T *buf;
8580 buf = find_buffer(&argvars[0]);
8581 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
8584 static buf_T *get_buf_tv __ARGS((typval_T *tv));
8587 * Get buffer by number or pattern.
8589 static buf_T *
8590 get_buf_tv(tv)
8591 typval_T *tv;
8593 char_u *name = tv->vval.v_string;
8594 int save_magic;
8595 char_u *save_cpo;
8596 buf_T *buf;
8598 if (tv->v_type == VAR_NUMBER)
8599 return buflist_findnr((int)tv->vval.v_number);
8600 if (tv->v_type != VAR_STRING)
8601 return NULL;
8602 if (name == NULL || *name == NUL)
8603 return curbuf;
8604 if (name[0] == '$' && name[1] == NUL)
8605 return lastbuf;
8607 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
8608 save_magic = p_magic;
8609 p_magic = TRUE;
8610 save_cpo = p_cpo;
8611 p_cpo = (char_u *)"";
8613 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8614 TRUE, FALSE));
8616 p_magic = save_magic;
8617 p_cpo = save_cpo;
8619 /* If not found, try expanding the name, like done for bufexists(). */
8620 if (buf == NULL)
8621 buf = find_buffer(tv);
8623 return buf;
8627 * "bufname(expr)" function
8629 static void
8630 f_bufname(argvars, rettv)
8631 typval_T *argvars;
8632 typval_T *rettv;
8634 buf_T *buf;
8636 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8637 ++emsg_off;
8638 buf = get_buf_tv(&argvars[0]);
8639 rettv->v_type = VAR_STRING;
8640 if (buf != NULL && buf->b_fname != NULL)
8641 rettv->vval.v_string = vim_strsave(buf->b_fname);
8642 else
8643 rettv->vval.v_string = NULL;
8644 --emsg_off;
8648 * "bufnr(expr)" function
8650 static void
8651 f_bufnr(argvars, rettv)
8652 typval_T *argvars;
8653 typval_T *rettv;
8655 buf_T *buf;
8656 int error = FALSE;
8657 char_u *name;
8659 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8660 ++emsg_off;
8661 buf = get_buf_tv(&argvars[0]);
8662 --emsg_off;
8664 /* If the buffer isn't found and the second argument is not zero create a
8665 * new buffer. */
8666 if (buf == NULL
8667 && argvars[1].v_type != VAR_UNKNOWN
8668 && get_tv_number_chk(&argvars[1], &error) != 0
8669 && !error
8670 && (name = get_tv_string_chk(&argvars[0])) != NULL
8671 && !error)
8672 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8674 if (buf != NULL)
8675 rettv->vval.v_number = buf->b_fnum;
8676 else
8677 rettv->vval.v_number = -1;
8681 * "bufwinnr(nr)" function
8683 static void
8684 f_bufwinnr(argvars, rettv)
8685 typval_T *argvars;
8686 typval_T *rettv;
8688 #ifdef FEAT_WINDOWS
8689 win_T *wp;
8690 int winnr = 0;
8691 #endif
8692 buf_T *buf;
8694 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8695 ++emsg_off;
8696 buf = get_buf_tv(&argvars[0]);
8697 #ifdef FEAT_WINDOWS
8698 for (wp = firstwin; wp; wp = wp->w_next)
8700 ++winnr;
8701 if (wp->w_buffer == buf)
8702 break;
8704 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8705 #else
8706 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8707 #endif
8708 --emsg_off;
8712 * "byte2line(byte)" function
8714 static void
8715 f_byte2line(argvars, rettv)
8716 typval_T *argvars UNUSED;
8717 typval_T *rettv;
8719 #ifndef FEAT_BYTEOFF
8720 rettv->vval.v_number = -1;
8721 #else
8722 long boff = 0;
8724 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8725 if (boff < 0)
8726 rettv->vval.v_number = -1;
8727 else
8728 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8729 (linenr_T)0, &boff);
8730 #endif
8734 * "byteidx()" function
8736 static void
8737 f_byteidx(argvars, rettv)
8738 typval_T *argvars;
8739 typval_T *rettv;
8741 #ifdef FEAT_MBYTE
8742 char_u *t;
8743 #endif
8744 char_u *str;
8745 long idx;
8747 str = get_tv_string_chk(&argvars[0]);
8748 idx = get_tv_number_chk(&argvars[1], NULL);
8749 rettv->vval.v_number = -1;
8750 if (str == NULL || idx < 0)
8751 return;
8753 #ifdef FEAT_MBYTE
8754 t = str;
8755 for ( ; idx > 0; idx--)
8757 if (*t == NUL) /* EOL reached */
8758 return;
8759 t += (*mb_ptr2len)(t);
8761 rettv->vval.v_number = (varnumber_T)(t - str);
8762 #else
8763 if ((size_t)idx <= STRLEN(str))
8764 rettv->vval.v_number = idx;
8765 #endif
8769 * "call(func, arglist)" function
8771 static void
8772 f_call(argvars, rettv)
8773 typval_T *argvars;
8774 typval_T *rettv;
8776 char_u *func;
8777 typval_T argv[MAX_FUNC_ARGS + 1];
8778 int argc = 0;
8779 listitem_T *item;
8780 int dummy;
8781 dict_T *selfdict = NULL;
8783 if (argvars[1].v_type != VAR_LIST)
8785 EMSG(_(e_listreq));
8786 return;
8788 if (argvars[1].vval.v_list == NULL)
8789 return;
8791 if (argvars[0].v_type == VAR_FUNC)
8792 func = argvars[0].vval.v_string;
8793 else
8794 func = get_tv_string(&argvars[0]);
8795 if (*func == NUL)
8796 return; /* type error or empty name */
8798 if (argvars[2].v_type != VAR_UNKNOWN)
8800 if (argvars[2].v_type != VAR_DICT)
8802 EMSG(_(e_dictreq));
8803 return;
8805 selfdict = argvars[2].vval.v_dict;
8808 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
8809 item = item->li_next)
8811 if (argc == MAX_FUNC_ARGS)
8813 EMSG(_("E699: Too many arguments"));
8814 break;
8816 /* Make a copy of each argument. This is needed to be able to set
8817 * v_lock to VAR_FIXED in the copy without changing the original list.
8819 copy_tv(&item->li_tv, &argv[argc++]);
8822 if (item == NULL)
8823 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
8824 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
8825 &dummy, TRUE, selfdict);
8827 /* Free the arguments. */
8828 while (argc > 0)
8829 clear_tv(&argv[--argc]);
8832 #ifdef FEAT_FLOAT
8834 * "ceil({float})" function
8836 static void
8837 f_ceil(argvars, rettv)
8838 typval_T *argvars;
8839 typval_T *rettv;
8841 float_T f;
8843 rettv->v_type = VAR_FLOAT;
8844 if (get_float_arg(argvars, &f) == OK)
8845 rettv->vval.v_float = ceil(f);
8846 else
8847 rettv->vval.v_float = 0.0;
8849 #endif
8852 * "changenr()" function
8854 static void
8855 f_changenr(argvars, rettv)
8856 typval_T *argvars UNUSED;
8857 typval_T *rettv;
8859 rettv->vval.v_number = curbuf->b_u_seq_cur;
8863 * "char2nr(string)" function
8865 static void
8866 f_char2nr(argvars, rettv)
8867 typval_T *argvars;
8868 typval_T *rettv;
8870 #ifdef FEAT_MBYTE
8871 if (has_mbyte)
8872 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
8873 else
8874 #endif
8875 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
8879 * "cindent(lnum)" function
8881 static void
8882 f_cindent(argvars, rettv)
8883 typval_T *argvars;
8884 typval_T *rettv;
8886 #ifdef FEAT_CINDENT
8887 pos_T pos;
8888 linenr_T lnum;
8890 pos = curwin->w_cursor;
8891 lnum = get_tv_lnum(argvars);
8892 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
8894 curwin->w_cursor.lnum = lnum;
8895 rettv->vval.v_number = get_c_indent();
8896 curwin->w_cursor = pos;
8898 else
8899 #endif
8900 rettv->vval.v_number = -1;
8904 * "clearmatches()" function
8906 static void
8907 f_clearmatches(argvars, rettv)
8908 typval_T *argvars UNUSED;
8909 typval_T *rettv UNUSED;
8911 #ifdef FEAT_SEARCH_EXTRA
8912 clear_matches(curwin);
8913 #endif
8917 * "col(string)" function
8919 static void
8920 f_col(argvars, rettv)
8921 typval_T *argvars;
8922 typval_T *rettv;
8924 colnr_T col = 0;
8925 pos_T *fp;
8926 int fnum = curbuf->b_fnum;
8928 fp = var2fpos(&argvars[0], FALSE, &fnum);
8929 if (fp != NULL && fnum == curbuf->b_fnum)
8931 if (fp->col == MAXCOL)
8933 /* '> can be MAXCOL, get the length of the line then */
8934 if (fp->lnum <= curbuf->b_ml.ml_line_count)
8935 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
8936 else
8937 col = MAXCOL;
8939 else
8941 col = fp->col + 1;
8942 #ifdef FEAT_VIRTUALEDIT
8943 /* col(".") when the cursor is on the NUL at the end of the line
8944 * because of "coladd" can be seen as an extra column. */
8945 if (virtual_active() && fp == &curwin->w_cursor)
8947 char_u *p = ml_get_cursor();
8949 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
8950 curwin->w_virtcol - curwin->w_cursor.coladd))
8952 # ifdef FEAT_MBYTE
8953 int l;
8955 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
8956 col += l;
8957 # else
8958 if (*p != NUL && p[1] == NUL)
8959 ++col;
8960 # endif
8963 #endif
8966 rettv->vval.v_number = col;
8969 #if defined(FEAT_INS_EXPAND)
8971 * "complete()" function
8973 static void
8974 f_complete(argvars, rettv)
8975 typval_T *argvars;
8976 typval_T *rettv UNUSED;
8978 int startcol;
8980 if ((State & INSERT) == 0)
8982 EMSG(_("E785: complete() can only be used in Insert mode"));
8983 return;
8986 /* Check for undo allowed here, because if something was already inserted
8987 * the line was already saved for undo and this check isn't done. */
8988 if (!undo_allowed())
8989 return;
8991 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
8993 EMSG(_(e_invarg));
8994 return;
8997 startcol = get_tv_number_chk(&argvars[0], NULL);
8998 if (startcol <= 0)
8999 return;
9001 set_completion(startcol - 1, argvars[1].vval.v_list);
9005 * "complete_add()" function
9007 static void
9008 f_complete_add(argvars, rettv)
9009 typval_T *argvars;
9010 typval_T *rettv;
9012 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
9016 * "complete_check()" function
9018 static void
9019 f_complete_check(argvars, rettv)
9020 typval_T *argvars UNUSED;
9021 typval_T *rettv;
9023 int saved = RedrawingDisabled;
9025 RedrawingDisabled = 0;
9026 ins_compl_check_keys(0);
9027 rettv->vval.v_number = compl_interrupted;
9028 RedrawingDisabled = saved;
9030 #endif
9033 * "confirm(message, buttons[, default [, type]])" function
9035 static void
9036 f_confirm(argvars, rettv)
9037 typval_T *argvars UNUSED;
9038 typval_T *rettv UNUSED;
9040 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
9041 char_u *message;
9042 char_u *buttons = NULL;
9043 char_u buf[NUMBUFLEN];
9044 char_u buf2[NUMBUFLEN];
9045 int def = 1;
9046 int type = VIM_GENERIC;
9047 char_u *typestr;
9048 int error = FALSE;
9050 message = get_tv_string_chk(&argvars[0]);
9051 if (message == NULL)
9052 error = TRUE;
9053 if (argvars[1].v_type != VAR_UNKNOWN)
9055 buttons = get_tv_string_buf_chk(&argvars[1], buf);
9056 if (buttons == NULL)
9057 error = TRUE;
9058 if (argvars[2].v_type != VAR_UNKNOWN)
9060 def = get_tv_number_chk(&argvars[2], &error);
9061 if (argvars[3].v_type != VAR_UNKNOWN)
9063 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
9064 if (typestr == NULL)
9065 error = TRUE;
9066 else
9068 switch (TOUPPER_ASC(*typestr))
9070 case 'E': type = VIM_ERROR; break;
9071 case 'Q': type = VIM_QUESTION; break;
9072 case 'I': type = VIM_INFO; break;
9073 case 'W': type = VIM_WARNING; break;
9074 case 'G': type = VIM_GENERIC; break;
9081 if (buttons == NULL || *buttons == NUL)
9082 buttons = (char_u *)_("&Ok");
9084 if (!error)
9085 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
9086 def, NULL);
9087 #endif
9091 * "copy()" function
9093 static void
9094 f_copy(argvars, rettv)
9095 typval_T *argvars;
9096 typval_T *rettv;
9098 item_copy(&argvars[0], rettv, FALSE, 0);
9101 #ifdef FEAT_FLOAT
9103 * "cos()" function
9105 static void
9106 f_cos(argvars, rettv)
9107 typval_T *argvars;
9108 typval_T *rettv;
9110 float_T f;
9112 rettv->v_type = VAR_FLOAT;
9113 if (get_float_arg(argvars, &f) == OK)
9114 rettv->vval.v_float = cos(f);
9115 else
9116 rettv->vval.v_float = 0.0;
9118 #endif
9121 * "count()" function
9123 static void
9124 f_count(argvars, rettv)
9125 typval_T *argvars;
9126 typval_T *rettv;
9128 long n = 0;
9129 int ic = FALSE;
9131 if (argvars[0].v_type == VAR_LIST)
9133 listitem_T *li;
9134 list_T *l;
9135 long idx;
9137 if ((l = argvars[0].vval.v_list) != NULL)
9139 li = l->lv_first;
9140 if (argvars[2].v_type != VAR_UNKNOWN)
9142 int error = FALSE;
9144 ic = get_tv_number_chk(&argvars[2], &error);
9145 if (argvars[3].v_type != VAR_UNKNOWN)
9147 idx = get_tv_number_chk(&argvars[3], &error);
9148 if (!error)
9150 li = list_find(l, idx);
9151 if (li == NULL)
9152 EMSGN(_(e_listidx), idx);
9155 if (error)
9156 li = NULL;
9159 for ( ; li != NULL; li = li->li_next)
9160 if (tv_equal(&li->li_tv, &argvars[1], ic))
9161 ++n;
9164 else if (argvars[0].v_type == VAR_DICT)
9166 int todo;
9167 dict_T *d;
9168 hashitem_T *hi;
9170 if ((d = argvars[0].vval.v_dict) != NULL)
9172 int error = FALSE;
9174 if (argvars[2].v_type != VAR_UNKNOWN)
9176 ic = get_tv_number_chk(&argvars[2], &error);
9177 if (argvars[3].v_type != VAR_UNKNOWN)
9178 EMSG(_(e_invarg));
9181 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
9182 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
9184 if (!HASHITEM_EMPTY(hi))
9186 --todo;
9187 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
9188 ++n;
9193 else
9194 EMSG2(_(e_listdictarg), "count()");
9195 rettv->vval.v_number = n;
9199 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
9201 * Checks the existence of a cscope connection.
9203 static void
9204 f_cscope_connection(argvars, rettv)
9205 typval_T *argvars UNUSED;
9206 typval_T *rettv UNUSED;
9208 #ifdef FEAT_CSCOPE
9209 int num = 0;
9210 char_u *dbpath = NULL;
9211 char_u *prepend = NULL;
9212 char_u buf[NUMBUFLEN];
9214 if (argvars[0].v_type != VAR_UNKNOWN
9215 && argvars[1].v_type != VAR_UNKNOWN)
9217 num = (int)get_tv_number(&argvars[0]);
9218 dbpath = get_tv_string(&argvars[1]);
9219 if (argvars[2].v_type != VAR_UNKNOWN)
9220 prepend = get_tv_string_buf(&argvars[2], buf);
9223 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
9224 #endif
9228 * "cursor(lnum, col)" function
9230 * Moves the cursor to the specified line and column.
9231 * Returns 0 when the position could be set, -1 otherwise.
9233 static void
9234 f_cursor(argvars, rettv)
9235 typval_T *argvars;
9236 typval_T *rettv;
9238 long line, col;
9239 #ifdef FEAT_VIRTUALEDIT
9240 long coladd = 0;
9241 #endif
9243 rettv->vval.v_number = -1;
9244 if (argvars[1].v_type == VAR_UNKNOWN)
9246 pos_T pos;
9248 if (list2fpos(argvars, &pos, NULL) == FAIL)
9249 return;
9250 line = pos.lnum;
9251 col = pos.col;
9252 #ifdef FEAT_VIRTUALEDIT
9253 coladd = pos.coladd;
9254 #endif
9256 else
9258 line = get_tv_lnum(argvars);
9259 col = get_tv_number_chk(&argvars[1], NULL);
9260 #ifdef FEAT_VIRTUALEDIT
9261 if (argvars[2].v_type != VAR_UNKNOWN)
9262 coladd = get_tv_number_chk(&argvars[2], NULL);
9263 #endif
9265 if (line < 0 || col < 0
9266 #ifdef FEAT_VIRTUALEDIT
9267 || coladd < 0
9268 #endif
9270 return; /* type error; errmsg already given */
9271 if (line > 0)
9272 curwin->w_cursor.lnum = line;
9273 if (col > 0)
9274 curwin->w_cursor.col = col - 1;
9275 #ifdef FEAT_VIRTUALEDIT
9276 curwin->w_cursor.coladd = coladd;
9277 #endif
9279 /* Make sure the cursor is in a valid position. */
9280 check_cursor();
9281 #ifdef FEAT_MBYTE
9282 /* Correct cursor for multi-byte character. */
9283 if (has_mbyte)
9284 mb_adjust_cursor();
9285 #endif
9287 curwin->w_set_curswant = TRUE;
9288 rettv->vval.v_number = 0;
9292 * "deepcopy()" function
9294 static void
9295 f_deepcopy(argvars, rettv)
9296 typval_T *argvars;
9297 typval_T *rettv;
9299 int noref = 0;
9301 if (argvars[1].v_type != VAR_UNKNOWN)
9302 noref = get_tv_number_chk(&argvars[1], NULL);
9303 if (noref < 0 || noref > 1)
9304 EMSG(_(e_invarg));
9305 else
9307 current_copyID += COPYID_INC;
9308 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? current_copyID : 0);
9313 * "delete()" function
9315 static void
9316 f_delete(argvars, rettv)
9317 typval_T *argvars;
9318 typval_T *rettv;
9320 if (check_restricted() || check_secure())
9321 rettv->vval.v_number = -1;
9322 else
9323 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
9327 * "did_filetype()" function
9329 static void
9330 f_did_filetype(argvars, rettv)
9331 typval_T *argvars UNUSED;
9332 typval_T *rettv UNUSED;
9334 #ifdef FEAT_AUTOCMD
9335 rettv->vval.v_number = did_filetype;
9336 #endif
9340 * "diff_filler()" function
9342 static void
9343 f_diff_filler(argvars, rettv)
9344 typval_T *argvars UNUSED;
9345 typval_T *rettv UNUSED;
9347 #ifdef FEAT_DIFF
9348 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
9349 #endif
9353 * "diff_hlID()" function
9355 static void
9356 f_diff_hlID(argvars, rettv)
9357 typval_T *argvars UNUSED;
9358 typval_T *rettv UNUSED;
9360 #ifdef FEAT_DIFF
9361 linenr_T lnum = get_tv_lnum(argvars);
9362 static linenr_T prev_lnum = 0;
9363 static int changedtick = 0;
9364 static int fnum = 0;
9365 static int change_start = 0;
9366 static int change_end = 0;
9367 static hlf_T hlID = (hlf_T)0;
9368 int filler_lines;
9369 int col;
9371 if (lnum < 0) /* ignore type error in {lnum} arg */
9372 lnum = 0;
9373 if (lnum != prev_lnum
9374 || changedtick != curbuf->b_changedtick
9375 || fnum != curbuf->b_fnum)
9377 /* New line, buffer, change: need to get the values. */
9378 filler_lines = diff_check(curwin, lnum);
9379 if (filler_lines < 0)
9381 if (filler_lines == -1)
9383 change_start = MAXCOL;
9384 change_end = -1;
9385 if (diff_find_change(curwin, lnum, &change_start, &change_end))
9386 hlID = HLF_ADD; /* added line */
9387 else
9388 hlID = HLF_CHD; /* changed line */
9390 else
9391 hlID = HLF_ADD; /* added line */
9393 else
9394 hlID = (hlf_T)0;
9395 prev_lnum = lnum;
9396 changedtick = curbuf->b_changedtick;
9397 fnum = curbuf->b_fnum;
9400 if (hlID == HLF_CHD || hlID == HLF_TXD)
9402 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
9403 if (col >= change_start && col <= change_end)
9404 hlID = HLF_TXD; /* changed text */
9405 else
9406 hlID = HLF_CHD; /* changed line */
9408 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
9409 #endif
9413 * "empty({expr})" function
9415 static void
9416 f_empty(argvars, rettv)
9417 typval_T *argvars;
9418 typval_T *rettv;
9420 int n;
9422 switch (argvars[0].v_type)
9424 case VAR_STRING:
9425 case VAR_FUNC:
9426 n = argvars[0].vval.v_string == NULL
9427 || *argvars[0].vval.v_string == NUL;
9428 break;
9429 case VAR_NUMBER:
9430 n = argvars[0].vval.v_number == 0;
9431 break;
9432 #ifdef FEAT_FLOAT
9433 case VAR_FLOAT:
9434 n = argvars[0].vval.v_float == 0.0;
9435 break;
9436 #endif
9437 case VAR_LIST:
9438 n = argvars[0].vval.v_list == NULL
9439 || argvars[0].vval.v_list->lv_first == NULL;
9440 break;
9441 case VAR_DICT:
9442 n = argvars[0].vval.v_dict == NULL
9443 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
9444 break;
9445 default:
9446 EMSG2(_(e_intern2), "f_empty()");
9447 n = 0;
9450 rettv->vval.v_number = n;
9454 * "escape({string}, {chars})" function
9456 static void
9457 f_escape(argvars, rettv)
9458 typval_T *argvars;
9459 typval_T *rettv;
9461 char_u buf[NUMBUFLEN];
9463 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
9464 get_tv_string_buf(&argvars[1], buf));
9465 rettv->v_type = VAR_STRING;
9469 * "eval()" function
9471 static void
9472 f_eval(argvars, rettv)
9473 typval_T *argvars;
9474 typval_T *rettv;
9476 char_u *s;
9478 s = get_tv_string_chk(&argvars[0]);
9479 if (s != NULL)
9480 s = skipwhite(s);
9482 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
9484 rettv->v_type = VAR_NUMBER;
9485 rettv->vval.v_number = 0;
9487 else if (*s != NUL)
9488 EMSG(_(e_trailing));
9492 * "eventhandler()" function
9494 static void
9495 f_eventhandler(argvars, rettv)
9496 typval_T *argvars UNUSED;
9497 typval_T *rettv;
9499 rettv->vval.v_number = vgetc_busy;
9503 * "executable()" function
9505 static void
9506 f_executable(argvars, rettv)
9507 typval_T *argvars;
9508 typval_T *rettv;
9510 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
9514 * "exists()" function
9516 static void
9517 f_exists(argvars, rettv)
9518 typval_T *argvars;
9519 typval_T *rettv;
9521 char_u *p;
9522 char_u *name;
9523 int n = FALSE;
9524 int len = 0;
9526 p = get_tv_string(&argvars[0]);
9527 if (*p == '$') /* environment variable */
9529 /* first try "normal" environment variables (fast) */
9530 if (mch_getenv(p + 1) != NULL)
9531 n = TRUE;
9532 else
9534 /* try expanding things like $VIM and ${HOME} */
9535 p = expand_env_save(p);
9536 if (p != NULL && *p != '$')
9537 n = TRUE;
9538 vim_free(p);
9541 else if (*p == '&' || *p == '+') /* option */
9543 n = (get_option_tv(&p, NULL, TRUE) == OK);
9544 if (*skipwhite(p) != NUL)
9545 n = FALSE; /* trailing garbage */
9547 else if (*p == '*') /* internal or user defined function */
9549 n = function_exists(p + 1);
9551 else if (*p == ':')
9553 n = cmd_exists(p + 1);
9555 else if (*p == '#')
9557 #ifdef FEAT_AUTOCMD
9558 if (p[1] == '#')
9559 n = autocmd_supported(p + 2);
9560 else
9561 n = au_exists(p + 1);
9562 #endif
9564 else /* internal variable */
9566 char_u *tofree;
9567 typval_T tv;
9569 /* get_name_len() takes care of expanding curly braces */
9570 name = p;
9571 len = get_name_len(&p, &tofree, TRUE, FALSE);
9572 if (len > 0)
9574 if (tofree != NULL)
9575 name = tofree;
9576 n = (get_var_tv(name, len, &tv, FALSE) == OK);
9577 if (n)
9579 /* handle d.key, l[idx], f(expr) */
9580 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
9581 if (n)
9582 clear_tv(&tv);
9585 if (*p != NUL)
9586 n = FALSE;
9588 vim_free(tofree);
9591 rettv->vval.v_number = n;
9595 * "expand()" function
9597 static void
9598 f_expand(argvars, rettv)
9599 typval_T *argvars;
9600 typval_T *rettv;
9602 char_u *s;
9603 int len;
9604 char_u *errormsg;
9605 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
9606 expand_T xpc;
9607 int error = FALSE;
9609 rettv->v_type = VAR_STRING;
9610 s = get_tv_string(&argvars[0]);
9611 if (*s == '%' || *s == '#' || *s == '<')
9613 ++emsg_off;
9614 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
9615 --emsg_off;
9617 else
9619 /* When the optional second argument is non-zero, don't remove matches
9620 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
9621 if (argvars[1].v_type != VAR_UNKNOWN
9622 && get_tv_number_chk(&argvars[1], &error))
9623 flags |= WILD_KEEP_ALL;
9624 if (!error)
9626 ExpandInit(&xpc);
9627 xpc.xp_context = EXPAND_FILES;
9628 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
9630 else
9631 rettv->vval.v_string = NULL;
9636 * "extend(list, list [, idx])" function
9637 * "extend(dict, dict [, action])" function
9639 static void
9640 f_extend(argvars, rettv)
9641 typval_T *argvars;
9642 typval_T *rettv;
9644 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9646 list_T *l1, *l2;
9647 listitem_T *item;
9648 long before;
9649 int error = FALSE;
9651 l1 = argvars[0].vval.v_list;
9652 l2 = argvars[1].vval.v_list;
9653 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9654 && l2 != NULL)
9656 if (argvars[2].v_type != VAR_UNKNOWN)
9658 before = get_tv_number_chk(&argvars[2], &error);
9659 if (error)
9660 return; /* type error; errmsg already given */
9662 if (before == l1->lv_len)
9663 item = NULL;
9664 else
9666 item = list_find(l1, before);
9667 if (item == NULL)
9669 EMSGN(_(e_listidx), before);
9670 return;
9674 else
9675 item = NULL;
9676 list_extend(l1, l2, item);
9678 copy_tv(&argvars[0], rettv);
9681 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9683 dict_T *d1, *d2;
9684 dictitem_T *di1;
9685 char_u *action;
9686 int i;
9687 hashitem_T *hi2;
9688 int todo;
9690 d1 = argvars[0].vval.v_dict;
9691 d2 = argvars[1].vval.v_dict;
9692 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9693 && d2 != NULL)
9695 /* Check the third argument. */
9696 if (argvars[2].v_type != VAR_UNKNOWN)
9698 static char *(av[]) = {"keep", "force", "error"};
9700 action = get_tv_string_chk(&argvars[2]);
9701 if (action == NULL)
9702 return; /* type error; errmsg already given */
9703 for (i = 0; i < 3; ++i)
9704 if (STRCMP(action, av[i]) == 0)
9705 break;
9706 if (i == 3)
9708 EMSG2(_(e_invarg2), action);
9709 return;
9712 else
9713 action = (char_u *)"force";
9715 /* Go over all entries in the second dict and add them to the
9716 * first dict. */
9717 todo = (int)d2->dv_hashtab.ht_used;
9718 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9720 if (!HASHITEM_EMPTY(hi2))
9722 --todo;
9723 di1 = dict_find(d1, hi2->hi_key, -1);
9724 if (di1 == NULL)
9726 di1 = dictitem_copy(HI2DI(hi2));
9727 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9728 dictitem_free(di1);
9730 else if (*action == 'e')
9732 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9733 break;
9735 else if (*action == 'f')
9737 clear_tv(&di1->di_tv);
9738 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9743 copy_tv(&argvars[0], rettv);
9746 else
9747 EMSG2(_(e_listdictarg), "extend()");
9751 * "feedkeys()" function
9753 static void
9754 f_feedkeys(argvars, rettv)
9755 typval_T *argvars;
9756 typval_T *rettv UNUSED;
9758 int remap = TRUE;
9759 char_u *keys, *flags;
9760 char_u nbuf[NUMBUFLEN];
9761 int typed = FALSE;
9762 char_u *keys_esc;
9764 /* This is not allowed in the sandbox. If the commands would still be
9765 * executed in the sandbox it would be OK, but it probably happens later,
9766 * when "sandbox" is no longer set. */
9767 if (check_secure())
9768 return;
9770 keys = get_tv_string(&argvars[0]);
9771 if (*keys != NUL)
9773 if (argvars[1].v_type != VAR_UNKNOWN)
9775 flags = get_tv_string_buf(&argvars[1], nbuf);
9776 for ( ; *flags != NUL; ++flags)
9778 switch (*flags)
9780 case 'n': remap = FALSE; break;
9781 case 'm': remap = TRUE; break;
9782 case 't': typed = TRUE; break;
9787 /* Need to escape K_SPECIAL and CSI before putting the string in the
9788 * typeahead buffer. */
9789 keys_esc = vim_strsave_escape_csi(keys);
9790 if (keys_esc != NULL)
9792 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
9793 typebuf.tb_len, !typed, FALSE);
9794 vim_free(keys_esc);
9795 if (vgetc_busy)
9796 typebuf_was_filled = TRUE;
9802 * "filereadable()" function
9804 static void
9805 f_filereadable(argvars, rettv)
9806 typval_T *argvars;
9807 typval_T *rettv;
9809 int fd;
9810 char_u *p;
9811 int n;
9813 #ifndef O_NONBLOCK
9814 # define O_NONBLOCK 0
9815 #endif
9816 p = get_tv_string(&argvars[0]);
9817 if (*p && !mch_isdir(p) && (fd = mch_open((char *)p,
9818 O_RDONLY | O_NONBLOCK, 0)) >= 0)
9820 n = TRUE;
9821 close(fd);
9823 else
9824 n = FALSE;
9826 rettv->vval.v_number = n;
9830 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
9831 * rights to write into.
9833 static void
9834 f_filewritable(argvars, rettv)
9835 typval_T *argvars;
9836 typval_T *rettv;
9838 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
9841 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
9843 static void
9844 findfilendir(argvars, rettv, find_what)
9845 typval_T *argvars;
9846 typval_T *rettv;
9847 int find_what;
9849 #ifdef FEAT_SEARCHPATH
9850 char_u *fname;
9851 char_u *fresult = NULL;
9852 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
9853 char_u *p;
9854 char_u pathbuf[NUMBUFLEN];
9855 int count = 1;
9856 int first = TRUE;
9857 int error = FALSE;
9858 #endif
9860 rettv->vval.v_string = NULL;
9861 rettv->v_type = VAR_STRING;
9863 #ifdef FEAT_SEARCHPATH
9864 fname = get_tv_string(&argvars[0]);
9866 if (argvars[1].v_type != VAR_UNKNOWN)
9868 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
9869 if (p == NULL)
9870 error = TRUE;
9871 else
9873 if (*p != NUL)
9874 path = p;
9876 if (argvars[2].v_type != VAR_UNKNOWN)
9877 count = get_tv_number_chk(&argvars[2], &error);
9881 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
9882 error = TRUE;
9884 if (*fname != NUL && !error)
9888 if (rettv->v_type == VAR_STRING)
9889 vim_free(fresult);
9890 fresult = find_file_in_path_option(first ? fname : NULL,
9891 first ? (int)STRLEN(fname) : 0,
9892 0, first, path,
9893 find_what,
9894 curbuf->b_ffname,
9895 find_what == FINDFILE_DIR
9896 ? (char_u *)"" : curbuf->b_p_sua);
9897 first = FALSE;
9899 if (fresult != NULL && rettv->v_type == VAR_LIST)
9900 list_append_string(rettv->vval.v_list, fresult, -1);
9902 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
9905 if (rettv->v_type == VAR_STRING)
9906 rettv->vval.v_string = fresult;
9907 #endif
9910 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
9911 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
9914 * Implementation of map() and filter().
9916 static void
9917 filter_map(argvars, rettv, map)
9918 typval_T *argvars;
9919 typval_T *rettv;
9920 int map;
9922 char_u buf[NUMBUFLEN];
9923 char_u *expr;
9924 listitem_T *li, *nli;
9925 list_T *l = NULL;
9926 dictitem_T *di;
9927 hashtab_T *ht;
9928 hashitem_T *hi;
9929 dict_T *d = NULL;
9930 typval_T save_val;
9931 typval_T save_key;
9932 int rem;
9933 int todo;
9934 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
9935 int save_did_emsg;
9936 int index = 0;
9938 if (argvars[0].v_type == VAR_LIST)
9940 if ((l = argvars[0].vval.v_list) == NULL
9941 || (map && tv_check_lock(l->lv_lock, ermsg)))
9942 return;
9944 else if (argvars[0].v_type == VAR_DICT)
9946 if ((d = argvars[0].vval.v_dict) == NULL
9947 || (map && tv_check_lock(d->dv_lock, ermsg)))
9948 return;
9950 else
9952 EMSG2(_(e_listdictarg), ermsg);
9953 return;
9956 expr = get_tv_string_buf_chk(&argvars[1], buf);
9957 /* On type errors, the preceding call has already displayed an error
9958 * message. Avoid a misleading error message for an empty string that
9959 * was not passed as argument. */
9960 if (expr != NULL)
9962 prepare_vimvar(VV_VAL, &save_val);
9963 expr = skipwhite(expr);
9965 /* We reset "did_emsg" to be able to detect whether an error
9966 * occurred during evaluation of the expression. */
9967 save_did_emsg = did_emsg;
9968 did_emsg = FALSE;
9970 prepare_vimvar(VV_KEY, &save_key);
9971 if (argvars[0].v_type == VAR_DICT)
9973 vimvars[VV_KEY].vv_type = VAR_STRING;
9975 ht = &d->dv_hashtab;
9976 hash_lock(ht);
9977 todo = (int)ht->ht_used;
9978 for (hi = ht->ht_array; todo > 0; ++hi)
9980 if (!HASHITEM_EMPTY(hi))
9982 --todo;
9983 di = HI2DI(hi);
9984 if (tv_check_lock(di->di_tv.v_lock, ermsg))
9985 break;
9986 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
9987 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
9988 || did_emsg)
9989 break;
9990 if (!map && rem)
9991 dictitem_remove(d, di);
9992 clear_tv(&vimvars[VV_KEY].vv_tv);
9995 hash_unlock(ht);
9997 else
9999 vimvars[VV_KEY].vv_type = VAR_NUMBER;
10001 for (li = l->lv_first; li != NULL; li = nli)
10003 if (tv_check_lock(li->li_tv.v_lock, ermsg))
10004 break;
10005 nli = li->li_next;
10006 vimvars[VV_KEY].vv_nr = index;
10007 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
10008 || did_emsg)
10009 break;
10010 if (!map && rem)
10011 listitem_remove(l, li);
10012 ++index;
10016 restore_vimvar(VV_KEY, &save_key);
10017 restore_vimvar(VV_VAL, &save_val);
10019 did_emsg |= save_did_emsg;
10022 copy_tv(&argvars[0], rettv);
10025 static int
10026 filter_map_one(tv, expr, map, remp)
10027 typval_T *tv;
10028 char_u *expr;
10029 int map;
10030 int *remp;
10032 typval_T rettv;
10033 char_u *s;
10034 int retval = FAIL;
10036 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
10037 s = expr;
10038 if (eval1(&s, &rettv, TRUE) == FAIL)
10039 goto theend;
10040 if (*s != NUL) /* check for trailing chars after expr */
10042 EMSG2(_(e_invexpr2), s);
10043 goto theend;
10045 if (map)
10047 /* map(): replace the list item value */
10048 clear_tv(tv);
10049 rettv.v_lock = 0;
10050 *tv = rettv;
10052 else
10054 int error = FALSE;
10056 /* filter(): when expr is zero remove the item */
10057 *remp = (get_tv_number_chk(&rettv, &error) == 0);
10058 clear_tv(&rettv);
10059 /* On type error, nothing has been removed; return FAIL to stop the
10060 * loop. The error message was given by get_tv_number_chk(). */
10061 if (error)
10062 goto theend;
10064 retval = OK;
10065 theend:
10066 clear_tv(&vimvars[VV_VAL].vv_tv);
10067 return retval;
10071 * "filter()" function
10073 static void
10074 f_filter(argvars, rettv)
10075 typval_T *argvars;
10076 typval_T *rettv;
10078 filter_map(argvars, rettv, FALSE);
10082 * "finddir({fname}[, {path}[, {count}]])" function
10084 static void
10085 f_finddir(argvars, rettv)
10086 typval_T *argvars;
10087 typval_T *rettv;
10089 findfilendir(argvars, rettv, FINDFILE_DIR);
10093 * "findfile({fname}[, {path}[, {count}]])" function
10095 static void
10096 f_findfile(argvars, rettv)
10097 typval_T *argvars;
10098 typval_T *rettv;
10100 findfilendir(argvars, rettv, FINDFILE_FILE);
10103 #ifdef FEAT_FLOAT
10105 * "float2nr({float})" function
10107 static void
10108 f_float2nr(argvars, rettv)
10109 typval_T *argvars;
10110 typval_T *rettv;
10112 float_T f;
10114 if (get_float_arg(argvars, &f) == OK)
10116 if (f < -0x7fffffff)
10117 rettv->vval.v_number = -0x7fffffff;
10118 else if (f > 0x7fffffff)
10119 rettv->vval.v_number = 0x7fffffff;
10120 else
10121 rettv->vval.v_number = (varnumber_T)f;
10126 * "floor({float})" function
10128 static void
10129 f_floor(argvars, rettv)
10130 typval_T *argvars;
10131 typval_T *rettv;
10133 float_T f;
10135 rettv->v_type = VAR_FLOAT;
10136 if (get_float_arg(argvars, &f) == OK)
10137 rettv->vval.v_float = floor(f);
10138 else
10139 rettv->vval.v_float = 0.0;
10141 #endif
10144 * "fnameescape({string})" function
10146 static void
10147 f_fnameescape(argvars, rettv)
10148 typval_T *argvars;
10149 typval_T *rettv;
10151 rettv->vval.v_string = vim_strsave_fnameescape(
10152 get_tv_string(&argvars[0]), FALSE);
10153 rettv->v_type = VAR_STRING;
10157 * "fnamemodify({fname}, {mods})" function
10159 static void
10160 f_fnamemodify(argvars, rettv)
10161 typval_T *argvars;
10162 typval_T *rettv;
10164 char_u *fname;
10165 char_u *mods;
10166 int usedlen = 0;
10167 int len;
10168 char_u *fbuf = NULL;
10169 char_u buf[NUMBUFLEN];
10171 fname = get_tv_string_chk(&argvars[0]);
10172 mods = get_tv_string_buf_chk(&argvars[1], buf);
10173 if (fname == NULL || mods == NULL)
10174 fname = NULL;
10175 else
10177 len = (int)STRLEN(fname);
10178 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
10181 rettv->v_type = VAR_STRING;
10182 if (fname == NULL)
10183 rettv->vval.v_string = NULL;
10184 else
10185 rettv->vval.v_string = vim_strnsave(fname, len);
10186 vim_free(fbuf);
10189 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
10192 * "foldclosed()" function
10194 static void
10195 foldclosed_both(argvars, rettv, end)
10196 typval_T *argvars;
10197 typval_T *rettv;
10198 int end;
10200 #ifdef FEAT_FOLDING
10201 linenr_T lnum;
10202 linenr_T first, last;
10204 lnum = get_tv_lnum(argvars);
10205 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10207 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
10209 if (end)
10210 rettv->vval.v_number = (varnumber_T)last;
10211 else
10212 rettv->vval.v_number = (varnumber_T)first;
10213 return;
10216 #endif
10217 rettv->vval.v_number = -1;
10221 * "foldclosed()" function
10223 static void
10224 f_foldclosed(argvars, rettv)
10225 typval_T *argvars;
10226 typval_T *rettv;
10228 foldclosed_both(argvars, rettv, FALSE);
10232 * "foldclosedend()" function
10234 static void
10235 f_foldclosedend(argvars, rettv)
10236 typval_T *argvars;
10237 typval_T *rettv;
10239 foldclosed_both(argvars, rettv, TRUE);
10243 * "foldlevel()" function
10245 static void
10246 f_foldlevel(argvars, rettv)
10247 typval_T *argvars;
10248 typval_T *rettv;
10250 #ifdef FEAT_FOLDING
10251 linenr_T lnum;
10253 lnum = get_tv_lnum(argvars);
10254 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10255 rettv->vval.v_number = foldLevel(lnum);
10256 #endif
10260 * "foldtext()" function
10262 static void
10263 f_foldtext(argvars, rettv)
10264 typval_T *argvars UNUSED;
10265 typval_T *rettv;
10267 #ifdef FEAT_FOLDING
10268 linenr_T lnum;
10269 char_u *s;
10270 char_u *r;
10271 int len;
10272 char *txt;
10273 #endif
10275 rettv->v_type = VAR_STRING;
10276 rettv->vval.v_string = NULL;
10277 #ifdef FEAT_FOLDING
10278 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
10279 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
10280 <= curbuf->b_ml.ml_line_count
10281 && vimvars[VV_FOLDDASHES].vv_str != NULL)
10283 /* Find first non-empty line in the fold. */
10284 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
10285 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10287 if (!linewhite(lnum))
10288 break;
10289 ++lnum;
10292 /* Find interesting text in this line. */
10293 s = skipwhite(ml_get(lnum));
10294 /* skip C comment-start */
10295 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
10297 s = skipwhite(s + 2);
10298 if (*skipwhite(s) == NUL
10299 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10301 s = skipwhite(ml_get(lnum + 1));
10302 if (*s == '*')
10303 s = skipwhite(s + 1);
10306 txt = _("+-%s%3ld lines: ");
10307 r = alloc((unsigned)(STRLEN(txt)
10308 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
10309 + 20 /* for %3ld */
10310 + STRLEN(s))); /* concatenated */
10311 if (r != NULL)
10313 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
10314 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
10315 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
10316 len = (int)STRLEN(r);
10317 STRCAT(r, s);
10318 /* remove 'foldmarker' and 'commentstring' */
10319 foldtext_cleanup(r + len);
10320 rettv->vval.v_string = r;
10323 #endif
10327 * "foldtextresult(lnum)" function
10329 static void
10330 f_foldtextresult(argvars, rettv)
10331 typval_T *argvars UNUSED;
10332 typval_T *rettv;
10334 #ifdef FEAT_FOLDING
10335 linenr_T lnum;
10336 char_u *text;
10337 char_u buf[51];
10338 foldinfo_T foldinfo;
10339 int fold_count;
10340 #endif
10342 rettv->v_type = VAR_STRING;
10343 rettv->vval.v_string = NULL;
10344 #ifdef FEAT_FOLDING
10345 lnum = get_tv_lnum(argvars);
10346 /* treat illegal types and illegal string values for {lnum} the same */
10347 if (lnum < 0)
10348 lnum = 0;
10349 fold_count = foldedCount(curwin, lnum, &foldinfo);
10350 if (fold_count > 0)
10352 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
10353 &foldinfo, buf);
10354 if (text == buf)
10355 text = vim_strsave(text);
10356 rettv->vval.v_string = text;
10358 #endif
10362 * "foreground()" function
10364 static void
10365 f_foreground(argvars, rettv)
10366 typval_T *argvars UNUSED;
10367 typval_T *rettv UNUSED;
10369 #ifdef FEAT_GUI
10370 if (gui.in_use)
10371 gui_mch_set_foreground();
10372 #else
10373 # ifdef WIN32
10374 win32_set_foreground();
10375 # endif
10376 #endif
10380 * "function()" function
10382 static void
10383 f_function(argvars, rettv)
10384 typval_T *argvars;
10385 typval_T *rettv;
10387 char_u *s;
10389 s = get_tv_string(&argvars[0]);
10390 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
10391 EMSG2(_(e_invarg2), s);
10392 /* Don't check an autoload name for existence here. */
10393 else if (vim_strchr(s, AUTOLOAD_CHAR) == NULL && !function_exists(s))
10394 EMSG2(_("E700: Unknown function: %s"), s);
10395 else
10397 rettv->vval.v_string = vim_strsave(s);
10398 rettv->v_type = VAR_FUNC;
10403 * "garbagecollect()" function
10405 static void
10406 f_garbagecollect(argvars, rettv)
10407 typval_T *argvars;
10408 typval_T *rettv UNUSED;
10410 /* This is postponed until we are back at the toplevel, because we may be
10411 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
10412 want_garbage_collect = TRUE;
10414 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
10415 garbage_collect_at_exit = TRUE;
10419 * "get()" function
10421 static void
10422 f_get(argvars, rettv)
10423 typval_T *argvars;
10424 typval_T *rettv;
10426 listitem_T *li;
10427 list_T *l;
10428 dictitem_T *di;
10429 dict_T *d;
10430 typval_T *tv = NULL;
10432 if (argvars[0].v_type == VAR_LIST)
10434 if ((l = argvars[0].vval.v_list) != NULL)
10436 int error = FALSE;
10438 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
10439 if (!error && li != NULL)
10440 tv = &li->li_tv;
10443 else if (argvars[0].v_type == VAR_DICT)
10445 if ((d = argvars[0].vval.v_dict) != NULL)
10447 di = dict_find(d, get_tv_string(&argvars[1]), -1);
10448 if (di != NULL)
10449 tv = &di->di_tv;
10452 else
10453 EMSG2(_(e_listdictarg), "get()");
10455 if (tv == NULL)
10457 if (argvars[2].v_type != VAR_UNKNOWN)
10458 copy_tv(&argvars[2], rettv);
10460 else
10461 copy_tv(tv, rettv);
10464 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
10467 * Get line or list of lines from buffer "buf" into "rettv".
10468 * Return a range (from start to end) of lines in rettv from the specified
10469 * buffer.
10470 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
10472 static void
10473 get_buffer_lines(buf, start, end, retlist, rettv)
10474 buf_T *buf;
10475 linenr_T start;
10476 linenr_T end;
10477 int retlist;
10478 typval_T *rettv;
10480 char_u *p;
10482 if (retlist && rettv_list_alloc(rettv) == FAIL)
10483 return;
10485 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
10486 return;
10488 if (!retlist)
10490 if (start >= 1 && start <= buf->b_ml.ml_line_count)
10491 p = ml_get_buf(buf, start, FALSE);
10492 else
10493 p = (char_u *)"";
10495 rettv->v_type = VAR_STRING;
10496 rettv->vval.v_string = vim_strsave(p);
10498 else
10500 if (end < start)
10501 return;
10503 if (start < 1)
10504 start = 1;
10505 if (end > buf->b_ml.ml_line_count)
10506 end = buf->b_ml.ml_line_count;
10507 while (start <= end)
10508 if (list_append_string(rettv->vval.v_list,
10509 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
10510 break;
10515 * "getbufline()" function
10517 static void
10518 f_getbufline(argvars, rettv)
10519 typval_T *argvars;
10520 typval_T *rettv;
10522 linenr_T lnum;
10523 linenr_T end;
10524 buf_T *buf;
10526 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10527 ++emsg_off;
10528 buf = get_buf_tv(&argvars[0]);
10529 --emsg_off;
10531 lnum = get_tv_lnum_buf(&argvars[1], buf);
10532 if (argvars[2].v_type == VAR_UNKNOWN)
10533 end = lnum;
10534 else
10535 end = get_tv_lnum_buf(&argvars[2], buf);
10537 get_buffer_lines(buf, lnum, end, TRUE, rettv);
10541 * "getbufvar()" function
10543 static void
10544 f_getbufvar(argvars, rettv)
10545 typval_T *argvars;
10546 typval_T *rettv;
10548 buf_T *buf;
10549 buf_T *save_curbuf;
10550 char_u *varname;
10551 dictitem_T *v;
10553 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10554 varname = get_tv_string_chk(&argvars[1]);
10555 ++emsg_off;
10556 buf = get_buf_tv(&argvars[0]);
10558 rettv->v_type = VAR_STRING;
10559 rettv->vval.v_string = NULL;
10561 if (buf != NULL && varname != NULL)
10563 /* set curbuf to be our buf, temporarily */
10564 save_curbuf = curbuf;
10565 curbuf = buf;
10567 if (*varname == '&') /* buffer-local-option */
10568 get_option_tv(&varname, rettv, TRUE);
10569 else
10571 if (*varname == NUL)
10572 /* let getbufvar({nr}, "") return the "b:" dictionary. The
10573 * scope prefix before the NUL byte is required by
10574 * find_var_in_ht(). */
10575 varname = (char_u *)"b:" + 2;
10576 /* look up the variable */
10577 v = find_var_in_ht(&curbuf->b_vars.dv_hashtab, varname, FALSE);
10578 if (v != NULL)
10579 copy_tv(&v->di_tv, rettv);
10582 /* restore previous notion of curbuf */
10583 curbuf = save_curbuf;
10586 --emsg_off;
10590 * "getchar()" function
10592 static void
10593 f_getchar(argvars, rettv)
10594 typval_T *argvars;
10595 typval_T *rettv;
10597 varnumber_T n;
10598 int error = FALSE;
10600 /* Position the cursor. Needed after a message that ends in a space. */
10601 windgoto(msg_row, msg_col);
10603 ++no_mapping;
10604 ++allow_keys;
10605 for (;;)
10607 if (argvars[0].v_type == VAR_UNKNOWN)
10608 /* getchar(): blocking wait. */
10609 n = safe_vgetc();
10610 else if (get_tv_number_chk(&argvars[0], &error) == 1)
10611 /* getchar(1): only check if char avail */
10612 n = vpeekc();
10613 else if (error || vpeekc() == NUL)
10614 /* illegal argument or getchar(0) and no char avail: return zero */
10615 n = 0;
10616 else
10617 /* getchar(0) and char avail: return char */
10618 n = safe_vgetc();
10619 if (n == K_IGNORE)
10620 continue;
10621 break;
10623 --no_mapping;
10624 --allow_keys;
10626 vimvars[VV_MOUSE_WIN].vv_nr = 0;
10627 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
10628 vimvars[VV_MOUSE_COL].vv_nr = 0;
10630 rettv->vval.v_number = n;
10631 if (IS_SPECIAL(n) || mod_mask != 0)
10633 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
10634 int i = 0;
10636 /* Turn a special key into three bytes, plus modifier. */
10637 if (mod_mask != 0)
10639 temp[i++] = K_SPECIAL;
10640 temp[i++] = KS_MODIFIER;
10641 temp[i++] = mod_mask;
10643 if (IS_SPECIAL(n))
10645 temp[i++] = K_SPECIAL;
10646 temp[i++] = K_SECOND(n);
10647 temp[i++] = K_THIRD(n);
10649 #ifdef FEAT_MBYTE
10650 else if (has_mbyte)
10651 i += (*mb_char2bytes)(n, temp + i);
10652 #endif
10653 else
10654 temp[i++] = n;
10655 temp[i++] = NUL;
10656 rettv->v_type = VAR_STRING;
10657 rettv->vval.v_string = vim_strsave(temp);
10659 #ifdef FEAT_MOUSE
10660 if (n == K_LEFTMOUSE
10661 || n == K_LEFTMOUSE_NM
10662 || n == K_LEFTDRAG
10663 || n == K_LEFTRELEASE
10664 || n == K_LEFTRELEASE_NM
10665 || n == K_MIDDLEMOUSE
10666 || n == K_MIDDLEDRAG
10667 || n == K_MIDDLERELEASE
10668 || n == K_RIGHTMOUSE
10669 || n == K_RIGHTDRAG
10670 || n == K_RIGHTRELEASE
10671 || n == K_X1MOUSE
10672 || n == K_X1DRAG
10673 || n == K_X1RELEASE
10674 || n == K_X2MOUSE
10675 || n == K_X2DRAG
10676 || n == K_X2RELEASE
10677 || n == K_MOUSEDOWN
10678 || n == K_MOUSEUP)
10680 int row = mouse_row;
10681 int col = mouse_col;
10682 win_T *win;
10683 linenr_T lnum;
10684 # ifdef FEAT_WINDOWS
10685 win_T *wp;
10686 # endif
10687 int winnr = 1;
10689 if (row >= 0 && col >= 0)
10691 /* Find the window at the mouse coordinates and compute the
10692 * text position. */
10693 win = mouse_find_win(&row, &col);
10694 (void)mouse_comp_pos(win, &row, &col, &lnum);
10695 # ifdef FEAT_WINDOWS
10696 for (wp = firstwin; wp != win; wp = wp->w_next)
10697 ++winnr;
10698 # endif
10699 vimvars[VV_MOUSE_WIN].vv_nr = winnr;
10700 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
10701 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
10704 #endif
10709 * "getcharmod()" function
10711 static void
10712 f_getcharmod(argvars, rettv)
10713 typval_T *argvars UNUSED;
10714 typval_T *rettv;
10716 rettv->vval.v_number = mod_mask;
10720 * "getcmdline()" function
10722 static void
10723 f_getcmdline(argvars, rettv)
10724 typval_T *argvars UNUSED;
10725 typval_T *rettv;
10727 rettv->v_type = VAR_STRING;
10728 rettv->vval.v_string = get_cmdline_str();
10732 * "getcmdpos()" function
10734 static void
10735 f_getcmdpos(argvars, rettv)
10736 typval_T *argvars UNUSED;
10737 typval_T *rettv;
10739 rettv->vval.v_number = get_cmdline_pos() + 1;
10743 * "getcmdtype()" function
10745 static void
10746 f_getcmdtype(argvars, rettv)
10747 typval_T *argvars UNUSED;
10748 typval_T *rettv;
10750 rettv->v_type = VAR_STRING;
10751 rettv->vval.v_string = alloc(2);
10752 if (rettv->vval.v_string != NULL)
10754 rettv->vval.v_string[0] = get_cmdline_type();
10755 rettv->vval.v_string[1] = NUL;
10760 * "getcwd()" function
10762 static void
10763 f_getcwd(argvars, rettv)
10764 typval_T *argvars UNUSED;
10765 typval_T *rettv;
10767 char_u cwd[MAXPATHL];
10769 rettv->v_type = VAR_STRING;
10770 if (mch_dirname(cwd, MAXPATHL) == FAIL)
10771 rettv->vval.v_string = NULL;
10772 else
10774 rettv->vval.v_string = vim_strsave(cwd);
10775 #ifdef BACKSLASH_IN_FILENAME
10776 if (rettv->vval.v_string != NULL)
10777 slash_adjust(rettv->vval.v_string);
10778 #endif
10783 * "getfontname()" function
10785 static void
10786 f_getfontname(argvars, rettv)
10787 typval_T *argvars UNUSED;
10788 typval_T *rettv;
10790 rettv->v_type = VAR_STRING;
10791 rettv->vval.v_string = NULL;
10792 #ifdef FEAT_GUI
10793 if (gui.in_use)
10795 GuiFont font;
10796 char_u *name = NULL;
10798 if (argvars[0].v_type == VAR_UNKNOWN)
10800 /* Get the "Normal" font. Either the name saved by
10801 * hl_set_font_name() or from the font ID. */
10802 font = gui.norm_font;
10803 name = hl_get_font_name();
10805 else
10807 name = get_tv_string(&argvars[0]);
10808 if (STRCMP(name, "*") == 0) /* don't use font dialog */
10809 return;
10810 font = gui_mch_get_font(name, FALSE);
10811 if (font == NOFONT)
10812 return; /* Invalid font name, return empty string. */
10814 rettv->vval.v_string = gui_mch_get_fontname(font, name);
10815 if (argvars[0].v_type != VAR_UNKNOWN)
10816 gui_mch_free_font(font);
10818 #endif
10822 * "getfperm({fname})" function
10824 static void
10825 f_getfperm(argvars, rettv)
10826 typval_T *argvars;
10827 typval_T *rettv;
10829 char_u *fname;
10830 struct stat st;
10831 char_u *perm = NULL;
10832 char_u flags[] = "rwx";
10833 int i;
10835 fname = get_tv_string(&argvars[0]);
10837 rettv->v_type = VAR_STRING;
10838 if (mch_stat((char *)fname, &st) >= 0)
10840 perm = vim_strsave((char_u *)"---------");
10841 if (perm != NULL)
10843 for (i = 0; i < 9; i++)
10845 if (st.st_mode & (1 << (8 - i)))
10846 perm[i] = flags[i % 3];
10850 rettv->vval.v_string = perm;
10854 * "getfsize({fname})" function
10856 static void
10857 f_getfsize(argvars, rettv)
10858 typval_T *argvars;
10859 typval_T *rettv;
10861 char_u *fname;
10862 struct stat st;
10864 fname = get_tv_string(&argvars[0]);
10866 rettv->v_type = VAR_NUMBER;
10868 if (mch_stat((char *)fname, &st) >= 0)
10870 if (mch_isdir(fname))
10871 rettv->vval.v_number = 0;
10872 else
10874 rettv->vval.v_number = (varnumber_T)st.st_size;
10876 /* non-perfect check for overflow */
10877 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
10878 rettv->vval.v_number = -2;
10881 else
10882 rettv->vval.v_number = -1;
10886 * "getftime({fname})" function
10888 static void
10889 f_getftime(argvars, rettv)
10890 typval_T *argvars;
10891 typval_T *rettv;
10893 char_u *fname;
10894 struct stat st;
10896 fname = get_tv_string(&argvars[0]);
10898 if (mch_stat((char *)fname, &st) >= 0)
10899 rettv->vval.v_number = (varnumber_T)st.st_mtime;
10900 else
10901 rettv->vval.v_number = -1;
10905 * "getftype({fname})" function
10907 static void
10908 f_getftype(argvars, rettv)
10909 typval_T *argvars;
10910 typval_T *rettv;
10912 char_u *fname;
10913 struct stat st;
10914 char_u *type = NULL;
10915 char *t;
10917 fname = get_tv_string(&argvars[0]);
10919 rettv->v_type = VAR_STRING;
10920 if (mch_lstat((char *)fname, &st) >= 0)
10922 #ifdef S_ISREG
10923 if (S_ISREG(st.st_mode))
10924 t = "file";
10925 else if (S_ISDIR(st.st_mode))
10926 t = "dir";
10927 # ifdef S_ISLNK
10928 else if (S_ISLNK(st.st_mode))
10929 t = "link";
10930 # endif
10931 # ifdef S_ISBLK
10932 else if (S_ISBLK(st.st_mode))
10933 t = "bdev";
10934 # endif
10935 # ifdef S_ISCHR
10936 else if (S_ISCHR(st.st_mode))
10937 t = "cdev";
10938 # endif
10939 # ifdef S_ISFIFO
10940 else if (S_ISFIFO(st.st_mode))
10941 t = "fifo";
10942 # endif
10943 # ifdef S_ISSOCK
10944 else if (S_ISSOCK(st.st_mode))
10945 t = "fifo";
10946 # endif
10947 else
10948 t = "other";
10949 #else
10950 # ifdef S_IFMT
10951 switch (st.st_mode & S_IFMT)
10953 case S_IFREG: t = "file"; break;
10954 case S_IFDIR: t = "dir"; break;
10955 # ifdef S_IFLNK
10956 case S_IFLNK: t = "link"; break;
10957 # endif
10958 # ifdef S_IFBLK
10959 case S_IFBLK: t = "bdev"; break;
10960 # endif
10961 # ifdef S_IFCHR
10962 case S_IFCHR: t = "cdev"; break;
10963 # endif
10964 # ifdef S_IFIFO
10965 case S_IFIFO: t = "fifo"; break;
10966 # endif
10967 # ifdef S_IFSOCK
10968 case S_IFSOCK: t = "socket"; break;
10969 # endif
10970 default: t = "other";
10972 # else
10973 if (mch_isdir(fname))
10974 t = "dir";
10975 else
10976 t = "file";
10977 # endif
10978 #endif
10979 type = vim_strsave((char_u *)t);
10981 rettv->vval.v_string = type;
10985 * "getline(lnum, [end])" function
10987 static void
10988 f_getline(argvars, rettv)
10989 typval_T *argvars;
10990 typval_T *rettv;
10992 linenr_T lnum;
10993 linenr_T end;
10994 int retlist;
10996 lnum = get_tv_lnum(argvars);
10997 if (argvars[1].v_type == VAR_UNKNOWN)
10999 end = 0;
11000 retlist = FALSE;
11002 else
11004 end = get_tv_lnum(&argvars[1]);
11005 retlist = TRUE;
11008 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
11012 * "getmatches()" function
11014 static void
11015 f_getmatches(argvars, rettv)
11016 typval_T *argvars UNUSED;
11017 typval_T *rettv;
11019 #ifdef FEAT_SEARCH_EXTRA
11020 dict_T *dict;
11021 matchitem_T *cur = curwin->w_match_head;
11023 if (rettv_list_alloc(rettv) == OK)
11025 while (cur != NULL)
11027 dict = dict_alloc();
11028 if (dict == NULL)
11029 return;
11030 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
11031 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
11032 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
11033 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
11034 list_append_dict(rettv->vval.v_list, dict);
11035 cur = cur->next;
11038 #endif
11042 * "getpid()" function
11044 static void
11045 f_getpid(argvars, rettv)
11046 typval_T *argvars UNUSED;
11047 typval_T *rettv;
11049 rettv->vval.v_number = mch_get_pid();
11053 * "getpos(string)" function
11055 static void
11056 f_getpos(argvars, rettv)
11057 typval_T *argvars;
11058 typval_T *rettv;
11060 pos_T *fp;
11061 list_T *l;
11062 int fnum = -1;
11064 if (rettv_list_alloc(rettv) == OK)
11066 l = rettv->vval.v_list;
11067 fp = var2fpos(&argvars[0], TRUE, &fnum);
11068 if (fnum != -1)
11069 list_append_number(l, (varnumber_T)fnum);
11070 else
11071 list_append_number(l, (varnumber_T)0);
11072 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
11073 : (varnumber_T)0);
11074 list_append_number(l, (fp != NULL)
11075 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
11076 : (varnumber_T)0);
11077 list_append_number(l,
11078 #ifdef FEAT_VIRTUALEDIT
11079 (fp != NULL) ? (varnumber_T)fp->coladd :
11080 #endif
11081 (varnumber_T)0);
11083 else
11084 rettv->vval.v_number = FALSE;
11088 * "getqflist()" and "getloclist()" functions
11090 static void
11091 f_getqflist(argvars, rettv)
11092 typval_T *argvars UNUSED;
11093 typval_T *rettv UNUSED;
11095 #ifdef FEAT_QUICKFIX
11096 win_T *wp;
11097 #endif
11099 #ifdef FEAT_QUICKFIX
11100 if (rettv_list_alloc(rettv) == OK)
11102 wp = NULL;
11103 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
11105 wp = find_win_by_nr(&argvars[0], NULL);
11106 if (wp == NULL)
11107 return;
11110 (void)get_errorlist(wp, rettv->vval.v_list);
11112 #endif
11116 * "getreg()" function
11118 static void
11119 f_getreg(argvars, rettv)
11120 typval_T *argvars;
11121 typval_T *rettv;
11123 char_u *strregname;
11124 int regname;
11125 int arg2 = FALSE;
11126 int error = FALSE;
11128 if (argvars[0].v_type != VAR_UNKNOWN)
11130 strregname = get_tv_string_chk(&argvars[0]);
11131 error = strregname == NULL;
11132 if (argvars[1].v_type != VAR_UNKNOWN)
11133 arg2 = get_tv_number_chk(&argvars[1], &error);
11135 else
11136 strregname = vimvars[VV_REG].vv_str;
11137 regname = (strregname == NULL ? '"' : *strregname);
11138 if (regname == 0)
11139 regname = '"';
11141 rettv->v_type = VAR_STRING;
11142 rettv->vval.v_string = error ? NULL :
11143 get_reg_contents(regname, TRUE, arg2);
11147 * "getregtype()" function
11149 static void
11150 f_getregtype(argvars, rettv)
11151 typval_T *argvars;
11152 typval_T *rettv;
11154 char_u *strregname;
11155 int regname;
11156 char_u buf[NUMBUFLEN + 2];
11157 long reglen = 0;
11159 if (argvars[0].v_type != VAR_UNKNOWN)
11161 strregname = get_tv_string_chk(&argvars[0]);
11162 if (strregname == NULL) /* type error; errmsg already given */
11164 rettv->v_type = VAR_STRING;
11165 rettv->vval.v_string = NULL;
11166 return;
11169 else
11170 /* Default to v:register */
11171 strregname = vimvars[VV_REG].vv_str;
11173 regname = (strregname == NULL ? '"' : *strregname);
11174 if (regname == 0)
11175 regname = '"';
11177 buf[0] = NUL;
11178 buf[1] = NUL;
11179 switch (get_reg_type(regname, &reglen))
11181 case MLINE: buf[0] = 'V'; break;
11182 case MCHAR: buf[0] = 'v'; break;
11183 #ifdef FEAT_VISUAL
11184 case MBLOCK:
11185 buf[0] = Ctrl_V;
11186 sprintf((char *)buf + 1, "%ld", reglen + 1);
11187 break;
11188 #endif
11190 rettv->v_type = VAR_STRING;
11191 rettv->vval.v_string = vim_strsave(buf);
11195 * "gettabwinvar()" function
11197 static void
11198 f_gettabwinvar(argvars, rettv)
11199 typval_T *argvars;
11200 typval_T *rettv;
11202 getwinvar(argvars, rettv, 1);
11206 * "getwinposx()" function
11208 static void
11209 f_getwinposx(argvars, rettv)
11210 typval_T *argvars UNUSED;
11211 typval_T *rettv;
11213 rettv->vval.v_number = -1;
11214 #ifdef FEAT_GUI
11215 if (gui.in_use)
11217 int x, y;
11219 if (gui_mch_get_winpos(&x, &y) == OK)
11220 rettv->vval.v_number = x;
11222 #endif
11226 * "getwinposy()" function
11228 static void
11229 f_getwinposy(argvars, rettv)
11230 typval_T *argvars UNUSED;
11231 typval_T *rettv;
11233 rettv->vval.v_number = -1;
11234 #ifdef FEAT_GUI
11235 if (gui.in_use)
11237 int x, y;
11239 if (gui_mch_get_winpos(&x, &y) == OK)
11240 rettv->vval.v_number = y;
11242 #endif
11246 * Find window specified by "vp" in tabpage "tp".
11248 static win_T *
11249 find_win_by_nr(vp, tp)
11250 typval_T *vp;
11251 tabpage_T *tp; /* NULL for current tab page */
11253 #ifdef FEAT_WINDOWS
11254 win_T *wp;
11255 #endif
11256 int nr;
11258 nr = get_tv_number_chk(vp, NULL);
11260 #ifdef FEAT_WINDOWS
11261 if (nr < 0)
11262 return NULL;
11263 if (nr == 0)
11264 return curwin;
11266 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
11267 wp != NULL; wp = wp->w_next)
11268 if (--nr <= 0)
11269 break;
11270 return wp;
11271 #else
11272 if (nr == 0 || nr == 1)
11273 return curwin;
11274 return NULL;
11275 #endif
11279 * "getwinvar()" function
11281 static void
11282 f_getwinvar(argvars, rettv)
11283 typval_T *argvars;
11284 typval_T *rettv;
11286 getwinvar(argvars, rettv, 0);
11290 * getwinvar() and gettabwinvar()
11292 static void
11293 getwinvar(argvars, rettv, off)
11294 typval_T *argvars;
11295 typval_T *rettv;
11296 int off; /* 1 for gettabwinvar() */
11298 win_T *win, *oldcurwin;
11299 char_u *varname;
11300 dictitem_T *v;
11301 tabpage_T *tp;
11303 #ifdef FEAT_WINDOWS
11304 if (off == 1)
11305 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
11306 else
11307 tp = curtab;
11308 #endif
11309 win = find_win_by_nr(&argvars[off], tp);
11310 varname = get_tv_string_chk(&argvars[off + 1]);
11311 ++emsg_off;
11313 rettv->v_type = VAR_STRING;
11314 rettv->vval.v_string = NULL;
11316 if (win != NULL && varname != NULL)
11318 /* Set curwin to be our win, temporarily. Also set curbuf, so
11319 * that we can get buffer-local options. */
11320 oldcurwin = curwin;
11321 curwin = win;
11322 curbuf = win->w_buffer;
11324 if (*varname == '&') /* window-local-option */
11325 get_option_tv(&varname, rettv, 1);
11326 else
11328 if (*varname == NUL)
11329 /* let getwinvar({nr}, "") return the "w:" dictionary. The
11330 * scope prefix before the NUL byte is required by
11331 * find_var_in_ht(). */
11332 varname = (char_u *)"w:" + 2;
11333 /* look up the variable */
11334 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
11335 if (v != NULL)
11336 copy_tv(&v->di_tv, rettv);
11339 /* restore previous notion of curwin */
11340 curwin = oldcurwin;
11341 curbuf = curwin->w_buffer;
11344 --emsg_off;
11348 * "glob()" function
11350 static void
11351 f_glob(argvars, rettv)
11352 typval_T *argvars;
11353 typval_T *rettv;
11355 int flags = WILD_SILENT|WILD_USE_NL;
11356 expand_T xpc;
11357 int error = FALSE;
11359 /* When the optional second argument is non-zero, don't remove matches
11360 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11361 if (argvars[1].v_type != VAR_UNKNOWN
11362 && get_tv_number_chk(&argvars[1], &error))
11363 flags |= WILD_KEEP_ALL;
11364 rettv->v_type = VAR_STRING;
11365 if (!error)
11367 ExpandInit(&xpc);
11368 xpc.xp_context = EXPAND_FILES;
11369 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
11370 NULL, flags, WILD_ALL);
11372 else
11373 rettv->vval.v_string = NULL;
11377 * "globpath()" function
11379 static void
11380 f_globpath(argvars, rettv)
11381 typval_T *argvars;
11382 typval_T *rettv;
11384 int flags = 0;
11385 char_u buf1[NUMBUFLEN];
11386 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
11387 int error = FALSE;
11389 /* When the optional second argument is non-zero, don't remove matches
11390 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11391 if (argvars[2].v_type != VAR_UNKNOWN
11392 && get_tv_number_chk(&argvars[2], &error))
11393 flags |= WILD_KEEP_ALL;
11394 rettv->v_type = VAR_STRING;
11395 if (file == NULL || error)
11396 rettv->vval.v_string = NULL;
11397 else
11398 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file,
11399 flags);
11403 * "has()" function
11405 static void
11406 f_has(argvars, rettv)
11407 typval_T *argvars;
11408 typval_T *rettv;
11410 int i;
11411 char_u *name;
11412 int n = FALSE;
11413 static char *(has_list[]) =
11415 #ifdef AMIGA
11416 "amiga",
11417 # ifdef FEAT_ARP
11418 "arp",
11419 # endif
11420 #endif
11421 #ifdef __BEOS__
11422 "beos",
11423 #endif
11424 #ifdef MSDOS
11425 # ifdef DJGPP
11426 "dos32",
11427 # else
11428 "dos16",
11429 # endif
11430 #endif
11431 #ifdef MACOS
11432 "mac",
11433 #endif
11434 #if defined(MACOS_X_UNIX)
11435 "macunix",
11436 #endif
11437 #ifdef OS2
11438 "os2",
11439 #endif
11440 #ifdef __QNX__
11441 "qnx",
11442 #endif
11443 #ifdef RISCOS
11444 "riscos",
11445 #endif
11446 #ifdef UNIX
11447 "unix",
11448 #endif
11449 #ifdef VMS
11450 "vms",
11451 #endif
11452 #ifdef WIN16
11453 "win16",
11454 #endif
11455 #ifdef WIN32
11456 "win32",
11457 #endif
11458 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
11459 "win32unix",
11460 #endif
11461 #if defined(WIN64) || defined(_WIN64)
11462 "win64",
11463 #endif
11464 #ifdef EBCDIC
11465 "ebcdic",
11466 #endif
11467 #ifndef CASE_INSENSITIVE_FILENAME
11468 "fname_case",
11469 #endif
11470 #ifdef FEAT_ARABIC
11471 "arabic",
11472 #endif
11473 #ifdef FEAT_AUTOCMD
11474 "autocmd",
11475 #endif
11476 #ifdef FEAT_BEVAL
11477 "balloon_eval",
11478 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
11479 "balloon_multiline",
11480 # endif
11481 #endif
11482 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
11483 "builtin_terms",
11484 # ifdef ALL_BUILTIN_TCAPS
11485 "all_builtin_terms",
11486 # endif
11487 #endif
11488 #ifdef FEAT_BYTEOFF
11489 "byte_offset",
11490 #endif
11491 #ifdef FEAT_CINDENT
11492 "cindent",
11493 #endif
11494 #ifdef FEAT_CLIENTSERVER
11495 "clientserver",
11496 #endif
11497 #ifdef FEAT_CLIPBOARD
11498 "clipboard",
11499 #endif
11500 #ifdef FEAT_CMDL_COMPL
11501 "cmdline_compl",
11502 #endif
11503 #ifdef FEAT_CMDHIST
11504 "cmdline_hist",
11505 #endif
11506 #ifdef FEAT_COMMENTS
11507 "comments",
11508 #endif
11509 #ifdef FEAT_CRYPT
11510 "cryptv",
11511 #endif
11512 #ifdef FEAT_CSCOPE
11513 "cscope",
11514 #endif
11515 #ifdef CURSOR_SHAPE
11516 "cursorshape",
11517 #endif
11518 #ifdef DEBUG
11519 "debug",
11520 #endif
11521 #ifdef FEAT_CON_DIALOG
11522 "dialog_con",
11523 #endif
11524 #ifdef FEAT_GUI_DIALOG
11525 "dialog_gui",
11526 #endif
11527 #ifdef FEAT_DIFF
11528 "diff",
11529 #endif
11530 #ifdef FEAT_DIGRAPHS
11531 "digraphs",
11532 #endif
11533 #ifdef FEAT_DND
11534 "dnd",
11535 #endif
11536 #ifdef FEAT_EMACS_TAGS
11537 "emacs_tags",
11538 #endif
11539 "eval", /* always present, of course! */
11540 #ifdef FEAT_EX_EXTRA
11541 "ex_extra",
11542 #endif
11543 #ifdef FEAT_SEARCH_EXTRA
11544 "extra_search",
11545 #endif
11546 #ifdef FEAT_FKMAP
11547 "farsi",
11548 #endif
11549 #ifdef FEAT_SEARCHPATH
11550 "file_in_path",
11551 #endif
11552 #if defined(UNIX) && !defined(USE_SYSTEM)
11553 "filterpipe",
11554 #endif
11555 #ifdef FEAT_FIND_ID
11556 "find_in_path",
11557 #endif
11558 #ifdef FEAT_FLOAT
11559 "float",
11560 #endif
11561 #ifdef FEAT_FOLDING
11562 "folding",
11563 #endif
11564 #ifdef FEAT_FOOTER
11565 "footer",
11566 #endif
11567 #if !defined(USE_SYSTEM) && defined(UNIX)
11568 "fork",
11569 #endif
11570 #ifdef FEAT_GETTEXT
11571 "gettext",
11572 #endif
11573 "guess_encode",
11574 #ifdef FEAT_GUI
11575 "gui",
11576 #endif
11577 #ifdef FEAT_GUI_ATHENA
11578 # ifdef FEAT_GUI_NEXTAW
11579 "gui_neXtaw",
11580 # else
11581 "gui_athena",
11582 # endif
11583 #endif
11584 #ifdef FEAT_GUI_GTK
11585 "gui_gtk",
11586 # ifdef HAVE_GTK2
11587 "gui_gtk2",
11588 # endif
11589 #endif
11590 #ifdef FEAT_GUI_GNOME
11591 "gui_gnome",
11592 #endif
11593 #ifdef FEAT_GUI_MAC
11594 "gui_mac",
11595 #endif
11596 #ifdef FEAT_GUI_MOTIF
11597 "gui_motif",
11598 #endif
11599 #ifdef FEAT_GUI_PHOTON
11600 "gui_photon",
11601 #endif
11602 #ifdef FEAT_GUI_W16
11603 "gui_win16",
11604 #endif
11605 #ifdef FEAT_GUI_W32
11606 "gui_win32",
11607 #endif
11608 #ifdef FEAT_HANGULIN
11609 "hangul_input",
11610 #endif
11611 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
11612 "iconv",
11613 #endif
11614 #ifdef FEAT_INS_EXPAND
11615 "insert_expand",
11616 #endif
11617 #ifdef FEAT_JUMPLIST
11618 "jumplist",
11619 #endif
11620 "kaoriya",
11621 #ifdef FEAT_KEYMAP
11622 "keymap",
11623 #endif
11624 #ifdef FEAT_LANGMAP
11625 "langmap",
11626 #endif
11627 #ifdef FEAT_LIBCALL
11628 "libcall",
11629 #endif
11630 #ifdef FEAT_LINEBREAK
11631 "linebreak",
11632 #endif
11633 #ifdef FEAT_LISP
11634 "lispindent",
11635 #endif
11636 #ifdef FEAT_LISTCMDS
11637 "listcmds",
11638 #endif
11639 #ifdef FEAT_LOCALMAP
11640 "localmap",
11641 #endif
11642 #ifdef FEAT_MENU
11643 "menu",
11644 #endif
11645 #ifdef USE_MIGEMO
11646 # ifndef DYNAMIC_MIGEMO
11647 "migemo",
11648 # endif
11649 #endif
11650 #ifdef FEAT_SESSION
11651 "mksession",
11652 #endif
11653 #ifdef FEAT_MODIFY_FNAME
11654 "modify_fname",
11655 #endif
11656 #ifdef FEAT_MOUSE
11657 "mouse",
11658 #endif
11659 #ifdef FEAT_MOUSESHAPE
11660 "mouseshape",
11661 #endif
11662 #if defined(UNIX) || defined(VMS)
11663 # ifdef FEAT_MOUSE_DEC
11664 "mouse_dec",
11665 # endif
11666 # ifdef FEAT_MOUSE_GPM
11667 "mouse_gpm",
11668 # endif
11669 # ifdef FEAT_MOUSE_JSB
11670 "mouse_jsbterm",
11671 # endif
11672 # ifdef FEAT_MOUSE_NET
11673 "mouse_netterm",
11674 # endif
11675 # ifdef FEAT_MOUSE_PTERM
11676 "mouse_pterm",
11677 # endif
11678 # ifdef FEAT_SYSMOUSE
11679 "mouse_sysmouse",
11680 # endif
11681 # ifdef FEAT_MOUSE_XTERM
11682 "mouse_xterm",
11683 # endif
11684 #endif
11685 #ifdef FEAT_MBYTE
11686 "multi_byte",
11687 #endif
11688 #ifdef FEAT_MBYTE_IME
11689 "multi_byte_ime",
11690 #endif
11691 #ifdef FEAT_MULTI_LANG
11692 "multi_lang",
11693 #endif
11694 #ifdef FEAT_MZSCHEME
11695 #ifndef DYNAMIC_MZSCHEME
11696 "mzscheme",
11697 #endif
11698 #endif
11699 #ifdef FEAT_OLE
11700 "ole",
11701 #endif
11702 #ifdef FEAT_OSFILETYPE
11703 "osfiletype",
11704 #endif
11705 #ifdef FEAT_PATH_EXTRA
11706 "path_extra",
11707 #endif
11708 #ifdef FEAT_PERL
11709 #ifndef DYNAMIC_PERL
11710 "perl",
11711 #endif
11712 #endif
11713 #ifdef FEAT_PYTHON
11714 #ifndef DYNAMIC_PYTHON
11715 "python",
11716 #endif
11717 #endif
11718 #ifdef FEAT_POSTSCRIPT
11719 "postscript",
11720 #endif
11721 #ifdef FEAT_PRINTER
11722 "printer",
11723 #endif
11724 #ifdef FEAT_PROFILE
11725 "profile",
11726 #endif
11727 #ifdef FEAT_RELTIME
11728 "reltime",
11729 #endif
11730 #ifdef FEAT_QUICKFIX
11731 "quickfix",
11732 #endif
11733 #ifdef FEAT_RIGHTLEFT
11734 "rightleft",
11735 #endif
11736 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11737 "ruby",
11738 #endif
11739 #ifdef FEAT_SCROLLBIND
11740 "scrollbind",
11741 #endif
11742 #ifdef FEAT_CMDL_INFO
11743 "showcmd",
11744 "cmdline_info",
11745 #endif
11746 #ifdef FEAT_SIGNS
11747 "signs",
11748 #endif
11749 #ifdef FEAT_SMARTINDENT
11750 "smartindent",
11751 #endif
11752 #ifdef FEAT_SNIFF
11753 "sniff",
11754 #endif
11755 #ifdef STARTUPTIME
11756 "startuptime",
11757 #endif
11758 #ifdef FEAT_STL_OPT
11759 "statusline",
11760 #endif
11761 #ifdef FEAT_SUN_WORKSHOP
11762 "sun_workshop",
11763 #endif
11764 #ifdef FEAT_NETBEANS_INTG
11765 "netbeans_intg",
11766 #endif
11767 #ifdef FEAT_SPELL
11768 "spell",
11769 #endif
11770 #ifdef FEAT_SYN_HL
11771 "syntax",
11772 #endif
11773 #if defined(USE_SYSTEM) || !defined(UNIX)
11774 "system",
11775 #endif
11776 #ifdef FEAT_TAG_BINS
11777 "tag_binary",
11778 #endif
11779 #ifdef FEAT_TAG_OLDSTATIC
11780 "tag_old_static",
11781 #endif
11782 #ifdef FEAT_TAG_ANYWHITE
11783 "tag_any_white",
11784 #endif
11785 #ifdef FEAT_TCL
11786 # ifndef DYNAMIC_TCL
11787 "tcl",
11788 # endif
11789 #endif
11790 #ifdef TERMINFO
11791 "terminfo",
11792 #endif
11793 #ifdef FEAT_TERMRESPONSE
11794 "termresponse",
11795 #endif
11796 #ifdef FEAT_TEXTOBJ
11797 "textobjects",
11798 #endif
11799 #ifdef HAVE_TGETENT
11800 "tgetent",
11801 #endif
11802 #ifdef FEAT_TITLE
11803 "title",
11804 #endif
11805 #ifdef FEAT_TOOLBAR
11806 "toolbar",
11807 #endif
11808 #ifdef FEAT_USR_CMDS
11809 "user-commands", /* was accidentally included in 5.4 */
11810 "user_commands",
11811 #endif
11812 #ifdef FEAT_VIMINFO
11813 "viminfo",
11814 #endif
11815 #ifdef FEAT_VERTSPLIT
11816 "vertsplit",
11817 #endif
11818 #ifdef FEAT_VIRTUALEDIT
11819 "virtualedit",
11820 #endif
11821 #ifdef FEAT_VISUAL
11822 "visual",
11823 #endif
11824 #ifdef FEAT_VISUALEXTRA
11825 "visualextra",
11826 #endif
11827 #ifdef FEAT_VREPLACE
11828 "vreplace",
11829 #endif
11830 #ifdef FEAT_WILDIGN
11831 "wildignore",
11832 #endif
11833 #ifdef FEAT_WILDMENU
11834 "wildmenu",
11835 #endif
11836 #ifdef FEAT_WINDOWS
11837 "windows",
11838 #endif
11839 #ifdef FEAT_WAK
11840 "winaltkeys",
11841 #endif
11842 #ifdef FEAT_WRITEBACKUP
11843 "writebackup",
11844 #endif
11845 #ifdef FEAT_XIM
11846 "xim",
11847 #endif
11848 #ifdef FEAT_XFONTSET
11849 "xfontset",
11850 #endif
11851 #ifdef USE_XSMP
11852 "xsmp",
11853 #endif
11854 #ifdef USE_XSMP_INTERACT
11855 "xsmp_interact",
11856 #endif
11857 #ifdef FEAT_XCLIPBOARD
11858 "xterm_clipboard",
11859 #endif
11860 #ifdef FEAT_XTERM_SAVE
11861 "xterm_save",
11862 #endif
11863 #if defined(UNIX) && defined(FEAT_X11)
11864 "X11",
11865 #endif
11866 NULL
11869 name = get_tv_string(&argvars[0]);
11870 for (i = 0; has_list[i] != NULL; ++i)
11871 if (STRICMP(name, has_list[i]) == 0)
11873 n = TRUE;
11874 break;
11877 if (n == FALSE)
11879 if (STRNICMP(name, "patch", 5) == 0)
11880 n = has_patch(atoi((char *)name + 5));
11881 else if (STRICMP(name, "vim_starting") == 0)
11882 n = (starting != 0);
11883 #ifdef FEAT_MBYTE
11884 else if (STRICMP(name, "multi_byte_encoding") == 0)
11885 n = has_mbyte;
11886 #endif
11887 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
11888 else if (STRICMP(name, "balloon_multiline") == 0)
11889 n = multiline_balloon_available();
11890 #endif
11891 #ifdef DYNAMIC_TCL
11892 else if (STRICMP(name, "tcl") == 0)
11893 n = tcl_enabled(FALSE);
11894 #endif
11895 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
11896 else if (STRICMP(name, "iconv") == 0)
11897 n = iconv_enabled(FALSE);
11898 #endif
11899 #ifdef DYNAMIC_MZSCHEME
11900 else if (STRICMP(name, "mzscheme") == 0)
11901 n = mzscheme_enabled(FALSE);
11902 #endif
11903 #ifdef DYNAMIC_RUBY
11904 else if (STRICMP(name, "ruby") == 0)
11905 n = ruby_enabled(FALSE);
11906 #endif
11907 #ifdef DYNAMIC_PYTHON
11908 else if (STRICMP(name, "python") == 0)
11909 n = python_enabled(FALSE);
11910 #endif
11911 #ifdef DYNAMIC_PERL
11912 else if (STRICMP(name, "perl") == 0)
11913 n = perl_enabled(FALSE);
11914 #endif
11915 #ifdef FEAT_GUI
11916 else if (STRICMP(name, "gui_running") == 0)
11917 n = (gui.in_use || gui.starting);
11918 # ifdef FEAT_GUI_W32
11919 else if (STRICMP(name, "gui_win32s") == 0)
11920 n = gui_is_win32s();
11921 # endif
11922 # ifdef FEAT_BROWSE
11923 else if (STRICMP(name, "browse") == 0)
11924 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
11925 # endif
11926 #endif
11927 #ifdef FEAT_SYN_HL
11928 else if (STRICMP(name, "syntax_items") == 0)
11929 n = syntax_present(curbuf);
11930 #endif
11931 #if defined(WIN3264)
11932 else if (STRICMP(name, "win95") == 0)
11933 n = mch_windows95();
11934 #endif
11935 #if defined(USE_MIGEMO)
11936 else if (STRICMP(name, "migemo") == 0)
11937 n = migemo_enabled() ? TRUE : FALSE;
11938 #endif
11939 #ifdef FEAT_NETBEANS_INTG
11940 else if (STRICMP(name, "netbeans_enabled") == 0)
11941 n = usingNetbeans;
11942 #endif
11945 rettv->vval.v_number = n;
11949 * "has_key()" function
11951 static void
11952 f_has_key(argvars, rettv)
11953 typval_T *argvars;
11954 typval_T *rettv;
11956 if (argvars[0].v_type != VAR_DICT)
11958 EMSG(_(e_dictreq));
11959 return;
11961 if (argvars[0].vval.v_dict == NULL)
11962 return;
11964 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
11965 get_tv_string(&argvars[1]), -1) != NULL;
11969 * "haslocaldir()" function
11971 static void
11972 f_haslocaldir(argvars, rettv)
11973 typval_T *argvars UNUSED;
11974 typval_T *rettv;
11976 rettv->vval.v_number = (curwin->w_localdir != NULL);
11980 * "hasmapto()" function
11982 static void
11983 f_hasmapto(argvars, rettv)
11984 typval_T *argvars;
11985 typval_T *rettv;
11987 char_u *name;
11988 char_u *mode;
11989 char_u buf[NUMBUFLEN];
11990 int abbr = FALSE;
11992 name = get_tv_string(&argvars[0]);
11993 if (argvars[1].v_type == VAR_UNKNOWN)
11994 mode = (char_u *)"nvo";
11995 else
11997 mode = get_tv_string_buf(&argvars[1], buf);
11998 if (argvars[2].v_type != VAR_UNKNOWN)
11999 abbr = get_tv_number(&argvars[2]);
12002 if (map_to_exists(name, mode, abbr))
12003 rettv->vval.v_number = TRUE;
12004 else
12005 rettv->vval.v_number = FALSE;
12009 * "histadd()" function
12011 static void
12012 f_histadd(argvars, rettv)
12013 typval_T *argvars UNUSED;
12014 typval_T *rettv;
12016 #ifdef FEAT_CMDHIST
12017 int histype;
12018 char_u *str;
12019 char_u buf[NUMBUFLEN];
12020 #endif
12022 rettv->vval.v_number = FALSE;
12023 if (check_restricted() || check_secure())
12024 return;
12025 #ifdef FEAT_CMDHIST
12026 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12027 histype = str != NULL ? get_histtype(str) : -1;
12028 if (histype >= 0)
12030 str = get_tv_string_buf(&argvars[1], buf);
12031 if (*str != NUL)
12033 init_history();
12034 add_to_history(histype, str, FALSE, NUL);
12035 rettv->vval.v_number = TRUE;
12036 return;
12039 #endif
12043 * "histdel()" function
12045 static void
12046 f_histdel(argvars, rettv)
12047 typval_T *argvars UNUSED;
12048 typval_T *rettv UNUSED;
12050 #ifdef FEAT_CMDHIST
12051 int n;
12052 char_u buf[NUMBUFLEN];
12053 char_u *str;
12055 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12056 if (str == NULL)
12057 n = 0;
12058 else if (argvars[1].v_type == VAR_UNKNOWN)
12059 /* only one argument: clear entire history */
12060 n = clr_history(get_histtype(str));
12061 else if (argvars[1].v_type == VAR_NUMBER)
12062 /* index given: remove that entry */
12063 n = del_history_idx(get_histtype(str),
12064 (int)get_tv_number(&argvars[1]));
12065 else
12066 /* string given: remove all matching entries */
12067 n = del_history_entry(get_histtype(str),
12068 get_tv_string_buf(&argvars[1], buf));
12069 rettv->vval.v_number = n;
12070 #endif
12074 * "histget()" function
12076 static void
12077 f_histget(argvars, rettv)
12078 typval_T *argvars UNUSED;
12079 typval_T *rettv;
12081 #ifdef FEAT_CMDHIST
12082 int type;
12083 int idx;
12084 char_u *str;
12086 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12087 if (str == NULL)
12088 rettv->vval.v_string = NULL;
12089 else
12091 type = get_histtype(str);
12092 if (argvars[1].v_type == VAR_UNKNOWN)
12093 idx = get_history_idx(type);
12094 else
12095 idx = (int)get_tv_number_chk(&argvars[1], NULL);
12096 /* -1 on type error */
12097 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
12099 #else
12100 rettv->vval.v_string = NULL;
12101 #endif
12102 rettv->v_type = VAR_STRING;
12106 * "histnr()" function
12108 static void
12109 f_histnr(argvars, rettv)
12110 typval_T *argvars UNUSED;
12111 typval_T *rettv;
12113 int i;
12115 #ifdef FEAT_CMDHIST
12116 char_u *history = get_tv_string_chk(&argvars[0]);
12118 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
12119 if (i >= HIST_CMD && i < HIST_COUNT)
12120 i = get_history_idx(i);
12121 else
12122 #endif
12123 i = -1;
12124 rettv->vval.v_number = i;
12128 * "highlightID(name)" function
12130 static void
12131 f_hlID(argvars, rettv)
12132 typval_T *argvars;
12133 typval_T *rettv;
12135 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
12139 * "highlight_exists()" function
12141 static void
12142 f_hlexists(argvars, rettv)
12143 typval_T *argvars;
12144 typval_T *rettv;
12146 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
12150 * "hostname()" function
12152 static void
12153 f_hostname(argvars, rettv)
12154 typval_T *argvars UNUSED;
12155 typval_T *rettv;
12157 char_u hostname[256];
12159 mch_get_host_name(hostname, 256);
12160 rettv->v_type = VAR_STRING;
12161 rettv->vval.v_string = vim_strsave(hostname);
12165 * iconv() function
12167 static void
12168 f_iconv(argvars, rettv)
12169 typval_T *argvars UNUSED;
12170 typval_T *rettv;
12172 #ifdef FEAT_MBYTE
12173 char_u buf1[NUMBUFLEN];
12174 char_u buf2[NUMBUFLEN];
12175 char_u *from, *to, *str;
12176 vimconv_T vimconv;
12177 #endif
12179 rettv->v_type = VAR_STRING;
12180 rettv->vval.v_string = NULL;
12182 #ifdef FEAT_MBYTE
12183 str = get_tv_string(&argvars[0]);
12184 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
12185 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
12186 vimconv.vc_type = CONV_NONE;
12187 convert_setup(&vimconv, from, to);
12189 /* If the encodings are equal, no conversion needed. */
12190 if (vimconv.vc_type == CONV_NONE)
12191 rettv->vval.v_string = vim_strsave(str);
12192 else
12193 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
12195 convert_setup(&vimconv, NULL, NULL);
12196 vim_free(from);
12197 vim_free(to);
12198 #endif
12202 * "indent()" function
12204 static void
12205 f_indent(argvars, rettv)
12206 typval_T *argvars;
12207 typval_T *rettv;
12209 linenr_T lnum;
12211 lnum = get_tv_lnum(argvars);
12212 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12213 rettv->vval.v_number = get_indent_lnum(lnum);
12214 else
12215 rettv->vval.v_number = -1;
12219 * "index()" function
12221 static void
12222 f_index(argvars, rettv)
12223 typval_T *argvars;
12224 typval_T *rettv;
12226 list_T *l;
12227 listitem_T *item;
12228 long idx = 0;
12229 int ic = FALSE;
12231 rettv->vval.v_number = -1;
12232 if (argvars[0].v_type != VAR_LIST)
12234 EMSG(_(e_listreq));
12235 return;
12237 l = argvars[0].vval.v_list;
12238 if (l != NULL)
12240 item = l->lv_first;
12241 if (argvars[2].v_type != VAR_UNKNOWN)
12243 int error = FALSE;
12245 /* Start at specified item. Use the cached index that list_find()
12246 * sets, so that a negative number also works. */
12247 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
12248 idx = l->lv_idx;
12249 if (argvars[3].v_type != VAR_UNKNOWN)
12250 ic = get_tv_number_chk(&argvars[3], &error);
12251 if (error)
12252 item = NULL;
12255 for ( ; item != NULL; item = item->li_next, ++idx)
12256 if (tv_equal(&item->li_tv, &argvars[1], ic))
12258 rettv->vval.v_number = idx;
12259 break;
12264 static int inputsecret_flag = 0;
12266 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
12269 * This function is used by f_input() and f_inputdialog() functions. The third
12270 * argument to f_input() specifies the type of completion to use at the
12271 * prompt. The third argument to f_inputdialog() specifies the value to return
12272 * when the user cancels the prompt.
12274 static void
12275 get_user_input(argvars, rettv, inputdialog)
12276 typval_T *argvars;
12277 typval_T *rettv;
12278 int inputdialog;
12280 char_u *prompt = get_tv_string_chk(&argvars[0]);
12281 char_u *p = NULL;
12282 int c;
12283 char_u buf[NUMBUFLEN];
12284 int cmd_silent_save = cmd_silent;
12285 char_u *defstr = (char_u *)"";
12286 int xp_type = EXPAND_NOTHING;
12287 char_u *xp_arg = NULL;
12289 rettv->v_type = VAR_STRING;
12290 rettv->vval.v_string = NULL;
12292 #ifdef NO_CONSOLE_INPUT
12293 /* While starting up, there is no place to enter text. */
12294 if (no_console_input())
12295 return;
12296 #endif
12298 cmd_silent = FALSE; /* Want to see the prompt. */
12299 if (prompt != NULL)
12301 /* Only the part of the message after the last NL is considered as
12302 * prompt for the command line */
12303 p = vim_strrchr(prompt, '\n');
12304 if (p == NULL)
12305 p = prompt;
12306 else
12308 ++p;
12309 c = *p;
12310 *p = NUL;
12311 msg_start();
12312 msg_clr_eos();
12313 msg_puts_attr(prompt, echo_attr);
12314 msg_didout = FALSE;
12315 msg_starthere();
12316 *p = c;
12318 cmdline_row = msg_row;
12320 if (argvars[1].v_type != VAR_UNKNOWN)
12322 defstr = get_tv_string_buf_chk(&argvars[1], buf);
12323 if (defstr != NULL)
12324 stuffReadbuffSpec(defstr);
12326 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
12328 char_u *xp_name;
12329 int xp_namelen;
12330 long argt;
12332 rettv->vval.v_string = NULL;
12334 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
12335 if (xp_name == NULL)
12336 return;
12338 xp_namelen = (int)STRLEN(xp_name);
12340 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
12341 &xp_arg) == FAIL)
12342 return;
12346 if (defstr != NULL)
12347 rettv->vval.v_string =
12348 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
12349 xp_type, xp_arg);
12351 vim_free(xp_arg);
12353 /* since the user typed this, no need to wait for return */
12354 need_wait_return = FALSE;
12355 msg_didout = FALSE;
12357 cmd_silent = cmd_silent_save;
12361 * "input()" function
12362 * Also handles inputsecret() when inputsecret is set.
12364 static void
12365 f_input(argvars, rettv)
12366 typval_T *argvars;
12367 typval_T *rettv;
12369 get_user_input(argvars, rettv, FALSE);
12373 * "inputdialog()" function
12375 static void
12376 f_inputdialog(argvars, rettv)
12377 typval_T *argvars;
12378 typval_T *rettv;
12380 #if defined(FEAT_GUI_TEXTDIALOG)
12381 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
12382 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
12384 char_u *message;
12385 char_u buf[NUMBUFLEN];
12386 char_u *defstr = (char_u *)"";
12388 message = get_tv_string_chk(&argvars[0]);
12389 if (argvars[1].v_type != VAR_UNKNOWN
12390 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
12391 vim_strncpy(IObuff, defstr, IOSIZE - 1);
12392 else
12393 IObuff[0] = NUL;
12394 if (message != NULL && defstr != NULL
12395 && do_dialog(VIM_QUESTION, NULL, message,
12396 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
12397 rettv->vval.v_string = vim_strsave(IObuff);
12398 else
12400 if (message != NULL && defstr != NULL
12401 && argvars[1].v_type != VAR_UNKNOWN
12402 && argvars[2].v_type != VAR_UNKNOWN)
12403 rettv->vval.v_string = vim_strsave(
12404 get_tv_string_buf(&argvars[2], buf));
12405 else
12406 rettv->vval.v_string = NULL;
12408 rettv->v_type = VAR_STRING;
12410 else
12411 #endif
12412 get_user_input(argvars, rettv, TRUE);
12416 * "inputlist()" function
12418 static void
12419 f_inputlist(argvars, rettv)
12420 typval_T *argvars;
12421 typval_T *rettv;
12423 listitem_T *li;
12424 int selected;
12425 int mouse_used;
12427 #ifdef NO_CONSOLE_INPUT
12428 /* While starting up, there is no place to enter text. */
12429 if (no_console_input())
12430 return;
12431 #endif
12432 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
12434 EMSG2(_(e_listarg), "inputlist()");
12435 return;
12438 msg_start();
12439 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
12440 lines_left = Rows; /* avoid more prompt */
12441 msg_scroll = TRUE;
12442 msg_clr_eos();
12444 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
12446 msg_puts(get_tv_string(&li->li_tv));
12447 msg_putchar('\n');
12450 /* Ask for choice. */
12451 selected = prompt_for_number(&mouse_used);
12452 if (mouse_used)
12453 selected -= lines_left;
12455 rettv->vval.v_number = selected;
12459 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
12462 * "inputrestore()" function
12464 static void
12465 f_inputrestore(argvars, rettv)
12466 typval_T *argvars UNUSED;
12467 typval_T *rettv;
12469 if (ga_userinput.ga_len > 0)
12471 --ga_userinput.ga_len;
12472 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
12473 + ga_userinput.ga_len);
12474 /* default return is zero == OK */
12476 else if (p_verbose > 1)
12478 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
12479 rettv->vval.v_number = 1; /* Failed */
12484 * "inputsave()" function
12486 static void
12487 f_inputsave(argvars, rettv)
12488 typval_T *argvars UNUSED;
12489 typval_T *rettv;
12491 /* Add an entry to the stack of typeahead storage. */
12492 if (ga_grow(&ga_userinput, 1) == OK)
12494 save_typeahead((tasave_T *)(ga_userinput.ga_data)
12495 + ga_userinput.ga_len);
12496 ++ga_userinput.ga_len;
12497 /* default return is zero == OK */
12499 else
12500 rettv->vval.v_number = 1; /* Failed */
12504 * "inputsecret()" function
12506 static void
12507 f_inputsecret(argvars, rettv)
12508 typval_T *argvars;
12509 typval_T *rettv;
12511 ++cmdline_star;
12512 ++inputsecret_flag;
12513 f_input(argvars, rettv);
12514 --cmdline_star;
12515 --inputsecret_flag;
12519 * "insert()" function
12521 static void
12522 f_insert(argvars, rettv)
12523 typval_T *argvars;
12524 typval_T *rettv;
12526 long before = 0;
12527 listitem_T *item;
12528 list_T *l;
12529 int error = FALSE;
12531 if (argvars[0].v_type != VAR_LIST)
12532 EMSG2(_(e_listarg), "insert()");
12533 else if ((l = argvars[0].vval.v_list) != NULL
12534 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
12536 if (argvars[2].v_type != VAR_UNKNOWN)
12537 before = get_tv_number_chk(&argvars[2], &error);
12538 if (error)
12539 return; /* type error; errmsg already given */
12541 if (before == l->lv_len)
12542 item = NULL;
12543 else
12545 item = list_find(l, before);
12546 if (item == NULL)
12548 EMSGN(_(e_listidx), before);
12549 l = NULL;
12552 if (l != NULL)
12554 list_insert_tv(l, &argvars[1], item);
12555 copy_tv(&argvars[0], rettv);
12561 * "isdirectory()" function
12563 static void
12564 f_isdirectory(argvars, rettv)
12565 typval_T *argvars;
12566 typval_T *rettv;
12568 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
12572 * "islocked()" function
12574 static void
12575 f_islocked(argvars, rettv)
12576 typval_T *argvars;
12577 typval_T *rettv;
12579 lval_T lv;
12580 char_u *end;
12581 dictitem_T *di;
12583 rettv->vval.v_number = -1;
12584 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
12585 FNE_CHECK_START);
12586 if (end != NULL && lv.ll_name != NULL)
12588 if (*end != NUL)
12589 EMSG(_(e_trailing));
12590 else
12592 if (lv.ll_tv == NULL)
12594 if (check_changedtick(lv.ll_name))
12595 rettv->vval.v_number = 1; /* always locked */
12596 else
12598 di = find_var(lv.ll_name, NULL);
12599 if (di != NULL)
12601 /* Consider a variable locked when:
12602 * 1. the variable itself is locked
12603 * 2. the value of the variable is locked.
12604 * 3. the List or Dict value is locked.
12606 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
12607 || tv_islocked(&di->di_tv));
12611 else if (lv.ll_range)
12612 EMSG(_("E786: Range not allowed"));
12613 else if (lv.ll_newkey != NULL)
12614 EMSG2(_(e_dictkey), lv.ll_newkey);
12615 else if (lv.ll_list != NULL)
12616 /* List item. */
12617 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
12618 else
12619 /* Dictionary item. */
12620 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
12624 clear_lval(&lv);
12627 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
12630 * Turn a dict into a list:
12631 * "what" == 0: list of keys
12632 * "what" == 1: list of values
12633 * "what" == 2: list of items
12635 static void
12636 dict_list(argvars, rettv, what)
12637 typval_T *argvars;
12638 typval_T *rettv;
12639 int what;
12641 list_T *l2;
12642 dictitem_T *di;
12643 hashitem_T *hi;
12644 listitem_T *li;
12645 listitem_T *li2;
12646 dict_T *d;
12647 int todo;
12649 if (argvars[0].v_type != VAR_DICT)
12651 EMSG(_(e_dictreq));
12652 return;
12654 if ((d = argvars[0].vval.v_dict) == NULL)
12655 return;
12657 if (rettv_list_alloc(rettv) == FAIL)
12658 return;
12660 todo = (int)d->dv_hashtab.ht_used;
12661 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12663 if (!HASHITEM_EMPTY(hi))
12665 --todo;
12666 di = HI2DI(hi);
12668 li = listitem_alloc();
12669 if (li == NULL)
12670 break;
12671 list_append(rettv->vval.v_list, li);
12673 if (what == 0)
12675 /* keys() */
12676 li->li_tv.v_type = VAR_STRING;
12677 li->li_tv.v_lock = 0;
12678 li->li_tv.vval.v_string = vim_strsave(di->di_key);
12680 else if (what == 1)
12682 /* values() */
12683 copy_tv(&di->di_tv, &li->li_tv);
12685 else
12687 /* items() */
12688 l2 = list_alloc();
12689 li->li_tv.v_type = VAR_LIST;
12690 li->li_tv.v_lock = 0;
12691 li->li_tv.vval.v_list = l2;
12692 if (l2 == NULL)
12693 break;
12694 ++l2->lv_refcount;
12696 li2 = listitem_alloc();
12697 if (li2 == NULL)
12698 break;
12699 list_append(l2, li2);
12700 li2->li_tv.v_type = VAR_STRING;
12701 li2->li_tv.v_lock = 0;
12702 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12704 li2 = listitem_alloc();
12705 if (li2 == NULL)
12706 break;
12707 list_append(l2, li2);
12708 copy_tv(&di->di_tv, &li2->li_tv);
12715 * "items(dict)" function
12717 static void
12718 f_items(argvars, rettv)
12719 typval_T *argvars;
12720 typval_T *rettv;
12722 dict_list(argvars, rettv, 2);
12726 * "join()" function
12728 static void
12729 f_join(argvars, rettv)
12730 typval_T *argvars;
12731 typval_T *rettv;
12733 garray_T ga;
12734 char_u *sep;
12736 if (argvars[0].v_type != VAR_LIST)
12738 EMSG(_(e_listreq));
12739 return;
12741 if (argvars[0].vval.v_list == NULL)
12742 return;
12743 if (argvars[1].v_type == VAR_UNKNOWN)
12744 sep = (char_u *)" ";
12745 else
12746 sep = get_tv_string_chk(&argvars[1]);
12748 rettv->v_type = VAR_STRING;
12750 if (sep != NULL)
12752 ga_init2(&ga, (int)sizeof(char), 80);
12753 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12754 ga_append(&ga, NUL);
12755 rettv->vval.v_string = (char_u *)ga.ga_data;
12757 else
12758 rettv->vval.v_string = NULL;
12762 * "keys()" function
12764 static void
12765 f_keys(argvars, rettv)
12766 typval_T *argvars;
12767 typval_T *rettv;
12769 dict_list(argvars, rettv, 0);
12773 * "last_buffer_nr()" function.
12775 static void
12776 f_last_buffer_nr(argvars, rettv)
12777 typval_T *argvars UNUSED;
12778 typval_T *rettv;
12780 int n = 0;
12781 buf_T *buf;
12783 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12784 if (n < buf->b_fnum)
12785 n = buf->b_fnum;
12787 rettv->vval.v_number = n;
12791 * "len()" function
12793 static void
12794 f_len(argvars, rettv)
12795 typval_T *argvars;
12796 typval_T *rettv;
12798 switch (argvars[0].v_type)
12800 case VAR_STRING:
12801 case VAR_NUMBER:
12802 rettv->vval.v_number = (varnumber_T)STRLEN(
12803 get_tv_string(&argvars[0]));
12804 break;
12805 case VAR_LIST:
12806 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
12807 break;
12808 case VAR_DICT:
12809 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
12810 break;
12811 default:
12812 EMSG(_("E701: Invalid type for len()"));
12813 break;
12817 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
12819 static void
12820 libcall_common(argvars, rettv, type)
12821 typval_T *argvars;
12822 typval_T *rettv;
12823 int type;
12825 #ifdef FEAT_LIBCALL
12826 char_u *string_in;
12827 char_u **string_result;
12828 int nr_result;
12829 #endif
12831 rettv->v_type = type;
12832 if (type != VAR_NUMBER)
12833 rettv->vval.v_string = NULL;
12835 if (check_restricted() || check_secure())
12836 return;
12838 #ifdef FEAT_LIBCALL
12839 /* The first two args must be strings, otherwise its meaningless */
12840 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
12842 string_in = NULL;
12843 if (argvars[2].v_type == VAR_STRING)
12844 string_in = argvars[2].vval.v_string;
12845 if (type == VAR_NUMBER)
12846 string_result = NULL;
12847 else
12848 string_result = &rettv->vval.v_string;
12849 if (mch_libcall(argvars[0].vval.v_string,
12850 argvars[1].vval.v_string,
12851 string_in,
12852 argvars[2].vval.v_number,
12853 string_result,
12854 &nr_result) == OK
12855 && type == VAR_NUMBER)
12856 rettv->vval.v_number = nr_result;
12858 #endif
12862 * "libcall()" function
12864 static void
12865 f_libcall(argvars, rettv)
12866 typval_T *argvars;
12867 typval_T *rettv;
12869 libcall_common(argvars, rettv, VAR_STRING);
12873 * "libcallnr()" function
12875 static void
12876 f_libcallnr(argvars, rettv)
12877 typval_T *argvars;
12878 typval_T *rettv;
12880 libcall_common(argvars, rettv, VAR_NUMBER);
12884 * "line(string)" function
12886 static void
12887 f_line(argvars, rettv)
12888 typval_T *argvars;
12889 typval_T *rettv;
12891 linenr_T lnum = 0;
12892 pos_T *fp;
12893 int fnum;
12895 fp = var2fpos(&argvars[0], TRUE, &fnum);
12896 if (fp != NULL)
12897 lnum = fp->lnum;
12898 rettv->vval.v_number = lnum;
12902 * "line2byte(lnum)" function
12904 static void
12905 f_line2byte(argvars, rettv)
12906 typval_T *argvars UNUSED;
12907 typval_T *rettv;
12909 #ifndef FEAT_BYTEOFF
12910 rettv->vval.v_number = -1;
12911 #else
12912 linenr_T lnum;
12914 lnum = get_tv_lnum(argvars);
12915 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
12916 rettv->vval.v_number = -1;
12917 else
12918 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
12919 if (rettv->vval.v_number >= 0)
12920 ++rettv->vval.v_number;
12921 #endif
12925 * "lispindent(lnum)" function
12927 static void
12928 f_lispindent(argvars, rettv)
12929 typval_T *argvars;
12930 typval_T *rettv;
12932 #ifdef FEAT_LISP
12933 pos_T pos;
12934 linenr_T lnum;
12936 pos = curwin->w_cursor;
12937 lnum = get_tv_lnum(argvars);
12938 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12940 curwin->w_cursor.lnum = lnum;
12941 rettv->vval.v_number = get_lisp_indent();
12942 curwin->w_cursor = pos;
12944 else
12945 #endif
12946 rettv->vval.v_number = -1;
12950 * "localtime()" function
12952 static void
12953 f_localtime(argvars, rettv)
12954 typval_T *argvars UNUSED;
12955 typval_T *rettv;
12957 rettv->vval.v_number = (varnumber_T)time(NULL);
12960 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
12962 static void
12963 get_maparg(argvars, rettv, exact)
12964 typval_T *argvars;
12965 typval_T *rettv;
12966 int exact;
12968 char_u *keys;
12969 char_u *which;
12970 char_u buf[NUMBUFLEN];
12971 char_u *keys_buf = NULL;
12972 char_u *rhs;
12973 int mode;
12974 garray_T ga;
12975 int abbr = FALSE;
12977 /* return empty string for failure */
12978 rettv->v_type = VAR_STRING;
12979 rettv->vval.v_string = NULL;
12981 keys = get_tv_string(&argvars[0]);
12982 if (*keys == NUL)
12983 return;
12985 if (argvars[1].v_type != VAR_UNKNOWN)
12987 which = get_tv_string_buf_chk(&argvars[1], buf);
12988 if (argvars[2].v_type != VAR_UNKNOWN)
12989 abbr = get_tv_number(&argvars[2]);
12991 else
12992 which = (char_u *)"";
12993 if (which == NULL)
12994 return;
12996 mode = get_map_mode(&which, 0);
12998 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
12999 rhs = check_map(keys, mode, exact, FALSE, abbr);
13000 vim_free(keys_buf);
13001 if (rhs != NULL)
13003 ga_init(&ga);
13004 ga.ga_itemsize = 1;
13005 ga.ga_growsize = 40;
13007 while (*rhs != NUL)
13008 ga_concat(&ga, str2special(&rhs, FALSE));
13010 ga_append(&ga, NUL);
13011 rettv->vval.v_string = (char_u *)ga.ga_data;
13015 #ifdef FEAT_FLOAT
13017 * "log10()" function
13019 static void
13020 f_log10(argvars, rettv)
13021 typval_T *argvars;
13022 typval_T *rettv;
13024 float_T f;
13026 rettv->v_type = VAR_FLOAT;
13027 if (get_float_arg(argvars, &f) == OK)
13028 rettv->vval.v_float = log10(f);
13029 else
13030 rettv->vval.v_float = 0.0;
13032 #endif
13035 * "map()" function
13037 static void
13038 f_map(argvars, rettv)
13039 typval_T *argvars;
13040 typval_T *rettv;
13042 filter_map(argvars, rettv, TRUE);
13046 * "maparg()" function
13048 static void
13049 f_maparg(argvars, rettv)
13050 typval_T *argvars;
13051 typval_T *rettv;
13053 get_maparg(argvars, rettv, TRUE);
13057 * "mapcheck()" function
13059 static void
13060 f_mapcheck(argvars, rettv)
13061 typval_T *argvars;
13062 typval_T *rettv;
13064 get_maparg(argvars, rettv, FALSE);
13067 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
13069 static void
13070 find_some_match(argvars, rettv, type)
13071 typval_T *argvars;
13072 typval_T *rettv;
13073 int type;
13075 char_u *str = NULL;
13076 char_u *expr = NULL;
13077 char_u *pat;
13078 regmatch_T regmatch;
13079 char_u patbuf[NUMBUFLEN];
13080 char_u strbuf[NUMBUFLEN];
13081 char_u *save_cpo;
13082 long start = 0;
13083 long nth = 1;
13084 colnr_T startcol = 0;
13085 int match = 0;
13086 list_T *l = NULL;
13087 listitem_T *li = NULL;
13088 long idx = 0;
13089 char_u *tofree = NULL;
13091 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
13092 save_cpo = p_cpo;
13093 p_cpo = (char_u *)"";
13095 rettv->vval.v_number = -1;
13096 if (type == 3)
13098 /* return empty list when there are no matches */
13099 if (rettv_list_alloc(rettv) == FAIL)
13100 goto theend;
13102 else if (type == 2)
13104 rettv->v_type = VAR_STRING;
13105 rettv->vval.v_string = NULL;
13108 if (argvars[0].v_type == VAR_LIST)
13110 if ((l = argvars[0].vval.v_list) == NULL)
13111 goto theend;
13112 li = l->lv_first;
13114 else
13115 expr = str = get_tv_string(&argvars[0]);
13117 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
13118 if (pat == NULL)
13119 goto theend;
13121 if (argvars[2].v_type != VAR_UNKNOWN)
13123 int error = FALSE;
13125 start = get_tv_number_chk(&argvars[2], &error);
13126 if (error)
13127 goto theend;
13128 if (l != NULL)
13130 li = list_find(l, start);
13131 if (li == NULL)
13132 goto theend;
13133 idx = l->lv_idx; /* use the cached index */
13135 else
13137 if (start < 0)
13138 start = 0;
13139 if (start > (long)STRLEN(str))
13140 goto theend;
13141 /* When "count" argument is there ignore matches before "start",
13142 * otherwise skip part of the string. Differs when pattern is "^"
13143 * or "\<". */
13144 if (argvars[3].v_type != VAR_UNKNOWN)
13145 startcol = start;
13146 else
13147 str += start;
13150 if (argvars[3].v_type != VAR_UNKNOWN)
13151 nth = get_tv_number_chk(&argvars[3], &error);
13152 if (error)
13153 goto theend;
13156 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
13157 if (regmatch.regprog != NULL)
13159 regmatch.rm_ic = p_ic;
13161 for (;;)
13163 if (l != NULL)
13165 if (li == NULL)
13167 match = FALSE;
13168 break;
13170 vim_free(tofree);
13171 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
13172 if (str == NULL)
13173 break;
13176 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
13178 if (match && --nth <= 0)
13179 break;
13180 if (l == NULL && !match)
13181 break;
13183 /* Advance to just after the match. */
13184 if (l != NULL)
13186 li = li->li_next;
13187 ++idx;
13189 else
13191 #ifdef FEAT_MBYTE
13192 startcol = (colnr_T)(regmatch.startp[0]
13193 + (*mb_ptr2len)(regmatch.startp[0]) - str);
13194 #else
13195 startcol = regmatch.startp[0] + 1 - str;
13196 #endif
13200 if (match)
13202 if (type == 3)
13204 int i;
13206 /* return list with matched string and submatches */
13207 for (i = 0; i < NSUBEXP; ++i)
13209 if (regmatch.endp[i] == NULL)
13211 if (list_append_string(rettv->vval.v_list,
13212 (char_u *)"", 0) == FAIL)
13213 break;
13215 else if (list_append_string(rettv->vval.v_list,
13216 regmatch.startp[i],
13217 (int)(regmatch.endp[i] - regmatch.startp[i]))
13218 == FAIL)
13219 break;
13222 else if (type == 2)
13224 /* return matched string */
13225 if (l != NULL)
13226 copy_tv(&li->li_tv, rettv);
13227 else
13228 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
13229 (int)(regmatch.endp[0] - regmatch.startp[0]));
13231 else if (l != NULL)
13232 rettv->vval.v_number = idx;
13233 else
13235 if (type != 0)
13236 rettv->vval.v_number =
13237 (varnumber_T)(regmatch.startp[0] - str);
13238 else
13239 rettv->vval.v_number =
13240 (varnumber_T)(regmatch.endp[0] - str);
13241 rettv->vval.v_number += (varnumber_T)(str - expr);
13244 vim_free(regmatch.regprog);
13247 theend:
13248 vim_free(tofree);
13249 p_cpo = save_cpo;
13253 * "match()" function
13255 static void
13256 f_match(argvars, rettv)
13257 typval_T *argvars;
13258 typval_T *rettv;
13260 find_some_match(argvars, rettv, 1);
13264 * "matchadd()" function
13266 static void
13267 f_matchadd(argvars, rettv)
13268 typval_T *argvars;
13269 typval_T *rettv;
13271 #ifdef FEAT_SEARCH_EXTRA
13272 char_u buf[NUMBUFLEN];
13273 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
13274 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
13275 int prio = 10; /* default priority */
13276 int id = -1;
13277 int error = FALSE;
13279 rettv->vval.v_number = -1;
13281 if (grp == NULL || pat == NULL)
13282 return;
13283 if (argvars[2].v_type != VAR_UNKNOWN)
13285 prio = get_tv_number_chk(&argvars[2], &error);
13286 if (argvars[3].v_type != VAR_UNKNOWN)
13287 id = get_tv_number_chk(&argvars[3], &error);
13289 if (error == TRUE)
13290 return;
13291 if (id >= 1 && id <= 3)
13293 EMSGN("E798: ID is reserved for \":match\": %ld", id);
13294 return;
13297 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
13298 #endif
13302 * "matcharg()" function
13304 static void
13305 f_matcharg(argvars, rettv)
13306 typval_T *argvars;
13307 typval_T *rettv;
13309 if (rettv_list_alloc(rettv) == OK)
13311 #ifdef FEAT_SEARCH_EXTRA
13312 int id = get_tv_number(&argvars[0]);
13313 matchitem_T *m;
13315 if (id >= 1 && id <= 3)
13317 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
13319 list_append_string(rettv->vval.v_list,
13320 syn_id2name(m->hlg_id), -1);
13321 list_append_string(rettv->vval.v_list, m->pattern, -1);
13323 else
13325 list_append_string(rettv->vval.v_list, NUL, -1);
13326 list_append_string(rettv->vval.v_list, NUL, -1);
13329 #endif
13334 * "matchdelete()" function
13336 static void
13337 f_matchdelete(argvars, rettv)
13338 typval_T *argvars;
13339 typval_T *rettv;
13341 #ifdef FEAT_SEARCH_EXTRA
13342 rettv->vval.v_number = match_delete(curwin,
13343 (int)get_tv_number(&argvars[0]), TRUE);
13344 #endif
13348 * "matchend()" function
13350 static void
13351 f_matchend(argvars, rettv)
13352 typval_T *argvars;
13353 typval_T *rettv;
13355 find_some_match(argvars, rettv, 0);
13359 * "matchlist()" function
13361 static void
13362 f_matchlist(argvars, rettv)
13363 typval_T *argvars;
13364 typval_T *rettv;
13366 find_some_match(argvars, rettv, 3);
13370 * "matchstr()" function
13372 static void
13373 f_matchstr(argvars, rettv)
13374 typval_T *argvars;
13375 typval_T *rettv;
13377 find_some_match(argvars, rettv, 2);
13380 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
13382 static void
13383 max_min(argvars, rettv, domax)
13384 typval_T *argvars;
13385 typval_T *rettv;
13386 int domax;
13388 long n = 0;
13389 long i;
13390 int error = FALSE;
13392 if (argvars[0].v_type == VAR_LIST)
13394 list_T *l;
13395 listitem_T *li;
13397 l = argvars[0].vval.v_list;
13398 if (l != NULL)
13400 li = l->lv_first;
13401 if (li != NULL)
13403 n = get_tv_number_chk(&li->li_tv, &error);
13404 for (;;)
13406 li = li->li_next;
13407 if (li == NULL)
13408 break;
13409 i = get_tv_number_chk(&li->li_tv, &error);
13410 if (domax ? i > n : i < n)
13411 n = i;
13416 else if (argvars[0].v_type == VAR_DICT)
13418 dict_T *d;
13419 int first = TRUE;
13420 hashitem_T *hi;
13421 int todo;
13423 d = argvars[0].vval.v_dict;
13424 if (d != NULL)
13426 todo = (int)d->dv_hashtab.ht_used;
13427 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13429 if (!HASHITEM_EMPTY(hi))
13431 --todo;
13432 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
13433 if (first)
13435 n = i;
13436 first = FALSE;
13438 else if (domax ? i > n : i < n)
13439 n = i;
13444 else
13445 EMSG(_(e_listdictarg));
13446 rettv->vval.v_number = error ? 0 : n;
13450 * "max()" function
13452 static void
13453 f_max(argvars, rettv)
13454 typval_T *argvars;
13455 typval_T *rettv;
13457 max_min(argvars, rettv, TRUE);
13461 * "migemo()" function
13463 static void
13464 f_migemo(argvars, rettv)
13465 typval_T *argvars;
13466 typval_T *rettv;
13468 char_u* arg = get_tv_string(&argvars[0]);
13470 rettv->v_type = VAR_STRING;
13471 #ifdef USE_MIGEMO
13472 rettv->vval.v_string = query_migemo(arg);
13473 #else
13474 rettv->vval.v_string = vim_strsave(arg);
13475 #endif
13479 * "min()" function
13481 static void
13482 f_min(argvars, rettv)
13483 typval_T *argvars;
13484 typval_T *rettv;
13486 max_min(argvars, rettv, FALSE);
13489 static int mkdir_recurse __ARGS((char_u *dir, int prot));
13492 * Create the directory in which "dir" is located, and higher levels when
13493 * needed.
13495 static int
13496 mkdir_recurse(dir, prot)
13497 char_u *dir;
13498 int prot;
13500 char_u *p;
13501 char_u *updir;
13502 int r = FAIL;
13504 /* Get end of directory name in "dir".
13505 * We're done when it's "/" or "c:/". */
13506 p = gettail_sep(dir);
13507 if (p <= get_past_head(dir))
13508 return OK;
13510 /* If the directory exists we're done. Otherwise: create it.*/
13511 updir = vim_strnsave(dir, (int)(p - dir));
13512 if (updir == NULL)
13513 return FAIL;
13514 if (mch_isdir(updir))
13515 r = OK;
13516 else if (mkdir_recurse(updir, prot) == OK)
13517 r = vim_mkdir_emsg(updir, prot);
13518 vim_free(updir);
13519 return r;
13522 #ifdef vim_mkdir
13524 * "mkdir()" function
13526 static void
13527 f_mkdir(argvars, rettv)
13528 typval_T *argvars;
13529 typval_T *rettv;
13531 char_u *dir;
13532 char_u buf[NUMBUFLEN];
13533 int prot = 0755;
13535 rettv->vval.v_number = FAIL;
13536 if (check_restricted() || check_secure())
13537 return;
13539 dir = get_tv_string_buf(&argvars[0], buf);
13540 if (argvars[1].v_type != VAR_UNKNOWN)
13542 if (argvars[2].v_type != VAR_UNKNOWN)
13543 prot = get_tv_number_chk(&argvars[2], NULL);
13544 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
13545 mkdir_recurse(dir, prot);
13547 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
13549 #endif
13552 * "mode()" function
13554 static void
13555 f_mode(argvars, rettv)
13556 typval_T *argvars;
13557 typval_T *rettv;
13559 char_u buf[3];
13561 buf[1] = NUL;
13562 buf[2] = NUL;
13564 #ifdef FEAT_VISUAL
13565 if (VIsual_active)
13567 if (VIsual_select)
13568 buf[0] = VIsual_mode + 's' - 'v';
13569 else
13570 buf[0] = VIsual_mode;
13572 else
13573 #endif
13574 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
13575 || State == CONFIRM)
13577 buf[0] = 'r';
13578 if (State == ASKMORE)
13579 buf[1] = 'm';
13580 else if (State == CONFIRM)
13581 buf[1] = '?';
13583 else if (State == EXTERNCMD)
13584 buf[0] = '!';
13585 else if (State & INSERT)
13587 #ifdef FEAT_VREPLACE
13588 if (State & VREPLACE_FLAG)
13590 buf[0] = 'R';
13591 buf[1] = 'v';
13593 else
13594 #endif
13595 if (State & REPLACE_FLAG)
13596 buf[0] = 'R';
13597 else
13598 buf[0] = 'i';
13600 else if (State & CMDLINE)
13602 buf[0] = 'c';
13603 if (exmode_active)
13604 buf[1] = 'v';
13606 else if (exmode_active)
13608 buf[0] = 'c';
13609 buf[1] = 'e';
13611 else
13613 buf[0] = 'n';
13614 if (finish_op)
13615 buf[1] = 'o';
13618 /* Clear out the minor mode when the argument is not a non-zero number or
13619 * non-empty string. */
13620 if (!non_zero_arg(&argvars[0]))
13621 buf[1] = NUL;
13623 rettv->vval.v_string = vim_strsave(buf);
13624 rettv->v_type = VAR_STRING;
13627 #ifdef FEAT_MZSCHEME
13629 * "mzeval()" function
13631 static void
13632 f_mzeval(argvars, rettv)
13633 typval_T *argvars;
13634 typval_T *rettv;
13636 char_u *str;
13637 char_u buf[NUMBUFLEN];
13639 str = get_tv_string_buf(&argvars[0], buf);
13640 do_mzeval(str, rettv);
13642 #endif
13645 * "nextnonblank()" function
13647 static void
13648 f_nextnonblank(argvars, rettv)
13649 typval_T *argvars;
13650 typval_T *rettv;
13652 linenr_T lnum;
13654 for (lnum = get_tv_lnum(argvars); ; ++lnum)
13656 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
13658 lnum = 0;
13659 break;
13661 if (*skipwhite(ml_get(lnum)) != NUL)
13662 break;
13664 rettv->vval.v_number = lnum;
13668 * "nr2char()" function
13670 static void
13671 f_nr2char(argvars, rettv)
13672 typval_T *argvars;
13673 typval_T *rettv;
13675 char_u buf[NUMBUFLEN];
13677 #ifdef FEAT_MBYTE
13678 if (has_mbyte)
13679 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
13680 else
13681 #endif
13683 buf[0] = (char_u)get_tv_number(&argvars[0]);
13684 buf[1] = NUL;
13686 rettv->v_type = VAR_STRING;
13687 rettv->vval.v_string = vim_strsave(buf);
13691 * "pathshorten()" function
13693 static void
13694 f_pathshorten(argvars, rettv)
13695 typval_T *argvars;
13696 typval_T *rettv;
13698 char_u *p;
13700 rettv->v_type = VAR_STRING;
13701 p = get_tv_string_chk(&argvars[0]);
13702 if (p == NULL)
13703 rettv->vval.v_string = NULL;
13704 else
13706 p = vim_strsave(p);
13707 rettv->vval.v_string = p;
13708 if (p != NULL)
13709 shorten_dir(p);
13713 #ifdef FEAT_FLOAT
13715 * "pow()" function
13717 static void
13718 f_pow(argvars, rettv)
13719 typval_T *argvars;
13720 typval_T *rettv;
13722 float_T fx, fy;
13724 rettv->v_type = VAR_FLOAT;
13725 if (get_float_arg(argvars, &fx) == OK
13726 && get_float_arg(&argvars[1], &fy) == OK)
13727 rettv->vval.v_float = pow(fx, fy);
13728 else
13729 rettv->vval.v_float = 0.0;
13731 #endif
13734 * "prevnonblank()" function
13736 static void
13737 f_prevnonblank(argvars, rettv)
13738 typval_T *argvars;
13739 typval_T *rettv;
13741 linenr_T lnum;
13743 lnum = get_tv_lnum(argvars);
13744 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
13745 lnum = 0;
13746 else
13747 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
13748 --lnum;
13749 rettv->vval.v_number = lnum;
13752 #ifdef HAVE_STDARG_H
13753 /* This dummy va_list is here because:
13754 * - passing a NULL pointer doesn't work when va_list isn't a pointer
13755 * - locally in the function results in a "used before set" warning
13756 * - using va_start() to initialize it gives "function with fixed args" error */
13757 static va_list ap;
13758 #endif
13761 * "printf()" function
13763 static void
13764 f_printf(argvars, rettv)
13765 typval_T *argvars;
13766 typval_T *rettv;
13768 rettv->v_type = VAR_STRING;
13769 rettv->vval.v_string = NULL;
13770 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
13772 char_u buf[NUMBUFLEN];
13773 int len;
13774 char_u *s;
13775 int saved_did_emsg = did_emsg;
13776 char *fmt;
13778 /* Get the required length, allocate the buffer and do it for real. */
13779 did_emsg = FALSE;
13780 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
13781 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
13782 if (!did_emsg)
13784 s = alloc(len + 1);
13785 if (s != NULL)
13787 rettv->vval.v_string = s;
13788 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
13791 did_emsg |= saved_did_emsg;
13793 #endif
13797 * "pumvisible()" function
13799 static void
13800 f_pumvisible(argvars, rettv)
13801 typval_T *argvars UNUSED;
13802 typval_T *rettv UNUSED;
13804 #ifdef FEAT_INS_EXPAND
13805 if (pum_visible())
13806 rettv->vval.v_number = 1;
13807 #endif
13811 * "range()" function
13813 static void
13814 f_range(argvars, rettv)
13815 typval_T *argvars;
13816 typval_T *rettv;
13818 long start;
13819 long end;
13820 long stride = 1;
13821 long i;
13822 int error = FALSE;
13824 start = get_tv_number_chk(&argvars[0], &error);
13825 if (argvars[1].v_type == VAR_UNKNOWN)
13827 end = start - 1;
13828 start = 0;
13830 else
13832 end = get_tv_number_chk(&argvars[1], &error);
13833 if (argvars[2].v_type != VAR_UNKNOWN)
13834 stride = get_tv_number_chk(&argvars[2], &error);
13837 if (error)
13838 return; /* type error; errmsg already given */
13839 if (stride == 0)
13840 EMSG(_("E726: Stride is zero"));
13841 else if (stride > 0 ? end + 1 < start : end - 1 > start)
13842 EMSG(_("E727: Start past end"));
13843 else
13845 if (rettv_list_alloc(rettv) == OK)
13846 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
13847 if (list_append_number(rettv->vval.v_list,
13848 (varnumber_T)i) == FAIL)
13849 break;
13854 * "readfile()" function
13856 static void
13857 f_readfile(argvars, rettv)
13858 typval_T *argvars;
13859 typval_T *rettv;
13861 int binary = FALSE;
13862 char_u *fname;
13863 FILE *fd;
13864 listitem_T *li;
13865 #define FREAD_SIZE 200 /* optimized for text lines */
13866 char_u buf[FREAD_SIZE];
13867 int readlen; /* size of last fread() */
13868 int buflen; /* nr of valid chars in buf[] */
13869 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
13870 int tolist; /* first byte in buf[] still to be put in list */
13871 int chop; /* how many CR to chop off */
13872 char_u *prev = NULL; /* previously read bytes, if any */
13873 int prevlen = 0; /* length of "prev" if not NULL */
13874 char_u *s;
13875 int len;
13876 long maxline = MAXLNUM;
13877 long cnt = 0;
13879 if (argvars[1].v_type != VAR_UNKNOWN)
13881 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
13882 binary = TRUE;
13883 if (argvars[2].v_type != VAR_UNKNOWN)
13884 maxline = get_tv_number(&argvars[2]);
13887 if (rettv_list_alloc(rettv) == FAIL)
13888 return;
13890 /* Always open the file in binary mode, library functions have a mind of
13891 * their own about CR-LF conversion. */
13892 fname = get_tv_string(&argvars[0]);
13893 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
13895 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
13896 return;
13899 filtd = 0;
13900 while (cnt < maxline || maxline < 0)
13902 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
13903 buflen = filtd + readlen;
13904 tolist = 0;
13905 for ( ; filtd < buflen || readlen <= 0; ++filtd)
13907 if (buf[filtd] == '\n' || readlen <= 0)
13909 /* Only when in binary mode add an empty list item when the
13910 * last line ends in a '\n'. */
13911 if (!binary && readlen == 0 && filtd == 0)
13912 break;
13914 /* Found end-of-line or end-of-file: add a text line to the
13915 * list. */
13916 chop = 0;
13917 if (!binary)
13918 while (filtd - chop - 1 >= tolist
13919 && buf[filtd - chop - 1] == '\r')
13920 ++chop;
13921 len = filtd - tolist - chop;
13922 if (prev == NULL)
13923 s = vim_strnsave(buf + tolist, len);
13924 else
13926 s = alloc((unsigned)(prevlen + len + 1));
13927 if (s != NULL)
13929 mch_memmove(s, prev, prevlen);
13930 vim_free(prev);
13931 prev = NULL;
13932 mch_memmove(s + prevlen, buf + tolist, len);
13933 s[prevlen + len] = NUL;
13936 tolist = filtd + 1;
13938 li = listitem_alloc();
13939 if (li == NULL)
13941 vim_free(s);
13942 break;
13944 li->li_tv.v_type = VAR_STRING;
13945 li->li_tv.v_lock = 0;
13946 li->li_tv.vval.v_string = s;
13947 list_append(rettv->vval.v_list, li);
13949 if (++cnt >= maxline && maxline >= 0)
13950 break;
13951 if (readlen <= 0)
13952 break;
13954 else if (buf[filtd] == NUL)
13955 buf[filtd] = '\n';
13957 if (readlen <= 0)
13958 break;
13960 if (tolist == 0)
13962 /* "buf" is full, need to move text to an allocated buffer */
13963 if (prev == NULL)
13965 prev = vim_strnsave(buf, buflen);
13966 prevlen = buflen;
13968 else
13970 s = alloc((unsigned)(prevlen + buflen));
13971 if (s != NULL)
13973 mch_memmove(s, prev, prevlen);
13974 mch_memmove(s + prevlen, buf, buflen);
13975 vim_free(prev);
13976 prev = s;
13977 prevlen += buflen;
13980 filtd = 0;
13982 else
13984 mch_memmove(buf, buf + tolist, buflen - tolist);
13985 filtd -= tolist;
13990 * For a negative line count use only the lines at the end of the file,
13991 * free the rest.
13993 if (maxline < 0)
13994 while (cnt > -maxline)
13996 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
13997 --cnt;
14000 vim_free(prev);
14001 fclose(fd);
14004 #if defined(FEAT_RELTIME)
14005 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
14008 * Convert a List to proftime_T.
14009 * Return FAIL when there is something wrong.
14011 static int
14012 list2proftime(arg, tm)
14013 typval_T *arg;
14014 proftime_T *tm;
14016 long n1, n2;
14017 int error = FALSE;
14019 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
14020 || arg->vval.v_list->lv_len != 2)
14021 return FAIL;
14022 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
14023 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
14024 # ifdef WIN3264
14025 tm->HighPart = n1;
14026 tm->LowPart = n2;
14027 # else
14028 tm->tv_sec = n1;
14029 tm->tv_usec = n2;
14030 # endif
14031 return error ? FAIL : OK;
14033 #endif /* FEAT_RELTIME */
14036 * "reltime()" function
14038 static void
14039 f_reltime(argvars, rettv)
14040 typval_T *argvars;
14041 typval_T *rettv;
14043 #ifdef FEAT_RELTIME
14044 proftime_T res;
14045 proftime_T start;
14047 if (argvars[0].v_type == VAR_UNKNOWN)
14049 /* No arguments: get current time. */
14050 profile_start(&res);
14052 else if (argvars[1].v_type == VAR_UNKNOWN)
14054 if (list2proftime(&argvars[0], &res) == FAIL)
14055 return;
14056 profile_end(&res);
14058 else
14060 /* Two arguments: compute the difference. */
14061 if (list2proftime(&argvars[0], &start) == FAIL
14062 || list2proftime(&argvars[1], &res) == FAIL)
14063 return;
14064 profile_sub(&res, &start);
14067 if (rettv_list_alloc(rettv) == OK)
14069 long n1, n2;
14071 # ifdef WIN3264
14072 n1 = res.HighPart;
14073 n2 = res.LowPart;
14074 # else
14075 n1 = res.tv_sec;
14076 n2 = res.tv_usec;
14077 # endif
14078 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
14079 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
14081 #endif
14085 * "reltimestr()" function
14087 static void
14088 f_reltimestr(argvars, rettv)
14089 typval_T *argvars;
14090 typval_T *rettv;
14092 #ifdef FEAT_RELTIME
14093 proftime_T tm;
14094 #endif
14096 rettv->v_type = VAR_STRING;
14097 rettv->vval.v_string = NULL;
14098 #ifdef FEAT_RELTIME
14099 if (list2proftime(&argvars[0], &tm) == OK)
14100 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
14101 #endif
14104 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
14105 static void make_connection __ARGS((void));
14106 static int check_connection __ARGS((void));
14108 static void
14109 make_connection()
14111 if (X_DISPLAY == NULL
14112 # ifdef FEAT_GUI
14113 && !gui.in_use
14114 # endif
14117 x_force_connect = TRUE;
14118 setup_term_clip();
14119 x_force_connect = FALSE;
14123 static int
14124 check_connection()
14126 make_connection();
14127 if (X_DISPLAY == NULL)
14129 EMSG(_("E240: No connection to Vim server"));
14130 return FAIL;
14132 return OK;
14134 #endif
14136 #ifdef FEAT_CLIENTSERVER
14137 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
14139 static void
14140 remote_common(argvars, rettv, expr)
14141 typval_T *argvars;
14142 typval_T *rettv;
14143 int expr;
14145 char_u *server_name;
14146 char_u *keys;
14147 char_u *r = NULL;
14148 char_u buf[NUMBUFLEN];
14149 # ifdef WIN32
14150 HWND w;
14151 # else
14152 Window w;
14153 # endif
14155 if (check_restricted() || check_secure())
14156 return;
14158 # ifdef FEAT_X11
14159 if (check_connection() == FAIL)
14160 return;
14161 # endif
14163 server_name = get_tv_string_chk(&argvars[0]);
14164 if (server_name == NULL)
14165 return; /* type error; errmsg already given */
14166 keys = get_tv_string_buf(&argvars[1], buf);
14167 # ifdef WIN32
14168 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14169 # else
14170 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
14171 < 0)
14172 # endif
14174 if (r != NULL)
14175 EMSG(r); /* sending worked but evaluation failed */
14176 else
14177 EMSG2(_("E241: Unable to send to %s"), server_name);
14178 return;
14181 rettv->vval.v_string = r;
14183 if (argvars[2].v_type != VAR_UNKNOWN)
14185 dictitem_T v;
14186 char_u str[30];
14187 char_u *idvar;
14189 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
14190 v.di_tv.v_type = VAR_STRING;
14191 v.di_tv.vval.v_string = vim_strsave(str);
14192 idvar = get_tv_string_chk(&argvars[2]);
14193 if (idvar != NULL)
14194 set_var(idvar, &v.di_tv, FALSE);
14195 vim_free(v.di_tv.vval.v_string);
14198 #endif
14201 * "remote_expr()" function
14203 static void
14204 f_remote_expr(argvars, rettv)
14205 typval_T *argvars UNUSED;
14206 typval_T *rettv;
14208 rettv->v_type = VAR_STRING;
14209 rettv->vval.v_string = NULL;
14210 #ifdef FEAT_CLIENTSERVER
14211 remote_common(argvars, rettv, TRUE);
14212 #endif
14216 * "remote_foreground()" function
14218 static void
14219 f_remote_foreground(argvars, rettv)
14220 typval_T *argvars UNUSED;
14221 typval_T *rettv UNUSED;
14223 #ifdef FEAT_CLIENTSERVER
14224 # ifdef WIN32
14225 /* On Win32 it's done in this application. */
14227 char_u *server_name = get_tv_string_chk(&argvars[0]);
14229 if (server_name != NULL)
14230 serverForeground(server_name);
14232 # else
14233 /* Send a foreground() expression to the server. */
14234 argvars[1].v_type = VAR_STRING;
14235 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
14236 argvars[2].v_type = VAR_UNKNOWN;
14237 remote_common(argvars, rettv, TRUE);
14238 vim_free(argvars[1].vval.v_string);
14239 # endif
14240 #endif
14243 static void
14244 f_remote_peek(argvars, rettv)
14245 typval_T *argvars UNUSED;
14246 typval_T *rettv;
14248 #ifdef FEAT_CLIENTSERVER
14249 dictitem_T v;
14250 char_u *s = NULL;
14251 # ifdef WIN32
14252 long_u n = 0;
14253 # endif
14254 char_u *serverid;
14256 if (check_restricted() || check_secure())
14258 rettv->vval.v_number = -1;
14259 return;
14261 serverid = get_tv_string_chk(&argvars[0]);
14262 if (serverid == NULL)
14264 rettv->vval.v_number = -1;
14265 return; /* type error; errmsg already given */
14267 # ifdef WIN32
14268 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14269 if (n == 0)
14270 rettv->vval.v_number = -1;
14271 else
14273 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
14274 rettv->vval.v_number = (s != NULL);
14276 # else
14277 if (check_connection() == FAIL)
14278 return;
14280 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
14281 serverStrToWin(serverid), &s);
14282 # endif
14284 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
14286 char_u *retvar;
14288 v.di_tv.v_type = VAR_STRING;
14289 v.di_tv.vval.v_string = vim_strsave(s);
14290 retvar = get_tv_string_chk(&argvars[1]);
14291 if (retvar != NULL)
14292 set_var(retvar, &v.di_tv, FALSE);
14293 vim_free(v.di_tv.vval.v_string);
14295 #else
14296 rettv->vval.v_number = -1;
14297 #endif
14300 static void
14301 f_remote_read(argvars, rettv)
14302 typval_T *argvars UNUSED;
14303 typval_T *rettv;
14305 char_u *r = NULL;
14307 #ifdef FEAT_CLIENTSERVER
14308 char_u *serverid = get_tv_string_chk(&argvars[0]);
14310 if (serverid != NULL && !check_restricted() && !check_secure())
14312 # ifdef WIN32
14313 /* The server's HWND is encoded in the 'id' parameter */
14314 long_u n = 0;
14316 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14317 if (n != 0)
14318 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
14319 if (r == NULL)
14320 # else
14321 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
14322 serverStrToWin(serverid), &r, FALSE) < 0)
14323 # endif
14324 EMSG(_("E277: Unable to read a server reply"));
14326 #endif
14327 rettv->v_type = VAR_STRING;
14328 rettv->vval.v_string = r;
14332 * "remote_send()" function
14334 static void
14335 f_remote_send(argvars, rettv)
14336 typval_T *argvars UNUSED;
14337 typval_T *rettv;
14339 rettv->v_type = VAR_STRING;
14340 rettv->vval.v_string = NULL;
14341 #ifdef FEAT_CLIENTSERVER
14342 remote_common(argvars, rettv, FALSE);
14343 #endif
14347 * "remove()" function
14349 static void
14350 f_remove(argvars, rettv)
14351 typval_T *argvars;
14352 typval_T *rettv;
14354 list_T *l;
14355 listitem_T *item, *item2;
14356 listitem_T *li;
14357 long idx;
14358 long end;
14359 char_u *key;
14360 dict_T *d;
14361 dictitem_T *di;
14363 if (argvars[0].v_type == VAR_DICT)
14365 if (argvars[2].v_type != VAR_UNKNOWN)
14366 EMSG2(_(e_toomanyarg), "remove()");
14367 else if ((d = argvars[0].vval.v_dict) != NULL
14368 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
14370 key = get_tv_string_chk(&argvars[1]);
14371 if (key != NULL)
14373 di = dict_find(d, key, -1);
14374 if (di == NULL)
14375 EMSG2(_(e_dictkey), key);
14376 else
14378 *rettv = di->di_tv;
14379 init_tv(&di->di_tv);
14380 dictitem_remove(d, di);
14385 else if (argvars[0].v_type != VAR_LIST)
14386 EMSG2(_(e_listdictarg), "remove()");
14387 else if ((l = argvars[0].vval.v_list) != NULL
14388 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
14390 int error = FALSE;
14392 idx = get_tv_number_chk(&argvars[1], &error);
14393 if (error)
14394 ; /* type error: do nothing, errmsg already given */
14395 else if ((item = list_find(l, idx)) == NULL)
14396 EMSGN(_(e_listidx), idx);
14397 else
14399 if (argvars[2].v_type == VAR_UNKNOWN)
14401 /* Remove one item, return its value. */
14402 list_remove(l, item, item);
14403 *rettv = item->li_tv;
14404 vim_free(item);
14406 else
14408 /* Remove range of items, return list with values. */
14409 end = get_tv_number_chk(&argvars[2], &error);
14410 if (error)
14411 ; /* type error: do nothing */
14412 else if ((item2 = list_find(l, end)) == NULL)
14413 EMSGN(_(e_listidx), end);
14414 else
14416 int cnt = 0;
14418 for (li = item; li != NULL; li = li->li_next)
14420 ++cnt;
14421 if (li == item2)
14422 break;
14424 if (li == NULL) /* didn't find "item2" after "item" */
14425 EMSG(_(e_invrange));
14426 else
14428 list_remove(l, item, item2);
14429 if (rettv_list_alloc(rettv) == OK)
14431 l = rettv->vval.v_list;
14432 l->lv_first = item;
14433 l->lv_last = item2;
14434 item->li_prev = NULL;
14435 item2->li_next = NULL;
14436 l->lv_len = cnt;
14446 * "rename({from}, {to})" function
14448 static void
14449 f_rename(argvars, rettv)
14450 typval_T *argvars;
14451 typval_T *rettv;
14453 char_u buf[NUMBUFLEN];
14455 if (check_restricted() || check_secure())
14456 rettv->vval.v_number = -1;
14457 else
14458 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
14459 get_tv_string_buf(&argvars[1], buf));
14463 * "repeat()" function
14465 static void
14466 f_repeat(argvars, rettv)
14467 typval_T *argvars;
14468 typval_T *rettv;
14470 char_u *p;
14471 int n;
14472 int slen;
14473 int len;
14474 char_u *r;
14475 int i;
14477 n = get_tv_number(&argvars[1]);
14478 if (argvars[0].v_type == VAR_LIST)
14480 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
14481 while (n-- > 0)
14482 if (list_extend(rettv->vval.v_list,
14483 argvars[0].vval.v_list, NULL) == FAIL)
14484 break;
14486 else
14488 p = get_tv_string(&argvars[0]);
14489 rettv->v_type = VAR_STRING;
14490 rettv->vval.v_string = NULL;
14492 slen = (int)STRLEN(p);
14493 len = slen * n;
14494 if (len <= 0)
14495 return;
14497 r = alloc(len + 1);
14498 if (r != NULL)
14500 for (i = 0; i < n; i++)
14501 mch_memmove(r + i * slen, p, (size_t)slen);
14502 r[len] = NUL;
14505 rettv->vval.v_string = r;
14510 * "resolve()" function
14512 static void
14513 f_resolve(argvars, rettv)
14514 typval_T *argvars;
14515 typval_T *rettv;
14517 char_u *p;
14519 p = get_tv_string(&argvars[0]);
14520 #ifdef FEAT_SHORTCUT
14522 char_u *v = NULL;
14524 v = mch_resolve_shortcut(p);
14525 if (v != NULL)
14526 rettv->vval.v_string = v;
14527 else
14528 rettv->vval.v_string = vim_strsave(p);
14530 #else
14531 # ifdef HAVE_READLINK
14533 char_u buf[MAXPATHL + 1];
14534 char_u *cpy;
14535 int len;
14536 char_u *remain = NULL;
14537 char_u *q;
14538 int is_relative_to_current = FALSE;
14539 int has_trailing_pathsep = FALSE;
14540 int limit = 100;
14542 p = vim_strsave(p);
14544 if (p[0] == '.' && (vim_ispathsep(p[1])
14545 || (p[1] == '.' && (vim_ispathsep(p[2])))))
14546 is_relative_to_current = TRUE;
14548 len = STRLEN(p);
14549 if (len > 0 && after_pathsep(p, p + len))
14550 has_trailing_pathsep = TRUE;
14552 q = getnextcomp(p);
14553 if (*q != NUL)
14555 /* Separate the first path component in "p", and keep the
14556 * remainder (beginning with the path separator). */
14557 remain = vim_strsave(q - 1);
14558 q[-1] = NUL;
14561 for (;;)
14563 for (;;)
14565 len = readlink((char *)p, (char *)buf, MAXPATHL);
14566 if (len <= 0)
14567 break;
14568 buf[len] = NUL;
14570 if (limit-- == 0)
14572 vim_free(p);
14573 vim_free(remain);
14574 EMSG(_("E655: Too many symbolic links (cycle?)"));
14575 rettv->vval.v_string = NULL;
14576 goto fail;
14579 /* Ensure that the result will have a trailing path separator
14580 * if the argument has one. */
14581 if (remain == NULL && has_trailing_pathsep)
14582 add_pathsep(buf);
14584 /* Separate the first path component in the link value and
14585 * concatenate the remainders. */
14586 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
14587 if (*q != NUL)
14589 if (remain == NULL)
14590 remain = vim_strsave(q - 1);
14591 else
14593 cpy = concat_str(q - 1, remain);
14594 if (cpy != NULL)
14596 vim_free(remain);
14597 remain = cpy;
14600 q[-1] = NUL;
14603 q = gettail(p);
14604 if (q > p && *q == NUL)
14606 /* Ignore trailing path separator. */
14607 q[-1] = NUL;
14608 q = gettail(p);
14610 if (q > p && !mch_isFullName(buf))
14612 /* symlink is relative to directory of argument */
14613 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
14614 if (cpy != NULL)
14616 STRCPY(cpy, p);
14617 STRCPY(gettail(cpy), buf);
14618 vim_free(p);
14619 p = cpy;
14622 else
14624 vim_free(p);
14625 p = vim_strsave(buf);
14629 if (remain == NULL)
14630 break;
14632 /* Append the first path component of "remain" to "p". */
14633 q = getnextcomp(remain + 1);
14634 len = q - remain - (*q != NUL);
14635 cpy = vim_strnsave(p, STRLEN(p) + len);
14636 if (cpy != NULL)
14638 STRNCAT(cpy, remain, len);
14639 vim_free(p);
14640 p = cpy;
14642 /* Shorten "remain". */
14643 if (*q != NUL)
14644 STRMOVE(remain, q - 1);
14645 else
14647 vim_free(remain);
14648 remain = NULL;
14652 /* If the result is a relative path name, make it explicitly relative to
14653 * the current directory if and only if the argument had this form. */
14654 if (!vim_ispathsep(*p))
14656 if (is_relative_to_current
14657 && *p != NUL
14658 && !(p[0] == '.'
14659 && (p[1] == NUL
14660 || vim_ispathsep(p[1])
14661 || (p[1] == '.'
14662 && (p[2] == NUL
14663 || vim_ispathsep(p[2]))))))
14665 /* Prepend "./". */
14666 cpy = concat_str((char_u *)"./", p);
14667 if (cpy != NULL)
14669 vim_free(p);
14670 p = cpy;
14673 else if (!is_relative_to_current)
14675 /* Strip leading "./". */
14676 q = p;
14677 while (q[0] == '.' && vim_ispathsep(q[1]))
14678 q += 2;
14679 if (q > p)
14680 STRMOVE(p, p + 2);
14684 /* Ensure that the result will have no trailing path separator
14685 * if the argument had none. But keep "/" or "//". */
14686 if (!has_trailing_pathsep)
14688 q = p + STRLEN(p);
14689 if (after_pathsep(p, q))
14690 *gettail_sep(p) = NUL;
14693 rettv->vval.v_string = p;
14695 # else
14696 rettv->vval.v_string = vim_strsave(p);
14697 # endif
14698 #endif
14700 simplify_filename(rettv->vval.v_string);
14702 #ifdef HAVE_READLINK
14703 fail:
14704 #endif
14705 rettv->v_type = VAR_STRING;
14709 * "reverse({list})" function
14711 static void
14712 f_reverse(argvars, rettv)
14713 typval_T *argvars;
14714 typval_T *rettv;
14716 list_T *l;
14717 listitem_T *li, *ni;
14719 if (argvars[0].v_type != VAR_LIST)
14720 EMSG2(_(e_listarg), "reverse()");
14721 else if ((l = argvars[0].vval.v_list) != NULL
14722 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
14724 li = l->lv_last;
14725 l->lv_first = l->lv_last = NULL;
14726 l->lv_len = 0;
14727 while (li != NULL)
14729 ni = li->li_prev;
14730 list_append(l, li);
14731 li = ni;
14733 rettv->vval.v_list = l;
14734 rettv->v_type = VAR_LIST;
14735 ++l->lv_refcount;
14736 l->lv_idx = l->lv_len - l->lv_idx - 1;
14740 #define SP_NOMOVE 0x01 /* don't move cursor */
14741 #define SP_REPEAT 0x02 /* repeat to find outer pair */
14742 #define SP_RETCOUNT 0x04 /* return matchcount */
14743 #define SP_SETPCMARK 0x08 /* set previous context mark */
14744 #define SP_START 0x10 /* accept match at start position */
14745 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
14746 #define SP_END 0x40 /* leave cursor at end of match */
14748 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
14751 * Get flags for a search function.
14752 * Possibly sets "p_ws".
14753 * Returns BACKWARD, FORWARD or zero (for an error).
14755 static int
14756 get_search_arg(varp, flagsp)
14757 typval_T *varp;
14758 int *flagsp;
14760 int dir = FORWARD;
14761 char_u *flags;
14762 char_u nbuf[NUMBUFLEN];
14763 int mask;
14765 if (varp->v_type != VAR_UNKNOWN)
14767 flags = get_tv_string_buf_chk(varp, nbuf);
14768 if (flags == NULL)
14769 return 0; /* type error; errmsg already given */
14770 while (*flags != NUL)
14772 switch (*flags)
14774 case 'b': dir = BACKWARD; break;
14775 case 'w': p_ws = TRUE; break;
14776 case 'W': p_ws = FALSE; break;
14777 default: mask = 0;
14778 if (flagsp != NULL)
14779 switch (*flags)
14781 case 'c': mask = SP_START; break;
14782 case 'e': mask = SP_END; break;
14783 case 'm': mask = SP_RETCOUNT; break;
14784 case 'n': mask = SP_NOMOVE; break;
14785 case 'p': mask = SP_SUBPAT; break;
14786 case 'r': mask = SP_REPEAT; break;
14787 case 's': mask = SP_SETPCMARK; break;
14789 if (mask == 0)
14791 EMSG2(_(e_invarg2), flags);
14792 dir = 0;
14794 else
14795 *flagsp |= mask;
14797 if (dir == 0)
14798 break;
14799 ++flags;
14802 return dir;
14806 * Shared by search() and searchpos() functions
14808 static int
14809 search_cmn(argvars, match_pos, flagsp)
14810 typval_T *argvars;
14811 pos_T *match_pos;
14812 int *flagsp;
14814 int flags;
14815 char_u *pat;
14816 pos_T pos;
14817 pos_T save_cursor;
14818 int save_p_ws = p_ws;
14819 int dir;
14820 int retval = 0; /* default: FAIL */
14821 long lnum_stop = 0;
14822 proftime_T tm;
14823 #ifdef FEAT_RELTIME
14824 long time_limit = 0;
14825 #endif
14826 int options = SEARCH_KEEP;
14827 int subpatnum;
14829 pat = get_tv_string(&argvars[0]);
14830 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
14831 if (dir == 0)
14832 goto theend;
14833 flags = *flagsp;
14834 if (flags & SP_START)
14835 options |= SEARCH_START;
14836 if (flags & SP_END)
14837 options |= SEARCH_END;
14839 /* Optional arguments: line number to stop searching and timeout. */
14840 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
14842 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
14843 if (lnum_stop < 0)
14844 goto theend;
14845 #ifdef FEAT_RELTIME
14846 if (argvars[3].v_type != VAR_UNKNOWN)
14848 time_limit = get_tv_number_chk(&argvars[3], NULL);
14849 if (time_limit < 0)
14850 goto theend;
14852 #endif
14855 #ifdef FEAT_RELTIME
14856 /* Set the time limit, if there is one. */
14857 profile_setlimit(time_limit, &tm);
14858 #endif
14861 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
14862 * Check to make sure only those flags are set.
14863 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
14864 * flags cannot be set. Check for that condition also.
14866 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
14867 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14869 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
14870 goto theend;
14873 pos = save_cursor = curwin->w_cursor;
14874 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14875 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
14876 if (subpatnum != FAIL)
14878 if (flags & SP_SUBPAT)
14879 retval = subpatnum;
14880 else
14881 retval = pos.lnum;
14882 if (flags & SP_SETPCMARK)
14883 setpcmark();
14884 curwin->w_cursor = pos;
14885 if (match_pos != NULL)
14887 /* Store the match cursor position */
14888 match_pos->lnum = pos.lnum;
14889 match_pos->col = pos.col + 1;
14891 /* "/$" will put the cursor after the end of the line, may need to
14892 * correct that here */
14893 check_cursor();
14896 /* If 'n' flag is used: restore cursor position. */
14897 if (flags & SP_NOMOVE)
14898 curwin->w_cursor = save_cursor;
14899 else
14900 curwin->w_set_curswant = TRUE;
14901 theend:
14902 p_ws = save_p_ws;
14904 return retval;
14907 #ifdef FEAT_FLOAT
14909 * "round({float})" function
14911 static void
14912 f_round(argvars, rettv)
14913 typval_T *argvars;
14914 typval_T *rettv;
14916 float_T f;
14918 rettv->v_type = VAR_FLOAT;
14919 if (get_float_arg(argvars, &f) == OK)
14920 /* round() is not in C90, use ceil() or floor() instead. */
14921 rettv->vval.v_float = f > 0 ? floor(f + 0.5) : ceil(f - 0.5);
14922 else
14923 rettv->vval.v_float = 0.0;
14925 #endif
14928 * "search()" function
14930 static void
14931 f_search(argvars, rettv)
14932 typval_T *argvars;
14933 typval_T *rettv;
14935 int flags = 0;
14937 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
14941 * "searchdecl()" function
14943 static void
14944 f_searchdecl(argvars, rettv)
14945 typval_T *argvars;
14946 typval_T *rettv;
14948 int locally = 1;
14949 int thisblock = 0;
14950 int error = FALSE;
14951 char_u *name;
14953 rettv->vval.v_number = 1; /* default: FAIL */
14955 name = get_tv_string_chk(&argvars[0]);
14956 if (argvars[1].v_type != VAR_UNKNOWN)
14958 locally = get_tv_number_chk(&argvars[1], &error) == 0;
14959 if (!error && argvars[2].v_type != VAR_UNKNOWN)
14960 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
14962 if (!error && name != NULL)
14963 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
14964 locally, thisblock, SEARCH_KEEP) == FAIL;
14968 * Used by searchpair() and searchpairpos()
14970 static int
14971 searchpair_cmn(argvars, match_pos)
14972 typval_T *argvars;
14973 pos_T *match_pos;
14975 char_u *spat, *mpat, *epat;
14976 char_u *skip;
14977 int save_p_ws = p_ws;
14978 int dir;
14979 int flags = 0;
14980 char_u nbuf1[NUMBUFLEN];
14981 char_u nbuf2[NUMBUFLEN];
14982 char_u nbuf3[NUMBUFLEN];
14983 int retval = 0; /* default: FAIL */
14984 long lnum_stop = 0;
14985 long time_limit = 0;
14987 /* Get the three pattern arguments: start, middle, end. */
14988 spat = get_tv_string_chk(&argvars[0]);
14989 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
14990 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
14991 if (spat == NULL || mpat == NULL || epat == NULL)
14992 goto theend; /* type error */
14994 /* Handle the optional fourth argument: flags */
14995 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
14996 if (dir == 0)
14997 goto theend;
14999 /* Don't accept SP_END or SP_SUBPAT.
15000 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
15002 if ((flags & (SP_END | SP_SUBPAT)) != 0
15003 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
15005 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
15006 goto theend;
15009 /* Using 'r' implies 'W', otherwise it doesn't work. */
15010 if (flags & SP_REPEAT)
15011 p_ws = FALSE;
15013 /* Optional fifth argument: skip expression */
15014 if (argvars[3].v_type == VAR_UNKNOWN
15015 || argvars[4].v_type == VAR_UNKNOWN)
15016 skip = (char_u *)"";
15017 else
15019 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
15020 if (argvars[5].v_type != VAR_UNKNOWN)
15022 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
15023 if (lnum_stop < 0)
15024 goto theend;
15025 #ifdef FEAT_RELTIME
15026 if (argvars[6].v_type != VAR_UNKNOWN)
15028 time_limit = get_tv_number_chk(&argvars[6], NULL);
15029 if (time_limit < 0)
15030 goto theend;
15032 #endif
15035 if (skip == NULL)
15036 goto theend; /* type error */
15038 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
15039 match_pos, lnum_stop, time_limit);
15041 theend:
15042 p_ws = save_p_ws;
15044 return retval;
15048 * "searchpair()" function
15050 static void
15051 f_searchpair(argvars, rettv)
15052 typval_T *argvars;
15053 typval_T *rettv;
15055 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
15059 * "searchpairpos()" function
15061 static void
15062 f_searchpairpos(argvars, rettv)
15063 typval_T *argvars;
15064 typval_T *rettv;
15066 pos_T match_pos;
15067 int lnum = 0;
15068 int col = 0;
15070 if (rettv_list_alloc(rettv) == FAIL)
15071 return;
15073 if (searchpair_cmn(argvars, &match_pos) > 0)
15075 lnum = match_pos.lnum;
15076 col = match_pos.col;
15079 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15080 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15084 * Search for a start/middle/end thing.
15085 * Used by searchpair(), see its documentation for the details.
15086 * Returns 0 or -1 for no match,
15088 long
15089 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
15090 lnum_stop, time_limit)
15091 char_u *spat; /* start pattern */
15092 char_u *mpat; /* middle pattern */
15093 char_u *epat; /* end pattern */
15094 int dir; /* BACKWARD or FORWARD */
15095 char_u *skip; /* skip expression */
15096 int flags; /* SP_SETPCMARK and other SP_ values */
15097 pos_T *match_pos;
15098 linenr_T lnum_stop; /* stop at this line if not zero */
15099 long time_limit; /* stop after this many msec */
15101 char_u *save_cpo;
15102 char_u *pat, *pat2 = NULL, *pat3 = NULL;
15103 long retval = 0;
15104 pos_T pos;
15105 pos_T firstpos;
15106 pos_T foundpos;
15107 pos_T save_cursor;
15108 pos_T save_pos;
15109 int n;
15110 int r;
15111 int nest = 1;
15112 int err;
15113 int options = SEARCH_KEEP;
15114 proftime_T tm;
15116 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15117 save_cpo = p_cpo;
15118 p_cpo = empty_option;
15120 #ifdef FEAT_RELTIME
15121 /* Set the time limit, if there is one. */
15122 profile_setlimit(time_limit, &tm);
15123 #endif
15125 /* Make two search patterns: start/end (pat2, for in nested pairs) and
15126 * start/middle/end (pat3, for the top pair). */
15127 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
15128 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
15129 if (pat2 == NULL || pat3 == NULL)
15130 goto theend;
15131 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
15132 if (*mpat == NUL)
15133 STRCPY(pat3, pat2);
15134 else
15135 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
15136 spat, epat, mpat);
15137 if (flags & SP_START)
15138 options |= SEARCH_START;
15140 save_cursor = curwin->w_cursor;
15141 pos = curwin->w_cursor;
15142 clearpos(&firstpos);
15143 clearpos(&foundpos);
15144 pat = pat3;
15145 for (;;)
15147 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15148 options, RE_SEARCH, lnum_stop, &tm);
15149 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
15150 /* didn't find it or found the first match again: FAIL */
15151 break;
15153 if (firstpos.lnum == 0)
15154 firstpos = pos;
15155 if (equalpos(pos, foundpos))
15157 /* Found the same position again. Can happen with a pattern that
15158 * has "\zs" at the end and searching backwards. Advance one
15159 * character and try again. */
15160 if (dir == BACKWARD)
15161 decl(&pos);
15162 else
15163 incl(&pos);
15165 foundpos = pos;
15167 /* clear the start flag to avoid getting stuck here */
15168 options &= ~SEARCH_START;
15170 /* If the skip pattern matches, ignore this match. */
15171 if (*skip != NUL)
15173 save_pos = curwin->w_cursor;
15174 curwin->w_cursor = pos;
15175 r = eval_to_bool(skip, &err, NULL, FALSE);
15176 curwin->w_cursor = save_pos;
15177 if (err)
15179 /* Evaluating {skip} caused an error, break here. */
15180 curwin->w_cursor = save_cursor;
15181 retval = -1;
15182 break;
15184 if (r)
15185 continue;
15188 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
15190 /* Found end when searching backwards or start when searching
15191 * forward: nested pair. */
15192 ++nest;
15193 pat = pat2; /* nested, don't search for middle */
15195 else
15197 /* Found end when searching forward or start when searching
15198 * backward: end of (nested) pair; or found middle in outer pair. */
15199 if (--nest == 1)
15200 pat = pat3; /* outer level, search for middle */
15203 if (nest == 0)
15205 /* Found the match: return matchcount or line number. */
15206 if (flags & SP_RETCOUNT)
15207 ++retval;
15208 else
15209 retval = pos.lnum;
15210 if (flags & SP_SETPCMARK)
15211 setpcmark();
15212 curwin->w_cursor = pos;
15213 if (!(flags & SP_REPEAT))
15214 break;
15215 nest = 1; /* search for next unmatched */
15219 if (match_pos != NULL)
15221 /* Store the match cursor position */
15222 match_pos->lnum = curwin->w_cursor.lnum;
15223 match_pos->col = curwin->w_cursor.col + 1;
15226 /* If 'n' flag is used or search failed: restore cursor position. */
15227 if ((flags & SP_NOMOVE) || retval == 0)
15228 curwin->w_cursor = save_cursor;
15230 theend:
15231 vim_free(pat2);
15232 vim_free(pat3);
15233 if (p_cpo == empty_option)
15234 p_cpo = save_cpo;
15235 else
15236 /* Darn, evaluating the {skip} expression changed the value. */
15237 free_string_option(save_cpo);
15239 return retval;
15243 * "searchpos()" function
15245 static void
15246 f_searchpos(argvars, rettv)
15247 typval_T *argvars;
15248 typval_T *rettv;
15250 pos_T match_pos;
15251 int lnum = 0;
15252 int col = 0;
15253 int n;
15254 int flags = 0;
15256 if (rettv_list_alloc(rettv) == FAIL)
15257 return;
15259 n = search_cmn(argvars, &match_pos, &flags);
15260 if (n > 0)
15262 lnum = match_pos.lnum;
15263 col = match_pos.col;
15266 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15267 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15268 if (flags & SP_SUBPAT)
15269 list_append_number(rettv->vval.v_list, (varnumber_T)n);
15273 static void
15274 f_server2client(argvars, rettv)
15275 typval_T *argvars UNUSED;
15276 typval_T *rettv;
15278 #ifdef FEAT_CLIENTSERVER
15279 char_u buf[NUMBUFLEN];
15280 char_u *server = get_tv_string_chk(&argvars[0]);
15281 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
15283 rettv->vval.v_number = -1;
15284 if (server == NULL || reply == NULL)
15285 return;
15286 if (check_restricted() || check_secure())
15287 return;
15288 # ifdef FEAT_X11
15289 if (check_connection() == FAIL)
15290 return;
15291 # endif
15293 if (serverSendReply(server, reply) < 0)
15295 EMSG(_("E258: Unable to send to client"));
15296 return;
15298 rettv->vval.v_number = 0;
15299 #else
15300 rettv->vval.v_number = -1;
15301 #endif
15304 static void
15305 f_serverlist(argvars, rettv)
15306 typval_T *argvars UNUSED;
15307 typval_T *rettv;
15309 char_u *r = NULL;
15311 #ifdef FEAT_CLIENTSERVER
15312 # ifdef WIN32
15313 r = serverGetVimNames();
15314 # else
15315 make_connection();
15316 if (X_DISPLAY != NULL)
15317 r = serverGetVimNames(X_DISPLAY);
15318 # endif
15319 #endif
15320 rettv->v_type = VAR_STRING;
15321 rettv->vval.v_string = r;
15325 * "setbufvar()" function
15327 static void
15328 f_setbufvar(argvars, rettv)
15329 typval_T *argvars;
15330 typval_T *rettv UNUSED;
15332 buf_T *buf;
15333 aco_save_T aco;
15334 char_u *varname, *bufvarname;
15335 typval_T *varp;
15336 char_u nbuf[NUMBUFLEN];
15338 if (check_restricted() || check_secure())
15339 return;
15340 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
15341 varname = get_tv_string_chk(&argvars[1]);
15342 buf = get_buf_tv(&argvars[0]);
15343 varp = &argvars[2];
15345 if (buf != NULL && varname != NULL && varp != NULL)
15347 /* set curbuf to be our buf, temporarily */
15348 aucmd_prepbuf(&aco, buf);
15350 if (*varname == '&')
15352 long numval;
15353 char_u *strval;
15354 int error = FALSE;
15356 ++varname;
15357 numval = get_tv_number_chk(varp, &error);
15358 strval = get_tv_string_buf_chk(varp, nbuf);
15359 if (!error && strval != NULL)
15360 set_option_value(varname, numval, strval, OPT_LOCAL);
15362 else
15364 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
15365 if (bufvarname != NULL)
15367 STRCPY(bufvarname, "b:");
15368 STRCPY(bufvarname + 2, varname);
15369 set_var(bufvarname, varp, TRUE);
15370 vim_free(bufvarname);
15374 /* reset notion of buffer */
15375 aucmd_restbuf(&aco);
15380 * "setcmdpos()" function
15382 static void
15383 f_setcmdpos(argvars, rettv)
15384 typval_T *argvars;
15385 typval_T *rettv;
15387 int pos = (int)get_tv_number(&argvars[0]) - 1;
15389 if (pos >= 0)
15390 rettv->vval.v_number = set_cmdline_pos(pos);
15394 * "setline()" function
15396 static void
15397 f_setline(argvars, rettv)
15398 typval_T *argvars;
15399 typval_T *rettv;
15401 linenr_T lnum;
15402 char_u *line = NULL;
15403 list_T *l = NULL;
15404 listitem_T *li = NULL;
15405 long added = 0;
15406 linenr_T lcount = curbuf->b_ml.ml_line_count;
15408 lnum = get_tv_lnum(&argvars[0]);
15409 if (argvars[1].v_type == VAR_LIST)
15411 l = argvars[1].vval.v_list;
15412 li = l->lv_first;
15414 else
15415 line = get_tv_string_chk(&argvars[1]);
15417 /* default result is zero == OK */
15418 for (;;)
15420 if (l != NULL)
15422 /* list argument, get next string */
15423 if (li == NULL)
15424 break;
15425 line = get_tv_string_chk(&li->li_tv);
15426 li = li->li_next;
15429 rettv->vval.v_number = 1; /* FAIL */
15430 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
15431 break;
15432 if (lnum <= curbuf->b_ml.ml_line_count)
15434 /* existing line, replace it */
15435 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
15437 changed_bytes(lnum, 0);
15438 if (lnum == curwin->w_cursor.lnum)
15439 check_cursor_col();
15440 rettv->vval.v_number = 0; /* OK */
15443 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
15445 /* lnum is one past the last line, append the line */
15446 ++added;
15447 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
15448 rettv->vval.v_number = 0; /* OK */
15451 if (l == NULL) /* only one string argument */
15452 break;
15453 ++lnum;
15456 if (added > 0)
15457 appended_lines_mark(lcount, added);
15460 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
15463 * Used by "setqflist()" and "setloclist()" functions
15465 static void
15466 set_qf_ll_list(wp, list_arg, action_arg, rettv)
15467 win_T *wp UNUSED;
15468 typval_T *list_arg UNUSED;
15469 typval_T *action_arg UNUSED;
15470 typval_T *rettv;
15472 #ifdef FEAT_QUICKFIX
15473 char_u *act;
15474 int action = ' ';
15475 #endif
15477 rettv->vval.v_number = -1;
15479 #ifdef FEAT_QUICKFIX
15480 if (list_arg->v_type != VAR_LIST)
15481 EMSG(_(e_listreq));
15482 else
15484 list_T *l = list_arg->vval.v_list;
15486 if (action_arg->v_type == VAR_STRING)
15488 act = get_tv_string_chk(action_arg);
15489 if (act == NULL)
15490 return; /* type error; errmsg already given */
15491 if (*act == 'a' || *act == 'r')
15492 action = *act;
15495 if (l != NULL && set_errorlist(wp, l, action) == OK)
15496 rettv->vval.v_number = 0;
15498 #endif
15502 * "setloclist()" function
15504 static void
15505 f_setloclist(argvars, rettv)
15506 typval_T *argvars;
15507 typval_T *rettv;
15509 win_T *win;
15511 rettv->vval.v_number = -1;
15513 win = find_win_by_nr(&argvars[0], NULL);
15514 if (win != NULL)
15515 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
15519 * "setmatches()" function
15521 static void
15522 f_setmatches(argvars, rettv)
15523 typval_T *argvars;
15524 typval_T *rettv;
15526 #ifdef FEAT_SEARCH_EXTRA
15527 list_T *l;
15528 listitem_T *li;
15529 dict_T *d;
15531 rettv->vval.v_number = -1;
15532 if (argvars[0].v_type != VAR_LIST)
15534 EMSG(_(e_listreq));
15535 return;
15537 if ((l = argvars[0].vval.v_list) != NULL)
15540 /* To some extent make sure that we are dealing with a list from
15541 * "getmatches()". */
15542 li = l->lv_first;
15543 while (li != NULL)
15545 if (li->li_tv.v_type != VAR_DICT
15546 || (d = li->li_tv.vval.v_dict) == NULL)
15548 EMSG(_(e_invarg));
15549 return;
15551 if (!(dict_find(d, (char_u *)"group", -1) != NULL
15552 && dict_find(d, (char_u *)"pattern", -1) != NULL
15553 && dict_find(d, (char_u *)"priority", -1) != NULL
15554 && dict_find(d, (char_u *)"id", -1) != NULL))
15556 EMSG(_(e_invarg));
15557 return;
15559 li = li->li_next;
15562 clear_matches(curwin);
15563 li = l->lv_first;
15564 while (li != NULL)
15566 d = li->li_tv.vval.v_dict;
15567 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
15568 get_dict_string(d, (char_u *)"pattern", FALSE),
15569 (int)get_dict_number(d, (char_u *)"priority"),
15570 (int)get_dict_number(d, (char_u *)"id"));
15571 li = li->li_next;
15573 rettv->vval.v_number = 0;
15575 #endif
15579 * "setpos()" function
15581 static void
15582 f_setpos(argvars, rettv)
15583 typval_T *argvars;
15584 typval_T *rettv;
15586 pos_T pos;
15587 int fnum;
15588 char_u *name;
15590 rettv->vval.v_number = -1;
15591 name = get_tv_string_chk(argvars);
15592 if (name != NULL)
15594 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
15596 if (--pos.col < 0)
15597 pos.col = 0;
15598 if (name[0] == '.' && name[1] == NUL)
15600 /* set cursor */
15601 if (fnum == curbuf->b_fnum)
15603 curwin->w_cursor = pos;
15604 check_cursor();
15605 rettv->vval.v_number = 0;
15607 else
15608 EMSG(_(e_invarg));
15610 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
15612 /* set mark */
15613 if (setmark_pos(name[1], &pos, fnum) == OK)
15614 rettv->vval.v_number = 0;
15616 else
15617 EMSG(_(e_invarg));
15623 * "setqflist()" function
15625 static void
15626 f_setqflist(argvars, rettv)
15627 typval_T *argvars;
15628 typval_T *rettv;
15630 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
15634 * "setreg()" function
15636 static void
15637 f_setreg(argvars, rettv)
15638 typval_T *argvars;
15639 typval_T *rettv;
15641 int regname;
15642 char_u *strregname;
15643 char_u *stropt;
15644 char_u *strval;
15645 int append;
15646 char_u yank_type;
15647 long block_len;
15649 block_len = -1;
15650 yank_type = MAUTO;
15651 append = FALSE;
15653 strregname = get_tv_string_chk(argvars);
15654 rettv->vval.v_number = 1; /* FAIL is default */
15656 if (strregname == NULL)
15657 return; /* type error; errmsg already given */
15658 regname = *strregname;
15659 if (regname == 0 || regname == '@')
15660 regname = '"';
15661 else if (regname == '=')
15662 return;
15664 if (argvars[2].v_type != VAR_UNKNOWN)
15666 stropt = get_tv_string_chk(&argvars[2]);
15667 if (stropt == NULL)
15668 return; /* type error */
15669 for (; *stropt != NUL; ++stropt)
15670 switch (*stropt)
15672 case 'a': case 'A': /* append */
15673 append = TRUE;
15674 break;
15675 case 'v': case 'c': /* character-wise selection */
15676 yank_type = MCHAR;
15677 break;
15678 case 'V': case 'l': /* line-wise selection */
15679 yank_type = MLINE;
15680 break;
15681 #ifdef FEAT_VISUAL
15682 case 'b': case Ctrl_V: /* block-wise selection */
15683 yank_type = MBLOCK;
15684 if (VIM_ISDIGIT(stropt[1]))
15686 ++stropt;
15687 block_len = getdigits(&stropt) - 1;
15688 --stropt;
15690 break;
15691 #endif
15695 strval = get_tv_string_chk(&argvars[1]);
15696 if (strval != NULL)
15697 write_reg_contents_ex(regname, strval, -1,
15698 append, yank_type, block_len);
15699 rettv->vval.v_number = 0;
15703 * "settabwinvar()" function
15705 static void
15706 f_settabwinvar(argvars, rettv)
15707 typval_T *argvars;
15708 typval_T *rettv;
15710 setwinvar(argvars, rettv, 1);
15714 * "setwinvar()" function
15716 static void
15717 f_setwinvar(argvars, rettv)
15718 typval_T *argvars;
15719 typval_T *rettv;
15721 setwinvar(argvars, rettv, 0);
15725 * "setwinvar()" and "settabwinvar()" functions
15727 static void
15728 setwinvar(argvars, rettv, off)
15729 typval_T *argvars;
15730 typval_T *rettv UNUSED;
15731 int off;
15733 win_T *win;
15734 #ifdef FEAT_WINDOWS
15735 win_T *save_curwin;
15736 tabpage_T *save_curtab;
15737 #endif
15738 char_u *varname, *winvarname;
15739 typval_T *varp;
15740 char_u nbuf[NUMBUFLEN];
15741 tabpage_T *tp;
15743 if (check_restricted() || check_secure())
15744 return;
15746 #ifdef FEAT_WINDOWS
15747 if (off == 1)
15748 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
15749 else
15750 tp = curtab;
15751 #endif
15752 win = find_win_by_nr(&argvars[off], tp);
15753 varname = get_tv_string_chk(&argvars[off + 1]);
15754 varp = &argvars[off + 2];
15756 if (win != NULL && varname != NULL && varp != NULL)
15758 #ifdef FEAT_WINDOWS
15759 /* set curwin to be our win, temporarily */
15760 save_curwin = curwin;
15761 save_curtab = curtab;
15762 goto_tabpage_tp(tp);
15763 if (!win_valid(win))
15764 return;
15765 curwin = win;
15766 curbuf = curwin->w_buffer;
15767 #endif
15769 if (*varname == '&')
15771 long numval;
15772 char_u *strval;
15773 int error = FALSE;
15775 ++varname;
15776 numval = get_tv_number_chk(varp, &error);
15777 strval = get_tv_string_buf_chk(varp, nbuf);
15778 if (!error && strval != NULL)
15779 set_option_value(varname, numval, strval, OPT_LOCAL);
15781 else
15783 winvarname = alloc((unsigned)STRLEN(varname) + 3);
15784 if (winvarname != NULL)
15786 STRCPY(winvarname, "w:");
15787 STRCPY(winvarname + 2, varname);
15788 set_var(winvarname, varp, TRUE);
15789 vim_free(winvarname);
15793 #ifdef FEAT_WINDOWS
15794 /* Restore current tabpage and window, if still valid (autocomands can
15795 * make them invalid). */
15796 if (valid_tabpage(save_curtab))
15797 goto_tabpage_tp(save_curtab);
15798 if (win_valid(save_curwin))
15800 curwin = save_curwin;
15801 curbuf = curwin->w_buffer;
15803 #endif
15808 * "shellescape({string})" function
15810 static void
15811 f_shellescape(argvars, rettv)
15812 typval_T *argvars;
15813 typval_T *rettv;
15815 rettv->vval.v_string = vim_strsave_shellescape(
15816 get_tv_string(&argvars[0]), non_zero_arg(&argvars[1]));
15817 rettv->v_type = VAR_STRING;
15821 * "simplify()" function
15823 static void
15824 f_simplify(argvars, rettv)
15825 typval_T *argvars;
15826 typval_T *rettv;
15828 char_u *p;
15830 p = get_tv_string(&argvars[0]);
15831 rettv->vval.v_string = vim_strsave(p);
15832 simplify_filename(rettv->vval.v_string); /* simplify in place */
15833 rettv->v_type = VAR_STRING;
15836 #ifdef FEAT_FLOAT
15838 * "sin()" function
15840 static void
15841 f_sin(argvars, rettv)
15842 typval_T *argvars;
15843 typval_T *rettv;
15845 float_T f;
15847 rettv->v_type = VAR_FLOAT;
15848 if (get_float_arg(argvars, &f) == OK)
15849 rettv->vval.v_float = sin(f);
15850 else
15851 rettv->vval.v_float = 0.0;
15853 #endif
15855 static int
15856 #ifdef __BORLANDC__
15857 _RTLENTRYF
15858 #endif
15859 item_compare __ARGS((const void *s1, const void *s2));
15860 static int
15861 #ifdef __BORLANDC__
15862 _RTLENTRYF
15863 #endif
15864 item_compare2 __ARGS((const void *s1, const void *s2));
15866 static int item_compare_ic;
15867 static char_u *item_compare_func;
15868 static int item_compare_func_err;
15869 #define ITEM_COMPARE_FAIL 999
15872 * Compare functions for f_sort() below.
15874 static int
15875 #ifdef __BORLANDC__
15876 _RTLENTRYF
15877 #endif
15878 item_compare(s1, s2)
15879 const void *s1;
15880 const void *s2;
15882 char_u *p1, *p2;
15883 char_u *tofree1, *tofree2;
15884 int res;
15885 char_u numbuf1[NUMBUFLEN];
15886 char_u numbuf2[NUMBUFLEN];
15888 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
15889 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
15890 if (p1 == NULL)
15891 p1 = (char_u *)"";
15892 if (p2 == NULL)
15893 p2 = (char_u *)"";
15894 if (item_compare_ic)
15895 res = STRICMP(p1, p2);
15896 else
15897 res = STRCMP(p1, p2);
15898 vim_free(tofree1);
15899 vim_free(tofree2);
15900 return res;
15903 static int
15904 #ifdef __BORLANDC__
15905 _RTLENTRYF
15906 #endif
15907 item_compare2(s1, s2)
15908 const void *s1;
15909 const void *s2;
15911 int res;
15912 typval_T rettv;
15913 typval_T argv[3];
15914 int dummy;
15916 /* shortcut after failure in previous call; compare all items equal */
15917 if (item_compare_func_err)
15918 return 0;
15920 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
15921 * in the copy without changing the original list items. */
15922 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
15923 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
15925 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
15926 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
15927 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
15928 clear_tv(&argv[0]);
15929 clear_tv(&argv[1]);
15931 if (res == FAIL)
15932 res = ITEM_COMPARE_FAIL;
15933 else
15934 res = get_tv_number_chk(&rettv, &item_compare_func_err);
15935 if (item_compare_func_err)
15936 res = ITEM_COMPARE_FAIL; /* return value has wrong type */
15937 clear_tv(&rettv);
15938 return res;
15942 * "sort({list})" function
15944 static void
15945 f_sort(argvars, rettv)
15946 typval_T *argvars;
15947 typval_T *rettv;
15949 list_T *l;
15950 listitem_T *li;
15951 listitem_T **ptrs;
15952 long len;
15953 long i;
15955 if (argvars[0].v_type != VAR_LIST)
15956 EMSG2(_(e_listarg), "sort()");
15957 else
15959 l = argvars[0].vval.v_list;
15960 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
15961 return;
15962 rettv->vval.v_list = l;
15963 rettv->v_type = VAR_LIST;
15964 ++l->lv_refcount;
15966 len = list_len(l);
15967 if (len <= 1)
15968 return; /* short list sorts pretty quickly */
15970 item_compare_ic = FALSE;
15971 item_compare_func = NULL;
15972 if (argvars[1].v_type != VAR_UNKNOWN)
15974 if (argvars[1].v_type == VAR_FUNC)
15975 item_compare_func = argvars[1].vval.v_string;
15976 else
15978 int error = FALSE;
15980 i = get_tv_number_chk(&argvars[1], &error);
15981 if (error)
15982 return; /* type error; errmsg already given */
15983 if (i == 1)
15984 item_compare_ic = TRUE;
15985 else
15986 item_compare_func = get_tv_string(&argvars[1]);
15990 /* Make an array with each entry pointing to an item in the List. */
15991 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
15992 if (ptrs == NULL)
15993 return;
15994 i = 0;
15995 for (li = l->lv_first; li != NULL; li = li->li_next)
15996 ptrs[i++] = li;
15998 item_compare_func_err = FALSE;
15999 /* test the compare function */
16000 if (item_compare_func != NULL
16001 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
16002 == ITEM_COMPARE_FAIL)
16003 EMSG(_("E702: Sort compare function failed"));
16004 else
16006 /* Sort the array with item pointers. */
16007 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
16008 item_compare_func == NULL ? item_compare : item_compare2);
16010 if (!item_compare_func_err)
16012 /* Clear the List and append the items in the sorted order. */
16013 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
16014 l->lv_len = 0;
16015 for (i = 0; i < len; ++i)
16016 list_append(l, ptrs[i]);
16020 vim_free(ptrs);
16025 * "soundfold({word})" function
16027 static void
16028 f_soundfold(argvars, rettv)
16029 typval_T *argvars;
16030 typval_T *rettv;
16032 char_u *s;
16034 rettv->v_type = VAR_STRING;
16035 s = get_tv_string(&argvars[0]);
16036 #ifdef FEAT_SPELL
16037 rettv->vval.v_string = eval_soundfold(s);
16038 #else
16039 rettv->vval.v_string = vim_strsave(s);
16040 #endif
16044 * "spellbadword()" function
16046 static void
16047 f_spellbadword(argvars, rettv)
16048 typval_T *argvars UNUSED;
16049 typval_T *rettv;
16051 char_u *word = (char_u *)"";
16052 hlf_T attr = HLF_COUNT;
16053 int len = 0;
16055 if (rettv_list_alloc(rettv) == FAIL)
16056 return;
16058 #ifdef FEAT_SPELL
16059 if (argvars[0].v_type == VAR_UNKNOWN)
16061 /* Find the start and length of the badly spelled word. */
16062 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
16063 if (len != 0)
16064 word = ml_get_cursor();
16066 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16068 char_u *str = get_tv_string_chk(&argvars[0]);
16069 int capcol = -1;
16071 if (str != NULL)
16073 /* Check the argument for spelling. */
16074 while (*str != NUL)
16076 len = spell_check(curwin, str, &attr, &capcol, FALSE);
16077 if (attr != HLF_COUNT)
16079 word = str;
16080 break;
16082 str += len;
16086 #endif
16088 list_append_string(rettv->vval.v_list, word, len);
16089 list_append_string(rettv->vval.v_list, (char_u *)(
16090 attr == HLF_SPB ? "bad" :
16091 attr == HLF_SPR ? "rare" :
16092 attr == HLF_SPL ? "local" :
16093 attr == HLF_SPC ? "caps" :
16094 ""), -1);
16098 * "spellsuggest()" function
16100 static void
16101 f_spellsuggest(argvars, rettv)
16102 typval_T *argvars UNUSED;
16103 typval_T *rettv;
16105 #ifdef FEAT_SPELL
16106 char_u *str;
16107 int typeerr = FALSE;
16108 int maxcount;
16109 garray_T ga;
16110 int i;
16111 listitem_T *li;
16112 int need_capital = FALSE;
16113 #endif
16115 if (rettv_list_alloc(rettv) == FAIL)
16116 return;
16118 #ifdef FEAT_SPELL
16119 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16121 str = get_tv_string(&argvars[0]);
16122 if (argvars[1].v_type != VAR_UNKNOWN)
16124 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
16125 if (maxcount <= 0)
16126 return;
16127 if (argvars[2].v_type != VAR_UNKNOWN)
16129 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
16130 if (typeerr)
16131 return;
16134 else
16135 maxcount = 25;
16137 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
16139 for (i = 0; i < ga.ga_len; ++i)
16141 str = ((char_u **)ga.ga_data)[i];
16143 li = listitem_alloc();
16144 if (li == NULL)
16145 vim_free(str);
16146 else
16148 li->li_tv.v_type = VAR_STRING;
16149 li->li_tv.v_lock = 0;
16150 li->li_tv.vval.v_string = str;
16151 list_append(rettv->vval.v_list, li);
16154 ga_clear(&ga);
16156 #endif
16159 static void
16160 f_split(argvars, rettv)
16161 typval_T *argvars;
16162 typval_T *rettv;
16164 char_u *str;
16165 char_u *end;
16166 char_u *pat = NULL;
16167 regmatch_T regmatch;
16168 char_u patbuf[NUMBUFLEN];
16169 char_u *save_cpo;
16170 int match;
16171 colnr_T col = 0;
16172 int keepempty = FALSE;
16173 int typeerr = FALSE;
16175 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
16176 save_cpo = p_cpo;
16177 p_cpo = (char_u *)"";
16179 str = get_tv_string(&argvars[0]);
16180 if (argvars[1].v_type != VAR_UNKNOWN)
16182 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16183 if (pat == NULL)
16184 typeerr = TRUE;
16185 if (argvars[2].v_type != VAR_UNKNOWN)
16186 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
16188 if (pat == NULL || *pat == NUL)
16189 pat = (char_u *)"[\\x01- ]\\+";
16191 if (rettv_list_alloc(rettv) == FAIL)
16192 return;
16193 if (typeerr)
16194 return;
16196 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
16197 if (regmatch.regprog != NULL)
16199 regmatch.rm_ic = FALSE;
16200 while (*str != NUL || keepempty)
16202 if (*str == NUL)
16203 match = FALSE; /* empty item at the end */
16204 else
16205 match = vim_regexec_nl(&regmatch, str, col);
16206 if (match)
16207 end = regmatch.startp[0];
16208 else
16209 end = str + STRLEN(str);
16210 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
16211 && *str != NUL && match && end < regmatch.endp[0]))
16213 if (list_append_string(rettv->vval.v_list, str,
16214 (int)(end - str)) == FAIL)
16215 break;
16217 if (!match)
16218 break;
16219 /* Advance to just after the match. */
16220 if (regmatch.endp[0] > str)
16221 col = 0;
16222 else
16224 /* Don't get stuck at the same match. */
16225 #ifdef FEAT_MBYTE
16226 col = (*mb_ptr2len)(regmatch.endp[0]);
16227 #else
16228 col = 1;
16229 #endif
16231 str = regmatch.endp[0];
16234 vim_free(regmatch.regprog);
16237 p_cpo = save_cpo;
16240 #ifdef FEAT_FLOAT
16242 * "sqrt()" function
16244 static void
16245 f_sqrt(argvars, rettv)
16246 typval_T *argvars;
16247 typval_T *rettv;
16249 float_T f;
16251 rettv->v_type = VAR_FLOAT;
16252 if (get_float_arg(argvars, &f) == OK)
16253 rettv->vval.v_float = sqrt(f);
16254 else
16255 rettv->vval.v_float = 0.0;
16259 * "str2float()" function
16261 static void
16262 f_str2float(argvars, rettv)
16263 typval_T *argvars;
16264 typval_T *rettv;
16266 char_u *p = skipwhite(get_tv_string(&argvars[0]));
16268 if (*p == '+')
16269 p = skipwhite(p + 1);
16270 (void)string2float(p, &rettv->vval.v_float);
16271 rettv->v_type = VAR_FLOAT;
16273 #endif
16276 * "str2nr()" function
16278 static void
16279 f_str2nr(argvars, rettv)
16280 typval_T *argvars;
16281 typval_T *rettv;
16283 int base = 10;
16284 char_u *p;
16285 long n;
16287 if (argvars[1].v_type != VAR_UNKNOWN)
16289 base = get_tv_number(&argvars[1]);
16290 if (base != 8 && base != 10 && base != 16)
16292 EMSG(_(e_invarg));
16293 return;
16297 p = skipwhite(get_tv_string(&argvars[0]));
16298 if (*p == '+')
16299 p = skipwhite(p + 1);
16300 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
16301 rettv->vval.v_number = n;
16304 #ifdef HAVE_STRFTIME
16306 * "strftime({format}[, {time}])" function
16308 static void
16309 f_strftime(argvars, rettv)
16310 typval_T *argvars;
16311 typval_T *rettv;
16313 char_u result_buf[256];
16314 struct tm *curtime;
16315 time_t seconds;
16316 char_u *p;
16318 rettv->v_type = VAR_STRING;
16320 p = get_tv_string(&argvars[0]);
16321 if (argvars[1].v_type == VAR_UNKNOWN)
16322 seconds = time(NULL);
16323 else
16324 seconds = (time_t)get_tv_number(&argvars[1]);
16325 curtime = localtime(&seconds);
16326 /* MSVC returns NULL for an invalid value of seconds. */
16327 if (curtime == NULL)
16328 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
16329 else
16331 # ifdef FEAT_MBYTE
16332 vimconv_T conv;
16333 char_u *enc;
16335 conv.vc_type = CONV_NONE;
16336 enc = enc_locale();
16337 convert_setup(&conv, p_enc, enc);
16338 if (conv.vc_type != CONV_NONE)
16339 p = string_convert(&conv, p, NULL);
16340 # endif
16341 if (p != NULL)
16342 (void)strftime((char *)result_buf, sizeof(result_buf),
16343 (char *)p, curtime);
16344 else
16345 result_buf[0] = NUL;
16347 # ifdef FEAT_MBYTE
16348 if (conv.vc_type != CONV_NONE)
16349 vim_free(p);
16350 convert_setup(&conv, enc, p_enc);
16351 if (conv.vc_type != CONV_NONE)
16352 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
16353 else
16354 # endif
16355 rettv->vval.v_string = vim_strsave(result_buf);
16357 # ifdef FEAT_MBYTE
16358 /* Release conversion descriptors */
16359 convert_setup(&conv, NULL, NULL);
16360 vim_free(enc);
16361 # endif
16364 #endif
16367 * "stridx()" function
16369 static void
16370 f_stridx(argvars, rettv)
16371 typval_T *argvars;
16372 typval_T *rettv;
16374 char_u buf[NUMBUFLEN];
16375 char_u *needle;
16376 char_u *haystack;
16377 char_u *save_haystack;
16378 char_u *pos;
16379 int start_idx;
16381 needle = get_tv_string_chk(&argvars[1]);
16382 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
16383 rettv->vval.v_number = -1;
16384 if (needle == NULL || haystack == NULL)
16385 return; /* type error; errmsg already given */
16387 if (argvars[2].v_type != VAR_UNKNOWN)
16389 int error = FALSE;
16391 start_idx = get_tv_number_chk(&argvars[2], &error);
16392 if (error || start_idx >= (int)STRLEN(haystack))
16393 return;
16394 if (start_idx >= 0)
16395 haystack += start_idx;
16398 pos = (char_u *)strstr((char *)haystack, (char *)needle);
16399 if (pos != NULL)
16400 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
16404 * "string()" function
16406 static void
16407 f_string(argvars, rettv)
16408 typval_T *argvars;
16409 typval_T *rettv;
16411 char_u *tofree;
16412 char_u numbuf[NUMBUFLEN];
16414 rettv->v_type = VAR_STRING;
16415 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
16416 /* Make a copy if we have a value but it's not in allocated memory. */
16417 if (rettv->vval.v_string != NULL && tofree == NULL)
16418 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
16422 * "strlen()" function
16424 static void
16425 f_strlen(argvars, rettv)
16426 typval_T *argvars;
16427 typval_T *rettv;
16429 rettv->vval.v_number = (varnumber_T)(STRLEN(
16430 get_tv_string(&argvars[0])));
16434 * "strpart()" function
16436 static void
16437 f_strpart(argvars, rettv)
16438 typval_T *argvars;
16439 typval_T *rettv;
16441 char_u *p;
16442 int n;
16443 int len;
16444 int slen;
16445 int error = FALSE;
16447 p = get_tv_string(&argvars[0]);
16448 slen = (int)STRLEN(p);
16450 n = get_tv_number_chk(&argvars[1], &error);
16451 if (error)
16452 len = 0;
16453 else if (argvars[2].v_type != VAR_UNKNOWN)
16454 len = get_tv_number(&argvars[2]);
16455 else
16456 len = slen - n; /* default len: all bytes that are available. */
16459 * Only return the overlap between the specified part and the actual
16460 * string.
16462 if (n < 0)
16464 len += n;
16465 n = 0;
16467 else if (n > slen)
16468 n = slen;
16469 if (len < 0)
16470 len = 0;
16471 else if (n + len > slen)
16472 len = slen - n;
16474 rettv->v_type = VAR_STRING;
16475 rettv->vval.v_string = vim_strnsave(p + n, len);
16479 * "strridx()" function
16481 static void
16482 f_strridx(argvars, rettv)
16483 typval_T *argvars;
16484 typval_T *rettv;
16486 char_u buf[NUMBUFLEN];
16487 char_u *needle;
16488 char_u *haystack;
16489 char_u *rest;
16490 char_u *lastmatch = NULL;
16491 int haystack_len, end_idx;
16493 needle = get_tv_string_chk(&argvars[1]);
16494 haystack = get_tv_string_buf_chk(&argvars[0], buf);
16496 rettv->vval.v_number = -1;
16497 if (needle == NULL || haystack == NULL)
16498 return; /* type error; errmsg already given */
16500 haystack_len = (int)STRLEN(haystack);
16501 if (argvars[2].v_type != VAR_UNKNOWN)
16503 /* Third argument: upper limit for index */
16504 end_idx = get_tv_number_chk(&argvars[2], NULL);
16505 if (end_idx < 0)
16506 return; /* can never find a match */
16508 else
16509 end_idx = haystack_len;
16511 if (*needle == NUL)
16513 /* Empty string matches past the end. */
16514 lastmatch = haystack + end_idx;
16516 else
16518 for (rest = haystack; *rest != '\0'; ++rest)
16520 rest = (char_u *)strstr((char *)rest, (char *)needle);
16521 if (rest == NULL || rest > haystack + end_idx)
16522 break;
16523 lastmatch = rest;
16527 if (lastmatch == NULL)
16528 rettv->vval.v_number = -1;
16529 else
16530 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
16534 * "strtrans()" function
16536 static void
16537 f_strtrans(argvars, rettv)
16538 typval_T *argvars;
16539 typval_T *rettv;
16541 rettv->v_type = VAR_STRING;
16542 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
16546 * "submatch()" function
16548 static void
16549 f_submatch(argvars, rettv)
16550 typval_T *argvars;
16551 typval_T *rettv;
16553 rettv->v_type = VAR_STRING;
16554 rettv->vval.v_string =
16555 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
16559 * "substitute()" function
16561 static void
16562 f_substitute(argvars, rettv)
16563 typval_T *argvars;
16564 typval_T *rettv;
16566 char_u patbuf[NUMBUFLEN];
16567 char_u subbuf[NUMBUFLEN];
16568 char_u flagsbuf[NUMBUFLEN];
16570 char_u *str = get_tv_string_chk(&argvars[0]);
16571 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16572 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
16573 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
16575 rettv->v_type = VAR_STRING;
16576 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
16577 rettv->vval.v_string = NULL;
16578 else
16579 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
16583 * "synID(lnum, col, trans)" function
16585 static void
16586 f_synID(argvars, rettv)
16587 typval_T *argvars UNUSED;
16588 typval_T *rettv;
16590 int id = 0;
16591 #ifdef FEAT_SYN_HL
16592 long lnum;
16593 long col;
16594 int trans;
16595 int transerr = FALSE;
16597 lnum = get_tv_lnum(argvars); /* -1 on type error */
16598 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16599 trans = get_tv_number_chk(&argvars[2], &transerr);
16601 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16602 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
16603 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
16604 #endif
16606 rettv->vval.v_number = id;
16610 * "synIDattr(id, what [, mode])" function
16612 static void
16613 f_synIDattr(argvars, rettv)
16614 typval_T *argvars UNUSED;
16615 typval_T *rettv;
16617 char_u *p = NULL;
16618 #ifdef FEAT_SYN_HL
16619 int id;
16620 char_u *what;
16621 char_u *mode;
16622 char_u modebuf[NUMBUFLEN];
16623 int modec;
16625 id = get_tv_number(&argvars[0]);
16626 what = get_tv_string(&argvars[1]);
16627 if (argvars[2].v_type != VAR_UNKNOWN)
16629 mode = get_tv_string_buf(&argvars[2], modebuf);
16630 modec = TOLOWER_ASC(mode[0]);
16631 if (modec != 't' && modec != 'c'
16632 #ifdef FEAT_GUI
16633 && modec != 'g'
16634 #endif
16636 modec = 0; /* replace invalid with current */
16638 else
16640 #ifdef FEAT_GUI
16641 if (gui.in_use)
16642 modec = 'g';
16643 else
16644 #endif
16645 if (t_colors > 1)
16646 modec = 'c';
16647 else
16648 modec = 't';
16652 switch (TOLOWER_ASC(what[0]))
16654 case 'b':
16655 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
16656 p = highlight_color(id, what, modec);
16657 else /* bold */
16658 p = highlight_has_attr(id, HL_BOLD, modec);
16659 break;
16661 case 'f': /* fg[#] or font */
16662 p = highlight_color(id, what, modec);
16663 break;
16665 case 'i':
16666 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
16667 p = highlight_has_attr(id, HL_INVERSE, modec);
16668 else /* italic */
16669 p = highlight_has_attr(id, HL_ITALIC, modec);
16670 break;
16672 case 'n': /* name */
16673 p = get_highlight_name(NULL, id - 1);
16674 break;
16676 case 'r': /* reverse */
16677 p = highlight_has_attr(id, HL_INVERSE, modec);
16678 break;
16680 case 's':
16681 if (TOLOWER_ASC(what[1]) == 'p') /* sp[#] */
16682 p = highlight_color(id, what, modec);
16683 else /* standout */
16684 p = highlight_has_attr(id, HL_STANDOUT, modec);
16685 break;
16687 case 'u':
16688 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
16689 /* underline */
16690 p = highlight_has_attr(id, HL_UNDERLINE, modec);
16691 else
16692 /* undercurl */
16693 p = highlight_has_attr(id, HL_UNDERCURL, modec);
16694 break;
16697 if (p != NULL)
16698 p = vim_strsave(p);
16699 #endif
16700 rettv->v_type = VAR_STRING;
16701 rettv->vval.v_string = p;
16705 * "synIDtrans(id)" function
16707 static void
16708 f_synIDtrans(argvars, rettv)
16709 typval_T *argvars UNUSED;
16710 typval_T *rettv;
16712 int id;
16714 #ifdef FEAT_SYN_HL
16715 id = get_tv_number(&argvars[0]);
16717 if (id > 0)
16718 id = syn_get_final_id(id);
16719 else
16720 #endif
16721 id = 0;
16723 rettv->vval.v_number = id;
16727 * "synstack(lnum, col)" function
16729 static void
16730 f_synstack(argvars, rettv)
16731 typval_T *argvars UNUSED;
16732 typval_T *rettv;
16734 #ifdef FEAT_SYN_HL
16735 long lnum;
16736 long col;
16737 int i;
16738 int id;
16739 #endif
16741 rettv->v_type = VAR_LIST;
16742 rettv->vval.v_list = NULL;
16744 #ifdef FEAT_SYN_HL
16745 lnum = get_tv_lnum(argvars); /* -1 on type error */
16746 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16748 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16749 && col >= 0 && (col == 0 || col < (long)STRLEN(ml_get(lnum)))
16750 && rettv_list_alloc(rettv) != FAIL)
16752 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
16753 for (i = 0; ; ++i)
16755 id = syn_get_stack_item(i);
16756 if (id < 0)
16757 break;
16758 if (list_append_number(rettv->vval.v_list, id) == FAIL)
16759 break;
16762 #endif
16766 * "system()" function
16768 static void
16769 f_system(argvars, rettv)
16770 typval_T *argvars;
16771 typval_T *rettv;
16773 char_u *res = NULL;
16774 char_u *p;
16775 char_u *infile = NULL;
16776 char_u buf[NUMBUFLEN];
16777 int err = FALSE;
16778 FILE *fd;
16780 if (check_restricted() || check_secure())
16781 goto done;
16783 if (argvars[1].v_type != VAR_UNKNOWN)
16786 * Write the string to a temp file, to be used for input of the shell
16787 * command.
16789 if ((infile = vim_tempname('i')) == NULL)
16791 EMSG(_(e_notmp));
16792 goto done;
16795 fd = mch_fopen((char *)infile, WRITEBIN);
16796 if (fd == NULL)
16798 EMSG2(_(e_notopen), infile);
16799 goto done;
16801 p = get_tv_string_buf_chk(&argvars[1], buf);
16802 if (p == NULL)
16804 fclose(fd);
16805 goto done; /* type error; errmsg already given */
16807 if (fwrite(p, STRLEN(p), 1, fd) != 1)
16808 err = TRUE;
16809 if (fclose(fd) != 0)
16810 err = TRUE;
16811 if (err)
16813 EMSG(_("E677: Error writing temp file"));
16814 goto done;
16818 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
16819 SHELL_SILENT | SHELL_COOKED);
16821 #ifdef USE_CR
16822 /* translate <CR> into <NL> */
16823 if (res != NULL)
16825 char_u *s;
16827 for (s = res; *s; ++s)
16829 if (*s == CAR)
16830 *s = NL;
16833 #else
16834 # ifdef USE_CRNL
16835 /* translate <CR><NL> into <NL> */
16836 if (res != NULL)
16838 char_u *s, *d;
16840 d = res;
16841 for (s = res; *s; ++s)
16843 if (s[0] == CAR && s[1] == NL)
16844 ++s;
16845 *d++ = *s;
16847 *d = NUL;
16849 # endif
16850 #endif
16852 done:
16853 if (infile != NULL)
16855 mch_remove(infile);
16856 vim_free(infile);
16858 rettv->v_type = VAR_STRING;
16859 rettv->vval.v_string = res;
16863 * "tabpagebuflist()" function
16865 static void
16866 f_tabpagebuflist(argvars, rettv)
16867 typval_T *argvars UNUSED;
16868 typval_T *rettv UNUSED;
16870 #ifdef FEAT_WINDOWS
16871 tabpage_T *tp;
16872 win_T *wp = NULL;
16874 if (argvars[0].v_type == VAR_UNKNOWN)
16875 wp = firstwin;
16876 else
16878 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16879 if (tp != NULL)
16880 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16882 if (wp != NULL && rettv_list_alloc(rettv) != FAIL)
16884 for (; wp != NULL; wp = wp->w_next)
16885 if (list_append_number(rettv->vval.v_list,
16886 wp->w_buffer->b_fnum) == FAIL)
16887 break;
16889 #endif
16894 * "tabpagenr()" function
16896 static void
16897 f_tabpagenr(argvars, rettv)
16898 typval_T *argvars UNUSED;
16899 typval_T *rettv;
16901 int nr = 1;
16902 #ifdef FEAT_WINDOWS
16903 char_u *arg;
16905 if (argvars[0].v_type != VAR_UNKNOWN)
16907 arg = get_tv_string_chk(&argvars[0]);
16908 nr = 0;
16909 if (arg != NULL)
16911 if (STRCMP(arg, "$") == 0)
16912 nr = tabpage_index(NULL) - 1;
16913 else
16914 EMSG2(_(e_invexpr2), arg);
16917 else
16918 nr = tabpage_index(curtab);
16919 #endif
16920 rettv->vval.v_number = nr;
16924 #ifdef FEAT_WINDOWS
16925 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
16928 * Common code for tabpagewinnr() and winnr().
16930 static int
16931 get_winnr(tp, argvar)
16932 tabpage_T *tp;
16933 typval_T *argvar;
16935 win_T *twin;
16936 int nr = 1;
16937 win_T *wp;
16938 char_u *arg;
16940 twin = (tp == curtab) ? curwin : tp->tp_curwin;
16941 if (argvar->v_type != VAR_UNKNOWN)
16943 arg = get_tv_string_chk(argvar);
16944 if (arg == NULL)
16945 nr = 0; /* type error; errmsg already given */
16946 else if (STRCMP(arg, "$") == 0)
16947 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
16948 else if (STRCMP(arg, "#") == 0)
16950 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
16951 if (twin == NULL)
16952 nr = 0;
16954 else
16956 EMSG2(_(e_invexpr2), arg);
16957 nr = 0;
16961 if (nr > 0)
16962 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16963 wp != twin; wp = wp->w_next)
16965 if (wp == NULL)
16967 /* didn't find it in this tabpage */
16968 nr = 0;
16969 break;
16971 ++nr;
16973 return nr;
16975 #endif
16978 * "tabpagewinnr()" function
16980 static void
16981 f_tabpagewinnr(argvars, rettv)
16982 typval_T *argvars UNUSED;
16983 typval_T *rettv;
16985 int nr = 1;
16986 #ifdef FEAT_WINDOWS
16987 tabpage_T *tp;
16989 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16990 if (tp == NULL)
16991 nr = 0;
16992 else
16993 nr = get_winnr(tp, &argvars[1]);
16994 #endif
16995 rettv->vval.v_number = nr;
17000 * "tagfiles()" function
17002 static void
17003 f_tagfiles(argvars, rettv)
17004 typval_T *argvars UNUSED;
17005 typval_T *rettv;
17007 char_u fname[MAXPATHL + 1];
17008 tagname_T tn;
17009 int first;
17011 if (rettv_list_alloc(rettv) == FAIL)
17012 return;
17014 for (first = TRUE; ; first = FALSE)
17015 if (get_tagfname(&tn, first, fname) == FAIL
17016 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
17017 break;
17018 tagname_free(&tn);
17022 * "taglist()" function
17024 static void
17025 f_taglist(argvars, rettv)
17026 typval_T *argvars;
17027 typval_T *rettv;
17029 char_u *tag_pattern;
17031 tag_pattern = get_tv_string(&argvars[0]);
17033 rettv->vval.v_number = FALSE;
17034 if (*tag_pattern == NUL)
17035 return;
17037 if (rettv_list_alloc(rettv) == OK)
17038 (void)get_tags(rettv->vval.v_list, tag_pattern);
17042 * "tempname()" function
17044 static void
17045 f_tempname(argvars, rettv)
17046 typval_T *argvars UNUSED;
17047 typval_T *rettv;
17049 static int x = 'A';
17051 rettv->v_type = VAR_STRING;
17052 rettv->vval.v_string = vim_tempname(x);
17054 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
17055 * names. Skip 'I' and 'O', they are used for shell redirection. */
17058 if (x == 'Z')
17059 x = '0';
17060 else if (x == '9')
17061 x = 'A';
17062 else
17064 #ifdef EBCDIC
17065 if (x == 'I')
17066 x = 'J';
17067 else if (x == 'R')
17068 x = 'S';
17069 else
17070 #endif
17071 ++x;
17073 } while (x == 'I' || x == 'O');
17077 * "test(list)" function: Just checking the walls...
17079 static void
17080 f_test(argvars, rettv)
17081 typval_T *argvars UNUSED;
17082 typval_T *rettv UNUSED;
17084 /* Used for unit testing. Change the code below to your liking. */
17085 #if 0
17086 listitem_T *li;
17087 list_T *l;
17088 char_u *bad, *good;
17090 if (argvars[0].v_type != VAR_LIST)
17091 return;
17092 l = argvars[0].vval.v_list;
17093 if (l == NULL)
17094 return;
17095 li = l->lv_first;
17096 if (li == NULL)
17097 return;
17098 bad = get_tv_string(&li->li_tv);
17099 li = li->li_next;
17100 if (li == NULL)
17101 return;
17102 good = get_tv_string(&li->li_tv);
17103 rettv->vval.v_number = test_edit_score(bad, good);
17104 #endif
17108 * "tolower(string)" function
17110 static void
17111 f_tolower(argvars, rettv)
17112 typval_T *argvars;
17113 typval_T *rettv;
17115 char_u *p;
17117 p = vim_strsave(get_tv_string(&argvars[0]));
17118 rettv->v_type = VAR_STRING;
17119 rettv->vval.v_string = p;
17121 if (p != NULL)
17122 while (*p != NUL)
17124 #ifdef FEAT_MBYTE
17125 int l;
17127 if (enc_utf8)
17129 int c, lc;
17131 c = utf_ptr2char(p);
17132 lc = utf_tolower(c);
17133 l = utf_ptr2len(p);
17134 /* TODO: reallocate string when byte count changes. */
17135 if (utf_char2len(lc) == l)
17136 utf_char2bytes(lc, p);
17137 p += l;
17139 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
17140 p += l; /* skip multi-byte character */
17141 else
17142 #endif
17144 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
17145 ++p;
17151 * "toupper(string)" function
17153 static void
17154 f_toupper(argvars, rettv)
17155 typval_T *argvars;
17156 typval_T *rettv;
17158 rettv->v_type = VAR_STRING;
17159 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
17163 * "tr(string, fromstr, tostr)" function
17165 static void
17166 f_tr(argvars, rettv)
17167 typval_T *argvars;
17168 typval_T *rettv;
17170 char_u *instr;
17171 char_u *fromstr;
17172 char_u *tostr;
17173 char_u *p;
17174 #ifdef FEAT_MBYTE
17175 int inlen;
17176 int fromlen;
17177 int tolen;
17178 int idx;
17179 char_u *cpstr;
17180 int cplen;
17181 int first = TRUE;
17182 #endif
17183 char_u buf[NUMBUFLEN];
17184 char_u buf2[NUMBUFLEN];
17185 garray_T ga;
17187 instr = get_tv_string(&argvars[0]);
17188 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
17189 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
17191 /* Default return value: empty string. */
17192 rettv->v_type = VAR_STRING;
17193 rettv->vval.v_string = NULL;
17194 if (fromstr == NULL || tostr == NULL)
17195 return; /* type error; errmsg already given */
17196 ga_init2(&ga, (int)sizeof(char), 80);
17198 #ifdef FEAT_MBYTE
17199 if (!has_mbyte)
17200 #endif
17201 /* not multi-byte: fromstr and tostr must be the same length */
17202 if (STRLEN(fromstr) != STRLEN(tostr))
17204 #ifdef FEAT_MBYTE
17205 error:
17206 #endif
17207 EMSG2(_(e_invarg2), fromstr);
17208 ga_clear(&ga);
17209 return;
17212 /* fromstr and tostr have to contain the same number of chars */
17213 while (*instr != NUL)
17215 #ifdef FEAT_MBYTE
17216 if (has_mbyte)
17218 inlen = (*mb_ptr2len)(instr);
17219 cpstr = instr;
17220 cplen = inlen;
17221 idx = 0;
17222 for (p = fromstr; *p != NUL; p += fromlen)
17224 fromlen = (*mb_ptr2len)(p);
17225 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
17227 for (p = tostr; *p != NUL; p += tolen)
17229 tolen = (*mb_ptr2len)(p);
17230 if (idx-- == 0)
17232 cplen = tolen;
17233 cpstr = p;
17234 break;
17237 if (*p == NUL) /* tostr is shorter than fromstr */
17238 goto error;
17239 break;
17241 ++idx;
17244 if (first && cpstr == instr)
17246 /* Check that fromstr and tostr have the same number of
17247 * (multi-byte) characters. Done only once when a character
17248 * of instr doesn't appear in fromstr. */
17249 first = FALSE;
17250 for (p = tostr; *p != NUL; p += tolen)
17252 tolen = (*mb_ptr2len)(p);
17253 --idx;
17255 if (idx != 0)
17256 goto error;
17259 ga_grow(&ga, cplen);
17260 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
17261 ga.ga_len += cplen;
17263 instr += inlen;
17265 else
17266 #endif
17268 /* When not using multi-byte chars we can do it faster. */
17269 p = vim_strchr(fromstr, *instr);
17270 if (p != NULL)
17271 ga_append(&ga, tostr[p - fromstr]);
17272 else
17273 ga_append(&ga, *instr);
17274 ++instr;
17278 /* add a terminating NUL */
17279 ga_grow(&ga, 1);
17280 ga_append(&ga, NUL);
17282 rettv->vval.v_string = ga.ga_data;
17285 #ifdef FEAT_FLOAT
17287 * "trunc({float})" function
17289 static void
17290 f_trunc(argvars, rettv)
17291 typval_T *argvars;
17292 typval_T *rettv;
17294 float_T f;
17296 rettv->v_type = VAR_FLOAT;
17297 if (get_float_arg(argvars, &f) == OK)
17298 /* trunc() is not in C90, use floor() or ceil() instead. */
17299 rettv->vval.v_float = f > 0 ? floor(f) : ceil(f);
17300 else
17301 rettv->vval.v_float = 0.0;
17303 #endif
17306 * "type(expr)" function
17308 static void
17309 f_type(argvars, rettv)
17310 typval_T *argvars;
17311 typval_T *rettv;
17313 int n;
17315 switch (argvars[0].v_type)
17317 case VAR_NUMBER: n = 0; break;
17318 case VAR_STRING: n = 1; break;
17319 case VAR_FUNC: n = 2; break;
17320 case VAR_LIST: n = 3; break;
17321 case VAR_DICT: n = 4; break;
17322 #ifdef FEAT_FLOAT
17323 case VAR_FLOAT: n = 5; break;
17324 #endif
17325 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
17327 rettv->vval.v_number = n;
17331 * "values(dict)" function
17333 static void
17334 f_values(argvars, rettv)
17335 typval_T *argvars;
17336 typval_T *rettv;
17338 dict_list(argvars, rettv, 1);
17342 * "virtcol(string)" function
17344 static void
17345 f_virtcol(argvars, rettv)
17346 typval_T *argvars;
17347 typval_T *rettv;
17349 colnr_T vcol = 0;
17350 pos_T *fp;
17351 int fnum = curbuf->b_fnum;
17353 fp = var2fpos(&argvars[0], FALSE, &fnum);
17354 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
17355 && fnum == curbuf->b_fnum)
17357 getvvcol(curwin, fp, NULL, NULL, &vcol);
17358 ++vcol;
17361 rettv->vval.v_number = vcol;
17365 * "visualmode()" function
17367 static void
17368 f_visualmode(argvars, rettv)
17369 typval_T *argvars UNUSED;
17370 typval_T *rettv UNUSED;
17372 #ifdef FEAT_VISUAL
17373 char_u str[2];
17375 rettv->v_type = VAR_STRING;
17376 str[0] = curbuf->b_visual_mode_eval;
17377 str[1] = NUL;
17378 rettv->vval.v_string = vim_strsave(str);
17380 /* A non-zero number or non-empty string argument: reset mode. */
17381 if (non_zero_arg(&argvars[0]))
17382 curbuf->b_visual_mode_eval = NUL;
17383 #endif
17387 * "winbufnr(nr)" function
17389 static void
17390 f_winbufnr(argvars, rettv)
17391 typval_T *argvars;
17392 typval_T *rettv;
17394 win_T *wp;
17396 wp = find_win_by_nr(&argvars[0], NULL);
17397 if (wp == NULL)
17398 rettv->vval.v_number = -1;
17399 else
17400 rettv->vval.v_number = wp->w_buffer->b_fnum;
17404 * "wincol()" function
17406 static void
17407 f_wincol(argvars, rettv)
17408 typval_T *argvars UNUSED;
17409 typval_T *rettv;
17411 validate_cursor();
17412 rettv->vval.v_number = curwin->w_wcol + 1;
17416 * "winheight(nr)" function
17418 static void
17419 f_winheight(argvars, rettv)
17420 typval_T *argvars;
17421 typval_T *rettv;
17423 win_T *wp;
17425 wp = find_win_by_nr(&argvars[0], NULL);
17426 if (wp == NULL)
17427 rettv->vval.v_number = -1;
17428 else
17429 rettv->vval.v_number = wp->w_height;
17433 * "winline()" function
17435 static void
17436 f_winline(argvars, rettv)
17437 typval_T *argvars UNUSED;
17438 typval_T *rettv;
17440 validate_cursor();
17441 rettv->vval.v_number = curwin->w_wrow + 1;
17445 * "winnr()" function
17447 static void
17448 f_winnr(argvars, rettv)
17449 typval_T *argvars UNUSED;
17450 typval_T *rettv;
17452 int nr = 1;
17454 #ifdef FEAT_WINDOWS
17455 nr = get_winnr(curtab, &argvars[0]);
17456 #endif
17457 rettv->vval.v_number = nr;
17461 * "winrestcmd()" function
17463 static void
17464 f_winrestcmd(argvars, rettv)
17465 typval_T *argvars UNUSED;
17466 typval_T *rettv;
17468 #ifdef FEAT_WINDOWS
17469 win_T *wp;
17470 int winnr = 1;
17471 garray_T ga;
17472 char_u buf[50];
17474 ga_init2(&ga, (int)sizeof(char), 70);
17475 for (wp = firstwin; wp != NULL; wp = wp->w_next)
17477 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
17478 ga_concat(&ga, buf);
17479 # ifdef FEAT_VERTSPLIT
17480 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
17481 ga_concat(&ga, buf);
17482 # endif
17483 ++winnr;
17485 ga_append(&ga, NUL);
17487 rettv->vval.v_string = ga.ga_data;
17488 #else
17489 rettv->vval.v_string = NULL;
17490 #endif
17491 rettv->v_type = VAR_STRING;
17495 * "winrestview()" function
17497 static void
17498 f_winrestview(argvars, rettv)
17499 typval_T *argvars;
17500 typval_T *rettv UNUSED;
17502 dict_T *dict;
17504 if (argvars[0].v_type != VAR_DICT
17505 || (dict = argvars[0].vval.v_dict) == NULL)
17506 EMSG(_(e_invarg));
17507 else
17509 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
17510 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
17511 #ifdef FEAT_VIRTUALEDIT
17512 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
17513 #endif
17514 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
17515 curwin->w_set_curswant = FALSE;
17517 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
17518 #ifdef FEAT_DIFF
17519 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
17520 #endif
17521 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
17522 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
17524 check_cursor();
17525 changed_cline_bef_curs();
17526 invalidate_botline();
17527 redraw_later(VALID);
17529 if (curwin->w_topline == 0)
17530 curwin->w_topline = 1;
17531 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
17532 curwin->w_topline = curbuf->b_ml.ml_line_count;
17533 #ifdef FEAT_DIFF
17534 check_topfill(curwin, TRUE);
17535 #endif
17540 * "winsaveview()" function
17542 static void
17543 f_winsaveview(argvars, rettv)
17544 typval_T *argvars UNUSED;
17545 typval_T *rettv;
17547 dict_T *dict;
17549 dict = dict_alloc();
17550 if (dict == NULL)
17551 return;
17552 rettv->v_type = VAR_DICT;
17553 rettv->vval.v_dict = dict;
17554 ++dict->dv_refcount;
17556 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
17557 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
17558 #ifdef FEAT_VIRTUALEDIT
17559 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
17560 #endif
17561 update_curswant();
17562 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
17564 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
17565 #ifdef FEAT_DIFF
17566 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
17567 #endif
17568 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
17569 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
17573 * "winwidth(nr)" function
17575 static void
17576 f_winwidth(argvars, rettv)
17577 typval_T *argvars;
17578 typval_T *rettv;
17580 win_T *wp;
17582 wp = find_win_by_nr(&argvars[0], NULL);
17583 if (wp == NULL)
17584 rettv->vval.v_number = -1;
17585 else
17586 #ifdef FEAT_VERTSPLIT
17587 rettv->vval.v_number = wp->w_width;
17588 #else
17589 rettv->vval.v_number = Columns;
17590 #endif
17594 * "writefile()" function
17596 static void
17597 f_writefile(argvars, rettv)
17598 typval_T *argvars;
17599 typval_T *rettv;
17601 int binary = FALSE;
17602 char_u *fname;
17603 FILE *fd;
17604 listitem_T *li;
17605 char_u *s;
17606 int ret = 0;
17607 int c;
17609 if (check_restricted() || check_secure())
17610 return;
17612 if (argvars[0].v_type != VAR_LIST)
17614 EMSG2(_(e_listarg), "writefile()");
17615 return;
17617 if (argvars[0].vval.v_list == NULL)
17618 return;
17620 if (argvars[2].v_type != VAR_UNKNOWN
17621 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
17622 binary = TRUE;
17624 /* Always open the file in binary mode, library functions have a mind of
17625 * their own about CR-LF conversion. */
17626 fname = get_tv_string(&argvars[1]);
17627 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
17629 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
17630 ret = -1;
17632 else
17634 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
17635 li = li->li_next)
17637 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
17639 if (*s == '\n')
17640 c = putc(NUL, fd);
17641 else
17642 c = putc(*s, fd);
17643 if (c == EOF)
17645 ret = -1;
17646 break;
17649 if (!binary || li->li_next != NULL)
17650 if (putc('\n', fd) == EOF)
17652 ret = -1;
17653 break;
17655 if (ret < 0)
17657 EMSG(_(e_write));
17658 break;
17661 fclose(fd);
17664 rettv->vval.v_number = ret;
17668 * Translate a String variable into a position.
17669 * Returns NULL when there is an error.
17671 static pos_T *
17672 var2fpos(varp, dollar_lnum, fnum)
17673 typval_T *varp;
17674 int dollar_lnum; /* TRUE when $ is last line */
17675 int *fnum; /* set to fnum for '0, 'A, etc. */
17677 char_u *name;
17678 static pos_T pos;
17679 pos_T *pp;
17681 /* Argument can be [lnum, col, coladd]. */
17682 if (varp->v_type == VAR_LIST)
17684 list_T *l;
17685 int len;
17686 int error = FALSE;
17687 listitem_T *li;
17689 l = varp->vval.v_list;
17690 if (l == NULL)
17691 return NULL;
17693 /* Get the line number */
17694 pos.lnum = list_find_nr(l, 0L, &error);
17695 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
17696 return NULL; /* invalid line number */
17698 /* Get the column number */
17699 pos.col = list_find_nr(l, 1L, &error);
17700 if (error)
17701 return NULL;
17702 len = (long)STRLEN(ml_get(pos.lnum));
17704 /* We accept "$" for the column number: last column. */
17705 li = list_find(l, 1L);
17706 if (li != NULL && li->li_tv.v_type == VAR_STRING
17707 && li->li_tv.vval.v_string != NULL
17708 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
17709 pos.col = len + 1;
17711 /* Accept a position up to the NUL after the line. */
17712 if (pos.col == 0 || (int)pos.col > len + 1)
17713 return NULL; /* invalid column number */
17714 --pos.col;
17716 #ifdef FEAT_VIRTUALEDIT
17717 /* Get the virtual offset. Defaults to zero. */
17718 pos.coladd = list_find_nr(l, 2L, &error);
17719 if (error)
17720 pos.coladd = 0;
17721 #endif
17723 return &pos;
17726 name = get_tv_string_chk(varp);
17727 if (name == NULL)
17728 return NULL;
17729 if (name[0] == '.') /* cursor */
17730 return &curwin->w_cursor;
17731 #ifdef FEAT_VISUAL
17732 if (name[0] == 'v' && name[1] == NUL) /* Visual start */
17734 if (VIsual_active)
17735 return &VIsual;
17736 return &curwin->w_cursor;
17738 #endif
17739 if (name[0] == '\'') /* mark */
17741 pp = getmark_fnum(name[1], FALSE, fnum);
17742 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
17743 return NULL;
17744 return pp;
17747 #ifdef FEAT_VIRTUALEDIT
17748 pos.coladd = 0;
17749 #endif
17751 if (name[0] == 'w' && dollar_lnum)
17753 pos.col = 0;
17754 if (name[1] == '0') /* "w0": first visible line */
17756 update_topline();
17757 pos.lnum = curwin->w_topline;
17758 return &pos;
17760 else if (name[1] == '$') /* "w$": last visible line */
17762 validate_botline();
17763 pos.lnum = curwin->w_botline - 1;
17764 return &pos;
17767 else if (name[0] == '$') /* last column or line */
17769 if (dollar_lnum)
17771 pos.lnum = curbuf->b_ml.ml_line_count;
17772 pos.col = 0;
17774 else
17776 pos.lnum = curwin->w_cursor.lnum;
17777 pos.col = (colnr_T)STRLEN(ml_get_curline());
17779 return &pos;
17781 return NULL;
17785 * Convert list in "arg" into a position and optional file number.
17786 * When "fnump" is NULL there is no file number, only 3 items.
17787 * Note that the column is passed on as-is, the caller may want to decrement
17788 * it to use 1 for the first column.
17789 * Return FAIL when conversion is not possible, doesn't check the position for
17790 * validity.
17792 static int
17793 list2fpos(arg, posp, fnump)
17794 typval_T *arg;
17795 pos_T *posp;
17796 int *fnump;
17798 list_T *l = arg->vval.v_list;
17799 long i = 0;
17800 long n;
17802 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
17803 * when "fnump" isn't NULL and "coladd" is optional. */
17804 if (arg->v_type != VAR_LIST
17805 || l == NULL
17806 || l->lv_len < (fnump == NULL ? 2 : 3)
17807 || l->lv_len > (fnump == NULL ? 3 : 4))
17808 return FAIL;
17810 if (fnump != NULL)
17812 n = list_find_nr(l, i++, NULL); /* fnum */
17813 if (n < 0)
17814 return FAIL;
17815 if (n == 0)
17816 n = curbuf->b_fnum; /* current buffer */
17817 *fnump = n;
17820 n = list_find_nr(l, i++, NULL); /* lnum */
17821 if (n < 0)
17822 return FAIL;
17823 posp->lnum = n;
17825 n = list_find_nr(l, i++, NULL); /* col */
17826 if (n < 0)
17827 return FAIL;
17828 posp->col = n;
17830 #ifdef FEAT_VIRTUALEDIT
17831 n = list_find_nr(l, i, NULL);
17832 if (n < 0)
17833 posp->coladd = 0;
17834 else
17835 posp->coladd = n;
17836 #endif
17838 return OK;
17842 * Get the length of an environment variable name.
17843 * Advance "arg" to the first character after the name.
17844 * Return 0 for error.
17846 static int
17847 get_env_len(arg)
17848 char_u **arg;
17850 char_u *p;
17851 int len;
17853 for (p = *arg; vim_isIDc(*p); ++p)
17855 if (p == *arg) /* no name found */
17856 return 0;
17858 len = (int)(p - *arg);
17859 *arg = p;
17860 return len;
17864 * Get the length of the name of a function or internal variable.
17865 * "arg" is advanced to the first non-white character after the name.
17866 * Return 0 if something is wrong.
17868 static int
17869 get_id_len(arg)
17870 char_u **arg;
17872 char_u *p;
17873 int len;
17875 /* Find the end of the name. */
17876 for (p = *arg; eval_isnamec(*p); ++p)
17878 if (p == *arg) /* no name found */
17879 return 0;
17881 len = (int)(p - *arg);
17882 *arg = skipwhite(p);
17884 return len;
17888 * Get the length of the name of a variable or function.
17889 * Only the name is recognized, does not handle ".key" or "[idx]".
17890 * "arg" is advanced to the first non-white character after the name.
17891 * Return -1 if curly braces expansion failed.
17892 * Return 0 if something else is wrong.
17893 * If the name contains 'magic' {}'s, expand them and return the
17894 * expanded name in an allocated string via 'alias' - caller must free.
17896 static int
17897 get_name_len(arg, alias, evaluate, verbose)
17898 char_u **arg;
17899 char_u **alias;
17900 int evaluate;
17901 int verbose;
17903 int len;
17904 char_u *p;
17905 char_u *expr_start;
17906 char_u *expr_end;
17908 *alias = NULL; /* default to no alias */
17910 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
17911 && (*arg)[2] == (int)KE_SNR)
17913 /* hard coded <SNR>, already translated */
17914 *arg += 3;
17915 return get_id_len(arg) + 3;
17917 len = eval_fname_script(*arg);
17918 if (len > 0)
17920 /* literal "<SID>", "s:" or "<SNR>" */
17921 *arg += len;
17925 * Find the end of the name; check for {} construction.
17927 p = find_name_end(*arg, &expr_start, &expr_end,
17928 len > 0 ? 0 : FNE_CHECK_START);
17929 if (expr_start != NULL)
17931 char_u *temp_string;
17933 if (!evaluate)
17935 len += (int)(p - *arg);
17936 *arg = skipwhite(p);
17937 return len;
17941 * Include any <SID> etc in the expanded string:
17942 * Thus the -len here.
17944 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
17945 if (temp_string == NULL)
17946 return -1;
17947 *alias = temp_string;
17948 *arg = skipwhite(p);
17949 return (int)STRLEN(temp_string);
17952 len += get_id_len(arg);
17953 if (len == 0 && verbose)
17954 EMSG2(_(e_invexpr2), *arg);
17956 return len;
17960 * Find the end of a variable or function name, taking care of magic braces.
17961 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
17962 * start and end of the first magic braces item.
17963 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
17964 * Return a pointer to just after the name. Equal to "arg" if there is no
17965 * valid name.
17967 static char_u *
17968 find_name_end(arg, expr_start, expr_end, flags)
17969 char_u *arg;
17970 char_u **expr_start;
17971 char_u **expr_end;
17972 int flags;
17974 int mb_nest = 0;
17975 int br_nest = 0;
17976 char_u *p;
17978 if (expr_start != NULL)
17980 *expr_start = NULL;
17981 *expr_end = NULL;
17984 /* Quick check for valid starting character. */
17985 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
17986 return arg;
17988 for (p = arg; *p != NUL
17989 && (eval_isnamec(*p)
17990 || *p == '{'
17991 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
17992 || mb_nest != 0
17993 || br_nest != 0); mb_ptr_adv(p))
17995 if (*p == '\'')
17997 /* skip over 'string' to avoid counting [ and ] inside it. */
17998 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
18000 if (*p == NUL)
18001 break;
18003 else if (*p == '"')
18005 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
18006 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
18007 if (*p == '\\' && p[1] != NUL)
18008 ++p;
18009 if (*p == NUL)
18010 break;
18013 if (mb_nest == 0)
18015 if (*p == '[')
18016 ++br_nest;
18017 else if (*p == ']')
18018 --br_nest;
18021 if (br_nest == 0)
18023 if (*p == '{')
18025 mb_nest++;
18026 if (expr_start != NULL && *expr_start == NULL)
18027 *expr_start = p;
18029 else if (*p == '}')
18031 mb_nest--;
18032 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
18033 *expr_end = p;
18038 return p;
18042 * Expands out the 'magic' {}'s in a variable/function name.
18043 * Note that this can call itself recursively, to deal with
18044 * constructs like foo{bar}{baz}{bam}
18045 * The four pointer arguments point to "foo{expre}ss{ion}bar"
18046 * "in_start" ^
18047 * "expr_start" ^
18048 * "expr_end" ^
18049 * "in_end" ^
18051 * Returns a new allocated string, which the caller must free.
18052 * Returns NULL for failure.
18054 static char_u *
18055 make_expanded_name(in_start, expr_start, expr_end, in_end)
18056 char_u *in_start;
18057 char_u *expr_start;
18058 char_u *expr_end;
18059 char_u *in_end;
18061 char_u c1;
18062 char_u *retval = NULL;
18063 char_u *temp_result;
18064 char_u *nextcmd = NULL;
18066 if (expr_end == NULL || in_end == NULL)
18067 return NULL;
18068 *expr_start = NUL;
18069 *expr_end = NUL;
18070 c1 = *in_end;
18071 *in_end = NUL;
18073 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
18074 if (temp_result != NULL && nextcmd == NULL)
18076 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
18077 + (in_end - expr_end) + 1));
18078 if (retval != NULL)
18080 STRCPY(retval, in_start);
18081 STRCAT(retval, temp_result);
18082 STRCAT(retval, expr_end + 1);
18085 vim_free(temp_result);
18087 *in_end = c1; /* put char back for error messages */
18088 *expr_start = '{';
18089 *expr_end = '}';
18091 if (retval != NULL)
18093 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
18094 if (expr_start != NULL)
18096 /* Further expansion! */
18097 temp_result = make_expanded_name(retval, expr_start,
18098 expr_end, temp_result);
18099 vim_free(retval);
18100 retval = temp_result;
18104 return retval;
18108 * Return TRUE if character "c" can be used in a variable or function name.
18109 * Does not include '{' or '}' for magic braces.
18111 static int
18112 eval_isnamec(c)
18113 int c;
18115 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
18119 * Return TRUE if character "c" can be used as the first character in a
18120 * variable or function name (excluding '{' and '}').
18122 static int
18123 eval_isnamec1(c)
18124 int c;
18126 return (ASCII_ISALPHA(c) || c == '_');
18130 * Set number v: variable to "val".
18132 void
18133 set_vim_var_nr(idx, val)
18134 int idx;
18135 long val;
18137 vimvars[idx].vv_nr = val;
18141 * Get number v: variable value.
18143 long
18144 get_vim_var_nr(idx)
18145 int idx;
18147 return vimvars[idx].vv_nr;
18151 * Get string v: variable value. Uses a static buffer, can only be used once.
18153 char_u *
18154 get_vim_var_str(idx)
18155 int idx;
18157 return get_tv_string(&vimvars[idx].vv_tv);
18161 * Get List v: variable value. Caller must take care of reference count when
18162 * needed.
18164 list_T *
18165 get_vim_var_list(idx)
18166 int idx;
18168 return vimvars[idx].vv_list;
18172 * Set v:char to character "c".
18174 void
18175 set_vim_var_char(c)
18176 int c;
18178 #ifdef FEAT_MBYTE
18179 char_u buf[MB_MAXBYTES];
18180 #else
18181 char_u buf[2];
18182 #endif
18184 #ifdef FEAT_MBYTE
18185 if (has_mbyte)
18186 buf[(*mb_char2bytes)(c, buf)] = NUL;
18187 else
18188 #endif
18190 buf[0] = c;
18191 buf[1] = NUL;
18193 set_vim_var_string(VV_CHAR, buf, -1);
18197 * Set v:count to "count" and v:count1 to "count1".
18198 * When "set_prevcount" is TRUE first set v:prevcount from v:count.
18200 void
18201 set_vcount(count, count1, set_prevcount)
18202 long count;
18203 long count1;
18204 int set_prevcount;
18206 if (set_prevcount)
18207 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
18208 vimvars[VV_COUNT].vv_nr = count;
18209 vimvars[VV_COUNT1].vv_nr = count1;
18213 * Set string v: variable to a copy of "val".
18215 void
18216 set_vim_var_string(idx, val, len)
18217 int idx;
18218 char_u *val;
18219 int len; /* length of "val" to use or -1 (whole string) */
18221 /* Need to do this (at least) once, since we can't initialize a union.
18222 * Will always be invoked when "v:progname" is set. */
18223 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
18225 vim_free(vimvars[idx].vv_str);
18226 if (val == NULL)
18227 vimvars[idx].vv_str = NULL;
18228 else if (len == -1)
18229 vimvars[idx].vv_str = vim_strsave(val);
18230 else
18231 vimvars[idx].vv_str = vim_strnsave(val, len);
18235 * Set List v: variable to "val".
18237 void
18238 set_vim_var_list(idx, val)
18239 int idx;
18240 list_T *val;
18242 list_unref(vimvars[idx].vv_list);
18243 vimvars[idx].vv_list = val;
18244 if (val != NULL)
18245 ++val->lv_refcount;
18249 * Set v:register if needed.
18251 void
18252 set_reg_var(c)
18253 int c;
18255 char_u regname;
18257 if (c == 0 || c == ' ')
18258 regname = '"';
18259 else
18260 regname = c;
18261 /* Avoid free/alloc when the value is already right. */
18262 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
18263 set_vim_var_string(VV_REG, &regname, 1);
18267 * Get or set v:exception. If "oldval" == NULL, return the current value.
18268 * Otherwise, restore the value to "oldval" and return NULL.
18269 * Must always be called in pairs to save and restore v:exception! Does not
18270 * take care of memory allocations.
18272 char_u *
18273 v_exception(oldval)
18274 char_u *oldval;
18276 if (oldval == NULL)
18277 return vimvars[VV_EXCEPTION].vv_str;
18279 vimvars[VV_EXCEPTION].vv_str = oldval;
18280 return NULL;
18284 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
18285 * Otherwise, restore the value to "oldval" and return NULL.
18286 * Must always be called in pairs to save and restore v:throwpoint! Does not
18287 * take care of memory allocations.
18289 char_u *
18290 v_throwpoint(oldval)
18291 char_u *oldval;
18293 if (oldval == NULL)
18294 return vimvars[VV_THROWPOINT].vv_str;
18296 vimvars[VV_THROWPOINT].vv_str = oldval;
18297 return NULL;
18300 #if defined(FEAT_AUTOCMD) || defined(PROTO)
18302 * Set v:cmdarg.
18303 * If "eap" != NULL, use "eap" to generate the value and return the old value.
18304 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
18305 * Must always be called in pairs!
18307 char_u *
18308 set_cmdarg(eap, oldarg)
18309 exarg_T *eap;
18310 char_u *oldarg;
18312 char_u *oldval;
18313 char_u *newval;
18314 unsigned len;
18316 oldval = vimvars[VV_CMDARG].vv_str;
18317 if (eap == NULL)
18319 vim_free(oldval);
18320 vimvars[VV_CMDARG].vv_str = oldarg;
18321 return NULL;
18324 if (eap->force_bin == FORCE_BIN)
18325 len = 6;
18326 else if (eap->force_bin == FORCE_NOBIN)
18327 len = 8;
18328 else
18329 len = 0;
18331 if (eap->read_edit)
18332 len += 7;
18334 if (eap->force_ff != 0)
18335 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
18336 # ifdef FEAT_MBYTE
18337 if (eap->force_enc != 0)
18338 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
18339 if (eap->bad_char != 0)
18340 len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
18341 # endif
18343 newval = alloc(len + 1);
18344 if (newval == NULL)
18345 return NULL;
18347 if (eap->force_bin == FORCE_BIN)
18348 sprintf((char *)newval, " ++bin");
18349 else if (eap->force_bin == FORCE_NOBIN)
18350 sprintf((char *)newval, " ++nobin");
18351 else
18352 *newval = NUL;
18354 if (eap->read_edit)
18355 STRCAT(newval, " ++edit");
18357 if (eap->force_ff != 0)
18358 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
18359 eap->cmd + eap->force_ff);
18360 # ifdef FEAT_MBYTE
18361 if (eap->force_enc != 0)
18362 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
18363 eap->cmd + eap->force_enc);
18364 if (eap->bad_char != 0)
18365 sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
18366 eap->cmd + eap->bad_char);
18367 # endif
18368 vimvars[VV_CMDARG].vv_str = newval;
18369 return oldval;
18371 #endif
18374 * Get the value of internal variable "name".
18375 * Return OK or FAIL.
18377 static int
18378 get_var_tv(name, len, rettv, verbose)
18379 char_u *name;
18380 int len; /* length of "name" */
18381 typval_T *rettv; /* NULL when only checking existence */
18382 int verbose; /* may give error message */
18384 int ret = OK;
18385 typval_T *tv = NULL;
18386 typval_T atv;
18387 dictitem_T *v;
18388 int cc;
18390 /* truncate the name, so that we can use strcmp() */
18391 cc = name[len];
18392 name[len] = NUL;
18395 * Check for "b:changedtick".
18397 if (STRCMP(name, "b:changedtick") == 0)
18399 atv.v_type = VAR_NUMBER;
18400 atv.vval.v_number = curbuf->b_changedtick;
18401 tv = &atv;
18405 * Check for user-defined variables.
18407 else
18409 v = find_var(name, NULL);
18410 if (v != NULL)
18411 tv = &v->di_tv;
18414 if (tv == NULL)
18416 if (rettv != NULL && verbose)
18417 EMSG2(_(e_undefvar), name);
18418 ret = FAIL;
18420 else if (rettv != NULL)
18421 copy_tv(tv, rettv);
18423 name[len] = cc;
18425 return ret;
18429 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
18430 * Also handle function call with Funcref variable: func(expr)
18431 * Can all be combined: dict.func(expr)[idx]['func'](expr)
18433 static int
18434 handle_subscript(arg, rettv, evaluate, verbose)
18435 char_u **arg;
18436 typval_T *rettv;
18437 int evaluate; /* do more than finding the end */
18438 int verbose; /* give error messages */
18440 int ret = OK;
18441 dict_T *selfdict = NULL;
18442 char_u *s;
18443 int len;
18444 typval_T functv;
18446 while (ret == OK
18447 && (**arg == '['
18448 || (**arg == '.' && rettv->v_type == VAR_DICT)
18449 || (**arg == '(' && rettv->v_type == VAR_FUNC))
18450 && !vim_iswhite(*(*arg - 1)))
18452 if (**arg == '(')
18454 /* need to copy the funcref so that we can clear rettv */
18455 functv = *rettv;
18456 rettv->v_type = VAR_UNKNOWN;
18458 /* Invoke the function. Recursive! */
18459 s = functv.vval.v_string;
18460 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
18461 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
18462 &len, evaluate, selfdict);
18464 /* Clear the funcref afterwards, so that deleting it while
18465 * evaluating the arguments is possible (see test55). */
18466 clear_tv(&functv);
18468 /* Stop the expression evaluation when immediately aborting on
18469 * error, or when an interrupt occurred or an exception was thrown
18470 * but not caught. */
18471 if (aborting())
18473 if (ret == OK)
18474 clear_tv(rettv);
18475 ret = FAIL;
18477 dict_unref(selfdict);
18478 selfdict = NULL;
18480 else /* **arg == '[' || **arg == '.' */
18482 dict_unref(selfdict);
18483 if (rettv->v_type == VAR_DICT)
18485 selfdict = rettv->vval.v_dict;
18486 if (selfdict != NULL)
18487 ++selfdict->dv_refcount;
18489 else
18490 selfdict = NULL;
18491 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
18493 clear_tv(rettv);
18494 ret = FAIL;
18498 dict_unref(selfdict);
18499 return ret;
18503 * Allocate memory for a variable type-value, and make it empty (0 or NULL
18504 * value).
18506 static typval_T *
18507 alloc_tv()
18509 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
18513 * Allocate memory for a variable type-value, and assign a string to it.
18514 * The string "s" must have been allocated, it is consumed.
18515 * Return NULL for out of memory, the variable otherwise.
18517 static typval_T *
18518 alloc_string_tv(s)
18519 char_u *s;
18521 typval_T *rettv;
18523 rettv = alloc_tv();
18524 if (rettv != NULL)
18526 rettv->v_type = VAR_STRING;
18527 rettv->vval.v_string = s;
18529 else
18530 vim_free(s);
18531 return rettv;
18535 * Free the memory for a variable type-value.
18537 void
18538 free_tv(varp)
18539 typval_T *varp;
18541 if (varp != NULL)
18543 switch (varp->v_type)
18545 case VAR_FUNC:
18546 func_unref(varp->vval.v_string);
18547 /*FALLTHROUGH*/
18548 case VAR_STRING:
18549 vim_free(varp->vval.v_string);
18550 break;
18551 case VAR_LIST:
18552 list_unref(varp->vval.v_list);
18553 break;
18554 case VAR_DICT:
18555 dict_unref(varp->vval.v_dict);
18556 break;
18557 case VAR_NUMBER:
18558 #ifdef FEAT_FLOAT
18559 case VAR_FLOAT:
18560 #endif
18561 case VAR_UNKNOWN:
18562 break;
18563 default:
18564 EMSG2(_(e_intern2), "free_tv()");
18565 break;
18567 vim_free(varp);
18572 * Free the memory for a variable value and set the value to NULL or 0.
18574 void
18575 clear_tv(varp)
18576 typval_T *varp;
18578 if (varp != NULL)
18580 switch (varp->v_type)
18582 case VAR_FUNC:
18583 func_unref(varp->vval.v_string);
18584 /*FALLTHROUGH*/
18585 case VAR_STRING:
18586 vim_free(varp->vval.v_string);
18587 varp->vval.v_string = NULL;
18588 break;
18589 case VAR_LIST:
18590 list_unref(varp->vval.v_list);
18591 varp->vval.v_list = NULL;
18592 break;
18593 case VAR_DICT:
18594 dict_unref(varp->vval.v_dict);
18595 varp->vval.v_dict = NULL;
18596 break;
18597 case VAR_NUMBER:
18598 varp->vval.v_number = 0;
18599 break;
18600 #ifdef FEAT_FLOAT
18601 case VAR_FLOAT:
18602 varp->vval.v_float = 0.0;
18603 break;
18604 #endif
18605 case VAR_UNKNOWN:
18606 break;
18607 default:
18608 EMSG2(_(e_intern2), "clear_tv()");
18610 varp->v_lock = 0;
18615 * Set the value of a variable to NULL without freeing items.
18617 static void
18618 init_tv(varp)
18619 typval_T *varp;
18621 if (varp != NULL)
18622 vim_memset(varp, 0, sizeof(typval_T));
18626 * Get the number value of a variable.
18627 * If it is a String variable, uses vim_str2nr().
18628 * For incompatible types, return 0.
18629 * get_tv_number_chk() is similar to get_tv_number(), but informs the
18630 * caller of incompatible types: it sets *denote to TRUE if "denote"
18631 * is not NULL or returns -1 otherwise.
18633 static long
18634 get_tv_number(varp)
18635 typval_T *varp;
18637 int error = FALSE;
18639 return get_tv_number_chk(varp, &error); /* return 0L on error */
18642 long
18643 get_tv_number_chk(varp, denote)
18644 typval_T *varp;
18645 int *denote;
18647 long n = 0L;
18649 switch (varp->v_type)
18651 case VAR_NUMBER:
18652 return (long)(varp->vval.v_number);
18653 #ifdef FEAT_FLOAT
18654 case VAR_FLOAT:
18655 EMSG(_("E805: Using a Float as a Number"));
18656 break;
18657 #endif
18658 case VAR_FUNC:
18659 EMSG(_("E703: Using a Funcref as a Number"));
18660 break;
18661 case VAR_STRING:
18662 if (varp->vval.v_string != NULL)
18663 vim_str2nr(varp->vval.v_string, NULL, NULL,
18664 TRUE, TRUE, &n, NULL);
18665 return n;
18666 case VAR_LIST:
18667 EMSG(_("E745: Using a List as a Number"));
18668 break;
18669 case VAR_DICT:
18670 EMSG(_("E728: Using a Dictionary as a Number"));
18671 break;
18672 default:
18673 EMSG2(_(e_intern2), "get_tv_number()");
18674 break;
18676 if (denote == NULL) /* useful for values that must be unsigned */
18677 n = -1;
18678 else
18679 *denote = TRUE;
18680 return n;
18684 * Get the lnum from the first argument.
18685 * Also accepts ".", "$", etc., but that only works for the current buffer.
18686 * Returns -1 on error.
18688 static linenr_T
18689 get_tv_lnum(argvars)
18690 typval_T *argvars;
18692 typval_T rettv;
18693 linenr_T lnum;
18695 lnum = get_tv_number_chk(&argvars[0], NULL);
18696 if (lnum == 0) /* no valid number, try using line() */
18698 rettv.v_type = VAR_NUMBER;
18699 f_line(argvars, &rettv);
18700 lnum = rettv.vval.v_number;
18701 clear_tv(&rettv);
18703 return lnum;
18707 * Get the lnum from the first argument.
18708 * Also accepts "$", then "buf" is used.
18709 * Returns 0 on error.
18711 static linenr_T
18712 get_tv_lnum_buf(argvars, buf)
18713 typval_T *argvars;
18714 buf_T *buf;
18716 if (argvars[0].v_type == VAR_STRING
18717 && argvars[0].vval.v_string != NULL
18718 && argvars[0].vval.v_string[0] == '$'
18719 && buf != NULL)
18720 return buf->b_ml.ml_line_count;
18721 return get_tv_number_chk(&argvars[0], NULL);
18725 * Get the string value of a variable.
18726 * If it is a Number variable, the number is converted into a string.
18727 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
18728 * get_tv_string_buf() uses a given buffer.
18729 * If the String variable has never been set, return an empty string.
18730 * Never returns NULL;
18731 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
18732 * NULL on error.
18734 static char_u *
18735 get_tv_string(varp)
18736 typval_T *varp;
18738 static char_u mybuf[NUMBUFLEN];
18740 return get_tv_string_buf(varp, mybuf);
18743 static char_u *
18744 get_tv_string_buf(varp, buf)
18745 typval_T *varp;
18746 char_u *buf;
18748 char_u *res = get_tv_string_buf_chk(varp, buf);
18750 return res != NULL ? res : (char_u *)"";
18753 char_u *
18754 get_tv_string_chk(varp)
18755 typval_T *varp;
18757 static char_u mybuf[NUMBUFLEN];
18759 return get_tv_string_buf_chk(varp, mybuf);
18762 static char_u *
18763 get_tv_string_buf_chk(varp, buf)
18764 typval_T *varp;
18765 char_u *buf;
18767 switch (varp->v_type)
18769 case VAR_NUMBER:
18770 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
18771 return buf;
18772 case VAR_FUNC:
18773 EMSG(_("E729: using Funcref as a String"));
18774 break;
18775 case VAR_LIST:
18776 EMSG(_("E730: using List as a String"));
18777 break;
18778 case VAR_DICT:
18779 EMSG(_("E731: using Dictionary as a String"));
18780 break;
18781 #ifdef FEAT_FLOAT
18782 case VAR_FLOAT:
18783 EMSG(_("E806: using Float as a String"));
18784 break;
18785 #endif
18786 case VAR_STRING:
18787 if (varp->vval.v_string != NULL)
18788 return varp->vval.v_string;
18789 return (char_u *)"";
18790 default:
18791 EMSG2(_(e_intern2), "get_tv_string_buf()");
18792 break;
18794 return NULL;
18798 * Find variable "name" in the list of variables.
18799 * Return a pointer to it if found, NULL if not found.
18800 * Careful: "a:0" variables don't have a name.
18801 * When "htp" is not NULL we are writing to the variable, set "htp" to the
18802 * hashtab_T used.
18804 static dictitem_T *
18805 find_var(name, htp)
18806 char_u *name;
18807 hashtab_T **htp;
18809 char_u *varname;
18810 hashtab_T *ht;
18812 ht = find_var_ht(name, &varname);
18813 if (htp != NULL)
18814 *htp = ht;
18815 if (ht == NULL)
18816 return NULL;
18817 return find_var_in_ht(ht, varname, htp != NULL);
18821 * Find variable "varname" in hashtab "ht".
18822 * Returns NULL if not found.
18824 static dictitem_T *
18825 find_var_in_ht(ht, varname, writing)
18826 hashtab_T *ht;
18827 char_u *varname;
18828 int writing;
18830 hashitem_T *hi;
18832 if (*varname == NUL)
18834 /* Must be something like "s:", otherwise "ht" would be NULL. */
18835 switch (varname[-2])
18837 case 's': return &SCRIPT_SV(current_SID).sv_var;
18838 case 'g': return &globvars_var;
18839 case 'v': return &vimvars_var;
18840 case 'b': return &curbuf->b_bufvar;
18841 case 'w': return &curwin->w_winvar;
18842 #ifdef FEAT_WINDOWS
18843 case 't': return &curtab->tp_winvar;
18844 #endif
18845 case 'l': return current_funccal == NULL
18846 ? NULL : &current_funccal->l_vars_var;
18847 case 'a': return current_funccal == NULL
18848 ? NULL : &current_funccal->l_avars_var;
18850 return NULL;
18853 hi = hash_find(ht, varname);
18854 if (HASHITEM_EMPTY(hi))
18856 /* For global variables we may try auto-loading the script. If it
18857 * worked find the variable again. Don't auto-load a script if it was
18858 * loaded already, otherwise it would be loaded every time when
18859 * checking if a function name is a Funcref variable. */
18860 if (ht == &globvarht && !writing
18861 && script_autoload(varname, FALSE) && !aborting())
18862 hi = hash_find(ht, varname);
18863 if (HASHITEM_EMPTY(hi))
18864 return NULL;
18866 return HI2DI(hi);
18870 * Find the hashtab used for a variable name.
18871 * Set "varname" to the start of name without ':'.
18873 static hashtab_T *
18874 find_var_ht(name, varname)
18875 char_u *name;
18876 char_u **varname;
18878 hashitem_T *hi;
18880 if (name[1] != ':')
18882 /* The name must not start with a colon or #. */
18883 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
18884 return NULL;
18885 *varname = name;
18887 /* "version" is "v:version" in all scopes */
18888 hi = hash_find(&compat_hashtab, name);
18889 if (!HASHITEM_EMPTY(hi))
18890 return &compat_hashtab;
18892 if (current_funccal == NULL)
18893 return &globvarht; /* global variable */
18894 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
18896 *varname = name + 2;
18897 if (*name == 'g') /* global variable */
18898 return &globvarht;
18899 /* There must be no ':' or '#' in the rest of the name, unless g: is used
18901 if (vim_strchr(name + 2, ':') != NULL
18902 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
18903 return NULL;
18904 if (*name == 'b') /* buffer variable */
18905 return &curbuf->b_vars.dv_hashtab;
18906 if (*name == 'w') /* window variable */
18907 return &curwin->w_vars.dv_hashtab;
18908 #ifdef FEAT_WINDOWS
18909 if (*name == 't') /* tab page variable */
18910 return &curtab->tp_vars.dv_hashtab;
18911 #endif
18912 if (*name == 'v') /* v: variable */
18913 return &vimvarht;
18914 if (*name == 'a' && current_funccal != NULL) /* function argument */
18915 return &current_funccal->l_avars.dv_hashtab;
18916 if (*name == 'l' && current_funccal != NULL) /* local function variable */
18917 return &current_funccal->l_vars.dv_hashtab;
18918 if (*name == 's' /* script variable */
18919 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
18920 return &SCRIPT_VARS(current_SID);
18921 return NULL;
18925 * Get the string value of a (global/local) variable.
18926 * Returns NULL when it doesn't exist.
18928 char_u *
18929 get_var_value(name)
18930 char_u *name;
18932 dictitem_T *v;
18934 v = find_var(name, NULL);
18935 if (v == NULL)
18936 return NULL;
18937 return get_tv_string(&v->di_tv);
18941 * Allocate a new hashtab for a sourced script. It will be used while
18942 * sourcing this script and when executing functions defined in the script.
18944 void
18945 new_script_vars(id)
18946 scid_T id;
18948 int i;
18949 hashtab_T *ht;
18950 scriptvar_T *sv;
18952 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
18954 /* Re-allocating ga_data means that an ht_array pointing to
18955 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
18956 * at its init value. Also reset "v_dict", it's always the same. */
18957 for (i = 1; i <= ga_scripts.ga_len; ++i)
18959 ht = &SCRIPT_VARS(i);
18960 if (ht->ht_mask == HT_INIT_SIZE - 1)
18961 ht->ht_array = ht->ht_smallarray;
18962 sv = &SCRIPT_SV(i);
18963 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
18966 while (ga_scripts.ga_len < id)
18968 sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
18969 init_var_dict(&sv->sv_dict, &sv->sv_var);
18970 ++ga_scripts.ga_len;
18976 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
18977 * point to it.
18979 void
18980 init_var_dict(dict, dict_var)
18981 dict_T *dict;
18982 dictitem_T *dict_var;
18984 hash_init(&dict->dv_hashtab);
18985 dict->dv_refcount = DO_NOT_FREE_CNT;
18986 dict->dv_copyID = 0;
18987 dict_var->di_tv.vval.v_dict = dict;
18988 dict_var->di_tv.v_type = VAR_DICT;
18989 dict_var->di_tv.v_lock = VAR_FIXED;
18990 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
18991 dict_var->di_key[0] = NUL;
18995 * Clean up a list of internal variables.
18996 * Frees all allocated variables and the value they contain.
18997 * Clears hashtab "ht", does not free it.
18999 void
19000 vars_clear(ht)
19001 hashtab_T *ht;
19003 vars_clear_ext(ht, TRUE);
19007 * Like vars_clear(), but only free the value if "free_val" is TRUE.
19009 static void
19010 vars_clear_ext(ht, free_val)
19011 hashtab_T *ht;
19012 int free_val;
19014 int todo;
19015 hashitem_T *hi;
19016 dictitem_T *v;
19018 hash_lock(ht);
19019 todo = (int)ht->ht_used;
19020 for (hi = ht->ht_array; todo > 0; ++hi)
19022 if (!HASHITEM_EMPTY(hi))
19024 --todo;
19026 /* Free the variable. Don't remove it from the hashtab,
19027 * ht_array might change then. hash_clear() takes care of it
19028 * later. */
19029 v = HI2DI(hi);
19030 if (free_val)
19031 clear_tv(&v->di_tv);
19032 if ((v->di_flags & DI_FLAGS_FIX) == 0)
19033 vim_free(v);
19036 hash_clear(ht);
19037 ht->ht_used = 0;
19041 * Delete a variable from hashtab "ht" at item "hi".
19042 * Clear the variable value and free the dictitem.
19044 static void
19045 delete_var(ht, hi)
19046 hashtab_T *ht;
19047 hashitem_T *hi;
19049 dictitem_T *di = HI2DI(hi);
19051 hash_remove(ht, hi);
19052 clear_tv(&di->di_tv);
19053 vim_free(di);
19057 * List the value of one internal variable.
19059 static void
19060 list_one_var(v, prefix, first)
19061 dictitem_T *v;
19062 char_u *prefix;
19063 int *first;
19065 char_u *tofree;
19066 char_u *s;
19067 char_u numbuf[NUMBUFLEN];
19069 current_copyID += COPYID_INC;
19070 s = echo_string(&v->di_tv, &tofree, numbuf, current_copyID);
19071 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
19072 s == NULL ? (char_u *)"" : s, first);
19073 vim_free(tofree);
19076 static void
19077 list_one_var_a(prefix, name, type, string, first)
19078 char_u *prefix;
19079 char_u *name;
19080 int type;
19081 char_u *string;
19082 int *first; /* when TRUE clear rest of screen and set to FALSE */
19084 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
19085 msg_start();
19086 msg_puts(prefix);
19087 if (name != NULL) /* "a:" vars don't have a name stored */
19088 msg_puts(name);
19089 msg_putchar(' ');
19090 msg_advance(22);
19091 if (type == VAR_NUMBER)
19092 msg_putchar('#');
19093 else if (type == VAR_FUNC)
19094 msg_putchar('*');
19095 else if (type == VAR_LIST)
19097 msg_putchar('[');
19098 if (*string == '[')
19099 ++string;
19101 else if (type == VAR_DICT)
19103 msg_putchar('{');
19104 if (*string == '{')
19105 ++string;
19107 else
19108 msg_putchar(' ');
19110 msg_outtrans(string);
19112 if (type == VAR_FUNC)
19113 msg_puts((char_u *)"()");
19114 if (*first)
19116 msg_clr_eos();
19117 *first = FALSE;
19122 * Set variable "name" to value in "tv".
19123 * If the variable already exists, the value is updated.
19124 * Otherwise the variable is created.
19126 static void
19127 set_var(name, tv, copy)
19128 char_u *name;
19129 typval_T *tv;
19130 int copy; /* make copy of value in "tv" */
19132 dictitem_T *v;
19133 char_u *varname;
19134 hashtab_T *ht;
19135 char_u *p;
19137 ht = find_var_ht(name, &varname);
19138 if (ht == NULL || *varname == NUL)
19140 EMSG2(_(e_illvar), name);
19141 return;
19143 v = find_var_in_ht(ht, varname, TRUE);
19145 if (tv->v_type == VAR_FUNC)
19147 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
19148 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
19149 ? name[2] : name[0]))
19151 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
19152 return;
19154 /* Don't allow hiding a function. When "v" is not NULL we migth be
19155 * assigning another function to the same var, the type is checked
19156 * below. */
19157 if (v == NULL && function_exists(name))
19159 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
19160 name);
19161 return;
19165 if (v != NULL)
19167 /* existing variable, need to clear the value */
19168 if (var_check_ro(v->di_flags, name)
19169 || tv_check_lock(v->di_tv.v_lock, name))
19170 return;
19171 if (v->di_tv.v_type != tv->v_type
19172 && !((v->di_tv.v_type == VAR_STRING
19173 || v->di_tv.v_type == VAR_NUMBER)
19174 && (tv->v_type == VAR_STRING
19175 || tv->v_type == VAR_NUMBER))
19176 #ifdef FEAT_FLOAT
19177 && !((v->di_tv.v_type == VAR_NUMBER
19178 || v->di_tv.v_type == VAR_FLOAT)
19179 && (tv->v_type == VAR_NUMBER
19180 || tv->v_type == VAR_FLOAT))
19181 #endif
19184 EMSG2(_("E706: Variable type mismatch for: %s"), name);
19185 return;
19189 * Handle setting internal v: variables separately: we don't change
19190 * the type.
19192 if (ht == &vimvarht)
19194 if (v->di_tv.v_type == VAR_STRING)
19196 vim_free(v->di_tv.vval.v_string);
19197 if (copy || tv->v_type != VAR_STRING)
19198 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
19199 else
19201 /* Take over the string to avoid an extra alloc/free. */
19202 v->di_tv.vval.v_string = tv->vval.v_string;
19203 tv->vval.v_string = NULL;
19206 else if (v->di_tv.v_type != VAR_NUMBER)
19207 EMSG2(_(e_intern2), "set_var()");
19208 else
19210 v->di_tv.vval.v_number = get_tv_number(tv);
19211 if (STRCMP(varname, "searchforward") == 0)
19212 set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
19214 return;
19217 clear_tv(&v->di_tv);
19219 else /* add a new variable */
19221 /* Can't add "v:" variable. */
19222 if (ht == &vimvarht)
19224 EMSG2(_(e_illvar), name);
19225 return;
19228 /* Make sure the variable name is valid. */
19229 for (p = varname; *p != NUL; ++p)
19230 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
19231 && *p != AUTOLOAD_CHAR)
19233 EMSG2(_(e_illvar), varname);
19234 return;
19237 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
19238 + STRLEN(varname)));
19239 if (v == NULL)
19240 return;
19241 STRCPY(v->di_key, varname);
19242 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
19244 vim_free(v);
19245 return;
19247 v->di_flags = 0;
19250 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
19251 copy_tv(tv, &v->di_tv);
19252 else
19254 v->di_tv = *tv;
19255 v->di_tv.v_lock = 0;
19256 init_tv(tv);
19261 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
19262 * Also give an error message.
19264 static int
19265 var_check_ro(flags, name)
19266 int flags;
19267 char_u *name;
19269 if (flags & DI_FLAGS_RO)
19271 EMSG2(_(e_readonlyvar), name);
19272 return TRUE;
19274 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
19276 EMSG2(_(e_readonlysbx), name);
19277 return TRUE;
19279 return FALSE;
19283 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
19284 * Also give an error message.
19286 static int
19287 var_check_fixed(flags, name)
19288 int flags;
19289 char_u *name;
19291 if (flags & DI_FLAGS_FIX)
19293 EMSG2(_("E795: Cannot delete variable %s"), name);
19294 return TRUE;
19296 return FALSE;
19300 * Return TRUE if typeval "tv" is set to be locked (immutable).
19301 * Also give an error message, using "name".
19303 static int
19304 tv_check_lock(lock, name)
19305 int lock;
19306 char_u *name;
19308 if (lock & VAR_LOCKED)
19310 EMSG2(_("E741: Value is locked: %s"),
19311 name == NULL ? (char_u *)_("Unknown") : name);
19312 return TRUE;
19314 if (lock & VAR_FIXED)
19316 EMSG2(_("E742: Cannot change value of %s"),
19317 name == NULL ? (char_u *)_("Unknown") : name);
19318 return TRUE;
19320 return FALSE;
19324 * Copy the values from typval_T "from" to typval_T "to".
19325 * When needed allocates string or increases reference count.
19326 * Does not make a copy of a list or dict but copies the reference!
19327 * It is OK for "from" and "to" to point to the same item. This is used to
19328 * make a copy later.
19330 void
19331 copy_tv(from, to)
19332 typval_T *from;
19333 typval_T *to;
19335 to->v_type = from->v_type;
19336 to->v_lock = 0;
19337 switch (from->v_type)
19339 case VAR_NUMBER:
19340 to->vval.v_number = from->vval.v_number;
19341 break;
19342 #ifdef FEAT_FLOAT
19343 case VAR_FLOAT:
19344 to->vval.v_float = from->vval.v_float;
19345 break;
19346 #endif
19347 case VAR_STRING:
19348 case VAR_FUNC:
19349 if (from->vval.v_string == NULL)
19350 to->vval.v_string = NULL;
19351 else
19353 to->vval.v_string = vim_strsave(from->vval.v_string);
19354 if (from->v_type == VAR_FUNC)
19355 func_ref(to->vval.v_string);
19357 break;
19358 case VAR_LIST:
19359 if (from->vval.v_list == NULL)
19360 to->vval.v_list = NULL;
19361 else
19363 to->vval.v_list = from->vval.v_list;
19364 ++to->vval.v_list->lv_refcount;
19366 break;
19367 case VAR_DICT:
19368 if (from->vval.v_dict == NULL)
19369 to->vval.v_dict = NULL;
19370 else
19372 to->vval.v_dict = from->vval.v_dict;
19373 ++to->vval.v_dict->dv_refcount;
19375 break;
19376 default:
19377 EMSG2(_(e_intern2), "copy_tv()");
19378 break;
19383 * Make a copy of an item.
19384 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
19385 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
19386 * reference to an already copied list/dict can be used.
19387 * Returns FAIL or OK.
19389 static int
19390 item_copy(from, to, deep, copyID)
19391 typval_T *from;
19392 typval_T *to;
19393 int deep;
19394 int copyID;
19396 static int recurse = 0;
19397 int ret = OK;
19399 if (recurse >= DICT_MAXNEST)
19401 EMSG(_("E698: variable nested too deep for making a copy"));
19402 return FAIL;
19404 ++recurse;
19406 switch (from->v_type)
19408 case VAR_NUMBER:
19409 #ifdef FEAT_FLOAT
19410 case VAR_FLOAT:
19411 #endif
19412 case VAR_STRING:
19413 case VAR_FUNC:
19414 copy_tv(from, to);
19415 break;
19416 case VAR_LIST:
19417 to->v_type = VAR_LIST;
19418 to->v_lock = 0;
19419 if (from->vval.v_list == NULL)
19420 to->vval.v_list = NULL;
19421 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
19423 /* use the copy made earlier */
19424 to->vval.v_list = from->vval.v_list->lv_copylist;
19425 ++to->vval.v_list->lv_refcount;
19427 else
19428 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
19429 if (to->vval.v_list == NULL)
19430 ret = FAIL;
19431 break;
19432 case VAR_DICT:
19433 to->v_type = VAR_DICT;
19434 to->v_lock = 0;
19435 if (from->vval.v_dict == NULL)
19436 to->vval.v_dict = NULL;
19437 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
19439 /* use the copy made earlier */
19440 to->vval.v_dict = from->vval.v_dict->dv_copydict;
19441 ++to->vval.v_dict->dv_refcount;
19443 else
19444 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
19445 if (to->vval.v_dict == NULL)
19446 ret = FAIL;
19447 break;
19448 default:
19449 EMSG2(_(e_intern2), "item_copy()");
19450 ret = FAIL;
19452 --recurse;
19453 return ret;
19457 * ":echo expr1 ..." print each argument separated with a space, add a
19458 * newline at the end.
19459 * ":echon expr1 ..." print each argument plain.
19461 void
19462 ex_echo(eap)
19463 exarg_T *eap;
19465 char_u *arg = eap->arg;
19466 typval_T rettv;
19467 char_u *tofree;
19468 char_u *p;
19469 int needclr = TRUE;
19470 int atstart = TRUE;
19471 char_u numbuf[NUMBUFLEN];
19473 if (eap->skip)
19474 ++emsg_skip;
19475 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
19477 /* If eval1() causes an error message the text from the command may
19478 * still need to be cleared. E.g., "echo 22,44". */
19479 need_clr_eos = needclr;
19481 p = arg;
19482 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19485 * Report the invalid expression unless the expression evaluation
19486 * has been cancelled due to an aborting error, an interrupt, or an
19487 * exception.
19489 if (!aborting())
19490 EMSG2(_(e_invexpr2), p);
19491 need_clr_eos = FALSE;
19492 break;
19494 need_clr_eos = FALSE;
19496 if (!eap->skip)
19498 if (atstart)
19500 atstart = FALSE;
19501 /* Call msg_start() after eval1(), evaluating the expression
19502 * may cause a message to appear. */
19503 if (eap->cmdidx == CMD_echo)
19504 msg_start();
19506 else if (eap->cmdidx == CMD_echo)
19507 msg_puts_attr((char_u *)" ", echo_attr);
19508 current_copyID += COPYID_INC;
19509 p = echo_string(&rettv, &tofree, numbuf, current_copyID);
19510 if (p != NULL)
19511 for ( ; *p != NUL && !got_int; ++p)
19513 if (*p == '\n' || *p == '\r' || *p == TAB)
19515 if (*p != TAB && needclr)
19517 /* remove any text still there from the command */
19518 msg_clr_eos();
19519 needclr = FALSE;
19521 msg_putchar_attr(*p, echo_attr);
19523 else
19525 #ifdef FEAT_MBYTE
19526 if (has_mbyte)
19528 int i = (*mb_ptr2len)(p);
19530 (void)msg_outtrans_len_attr(p, i, echo_attr);
19531 p += i - 1;
19533 else
19534 #endif
19535 (void)msg_outtrans_len_attr(p, 1, echo_attr);
19538 vim_free(tofree);
19540 clear_tv(&rettv);
19541 arg = skipwhite(arg);
19543 eap->nextcmd = check_nextcmd(arg);
19545 if (eap->skip)
19546 --emsg_skip;
19547 else
19549 /* remove text that may still be there from the command */
19550 if (needclr)
19551 msg_clr_eos();
19552 if (eap->cmdidx == CMD_echo)
19553 msg_end();
19558 * ":echohl {name}".
19560 void
19561 ex_echohl(eap)
19562 exarg_T *eap;
19564 int id;
19566 id = syn_name2id(eap->arg);
19567 if (id == 0)
19568 echo_attr = 0;
19569 else
19570 echo_attr = syn_id2attr(id);
19574 * ":execute expr1 ..." execute the result of an expression.
19575 * ":echomsg expr1 ..." Print a message
19576 * ":echoerr expr1 ..." Print an error
19577 * Each gets spaces around each argument and a newline at the end for
19578 * echo commands
19580 void
19581 ex_execute(eap)
19582 exarg_T *eap;
19584 char_u *arg = eap->arg;
19585 typval_T rettv;
19586 int ret = OK;
19587 char_u *p;
19588 garray_T ga;
19589 int len;
19590 int save_did_emsg;
19592 ga_init2(&ga, 1, 80);
19594 if (eap->skip)
19595 ++emsg_skip;
19596 while (*arg != NUL && *arg != '|' && *arg != '\n')
19598 p = arg;
19599 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19602 * Report the invalid expression unless the expression evaluation
19603 * has been cancelled due to an aborting error, an interrupt, or an
19604 * exception.
19606 if (!aborting())
19607 EMSG2(_(e_invexpr2), p);
19608 ret = FAIL;
19609 break;
19612 if (!eap->skip)
19614 p = get_tv_string(&rettv);
19615 len = (int)STRLEN(p);
19616 if (ga_grow(&ga, len + 2) == FAIL)
19618 clear_tv(&rettv);
19619 ret = FAIL;
19620 break;
19622 if (ga.ga_len)
19623 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
19624 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
19625 ga.ga_len += len;
19628 clear_tv(&rettv);
19629 arg = skipwhite(arg);
19632 if (ret != FAIL && ga.ga_data != NULL)
19634 if (eap->cmdidx == CMD_echomsg)
19636 MSG_ATTR(ga.ga_data, echo_attr);
19637 out_flush();
19639 else if (eap->cmdidx == CMD_echoerr)
19641 /* We don't want to abort following commands, restore did_emsg. */
19642 save_did_emsg = did_emsg;
19643 EMSG((char_u *)ga.ga_data);
19644 if (!force_abort)
19645 did_emsg = save_did_emsg;
19647 else if (eap->cmdidx == CMD_execute)
19648 do_cmdline((char_u *)ga.ga_data,
19649 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
19652 ga_clear(&ga);
19654 if (eap->skip)
19655 --emsg_skip;
19657 eap->nextcmd = check_nextcmd(arg);
19661 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
19662 * "arg" points to the "&" or '+' when called, to "option" when returning.
19663 * Returns NULL when no option name found. Otherwise pointer to the char
19664 * after the option name.
19666 static char_u *
19667 find_option_end(arg, opt_flags)
19668 char_u **arg;
19669 int *opt_flags;
19671 char_u *p = *arg;
19673 ++p;
19674 if (*p == 'g' && p[1] == ':')
19676 *opt_flags = OPT_GLOBAL;
19677 p += 2;
19679 else if (*p == 'l' && p[1] == ':')
19681 *opt_flags = OPT_LOCAL;
19682 p += 2;
19684 else
19685 *opt_flags = 0;
19687 if (!ASCII_ISALPHA(*p))
19688 return NULL;
19689 *arg = p;
19691 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
19692 p += 4; /* termcap option */
19693 else
19694 while (ASCII_ISALPHA(*p))
19695 ++p;
19696 return p;
19700 * ":function"
19702 void
19703 ex_function(eap)
19704 exarg_T *eap;
19706 char_u *theline;
19707 int j;
19708 int c;
19709 int saved_did_emsg;
19710 char_u *name = NULL;
19711 char_u *p;
19712 char_u *arg;
19713 char_u *line_arg = NULL;
19714 garray_T newargs;
19715 garray_T newlines;
19716 int varargs = FALSE;
19717 int mustend = FALSE;
19718 int flags = 0;
19719 ufunc_T *fp;
19720 int indent;
19721 int nesting;
19722 char_u *skip_until = NULL;
19723 dictitem_T *v;
19724 funcdict_T fudi;
19725 static int func_nr = 0; /* number for nameless function */
19726 int paren;
19727 hashtab_T *ht;
19728 int todo;
19729 hashitem_T *hi;
19730 int sourcing_lnum_off;
19733 * ":function" without argument: list functions.
19735 if (ends_excmd(*eap->arg))
19737 if (!eap->skip)
19739 todo = (int)func_hashtab.ht_used;
19740 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19742 if (!HASHITEM_EMPTY(hi))
19744 --todo;
19745 fp = HI2UF(hi);
19746 if (!isdigit(*fp->uf_name))
19747 list_func_head(fp, FALSE);
19751 eap->nextcmd = check_nextcmd(eap->arg);
19752 return;
19756 * ":function /pat": list functions matching pattern.
19758 if (*eap->arg == '/')
19760 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
19761 if (!eap->skip)
19763 regmatch_T regmatch;
19765 c = *p;
19766 *p = NUL;
19767 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
19768 *p = c;
19769 if (regmatch.regprog != NULL)
19771 regmatch.rm_ic = p_ic;
19773 todo = (int)func_hashtab.ht_used;
19774 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19776 if (!HASHITEM_EMPTY(hi))
19778 --todo;
19779 fp = HI2UF(hi);
19780 if (!isdigit(*fp->uf_name)
19781 && vim_regexec(&regmatch, fp->uf_name, 0))
19782 list_func_head(fp, FALSE);
19785 vim_free(regmatch.regprog);
19788 if (*p == '/')
19789 ++p;
19790 eap->nextcmd = check_nextcmd(p);
19791 return;
19795 * Get the function name. There are these situations:
19796 * func normal function name
19797 * "name" == func, "fudi.fd_dict" == NULL
19798 * dict.func new dictionary entry
19799 * "name" == NULL, "fudi.fd_dict" set,
19800 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
19801 * dict.func existing dict entry with a Funcref
19802 * "name" == func, "fudi.fd_dict" set,
19803 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19804 * dict.func existing dict entry that's not a Funcref
19805 * "name" == NULL, "fudi.fd_dict" set,
19806 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19808 p = eap->arg;
19809 name = trans_function_name(&p, eap->skip, 0, &fudi);
19810 paren = (vim_strchr(p, '(') != NULL);
19811 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
19814 * Return on an invalid expression in braces, unless the expression
19815 * evaluation has been cancelled due to an aborting error, an
19816 * interrupt, or an exception.
19818 if (!aborting())
19820 if (!eap->skip && fudi.fd_newkey != NULL)
19821 EMSG2(_(e_dictkey), fudi.fd_newkey);
19822 vim_free(fudi.fd_newkey);
19823 return;
19825 else
19826 eap->skip = TRUE;
19829 /* An error in a function call during evaluation of an expression in magic
19830 * braces should not cause the function not to be defined. */
19831 saved_did_emsg = did_emsg;
19832 did_emsg = FALSE;
19835 * ":function func" with only function name: list function.
19837 if (!paren)
19839 if (!ends_excmd(*skipwhite(p)))
19841 EMSG(_(e_trailing));
19842 goto ret_free;
19844 eap->nextcmd = check_nextcmd(p);
19845 if (eap->nextcmd != NULL)
19846 *p = NUL;
19847 if (!eap->skip && !got_int)
19849 fp = find_func(name);
19850 if (fp != NULL)
19852 list_func_head(fp, TRUE);
19853 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
19855 if (FUNCLINE(fp, j) == NULL)
19856 continue;
19857 msg_putchar('\n');
19858 msg_outnum((long)(j + 1));
19859 if (j < 9)
19860 msg_putchar(' ');
19861 if (j < 99)
19862 msg_putchar(' ');
19863 msg_prt_line(FUNCLINE(fp, j), FALSE);
19864 out_flush(); /* show a line at a time */
19865 ui_breakcheck();
19867 if (!got_int)
19869 msg_putchar('\n');
19870 msg_puts((char_u *)" endfunction");
19873 else
19874 emsg_funcname(N_("E123: Undefined function: %s"), name);
19876 goto ret_free;
19880 * ":function name(arg1, arg2)" Define function.
19882 p = skipwhite(p);
19883 if (*p != '(')
19885 if (!eap->skip)
19887 EMSG2(_("E124: Missing '(': %s"), eap->arg);
19888 goto ret_free;
19890 /* attempt to continue by skipping some text */
19891 if (vim_strchr(p, '(') != NULL)
19892 p = vim_strchr(p, '(');
19894 p = skipwhite(p + 1);
19896 ga_init2(&newargs, (int)sizeof(char_u *), 3);
19897 ga_init2(&newlines, (int)sizeof(char_u *), 3);
19899 if (!eap->skip)
19901 /* Check the name of the function. Unless it's a dictionary function
19902 * (that we are overwriting). */
19903 if (name != NULL)
19904 arg = name;
19905 else
19906 arg = fudi.fd_newkey;
19907 if (arg != NULL && (fudi.fd_di == NULL
19908 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
19910 if (*arg == K_SPECIAL)
19911 j = 3;
19912 else
19913 j = 0;
19914 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
19915 : eval_isnamec(arg[j])))
19916 ++j;
19917 if (arg[j] != NUL)
19918 emsg_funcname((char *)e_invarg2, arg);
19923 * Isolate the arguments: "arg1, arg2, ...)"
19925 while (*p != ')')
19927 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
19929 varargs = TRUE;
19930 p += 3;
19931 mustend = TRUE;
19933 else
19935 arg = p;
19936 while (ASCII_ISALNUM(*p) || *p == '_')
19937 ++p;
19938 if (arg == p || isdigit(*arg)
19939 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
19940 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
19942 if (!eap->skip)
19943 EMSG2(_("E125: Illegal argument: %s"), arg);
19944 break;
19946 if (ga_grow(&newargs, 1) == FAIL)
19947 goto erret;
19948 c = *p;
19949 *p = NUL;
19950 arg = vim_strsave(arg);
19951 if (arg == NULL)
19952 goto erret;
19953 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
19954 *p = c;
19955 newargs.ga_len++;
19956 if (*p == ',')
19957 ++p;
19958 else
19959 mustend = TRUE;
19961 p = skipwhite(p);
19962 if (mustend && *p != ')')
19964 if (!eap->skip)
19965 EMSG2(_(e_invarg2), eap->arg);
19966 break;
19969 ++p; /* skip the ')' */
19971 /* find extra arguments "range", "dict" and "abort" */
19972 for (;;)
19974 p = skipwhite(p);
19975 if (STRNCMP(p, "range", 5) == 0)
19977 flags |= FC_RANGE;
19978 p += 5;
19980 else if (STRNCMP(p, "dict", 4) == 0)
19982 flags |= FC_DICT;
19983 p += 4;
19985 else if (STRNCMP(p, "abort", 5) == 0)
19987 flags |= FC_ABORT;
19988 p += 5;
19990 else
19991 break;
19994 /* When there is a line break use what follows for the function body.
19995 * Makes 'exe "func Test()\n...\nendfunc"' work. */
19996 if (*p == '\n')
19997 line_arg = p + 1;
19998 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
19999 EMSG(_(e_trailing));
20002 * Read the body of the function, until ":endfunction" is found.
20004 if (KeyTyped)
20006 /* Check if the function already exists, don't let the user type the
20007 * whole function before telling him it doesn't work! For a script we
20008 * need to skip the body to be able to find what follows. */
20009 if (!eap->skip && !eap->forceit)
20011 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
20012 EMSG(_(e_funcdict));
20013 else if (name != NULL && find_func(name) != NULL)
20014 emsg_funcname(e_funcexts, name);
20017 if (!eap->skip && did_emsg)
20018 goto erret;
20020 msg_putchar('\n'); /* don't overwrite the function name */
20021 cmdline_row = msg_row;
20024 indent = 2;
20025 nesting = 0;
20026 for (;;)
20028 msg_scroll = TRUE;
20029 need_wait_return = FALSE;
20030 sourcing_lnum_off = sourcing_lnum;
20032 if (line_arg != NULL)
20034 /* Use eap->arg, split up in parts by line breaks. */
20035 theline = line_arg;
20036 p = vim_strchr(theline, '\n');
20037 if (p == NULL)
20038 line_arg += STRLEN(line_arg);
20039 else
20041 *p = NUL;
20042 line_arg = p + 1;
20045 else if (eap->getline == NULL)
20046 theline = getcmdline(':', 0L, indent);
20047 else
20048 theline = eap->getline(':', eap->cookie, indent);
20049 if (KeyTyped)
20050 lines_left = Rows - 1;
20051 if (theline == NULL)
20053 EMSG(_("E126: Missing :endfunction"));
20054 goto erret;
20057 /* Detect line continuation: sourcing_lnum increased more than one. */
20058 if (sourcing_lnum > sourcing_lnum_off + 1)
20059 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
20060 else
20061 sourcing_lnum_off = 0;
20063 if (skip_until != NULL)
20065 /* between ":append" and "." and between ":python <<EOF" and "EOF"
20066 * don't check for ":endfunc". */
20067 if (STRCMP(theline, skip_until) == 0)
20069 vim_free(skip_until);
20070 skip_until = NULL;
20073 else
20075 /* skip ':' and blanks*/
20076 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
20079 /* Check for "endfunction". */
20080 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
20082 if (line_arg == NULL)
20083 vim_free(theline);
20084 break;
20087 /* Increase indent inside "if", "while", "for" and "try", decrease
20088 * at "end". */
20089 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
20090 indent -= 2;
20091 else if (STRNCMP(p, "if", 2) == 0
20092 || STRNCMP(p, "wh", 2) == 0
20093 || STRNCMP(p, "for", 3) == 0
20094 || STRNCMP(p, "try", 3) == 0)
20095 indent += 2;
20097 /* Check for defining a function inside this function. */
20098 if (checkforcmd(&p, "function", 2))
20100 if (*p == '!')
20101 p = skipwhite(p + 1);
20102 p += eval_fname_script(p);
20103 if (ASCII_ISALPHA(*p))
20105 vim_free(trans_function_name(&p, TRUE, 0, NULL));
20106 if (*skipwhite(p) == '(')
20108 ++nesting;
20109 indent += 2;
20114 /* Check for ":append" or ":insert". */
20115 p = skip_range(p, NULL);
20116 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
20117 || (p[0] == 'i'
20118 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
20119 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
20120 skip_until = vim_strsave((char_u *)".");
20122 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
20123 arg = skipwhite(skiptowhite(p));
20124 if (arg[0] == '<' && arg[1] =='<'
20125 && ((p[0] == 'p' && p[1] == 'y'
20126 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
20127 || (p[0] == 'p' && p[1] == 'e'
20128 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
20129 || (p[0] == 't' && p[1] == 'c'
20130 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
20131 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
20132 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
20133 || (p[0] == 'm' && p[1] == 'z'
20134 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
20137 /* ":python <<" continues until a dot, like ":append" */
20138 p = skipwhite(arg + 2);
20139 if (*p == NUL)
20140 skip_until = vim_strsave((char_u *)".");
20141 else
20142 skip_until = vim_strsave(p);
20146 /* Add the line to the function. */
20147 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
20149 if (line_arg == NULL)
20150 vim_free(theline);
20151 goto erret;
20154 /* Copy the line to newly allocated memory. get_one_sourceline()
20155 * allocates 250 bytes per line, this saves 80% on average. The cost
20156 * is an extra alloc/free. */
20157 p = vim_strsave(theline);
20158 if (p != NULL)
20160 if (line_arg == NULL)
20161 vim_free(theline);
20162 theline = p;
20165 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
20167 /* Add NULL lines for continuation lines, so that the line count is
20168 * equal to the index in the growarray. */
20169 while (sourcing_lnum_off-- > 0)
20170 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
20172 /* Check for end of eap->arg. */
20173 if (line_arg != NULL && *line_arg == NUL)
20174 line_arg = NULL;
20177 /* Don't define the function when skipping commands or when an error was
20178 * detected. */
20179 if (eap->skip || did_emsg)
20180 goto erret;
20183 * If there are no errors, add the function
20185 if (fudi.fd_dict == NULL)
20187 v = find_var(name, &ht);
20188 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
20190 emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
20191 name);
20192 goto erret;
20195 fp = find_func(name);
20196 if (fp != NULL)
20198 if (!eap->forceit)
20200 emsg_funcname(e_funcexts, name);
20201 goto erret;
20203 if (fp->uf_calls > 0)
20205 emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"),
20206 name);
20207 goto erret;
20209 /* redefine existing function */
20210 ga_clear_strings(&(fp->uf_args));
20211 ga_clear_strings(&(fp->uf_lines));
20212 vim_free(name);
20213 name = NULL;
20216 else
20218 char numbuf[20];
20220 fp = NULL;
20221 if (fudi.fd_newkey == NULL && !eap->forceit)
20223 EMSG(_(e_funcdict));
20224 goto erret;
20226 if (fudi.fd_di == NULL)
20228 /* Can't add a function to a locked dictionary */
20229 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
20230 goto erret;
20232 /* Can't change an existing function if it is locked */
20233 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
20234 goto erret;
20236 /* Give the function a sequential number. Can only be used with a
20237 * Funcref! */
20238 vim_free(name);
20239 sprintf(numbuf, "%d", ++func_nr);
20240 name = vim_strsave((char_u *)numbuf);
20241 if (name == NULL)
20242 goto erret;
20245 if (fp == NULL)
20247 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
20249 int slen, plen;
20250 char_u *scriptname;
20252 /* Check that the autoload name matches the script name. */
20253 j = FAIL;
20254 if (sourcing_name != NULL)
20256 scriptname = autoload_name(name);
20257 if (scriptname != NULL)
20259 p = vim_strchr(scriptname, '/');
20260 plen = (int)STRLEN(p);
20261 slen = (int)STRLEN(sourcing_name);
20262 if (slen > plen && fnamecmp(p,
20263 sourcing_name + slen - plen) == 0)
20264 j = OK;
20265 vim_free(scriptname);
20268 if (j == FAIL)
20270 EMSG2(_("E746: Function name does not match script file name: %s"), name);
20271 goto erret;
20275 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
20276 if (fp == NULL)
20277 goto erret;
20279 if (fudi.fd_dict != NULL)
20281 if (fudi.fd_di == NULL)
20283 /* add new dict entry */
20284 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
20285 if (fudi.fd_di == NULL)
20287 vim_free(fp);
20288 goto erret;
20290 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
20292 vim_free(fudi.fd_di);
20293 vim_free(fp);
20294 goto erret;
20297 else
20298 /* overwrite existing dict entry */
20299 clear_tv(&fudi.fd_di->di_tv);
20300 fudi.fd_di->di_tv.v_type = VAR_FUNC;
20301 fudi.fd_di->di_tv.v_lock = 0;
20302 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
20303 fp->uf_refcount = 1;
20305 /* behave like "dict" was used */
20306 flags |= FC_DICT;
20309 /* insert the new function in the function list */
20310 STRCPY(fp->uf_name, name);
20311 hash_add(&func_hashtab, UF2HIKEY(fp));
20313 fp->uf_args = newargs;
20314 fp->uf_lines = newlines;
20315 #ifdef FEAT_PROFILE
20316 fp->uf_tml_count = NULL;
20317 fp->uf_tml_total = NULL;
20318 fp->uf_tml_self = NULL;
20319 fp->uf_profiling = FALSE;
20320 if (prof_def_func())
20321 func_do_profile(fp);
20322 #endif
20323 fp->uf_varargs = varargs;
20324 fp->uf_flags = flags;
20325 fp->uf_calls = 0;
20326 fp->uf_script_ID = current_SID;
20327 goto ret_free;
20329 erret:
20330 ga_clear_strings(&newargs);
20331 ga_clear_strings(&newlines);
20332 ret_free:
20333 vim_free(skip_until);
20334 vim_free(fudi.fd_newkey);
20335 vim_free(name);
20336 did_emsg |= saved_did_emsg;
20340 * Get a function name, translating "<SID>" and "<SNR>".
20341 * Also handles a Funcref in a List or Dictionary.
20342 * Returns the function name in allocated memory, or NULL for failure.
20343 * flags:
20344 * TFN_INT: internal function name OK
20345 * TFN_QUIET: be quiet
20346 * Advances "pp" to just after the function name (if no error).
20348 static char_u *
20349 trans_function_name(pp, skip, flags, fdp)
20350 char_u **pp;
20351 int skip; /* only find the end, don't evaluate */
20352 int flags;
20353 funcdict_T *fdp; /* return: info about dictionary used */
20355 char_u *name = NULL;
20356 char_u *start;
20357 char_u *end;
20358 int lead;
20359 char_u sid_buf[20];
20360 int len;
20361 lval_T lv;
20363 if (fdp != NULL)
20364 vim_memset(fdp, 0, sizeof(funcdict_T));
20365 start = *pp;
20367 /* Check for hard coded <SNR>: already translated function ID (from a user
20368 * command). */
20369 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
20370 && (*pp)[2] == (int)KE_SNR)
20372 *pp += 3;
20373 len = get_id_len(pp) + 3;
20374 return vim_strnsave(start, len);
20377 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
20378 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
20379 lead = eval_fname_script(start);
20380 if (lead > 2)
20381 start += lead;
20383 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
20384 lead > 2 ? 0 : FNE_CHECK_START);
20385 if (end == start)
20387 if (!skip)
20388 EMSG(_("E129: Function name required"));
20389 goto theend;
20391 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
20394 * Report an invalid expression in braces, unless the expression
20395 * evaluation has been cancelled due to an aborting error, an
20396 * interrupt, or an exception.
20398 if (!aborting())
20400 if (end != NULL)
20401 EMSG2(_(e_invarg2), start);
20403 else
20404 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
20405 goto theend;
20408 if (lv.ll_tv != NULL)
20410 if (fdp != NULL)
20412 fdp->fd_dict = lv.ll_dict;
20413 fdp->fd_newkey = lv.ll_newkey;
20414 lv.ll_newkey = NULL;
20415 fdp->fd_di = lv.ll_di;
20417 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
20419 name = vim_strsave(lv.ll_tv->vval.v_string);
20420 *pp = end;
20422 else
20424 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
20425 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
20426 EMSG(_(e_funcref));
20427 else
20428 *pp = end;
20429 name = NULL;
20431 goto theend;
20434 if (lv.ll_name == NULL)
20436 /* Error found, but continue after the function name. */
20437 *pp = end;
20438 goto theend;
20441 /* Check if the name is a Funcref. If so, use the value. */
20442 if (lv.ll_exp_name != NULL)
20444 len = (int)STRLEN(lv.ll_exp_name);
20445 name = deref_func_name(lv.ll_exp_name, &len);
20446 if (name == lv.ll_exp_name)
20447 name = NULL;
20449 else
20451 len = (int)(end - *pp);
20452 name = deref_func_name(*pp, &len);
20453 if (name == *pp)
20454 name = NULL;
20456 if (name != NULL)
20458 name = vim_strsave(name);
20459 *pp = end;
20460 goto theend;
20463 if (lv.ll_exp_name != NULL)
20465 len = (int)STRLEN(lv.ll_exp_name);
20466 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
20467 && STRNCMP(lv.ll_name, "s:", 2) == 0)
20469 /* When there was "s:" already or the name expanded to get a
20470 * leading "s:" then remove it. */
20471 lv.ll_name += 2;
20472 len -= 2;
20473 lead = 2;
20476 else
20478 if (lead == 2) /* skip over "s:" */
20479 lv.ll_name += 2;
20480 len = (int)(end - lv.ll_name);
20484 * Copy the function name to allocated memory.
20485 * Accept <SID>name() inside a script, translate into <SNR>123_name().
20486 * Accept <SNR>123_name() outside a script.
20488 if (skip)
20489 lead = 0; /* do nothing */
20490 else if (lead > 0)
20492 lead = 3;
20493 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
20494 || eval_fname_sid(*pp))
20496 /* It's "s:" or "<SID>" */
20497 if (current_SID <= 0)
20499 EMSG(_(e_usingsid));
20500 goto theend;
20502 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
20503 lead += (int)STRLEN(sid_buf);
20506 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
20508 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
20509 goto theend;
20511 name = alloc((unsigned)(len + lead + 1));
20512 if (name != NULL)
20514 if (lead > 0)
20516 name[0] = K_SPECIAL;
20517 name[1] = KS_EXTRA;
20518 name[2] = (int)KE_SNR;
20519 if (lead > 3) /* If it's "<SID>" */
20520 STRCPY(name + 3, sid_buf);
20522 mch_memmove(name + lead, lv.ll_name, (size_t)len);
20523 name[len + lead] = NUL;
20525 *pp = end;
20527 theend:
20528 clear_lval(&lv);
20529 return name;
20533 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
20534 * Return 2 if "p" starts with "s:".
20535 * Return 0 otherwise.
20537 static int
20538 eval_fname_script(p)
20539 char_u *p;
20541 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
20542 || STRNICMP(p + 1, "SNR>", 4) == 0))
20543 return 5;
20544 if (p[0] == 's' && p[1] == ':')
20545 return 2;
20546 return 0;
20550 * Return TRUE if "p" starts with "<SID>" or "s:".
20551 * Only works if eval_fname_script() returned non-zero for "p"!
20553 static int
20554 eval_fname_sid(p)
20555 char_u *p;
20557 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
20561 * List the head of the function: "name(arg1, arg2)".
20563 static void
20564 list_func_head(fp, indent)
20565 ufunc_T *fp;
20566 int indent;
20568 int j;
20570 msg_start();
20571 if (indent)
20572 MSG_PUTS(" ");
20573 MSG_PUTS("function ");
20574 if (fp->uf_name[0] == K_SPECIAL)
20576 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
20577 msg_puts(fp->uf_name + 3);
20579 else
20580 msg_puts(fp->uf_name);
20581 msg_putchar('(');
20582 for (j = 0; j < fp->uf_args.ga_len; ++j)
20584 if (j)
20585 MSG_PUTS(", ");
20586 msg_puts(FUNCARG(fp, j));
20588 if (fp->uf_varargs)
20590 if (j)
20591 MSG_PUTS(", ");
20592 MSG_PUTS("...");
20594 msg_putchar(')');
20595 msg_clr_eos();
20596 if (p_verbose > 0)
20597 last_set_msg(fp->uf_script_ID);
20601 * Find a function by name, return pointer to it in ufuncs.
20602 * Return NULL for unknown function.
20604 static ufunc_T *
20605 find_func(name)
20606 char_u *name;
20608 hashitem_T *hi;
20610 hi = hash_find(&func_hashtab, name);
20611 if (!HASHITEM_EMPTY(hi))
20612 return HI2UF(hi);
20613 return NULL;
20616 #if defined(EXITFREE) || defined(PROTO)
20617 void
20618 free_all_functions()
20620 hashitem_T *hi;
20622 /* Need to start all over every time, because func_free() may change the
20623 * hash table. */
20624 while (func_hashtab.ht_used > 0)
20625 for (hi = func_hashtab.ht_array; ; ++hi)
20626 if (!HASHITEM_EMPTY(hi))
20628 func_free(HI2UF(hi));
20629 break;
20632 #endif
20635 * Return TRUE if a function "name" exists.
20637 static int
20638 function_exists(name)
20639 char_u *name;
20641 char_u *nm = name;
20642 char_u *p;
20643 int n = FALSE;
20645 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
20646 nm = skipwhite(nm);
20648 /* Only accept "funcname", "funcname ", "funcname (..." and
20649 * "funcname(...", not "funcname!...". */
20650 if (p != NULL && (*nm == NUL || *nm == '('))
20652 if (builtin_function(p))
20653 n = (find_internal_func(p) >= 0);
20654 else
20655 n = (find_func(p) != NULL);
20657 vim_free(p);
20658 return n;
20662 * Return TRUE if "name" looks like a builtin function name: starts with a
20663 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
20665 static int
20666 builtin_function(name)
20667 char_u *name;
20669 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
20670 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
20673 #if defined(FEAT_PROFILE) || defined(PROTO)
20675 * Start profiling function "fp".
20677 static void
20678 func_do_profile(fp)
20679 ufunc_T *fp;
20681 fp->uf_tm_count = 0;
20682 profile_zero(&fp->uf_tm_self);
20683 profile_zero(&fp->uf_tm_total);
20684 if (fp->uf_tml_count == NULL)
20685 fp->uf_tml_count = (int *)alloc_clear((unsigned)
20686 (sizeof(int) * fp->uf_lines.ga_len));
20687 if (fp->uf_tml_total == NULL)
20688 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
20689 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20690 if (fp->uf_tml_self == NULL)
20691 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
20692 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20693 fp->uf_tml_idx = -1;
20694 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
20695 || fp->uf_tml_self == NULL)
20696 return; /* out of memory */
20698 fp->uf_profiling = TRUE;
20702 * Dump the profiling results for all functions in file "fd".
20704 void
20705 func_dump_profile(fd)
20706 FILE *fd;
20708 hashitem_T *hi;
20709 int todo;
20710 ufunc_T *fp;
20711 int i;
20712 ufunc_T **sorttab;
20713 int st_len = 0;
20715 todo = (int)func_hashtab.ht_used;
20716 if (todo == 0)
20717 return; /* nothing to dump */
20719 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
20721 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
20723 if (!HASHITEM_EMPTY(hi))
20725 --todo;
20726 fp = HI2UF(hi);
20727 if (fp->uf_profiling)
20729 if (sorttab != NULL)
20730 sorttab[st_len++] = fp;
20732 if (fp->uf_name[0] == K_SPECIAL)
20733 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
20734 else
20735 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
20736 if (fp->uf_tm_count == 1)
20737 fprintf(fd, "Called 1 time\n");
20738 else
20739 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
20740 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
20741 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
20742 fprintf(fd, "\n");
20743 fprintf(fd, "count total (s) self (s)\n");
20745 for (i = 0; i < fp->uf_lines.ga_len; ++i)
20747 if (FUNCLINE(fp, i) == NULL)
20748 continue;
20749 prof_func_line(fd, fp->uf_tml_count[i],
20750 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
20751 fprintf(fd, "%s\n", FUNCLINE(fp, i));
20753 fprintf(fd, "\n");
20758 if (sorttab != NULL && st_len > 0)
20760 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20761 prof_total_cmp);
20762 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
20763 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20764 prof_self_cmp);
20765 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
20768 vim_free(sorttab);
20771 static void
20772 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
20773 FILE *fd;
20774 ufunc_T **sorttab;
20775 int st_len;
20776 char *title;
20777 int prefer_self; /* when equal print only self time */
20779 int i;
20780 ufunc_T *fp;
20782 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
20783 fprintf(fd, "count total (s) self (s) function\n");
20784 for (i = 0; i < 20 && i < st_len; ++i)
20786 fp = sorttab[i];
20787 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
20788 prefer_self);
20789 if (fp->uf_name[0] == K_SPECIAL)
20790 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
20791 else
20792 fprintf(fd, " %s()\n", fp->uf_name);
20794 fprintf(fd, "\n");
20798 * Print the count and times for one function or function line.
20800 static void
20801 prof_func_line(fd, count, total, self, prefer_self)
20802 FILE *fd;
20803 int count;
20804 proftime_T *total;
20805 proftime_T *self;
20806 int prefer_self; /* when equal print only self time */
20808 if (count > 0)
20810 fprintf(fd, "%5d ", count);
20811 if (prefer_self && profile_equal(total, self))
20812 fprintf(fd, " ");
20813 else
20814 fprintf(fd, "%s ", profile_msg(total));
20815 if (!prefer_self && profile_equal(total, self))
20816 fprintf(fd, " ");
20817 else
20818 fprintf(fd, "%s ", profile_msg(self));
20820 else
20821 fprintf(fd, " ");
20825 * Compare function for total time sorting.
20827 static int
20828 #ifdef __BORLANDC__
20829 _RTLENTRYF
20830 #endif
20831 prof_total_cmp(s1, s2)
20832 const void *s1;
20833 const void *s2;
20835 ufunc_T *p1, *p2;
20837 p1 = *(ufunc_T **)s1;
20838 p2 = *(ufunc_T **)s2;
20839 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
20843 * Compare function for self time sorting.
20845 static int
20846 #ifdef __BORLANDC__
20847 _RTLENTRYF
20848 #endif
20849 prof_self_cmp(s1, s2)
20850 const void *s1;
20851 const void *s2;
20853 ufunc_T *p1, *p2;
20855 p1 = *(ufunc_T **)s1;
20856 p2 = *(ufunc_T **)s2;
20857 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
20860 #endif
20863 * If "name" has a package name try autoloading the script for it.
20864 * Return TRUE if a package was loaded.
20866 static int
20867 script_autoload(name, reload)
20868 char_u *name;
20869 int reload; /* load script again when already loaded */
20871 char_u *p;
20872 char_u *scriptname, *tofree;
20873 int ret = FALSE;
20874 int i;
20876 /* If there is no '#' after name[0] there is no package name. */
20877 p = vim_strchr(name, AUTOLOAD_CHAR);
20878 if (p == NULL || p == name)
20879 return FALSE;
20881 tofree = scriptname = autoload_name(name);
20883 /* Find the name in the list of previously loaded package names. Skip
20884 * "autoload/", it's always the same. */
20885 for (i = 0; i < ga_loaded.ga_len; ++i)
20886 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
20887 break;
20888 if (!reload && i < ga_loaded.ga_len)
20889 ret = FALSE; /* was loaded already */
20890 else
20892 /* Remember the name if it wasn't loaded already. */
20893 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
20895 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
20896 tofree = NULL;
20899 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
20900 if (source_runtime(scriptname, FALSE) == OK)
20901 ret = TRUE;
20904 vim_free(tofree);
20905 return ret;
20909 * Return the autoload script name for a function or variable name.
20910 * Returns NULL when out of memory.
20912 static char_u *
20913 autoload_name(name)
20914 char_u *name;
20916 char_u *p;
20917 char_u *scriptname;
20919 /* Get the script file name: replace '#' with '/', append ".vim". */
20920 scriptname = alloc((unsigned)(STRLEN(name) + 14));
20921 if (scriptname == NULL)
20922 return FALSE;
20923 STRCPY(scriptname, "autoload/");
20924 STRCAT(scriptname, name);
20925 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
20926 STRCAT(scriptname, ".vim");
20927 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
20928 *p = '/';
20929 return scriptname;
20932 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
20935 * Function given to ExpandGeneric() to obtain the list of user defined
20936 * function names.
20938 char_u *
20939 get_user_func_name(xp, idx)
20940 expand_T *xp;
20941 int idx;
20943 static long_u done;
20944 static hashitem_T *hi;
20945 ufunc_T *fp;
20947 if (idx == 0)
20949 done = 0;
20950 hi = func_hashtab.ht_array;
20952 if (done < func_hashtab.ht_used)
20954 if (done++ > 0)
20955 ++hi;
20956 while (HASHITEM_EMPTY(hi))
20957 ++hi;
20958 fp = HI2UF(hi);
20960 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
20961 return fp->uf_name; /* prevents overflow */
20963 cat_func_name(IObuff, fp);
20964 if (xp->xp_context != EXPAND_USER_FUNC)
20966 STRCAT(IObuff, "(");
20967 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
20968 STRCAT(IObuff, ")");
20970 return IObuff;
20972 return NULL;
20975 #endif /* FEAT_CMDL_COMPL */
20978 * Copy the function name of "fp" to buffer "buf".
20979 * "buf" must be able to hold the function name plus three bytes.
20980 * Takes care of script-local function names.
20982 static void
20983 cat_func_name(buf, fp)
20984 char_u *buf;
20985 ufunc_T *fp;
20987 if (fp->uf_name[0] == K_SPECIAL)
20989 STRCPY(buf, "<SNR>");
20990 STRCAT(buf, fp->uf_name + 3);
20992 else
20993 STRCPY(buf, fp->uf_name);
20997 * ":delfunction {name}"
20999 void
21000 ex_delfunction(eap)
21001 exarg_T *eap;
21003 ufunc_T *fp = NULL;
21004 char_u *p;
21005 char_u *name;
21006 funcdict_T fudi;
21008 p = eap->arg;
21009 name = trans_function_name(&p, eap->skip, 0, &fudi);
21010 vim_free(fudi.fd_newkey);
21011 if (name == NULL)
21013 if (fudi.fd_dict != NULL && !eap->skip)
21014 EMSG(_(e_funcref));
21015 return;
21017 if (!ends_excmd(*skipwhite(p)))
21019 vim_free(name);
21020 EMSG(_(e_trailing));
21021 return;
21023 eap->nextcmd = check_nextcmd(p);
21024 if (eap->nextcmd != NULL)
21025 *p = NUL;
21027 if (!eap->skip)
21028 fp = find_func(name);
21029 vim_free(name);
21031 if (!eap->skip)
21033 if (fp == NULL)
21035 EMSG2(_(e_nofunc), eap->arg);
21036 return;
21038 if (fp->uf_calls > 0)
21040 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
21041 return;
21044 if (fudi.fd_dict != NULL)
21046 /* Delete the dict item that refers to the function, it will
21047 * invoke func_unref() and possibly delete the function. */
21048 dictitem_remove(fudi.fd_dict, fudi.fd_di);
21050 else
21051 func_free(fp);
21056 * Free a function and remove it from the list of functions.
21058 static void
21059 func_free(fp)
21060 ufunc_T *fp;
21062 hashitem_T *hi;
21064 /* clear this function */
21065 ga_clear_strings(&(fp->uf_args));
21066 ga_clear_strings(&(fp->uf_lines));
21067 #ifdef FEAT_PROFILE
21068 vim_free(fp->uf_tml_count);
21069 vim_free(fp->uf_tml_total);
21070 vim_free(fp->uf_tml_self);
21071 #endif
21073 /* remove the function from the function hashtable */
21074 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
21075 if (HASHITEM_EMPTY(hi))
21076 EMSG2(_(e_intern2), "func_free()");
21077 else
21078 hash_remove(&func_hashtab, hi);
21080 vim_free(fp);
21084 * Unreference a Function: decrement the reference count and free it when it
21085 * becomes zero. Only for numbered functions.
21087 static void
21088 func_unref(name)
21089 char_u *name;
21091 ufunc_T *fp;
21093 if (name != NULL && isdigit(*name))
21095 fp = find_func(name);
21096 if (fp == NULL)
21097 EMSG2(_(e_intern2), "func_unref()");
21098 else if (--fp->uf_refcount <= 0)
21100 /* Only delete it when it's not being used. Otherwise it's done
21101 * when "uf_calls" becomes zero. */
21102 if (fp->uf_calls == 0)
21103 func_free(fp);
21109 * Count a reference to a Function.
21111 static void
21112 func_ref(name)
21113 char_u *name;
21115 ufunc_T *fp;
21117 if (name != NULL && isdigit(*name))
21119 fp = find_func(name);
21120 if (fp == NULL)
21121 EMSG2(_(e_intern2), "func_ref()");
21122 else
21123 ++fp->uf_refcount;
21128 * Call a user function.
21130 static void
21131 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
21132 ufunc_T *fp; /* pointer to function */
21133 int argcount; /* nr of args */
21134 typval_T *argvars; /* arguments */
21135 typval_T *rettv; /* return value */
21136 linenr_T firstline; /* first line of range */
21137 linenr_T lastline; /* last line of range */
21138 dict_T *selfdict; /* Dictionary for "self" */
21140 char_u *save_sourcing_name;
21141 linenr_T save_sourcing_lnum;
21142 scid_T save_current_SID;
21143 funccall_T *fc;
21144 int save_did_emsg;
21145 static int depth = 0;
21146 dictitem_T *v;
21147 int fixvar_idx = 0; /* index in fixvar[] */
21148 int i;
21149 int ai;
21150 char_u numbuf[NUMBUFLEN];
21151 char_u *name;
21152 #ifdef FEAT_PROFILE
21153 proftime_T wait_start;
21154 proftime_T call_start;
21155 #endif
21157 /* If depth of calling is getting too high, don't execute the function */
21158 if (depth >= p_mfd)
21160 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
21161 rettv->v_type = VAR_NUMBER;
21162 rettv->vval.v_number = -1;
21163 return;
21165 ++depth;
21167 line_breakcheck(); /* check for CTRL-C hit */
21169 fc = (funccall_T *)alloc(sizeof(funccall_T));
21170 fc->caller = current_funccal;
21171 current_funccal = fc;
21172 fc->func = fp;
21173 fc->rettv = rettv;
21174 rettv->vval.v_number = 0;
21175 fc->linenr = 0;
21176 fc->returned = FALSE;
21177 fc->level = ex_nesting_level;
21178 /* Check if this function has a breakpoint. */
21179 fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
21180 fc->dbg_tick = debug_tick;
21183 * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables
21184 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
21185 * each argument variable and saves a lot of time.
21188 * Init l: variables.
21190 init_var_dict(&fc->l_vars, &fc->l_vars_var);
21191 if (selfdict != NULL)
21193 /* Set l:self to "selfdict". Use "name" to avoid a warning from
21194 * some compiler that checks the destination size. */
21195 v = &fc->fixvar[fixvar_idx++].var;
21196 name = v->di_key;
21197 STRCPY(name, "self");
21198 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
21199 hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
21200 v->di_tv.v_type = VAR_DICT;
21201 v->di_tv.v_lock = 0;
21202 v->di_tv.vval.v_dict = selfdict;
21203 ++selfdict->dv_refcount;
21207 * Init a: variables.
21208 * Set a:0 to "argcount".
21209 * Set a:000 to a list with room for the "..." arguments.
21211 init_var_dict(&fc->l_avars, &fc->l_avars_var);
21212 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0",
21213 (varnumber_T)(argcount - fp->uf_args.ga_len));
21214 /* Use "name" to avoid a warning from some compiler that checks the
21215 * destination size. */
21216 v = &fc->fixvar[fixvar_idx++].var;
21217 name = v->di_key;
21218 STRCPY(name, "000");
21219 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21220 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21221 v->di_tv.v_type = VAR_LIST;
21222 v->di_tv.v_lock = VAR_FIXED;
21223 v->di_tv.vval.v_list = &fc->l_varlist;
21224 vim_memset(&fc->l_varlist, 0, sizeof(list_T));
21225 fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT;
21226 fc->l_varlist.lv_lock = VAR_FIXED;
21229 * Set a:firstline to "firstline" and a:lastline to "lastline".
21230 * Set a:name to named arguments.
21231 * Set a:N to the "..." arguments.
21233 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline",
21234 (varnumber_T)firstline);
21235 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline",
21236 (varnumber_T)lastline);
21237 for (i = 0; i < argcount; ++i)
21239 ai = i - fp->uf_args.ga_len;
21240 if (ai < 0)
21241 /* named argument a:name */
21242 name = FUNCARG(fp, i);
21243 else
21245 /* "..." argument a:1, a:2, etc. */
21246 sprintf((char *)numbuf, "%d", ai + 1);
21247 name = numbuf;
21249 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
21251 v = &fc->fixvar[fixvar_idx++].var;
21252 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21254 else
21256 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
21257 + STRLEN(name)));
21258 if (v == NULL)
21259 break;
21260 v->di_flags = DI_FLAGS_RO;
21262 STRCPY(v->di_key, name);
21263 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21265 /* Note: the values are copied directly to avoid alloc/free.
21266 * "argvars" must have VAR_FIXED for v_lock. */
21267 v->di_tv = argvars[i];
21268 v->di_tv.v_lock = VAR_FIXED;
21270 if (ai >= 0 && ai < MAX_FUNC_ARGS)
21272 list_append(&fc->l_varlist, &fc->l_listitems[ai]);
21273 fc->l_listitems[ai].li_tv = argvars[i];
21274 fc->l_listitems[ai].li_tv.v_lock = VAR_FIXED;
21278 /* Don't redraw while executing the function. */
21279 ++RedrawingDisabled;
21280 save_sourcing_name = sourcing_name;
21281 save_sourcing_lnum = sourcing_lnum;
21282 sourcing_lnum = 1;
21283 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
21284 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
21285 if (sourcing_name != NULL)
21287 if (save_sourcing_name != NULL
21288 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
21289 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
21290 else
21291 STRCPY(sourcing_name, "function ");
21292 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
21294 if (p_verbose >= 12)
21296 ++no_wait_return;
21297 verbose_enter_scroll();
21299 smsg((char_u *)_("calling %s"), sourcing_name);
21300 if (p_verbose >= 14)
21302 char_u buf[MSG_BUF_LEN];
21303 char_u numbuf2[NUMBUFLEN];
21304 char_u *tofree;
21305 char_u *s;
21307 msg_puts((char_u *)"(");
21308 for (i = 0; i < argcount; ++i)
21310 if (i > 0)
21311 msg_puts((char_u *)", ");
21312 if (argvars[i].v_type == VAR_NUMBER)
21313 msg_outnum((long)argvars[i].vval.v_number);
21314 else
21316 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
21317 if (s != NULL)
21319 trunc_string(s, buf, MSG_BUF_CLEN);
21320 msg_puts(buf);
21321 vim_free(tofree);
21325 msg_puts((char_u *)")");
21327 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21329 verbose_leave_scroll();
21330 --no_wait_return;
21333 #ifdef FEAT_PROFILE
21334 if (do_profiling == PROF_YES)
21336 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
21337 func_do_profile(fp);
21338 if (fp->uf_profiling
21339 || (fc->caller != NULL && fc->caller->func->uf_profiling))
21341 ++fp->uf_tm_count;
21342 profile_start(&call_start);
21343 profile_zero(&fp->uf_tm_children);
21345 script_prof_save(&wait_start);
21347 #endif
21349 save_current_SID = current_SID;
21350 current_SID = fp->uf_script_ID;
21351 save_did_emsg = did_emsg;
21352 did_emsg = FALSE;
21354 /* call do_cmdline() to execute the lines */
21355 do_cmdline(NULL, get_func_line, (void *)fc,
21356 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
21358 --RedrawingDisabled;
21360 /* when the function was aborted because of an error, return -1 */
21361 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
21363 clear_tv(rettv);
21364 rettv->v_type = VAR_NUMBER;
21365 rettv->vval.v_number = -1;
21368 #ifdef FEAT_PROFILE
21369 if (do_profiling == PROF_YES && (fp->uf_profiling
21370 || (fc->caller != NULL && fc->caller->func->uf_profiling)))
21372 profile_end(&call_start);
21373 profile_sub_wait(&wait_start, &call_start);
21374 profile_add(&fp->uf_tm_total, &call_start);
21375 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
21376 if (fc->caller != NULL && fc->caller->func->uf_profiling)
21378 profile_add(&fc->caller->func->uf_tm_children, &call_start);
21379 profile_add(&fc->caller->func->uf_tml_children, &call_start);
21382 #endif
21384 /* when being verbose, mention the return value */
21385 if (p_verbose >= 12)
21387 ++no_wait_return;
21388 verbose_enter_scroll();
21390 if (aborting())
21391 smsg((char_u *)_("%s aborted"), sourcing_name);
21392 else if (fc->rettv->v_type == VAR_NUMBER)
21393 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
21394 (long)fc->rettv->vval.v_number);
21395 else
21397 char_u buf[MSG_BUF_LEN];
21398 char_u numbuf2[NUMBUFLEN];
21399 char_u *tofree;
21400 char_u *s;
21402 /* The value may be very long. Skip the middle part, so that we
21403 * have some idea how it starts and ends. smsg() would always
21404 * truncate it at the end. */
21405 s = tv2string(fc->rettv, &tofree, numbuf2, 0);
21406 if (s != NULL)
21408 trunc_string(s, buf, MSG_BUF_CLEN);
21409 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
21410 vim_free(tofree);
21413 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21415 verbose_leave_scroll();
21416 --no_wait_return;
21419 vim_free(sourcing_name);
21420 sourcing_name = save_sourcing_name;
21421 sourcing_lnum = save_sourcing_lnum;
21422 current_SID = save_current_SID;
21423 #ifdef FEAT_PROFILE
21424 if (do_profiling == PROF_YES)
21425 script_prof_restore(&wait_start);
21426 #endif
21428 if (p_verbose >= 12 && sourcing_name != NULL)
21430 ++no_wait_return;
21431 verbose_enter_scroll();
21433 smsg((char_u *)_("continuing in %s"), sourcing_name);
21434 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21436 verbose_leave_scroll();
21437 --no_wait_return;
21440 did_emsg |= save_did_emsg;
21441 current_funccal = fc->caller;
21442 --depth;
21444 /* If the a:000 list and the l: and a: dicts are not referenced we can
21445 * free the funccall_T and what's in it. */
21446 if (fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
21447 && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
21448 && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT)
21450 free_funccal(fc, FALSE);
21452 else
21454 hashitem_T *hi;
21455 listitem_T *li;
21456 int todo;
21458 /* "fc" is still in use. This can happen when returning "a:000" or
21459 * assigning "l:" to a global variable.
21460 * Link "fc" in the list for garbage collection later. */
21461 fc->caller = previous_funccal;
21462 previous_funccal = fc;
21464 /* Make a copy of the a: variables, since we didn't do that above. */
21465 todo = (int)fc->l_avars.dv_hashtab.ht_used;
21466 for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi)
21468 if (!HASHITEM_EMPTY(hi))
21470 --todo;
21471 v = HI2DI(hi);
21472 copy_tv(&v->di_tv, &v->di_tv);
21476 /* Make a copy of the a:000 items, since we didn't do that above. */
21477 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21478 copy_tv(&li->li_tv, &li->li_tv);
21483 * Return TRUE if items in "fc" do not have "copyID". That means they are not
21484 * referenced from anywhere that is in use.
21486 static int
21487 can_free_funccal(fc, copyID)
21488 funccall_T *fc;
21489 int copyID;
21491 return (fc->l_varlist.lv_copyID != copyID
21492 && fc->l_vars.dv_copyID != copyID
21493 && fc->l_avars.dv_copyID != copyID);
21497 * Free "fc" and what it contains.
21499 static void
21500 free_funccal(fc, free_val)
21501 funccall_T *fc;
21502 int free_val; /* a: vars were allocated */
21504 listitem_T *li;
21506 /* The a: variables typevals may not have been allocated, only free the
21507 * allocated variables. */
21508 vars_clear_ext(&fc->l_avars.dv_hashtab, free_val);
21510 /* free all l: variables */
21511 vars_clear(&fc->l_vars.dv_hashtab);
21513 /* Free the a:000 variables if they were allocated. */
21514 if (free_val)
21515 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21516 clear_tv(&li->li_tv);
21518 vim_free(fc);
21522 * Add a number variable "name" to dict "dp" with value "nr".
21524 static void
21525 add_nr_var(dp, v, name, nr)
21526 dict_T *dp;
21527 dictitem_T *v;
21528 char *name;
21529 varnumber_T nr;
21531 STRCPY(v->di_key, name);
21532 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21533 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
21534 v->di_tv.v_type = VAR_NUMBER;
21535 v->di_tv.v_lock = VAR_FIXED;
21536 v->di_tv.vval.v_number = nr;
21540 * ":return [expr]"
21542 void
21543 ex_return(eap)
21544 exarg_T *eap;
21546 char_u *arg = eap->arg;
21547 typval_T rettv;
21548 int returning = FALSE;
21550 if (current_funccal == NULL)
21552 EMSG(_("E133: :return not inside a function"));
21553 return;
21556 if (eap->skip)
21557 ++emsg_skip;
21559 eap->nextcmd = NULL;
21560 if ((*arg != NUL && *arg != '|' && *arg != '\n')
21561 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
21563 if (!eap->skip)
21564 returning = do_return(eap, FALSE, TRUE, &rettv);
21565 else
21566 clear_tv(&rettv);
21568 /* It's safer to return also on error. */
21569 else if (!eap->skip)
21572 * Return unless the expression evaluation has been cancelled due to an
21573 * aborting error, an interrupt, or an exception.
21575 if (!aborting())
21576 returning = do_return(eap, FALSE, TRUE, NULL);
21579 /* When skipping or the return gets pending, advance to the next command
21580 * in this line (!returning). Otherwise, ignore the rest of the line.
21581 * Following lines will be ignored by get_func_line(). */
21582 if (returning)
21583 eap->nextcmd = NULL;
21584 else if (eap->nextcmd == NULL) /* no argument */
21585 eap->nextcmd = check_nextcmd(arg);
21587 if (eap->skip)
21588 --emsg_skip;
21592 * Return from a function. Possibly makes the return pending. Also called
21593 * for a pending return at the ":endtry" or after returning from an extra
21594 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
21595 * when called due to a ":return" command. "rettv" may point to a typval_T
21596 * with the return rettv. Returns TRUE when the return can be carried out,
21597 * FALSE when the return gets pending.
21600 do_return(eap, reanimate, is_cmd, rettv)
21601 exarg_T *eap;
21602 int reanimate;
21603 int is_cmd;
21604 void *rettv;
21606 int idx;
21607 struct condstack *cstack = eap->cstack;
21609 if (reanimate)
21610 /* Undo the return. */
21611 current_funccal->returned = FALSE;
21614 * Cleanup (and inactivate) conditionals, but stop when a try conditional
21615 * not in its finally clause (which then is to be executed next) is found.
21616 * In this case, make the ":return" pending for execution at the ":endtry".
21617 * Otherwise, return normally.
21619 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
21620 if (idx >= 0)
21622 cstack->cs_pending[idx] = CSTP_RETURN;
21624 if (!is_cmd && !reanimate)
21625 /* A pending return again gets pending. "rettv" points to an
21626 * allocated variable with the rettv of the original ":return"'s
21627 * argument if present or is NULL else. */
21628 cstack->cs_rettv[idx] = rettv;
21629 else
21631 /* When undoing a return in order to make it pending, get the stored
21632 * return rettv. */
21633 if (reanimate)
21634 rettv = current_funccal->rettv;
21636 if (rettv != NULL)
21638 /* Store the value of the pending return. */
21639 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
21640 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
21641 else
21642 EMSG(_(e_outofmem));
21644 else
21645 cstack->cs_rettv[idx] = NULL;
21647 if (reanimate)
21649 /* The pending return value could be overwritten by a ":return"
21650 * without argument in a finally clause; reset the default
21651 * return value. */
21652 current_funccal->rettv->v_type = VAR_NUMBER;
21653 current_funccal->rettv->vval.v_number = 0;
21656 report_make_pending(CSTP_RETURN, rettv);
21658 else
21660 current_funccal->returned = TRUE;
21662 /* If the return is carried out now, store the return value. For
21663 * a return immediately after reanimation, the value is already
21664 * there. */
21665 if (!reanimate && rettv != NULL)
21667 clear_tv(current_funccal->rettv);
21668 *current_funccal->rettv = *(typval_T *)rettv;
21669 if (!is_cmd)
21670 vim_free(rettv);
21674 return idx < 0;
21678 * Free the variable with a pending return value.
21680 void
21681 discard_pending_return(rettv)
21682 void *rettv;
21684 free_tv((typval_T *)rettv);
21688 * Generate a return command for producing the value of "rettv". The result
21689 * is an allocated string. Used by report_pending() for verbose messages.
21691 char_u *
21692 get_return_cmd(rettv)
21693 void *rettv;
21695 char_u *s = NULL;
21696 char_u *tofree = NULL;
21697 char_u numbuf[NUMBUFLEN];
21699 if (rettv != NULL)
21700 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
21701 if (s == NULL)
21702 s = (char_u *)"";
21704 STRCPY(IObuff, ":return ");
21705 STRNCPY(IObuff + 8, s, IOSIZE - 8);
21706 if (STRLEN(s) + 8 >= IOSIZE)
21707 STRCPY(IObuff + IOSIZE - 4, "...");
21708 vim_free(tofree);
21709 return vim_strsave(IObuff);
21713 * Get next function line.
21714 * Called by do_cmdline() to get the next line.
21715 * Returns allocated string, or NULL for end of function.
21717 char_u *
21718 get_func_line(c, cookie, indent)
21719 int c UNUSED;
21720 void *cookie;
21721 int indent UNUSED;
21723 funccall_T *fcp = (funccall_T *)cookie;
21724 ufunc_T *fp = fcp->func;
21725 char_u *retval;
21726 garray_T *gap; /* growarray with function lines */
21728 /* If breakpoints have been added/deleted need to check for it. */
21729 if (fcp->dbg_tick != debug_tick)
21731 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21732 sourcing_lnum);
21733 fcp->dbg_tick = debug_tick;
21735 #ifdef FEAT_PROFILE
21736 if (do_profiling == PROF_YES)
21737 func_line_end(cookie);
21738 #endif
21740 gap = &fp->uf_lines;
21741 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21742 || fcp->returned)
21743 retval = NULL;
21744 else
21746 /* Skip NULL lines (continuation lines). */
21747 while (fcp->linenr < gap->ga_len
21748 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
21749 ++fcp->linenr;
21750 if (fcp->linenr >= gap->ga_len)
21751 retval = NULL;
21752 else
21754 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
21755 sourcing_lnum = fcp->linenr;
21756 #ifdef FEAT_PROFILE
21757 if (do_profiling == PROF_YES)
21758 func_line_start(cookie);
21759 #endif
21763 /* Did we encounter a breakpoint? */
21764 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
21766 dbg_breakpoint(fp->uf_name, sourcing_lnum);
21767 /* Find next breakpoint. */
21768 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21769 sourcing_lnum);
21770 fcp->dbg_tick = debug_tick;
21773 return retval;
21776 #if defined(FEAT_PROFILE) || defined(PROTO)
21778 * Called when starting to read a function line.
21779 * "sourcing_lnum" must be correct!
21780 * When skipping lines it may not actually be executed, but we won't find out
21781 * until later and we need to store the time now.
21783 void
21784 func_line_start(cookie)
21785 void *cookie;
21787 funccall_T *fcp = (funccall_T *)cookie;
21788 ufunc_T *fp = fcp->func;
21790 if (fp->uf_profiling && sourcing_lnum >= 1
21791 && sourcing_lnum <= fp->uf_lines.ga_len)
21793 fp->uf_tml_idx = sourcing_lnum - 1;
21794 /* Skip continuation lines. */
21795 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
21796 --fp->uf_tml_idx;
21797 fp->uf_tml_execed = FALSE;
21798 profile_start(&fp->uf_tml_start);
21799 profile_zero(&fp->uf_tml_children);
21800 profile_get_wait(&fp->uf_tml_wait);
21805 * Called when actually executing a function line.
21807 void
21808 func_line_exec(cookie)
21809 void *cookie;
21811 funccall_T *fcp = (funccall_T *)cookie;
21812 ufunc_T *fp = fcp->func;
21814 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21815 fp->uf_tml_execed = TRUE;
21819 * Called when done with a function line.
21821 void
21822 func_line_end(cookie)
21823 void *cookie;
21825 funccall_T *fcp = (funccall_T *)cookie;
21826 ufunc_T *fp = fcp->func;
21828 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21830 if (fp->uf_tml_execed)
21832 ++fp->uf_tml_count[fp->uf_tml_idx];
21833 profile_end(&fp->uf_tml_start);
21834 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
21835 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
21836 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
21837 &fp->uf_tml_children);
21839 fp->uf_tml_idx = -1;
21842 #endif
21845 * Return TRUE if the currently active function should be ended, because a
21846 * return was encountered or an error occurred. Used inside a ":while".
21849 func_has_ended(cookie)
21850 void *cookie;
21852 funccall_T *fcp = (funccall_T *)cookie;
21854 /* Ignore the "abort" flag if the abortion behavior has been changed due to
21855 * an error inside a try conditional. */
21856 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21857 || fcp->returned);
21861 * return TRUE if cookie indicates a function which "abort"s on errors.
21864 func_has_abort(cookie)
21865 void *cookie;
21867 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
21870 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
21871 typedef enum
21873 VAR_FLAVOUR_DEFAULT, /* doesn't start with uppercase */
21874 VAR_FLAVOUR_SESSION, /* starts with uppercase, some lower */
21875 VAR_FLAVOUR_VIMINFO /* all uppercase */
21876 } var_flavour_T;
21878 static var_flavour_T var_flavour __ARGS((char_u *varname));
21880 static var_flavour_T
21881 var_flavour(varname)
21882 char_u *varname;
21884 char_u *p = varname;
21886 if (ASCII_ISUPPER(*p))
21888 while (*(++p))
21889 if (ASCII_ISLOWER(*p))
21890 return VAR_FLAVOUR_SESSION;
21891 return VAR_FLAVOUR_VIMINFO;
21893 else
21894 return VAR_FLAVOUR_DEFAULT;
21896 #endif
21898 #if defined(FEAT_VIMINFO) || defined(PROTO)
21900 * Restore global vars that start with a capital from the viminfo file
21903 read_viminfo_varlist(virp, writing)
21904 vir_T *virp;
21905 int writing;
21907 char_u *tab;
21908 int type = VAR_NUMBER;
21909 typval_T tv;
21911 if (!writing && (find_viminfo_parameter('!') != NULL))
21913 tab = vim_strchr(virp->vir_line + 1, '\t');
21914 if (tab != NULL)
21916 *tab++ = '\0'; /* isolate the variable name */
21917 if (*tab == 'S') /* string var */
21918 type = VAR_STRING;
21919 #ifdef FEAT_FLOAT
21920 else if (*tab == 'F')
21921 type = VAR_FLOAT;
21922 #endif
21924 tab = vim_strchr(tab, '\t');
21925 if (tab != NULL)
21927 tv.v_type = type;
21928 if (type == VAR_STRING)
21929 tv.vval.v_string = viminfo_readstring(virp,
21930 (int)(tab - virp->vir_line + 1), TRUE);
21931 #ifdef FEAT_FLOAT
21932 else if (type == VAR_FLOAT)
21933 (void)string2float(tab + 1, &tv.vval.v_float);
21934 #endif
21935 else
21936 tv.vval.v_number = atol((char *)tab + 1);
21937 set_var(virp->vir_line + 1, &tv, FALSE);
21938 if (type == VAR_STRING)
21939 vim_free(tv.vval.v_string);
21944 return viminfo_readline(virp);
21948 * Write global vars that start with a capital to the viminfo file
21950 void
21951 write_viminfo_varlist(fp)
21952 FILE *fp;
21954 hashitem_T *hi;
21955 dictitem_T *this_var;
21956 int todo;
21957 char *s;
21958 char_u *p;
21959 char_u *tofree;
21960 char_u numbuf[NUMBUFLEN];
21962 if (find_viminfo_parameter('!') == NULL)
21963 return;
21965 fprintf(fp, _("\n# global variables:\n"));
21967 todo = (int)globvarht.ht_used;
21968 for (hi = globvarht.ht_array; todo > 0; ++hi)
21970 if (!HASHITEM_EMPTY(hi))
21972 --todo;
21973 this_var = HI2DI(hi);
21974 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
21976 switch (this_var->di_tv.v_type)
21978 case VAR_STRING: s = "STR"; break;
21979 case VAR_NUMBER: s = "NUM"; break;
21980 #ifdef FEAT_FLOAT
21981 case VAR_FLOAT: s = "FLO"; break;
21982 #endif
21983 default: continue;
21985 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
21986 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
21987 if (p != NULL)
21988 viminfo_writestring(fp, p);
21989 vim_free(tofree);
21994 #endif
21996 #if defined(FEAT_SESSION) || defined(PROTO)
21998 store_session_globals(fd)
21999 FILE *fd;
22001 hashitem_T *hi;
22002 dictitem_T *this_var;
22003 int todo;
22004 char_u *p, *t;
22006 todo = (int)globvarht.ht_used;
22007 for (hi = globvarht.ht_array; todo > 0; ++hi)
22009 if (!HASHITEM_EMPTY(hi))
22011 --todo;
22012 this_var = HI2DI(hi);
22013 if ((this_var->di_tv.v_type == VAR_NUMBER
22014 || this_var->di_tv.v_type == VAR_STRING)
22015 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22017 /* Escape special characters with a backslash. Turn a LF and
22018 * CR into \n and \r. */
22019 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
22020 (char_u *)"\\\"\n\r");
22021 if (p == NULL) /* out of memory */
22022 break;
22023 for (t = p; *t != NUL; ++t)
22024 if (*t == '\n')
22025 *t = 'n';
22026 else if (*t == '\r')
22027 *t = 'r';
22028 if ((fprintf(fd, "let %s = %c%s%c",
22029 this_var->di_key,
22030 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22031 : ' ',
22033 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22034 : ' ') < 0)
22035 || put_eol(fd) == FAIL)
22037 vim_free(p);
22038 return FAIL;
22040 vim_free(p);
22042 #ifdef FEAT_FLOAT
22043 else if (this_var->di_tv.v_type == VAR_FLOAT
22044 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22046 float_T f = this_var->di_tv.vval.v_float;
22047 int sign = ' ';
22049 if (f < 0)
22051 f = -f;
22052 sign = '-';
22054 if ((fprintf(fd, "let %s = %c&%f",
22055 this_var->di_key, sign, f) < 0)
22056 || put_eol(fd) == FAIL)
22057 return FAIL;
22059 #endif
22062 return OK;
22064 #endif
22067 * Display script name where an item was last set.
22068 * Should only be invoked when 'verbose' is non-zero.
22070 void
22071 last_set_msg(scriptID)
22072 scid_T scriptID;
22074 char_u *p;
22076 if (scriptID != 0)
22078 p = home_replace_save(NULL, get_scriptname(scriptID));
22079 if (p != NULL)
22081 verbose_enter();
22082 MSG_PUTS(_("\n\tLast set from "));
22083 MSG_PUTS(p);
22084 vim_free(p);
22085 verbose_leave();
22091 * List v:oldfiles in a nice way.
22093 void
22094 ex_oldfiles(eap)
22095 exarg_T *eap UNUSED;
22097 list_T *l = vimvars[VV_OLDFILES].vv_list;
22098 listitem_T *li;
22099 int nr = 0;
22101 if (l == NULL)
22102 msg((char_u *)_("No old files"));
22103 else
22105 msg_start();
22106 msg_scroll = TRUE;
22107 for (li = l->lv_first; li != NULL && !got_int; li = li->li_next)
22109 msg_outnum((long)++nr);
22110 MSG_PUTS(": ");
22111 msg_outtrans(get_tv_string(&li->li_tv));
22112 msg_putchar('\n');
22113 out_flush(); /* output one line at a time */
22114 ui_breakcheck();
22116 /* Assume "got_int" was set to truncate the listing. */
22117 got_int = FALSE;
22119 #ifdef FEAT_BROWSE_CMD
22120 if (cmdmod.browse)
22122 quit_more = FALSE;
22123 nr = prompt_for_number(FALSE);
22124 msg_starthere();
22125 if (nr > 0)
22127 char_u *p = list_find_str(get_vim_var_list(VV_OLDFILES),
22128 (long)nr);
22130 if (p != NULL)
22132 p = expand_env_save(p);
22133 eap->arg = p;
22134 eap->cmdidx = CMD_edit;
22135 cmdmod.browse = FALSE;
22136 do_exedit(eap, NULL);
22137 vim_free(p);
22141 #endif
22145 #endif /* FEAT_EVAL */
22148 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
22150 #ifdef WIN3264
22152 * Functions for ":8" filename modifier: get 8.3 version of a filename.
22154 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22155 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
22156 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22159 * Get the short path (8.3) for the filename in "fnamep".
22160 * Only works for a valid file name.
22161 * When the path gets longer "fnamep" is changed and the allocated buffer
22162 * is put in "bufp".
22163 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
22164 * Returns OK on success, FAIL on failure.
22166 static int
22167 get_short_pathname(fnamep, bufp, fnamelen)
22168 char_u **fnamep;
22169 char_u **bufp;
22170 int *fnamelen;
22172 int l, len;
22173 char_u *newbuf;
22175 len = *fnamelen;
22176 l = GetShortPathName(*fnamep, *fnamep, len);
22177 if (l > len - 1)
22179 /* If that doesn't work (not enough space), then save the string
22180 * and try again with a new buffer big enough. */
22181 newbuf = vim_strnsave(*fnamep, l);
22182 if (newbuf == NULL)
22183 return FAIL;
22185 vim_free(*bufp);
22186 *fnamep = *bufp = newbuf;
22188 /* Really should always succeed, as the buffer is big enough. */
22189 l = GetShortPathName(*fnamep, *fnamep, l+1);
22192 *fnamelen = l;
22193 return OK;
22197 * Get the short path (8.3) for the filename in "fname". The converted
22198 * path is returned in "bufp".
22200 * Some of the directories specified in "fname" may not exist. This function
22201 * will shorten the existing directories at the beginning of the path and then
22202 * append the remaining non-existing path.
22204 * fname - Pointer to the filename to shorten. On return, contains the
22205 * pointer to the shortened pathname
22206 * bufp - Pointer to an allocated buffer for the filename.
22207 * fnamelen - Length of the filename pointed to by fname
22209 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
22211 static int
22212 shortpath_for_invalid_fname(fname, bufp, fnamelen)
22213 char_u **fname;
22214 char_u **bufp;
22215 int *fnamelen;
22217 char_u *short_fname, *save_fname, *pbuf_unused;
22218 char_u *endp, *save_endp;
22219 char_u ch;
22220 int old_len, len;
22221 int new_len, sfx_len;
22222 int retval = OK;
22224 /* Make a copy */
22225 old_len = *fnamelen;
22226 save_fname = vim_strnsave(*fname, old_len);
22227 pbuf_unused = NULL;
22228 short_fname = NULL;
22230 endp = save_fname + old_len - 1; /* Find the end of the copy */
22231 save_endp = endp;
22234 * Try shortening the supplied path till it succeeds by removing one
22235 * directory at a time from the tail of the path.
22237 len = 0;
22238 for (;;)
22240 /* go back one path-separator */
22241 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
22242 --endp;
22243 if (endp <= save_fname)
22244 break; /* processed the complete path */
22247 * Replace the path separator with a NUL and try to shorten the
22248 * resulting path.
22250 ch = *endp;
22251 *endp = 0;
22252 short_fname = save_fname;
22253 len = (int)STRLEN(short_fname) + 1;
22254 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
22256 retval = FAIL;
22257 goto theend;
22259 *endp = ch; /* preserve the string */
22261 if (len > 0)
22262 break; /* successfully shortened the path */
22264 /* failed to shorten the path. Skip the path separator */
22265 --endp;
22268 if (len > 0)
22271 * Succeeded in shortening the path. Now concatenate the shortened
22272 * path with the remaining path at the tail.
22275 /* Compute the length of the new path. */
22276 sfx_len = (int)(save_endp - endp) + 1;
22277 new_len = len + sfx_len;
22279 *fnamelen = new_len;
22280 vim_free(*bufp);
22281 if (new_len > old_len)
22283 /* There is not enough space in the currently allocated string,
22284 * copy it to a buffer big enough. */
22285 *fname = *bufp = vim_strnsave(short_fname, new_len);
22286 if (*fname == NULL)
22288 retval = FAIL;
22289 goto theend;
22292 else
22294 /* Transfer short_fname to the main buffer (it's big enough),
22295 * unless get_short_pathname() did its work in-place. */
22296 *fname = *bufp = save_fname;
22297 if (short_fname != save_fname)
22298 vim_strncpy(save_fname, short_fname, len);
22299 save_fname = NULL;
22302 /* concat the not-shortened part of the path */
22303 vim_strncpy(*fname + len, endp, sfx_len);
22304 (*fname)[new_len] = NUL;
22307 theend:
22308 vim_free(pbuf_unused);
22309 vim_free(save_fname);
22311 return retval;
22315 * Get a pathname for a partial path.
22316 * Returns OK for success, FAIL for failure.
22318 static int
22319 shortpath_for_partial(fnamep, bufp, fnamelen)
22320 char_u **fnamep;
22321 char_u **bufp;
22322 int *fnamelen;
22324 int sepcount, len, tflen;
22325 char_u *p;
22326 char_u *pbuf, *tfname;
22327 int hasTilde;
22329 /* Count up the path separators from the RHS.. so we know which part
22330 * of the path to return. */
22331 sepcount = 0;
22332 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
22333 if (vim_ispathsep(*p))
22334 ++sepcount;
22336 /* Need full path first (use expand_env() to remove a "~/") */
22337 hasTilde = (**fnamep == '~');
22338 if (hasTilde)
22339 pbuf = tfname = expand_env_save(*fnamep);
22340 else
22341 pbuf = tfname = FullName_save(*fnamep, FALSE);
22343 len = tflen = (int)STRLEN(tfname);
22345 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
22346 return FAIL;
22348 if (len == 0)
22350 /* Don't have a valid filename, so shorten the rest of the
22351 * path if we can. This CAN give us invalid 8.3 filenames, but
22352 * there's not a lot of point in guessing what it might be.
22354 len = tflen;
22355 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
22356 return FAIL;
22359 /* Count the paths backward to find the beginning of the desired string. */
22360 for (p = tfname + len - 1; p >= tfname; --p)
22362 #ifdef FEAT_MBYTE
22363 if (has_mbyte)
22364 p -= mb_head_off(tfname, p);
22365 #endif
22366 if (vim_ispathsep(*p))
22368 if (sepcount == 0 || (hasTilde && sepcount == 1))
22369 break;
22370 else
22371 sepcount --;
22374 if (hasTilde)
22376 --p;
22377 if (p >= tfname)
22378 *p = '~';
22379 else
22380 return FAIL;
22382 else
22383 ++p;
22385 /* Copy in the string - p indexes into tfname - allocated at pbuf */
22386 vim_free(*bufp);
22387 *fnamelen = (int)STRLEN(p);
22388 *bufp = pbuf;
22389 *fnamep = p;
22391 return OK;
22393 #endif /* WIN3264 */
22396 * Adjust a filename, according to a string of modifiers.
22397 * *fnamep must be NUL terminated when called. When returning, the length is
22398 * determined by *fnamelen.
22399 * Returns VALID_ flags or -1 for failure.
22400 * When there is an error, *fnamep is set to NULL.
22403 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
22404 char_u *src; /* string with modifiers */
22405 int *usedlen; /* characters after src that are used */
22406 char_u **fnamep; /* file name so far */
22407 char_u **bufp; /* buffer for allocated file name or NULL */
22408 int *fnamelen; /* length of fnamep */
22410 int valid = 0;
22411 char_u *tail;
22412 char_u *s, *p, *pbuf;
22413 char_u dirname[MAXPATHL];
22414 int c;
22415 int has_fullname = 0;
22416 #ifdef WIN3264
22417 int has_shortname = 0;
22418 #endif
22420 repeat:
22421 /* ":p" - full path/file_name */
22422 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
22424 has_fullname = 1;
22426 valid |= VALID_PATH;
22427 *usedlen += 2;
22429 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
22430 if ((*fnamep)[0] == '~'
22431 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
22432 && ((*fnamep)[1] == '/'
22433 # ifdef BACKSLASH_IN_FILENAME
22434 || (*fnamep)[1] == '\\'
22435 # endif
22436 || (*fnamep)[1] == NUL)
22438 #endif
22441 *fnamep = expand_env_save(*fnamep);
22442 vim_free(*bufp); /* free any allocated file name */
22443 *bufp = *fnamep;
22444 if (*fnamep == NULL)
22445 return -1;
22448 /* When "/." or "/.." is used: force expansion to get rid of it. */
22449 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
22451 if (vim_ispathsep(*p)
22452 && p[1] == '.'
22453 && (p[2] == NUL
22454 || vim_ispathsep(p[2])
22455 || (p[2] == '.'
22456 && (p[3] == NUL || vim_ispathsep(p[3])))))
22457 break;
22460 /* FullName_save() is slow, don't use it when not needed. */
22461 if (*p != NUL || !vim_isAbsName(*fnamep))
22463 *fnamep = FullName_save(*fnamep, *p != NUL);
22464 vim_free(*bufp); /* free any allocated file name */
22465 *bufp = *fnamep;
22466 if (*fnamep == NULL)
22467 return -1;
22470 /* Append a path separator to a directory. */
22471 if (mch_isdir(*fnamep))
22473 /* Make room for one or two extra characters. */
22474 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
22475 vim_free(*bufp); /* free any allocated file name */
22476 *bufp = *fnamep;
22477 if (*fnamep == NULL)
22478 return -1;
22479 add_pathsep(*fnamep);
22483 /* ":." - path relative to the current directory */
22484 /* ":~" - path relative to the home directory */
22485 /* ":8" - shortname path - postponed till after */
22486 while (src[*usedlen] == ':'
22487 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
22489 *usedlen += 2;
22490 if (c == '8')
22492 #ifdef WIN3264
22493 has_shortname = 1; /* Postpone this. */
22494 #endif
22495 continue;
22497 pbuf = NULL;
22498 /* Need full path first (use expand_env() to remove a "~/") */
22499 if (!has_fullname)
22501 if (c == '.' && **fnamep == '~')
22502 p = pbuf = expand_env_save(*fnamep);
22503 else
22504 p = pbuf = FullName_save(*fnamep, FALSE);
22506 else
22507 p = *fnamep;
22509 has_fullname = 0;
22511 if (p != NULL)
22513 if (c == '.')
22515 mch_dirname(dirname, MAXPATHL);
22516 s = shorten_fname(p, dirname);
22517 if (s != NULL)
22519 *fnamep = s;
22520 if (pbuf != NULL)
22522 vim_free(*bufp); /* free any allocated file name */
22523 *bufp = pbuf;
22524 pbuf = NULL;
22528 else
22530 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
22531 /* Only replace it when it starts with '~' */
22532 if (*dirname == '~')
22534 s = vim_strsave(dirname);
22535 if (s != NULL)
22537 *fnamep = s;
22538 vim_free(*bufp);
22539 *bufp = s;
22543 vim_free(pbuf);
22547 tail = gettail(*fnamep);
22548 *fnamelen = (int)STRLEN(*fnamep);
22550 /* ":h" - head, remove "/file_name", can be repeated */
22551 /* Don't remove the first "/" or "c:\" */
22552 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
22554 valid |= VALID_HEAD;
22555 *usedlen += 2;
22556 s = get_past_head(*fnamep);
22557 while (tail > s && after_pathsep(s, tail))
22558 mb_ptr_back(*fnamep, tail);
22559 *fnamelen = (int)(tail - *fnamep);
22560 #ifdef VMS
22561 if (*fnamelen > 0)
22562 *fnamelen += 1; /* the path separator is part of the path */
22563 #endif
22564 if (*fnamelen == 0)
22566 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
22567 p = vim_strsave((char_u *)".");
22568 if (p == NULL)
22569 return -1;
22570 vim_free(*bufp);
22571 *bufp = *fnamep = tail = p;
22572 *fnamelen = 1;
22574 else
22576 while (tail > s && !after_pathsep(s, tail))
22577 mb_ptr_back(*fnamep, tail);
22581 /* ":8" - shortname */
22582 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
22584 *usedlen += 2;
22585 #ifdef WIN3264
22586 has_shortname = 1;
22587 #endif
22590 #ifdef WIN3264
22591 /* Check shortname after we have done 'heads' and before we do 'tails'
22593 if (has_shortname)
22595 pbuf = NULL;
22596 /* Copy the string if it is shortened by :h */
22597 if (*fnamelen < (int)STRLEN(*fnamep))
22599 p = vim_strnsave(*fnamep, *fnamelen);
22600 if (p == 0)
22601 return -1;
22602 vim_free(*bufp);
22603 *bufp = *fnamep = p;
22606 /* Split into two implementations - makes it easier. First is where
22607 * there isn't a full name already, second is where there is.
22609 if (!has_fullname && !vim_isAbsName(*fnamep))
22611 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
22612 return -1;
22614 else
22616 int l;
22618 /* Simple case, already have the full-name
22619 * Nearly always shorter, so try first time. */
22620 l = *fnamelen;
22621 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
22622 return -1;
22624 if (l == 0)
22626 /* Couldn't find the filename.. search the paths.
22628 l = *fnamelen;
22629 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
22630 return -1;
22632 *fnamelen = l;
22635 #endif /* WIN3264 */
22637 /* ":t" - tail, just the basename */
22638 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
22640 *usedlen += 2;
22641 *fnamelen -= (int)(tail - *fnamep);
22642 *fnamep = tail;
22645 /* ":e" - extension, can be repeated */
22646 /* ":r" - root, without extension, can be repeated */
22647 while (src[*usedlen] == ':'
22648 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
22650 /* find a '.' in the tail:
22651 * - for second :e: before the current fname
22652 * - otherwise: The last '.'
22654 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
22655 s = *fnamep - 2;
22656 else
22657 s = *fnamep + *fnamelen - 1;
22658 for ( ; s > tail; --s)
22659 if (s[0] == '.')
22660 break;
22661 if (src[*usedlen + 1] == 'e') /* :e */
22663 if (s > tail)
22665 *fnamelen += (int)(*fnamep - (s + 1));
22666 *fnamep = s + 1;
22667 #ifdef VMS
22668 /* cut version from the extension */
22669 s = *fnamep + *fnamelen - 1;
22670 for ( ; s > *fnamep; --s)
22671 if (s[0] == ';')
22672 break;
22673 if (s > *fnamep)
22674 *fnamelen = s - *fnamep;
22675 #endif
22677 else if (*fnamep <= tail)
22678 *fnamelen = 0;
22680 else /* :r */
22682 if (s > tail) /* remove one extension */
22683 *fnamelen = (int)(s - *fnamep);
22685 *usedlen += 2;
22688 /* ":s?pat?foo?" - substitute */
22689 /* ":gs?pat?foo?" - global substitute */
22690 if (src[*usedlen] == ':'
22691 && (src[*usedlen + 1] == 's'
22692 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
22694 char_u *str;
22695 char_u *pat;
22696 char_u *sub;
22697 int sep;
22698 char_u *flags;
22699 int didit = FALSE;
22701 flags = (char_u *)"";
22702 s = src + *usedlen + 2;
22703 if (src[*usedlen + 1] == 'g')
22705 flags = (char_u *)"g";
22706 ++s;
22709 sep = *s++;
22710 if (sep)
22712 /* find end of pattern */
22713 p = vim_strchr(s, sep);
22714 if (p != NULL)
22716 pat = vim_strnsave(s, (int)(p - s));
22717 if (pat != NULL)
22719 s = p + 1;
22720 /* find end of substitution */
22721 p = vim_strchr(s, sep);
22722 if (p != NULL)
22724 sub = vim_strnsave(s, (int)(p - s));
22725 str = vim_strnsave(*fnamep, *fnamelen);
22726 if (sub != NULL && str != NULL)
22728 *usedlen = (int)(p + 1 - src);
22729 s = do_string_sub(str, pat, sub, flags);
22730 if (s != NULL)
22732 *fnamep = s;
22733 *fnamelen = (int)STRLEN(s);
22734 vim_free(*bufp);
22735 *bufp = s;
22736 didit = TRUE;
22739 vim_free(sub);
22740 vim_free(str);
22742 vim_free(pat);
22745 /* after using ":s", repeat all the modifiers */
22746 if (didit)
22747 goto repeat;
22751 return valid;
22755 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
22756 * "flags" can be "g" to do a global substitute.
22757 * Returns an allocated string, NULL for error.
22759 char_u *
22760 do_string_sub(str, pat, sub, flags)
22761 char_u *str;
22762 char_u *pat;
22763 char_u *sub;
22764 char_u *flags;
22766 int sublen;
22767 regmatch_T regmatch;
22768 int i;
22769 int do_all;
22770 char_u *tail;
22771 garray_T ga;
22772 char_u *ret;
22773 char_u *save_cpo;
22775 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
22776 save_cpo = p_cpo;
22777 p_cpo = empty_option;
22779 ga_init2(&ga, 1, 200);
22781 do_all = (flags[0] == 'g');
22783 regmatch.rm_ic = p_ic;
22784 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
22785 if (regmatch.regprog != NULL)
22787 tail = str;
22788 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
22791 * Get some space for a temporary buffer to do the substitution
22792 * into. It will contain:
22793 * - The text up to where the match is.
22794 * - The substituted text.
22795 * - The text after the match.
22797 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
22798 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
22799 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
22801 ga_clear(&ga);
22802 break;
22805 /* copy the text up to where the match is */
22806 i = (int)(regmatch.startp[0] - tail);
22807 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
22808 /* add the substituted text */
22809 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
22810 + ga.ga_len + i, TRUE, TRUE, FALSE);
22811 ga.ga_len += i + sublen - 1;
22812 /* avoid getting stuck on a match with an empty string */
22813 if (tail == regmatch.endp[0])
22815 if (*tail == NUL)
22816 break;
22817 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
22818 ++ga.ga_len;
22820 else
22822 tail = regmatch.endp[0];
22823 if (*tail == NUL)
22824 break;
22826 if (!do_all)
22827 break;
22830 if (ga.ga_data != NULL)
22831 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
22833 vim_free(regmatch.regprog);
22836 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
22837 ga_clear(&ga);
22838 if (p_cpo == empty_option)
22839 p_cpo = save_cpo;
22840 else
22841 /* Darn, evaluating {sub} expression changed the value. */
22842 free_string_option(save_cpo);
22844 return ret;
22847 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */