Merge branch 'vim-with-runtime' into feat/var-tabstops
[vim_extended.git] / src / eval.c
blob8634cc2508e50b77dd234f8a7687d193b2f89d11
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_VARTABS
11814 "vartabs",
11815 #endif
11816 #ifdef FEAT_VERTSPLIT
11817 "vertsplit",
11818 #endif
11819 #ifdef FEAT_VIRTUALEDIT
11820 "virtualedit",
11821 #endif
11822 #ifdef FEAT_VISUAL
11823 "visual",
11824 #endif
11825 #ifdef FEAT_VISUALEXTRA
11826 "visualextra",
11827 #endif
11828 #ifdef FEAT_VREPLACE
11829 "vreplace",
11830 #endif
11831 #ifdef FEAT_WILDIGN
11832 "wildignore",
11833 #endif
11834 #ifdef FEAT_WILDMENU
11835 "wildmenu",
11836 #endif
11837 #ifdef FEAT_WINDOWS
11838 "windows",
11839 #endif
11840 #ifdef FEAT_WAK
11841 "winaltkeys",
11842 #endif
11843 #ifdef FEAT_WRITEBACKUP
11844 "writebackup",
11845 #endif
11846 #ifdef FEAT_XIM
11847 "xim",
11848 #endif
11849 #ifdef FEAT_XFONTSET
11850 "xfontset",
11851 #endif
11852 #ifdef USE_XSMP
11853 "xsmp",
11854 #endif
11855 #ifdef USE_XSMP_INTERACT
11856 "xsmp_interact",
11857 #endif
11858 #ifdef FEAT_XCLIPBOARD
11859 "xterm_clipboard",
11860 #endif
11861 #ifdef FEAT_XTERM_SAVE
11862 "xterm_save",
11863 #endif
11864 #if defined(UNIX) && defined(FEAT_X11)
11865 "X11",
11866 #endif
11867 NULL
11870 name = get_tv_string(&argvars[0]);
11871 for (i = 0; has_list[i] != NULL; ++i)
11872 if (STRICMP(name, has_list[i]) == 0)
11874 n = TRUE;
11875 break;
11878 if (n == FALSE)
11880 if (STRNICMP(name, "patch", 5) == 0)
11881 n = has_patch(atoi((char *)name + 5));
11882 else if (STRICMP(name, "vim_starting") == 0)
11883 n = (starting != 0);
11884 #ifdef FEAT_MBYTE
11885 else if (STRICMP(name, "multi_byte_encoding") == 0)
11886 n = has_mbyte;
11887 #endif
11888 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
11889 else if (STRICMP(name, "balloon_multiline") == 0)
11890 n = multiline_balloon_available();
11891 #endif
11892 #ifdef DYNAMIC_TCL
11893 else if (STRICMP(name, "tcl") == 0)
11894 n = tcl_enabled(FALSE);
11895 #endif
11896 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
11897 else if (STRICMP(name, "iconv") == 0)
11898 n = iconv_enabled(FALSE);
11899 #endif
11900 #ifdef DYNAMIC_MZSCHEME
11901 else if (STRICMP(name, "mzscheme") == 0)
11902 n = mzscheme_enabled(FALSE);
11903 #endif
11904 #ifdef DYNAMIC_RUBY
11905 else if (STRICMP(name, "ruby") == 0)
11906 n = ruby_enabled(FALSE);
11907 #endif
11908 #ifdef DYNAMIC_PYTHON
11909 else if (STRICMP(name, "python") == 0)
11910 n = python_enabled(FALSE);
11911 #endif
11912 #ifdef DYNAMIC_PERL
11913 else if (STRICMP(name, "perl") == 0)
11914 n = perl_enabled(FALSE);
11915 #endif
11916 #ifdef FEAT_GUI
11917 else if (STRICMP(name, "gui_running") == 0)
11918 n = (gui.in_use || gui.starting);
11919 # ifdef FEAT_GUI_W32
11920 else if (STRICMP(name, "gui_win32s") == 0)
11921 n = gui_is_win32s();
11922 # endif
11923 # ifdef FEAT_BROWSE
11924 else if (STRICMP(name, "browse") == 0)
11925 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
11926 # endif
11927 #endif
11928 #ifdef FEAT_SYN_HL
11929 else if (STRICMP(name, "syntax_items") == 0)
11930 n = syntax_present(curbuf);
11931 #endif
11932 #if defined(WIN3264)
11933 else if (STRICMP(name, "win95") == 0)
11934 n = mch_windows95();
11935 #endif
11936 #ifdef FEAT_NETBEANS_INTG
11937 else if (STRICMP(name, "netbeans_enabled") == 0)
11938 n = usingNetbeans;
11939 #endif
11942 rettv->vval.v_number = n;
11946 * "has_key()" function
11948 static void
11949 f_has_key(argvars, rettv)
11950 typval_T *argvars;
11951 typval_T *rettv;
11953 if (argvars[0].v_type != VAR_DICT)
11955 EMSG(_(e_dictreq));
11956 return;
11958 if (argvars[0].vval.v_dict == NULL)
11959 return;
11961 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
11962 get_tv_string(&argvars[1]), -1) != NULL;
11966 * "haslocaldir()" function
11968 static void
11969 f_haslocaldir(argvars, rettv)
11970 typval_T *argvars UNUSED;
11971 typval_T *rettv;
11973 rettv->vval.v_number = (curwin->w_localdir != NULL);
11977 * "hasmapto()" function
11979 static void
11980 f_hasmapto(argvars, rettv)
11981 typval_T *argvars;
11982 typval_T *rettv;
11984 char_u *name;
11985 char_u *mode;
11986 char_u buf[NUMBUFLEN];
11987 int abbr = FALSE;
11989 name = get_tv_string(&argvars[0]);
11990 if (argvars[1].v_type == VAR_UNKNOWN)
11991 mode = (char_u *)"nvo";
11992 else
11994 mode = get_tv_string_buf(&argvars[1], buf);
11995 if (argvars[2].v_type != VAR_UNKNOWN)
11996 abbr = get_tv_number(&argvars[2]);
11999 if (map_to_exists(name, mode, abbr))
12000 rettv->vval.v_number = TRUE;
12001 else
12002 rettv->vval.v_number = FALSE;
12006 * "histadd()" function
12008 static void
12009 f_histadd(argvars, rettv)
12010 typval_T *argvars UNUSED;
12011 typval_T *rettv;
12013 #ifdef FEAT_CMDHIST
12014 int histype;
12015 char_u *str;
12016 char_u buf[NUMBUFLEN];
12017 #endif
12019 rettv->vval.v_number = FALSE;
12020 if (check_restricted() || check_secure())
12021 return;
12022 #ifdef FEAT_CMDHIST
12023 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12024 histype = str != NULL ? get_histtype(str) : -1;
12025 if (histype >= 0)
12027 str = get_tv_string_buf(&argvars[1], buf);
12028 if (*str != NUL)
12030 init_history();
12031 add_to_history(histype, str, FALSE, NUL);
12032 rettv->vval.v_number = TRUE;
12033 return;
12036 #endif
12040 * "histdel()" function
12042 static void
12043 f_histdel(argvars, rettv)
12044 typval_T *argvars UNUSED;
12045 typval_T *rettv UNUSED;
12047 #ifdef FEAT_CMDHIST
12048 int n;
12049 char_u buf[NUMBUFLEN];
12050 char_u *str;
12052 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12053 if (str == NULL)
12054 n = 0;
12055 else if (argvars[1].v_type == VAR_UNKNOWN)
12056 /* only one argument: clear entire history */
12057 n = clr_history(get_histtype(str));
12058 else if (argvars[1].v_type == VAR_NUMBER)
12059 /* index given: remove that entry */
12060 n = del_history_idx(get_histtype(str),
12061 (int)get_tv_number(&argvars[1]));
12062 else
12063 /* string given: remove all matching entries */
12064 n = del_history_entry(get_histtype(str),
12065 get_tv_string_buf(&argvars[1], buf));
12066 rettv->vval.v_number = n;
12067 #endif
12071 * "histget()" function
12073 static void
12074 f_histget(argvars, rettv)
12075 typval_T *argvars UNUSED;
12076 typval_T *rettv;
12078 #ifdef FEAT_CMDHIST
12079 int type;
12080 int idx;
12081 char_u *str;
12083 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12084 if (str == NULL)
12085 rettv->vval.v_string = NULL;
12086 else
12088 type = get_histtype(str);
12089 if (argvars[1].v_type == VAR_UNKNOWN)
12090 idx = get_history_idx(type);
12091 else
12092 idx = (int)get_tv_number_chk(&argvars[1], NULL);
12093 /* -1 on type error */
12094 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
12096 #else
12097 rettv->vval.v_string = NULL;
12098 #endif
12099 rettv->v_type = VAR_STRING;
12103 * "histnr()" function
12105 static void
12106 f_histnr(argvars, rettv)
12107 typval_T *argvars UNUSED;
12108 typval_T *rettv;
12110 int i;
12112 #ifdef FEAT_CMDHIST
12113 char_u *history = get_tv_string_chk(&argvars[0]);
12115 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
12116 if (i >= HIST_CMD && i < HIST_COUNT)
12117 i = get_history_idx(i);
12118 else
12119 #endif
12120 i = -1;
12121 rettv->vval.v_number = i;
12125 * "highlightID(name)" function
12127 static void
12128 f_hlID(argvars, rettv)
12129 typval_T *argvars;
12130 typval_T *rettv;
12132 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
12136 * "highlight_exists()" function
12138 static void
12139 f_hlexists(argvars, rettv)
12140 typval_T *argvars;
12141 typval_T *rettv;
12143 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
12147 * "hostname()" function
12149 static void
12150 f_hostname(argvars, rettv)
12151 typval_T *argvars UNUSED;
12152 typval_T *rettv;
12154 char_u hostname[256];
12156 mch_get_host_name(hostname, 256);
12157 rettv->v_type = VAR_STRING;
12158 rettv->vval.v_string = vim_strsave(hostname);
12162 * iconv() function
12164 static void
12165 f_iconv(argvars, rettv)
12166 typval_T *argvars UNUSED;
12167 typval_T *rettv;
12169 #ifdef FEAT_MBYTE
12170 char_u buf1[NUMBUFLEN];
12171 char_u buf2[NUMBUFLEN];
12172 char_u *from, *to, *str;
12173 vimconv_T vimconv;
12174 #endif
12176 rettv->v_type = VAR_STRING;
12177 rettv->vval.v_string = NULL;
12179 #ifdef FEAT_MBYTE
12180 str = get_tv_string(&argvars[0]);
12181 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
12182 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
12183 vimconv.vc_type = CONV_NONE;
12184 convert_setup(&vimconv, from, to);
12186 /* If the encodings are equal, no conversion needed. */
12187 if (vimconv.vc_type == CONV_NONE)
12188 rettv->vval.v_string = vim_strsave(str);
12189 else
12190 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
12192 convert_setup(&vimconv, NULL, NULL);
12193 vim_free(from);
12194 vim_free(to);
12195 #endif
12199 * "indent()" function
12201 static void
12202 f_indent(argvars, rettv)
12203 typval_T *argvars;
12204 typval_T *rettv;
12206 linenr_T lnum;
12208 lnum = get_tv_lnum(argvars);
12209 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12210 rettv->vval.v_number = get_indent_lnum(lnum);
12211 else
12212 rettv->vval.v_number = -1;
12216 * "index()" function
12218 static void
12219 f_index(argvars, rettv)
12220 typval_T *argvars;
12221 typval_T *rettv;
12223 list_T *l;
12224 listitem_T *item;
12225 long idx = 0;
12226 int ic = FALSE;
12228 rettv->vval.v_number = -1;
12229 if (argvars[0].v_type != VAR_LIST)
12231 EMSG(_(e_listreq));
12232 return;
12234 l = argvars[0].vval.v_list;
12235 if (l != NULL)
12237 item = l->lv_first;
12238 if (argvars[2].v_type != VAR_UNKNOWN)
12240 int error = FALSE;
12242 /* Start at specified item. Use the cached index that list_find()
12243 * sets, so that a negative number also works. */
12244 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
12245 idx = l->lv_idx;
12246 if (argvars[3].v_type != VAR_UNKNOWN)
12247 ic = get_tv_number_chk(&argvars[3], &error);
12248 if (error)
12249 item = NULL;
12252 for ( ; item != NULL; item = item->li_next, ++idx)
12253 if (tv_equal(&item->li_tv, &argvars[1], ic))
12255 rettv->vval.v_number = idx;
12256 break;
12261 static int inputsecret_flag = 0;
12263 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
12266 * This function is used by f_input() and f_inputdialog() functions. The third
12267 * argument to f_input() specifies the type of completion to use at the
12268 * prompt. The third argument to f_inputdialog() specifies the value to return
12269 * when the user cancels the prompt.
12271 static void
12272 get_user_input(argvars, rettv, inputdialog)
12273 typval_T *argvars;
12274 typval_T *rettv;
12275 int inputdialog;
12277 char_u *prompt = get_tv_string_chk(&argvars[0]);
12278 char_u *p = NULL;
12279 int c;
12280 char_u buf[NUMBUFLEN];
12281 int cmd_silent_save = cmd_silent;
12282 char_u *defstr = (char_u *)"";
12283 int xp_type = EXPAND_NOTHING;
12284 char_u *xp_arg = NULL;
12286 rettv->v_type = VAR_STRING;
12287 rettv->vval.v_string = NULL;
12289 #ifdef NO_CONSOLE_INPUT
12290 /* While starting up, there is no place to enter text. */
12291 if (no_console_input())
12292 return;
12293 #endif
12295 cmd_silent = FALSE; /* Want to see the prompt. */
12296 if (prompt != NULL)
12298 /* Only the part of the message after the last NL is considered as
12299 * prompt for the command line */
12300 p = vim_strrchr(prompt, '\n');
12301 if (p == NULL)
12302 p = prompt;
12303 else
12305 ++p;
12306 c = *p;
12307 *p = NUL;
12308 msg_start();
12309 msg_clr_eos();
12310 msg_puts_attr(prompt, echo_attr);
12311 msg_didout = FALSE;
12312 msg_starthere();
12313 *p = c;
12315 cmdline_row = msg_row;
12317 if (argvars[1].v_type != VAR_UNKNOWN)
12319 defstr = get_tv_string_buf_chk(&argvars[1], buf);
12320 if (defstr != NULL)
12321 stuffReadbuffSpec(defstr);
12323 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
12325 char_u *xp_name;
12326 int xp_namelen;
12327 long argt;
12329 rettv->vval.v_string = NULL;
12331 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
12332 if (xp_name == NULL)
12333 return;
12335 xp_namelen = (int)STRLEN(xp_name);
12337 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
12338 &xp_arg) == FAIL)
12339 return;
12343 if (defstr != NULL)
12344 rettv->vval.v_string =
12345 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
12346 xp_type, xp_arg);
12348 vim_free(xp_arg);
12350 /* since the user typed this, no need to wait for return */
12351 need_wait_return = FALSE;
12352 msg_didout = FALSE;
12354 cmd_silent = cmd_silent_save;
12358 * "input()" function
12359 * Also handles inputsecret() when inputsecret is set.
12361 static void
12362 f_input(argvars, rettv)
12363 typval_T *argvars;
12364 typval_T *rettv;
12366 get_user_input(argvars, rettv, FALSE);
12370 * "inputdialog()" function
12372 static void
12373 f_inputdialog(argvars, rettv)
12374 typval_T *argvars;
12375 typval_T *rettv;
12377 #if defined(FEAT_GUI_TEXTDIALOG)
12378 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
12379 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
12381 char_u *message;
12382 char_u buf[NUMBUFLEN];
12383 char_u *defstr = (char_u *)"";
12385 message = get_tv_string_chk(&argvars[0]);
12386 if (argvars[1].v_type != VAR_UNKNOWN
12387 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
12388 vim_strncpy(IObuff, defstr, IOSIZE - 1);
12389 else
12390 IObuff[0] = NUL;
12391 if (message != NULL && defstr != NULL
12392 && do_dialog(VIM_QUESTION, NULL, message,
12393 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
12394 rettv->vval.v_string = vim_strsave(IObuff);
12395 else
12397 if (message != NULL && defstr != NULL
12398 && argvars[1].v_type != VAR_UNKNOWN
12399 && argvars[2].v_type != VAR_UNKNOWN)
12400 rettv->vval.v_string = vim_strsave(
12401 get_tv_string_buf(&argvars[2], buf));
12402 else
12403 rettv->vval.v_string = NULL;
12405 rettv->v_type = VAR_STRING;
12407 else
12408 #endif
12409 get_user_input(argvars, rettv, TRUE);
12413 * "inputlist()" function
12415 static void
12416 f_inputlist(argvars, rettv)
12417 typval_T *argvars;
12418 typval_T *rettv;
12420 listitem_T *li;
12421 int selected;
12422 int mouse_used;
12424 #ifdef NO_CONSOLE_INPUT
12425 /* While starting up, there is no place to enter text. */
12426 if (no_console_input())
12427 return;
12428 #endif
12429 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
12431 EMSG2(_(e_listarg), "inputlist()");
12432 return;
12435 msg_start();
12436 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
12437 lines_left = Rows; /* avoid more prompt */
12438 msg_scroll = TRUE;
12439 msg_clr_eos();
12441 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
12443 msg_puts(get_tv_string(&li->li_tv));
12444 msg_putchar('\n');
12447 /* Ask for choice. */
12448 selected = prompt_for_number(&mouse_used);
12449 if (mouse_used)
12450 selected -= lines_left;
12452 rettv->vval.v_number = selected;
12456 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
12459 * "inputrestore()" function
12461 static void
12462 f_inputrestore(argvars, rettv)
12463 typval_T *argvars UNUSED;
12464 typval_T *rettv;
12466 if (ga_userinput.ga_len > 0)
12468 --ga_userinput.ga_len;
12469 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
12470 + ga_userinput.ga_len);
12471 /* default return is zero == OK */
12473 else if (p_verbose > 1)
12475 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
12476 rettv->vval.v_number = 1; /* Failed */
12481 * "inputsave()" function
12483 static void
12484 f_inputsave(argvars, rettv)
12485 typval_T *argvars UNUSED;
12486 typval_T *rettv;
12488 /* Add an entry to the stack of typeahead storage. */
12489 if (ga_grow(&ga_userinput, 1) == OK)
12491 save_typeahead((tasave_T *)(ga_userinput.ga_data)
12492 + ga_userinput.ga_len);
12493 ++ga_userinput.ga_len;
12494 /* default return is zero == OK */
12496 else
12497 rettv->vval.v_number = 1; /* Failed */
12501 * "inputsecret()" function
12503 static void
12504 f_inputsecret(argvars, rettv)
12505 typval_T *argvars;
12506 typval_T *rettv;
12508 ++cmdline_star;
12509 ++inputsecret_flag;
12510 f_input(argvars, rettv);
12511 --cmdline_star;
12512 --inputsecret_flag;
12516 * "insert()" function
12518 static void
12519 f_insert(argvars, rettv)
12520 typval_T *argvars;
12521 typval_T *rettv;
12523 long before = 0;
12524 listitem_T *item;
12525 list_T *l;
12526 int error = FALSE;
12528 if (argvars[0].v_type != VAR_LIST)
12529 EMSG2(_(e_listarg), "insert()");
12530 else if ((l = argvars[0].vval.v_list) != NULL
12531 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
12533 if (argvars[2].v_type != VAR_UNKNOWN)
12534 before = get_tv_number_chk(&argvars[2], &error);
12535 if (error)
12536 return; /* type error; errmsg already given */
12538 if (before == l->lv_len)
12539 item = NULL;
12540 else
12542 item = list_find(l, before);
12543 if (item == NULL)
12545 EMSGN(_(e_listidx), before);
12546 l = NULL;
12549 if (l != NULL)
12551 list_insert_tv(l, &argvars[1], item);
12552 copy_tv(&argvars[0], rettv);
12558 * "isdirectory()" function
12560 static void
12561 f_isdirectory(argvars, rettv)
12562 typval_T *argvars;
12563 typval_T *rettv;
12565 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
12569 * "islocked()" function
12571 static void
12572 f_islocked(argvars, rettv)
12573 typval_T *argvars;
12574 typval_T *rettv;
12576 lval_T lv;
12577 char_u *end;
12578 dictitem_T *di;
12580 rettv->vval.v_number = -1;
12581 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
12582 FNE_CHECK_START);
12583 if (end != NULL && lv.ll_name != NULL)
12585 if (*end != NUL)
12586 EMSG(_(e_trailing));
12587 else
12589 if (lv.ll_tv == NULL)
12591 if (check_changedtick(lv.ll_name))
12592 rettv->vval.v_number = 1; /* always locked */
12593 else
12595 di = find_var(lv.ll_name, NULL);
12596 if (di != NULL)
12598 /* Consider a variable locked when:
12599 * 1. the variable itself is locked
12600 * 2. the value of the variable is locked.
12601 * 3. the List or Dict value is locked.
12603 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
12604 || tv_islocked(&di->di_tv));
12608 else if (lv.ll_range)
12609 EMSG(_("E786: Range not allowed"));
12610 else if (lv.ll_newkey != NULL)
12611 EMSG2(_(e_dictkey), lv.ll_newkey);
12612 else if (lv.ll_list != NULL)
12613 /* List item. */
12614 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
12615 else
12616 /* Dictionary item. */
12617 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
12621 clear_lval(&lv);
12624 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
12627 * Turn a dict into a list:
12628 * "what" == 0: list of keys
12629 * "what" == 1: list of values
12630 * "what" == 2: list of items
12632 static void
12633 dict_list(argvars, rettv, what)
12634 typval_T *argvars;
12635 typval_T *rettv;
12636 int what;
12638 list_T *l2;
12639 dictitem_T *di;
12640 hashitem_T *hi;
12641 listitem_T *li;
12642 listitem_T *li2;
12643 dict_T *d;
12644 int todo;
12646 if (argvars[0].v_type != VAR_DICT)
12648 EMSG(_(e_dictreq));
12649 return;
12651 if ((d = argvars[0].vval.v_dict) == NULL)
12652 return;
12654 if (rettv_list_alloc(rettv) == FAIL)
12655 return;
12657 todo = (int)d->dv_hashtab.ht_used;
12658 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12660 if (!HASHITEM_EMPTY(hi))
12662 --todo;
12663 di = HI2DI(hi);
12665 li = listitem_alloc();
12666 if (li == NULL)
12667 break;
12668 list_append(rettv->vval.v_list, li);
12670 if (what == 0)
12672 /* keys() */
12673 li->li_tv.v_type = VAR_STRING;
12674 li->li_tv.v_lock = 0;
12675 li->li_tv.vval.v_string = vim_strsave(di->di_key);
12677 else if (what == 1)
12679 /* values() */
12680 copy_tv(&di->di_tv, &li->li_tv);
12682 else
12684 /* items() */
12685 l2 = list_alloc();
12686 li->li_tv.v_type = VAR_LIST;
12687 li->li_tv.v_lock = 0;
12688 li->li_tv.vval.v_list = l2;
12689 if (l2 == NULL)
12690 break;
12691 ++l2->lv_refcount;
12693 li2 = listitem_alloc();
12694 if (li2 == NULL)
12695 break;
12696 list_append(l2, li2);
12697 li2->li_tv.v_type = VAR_STRING;
12698 li2->li_tv.v_lock = 0;
12699 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12701 li2 = listitem_alloc();
12702 if (li2 == NULL)
12703 break;
12704 list_append(l2, li2);
12705 copy_tv(&di->di_tv, &li2->li_tv);
12712 * "items(dict)" function
12714 static void
12715 f_items(argvars, rettv)
12716 typval_T *argvars;
12717 typval_T *rettv;
12719 dict_list(argvars, rettv, 2);
12723 * "join()" function
12725 static void
12726 f_join(argvars, rettv)
12727 typval_T *argvars;
12728 typval_T *rettv;
12730 garray_T ga;
12731 char_u *sep;
12733 if (argvars[0].v_type != VAR_LIST)
12735 EMSG(_(e_listreq));
12736 return;
12738 if (argvars[0].vval.v_list == NULL)
12739 return;
12740 if (argvars[1].v_type == VAR_UNKNOWN)
12741 sep = (char_u *)" ";
12742 else
12743 sep = get_tv_string_chk(&argvars[1]);
12745 rettv->v_type = VAR_STRING;
12747 if (sep != NULL)
12749 ga_init2(&ga, (int)sizeof(char), 80);
12750 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12751 ga_append(&ga, NUL);
12752 rettv->vval.v_string = (char_u *)ga.ga_data;
12754 else
12755 rettv->vval.v_string = NULL;
12759 * "keys()" function
12761 static void
12762 f_keys(argvars, rettv)
12763 typval_T *argvars;
12764 typval_T *rettv;
12766 dict_list(argvars, rettv, 0);
12770 * "last_buffer_nr()" function.
12772 static void
12773 f_last_buffer_nr(argvars, rettv)
12774 typval_T *argvars UNUSED;
12775 typval_T *rettv;
12777 int n = 0;
12778 buf_T *buf;
12780 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12781 if (n < buf->b_fnum)
12782 n = buf->b_fnum;
12784 rettv->vval.v_number = n;
12788 * "len()" function
12790 static void
12791 f_len(argvars, rettv)
12792 typval_T *argvars;
12793 typval_T *rettv;
12795 switch (argvars[0].v_type)
12797 case VAR_STRING:
12798 case VAR_NUMBER:
12799 rettv->vval.v_number = (varnumber_T)STRLEN(
12800 get_tv_string(&argvars[0]));
12801 break;
12802 case VAR_LIST:
12803 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
12804 break;
12805 case VAR_DICT:
12806 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
12807 break;
12808 default:
12809 EMSG(_("E701: Invalid type for len()"));
12810 break;
12814 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
12816 static void
12817 libcall_common(argvars, rettv, type)
12818 typval_T *argvars;
12819 typval_T *rettv;
12820 int type;
12822 #ifdef FEAT_LIBCALL
12823 char_u *string_in;
12824 char_u **string_result;
12825 int nr_result;
12826 #endif
12828 rettv->v_type = type;
12829 if (type != VAR_NUMBER)
12830 rettv->vval.v_string = NULL;
12832 if (check_restricted() || check_secure())
12833 return;
12835 #ifdef FEAT_LIBCALL
12836 /* The first two args must be strings, otherwise its meaningless */
12837 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
12839 string_in = NULL;
12840 if (argvars[2].v_type == VAR_STRING)
12841 string_in = argvars[2].vval.v_string;
12842 if (type == VAR_NUMBER)
12843 string_result = NULL;
12844 else
12845 string_result = &rettv->vval.v_string;
12846 if (mch_libcall(argvars[0].vval.v_string,
12847 argvars[1].vval.v_string,
12848 string_in,
12849 argvars[2].vval.v_number,
12850 string_result,
12851 &nr_result) == OK
12852 && type == VAR_NUMBER)
12853 rettv->vval.v_number = nr_result;
12855 #endif
12859 * "libcall()" function
12861 static void
12862 f_libcall(argvars, rettv)
12863 typval_T *argvars;
12864 typval_T *rettv;
12866 libcall_common(argvars, rettv, VAR_STRING);
12870 * "libcallnr()" function
12872 static void
12873 f_libcallnr(argvars, rettv)
12874 typval_T *argvars;
12875 typval_T *rettv;
12877 libcall_common(argvars, rettv, VAR_NUMBER);
12881 * "line(string)" function
12883 static void
12884 f_line(argvars, rettv)
12885 typval_T *argvars;
12886 typval_T *rettv;
12888 linenr_T lnum = 0;
12889 pos_T *fp;
12890 int fnum;
12892 fp = var2fpos(&argvars[0], TRUE, &fnum);
12893 if (fp != NULL)
12894 lnum = fp->lnum;
12895 rettv->vval.v_number = lnum;
12899 * "line2byte(lnum)" function
12901 static void
12902 f_line2byte(argvars, rettv)
12903 typval_T *argvars UNUSED;
12904 typval_T *rettv;
12906 #ifndef FEAT_BYTEOFF
12907 rettv->vval.v_number = -1;
12908 #else
12909 linenr_T lnum;
12911 lnum = get_tv_lnum(argvars);
12912 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
12913 rettv->vval.v_number = -1;
12914 else
12915 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
12916 if (rettv->vval.v_number >= 0)
12917 ++rettv->vval.v_number;
12918 #endif
12922 * "lispindent(lnum)" function
12924 static void
12925 f_lispindent(argvars, rettv)
12926 typval_T *argvars;
12927 typval_T *rettv;
12929 #ifdef FEAT_LISP
12930 pos_T pos;
12931 linenr_T lnum;
12933 pos = curwin->w_cursor;
12934 lnum = get_tv_lnum(argvars);
12935 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12937 curwin->w_cursor.lnum = lnum;
12938 rettv->vval.v_number = get_lisp_indent();
12939 curwin->w_cursor = pos;
12941 else
12942 #endif
12943 rettv->vval.v_number = -1;
12947 * "localtime()" function
12949 static void
12950 f_localtime(argvars, rettv)
12951 typval_T *argvars UNUSED;
12952 typval_T *rettv;
12954 rettv->vval.v_number = (varnumber_T)time(NULL);
12957 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
12959 static void
12960 get_maparg(argvars, rettv, exact)
12961 typval_T *argvars;
12962 typval_T *rettv;
12963 int exact;
12965 char_u *keys;
12966 char_u *which;
12967 char_u buf[NUMBUFLEN];
12968 char_u *keys_buf = NULL;
12969 char_u *rhs;
12970 int mode;
12971 garray_T ga;
12972 int abbr = FALSE;
12974 /* return empty string for failure */
12975 rettv->v_type = VAR_STRING;
12976 rettv->vval.v_string = NULL;
12978 keys = get_tv_string(&argvars[0]);
12979 if (*keys == NUL)
12980 return;
12982 if (argvars[1].v_type != VAR_UNKNOWN)
12984 which = get_tv_string_buf_chk(&argvars[1], buf);
12985 if (argvars[2].v_type != VAR_UNKNOWN)
12986 abbr = get_tv_number(&argvars[2]);
12988 else
12989 which = (char_u *)"";
12990 if (which == NULL)
12991 return;
12993 mode = get_map_mode(&which, 0);
12995 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
12996 rhs = check_map(keys, mode, exact, FALSE, abbr);
12997 vim_free(keys_buf);
12998 if (rhs != NULL)
13000 ga_init(&ga);
13001 ga.ga_itemsize = 1;
13002 ga.ga_growsize = 40;
13004 while (*rhs != NUL)
13005 ga_concat(&ga, str2special(&rhs, FALSE));
13007 ga_append(&ga, NUL);
13008 rettv->vval.v_string = (char_u *)ga.ga_data;
13012 #ifdef FEAT_FLOAT
13014 * "log10()" function
13016 static void
13017 f_log10(argvars, rettv)
13018 typval_T *argvars;
13019 typval_T *rettv;
13021 float_T f;
13023 rettv->v_type = VAR_FLOAT;
13024 if (get_float_arg(argvars, &f) == OK)
13025 rettv->vval.v_float = log10(f);
13026 else
13027 rettv->vval.v_float = 0.0;
13029 #endif
13032 * "map()" function
13034 static void
13035 f_map(argvars, rettv)
13036 typval_T *argvars;
13037 typval_T *rettv;
13039 filter_map(argvars, rettv, TRUE);
13043 * "maparg()" function
13045 static void
13046 f_maparg(argvars, rettv)
13047 typval_T *argvars;
13048 typval_T *rettv;
13050 get_maparg(argvars, rettv, TRUE);
13054 * "mapcheck()" function
13056 static void
13057 f_mapcheck(argvars, rettv)
13058 typval_T *argvars;
13059 typval_T *rettv;
13061 get_maparg(argvars, rettv, FALSE);
13064 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
13066 static void
13067 find_some_match(argvars, rettv, type)
13068 typval_T *argvars;
13069 typval_T *rettv;
13070 int type;
13072 char_u *str = NULL;
13073 char_u *expr = NULL;
13074 char_u *pat;
13075 regmatch_T regmatch;
13076 char_u patbuf[NUMBUFLEN];
13077 char_u strbuf[NUMBUFLEN];
13078 char_u *save_cpo;
13079 long start = 0;
13080 long nth = 1;
13081 colnr_T startcol = 0;
13082 int match = 0;
13083 list_T *l = NULL;
13084 listitem_T *li = NULL;
13085 long idx = 0;
13086 char_u *tofree = NULL;
13088 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
13089 save_cpo = p_cpo;
13090 p_cpo = (char_u *)"";
13092 rettv->vval.v_number = -1;
13093 if (type == 3)
13095 /* return empty list when there are no matches */
13096 if (rettv_list_alloc(rettv) == FAIL)
13097 goto theend;
13099 else if (type == 2)
13101 rettv->v_type = VAR_STRING;
13102 rettv->vval.v_string = NULL;
13105 if (argvars[0].v_type == VAR_LIST)
13107 if ((l = argvars[0].vval.v_list) == NULL)
13108 goto theend;
13109 li = l->lv_first;
13111 else
13112 expr = str = get_tv_string(&argvars[0]);
13114 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
13115 if (pat == NULL)
13116 goto theend;
13118 if (argvars[2].v_type != VAR_UNKNOWN)
13120 int error = FALSE;
13122 start = get_tv_number_chk(&argvars[2], &error);
13123 if (error)
13124 goto theend;
13125 if (l != NULL)
13127 li = list_find(l, start);
13128 if (li == NULL)
13129 goto theend;
13130 idx = l->lv_idx; /* use the cached index */
13132 else
13134 if (start < 0)
13135 start = 0;
13136 if (start > (long)STRLEN(str))
13137 goto theend;
13138 /* When "count" argument is there ignore matches before "start",
13139 * otherwise skip part of the string. Differs when pattern is "^"
13140 * or "\<". */
13141 if (argvars[3].v_type != VAR_UNKNOWN)
13142 startcol = start;
13143 else
13144 str += start;
13147 if (argvars[3].v_type != VAR_UNKNOWN)
13148 nth = get_tv_number_chk(&argvars[3], &error);
13149 if (error)
13150 goto theend;
13153 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
13154 if (regmatch.regprog != NULL)
13156 regmatch.rm_ic = p_ic;
13158 for (;;)
13160 if (l != NULL)
13162 if (li == NULL)
13164 match = FALSE;
13165 break;
13167 vim_free(tofree);
13168 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
13169 if (str == NULL)
13170 break;
13173 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
13175 if (match && --nth <= 0)
13176 break;
13177 if (l == NULL && !match)
13178 break;
13180 /* Advance to just after the match. */
13181 if (l != NULL)
13183 li = li->li_next;
13184 ++idx;
13186 else
13188 #ifdef FEAT_MBYTE
13189 startcol = (colnr_T)(regmatch.startp[0]
13190 + (*mb_ptr2len)(regmatch.startp[0]) - str);
13191 #else
13192 startcol = regmatch.startp[0] + 1 - str;
13193 #endif
13197 if (match)
13199 if (type == 3)
13201 int i;
13203 /* return list with matched string and submatches */
13204 for (i = 0; i < NSUBEXP; ++i)
13206 if (regmatch.endp[i] == NULL)
13208 if (list_append_string(rettv->vval.v_list,
13209 (char_u *)"", 0) == FAIL)
13210 break;
13212 else if (list_append_string(rettv->vval.v_list,
13213 regmatch.startp[i],
13214 (int)(regmatch.endp[i] - regmatch.startp[i]))
13215 == FAIL)
13216 break;
13219 else if (type == 2)
13221 /* return matched string */
13222 if (l != NULL)
13223 copy_tv(&li->li_tv, rettv);
13224 else
13225 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
13226 (int)(regmatch.endp[0] - regmatch.startp[0]));
13228 else if (l != NULL)
13229 rettv->vval.v_number = idx;
13230 else
13232 if (type != 0)
13233 rettv->vval.v_number =
13234 (varnumber_T)(regmatch.startp[0] - str);
13235 else
13236 rettv->vval.v_number =
13237 (varnumber_T)(regmatch.endp[0] - str);
13238 rettv->vval.v_number += (varnumber_T)(str - expr);
13241 vim_free(regmatch.regprog);
13244 theend:
13245 vim_free(tofree);
13246 p_cpo = save_cpo;
13250 * "match()" function
13252 static void
13253 f_match(argvars, rettv)
13254 typval_T *argvars;
13255 typval_T *rettv;
13257 find_some_match(argvars, rettv, 1);
13261 * "matchadd()" function
13263 static void
13264 f_matchadd(argvars, rettv)
13265 typval_T *argvars;
13266 typval_T *rettv;
13268 #ifdef FEAT_SEARCH_EXTRA
13269 char_u buf[NUMBUFLEN];
13270 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
13271 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
13272 int prio = 10; /* default priority */
13273 int id = -1;
13274 int error = FALSE;
13276 rettv->vval.v_number = -1;
13278 if (grp == NULL || pat == NULL)
13279 return;
13280 if (argvars[2].v_type != VAR_UNKNOWN)
13282 prio = get_tv_number_chk(&argvars[2], &error);
13283 if (argvars[3].v_type != VAR_UNKNOWN)
13284 id = get_tv_number_chk(&argvars[3], &error);
13286 if (error == TRUE)
13287 return;
13288 if (id >= 1 && id <= 3)
13290 EMSGN("E798: ID is reserved for \":match\": %ld", id);
13291 return;
13294 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
13295 #endif
13299 * "matcharg()" function
13301 static void
13302 f_matcharg(argvars, rettv)
13303 typval_T *argvars;
13304 typval_T *rettv;
13306 if (rettv_list_alloc(rettv) == OK)
13308 #ifdef FEAT_SEARCH_EXTRA
13309 int id = get_tv_number(&argvars[0]);
13310 matchitem_T *m;
13312 if (id >= 1 && id <= 3)
13314 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
13316 list_append_string(rettv->vval.v_list,
13317 syn_id2name(m->hlg_id), -1);
13318 list_append_string(rettv->vval.v_list, m->pattern, -1);
13320 else
13322 list_append_string(rettv->vval.v_list, NUL, -1);
13323 list_append_string(rettv->vval.v_list, NUL, -1);
13326 #endif
13331 * "matchdelete()" function
13333 static void
13334 f_matchdelete(argvars, rettv)
13335 typval_T *argvars;
13336 typval_T *rettv;
13338 #ifdef FEAT_SEARCH_EXTRA
13339 rettv->vval.v_number = match_delete(curwin,
13340 (int)get_tv_number(&argvars[0]), TRUE);
13341 #endif
13345 * "matchend()" function
13347 static void
13348 f_matchend(argvars, rettv)
13349 typval_T *argvars;
13350 typval_T *rettv;
13352 find_some_match(argvars, rettv, 0);
13356 * "matchlist()" function
13358 static void
13359 f_matchlist(argvars, rettv)
13360 typval_T *argvars;
13361 typval_T *rettv;
13363 find_some_match(argvars, rettv, 3);
13367 * "matchstr()" function
13369 static void
13370 f_matchstr(argvars, rettv)
13371 typval_T *argvars;
13372 typval_T *rettv;
13374 find_some_match(argvars, rettv, 2);
13377 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
13379 static void
13380 max_min(argvars, rettv, domax)
13381 typval_T *argvars;
13382 typval_T *rettv;
13383 int domax;
13385 long n = 0;
13386 long i;
13387 int error = FALSE;
13389 if (argvars[0].v_type == VAR_LIST)
13391 list_T *l;
13392 listitem_T *li;
13394 l = argvars[0].vval.v_list;
13395 if (l != NULL)
13397 li = l->lv_first;
13398 if (li != NULL)
13400 n = get_tv_number_chk(&li->li_tv, &error);
13401 for (;;)
13403 li = li->li_next;
13404 if (li == NULL)
13405 break;
13406 i = get_tv_number_chk(&li->li_tv, &error);
13407 if (domax ? i > n : i < n)
13408 n = i;
13413 else if (argvars[0].v_type == VAR_DICT)
13415 dict_T *d;
13416 int first = TRUE;
13417 hashitem_T *hi;
13418 int todo;
13420 d = argvars[0].vval.v_dict;
13421 if (d != NULL)
13423 todo = (int)d->dv_hashtab.ht_used;
13424 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13426 if (!HASHITEM_EMPTY(hi))
13428 --todo;
13429 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
13430 if (first)
13432 n = i;
13433 first = FALSE;
13435 else if (domax ? i > n : i < n)
13436 n = i;
13441 else
13442 EMSG(_(e_listdictarg));
13443 rettv->vval.v_number = error ? 0 : n;
13447 * "max()" function
13449 static void
13450 f_max(argvars, rettv)
13451 typval_T *argvars;
13452 typval_T *rettv;
13454 max_min(argvars, rettv, TRUE);
13458 * "min()" function
13460 static void
13461 f_min(argvars, rettv)
13462 typval_T *argvars;
13463 typval_T *rettv;
13465 max_min(argvars, rettv, FALSE);
13468 static int mkdir_recurse __ARGS((char_u *dir, int prot));
13471 * Create the directory in which "dir" is located, and higher levels when
13472 * needed.
13474 static int
13475 mkdir_recurse(dir, prot)
13476 char_u *dir;
13477 int prot;
13479 char_u *p;
13480 char_u *updir;
13481 int r = FAIL;
13483 /* Get end of directory name in "dir".
13484 * We're done when it's "/" or "c:/". */
13485 p = gettail_sep(dir);
13486 if (p <= get_past_head(dir))
13487 return OK;
13489 /* If the directory exists we're done. Otherwise: create it.*/
13490 updir = vim_strnsave(dir, (int)(p - dir));
13491 if (updir == NULL)
13492 return FAIL;
13493 if (mch_isdir(updir))
13494 r = OK;
13495 else if (mkdir_recurse(updir, prot) == OK)
13496 r = vim_mkdir_emsg(updir, prot);
13497 vim_free(updir);
13498 return r;
13501 #ifdef vim_mkdir
13503 * "mkdir()" function
13505 static void
13506 f_mkdir(argvars, rettv)
13507 typval_T *argvars;
13508 typval_T *rettv;
13510 char_u *dir;
13511 char_u buf[NUMBUFLEN];
13512 int prot = 0755;
13514 rettv->vval.v_number = FAIL;
13515 if (check_restricted() || check_secure())
13516 return;
13518 dir = get_tv_string_buf(&argvars[0], buf);
13519 if (argvars[1].v_type != VAR_UNKNOWN)
13521 if (argvars[2].v_type != VAR_UNKNOWN)
13522 prot = get_tv_number_chk(&argvars[2], NULL);
13523 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
13524 mkdir_recurse(dir, prot);
13526 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
13528 #endif
13531 * "mode()" function
13533 static void
13534 f_mode(argvars, rettv)
13535 typval_T *argvars;
13536 typval_T *rettv;
13538 char_u buf[3];
13540 buf[1] = NUL;
13541 buf[2] = NUL;
13543 #ifdef FEAT_VISUAL
13544 if (VIsual_active)
13546 if (VIsual_select)
13547 buf[0] = VIsual_mode + 's' - 'v';
13548 else
13549 buf[0] = VIsual_mode;
13551 else
13552 #endif
13553 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
13554 || State == CONFIRM)
13556 buf[0] = 'r';
13557 if (State == ASKMORE)
13558 buf[1] = 'm';
13559 else if (State == CONFIRM)
13560 buf[1] = '?';
13562 else if (State == EXTERNCMD)
13563 buf[0] = '!';
13564 else if (State & INSERT)
13566 #ifdef FEAT_VREPLACE
13567 if (State & VREPLACE_FLAG)
13569 buf[0] = 'R';
13570 buf[1] = 'v';
13572 else
13573 #endif
13574 if (State & REPLACE_FLAG)
13575 buf[0] = 'R';
13576 else
13577 buf[0] = 'i';
13579 else if (State & CMDLINE)
13581 buf[0] = 'c';
13582 if (exmode_active)
13583 buf[1] = 'v';
13585 else if (exmode_active)
13587 buf[0] = 'c';
13588 buf[1] = 'e';
13590 else
13592 buf[0] = 'n';
13593 if (finish_op)
13594 buf[1] = 'o';
13597 /* Clear out the minor mode when the argument is not a non-zero number or
13598 * non-empty string. */
13599 if (!non_zero_arg(&argvars[0]))
13600 buf[1] = NUL;
13602 rettv->vval.v_string = vim_strsave(buf);
13603 rettv->v_type = VAR_STRING;
13606 #ifdef FEAT_MZSCHEME
13608 * "mzeval()" function
13610 static void
13611 f_mzeval(argvars, rettv)
13612 typval_T *argvars;
13613 typval_T *rettv;
13615 char_u *str;
13616 char_u buf[NUMBUFLEN];
13618 str = get_tv_string_buf(&argvars[0], buf);
13619 do_mzeval(str, rettv);
13621 #endif
13624 * "nextnonblank()" function
13626 static void
13627 f_nextnonblank(argvars, rettv)
13628 typval_T *argvars;
13629 typval_T *rettv;
13631 linenr_T lnum;
13633 for (lnum = get_tv_lnum(argvars); ; ++lnum)
13635 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
13637 lnum = 0;
13638 break;
13640 if (*skipwhite(ml_get(lnum)) != NUL)
13641 break;
13643 rettv->vval.v_number = lnum;
13647 * "nr2char()" function
13649 static void
13650 f_nr2char(argvars, rettv)
13651 typval_T *argvars;
13652 typval_T *rettv;
13654 char_u buf[NUMBUFLEN];
13656 #ifdef FEAT_MBYTE
13657 if (has_mbyte)
13658 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
13659 else
13660 #endif
13662 buf[0] = (char_u)get_tv_number(&argvars[0]);
13663 buf[1] = NUL;
13665 rettv->v_type = VAR_STRING;
13666 rettv->vval.v_string = vim_strsave(buf);
13670 * "pathshorten()" function
13672 static void
13673 f_pathshorten(argvars, rettv)
13674 typval_T *argvars;
13675 typval_T *rettv;
13677 char_u *p;
13679 rettv->v_type = VAR_STRING;
13680 p = get_tv_string_chk(&argvars[0]);
13681 if (p == NULL)
13682 rettv->vval.v_string = NULL;
13683 else
13685 p = vim_strsave(p);
13686 rettv->vval.v_string = p;
13687 if (p != NULL)
13688 shorten_dir(p);
13692 #ifdef FEAT_FLOAT
13694 * "pow()" function
13696 static void
13697 f_pow(argvars, rettv)
13698 typval_T *argvars;
13699 typval_T *rettv;
13701 float_T fx, fy;
13703 rettv->v_type = VAR_FLOAT;
13704 if (get_float_arg(argvars, &fx) == OK
13705 && get_float_arg(&argvars[1], &fy) == OK)
13706 rettv->vval.v_float = pow(fx, fy);
13707 else
13708 rettv->vval.v_float = 0.0;
13710 #endif
13713 * "prevnonblank()" function
13715 static void
13716 f_prevnonblank(argvars, rettv)
13717 typval_T *argvars;
13718 typval_T *rettv;
13720 linenr_T lnum;
13722 lnum = get_tv_lnum(argvars);
13723 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
13724 lnum = 0;
13725 else
13726 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
13727 --lnum;
13728 rettv->vval.v_number = lnum;
13731 #ifdef HAVE_STDARG_H
13732 /* This dummy va_list is here because:
13733 * - passing a NULL pointer doesn't work when va_list isn't a pointer
13734 * - locally in the function results in a "used before set" warning
13735 * - using va_start() to initialize it gives "function with fixed args" error */
13736 static va_list ap;
13737 #endif
13740 * "printf()" function
13742 static void
13743 f_printf(argvars, rettv)
13744 typval_T *argvars;
13745 typval_T *rettv;
13747 rettv->v_type = VAR_STRING;
13748 rettv->vval.v_string = NULL;
13749 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
13751 char_u buf[NUMBUFLEN];
13752 int len;
13753 char_u *s;
13754 int saved_did_emsg = did_emsg;
13755 char *fmt;
13757 /* Get the required length, allocate the buffer and do it for real. */
13758 did_emsg = FALSE;
13759 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
13760 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
13761 if (!did_emsg)
13763 s = alloc(len + 1);
13764 if (s != NULL)
13766 rettv->vval.v_string = s;
13767 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
13770 did_emsg |= saved_did_emsg;
13772 #endif
13776 * "pumvisible()" function
13778 static void
13779 f_pumvisible(argvars, rettv)
13780 typval_T *argvars UNUSED;
13781 typval_T *rettv UNUSED;
13783 #ifdef FEAT_INS_EXPAND
13784 if (pum_visible())
13785 rettv->vval.v_number = 1;
13786 #endif
13790 * "range()" function
13792 static void
13793 f_range(argvars, rettv)
13794 typval_T *argvars;
13795 typval_T *rettv;
13797 long start;
13798 long end;
13799 long stride = 1;
13800 long i;
13801 int error = FALSE;
13803 start = get_tv_number_chk(&argvars[0], &error);
13804 if (argvars[1].v_type == VAR_UNKNOWN)
13806 end = start - 1;
13807 start = 0;
13809 else
13811 end = get_tv_number_chk(&argvars[1], &error);
13812 if (argvars[2].v_type != VAR_UNKNOWN)
13813 stride = get_tv_number_chk(&argvars[2], &error);
13816 if (error)
13817 return; /* type error; errmsg already given */
13818 if (stride == 0)
13819 EMSG(_("E726: Stride is zero"));
13820 else if (stride > 0 ? end + 1 < start : end - 1 > start)
13821 EMSG(_("E727: Start past end"));
13822 else
13824 if (rettv_list_alloc(rettv) == OK)
13825 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
13826 if (list_append_number(rettv->vval.v_list,
13827 (varnumber_T)i) == FAIL)
13828 break;
13833 * "readfile()" function
13835 static void
13836 f_readfile(argvars, rettv)
13837 typval_T *argvars;
13838 typval_T *rettv;
13840 int binary = FALSE;
13841 char_u *fname;
13842 FILE *fd;
13843 listitem_T *li;
13844 #define FREAD_SIZE 200 /* optimized for text lines */
13845 char_u buf[FREAD_SIZE];
13846 int readlen; /* size of last fread() */
13847 int buflen; /* nr of valid chars in buf[] */
13848 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
13849 int tolist; /* first byte in buf[] still to be put in list */
13850 int chop; /* how many CR to chop off */
13851 char_u *prev = NULL; /* previously read bytes, if any */
13852 int prevlen = 0; /* length of "prev" if not NULL */
13853 char_u *s;
13854 int len;
13855 long maxline = MAXLNUM;
13856 long cnt = 0;
13858 if (argvars[1].v_type != VAR_UNKNOWN)
13860 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
13861 binary = TRUE;
13862 if (argvars[2].v_type != VAR_UNKNOWN)
13863 maxline = get_tv_number(&argvars[2]);
13866 if (rettv_list_alloc(rettv) == FAIL)
13867 return;
13869 /* Always open the file in binary mode, library functions have a mind of
13870 * their own about CR-LF conversion. */
13871 fname = get_tv_string(&argvars[0]);
13872 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
13874 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
13875 return;
13878 filtd = 0;
13879 while (cnt < maxline || maxline < 0)
13881 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
13882 buflen = filtd + readlen;
13883 tolist = 0;
13884 for ( ; filtd < buflen || readlen <= 0; ++filtd)
13886 if (buf[filtd] == '\n' || readlen <= 0)
13888 /* Only when in binary mode add an empty list item when the
13889 * last line ends in a '\n'. */
13890 if (!binary && readlen == 0 && filtd == 0)
13891 break;
13893 /* Found end-of-line or end-of-file: add a text line to the
13894 * list. */
13895 chop = 0;
13896 if (!binary)
13897 while (filtd - chop - 1 >= tolist
13898 && buf[filtd - chop - 1] == '\r')
13899 ++chop;
13900 len = filtd - tolist - chop;
13901 if (prev == NULL)
13902 s = vim_strnsave(buf + tolist, len);
13903 else
13905 s = alloc((unsigned)(prevlen + len + 1));
13906 if (s != NULL)
13908 mch_memmove(s, prev, prevlen);
13909 vim_free(prev);
13910 prev = NULL;
13911 mch_memmove(s + prevlen, buf + tolist, len);
13912 s[prevlen + len] = NUL;
13915 tolist = filtd + 1;
13917 li = listitem_alloc();
13918 if (li == NULL)
13920 vim_free(s);
13921 break;
13923 li->li_tv.v_type = VAR_STRING;
13924 li->li_tv.v_lock = 0;
13925 li->li_tv.vval.v_string = s;
13926 list_append(rettv->vval.v_list, li);
13928 if (++cnt >= maxline && maxline >= 0)
13929 break;
13930 if (readlen <= 0)
13931 break;
13933 else if (buf[filtd] == NUL)
13934 buf[filtd] = '\n';
13936 if (readlen <= 0)
13937 break;
13939 if (tolist == 0)
13941 /* "buf" is full, need to move text to an allocated buffer */
13942 if (prev == NULL)
13944 prev = vim_strnsave(buf, buflen);
13945 prevlen = buflen;
13947 else
13949 s = alloc((unsigned)(prevlen + buflen));
13950 if (s != NULL)
13952 mch_memmove(s, prev, prevlen);
13953 mch_memmove(s + prevlen, buf, buflen);
13954 vim_free(prev);
13955 prev = s;
13956 prevlen += buflen;
13959 filtd = 0;
13961 else
13963 mch_memmove(buf, buf + tolist, buflen - tolist);
13964 filtd -= tolist;
13969 * For a negative line count use only the lines at the end of the file,
13970 * free the rest.
13972 if (maxline < 0)
13973 while (cnt > -maxline)
13975 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
13976 --cnt;
13979 vim_free(prev);
13980 fclose(fd);
13983 #if defined(FEAT_RELTIME)
13984 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
13987 * Convert a List to proftime_T.
13988 * Return FAIL when there is something wrong.
13990 static int
13991 list2proftime(arg, tm)
13992 typval_T *arg;
13993 proftime_T *tm;
13995 long n1, n2;
13996 int error = FALSE;
13998 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
13999 || arg->vval.v_list->lv_len != 2)
14000 return FAIL;
14001 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
14002 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
14003 # ifdef WIN3264
14004 tm->HighPart = n1;
14005 tm->LowPart = n2;
14006 # else
14007 tm->tv_sec = n1;
14008 tm->tv_usec = n2;
14009 # endif
14010 return error ? FAIL : OK;
14012 #endif /* FEAT_RELTIME */
14015 * "reltime()" function
14017 static void
14018 f_reltime(argvars, rettv)
14019 typval_T *argvars;
14020 typval_T *rettv;
14022 #ifdef FEAT_RELTIME
14023 proftime_T res;
14024 proftime_T start;
14026 if (argvars[0].v_type == VAR_UNKNOWN)
14028 /* No arguments: get current time. */
14029 profile_start(&res);
14031 else if (argvars[1].v_type == VAR_UNKNOWN)
14033 if (list2proftime(&argvars[0], &res) == FAIL)
14034 return;
14035 profile_end(&res);
14037 else
14039 /* Two arguments: compute the difference. */
14040 if (list2proftime(&argvars[0], &start) == FAIL
14041 || list2proftime(&argvars[1], &res) == FAIL)
14042 return;
14043 profile_sub(&res, &start);
14046 if (rettv_list_alloc(rettv) == OK)
14048 long n1, n2;
14050 # ifdef WIN3264
14051 n1 = res.HighPart;
14052 n2 = res.LowPart;
14053 # else
14054 n1 = res.tv_sec;
14055 n2 = res.tv_usec;
14056 # endif
14057 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
14058 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
14060 #endif
14064 * "reltimestr()" function
14066 static void
14067 f_reltimestr(argvars, rettv)
14068 typval_T *argvars;
14069 typval_T *rettv;
14071 #ifdef FEAT_RELTIME
14072 proftime_T tm;
14073 #endif
14075 rettv->v_type = VAR_STRING;
14076 rettv->vval.v_string = NULL;
14077 #ifdef FEAT_RELTIME
14078 if (list2proftime(&argvars[0], &tm) == OK)
14079 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
14080 #endif
14083 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
14084 static void make_connection __ARGS((void));
14085 static int check_connection __ARGS((void));
14087 static void
14088 make_connection()
14090 if (X_DISPLAY == NULL
14091 # ifdef FEAT_GUI
14092 && !gui.in_use
14093 # endif
14096 x_force_connect = TRUE;
14097 setup_term_clip();
14098 x_force_connect = FALSE;
14102 static int
14103 check_connection()
14105 make_connection();
14106 if (X_DISPLAY == NULL)
14108 EMSG(_("E240: No connection to Vim server"));
14109 return FAIL;
14111 return OK;
14113 #endif
14115 #ifdef FEAT_CLIENTSERVER
14116 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
14118 static void
14119 remote_common(argvars, rettv, expr)
14120 typval_T *argvars;
14121 typval_T *rettv;
14122 int expr;
14124 char_u *server_name;
14125 char_u *keys;
14126 char_u *r = NULL;
14127 char_u buf[NUMBUFLEN];
14128 # ifdef WIN32
14129 HWND w;
14130 # else
14131 Window w;
14132 # endif
14134 if (check_restricted() || check_secure())
14135 return;
14137 # ifdef FEAT_X11
14138 if (check_connection() == FAIL)
14139 return;
14140 # endif
14142 server_name = get_tv_string_chk(&argvars[0]);
14143 if (server_name == NULL)
14144 return; /* type error; errmsg already given */
14145 keys = get_tv_string_buf(&argvars[1], buf);
14146 # ifdef WIN32
14147 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14148 # else
14149 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
14150 < 0)
14151 # endif
14153 if (r != NULL)
14154 EMSG(r); /* sending worked but evaluation failed */
14155 else
14156 EMSG2(_("E241: Unable to send to %s"), server_name);
14157 return;
14160 rettv->vval.v_string = r;
14162 if (argvars[2].v_type != VAR_UNKNOWN)
14164 dictitem_T v;
14165 char_u str[30];
14166 char_u *idvar;
14168 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
14169 v.di_tv.v_type = VAR_STRING;
14170 v.di_tv.vval.v_string = vim_strsave(str);
14171 idvar = get_tv_string_chk(&argvars[2]);
14172 if (idvar != NULL)
14173 set_var(idvar, &v.di_tv, FALSE);
14174 vim_free(v.di_tv.vval.v_string);
14177 #endif
14180 * "remote_expr()" function
14182 static void
14183 f_remote_expr(argvars, rettv)
14184 typval_T *argvars UNUSED;
14185 typval_T *rettv;
14187 rettv->v_type = VAR_STRING;
14188 rettv->vval.v_string = NULL;
14189 #ifdef FEAT_CLIENTSERVER
14190 remote_common(argvars, rettv, TRUE);
14191 #endif
14195 * "remote_foreground()" function
14197 static void
14198 f_remote_foreground(argvars, rettv)
14199 typval_T *argvars UNUSED;
14200 typval_T *rettv UNUSED;
14202 #ifdef FEAT_CLIENTSERVER
14203 # ifdef WIN32
14204 /* On Win32 it's done in this application. */
14206 char_u *server_name = get_tv_string_chk(&argvars[0]);
14208 if (server_name != NULL)
14209 serverForeground(server_name);
14211 # else
14212 /* Send a foreground() expression to the server. */
14213 argvars[1].v_type = VAR_STRING;
14214 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
14215 argvars[2].v_type = VAR_UNKNOWN;
14216 remote_common(argvars, rettv, TRUE);
14217 vim_free(argvars[1].vval.v_string);
14218 # endif
14219 #endif
14222 static void
14223 f_remote_peek(argvars, rettv)
14224 typval_T *argvars UNUSED;
14225 typval_T *rettv;
14227 #ifdef FEAT_CLIENTSERVER
14228 dictitem_T v;
14229 char_u *s = NULL;
14230 # ifdef WIN32
14231 long_u n = 0;
14232 # endif
14233 char_u *serverid;
14235 if (check_restricted() || check_secure())
14237 rettv->vval.v_number = -1;
14238 return;
14240 serverid = get_tv_string_chk(&argvars[0]);
14241 if (serverid == NULL)
14243 rettv->vval.v_number = -1;
14244 return; /* type error; errmsg already given */
14246 # ifdef WIN32
14247 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14248 if (n == 0)
14249 rettv->vval.v_number = -1;
14250 else
14252 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
14253 rettv->vval.v_number = (s != NULL);
14255 # else
14256 if (check_connection() == FAIL)
14257 return;
14259 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
14260 serverStrToWin(serverid), &s);
14261 # endif
14263 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
14265 char_u *retvar;
14267 v.di_tv.v_type = VAR_STRING;
14268 v.di_tv.vval.v_string = vim_strsave(s);
14269 retvar = get_tv_string_chk(&argvars[1]);
14270 if (retvar != NULL)
14271 set_var(retvar, &v.di_tv, FALSE);
14272 vim_free(v.di_tv.vval.v_string);
14274 #else
14275 rettv->vval.v_number = -1;
14276 #endif
14279 static void
14280 f_remote_read(argvars, rettv)
14281 typval_T *argvars UNUSED;
14282 typval_T *rettv;
14284 char_u *r = NULL;
14286 #ifdef FEAT_CLIENTSERVER
14287 char_u *serverid = get_tv_string_chk(&argvars[0]);
14289 if (serverid != NULL && !check_restricted() && !check_secure())
14291 # ifdef WIN32
14292 /* The server's HWND is encoded in the 'id' parameter */
14293 long_u n = 0;
14295 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14296 if (n != 0)
14297 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
14298 if (r == NULL)
14299 # else
14300 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
14301 serverStrToWin(serverid), &r, FALSE) < 0)
14302 # endif
14303 EMSG(_("E277: Unable to read a server reply"));
14305 #endif
14306 rettv->v_type = VAR_STRING;
14307 rettv->vval.v_string = r;
14311 * "remote_send()" function
14313 static void
14314 f_remote_send(argvars, rettv)
14315 typval_T *argvars UNUSED;
14316 typval_T *rettv;
14318 rettv->v_type = VAR_STRING;
14319 rettv->vval.v_string = NULL;
14320 #ifdef FEAT_CLIENTSERVER
14321 remote_common(argvars, rettv, FALSE);
14322 #endif
14326 * "remove()" function
14328 static void
14329 f_remove(argvars, rettv)
14330 typval_T *argvars;
14331 typval_T *rettv;
14333 list_T *l;
14334 listitem_T *item, *item2;
14335 listitem_T *li;
14336 long idx;
14337 long end;
14338 char_u *key;
14339 dict_T *d;
14340 dictitem_T *di;
14342 if (argvars[0].v_type == VAR_DICT)
14344 if (argvars[2].v_type != VAR_UNKNOWN)
14345 EMSG2(_(e_toomanyarg), "remove()");
14346 else if ((d = argvars[0].vval.v_dict) != NULL
14347 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
14349 key = get_tv_string_chk(&argvars[1]);
14350 if (key != NULL)
14352 di = dict_find(d, key, -1);
14353 if (di == NULL)
14354 EMSG2(_(e_dictkey), key);
14355 else
14357 *rettv = di->di_tv;
14358 init_tv(&di->di_tv);
14359 dictitem_remove(d, di);
14364 else if (argvars[0].v_type != VAR_LIST)
14365 EMSG2(_(e_listdictarg), "remove()");
14366 else if ((l = argvars[0].vval.v_list) != NULL
14367 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
14369 int error = FALSE;
14371 idx = get_tv_number_chk(&argvars[1], &error);
14372 if (error)
14373 ; /* type error: do nothing, errmsg already given */
14374 else if ((item = list_find(l, idx)) == NULL)
14375 EMSGN(_(e_listidx), idx);
14376 else
14378 if (argvars[2].v_type == VAR_UNKNOWN)
14380 /* Remove one item, return its value. */
14381 list_remove(l, item, item);
14382 *rettv = item->li_tv;
14383 vim_free(item);
14385 else
14387 /* Remove range of items, return list with values. */
14388 end = get_tv_number_chk(&argvars[2], &error);
14389 if (error)
14390 ; /* type error: do nothing */
14391 else if ((item2 = list_find(l, end)) == NULL)
14392 EMSGN(_(e_listidx), end);
14393 else
14395 int cnt = 0;
14397 for (li = item; li != NULL; li = li->li_next)
14399 ++cnt;
14400 if (li == item2)
14401 break;
14403 if (li == NULL) /* didn't find "item2" after "item" */
14404 EMSG(_(e_invrange));
14405 else
14407 list_remove(l, item, item2);
14408 if (rettv_list_alloc(rettv) == OK)
14410 l = rettv->vval.v_list;
14411 l->lv_first = item;
14412 l->lv_last = item2;
14413 item->li_prev = NULL;
14414 item2->li_next = NULL;
14415 l->lv_len = cnt;
14425 * "rename({from}, {to})" function
14427 static void
14428 f_rename(argvars, rettv)
14429 typval_T *argvars;
14430 typval_T *rettv;
14432 char_u buf[NUMBUFLEN];
14434 if (check_restricted() || check_secure())
14435 rettv->vval.v_number = -1;
14436 else
14437 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
14438 get_tv_string_buf(&argvars[1], buf));
14442 * "repeat()" function
14444 static void
14445 f_repeat(argvars, rettv)
14446 typval_T *argvars;
14447 typval_T *rettv;
14449 char_u *p;
14450 int n;
14451 int slen;
14452 int len;
14453 char_u *r;
14454 int i;
14456 n = get_tv_number(&argvars[1]);
14457 if (argvars[0].v_type == VAR_LIST)
14459 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
14460 while (n-- > 0)
14461 if (list_extend(rettv->vval.v_list,
14462 argvars[0].vval.v_list, NULL) == FAIL)
14463 break;
14465 else
14467 p = get_tv_string(&argvars[0]);
14468 rettv->v_type = VAR_STRING;
14469 rettv->vval.v_string = NULL;
14471 slen = (int)STRLEN(p);
14472 len = slen * n;
14473 if (len <= 0)
14474 return;
14476 r = alloc(len + 1);
14477 if (r != NULL)
14479 for (i = 0; i < n; i++)
14480 mch_memmove(r + i * slen, p, (size_t)slen);
14481 r[len] = NUL;
14484 rettv->vval.v_string = r;
14489 * "resolve()" function
14491 static void
14492 f_resolve(argvars, rettv)
14493 typval_T *argvars;
14494 typval_T *rettv;
14496 char_u *p;
14498 p = get_tv_string(&argvars[0]);
14499 #ifdef FEAT_SHORTCUT
14501 char_u *v = NULL;
14503 v = mch_resolve_shortcut(p);
14504 if (v != NULL)
14505 rettv->vval.v_string = v;
14506 else
14507 rettv->vval.v_string = vim_strsave(p);
14509 #else
14510 # ifdef HAVE_READLINK
14512 char_u buf[MAXPATHL + 1];
14513 char_u *cpy;
14514 int len;
14515 char_u *remain = NULL;
14516 char_u *q;
14517 int is_relative_to_current = FALSE;
14518 int has_trailing_pathsep = FALSE;
14519 int limit = 100;
14521 p = vim_strsave(p);
14523 if (p[0] == '.' && (vim_ispathsep(p[1])
14524 || (p[1] == '.' && (vim_ispathsep(p[2])))))
14525 is_relative_to_current = TRUE;
14527 len = STRLEN(p);
14528 if (len > 0 && after_pathsep(p, p + len))
14529 has_trailing_pathsep = TRUE;
14531 q = getnextcomp(p);
14532 if (*q != NUL)
14534 /* Separate the first path component in "p", and keep the
14535 * remainder (beginning with the path separator). */
14536 remain = vim_strsave(q - 1);
14537 q[-1] = NUL;
14540 for (;;)
14542 for (;;)
14544 len = readlink((char *)p, (char *)buf, MAXPATHL);
14545 if (len <= 0)
14546 break;
14547 buf[len] = NUL;
14549 if (limit-- == 0)
14551 vim_free(p);
14552 vim_free(remain);
14553 EMSG(_("E655: Too many symbolic links (cycle?)"));
14554 rettv->vval.v_string = NULL;
14555 goto fail;
14558 /* Ensure that the result will have a trailing path separator
14559 * if the argument has one. */
14560 if (remain == NULL && has_trailing_pathsep)
14561 add_pathsep(buf);
14563 /* Separate the first path component in the link value and
14564 * concatenate the remainders. */
14565 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
14566 if (*q != NUL)
14568 if (remain == NULL)
14569 remain = vim_strsave(q - 1);
14570 else
14572 cpy = concat_str(q - 1, remain);
14573 if (cpy != NULL)
14575 vim_free(remain);
14576 remain = cpy;
14579 q[-1] = NUL;
14582 q = gettail(p);
14583 if (q > p && *q == NUL)
14585 /* Ignore trailing path separator. */
14586 q[-1] = NUL;
14587 q = gettail(p);
14589 if (q > p && !mch_isFullName(buf))
14591 /* symlink is relative to directory of argument */
14592 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
14593 if (cpy != NULL)
14595 STRCPY(cpy, p);
14596 STRCPY(gettail(cpy), buf);
14597 vim_free(p);
14598 p = cpy;
14601 else
14603 vim_free(p);
14604 p = vim_strsave(buf);
14608 if (remain == NULL)
14609 break;
14611 /* Append the first path component of "remain" to "p". */
14612 q = getnextcomp(remain + 1);
14613 len = q - remain - (*q != NUL);
14614 cpy = vim_strnsave(p, STRLEN(p) + len);
14615 if (cpy != NULL)
14617 STRNCAT(cpy, remain, len);
14618 vim_free(p);
14619 p = cpy;
14621 /* Shorten "remain". */
14622 if (*q != NUL)
14623 STRMOVE(remain, q - 1);
14624 else
14626 vim_free(remain);
14627 remain = NULL;
14631 /* If the result is a relative path name, make it explicitly relative to
14632 * the current directory if and only if the argument had this form. */
14633 if (!vim_ispathsep(*p))
14635 if (is_relative_to_current
14636 && *p != NUL
14637 && !(p[0] == '.'
14638 && (p[1] == NUL
14639 || vim_ispathsep(p[1])
14640 || (p[1] == '.'
14641 && (p[2] == NUL
14642 || vim_ispathsep(p[2]))))))
14644 /* Prepend "./". */
14645 cpy = concat_str((char_u *)"./", p);
14646 if (cpy != NULL)
14648 vim_free(p);
14649 p = cpy;
14652 else if (!is_relative_to_current)
14654 /* Strip leading "./". */
14655 q = p;
14656 while (q[0] == '.' && vim_ispathsep(q[1]))
14657 q += 2;
14658 if (q > p)
14659 STRMOVE(p, p + 2);
14663 /* Ensure that the result will have no trailing path separator
14664 * if the argument had none. But keep "/" or "//". */
14665 if (!has_trailing_pathsep)
14667 q = p + STRLEN(p);
14668 if (after_pathsep(p, q))
14669 *gettail_sep(p) = NUL;
14672 rettv->vval.v_string = p;
14674 # else
14675 rettv->vval.v_string = vim_strsave(p);
14676 # endif
14677 #endif
14679 simplify_filename(rettv->vval.v_string);
14681 #ifdef HAVE_READLINK
14682 fail:
14683 #endif
14684 rettv->v_type = VAR_STRING;
14688 * "reverse({list})" function
14690 static void
14691 f_reverse(argvars, rettv)
14692 typval_T *argvars;
14693 typval_T *rettv;
14695 list_T *l;
14696 listitem_T *li, *ni;
14698 if (argvars[0].v_type != VAR_LIST)
14699 EMSG2(_(e_listarg), "reverse()");
14700 else if ((l = argvars[0].vval.v_list) != NULL
14701 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
14703 li = l->lv_last;
14704 l->lv_first = l->lv_last = NULL;
14705 l->lv_len = 0;
14706 while (li != NULL)
14708 ni = li->li_prev;
14709 list_append(l, li);
14710 li = ni;
14712 rettv->vval.v_list = l;
14713 rettv->v_type = VAR_LIST;
14714 ++l->lv_refcount;
14715 l->lv_idx = l->lv_len - l->lv_idx - 1;
14719 #define SP_NOMOVE 0x01 /* don't move cursor */
14720 #define SP_REPEAT 0x02 /* repeat to find outer pair */
14721 #define SP_RETCOUNT 0x04 /* return matchcount */
14722 #define SP_SETPCMARK 0x08 /* set previous context mark */
14723 #define SP_START 0x10 /* accept match at start position */
14724 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
14725 #define SP_END 0x40 /* leave cursor at end of match */
14727 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
14730 * Get flags for a search function.
14731 * Possibly sets "p_ws".
14732 * Returns BACKWARD, FORWARD or zero (for an error).
14734 static int
14735 get_search_arg(varp, flagsp)
14736 typval_T *varp;
14737 int *flagsp;
14739 int dir = FORWARD;
14740 char_u *flags;
14741 char_u nbuf[NUMBUFLEN];
14742 int mask;
14744 if (varp->v_type != VAR_UNKNOWN)
14746 flags = get_tv_string_buf_chk(varp, nbuf);
14747 if (flags == NULL)
14748 return 0; /* type error; errmsg already given */
14749 while (*flags != NUL)
14751 switch (*flags)
14753 case 'b': dir = BACKWARD; break;
14754 case 'w': p_ws = TRUE; break;
14755 case 'W': p_ws = FALSE; break;
14756 default: mask = 0;
14757 if (flagsp != NULL)
14758 switch (*flags)
14760 case 'c': mask = SP_START; break;
14761 case 'e': mask = SP_END; break;
14762 case 'm': mask = SP_RETCOUNT; break;
14763 case 'n': mask = SP_NOMOVE; break;
14764 case 'p': mask = SP_SUBPAT; break;
14765 case 'r': mask = SP_REPEAT; break;
14766 case 's': mask = SP_SETPCMARK; break;
14768 if (mask == 0)
14770 EMSG2(_(e_invarg2), flags);
14771 dir = 0;
14773 else
14774 *flagsp |= mask;
14776 if (dir == 0)
14777 break;
14778 ++flags;
14781 return dir;
14785 * Shared by search() and searchpos() functions
14787 static int
14788 search_cmn(argvars, match_pos, flagsp)
14789 typval_T *argvars;
14790 pos_T *match_pos;
14791 int *flagsp;
14793 int flags;
14794 char_u *pat;
14795 pos_T pos;
14796 pos_T save_cursor;
14797 int save_p_ws = p_ws;
14798 int dir;
14799 int retval = 0; /* default: FAIL */
14800 long lnum_stop = 0;
14801 proftime_T tm;
14802 #ifdef FEAT_RELTIME
14803 long time_limit = 0;
14804 #endif
14805 int options = SEARCH_KEEP;
14806 int subpatnum;
14808 pat = get_tv_string(&argvars[0]);
14809 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
14810 if (dir == 0)
14811 goto theend;
14812 flags = *flagsp;
14813 if (flags & SP_START)
14814 options |= SEARCH_START;
14815 if (flags & SP_END)
14816 options |= SEARCH_END;
14818 /* Optional arguments: line number to stop searching and timeout. */
14819 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
14821 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
14822 if (lnum_stop < 0)
14823 goto theend;
14824 #ifdef FEAT_RELTIME
14825 if (argvars[3].v_type != VAR_UNKNOWN)
14827 time_limit = get_tv_number_chk(&argvars[3], NULL);
14828 if (time_limit < 0)
14829 goto theend;
14831 #endif
14834 #ifdef FEAT_RELTIME
14835 /* Set the time limit, if there is one. */
14836 profile_setlimit(time_limit, &tm);
14837 #endif
14840 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
14841 * Check to make sure only those flags are set.
14842 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
14843 * flags cannot be set. Check for that condition also.
14845 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
14846 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14848 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
14849 goto theend;
14852 pos = save_cursor = curwin->w_cursor;
14853 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14854 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
14855 if (subpatnum != FAIL)
14857 if (flags & SP_SUBPAT)
14858 retval = subpatnum;
14859 else
14860 retval = pos.lnum;
14861 if (flags & SP_SETPCMARK)
14862 setpcmark();
14863 curwin->w_cursor = pos;
14864 if (match_pos != NULL)
14866 /* Store the match cursor position */
14867 match_pos->lnum = pos.lnum;
14868 match_pos->col = pos.col + 1;
14870 /* "/$" will put the cursor after the end of the line, may need to
14871 * correct that here */
14872 check_cursor();
14875 /* If 'n' flag is used: restore cursor position. */
14876 if (flags & SP_NOMOVE)
14877 curwin->w_cursor = save_cursor;
14878 else
14879 curwin->w_set_curswant = TRUE;
14880 theend:
14881 p_ws = save_p_ws;
14883 return retval;
14886 #ifdef FEAT_FLOAT
14888 * "round({float})" function
14890 static void
14891 f_round(argvars, rettv)
14892 typval_T *argvars;
14893 typval_T *rettv;
14895 float_T f;
14897 rettv->v_type = VAR_FLOAT;
14898 if (get_float_arg(argvars, &f) == OK)
14899 /* round() is not in C90, use ceil() or floor() instead. */
14900 rettv->vval.v_float = f > 0 ? floor(f + 0.5) : ceil(f - 0.5);
14901 else
14902 rettv->vval.v_float = 0.0;
14904 #endif
14907 * "search()" function
14909 static void
14910 f_search(argvars, rettv)
14911 typval_T *argvars;
14912 typval_T *rettv;
14914 int flags = 0;
14916 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
14920 * "searchdecl()" function
14922 static void
14923 f_searchdecl(argvars, rettv)
14924 typval_T *argvars;
14925 typval_T *rettv;
14927 int locally = 1;
14928 int thisblock = 0;
14929 int error = FALSE;
14930 char_u *name;
14932 rettv->vval.v_number = 1; /* default: FAIL */
14934 name = get_tv_string_chk(&argvars[0]);
14935 if (argvars[1].v_type != VAR_UNKNOWN)
14937 locally = get_tv_number_chk(&argvars[1], &error) == 0;
14938 if (!error && argvars[2].v_type != VAR_UNKNOWN)
14939 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
14941 if (!error && name != NULL)
14942 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
14943 locally, thisblock, SEARCH_KEEP) == FAIL;
14947 * Used by searchpair() and searchpairpos()
14949 static int
14950 searchpair_cmn(argvars, match_pos)
14951 typval_T *argvars;
14952 pos_T *match_pos;
14954 char_u *spat, *mpat, *epat;
14955 char_u *skip;
14956 int save_p_ws = p_ws;
14957 int dir;
14958 int flags = 0;
14959 char_u nbuf1[NUMBUFLEN];
14960 char_u nbuf2[NUMBUFLEN];
14961 char_u nbuf3[NUMBUFLEN];
14962 int retval = 0; /* default: FAIL */
14963 long lnum_stop = 0;
14964 long time_limit = 0;
14966 /* Get the three pattern arguments: start, middle, end. */
14967 spat = get_tv_string_chk(&argvars[0]);
14968 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
14969 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
14970 if (spat == NULL || mpat == NULL || epat == NULL)
14971 goto theend; /* type error */
14973 /* Handle the optional fourth argument: flags */
14974 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
14975 if (dir == 0)
14976 goto theend;
14978 /* Don't accept SP_END or SP_SUBPAT.
14979 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
14981 if ((flags & (SP_END | SP_SUBPAT)) != 0
14982 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14984 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
14985 goto theend;
14988 /* Using 'r' implies 'W', otherwise it doesn't work. */
14989 if (flags & SP_REPEAT)
14990 p_ws = FALSE;
14992 /* Optional fifth argument: skip expression */
14993 if (argvars[3].v_type == VAR_UNKNOWN
14994 || argvars[4].v_type == VAR_UNKNOWN)
14995 skip = (char_u *)"";
14996 else
14998 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
14999 if (argvars[5].v_type != VAR_UNKNOWN)
15001 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
15002 if (lnum_stop < 0)
15003 goto theend;
15004 #ifdef FEAT_RELTIME
15005 if (argvars[6].v_type != VAR_UNKNOWN)
15007 time_limit = get_tv_number_chk(&argvars[6], NULL);
15008 if (time_limit < 0)
15009 goto theend;
15011 #endif
15014 if (skip == NULL)
15015 goto theend; /* type error */
15017 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
15018 match_pos, lnum_stop, time_limit);
15020 theend:
15021 p_ws = save_p_ws;
15023 return retval;
15027 * "searchpair()" function
15029 static void
15030 f_searchpair(argvars, rettv)
15031 typval_T *argvars;
15032 typval_T *rettv;
15034 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
15038 * "searchpairpos()" function
15040 static void
15041 f_searchpairpos(argvars, rettv)
15042 typval_T *argvars;
15043 typval_T *rettv;
15045 pos_T match_pos;
15046 int lnum = 0;
15047 int col = 0;
15049 if (rettv_list_alloc(rettv) == FAIL)
15050 return;
15052 if (searchpair_cmn(argvars, &match_pos) > 0)
15054 lnum = match_pos.lnum;
15055 col = match_pos.col;
15058 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15059 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15063 * Search for a start/middle/end thing.
15064 * Used by searchpair(), see its documentation for the details.
15065 * Returns 0 or -1 for no match,
15067 long
15068 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
15069 lnum_stop, time_limit)
15070 char_u *spat; /* start pattern */
15071 char_u *mpat; /* middle pattern */
15072 char_u *epat; /* end pattern */
15073 int dir; /* BACKWARD or FORWARD */
15074 char_u *skip; /* skip expression */
15075 int flags; /* SP_SETPCMARK and other SP_ values */
15076 pos_T *match_pos;
15077 linenr_T lnum_stop; /* stop at this line if not zero */
15078 long time_limit; /* stop after this many msec */
15080 char_u *save_cpo;
15081 char_u *pat, *pat2 = NULL, *pat3 = NULL;
15082 long retval = 0;
15083 pos_T pos;
15084 pos_T firstpos;
15085 pos_T foundpos;
15086 pos_T save_cursor;
15087 pos_T save_pos;
15088 int n;
15089 int r;
15090 int nest = 1;
15091 int err;
15092 int options = SEARCH_KEEP;
15093 proftime_T tm;
15095 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15096 save_cpo = p_cpo;
15097 p_cpo = empty_option;
15099 #ifdef FEAT_RELTIME
15100 /* Set the time limit, if there is one. */
15101 profile_setlimit(time_limit, &tm);
15102 #endif
15104 /* Make two search patterns: start/end (pat2, for in nested pairs) and
15105 * start/middle/end (pat3, for the top pair). */
15106 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
15107 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
15108 if (pat2 == NULL || pat3 == NULL)
15109 goto theend;
15110 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
15111 if (*mpat == NUL)
15112 STRCPY(pat3, pat2);
15113 else
15114 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
15115 spat, epat, mpat);
15116 if (flags & SP_START)
15117 options |= SEARCH_START;
15119 save_cursor = curwin->w_cursor;
15120 pos = curwin->w_cursor;
15121 clearpos(&firstpos);
15122 clearpos(&foundpos);
15123 pat = pat3;
15124 for (;;)
15126 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15127 options, RE_SEARCH, lnum_stop, &tm);
15128 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
15129 /* didn't find it or found the first match again: FAIL */
15130 break;
15132 if (firstpos.lnum == 0)
15133 firstpos = pos;
15134 if (equalpos(pos, foundpos))
15136 /* Found the same position again. Can happen with a pattern that
15137 * has "\zs" at the end and searching backwards. Advance one
15138 * character and try again. */
15139 if (dir == BACKWARD)
15140 decl(&pos);
15141 else
15142 incl(&pos);
15144 foundpos = pos;
15146 /* clear the start flag to avoid getting stuck here */
15147 options &= ~SEARCH_START;
15149 /* If the skip pattern matches, ignore this match. */
15150 if (*skip != NUL)
15152 save_pos = curwin->w_cursor;
15153 curwin->w_cursor = pos;
15154 r = eval_to_bool(skip, &err, NULL, FALSE);
15155 curwin->w_cursor = save_pos;
15156 if (err)
15158 /* Evaluating {skip} caused an error, break here. */
15159 curwin->w_cursor = save_cursor;
15160 retval = -1;
15161 break;
15163 if (r)
15164 continue;
15167 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
15169 /* Found end when searching backwards or start when searching
15170 * forward: nested pair. */
15171 ++nest;
15172 pat = pat2; /* nested, don't search for middle */
15174 else
15176 /* Found end when searching forward or start when searching
15177 * backward: end of (nested) pair; or found middle in outer pair. */
15178 if (--nest == 1)
15179 pat = pat3; /* outer level, search for middle */
15182 if (nest == 0)
15184 /* Found the match: return matchcount or line number. */
15185 if (flags & SP_RETCOUNT)
15186 ++retval;
15187 else
15188 retval = pos.lnum;
15189 if (flags & SP_SETPCMARK)
15190 setpcmark();
15191 curwin->w_cursor = pos;
15192 if (!(flags & SP_REPEAT))
15193 break;
15194 nest = 1; /* search for next unmatched */
15198 if (match_pos != NULL)
15200 /* Store the match cursor position */
15201 match_pos->lnum = curwin->w_cursor.lnum;
15202 match_pos->col = curwin->w_cursor.col + 1;
15205 /* If 'n' flag is used or search failed: restore cursor position. */
15206 if ((flags & SP_NOMOVE) || retval == 0)
15207 curwin->w_cursor = save_cursor;
15209 theend:
15210 vim_free(pat2);
15211 vim_free(pat3);
15212 if (p_cpo == empty_option)
15213 p_cpo = save_cpo;
15214 else
15215 /* Darn, evaluating the {skip} expression changed the value. */
15216 free_string_option(save_cpo);
15218 return retval;
15222 * "searchpos()" function
15224 static void
15225 f_searchpos(argvars, rettv)
15226 typval_T *argvars;
15227 typval_T *rettv;
15229 pos_T match_pos;
15230 int lnum = 0;
15231 int col = 0;
15232 int n;
15233 int flags = 0;
15235 if (rettv_list_alloc(rettv) == FAIL)
15236 return;
15238 n = search_cmn(argvars, &match_pos, &flags);
15239 if (n > 0)
15241 lnum = match_pos.lnum;
15242 col = match_pos.col;
15245 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15246 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15247 if (flags & SP_SUBPAT)
15248 list_append_number(rettv->vval.v_list, (varnumber_T)n);
15252 static void
15253 f_server2client(argvars, rettv)
15254 typval_T *argvars UNUSED;
15255 typval_T *rettv;
15257 #ifdef FEAT_CLIENTSERVER
15258 char_u buf[NUMBUFLEN];
15259 char_u *server = get_tv_string_chk(&argvars[0]);
15260 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
15262 rettv->vval.v_number = -1;
15263 if (server == NULL || reply == NULL)
15264 return;
15265 if (check_restricted() || check_secure())
15266 return;
15267 # ifdef FEAT_X11
15268 if (check_connection() == FAIL)
15269 return;
15270 # endif
15272 if (serverSendReply(server, reply) < 0)
15274 EMSG(_("E258: Unable to send to client"));
15275 return;
15277 rettv->vval.v_number = 0;
15278 #else
15279 rettv->vval.v_number = -1;
15280 #endif
15283 static void
15284 f_serverlist(argvars, rettv)
15285 typval_T *argvars UNUSED;
15286 typval_T *rettv;
15288 char_u *r = NULL;
15290 #ifdef FEAT_CLIENTSERVER
15291 # ifdef WIN32
15292 r = serverGetVimNames();
15293 # else
15294 make_connection();
15295 if (X_DISPLAY != NULL)
15296 r = serverGetVimNames(X_DISPLAY);
15297 # endif
15298 #endif
15299 rettv->v_type = VAR_STRING;
15300 rettv->vval.v_string = r;
15304 * "setbufvar()" function
15306 static void
15307 f_setbufvar(argvars, rettv)
15308 typval_T *argvars;
15309 typval_T *rettv UNUSED;
15311 buf_T *buf;
15312 aco_save_T aco;
15313 char_u *varname, *bufvarname;
15314 typval_T *varp;
15315 char_u nbuf[NUMBUFLEN];
15317 if (check_restricted() || check_secure())
15318 return;
15319 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
15320 varname = get_tv_string_chk(&argvars[1]);
15321 buf = get_buf_tv(&argvars[0]);
15322 varp = &argvars[2];
15324 if (buf != NULL && varname != NULL && varp != NULL)
15326 /* set curbuf to be our buf, temporarily */
15327 aucmd_prepbuf(&aco, buf);
15329 if (*varname == '&')
15331 long numval;
15332 char_u *strval;
15333 int error = FALSE;
15335 ++varname;
15336 numval = get_tv_number_chk(varp, &error);
15337 strval = get_tv_string_buf_chk(varp, nbuf);
15338 if (!error && strval != NULL)
15339 set_option_value(varname, numval, strval, OPT_LOCAL);
15341 else
15343 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
15344 if (bufvarname != NULL)
15346 STRCPY(bufvarname, "b:");
15347 STRCPY(bufvarname + 2, varname);
15348 set_var(bufvarname, varp, TRUE);
15349 vim_free(bufvarname);
15353 /* reset notion of buffer */
15354 aucmd_restbuf(&aco);
15359 * "setcmdpos()" function
15361 static void
15362 f_setcmdpos(argvars, rettv)
15363 typval_T *argvars;
15364 typval_T *rettv;
15366 int pos = (int)get_tv_number(&argvars[0]) - 1;
15368 if (pos >= 0)
15369 rettv->vval.v_number = set_cmdline_pos(pos);
15373 * "setline()" function
15375 static void
15376 f_setline(argvars, rettv)
15377 typval_T *argvars;
15378 typval_T *rettv;
15380 linenr_T lnum;
15381 char_u *line = NULL;
15382 list_T *l = NULL;
15383 listitem_T *li = NULL;
15384 long added = 0;
15385 linenr_T lcount = curbuf->b_ml.ml_line_count;
15387 lnum = get_tv_lnum(&argvars[0]);
15388 if (argvars[1].v_type == VAR_LIST)
15390 l = argvars[1].vval.v_list;
15391 li = l->lv_first;
15393 else
15394 line = get_tv_string_chk(&argvars[1]);
15396 /* default result is zero == OK */
15397 for (;;)
15399 if (l != NULL)
15401 /* list argument, get next string */
15402 if (li == NULL)
15403 break;
15404 line = get_tv_string_chk(&li->li_tv);
15405 li = li->li_next;
15408 rettv->vval.v_number = 1; /* FAIL */
15409 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
15410 break;
15411 if (lnum <= curbuf->b_ml.ml_line_count)
15413 /* existing line, replace it */
15414 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
15416 changed_bytes(lnum, 0);
15417 if (lnum == curwin->w_cursor.lnum)
15418 check_cursor_col();
15419 rettv->vval.v_number = 0; /* OK */
15422 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
15424 /* lnum is one past the last line, append the line */
15425 ++added;
15426 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
15427 rettv->vval.v_number = 0; /* OK */
15430 if (l == NULL) /* only one string argument */
15431 break;
15432 ++lnum;
15435 if (added > 0)
15436 appended_lines_mark(lcount, added);
15439 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
15442 * Used by "setqflist()" and "setloclist()" functions
15444 static void
15445 set_qf_ll_list(wp, list_arg, action_arg, rettv)
15446 win_T *wp UNUSED;
15447 typval_T *list_arg UNUSED;
15448 typval_T *action_arg UNUSED;
15449 typval_T *rettv;
15451 #ifdef FEAT_QUICKFIX
15452 char_u *act;
15453 int action = ' ';
15454 #endif
15456 rettv->vval.v_number = -1;
15458 #ifdef FEAT_QUICKFIX
15459 if (list_arg->v_type != VAR_LIST)
15460 EMSG(_(e_listreq));
15461 else
15463 list_T *l = list_arg->vval.v_list;
15465 if (action_arg->v_type == VAR_STRING)
15467 act = get_tv_string_chk(action_arg);
15468 if (act == NULL)
15469 return; /* type error; errmsg already given */
15470 if (*act == 'a' || *act == 'r')
15471 action = *act;
15474 if (l != NULL && set_errorlist(wp, l, action) == OK)
15475 rettv->vval.v_number = 0;
15477 #endif
15481 * "setloclist()" function
15483 static void
15484 f_setloclist(argvars, rettv)
15485 typval_T *argvars;
15486 typval_T *rettv;
15488 win_T *win;
15490 rettv->vval.v_number = -1;
15492 win = find_win_by_nr(&argvars[0], NULL);
15493 if (win != NULL)
15494 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
15498 * "setmatches()" function
15500 static void
15501 f_setmatches(argvars, rettv)
15502 typval_T *argvars;
15503 typval_T *rettv;
15505 #ifdef FEAT_SEARCH_EXTRA
15506 list_T *l;
15507 listitem_T *li;
15508 dict_T *d;
15510 rettv->vval.v_number = -1;
15511 if (argvars[0].v_type != VAR_LIST)
15513 EMSG(_(e_listreq));
15514 return;
15516 if ((l = argvars[0].vval.v_list) != NULL)
15519 /* To some extent make sure that we are dealing with a list from
15520 * "getmatches()". */
15521 li = l->lv_first;
15522 while (li != NULL)
15524 if (li->li_tv.v_type != VAR_DICT
15525 || (d = li->li_tv.vval.v_dict) == NULL)
15527 EMSG(_(e_invarg));
15528 return;
15530 if (!(dict_find(d, (char_u *)"group", -1) != NULL
15531 && dict_find(d, (char_u *)"pattern", -1) != NULL
15532 && dict_find(d, (char_u *)"priority", -1) != NULL
15533 && dict_find(d, (char_u *)"id", -1) != NULL))
15535 EMSG(_(e_invarg));
15536 return;
15538 li = li->li_next;
15541 clear_matches(curwin);
15542 li = l->lv_first;
15543 while (li != NULL)
15545 d = li->li_tv.vval.v_dict;
15546 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
15547 get_dict_string(d, (char_u *)"pattern", FALSE),
15548 (int)get_dict_number(d, (char_u *)"priority"),
15549 (int)get_dict_number(d, (char_u *)"id"));
15550 li = li->li_next;
15552 rettv->vval.v_number = 0;
15554 #endif
15558 * "setpos()" function
15560 static void
15561 f_setpos(argvars, rettv)
15562 typval_T *argvars;
15563 typval_T *rettv;
15565 pos_T pos;
15566 int fnum;
15567 char_u *name;
15569 rettv->vval.v_number = -1;
15570 name = get_tv_string_chk(argvars);
15571 if (name != NULL)
15573 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
15575 if (--pos.col < 0)
15576 pos.col = 0;
15577 if (name[0] == '.' && name[1] == NUL)
15579 /* set cursor */
15580 if (fnum == curbuf->b_fnum)
15582 curwin->w_cursor = pos;
15583 check_cursor();
15584 rettv->vval.v_number = 0;
15586 else
15587 EMSG(_(e_invarg));
15589 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
15591 /* set mark */
15592 if (setmark_pos(name[1], &pos, fnum) == OK)
15593 rettv->vval.v_number = 0;
15595 else
15596 EMSG(_(e_invarg));
15602 * "setqflist()" function
15604 static void
15605 f_setqflist(argvars, rettv)
15606 typval_T *argvars;
15607 typval_T *rettv;
15609 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
15613 * "setreg()" function
15615 static void
15616 f_setreg(argvars, rettv)
15617 typval_T *argvars;
15618 typval_T *rettv;
15620 int regname;
15621 char_u *strregname;
15622 char_u *stropt;
15623 char_u *strval;
15624 int append;
15625 char_u yank_type;
15626 long block_len;
15628 block_len = -1;
15629 yank_type = MAUTO;
15630 append = FALSE;
15632 strregname = get_tv_string_chk(argvars);
15633 rettv->vval.v_number = 1; /* FAIL is default */
15635 if (strregname == NULL)
15636 return; /* type error; errmsg already given */
15637 regname = *strregname;
15638 if (regname == 0 || regname == '@')
15639 regname = '"';
15640 else if (regname == '=')
15641 return;
15643 if (argvars[2].v_type != VAR_UNKNOWN)
15645 stropt = get_tv_string_chk(&argvars[2]);
15646 if (stropt == NULL)
15647 return; /* type error */
15648 for (; *stropt != NUL; ++stropt)
15649 switch (*stropt)
15651 case 'a': case 'A': /* append */
15652 append = TRUE;
15653 break;
15654 case 'v': case 'c': /* character-wise selection */
15655 yank_type = MCHAR;
15656 break;
15657 case 'V': case 'l': /* line-wise selection */
15658 yank_type = MLINE;
15659 break;
15660 #ifdef FEAT_VISUAL
15661 case 'b': case Ctrl_V: /* block-wise selection */
15662 yank_type = MBLOCK;
15663 if (VIM_ISDIGIT(stropt[1]))
15665 ++stropt;
15666 block_len = getdigits(&stropt) - 1;
15667 --stropt;
15669 break;
15670 #endif
15674 strval = get_tv_string_chk(&argvars[1]);
15675 if (strval != NULL)
15676 write_reg_contents_ex(regname, strval, -1,
15677 append, yank_type, block_len);
15678 rettv->vval.v_number = 0;
15682 * "settabwinvar()" function
15684 static void
15685 f_settabwinvar(argvars, rettv)
15686 typval_T *argvars;
15687 typval_T *rettv;
15689 setwinvar(argvars, rettv, 1);
15693 * "setwinvar()" function
15695 static void
15696 f_setwinvar(argvars, rettv)
15697 typval_T *argvars;
15698 typval_T *rettv;
15700 setwinvar(argvars, rettv, 0);
15704 * "setwinvar()" and "settabwinvar()" functions
15706 static void
15707 setwinvar(argvars, rettv, off)
15708 typval_T *argvars;
15709 typval_T *rettv UNUSED;
15710 int off;
15712 win_T *win;
15713 #ifdef FEAT_WINDOWS
15714 win_T *save_curwin;
15715 tabpage_T *save_curtab;
15716 #endif
15717 char_u *varname, *winvarname;
15718 typval_T *varp;
15719 char_u nbuf[NUMBUFLEN];
15720 tabpage_T *tp;
15722 if (check_restricted() || check_secure())
15723 return;
15725 #ifdef FEAT_WINDOWS
15726 if (off == 1)
15727 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
15728 else
15729 tp = curtab;
15730 #endif
15731 win = find_win_by_nr(&argvars[off], tp);
15732 varname = get_tv_string_chk(&argvars[off + 1]);
15733 varp = &argvars[off + 2];
15735 if (win != NULL && varname != NULL && varp != NULL)
15737 #ifdef FEAT_WINDOWS
15738 /* set curwin to be our win, temporarily */
15739 save_curwin = curwin;
15740 save_curtab = curtab;
15741 goto_tabpage_tp(tp);
15742 if (!win_valid(win))
15743 return;
15744 curwin = win;
15745 curbuf = curwin->w_buffer;
15746 #endif
15748 if (*varname == '&')
15750 long numval;
15751 char_u *strval;
15752 int error = FALSE;
15754 ++varname;
15755 numval = get_tv_number_chk(varp, &error);
15756 strval = get_tv_string_buf_chk(varp, nbuf);
15757 if (!error && strval != NULL)
15758 set_option_value(varname, numval, strval, OPT_LOCAL);
15760 else
15762 winvarname = alloc((unsigned)STRLEN(varname) + 3);
15763 if (winvarname != NULL)
15765 STRCPY(winvarname, "w:");
15766 STRCPY(winvarname + 2, varname);
15767 set_var(winvarname, varp, TRUE);
15768 vim_free(winvarname);
15772 #ifdef FEAT_WINDOWS
15773 /* Restore current tabpage and window, if still valid (autocomands can
15774 * make them invalid). */
15775 if (valid_tabpage(save_curtab))
15776 goto_tabpage_tp(save_curtab);
15777 if (win_valid(save_curwin))
15779 curwin = save_curwin;
15780 curbuf = curwin->w_buffer;
15782 #endif
15787 * "shellescape({string})" function
15789 static void
15790 f_shellescape(argvars, rettv)
15791 typval_T *argvars;
15792 typval_T *rettv;
15794 rettv->vval.v_string = vim_strsave_shellescape(
15795 get_tv_string(&argvars[0]), non_zero_arg(&argvars[1]));
15796 rettv->v_type = VAR_STRING;
15800 * "simplify()" function
15802 static void
15803 f_simplify(argvars, rettv)
15804 typval_T *argvars;
15805 typval_T *rettv;
15807 char_u *p;
15809 p = get_tv_string(&argvars[0]);
15810 rettv->vval.v_string = vim_strsave(p);
15811 simplify_filename(rettv->vval.v_string); /* simplify in place */
15812 rettv->v_type = VAR_STRING;
15815 #ifdef FEAT_FLOAT
15817 * "sin()" function
15819 static void
15820 f_sin(argvars, rettv)
15821 typval_T *argvars;
15822 typval_T *rettv;
15824 float_T f;
15826 rettv->v_type = VAR_FLOAT;
15827 if (get_float_arg(argvars, &f) == OK)
15828 rettv->vval.v_float = sin(f);
15829 else
15830 rettv->vval.v_float = 0.0;
15832 #endif
15834 static int
15835 #ifdef __BORLANDC__
15836 _RTLENTRYF
15837 #endif
15838 item_compare __ARGS((const void *s1, const void *s2));
15839 static int
15840 #ifdef __BORLANDC__
15841 _RTLENTRYF
15842 #endif
15843 item_compare2 __ARGS((const void *s1, const void *s2));
15845 static int item_compare_ic;
15846 static char_u *item_compare_func;
15847 static int item_compare_func_err;
15848 #define ITEM_COMPARE_FAIL 999
15851 * Compare functions for f_sort() below.
15853 static int
15854 #ifdef __BORLANDC__
15855 _RTLENTRYF
15856 #endif
15857 item_compare(s1, s2)
15858 const void *s1;
15859 const void *s2;
15861 char_u *p1, *p2;
15862 char_u *tofree1, *tofree2;
15863 int res;
15864 char_u numbuf1[NUMBUFLEN];
15865 char_u numbuf2[NUMBUFLEN];
15867 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
15868 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
15869 if (p1 == NULL)
15870 p1 = (char_u *)"";
15871 if (p2 == NULL)
15872 p2 = (char_u *)"";
15873 if (item_compare_ic)
15874 res = STRICMP(p1, p2);
15875 else
15876 res = STRCMP(p1, p2);
15877 vim_free(tofree1);
15878 vim_free(tofree2);
15879 return res;
15882 static int
15883 #ifdef __BORLANDC__
15884 _RTLENTRYF
15885 #endif
15886 item_compare2(s1, s2)
15887 const void *s1;
15888 const void *s2;
15890 int res;
15891 typval_T rettv;
15892 typval_T argv[3];
15893 int dummy;
15895 /* shortcut after failure in previous call; compare all items equal */
15896 if (item_compare_func_err)
15897 return 0;
15899 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
15900 * in the copy without changing the original list items. */
15901 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
15902 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
15904 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
15905 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
15906 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
15907 clear_tv(&argv[0]);
15908 clear_tv(&argv[1]);
15910 if (res == FAIL)
15911 res = ITEM_COMPARE_FAIL;
15912 else
15913 res = get_tv_number_chk(&rettv, &item_compare_func_err);
15914 if (item_compare_func_err)
15915 res = ITEM_COMPARE_FAIL; /* return value has wrong type */
15916 clear_tv(&rettv);
15917 return res;
15921 * "sort({list})" function
15923 static void
15924 f_sort(argvars, rettv)
15925 typval_T *argvars;
15926 typval_T *rettv;
15928 list_T *l;
15929 listitem_T *li;
15930 listitem_T **ptrs;
15931 long len;
15932 long i;
15934 if (argvars[0].v_type != VAR_LIST)
15935 EMSG2(_(e_listarg), "sort()");
15936 else
15938 l = argvars[0].vval.v_list;
15939 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
15940 return;
15941 rettv->vval.v_list = l;
15942 rettv->v_type = VAR_LIST;
15943 ++l->lv_refcount;
15945 len = list_len(l);
15946 if (len <= 1)
15947 return; /* short list sorts pretty quickly */
15949 item_compare_ic = FALSE;
15950 item_compare_func = NULL;
15951 if (argvars[1].v_type != VAR_UNKNOWN)
15953 if (argvars[1].v_type == VAR_FUNC)
15954 item_compare_func = argvars[1].vval.v_string;
15955 else
15957 int error = FALSE;
15959 i = get_tv_number_chk(&argvars[1], &error);
15960 if (error)
15961 return; /* type error; errmsg already given */
15962 if (i == 1)
15963 item_compare_ic = TRUE;
15964 else
15965 item_compare_func = get_tv_string(&argvars[1]);
15969 /* Make an array with each entry pointing to an item in the List. */
15970 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
15971 if (ptrs == NULL)
15972 return;
15973 i = 0;
15974 for (li = l->lv_first; li != NULL; li = li->li_next)
15975 ptrs[i++] = li;
15977 item_compare_func_err = FALSE;
15978 /* test the compare function */
15979 if (item_compare_func != NULL
15980 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
15981 == ITEM_COMPARE_FAIL)
15982 EMSG(_("E702: Sort compare function failed"));
15983 else
15985 /* Sort the array with item pointers. */
15986 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
15987 item_compare_func == NULL ? item_compare : item_compare2);
15989 if (!item_compare_func_err)
15991 /* Clear the List and append the items in the sorted order. */
15992 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
15993 l->lv_len = 0;
15994 for (i = 0; i < len; ++i)
15995 list_append(l, ptrs[i]);
15999 vim_free(ptrs);
16004 * "soundfold({word})" function
16006 static void
16007 f_soundfold(argvars, rettv)
16008 typval_T *argvars;
16009 typval_T *rettv;
16011 char_u *s;
16013 rettv->v_type = VAR_STRING;
16014 s = get_tv_string(&argvars[0]);
16015 #ifdef FEAT_SPELL
16016 rettv->vval.v_string = eval_soundfold(s);
16017 #else
16018 rettv->vval.v_string = vim_strsave(s);
16019 #endif
16023 * "spellbadword()" function
16025 static void
16026 f_spellbadword(argvars, rettv)
16027 typval_T *argvars UNUSED;
16028 typval_T *rettv;
16030 char_u *word = (char_u *)"";
16031 hlf_T attr = HLF_COUNT;
16032 int len = 0;
16034 if (rettv_list_alloc(rettv) == FAIL)
16035 return;
16037 #ifdef FEAT_SPELL
16038 if (argvars[0].v_type == VAR_UNKNOWN)
16040 /* Find the start and length of the badly spelled word. */
16041 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
16042 if (len != 0)
16043 word = ml_get_cursor();
16045 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16047 char_u *str = get_tv_string_chk(&argvars[0]);
16048 int capcol = -1;
16050 if (str != NULL)
16052 /* Check the argument for spelling. */
16053 while (*str != NUL)
16055 len = spell_check(curwin, str, &attr, &capcol, FALSE);
16056 if (attr != HLF_COUNT)
16058 word = str;
16059 break;
16061 str += len;
16065 #endif
16067 list_append_string(rettv->vval.v_list, word, len);
16068 list_append_string(rettv->vval.v_list, (char_u *)(
16069 attr == HLF_SPB ? "bad" :
16070 attr == HLF_SPR ? "rare" :
16071 attr == HLF_SPL ? "local" :
16072 attr == HLF_SPC ? "caps" :
16073 ""), -1);
16077 * "spellsuggest()" function
16079 static void
16080 f_spellsuggest(argvars, rettv)
16081 typval_T *argvars UNUSED;
16082 typval_T *rettv;
16084 #ifdef FEAT_SPELL
16085 char_u *str;
16086 int typeerr = FALSE;
16087 int maxcount;
16088 garray_T ga;
16089 int i;
16090 listitem_T *li;
16091 int need_capital = FALSE;
16092 #endif
16094 if (rettv_list_alloc(rettv) == FAIL)
16095 return;
16097 #ifdef FEAT_SPELL
16098 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16100 str = get_tv_string(&argvars[0]);
16101 if (argvars[1].v_type != VAR_UNKNOWN)
16103 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
16104 if (maxcount <= 0)
16105 return;
16106 if (argvars[2].v_type != VAR_UNKNOWN)
16108 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
16109 if (typeerr)
16110 return;
16113 else
16114 maxcount = 25;
16116 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
16118 for (i = 0; i < ga.ga_len; ++i)
16120 str = ((char_u **)ga.ga_data)[i];
16122 li = listitem_alloc();
16123 if (li == NULL)
16124 vim_free(str);
16125 else
16127 li->li_tv.v_type = VAR_STRING;
16128 li->li_tv.v_lock = 0;
16129 li->li_tv.vval.v_string = str;
16130 list_append(rettv->vval.v_list, li);
16133 ga_clear(&ga);
16135 #endif
16138 static void
16139 f_split(argvars, rettv)
16140 typval_T *argvars;
16141 typval_T *rettv;
16143 char_u *str;
16144 char_u *end;
16145 char_u *pat = NULL;
16146 regmatch_T regmatch;
16147 char_u patbuf[NUMBUFLEN];
16148 char_u *save_cpo;
16149 int match;
16150 colnr_T col = 0;
16151 int keepempty = FALSE;
16152 int typeerr = FALSE;
16154 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
16155 save_cpo = p_cpo;
16156 p_cpo = (char_u *)"";
16158 str = get_tv_string(&argvars[0]);
16159 if (argvars[1].v_type != VAR_UNKNOWN)
16161 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16162 if (pat == NULL)
16163 typeerr = TRUE;
16164 if (argvars[2].v_type != VAR_UNKNOWN)
16165 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
16167 if (pat == NULL || *pat == NUL)
16168 pat = (char_u *)"[\\x01- ]\\+";
16170 if (rettv_list_alloc(rettv) == FAIL)
16171 return;
16172 if (typeerr)
16173 return;
16175 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
16176 if (regmatch.regprog != NULL)
16178 regmatch.rm_ic = FALSE;
16179 while (*str != NUL || keepempty)
16181 if (*str == NUL)
16182 match = FALSE; /* empty item at the end */
16183 else
16184 match = vim_regexec_nl(&regmatch, str, col);
16185 if (match)
16186 end = regmatch.startp[0];
16187 else
16188 end = str + STRLEN(str);
16189 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
16190 && *str != NUL && match && end < regmatch.endp[0]))
16192 if (list_append_string(rettv->vval.v_list, str,
16193 (int)(end - str)) == FAIL)
16194 break;
16196 if (!match)
16197 break;
16198 /* Advance to just after the match. */
16199 if (regmatch.endp[0] > str)
16200 col = 0;
16201 else
16203 /* Don't get stuck at the same match. */
16204 #ifdef FEAT_MBYTE
16205 col = (*mb_ptr2len)(regmatch.endp[0]);
16206 #else
16207 col = 1;
16208 #endif
16210 str = regmatch.endp[0];
16213 vim_free(regmatch.regprog);
16216 p_cpo = save_cpo;
16219 #ifdef FEAT_FLOAT
16221 * "sqrt()" function
16223 static void
16224 f_sqrt(argvars, rettv)
16225 typval_T *argvars;
16226 typval_T *rettv;
16228 float_T f;
16230 rettv->v_type = VAR_FLOAT;
16231 if (get_float_arg(argvars, &f) == OK)
16232 rettv->vval.v_float = sqrt(f);
16233 else
16234 rettv->vval.v_float = 0.0;
16238 * "str2float()" function
16240 static void
16241 f_str2float(argvars, rettv)
16242 typval_T *argvars;
16243 typval_T *rettv;
16245 char_u *p = skipwhite(get_tv_string(&argvars[0]));
16247 if (*p == '+')
16248 p = skipwhite(p + 1);
16249 (void)string2float(p, &rettv->vval.v_float);
16250 rettv->v_type = VAR_FLOAT;
16252 #endif
16255 * "str2nr()" function
16257 static void
16258 f_str2nr(argvars, rettv)
16259 typval_T *argvars;
16260 typval_T *rettv;
16262 int base = 10;
16263 char_u *p;
16264 long n;
16266 if (argvars[1].v_type != VAR_UNKNOWN)
16268 base = get_tv_number(&argvars[1]);
16269 if (base != 8 && base != 10 && base != 16)
16271 EMSG(_(e_invarg));
16272 return;
16276 p = skipwhite(get_tv_string(&argvars[0]));
16277 if (*p == '+')
16278 p = skipwhite(p + 1);
16279 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
16280 rettv->vval.v_number = n;
16283 #ifdef HAVE_STRFTIME
16285 * "strftime({format}[, {time}])" function
16287 static void
16288 f_strftime(argvars, rettv)
16289 typval_T *argvars;
16290 typval_T *rettv;
16292 char_u result_buf[256];
16293 struct tm *curtime;
16294 time_t seconds;
16295 char_u *p;
16297 rettv->v_type = VAR_STRING;
16299 p = get_tv_string(&argvars[0]);
16300 if (argvars[1].v_type == VAR_UNKNOWN)
16301 seconds = time(NULL);
16302 else
16303 seconds = (time_t)get_tv_number(&argvars[1]);
16304 curtime = localtime(&seconds);
16305 /* MSVC returns NULL for an invalid value of seconds. */
16306 if (curtime == NULL)
16307 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
16308 else
16310 # ifdef FEAT_MBYTE
16311 vimconv_T conv;
16312 char_u *enc;
16314 conv.vc_type = CONV_NONE;
16315 enc = enc_locale();
16316 convert_setup(&conv, p_enc, enc);
16317 if (conv.vc_type != CONV_NONE)
16318 p = string_convert(&conv, p, NULL);
16319 # endif
16320 if (p != NULL)
16321 (void)strftime((char *)result_buf, sizeof(result_buf),
16322 (char *)p, curtime);
16323 else
16324 result_buf[0] = NUL;
16326 # ifdef FEAT_MBYTE
16327 if (conv.vc_type != CONV_NONE)
16328 vim_free(p);
16329 convert_setup(&conv, enc, p_enc);
16330 if (conv.vc_type != CONV_NONE)
16331 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
16332 else
16333 # endif
16334 rettv->vval.v_string = vim_strsave(result_buf);
16336 # ifdef FEAT_MBYTE
16337 /* Release conversion descriptors */
16338 convert_setup(&conv, NULL, NULL);
16339 vim_free(enc);
16340 # endif
16343 #endif
16346 * "stridx()" function
16348 static void
16349 f_stridx(argvars, rettv)
16350 typval_T *argvars;
16351 typval_T *rettv;
16353 char_u buf[NUMBUFLEN];
16354 char_u *needle;
16355 char_u *haystack;
16356 char_u *save_haystack;
16357 char_u *pos;
16358 int start_idx;
16360 needle = get_tv_string_chk(&argvars[1]);
16361 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
16362 rettv->vval.v_number = -1;
16363 if (needle == NULL || haystack == NULL)
16364 return; /* type error; errmsg already given */
16366 if (argvars[2].v_type != VAR_UNKNOWN)
16368 int error = FALSE;
16370 start_idx = get_tv_number_chk(&argvars[2], &error);
16371 if (error || start_idx >= (int)STRLEN(haystack))
16372 return;
16373 if (start_idx >= 0)
16374 haystack += start_idx;
16377 pos = (char_u *)strstr((char *)haystack, (char *)needle);
16378 if (pos != NULL)
16379 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
16383 * "string()" function
16385 static void
16386 f_string(argvars, rettv)
16387 typval_T *argvars;
16388 typval_T *rettv;
16390 char_u *tofree;
16391 char_u numbuf[NUMBUFLEN];
16393 rettv->v_type = VAR_STRING;
16394 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
16395 /* Make a copy if we have a value but it's not in allocated memory. */
16396 if (rettv->vval.v_string != NULL && tofree == NULL)
16397 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
16401 * "strlen()" function
16403 static void
16404 f_strlen(argvars, rettv)
16405 typval_T *argvars;
16406 typval_T *rettv;
16408 rettv->vval.v_number = (varnumber_T)(STRLEN(
16409 get_tv_string(&argvars[0])));
16413 * "strpart()" function
16415 static void
16416 f_strpart(argvars, rettv)
16417 typval_T *argvars;
16418 typval_T *rettv;
16420 char_u *p;
16421 int n;
16422 int len;
16423 int slen;
16424 int error = FALSE;
16426 p = get_tv_string(&argvars[0]);
16427 slen = (int)STRLEN(p);
16429 n = get_tv_number_chk(&argvars[1], &error);
16430 if (error)
16431 len = 0;
16432 else if (argvars[2].v_type != VAR_UNKNOWN)
16433 len = get_tv_number(&argvars[2]);
16434 else
16435 len = slen - n; /* default len: all bytes that are available. */
16438 * Only return the overlap between the specified part and the actual
16439 * string.
16441 if (n < 0)
16443 len += n;
16444 n = 0;
16446 else if (n > slen)
16447 n = slen;
16448 if (len < 0)
16449 len = 0;
16450 else if (n + len > slen)
16451 len = slen - n;
16453 rettv->v_type = VAR_STRING;
16454 rettv->vval.v_string = vim_strnsave(p + n, len);
16458 * "strridx()" function
16460 static void
16461 f_strridx(argvars, rettv)
16462 typval_T *argvars;
16463 typval_T *rettv;
16465 char_u buf[NUMBUFLEN];
16466 char_u *needle;
16467 char_u *haystack;
16468 char_u *rest;
16469 char_u *lastmatch = NULL;
16470 int haystack_len, end_idx;
16472 needle = get_tv_string_chk(&argvars[1]);
16473 haystack = get_tv_string_buf_chk(&argvars[0], buf);
16475 rettv->vval.v_number = -1;
16476 if (needle == NULL || haystack == NULL)
16477 return; /* type error; errmsg already given */
16479 haystack_len = (int)STRLEN(haystack);
16480 if (argvars[2].v_type != VAR_UNKNOWN)
16482 /* Third argument: upper limit for index */
16483 end_idx = get_tv_number_chk(&argvars[2], NULL);
16484 if (end_idx < 0)
16485 return; /* can never find a match */
16487 else
16488 end_idx = haystack_len;
16490 if (*needle == NUL)
16492 /* Empty string matches past the end. */
16493 lastmatch = haystack + end_idx;
16495 else
16497 for (rest = haystack; *rest != '\0'; ++rest)
16499 rest = (char_u *)strstr((char *)rest, (char *)needle);
16500 if (rest == NULL || rest > haystack + end_idx)
16501 break;
16502 lastmatch = rest;
16506 if (lastmatch == NULL)
16507 rettv->vval.v_number = -1;
16508 else
16509 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
16513 * "strtrans()" function
16515 static void
16516 f_strtrans(argvars, rettv)
16517 typval_T *argvars;
16518 typval_T *rettv;
16520 rettv->v_type = VAR_STRING;
16521 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
16525 * "submatch()" function
16527 static void
16528 f_submatch(argvars, rettv)
16529 typval_T *argvars;
16530 typval_T *rettv;
16532 rettv->v_type = VAR_STRING;
16533 rettv->vval.v_string =
16534 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
16538 * "substitute()" function
16540 static void
16541 f_substitute(argvars, rettv)
16542 typval_T *argvars;
16543 typval_T *rettv;
16545 char_u patbuf[NUMBUFLEN];
16546 char_u subbuf[NUMBUFLEN];
16547 char_u flagsbuf[NUMBUFLEN];
16549 char_u *str = get_tv_string_chk(&argvars[0]);
16550 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16551 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
16552 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
16554 rettv->v_type = VAR_STRING;
16555 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
16556 rettv->vval.v_string = NULL;
16557 else
16558 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
16562 * "synID(lnum, col, trans)" function
16564 static void
16565 f_synID(argvars, rettv)
16566 typval_T *argvars UNUSED;
16567 typval_T *rettv;
16569 int id = 0;
16570 #ifdef FEAT_SYN_HL
16571 long lnum;
16572 long col;
16573 int trans;
16574 int transerr = FALSE;
16576 lnum = get_tv_lnum(argvars); /* -1 on type error */
16577 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16578 trans = get_tv_number_chk(&argvars[2], &transerr);
16580 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16581 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
16582 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
16583 #endif
16585 rettv->vval.v_number = id;
16589 * "synIDattr(id, what [, mode])" function
16591 static void
16592 f_synIDattr(argvars, rettv)
16593 typval_T *argvars UNUSED;
16594 typval_T *rettv;
16596 char_u *p = NULL;
16597 #ifdef FEAT_SYN_HL
16598 int id;
16599 char_u *what;
16600 char_u *mode;
16601 char_u modebuf[NUMBUFLEN];
16602 int modec;
16604 id = get_tv_number(&argvars[0]);
16605 what = get_tv_string(&argvars[1]);
16606 if (argvars[2].v_type != VAR_UNKNOWN)
16608 mode = get_tv_string_buf(&argvars[2], modebuf);
16609 modec = TOLOWER_ASC(mode[0]);
16610 if (modec != 't' && modec != 'c'
16611 #ifdef FEAT_GUI
16612 && modec != 'g'
16613 #endif
16615 modec = 0; /* replace invalid with current */
16617 else
16619 #ifdef FEAT_GUI
16620 if (gui.in_use)
16621 modec = 'g';
16622 else
16623 #endif
16624 if (t_colors > 1)
16625 modec = 'c';
16626 else
16627 modec = 't';
16631 switch (TOLOWER_ASC(what[0]))
16633 case 'b':
16634 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
16635 p = highlight_color(id, what, modec);
16636 else /* bold */
16637 p = highlight_has_attr(id, HL_BOLD, modec);
16638 break;
16640 case 'f': /* fg[#] or font */
16641 p = highlight_color(id, what, modec);
16642 break;
16644 case 'i':
16645 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
16646 p = highlight_has_attr(id, HL_INVERSE, modec);
16647 else /* italic */
16648 p = highlight_has_attr(id, HL_ITALIC, modec);
16649 break;
16651 case 'n': /* name */
16652 p = get_highlight_name(NULL, id - 1);
16653 break;
16655 case 'r': /* reverse */
16656 p = highlight_has_attr(id, HL_INVERSE, modec);
16657 break;
16659 case 's':
16660 if (TOLOWER_ASC(what[1]) == 'p') /* sp[#] */
16661 p = highlight_color(id, what, modec);
16662 else /* standout */
16663 p = highlight_has_attr(id, HL_STANDOUT, modec);
16664 break;
16666 case 'u':
16667 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
16668 /* underline */
16669 p = highlight_has_attr(id, HL_UNDERLINE, modec);
16670 else
16671 /* undercurl */
16672 p = highlight_has_attr(id, HL_UNDERCURL, modec);
16673 break;
16676 if (p != NULL)
16677 p = vim_strsave(p);
16678 #endif
16679 rettv->v_type = VAR_STRING;
16680 rettv->vval.v_string = p;
16684 * "synIDtrans(id)" function
16686 static void
16687 f_synIDtrans(argvars, rettv)
16688 typval_T *argvars UNUSED;
16689 typval_T *rettv;
16691 int id;
16693 #ifdef FEAT_SYN_HL
16694 id = get_tv_number(&argvars[0]);
16696 if (id > 0)
16697 id = syn_get_final_id(id);
16698 else
16699 #endif
16700 id = 0;
16702 rettv->vval.v_number = id;
16706 * "synstack(lnum, col)" function
16708 static void
16709 f_synstack(argvars, rettv)
16710 typval_T *argvars UNUSED;
16711 typval_T *rettv;
16713 #ifdef FEAT_SYN_HL
16714 long lnum;
16715 long col;
16716 int i;
16717 int id;
16718 #endif
16720 rettv->v_type = VAR_LIST;
16721 rettv->vval.v_list = NULL;
16723 #ifdef FEAT_SYN_HL
16724 lnum = get_tv_lnum(argvars); /* -1 on type error */
16725 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16727 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16728 && col >= 0 && (col == 0 || col < (long)STRLEN(ml_get(lnum)))
16729 && rettv_list_alloc(rettv) != FAIL)
16731 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
16732 for (i = 0; ; ++i)
16734 id = syn_get_stack_item(i);
16735 if (id < 0)
16736 break;
16737 if (list_append_number(rettv->vval.v_list, id) == FAIL)
16738 break;
16741 #endif
16745 * "system()" function
16747 static void
16748 f_system(argvars, rettv)
16749 typval_T *argvars;
16750 typval_T *rettv;
16752 char_u *res = NULL;
16753 char_u *p;
16754 char_u *infile = NULL;
16755 char_u buf[NUMBUFLEN];
16756 int err = FALSE;
16757 FILE *fd;
16759 if (check_restricted() || check_secure())
16760 goto done;
16762 if (argvars[1].v_type != VAR_UNKNOWN)
16765 * Write the string to a temp file, to be used for input of the shell
16766 * command.
16768 if ((infile = vim_tempname('i')) == NULL)
16770 EMSG(_(e_notmp));
16771 goto done;
16774 fd = mch_fopen((char *)infile, WRITEBIN);
16775 if (fd == NULL)
16777 EMSG2(_(e_notopen), infile);
16778 goto done;
16780 p = get_tv_string_buf_chk(&argvars[1], buf);
16781 if (p == NULL)
16783 fclose(fd);
16784 goto done; /* type error; errmsg already given */
16786 if (fwrite(p, STRLEN(p), 1, fd) != 1)
16787 err = TRUE;
16788 if (fclose(fd) != 0)
16789 err = TRUE;
16790 if (err)
16792 EMSG(_("E677: Error writing temp file"));
16793 goto done;
16797 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
16798 SHELL_SILENT | SHELL_COOKED);
16800 #ifdef USE_CR
16801 /* translate <CR> into <NL> */
16802 if (res != NULL)
16804 char_u *s;
16806 for (s = res; *s; ++s)
16808 if (*s == CAR)
16809 *s = NL;
16812 #else
16813 # ifdef USE_CRNL
16814 /* translate <CR><NL> into <NL> */
16815 if (res != NULL)
16817 char_u *s, *d;
16819 d = res;
16820 for (s = res; *s; ++s)
16822 if (s[0] == CAR && s[1] == NL)
16823 ++s;
16824 *d++ = *s;
16826 *d = NUL;
16828 # endif
16829 #endif
16831 done:
16832 if (infile != NULL)
16834 mch_remove(infile);
16835 vim_free(infile);
16837 rettv->v_type = VAR_STRING;
16838 rettv->vval.v_string = res;
16842 * "tabpagebuflist()" function
16844 static void
16845 f_tabpagebuflist(argvars, rettv)
16846 typval_T *argvars UNUSED;
16847 typval_T *rettv UNUSED;
16849 #ifdef FEAT_WINDOWS
16850 tabpage_T *tp;
16851 win_T *wp = NULL;
16853 if (argvars[0].v_type == VAR_UNKNOWN)
16854 wp = firstwin;
16855 else
16857 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16858 if (tp != NULL)
16859 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16861 if (wp != NULL && rettv_list_alloc(rettv) != FAIL)
16863 for (; wp != NULL; wp = wp->w_next)
16864 if (list_append_number(rettv->vval.v_list,
16865 wp->w_buffer->b_fnum) == FAIL)
16866 break;
16868 #endif
16873 * "tabpagenr()" function
16875 static void
16876 f_tabpagenr(argvars, rettv)
16877 typval_T *argvars UNUSED;
16878 typval_T *rettv;
16880 int nr = 1;
16881 #ifdef FEAT_WINDOWS
16882 char_u *arg;
16884 if (argvars[0].v_type != VAR_UNKNOWN)
16886 arg = get_tv_string_chk(&argvars[0]);
16887 nr = 0;
16888 if (arg != NULL)
16890 if (STRCMP(arg, "$") == 0)
16891 nr = tabpage_index(NULL) - 1;
16892 else
16893 EMSG2(_(e_invexpr2), arg);
16896 else
16897 nr = tabpage_index(curtab);
16898 #endif
16899 rettv->vval.v_number = nr;
16903 #ifdef FEAT_WINDOWS
16904 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
16907 * Common code for tabpagewinnr() and winnr().
16909 static int
16910 get_winnr(tp, argvar)
16911 tabpage_T *tp;
16912 typval_T *argvar;
16914 win_T *twin;
16915 int nr = 1;
16916 win_T *wp;
16917 char_u *arg;
16919 twin = (tp == curtab) ? curwin : tp->tp_curwin;
16920 if (argvar->v_type != VAR_UNKNOWN)
16922 arg = get_tv_string_chk(argvar);
16923 if (arg == NULL)
16924 nr = 0; /* type error; errmsg already given */
16925 else if (STRCMP(arg, "$") == 0)
16926 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
16927 else if (STRCMP(arg, "#") == 0)
16929 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
16930 if (twin == NULL)
16931 nr = 0;
16933 else
16935 EMSG2(_(e_invexpr2), arg);
16936 nr = 0;
16940 if (nr > 0)
16941 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16942 wp != twin; wp = wp->w_next)
16944 if (wp == NULL)
16946 /* didn't find it in this tabpage */
16947 nr = 0;
16948 break;
16950 ++nr;
16952 return nr;
16954 #endif
16957 * "tabpagewinnr()" function
16959 static void
16960 f_tabpagewinnr(argvars, rettv)
16961 typval_T *argvars UNUSED;
16962 typval_T *rettv;
16964 int nr = 1;
16965 #ifdef FEAT_WINDOWS
16966 tabpage_T *tp;
16968 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16969 if (tp == NULL)
16970 nr = 0;
16971 else
16972 nr = get_winnr(tp, &argvars[1]);
16973 #endif
16974 rettv->vval.v_number = nr;
16979 * "tagfiles()" function
16981 static void
16982 f_tagfiles(argvars, rettv)
16983 typval_T *argvars UNUSED;
16984 typval_T *rettv;
16986 char_u fname[MAXPATHL + 1];
16987 tagname_T tn;
16988 int first;
16990 if (rettv_list_alloc(rettv) == FAIL)
16991 return;
16993 for (first = TRUE; ; first = FALSE)
16994 if (get_tagfname(&tn, first, fname) == FAIL
16995 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
16996 break;
16997 tagname_free(&tn);
17001 * "taglist()" function
17003 static void
17004 f_taglist(argvars, rettv)
17005 typval_T *argvars;
17006 typval_T *rettv;
17008 char_u *tag_pattern;
17010 tag_pattern = get_tv_string(&argvars[0]);
17012 rettv->vval.v_number = FALSE;
17013 if (*tag_pattern == NUL)
17014 return;
17016 if (rettv_list_alloc(rettv) == OK)
17017 (void)get_tags(rettv->vval.v_list, tag_pattern);
17021 * "tempname()" function
17023 static void
17024 f_tempname(argvars, rettv)
17025 typval_T *argvars UNUSED;
17026 typval_T *rettv;
17028 static int x = 'A';
17030 rettv->v_type = VAR_STRING;
17031 rettv->vval.v_string = vim_tempname(x);
17033 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
17034 * names. Skip 'I' and 'O', they are used for shell redirection. */
17037 if (x == 'Z')
17038 x = '0';
17039 else if (x == '9')
17040 x = 'A';
17041 else
17043 #ifdef EBCDIC
17044 if (x == 'I')
17045 x = 'J';
17046 else if (x == 'R')
17047 x = 'S';
17048 else
17049 #endif
17050 ++x;
17052 } while (x == 'I' || x == 'O');
17056 * "test(list)" function: Just checking the walls...
17058 static void
17059 f_test(argvars, rettv)
17060 typval_T *argvars UNUSED;
17061 typval_T *rettv UNUSED;
17063 /* Used for unit testing. Change the code below to your liking. */
17064 #if 0
17065 listitem_T *li;
17066 list_T *l;
17067 char_u *bad, *good;
17069 if (argvars[0].v_type != VAR_LIST)
17070 return;
17071 l = argvars[0].vval.v_list;
17072 if (l == NULL)
17073 return;
17074 li = l->lv_first;
17075 if (li == NULL)
17076 return;
17077 bad = get_tv_string(&li->li_tv);
17078 li = li->li_next;
17079 if (li == NULL)
17080 return;
17081 good = get_tv_string(&li->li_tv);
17082 rettv->vval.v_number = test_edit_score(bad, good);
17083 #endif
17087 * "tolower(string)" function
17089 static void
17090 f_tolower(argvars, rettv)
17091 typval_T *argvars;
17092 typval_T *rettv;
17094 char_u *p;
17096 p = vim_strsave(get_tv_string(&argvars[0]));
17097 rettv->v_type = VAR_STRING;
17098 rettv->vval.v_string = p;
17100 if (p != NULL)
17101 while (*p != NUL)
17103 #ifdef FEAT_MBYTE
17104 int l;
17106 if (enc_utf8)
17108 int c, lc;
17110 c = utf_ptr2char(p);
17111 lc = utf_tolower(c);
17112 l = utf_ptr2len(p);
17113 /* TODO: reallocate string when byte count changes. */
17114 if (utf_char2len(lc) == l)
17115 utf_char2bytes(lc, p);
17116 p += l;
17118 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
17119 p += l; /* skip multi-byte character */
17120 else
17121 #endif
17123 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
17124 ++p;
17130 * "toupper(string)" function
17132 static void
17133 f_toupper(argvars, rettv)
17134 typval_T *argvars;
17135 typval_T *rettv;
17137 rettv->v_type = VAR_STRING;
17138 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
17142 * "tr(string, fromstr, tostr)" function
17144 static void
17145 f_tr(argvars, rettv)
17146 typval_T *argvars;
17147 typval_T *rettv;
17149 char_u *instr;
17150 char_u *fromstr;
17151 char_u *tostr;
17152 char_u *p;
17153 #ifdef FEAT_MBYTE
17154 int inlen;
17155 int fromlen;
17156 int tolen;
17157 int idx;
17158 char_u *cpstr;
17159 int cplen;
17160 int first = TRUE;
17161 #endif
17162 char_u buf[NUMBUFLEN];
17163 char_u buf2[NUMBUFLEN];
17164 garray_T ga;
17166 instr = get_tv_string(&argvars[0]);
17167 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
17168 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
17170 /* Default return value: empty string. */
17171 rettv->v_type = VAR_STRING;
17172 rettv->vval.v_string = NULL;
17173 if (fromstr == NULL || tostr == NULL)
17174 return; /* type error; errmsg already given */
17175 ga_init2(&ga, (int)sizeof(char), 80);
17177 #ifdef FEAT_MBYTE
17178 if (!has_mbyte)
17179 #endif
17180 /* not multi-byte: fromstr and tostr must be the same length */
17181 if (STRLEN(fromstr) != STRLEN(tostr))
17183 #ifdef FEAT_MBYTE
17184 error:
17185 #endif
17186 EMSG2(_(e_invarg2), fromstr);
17187 ga_clear(&ga);
17188 return;
17191 /* fromstr and tostr have to contain the same number of chars */
17192 while (*instr != NUL)
17194 #ifdef FEAT_MBYTE
17195 if (has_mbyte)
17197 inlen = (*mb_ptr2len)(instr);
17198 cpstr = instr;
17199 cplen = inlen;
17200 idx = 0;
17201 for (p = fromstr; *p != NUL; p += fromlen)
17203 fromlen = (*mb_ptr2len)(p);
17204 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
17206 for (p = tostr; *p != NUL; p += tolen)
17208 tolen = (*mb_ptr2len)(p);
17209 if (idx-- == 0)
17211 cplen = tolen;
17212 cpstr = p;
17213 break;
17216 if (*p == NUL) /* tostr is shorter than fromstr */
17217 goto error;
17218 break;
17220 ++idx;
17223 if (first && cpstr == instr)
17225 /* Check that fromstr and tostr have the same number of
17226 * (multi-byte) characters. Done only once when a character
17227 * of instr doesn't appear in fromstr. */
17228 first = FALSE;
17229 for (p = tostr; *p != NUL; p += tolen)
17231 tolen = (*mb_ptr2len)(p);
17232 --idx;
17234 if (idx != 0)
17235 goto error;
17238 ga_grow(&ga, cplen);
17239 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
17240 ga.ga_len += cplen;
17242 instr += inlen;
17244 else
17245 #endif
17247 /* When not using multi-byte chars we can do it faster. */
17248 p = vim_strchr(fromstr, *instr);
17249 if (p != NULL)
17250 ga_append(&ga, tostr[p - fromstr]);
17251 else
17252 ga_append(&ga, *instr);
17253 ++instr;
17257 /* add a terminating NUL */
17258 ga_grow(&ga, 1);
17259 ga_append(&ga, NUL);
17261 rettv->vval.v_string = ga.ga_data;
17264 #ifdef FEAT_FLOAT
17266 * "trunc({float})" function
17268 static void
17269 f_trunc(argvars, rettv)
17270 typval_T *argvars;
17271 typval_T *rettv;
17273 float_T f;
17275 rettv->v_type = VAR_FLOAT;
17276 if (get_float_arg(argvars, &f) == OK)
17277 /* trunc() is not in C90, use floor() or ceil() instead. */
17278 rettv->vval.v_float = f > 0 ? floor(f) : ceil(f);
17279 else
17280 rettv->vval.v_float = 0.0;
17282 #endif
17285 * "type(expr)" function
17287 static void
17288 f_type(argvars, rettv)
17289 typval_T *argvars;
17290 typval_T *rettv;
17292 int n;
17294 switch (argvars[0].v_type)
17296 case VAR_NUMBER: n = 0; break;
17297 case VAR_STRING: n = 1; break;
17298 case VAR_FUNC: n = 2; break;
17299 case VAR_LIST: n = 3; break;
17300 case VAR_DICT: n = 4; break;
17301 #ifdef FEAT_FLOAT
17302 case VAR_FLOAT: n = 5; break;
17303 #endif
17304 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
17306 rettv->vval.v_number = n;
17310 * "values(dict)" function
17312 static void
17313 f_values(argvars, rettv)
17314 typval_T *argvars;
17315 typval_T *rettv;
17317 dict_list(argvars, rettv, 1);
17321 * "virtcol(string)" function
17323 static void
17324 f_virtcol(argvars, rettv)
17325 typval_T *argvars;
17326 typval_T *rettv;
17328 colnr_T vcol = 0;
17329 pos_T *fp;
17330 int fnum = curbuf->b_fnum;
17332 fp = var2fpos(&argvars[0], FALSE, &fnum);
17333 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
17334 && fnum == curbuf->b_fnum)
17336 getvvcol(curwin, fp, NULL, NULL, &vcol);
17337 ++vcol;
17340 rettv->vval.v_number = vcol;
17344 * "visualmode()" function
17346 static void
17347 f_visualmode(argvars, rettv)
17348 typval_T *argvars UNUSED;
17349 typval_T *rettv UNUSED;
17351 #ifdef FEAT_VISUAL
17352 char_u str[2];
17354 rettv->v_type = VAR_STRING;
17355 str[0] = curbuf->b_visual_mode_eval;
17356 str[1] = NUL;
17357 rettv->vval.v_string = vim_strsave(str);
17359 /* A non-zero number or non-empty string argument: reset mode. */
17360 if (non_zero_arg(&argvars[0]))
17361 curbuf->b_visual_mode_eval = NUL;
17362 #endif
17366 * "winbufnr(nr)" function
17368 static void
17369 f_winbufnr(argvars, rettv)
17370 typval_T *argvars;
17371 typval_T *rettv;
17373 win_T *wp;
17375 wp = find_win_by_nr(&argvars[0], NULL);
17376 if (wp == NULL)
17377 rettv->vval.v_number = -1;
17378 else
17379 rettv->vval.v_number = wp->w_buffer->b_fnum;
17383 * "wincol()" function
17385 static void
17386 f_wincol(argvars, rettv)
17387 typval_T *argvars UNUSED;
17388 typval_T *rettv;
17390 validate_cursor();
17391 rettv->vval.v_number = curwin->w_wcol + 1;
17395 * "winheight(nr)" function
17397 static void
17398 f_winheight(argvars, rettv)
17399 typval_T *argvars;
17400 typval_T *rettv;
17402 win_T *wp;
17404 wp = find_win_by_nr(&argvars[0], NULL);
17405 if (wp == NULL)
17406 rettv->vval.v_number = -1;
17407 else
17408 rettv->vval.v_number = wp->w_height;
17412 * "winline()" function
17414 static void
17415 f_winline(argvars, rettv)
17416 typval_T *argvars UNUSED;
17417 typval_T *rettv;
17419 validate_cursor();
17420 rettv->vval.v_number = curwin->w_wrow + 1;
17424 * "winnr()" function
17426 static void
17427 f_winnr(argvars, rettv)
17428 typval_T *argvars UNUSED;
17429 typval_T *rettv;
17431 int nr = 1;
17433 #ifdef FEAT_WINDOWS
17434 nr = get_winnr(curtab, &argvars[0]);
17435 #endif
17436 rettv->vval.v_number = nr;
17440 * "winrestcmd()" function
17442 static void
17443 f_winrestcmd(argvars, rettv)
17444 typval_T *argvars UNUSED;
17445 typval_T *rettv;
17447 #ifdef FEAT_WINDOWS
17448 win_T *wp;
17449 int winnr = 1;
17450 garray_T ga;
17451 char_u buf[50];
17453 ga_init2(&ga, (int)sizeof(char), 70);
17454 for (wp = firstwin; wp != NULL; wp = wp->w_next)
17456 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
17457 ga_concat(&ga, buf);
17458 # ifdef FEAT_VERTSPLIT
17459 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
17460 ga_concat(&ga, buf);
17461 # endif
17462 ++winnr;
17464 ga_append(&ga, NUL);
17466 rettv->vval.v_string = ga.ga_data;
17467 #else
17468 rettv->vval.v_string = NULL;
17469 #endif
17470 rettv->v_type = VAR_STRING;
17474 * "winrestview()" function
17476 static void
17477 f_winrestview(argvars, rettv)
17478 typval_T *argvars;
17479 typval_T *rettv UNUSED;
17481 dict_T *dict;
17483 if (argvars[0].v_type != VAR_DICT
17484 || (dict = argvars[0].vval.v_dict) == NULL)
17485 EMSG(_(e_invarg));
17486 else
17488 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
17489 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
17490 #ifdef FEAT_VIRTUALEDIT
17491 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
17492 #endif
17493 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
17494 curwin->w_set_curswant = FALSE;
17496 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
17497 #ifdef FEAT_DIFF
17498 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
17499 #endif
17500 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
17501 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
17503 check_cursor();
17504 changed_cline_bef_curs();
17505 invalidate_botline();
17506 redraw_later(VALID);
17508 if (curwin->w_topline == 0)
17509 curwin->w_topline = 1;
17510 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
17511 curwin->w_topline = curbuf->b_ml.ml_line_count;
17512 #ifdef FEAT_DIFF
17513 check_topfill(curwin, TRUE);
17514 #endif
17519 * "winsaveview()" function
17521 static void
17522 f_winsaveview(argvars, rettv)
17523 typval_T *argvars UNUSED;
17524 typval_T *rettv;
17526 dict_T *dict;
17528 dict = dict_alloc();
17529 if (dict == NULL)
17530 return;
17531 rettv->v_type = VAR_DICT;
17532 rettv->vval.v_dict = dict;
17533 ++dict->dv_refcount;
17535 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
17536 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
17537 #ifdef FEAT_VIRTUALEDIT
17538 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
17539 #endif
17540 update_curswant();
17541 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
17543 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
17544 #ifdef FEAT_DIFF
17545 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
17546 #endif
17547 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
17548 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
17552 * "winwidth(nr)" function
17554 static void
17555 f_winwidth(argvars, rettv)
17556 typval_T *argvars;
17557 typval_T *rettv;
17559 win_T *wp;
17561 wp = find_win_by_nr(&argvars[0], NULL);
17562 if (wp == NULL)
17563 rettv->vval.v_number = -1;
17564 else
17565 #ifdef FEAT_VERTSPLIT
17566 rettv->vval.v_number = wp->w_width;
17567 #else
17568 rettv->vval.v_number = Columns;
17569 #endif
17573 * "writefile()" function
17575 static void
17576 f_writefile(argvars, rettv)
17577 typval_T *argvars;
17578 typval_T *rettv;
17580 int binary = FALSE;
17581 char_u *fname;
17582 FILE *fd;
17583 listitem_T *li;
17584 char_u *s;
17585 int ret = 0;
17586 int c;
17588 if (check_restricted() || check_secure())
17589 return;
17591 if (argvars[0].v_type != VAR_LIST)
17593 EMSG2(_(e_listarg), "writefile()");
17594 return;
17596 if (argvars[0].vval.v_list == NULL)
17597 return;
17599 if (argvars[2].v_type != VAR_UNKNOWN
17600 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
17601 binary = TRUE;
17603 /* Always open the file in binary mode, library functions have a mind of
17604 * their own about CR-LF conversion. */
17605 fname = get_tv_string(&argvars[1]);
17606 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
17608 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
17609 ret = -1;
17611 else
17613 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
17614 li = li->li_next)
17616 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
17618 if (*s == '\n')
17619 c = putc(NUL, fd);
17620 else
17621 c = putc(*s, fd);
17622 if (c == EOF)
17624 ret = -1;
17625 break;
17628 if (!binary || li->li_next != NULL)
17629 if (putc('\n', fd) == EOF)
17631 ret = -1;
17632 break;
17634 if (ret < 0)
17636 EMSG(_(e_write));
17637 break;
17640 fclose(fd);
17643 rettv->vval.v_number = ret;
17647 * Translate a String variable into a position.
17648 * Returns NULL when there is an error.
17650 static pos_T *
17651 var2fpos(varp, dollar_lnum, fnum)
17652 typval_T *varp;
17653 int dollar_lnum; /* TRUE when $ is last line */
17654 int *fnum; /* set to fnum for '0, 'A, etc. */
17656 char_u *name;
17657 static pos_T pos;
17658 pos_T *pp;
17660 /* Argument can be [lnum, col, coladd]. */
17661 if (varp->v_type == VAR_LIST)
17663 list_T *l;
17664 int len;
17665 int error = FALSE;
17666 listitem_T *li;
17668 l = varp->vval.v_list;
17669 if (l == NULL)
17670 return NULL;
17672 /* Get the line number */
17673 pos.lnum = list_find_nr(l, 0L, &error);
17674 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
17675 return NULL; /* invalid line number */
17677 /* Get the column number */
17678 pos.col = list_find_nr(l, 1L, &error);
17679 if (error)
17680 return NULL;
17681 len = (long)STRLEN(ml_get(pos.lnum));
17683 /* We accept "$" for the column number: last column. */
17684 li = list_find(l, 1L);
17685 if (li != NULL && li->li_tv.v_type == VAR_STRING
17686 && li->li_tv.vval.v_string != NULL
17687 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
17688 pos.col = len + 1;
17690 /* Accept a position up to the NUL after the line. */
17691 if (pos.col == 0 || (int)pos.col > len + 1)
17692 return NULL; /* invalid column number */
17693 --pos.col;
17695 #ifdef FEAT_VIRTUALEDIT
17696 /* Get the virtual offset. Defaults to zero. */
17697 pos.coladd = list_find_nr(l, 2L, &error);
17698 if (error)
17699 pos.coladd = 0;
17700 #endif
17702 return &pos;
17705 name = get_tv_string_chk(varp);
17706 if (name == NULL)
17707 return NULL;
17708 if (name[0] == '.') /* cursor */
17709 return &curwin->w_cursor;
17710 #ifdef FEAT_VISUAL
17711 if (name[0] == 'v' && name[1] == NUL) /* Visual start */
17713 if (VIsual_active)
17714 return &VIsual;
17715 return &curwin->w_cursor;
17717 #endif
17718 if (name[0] == '\'') /* mark */
17720 pp = getmark_fnum(name[1], FALSE, fnum);
17721 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
17722 return NULL;
17723 return pp;
17726 #ifdef FEAT_VIRTUALEDIT
17727 pos.coladd = 0;
17728 #endif
17730 if (name[0] == 'w' && dollar_lnum)
17732 pos.col = 0;
17733 if (name[1] == '0') /* "w0": first visible line */
17735 update_topline();
17736 pos.lnum = curwin->w_topline;
17737 return &pos;
17739 else if (name[1] == '$') /* "w$": last visible line */
17741 validate_botline();
17742 pos.lnum = curwin->w_botline - 1;
17743 return &pos;
17746 else if (name[0] == '$') /* last column or line */
17748 if (dollar_lnum)
17750 pos.lnum = curbuf->b_ml.ml_line_count;
17751 pos.col = 0;
17753 else
17755 pos.lnum = curwin->w_cursor.lnum;
17756 pos.col = (colnr_T)STRLEN(ml_get_curline());
17758 return &pos;
17760 return NULL;
17764 * Convert list in "arg" into a position and optional file number.
17765 * When "fnump" is NULL there is no file number, only 3 items.
17766 * Note that the column is passed on as-is, the caller may want to decrement
17767 * it to use 1 for the first column.
17768 * Return FAIL when conversion is not possible, doesn't check the position for
17769 * validity.
17771 static int
17772 list2fpos(arg, posp, fnump)
17773 typval_T *arg;
17774 pos_T *posp;
17775 int *fnump;
17777 list_T *l = arg->vval.v_list;
17778 long i = 0;
17779 long n;
17781 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
17782 * when "fnump" isn't NULL and "coladd" is optional. */
17783 if (arg->v_type != VAR_LIST
17784 || l == NULL
17785 || l->lv_len < (fnump == NULL ? 2 : 3)
17786 || l->lv_len > (fnump == NULL ? 3 : 4))
17787 return FAIL;
17789 if (fnump != NULL)
17791 n = list_find_nr(l, i++, NULL); /* fnum */
17792 if (n < 0)
17793 return FAIL;
17794 if (n == 0)
17795 n = curbuf->b_fnum; /* current buffer */
17796 *fnump = n;
17799 n = list_find_nr(l, i++, NULL); /* lnum */
17800 if (n < 0)
17801 return FAIL;
17802 posp->lnum = n;
17804 n = list_find_nr(l, i++, NULL); /* col */
17805 if (n < 0)
17806 return FAIL;
17807 posp->col = n;
17809 #ifdef FEAT_VIRTUALEDIT
17810 n = list_find_nr(l, i, NULL);
17811 if (n < 0)
17812 posp->coladd = 0;
17813 else
17814 posp->coladd = n;
17815 #endif
17817 return OK;
17821 * Get the length of an environment variable name.
17822 * Advance "arg" to the first character after the name.
17823 * Return 0 for error.
17825 static int
17826 get_env_len(arg)
17827 char_u **arg;
17829 char_u *p;
17830 int len;
17832 for (p = *arg; vim_isIDc(*p); ++p)
17834 if (p == *arg) /* no name found */
17835 return 0;
17837 len = (int)(p - *arg);
17838 *arg = p;
17839 return len;
17843 * Get the length of the name of a function or internal variable.
17844 * "arg" is advanced to the first non-white character after the name.
17845 * Return 0 if something is wrong.
17847 static int
17848 get_id_len(arg)
17849 char_u **arg;
17851 char_u *p;
17852 int len;
17854 /* Find the end of the name. */
17855 for (p = *arg; eval_isnamec(*p); ++p)
17857 if (p == *arg) /* no name found */
17858 return 0;
17860 len = (int)(p - *arg);
17861 *arg = skipwhite(p);
17863 return len;
17867 * Get the length of the name of a variable or function.
17868 * Only the name is recognized, does not handle ".key" or "[idx]".
17869 * "arg" is advanced to the first non-white character after the name.
17870 * Return -1 if curly braces expansion failed.
17871 * Return 0 if something else is wrong.
17872 * If the name contains 'magic' {}'s, expand them and return the
17873 * expanded name in an allocated string via 'alias' - caller must free.
17875 static int
17876 get_name_len(arg, alias, evaluate, verbose)
17877 char_u **arg;
17878 char_u **alias;
17879 int evaluate;
17880 int verbose;
17882 int len;
17883 char_u *p;
17884 char_u *expr_start;
17885 char_u *expr_end;
17887 *alias = NULL; /* default to no alias */
17889 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
17890 && (*arg)[2] == (int)KE_SNR)
17892 /* hard coded <SNR>, already translated */
17893 *arg += 3;
17894 return get_id_len(arg) + 3;
17896 len = eval_fname_script(*arg);
17897 if (len > 0)
17899 /* literal "<SID>", "s:" or "<SNR>" */
17900 *arg += len;
17904 * Find the end of the name; check for {} construction.
17906 p = find_name_end(*arg, &expr_start, &expr_end,
17907 len > 0 ? 0 : FNE_CHECK_START);
17908 if (expr_start != NULL)
17910 char_u *temp_string;
17912 if (!evaluate)
17914 len += (int)(p - *arg);
17915 *arg = skipwhite(p);
17916 return len;
17920 * Include any <SID> etc in the expanded string:
17921 * Thus the -len here.
17923 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
17924 if (temp_string == NULL)
17925 return -1;
17926 *alias = temp_string;
17927 *arg = skipwhite(p);
17928 return (int)STRLEN(temp_string);
17931 len += get_id_len(arg);
17932 if (len == 0 && verbose)
17933 EMSG2(_(e_invexpr2), *arg);
17935 return len;
17939 * Find the end of a variable or function name, taking care of magic braces.
17940 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
17941 * start and end of the first magic braces item.
17942 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
17943 * Return a pointer to just after the name. Equal to "arg" if there is no
17944 * valid name.
17946 static char_u *
17947 find_name_end(arg, expr_start, expr_end, flags)
17948 char_u *arg;
17949 char_u **expr_start;
17950 char_u **expr_end;
17951 int flags;
17953 int mb_nest = 0;
17954 int br_nest = 0;
17955 char_u *p;
17957 if (expr_start != NULL)
17959 *expr_start = NULL;
17960 *expr_end = NULL;
17963 /* Quick check for valid starting character. */
17964 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
17965 return arg;
17967 for (p = arg; *p != NUL
17968 && (eval_isnamec(*p)
17969 || *p == '{'
17970 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
17971 || mb_nest != 0
17972 || br_nest != 0); mb_ptr_adv(p))
17974 if (*p == '\'')
17976 /* skip over 'string' to avoid counting [ and ] inside it. */
17977 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
17979 if (*p == NUL)
17980 break;
17982 else if (*p == '"')
17984 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
17985 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
17986 if (*p == '\\' && p[1] != NUL)
17987 ++p;
17988 if (*p == NUL)
17989 break;
17992 if (mb_nest == 0)
17994 if (*p == '[')
17995 ++br_nest;
17996 else if (*p == ']')
17997 --br_nest;
18000 if (br_nest == 0)
18002 if (*p == '{')
18004 mb_nest++;
18005 if (expr_start != NULL && *expr_start == NULL)
18006 *expr_start = p;
18008 else if (*p == '}')
18010 mb_nest--;
18011 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
18012 *expr_end = p;
18017 return p;
18021 * Expands out the 'magic' {}'s in a variable/function name.
18022 * Note that this can call itself recursively, to deal with
18023 * constructs like foo{bar}{baz}{bam}
18024 * The four pointer arguments point to "foo{expre}ss{ion}bar"
18025 * "in_start" ^
18026 * "expr_start" ^
18027 * "expr_end" ^
18028 * "in_end" ^
18030 * Returns a new allocated string, which the caller must free.
18031 * Returns NULL for failure.
18033 static char_u *
18034 make_expanded_name(in_start, expr_start, expr_end, in_end)
18035 char_u *in_start;
18036 char_u *expr_start;
18037 char_u *expr_end;
18038 char_u *in_end;
18040 char_u c1;
18041 char_u *retval = NULL;
18042 char_u *temp_result;
18043 char_u *nextcmd = NULL;
18045 if (expr_end == NULL || in_end == NULL)
18046 return NULL;
18047 *expr_start = NUL;
18048 *expr_end = NUL;
18049 c1 = *in_end;
18050 *in_end = NUL;
18052 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
18053 if (temp_result != NULL && nextcmd == NULL)
18055 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
18056 + (in_end - expr_end) + 1));
18057 if (retval != NULL)
18059 STRCPY(retval, in_start);
18060 STRCAT(retval, temp_result);
18061 STRCAT(retval, expr_end + 1);
18064 vim_free(temp_result);
18066 *in_end = c1; /* put char back for error messages */
18067 *expr_start = '{';
18068 *expr_end = '}';
18070 if (retval != NULL)
18072 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
18073 if (expr_start != NULL)
18075 /* Further expansion! */
18076 temp_result = make_expanded_name(retval, expr_start,
18077 expr_end, temp_result);
18078 vim_free(retval);
18079 retval = temp_result;
18083 return retval;
18087 * Return TRUE if character "c" can be used in a variable or function name.
18088 * Does not include '{' or '}' for magic braces.
18090 static int
18091 eval_isnamec(c)
18092 int c;
18094 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
18098 * Return TRUE if character "c" can be used as the first character in a
18099 * variable or function name (excluding '{' and '}').
18101 static int
18102 eval_isnamec1(c)
18103 int c;
18105 return (ASCII_ISALPHA(c) || c == '_');
18109 * Set number v: variable to "val".
18111 void
18112 set_vim_var_nr(idx, val)
18113 int idx;
18114 long val;
18116 vimvars[idx].vv_nr = val;
18120 * Get number v: variable value.
18122 long
18123 get_vim_var_nr(idx)
18124 int idx;
18126 return vimvars[idx].vv_nr;
18130 * Get string v: variable value. Uses a static buffer, can only be used once.
18132 char_u *
18133 get_vim_var_str(idx)
18134 int idx;
18136 return get_tv_string(&vimvars[idx].vv_tv);
18140 * Get List v: variable value. Caller must take care of reference count when
18141 * needed.
18143 list_T *
18144 get_vim_var_list(idx)
18145 int idx;
18147 return vimvars[idx].vv_list;
18151 * Set v:char to character "c".
18153 void
18154 set_vim_var_char(c)
18155 int c;
18157 #ifdef FEAT_MBYTE
18158 char_u buf[MB_MAXBYTES];
18159 #else
18160 char_u buf[2];
18161 #endif
18163 #ifdef FEAT_MBYTE
18164 if (has_mbyte)
18165 buf[(*mb_char2bytes)(c, buf)] = NUL;
18166 else
18167 #endif
18169 buf[0] = c;
18170 buf[1] = NUL;
18172 set_vim_var_string(VV_CHAR, buf, -1);
18176 * Set v:count to "count" and v:count1 to "count1".
18177 * When "set_prevcount" is TRUE first set v:prevcount from v:count.
18179 void
18180 set_vcount(count, count1, set_prevcount)
18181 long count;
18182 long count1;
18183 int set_prevcount;
18185 if (set_prevcount)
18186 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
18187 vimvars[VV_COUNT].vv_nr = count;
18188 vimvars[VV_COUNT1].vv_nr = count1;
18192 * Set string v: variable to a copy of "val".
18194 void
18195 set_vim_var_string(idx, val, len)
18196 int idx;
18197 char_u *val;
18198 int len; /* length of "val" to use or -1 (whole string) */
18200 /* Need to do this (at least) once, since we can't initialize a union.
18201 * Will always be invoked when "v:progname" is set. */
18202 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
18204 vim_free(vimvars[idx].vv_str);
18205 if (val == NULL)
18206 vimvars[idx].vv_str = NULL;
18207 else if (len == -1)
18208 vimvars[idx].vv_str = vim_strsave(val);
18209 else
18210 vimvars[idx].vv_str = vim_strnsave(val, len);
18214 * Set List v: variable to "val".
18216 void
18217 set_vim_var_list(idx, val)
18218 int idx;
18219 list_T *val;
18221 list_unref(vimvars[idx].vv_list);
18222 vimvars[idx].vv_list = val;
18223 if (val != NULL)
18224 ++val->lv_refcount;
18228 * Set v:register if needed.
18230 void
18231 set_reg_var(c)
18232 int c;
18234 char_u regname;
18236 if (c == 0 || c == ' ')
18237 regname = '"';
18238 else
18239 regname = c;
18240 /* Avoid free/alloc when the value is already right. */
18241 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
18242 set_vim_var_string(VV_REG, &regname, 1);
18246 * Get or set v:exception. If "oldval" == NULL, return the current value.
18247 * Otherwise, restore the value to "oldval" and return NULL.
18248 * Must always be called in pairs to save and restore v:exception! Does not
18249 * take care of memory allocations.
18251 char_u *
18252 v_exception(oldval)
18253 char_u *oldval;
18255 if (oldval == NULL)
18256 return vimvars[VV_EXCEPTION].vv_str;
18258 vimvars[VV_EXCEPTION].vv_str = oldval;
18259 return NULL;
18263 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
18264 * Otherwise, restore the value to "oldval" and return NULL.
18265 * Must always be called in pairs to save and restore v:throwpoint! Does not
18266 * take care of memory allocations.
18268 char_u *
18269 v_throwpoint(oldval)
18270 char_u *oldval;
18272 if (oldval == NULL)
18273 return vimvars[VV_THROWPOINT].vv_str;
18275 vimvars[VV_THROWPOINT].vv_str = oldval;
18276 return NULL;
18279 #if defined(FEAT_AUTOCMD) || defined(PROTO)
18281 * Set v:cmdarg.
18282 * If "eap" != NULL, use "eap" to generate the value and return the old value.
18283 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
18284 * Must always be called in pairs!
18286 char_u *
18287 set_cmdarg(eap, oldarg)
18288 exarg_T *eap;
18289 char_u *oldarg;
18291 char_u *oldval;
18292 char_u *newval;
18293 unsigned len;
18295 oldval = vimvars[VV_CMDARG].vv_str;
18296 if (eap == NULL)
18298 vim_free(oldval);
18299 vimvars[VV_CMDARG].vv_str = oldarg;
18300 return NULL;
18303 if (eap->force_bin == FORCE_BIN)
18304 len = 6;
18305 else if (eap->force_bin == FORCE_NOBIN)
18306 len = 8;
18307 else
18308 len = 0;
18310 if (eap->read_edit)
18311 len += 7;
18313 if (eap->force_ff != 0)
18314 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
18315 # ifdef FEAT_MBYTE
18316 if (eap->force_enc != 0)
18317 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
18318 if (eap->bad_char != 0)
18319 len += 7 + 4; /* " ++bad=" + "keep" or "drop" */
18320 # endif
18322 newval = alloc(len + 1);
18323 if (newval == NULL)
18324 return NULL;
18326 if (eap->force_bin == FORCE_BIN)
18327 sprintf((char *)newval, " ++bin");
18328 else if (eap->force_bin == FORCE_NOBIN)
18329 sprintf((char *)newval, " ++nobin");
18330 else
18331 *newval = NUL;
18333 if (eap->read_edit)
18334 STRCAT(newval, " ++edit");
18336 if (eap->force_ff != 0)
18337 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
18338 eap->cmd + eap->force_ff);
18339 # ifdef FEAT_MBYTE
18340 if (eap->force_enc != 0)
18341 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
18342 eap->cmd + eap->force_enc);
18343 if (eap->bad_char == BAD_KEEP)
18344 STRCPY(newval + STRLEN(newval), " ++bad=keep");
18345 else if (eap->bad_char == BAD_DROP)
18346 STRCPY(newval + STRLEN(newval), " ++bad=drop");
18347 else if (eap->bad_char != 0)
18348 sprintf((char *)newval + STRLEN(newval), " ++bad=%c", eap->bad_char);
18349 # endif
18350 vimvars[VV_CMDARG].vv_str = newval;
18351 return oldval;
18353 #endif
18356 * Get the value of internal variable "name".
18357 * Return OK or FAIL.
18359 static int
18360 get_var_tv(name, len, rettv, verbose)
18361 char_u *name;
18362 int len; /* length of "name" */
18363 typval_T *rettv; /* NULL when only checking existence */
18364 int verbose; /* may give error message */
18366 int ret = OK;
18367 typval_T *tv = NULL;
18368 typval_T atv;
18369 dictitem_T *v;
18370 int cc;
18372 /* truncate the name, so that we can use strcmp() */
18373 cc = name[len];
18374 name[len] = NUL;
18377 * Check for "b:changedtick".
18379 if (STRCMP(name, "b:changedtick") == 0)
18381 atv.v_type = VAR_NUMBER;
18382 atv.vval.v_number = curbuf->b_changedtick;
18383 tv = &atv;
18387 * Check for user-defined variables.
18389 else
18391 v = find_var(name, NULL);
18392 if (v != NULL)
18393 tv = &v->di_tv;
18396 if (tv == NULL)
18398 if (rettv != NULL && verbose)
18399 EMSG2(_(e_undefvar), name);
18400 ret = FAIL;
18402 else if (rettv != NULL)
18403 copy_tv(tv, rettv);
18405 name[len] = cc;
18407 return ret;
18411 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
18412 * Also handle function call with Funcref variable: func(expr)
18413 * Can all be combined: dict.func(expr)[idx]['func'](expr)
18415 static int
18416 handle_subscript(arg, rettv, evaluate, verbose)
18417 char_u **arg;
18418 typval_T *rettv;
18419 int evaluate; /* do more than finding the end */
18420 int verbose; /* give error messages */
18422 int ret = OK;
18423 dict_T *selfdict = NULL;
18424 char_u *s;
18425 int len;
18426 typval_T functv;
18428 while (ret == OK
18429 && (**arg == '['
18430 || (**arg == '.' && rettv->v_type == VAR_DICT)
18431 || (**arg == '(' && rettv->v_type == VAR_FUNC))
18432 && !vim_iswhite(*(*arg - 1)))
18434 if (**arg == '(')
18436 /* need to copy the funcref so that we can clear rettv */
18437 functv = *rettv;
18438 rettv->v_type = VAR_UNKNOWN;
18440 /* Invoke the function. Recursive! */
18441 s = functv.vval.v_string;
18442 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
18443 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
18444 &len, evaluate, selfdict);
18446 /* Clear the funcref afterwards, so that deleting it while
18447 * evaluating the arguments is possible (see test55). */
18448 clear_tv(&functv);
18450 /* Stop the expression evaluation when immediately aborting on
18451 * error, or when an interrupt occurred or an exception was thrown
18452 * but not caught. */
18453 if (aborting())
18455 if (ret == OK)
18456 clear_tv(rettv);
18457 ret = FAIL;
18459 dict_unref(selfdict);
18460 selfdict = NULL;
18462 else /* **arg == '[' || **arg == '.' */
18464 dict_unref(selfdict);
18465 if (rettv->v_type == VAR_DICT)
18467 selfdict = rettv->vval.v_dict;
18468 if (selfdict != NULL)
18469 ++selfdict->dv_refcount;
18471 else
18472 selfdict = NULL;
18473 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
18475 clear_tv(rettv);
18476 ret = FAIL;
18480 dict_unref(selfdict);
18481 return ret;
18485 * Allocate memory for a variable type-value, and make it empty (0 or NULL
18486 * value).
18488 static typval_T *
18489 alloc_tv()
18491 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
18495 * Allocate memory for a variable type-value, and assign a string to it.
18496 * The string "s" must have been allocated, it is consumed.
18497 * Return NULL for out of memory, the variable otherwise.
18499 static typval_T *
18500 alloc_string_tv(s)
18501 char_u *s;
18503 typval_T *rettv;
18505 rettv = alloc_tv();
18506 if (rettv != NULL)
18508 rettv->v_type = VAR_STRING;
18509 rettv->vval.v_string = s;
18511 else
18512 vim_free(s);
18513 return rettv;
18517 * Free the memory for a variable type-value.
18519 void
18520 free_tv(varp)
18521 typval_T *varp;
18523 if (varp != NULL)
18525 switch (varp->v_type)
18527 case VAR_FUNC:
18528 func_unref(varp->vval.v_string);
18529 /*FALLTHROUGH*/
18530 case VAR_STRING:
18531 vim_free(varp->vval.v_string);
18532 break;
18533 case VAR_LIST:
18534 list_unref(varp->vval.v_list);
18535 break;
18536 case VAR_DICT:
18537 dict_unref(varp->vval.v_dict);
18538 break;
18539 case VAR_NUMBER:
18540 #ifdef FEAT_FLOAT
18541 case VAR_FLOAT:
18542 #endif
18543 case VAR_UNKNOWN:
18544 break;
18545 default:
18546 EMSG2(_(e_intern2), "free_tv()");
18547 break;
18549 vim_free(varp);
18554 * Free the memory for a variable value and set the value to NULL or 0.
18556 void
18557 clear_tv(varp)
18558 typval_T *varp;
18560 if (varp != NULL)
18562 switch (varp->v_type)
18564 case VAR_FUNC:
18565 func_unref(varp->vval.v_string);
18566 /*FALLTHROUGH*/
18567 case VAR_STRING:
18568 vim_free(varp->vval.v_string);
18569 varp->vval.v_string = NULL;
18570 break;
18571 case VAR_LIST:
18572 list_unref(varp->vval.v_list);
18573 varp->vval.v_list = NULL;
18574 break;
18575 case VAR_DICT:
18576 dict_unref(varp->vval.v_dict);
18577 varp->vval.v_dict = NULL;
18578 break;
18579 case VAR_NUMBER:
18580 varp->vval.v_number = 0;
18581 break;
18582 #ifdef FEAT_FLOAT
18583 case VAR_FLOAT:
18584 varp->vval.v_float = 0.0;
18585 break;
18586 #endif
18587 case VAR_UNKNOWN:
18588 break;
18589 default:
18590 EMSG2(_(e_intern2), "clear_tv()");
18592 varp->v_lock = 0;
18597 * Set the value of a variable to NULL without freeing items.
18599 static void
18600 init_tv(varp)
18601 typval_T *varp;
18603 if (varp != NULL)
18604 vim_memset(varp, 0, sizeof(typval_T));
18608 * Get the number value of a variable.
18609 * If it is a String variable, uses vim_str2nr().
18610 * For incompatible types, return 0.
18611 * get_tv_number_chk() is similar to get_tv_number(), but informs the
18612 * caller of incompatible types: it sets *denote to TRUE if "denote"
18613 * is not NULL or returns -1 otherwise.
18615 static long
18616 get_tv_number(varp)
18617 typval_T *varp;
18619 int error = FALSE;
18621 return get_tv_number_chk(varp, &error); /* return 0L on error */
18624 long
18625 get_tv_number_chk(varp, denote)
18626 typval_T *varp;
18627 int *denote;
18629 long n = 0L;
18631 switch (varp->v_type)
18633 case VAR_NUMBER:
18634 return (long)(varp->vval.v_number);
18635 #ifdef FEAT_FLOAT
18636 case VAR_FLOAT:
18637 EMSG(_("E805: Using a Float as a Number"));
18638 break;
18639 #endif
18640 case VAR_FUNC:
18641 EMSG(_("E703: Using a Funcref as a Number"));
18642 break;
18643 case VAR_STRING:
18644 if (varp->vval.v_string != NULL)
18645 vim_str2nr(varp->vval.v_string, NULL, NULL,
18646 TRUE, TRUE, &n, NULL);
18647 return n;
18648 case VAR_LIST:
18649 EMSG(_("E745: Using a List as a Number"));
18650 break;
18651 case VAR_DICT:
18652 EMSG(_("E728: Using a Dictionary as a Number"));
18653 break;
18654 default:
18655 EMSG2(_(e_intern2), "get_tv_number()");
18656 break;
18658 if (denote == NULL) /* useful for values that must be unsigned */
18659 n = -1;
18660 else
18661 *denote = TRUE;
18662 return n;
18666 * Get the lnum from the first argument.
18667 * Also accepts ".", "$", etc., but that only works for the current buffer.
18668 * Returns -1 on error.
18670 static linenr_T
18671 get_tv_lnum(argvars)
18672 typval_T *argvars;
18674 typval_T rettv;
18675 linenr_T lnum;
18677 lnum = get_tv_number_chk(&argvars[0], NULL);
18678 if (lnum == 0) /* no valid number, try using line() */
18680 rettv.v_type = VAR_NUMBER;
18681 f_line(argvars, &rettv);
18682 lnum = rettv.vval.v_number;
18683 clear_tv(&rettv);
18685 return lnum;
18689 * Get the lnum from the first argument.
18690 * Also accepts "$", then "buf" is used.
18691 * Returns 0 on error.
18693 static linenr_T
18694 get_tv_lnum_buf(argvars, buf)
18695 typval_T *argvars;
18696 buf_T *buf;
18698 if (argvars[0].v_type == VAR_STRING
18699 && argvars[0].vval.v_string != NULL
18700 && argvars[0].vval.v_string[0] == '$'
18701 && buf != NULL)
18702 return buf->b_ml.ml_line_count;
18703 return get_tv_number_chk(&argvars[0], NULL);
18707 * Get the string value of a variable.
18708 * If it is a Number variable, the number is converted into a string.
18709 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
18710 * get_tv_string_buf() uses a given buffer.
18711 * If the String variable has never been set, return an empty string.
18712 * Never returns NULL;
18713 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
18714 * NULL on error.
18716 static char_u *
18717 get_tv_string(varp)
18718 typval_T *varp;
18720 static char_u mybuf[NUMBUFLEN];
18722 return get_tv_string_buf(varp, mybuf);
18725 static char_u *
18726 get_tv_string_buf(varp, buf)
18727 typval_T *varp;
18728 char_u *buf;
18730 char_u *res = get_tv_string_buf_chk(varp, buf);
18732 return res != NULL ? res : (char_u *)"";
18735 char_u *
18736 get_tv_string_chk(varp)
18737 typval_T *varp;
18739 static char_u mybuf[NUMBUFLEN];
18741 return get_tv_string_buf_chk(varp, mybuf);
18744 static char_u *
18745 get_tv_string_buf_chk(varp, buf)
18746 typval_T *varp;
18747 char_u *buf;
18749 switch (varp->v_type)
18751 case VAR_NUMBER:
18752 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
18753 return buf;
18754 case VAR_FUNC:
18755 EMSG(_("E729: using Funcref as a String"));
18756 break;
18757 case VAR_LIST:
18758 EMSG(_("E730: using List as a String"));
18759 break;
18760 case VAR_DICT:
18761 EMSG(_("E731: using Dictionary as a String"));
18762 break;
18763 #ifdef FEAT_FLOAT
18764 case VAR_FLOAT:
18765 EMSG(_("E806: using Float as a String"));
18766 break;
18767 #endif
18768 case VAR_STRING:
18769 if (varp->vval.v_string != NULL)
18770 return varp->vval.v_string;
18771 return (char_u *)"";
18772 default:
18773 EMSG2(_(e_intern2), "get_tv_string_buf()");
18774 break;
18776 return NULL;
18780 * Find variable "name" in the list of variables.
18781 * Return a pointer to it if found, NULL if not found.
18782 * Careful: "a:0" variables don't have a name.
18783 * When "htp" is not NULL we are writing to the variable, set "htp" to the
18784 * hashtab_T used.
18786 static dictitem_T *
18787 find_var(name, htp)
18788 char_u *name;
18789 hashtab_T **htp;
18791 char_u *varname;
18792 hashtab_T *ht;
18794 ht = find_var_ht(name, &varname);
18795 if (htp != NULL)
18796 *htp = ht;
18797 if (ht == NULL)
18798 return NULL;
18799 return find_var_in_ht(ht, varname, htp != NULL);
18803 * Find variable "varname" in hashtab "ht".
18804 * Returns NULL if not found.
18806 static dictitem_T *
18807 find_var_in_ht(ht, varname, writing)
18808 hashtab_T *ht;
18809 char_u *varname;
18810 int writing;
18812 hashitem_T *hi;
18814 if (*varname == NUL)
18816 /* Must be something like "s:", otherwise "ht" would be NULL. */
18817 switch (varname[-2])
18819 case 's': return &SCRIPT_SV(current_SID)->sv_var;
18820 case 'g': return &globvars_var;
18821 case 'v': return &vimvars_var;
18822 case 'b': return &curbuf->b_bufvar;
18823 case 'w': return &curwin->w_winvar;
18824 #ifdef FEAT_WINDOWS
18825 case 't': return &curtab->tp_winvar;
18826 #endif
18827 case 'l': return current_funccal == NULL
18828 ? NULL : &current_funccal->l_vars_var;
18829 case 'a': return current_funccal == NULL
18830 ? NULL : &current_funccal->l_avars_var;
18832 return NULL;
18835 hi = hash_find(ht, varname);
18836 if (HASHITEM_EMPTY(hi))
18838 /* For global variables we may try auto-loading the script. If it
18839 * worked find the variable again. Don't auto-load a script if it was
18840 * loaded already, otherwise it would be loaded every time when
18841 * checking if a function name is a Funcref variable. */
18842 if (ht == &globvarht && !writing
18843 && script_autoload(varname, FALSE) && !aborting())
18844 hi = hash_find(ht, varname);
18845 if (HASHITEM_EMPTY(hi))
18846 return NULL;
18848 return HI2DI(hi);
18852 * Find the hashtab used for a variable name.
18853 * Set "varname" to the start of name without ':'.
18855 static hashtab_T *
18856 find_var_ht(name, varname)
18857 char_u *name;
18858 char_u **varname;
18860 hashitem_T *hi;
18862 if (name[1] != ':')
18864 /* The name must not start with a colon or #. */
18865 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
18866 return NULL;
18867 *varname = name;
18869 /* "version" is "v:version" in all scopes */
18870 hi = hash_find(&compat_hashtab, name);
18871 if (!HASHITEM_EMPTY(hi))
18872 return &compat_hashtab;
18874 if (current_funccal == NULL)
18875 return &globvarht; /* global variable */
18876 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
18878 *varname = name + 2;
18879 if (*name == 'g') /* global variable */
18880 return &globvarht;
18881 /* There must be no ':' or '#' in the rest of the name, unless g: is used
18883 if (vim_strchr(name + 2, ':') != NULL
18884 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
18885 return NULL;
18886 if (*name == 'b') /* buffer variable */
18887 return &curbuf->b_vars.dv_hashtab;
18888 if (*name == 'w') /* window variable */
18889 return &curwin->w_vars.dv_hashtab;
18890 #ifdef FEAT_WINDOWS
18891 if (*name == 't') /* tab page variable */
18892 return &curtab->tp_vars.dv_hashtab;
18893 #endif
18894 if (*name == 'v') /* v: variable */
18895 return &vimvarht;
18896 if (*name == 'a' && current_funccal != NULL) /* function argument */
18897 return &current_funccal->l_avars.dv_hashtab;
18898 if (*name == 'l' && current_funccal != NULL) /* local function variable */
18899 return &current_funccal->l_vars.dv_hashtab;
18900 if (*name == 's' /* script variable */
18901 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
18902 return &SCRIPT_VARS(current_SID);
18903 return NULL;
18907 * Get the string value of a (global/local) variable.
18908 * Returns NULL when it doesn't exist.
18910 char_u *
18911 get_var_value(name)
18912 char_u *name;
18914 dictitem_T *v;
18916 v = find_var(name, NULL);
18917 if (v == NULL)
18918 return NULL;
18919 return get_tv_string(&v->di_tv);
18923 * Allocate a new hashtab for a sourced script. It will be used while
18924 * sourcing this script and when executing functions defined in the script.
18926 void
18927 new_script_vars(id)
18928 scid_T id;
18930 int i;
18931 hashtab_T *ht;
18932 scriptvar_T *sv;
18934 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
18936 /* Re-allocating ga_data means that an ht_array pointing to
18937 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
18938 * at its init value. Also reset "v_dict", it's always the same. */
18939 for (i = 1; i <= ga_scripts.ga_len; ++i)
18941 ht = &SCRIPT_VARS(i);
18942 if (ht->ht_mask == HT_INIT_SIZE - 1)
18943 ht->ht_array = ht->ht_smallarray;
18944 sv = SCRIPT_SV(i);
18945 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
18948 while (ga_scripts.ga_len < id)
18950 sv = SCRIPT_SV(ga_scripts.ga_len + 1) =
18951 (scriptvar_T *)alloc_clear(sizeof(scriptvar_T));
18952 init_var_dict(&sv->sv_dict, &sv->sv_var);
18953 ++ga_scripts.ga_len;
18959 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
18960 * point to it.
18962 void
18963 init_var_dict(dict, dict_var)
18964 dict_T *dict;
18965 dictitem_T *dict_var;
18967 hash_init(&dict->dv_hashtab);
18968 dict->dv_refcount = DO_NOT_FREE_CNT;
18969 dict->dv_copyID = 0;
18970 dict_var->di_tv.vval.v_dict = dict;
18971 dict_var->di_tv.v_type = VAR_DICT;
18972 dict_var->di_tv.v_lock = VAR_FIXED;
18973 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
18974 dict_var->di_key[0] = NUL;
18978 * Clean up a list of internal variables.
18979 * Frees all allocated variables and the value they contain.
18980 * Clears hashtab "ht", does not free it.
18982 void
18983 vars_clear(ht)
18984 hashtab_T *ht;
18986 vars_clear_ext(ht, TRUE);
18990 * Like vars_clear(), but only free the value if "free_val" is TRUE.
18992 static void
18993 vars_clear_ext(ht, free_val)
18994 hashtab_T *ht;
18995 int free_val;
18997 int todo;
18998 hashitem_T *hi;
18999 dictitem_T *v;
19001 hash_lock(ht);
19002 todo = (int)ht->ht_used;
19003 for (hi = ht->ht_array; todo > 0; ++hi)
19005 if (!HASHITEM_EMPTY(hi))
19007 --todo;
19009 /* Free the variable. Don't remove it from the hashtab,
19010 * ht_array might change then. hash_clear() takes care of it
19011 * later. */
19012 v = HI2DI(hi);
19013 if (free_val)
19014 clear_tv(&v->di_tv);
19015 if ((v->di_flags & DI_FLAGS_FIX) == 0)
19016 vim_free(v);
19019 hash_clear(ht);
19020 ht->ht_used = 0;
19024 * Delete a variable from hashtab "ht" at item "hi".
19025 * Clear the variable value and free the dictitem.
19027 static void
19028 delete_var(ht, hi)
19029 hashtab_T *ht;
19030 hashitem_T *hi;
19032 dictitem_T *di = HI2DI(hi);
19034 hash_remove(ht, hi);
19035 clear_tv(&di->di_tv);
19036 vim_free(di);
19040 * List the value of one internal variable.
19042 static void
19043 list_one_var(v, prefix, first)
19044 dictitem_T *v;
19045 char_u *prefix;
19046 int *first;
19048 char_u *tofree;
19049 char_u *s;
19050 char_u numbuf[NUMBUFLEN];
19052 current_copyID += COPYID_INC;
19053 s = echo_string(&v->di_tv, &tofree, numbuf, current_copyID);
19054 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
19055 s == NULL ? (char_u *)"" : s, first);
19056 vim_free(tofree);
19059 static void
19060 list_one_var_a(prefix, name, type, string, first)
19061 char_u *prefix;
19062 char_u *name;
19063 int type;
19064 char_u *string;
19065 int *first; /* when TRUE clear rest of screen and set to FALSE */
19067 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
19068 msg_start();
19069 msg_puts(prefix);
19070 if (name != NULL) /* "a:" vars don't have a name stored */
19071 msg_puts(name);
19072 msg_putchar(' ');
19073 msg_advance(22);
19074 if (type == VAR_NUMBER)
19075 msg_putchar('#');
19076 else if (type == VAR_FUNC)
19077 msg_putchar('*');
19078 else if (type == VAR_LIST)
19080 msg_putchar('[');
19081 if (*string == '[')
19082 ++string;
19084 else if (type == VAR_DICT)
19086 msg_putchar('{');
19087 if (*string == '{')
19088 ++string;
19090 else
19091 msg_putchar(' ');
19093 msg_outtrans(string);
19095 if (type == VAR_FUNC)
19096 msg_puts((char_u *)"()");
19097 if (*first)
19099 msg_clr_eos();
19100 *first = FALSE;
19105 * Set variable "name" to value in "tv".
19106 * If the variable already exists, the value is updated.
19107 * Otherwise the variable is created.
19109 static void
19110 set_var(name, tv, copy)
19111 char_u *name;
19112 typval_T *tv;
19113 int copy; /* make copy of value in "tv" */
19115 dictitem_T *v;
19116 char_u *varname;
19117 hashtab_T *ht;
19118 char_u *p;
19120 ht = find_var_ht(name, &varname);
19121 if (ht == NULL || *varname == NUL)
19123 EMSG2(_(e_illvar), name);
19124 return;
19126 v = find_var_in_ht(ht, varname, TRUE);
19128 if (tv->v_type == VAR_FUNC)
19130 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
19131 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
19132 ? name[2] : name[0]))
19134 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
19135 return;
19137 /* Don't allow hiding a function. When "v" is not NULL we migth be
19138 * assigning another function to the same var, the type is checked
19139 * below. */
19140 if (v == NULL && function_exists(name))
19142 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
19143 name);
19144 return;
19148 if (v != NULL)
19150 /* existing variable, need to clear the value */
19151 if (var_check_ro(v->di_flags, name)
19152 || tv_check_lock(v->di_tv.v_lock, name))
19153 return;
19154 if (v->di_tv.v_type != tv->v_type
19155 && !((v->di_tv.v_type == VAR_STRING
19156 || v->di_tv.v_type == VAR_NUMBER)
19157 && (tv->v_type == VAR_STRING
19158 || tv->v_type == VAR_NUMBER))
19159 #ifdef FEAT_FLOAT
19160 && !((v->di_tv.v_type == VAR_NUMBER
19161 || v->di_tv.v_type == VAR_FLOAT)
19162 && (tv->v_type == VAR_NUMBER
19163 || tv->v_type == VAR_FLOAT))
19164 #endif
19167 EMSG2(_("E706: Variable type mismatch for: %s"), name);
19168 return;
19172 * Handle setting internal v: variables separately: we don't change
19173 * the type.
19175 if (ht == &vimvarht)
19177 if (v->di_tv.v_type == VAR_STRING)
19179 vim_free(v->di_tv.vval.v_string);
19180 if (copy || tv->v_type != VAR_STRING)
19181 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
19182 else
19184 /* Take over the string to avoid an extra alloc/free. */
19185 v->di_tv.vval.v_string = tv->vval.v_string;
19186 tv->vval.v_string = NULL;
19189 else if (v->di_tv.v_type != VAR_NUMBER)
19190 EMSG2(_(e_intern2), "set_var()");
19191 else
19193 v->di_tv.vval.v_number = get_tv_number(tv);
19194 if (STRCMP(varname, "searchforward") == 0)
19195 set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
19197 return;
19200 clear_tv(&v->di_tv);
19202 else /* add a new variable */
19204 /* Can't add "v:" variable. */
19205 if (ht == &vimvarht)
19207 EMSG2(_(e_illvar), name);
19208 return;
19211 /* Make sure the variable name is valid. */
19212 for (p = varname; *p != NUL; ++p)
19213 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
19214 && *p != AUTOLOAD_CHAR)
19216 EMSG2(_(e_illvar), varname);
19217 return;
19220 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
19221 + STRLEN(varname)));
19222 if (v == NULL)
19223 return;
19224 STRCPY(v->di_key, varname);
19225 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
19227 vim_free(v);
19228 return;
19230 v->di_flags = 0;
19233 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
19234 copy_tv(tv, &v->di_tv);
19235 else
19237 v->di_tv = *tv;
19238 v->di_tv.v_lock = 0;
19239 init_tv(tv);
19244 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
19245 * Also give an error message.
19247 static int
19248 var_check_ro(flags, name)
19249 int flags;
19250 char_u *name;
19252 if (flags & DI_FLAGS_RO)
19254 EMSG2(_(e_readonlyvar), name);
19255 return TRUE;
19257 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
19259 EMSG2(_(e_readonlysbx), name);
19260 return TRUE;
19262 return FALSE;
19266 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
19267 * Also give an error message.
19269 static int
19270 var_check_fixed(flags, name)
19271 int flags;
19272 char_u *name;
19274 if (flags & DI_FLAGS_FIX)
19276 EMSG2(_("E795: Cannot delete variable %s"), name);
19277 return TRUE;
19279 return FALSE;
19283 * Return TRUE if typeval "tv" is set to be locked (immutable).
19284 * Also give an error message, using "name".
19286 static int
19287 tv_check_lock(lock, name)
19288 int lock;
19289 char_u *name;
19291 if (lock & VAR_LOCKED)
19293 EMSG2(_("E741: Value is locked: %s"),
19294 name == NULL ? (char_u *)_("Unknown") : name);
19295 return TRUE;
19297 if (lock & VAR_FIXED)
19299 EMSG2(_("E742: Cannot change value of %s"),
19300 name == NULL ? (char_u *)_("Unknown") : name);
19301 return TRUE;
19303 return FALSE;
19307 * Copy the values from typval_T "from" to typval_T "to".
19308 * When needed allocates string or increases reference count.
19309 * Does not make a copy of a list or dict but copies the reference!
19310 * It is OK for "from" and "to" to point to the same item. This is used to
19311 * make a copy later.
19313 void
19314 copy_tv(from, to)
19315 typval_T *from;
19316 typval_T *to;
19318 to->v_type = from->v_type;
19319 to->v_lock = 0;
19320 switch (from->v_type)
19322 case VAR_NUMBER:
19323 to->vval.v_number = from->vval.v_number;
19324 break;
19325 #ifdef FEAT_FLOAT
19326 case VAR_FLOAT:
19327 to->vval.v_float = from->vval.v_float;
19328 break;
19329 #endif
19330 case VAR_STRING:
19331 case VAR_FUNC:
19332 if (from->vval.v_string == NULL)
19333 to->vval.v_string = NULL;
19334 else
19336 to->vval.v_string = vim_strsave(from->vval.v_string);
19337 if (from->v_type == VAR_FUNC)
19338 func_ref(to->vval.v_string);
19340 break;
19341 case VAR_LIST:
19342 if (from->vval.v_list == NULL)
19343 to->vval.v_list = NULL;
19344 else
19346 to->vval.v_list = from->vval.v_list;
19347 ++to->vval.v_list->lv_refcount;
19349 break;
19350 case VAR_DICT:
19351 if (from->vval.v_dict == NULL)
19352 to->vval.v_dict = NULL;
19353 else
19355 to->vval.v_dict = from->vval.v_dict;
19356 ++to->vval.v_dict->dv_refcount;
19358 break;
19359 default:
19360 EMSG2(_(e_intern2), "copy_tv()");
19361 break;
19366 * Make a copy of an item.
19367 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
19368 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
19369 * reference to an already copied list/dict can be used.
19370 * Returns FAIL or OK.
19372 static int
19373 item_copy(from, to, deep, copyID)
19374 typval_T *from;
19375 typval_T *to;
19376 int deep;
19377 int copyID;
19379 static int recurse = 0;
19380 int ret = OK;
19382 if (recurse >= DICT_MAXNEST)
19384 EMSG(_("E698: variable nested too deep for making a copy"));
19385 return FAIL;
19387 ++recurse;
19389 switch (from->v_type)
19391 case VAR_NUMBER:
19392 #ifdef FEAT_FLOAT
19393 case VAR_FLOAT:
19394 #endif
19395 case VAR_STRING:
19396 case VAR_FUNC:
19397 copy_tv(from, to);
19398 break;
19399 case VAR_LIST:
19400 to->v_type = VAR_LIST;
19401 to->v_lock = 0;
19402 if (from->vval.v_list == NULL)
19403 to->vval.v_list = NULL;
19404 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
19406 /* use the copy made earlier */
19407 to->vval.v_list = from->vval.v_list->lv_copylist;
19408 ++to->vval.v_list->lv_refcount;
19410 else
19411 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
19412 if (to->vval.v_list == NULL)
19413 ret = FAIL;
19414 break;
19415 case VAR_DICT:
19416 to->v_type = VAR_DICT;
19417 to->v_lock = 0;
19418 if (from->vval.v_dict == NULL)
19419 to->vval.v_dict = NULL;
19420 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
19422 /* use the copy made earlier */
19423 to->vval.v_dict = from->vval.v_dict->dv_copydict;
19424 ++to->vval.v_dict->dv_refcount;
19426 else
19427 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
19428 if (to->vval.v_dict == NULL)
19429 ret = FAIL;
19430 break;
19431 default:
19432 EMSG2(_(e_intern2), "item_copy()");
19433 ret = FAIL;
19435 --recurse;
19436 return ret;
19440 * ":echo expr1 ..." print each argument separated with a space, add a
19441 * newline at the end.
19442 * ":echon expr1 ..." print each argument plain.
19444 void
19445 ex_echo(eap)
19446 exarg_T *eap;
19448 char_u *arg = eap->arg;
19449 typval_T rettv;
19450 char_u *tofree;
19451 char_u *p;
19452 int needclr = TRUE;
19453 int atstart = TRUE;
19454 char_u numbuf[NUMBUFLEN];
19456 if (eap->skip)
19457 ++emsg_skip;
19458 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
19460 /* If eval1() causes an error message the text from the command may
19461 * still need to be cleared. E.g., "echo 22,44". */
19462 need_clr_eos = needclr;
19464 p = arg;
19465 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19468 * Report the invalid expression unless the expression evaluation
19469 * has been cancelled due to an aborting error, an interrupt, or an
19470 * exception.
19472 if (!aborting())
19473 EMSG2(_(e_invexpr2), p);
19474 need_clr_eos = FALSE;
19475 break;
19477 need_clr_eos = FALSE;
19479 if (!eap->skip)
19481 if (atstart)
19483 atstart = FALSE;
19484 /* Call msg_start() after eval1(), evaluating the expression
19485 * may cause a message to appear. */
19486 if (eap->cmdidx == CMD_echo)
19487 msg_start();
19489 else if (eap->cmdidx == CMD_echo)
19490 msg_puts_attr((char_u *)" ", echo_attr);
19491 current_copyID += COPYID_INC;
19492 p = echo_string(&rettv, &tofree, numbuf, current_copyID);
19493 if (p != NULL)
19494 for ( ; *p != NUL && !got_int; ++p)
19496 if (*p == '\n' || *p == '\r' || *p == TAB)
19498 if (*p != TAB && needclr)
19500 /* remove any text still there from the command */
19501 msg_clr_eos();
19502 needclr = FALSE;
19504 msg_putchar_attr(*p, echo_attr);
19506 else
19508 #ifdef FEAT_MBYTE
19509 if (has_mbyte)
19511 int i = (*mb_ptr2len)(p);
19513 (void)msg_outtrans_len_attr(p, i, echo_attr);
19514 p += i - 1;
19516 else
19517 #endif
19518 (void)msg_outtrans_len_attr(p, 1, echo_attr);
19521 vim_free(tofree);
19523 clear_tv(&rettv);
19524 arg = skipwhite(arg);
19526 eap->nextcmd = check_nextcmd(arg);
19528 if (eap->skip)
19529 --emsg_skip;
19530 else
19532 /* remove text that may still be there from the command */
19533 if (needclr)
19534 msg_clr_eos();
19535 if (eap->cmdidx == CMD_echo)
19536 msg_end();
19541 * ":echohl {name}".
19543 void
19544 ex_echohl(eap)
19545 exarg_T *eap;
19547 int id;
19549 id = syn_name2id(eap->arg);
19550 if (id == 0)
19551 echo_attr = 0;
19552 else
19553 echo_attr = syn_id2attr(id);
19557 * ":execute expr1 ..." execute the result of an expression.
19558 * ":echomsg expr1 ..." Print a message
19559 * ":echoerr expr1 ..." Print an error
19560 * Each gets spaces around each argument and a newline at the end for
19561 * echo commands
19563 void
19564 ex_execute(eap)
19565 exarg_T *eap;
19567 char_u *arg = eap->arg;
19568 typval_T rettv;
19569 int ret = OK;
19570 char_u *p;
19571 garray_T ga;
19572 int len;
19573 int save_did_emsg;
19575 ga_init2(&ga, 1, 80);
19577 if (eap->skip)
19578 ++emsg_skip;
19579 while (*arg != NUL && *arg != '|' && *arg != '\n')
19581 p = arg;
19582 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19585 * Report the invalid expression unless the expression evaluation
19586 * has been cancelled due to an aborting error, an interrupt, or an
19587 * exception.
19589 if (!aborting())
19590 EMSG2(_(e_invexpr2), p);
19591 ret = FAIL;
19592 break;
19595 if (!eap->skip)
19597 p = get_tv_string(&rettv);
19598 len = (int)STRLEN(p);
19599 if (ga_grow(&ga, len + 2) == FAIL)
19601 clear_tv(&rettv);
19602 ret = FAIL;
19603 break;
19605 if (ga.ga_len)
19606 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
19607 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
19608 ga.ga_len += len;
19611 clear_tv(&rettv);
19612 arg = skipwhite(arg);
19615 if (ret != FAIL && ga.ga_data != NULL)
19617 if (eap->cmdidx == CMD_echomsg)
19619 MSG_ATTR(ga.ga_data, echo_attr);
19620 out_flush();
19622 else if (eap->cmdidx == CMD_echoerr)
19624 /* We don't want to abort following commands, restore did_emsg. */
19625 save_did_emsg = did_emsg;
19626 EMSG((char_u *)ga.ga_data);
19627 if (!force_abort)
19628 did_emsg = save_did_emsg;
19630 else if (eap->cmdidx == CMD_execute)
19631 do_cmdline((char_u *)ga.ga_data,
19632 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
19635 ga_clear(&ga);
19637 if (eap->skip)
19638 --emsg_skip;
19640 eap->nextcmd = check_nextcmd(arg);
19644 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
19645 * "arg" points to the "&" or '+' when called, to "option" when returning.
19646 * Returns NULL when no option name found. Otherwise pointer to the char
19647 * after the option name.
19649 static char_u *
19650 find_option_end(arg, opt_flags)
19651 char_u **arg;
19652 int *opt_flags;
19654 char_u *p = *arg;
19656 ++p;
19657 if (*p == 'g' && p[1] == ':')
19659 *opt_flags = OPT_GLOBAL;
19660 p += 2;
19662 else if (*p == 'l' && p[1] == ':')
19664 *opt_flags = OPT_LOCAL;
19665 p += 2;
19667 else
19668 *opt_flags = 0;
19670 if (!ASCII_ISALPHA(*p))
19671 return NULL;
19672 *arg = p;
19674 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
19675 p += 4; /* termcap option */
19676 else
19677 while (ASCII_ISALPHA(*p))
19678 ++p;
19679 return p;
19683 * ":function"
19685 void
19686 ex_function(eap)
19687 exarg_T *eap;
19689 char_u *theline;
19690 int j;
19691 int c;
19692 int saved_did_emsg;
19693 char_u *name = NULL;
19694 char_u *p;
19695 char_u *arg;
19696 char_u *line_arg = NULL;
19697 garray_T newargs;
19698 garray_T newlines;
19699 int varargs = FALSE;
19700 int mustend = FALSE;
19701 int flags = 0;
19702 ufunc_T *fp;
19703 int indent;
19704 int nesting;
19705 char_u *skip_until = NULL;
19706 dictitem_T *v;
19707 funcdict_T fudi;
19708 static int func_nr = 0; /* number for nameless function */
19709 int paren;
19710 hashtab_T *ht;
19711 int todo;
19712 hashitem_T *hi;
19713 int sourcing_lnum_off;
19716 * ":function" without argument: list functions.
19718 if (ends_excmd(*eap->arg))
19720 if (!eap->skip)
19722 todo = (int)func_hashtab.ht_used;
19723 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19725 if (!HASHITEM_EMPTY(hi))
19727 --todo;
19728 fp = HI2UF(hi);
19729 if (!isdigit(*fp->uf_name))
19730 list_func_head(fp, FALSE);
19734 eap->nextcmd = check_nextcmd(eap->arg);
19735 return;
19739 * ":function /pat": list functions matching pattern.
19741 if (*eap->arg == '/')
19743 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
19744 if (!eap->skip)
19746 regmatch_T regmatch;
19748 c = *p;
19749 *p = NUL;
19750 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
19751 *p = c;
19752 if (regmatch.regprog != NULL)
19754 regmatch.rm_ic = p_ic;
19756 todo = (int)func_hashtab.ht_used;
19757 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19759 if (!HASHITEM_EMPTY(hi))
19761 --todo;
19762 fp = HI2UF(hi);
19763 if (!isdigit(*fp->uf_name)
19764 && vim_regexec(&regmatch, fp->uf_name, 0))
19765 list_func_head(fp, FALSE);
19768 vim_free(regmatch.regprog);
19771 if (*p == '/')
19772 ++p;
19773 eap->nextcmd = check_nextcmd(p);
19774 return;
19778 * Get the function name. There are these situations:
19779 * func normal function name
19780 * "name" == func, "fudi.fd_dict" == NULL
19781 * dict.func new dictionary entry
19782 * "name" == NULL, "fudi.fd_dict" set,
19783 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
19784 * dict.func existing dict entry with a Funcref
19785 * "name" == func, "fudi.fd_dict" set,
19786 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19787 * dict.func existing dict entry that's not a Funcref
19788 * "name" == NULL, "fudi.fd_dict" set,
19789 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19791 p = eap->arg;
19792 name = trans_function_name(&p, eap->skip, 0, &fudi);
19793 paren = (vim_strchr(p, '(') != NULL);
19794 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
19797 * Return on an invalid expression in braces, unless the expression
19798 * evaluation has been cancelled due to an aborting error, an
19799 * interrupt, or an exception.
19801 if (!aborting())
19803 if (!eap->skip && fudi.fd_newkey != NULL)
19804 EMSG2(_(e_dictkey), fudi.fd_newkey);
19805 vim_free(fudi.fd_newkey);
19806 return;
19808 else
19809 eap->skip = TRUE;
19812 /* An error in a function call during evaluation of an expression in magic
19813 * braces should not cause the function not to be defined. */
19814 saved_did_emsg = did_emsg;
19815 did_emsg = FALSE;
19818 * ":function func" with only function name: list function.
19820 if (!paren)
19822 if (!ends_excmd(*skipwhite(p)))
19824 EMSG(_(e_trailing));
19825 goto ret_free;
19827 eap->nextcmd = check_nextcmd(p);
19828 if (eap->nextcmd != NULL)
19829 *p = NUL;
19830 if (!eap->skip && !got_int)
19832 fp = find_func(name);
19833 if (fp != NULL)
19835 list_func_head(fp, TRUE);
19836 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
19838 if (FUNCLINE(fp, j) == NULL)
19839 continue;
19840 msg_putchar('\n');
19841 msg_outnum((long)(j + 1));
19842 if (j < 9)
19843 msg_putchar(' ');
19844 if (j < 99)
19845 msg_putchar(' ');
19846 msg_prt_line(FUNCLINE(fp, j), FALSE);
19847 out_flush(); /* show a line at a time */
19848 ui_breakcheck();
19850 if (!got_int)
19852 msg_putchar('\n');
19853 msg_puts((char_u *)" endfunction");
19856 else
19857 emsg_funcname(N_("E123: Undefined function: %s"), name);
19859 goto ret_free;
19863 * ":function name(arg1, arg2)" Define function.
19865 p = skipwhite(p);
19866 if (*p != '(')
19868 if (!eap->skip)
19870 EMSG2(_("E124: Missing '(': %s"), eap->arg);
19871 goto ret_free;
19873 /* attempt to continue by skipping some text */
19874 if (vim_strchr(p, '(') != NULL)
19875 p = vim_strchr(p, '(');
19877 p = skipwhite(p + 1);
19879 ga_init2(&newargs, (int)sizeof(char_u *), 3);
19880 ga_init2(&newlines, (int)sizeof(char_u *), 3);
19882 if (!eap->skip)
19884 /* Check the name of the function. Unless it's a dictionary function
19885 * (that we are overwriting). */
19886 if (name != NULL)
19887 arg = name;
19888 else
19889 arg = fudi.fd_newkey;
19890 if (arg != NULL && (fudi.fd_di == NULL
19891 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
19893 if (*arg == K_SPECIAL)
19894 j = 3;
19895 else
19896 j = 0;
19897 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
19898 : eval_isnamec(arg[j])))
19899 ++j;
19900 if (arg[j] != NUL)
19901 emsg_funcname((char *)e_invarg2, arg);
19906 * Isolate the arguments: "arg1, arg2, ...)"
19908 while (*p != ')')
19910 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
19912 varargs = TRUE;
19913 p += 3;
19914 mustend = TRUE;
19916 else
19918 arg = p;
19919 while (ASCII_ISALNUM(*p) || *p == '_')
19920 ++p;
19921 if (arg == p || isdigit(*arg)
19922 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
19923 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
19925 if (!eap->skip)
19926 EMSG2(_("E125: Illegal argument: %s"), arg);
19927 break;
19929 if (ga_grow(&newargs, 1) == FAIL)
19930 goto erret;
19931 c = *p;
19932 *p = NUL;
19933 arg = vim_strsave(arg);
19934 if (arg == NULL)
19935 goto erret;
19936 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
19937 *p = c;
19938 newargs.ga_len++;
19939 if (*p == ',')
19940 ++p;
19941 else
19942 mustend = TRUE;
19944 p = skipwhite(p);
19945 if (mustend && *p != ')')
19947 if (!eap->skip)
19948 EMSG2(_(e_invarg2), eap->arg);
19949 break;
19952 ++p; /* skip the ')' */
19954 /* find extra arguments "range", "dict" and "abort" */
19955 for (;;)
19957 p = skipwhite(p);
19958 if (STRNCMP(p, "range", 5) == 0)
19960 flags |= FC_RANGE;
19961 p += 5;
19963 else if (STRNCMP(p, "dict", 4) == 0)
19965 flags |= FC_DICT;
19966 p += 4;
19968 else if (STRNCMP(p, "abort", 5) == 0)
19970 flags |= FC_ABORT;
19971 p += 5;
19973 else
19974 break;
19977 /* When there is a line break use what follows for the function body.
19978 * Makes 'exe "func Test()\n...\nendfunc"' work. */
19979 if (*p == '\n')
19980 line_arg = p + 1;
19981 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
19982 EMSG(_(e_trailing));
19985 * Read the body of the function, until ":endfunction" is found.
19987 if (KeyTyped)
19989 /* Check if the function already exists, don't let the user type the
19990 * whole function before telling him it doesn't work! For a script we
19991 * need to skip the body to be able to find what follows. */
19992 if (!eap->skip && !eap->forceit)
19994 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
19995 EMSG(_(e_funcdict));
19996 else if (name != NULL && find_func(name) != NULL)
19997 emsg_funcname(e_funcexts, name);
20000 if (!eap->skip && did_emsg)
20001 goto erret;
20003 msg_putchar('\n'); /* don't overwrite the function name */
20004 cmdline_row = msg_row;
20007 indent = 2;
20008 nesting = 0;
20009 for (;;)
20011 msg_scroll = TRUE;
20012 need_wait_return = FALSE;
20013 sourcing_lnum_off = sourcing_lnum;
20015 if (line_arg != NULL)
20017 /* Use eap->arg, split up in parts by line breaks. */
20018 theline = line_arg;
20019 p = vim_strchr(theline, '\n');
20020 if (p == NULL)
20021 line_arg += STRLEN(line_arg);
20022 else
20024 *p = NUL;
20025 line_arg = p + 1;
20028 else if (eap->getline == NULL)
20029 theline = getcmdline(':', 0L, indent);
20030 else
20031 theline = eap->getline(':', eap->cookie, indent);
20032 if (KeyTyped)
20033 lines_left = Rows - 1;
20034 if (theline == NULL)
20036 EMSG(_("E126: Missing :endfunction"));
20037 goto erret;
20040 /* Detect line continuation: sourcing_lnum increased more than one. */
20041 if (sourcing_lnum > sourcing_lnum_off + 1)
20042 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
20043 else
20044 sourcing_lnum_off = 0;
20046 if (skip_until != NULL)
20048 /* between ":append" and "." and between ":python <<EOF" and "EOF"
20049 * don't check for ":endfunc". */
20050 if (STRCMP(theline, skip_until) == 0)
20052 vim_free(skip_until);
20053 skip_until = NULL;
20056 else
20058 /* skip ':' and blanks*/
20059 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
20062 /* Check for "endfunction". */
20063 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
20065 if (line_arg == NULL)
20066 vim_free(theline);
20067 break;
20070 /* Increase indent inside "if", "while", "for" and "try", decrease
20071 * at "end". */
20072 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
20073 indent -= 2;
20074 else if (STRNCMP(p, "if", 2) == 0
20075 || STRNCMP(p, "wh", 2) == 0
20076 || STRNCMP(p, "for", 3) == 0
20077 || STRNCMP(p, "try", 3) == 0)
20078 indent += 2;
20080 /* Check for defining a function inside this function. */
20081 if (checkforcmd(&p, "function", 2))
20083 if (*p == '!')
20084 p = skipwhite(p + 1);
20085 p += eval_fname_script(p);
20086 if (ASCII_ISALPHA(*p))
20088 vim_free(trans_function_name(&p, TRUE, 0, NULL));
20089 if (*skipwhite(p) == '(')
20091 ++nesting;
20092 indent += 2;
20097 /* Check for ":append" or ":insert". */
20098 p = skip_range(p, NULL);
20099 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
20100 || (p[0] == 'i'
20101 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
20102 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
20103 skip_until = vim_strsave((char_u *)".");
20105 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
20106 arg = skipwhite(skiptowhite(p));
20107 if (arg[0] == '<' && arg[1] =='<'
20108 && ((p[0] == 'p' && p[1] == 'y'
20109 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
20110 || (p[0] == 'p' && p[1] == 'e'
20111 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
20112 || (p[0] == 't' && p[1] == 'c'
20113 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
20114 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
20115 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
20116 || (p[0] == 'm' && p[1] == 'z'
20117 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
20120 /* ":python <<" continues until a dot, like ":append" */
20121 p = skipwhite(arg + 2);
20122 if (*p == NUL)
20123 skip_until = vim_strsave((char_u *)".");
20124 else
20125 skip_until = vim_strsave(p);
20129 /* Add the line to the function. */
20130 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
20132 if (line_arg == NULL)
20133 vim_free(theline);
20134 goto erret;
20137 /* Copy the line to newly allocated memory. get_one_sourceline()
20138 * allocates 250 bytes per line, this saves 80% on average. The cost
20139 * is an extra alloc/free. */
20140 p = vim_strsave(theline);
20141 if (p != NULL)
20143 if (line_arg == NULL)
20144 vim_free(theline);
20145 theline = p;
20148 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
20150 /* Add NULL lines for continuation lines, so that the line count is
20151 * equal to the index in the growarray. */
20152 while (sourcing_lnum_off-- > 0)
20153 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
20155 /* Check for end of eap->arg. */
20156 if (line_arg != NULL && *line_arg == NUL)
20157 line_arg = NULL;
20160 /* Don't define the function when skipping commands or when an error was
20161 * detected. */
20162 if (eap->skip || did_emsg)
20163 goto erret;
20166 * If there are no errors, add the function
20168 if (fudi.fd_dict == NULL)
20170 v = find_var(name, &ht);
20171 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
20173 emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
20174 name);
20175 goto erret;
20178 fp = find_func(name);
20179 if (fp != NULL)
20181 if (!eap->forceit)
20183 emsg_funcname(e_funcexts, name);
20184 goto erret;
20186 if (fp->uf_calls > 0)
20188 emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"),
20189 name);
20190 goto erret;
20192 /* redefine existing function */
20193 ga_clear_strings(&(fp->uf_args));
20194 ga_clear_strings(&(fp->uf_lines));
20195 vim_free(name);
20196 name = NULL;
20199 else
20201 char numbuf[20];
20203 fp = NULL;
20204 if (fudi.fd_newkey == NULL && !eap->forceit)
20206 EMSG(_(e_funcdict));
20207 goto erret;
20209 if (fudi.fd_di == NULL)
20211 /* Can't add a function to a locked dictionary */
20212 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
20213 goto erret;
20215 /* Can't change an existing function if it is locked */
20216 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
20217 goto erret;
20219 /* Give the function a sequential number. Can only be used with a
20220 * Funcref! */
20221 vim_free(name);
20222 sprintf(numbuf, "%d", ++func_nr);
20223 name = vim_strsave((char_u *)numbuf);
20224 if (name == NULL)
20225 goto erret;
20228 if (fp == NULL)
20230 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
20232 int slen, plen;
20233 char_u *scriptname;
20235 /* Check that the autoload name matches the script name. */
20236 j = FAIL;
20237 if (sourcing_name != NULL)
20239 scriptname = autoload_name(name);
20240 if (scriptname != NULL)
20242 p = vim_strchr(scriptname, '/');
20243 plen = (int)STRLEN(p);
20244 slen = (int)STRLEN(sourcing_name);
20245 if (slen > plen && fnamecmp(p,
20246 sourcing_name + slen - plen) == 0)
20247 j = OK;
20248 vim_free(scriptname);
20251 if (j == FAIL)
20253 EMSG2(_("E746: Function name does not match script file name: %s"), name);
20254 goto erret;
20258 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
20259 if (fp == NULL)
20260 goto erret;
20262 if (fudi.fd_dict != NULL)
20264 if (fudi.fd_di == NULL)
20266 /* add new dict entry */
20267 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
20268 if (fudi.fd_di == NULL)
20270 vim_free(fp);
20271 goto erret;
20273 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
20275 vim_free(fudi.fd_di);
20276 vim_free(fp);
20277 goto erret;
20280 else
20281 /* overwrite existing dict entry */
20282 clear_tv(&fudi.fd_di->di_tv);
20283 fudi.fd_di->di_tv.v_type = VAR_FUNC;
20284 fudi.fd_di->di_tv.v_lock = 0;
20285 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
20286 fp->uf_refcount = 1;
20288 /* behave like "dict" was used */
20289 flags |= FC_DICT;
20292 /* insert the new function in the function list */
20293 STRCPY(fp->uf_name, name);
20294 hash_add(&func_hashtab, UF2HIKEY(fp));
20296 fp->uf_args = newargs;
20297 fp->uf_lines = newlines;
20298 #ifdef FEAT_PROFILE
20299 fp->uf_tml_count = NULL;
20300 fp->uf_tml_total = NULL;
20301 fp->uf_tml_self = NULL;
20302 fp->uf_profiling = FALSE;
20303 if (prof_def_func())
20304 func_do_profile(fp);
20305 #endif
20306 fp->uf_varargs = varargs;
20307 fp->uf_flags = flags;
20308 fp->uf_calls = 0;
20309 fp->uf_script_ID = current_SID;
20310 goto ret_free;
20312 erret:
20313 ga_clear_strings(&newargs);
20314 ga_clear_strings(&newlines);
20315 ret_free:
20316 vim_free(skip_until);
20317 vim_free(fudi.fd_newkey);
20318 vim_free(name);
20319 did_emsg |= saved_did_emsg;
20323 * Get a function name, translating "<SID>" and "<SNR>".
20324 * Also handles a Funcref in a List or Dictionary.
20325 * Returns the function name in allocated memory, or NULL for failure.
20326 * flags:
20327 * TFN_INT: internal function name OK
20328 * TFN_QUIET: be quiet
20329 * Advances "pp" to just after the function name (if no error).
20331 static char_u *
20332 trans_function_name(pp, skip, flags, fdp)
20333 char_u **pp;
20334 int skip; /* only find the end, don't evaluate */
20335 int flags;
20336 funcdict_T *fdp; /* return: info about dictionary used */
20338 char_u *name = NULL;
20339 char_u *start;
20340 char_u *end;
20341 int lead;
20342 char_u sid_buf[20];
20343 int len;
20344 lval_T lv;
20346 if (fdp != NULL)
20347 vim_memset(fdp, 0, sizeof(funcdict_T));
20348 start = *pp;
20350 /* Check for hard coded <SNR>: already translated function ID (from a user
20351 * command). */
20352 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
20353 && (*pp)[2] == (int)KE_SNR)
20355 *pp += 3;
20356 len = get_id_len(pp) + 3;
20357 return vim_strnsave(start, len);
20360 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
20361 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
20362 lead = eval_fname_script(start);
20363 if (lead > 2)
20364 start += lead;
20366 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
20367 lead > 2 ? 0 : FNE_CHECK_START);
20368 if (end == start)
20370 if (!skip)
20371 EMSG(_("E129: Function name required"));
20372 goto theend;
20374 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
20377 * Report an invalid expression in braces, unless the expression
20378 * evaluation has been cancelled due to an aborting error, an
20379 * interrupt, or an exception.
20381 if (!aborting())
20383 if (end != NULL)
20384 EMSG2(_(e_invarg2), start);
20386 else
20387 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
20388 goto theend;
20391 if (lv.ll_tv != NULL)
20393 if (fdp != NULL)
20395 fdp->fd_dict = lv.ll_dict;
20396 fdp->fd_newkey = lv.ll_newkey;
20397 lv.ll_newkey = NULL;
20398 fdp->fd_di = lv.ll_di;
20400 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
20402 name = vim_strsave(lv.ll_tv->vval.v_string);
20403 *pp = end;
20405 else
20407 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
20408 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
20409 EMSG(_(e_funcref));
20410 else
20411 *pp = end;
20412 name = NULL;
20414 goto theend;
20417 if (lv.ll_name == NULL)
20419 /* Error found, but continue after the function name. */
20420 *pp = end;
20421 goto theend;
20424 /* Check if the name is a Funcref. If so, use the value. */
20425 if (lv.ll_exp_name != NULL)
20427 len = (int)STRLEN(lv.ll_exp_name);
20428 name = deref_func_name(lv.ll_exp_name, &len);
20429 if (name == lv.ll_exp_name)
20430 name = NULL;
20432 else
20434 len = (int)(end - *pp);
20435 name = deref_func_name(*pp, &len);
20436 if (name == *pp)
20437 name = NULL;
20439 if (name != NULL)
20441 name = vim_strsave(name);
20442 *pp = end;
20443 goto theend;
20446 if (lv.ll_exp_name != NULL)
20448 len = (int)STRLEN(lv.ll_exp_name);
20449 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
20450 && STRNCMP(lv.ll_name, "s:", 2) == 0)
20452 /* When there was "s:" already or the name expanded to get a
20453 * leading "s:" then remove it. */
20454 lv.ll_name += 2;
20455 len -= 2;
20456 lead = 2;
20459 else
20461 if (lead == 2) /* skip over "s:" */
20462 lv.ll_name += 2;
20463 len = (int)(end - lv.ll_name);
20467 * Copy the function name to allocated memory.
20468 * Accept <SID>name() inside a script, translate into <SNR>123_name().
20469 * Accept <SNR>123_name() outside a script.
20471 if (skip)
20472 lead = 0; /* do nothing */
20473 else if (lead > 0)
20475 lead = 3;
20476 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
20477 || eval_fname_sid(*pp))
20479 /* It's "s:" or "<SID>" */
20480 if (current_SID <= 0)
20482 EMSG(_(e_usingsid));
20483 goto theend;
20485 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
20486 lead += (int)STRLEN(sid_buf);
20489 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
20491 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
20492 goto theend;
20494 name = alloc((unsigned)(len + lead + 1));
20495 if (name != NULL)
20497 if (lead > 0)
20499 name[0] = K_SPECIAL;
20500 name[1] = KS_EXTRA;
20501 name[2] = (int)KE_SNR;
20502 if (lead > 3) /* If it's "<SID>" */
20503 STRCPY(name + 3, sid_buf);
20505 mch_memmove(name + lead, lv.ll_name, (size_t)len);
20506 name[len + lead] = NUL;
20508 *pp = end;
20510 theend:
20511 clear_lval(&lv);
20512 return name;
20516 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
20517 * Return 2 if "p" starts with "s:".
20518 * Return 0 otherwise.
20520 static int
20521 eval_fname_script(p)
20522 char_u *p;
20524 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
20525 || STRNICMP(p + 1, "SNR>", 4) == 0))
20526 return 5;
20527 if (p[0] == 's' && p[1] == ':')
20528 return 2;
20529 return 0;
20533 * Return TRUE if "p" starts with "<SID>" or "s:".
20534 * Only works if eval_fname_script() returned non-zero for "p"!
20536 static int
20537 eval_fname_sid(p)
20538 char_u *p;
20540 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
20544 * List the head of the function: "name(arg1, arg2)".
20546 static void
20547 list_func_head(fp, indent)
20548 ufunc_T *fp;
20549 int indent;
20551 int j;
20553 msg_start();
20554 if (indent)
20555 MSG_PUTS(" ");
20556 MSG_PUTS("function ");
20557 if (fp->uf_name[0] == K_SPECIAL)
20559 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
20560 msg_puts(fp->uf_name + 3);
20562 else
20563 msg_puts(fp->uf_name);
20564 msg_putchar('(');
20565 for (j = 0; j < fp->uf_args.ga_len; ++j)
20567 if (j)
20568 MSG_PUTS(", ");
20569 msg_puts(FUNCARG(fp, j));
20571 if (fp->uf_varargs)
20573 if (j)
20574 MSG_PUTS(", ");
20575 MSG_PUTS("...");
20577 msg_putchar(')');
20578 msg_clr_eos();
20579 if (p_verbose > 0)
20580 last_set_msg(fp->uf_script_ID);
20584 * Find a function by name, return pointer to it in ufuncs.
20585 * Return NULL for unknown function.
20587 static ufunc_T *
20588 find_func(name)
20589 char_u *name;
20591 hashitem_T *hi;
20593 hi = hash_find(&func_hashtab, name);
20594 if (!HASHITEM_EMPTY(hi))
20595 return HI2UF(hi);
20596 return NULL;
20599 #if defined(EXITFREE) || defined(PROTO)
20600 void
20601 free_all_functions()
20603 hashitem_T *hi;
20605 /* Need to start all over every time, because func_free() may change the
20606 * hash table. */
20607 while (func_hashtab.ht_used > 0)
20608 for (hi = func_hashtab.ht_array; ; ++hi)
20609 if (!HASHITEM_EMPTY(hi))
20611 func_free(HI2UF(hi));
20612 break;
20615 #endif
20618 * Return TRUE if a function "name" exists.
20620 static int
20621 function_exists(name)
20622 char_u *name;
20624 char_u *nm = name;
20625 char_u *p;
20626 int n = FALSE;
20628 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
20629 nm = skipwhite(nm);
20631 /* Only accept "funcname", "funcname ", "funcname (..." and
20632 * "funcname(...", not "funcname!...". */
20633 if (p != NULL && (*nm == NUL || *nm == '('))
20635 if (builtin_function(p))
20636 n = (find_internal_func(p) >= 0);
20637 else
20638 n = (find_func(p) != NULL);
20640 vim_free(p);
20641 return n;
20645 * Return TRUE if "name" looks like a builtin function name: starts with a
20646 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
20648 static int
20649 builtin_function(name)
20650 char_u *name;
20652 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
20653 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
20656 #if defined(FEAT_PROFILE) || defined(PROTO)
20658 * Start profiling function "fp".
20660 static void
20661 func_do_profile(fp)
20662 ufunc_T *fp;
20664 fp->uf_tm_count = 0;
20665 profile_zero(&fp->uf_tm_self);
20666 profile_zero(&fp->uf_tm_total);
20667 if (fp->uf_tml_count == NULL)
20668 fp->uf_tml_count = (int *)alloc_clear((unsigned)
20669 (sizeof(int) * fp->uf_lines.ga_len));
20670 if (fp->uf_tml_total == NULL)
20671 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
20672 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20673 if (fp->uf_tml_self == NULL)
20674 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
20675 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20676 fp->uf_tml_idx = -1;
20677 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
20678 || fp->uf_tml_self == NULL)
20679 return; /* out of memory */
20681 fp->uf_profiling = TRUE;
20685 * Dump the profiling results for all functions in file "fd".
20687 void
20688 func_dump_profile(fd)
20689 FILE *fd;
20691 hashitem_T *hi;
20692 int todo;
20693 ufunc_T *fp;
20694 int i;
20695 ufunc_T **sorttab;
20696 int st_len = 0;
20698 todo = (int)func_hashtab.ht_used;
20699 if (todo == 0)
20700 return; /* nothing to dump */
20702 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
20704 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
20706 if (!HASHITEM_EMPTY(hi))
20708 --todo;
20709 fp = HI2UF(hi);
20710 if (fp->uf_profiling)
20712 if (sorttab != NULL)
20713 sorttab[st_len++] = fp;
20715 if (fp->uf_name[0] == K_SPECIAL)
20716 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
20717 else
20718 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
20719 if (fp->uf_tm_count == 1)
20720 fprintf(fd, "Called 1 time\n");
20721 else
20722 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
20723 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
20724 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
20725 fprintf(fd, "\n");
20726 fprintf(fd, "count total (s) self (s)\n");
20728 for (i = 0; i < fp->uf_lines.ga_len; ++i)
20730 if (FUNCLINE(fp, i) == NULL)
20731 continue;
20732 prof_func_line(fd, fp->uf_tml_count[i],
20733 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
20734 fprintf(fd, "%s\n", FUNCLINE(fp, i));
20736 fprintf(fd, "\n");
20741 if (sorttab != NULL && st_len > 0)
20743 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20744 prof_total_cmp);
20745 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
20746 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20747 prof_self_cmp);
20748 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
20751 vim_free(sorttab);
20754 static void
20755 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
20756 FILE *fd;
20757 ufunc_T **sorttab;
20758 int st_len;
20759 char *title;
20760 int prefer_self; /* when equal print only self time */
20762 int i;
20763 ufunc_T *fp;
20765 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
20766 fprintf(fd, "count total (s) self (s) function\n");
20767 for (i = 0; i < 20 && i < st_len; ++i)
20769 fp = sorttab[i];
20770 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
20771 prefer_self);
20772 if (fp->uf_name[0] == K_SPECIAL)
20773 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
20774 else
20775 fprintf(fd, " %s()\n", fp->uf_name);
20777 fprintf(fd, "\n");
20781 * Print the count and times for one function or function line.
20783 static void
20784 prof_func_line(fd, count, total, self, prefer_self)
20785 FILE *fd;
20786 int count;
20787 proftime_T *total;
20788 proftime_T *self;
20789 int prefer_self; /* when equal print only self time */
20791 if (count > 0)
20793 fprintf(fd, "%5d ", count);
20794 if (prefer_self && profile_equal(total, self))
20795 fprintf(fd, " ");
20796 else
20797 fprintf(fd, "%s ", profile_msg(total));
20798 if (!prefer_self && profile_equal(total, self))
20799 fprintf(fd, " ");
20800 else
20801 fprintf(fd, "%s ", profile_msg(self));
20803 else
20804 fprintf(fd, " ");
20808 * Compare function for total time sorting.
20810 static int
20811 #ifdef __BORLANDC__
20812 _RTLENTRYF
20813 #endif
20814 prof_total_cmp(s1, s2)
20815 const void *s1;
20816 const void *s2;
20818 ufunc_T *p1, *p2;
20820 p1 = *(ufunc_T **)s1;
20821 p2 = *(ufunc_T **)s2;
20822 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
20826 * Compare function for self time sorting.
20828 static int
20829 #ifdef __BORLANDC__
20830 _RTLENTRYF
20831 #endif
20832 prof_self_cmp(s1, s2)
20833 const void *s1;
20834 const void *s2;
20836 ufunc_T *p1, *p2;
20838 p1 = *(ufunc_T **)s1;
20839 p2 = *(ufunc_T **)s2;
20840 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
20843 #endif
20846 * If "name" has a package name try autoloading the script for it.
20847 * Return TRUE if a package was loaded.
20849 static int
20850 script_autoload(name, reload)
20851 char_u *name;
20852 int reload; /* load script again when already loaded */
20854 char_u *p;
20855 char_u *scriptname, *tofree;
20856 int ret = FALSE;
20857 int i;
20859 /* If there is no '#' after name[0] there is no package name. */
20860 p = vim_strchr(name, AUTOLOAD_CHAR);
20861 if (p == NULL || p == name)
20862 return FALSE;
20864 tofree = scriptname = autoload_name(name);
20866 /* Find the name in the list of previously loaded package names. Skip
20867 * "autoload/", it's always the same. */
20868 for (i = 0; i < ga_loaded.ga_len; ++i)
20869 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
20870 break;
20871 if (!reload && i < ga_loaded.ga_len)
20872 ret = FALSE; /* was loaded already */
20873 else
20875 /* Remember the name if it wasn't loaded already. */
20876 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
20878 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
20879 tofree = NULL;
20882 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
20883 if (source_runtime(scriptname, FALSE) == OK)
20884 ret = TRUE;
20887 vim_free(tofree);
20888 return ret;
20892 * Return the autoload script name for a function or variable name.
20893 * Returns NULL when out of memory.
20895 static char_u *
20896 autoload_name(name)
20897 char_u *name;
20899 char_u *p;
20900 char_u *scriptname;
20902 /* Get the script file name: replace '#' with '/', append ".vim". */
20903 scriptname = alloc((unsigned)(STRLEN(name) + 14));
20904 if (scriptname == NULL)
20905 return FALSE;
20906 STRCPY(scriptname, "autoload/");
20907 STRCAT(scriptname, name);
20908 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
20909 STRCAT(scriptname, ".vim");
20910 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
20911 *p = '/';
20912 return scriptname;
20915 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
20918 * Function given to ExpandGeneric() to obtain the list of user defined
20919 * function names.
20921 char_u *
20922 get_user_func_name(xp, idx)
20923 expand_T *xp;
20924 int idx;
20926 static long_u done;
20927 static hashitem_T *hi;
20928 ufunc_T *fp;
20930 if (idx == 0)
20932 done = 0;
20933 hi = func_hashtab.ht_array;
20935 if (done < func_hashtab.ht_used)
20937 if (done++ > 0)
20938 ++hi;
20939 while (HASHITEM_EMPTY(hi))
20940 ++hi;
20941 fp = HI2UF(hi);
20943 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
20944 return fp->uf_name; /* prevents overflow */
20946 cat_func_name(IObuff, fp);
20947 if (xp->xp_context != EXPAND_USER_FUNC)
20949 STRCAT(IObuff, "(");
20950 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
20951 STRCAT(IObuff, ")");
20953 return IObuff;
20955 return NULL;
20958 #endif /* FEAT_CMDL_COMPL */
20961 * Copy the function name of "fp" to buffer "buf".
20962 * "buf" must be able to hold the function name plus three bytes.
20963 * Takes care of script-local function names.
20965 static void
20966 cat_func_name(buf, fp)
20967 char_u *buf;
20968 ufunc_T *fp;
20970 if (fp->uf_name[0] == K_SPECIAL)
20972 STRCPY(buf, "<SNR>");
20973 STRCAT(buf, fp->uf_name + 3);
20975 else
20976 STRCPY(buf, fp->uf_name);
20980 * ":delfunction {name}"
20982 void
20983 ex_delfunction(eap)
20984 exarg_T *eap;
20986 ufunc_T *fp = NULL;
20987 char_u *p;
20988 char_u *name;
20989 funcdict_T fudi;
20991 p = eap->arg;
20992 name = trans_function_name(&p, eap->skip, 0, &fudi);
20993 vim_free(fudi.fd_newkey);
20994 if (name == NULL)
20996 if (fudi.fd_dict != NULL && !eap->skip)
20997 EMSG(_(e_funcref));
20998 return;
21000 if (!ends_excmd(*skipwhite(p)))
21002 vim_free(name);
21003 EMSG(_(e_trailing));
21004 return;
21006 eap->nextcmd = check_nextcmd(p);
21007 if (eap->nextcmd != NULL)
21008 *p = NUL;
21010 if (!eap->skip)
21011 fp = find_func(name);
21012 vim_free(name);
21014 if (!eap->skip)
21016 if (fp == NULL)
21018 EMSG2(_(e_nofunc), eap->arg);
21019 return;
21021 if (fp->uf_calls > 0)
21023 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
21024 return;
21027 if (fudi.fd_dict != NULL)
21029 /* Delete the dict item that refers to the function, it will
21030 * invoke func_unref() and possibly delete the function. */
21031 dictitem_remove(fudi.fd_dict, fudi.fd_di);
21033 else
21034 func_free(fp);
21039 * Free a function and remove it from the list of functions.
21041 static void
21042 func_free(fp)
21043 ufunc_T *fp;
21045 hashitem_T *hi;
21047 /* clear this function */
21048 ga_clear_strings(&(fp->uf_args));
21049 ga_clear_strings(&(fp->uf_lines));
21050 #ifdef FEAT_PROFILE
21051 vim_free(fp->uf_tml_count);
21052 vim_free(fp->uf_tml_total);
21053 vim_free(fp->uf_tml_self);
21054 #endif
21056 /* remove the function from the function hashtable */
21057 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
21058 if (HASHITEM_EMPTY(hi))
21059 EMSG2(_(e_intern2), "func_free()");
21060 else
21061 hash_remove(&func_hashtab, hi);
21063 vim_free(fp);
21067 * Unreference a Function: decrement the reference count and free it when it
21068 * becomes zero. Only for numbered functions.
21070 static void
21071 func_unref(name)
21072 char_u *name;
21074 ufunc_T *fp;
21076 if (name != NULL && isdigit(*name))
21078 fp = find_func(name);
21079 if (fp == NULL)
21080 EMSG2(_(e_intern2), "func_unref()");
21081 else if (--fp->uf_refcount <= 0)
21083 /* Only delete it when it's not being used. Otherwise it's done
21084 * when "uf_calls" becomes zero. */
21085 if (fp->uf_calls == 0)
21086 func_free(fp);
21092 * Count a reference to a Function.
21094 static void
21095 func_ref(name)
21096 char_u *name;
21098 ufunc_T *fp;
21100 if (name != NULL && isdigit(*name))
21102 fp = find_func(name);
21103 if (fp == NULL)
21104 EMSG2(_(e_intern2), "func_ref()");
21105 else
21106 ++fp->uf_refcount;
21111 * Call a user function.
21113 static void
21114 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
21115 ufunc_T *fp; /* pointer to function */
21116 int argcount; /* nr of args */
21117 typval_T *argvars; /* arguments */
21118 typval_T *rettv; /* return value */
21119 linenr_T firstline; /* first line of range */
21120 linenr_T lastline; /* last line of range */
21121 dict_T *selfdict; /* Dictionary for "self" */
21123 char_u *save_sourcing_name;
21124 linenr_T save_sourcing_lnum;
21125 scid_T save_current_SID;
21126 funccall_T *fc;
21127 int save_did_emsg;
21128 static int depth = 0;
21129 dictitem_T *v;
21130 int fixvar_idx = 0; /* index in fixvar[] */
21131 int i;
21132 int ai;
21133 char_u numbuf[NUMBUFLEN];
21134 char_u *name;
21135 #ifdef FEAT_PROFILE
21136 proftime_T wait_start;
21137 proftime_T call_start;
21138 #endif
21140 /* If depth of calling is getting too high, don't execute the function */
21141 if (depth >= p_mfd)
21143 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
21144 rettv->v_type = VAR_NUMBER;
21145 rettv->vval.v_number = -1;
21146 return;
21148 ++depth;
21150 line_breakcheck(); /* check for CTRL-C hit */
21152 fc = (funccall_T *)alloc(sizeof(funccall_T));
21153 fc->caller = current_funccal;
21154 current_funccal = fc;
21155 fc->func = fp;
21156 fc->rettv = rettv;
21157 rettv->vval.v_number = 0;
21158 fc->linenr = 0;
21159 fc->returned = FALSE;
21160 fc->level = ex_nesting_level;
21161 /* Check if this function has a breakpoint. */
21162 fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
21163 fc->dbg_tick = debug_tick;
21166 * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables
21167 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
21168 * each argument variable and saves a lot of time.
21171 * Init l: variables.
21173 init_var_dict(&fc->l_vars, &fc->l_vars_var);
21174 if (selfdict != NULL)
21176 /* Set l:self to "selfdict". Use "name" to avoid a warning from
21177 * some compiler that checks the destination size. */
21178 v = &fc->fixvar[fixvar_idx++].var;
21179 name = v->di_key;
21180 STRCPY(name, "self");
21181 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
21182 hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
21183 v->di_tv.v_type = VAR_DICT;
21184 v->di_tv.v_lock = 0;
21185 v->di_tv.vval.v_dict = selfdict;
21186 ++selfdict->dv_refcount;
21190 * Init a: variables.
21191 * Set a:0 to "argcount".
21192 * Set a:000 to a list with room for the "..." arguments.
21194 init_var_dict(&fc->l_avars, &fc->l_avars_var);
21195 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0",
21196 (varnumber_T)(argcount - fp->uf_args.ga_len));
21197 /* Use "name" to avoid a warning from some compiler that checks the
21198 * destination size. */
21199 v = &fc->fixvar[fixvar_idx++].var;
21200 name = v->di_key;
21201 STRCPY(name, "000");
21202 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21203 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21204 v->di_tv.v_type = VAR_LIST;
21205 v->di_tv.v_lock = VAR_FIXED;
21206 v->di_tv.vval.v_list = &fc->l_varlist;
21207 vim_memset(&fc->l_varlist, 0, sizeof(list_T));
21208 fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT;
21209 fc->l_varlist.lv_lock = VAR_FIXED;
21212 * Set a:firstline to "firstline" and a:lastline to "lastline".
21213 * Set a:name to named arguments.
21214 * Set a:N to the "..." arguments.
21216 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline",
21217 (varnumber_T)firstline);
21218 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline",
21219 (varnumber_T)lastline);
21220 for (i = 0; i < argcount; ++i)
21222 ai = i - fp->uf_args.ga_len;
21223 if (ai < 0)
21224 /* named argument a:name */
21225 name = FUNCARG(fp, i);
21226 else
21228 /* "..." argument a:1, a:2, etc. */
21229 sprintf((char *)numbuf, "%d", ai + 1);
21230 name = numbuf;
21232 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
21234 v = &fc->fixvar[fixvar_idx++].var;
21235 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21237 else
21239 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
21240 + STRLEN(name)));
21241 if (v == NULL)
21242 break;
21243 v->di_flags = DI_FLAGS_RO;
21245 STRCPY(v->di_key, name);
21246 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21248 /* Note: the values are copied directly to avoid alloc/free.
21249 * "argvars" must have VAR_FIXED for v_lock. */
21250 v->di_tv = argvars[i];
21251 v->di_tv.v_lock = VAR_FIXED;
21253 if (ai >= 0 && ai < MAX_FUNC_ARGS)
21255 list_append(&fc->l_varlist, &fc->l_listitems[ai]);
21256 fc->l_listitems[ai].li_tv = argvars[i];
21257 fc->l_listitems[ai].li_tv.v_lock = VAR_FIXED;
21261 /* Don't redraw while executing the function. */
21262 ++RedrawingDisabled;
21263 save_sourcing_name = sourcing_name;
21264 save_sourcing_lnum = sourcing_lnum;
21265 sourcing_lnum = 1;
21266 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
21267 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
21268 if (sourcing_name != NULL)
21270 if (save_sourcing_name != NULL
21271 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
21272 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
21273 else
21274 STRCPY(sourcing_name, "function ");
21275 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
21277 if (p_verbose >= 12)
21279 ++no_wait_return;
21280 verbose_enter_scroll();
21282 smsg((char_u *)_("calling %s"), sourcing_name);
21283 if (p_verbose >= 14)
21285 char_u buf[MSG_BUF_LEN];
21286 char_u numbuf2[NUMBUFLEN];
21287 char_u *tofree;
21288 char_u *s;
21290 msg_puts((char_u *)"(");
21291 for (i = 0; i < argcount; ++i)
21293 if (i > 0)
21294 msg_puts((char_u *)", ");
21295 if (argvars[i].v_type == VAR_NUMBER)
21296 msg_outnum((long)argvars[i].vval.v_number);
21297 else
21299 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
21300 if (s != NULL)
21302 trunc_string(s, buf, MSG_BUF_CLEN);
21303 msg_puts(buf);
21304 vim_free(tofree);
21308 msg_puts((char_u *)")");
21310 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21312 verbose_leave_scroll();
21313 --no_wait_return;
21316 #ifdef FEAT_PROFILE
21317 if (do_profiling == PROF_YES)
21319 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
21320 func_do_profile(fp);
21321 if (fp->uf_profiling
21322 || (fc->caller != NULL && fc->caller->func->uf_profiling))
21324 ++fp->uf_tm_count;
21325 profile_start(&call_start);
21326 profile_zero(&fp->uf_tm_children);
21328 script_prof_save(&wait_start);
21330 #endif
21332 save_current_SID = current_SID;
21333 current_SID = fp->uf_script_ID;
21334 save_did_emsg = did_emsg;
21335 did_emsg = FALSE;
21337 /* call do_cmdline() to execute the lines */
21338 do_cmdline(NULL, get_func_line, (void *)fc,
21339 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
21341 --RedrawingDisabled;
21343 /* when the function was aborted because of an error, return -1 */
21344 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
21346 clear_tv(rettv);
21347 rettv->v_type = VAR_NUMBER;
21348 rettv->vval.v_number = -1;
21351 #ifdef FEAT_PROFILE
21352 if (do_profiling == PROF_YES && (fp->uf_profiling
21353 || (fc->caller != NULL && fc->caller->func->uf_profiling)))
21355 profile_end(&call_start);
21356 profile_sub_wait(&wait_start, &call_start);
21357 profile_add(&fp->uf_tm_total, &call_start);
21358 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
21359 if (fc->caller != NULL && fc->caller->func->uf_profiling)
21361 profile_add(&fc->caller->func->uf_tm_children, &call_start);
21362 profile_add(&fc->caller->func->uf_tml_children, &call_start);
21365 #endif
21367 /* when being verbose, mention the return value */
21368 if (p_verbose >= 12)
21370 ++no_wait_return;
21371 verbose_enter_scroll();
21373 if (aborting())
21374 smsg((char_u *)_("%s aborted"), sourcing_name);
21375 else if (fc->rettv->v_type == VAR_NUMBER)
21376 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
21377 (long)fc->rettv->vval.v_number);
21378 else
21380 char_u buf[MSG_BUF_LEN];
21381 char_u numbuf2[NUMBUFLEN];
21382 char_u *tofree;
21383 char_u *s;
21385 /* The value may be very long. Skip the middle part, so that we
21386 * have some idea how it starts and ends. smsg() would always
21387 * truncate it at the end. */
21388 s = tv2string(fc->rettv, &tofree, numbuf2, 0);
21389 if (s != NULL)
21391 trunc_string(s, buf, MSG_BUF_CLEN);
21392 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
21393 vim_free(tofree);
21396 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21398 verbose_leave_scroll();
21399 --no_wait_return;
21402 vim_free(sourcing_name);
21403 sourcing_name = save_sourcing_name;
21404 sourcing_lnum = save_sourcing_lnum;
21405 current_SID = save_current_SID;
21406 #ifdef FEAT_PROFILE
21407 if (do_profiling == PROF_YES)
21408 script_prof_restore(&wait_start);
21409 #endif
21411 if (p_verbose >= 12 && sourcing_name != NULL)
21413 ++no_wait_return;
21414 verbose_enter_scroll();
21416 smsg((char_u *)_("continuing in %s"), sourcing_name);
21417 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21419 verbose_leave_scroll();
21420 --no_wait_return;
21423 did_emsg |= save_did_emsg;
21424 current_funccal = fc->caller;
21425 --depth;
21427 /* If the a:000 list and the l: and a: dicts are not referenced we can
21428 * free the funccall_T and what's in it. */
21429 if (fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
21430 && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
21431 && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT)
21433 free_funccal(fc, FALSE);
21435 else
21437 hashitem_T *hi;
21438 listitem_T *li;
21439 int todo;
21441 /* "fc" is still in use. This can happen when returning "a:000" or
21442 * assigning "l:" to a global variable.
21443 * Link "fc" in the list for garbage collection later. */
21444 fc->caller = previous_funccal;
21445 previous_funccal = fc;
21447 /* Make a copy of the a: variables, since we didn't do that above. */
21448 todo = (int)fc->l_avars.dv_hashtab.ht_used;
21449 for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi)
21451 if (!HASHITEM_EMPTY(hi))
21453 --todo;
21454 v = HI2DI(hi);
21455 copy_tv(&v->di_tv, &v->di_tv);
21459 /* Make a copy of the a:000 items, since we didn't do that above. */
21460 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21461 copy_tv(&li->li_tv, &li->li_tv);
21466 * Return TRUE if items in "fc" do not have "copyID". That means they are not
21467 * referenced from anywhere that is in use.
21469 static int
21470 can_free_funccal(fc, copyID)
21471 funccall_T *fc;
21472 int copyID;
21474 return (fc->l_varlist.lv_copyID != copyID
21475 && fc->l_vars.dv_copyID != copyID
21476 && fc->l_avars.dv_copyID != copyID);
21480 * Free "fc" and what it contains.
21482 static void
21483 free_funccal(fc, free_val)
21484 funccall_T *fc;
21485 int free_val; /* a: vars were allocated */
21487 listitem_T *li;
21489 /* The a: variables typevals may not have been allocated, only free the
21490 * allocated variables. */
21491 vars_clear_ext(&fc->l_avars.dv_hashtab, free_val);
21493 /* free all l: variables */
21494 vars_clear(&fc->l_vars.dv_hashtab);
21496 /* Free the a:000 variables if they were allocated. */
21497 if (free_val)
21498 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21499 clear_tv(&li->li_tv);
21501 vim_free(fc);
21505 * Add a number variable "name" to dict "dp" with value "nr".
21507 static void
21508 add_nr_var(dp, v, name, nr)
21509 dict_T *dp;
21510 dictitem_T *v;
21511 char *name;
21512 varnumber_T nr;
21514 STRCPY(v->di_key, name);
21515 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21516 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
21517 v->di_tv.v_type = VAR_NUMBER;
21518 v->di_tv.v_lock = VAR_FIXED;
21519 v->di_tv.vval.v_number = nr;
21523 * ":return [expr]"
21525 void
21526 ex_return(eap)
21527 exarg_T *eap;
21529 char_u *arg = eap->arg;
21530 typval_T rettv;
21531 int returning = FALSE;
21533 if (current_funccal == NULL)
21535 EMSG(_("E133: :return not inside a function"));
21536 return;
21539 if (eap->skip)
21540 ++emsg_skip;
21542 eap->nextcmd = NULL;
21543 if ((*arg != NUL && *arg != '|' && *arg != '\n')
21544 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
21546 if (!eap->skip)
21547 returning = do_return(eap, FALSE, TRUE, &rettv);
21548 else
21549 clear_tv(&rettv);
21551 /* It's safer to return also on error. */
21552 else if (!eap->skip)
21555 * Return unless the expression evaluation has been cancelled due to an
21556 * aborting error, an interrupt, or an exception.
21558 if (!aborting())
21559 returning = do_return(eap, FALSE, TRUE, NULL);
21562 /* When skipping or the return gets pending, advance to the next command
21563 * in this line (!returning). Otherwise, ignore the rest of the line.
21564 * Following lines will be ignored by get_func_line(). */
21565 if (returning)
21566 eap->nextcmd = NULL;
21567 else if (eap->nextcmd == NULL) /* no argument */
21568 eap->nextcmd = check_nextcmd(arg);
21570 if (eap->skip)
21571 --emsg_skip;
21575 * Return from a function. Possibly makes the return pending. Also called
21576 * for a pending return at the ":endtry" or after returning from an extra
21577 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
21578 * when called due to a ":return" command. "rettv" may point to a typval_T
21579 * with the return rettv. Returns TRUE when the return can be carried out,
21580 * FALSE when the return gets pending.
21583 do_return(eap, reanimate, is_cmd, rettv)
21584 exarg_T *eap;
21585 int reanimate;
21586 int is_cmd;
21587 void *rettv;
21589 int idx;
21590 struct condstack *cstack = eap->cstack;
21592 if (reanimate)
21593 /* Undo the return. */
21594 current_funccal->returned = FALSE;
21597 * Cleanup (and inactivate) conditionals, but stop when a try conditional
21598 * not in its finally clause (which then is to be executed next) is found.
21599 * In this case, make the ":return" pending for execution at the ":endtry".
21600 * Otherwise, return normally.
21602 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
21603 if (idx >= 0)
21605 cstack->cs_pending[idx] = CSTP_RETURN;
21607 if (!is_cmd && !reanimate)
21608 /* A pending return again gets pending. "rettv" points to an
21609 * allocated variable with the rettv of the original ":return"'s
21610 * argument if present or is NULL else. */
21611 cstack->cs_rettv[idx] = rettv;
21612 else
21614 /* When undoing a return in order to make it pending, get the stored
21615 * return rettv. */
21616 if (reanimate)
21617 rettv = current_funccal->rettv;
21619 if (rettv != NULL)
21621 /* Store the value of the pending return. */
21622 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
21623 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
21624 else
21625 EMSG(_(e_outofmem));
21627 else
21628 cstack->cs_rettv[idx] = NULL;
21630 if (reanimate)
21632 /* The pending return value could be overwritten by a ":return"
21633 * without argument in a finally clause; reset the default
21634 * return value. */
21635 current_funccal->rettv->v_type = VAR_NUMBER;
21636 current_funccal->rettv->vval.v_number = 0;
21639 report_make_pending(CSTP_RETURN, rettv);
21641 else
21643 current_funccal->returned = TRUE;
21645 /* If the return is carried out now, store the return value. For
21646 * a return immediately after reanimation, the value is already
21647 * there. */
21648 if (!reanimate && rettv != NULL)
21650 clear_tv(current_funccal->rettv);
21651 *current_funccal->rettv = *(typval_T *)rettv;
21652 if (!is_cmd)
21653 vim_free(rettv);
21657 return idx < 0;
21661 * Free the variable with a pending return value.
21663 void
21664 discard_pending_return(rettv)
21665 void *rettv;
21667 free_tv((typval_T *)rettv);
21671 * Generate a return command for producing the value of "rettv". The result
21672 * is an allocated string. Used by report_pending() for verbose messages.
21674 char_u *
21675 get_return_cmd(rettv)
21676 void *rettv;
21678 char_u *s = NULL;
21679 char_u *tofree = NULL;
21680 char_u numbuf[NUMBUFLEN];
21682 if (rettv != NULL)
21683 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
21684 if (s == NULL)
21685 s = (char_u *)"";
21687 STRCPY(IObuff, ":return ");
21688 STRNCPY(IObuff + 8, s, IOSIZE - 8);
21689 if (STRLEN(s) + 8 >= IOSIZE)
21690 STRCPY(IObuff + IOSIZE - 4, "...");
21691 vim_free(tofree);
21692 return vim_strsave(IObuff);
21696 * Get next function line.
21697 * Called by do_cmdline() to get the next line.
21698 * Returns allocated string, or NULL for end of function.
21700 char_u *
21701 get_func_line(c, cookie, indent)
21702 int c UNUSED;
21703 void *cookie;
21704 int indent UNUSED;
21706 funccall_T *fcp = (funccall_T *)cookie;
21707 ufunc_T *fp = fcp->func;
21708 char_u *retval;
21709 garray_T *gap; /* growarray with function lines */
21711 /* If breakpoints have been added/deleted need to check for it. */
21712 if (fcp->dbg_tick != debug_tick)
21714 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21715 sourcing_lnum);
21716 fcp->dbg_tick = debug_tick;
21718 #ifdef FEAT_PROFILE
21719 if (do_profiling == PROF_YES)
21720 func_line_end(cookie);
21721 #endif
21723 gap = &fp->uf_lines;
21724 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21725 || fcp->returned)
21726 retval = NULL;
21727 else
21729 /* Skip NULL lines (continuation lines). */
21730 while (fcp->linenr < gap->ga_len
21731 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
21732 ++fcp->linenr;
21733 if (fcp->linenr >= gap->ga_len)
21734 retval = NULL;
21735 else
21737 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
21738 sourcing_lnum = fcp->linenr;
21739 #ifdef FEAT_PROFILE
21740 if (do_profiling == PROF_YES)
21741 func_line_start(cookie);
21742 #endif
21746 /* Did we encounter a breakpoint? */
21747 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
21749 dbg_breakpoint(fp->uf_name, sourcing_lnum);
21750 /* Find next breakpoint. */
21751 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21752 sourcing_lnum);
21753 fcp->dbg_tick = debug_tick;
21756 return retval;
21759 #if defined(FEAT_PROFILE) || defined(PROTO)
21761 * Called when starting to read a function line.
21762 * "sourcing_lnum" must be correct!
21763 * When skipping lines it may not actually be executed, but we won't find out
21764 * until later and we need to store the time now.
21766 void
21767 func_line_start(cookie)
21768 void *cookie;
21770 funccall_T *fcp = (funccall_T *)cookie;
21771 ufunc_T *fp = fcp->func;
21773 if (fp->uf_profiling && sourcing_lnum >= 1
21774 && sourcing_lnum <= fp->uf_lines.ga_len)
21776 fp->uf_tml_idx = sourcing_lnum - 1;
21777 /* Skip continuation lines. */
21778 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
21779 --fp->uf_tml_idx;
21780 fp->uf_tml_execed = FALSE;
21781 profile_start(&fp->uf_tml_start);
21782 profile_zero(&fp->uf_tml_children);
21783 profile_get_wait(&fp->uf_tml_wait);
21788 * Called when actually executing a function line.
21790 void
21791 func_line_exec(cookie)
21792 void *cookie;
21794 funccall_T *fcp = (funccall_T *)cookie;
21795 ufunc_T *fp = fcp->func;
21797 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21798 fp->uf_tml_execed = TRUE;
21802 * Called when done with a function line.
21804 void
21805 func_line_end(cookie)
21806 void *cookie;
21808 funccall_T *fcp = (funccall_T *)cookie;
21809 ufunc_T *fp = fcp->func;
21811 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21813 if (fp->uf_tml_execed)
21815 ++fp->uf_tml_count[fp->uf_tml_idx];
21816 profile_end(&fp->uf_tml_start);
21817 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
21818 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
21819 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
21820 &fp->uf_tml_children);
21822 fp->uf_tml_idx = -1;
21825 #endif
21828 * Return TRUE if the currently active function should be ended, because a
21829 * return was encountered or an error occurred. Used inside a ":while".
21832 func_has_ended(cookie)
21833 void *cookie;
21835 funccall_T *fcp = (funccall_T *)cookie;
21837 /* Ignore the "abort" flag if the abortion behavior has been changed due to
21838 * an error inside a try conditional. */
21839 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21840 || fcp->returned);
21844 * return TRUE if cookie indicates a function which "abort"s on errors.
21847 func_has_abort(cookie)
21848 void *cookie;
21850 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
21853 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
21854 typedef enum
21856 VAR_FLAVOUR_DEFAULT, /* doesn't start with uppercase */
21857 VAR_FLAVOUR_SESSION, /* starts with uppercase, some lower */
21858 VAR_FLAVOUR_VIMINFO /* all uppercase */
21859 } var_flavour_T;
21861 static var_flavour_T var_flavour __ARGS((char_u *varname));
21863 static var_flavour_T
21864 var_flavour(varname)
21865 char_u *varname;
21867 char_u *p = varname;
21869 if (ASCII_ISUPPER(*p))
21871 while (*(++p))
21872 if (ASCII_ISLOWER(*p))
21873 return VAR_FLAVOUR_SESSION;
21874 return VAR_FLAVOUR_VIMINFO;
21876 else
21877 return VAR_FLAVOUR_DEFAULT;
21879 #endif
21881 #if defined(FEAT_VIMINFO) || defined(PROTO)
21883 * Restore global vars that start with a capital from the viminfo file
21886 read_viminfo_varlist(virp, writing)
21887 vir_T *virp;
21888 int writing;
21890 char_u *tab;
21891 int type = VAR_NUMBER;
21892 typval_T tv;
21894 if (!writing && (find_viminfo_parameter('!') != NULL))
21896 tab = vim_strchr(virp->vir_line + 1, '\t');
21897 if (tab != NULL)
21899 *tab++ = '\0'; /* isolate the variable name */
21900 if (*tab == 'S') /* string var */
21901 type = VAR_STRING;
21902 #ifdef FEAT_FLOAT
21903 else if (*tab == 'F')
21904 type = VAR_FLOAT;
21905 #endif
21907 tab = vim_strchr(tab, '\t');
21908 if (tab != NULL)
21910 tv.v_type = type;
21911 if (type == VAR_STRING)
21912 tv.vval.v_string = viminfo_readstring(virp,
21913 (int)(tab - virp->vir_line + 1), TRUE);
21914 #ifdef FEAT_FLOAT
21915 else if (type == VAR_FLOAT)
21916 (void)string2float(tab + 1, &tv.vval.v_float);
21917 #endif
21918 else
21919 tv.vval.v_number = atol((char *)tab + 1);
21920 set_var(virp->vir_line + 1, &tv, FALSE);
21921 if (type == VAR_STRING)
21922 vim_free(tv.vval.v_string);
21927 return viminfo_readline(virp);
21931 * Write global vars that start with a capital to the viminfo file
21933 void
21934 write_viminfo_varlist(fp)
21935 FILE *fp;
21937 hashitem_T *hi;
21938 dictitem_T *this_var;
21939 int todo;
21940 char *s;
21941 char_u *p;
21942 char_u *tofree;
21943 char_u numbuf[NUMBUFLEN];
21945 if (find_viminfo_parameter('!') == NULL)
21946 return;
21948 fputs(_("\n# global variables:\n"), fp);
21950 todo = (int)globvarht.ht_used;
21951 for (hi = globvarht.ht_array; todo > 0; ++hi)
21953 if (!HASHITEM_EMPTY(hi))
21955 --todo;
21956 this_var = HI2DI(hi);
21957 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
21959 switch (this_var->di_tv.v_type)
21961 case VAR_STRING: s = "STR"; break;
21962 case VAR_NUMBER: s = "NUM"; break;
21963 #ifdef FEAT_FLOAT
21964 case VAR_FLOAT: s = "FLO"; break;
21965 #endif
21966 default: continue;
21968 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
21969 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
21970 if (p != NULL)
21971 viminfo_writestring(fp, p);
21972 vim_free(tofree);
21977 #endif
21979 #if defined(FEAT_SESSION) || defined(PROTO)
21981 store_session_globals(fd)
21982 FILE *fd;
21984 hashitem_T *hi;
21985 dictitem_T *this_var;
21986 int todo;
21987 char_u *p, *t;
21989 todo = (int)globvarht.ht_used;
21990 for (hi = globvarht.ht_array; todo > 0; ++hi)
21992 if (!HASHITEM_EMPTY(hi))
21994 --todo;
21995 this_var = HI2DI(hi);
21996 if ((this_var->di_tv.v_type == VAR_NUMBER
21997 || this_var->di_tv.v_type == VAR_STRING)
21998 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22000 /* Escape special characters with a backslash. Turn a LF and
22001 * CR into \n and \r. */
22002 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
22003 (char_u *)"\\\"\n\r");
22004 if (p == NULL) /* out of memory */
22005 break;
22006 for (t = p; *t != NUL; ++t)
22007 if (*t == '\n')
22008 *t = 'n';
22009 else if (*t == '\r')
22010 *t = 'r';
22011 if ((fprintf(fd, "let %s = %c%s%c",
22012 this_var->di_key,
22013 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22014 : ' ',
22016 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22017 : ' ') < 0)
22018 || put_eol(fd) == FAIL)
22020 vim_free(p);
22021 return FAIL;
22023 vim_free(p);
22025 #ifdef FEAT_FLOAT
22026 else if (this_var->di_tv.v_type == VAR_FLOAT
22027 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22029 float_T f = this_var->di_tv.vval.v_float;
22030 int sign = ' ';
22032 if (f < 0)
22034 f = -f;
22035 sign = '-';
22037 if ((fprintf(fd, "let %s = %c&%f",
22038 this_var->di_key, sign, f) < 0)
22039 || put_eol(fd) == FAIL)
22040 return FAIL;
22042 #endif
22045 return OK;
22047 #endif
22050 * Display script name where an item was last set.
22051 * Should only be invoked when 'verbose' is non-zero.
22053 void
22054 last_set_msg(scriptID)
22055 scid_T scriptID;
22057 char_u *p;
22059 if (scriptID != 0)
22061 p = home_replace_save(NULL, get_scriptname(scriptID));
22062 if (p != NULL)
22064 verbose_enter();
22065 MSG_PUTS(_("\n\tLast set from "));
22066 MSG_PUTS(p);
22067 vim_free(p);
22068 verbose_leave();
22074 * List v:oldfiles in a nice way.
22076 void
22077 ex_oldfiles(eap)
22078 exarg_T *eap UNUSED;
22080 list_T *l = vimvars[VV_OLDFILES].vv_list;
22081 listitem_T *li;
22082 int nr = 0;
22084 if (l == NULL)
22085 msg((char_u *)_("No old files"));
22086 else
22088 msg_start();
22089 msg_scroll = TRUE;
22090 for (li = l->lv_first; li != NULL && !got_int; li = li->li_next)
22092 msg_outnum((long)++nr);
22093 MSG_PUTS(": ");
22094 msg_outtrans(get_tv_string(&li->li_tv));
22095 msg_putchar('\n');
22096 out_flush(); /* output one line at a time */
22097 ui_breakcheck();
22099 /* Assume "got_int" was set to truncate the listing. */
22100 got_int = FALSE;
22102 #ifdef FEAT_BROWSE_CMD
22103 if (cmdmod.browse)
22105 quit_more = FALSE;
22106 nr = prompt_for_number(FALSE);
22107 msg_starthere();
22108 if (nr > 0)
22110 char_u *p = list_find_str(get_vim_var_list(VV_OLDFILES),
22111 (long)nr);
22113 if (p != NULL)
22115 p = expand_env_save(p);
22116 eap->arg = p;
22117 eap->cmdidx = CMD_edit;
22118 cmdmod.browse = FALSE;
22119 do_exedit(eap, NULL);
22120 vim_free(p);
22124 #endif
22128 #endif /* FEAT_EVAL */
22131 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
22133 #ifdef WIN3264
22135 * Functions for ":8" filename modifier: get 8.3 version of a filename.
22137 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22138 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
22139 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22142 * Get the short path (8.3) for the filename in "fnamep".
22143 * Only works for a valid file name.
22144 * When the path gets longer "fnamep" is changed and the allocated buffer
22145 * is put in "bufp".
22146 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
22147 * Returns OK on success, FAIL on failure.
22149 static int
22150 get_short_pathname(fnamep, bufp, fnamelen)
22151 char_u **fnamep;
22152 char_u **bufp;
22153 int *fnamelen;
22155 int l, len;
22156 char_u *newbuf;
22158 len = *fnamelen;
22159 l = GetShortPathName(*fnamep, *fnamep, len);
22160 if (l > len - 1)
22162 /* If that doesn't work (not enough space), then save the string
22163 * and try again with a new buffer big enough. */
22164 newbuf = vim_strnsave(*fnamep, l);
22165 if (newbuf == NULL)
22166 return FAIL;
22168 vim_free(*bufp);
22169 *fnamep = *bufp = newbuf;
22171 /* Really should always succeed, as the buffer is big enough. */
22172 l = GetShortPathName(*fnamep, *fnamep, l+1);
22175 *fnamelen = l;
22176 return OK;
22180 * Get the short path (8.3) for the filename in "fname". The converted
22181 * path is returned in "bufp".
22183 * Some of the directories specified in "fname" may not exist. This function
22184 * will shorten the existing directories at the beginning of the path and then
22185 * append the remaining non-existing path.
22187 * fname - Pointer to the filename to shorten. On return, contains the
22188 * pointer to the shortened pathname
22189 * bufp - Pointer to an allocated buffer for the filename.
22190 * fnamelen - Length of the filename pointed to by fname
22192 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
22194 static int
22195 shortpath_for_invalid_fname(fname, bufp, fnamelen)
22196 char_u **fname;
22197 char_u **bufp;
22198 int *fnamelen;
22200 char_u *short_fname, *save_fname, *pbuf_unused;
22201 char_u *endp, *save_endp;
22202 char_u ch;
22203 int old_len, len;
22204 int new_len, sfx_len;
22205 int retval = OK;
22207 /* Make a copy */
22208 old_len = *fnamelen;
22209 save_fname = vim_strnsave(*fname, old_len);
22210 pbuf_unused = NULL;
22211 short_fname = NULL;
22213 endp = save_fname + old_len - 1; /* Find the end of the copy */
22214 save_endp = endp;
22217 * Try shortening the supplied path till it succeeds by removing one
22218 * directory at a time from the tail of the path.
22220 len = 0;
22221 for (;;)
22223 /* go back one path-separator */
22224 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
22225 --endp;
22226 if (endp <= save_fname)
22227 break; /* processed the complete path */
22230 * Replace the path separator with a NUL and try to shorten the
22231 * resulting path.
22233 ch = *endp;
22234 *endp = 0;
22235 short_fname = save_fname;
22236 len = (int)STRLEN(short_fname) + 1;
22237 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
22239 retval = FAIL;
22240 goto theend;
22242 *endp = ch; /* preserve the string */
22244 if (len > 0)
22245 break; /* successfully shortened the path */
22247 /* failed to shorten the path. Skip the path separator */
22248 --endp;
22251 if (len > 0)
22254 * Succeeded in shortening the path. Now concatenate the shortened
22255 * path with the remaining path at the tail.
22258 /* Compute the length of the new path. */
22259 sfx_len = (int)(save_endp - endp) + 1;
22260 new_len = len + sfx_len;
22262 *fnamelen = new_len;
22263 vim_free(*bufp);
22264 if (new_len > old_len)
22266 /* There is not enough space in the currently allocated string,
22267 * copy it to a buffer big enough. */
22268 *fname = *bufp = vim_strnsave(short_fname, new_len);
22269 if (*fname == NULL)
22271 retval = FAIL;
22272 goto theend;
22275 else
22277 /* Transfer short_fname to the main buffer (it's big enough),
22278 * unless get_short_pathname() did its work in-place. */
22279 *fname = *bufp = save_fname;
22280 if (short_fname != save_fname)
22281 vim_strncpy(save_fname, short_fname, len);
22282 save_fname = NULL;
22285 /* concat the not-shortened part of the path */
22286 vim_strncpy(*fname + len, endp, sfx_len);
22287 (*fname)[new_len] = NUL;
22290 theend:
22291 vim_free(pbuf_unused);
22292 vim_free(save_fname);
22294 return retval;
22298 * Get a pathname for a partial path.
22299 * Returns OK for success, FAIL for failure.
22301 static int
22302 shortpath_for_partial(fnamep, bufp, fnamelen)
22303 char_u **fnamep;
22304 char_u **bufp;
22305 int *fnamelen;
22307 int sepcount, len, tflen;
22308 char_u *p;
22309 char_u *pbuf, *tfname;
22310 int hasTilde;
22312 /* Count up the path separators from the RHS.. so we know which part
22313 * of the path to return. */
22314 sepcount = 0;
22315 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
22316 if (vim_ispathsep(*p))
22317 ++sepcount;
22319 /* Need full path first (use expand_env() to remove a "~/") */
22320 hasTilde = (**fnamep == '~');
22321 if (hasTilde)
22322 pbuf = tfname = expand_env_save(*fnamep);
22323 else
22324 pbuf = tfname = FullName_save(*fnamep, FALSE);
22326 len = tflen = (int)STRLEN(tfname);
22328 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
22329 return FAIL;
22331 if (len == 0)
22333 /* Don't have a valid filename, so shorten the rest of the
22334 * path if we can. This CAN give us invalid 8.3 filenames, but
22335 * there's not a lot of point in guessing what it might be.
22337 len = tflen;
22338 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
22339 return FAIL;
22342 /* Count the paths backward to find the beginning of the desired string. */
22343 for (p = tfname + len - 1; p >= tfname; --p)
22345 #ifdef FEAT_MBYTE
22346 if (has_mbyte)
22347 p -= mb_head_off(tfname, p);
22348 #endif
22349 if (vim_ispathsep(*p))
22351 if (sepcount == 0 || (hasTilde && sepcount == 1))
22352 break;
22353 else
22354 sepcount --;
22357 if (hasTilde)
22359 --p;
22360 if (p >= tfname)
22361 *p = '~';
22362 else
22363 return FAIL;
22365 else
22366 ++p;
22368 /* Copy in the string - p indexes into tfname - allocated at pbuf */
22369 vim_free(*bufp);
22370 *fnamelen = (int)STRLEN(p);
22371 *bufp = pbuf;
22372 *fnamep = p;
22374 return OK;
22376 #endif /* WIN3264 */
22379 * Adjust a filename, according to a string of modifiers.
22380 * *fnamep must be NUL terminated when called. When returning, the length is
22381 * determined by *fnamelen.
22382 * Returns VALID_ flags or -1 for failure.
22383 * When there is an error, *fnamep is set to NULL.
22386 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
22387 char_u *src; /* string with modifiers */
22388 int *usedlen; /* characters after src that are used */
22389 char_u **fnamep; /* file name so far */
22390 char_u **bufp; /* buffer for allocated file name or NULL */
22391 int *fnamelen; /* length of fnamep */
22393 int valid = 0;
22394 char_u *tail;
22395 char_u *s, *p, *pbuf;
22396 char_u dirname[MAXPATHL];
22397 int c;
22398 int has_fullname = 0;
22399 #ifdef WIN3264
22400 int has_shortname = 0;
22401 #endif
22403 repeat:
22404 /* ":p" - full path/file_name */
22405 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
22407 has_fullname = 1;
22409 valid |= VALID_PATH;
22410 *usedlen += 2;
22412 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
22413 if ((*fnamep)[0] == '~'
22414 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
22415 && ((*fnamep)[1] == '/'
22416 # ifdef BACKSLASH_IN_FILENAME
22417 || (*fnamep)[1] == '\\'
22418 # endif
22419 || (*fnamep)[1] == NUL)
22421 #endif
22424 *fnamep = expand_env_save(*fnamep);
22425 vim_free(*bufp); /* free any allocated file name */
22426 *bufp = *fnamep;
22427 if (*fnamep == NULL)
22428 return -1;
22431 /* When "/." or "/.." is used: force expansion to get rid of it. */
22432 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
22434 if (vim_ispathsep(*p)
22435 && p[1] == '.'
22436 && (p[2] == NUL
22437 || vim_ispathsep(p[2])
22438 || (p[2] == '.'
22439 && (p[3] == NUL || vim_ispathsep(p[3])))))
22440 break;
22443 /* FullName_save() is slow, don't use it when not needed. */
22444 if (*p != NUL || !vim_isAbsName(*fnamep))
22446 *fnamep = FullName_save(*fnamep, *p != NUL);
22447 vim_free(*bufp); /* free any allocated file name */
22448 *bufp = *fnamep;
22449 if (*fnamep == NULL)
22450 return -1;
22453 /* Append a path separator to a directory. */
22454 if (mch_isdir(*fnamep))
22456 /* Make room for one or two extra characters. */
22457 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
22458 vim_free(*bufp); /* free any allocated file name */
22459 *bufp = *fnamep;
22460 if (*fnamep == NULL)
22461 return -1;
22462 add_pathsep(*fnamep);
22466 /* ":." - path relative to the current directory */
22467 /* ":~" - path relative to the home directory */
22468 /* ":8" - shortname path - postponed till after */
22469 while (src[*usedlen] == ':'
22470 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
22472 *usedlen += 2;
22473 if (c == '8')
22475 #ifdef WIN3264
22476 has_shortname = 1; /* Postpone this. */
22477 #endif
22478 continue;
22480 pbuf = NULL;
22481 /* Need full path first (use expand_env() to remove a "~/") */
22482 if (!has_fullname)
22484 if (c == '.' && **fnamep == '~')
22485 p = pbuf = expand_env_save(*fnamep);
22486 else
22487 p = pbuf = FullName_save(*fnamep, FALSE);
22489 else
22490 p = *fnamep;
22492 has_fullname = 0;
22494 if (p != NULL)
22496 if (c == '.')
22498 mch_dirname(dirname, MAXPATHL);
22499 s = shorten_fname(p, dirname);
22500 if (s != NULL)
22502 *fnamep = s;
22503 if (pbuf != NULL)
22505 vim_free(*bufp); /* free any allocated file name */
22506 *bufp = pbuf;
22507 pbuf = NULL;
22511 else
22513 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
22514 /* Only replace it when it starts with '~' */
22515 if (*dirname == '~')
22517 s = vim_strsave(dirname);
22518 if (s != NULL)
22520 *fnamep = s;
22521 vim_free(*bufp);
22522 *bufp = s;
22526 vim_free(pbuf);
22530 tail = gettail(*fnamep);
22531 *fnamelen = (int)STRLEN(*fnamep);
22533 /* ":h" - head, remove "/file_name", can be repeated */
22534 /* Don't remove the first "/" or "c:\" */
22535 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
22537 valid |= VALID_HEAD;
22538 *usedlen += 2;
22539 s = get_past_head(*fnamep);
22540 while (tail > s && after_pathsep(s, tail))
22541 mb_ptr_back(*fnamep, tail);
22542 *fnamelen = (int)(tail - *fnamep);
22543 #ifdef VMS
22544 if (*fnamelen > 0)
22545 *fnamelen += 1; /* the path separator is part of the path */
22546 #endif
22547 if (*fnamelen == 0)
22549 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
22550 p = vim_strsave((char_u *)".");
22551 if (p == NULL)
22552 return -1;
22553 vim_free(*bufp);
22554 *bufp = *fnamep = tail = p;
22555 *fnamelen = 1;
22557 else
22559 while (tail > s && !after_pathsep(s, tail))
22560 mb_ptr_back(*fnamep, tail);
22564 /* ":8" - shortname */
22565 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
22567 *usedlen += 2;
22568 #ifdef WIN3264
22569 has_shortname = 1;
22570 #endif
22573 #ifdef WIN3264
22574 /* Check shortname after we have done 'heads' and before we do 'tails'
22576 if (has_shortname)
22578 pbuf = NULL;
22579 /* Copy the string if it is shortened by :h */
22580 if (*fnamelen < (int)STRLEN(*fnamep))
22582 p = vim_strnsave(*fnamep, *fnamelen);
22583 if (p == 0)
22584 return -1;
22585 vim_free(*bufp);
22586 *bufp = *fnamep = p;
22589 /* Split into two implementations - makes it easier. First is where
22590 * there isn't a full name already, second is where there is.
22592 if (!has_fullname && !vim_isAbsName(*fnamep))
22594 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
22595 return -1;
22597 else
22599 int l;
22601 /* Simple case, already have the full-name
22602 * Nearly always shorter, so try first time. */
22603 l = *fnamelen;
22604 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
22605 return -1;
22607 if (l == 0)
22609 /* Couldn't find the filename.. search the paths.
22611 l = *fnamelen;
22612 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
22613 return -1;
22615 *fnamelen = l;
22618 #endif /* WIN3264 */
22620 /* ":t" - tail, just the basename */
22621 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
22623 *usedlen += 2;
22624 *fnamelen -= (int)(tail - *fnamep);
22625 *fnamep = tail;
22628 /* ":e" - extension, can be repeated */
22629 /* ":r" - root, without extension, can be repeated */
22630 while (src[*usedlen] == ':'
22631 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
22633 /* find a '.' in the tail:
22634 * - for second :e: before the current fname
22635 * - otherwise: The last '.'
22637 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
22638 s = *fnamep - 2;
22639 else
22640 s = *fnamep + *fnamelen - 1;
22641 for ( ; s > tail; --s)
22642 if (s[0] == '.')
22643 break;
22644 if (src[*usedlen + 1] == 'e') /* :e */
22646 if (s > tail)
22648 *fnamelen += (int)(*fnamep - (s + 1));
22649 *fnamep = s + 1;
22650 #ifdef VMS
22651 /* cut version from the extension */
22652 s = *fnamep + *fnamelen - 1;
22653 for ( ; s > *fnamep; --s)
22654 if (s[0] == ';')
22655 break;
22656 if (s > *fnamep)
22657 *fnamelen = s - *fnamep;
22658 #endif
22660 else if (*fnamep <= tail)
22661 *fnamelen = 0;
22663 else /* :r */
22665 if (s > tail) /* remove one extension */
22666 *fnamelen = (int)(s - *fnamep);
22668 *usedlen += 2;
22671 /* ":s?pat?foo?" - substitute */
22672 /* ":gs?pat?foo?" - global substitute */
22673 if (src[*usedlen] == ':'
22674 && (src[*usedlen + 1] == 's'
22675 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
22677 char_u *str;
22678 char_u *pat;
22679 char_u *sub;
22680 int sep;
22681 char_u *flags;
22682 int didit = FALSE;
22684 flags = (char_u *)"";
22685 s = src + *usedlen + 2;
22686 if (src[*usedlen + 1] == 'g')
22688 flags = (char_u *)"g";
22689 ++s;
22692 sep = *s++;
22693 if (sep)
22695 /* find end of pattern */
22696 p = vim_strchr(s, sep);
22697 if (p != NULL)
22699 pat = vim_strnsave(s, (int)(p - s));
22700 if (pat != NULL)
22702 s = p + 1;
22703 /* find end of substitution */
22704 p = vim_strchr(s, sep);
22705 if (p != NULL)
22707 sub = vim_strnsave(s, (int)(p - s));
22708 str = vim_strnsave(*fnamep, *fnamelen);
22709 if (sub != NULL && str != NULL)
22711 *usedlen = (int)(p + 1 - src);
22712 s = do_string_sub(str, pat, sub, flags);
22713 if (s != NULL)
22715 *fnamep = s;
22716 *fnamelen = (int)STRLEN(s);
22717 vim_free(*bufp);
22718 *bufp = s;
22719 didit = TRUE;
22722 vim_free(sub);
22723 vim_free(str);
22725 vim_free(pat);
22728 /* after using ":s", repeat all the modifiers */
22729 if (didit)
22730 goto repeat;
22734 return valid;
22738 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
22739 * "flags" can be "g" to do a global substitute.
22740 * Returns an allocated string, NULL for error.
22742 char_u *
22743 do_string_sub(str, pat, sub, flags)
22744 char_u *str;
22745 char_u *pat;
22746 char_u *sub;
22747 char_u *flags;
22749 int sublen;
22750 regmatch_T regmatch;
22751 int i;
22752 int do_all;
22753 char_u *tail;
22754 garray_T ga;
22755 char_u *ret;
22756 char_u *save_cpo;
22758 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
22759 save_cpo = p_cpo;
22760 p_cpo = empty_option;
22762 ga_init2(&ga, 1, 200);
22764 do_all = (flags[0] == 'g');
22766 regmatch.rm_ic = p_ic;
22767 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
22768 if (regmatch.regprog != NULL)
22770 tail = str;
22771 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
22774 * Get some space for a temporary buffer to do the substitution
22775 * into. It will contain:
22776 * - The text up to where the match is.
22777 * - The substituted text.
22778 * - The text after the match.
22780 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
22781 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
22782 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
22784 ga_clear(&ga);
22785 break;
22788 /* copy the text up to where the match is */
22789 i = (int)(regmatch.startp[0] - tail);
22790 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
22791 /* add the substituted text */
22792 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
22793 + ga.ga_len + i, TRUE, TRUE, FALSE);
22794 ga.ga_len += i + sublen - 1;
22795 /* avoid getting stuck on a match with an empty string */
22796 if (tail == regmatch.endp[0])
22798 if (*tail == NUL)
22799 break;
22800 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
22801 ++ga.ga_len;
22803 else
22805 tail = regmatch.endp[0];
22806 if (*tail == NUL)
22807 break;
22809 if (!do_all)
22810 break;
22813 if (ga.ga_data != NULL)
22814 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
22816 vim_free(regmatch.regprog);
22819 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
22820 ga_clear(&ga);
22821 if (p_cpo == empty_option)
22822 p_cpo = save_cpo;
22823 else
22824 /* Darn, evaluating {sub} expression changed the value. */
22825 free_string_option(save_cpo);
22827 return ret;
22830 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */