[7.2.443] Using taglist() on a tag file with duplicate fields generates an
[vim_extended.git] / src / eval.c
blob32e3d2038cacf8ae8201f65acfe45eca6b05ef97
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 char_u *dict2string __ARGS((typval_T *tv, int copyID));
455 static int get_dict_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
456 static char_u *echo_string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
457 static char_u *tv2string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
458 static char_u *string_quote __ARGS((char_u *str, int function));
459 #ifdef FEAT_FLOAT
460 static int string2float __ARGS((char_u *text, float_T *value));
461 #endif
462 static int get_env_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
463 static int find_internal_func __ARGS((char_u *name));
464 static char_u *deref_func_name __ARGS((char_u *name, int *lenp));
465 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));
466 static int call_func __ARGS((char_u *func_name, int len, typval_T *rettv, int argcount, typval_T *argvars, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
467 static void emsg_funcname __ARGS((char *ermsg, char_u *name));
468 static int non_zero_arg __ARGS((typval_T *argvars));
470 #ifdef FEAT_FLOAT
471 static void f_abs __ARGS((typval_T *argvars, typval_T *rettv));
472 #endif
473 static void f_add __ARGS((typval_T *argvars, typval_T *rettv));
474 static void f_append __ARGS((typval_T *argvars, typval_T *rettv));
475 static void f_argc __ARGS((typval_T *argvars, typval_T *rettv));
476 static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv));
477 static void f_argv __ARGS((typval_T *argvars, typval_T *rettv));
478 #ifdef FEAT_FLOAT
479 static void f_atan __ARGS((typval_T *argvars, typval_T *rettv));
480 #endif
481 static void f_browse __ARGS((typval_T *argvars, typval_T *rettv));
482 static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv));
483 static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv));
484 static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv));
485 static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv));
486 static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv));
487 static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv));
488 static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv));
489 static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv));
490 static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv));
491 static void f_call __ARGS((typval_T *argvars, typval_T *rettv));
492 #ifdef FEAT_FLOAT
493 static void f_ceil __ARGS((typval_T *argvars, typval_T *rettv));
494 #endif
495 static void f_changenr __ARGS((typval_T *argvars, typval_T *rettv));
496 static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv));
497 static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv));
498 static void f_clearmatches __ARGS((typval_T *argvars, typval_T *rettv));
499 static void f_col __ARGS((typval_T *argvars, typval_T *rettv));
500 #if defined(FEAT_INS_EXPAND)
501 static void f_complete __ARGS((typval_T *argvars, typval_T *rettv));
502 static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv));
503 static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv));
504 #endif
505 static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv));
506 static void f_copy __ARGS((typval_T *argvars, typval_T *rettv));
507 #ifdef FEAT_FLOAT
508 static void f_cos __ARGS((typval_T *argvars, typval_T *rettv));
509 #endif
510 static void f_count __ARGS((typval_T *argvars, typval_T *rettv));
511 static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv));
513 static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv));
514 static void f_delete __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv));
516 static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv));
517 static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_empty __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_escape __ARGS((typval_T *argvars, typval_T *rettv));
520 static void f_eval __ARGS((typval_T *argvars, typval_T *rettv));
521 static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_executable __ARGS((typval_T *argvars, typval_T *rettv));
523 static void f_exists __ARGS((typval_T *argvars, typval_T *rettv));
524 static void f_expand __ARGS((typval_T *argvars, typval_T *rettv));
525 static void f_extend __ARGS((typval_T *argvars, typval_T *rettv));
526 static void f_feedkeys __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv));
528 static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv));
529 static void f_filter __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv));
531 static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv));
532 #ifdef FEAT_FLOAT
533 static void f_float2nr __ARGS((typval_T *argvars, typval_T *rettv));
534 static void f_floor __ARGS((typval_T *argvars, typval_T *rettv));
535 #endif
536 static void f_fnameescape __ARGS((typval_T *argvars, typval_T *rettv));
537 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
542 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
546 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
547 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
548 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
549 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
551 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
552 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_getpid __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
590 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
591 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
592 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
593 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
594 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
595 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
596 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
603 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
604 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
605 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
606 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
607 #ifdef FEAT_FLOAT
608 static void f_log10 __ARGS((typval_T *argvars, typval_T *rettv));
609 #endif
610 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
611 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
618 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
619 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
620 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
621 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
622 #ifdef vim_mkdir
623 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
624 #endif
625 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
626 #ifdef FEAT_MZSCHEME
627 static void f_mzeval __ARGS((typval_T *argvars, typval_T *rettv));
628 #endif
629 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
630 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
631 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
632 #ifdef FEAT_FLOAT
633 static void f_pow __ARGS((typval_T *argvars, typval_T *rettv));
634 #endif
635 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
636 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
637 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
638 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
639 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
640 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
641 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
642 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
643 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
644 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
645 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
646 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
647 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
648 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
649 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
650 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
651 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
652 #ifdef FEAT_FLOAT
653 static void f_round __ARGS((typval_T *argvars, typval_T *rettv));
654 #endif
655 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
656 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
657 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
667 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
668 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
669 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
670 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
671 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
672 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
673 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
674 #ifdef FEAT_FLOAT
675 static void f_sin __ARGS((typval_T *argvars, typval_T *rettv));
676 #endif
677 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
678 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
679 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
680 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
681 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
682 #ifdef FEAT_FLOAT
683 static void f_sqrt __ARGS((typval_T *argvars, typval_T *rettv));
684 static void f_str2float __ARGS((typval_T *argvars, typval_T *rettv));
685 #endif
686 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
687 #ifdef HAVE_STRFTIME
688 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
689 #endif
690 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
691 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
692 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
693 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
694 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
695 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
696 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
697 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
698 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
699 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
700 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
701 static void f_synstack __ARGS((typval_T *argvars, typval_T *rettv));
702 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
703 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
704 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
705 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
706 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
707 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
708 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
709 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
710 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
711 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
712 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
713 #ifdef FEAT_FLOAT
714 static void f_trunc __ARGS((typval_T *argvars, typval_T *rettv));
715 #endif
716 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
717 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
718 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
719 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
720 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
721 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
722 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
723 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
724 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
725 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
726 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
727 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
728 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
729 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
731 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
732 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
733 static int get_env_len __ARGS((char_u **arg));
734 static int get_id_len __ARGS((char_u **arg));
735 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
736 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
737 #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */
738 #define FNE_CHECK_START 2 /* find_name_end(): check name starts with
739 valid character */
740 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
741 static int eval_isnamec __ARGS((int c));
742 static int eval_isnamec1 __ARGS((int c));
743 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
744 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
745 static typval_T *alloc_tv __ARGS((void));
746 static typval_T *alloc_string_tv __ARGS((char_u *string));
747 static void init_tv __ARGS((typval_T *varp));
748 static long get_tv_number __ARGS((typval_T *varp));
749 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
750 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
751 static char_u *get_tv_string __ARGS((typval_T *varp));
752 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
753 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
754 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
755 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
756 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
757 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
758 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
759 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
760 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
761 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
762 static int var_check_ro __ARGS((int flags, char_u *name));
763 static int var_check_fixed __ARGS((int flags, char_u *name));
764 static int tv_check_lock __ARGS((int lock, char_u *name));
765 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
766 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
767 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
768 static int eval_fname_script __ARGS((char_u *p));
769 static int eval_fname_sid __ARGS((char_u *p));
770 static void list_func_head __ARGS((ufunc_T *fp, int indent));
771 static ufunc_T *find_func __ARGS((char_u *name));
772 static int function_exists __ARGS((char_u *name));
773 static int builtin_function __ARGS((char_u *name));
774 #ifdef FEAT_PROFILE
775 static void func_do_profile __ARGS((ufunc_T *fp));
776 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
777 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
778 static int
779 # ifdef __BORLANDC__
780 _RTLENTRYF
781 # endif
782 prof_total_cmp __ARGS((const void *s1, const void *s2));
783 static int
784 # ifdef __BORLANDC__
785 _RTLENTRYF
786 # endif
787 prof_self_cmp __ARGS((const void *s1, const void *s2));
788 #endif
789 static int script_autoload __ARGS((char_u *name, int reload));
790 static char_u *autoload_name __ARGS((char_u *name));
791 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
792 static void func_free __ARGS((ufunc_T *fp));
793 static void func_unref __ARGS((char_u *name));
794 static void func_ref __ARGS((char_u *name));
795 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));
796 static int can_free_funccal __ARGS((funccall_T *fc, int copyID)) ;
797 static void free_funccal __ARGS((funccall_T *fc, int free_val));
798 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
799 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
800 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
801 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
802 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
803 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
805 /* Character used as separated in autoload function/variable names. */
806 #define AUTOLOAD_CHAR '#'
809 * Initialize the global and v: variables.
811 void
812 eval_init()
814 int i;
815 struct vimvar *p;
817 init_var_dict(&globvardict, &globvars_var);
818 init_var_dict(&vimvardict, &vimvars_var);
819 hash_init(&compat_hashtab);
820 hash_init(&func_hashtab);
822 for (i = 0; i < VV_LEN; ++i)
824 p = &vimvars[i];
825 STRCPY(p->vv_di.di_key, p->vv_name);
826 if (p->vv_flags & VV_RO)
827 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
828 else if (p->vv_flags & VV_RO_SBX)
829 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
830 else
831 p->vv_di.di_flags = DI_FLAGS_FIX;
833 /* add to v: scope dict, unless the value is not always available */
834 if (p->vv_type != VAR_UNKNOWN)
835 hash_add(&vimvarht, p->vv_di.di_key);
836 if (p->vv_flags & VV_COMPAT)
837 /* add to compat scope dict */
838 hash_add(&compat_hashtab, p->vv_di.di_key);
840 set_vim_var_nr(VV_SEARCHFORWARD, 1L);
843 #if defined(EXITFREE) || defined(PROTO)
844 void
845 eval_clear()
847 int i;
848 struct vimvar *p;
850 for (i = 0; i < VV_LEN; ++i)
852 p = &vimvars[i];
853 if (p->vv_di.di_tv.v_type == VAR_STRING)
855 vim_free(p->vv_str);
856 p->vv_str = NULL;
858 else if (p->vv_di.di_tv.v_type == VAR_LIST)
860 list_unref(p->vv_list);
861 p->vv_list = NULL;
864 hash_clear(&vimvarht);
865 hash_init(&vimvarht); /* garbage_collect() will access it */
866 hash_clear(&compat_hashtab);
868 free_scriptnames();
870 /* global variables */
871 vars_clear(&globvarht);
873 /* autoloaded script names */
874 ga_clear_strings(&ga_loaded);
876 /* script-local variables */
877 for (i = 1; i <= ga_scripts.ga_len; ++i)
879 vars_clear(&SCRIPT_VARS(i));
880 vim_free(SCRIPT_SV(i));
882 ga_clear(&ga_scripts);
884 /* unreferenced lists and dicts */
885 (void)garbage_collect();
887 /* functions */
888 free_all_functions();
889 hash_clear(&func_hashtab);
891 #endif
894 * Return the name of the executed function.
896 char_u *
897 func_name(cookie)
898 void *cookie;
900 return ((funccall_T *)cookie)->func->uf_name;
904 * Return the address holding the next breakpoint line for a funccall cookie.
906 linenr_T *
907 func_breakpoint(cookie)
908 void *cookie;
910 return &((funccall_T *)cookie)->breakpoint;
914 * Return the address holding the debug tick for a funccall cookie.
916 int *
917 func_dbg_tick(cookie)
918 void *cookie;
920 return &((funccall_T *)cookie)->dbg_tick;
924 * Return the nesting level for a funccall cookie.
927 func_level(cookie)
928 void *cookie;
930 return ((funccall_T *)cookie)->level;
933 /* pointer to funccal for currently active function */
934 funccall_T *current_funccal = NULL;
936 /* pointer to list of previously used funccal, still around because some
937 * item in it is still being used. */
938 funccall_T *previous_funccal = NULL;
941 * Return TRUE when a function was ended by a ":return" command.
944 current_func_returned()
946 return current_funccal->returned;
951 * Set an internal variable to a string value. Creates the variable if it does
952 * not already exist.
954 void
955 set_internal_string_var(name, value)
956 char_u *name;
957 char_u *value;
959 char_u *val;
960 typval_T *tvp;
962 val = vim_strsave(value);
963 if (val != NULL)
965 tvp = alloc_string_tv(val);
966 if (tvp != NULL)
968 set_var(name, tvp, FALSE);
969 free_tv(tvp);
974 static lval_T *redir_lval = NULL;
975 static garray_T redir_ga; /* only valid when redir_lval is not NULL */
976 static char_u *redir_endp = NULL;
977 static char_u *redir_varname = NULL;
980 * Start recording command output to a variable
981 * Returns OK if successfully completed the setup. FAIL otherwise.
984 var_redir_start(name, append)
985 char_u *name;
986 int append; /* append to an existing variable */
988 int save_emsg;
989 int err;
990 typval_T tv;
992 /* Catch a bad name early. */
993 if (!eval_isnamec1(*name))
995 EMSG(_(e_invarg));
996 return FAIL;
999 /* Make a copy of the name, it is used in redir_lval until redir ends. */
1000 redir_varname = vim_strsave(name);
1001 if (redir_varname == NULL)
1002 return FAIL;
1004 redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
1005 if (redir_lval == NULL)
1007 var_redir_stop();
1008 return FAIL;
1011 /* The output is stored in growarray "redir_ga" until redirection ends. */
1012 ga_init2(&redir_ga, (int)sizeof(char), 500);
1014 /* Parse the variable name (can be a dict or list entry). */
1015 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
1016 FNE_CHECK_START);
1017 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
1019 if (redir_endp != NULL && *redir_endp != NUL)
1020 /* Trailing characters are present after the variable name */
1021 EMSG(_(e_trailing));
1022 else
1023 EMSG(_(e_invarg));
1024 redir_endp = NULL; /* don't store a value, only cleanup */
1025 var_redir_stop();
1026 return FAIL;
1029 /* check if we can write to the variable: set it to or append an empty
1030 * string */
1031 save_emsg = did_emsg;
1032 did_emsg = FALSE;
1033 tv.v_type = VAR_STRING;
1034 tv.vval.v_string = (char_u *)"";
1035 if (append)
1036 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
1037 else
1038 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
1039 err = did_emsg;
1040 did_emsg |= save_emsg;
1041 if (err)
1043 redir_endp = NULL; /* don't store a value, only cleanup */
1044 var_redir_stop();
1045 return FAIL;
1047 if (redir_lval->ll_newkey != NULL)
1049 /* Dictionary item was created, don't do it again. */
1050 vim_free(redir_lval->ll_newkey);
1051 redir_lval->ll_newkey = NULL;
1054 return OK;
1058 * Append "value[value_len]" to the variable set by var_redir_start().
1059 * The actual appending is postponed until redirection ends, because the value
1060 * appended may in fact be the string we write to, changing it may cause freed
1061 * memory to be used:
1062 * :redir => foo
1063 * :let foo
1064 * :redir END
1066 void
1067 var_redir_str(value, value_len)
1068 char_u *value;
1069 int value_len;
1071 int len;
1073 if (redir_lval == NULL)
1074 return;
1076 if (value_len == -1)
1077 len = (int)STRLEN(value); /* Append the entire string */
1078 else
1079 len = value_len; /* Append only "value_len" characters */
1081 if (ga_grow(&redir_ga, len) == OK)
1083 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1084 redir_ga.ga_len += len;
1086 else
1087 var_redir_stop();
1091 * Stop redirecting command output to a variable.
1092 * Frees the allocated memory.
1094 void
1095 var_redir_stop()
1097 typval_T tv;
1099 if (redir_lval != NULL)
1101 /* If there was no error: assign the text to the variable. */
1102 if (redir_endp != NULL)
1104 ga_append(&redir_ga, NUL); /* Append the trailing NUL. */
1105 tv.v_type = VAR_STRING;
1106 tv.vval.v_string = redir_ga.ga_data;
1107 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1110 /* free the collected output */
1111 vim_free(redir_ga.ga_data);
1112 redir_ga.ga_data = NULL;
1114 clear_lval(redir_lval);
1115 vim_free(redir_lval);
1116 redir_lval = NULL;
1118 vim_free(redir_varname);
1119 redir_varname = NULL;
1122 # if defined(FEAT_MBYTE) || defined(PROTO)
1124 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1125 char_u *enc_from;
1126 char_u *enc_to;
1127 char_u *fname_from;
1128 char_u *fname_to;
1130 int err = FALSE;
1132 set_vim_var_string(VV_CC_FROM, enc_from, -1);
1133 set_vim_var_string(VV_CC_TO, enc_to, -1);
1134 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1135 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1136 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1137 err = TRUE;
1138 set_vim_var_string(VV_CC_FROM, NULL, -1);
1139 set_vim_var_string(VV_CC_TO, NULL, -1);
1140 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1141 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1143 if (err)
1144 return FAIL;
1145 return OK;
1147 # endif
1149 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1151 eval_printexpr(fname, args)
1152 char_u *fname;
1153 char_u *args;
1155 int err = FALSE;
1157 set_vim_var_string(VV_FNAME_IN, fname, -1);
1158 set_vim_var_string(VV_CMDARG, args, -1);
1159 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1160 err = TRUE;
1161 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1162 set_vim_var_string(VV_CMDARG, NULL, -1);
1164 if (err)
1166 mch_remove(fname);
1167 return FAIL;
1169 return OK;
1171 # endif
1173 # if defined(FEAT_DIFF) || defined(PROTO)
1174 void
1175 eval_diff(origfile, newfile, outfile)
1176 char_u *origfile;
1177 char_u *newfile;
1178 char_u *outfile;
1180 int err = FALSE;
1182 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1183 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1184 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1185 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1186 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1187 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1188 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1191 void
1192 eval_patch(origfile, difffile, outfile)
1193 char_u *origfile;
1194 char_u *difffile;
1195 char_u *outfile;
1197 int err;
1199 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1200 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1201 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1202 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1203 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1204 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1205 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1207 # endif
1210 * Top level evaluation function, returning a boolean.
1211 * Sets "error" to TRUE if there was an error.
1212 * Return TRUE or FALSE.
1215 eval_to_bool(arg, error, nextcmd, skip)
1216 char_u *arg;
1217 int *error;
1218 char_u **nextcmd;
1219 int skip; /* only parse, don't execute */
1221 typval_T tv;
1222 int retval = FALSE;
1224 if (skip)
1225 ++emsg_skip;
1226 if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1227 *error = TRUE;
1228 else
1230 *error = FALSE;
1231 if (!skip)
1233 retval = (get_tv_number_chk(&tv, error) != 0);
1234 clear_tv(&tv);
1237 if (skip)
1238 --emsg_skip;
1240 return retval;
1244 * Top level evaluation function, returning a string. If "skip" is TRUE,
1245 * only parsing to "nextcmd" is done, without reporting errors. Return
1246 * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1248 char_u *
1249 eval_to_string_skip(arg, nextcmd, skip)
1250 char_u *arg;
1251 char_u **nextcmd;
1252 int skip; /* only parse, don't execute */
1254 typval_T tv;
1255 char_u *retval;
1257 if (skip)
1258 ++emsg_skip;
1259 if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1260 retval = NULL;
1261 else
1263 retval = vim_strsave(get_tv_string(&tv));
1264 clear_tv(&tv);
1266 if (skip)
1267 --emsg_skip;
1269 return retval;
1273 * Skip over an expression at "*pp".
1274 * Return FAIL for an error, OK otherwise.
1277 skip_expr(pp)
1278 char_u **pp;
1280 typval_T rettv;
1282 *pp = skipwhite(*pp);
1283 return eval1(pp, &rettv, FALSE);
1287 * Top level evaluation function, returning a string.
1288 * When "convert" is TRUE convert a List into a sequence of lines and convert
1289 * a Float to a String.
1290 * Return pointer to allocated memory, or NULL for failure.
1292 char_u *
1293 eval_to_string(arg, nextcmd, convert)
1294 char_u *arg;
1295 char_u **nextcmd;
1296 int convert;
1298 typval_T tv;
1299 char_u *retval;
1300 garray_T ga;
1301 #ifdef FEAT_FLOAT
1302 char_u numbuf[NUMBUFLEN];
1303 #endif
1305 if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1306 retval = NULL;
1307 else
1309 if (convert && tv.v_type == VAR_LIST)
1311 ga_init2(&ga, (int)sizeof(char), 80);
1312 if (tv.vval.v_list != NULL)
1313 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1314 ga_append(&ga, NUL);
1315 retval = (char_u *)ga.ga_data;
1317 #ifdef FEAT_FLOAT
1318 else if (convert && tv.v_type == VAR_FLOAT)
1320 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv.vval.v_float);
1321 retval = vim_strsave(numbuf);
1323 #endif
1324 else
1325 retval = vim_strsave(get_tv_string(&tv));
1326 clear_tv(&tv);
1329 return retval;
1333 * Call eval_to_string() without using current local variables and using
1334 * textlock. When "use_sandbox" is TRUE use the sandbox.
1336 char_u *
1337 eval_to_string_safe(arg, nextcmd, use_sandbox)
1338 char_u *arg;
1339 char_u **nextcmd;
1340 int use_sandbox;
1342 char_u *retval;
1343 void *save_funccalp;
1345 save_funccalp = save_funccal();
1346 if (use_sandbox)
1347 ++sandbox;
1348 ++textlock;
1349 retval = eval_to_string(arg, nextcmd, FALSE);
1350 if (use_sandbox)
1351 --sandbox;
1352 --textlock;
1353 restore_funccal(save_funccalp);
1354 return retval;
1358 * Top level evaluation function, returning a number.
1359 * Evaluates "expr" silently.
1360 * Returns -1 for an error.
1363 eval_to_number(expr)
1364 char_u *expr;
1366 typval_T rettv;
1367 int retval;
1368 char_u *p = skipwhite(expr);
1370 ++emsg_off;
1372 if (eval1(&p, &rettv, TRUE) == FAIL)
1373 retval = -1;
1374 else
1376 retval = get_tv_number_chk(&rettv, NULL);
1377 clear_tv(&rettv);
1379 --emsg_off;
1381 return retval;
1385 * Prepare v: variable "idx" to be used.
1386 * Save the current typeval in "save_tv".
1387 * When not used yet add the variable to the v: hashtable.
1389 static void
1390 prepare_vimvar(idx, save_tv)
1391 int idx;
1392 typval_T *save_tv;
1394 *save_tv = vimvars[idx].vv_tv;
1395 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1396 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1400 * Restore v: variable "idx" to typeval "save_tv".
1401 * When no longer defined, remove the variable from the v: hashtable.
1403 static void
1404 restore_vimvar(idx, save_tv)
1405 int idx;
1406 typval_T *save_tv;
1408 hashitem_T *hi;
1410 vimvars[idx].vv_tv = *save_tv;
1411 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1413 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1414 if (HASHITEM_EMPTY(hi))
1415 EMSG2(_(e_intern2), "restore_vimvar()");
1416 else
1417 hash_remove(&vimvarht, hi);
1421 #if defined(FEAT_SPELL) || defined(PROTO)
1423 * Evaluate an expression to a list with suggestions.
1424 * For the "expr:" part of 'spellsuggest'.
1425 * Returns NULL when there is an error.
1427 list_T *
1428 eval_spell_expr(badword, expr)
1429 char_u *badword;
1430 char_u *expr;
1432 typval_T save_val;
1433 typval_T rettv;
1434 list_T *list = NULL;
1435 char_u *p = skipwhite(expr);
1437 /* Set "v:val" to the bad word. */
1438 prepare_vimvar(VV_VAL, &save_val);
1439 vimvars[VV_VAL].vv_type = VAR_STRING;
1440 vimvars[VV_VAL].vv_str = badword;
1441 if (p_verbose == 0)
1442 ++emsg_off;
1444 if (eval1(&p, &rettv, TRUE) == OK)
1446 if (rettv.v_type != VAR_LIST)
1447 clear_tv(&rettv);
1448 else
1449 list = rettv.vval.v_list;
1452 if (p_verbose == 0)
1453 --emsg_off;
1454 restore_vimvar(VV_VAL, &save_val);
1456 return list;
1460 * "list" is supposed to contain two items: a word and a number. Return the
1461 * word in "pp" and the number as the return value.
1462 * Return -1 if anything isn't right.
1463 * Used to get the good word and score from the eval_spell_expr() result.
1466 get_spellword(list, pp)
1467 list_T *list;
1468 char_u **pp;
1470 listitem_T *li;
1472 li = list->lv_first;
1473 if (li == NULL)
1474 return -1;
1475 *pp = get_tv_string(&li->li_tv);
1477 li = li->li_next;
1478 if (li == NULL)
1479 return -1;
1480 return get_tv_number(&li->li_tv);
1482 #endif
1485 * Top level evaluation function.
1486 * Returns an allocated typval_T with the result.
1487 * Returns NULL when there is an error.
1489 typval_T *
1490 eval_expr(arg, nextcmd)
1491 char_u *arg;
1492 char_u **nextcmd;
1494 typval_T *tv;
1496 tv = (typval_T *)alloc(sizeof(typval_T));
1497 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1499 vim_free(tv);
1500 tv = NULL;
1503 return tv;
1507 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1508 || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1510 * Call some vimL function and return the result in "*rettv".
1511 * Uses argv[argc] for the function arguments. Only Number and String
1512 * arguments are currently supported.
1513 * Returns OK or FAIL.
1515 static int
1516 call_vim_function(func, argc, argv, safe, rettv)
1517 char_u *func;
1518 int argc;
1519 char_u **argv;
1520 int safe; /* use the sandbox */
1521 typval_T *rettv;
1523 typval_T *argvars;
1524 long n;
1525 int len;
1526 int i;
1527 int doesrange;
1528 void *save_funccalp = NULL;
1529 int ret;
1531 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1532 if (argvars == NULL)
1533 return FAIL;
1535 for (i = 0; i < argc; i++)
1537 /* Pass a NULL or empty argument as an empty string */
1538 if (argv[i] == NULL || *argv[i] == NUL)
1540 argvars[i].v_type = VAR_STRING;
1541 argvars[i].vval.v_string = (char_u *)"";
1542 continue;
1545 /* Recognize a number argument, the others must be strings. */
1546 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1547 if (len != 0 && len == (int)STRLEN(argv[i]))
1549 argvars[i].v_type = VAR_NUMBER;
1550 argvars[i].vval.v_number = n;
1552 else
1554 argvars[i].v_type = VAR_STRING;
1555 argvars[i].vval.v_string = argv[i];
1559 if (safe)
1561 save_funccalp = save_funccal();
1562 ++sandbox;
1565 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1566 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1567 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1568 &doesrange, TRUE, NULL);
1569 if (safe)
1571 --sandbox;
1572 restore_funccal(save_funccalp);
1574 vim_free(argvars);
1576 if (ret == FAIL)
1577 clear_tv(rettv);
1579 return ret;
1582 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1584 * Call vimL function "func" and return the result as a string.
1585 * Returns NULL when calling the function fails.
1586 * Uses argv[argc] for the function arguments.
1588 void *
1589 call_func_retstr(func, argc, argv, safe)
1590 char_u *func;
1591 int argc;
1592 char_u **argv;
1593 int safe; /* use the sandbox */
1595 typval_T rettv;
1596 char_u *retval;
1598 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1599 return NULL;
1601 retval = vim_strsave(get_tv_string(&rettv));
1602 clear_tv(&rettv);
1603 return retval;
1605 # endif
1607 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1609 * Call vimL function "func" and return the result as a number.
1610 * Returns -1 when calling the function fails.
1611 * Uses argv[argc] for the function arguments.
1613 long
1614 call_func_retnr(func, argc, argv, safe)
1615 char_u *func;
1616 int argc;
1617 char_u **argv;
1618 int safe; /* use the sandbox */
1620 typval_T rettv;
1621 long retval;
1623 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1624 return -1;
1626 retval = get_tv_number_chk(&rettv, NULL);
1627 clear_tv(&rettv);
1628 return retval;
1630 # endif
1633 * Call vimL function "func" and return the result as a List.
1634 * Uses argv[argc] for the function arguments.
1635 * Returns NULL when there is something wrong.
1637 void *
1638 call_func_retlist(func, argc, argv, safe)
1639 char_u *func;
1640 int argc;
1641 char_u **argv;
1642 int safe; /* use the sandbox */
1644 typval_T rettv;
1646 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1647 return NULL;
1649 if (rettv.v_type != VAR_LIST)
1651 clear_tv(&rettv);
1652 return NULL;
1655 return rettv.vval.v_list;
1657 #endif
1661 * Save the current function call pointer, and set it to NULL.
1662 * Used when executing autocommands and for ":source".
1664 void *
1665 save_funccal()
1667 funccall_T *fc = current_funccal;
1669 current_funccal = NULL;
1670 return (void *)fc;
1673 void
1674 restore_funccal(vfc)
1675 void *vfc;
1677 funccall_T *fc = (funccall_T *)vfc;
1679 current_funccal = fc;
1682 #if defined(FEAT_PROFILE) || defined(PROTO)
1684 * Prepare profiling for entering a child or something else that is not
1685 * counted for the script/function itself.
1686 * Should always be called in pair with prof_child_exit().
1688 void
1689 prof_child_enter(tm)
1690 proftime_T *tm; /* place to store waittime */
1692 funccall_T *fc = current_funccal;
1694 if (fc != NULL && fc->func->uf_profiling)
1695 profile_start(&fc->prof_child);
1696 script_prof_save(tm);
1700 * Take care of time spent in a child.
1701 * Should always be called after prof_child_enter().
1703 void
1704 prof_child_exit(tm)
1705 proftime_T *tm; /* where waittime was stored */
1707 funccall_T *fc = current_funccal;
1709 if (fc != NULL && fc->func->uf_profiling)
1711 profile_end(&fc->prof_child);
1712 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1713 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1714 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1716 script_prof_restore(tm);
1718 #endif
1721 #ifdef FEAT_FOLDING
1723 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1724 * it in "*cp". Doesn't give error messages.
1727 eval_foldexpr(arg, cp)
1728 char_u *arg;
1729 int *cp;
1731 typval_T tv;
1732 int retval;
1733 char_u *s;
1734 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1735 OPT_LOCAL);
1737 ++emsg_off;
1738 if (use_sandbox)
1739 ++sandbox;
1740 ++textlock;
1741 *cp = NUL;
1742 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1743 retval = 0;
1744 else
1746 /* If the result is a number, just return the number. */
1747 if (tv.v_type == VAR_NUMBER)
1748 retval = tv.vval.v_number;
1749 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1750 retval = 0;
1751 else
1753 /* If the result is a string, check if there is a non-digit before
1754 * the number. */
1755 s = tv.vval.v_string;
1756 if (!VIM_ISDIGIT(*s) && *s != '-')
1757 *cp = *s++;
1758 retval = atol((char *)s);
1760 clear_tv(&tv);
1762 --emsg_off;
1763 if (use_sandbox)
1764 --sandbox;
1765 --textlock;
1767 return retval;
1769 #endif
1772 * ":let" list all variable values
1773 * ":let var1 var2" list variable values
1774 * ":let var = expr" assignment command.
1775 * ":let var += expr" assignment command.
1776 * ":let var -= expr" assignment command.
1777 * ":let var .= expr" assignment command.
1778 * ":let [var1, var2] = expr" unpack list.
1780 void
1781 ex_let(eap)
1782 exarg_T *eap;
1784 char_u *arg = eap->arg;
1785 char_u *expr = NULL;
1786 typval_T rettv;
1787 int i;
1788 int var_count = 0;
1789 int semicolon = 0;
1790 char_u op[2];
1791 char_u *argend;
1792 int first = TRUE;
1794 argend = skip_var_list(arg, &var_count, &semicolon);
1795 if (argend == NULL)
1796 return;
1797 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1798 --argend;
1799 expr = vim_strchr(argend, '=');
1800 if (expr == NULL)
1803 * ":let" without "=": list variables
1805 if (*arg == '[')
1806 EMSG(_(e_invarg));
1807 else if (!ends_excmd(*arg))
1808 /* ":let var1 var2" */
1809 arg = list_arg_vars(eap, arg, &first);
1810 else if (!eap->skip)
1812 /* ":let" */
1813 list_glob_vars(&first);
1814 list_buf_vars(&first);
1815 list_win_vars(&first);
1816 #ifdef FEAT_WINDOWS
1817 list_tab_vars(&first);
1818 #endif
1819 list_script_vars(&first);
1820 list_func_vars(&first);
1821 list_vim_vars(&first);
1823 eap->nextcmd = check_nextcmd(arg);
1825 else
1827 op[0] = '=';
1828 op[1] = NUL;
1829 if (expr > argend)
1831 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1832 op[0] = expr[-1]; /* +=, -= or .= */
1834 expr = skipwhite(expr + 1);
1836 if (eap->skip)
1837 ++emsg_skip;
1838 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1839 if (eap->skip)
1841 if (i != FAIL)
1842 clear_tv(&rettv);
1843 --emsg_skip;
1845 else if (i != FAIL)
1847 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1848 op);
1849 clear_tv(&rettv);
1855 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1856 * Handles both "var" with any type and "[var, var; var]" with a list type.
1857 * When "nextchars" is not NULL it points to a string with characters that
1858 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1859 * or concatenate.
1860 * Returns OK or FAIL;
1862 static int
1863 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1864 char_u *arg_start;
1865 typval_T *tv;
1866 int copy; /* copy values from "tv", don't move */
1867 int semicolon; /* from skip_var_list() */
1868 int var_count; /* from skip_var_list() */
1869 char_u *nextchars;
1871 char_u *arg = arg_start;
1872 list_T *l;
1873 int i;
1874 listitem_T *item;
1875 typval_T ltv;
1877 if (*arg != '[')
1880 * ":let var = expr" or ":for var in list"
1882 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1883 return FAIL;
1884 return OK;
1888 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1890 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1892 EMSG(_(e_listreq));
1893 return FAIL;
1896 i = list_len(l);
1897 if (semicolon == 0 && var_count < i)
1899 EMSG(_("E687: Less targets than List items"));
1900 return FAIL;
1902 if (var_count - semicolon > i)
1904 EMSG(_("E688: More targets than List items"));
1905 return FAIL;
1908 item = l->lv_first;
1909 while (*arg != ']')
1911 arg = skipwhite(arg + 1);
1912 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1913 item = item->li_next;
1914 if (arg == NULL)
1915 return FAIL;
1917 arg = skipwhite(arg);
1918 if (*arg == ';')
1920 /* Put the rest of the list (may be empty) in the var after ';'.
1921 * Create a new list for this. */
1922 l = list_alloc();
1923 if (l == NULL)
1924 return FAIL;
1925 while (item != NULL)
1927 list_append_tv(l, &item->li_tv);
1928 item = item->li_next;
1931 ltv.v_type = VAR_LIST;
1932 ltv.v_lock = 0;
1933 ltv.vval.v_list = l;
1934 l->lv_refcount = 1;
1936 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1937 (char_u *)"]", nextchars);
1938 clear_tv(&ltv);
1939 if (arg == NULL)
1940 return FAIL;
1941 break;
1943 else if (*arg != ',' && *arg != ']')
1945 EMSG2(_(e_intern2), "ex_let_vars()");
1946 return FAIL;
1950 return OK;
1954 * Skip over assignable variable "var" or list of variables "[var, var]".
1955 * Used for ":let varvar = expr" and ":for varvar in expr".
1956 * For "[var, var]" increment "*var_count" for each variable.
1957 * for "[var, var; var]" set "semicolon".
1958 * Return NULL for an error.
1960 static char_u *
1961 skip_var_list(arg, var_count, semicolon)
1962 char_u *arg;
1963 int *var_count;
1964 int *semicolon;
1966 char_u *p, *s;
1968 if (*arg == '[')
1970 /* "[var, var]": find the matching ']'. */
1971 p = arg;
1972 for (;;)
1974 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
1975 s = skip_var_one(p);
1976 if (s == p)
1978 EMSG2(_(e_invarg2), p);
1979 return NULL;
1981 ++*var_count;
1983 p = skipwhite(s);
1984 if (*p == ']')
1985 break;
1986 else if (*p == ';')
1988 if (*semicolon == 1)
1990 EMSG(_("Double ; in list of variables"));
1991 return NULL;
1993 *semicolon = 1;
1995 else if (*p != ',')
1997 EMSG2(_(e_invarg2), p);
1998 return NULL;
2001 return p + 1;
2003 else
2004 return skip_var_one(arg);
2008 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
2009 * l[idx].
2011 static char_u *
2012 skip_var_one(arg)
2013 char_u *arg;
2015 if (*arg == '@' && arg[1] != NUL)
2016 return arg + 2;
2017 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
2018 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2022 * List variables for hashtab "ht" with prefix "prefix".
2023 * If "empty" is TRUE also list NULL strings as empty strings.
2025 static void
2026 list_hashtable_vars(ht, prefix, empty, first)
2027 hashtab_T *ht;
2028 char_u *prefix;
2029 int empty;
2030 int *first;
2032 hashitem_T *hi;
2033 dictitem_T *di;
2034 int todo;
2036 todo = (int)ht->ht_used;
2037 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
2039 if (!HASHITEM_EMPTY(hi))
2041 --todo;
2042 di = HI2DI(hi);
2043 if (empty || di->di_tv.v_type != VAR_STRING
2044 || di->di_tv.vval.v_string != NULL)
2045 list_one_var(di, prefix, first);
2051 * List global variables.
2053 static void
2054 list_glob_vars(first)
2055 int *first;
2057 list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
2061 * List buffer variables.
2063 static void
2064 list_buf_vars(first)
2065 int *first;
2067 char_u numbuf[NUMBUFLEN];
2069 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:",
2070 TRUE, first);
2072 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
2073 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
2074 numbuf, first);
2078 * List window variables.
2080 static void
2081 list_win_vars(first)
2082 int *first;
2084 list_hashtable_vars(&curwin->w_vars.dv_hashtab,
2085 (char_u *)"w:", TRUE, first);
2088 #ifdef FEAT_WINDOWS
2090 * List tab page variables.
2092 static void
2093 list_tab_vars(first)
2094 int *first;
2096 list_hashtable_vars(&curtab->tp_vars.dv_hashtab,
2097 (char_u *)"t:", TRUE, first);
2099 #endif
2102 * List Vim variables.
2104 static void
2105 list_vim_vars(first)
2106 int *first;
2108 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2112 * List script-local variables, if there is a script.
2114 static void
2115 list_script_vars(first)
2116 int *first;
2118 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2119 list_hashtable_vars(&SCRIPT_VARS(current_SID),
2120 (char_u *)"s:", FALSE, first);
2124 * List function variables, if there is a function.
2126 static void
2127 list_func_vars(first)
2128 int *first;
2130 if (current_funccal != NULL)
2131 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2132 (char_u *)"l:", FALSE, first);
2136 * List variables in "arg".
2138 static char_u *
2139 list_arg_vars(eap, arg, first)
2140 exarg_T *eap;
2141 char_u *arg;
2142 int *first;
2144 int error = FALSE;
2145 int len;
2146 char_u *name;
2147 char_u *name_start;
2148 char_u *arg_subsc;
2149 char_u *tofree;
2150 typval_T tv;
2152 while (!ends_excmd(*arg) && !got_int)
2154 if (error || eap->skip)
2156 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2157 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2159 emsg_severe = TRUE;
2160 EMSG(_(e_trailing));
2161 break;
2164 else
2166 /* get_name_len() takes care of expanding curly braces */
2167 name_start = name = arg;
2168 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2169 if (len <= 0)
2171 /* This is mainly to keep test 49 working: when expanding
2172 * curly braces fails overrule the exception error message. */
2173 if (len < 0 && !aborting())
2175 emsg_severe = TRUE;
2176 EMSG2(_(e_invarg2), arg);
2177 break;
2179 error = TRUE;
2181 else
2183 if (tofree != NULL)
2184 name = tofree;
2185 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2186 error = TRUE;
2187 else
2189 /* handle d.key, l[idx], f(expr) */
2190 arg_subsc = arg;
2191 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2192 error = TRUE;
2193 else
2195 if (arg == arg_subsc && len == 2 && name[1] == ':')
2197 switch (*name)
2199 case 'g': list_glob_vars(first); break;
2200 case 'b': list_buf_vars(first); break;
2201 case 'w': list_win_vars(first); break;
2202 #ifdef FEAT_WINDOWS
2203 case 't': list_tab_vars(first); break;
2204 #endif
2205 case 'v': list_vim_vars(first); break;
2206 case 's': list_script_vars(first); break;
2207 case 'l': list_func_vars(first); break;
2208 default:
2209 EMSG2(_("E738: Can't list variables for %s"), name);
2212 else
2214 char_u numbuf[NUMBUFLEN];
2215 char_u *tf;
2216 int c;
2217 char_u *s;
2219 s = echo_string(&tv, &tf, numbuf, 0);
2220 c = *arg;
2221 *arg = NUL;
2222 list_one_var_a((char_u *)"",
2223 arg == arg_subsc ? name : name_start,
2224 tv.v_type,
2225 s == NULL ? (char_u *)"" : s,
2226 first);
2227 *arg = c;
2228 vim_free(tf);
2230 clear_tv(&tv);
2235 vim_free(tofree);
2238 arg = skipwhite(arg);
2241 return arg;
2245 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2246 * Returns a pointer to the char just after the var name.
2247 * Returns NULL if there is an error.
2249 static char_u *
2250 ex_let_one(arg, tv, copy, endchars, op)
2251 char_u *arg; /* points to variable name */
2252 typval_T *tv; /* value to assign to variable */
2253 int copy; /* copy value from "tv" */
2254 char_u *endchars; /* valid chars after variable name or NULL */
2255 char_u *op; /* "+", "-", "." or NULL*/
2257 int c1;
2258 char_u *name;
2259 char_u *p;
2260 char_u *arg_end = NULL;
2261 int len;
2262 int opt_flags;
2263 char_u *tofree = NULL;
2266 * ":let $VAR = expr": Set environment variable.
2268 if (*arg == '$')
2270 /* Find the end of the name. */
2271 ++arg;
2272 name = arg;
2273 len = get_env_len(&arg);
2274 if (len == 0)
2275 EMSG2(_(e_invarg2), name - 1);
2276 else
2278 if (op != NULL && (*op == '+' || *op == '-'))
2279 EMSG2(_(e_letwrong), op);
2280 else if (endchars != NULL
2281 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2282 EMSG(_(e_letunexp));
2283 else
2285 c1 = name[len];
2286 name[len] = NUL;
2287 p = get_tv_string_chk(tv);
2288 if (p != NULL && op != NULL && *op == '.')
2290 int mustfree = FALSE;
2291 char_u *s = vim_getenv(name, &mustfree);
2293 if (s != NULL)
2295 p = tofree = concat_str(s, p);
2296 if (mustfree)
2297 vim_free(s);
2300 if (p != NULL)
2302 vim_setenv(name, p);
2303 if (STRICMP(name, "HOME") == 0)
2304 init_homedir();
2305 else if (didset_vim && STRICMP(name, "VIM") == 0)
2306 didset_vim = FALSE;
2307 else if (didset_vimruntime
2308 && STRICMP(name, "VIMRUNTIME") == 0)
2309 didset_vimruntime = FALSE;
2310 arg_end = arg;
2312 name[len] = c1;
2313 vim_free(tofree);
2319 * ":let &option = expr": Set option value.
2320 * ":let &l:option = expr": Set local option value.
2321 * ":let &g:option = expr": Set global option value.
2323 else if (*arg == '&')
2325 /* Find the end of the name. */
2326 p = find_option_end(&arg, &opt_flags);
2327 if (p == NULL || (endchars != NULL
2328 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2329 EMSG(_(e_letunexp));
2330 else
2332 long n;
2333 int opt_type;
2334 long numval;
2335 char_u *stringval = NULL;
2336 char_u *s;
2338 c1 = *p;
2339 *p = NUL;
2341 n = get_tv_number(tv);
2342 s = get_tv_string_chk(tv); /* != NULL if number or string */
2343 if (s != NULL && op != NULL && *op != '=')
2345 opt_type = get_option_value(arg, &numval,
2346 &stringval, opt_flags);
2347 if ((opt_type == 1 && *op == '.')
2348 || (opt_type == 0 && *op != '.'))
2349 EMSG2(_(e_letwrong), op);
2350 else
2352 if (opt_type == 1) /* number */
2354 if (*op == '+')
2355 n = numval + n;
2356 else
2357 n = numval - n;
2359 else if (opt_type == 0 && stringval != NULL) /* string */
2361 s = concat_str(stringval, s);
2362 vim_free(stringval);
2363 stringval = s;
2367 if (s != NULL)
2369 set_option_value(arg, n, s, opt_flags);
2370 arg_end = p;
2372 *p = c1;
2373 vim_free(stringval);
2378 * ":let @r = expr": Set register contents.
2380 else if (*arg == '@')
2382 ++arg;
2383 if (op != NULL && (*op == '+' || *op == '-'))
2384 EMSG2(_(e_letwrong), op);
2385 else if (endchars != NULL
2386 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2387 EMSG(_(e_letunexp));
2388 else
2390 char_u *ptofree = NULL;
2391 char_u *s;
2393 p = get_tv_string_chk(tv);
2394 if (p != NULL && op != NULL && *op == '.')
2396 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2397 if (s != NULL)
2399 p = ptofree = concat_str(s, p);
2400 vim_free(s);
2403 if (p != NULL)
2405 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2406 arg_end = arg + 1;
2408 vim_free(ptofree);
2413 * ":let var = expr": Set internal variable.
2414 * ":let {expr} = expr": Idem, name made with curly braces
2416 else if (eval_isnamec1(*arg) || *arg == '{')
2418 lval_T lv;
2420 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2421 if (p != NULL && lv.ll_name != NULL)
2423 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2424 EMSG(_(e_letunexp));
2425 else
2427 set_var_lval(&lv, p, tv, copy, op);
2428 arg_end = p;
2431 clear_lval(&lv);
2434 else
2435 EMSG2(_(e_invarg2), arg);
2437 return arg_end;
2441 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2443 static int
2444 check_changedtick(arg)
2445 char_u *arg;
2447 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2449 EMSG2(_(e_readonlyvar), arg);
2450 return TRUE;
2452 return FALSE;
2456 * Get an lval: variable, Dict item or List item that can be assigned a value
2457 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2458 * "name.key", "name.key[expr]" etc.
2459 * Indexing only works if "name" is an existing List or Dictionary.
2460 * "name" points to the start of the name.
2461 * If "rettv" is not NULL it points to the value to be assigned.
2462 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2463 * wrong; must end in space or cmd separator.
2465 * Returns a pointer to just after the name, including indexes.
2466 * When an evaluation error occurs "lp->ll_name" is NULL;
2467 * Returns NULL for a parsing error. Still need to free items in "lp"!
2469 static char_u *
2470 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2471 char_u *name;
2472 typval_T *rettv;
2473 lval_T *lp;
2474 int unlet;
2475 int skip;
2476 int quiet; /* don't give error messages */
2477 int fne_flags; /* flags for find_name_end() */
2479 char_u *p;
2480 char_u *expr_start, *expr_end;
2481 int cc;
2482 dictitem_T *v;
2483 typval_T var1;
2484 typval_T var2;
2485 int empty1 = FALSE;
2486 listitem_T *ni;
2487 char_u *key = NULL;
2488 int len;
2489 hashtab_T *ht;
2491 /* Clear everything in "lp". */
2492 vim_memset(lp, 0, sizeof(lval_T));
2494 if (skip)
2496 /* When skipping just find the end of the name. */
2497 lp->ll_name = name;
2498 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2501 /* Find the end of the name. */
2502 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2503 if (expr_start != NULL)
2505 /* Don't expand the name when we already know there is an error. */
2506 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2507 && *p != '[' && *p != '.')
2509 EMSG(_(e_trailing));
2510 return NULL;
2513 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2514 if (lp->ll_exp_name == NULL)
2516 /* Report an invalid expression in braces, unless the
2517 * expression evaluation has been cancelled due to an
2518 * aborting error, an interrupt, or an exception. */
2519 if (!aborting() && !quiet)
2521 emsg_severe = TRUE;
2522 EMSG2(_(e_invarg2), name);
2523 return NULL;
2526 lp->ll_name = lp->ll_exp_name;
2528 else
2529 lp->ll_name = name;
2531 /* Without [idx] or .key we are done. */
2532 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2533 return p;
2535 cc = *p;
2536 *p = NUL;
2537 v = find_var(lp->ll_name, &ht);
2538 if (v == NULL && !quiet)
2539 EMSG2(_(e_undefvar), lp->ll_name);
2540 *p = cc;
2541 if (v == NULL)
2542 return NULL;
2545 * Loop until no more [idx] or .key is following.
2547 lp->ll_tv = &v->di_tv;
2548 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2550 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2551 && !(lp->ll_tv->v_type == VAR_DICT
2552 && lp->ll_tv->vval.v_dict != NULL))
2554 if (!quiet)
2555 EMSG(_("E689: Can only index a List or Dictionary"));
2556 return NULL;
2558 if (lp->ll_range)
2560 if (!quiet)
2561 EMSG(_("E708: [:] must come last"));
2562 return NULL;
2565 len = -1;
2566 if (*p == '.')
2568 key = p + 1;
2569 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2571 if (len == 0)
2573 if (!quiet)
2574 EMSG(_(e_emptykey));
2575 return NULL;
2577 p = key + len;
2579 else
2581 /* Get the index [expr] or the first index [expr: ]. */
2582 p = skipwhite(p + 1);
2583 if (*p == ':')
2584 empty1 = TRUE;
2585 else
2587 empty1 = FALSE;
2588 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2589 return NULL;
2590 if (get_tv_string_chk(&var1) == NULL)
2592 /* not a number or string */
2593 clear_tv(&var1);
2594 return NULL;
2598 /* Optionally get the second index [ :expr]. */
2599 if (*p == ':')
2601 if (lp->ll_tv->v_type == VAR_DICT)
2603 if (!quiet)
2604 EMSG(_(e_dictrange));
2605 if (!empty1)
2606 clear_tv(&var1);
2607 return NULL;
2609 if (rettv != NULL && (rettv->v_type != VAR_LIST
2610 || rettv->vval.v_list == NULL))
2612 if (!quiet)
2613 EMSG(_("E709: [:] requires a List value"));
2614 if (!empty1)
2615 clear_tv(&var1);
2616 return NULL;
2618 p = skipwhite(p + 1);
2619 if (*p == ']')
2620 lp->ll_empty2 = TRUE;
2621 else
2623 lp->ll_empty2 = FALSE;
2624 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2626 if (!empty1)
2627 clear_tv(&var1);
2628 return NULL;
2630 if (get_tv_string_chk(&var2) == NULL)
2632 /* not a number or string */
2633 if (!empty1)
2634 clear_tv(&var1);
2635 clear_tv(&var2);
2636 return NULL;
2639 lp->ll_range = TRUE;
2641 else
2642 lp->ll_range = FALSE;
2644 if (*p != ']')
2646 if (!quiet)
2647 EMSG(_(e_missbrac));
2648 if (!empty1)
2649 clear_tv(&var1);
2650 if (lp->ll_range && !lp->ll_empty2)
2651 clear_tv(&var2);
2652 return NULL;
2655 /* Skip to past ']'. */
2656 ++p;
2659 if (lp->ll_tv->v_type == VAR_DICT)
2661 if (len == -1)
2663 /* "[key]": get key from "var1" */
2664 key = get_tv_string(&var1); /* is number or string */
2665 if (*key == NUL)
2667 if (!quiet)
2668 EMSG(_(e_emptykey));
2669 clear_tv(&var1);
2670 return NULL;
2673 lp->ll_list = NULL;
2674 lp->ll_dict = lp->ll_tv->vval.v_dict;
2675 lp->ll_di = dict_find(lp->ll_dict, key, len);
2676 if (lp->ll_di == NULL)
2678 /* Key does not exist in dict: may need to add it. */
2679 if (*p == '[' || *p == '.' || unlet)
2681 if (!quiet)
2682 EMSG2(_(e_dictkey), key);
2683 if (len == -1)
2684 clear_tv(&var1);
2685 return NULL;
2687 if (len == -1)
2688 lp->ll_newkey = vim_strsave(key);
2689 else
2690 lp->ll_newkey = vim_strnsave(key, len);
2691 if (len == -1)
2692 clear_tv(&var1);
2693 if (lp->ll_newkey == NULL)
2694 p = NULL;
2695 break;
2697 if (len == -1)
2698 clear_tv(&var1);
2699 lp->ll_tv = &lp->ll_di->di_tv;
2701 else
2704 * Get the number and item for the only or first index of the List.
2706 if (empty1)
2707 lp->ll_n1 = 0;
2708 else
2710 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2711 clear_tv(&var1);
2713 lp->ll_dict = NULL;
2714 lp->ll_list = lp->ll_tv->vval.v_list;
2715 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2716 if (lp->ll_li == NULL)
2718 if (lp->ll_n1 < 0)
2720 lp->ll_n1 = 0;
2721 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2724 if (lp->ll_li == NULL)
2726 if (lp->ll_range && !lp->ll_empty2)
2727 clear_tv(&var2);
2728 return NULL;
2732 * May need to find the item or absolute index for the second
2733 * index of a range.
2734 * When no index given: "lp->ll_empty2" is TRUE.
2735 * Otherwise "lp->ll_n2" is set to the second index.
2737 if (lp->ll_range && !lp->ll_empty2)
2739 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2740 clear_tv(&var2);
2741 if (lp->ll_n2 < 0)
2743 ni = list_find(lp->ll_list, lp->ll_n2);
2744 if (ni == NULL)
2745 return NULL;
2746 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2749 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2750 if (lp->ll_n1 < 0)
2751 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2752 if (lp->ll_n2 < lp->ll_n1)
2753 return NULL;
2756 lp->ll_tv = &lp->ll_li->li_tv;
2760 return p;
2764 * Clear lval "lp" that was filled by get_lval().
2766 static void
2767 clear_lval(lp)
2768 lval_T *lp;
2770 vim_free(lp->ll_exp_name);
2771 vim_free(lp->ll_newkey);
2775 * Set a variable that was parsed by get_lval() to "rettv".
2776 * "endp" points to just after the parsed name.
2777 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2779 static void
2780 set_var_lval(lp, endp, rettv, copy, op)
2781 lval_T *lp;
2782 char_u *endp;
2783 typval_T *rettv;
2784 int copy;
2785 char_u *op;
2787 int cc;
2788 listitem_T *ri;
2789 dictitem_T *di;
2791 if (lp->ll_tv == NULL)
2793 if (!check_changedtick(lp->ll_name))
2795 cc = *endp;
2796 *endp = NUL;
2797 if (op != NULL && *op != '=')
2799 typval_T tv;
2801 /* handle +=, -= and .= */
2802 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2803 &tv, TRUE) == OK)
2805 if (tv_op(&tv, rettv, op) == OK)
2806 set_var(lp->ll_name, &tv, FALSE);
2807 clear_tv(&tv);
2810 else
2811 set_var(lp->ll_name, rettv, copy);
2812 *endp = cc;
2815 else if (tv_check_lock(lp->ll_newkey == NULL
2816 ? lp->ll_tv->v_lock
2817 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2819 else if (lp->ll_range)
2822 * Assign the List values to the list items.
2824 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2826 if (op != NULL && *op != '=')
2827 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2828 else
2830 clear_tv(&lp->ll_li->li_tv);
2831 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2833 ri = ri->li_next;
2834 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2835 break;
2836 if (lp->ll_li->li_next == NULL)
2838 /* Need to add an empty item. */
2839 if (list_append_number(lp->ll_list, 0) == FAIL)
2841 ri = NULL;
2842 break;
2845 lp->ll_li = lp->ll_li->li_next;
2846 ++lp->ll_n1;
2848 if (ri != NULL)
2849 EMSG(_("E710: List value has more items than target"));
2850 else if (lp->ll_empty2
2851 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2852 : lp->ll_n1 != lp->ll_n2)
2853 EMSG(_("E711: List value has not enough items"));
2855 else
2858 * Assign to a List or Dictionary item.
2860 if (lp->ll_newkey != NULL)
2862 if (op != NULL && *op != '=')
2864 EMSG2(_(e_letwrong), op);
2865 return;
2868 /* Need to add an item to the Dictionary. */
2869 di = dictitem_alloc(lp->ll_newkey);
2870 if (di == NULL)
2871 return;
2872 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2874 vim_free(di);
2875 return;
2877 lp->ll_tv = &di->di_tv;
2879 else if (op != NULL && *op != '=')
2881 tv_op(lp->ll_tv, rettv, op);
2882 return;
2884 else
2885 clear_tv(lp->ll_tv);
2888 * Assign the value to the variable or list item.
2890 if (copy)
2891 copy_tv(rettv, lp->ll_tv);
2892 else
2894 *lp->ll_tv = *rettv;
2895 lp->ll_tv->v_lock = 0;
2896 init_tv(rettv);
2902 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2903 * Returns OK or FAIL.
2905 static int
2906 tv_op(tv1, tv2, op)
2907 typval_T *tv1;
2908 typval_T *tv2;
2909 char_u *op;
2911 long n;
2912 char_u numbuf[NUMBUFLEN];
2913 char_u *s;
2915 /* Can't do anything with a Funcref or a Dict on the right. */
2916 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2918 switch (tv1->v_type)
2920 case VAR_DICT:
2921 case VAR_FUNC:
2922 break;
2924 case VAR_LIST:
2925 if (*op != '+' || tv2->v_type != VAR_LIST)
2926 break;
2927 /* List += List */
2928 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2929 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2930 return OK;
2932 case VAR_NUMBER:
2933 case VAR_STRING:
2934 if (tv2->v_type == VAR_LIST)
2935 break;
2936 if (*op == '+' || *op == '-')
2938 /* nr += nr or nr -= nr*/
2939 n = get_tv_number(tv1);
2940 #ifdef FEAT_FLOAT
2941 if (tv2->v_type == VAR_FLOAT)
2943 float_T f = n;
2945 if (*op == '+')
2946 f += tv2->vval.v_float;
2947 else
2948 f -= tv2->vval.v_float;
2949 clear_tv(tv1);
2950 tv1->v_type = VAR_FLOAT;
2951 tv1->vval.v_float = f;
2953 else
2954 #endif
2956 if (*op == '+')
2957 n += get_tv_number(tv2);
2958 else
2959 n -= get_tv_number(tv2);
2960 clear_tv(tv1);
2961 tv1->v_type = VAR_NUMBER;
2962 tv1->vval.v_number = n;
2965 else
2967 if (tv2->v_type == VAR_FLOAT)
2968 break;
2970 /* str .= str */
2971 s = get_tv_string(tv1);
2972 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2973 clear_tv(tv1);
2974 tv1->v_type = VAR_STRING;
2975 tv1->vval.v_string = s;
2977 return OK;
2979 #ifdef FEAT_FLOAT
2980 case VAR_FLOAT:
2982 float_T f;
2984 if (*op == '.' || (tv2->v_type != VAR_FLOAT
2985 && tv2->v_type != VAR_NUMBER
2986 && tv2->v_type != VAR_STRING))
2987 break;
2988 if (tv2->v_type == VAR_FLOAT)
2989 f = tv2->vval.v_float;
2990 else
2991 f = get_tv_number(tv2);
2992 if (*op == '+')
2993 tv1->vval.v_float += f;
2994 else
2995 tv1->vval.v_float -= f;
2997 return OK;
2998 #endif
3002 EMSG2(_(e_letwrong), op);
3003 return FAIL;
3007 * Add a watcher to a list.
3009 static void
3010 list_add_watch(l, lw)
3011 list_T *l;
3012 listwatch_T *lw;
3014 lw->lw_next = l->lv_watch;
3015 l->lv_watch = lw;
3019 * Remove a watcher from a list.
3020 * No warning when it isn't found...
3022 static void
3023 list_rem_watch(l, lwrem)
3024 list_T *l;
3025 listwatch_T *lwrem;
3027 listwatch_T *lw, **lwp;
3029 lwp = &l->lv_watch;
3030 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3032 if (lw == lwrem)
3034 *lwp = lw->lw_next;
3035 break;
3037 lwp = &lw->lw_next;
3042 * Just before removing an item from a list: advance watchers to the next
3043 * item.
3045 static void
3046 list_fix_watch(l, item)
3047 list_T *l;
3048 listitem_T *item;
3050 listwatch_T *lw;
3052 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3053 if (lw->lw_item == item)
3054 lw->lw_item = item->li_next;
3058 * Evaluate the expression used in a ":for var in expr" command.
3059 * "arg" points to "var".
3060 * Set "*errp" to TRUE for an error, FALSE otherwise;
3061 * Return a pointer that holds the info. Null when there is an error.
3063 void *
3064 eval_for_line(arg, errp, nextcmdp, skip)
3065 char_u *arg;
3066 int *errp;
3067 char_u **nextcmdp;
3068 int skip;
3070 forinfo_T *fi;
3071 char_u *expr;
3072 typval_T tv;
3073 list_T *l;
3075 *errp = TRUE; /* default: there is an error */
3077 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
3078 if (fi == NULL)
3079 return NULL;
3081 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
3082 if (expr == NULL)
3083 return fi;
3085 expr = skipwhite(expr);
3086 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
3088 EMSG(_("E690: Missing \"in\" after :for"));
3089 return fi;
3092 if (skip)
3093 ++emsg_skip;
3094 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
3096 *errp = FALSE;
3097 if (!skip)
3099 l = tv.vval.v_list;
3100 if (tv.v_type != VAR_LIST || l == NULL)
3102 EMSG(_(e_listreq));
3103 clear_tv(&tv);
3105 else
3107 /* No need to increment the refcount, it's already set for the
3108 * list being used in "tv". */
3109 fi->fi_list = l;
3110 list_add_watch(l, &fi->fi_lw);
3111 fi->fi_lw.lw_item = l->lv_first;
3115 if (skip)
3116 --emsg_skip;
3118 return fi;
3122 * Use the first item in a ":for" list. Advance to the next.
3123 * Assign the values to the variable (list). "arg" points to the first one.
3124 * Return TRUE when a valid item was found, FALSE when at end of list or
3125 * something wrong.
3128 next_for_item(fi_void, arg)
3129 void *fi_void;
3130 char_u *arg;
3132 forinfo_T *fi = (forinfo_T *)fi_void;
3133 int result;
3134 listitem_T *item;
3136 item = fi->fi_lw.lw_item;
3137 if (item == NULL)
3138 result = FALSE;
3139 else
3141 fi->fi_lw.lw_item = item->li_next;
3142 result = (ex_let_vars(arg, &item->li_tv, TRUE,
3143 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3145 return result;
3149 * Free the structure used to store info used by ":for".
3151 void
3152 free_for_info(fi_void)
3153 void *fi_void;
3155 forinfo_T *fi = (forinfo_T *)fi_void;
3157 if (fi != NULL && fi->fi_list != NULL)
3159 list_rem_watch(fi->fi_list, &fi->fi_lw);
3160 list_unref(fi->fi_list);
3162 vim_free(fi);
3165 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3167 void
3168 set_context_for_expression(xp, arg, cmdidx)
3169 expand_T *xp;
3170 char_u *arg;
3171 cmdidx_T cmdidx;
3173 int got_eq = FALSE;
3174 int c;
3175 char_u *p;
3177 if (cmdidx == CMD_let)
3179 xp->xp_context = EXPAND_USER_VARS;
3180 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3182 /* ":let var1 var2 ...": find last space. */
3183 for (p = arg + STRLEN(arg); p >= arg; )
3185 xp->xp_pattern = p;
3186 mb_ptr_back(arg, p);
3187 if (vim_iswhite(*p))
3188 break;
3190 return;
3193 else
3194 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3195 : EXPAND_EXPRESSION;
3196 while ((xp->xp_pattern = vim_strpbrk(arg,
3197 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3199 c = *xp->xp_pattern;
3200 if (c == '&')
3202 c = xp->xp_pattern[1];
3203 if (c == '&')
3205 ++xp->xp_pattern;
3206 xp->xp_context = cmdidx != CMD_let || got_eq
3207 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3209 else if (c != ' ')
3211 xp->xp_context = EXPAND_SETTINGS;
3212 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3213 xp->xp_pattern += 2;
3217 else if (c == '$')
3219 /* environment variable */
3220 xp->xp_context = EXPAND_ENV_VARS;
3222 else if (c == '=')
3224 got_eq = TRUE;
3225 xp->xp_context = EXPAND_EXPRESSION;
3227 else if (c == '<'
3228 && xp->xp_context == EXPAND_FUNCTIONS
3229 && vim_strchr(xp->xp_pattern, '(') == NULL)
3231 /* Function name can start with "<SNR>" */
3232 break;
3234 else if (cmdidx != CMD_let || got_eq)
3236 if (c == '"') /* string */
3238 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3239 if (c == '\\' && xp->xp_pattern[1] != NUL)
3240 ++xp->xp_pattern;
3241 xp->xp_context = EXPAND_NOTHING;
3243 else if (c == '\'') /* literal string */
3245 /* Trick: '' is like stopping and starting a literal string. */
3246 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3247 /* skip */ ;
3248 xp->xp_context = EXPAND_NOTHING;
3250 else if (c == '|')
3252 if (xp->xp_pattern[1] == '|')
3254 ++xp->xp_pattern;
3255 xp->xp_context = EXPAND_EXPRESSION;
3257 else
3258 xp->xp_context = EXPAND_COMMANDS;
3260 else
3261 xp->xp_context = EXPAND_EXPRESSION;
3263 else
3264 /* Doesn't look like something valid, expand as an expression
3265 * anyway. */
3266 xp->xp_context = EXPAND_EXPRESSION;
3267 arg = xp->xp_pattern;
3268 if (*arg != NUL)
3269 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3270 /* skip */ ;
3272 xp->xp_pattern = arg;
3275 #endif /* FEAT_CMDL_COMPL */
3278 * ":1,25call func(arg1, arg2)" function call.
3280 void
3281 ex_call(eap)
3282 exarg_T *eap;
3284 char_u *arg = eap->arg;
3285 char_u *startarg;
3286 char_u *name;
3287 char_u *tofree;
3288 int len;
3289 typval_T rettv;
3290 linenr_T lnum;
3291 int doesrange;
3292 int failed = FALSE;
3293 funcdict_T fudi;
3295 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3296 if (fudi.fd_newkey != NULL)
3298 /* Still need to give an error message for missing key. */
3299 EMSG2(_(e_dictkey), fudi.fd_newkey);
3300 vim_free(fudi.fd_newkey);
3302 if (tofree == NULL)
3303 return;
3305 /* Increase refcount on dictionary, it could get deleted when evaluating
3306 * the arguments. */
3307 if (fudi.fd_dict != NULL)
3308 ++fudi.fd_dict->dv_refcount;
3310 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3311 len = (int)STRLEN(tofree);
3312 name = deref_func_name(tofree, &len);
3314 /* Skip white space to allow ":call func ()". Not good, but required for
3315 * backward compatibility. */
3316 startarg = skipwhite(arg);
3317 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3319 if (*startarg != '(')
3321 EMSG2(_("E107: Missing parentheses: %s"), eap->arg);
3322 goto end;
3326 * When skipping, evaluate the function once, to find the end of the
3327 * arguments.
3328 * When the function takes a range, this is discovered after the first
3329 * call, and the loop is broken.
3331 if (eap->skip)
3333 ++emsg_skip;
3334 lnum = eap->line2; /* do it once, also with an invalid range */
3336 else
3337 lnum = eap->line1;
3338 for ( ; lnum <= eap->line2; ++lnum)
3340 if (!eap->skip && eap->addr_count > 0)
3342 curwin->w_cursor.lnum = lnum;
3343 curwin->w_cursor.col = 0;
3345 arg = startarg;
3346 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3347 eap->line1, eap->line2, &doesrange,
3348 !eap->skip, fudi.fd_dict) == FAIL)
3350 failed = TRUE;
3351 break;
3354 /* Handle a function returning a Funcref, Dictionary or List. */
3355 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3357 failed = TRUE;
3358 break;
3361 clear_tv(&rettv);
3362 if (doesrange || eap->skip)
3363 break;
3365 /* Stop when immediately aborting on error, or when an interrupt
3366 * occurred or an exception was thrown but not caught.
3367 * get_func_tv() returned OK, so that the check for trailing
3368 * characters below is executed. */
3369 if (aborting())
3370 break;
3372 if (eap->skip)
3373 --emsg_skip;
3375 if (!failed)
3377 /* Check for trailing illegal characters and a following command. */
3378 if (!ends_excmd(*arg))
3380 emsg_severe = TRUE;
3381 EMSG(_(e_trailing));
3383 else
3384 eap->nextcmd = check_nextcmd(arg);
3387 end:
3388 dict_unref(fudi.fd_dict);
3389 vim_free(tofree);
3393 * ":unlet[!] var1 ... " command.
3395 void
3396 ex_unlet(eap)
3397 exarg_T *eap;
3399 ex_unletlock(eap, eap->arg, 0);
3403 * ":lockvar" and ":unlockvar" commands
3405 void
3406 ex_lockvar(eap)
3407 exarg_T *eap;
3409 char_u *arg = eap->arg;
3410 int deep = 2;
3412 if (eap->forceit)
3413 deep = -1;
3414 else if (vim_isdigit(*arg))
3416 deep = getdigits(&arg);
3417 arg = skipwhite(arg);
3420 ex_unletlock(eap, arg, deep);
3424 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3426 static void
3427 ex_unletlock(eap, argstart, deep)
3428 exarg_T *eap;
3429 char_u *argstart;
3430 int deep;
3432 char_u *arg = argstart;
3433 char_u *name_end;
3434 int error = FALSE;
3435 lval_T lv;
3439 /* Parse the name and find the end. */
3440 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3441 FNE_CHECK_START);
3442 if (lv.ll_name == NULL)
3443 error = TRUE; /* error but continue parsing */
3444 if (name_end == NULL || (!vim_iswhite(*name_end)
3445 && !ends_excmd(*name_end)))
3447 if (name_end != NULL)
3449 emsg_severe = TRUE;
3450 EMSG(_(e_trailing));
3452 if (!(eap->skip || error))
3453 clear_lval(&lv);
3454 break;
3457 if (!error && !eap->skip)
3459 if (eap->cmdidx == CMD_unlet)
3461 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3462 error = TRUE;
3464 else
3466 if (do_lock_var(&lv, name_end, deep,
3467 eap->cmdidx == CMD_lockvar) == FAIL)
3468 error = TRUE;
3472 if (!eap->skip)
3473 clear_lval(&lv);
3475 arg = skipwhite(name_end);
3476 } while (!ends_excmd(*arg));
3478 eap->nextcmd = check_nextcmd(arg);
3481 static int
3482 do_unlet_var(lp, name_end, forceit)
3483 lval_T *lp;
3484 char_u *name_end;
3485 int forceit;
3487 int ret = OK;
3488 int cc;
3490 if (lp->ll_tv == NULL)
3492 cc = *name_end;
3493 *name_end = NUL;
3495 /* Normal name or expanded name. */
3496 if (check_changedtick(lp->ll_name))
3497 ret = FAIL;
3498 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3499 ret = FAIL;
3500 *name_end = cc;
3502 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3503 return FAIL;
3504 else if (lp->ll_range)
3506 listitem_T *li;
3508 /* Delete a range of List items. */
3509 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3511 li = lp->ll_li->li_next;
3512 listitem_remove(lp->ll_list, lp->ll_li);
3513 lp->ll_li = li;
3514 ++lp->ll_n1;
3517 else
3519 if (lp->ll_list != NULL)
3520 /* unlet a List item. */
3521 listitem_remove(lp->ll_list, lp->ll_li);
3522 else
3523 /* unlet a Dictionary item. */
3524 dictitem_remove(lp->ll_dict, lp->ll_di);
3527 return ret;
3531 * "unlet" a variable. Return OK if it existed, FAIL if not.
3532 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3535 do_unlet(name, forceit)
3536 char_u *name;
3537 int forceit;
3539 hashtab_T *ht;
3540 hashitem_T *hi;
3541 char_u *varname;
3542 dictitem_T *di;
3544 ht = find_var_ht(name, &varname);
3545 if (ht != NULL && *varname != NUL)
3547 hi = hash_find(ht, varname);
3548 if (!HASHITEM_EMPTY(hi))
3550 di = HI2DI(hi);
3551 if (var_check_fixed(di->di_flags, name)
3552 || var_check_ro(di->di_flags, name))
3553 return FAIL;
3554 delete_var(ht, hi);
3555 return OK;
3558 if (forceit)
3559 return OK;
3560 EMSG2(_("E108: No such variable: \"%s\""), name);
3561 return FAIL;
3565 * Lock or unlock variable indicated by "lp".
3566 * "deep" is the levels to go (-1 for unlimited);
3567 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3569 static int
3570 do_lock_var(lp, name_end, deep, lock)
3571 lval_T *lp;
3572 char_u *name_end;
3573 int deep;
3574 int lock;
3576 int ret = OK;
3577 int cc;
3578 dictitem_T *di;
3580 if (deep == 0) /* nothing to do */
3581 return OK;
3583 if (lp->ll_tv == NULL)
3585 cc = *name_end;
3586 *name_end = NUL;
3588 /* Normal name or expanded name. */
3589 if (check_changedtick(lp->ll_name))
3590 ret = FAIL;
3591 else
3593 di = find_var(lp->ll_name, NULL);
3594 if (di == NULL)
3595 ret = FAIL;
3596 else
3598 if (lock)
3599 di->di_flags |= DI_FLAGS_LOCK;
3600 else
3601 di->di_flags &= ~DI_FLAGS_LOCK;
3602 item_lock(&di->di_tv, deep, lock);
3605 *name_end = cc;
3607 else if (lp->ll_range)
3609 listitem_T *li = lp->ll_li;
3611 /* (un)lock a range of List items. */
3612 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3614 item_lock(&li->li_tv, deep, lock);
3615 li = li->li_next;
3616 ++lp->ll_n1;
3619 else if (lp->ll_list != NULL)
3620 /* (un)lock a List item. */
3621 item_lock(&lp->ll_li->li_tv, deep, lock);
3622 else
3623 /* un(lock) a Dictionary item. */
3624 item_lock(&lp->ll_di->di_tv, deep, lock);
3626 return ret;
3630 * Lock or unlock an item. "deep" is nr of levels to go.
3632 static void
3633 item_lock(tv, deep, lock)
3634 typval_T *tv;
3635 int deep;
3636 int lock;
3638 static int recurse = 0;
3639 list_T *l;
3640 listitem_T *li;
3641 dict_T *d;
3642 hashitem_T *hi;
3643 int todo;
3645 if (recurse >= DICT_MAXNEST)
3647 EMSG(_("E743: variable nested too deep for (un)lock"));
3648 return;
3650 if (deep == 0)
3651 return;
3652 ++recurse;
3654 /* lock/unlock the item itself */
3655 if (lock)
3656 tv->v_lock |= VAR_LOCKED;
3657 else
3658 tv->v_lock &= ~VAR_LOCKED;
3660 switch (tv->v_type)
3662 case VAR_LIST:
3663 if ((l = tv->vval.v_list) != NULL)
3665 if (lock)
3666 l->lv_lock |= VAR_LOCKED;
3667 else
3668 l->lv_lock &= ~VAR_LOCKED;
3669 if (deep < 0 || deep > 1)
3670 /* recursive: lock/unlock the items the List contains */
3671 for (li = l->lv_first; li != NULL; li = li->li_next)
3672 item_lock(&li->li_tv, deep - 1, lock);
3674 break;
3675 case VAR_DICT:
3676 if ((d = tv->vval.v_dict) != NULL)
3678 if (lock)
3679 d->dv_lock |= VAR_LOCKED;
3680 else
3681 d->dv_lock &= ~VAR_LOCKED;
3682 if (deep < 0 || deep > 1)
3684 /* recursive: lock/unlock the items the List contains */
3685 todo = (int)d->dv_hashtab.ht_used;
3686 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3688 if (!HASHITEM_EMPTY(hi))
3690 --todo;
3691 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3697 --recurse;
3701 * Return TRUE if typeval "tv" is locked: Either that value is locked itself
3702 * or it refers to a List or Dictionary that is locked.
3704 static int
3705 tv_islocked(tv)
3706 typval_T *tv;
3708 return (tv->v_lock & VAR_LOCKED)
3709 || (tv->v_type == VAR_LIST
3710 && tv->vval.v_list != NULL
3711 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3712 || (tv->v_type == VAR_DICT
3713 && tv->vval.v_dict != NULL
3714 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3717 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3719 * Delete all "menutrans_" variables.
3721 void
3722 del_menutrans_vars()
3724 hashitem_T *hi;
3725 int todo;
3727 hash_lock(&globvarht);
3728 todo = (int)globvarht.ht_used;
3729 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3731 if (!HASHITEM_EMPTY(hi))
3733 --todo;
3734 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3735 delete_var(&globvarht, hi);
3738 hash_unlock(&globvarht);
3740 #endif
3742 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3745 * Local string buffer for the next two functions to store a variable name
3746 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3747 * get_user_var_name().
3750 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3752 static char_u *varnamebuf = NULL;
3753 static int varnamebuflen = 0;
3756 * Function to concatenate a prefix and a variable name.
3758 static char_u *
3759 cat_prefix_varname(prefix, name)
3760 int prefix;
3761 char_u *name;
3763 int len;
3765 len = (int)STRLEN(name) + 3;
3766 if (len > varnamebuflen)
3768 vim_free(varnamebuf);
3769 len += 10; /* some additional space */
3770 varnamebuf = alloc(len);
3771 if (varnamebuf == NULL)
3773 varnamebuflen = 0;
3774 return NULL;
3776 varnamebuflen = len;
3778 *varnamebuf = prefix;
3779 varnamebuf[1] = ':';
3780 STRCPY(varnamebuf + 2, name);
3781 return varnamebuf;
3785 * Function given to ExpandGeneric() to obtain the list of user defined
3786 * (global/buffer/window/built-in) variable names.
3788 char_u *
3789 get_user_var_name(xp, idx)
3790 expand_T *xp;
3791 int idx;
3793 static long_u gdone;
3794 static long_u bdone;
3795 static long_u wdone;
3796 #ifdef FEAT_WINDOWS
3797 static long_u tdone;
3798 #endif
3799 static int vidx;
3800 static hashitem_T *hi;
3801 hashtab_T *ht;
3803 if (idx == 0)
3805 gdone = bdone = wdone = vidx = 0;
3806 #ifdef FEAT_WINDOWS
3807 tdone = 0;
3808 #endif
3811 /* Global variables */
3812 if (gdone < globvarht.ht_used)
3814 if (gdone++ == 0)
3815 hi = globvarht.ht_array;
3816 else
3817 ++hi;
3818 while (HASHITEM_EMPTY(hi))
3819 ++hi;
3820 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3821 return cat_prefix_varname('g', hi->hi_key);
3822 return hi->hi_key;
3825 /* b: variables */
3826 ht = &curbuf->b_vars.dv_hashtab;
3827 if (bdone < ht->ht_used)
3829 if (bdone++ == 0)
3830 hi = ht->ht_array;
3831 else
3832 ++hi;
3833 while (HASHITEM_EMPTY(hi))
3834 ++hi;
3835 return cat_prefix_varname('b', hi->hi_key);
3837 if (bdone == ht->ht_used)
3839 ++bdone;
3840 return (char_u *)"b:changedtick";
3843 /* w: variables */
3844 ht = &curwin->w_vars.dv_hashtab;
3845 if (wdone < ht->ht_used)
3847 if (wdone++ == 0)
3848 hi = ht->ht_array;
3849 else
3850 ++hi;
3851 while (HASHITEM_EMPTY(hi))
3852 ++hi;
3853 return cat_prefix_varname('w', hi->hi_key);
3856 #ifdef FEAT_WINDOWS
3857 /* t: variables */
3858 ht = &curtab->tp_vars.dv_hashtab;
3859 if (tdone < ht->ht_used)
3861 if (tdone++ == 0)
3862 hi = ht->ht_array;
3863 else
3864 ++hi;
3865 while (HASHITEM_EMPTY(hi))
3866 ++hi;
3867 return cat_prefix_varname('t', hi->hi_key);
3869 #endif
3871 /* v: variables */
3872 if (vidx < VV_LEN)
3873 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3875 vim_free(varnamebuf);
3876 varnamebuf = NULL;
3877 varnamebuflen = 0;
3878 return NULL;
3881 #endif /* FEAT_CMDL_COMPL */
3884 * types for expressions.
3886 typedef enum
3888 TYPE_UNKNOWN = 0
3889 , TYPE_EQUAL /* == */
3890 , TYPE_NEQUAL /* != */
3891 , TYPE_GREATER /* > */
3892 , TYPE_GEQUAL /* >= */
3893 , TYPE_SMALLER /* < */
3894 , TYPE_SEQUAL /* <= */
3895 , TYPE_MATCH /* =~ */
3896 , TYPE_NOMATCH /* !~ */
3897 } exptype_T;
3900 * The "evaluate" argument: When FALSE, the argument is only parsed but not
3901 * executed. The function may return OK, but the rettv will be of type
3902 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
3906 * Handle zero level expression.
3907 * This calls eval1() and handles error message and nextcmd.
3908 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3909 * Note: "rettv.v_lock" is not set.
3910 * Return OK or FAIL.
3912 static int
3913 eval0(arg, rettv, nextcmd, evaluate)
3914 char_u *arg;
3915 typval_T *rettv;
3916 char_u **nextcmd;
3917 int evaluate;
3919 int ret;
3920 char_u *p;
3922 p = skipwhite(arg);
3923 ret = eval1(&p, rettv, evaluate);
3924 if (ret == FAIL || !ends_excmd(*p))
3926 if (ret != FAIL)
3927 clear_tv(rettv);
3929 * Report the invalid expression unless the expression evaluation has
3930 * been cancelled due to an aborting error, an interrupt, or an
3931 * exception.
3933 if (!aborting())
3934 EMSG2(_(e_invexpr2), arg);
3935 ret = FAIL;
3937 if (nextcmd != NULL)
3938 *nextcmd = check_nextcmd(p);
3940 return ret;
3944 * Handle top level expression:
3945 * expr2 ? expr1 : expr1
3947 * "arg" must point to the first non-white of the expression.
3948 * "arg" is advanced to the next non-white after the recognized expression.
3950 * Note: "rettv.v_lock" is not set.
3952 * Return OK or FAIL.
3954 static int
3955 eval1(arg, rettv, evaluate)
3956 char_u **arg;
3957 typval_T *rettv;
3958 int evaluate;
3960 int result;
3961 typval_T var2;
3964 * Get the first variable.
3966 if (eval2(arg, rettv, evaluate) == FAIL)
3967 return FAIL;
3969 if ((*arg)[0] == '?')
3971 result = FALSE;
3972 if (evaluate)
3974 int error = FALSE;
3976 if (get_tv_number_chk(rettv, &error) != 0)
3977 result = TRUE;
3978 clear_tv(rettv);
3979 if (error)
3980 return FAIL;
3984 * Get the second variable.
3986 *arg = skipwhite(*arg + 1);
3987 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
3988 return FAIL;
3991 * Check for the ":".
3993 if ((*arg)[0] != ':')
3995 EMSG(_("E109: Missing ':' after '?'"));
3996 if (evaluate && result)
3997 clear_tv(rettv);
3998 return FAIL;
4002 * Get the third variable.
4004 *arg = skipwhite(*arg + 1);
4005 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
4007 if (evaluate && result)
4008 clear_tv(rettv);
4009 return FAIL;
4011 if (evaluate && !result)
4012 *rettv = var2;
4015 return OK;
4019 * Handle first level expression:
4020 * expr2 || expr2 || expr2 logical OR
4022 * "arg" must point to the first non-white of the expression.
4023 * "arg" is advanced to the next non-white after the recognized expression.
4025 * Return OK or FAIL.
4027 static int
4028 eval2(arg, rettv, evaluate)
4029 char_u **arg;
4030 typval_T *rettv;
4031 int evaluate;
4033 typval_T var2;
4034 long result;
4035 int first;
4036 int error = FALSE;
4039 * Get the first variable.
4041 if (eval3(arg, rettv, evaluate) == FAIL)
4042 return FAIL;
4045 * Repeat until there is no following "||".
4047 first = TRUE;
4048 result = FALSE;
4049 while ((*arg)[0] == '|' && (*arg)[1] == '|')
4051 if (evaluate && first)
4053 if (get_tv_number_chk(rettv, &error) != 0)
4054 result = TRUE;
4055 clear_tv(rettv);
4056 if (error)
4057 return FAIL;
4058 first = FALSE;
4062 * Get the second variable.
4064 *arg = skipwhite(*arg + 2);
4065 if (eval3(arg, &var2, evaluate && !result) == FAIL)
4066 return FAIL;
4069 * Compute the result.
4071 if (evaluate && !result)
4073 if (get_tv_number_chk(&var2, &error) != 0)
4074 result = TRUE;
4075 clear_tv(&var2);
4076 if (error)
4077 return FAIL;
4079 if (evaluate)
4081 rettv->v_type = VAR_NUMBER;
4082 rettv->vval.v_number = result;
4086 return OK;
4090 * Handle second level expression:
4091 * expr3 && expr3 && expr3 logical AND
4093 * "arg" must point to the first non-white of the expression.
4094 * "arg" is advanced to the next non-white after the recognized expression.
4096 * Return OK or FAIL.
4098 static int
4099 eval3(arg, rettv, evaluate)
4100 char_u **arg;
4101 typval_T *rettv;
4102 int evaluate;
4104 typval_T var2;
4105 long result;
4106 int first;
4107 int error = FALSE;
4110 * Get the first variable.
4112 if (eval4(arg, rettv, evaluate) == FAIL)
4113 return FAIL;
4116 * Repeat until there is no following "&&".
4118 first = TRUE;
4119 result = TRUE;
4120 while ((*arg)[0] == '&' && (*arg)[1] == '&')
4122 if (evaluate && first)
4124 if (get_tv_number_chk(rettv, &error) == 0)
4125 result = FALSE;
4126 clear_tv(rettv);
4127 if (error)
4128 return FAIL;
4129 first = FALSE;
4133 * Get the second variable.
4135 *arg = skipwhite(*arg + 2);
4136 if (eval4(arg, &var2, evaluate && result) == FAIL)
4137 return FAIL;
4140 * Compute the result.
4142 if (evaluate && result)
4144 if (get_tv_number_chk(&var2, &error) == 0)
4145 result = FALSE;
4146 clear_tv(&var2);
4147 if (error)
4148 return FAIL;
4150 if (evaluate)
4152 rettv->v_type = VAR_NUMBER;
4153 rettv->vval.v_number = result;
4157 return OK;
4161 * Handle third level expression:
4162 * var1 == var2
4163 * var1 =~ var2
4164 * var1 != var2
4165 * var1 !~ var2
4166 * var1 > var2
4167 * var1 >= var2
4168 * var1 < var2
4169 * var1 <= var2
4170 * var1 is var2
4171 * var1 isnot var2
4173 * "arg" must point to the first non-white of the expression.
4174 * "arg" is advanced to the next non-white after the recognized expression.
4176 * Return OK or FAIL.
4178 static int
4179 eval4(arg, rettv, evaluate)
4180 char_u **arg;
4181 typval_T *rettv;
4182 int evaluate;
4184 typval_T var2;
4185 char_u *p;
4186 int i;
4187 exptype_T type = TYPE_UNKNOWN;
4188 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4189 int len = 2;
4190 long n1, n2;
4191 char_u *s1, *s2;
4192 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4193 regmatch_T regmatch;
4194 int ic;
4195 char_u *save_cpo;
4198 * Get the first variable.
4200 if (eval5(arg, rettv, evaluate) == FAIL)
4201 return FAIL;
4203 p = *arg;
4204 switch (p[0])
4206 case '=': if (p[1] == '=')
4207 type = TYPE_EQUAL;
4208 else if (p[1] == '~')
4209 type = TYPE_MATCH;
4210 break;
4211 case '!': if (p[1] == '=')
4212 type = TYPE_NEQUAL;
4213 else if (p[1] == '~')
4214 type = TYPE_NOMATCH;
4215 break;
4216 case '>': if (p[1] != '=')
4218 type = TYPE_GREATER;
4219 len = 1;
4221 else
4222 type = TYPE_GEQUAL;
4223 break;
4224 case '<': if (p[1] != '=')
4226 type = TYPE_SMALLER;
4227 len = 1;
4229 else
4230 type = TYPE_SEQUAL;
4231 break;
4232 case 'i': if (p[1] == 's')
4234 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4235 len = 5;
4236 if (!vim_isIDc(p[len]))
4238 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4239 type_is = TRUE;
4242 break;
4246 * If there is a comparative operator, use it.
4248 if (type != TYPE_UNKNOWN)
4250 /* extra question mark appended: ignore case */
4251 if (p[len] == '?')
4253 ic = TRUE;
4254 ++len;
4256 /* extra '#' appended: match case */
4257 else if (p[len] == '#')
4259 ic = FALSE;
4260 ++len;
4262 /* nothing appended: use 'ignorecase' */
4263 else
4264 ic = p_ic;
4267 * Get the second variable.
4269 *arg = skipwhite(p + len);
4270 if (eval5(arg, &var2, evaluate) == FAIL)
4272 clear_tv(rettv);
4273 return FAIL;
4276 if (evaluate)
4278 if (type_is && rettv->v_type != var2.v_type)
4280 /* For "is" a different type always means FALSE, for "notis"
4281 * it means TRUE. */
4282 n1 = (type == TYPE_NEQUAL);
4284 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4286 if (type_is)
4288 n1 = (rettv->v_type == var2.v_type
4289 && rettv->vval.v_list == var2.vval.v_list);
4290 if (type == TYPE_NEQUAL)
4291 n1 = !n1;
4293 else if (rettv->v_type != var2.v_type
4294 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4296 if (rettv->v_type != var2.v_type)
4297 EMSG(_("E691: Can only compare List with List"));
4298 else
4299 EMSG(_("E692: Invalid operation for Lists"));
4300 clear_tv(rettv);
4301 clear_tv(&var2);
4302 return FAIL;
4304 else
4306 /* Compare two Lists for being equal or unequal. */
4307 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
4308 if (type == TYPE_NEQUAL)
4309 n1 = !n1;
4313 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4315 if (type_is)
4317 n1 = (rettv->v_type == var2.v_type
4318 && rettv->vval.v_dict == var2.vval.v_dict);
4319 if (type == TYPE_NEQUAL)
4320 n1 = !n1;
4322 else if (rettv->v_type != var2.v_type
4323 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4325 if (rettv->v_type != var2.v_type)
4326 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4327 else
4328 EMSG(_("E736: Invalid operation for Dictionary"));
4329 clear_tv(rettv);
4330 clear_tv(&var2);
4331 return FAIL;
4333 else
4335 /* Compare two Dictionaries for being equal or unequal. */
4336 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4337 if (type == TYPE_NEQUAL)
4338 n1 = !n1;
4342 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4344 if (rettv->v_type != var2.v_type
4345 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4347 if (rettv->v_type != var2.v_type)
4348 EMSG(_("E693: Can only compare Funcref with Funcref"));
4349 else
4350 EMSG(_("E694: Invalid operation for Funcrefs"));
4351 clear_tv(rettv);
4352 clear_tv(&var2);
4353 return FAIL;
4355 else
4357 /* Compare two Funcrefs for being equal or unequal. */
4358 if (rettv->vval.v_string == NULL
4359 || var2.vval.v_string == NULL)
4360 n1 = FALSE;
4361 else
4362 n1 = STRCMP(rettv->vval.v_string,
4363 var2.vval.v_string) == 0;
4364 if (type == TYPE_NEQUAL)
4365 n1 = !n1;
4369 #ifdef FEAT_FLOAT
4371 * If one of the two variables is a float, compare as a float.
4372 * When using "=~" or "!~", always compare as string.
4374 else if ((rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4375 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4377 float_T f1, f2;
4379 if (rettv->v_type == VAR_FLOAT)
4380 f1 = rettv->vval.v_float;
4381 else
4382 f1 = get_tv_number(rettv);
4383 if (var2.v_type == VAR_FLOAT)
4384 f2 = var2.vval.v_float;
4385 else
4386 f2 = get_tv_number(&var2);
4387 n1 = FALSE;
4388 switch (type)
4390 case TYPE_EQUAL: n1 = (f1 == f2); break;
4391 case TYPE_NEQUAL: n1 = (f1 != f2); break;
4392 case TYPE_GREATER: n1 = (f1 > f2); break;
4393 case TYPE_GEQUAL: n1 = (f1 >= f2); break;
4394 case TYPE_SMALLER: n1 = (f1 < f2); break;
4395 case TYPE_SEQUAL: n1 = (f1 <= f2); break;
4396 case TYPE_UNKNOWN:
4397 case TYPE_MATCH:
4398 case TYPE_NOMATCH: break; /* avoid gcc warning */
4401 #endif
4404 * If one of the two variables is a number, compare as a number.
4405 * When using "=~" or "!~", always compare as string.
4407 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4408 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4410 n1 = get_tv_number(rettv);
4411 n2 = get_tv_number(&var2);
4412 switch (type)
4414 case TYPE_EQUAL: n1 = (n1 == n2); break;
4415 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4416 case TYPE_GREATER: n1 = (n1 > n2); break;
4417 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4418 case TYPE_SMALLER: n1 = (n1 < n2); break;
4419 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4420 case TYPE_UNKNOWN:
4421 case TYPE_MATCH:
4422 case TYPE_NOMATCH: break; /* avoid gcc warning */
4425 else
4427 s1 = get_tv_string_buf(rettv, buf1);
4428 s2 = get_tv_string_buf(&var2, buf2);
4429 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4430 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4431 else
4432 i = 0;
4433 n1 = FALSE;
4434 switch (type)
4436 case TYPE_EQUAL: n1 = (i == 0); break;
4437 case TYPE_NEQUAL: n1 = (i != 0); break;
4438 case TYPE_GREATER: n1 = (i > 0); break;
4439 case TYPE_GEQUAL: n1 = (i >= 0); break;
4440 case TYPE_SMALLER: n1 = (i < 0); break;
4441 case TYPE_SEQUAL: n1 = (i <= 0); break;
4443 case TYPE_MATCH:
4444 case TYPE_NOMATCH:
4445 /* avoid 'l' flag in 'cpoptions' */
4446 save_cpo = p_cpo;
4447 p_cpo = (char_u *)"";
4448 regmatch.regprog = vim_regcomp(s2,
4449 RE_MAGIC + RE_STRING);
4450 regmatch.rm_ic = ic;
4451 if (regmatch.regprog != NULL)
4453 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4454 vim_free(regmatch.regprog);
4455 if (type == TYPE_NOMATCH)
4456 n1 = !n1;
4458 p_cpo = save_cpo;
4459 break;
4461 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4464 clear_tv(rettv);
4465 clear_tv(&var2);
4466 rettv->v_type = VAR_NUMBER;
4467 rettv->vval.v_number = n1;
4471 return OK;
4475 * Handle fourth level expression:
4476 * + number addition
4477 * - number subtraction
4478 * . string concatenation
4480 * "arg" must point to the first non-white of the expression.
4481 * "arg" is advanced to the next non-white after the recognized expression.
4483 * Return OK or FAIL.
4485 static int
4486 eval5(arg, rettv, evaluate)
4487 char_u **arg;
4488 typval_T *rettv;
4489 int evaluate;
4491 typval_T var2;
4492 typval_T var3;
4493 int op;
4494 long n1, n2;
4495 #ifdef FEAT_FLOAT
4496 float_T f1 = 0, f2 = 0;
4497 #endif
4498 char_u *s1, *s2;
4499 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4500 char_u *p;
4503 * Get the first variable.
4505 if (eval6(arg, rettv, evaluate, FALSE) == FAIL)
4506 return FAIL;
4509 * Repeat computing, until no '+', '-' or '.' is following.
4511 for (;;)
4513 op = **arg;
4514 if (op != '+' && op != '-' && op != '.')
4515 break;
4517 if ((op != '+' || rettv->v_type != VAR_LIST)
4518 #ifdef FEAT_FLOAT
4519 && (op == '.' || rettv->v_type != VAR_FLOAT)
4520 #endif
4523 /* For "list + ...", an illegal use of the first operand as
4524 * a number cannot be determined before evaluating the 2nd
4525 * operand: if this is also a list, all is ok.
4526 * For "something . ...", "something - ..." or "non-list + ...",
4527 * we know that the first operand needs to be a string or number
4528 * without evaluating the 2nd operand. So check before to avoid
4529 * side effects after an error. */
4530 if (evaluate && get_tv_string_chk(rettv) == NULL)
4532 clear_tv(rettv);
4533 return FAIL;
4538 * Get the second variable.
4540 *arg = skipwhite(*arg + 1);
4541 if (eval6(arg, &var2, evaluate, op == '.') == FAIL)
4543 clear_tv(rettv);
4544 return FAIL;
4547 if (evaluate)
4550 * Compute the result.
4552 if (op == '.')
4554 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4555 s2 = get_tv_string_buf_chk(&var2, buf2);
4556 if (s2 == NULL) /* type error ? */
4558 clear_tv(rettv);
4559 clear_tv(&var2);
4560 return FAIL;
4562 p = concat_str(s1, s2);
4563 clear_tv(rettv);
4564 rettv->v_type = VAR_STRING;
4565 rettv->vval.v_string = p;
4567 else if (op == '+' && rettv->v_type == VAR_LIST
4568 && var2.v_type == VAR_LIST)
4570 /* concatenate Lists */
4571 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4572 &var3) == FAIL)
4574 clear_tv(rettv);
4575 clear_tv(&var2);
4576 return FAIL;
4578 clear_tv(rettv);
4579 *rettv = var3;
4581 else
4583 int error = FALSE;
4585 #ifdef FEAT_FLOAT
4586 if (rettv->v_type == VAR_FLOAT)
4588 f1 = rettv->vval.v_float;
4589 n1 = 0;
4591 else
4592 #endif
4594 n1 = get_tv_number_chk(rettv, &error);
4595 if (error)
4597 /* This can only happen for "list + non-list". For
4598 * "non-list + ..." or "something - ...", we returned
4599 * before evaluating the 2nd operand. */
4600 clear_tv(rettv);
4601 return FAIL;
4603 #ifdef FEAT_FLOAT
4604 if (var2.v_type == VAR_FLOAT)
4605 f1 = n1;
4606 #endif
4608 #ifdef FEAT_FLOAT
4609 if (var2.v_type == VAR_FLOAT)
4611 f2 = var2.vval.v_float;
4612 n2 = 0;
4614 else
4615 #endif
4617 n2 = get_tv_number_chk(&var2, &error);
4618 if (error)
4620 clear_tv(rettv);
4621 clear_tv(&var2);
4622 return FAIL;
4624 #ifdef FEAT_FLOAT
4625 if (rettv->v_type == VAR_FLOAT)
4626 f2 = n2;
4627 #endif
4629 clear_tv(rettv);
4631 #ifdef FEAT_FLOAT
4632 /* If there is a float on either side the result is a float. */
4633 if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4635 if (op == '+')
4636 f1 = f1 + f2;
4637 else
4638 f1 = f1 - f2;
4639 rettv->v_type = VAR_FLOAT;
4640 rettv->vval.v_float = f1;
4642 else
4643 #endif
4645 if (op == '+')
4646 n1 = n1 + n2;
4647 else
4648 n1 = n1 - n2;
4649 rettv->v_type = VAR_NUMBER;
4650 rettv->vval.v_number = n1;
4653 clear_tv(&var2);
4656 return OK;
4660 * Handle fifth level expression:
4661 * * number multiplication
4662 * / number division
4663 * % number modulo
4665 * "arg" must point to the first non-white of the expression.
4666 * "arg" is advanced to the next non-white after the recognized expression.
4668 * Return OK or FAIL.
4670 static int
4671 eval6(arg, rettv, evaluate, want_string)
4672 char_u **arg;
4673 typval_T *rettv;
4674 int evaluate;
4675 int want_string; /* after "." operator */
4677 typval_T var2;
4678 int op;
4679 long n1, n2;
4680 #ifdef FEAT_FLOAT
4681 int use_float = FALSE;
4682 float_T f1 = 0, f2;
4683 #endif
4684 int error = FALSE;
4687 * Get the first variable.
4689 if (eval7(arg, rettv, evaluate, want_string) == FAIL)
4690 return FAIL;
4693 * Repeat computing, until no '*', '/' or '%' is following.
4695 for (;;)
4697 op = **arg;
4698 if (op != '*' && op != '/' && op != '%')
4699 break;
4701 if (evaluate)
4703 #ifdef FEAT_FLOAT
4704 if (rettv->v_type == VAR_FLOAT)
4706 f1 = rettv->vval.v_float;
4707 use_float = TRUE;
4708 n1 = 0;
4710 else
4711 #endif
4712 n1 = get_tv_number_chk(rettv, &error);
4713 clear_tv(rettv);
4714 if (error)
4715 return FAIL;
4717 else
4718 n1 = 0;
4721 * Get the second variable.
4723 *arg = skipwhite(*arg + 1);
4724 if (eval7(arg, &var2, evaluate, FALSE) == FAIL)
4725 return FAIL;
4727 if (evaluate)
4729 #ifdef FEAT_FLOAT
4730 if (var2.v_type == VAR_FLOAT)
4732 if (!use_float)
4734 f1 = n1;
4735 use_float = TRUE;
4737 f2 = var2.vval.v_float;
4738 n2 = 0;
4740 else
4741 #endif
4743 n2 = get_tv_number_chk(&var2, &error);
4744 clear_tv(&var2);
4745 if (error)
4746 return FAIL;
4747 #ifdef FEAT_FLOAT
4748 if (use_float)
4749 f2 = n2;
4750 #endif
4754 * Compute the result.
4755 * When either side is a float the result is a float.
4757 #ifdef FEAT_FLOAT
4758 if (use_float)
4760 if (op == '*')
4761 f1 = f1 * f2;
4762 else if (op == '/')
4764 /* We rely on the floating point library to handle divide
4765 * by zero to result in "inf" and not a crash. */
4766 f1 = f1 / f2;
4768 else
4770 EMSG(_("E804: Cannot use '%' with Float"));
4771 return FAIL;
4773 rettv->v_type = VAR_FLOAT;
4774 rettv->vval.v_float = f1;
4776 else
4777 #endif
4779 if (op == '*')
4780 n1 = n1 * n2;
4781 else if (op == '/')
4783 if (n2 == 0) /* give an error message? */
4785 if (n1 == 0)
4786 n1 = -0x7fffffffL - 1L; /* similar to NaN */
4787 else if (n1 < 0)
4788 n1 = -0x7fffffffL;
4789 else
4790 n1 = 0x7fffffffL;
4792 else
4793 n1 = n1 / n2;
4795 else
4797 if (n2 == 0) /* give an error message? */
4798 n1 = 0;
4799 else
4800 n1 = n1 % n2;
4802 rettv->v_type = VAR_NUMBER;
4803 rettv->vval.v_number = n1;
4808 return OK;
4812 * Handle sixth level expression:
4813 * number number constant
4814 * "string" string constant
4815 * 'string' literal string constant
4816 * &option-name option value
4817 * @r register contents
4818 * identifier variable value
4819 * function() function call
4820 * $VAR environment variable
4821 * (expression) nested expression
4822 * [expr, expr] List
4823 * {key: val, key: val} Dictionary
4825 * Also handle:
4826 * ! in front logical NOT
4827 * - in front unary minus
4828 * + in front unary plus (ignored)
4829 * trailing [] subscript in String or List
4830 * trailing .name entry in Dictionary
4832 * "arg" must point to the first non-white of the expression.
4833 * "arg" is advanced to the next non-white after the recognized expression.
4835 * Return OK or FAIL.
4837 static int
4838 eval7(arg, rettv, evaluate, want_string)
4839 char_u **arg;
4840 typval_T *rettv;
4841 int evaluate;
4842 int want_string; /* after "." operator */
4844 long n;
4845 int len;
4846 char_u *s;
4847 char_u *start_leader, *end_leader;
4848 int ret = OK;
4849 char_u *alias;
4852 * Initialise variable so that clear_tv() can't mistake this for a
4853 * string and free a string that isn't there.
4855 rettv->v_type = VAR_UNKNOWN;
4858 * Skip '!' and '-' characters. They are handled later.
4860 start_leader = *arg;
4861 while (**arg == '!' || **arg == '-' || **arg == '+')
4862 *arg = skipwhite(*arg + 1);
4863 end_leader = *arg;
4865 switch (**arg)
4868 * Number constant.
4870 case '0':
4871 case '1':
4872 case '2':
4873 case '3':
4874 case '4':
4875 case '5':
4876 case '6':
4877 case '7':
4878 case '8':
4879 case '9':
4881 #ifdef FEAT_FLOAT
4882 char_u *p = skipdigits(*arg + 1);
4883 int get_float = FALSE;
4885 /* We accept a float when the format matches
4886 * "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?". This is very
4887 * strict to avoid backwards compatibility problems.
4888 * Don't look for a float after the "." operator, so that
4889 * ":let vers = 1.2.3" doesn't fail. */
4890 if (!want_string && p[0] == '.' && vim_isdigit(p[1]))
4892 get_float = TRUE;
4893 p = skipdigits(p + 2);
4894 if (*p == 'e' || *p == 'E')
4896 ++p;
4897 if (*p == '-' || *p == '+')
4898 ++p;
4899 if (!vim_isdigit(*p))
4900 get_float = FALSE;
4901 else
4902 p = skipdigits(p + 1);
4904 if (ASCII_ISALPHA(*p) || *p == '.')
4905 get_float = FALSE;
4907 if (get_float)
4909 float_T f;
4911 *arg += string2float(*arg, &f);
4912 if (evaluate)
4914 rettv->v_type = VAR_FLOAT;
4915 rettv->vval.v_float = f;
4918 else
4919 #endif
4921 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4922 *arg += len;
4923 if (evaluate)
4925 rettv->v_type = VAR_NUMBER;
4926 rettv->vval.v_number = n;
4929 break;
4933 * String constant: "string".
4935 case '"': ret = get_string_tv(arg, rettv, evaluate);
4936 break;
4939 * Literal string constant: 'str''ing'.
4941 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
4942 break;
4945 * List: [expr, expr]
4947 case '[': ret = get_list_tv(arg, rettv, evaluate);
4948 break;
4951 * Dictionary: {key: val, key: val}
4953 case '{': ret = get_dict_tv(arg, rettv, evaluate);
4954 break;
4957 * Option value: &name
4959 case '&': ret = get_option_tv(arg, rettv, evaluate);
4960 break;
4963 * Environment variable: $VAR.
4965 case '$': ret = get_env_tv(arg, rettv, evaluate);
4966 break;
4969 * Register contents: @r.
4971 case '@': ++*arg;
4972 if (evaluate)
4974 rettv->v_type = VAR_STRING;
4975 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4977 if (**arg != NUL)
4978 ++*arg;
4979 break;
4982 * nested expression: (expression).
4984 case '(': *arg = skipwhite(*arg + 1);
4985 ret = eval1(arg, rettv, evaluate); /* recursive! */
4986 if (**arg == ')')
4987 ++*arg;
4988 else if (ret == OK)
4990 EMSG(_("E110: Missing ')'"));
4991 clear_tv(rettv);
4992 ret = FAIL;
4994 break;
4996 default: ret = NOTDONE;
4997 break;
5000 if (ret == NOTDONE)
5003 * Must be a variable or function name.
5004 * Can also be a curly-braces kind of name: {expr}.
5006 s = *arg;
5007 len = get_name_len(arg, &alias, evaluate, TRUE);
5008 if (alias != NULL)
5009 s = alias;
5011 if (len <= 0)
5012 ret = FAIL;
5013 else
5015 if (**arg == '(') /* recursive! */
5017 /* If "s" is the name of a variable of type VAR_FUNC
5018 * use its contents. */
5019 s = deref_func_name(s, &len);
5021 /* Invoke the function. */
5022 ret = get_func_tv(s, len, rettv, arg,
5023 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
5024 &len, evaluate, NULL);
5025 /* Stop the expression evaluation when immediately
5026 * aborting on error, or when an interrupt occurred or
5027 * an exception was thrown but not caught. */
5028 if (aborting())
5030 if (ret == OK)
5031 clear_tv(rettv);
5032 ret = FAIL;
5035 else if (evaluate)
5036 ret = get_var_tv(s, len, rettv, TRUE);
5037 else
5038 ret = OK;
5041 if (alias != NULL)
5042 vim_free(alias);
5045 *arg = skipwhite(*arg);
5047 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
5048 * expr(expr). */
5049 if (ret == OK)
5050 ret = handle_subscript(arg, rettv, evaluate, TRUE);
5053 * Apply logical NOT and unary '-', from right to left, ignore '+'.
5055 if (ret == OK && evaluate && end_leader > start_leader)
5057 int error = FALSE;
5058 int val = 0;
5059 #ifdef FEAT_FLOAT
5060 float_T f = 0.0;
5062 if (rettv->v_type == VAR_FLOAT)
5063 f = rettv->vval.v_float;
5064 else
5065 #endif
5066 val = get_tv_number_chk(rettv, &error);
5067 if (error)
5069 clear_tv(rettv);
5070 ret = FAIL;
5072 else
5074 while (end_leader > start_leader)
5076 --end_leader;
5077 if (*end_leader == '!')
5079 #ifdef FEAT_FLOAT
5080 if (rettv->v_type == VAR_FLOAT)
5081 f = !f;
5082 else
5083 #endif
5084 val = !val;
5086 else if (*end_leader == '-')
5088 #ifdef FEAT_FLOAT
5089 if (rettv->v_type == VAR_FLOAT)
5090 f = -f;
5091 else
5092 #endif
5093 val = -val;
5096 #ifdef FEAT_FLOAT
5097 if (rettv->v_type == VAR_FLOAT)
5099 clear_tv(rettv);
5100 rettv->vval.v_float = f;
5102 else
5103 #endif
5105 clear_tv(rettv);
5106 rettv->v_type = VAR_NUMBER;
5107 rettv->vval.v_number = val;
5112 return ret;
5116 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
5117 * "*arg" points to the '[' or '.'.
5118 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
5120 static int
5121 eval_index(arg, rettv, evaluate, verbose)
5122 char_u **arg;
5123 typval_T *rettv;
5124 int evaluate;
5125 int verbose; /* give error messages */
5127 int empty1 = FALSE, empty2 = FALSE;
5128 typval_T var1, var2;
5129 long n1, n2 = 0;
5130 long len = -1;
5131 int range = FALSE;
5132 char_u *s;
5133 char_u *key = NULL;
5135 if (rettv->v_type == VAR_FUNC
5136 #ifdef FEAT_FLOAT
5137 || rettv->v_type == VAR_FLOAT
5138 #endif
5141 if (verbose)
5142 EMSG(_("E695: Cannot index a Funcref"));
5143 return FAIL;
5146 if (**arg == '.')
5149 * dict.name
5151 key = *arg + 1;
5152 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
5154 if (len == 0)
5155 return FAIL;
5156 *arg = skipwhite(key + len);
5158 else
5161 * something[idx]
5163 * Get the (first) variable from inside the [].
5165 *arg = skipwhite(*arg + 1);
5166 if (**arg == ':')
5167 empty1 = TRUE;
5168 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
5169 return FAIL;
5170 else if (evaluate && get_tv_string_chk(&var1) == NULL)
5172 /* not a number or string */
5173 clear_tv(&var1);
5174 return FAIL;
5178 * Get the second variable from inside the [:].
5180 if (**arg == ':')
5182 range = TRUE;
5183 *arg = skipwhite(*arg + 1);
5184 if (**arg == ']')
5185 empty2 = TRUE;
5186 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
5188 if (!empty1)
5189 clear_tv(&var1);
5190 return FAIL;
5192 else if (evaluate && get_tv_string_chk(&var2) == NULL)
5194 /* not a number or string */
5195 if (!empty1)
5196 clear_tv(&var1);
5197 clear_tv(&var2);
5198 return FAIL;
5202 /* Check for the ']'. */
5203 if (**arg != ']')
5205 if (verbose)
5206 EMSG(_(e_missbrac));
5207 clear_tv(&var1);
5208 if (range)
5209 clear_tv(&var2);
5210 return FAIL;
5212 *arg = skipwhite(*arg + 1); /* skip the ']' */
5215 if (evaluate)
5217 n1 = 0;
5218 if (!empty1 && rettv->v_type != VAR_DICT)
5220 n1 = get_tv_number(&var1);
5221 clear_tv(&var1);
5223 if (range)
5225 if (empty2)
5226 n2 = -1;
5227 else
5229 n2 = get_tv_number(&var2);
5230 clear_tv(&var2);
5234 switch (rettv->v_type)
5236 case VAR_NUMBER:
5237 case VAR_STRING:
5238 s = get_tv_string(rettv);
5239 len = (long)STRLEN(s);
5240 if (range)
5242 /* The resulting variable is a substring. If the indexes
5243 * are out of range the result is empty. */
5244 if (n1 < 0)
5246 n1 = len + n1;
5247 if (n1 < 0)
5248 n1 = 0;
5250 if (n2 < 0)
5251 n2 = len + n2;
5252 else if (n2 >= len)
5253 n2 = len;
5254 if (n1 >= len || n2 < 0 || n1 > n2)
5255 s = NULL;
5256 else
5257 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
5259 else
5261 /* The resulting variable is a string of a single
5262 * character. If the index is too big or negative the
5263 * result is empty. */
5264 if (n1 >= len || n1 < 0)
5265 s = NULL;
5266 else
5267 s = vim_strnsave(s + n1, 1);
5269 clear_tv(rettv);
5270 rettv->v_type = VAR_STRING;
5271 rettv->vval.v_string = s;
5272 break;
5274 case VAR_LIST:
5275 len = list_len(rettv->vval.v_list);
5276 if (n1 < 0)
5277 n1 = len + n1;
5278 if (!empty1 && (n1 < 0 || n1 >= len))
5280 /* For a range we allow invalid values and return an empty
5281 * list. A list index out of range is an error. */
5282 if (!range)
5284 if (verbose)
5285 EMSGN(_(e_listidx), n1);
5286 return FAIL;
5288 n1 = len;
5290 if (range)
5292 list_T *l;
5293 listitem_T *item;
5295 if (n2 < 0)
5296 n2 = len + n2;
5297 else if (n2 >= len)
5298 n2 = len - 1;
5299 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
5300 n2 = -1;
5301 l = list_alloc();
5302 if (l == NULL)
5303 return FAIL;
5304 for (item = list_find(rettv->vval.v_list, n1);
5305 n1 <= n2; ++n1)
5307 if (list_append_tv(l, &item->li_tv) == FAIL)
5309 list_free(l, TRUE);
5310 return FAIL;
5312 item = item->li_next;
5314 clear_tv(rettv);
5315 rettv->v_type = VAR_LIST;
5316 rettv->vval.v_list = l;
5317 ++l->lv_refcount;
5319 else
5321 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
5322 clear_tv(rettv);
5323 *rettv = var1;
5325 break;
5327 case VAR_DICT:
5328 if (range)
5330 if (verbose)
5331 EMSG(_(e_dictrange));
5332 if (len == -1)
5333 clear_tv(&var1);
5334 return FAIL;
5337 dictitem_T *item;
5339 if (len == -1)
5341 key = get_tv_string(&var1);
5342 if (*key == NUL)
5344 if (verbose)
5345 EMSG(_(e_emptykey));
5346 clear_tv(&var1);
5347 return FAIL;
5351 item = dict_find(rettv->vval.v_dict, key, (int)len);
5353 if (item == NULL && verbose)
5354 EMSG2(_(e_dictkey), key);
5355 if (len == -1)
5356 clear_tv(&var1);
5357 if (item == NULL)
5358 return FAIL;
5360 copy_tv(&item->di_tv, &var1);
5361 clear_tv(rettv);
5362 *rettv = var1;
5364 break;
5368 return OK;
5372 * Get an option value.
5373 * "arg" points to the '&' or '+' before the option name.
5374 * "arg" is advanced to character after the option name.
5375 * Return OK or FAIL.
5377 static int
5378 get_option_tv(arg, rettv, evaluate)
5379 char_u **arg;
5380 typval_T *rettv; /* when NULL, only check if option exists */
5381 int evaluate;
5383 char_u *option_end;
5384 long numval;
5385 char_u *stringval;
5386 int opt_type;
5387 int c;
5388 int working = (**arg == '+'); /* has("+option") */
5389 int ret = OK;
5390 int opt_flags;
5393 * Isolate the option name and find its value.
5395 option_end = find_option_end(arg, &opt_flags);
5396 if (option_end == NULL)
5398 if (rettv != NULL)
5399 EMSG2(_("E112: Option name missing: %s"), *arg);
5400 return FAIL;
5403 if (!evaluate)
5405 *arg = option_end;
5406 return OK;
5409 c = *option_end;
5410 *option_end = NUL;
5411 opt_type = get_option_value(*arg, &numval,
5412 rettv == NULL ? NULL : &stringval, opt_flags);
5414 if (opt_type == -3) /* invalid name */
5416 if (rettv != NULL)
5417 EMSG2(_("E113: Unknown option: %s"), *arg);
5418 ret = FAIL;
5420 else if (rettv != NULL)
5422 if (opt_type == -2) /* hidden string option */
5424 rettv->v_type = VAR_STRING;
5425 rettv->vval.v_string = NULL;
5427 else if (opt_type == -1) /* hidden number option */
5429 rettv->v_type = VAR_NUMBER;
5430 rettv->vval.v_number = 0;
5432 else if (opt_type == 1) /* number option */
5434 rettv->v_type = VAR_NUMBER;
5435 rettv->vval.v_number = numval;
5437 else /* string option */
5439 rettv->v_type = VAR_STRING;
5440 rettv->vval.v_string = stringval;
5443 else if (working && (opt_type == -2 || opt_type == -1))
5444 ret = FAIL;
5446 *option_end = c; /* put back for error messages */
5447 *arg = option_end;
5449 return ret;
5453 * Allocate a variable for a string constant.
5454 * Return OK or FAIL.
5456 static int
5457 get_string_tv(arg, rettv, evaluate)
5458 char_u **arg;
5459 typval_T *rettv;
5460 int evaluate;
5462 char_u *p;
5463 char_u *name;
5464 int extra = 0;
5467 * Find the end of the string, skipping backslashed characters.
5469 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5471 if (*p == '\\' && p[1] != NUL)
5473 ++p;
5474 /* A "\<x>" form occupies at least 4 characters, and produces up
5475 * to 6 characters: reserve space for 2 extra */
5476 if (*p == '<')
5477 extra += 2;
5481 if (*p != '"')
5483 EMSG2(_("E114: Missing quote: %s"), *arg);
5484 return FAIL;
5487 /* If only parsing, set *arg and return here */
5488 if (!evaluate)
5490 *arg = p + 1;
5491 return OK;
5495 * Copy the string into allocated memory, handling backslashed
5496 * characters.
5498 name = alloc((unsigned)(p - *arg + extra));
5499 if (name == NULL)
5500 return FAIL;
5501 rettv->v_type = VAR_STRING;
5502 rettv->vval.v_string = name;
5504 for (p = *arg + 1; *p != NUL && *p != '"'; )
5506 if (*p == '\\')
5508 switch (*++p)
5510 case 'b': *name++ = BS; ++p; break;
5511 case 'e': *name++ = ESC; ++p; break;
5512 case 'f': *name++ = FF; ++p; break;
5513 case 'n': *name++ = NL; ++p; break;
5514 case 'r': *name++ = CAR; ++p; break;
5515 case 't': *name++ = TAB; ++p; break;
5517 case 'X': /* hex: "\x1", "\x12" */
5518 case 'x':
5519 case 'u': /* Unicode: "\u0023" */
5520 case 'U':
5521 if (vim_isxdigit(p[1]))
5523 int n, nr;
5524 int c = toupper(*p);
5526 if (c == 'X')
5527 n = 2;
5528 else
5529 n = 4;
5530 nr = 0;
5531 while (--n >= 0 && vim_isxdigit(p[1]))
5533 ++p;
5534 nr = (nr << 4) + hex2nr(*p);
5536 ++p;
5537 #ifdef FEAT_MBYTE
5538 /* For "\u" store the number according to
5539 * 'encoding'. */
5540 if (c != 'X')
5541 name += (*mb_char2bytes)(nr, name);
5542 else
5543 #endif
5544 *name++ = nr;
5546 break;
5548 /* octal: "\1", "\12", "\123" */
5549 case '0':
5550 case '1':
5551 case '2':
5552 case '3':
5553 case '4':
5554 case '5':
5555 case '6':
5556 case '7': *name = *p++ - '0';
5557 if (*p >= '0' && *p <= '7')
5559 *name = (*name << 3) + *p++ - '0';
5560 if (*p >= '0' && *p <= '7')
5561 *name = (*name << 3) + *p++ - '0';
5563 ++name;
5564 break;
5566 /* Special key, e.g.: "\<C-W>" */
5567 case '<': extra = trans_special(&p, name, TRUE);
5568 if (extra != 0)
5570 name += extra;
5571 break;
5573 /* FALLTHROUGH */
5575 default: MB_COPY_CHAR(p, name);
5576 break;
5579 else
5580 MB_COPY_CHAR(p, name);
5583 *name = NUL;
5584 *arg = p + 1;
5586 return OK;
5590 * Allocate a variable for a 'str''ing' constant.
5591 * Return OK or FAIL.
5593 static int
5594 get_lit_string_tv(arg, rettv, evaluate)
5595 char_u **arg;
5596 typval_T *rettv;
5597 int evaluate;
5599 char_u *p;
5600 char_u *str;
5601 int reduce = 0;
5604 * Find the end of the string, skipping ''.
5606 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5608 if (*p == '\'')
5610 if (p[1] != '\'')
5611 break;
5612 ++reduce;
5613 ++p;
5617 if (*p != '\'')
5619 EMSG2(_("E115: Missing quote: %s"), *arg);
5620 return FAIL;
5623 /* If only parsing return after setting "*arg" */
5624 if (!evaluate)
5626 *arg = p + 1;
5627 return OK;
5631 * Copy the string into allocated memory, handling '' to ' reduction.
5633 str = alloc((unsigned)((p - *arg) - reduce));
5634 if (str == NULL)
5635 return FAIL;
5636 rettv->v_type = VAR_STRING;
5637 rettv->vval.v_string = str;
5639 for (p = *arg + 1; *p != NUL; )
5641 if (*p == '\'')
5643 if (p[1] != '\'')
5644 break;
5645 ++p;
5647 MB_COPY_CHAR(p, str);
5649 *str = NUL;
5650 *arg = p + 1;
5652 return OK;
5656 * Allocate a variable for a List and fill it from "*arg".
5657 * Return OK or FAIL.
5659 static int
5660 get_list_tv(arg, rettv, evaluate)
5661 char_u **arg;
5662 typval_T *rettv;
5663 int evaluate;
5665 list_T *l = NULL;
5666 typval_T tv;
5667 listitem_T *item;
5669 if (evaluate)
5671 l = list_alloc();
5672 if (l == NULL)
5673 return FAIL;
5676 *arg = skipwhite(*arg + 1);
5677 while (**arg != ']' && **arg != NUL)
5679 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5680 goto failret;
5681 if (evaluate)
5683 item = listitem_alloc();
5684 if (item != NULL)
5686 item->li_tv = tv;
5687 item->li_tv.v_lock = 0;
5688 list_append(l, item);
5690 else
5691 clear_tv(&tv);
5694 if (**arg == ']')
5695 break;
5696 if (**arg != ',')
5698 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5699 goto failret;
5701 *arg = skipwhite(*arg + 1);
5704 if (**arg != ']')
5706 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5707 failret:
5708 if (evaluate)
5709 list_free(l, TRUE);
5710 return FAIL;
5713 *arg = skipwhite(*arg + 1);
5714 if (evaluate)
5716 rettv->v_type = VAR_LIST;
5717 rettv->vval.v_list = l;
5718 ++l->lv_refcount;
5721 return OK;
5725 * Allocate an empty header for a list.
5726 * Caller should take care of the reference count.
5728 list_T *
5729 list_alloc()
5731 list_T *l;
5733 l = (list_T *)alloc_clear(sizeof(list_T));
5734 if (l != NULL)
5736 /* Prepend the list to the list of lists for garbage collection. */
5737 if (first_list != NULL)
5738 first_list->lv_used_prev = l;
5739 l->lv_used_prev = NULL;
5740 l->lv_used_next = first_list;
5741 first_list = l;
5743 return l;
5747 * Allocate an empty list for a return value.
5748 * Returns OK or FAIL.
5750 static int
5751 rettv_list_alloc(rettv)
5752 typval_T *rettv;
5754 list_T *l = list_alloc();
5756 if (l == NULL)
5757 return FAIL;
5759 rettv->vval.v_list = l;
5760 rettv->v_type = VAR_LIST;
5761 ++l->lv_refcount;
5762 return OK;
5766 * Unreference a list: decrement the reference count and free it when it
5767 * becomes zero.
5769 void
5770 list_unref(l)
5771 list_T *l;
5773 if (l != NULL && --l->lv_refcount <= 0)
5774 list_free(l, TRUE);
5778 * Free a list, including all items it points to.
5779 * Ignores the reference count.
5781 void
5782 list_free(l, recurse)
5783 list_T *l;
5784 int recurse; /* Free Lists and Dictionaries recursively. */
5786 listitem_T *item;
5788 /* Remove the list from the list of lists for garbage collection. */
5789 if (l->lv_used_prev == NULL)
5790 first_list = l->lv_used_next;
5791 else
5792 l->lv_used_prev->lv_used_next = l->lv_used_next;
5793 if (l->lv_used_next != NULL)
5794 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5796 for (item = l->lv_first; item != NULL; item = l->lv_first)
5798 /* Remove the item before deleting it. */
5799 l->lv_first = item->li_next;
5800 if (recurse || (item->li_tv.v_type != VAR_LIST
5801 && item->li_tv.v_type != VAR_DICT))
5802 clear_tv(&item->li_tv);
5803 vim_free(item);
5805 vim_free(l);
5809 * Allocate a list item.
5811 static listitem_T *
5812 listitem_alloc()
5814 return (listitem_T *)alloc(sizeof(listitem_T));
5818 * Free a list item. Also clears the value. Does not notify watchers.
5820 static void
5821 listitem_free(item)
5822 listitem_T *item;
5824 clear_tv(&item->li_tv);
5825 vim_free(item);
5829 * Remove a list item from a List and free it. Also clears the value.
5831 static void
5832 listitem_remove(l, item)
5833 list_T *l;
5834 listitem_T *item;
5836 list_remove(l, item, item);
5837 listitem_free(item);
5841 * Get the number of items in a list.
5843 static long
5844 list_len(l)
5845 list_T *l;
5847 if (l == NULL)
5848 return 0L;
5849 return l->lv_len;
5853 * Return TRUE when two lists have exactly the same values.
5855 static int
5856 list_equal(l1, l2, ic)
5857 list_T *l1;
5858 list_T *l2;
5859 int ic; /* ignore case for strings */
5861 listitem_T *item1, *item2;
5863 if (l1 == NULL || l2 == NULL)
5864 return FALSE;
5865 if (l1 == l2)
5866 return TRUE;
5867 if (list_len(l1) != list_len(l2))
5868 return FALSE;
5870 for (item1 = l1->lv_first, item2 = l2->lv_first;
5871 item1 != NULL && item2 != NULL;
5872 item1 = item1->li_next, item2 = item2->li_next)
5873 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5874 return FALSE;
5875 return item1 == NULL && item2 == NULL;
5878 #if defined(FEAT_RUBY) || defined(FEAT_PYTHON) || defined(FEAT_MZSCHEME) \
5879 || defined(PROTO)
5881 * Return the dictitem that an entry in a hashtable points to.
5883 dictitem_T *
5884 dict_lookup(hi)
5885 hashitem_T *hi;
5887 return HI2DI(hi);
5889 #endif
5892 * Return TRUE when two dictionaries have exactly the same key/values.
5894 static int
5895 dict_equal(d1, d2, ic)
5896 dict_T *d1;
5897 dict_T *d2;
5898 int ic; /* ignore case for strings */
5900 hashitem_T *hi;
5901 dictitem_T *item2;
5902 int todo;
5904 if (d1 == NULL || d2 == NULL)
5905 return FALSE;
5906 if (d1 == d2)
5907 return TRUE;
5908 if (dict_len(d1) != dict_len(d2))
5909 return FALSE;
5911 todo = (int)d1->dv_hashtab.ht_used;
5912 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5914 if (!HASHITEM_EMPTY(hi))
5916 item2 = dict_find(d2, hi->hi_key, -1);
5917 if (item2 == NULL)
5918 return FALSE;
5919 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5920 return FALSE;
5921 --todo;
5924 return TRUE;
5928 * Return TRUE if "tv1" and "tv2" have the same value.
5929 * Compares the items just like "==" would compare them, but strings and
5930 * numbers are different. Floats and numbers are also different.
5932 static int
5933 tv_equal(tv1, tv2, ic)
5934 typval_T *tv1;
5935 typval_T *tv2;
5936 int ic; /* ignore case */
5938 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5939 char_u *s1, *s2;
5940 static int recursive = 0; /* cach recursive loops */
5941 int r;
5943 if (tv1->v_type != tv2->v_type)
5944 return FALSE;
5945 /* Catch lists and dicts that have an endless loop by limiting
5946 * recursiveness to 1000. We guess they are equal then. */
5947 if (recursive >= 1000)
5948 return TRUE;
5950 switch (tv1->v_type)
5952 case VAR_LIST:
5953 ++recursive;
5954 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5955 --recursive;
5956 return r;
5958 case VAR_DICT:
5959 ++recursive;
5960 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5961 --recursive;
5962 return r;
5964 case VAR_FUNC:
5965 return (tv1->vval.v_string != NULL
5966 && tv2->vval.v_string != NULL
5967 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5969 case VAR_NUMBER:
5970 return tv1->vval.v_number == tv2->vval.v_number;
5972 #ifdef FEAT_FLOAT
5973 case VAR_FLOAT:
5974 return tv1->vval.v_float == tv2->vval.v_float;
5975 #endif
5977 case VAR_STRING:
5978 s1 = get_tv_string_buf(tv1, buf1);
5979 s2 = get_tv_string_buf(tv2, buf2);
5980 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5983 EMSG2(_(e_intern2), "tv_equal()");
5984 return TRUE;
5988 * Locate item with index "n" in list "l" and return it.
5989 * A negative index is counted from the end; -1 is the last item.
5990 * Returns NULL when "n" is out of range.
5992 static listitem_T *
5993 list_find(l, n)
5994 list_T *l;
5995 long n;
5997 listitem_T *item;
5998 long idx;
6000 if (l == NULL)
6001 return NULL;
6003 /* Negative index is relative to the end. */
6004 if (n < 0)
6005 n = l->lv_len + n;
6007 /* Check for index out of range. */
6008 if (n < 0 || n >= l->lv_len)
6009 return NULL;
6011 /* When there is a cached index may start search from there. */
6012 if (l->lv_idx_item != NULL)
6014 if (n < l->lv_idx / 2)
6016 /* closest to the start of the list */
6017 item = l->lv_first;
6018 idx = 0;
6020 else if (n > (l->lv_idx + l->lv_len) / 2)
6022 /* closest to the end of the list */
6023 item = l->lv_last;
6024 idx = l->lv_len - 1;
6026 else
6028 /* closest to the cached index */
6029 item = l->lv_idx_item;
6030 idx = l->lv_idx;
6033 else
6035 if (n < l->lv_len / 2)
6037 /* closest to the start of the list */
6038 item = l->lv_first;
6039 idx = 0;
6041 else
6043 /* closest to the end of the list */
6044 item = l->lv_last;
6045 idx = l->lv_len - 1;
6049 while (n > idx)
6051 /* search forward */
6052 item = item->li_next;
6053 ++idx;
6055 while (n < idx)
6057 /* search backward */
6058 item = item->li_prev;
6059 --idx;
6062 /* cache the used index */
6063 l->lv_idx = idx;
6064 l->lv_idx_item = item;
6066 return item;
6070 * Get list item "l[idx]" as a number.
6072 static long
6073 list_find_nr(l, idx, errorp)
6074 list_T *l;
6075 long idx;
6076 int *errorp; /* set to TRUE when something wrong */
6078 listitem_T *li;
6080 li = list_find(l, idx);
6081 if (li == NULL)
6083 if (errorp != NULL)
6084 *errorp = TRUE;
6085 return -1L;
6087 return get_tv_number_chk(&li->li_tv, errorp);
6091 * Get list item "l[idx - 1]" as a string. Returns NULL for failure.
6093 char_u *
6094 list_find_str(l, idx)
6095 list_T *l;
6096 long idx;
6098 listitem_T *li;
6100 li = list_find(l, idx - 1);
6101 if (li == NULL)
6103 EMSGN(_(e_listidx), idx);
6104 return NULL;
6106 return get_tv_string(&li->li_tv);
6110 * Locate "item" list "l" and return its index.
6111 * Returns -1 when "item" is not in the list.
6113 static long
6114 list_idx_of_item(l, item)
6115 list_T *l;
6116 listitem_T *item;
6118 long idx = 0;
6119 listitem_T *li;
6121 if (l == NULL)
6122 return -1;
6123 idx = 0;
6124 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
6125 ++idx;
6126 if (li == NULL)
6127 return -1;
6128 return idx;
6132 * Append item "item" to the end of list "l".
6134 static void
6135 list_append(l, item)
6136 list_T *l;
6137 listitem_T *item;
6139 if (l->lv_last == NULL)
6141 /* empty list */
6142 l->lv_first = item;
6143 l->lv_last = item;
6144 item->li_prev = NULL;
6146 else
6148 l->lv_last->li_next = item;
6149 item->li_prev = l->lv_last;
6150 l->lv_last = item;
6152 ++l->lv_len;
6153 item->li_next = NULL;
6157 * Append typval_T "tv" to the end of list "l".
6158 * Return FAIL when out of memory.
6161 list_append_tv(l, tv)
6162 list_T *l;
6163 typval_T *tv;
6165 listitem_T *li = listitem_alloc();
6167 if (li == NULL)
6168 return FAIL;
6169 copy_tv(tv, &li->li_tv);
6170 list_append(l, li);
6171 return OK;
6175 * Add a dictionary to a list. Used by getqflist().
6176 * Return FAIL when out of memory.
6179 list_append_dict(list, dict)
6180 list_T *list;
6181 dict_T *dict;
6183 listitem_T *li = listitem_alloc();
6185 if (li == NULL)
6186 return FAIL;
6187 li->li_tv.v_type = VAR_DICT;
6188 li->li_tv.v_lock = 0;
6189 li->li_tv.vval.v_dict = dict;
6190 list_append(list, li);
6191 ++dict->dv_refcount;
6192 return OK;
6196 * Make a copy of "str" and append it as an item to list "l".
6197 * When "len" >= 0 use "str[len]".
6198 * Returns FAIL when out of memory.
6201 list_append_string(l, str, len)
6202 list_T *l;
6203 char_u *str;
6204 int len;
6206 listitem_T *li = listitem_alloc();
6208 if (li == NULL)
6209 return FAIL;
6210 list_append(l, li);
6211 li->li_tv.v_type = VAR_STRING;
6212 li->li_tv.v_lock = 0;
6213 if (str == NULL)
6214 li->li_tv.vval.v_string = NULL;
6215 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
6216 : vim_strsave(str))) == NULL)
6217 return FAIL;
6218 return OK;
6222 * Append "n" to list "l".
6223 * Returns FAIL when out of memory.
6225 static int
6226 list_append_number(l, n)
6227 list_T *l;
6228 varnumber_T n;
6230 listitem_T *li;
6232 li = listitem_alloc();
6233 if (li == NULL)
6234 return FAIL;
6235 li->li_tv.v_type = VAR_NUMBER;
6236 li->li_tv.v_lock = 0;
6237 li->li_tv.vval.v_number = n;
6238 list_append(l, li);
6239 return OK;
6243 * Insert typval_T "tv" in list "l" before "item".
6244 * If "item" is NULL append at the end.
6245 * Return FAIL when out of memory.
6247 static int
6248 list_insert_tv(l, tv, item)
6249 list_T *l;
6250 typval_T *tv;
6251 listitem_T *item;
6253 listitem_T *ni = listitem_alloc();
6255 if (ni == NULL)
6256 return FAIL;
6257 copy_tv(tv, &ni->li_tv);
6258 if (item == NULL)
6259 /* Append new item at end of list. */
6260 list_append(l, ni);
6261 else
6263 /* Insert new item before existing item. */
6264 ni->li_prev = item->li_prev;
6265 ni->li_next = item;
6266 if (item->li_prev == NULL)
6268 l->lv_first = ni;
6269 ++l->lv_idx;
6271 else
6273 item->li_prev->li_next = ni;
6274 l->lv_idx_item = NULL;
6276 item->li_prev = ni;
6277 ++l->lv_len;
6279 return OK;
6283 * Extend "l1" with "l2".
6284 * If "bef" is NULL append at the end, otherwise insert before this item.
6285 * Returns FAIL when out of memory.
6287 static int
6288 list_extend(l1, l2, bef)
6289 list_T *l1;
6290 list_T *l2;
6291 listitem_T *bef;
6293 listitem_T *item;
6294 int todo = l2->lv_len;
6296 /* We also quit the loop when we have inserted the original item count of
6297 * the list, avoid a hang when we extend a list with itself. */
6298 for (item = l2->lv_first; item != NULL && --todo >= 0; item = item->li_next)
6299 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
6300 return FAIL;
6301 return OK;
6305 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
6306 * Return FAIL when out of memory.
6308 static int
6309 list_concat(l1, l2, tv)
6310 list_T *l1;
6311 list_T *l2;
6312 typval_T *tv;
6314 list_T *l;
6316 if (l1 == NULL || l2 == NULL)
6317 return FAIL;
6319 /* make a copy of the first list. */
6320 l = list_copy(l1, FALSE, 0);
6321 if (l == NULL)
6322 return FAIL;
6323 tv->v_type = VAR_LIST;
6324 tv->vval.v_list = l;
6326 /* append all items from the second list */
6327 return list_extend(l, l2, NULL);
6331 * Make a copy of list "orig". Shallow if "deep" is FALSE.
6332 * The refcount of the new list is set to 1.
6333 * See item_copy() for "copyID".
6334 * Returns NULL when out of memory.
6336 static list_T *
6337 list_copy(orig, deep, copyID)
6338 list_T *orig;
6339 int deep;
6340 int copyID;
6342 list_T *copy;
6343 listitem_T *item;
6344 listitem_T *ni;
6346 if (orig == NULL)
6347 return NULL;
6349 copy = list_alloc();
6350 if (copy != NULL)
6352 if (copyID != 0)
6354 /* Do this before adding the items, because one of the items may
6355 * refer back to this list. */
6356 orig->lv_copyID = copyID;
6357 orig->lv_copylist = copy;
6359 for (item = orig->lv_first; item != NULL && !got_int;
6360 item = item->li_next)
6362 ni = listitem_alloc();
6363 if (ni == NULL)
6364 break;
6365 if (deep)
6367 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
6369 vim_free(ni);
6370 break;
6373 else
6374 copy_tv(&item->li_tv, &ni->li_tv);
6375 list_append(copy, ni);
6377 ++copy->lv_refcount;
6378 if (item != NULL)
6380 list_unref(copy);
6381 copy = NULL;
6385 return copy;
6389 * Remove items "item" to "item2" from list "l".
6390 * Does not free the listitem or the value!
6392 static void
6393 list_remove(l, item, item2)
6394 list_T *l;
6395 listitem_T *item;
6396 listitem_T *item2;
6398 listitem_T *ip;
6400 /* notify watchers */
6401 for (ip = item; ip != NULL; ip = ip->li_next)
6403 --l->lv_len;
6404 list_fix_watch(l, ip);
6405 if (ip == item2)
6406 break;
6409 if (item2->li_next == NULL)
6410 l->lv_last = item->li_prev;
6411 else
6412 item2->li_next->li_prev = item->li_prev;
6413 if (item->li_prev == NULL)
6414 l->lv_first = item2->li_next;
6415 else
6416 item->li_prev->li_next = item2->li_next;
6417 l->lv_idx_item = NULL;
6421 * Return an allocated string with the string representation of a list.
6422 * May return NULL.
6424 static char_u *
6425 list2string(tv, copyID)
6426 typval_T *tv;
6427 int copyID;
6429 garray_T ga;
6431 if (tv->vval.v_list == NULL)
6432 return NULL;
6433 ga_init2(&ga, (int)sizeof(char), 80);
6434 ga_append(&ga, '[');
6435 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6437 vim_free(ga.ga_data);
6438 return NULL;
6440 ga_append(&ga, ']');
6441 ga_append(&ga, NUL);
6442 return (char_u *)ga.ga_data;
6446 * Join list "l" into a string in "*gap", using separator "sep".
6447 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6448 * Return FAIL or OK.
6450 static int
6451 list_join(gap, l, sep, echo, copyID)
6452 garray_T *gap;
6453 list_T *l;
6454 char_u *sep;
6455 int echo;
6456 int copyID;
6458 int first = TRUE;
6459 char_u *tofree;
6460 char_u numbuf[NUMBUFLEN];
6461 listitem_T *item;
6462 char_u *s;
6464 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6466 if (first)
6467 first = FALSE;
6468 else
6469 ga_concat(gap, sep);
6471 if (echo)
6472 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6473 else
6474 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6475 if (s != NULL)
6476 ga_concat(gap, s);
6477 vim_free(tofree);
6478 if (s == NULL)
6479 return FAIL;
6480 line_breakcheck();
6482 return OK;
6486 * Garbage collection for lists and dictionaries.
6488 * We use reference counts to be able to free most items right away when they
6489 * are no longer used. But for composite items it's possible that it becomes
6490 * unused while the reference count is > 0: When there is a recursive
6491 * reference. Example:
6492 * :let l = [1, 2, 3]
6493 * :let d = {9: l}
6494 * :let l[1] = d
6496 * Since this is quite unusual we handle this with garbage collection: every
6497 * once in a while find out which lists and dicts are not referenced from any
6498 * variable.
6500 * Here is a good reference text about garbage collection (refers to Python
6501 * but it applies to all reference-counting mechanisms):
6502 * http://python.ca/nas/python/gc/
6506 * Do garbage collection for lists and dicts.
6507 * Return TRUE if some memory was freed.
6510 garbage_collect()
6512 int copyID;
6513 buf_T *buf;
6514 win_T *wp;
6515 int i;
6516 funccall_T *fc, **pfc;
6517 int did_free;
6518 int did_free_funccal = FALSE;
6519 #ifdef FEAT_WINDOWS
6520 tabpage_T *tp;
6521 #endif
6523 /* Only do this once. */
6524 want_garbage_collect = FALSE;
6525 may_garbage_collect = FALSE;
6526 garbage_collect_at_exit = FALSE;
6528 /* We advance by two because we add one for items referenced through
6529 * previous_funccal. */
6530 current_copyID += COPYID_INC;
6531 copyID = current_copyID;
6534 * 1. Go through all accessible variables and mark all lists and dicts
6535 * with copyID.
6538 /* Don't free variables in the previous_funccal list unless they are only
6539 * referenced through previous_funccal. This must be first, because if
6540 * the item is referenced elsewhere the funccal must not be freed. */
6541 for (fc = previous_funccal; fc != NULL; fc = fc->caller)
6543 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1);
6544 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1);
6547 /* script-local variables */
6548 for (i = 1; i <= ga_scripts.ga_len; ++i)
6549 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6551 /* buffer-local variables */
6552 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6553 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6555 /* window-local variables */
6556 FOR_ALL_TAB_WINDOWS(tp, wp)
6557 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6559 #ifdef FEAT_WINDOWS
6560 /* tabpage-local variables */
6561 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6562 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6563 #endif
6565 /* global variables */
6566 set_ref_in_ht(&globvarht, copyID);
6568 /* function-local variables */
6569 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6571 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6572 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6575 /* v: vars */
6576 set_ref_in_ht(&vimvarht, copyID);
6579 * 2. Free lists and dictionaries that are not referenced.
6581 did_free = free_unref_items(copyID);
6584 * 3. Check if any funccal can be freed now.
6586 for (pfc = &previous_funccal; *pfc != NULL; )
6588 if (can_free_funccal(*pfc, copyID))
6590 fc = *pfc;
6591 *pfc = fc->caller;
6592 free_funccal(fc, TRUE);
6593 did_free = TRUE;
6594 did_free_funccal = TRUE;
6596 else
6597 pfc = &(*pfc)->caller;
6599 if (did_free_funccal)
6600 /* When a funccal was freed some more items might be garbage
6601 * collected, so run again. */
6602 (void)garbage_collect();
6604 return did_free;
6608 * Free lists and dictionaries that are no longer referenced.
6610 static int
6611 free_unref_items(copyID)
6612 int copyID;
6614 dict_T *dd;
6615 list_T *ll;
6616 int did_free = FALSE;
6619 * Go through the list of dicts and free items without the copyID.
6621 for (dd = first_dict; dd != NULL; )
6622 if ((dd->dv_copyID & COPYID_MASK) != (copyID & COPYID_MASK))
6624 /* Free the Dictionary and ordinary items it contains, but don't
6625 * recurse into Lists and Dictionaries, they will be in the list
6626 * of dicts or list of lists. */
6627 dict_free(dd, FALSE);
6628 did_free = TRUE;
6630 /* restart, next dict may also have been freed */
6631 dd = first_dict;
6633 else
6634 dd = dd->dv_used_next;
6637 * Go through the list of lists and free items without the copyID.
6638 * But don't free a list that has a watcher (used in a for loop), these
6639 * are not referenced anywhere.
6641 for (ll = first_list; ll != NULL; )
6642 if ((ll->lv_copyID & COPYID_MASK) != (copyID & COPYID_MASK)
6643 && ll->lv_watch == NULL)
6645 /* Free the List and ordinary items it contains, but don't recurse
6646 * into Lists and Dictionaries, they will be in the list of dicts
6647 * or list of lists. */
6648 list_free(ll, FALSE);
6649 did_free = TRUE;
6651 /* restart, next list may also have been freed */
6652 ll = first_list;
6654 else
6655 ll = ll->lv_used_next;
6657 return did_free;
6661 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6663 static void
6664 set_ref_in_ht(ht, copyID)
6665 hashtab_T *ht;
6666 int copyID;
6668 int todo;
6669 hashitem_T *hi;
6671 todo = (int)ht->ht_used;
6672 for (hi = ht->ht_array; todo > 0; ++hi)
6673 if (!HASHITEM_EMPTY(hi))
6675 --todo;
6676 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6681 * Mark all lists and dicts referenced through list "l" with "copyID".
6683 static void
6684 set_ref_in_list(l, copyID)
6685 list_T *l;
6686 int copyID;
6688 listitem_T *li;
6690 for (li = l->lv_first; li != NULL; li = li->li_next)
6691 set_ref_in_item(&li->li_tv, copyID);
6695 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6697 static void
6698 set_ref_in_item(tv, copyID)
6699 typval_T *tv;
6700 int copyID;
6702 dict_T *dd;
6703 list_T *ll;
6705 switch (tv->v_type)
6707 case VAR_DICT:
6708 dd = tv->vval.v_dict;
6709 if (dd != NULL && dd->dv_copyID != copyID)
6711 /* Didn't see this dict yet. */
6712 dd->dv_copyID = copyID;
6713 set_ref_in_ht(&dd->dv_hashtab, copyID);
6715 break;
6717 case VAR_LIST:
6718 ll = tv->vval.v_list;
6719 if (ll != NULL && ll->lv_copyID != copyID)
6721 /* Didn't see this list yet. */
6722 ll->lv_copyID = copyID;
6723 set_ref_in_list(ll, copyID);
6725 break;
6727 return;
6731 * Allocate an empty header for a dictionary.
6733 dict_T *
6734 dict_alloc()
6736 dict_T *d;
6738 d = (dict_T *)alloc(sizeof(dict_T));
6739 if (d != NULL)
6741 /* Add the list to the list of dicts for garbage collection. */
6742 if (first_dict != NULL)
6743 first_dict->dv_used_prev = d;
6744 d->dv_used_next = first_dict;
6745 d->dv_used_prev = NULL;
6746 first_dict = d;
6748 hash_init(&d->dv_hashtab);
6749 d->dv_lock = 0;
6750 d->dv_refcount = 0;
6751 d->dv_copyID = 0;
6753 return d;
6757 * Unreference a Dictionary: decrement the reference count and free it when it
6758 * becomes zero.
6760 static void
6761 dict_unref(d)
6762 dict_T *d;
6764 if (d != NULL && --d->dv_refcount <= 0)
6765 dict_free(d, TRUE);
6769 * Free a Dictionary, including all items it contains.
6770 * Ignores the reference count.
6772 static void
6773 dict_free(d, recurse)
6774 dict_T *d;
6775 int recurse; /* Free Lists and Dictionaries recursively. */
6777 int todo;
6778 hashitem_T *hi;
6779 dictitem_T *di;
6781 /* Remove the dict from the list of dicts for garbage collection. */
6782 if (d->dv_used_prev == NULL)
6783 first_dict = d->dv_used_next;
6784 else
6785 d->dv_used_prev->dv_used_next = d->dv_used_next;
6786 if (d->dv_used_next != NULL)
6787 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6789 /* Lock the hashtab, we don't want it to resize while freeing items. */
6790 hash_lock(&d->dv_hashtab);
6791 todo = (int)d->dv_hashtab.ht_used;
6792 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6794 if (!HASHITEM_EMPTY(hi))
6796 /* Remove the item before deleting it, just in case there is
6797 * something recursive causing trouble. */
6798 di = HI2DI(hi);
6799 hash_remove(&d->dv_hashtab, hi);
6800 if (recurse || (di->di_tv.v_type != VAR_LIST
6801 && di->di_tv.v_type != VAR_DICT))
6802 clear_tv(&di->di_tv);
6803 vim_free(di);
6804 --todo;
6807 hash_clear(&d->dv_hashtab);
6808 vim_free(d);
6812 * Allocate a Dictionary item.
6813 * The "key" is copied to the new item.
6814 * Note that the value of the item "di_tv" still needs to be initialized!
6815 * Returns NULL when out of memory.
6817 dictitem_T *
6818 dictitem_alloc(key)
6819 char_u *key;
6821 dictitem_T *di;
6823 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6824 if (di != NULL)
6826 STRCPY(di->di_key, key);
6827 di->di_flags = 0;
6829 return di;
6833 * Make a copy of a Dictionary item.
6835 static dictitem_T *
6836 dictitem_copy(org)
6837 dictitem_T *org;
6839 dictitem_T *di;
6841 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6842 + STRLEN(org->di_key)));
6843 if (di != NULL)
6845 STRCPY(di->di_key, org->di_key);
6846 di->di_flags = 0;
6847 copy_tv(&org->di_tv, &di->di_tv);
6849 return di;
6853 * Remove item "item" from Dictionary "dict" and free it.
6855 static void
6856 dictitem_remove(dict, item)
6857 dict_T *dict;
6858 dictitem_T *item;
6860 hashitem_T *hi;
6862 hi = hash_find(&dict->dv_hashtab, item->di_key);
6863 if (HASHITEM_EMPTY(hi))
6864 EMSG2(_(e_intern2), "dictitem_remove()");
6865 else
6866 hash_remove(&dict->dv_hashtab, hi);
6867 dictitem_free(item);
6871 * Free a dict item. Also clears the value.
6873 void
6874 dictitem_free(item)
6875 dictitem_T *item;
6877 clear_tv(&item->di_tv);
6878 vim_free(item);
6882 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6883 * The refcount of the new dict is set to 1.
6884 * See item_copy() for "copyID".
6885 * Returns NULL when out of memory.
6887 static dict_T *
6888 dict_copy(orig, deep, copyID)
6889 dict_T *orig;
6890 int deep;
6891 int copyID;
6893 dict_T *copy;
6894 dictitem_T *di;
6895 int todo;
6896 hashitem_T *hi;
6898 if (orig == NULL)
6899 return NULL;
6901 copy = dict_alloc();
6902 if (copy != NULL)
6904 if (copyID != 0)
6906 orig->dv_copyID = copyID;
6907 orig->dv_copydict = copy;
6909 todo = (int)orig->dv_hashtab.ht_used;
6910 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6912 if (!HASHITEM_EMPTY(hi))
6914 --todo;
6916 di = dictitem_alloc(hi->hi_key);
6917 if (di == NULL)
6918 break;
6919 if (deep)
6921 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6922 copyID) == FAIL)
6924 vim_free(di);
6925 break;
6928 else
6929 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6930 if (dict_add(copy, di) == FAIL)
6932 dictitem_free(di);
6933 break;
6938 ++copy->dv_refcount;
6939 if (todo > 0)
6941 dict_unref(copy);
6942 copy = NULL;
6946 return copy;
6950 * Add item "item" to Dictionary "d".
6951 * Returns FAIL when out of memory and when key already existed.
6954 dict_add(d, item)
6955 dict_T *d;
6956 dictitem_T *item;
6958 return hash_add(&d->dv_hashtab, item->di_key);
6962 * Add a number or string entry to dictionary "d".
6963 * When "str" is NULL use number "nr", otherwise use "str".
6964 * Returns FAIL when out of memory and when key already exists.
6967 dict_add_nr_str(d, key, nr, str)
6968 dict_T *d;
6969 char *key;
6970 long nr;
6971 char_u *str;
6973 dictitem_T *item;
6975 item = dictitem_alloc((char_u *)key);
6976 if (item == NULL)
6977 return FAIL;
6978 item->di_tv.v_lock = 0;
6979 if (str == NULL)
6981 item->di_tv.v_type = VAR_NUMBER;
6982 item->di_tv.vval.v_number = nr;
6984 else
6986 item->di_tv.v_type = VAR_STRING;
6987 item->di_tv.vval.v_string = vim_strsave(str);
6989 if (dict_add(d, item) == FAIL)
6991 dictitem_free(item);
6992 return FAIL;
6994 return OK;
6998 * Get the number of items in a Dictionary.
7000 static long
7001 dict_len(d)
7002 dict_T *d;
7004 if (d == NULL)
7005 return 0L;
7006 return (long)d->dv_hashtab.ht_used;
7010 * Find item "key[len]" in Dictionary "d".
7011 * If "len" is negative use strlen(key).
7012 * Returns NULL when not found.
7014 dictitem_T *
7015 dict_find(d, key, len)
7016 dict_T *d;
7017 char_u *key;
7018 int len;
7020 #define AKEYLEN 200
7021 char_u buf[AKEYLEN];
7022 char_u *akey;
7023 char_u *tofree = NULL;
7024 hashitem_T *hi;
7026 if (len < 0)
7027 akey = key;
7028 else if (len >= AKEYLEN)
7030 tofree = akey = vim_strnsave(key, len);
7031 if (akey == NULL)
7032 return NULL;
7034 else
7036 /* Avoid a malloc/free by using buf[]. */
7037 vim_strncpy(buf, key, len);
7038 akey = buf;
7041 hi = hash_find(&d->dv_hashtab, akey);
7042 vim_free(tofree);
7043 if (HASHITEM_EMPTY(hi))
7044 return NULL;
7045 return HI2DI(hi);
7049 * Get a string item from a dictionary.
7050 * When "save" is TRUE allocate memory for it.
7051 * Returns NULL if the entry doesn't exist or out of memory.
7053 char_u *
7054 get_dict_string(d, key, save)
7055 dict_T *d;
7056 char_u *key;
7057 int save;
7059 dictitem_T *di;
7060 char_u *s;
7062 di = dict_find(d, key, -1);
7063 if (di == NULL)
7064 return NULL;
7065 s = get_tv_string(&di->di_tv);
7066 if (save && s != NULL)
7067 s = vim_strsave(s);
7068 return s;
7072 * Get a number item from a dictionary.
7073 * Returns 0 if the entry doesn't exist or out of memory.
7075 long
7076 get_dict_number(d, key)
7077 dict_T *d;
7078 char_u *key;
7080 dictitem_T *di;
7082 di = dict_find(d, key, -1);
7083 if (di == NULL)
7084 return 0;
7085 return get_tv_number(&di->di_tv);
7089 * Return an allocated string with the string representation of a Dictionary.
7090 * May return NULL.
7092 static char_u *
7093 dict2string(tv, copyID)
7094 typval_T *tv;
7095 int copyID;
7097 garray_T ga;
7098 int first = TRUE;
7099 char_u *tofree;
7100 char_u numbuf[NUMBUFLEN];
7101 hashitem_T *hi;
7102 char_u *s;
7103 dict_T *d;
7104 int todo;
7106 if ((d = tv->vval.v_dict) == NULL)
7107 return NULL;
7108 ga_init2(&ga, (int)sizeof(char), 80);
7109 ga_append(&ga, '{');
7111 todo = (int)d->dv_hashtab.ht_used;
7112 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
7114 if (!HASHITEM_EMPTY(hi))
7116 --todo;
7118 if (first)
7119 first = FALSE;
7120 else
7121 ga_concat(&ga, (char_u *)", ");
7123 tofree = string_quote(hi->hi_key, FALSE);
7124 if (tofree != NULL)
7126 ga_concat(&ga, tofree);
7127 vim_free(tofree);
7129 ga_concat(&ga, (char_u *)": ");
7130 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
7131 if (s != NULL)
7132 ga_concat(&ga, s);
7133 vim_free(tofree);
7134 if (s == NULL)
7135 break;
7138 if (todo > 0)
7140 vim_free(ga.ga_data);
7141 return NULL;
7144 ga_append(&ga, '}');
7145 ga_append(&ga, NUL);
7146 return (char_u *)ga.ga_data;
7150 * Allocate a variable for a Dictionary and fill it from "*arg".
7151 * Return OK or FAIL. Returns NOTDONE for {expr}.
7153 static int
7154 get_dict_tv(arg, rettv, evaluate)
7155 char_u **arg;
7156 typval_T *rettv;
7157 int evaluate;
7159 dict_T *d = NULL;
7160 typval_T tvkey;
7161 typval_T tv;
7162 char_u *key = NULL;
7163 dictitem_T *item;
7164 char_u *start = skipwhite(*arg + 1);
7165 char_u buf[NUMBUFLEN];
7168 * First check if it's not a curly-braces thing: {expr}.
7169 * Must do this without evaluating, otherwise a function may be called
7170 * twice. Unfortunately this means we need to call eval1() twice for the
7171 * first item.
7172 * But {} is an empty Dictionary.
7174 if (*start != '}')
7176 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
7177 return FAIL;
7178 if (*start == '}')
7179 return NOTDONE;
7182 if (evaluate)
7184 d = dict_alloc();
7185 if (d == NULL)
7186 return FAIL;
7188 tvkey.v_type = VAR_UNKNOWN;
7189 tv.v_type = VAR_UNKNOWN;
7191 *arg = skipwhite(*arg + 1);
7192 while (**arg != '}' && **arg != NUL)
7194 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
7195 goto failret;
7196 if (**arg != ':')
7198 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
7199 clear_tv(&tvkey);
7200 goto failret;
7202 if (evaluate)
7204 key = get_tv_string_buf_chk(&tvkey, buf);
7205 if (key == NULL || *key == NUL)
7207 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
7208 if (key != NULL)
7209 EMSG(_(e_emptykey));
7210 clear_tv(&tvkey);
7211 goto failret;
7215 *arg = skipwhite(*arg + 1);
7216 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
7218 if (evaluate)
7219 clear_tv(&tvkey);
7220 goto failret;
7222 if (evaluate)
7224 item = dict_find(d, key, -1);
7225 if (item != NULL)
7227 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
7228 clear_tv(&tvkey);
7229 clear_tv(&tv);
7230 goto failret;
7232 item = dictitem_alloc(key);
7233 clear_tv(&tvkey);
7234 if (item != NULL)
7236 item->di_tv = tv;
7237 item->di_tv.v_lock = 0;
7238 if (dict_add(d, item) == FAIL)
7239 dictitem_free(item);
7243 if (**arg == '}')
7244 break;
7245 if (**arg != ',')
7247 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
7248 goto failret;
7250 *arg = skipwhite(*arg + 1);
7253 if (**arg != '}')
7255 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
7256 failret:
7257 if (evaluate)
7258 dict_free(d, TRUE);
7259 return FAIL;
7262 *arg = skipwhite(*arg + 1);
7263 if (evaluate)
7265 rettv->v_type = VAR_DICT;
7266 rettv->vval.v_dict = d;
7267 ++d->dv_refcount;
7270 return OK;
7274 * Return a string with the string representation of a variable.
7275 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7276 * "numbuf" is used for a number.
7277 * Does not put quotes around strings, as ":echo" displays values.
7278 * When "copyID" is not NULL replace recursive lists and dicts with "...".
7279 * May return NULL.
7281 static char_u *
7282 echo_string(tv, tofree, numbuf, copyID)
7283 typval_T *tv;
7284 char_u **tofree;
7285 char_u *numbuf;
7286 int copyID;
7288 static int recurse = 0;
7289 char_u *r = NULL;
7291 if (recurse >= DICT_MAXNEST)
7293 EMSG(_("E724: variable nested too deep for displaying"));
7294 *tofree = NULL;
7295 return NULL;
7297 ++recurse;
7299 switch (tv->v_type)
7301 case VAR_FUNC:
7302 *tofree = NULL;
7303 r = tv->vval.v_string;
7304 break;
7306 case VAR_LIST:
7307 if (tv->vval.v_list == NULL)
7309 *tofree = NULL;
7310 r = NULL;
7312 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
7314 *tofree = NULL;
7315 r = (char_u *)"[...]";
7317 else
7319 tv->vval.v_list->lv_copyID = copyID;
7320 *tofree = list2string(tv, copyID);
7321 r = *tofree;
7323 break;
7325 case VAR_DICT:
7326 if (tv->vval.v_dict == NULL)
7328 *tofree = NULL;
7329 r = NULL;
7331 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
7333 *tofree = NULL;
7334 r = (char_u *)"{...}";
7336 else
7338 tv->vval.v_dict->dv_copyID = copyID;
7339 *tofree = dict2string(tv, copyID);
7340 r = *tofree;
7342 break;
7344 case VAR_STRING:
7345 case VAR_NUMBER:
7346 *tofree = NULL;
7347 r = get_tv_string_buf(tv, numbuf);
7348 break;
7350 #ifdef FEAT_FLOAT
7351 case VAR_FLOAT:
7352 *tofree = NULL;
7353 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
7354 r = numbuf;
7355 break;
7356 #endif
7358 default:
7359 EMSG2(_(e_intern2), "echo_string()");
7360 *tofree = NULL;
7363 --recurse;
7364 return r;
7368 * Return a string with the string representation of a variable.
7369 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7370 * "numbuf" is used for a number.
7371 * Puts quotes around strings, so that they can be parsed back by eval().
7372 * May return NULL.
7374 static char_u *
7375 tv2string(tv, tofree, numbuf, copyID)
7376 typval_T *tv;
7377 char_u **tofree;
7378 char_u *numbuf;
7379 int copyID;
7381 switch (tv->v_type)
7383 case VAR_FUNC:
7384 *tofree = string_quote(tv->vval.v_string, TRUE);
7385 return *tofree;
7386 case VAR_STRING:
7387 *tofree = string_quote(tv->vval.v_string, FALSE);
7388 return *tofree;
7389 #ifdef FEAT_FLOAT
7390 case VAR_FLOAT:
7391 *tofree = NULL;
7392 vim_snprintf((char *)numbuf, NUMBUFLEN - 1, "%g", tv->vval.v_float);
7393 return numbuf;
7394 #endif
7395 case VAR_NUMBER:
7396 case VAR_LIST:
7397 case VAR_DICT:
7398 break;
7399 default:
7400 EMSG2(_(e_intern2), "tv2string()");
7402 return echo_string(tv, tofree, numbuf, copyID);
7406 * Return string "str" in ' quotes, doubling ' characters.
7407 * If "str" is NULL an empty string is assumed.
7408 * If "function" is TRUE make it function('string').
7410 static char_u *
7411 string_quote(str, function)
7412 char_u *str;
7413 int function;
7415 unsigned len;
7416 char_u *p, *r, *s;
7418 len = (function ? 13 : 3);
7419 if (str != NULL)
7421 len += (unsigned)STRLEN(str);
7422 for (p = str; *p != NUL; mb_ptr_adv(p))
7423 if (*p == '\'')
7424 ++len;
7426 s = r = alloc(len);
7427 if (r != NULL)
7429 if (function)
7431 STRCPY(r, "function('");
7432 r += 10;
7434 else
7435 *r++ = '\'';
7436 if (str != NULL)
7437 for (p = str; *p != NUL; )
7439 if (*p == '\'')
7440 *r++ = '\'';
7441 MB_COPY_CHAR(p, r);
7443 *r++ = '\'';
7444 if (function)
7445 *r++ = ')';
7446 *r++ = NUL;
7448 return s;
7451 #ifdef FEAT_FLOAT
7453 * Convert the string "text" to a floating point number.
7454 * This uses strtod(). setlocale(LC_NUMERIC, "C") has been used to make sure
7455 * this always uses a decimal point.
7456 * Returns the length of the text that was consumed.
7458 static int
7459 string2float(text, value)
7460 char_u *text;
7461 float_T *value; /* result stored here */
7463 char *s = (char *)text;
7464 float_T f;
7466 f = strtod(s, &s);
7467 *value = f;
7468 return (int)((char_u *)s - text);
7470 #endif
7473 * Get the value of an environment variable.
7474 * "arg" is pointing to the '$'. It is advanced to after the name.
7475 * If the environment variable was not set, silently assume it is empty.
7476 * Always return OK.
7478 static int
7479 get_env_tv(arg, rettv, evaluate)
7480 char_u **arg;
7481 typval_T *rettv;
7482 int evaluate;
7484 char_u *string = NULL;
7485 int len;
7486 int cc;
7487 char_u *name;
7488 int mustfree = FALSE;
7490 ++*arg;
7491 name = *arg;
7492 len = get_env_len(arg);
7493 if (evaluate)
7495 if (len != 0)
7497 cc = name[len];
7498 name[len] = NUL;
7499 /* first try vim_getenv(), fast for normal environment vars */
7500 string = vim_getenv(name, &mustfree);
7501 if (string != NULL && *string != NUL)
7503 if (!mustfree)
7504 string = vim_strsave(string);
7506 else
7508 if (mustfree)
7509 vim_free(string);
7511 /* next try expanding things like $VIM and ${HOME} */
7512 string = expand_env_save(name - 1);
7513 if (string != NULL && *string == '$')
7515 vim_free(string);
7516 string = NULL;
7519 name[len] = cc;
7521 rettv->v_type = VAR_STRING;
7522 rettv->vval.v_string = string;
7525 return OK;
7529 * Array with names and number of arguments of all internal functions
7530 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7532 static struct fst
7534 char *f_name; /* function name */
7535 char f_min_argc; /* minimal number of arguments */
7536 char f_max_argc; /* maximal number of arguments */
7537 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7538 /* implementation of function */
7539 } functions[] =
7541 #ifdef FEAT_FLOAT
7542 {"abs", 1, 1, f_abs},
7543 #endif
7544 {"add", 2, 2, f_add},
7545 {"append", 2, 2, f_append},
7546 {"argc", 0, 0, f_argc},
7547 {"argidx", 0, 0, f_argidx},
7548 {"argv", 0, 1, f_argv},
7549 #ifdef FEAT_FLOAT
7550 {"atan", 1, 1, f_atan},
7551 #endif
7552 {"browse", 4, 4, f_browse},
7553 {"browsedir", 2, 2, f_browsedir},
7554 {"bufexists", 1, 1, f_bufexists},
7555 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7556 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7557 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7558 {"buflisted", 1, 1, f_buflisted},
7559 {"bufloaded", 1, 1, f_bufloaded},
7560 {"bufname", 1, 1, f_bufname},
7561 {"bufnr", 1, 2, f_bufnr},
7562 {"bufwinnr", 1, 1, f_bufwinnr},
7563 {"byte2line", 1, 1, f_byte2line},
7564 {"byteidx", 2, 2, f_byteidx},
7565 {"call", 2, 3, f_call},
7566 #ifdef FEAT_FLOAT
7567 {"ceil", 1, 1, f_ceil},
7568 #endif
7569 {"changenr", 0, 0, f_changenr},
7570 {"char2nr", 1, 1, f_char2nr},
7571 {"cindent", 1, 1, f_cindent},
7572 {"clearmatches", 0, 0, f_clearmatches},
7573 {"col", 1, 1, f_col},
7574 #if defined(FEAT_INS_EXPAND)
7575 {"complete", 2, 2, f_complete},
7576 {"complete_add", 1, 1, f_complete_add},
7577 {"complete_check", 0, 0, f_complete_check},
7578 #endif
7579 {"confirm", 1, 4, f_confirm},
7580 {"copy", 1, 1, f_copy},
7581 #ifdef FEAT_FLOAT
7582 {"cos", 1, 1, f_cos},
7583 #endif
7584 {"count", 2, 4, f_count},
7585 {"cscope_connection",0,3, f_cscope_connection},
7586 {"cursor", 1, 3, f_cursor},
7587 {"deepcopy", 1, 2, f_deepcopy},
7588 {"delete", 1, 1, f_delete},
7589 {"did_filetype", 0, 0, f_did_filetype},
7590 {"diff_filler", 1, 1, f_diff_filler},
7591 {"diff_hlID", 2, 2, f_diff_hlID},
7592 {"empty", 1, 1, f_empty},
7593 {"escape", 2, 2, f_escape},
7594 {"eval", 1, 1, f_eval},
7595 {"eventhandler", 0, 0, f_eventhandler},
7596 {"executable", 1, 1, f_executable},
7597 {"exists", 1, 1, f_exists},
7598 {"expand", 1, 2, f_expand},
7599 {"extend", 2, 3, f_extend},
7600 {"feedkeys", 1, 2, f_feedkeys},
7601 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7602 {"filereadable", 1, 1, f_filereadable},
7603 {"filewritable", 1, 1, f_filewritable},
7604 {"filter", 2, 2, f_filter},
7605 {"finddir", 1, 3, f_finddir},
7606 {"findfile", 1, 3, f_findfile},
7607 #ifdef FEAT_FLOAT
7608 {"float2nr", 1, 1, f_float2nr},
7609 {"floor", 1, 1, f_floor},
7610 #endif
7611 {"fnameescape", 1, 1, f_fnameescape},
7612 {"fnamemodify", 2, 2, f_fnamemodify},
7613 {"foldclosed", 1, 1, f_foldclosed},
7614 {"foldclosedend", 1, 1, f_foldclosedend},
7615 {"foldlevel", 1, 1, f_foldlevel},
7616 {"foldtext", 0, 0, f_foldtext},
7617 {"foldtextresult", 1, 1, f_foldtextresult},
7618 {"foreground", 0, 0, f_foreground},
7619 {"function", 1, 1, f_function},
7620 {"garbagecollect", 0, 1, f_garbagecollect},
7621 {"get", 2, 3, f_get},
7622 {"getbufline", 2, 3, f_getbufline},
7623 {"getbufvar", 2, 2, f_getbufvar},
7624 {"getchar", 0, 1, f_getchar},
7625 {"getcharmod", 0, 0, f_getcharmod},
7626 {"getcmdline", 0, 0, f_getcmdline},
7627 {"getcmdpos", 0, 0, f_getcmdpos},
7628 {"getcmdtype", 0, 0, f_getcmdtype},
7629 {"getcwd", 0, 0, f_getcwd},
7630 {"getfontname", 0, 1, f_getfontname},
7631 {"getfperm", 1, 1, f_getfperm},
7632 {"getfsize", 1, 1, f_getfsize},
7633 {"getftime", 1, 1, f_getftime},
7634 {"getftype", 1, 1, f_getftype},
7635 {"getline", 1, 2, f_getline},
7636 {"getloclist", 1, 1, f_getqflist},
7637 {"getmatches", 0, 0, f_getmatches},
7638 {"getpid", 0, 0, f_getpid},
7639 {"getpos", 1, 1, f_getpos},
7640 {"getqflist", 0, 0, f_getqflist},
7641 {"getreg", 0, 2, f_getreg},
7642 {"getregtype", 0, 1, f_getregtype},
7643 {"gettabwinvar", 3, 3, f_gettabwinvar},
7644 {"getwinposx", 0, 0, f_getwinposx},
7645 {"getwinposy", 0, 0, f_getwinposy},
7646 {"getwinvar", 2, 2, f_getwinvar},
7647 {"glob", 1, 2, f_glob},
7648 {"globpath", 2, 3, f_globpath},
7649 {"has", 1, 1, f_has},
7650 {"has_key", 2, 2, f_has_key},
7651 {"haslocaldir", 0, 0, f_haslocaldir},
7652 {"hasmapto", 1, 3, f_hasmapto},
7653 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7654 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7655 {"histadd", 2, 2, f_histadd},
7656 {"histdel", 1, 2, f_histdel},
7657 {"histget", 1, 2, f_histget},
7658 {"histnr", 1, 1, f_histnr},
7659 {"hlID", 1, 1, f_hlID},
7660 {"hlexists", 1, 1, f_hlexists},
7661 {"hostname", 0, 0, f_hostname},
7662 {"iconv", 3, 3, f_iconv},
7663 {"indent", 1, 1, f_indent},
7664 {"index", 2, 4, f_index},
7665 {"input", 1, 3, f_input},
7666 {"inputdialog", 1, 3, f_inputdialog},
7667 {"inputlist", 1, 1, f_inputlist},
7668 {"inputrestore", 0, 0, f_inputrestore},
7669 {"inputsave", 0, 0, f_inputsave},
7670 {"inputsecret", 1, 2, f_inputsecret},
7671 {"insert", 2, 3, f_insert},
7672 {"isdirectory", 1, 1, f_isdirectory},
7673 {"islocked", 1, 1, f_islocked},
7674 {"items", 1, 1, f_items},
7675 {"join", 1, 2, f_join},
7676 {"keys", 1, 1, f_keys},
7677 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7678 {"len", 1, 1, f_len},
7679 {"libcall", 3, 3, f_libcall},
7680 {"libcallnr", 3, 3, f_libcallnr},
7681 {"line", 1, 1, f_line},
7682 {"line2byte", 1, 1, f_line2byte},
7683 {"lispindent", 1, 1, f_lispindent},
7684 {"localtime", 0, 0, f_localtime},
7685 #ifdef FEAT_FLOAT
7686 {"log10", 1, 1, f_log10},
7687 #endif
7688 {"map", 2, 2, f_map},
7689 {"maparg", 1, 3, f_maparg},
7690 {"mapcheck", 1, 3, f_mapcheck},
7691 {"match", 2, 4, f_match},
7692 {"matchadd", 2, 4, f_matchadd},
7693 {"matcharg", 1, 1, f_matcharg},
7694 {"matchdelete", 1, 1, f_matchdelete},
7695 {"matchend", 2, 4, f_matchend},
7696 {"matchlist", 2, 4, f_matchlist},
7697 {"matchstr", 2, 4, f_matchstr},
7698 {"max", 1, 1, f_max},
7699 {"min", 1, 1, f_min},
7700 #ifdef vim_mkdir
7701 {"mkdir", 1, 3, f_mkdir},
7702 #endif
7703 {"mode", 0, 1, f_mode},
7704 #ifdef FEAT_MZSCHEME
7705 {"mzeval", 1, 1, f_mzeval},
7706 #endif
7707 {"nextnonblank", 1, 1, f_nextnonblank},
7708 {"nr2char", 1, 1, f_nr2char},
7709 {"pathshorten", 1, 1, f_pathshorten},
7710 #ifdef FEAT_FLOAT
7711 {"pow", 2, 2, f_pow},
7712 #endif
7713 {"prevnonblank", 1, 1, f_prevnonblank},
7714 {"printf", 2, 19, f_printf},
7715 {"pumvisible", 0, 0, f_pumvisible},
7716 {"range", 1, 3, f_range},
7717 {"readfile", 1, 3, f_readfile},
7718 {"reltime", 0, 2, f_reltime},
7719 {"reltimestr", 1, 1, f_reltimestr},
7720 {"remote_expr", 2, 3, f_remote_expr},
7721 {"remote_foreground", 1, 1, f_remote_foreground},
7722 {"remote_peek", 1, 2, f_remote_peek},
7723 {"remote_read", 1, 1, f_remote_read},
7724 {"remote_send", 2, 3, f_remote_send},
7725 {"remove", 2, 3, f_remove},
7726 {"rename", 2, 2, f_rename},
7727 {"repeat", 2, 2, f_repeat},
7728 {"resolve", 1, 1, f_resolve},
7729 {"reverse", 1, 1, f_reverse},
7730 #ifdef FEAT_FLOAT
7731 {"round", 1, 1, f_round},
7732 #endif
7733 {"search", 1, 4, f_search},
7734 {"searchdecl", 1, 3, f_searchdecl},
7735 {"searchpair", 3, 7, f_searchpair},
7736 {"searchpairpos", 3, 7, f_searchpairpos},
7737 {"searchpos", 1, 4, f_searchpos},
7738 {"server2client", 2, 2, f_server2client},
7739 {"serverlist", 0, 0, f_serverlist},
7740 {"setbufvar", 3, 3, f_setbufvar},
7741 {"setcmdpos", 1, 1, f_setcmdpos},
7742 {"setline", 2, 2, f_setline},
7743 {"setloclist", 2, 3, f_setloclist},
7744 {"setmatches", 1, 1, f_setmatches},
7745 {"setpos", 2, 2, f_setpos},
7746 {"setqflist", 1, 2, f_setqflist},
7747 {"setreg", 2, 3, f_setreg},
7748 {"settabwinvar", 4, 4, f_settabwinvar},
7749 {"setwinvar", 3, 3, f_setwinvar},
7750 {"shellescape", 1, 2, f_shellescape},
7751 {"simplify", 1, 1, f_simplify},
7752 #ifdef FEAT_FLOAT
7753 {"sin", 1, 1, f_sin},
7754 #endif
7755 {"sort", 1, 2, f_sort},
7756 {"soundfold", 1, 1, f_soundfold},
7757 {"spellbadword", 0, 1, f_spellbadword},
7758 {"spellsuggest", 1, 3, f_spellsuggest},
7759 {"split", 1, 3, f_split},
7760 #ifdef FEAT_FLOAT
7761 {"sqrt", 1, 1, f_sqrt},
7762 {"str2float", 1, 1, f_str2float},
7763 #endif
7764 {"str2nr", 1, 2, f_str2nr},
7765 #ifdef HAVE_STRFTIME
7766 {"strftime", 1, 2, f_strftime},
7767 #endif
7768 {"stridx", 2, 3, f_stridx},
7769 {"string", 1, 1, f_string},
7770 {"strlen", 1, 1, f_strlen},
7771 {"strpart", 2, 3, f_strpart},
7772 {"strridx", 2, 3, f_strridx},
7773 {"strtrans", 1, 1, f_strtrans},
7774 {"submatch", 1, 1, f_submatch},
7775 {"substitute", 4, 4, f_substitute},
7776 {"synID", 3, 3, f_synID},
7777 {"synIDattr", 2, 3, f_synIDattr},
7778 {"synIDtrans", 1, 1, f_synIDtrans},
7779 {"synstack", 2, 2, f_synstack},
7780 {"system", 1, 2, f_system},
7781 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7782 {"tabpagenr", 0, 1, f_tabpagenr},
7783 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7784 {"tagfiles", 0, 0, f_tagfiles},
7785 {"taglist", 1, 1, f_taglist},
7786 {"tempname", 0, 0, f_tempname},
7787 {"test", 1, 1, f_test},
7788 {"tolower", 1, 1, f_tolower},
7789 {"toupper", 1, 1, f_toupper},
7790 {"tr", 3, 3, f_tr},
7791 #ifdef FEAT_FLOAT
7792 {"trunc", 1, 1, f_trunc},
7793 #endif
7794 {"type", 1, 1, f_type},
7795 {"values", 1, 1, f_values},
7796 {"virtcol", 1, 1, f_virtcol},
7797 {"visualmode", 0, 1, f_visualmode},
7798 {"winbufnr", 1, 1, f_winbufnr},
7799 {"wincol", 0, 0, f_wincol},
7800 {"winheight", 1, 1, f_winheight},
7801 {"winline", 0, 0, f_winline},
7802 {"winnr", 0, 1, f_winnr},
7803 {"winrestcmd", 0, 0, f_winrestcmd},
7804 {"winrestview", 1, 1, f_winrestview},
7805 {"winsaveview", 0, 0, f_winsaveview},
7806 {"winwidth", 1, 1, f_winwidth},
7807 {"writefile", 2, 3, f_writefile},
7810 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7813 * Function given to ExpandGeneric() to obtain the list of internal
7814 * or user defined function names.
7816 char_u *
7817 get_function_name(xp, idx)
7818 expand_T *xp;
7819 int idx;
7821 static int intidx = -1;
7822 char_u *name;
7824 if (idx == 0)
7825 intidx = -1;
7826 if (intidx < 0)
7828 name = get_user_func_name(xp, idx);
7829 if (name != NULL)
7830 return name;
7832 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7834 STRCPY(IObuff, functions[intidx].f_name);
7835 STRCAT(IObuff, "(");
7836 if (functions[intidx].f_max_argc == 0)
7837 STRCAT(IObuff, ")");
7838 return IObuff;
7841 return NULL;
7845 * Function given to ExpandGeneric() to obtain the list of internal or
7846 * user defined variable or function names.
7848 char_u *
7849 get_expr_name(xp, idx)
7850 expand_T *xp;
7851 int idx;
7853 static int intidx = -1;
7854 char_u *name;
7856 if (idx == 0)
7857 intidx = -1;
7858 if (intidx < 0)
7860 name = get_function_name(xp, idx);
7861 if (name != NULL)
7862 return name;
7864 return get_user_var_name(xp, ++intidx);
7867 #endif /* FEAT_CMDL_COMPL */
7870 * Find internal function in table above.
7871 * Return index, or -1 if not found
7873 static int
7874 find_internal_func(name)
7875 char_u *name; /* name of the function */
7877 int first = 0;
7878 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7879 int cmp;
7880 int x;
7883 * Find the function name in the table. Binary search.
7885 while (first <= last)
7887 x = first + ((unsigned)(last - first) >> 1);
7888 cmp = STRCMP(name, functions[x].f_name);
7889 if (cmp < 0)
7890 last = x - 1;
7891 else if (cmp > 0)
7892 first = x + 1;
7893 else
7894 return x;
7896 return -1;
7900 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7901 * name it contains, otherwise return "name".
7903 static char_u *
7904 deref_func_name(name, lenp)
7905 char_u *name;
7906 int *lenp;
7908 dictitem_T *v;
7909 int cc;
7911 cc = name[*lenp];
7912 name[*lenp] = NUL;
7913 v = find_var(name, NULL);
7914 name[*lenp] = cc;
7915 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7917 if (v->di_tv.vval.v_string == NULL)
7919 *lenp = 0;
7920 return (char_u *)""; /* just in case */
7922 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7923 return v->di_tv.vval.v_string;
7926 return name;
7930 * Allocate a variable for the result of a function.
7931 * Return OK or FAIL.
7933 static int
7934 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7935 evaluate, selfdict)
7936 char_u *name; /* name of the function */
7937 int len; /* length of "name" */
7938 typval_T *rettv;
7939 char_u **arg; /* argument, pointing to the '(' */
7940 linenr_T firstline; /* first line of range */
7941 linenr_T lastline; /* last line of range */
7942 int *doesrange; /* return: function handled range */
7943 int evaluate;
7944 dict_T *selfdict; /* Dictionary for "self" */
7946 char_u *argp;
7947 int ret = OK;
7948 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7949 int argcount = 0; /* number of arguments found */
7952 * Get the arguments.
7954 argp = *arg;
7955 while (argcount < MAX_FUNC_ARGS)
7957 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7958 if (*argp == ')' || *argp == ',' || *argp == NUL)
7959 break;
7960 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7962 ret = FAIL;
7963 break;
7965 ++argcount;
7966 if (*argp != ',')
7967 break;
7969 if (*argp == ')')
7970 ++argp;
7971 else
7972 ret = FAIL;
7974 if (ret == OK)
7975 ret = call_func(name, len, rettv, argcount, argvars,
7976 firstline, lastline, doesrange, evaluate, selfdict);
7977 else if (!aborting())
7979 if (argcount == MAX_FUNC_ARGS)
7980 emsg_funcname(N_("E740: Too many arguments for function %s"), name);
7981 else
7982 emsg_funcname(N_("E116: Invalid arguments for function %s"), name);
7985 while (--argcount >= 0)
7986 clear_tv(&argvars[argcount]);
7988 *arg = skipwhite(argp);
7989 return ret;
7994 * Call a function with its resolved parameters
7995 * Return OK when the function can't be called, FAIL otherwise.
7996 * Also returns OK when an error was encountered while executing the function.
7998 static int
7999 call_func(func_name, len, rettv, argcount, argvars, firstline, lastline,
8000 doesrange, evaluate, selfdict)
8001 char_u *func_name; /* name of the function */
8002 int len; /* length of "name" */
8003 typval_T *rettv; /* return value goes here */
8004 int argcount; /* number of "argvars" */
8005 typval_T *argvars; /* vars for arguments, must have "argcount"
8006 PLUS ONE elements! */
8007 linenr_T firstline; /* first line of range */
8008 linenr_T lastline; /* last line of range */
8009 int *doesrange; /* return: function handled range */
8010 int evaluate;
8011 dict_T *selfdict; /* Dictionary for "self" */
8013 int ret = FAIL;
8014 #define ERROR_UNKNOWN 0
8015 #define ERROR_TOOMANY 1
8016 #define ERROR_TOOFEW 2
8017 #define ERROR_SCRIPT 3
8018 #define ERROR_DICT 4
8019 #define ERROR_NONE 5
8020 #define ERROR_OTHER 6
8021 int error = ERROR_NONE;
8022 int i;
8023 int llen;
8024 ufunc_T *fp;
8025 #define FLEN_FIXED 40
8026 char_u fname_buf[FLEN_FIXED + 1];
8027 char_u *fname;
8028 char_u *name;
8030 /* Make a copy of the name, if it comes from a funcref variable it could
8031 * be changed or deleted in the called function. */
8032 name = vim_strnsave(func_name, len);
8033 if (name == NULL)
8034 return ret;
8037 * In a script change <SID>name() and s:name() to K_SNR 123_name().
8038 * Change <SNR>123_name() to K_SNR 123_name().
8039 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
8041 llen = eval_fname_script(name);
8042 if (llen > 0)
8044 fname_buf[0] = K_SPECIAL;
8045 fname_buf[1] = KS_EXTRA;
8046 fname_buf[2] = (int)KE_SNR;
8047 i = 3;
8048 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
8050 if (current_SID <= 0)
8051 error = ERROR_SCRIPT;
8052 else
8054 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
8055 i = (int)STRLEN(fname_buf);
8058 if (i + STRLEN(name + llen) < FLEN_FIXED)
8060 STRCPY(fname_buf + i, name + llen);
8061 fname = fname_buf;
8063 else
8065 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
8066 if (fname == NULL)
8067 error = ERROR_OTHER;
8068 else
8070 mch_memmove(fname, fname_buf, (size_t)i);
8071 STRCPY(fname + i, name + llen);
8075 else
8076 fname = name;
8078 *doesrange = FALSE;
8081 /* execute the function if no errors detected and executing */
8082 if (evaluate && error == ERROR_NONE)
8084 rettv->v_type = VAR_NUMBER; /* default rettv is number zero */
8085 rettv->vval.v_number = 0;
8086 error = ERROR_UNKNOWN;
8088 if (!builtin_function(fname))
8091 * User defined function.
8093 fp = find_func(fname);
8095 #ifdef FEAT_AUTOCMD
8096 /* Trigger FuncUndefined event, may load the function. */
8097 if (fp == NULL
8098 && apply_autocmds(EVENT_FUNCUNDEFINED,
8099 fname, fname, TRUE, NULL)
8100 && !aborting())
8102 /* executed an autocommand, search for the function again */
8103 fp = find_func(fname);
8105 #endif
8106 /* Try loading a package. */
8107 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
8109 /* loaded a package, search for the function again */
8110 fp = find_func(fname);
8113 if (fp != NULL)
8115 if (fp->uf_flags & FC_RANGE)
8116 *doesrange = TRUE;
8117 if (argcount < fp->uf_args.ga_len)
8118 error = ERROR_TOOFEW;
8119 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
8120 error = ERROR_TOOMANY;
8121 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
8122 error = ERROR_DICT;
8123 else
8126 * Call the user function.
8127 * Save and restore search patterns, script variables and
8128 * redo buffer.
8130 save_search_patterns();
8131 saveRedobuff();
8132 ++fp->uf_calls;
8133 call_user_func(fp, argcount, argvars, rettv,
8134 firstline, lastline,
8135 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
8136 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
8137 && fp->uf_refcount <= 0)
8138 /* Function was unreferenced while being used, free it
8139 * now. */
8140 func_free(fp);
8141 restoreRedobuff();
8142 restore_search_patterns();
8143 error = ERROR_NONE;
8147 else
8150 * Find the function name in the table, call its implementation.
8152 i = find_internal_func(fname);
8153 if (i >= 0)
8155 if (argcount < functions[i].f_min_argc)
8156 error = ERROR_TOOFEW;
8157 else if (argcount > functions[i].f_max_argc)
8158 error = ERROR_TOOMANY;
8159 else
8161 argvars[argcount].v_type = VAR_UNKNOWN;
8162 functions[i].f_func(argvars, rettv);
8163 error = ERROR_NONE;
8168 * The function call (or "FuncUndefined" autocommand sequence) might
8169 * have been aborted by an error, an interrupt, or an explicitly thrown
8170 * exception that has not been caught so far. This situation can be
8171 * tested for by calling aborting(). For an error in an internal
8172 * function or for the "E132" error in call_user_func(), however, the
8173 * throw point at which the "force_abort" flag (temporarily reset by
8174 * emsg()) is normally updated has not been reached yet. We need to
8175 * update that flag first to make aborting() reliable.
8177 update_force_abort();
8179 if (error == ERROR_NONE)
8180 ret = OK;
8183 * Report an error unless the argument evaluation or function call has been
8184 * cancelled due to an aborting error, an interrupt, or an exception.
8186 if (!aborting())
8188 switch (error)
8190 case ERROR_UNKNOWN:
8191 emsg_funcname(N_("E117: Unknown function: %s"), name);
8192 break;
8193 case ERROR_TOOMANY:
8194 emsg_funcname(e_toomanyarg, name);
8195 break;
8196 case ERROR_TOOFEW:
8197 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
8198 name);
8199 break;
8200 case ERROR_SCRIPT:
8201 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
8202 name);
8203 break;
8204 case ERROR_DICT:
8205 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
8206 name);
8207 break;
8211 if (fname != name && fname != fname_buf)
8212 vim_free(fname);
8213 vim_free(name);
8215 return ret;
8219 * Give an error message with a function name. Handle <SNR> things.
8220 * "ermsg" is to be passed without translation, use N_() instead of _().
8222 static void
8223 emsg_funcname(ermsg, name)
8224 char *ermsg;
8225 char_u *name;
8227 char_u *p;
8229 if (*name == K_SPECIAL)
8230 p = concat_str((char_u *)"<SNR>", name + 3);
8231 else
8232 p = name;
8233 EMSG2(_(ermsg), p);
8234 if (p != name)
8235 vim_free(p);
8239 * Return TRUE for a non-zero Number and a non-empty String.
8241 static int
8242 non_zero_arg(argvars)
8243 typval_T *argvars;
8245 return ((argvars[0].v_type == VAR_NUMBER
8246 && argvars[0].vval.v_number != 0)
8247 || (argvars[0].v_type == VAR_STRING
8248 && argvars[0].vval.v_string != NULL
8249 && *argvars[0].vval.v_string != NUL));
8252 /*********************************************
8253 * Implementation of the built-in functions
8256 #ifdef FEAT_FLOAT
8258 * "abs(expr)" function
8260 static void
8261 f_abs(argvars, rettv)
8262 typval_T *argvars;
8263 typval_T *rettv;
8265 if (argvars[0].v_type == VAR_FLOAT)
8267 rettv->v_type = VAR_FLOAT;
8268 rettv->vval.v_float = fabs(argvars[0].vval.v_float);
8270 else
8272 varnumber_T n;
8273 int error = FALSE;
8275 n = get_tv_number_chk(&argvars[0], &error);
8276 if (error)
8277 rettv->vval.v_number = -1;
8278 else if (n > 0)
8279 rettv->vval.v_number = n;
8280 else
8281 rettv->vval.v_number = -n;
8284 #endif
8287 * "add(list, item)" function
8289 static void
8290 f_add(argvars, rettv)
8291 typval_T *argvars;
8292 typval_T *rettv;
8294 list_T *l;
8296 rettv->vval.v_number = 1; /* Default: Failed */
8297 if (argvars[0].v_type == VAR_LIST)
8299 if ((l = argvars[0].vval.v_list) != NULL
8300 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
8301 && list_append_tv(l, &argvars[1]) == OK)
8302 copy_tv(&argvars[0], rettv);
8304 else
8305 EMSG(_(e_listreq));
8309 * "append(lnum, string/list)" function
8311 static void
8312 f_append(argvars, rettv)
8313 typval_T *argvars;
8314 typval_T *rettv;
8316 long lnum;
8317 char_u *line;
8318 list_T *l = NULL;
8319 listitem_T *li = NULL;
8320 typval_T *tv;
8321 long added = 0;
8323 lnum = get_tv_lnum(argvars);
8324 if (lnum >= 0
8325 && lnum <= curbuf->b_ml.ml_line_count
8326 && u_save(lnum, lnum + 1) == OK)
8328 if (argvars[1].v_type == VAR_LIST)
8330 l = argvars[1].vval.v_list;
8331 if (l == NULL)
8332 return;
8333 li = l->lv_first;
8335 for (;;)
8337 if (l == NULL)
8338 tv = &argvars[1]; /* append a string */
8339 else if (li == NULL)
8340 break; /* end of list */
8341 else
8342 tv = &li->li_tv; /* append item from list */
8343 line = get_tv_string_chk(tv);
8344 if (line == NULL) /* type error */
8346 rettv->vval.v_number = 1; /* Failed */
8347 break;
8349 ml_append(lnum + added, line, (colnr_T)0, FALSE);
8350 ++added;
8351 if (l == NULL)
8352 break;
8353 li = li->li_next;
8356 appended_lines_mark(lnum, added);
8357 if (curwin->w_cursor.lnum > lnum)
8358 curwin->w_cursor.lnum += added;
8360 else
8361 rettv->vval.v_number = 1; /* Failed */
8365 * "argc()" function
8367 static void
8368 f_argc(argvars, rettv)
8369 typval_T *argvars UNUSED;
8370 typval_T *rettv;
8372 rettv->vval.v_number = ARGCOUNT;
8376 * "argidx()" function
8378 static void
8379 f_argidx(argvars, rettv)
8380 typval_T *argvars UNUSED;
8381 typval_T *rettv;
8383 rettv->vval.v_number = curwin->w_arg_idx;
8387 * "argv(nr)" function
8389 static void
8390 f_argv(argvars, rettv)
8391 typval_T *argvars;
8392 typval_T *rettv;
8394 int idx;
8396 if (argvars[0].v_type != VAR_UNKNOWN)
8398 idx = get_tv_number_chk(&argvars[0], NULL);
8399 if (idx >= 0 && idx < ARGCOUNT)
8400 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
8401 else
8402 rettv->vval.v_string = NULL;
8403 rettv->v_type = VAR_STRING;
8405 else if (rettv_list_alloc(rettv) == OK)
8406 for (idx = 0; idx < ARGCOUNT; ++idx)
8407 list_append_string(rettv->vval.v_list,
8408 alist_name(&ARGLIST[idx]), -1);
8411 #ifdef FEAT_FLOAT
8412 static int get_float_arg __ARGS((typval_T *argvars, float_T *f));
8415 * Get the float value of "argvars[0]" into "f".
8416 * Returns FAIL when the argument is not a Number or Float.
8418 static int
8419 get_float_arg(argvars, f)
8420 typval_T *argvars;
8421 float_T *f;
8423 if (argvars[0].v_type == VAR_FLOAT)
8425 *f = argvars[0].vval.v_float;
8426 return OK;
8428 if (argvars[0].v_type == VAR_NUMBER)
8430 *f = (float_T)argvars[0].vval.v_number;
8431 return OK;
8433 EMSG(_("E808: Number or Float required"));
8434 return FAIL;
8438 * "atan()" function
8440 static void
8441 f_atan(argvars, rettv)
8442 typval_T *argvars;
8443 typval_T *rettv;
8445 float_T f;
8447 rettv->v_type = VAR_FLOAT;
8448 if (get_float_arg(argvars, &f) == OK)
8449 rettv->vval.v_float = atan(f);
8450 else
8451 rettv->vval.v_float = 0.0;
8453 #endif
8456 * "browse(save, title, initdir, default)" function
8458 static void
8459 f_browse(argvars, rettv)
8460 typval_T *argvars UNUSED;
8461 typval_T *rettv;
8463 #ifdef FEAT_BROWSE
8464 int save;
8465 char_u *title;
8466 char_u *initdir;
8467 char_u *defname;
8468 char_u buf[NUMBUFLEN];
8469 char_u buf2[NUMBUFLEN];
8470 int error = FALSE;
8472 save = get_tv_number_chk(&argvars[0], &error);
8473 title = get_tv_string_chk(&argvars[1]);
8474 initdir = get_tv_string_buf_chk(&argvars[2], buf);
8475 defname = get_tv_string_buf_chk(&argvars[3], buf2);
8477 if (error || title == NULL || initdir == NULL || defname == NULL)
8478 rettv->vval.v_string = NULL;
8479 else
8480 rettv->vval.v_string =
8481 do_browse(save ? BROWSE_SAVE : 0,
8482 title, defname, NULL, initdir, NULL, curbuf);
8483 #else
8484 rettv->vval.v_string = NULL;
8485 #endif
8486 rettv->v_type = VAR_STRING;
8490 * "browsedir(title, initdir)" function
8492 static void
8493 f_browsedir(argvars, rettv)
8494 typval_T *argvars UNUSED;
8495 typval_T *rettv;
8497 #ifdef FEAT_BROWSE
8498 char_u *title;
8499 char_u *initdir;
8500 char_u buf[NUMBUFLEN];
8502 title = get_tv_string_chk(&argvars[0]);
8503 initdir = get_tv_string_buf_chk(&argvars[1], buf);
8505 if (title == NULL || initdir == NULL)
8506 rettv->vval.v_string = NULL;
8507 else
8508 rettv->vval.v_string = do_browse(BROWSE_DIR,
8509 title, NULL, NULL, initdir, NULL, curbuf);
8510 #else
8511 rettv->vval.v_string = NULL;
8512 #endif
8513 rettv->v_type = VAR_STRING;
8516 static buf_T *find_buffer __ARGS((typval_T *avar));
8519 * Find a buffer by number or exact name.
8521 static buf_T *
8522 find_buffer(avar)
8523 typval_T *avar;
8525 buf_T *buf = NULL;
8527 if (avar->v_type == VAR_NUMBER)
8528 buf = buflist_findnr((int)avar->vval.v_number);
8529 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
8531 buf = buflist_findname_exp(avar->vval.v_string);
8532 if (buf == NULL)
8534 /* No full path name match, try a match with a URL or a "nofile"
8535 * buffer, these don't use the full path. */
8536 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8537 if (buf->b_fname != NULL
8538 && (path_with_url(buf->b_fname)
8539 #ifdef FEAT_QUICKFIX
8540 || bt_nofile(buf)
8541 #endif
8543 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
8544 break;
8547 return buf;
8551 * "bufexists(expr)" function
8553 static void
8554 f_bufexists(argvars, rettv)
8555 typval_T *argvars;
8556 typval_T *rettv;
8558 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
8562 * "buflisted(expr)" function
8564 static void
8565 f_buflisted(argvars, rettv)
8566 typval_T *argvars;
8567 typval_T *rettv;
8569 buf_T *buf;
8571 buf = find_buffer(&argvars[0]);
8572 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
8576 * "bufloaded(expr)" function
8578 static void
8579 f_bufloaded(argvars, rettv)
8580 typval_T *argvars;
8581 typval_T *rettv;
8583 buf_T *buf;
8585 buf = find_buffer(&argvars[0]);
8586 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
8589 static buf_T *get_buf_tv __ARGS((typval_T *tv));
8592 * Get buffer by number or pattern.
8594 static buf_T *
8595 get_buf_tv(tv)
8596 typval_T *tv;
8598 char_u *name = tv->vval.v_string;
8599 int save_magic;
8600 char_u *save_cpo;
8601 buf_T *buf;
8603 if (tv->v_type == VAR_NUMBER)
8604 return buflist_findnr((int)tv->vval.v_number);
8605 if (tv->v_type != VAR_STRING)
8606 return NULL;
8607 if (name == NULL || *name == NUL)
8608 return curbuf;
8609 if (name[0] == '$' && name[1] == NUL)
8610 return lastbuf;
8612 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
8613 save_magic = p_magic;
8614 p_magic = TRUE;
8615 save_cpo = p_cpo;
8616 p_cpo = (char_u *)"";
8618 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8619 TRUE, FALSE));
8621 p_magic = save_magic;
8622 p_cpo = save_cpo;
8624 /* If not found, try expanding the name, like done for bufexists(). */
8625 if (buf == NULL)
8626 buf = find_buffer(tv);
8628 return buf;
8632 * "bufname(expr)" function
8634 static void
8635 f_bufname(argvars, rettv)
8636 typval_T *argvars;
8637 typval_T *rettv;
8639 buf_T *buf;
8641 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8642 ++emsg_off;
8643 buf = get_buf_tv(&argvars[0]);
8644 rettv->v_type = VAR_STRING;
8645 if (buf != NULL && buf->b_fname != NULL)
8646 rettv->vval.v_string = vim_strsave(buf->b_fname);
8647 else
8648 rettv->vval.v_string = NULL;
8649 --emsg_off;
8653 * "bufnr(expr)" function
8655 static void
8656 f_bufnr(argvars, rettv)
8657 typval_T *argvars;
8658 typval_T *rettv;
8660 buf_T *buf;
8661 int error = FALSE;
8662 char_u *name;
8664 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8665 ++emsg_off;
8666 buf = get_buf_tv(&argvars[0]);
8667 --emsg_off;
8669 /* If the buffer isn't found and the second argument is not zero create a
8670 * new buffer. */
8671 if (buf == NULL
8672 && argvars[1].v_type != VAR_UNKNOWN
8673 && get_tv_number_chk(&argvars[1], &error) != 0
8674 && !error
8675 && (name = get_tv_string_chk(&argvars[0])) != NULL
8676 && !error)
8677 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8679 if (buf != NULL)
8680 rettv->vval.v_number = buf->b_fnum;
8681 else
8682 rettv->vval.v_number = -1;
8686 * "bufwinnr(nr)" function
8688 static void
8689 f_bufwinnr(argvars, rettv)
8690 typval_T *argvars;
8691 typval_T *rettv;
8693 #ifdef FEAT_WINDOWS
8694 win_T *wp;
8695 int winnr = 0;
8696 #endif
8697 buf_T *buf;
8699 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8700 ++emsg_off;
8701 buf = get_buf_tv(&argvars[0]);
8702 #ifdef FEAT_WINDOWS
8703 for (wp = firstwin; wp; wp = wp->w_next)
8705 ++winnr;
8706 if (wp->w_buffer == buf)
8707 break;
8709 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8710 #else
8711 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8712 #endif
8713 --emsg_off;
8717 * "byte2line(byte)" function
8719 static void
8720 f_byte2line(argvars, rettv)
8721 typval_T *argvars UNUSED;
8722 typval_T *rettv;
8724 #ifndef FEAT_BYTEOFF
8725 rettv->vval.v_number = -1;
8726 #else
8727 long boff = 0;
8729 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8730 if (boff < 0)
8731 rettv->vval.v_number = -1;
8732 else
8733 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8734 (linenr_T)0, &boff);
8735 #endif
8739 * "byteidx()" function
8741 static void
8742 f_byteidx(argvars, rettv)
8743 typval_T *argvars;
8744 typval_T *rettv;
8746 #ifdef FEAT_MBYTE
8747 char_u *t;
8748 #endif
8749 char_u *str;
8750 long idx;
8752 str = get_tv_string_chk(&argvars[0]);
8753 idx = get_tv_number_chk(&argvars[1], NULL);
8754 rettv->vval.v_number = -1;
8755 if (str == NULL || idx < 0)
8756 return;
8758 #ifdef FEAT_MBYTE
8759 t = str;
8760 for ( ; idx > 0; idx--)
8762 if (*t == NUL) /* EOL reached */
8763 return;
8764 t += (*mb_ptr2len)(t);
8766 rettv->vval.v_number = (varnumber_T)(t - str);
8767 #else
8768 if ((size_t)idx <= STRLEN(str))
8769 rettv->vval.v_number = idx;
8770 #endif
8774 * "call(func, arglist)" function
8776 static void
8777 f_call(argvars, rettv)
8778 typval_T *argvars;
8779 typval_T *rettv;
8781 char_u *func;
8782 typval_T argv[MAX_FUNC_ARGS + 1];
8783 int argc = 0;
8784 listitem_T *item;
8785 int dummy;
8786 dict_T *selfdict = NULL;
8788 if (argvars[1].v_type != VAR_LIST)
8790 EMSG(_(e_listreq));
8791 return;
8793 if (argvars[1].vval.v_list == NULL)
8794 return;
8796 if (argvars[0].v_type == VAR_FUNC)
8797 func = argvars[0].vval.v_string;
8798 else
8799 func = get_tv_string(&argvars[0]);
8800 if (*func == NUL)
8801 return; /* type error or empty name */
8803 if (argvars[2].v_type != VAR_UNKNOWN)
8805 if (argvars[2].v_type != VAR_DICT)
8807 EMSG(_(e_dictreq));
8808 return;
8810 selfdict = argvars[2].vval.v_dict;
8813 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
8814 item = item->li_next)
8816 if (argc == MAX_FUNC_ARGS)
8818 EMSG(_("E699: Too many arguments"));
8819 break;
8821 /* Make a copy of each argument. This is needed to be able to set
8822 * v_lock to VAR_FIXED in the copy without changing the original list.
8824 copy_tv(&item->li_tv, &argv[argc++]);
8827 if (item == NULL)
8828 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
8829 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
8830 &dummy, TRUE, selfdict);
8832 /* Free the arguments. */
8833 while (argc > 0)
8834 clear_tv(&argv[--argc]);
8837 #ifdef FEAT_FLOAT
8839 * "ceil({float})" function
8841 static void
8842 f_ceil(argvars, rettv)
8843 typval_T *argvars;
8844 typval_T *rettv;
8846 float_T f;
8848 rettv->v_type = VAR_FLOAT;
8849 if (get_float_arg(argvars, &f) == OK)
8850 rettv->vval.v_float = ceil(f);
8851 else
8852 rettv->vval.v_float = 0.0;
8854 #endif
8857 * "changenr()" function
8859 static void
8860 f_changenr(argvars, rettv)
8861 typval_T *argvars UNUSED;
8862 typval_T *rettv;
8864 rettv->vval.v_number = curbuf->b_u_seq_cur;
8868 * "char2nr(string)" function
8870 static void
8871 f_char2nr(argvars, rettv)
8872 typval_T *argvars;
8873 typval_T *rettv;
8875 #ifdef FEAT_MBYTE
8876 if (has_mbyte)
8877 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
8878 else
8879 #endif
8880 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
8884 * "cindent(lnum)" function
8886 static void
8887 f_cindent(argvars, rettv)
8888 typval_T *argvars;
8889 typval_T *rettv;
8891 #ifdef FEAT_CINDENT
8892 pos_T pos;
8893 linenr_T lnum;
8895 pos = curwin->w_cursor;
8896 lnum = get_tv_lnum(argvars);
8897 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
8899 curwin->w_cursor.lnum = lnum;
8900 rettv->vval.v_number = get_c_indent();
8901 curwin->w_cursor = pos;
8903 else
8904 #endif
8905 rettv->vval.v_number = -1;
8909 * "clearmatches()" function
8911 static void
8912 f_clearmatches(argvars, rettv)
8913 typval_T *argvars UNUSED;
8914 typval_T *rettv UNUSED;
8916 #ifdef FEAT_SEARCH_EXTRA
8917 clear_matches(curwin);
8918 #endif
8922 * "col(string)" function
8924 static void
8925 f_col(argvars, rettv)
8926 typval_T *argvars;
8927 typval_T *rettv;
8929 colnr_T col = 0;
8930 pos_T *fp;
8931 int fnum = curbuf->b_fnum;
8933 fp = var2fpos(&argvars[0], FALSE, &fnum);
8934 if (fp != NULL && fnum == curbuf->b_fnum)
8936 if (fp->col == MAXCOL)
8938 /* '> can be MAXCOL, get the length of the line then */
8939 if (fp->lnum <= curbuf->b_ml.ml_line_count)
8940 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
8941 else
8942 col = MAXCOL;
8944 else
8946 col = fp->col + 1;
8947 #ifdef FEAT_VIRTUALEDIT
8948 /* col(".") when the cursor is on the NUL at the end of the line
8949 * because of "coladd" can be seen as an extra column. */
8950 if (virtual_active() && fp == &curwin->w_cursor)
8952 char_u *p = ml_get_cursor();
8954 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
8955 curwin->w_virtcol - curwin->w_cursor.coladd))
8957 # ifdef FEAT_MBYTE
8958 int l;
8960 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
8961 col += l;
8962 # else
8963 if (*p != NUL && p[1] == NUL)
8964 ++col;
8965 # endif
8968 #endif
8971 rettv->vval.v_number = col;
8974 #if defined(FEAT_INS_EXPAND)
8976 * "complete()" function
8978 static void
8979 f_complete(argvars, rettv)
8980 typval_T *argvars;
8981 typval_T *rettv UNUSED;
8983 int startcol;
8985 if ((State & INSERT) == 0)
8987 EMSG(_("E785: complete() can only be used in Insert mode"));
8988 return;
8991 /* Check for undo allowed here, because if something was already inserted
8992 * the line was already saved for undo and this check isn't done. */
8993 if (!undo_allowed())
8994 return;
8996 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
8998 EMSG(_(e_invarg));
8999 return;
9002 startcol = get_tv_number_chk(&argvars[0], NULL);
9003 if (startcol <= 0)
9004 return;
9006 set_completion(startcol - 1, argvars[1].vval.v_list);
9010 * "complete_add()" function
9012 static void
9013 f_complete_add(argvars, rettv)
9014 typval_T *argvars;
9015 typval_T *rettv;
9017 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
9021 * "complete_check()" function
9023 static void
9024 f_complete_check(argvars, rettv)
9025 typval_T *argvars UNUSED;
9026 typval_T *rettv;
9028 int saved = RedrawingDisabled;
9030 RedrawingDisabled = 0;
9031 ins_compl_check_keys(0);
9032 rettv->vval.v_number = compl_interrupted;
9033 RedrawingDisabled = saved;
9035 #endif
9038 * "confirm(message, buttons[, default [, type]])" function
9040 static void
9041 f_confirm(argvars, rettv)
9042 typval_T *argvars UNUSED;
9043 typval_T *rettv UNUSED;
9045 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
9046 char_u *message;
9047 char_u *buttons = NULL;
9048 char_u buf[NUMBUFLEN];
9049 char_u buf2[NUMBUFLEN];
9050 int def = 1;
9051 int type = VIM_GENERIC;
9052 char_u *typestr;
9053 int error = FALSE;
9055 message = get_tv_string_chk(&argvars[0]);
9056 if (message == NULL)
9057 error = TRUE;
9058 if (argvars[1].v_type != VAR_UNKNOWN)
9060 buttons = get_tv_string_buf_chk(&argvars[1], buf);
9061 if (buttons == NULL)
9062 error = TRUE;
9063 if (argvars[2].v_type != VAR_UNKNOWN)
9065 def = get_tv_number_chk(&argvars[2], &error);
9066 if (argvars[3].v_type != VAR_UNKNOWN)
9068 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
9069 if (typestr == NULL)
9070 error = TRUE;
9071 else
9073 switch (TOUPPER_ASC(*typestr))
9075 case 'E': type = VIM_ERROR; break;
9076 case 'Q': type = VIM_QUESTION; break;
9077 case 'I': type = VIM_INFO; break;
9078 case 'W': type = VIM_WARNING; break;
9079 case 'G': type = VIM_GENERIC; break;
9086 if (buttons == NULL || *buttons == NUL)
9087 buttons = (char_u *)_("&Ok");
9089 if (!error)
9090 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
9091 def, NULL);
9092 #endif
9096 * "copy()" function
9098 static void
9099 f_copy(argvars, rettv)
9100 typval_T *argvars;
9101 typval_T *rettv;
9103 item_copy(&argvars[0], rettv, FALSE, 0);
9106 #ifdef FEAT_FLOAT
9108 * "cos()" function
9110 static void
9111 f_cos(argvars, rettv)
9112 typval_T *argvars;
9113 typval_T *rettv;
9115 float_T f;
9117 rettv->v_type = VAR_FLOAT;
9118 if (get_float_arg(argvars, &f) == OK)
9119 rettv->vval.v_float = cos(f);
9120 else
9121 rettv->vval.v_float = 0.0;
9123 #endif
9126 * "count()" function
9128 static void
9129 f_count(argvars, rettv)
9130 typval_T *argvars;
9131 typval_T *rettv;
9133 long n = 0;
9134 int ic = FALSE;
9136 if (argvars[0].v_type == VAR_LIST)
9138 listitem_T *li;
9139 list_T *l;
9140 long idx;
9142 if ((l = argvars[0].vval.v_list) != NULL)
9144 li = l->lv_first;
9145 if (argvars[2].v_type != VAR_UNKNOWN)
9147 int error = FALSE;
9149 ic = get_tv_number_chk(&argvars[2], &error);
9150 if (argvars[3].v_type != VAR_UNKNOWN)
9152 idx = get_tv_number_chk(&argvars[3], &error);
9153 if (!error)
9155 li = list_find(l, idx);
9156 if (li == NULL)
9157 EMSGN(_(e_listidx), idx);
9160 if (error)
9161 li = NULL;
9164 for ( ; li != NULL; li = li->li_next)
9165 if (tv_equal(&li->li_tv, &argvars[1], ic))
9166 ++n;
9169 else if (argvars[0].v_type == VAR_DICT)
9171 int todo;
9172 dict_T *d;
9173 hashitem_T *hi;
9175 if ((d = argvars[0].vval.v_dict) != NULL)
9177 int error = FALSE;
9179 if (argvars[2].v_type != VAR_UNKNOWN)
9181 ic = get_tv_number_chk(&argvars[2], &error);
9182 if (argvars[3].v_type != VAR_UNKNOWN)
9183 EMSG(_(e_invarg));
9186 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
9187 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
9189 if (!HASHITEM_EMPTY(hi))
9191 --todo;
9192 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
9193 ++n;
9198 else
9199 EMSG2(_(e_listdictarg), "count()");
9200 rettv->vval.v_number = n;
9204 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
9206 * Checks the existence of a cscope connection.
9208 static void
9209 f_cscope_connection(argvars, rettv)
9210 typval_T *argvars UNUSED;
9211 typval_T *rettv UNUSED;
9213 #ifdef FEAT_CSCOPE
9214 int num = 0;
9215 char_u *dbpath = NULL;
9216 char_u *prepend = NULL;
9217 char_u buf[NUMBUFLEN];
9219 if (argvars[0].v_type != VAR_UNKNOWN
9220 && argvars[1].v_type != VAR_UNKNOWN)
9222 num = (int)get_tv_number(&argvars[0]);
9223 dbpath = get_tv_string(&argvars[1]);
9224 if (argvars[2].v_type != VAR_UNKNOWN)
9225 prepend = get_tv_string_buf(&argvars[2], buf);
9228 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
9229 #endif
9233 * "cursor(lnum, col)" function
9235 * Moves the cursor to the specified line and column.
9236 * Returns 0 when the position could be set, -1 otherwise.
9238 static void
9239 f_cursor(argvars, rettv)
9240 typval_T *argvars;
9241 typval_T *rettv;
9243 long line, col;
9244 #ifdef FEAT_VIRTUALEDIT
9245 long coladd = 0;
9246 #endif
9248 rettv->vval.v_number = -1;
9249 if (argvars[1].v_type == VAR_UNKNOWN)
9251 pos_T pos;
9253 if (list2fpos(argvars, &pos, NULL) == FAIL)
9254 return;
9255 line = pos.lnum;
9256 col = pos.col;
9257 #ifdef FEAT_VIRTUALEDIT
9258 coladd = pos.coladd;
9259 #endif
9261 else
9263 line = get_tv_lnum(argvars);
9264 col = get_tv_number_chk(&argvars[1], NULL);
9265 #ifdef FEAT_VIRTUALEDIT
9266 if (argvars[2].v_type != VAR_UNKNOWN)
9267 coladd = get_tv_number_chk(&argvars[2], NULL);
9268 #endif
9270 if (line < 0 || col < 0
9271 #ifdef FEAT_VIRTUALEDIT
9272 || coladd < 0
9273 #endif
9275 return; /* type error; errmsg already given */
9276 if (line > 0)
9277 curwin->w_cursor.lnum = line;
9278 if (col > 0)
9279 curwin->w_cursor.col = col - 1;
9280 #ifdef FEAT_VIRTUALEDIT
9281 curwin->w_cursor.coladd = coladd;
9282 #endif
9284 /* Make sure the cursor is in a valid position. */
9285 check_cursor();
9286 #ifdef FEAT_MBYTE
9287 /* Correct cursor for multi-byte character. */
9288 if (has_mbyte)
9289 mb_adjust_cursor();
9290 #endif
9292 curwin->w_set_curswant = TRUE;
9293 rettv->vval.v_number = 0;
9297 * "deepcopy()" function
9299 static void
9300 f_deepcopy(argvars, rettv)
9301 typval_T *argvars;
9302 typval_T *rettv;
9304 int noref = 0;
9306 if (argvars[1].v_type != VAR_UNKNOWN)
9307 noref = get_tv_number_chk(&argvars[1], NULL);
9308 if (noref < 0 || noref > 1)
9309 EMSG(_(e_invarg));
9310 else
9312 current_copyID += COPYID_INC;
9313 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? current_copyID : 0);
9318 * "delete()" function
9320 static void
9321 f_delete(argvars, rettv)
9322 typval_T *argvars;
9323 typval_T *rettv;
9325 if (check_restricted() || check_secure())
9326 rettv->vval.v_number = -1;
9327 else
9328 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
9332 * "did_filetype()" function
9334 static void
9335 f_did_filetype(argvars, rettv)
9336 typval_T *argvars UNUSED;
9337 typval_T *rettv UNUSED;
9339 #ifdef FEAT_AUTOCMD
9340 rettv->vval.v_number = did_filetype;
9341 #endif
9345 * "diff_filler()" function
9347 static void
9348 f_diff_filler(argvars, rettv)
9349 typval_T *argvars UNUSED;
9350 typval_T *rettv UNUSED;
9352 #ifdef FEAT_DIFF
9353 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
9354 #endif
9358 * "diff_hlID()" function
9360 static void
9361 f_diff_hlID(argvars, rettv)
9362 typval_T *argvars UNUSED;
9363 typval_T *rettv UNUSED;
9365 #ifdef FEAT_DIFF
9366 linenr_T lnum = get_tv_lnum(argvars);
9367 static linenr_T prev_lnum = 0;
9368 static int changedtick = 0;
9369 static int fnum = 0;
9370 static int change_start = 0;
9371 static int change_end = 0;
9372 static hlf_T hlID = (hlf_T)0;
9373 int filler_lines;
9374 int col;
9376 if (lnum < 0) /* ignore type error in {lnum} arg */
9377 lnum = 0;
9378 if (lnum != prev_lnum
9379 || changedtick != curbuf->b_changedtick
9380 || fnum != curbuf->b_fnum)
9382 /* New line, buffer, change: need to get the values. */
9383 filler_lines = diff_check(curwin, lnum);
9384 if (filler_lines < 0)
9386 if (filler_lines == -1)
9388 change_start = MAXCOL;
9389 change_end = -1;
9390 if (diff_find_change(curwin, lnum, &change_start, &change_end))
9391 hlID = HLF_ADD; /* added line */
9392 else
9393 hlID = HLF_CHD; /* changed line */
9395 else
9396 hlID = HLF_ADD; /* added line */
9398 else
9399 hlID = (hlf_T)0;
9400 prev_lnum = lnum;
9401 changedtick = curbuf->b_changedtick;
9402 fnum = curbuf->b_fnum;
9405 if (hlID == HLF_CHD || hlID == HLF_TXD)
9407 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
9408 if (col >= change_start && col <= change_end)
9409 hlID = HLF_TXD; /* changed text */
9410 else
9411 hlID = HLF_CHD; /* changed line */
9413 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
9414 #endif
9418 * "empty({expr})" function
9420 static void
9421 f_empty(argvars, rettv)
9422 typval_T *argvars;
9423 typval_T *rettv;
9425 int n;
9427 switch (argvars[0].v_type)
9429 case VAR_STRING:
9430 case VAR_FUNC:
9431 n = argvars[0].vval.v_string == NULL
9432 || *argvars[0].vval.v_string == NUL;
9433 break;
9434 case VAR_NUMBER:
9435 n = argvars[0].vval.v_number == 0;
9436 break;
9437 #ifdef FEAT_FLOAT
9438 case VAR_FLOAT:
9439 n = argvars[0].vval.v_float == 0.0;
9440 break;
9441 #endif
9442 case VAR_LIST:
9443 n = argvars[0].vval.v_list == NULL
9444 || argvars[0].vval.v_list->lv_first == NULL;
9445 break;
9446 case VAR_DICT:
9447 n = argvars[0].vval.v_dict == NULL
9448 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
9449 break;
9450 default:
9451 EMSG2(_(e_intern2), "f_empty()");
9452 n = 0;
9455 rettv->vval.v_number = n;
9459 * "escape({string}, {chars})" function
9461 static void
9462 f_escape(argvars, rettv)
9463 typval_T *argvars;
9464 typval_T *rettv;
9466 char_u buf[NUMBUFLEN];
9468 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
9469 get_tv_string_buf(&argvars[1], buf));
9470 rettv->v_type = VAR_STRING;
9474 * "eval()" function
9476 static void
9477 f_eval(argvars, rettv)
9478 typval_T *argvars;
9479 typval_T *rettv;
9481 char_u *s;
9483 s = get_tv_string_chk(&argvars[0]);
9484 if (s != NULL)
9485 s = skipwhite(s);
9487 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
9489 rettv->v_type = VAR_NUMBER;
9490 rettv->vval.v_number = 0;
9492 else if (*s != NUL)
9493 EMSG(_(e_trailing));
9497 * "eventhandler()" function
9499 static void
9500 f_eventhandler(argvars, rettv)
9501 typval_T *argvars UNUSED;
9502 typval_T *rettv;
9504 rettv->vval.v_number = vgetc_busy;
9508 * "executable()" function
9510 static void
9511 f_executable(argvars, rettv)
9512 typval_T *argvars;
9513 typval_T *rettv;
9515 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
9519 * "exists()" function
9521 static void
9522 f_exists(argvars, rettv)
9523 typval_T *argvars;
9524 typval_T *rettv;
9526 char_u *p;
9527 char_u *name;
9528 int n = FALSE;
9529 int len = 0;
9531 p = get_tv_string(&argvars[0]);
9532 if (*p == '$') /* environment variable */
9534 /* first try "normal" environment variables (fast) */
9535 if (mch_getenv(p + 1) != NULL)
9536 n = TRUE;
9537 else
9539 /* try expanding things like $VIM and ${HOME} */
9540 p = expand_env_save(p);
9541 if (p != NULL && *p != '$')
9542 n = TRUE;
9543 vim_free(p);
9546 else if (*p == '&' || *p == '+') /* option */
9548 n = (get_option_tv(&p, NULL, TRUE) == OK);
9549 if (*skipwhite(p) != NUL)
9550 n = FALSE; /* trailing garbage */
9552 else if (*p == '*') /* internal or user defined function */
9554 n = function_exists(p + 1);
9556 else if (*p == ':')
9558 n = cmd_exists(p + 1);
9560 else if (*p == '#')
9562 #ifdef FEAT_AUTOCMD
9563 if (p[1] == '#')
9564 n = autocmd_supported(p + 2);
9565 else
9566 n = au_exists(p + 1);
9567 #endif
9569 else /* internal variable */
9571 char_u *tofree;
9572 typval_T tv;
9574 /* get_name_len() takes care of expanding curly braces */
9575 name = p;
9576 len = get_name_len(&p, &tofree, TRUE, FALSE);
9577 if (len > 0)
9579 if (tofree != NULL)
9580 name = tofree;
9581 n = (get_var_tv(name, len, &tv, FALSE) == OK);
9582 if (n)
9584 /* handle d.key, l[idx], f(expr) */
9585 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
9586 if (n)
9587 clear_tv(&tv);
9590 if (*p != NUL)
9591 n = FALSE;
9593 vim_free(tofree);
9596 rettv->vval.v_number = n;
9600 * "expand()" function
9602 static void
9603 f_expand(argvars, rettv)
9604 typval_T *argvars;
9605 typval_T *rettv;
9607 char_u *s;
9608 int len;
9609 char_u *errormsg;
9610 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
9611 expand_T xpc;
9612 int error = FALSE;
9614 rettv->v_type = VAR_STRING;
9615 s = get_tv_string(&argvars[0]);
9616 if (*s == '%' || *s == '#' || *s == '<')
9618 ++emsg_off;
9619 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
9620 --emsg_off;
9622 else
9624 /* When the optional second argument is non-zero, don't remove matches
9625 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
9626 if (argvars[1].v_type != VAR_UNKNOWN
9627 && get_tv_number_chk(&argvars[1], &error))
9628 flags |= WILD_KEEP_ALL;
9629 if (!error)
9631 ExpandInit(&xpc);
9632 xpc.xp_context = EXPAND_FILES;
9633 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
9635 else
9636 rettv->vval.v_string = NULL;
9641 * "extend(list, list [, idx])" function
9642 * "extend(dict, dict [, action])" function
9644 static void
9645 f_extend(argvars, rettv)
9646 typval_T *argvars;
9647 typval_T *rettv;
9649 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9651 list_T *l1, *l2;
9652 listitem_T *item;
9653 long before;
9654 int error = FALSE;
9656 l1 = argvars[0].vval.v_list;
9657 l2 = argvars[1].vval.v_list;
9658 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9659 && l2 != NULL)
9661 if (argvars[2].v_type != VAR_UNKNOWN)
9663 before = get_tv_number_chk(&argvars[2], &error);
9664 if (error)
9665 return; /* type error; errmsg already given */
9667 if (before == l1->lv_len)
9668 item = NULL;
9669 else
9671 item = list_find(l1, before);
9672 if (item == NULL)
9674 EMSGN(_(e_listidx), before);
9675 return;
9679 else
9680 item = NULL;
9681 list_extend(l1, l2, item);
9683 copy_tv(&argvars[0], rettv);
9686 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9688 dict_T *d1, *d2;
9689 dictitem_T *di1;
9690 char_u *action;
9691 int i;
9692 hashitem_T *hi2;
9693 int todo;
9695 d1 = argvars[0].vval.v_dict;
9696 d2 = argvars[1].vval.v_dict;
9697 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9698 && d2 != NULL)
9700 /* Check the third argument. */
9701 if (argvars[2].v_type != VAR_UNKNOWN)
9703 static char *(av[]) = {"keep", "force", "error"};
9705 action = get_tv_string_chk(&argvars[2]);
9706 if (action == NULL)
9707 return; /* type error; errmsg already given */
9708 for (i = 0; i < 3; ++i)
9709 if (STRCMP(action, av[i]) == 0)
9710 break;
9711 if (i == 3)
9713 EMSG2(_(e_invarg2), action);
9714 return;
9717 else
9718 action = (char_u *)"force";
9720 /* Go over all entries in the second dict and add them to the
9721 * first dict. */
9722 todo = (int)d2->dv_hashtab.ht_used;
9723 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9725 if (!HASHITEM_EMPTY(hi2))
9727 --todo;
9728 di1 = dict_find(d1, hi2->hi_key, -1);
9729 if (di1 == NULL)
9731 di1 = dictitem_copy(HI2DI(hi2));
9732 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9733 dictitem_free(di1);
9735 else if (*action == 'e')
9737 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9738 break;
9740 else if (*action == 'f')
9742 clear_tv(&di1->di_tv);
9743 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9748 copy_tv(&argvars[0], rettv);
9751 else
9752 EMSG2(_(e_listdictarg), "extend()");
9756 * "feedkeys()" function
9758 static void
9759 f_feedkeys(argvars, rettv)
9760 typval_T *argvars;
9761 typval_T *rettv UNUSED;
9763 int remap = TRUE;
9764 char_u *keys, *flags;
9765 char_u nbuf[NUMBUFLEN];
9766 int typed = FALSE;
9767 char_u *keys_esc;
9769 /* This is not allowed in the sandbox. If the commands would still be
9770 * executed in the sandbox it would be OK, but it probably happens later,
9771 * when "sandbox" is no longer set. */
9772 if (check_secure())
9773 return;
9775 keys = get_tv_string(&argvars[0]);
9776 if (*keys != NUL)
9778 if (argvars[1].v_type != VAR_UNKNOWN)
9780 flags = get_tv_string_buf(&argvars[1], nbuf);
9781 for ( ; *flags != NUL; ++flags)
9783 switch (*flags)
9785 case 'n': remap = FALSE; break;
9786 case 'm': remap = TRUE; break;
9787 case 't': typed = TRUE; break;
9792 /* Need to escape K_SPECIAL and CSI before putting the string in the
9793 * typeahead buffer. */
9794 keys_esc = vim_strsave_escape_csi(keys);
9795 if (keys_esc != NULL)
9797 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
9798 typebuf.tb_len, !typed, FALSE);
9799 vim_free(keys_esc);
9800 if (vgetc_busy)
9801 typebuf_was_filled = TRUE;
9807 * "filereadable()" function
9809 static void
9810 f_filereadable(argvars, rettv)
9811 typval_T *argvars;
9812 typval_T *rettv;
9814 int fd;
9815 char_u *p;
9816 int n;
9818 #ifndef O_NONBLOCK
9819 # define O_NONBLOCK 0
9820 #endif
9821 p = get_tv_string(&argvars[0]);
9822 if (*p && !mch_isdir(p) && (fd = mch_open((char *)p,
9823 O_RDONLY | O_NONBLOCK, 0)) >= 0)
9825 n = TRUE;
9826 close(fd);
9828 else
9829 n = FALSE;
9831 rettv->vval.v_number = n;
9835 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
9836 * rights to write into.
9838 static void
9839 f_filewritable(argvars, rettv)
9840 typval_T *argvars;
9841 typval_T *rettv;
9843 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
9846 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
9848 static void
9849 findfilendir(argvars, rettv, find_what)
9850 typval_T *argvars;
9851 typval_T *rettv;
9852 int find_what;
9854 #ifdef FEAT_SEARCHPATH
9855 char_u *fname;
9856 char_u *fresult = NULL;
9857 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
9858 char_u *p;
9859 char_u pathbuf[NUMBUFLEN];
9860 int count = 1;
9861 int first = TRUE;
9862 int error = FALSE;
9863 #endif
9865 rettv->vval.v_string = NULL;
9866 rettv->v_type = VAR_STRING;
9868 #ifdef FEAT_SEARCHPATH
9869 fname = get_tv_string(&argvars[0]);
9871 if (argvars[1].v_type != VAR_UNKNOWN)
9873 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
9874 if (p == NULL)
9875 error = TRUE;
9876 else
9878 if (*p != NUL)
9879 path = p;
9881 if (argvars[2].v_type != VAR_UNKNOWN)
9882 count = get_tv_number_chk(&argvars[2], &error);
9886 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
9887 error = TRUE;
9889 if (*fname != NUL && !error)
9893 if (rettv->v_type == VAR_STRING)
9894 vim_free(fresult);
9895 fresult = find_file_in_path_option(first ? fname : NULL,
9896 first ? (int)STRLEN(fname) : 0,
9897 0, first, path,
9898 find_what,
9899 curbuf->b_ffname,
9900 find_what == FINDFILE_DIR
9901 ? (char_u *)"" : curbuf->b_p_sua);
9902 first = FALSE;
9904 if (fresult != NULL && rettv->v_type == VAR_LIST)
9905 list_append_string(rettv->vval.v_list, fresult, -1);
9907 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
9910 if (rettv->v_type == VAR_STRING)
9911 rettv->vval.v_string = fresult;
9912 #endif
9915 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
9916 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
9919 * Implementation of map() and filter().
9921 static void
9922 filter_map(argvars, rettv, map)
9923 typval_T *argvars;
9924 typval_T *rettv;
9925 int map;
9927 char_u buf[NUMBUFLEN];
9928 char_u *expr;
9929 listitem_T *li, *nli;
9930 list_T *l = NULL;
9931 dictitem_T *di;
9932 hashtab_T *ht;
9933 hashitem_T *hi;
9934 dict_T *d = NULL;
9935 typval_T save_val;
9936 typval_T save_key;
9937 int rem;
9938 int todo;
9939 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
9940 int save_did_emsg;
9941 int index = 0;
9943 if (argvars[0].v_type == VAR_LIST)
9945 if ((l = argvars[0].vval.v_list) == NULL
9946 || (map && tv_check_lock(l->lv_lock, ermsg)))
9947 return;
9949 else if (argvars[0].v_type == VAR_DICT)
9951 if ((d = argvars[0].vval.v_dict) == NULL
9952 || (map && tv_check_lock(d->dv_lock, ermsg)))
9953 return;
9955 else
9957 EMSG2(_(e_listdictarg), ermsg);
9958 return;
9961 expr = get_tv_string_buf_chk(&argvars[1], buf);
9962 /* On type errors, the preceding call has already displayed an error
9963 * message. Avoid a misleading error message for an empty string that
9964 * was not passed as argument. */
9965 if (expr != NULL)
9967 prepare_vimvar(VV_VAL, &save_val);
9968 expr = skipwhite(expr);
9970 /* We reset "did_emsg" to be able to detect whether an error
9971 * occurred during evaluation of the expression. */
9972 save_did_emsg = did_emsg;
9973 did_emsg = FALSE;
9975 prepare_vimvar(VV_KEY, &save_key);
9976 if (argvars[0].v_type == VAR_DICT)
9978 vimvars[VV_KEY].vv_type = VAR_STRING;
9980 ht = &d->dv_hashtab;
9981 hash_lock(ht);
9982 todo = (int)ht->ht_used;
9983 for (hi = ht->ht_array; todo > 0; ++hi)
9985 if (!HASHITEM_EMPTY(hi))
9987 --todo;
9988 di = HI2DI(hi);
9989 if (tv_check_lock(di->di_tv.v_lock, ermsg))
9990 break;
9991 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
9992 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
9993 || did_emsg)
9994 break;
9995 if (!map && rem)
9996 dictitem_remove(d, di);
9997 clear_tv(&vimvars[VV_KEY].vv_tv);
10000 hash_unlock(ht);
10002 else
10004 vimvars[VV_KEY].vv_type = VAR_NUMBER;
10006 for (li = l->lv_first; li != NULL; li = nli)
10008 if (tv_check_lock(li->li_tv.v_lock, ermsg))
10009 break;
10010 nli = li->li_next;
10011 vimvars[VV_KEY].vv_nr = index;
10012 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
10013 || did_emsg)
10014 break;
10015 if (!map && rem)
10016 listitem_remove(l, li);
10017 ++index;
10021 restore_vimvar(VV_KEY, &save_key);
10022 restore_vimvar(VV_VAL, &save_val);
10024 did_emsg |= save_did_emsg;
10027 copy_tv(&argvars[0], rettv);
10030 static int
10031 filter_map_one(tv, expr, map, remp)
10032 typval_T *tv;
10033 char_u *expr;
10034 int map;
10035 int *remp;
10037 typval_T rettv;
10038 char_u *s;
10039 int retval = FAIL;
10041 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
10042 s = expr;
10043 if (eval1(&s, &rettv, TRUE) == FAIL)
10044 goto theend;
10045 if (*s != NUL) /* check for trailing chars after expr */
10047 EMSG2(_(e_invexpr2), s);
10048 goto theend;
10050 if (map)
10052 /* map(): replace the list item value */
10053 clear_tv(tv);
10054 rettv.v_lock = 0;
10055 *tv = rettv;
10057 else
10059 int error = FALSE;
10061 /* filter(): when expr is zero remove the item */
10062 *remp = (get_tv_number_chk(&rettv, &error) == 0);
10063 clear_tv(&rettv);
10064 /* On type error, nothing has been removed; return FAIL to stop the
10065 * loop. The error message was given by get_tv_number_chk(). */
10066 if (error)
10067 goto theend;
10069 retval = OK;
10070 theend:
10071 clear_tv(&vimvars[VV_VAL].vv_tv);
10072 return retval;
10076 * "filter()" function
10078 static void
10079 f_filter(argvars, rettv)
10080 typval_T *argvars;
10081 typval_T *rettv;
10083 filter_map(argvars, rettv, FALSE);
10087 * "finddir({fname}[, {path}[, {count}]])" function
10089 static void
10090 f_finddir(argvars, rettv)
10091 typval_T *argvars;
10092 typval_T *rettv;
10094 findfilendir(argvars, rettv, FINDFILE_DIR);
10098 * "findfile({fname}[, {path}[, {count}]])" function
10100 static void
10101 f_findfile(argvars, rettv)
10102 typval_T *argvars;
10103 typval_T *rettv;
10105 findfilendir(argvars, rettv, FINDFILE_FILE);
10108 #ifdef FEAT_FLOAT
10110 * "float2nr({float})" function
10112 static void
10113 f_float2nr(argvars, rettv)
10114 typval_T *argvars;
10115 typval_T *rettv;
10117 float_T f;
10119 if (get_float_arg(argvars, &f) == OK)
10121 if (f < -0x7fffffff)
10122 rettv->vval.v_number = -0x7fffffff;
10123 else if (f > 0x7fffffff)
10124 rettv->vval.v_number = 0x7fffffff;
10125 else
10126 rettv->vval.v_number = (varnumber_T)f;
10131 * "floor({float})" function
10133 static void
10134 f_floor(argvars, rettv)
10135 typval_T *argvars;
10136 typval_T *rettv;
10138 float_T f;
10140 rettv->v_type = VAR_FLOAT;
10141 if (get_float_arg(argvars, &f) == OK)
10142 rettv->vval.v_float = floor(f);
10143 else
10144 rettv->vval.v_float = 0.0;
10146 #endif
10149 * "fnameescape({string})" function
10151 static void
10152 f_fnameescape(argvars, rettv)
10153 typval_T *argvars;
10154 typval_T *rettv;
10156 rettv->vval.v_string = vim_strsave_fnameescape(
10157 get_tv_string(&argvars[0]), FALSE);
10158 rettv->v_type = VAR_STRING;
10162 * "fnamemodify({fname}, {mods})" function
10164 static void
10165 f_fnamemodify(argvars, rettv)
10166 typval_T *argvars;
10167 typval_T *rettv;
10169 char_u *fname;
10170 char_u *mods;
10171 int usedlen = 0;
10172 int len;
10173 char_u *fbuf = NULL;
10174 char_u buf[NUMBUFLEN];
10176 fname = get_tv_string_chk(&argvars[0]);
10177 mods = get_tv_string_buf_chk(&argvars[1], buf);
10178 if (fname == NULL || mods == NULL)
10179 fname = NULL;
10180 else
10182 len = (int)STRLEN(fname);
10183 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
10186 rettv->v_type = VAR_STRING;
10187 if (fname == NULL)
10188 rettv->vval.v_string = NULL;
10189 else
10190 rettv->vval.v_string = vim_strnsave(fname, len);
10191 vim_free(fbuf);
10194 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
10197 * "foldclosed()" function
10199 static void
10200 foldclosed_both(argvars, rettv, end)
10201 typval_T *argvars;
10202 typval_T *rettv;
10203 int end;
10205 #ifdef FEAT_FOLDING
10206 linenr_T lnum;
10207 linenr_T first, last;
10209 lnum = get_tv_lnum(argvars);
10210 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10212 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
10214 if (end)
10215 rettv->vval.v_number = (varnumber_T)last;
10216 else
10217 rettv->vval.v_number = (varnumber_T)first;
10218 return;
10221 #endif
10222 rettv->vval.v_number = -1;
10226 * "foldclosed()" function
10228 static void
10229 f_foldclosed(argvars, rettv)
10230 typval_T *argvars;
10231 typval_T *rettv;
10233 foldclosed_both(argvars, rettv, FALSE);
10237 * "foldclosedend()" function
10239 static void
10240 f_foldclosedend(argvars, rettv)
10241 typval_T *argvars;
10242 typval_T *rettv;
10244 foldclosed_both(argvars, rettv, TRUE);
10248 * "foldlevel()" function
10250 static void
10251 f_foldlevel(argvars, rettv)
10252 typval_T *argvars;
10253 typval_T *rettv;
10255 #ifdef FEAT_FOLDING
10256 linenr_T lnum;
10258 lnum = get_tv_lnum(argvars);
10259 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10260 rettv->vval.v_number = foldLevel(lnum);
10261 #endif
10265 * "foldtext()" function
10267 static void
10268 f_foldtext(argvars, rettv)
10269 typval_T *argvars UNUSED;
10270 typval_T *rettv;
10272 #ifdef FEAT_FOLDING
10273 linenr_T lnum;
10274 char_u *s;
10275 char_u *r;
10276 int len;
10277 char *txt;
10278 #endif
10280 rettv->v_type = VAR_STRING;
10281 rettv->vval.v_string = NULL;
10282 #ifdef FEAT_FOLDING
10283 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
10284 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
10285 <= curbuf->b_ml.ml_line_count
10286 && vimvars[VV_FOLDDASHES].vv_str != NULL)
10288 /* Find first non-empty line in the fold. */
10289 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
10290 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10292 if (!linewhite(lnum))
10293 break;
10294 ++lnum;
10297 /* Find interesting text in this line. */
10298 s = skipwhite(ml_get(lnum));
10299 /* skip C comment-start */
10300 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
10302 s = skipwhite(s + 2);
10303 if (*skipwhite(s) == NUL
10304 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10306 s = skipwhite(ml_get(lnum + 1));
10307 if (*s == '*')
10308 s = skipwhite(s + 1);
10311 txt = _("+-%s%3ld lines: ");
10312 r = alloc((unsigned)(STRLEN(txt)
10313 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
10314 + 20 /* for %3ld */
10315 + STRLEN(s))); /* concatenated */
10316 if (r != NULL)
10318 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
10319 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
10320 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
10321 len = (int)STRLEN(r);
10322 STRCAT(r, s);
10323 /* remove 'foldmarker' and 'commentstring' */
10324 foldtext_cleanup(r + len);
10325 rettv->vval.v_string = r;
10328 #endif
10332 * "foldtextresult(lnum)" function
10334 static void
10335 f_foldtextresult(argvars, rettv)
10336 typval_T *argvars UNUSED;
10337 typval_T *rettv;
10339 #ifdef FEAT_FOLDING
10340 linenr_T lnum;
10341 char_u *text;
10342 char_u buf[51];
10343 foldinfo_T foldinfo;
10344 int fold_count;
10345 #endif
10347 rettv->v_type = VAR_STRING;
10348 rettv->vval.v_string = NULL;
10349 #ifdef FEAT_FOLDING
10350 lnum = get_tv_lnum(argvars);
10351 /* treat illegal types and illegal string values for {lnum} the same */
10352 if (lnum < 0)
10353 lnum = 0;
10354 fold_count = foldedCount(curwin, lnum, &foldinfo);
10355 if (fold_count > 0)
10357 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
10358 &foldinfo, buf);
10359 if (text == buf)
10360 text = vim_strsave(text);
10361 rettv->vval.v_string = text;
10363 #endif
10367 * "foreground()" function
10369 static void
10370 f_foreground(argvars, rettv)
10371 typval_T *argvars UNUSED;
10372 typval_T *rettv UNUSED;
10374 #ifdef FEAT_GUI
10375 if (gui.in_use)
10376 gui_mch_set_foreground();
10377 #else
10378 # ifdef WIN32
10379 win32_set_foreground();
10380 # endif
10381 #endif
10385 * "function()" function
10387 static void
10388 f_function(argvars, rettv)
10389 typval_T *argvars;
10390 typval_T *rettv;
10392 char_u *s;
10394 s = get_tv_string(&argvars[0]);
10395 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
10396 EMSG2(_(e_invarg2), s);
10397 /* Don't check an autoload name for existence here. */
10398 else if (vim_strchr(s, AUTOLOAD_CHAR) == NULL && !function_exists(s))
10399 EMSG2(_("E700: Unknown function: %s"), s);
10400 else
10402 rettv->vval.v_string = vim_strsave(s);
10403 rettv->v_type = VAR_FUNC;
10408 * "garbagecollect()" function
10410 static void
10411 f_garbagecollect(argvars, rettv)
10412 typval_T *argvars;
10413 typval_T *rettv UNUSED;
10415 /* This is postponed until we are back at the toplevel, because we may be
10416 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
10417 want_garbage_collect = TRUE;
10419 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
10420 garbage_collect_at_exit = TRUE;
10424 * "get()" function
10426 static void
10427 f_get(argvars, rettv)
10428 typval_T *argvars;
10429 typval_T *rettv;
10431 listitem_T *li;
10432 list_T *l;
10433 dictitem_T *di;
10434 dict_T *d;
10435 typval_T *tv = NULL;
10437 if (argvars[0].v_type == VAR_LIST)
10439 if ((l = argvars[0].vval.v_list) != NULL)
10441 int error = FALSE;
10443 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
10444 if (!error && li != NULL)
10445 tv = &li->li_tv;
10448 else if (argvars[0].v_type == VAR_DICT)
10450 if ((d = argvars[0].vval.v_dict) != NULL)
10452 di = dict_find(d, get_tv_string(&argvars[1]), -1);
10453 if (di != NULL)
10454 tv = &di->di_tv;
10457 else
10458 EMSG2(_(e_listdictarg), "get()");
10460 if (tv == NULL)
10462 if (argvars[2].v_type != VAR_UNKNOWN)
10463 copy_tv(&argvars[2], rettv);
10465 else
10466 copy_tv(tv, rettv);
10469 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
10472 * Get line or list of lines from buffer "buf" into "rettv".
10473 * Return a range (from start to end) of lines in rettv from the specified
10474 * buffer.
10475 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
10477 static void
10478 get_buffer_lines(buf, start, end, retlist, rettv)
10479 buf_T *buf;
10480 linenr_T start;
10481 linenr_T end;
10482 int retlist;
10483 typval_T *rettv;
10485 char_u *p;
10487 if (retlist && rettv_list_alloc(rettv) == FAIL)
10488 return;
10490 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
10491 return;
10493 if (!retlist)
10495 if (start >= 1 && start <= buf->b_ml.ml_line_count)
10496 p = ml_get_buf(buf, start, FALSE);
10497 else
10498 p = (char_u *)"";
10500 rettv->v_type = VAR_STRING;
10501 rettv->vval.v_string = vim_strsave(p);
10503 else
10505 if (end < start)
10506 return;
10508 if (start < 1)
10509 start = 1;
10510 if (end > buf->b_ml.ml_line_count)
10511 end = buf->b_ml.ml_line_count;
10512 while (start <= end)
10513 if (list_append_string(rettv->vval.v_list,
10514 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
10515 break;
10520 * "getbufline()" function
10522 static void
10523 f_getbufline(argvars, rettv)
10524 typval_T *argvars;
10525 typval_T *rettv;
10527 linenr_T lnum;
10528 linenr_T end;
10529 buf_T *buf;
10531 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10532 ++emsg_off;
10533 buf = get_buf_tv(&argvars[0]);
10534 --emsg_off;
10536 lnum = get_tv_lnum_buf(&argvars[1], buf);
10537 if (argvars[2].v_type == VAR_UNKNOWN)
10538 end = lnum;
10539 else
10540 end = get_tv_lnum_buf(&argvars[2], buf);
10542 get_buffer_lines(buf, lnum, end, TRUE, rettv);
10546 * "getbufvar()" function
10548 static void
10549 f_getbufvar(argvars, rettv)
10550 typval_T *argvars;
10551 typval_T *rettv;
10553 buf_T *buf;
10554 buf_T *save_curbuf;
10555 char_u *varname;
10556 dictitem_T *v;
10558 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10559 varname = get_tv_string_chk(&argvars[1]);
10560 ++emsg_off;
10561 buf = get_buf_tv(&argvars[0]);
10563 rettv->v_type = VAR_STRING;
10564 rettv->vval.v_string = NULL;
10566 if (buf != NULL && varname != NULL)
10568 /* set curbuf to be our buf, temporarily */
10569 save_curbuf = curbuf;
10570 curbuf = buf;
10572 if (*varname == '&') /* buffer-local-option */
10573 get_option_tv(&varname, rettv, TRUE);
10574 else
10576 if (*varname == NUL)
10577 /* let getbufvar({nr}, "") return the "b:" dictionary. The
10578 * scope prefix before the NUL byte is required by
10579 * find_var_in_ht(). */
10580 varname = (char_u *)"b:" + 2;
10581 /* look up the variable */
10582 v = find_var_in_ht(&curbuf->b_vars.dv_hashtab, varname, FALSE);
10583 if (v != NULL)
10584 copy_tv(&v->di_tv, rettv);
10587 /* restore previous notion of curbuf */
10588 curbuf = save_curbuf;
10591 --emsg_off;
10595 * "getchar()" function
10597 static void
10598 f_getchar(argvars, rettv)
10599 typval_T *argvars;
10600 typval_T *rettv;
10602 varnumber_T n;
10603 int error = FALSE;
10605 /* Position the cursor. Needed after a message that ends in a space. */
10606 windgoto(msg_row, msg_col);
10608 ++no_mapping;
10609 ++allow_keys;
10610 for (;;)
10612 if (argvars[0].v_type == VAR_UNKNOWN)
10613 /* getchar(): blocking wait. */
10614 n = safe_vgetc();
10615 else if (get_tv_number_chk(&argvars[0], &error) == 1)
10616 /* getchar(1): only check if char avail */
10617 n = vpeekc();
10618 else if (error || vpeekc() == NUL)
10619 /* illegal argument or getchar(0) and no char avail: return zero */
10620 n = 0;
10621 else
10622 /* getchar(0) and char avail: return char */
10623 n = safe_vgetc();
10624 if (n == K_IGNORE)
10625 continue;
10626 break;
10628 --no_mapping;
10629 --allow_keys;
10631 vimvars[VV_MOUSE_WIN].vv_nr = 0;
10632 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
10633 vimvars[VV_MOUSE_COL].vv_nr = 0;
10635 rettv->vval.v_number = n;
10636 if (IS_SPECIAL(n) || mod_mask != 0)
10638 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
10639 int i = 0;
10641 /* Turn a special key into three bytes, plus modifier. */
10642 if (mod_mask != 0)
10644 temp[i++] = K_SPECIAL;
10645 temp[i++] = KS_MODIFIER;
10646 temp[i++] = mod_mask;
10648 if (IS_SPECIAL(n))
10650 temp[i++] = K_SPECIAL;
10651 temp[i++] = K_SECOND(n);
10652 temp[i++] = K_THIRD(n);
10654 #ifdef FEAT_MBYTE
10655 else if (has_mbyte)
10656 i += (*mb_char2bytes)(n, temp + i);
10657 #endif
10658 else
10659 temp[i++] = n;
10660 temp[i++] = NUL;
10661 rettv->v_type = VAR_STRING;
10662 rettv->vval.v_string = vim_strsave(temp);
10664 #ifdef FEAT_MOUSE
10665 if (n == K_LEFTMOUSE
10666 || n == K_LEFTMOUSE_NM
10667 || n == K_LEFTDRAG
10668 || n == K_LEFTRELEASE
10669 || n == K_LEFTRELEASE_NM
10670 || n == K_MIDDLEMOUSE
10671 || n == K_MIDDLEDRAG
10672 || n == K_MIDDLERELEASE
10673 || n == K_RIGHTMOUSE
10674 || n == K_RIGHTDRAG
10675 || n == K_RIGHTRELEASE
10676 || n == K_X1MOUSE
10677 || n == K_X1DRAG
10678 || n == K_X1RELEASE
10679 || n == K_X2MOUSE
10680 || n == K_X2DRAG
10681 || n == K_X2RELEASE
10682 || n == K_MOUSEDOWN
10683 || n == K_MOUSEUP)
10685 int row = mouse_row;
10686 int col = mouse_col;
10687 win_T *win;
10688 linenr_T lnum;
10689 # ifdef FEAT_WINDOWS
10690 win_T *wp;
10691 # endif
10692 int winnr = 1;
10694 if (row >= 0 && col >= 0)
10696 /* Find the window at the mouse coordinates and compute the
10697 * text position. */
10698 win = mouse_find_win(&row, &col);
10699 (void)mouse_comp_pos(win, &row, &col, &lnum);
10700 # ifdef FEAT_WINDOWS
10701 for (wp = firstwin; wp != win; wp = wp->w_next)
10702 ++winnr;
10703 # endif
10704 vimvars[VV_MOUSE_WIN].vv_nr = winnr;
10705 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
10706 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
10709 #endif
10714 * "getcharmod()" function
10716 static void
10717 f_getcharmod(argvars, rettv)
10718 typval_T *argvars UNUSED;
10719 typval_T *rettv;
10721 rettv->vval.v_number = mod_mask;
10725 * "getcmdline()" function
10727 static void
10728 f_getcmdline(argvars, rettv)
10729 typval_T *argvars UNUSED;
10730 typval_T *rettv;
10732 rettv->v_type = VAR_STRING;
10733 rettv->vval.v_string = get_cmdline_str();
10737 * "getcmdpos()" function
10739 static void
10740 f_getcmdpos(argvars, rettv)
10741 typval_T *argvars UNUSED;
10742 typval_T *rettv;
10744 rettv->vval.v_number = get_cmdline_pos() + 1;
10748 * "getcmdtype()" function
10750 static void
10751 f_getcmdtype(argvars, rettv)
10752 typval_T *argvars UNUSED;
10753 typval_T *rettv;
10755 rettv->v_type = VAR_STRING;
10756 rettv->vval.v_string = alloc(2);
10757 if (rettv->vval.v_string != NULL)
10759 rettv->vval.v_string[0] = get_cmdline_type();
10760 rettv->vval.v_string[1] = NUL;
10765 * "getcwd()" function
10767 static void
10768 f_getcwd(argvars, rettv)
10769 typval_T *argvars UNUSED;
10770 typval_T *rettv;
10772 char_u cwd[MAXPATHL];
10774 rettv->v_type = VAR_STRING;
10775 if (mch_dirname(cwd, MAXPATHL) == FAIL)
10776 rettv->vval.v_string = NULL;
10777 else
10779 rettv->vval.v_string = vim_strsave(cwd);
10780 #ifdef BACKSLASH_IN_FILENAME
10781 if (rettv->vval.v_string != NULL)
10782 slash_adjust(rettv->vval.v_string);
10783 #endif
10788 * "getfontname()" function
10790 static void
10791 f_getfontname(argvars, rettv)
10792 typval_T *argvars UNUSED;
10793 typval_T *rettv;
10795 rettv->v_type = VAR_STRING;
10796 rettv->vval.v_string = NULL;
10797 #ifdef FEAT_GUI
10798 if (gui.in_use)
10800 GuiFont font;
10801 char_u *name = NULL;
10803 if (argvars[0].v_type == VAR_UNKNOWN)
10805 /* Get the "Normal" font. Either the name saved by
10806 * hl_set_font_name() or from the font ID. */
10807 font = gui.norm_font;
10808 name = hl_get_font_name();
10810 else
10812 name = get_tv_string(&argvars[0]);
10813 if (STRCMP(name, "*") == 0) /* don't use font dialog */
10814 return;
10815 font = gui_mch_get_font(name, FALSE);
10816 if (font == NOFONT)
10817 return; /* Invalid font name, return empty string. */
10819 rettv->vval.v_string = gui_mch_get_fontname(font, name);
10820 if (argvars[0].v_type != VAR_UNKNOWN)
10821 gui_mch_free_font(font);
10823 #endif
10827 * "getfperm({fname})" function
10829 static void
10830 f_getfperm(argvars, rettv)
10831 typval_T *argvars;
10832 typval_T *rettv;
10834 char_u *fname;
10835 struct stat st;
10836 char_u *perm = NULL;
10837 char_u flags[] = "rwx";
10838 int i;
10840 fname = get_tv_string(&argvars[0]);
10842 rettv->v_type = VAR_STRING;
10843 if (mch_stat((char *)fname, &st) >= 0)
10845 perm = vim_strsave((char_u *)"---------");
10846 if (perm != NULL)
10848 for (i = 0; i < 9; i++)
10850 if (st.st_mode & (1 << (8 - i)))
10851 perm[i] = flags[i % 3];
10855 rettv->vval.v_string = perm;
10859 * "getfsize({fname})" function
10861 static void
10862 f_getfsize(argvars, rettv)
10863 typval_T *argvars;
10864 typval_T *rettv;
10866 char_u *fname;
10867 struct stat st;
10869 fname = get_tv_string(&argvars[0]);
10871 rettv->v_type = VAR_NUMBER;
10873 if (mch_stat((char *)fname, &st) >= 0)
10875 if (mch_isdir(fname))
10876 rettv->vval.v_number = 0;
10877 else
10879 rettv->vval.v_number = (varnumber_T)st.st_size;
10881 /* non-perfect check for overflow */
10882 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
10883 rettv->vval.v_number = -2;
10886 else
10887 rettv->vval.v_number = -1;
10891 * "getftime({fname})" function
10893 static void
10894 f_getftime(argvars, rettv)
10895 typval_T *argvars;
10896 typval_T *rettv;
10898 char_u *fname;
10899 struct stat st;
10901 fname = get_tv_string(&argvars[0]);
10903 if (mch_stat((char *)fname, &st) >= 0)
10904 rettv->vval.v_number = (varnumber_T)st.st_mtime;
10905 else
10906 rettv->vval.v_number = -1;
10910 * "getftype({fname})" function
10912 static void
10913 f_getftype(argvars, rettv)
10914 typval_T *argvars;
10915 typval_T *rettv;
10917 char_u *fname;
10918 struct stat st;
10919 char_u *type = NULL;
10920 char *t;
10922 fname = get_tv_string(&argvars[0]);
10924 rettv->v_type = VAR_STRING;
10925 if (mch_lstat((char *)fname, &st) >= 0)
10927 #ifdef S_ISREG
10928 if (S_ISREG(st.st_mode))
10929 t = "file";
10930 else if (S_ISDIR(st.st_mode))
10931 t = "dir";
10932 # ifdef S_ISLNK
10933 else if (S_ISLNK(st.st_mode))
10934 t = "link";
10935 # endif
10936 # ifdef S_ISBLK
10937 else if (S_ISBLK(st.st_mode))
10938 t = "bdev";
10939 # endif
10940 # ifdef S_ISCHR
10941 else if (S_ISCHR(st.st_mode))
10942 t = "cdev";
10943 # endif
10944 # ifdef S_ISFIFO
10945 else if (S_ISFIFO(st.st_mode))
10946 t = "fifo";
10947 # endif
10948 # ifdef S_ISSOCK
10949 else if (S_ISSOCK(st.st_mode))
10950 t = "fifo";
10951 # endif
10952 else
10953 t = "other";
10954 #else
10955 # ifdef S_IFMT
10956 switch (st.st_mode & S_IFMT)
10958 case S_IFREG: t = "file"; break;
10959 case S_IFDIR: t = "dir"; break;
10960 # ifdef S_IFLNK
10961 case S_IFLNK: t = "link"; break;
10962 # endif
10963 # ifdef S_IFBLK
10964 case S_IFBLK: t = "bdev"; break;
10965 # endif
10966 # ifdef S_IFCHR
10967 case S_IFCHR: t = "cdev"; break;
10968 # endif
10969 # ifdef S_IFIFO
10970 case S_IFIFO: t = "fifo"; break;
10971 # endif
10972 # ifdef S_IFSOCK
10973 case S_IFSOCK: t = "socket"; break;
10974 # endif
10975 default: t = "other";
10977 # else
10978 if (mch_isdir(fname))
10979 t = "dir";
10980 else
10981 t = "file";
10982 # endif
10983 #endif
10984 type = vim_strsave((char_u *)t);
10986 rettv->vval.v_string = type;
10990 * "getline(lnum, [end])" function
10992 static void
10993 f_getline(argvars, rettv)
10994 typval_T *argvars;
10995 typval_T *rettv;
10997 linenr_T lnum;
10998 linenr_T end;
10999 int retlist;
11001 lnum = get_tv_lnum(argvars);
11002 if (argvars[1].v_type == VAR_UNKNOWN)
11004 end = 0;
11005 retlist = FALSE;
11007 else
11009 end = get_tv_lnum(&argvars[1]);
11010 retlist = TRUE;
11013 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
11017 * "getmatches()" function
11019 static void
11020 f_getmatches(argvars, rettv)
11021 typval_T *argvars UNUSED;
11022 typval_T *rettv;
11024 #ifdef FEAT_SEARCH_EXTRA
11025 dict_T *dict;
11026 matchitem_T *cur = curwin->w_match_head;
11028 if (rettv_list_alloc(rettv) == OK)
11030 while (cur != NULL)
11032 dict = dict_alloc();
11033 if (dict == NULL)
11034 return;
11035 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
11036 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
11037 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
11038 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
11039 list_append_dict(rettv->vval.v_list, dict);
11040 cur = cur->next;
11043 #endif
11047 * "getpid()" function
11049 static void
11050 f_getpid(argvars, rettv)
11051 typval_T *argvars UNUSED;
11052 typval_T *rettv;
11054 rettv->vval.v_number = mch_get_pid();
11058 * "getpos(string)" function
11060 static void
11061 f_getpos(argvars, rettv)
11062 typval_T *argvars;
11063 typval_T *rettv;
11065 pos_T *fp;
11066 list_T *l;
11067 int fnum = -1;
11069 if (rettv_list_alloc(rettv) == OK)
11071 l = rettv->vval.v_list;
11072 fp = var2fpos(&argvars[0], TRUE, &fnum);
11073 if (fnum != -1)
11074 list_append_number(l, (varnumber_T)fnum);
11075 else
11076 list_append_number(l, (varnumber_T)0);
11077 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
11078 : (varnumber_T)0);
11079 list_append_number(l, (fp != NULL)
11080 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
11081 : (varnumber_T)0);
11082 list_append_number(l,
11083 #ifdef FEAT_VIRTUALEDIT
11084 (fp != NULL) ? (varnumber_T)fp->coladd :
11085 #endif
11086 (varnumber_T)0);
11088 else
11089 rettv->vval.v_number = FALSE;
11093 * "getqflist()" and "getloclist()" functions
11095 static void
11096 f_getqflist(argvars, rettv)
11097 typval_T *argvars UNUSED;
11098 typval_T *rettv UNUSED;
11100 #ifdef FEAT_QUICKFIX
11101 win_T *wp;
11102 #endif
11104 #ifdef FEAT_QUICKFIX
11105 if (rettv_list_alloc(rettv) == OK)
11107 wp = NULL;
11108 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
11110 wp = find_win_by_nr(&argvars[0], NULL);
11111 if (wp == NULL)
11112 return;
11115 (void)get_errorlist(wp, rettv->vval.v_list);
11117 #endif
11121 * "getreg()" function
11123 static void
11124 f_getreg(argvars, rettv)
11125 typval_T *argvars;
11126 typval_T *rettv;
11128 char_u *strregname;
11129 int regname;
11130 int arg2 = FALSE;
11131 int error = FALSE;
11133 if (argvars[0].v_type != VAR_UNKNOWN)
11135 strregname = get_tv_string_chk(&argvars[0]);
11136 error = strregname == NULL;
11137 if (argvars[1].v_type != VAR_UNKNOWN)
11138 arg2 = get_tv_number_chk(&argvars[1], &error);
11140 else
11141 strregname = vimvars[VV_REG].vv_str;
11142 regname = (strregname == NULL ? '"' : *strregname);
11143 if (regname == 0)
11144 regname = '"';
11146 rettv->v_type = VAR_STRING;
11147 rettv->vval.v_string = error ? NULL :
11148 get_reg_contents(regname, TRUE, arg2);
11152 * "getregtype()" function
11154 static void
11155 f_getregtype(argvars, rettv)
11156 typval_T *argvars;
11157 typval_T *rettv;
11159 char_u *strregname;
11160 int regname;
11161 char_u buf[NUMBUFLEN + 2];
11162 long reglen = 0;
11164 if (argvars[0].v_type != VAR_UNKNOWN)
11166 strregname = get_tv_string_chk(&argvars[0]);
11167 if (strregname == NULL) /* type error; errmsg already given */
11169 rettv->v_type = VAR_STRING;
11170 rettv->vval.v_string = NULL;
11171 return;
11174 else
11175 /* Default to v:register */
11176 strregname = vimvars[VV_REG].vv_str;
11178 regname = (strregname == NULL ? '"' : *strregname);
11179 if (regname == 0)
11180 regname = '"';
11182 buf[0] = NUL;
11183 buf[1] = NUL;
11184 switch (get_reg_type(regname, &reglen))
11186 case MLINE: buf[0] = 'V'; break;
11187 case MCHAR: buf[0] = 'v'; break;
11188 #ifdef FEAT_VISUAL
11189 case MBLOCK:
11190 buf[0] = Ctrl_V;
11191 sprintf((char *)buf + 1, "%ld", reglen + 1);
11192 break;
11193 #endif
11195 rettv->v_type = VAR_STRING;
11196 rettv->vval.v_string = vim_strsave(buf);
11200 * "gettabwinvar()" function
11202 static void
11203 f_gettabwinvar(argvars, rettv)
11204 typval_T *argvars;
11205 typval_T *rettv;
11207 getwinvar(argvars, rettv, 1);
11211 * "getwinposx()" function
11213 static void
11214 f_getwinposx(argvars, rettv)
11215 typval_T *argvars UNUSED;
11216 typval_T *rettv;
11218 rettv->vval.v_number = -1;
11219 #ifdef FEAT_GUI
11220 if (gui.in_use)
11222 int x, y;
11224 if (gui_mch_get_winpos(&x, &y) == OK)
11225 rettv->vval.v_number = x;
11227 #endif
11231 * "getwinposy()" function
11233 static void
11234 f_getwinposy(argvars, rettv)
11235 typval_T *argvars UNUSED;
11236 typval_T *rettv;
11238 rettv->vval.v_number = -1;
11239 #ifdef FEAT_GUI
11240 if (gui.in_use)
11242 int x, y;
11244 if (gui_mch_get_winpos(&x, &y) == OK)
11245 rettv->vval.v_number = y;
11247 #endif
11251 * Find window specified by "vp" in tabpage "tp".
11253 static win_T *
11254 find_win_by_nr(vp, tp)
11255 typval_T *vp;
11256 tabpage_T *tp; /* NULL for current tab page */
11258 #ifdef FEAT_WINDOWS
11259 win_T *wp;
11260 #endif
11261 int nr;
11263 nr = get_tv_number_chk(vp, NULL);
11265 #ifdef FEAT_WINDOWS
11266 if (nr < 0)
11267 return NULL;
11268 if (nr == 0)
11269 return curwin;
11271 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
11272 wp != NULL; wp = wp->w_next)
11273 if (--nr <= 0)
11274 break;
11275 return wp;
11276 #else
11277 if (nr == 0 || nr == 1)
11278 return curwin;
11279 return NULL;
11280 #endif
11284 * "getwinvar()" function
11286 static void
11287 f_getwinvar(argvars, rettv)
11288 typval_T *argvars;
11289 typval_T *rettv;
11291 getwinvar(argvars, rettv, 0);
11295 * getwinvar() and gettabwinvar()
11297 static void
11298 getwinvar(argvars, rettv, off)
11299 typval_T *argvars;
11300 typval_T *rettv;
11301 int off; /* 1 for gettabwinvar() */
11303 win_T *win, *oldcurwin;
11304 char_u *varname;
11305 dictitem_T *v;
11306 tabpage_T *tp;
11308 #ifdef FEAT_WINDOWS
11309 if (off == 1)
11310 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
11311 else
11312 tp = curtab;
11313 #endif
11314 win = find_win_by_nr(&argvars[off], tp);
11315 varname = get_tv_string_chk(&argvars[off + 1]);
11316 ++emsg_off;
11318 rettv->v_type = VAR_STRING;
11319 rettv->vval.v_string = NULL;
11321 if (win != NULL && varname != NULL)
11323 /* Set curwin to be our win, temporarily. Also set curbuf, so
11324 * that we can get buffer-local options. */
11325 oldcurwin = curwin;
11326 curwin = win;
11327 curbuf = win->w_buffer;
11329 if (*varname == '&') /* window-local-option */
11330 get_option_tv(&varname, rettv, 1);
11331 else
11333 if (*varname == NUL)
11334 /* let getwinvar({nr}, "") return the "w:" dictionary. The
11335 * scope prefix before the NUL byte is required by
11336 * find_var_in_ht(). */
11337 varname = (char_u *)"w:" + 2;
11338 /* look up the variable */
11339 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
11340 if (v != NULL)
11341 copy_tv(&v->di_tv, rettv);
11344 /* restore previous notion of curwin */
11345 curwin = oldcurwin;
11346 curbuf = curwin->w_buffer;
11349 --emsg_off;
11353 * "glob()" function
11355 static void
11356 f_glob(argvars, rettv)
11357 typval_T *argvars;
11358 typval_T *rettv;
11360 int flags = WILD_SILENT|WILD_USE_NL;
11361 expand_T xpc;
11362 int error = FALSE;
11364 /* When the optional second argument is non-zero, don't remove matches
11365 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11366 if (argvars[1].v_type != VAR_UNKNOWN
11367 && get_tv_number_chk(&argvars[1], &error))
11368 flags |= WILD_KEEP_ALL;
11369 rettv->v_type = VAR_STRING;
11370 if (!error)
11372 ExpandInit(&xpc);
11373 xpc.xp_context = EXPAND_FILES;
11374 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
11375 NULL, flags, WILD_ALL);
11377 else
11378 rettv->vval.v_string = NULL;
11382 * "globpath()" function
11384 static void
11385 f_globpath(argvars, rettv)
11386 typval_T *argvars;
11387 typval_T *rettv;
11389 int flags = 0;
11390 char_u buf1[NUMBUFLEN];
11391 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
11392 int error = FALSE;
11394 /* When the optional second argument is non-zero, don't remove matches
11395 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11396 if (argvars[2].v_type != VAR_UNKNOWN
11397 && get_tv_number_chk(&argvars[2], &error))
11398 flags |= WILD_KEEP_ALL;
11399 rettv->v_type = VAR_STRING;
11400 if (file == NULL || error)
11401 rettv->vval.v_string = NULL;
11402 else
11403 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file,
11404 flags);
11408 * "has()" function
11410 static void
11411 f_has(argvars, rettv)
11412 typval_T *argvars;
11413 typval_T *rettv;
11415 int i;
11416 char_u *name;
11417 int n = FALSE;
11418 static char *(has_list[]) =
11420 #ifdef AMIGA
11421 "amiga",
11422 # ifdef FEAT_ARP
11423 "arp",
11424 # endif
11425 #endif
11426 #ifdef __BEOS__
11427 "beos",
11428 #endif
11429 #ifdef MSDOS
11430 # ifdef DJGPP
11431 "dos32",
11432 # else
11433 "dos16",
11434 # endif
11435 #endif
11436 #ifdef MACOS
11437 "mac",
11438 #endif
11439 #if defined(MACOS_X_UNIX)
11440 "macunix",
11441 #endif
11442 #ifdef OS2
11443 "os2",
11444 #endif
11445 #ifdef __QNX__
11446 "qnx",
11447 #endif
11448 #ifdef RISCOS
11449 "riscos",
11450 #endif
11451 #ifdef UNIX
11452 "unix",
11453 #endif
11454 #ifdef VMS
11455 "vms",
11456 #endif
11457 #ifdef WIN16
11458 "win16",
11459 #endif
11460 #ifdef WIN32
11461 "win32",
11462 #endif
11463 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
11464 "win32unix",
11465 #endif
11466 #if defined(WIN64) || defined(_WIN64)
11467 "win64",
11468 #endif
11469 #ifdef EBCDIC
11470 "ebcdic",
11471 #endif
11472 #ifndef CASE_INSENSITIVE_FILENAME
11473 "fname_case",
11474 #endif
11475 #ifdef FEAT_ARABIC
11476 "arabic",
11477 #endif
11478 #ifdef FEAT_AUTOCMD
11479 "autocmd",
11480 #endif
11481 #ifdef FEAT_BEVAL
11482 "balloon_eval",
11483 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
11484 "balloon_multiline",
11485 # endif
11486 #endif
11487 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
11488 "builtin_terms",
11489 # ifdef ALL_BUILTIN_TCAPS
11490 "all_builtin_terms",
11491 # endif
11492 #endif
11493 #ifdef FEAT_BYTEOFF
11494 "byte_offset",
11495 #endif
11496 #ifdef FEAT_CINDENT
11497 "cindent",
11498 #endif
11499 #ifdef FEAT_CLIENTSERVER
11500 "clientserver",
11501 #endif
11502 #ifdef FEAT_CLIPBOARD
11503 "clipboard",
11504 #endif
11505 #ifdef FEAT_CMDL_COMPL
11506 "cmdline_compl",
11507 #endif
11508 #ifdef FEAT_CMDHIST
11509 "cmdline_hist",
11510 #endif
11511 #ifdef FEAT_COMMENTS
11512 "comments",
11513 #endif
11514 #ifdef FEAT_CRYPT
11515 "cryptv",
11516 #endif
11517 #ifdef FEAT_CSCOPE
11518 "cscope",
11519 #endif
11520 #ifdef CURSOR_SHAPE
11521 "cursorshape",
11522 #endif
11523 #ifdef DEBUG
11524 "debug",
11525 #endif
11526 #ifdef FEAT_CON_DIALOG
11527 "dialog_con",
11528 #endif
11529 #ifdef FEAT_GUI_DIALOG
11530 "dialog_gui",
11531 #endif
11532 #ifdef FEAT_DIFF
11533 "diff",
11534 #endif
11535 #ifdef FEAT_DIGRAPHS
11536 "digraphs",
11537 #endif
11538 #ifdef FEAT_DND
11539 "dnd",
11540 #endif
11541 #ifdef FEAT_EMACS_TAGS
11542 "emacs_tags",
11543 #endif
11544 "eval", /* always present, of course! */
11545 #ifdef FEAT_EX_EXTRA
11546 "ex_extra",
11547 #endif
11548 #ifdef FEAT_SEARCH_EXTRA
11549 "extra_search",
11550 #endif
11551 #ifdef FEAT_FKMAP
11552 "farsi",
11553 #endif
11554 #ifdef FEAT_SEARCHPATH
11555 "file_in_path",
11556 #endif
11557 #if defined(UNIX) && !defined(USE_SYSTEM)
11558 "filterpipe",
11559 #endif
11560 #ifdef FEAT_FIND_ID
11561 "find_in_path",
11562 #endif
11563 #ifdef FEAT_FLOAT
11564 "float",
11565 #endif
11566 #ifdef FEAT_FOLDING
11567 "folding",
11568 #endif
11569 #ifdef FEAT_FOOTER
11570 "footer",
11571 #endif
11572 #if !defined(USE_SYSTEM) && defined(UNIX)
11573 "fork",
11574 #endif
11575 #ifdef FEAT_GETTEXT
11576 "gettext",
11577 #endif
11578 #ifdef FEAT_GUI
11579 "gui",
11580 #endif
11581 #ifdef FEAT_GUI_ATHENA
11582 # ifdef FEAT_GUI_NEXTAW
11583 "gui_neXtaw",
11584 # else
11585 "gui_athena",
11586 # endif
11587 #endif
11588 #ifdef FEAT_GUI_GTK
11589 "gui_gtk",
11590 # ifdef HAVE_GTK2
11591 "gui_gtk2",
11592 # endif
11593 #endif
11594 #ifdef FEAT_GUI_GNOME
11595 "gui_gnome",
11596 #endif
11597 #ifdef FEAT_GUI_MAC
11598 "gui_mac",
11599 #endif
11600 #ifdef FEAT_GUI_MOTIF
11601 "gui_motif",
11602 #endif
11603 #ifdef FEAT_GUI_PHOTON
11604 "gui_photon",
11605 #endif
11606 #ifdef FEAT_GUI_W16
11607 "gui_win16",
11608 #endif
11609 #ifdef FEAT_GUI_W32
11610 "gui_win32",
11611 #endif
11612 #ifdef FEAT_HANGULIN
11613 "hangul_input",
11614 #endif
11615 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
11616 "iconv",
11617 #endif
11618 #ifdef FEAT_INS_EXPAND
11619 "insert_expand",
11620 #endif
11621 #ifdef FEAT_JUMPLIST
11622 "jumplist",
11623 #endif
11624 #ifdef FEAT_KEYMAP
11625 "keymap",
11626 #endif
11627 #ifdef FEAT_LANGMAP
11628 "langmap",
11629 #endif
11630 #ifdef FEAT_LIBCALL
11631 "libcall",
11632 #endif
11633 #ifdef FEAT_LINEBREAK
11634 "linebreak",
11635 #endif
11636 #ifdef FEAT_LISP
11637 "lispindent",
11638 #endif
11639 #ifdef FEAT_LISTCMDS
11640 "listcmds",
11641 #endif
11642 #ifdef FEAT_LOCALMAP
11643 "localmap",
11644 #endif
11645 #ifdef FEAT_MENU
11646 "menu",
11647 #endif
11648 #ifdef FEAT_SESSION
11649 "mksession",
11650 #endif
11651 #ifdef FEAT_MODIFY_FNAME
11652 "modify_fname",
11653 #endif
11654 #ifdef FEAT_MOUSE
11655 "mouse",
11656 #endif
11657 #ifdef FEAT_MOUSESHAPE
11658 "mouseshape",
11659 #endif
11660 #if defined(UNIX) || defined(VMS)
11661 # ifdef FEAT_MOUSE_DEC
11662 "mouse_dec",
11663 # endif
11664 # ifdef FEAT_MOUSE_GPM
11665 "mouse_gpm",
11666 # endif
11667 # ifdef FEAT_MOUSE_JSB
11668 "mouse_jsbterm",
11669 # endif
11670 # ifdef FEAT_MOUSE_NET
11671 "mouse_netterm",
11672 # endif
11673 # ifdef FEAT_MOUSE_PTERM
11674 "mouse_pterm",
11675 # endif
11676 # ifdef FEAT_SYSMOUSE
11677 "mouse_sysmouse",
11678 # endif
11679 # ifdef FEAT_MOUSE_XTERM
11680 "mouse_xterm",
11681 # endif
11682 #endif
11683 #ifdef FEAT_MBYTE
11684 "multi_byte",
11685 #endif
11686 #ifdef FEAT_MBYTE_IME
11687 "multi_byte_ime",
11688 #endif
11689 #ifdef FEAT_MULTI_LANG
11690 "multi_lang",
11691 #endif
11692 #ifdef FEAT_MZSCHEME
11693 #ifndef DYNAMIC_MZSCHEME
11694 "mzscheme",
11695 #endif
11696 #endif
11697 #ifdef FEAT_OLE
11698 "ole",
11699 #endif
11700 #ifdef FEAT_OSFILETYPE
11701 "osfiletype",
11702 #endif
11703 #ifdef FEAT_PATH_EXTRA
11704 "path_extra",
11705 #endif
11706 #ifdef FEAT_PERL
11707 #ifndef DYNAMIC_PERL
11708 "perl",
11709 #endif
11710 #endif
11711 #ifdef FEAT_PYTHON
11712 #ifndef DYNAMIC_PYTHON
11713 "python",
11714 #endif
11715 #endif
11716 #ifdef FEAT_POSTSCRIPT
11717 "postscript",
11718 #endif
11719 #ifdef FEAT_PRINTER
11720 "printer",
11721 #endif
11722 #ifdef FEAT_PROFILE
11723 "profile",
11724 #endif
11725 #ifdef FEAT_RELTIME
11726 "reltime",
11727 #endif
11728 #ifdef FEAT_QUICKFIX
11729 "quickfix",
11730 #endif
11731 #ifdef FEAT_RIGHTLEFT
11732 "rightleft",
11733 #endif
11734 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11735 "ruby",
11736 #endif
11737 #ifdef FEAT_SCROLLBIND
11738 "scrollbind",
11739 #endif
11740 #ifdef FEAT_CMDL_INFO
11741 "showcmd",
11742 "cmdline_info",
11743 #endif
11744 #ifdef FEAT_SIGNS
11745 "signs",
11746 #endif
11747 #ifdef FEAT_SMARTINDENT
11748 "smartindent",
11749 #endif
11750 #ifdef FEAT_SNIFF
11751 "sniff",
11752 #endif
11753 #ifdef STARTUPTIME
11754 "startuptime",
11755 #endif
11756 #ifdef FEAT_STL_OPT
11757 "statusline",
11758 #endif
11759 #ifdef FEAT_SUN_WORKSHOP
11760 "sun_workshop",
11761 #endif
11762 #ifdef FEAT_NETBEANS_INTG
11763 "netbeans_intg",
11764 #endif
11765 #ifdef FEAT_SPELL
11766 "spell",
11767 #endif
11768 #ifdef FEAT_SYN_HL
11769 "syntax",
11770 #endif
11771 #if defined(USE_SYSTEM) || !defined(UNIX)
11772 "system",
11773 #endif
11774 #ifdef FEAT_TAG_BINS
11775 "tag_binary",
11776 #endif
11777 #ifdef FEAT_TAG_OLDSTATIC
11778 "tag_old_static",
11779 #endif
11780 #ifdef FEAT_TAG_ANYWHITE
11781 "tag_any_white",
11782 #endif
11783 #ifdef FEAT_TCL
11784 # ifndef DYNAMIC_TCL
11785 "tcl",
11786 # endif
11787 #endif
11788 #ifdef TERMINFO
11789 "terminfo",
11790 #endif
11791 #ifdef FEAT_TERMRESPONSE
11792 "termresponse",
11793 #endif
11794 #ifdef FEAT_TEXTOBJ
11795 "textobjects",
11796 #endif
11797 #ifdef HAVE_TGETENT
11798 "tgetent",
11799 #endif
11800 #ifdef FEAT_TITLE
11801 "title",
11802 #endif
11803 #ifdef FEAT_TOOLBAR
11804 "toolbar",
11805 #endif
11806 #ifdef FEAT_USR_CMDS
11807 "user-commands", /* was accidentally included in 5.4 */
11808 "user_commands",
11809 #endif
11810 #ifdef FEAT_VIMINFO
11811 "viminfo",
11812 #endif
11813 #ifdef FEAT_VERTSPLIT
11814 "vertsplit",
11815 #endif
11816 #ifdef FEAT_VIRTUALEDIT
11817 "virtualedit",
11818 #endif
11819 #ifdef FEAT_VISUAL
11820 "visual",
11821 #endif
11822 #ifdef FEAT_VISUALEXTRA
11823 "visualextra",
11824 #endif
11825 #ifdef FEAT_VREPLACE
11826 "vreplace",
11827 #endif
11828 #ifdef FEAT_WILDIGN
11829 "wildignore",
11830 #endif
11831 #ifdef FEAT_WILDMENU
11832 "wildmenu",
11833 #endif
11834 #ifdef FEAT_WINDOWS
11835 "windows",
11836 #endif
11837 #ifdef FEAT_WAK
11838 "winaltkeys",
11839 #endif
11840 #ifdef FEAT_WRITEBACKUP
11841 "writebackup",
11842 #endif
11843 #ifdef FEAT_XIM
11844 "xim",
11845 #endif
11846 #ifdef FEAT_XFONTSET
11847 "xfontset",
11848 #endif
11849 #ifdef USE_XSMP
11850 "xsmp",
11851 #endif
11852 #ifdef USE_XSMP_INTERACT
11853 "xsmp_interact",
11854 #endif
11855 #ifdef FEAT_XCLIPBOARD
11856 "xterm_clipboard",
11857 #endif
11858 #ifdef FEAT_XTERM_SAVE
11859 "xterm_save",
11860 #endif
11861 #if defined(UNIX) && defined(FEAT_X11)
11862 "X11",
11863 #endif
11864 NULL
11867 name = get_tv_string(&argvars[0]);
11868 for (i = 0; has_list[i] != NULL; ++i)
11869 if (STRICMP(name, has_list[i]) == 0)
11871 n = TRUE;
11872 break;
11875 if (n == FALSE)
11877 if (STRNICMP(name, "patch", 5) == 0)
11878 n = has_patch(atoi((char *)name + 5));
11879 else if (STRICMP(name, "vim_starting") == 0)
11880 n = (starting != 0);
11881 #ifdef FEAT_MBYTE
11882 else if (STRICMP(name, "multi_byte_encoding") == 0)
11883 n = has_mbyte;
11884 #endif
11885 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
11886 else if (STRICMP(name, "balloon_multiline") == 0)
11887 n = multiline_balloon_available();
11888 #endif
11889 #ifdef DYNAMIC_TCL
11890 else if (STRICMP(name, "tcl") == 0)
11891 n = tcl_enabled(FALSE);
11892 #endif
11893 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
11894 else if (STRICMP(name, "iconv") == 0)
11895 n = iconv_enabled(FALSE);
11896 #endif
11897 #ifdef DYNAMIC_MZSCHEME
11898 else if (STRICMP(name, "mzscheme") == 0)
11899 n = mzscheme_enabled(FALSE);
11900 #endif
11901 #ifdef DYNAMIC_RUBY
11902 else if (STRICMP(name, "ruby") == 0)
11903 n = ruby_enabled(FALSE);
11904 #endif
11905 #ifdef DYNAMIC_PYTHON
11906 else if (STRICMP(name, "python") == 0)
11907 n = python_enabled(FALSE);
11908 #endif
11909 #ifdef DYNAMIC_PERL
11910 else if (STRICMP(name, "perl") == 0)
11911 n = perl_enabled(FALSE);
11912 #endif
11913 #ifdef FEAT_GUI
11914 else if (STRICMP(name, "gui_running") == 0)
11915 n = (gui.in_use || gui.starting);
11916 # ifdef FEAT_GUI_W32
11917 else if (STRICMP(name, "gui_win32s") == 0)
11918 n = gui_is_win32s();
11919 # endif
11920 # ifdef FEAT_BROWSE
11921 else if (STRICMP(name, "browse") == 0)
11922 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
11923 # endif
11924 #endif
11925 #ifdef FEAT_SYN_HL
11926 else if (STRICMP(name, "syntax_items") == 0)
11927 n = syntax_present(curbuf);
11928 #endif
11929 #if defined(WIN3264)
11930 else if (STRICMP(name, "win95") == 0)
11931 n = mch_windows95();
11932 #endif
11933 #ifdef FEAT_NETBEANS_INTG
11934 else if (STRICMP(name, "netbeans_enabled") == 0)
11935 n = usingNetbeans;
11936 #endif
11939 rettv->vval.v_number = n;
11943 * "has_key()" function
11945 static void
11946 f_has_key(argvars, rettv)
11947 typval_T *argvars;
11948 typval_T *rettv;
11950 if (argvars[0].v_type != VAR_DICT)
11952 EMSG(_(e_dictreq));
11953 return;
11955 if (argvars[0].vval.v_dict == NULL)
11956 return;
11958 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
11959 get_tv_string(&argvars[1]), -1) != NULL;
11963 * "haslocaldir()" function
11965 static void
11966 f_haslocaldir(argvars, rettv)
11967 typval_T *argvars UNUSED;
11968 typval_T *rettv;
11970 rettv->vval.v_number = (curwin->w_localdir != NULL);
11974 * "hasmapto()" function
11976 static void
11977 f_hasmapto(argvars, rettv)
11978 typval_T *argvars;
11979 typval_T *rettv;
11981 char_u *name;
11982 char_u *mode;
11983 char_u buf[NUMBUFLEN];
11984 int abbr = FALSE;
11986 name = get_tv_string(&argvars[0]);
11987 if (argvars[1].v_type == VAR_UNKNOWN)
11988 mode = (char_u *)"nvo";
11989 else
11991 mode = get_tv_string_buf(&argvars[1], buf);
11992 if (argvars[2].v_type != VAR_UNKNOWN)
11993 abbr = get_tv_number(&argvars[2]);
11996 if (map_to_exists(name, mode, abbr))
11997 rettv->vval.v_number = TRUE;
11998 else
11999 rettv->vval.v_number = FALSE;
12003 * "histadd()" function
12005 static void
12006 f_histadd(argvars, rettv)
12007 typval_T *argvars UNUSED;
12008 typval_T *rettv;
12010 #ifdef FEAT_CMDHIST
12011 int histype;
12012 char_u *str;
12013 char_u buf[NUMBUFLEN];
12014 #endif
12016 rettv->vval.v_number = FALSE;
12017 if (check_restricted() || check_secure())
12018 return;
12019 #ifdef FEAT_CMDHIST
12020 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12021 histype = str != NULL ? get_histtype(str) : -1;
12022 if (histype >= 0)
12024 str = get_tv_string_buf(&argvars[1], buf);
12025 if (*str != NUL)
12027 init_history();
12028 add_to_history(histype, str, FALSE, NUL);
12029 rettv->vval.v_number = TRUE;
12030 return;
12033 #endif
12037 * "histdel()" function
12039 static void
12040 f_histdel(argvars, rettv)
12041 typval_T *argvars UNUSED;
12042 typval_T *rettv UNUSED;
12044 #ifdef FEAT_CMDHIST
12045 int n;
12046 char_u buf[NUMBUFLEN];
12047 char_u *str;
12049 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12050 if (str == NULL)
12051 n = 0;
12052 else if (argvars[1].v_type == VAR_UNKNOWN)
12053 /* only one argument: clear entire history */
12054 n = clr_history(get_histtype(str));
12055 else if (argvars[1].v_type == VAR_NUMBER)
12056 /* index given: remove that entry */
12057 n = del_history_idx(get_histtype(str),
12058 (int)get_tv_number(&argvars[1]));
12059 else
12060 /* string given: remove all matching entries */
12061 n = del_history_entry(get_histtype(str),
12062 get_tv_string_buf(&argvars[1], buf));
12063 rettv->vval.v_number = n;
12064 #endif
12068 * "histget()" function
12070 static void
12071 f_histget(argvars, rettv)
12072 typval_T *argvars UNUSED;
12073 typval_T *rettv;
12075 #ifdef FEAT_CMDHIST
12076 int type;
12077 int idx;
12078 char_u *str;
12080 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12081 if (str == NULL)
12082 rettv->vval.v_string = NULL;
12083 else
12085 type = get_histtype(str);
12086 if (argvars[1].v_type == VAR_UNKNOWN)
12087 idx = get_history_idx(type);
12088 else
12089 idx = (int)get_tv_number_chk(&argvars[1], NULL);
12090 /* -1 on type error */
12091 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
12093 #else
12094 rettv->vval.v_string = NULL;
12095 #endif
12096 rettv->v_type = VAR_STRING;
12100 * "histnr()" function
12102 static void
12103 f_histnr(argvars, rettv)
12104 typval_T *argvars UNUSED;
12105 typval_T *rettv;
12107 int i;
12109 #ifdef FEAT_CMDHIST
12110 char_u *history = get_tv_string_chk(&argvars[0]);
12112 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
12113 if (i >= HIST_CMD && i < HIST_COUNT)
12114 i = get_history_idx(i);
12115 else
12116 #endif
12117 i = -1;
12118 rettv->vval.v_number = i;
12122 * "highlightID(name)" function
12124 static void
12125 f_hlID(argvars, rettv)
12126 typval_T *argvars;
12127 typval_T *rettv;
12129 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
12133 * "highlight_exists()" function
12135 static void
12136 f_hlexists(argvars, rettv)
12137 typval_T *argvars;
12138 typval_T *rettv;
12140 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
12144 * "hostname()" function
12146 static void
12147 f_hostname(argvars, rettv)
12148 typval_T *argvars UNUSED;
12149 typval_T *rettv;
12151 char_u hostname[256];
12153 mch_get_host_name(hostname, 256);
12154 rettv->v_type = VAR_STRING;
12155 rettv->vval.v_string = vim_strsave(hostname);
12159 * iconv() function
12161 static void
12162 f_iconv(argvars, rettv)
12163 typval_T *argvars UNUSED;
12164 typval_T *rettv;
12166 #ifdef FEAT_MBYTE
12167 char_u buf1[NUMBUFLEN];
12168 char_u buf2[NUMBUFLEN];
12169 char_u *from, *to, *str;
12170 vimconv_T vimconv;
12171 #endif
12173 rettv->v_type = VAR_STRING;
12174 rettv->vval.v_string = NULL;
12176 #ifdef FEAT_MBYTE
12177 str = get_tv_string(&argvars[0]);
12178 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
12179 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
12180 vimconv.vc_type = CONV_NONE;
12181 convert_setup(&vimconv, from, to);
12183 /* If the encodings are equal, no conversion needed. */
12184 if (vimconv.vc_type == CONV_NONE)
12185 rettv->vval.v_string = vim_strsave(str);
12186 else
12187 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
12189 convert_setup(&vimconv, NULL, NULL);
12190 vim_free(from);
12191 vim_free(to);
12192 #endif
12196 * "indent()" function
12198 static void
12199 f_indent(argvars, rettv)
12200 typval_T *argvars;
12201 typval_T *rettv;
12203 linenr_T lnum;
12205 lnum = get_tv_lnum(argvars);
12206 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12207 rettv->vval.v_number = get_indent_lnum(lnum);
12208 else
12209 rettv->vval.v_number = -1;
12213 * "index()" function
12215 static void
12216 f_index(argvars, rettv)
12217 typval_T *argvars;
12218 typval_T *rettv;
12220 list_T *l;
12221 listitem_T *item;
12222 long idx = 0;
12223 int ic = FALSE;
12225 rettv->vval.v_number = -1;
12226 if (argvars[0].v_type != VAR_LIST)
12228 EMSG(_(e_listreq));
12229 return;
12231 l = argvars[0].vval.v_list;
12232 if (l != NULL)
12234 item = l->lv_first;
12235 if (argvars[2].v_type != VAR_UNKNOWN)
12237 int error = FALSE;
12239 /* Start at specified item. Use the cached index that list_find()
12240 * sets, so that a negative number also works. */
12241 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
12242 idx = l->lv_idx;
12243 if (argvars[3].v_type != VAR_UNKNOWN)
12244 ic = get_tv_number_chk(&argvars[3], &error);
12245 if (error)
12246 item = NULL;
12249 for ( ; item != NULL; item = item->li_next, ++idx)
12250 if (tv_equal(&item->li_tv, &argvars[1], ic))
12252 rettv->vval.v_number = idx;
12253 break;
12258 static int inputsecret_flag = 0;
12260 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
12263 * This function is used by f_input() and f_inputdialog() functions. The third
12264 * argument to f_input() specifies the type of completion to use at the
12265 * prompt. The third argument to f_inputdialog() specifies the value to return
12266 * when the user cancels the prompt.
12268 static void
12269 get_user_input(argvars, rettv, inputdialog)
12270 typval_T *argvars;
12271 typval_T *rettv;
12272 int inputdialog;
12274 char_u *prompt = get_tv_string_chk(&argvars[0]);
12275 char_u *p = NULL;
12276 int c;
12277 char_u buf[NUMBUFLEN];
12278 int cmd_silent_save = cmd_silent;
12279 char_u *defstr = (char_u *)"";
12280 int xp_type = EXPAND_NOTHING;
12281 char_u *xp_arg = NULL;
12283 rettv->v_type = VAR_STRING;
12284 rettv->vval.v_string = NULL;
12286 #ifdef NO_CONSOLE_INPUT
12287 /* While starting up, there is no place to enter text. */
12288 if (no_console_input())
12289 return;
12290 #endif
12292 cmd_silent = FALSE; /* Want to see the prompt. */
12293 if (prompt != NULL)
12295 /* Only the part of the message after the last NL is considered as
12296 * prompt for the command line */
12297 p = vim_strrchr(prompt, '\n');
12298 if (p == NULL)
12299 p = prompt;
12300 else
12302 ++p;
12303 c = *p;
12304 *p = NUL;
12305 msg_start();
12306 msg_clr_eos();
12307 msg_puts_attr(prompt, echo_attr);
12308 msg_didout = FALSE;
12309 msg_starthere();
12310 *p = c;
12312 cmdline_row = msg_row;
12314 if (argvars[1].v_type != VAR_UNKNOWN)
12316 defstr = get_tv_string_buf_chk(&argvars[1], buf);
12317 if (defstr != NULL)
12318 stuffReadbuffSpec(defstr);
12320 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
12322 char_u *xp_name;
12323 int xp_namelen;
12324 long argt;
12326 rettv->vval.v_string = NULL;
12328 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
12329 if (xp_name == NULL)
12330 return;
12332 xp_namelen = (int)STRLEN(xp_name);
12334 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
12335 &xp_arg) == FAIL)
12336 return;
12340 if (defstr != NULL)
12341 rettv->vval.v_string =
12342 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
12343 xp_type, xp_arg);
12345 vim_free(xp_arg);
12347 /* since the user typed this, no need to wait for return */
12348 need_wait_return = FALSE;
12349 msg_didout = FALSE;
12351 cmd_silent = cmd_silent_save;
12355 * "input()" function
12356 * Also handles inputsecret() when inputsecret is set.
12358 static void
12359 f_input(argvars, rettv)
12360 typval_T *argvars;
12361 typval_T *rettv;
12363 get_user_input(argvars, rettv, FALSE);
12367 * "inputdialog()" function
12369 static void
12370 f_inputdialog(argvars, rettv)
12371 typval_T *argvars;
12372 typval_T *rettv;
12374 #if defined(FEAT_GUI_TEXTDIALOG)
12375 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
12376 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
12378 char_u *message;
12379 char_u buf[NUMBUFLEN];
12380 char_u *defstr = (char_u *)"";
12382 message = get_tv_string_chk(&argvars[0]);
12383 if (argvars[1].v_type != VAR_UNKNOWN
12384 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
12385 vim_strncpy(IObuff, defstr, IOSIZE - 1);
12386 else
12387 IObuff[0] = NUL;
12388 if (message != NULL && defstr != NULL
12389 && do_dialog(VIM_QUESTION, NULL, message,
12390 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
12391 rettv->vval.v_string = vim_strsave(IObuff);
12392 else
12394 if (message != NULL && defstr != NULL
12395 && argvars[1].v_type != VAR_UNKNOWN
12396 && argvars[2].v_type != VAR_UNKNOWN)
12397 rettv->vval.v_string = vim_strsave(
12398 get_tv_string_buf(&argvars[2], buf));
12399 else
12400 rettv->vval.v_string = NULL;
12402 rettv->v_type = VAR_STRING;
12404 else
12405 #endif
12406 get_user_input(argvars, rettv, TRUE);
12410 * "inputlist()" function
12412 static void
12413 f_inputlist(argvars, rettv)
12414 typval_T *argvars;
12415 typval_T *rettv;
12417 listitem_T *li;
12418 int selected;
12419 int mouse_used;
12421 #ifdef NO_CONSOLE_INPUT
12422 /* While starting up, there is no place to enter text. */
12423 if (no_console_input())
12424 return;
12425 #endif
12426 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
12428 EMSG2(_(e_listarg), "inputlist()");
12429 return;
12432 msg_start();
12433 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
12434 lines_left = Rows; /* avoid more prompt */
12435 msg_scroll = TRUE;
12436 msg_clr_eos();
12438 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
12440 msg_puts(get_tv_string(&li->li_tv));
12441 msg_putchar('\n');
12444 /* Ask for choice. */
12445 selected = prompt_for_number(&mouse_used);
12446 if (mouse_used)
12447 selected -= lines_left;
12449 rettv->vval.v_number = selected;
12453 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
12456 * "inputrestore()" function
12458 static void
12459 f_inputrestore(argvars, rettv)
12460 typval_T *argvars UNUSED;
12461 typval_T *rettv;
12463 if (ga_userinput.ga_len > 0)
12465 --ga_userinput.ga_len;
12466 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
12467 + ga_userinput.ga_len);
12468 /* default return is zero == OK */
12470 else if (p_verbose > 1)
12472 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
12473 rettv->vval.v_number = 1; /* Failed */
12478 * "inputsave()" function
12480 static void
12481 f_inputsave(argvars, rettv)
12482 typval_T *argvars UNUSED;
12483 typval_T *rettv;
12485 /* Add an entry to the stack of typeahead storage. */
12486 if (ga_grow(&ga_userinput, 1) == OK)
12488 save_typeahead((tasave_T *)(ga_userinput.ga_data)
12489 + ga_userinput.ga_len);
12490 ++ga_userinput.ga_len;
12491 /* default return is zero == OK */
12493 else
12494 rettv->vval.v_number = 1; /* Failed */
12498 * "inputsecret()" function
12500 static void
12501 f_inputsecret(argvars, rettv)
12502 typval_T *argvars;
12503 typval_T *rettv;
12505 ++cmdline_star;
12506 ++inputsecret_flag;
12507 f_input(argvars, rettv);
12508 --cmdline_star;
12509 --inputsecret_flag;
12513 * "insert()" function
12515 static void
12516 f_insert(argvars, rettv)
12517 typval_T *argvars;
12518 typval_T *rettv;
12520 long before = 0;
12521 listitem_T *item;
12522 list_T *l;
12523 int error = FALSE;
12525 if (argvars[0].v_type != VAR_LIST)
12526 EMSG2(_(e_listarg), "insert()");
12527 else if ((l = argvars[0].vval.v_list) != NULL
12528 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
12530 if (argvars[2].v_type != VAR_UNKNOWN)
12531 before = get_tv_number_chk(&argvars[2], &error);
12532 if (error)
12533 return; /* type error; errmsg already given */
12535 if (before == l->lv_len)
12536 item = NULL;
12537 else
12539 item = list_find(l, before);
12540 if (item == NULL)
12542 EMSGN(_(e_listidx), before);
12543 l = NULL;
12546 if (l != NULL)
12548 list_insert_tv(l, &argvars[1], item);
12549 copy_tv(&argvars[0], rettv);
12555 * "isdirectory()" function
12557 static void
12558 f_isdirectory(argvars, rettv)
12559 typval_T *argvars;
12560 typval_T *rettv;
12562 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
12566 * "islocked()" function
12568 static void
12569 f_islocked(argvars, rettv)
12570 typval_T *argvars;
12571 typval_T *rettv;
12573 lval_T lv;
12574 char_u *end;
12575 dictitem_T *di;
12577 rettv->vval.v_number = -1;
12578 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
12579 FNE_CHECK_START);
12580 if (end != NULL && lv.ll_name != NULL)
12582 if (*end != NUL)
12583 EMSG(_(e_trailing));
12584 else
12586 if (lv.ll_tv == NULL)
12588 if (check_changedtick(lv.ll_name))
12589 rettv->vval.v_number = 1; /* always locked */
12590 else
12592 di = find_var(lv.ll_name, NULL);
12593 if (di != NULL)
12595 /* Consider a variable locked when:
12596 * 1. the variable itself is locked
12597 * 2. the value of the variable is locked.
12598 * 3. the List or Dict value is locked.
12600 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
12601 || tv_islocked(&di->di_tv));
12605 else if (lv.ll_range)
12606 EMSG(_("E786: Range not allowed"));
12607 else if (lv.ll_newkey != NULL)
12608 EMSG2(_(e_dictkey), lv.ll_newkey);
12609 else if (lv.ll_list != NULL)
12610 /* List item. */
12611 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
12612 else
12613 /* Dictionary item. */
12614 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
12618 clear_lval(&lv);
12621 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
12624 * Turn a dict into a list:
12625 * "what" == 0: list of keys
12626 * "what" == 1: list of values
12627 * "what" == 2: list of items
12629 static void
12630 dict_list(argvars, rettv, what)
12631 typval_T *argvars;
12632 typval_T *rettv;
12633 int what;
12635 list_T *l2;
12636 dictitem_T *di;
12637 hashitem_T *hi;
12638 listitem_T *li;
12639 listitem_T *li2;
12640 dict_T *d;
12641 int todo;
12643 if (argvars[0].v_type != VAR_DICT)
12645 EMSG(_(e_dictreq));
12646 return;
12648 if ((d = argvars[0].vval.v_dict) == NULL)
12649 return;
12651 if (rettv_list_alloc(rettv) == FAIL)
12652 return;
12654 todo = (int)d->dv_hashtab.ht_used;
12655 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12657 if (!HASHITEM_EMPTY(hi))
12659 --todo;
12660 di = HI2DI(hi);
12662 li = listitem_alloc();
12663 if (li == NULL)
12664 break;
12665 list_append(rettv->vval.v_list, li);
12667 if (what == 0)
12669 /* keys() */
12670 li->li_tv.v_type = VAR_STRING;
12671 li->li_tv.v_lock = 0;
12672 li->li_tv.vval.v_string = vim_strsave(di->di_key);
12674 else if (what == 1)
12676 /* values() */
12677 copy_tv(&di->di_tv, &li->li_tv);
12679 else
12681 /* items() */
12682 l2 = list_alloc();
12683 li->li_tv.v_type = VAR_LIST;
12684 li->li_tv.v_lock = 0;
12685 li->li_tv.vval.v_list = l2;
12686 if (l2 == NULL)
12687 break;
12688 ++l2->lv_refcount;
12690 li2 = listitem_alloc();
12691 if (li2 == NULL)
12692 break;
12693 list_append(l2, li2);
12694 li2->li_tv.v_type = VAR_STRING;
12695 li2->li_tv.v_lock = 0;
12696 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12698 li2 = listitem_alloc();
12699 if (li2 == NULL)
12700 break;
12701 list_append(l2, li2);
12702 copy_tv(&di->di_tv, &li2->li_tv);
12709 * "items(dict)" function
12711 static void
12712 f_items(argvars, rettv)
12713 typval_T *argvars;
12714 typval_T *rettv;
12716 dict_list(argvars, rettv, 2);
12720 * "join()" function
12722 static void
12723 f_join(argvars, rettv)
12724 typval_T *argvars;
12725 typval_T *rettv;
12727 garray_T ga;
12728 char_u *sep;
12730 if (argvars[0].v_type != VAR_LIST)
12732 EMSG(_(e_listreq));
12733 return;
12735 if (argvars[0].vval.v_list == NULL)
12736 return;
12737 if (argvars[1].v_type == VAR_UNKNOWN)
12738 sep = (char_u *)" ";
12739 else
12740 sep = get_tv_string_chk(&argvars[1]);
12742 rettv->v_type = VAR_STRING;
12744 if (sep != NULL)
12746 ga_init2(&ga, (int)sizeof(char), 80);
12747 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12748 ga_append(&ga, NUL);
12749 rettv->vval.v_string = (char_u *)ga.ga_data;
12751 else
12752 rettv->vval.v_string = NULL;
12756 * "keys()" function
12758 static void
12759 f_keys(argvars, rettv)
12760 typval_T *argvars;
12761 typval_T *rettv;
12763 dict_list(argvars, rettv, 0);
12767 * "last_buffer_nr()" function.
12769 static void
12770 f_last_buffer_nr(argvars, rettv)
12771 typval_T *argvars UNUSED;
12772 typval_T *rettv;
12774 int n = 0;
12775 buf_T *buf;
12777 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12778 if (n < buf->b_fnum)
12779 n = buf->b_fnum;
12781 rettv->vval.v_number = n;
12785 * "len()" function
12787 static void
12788 f_len(argvars, rettv)
12789 typval_T *argvars;
12790 typval_T *rettv;
12792 switch (argvars[0].v_type)
12794 case VAR_STRING:
12795 case VAR_NUMBER:
12796 rettv->vval.v_number = (varnumber_T)STRLEN(
12797 get_tv_string(&argvars[0]));
12798 break;
12799 case VAR_LIST:
12800 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
12801 break;
12802 case VAR_DICT:
12803 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
12804 break;
12805 default:
12806 EMSG(_("E701: Invalid type for len()"));
12807 break;
12811 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
12813 static void
12814 libcall_common(argvars, rettv, type)
12815 typval_T *argvars;
12816 typval_T *rettv;
12817 int type;
12819 #ifdef FEAT_LIBCALL
12820 char_u *string_in;
12821 char_u **string_result;
12822 int nr_result;
12823 #endif
12825 rettv->v_type = type;
12826 if (type != VAR_NUMBER)
12827 rettv->vval.v_string = NULL;
12829 if (check_restricted() || check_secure())
12830 return;
12832 #ifdef FEAT_LIBCALL
12833 /* The first two args must be strings, otherwise its meaningless */
12834 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
12836 string_in = NULL;
12837 if (argvars[2].v_type == VAR_STRING)
12838 string_in = argvars[2].vval.v_string;
12839 if (type == VAR_NUMBER)
12840 string_result = NULL;
12841 else
12842 string_result = &rettv->vval.v_string;
12843 if (mch_libcall(argvars[0].vval.v_string,
12844 argvars[1].vval.v_string,
12845 string_in,
12846 argvars[2].vval.v_number,
12847 string_result,
12848 &nr_result) == OK
12849 && type == VAR_NUMBER)
12850 rettv->vval.v_number = nr_result;
12852 #endif
12856 * "libcall()" function
12858 static void
12859 f_libcall(argvars, rettv)
12860 typval_T *argvars;
12861 typval_T *rettv;
12863 libcall_common(argvars, rettv, VAR_STRING);
12867 * "libcallnr()" function
12869 static void
12870 f_libcallnr(argvars, rettv)
12871 typval_T *argvars;
12872 typval_T *rettv;
12874 libcall_common(argvars, rettv, VAR_NUMBER);
12878 * "line(string)" function
12880 static void
12881 f_line(argvars, rettv)
12882 typval_T *argvars;
12883 typval_T *rettv;
12885 linenr_T lnum = 0;
12886 pos_T *fp;
12887 int fnum;
12889 fp = var2fpos(&argvars[0], TRUE, &fnum);
12890 if (fp != NULL)
12891 lnum = fp->lnum;
12892 rettv->vval.v_number = lnum;
12896 * "line2byte(lnum)" function
12898 static void
12899 f_line2byte(argvars, rettv)
12900 typval_T *argvars UNUSED;
12901 typval_T *rettv;
12903 #ifndef FEAT_BYTEOFF
12904 rettv->vval.v_number = -1;
12905 #else
12906 linenr_T lnum;
12908 lnum = get_tv_lnum(argvars);
12909 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
12910 rettv->vval.v_number = -1;
12911 else
12912 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
12913 if (rettv->vval.v_number >= 0)
12914 ++rettv->vval.v_number;
12915 #endif
12919 * "lispindent(lnum)" function
12921 static void
12922 f_lispindent(argvars, rettv)
12923 typval_T *argvars;
12924 typval_T *rettv;
12926 #ifdef FEAT_LISP
12927 pos_T pos;
12928 linenr_T lnum;
12930 pos = curwin->w_cursor;
12931 lnum = get_tv_lnum(argvars);
12932 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12934 curwin->w_cursor.lnum = lnum;
12935 rettv->vval.v_number = get_lisp_indent();
12936 curwin->w_cursor = pos;
12938 else
12939 #endif
12940 rettv->vval.v_number = -1;
12944 * "localtime()" function
12946 static void
12947 f_localtime(argvars, rettv)
12948 typval_T *argvars UNUSED;
12949 typval_T *rettv;
12951 rettv->vval.v_number = (varnumber_T)time(NULL);
12954 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
12956 static void
12957 get_maparg(argvars, rettv, exact)
12958 typval_T *argvars;
12959 typval_T *rettv;
12960 int exact;
12962 char_u *keys;
12963 char_u *which;
12964 char_u buf[NUMBUFLEN];
12965 char_u *keys_buf = NULL;
12966 char_u *rhs;
12967 int mode;
12968 garray_T ga;
12969 int abbr = FALSE;
12971 /* return empty string for failure */
12972 rettv->v_type = VAR_STRING;
12973 rettv->vval.v_string = NULL;
12975 keys = get_tv_string(&argvars[0]);
12976 if (*keys == NUL)
12977 return;
12979 if (argvars[1].v_type != VAR_UNKNOWN)
12981 which = get_tv_string_buf_chk(&argvars[1], buf);
12982 if (argvars[2].v_type != VAR_UNKNOWN)
12983 abbr = get_tv_number(&argvars[2]);
12985 else
12986 which = (char_u *)"";
12987 if (which == NULL)
12988 return;
12990 mode = get_map_mode(&which, 0);
12992 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
12993 rhs = check_map(keys, mode, exact, FALSE, abbr);
12994 vim_free(keys_buf);
12995 if (rhs != NULL)
12997 ga_init(&ga);
12998 ga.ga_itemsize = 1;
12999 ga.ga_growsize = 40;
13001 while (*rhs != NUL)
13002 ga_concat(&ga, str2special(&rhs, FALSE));
13004 ga_append(&ga, NUL);
13005 rettv->vval.v_string = (char_u *)ga.ga_data;
13009 #ifdef FEAT_FLOAT
13011 * "log10()" function
13013 static void
13014 f_log10(argvars, rettv)
13015 typval_T *argvars;
13016 typval_T *rettv;
13018 float_T f;
13020 rettv->v_type = VAR_FLOAT;
13021 if (get_float_arg(argvars, &f) == OK)
13022 rettv->vval.v_float = log10(f);
13023 else
13024 rettv->vval.v_float = 0.0;
13026 #endif
13029 * "map()" function
13031 static void
13032 f_map(argvars, rettv)
13033 typval_T *argvars;
13034 typval_T *rettv;
13036 filter_map(argvars, rettv, TRUE);
13040 * "maparg()" function
13042 static void
13043 f_maparg(argvars, rettv)
13044 typval_T *argvars;
13045 typval_T *rettv;
13047 get_maparg(argvars, rettv, TRUE);
13051 * "mapcheck()" function
13053 static void
13054 f_mapcheck(argvars, rettv)
13055 typval_T *argvars;
13056 typval_T *rettv;
13058 get_maparg(argvars, rettv, FALSE);
13061 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
13063 static void
13064 find_some_match(argvars, rettv, type)
13065 typval_T *argvars;
13066 typval_T *rettv;
13067 int type;
13069 char_u *str = NULL;
13070 char_u *expr = NULL;
13071 char_u *pat;
13072 regmatch_T regmatch;
13073 char_u patbuf[NUMBUFLEN];
13074 char_u strbuf[NUMBUFLEN];
13075 char_u *save_cpo;
13076 long start = 0;
13077 long nth = 1;
13078 colnr_T startcol = 0;
13079 int match = 0;
13080 list_T *l = NULL;
13081 listitem_T *li = NULL;
13082 long idx = 0;
13083 char_u *tofree = NULL;
13085 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
13086 save_cpo = p_cpo;
13087 p_cpo = (char_u *)"";
13089 rettv->vval.v_number = -1;
13090 if (type == 3)
13092 /* return empty list when there are no matches */
13093 if (rettv_list_alloc(rettv) == FAIL)
13094 goto theend;
13096 else if (type == 2)
13098 rettv->v_type = VAR_STRING;
13099 rettv->vval.v_string = NULL;
13102 if (argvars[0].v_type == VAR_LIST)
13104 if ((l = argvars[0].vval.v_list) == NULL)
13105 goto theend;
13106 li = l->lv_first;
13108 else
13109 expr = str = get_tv_string(&argvars[0]);
13111 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
13112 if (pat == NULL)
13113 goto theend;
13115 if (argvars[2].v_type != VAR_UNKNOWN)
13117 int error = FALSE;
13119 start = get_tv_number_chk(&argvars[2], &error);
13120 if (error)
13121 goto theend;
13122 if (l != NULL)
13124 li = list_find(l, start);
13125 if (li == NULL)
13126 goto theend;
13127 idx = l->lv_idx; /* use the cached index */
13129 else
13131 if (start < 0)
13132 start = 0;
13133 if (start > (long)STRLEN(str))
13134 goto theend;
13135 /* When "count" argument is there ignore matches before "start",
13136 * otherwise skip part of the string. Differs when pattern is "^"
13137 * or "\<". */
13138 if (argvars[3].v_type != VAR_UNKNOWN)
13139 startcol = start;
13140 else
13141 str += start;
13144 if (argvars[3].v_type != VAR_UNKNOWN)
13145 nth = get_tv_number_chk(&argvars[3], &error);
13146 if (error)
13147 goto theend;
13150 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
13151 if (regmatch.regprog != NULL)
13153 regmatch.rm_ic = p_ic;
13155 for (;;)
13157 if (l != NULL)
13159 if (li == NULL)
13161 match = FALSE;
13162 break;
13164 vim_free(tofree);
13165 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
13166 if (str == NULL)
13167 break;
13170 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
13172 if (match && --nth <= 0)
13173 break;
13174 if (l == NULL && !match)
13175 break;
13177 /* Advance to just after the match. */
13178 if (l != NULL)
13180 li = li->li_next;
13181 ++idx;
13183 else
13185 #ifdef FEAT_MBYTE
13186 startcol = (colnr_T)(regmatch.startp[0]
13187 + (*mb_ptr2len)(regmatch.startp[0]) - str);
13188 #else
13189 startcol = regmatch.startp[0] + 1 - str;
13190 #endif
13194 if (match)
13196 if (type == 3)
13198 int i;
13200 /* return list with matched string and submatches */
13201 for (i = 0; i < NSUBEXP; ++i)
13203 if (regmatch.endp[i] == NULL)
13205 if (list_append_string(rettv->vval.v_list,
13206 (char_u *)"", 0) == FAIL)
13207 break;
13209 else if (list_append_string(rettv->vval.v_list,
13210 regmatch.startp[i],
13211 (int)(regmatch.endp[i] - regmatch.startp[i]))
13212 == FAIL)
13213 break;
13216 else if (type == 2)
13218 /* return matched string */
13219 if (l != NULL)
13220 copy_tv(&li->li_tv, rettv);
13221 else
13222 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
13223 (int)(regmatch.endp[0] - regmatch.startp[0]));
13225 else if (l != NULL)
13226 rettv->vval.v_number = idx;
13227 else
13229 if (type != 0)
13230 rettv->vval.v_number =
13231 (varnumber_T)(regmatch.startp[0] - str);
13232 else
13233 rettv->vval.v_number =
13234 (varnumber_T)(regmatch.endp[0] - str);
13235 rettv->vval.v_number += (varnumber_T)(str - expr);
13238 vim_free(regmatch.regprog);
13241 theend:
13242 vim_free(tofree);
13243 p_cpo = save_cpo;
13247 * "match()" function
13249 static void
13250 f_match(argvars, rettv)
13251 typval_T *argvars;
13252 typval_T *rettv;
13254 find_some_match(argvars, rettv, 1);
13258 * "matchadd()" function
13260 static void
13261 f_matchadd(argvars, rettv)
13262 typval_T *argvars;
13263 typval_T *rettv;
13265 #ifdef FEAT_SEARCH_EXTRA
13266 char_u buf[NUMBUFLEN];
13267 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
13268 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
13269 int prio = 10; /* default priority */
13270 int id = -1;
13271 int error = FALSE;
13273 rettv->vval.v_number = -1;
13275 if (grp == NULL || pat == NULL)
13276 return;
13277 if (argvars[2].v_type != VAR_UNKNOWN)
13279 prio = get_tv_number_chk(&argvars[2], &error);
13280 if (argvars[3].v_type != VAR_UNKNOWN)
13281 id = get_tv_number_chk(&argvars[3], &error);
13283 if (error == TRUE)
13284 return;
13285 if (id >= 1 && id <= 3)
13287 EMSGN("E798: ID is reserved for \":match\": %ld", id);
13288 return;
13291 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
13292 #endif
13296 * "matcharg()" function
13298 static void
13299 f_matcharg(argvars, rettv)
13300 typval_T *argvars;
13301 typval_T *rettv;
13303 if (rettv_list_alloc(rettv) == OK)
13305 #ifdef FEAT_SEARCH_EXTRA
13306 int id = get_tv_number(&argvars[0]);
13307 matchitem_T *m;
13309 if (id >= 1 && id <= 3)
13311 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
13313 list_append_string(rettv->vval.v_list,
13314 syn_id2name(m->hlg_id), -1);
13315 list_append_string(rettv->vval.v_list, m->pattern, -1);
13317 else
13319 list_append_string(rettv->vval.v_list, NUL, -1);
13320 list_append_string(rettv->vval.v_list, NUL, -1);
13323 #endif
13328 * "matchdelete()" function
13330 static void
13331 f_matchdelete(argvars, rettv)
13332 typval_T *argvars;
13333 typval_T *rettv;
13335 #ifdef FEAT_SEARCH_EXTRA
13336 rettv->vval.v_number = match_delete(curwin,
13337 (int)get_tv_number(&argvars[0]), TRUE);
13338 #endif
13342 * "matchend()" function
13344 static void
13345 f_matchend(argvars, rettv)
13346 typval_T *argvars;
13347 typval_T *rettv;
13349 find_some_match(argvars, rettv, 0);
13353 * "matchlist()" function
13355 static void
13356 f_matchlist(argvars, rettv)
13357 typval_T *argvars;
13358 typval_T *rettv;
13360 find_some_match(argvars, rettv, 3);
13364 * "matchstr()" function
13366 static void
13367 f_matchstr(argvars, rettv)
13368 typval_T *argvars;
13369 typval_T *rettv;
13371 find_some_match(argvars, rettv, 2);
13374 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
13376 static void
13377 max_min(argvars, rettv, domax)
13378 typval_T *argvars;
13379 typval_T *rettv;
13380 int domax;
13382 long n = 0;
13383 long i;
13384 int error = FALSE;
13386 if (argvars[0].v_type == VAR_LIST)
13388 list_T *l;
13389 listitem_T *li;
13391 l = argvars[0].vval.v_list;
13392 if (l != NULL)
13394 li = l->lv_first;
13395 if (li != NULL)
13397 n = get_tv_number_chk(&li->li_tv, &error);
13398 for (;;)
13400 li = li->li_next;
13401 if (li == NULL)
13402 break;
13403 i = get_tv_number_chk(&li->li_tv, &error);
13404 if (domax ? i > n : i < n)
13405 n = i;
13410 else if (argvars[0].v_type == VAR_DICT)
13412 dict_T *d;
13413 int first = TRUE;
13414 hashitem_T *hi;
13415 int todo;
13417 d = argvars[0].vval.v_dict;
13418 if (d != NULL)
13420 todo = (int)d->dv_hashtab.ht_used;
13421 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13423 if (!HASHITEM_EMPTY(hi))
13425 --todo;
13426 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
13427 if (first)
13429 n = i;
13430 first = FALSE;
13432 else if (domax ? i > n : i < n)
13433 n = i;
13438 else
13439 EMSG(_(e_listdictarg));
13440 rettv->vval.v_number = error ? 0 : n;
13444 * "max()" function
13446 static void
13447 f_max(argvars, rettv)
13448 typval_T *argvars;
13449 typval_T *rettv;
13451 max_min(argvars, rettv, TRUE);
13455 * "min()" function
13457 static void
13458 f_min(argvars, rettv)
13459 typval_T *argvars;
13460 typval_T *rettv;
13462 max_min(argvars, rettv, FALSE);
13465 static int mkdir_recurse __ARGS((char_u *dir, int prot));
13468 * Create the directory in which "dir" is located, and higher levels when
13469 * needed.
13471 static int
13472 mkdir_recurse(dir, prot)
13473 char_u *dir;
13474 int prot;
13476 char_u *p;
13477 char_u *updir;
13478 int r = FAIL;
13480 /* Get end of directory name in "dir".
13481 * We're done when it's "/" or "c:/". */
13482 p = gettail_sep(dir);
13483 if (p <= get_past_head(dir))
13484 return OK;
13486 /* If the directory exists we're done. Otherwise: create it.*/
13487 updir = vim_strnsave(dir, (int)(p - dir));
13488 if (updir == NULL)
13489 return FAIL;
13490 if (mch_isdir(updir))
13491 r = OK;
13492 else if (mkdir_recurse(updir, prot) == OK)
13493 r = vim_mkdir_emsg(updir, prot);
13494 vim_free(updir);
13495 return r;
13498 #ifdef vim_mkdir
13500 * "mkdir()" function
13502 static void
13503 f_mkdir(argvars, rettv)
13504 typval_T *argvars;
13505 typval_T *rettv;
13507 char_u *dir;
13508 char_u buf[NUMBUFLEN];
13509 int prot = 0755;
13511 rettv->vval.v_number = FAIL;
13512 if (check_restricted() || check_secure())
13513 return;
13515 dir = get_tv_string_buf(&argvars[0], buf);
13516 if (argvars[1].v_type != VAR_UNKNOWN)
13518 if (argvars[2].v_type != VAR_UNKNOWN)
13519 prot = get_tv_number_chk(&argvars[2], NULL);
13520 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
13521 mkdir_recurse(dir, prot);
13523 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
13525 #endif
13528 * "mode()" function
13530 static void
13531 f_mode(argvars, rettv)
13532 typval_T *argvars;
13533 typval_T *rettv;
13535 char_u buf[3];
13537 buf[1] = NUL;
13538 buf[2] = NUL;
13540 #ifdef FEAT_VISUAL
13541 if (VIsual_active)
13543 if (VIsual_select)
13544 buf[0] = VIsual_mode + 's' - 'v';
13545 else
13546 buf[0] = VIsual_mode;
13548 else
13549 #endif
13550 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
13551 || State == CONFIRM)
13553 buf[0] = 'r';
13554 if (State == ASKMORE)
13555 buf[1] = 'm';
13556 else if (State == CONFIRM)
13557 buf[1] = '?';
13559 else if (State == EXTERNCMD)
13560 buf[0] = '!';
13561 else if (State & INSERT)
13563 #ifdef FEAT_VREPLACE
13564 if (State & VREPLACE_FLAG)
13566 buf[0] = 'R';
13567 buf[1] = 'v';
13569 else
13570 #endif
13571 if (State & REPLACE_FLAG)
13572 buf[0] = 'R';
13573 else
13574 buf[0] = 'i';
13576 else if (State & CMDLINE)
13578 buf[0] = 'c';
13579 if (exmode_active)
13580 buf[1] = 'v';
13582 else if (exmode_active)
13584 buf[0] = 'c';
13585 buf[1] = 'e';
13587 else
13589 buf[0] = 'n';
13590 if (finish_op)
13591 buf[1] = 'o';
13594 /* Clear out the minor mode when the argument is not a non-zero number or
13595 * non-empty string. */
13596 if (!non_zero_arg(&argvars[0]))
13597 buf[1] = NUL;
13599 rettv->vval.v_string = vim_strsave(buf);
13600 rettv->v_type = VAR_STRING;
13603 #ifdef FEAT_MZSCHEME
13605 * "mzeval()" function
13607 static void
13608 f_mzeval(argvars, rettv)
13609 typval_T *argvars;
13610 typval_T *rettv;
13612 char_u *str;
13613 char_u buf[NUMBUFLEN];
13615 str = get_tv_string_buf(&argvars[0], buf);
13616 do_mzeval(str, rettv);
13618 #endif
13621 * "nextnonblank()" function
13623 static void
13624 f_nextnonblank(argvars, rettv)
13625 typval_T *argvars;
13626 typval_T *rettv;
13628 linenr_T lnum;
13630 for (lnum = get_tv_lnum(argvars); ; ++lnum)
13632 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
13634 lnum = 0;
13635 break;
13637 if (*skipwhite(ml_get(lnum)) != NUL)
13638 break;
13640 rettv->vval.v_number = lnum;
13644 * "nr2char()" function
13646 static void
13647 f_nr2char(argvars, rettv)
13648 typval_T *argvars;
13649 typval_T *rettv;
13651 char_u buf[NUMBUFLEN];
13653 #ifdef FEAT_MBYTE
13654 if (has_mbyte)
13655 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
13656 else
13657 #endif
13659 buf[0] = (char_u)get_tv_number(&argvars[0]);
13660 buf[1] = NUL;
13662 rettv->v_type = VAR_STRING;
13663 rettv->vval.v_string = vim_strsave(buf);
13667 * "pathshorten()" function
13669 static void
13670 f_pathshorten(argvars, rettv)
13671 typval_T *argvars;
13672 typval_T *rettv;
13674 char_u *p;
13676 rettv->v_type = VAR_STRING;
13677 p = get_tv_string_chk(&argvars[0]);
13678 if (p == NULL)
13679 rettv->vval.v_string = NULL;
13680 else
13682 p = vim_strsave(p);
13683 rettv->vval.v_string = p;
13684 if (p != NULL)
13685 shorten_dir(p);
13689 #ifdef FEAT_FLOAT
13691 * "pow()" function
13693 static void
13694 f_pow(argvars, rettv)
13695 typval_T *argvars;
13696 typval_T *rettv;
13698 float_T fx, fy;
13700 rettv->v_type = VAR_FLOAT;
13701 if (get_float_arg(argvars, &fx) == OK
13702 && get_float_arg(&argvars[1], &fy) == OK)
13703 rettv->vval.v_float = pow(fx, fy);
13704 else
13705 rettv->vval.v_float = 0.0;
13707 #endif
13710 * "prevnonblank()" function
13712 static void
13713 f_prevnonblank(argvars, rettv)
13714 typval_T *argvars;
13715 typval_T *rettv;
13717 linenr_T lnum;
13719 lnum = get_tv_lnum(argvars);
13720 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
13721 lnum = 0;
13722 else
13723 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
13724 --lnum;
13725 rettv->vval.v_number = lnum;
13728 #ifdef HAVE_STDARG_H
13729 /* This dummy va_list is here because:
13730 * - passing a NULL pointer doesn't work when va_list isn't a pointer
13731 * - locally in the function results in a "used before set" warning
13732 * - using va_start() to initialize it gives "function with fixed args" error */
13733 static va_list ap;
13734 #endif
13737 * "printf()" function
13739 static void
13740 f_printf(argvars, rettv)
13741 typval_T *argvars;
13742 typval_T *rettv;
13744 rettv->v_type = VAR_STRING;
13745 rettv->vval.v_string = NULL;
13746 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
13748 char_u buf[NUMBUFLEN];
13749 int len;
13750 char_u *s;
13751 int saved_did_emsg = did_emsg;
13752 char *fmt;
13754 /* Get the required length, allocate the buffer and do it for real. */
13755 did_emsg = FALSE;
13756 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
13757 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
13758 if (!did_emsg)
13760 s = alloc(len + 1);
13761 if (s != NULL)
13763 rettv->vval.v_string = s;
13764 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
13767 did_emsg |= saved_did_emsg;
13769 #endif
13773 * "pumvisible()" function
13775 static void
13776 f_pumvisible(argvars, rettv)
13777 typval_T *argvars UNUSED;
13778 typval_T *rettv UNUSED;
13780 #ifdef FEAT_INS_EXPAND
13781 if (pum_visible())
13782 rettv->vval.v_number = 1;
13783 #endif
13787 * "range()" function
13789 static void
13790 f_range(argvars, rettv)
13791 typval_T *argvars;
13792 typval_T *rettv;
13794 long start;
13795 long end;
13796 long stride = 1;
13797 long i;
13798 int error = FALSE;
13800 start = get_tv_number_chk(&argvars[0], &error);
13801 if (argvars[1].v_type == VAR_UNKNOWN)
13803 end = start - 1;
13804 start = 0;
13806 else
13808 end = get_tv_number_chk(&argvars[1], &error);
13809 if (argvars[2].v_type != VAR_UNKNOWN)
13810 stride = get_tv_number_chk(&argvars[2], &error);
13813 if (error)
13814 return; /* type error; errmsg already given */
13815 if (stride == 0)
13816 EMSG(_("E726: Stride is zero"));
13817 else if (stride > 0 ? end + 1 < start : end - 1 > start)
13818 EMSG(_("E727: Start past end"));
13819 else
13821 if (rettv_list_alloc(rettv) == OK)
13822 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
13823 if (list_append_number(rettv->vval.v_list,
13824 (varnumber_T)i) == FAIL)
13825 break;
13830 * "readfile()" function
13832 static void
13833 f_readfile(argvars, rettv)
13834 typval_T *argvars;
13835 typval_T *rettv;
13837 int binary = FALSE;
13838 char_u *fname;
13839 FILE *fd;
13840 listitem_T *li;
13841 #define FREAD_SIZE 200 /* optimized for text lines */
13842 char_u buf[FREAD_SIZE];
13843 int readlen; /* size of last fread() */
13844 int buflen; /* nr of valid chars in buf[] */
13845 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
13846 int tolist; /* first byte in buf[] still to be put in list */
13847 int chop; /* how many CR to chop off */
13848 char_u *prev = NULL; /* previously read bytes, if any */
13849 int prevlen = 0; /* length of "prev" if not NULL */
13850 char_u *s;
13851 int len;
13852 long maxline = MAXLNUM;
13853 long cnt = 0;
13855 if (argvars[1].v_type != VAR_UNKNOWN)
13857 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
13858 binary = TRUE;
13859 if (argvars[2].v_type != VAR_UNKNOWN)
13860 maxline = get_tv_number(&argvars[2]);
13863 if (rettv_list_alloc(rettv) == FAIL)
13864 return;
13866 /* Always open the file in binary mode, library functions have a mind of
13867 * their own about CR-LF conversion. */
13868 fname = get_tv_string(&argvars[0]);
13869 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
13871 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
13872 return;
13875 filtd = 0;
13876 while (cnt < maxline || maxline < 0)
13878 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
13879 buflen = filtd + readlen;
13880 tolist = 0;
13881 for ( ; filtd < buflen || readlen <= 0; ++filtd)
13883 if (buf[filtd] == '\n' || readlen <= 0)
13885 /* Only when in binary mode add an empty list item when the
13886 * last line ends in a '\n'. */
13887 if (!binary && readlen == 0 && filtd == 0)
13888 break;
13890 /* Found end-of-line or end-of-file: add a text line to the
13891 * list. */
13892 chop = 0;
13893 if (!binary)
13894 while (filtd - chop - 1 >= tolist
13895 && buf[filtd - chop - 1] == '\r')
13896 ++chop;
13897 len = filtd - tolist - chop;
13898 if (prev == NULL)
13899 s = vim_strnsave(buf + tolist, len);
13900 else
13902 s = alloc((unsigned)(prevlen + len + 1));
13903 if (s != NULL)
13905 mch_memmove(s, prev, prevlen);
13906 vim_free(prev);
13907 prev = NULL;
13908 mch_memmove(s + prevlen, buf + tolist, len);
13909 s[prevlen + len] = NUL;
13912 tolist = filtd + 1;
13914 li = listitem_alloc();
13915 if (li == NULL)
13917 vim_free(s);
13918 break;
13920 li->li_tv.v_type = VAR_STRING;
13921 li->li_tv.v_lock = 0;
13922 li->li_tv.vval.v_string = s;
13923 list_append(rettv->vval.v_list, li);
13925 if (++cnt >= maxline && maxline >= 0)
13926 break;
13927 if (readlen <= 0)
13928 break;
13930 else if (buf[filtd] == NUL)
13931 buf[filtd] = '\n';
13933 if (readlen <= 0)
13934 break;
13936 if (tolist == 0)
13938 /* "buf" is full, need to move text to an allocated buffer */
13939 if (prev == NULL)
13941 prev = vim_strnsave(buf, buflen);
13942 prevlen = buflen;
13944 else
13946 s = alloc((unsigned)(prevlen + buflen));
13947 if (s != NULL)
13949 mch_memmove(s, prev, prevlen);
13950 mch_memmove(s + prevlen, buf, buflen);
13951 vim_free(prev);
13952 prev = s;
13953 prevlen += buflen;
13956 filtd = 0;
13958 else
13960 mch_memmove(buf, buf + tolist, buflen - tolist);
13961 filtd -= tolist;
13966 * For a negative line count use only the lines at the end of the file,
13967 * free the rest.
13969 if (maxline < 0)
13970 while (cnt > -maxline)
13972 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
13973 --cnt;
13976 vim_free(prev);
13977 fclose(fd);
13980 #if defined(FEAT_RELTIME)
13981 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
13984 * Convert a List to proftime_T.
13985 * Return FAIL when there is something wrong.
13987 static int
13988 list2proftime(arg, tm)
13989 typval_T *arg;
13990 proftime_T *tm;
13992 long n1, n2;
13993 int error = FALSE;
13995 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
13996 || arg->vval.v_list->lv_len != 2)
13997 return FAIL;
13998 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
13999 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
14000 # ifdef WIN3264
14001 tm->HighPart = n1;
14002 tm->LowPart = n2;
14003 # else
14004 tm->tv_sec = n1;
14005 tm->tv_usec = n2;
14006 # endif
14007 return error ? FAIL : OK;
14009 #endif /* FEAT_RELTIME */
14012 * "reltime()" function
14014 static void
14015 f_reltime(argvars, rettv)
14016 typval_T *argvars;
14017 typval_T *rettv;
14019 #ifdef FEAT_RELTIME
14020 proftime_T res;
14021 proftime_T start;
14023 if (argvars[0].v_type == VAR_UNKNOWN)
14025 /* No arguments: get current time. */
14026 profile_start(&res);
14028 else if (argvars[1].v_type == VAR_UNKNOWN)
14030 if (list2proftime(&argvars[0], &res) == FAIL)
14031 return;
14032 profile_end(&res);
14034 else
14036 /* Two arguments: compute the difference. */
14037 if (list2proftime(&argvars[0], &start) == FAIL
14038 || list2proftime(&argvars[1], &res) == FAIL)
14039 return;
14040 profile_sub(&res, &start);
14043 if (rettv_list_alloc(rettv) == OK)
14045 long n1, n2;
14047 # ifdef WIN3264
14048 n1 = res.HighPart;
14049 n2 = res.LowPart;
14050 # else
14051 n1 = res.tv_sec;
14052 n2 = res.tv_usec;
14053 # endif
14054 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
14055 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
14057 #endif
14061 * "reltimestr()" function
14063 static void
14064 f_reltimestr(argvars, rettv)
14065 typval_T *argvars;
14066 typval_T *rettv;
14068 #ifdef FEAT_RELTIME
14069 proftime_T tm;
14070 #endif
14072 rettv->v_type = VAR_STRING;
14073 rettv->vval.v_string = NULL;
14074 #ifdef FEAT_RELTIME
14075 if (list2proftime(&argvars[0], &tm) == OK)
14076 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
14077 #endif
14080 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
14081 static void make_connection __ARGS((void));
14082 static int check_connection __ARGS((void));
14084 static void
14085 make_connection()
14087 if (X_DISPLAY == NULL
14088 # ifdef FEAT_GUI
14089 && !gui.in_use
14090 # endif
14093 x_force_connect = TRUE;
14094 setup_term_clip();
14095 x_force_connect = FALSE;
14099 static int
14100 check_connection()
14102 make_connection();
14103 if (X_DISPLAY == NULL)
14105 EMSG(_("E240: No connection to Vim server"));
14106 return FAIL;
14108 return OK;
14110 #endif
14112 #ifdef FEAT_CLIENTSERVER
14113 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
14115 static void
14116 remote_common(argvars, rettv, expr)
14117 typval_T *argvars;
14118 typval_T *rettv;
14119 int expr;
14121 char_u *server_name;
14122 char_u *keys;
14123 char_u *r = NULL;
14124 char_u buf[NUMBUFLEN];
14125 # ifdef WIN32
14126 HWND w;
14127 # else
14128 Window w;
14129 # endif
14131 if (check_restricted() || check_secure())
14132 return;
14134 # ifdef FEAT_X11
14135 if (check_connection() == FAIL)
14136 return;
14137 # endif
14139 server_name = get_tv_string_chk(&argvars[0]);
14140 if (server_name == NULL)
14141 return; /* type error; errmsg already given */
14142 keys = get_tv_string_buf(&argvars[1], buf);
14143 # ifdef WIN32
14144 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14145 # else
14146 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
14147 < 0)
14148 # endif
14150 if (r != NULL)
14151 EMSG(r); /* sending worked but evaluation failed */
14152 else
14153 EMSG2(_("E241: Unable to send to %s"), server_name);
14154 return;
14157 rettv->vval.v_string = r;
14159 if (argvars[2].v_type != VAR_UNKNOWN)
14161 dictitem_T v;
14162 char_u str[30];
14163 char_u *idvar;
14165 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
14166 v.di_tv.v_type = VAR_STRING;
14167 v.di_tv.vval.v_string = vim_strsave(str);
14168 idvar = get_tv_string_chk(&argvars[2]);
14169 if (idvar != NULL)
14170 set_var(idvar, &v.di_tv, FALSE);
14171 vim_free(v.di_tv.vval.v_string);
14174 #endif
14177 * "remote_expr()" function
14179 static void
14180 f_remote_expr(argvars, rettv)
14181 typval_T *argvars UNUSED;
14182 typval_T *rettv;
14184 rettv->v_type = VAR_STRING;
14185 rettv->vval.v_string = NULL;
14186 #ifdef FEAT_CLIENTSERVER
14187 remote_common(argvars, rettv, TRUE);
14188 #endif
14192 * "remote_foreground()" function
14194 static void
14195 f_remote_foreground(argvars, rettv)
14196 typval_T *argvars UNUSED;
14197 typval_T *rettv UNUSED;
14199 #ifdef FEAT_CLIENTSERVER
14200 # ifdef WIN32
14201 /* On Win32 it's done in this application. */
14203 char_u *server_name = get_tv_string_chk(&argvars[0]);
14205 if (server_name != NULL)
14206 serverForeground(server_name);
14208 # else
14209 /* Send a foreground() expression to the server. */
14210 argvars[1].v_type = VAR_STRING;
14211 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
14212 argvars[2].v_type = VAR_UNKNOWN;
14213 remote_common(argvars, rettv, TRUE);
14214 vim_free(argvars[1].vval.v_string);
14215 # endif
14216 #endif
14219 static void
14220 f_remote_peek(argvars, rettv)
14221 typval_T *argvars UNUSED;
14222 typval_T *rettv;
14224 #ifdef FEAT_CLIENTSERVER
14225 dictitem_T v;
14226 char_u *s = NULL;
14227 # ifdef WIN32
14228 long_u n = 0;
14229 # endif
14230 char_u *serverid;
14232 if (check_restricted() || check_secure())
14234 rettv->vval.v_number = -1;
14235 return;
14237 serverid = get_tv_string_chk(&argvars[0]);
14238 if (serverid == NULL)
14240 rettv->vval.v_number = -1;
14241 return; /* type error; errmsg already given */
14243 # ifdef WIN32
14244 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14245 if (n == 0)
14246 rettv->vval.v_number = -1;
14247 else
14249 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
14250 rettv->vval.v_number = (s != NULL);
14252 # else
14253 if (check_connection() == FAIL)
14254 return;
14256 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
14257 serverStrToWin(serverid), &s);
14258 # endif
14260 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
14262 char_u *retvar;
14264 v.di_tv.v_type = VAR_STRING;
14265 v.di_tv.vval.v_string = vim_strsave(s);
14266 retvar = get_tv_string_chk(&argvars[1]);
14267 if (retvar != NULL)
14268 set_var(retvar, &v.di_tv, FALSE);
14269 vim_free(v.di_tv.vval.v_string);
14271 #else
14272 rettv->vval.v_number = -1;
14273 #endif
14276 static void
14277 f_remote_read(argvars, rettv)
14278 typval_T *argvars UNUSED;
14279 typval_T *rettv;
14281 char_u *r = NULL;
14283 #ifdef FEAT_CLIENTSERVER
14284 char_u *serverid = get_tv_string_chk(&argvars[0]);
14286 if (serverid != NULL && !check_restricted() && !check_secure())
14288 # ifdef WIN32
14289 /* The server's HWND is encoded in the 'id' parameter */
14290 long_u n = 0;
14292 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14293 if (n != 0)
14294 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
14295 if (r == NULL)
14296 # else
14297 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
14298 serverStrToWin(serverid), &r, FALSE) < 0)
14299 # endif
14300 EMSG(_("E277: Unable to read a server reply"));
14302 #endif
14303 rettv->v_type = VAR_STRING;
14304 rettv->vval.v_string = r;
14308 * "remote_send()" function
14310 static void
14311 f_remote_send(argvars, rettv)
14312 typval_T *argvars UNUSED;
14313 typval_T *rettv;
14315 rettv->v_type = VAR_STRING;
14316 rettv->vval.v_string = NULL;
14317 #ifdef FEAT_CLIENTSERVER
14318 remote_common(argvars, rettv, FALSE);
14319 #endif
14323 * "remove()" function
14325 static void
14326 f_remove(argvars, rettv)
14327 typval_T *argvars;
14328 typval_T *rettv;
14330 list_T *l;
14331 listitem_T *item, *item2;
14332 listitem_T *li;
14333 long idx;
14334 long end;
14335 char_u *key;
14336 dict_T *d;
14337 dictitem_T *di;
14339 if (argvars[0].v_type == VAR_DICT)
14341 if (argvars[2].v_type != VAR_UNKNOWN)
14342 EMSG2(_(e_toomanyarg), "remove()");
14343 else if ((d = argvars[0].vval.v_dict) != NULL
14344 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
14346 key = get_tv_string_chk(&argvars[1]);
14347 if (key != NULL)
14349 di = dict_find(d, key, -1);
14350 if (di == NULL)
14351 EMSG2(_(e_dictkey), key);
14352 else
14354 *rettv = di->di_tv;
14355 init_tv(&di->di_tv);
14356 dictitem_remove(d, di);
14361 else if (argvars[0].v_type != VAR_LIST)
14362 EMSG2(_(e_listdictarg), "remove()");
14363 else if ((l = argvars[0].vval.v_list) != NULL
14364 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
14366 int error = FALSE;
14368 idx = get_tv_number_chk(&argvars[1], &error);
14369 if (error)
14370 ; /* type error: do nothing, errmsg already given */
14371 else if ((item = list_find(l, idx)) == NULL)
14372 EMSGN(_(e_listidx), idx);
14373 else
14375 if (argvars[2].v_type == VAR_UNKNOWN)
14377 /* Remove one item, return its value. */
14378 list_remove(l, item, item);
14379 *rettv = item->li_tv;
14380 vim_free(item);
14382 else
14384 /* Remove range of items, return list with values. */
14385 end = get_tv_number_chk(&argvars[2], &error);
14386 if (error)
14387 ; /* type error: do nothing */
14388 else if ((item2 = list_find(l, end)) == NULL)
14389 EMSGN(_(e_listidx), end);
14390 else
14392 int cnt = 0;
14394 for (li = item; li != NULL; li = li->li_next)
14396 ++cnt;
14397 if (li == item2)
14398 break;
14400 if (li == NULL) /* didn't find "item2" after "item" */
14401 EMSG(_(e_invrange));
14402 else
14404 list_remove(l, item, item2);
14405 if (rettv_list_alloc(rettv) == OK)
14407 l = rettv->vval.v_list;
14408 l->lv_first = item;
14409 l->lv_last = item2;
14410 item->li_prev = NULL;
14411 item2->li_next = NULL;
14412 l->lv_len = cnt;
14422 * "rename({from}, {to})" function
14424 static void
14425 f_rename(argvars, rettv)
14426 typval_T *argvars;
14427 typval_T *rettv;
14429 char_u buf[NUMBUFLEN];
14431 if (check_restricted() || check_secure())
14432 rettv->vval.v_number = -1;
14433 else
14434 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
14435 get_tv_string_buf(&argvars[1], buf));
14439 * "repeat()" function
14441 static void
14442 f_repeat(argvars, rettv)
14443 typval_T *argvars;
14444 typval_T *rettv;
14446 char_u *p;
14447 int n;
14448 int slen;
14449 int len;
14450 char_u *r;
14451 int i;
14453 n = get_tv_number(&argvars[1]);
14454 if (argvars[0].v_type == VAR_LIST)
14456 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
14457 while (n-- > 0)
14458 if (list_extend(rettv->vval.v_list,
14459 argvars[0].vval.v_list, NULL) == FAIL)
14460 break;
14462 else
14464 p = get_tv_string(&argvars[0]);
14465 rettv->v_type = VAR_STRING;
14466 rettv->vval.v_string = NULL;
14468 slen = (int)STRLEN(p);
14469 len = slen * n;
14470 if (len <= 0)
14471 return;
14473 r = alloc(len + 1);
14474 if (r != NULL)
14476 for (i = 0; i < n; i++)
14477 mch_memmove(r + i * slen, p, (size_t)slen);
14478 r[len] = NUL;
14481 rettv->vval.v_string = r;
14486 * "resolve()" function
14488 static void
14489 f_resolve(argvars, rettv)
14490 typval_T *argvars;
14491 typval_T *rettv;
14493 char_u *p;
14495 p = get_tv_string(&argvars[0]);
14496 #ifdef FEAT_SHORTCUT
14498 char_u *v = NULL;
14500 v = mch_resolve_shortcut(p);
14501 if (v != NULL)
14502 rettv->vval.v_string = v;
14503 else
14504 rettv->vval.v_string = vim_strsave(p);
14506 #else
14507 # ifdef HAVE_READLINK
14509 char_u buf[MAXPATHL + 1];
14510 char_u *cpy;
14511 int len;
14512 char_u *remain = NULL;
14513 char_u *q;
14514 int is_relative_to_current = FALSE;
14515 int has_trailing_pathsep = FALSE;
14516 int limit = 100;
14518 p = vim_strsave(p);
14520 if (p[0] == '.' && (vim_ispathsep(p[1])
14521 || (p[1] == '.' && (vim_ispathsep(p[2])))))
14522 is_relative_to_current = TRUE;
14524 len = STRLEN(p);
14525 if (len > 0 && after_pathsep(p, p + len))
14526 has_trailing_pathsep = TRUE;
14528 q = getnextcomp(p);
14529 if (*q != NUL)
14531 /* Separate the first path component in "p", and keep the
14532 * remainder (beginning with the path separator). */
14533 remain = vim_strsave(q - 1);
14534 q[-1] = NUL;
14537 for (;;)
14539 for (;;)
14541 len = readlink((char *)p, (char *)buf, MAXPATHL);
14542 if (len <= 0)
14543 break;
14544 buf[len] = NUL;
14546 if (limit-- == 0)
14548 vim_free(p);
14549 vim_free(remain);
14550 EMSG(_("E655: Too many symbolic links (cycle?)"));
14551 rettv->vval.v_string = NULL;
14552 goto fail;
14555 /* Ensure that the result will have a trailing path separator
14556 * if the argument has one. */
14557 if (remain == NULL && has_trailing_pathsep)
14558 add_pathsep(buf);
14560 /* Separate the first path component in the link value and
14561 * concatenate the remainders. */
14562 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
14563 if (*q != NUL)
14565 if (remain == NULL)
14566 remain = vim_strsave(q - 1);
14567 else
14569 cpy = concat_str(q - 1, remain);
14570 if (cpy != NULL)
14572 vim_free(remain);
14573 remain = cpy;
14576 q[-1] = NUL;
14579 q = gettail(p);
14580 if (q > p && *q == NUL)
14582 /* Ignore trailing path separator. */
14583 q[-1] = NUL;
14584 q = gettail(p);
14586 if (q > p && !mch_isFullName(buf))
14588 /* symlink is relative to directory of argument */
14589 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
14590 if (cpy != NULL)
14592 STRCPY(cpy, p);
14593 STRCPY(gettail(cpy), buf);
14594 vim_free(p);
14595 p = cpy;
14598 else
14600 vim_free(p);
14601 p = vim_strsave(buf);
14605 if (remain == NULL)
14606 break;
14608 /* Append the first path component of "remain" to "p". */
14609 q = getnextcomp(remain + 1);
14610 len = q - remain - (*q != NUL);
14611 cpy = vim_strnsave(p, STRLEN(p) + len);
14612 if (cpy != NULL)
14614 STRNCAT(cpy, remain, len);
14615 vim_free(p);
14616 p = cpy;
14618 /* Shorten "remain". */
14619 if (*q != NUL)
14620 STRMOVE(remain, q - 1);
14621 else
14623 vim_free(remain);
14624 remain = NULL;
14628 /* If the result is a relative path name, make it explicitly relative to
14629 * the current directory if and only if the argument had this form. */
14630 if (!vim_ispathsep(*p))
14632 if (is_relative_to_current
14633 && *p != NUL
14634 && !(p[0] == '.'
14635 && (p[1] == NUL
14636 || vim_ispathsep(p[1])
14637 || (p[1] == '.'
14638 && (p[2] == NUL
14639 || vim_ispathsep(p[2]))))))
14641 /* Prepend "./". */
14642 cpy = concat_str((char_u *)"./", p);
14643 if (cpy != NULL)
14645 vim_free(p);
14646 p = cpy;
14649 else if (!is_relative_to_current)
14651 /* Strip leading "./". */
14652 q = p;
14653 while (q[0] == '.' && vim_ispathsep(q[1]))
14654 q += 2;
14655 if (q > p)
14656 STRMOVE(p, p + 2);
14660 /* Ensure that the result will have no trailing path separator
14661 * if the argument had none. But keep "/" or "//". */
14662 if (!has_trailing_pathsep)
14664 q = p + STRLEN(p);
14665 if (after_pathsep(p, q))
14666 *gettail_sep(p) = NUL;
14669 rettv->vval.v_string = p;
14671 # else
14672 rettv->vval.v_string = vim_strsave(p);
14673 # endif
14674 #endif
14676 simplify_filename(rettv->vval.v_string);
14678 #ifdef HAVE_READLINK
14679 fail:
14680 #endif
14681 rettv->v_type = VAR_STRING;
14685 * "reverse({list})" function
14687 static void
14688 f_reverse(argvars, rettv)
14689 typval_T *argvars;
14690 typval_T *rettv;
14692 list_T *l;
14693 listitem_T *li, *ni;
14695 if (argvars[0].v_type != VAR_LIST)
14696 EMSG2(_(e_listarg), "reverse()");
14697 else if ((l = argvars[0].vval.v_list) != NULL
14698 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
14700 li = l->lv_last;
14701 l->lv_first = l->lv_last = NULL;
14702 l->lv_len = 0;
14703 while (li != NULL)
14705 ni = li->li_prev;
14706 list_append(l, li);
14707 li = ni;
14709 rettv->vval.v_list = l;
14710 rettv->v_type = VAR_LIST;
14711 ++l->lv_refcount;
14712 l->lv_idx = l->lv_len - l->lv_idx - 1;
14716 #define SP_NOMOVE 0x01 /* don't move cursor */
14717 #define SP_REPEAT 0x02 /* repeat to find outer pair */
14718 #define SP_RETCOUNT 0x04 /* return matchcount */
14719 #define SP_SETPCMARK 0x08 /* set previous context mark */
14720 #define SP_START 0x10 /* accept match at start position */
14721 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
14722 #define SP_END 0x40 /* leave cursor at end of match */
14724 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
14727 * Get flags for a search function.
14728 * Possibly sets "p_ws".
14729 * Returns BACKWARD, FORWARD or zero (for an error).
14731 static int
14732 get_search_arg(varp, flagsp)
14733 typval_T *varp;
14734 int *flagsp;
14736 int dir = FORWARD;
14737 char_u *flags;
14738 char_u nbuf[NUMBUFLEN];
14739 int mask;
14741 if (varp->v_type != VAR_UNKNOWN)
14743 flags = get_tv_string_buf_chk(varp, nbuf);
14744 if (flags == NULL)
14745 return 0; /* type error; errmsg already given */
14746 while (*flags != NUL)
14748 switch (*flags)
14750 case 'b': dir = BACKWARD; break;
14751 case 'w': p_ws = TRUE; break;
14752 case 'W': p_ws = FALSE; break;
14753 default: mask = 0;
14754 if (flagsp != NULL)
14755 switch (*flags)
14757 case 'c': mask = SP_START; break;
14758 case 'e': mask = SP_END; break;
14759 case 'm': mask = SP_RETCOUNT; break;
14760 case 'n': mask = SP_NOMOVE; break;
14761 case 'p': mask = SP_SUBPAT; break;
14762 case 'r': mask = SP_REPEAT; break;
14763 case 's': mask = SP_SETPCMARK; break;
14765 if (mask == 0)
14767 EMSG2(_(e_invarg2), flags);
14768 dir = 0;
14770 else
14771 *flagsp |= mask;
14773 if (dir == 0)
14774 break;
14775 ++flags;
14778 return dir;
14782 * Shared by search() and searchpos() functions
14784 static int
14785 search_cmn(argvars, match_pos, flagsp)
14786 typval_T *argvars;
14787 pos_T *match_pos;
14788 int *flagsp;
14790 int flags;
14791 char_u *pat;
14792 pos_T pos;
14793 pos_T save_cursor;
14794 int save_p_ws = p_ws;
14795 int dir;
14796 int retval = 0; /* default: FAIL */
14797 long lnum_stop = 0;
14798 proftime_T tm;
14799 #ifdef FEAT_RELTIME
14800 long time_limit = 0;
14801 #endif
14802 int options = SEARCH_KEEP;
14803 int subpatnum;
14805 pat = get_tv_string(&argvars[0]);
14806 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
14807 if (dir == 0)
14808 goto theend;
14809 flags = *flagsp;
14810 if (flags & SP_START)
14811 options |= SEARCH_START;
14812 if (flags & SP_END)
14813 options |= SEARCH_END;
14815 /* Optional arguments: line number to stop searching and timeout. */
14816 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
14818 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
14819 if (lnum_stop < 0)
14820 goto theend;
14821 #ifdef FEAT_RELTIME
14822 if (argvars[3].v_type != VAR_UNKNOWN)
14824 time_limit = get_tv_number_chk(&argvars[3], NULL);
14825 if (time_limit < 0)
14826 goto theend;
14828 #endif
14831 #ifdef FEAT_RELTIME
14832 /* Set the time limit, if there is one. */
14833 profile_setlimit(time_limit, &tm);
14834 #endif
14837 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
14838 * Check to make sure only those flags are set.
14839 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
14840 * flags cannot be set. Check for that condition also.
14842 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
14843 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14845 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
14846 goto theend;
14849 pos = save_cursor = curwin->w_cursor;
14850 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14851 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
14852 if (subpatnum != FAIL)
14854 if (flags & SP_SUBPAT)
14855 retval = subpatnum;
14856 else
14857 retval = pos.lnum;
14858 if (flags & SP_SETPCMARK)
14859 setpcmark();
14860 curwin->w_cursor = pos;
14861 if (match_pos != NULL)
14863 /* Store the match cursor position */
14864 match_pos->lnum = pos.lnum;
14865 match_pos->col = pos.col + 1;
14867 /* "/$" will put the cursor after the end of the line, may need to
14868 * correct that here */
14869 check_cursor();
14872 /* If 'n' flag is used: restore cursor position. */
14873 if (flags & SP_NOMOVE)
14874 curwin->w_cursor = save_cursor;
14875 else
14876 curwin->w_set_curswant = TRUE;
14877 theend:
14878 p_ws = save_p_ws;
14880 return retval;
14883 #ifdef FEAT_FLOAT
14885 * "round({float})" function
14887 static void
14888 f_round(argvars, rettv)
14889 typval_T *argvars;
14890 typval_T *rettv;
14892 float_T f;
14894 rettv->v_type = VAR_FLOAT;
14895 if (get_float_arg(argvars, &f) == OK)
14896 /* round() is not in C90, use ceil() or floor() instead. */
14897 rettv->vval.v_float = f > 0 ? floor(f + 0.5) : ceil(f - 0.5);
14898 else
14899 rettv->vval.v_float = 0.0;
14901 #endif
14904 * "search()" function
14906 static void
14907 f_search(argvars, rettv)
14908 typval_T *argvars;
14909 typval_T *rettv;
14911 int flags = 0;
14913 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
14917 * "searchdecl()" function
14919 static void
14920 f_searchdecl(argvars, rettv)
14921 typval_T *argvars;
14922 typval_T *rettv;
14924 int locally = 1;
14925 int thisblock = 0;
14926 int error = FALSE;
14927 char_u *name;
14929 rettv->vval.v_number = 1; /* default: FAIL */
14931 name = get_tv_string_chk(&argvars[0]);
14932 if (argvars[1].v_type != VAR_UNKNOWN)
14934 locally = get_tv_number_chk(&argvars[1], &error) == 0;
14935 if (!error && argvars[2].v_type != VAR_UNKNOWN)
14936 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
14938 if (!error && name != NULL)
14939 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
14940 locally, thisblock, SEARCH_KEEP) == FAIL;
14944 * Used by searchpair() and searchpairpos()
14946 static int
14947 searchpair_cmn(argvars, match_pos)
14948 typval_T *argvars;
14949 pos_T *match_pos;
14951 char_u *spat, *mpat, *epat;
14952 char_u *skip;
14953 int save_p_ws = p_ws;
14954 int dir;
14955 int flags = 0;
14956 char_u nbuf1[NUMBUFLEN];
14957 char_u nbuf2[NUMBUFLEN];
14958 char_u nbuf3[NUMBUFLEN];
14959 int retval = 0; /* default: FAIL */
14960 long lnum_stop = 0;
14961 long time_limit = 0;
14963 /* Get the three pattern arguments: start, middle, end. */
14964 spat = get_tv_string_chk(&argvars[0]);
14965 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
14966 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
14967 if (spat == NULL || mpat == NULL || epat == NULL)
14968 goto theend; /* type error */
14970 /* Handle the optional fourth argument: flags */
14971 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
14972 if (dir == 0)
14973 goto theend;
14975 /* Don't accept SP_END or SP_SUBPAT.
14976 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
14978 if ((flags & (SP_END | SP_SUBPAT)) != 0
14979 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14981 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
14982 goto theend;
14985 /* Using 'r' implies 'W', otherwise it doesn't work. */
14986 if (flags & SP_REPEAT)
14987 p_ws = FALSE;
14989 /* Optional fifth argument: skip expression */
14990 if (argvars[3].v_type == VAR_UNKNOWN
14991 || argvars[4].v_type == VAR_UNKNOWN)
14992 skip = (char_u *)"";
14993 else
14995 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
14996 if (argvars[5].v_type != VAR_UNKNOWN)
14998 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
14999 if (lnum_stop < 0)
15000 goto theend;
15001 #ifdef FEAT_RELTIME
15002 if (argvars[6].v_type != VAR_UNKNOWN)
15004 time_limit = get_tv_number_chk(&argvars[6], NULL);
15005 if (time_limit < 0)
15006 goto theend;
15008 #endif
15011 if (skip == NULL)
15012 goto theend; /* type error */
15014 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
15015 match_pos, lnum_stop, time_limit);
15017 theend:
15018 p_ws = save_p_ws;
15020 return retval;
15024 * "searchpair()" function
15026 static void
15027 f_searchpair(argvars, rettv)
15028 typval_T *argvars;
15029 typval_T *rettv;
15031 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
15035 * "searchpairpos()" function
15037 static void
15038 f_searchpairpos(argvars, rettv)
15039 typval_T *argvars;
15040 typval_T *rettv;
15042 pos_T match_pos;
15043 int lnum = 0;
15044 int col = 0;
15046 if (rettv_list_alloc(rettv) == FAIL)
15047 return;
15049 if (searchpair_cmn(argvars, &match_pos) > 0)
15051 lnum = match_pos.lnum;
15052 col = match_pos.col;
15055 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15056 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15060 * Search for a start/middle/end thing.
15061 * Used by searchpair(), see its documentation for the details.
15062 * Returns 0 or -1 for no match,
15064 long
15065 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
15066 lnum_stop, time_limit)
15067 char_u *spat; /* start pattern */
15068 char_u *mpat; /* middle pattern */
15069 char_u *epat; /* end pattern */
15070 int dir; /* BACKWARD or FORWARD */
15071 char_u *skip; /* skip expression */
15072 int flags; /* SP_SETPCMARK and other SP_ values */
15073 pos_T *match_pos;
15074 linenr_T lnum_stop; /* stop at this line if not zero */
15075 long time_limit; /* stop after this many msec */
15077 char_u *save_cpo;
15078 char_u *pat, *pat2 = NULL, *pat3 = NULL;
15079 long retval = 0;
15080 pos_T pos;
15081 pos_T firstpos;
15082 pos_T foundpos;
15083 pos_T save_cursor;
15084 pos_T save_pos;
15085 int n;
15086 int r;
15087 int nest = 1;
15088 int err;
15089 int options = SEARCH_KEEP;
15090 proftime_T tm;
15092 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15093 save_cpo = p_cpo;
15094 p_cpo = empty_option;
15096 #ifdef FEAT_RELTIME
15097 /* Set the time limit, if there is one. */
15098 profile_setlimit(time_limit, &tm);
15099 #endif
15101 /* Make two search patterns: start/end (pat2, for in nested pairs) and
15102 * start/middle/end (pat3, for the top pair). */
15103 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
15104 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
15105 if (pat2 == NULL || pat3 == NULL)
15106 goto theend;
15107 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
15108 if (*mpat == NUL)
15109 STRCPY(pat3, pat2);
15110 else
15111 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
15112 spat, epat, mpat);
15113 if (flags & SP_START)
15114 options |= SEARCH_START;
15116 save_cursor = curwin->w_cursor;
15117 pos = curwin->w_cursor;
15118 clearpos(&firstpos);
15119 clearpos(&foundpos);
15120 pat = pat3;
15121 for (;;)
15123 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15124 options, RE_SEARCH, lnum_stop, &tm);
15125 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
15126 /* didn't find it or found the first match again: FAIL */
15127 break;
15129 if (firstpos.lnum == 0)
15130 firstpos = pos;
15131 if (equalpos(pos, foundpos))
15133 /* Found the same position again. Can happen with a pattern that
15134 * has "\zs" at the end and searching backwards. Advance one
15135 * character and try again. */
15136 if (dir == BACKWARD)
15137 decl(&pos);
15138 else
15139 incl(&pos);
15141 foundpos = pos;
15143 /* clear the start flag to avoid getting stuck here */
15144 options &= ~SEARCH_START;
15146 /* If the skip pattern matches, ignore this match. */
15147 if (*skip != NUL)
15149 save_pos = curwin->w_cursor;
15150 curwin->w_cursor = pos;
15151 r = eval_to_bool(skip, &err, NULL, FALSE);
15152 curwin->w_cursor = save_pos;
15153 if (err)
15155 /* Evaluating {skip} caused an error, break here. */
15156 curwin->w_cursor = save_cursor;
15157 retval = -1;
15158 break;
15160 if (r)
15161 continue;
15164 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
15166 /* Found end when searching backwards or start when searching
15167 * forward: nested pair. */
15168 ++nest;
15169 pat = pat2; /* nested, don't search for middle */
15171 else
15173 /* Found end when searching forward or start when searching
15174 * backward: end of (nested) pair; or found middle in outer pair. */
15175 if (--nest == 1)
15176 pat = pat3; /* outer level, search for middle */
15179 if (nest == 0)
15181 /* Found the match: return matchcount or line number. */
15182 if (flags & SP_RETCOUNT)
15183 ++retval;
15184 else
15185 retval = pos.lnum;
15186 if (flags & SP_SETPCMARK)
15187 setpcmark();
15188 curwin->w_cursor = pos;
15189 if (!(flags & SP_REPEAT))
15190 break;
15191 nest = 1; /* search for next unmatched */
15195 if (match_pos != NULL)
15197 /* Store the match cursor position */
15198 match_pos->lnum = curwin->w_cursor.lnum;
15199 match_pos->col = curwin->w_cursor.col + 1;
15202 /* If 'n' flag is used or search failed: restore cursor position. */
15203 if ((flags & SP_NOMOVE) || retval == 0)
15204 curwin->w_cursor = save_cursor;
15206 theend:
15207 vim_free(pat2);
15208 vim_free(pat3);
15209 if (p_cpo == empty_option)
15210 p_cpo = save_cpo;
15211 else
15212 /* Darn, evaluating the {skip} expression changed the value. */
15213 free_string_option(save_cpo);
15215 return retval;
15219 * "searchpos()" function
15221 static void
15222 f_searchpos(argvars, rettv)
15223 typval_T *argvars;
15224 typval_T *rettv;
15226 pos_T match_pos;
15227 int lnum = 0;
15228 int col = 0;
15229 int n;
15230 int flags = 0;
15232 if (rettv_list_alloc(rettv) == FAIL)
15233 return;
15235 n = search_cmn(argvars, &match_pos, &flags);
15236 if (n > 0)
15238 lnum = match_pos.lnum;
15239 col = match_pos.col;
15242 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15243 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15244 if (flags & SP_SUBPAT)
15245 list_append_number(rettv->vval.v_list, (varnumber_T)n);
15249 static void
15250 f_server2client(argvars, rettv)
15251 typval_T *argvars UNUSED;
15252 typval_T *rettv;
15254 #ifdef FEAT_CLIENTSERVER
15255 char_u buf[NUMBUFLEN];
15256 char_u *server = get_tv_string_chk(&argvars[0]);
15257 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
15259 rettv->vval.v_number = -1;
15260 if (server == NULL || reply == NULL)
15261 return;
15262 if (check_restricted() || check_secure())
15263 return;
15264 # ifdef FEAT_X11
15265 if (check_connection() == FAIL)
15266 return;
15267 # endif
15269 if (serverSendReply(server, reply) < 0)
15271 EMSG(_("E258: Unable to send to client"));
15272 return;
15274 rettv->vval.v_number = 0;
15275 #else
15276 rettv->vval.v_number = -1;
15277 #endif
15280 static void
15281 f_serverlist(argvars, rettv)
15282 typval_T *argvars UNUSED;
15283 typval_T *rettv;
15285 char_u *r = NULL;
15287 #ifdef FEAT_CLIENTSERVER
15288 # ifdef WIN32
15289 r = serverGetVimNames();
15290 # else
15291 make_connection();
15292 if (X_DISPLAY != NULL)
15293 r = serverGetVimNames(X_DISPLAY);
15294 # endif
15295 #endif
15296 rettv->v_type = VAR_STRING;
15297 rettv->vval.v_string = r;
15301 * "setbufvar()" function
15303 static void
15304 f_setbufvar(argvars, rettv)
15305 typval_T *argvars;
15306 typval_T *rettv UNUSED;
15308 buf_T *buf;
15309 aco_save_T aco;
15310 char_u *varname, *bufvarname;
15311 typval_T *varp;
15312 char_u nbuf[NUMBUFLEN];
15314 if (check_restricted() || check_secure())
15315 return;
15316 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
15317 varname = get_tv_string_chk(&argvars[1]);
15318 buf = get_buf_tv(&argvars[0]);
15319 varp = &argvars[2];
15321 if (buf != NULL && varname != NULL && varp != NULL)
15323 /* set curbuf to be our buf, temporarily */
15324 aucmd_prepbuf(&aco, buf);
15326 if (*varname == '&')
15328 long numval;
15329 char_u *strval;
15330 int error = FALSE;
15332 ++varname;
15333 numval = get_tv_number_chk(varp, &error);
15334 strval = get_tv_string_buf_chk(varp, nbuf);
15335 if (!error && strval != NULL)
15336 set_option_value(varname, numval, strval, OPT_LOCAL);
15338 else
15340 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
15341 if (bufvarname != NULL)
15343 STRCPY(bufvarname, "b:");
15344 STRCPY(bufvarname + 2, varname);
15345 set_var(bufvarname, varp, TRUE);
15346 vim_free(bufvarname);
15350 /* reset notion of buffer */
15351 aucmd_restbuf(&aco);
15356 * "setcmdpos()" function
15358 static void
15359 f_setcmdpos(argvars, rettv)
15360 typval_T *argvars;
15361 typval_T *rettv;
15363 int pos = (int)get_tv_number(&argvars[0]) - 1;
15365 if (pos >= 0)
15366 rettv->vval.v_number = set_cmdline_pos(pos);
15370 * "setline()" function
15372 static void
15373 f_setline(argvars, rettv)
15374 typval_T *argvars;
15375 typval_T *rettv;
15377 linenr_T lnum;
15378 char_u *line = NULL;
15379 list_T *l = NULL;
15380 listitem_T *li = NULL;
15381 long added = 0;
15382 linenr_T lcount = curbuf->b_ml.ml_line_count;
15384 lnum = get_tv_lnum(&argvars[0]);
15385 if (argvars[1].v_type == VAR_LIST)
15387 l = argvars[1].vval.v_list;
15388 li = l->lv_first;
15390 else
15391 line = get_tv_string_chk(&argvars[1]);
15393 /* default result is zero == OK */
15394 for (;;)
15396 if (l != NULL)
15398 /* list argument, get next string */
15399 if (li == NULL)
15400 break;
15401 line = get_tv_string_chk(&li->li_tv);
15402 li = li->li_next;
15405 rettv->vval.v_number = 1; /* FAIL */
15406 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
15407 break;
15408 if (lnum <= curbuf->b_ml.ml_line_count)
15410 /* existing line, replace it */
15411 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
15413 changed_bytes(lnum, 0);
15414 if (lnum == curwin->w_cursor.lnum)
15415 check_cursor_col();
15416 rettv->vval.v_number = 0; /* OK */
15419 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
15421 /* lnum is one past the last line, append the line */
15422 ++added;
15423 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
15424 rettv->vval.v_number = 0; /* OK */
15427 if (l == NULL) /* only one string argument */
15428 break;
15429 ++lnum;
15432 if (added > 0)
15433 appended_lines_mark(lcount, added);
15436 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
15439 * Used by "setqflist()" and "setloclist()" functions
15441 static void
15442 set_qf_ll_list(wp, list_arg, action_arg, rettv)
15443 win_T *wp UNUSED;
15444 typval_T *list_arg UNUSED;
15445 typval_T *action_arg UNUSED;
15446 typval_T *rettv;
15448 #ifdef FEAT_QUICKFIX
15449 char_u *act;
15450 int action = ' ';
15451 #endif
15453 rettv->vval.v_number = -1;
15455 #ifdef FEAT_QUICKFIX
15456 if (list_arg->v_type != VAR_LIST)
15457 EMSG(_(e_listreq));
15458 else
15460 list_T *l = list_arg->vval.v_list;
15462 if (action_arg->v_type == VAR_STRING)
15464 act = get_tv_string_chk(action_arg);
15465 if (act == NULL)
15466 return; /* type error; errmsg already given */
15467 if (*act == 'a' || *act == 'r')
15468 action = *act;
15471 if (l != NULL && set_errorlist(wp, l, action) == OK)
15472 rettv->vval.v_number = 0;
15474 #endif
15478 * "setloclist()" function
15480 static void
15481 f_setloclist(argvars, rettv)
15482 typval_T *argvars;
15483 typval_T *rettv;
15485 win_T *win;
15487 rettv->vval.v_number = -1;
15489 win = find_win_by_nr(&argvars[0], NULL);
15490 if (win != NULL)
15491 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
15495 * "setmatches()" function
15497 static void
15498 f_setmatches(argvars, rettv)
15499 typval_T *argvars;
15500 typval_T *rettv;
15502 #ifdef FEAT_SEARCH_EXTRA
15503 list_T *l;
15504 listitem_T *li;
15505 dict_T *d;
15507 rettv->vval.v_number = -1;
15508 if (argvars[0].v_type != VAR_LIST)
15510 EMSG(_(e_listreq));
15511 return;
15513 if ((l = argvars[0].vval.v_list) != NULL)
15516 /* To some extent make sure that we are dealing with a list from
15517 * "getmatches()". */
15518 li = l->lv_first;
15519 while (li != NULL)
15521 if (li->li_tv.v_type != VAR_DICT
15522 || (d = li->li_tv.vval.v_dict) == NULL)
15524 EMSG(_(e_invarg));
15525 return;
15527 if (!(dict_find(d, (char_u *)"group", -1) != NULL
15528 && dict_find(d, (char_u *)"pattern", -1) != NULL
15529 && dict_find(d, (char_u *)"priority", -1) != NULL
15530 && dict_find(d, (char_u *)"id", -1) != NULL))
15532 EMSG(_(e_invarg));
15533 return;
15535 li = li->li_next;
15538 clear_matches(curwin);
15539 li = l->lv_first;
15540 while (li != NULL)
15542 d = li->li_tv.vval.v_dict;
15543 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
15544 get_dict_string(d, (char_u *)"pattern", FALSE),
15545 (int)get_dict_number(d, (char_u *)"priority"),
15546 (int)get_dict_number(d, (char_u *)"id"));
15547 li = li->li_next;
15549 rettv->vval.v_number = 0;
15551 #endif
15555 * "setpos()" function
15557 static void
15558 f_setpos(argvars, rettv)
15559 typval_T *argvars;
15560 typval_T *rettv;
15562 pos_T pos;
15563 int fnum;
15564 char_u *name;
15566 rettv->vval.v_number = -1;
15567 name = get_tv_string_chk(argvars);
15568 if (name != NULL)
15570 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
15572 if (--pos.col < 0)
15573 pos.col = 0;
15574 if (name[0] == '.' && name[1] == NUL)
15576 /* set cursor */
15577 if (fnum == curbuf->b_fnum)
15579 curwin->w_cursor = pos;
15580 check_cursor();
15581 rettv->vval.v_number = 0;
15583 else
15584 EMSG(_(e_invarg));
15586 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
15588 /* set mark */
15589 if (setmark_pos(name[1], &pos, fnum) == OK)
15590 rettv->vval.v_number = 0;
15592 else
15593 EMSG(_(e_invarg));
15599 * "setqflist()" function
15601 static void
15602 f_setqflist(argvars, rettv)
15603 typval_T *argvars;
15604 typval_T *rettv;
15606 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
15610 * "setreg()" function
15612 static void
15613 f_setreg(argvars, rettv)
15614 typval_T *argvars;
15615 typval_T *rettv;
15617 int regname;
15618 char_u *strregname;
15619 char_u *stropt;
15620 char_u *strval;
15621 int append;
15622 char_u yank_type;
15623 long block_len;
15625 block_len = -1;
15626 yank_type = MAUTO;
15627 append = FALSE;
15629 strregname = get_tv_string_chk(argvars);
15630 rettv->vval.v_number = 1; /* FAIL is default */
15632 if (strregname == NULL)
15633 return; /* type error; errmsg already given */
15634 regname = *strregname;
15635 if (regname == 0 || regname == '@')
15636 regname = '"';
15637 else if (regname == '=')
15638 return;
15640 if (argvars[2].v_type != VAR_UNKNOWN)
15642 stropt = get_tv_string_chk(&argvars[2]);
15643 if (stropt == NULL)
15644 return; /* type error */
15645 for (; *stropt != NUL; ++stropt)
15646 switch (*stropt)
15648 case 'a': case 'A': /* append */
15649 append = TRUE;
15650 break;
15651 case 'v': case 'c': /* character-wise selection */
15652 yank_type = MCHAR;
15653 break;
15654 case 'V': case 'l': /* line-wise selection */
15655 yank_type = MLINE;
15656 break;
15657 #ifdef FEAT_VISUAL
15658 case 'b': case Ctrl_V: /* block-wise selection */
15659 yank_type = MBLOCK;
15660 if (VIM_ISDIGIT(stropt[1]))
15662 ++stropt;
15663 block_len = getdigits(&stropt) - 1;
15664 --stropt;
15666 break;
15667 #endif
15671 strval = get_tv_string_chk(&argvars[1]);
15672 if (strval != NULL)
15673 write_reg_contents_ex(regname, strval, -1,
15674 append, yank_type, block_len);
15675 rettv->vval.v_number = 0;
15679 * "settabwinvar()" function
15681 static void
15682 f_settabwinvar(argvars, rettv)
15683 typval_T *argvars;
15684 typval_T *rettv;
15686 setwinvar(argvars, rettv, 1);
15690 * "setwinvar()" function
15692 static void
15693 f_setwinvar(argvars, rettv)
15694 typval_T *argvars;
15695 typval_T *rettv;
15697 setwinvar(argvars, rettv, 0);
15701 * "setwinvar()" and "settabwinvar()" functions
15703 static void
15704 setwinvar(argvars, rettv, off)
15705 typval_T *argvars;
15706 typval_T *rettv UNUSED;
15707 int off;
15709 win_T *win;
15710 #ifdef FEAT_WINDOWS
15711 win_T *save_curwin;
15712 tabpage_T *save_curtab;
15713 #endif
15714 char_u *varname, *winvarname;
15715 typval_T *varp;
15716 char_u nbuf[NUMBUFLEN];
15717 tabpage_T *tp;
15719 if (check_restricted() || check_secure())
15720 return;
15722 #ifdef FEAT_WINDOWS
15723 if (off == 1)
15724 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
15725 else
15726 tp = curtab;
15727 #endif
15728 win = find_win_by_nr(&argvars[off], tp);
15729 varname = get_tv_string_chk(&argvars[off + 1]);
15730 varp = &argvars[off + 2];
15732 if (win != NULL && varname != NULL && varp != NULL)
15734 #ifdef FEAT_WINDOWS
15735 /* set curwin to be our win, temporarily */
15736 save_curwin = curwin;
15737 save_curtab = curtab;
15738 goto_tabpage_tp(tp);
15739 if (!win_valid(win))
15740 return;
15741 curwin = win;
15742 curbuf = curwin->w_buffer;
15743 #endif
15745 if (*varname == '&')
15747 long numval;
15748 char_u *strval;
15749 int error = FALSE;
15751 ++varname;
15752 numval = get_tv_number_chk(varp, &error);
15753 strval = get_tv_string_buf_chk(varp, nbuf);
15754 if (!error && strval != NULL)
15755 set_option_value(varname, numval, strval, OPT_LOCAL);
15757 else
15759 winvarname = alloc((unsigned)STRLEN(varname) + 3);
15760 if (winvarname != NULL)
15762 STRCPY(winvarname, "w:");
15763 STRCPY(winvarname + 2, varname);
15764 set_var(winvarname, varp, TRUE);
15765 vim_free(winvarname);
15769 #ifdef FEAT_WINDOWS
15770 /* Restore current tabpage and window, if still valid (autocomands can
15771 * make them invalid). */
15772 if (valid_tabpage(save_curtab))
15773 goto_tabpage_tp(save_curtab);
15774 if (win_valid(save_curwin))
15776 curwin = save_curwin;
15777 curbuf = curwin->w_buffer;
15779 #endif
15784 * "shellescape({string})" function
15786 static void
15787 f_shellescape(argvars, rettv)
15788 typval_T *argvars;
15789 typval_T *rettv;
15791 rettv->vval.v_string = vim_strsave_shellescape(
15792 get_tv_string(&argvars[0]), non_zero_arg(&argvars[1]));
15793 rettv->v_type = VAR_STRING;
15797 * "simplify()" function
15799 static void
15800 f_simplify(argvars, rettv)
15801 typval_T *argvars;
15802 typval_T *rettv;
15804 char_u *p;
15806 p = get_tv_string(&argvars[0]);
15807 rettv->vval.v_string = vim_strsave(p);
15808 simplify_filename(rettv->vval.v_string); /* simplify in place */
15809 rettv->v_type = VAR_STRING;
15812 #ifdef FEAT_FLOAT
15814 * "sin()" function
15816 static void
15817 f_sin(argvars, rettv)
15818 typval_T *argvars;
15819 typval_T *rettv;
15821 float_T f;
15823 rettv->v_type = VAR_FLOAT;
15824 if (get_float_arg(argvars, &f) == OK)
15825 rettv->vval.v_float = sin(f);
15826 else
15827 rettv->vval.v_float = 0.0;
15829 #endif
15831 static int
15832 #ifdef __BORLANDC__
15833 _RTLENTRYF
15834 #endif
15835 item_compare __ARGS((const void *s1, const void *s2));
15836 static int
15837 #ifdef __BORLANDC__
15838 _RTLENTRYF
15839 #endif
15840 item_compare2 __ARGS((const void *s1, const void *s2));
15842 static int item_compare_ic;
15843 static char_u *item_compare_func;
15844 static int item_compare_func_err;
15845 #define ITEM_COMPARE_FAIL 999
15848 * Compare functions for f_sort() below.
15850 static int
15851 #ifdef __BORLANDC__
15852 _RTLENTRYF
15853 #endif
15854 item_compare(s1, s2)
15855 const void *s1;
15856 const void *s2;
15858 char_u *p1, *p2;
15859 char_u *tofree1, *tofree2;
15860 int res;
15861 char_u numbuf1[NUMBUFLEN];
15862 char_u numbuf2[NUMBUFLEN];
15864 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
15865 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
15866 if (p1 == NULL)
15867 p1 = (char_u *)"";
15868 if (p2 == NULL)
15869 p2 = (char_u *)"";
15870 if (item_compare_ic)
15871 res = STRICMP(p1, p2);
15872 else
15873 res = STRCMP(p1, p2);
15874 vim_free(tofree1);
15875 vim_free(tofree2);
15876 return res;
15879 static int
15880 #ifdef __BORLANDC__
15881 _RTLENTRYF
15882 #endif
15883 item_compare2(s1, s2)
15884 const void *s1;
15885 const void *s2;
15887 int res;
15888 typval_T rettv;
15889 typval_T argv[3];
15890 int dummy;
15892 /* shortcut after failure in previous call; compare all items equal */
15893 if (item_compare_func_err)
15894 return 0;
15896 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
15897 * in the copy without changing the original list items. */
15898 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
15899 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
15901 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
15902 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
15903 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
15904 clear_tv(&argv[0]);
15905 clear_tv(&argv[1]);
15907 if (res == FAIL)
15908 res = ITEM_COMPARE_FAIL;
15909 else
15910 res = get_tv_number_chk(&rettv, &item_compare_func_err);
15911 if (item_compare_func_err)
15912 res = ITEM_COMPARE_FAIL; /* return value has wrong type */
15913 clear_tv(&rettv);
15914 return res;
15918 * "sort({list})" function
15920 static void
15921 f_sort(argvars, rettv)
15922 typval_T *argvars;
15923 typval_T *rettv;
15925 list_T *l;
15926 listitem_T *li;
15927 listitem_T **ptrs;
15928 long len;
15929 long i;
15931 if (argvars[0].v_type != VAR_LIST)
15932 EMSG2(_(e_listarg), "sort()");
15933 else
15935 l = argvars[0].vval.v_list;
15936 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
15937 return;
15938 rettv->vval.v_list = l;
15939 rettv->v_type = VAR_LIST;
15940 ++l->lv_refcount;
15942 len = list_len(l);
15943 if (len <= 1)
15944 return; /* short list sorts pretty quickly */
15946 item_compare_ic = FALSE;
15947 item_compare_func = NULL;
15948 if (argvars[1].v_type != VAR_UNKNOWN)
15950 if (argvars[1].v_type == VAR_FUNC)
15951 item_compare_func = argvars[1].vval.v_string;
15952 else
15954 int error = FALSE;
15956 i = get_tv_number_chk(&argvars[1], &error);
15957 if (error)
15958 return; /* type error; errmsg already given */
15959 if (i == 1)
15960 item_compare_ic = TRUE;
15961 else
15962 item_compare_func = get_tv_string(&argvars[1]);
15966 /* Make an array with each entry pointing to an item in the List. */
15967 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
15968 if (ptrs == NULL)
15969 return;
15970 i = 0;
15971 for (li = l->lv_first; li != NULL; li = li->li_next)
15972 ptrs[i++] = li;
15974 item_compare_func_err = FALSE;
15975 /* test the compare function */
15976 if (item_compare_func != NULL
15977 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
15978 == ITEM_COMPARE_FAIL)
15979 EMSG(_("E702: Sort compare function failed"));
15980 else
15982 /* Sort the array with item pointers. */
15983 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
15984 item_compare_func == NULL ? item_compare : item_compare2);
15986 if (!item_compare_func_err)
15988 /* Clear the List and append the items in the sorted order. */
15989 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
15990 l->lv_len = 0;
15991 for (i = 0; i < len; ++i)
15992 list_append(l, ptrs[i]);
15996 vim_free(ptrs);
16001 * "soundfold({word})" function
16003 static void
16004 f_soundfold(argvars, rettv)
16005 typval_T *argvars;
16006 typval_T *rettv;
16008 char_u *s;
16010 rettv->v_type = VAR_STRING;
16011 s = get_tv_string(&argvars[0]);
16012 #ifdef FEAT_SPELL
16013 rettv->vval.v_string = eval_soundfold(s);
16014 #else
16015 rettv->vval.v_string = vim_strsave(s);
16016 #endif
16020 * "spellbadword()" function
16022 static void
16023 f_spellbadword(argvars, rettv)
16024 typval_T *argvars UNUSED;
16025 typval_T *rettv;
16027 char_u *word = (char_u *)"";
16028 hlf_T attr = HLF_COUNT;
16029 int len = 0;
16031 if (rettv_list_alloc(rettv) == FAIL)
16032 return;
16034 #ifdef FEAT_SPELL
16035 if (argvars[0].v_type == VAR_UNKNOWN)
16037 /* Find the start and length of the badly spelled word. */
16038 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
16039 if (len != 0)
16040 word = ml_get_cursor();
16042 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16044 char_u *str = get_tv_string_chk(&argvars[0]);
16045 int capcol = -1;
16047 if (str != NULL)
16049 /* Check the argument for spelling. */
16050 while (*str != NUL)
16052 len = spell_check(curwin, str, &attr, &capcol, FALSE);
16053 if (attr != HLF_COUNT)
16055 word = str;
16056 break;
16058 str += len;
16062 #endif
16064 list_append_string(rettv->vval.v_list, word, len);
16065 list_append_string(rettv->vval.v_list, (char_u *)(
16066 attr == HLF_SPB ? "bad" :
16067 attr == HLF_SPR ? "rare" :
16068 attr == HLF_SPL ? "local" :
16069 attr == HLF_SPC ? "caps" :
16070 ""), -1);
16074 * "spellsuggest()" function
16076 static void
16077 f_spellsuggest(argvars, rettv)
16078 typval_T *argvars UNUSED;
16079 typval_T *rettv;
16081 #ifdef FEAT_SPELL
16082 char_u *str;
16083 int typeerr = FALSE;
16084 int maxcount;
16085 garray_T ga;
16086 int i;
16087 listitem_T *li;
16088 int need_capital = FALSE;
16089 #endif
16091 if (rettv_list_alloc(rettv) == FAIL)
16092 return;
16094 #ifdef FEAT_SPELL
16095 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16097 str = get_tv_string(&argvars[0]);
16098 if (argvars[1].v_type != VAR_UNKNOWN)
16100 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
16101 if (maxcount <= 0)
16102 return;
16103 if (argvars[2].v_type != VAR_UNKNOWN)
16105 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
16106 if (typeerr)
16107 return;
16110 else
16111 maxcount = 25;
16113 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
16115 for (i = 0; i < ga.ga_len; ++i)
16117 str = ((char_u **)ga.ga_data)[i];
16119 li = listitem_alloc();
16120 if (li == NULL)
16121 vim_free(str);
16122 else
16124 li->li_tv.v_type = VAR_STRING;
16125 li->li_tv.v_lock = 0;
16126 li->li_tv.vval.v_string = str;
16127 list_append(rettv->vval.v_list, li);
16130 ga_clear(&ga);
16132 #endif
16135 static void
16136 f_split(argvars, rettv)
16137 typval_T *argvars;
16138 typval_T *rettv;
16140 char_u *str;
16141 char_u *end;
16142 char_u *pat = NULL;
16143 regmatch_T regmatch;
16144 char_u patbuf[NUMBUFLEN];
16145 char_u *save_cpo;
16146 int match;
16147 colnr_T col = 0;
16148 int keepempty = FALSE;
16149 int typeerr = FALSE;
16151 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
16152 save_cpo = p_cpo;
16153 p_cpo = (char_u *)"";
16155 str = get_tv_string(&argvars[0]);
16156 if (argvars[1].v_type != VAR_UNKNOWN)
16158 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16159 if (pat == NULL)
16160 typeerr = TRUE;
16161 if (argvars[2].v_type != VAR_UNKNOWN)
16162 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
16164 if (pat == NULL || *pat == NUL)
16165 pat = (char_u *)"[\\x01- ]\\+";
16167 if (rettv_list_alloc(rettv) == FAIL)
16168 return;
16169 if (typeerr)
16170 return;
16172 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
16173 if (regmatch.regprog != NULL)
16175 regmatch.rm_ic = FALSE;
16176 while (*str != NUL || keepempty)
16178 if (*str == NUL)
16179 match = FALSE; /* empty item at the end */
16180 else
16181 match = vim_regexec_nl(&regmatch, str, col);
16182 if (match)
16183 end = regmatch.startp[0];
16184 else
16185 end = str + STRLEN(str);
16186 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
16187 && *str != NUL && match && end < regmatch.endp[0]))
16189 if (list_append_string(rettv->vval.v_list, str,
16190 (int)(end - str)) == FAIL)
16191 break;
16193 if (!match)
16194 break;
16195 /* Advance to just after the match. */
16196 if (regmatch.endp[0] > str)
16197 col = 0;
16198 else
16200 /* Don't get stuck at the same match. */
16201 #ifdef FEAT_MBYTE
16202 col = (*mb_ptr2len)(regmatch.endp[0]);
16203 #else
16204 col = 1;
16205 #endif
16207 str = regmatch.endp[0];
16210 vim_free(regmatch.regprog);
16213 p_cpo = save_cpo;
16216 #ifdef FEAT_FLOAT
16218 * "sqrt()" function
16220 static void
16221 f_sqrt(argvars, rettv)
16222 typval_T *argvars;
16223 typval_T *rettv;
16225 float_T f;
16227 rettv->v_type = VAR_FLOAT;
16228 if (get_float_arg(argvars, &f) == OK)
16229 rettv->vval.v_float = sqrt(f);
16230 else
16231 rettv->vval.v_float = 0.0;
16235 * "str2float()" function
16237 static void
16238 f_str2float(argvars, rettv)
16239 typval_T *argvars;
16240 typval_T *rettv;
16242 char_u *p = skipwhite(get_tv_string(&argvars[0]));
16244 if (*p == '+')
16245 p = skipwhite(p + 1);
16246 (void)string2float(p, &rettv->vval.v_float);
16247 rettv->v_type = VAR_FLOAT;
16249 #endif
16252 * "str2nr()" function
16254 static void
16255 f_str2nr(argvars, rettv)
16256 typval_T *argvars;
16257 typval_T *rettv;
16259 int base = 10;
16260 char_u *p;
16261 long n;
16263 if (argvars[1].v_type != VAR_UNKNOWN)
16265 base = get_tv_number(&argvars[1]);
16266 if (base != 8 && base != 10 && base != 16)
16268 EMSG(_(e_invarg));
16269 return;
16273 p = skipwhite(get_tv_string(&argvars[0]));
16274 if (*p == '+')
16275 p = skipwhite(p + 1);
16276 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
16277 rettv->vval.v_number = n;
16280 #ifdef HAVE_STRFTIME
16282 * "strftime({format}[, {time}])" function
16284 static void
16285 f_strftime(argvars, rettv)
16286 typval_T *argvars;
16287 typval_T *rettv;
16289 char_u result_buf[256];
16290 struct tm *curtime;
16291 time_t seconds;
16292 char_u *p;
16294 rettv->v_type = VAR_STRING;
16296 p = get_tv_string(&argvars[0]);
16297 if (argvars[1].v_type == VAR_UNKNOWN)
16298 seconds = time(NULL);
16299 else
16300 seconds = (time_t)get_tv_number(&argvars[1]);
16301 curtime = localtime(&seconds);
16302 /* MSVC returns NULL for an invalid value of seconds. */
16303 if (curtime == NULL)
16304 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
16305 else
16307 # ifdef FEAT_MBYTE
16308 vimconv_T conv;
16309 char_u *enc;
16311 conv.vc_type = CONV_NONE;
16312 enc = enc_locale();
16313 convert_setup(&conv, p_enc, enc);
16314 if (conv.vc_type != CONV_NONE)
16315 p = string_convert(&conv, p, NULL);
16316 # endif
16317 if (p != NULL)
16318 (void)strftime((char *)result_buf, sizeof(result_buf),
16319 (char *)p, curtime);
16320 else
16321 result_buf[0] = NUL;
16323 # ifdef FEAT_MBYTE
16324 if (conv.vc_type != CONV_NONE)
16325 vim_free(p);
16326 convert_setup(&conv, enc, p_enc);
16327 if (conv.vc_type != CONV_NONE)
16328 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
16329 else
16330 # endif
16331 rettv->vval.v_string = vim_strsave(result_buf);
16333 # ifdef FEAT_MBYTE
16334 /* Release conversion descriptors */
16335 convert_setup(&conv, NULL, NULL);
16336 vim_free(enc);
16337 # endif
16340 #endif
16343 * "stridx()" function
16345 static void
16346 f_stridx(argvars, rettv)
16347 typval_T *argvars;
16348 typval_T *rettv;
16350 char_u buf[NUMBUFLEN];
16351 char_u *needle;
16352 char_u *haystack;
16353 char_u *save_haystack;
16354 char_u *pos;
16355 int start_idx;
16357 needle = get_tv_string_chk(&argvars[1]);
16358 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
16359 rettv->vval.v_number = -1;
16360 if (needle == NULL || haystack == NULL)
16361 return; /* type error; errmsg already given */
16363 if (argvars[2].v_type != VAR_UNKNOWN)
16365 int error = FALSE;
16367 start_idx = get_tv_number_chk(&argvars[2], &error);
16368 if (error || start_idx >= (int)STRLEN(haystack))
16369 return;
16370 if (start_idx >= 0)
16371 haystack += start_idx;
16374 pos = (char_u *)strstr((char *)haystack, (char *)needle);
16375 if (pos != NULL)
16376 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
16380 * "string()" function
16382 static void
16383 f_string(argvars, rettv)
16384 typval_T *argvars;
16385 typval_T *rettv;
16387 char_u *tofree;
16388 char_u numbuf[NUMBUFLEN];
16390 rettv->v_type = VAR_STRING;
16391 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
16392 /* Make a copy if we have a value but it's not in allocated memory. */
16393 if (rettv->vval.v_string != NULL && tofree == NULL)
16394 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
16398 * "strlen()" function
16400 static void
16401 f_strlen(argvars, rettv)
16402 typval_T *argvars;
16403 typval_T *rettv;
16405 rettv->vval.v_number = (varnumber_T)(STRLEN(
16406 get_tv_string(&argvars[0])));
16410 * "strpart()" function
16412 static void
16413 f_strpart(argvars, rettv)
16414 typval_T *argvars;
16415 typval_T *rettv;
16417 char_u *p;
16418 int n;
16419 int len;
16420 int slen;
16421 int error = FALSE;
16423 p = get_tv_string(&argvars[0]);
16424 slen = (int)STRLEN(p);
16426 n = get_tv_number_chk(&argvars[1], &error);
16427 if (error)
16428 len = 0;
16429 else if (argvars[2].v_type != VAR_UNKNOWN)
16430 len = get_tv_number(&argvars[2]);
16431 else
16432 len = slen - n; /* default len: all bytes that are available. */
16435 * Only return the overlap between the specified part and the actual
16436 * string.
16438 if (n < 0)
16440 len += n;
16441 n = 0;
16443 else if (n > slen)
16444 n = slen;
16445 if (len < 0)
16446 len = 0;
16447 else if (n + len > slen)
16448 len = slen - n;
16450 rettv->v_type = VAR_STRING;
16451 rettv->vval.v_string = vim_strnsave(p + n, len);
16455 * "strridx()" function
16457 static void
16458 f_strridx(argvars, rettv)
16459 typval_T *argvars;
16460 typval_T *rettv;
16462 char_u buf[NUMBUFLEN];
16463 char_u *needle;
16464 char_u *haystack;
16465 char_u *rest;
16466 char_u *lastmatch = NULL;
16467 int haystack_len, end_idx;
16469 needle = get_tv_string_chk(&argvars[1]);
16470 haystack = get_tv_string_buf_chk(&argvars[0], buf);
16472 rettv->vval.v_number = -1;
16473 if (needle == NULL || haystack == NULL)
16474 return; /* type error; errmsg already given */
16476 haystack_len = (int)STRLEN(haystack);
16477 if (argvars[2].v_type != VAR_UNKNOWN)
16479 /* Third argument: upper limit for index */
16480 end_idx = get_tv_number_chk(&argvars[2], NULL);
16481 if (end_idx < 0)
16482 return; /* can never find a match */
16484 else
16485 end_idx = haystack_len;
16487 if (*needle == NUL)
16489 /* Empty string matches past the end. */
16490 lastmatch = haystack + end_idx;
16492 else
16494 for (rest = haystack; *rest != '\0'; ++rest)
16496 rest = (char_u *)strstr((char *)rest, (char *)needle);
16497 if (rest == NULL || rest > haystack + end_idx)
16498 break;
16499 lastmatch = rest;
16503 if (lastmatch == NULL)
16504 rettv->vval.v_number = -1;
16505 else
16506 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
16510 * "strtrans()" function
16512 static void
16513 f_strtrans(argvars, rettv)
16514 typval_T *argvars;
16515 typval_T *rettv;
16517 rettv->v_type = VAR_STRING;
16518 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
16522 * "submatch()" function
16524 static void
16525 f_submatch(argvars, rettv)
16526 typval_T *argvars;
16527 typval_T *rettv;
16529 rettv->v_type = VAR_STRING;
16530 rettv->vval.v_string =
16531 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
16535 * "substitute()" function
16537 static void
16538 f_substitute(argvars, rettv)
16539 typval_T *argvars;
16540 typval_T *rettv;
16542 char_u patbuf[NUMBUFLEN];
16543 char_u subbuf[NUMBUFLEN];
16544 char_u flagsbuf[NUMBUFLEN];
16546 char_u *str = get_tv_string_chk(&argvars[0]);
16547 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16548 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
16549 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
16551 rettv->v_type = VAR_STRING;
16552 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
16553 rettv->vval.v_string = NULL;
16554 else
16555 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
16559 * "synID(lnum, col, trans)" function
16561 static void
16562 f_synID(argvars, rettv)
16563 typval_T *argvars UNUSED;
16564 typval_T *rettv;
16566 int id = 0;
16567 #ifdef FEAT_SYN_HL
16568 long lnum;
16569 long col;
16570 int trans;
16571 int transerr = FALSE;
16573 lnum = get_tv_lnum(argvars); /* -1 on type error */
16574 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16575 trans = get_tv_number_chk(&argvars[2], &transerr);
16577 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16578 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
16579 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
16580 #endif
16582 rettv->vval.v_number = id;
16586 * "synIDattr(id, what [, mode])" function
16588 static void
16589 f_synIDattr(argvars, rettv)
16590 typval_T *argvars UNUSED;
16591 typval_T *rettv;
16593 char_u *p = NULL;
16594 #ifdef FEAT_SYN_HL
16595 int id;
16596 char_u *what;
16597 char_u *mode;
16598 char_u modebuf[NUMBUFLEN];
16599 int modec;
16601 id = get_tv_number(&argvars[0]);
16602 what = get_tv_string(&argvars[1]);
16603 if (argvars[2].v_type != VAR_UNKNOWN)
16605 mode = get_tv_string_buf(&argvars[2], modebuf);
16606 modec = TOLOWER_ASC(mode[0]);
16607 if (modec != 't' && modec != 'c'
16608 #ifdef FEAT_GUI
16609 && modec != 'g'
16610 #endif
16612 modec = 0; /* replace invalid with current */
16614 else
16616 #ifdef FEAT_GUI
16617 if (gui.in_use)
16618 modec = 'g';
16619 else
16620 #endif
16621 if (t_colors > 1)
16622 modec = 'c';
16623 else
16624 modec = 't';
16628 switch (TOLOWER_ASC(what[0]))
16630 case 'b':
16631 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
16632 p = highlight_color(id, what, modec);
16633 else /* bold */
16634 p = highlight_has_attr(id, HL_BOLD, modec);
16635 break;
16637 case 'f': /* fg[#] or font */
16638 p = highlight_color(id, what, modec);
16639 break;
16641 case 'i':
16642 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
16643 p = highlight_has_attr(id, HL_INVERSE, modec);
16644 else /* italic */
16645 p = highlight_has_attr(id, HL_ITALIC, modec);
16646 break;
16648 case 'n': /* name */
16649 p = get_highlight_name(NULL, id - 1);
16650 break;
16652 case 'r': /* reverse */
16653 p = highlight_has_attr(id, HL_INVERSE, modec);
16654 break;
16656 case 's':
16657 if (TOLOWER_ASC(what[1]) == 'p') /* sp[#] */
16658 p = highlight_color(id, what, modec);
16659 else /* standout */
16660 p = highlight_has_attr(id, HL_STANDOUT, modec);
16661 break;
16663 case 'u':
16664 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
16665 /* underline */
16666 p = highlight_has_attr(id, HL_UNDERLINE, modec);
16667 else
16668 /* undercurl */
16669 p = highlight_has_attr(id, HL_UNDERCURL, modec);
16670 break;
16673 if (p != NULL)
16674 p = vim_strsave(p);
16675 #endif
16676 rettv->v_type = VAR_STRING;
16677 rettv->vval.v_string = p;
16681 * "synIDtrans(id)" function
16683 static void
16684 f_synIDtrans(argvars, rettv)
16685 typval_T *argvars UNUSED;
16686 typval_T *rettv;
16688 int id;
16690 #ifdef FEAT_SYN_HL
16691 id = get_tv_number(&argvars[0]);
16693 if (id > 0)
16694 id = syn_get_final_id(id);
16695 else
16696 #endif
16697 id = 0;
16699 rettv->vval.v_number = id;
16703 * "synstack(lnum, col)" function
16705 static void
16706 f_synstack(argvars, rettv)
16707 typval_T *argvars UNUSED;
16708 typval_T *rettv;
16710 #ifdef FEAT_SYN_HL
16711 long lnum;
16712 long col;
16713 int i;
16714 int id;
16715 #endif
16717 rettv->v_type = VAR_LIST;
16718 rettv->vval.v_list = NULL;
16720 #ifdef FEAT_SYN_HL
16721 lnum = get_tv_lnum(argvars); /* -1 on type error */
16722 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16724 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16725 && col >= 0 && (col == 0 || col < (long)STRLEN(ml_get(lnum)))
16726 && rettv_list_alloc(rettv) != FAIL)
16728 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
16729 for (i = 0; ; ++i)
16731 id = syn_get_stack_item(i);
16732 if (id < 0)
16733 break;
16734 if (list_append_number(rettv->vval.v_list, id) == FAIL)
16735 break;
16738 #endif
16742 * "system()" function
16744 static void
16745 f_system(argvars, rettv)
16746 typval_T *argvars;
16747 typval_T *rettv;
16749 char_u *res = NULL;
16750 char_u *p;
16751 char_u *infile = NULL;
16752 char_u buf[NUMBUFLEN];
16753 int err = FALSE;
16754 FILE *fd;
16756 if (check_restricted() || check_secure())
16757 goto done;
16759 if (argvars[1].v_type != VAR_UNKNOWN)
16762 * Write the string to a temp file, to be used for input of the shell
16763 * command.
16765 if ((infile = vim_tempname('i')) == NULL)
16767 EMSG(_(e_notmp));
16768 goto done;
16771 fd = mch_fopen((char *)infile, WRITEBIN);
16772 if (fd == NULL)
16774 EMSG2(_(e_notopen), infile);
16775 goto done;
16777 p = get_tv_string_buf_chk(&argvars[1], buf);
16778 if (p == NULL)
16780 fclose(fd);
16781 goto done; /* type error; errmsg already given */
16783 if (fwrite(p, STRLEN(p), 1, fd) != 1)
16784 err = TRUE;
16785 if (fclose(fd) != 0)
16786 err = TRUE;
16787 if (err)
16789 EMSG(_("E677: Error writing temp file"));
16790 goto done;
16794 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
16795 SHELL_SILENT | SHELL_COOKED);
16797 #ifdef USE_CR
16798 /* translate <CR> into <NL> */
16799 if (res != NULL)
16801 char_u *s;
16803 for (s = res; *s; ++s)
16805 if (*s == CAR)
16806 *s = NL;
16809 #else
16810 # ifdef USE_CRNL
16811 /* translate <CR><NL> into <NL> */
16812 if (res != NULL)
16814 char_u *s, *d;
16816 d = res;
16817 for (s = res; *s; ++s)
16819 if (s[0] == CAR && s[1] == NL)
16820 ++s;
16821 *d++ = *s;
16823 *d = NUL;
16825 # endif
16826 #endif
16828 done:
16829 if (infile != NULL)
16831 mch_remove(infile);
16832 vim_free(infile);
16834 rettv->v_type = VAR_STRING;
16835 rettv->vval.v_string = res;
16839 * "tabpagebuflist()" function
16841 static void
16842 f_tabpagebuflist(argvars, rettv)
16843 typval_T *argvars UNUSED;
16844 typval_T *rettv UNUSED;
16846 #ifdef FEAT_WINDOWS
16847 tabpage_T *tp;
16848 win_T *wp = NULL;
16850 if (argvars[0].v_type == VAR_UNKNOWN)
16851 wp = firstwin;
16852 else
16854 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16855 if (tp != NULL)
16856 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16858 if (wp != NULL && rettv_list_alloc(rettv) != FAIL)
16860 for (; wp != NULL; wp = wp->w_next)
16861 if (list_append_number(rettv->vval.v_list,
16862 wp->w_buffer->b_fnum) == FAIL)
16863 break;
16865 #endif
16870 * "tabpagenr()" function
16872 static void
16873 f_tabpagenr(argvars, rettv)
16874 typval_T *argvars UNUSED;
16875 typval_T *rettv;
16877 int nr = 1;
16878 #ifdef FEAT_WINDOWS
16879 char_u *arg;
16881 if (argvars[0].v_type != VAR_UNKNOWN)
16883 arg = get_tv_string_chk(&argvars[0]);
16884 nr = 0;
16885 if (arg != NULL)
16887 if (STRCMP(arg, "$") == 0)
16888 nr = tabpage_index(NULL) - 1;
16889 else
16890 EMSG2(_(e_invexpr2), arg);
16893 else
16894 nr = tabpage_index(curtab);
16895 #endif
16896 rettv->vval.v_number = nr;
16900 #ifdef FEAT_WINDOWS
16901 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
16904 * Common code for tabpagewinnr() and winnr().
16906 static int
16907 get_winnr(tp, argvar)
16908 tabpage_T *tp;
16909 typval_T *argvar;
16911 win_T *twin;
16912 int nr = 1;
16913 win_T *wp;
16914 char_u *arg;
16916 twin = (tp == curtab) ? curwin : tp->tp_curwin;
16917 if (argvar->v_type != VAR_UNKNOWN)
16919 arg = get_tv_string_chk(argvar);
16920 if (arg == NULL)
16921 nr = 0; /* type error; errmsg already given */
16922 else if (STRCMP(arg, "$") == 0)
16923 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
16924 else if (STRCMP(arg, "#") == 0)
16926 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
16927 if (twin == NULL)
16928 nr = 0;
16930 else
16932 EMSG2(_(e_invexpr2), arg);
16933 nr = 0;
16937 if (nr > 0)
16938 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16939 wp != twin; wp = wp->w_next)
16941 if (wp == NULL)
16943 /* didn't find it in this tabpage */
16944 nr = 0;
16945 break;
16947 ++nr;
16949 return nr;
16951 #endif
16954 * "tabpagewinnr()" function
16956 static void
16957 f_tabpagewinnr(argvars, rettv)
16958 typval_T *argvars UNUSED;
16959 typval_T *rettv;
16961 int nr = 1;
16962 #ifdef FEAT_WINDOWS
16963 tabpage_T *tp;
16965 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16966 if (tp == NULL)
16967 nr = 0;
16968 else
16969 nr = get_winnr(tp, &argvars[1]);
16970 #endif
16971 rettv->vval.v_number = nr;
16976 * "tagfiles()" function
16978 static void
16979 f_tagfiles(argvars, rettv)
16980 typval_T *argvars UNUSED;
16981 typval_T *rettv;
16983 char_u fname[MAXPATHL + 1];
16984 tagname_T tn;
16985 int first;
16987 if (rettv_list_alloc(rettv) == FAIL)
16988 return;
16990 for (first = TRUE; ; first = FALSE)
16991 if (get_tagfname(&tn, first, fname) == FAIL
16992 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
16993 break;
16994 tagname_free(&tn);
16998 * "taglist()" function
17000 static void
17001 f_taglist(argvars, rettv)
17002 typval_T *argvars;
17003 typval_T *rettv;
17005 char_u *tag_pattern;
17007 tag_pattern = get_tv_string(&argvars[0]);
17009 rettv->vval.v_number = FALSE;
17010 if (*tag_pattern == NUL)
17011 return;
17013 if (rettv_list_alloc(rettv) == OK)
17014 (void)get_tags(rettv->vval.v_list, tag_pattern);
17018 * "tempname()" function
17020 static void
17021 f_tempname(argvars, rettv)
17022 typval_T *argvars UNUSED;
17023 typval_T *rettv;
17025 static int x = 'A';
17027 rettv->v_type = VAR_STRING;
17028 rettv->vval.v_string = vim_tempname(x);
17030 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
17031 * names. Skip 'I' and 'O', they are used for shell redirection. */
17034 if (x == 'Z')
17035 x = '0';
17036 else if (x == '9')
17037 x = 'A';
17038 else
17040 #ifdef EBCDIC
17041 if (x == 'I')
17042 x = 'J';
17043 else if (x == 'R')
17044 x = 'S';
17045 else
17046 #endif
17047 ++x;
17049 } while (x == 'I' || x == 'O');
17053 * "test(list)" function: Just checking the walls...
17055 static void
17056 f_test(argvars, rettv)
17057 typval_T *argvars UNUSED;
17058 typval_T *rettv UNUSED;
17060 /* Used for unit testing. Change the code below to your liking. */
17061 #if 0
17062 listitem_T *li;
17063 list_T *l;
17064 char_u *bad, *good;
17066 if (argvars[0].v_type != VAR_LIST)
17067 return;
17068 l = argvars[0].vval.v_list;
17069 if (l == NULL)
17070 return;
17071 li = l->lv_first;
17072 if (li == NULL)
17073 return;
17074 bad = get_tv_string(&li->li_tv);
17075 li = li->li_next;
17076 if (li == NULL)
17077 return;
17078 good = get_tv_string(&li->li_tv);
17079 rettv->vval.v_number = test_edit_score(bad, good);
17080 #endif
17084 * "tolower(string)" function
17086 static void
17087 f_tolower(argvars, rettv)
17088 typval_T *argvars;
17089 typval_T *rettv;
17091 char_u *p;
17093 p = vim_strsave(get_tv_string(&argvars[0]));
17094 rettv->v_type = VAR_STRING;
17095 rettv->vval.v_string = p;
17097 if (p != NULL)
17098 while (*p != NUL)
17100 #ifdef FEAT_MBYTE
17101 int l;
17103 if (enc_utf8)
17105 int c, lc;
17107 c = utf_ptr2char(p);
17108 lc = utf_tolower(c);
17109 l = utf_ptr2len(p);
17110 /* TODO: reallocate string when byte count changes. */
17111 if (utf_char2len(lc) == l)
17112 utf_char2bytes(lc, p);
17113 p += l;
17115 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
17116 p += l; /* skip multi-byte character */
17117 else
17118 #endif
17120 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
17121 ++p;
17127 * "toupper(string)" function
17129 static void
17130 f_toupper(argvars, rettv)
17131 typval_T *argvars;
17132 typval_T *rettv;
17134 rettv->v_type = VAR_STRING;
17135 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
17139 * "tr(string, fromstr, tostr)" function
17141 static void
17142 f_tr(argvars, rettv)
17143 typval_T *argvars;
17144 typval_T *rettv;
17146 char_u *instr;
17147 char_u *fromstr;
17148 char_u *tostr;
17149 char_u *p;
17150 #ifdef FEAT_MBYTE
17151 int inlen;
17152 int fromlen;
17153 int tolen;
17154 int idx;
17155 char_u *cpstr;
17156 int cplen;
17157 int first = TRUE;
17158 #endif
17159 char_u buf[NUMBUFLEN];
17160 char_u buf2[NUMBUFLEN];
17161 garray_T ga;
17163 instr = get_tv_string(&argvars[0]);
17164 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
17165 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
17167 /* Default return value: empty string. */
17168 rettv->v_type = VAR_STRING;
17169 rettv->vval.v_string = NULL;
17170 if (fromstr == NULL || tostr == NULL)
17171 return; /* type error; errmsg already given */
17172 ga_init2(&ga, (int)sizeof(char), 80);
17174 #ifdef FEAT_MBYTE
17175 if (!has_mbyte)
17176 #endif
17177 /* not multi-byte: fromstr and tostr must be the same length */
17178 if (STRLEN(fromstr) != STRLEN(tostr))
17180 #ifdef FEAT_MBYTE
17181 error:
17182 #endif
17183 EMSG2(_(e_invarg2), fromstr);
17184 ga_clear(&ga);
17185 return;
17188 /* fromstr and tostr have to contain the same number of chars */
17189 while (*instr != NUL)
17191 #ifdef FEAT_MBYTE
17192 if (has_mbyte)
17194 inlen = (*mb_ptr2len)(instr);
17195 cpstr = instr;
17196 cplen = inlen;
17197 idx = 0;
17198 for (p = fromstr; *p != NUL; p += fromlen)
17200 fromlen = (*mb_ptr2len)(p);
17201 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
17203 for (p = tostr; *p != NUL; p += tolen)
17205 tolen = (*mb_ptr2len)(p);
17206 if (idx-- == 0)
17208 cplen = tolen;
17209 cpstr = p;
17210 break;
17213 if (*p == NUL) /* tostr is shorter than fromstr */
17214 goto error;
17215 break;
17217 ++idx;
17220 if (first && cpstr == instr)
17222 /* Check that fromstr and tostr have the same number of
17223 * (multi-byte) characters. Done only once when a character
17224 * of instr doesn't appear in fromstr. */
17225 first = FALSE;
17226 for (p = tostr; *p != NUL; p += tolen)
17228 tolen = (*mb_ptr2len)(p);
17229 --idx;
17231 if (idx != 0)
17232 goto error;
17235 ga_grow(&ga, cplen);
17236 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
17237 ga.ga_len += cplen;
17239 instr += inlen;
17241 else
17242 #endif
17244 /* When not using multi-byte chars we can do it faster. */
17245 p = vim_strchr(fromstr, *instr);
17246 if (p != NULL)
17247 ga_append(&ga, tostr[p - fromstr]);
17248 else
17249 ga_append(&ga, *instr);
17250 ++instr;
17254 /* add a terminating NUL */
17255 ga_grow(&ga, 1);
17256 ga_append(&ga, NUL);
17258 rettv->vval.v_string = ga.ga_data;
17261 #ifdef FEAT_FLOAT
17263 * "trunc({float})" function
17265 static void
17266 f_trunc(argvars, rettv)
17267 typval_T *argvars;
17268 typval_T *rettv;
17270 float_T f;
17272 rettv->v_type = VAR_FLOAT;
17273 if (get_float_arg(argvars, &f) == OK)
17274 /* trunc() is not in C90, use floor() or ceil() instead. */
17275 rettv->vval.v_float = f > 0 ? floor(f) : ceil(f);
17276 else
17277 rettv->vval.v_float = 0.0;
17279 #endif
17282 * "type(expr)" function
17284 static void
17285 f_type(argvars, rettv)
17286 typval_T *argvars;
17287 typval_T *rettv;
17289 int n;
17291 switch (argvars[0].v_type)
17293 case VAR_NUMBER: n = 0; break;
17294 case VAR_STRING: n = 1; break;
17295 case VAR_FUNC: n = 2; break;
17296 case VAR_LIST: n = 3; break;
17297 case VAR_DICT: n = 4; break;
17298 #ifdef FEAT_FLOAT
17299 case VAR_FLOAT: n = 5; break;
17300 #endif
17301 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
17303 rettv->vval.v_number = n;
17307 * "values(dict)" function
17309 static void
17310 f_values(argvars, rettv)
17311 typval_T *argvars;
17312 typval_T *rettv;
17314 dict_list(argvars, rettv, 1);
17318 * "virtcol(string)" function
17320 static void
17321 f_virtcol(argvars, rettv)
17322 typval_T *argvars;
17323 typval_T *rettv;
17325 colnr_T vcol = 0;
17326 pos_T *fp;
17327 int fnum = curbuf->b_fnum;
17329 fp = var2fpos(&argvars[0], FALSE, &fnum);
17330 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
17331 && fnum == curbuf->b_fnum)
17333 getvvcol(curwin, fp, NULL, NULL, &vcol);
17334 ++vcol;
17337 rettv->vval.v_number = vcol;
17341 * "visualmode()" function
17343 static void
17344 f_visualmode(argvars, rettv)
17345 typval_T *argvars UNUSED;
17346 typval_T *rettv UNUSED;
17348 #ifdef FEAT_VISUAL
17349 char_u str[2];
17351 rettv->v_type = VAR_STRING;
17352 str[0] = curbuf->b_visual_mode_eval;
17353 str[1] = NUL;
17354 rettv->vval.v_string = vim_strsave(str);
17356 /* A non-zero number or non-empty string argument: reset mode. */
17357 if (non_zero_arg(&argvars[0]))
17358 curbuf->b_visual_mode_eval = NUL;
17359 #endif
17363 * "winbufnr(nr)" function
17365 static void
17366 f_winbufnr(argvars, rettv)
17367 typval_T *argvars;
17368 typval_T *rettv;
17370 win_T *wp;
17372 wp = find_win_by_nr(&argvars[0], NULL);
17373 if (wp == NULL)
17374 rettv->vval.v_number = -1;
17375 else
17376 rettv->vval.v_number = wp->w_buffer->b_fnum;
17380 * "wincol()" function
17382 static void
17383 f_wincol(argvars, rettv)
17384 typval_T *argvars UNUSED;
17385 typval_T *rettv;
17387 validate_cursor();
17388 rettv->vval.v_number = curwin->w_wcol + 1;
17392 * "winheight(nr)" function
17394 static void
17395 f_winheight(argvars, rettv)
17396 typval_T *argvars;
17397 typval_T *rettv;
17399 win_T *wp;
17401 wp = find_win_by_nr(&argvars[0], NULL);
17402 if (wp == NULL)
17403 rettv->vval.v_number = -1;
17404 else
17405 rettv->vval.v_number = wp->w_height;
17409 * "winline()" function
17411 static void
17412 f_winline(argvars, rettv)
17413 typval_T *argvars UNUSED;
17414 typval_T *rettv;
17416 validate_cursor();
17417 rettv->vval.v_number = curwin->w_wrow + 1;
17421 * "winnr()" function
17423 static void
17424 f_winnr(argvars, rettv)
17425 typval_T *argvars UNUSED;
17426 typval_T *rettv;
17428 int nr = 1;
17430 #ifdef FEAT_WINDOWS
17431 nr = get_winnr(curtab, &argvars[0]);
17432 #endif
17433 rettv->vval.v_number = nr;
17437 * "winrestcmd()" function
17439 static void
17440 f_winrestcmd(argvars, rettv)
17441 typval_T *argvars UNUSED;
17442 typval_T *rettv;
17444 #ifdef FEAT_WINDOWS
17445 win_T *wp;
17446 int winnr = 1;
17447 garray_T ga;
17448 char_u buf[50];
17450 ga_init2(&ga, (int)sizeof(char), 70);
17451 for (wp = firstwin; wp != NULL; wp = wp->w_next)
17453 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
17454 ga_concat(&ga, buf);
17455 # ifdef FEAT_VERTSPLIT
17456 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
17457 ga_concat(&ga, buf);
17458 # endif
17459 ++winnr;
17461 ga_append(&ga, NUL);
17463 rettv->vval.v_string = ga.ga_data;
17464 #else
17465 rettv->vval.v_string = NULL;
17466 #endif
17467 rettv->v_type = VAR_STRING;
17471 * "winrestview()" function
17473 static void
17474 f_winrestview(argvars, rettv)
17475 typval_T *argvars;
17476 typval_T *rettv UNUSED;
17478 dict_T *dict;
17480 if (argvars[0].v_type != VAR_DICT
17481 || (dict = argvars[0].vval.v_dict) == NULL)
17482 EMSG(_(e_invarg));
17483 else
17485 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
17486 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
17487 #ifdef FEAT_VIRTUALEDIT
17488 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
17489 #endif
17490 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
17491 curwin->w_set_curswant = FALSE;
17493 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
17494 #ifdef FEAT_DIFF
17495 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
17496 #endif
17497 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
17498 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
17500 check_cursor();
17501 changed_cline_bef_curs();
17502 invalidate_botline();
17503 redraw_later(VALID);
17505 if (curwin->w_topline == 0)
17506 curwin->w_topline = 1;
17507 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
17508 curwin->w_topline = curbuf->b_ml.ml_line_count;
17509 #ifdef FEAT_DIFF
17510 check_topfill(curwin, TRUE);
17511 #endif
17516 * "winsaveview()" function
17518 static void
17519 f_winsaveview(argvars, rettv)
17520 typval_T *argvars UNUSED;
17521 typval_T *rettv;
17523 dict_T *dict;
17525 dict = dict_alloc();
17526 if (dict == NULL)
17527 return;
17528 rettv->v_type = VAR_DICT;
17529 rettv->vval.v_dict = dict;
17530 ++dict->dv_refcount;
17532 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
17533 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
17534 #ifdef FEAT_VIRTUALEDIT
17535 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
17536 #endif
17537 update_curswant();
17538 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
17540 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
17541 #ifdef FEAT_DIFF
17542 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
17543 #endif
17544 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
17545 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
17549 * "winwidth(nr)" function
17551 static void
17552 f_winwidth(argvars, rettv)
17553 typval_T *argvars;
17554 typval_T *rettv;
17556 win_T *wp;
17558 wp = find_win_by_nr(&argvars[0], NULL);
17559 if (wp == NULL)
17560 rettv->vval.v_number = -1;
17561 else
17562 #ifdef FEAT_VERTSPLIT
17563 rettv->vval.v_number = wp->w_width;
17564 #else
17565 rettv->vval.v_number = Columns;
17566 #endif
17570 * "writefile()" function
17572 static void
17573 f_writefile(argvars, rettv)
17574 typval_T *argvars;
17575 typval_T *rettv;
17577 int binary = FALSE;
17578 char_u *fname;
17579 FILE *fd;
17580 listitem_T *li;
17581 char_u *s;
17582 int ret = 0;
17583 int c;
17585 if (check_restricted() || check_secure())
17586 return;
17588 if (argvars[0].v_type != VAR_LIST)
17590 EMSG2(_(e_listarg), "writefile()");
17591 return;
17593 if (argvars[0].vval.v_list == NULL)
17594 return;
17596 if (argvars[2].v_type != VAR_UNKNOWN
17597 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
17598 binary = TRUE;
17600 /* Always open the file in binary mode, library functions have a mind of
17601 * their own about CR-LF conversion. */
17602 fname = get_tv_string(&argvars[1]);
17603 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
17605 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
17606 ret = -1;
17608 else
17610 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
17611 li = li->li_next)
17613 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
17615 if (*s == '\n')
17616 c = putc(NUL, fd);
17617 else
17618 c = putc(*s, fd);
17619 if (c == EOF)
17621 ret = -1;
17622 break;
17625 if (!binary || li->li_next != NULL)
17626 if (putc('\n', fd) == EOF)
17628 ret = -1;
17629 break;
17631 if (ret < 0)
17633 EMSG(_(e_write));
17634 break;
17637 fclose(fd);
17640 rettv->vval.v_number = ret;
17644 * Translate a String variable into a position.
17645 * Returns NULL when there is an error.
17647 static pos_T *
17648 var2fpos(varp, dollar_lnum, fnum)
17649 typval_T *varp;
17650 int dollar_lnum; /* TRUE when $ is last line */
17651 int *fnum; /* set to fnum for '0, 'A, etc. */
17653 char_u *name;
17654 static pos_T pos;
17655 pos_T *pp;
17657 /* Argument can be [lnum, col, coladd]. */
17658 if (varp->v_type == VAR_LIST)
17660 list_T *l;
17661 int len;
17662 int error = FALSE;
17663 listitem_T *li;
17665 l = varp->vval.v_list;
17666 if (l == NULL)
17667 return NULL;
17669 /* Get the line number */
17670 pos.lnum = list_find_nr(l, 0L, &error);
17671 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
17672 return NULL; /* invalid line number */
17674 /* Get the column number */
17675 pos.col = list_find_nr(l, 1L, &error);
17676 if (error)
17677 return NULL;
17678 len = (long)STRLEN(ml_get(pos.lnum));
17680 /* We accept "$" for the column number: last column. */
17681 li = list_find(l, 1L);
17682 if (li != NULL && li->li_tv.v_type == VAR_STRING
17683 && li->li_tv.vval.v_string != NULL
17684 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
17685 pos.col = len + 1;
17687 /* Accept a position up to the NUL after the line. */
17688 if (pos.col == 0 || (int)pos.col > len + 1)
17689 return NULL; /* invalid column number */
17690 --pos.col;
17692 #ifdef FEAT_VIRTUALEDIT
17693 /* Get the virtual offset. Defaults to zero. */
17694 pos.coladd = list_find_nr(l, 2L, &error);
17695 if (error)
17696 pos.coladd = 0;
17697 #endif
17699 return &pos;
17702 name = get_tv_string_chk(varp);
17703 if (name == NULL)
17704 return NULL;
17705 if (name[0] == '.') /* cursor */
17706 return &curwin->w_cursor;
17707 #ifdef FEAT_VISUAL
17708 if (name[0] == 'v' && name[1] == NUL) /* Visual start */
17710 if (VIsual_active)
17711 return &VIsual;
17712 return &curwin->w_cursor;
17714 #endif
17715 if (name[0] == '\'') /* mark */
17717 pp = getmark_fnum(name[1], FALSE, fnum);
17718 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
17719 return NULL;
17720 return pp;
17723 #ifdef FEAT_VIRTUALEDIT
17724 pos.coladd = 0;
17725 #endif
17727 if (name[0] == 'w' && dollar_lnum)
17729 pos.col = 0;
17730 if (name[1] == '0') /* "w0": first visible line */
17732 update_topline();
17733 pos.lnum = curwin->w_topline;
17734 return &pos;
17736 else if (name[1] == '$') /* "w$": last visible line */
17738 validate_botline();
17739 pos.lnum = curwin->w_botline - 1;
17740 return &pos;
17743 else if (name[0] == '$') /* last column or line */
17745 if (dollar_lnum)
17747 pos.lnum = curbuf->b_ml.ml_line_count;
17748 pos.col = 0;
17750 else
17752 pos.lnum = curwin->w_cursor.lnum;
17753 pos.col = (colnr_T)STRLEN(ml_get_curline());
17755 return &pos;
17757 return NULL;
17761 * Convert list in "arg" into a position and optional file number.
17762 * When "fnump" is NULL there is no file number, only 3 items.
17763 * Note that the column is passed on as-is, the caller may want to decrement
17764 * it to use 1 for the first column.
17765 * Return FAIL when conversion is not possible, doesn't check the position for
17766 * validity.
17768 static int
17769 list2fpos(arg, posp, fnump)
17770 typval_T *arg;
17771 pos_T *posp;
17772 int *fnump;
17774 list_T *l = arg->vval.v_list;
17775 long i = 0;
17776 long n;
17778 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
17779 * when "fnump" isn't NULL and "coladd" is optional. */
17780 if (arg->v_type != VAR_LIST
17781 || l == NULL
17782 || l->lv_len < (fnump == NULL ? 2 : 3)
17783 || l->lv_len > (fnump == NULL ? 3 : 4))
17784 return FAIL;
17786 if (fnump != NULL)
17788 n = list_find_nr(l, i++, NULL); /* fnum */
17789 if (n < 0)
17790 return FAIL;
17791 if (n == 0)
17792 n = curbuf->b_fnum; /* current buffer */
17793 *fnump = n;
17796 n = list_find_nr(l, i++, NULL); /* lnum */
17797 if (n < 0)
17798 return FAIL;
17799 posp->lnum = n;
17801 n = list_find_nr(l, i++, NULL); /* col */
17802 if (n < 0)
17803 return FAIL;
17804 posp->col = n;
17806 #ifdef FEAT_VIRTUALEDIT
17807 n = list_find_nr(l, i, NULL);
17808 if (n < 0)
17809 posp->coladd = 0;
17810 else
17811 posp->coladd = n;
17812 #endif
17814 return OK;
17818 * Get the length of an environment variable name.
17819 * Advance "arg" to the first character after the name.
17820 * Return 0 for error.
17822 static int
17823 get_env_len(arg)
17824 char_u **arg;
17826 char_u *p;
17827 int len;
17829 for (p = *arg; vim_isIDc(*p); ++p)
17831 if (p == *arg) /* no name found */
17832 return 0;
17834 len = (int)(p - *arg);
17835 *arg = p;
17836 return len;
17840 * Get the length of the name of a function or internal variable.
17841 * "arg" is advanced to the first non-white character after the name.
17842 * Return 0 if something is wrong.
17844 static int
17845 get_id_len(arg)
17846 char_u **arg;
17848 char_u *p;
17849 int len;
17851 /* Find the end of the name. */
17852 for (p = *arg; eval_isnamec(*p); ++p)
17854 if (p == *arg) /* no name found */
17855 return 0;
17857 len = (int)(p - *arg);
17858 *arg = skipwhite(p);
17860 return len;
17864 * Get the length of the name of a variable or function.
17865 * Only the name is recognized, does not handle ".key" or "[idx]".
17866 * "arg" is advanced to the first non-white character after the name.
17867 * Return -1 if curly braces expansion failed.
17868 * Return 0 if something else is wrong.
17869 * If the name contains 'magic' {}'s, expand them and return the
17870 * expanded name in an allocated string via 'alias' - caller must free.
17872 static int
17873 get_name_len(arg, alias, evaluate, verbose)
17874 char_u **arg;
17875 char_u **alias;
17876 int evaluate;
17877 int verbose;
17879 int len;
17880 char_u *p;
17881 char_u *expr_start;
17882 char_u *expr_end;
17884 *alias = NULL; /* default to no alias */
17886 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
17887 && (*arg)[2] == (int)KE_SNR)
17889 /* hard coded <SNR>, already translated */
17890 *arg += 3;
17891 return get_id_len(arg) + 3;
17893 len = eval_fname_script(*arg);
17894 if (len > 0)
17896 /* literal "<SID>", "s:" or "<SNR>" */
17897 *arg += len;
17901 * Find the end of the name; check for {} construction.
17903 p = find_name_end(*arg, &expr_start, &expr_end,
17904 len > 0 ? 0 : FNE_CHECK_START);
17905 if (expr_start != NULL)
17907 char_u *temp_string;
17909 if (!evaluate)
17911 len += (int)(p - *arg);
17912 *arg = skipwhite(p);
17913 return len;
17917 * Include any <SID> etc in the expanded string:
17918 * Thus the -len here.
17920 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
17921 if (temp_string == NULL)
17922 return -1;
17923 *alias = temp_string;
17924 *arg = skipwhite(p);
17925 return (int)STRLEN(temp_string);
17928 len += get_id_len(arg);
17929 if (len == 0 && verbose)
17930 EMSG2(_(e_invexpr2), *arg);
17932 return len;
17936 * Find the end of a variable or function name, taking care of magic braces.
17937 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
17938 * start and end of the first magic braces item.
17939 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
17940 * Return a pointer to just after the name. Equal to "arg" if there is no
17941 * valid name.
17943 static char_u *
17944 find_name_end(arg, expr_start, expr_end, flags)
17945 char_u *arg;
17946 char_u **expr_start;
17947 char_u **expr_end;
17948 int flags;
17950 int mb_nest = 0;
17951 int br_nest = 0;
17952 char_u *p;
17954 if (expr_start != NULL)
17956 *expr_start = NULL;
17957 *expr_end = NULL;
17960 /* Quick check for valid starting character. */
17961 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
17962 return arg;
17964 for (p = arg; *p != NUL
17965 && (eval_isnamec(*p)
17966 || *p == '{'
17967 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
17968 || mb_nest != 0
17969 || br_nest != 0); mb_ptr_adv(p))
17971 if (*p == '\'')
17973 /* skip over 'string' to avoid counting [ and ] inside it. */
17974 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
17976 if (*p == NUL)
17977 break;
17979 else if (*p == '"')
17981 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
17982 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
17983 if (*p == '\\' && p[1] != NUL)
17984 ++p;
17985 if (*p == NUL)
17986 break;
17989 if (mb_nest == 0)
17991 if (*p == '[')
17992 ++br_nest;
17993 else if (*p == ']')
17994 --br_nest;
17997 if (br_nest == 0)
17999 if (*p == '{')
18001 mb_nest++;
18002 if (expr_start != NULL && *expr_start == NULL)
18003 *expr_start = p;
18005 else if (*p == '}')
18007 mb_nest--;
18008 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
18009 *expr_end = p;
18014 return p;
18018 * Expands out the 'magic' {}'s in a variable/function name.
18019 * Note that this can call itself recursively, to deal with
18020 * constructs like foo{bar}{baz}{bam}
18021 * The four pointer arguments point to "foo{expre}ss{ion}bar"
18022 * "in_start" ^
18023 * "expr_start" ^
18024 * "expr_end" ^
18025 * "in_end" ^
18027 * Returns a new allocated string, which the caller must free.
18028 * Returns NULL for failure.
18030 static char_u *
18031 make_expanded_name(in_start, expr_start, expr_end, in_end)
18032 char_u *in_start;
18033 char_u *expr_start;
18034 char_u *expr_end;
18035 char_u *in_end;
18037 char_u c1;
18038 char_u *retval = NULL;
18039 char_u *temp_result;
18040 char_u *nextcmd = NULL;
18042 if (expr_end == NULL || in_end == NULL)
18043 return NULL;
18044 *expr_start = NUL;
18045 *expr_end = NUL;
18046 c1 = *in_end;
18047 *in_end = NUL;
18049 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
18050 if (temp_result != NULL && nextcmd == NULL)
18052 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
18053 + (in_end - expr_end) + 1));
18054 if (retval != NULL)
18056 STRCPY(retval, in_start);
18057 STRCAT(retval, temp_result);
18058 STRCAT(retval, expr_end + 1);
18061 vim_free(temp_result);
18063 *in_end = c1; /* put char back for error messages */
18064 *expr_start = '{';
18065 *expr_end = '}';
18067 if (retval != NULL)
18069 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
18070 if (expr_start != NULL)
18072 /* Further expansion! */
18073 temp_result = make_expanded_name(retval, expr_start,
18074 expr_end, temp_result);
18075 vim_free(retval);
18076 retval = temp_result;
18080 return retval;
18084 * Return TRUE if character "c" can be used in a variable or function name.
18085 * Does not include '{' or '}' for magic braces.
18087 static int
18088 eval_isnamec(c)
18089 int c;
18091 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
18095 * Return TRUE if character "c" can be used as the first character in a
18096 * variable or function name (excluding '{' and '}').
18098 static int
18099 eval_isnamec1(c)
18100 int c;
18102 return (ASCII_ISALPHA(c) || c == '_');
18106 * Set number v: variable to "val".
18108 void
18109 set_vim_var_nr(idx, val)
18110 int idx;
18111 long val;
18113 vimvars[idx].vv_nr = val;
18117 * Get number v: variable value.
18119 long
18120 get_vim_var_nr(idx)
18121 int idx;
18123 return vimvars[idx].vv_nr;
18127 * Get string v: variable value. Uses a static buffer, can only be used once.
18129 char_u *
18130 get_vim_var_str(idx)
18131 int idx;
18133 return get_tv_string(&vimvars[idx].vv_tv);
18137 * Get List v: variable value. Caller must take care of reference count when
18138 * needed.
18140 list_T *
18141 get_vim_var_list(idx)
18142 int idx;
18144 return vimvars[idx].vv_list;
18148 * Set v:char to character "c".
18150 void
18151 set_vim_var_char(c)
18152 int c;
18154 #ifdef FEAT_MBYTE
18155 char_u buf[MB_MAXBYTES];
18156 #else
18157 char_u buf[2];
18158 #endif
18160 #ifdef FEAT_MBYTE
18161 if (has_mbyte)
18162 buf[(*mb_char2bytes)(c, buf)] = NUL;
18163 else
18164 #endif
18166 buf[0] = c;
18167 buf[1] = NUL;
18169 set_vim_var_string(VV_CHAR, buf, -1);
18173 * Set v:count to "count" and v:count1 to "count1".
18174 * When "set_prevcount" is TRUE first set v:prevcount from v:count.
18176 void
18177 set_vcount(count, count1, set_prevcount)
18178 long count;
18179 long count1;
18180 int set_prevcount;
18182 if (set_prevcount)
18183 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
18184 vimvars[VV_COUNT].vv_nr = count;
18185 vimvars[VV_COUNT1].vv_nr = count1;
18189 * Set string v: variable to a copy of "val".
18191 void
18192 set_vim_var_string(idx, val, len)
18193 int idx;
18194 char_u *val;
18195 int len; /* length of "val" to use or -1 (whole string) */
18197 /* Need to do this (at least) once, since we can't initialize a union.
18198 * Will always be invoked when "v:progname" is set. */
18199 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
18201 vim_free(vimvars[idx].vv_str);
18202 if (val == NULL)
18203 vimvars[idx].vv_str = NULL;
18204 else if (len == -1)
18205 vimvars[idx].vv_str = vim_strsave(val);
18206 else
18207 vimvars[idx].vv_str = vim_strnsave(val, len);
18211 * Set List v: variable to "val".
18213 void
18214 set_vim_var_list(idx, val)
18215 int idx;
18216 list_T *val;
18218 list_unref(vimvars[idx].vv_list);
18219 vimvars[idx].vv_list = val;
18220 if (val != NULL)
18221 ++val->lv_refcount;
18225 * Set v:register if needed.
18227 void
18228 set_reg_var(c)
18229 int c;
18231 char_u regname;
18233 if (c == 0 || c == ' ')
18234 regname = '"';
18235 else
18236 regname = c;
18237 /* Avoid free/alloc when the value is already right. */
18238 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
18239 set_vim_var_string(VV_REG, &regname, 1);
18243 * Get or set v:exception. If "oldval" == NULL, return the current value.
18244 * Otherwise, restore the value to "oldval" and return NULL.
18245 * Must always be called in pairs to save and restore v:exception! Does not
18246 * take care of memory allocations.
18248 char_u *
18249 v_exception(oldval)
18250 char_u *oldval;
18252 if (oldval == NULL)
18253 return vimvars[VV_EXCEPTION].vv_str;
18255 vimvars[VV_EXCEPTION].vv_str = oldval;
18256 return NULL;
18260 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
18261 * Otherwise, restore the value to "oldval" and return NULL.
18262 * Must always be called in pairs to save and restore v:throwpoint! Does not
18263 * take care of memory allocations.
18265 char_u *
18266 v_throwpoint(oldval)
18267 char_u *oldval;
18269 if (oldval == NULL)
18270 return vimvars[VV_THROWPOINT].vv_str;
18272 vimvars[VV_THROWPOINT].vv_str = oldval;
18273 return NULL;
18276 #if defined(FEAT_AUTOCMD) || defined(PROTO)
18278 * Set v:cmdarg.
18279 * If "eap" != NULL, use "eap" to generate the value and return the old value.
18280 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
18281 * Must always be called in pairs!
18283 char_u *
18284 set_cmdarg(eap, oldarg)
18285 exarg_T *eap;
18286 char_u *oldarg;
18288 char_u *oldval;
18289 char_u *newval;
18290 unsigned len;
18292 oldval = vimvars[VV_CMDARG].vv_str;
18293 if (eap == NULL)
18295 vim_free(oldval);
18296 vimvars[VV_CMDARG].vv_str = oldarg;
18297 return NULL;
18300 if (eap->force_bin == FORCE_BIN)
18301 len = 6;
18302 else if (eap->force_bin == FORCE_NOBIN)
18303 len = 8;
18304 else
18305 len = 0;
18307 if (eap->read_edit)
18308 len += 7;
18310 if (eap->force_ff != 0)
18311 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
18312 # ifdef FEAT_MBYTE
18313 if (eap->force_enc != 0)
18314 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
18315 if (eap->bad_char != 0)
18316 len += 7 + 4; /* " ++bad=" + "keep" or "drop" */
18317 # endif
18319 newval = alloc(len + 1);
18320 if (newval == NULL)
18321 return NULL;
18323 if (eap->force_bin == FORCE_BIN)
18324 sprintf((char *)newval, " ++bin");
18325 else if (eap->force_bin == FORCE_NOBIN)
18326 sprintf((char *)newval, " ++nobin");
18327 else
18328 *newval = NUL;
18330 if (eap->read_edit)
18331 STRCAT(newval, " ++edit");
18333 if (eap->force_ff != 0)
18334 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
18335 eap->cmd + eap->force_ff);
18336 # ifdef FEAT_MBYTE
18337 if (eap->force_enc != 0)
18338 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
18339 eap->cmd + eap->force_enc);
18340 if (eap->bad_char == BAD_KEEP)
18341 STRCPY(newval + STRLEN(newval), " ++bad=keep");
18342 else if (eap->bad_char == BAD_DROP)
18343 STRCPY(newval + STRLEN(newval), " ++bad=drop");
18344 else if (eap->bad_char != 0)
18345 sprintf((char *)newval + STRLEN(newval), " ++bad=%c", eap->bad_char);
18346 # endif
18347 vimvars[VV_CMDARG].vv_str = newval;
18348 return oldval;
18350 #endif
18353 * Get the value of internal variable "name".
18354 * Return OK or FAIL.
18356 static int
18357 get_var_tv(name, len, rettv, verbose)
18358 char_u *name;
18359 int len; /* length of "name" */
18360 typval_T *rettv; /* NULL when only checking existence */
18361 int verbose; /* may give error message */
18363 int ret = OK;
18364 typval_T *tv = NULL;
18365 typval_T atv;
18366 dictitem_T *v;
18367 int cc;
18369 /* truncate the name, so that we can use strcmp() */
18370 cc = name[len];
18371 name[len] = NUL;
18374 * Check for "b:changedtick".
18376 if (STRCMP(name, "b:changedtick") == 0)
18378 atv.v_type = VAR_NUMBER;
18379 atv.vval.v_number = curbuf->b_changedtick;
18380 tv = &atv;
18384 * Check for user-defined variables.
18386 else
18388 v = find_var(name, NULL);
18389 if (v != NULL)
18390 tv = &v->di_tv;
18393 if (tv == NULL)
18395 if (rettv != NULL && verbose)
18396 EMSG2(_(e_undefvar), name);
18397 ret = FAIL;
18399 else if (rettv != NULL)
18400 copy_tv(tv, rettv);
18402 name[len] = cc;
18404 return ret;
18408 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
18409 * Also handle function call with Funcref variable: func(expr)
18410 * Can all be combined: dict.func(expr)[idx]['func'](expr)
18412 static int
18413 handle_subscript(arg, rettv, evaluate, verbose)
18414 char_u **arg;
18415 typval_T *rettv;
18416 int evaluate; /* do more than finding the end */
18417 int verbose; /* give error messages */
18419 int ret = OK;
18420 dict_T *selfdict = NULL;
18421 char_u *s;
18422 int len;
18423 typval_T functv;
18425 while (ret == OK
18426 && (**arg == '['
18427 || (**arg == '.' && rettv->v_type == VAR_DICT)
18428 || (**arg == '(' && rettv->v_type == VAR_FUNC))
18429 && !vim_iswhite(*(*arg - 1)))
18431 if (**arg == '(')
18433 /* need to copy the funcref so that we can clear rettv */
18434 functv = *rettv;
18435 rettv->v_type = VAR_UNKNOWN;
18437 /* Invoke the function. Recursive! */
18438 s = functv.vval.v_string;
18439 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
18440 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
18441 &len, evaluate, selfdict);
18443 /* Clear the funcref afterwards, so that deleting it while
18444 * evaluating the arguments is possible (see test55). */
18445 clear_tv(&functv);
18447 /* Stop the expression evaluation when immediately aborting on
18448 * error, or when an interrupt occurred or an exception was thrown
18449 * but not caught. */
18450 if (aborting())
18452 if (ret == OK)
18453 clear_tv(rettv);
18454 ret = FAIL;
18456 dict_unref(selfdict);
18457 selfdict = NULL;
18459 else /* **arg == '[' || **arg == '.' */
18461 dict_unref(selfdict);
18462 if (rettv->v_type == VAR_DICT)
18464 selfdict = rettv->vval.v_dict;
18465 if (selfdict != NULL)
18466 ++selfdict->dv_refcount;
18468 else
18469 selfdict = NULL;
18470 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
18472 clear_tv(rettv);
18473 ret = FAIL;
18477 dict_unref(selfdict);
18478 return ret;
18482 * Allocate memory for a variable type-value, and make it empty (0 or NULL
18483 * value).
18485 static typval_T *
18486 alloc_tv()
18488 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
18492 * Allocate memory for a variable type-value, and assign a string to it.
18493 * The string "s" must have been allocated, it is consumed.
18494 * Return NULL for out of memory, the variable otherwise.
18496 static typval_T *
18497 alloc_string_tv(s)
18498 char_u *s;
18500 typval_T *rettv;
18502 rettv = alloc_tv();
18503 if (rettv != NULL)
18505 rettv->v_type = VAR_STRING;
18506 rettv->vval.v_string = s;
18508 else
18509 vim_free(s);
18510 return rettv;
18514 * Free the memory for a variable type-value.
18516 void
18517 free_tv(varp)
18518 typval_T *varp;
18520 if (varp != NULL)
18522 switch (varp->v_type)
18524 case VAR_FUNC:
18525 func_unref(varp->vval.v_string);
18526 /*FALLTHROUGH*/
18527 case VAR_STRING:
18528 vim_free(varp->vval.v_string);
18529 break;
18530 case VAR_LIST:
18531 list_unref(varp->vval.v_list);
18532 break;
18533 case VAR_DICT:
18534 dict_unref(varp->vval.v_dict);
18535 break;
18536 case VAR_NUMBER:
18537 #ifdef FEAT_FLOAT
18538 case VAR_FLOAT:
18539 #endif
18540 case VAR_UNKNOWN:
18541 break;
18542 default:
18543 EMSG2(_(e_intern2), "free_tv()");
18544 break;
18546 vim_free(varp);
18551 * Free the memory for a variable value and set the value to NULL or 0.
18553 void
18554 clear_tv(varp)
18555 typval_T *varp;
18557 if (varp != NULL)
18559 switch (varp->v_type)
18561 case VAR_FUNC:
18562 func_unref(varp->vval.v_string);
18563 /*FALLTHROUGH*/
18564 case VAR_STRING:
18565 vim_free(varp->vval.v_string);
18566 varp->vval.v_string = NULL;
18567 break;
18568 case VAR_LIST:
18569 list_unref(varp->vval.v_list);
18570 varp->vval.v_list = NULL;
18571 break;
18572 case VAR_DICT:
18573 dict_unref(varp->vval.v_dict);
18574 varp->vval.v_dict = NULL;
18575 break;
18576 case VAR_NUMBER:
18577 varp->vval.v_number = 0;
18578 break;
18579 #ifdef FEAT_FLOAT
18580 case VAR_FLOAT:
18581 varp->vval.v_float = 0.0;
18582 break;
18583 #endif
18584 case VAR_UNKNOWN:
18585 break;
18586 default:
18587 EMSG2(_(e_intern2), "clear_tv()");
18589 varp->v_lock = 0;
18594 * Set the value of a variable to NULL without freeing items.
18596 static void
18597 init_tv(varp)
18598 typval_T *varp;
18600 if (varp != NULL)
18601 vim_memset(varp, 0, sizeof(typval_T));
18605 * Get the number value of a variable.
18606 * If it is a String variable, uses vim_str2nr().
18607 * For incompatible types, return 0.
18608 * get_tv_number_chk() is similar to get_tv_number(), but informs the
18609 * caller of incompatible types: it sets *denote to TRUE if "denote"
18610 * is not NULL or returns -1 otherwise.
18612 static long
18613 get_tv_number(varp)
18614 typval_T *varp;
18616 int error = FALSE;
18618 return get_tv_number_chk(varp, &error); /* return 0L on error */
18621 long
18622 get_tv_number_chk(varp, denote)
18623 typval_T *varp;
18624 int *denote;
18626 long n = 0L;
18628 switch (varp->v_type)
18630 case VAR_NUMBER:
18631 return (long)(varp->vval.v_number);
18632 #ifdef FEAT_FLOAT
18633 case VAR_FLOAT:
18634 EMSG(_("E805: Using a Float as a Number"));
18635 break;
18636 #endif
18637 case VAR_FUNC:
18638 EMSG(_("E703: Using a Funcref as a Number"));
18639 break;
18640 case VAR_STRING:
18641 if (varp->vval.v_string != NULL)
18642 vim_str2nr(varp->vval.v_string, NULL, NULL,
18643 TRUE, TRUE, &n, NULL);
18644 return n;
18645 case VAR_LIST:
18646 EMSG(_("E745: Using a List as a Number"));
18647 break;
18648 case VAR_DICT:
18649 EMSG(_("E728: Using a Dictionary as a Number"));
18650 break;
18651 default:
18652 EMSG2(_(e_intern2), "get_tv_number()");
18653 break;
18655 if (denote == NULL) /* useful for values that must be unsigned */
18656 n = -1;
18657 else
18658 *denote = TRUE;
18659 return n;
18663 * Get the lnum from the first argument.
18664 * Also accepts ".", "$", etc., but that only works for the current buffer.
18665 * Returns -1 on error.
18667 static linenr_T
18668 get_tv_lnum(argvars)
18669 typval_T *argvars;
18671 typval_T rettv;
18672 linenr_T lnum;
18674 lnum = get_tv_number_chk(&argvars[0], NULL);
18675 if (lnum == 0) /* no valid number, try using line() */
18677 rettv.v_type = VAR_NUMBER;
18678 f_line(argvars, &rettv);
18679 lnum = rettv.vval.v_number;
18680 clear_tv(&rettv);
18682 return lnum;
18686 * Get the lnum from the first argument.
18687 * Also accepts "$", then "buf" is used.
18688 * Returns 0 on error.
18690 static linenr_T
18691 get_tv_lnum_buf(argvars, buf)
18692 typval_T *argvars;
18693 buf_T *buf;
18695 if (argvars[0].v_type == VAR_STRING
18696 && argvars[0].vval.v_string != NULL
18697 && argvars[0].vval.v_string[0] == '$'
18698 && buf != NULL)
18699 return buf->b_ml.ml_line_count;
18700 return get_tv_number_chk(&argvars[0], NULL);
18704 * Get the string value of a variable.
18705 * If it is a Number variable, the number is converted into a string.
18706 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
18707 * get_tv_string_buf() uses a given buffer.
18708 * If the String variable has never been set, return an empty string.
18709 * Never returns NULL;
18710 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
18711 * NULL on error.
18713 static char_u *
18714 get_tv_string(varp)
18715 typval_T *varp;
18717 static char_u mybuf[NUMBUFLEN];
18719 return get_tv_string_buf(varp, mybuf);
18722 static char_u *
18723 get_tv_string_buf(varp, buf)
18724 typval_T *varp;
18725 char_u *buf;
18727 char_u *res = get_tv_string_buf_chk(varp, buf);
18729 return res != NULL ? res : (char_u *)"";
18732 char_u *
18733 get_tv_string_chk(varp)
18734 typval_T *varp;
18736 static char_u mybuf[NUMBUFLEN];
18738 return get_tv_string_buf_chk(varp, mybuf);
18741 static char_u *
18742 get_tv_string_buf_chk(varp, buf)
18743 typval_T *varp;
18744 char_u *buf;
18746 switch (varp->v_type)
18748 case VAR_NUMBER:
18749 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
18750 return buf;
18751 case VAR_FUNC:
18752 EMSG(_("E729: using Funcref as a String"));
18753 break;
18754 case VAR_LIST:
18755 EMSG(_("E730: using List as a String"));
18756 break;
18757 case VAR_DICT:
18758 EMSG(_("E731: using Dictionary as a String"));
18759 break;
18760 #ifdef FEAT_FLOAT
18761 case VAR_FLOAT:
18762 EMSG(_("E806: using Float as a String"));
18763 break;
18764 #endif
18765 case VAR_STRING:
18766 if (varp->vval.v_string != NULL)
18767 return varp->vval.v_string;
18768 return (char_u *)"";
18769 default:
18770 EMSG2(_(e_intern2), "get_tv_string_buf()");
18771 break;
18773 return NULL;
18777 * Find variable "name" in the list of variables.
18778 * Return a pointer to it if found, NULL if not found.
18779 * Careful: "a:0" variables don't have a name.
18780 * When "htp" is not NULL we are writing to the variable, set "htp" to the
18781 * hashtab_T used.
18783 static dictitem_T *
18784 find_var(name, htp)
18785 char_u *name;
18786 hashtab_T **htp;
18788 char_u *varname;
18789 hashtab_T *ht;
18791 ht = find_var_ht(name, &varname);
18792 if (htp != NULL)
18793 *htp = ht;
18794 if (ht == NULL)
18795 return NULL;
18796 return find_var_in_ht(ht, varname, htp != NULL);
18800 * Find variable "varname" in hashtab "ht".
18801 * Returns NULL if not found.
18803 static dictitem_T *
18804 find_var_in_ht(ht, varname, writing)
18805 hashtab_T *ht;
18806 char_u *varname;
18807 int writing;
18809 hashitem_T *hi;
18811 if (*varname == NUL)
18813 /* Must be something like "s:", otherwise "ht" would be NULL. */
18814 switch (varname[-2])
18816 case 's': return &SCRIPT_SV(current_SID)->sv_var;
18817 case 'g': return &globvars_var;
18818 case 'v': return &vimvars_var;
18819 case 'b': return &curbuf->b_bufvar;
18820 case 'w': return &curwin->w_winvar;
18821 #ifdef FEAT_WINDOWS
18822 case 't': return &curtab->tp_winvar;
18823 #endif
18824 case 'l': return current_funccal == NULL
18825 ? NULL : &current_funccal->l_vars_var;
18826 case 'a': return current_funccal == NULL
18827 ? NULL : &current_funccal->l_avars_var;
18829 return NULL;
18832 hi = hash_find(ht, varname);
18833 if (HASHITEM_EMPTY(hi))
18835 /* For global variables we may try auto-loading the script. If it
18836 * worked find the variable again. Don't auto-load a script if it was
18837 * loaded already, otherwise it would be loaded every time when
18838 * checking if a function name is a Funcref variable. */
18839 if (ht == &globvarht && !writing
18840 && script_autoload(varname, FALSE) && !aborting())
18841 hi = hash_find(ht, varname);
18842 if (HASHITEM_EMPTY(hi))
18843 return NULL;
18845 return HI2DI(hi);
18849 * Find the hashtab used for a variable name.
18850 * Set "varname" to the start of name without ':'.
18852 static hashtab_T *
18853 find_var_ht(name, varname)
18854 char_u *name;
18855 char_u **varname;
18857 hashitem_T *hi;
18859 if (name[1] != ':')
18861 /* The name must not start with a colon or #. */
18862 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
18863 return NULL;
18864 *varname = name;
18866 /* "version" is "v:version" in all scopes */
18867 hi = hash_find(&compat_hashtab, name);
18868 if (!HASHITEM_EMPTY(hi))
18869 return &compat_hashtab;
18871 if (current_funccal == NULL)
18872 return &globvarht; /* global variable */
18873 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
18875 *varname = name + 2;
18876 if (*name == 'g') /* global variable */
18877 return &globvarht;
18878 /* There must be no ':' or '#' in the rest of the name, unless g: is used
18880 if (vim_strchr(name + 2, ':') != NULL
18881 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
18882 return NULL;
18883 if (*name == 'b') /* buffer variable */
18884 return &curbuf->b_vars.dv_hashtab;
18885 if (*name == 'w') /* window variable */
18886 return &curwin->w_vars.dv_hashtab;
18887 #ifdef FEAT_WINDOWS
18888 if (*name == 't') /* tab page variable */
18889 return &curtab->tp_vars.dv_hashtab;
18890 #endif
18891 if (*name == 'v') /* v: variable */
18892 return &vimvarht;
18893 if (*name == 'a' && current_funccal != NULL) /* function argument */
18894 return &current_funccal->l_avars.dv_hashtab;
18895 if (*name == 'l' && current_funccal != NULL) /* local function variable */
18896 return &current_funccal->l_vars.dv_hashtab;
18897 if (*name == 's' /* script variable */
18898 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
18899 return &SCRIPT_VARS(current_SID);
18900 return NULL;
18904 * Get the string value of a (global/local) variable.
18905 * Returns NULL when it doesn't exist.
18907 char_u *
18908 get_var_value(name)
18909 char_u *name;
18911 dictitem_T *v;
18913 v = find_var(name, NULL);
18914 if (v == NULL)
18915 return NULL;
18916 return get_tv_string(&v->di_tv);
18920 * Allocate a new hashtab for a sourced script. It will be used while
18921 * sourcing this script and when executing functions defined in the script.
18923 void
18924 new_script_vars(id)
18925 scid_T id;
18927 int i;
18928 hashtab_T *ht;
18929 scriptvar_T *sv;
18931 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
18933 /* Re-allocating ga_data means that an ht_array pointing to
18934 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
18935 * at its init value. Also reset "v_dict", it's always the same. */
18936 for (i = 1; i <= ga_scripts.ga_len; ++i)
18938 ht = &SCRIPT_VARS(i);
18939 if (ht->ht_mask == HT_INIT_SIZE - 1)
18940 ht->ht_array = ht->ht_smallarray;
18941 sv = SCRIPT_SV(i);
18942 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
18945 while (ga_scripts.ga_len < id)
18947 sv = SCRIPT_SV(ga_scripts.ga_len + 1) =
18948 (scriptvar_T *)alloc_clear(sizeof(scriptvar_T));
18949 init_var_dict(&sv->sv_dict, &sv->sv_var);
18950 ++ga_scripts.ga_len;
18956 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
18957 * point to it.
18959 void
18960 init_var_dict(dict, dict_var)
18961 dict_T *dict;
18962 dictitem_T *dict_var;
18964 hash_init(&dict->dv_hashtab);
18965 dict->dv_refcount = DO_NOT_FREE_CNT;
18966 dict->dv_copyID = 0;
18967 dict_var->di_tv.vval.v_dict = dict;
18968 dict_var->di_tv.v_type = VAR_DICT;
18969 dict_var->di_tv.v_lock = VAR_FIXED;
18970 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
18971 dict_var->di_key[0] = NUL;
18975 * Clean up a list of internal variables.
18976 * Frees all allocated variables and the value they contain.
18977 * Clears hashtab "ht", does not free it.
18979 void
18980 vars_clear(ht)
18981 hashtab_T *ht;
18983 vars_clear_ext(ht, TRUE);
18987 * Like vars_clear(), but only free the value if "free_val" is TRUE.
18989 static void
18990 vars_clear_ext(ht, free_val)
18991 hashtab_T *ht;
18992 int free_val;
18994 int todo;
18995 hashitem_T *hi;
18996 dictitem_T *v;
18998 hash_lock(ht);
18999 todo = (int)ht->ht_used;
19000 for (hi = ht->ht_array; todo > 0; ++hi)
19002 if (!HASHITEM_EMPTY(hi))
19004 --todo;
19006 /* Free the variable. Don't remove it from the hashtab,
19007 * ht_array might change then. hash_clear() takes care of it
19008 * later. */
19009 v = HI2DI(hi);
19010 if (free_val)
19011 clear_tv(&v->di_tv);
19012 if ((v->di_flags & DI_FLAGS_FIX) == 0)
19013 vim_free(v);
19016 hash_clear(ht);
19017 ht->ht_used = 0;
19021 * Delete a variable from hashtab "ht" at item "hi".
19022 * Clear the variable value and free the dictitem.
19024 static void
19025 delete_var(ht, hi)
19026 hashtab_T *ht;
19027 hashitem_T *hi;
19029 dictitem_T *di = HI2DI(hi);
19031 hash_remove(ht, hi);
19032 clear_tv(&di->di_tv);
19033 vim_free(di);
19037 * List the value of one internal variable.
19039 static void
19040 list_one_var(v, prefix, first)
19041 dictitem_T *v;
19042 char_u *prefix;
19043 int *first;
19045 char_u *tofree;
19046 char_u *s;
19047 char_u numbuf[NUMBUFLEN];
19049 current_copyID += COPYID_INC;
19050 s = echo_string(&v->di_tv, &tofree, numbuf, current_copyID);
19051 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
19052 s == NULL ? (char_u *)"" : s, first);
19053 vim_free(tofree);
19056 static void
19057 list_one_var_a(prefix, name, type, string, first)
19058 char_u *prefix;
19059 char_u *name;
19060 int type;
19061 char_u *string;
19062 int *first; /* when TRUE clear rest of screen and set to FALSE */
19064 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
19065 msg_start();
19066 msg_puts(prefix);
19067 if (name != NULL) /* "a:" vars don't have a name stored */
19068 msg_puts(name);
19069 msg_putchar(' ');
19070 msg_advance(22);
19071 if (type == VAR_NUMBER)
19072 msg_putchar('#');
19073 else if (type == VAR_FUNC)
19074 msg_putchar('*');
19075 else if (type == VAR_LIST)
19077 msg_putchar('[');
19078 if (*string == '[')
19079 ++string;
19081 else if (type == VAR_DICT)
19083 msg_putchar('{');
19084 if (*string == '{')
19085 ++string;
19087 else
19088 msg_putchar(' ');
19090 msg_outtrans(string);
19092 if (type == VAR_FUNC)
19093 msg_puts((char_u *)"()");
19094 if (*first)
19096 msg_clr_eos();
19097 *first = FALSE;
19102 * Set variable "name" to value in "tv".
19103 * If the variable already exists, the value is updated.
19104 * Otherwise the variable is created.
19106 static void
19107 set_var(name, tv, copy)
19108 char_u *name;
19109 typval_T *tv;
19110 int copy; /* make copy of value in "tv" */
19112 dictitem_T *v;
19113 char_u *varname;
19114 hashtab_T *ht;
19115 char_u *p;
19117 ht = find_var_ht(name, &varname);
19118 if (ht == NULL || *varname == NUL)
19120 EMSG2(_(e_illvar), name);
19121 return;
19123 v = find_var_in_ht(ht, varname, TRUE);
19125 if (tv->v_type == VAR_FUNC)
19127 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
19128 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
19129 ? name[2] : name[0]))
19131 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
19132 return;
19134 /* Don't allow hiding a function. When "v" is not NULL we migth be
19135 * assigning another function to the same var, the type is checked
19136 * below. */
19137 if (v == NULL && function_exists(name))
19139 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
19140 name);
19141 return;
19145 if (v != NULL)
19147 /* existing variable, need to clear the value */
19148 if (var_check_ro(v->di_flags, name)
19149 || tv_check_lock(v->di_tv.v_lock, name))
19150 return;
19151 if (v->di_tv.v_type != tv->v_type
19152 && !((v->di_tv.v_type == VAR_STRING
19153 || v->di_tv.v_type == VAR_NUMBER)
19154 && (tv->v_type == VAR_STRING
19155 || tv->v_type == VAR_NUMBER))
19156 #ifdef FEAT_FLOAT
19157 && !((v->di_tv.v_type == VAR_NUMBER
19158 || v->di_tv.v_type == VAR_FLOAT)
19159 && (tv->v_type == VAR_NUMBER
19160 || tv->v_type == VAR_FLOAT))
19161 #endif
19164 EMSG2(_("E706: Variable type mismatch for: %s"), name);
19165 return;
19169 * Handle setting internal v: variables separately: we don't change
19170 * the type.
19172 if (ht == &vimvarht)
19174 if (v->di_tv.v_type == VAR_STRING)
19176 vim_free(v->di_tv.vval.v_string);
19177 if (copy || tv->v_type != VAR_STRING)
19178 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
19179 else
19181 /* Take over the string to avoid an extra alloc/free. */
19182 v->di_tv.vval.v_string = tv->vval.v_string;
19183 tv->vval.v_string = NULL;
19186 else if (v->di_tv.v_type != VAR_NUMBER)
19187 EMSG2(_(e_intern2), "set_var()");
19188 else
19190 v->di_tv.vval.v_number = get_tv_number(tv);
19191 if (STRCMP(varname, "searchforward") == 0)
19192 set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
19194 return;
19197 clear_tv(&v->di_tv);
19199 else /* add a new variable */
19201 /* Can't add "v:" variable. */
19202 if (ht == &vimvarht)
19204 EMSG2(_(e_illvar), name);
19205 return;
19208 /* Make sure the variable name is valid. */
19209 for (p = varname; *p != NUL; ++p)
19210 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
19211 && *p != AUTOLOAD_CHAR)
19213 EMSG2(_(e_illvar), varname);
19214 return;
19217 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
19218 + STRLEN(varname)));
19219 if (v == NULL)
19220 return;
19221 STRCPY(v->di_key, varname);
19222 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
19224 vim_free(v);
19225 return;
19227 v->di_flags = 0;
19230 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
19231 copy_tv(tv, &v->di_tv);
19232 else
19234 v->di_tv = *tv;
19235 v->di_tv.v_lock = 0;
19236 init_tv(tv);
19241 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
19242 * Also give an error message.
19244 static int
19245 var_check_ro(flags, name)
19246 int flags;
19247 char_u *name;
19249 if (flags & DI_FLAGS_RO)
19251 EMSG2(_(e_readonlyvar), name);
19252 return TRUE;
19254 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
19256 EMSG2(_(e_readonlysbx), name);
19257 return TRUE;
19259 return FALSE;
19263 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
19264 * Also give an error message.
19266 static int
19267 var_check_fixed(flags, name)
19268 int flags;
19269 char_u *name;
19271 if (flags & DI_FLAGS_FIX)
19273 EMSG2(_("E795: Cannot delete variable %s"), name);
19274 return TRUE;
19276 return FALSE;
19280 * Return TRUE if typeval "tv" is set to be locked (immutable).
19281 * Also give an error message, using "name".
19283 static int
19284 tv_check_lock(lock, name)
19285 int lock;
19286 char_u *name;
19288 if (lock & VAR_LOCKED)
19290 EMSG2(_("E741: Value is locked: %s"),
19291 name == NULL ? (char_u *)_("Unknown") : name);
19292 return TRUE;
19294 if (lock & VAR_FIXED)
19296 EMSG2(_("E742: Cannot change value of %s"),
19297 name == NULL ? (char_u *)_("Unknown") : name);
19298 return TRUE;
19300 return FALSE;
19304 * Copy the values from typval_T "from" to typval_T "to".
19305 * When needed allocates string or increases reference count.
19306 * Does not make a copy of a list or dict but copies the reference!
19307 * It is OK for "from" and "to" to point to the same item. This is used to
19308 * make a copy later.
19310 void
19311 copy_tv(from, to)
19312 typval_T *from;
19313 typval_T *to;
19315 to->v_type = from->v_type;
19316 to->v_lock = 0;
19317 switch (from->v_type)
19319 case VAR_NUMBER:
19320 to->vval.v_number = from->vval.v_number;
19321 break;
19322 #ifdef FEAT_FLOAT
19323 case VAR_FLOAT:
19324 to->vval.v_float = from->vval.v_float;
19325 break;
19326 #endif
19327 case VAR_STRING:
19328 case VAR_FUNC:
19329 if (from->vval.v_string == NULL)
19330 to->vval.v_string = NULL;
19331 else
19333 to->vval.v_string = vim_strsave(from->vval.v_string);
19334 if (from->v_type == VAR_FUNC)
19335 func_ref(to->vval.v_string);
19337 break;
19338 case VAR_LIST:
19339 if (from->vval.v_list == NULL)
19340 to->vval.v_list = NULL;
19341 else
19343 to->vval.v_list = from->vval.v_list;
19344 ++to->vval.v_list->lv_refcount;
19346 break;
19347 case VAR_DICT:
19348 if (from->vval.v_dict == NULL)
19349 to->vval.v_dict = NULL;
19350 else
19352 to->vval.v_dict = from->vval.v_dict;
19353 ++to->vval.v_dict->dv_refcount;
19355 break;
19356 default:
19357 EMSG2(_(e_intern2), "copy_tv()");
19358 break;
19363 * Make a copy of an item.
19364 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
19365 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
19366 * reference to an already copied list/dict can be used.
19367 * Returns FAIL or OK.
19369 static int
19370 item_copy(from, to, deep, copyID)
19371 typval_T *from;
19372 typval_T *to;
19373 int deep;
19374 int copyID;
19376 static int recurse = 0;
19377 int ret = OK;
19379 if (recurse >= DICT_MAXNEST)
19381 EMSG(_("E698: variable nested too deep for making a copy"));
19382 return FAIL;
19384 ++recurse;
19386 switch (from->v_type)
19388 case VAR_NUMBER:
19389 #ifdef FEAT_FLOAT
19390 case VAR_FLOAT:
19391 #endif
19392 case VAR_STRING:
19393 case VAR_FUNC:
19394 copy_tv(from, to);
19395 break;
19396 case VAR_LIST:
19397 to->v_type = VAR_LIST;
19398 to->v_lock = 0;
19399 if (from->vval.v_list == NULL)
19400 to->vval.v_list = NULL;
19401 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
19403 /* use the copy made earlier */
19404 to->vval.v_list = from->vval.v_list->lv_copylist;
19405 ++to->vval.v_list->lv_refcount;
19407 else
19408 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
19409 if (to->vval.v_list == NULL)
19410 ret = FAIL;
19411 break;
19412 case VAR_DICT:
19413 to->v_type = VAR_DICT;
19414 to->v_lock = 0;
19415 if (from->vval.v_dict == NULL)
19416 to->vval.v_dict = NULL;
19417 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
19419 /* use the copy made earlier */
19420 to->vval.v_dict = from->vval.v_dict->dv_copydict;
19421 ++to->vval.v_dict->dv_refcount;
19423 else
19424 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
19425 if (to->vval.v_dict == NULL)
19426 ret = FAIL;
19427 break;
19428 default:
19429 EMSG2(_(e_intern2), "item_copy()");
19430 ret = FAIL;
19432 --recurse;
19433 return ret;
19437 * ":echo expr1 ..." print each argument separated with a space, add a
19438 * newline at the end.
19439 * ":echon expr1 ..." print each argument plain.
19441 void
19442 ex_echo(eap)
19443 exarg_T *eap;
19445 char_u *arg = eap->arg;
19446 typval_T rettv;
19447 char_u *tofree;
19448 char_u *p;
19449 int needclr = TRUE;
19450 int atstart = TRUE;
19451 char_u numbuf[NUMBUFLEN];
19453 if (eap->skip)
19454 ++emsg_skip;
19455 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
19457 /* If eval1() causes an error message the text from the command may
19458 * still need to be cleared. E.g., "echo 22,44". */
19459 need_clr_eos = needclr;
19461 p = arg;
19462 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19465 * Report the invalid expression unless the expression evaluation
19466 * has been cancelled due to an aborting error, an interrupt, or an
19467 * exception.
19469 if (!aborting())
19470 EMSG2(_(e_invexpr2), p);
19471 need_clr_eos = FALSE;
19472 break;
19474 need_clr_eos = FALSE;
19476 if (!eap->skip)
19478 if (atstart)
19480 atstart = FALSE;
19481 /* Call msg_start() after eval1(), evaluating the expression
19482 * may cause a message to appear. */
19483 if (eap->cmdidx == CMD_echo)
19484 msg_start();
19486 else if (eap->cmdidx == CMD_echo)
19487 msg_puts_attr((char_u *)" ", echo_attr);
19488 current_copyID += COPYID_INC;
19489 p = echo_string(&rettv, &tofree, numbuf, current_copyID);
19490 if (p != NULL)
19491 for ( ; *p != NUL && !got_int; ++p)
19493 if (*p == '\n' || *p == '\r' || *p == TAB)
19495 if (*p != TAB && needclr)
19497 /* remove any text still there from the command */
19498 msg_clr_eos();
19499 needclr = FALSE;
19501 msg_putchar_attr(*p, echo_attr);
19503 else
19505 #ifdef FEAT_MBYTE
19506 if (has_mbyte)
19508 int i = (*mb_ptr2len)(p);
19510 (void)msg_outtrans_len_attr(p, i, echo_attr);
19511 p += i - 1;
19513 else
19514 #endif
19515 (void)msg_outtrans_len_attr(p, 1, echo_attr);
19518 vim_free(tofree);
19520 clear_tv(&rettv);
19521 arg = skipwhite(arg);
19523 eap->nextcmd = check_nextcmd(arg);
19525 if (eap->skip)
19526 --emsg_skip;
19527 else
19529 /* remove text that may still be there from the command */
19530 if (needclr)
19531 msg_clr_eos();
19532 if (eap->cmdidx == CMD_echo)
19533 msg_end();
19538 * ":echohl {name}".
19540 void
19541 ex_echohl(eap)
19542 exarg_T *eap;
19544 int id;
19546 id = syn_name2id(eap->arg);
19547 if (id == 0)
19548 echo_attr = 0;
19549 else
19550 echo_attr = syn_id2attr(id);
19554 * ":execute expr1 ..." execute the result of an expression.
19555 * ":echomsg expr1 ..." Print a message
19556 * ":echoerr expr1 ..." Print an error
19557 * Each gets spaces around each argument and a newline at the end for
19558 * echo commands
19560 void
19561 ex_execute(eap)
19562 exarg_T *eap;
19564 char_u *arg = eap->arg;
19565 typval_T rettv;
19566 int ret = OK;
19567 char_u *p;
19568 garray_T ga;
19569 int len;
19570 int save_did_emsg;
19572 ga_init2(&ga, 1, 80);
19574 if (eap->skip)
19575 ++emsg_skip;
19576 while (*arg != NUL && *arg != '|' && *arg != '\n')
19578 p = arg;
19579 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19582 * Report the invalid expression unless the expression evaluation
19583 * has been cancelled due to an aborting error, an interrupt, or an
19584 * exception.
19586 if (!aborting())
19587 EMSG2(_(e_invexpr2), p);
19588 ret = FAIL;
19589 break;
19592 if (!eap->skip)
19594 p = get_tv_string(&rettv);
19595 len = (int)STRLEN(p);
19596 if (ga_grow(&ga, len + 2) == FAIL)
19598 clear_tv(&rettv);
19599 ret = FAIL;
19600 break;
19602 if (ga.ga_len)
19603 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
19604 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
19605 ga.ga_len += len;
19608 clear_tv(&rettv);
19609 arg = skipwhite(arg);
19612 if (ret != FAIL && ga.ga_data != NULL)
19614 if (eap->cmdidx == CMD_echomsg)
19616 MSG_ATTR(ga.ga_data, echo_attr);
19617 out_flush();
19619 else if (eap->cmdidx == CMD_echoerr)
19621 /* We don't want to abort following commands, restore did_emsg. */
19622 save_did_emsg = did_emsg;
19623 EMSG((char_u *)ga.ga_data);
19624 if (!force_abort)
19625 did_emsg = save_did_emsg;
19627 else if (eap->cmdidx == CMD_execute)
19628 do_cmdline((char_u *)ga.ga_data,
19629 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
19632 ga_clear(&ga);
19634 if (eap->skip)
19635 --emsg_skip;
19637 eap->nextcmd = check_nextcmd(arg);
19641 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
19642 * "arg" points to the "&" or '+' when called, to "option" when returning.
19643 * Returns NULL when no option name found. Otherwise pointer to the char
19644 * after the option name.
19646 static char_u *
19647 find_option_end(arg, opt_flags)
19648 char_u **arg;
19649 int *opt_flags;
19651 char_u *p = *arg;
19653 ++p;
19654 if (*p == 'g' && p[1] == ':')
19656 *opt_flags = OPT_GLOBAL;
19657 p += 2;
19659 else if (*p == 'l' && p[1] == ':')
19661 *opt_flags = OPT_LOCAL;
19662 p += 2;
19664 else
19665 *opt_flags = 0;
19667 if (!ASCII_ISALPHA(*p))
19668 return NULL;
19669 *arg = p;
19671 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
19672 p += 4; /* termcap option */
19673 else
19674 while (ASCII_ISALPHA(*p))
19675 ++p;
19676 return p;
19680 * ":function"
19682 void
19683 ex_function(eap)
19684 exarg_T *eap;
19686 char_u *theline;
19687 int j;
19688 int c;
19689 int saved_did_emsg;
19690 char_u *name = NULL;
19691 char_u *p;
19692 char_u *arg;
19693 char_u *line_arg = NULL;
19694 garray_T newargs;
19695 garray_T newlines;
19696 int varargs = FALSE;
19697 int mustend = FALSE;
19698 int flags = 0;
19699 ufunc_T *fp;
19700 int indent;
19701 int nesting;
19702 char_u *skip_until = NULL;
19703 dictitem_T *v;
19704 funcdict_T fudi;
19705 static int func_nr = 0; /* number for nameless function */
19706 int paren;
19707 hashtab_T *ht;
19708 int todo;
19709 hashitem_T *hi;
19710 int sourcing_lnum_off;
19713 * ":function" without argument: list functions.
19715 if (ends_excmd(*eap->arg))
19717 if (!eap->skip)
19719 todo = (int)func_hashtab.ht_used;
19720 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19722 if (!HASHITEM_EMPTY(hi))
19724 --todo;
19725 fp = HI2UF(hi);
19726 if (!isdigit(*fp->uf_name))
19727 list_func_head(fp, FALSE);
19731 eap->nextcmd = check_nextcmd(eap->arg);
19732 return;
19736 * ":function /pat": list functions matching pattern.
19738 if (*eap->arg == '/')
19740 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
19741 if (!eap->skip)
19743 regmatch_T regmatch;
19745 c = *p;
19746 *p = NUL;
19747 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
19748 *p = c;
19749 if (regmatch.regprog != NULL)
19751 regmatch.rm_ic = p_ic;
19753 todo = (int)func_hashtab.ht_used;
19754 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19756 if (!HASHITEM_EMPTY(hi))
19758 --todo;
19759 fp = HI2UF(hi);
19760 if (!isdigit(*fp->uf_name)
19761 && vim_regexec(&regmatch, fp->uf_name, 0))
19762 list_func_head(fp, FALSE);
19765 vim_free(regmatch.regprog);
19768 if (*p == '/')
19769 ++p;
19770 eap->nextcmd = check_nextcmd(p);
19771 return;
19775 * Get the function name. There are these situations:
19776 * func normal function name
19777 * "name" == func, "fudi.fd_dict" == NULL
19778 * dict.func new dictionary entry
19779 * "name" == NULL, "fudi.fd_dict" set,
19780 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
19781 * dict.func existing dict entry with a Funcref
19782 * "name" == func, "fudi.fd_dict" set,
19783 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19784 * dict.func existing dict entry that's not a Funcref
19785 * "name" == NULL, "fudi.fd_dict" set,
19786 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19788 p = eap->arg;
19789 name = trans_function_name(&p, eap->skip, 0, &fudi);
19790 paren = (vim_strchr(p, '(') != NULL);
19791 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
19794 * Return on an invalid expression in braces, unless the expression
19795 * evaluation has been cancelled due to an aborting error, an
19796 * interrupt, or an exception.
19798 if (!aborting())
19800 if (!eap->skip && fudi.fd_newkey != NULL)
19801 EMSG2(_(e_dictkey), fudi.fd_newkey);
19802 vim_free(fudi.fd_newkey);
19803 return;
19805 else
19806 eap->skip = TRUE;
19809 /* An error in a function call during evaluation of an expression in magic
19810 * braces should not cause the function not to be defined. */
19811 saved_did_emsg = did_emsg;
19812 did_emsg = FALSE;
19815 * ":function func" with only function name: list function.
19817 if (!paren)
19819 if (!ends_excmd(*skipwhite(p)))
19821 EMSG(_(e_trailing));
19822 goto ret_free;
19824 eap->nextcmd = check_nextcmd(p);
19825 if (eap->nextcmd != NULL)
19826 *p = NUL;
19827 if (!eap->skip && !got_int)
19829 fp = find_func(name);
19830 if (fp != NULL)
19832 list_func_head(fp, TRUE);
19833 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
19835 if (FUNCLINE(fp, j) == NULL)
19836 continue;
19837 msg_putchar('\n');
19838 msg_outnum((long)(j + 1));
19839 if (j < 9)
19840 msg_putchar(' ');
19841 if (j < 99)
19842 msg_putchar(' ');
19843 msg_prt_line(FUNCLINE(fp, j), FALSE);
19844 out_flush(); /* show a line at a time */
19845 ui_breakcheck();
19847 if (!got_int)
19849 msg_putchar('\n');
19850 msg_puts((char_u *)" endfunction");
19853 else
19854 emsg_funcname(N_("E123: Undefined function: %s"), name);
19856 goto ret_free;
19860 * ":function name(arg1, arg2)" Define function.
19862 p = skipwhite(p);
19863 if (*p != '(')
19865 if (!eap->skip)
19867 EMSG2(_("E124: Missing '(': %s"), eap->arg);
19868 goto ret_free;
19870 /* attempt to continue by skipping some text */
19871 if (vim_strchr(p, '(') != NULL)
19872 p = vim_strchr(p, '(');
19874 p = skipwhite(p + 1);
19876 ga_init2(&newargs, (int)sizeof(char_u *), 3);
19877 ga_init2(&newlines, (int)sizeof(char_u *), 3);
19879 if (!eap->skip)
19881 /* Check the name of the function. Unless it's a dictionary function
19882 * (that we are overwriting). */
19883 if (name != NULL)
19884 arg = name;
19885 else
19886 arg = fudi.fd_newkey;
19887 if (arg != NULL && (fudi.fd_di == NULL
19888 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
19890 if (*arg == K_SPECIAL)
19891 j = 3;
19892 else
19893 j = 0;
19894 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
19895 : eval_isnamec(arg[j])))
19896 ++j;
19897 if (arg[j] != NUL)
19898 emsg_funcname((char *)e_invarg2, arg);
19903 * Isolate the arguments: "arg1, arg2, ...)"
19905 while (*p != ')')
19907 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
19909 varargs = TRUE;
19910 p += 3;
19911 mustend = TRUE;
19913 else
19915 arg = p;
19916 while (ASCII_ISALNUM(*p) || *p == '_')
19917 ++p;
19918 if (arg == p || isdigit(*arg)
19919 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
19920 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
19922 if (!eap->skip)
19923 EMSG2(_("E125: Illegal argument: %s"), arg);
19924 break;
19926 if (ga_grow(&newargs, 1) == FAIL)
19927 goto erret;
19928 c = *p;
19929 *p = NUL;
19930 arg = vim_strsave(arg);
19931 if (arg == NULL)
19932 goto erret;
19933 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
19934 *p = c;
19935 newargs.ga_len++;
19936 if (*p == ',')
19937 ++p;
19938 else
19939 mustend = TRUE;
19941 p = skipwhite(p);
19942 if (mustend && *p != ')')
19944 if (!eap->skip)
19945 EMSG2(_(e_invarg2), eap->arg);
19946 break;
19949 ++p; /* skip the ')' */
19951 /* find extra arguments "range", "dict" and "abort" */
19952 for (;;)
19954 p = skipwhite(p);
19955 if (STRNCMP(p, "range", 5) == 0)
19957 flags |= FC_RANGE;
19958 p += 5;
19960 else if (STRNCMP(p, "dict", 4) == 0)
19962 flags |= FC_DICT;
19963 p += 4;
19965 else if (STRNCMP(p, "abort", 5) == 0)
19967 flags |= FC_ABORT;
19968 p += 5;
19970 else
19971 break;
19974 /* When there is a line break use what follows for the function body.
19975 * Makes 'exe "func Test()\n...\nendfunc"' work. */
19976 if (*p == '\n')
19977 line_arg = p + 1;
19978 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
19979 EMSG(_(e_trailing));
19982 * Read the body of the function, until ":endfunction" is found.
19984 if (KeyTyped)
19986 /* Check if the function already exists, don't let the user type the
19987 * whole function before telling him it doesn't work! For a script we
19988 * need to skip the body to be able to find what follows. */
19989 if (!eap->skip && !eap->forceit)
19991 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
19992 EMSG(_(e_funcdict));
19993 else if (name != NULL && find_func(name) != NULL)
19994 emsg_funcname(e_funcexts, name);
19997 if (!eap->skip && did_emsg)
19998 goto erret;
20000 msg_putchar('\n'); /* don't overwrite the function name */
20001 cmdline_row = msg_row;
20004 indent = 2;
20005 nesting = 0;
20006 for (;;)
20008 msg_scroll = TRUE;
20009 need_wait_return = FALSE;
20010 sourcing_lnum_off = sourcing_lnum;
20012 if (line_arg != NULL)
20014 /* Use eap->arg, split up in parts by line breaks. */
20015 theline = line_arg;
20016 p = vim_strchr(theline, '\n');
20017 if (p == NULL)
20018 line_arg += STRLEN(line_arg);
20019 else
20021 *p = NUL;
20022 line_arg = p + 1;
20025 else if (eap->getline == NULL)
20026 theline = getcmdline(':', 0L, indent);
20027 else
20028 theline = eap->getline(':', eap->cookie, indent);
20029 if (KeyTyped)
20030 lines_left = Rows - 1;
20031 if (theline == NULL)
20033 EMSG(_("E126: Missing :endfunction"));
20034 goto erret;
20037 /* Detect line continuation: sourcing_lnum increased more than one. */
20038 if (sourcing_lnum > sourcing_lnum_off + 1)
20039 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
20040 else
20041 sourcing_lnum_off = 0;
20043 if (skip_until != NULL)
20045 /* between ":append" and "." and between ":python <<EOF" and "EOF"
20046 * don't check for ":endfunc". */
20047 if (STRCMP(theline, skip_until) == 0)
20049 vim_free(skip_until);
20050 skip_until = NULL;
20053 else
20055 /* skip ':' and blanks*/
20056 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
20059 /* Check for "endfunction". */
20060 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
20062 if (line_arg == NULL)
20063 vim_free(theline);
20064 break;
20067 /* Increase indent inside "if", "while", "for" and "try", decrease
20068 * at "end". */
20069 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
20070 indent -= 2;
20071 else if (STRNCMP(p, "if", 2) == 0
20072 || STRNCMP(p, "wh", 2) == 0
20073 || STRNCMP(p, "for", 3) == 0
20074 || STRNCMP(p, "try", 3) == 0)
20075 indent += 2;
20077 /* Check for defining a function inside this function. */
20078 if (checkforcmd(&p, "function", 2))
20080 if (*p == '!')
20081 p = skipwhite(p + 1);
20082 p += eval_fname_script(p);
20083 if (ASCII_ISALPHA(*p))
20085 vim_free(trans_function_name(&p, TRUE, 0, NULL));
20086 if (*skipwhite(p) == '(')
20088 ++nesting;
20089 indent += 2;
20094 /* Check for ":append" or ":insert". */
20095 p = skip_range(p, NULL);
20096 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
20097 || (p[0] == 'i'
20098 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
20099 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
20100 skip_until = vim_strsave((char_u *)".");
20102 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
20103 arg = skipwhite(skiptowhite(p));
20104 if (arg[0] == '<' && arg[1] =='<'
20105 && ((p[0] == 'p' && p[1] == 'y'
20106 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
20107 || (p[0] == 'p' && p[1] == 'e'
20108 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
20109 || (p[0] == 't' && p[1] == 'c'
20110 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
20111 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
20112 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
20113 || (p[0] == 'm' && p[1] == 'z'
20114 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
20117 /* ":python <<" continues until a dot, like ":append" */
20118 p = skipwhite(arg + 2);
20119 if (*p == NUL)
20120 skip_until = vim_strsave((char_u *)".");
20121 else
20122 skip_until = vim_strsave(p);
20126 /* Add the line to the function. */
20127 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
20129 if (line_arg == NULL)
20130 vim_free(theline);
20131 goto erret;
20134 /* Copy the line to newly allocated memory. get_one_sourceline()
20135 * allocates 250 bytes per line, this saves 80% on average. The cost
20136 * is an extra alloc/free. */
20137 p = vim_strsave(theline);
20138 if (p != NULL)
20140 if (line_arg == NULL)
20141 vim_free(theline);
20142 theline = p;
20145 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
20147 /* Add NULL lines for continuation lines, so that the line count is
20148 * equal to the index in the growarray. */
20149 while (sourcing_lnum_off-- > 0)
20150 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
20152 /* Check for end of eap->arg. */
20153 if (line_arg != NULL && *line_arg == NUL)
20154 line_arg = NULL;
20157 /* Don't define the function when skipping commands or when an error was
20158 * detected. */
20159 if (eap->skip || did_emsg)
20160 goto erret;
20163 * If there are no errors, add the function
20165 if (fudi.fd_dict == NULL)
20167 v = find_var(name, &ht);
20168 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
20170 emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
20171 name);
20172 goto erret;
20175 fp = find_func(name);
20176 if (fp != NULL)
20178 if (!eap->forceit)
20180 emsg_funcname(e_funcexts, name);
20181 goto erret;
20183 if (fp->uf_calls > 0)
20185 emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"),
20186 name);
20187 goto erret;
20189 /* redefine existing function */
20190 ga_clear_strings(&(fp->uf_args));
20191 ga_clear_strings(&(fp->uf_lines));
20192 vim_free(name);
20193 name = NULL;
20196 else
20198 char numbuf[20];
20200 fp = NULL;
20201 if (fudi.fd_newkey == NULL && !eap->forceit)
20203 EMSG(_(e_funcdict));
20204 goto erret;
20206 if (fudi.fd_di == NULL)
20208 /* Can't add a function to a locked dictionary */
20209 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
20210 goto erret;
20212 /* Can't change an existing function if it is locked */
20213 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
20214 goto erret;
20216 /* Give the function a sequential number. Can only be used with a
20217 * Funcref! */
20218 vim_free(name);
20219 sprintf(numbuf, "%d", ++func_nr);
20220 name = vim_strsave((char_u *)numbuf);
20221 if (name == NULL)
20222 goto erret;
20225 if (fp == NULL)
20227 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
20229 int slen, plen;
20230 char_u *scriptname;
20232 /* Check that the autoload name matches the script name. */
20233 j = FAIL;
20234 if (sourcing_name != NULL)
20236 scriptname = autoload_name(name);
20237 if (scriptname != NULL)
20239 p = vim_strchr(scriptname, '/');
20240 plen = (int)STRLEN(p);
20241 slen = (int)STRLEN(sourcing_name);
20242 if (slen > plen && fnamecmp(p,
20243 sourcing_name + slen - plen) == 0)
20244 j = OK;
20245 vim_free(scriptname);
20248 if (j == FAIL)
20250 EMSG2(_("E746: Function name does not match script file name: %s"), name);
20251 goto erret;
20255 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
20256 if (fp == NULL)
20257 goto erret;
20259 if (fudi.fd_dict != NULL)
20261 if (fudi.fd_di == NULL)
20263 /* add new dict entry */
20264 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
20265 if (fudi.fd_di == NULL)
20267 vim_free(fp);
20268 goto erret;
20270 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
20272 vim_free(fudi.fd_di);
20273 vim_free(fp);
20274 goto erret;
20277 else
20278 /* overwrite existing dict entry */
20279 clear_tv(&fudi.fd_di->di_tv);
20280 fudi.fd_di->di_tv.v_type = VAR_FUNC;
20281 fudi.fd_di->di_tv.v_lock = 0;
20282 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
20283 fp->uf_refcount = 1;
20285 /* behave like "dict" was used */
20286 flags |= FC_DICT;
20289 /* insert the new function in the function list */
20290 STRCPY(fp->uf_name, name);
20291 hash_add(&func_hashtab, UF2HIKEY(fp));
20293 fp->uf_args = newargs;
20294 fp->uf_lines = newlines;
20295 #ifdef FEAT_PROFILE
20296 fp->uf_tml_count = NULL;
20297 fp->uf_tml_total = NULL;
20298 fp->uf_tml_self = NULL;
20299 fp->uf_profiling = FALSE;
20300 if (prof_def_func())
20301 func_do_profile(fp);
20302 #endif
20303 fp->uf_varargs = varargs;
20304 fp->uf_flags = flags;
20305 fp->uf_calls = 0;
20306 fp->uf_script_ID = current_SID;
20307 goto ret_free;
20309 erret:
20310 ga_clear_strings(&newargs);
20311 ga_clear_strings(&newlines);
20312 ret_free:
20313 vim_free(skip_until);
20314 vim_free(fudi.fd_newkey);
20315 vim_free(name);
20316 did_emsg |= saved_did_emsg;
20320 * Get a function name, translating "<SID>" and "<SNR>".
20321 * Also handles a Funcref in a List or Dictionary.
20322 * Returns the function name in allocated memory, or NULL for failure.
20323 * flags:
20324 * TFN_INT: internal function name OK
20325 * TFN_QUIET: be quiet
20326 * Advances "pp" to just after the function name (if no error).
20328 static char_u *
20329 trans_function_name(pp, skip, flags, fdp)
20330 char_u **pp;
20331 int skip; /* only find the end, don't evaluate */
20332 int flags;
20333 funcdict_T *fdp; /* return: info about dictionary used */
20335 char_u *name = NULL;
20336 char_u *start;
20337 char_u *end;
20338 int lead;
20339 char_u sid_buf[20];
20340 int len;
20341 lval_T lv;
20343 if (fdp != NULL)
20344 vim_memset(fdp, 0, sizeof(funcdict_T));
20345 start = *pp;
20347 /* Check for hard coded <SNR>: already translated function ID (from a user
20348 * command). */
20349 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
20350 && (*pp)[2] == (int)KE_SNR)
20352 *pp += 3;
20353 len = get_id_len(pp) + 3;
20354 return vim_strnsave(start, len);
20357 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
20358 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
20359 lead = eval_fname_script(start);
20360 if (lead > 2)
20361 start += lead;
20363 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
20364 lead > 2 ? 0 : FNE_CHECK_START);
20365 if (end == start)
20367 if (!skip)
20368 EMSG(_("E129: Function name required"));
20369 goto theend;
20371 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
20374 * Report an invalid expression in braces, unless the expression
20375 * evaluation has been cancelled due to an aborting error, an
20376 * interrupt, or an exception.
20378 if (!aborting())
20380 if (end != NULL)
20381 EMSG2(_(e_invarg2), start);
20383 else
20384 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
20385 goto theend;
20388 if (lv.ll_tv != NULL)
20390 if (fdp != NULL)
20392 fdp->fd_dict = lv.ll_dict;
20393 fdp->fd_newkey = lv.ll_newkey;
20394 lv.ll_newkey = NULL;
20395 fdp->fd_di = lv.ll_di;
20397 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
20399 name = vim_strsave(lv.ll_tv->vval.v_string);
20400 *pp = end;
20402 else
20404 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
20405 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
20406 EMSG(_(e_funcref));
20407 else
20408 *pp = end;
20409 name = NULL;
20411 goto theend;
20414 if (lv.ll_name == NULL)
20416 /* Error found, but continue after the function name. */
20417 *pp = end;
20418 goto theend;
20421 /* Check if the name is a Funcref. If so, use the value. */
20422 if (lv.ll_exp_name != NULL)
20424 len = (int)STRLEN(lv.ll_exp_name);
20425 name = deref_func_name(lv.ll_exp_name, &len);
20426 if (name == lv.ll_exp_name)
20427 name = NULL;
20429 else
20431 len = (int)(end - *pp);
20432 name = deref_func_name(*pp, &len);
20433 if (name == *pp)
20434 name = NULL;
20436 if (name != NULL)
20438 name = vim_strsave(name);
20439 *pp = end;
20440 goto theend;
20443 if (lv.ll_exp_name != NULL)
20445 len = (int)STRLEN(lv.ll_exp_name);
20446 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
20447 && STRNCMP(lv.ll_name, "s:", 2) == 0)
20449 /* When there was "s:" already or the name expanded to get a
20450 * leading "s:" then remove it. */
20451 lv.ll_name += 2;
20452 len -= 2;
20453 lead = 2;
20456 else
20458 if (lead == 2) /* skip over "s:" */
20459 lv.ll_name += 2;
20460 len = (int)(end - lv.ll_name);
20464 * Copy the function name to allocated memory.
20465 * Accept <SID>name() inside a script, translate into <SNR>123_name().
20466 * Accept <SNR>123_name() outside a script.
20468 if (skip)
20469 lead = 0; /* do nothing */
20470 else if (lead > 0)
20472 lead = 3;
20473 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
20474 || eval_fname_sid(*pp))
20476 /* It's "s:" or "<SID>" */
20477 if (current_SID <= 0)
20479 EMSG(_(e_usingsid));
20480 goto theend;
20482 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
20483 lead += (int)STRLEN(sid_buf);
20486 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
20488 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
20489 goto theend;
20491 name = alloc((unsigned)(len + lead + 1));
20492 if (name != NULL)
20494 if (lead > 0)
20496 name[0] = K_SPECIAL;
20497 name[1] = KS_EXTRA;
20498 name[2] = (int)KE_SNR;
20499 if (lead > 3) /* If it's "<SID>" */
20500 STRCPY(name + 3, sid_buf);
20502 mch_memmove(name + lead, lv.ll_name, (size_t)len);
20503 name[len + lead] = NUL;
20505 *pp = end;
20507 theend:
20508 clear_lval(&lv);
20509 return name;
20513 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
20514 * Return 2 if "p" starts with "s:".
20515 * Return 0 otherwise.
20517 static int
20518 eval_fname_script(p)
20519 char_u *p;
20521 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
20522 || STRNICMP(p + 1, "SNR>", 4) == 0))
20523 return 5;
20524 if (p[0] == 's' && p[1] == ':')
20525 return 2;
20526 return 0;
20530 * Return TRUE if "p" starts with "<SID>" or "s:".
20531 * Only works if eval_fname_script() returned non-zero for "p"!
20533 static int
20534 eval_fname_sid(p)
20535 char_u *p;
20537 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
20541 * List the head of the function: "name(arg1, arg2)".
20543 static void
20544 list_func_head(fp, indent)
20545 ufunc_T *fp;
20546 int indent;
20548 int j;
20550 msg_start();
20551 if (indent)
20552 MSG_PUTS(" ");
20553 MSG_PUTS("function ");
20554 if (fp->uf_name[0] == K_SPECIAL)
20556 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
20557 msg_puts(fp->uf_name + 3);
20559 else
20560 msg_puts(fp->uf_name);
20561 msg_putchar('(');
20562 for (j = 0; j < fp->uf_args.ga_len; ++j)
20564 if (j)
20565 MSG_PUTS(", ");
20566 msg_puts(FUNCARG(fp, j));
20568 if (fp->uf_varargs)
20570 if (j)
20571 MSG_PUTS(", ");
20572 MSG_PUTS("...");
20574 msg_putchar(')');
20575 msg_clr_eos();
20576 if (p_verbose > 0)
20577 last_set_msg(fp->uf_script_ID);
20581 * Find a function by name, return pointer to it in ufuncs.
20582 * Return NULL for unknown function.
20584 static ufunc_T *
20585 find_func(name)
20586 char_u *name;
20588 hashitem_T *hi;
20590 hi = hash_find(&func_hashtab, name);
20591 if (!HASHITEM_EMPTY(hi))
20592 return HI2UF(hi);
20593 return NULL;
20596 #if defined(EXITFREE) || defined(PROTO)
20597 void
20598 free_all_functions()
20600 hashitem_T *hi;
20602 /* Need to start all over every time, because func_free() may change the
20603 * hash table. */
20604 while (func_hashtab.ht_used > 0)
20605 for (hi = func_hashtab.ht_array; ; ++hi)
20606 if (!HASHITEM_EMPTY(hi))
20608 func_free(HI2UF(hi));
20609 break;
20612 #endif
20615 * Return TRUE if a function "name" exists.
20617 static int
20618 function_exists(name)
20619 char_u *name;
20621 char_u *nm = name;
20622 char_u *p;
20623 int n = FALSE;
20625 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
20626 nm = skipwhite(nm);
20628 /* Only accept "funcname", "funcname ", "funcname (..." and
20629 * "funcname(...", not "funcname!...". */
20630 if (p != NULL && (*nm == NUL || *nm == '('))
20632 if (builtin_function(p))
20633 n = (find_internal_func(p) >= 0);
20634 else
20635 n = (find_func(p) != NULL);
20637 vim_free(p);
20638 return n;
20642 * Return TRUE if "name" looks like a builtin function name: starts with a
20643 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
20645 static int
20646 builtin_function(name)
20647 char_u *name;
20649 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
20650 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
20653 #if defined(FEAT_PROFILE) || defined(PROTO)
20655 * Start profiling function "fp".
20657 static void
20658 func_do_profile(fp)
20659 ufunc_T *fp;
20661 fp->uf_tm_count = 0;
20662 profile_zero(&fp->uf_tm_self);
20663 profile_zero(&fp->uf_tm_total);
20664 if (fp->uf_tml_count == NULL)
20665 fp->uf_tml_count = (int *)alloc_clear((unsigned)
20666 (sizeof(int) * fp->uf_lines.ga_len));
20667 if (fp->uf_tml_total == NULL)
20668 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
20669 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20670 if (fp->uf_tml_self == NULL)
20671 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
20672 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20673 fp->uf_tml_idx = -1;
20674 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
20675 || fp->uf_tml_self == NULL)
20676 return; /* out of memory */
20678 fp->uf_profiling = TRUE;
20682 * Dump the profiling results for all functions in file "fd".
20684 void
20685 func_dump_profile(fd)
20686 FILE *fd;
20688 hashitem_T *hi;
20689 int todo;
20690 ufunc_T *fp;
20691 int i;
20692 ufunc_T **sorttab;
20693 int st_len = 0;
20695 todo = (int)func_hashtab.ht_used;
20696 if (todo == 0)
20697 return; /* nothing to dump */
20699 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
20701 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
20703 if (!HASHITEM_EMPTY(hi))
20705 --todo;
20706 fp = HI2UF(hi);
20707 if (fp->uf_profiling)
20709 if (sorttab != NULL)
20710 sorttab[st_len++] = fp;
20712 if (fp->uf_name[0] == K_SPECIAL)
20713 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
20714 else
20715 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
20716 if (fp->uf_tm_count == 1)
20717 fprintf(fd, "Called 1 time\n");
20718 else
20719 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
20720 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
20721 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
20722 fprintf(fd, "\n");
20723 fprintf(fd, "count total (s) self (s)\n");
20725 for (i = 0; i < fp->uf_lines.ga_len; ++i)
20727 if (FUNCLINE(fp, i) == NULL)
20728 continue;
20729 prof_func_line(fd, fp->uf_tml_count[i],
20730 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
20731 fprintf(fd, "%s\n", FUNCLINE(fp, i));
20733 fprintf(fd, "\n");
20738 if (sorttab != NULL && st_len > 0)
20740 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20741 prof_total_cmp);
20742 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
20743 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20744 prof_self_cmp);
20745 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
20748 vim_free(sorttab);
20751 static void
20752 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
20753 FILE *fd;
20754 ufunc_T **sorttab;
20755 int st_len;
20756 char *title;
20757 int prefer_self; /* when equal print only self time */
20759 int i;
20760 ufunc_T *fp;
20762 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
20763 fprintf(fd, "count total (s) self (s) function\n");
20764 for (i = 0; i < 20 && i < st_len; ++i)
20766 fp = sorttab[i];
20767 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
20768 prefer_self);
20769 if (fp->uf_name[0] == K_SPECIAL)
20770 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
20771 else
20772 fprintf(fd, " %s()\n", fp->uf_name);
20774 fprintf(fd, "\n");
20778 * Print the count and times for one function or function line.
20780 static void
20781 prof_func_line(fd, count, total, self, prefer_self)
20782 FILE *fd;
20783 int count;
20784 proftime_T *total;
20785 proftime_T *self;
20786 int prefer_self; /* when equal print only self time */
20788 if (count > 0)
20790 fprintf(fd, "%5d ", count);
20791 if (prefer_self && profile_equal(total, self))
20792 fprintf(fd, " ");
20793 else
20794 fprintf(fd, "%s ", profile_msg(total));
20795 if (!prefer_self && profile_equal(total, self))
20796 fprintf(fd, " ");
20797 else
20798 fprintf(fd, "%s ", profile_msg(self));
20800 else
20801 fprintf(fd, " ");
20805 * Compare function for total time sorting.
20807 static int
20808 #ifdef __BORLANDC__
20809 _RTLENTRYF
20810 #endif
20811 prof_total_cmp(s1, s2)
20812 const void *s1;
20813 const void *s2;
20815 ufunc_T *p1, *p2;
20817 p1 = *(ufunc_T **)s1;
20818 p2 = *(ufunc_T **)s2;
20819 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
20823 * Compare function for self time sorting.
20825 static int
20826 #ifdef __BORLANDC__
20827 _RTLENTRYF
20828 #endif
20829 prof_self_cmp(s1, s2)
20830 const void *s1;
20831 const void *s2;
20833 ufunc_T *p1, *p2;
20835 p1 = *(ufunc_T **)s1;
20836 p2 = *(ufunc_T **)s2;
20837 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
20840 #endif
20843 * If "name" has a package name try autoloading the script for it.
20844 * Return TRUE if a package was loaded.
20846 static int
20847 script_autoload(name, reload)
20848 char_u *name;
20849 int reload; /* load script again when already loaded */
20851 char_u *p;
20852 char_u *scriptname, *tofree;
20853 int ret = FALSE;
20854 int i;
20856 /* If there is no '#' after name[0] there is no package name. */
20857 p = vim_strchr(name, AUTOLOAD_CHAR);
20858 if (p == NULL || p == name)
20859 return FALSE;
20861 tofree = scriptname = autoload_name(name);
20863 /* Find the name in the list of previously loaded package names. Skip
20864 * "autoload/", it's always the same. */
20865 for (i = 0; i < ga_loaded.ga_len; ++i)
20866 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
20867 break;
20868 if (!reload && i < ga_loaded.ga_len)
20869 ret = FALSE; /* was loaded already */
20870 else
20872 /* Remember the name if it wasn't loaded already. */
20873 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
20875 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
20876 tofree = NULL;
20879 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
20880 if (source_runtime(scriptname, FALSE) == OK)
20881 ret = TRUE;
20884 vim_free(tofree);
20885 return ret;
20889 * Return the autoload script name for a function or variable name.
20890 * Returns NULL when out of memory.
20892 static char_u *
20893 autoload_name(name)
20894 char_u *name;
20896 char_u *p;
20897 char_u *scriptname;
20899 /* Get the script file name: replace '#' with '/', append ".vim". */
20900 scriptname = alloc((unsigned)(STRLEN(name) + 14));
20901 if (scriptname == NULL)
20902 return FALSE;
20903 STRCPY(scriptname, "autoload/");
20904 STRCAT(scriptname, name);
20905 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
20906 STRCAT(scriptname, ".vim");
20907 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
20908 *p = '/';
20909 return scriptname;
20912 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
20915 * Function given to ExpandGeneric() to obtain the list of user defined
20916 * function names.
20918 char_u *
20919 get_user_func_name(xp, idx)
20920 expand_T *xp;
20921 int idx;
20923 static long_u done;
20924 static hashitem_T *hi;
20925 ufunc_T *fp;
20927 if (idx == 0)
20929 done = 0;
20930 hi = func_hashtab.ht_array;
20932 if (done < func_hashtab.ht_used)
20934 if (done++ > 0)
20935 ++hi;
20936 while (HASHITEM_EMPTY(hi))
20937 ++hi;
20938 fp = HI2UF(hi);
20940 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
20941 return fp->uf_name; /* prevents overflow */
20943 cat_func_name(IObuff, fp);
20944 if (xp->xp_context != EXPAND_USER_FUNC)
20946 STRCAT(IObuff, "(");
20947 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
20948 STRCAT(IObuff, ")");
20950 return IObuff;
20952 return NULL;
20955 #endif /* FEAT_CMDL_COMPL */
20958 * Copy the function name of "fp" to buffer "buf".
20959 * "buf" must be able to hold the function name plus three bytes.
20960 * Takes care of script-local function names.
20962 static void
20963 cat_func_name(buf, fp)
20964 char_u *buf;
20965 ufunc_T *fp;
20967 if (fp->uf_name[0] == K_SPECIAL)
20969 STRCPY(buf, "<SNR>");
20970 STRCAT(buf, fp->uf_name + 3);
20972 else
20973 STRCPY(buf, fp->uf_name);
20977 * ":delfunction {name}"
20979 void
20980 ex_delfunction(eap)
20981 exarg_T *eap;
20983 ufunc_T *fp = NULL;
20984 char_u *p;
20985 char_u *name;
20986 funcdict_T fudi;
20988 p = eap->arg;
20989 name = trans_function_name(&p, eap->skip, 0, &fudi);
20990 vim_free(fudi.fd_newkey);
20991 if (name == NULL)
20993 if (fudi.fd_dict != NULL && !eap->skip)
20994 EMSG(_(e_funcref));
20995 return;
20997 if (!ends_excmd(*skipwhite(p)))
20999 vim_free(name);
21000 EMSG(_(e_trailing));
21001 return;
21003 eap->nextcmd = check_nextcmd(p);
21004 if (eap->nextcmd != NULL)
21005 *p = NUL;
21007 if (!eap->skip)
21008 fp = find_func(name);
21009 vim_free(name);
21011 if (!eap->skip)
21013 if (fp == NULL)
21015 EMSG2(_(e_nofunc), eap->arg);
21016 return;
21018 if (fp->uf_calls > 0)
21020 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
21021 return;
21024 if (fudi.fd_dict != NULL)
21026 /* Delete the dict item that refers to the function, it will
21027 * invoke func_unref() and possibly delete the function. */
21028 dictitem_remove(fudi.fd_dict, fudi.fd_di);
21030 else
21031 func_free(fp);
21036 * Free a function and remove it from the list of functions.
21038 static void
21039 func_free(fp)
21040 ufunc_T *fp;
21042 hashitem_T *hi;
21044 /* clear this function */
21045 ga_clear_strings(&(fp->uf_args));
21046 ga_clear_strings(&(fp->uf_lines));
21047 #ifdef FEAT_PROFILE
21048 vim_free(fp->uf_tml_count);
21049 vim_free(fp->uf_tml_total);
21050 vim_free(fp->uf_tml_self);
21051 #endif
21053 /* remove the function from the function hashtable */
21054 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
21055 if (HASHITEM_EMPTY(hi))
21056 EMSG2(_(e_intern2), "func_free()");
21057 else
21058 hash_remove(&func_hashtab, hi);
21060 vim_free(fp);
21064 * Unreference a Function: decrement the reference count and free it when it
21065 * becomes zero. Only for numbered functions.
21067 static void
21068 func_unref(name)
21069 char_u *name;
21071 ufunc_T *fp;
21073 if (name != NULL && isdigit(*name))
21075 fp = find_func(name);
21076 if (fp == NULL)
21077 EMSG2(_(e_intern2), "func_unref()");
21078 else if (--fp->uf_refcount <= 0)
21080 /* Only delete it when it's not being used. Otherwise it's done
21081 * when "uf_calls" becomes zero. */
21082 if (fp->uf_calls == 0)
21083 func_free(fp);
21089 * Count a reference to a Function.
21091 static void
21092 func_ref(name)
21093 char_u *name;
21095 ufunc_T *fp;
21097 if (name != NULL && isdigit(*name))
21099 fp = find_func(name);
21100 if (fp == NULL)
21101 EMSG2(_(e_intern2), "func_ref()");
21102 else
21103 ++fp->uf_refcount;
21108 * Call a user function.
21110 static void
21111 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
21112 ufunc_T *fp; /* pointer to function */
21113 int argcount; /* nr of args */
21114 typval_T *argvars; /* arguments */
21115 typval_T *rettv; /* return value */
21116 linenr_T firstline; /* first line of range */
21117 linenr_T lastline; /* last line of range */
21118 dict_T *selfdict; /* Dictionary for "self" */
21120 char_u *save_sourcing_name;
21121 linenr_T save_sourcing_lnum;
21122 scid_T save_current_SID;
21123 funccall_T *fc;
21124 int save_did_emsg;
21125 static int depth = 0;
21126 dictitem_T *v;
21127 int fixvar_idx = 0; /* index in fixvar[] */
21128 int i;
21129 int ai;
21130 char_u numbuf[NUMBUFLEN];
21131 char_u *name;
21132 #ifdef FEAT_PROFILE
21133 proftime_T wait_start;
21134 proftime_T call_start;
21135 #endif
21137 /* If depth of calling is getting too high, don't execute the function */
21138 if (depth >= p_mfd)
21140 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
21141 rettv->v_type = VAR_NUMBER;
21142 rettv->vval.v_number = -1;
21143 return;
21145 ++depth;
21147 line_breakcheck(); /* check for CTRL-C hit */
21149 fc = (funccall_T *)alloc(sizeof(funccall_T));
21150 fc->caller = current_funccal;
21151 current_funccal = fc;
21152 fc->func = fp;
21153 fc->rettv = rettv;
21154 rettv->vval.v_number = 0;
21155 fc->linenr = 0;
21156 fc->returned = FALSE;
21157 fc->level = ex_nesting_level;
21158 /* Check if this function has a breakpoint. */
21159 fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
21160 fc->dbg_tick = debug_tick;
21163 * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables
21164 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
21165 * each argument variable and saves a lot of time.
21168 * Init l: variables.
21170 init_var_dict(&fc->l_vars, &fc->l_vars_var);
21171 if (selfdict != NULL)
21173 /* Set l:self to "selfdict". Use "name" to avoid a warning from
21174 * some compiler that checks the destination size. */
21175 v = &fc->fixvar[fixvar_idx++].var;
21176 name = v->di_key;
21177 STRCPY(name, "self");
21178 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
21179 hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
21180 v->di_tv.v_type = VAR_DICT;
21181 v->di_tv.v_lock = 0;
21182 v->di_tv.vval.v_dict = selfdict;
21183 ++selfdict->dv_refcount;
21187 * Init a: variables.
21188 * Set a:0 to "argcount".
21189 * Set a:000 to a list with room for the "..." arguments.
21191 init_var_dict(&fc->l_avars, &fc->l_avars_var);
21192 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0",
21193 (varnumber_T)(argcount - fp->uf_args.ga_len));
21194 /* Use "name" to avoid a warning from some compiler that checks the
21195 * destination size. */
21196 v = &fc->fixvar[fixvar_idx++].var;
21197 name = v->di_key;
21198 STRCPY(name, "000");
21199 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21200 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21201 v->di_tv.v_type = VAR_LIST;
21202 v->di_tv.v_lock = VAR_FIXED;
21203 v->di_tv.vval.v_list = &fc->l_varlist;
21204 vim_memset(&fc->l_varlist, 0, sizeof(list_T));
21205 fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT;
21206 fc->l_varlist.lv_lock = VAR_FIXED;
21209 * Set a:firstline to "firstline" and a:lastline to "lastline".
21210 * Set a:name to named arguments.
21211 * Set a:N to the "..." arguments.
21213 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline",
21214 (varnumber_T)firstline);
21215 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline",
21216 (varnumber_T)lastline);
21217 for (i = 0; i < argcount; ++i)
21219 ai = i - fp->uf_args.ga_len;
21220 if (ai < 0)
21221 /* named argument a:name */
21222 name = FUNCARG(fp, i);
21223 else
21225 /* "..." argument a:1, a:2, etc. */
21226 sprintf((char *)numbuf, "%d", ai + 1);
21227 name = numbuf;
21229 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
21231 v = &fc->fixvar[fixvar_idx++].var;
21232 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21234 else
21236 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
21237 + STRLEN(name)));
21238 if (v == NULL)
21239 break;
21240 v->di_flags = DI_FLAGS_RO;
21242 STRCPY(v->di_key, name);
21243 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21245 /* Note: the values are copied directly to avoid alloc/free.
21246 * "argvars" must have VAR_FIXED for v_lock. */
21247 v->di_tv = argvars[i];
21248 v->di_tv.v_lock = VAR_FIXED;
21250 if (ai >= 0 && ai < MAX_FUNC_ARGS)
21252 list_append(&fc->l_varlist, &fc->l_listitems[ai]);
21253 fc->l_listitems[ai].li_tv = argvars[i];
21254 fc->l_listitems[ai].li_tv.v_lock = VAR_FIXED;
21258 /* Don't redraw while executing the function. */
21259 ++RedrawingDisabled;
21260 save_sourcing_name = sourcing_name;
21261 save_sourcing_lnum = sourcing_lnum;
21262 sourcing_lnum = 1;
21263 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
21264 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
21265 if (sourcing_name != NULL)
21267 if (save_sourcing_name != NULL
21268 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
21269 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
21270 else
21271 STRCPY(sourcing_name, "function ");
21272 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
21274 if (p_verbose >= 12)
21276 ++no_wait_return;
21277 verbose_enter_scroll();
21279 smsg((char_u *)_("calling %s"), sourcing_name);
21280 if (p_verbose >= 14)
21282 char_u buf[MSG_BUF_LEN];
21283 char_u numbuf2[NUMBUFLEN];
21284 char_u *tofree;
21285 char_u *s;
21287 msg_puts((char_u *)"(");
21288 for (i = 0; i < argcount; ++i)
21290 if (i > 0)
21291 msg_puts((char_u *)", ");
21292 if (argvars[i].v_type == VAR_NUMBER)
21293 msg_outnum((long)argvars[i].vval.v_number);
21294 else
21296 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
21297 if (s != NULL)
21299 trunc_string(s, buf, MSG_BUF_CLEN);
21300 msg_puts(buf);
21301 vim_free(tofree);
21305 msg_puts((char_u *)")");
21307 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21309 verbose_leave_scroll();
21310 --no_wait_return;
21313 #ifdef FEAT_PROFILE
21314 if (do_profiling == PROF_YES)
21316 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
21317 func_do_profile(fp);
21318 if (fp->uf_profiling
21319 || (fc->caller != NULL && fc->caller->func->uf_profiling))
21321 ++fp->uf_tm_count;
21322 profile_start(&call_start);
21323 profile_zero(&fp->uf_tm_children);
21325 script_prof_save(&wait_start);
21327 #endif
21329 save_current_SID = current_SID;
21330 current_SID = fp->uf_script_ID;
21331 save_did_emsg = did_emsg;
21332 did_emsg = FALSE;
21334 /* call do_cmdline() to execute the lines */
21335 do_cmdline(NULL, get_func_line, (void *)fc,
21336 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
21338 --RedrawingDisabled;
21340 /* when the function was aborted because of an error, return -1 */
21341 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
21343 clear_tv(rettv);
21344 rettv->v_type = VAR_NUMBER;
21345 rettv->vval.v_number = -1;
21348 #ifdef FEAT_PROFILE
21349 if (do_profiling == PROF_YES && (fp->uf_profiling
21350 || (fc->caller != NULL && fc->caller->func->uf_profiling)))
21352 profile_end(&call_start);
21353 profile_sub_wait(&wait_start, &call_start);
21354 profile_add(&fp->uf_tm_total, &call_start);
21355 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
21356 if (fc->caller != NULL && fc->caller->func->uf_profiling)
21358 profile_add(&fc->caller->func->uf_tm_children, &call_start);
21359 profile_add(&fc->caller->func->uf_tml_children, &call_start);
21362 #endif
21364 /* when being verbose, mention the return value */
21365 if (p_verbose >= 12)
21367 ++no_wait_return;
21368 verbose_enter_scroll();
21370 if (aborting())
21371 smsg((char_u *)_("%s aborted"), sourcing_name);
21372 else if (fc->rettv->v_type == VAR_NUMBER)
21373 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
21374 (long)fc->rettv->vval.v_number);
21375 else
21377 char_u buf[MSG_BUF_LEN];
21378 char_u numbuf2[NUMBUFLEN];
21379 char_u *tofree;
21380 char_u *s;
21382 /* The value may be very long. Skip the middle part, so that we
21383 * have some idea how it starts and ends. smsg() would always
21384 * truncate it at the end. */
21385 s = tv2string(fc->rettv, &tofree, numbuf2, 0);
21386 if (s != NULL)
21388 trunc_string(s, buf, MSG_BUF_CLEN);
21389 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
21390 vim_free(tofree);
21393 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21395 verbose_leave_scroll();
21396 --no_wait_return;
21399 vim_free(sourcing_name);
21400 sourcing_name = save_sourcing_name;
21401 sourcing_lnum = save_sourcing_lnum;
21402 current_SID = save_current_SID;
21403 #ifdef FEAT_PROFILE
21404 if (do_profiling == PROF_YES)
21405 script_prof_restore(&wait_start);
21406 #endif
21408 if (p_verbose >= 12 && sourcing_name != NULL)
21410 ++no_wait_return;
21411 verbose_enter_scroll();
21413 smsg((char_u *)_("continuing in %s"), sourcing_name);
21414 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21416 verbose_leave_scroll();
21417 --no_wait_return;
21420 did_emsg |= save_did_emsg;
21421 current_funccal = fc->caller;
21422 --depth;
21424 /* If the a:000 list and the l: and a: dicts are not referenced we can
21425 * free the funccall_T and what's in it. */
21426 if (fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
21427 && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
21428 && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT)
21430 free_funccal(fc, FALSE);
21432 else
21434 hashitem_T *hi;
21435 listitem_T *li;
21436 int todo;
21438 /* "fc" is still in use. This can happen when returning "a:000" or
21439 * assigning "l:" to a global variable.
21440 * Link "fc" in the list for garbage collection later. */
21441 fc->caller = previous_funccal;
21442 previous_funccal = fc;
21444 /* Make a copy of the a: variables, since we didn't do that above. */
21445 todo = (int)fc->l_avars.dv_hashtab.ht_used;
21446 for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi)
21448 if (!HASHITEM_EMPTY(hi))
21450 --todo;
21451 v = HI2DI(hi);
21452 copy_tv(&v->di_tv, &v->di_tv);
21456 /* Make a copy of the a:000 items, since we didn't do that above. */
21457 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21458 copy_tv(&li->li_tv, &li->li_tv);
21463 * Return TRUE if items in "fc" do not have "copyID". That means they are not
21464 * referenced from anywhere that is in use.
21466 static int
21467 can_free_funccal(fc, copyID)
21468 funccall_T *fc;
21469 int copyID;
21471 return (fc->l_varlist.lv_copyID != copyID
21472 && fc->l_vars.dv_copyID != copyID
21473 && fc->l_avars.dv_copyID != copyID);
21477 * Free "fc" and what it contains.
21479 static void
21480 free_funccal(fc, free_val)
21481 funccall_T *fc;
21482 int free_val; /* a: vars were allocated */
21484 listitem_T *li;
21486 /* The a: variables typevals may not have been allocated, only free the
21487 * allocated variables. */
21488 vars_clear_ext(&fc->l_avars.dv_hashtab, free_val);
21490 /* free all l: variables */
21491 vars_clear(&fc->l_vars.dv_hashtab);
21493 /* Free the a:000 variables if they were allocated. */
21494 if (free_val)
21495 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21496 clear_tv(&li->li_tv);
21498 vim_free(fc);
21502 * Add a number variable "name" to dict "dp" with value "nr".
21504 static void
21505 add_nr_var(dp, v, name, nr)
21506 dict_T *dp;
21507 dictitem_T *v;
21508 char *name;
21509 varnumber_T nr;
21511 STRCPY(v->di_key, name);
21512 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21513 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
21514 v->di_tv.v_type = VAR_NUMBER;
21515 v->di_tv.v_lock = VAR_FIXED;
21516 v->di_tv.vval.v_number = nr;
21520 * ":return [expr]"
21522 void
21523 ex_return(eap)
21524 exarg_T *eap;
21526 char_u *arg = eap->arg;
21527 typval_T rettv;
21528 int returning = FALSE;
21530 if (current_funccal == NULL)
21532 EMSG(_("E133: :return not inside a function"));
21533 return;
21536 if (eap->skip)
21537 ++emsg_skip;
21539 eap->nextcmd = NULL;
21540 if ((*arg != NUL && *arg != '|' && *arg != '\n')
21541 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
21543 if (!eap->skip)
21544 returning = do_return(eap, FALSE, TRUE, &rettv);
21545 else
21546 clear_tv(&rettv);
21548 /* It's safer to return also on error. */
21549 else if (!eap->skip)
21552 * Return unless the expression evaluation has been cancelled due to an
21553 * aborting error, an interrupt, or an exception.
21555 if (!aborting())
21556 returning = do_return(eap, FALSE, TRUE, NULL);
21559 /* When skipping or the return gets pending, advance to the next command
21560 * in this line (!returning). Otherwise, ignore the rest of the line.
21561 * Following lines will be ignored by get_func_line(). */
21562 if (returning)
21563 eap->nextcmd = NULL;
21564 else if (eap->nextcmd == NULL) /* no argument */
21565 eap->nextcmd = check_nextcmd(arg);
21567 if (eap->skip)
21568 --emsg_skip;
21572 * Return from a function. Possibly makes the return pending. Also called
21573 * for a pending return at the ":endtry" or after returning from an extra
21574 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
21575 * when called due to a ":return" command. "rettv" may point to a typval_T
21576 * with the return rettv. Returns TRUE when the return can be carried out,
21577 * FALSE when the return gets pending.
21580 do_return(eap, reanimate, is_cmd, rettv)
21581 exarg_T *eap;
21582 int reanimate;
21583 int is_cmd;
21584 void *rettv;
21586 int idx;
21587 struct condstack *cstack = eap->cstack;
21589 if (reanimate)
21590 /* Undo the return. */
21591 current_funccal->returned = FALSE;
21594 * Cleanup (and inactivate) conditionals, but stop when a try conditional
21595 * not in its finally clause (which then is to be executed next) is found.
21596 * In this case, make the ":return" pending for execution at the ":endtry".
21597 * Otherwise, return normally.
21599 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
21600 if (idx >= 0)
21602 cstack->cs_pending[idx] = CSTP_RETURN;
21604 if (!is_cmd && !reanimate)
21605 /* A pending return again gets pending. "rettv" points to an
21606 * allocated variable with the rettv of the original ":return"'s
21607 * argument if present or is NULL else. */
21608 cstack->cs_rettv[idx] = rettv;
21609 else
21611 /* When undoing a return in order to make it pending, get the stored
21612 * return rettv. */
21613 if (reanimate)
21614 rettv = current_funccal->rettv;
21616 if (rettv != NULL)
21618 /* Store the value of the pending return. */
21619 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
21620 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
21621 else
21622 EMSG(_(e_outofmem));
21624 else
21625 cstack->cs_rettv[idx] = NULL;
21627 if (reanimate)
21629 /* The pending return value could be overwritten by a ":return"
21630 * without argument in a finally clause; reset the default
21631 * return value. */
21632 current_funccal->rettv->v_type = VAR_NUMBER;
21633 current_funccal->rettv->vval.v_number = 0;
21636 report_make_pending(CSTP_RETURN, rettv);
21638 else
21640 current_funccal->returned = TRUE;
21642 /* If the return is carried out now, store the return value. For
21643 * a return immediately after reanimation, the value is already
21644 * there. */
21645 if (!reanimate && rettv != NULL)
21647 clear_tv(current_funccal->rettv);
21648 *current_funccal->rettv = *(typval_T *)rettv;
21649 if (!is_cmd)
21650 vim_free(rettv);
21654 return idx < 0;
21658 * Free the variable with a pending return value.
21660 void
21661 discard_pending_return(rettv)
21662 void *rettv;
21664 free_tv((typval_T *)rettv);
21668 * Generate a return command for producing the value of "rettv". The result
21669 * is an allocated string. Used by report_pending() for verbose messages.
21671 char_u *
21672 get_return_cmd(rettv)
21673 void *rettv;
21675 char_u *s = NULL;
21676 char_u *tofree = NULL;
21677 char_u numbuf[NUMBUFLEN];
21679 if (rettv != NULL)
21680 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
21681 if (s == NULL)
21682 s = (char_u *)"";
21684 STRCPY(IObuff, ":return ");
21685 STRNCPY(IObuff + 8, s, IOSIZE - 8);
21686 if (STRLEN(s) + 8 >= IOSIZE)
21687 STRCPY(IObuff + IOSIZE - 4, "...");
21688 vim_free(tofree);
21689 return vim_strsave(IObuff);
21693 * Get next function line.
21694 * Called by do_cmdline() to get the next line.
21695 * Returns allocated string, or NULL for end of function.
21697 char_u *
21698 get_func_line(c, cookie, indent)
21699 int c UNUSED;
21700 void *cookie;
21701 int indent UNUSED;
21703 funccall_T *fcp = (funccall_T *)cookie;
21704 ufunc_T *fp = fcp->func;
21705 char_u *retval;
21706 garray_T *gap; /* growarray with function lines */
21708 /* If breakpoints have been added/deleted need to check for it. */
21709 if (fcp->dbg_tick != debug_tick)
21711 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21712 sourcing_lnum);
21713 fcp->dbg_tick = debug_tick;
21715 #ifdef FEAT_PROFILE
21716 if (do_profiling == PROF_YES)
21717 func_line_end(cookie);
21718 #endif
21720 gap = &fp->uf_lines;
21721 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21722 || fcp->returned)
21723 retval = NULL;
21724 else
21726 /* Skip NULL lines (continuation lines). */
21727 while (fcp->linenr < gap->ga_len
21728 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
21729 ++fcp->linenr;
21730 if (fcp->linenr >= gap->ga_len)
21731 retval = NULL;
21732 else
21734 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
21735 sourcing_lnum = fcp->linenr;
21736 #ifdef FEAT_PROFILE
21737 if (do_profiling == PROF_YES)
21738 func_line_start(cookie);
21739 #endif
21743 /* Did we encounter a breakpoint? */
21744 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
21746 dbg_breakpoint(fp->uf_name, sourcing_lnum);
21747 /* Find next breakpoint. */
21748 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21749 sourcing_lnum);
21750 fcp->dbg_tick = debug_tick;
21753 return retval;
21756 #if defined(FEAT_PROFILE) || defined(PROTO)
21758 * Called when starting to read a function line.
21759 * "sourcing_lnum" must be correct!
21760 * When skipping lines it may not actually be executed, but we won't find out
21761 * until later and we need to store the time now.
21763 void
21764 func_line_start(cookie)
21765 void *cookie;
21767 funccall_T *fcp = (funccall_T *)cookie;
21768 ufunc_T *fp = fcp->func;
21770 if (fp->uf_profiling && sourcing_lnum >= 1
21771 && sourcing_lnum <= fp->uf_lines.ga_len)
21773 fp->uf_tml_idx = sourcing_lnum - 1;
21774 /* Skip continuation lines. */
21775 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
21776 --fp->uf_tml_idx;
21777 fp->uf_tml_execed = FALSE;
21778 profile_start(&fp->uf_tml_start);
21779 profile_zero(&fp->uf_tml_children);
21780 profile_get_wait(&fp->uf_tml_wait);
21785 * Called when actually executing a function line.
21787 void
21788 func_line_exec(cookie)
21789 void *cookie;
21791 funccall_T *fcp = (funccall_T *)cookie;
21792 ufunc_T *fp = fcp->func;
21794 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21795 fp->uf_tml_execed = TRUE;
21799 * Called when done with a function line.
21801 void
21802 func_line_end(cookie)
21803 void *cookie;
21805 funccall_T *fcp = (funccall_T *)cookie;
21806 ufunc_T *fp = fcp->func;
21808 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21810 if (fp->uf_tml_execed)
21812 ++fp->uf_tml_count[fp->uf_tml_idx];
21813 profile_end(&fp->uf_tml_start);
21814 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
21815 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
21816 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
21817 &fp->uf_tml_children);
21819 fp->uf_tml_idx = -1;
21822 #endif
21825 * Return TRUE if the currently active function should be ended, because a
21826 * return was encountered or an error occurred. Used inside a ":while".
21829 func_has_ended(cookie)
21830 void *cookie;
21832 funccall_T *fcp = (funccall_T *)cookie;
21834 /* Ignore the "abort" flag if the abortion behavior has been changed due to
21835 * an error inside a try conditional. */
21836 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21837 || fcp->returned);
21841 * return TRUE if cookie indicates a function which "abort"s on errors.
21844 func_has_abort(cookie)
21845 void *cookie;
21847 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
21850 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
21851 typedef enum
21853 VAR_FLAVOUR_DEFAULT, /* doesn't start with uppercase */
21854 VAR_FLAVOUR_SESSION, /* starts with uppercase, some lower */
21855 VAR_FLAVOUR_VIMINFO /* all uppercase */
21856 } var_flavour_T;
21858 static var_flavour_T var_flavour __ARGS((char_u *varname));
21860 static var_flavour_T
21861 var_flavour(varname)
21862 char_u *varname;
21864 char_u *p = varname;
21866 if (ASCII_ISUPPER(*p))
21868 while (*(++p))
21869 if (ASCII_ISLOWER(*p))
21870 return VAR_FLAVOUR_SESSION;
21871 return VAR_FLAVOUR_VIMINFO;
21873 else
21874 return VAR_FLAVOUR_DEFAULT;
21876 #endif
21878 #if defined(FEAT_VIMINFO) || defined(PROTO)
21880 * Restore global vars that start with a capital from the viminfo file
21883 read_viminfo_varlist(virp, writing)
21884 vir_T *virp;
21885 int writing;
21887 char_u *tab;
21888 int type = VAR_NUMBER;
21889 typval_T tv;
21891 if (!writing && (find_viminfo_parameter('!') != NULL))
21893 tab = vim_strchr(virp->vir_line + 1, '\t');
21894 if (tab != NULL)
21896 *tab++ = '\0'; /* isolate the variable name */
21897 if (*tab == 'S') /* string var */
21898 type = VAR_STRING;
21899 #ifdef FEAT_FLOAT
21900 else if (*tab == 'F')
21901 type = VAR_FLOAT;
21902 #endif
21904 tab = vim_strchr(tab, '\t');
21905 if (tab != NULL)
21907 tv.v_type = type;
21908 if (type == VAR_STRING)
21909 tv.vval.v_string = viminfo_readstring(virp,
21910 (int)(tab - virp->vir_line + 1), TRUE);
21911 #ifdef FEAT_FLOAT
21912 else if (type == VAR_FLOAT)
21913 (void)string2float(tab + 1, &tv.vval.v_float);
21914 #endif
21915 else
21916 tv.vval.v_number = atol((char *)tab + 1);
21917 set_var(virp->vir_line + 1, &tv, FALSE);
21918 if (type == VAR_STRING)
21919 vim_free(tv.vval.v_string);
21924 return viminfo_readline(virp);
21928 * Write global vars that start with a capital to the viminfo file
21930 void
21931 write_viminfo_varlist(fp)
21932 FILE *fp;
21934 hashitem_T *hi;
21935 dictitem_T *this_var;
21936 int todo;
21937 char *s;
21938 char_u *p;
21939 char_u *tofree;
21940 char_u numbuf[NUMBUFLEN];
21942 if (find_viminfo_parameter('!') == NULL)
21943 return;
21945 fputs(_("\n# global variables:\n"), fp);
21947 todo = (int)globvarht.ht_used;
21948 for (hi = globvarht.ht_array; todo > 0; ++hi)
21950 if (!HASHITEM_EMPTY(hi))
21952 --todo;
21953 this_var = HI2DI(hi);
21954 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
21956 switch (this_var->di_tv.v_type)
21958 case VAR_STRING: s = "STR"; break;
21959 case VAR_NUMBER: s = "NUM"; break;
21960 #ifdef FEAT_FLOAT
21961 case VAR_FLOAT: s = "FLO"; break;
21962 #endif
21963 default: continue;
21965 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
21966 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
21967 if (p != NULL)
21968 viminfo_writestring(fp, p);
21969 vim_free(tofree);
21974 #endif
21976 #if defined(FEAT_SESSION) || defined(PROTO)
21978 store_session_globals(fd)
21979 FILE *fd;
21981 hashitem_T *hi;
21982 dictitem_T *this_var;
21983 int todo;
21984 char_u *p, *t;
21986 todo = (int)globvarht.ht_used;
21987 for (hi = globvarht.ht_array; todo > 0; ++hi)
21989 if (!HASHITEM_EMPTY(hi))
21991 --todo;
21992 this_var = HI2DI(hi);
21993 if ((this_var->di_tv.v_type == VAR_NUMBER
21994 || this_var->di_tv.v_type == VAR_STRING)
21995 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
21997 /* Escape special characters with a backslash. Turn a LF and
21998 * CR into \n and \r. */
21999 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
22000 (char_u *)"\\\"\n\r");
22001 if (p == NULL) /* out of memory */
22002 break;
22003 for (t = p; *t != NUL; ++t)
22004 if (*t == '\n')
22005 *t = 'n';
22006 else if (*t == '\r')
22007 *t = 'r';
22008 if ((fprintf(fd, "let %s = %c%s%c",
22009 this_var->di_key,
22010 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22011 : ' ',
22013 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22014 : ' ') < 0)
22015 || put_eol(fd) == FAIL)
22017 vim_free(p);
22018 return FAIL;
22020 vim_free(p);
22022 #ifdef FEAT_FLOAT
22023 else if (this_var->di_tv.v_type == VAR_FLOAT
22024 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22026 float_T f = this_var->di_tv.vval.v_float;
22027 int sign = ' ';
22029 if (f < 0)
22031 f = -f;
22032 sign = '-';
22034 if ((fprintf(fd, "let %s = %c&%f",
22035 this_var->di_key, sign, f) < 0)
22036 || put_eol(fd) == FAIL)
22037 return FAIL;
22039 #endif
22042 return OK;
22044 #endif
22047 * Display script name where an item was last set.
22048 * Should only be invoked when 'verbose' is non-zero.
22050 void
22051 last_set_msg(scriptID)
22052 scid_T scriptID;
22054 char_u *p;
22056 if (scriptID != 0)
22058 p = home_replace_save(NULL, get_scriptname(scriptID));
22059 if (p != NULL)
22061 verbose_enter();
22062 MSG_PUTS(_("\n\tLast set from "));
22063 MSG_PUTS(p);
22064 vim_free(p);
22065 verbose_leave();
22071 * List v:oldfiles in a nice way.
22073 void
22074 ex_oldfiles(eap)
22075 exarg_T *eap UNUSED;
22077 list_T *l = vimvars[VV_OLDFILES].vv_list;
22078 listitem_T *li;
22079 int nr = 0;
22081 if (l == NULL)
22082 msg((char_u *)_("No old files"));
22083 else
22085 msg_start();
22086 msg_scroll = TRUE;
22087 for (li = l->lv_first; li != NULL && !got_int; li = li->li_next)
22089 msg_outnum((long)++nr);
22090 MSG_PUTS(": ");
22091 msg_outtrans(get_tv_string(&li->li_tv));
22092 msg_putchar('\n');
22093 out_flush(); /* output one line at a time */
22094 ui_breakcheck();
22096 /* Assume "got_int" was set to truncate the listing. */
22097 got_int = FALSE;
22099 #ifdef FEAT_BROWSE_CMD
22100 if (cmdmod.browse)
22102 quit_more = FALSE;
22103 nr = prompt_for_number(FALSE);
22104 msg_starthere();
22105 if (nr > 0)
22107 char_u *p = list_find_str(get_vim_var_list(VV_OLDFILES),
22108 (long)nr);
22110 if (p != NULL)
22112 p = expand_env_save(p);
22113 eap->arg = p;
22114 eap->cmdidx = CMD_edit;
22115 cmdmod.browse = FALSE;
22116 do_exedit(eap, NULL);
22117 vim_free(p);
22121 #endif
22125 #endif /* FEAT_EVAL */
22128 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
22130 #ifdef WIN3264
22132 * Functions for ":8" filename modifier: get 8.3 version of a filename.
22134 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22135 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
22136 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22139 * Get the short path (8.3) for the filename in "fnamep".
22140 * Only works for a valid file name.
22141 * When the path gets longer "fnamep" is changed and the allocated buffer
22142 * is put in "bufp".
22143 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
22144 * Returns OK on success, FAIL on failure.
22146 static int
22147 get_short_pathname(fnamep, bufp, fnamelen)
22148 char_u **fnamep;
22149 char_u **bufp;
22150 int *fnamelen;
22152 int l, len;
22153 char_u *newbuf;
22155 len = *fnamelen;
22156 l = GetShortPathName(*fnamep, *fnamep, len);
22157 if (l > len - 1)
22159 /* If that doesn't work (not enough space), then save the string
22160 * and try again with a new buffer big enough. */
22161 newbuf = vim_strnsave(*fnamep, l);
22162 if (newbuf == NULL)
22163 return FAIL;
22165 vim_free(*bufp);
22166 *fnamep = *bufp = newbuf;
22168 /* Really should always succeed, as the buffer is big enough. */
22169 l = GetShortPathName(*fnamep, *fnamep, l+1);
22172 *fnamelen = l;
22173 return OK;
22177 * Get the short path (8.3) for the filename in "fname". The converted
22178 * path is returned in "bufp".
22180 * Some of the directories specified in "fname" may not exist. This function
22181 * will shorten the existing directories at the beginning of the path and then
22182 * append the remaining non-existing path.
22184 * fname - Pointer to the filename to shorten. On return, contains the
22185 * pointer to the shortened pathname
22186 * bufp - Pointer to an allocated buffer for the filename.
22187 * fnamelen - Length of the filename pointed to by fname
22189 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
22191 static int
22192 shortpath_for_invalid_fname(fname, bufp, fnamelen)
22193 char_u **fname;
22194 char_u **bufp;
22195 int *fnamelen;
22197 char_u *short_fname, *save_fname, *pbuf_unused;
22198 char_u *endp, *save_endp;
22199 char_u ch;
22200 int old_len, len;
22201 int new_len, sfx_len;
22202 int retval = OK;
22204 /* Make a copy */
22205 old_len = *fnamelen;
22206 save_fname = vim_strnsave(*fname, old_len);
22207 pbuf_unused = NULL;
22208 short_fname = NULL;
22210 endp = save_fname + old_len - 1; /* Find the end of the copy */
22211 save_endp = endp;
22214 * Try shortening the supplied path till it succeeds by removing one
22215 * directory at a time from the tail of the path.
22217 len = 0;
22218 for (;;)
22220 /* go back one path-separator */
22221 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
22222 --endp;
22223 if (endp <= save_fname)
22224 break; /* processed the complete path */
22227 * Replace the path separator with a NUL and try to shorten the
22228 * resulting path.
22230 ch = *endp;
22231 *endp = 0;
22232 short_fname = save_fname;
22233 len = (int)STRLEN(short_fname) + 1;
22234 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
22236 retval = FAIL;
22237 goto theend;
22239 *endp = ch; /* preserve the string */
22241 if (len > 0)
22242 break; /* successfully shortened the path */
22244 /* failed to shorten the path. Skip the path separator */
22245 --endp;
22248 if (len > 0)
22251 * Succeeded in shortening the path. Now concatenate the shortened
22252 * path with the remaining path at the tail.
22255 /* Compute the length of the new path. */
22256 sfx_len = (int)(save_endp - endp) + 1;
22257 new_len = len + sfx_len;
22259 *fnamelen = new_len;
22260 vim_free(*bufp);
22261 if (new_len > old_len)
22263 /* There is not enough space in the currently allocated string,
22264 * copy it to a buffer big enough. */
22265 *fname = *bufp = vim_strnsave(short_fname, new_len);
22266 if (*fname == NULL)
22268 retval = FAIL;
22269 goto theend;
22272 else
22274 /* Transfer short_fname to the main buffer (it's big enough),
22275 * unless get_short_pathname() did its work in-place. */
22276 *fname = *bufp = save_fname;
22277 if (short_fname != save_fname)
22278 vim_strncpy(save_fname, short_fname, len);
22279 save_fname = NULL;
22282 /* concat the not-shortened part of the path */
22283 vim_strncpy(*fname + len, endp, sfx_len);
22284 (*fname)[new_len] = NUL;
22287 theend:
22288 vim_free(pbuf_unused);
22289 vim_free(save_fname);
22291 return retval;
22295 * Get a pathname for a partial path.
22296 * Returns OK for success, FAIL for failure.
22298 static int
22299 shortpath_for_partial(fnamep, bufp, fnamelen)
22300 char_u **fnamep;
22301 char_u **bufp;
22302 int *fnamelen;
22304 int sepcount, len, tflen;
22305 char_u *p;
22306 char_u *pbuf, *tfname;
22307 int hasTilde;
22309 /* Count up the path separators from the RHS.. so we know which part
22310 * of the path to return. */
22311 sepcount = 0;
22312 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
22313 if (vim_ispathsep(*p))
22314 ++sepcount;
22316 /* Need full path first (use expand_env() to remove a "~/") */
22317 hasTilde = (**fnamep == '~');
22318 if (hasTilde)
22319 pbuf = tfname = expand_env_save(*fnamep);
22320 else
22321 pbuf = tfname = FullName_save(*fnamep, FALSE);
22323 len = tflen = (int)STRLEN(tfname);
22325 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
22326 return FAIL;
22328 if (len == 0)
22330 /* Don't have a valid filename, so shorten the rest of the
22331 * path if we can. This CAN give us invalid 8.3 filenames, but
22332 * there's not a lot of point in guessing what it might be.
22334 len = tflen;
22335 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
22336 return FAIL;
22339 /* Count the paths backward to find the beginning of the desired string. */
22340 for (p = tfname + len - 1; p >= tfname; --p)
22342 #ifdef FEAT_MBYTE
22343 if (has_mbyte)
22344 p -= mb_head_off(tfname, p);
22345 #endif
22346 if (vim_ispathsep(*p))
22348 if (sepcount == 0 || (hasTilde && sepcount == 1))
22349 break;
22350 else
22351 sepcount --;
22354 if (hasTilde)
22356 --p;
22357 if (p >= tfname)
22358 *p = '~';
22359 else
22360 return FAIL;
22362 else
22363 ++p;
22365 /* Copy in the string - p indexes into tfname - allocated at pbuf */
22366 vim_free(*bufp);
22367 *fnamelen = (int)STRLEN(p);
22368 *bufp = pbuf;
22369 *fnamep = p;
22371 return OK;
22373 #endif /* WIN3264 */
22376 * Adjust a filename, according to a string of modifiers.
22377 * *fnamep must be NUL terminated when called. When returning, the length is
22378 * determined by *fnamelen.
22379 * Returns VALID_ flags or -1 for failure.
22380 * When there is an error, *fnamep is set to NULL.
22383 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
22384 char_u *src; /* string with modifiers */
22385 int *usedlen; /* characters after src that are used */
22386 char_u **fnamep; /* file name so far */
22387 char_u **bufp; /* buffer for allocated file name or NULL */
22388 int *fnamelen; /* length of fnamep */
22390 int valid = 0;
22391 char_u *tail;
22392 char_u *s, *p, *pbuf;
22393 char_u dirname[MAXPATHL];
22394 int c;
22395 int has_fullname = 0;
22396 #ifdef WIN3264
22397 int has_shortname = 0;
22398 #endif
22400 repeat:
22401 /* ":p" - full path/file_name */
22402 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
22404 has_fullname = 1;
22406 valid |= VALID_PATH;
22407 *usedlen += 2;
22409 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
22410 if ((*fnamep)[0] == '~'
22411 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
22412 && ((*fnamep)[1] == '/'
22413 # ifdef BACKSLASH_IN_FILENAME
22414 || (*fnamep)[1] == '\\'
22415 # endif
22416 || (*fnamep)[1] == NUL)
22418 #endif
22421 *fnamep = expand_env_save(*fnamep);
22422 vim_free(*bufp); /* free any allocated file name */
22423 *bufp = *fnamep;
22424 if (*fnamep == NULL)
22425 return -1;
22428 /* When "/." or "/.." is used: force expansion to get rid of it. */
22429 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
22431 if (vim_ispathsep(*p)
22432 && p[1] == '.'
22433 && (p[2] == NUL
22434 || vim_ispathsep(p[2])
22435 || (p[2] == '.'
22436 && (p[3] == NUL || vim_ispathsep(p[3])))))
22437 break;
22440 /* FullName_save() is slow, don't use it when not needed. */
22441 if (*p != NUL || !vim_isAbsName(*fnamep))
22443 *fnamep = FullName_save(*fnamep, *p != NUL);
22444 vim_free(*bufp); /* free any allocated file name */
22445 *bufp = *fnamep;
22446 if (*fnamep == NULL)
22447 return -1;
22450 /* Append a path separator to a directory. */
22451 if (mch_isdir(*fnamep))
22453 /* Make room for one or two extra characters. */
22454 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
22455 vim_free(*bufp); /* free any allocated file name */
22456 *bufp = *fnamep;
22457 if (*fnamep == NULL)
22458 return -1;
22459 add_pathsep(*fnamep);
22463 /* ":." - path relative to the current directory */
22464 /* ":~" - path relative to the home directory */
22465 /* ":8" - shortname path - postponed till after */
22466 while (src[*usedlen] == ':'
22467 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
22469 *usedlen += 2;
22470 if (c == '8')
22472 #ifdef WIN3264
22473 has_shortname = 1; /* Postpone this. */
22474 #endif
22475 continue;
22477 pbuf = NULL;
22478 /* Need full path first (use expand_env() to remove a "~/") */
22479 if (!has_fullname)
22481 if (c == '.' && **fnamep == '~')
22482 p = pbuf = expand_env_save(*fnamep);
22483 else
22484 p = pbuf = FullName_save(*fnamep, FALSE);
22486 else
22487 p = *fnamep;
22489 has_fullname = 0;
22491 if (p != NULL)
22493 if (c == '.')
22495 mch_dirname(dirname, MAXPATHL);
22496 s = shorten_fname(p, dirname);
22497 if (s != NULL)
22499 *fnamep = s;
22500 if (pbuf != NULL)
22502 vim_free(*bufp); /* free any allocated file name */
22503 *bufp = pbuf;
22504 pbuf = NULL;
22508 else
22510 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
22511 /* Only replace it when it starts with '~' */
22512 if (*dirname == '~')
22514 s = vim_strsave(dirname);
22515 if (s != NULL)
22517 *fnamep = s;
22518 vim_free(*bufp);
22519 *bufp = s;
22523 vim_free(pbuf);
22527 tail = gettail(*fnamep);
22528 *fnamelen = (int)STRLEN(*fnamep);
22530 /* ":h" - head, remove "/file_name", can be repeated */
22531 /* Don't remove the first "/" or "c:\" */
22532 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
22534 valid |= VALID_HEAD;
22535 *usedlen += 2;
22536 s = get_past_head(*fnamep);
22537 while (tail > s && after_pathsep(s, tail))
22538 mb_ptr_back(*fnamep, tail);
22539 *fnamelen = (int)(tail - *fnamep);
22540 #ifdef VMS
22541 if (*fnamelen > 0)
22542 *fnamelen += 1; /* the path separator is part of the path */
22543 #endif
22544 if (*fnamelen == 0)
22546 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
22547 p = vim_strsave((char_u *)".");
22548 if (p == NULL)
22549 return -1;
22550 vim_free(*bufp);
22551 *bufp = *fnamep = tail = p;
22552 *fnamelen = 1;
22554 else
22556 while (tail > s && !after_pathsep(s, tail))
22557 mb_ptr_back(*fnamep, tail);
22561 /* ":8" - shortname */
22562 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
22564 *usedlen += 2;
22565 #ifdef WIN3264
22566 has_shortname = 1;
22567 #endif
22570 #ifdef WIN3264
22571 /* Check shortname after we have done 'heads' and before we do 'tails'
22573 if (has_shortname)
22575 pbuf = NULL;
22576 /* Copy the string if it is shortened by :h */
22577 if (*fnamelen < (int)STRLEN(*fnamep))
22579 p = vim_strnsave(*fnamep, *fnamelen);
22580 if (p == 0)
22581 return -1;
22582 vim_free(*bufp);
22583 *bufp = *fnamep = p;
22586 /* Split into two implementations - makes it easier. First is where
22587 * there isn't a full name already, second is where there is.
22589 if (!has_fullname && !vim_isAbsName(*fnamep))
22591 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
22592 return -1;
22594 else
22596 int l;
22598 /* Simple case, already have the full-name
22599 * Nearly always shorter, so try first time. */
22600 l = *fnamelen;
22601 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
22602 return -1;
22604 if (l == 0)
22606 /* Couldn't find the filename.. search the paths.
22608 l = *fnamelen;
22609 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
22610 return -1;
22612 *fnamelen = l;
22615 #endif /* WIN3264 */
22617 /* ":t" - tail, just the basename */
22618 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
22620 *usedlen += 2;
22621 *fnamelen -= (int)(tail - *fnamep);
22622 *fnamep = tail;
22625 /* ":e" - extension, can be repeated */
22626 /* ":r" - root, without extension, can be repeated */
22627 while (src[*usedlen] == ':'
22628 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
22630 /* find a '.' in the tail:
22631 * - for second :e: before the current fname
22632 * - otherwise: The last '.'
22634 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
22635 s = *fnamep - 2;
22636 else
22637 s = *fnamep + *fnamelen - 1;
22638 for ( ; s > tail; --s)
22639 if (s[0] == '.')
22640 break;
22641 if (src[*usedlen + 1] == 'e') /* :e */
22643 if (s > tail)
22645 *fnamelen += (int)(*fnamep - (s + 1));
22646 *fnamep = s + 1;
22647 #ifdef VMS
22648 /* cut version from the extension */
22649 s = *fnamep + *fnamelen - 1;
22650 for ( ; s > *fnamep; --s)
22651 if (s[0] == ';')
22652 break;
22653 if (s > *fnamep)
22654 *fnamelen = s - *fnamep;
22655 #endif
22657 else if (*fnamep <= tail)
22658 *fnamelen = 0;
22660 else /* :r */
22662 if (s > tail) /* remove one extension */
22663 *fnamelen = (int)(s - *fnamep);
22665 *usedlen += 2;
22668 /* ":s?pat?foo?" - substitute */
22669 /* ":gs?pat?foo?" - global substitute */
22670 if (src[*usedlen] == ':'
22671 && (src[*usedlen + 1] == 's'
22672 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
22674 char_u *str;
22675 char_u *pat;
22676 char_u *sub;
22677 int sep;
22678 char_u *flags;
22679 int didit = FALSE;
22681 flags = (char_u *)"";
22682 s = src + *usedlen + 2;
22683 if (src[*usedlen + 1] == 'g')
22685 flags = (char_u *)"g";
22686 ++s;
22689 sep = *s++;
22690 if (sep)
22692 /* find end of pattern */
22693 p = vim_strchr(s, sep);
22694 if (p != NULL)
22696 pat = vim_strnsave(s, (int)(p - s));
22697 if (pat != NULL)
22699 s = p + 1;
22700 /* find end of substitution */
22701 p = vim_strchr(s, sep);
22702 if (p != NULL)
22704 sub = vim_strnsave(s, (int)(p - s));
22705 str = vim_strnsave(*fnamep, *fnamelen);
22706 if (sub != NULL && str != NULL)
22708 *usedlen = (int)(p + 1 - src);
22709 s = do_string_sub(str, pat, sub, flags);
22710 if (s != NULL)
22712 *fnamep = s;
22713 *fnamelen = (int)STRLEN(s);
22714 vim_free(*bufp);
22715 *bufp = s;
22716 didit = TRUE;
22719 vim_free(sub);
22720 vim_free(str);
22722 vim_free(pat);
22725 /* after using ":s", repeat all the modifiers */
22726 if (didit)
22727 goto repeat;
22731 return valid;
22735 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
22736 * "flags" can be "g" to do a global substitute.
22737 * Returns an allocated string, NULL for error.
22739 char_u *
22740 do_string_sub(str, pat, sub, flags)
22741 char_u *str;
22742 char_u *pat;
22743 char_u *sub;
22744 char_u *flags;
22746 int sublen;
22747 regmatch_T regmatch;
22748 int i;
22749 int do_all;
22750 char_u *tail;
22751 garray_T ga;
22752 char_u *ret;
22753 char_u *save_cpo;
22755 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
22756 save_cpo = p_cpo;
22757 p_cpo = empty_option;
22759 ga_init2(&ga, 1, 200);
22761 do_all = (flags[0] == 'g');
22763 regmatch.rm_ic = p_ic;
22764 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
22765 if (regmatch.regprog != NULL)
22767 tail = str;
22768 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
22771 * Get some space for a temporary buffer to do the substitution
22772 * into. It will contain:
22773 * - The text up to where the match is.
22774 * - The substituted text.
22775 * - The text after the match.
22777 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
22778 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
22779 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
22781 ga_clear(&ga);
22782 break;
22785 /* copy the text up to where the match is */
22786 i = (int)(regmatch.startp[0] - tail);
22787 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
22788 /* add the substituted text */
22789 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
22790 + ga.ga_len + i, TRUE, TRUE, FALSE);
22791 ga.ga_len += i + sublen - 1;
22792 /* avoid getting stuck on a match with an empty string */
22793 if (tail == regmatch.endp[0])
22795 if (*tail == NUL)
22796 break;
22797 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
22798 ++ga.ga_len;
22800 else
22802 tail = regmatch.endp[0];
22803 if (*tail == NUL)
22804 break;
22806 if (!do_all)
22807 break;
22810 if (ga.ga_data != NULL)
22811 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
22813 vim_free(regmatch.regprog);
22816 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
22817 ga_clear(&ga);
22818 if (p_cpo == empty_option)
22819 p_cpo = save_cpo;
22820 else
22821 /* Darn, evaluating {sub} expression changed the value. */
22822 free_string_option(save_cpo);
22824 return ret;
22827 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */