Merge branch 'vim-with-runtime' into feat/tagfunc
[vim_extended.git] / src / eval.c
blob9b748317ff2d8a7fd5bac75d873ed1f5f4c7b687
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;
6997 /* Initializes a data structure used for iterating over dictionary items in
6998 * dict_iterate_next().
7000 void
7001 dict_iterate_start(argvars, iter)
7002 typval_T *argvars;
7003 struct dict_iterator_S *iter;
7005 dict_T *d;
7007 if (argvars[0].v_type != VAR_DICT)
7009 iter->items = 0;
7010 return;
7013 if ((d = argvars[0].vval.v_dict) == NULL)
7015 iter->items = 0;
7016 return;
7019 iter->items = (int)d->dv_hashtab.ht_used;
7020 iter->hi = d->dv_hashtab.ht_array;
7023 /* Allows iterating over the items stored in a dictionary.
7024 * Returns the pointer to the key, *tv_result is set to point to the value
7025 * for that key.
7026 * If there are no more items, NULL is returned.
7027 * iter should be initialized with dict_iterate_start() before calling this
7028 * function for the first time.
7030 char_u*
7031 dict_iterate_next(iter, tv_result)
7032 struct dict_iterator_S *iter;
7033 typval_T **tv_result;
7035 dictitem_T *di;
7036 char_u *result;
7038 if (iter->items <= 0)
7039 return NULL;
7041 while (HASHITEM_EMPTY(iter->hi))
7042 ++iter->hi;
7044 di = HI2DI(iter->hi);
7045 result = di->di_key;
7046 *tv_result = &di->di_tv;
7048 --iter->items;
7049 ++iter->hi;
7050 return result;
7054 * Get the number of items in a Dictionary.
7056 static long
7057 dict_len(d)
7058 dict_T *d;
7060 if (d == NULL)
7061 return 0L;
7062 return (long)d->dv_hashtab.ht_used;
7066 * Find item "key[len]" in Dictionary "d".
7067 * If "len" is negative use strlen(key).
7068 * Returns NULL when not found.
7070 dictitem_T *
7071 dict_find(d, key, len)
7072 dict_T *d;
7073 char_u *key;
7074 int len;
7076 #define AKEYLEN 200
7077 char_u buf[AKEYLEN];
7078 char_u *akey;
7079 char_u *tofree = NULL;
7080 hashitem_T *hi;
7082 if (len < 0)
7083 akey = key;
7084 else if (len >= AKEYLEN)
7086 tofree = akey = vim_strnsave(key, len);
7087 if (akey == NULL)
7088 return NULL;
7090 else
7092 /* Avoid a malloc/free by using buf[]. */
7093 vim_strncpy(buf, key, len);
7094 akey = buf;
7097 hi = hash_find(&d->dv_hashtab, akey);
7098 vim_free(tofree);
7099 if (HASHITEM_EMPTY(hi))
7100 return NULL;
7101 return HI2DI(hi);
7105 * Get a string item from a dictionary.
7106 * When "save" is TRUE allocate memory for it.
7107 * Returns NULL if the entry doesn't exist or out of memory.
7109 char_u *
7110 get_dict_string(d, key, save)
7111 dict_T *d;
7112 char_u *key;
7113 int save;
7115 dictitem_T *di;
7116 char_u *s;
7118 di = dict_find(d, key, -1);
7119 if (di == NULL)
7120 return NULL;
7121 s = get_tv_string(&di->di_tv);
7122 if (save && s != NULL)
7123 s = vim_strsave(s);
7124 return s;
7128 * Get a number item from a dictionary.
7129 * Returns 0 if the entry doesn't exist or out of memory.
7131 long
7132 get_dict_number(d, key)
7133 dict_T *d;
7134 char_u *key;
7136 dictitem_T *di;
7138 di = dict_find(d, key, -1);
7139 if (di == NULL)
7140 return 0;
7141 return get_tv_number(&di->di_tv);
7145 * Return an allocated string with the string representation of a Dictionary.
7146 * May return NULL.
7148 static char_u *
7149 dict2string(tv, copyID)
7150 typval_T *tv;
7151 int copyID;
7153 garray_T ga;
7154 int first = TRUE;
7155 char_u *tofree;
7156 char_u numbuf[NUMBUFLEN];
7157 hashitem_T *hi;
7158 char_u *s;
7159 dict_T *d;
7160 int todo;
7162 if ((d = tv->vval.v_dict) == NULL)
7163 return NULL;
7164 ga_init2(&ga, (int)sizeof(char), 80);
7165 ga_append(&ga, '{');
7167 todo = (int)d->dv_hashtab.ht_used;
7168 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
7170 if (!HASHITEM_EMPTY(hi))
7172 --todo;
7174 if (first)
7175 first = FALSE;
7176 else
7177 ga_concat(&ga, (char_u *)", ");
7179 tofree = string_quote(hi->hi_key, FALSE);
7180 if (tofree != NULL)
7182 ga_concat(&ga, tofree);
7183 vim_free(tofree);
7185 ga_concat(&ga, (char_u *)": ");
7186 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
7187 if (s != NULL)
7188 ga_concat(&ga, s);
7189 vim_free(tofree);
7190 if (s == NULL)
7191 break;
7194 if (todo > 0)
7196 vim_free(ga.ga_data);
7197 return NULL;
7200 ga_append(&ga, '}');
7201 ga_append(&ga, NUL);
7202 return (char_u *)ga.ga_data;
7206 * Allocate a variable for a Dictionary and fill it from "*arg".
7207 * Return OK or FAIL. Returns NOTDONE for {expr}.
7209 static int
7210 get_dict_tv(arg, rettv, evaluate)
7211 char_u **arg;
7212 typval_T *rettv;
7213 int evaluate;
7215 dict_T *d = NULL;
7216 typval_T tvkey;
7217 typval_T tv;
7218 char_u *key = NULL;
7219 dictitem_T *item;
7220 char_u *start = skipwhite(*arg + 1);
7221 char_u buf[NUMBUFLEN];
7224 * First check if it's not a curly-braces thing: {expr}.
7225 * Must do this without evaluating, otherwise a function may be called
7226 * twice. Unfortunately this means we need to call eval1() twice for the
7227 * first item.
7228 * But {} is an empty Dictionary.
7230 if (*start != '}')
7232 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
7233 return FAIL;
7234 if (*start == '}')
7235 return NOTDONE;
7238 if (evaluate)
7240 d = dict_alloc();
7241 if (d == NULL)
7242 return FAIL;
7244 tvkey.v_type = VAR_UNKNOWN;
7245 tv.v_type = VAR_UNKNOWN;
7247 *arg = skipwhite(*arg + 1);
7248 while (**arg != '}' && **arg != NUL)
7250 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
7251 goto failret;
7252 if (**arg != ':')
7254 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
7255 clear_tv(&tvkey);
7256 goto failret;
7258 if (evaluate)
7260 key = get_tv_string_buf_chk(&tvkey, buf);
7261 if (key == NULL || *key == NUL)
7263 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
7264 if (key != NULL)
7265 EMSG(_(e_emptykey));
7266 clear_tv(&tvkey);
7267 goto failret;
7271 *arg = skipwhite(*arg + 1);
7272 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
7274 if (evaluate)
7275 clear_tv(&tvkey);
7276 goto failret;
7278 if (evaluate)
7280 item = dict_find(d, key, -1);
7281 if (item != NULL)
7283 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
7284 clear_tv(&tvkey);
7285 clear_tv(&tv);
7286 goto failret;
7288 item = dictitem_alloc(key);
7289 clear_tv(&tvkey);
7290 if (item != NULL)
7292 item->di_tv = tv;
7293 item->di_tv.v_lock = 0;
7294 if (dict_add(d, item) == FAIL)
7295 dictitem_free(item);
7299 if (**arg == '}')
7300 break;
7301 if (**arg != ',')
7303 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
7304 goto failret;
7306 *arg = skipwhite(*arg + 1);
7309 if (**arg != '}')
7311 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
7312 failret:
7313 if (evaluate)
7314 dict_free(d, TRUE);
7315 return FAIL;
7318 *arg = skipwhite(*arg + 1);
7319 if (evaluate)
7321 rettv->v_type = VAR_DICT;
7322 rettv->vval.v_dict = d;
7323 ++d->dv_refcount;
7326 return OK;
7330 * Return a string with the string representation of a variable.
7331 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7332 * "numbuf" is used for a number.
7333 * Does not put quotes around strings, as ":echo" displays values.
7334 * When "copyID" is not NULL replace recursive lists and dicts with "...".
7335 * May return NULL.
7337 static char_u *
7338 echo_string(tv, tofree, numbuf, copyID)
7339 typval_T *tv;
7340 char_u **tofree;
7341 char_u *numbuf;
7342 int copyID;
7344 static int recurse = 0;
7345 char_u *r = NULL;
7347 if (recurse >= DICT_MAXNEST)
7349 EMSG(_("E724: variable nested too deep for displaying"));
7350 *tofree = NULL;
7351 return NULL;
7353 ++recurse;
7355 switch (tv->v_type)
7357 case VAR_FUNC:
7358 *tofree = NULL;
7359 r = tv->vval.v_string;
7360 break;
7362 case VAR_LIST:
7363 if (tv->vval.v_list == NULL)
7365 *tofree = NULL;
7366 r = NULL;
7368 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
7370 *tofree = NULL;
7371 r = (char_u *)"[...]";
7373 else
7375 tv->vval.v_list->lv_copyID = copyID;
7376 *tofree = list2string(tv, copyID);
7377 r = *tofree;
7379 break;
7381 case VAR_DICT:
7382 if (tv->vval.v_dict == NULL)
7384 *tofree = NULL;
7385 r = NULL;
7387 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
7389 *tofree = NULL;
7390 r = (char_u *)"{...}";
7392 else
7394 tv->vval.v_dict->dv_copyID = copyID;
7395 *tofree = dict2string(tv, copyID);
7396 r = *tofree;
7398 break;
7400 case VAR_STRING:
7401 case VAR_NUMBER:
7402 *tofree = NULL;
7403 r = get_tv_string_buf(tv, numbuf);
7404 break;
7406 #ifdef FEAT_FLOAT
7407 case VAR_FLOAT:
7408 *tofree = NULL;
7409 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
7410 r = numbuf;
7411 break;
7412 #endif
7414 default:
7415 EMSG2(_(e_intern2), "echo_string()");
7416 *tofree = NULL;
7419 --recurse;
7420 return r;
7424 * Return a string with the string representation of a variable.
7425 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7426 * "numbuf" is used for a number.
7427 * Puts quotes around strings, so that they can be parsed back by eval().
7428 * May return NULL.
7430 static char_u *
7431 tv2string(tv, tofree, numbuf, copyID)
7432 typval_T *tv;
7433 char_u **tofree;
7434 char_u *numbuf;
7435 int copyID;
7437 switch (tv->v_type)
7439 case VAR_FUNC:
7440 *tofree = string_quote(tv->vval.v_string, TRUE);
7441 return *tofree;
7442 case VAR_STRING:
7443 *tofree = string_quote(tv->vval.v_string, FALSE);
7444 return *tofree;
7445 #ifdef FEAT_FLOAT
7446 case VAR_FLOAT:
7447 *tofree = NULL;
7448 vim_snprintf((char *)numbuf, NUMBUFLEN - 1, "%g", tv->vval.v_float);
7449 return numbuf;
7450 #endif
7451 case VAR_NUMBER:
7452 case VAR_LIST:
7453 case VAR_DICT:
7454 break;
7455 default:
7456 EMSG2(_(e_intern2), "tv2string()");
7458 return echo_string(tv, tofree, numbuf, copyID);
7462 * Return string "str" in ' quotes, doubling ' characters.
7463 * If "str" is NULL an empty string is assumed.
7464 * If "function" is TRUE make it function('string').
7466 static char_u *
7467 string_quote(str, function)
7468 char_u *str;
7469 int function;
7471 unsigned len;
7472 char_u *p, *r, *s;
7474 len = (function ? 13 : 3);
7475 if (str != NULL)
7477 len += (unsigned)STRLEN(str);
7478 for (p = str; *p != NUL; mb_ptr_adv(p))
7479 if (*p == '\'')
7480 ++len;
7482 s = r = alloc(len);
7483 if (r != NULL)
7485 if (function)
7487 STRCPY(r, "function('");
7488 r += 10;
7490 else
7491 *r++ = '\'';
7492 if (str != NULL)
7493 for (p = str; *p != NUL; )
7495 if (*p == '\'')
7496 *r++ = '\'';
7497 MB_COPY_CHAR(p, r);
7499 *r++ = '\'';
7500 if (function)
7501 *r++ = ')';
7502 *r++ = NUL;
7504 return s;
7507 #ifdef FEAT_FLOAT
7509 * Convert the string "text" to a floating point number.
7510 * This uses strtod(). setlocale(LC_NUMERIC, "C") has been used to make sure
7511 * this always uses a decimal point.
7512 * Returns the length of the text that was consumed.
7514 static int
7515 string2float(text, value)
7516 char_u *text;
7517 float_T *value; /* result stored here */
7519 char *s = (char *)text;
7520 float_T f;
7522 f = strtod(s, &s);
7523 *value = f;
7524 return (int)((char_u *)s - text);
7526 #endif
7529 * Get the value of an environment variable.
7530 * "arg" is pointing to the '$'. It is advanced to after the name.
7531 * If the environment variable was not set, silently assume it is empty.
7532 * Always return OK.
7534 static int
7535 get_env_tv(arg, rettv, evaluate)
7536 char_u **arg;
7537 typval_T *rettv;
7538 int evaluate;
7540 char_u *string = NULL;
7541 int len;
7542 int cc;
7543 char_u *name;
7544 int mustfree = FALSE;
7546 ++*arg;
7547 name = *arg;
7548 len = get_env_len(arg);
7549 if (evaluate)
7551 if (len != 0)
7553 cc = name[len];
7554 name[len] = NUL;
7555 /* first try vim_getenv(), fast for normal environment vars */
7556 string = vim_getenv(name, &mustfree);
7557 if (string != NULL && *string != NUL)
7559 if (!mustfree)
7560 string = vim_strsave(string);
7562 else
7564 if (mustfree)
7565 vim_free(string);
7567 /* next try expanding things like $VIM and ${HOME} */
7568 string = expand_env_save(name - 1);
7569 if (string != NULL && *string == '$')
7571 vim_free(string);
7572 string = NULL;
7575 name[len] = cc;
7577 rettv->v_type = VAR_STRING;
7578 rettv->vval.v_string = string;
7581 return OK;
7585 * Array with names and number of arguments of all internal functions
7586 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7588 static struct fst
7590 char *f_name; /* function name */
7591 char f_min_argc; /* minimal number of arguments */
7592 char f_max_argc; /* maximal number of arguments */
7593 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7594 /* implementation of function */
7595 } functions[] =
7597 #ifdef FEAT_FLOAT
7598 {"abs", 1, 1, f_abs},
7599 #endif
7600 {"add", 2, 2, f_add},
7601 {"append", 2, 2, f_append},
7602 {"argc", 0, 0, f_argc},
7603 {"argidx", 0, 0, f_argidx},
7604 {"argv", 0, 1, f_argv},
7605 #ifdef FEAT_FLOAT
7606 {"atan", 1, 1, f_atan},
7607 #endif
7608 {"browse", 4, 4, f_browse},
7609 {"browsedir", 2, 2, f_browsedir},
7610 {"bufexists", 1, 1, f_bufexists},
7611 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7612 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7613 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7614 {"buflisted", 1, 1, f_buflisted},
7615 {"bufloaded", 1, 1, f_bufloaded},
7616 {"bufname", 1, 1, f_bufname},
7617 {"bufnr", 1, 2, f_bufnr},
7618 {"bufwinnr", 1, 1, f_bufwinnr},
7619 {"byte2line", 1, 1, f_byte2line},
7620 {"byteidx", 2, 2, f_byteidx},
7621 {"call", 2, 3, f_call},
7622 #ifdef FEAT_FLOAT
7623 {"ceil", 1, 1, f_ceil},
7624 #endif
7625 {"changenr", 0, 0, f_changenr},
7626 {"char2nr", 1, 1, f_char2nr},
7627 {"cindent", 1, 1, f_cindent},
7628 {"clearmatches", 0, 0, f_clearmatches},
7629 {"col", 1, 1, f_col},
7630 #if defined(FEAT_INS_EXPAND)
7631 {"complete", 2, 2, f_complete},
7632 {"complete_add", 1, 1, f_complete_add},
7633 {"complete_check", 0, 0, f_complete_check},
7634 #endif
7635 {"confirm", 1, 4, f_confirm},
7636 {"copy", 1, 1, f_copy},
7637 #ifdef FEAT_FLOAT
7638 {"cos", 1, 1, f_cos},
7639 #endif
7640 {"count", 2, 4, f_count},
7641 {"cscope_connection",0,3, f_cscope_connection},
7642 {"cursor", 1, 3, f_cursor},
7643 {"deepcopy", 1, 2, f_deepcopy},
7644 {"delete", 1, 1, f_delete},
7645 {"did_filetype", 0, 0, f_did_filetype},
7646 {"diff_filler", 1, 1, f_diff_filler},
7647 {"diff_hlID", 2, 2, f_diff_hlID},
7648 {"empty", 1, 1, f_empty},
7649 {"escape", 2, 2, f_escape},
7650 {"eval", 1, 1, f_eval},
7651 {"eventhandler", 0, 0, f_eventhandler},
7652 {"executable", 1, 1, f_executable},
7653 {"exists", 1, 1, f_exists},
7654 {"expand", 1, 2, f_expand},
7655 {"extend", 2, 3, f_extend},
7656 {"feedkeys", 1, 2, f_feedkeys},
7657 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7658 {"filereadable", 1, 1, f_filereadable},
7659 {"filewritable", 1, 1, f_filewritable},
7660 {"filter", 2, 2, f_filter},
7661 {"finddir", 1, 3, f_finddir},
7662 {"findfile", 1, 3, f_findfile},
7663 #ifdef FEAT_FLOAT
7664 {"float2nr", 1, 1, f_float2nr},
7665 {"floor", 1, 1, f_floor},
7666 #endif
7667 {"fnameescape", 1, 1, f_fnameescape},
7668 {"fnamemodify", 2, 2, f_fnamemodify},
7669 {"foldclosed", 1, 1, f_foldclosed},
7670 {"foldclosedend", 1, 1, f_foldclosedend},
7671 {"foldlevel", 1, 1, f_foldlevel},
7672 {"foldtext", 0, 0, f_foldtext},
7673 {"foldtextresult", 1, 1, f_foldtextresult},
7674 {"foreground", 0, 0, f_foreground},
7675 {"function", 1, 1, f_function},
7676 {"garbagecollect", 0, 1, f_garbagecollect},
7677 {"get", 2, 3, f_get},
7678 {"getbufline", 2, 3, f_getbufline},
7679 {"getbufvar", 2, 2, f_getbufvar},
7680 {"getchar", 0, 1, f_getchar},
7681 {"getcharmod", 0, 0, f_getcharmod},
7682 {"getcmdline", 0, 0, f_getcmdline},
7683 {"getcmdpos", 0, 0, f_getcmdpos},
7684 {"getcmdtype", 0, 0, f_getcmdtype},
7685 {"getcwd", 0, 0, f_getcwd},
7686 {"getfontname", 0, 1, f_getfontname},
7687 {"getfperm", 1, 1, f_getfperm},
7688 {"getfsize", 1, 1, f_getfsize},
7689 {"getftime", 1, 1, f_getftime},
7690 {"getftype", 1, 1, f_getftype},
7691 {"getline", 1, 2, f_getline},
7692 {"getloclist", 1, 1, f_getqflist},
7693 {"getmatches", 0, 0, f_getmatches},
7694 {"getpid", 0, 0, f_getpid},
7695 {"getpos", 1, 1, f_getpos},
7696 {"getqflist", 0, 0, f_getqflist},
7697 {"getreg", 0, 2, f_getreg},
7698 {"getregtype", 0, 1, f_getregtype},
7699 {"gettabwinvar", 3, 3, f_gettabwinvar},
7700 {"getwinposx", 0, 0, f_getwinposx},
7701 {"getwinposy", 0, 0, f_getwinposy},
7702 {"getwinvar", 2, 2, f_getwinvar},
7703 {"glob", 1, 2, f_glob},
7704 {"globpath", 2, 3, f_globpath},
7705 {"has", 1, 1, f_has},
7706 {"has_key", 2, 2, f_has_key},
7707 {"haslocaldir", 0, 0, f_haslocaldir},
7708 {"hasmapto", 1, 3, f_hasmapto},
7709 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7710 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7711 {"histadd", 2, 2, f_histadd},
7712 {"histdel", 1, 2, f_histdel},
7713 {"histget", 1, 2, f_histget},
7714 {"histnr", 1, 1, f_histnr},
7715 {"hlID", 1, 1, f_hlID},
7716 {"hlexists", 1, 1, f_hlexists},
7717 {"hostname", 0, 0, f_hostname},
7718 {"iconv", 3, 3, f_iconv},
7719 {"indent", 1, 1, f_indent},
7720 {"index", 2, 4, f_index},
7721 {"input", 1, 3, f_input},
7722 {"inputdialog", 1, 3, f_inputdialog},
7723 {"inputlist", 1, 1, f_inputlist},
7724 {"inputrestore", 0, 0, f_inputrestore},
7725 {"inputsave", 0, 0, f_inputsave},
7726 {"inputsecret", 1, 2, f_inputsecret},
7727 {"insert", 2, 3, f_insert},
7728 {"isdirectory", 1, 1, f_isdirectory},
7729 {"islocked", 1, 1, f_islocked},
7730 {"items", 1, 1, f_items},
7731 {"join", 1, 2, f_join},
7732 {"keys", 1, 1, f_keys},
7733 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7734 {"len", 1, 1, f_len},
7735 {"libcall", 3, 3, f_libcall},
7736 {"libcallnr", 3, 3, f_libcallnr},
7737 {"line", 1, 1, f_line},
7738 {"line2byte", 1, 1, f_line2byte},
7739 {"lispindent", 1, 1, f_lispindent},
7740 {"localtime", 0, 0, f_localtime},
7741 #ifdef FEAT_FLOAT
7742 {"log10", 1, 1, f_log10},
7743 #endif
7744 {"map", 2, 2, f_map},
7745 {"maparg", 1, 3, f_maparg},
7746 {"mapcheck", 1, 3, f_mapcheck},
7747 {"match", 2, 4, f_match},
7748 {"matchadd", 2, 4, f_matchadd},
7749 {"matcharg", 1, 1, f_matcharg},
7750 {"matchdelete", 1, 1, f_matchdelete},
7751 {"matchend", 2, 4, f_matchend},
7752 {"matchlist", 2, 4, f_matchlist},
7753 {"matchstr", 2, 4, f_matchstr},
7754 {"max", 1, 1, f_max},
7755 {"min", 1, 1, f_min},
7756 #ifdef vim_mkdir
7757 {"mkdir", 1, 3, f_mkdir},
7758 #endif
7759 {"mode", 0, 1, f_mode},
7760 #ifdef FEAT_MZSCHEME
7761 {"mzeval", 1, 1, f_mzeval},
7762 #endif
7763 {"nextnonblank", 1, 1, f_nextnonblank},
7764 {"nr2char", 1, 1, f_nr2char},
7765 {"pathshorten", 1, 1, f_pathshorten},
7766 #ifdef FEAT_FLOAT
7767 {"pow", 2, 2, f_pow},
7768 #endif
7769 {"prevnonblank", 1, 1, f_prevnonblank},
7770 {"printf", 2, 19, f_printf},
7771 {"pumvisible", 0, 0, f_pumvisible},
7772 {"range", 1, 3, f_range},
7773 {"readfile", 1, 3, f_readfile},
7774 {"reltime", 0, 2, f_reltime},
7775 {"reltimestr", 1, 1, f_reltimestr},
7776 {"remote_expr", 2, 3, f_remote_expr},
7777 {"remote_foreground", 1, 1, f_remote_foreground},
7778 {"remote_peek", 1, 2, f_remote_peek},
7779 {"remote_read", 1, 1, f_remote_read},
7780 {"remote_send", 2, 3, f_remote_send},
7781 {"remove", 2, 3, f_remove},
7782 {"rename", 2, 2, f_rename},
7783 {"repeat", 2, 2, f_repeat},
7784 {"resolve", 1, 1, f_resolve},
7785 {"reverse", 1, 1, f_reverse},
7786 #ifdef FEAT_FLOAT
7787 {"round", 1, 1, f_round},
7788 #endif
7789 {"search", 1, 4, f_search},
7790 {"searchdecl", 1, 3, f_searchdecl},
7791 {"searchpair", 3, 7, f_searchpair},
7792 {"searchpairpos", 3, 7, f_searchpairpos},
7793 {"searchpos", 1, 4, f_searchpos},
7794 {"server2client", 2, 2, f_server2client},
7795 {"serverlist", 0, 0, f_serverlist},
7796 {"setbufvar", 3, 3, f_setbufvar},
7797 {"setcmdpos", 1, 1, f_setcmdpos},
7798 {"setline", 2, 2, f_setline},
7799 {"setloclist", 2, 3, f_setloclist},
7800 {"setmatches", 1, 1, f_setmatches},
7801 {"setpos", 2, 2, f_setpos},
7802 {"setqflist", 1, 2, f_setqflist},
7803 {"setreg", 2, 3, f_setreg},
7804 {"settabwinvar", 4, 4, f_settabwinvar},
7805 {"setwinvar", 3, 3, f_setwinvar},
7806 {"shellescape", 1, 2, f_shellescape},
7807 {"simplify", 1, 1, f_simplify},
7808 #ifdef FEAT_FLOAT
7809 {"sin", 1, 1, f_sin},
7810 #endif
7811 {"sort", 1, 2, f_sort},
7812 {"soundfold", 1, 1, f_soundfold},
7813 {"spellbadword", 0, 1, f_spellbadword},
7814 {"spellsuggest", 1, 3, f_spellsuggest},
7815 {"split", 1, 3, f_split},
7816 #ifdef FEAT_FLOAT
7817 {"sqrt", 1, 1, f_sqrt},
7818 {"str2float", 1, 1, f_str2float},
7819 #endif
7820 {"str2nr", 1, 2, f_str2nr},
7821 #ifdef HAVE_STRFTIME
7822 {"strftime", 1, 2, f_strftime},
7823 #endif
7824 {"stridx", 2, 3, f_stridx},
7825 {"string", 1, 1, f_string},
7826 {"strlen", 1, 1, f_strlen},
7827 {"strpart", 2, 3, f_strpart},
7828 {"strridx", 2, 3, f_strridx},
7829 {"strtrans", 1, 1, f_strtrans},
7830 {"submatch", 1, 1, f_submatch},
7831 {"substitute", 4, 4, f_substitute},
7832 {"synID", 3, 3, f_synID},
7833 {"synIDattr", 2, 3, f_synIDattr},
7834 {"synIDtrans", 1, 1, f_synIDtrans},
7835 {"synstack", 2, 2, f_synstack},
7836 {"system", 1, 2, f_system},
7837 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7838 {"tabpagenr", 0, 1, f_tabpagenr},
7839 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7840 {"tagfiles", 0, 0, f_tagfiles},
7841 {"taglist", 1, 1, f_taglist},
7842 {"tempname", 0, 0, f_tempname},
7843 {"test", 1, 1, f_test},
7844 {"tolower", 1, 1, f_tolower},
7845 {"toupper", 1, 1, f_toupper},
7846 {"tr", 3, 3, f_tr},
7847 #ifdef FEAT_FLOAT
7848 {"trunc", 1, 1, f_trunc},
7849 #endif
7850 {"type", 1, 1, f_type},
7851 {"values", 1, 1, f_values},
7852 {"virtcol", 1, 1, f_virtcol},
7853 {"visualmode", 0, 1, f_visualmode},
7854 {"winbufnr", 1, 1, f_winbufnr},
7855 {"wincol", 0, 0, f_wincol},
7856 {"winheight", 1, 1, f_winheight},
7857 {"winline", 0, 0, f_winline},
7858 {"winnr", 0, 1, f_winnr},
7859 {"winrestcmd", 0, 0, f_winrestcmd},
7860 {"winrestview", 1, 1, f_winrestview},
7861 {"winsaveview", 0, 0, f_winsaveview},
7862 {"winwidth", 1, 1, f_winwidth},
7863 {"writefile", 2, 3, f_writefile},
7866 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7869 * Function given to ExpandGeneric() to obtain the list of internal
7870 * or user defined function names.
7872 char_u *
7873 get_function_name(xp, idx)
7874 expand_T *xp;
7875 int idx;
7877 static int intidx = -1;
7878 char_u *name;
7880 if (idx == 0)
7881 intidx = -1;
7882 if (intidx < 0)
7884 name = get_user_func_name(xp, idx);
7885 if (name != NULL)
7886 return name;
7888 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7890 STRCPY(IObuff, functions[intidx].f_name);
7891 STRCAT(IObuff, "(");
7892 if (functions[intidx].f_max_argc == 0)
7893 STRCAT(IObuff, ")");
7894 return IObuff;
7897 return NULL;
7901 * Function given to ExpandGeneric() to obtain the list of internal or
7902 * user defined variable or function names.
7904 char_u *
7905 get_expr_name(xp, idx)
7906 expand_T *xp;
7907 int idx;
7909 static int intidx = -1;
7910 char_u *name;
7912 if (idx == 0)
7913 intidx = -1;
7914 if (intidx < 0)
7916 name = get_function_name(xp, idx);
7917 if (name != NULL)
7918 return name;
7920 return get_user_var_name(xp, ++intidx);
7923 #endif /* FEAT_CMDL_COMPL */
7926 * Find internal function in table above.
7927 * Return index, or -1 if not found
7929 static int
7930 find_internal_func(name)
7931 char_u *name; /* name of the function */
7933 int first = 0;
7934 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7935 int cmp;
7936 int x;
7939 * Find the function name in the table. Binary search.
7941 while (first <= last)
7943 x = first + ((unsigned)(last - first) >> 1);
7944 cmp = STRCMP(name, functions[x].f_name);
7945 if (cmp < 0)
7946 last = x - 1;
7947 else if (cmp > 0)
7948 first = x + 1;
7949 else
7950 return x;
7952 return -1;
7956 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7957 * name it contains, otherwise return "name".
7959 static char_u *
7960 deref_func_name(name, lenp)
7961 char_u *name;
7962 int *lenp;
7964 dictitem_T *v;
7965 int cc;
7967 cc = name[*lenp];
7968 name[*lenp] = NUL;
7969 v = find_var(name, NULL);
7970 name[*lenp] = cc;
7971 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7973 if (v->di_tv.vval.v_string == NULL)
7975 *lenp = 0;
7976 return (char_u *)""; /* just in case */
7978 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7979 return v->di_tv.vval.v_string;
7982 return name;
7986 * Allocate a variable for the result of a function.
7987 * Return OK or FAIL.
7989 static int
7990 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7991 evaluate, selfdict)
7992 char_u *name; /* name of the function */
7993 int len; /* length of "name" */
7994 typval_T *rettv;
7995 char_u **arg; /* argument, pointing to the '(' */
7996 linenr_T firstline; /* first line of range */
7997 linenr_T lastline; /* last line of range */
7998 int *doesrange; /* return: function handled range */
7999 int evaluate;
8000 dict_T *selfdict; /* Dictionary for "self" */
8002 char_u *argp;
8003 int ret = OK;
8004 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
8005 int argcount = 0; /* number of arguments found */
8008 * Get the arguments.
8010 argp = *arg;
8011 while (argcount < MAX_FUNC_ARGS)
8013 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
8014 if (*argp == ')' || *argp == ',' || *argp == NUL)
8015 break;
8016 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
8018 ret = FAIL;
8019 break;
8021 ++argcount;
8022 if (*argp != ',')
8023 break;
8025 if (*argp == ')')
8026 ++argp;
8027 else
8028 ret = FAIL;
8030 if (ret == OK)
8031 ret = call_func(name, len, rettv, argcount, argvars,
8032 firstline, lastline, doesrange, evaluate, selfdict);
8033 else if (!aborting())
8035 if (argcount == MAX_FUNC_ARGS)
8036 emsg_funcname(N_("E740: Too many arguments for function %s"), name);
8037 else
8038 emsg_funcname(N_("E116: Invalid arguments for function %s"), name);
8041 while (--argcount >= 0)
8042 clear_tv(&argvars[argcount]);
8044 *arg = skipwhite(argp);
8045 return ret;
8050 * Call a function with its resolved parameters
8051 * Return OK when the function can't be called, FAIL otherwise.
8052 * Also returns OK when an error was encountered while executing the function.
8054 static int
8055 call_func(func_name, len, rettv, argcount, argvars, firstline, lastline,
8056 doesrange, evaluate, selfdict)
8057 char_u *func_name; /* name of the function */
8058 int len; /* length of "name" */
8059 typval_T *rettv; /* return value goes here */
8060 int argcount; /* number of "argvars" */
8061 typval_T *argvars; /* vars for arguments, must have "argcount"
8062 PLUS ONE elements! */
8063 linenr_T firstline; /* first line of range */
8064 linenr_T lastline; /* last line of range */
8065 int *doesrange; /* return: function handled range */
8066 int evaluate;
8067 dict_T *selfdict; /* Dictionary for "self" */
8069 int ret = FAIL;
8070 #define ERROR_UNKNOWN 0
8071 #define ERROR_TOOMANY 1
8072 #define ERROR_TOOFEW 2
8073 #define ERROR_SCRIPT 3
8074 #define ERROR_DICT 4
8075 #define ERROR_NONE 5
8076 #define ERROR_OTHER 6
8077 int error = ERROR_NONE;
8078 int i;
8079 int llen;
8080 ufunc_T *fp;
8081 #define FLEN_FIXED 40
8082 char_u fname_buf[FLEN_FIXED + 1];
8083 char_u *fname;
8084 char_u *name;
8086 /* Make a copy of the name, if it comes from a funcref variable it could
8087 * be changed or deleted in the called function. */
8088 name = vim_strnsave(func_name, len);
8089 if (name == NULL)
8090 return ret;
8093 * In a script change <SID>name() and s:name() to K_SNR 123_name().
8094 * Change <SNR>123_name() to K_SNR 123_name().
8095 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
8097 llen = eval_fname_script(name);
8098 if (llen > 0)
8100 fname_buf[0] = K_SPECIAL;
8101 fname_buf[1] = KS_EXTRA;
8102 fname_buf[2] = (int)KE_SNR;
8103 i = 3;
8104 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
8106 if (current_SID <= 0)
8107 error = ERROR_SCRIPT;
8108 else
8110 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
8111 i = (int)STRLEN(fname_buf);
8114 if (i + STRLEN(name + llen) < FLEN_FIXED)
8116 STRCPY(fname_buf + i, name + llen);
8117 fname = fname_buf;
8119 else
8121 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
8122 if (fname == NULL)
8123 error = ERROR_OTHER;
8124 else
8126 mch_memmove(fname, fname_buf, (size_t)i);
8127 STRCPY(fname + i, name + llen);
8131 else
8132 fname = name;
8134 *doesrange = FALSE;
8137 /* execute the function if no errors detected and executing */
8138 if (evaluate && error == ERROR_NONE)
8140 rettv->v_type = VAR_NUMBER; /* default rettv is number zero */
8141 rettv->vval.v_number = 0;
8142 error = ERROR_UNKNOWN;
8144 if (!builtin_function(fname))
8147 * User defined function.
8149 fp = find_func(fname);
8151 #ifdef FEAT_AUTOCMD
8152 /* Trigger FuncUndefined event, may load the function. */
8153 if (fp == NULL
8154 && apply_autocmds(EVENT_FUNCUNDEFINED,
8155 fname, fname, TRUE, NULL)
8156 && !aborting())
8158 /* executed an autocommand, search for the function again */
8159 fp = find_func(fname);
8161 #endif
8162 /* Try loading a package. */
8163 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
8165 /* loaded a package, search for the function again */
8166 fp = find_func(fname);
8169 if (fp != NULL)
8171 if (fp->uf_flags & FC_RANGE)
8172 *doesrange = TRUE;
8173 if (argcount < fp->uf_args.ga_len)
8174 error = ERROR_TOOFEW;
8175 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
8176 error = ERROR_TOOMANY;
8177 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
8178 error = ERROR_DICT;
8179 else
8182 * Call the user function.
8183 * Save and restore search patterns, script variables and
8184 * redo buffer.
8186 save_search_patterns();
8187 saveRedobuff();
8188 ++fp->uf_calls;
8189 call_user_func(fp, argcount, argvars, rettv,
8190 firstline, lastline,
8191 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
8192 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
8193 && fp->uf_refcount <= 0)
8194 /* Function was unreferenced while being used, free it
8195 * now. */
8196 func_free(fp);
8197 restoreRedobuff();
8198 restore_search_patterns();
8199 error = ERROR_NONE;
8203 else
8206 * Find the function name in the table, call its implementation.
8208 i = find_internal_func(fname);
8209 if (i >= 0)
8211 if (argcount < functions[i].f_min_argc)
8212 error = ERROR_TOOFEW;
8213 else if (argcount > functions[i].f_max_argc)
8214 error = ERROR_TOOMANY;
8215 else
8217 argvars[argcount].v_type = VAR_UNKNOWN;
8218 functions[i].f_func(argvars, rettv);
8219 error = ERROR_NONE;
8224 * The function call (or "FuncUndefined" autocommand sequence) might
8225 * have been aborted by an error, an interrupt, or an explicitly thrown
8226 * exception that has not been caught so far. This situation can be
8227 * tested for by calling aborting(). For an error in an internal
8228 * function or for the "E132" error in call_user_func(), however, the
8229 * throw point at which the "force_abort" flag (temporarily reset by
8230 * emsg()) is normally updated has not been reached yet. We need to
8231 * update that flag first to make aborting() reliable.
8233 update_force_abort();
8235 if (error == ERROR_NONE)
8236 ret = OK;
8239 * Report an error unless the argument evaluation or function call has been
8240 * cancelled due to an aborting error, an interrupt, or an exception.
8242 if (!aborting())
8244 switch (error)
8246 case ERROR_UNKNOWN:
8247 emsg_funcname(N_("E117: Unknown function: %s"), name);
8248 break;
8249 case ERROR_TOOMANY:
8250 emsg_funcname(e_toomanyarg, name);
8251 break;
8252 case ERROR_TOOFEW:
8253 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
8254 name);
8255 break;
8256 case ERROR_SCRIPT:
8257 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
8258 name);
8259 break;
8260 case ERROR_DICT:
8261 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
8262 name);
8263 break;
8267 if (fname != name && fname != fname_buf)
8268 vim_free(fname);
8269 vim_free(name);
8271 return ret;
8275 * Give an error message with a function name. Handle <SNR> things.
8276 * "ermsg" is to be passed without translation, use N_() instead of _().
8278 static void
8279 emsg_funcname(ermsg, name)
8280 char *ermsg;
8281 char_u *name;
8283 char_u *p;
8285 if (*name == K_SPECIAL)
8286 p = concat_str((char_u *)"<SNR>", name + 3);
8287 else
8288 p = name;
8289 EMSG2(_(ermsg), p);
8290 if (p != name)
8291 vim_free(p);
8295 * Return TRUE for a non-zero Number and a non-empty String.
8297 static int
8298 non_zero_arg(argvars)
8299 typval_T *argvars;
8301 return ((argvars[0].v_type == VAR_NUMBER
8302 && argvars[0].vval.v_number != 0)
8303 || (argvars[0].v_type == VAR_STRING
8304 && argvars[0].vval.v_string != NULL
8305 && *argvars[0].vval.v_string != NUL));
8308 /*********************************************
8309 * Implementation of the built-in functions
8312 #ifdef FEAT_FLOAT
8314 * "abs(expr)" function
8316 static void
8317 f_abs(argvars, rettv)
8318 typval_T *argvars;
8319 typval_T *rettv;
8321 if (argvars[0].v_type == VAR_FLOAT)
8323 rettv->v_type = VAR_FLOAT;
8324 rettv->vval.v_float = fabs(argvars[0].vval.v_float);
8326 else
8328 varnumber_T n;
8329 int error = FALSE;
8331 n = get_tv_number_chk(&argvars[0], &error);
8332 if (error)
8333 rettv->vval.v_number = -1;
8334 else if (n > 0)
8335 rettv->vval.v_number = n;
8336 else
8337 rettv->vval.v_number = -n;
8340 #endif
8343 * "add(list, item)" function
8345 static void
8346 f_add(argvars, rettv)
8347 typval_T *argvars;
8348 typval_T *rettv;
8350 list_T *l;
8352 rettv->vval.v_number = 1; /* Default: Failed */
8353 if (argvars[0].v_type == VAR_LIST)
8355 if ((l = argvars[0].vval.v_list) != NULL
8356 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
8357 && list_append_tv(l, &argvars[1]) == OK)
8358 copy_tv(&argvars[0], rettv);
8360 else
8361 EMSG(_(e_listreq));
8365 * "append(lnum, string/list)" function
8367 static void
8368 f_append(argvars, rettv)
8369 typval_T *argvars;
8370 typval_T *rettv;
8372 long lnum;
8373 char_u *line;
8374 list_T *l = NULL;
8375 listitem_T *li = NULL;
8376 typval_T *tv;
8377 long added = 0;
8379 lnum = get_tv_lnum(argvars);
8380 if (lnum >= 0
8381 && lnum <= curbuf->b_ml.ml_line_count
8382 && u_save(lnum, lnum + 1) == OK)
8384 if (argvars[1].v_type == VAR_LIST)
8386 l = argvars[1].vval.v_list;
8387 if (l == NULL)
8388 return;
8389 li = l->lv_first;
8391 for (;;)
8393 if (l == NULL)
8394 tv = &argvars[1]; /* append a string */
8395 else if (li == NULL)
8396 break; /* end of list */
8397 else
8398 tv = &li->li_tv; /* append item from list */
8399 line = get_tv_string_chk(tv);
8400 if (line == NULL) /* type error */
8402 rettv->vval.v_number = 1; /* Failed */
8403 break;
8405 ml_append(lnum + added, line, (colnr_T)0, FALSE);
8406 ++added;
8407 if (l == NULL)
8408 break;
8409 li = li->li_next;
8412 appended_lines_mark(lnum, added);
8413 if (curwin->w_cursor.lnum > lnum)
8414 curwin->w_cursor.lnum += added;
8416 else
8417 rettv->vval.v_number = 1; /* Failed */
8421 * "argc()" function
8423 static void
8424 f_argc(argvars, rettv)
8425 typval_T *argvars UNUSED;
8426 typval_T *rettv;
8428 rettv->vval.v_number = ARGCOUNT;
8432 * "argidx()" function
8434 static void
8435 f_argidx(argvars, rettv)
8436 typval_T *argvars UNUSED;
8437 typval_T *rettv;
8439 rettv->vval.v_number = curwin->w_arg_idx;
8443 * "argv(nr)" function
8445 static void
8446 f_argv(argvars, rettv)
8447 typval_T *argvars;
8448 typval_T *rettv;
8450 int idx;
8452 if (argvars[0].v_type != VAR_UNKNOWN)
8454 idx = get_tv_number_chk(&argvars[0], NULL);
8455 if (idx >= 0 && idx < ARGCOUNT)
8456 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
8457 else
8458 rettv->vval.v_string = NULL;
8459 rettv->v_type = VAR_STRING;
8461 else if (rettv_list_alloc(rettv) == OK)
8462 for (idx = 0; idx < ARGCOUNT; ++idx)
8463 list_append_string(rettv->vval.v_list,
8464 alist_name(&ARGLIST[idx]), -1);
8467 #ifdef FEAT_FLOAT
8468 static int get_float_arg __ARGS((typval_T *argvars, float_T *f));
8471 * Get the float value of "argvars[0]" into "f".
8472 * Returns FAIL when the argument is not a Number or Float.
8474 static int
8475 get_float_arg(argvars, f)
8476 typval_T *argvars;
8477 float_T *f;
8479 if (argvars[0].v_type == VAR_FLOAT)
8481 *f = argvars[0].vval.v_float;
8482 return OK;
8484 if (argvars[0].v_type == VAR_NUMBER)
8486 *f = (float_T)argvars[0].vval.v_number;
8487 return OK;
8489 EMSG(_("E808: Number or Float required"));
8490 return FAIL;
8494 * "atan()" function
8496 static void
8497 f_atan(argvars, rettv)
8498 typval_T *argvars;
8499 typval_T *rettv;
8501 float_T f;
8503 rettv->v_type = VAR_FLOAT;
8504 if (get_float_arg(argvars, &f) == OK)
8505 rettv->vval.v_float = atan(f);
8506 else
8507 rettv->vval.v_float = 0.0;
8509 #endif
8512 * "browse(save, title, initdir, default)" function
8514 static void
8515 f_browse(argvars, rettv)
8516 typval_T *argvars UNUSED;
8517 typval_T *rettv;
8519 #ifdef FEAT_BROWSE
8520 int save;
8521 char_u *title;
8522 char_u *initdir;
8523 char_u *defname;
8524 char_u buf[NUMBUFLEN];
8525 char_u buf2[NUMBUFLEN];
8526 int error = FALSE;
8528 save = get_tv_number_chk(&argvars[0], &error);
8529 title = get_tv_string_chk(&argvars[1]);
8530 initdir = get_tv_string_buf_chk(&argvars[2], buf);
8531 defname = get_tv_string_buf_chk(&argvars[3], buf2);
8533 if (error || title == NULL || initdir == NULL || defname == NULL)
8534 rettv->vval.v_string = NULL;
8535 else
8536 rettv->vval.v_string =
8537 do_browse(save ? BROWSE_SAVE : 0,
8538 title, defname, NULL, initdir, NULL, curbuf);
8539 #else
8540 rettv->vval.v_string = NULL;
8541 #endif
8542 rettv->v_type = VAR_STRING;
8546 * "browsedir(title, initdir)" function
8548 static void
8549 f_browsedir(argvars, rettv)
8550 typval_T *argvars UNUSED;
8551 typval_T *rettv;
8553 #ifdef FEAT_BROWSE
8554 char_u *title;
8555 char_u *initdir;
8556 char_u buf[NUMBUFLEN];
8558 title = get_tv_string_chk(&argvars[0]);
8559 initdir = get_tv_string_buf_chk(&argvars[1], buf);
8561 if (title == NULL || initdir == NULL)
8562 rettv->vval.v_string = NULL;
8563 else
8564 rettv->vval.v_string = do_browse(BROWSE_DIR,
8565 title, NULL, NULL, initdir, NULL, curbuf);
8566 #else
8567 rettv->vval.v_string = NULL;
8568 #endif
8569 rettv->v_type = VAR_STRING;
8572 static buf_T *find_buffer __ARGS((typval_T *avar));
8575 * Find a buffer by number or exact name.
8577 static buf_T *
8578 find_buffer(avar)
8579 typval_T *avar;
8581 buf_T *buf = NULL;
8583 if (avar->v_type == VAR_NUMBER)
8584 buf = buflist_findnr((int)avar->vval.v_number);
8585 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
8587 buf = buflist_findname_exp(avar->vval.v_string);
8588 if (buf == NULL)
8590 /* No full path name match, try a match with a URL or a "nofile"
8591 * buffer, these don't use the full path. */
8592 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8593 if (buf->b_fname != NULL
8594 && (path_with_url(buf->b_fname)
8595 #ifdef FEAT_QUICKFIX
8596 || bt_nofile(buf)
8597 #endif
8599 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
8600 break;
8603 return buf;
8607 * "bufexists(expr)" function
8609 static void
8610 f_bufexists(argvars, rettv)
8611 typval_T *argvars;
8612 typval_T *rettv;
8614 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
8618 * "buflisted(expr)" function
8620 static void
8621 f_buflisted(argvars, rettv)
8622 typval_T *argvars;
8623 typval_T *rettv;
8625 buf_T *buf;
8627 buf = find_buffer(&argvars[0]);
8628 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
8632 * "bufloaded(expr)" function
8634 static void
8635 f_bufloaded(argvars, rettv)
8636 typval_T *argvars;
8637 typval_T *rettv;
8639 buf_T *buf;
8641 buf = find_buffer(&argvars[0]);
8642 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
8645 static buf_T *get_buf_tv __ARGS((typval_T *tv));
8648 * Get buffer by number or pattern.
8650 static buf_T *
8651 get_buf_tv(tv)
8652 typval_T *tv;
8654 char_u *name = tv->vval.v_string;
8655 int save_magic;
8656 char_u *save_cpo;
8657 buf_T *buf;
8659 if (tv->v_type == VAR_NUMBER)
8660 return buflist_findnr((int)tv->vval.v_number);
8661 if (tv->v_type != VAR_STRING)
8662 return NULL;
8663 if (name == NULL || *name == NUL)
8664 return curbuf;
8665 if (name[0] == '$' && name[1] == NUL)
8666 return lastbuf;
8668 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
8669 save_magic = p_magic;
8670 p_magic = TRUE;
8671 save_cpo = p_cpo;
8672 p_cpo = (char_u *)"";
8674 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8675 TRUE, FALSE));
8677 p_magic = save_magic;
8678 p_cpo = save_cpo;
8680 /* If not found, try expanding the name, like done for bufexists(). */
8681 if (buf == NULL)
8682 buf = find_buffer(tv);
8684 return buf;
8688 * "bufname(expr)" function
8690 static void
8691 f_bufname(argvars, rettv)
8692 typval_T *argvars;
8693 typval_T *rettv;
8695 buf_T *buf;
8697 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8698 ++emsg_off;
8699 buf = get_buf_tv(&argvars[0]);
8700 rettv->v_type = VAR_STRING;
8701 if (buf != NULL && buf->b_fname != NULL)
8702 rettv->vval.v_string = vim_strsave(buf->b_fname);
8703 else
8704 rettv->vval.v_string = NULL;
8705 --emsg_off;
8709 * "bufnr(expr)" function
8711 static void
8712 f_bufnr(argvars, rettv)
8713 typval_T *argvars;
8714 typval_T *rettv;
8716 buf_T *buf;
8717 int error = FALSE;
8718 char_u *name;
8720 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8721 ++emsg_off;
8722 buf = get_buf_tv(&argvars[0]);
8723 --emsg_off;
8725 /* If the buffer isn't found and the second argument is not zero create a
8726 * new buffer. */
8727 if (buf == NULL
8728 && argvars[1].v_type != VAR_UNKNOWN
8729 && get_tv_number_chk(&argvars[1], &error) != 0
8730 && !error
8731 && (name = get_tv_string_chk(&argvars[0])) != NULL
8732 && !error)
8733 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8735 if (buf != NULL)
8736 rettv->vval.v_number = buf->b_fnum;
8737 else
8738 rettv->vval.v_number = -1;
8742 * "bufwinnr(nr)" function
8744 static void
8745 f_bufwinnr(argvars, rettv)
8746 typval_T *argvars;
8747 typval_T *rettv;
8749 #ifdef FEAT_WINDOWS
8750 win_T *wp;
8751 int winnr = 0;
8752 #endif
8753 buf_T *buf;
8755 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8756 ++emsg_off;
8757 buf = get_buf_tv(&argvars[0]);
8758 #ifdef FEAT_WINDOWS
8759 for (wp = firstwin; wp; wp = wp->w_next)
8761 ++winnr;
8762 if (wp->w_buffer == buf)
8763 break;
8765 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8766 #else
8767 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8768 #endif
8769 --emsg_off;
8773 * "byte2line(byte)" function
8775 static void
8776 f_byte2line(argvars, rettv)
8777 typval_T *argvars UNUSED;
8778 typval_T *rettv;
8780 #ifndef FEAT_BYTEOFF
8781 rettv->vval.v_number = -1;
8782 #else
8783 long boff = 0;
8785 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8786 if (boff < 0)
8787 rettv->vval.v_number = -1;
8788 else
8789 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8790 (linenr_T)0, &boff);
8791 #endif
8795 * "byteidx()" function
8797 static void
8798 f_byteidx(argvars, rettv)
8799 typval_T *argvars;
8800 typval_T *rettv;
8802 #ifdef FEAT_MBYTE
8803 char_u *t;
8804 #endif
8805 char_u *str;
8806 long idx;
8808 str = get_tv_string_chk(&argvars[0]);
8809 idx = get_tv_number_chk(&argvars[1], NULL);
8810 rettv->vval.v_number = -1;
8811 if (str == NULL || idx < 0)
8812 return;
8814 #ifdef FEAT_MBYTE
8815 t = str;
8816 for ( ; idx > 0; idx--)
8818 if (*t == NUL) /* EOL reached */
8819 return;
8820 t += (*mb_ptr2len)(t);
8822 rettv->vval.v_number = (varnumber_T)(t - str);
8823 #else
8824 if ((size_t)idx <= STRLEN(str))
8825 rettv->vval.v_number = idx;
8826 #endif
8830 * "call(func, arglist)" function
8832 static void
8833 f_call(argvars, rettv)
8834 typval_T *argvars;
8835 typval_T *rettv;
8837 char_u *func;
8838 typval_T argv[MAX_FUNC_ARGS + 1];
8839 int argc = 0;
8840 listitem_T *item;
8841 int dummy;
8842 dict_T *selfdict = NULL;
8844 if (argvars[1].v_type != VAR_LIST)
8846 EMSG(_(e_listreq));
8847 return;
8849 if (argvars[1].vval.v_list == NULL)
8850 return;
8852 if (argvars[0].v_type == VAR_FUNC)
8853 func = argvars[0].vval.v_string;
8854 else
8855 func = get_tv_string(&argvars[0]);
8856 if (*func == NUL)
8857 return; /* type error or empty name */
8859 if (argvars[2].v_type != VAR_UNKNOWN)
8861 if (argvars[2].v_type != VAR_DICT)
8863 EMSG(_(e_dictreq));
8864 return;
8866 selfdict = argvars[2].vval.v_dict;
8869 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
8870 item = item->li_next)
8872 if (argc == MAX_FUNC_ARGS)
8874 EMSG(_("E699: Too many arguments"));
8875 break;
8877 /* Make a copy of each argument. This is needed to be able to set
8878 * v_lock to VAR_FIXED in the copy without changing the original list.
8880 copy_tv(&item->li_tv, &argv[argc++]);
8883 if (item == NULL)
8884 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
8885 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
8886 &dummy, TRUE, selfdict);
8888 /* Free the arguments. */
8889 while (argc > 0)
8890 clear_tv(&argv[--argc]);
8893 #ifdef FEAT_FLOAT
8895 * "ceil({float})" function
8897 static void
8898 f_ceil(argvars, rettv)
8899 typval_T *argvars;
8900 typval_T *rettv;
8902 float_T f;
8904 rettv->v_type = VAR_FLOAT;
8905 if (get_float_arg(argvars, &f) == OK)
8906 rettv->vval.v_float = ceil(f);
8907 else
8908 rettv->vval.v_float = 0.0;
8910 #endif
8913 * "changenr()" function
8915 static void
8916 f_changenr(argvars, rettv)
8917 typval_T *argvars UNUSED;
8918 typval_T *rettv;
8920 rettv->vval.v_number = curbuf->b_u_seq_cur;
8924 * "char2nr(string)" function
8926 static void
8927 f_char2nr(argvars, rettv)
8928 typval_T *argvars;
8929 typval_T *rettv;
8931 #ifdef FEAT_MBYTE
8932 if (has_mbyte)
8933 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
8934 else
8935 #endif
8936 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
8940 * "cindent(lnum)" function
8942 static void
8943 f_cindent(argvars, rettv)
8944 typval_T *argvars;
8945 typval_T *rettv;
8947 #ifdef FEAT_CINDENT
8948 pos_T pos;
8949 linenr_T lnum;
8951 pos = curwin->w_cursor;
8952 lnum = get_tv_lnum(argvars);
8953 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
8955 curwin->w_cursor.lnum = lnum;
8956 rettv->vval.v_number = get_c_indent();
8957 curwin->w_cursor = pos;
8959 else
8960 #endif
8961 rettv->vval.v_number = -1;
8965 * "clearmatches()" function
8967 static void
8968 f_clearmatches(argvars, rettv)
8969 typval_T *argvars UNUSED;
8970 typval_T *rettv UNUSED;
8972 #ifdef FEAT_SEARCH_EXTRA
8973 clear_matches(curwin);
8974 #endif
8978 * "col(string)" function
8980 static void
8981 f_col(argvars, rettv)
8982 typval_T *argvars;
8983 typval_T *rettv;
8985 colnr_T col = 0;
8986 pos_T *fp;
8987 int fnum = curbuf->b_fnum;
8989 fp = var2fpos(&argvars[0], FALSE, &fnum);
8990 if (fp != NULL && fnum == curbuf->b_fnum)
8992 if (fp->col == MAXCOL)
8994 /* '> can be MAXCOL, get the length of the line then */
8995 if (fp->lnum <= curbuf->b_ml.ml_line_count)
8996 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
8997 else
8998 col = MAXCOL;
9000 else
9002 col = fp->col + 1;
9003 #ifdef FEAT_VIRTUALEDIT
9004 /* col(".") when the cursor is on the NUL at the end of the line
9005 * because of "coladd" can be seen as an extra column. */
9006 if (virtual_active() && fp == &curwin->w_cursor)
9008 char_u *p = ml_get_cursor();
9010 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
9011 curwin->w_virtcol - curwin->w_cursor.coladd))
9013 # ifdef FEAT_MBYTE
9014 int l;
9016 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
9017 col += l;
9018 # else
9019 if (*p != NUL && p[1] == NUL)
9020 ++col;
9021 # endif
9024 #endif
9027 rettv->vval.v_number = col;
9030 #if defined(FEAT_INS_EXPAND)
9032 * "complete()" function
9034 static void
9035 f_complete(argvars, rettv)
9036 typval_T *argvars;
9037 typval_T *rettv UNUSED;
9039 int startcol;
9041 if ((State & INSERT) == 0)
9043 EMSG(_("E785: complete() can only be used in Insert mode"));
9044 return;
9047 /* Check for undo allowed here, because if something was already inserted
9048 * the line was already saved for undo and this check isn't done. */
9049 if (!undo_allowed())
9050 return;
9052 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
9054 EMSG(_(e_invarg));
9055 return;
9058 startcol = get_tv_number_chk(&argvars[0], NULL);
9059 if (startcol <= 0)
9060 return;
9062 set_completion(startcol - 1, argvars[1].vval.v_list);
9066 * "complete_add()" function
9068 static void
9069 f_complete_add(argvars, rettv)
9070 typval_T *argvars;
9071 typval_T *rettv;
9073 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
9077 * "complete_check()" function
9079 static void
9080 f_complete_check(argvars, rettv)
9081 typval_T *argvars UNUSED;
9082 typval_T *rettv;
9084 int saved = RedrawingDisabled;
9086 RedrawingDisabled = 0;
9087 ins_compl_check_keys(0);
9088 rettv->vval.v_number = compl_interrupted;
9089 RedrawingDisabled = saved;
9091 #endif
9094 * "confirm(message, buttons[, default [, type]])" function
9096 static void
9097 f_confirm(argvars, rettv)
9098 typval_T *argvars UNUSED;
9099 typval_T *rettv UNUSED;
9101 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
9102 char_u *message;
9103 char_u *buttons = NULL;
9104 char_u buf[NUMBUFLEN];
9105 char_u buf2[NUMBUFLEN];
9106 int def = 1;
9107 int type = VIM_GENERIC;
9108 char_u *typestr;
9109 int error = FALSE;
9111 message = get_tv_string_chk(&argvars[0]);
9112 if (message == NULL)
9113 error = TRUE;
9114 if (argvars[1].v_type != VAR_UNKNOWN)
9116 buttons = get_tv_string_buf_chk(&argvars[1], buf);
9117 if (buttons == NULL)
9118 error = TRUE;
9119 if (argvars[2].v_type != VAR_UNKNOWN)
9121 def = get_tv_number_chk(&argvars[2], &error);
9122 if (argvars[3].v_type != VAR_UNKNOWN)
9124 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
9125 if (typestr == NULL)
9126 error = TRUE;
9127 else
9129 switch (TOUPPER_ASC(*typestr))
9131 case 'E': type = VIM_ERROR; break;
9132 case 'Q': type = VIM_QUESTION; break;
9133 case 'I': type = VIM_INFO; break;
9134 case 'W': type = VIM_WARNING; break;
9135 case 'G': type = VIM_GENERIC; break;
9142 if (buttons == NULL || *buttons == NUL)
9143 buttons = (char_u *)_("&Ok");
9145 if (!error)
9146 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
9147 def, NULL);
9148 #endif
9152 * "copy()" function
9154 static void
9155 f_copy(argvars, rettv)
9156 typval_T *argvars;
9157 typval_T *rettv;
9159 item_copy(&argvars[0], rettv, FALSE, 0);
9162 #ifdef FEAT_FLOAT
9164 * "cos()" function
9166 static void
9167 f_cos(argvars, rettv)
9168 typval_T *argvars;
9169 typval_T *rettv;
9171 float_T f;
9173 rettv->v_type = VAR_FLOAT;
9174 if (get_float_arg(argvars, &f) == OK)
9175 rettv->vval.v_float = cos(f);
9176 else
9177 rettv->vval.v_float = 0.0;
9179 #endif
9182 * "count()" function
9184 static void
9185 f_count(argvars, rettv)
9186 typval_T *argvars;
9187 typval_T *rettv;
9189 long n = 0;
9190 int ic = FALSE;
9192 if (argvars[0].v_type == VAR_LIST)
9194 listitem_T *li;
9195 list_T *l;
9196 long idx;
9198 if ((l = argvars[0].vval.v_list) != NULL)
9200 li = l->lv_first;
9201 if (argvars[2].v_type != VAR_UNKNOWN)
9203 int error = FALSE;
9205 ic = get_tv_number_chk(&argvars[2], &error);
9206 if (argvars[3].v_type != VAR_UNKNOWN)
9208 idx = get_tv_number_chk(&argvars[3], &error);
9209 if (!error)
9211 li = list_find(l, idx);
9212 if (li == NULL)
9213 EMSGN(_(e_listidx), idx);
9216 if (error)
9217 li = NULL;
9220 for ( ; li != NULL; li = li->li_next)
9221 if (tv_equal(&li->li_tv, &argvars[1], ic))
9222 ++n;
9225 else if (argvars[0].v_type == VAR_DICT)
9227 int todo;
9228 dict_T *d;
9229 hashitem_T *hi;
9231 if ((d = argvars[0].vval.v_dict) != NULL)
9233 int error = FALSE;
9235 if (argvars[2].v_type != VAR_UNKNOWN)
9237 ic = get_tv_number_chk(&argvars[2], &error);
9238 if (argvars[3].v_type != VAR_UNKNOWN)
9239 EMSG(_(e_invarg));
9242 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
9243 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
9245 if (!HASHITEM_EMPTY(hi))
9247 --todo;
9248 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
9249 ++n;
9254 else
9255 EMSG2(_(e_listdictarg), "count()");
9256 rettv->vval.v_number = n;
9260 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
9262 * Checks the existence of a cscope connection.
9264 static void
9265 f_cscope_connection(argvars, rettv)
9266 typval_T *argvars UNUSED;
9267 typval_T *rettv UNUSED;
9269 #ifdef FEAT_CSCOPE
9270 int num = 0;
9271 char_u *dbpath = NULL;
9272 char_u *prepend = NULL;
9273 char_u buf[NUMBUFLEN];
9275 if (argvars[0].v_type != VAR_UNKNOWN
9276 && argvars[1].v_type != VAR_UNKNOWN)
9278 num = (int)get_tv_number(&argvars[0]);
9279 dbpath = get_tv_string(&argvars[1]);
9280 if (argvars[2].v_type != VAR_UNKNOWN)
9281 prepend = get_tv_string_buf(&argvars[2], buf);
9284 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
9285 #endif
9289 * "cursor(lnum, col)" function
9291 * Moves the cursor to the specified line and column.
9292 * Returns 0 when the position could be set, -1 otherwise.
9294 static void
9295 f_cursor(argvars, rettv)
9296 typval_T *argvars;
9297 typval_T *rettv;
9299 long line, col;
9300 #ifdef FEAT_VIRTUALEDIT
9301 long coladd = 0;
9302 #endif
9304 rettv->vval.v_number = -1;
9305 if (argvars[1].v_type == VAR_UNKNOWN)
9307 pos_T pos;
9309 if (list2fpos(argvars, &pos, NULL) == FAIL)
9310 return;
9311 line = pos.lnum;
9312 col = pos.col;
9313 #ifdef FEAT_VIRTUALEDIT
9314 coladd = pos.coladd;
9315 #endif
9317 else
9319 line = get_tv_lnum(argvars);
9320 col = get_tv_number_chk(&argvars[1], NULL);
9321 #ifdef FEAT_VIRTUALEDIT
9322 if (argvars[2].v_type != VAR_UNKNOWN)
9323 coladd = get_tv_number_chk(&argvars[2], NULL);
9324 #endif
9326 if (line < 0 || col < 0
9327 #ifdef FEAT_VIRTUALEDIT
9328 || coladd < 0
9329 #endif
9331 return; /* type error; errmsg already given */
9332 if (line > 0)
9333 curwin->w_cursor.lnum = line;
9334 if (col > 0)
9335 curwin->w_cursor.col = col - 1;
9336 #ifdef FEAT_VIRTUALEDIT
9337 curwin->w_cursor.coladd = coladd;
9338 #endif
9340 /* Make sure the cursor is in a valid position. */
9341 check_cursor();
9342 #ifdef FEAT_MBYTE
9343 /* Correct cursor for multi-byte character. */
9344 if (has_mbyte)
9345 mb_adjust_cursor();
9346 #endif
9348 curwin->w_set_curswant = TRUE;
9349 rettv->vval.v_number = 0;
9353 * "deepcopy()" function
9355 static void
9356 f_deepcopy(argvars, rettv)
9357 typval_T *argvars;
9358 typval_T *rettv;
9360 int noref = 0;
9362 if (argvars[1].v_type != VAR_UNKNOWN)
9363 noref = get_tv_number_chk(&argvars[1], NULL);
9364 if (noref < 0 || noref > 1)
9365 EMSG(_(e_invarg));
9366 else
9368 current_copyID += COPYID_INC;
9369 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? current_copyID : 0);
9374 * "delete()" function
9376 static void
9377 f_delete(argvars, rettv)
9378 typval_T *argvars;
9379 typval_T *rettv;
9381 if (check_restricted() || check_secure())
9382 rettv->vval.v_number = -1;
9383 else
9384 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
9388 * "did_filetype()" function
9390 static void
9391 f_did_filetype(argvars, rettv)
9392 typval_T *argvars UNUSED;
9393 typval_T *rettv UNUSED;
9395 #ifdef FEAT_AUTOCMD
9396 rettv->vval.v_number = did_filetype;
9397 #endif
9401 * "diff_filler()" function
9403 static void
9404 f_diff_filler(argvars, rettv)
9405 typval_T *argvars UNUSED;
9406 typval_T *rettv UNUSED;
9408 #ifdef FEAT_DIFF
9409 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
9410 #endif
9414 * "diff_hlID()" function
9416 static void
9417 f_diff_hlID(argvars, rettv)
9418 typval_T *argvars UNUSED;
9419 typval_T *rettv UNUSED;
9421 #ifdef FEAT_DIFF
9422 linenr_T lnum = get_tv_lnum(argvars);
9423 static linenr_T prev_lnum = 0;
9424 static int changedtick = 0;
9425 static int fnum = 0;
9426 static int change_start = 0;
9427 static int change_end = 0;
9428 static hlf_T hlID = (hlf_T)0;
9429 int filler_lines;
9430 int col;
9432 if (lnum < 0) /* ignore type error in {lnum} arg */
9433 lnum = 0;
9434 if (lnum != prev_lnum
9435 || changedtick != curbuf->b_changedtick
9436 || fnum != curbuf->b_fnum)
9438 /* New line, buffer, change: need to get the values. */
9439 filler_lines = diff_check(curwin, lnum);
9440 if (filler_lines < 0)
9442 if (filler_lines == -1)
9444 change_start = MAXCOL;
9445 change_end = -1;
9446 if (diff_find_change(curwin, lnum, &change_start, &change_end))
9447 hlID = HLF_ADD; /* added line */
9448 else
9449 hlID = HLF_CHD; /* changed line */
9451 else
9452 hlID = HLF_ADD; /* added line */
9454 else
9455 hlID = (hlf_T)0;
9456 prev_lnum = lnum;
9457 changedtick = curbuf->b_changedtick;
9458 fnum = curbuf->b_fnum;
9461 if (hlID == HLF_CHD || hlID == HLF_TXD)
9463 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
9464 if (col >= change_start && col <= change_end)
9465 hlID = HLF_TXD; /* changed text */
9466 else
9467 hlID = HLF_CHD; /* changed line */
9469 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
9470 #endif
9474 * "empty({expr})" function
9476 static void
9477 f_empty(argvars, rettv)
9478 typval_T *argvars;
9479 typval_T *rettv;
9481 int n;
9483 switch (argvars[0].v_type)
9485 case VAR_STRING:
9486 case VAR_FUNC:
9487 n = argvars[0].vval.v_string == NULL
9488 || *argvars[0].vval.v_string == NUL;
9489 break;
9490 case VAR_NUMBER:
9491 n = argvars[0].vval.v_number == 0;
9492 break;
9493 #ifdef FEAT_FLOAT
9494 case VAR_FLOAT:
9495 n = argvars[0].vval.v_float == 0.0;
9496 break;
9497 #endif
9498 case VAR_LIST:
9499 n = argvars[0].vval.v_list == NULL
9500 || argvars[0].vval.v_list->lv_first == NULL;
9501 break;
9502 case VAR_DICT:
9503 n = argvars[0].vval.v_dict == NULL
9504 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
9505 break;
9506 default:
9507 EMSG2(_(e_intern2), "f_empty()");
9508 n = 0;
9511 rettv->vval.v_number = n;
9515 * "escape({string}, {chars})" function
9517 static void
9518 f_escape(argvars, rettv)
9519 typval_T *argvars;
9520 typval_T *rettv;
9522 char_u buf[NUMBUFLEN];
9524 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
9525 get_tv_string_buf(&argvars[1], buf));
9526 rettv->v_type = VAR_STRING;
9530 * "eval()" function
9532 static void
9533 f_eval(argvars, rettv)
9534 typval_T *argvars;
9535 typval_T *rettv;
9537 char_u *s;
9539 s = get_tv_string_chk(&argvars[0]);
9540 if (s != NULL)
9541 s = skipwhite(s);
9543 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
9545 rettv->v_type = VAR_NUMBER;
9546 rettv->vval.v_number = 0;
9548 else if (*s != NUL)
9549 EMSG(_(e_trailing));
9553 * "eventhandler()" function
9555 static void
9556 f_eventhandler(argvars, rettv)
9557 typval_T *argvars UNUSED;
9558 typval_T *rettv;
9560 rettv->vval.v_number = vgetc_busy;
9564 * "executable()" function
9566 static void
9567 f_executable(argvars, rettv)
9568 typval_T *argvars;
9569 typval_T *rettv;
9571 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
9575 * "exists()" function
9577 static void
9578 f_exists(argvars, rettv)
9579 typval_T *argvars;
9580 typval_T *rettv;
9582 char_u *p;
9583 char_u *name;
9584 int n = FALSE;
9585 int len = 0;
9587 p = get_tv_string(&argvars[0]);
9588 if (*p == '$') /* environment variable */
9590 /* first try "normal" environment variables (fast) */
9591 if (mch_getenv(p + 1) != NULL)
9592 n = TRUE;
9593 else
9595 /* try expanding things like $VIM and ${HOME} */
9596 p = expand_env_save(p);
9597 if (p != NULL && *p != '$')
9598 n = TRUE;
9599 vim_free(p);
9602 else if (*p == '&' || *p == '+') /* option */
9604 n = (get_option_tv(&p, NULL, TRUE) == OK);
9605 if (*skipwhite(p) != NUL)
9606 n = FALSE; /* trailing garbage */
9608 else if (*p == '*') /* internal or user defined function */
9610 n = function_exists(p + 1);
9612 else if (*p == ':')
9614 n = cmd_exists(p + 1);
9616 else if (*p == '#')
9618 #ifdef FEAT_AUTOCMD
9619 if (p[1] == '#')
9620 n = autocmd_supported(p + 2);
9621 else
9622 n = au_exists(p + 1);
9623 #endif
9625 else /* internal variable */
9627 char_u *tofree;
9628 typval_T tv;
9630 /* get_name_len() takes care of expanding curly braces */
9631 name = p;
9632 len = get_name_len(&p, &tofree, TRUE, FALSE);
9633 if (len > 0)
9635 if (tofree != NULL)
9636 name = tofree;
9637 n = (get_var_tv(name, len, &tv, FALSE) == OK);
9638 if (n)
9640 /* handle d.key, l[idx], f(expr) */
9641 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
9642 if (n)
9643 clear_tv(&tv);
9646 if (*p != NUL)
9647 n = FALSE;
9649 vim_free(tofree);
9652 rettv->vval.v_number = n;
9656 * "expand()" function
9658 static void
9659 f_expand(argvars, rettv)
9660 typval_T *argvars;
9661 typval_T *rettv;
9663 char_u *s;
9664 int len;
9665 char_u *errormsg;
9666 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
9667 expand_T xpc;
9668 int error = FALSE;
9670 rettv->v_type = VAR_STRING;
9671 s = get_tv_string(&argvars[0]);
9672 if (*s == '%' || *s == '#' || *s == '<')
9674 ++emsg_off;
9675 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
9676 --emsg_off;
9678 else
9680 /* When the optional second argument is non-zero, don't remove matches
9681 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
9682 if (argvars[1].v_type != VAR_UNKNOWN
9683 && get_tv_number_chk(&argvars[1], &error))
9684 flags |= WILD_KEEP_ALL;
9685 if (!error)
9687 ExpandInit(&xpc);
9688 xpc.xp_context = EXPAND_FILES;
9689 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
9691 else
9692 rettv->vval.v_string = NULL;
9697 * "extend(list, list [, idx])" function
9698 * "extend(dict, dict [, action])" function
9700 static void
9701 f_extend(argvars, rettv)
9702 typval_T *argvars;
9703 typval_T *rettv;
9705 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9707 list_T *l1, *l2;
9708 listitem_T *item;
9709 long before;
9710 int error = FALSE;
9712 l1 = argvars[0].vval.v_list;
9713 l2 = argvars[1].vval.v_list;
9714 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9715 && l2 != NULL)
9717 if (argvars[2].v_type != VAR_UNKNOWN)
9719 before = get_tv_number_chk(&argvars[2], &error);
9720 if (error)
9721 return; /* type error; errmsg already given */
9723 if (before == l1->lv_len)
9724 item = NULL;
9725 else
9727 item = list_find(l1, before);
9728 if (item == NULL)
9730 EMSGN(_(e_listidx), before);
9731 return;
9735 else
9736 item = NULL;
9737 list_extend(l1, l2, item);
9739 copy_tv(&argvars[0], rettv);
9742 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9744 dict_T *d1, *d2;
9745 dictitem_T *di1;
9746 char_u *action;
9747 int i;
9748 hashitem_T *hi2;
9749 int todo;
9751 d1 = argvars[0].vval.v_dict;
9752 d2 = argvars[1].vval.v_dict;
9753 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9754 && d2 != NULL)
9756 /* Check the third argument. */
9757 if (argvars[2].v_type != VAR_UNKNOWN)
9759 static char *(av[]) = {"keep", "force", "error"};
9761 action = get_tv_string_chk(&argvars[2]);
9762 if (action == NULL)
9763 return; /* type error; errmsg already given */
9764 for (i = 0; i < 3; ++i)
9765 if (STRCMP(action, av[i]) == 0)
9766 break;
9767 if (i == 3)
9769 EMSG2(_(e_invarg2), action);
9770 return;
9773 else
9774 action = (char_u *)"force";
9776 /* Go over all entries in the second dict and add them to the
9777 * first dict. */
9778 todo = (int)d2->dv_hashtab.ht_used;
9779 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9781 if (!HASHITEM_EMPTY(hi2))
9783 --todo;
9784 di1 = dict_find(d1, hi2->hi_key, -1);
9785 if (di1 == NULL)
9787 di1 = dictitem_copy(HI2DI(hi2));
9788 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9789 dictitem_free(di1);
9791 else if (*action == 'e')
9793 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9794 break;
9796 else if (*action == 'f')
9798 clear_tv(&di1->di_tv);
9799 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9804 copy_tv(&argvars[0], rettv);
9807 else
9808 EMSG2(_(e_listdictarg), "extend()");
9812 * "feedkeys()" function
9814 static void
9815 f_feedkeys(argvars, rettv)
9816 typval_T *argvars;
9817 typval_T *rettv UNUSED;
9819 int remap = TRUE;
9820 char_u *keys, *flags;
9821 char_u nbuf[NUMBUFLEN];
9822 int typed = FALSE;
9823 char_u *keys_esc;
9825 /* This is not allowed in the sandbox. If the commands would still be
9826 * executed in the sandbox it would be OK, but it probably happens later,
9827 * when "sandbox" is no longer set. */
9828 if (check_secure())
9829 return;
9831 keys = get_tv_string(&argvars[0]);
9832 if (*keys != NUL)
9834 if (argvars[1].v_type != VAR_UNKNOWN)
9836 flags = get_tv_string_buf(&argvars[1], nbuf);
9837 for ( ; *flags != NUL; ++flags)
9839 switch (*flags)
9841 case 'n': remap = FALSE; break;
9842 case 'm': remap = TRUE; break;
9843 case 't': typed = TRUE; break;
9848 /* Need to escape K_SPECIAL and CSI before putting the string in the
9849 * typeahead buffer. */
9850 keys_esc = vim_strsave_escape_csi(keys);
9851 if (keys_esc != NULL)
9853 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
9854 typebuf.tb_len, !typed, FALSE);
9855 vim_free(keys_esc);
9856 if (vgetc_busy)
9857 typebuf_was_filled = TRUE;
9863 * "filereadable()" function
9865 static void
9866 f_filereadable(argvars, rettv)
9867 typval_T *argvars;
9868 typval_T *rettv;
9870 int fd;
9871 char_u *p;
9872 int n;
9874 #ifndef O_NONBLOCK
9875 # define O_NONBLOCK 0
9876 #endif
9877 p = get_tv_string(&argvars[0]);
9878 if (*p && !mch_isdir(p) && (fd = mch_open((char *)p,
9879 O_RDONLY | O_NONBLOCK, 0)) >= 0)
9881 n = TRUE;
9882 close(fd);
9884 else
9885 n = FALSE;
9887 rettv->vval.v_number = n;
9891 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
9892 * rights to write into.
9894 static void
9895 f_filewritable(argvars, rettv)
9896 typval_T *argvars;
9897 typval_T *rettv;
9899 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
9902 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
9904 static void
9905 findfilendir(argvars, rettv, find_what)
9906 typval_T *argvars;
9907 typval_T *rettv;
9908 int find_what;
9910 #ifdef FEAT_SEARCHPATH
9911 char_u *fname;
9912 char_u *fresult = NULL;
9913 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
9914 char_u *p;
9915 char_u pathbuf[NUMBUFLEN];
9916 int count = 1;
9917 int first = TRUE;
9918 int error = FALSE;
9919 #endif
9921 rettv->vval.v_string = NULL;
9922 rettv->v_type = VAR_STRING;
9924 #ifdef FEAT_SEARCHPATH
9925 fname = get_tv_string(&argvars[0]);
9927 if (argvars[1].v_type != VAR_UNKNOWN)
9929 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
9930 if (p == NULL)
9931 error = TRUE;
9932 else
9934 if (*p != NUL)
9935 path = p;
9937 if (argvars[2].v_type != VAR_UNKNOWN)
9938 count = get_tv_number_chk(&argvars[2], &error);
9942 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
9943 error = TRUE;
9945 if (*fname != NUL && !error)
9949 if (rettv->v_type == VAR_STRING)
9950 vim_free(fresult);
9951 fresult = find_file_in_path_option(first ? fname : NULL,
9952 first ? (int)STRLEN(fname) : 0,
9953 0, first, path,
9954 find_what,
9955 curbuf->b_ffname,
9956 find_what == FINDFILE_DIR
9957 ? (char_u *)"" : curbuf->b_p_sua);
9958 first = FALSE;
9960 if (fresult != NULL && rettv->v_type == VAR_LIST)
9961 list_append_string(rettv->vval.v_list, fresult, -1);
9963 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
9966 if (rettv->v_type == VAR_STRING)
9967 rettv->vval.v_string = fresult;
9968 #endif
9971 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
9972 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
9975 * Implementation of map() and filter().
9977 static void
9978 filter_map(argvars, rettv, map)
9979 typval_T *argvars;
9980 typval_T *rettv;
9981 int map;
9983 char_u buf[NUMBUFLEN];
9984 char_u *expr;
9985 listitem_T *li, *nli;
9986 list_T *l = NULL;
9987 dictitem_T *di;
9988 hashtab_T *ht;
9989 hashitem_T *hi;
9990 dict_T *d = NULL;
9991 typval_T save_val;
9992 typval_T save_key;
9993 int rem;
9994 int todo;
9995 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
9996 int save_did_emsg;
9997 int index = 0;
9999 if (argvars[0].v_type == VAR_LIST)
10001 if ((l = argvars[0].vval.v_list) == NULL
10002 || (map && tv_check_lock(l->lv_lock, ermsg)))
10003 return;
10005 else if (argvars[0].v_type == VAR_DICT)
10007 if ((d = argvars[0].vval.v_dict) == NULL
10008 || (map && tv_check_lock(d->dv_lock, ermsg)))
10009 return;
10011 else
10013 EMSG2(_(e_listdictarg), ermsg);
10014 return;
10017 expr = get_tv_string_buf_chk(&argvars[1], buf);
10018 /* On type errors, the preceding call has already displayed an error
10019 * message. Avoid a misleading error message for an empty string that
10020 * was not passed as argument. */
10021 if (expr != NULL)
10023 prepare_vimvar(VV_VAL, &save_val);
10024 expr = skipwhite(expr);
10026 /* We reset "did_emsg" to be able to detect whether an error
10027 * occurred during evaluation of the expression. */
10028 save_did_emsg = did_emsg;
10029 did_emsg = FALSE;
10031 prepare_vimvar(VV_KEY, &save_key);
10032 if (argvars[0].v_type == VAR_DICT)
10034 vimvars[VV_KEY].vv_type = VAR_STRING;
10036 ht = &d->dv_hashtab;
10037 hash_lock(ht);
10038 todo = (int)ht->ht_used;
10039 for (hi = ht->ht_array; todo > 0; ++hi)
10041 if (!HASHITEM_EMPTY(hi))
10043 --todo;
10044 di = HI2DI(hi);
10045 if (tv_check_lock(di->di_tv.v_lock, ermsg))
10046 break;
10047 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
10048 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
10049 || did_emsg)
10050 break;
10051 if (!map && rem)
10052 dictitem_remove(d, di);
10053 clear_tv(&vimvars[VV_KEY].vv_tv);
10056 hash_unlock(ht);
10058 else
10060 vimvars[VV_KEY].vv_type = VAR_NUMBER;
10062 for (li = l->lv_first; li != NULL; li = nli)
10064 if (tv_check_lock(li->li_tv.v_lock, ermsg))
10065 break;
10066 nli = li->li_next;
10067 vimvars[VV_KEY].vv_nr = index;
10068 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
10069 || did_emsg)
10070 break;
10071 if (!map && rem)
10072 listitem_remove(l, li);
10073 ++index;
10077 restore_vimvar(VV_KEY, &save_key);
10078 restore_vimvar(VV_VAL, &save_val);
10080 did_emsg |= save_did_emsg;
10083 copy_tv(&argvars[0], rettv);
10086 static int
10087 filter_map_one(tv, expr, map, remp)
10088 typval_T *tv;
10089 char_u *expr;
10090 int map;
10091 int *remp;
10093 typval_T rettv;
10094 char_u *s;
10095 int retval = FAIL;
10097 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
10098 s = expr;
10099 if (eval1(&s, &rettv, TRUE) == FAIL)
10100 goto theend;
10101 if (*s != NUL) /* check for trailing chars after expr */
10103 EMSG2(_(e_invexpr2), s);
10104 goto theend;
10106 if (map)
10108 /* map(): replace the list item value */
10109 clear_tv(tv);
10110 rettv.v_lock = 0;
10111 *tv = rettv;
10113 else
10115 int error = FALSE;
10117 /* filter(): when expr is zero remove the item */
10118 *remp = (get_tv_number_chk(&rettv, &error) == 0);
10119 clear_tv(&rettv);
10120 /* On type error, nothing has been removed; return FAIL to stop the
10121 * loop. The error message was given by get_tv_number_chk(). */
10122 if (error)
10123 goto theend;
10125 retval = OK;
10126 theend:
10127 clear_tv(&vimvars[VV_VAL].vv_tv);
10128 return retval;
10132 * "filter()" function
10134 static void
10135 f_filter(argvars, rettv)
10136 typval_T *argvars;
10137 typval_T *rettv;
10139 filter_map(argvars, rettv, FALSE);
10143 * "finddir({fname}[, {path}[, {count}]])" function
10145 static void
10146 f_finddir(argvars, rettv)
10147 typval_T *argvars;
10148 typval_T *rettv;
10150 findfilendir(argvars, rettv, FINDFILE_DIR);
10154 * "findfile({fname}[, {path}[, {count}]])" function
10156 static void
10157 f_findfile(argvars, rettv)
10158 typval_T *argvars;
10159 typval_T *rettv;
10161 findfilendir(argvars, rettv, FINDFILE_FILE);
10164 #ifdef FEAT_FLOAT
10166 * "float2nr({float})" function
10168 static void
10169 f_float2nr(argvars, rettv)
10170 typval_T *argvars;
10171 typval_T *rettv;
10173 float_T f;
10175 if (get_float_arg(argvars, &f) == OK)
10177 if (f < -0x7fffffff)
10178 rettv->vval.v_number = -0x7fffffff;
10179 else if (f > 0x7fffffff)
10180 rettv->vval.v_number = 0x7fffffff;
10181 else
10182 rettv->vval.v_number = (varnumber_T)f;
10187 * "floor({float})" function
10189 static void
10190 f_floor(argvars, rettv)
10191 typval_T *argvars;
10192 typval_T *rettv;
10194 float_T f;
10196 rettv->v_type = VAR_FLOAT;
10197 if (get_float_arg(argvars, &f) == OK)
10198 rettv->vval.v_float = floor(f);
10199 else
10200 rettv->vval.v_float = 0.0;
10202 #endif
10205 * "fnameescape({string})" function
10207 static void
10208 f_fnameescape(argvars, rettv)
10209 typval_T *argvars;
10210 typval_T *rettv;
10212 rettv->vval.v_string = vim_strsave_fnameescape(
10213 get_tv_string(&argvars[0]), FALSE);
10214 rettv->v_type = VAR_STRING;
10218 * "fnamemodify({fname}, {mods})" function
10220 static void
10221 f_fnamemodify(argvars, rettv)
10222 typval_T *argvars;
10223 typval_T *rettv;
10225 char_u *fname;
10226 char_u *mods;
10227 int usedlen = 0;
10228 int len;
10229 char_u *fbuf = NULL;
10230 char_u buf[NUMBUFLEN];
10232 fname = get_tv_string_chk(&argvars[0]);
10233 mods = get_tv_string_buf_chk(&argvars[1], buf);
10234 if (fname == NULL || mods == NULL)
10235 fname = NULL;
10236 else
10238 len = (int)STRLEN(fname);
10239 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
10242 rettv->v_type = VAR_STRING;
10243 if (fname == NULL)
10244 rettv->vval.v_string = NULL;
10245 else
10246 rettv->vval.v_string = vim_strnsave(fname, len);
10247 vim_free(fbuf);
10250 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
10253 * "foldclosed()" function
10255 static void
10256 foldclosed_both(argvars, rettv, end)
10257 typval_T *argvars;
10258 typval_T *rettv;
10259 int end;
10261 #ifdef FEAT_FOLDING
10262 linenr_T lnum;
10263 linenr_T first, last;
10265 lnum = get_tv_lnum(argvars);
10266 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10268 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
10270 if (end)
10271 rettv->vval.v_number = (varnumber_T)last;
10272 else
10273 rettv->vval.v_number = (varnumber_T)first;
10274 return;
10277 #endif
10278 rettv->vval.v_number = -1;
10282 * "foldclosed()" function
10284 static void
10285 f_foldclosed(argvars, rettv)
10286 typval_T *argvars;
10287 typval_T *rettv;
10289 foldclosed_both(argvars, rettv, FALSE);
10293 * "foldclosedend()" function
10295 static void
10296 f_foldclosedend(argvars, rettv)
10297 typval_T *argvars;
10298 typval_T *rettv;
10300 foldclosed_both(argvars, rettv, TRUE);
10304 * "foldlevel()" function
10306 static void
10307 f_foldlevel(argvars, rettv)
10308 typval_T *argvars;
10309 typval_T *rettv;
10311 #ifdef FEAT_FOLDING
10312 linenr_T lnum;
10314 lnum = get_tv_lnum(argvars);
10315 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10316 rettv->vval.v_number = foldLevel(lnum);
10317 #endif
10321 * "foldtext()" function
10323 static void
10324 f_foldtext(argvars, rettv)
10325 typval_T *argvars UNUSED;
10326 typval_T *rettv;
10328 #ifdef FEAT_FOLDING
10329 linenr_T lnum;
10330 char_u *s;
10331 char_u *r;
10332 int len;
10333 char *txt;
10334 #endif
10336 rettv->v_type = VAR_STRING;
10337 rettv->vval.v_string = NULL;
10338 #ifdef FEAT_FOLDING
10339 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
10340 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
10341 <= curbuf->b_ml.ml_line_count
10342 && vimvars[VV_FOLDDASHES].vv_str != NULL)
10344 /* Find first non-empty line in the fold. */
10345 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
10346 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10348 if (!linewhite(lnum))
10349 break;
10350 ++lnum;
10353 /* Find interesting text in this line. */
10354 s = skipwhite(ml_get(lnum));
10355 /* skip C comment-start */
10356 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
10358 s = skipwhite(s + 2);
10359 if (*skipwhite(s) == NUL
10360 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10362 s = skipwhite(ml_get(lnum + 1));
10363 if (*s == '*')
10364 s = skipwhite(s + 1);
10367 txt = _("+-%s%3ld lines: ");
10368 r = alloc((unsigned)(STRLEN(txt)
10369 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
10370 + 20 /* for %3ld */
10371 + STRLEN(s))); /* concatenated */
10372 if (r != NULL)
10374 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
10375 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
10376 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
10377 len = (int)STRLEN(r);
10378 STRCAT(r, s);
10379 /* remove 'foldmarker' and 'commentstring' */
10380 foldtext_cleanup(r + len);
10381 rettv->vval.v_string = r;
10384 #endif
10388 * "foldtextresult(lnum)" function
10390 static void
10391 f_foldtextresult(argvars, rettv)
10392 typval_T *argvars UNUSED;
10393 typval_T *rettv;
10395 #ifdef FEAT_FOLDING
10396 linenr_T lnum;
10397 char_u *text;
10398 char_u buf[51];
10399 foldinfo_T foldinfo;
10400 int fold_count;
10401 #endif
10403 rettv->v_type = VAR_STRING;
10404 rettv->vval.v_string = NULL;
10405 #ifdef FEAT_FOLDING
10406 lnum = get_tv_lnum(argvars);
10407 /* treat illegal types and illegal string values for {lnum} the same */
10408 if (lnum < 0)
10409 lnum = 0;
10410 fold_count = foldedCount(curwin, lnum, &foldinfo);
10411 if (fold_count > 0)
10413 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
10414 &foldinfo, buf);
10415 if (text == buf)
10416 text = vim_strsave(text);
10417 rettv->vval.v_string = text;
10419 #endif
10423 * "foreground()" function
10425 static void
10426 f_foreground(argvars, rettv)
10427 typval_T *argvars UNUSED;
10428 typval_T *rettv UNUSED;
10430 #ifdef FEAT_GUI
10431 if (gui.in_use)
10432 gui_mch_set_foreground();
10433 #else
10434 # ifdef WIN32
10435 win32_set_foreground();
10436 # endif
10437 #endif
10441 * "function()" function
10443 static void
10444 f_function(argvars, rettv)
10445 typval_T *argvars;
10446 typval_T *rettv;
10448 char_u *s;
10450 s = get_tv_string(&argvars[0]);
10451 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
10452 EMSG2(_(e_invarg2), s);
10453 /* Don't check an autoload name for existence here. */
10454 else if (vim_strchr(s, AUTOLOAD_CHAR) == NULL && !function_exists(s))
10455 EMSG2(_("E700: Unknown function: %s"), s);
10456 else
10458 rettv->vval.v_string = vim_strsave(s);
10459 rettv->v_type = VAR_FUNC;
10464 * "garbagecollect()" function
10466 static void
10467 f_garbagecollect(argvars, rettv)
10468 typval_T *argvars;
10469 typval_T *rettv UNUSED;
10471 /* This is postponed until we are back at the toplevel, because we may be
10472 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
10473 want_garbage_collect = TRUE;
10475 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
10476 garbage_collect_at_exit = TRUE;
10480 * "get()" function
10482 static void
10483 f_get(argvars, rettv)
10484 typval_T *argvars;
10485 typval_T *rettv;
10487 listitem_T *li;
10488 list_T *l;
10489 dictitem_T *di;
10490 dict_T *d;
10491 typval_T *tv = NULL;
10493 if (argvars[0].v_type == VAR_LIST)
10495 if ((l = argvars[0].vval.v_list) != NULL)
10497 int error = FALSE;
10499 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
10500 if (!error && li != NULL)
10501 tv = &li->li_tv;
10504 else if (argvars[0].v_type == VAR_DICT)
10506 if ((d = argvars[0].vval.v_dict) != NULL)
10508 di = dict_find(d, get_tv_string(&argvars[1]), -1);
10509 if (di != NULL)
10510 tv = &di->di_tv;
10513 else
10514 EMSG2(_(e_listdictarg), "get()");
10516 if (tv == NULL)
10518 if (argvars[2].v_type != VAR_UNKNOWN)
10519 copy_tv(&argvars[2], rettv);
10521 else
10522 copy_tv(tv, rettv);
10525 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
10528 * Get line or list of lines from buffer "buf" into "rettv".
10529 * Return a range (from start to end) of lines in rettv from the specified
10530 * buffer.
10531 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
10533 static void
10534 get_buffer_lines(buf, start, end, retlist, rettv)
10535 buf_T *buf;
10536 linenr_T start;
10537 linenr_T end;
10538 int retlist;
10539 typval_T *rettv;
10541 char_u *p;
10543 if (retlist && rettv_list_alloc(rettv) == FAIL)
10544 return;
10546 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
10547 return;
10549 if (!retlist)
10551 if (start >= 1 && start <= buf->b_ml.ml_line_count)
10552 p = ml_get_buf(buf, start, FALSE);
10553 else
10554 p = (char_u *)"";
10556 rettv->v_type = VAR_STRING;
10557 rettv->vval.v_string = vim_strsave(p);
10559 else
10561 if (end < start)
10562 return;
10564 if (start < 1)
10565 start = 1;
10566 if (end > buf->b_ml.ml_line_count)
10567 end = buf->b_ml.ml_line_count;
10568 while (start <= end)
10569 if (list_append_string(rettv->vval.v_list,
10570 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
10571 break;
10576 * "getbufline()" function
10578 static void
10579 f_getbufline(argvars, rettv)
10580 typval_T *argvars;
10581 typval_T *rettv;
10583 linenr_T lnum;
10584 linenr_T end;
10585 buf_T *buf;
10587 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10588 ++emsg_off;
10589 buf = get_buf_tv(&argvars[0]);
10590 --emsg_off;
10592 lnum = get_tv_lnum_buf(&argvars[1], buf);
10593 if (argvars[2].v_type == VAR_UNKNOWN)
10594 end = lnum;
10595 else
10596 end = get_tv_lnum_buf(&argvars[2], buf);
10598 get_buffer_lines(buf, lnum, end, TRUE, rettv);
10602 * "getbufvar()" function
10604 static void
10605 f_getbufvar(argvars, rettv)
10606 typval_T *argvars;
10607 typval_T *rettv;
10609 buf_T *buf;
10610 buf_T *save_curbuf;
10611 char_u *varname;
10612 dictitem_T *v;
10614 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10615 varname = get_tv_string_chk(&argvars[1]);
10616 ++emsg_off;
10617 buf = get_buf_tv(&argvars[0]);
10619 rettv->v_type = VAR_STRING;
10620 rettv->vval.v_string = NULL;
10622 if (buf != NULL && varname != NULL)
10624 /* set curbuf to be our buf, temporarily */
10625 save_curbuf = curbuf;
10626 curbuf = buf;
10628 if (*varname == '&') /* buffer-local-option */
10629 get_option_tv(&varname, rettv, TRUE);
10630 else
10632 if (*varname == NUL)
10633 /* let getbufvar({nr}, "") return the "b:" dictionary. The
10634 * scope prefix before the NUL byte is required by
10635 * find_var_in_ht(). */
10636 varname = (char_u *)"b:" + 2;
10637 /* look up the variable */
10638 v = find_var_in_ht(&curbuf->b_vars.dv_hashtab, varname, FALSE);
10639 if (v != NULL)
10640 copy_tv(&v->di_tv, rettv);
10643 /* restore previous notion of curbuf */
10644 curbuf = save_curbuf;
10647 --emsg_off;
10651 * "getchar()" function
10653 static void
10654 f_getchar(argvars, rettv)
10655 typval_T *argvars;
10656 typval_T *rettv;
10658 varnumber_T n;
10659 int error = FALSE;
10661 /* Position the cursor. Needed after a message that ends in a space. */
10662 windgoto(msg_row, msg_col);
10664 ++no_mapping;
10665 ++allow_keys;
10666 for (;;)
10668 if (argvars[0].v_type == VAR_UNKNOWN)
10669 /* getchar(): blocking wait. */
10670 n = safe_vgetc();
10671 else if (get_tv_number_chk(&argvars[0], &error) == 1)
10672 /* getchar(1): only check if char avail */
10673 n = vpeekc();
10674 else if (error || vpeekc() == NUL)
10675 /* illegal argument or getchar(0) and no char avail: return zero */
10676 n = 0;
10677 else
10678 /* getchar(0) and char avail: return char */
10679 n = safe_vgetc();
10680 if (n == K_IGNORE)
10681 continue;
10682 break;
10684 --no_mapping;
10685 --allow_keys;
10687 vimvars[VV_MOUSE_WIN].vv_nr = 0;
10688 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
10689 vimvars[VV_MOUSE_COL].vv_nr = 0;
10691 rettv->vval.v_number = n;
10692 if (IS_SPECIAL(n) || mod_mask != 0)
10694 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
10695 int i = 0;
10697 /* Turn a special key into three bytes, plus modifier. */
10698 if (mod_mask != 0)
10700 temp[i++] = K_SPECIAL;
10701 temp[i++] = KS_MODIFIER;
10702 temp[i++] = mod_mask;
10704 if (IS_SPECIAL(n))
10706 temp[i++] = K_SPECIAL;
10707 temp[i++] = K_SECOND(n);
10708 temp[i++] = K_THIRD(n);
10710 #ifdef FEAT_MBYTE
10711 else if (has_mbyte)
10712 i += (*mb_char2bytes)(n, temp + i);
10713 #endif
10714 else
10715 temp[i++] = n;
10716 temp[i++] = NUL;
10717 rettv->v_type = VAR_STRING;
10718 rettv->vval.v_string = vim_strsave(temp);
10720 #ifdef FEAT_MOUSE
10721 if (n == K_LEFTMOUSE
10722 || n == K_LEFTMOUSE_NM
10723 || n == K_LEFTDRAG
10724 || n == K_LEFTRELEASE
10725 || n == K_LEFTRELEASE_NM
10726 || n == K_MIDDLEMOUSE
10727 || n == K_MIDDLEDRAG
10728 || n == K_MIDDLERELEASE
10729 || n == K_RIGHTMOUSE
10730 || n == K_RIGHTDRAG
10731 || n == K_RIGHTRELEASE
10732 || n == K_X1MOUSE
10733 || n == K_X1DRAG
10734 || n == K_X1RELEASE
10735 || n == K_X2MOUSE
10736 || n == K_X2DRAG
10737 || n == K_X2RELEASE
10738 || n == K_MOUSEDOWN
10739 || n == K_MOUSEUP)
10741 int row = mouse_row;
10742 int col = mouse_col;
10743 win_T *win;
10744 linenr_T lnum;
10745 # ifdef FEAT_WINDOWS
10746 win_T *wp;
10747 # endif
10748 int winnr = 1;
10750 if (row >= 0 && col >= 0)
10752 /* Find the window at the mouse coordinates and compute the
10753 * text position. */
10754 win = mouse_find_win(&row, &col);
10755 (void)mouse_comp_pos(win, &row, &col, &lnum);
10756 # ifdef FEAT_WINDOWS
10757 for (wp = firstwin; wp != win; wp = wp->w_next)
10758 ++winnr;
10759 # endif
10760 vimvars[VV_MOUSE_WIN].vv_nr = winnr;
10761 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
10762 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
10765 #endif
10770 * "getcharmod()" function
10772 static void
10773 f_getcharmod(argvars, rettv)
10774 typval_T *argvars UNUSED;
10775 typval_T *rettv;
10777 rettv->vval.v_number = mod_mask;
10781 * "getcmdline()" function
10783 static void
10784 f_getcmdline(argvars, rettv)
10785 typval_T *argvars UNUSED;
10786 typval_T *rettv;
10788 rettv->v_type = VAR_STRING;
10789 rettv->vval.v_string = get_cmdline_str();
10793 * "getcmdpos()" function
10795 static void
10796 f_getcmdpos(argvars, rettv)
10797 typval_T *argvars UNUSED;
10798 typval_T *rettv;
10800 rettv->vval.v_number = get_cmdline_pos() + 1;
10804 * "getcmdtype()" function
10806 static void
10807 f_getcmdtype(argvars, rettv)
10808 typval_T *argvars UNUSED;
10809 typval_T *rettv;
10811 rettv->v_type = VAR_STRING;
10812 rettv->vval.v_string = alloc(2);
10813 if (rettv->vval.v_string != NULL)
10815 rettv->vval.v_string[0] = get_cmdline_type();
10816 rettv->vval.v_string[1] = NUL;
10821 * "getcwd()" function
10823 static void
10824 f_getcwd(argvars, rettv)
10825 typval_T *argvars UNUSED;
10826 typval_T *rettv;
10828 char_u cwd[MAXPATHL];
10830 rettv->v_type = VAR_STRING;
10831 if (mch_dirname(cwd, MAXPATHL) == FAIL)
10832 rettv->vval.v_string = NULL;
10833 else
10835 rettv->vval.v_string = vim_strsave(cwd);
10836 #ifdef BACKSLASH_IN_FILENAME
10837 if (rettv->vval.v_string != NULL)
10838 slash_adjust(rettv->vval.v_string);
10839 #endif
10844 * "getfontname()" function
10846 static void
10847 f_getfontname(argvars, rettv)
10848 typval_T *argvars UNUSED;
10849 typval_T *rettv;
10851 rettv->v_type = VAR_STRING;
10852 rettv->vval.v_string = NULL;
10853 #ifdef FEAT_GUI
10854 if (gui.in_use)
10856 GuiFont font;
10857 char_u *name = NULL;
10859 if (argvars[0].v_type == VAR_UNKNOWN)
10861 /* Get the "Normal" font. Either the name saved by
10862 * hl_set_font_name() or from the font ID. */
10863 font = gui.norm_font;
10864 name = hl_get_font_name();
10866 else
10868 name = get_tv_string(&argvars[0]);
10869 if (STRCMP(name, "*") == 0) /* don't use font dialog */
10870 return;
10871 font = gui_mch_get_font(name, FALSE);
10872 if (font == NOFONT)
10873 return; /* Invalid font name, return empty string. */
10875 rettv->vval.v_string = gui_mch_get_fontname(font, name);
10876 if (argvars[0].v_type != VAR_UNKNOWN)
10877 gui_mch_free_font(font);
10879 #endif
10883 * "getfperm({fname})" function
10885 static void
10886 f_getfperm(argvars, rettv)
10887 typval_T *argvars;
10888 typval_T *rettv;
10890 char_u *fname;
10891 struct stat st;
10892 char_u *perm = NULL;
10893 char_u flags[] = "rwx";
10894 int i;
10896 fname = get_tv_string(&argvars[0]);
10898 rettv->v_type = VAR_STRING;
10899 if (mch_stat((char *)fname, &st) >= 0)
10901 perm = vim_strsave((char_u *)"---------");
10902 if (perm != NULL)
10904 for (i = 0; i < 9; i++)
10906 if (st.st_mode & (1 << (8 - i)))
10907 perm[i] = flags[i % 3];
10911 rettv->vval.v_string = perm;
10915 * "getfsize({fname})" function
10917 static void
10918 f_getfsize(argvars, rettv)
10919 typval_T *argvars;
10920 typval_T *rettv;
10922 char_u *fname;
10923 struct stat st;
10925 fname = get_tv_string(&argvars[0]);
10927 rettv->v_type = VAR_NUMBER;
10929 if (mch_stat((char *)fname, &st) >= 0)
10931 if (mch_isdir(fname))
10932 rettv->vval.v_number = 0;
10933 else
10935 rettv->vval.v_number = (varnumber_T)st.st_size;
10937 /* non-perfect check for overflow */
10938 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
10939 rettv->vval.v_number = -2;
10942 else
10943 rettv->vval.v_number = -1;
10947 * "getftime({fname})" function
10949 static void
10950 f_getftime(argvars, rettv)
10951 typval_T *argvars;
10952 typval_T *rettv;
10954 char_u *fname;
10955 struct stat st;
10957 fname = get_tv_string(&argvars[0]);
10959 if (mch_stat((char *)fname, &st) >= 0)
10960 rettv->vval.v_number = (varnumber_T)st.st_mtime;
10961 else
10962 rettv->vval.v_number = -1;
10966 * "getftype({fname})" function
10968 static void
10969 f_getftype(argvars, rettv)
10970 typval_T *argvars;
10971 typval_T *rettv;
10973 char_u *fname;
10974 struct stat st;
10975 char_u *type = NULL;
10976 char *t;
10978 fname = get_tv_string(&argvars[0]);
10980 rettv->v_type = VAR_STRING;
10981 if (mch_lstat((char *)fname, &st) >= 0)
10983 #ifdef S_ISREG
10984 if (S_ISREG(st.st_mode))
10985 t = "file";
10986 else if (S_ISDIR(st.st_mode))
10987 t = "dir";
10988 # ifdef S_ISLNK
10989 else if (S_ISLNK(st.st_mode))
10990 t = "link";
10991 # endif
10992 # ifdef S_ISBLK
10993 else if (S_ISBLK(st.st_mode))
10994 t = "bdev";
10995 # endif
10996 # ifdef S_ISCHR
10997 else if (S_ISCHR(st.st_mode))
10998 t = "cdev";
10999 # endif
11000 # ifdef S_ISFIFO
11001 else if (S_ISFIFO(st.st_mode))
11002 t = "fifo";
11003 # endif
11004 # ifdef S_ISSOCK
11005 else if (S_ISSOCK(st.st_mode))
11006 t = "fifo";
11007 # endif
11008 else
11009 t = "other";
11010 #else
11011 # ifdef S_IFMT
11012 switch (st.st_mode & S_IFMT)
11014 case S_IFREG: t = "file"; break;
11015 case S_IFDIR: t = "dir"; break;
11016 # ifdef S_IFLNK
11017 case S_IFLNK: t = "link"; break;
11018 # endif
11019 # ifdef S_IFBLK
11020 case S_IFBLK: t = "bdev"; break;
11021 # endif
11022 # ifdef S_IFCHR
11023 case S_IFCHR: t = "cdev"; break;
11024 # endif
11025 # ifdef S_IFIFO
11026 case S_IFIFO: t = "fifo"; break;
11027 # endif
11028 # ifdef S_IFSOCK
11029 case S_IFSOCK: t = "socket"; break;
11030 # endif
11031 default: t = "other";
11033 # else
11034 if (mch_isdir(fname))
11035 t = "dir";
11036 else
11037 t = "file";
11038 # endif
11039 #endif
11040 type = vim_strsave((char_u *)t);
11042 rettv->vval.v_string = type;
11046 * "getline(lnum, [end])" function
11048 static void
11049 f_getline(argvars, rettv)
11050 typval_T *argvars;
11051 typval_T *rettv;
11053 linenr_T lnum;
11054 linenr_T end;
11055 int retlist;
11057 lnum = get_tv_lnum(argvars);
11058 if (argvars[1].v_type == VAR_UNKNOWN)
11060 end = 0;
11061 retlist = FALSE;
11063 else
11065 end = get_tv_lnum(&argvars[1]);
11066 retlist = TRUE;
11069 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
11073 * "getmatches()" function
11075 static void
11076 f_getmatches(argvars, rettv)
11077 typval_T *argvars UNUSED;
11078 typval_T *rettv;
11080 #ifdef FEAT_SEARCH_EXTRA
11081 dict_T *dict;
11082 matchitem_T *cur = curwin->w_match_head;
11084 if (rettv_list_alloc(rettv) == OK)
11086 while (cur != NULL)
11088 dict = dict_alloc();
11089 if (dict == NULL)
11090 return;
11091 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
11092 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
11093 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
11094 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
11095 list_append_dict(rettv->vval.v_list, dict);
11096 cur = cur->next;
11099 #endif
11103 * "getpid()" function
11105 static void
11106 f_getpid(argvars, rettv)
11107 typval_T *argvars UNUSED;
11108 typval_T *rettv;
11110 rettv->vval.v_number = mch_get_pid();
11114 * "getpos(string)" function
11116 static void
11117 f_getpos(argvars, rettv)
11118 typval_T *argvars;
11119 typval_T *rettv;
11121 pos_T *fp;
11122 list_T *l;
11123 int fnum = -1;
11125 if (rettv_list_alloc(rettv) == OK)
11127 l = rettv->vval.v_list;
11128 fp = var2fpos(&argvars[0], TRUE, &fnum);
11129 if (fnum != -1)
11130 list_append_number(l, (varnumber_T)fnum);
11131 else
11132 list_append_number(l, (varnumber_T)0);
11133 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
11134 : (varnumber_T)0);
11135 list_append_number(l, (fp != NULL)
11136 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
11137 : (varnumber_T)0);
11138 list_append_number(l,
11139 #ifdef FEAT_VIRTUALEDIT
11140 (fp != NULL) ? (varnumber_T)fp->coladd :
11141 #endif
11142 (varnumber_T)0);
11144 else
11145 rettv->vval.v_number = FALSE;
11149 * "getqflist()" and "getloclist()" functions
11151 static void
11152 f_getqflist(argvars, rettv)
11153 typval_T *argvars UNUSED;
11154 typval_T *rettv UNUSED;
11156 #ifdef FEAT_QUICKFIX
11157 win_T *wp;
11158 #endif
11160 #ifdef FEAT_QUICKFIX
11161 if (rettv_list_alloc(rettv) == OK)
11163 wp = NULL;
11164 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
11166 wp = find_win_by_nr(&argvars[0], NULL);
11167 if (wp == NULL)
11168 return;
11171 (void)get_errorlist(wp, rettv->vval.v_list);
11173 #endif
11177 * "getreg()" function
11179 static void
11180 f_getreg(argvars, rettv)
11181 typval_T *argvars;
11182 typval_T *rettv;
11184 char_u *strregname;
11185 int regname;
11186 int arg2 = FALSE;
11187 int error = FALSE;
11189 if (argvars[0].v_type != VAR_UNKNOWN)
11191 strregname = get_tv_string_chk(&argvars[0]);
11192 error = strregname == NULL;
11193 if (argvars[1].v_type != VAR_UNKNOWN)
11194 arg2 = get_tv_number_chk(&argvars[1], &error);
11196 else
11197 strregname = vimvars[VV_REG].vv_str;
11198 regname = (strregname == NULL ? '"' : *strregname);
11199 if (regname == 0)
11200 regname = '"';
11202 rettv->v_type = VAR_STRING;
11203 rettv->vval.v_string = error ? NULL :
11204 get_reg_contents(regname, TRUE, arg2);
11208 * "getregtype()" function
11210 static void
11211 f_getregtype(argvars, rettv)
11212 typval_T *argvars;
11213 typval_T *rettv;
11215 char_u *strregname;
11216 int regname;
11217 char_u buf[NUMBUFLEN + 2];
11218 long reglen = 0;
11220 if (argvars[0].v_type != VAR_UNKNOWN)
11222 strregname = get_tv_string_chk(&argvars[0]);
11223 if (strregname == NULL) /* type error; errmsg already given */
11225 rettv->v_type = VAR_STRING;
11226 rettv->vval.v_string = NULL;
11227 return;
11230 else
11231 /* Default to v:register */
11232 strregname = vimvars[VV_REG].vv_str;
11234 regname = (strregname == NULL ? '"' : *strregname);
11235 if (regname == 0)
11236 regname = '"';
11238 buf[0] = NUL;
11239 buf[1] = NUL;
11240 switch (get_reg_type(regname, &reglen))
11242 case MLINE: buf[0] = 'V'; break;
11243 case MCHAR: buf[0] = 'v'; break;
11244 #ifdef FEAT_VISUAL
11245 case MBLOCK:
11246 buf[0] = Ctrl_V;
11247 sprintf((char *)buf + 1, "%ld", reglen + 1);
11248 break;
11249 #endif
11251 rettv->v_type = VAR_STRING;
11252 rettv->vval.v_string = vim_strsave(buf);
11256 * "gettabwinvar()" function
11258 static void
11259 f_gettabwinvar(argvars, rettv)
11260 typval_T *argvars;
11261 typval_T *rettv;
11263 getwinvar(argvars, rettv, 1);
11267 * "getwinposx()" function
11269 static void
11270 f_getwinposx(argvars, rettv)
11271 typval_T *argvars UNUSED;
11272 typval_T *rettv;
11274 rettv->vval.v_number = -1;
11275 #ifdef FEAT_GUI
11276 if (gui.in_use)
11278 int x, y;
11280 if (gui_mch_get_winpos(&x, &y) == OK)
11281 rettv->vval.v_number = x;
11283 #endif
11287 * "getwinposy()" function
11289 static void
11290 f_getwinposy(argvars, rettv)
11291 typval_T *argvars UNUSED;
11292 typval_T *rettv;
11294 rettv->vval.v_number = -1;
11295 #ifdef FEAT_GUI
11296 if (gui.in_use)
11298 int x, y;
11300 if (gui_mch_get_winpos(&x, &y) == OK)
11301 rettv->vval.v_number = y;
11303 #endif
11307 * Find window specified by "vp" in tabpage "tp".
11309 static win_T *
11310 find_win_by_nr(vp, tp)
11311 typval_T *vp;
11312 tabpage_T *tp; /* NULL for current tab page */
11314 #ifdef FEAT_WINDOWS
11315 win_T *wp;
11316 #endif
11317 int nr;
11319 nr = get_tv_number_chk(vp, NULL);
11321 #ifdef FEAT_WINDOWS
11322 if (nr < 0)
11323 return NULL;
11324 if (nr == 0)
11325 return curwin;
11327 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
11328 wp != NULL; wp = wp->w_next)
11329 if (--nr <= 0)
11330 break;
11331 return wp;
11332 #else
11333 if (nr == 0 || nr == 1)
11334 return curwin;
11335 return NULL;
11336 #endif
11340 * "getwinvar()" function
11342 static void
11343 f_getwinvar(argvars, rettv)
11344 typval_T *argvars;
11345 typval_T *rettv;
11347 getwinvar(argvars, rettv, 0);
11351 * getwinvar() and gettabwinvar()
11353 static void
11354 getwinvar(argvars, rettv, off)
11355 typval_T *argvars;
11356 typval_T *rettv;
11357 int off; /* 1 for gettabwinvar() */
11359 win_T *win, *oldcurwin;
11360 char_u *varname;
11361 dictitem_T *v;
11362 tabpage_T *tp;
11364 #ifdef FEAT_WINDOWS
11365 if (off == 1)
11366 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
11367 else
11368 tp = curtab;
11369 #endif
11370 win = find_win_by_nr(&argvars[off], tp);
11371 varname = get_tv_string_chk(&argvars[off + 1]);
11372 ++emsg_off;
11374 rettv->v_type = VAR_STRING;
11375 rettv->vval.v_string = NULL;
11377 if (win != NULL && varname != NULL)
11379 /* Set curwin to be our win, temporarily. Also set curbuf, so
11380 * that we can get buffer-local options. */
11381 oldcurwin = curwin;
11382 curwin = win;
11383 curbuf = win->w_buffer;
11385 if (*varname == '&') /* window-local-option */
11386 get_option_tv(&varname, rettv, 1);
11387 else
11389 if (*varname == NUL)
11390 /* let getwinvar({nr}, "") return the "w:" dictionary. The
11391 * scope prefix before the NUL byte is required by
11392 * find_var_in_ht(). */
11393 varname = (char_u *)"w:" + 2;
11394 /* look up the variable */
11395 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
11396 if (v != NULL)
11397 copy_tv(&v->di_tv, rettv);
11400 /* restore previous notion of curwin */
11401 curwin = oldcurwin;
11402 curbuf = curwin->w_buffer;
11405 --emsg_off;
11409 * "glob()" function
11411 static void
11412 f_glob(argvars, rettv)
11413 typval_T *argvars;
11414 typval_T *rettv;
11416 int flags = WILD_SILENT|WILD_USE_NL;
11417 expand_T xpc;
11418 int error = FALSE;
11420 /* When the optional second argument is non-zero, don't remove matches
11421 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11422 if (argvars[1].v_type != VAR_UNKNOWN
11423 && get_tv_number_chk(&argvars[1], &error))
11424 flags |= WILD_KEEP_ALL;
11425 rettv->v_type = VAR_STRING;
11426 if (!error)
11428 ExpandInit(&xpc);
11429 xpc.xp_context = EXPAND_FILES;
11430 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
11431 NULL, flags, WILD_ALL);
11433 else
11434 rettv->vval.v_string = NULL;
11438 * "globpath()" function
11440 static void
11441 f_globpath(argvars, rettv)
11442 typval_T *argvars;
11443 typval_T *rettv;
11445 int flags = 0;
11446 char_u buf1[NUMBUFLEN];
11447 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
11448 int error = FALSE;
11450 /* When the optional second argument is non-zero, don't remove matches
11451 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11452 if (argvars[2].v_type != VAR_UNKNOWN
11453 && get_tv_number_chk(&argvars[2], &error))
11454 flags |= WILD_KEEP_ALL;
11455 rettv->v_type = VAR_STRING;
11456 if (file == NULL || error)
11457 rettv->vval.v_string = NULL;
11458 else
11459 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file,
11460 flags);
11464 * "has()" function
11466 static void
11467 f_has(argvars, rettv)
11468 typval_T *argvars;
11469 typval_T *rettv;
11471 int i;
11472 char_u *name;
11473 int n = FALSE;
11474 static char *(has_list[]) =
11476 #ifdef AMIGA
11477 "amiga",
11478 # ifdef FEAT_ARP
11479 "arp",
11480 # endif
11481 #endif
11482 #ifdef __BEOS__
11483 "beos",
11484 #endif
11485 #ifdef MSDOS
11486 # ifdef DJGPP
11487 "dos32",
11488 # else
11489 "dos16",
11490 # endif
11491 #endif
11492 #ifdef MACOS
11493 "mac",
11494 #endif
11495 #if defined(MACOS_X_UNIX)
11496 "macunix",
11497 #endif
11498 #ifdef OS2
11499 "os2",
11500 #endif
11501 #ifdef __QNX__
11502 "qnx",
11503 #endif
11504 #ifdef RISCOS
11505 "riscos",
11506 #endif
11507 #ifdef UNIX
11508 "unix",
11509 #endif
11510 #ifdef VMS
11511 "vms",
11512 #endif
11513 #ifdef WIN16
11514 "win16",
11515 #endif
11516 #ifdef WIN32
11517 "win32",
11518 #endif
11519 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
11520 "win32unix",
11521 #endif
11522 #if defined(WIN64) || defined(_WIN64)
11523 "win64",
11524 #endif
11525 #ifdef EBCDIC
11526 "ebcdic",
11527 #endif
11528 #ifndef CASE_INSENSITIVE_FILENAME
11529 "fname_case",
11530 #endif
11531 #ifdef FEAT_ARABIC
11532 "arabic",
11533 #endif
11534 #ifdef FEAT_AUTOCMD
11535 "autocmd",
11536 #endif
11537 #ifdef FEAT_BEVAL
11538 "balloon_eval",
11539 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
11540 "balloon_multiline",
11541 # endif
11542 #endif
11543 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
11544 "builtin_terms",
11545 # ifdef ALL_BUILTIN_TCAPS
11546 "all_builtin_terms",
11547 # endif
11548 #endif
11549 #ifdef FEAT_BYTEOFF
11550 "byte_offset",
11551 #endif
11552 #ifdef FEAT_CINDENT
11553 "cindent",
11554 #endif
11555 #ifdef FEAT_CLIENTSERVER
11556 "clientserver",
11557 #endif
11558 #ifdef FEAT_CLIPBOARD
11559 "clipboard",
11560 #endif
11561 #ifdef FEAT_CMDL_COMPL
11562 "cmdline_compl",
11563 #endif
11564 #ifdef FEAT_CMDHIST
11565 "cmdline_hist",
11566 #endif
11567 #ifdef FEAT_COMMENTS
11568 "comments",
11569 #endif
11570 #ifdef FEAT_CRYPT
11571 "cryptv",
11572 #endif
11573 #ifdef FEAT_CSCOPE
11574 "cscope",
11575 #endif
11576 #ifdef CURSOR_SHAPE
11577 "cursorshape",
11578 #endif
11579 #ifdef DEBUG
11580 "debug",
11581 #endif
11582 #ifdef FEAT_CON_DIALOG
11583 "dialog_con",
11584 #endif
11585 #ifdef FEAT_GUI_DIALOG
11586 "dialog_gui",
11587 #endif
11588 #ifdef FEAT_DIFF
11589 "diff",
11590 #endif
11591 #ifdef FEAT_DIGRAPHS
11592 "digraphs",
11593 #endif
11594 #ifdef FEAT_DND
11595 "dnd",
11596 #endif
11597 #ifdef FEAT_EMACS_TAGS
11598 "emacs_tags",
11599 #endif
11600 "eval", /* always present, of course! */
11601 #ifdef FEAT_EX_EXTRA
11602 "ex_extra",
11603 #endif
11604 #ifdef FEAT_SEARCH_EXTRA
11605 "extra_search",
11606 #endif
11607 #ifdef FEAT_FKMAP
11608 "farsi",
11609 #endif
11610 #ifdef FEAT_SEARCHPATH
11611 "file_in_path",
11612 #endif
11613 #if defined(UNIX) && !defined(USE_SYSTEM)
11614 "filterpipe",
11615 #endif
11616 #ifdef FEAT_FIND_ID
11617 "find_in_path",
11618 #endif
11619 #ifdef FEAT_FLOAT
11620 "float",
11621 #endif
11622 #ifdef FEAT_FOLDING
11623 "folding",
11624 #endif
11625 #ifdef FEAT_FOOTER
11626 "footer",
11627 #endif
11628 #if !defined(USE_SYSTEM) && defined(UNIX)
11629 "fork",
11630 #endif
11631 #ifdef FEAT_GETTEXT
11632 "gettext",
11633 #endif
11634 #ifdef FEAT_GUI
11635 "gui",
11636 #endif
11637 #ifdef FEAT_GUI_ATHENA
11638 # ifdef FEAT_GUI_NEXTAW
11639 "gui_neXtaw",
11640 # else
11641 "gui_athena",
11642 # endif
11643 #endif
11644 #ifdef FEAT_GUI_GTK
11645 "gui_gtk",
11646 # ifdef HAVE_GTK2
11647 "gui_gtk2",
11648 # endif
11649 #endif
11650 #ifdef FEAT_GUI_GNOME
11651 "gui_gnome",
11652 #endif
11653 #ifdef FEAT_GUI_MAC
11654 "gui_mac",
11655 #endif
11656 #ifdef FEAT_GUI_MOTIF
11657 "gui_motif",
11658 #endif
11659 #ifdef FEAT_GUI_PHOTON
11660 "gui_photon",
11661 #endif
11662 #ifdef FEAT_GUI_W16
11663 "gui_win16",
11664 #endif
11665 #ifdef FEAT_GUI_W32
11666 "gui_win32",
11667 #endif
11668 #ifdef FEAT_HANGULIN
11669 "hangul_input",
11670 #endif
11671 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
11672 "iconv",
11673 #endif
11674 #ifdef FEAT_INS_EXPAND
11675 "insert_expand",
11676 #endif
11677 #ifdef FEAT_JUMPLIST
11678 "jumplist",
11679 #endif
11680 #ifdef FEAT_KEYMAP
11681 "keymap",
11682 #endif
11683 #ifdef FEAT_LANGMAP
11684 "langmap",
11685 #endif
11686 #ifdef FEAT_LIBCALL
11687 "libcall",
11688 #endif
11689 #ifdef FEAT_LINEBREAK
11690 "linebreak",
11691 #endif
11692 #ifdef FEAT_LISP
11693 "lispindent",
11694 #endif
11695 #ifdef FEAT_LISTCMDS
11696 "listcmds",
11697 #endif
11698 #ifdef FEAT_LOCALMAP
11699 "localmap",
11700 #endif
11701 #ifdef FEAT_MENU
11702 "menu",
11703 #endif
11704 #ifdef FEAT_SESSION
11705 "mksession",
11706 #endif
11707 #ifdef FEAT_MODIFY_FNAME
11708 "modify_fname",
11709 #endif
11710 #ifdef FEAT_MOUSE
11711 "mouse",
11712 #endif
11713 #ifdef FEAT_MOUSESHAPE
11714 "mouseshape",
11715 #endif
11716 #if defined(UNIX) || defined(VMS)
11717 # ifdef FEAT_MOUSE_DEC
11718 "mouse_dec",
11719 # endif
11720 # ifdef FEAT_MOUSE_GPM
11721 "mouse_gpm",
11722 # endif
11723 # ifdef FEAT_MOUSE_JSB
11724 "mouse_jsbterm",
11725 # endif
11726 # ifdef FEAT_MOUSE_NET
11727 "mouse_netterm",
11728 # endif
11729 # ifdef FEAT_MOUSE_PTERM
11730 "mouse_pterm",
11731 # endif
11732 # ifdef FEAT_SYSMOUSE
11733 "mouse_sysmouse",
11734 # endif
11735 # ifdef FEAT_MOUSE_XTERM
11736 "mouse_xterm",
11737 # endif
11738 #endif
11739 #ifdef FEAT_MBYTE
11740 "multi_byte",
11741 #endif
11742 #ifdef FEAT_MBYTE_IME
11743 "multi_byte_ime",
11744 #endif
11745 #ifdef FEAT_MULTI_LANG
11746 "multi_lang",
11747 #endif
11748 #ifdef FEAT_MZSCHEME
11749 #ifndef DYNAMIC_MZSCHEME
11750 "mzscheme",
11751 #endif
11752 #endif
11753 #ifdef FEAT_OLE
11754 "ole",
11755 #endif
11756 #ifdef FEAT_OSFILETYPE
11757 "osfiletype",
11758 #endif
11759 #ifdef FEAT_PATH_EXTRA
11760 "path_extra",
11761 #endif
11762 #ifdef FEAT_PERL
11763 #ifndef DYNAMIC_PERL
11764 "perl",
11765 #endif
11766 #endif
11767 #ifdef FEAT_PYTHON
11768 #ifndef DYNAMIC_PYTHON
11769 "python",
11770 #endif
11771 #endif
11772 #ifdef FEAT_POSTSCRIPT
11773 "postscript",
11774 #endif
11775 #ifdef FEAT_PRINTER
11776 "printer",
11777 #endif
11778 #ifdef FEAT_PROFILE
11779 "profile",
11780 #endif
11781 #ifdef FEAT_RELTIME
11782 "reltime",
11783 #endif
11784 #ifdef FEAT_QUICKFIX
11785 "quickfix",
11786 #endif
11787 #ifdef FEAT_RIGHTLEFT
11788 "rightleft",
11789 #endif
11790 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11791 "ruby",
11792 #endif
11793 #ifdef FEAT_SCROLLBIND
11794 "scrollbind",
11795 #endif
11796 #ifdef FEAT_CMDL_INFO
11797 "showcmd",
11798 "cmdline_info",
11799 #endif
11800 #ifdef FEAT_SIGNS
11801 "signs",
11802 #endif
11803 #ifdef FEAT_SMARTINDENT
11804 "smartindent",
11805 #endif
11806 #ifdef FEAT_SNIFF
11807 "sniff",
11808 #endif
11809 #ifdef STARTUPTIME
11810 "startuptime",
11811 #endif
11812 #ifdef FEAT_STL_OPT
11813 "statusline",
11814 #endif
11815 #ifdef FEAT_SUN_WORKSHOP
11816 "sun_workshop",
11817 #endif
11818 #ifdef FEAT_NETBEANS_INTG
11819 "netbeans_intg",
11820 #endif
11821 #ifdef FEAT_SPELL
11822 "spell",
11823 #endif
11824 #ifdef FEAT_SYN_HL
11825 "syntax",
11826 #endif
11827 #if defined(USE_SYSTEM) || !defined(UNIX)
11828 "system",
11829 #endif
11830 #ifdef FEAT_TAG_BINS
11831 "tag_binary",
11832 #endif
11833 #ifdef FEAT_TAG_OLDSTATIC
11834 "tag_old_static",
11835 #endif
11836 #ifdef FEAT_TAG_ANYWHITE
11837 "tag_any_white",
11838 #endif
11839 #ifdef FEAT_TCL
11840 # ifndef DYNAMIC_TCL
11841 "tcl",
11842 # endif
11843 #endif
11844 #ifdef TERMINFO
11845 "terminfo",
11846 #endif
11847 #ifdef FEAT_TERMRESPONSE
11848 "termresponse",
11849 #endif
11850 #ifdef FEAT_TEXTOBJ
11851 "textobjects",
11852 #endif
11853 #ifdef HAVE_TGETENT
11854 "tgetent",
11855 #endif
11856 #ifdef FEAT_TITLE
11857 "title",
11858 #endif
11859 #ifdef FEAT_TOOLBAR
11860 "toolbar",
11861 #endif
11862 #ifdef FEAT_USR_CMDS
11863 "user-commands", /* was accidentally included in 5.4 */
11864 "user_commands",
11865 #endif
11866 #ifdef FEAT_VIMINFO
11867 "viminfo",
11868 #endif
11869 #ifdef FEAT_VERTSPLIT
11870 "vertsplit",
11871 #endif
11872 #ifdef FEAT_VIRTUALEDIT
11873 "virtualedit",
11874 #endif
11875 #ifdef FEAT_VISUAL
11876 "visual",
11877 #endif
11878 #ifdef FEAT_VISUALEXTRA
11879 "visualextra",
11880 #endif
11881 #ifdef FEAT_VREPLACE
11882 "vreplace",
11883 #endif
11884 #ifdef FEAT_WILDIGN
11885 "wildignore",
11886 #endif
11887 #ifdef FEAT_WILDMENU
11888 "wildmenu",
11889 #endif
11890 #ifdef FEAT_WINDOWS
11891 "windows",
11892 #endif
11893 #ifdef FEAT_WAK
11894 "winaltkeys",
11895 #endif
11896 #ifdef FEAT_WRITEBACKUP
11897 "writebackup",
11898 #endif
11899 #ifdef FEAT_XIM
11900 "xim",
11901 #endif
11902 #ifdef FEAT_XFONTSET
11903 "xfontset",
11904 #endif
11905 #ifdef USE_XSMP
11906 "xsmp",
11907 #endif
11908 #ifdef USE_XSMP_INTERACT
11909 "xsmp_interact",
11910 #endif
11911 #ifdef FEAT_XCLIPBOARD
11912 "xterm_clipboard",
11913 #endif
11914 #ifdef FEAT_XTERM_SAVE
11915 "xterm_save",
11916 #endif
11917 #if defined(UNIX) && defined(FEAT_X11)
11918 "X11",
11919 #endif
11920 NULL
11923 name = get_tv_string(&argvars[0]);
11924 for (i = 0; has_list[i] != NULL; ++i)
11925 if (STRICMP(name, has_list[i]) == 0)
11927 n = TRUE;
11928 break;
11931 if (n == FALSE)
11933 if (STRNICMP(name, "patch", 5) == 0)
11934 n = has_patch(atoi((char *)name + 5));
11935 else if (STRICMP(name, "vim_starting") == 0)
11936 n = (starting != 0);
11937 #ifdef FEAT_MBYTE
11938 else if (STRICMP(name, "multi_byte_encoding") == 0)
11939 n = has_mbyte;
11940 #endif
11941 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
11942 else if (STRICMP(name, "balloon_multiline") == 0)
11943 n = multiline_balloon_available();
11944 #endif
11945 #ifdef DYNAMIC_TCL
11946 else if (STRICMP(name, "tcl") == 0)
11947 n = tcl_enabled(FALSE);
11948 #endif
11949 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
11950 else if (STRICMP(name, "iconv") == 0)
11951 n = iconv_enabled(FALSE);
11952 #endif
11953 #ifdef DYNAMIC_MZSCHEME
11954 else if (STRICMP(name, "mzscheme") == 0)
11955 n = mzscheme_enabled(FALSE);
11956 #endif
11957 #ifdef DYNAMIC_RUBY
11958 else if (STRICMP(name, "ruby") == 0)
11959 n = ruby_enabled(FALSE);
11960 #endif
11961 #ifdef DYNAMIC_PYTHON
11962 else if (STRICMP(name, "python") == 0)
11963 n = python_enabled(FALSE);
11964 #endif
11965 #ifdef DYNAMIC_PERL
11966 else if (STRICMP(name, "perl") == 0)
11967 n = perl_enabled(FALSE);
11968 #endif
11969 #ifdef FEAT_GUI
11970 else if (STRICMP(name, "gui_running") == 0)
11971 n = (gui.in_use || gui.starting);
11972 # ifdef FEAT_GUI_W32
11973 else if (STRICMP(name, "gui_win32s") == 0)
11974 n = gui_is_win32s();
11975 # endif
11976 # ifdef FEAT_BROWSE
11977 else if (STRICMP(name, "browse") == 0)
11978 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
11979 # endif
11980 #endif
11981 #ifdef FEAT_SYN_HL
11982 else if (STRICMP(name, "syntax_items") == 0)
11983 n = syntax_present(curbuf);
11984 #endif
11985 #if defined(WIN3264)
11986 else if (STRICMP(name, "win95") == 0)
11987 n = mch_windows95();
11988 #endif
11989 #ifdef FEAT_NETBEANS_INTG
11990 else if (STRICMP(name, "netbeans_enabled") == 0)
11991 n = usingNetbeans;
11992 #endif
11995 rettv->vval.v_number = n;
11999 * "has_key()" function
12001 static void
12002 f_has_key(argvars, rettv)
12003 typval_T *argvars;
12004 typval_T *rettv;
12006 if (argvars[0].v_type != VAR_DICT)
12008 EMSG(_(e_dictreq));
12009 return;
12011 if (argvars[0].vval.v_dict == NULL)
12012 return;
12014 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
12015 get_tv_string(&argvars[1]), -1) != NULL;
12019 * "haslocaldir()" function
12021 static void
12022 f_haslocaldir(argvars, rettv)
12023 typval_T *argvars UNUSED;
12024 typval_T *rettv;
12026 rettv->vval.v_number = (curwin->w_localdir != NULL);
12030 * "hasmapto()" function
12032 static void
12033 f_hasmapto(argvars, rettv)
12034 typval_T *argvars;
12035 typval_T *rettv;
12037 char_u *name;
12038 char_u *mode;
12039 char_u buf[NUMBUFLEN];
12040 int abbr = FALSE;
12042 name = get_tv_string(&argvars[0]);
12043 if (argvars[1].v_type == VAR_UNKNOWN)
12044 mode = (char_u *)"nvo";
12045 else
12047 mode = get_tv_string_buf(&argvars[1], buf);
12048 if (argvars[2].v_type != VAR_UNKNOWN)
12049 abbr = get_tv_number(&argvars[2]);
12052 if (map_to_exists(name, mode, abbr))
12053 rettv->vval.v_number = TRUE;
12054 else
12055 rettv->vval.v_number = FALSE;
12059 * "histadd()" function
12061 static void
12062 f_histadd(argvars, rettv)
12063 typval_T *argvars UNUSED;
12064 typval_T *rettv;
12066 #ifdef FEAT_CMDHIST
12067 int histype;
12068 char_u *str;
12069 char_u buf[NUMBUFLEN];
12070 #endif
12072 rettv->vval.v_number = FALSE;
12073 if (check_restricted() || check_secure())
12074 return;
12075 #ifdef FEAT_CMDHIST
12076 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12077 histype = str != NULL ? get_histtype(str) : -1;
12078 if (histype >= 0)
12080 str = get_tv_string_buf(&argvars[1], buf);
12081 if (*str != NUL)
12083 init_history();
12084 add_to_history(histype, str, FALSE, NUL);
12085 rettv->vval.v_number = TRUE;
12086 return;
12089 #endif
12093 * "histdel()" function
12095 static void
12096 f_histdel(argvars, rettv)
12097 typval_T *argvars UNUSED;
12098 typval_T *rettv UNUSED;
12100 #ifdef FEAT_CMDHIST
12101 int n;
12102 char_u buf[NUMBUFLEN];
12103 char_u *str;
12105 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12106 if (str == NULL)
12107 n = 0;
12108 else if (argvars[1].v_type == VAR_UNKNOWN)
12109 /* only one argument: clear entire history */
12110 n = clr_history(get_histtype(str));
12111 else if (argvars[1].v_type == VAR_NUMBER)
12112 /* index given: remove that entry */
12113 n = del_history_idx(get_histtype(str),
12114 (int)get_tv_number(&argvars[1]));
12115 else
12116 /* string given: remove all matching entries */
12117 n = del_history_entry(get_histtype(str),
12118 get_tv_string_buf(&argvars[1], buf));
12119 rettv->vval.v_number = n;
12120 #endif
12124 * "histget()" function
12126 static void
12127 f_histget(argvars, rettv)
12128 typval_T *argvars UNUSED;
12129 typval_T *rettv;
12131 #ifdef FEAT_CMDHIST
12132 int type;
12133 int idx;
12134 char_u *str;
12136 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12137 if (str == NULL)
12138 rettv->vval.v_string = NULL;
12139 else
12141 type = get_histtype(str);
12142 if (argvars[1].v_type == VAR_UNKNOWN)
12143 idx = get_history_idx(type);
12144 else
12145 idx = (int)get_tv_number_chk(&argvars[1], NULL);
12146 /* -1 on type error */
12147 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
12149 #else
12150 rettv->vval.v_string = NULL;
12151 #endif
12152 rettv->v_type = VAR_STRING;
12156 * "histnr()" function
12158 static void
12159 f_histnr(argvars, rettv)
12160 typval_T *argvars UNUSED;
12161 typval_T *rettv;
12163 int i;
12165 #ifdef FEAT_CMDHIST
12166 char_u *history = get_tv_string_chk(&argvars[0]);
12168 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
12169 if (i >= HIST_CMD && i < HIST_COUNT)
12170 i = get_history_idx(i);
12171 else
12172 #endif
12173 i = -1;
12174 rettv->vval.v_number = i;
12178 * "highlightID(name)" function
12180 static void
12181 f_hlID(argvars, rettv)
12182 typval_T *argvars;
12183 typval_T *rettv;
12185 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
12189 * "highlight_exists()" function
12191 static void
12192 f_hlexists(argvars, rettv)
12193 typval_T *argvars;
12194 typval_T *rettv;
12196 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
12200 * "hostname()" function
12202 static void
12203 f_hostname(argvars, rettv)
12204 typval_T *argvars UNUSED;
12205 typval_T *rettv;
12207 char_u hostname[256];
12209 mch_get_host_name(hostname, 256);
12210 rettv->v_type = VAR_STRING;
12211 rettv->vval.v_string = vim_strsave(hostname);
12215 * iconv() function
12217 static void
12218 f_iconv(argvars, rettv)
12219 typval_T *argvars UNUSED;
12220 typval_T *rettv;
12222 #ifdef FEAT_MBYTE
12223 char_u buf1[NUMBUFLEN];
12224 char_u buf2[NUMBUFLEN];
12225 char_u *from, *to, *str;
12226 vimconv_T vimconv;
12227 #endif
12229 rettv->v_type = VAR_STRING;
12230 rettv->vval.v_string = NULL;
12232 #ifdef FEAT_MBYTE
12233 str = get_tv_string(&argvars[0]);
12234 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
12235 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
12236 vimconv.vc_type = CONV_NONE;
12237 convert_setup(&vimconv, from, to);
12239 /* If the encodings are equal, no conversion needed. */
12240 if (vimconv.vc_type == CONV_NONE)
12241 rettv->vval.v_string = vim_strsave(str);
12242 else
12243 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
12245 convert_setup(&vimconv, NULL, NULL);
12246 vim_free(from);
12247 vim_free(to);
12248 #endif
12252 * "indent()" function
12254 static void
12255 f_indent(argvars, rettv)
12256 typval_T *argvars;
12257 typval_T *rettv;
12259 linenr_T lnum;
12261 lnum = get_tv_lnum(argvars);
12262 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12263 rettv->vval.v_number = get_indent_lnum(lnum);
12264 else
12265 rettv->vval.v_number = -1;
12269 * "index()" function
12271 static void
12272 f_index(argvars, rettv)
12273 typval_T *argvars;
12274 typval_T *rettv;
12276 list_T *l;
12277 listitem_T *item;
12278 long idx = 0;
12279 int ic = FALSE;
12281 rettv->vval.v_number = -1;
12282 if (argvars[0].v_type != VAR_LIST)
12284 EMSG(_(e_listreq));
12285 return;
12287 l = argvars[0].vval.v_list;
12288 if (l != NULL)
12290 item = l->lv_first;
12291 if (argvars[2].v_type != VAR_UNKNOWN)
12293 int error = FALSE;
12295 /* Start at specified item. Use the cached index that list_find()
12296 * sets, so that a negative number also works. */
12297 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
12298 idx = l->lv_idx;
12299 if (argvars[3].v_type != VAR_UNKNOWN)
12300 ic = get_tv_number_chk(&argvars[3], &error);
12301 if (error)
12302 item = NULL;
12305 for ( ; item != NULL; item = item->li_next, ++idx)
12306 if (tv_equal(&item->li_tv, &argvars[1], ic))
12308 rettv->vval.v_number = idx;
12309 break;
12314 static int inputsecret_flag = 0;
12316 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
12319 * This function is used by f_input() and f_inputdialog() functions. The third
12320 * argument to f_input() specifies the type of completion to use at the
12321 * prompt. The third argument to f_inputdialog() specifies the value to return
12322 * when the user cancels the prompt.
12324 static void
12325 get_user_input(argvars, rettv, inputdialog)
12326 typval_T *argvars;
12327 typval_T *rettv;
12328 int inputdialog;
12330 char_u *prompt = get_tv_string_chk(&argvars[0]);
12331 char_u *p = NULL;
12332 int c;
12333 char_u buf[NUMBUFLEN];
12334 int cmd_silent_save = cmd_silent;
12335 char_u *defstr = (char_u *)"";
12336 int xp_type = EXPAND_NOTHING;
12337 char_u *xp_arg = NULL;
12339 rettv->v_type = VAR_STRING;
12340 rettv->vval.v_string = NULL;
12342 #ifdef NO_CONSOLE_INPUT
12343 /* While starting up, there is no place to enter text. */
12344 if (no_console_input())
12345 return;
12346 #endif
12348 cmd_silent = FALSE; /* Want to see the prompt. */
12349 if (prompt != NULL)
12351 /* Only the part of the message after the last NL is considered as
12352 * prompt for the command line */
12353 p = vim_strrchr(prompt, '\n');
12354 if (p == NULL)
12355 p = prompt;
12356 else
12358 ++p;
12359 c = *p;
12360 *p = NUL;
12361 msg_start();
12362 msg_clr_eos();
12363 msg_puts_attr(prompt, echo_attr);
12364 msg_didout = FALSE;
12365 msg_starthere();
12366 *p = c;
12368 cmdline_row = msg_row;
12370 if (argvars[1].v_type != VAR_UNKNOWN)
12372 defstr = get_tv_string_buf_chk(&argvars[1], buf);
12373 if (defstr != NULL)
12374 stuffReadbuffSpec(defstr);
12376 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
12378 char_u *xp_name;
12379 int xp_namelen;
12380 long argt;
12382 rettv->vval.v_string = NULL;
12384 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
12385 if (xp_name == NULL)
12386 return;
12388 xp_namelen = (int)STRLEN(xp_name);
12390 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
12391 &xp_arg) == FAIL)
12392 return;
12396 if (defstr != NULL)
12397 rettv->vval.v_string =
12398 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
12399 xp_type, xp_arg);
12401 vim_free(xp_arg);
12403 /* since the user typed this, no need to wait for return */
12404 need_wait_return = FALSE;
12405 msg_didout = FALSE;
12407 cmd_silent = cmd_silent_save;
12411 * "input()" function
12412 * Also handles inputsecret() when inputsecret is set.
12414 static void
12415 f_input(argvars, rettv)
12416 typval_T *argvars;
12417 typval_T *rettv;
12419 get_user_input(argvars, rettv, FALSE);
12423 * "inputdialog()" function
12425 static void
12426 f_inputdialog(argvars, rettv)
12427 typval_T *argvars;
12428 typval_T *rettv;
12430 #if defined(FEAT_GUI_TEXTDIALOG)
12431 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
12432 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
12434 char_u *message;
12435 char_u buf[NUMBUFLEN];
12436 char_u *defstr = (char_u *)"";
12438 message = get_tv_string_chk(&argvars[0]);
12439 if (argvars[1].v_type != VAR_UNKNOWN
12440 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
12441 vim_strncpy(IObuff, defstr, IOSIZE - 1);
12442 else
12443 IObuff[0] = NUL;
12444 if (message != NULL && defstr != NULL
12445 && do_dialog(VIM_QUESTION, NULL, message,
12446 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
12447 rettv->vval.v_string = vim_strsave(IObuff);
12448 else
12450 if (message != NULL && defstr != NULL
12451 && argvars[1].v_type != VAR_UNKNOWN
12452 && argvars[2].v_type != VAR_UNKNOWN)
12453 rettv->vval.v_string = vim_strsave(
12454 get_tv_string_buf(&argvars[2], buf));
12455 else
12456 rettv->vval.v_string = NULL;
12458 rettv->v_type = VAR_STRING;
12460 else
12461 #endif
12462 get_user_input(argvars, rettv, TRUE);
12466 * "inputlist()" function
12468 static void
12469 f_inputlist(argvars, rettv)
12470 typval_T *argvars;
12471 typval_T *rettv;
12473 listitem_T *li;
12474 int selected;
12475 int mouse_used;
12477 #ifdef NO_CONSOLE_INPUT
12478 /* While starting up, there is no place to enter text. */
12479 if (no_console_input())
12480 return;
12481 #endif
12482 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
12484 EMSG2(_(e_listarg), "inputlist()");
12485 return;
12488 msg_start();
12489 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
12490 lines_left = Rows; /* avoid more prompt */
12491 msg_scroll = TRUE;
12492 msg_clr_eos();
12494 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
12496 msg_puts(get_tv_string(&li->li_tv));
12497 msg_putchar('\n');
12500 /* Ask for choice. */
12501 selected = prompt_for_number(&mouse_used);
12502 if (mouse_used)
12503 selected -= lines_left;
12505 rettv->vval.v_number = selected;
12509 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
12512 * "inputrestore()" function
12514 static void
12515 f_inputrestore(argvars, rettv)
12516 typval_T *argvars UNUSED;
12517 typval_T *rettv;
12519 if (ga_userinput.ga_len > 0)
12521 --ga_userinput.ga_len;
12522 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
12523 + ga_userinput.ga_len);
12524 /* default return is zero == OK */
12526 else if (p_verbose > 1)
12528 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
12529 rettv->vval.v_number = 1; /* Failed */
12534 * "inputsave()" function
12536 static void
12537 f_inputsave(argvars, rettv)
12538 typval_T *argvars UNUSED;
12539 typval_T *rettv;
12541 /* Add an entry to the stack of typeahead storage. */
12542 if (ga_grow(&ga_userinput, 1) == OK)
12544 save_typeahead((tasave_T *)(ga_userinput.ga_data)
12545 + ga_userinput.ga_len);
12546 ++ga_userinput.ga_len;
12547 /* default return is zero == OK */
12549 else
12550 rettv->vval.v_number = 1; /* Failed */
12554 * "inputsecret()" function
12556 static void
12557 f_inputsecret(argvars, rettv)
12558 typval_T *argvars;
12559 typval_T *rettv;
12561 ++cmdline_star;
12562 ++inputsecret_flag;
12563 f_input(argvars, rettv);
12564 --cmdline_star;
12565 --inputsecret_flag;
12569 * "insert()" function
12571 static void
12572 f_insert(argvars, rettv)
12573 typval_T *argvars;
12574 typval_T *rettv;
12576 long before = 0;
12577 listitem_T *item;
12578 list_T *l;
12579 int error = FALSE;
12581 if (argvars[0].v_type != VAR_LIST)
12582 EMSG2(_(e_listarg), "insert()");
12583 else if ((l = argvars[0].vval.v_list) != NULL
12584 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
12586 if (argvars[2].v_type != VAR_UNKNOWN)
12587 before = get_tv_number_chk(&argvars[2], &error);
12588 if (error)
12589 return; /* type error; errmsg already given */
12591 if (before == l->lv_len)
12592 item = NULL;
12593 else
12595 item = list_find(l, before);
12596 if (item == NULL)
12598 EMSGN(_(e_listidx), before);
12599 l = NULL;
12602 if (l != NULL)
12604 list_insert_tv(l, &argvars[1], item);
12605 copy_tv(&argvars[0], rettv);
12611 * "isdirectory()" function
12613 static void
12614 f_isdirectory(argvars, rettv)
12615 typval_T *argvars;
12616 typval_T *rettv;
12618 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
12622 * "islocked()" function
12624 static void
12625 f_islocked(argvars, rettv)
12626 typval_T *argvars;
12627 typval_T *rettv;
12629 lval_T lv;
12630 char_u *end;
12631 dictitem_T *di;
12633 rettv->vval.v_number = -1;
12634 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
12635 FNE_CHECK_START);
12636 if (end != NULL && lv.ll_name != NULL)
12638 if (*end != NUL)
12639 EMSG(_(e_trailing));
12640 else
12642 if (lv.ll_tv == NULL)
12644 if (check_changedtick(lv.ll_name))
12645 rettv->vval.v_number = 1; /* always locked */
12646 else
12648 di = find_var(lv.ll_name, NULL);
12649 if (di != NULL)
12651 /* Consider a variable locked when:
12652 * 1. the variable itself is locked
12653 * 2. the value of the variable is locked.
12654 * 3. the List or Dict value is locked.
12656 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
12657 || tv_islocked(&di->di_tv));
12661 else if (lv.ll_range)
12662 EMSG(_("E786: Range not allowed"));
12663 else if (lv.ll_newkey != NULL)
12664 EMSG2(_(e_dictkey), lv.ll_newkey);
12665 else if (lv.ll_list != NULL)
12666 /* List item. */
12667 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
12668 else
12669 /* Dictionary item. */
12670 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
12674 clear_lval(&lv);
12677 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
12680 * Turn a dict into a list:
12681 * "what" == 0: list of keys
12682 * "what" == 1: list of values
12683 * "what" == 2: list of items
12685 static void
12686 dict_list(argvars, rettv, what)
12687 typval_T *argvars;
12688 typval_T *rettv;
12689 int what;
12691 list_T *l2;
12692 dictitem_T *di;
12693 hashitem_T *hi;
12694 listitem_T *li;
12695 listitem_T *li2;
12696 dict_T *d;
12697 int todo;
12699 if (argvars[0].v_type != VAR_DICT)
12701 EMSG(_(e_dictreq));
12702 return;
12704 if ((d = argvars[0].vval.v_dict) == NULL)
12705 return;
12707 if (rettv_list_alloc(rettv) == FAIL)
12708 return;
12710 todo = (int)d->dv_hashtab.ht_used;
12711 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12713 if (!HASHITEM_EMPTY(hi))
12715 --todo;
12716 di = HI2DI(hi);
12718 li = listitem_alloc();
12719 if (li == NULL)
12720 break;
12721 list_append(rettv->vval.v_list, li);
12723 if (what == 0)
12725 /* keys() */
12726 li->li_tv.v_type = VAR_STRING;
12727 li->li_tv.v_lock = 0;
12728 li->li_tv.vval.v_string = vim_strsave(di->di_key);
12730 else if (what == 1)
12732 /* values() */
12733 copy_tv(&di->di_tv, &li->li_tv);
12735 else
12737 /* items() */
12738 l2 = list_alloc();
12739 li->li_tv.v_type = VAR_LIST;
12740 li->li_tv.v_lock = 0;
12741 li->li_tv.vval.v_list = l2;
12742 if (l2 == NULL)
12743 break;
12744 ++l2->lv_refcount;
12746 li2 = listitem_alloc();
12747 if (li2 == NULL)
12748 break;
12749 list_append(l2, li2);
12750 li2->li_tv.v_type = VAR_STRING;
12751 li2->li_tv.v_lock = 0;
12752 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12754 li2 = listitem_alloc();
12755 if (li2 == NULL)
12756 break;
12757 list_append(l2, li2);
12758 copy_tv(&di->di_tv, &li2->li_tv);
12765 * "items(dict)" function
12767 static void
12768 f_items(argvars, rettv)
12769 typval_T *argvars;
12770 typval_T *rettv;
12772 dict_list(argvars, rettv, 2);
12776 * "join()" function
12778 static void
12779 f_join(argvars, rettv)
12780 typval_T *argvars;
12781 typval_T *rettv;
12783 garray_T ga;
12784 char_u *sep;
12786 if (argvars[0].v_type != VAR_LIST)
12788 EMSG(_(e_listreq));
12789 return;
12791 if (argvars[0].vval.v_list == NULL)
12792 return;
12793 if (argvars[1].v_type == VAR_UNKNOWN)
12794 sep = (char_u *)" ";
12795 else
12796 sep = get_tv_string_chk(&argvars[1]);
12798 rettv->v_type = VAR_STRING;
12800 if (sep != NULL)
12802 ga_init2(&ga, (int)sizeof(char), 80);
12803 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12804 ga_append(&ga, NUL);
12805 rettv->vval.v_string = (char_u *)ga.ga_data;
12807 else
12808 rettv->vval.v_string = NULL;
12812 * "keys()" function
12814 static void
12815 f_keys(argvars, rettv)
12816 typval_T *argvars;
12817 typval_T *rettv;
12819 dict_list(argvars, rettv, 0);
12823 * "last_buffer_nr()" function.
12825 static void
12826 f_last_buffer_nr(argvars, rettv)
12827 typval_T *argvars UNUSED;
12828 typval_T *rettv;
12830 int n = 0;
12831 buf_T *buf;
12833 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12834 if (n < buf->b_fnum)
12835 n = buf->b_fnum;
12837 rettv->vval.v_number = n;
12841 * "len()" function
12843 static void
12844 f_len(argvars, rettv)
12845 typval_T *argvars;
12846 typval_T *rettv;
12848 switch (argvars[0].v_type)
12850 case VAR_STRING:
12851 case VAR_NUMBER:
12852 rettv->vval.v_number = (varnumber_T)STRLEN(
12853 get_tv_string(&argvars[0]));
12854 break;
12855 case VAR_LIST:
12856 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
12857 break;
12858 case VAR_DICT:
12859 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
12860 break;
12861 default:
12862 EMSG(_("E701: Invalid type for len()"));
12863 break;
12867 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
12869 static void
12870 libcall_common(argvars, rettv, type)
12871 typval_T *argvars;
12872 typval_T *rettv;
12873 int type;
12875 #ifdef FEAT_LIBCALL
12876 char_u *string_in;
12877 char_u **string_result;
12878 int nr_result;
12879 #endif
12881 rettv->v_type = type;
12882 if (type != VAR_NUMBER)
12883 rettv->vval.v_string = NULL;
12885 if (check_restricted() || check_secure())
12886 return;
12888 #ifdef FEAT_LIBCALL
12889 /* The first two args must be strings, otherwise its meaningless */
12890 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
12892 string_in = NULL;
12893 if (argvars[2].v_type == VAR_STRING)
12894 string_in = argvars[2].vval.v_string;
12895 if (type == VAR_NUMBER)
12896 string_result = NULL;
12897 else
12898 string_result = &rettv->vval.v_string;
12899 if (mch_libcall(argvars[0].vval.v_string,
12900 argvars[1].vval.v_string,
12901 string_in,
12902 argvars[2].vval.v_number,
12903 string_result,
12904 &nr_result) == OK
12905 && type == VAR_NUMBER)
12906 rettv->vval.v_number = nr_result;
12908 #endif
12912 * "libcall()" function
12914 static void
12915 f_libcall(argvars, rettv)
12916 typval_T *argvars;
12917 typval_T *rettv;
12919 libcall_common(argvars, rettv, VAR_STRING);
12923 * "libcallnr()" function
12925 static void
12926 f_libcallnr(argvars, rettv)
12927 typval_T *argvars;
12928 typval_T *rettv;
12930 libcall_common(argvars, rettv, VAR_NUMBER);
12934 * "line(string)" function
12936 static void
12937 f_line(argvars, rettv)
12938 typval_T *argvars;
12939 typval_T *rettv;
12941 linenr_T lnum = 0;
12942 pos_T *fp;
12943 int fnum;
12945 fp = var2fpos(&argvars[0], TRUE, &fnum);
12946 if (fp != NULL)
12947 lnum = fp->lnum;
12948 rettv->vval.v_number = lnum;
12952 * "line2byte(lnum)" function
12954 static void
12955 f_line2byte(argvars, rettv)
12956 typval_T *argvars UNUSED;
12957 typval_T *rettv;
12959 #ifndef FEAT_BYTEOFF
12960 rettv->vval.v_number = -1;
12961 #else
12962 linenr_T lnum;
12964 lnum = get_tv_lnum(argvars);
12965 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
12966 rettv->vval.v_number = -1;
12967 else
12968 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
12969 if (rettv->vval.v_number >= 0)
12970 ++rettv->vval.v_number;
12971 #endif
12975 * "lispindent(lnum)" function
12977 static void
12978 f_lispindent(argvars, rettv)
12979 typval_T *argvars;
12980 typval_T *rettv;
12982 #ifdef FEAT_LISP
12983 pos_T pos;
12984 linenr_T lnum;
12986 pos = curwin->w_cursor;
12987 lnum = get_tv_lnum(argvars);
12988 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12990 curwin->w_cursor.lnum = lnum;
12991 rettv->vval.v_number = get_lisp_indent();
12992 curwin->w_cursor = pos;
12994 else
12995 #endif
12996 rettv->vval.v_number = -1;
13000 * "localtime()" function
13002 static void
13003 f_localtime(argvars, rettv)
13004 typval_T *argvars UNUSED;
13005 typval_T *rettv;
13007 rettv->vval.v_number = (varnumber_T)time(NULL);
13010 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
13012 static void
13013 get_maparg(argvars, rettv, exact)
13014 typval_T *argvars;
13015 typval_T *rettv;
13016 int exact;
13018 char_u *keys;
13019 char_u *which;
13020 char_u buf[NUMBUFLEN];
13021 char_u *keys_buf = NULL;
13022 char_u *rhs;
13023 int mode;
13024 garray_T ga;
13025 int abbr = FALSE;
13027 /* return empty string for failure */
13028 rettv->v_type = VAR_STRING;
13029 rettv->vval.v_string = NULL;
13031 keys = get_tv_string(&argvars[0]);
13032 if (*keys == NUL)
13033 return;
13035 if (argvars[1].v_type != VAR_UNKNOWN)
13037 which = get_tv_string_buf_chk(&argvars[1], buf);
13038 if (argvars[2].v_type != VAR_UNKNOWN)
13039 abbr = get_tv_number(&argvars[2]);
13041 else
13042 which = (char_u *)"";
13043 if (which == NULL)
13044 return;
13046 mode = get_map_mode(&which, 0);
13048 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
13049 rhs = check_map(keys, mode, exact, FALSE, abbr);
13050 vim_free(keys_buf);
13051 if (rhs != NULL)
13053 ga_init(&ga);
13054 ga.ga_itemsize = 1;
13055 ga.ga_growsize = 40;
13057 while (*rhs != NUL)
13058 ga_concat(&ga, str2special(&rhs, FALSE));
13060 ga_append(&ga, NUL);
13061 rettv->vval.v_string = (char_u *)ga.ga_data;
13065 #ifdef FEAT_FLOAT
13067 * "log10()" function
13069 static void
13070 f_log10(argvars, rettv)
13071 typval_T *argvars;
13072 typval_T *rettv;
13074 float_T f;
13076 rettv->v_type = VAR_FLOAT;
13077 if (get_float_arg(argvars, &f) == OK)
13078 rettv->vval.v_float = log10(f);
13079 else
13080 rettv->vval.v_float = 0.0;
13082 #endif
13085 * "map()" function
13087 static void
13088 f_map(argvars, rettv)
13089 typval_T *argvars;
13090 typval_T *rettv;
13092 filter_map(argvars, rettv, TRUE);
13096 * "maparg()" function
13098 static void
13099 f_maparg(argvars, rettv)
13100 typval_T *argvars;
13101 typval_T *rettv;
13103 get_maparg(argvars, rettv, TRUE);
13107 * "mapcheck()" function
13109 static void
13110 f_mapcheck(argvars, rettv)
13111 typval_T *argvars;
13112 typval_T *rettv;
13114 get_maparg(argvars, rettv, FALSE);
13117 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
13119 static void
13120 find_some_match(argvars, rettv, type)
13121 typval_T *argvars;
13122 typval_T *rettv;
13123 int type;
13125 char_u *str = NULL;
13126 char_u *expr = NULL;
13127 char_u *pat;
13128 regmatch_T regmatch;
13129 char_u patbuf[NUMBUFLEN];
13130 char_u strbuf[NUMBUFLEN];
13131 char_u *save_cpo;
13132 long start = 0;
13133 long nth = 1;
13134 colnr_T startcol = 0;
13135 int match = 0;
13136 list_T *l = NULL;
13137 listitem_T *li = NULL;
13138 long idx = 0;
13139 char_u *tofree = NULL;
13141 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
13142 save_cpo = p_cpo;
13143 p_cpo = (char_u *)"";
13145 rettv->vval.v_number = -1;
13146 if (type == 3)
13148 /* return empty list when there are no matches */
13149 if (rettv_list_alloc(rettv) == FAIL)
13150 goto theend;
13152 else if (type == 2)
13154 rettv->v_type = VAR_STRING;
13155 rettv->vval.v_string = NULL;
13158 if (argvars[0].v_type == VAR_LIST)
13160 if ((l = argvars[0].vval.v_list) == NULL)
13161 goto theend;
13162 li = l->lv_first;
13164 else
13165 expr = str = get_tv_string(&argvars[0]);
13167 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
13168 if (pat == NULL)
13169 goto theend;
13171 if (argvars[2].v_type != VAR_UNKNOWN)
13173 int error = FALSE;
13175 start = get_tv_number_chk(&argvars[2], &error);
13176 if (error)
13177 goto theend;
13178 if (l != NULL)
13180 li = list_find(l, start);
13181 if (li == NULL)
13182 goto theend;
13183 idx = l->lv_idx; /* use the cached index */
13185 else
13187 if (start < 0)
13188 start = 0;
13189 if (start > (long)STRLEN(str))
13190 goto theend;
13191 /* When "count" argument is there ignore matches before "start",
13192 * otherwise skip part of the string. Differs when pattern is "^"
13193 * or "\<". */
13194 if (argvars[3].v_type != VAR_UNKNOWN)
13195 startcol = start;
13196 else
13197 str += start;
13200 if (argvars[3].v_type != VAR_UNKNOWN)
13201 nth = get_tv_number_chk(&argvars[3], &error);
13202 if (error)
13203 goto theend;
13206 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
13207 if (regmatch.regprog != NULL)
13209 regmatch.rm_ic = p_ic;
13211 for (;;)
13213 if (l != NULL)
13215 if (li == NULL)
13217 match = FALSE;
13218 break;
13220 vim_free(tofree);
13221 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
13222 if (str == NULL)
13223 break;
13226 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
13228 if (match && --nth <= 0)
13229 break;
13230 if (l == NULL && !match)
13231 break;
13233 /* Advance to just after the match. */
13234 if (l != NULL)
13236 li = li->li_next;
13237 ++idx;
13239 else
13241 #ifdef FEAT_MBYTE
13242 startcol = (colnr_T)(regmatch.startp[0]
13243 + (*mb_ptr2len)(regmatch.startp[0]) - str);
13244 #else
13245 startcol = regmatch.startp[0] + 1 - str;
13246 #endif
13250 if (match)
13252 if (type == 3)
13254 int i;
13256 /* return list with matched string and submatches */
13257 for (i = 0; i < NSUBEXP; ++i)
13259 if (regmatch.endp[i] == NULL)
13261 if (list_append_string(rettv->vval.v_list,
13262 (char_u *)"", 0) == FAIL)
13263 break;
13265 else if (list_append_string(rettv->vval.v_list,
13266 regmatch.startp[i],
13267 (int)(regmatch.endp[i] - regmatch.startp[i]))
13268 == FAIL)
13269 break;
13272 else if (type == 2)
13274 /* return matched string */
13275 if (l != NULL)
13276 copy_tv(&li->li_tv, rettv);
13277 else
13278 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
13279 (int)(regmatch.endp[0] - regmatch.startp[0]));
13281 else if (l != NULL)
13282 rettv->vval.v_number = idx;
13283 else
13285 if (type != 0)
13286 rettv->vval.v_number =
13287 (varnumber_T)(regmatch.startp[0] - str);
13288 else
13289 rettv->vval.v_number =
13290 (varnumber_T)(regmatch.endp[0] - str);
13291 rettv->vval.v_number += (varnumber_T)(str - expr);
13294 vim_free(regmatch.regprog);
13297 theend:
13298 vim_free(tofree);
13299 p_cpo = save_cpo;
13303 * "match()" function
13305 static void
13306 f_match(argvars, rettv)
13307 typval_T *argvars;
13308 typval_T *rettv;
13310 find_some_match(argvars, rettv, 1);
13314 * "matchadd()" function
13316 static void
13317 f_matchadd(argvars, rettv)
13318 typval_T *argvars;
13319 typval_T *rettv;
13321 #ifdef FEAT_SEARCH_EXTRA
13322 char_u buf[NUMBUFLEN];
13323 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
13324 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
13325 int prio = 10; /* default priority */
13326 int id = -1;
13327 int error = FALSE;
13329 rettv->vval.v_number = -1;
13331 if (grp == NULL || pat == NULL)
13332 return;
13333 if (argvars[2].v_type != VAR_UNKNOWN)
13335 prio = get_tv_number_chk(&argvars[2], &error);
13336 if (argvars[3].v_type != VAR_UNKNOWN)
13337 id = get_tv_number_chk(&argvars[3], &error);
13339 if (error == TRUE)
13340 return;
13341 if (id >= 1 && id <= 3)
13343 EMSGN("E798: ID is reserved for \":match\": %ld", id);
13344 return;
13347 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
13348 #endif
13352 * "matcharg()" function
13354 static void
13355 f_matcharg(argvars, rettv)
13356 typval_T *argvars;
13357 typval_T *rettv;
13359 if (rettv_list_alloc(rettv) == OK)
13361 #ifdef FEAT_SEARCH_EXTRA
13362 int id = get_tv_number(&argvars[0]);
13363 matchitem_T *m;
13365 if (id >= 1 && id <= 3)
13367 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
13369 list_append_string(rettv->vval.v_list,
13370 syn_id2name(m->hlg_id), -1);
13371 list_append_string(rettv->vval.v_list, m->pattern, -1);
13373 else
13375 list_append_string(rettv->vval.v_list, NUL, -1);
13376 list_append_string(rettv->vval.v_list, NUL, -1);
13379 #endif
13384 * "matchdelete()" function
13386 static void
13387 f_matchdelete(argvars, rettv)
13388 typval_T *argvars;
13389 typval_T *rettv;
13391 #ifdef FEAT_SEARCH_EXTRA
13392 rettv->vval.v_number = match_delete(curwin,
13393 (int)get_tv_number(&argvars[0]), TRUE);
13394 #endif
13398 * "matchend()" function
13400 static void
13401 f_matchend(argvars, rettv)
13402 typval_T *argvars;
13403 typval_T *rettv;
13405 find_some_match(argvars, rettv, 0);
13409 * "matchlist()" function
13411 static void
13412 f_matchlist(argvars, rettv)
13413 typval_T *argvars;
13414 typval_T *rettv;
13416 find_some_match(argvars, rettv, 3);
13420 * "matchstr()" function
13422 static void
13423 f_matchstr(argvars, rettv)
13424 typval_T *argvars;
13425 typval_T *rettv;
13427 find_some_match(argvars, rettv, 2);
13430 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
13432 static void
13433 max_min(argvars, rettv, domax)
13434 typval_T *argvars;
13435 typval_T *rettv;
13436 int domax;
13438 long n = 0;
13439 long i;
13440 int error = FALSE;
13442 if (argvars[0].v_type == VAR_LIST)
13444 list_T *l;
13445 listitem_T *li;
13447 l = argvars[0].vval.v_list;
13448 if (l != NULL)
13450 li = l->lv_first;
13451 if (li != NULL)
13453 n = get_tv_number_chk(&li->li_tv, &error);
13454 for (;;)
13456 li = li->li_next;
13457 if (li == NULL)
13458 break;
13459 i = get_tv_number_chk(&li->li_tv, &error);
13460 if (domax ? i > n : i < n)
13461 n = i;
13466 else if (argvars[0].v_type == VAR_DICT)
13468 dict_T *d;
13469 int first = TRUE;
13470 hashitem_T *hi;
13471 int todo;
13473 d = argvars[0].vval.v_dict;
13474 if (d != NULL)
13476 todo = (int)d->dv_hashtab.ht_used;
13477 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13479 if (!HASHITEM_EMPTY(hi))
13481 --todo;
13482 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
13483 if (first)
13485 n = i;
13486 first = FALSE;
13488 else if (domax ? i > n : i < n)
13489 n = i;
13494 else
13495 EMSG(_(e_listdictarg));
13496 rettv->vval.v_number = error ? 0 : n;
13500 * "max()" function
13502 static void
13503 f_max(argvars, rettv)
13504 typval_T *argvars;
13505 typval_T *rettv;
13507 max_min(argvars, rettv, TRUE);
13511 * "min()" function
13513 static void
13514 f_min(argvars, rettv)
13515 typval_T *argvars;
13516 typval_T *rettv;
13518 max_min(argvars, rettv, FALSE);
13521 static int mkdir_recurse __ARGS((char_u *dir, int prot));
13524 * Create the directory in which "dir" is located, and higher levels when
13525 * needed.
13527 static int
13528 mkdir_recurse(dir, prot)
13529 char_u *dir;
13530 int prot;
13532 char_u *p;
13533 char_u *updir;
13534 int r = FAIL;
13536 /* Get end of directory name in "dir".
13537 * We're done when it's "/" or "c:/". */
13538 p = gettail_sep(dir);
13539 if (p <= get_past_head(dir))
13540 return OK;
13542 /* If the directory exists we're done. Otherwise: create it.*/
13543 updir = vim_strnsave(dir, (int)(p - dir));
13544 if (updir == NULL)
13545 return FAIL;
13546 if (mch_isdir(updir))
13547 r = OK;
13548 else if (mkdir_recurse(updir, prot) == OK)
13549 r = vim_mkdir_emsg(updir, prot);
13550 vim_free(updir);
13551 return r;
13554 #ifdef vim_mkdir
13556 * "mkdir()" function
13558 static void
13559 f_mkdir(argvars, rettv)
13560 typval_T *argvars;
13561 typval_T *rettv;
13563 char_u *dir;
13564 char_u buf[NUMBUFLEN];
13565 int prot = 0755;
13567 rettv->vval.v_number = FAIL;
13568 if (check_restricted() || check_secure())
13569 return;
13571 dir = get_tv_string_buf(&argvars[0], buf);
13572 if (argvars[1].v_type != VAR_UNKNOWN)
13574 if (argvars[2].v_type != VAR_UNKNOWN)
13575 prot = get_tv_number_chk(&argvars[2], NULL);
13576 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
13577 mkdir_recurse(dir, prot);
13579 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
13581 #endif
13584 * "mode()" function
13586 static void
13587 f_mode(argvars, rettv)
13588 typval_T *argvars;
13589 typval_T *rettv;
13591 char_u buf[3];
13593 buf[1] = NUL;
13594 buf[2] = NUL;
13596 #ifdef FEAT_VISUAL
13597 if (VIsual_active)
13599 if (VIsual_select)
13600 buf[0] = VIsual_mode + 's' - 'v';
13601 else
13602 buf[0] = VIsual_mode;
13604 else
13605 #endif
13606 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
13607 || State == CONFIRM)
13609 buf[0] = 'r';
13610 if (State == ASKMORE)
13611 buf[1] = 'm';
13612 else if (State == CONFIRM)
13613 buf[1] = '?';
13615 else if (State == EXTERNCMD)
13616 buf[0] = '!';
13617 else if (State & INSERT)
13619 #ifdef FEAT_VREPLACE
13620 if (State & VREPLACE_FLAG)
13622 buf[0] = 'R';
13623 buf[1] = 'v';
13625 else
13626 #endif
13627 if (State & REPLACE_FLAG)
13628 buf[0] = 'R';
13629 else
13630 buf[0] = 'i';
13632 else if (State & CMDLINE)
13634 buf[0] = 'c';
13635 if (exmode_active)
13636 buf[1] = 'v';
13638 else if (exmode_active)
13640 buf[0] = 'c';
13641 buf[1] = 'e';
13643 else
13645 buf[0] = 'n';
13646 if (finish_op)
13647 buf[1] = 'o';
13650 /* Clear out the minor mode when the argument is not a non-zero number or
13651 * non-empty string. */
13652 if (!non_zero_arg(&argvars[0]))
13653 buf[1] = NUL;
13655 rettv->vval.v_string = vim_strsave(buf);
13656 rettv->v_type = VAR_STRING;
13659 #ifdef FEAT_MZSCHEME
13661 * "mzeval()" function
13663 static void
13664 f_mzeval(argvars, rettv)
13665 typval_T *argvars;
13666 typval_T *rettv;
13668 char_u *str;
13669 char_u buf[NUMBUFLEN];
13671 str = get_tv_string_buf(&argvars[0], buf);
13672 do_mzeval(str, rettv);
13674 #endif
13677 * "nextnonblank()" function
13679 static void
13680 f_nextnonblank(argvars, rettv)
13681 typval_T *argvars;
13682 typval_T *rettv;
13684 linenr_T lnum;
13686 for (lnum = get_tv_lnum(argvars); ; ++lnum)
13688 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
13690 lnum = 0;
13691 break;
13693 if (*skipwhite(ml_get(lnum)) != NUL)
13694 break;
13696 rettv->vval.v_number = lnum;
13700 * "nr2char()" function
13702 static void
13703 f_nr2char(argvars, rettv)
13704 typval_T *argvars;
13705 typval_T *rettv;
13707 char_u buf[NUMBUFLEN];
13709 #ifdef FEAT_MBYTE
13710 if (has_mbyte)
13711 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
13712 else
13713 #endif
13715 buf[0] = (char_u)get_tv_number(&argvars[0]);
13716 buf[1] = NUL;
13718 rettv->v_type = VAR_STRING;
13719 rettv->vval.v_string = vim_strsave(buf);
13723 * "pathshorten()" function
13725 static void
13726 f_pathshorten(argvars, rettv)
13727 typval_T *argvars;
13728 typval_T *rettv;
13730 char_u *p;
13732 rettv->v_type = VAR_STRING;
13733 p = get_tv_string_chk(&argvars[0]);
13734 if (p == NULL)
13735 rettv->vval.v_string = NULL;
13736 else
13738 p = vim_strsave(p);
13739 rettv->vval.v_string = p;
13740 if (p != NULL)
13741 shorten_dir(p);
13745 #ifdef FEAT_FLOAT
13747 * "pow()" function
13749 static void
13750 f_pow(argvars, rettv)
13751 typval_T *argvars;
13752 typval_T *rettv;
13754 float_T fx, fy;
13756 rettv->v_type = VAR_FLOAT;
13757 if (get_float_arg(argvars, &fx) == OK
13758 && get_float_arg(&argvars[1], &fy) == OK)
13759 rettv->vval.v_float = pow(fx, fy);
13760 else
13761 rettv->vval.v_float = 0.0;
13763 #endif
13766 * "prevnonblank()" function
13768 static void
13769 f_prevnonblank(argvars, rettv)
13770 typval_T *argvars;
13771 typval_T *rettv;
13773 linenr_T lnum;
13775 lnum = get_tv_lnum(argvars);
13776 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
13777 lnum = 0;
13778 else
13779 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
13780 --lnum;
13781 rettv->vval.v_number = lnum;
13784 #ifdef HAVE_STDARG_H
13785 /* This dummy va_list is here because:
13786 * - passing a NULL pointer doesn't work when va_list isn't a pointer
13787 * - locally in the function results in a "used before set" warning
13788 * - using va_start() to initialize it gives "function with fixed args" error */
13789 static va_list ap;
13790 #endif
13793 * "printf()" function
13795 static void
13796 f_printf(argvars, rettv)
13797 typval_T *argvars;
13798 typval_T *rettv;
13800 rettv->v_type = VAR_STRING;
13801 rettv->vval.v_string = NULL;
13802 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
13804 char_u buf[NUMBUFLEN];
13805 int len;
13806 char_u *s;
13807 int saved_did_emsg = did_emsg;
13808 char *fmt;
13810 /* Get the required length, allocate the buffer and do it for real. */
13811 did_emsg = FALSE;
13812 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
13813 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
13814 if (!did_emsg)
13816 s = alloc(len + 1);
13817 if (s != NULL)
13819 rettv->vval.v_string = s;
13820 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
13823 did_emsg |= saved_did_emsg;
13825 #endif
13829 * "pumvisible()" function
13831 static void
13832 f_pumvisible(argvars, rettv)
13833 typval_T *argvars UNUSED;
13834 typval_T *rettv UNUSED;
13836 #ifdef FEAT_INS_EXPAND
13837 if (pum_visible())
13838 rettv->vval.v_number = 1;
13839 #endif
13843 * "range()" function
13845 static void
13846 f_range(argvars, rettv)
13847 typval_T *argvars;
13848 typval_T *rettv;
13850 long start;
13851 long end;
13852 long stride = 1;
13853 long i;
13854 int error = FALSE;
13856 start = get_tv_number_chk(&argvars[0], &error);
13857 if (argvars[1].v_type == VAR_UNKNOWN)
13859 end = start - 1;
13860 start = 0;
13862 else
13864 end = get_tv_number_chk(&argvars[1], &error);
13865 if (argvars[2].v_type != VAR_UNKNOWN)
13866 stride = get_tv_number_chk(&argvars[2], &error);
13869 if (error)
13870 return; /* type error; errmsg already given */
13871 if (stride == 0)
13872 EMSG(_("E726: Stride is zero"));
13873 else if (stride > 0 ? end + 1 < start : end - 1 > start)
13874 EMSG(_("E727: Start past end"));
13875 else
13877 if (rettv_list_alloc(rettv) == OK)
13878 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
13879 if (list_append_number(rettv->vval.v_list,
13880 (varnumber_T)i) == FAIL)
13881 break;
13886 * "readfile()" function
13888 static void
13889 f_readfile(argvars, rettv)
13890 typval_T *argvars;
13891 typval_T *rettv;
13893 int binary = FALSE;
13894 char_u *fname;
13895 FILE *fd;
13896 listitem_T *li;
13897 #define FREAD_SIZE 200 /* optimized for text lines */
13898 char_u buf[FREAD_SIZE];
13899 int readlen; /* size of last fread() */
13900 int buflen; /* nr of valid chars in buf[] */
13901 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
13902 int tolist; /* first byte in buf[] still to be put in list */
13903 int chop; /* how many CR to chop off */
13904 char_u *prev = NULL; /* previously read bytes, if any */
13905 int prevlen = 0; /* length of "prev" if not NULL */
13906 char_u *s;
13907 int len;
13908 long maxline = MAXLNUM;
13909 long cnt = 0;
13911 if (argvars[1].v_type != VAR_UNKNOWN)
13913 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
13914 binary = TRUE;
13915 if (argvars[2].v_type != VAR_UNKNOWN)
13916 maxline = get_tv_number(&argvars[2]);
13919 if (rettv_list_alloc(rettv) == FAIL)
13920 return;
13922 /* Always open the file in binary mode, library functions have a mind of
13923 * their own about CR-LF conversion. */
13924 fname = get_tv_string(&argvars[0]);
13925 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
13927 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
13928 return;
13931 filtd = 0;
13932 while (cnt < maxline || maxline < 0)
13934 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
13935 buflen = filtd + readlen;
13936 tolist = 0;
13937 for ( ; filtd < buflen || readlen <= 0; ++filtd)
13939 if (buf[filtd] == '\n' || readlen <= 0)
13941 /* Only when in binary mode add an empty list item when the
13942 * last line ends in a '\n'. */
13943 if (!binary && readlen == 0 && filtd == 0)
13944 break;
13946 /* Found end-of-line or end-of-file: add a text line to the
13947 * list. */
13948 chop = 0;
13949 if (!binary)
13950 while (filtd - chop - 1 >= tolist
13951 && buf[filtd - chop - 1] == '\r')
13952 ++chop;
13953 len = filtd - tolist - chop;
13954 if (prev == NULL)
13955 s = vim_strnsave(buf + tolist, len);
13956 else
13958 s = alloc((unsigned)(prevlen + len + 1));
13959 if (s != NULL)
13961 mch_memmove(s, prev, prevlen);
13962 vim_free(prev);
13963 prev = NULL;
13964 mch_memmove(s + prevlen, buf + tolist, len);
13965 s[prevlen + len] = NUL;
13968 tolist = filtd + 1;
13970 li = listitem_alloc();
13971 if (li == NULL)
13973 vim_free(s);
13974 break;
13976 li->li_tv.v_type = VAR_STRING;
13977 li->li_tv.v_lock = 0;
13978 li->li_tv.vval.v_string = s;
13979 list_append(rettv->vval.v_list, li);
13981 if (++cnt >= maxline && maxline >= 0)
13982 break;
13983 if (readlen <= 0)
13984 break;
13986 else if (buf[filtd] == NUL)
13987 buf[filtd] = '\n';
13989 if (readlen <= 0)
13990 break;
13992 if (tolist == 0)
13994 /* "buf" is full, need to move text to an allocated buffer */
13995 if (prev == NULL)
13997 prev = vim_strnsave(buf, buflen);
13998 prevlen = buflen;
14000 else
14002 s = alloc((unsigned)(prevlen + buflen));
14003 if (s != NULL)
14005 mch_memmove(s, prev, prevlen);
14006 mch_memmove(s + prevlen, buf, buflen);
14007 vim_free(prev);
14008 prev = s;
14009 prevlen += buflen;
14012 filtd = 0;
14014 else
14016 mch_memmove(buf, buf + tolist, buflen - tolist);
14017 filtd -= tolist;
14022 * For a negative line count use only the lines at the end of the file,
14023 * free the rest.
14025 if (maxline < 0)
14026 while (cnt > -maxline)
14028 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
14029 --cnt;
14032 vim_free(prev);
14033 fclose(fd);
14036 #if defined(FEAT_RELTIME)
14037 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
14040 * Convert a List to proftime_T.
14041 * Return FAIL when there is something wrong.
14043 static int
14044 list2proftime(arg, tm)
14045 typval_T *arg;
14046 proftime_T *tm;
14048 long n1, n2;
14049 int error = FALSE;
14051 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
14052 || arg->vval.v_list->lv_len != 2)
14053 return FAIL;
14054 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
14055 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
14056 # ifdef WIN3264
14057 tm->HighPart = n1;
14058 tm->LowPart = n2;
14059 # else
14060 tm->tv_sec = n1;
14061 tm->tv_usec = n2;
14062 # endif
14063 return error ? FAIL : OK;
14065 #endif /* FEAT_RELTIME */
14068 * "reltime()" function
14070 static void
14071 f_reltime(argvars, rettv)
14072 typval_T *argvars;
14073 typval_T *rettv;
14075 #ifdef FEAT_RELTIME
14076 proftime_T res;
14077 proftime_T start;
14079 if (argvars[0].v_type == VAR_UNKNOWN)
14081 /* No arguments: get current time. */
14082 profile_start(&res);
14084 else if (argvars[1].v_type == VAR_UNKNOWN)
14086 if (list2proftime(&argvars[0], &res) == FAIL)
14087 return;
14088 profile_end(&res);
14090 else
14092 /* Two arguments: compute the difference. */
14093 if (list2proftime(&argvars[0], &start) == FAIL
14094 || list2proftime(&argvars[1], &res) == FAIL)
14095 return;
14096 profile_sub(&res, &start);
14099 if (rettv_list_alloc(rettv) == OK)
14101 long n1, n2;
14103 # ifdef WIN3264
14104 n1 = res.HighPart;
14105 n2 = res.LowPart;
14106 # else
14107 n1 = res.tv_sec;
14108 n2 = res.tv_usec;
14109 # endif
14110 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
14111 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
14113 #endif
14117 * "reltimestr()" function
14119 static void
14120 f_reltimestr(argvars, rettv)
14121 typval_T *argvars;
14122 typval_T *rettv;
14124 #ifdef FEAT_RELTIME
14125 proftime_T tm;
14126 #endif
14128 rettv->v_type = VAR_STRING;
14129 rettv->vval.v_string = NULL;
14130 #ifdef FEAT_RELTIME
14131 if (list2proftime(&argvars[0], &tm) == OK)
14132 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
14133 #endif
14136 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
14137 static void make_connection __ARGS((void));
14138 static int check_connection __ARGS((void));
14140 static void
14141 make_connection()
14143 if (X_DISPLAY == NULL
14144 # ifdef FEAT_GUI
14145 && !gui.in_use
14146 # endif
14149 x_force_connect = TRUE;
14150 setup_term_clip();
14151 x_force_connect = FALSE;
14155 static int
14156 check_connection()
14158 make_connection();
14159 if (X_DISPLAY == NULL)
14161 EMSG(_("E240: No connection to Vim server"));
14162 return FAIL;
14164 return OK;
14166 #endif
14168 #ifdef FEAT_CLIENTSERVER
14169 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
14171 static void
14172 remote_common(argvars, rettv, expr)
14173 typval_T *argvars;
14174 typval_T *rettv;
14175 int expr;
14177 char_u *server_name;
14178 char_u *keys;
14179 char_u *r = NULL;
14180 char_u buf[NUMBUFLEN];
14181 # ifdef WIN32
14182 HWND w;
14183 # else
14184 Window w;
14185 # endif
14187 if (check_restricted() || check_secure())
14188 return;
14190 # ifdef FEAT_X11
14191 if (check_connection() == FAIL)
14192 return;
14193 # endif
14195 server_name = get_tv_string_chk(&argvars[0]);
14196 if (server_name == NULL)
14197 return; /* type error; errmsg already given */
14198 keys = get_tv_string_buf(&argvars[1], buf);
14199 # ifdef WIN32
14200 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14201 # else
14202 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
14203 < 0)
14204 # endif
14206 if (r != NULL)
14207 EMSG(r); /* sending worked but evaluation failed */
14208 else
14209 EMSG2(_("E241: Unable to send to %s"), server_name);
14210 return;
14213 rettv->vval.v_string = r;
14215 if (argvars[2].v_type != VAR_UNKNOWN)
14217 dictitem_T v;
14218 char_u str[30];
14219 char_u *idvar;
14221 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
14222 v.di_tv.v_type = VAR_STRING;
14223 v.di_tv.vval.v_string = vim_strsave(str);
14224 idvar = get_tv_string_chk(&argvars[2]);
14225 if (idvar != NULL)
14226 set_var(idvar, &v.di_tv, FALSE);
14227 vim_free(v.di_tv.vval.v_string);
14230 #endif
14233 * "remote_expr()" function
14235 static void
14236 f_remote_expr(argvars, rettv)
14237 typval_T *argvars UNUSED;
14238 typval_T *rettv;
14240 rettv->v_type = VAR_STRING;
14241 rettv->vval.v_string = NULL;
14242 #ifdef FEAT_CLIENTSERVER
14243 remote_common(argvars, rettv, TRUE);
14244 #endif
14248 * "remote_foreground()" function
14250 static void
14251 f_remote_foreground(argvars, rettv)
14252 typval_T *argvars UNUSED;
14253 typval_T *rettv UNUSED;
14255 #ifdef FEAT_CLIENTSERVER
14256 # ifdef WIN32
14257 /* On Win32 it's done in this application. */
14259 char_u *server_name = get_tv_string_chk(&argvars[0]);
14261 if (server_name != NULL)
14262 serverForeground(server_name);
14264 # else
14265 /* Send a foreground() expression to the server. */
14266 argvars[1].v_type = VAR_STRING;
14267 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
14268 argvars[2].v_type = VAR_UNKNOWN;
14269 remote_common(argvars, rettv, TRUE);
14270 vim_free(argvars[1].vval.v_string);
14271 # endif
14272 #endif
14275 static void
14276 f_remote_peek(argvars, rettv)
14277 typval_T *argvars UNUSED;
14278 typval_T *rettv;
14280 #ifdef FEAT_CLIENTSERVER
14281 dictitem_T v;
14282 char_u *s = NULL;
14283 # ifdef WIN32
14284 long_u n = 0;
14285 # endif
14286 char_u *serverid;
14288 if (check_restricted() || check_secure())
14290 rettv->vval.v_number = -1;
14291 return;
14293 serverid = get_tv_string_chk(&argvars[0]);
14294 if (serverid == NULL)
14296 rettv->vval.v_number = -1;
14297 return; /* type error; errmsg already given */
14299 # ifdef WIN32
14300 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14301 if (n == 0)
14302 rettv->vval.v_number = -1;
14303 else
14305 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
14306 rettv->vval.v_number = (s != NULL);
14308 # else
14309 if (check_connection() == FAIL)
14310 return;
14312 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
14313 serverStrToWin(serverid), &s);
14314 # endif
14316 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
14318 char_u *retvar;
14320 v.di_tv.v_type = VAR_STRING;
14321 v.di_tv.vval.v_string = vim_strsave(s);
14322 retvar = get_tv_string_chk(&argvars[1]);
14323 if (retvar != NULL)
14324 set_var(retvar, &v.di_tv, FALSE);
14325 vim_free(v.di_tv.vval.v_string);
14327 #else
14328 rettv->vval.v_number = -1;
14329 #endif
14332 static void
14333 f_remote_read(argvars, rettv)
14334 typval_T *argvars UNUSED;
14335 typval_T *rettv;
14337 char_u *r = NULL;
14339 #ifdef FEAT_CLIENTSERVER
14340 char_u *serverid = get_tv_string_chk(&argvars[0]);
14342 if (serverid != NULL && !check_restricted() && !check_secure())
14344 # ifdef WIN32
14345 /* The server's HWND is encoded in the 'id' parameter */
14346 long_u n = 0;
14348 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14349 if (n != 0)
14350 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
14351 if (r == NULL)
14352 # else
14353 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
14354 serverStrToWin(serverid), &r, FALSE) < 0)
14355 # endif
14356 EMSG(_("E277: Unable to read a server reply"));
14358 #endif
14359 rettv->v_type = VAR_STRING;
14360 rettv->vval.v_string = r;
14364 * "remote_send()" function
14366 static void
14367 f_remote_send(argvars, rettv)
14368 typval_T *argvars UNUSED;
14369 typval_T *rettv;
14371 rettv->v_type = VAR_STRING;
14372 rettv->vval.v_string = NULL;
14373 #ifdef FEAT_CLIENTSERVER
14374 remote_common(argvars, rettv, FALSE);
14375 #endif
14379 * "remove()" function
14381 static void
14382 f_remove(argvars, rettv)
14383 typval_T *argvars;
14384 typval_T *rettv;
14386 list_T *l;
14387 listitem_T *item, *item2;
14388 listitem_T *li;
14389 long idx;
14390 long end;
14391 char_u *key;
14392 dict_T *d;
14393 dictitem_T *di;
14395 if (argvars[0].v_type == VAR_DICT)
14397 if (argvars[2].v_type != VAR_UNKNOWN)
14398 EMSG2(_(e_toomanyarg), "remove()");
14399 else if ((d = argvars[0].vval.v_dict) != NULL
14400 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
14402 key = get_tv_string_chk(&argvars[1]);
14403 if (key != NULL)
14405 di = dict_find(d, key, -1);
14406 if (di == NULL)
14407 EMSG2(_(e_dictkey), key);
14408 else
14410 *rettv = di->di_tv;
14411 init_tv(&di->di_tv);
14412 dictitem_remove(d, di);
14417 else if (argvars[0].v_type != VAR_LIST)
14418 EMSG2(_(e_listdictarg), "remove()");
14419 else if ((l = argvars[0].vval.v_list) != NULL
14420 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
14422 int error = FALSE;
14424 idx = get_tv_number_chk(&argvars[1], &error);
14425 if (error)
14426 ; /* type error: do nothing, errmsg already given */
14427 else if ((item = list_find(l, idx)) == NULL)
14428 EMSGN(_(e_listidx), idx);
14429 else
14431 if (argvars[2].v_type == VAR_UNKNOWN)
14433 /* Remove one item, return its value. */
14434 list_remove(l, item, item);
14435 *rettv = item->li_tv;
14436 vim_free(item);
14438 else
14440 /* Remove range of items, return list with values. */
14441 end = get_tv_number_chk(&argvars[2], &error);
14442 if (error)
14443 ; /* type error: do nothing */
14444 else if ((item2 = list_find(l, end)) == NULL)
14445 EMSGN(_(e_listidx), end);
14446 else
14448 int cnt = 0;
14450 for (li = item; li != NULL; li = li->li_next)
14452 ++cnt;
14453 if (li == item2)
14454 break;
14456 if (li == NULL) /* didn't find "item2" after "item" */
14457 EMSG(_(e_invrange));
14458 else
14460 list_remove(l, item, item2);
14461 if (rettv_list_alloc(rettv) == OK)
14463 l = rettv->vval.v_list;
14464 l->lv_first = item;
14465 l->lv_last = item2;
14466 item->li_prev = NULL;
14467 item2->li_next = NULL;
14468 l->lv_len = cnt;
14478 * "rename({from}, {to})" function
14480 static void
14481 f_rename(argvars, rettv)
14482 typval_T *argvars;
14483 typval_T *rettv;
14485 char_u buf[NUMBUFLEN];
14487 if (check_restricted() || check_secure())
14488 rettv->vval.v_number = -1;
14489 else
14490 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
14491 get_tv_string_buf(&argvars[1], buf));
14495 * "repeat()" function
14497 static void
14498 f_repeat(argvars, rettv)
14499 typval_T *argvars;
14500 typval_T *rettv;
14502 char_u *p;
14503 int n;
14504 int slen;
14505 int len;
14506 char_u *r;
14507 int i;
14509 n = get_tv_number(&argvars[1]);
14510 if (argvars[0].v_type == VAR_LIST)
14512 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
14513 while (n-- > 0)
14514 if (list_extend(rettv->vval.v_list,
14515 argvars[0].vval.v_list, NULL) == FAIL)
14516 break;
14518 else
14520 p = get_tv_string(&argvars[0]);
14521 rettv->v_type = VAR_STRING;
14522 rettv->vval.v_string = NULL;
14524 slen = (int)STRLEN(p);
14525 len = slen * n;
14526 if (len <= 0)
14527 return;
14529 r = alloc(len + 1);
14530 if (r != NULL)
14532 for (i = 0; i < n; i++)
14533 mch_memmove(r + i * slen, p, (size_t)slen);
14534 r[len] = NUL;
14537 rettv->vval.v_string = r;
14542 * "resolve()" function
14544 static void
14545 f_resolve(argvars, rettv)
14546 typval_T *argvars;
14547 typval_T *rettv;
14549 char_u *p;
14551 p = get_tv_string(&argvars[0]);
14552 #ifdef FEAT_SHORTCUT
14554 char_u *v = NULL;
14556 v = mch_resolve_shortcut(p);
14557 if (v != NULL)
14558 rettv->vval.v_string = v;
14559 else
14560 rettv->vval.v_string = vim_strsave(p);
14562 #else
14563 # ifdef HAVE_READLINK
14565 char_u buf[MAXPATHL + 1];
14566 char_u *cpy;
14567 int len;
14568 char_u *remain = NULL;
14569 char_u *q;
14570 int is_relative_to_current = FALSE;
14571 int has_trailing_pathsep = FALSE;
14572 int limit = 100;
14574 p = vim_strsave(p);
14576 if (p[0] == '.' && (vim_ispathsep(p[1])
14577 || (p[1] == '.' && (vim_ispathsep(p[2])))))
14578 is_relative_to_current = TRUE;
14580 len = STRLEN(p);
14581 if (len > 0 && after_pathsep(p, p + len))
14582 has_trailing_pathsep = TRUE;
14584 q = getnextcomp(p);
14585 if (*q != NUL)
14587 /* Separate the first path component in "p", and keep the
14588 * remainder (beginning with the path separator). */
14589 remain = vim_strsave(q - 1);
14590 q[-1] = NUL;
14593 for (;;)
14595 for (;;)
14597 len = readlink((char *)p, (char *)buf, MAXPATHL);
14598 if (len <= 0)
14599 break;
14600 buf[len] = NUL;
14602 if (limit-- == 0)
14604 vim_free(p);
14605 vim_free(remain);
14606 EMSG(_("E655: Too many symbolic links (cycle?)"));
14607 rettv->vval.v_string = NULL;
14608 goto fail;
14611 /* Ensure that the result will have a trailing path separator
14612 * if the argument has one. */
14613 if (remain == NULL && has_trailing_pathsep)
14614 add_pathsep(buf);
14616 /* Separate the first path component in the link value and
14617 * concatenate the remainders. */
14618 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
14619 if (*q != NUL)
14621 if (remain == NULL)
14622 remain = vim_strsave(q - 1);
14623 else
14625 cpy = concat_str(q - 1, remain);
14626 if (cpy != NULL)
14628 vim_free(remain);
14629 remain = cpy;
14632 q[-1] = NUL;
14635 q = gettail(p);
14636 if (q > p && *q == NUL)
14638 /* Ignore trailing path separator. */
14639 q[-1] = NUL;
14640 q = gettail(p);
14642 if (q > p && !mch_isFullName(buf))
14644 /* symlink is relative to directory of argument */
14645 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
14646 if (cpy != NULL)
14648 STRCPY(cpy, p);
14649 STRCPY(gettail(cpy), buf);
14650 vim_free(p);
14651 p = cpy;
14654 else
14656 vim_free(p);
14657 p = vim_strsave(buf);
14661 if (remain == NULL)
14662 break;
14664 /* Append the first path component of "remain" to "p". */
14665 q = getnextcomp(remain + 1);
14666 len = q - remain - (*q != NUL);
14667 cpy = vim_strnsave(p, STRLEN(p) + len);
14668 if (cpy != NULL)
14670 STRNCAT(cpy, remain, len);
14671 vim_free(p);
14672 p = cpy;
14674 /* Shorten "remain". */
14675 if (*q != NUL)
14676 STRMOVE(remain, q - 1);
14677 else
14679 vim_free(remain);
14680 remain = NULL;
14684 /* If the result is a relative path name, make it explicitly relative to
14685 * the current directory if and only if the argument had this form. */
14686 if (!vim_ispathsep(*p))
14688 if (is_relative_to_current
14689 && *p != NUL
14690 && !(p[0] == '.'
14691 && (p[1] == NUL
14692 || vim_ispathsep(p[1])
14693 || (p[1] == '.'
14694 && (p[2] == NUL
14695 || vim_ispathsep(p[2]))))))
14697 /* Prepend "./". */
14698 cpy = concat_str((char_u *)"./", p);
14699 if (cpy != NULL)
14701 vim_free(p);
14702 p = cpy;
14705 else if (!is_relative_to_current)
14707 /* Strip leading "./". */
14708 q = p;
14709 while (q[0] == '.' && vim_ispathsep(q[1]))
14710 q += 2;
14711 if (q > p)
14712 STRMOVE(p, p + 2);
14716 /* Ensure that the result will have no trailing path separator
14717 * if the argument had none. But keep "/" or "//". */
14718 if (!has_trailing_pathsep)
14720 q = p + STRLEN(p);
14721 if (after_pathsep(p, q))
14722 *gettail_sep(p) = NUL;
14725 rettv->vval.v_string = p;
14727 # else
14728 rettv->vval.v_string = vim_strsave(p);
14729 # endif
14730 #endif
14732 simplify_filename(rettv->vval.v_string);
14734 #ifdef HAVE_READLINK
14735 fail:
14736 #endif
14737 rettv->v_type = VAR_STRING;
14741 * "reverse({list})" function
14743 static void
14744 f_reverse(argvars, rettv)
14745 typval_T *argvars;
14746 typval_T *rettv;
14748 list_T *l;
14749 listitem_T *li, *ni;
14751 if (argvars[0].v_type != VAR_LIST)
14752 EMSG2(_(e_listarg), "reverse()");
14753 else if ((l = argvars[0].vval.v_list) != NULL
14754 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
14756 li = l->lv_last;
14757 l->lv_first = l->lv_last = NULL;
14758 l->lv_len = 0;
14759 while (li != NULL)
14761 ni = li->li_prev;
14762 list_append(l, li);
14763 li = ni;
14765 rettv->vval.v_list = l;
14766 rettv->v_type = VAR_LIST;
14767 ++l->lv_refcount;
14768 l->lv_idx = l->lv_len - l->lv_idx - 1;
14772 #define SP_NOMOVE 0x01 /* don't move cursor */
14773 #define SP_REPEAT 0x02 /* repeat to find outer pair */
14774 #define SP_RETCOUNT 0x04 /* return matchcount */
14775 #define SP_SETPCMARK 0x08 /* set previous context mark */
14776 #define SP_START 0x10 /* accept match at start position */
14777 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
14778 #define SP_END 0x40 /* leave cursor at end of match */
14780 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
14783 * Get flags for a search function.
14784 * Possibly sets "p_ws".
14785 * Returns BACKWARD, FORWARD or zero (for an error).
14787 static int
14788 get_search_arg(varp, flagsp)
14789 typval_T *varp;
14790 int *flagsp;
14792 int dir = FORWARD;
14793 char_u *flags;
14794 char_u nbuf[NUMBUFLEN];
14795 int mask;
14797 if (varp->v_type != VAR_UNKNOWN)
14799 flags = get_tv_string_buf_chk(varp, nbuf);
14800 if (flags == NULL)
14801 return 0; /* type error; errmsg already given */
14802 while (*flags != NUL)
14804 switch (*flags)
14806 case 'b': dir = BACKWARD; break;
14807 case 'w': p_ws = TRUE; break;
14808 case 'W': p_ws = FALSE; break;
14809 default: mask = 0;
14810 if (flagsp != NULL)
14811 switch (*flags)
14813 case 'c': mask = SP_START; break;
14814 case 'e': mask = SP_END; break;
14815 case 'm': mask = SP_RETCOUNT; break;
14816 case 'n': mask = SP_NOMOVE; break;
14817 case 'p': mask = SP_SUBPAT; break;
14818 case 'r': mask = SP_REPEAT; break;
14819 case 's': mask = SP_SETPCMARK; break;
14821 if (mask == 0)
14823 EMSG2(_(e_invarg2), flags);
14824 dir = 0;
14826 else
14827 *flagsp |= mask;
14829 if (dir == 0)
14830 break;
14831 ++flags;
14834 return dir;
14838 * Shared by search() and searchpos() functions
14840 static int
14841 search_cmn(argvars, match_pos, flagsp)
14842 typval_T *argvars;
14843 pos_T *match_pos;
14844 int *flagsp;
14846 int flags;
14847 char_u *pat;
14848 pos_T pos;
14849 pos_T save_cursor;
14850 int save_p_ws = p_ws;
14851 int dir;
14852 int retval = 0; /* default: FAIL */
14853 long lnum_stop = 0;
14854 proftime_T tm;
14855 #ifdef FEAT_RELTIME
14856 long time_limit = 0;
14857 #endif
14858 int options = SEARCH_KEEP;
14859 int subpatnum;
14861 pat = get_tv_string(&argvars[0]);
14862 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
14863 if (dir == 0)
14864 goto theend;
14865 flags = *flagsp;
14866 if (flags & SP_START)
14867 options |= SEARCH_START;
14868 if (flags & SP_END)
14869 options |= SEARCH_END;
14871 /* Optional arguments: line number to stop searching and timeout. */
14872 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
14874 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
14875 if (lnum_stop < 0)
14876 goto theend;
14877 #ifdef FEAT_RELTIME
14878 if (argvars[3].v_type != VAR_UNKNOWN)
14880 time_limit = get_tv_number_chk(&argvars[3], NULL);
14881 if (time_limit < 0)
14882 goto theend;
14884 #endif
14887 #ifdef FEAT_RELTIME
14888 /* Set the time limit, if there is one. */
14889 profile_setlimit(time_limit, &tm);
14890 #endif
14893 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
14894 * Check to make sure only those flags are set.
14895 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
14896 * flags cannot be set. Check for that condition also.
14898 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
14899 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14901 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
14902 goto theend;
14905 pos = save_cursor = curwin->w_cursor;
14906 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14907 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
14908 if (subpatnum != FAIL)
14910 if (flags & SP_SUBPAT)
14911 retval = subpatnum;
14912 else
14913 retval = pos.lnum;
14914 if (flags & SP_SETPCMARK)
14915 setpcmark();
14916 curwin->w_cursor = pos;
14917 if (match_pos != NULL)
14919 /* Store the match cursor position */
14920 match_pos->lnum = pos.lnum;
14921 match_pos->col = pos.col + 1;
14923 /* "/$" will put the cursor after the end of the line, may need to
14924 * correct that here */
14925 check_cursor();
14928 /* If 'n' flag is used: restore cursor position. */
14929 if (flags & SP_NOMOVE)
14930 curwin->w_cursor = save_cursor;
14931 else
14932 curwin->w_set_curswant = TRUE;
14933 theend:
14934 p_ws = save_p_ws;
14936 return retval;
14939 #ifdef FEAT_FLOAT
14941 * "round({float})" function
14943 static void
14944 f_round(argvars, rettv)
14945 typval_T *argvars;
14946 typval_T *rettv;
14948 float_T f;
14950 rettv->v_type = VAR_FLOAT;
14951 if (get_float_arg(argvars, &f) == OK)
14952 /* round() is not in C90, use ceil() or floor() instead. */
14953 rettv->vval.v_float = f > 0 ? floor(f + 0.5) : ceil(f - 0.5);
14954 else
14955 rettv->vval.v_float = 0.0;
14957 #endif
14960 * "search()" function
14962 static void
14963 f_search(argvars, rettv)
14964 typval_T *argvars;
14965 typval_T *rettv;
14967 int flags = 0;
14969 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
14973 * "searchdecl()" function
14975 static void
14976 f_searchdecl(argvars, rettv)
14977 typval_T *argvars;
14978 typval_T *rettv;
14980 int locally = 1;
14981 int thisblock = 0;
14982 int error = FALSE;
14983 char_u *name;
14985 rettv->vval.v_number = 1; /* default: FAIL */
14987 name = get_tv_string_chk(&argvars[0]);
14988 if (argvars[1].v_type != VAR_UNKNOWN)
14990 locally = get_tv_number_chk(&argvars[1], &error) == 0;
14991 if (!error && argvars[2].v_type != VAR_UNKNOWN)
14992 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
14994 if (!error && name != NULL)
14995 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
14996 locally, thisblock, SEARCH_KEEP) == FAIL;
15000 * Used by searchpair() and searchpairpos()
15002 static int
15003 searchpair_cmn(argvars, match_pos)
15004 typval_T *argvars;
15005 pos_T *match_pos;
15007 char_u *spat, *mpat, *epat;
15008 char_u *skip;
15009 int save_p_ws = p_ws;
15010 int dir;
15011 int flags = 0;
15012 char_u nbuf1[NUMBUFLEN];
15013 char_u nbuf2[NUMBUFLEN];
15014 char_u nbuf3[NUMBUFLEN];
15015 int retval = 0; /* default: FAIL */
15016 long lnum_stop = 0;
15017 long time_limit = 0;
15019 /* Get the three pattern arguments: start, middle, end. */
15020 spat = get_tv_string_chk(&argvars[0]);
15021 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
15022 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
15023 if (spat == NULL || mpat == NULL || epat == NULL)
15024 goto theend; /* type error */
15026 /* Handle the optional fourth argument: flags */
15027 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
15028 if (dir == 0)
15029 goto theend;
15031 /* Don't accept SP_END or SP_SUBPAT.
15032 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
15034 if ((flags & (SP_END | SP_SUBPAT)) != 0
15035 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
15037 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
15038 goto theend;
15041 /* Using 'r' implies 'W', otherwise it doesn't work. */
15042 if (flags & SP_REPEAT)
15043 p_ws = FALSE;
15045 /* Optional fifth argument: skip expression */
15046 if (argvars[3].v_type == VAR_UNKNOWN
15047 || argvars[4].v_type == VAR_UNKNOWN)
15048 skip = (char_u *)"";
15049 else
15051 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
15052 if (argvars[5].v_type != VAR_UNKNOWN)
15054 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
15055 if (lnum_stop < 0)
15056 goto theend;
15057 #ifdef FEAT_RELTIME
15058 if (argvars[6].v_type != VAR_UNKNOWN)
15060 time_limit = get_tv_number_chk(&argvars[6], NULL);
15061 if (time_limit < 0)
15062 goto theend;
15064 #endif
15067 if (skip == NULL)
15068 goto theend; /* type error */
15070 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
15071 match_pos, lnum_stop, time_limit);
15073 theend:
15074 p_ws = save_p_ws;
15076 return retval;
15080 * "searchpair()" function
15082 static void
15083 f_searchpair(argvars, rettv)
15084 typval_T *argvars;
15085 typval_T *rettv;
15087 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
15091 * "searchpairpos()" function
15093 static void
15094 f_searchpairpos(argvars, rettv)
15095 typval_T *argvars;
15096 typval_T *rettv;
15098 pos_T match_pos;
15099 int lnum = 0;
15100 int col = 0;
15102 if (rettv_list_alloc(rettv) == FAIL)
15103 return;
15105 if (searchpair_cmn(argvars, &match_pos) > 0)
15107 lnum = match_pos.lnum;
15108 col = match_pos.col;
15111 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15112 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15116 * Search for a start/middle/end thing.
15117 * Used by searchpair(), see its documentation for the details.
15118 * Returns 0 or -1 for no match,
15120 long
15121 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
15122 lnum_stop, time_limit)
15123 char_u *spat; /* start pattern */
15124 char_u *mpat; /* middle pattern */
15125 char_u *epat; /* end pattern */
15126 int dir; /* BACKWARD or FORWARD */
15127 char_u *skip; /* skip expression */
15128 int flags; /* SP_SETPCMARK and other SP_ values */
15129 pos_T *match_pos;
15130 linenr_T lnum_stop; /* stop at this line if not zero */
15131 long time_limit; /* stop after this many msec */
15133 char_u *save_cpo;
15134 char_u *pat, *pat2 = NULL, *pat3 = NULL;
15135 long retval = 0;
15136 pos_T pos;
15137 pos_T firstpos;
15138 pos_T foundpos;
15139 pos_T save_cursor;
15140 pos_T save_pos;
15141 int n;
15142 int r;
15143 int nest = 1;
15144 int err;
15145 int options = SEARCH_KEEP;
15146 proftime_T tm;
15148 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15149 save_cpo = p_cpo;
15150 p_cpo = empty_option;
15152 #ifdef FEAT_RELTIME
15153 /* Set the time limit, if there is one. */
15154 profile_setlimit(time_limit, &tm);
15155 #endif
15157 /* Make two search patterns: start/end (pat2, for in nested pairs) and
15158 * start/middle/end (pat3, for the top pair). */
15159 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
15160 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
15161 if (pat2 == NULL || pat3 == NULL)
15162 goto theend;
15163 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
15164 if (*mpat == NUL)
15165 STRCPY(pat3, pat2);
15166 else
15167 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
15168 spat, epat, mpat);
15169 if (flags & SP_START)
15170 options |= SEARCH_START;
15172 save_cursor = curwin->w_cursor;
15173 pos = curwin->w_cursor;
15174 clearpos(&firstpos);
15175 clearpos(&foundpos);
15176 pat = pat3;
15177 for (;;)
15179 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15180 options, RE_SEARCH, lnum_stop, &tm);
15181 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
15182 /* didn't find it or found the first match again: FAIL */
15183 break;
15185 if (firstpos.lnum == 0)
15186 firstpos = pos;
15187 if (equalpos(pos, foundpos))
15189 /* Found the same position again. Can happen with a pattern that
15190 * has "\zs" at the end and searching backwards. Advance one
15191 * character and try again. */
15192 if (dir == BACKWARD)
15193 decl(&pos);
15194 else
15195 incl(&pos);
15197 foundpos = pos;
15199 /* clear the start flag to avoid getting stuck here */
15200 options &= ~SEARCH_START;
15202 /* If the skip pattern matches, ignore this match. */
15203 if (*skip != NUL)
15205 save_pos = curwin->w_cursor;
15206 curwin->w_cursor = pos;
15207 r = eval_to_bool(skip, &err, NULL, FALSE);
15208 curwin->w_cursor = save_pos;
15209 if (err)
15211 /* Evaluating {skip} caused an error, break here. */
15212 curwin->w_cursor = save_cursor;
15213 retval = -1;
15214 break;
15216 if (r)
15217 continue;
15220 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
15222 /* Found end when searching backwards or start when searching
15223 * forward: nested pair. */
15224 ++nest;
15225 pat = pat2; /* nested, don't search for middle */
15227 else
15229 /* Found end when searching forward or start when searching
15230 * backward: end of (nested) pair; or found middle in outer pair. */
15231 if (--nest == 1)
15232 pat = pat3; /* outer level, search for middle */
15235 if (nest == 0)
15237 /* Found the match: return matchcount or line number. */
15238 if (flags & SP_RETCOUNT)
15239 ++retval;
15240 else
15241 retval = pos.lnum;
15242 if (flags & SP_SETPCMARK)
15243 setpcmark();
15244 curwin->w_cursor = pos;
15245 if (!(flags & SP_REPEAT))
15246 break;
15247 nest = 1; /* search for next unmatched */
15251 if (match_pos != NULL)
15253 /* Store the match cursor position */
15254 match_pos->lnum = curwin->w_cursor.lnum;
15255 match_pos->col = curwin->w_cursor.col + 1;
15258 /* If 'n' flag is used or search failed: restore cursor position. */
15259 if ((flags & SP_NOMOVE) || retval == 0)
15260 curwin->w_cursor = save_cursor;
15262 theend:
15263 vim_free(pat2);
15264 vim_free(pat3);
15265 if (p_cpo == empty_option)
15266 p_cpo = save_cpo;
15267 else
15268 /* Darn, evaluating the {skip} expression changed the value. */
15269 free_string_option(save_cpo);
15271 return retval;
15275 * "searchpos()" function
15277 static void
15278 f_searchpos(argvars, rettv)
15279 typval_T *argvars;
15280 typval_T *rettv;
15282 pos_T match_pos;
15283 int lnum = 0;
15284 int col = 0;
15285 int n;
15286 int flags = 0;
15288 if (rettv_list_alloc(rettv) == FAIL)
15289 return;
15291 n = search_cmn(argvars, &match_pos, &flags);
15292 if (n > 0)
15294 lnum = match_pos.lnum;
15295 col = match_pos.col;
15298 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15299 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15300 if (flags & SP_SUBPAT)
15301 list_append_number(rettv->vval.v_list, (varnumber_T)n);
15305 static void
15306 f_server2client(argvars, rettv)
15307 typval_T *argvars UNUSED;
15308 typval_T *rettv;
15310 #ifdef FEAT_CLIENTSERVER
15311 char_u buf[NUMBUFLEN];
15312 char_u *server = get_tv_string_chk(&argvars[0]);
15313 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
15315 rettv->vval.v_number = -1;
15316 if (server == NULL || reply == NULL)
15317 return;
15318 if (check_restricted() || check_secure())
15319 return;
15320 # ifdef FEAT_X11
15321 if (check_connection() == FAIL)
15322 return;
15323 # endif
15325 if (serverSendReply(server, reply) < 0)
15327 EMSG(_("E258: Unable to send to client"));
15328 return;
15330 rettv->vval.v_number = 0;
15331 #else
15332 rettv->vval.v_number = -1;
15333 #endif
15336 static void
15337 f_serverlist(argvars, rettv)
15338 typval_T *argvars UNUSED;
15339 typval_T *rettv;
15341 char_u *r = NULL;
15343 #ifdef FEAT_CLIENTSERVER
15344 # ifdef WIN32
15345 r = serverGetVimNames();
15346 # else
15347 make_connection();
15348 if (X_DISPLAY != NULL)
15349 r = serverGetVimNames(X_DISPLAY);
15350 # endif
15351 #endif
15352 rettv->v_type = VAR_STRING;
15353 rettv->vval.v_string = r;
15357 * "setbufvar()" function
15359 static void
15360 f_setbufvar(argvars, rettv)
15361 typval_T *argvars;
15362 typval_T *rettv UNUSED;
15364 buf_T *buf;
15365 aco_save_T aco;
15366 char_u *varname, *bufvarname;
15367 typval_T *varp;
15368 char_u nbuf[NUMBUFLEN];
15370 if (check_restricted() || check_secure())
15371 return;
15372 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
15373 varname = get_tv_string_chk(&argvars[1]);
15374 buf = get_buf_tv(&argvars[0]);
15375 varp = &argvars[2];
15377 if (buf != NULL && varname != NULL && varp != NULL)
15379 /* set curbuf to be our buf, temporarily */
15380 aucmd_prepbuf(&aco, buf);
15382 if (*varname == '&')
15384 long numval;
15385 char_u *strval;
15386 int error = FALSE;
15388 ++varname;
15389 numval = get_tv_number_chk(varp, &error);
15390 strval = get_tv_string_buf_chk(varp, nbuf);
15391 if (!error && strval != NULL)
15392 set_option_value(varname, numval, strval, OPT_LOCAL);
15394 else
15396 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
15397 if (bufvarname != NULL)
15399 STRCPY(bufvarname, "b:");
15400 STRCPY(bufvarname + 2, varname);
15401 set_var(bufvarname, varp, TRUE);
15402 vim_free(bufvarname);
15406 /* reset notion of buffer */
15407 aucmd_restbuf(&aco);
15412 * "setcmdpos()" function
15414 static void
15415 f_setcmdpos(argvars, rettv)
15416 typval_T *argvars;
15417 typval_T *rettv;
15419 int pos = (int)get_tv_number(&argvars[0]) - 1;
15421 if (pos >= 0)
15422 rettv->vval.v_number = set_cmdline_pos(pos);
15426 * "setline()" function
15428 static void
15429 f_setline(argvars, rettv)
15430 typval_T *argvars;
15431 typval_T *rettv;
15433 linenr_T lnum;
15434 char_u *line = NULL;
15435 list_T *l = NULL;
15436 listitem_T *li = NULL;
15437 long added = 0;
15438 linenr_T lcount = curbuf->b_ml.ml_line_count;
15440 lnum = get_tv_lnum(&argvars[0]);
15441 if (argvars[1].v_type == VAR_LIST)
15443 l = argvars[1].vval.v_list;
15444 li = l->lv_first;
15446 else
15447 line = get_tv_string_chk(&argvars[1]);
15449 /* default result is zero == OK */
15450 for (;;)
15452 if (l != NULL)
15454 /* list argument, get next string */
15455 if (li == NULL)
15456 break;
15457 line = get_tv_string_chk(&li->li_tv);
15458 li = li->li_next;
15461 rettv->vval.v_number = 1; /* FAIL */
15462 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
15463 break;
15464 if (lnum <= curbuf->b_ml.ml_line_count)
15466 /* existing line, replace it */
15467 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
15469 changed_bytes(lnum, 0);
15470 if (lnum == curwin->w_cursor.lnum)
15471 check_cursor_col();
15472 rettv->vval.v_number = 0; /* OK */
15475 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
15477 /* lnum is one past the last line, append the line */
15478 ++added;
15479 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
15480 rettv->vval.v_number = 0; /* OK */
15483 if (l == NULL) /* only one string argument */
15484 break;
15485 ++lnum;
15488 if (added > 0)
15489 appended_lines_mark(lcount, added);
15492 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
15495 * Used by "setqflist()" and "setloclist()" functions
15497 static void
15498 set_qf_ll_list(wp, list_arg, action_arg, rettv)
15499 win_T *wp UNUSED;
15500 typval_T *list_arg UNUSED;
15501 typval_T *action_arg UNUSED;
15502 typval_T *rettv;
15504 #ifdef FEAT_QUICKFIX
15505 char_u *act;
15506 int action = ' ';
15507 #endif
15509 rettv->vval.v_number = -1;
15511 #ifdef FEAT_QUICKFIX
15512 if (list_arg->v_type != VAR_LIST)
15513 EMSG(_(e_listreq));
15514 else
15516 list_T *l = list_arg->vval.v_list;
15518 if (action_arg->v_type == VAR_STRING)
15520 act = get_tv_string_chk(action_arg);
15521 if (act == NULL)
15522 return; /* type error; errmsg already given */
15523 if (*act == 'a' || *act == 'r')
15524 action = *act;
15527 if (l != NULL && set_errorlist(wp, l, action) == OK)
15528 rettv->vval.v_number = 0;
15530 #endif
15534 * "setloclist()" function
15536 static void
15537 f_setloclist(argvars, rettv)
15538 typval_T *argvars;
15539 typval_T *rettv;
15541 win_T *win;
15543 rettv->vval.v_number = -1;
15545 win = find_win_by_nr(&argvars[0], NULL);
15546 if (win != NULL)
15547 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
15551 * "setmatches()" function
15553 static void
15554 f_setmatches(argvars, rettv)
15555 typval_T *argvars;
15556 typval_T *rettv;
15558 #ifdef FEAT_SEARCH_EXTRA
15559 list_T *l;
15560 listitem_T *li;
15561 dict_T *d;
15563 rettv->vval.v_number = -1;
15564 if (argvars[0].v_type != VAR_LIST)
15566 EMSG(_(e_listreq));
15567 return;
15569 if ((l = argvars[0].vval.v_list) != NULL)
15572 /* To some extent make sure that we are dealing with a list from
15573 * "getmatches()". */
15574 li = l->lv_first;
15575 while (li != NULL)
15577 if (li->li_tv.v_type != VAR_DICT
15578 || (d = li->li_tv.vval.v_dict) == NULL)
15580 EMSG(_(e_invarg));
15581 return;
15583 if (!(dict_find(d, (char_u *)"group", -1) != NULL
15584 && dict_find(d, (char_u *)"pattern", -1) != NULL
15585 && dict_find(d, (char_u *)"priority", -1) != NULL
15586 && dict_find(d, (char_u *)"id", -1) != NULL))
15588 EMSG(_(e_invarg));
15589 return;
15591 li = li->li_next;
15594 clear_matches(curwin);
15595 li = l->lv_first;
15596 while (li != NULL)
15598 d = li->li_tv.vval.v_dict;
15599 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
15600 get_dict_string(d, (char_u *)"pattern", FALSE),
15601 (int)get_dict_number(d, (char_u *)"priority"),
15602 (int)get_dict_number(d, (char_u *)"id"));
15603 li = li->li_next;
15605 rettv->vval.v_number = 0;
15607 #endif
15611 * "setpos()" function
15613 static void
15614 f_setpos(argvars, rettv)
15615 typval_T *argvars;
15616 typval_T *rettv;
15618 pos_T pos;
15619 int fnum;
15620 char_u *name;
15622 rettv->vval.v_number = -1;
15623 name = get_tv_string_chk(argvars);
15624 if (name != NULL)
15626 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
15628 if (--pos.col < 0)
15629 pos.col = 0;
15630 if (name[0] == '.' && name[1] == NUL)
15632 /* set cursor */
15633 if (fnum == curbuf->b_fnum)
15635 curwin->w_cursor = pos;
15636 check_cursor();
15637 rettv->vval.v_number = 0;
15639 else
15640 EMSG(_(e_invarg));
15642 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
15644 /* set mark */
15645 if (setmark_pos(name[1], &pos, fnum) == OK)
15646 rettv->vval.v_number = 0;
15648 else
15649 EMSG(_(e_invarg));
15655 * "setqflist()" function
15657 static void
15658 f_setqflist(argvars, rettv)
15659 typval_T *argvars;
15660 typval_T *rettv;
15662 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
15666 * "setreg()" function
15668 static void
15669 f_setreg(argvars, rettv)
15670 typval_T *argvars;
15671 typval_T *rettv;
15673 int regname;
15674 char_u *strregname;
15675 char_u *stropt;
15676 char_u *strval;
15677 int append;
15678 char_u yank_type;
15679 long block_len;
15681 block_len = -1;
15682 yank_type = MAUTO;
15683 append = FALSE;
15685 strregname = get_tv_string_chk(argvars);
15686 rettv->vval.v_number = 1; /* FAIL is default */
15688 if (strregname == NULL)
15689 return; /* type error; errmsg already given */
15690 regname = *strregname;
15691 if (regname == 0 || regname == '@')
15692 regname = '"';
15693 else if (regname == '=')
15694 return;
15696 if (argvars[2].v_type != VAR_UNKNOWN)
15698 stropt = get_tv_string_chk(&argvars[2]);
15699 if (stropt == NULL)
15700 return; /* type error */
15701 for (; *stropt != NUL; ++stropt)
15702 switch (*stropt)
15704 case 'a': case 'A': /* append */
15705 append = TRUE;
15706 break;
15707 case 'v': case 'c': /* character-wise selection */
15708 yank_type = MCHAR;
15709 break;
15710 case 'V': case 'l': /* line-wise selection */
15711 yank_type = MLINE;
15712 break;
15713 #ifdef FEAT_VISUAL
15714 case 'b': case Ctrl_V: /* block-wise selection */
15715 yank_type = MBLOCK;
15716 if (VIM_ISDIGIT(stropt[1]))
15718 ++stropt;
15719 block_len = getdigits(&stropt) - 1;
15720 --stropt;
15722 break;
15723 #endif
15727 strval = get_tv_string_chk(&argvars[1]);
15728 if (strval != NULL)
15729 write_reg_contents_ex(regname, strval, -1,
15730 append, yank_type, block_len);
15731 rettv->vval.v_number = 0;
15735 * "settabwinvar()" function
15737 static void
15738 f_settabwinvar(argvars, rettv)
15739 typval_T *argvars;
15740 typval_T *rettv;
15742 setwinvar(argvars, rettv, 1);
15746 * "setwinvar()" function
15748 static void
15749 f_setwinvar(argvars, rettv)
15750 typval_T *argvars;
15751 typval_T *rettv;
15753 setwinvar(argvars, rettv, 0);
15757 * "setwinvar()" and "settabwinvar()" functions
15759 static void
15760 setwinvar(argvars, rettv, off)
15761 typval_T *argvars;
15762 typval_T *rettv UNUSED;
15763 int off;
15765 win_T *win;
15766 #ifdef FEAT_WINDOWS
15767 win_T *save_curwin;
15768 tabpage_T *save_curtab;
15769 #endif
15770 char_u *varname, *winvarname;
15771 typval_T *varp;
15772 char_u nbuf[NUMBUFLEN];
15773 tabpage_T *tp;
15775 if (check_restricted() || check_secure())
15776 return;
15778 #ifdef FEAT_WINDOWS
15779 if (off == 1)
15780 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
15781 else
15782 tp = curtab;
15783 #endif
15784 win = find_win_by_nr(&argvars[off], tp);
15785 varname = get_tv_string_chk(&argvars[off + 1]);
15786 varp = &argvars[off + 2];
15788 if (win != NULL && varname != NULL && varp != NULL)
15790 #ifdef FEAT_WINDOWS
15791 /* set curwin to be our win, temporarily */
15792 save_curwin = curwin;
15793 save_curtab = curtab;
15794 goto_tabpage_tp(tp);
15795 if (!win_valid(win))
15796 return;
15797 curwin = win;
15798 curbuf = curwin->w_buffer;
15799 #endif
15801 if (*varname == '&')
15803 long numval;
15804 char_u *strval;
15805 int error = FALSE;
15807 ++varname;
15808 numval = get_tv_number_chk(varp, &error);
15809 strval = get_tv_string_buf_chk(varp, nbuf);
15810 if (!error && strval != NULL)
15811 set_option_value(varname, numval, strval, OPT_LOCAL);
15813 else
15815 winvarname = alloc((unsigned)STRLEN(varname) + 3);
15816 if (winvarname != NULL)
15818 STRCPY(winvarname, "w:");
15819 STRCPY(winvarname + 2, varname);
15820 set_var(winvarname, varp, TRUE);
15821 vim_free(winvarname);
15825 #ifdef FEAT_WINDOWS
15826 /* Restore current tabpage and window, if still valid (autocomands can
15827 * make them invalid). */
15828 if (valid_tabpage(save_curtab))
15829 goto_tabpage_tp(save_curtab);
15830 if (win_valid(save_curwin))
15832 curwin = save_curwin;
15833 curbuf = curwin->w_buffer;
15835 #endif
15840 * "shellescape({string})" function
15842 static void
15843 f_shellescape(argvars, rettv)
15844 typval_T *argvars;
15845 typval_T *rettv;
15847 rettv->vval.v_string = vim_strsave_shellescape(
15848 get_tv_string(&argvars[0]), non_zero_arg(&argvars[1]));
15849 rettv->v_type = VAR_STRING;
15853 * "simplify()" function
15855 static void
15856 f_simplify(argvars, rettv)
15857 typval_T *argvars;
15858 typval_T *rettv;
15860 char_u *p;
15862 p = get_tv_string(&argvars[0]);
15863 rettv->vval.v_string = vim_strsave(p);
15864 simplify_filename(rettv->vval.v_string); /* simplify in place */
15865 rettv->v_type = VAR_STRING;
15868 #ifdef FEAT_FLOAT
15870 * "sin()" function
15872 static void
15873 f_sin(argvars, rettv)
15874 typval_T *argvars;
15875 typval_T *rettv;
15877 float_T f;
15879 rettv->v_type = VAR_FLOAT;
15880 if (get_float_arg(argvars, &f) == OK)
15881 rettv->vval.v_float = sin(f);
15882 else
15883 rettv->vval.v_float = 0.0;
15885 #endif
15887 static int
15888 #ifdef __BORLANDC__
15889 _RTLENTRYF
15890 #endif
15891 item_compare __ARGS((const void *s1, const void *s2));
15892 static int
15893 #ifdef __BORLANDC__
15894 _RTLENTRYF
15895 #endif
15896 item_compare2 __ARGS((const void *s1, const void *s2));
15898 static int item_compare_ic;
15899 static char_u *item_compare_func;
15900 static int item_compare_func_err;
15901 #define ITEM_COMPARE_FAIL 999
15904 * Compare functions for f_sort() below.
15906 static int
15907 #ifdef __BORLANDC__
15908 _RTLENTRYF
15909 #endif
15910 item_compare(s1, s2)
15911 const void *s1;
15912 const void *s2;
15914 char_u *p1, *p2;
15915 char_u *tofree1, *tofree2;
15916 int res;
15917 char_u numbuf1[NUMBUFLEN];
15918 char_u numbuf2[NUMBUFLEN];
15920 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
15921 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
15922 if (p1 == NULL)
15923 p1 = (char_u *)"";
15924 if (p2 == NULL)
15925 p2 = (char_u *)"";
15926 if (item_compare_ic)
15927 res = STRICMP(p1, p2);
15928 else
15929 res = STRCMP(p1, p2);
15930 vim_free(tofree1);
15931 vim_free(tofree2);
15932 return res;
15935 static int
15936 #ifdef __BORLANDC__
15937 _RTLENTRYF
15938 #endif
15939 item_compare2(s1, s2)
15940 const void *s1;
15941 const void *s2;
15943 int res;
15944 typval_T rettv;
15945 typval_T argv[3];
15946 int dummy;
15948 /* shortcut after failure in previous call; compare all items equal */
15949 if (item_compare_func_err)
15950 return 0;
15952 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
15953 * in the copy without changing the original list items. */
15954 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
15955 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
15957 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
15958 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
15959 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
15960 clear_tv(&argv[0]);
15961 clear_tv(&argv[1]);
15963 if (res == FAIL)
15964 res = ITEM_COMPARE_FAIL;
15965 else
15966 res = get_tv_number_chk(&rettv, &item_compare_func_err);
15967 if (item_compare_func_err)
15968 res = ITEM_COMPARE_FAIL; /* return value has wrong type */
15969 clear_tv(&rettv);
15970 return res;
15974 * "sort({list})" function
15976 static void
15977 f_sort(argvars, rettv)
15978 typval_T *argvars;
15979 typval_T *rettv;
15981 list_T *l;
15982 listitem_T *li;
15983 listitem_T **ptrs;
15984 long len;
15985 long i;
15987 if (argvars[0].v_type != VAR_LIST)
15988 EMSG2(_(e_listarg), "sort()");
15989 else
15991 l = argvars[0].vval.v_list;
15992 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
15993 return;
15994 rettv->vval.v_list = l;
15995 rettv->v_type = VAR_LIST;
15996 ++l->lv_refcount;
15998 len = list_len(l);
15999 if (len <= 1)
16000 return; /* short list sorts pretty quickly */
16002 item_compare_ic = FALSE;
16003 item_compare_func = NULL;
16004 if (argvars[1].v_type != VAR_UNKNOWN)
16006 if (argvars[1].v_type == VAR_FUNC)
16007 item_compare_func = argvars[1].vval.v_string;
16008 else
16010 int error = FALSE;
16012 i = get_tv_number_chk(&argvars[1], &error);
16013 if (error)
16014 return; /* type error; errmsg already given */
16015 if (i == 1)
16016 item_compare_ic = TRUE;
16017 else
16018 item_compare_func = get_tv_string(&argvars[1]);
16022 /* Make an array with each entry pointing to an item in the List. */
16023 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
16024 if (ptrs == NULL)
16025 return;
16026 i = 0;
16027 for (li = l->lv_first; li != NULL; li = li->li_next)
16028 ptrs[i++] = li;
16030 item_compare_func_err = FALSE;
16031 /* test the compare function */
16032 if (item_compare_func != NULL
16033 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
16034 == ITEM_COMPARE_FAIL)
16035 EMSG(_("E702: Sort compare function failed"));
16036 else
16038 /* Sort the array with item pointers. */
16039 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
16040 item_compare_func == NULL ? item_compare : item_compare2);
16042 if (!item_compare_func_err)
16044 /* Clear the List and append the items in the sorted order. */
16045 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
16046 l->lv_len = 0;
16047 for (i = 0; i < len; ++i)
16048 list_append(l, ptrs[i]);
16052 vim_free(ptrs);
16057 * "soundfold({word})" function
16059 static void
16060 f_soundfold(argvars, rettv)
16061 typval_T *argvars;
16062 typval_T *rettv;
16064 char_u *s;
16066 rettv->v_type = VAR_STRING;
16067 s = get_tv_string(&argvars[0]);
16068 #ifdef FEAT_SPELL
16069 rettv->vval.v_string = eval_soundfold(s);
16070 #else
16071 rettv->vval.v_string = vim_strsave(s);
16072 #endif
16076 * "spellbadword()" function
16078 static void
16079 f_spellbadword(argvars, rettv)
16080 typval_T *argvars UNUSED;
16081 typval_T *rettv;
16083 char_u *word = (char_u *)"";
16084 hlf_T attr = HLF_COUNT;
16085 int len = 0;
16087 if (rettv_list_alloc(rettv) == FAIL)
16088 return;
16090 #ifdef FEAT_SPELL
16091 if (argvars[0].v_type == VAR_UNKNOWN)
16093 /* Find the start and length of the badly spelled word. */
16094 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
16095 if (len != 0)
16096 word = ml_get_cursor();
16098 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16100 char_u *str = get_tv_string_chk(&argvars[0]);
16101 int capcol = -1;
16103 if (str != NULL)
16105 /* Check the argument for spelling. */
16106 while (*str != NUL)
16108 len = spell_check(curwin, str, &attr, &capcol, FALSE);
16109 if (attr != HLF_COUNT)
16111 word = str;
16112 break;
16114 str += len;
16118 #endif
16120 list_append_string(rettv->vval.v_list, word, len);
16121 list_append_string(rettv->vval.v_list, (char_u *)(
16122 attr == HLF_SPB ? "bad" :
16123 attr == HLF_SPR ? "rare" :
16124 attr == HLF_SPL ? "local" :
16125 attr == HLF_SPC ? "caps" :
16126 ""), -1);
16130 * "spellsuggest()" function
16132 static void
16133 f_spellsuggest(argvars, rettv)
16134 typval_T *argvars UNUSED;
16135 typval_T *rettv;
16137 #ifdef FEAT_SPELL
16138 char_u *str;
16139 int typeerr = FALSE;
16140 int maxcount;
16141 garray_T ga;
16142 int i;
16143 listitem_T *li;
16144 int need_capital = FALSE;
16145 #endif
16147 if (rettv_list_alloc(rettv) == FAIL)
16148 return;
16150 #ifdef FEAT_SPELL
16151 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16153 str = get_tv_string(&argvars[0]);
16154 if (argvars[1].v_type != VAR_UNKNOWN)
16156 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
16157 if (maxcount <= 0)
16158 return;
16159 if (argvars[2].v_type != VAR_UNKNOWN)
16161 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
16162 if (typeerr)
16163 return;
16166 else
16167 maxcount = 25;
16169 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
16171 for (i = 0; i < ga.ga_len; ++i)
16173 str = ((char_u **)ga.ga_data)[i];
16175 li = listitem_alloc();
16176 if (li == NULL)
16177 vim_free(str);
16178 else
16180 li->li_tv.v_type = VAR_STRING;
16181 li->li_tv.v_lock = 0;
16182 li->li_tv.vval.v_string = str;
16183 list_append(rettv->vval.v_list, li);
16186 ga_clear(&ga);
16188 #endif
16191 static void
16192 f_split(argvars, rettv)
16193 typval_T *argvars;
16194 typval_T *rettv;
16196 char_u *str;
16197 char_u *end;
16198 char_u *pat = NULL;
16199 regmatch_T regmatch;
16200 char_u patbuf[NUMBUFLEN];
16201 char_u *save_cpo;
16202 int match;
16203 colnr_T col = 0;
16204 int keepempty = FALSE;
16205 int typeerr = FALSE;
16207 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
16208 save_cpo = p_cpo;
16209 p_cpo = (char_u *)"";
16211 str = get_tv_string(&argvars[0]);
16212 if (argvars[1].v_type != VAR_UNKNOWN)
16214 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16215 if (pat == NULL)
16216 typeerr = TRUE;
16217 if (argvars[2].v_type != VAR_UNKNOWN)
16218 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
16220 if (pat == NULL || *pat == NUL)
16221 pat = (char_u *)"[\\x01- ]\\+";
16223 if (rettv_list_alloc(rettv) == FAIL)
16224 return;
16225 if (typeerr)
16226 return;
16228 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
16229 if (regmatch.regprog != NULL)
16231 regmatch.rm_ic = FALSE;
16232 while (*str != NUL || keepempty)
16234 if (*str == NUL)
16235 match = FALSE; /* empty item at the end */
16236 else
16237 match = vim_regexec_nl(&regmatch, str, col);
16238 if (match)
16239 end = regmatch.startp[0];
16240 else
16241 end = str + STRLEN(str);
16242 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
16243 && *str != NUL && match && end < regmatch.endp[0]))
16245 if (list_append_string(rettv->vval.v_list, str,
16246 (int)(end - str)) == FAIL)
16247 break;
16249 if (!match)
16250 break;
16251 /* Advance to just after the match. */
16252 if (regmatch.endp[0] > str)
16253 col = 0;
16254 else
16256 /* Don't get stuck at the same match. */
16257 #ifdef FEAT_MBYTE
16258 col = (*mb_ptr2len)(regmatch.endp[0]);
16259 #else
16260 col = 1;
16261 #endif
16263 str = regmatch.endp[0];
16266 vim_free(regmatch.regprog);
16269 p_cpo = save_cpo;
16272 #ifdef FEAT_FLOAT
16274 * "sqrt()" function
16276 static void
16277 f_sqrt(argvars, rettv)
16278 typval_T *argvars;
16279 typval_T *rettv;
16281 float_T f;
16283 rettv->v_type = VAR_FLOAT;
16284 if (get_float_arg(argvars, &f) == OK)
16285 rettv->vval.v_float = sqrt(f);
16286 else
16287 rettv->vval.v_float = 0.0;
16291 * "str2float()" function
16293 static void
16294 f_str2float(argvars, rettv)
16295 typval_T *argvars;
16296 typval_T *rettv;
16298 char_u *p = skipwhite(get_tv_string(&argvars[0]));
16300 if (*p == '+')
16301 p = skipwhite(p + 1);
16302 (void)string2float(p, &rettv->vval.v_float);
16303 rettv->v_type = VAR_FLOAT;
16305 #endif
16308 * "str2nr()" function
16310 static void
16311 f_str2nr(argvars, rettv)
16312 typval_T *argvars;
16313 typval_T *rettv;
16315 int base = 10;
16316 char_u *p;
16317 long n;
16319 if (argvars[1].v_type != VAR_UNKNOWN)
16321 base = get_tv_number(&argvars[1]);
16322 if (base != 8 && base != 10 && base != 16)
16324 EMSG(_(e_invarg));
16325 return;
16329 p = skipwhite(get_tv_string(&argvars[0]));
16330 if (*p == '+')
16331 p = skipwhite(p + 1);
16332 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
16333 rettv->vval.v_number = n;
16336 #ifdef HAVE_STRFTIME
16338 * "strftime({format}[, {time}])" function
16340 static void
16341 f_strftime(argvars, rettv)
16342 typval_T *argvars;
16343 typval_T *rettv;
16345 char_u result_buf[256];
16346 struct tm *curtime;
16347 time_t seconds;
16348 char_u *p;
16350 rettv->v_type = VAR_STRING;
16352 p = get_tv_string(&argvars[0]);
16353 if (argvars[1].v_type == VAR_UNKNOWN)
16354 seconds = time(NULL);
16355 else
16356 seconds = (time_t)get_tv_number(&argvars[1]);
16357 curtime = localtime(&seconds);
16358 /* MSVC returns NULL for an invalid value of seconds. */
16359 if (curtime == NULL)
16360 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
16361 else
16363 # ifdef FEAT_MBYTE
16364 vimconv_T conv;
16365 char_u *enc;
16367 conv.vc_type = CONV_NONE;
16368 enc = enc_locale();
16369 convert_setup(&conv, p_enc, enc);
16370 if (conv.vc_type != CONV_NONE)
16371 p = string_convert(&conv, p, NULL);
16372 # endif
16373 if (p != NULL)
16374 (void)strftime((char *)result_buf, sizeof(result_buf),
16375 (char *)p, curtime);
16376 else
16377 result_buf[0] = NUL;
16379 # ifdef FEAT_MBYTE
16380 if (conv.vc_type != CONV_NONE)
16381 vim_free(p);
16382 convert_setup(&conv, enc, p_enc);
16383 if (conv.vc_type != CONV_NONE)
16384 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
16385 else
16386 # endif
16387 rettv->vval.v_string = vim_strsave(result_buf);
16389 # ifdef FEAT_MBYTE
16390 /* Release conversion descriptors */
16391 convert_setup(&conv, NULL, NULL);
16392 vim_free(enc);
16393 # endif
16396 #endif
16399 * "stridx()" function
16401 static void
16402 f_stridx(argvars, rettv)
16403 typval_T *argvars;
16404 typval_T *rettv;
16406 char_u buf[NUMBUFLEN];
16407 char_u *needle;
16408 char_u *haystack;
16409 char_u *save_haystack;
16410 char_u *pos;
16411 int start_idx;
16413 needle = get_tv_string_chk(&argvars[1]);
16414 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
16415 rettv->vval.v_number = -1;
16416 if (needle == NULL || haystack == NULL)
16417 return; /* type error; errmsg already given */
16419 if (argvars[2].v_type != VAR_UNKNOWN)
16421 int error = FALSE;
16423 start_idx = get_tv_number_chk(&argvars[2], &error);
16424 if (error || start_idx >= (int)STRLEN(haystack))
16425 return;
16426 if (start_idx >= 0)
16427 haystack += start_idx;
16430 pos = (char_u *)strstr((char *)haystack, (char *)needle);
16431 if (pos != NULL)
16432 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
16436 * "string()" function
16438 static void
16439 f_string(argvars, rettv)
16440 typval_T *argvars;
16441 typval_T *rettv;
16443 char_u *tofree;
16444 char_u numbuf[NUMBUFLEN];
16446 rettv->v_type = VAR_STRING;
16447 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
16448 /* Make a copy if we have a value but it's not in allocated memory. */
16449 if (rettv->vval.v_string != NULL && tofree == NULL)
16450 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
16454 * "strlen()" function
16456 static void
16457 f_strlen(argvars, rettv)
16458 typval_T *argvars;
16459 typval_T *rettv;
16461 rettv->vval.v_number = (varnumber_T)(STRLEN(
16462 get_tv_string(&argvars[0])));
16466 * "strpart()" function
16468 static void
16469 f_strpart(argvars, rettv)
16470 typval_T *argvars;
16471 typval_T *rettv;
16473 char_u *p;
16474 int n;
16475 int len;
16476 int slen;
16477 int error = FALSE;
16479 p = get_tv_string(&argvars[0]);
16480 slen = (int)STRLEN(p);
16482 n = get_tv_number_chk(&argvars[1], &error);
16483 if (error)
16484 len = 0;
16485 else if (argvars[2].v_type != VAR_UNKNOWN)
16486 len = get_tv_number(&argvars[2]);
16487 else
16488 len = slen - n; /* default len: all bytes that are available. */
16491 * Only return the overlap between the specified part and the actual
16492 * string.
16494 if (n < 0)
16496 len += n;
16497 n = 0;
16499 else if (n > slen)
16500 n = slen;
16501 if (len < 0)
16502 len = 0;
16503 else if (n + len > slen)
16504 len = slen - n;
16506 rettv->v_type = VAR_STRING;
16507 rettv->vval.v_string = vim_strnsave(p + n, len);
16511 * "strridx()" function
16513 static void
16514 f_strridx(argvars, rettv)
16515 typval_T *argvars;
16516 typval_T *rettv;
16518 char_u buf[NUMBUFLEN];
16519 char_u *needle;
16520 char_u *haystack;
16521 char_u *rest;
16522 char_u *lastmatch = NULL;
16523 int haystack_len, end_idx;
16525 needle = get_tv_string_chk(&argvars[1]);
16526 haystack = get_tv_string_buf_chk(&argvars[0], buf);
16528 rettv->vval.v_number = -1;
16529 if (needle == NULL || haystack == NULL)
16530 return; /* type error; errmsg already given */
16532 haystack_len = (int)STRLEN(haystack);
16533 if (argvars[2].v_type != VAR_UNKNOWN)
16535 /* Third argument: upper limit for index */
16536 end_idx = get_tv_number_chk(&argvars[2], NULL);
16537 if (end_idx < 0)
16538 return; /* can never find a match */
16540 else
16541 end_idx = haystack_len;
16543 if (*needle == NUL)
16545 /* Empty string matches past the end. */
16546 lastmatch = haystack + end_idx;
16548 else
16550 for (rest = haystack; *rest != '\0'; ++rest)
16552 rest = (char_u *)strstr((char *)rest, (char *)needle);
16553 if (rest == NULL || rest > haystack + end_idx)
16554 break;
16555 lastmatch = rest;
16559 if (lastmatch == NULL)
16560 rettv->vval.v_number = -1;
16561 else
16562 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
16566 * "strtrans()" function
16568 static void
16569 f_strtrans(argvars, rettv)
16570 typval_T *argvars;
16571 typval_T *rettv;
16573 rettv->v_type = VAR_STRING;
16574 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
16578 * "submatch()" function
16580 static void
16581 f_submatch(argvars, rettv)
16582 typval_T *argvars;
16583 typval_T *rettv;
16585 rettv->v_type = VAR_STRING;
16586 rettv->vval.v_string =
16587 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
16591 * "substitute()" function
16593 static void
16594 f_substitute(argvars, rettv)
16595 typval_T *argvars;
16596 typval_T *rettv;
16598 char_u patbuf[NUMBUFLEN];
16599 char_u subbuf[NUMBUFLEN];
16600 char_u flagsbuf[NUMBUFLEN];
16602 char_u *str = get_tv_string_chk(&argvars[0]);
16603 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16604 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
16605 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
16607 rettv->v_type = VAR_STRING;
16608 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
16609 rettv->vval.v_string = NULL;
16610 else
16611 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
16615 * "synID(lnum, col, trans)" function
16617 static void
16618 f_synID(argvars, rettv)
16619 typval_T *argvars UNUSED;
16620 typval_T *rettv;
16622 int id = 0;
16623 #ifdef FEAT_SYN_HL
16624 long lnum;
16625 long col;
16626 int trans;
16627 int transerr = FALSE;
16629 lnum = get_tv_lnum(argvars); /* -1 on type error */
16630 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16631 trans = get_tv_number_chk(&argvars[2], &transerr);
16633 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16634 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
16635 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
16636 #endif
16638 rettv->vval.v_number = id;
16642 * "synIDattr(id, what [, mode])" function
16644 static void
16645 f_synIDattr(argvars, rettv)
16646 typval_T *argvars UNUSED;
16647 typval_T *rettv;
16649 char_u *p = NULL;
16650 #ifdef FEAT_SYN_HL
16651 int id;
16652 char_u *what;
16653 char_u *mode;
16654 char_u modebuf[NUMBUFLEN];
16655 int modec;
16657 id = get_tv_number(&argvars[0]);
16658 what = get_tv_string(&argvars[1]);
16659 if (argvars[2].v_type != VAR_UNKNOWN)
16661 mode = get_tv_string_buf(&argvars[2], modebuf);
16662 modec = TOLOWER_ASC(mode[0]);
16663 if (modec != 't' && modec != 'c'
16664 #ifdef FEAT_GUI
16665 && modec != 'g'
16666 #endif
16668 modec = 0; /* replace invalid with current */
16670 else
16672 #ifdef FEAT_GUI
16673 if (gui.in_use)
16674 modec = 'g';
16675 else
16676 #endif
16677 if (t_colors > 1)
16678 modec = 'c';
16679 else
16680 modec = 't';
16684 switch (TOLOWER_ASC(what[0]))
16686 case 'b':
16687 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
16688 p = highlight_color(id, what, modec);
16689 else /* bold */
16690 p = highlight_has_attr(id, HL_BOLD, modec);
16691 break;
16693 case 'f': /* fg[#] or font */
16694 p = highlight_color(id, what, modec);
16695 break;
16697 case 'i':
16698 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
16699 p = highlight_has_attr(id, HL_INVERSE, modec);
16700 else /* italic */
16701 p = highlight_has_attr(id, HL_ITALIC, modec);
16702 break;
16704 case 'n': /* name */
16705 p = get_highlight_name(NULL, id - 1);
16706 break;
16708 case 'r': /* reverse */
16709 p = highlight_has_attr(id, HL_INVERSE, modec);
16710 break;
16712 case 's':
16713 if (TOLOWER_ASC(what[1]) == 'p') /* sp[#] */
16714 p = highlight_color(id, what, modec);
16715 else /* standout */
16716 p = highlight_has_attr(id, HL_STANDOUT, modec);
16717 break;
16719 case 'u':
16720 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
16721 /* underline */
16722 p = highlight_has_attr(id, HL_UNDERLINE, modec);
16723 else
16724 /* undercurl */
16725 p = highlight_has_attr(id, HL_UNDERCURL, modec);
16726 break;
16729 if (p != NULL)
16730 p = vim_strsave(p);
16731 #endif
16732 rettv->v_type = VAR_STRING;
16733 rettv->vval.v_string = p;
16737 * "synIDtrans(id)" function
16739 static void
16740 f_synIDtrans(argvars, rettv)
16741 typval_T *argvars UNUSED;
16742 typval_T *rettv;
16744 int id;
16746 #ifdef FEAT_SYN_HL
16747 id = get_tv_number(&argvars[0]);
16749 if (id > 0)
16750 id = syn_get_final_id(id);
16751 else
16752 #endif
16753 id = 0;
16755 rettv->vval.v_number = id;
16759 * "synstack(lnum, col)" function
16761 static void
16762 f_synstack(argvars, rettv)
16763 typval_T *argvars UNUSED;
16764 typval_T *rettv;
16766 #ifdef FEAT_SYN_HL
16767 long lnum;
16768 long col;
16769 int i;
16770 int id;
16771 #endif
16773 rettv->v_type = VAR_LIST;
16774 rettv->vval.v_list = NULL;
16776 #ifdef FEAT_SYN_HL
16777 lnum = get_tv_lnum(argvars); /* -1 on type error */
16778 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16780 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16781 && col >= 0 && (col == 0 || col < (long)STRLEN(ml_get(lnum)))
16782 && rettv_list_alloc(rettv) != FAIL)
16784 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
16785 for (i = 0; ; ++i)
16787 id = syn_get_stack_item(i);
16788 if (id < 0)
16789 break;
16790 if (list_append_number(rettv->vval.v_list, id) == FAIL)
16791 break;
16794 #endif
16798 * "system()" function
16800 static void
16801 f_system(argvars, rettv)
16802 typval_T *argvars;
16803 typval_T *rettv;
16805 char_u *res = NULL;
16806 char_u *p;
16807 char_u *infile = NULL;
16808 char_u buf[NUMBUFLEN];
16809 int err = FALSE;
16810 FILE *fd;
16812 if (check_restricted() || check_secure())
16813 goto done;
16815 if (argvars[1].v_type != VAR_UNKNOWN)
16818 * Write the string to a temp file, to be used for input of the shell
16819 * command.
16821 if ((infile = vim_tempname('i')) == NULL)
16823 EMSG(_(e_notmp));
16824 goto done;
16827 fd = mch_fopen((char *)infile, WRITEBIN);
16828 if (fd == NULL)
16830 EMSG2(_(e_notopen), infile);
16831 goto done;
16833 p = get_tv_string_buf_chk(&argvars[1], buf);
16834 if (p == NULL)
16836 fclose(fd);
16837 goto done; /* type error; errmsg already given */
16839 if (fwrite(p, STRLEN(p), 1, fd) != 1)
16840 err = TRUE;
16841 if (fclose(fd) != 0)
16842 err = TRUE;
16843 if (err)
16845 EMSG(_("E677: Error writing temp file"));
16846 goto done;
16850 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
16851 SHELL_SILENT | SHELL_COOKED);
16853 #ifdef USE_CR
16854 /* translate <CR> into <NL> */
16855 if (res != NULL)
16857 char_u *s;
16859 for (s = res; *s; ++s)
16861 if (*s == CAR)
16862 *s = NL;
16865 #else
16866 # ifdef USE_CRNL
16867 /* translate <CR><NL> into <NL> */
16868 if (res != NULL)
16870 char_u *s, *d;
16872 d = res;
16873 for (s = res; *s; ++s)
16875 if (s[0] == CAR && s[1] == NL)
16876 ++s;
16877 *d++ = *s;
16879 *d = NUL;
16881 # endif
16882 #endif
16884 done:
16885 if (infile != NULL)
16887 mch_remove(infile);
16888 vim_free(infile);
16890 rettv->v_type = VAR_STRING;
16891 rettv->vval.v_string = res;
16895 * "tabpagebuflist()" function
16897 static void
16898 f_tabpagebuflist(argvars, rettv)
16899 typval_T *argvars UNUSED;
16900 typval_T *rettv UNUSED;
16902 #ifdef FEAT_WINDOWS
16903 tabpage_T *tp;
16904 win_T *wp = NULL;
16906 if (argvars[0].v_type == VAR_UNKNOWN)
16907 wp = firstwin;
16908 else
16910 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16911 if (tp != NULL)
16912 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16914 if (wp != NULL && rettv_list_alloc(rettv) != FAIL)
16916 for (; wp != NULL; wp = wp->w_next)
16917 if (list_append_number(rettv->vval.v_list,
16918 wp->w_buffer->b_fnum) == FAIL)
16919 break;
16921 #endif
16926 * "tabpagenr()" function
16928 static void
16929 f_tabpagenr(argvars, rettv)
16930 typval_T *argvars UNUSED;
16931 typval_T *rettv;
16933 int nr = 1;
16934 #ifdef FEAT_WINDOWS
16935 char_u *arg;
16937 if (argvars[0].v_type != VAR_UNKNOWN)
16939 arg = get_tv_string_chk(&argvars[0]);
16940 nr = 0;
16941 if (arg != NULL)
16943 if (STRCMP(arg, "$") == 0)
16944 nr = tabpage_index(NULL) - 1;
16945 else
16946 EMSG2(_(e_invexpr2), arg);
16949 else
16950 nr = tabpage_index(curtab);
16951 #endif
16952 rettv->vval.v_number = nr;
16956 #ifdef FEAT_WINDOWS
16957 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
16960 * Common code for tabpagewinnr() and winnr().
16962 static int
16963 get_winnr(tp, argvar)
16964 tabpage_T *tp;
16965 typval_T *argvar;
16967 win_T *twin;
16968 int nr = 1;
16969 win_T *wp;
16970 char_u *arg;
16972 twin = (tp == curtab) ? curwin : tp->tp_curwin;
16973 if (argvar->v_type != VAR_UNKNOWN)
16975 arg = get_tv_string_chk(argvar);
16976 if (arg == NULL)
16977 nr = 0; /* type error; errmsg already given */
16978 else if (STRCMP(arg, "$") == 0)
16979 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
16980 else if (STRCMP(arg, "#") == 0)
16982 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
16983 if (twin == NULL)
16984 nr = 0;
16986 else
16988 EMSG2(_(e_invexpr2), arg);
16989 nr = 0;
16993 if (nr > 0)
16994 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16995 wp != twin; wp = wp->w_next)
16997 if (wp == NULL)
16999 /* didn't find it in this tabpage */
17000 nr = 0;
17001 break;
17003 ++nr;
17005 return nr;
17007 #endif
17010 * "tabpagewinnr()" function
17012 static void
17013 f_tabpagewinnr(argvars, rettv)
17014 typval_T *argvars UNUSED;
17015 typval_T *rettv;
17017 int nr = 1;
17018 #ifdef FEAT_WINDOWS
17019 tabpage_T *tp;
17021 tp = find_tabpage((int)get_tv_number(&argvars[0]));
17022 if (tp == NULL)
17023 nr = 0;
17024 else
17025 nr = get_winnr(tp, &argvars[1]);
17026 #endif
17027 rettv->vval.v_number = nr;
17032 * "tagfiles()" function
17034 static void
17035 f_tagfiles(argvars, rettv)
17036 typval_T *argvars UNUSED;
17037 typval_T *rettv;
17039 char_u fname[MAXPATHL + 1];
17040 tagname_T tn;
17041 int first;
17043 if (rettv_list_alloc(rettv) == FAIL)
17044 return;
17046 for (first = TRUE; ; first = FALSE)
17047 if (get_tagfname(&tn, first, fname) == FAIL
17048 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
17049 break;
17050 tagname_free(&tn);
17054 * "taglist()" function
17056 static void
17057 f_taglist(argvars, rettv)
17058 typval_T *argvars;
17059 typval_T *rettv;
17061 char_u *tag_pattern;
17063 tag_pattern = get_tv_string(&argvars[0]);
17065 rettv->vval.v_number = FALSE;
17066 if (*tag_pattern == NUL)
17067 return;
17069 if (rettv_list_alloc(rettv) == OK)
17070 (void)get_tags(rettv->vval.v_list, tag_pattern);
17074 * "tempname()" function
17076 static void
17077 f_tempname(argvars, rettv)
17078 typval_T *argvars UNUSED;
17079 typval_T *rettv;
17081 static int x = 'A';
17083 rettv->v_type = VAR_STRING;
17084 rettv->vval.v_string = vim_tempname(x);
17086 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
17087 * names. Skip 'I' and 'O', they are used for shell redirection. */
17090 if (x == 'Z')
17091 x = '0';
17092 else if (x == '9')
17093 x = 'A';
17094 else
17096 #ifdef EBCDIC
17097 if (x == 'I')
17098 x = 'J';
17099 else if (x == 'R')
17100 x = 'S';
17101 else
17102 #endif
17103 ++x;
17105 } while (x == 'I' || x == 'O');
17109 * "test(list)" function: Just checking the walls...
17111 static void
17112 f_test(argvars, rettv)
17113 typval_T *argvars UNUSED;
17114 typval_T *rettv UNUSED;
17116 /* Used for unit testing. Change the code below to your liking. */
17117 #if 0
17118 listitem_T *li;
17119 list_T *l;
17120 char_u *bad, *good;
17122 if (argvars[0].v_type != VAR_LIST)
17123 return;
17124 l = argvars[0].vval.v_list;
17125 if (l == NULL)
17126 return;
17127 li = l->lv_first;
17128 if (li == NULL)
17129 return;
17130 bad = get_tv_string(&li->li_tv);
17131 li = li->li_next;
17132 if (li == NULL)
17133 return;
17134 good = get_tv_string(&li->li_tv);
17135 rettv->vval.v_number = test_edit_score(bad, good);
17136 #endif
17140 * "tolower(string)" function
17142 static void
17143 f_tolower(argvars, rettv)
17144 typval_T *argvars;
17145 typval_T *rettv;
17147 char_u *p;
17149 p = vim_strsave(get_tv_string(&argvars[0]));
17150 rettv->v_type = VAR_STRING;
17151 rettv->vval.v_string = p;
17153 if (p != NULL)
17154 while (*p != NUL)
17156 #ifdef FEAT_MBYTE
17157 int l;
17159 if (enc_utf8)
17161 int c, lc;
17163 c = utf_ptr2char(p);
17164 lc = utf_tolower(c);
17165 l = utf_ptr2len(p);
17166 /* TODO: reallocate string when byte count changes. */
17167 if (utf_char2len(lc) == l)
17168 utf_char2bytes(lc, p);
17169 p += l;
17171 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
17172 p += l; /* skip multi-byte character */
17173 else
17174 #endif
17176 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
17177 ++p;
17183 * "toupper(string)" function
17185 static void
17186 f_toupper(argvars, rettv)
17187 typval_T *argvars;
17188 typval_T *rettv;
17190 rettv->v_type = VAR_STRING;
17191 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
17195 * "tr(string, fromstr, tostr)" function
17197 static void
17198 f_tr(argvars, rettv)
17199 typval_T *argvars;
17200 typval_T *rettv;
17202 char_u *instr;
17203 char_u *fromstr;
17204 char_u *tostr;
17205 char_u *p;
17206 #ifdef FEAT_MBYTE
17207 int inlen;
17208 int fromlen;
17209 int tolen;
17210 int idx;
17211 char_u *cpstr;
17212 int cplen;
17213 int first = TRUE;
17214 #endif
17215 char_u buf[NUMBUFLEN];
17216 char_u buf2[NUMBUFLEN];
17217 garray_T ga;
17219 instr = get_tv_string(&argvars[0]);
17220 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
17221 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
17223 /* Default return value: empty string. */
17224 rettv->v_type = VAR_STRING;
17225 rettv->vval.v_string = NULL;
17226 if (fromstr == NULL || tostr == NULL)
17227 return; /* type error; errmsg already given */
17228 ga_init2(&ga, (int)sizeof(char), 80);
17230 #ifdef FEAT_MBYTE
17231 if (!has_mbyte)
17232 #endif
17233 /* not multi-byte: fromstr and tostr must be the same length */
17234 if (STRLEN(fromstr) != STRLEN(tostr))
17236 #ifdef FEAT_MBYTE
17237 error:
17238 #endif
17239 EMSG2(_(e_invarg2), fromstr);
17240 ga_clear(&ga);
17241 return;
17244 /* fromstr and tostr have to contain the same number of chars */
17245 while (*instr != NUL)
17247 #ifdef FEAT_MBYTE
17248 if (has_mbyte)
17250 inlen = (*mb_ptr2len)(instr);
17251 cpstr = instr;
17252 cplen = inlen;
17253 idx = 0;
17254 for (p = fromstr; *p != NUL; p += fromlen)
17256 fromlen = (*mb_ptr2len)(p);
17257 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
17259 for (p = tostr; *p != NUL; p += tolen)
17261 tolen = (*mb_ptr2len)(p);
17262 if (idx-- == 0)
17264 cplen = tolen;
17265 cpstr = p;
17266 break;
17269 if (*p == NUL) /* tostr is shorter than fromstr */
17270 goto error;
17271 break;
17273 ++idx;
17276 if (first && cpstr == instr)
17278 /* Check that fromstr and tostr have the same number of
17279 * (multi-byte) characters. Done only once when a character
17280 * of instr doesn't appear in fromstr. */
17281 first = FALSE;
17282 for (p = tostr; *p != NUL; p += tolen)
17284 tolen = (*mb_ptr2len)(p);
17285 --idx;
17287 if (idx != 0)
17288 goto error;
17291 ga_grow(&ga, cplen);
17292 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
17293 ga.ga_len += cplen;
17295 instr += inlen;
17297 else
17298 #endif
17300 /* When not using multi-byte chars we can do it faster. */
17301 p = vim_strchr(fromstr, *instr);
17302 if (p != NULL)
17303 ga_append(&ga, tostr[p - fromstr]);
17304 else
17305 ga_append(&ga, *instr);
17306 ++instr;
17310 /* add a terminating NUL */
17311 ga_grow(&ga, 1);
17312 ga_append(&ga, NUL);
17314 rettv->vval.v_string = ga.ga_data;
17317 #ifdef FEAT_FLOAT
17319 * "trunc({float})" function
17321 static void
17322 f_trunc(argvars, rettv)
17323 typval_T *argvars;
17324 typval_T *rettv;
17326 float_T f;
17328 rettv->v_type = VAR_FLOAT;
17329 if (get_float_arg(argvars, &f) == OK)
17330 /* trunc() is not in C90, use floor() or ceil() instead. */
17331 rettv->vval.v_float = f > 0 ? floor(f) : ceil(f);
17332 else
17333 rettv->vval.v_float = 0.0;
17335 #endif
17338 * "type(expr)" function
17340 static void
17341 f_type(argvars, rettv)
17342 typval_T *argvars;
17343 typval_T *rettv;
17345 int n;
17347 switch (argvars[0].v_type)
17349 case VAR_NUMBER: n = 0; break;
17350 case VAR_STRING: n = 1; break;
17351 case VAR_FUNC: n = 2; break;
17352 case VAR_LIST: n = 3; break;
17353 case VAR_DICT: n = 4; break;
17354 #ifdef FEAT_FLOAT
17355 case VAR_FLOAT: n = 5; break;
17356 #endif
17357 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
17359 rettv->vval.v_number = n;
17363 * "values(dict)" function
17365 static void
17366 f_values(argvars, rettv)
17367 typval_T *argvars;
17368 typval_T *rettv;
17370 dict_list(argvars, rettv, 1);
17374 * "virtcol(string)" function
17376 static void
17377 f_virtcol(argvars, rettv)
17378 typval_T *argvars;
17379 typval_T *rettv;
17381 colnr_T vcol = 0;
17382 pos_T *fp;
17383 int fnum = curbuf->b_fnum;
17385 fp = var2fpos(&argvars[0], FALSE, &fnum);
17386 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
17387 && fnum == curbuf->b_fnum)
17389 getvvcol(curwin, fp, NULL, NULL, &vcol);
17390 ++vcol;
17393 rettv->vval.v_number = vcol;
17397 * "visualmode()" function
17399 static void
17400 f_visualmode(argvars, rettv)
17401 typval_T *argvars UNUSED;
17402 typval_T *rettv UNUSED;
17404 #ifdef FEAT_VISUAL
17405 char_u str[2];
17407 rettv->v_type = VAR_STRING;
17408 str[0] = curbuf->b_visual_mode_eval;
17409 str[1] = NUL;
17410 rettv->vval.v_string = vim_strsave(str);
17412 /* A non-zero number or non-empty string argument: reset mode. */
17413 if (non_zero_arg(&argvars[0]))
17414 curbuf->b_visual_mode_eval = NUL;
17415 #endif
17419 * "winbufnr(nr)" function
17421 static void
17422 f_winbufnr(argvars, rettv)
17423 typval_T *argvars;
17424 typval_T *rettv;
17426 win_T *wp;
17428 wp = find_win_by_nr(&argvars[0], NULL);
17429 if (wp == NULL)
17430 rettv->vval.v_number = -1;
17431 else
17432 rettv->vval.v_number = wp->w_buffer->b_fnum;
17436 * "wincol()" function
17438 static void
17439 f_wincol(argvars, rettv)
17440 typval_T *argvars UNUSED;
17441 typval_T *rettv;
17443 validate_cursor();
17444 rettv->vval.v_number = curwin->w_wcol + 1;
17448 * "winheight(nr)" function
17450 static void
17451 f_winheight(argvars, rettv)
17452 typval_T *argvars;
17453 typval_T *rettv;
17455 win_T *wp;
17457 wp = find_win_by_nr(&argvars[0], NULL);
17458 if (wp == NULL)
17459 rettv->vval.v_number = -1;
17460 else
17461 rettv->vval.v_number = wp->w_height;
17465 * "winline()" function
17467 static void
17468 f_winline(argvars, rettv)
17469 typval_T *argvars UNUSED;
17470 typval_T *rettv;
17472 validate_cursor();
17473 rettv->vval.v_number = curwin->w_wrow + 1;
17477 * "winnr()" function
17479 static void
17480 f_winnr(argvars, rettv)
17481 typval_T *argvars UNUSED;
17482 typval_T *rettv;
17484 int nr = 1;
17486 #ifdef FEAT_WINDOWS
17487 nr = get_winnr(curtab, &argvars[0]);
17488 #endif
17489 rettv->vval.v_number = nr;
17493 * "winrestcmd()" function
17495 static void
17496 f_winrestcmd(argvars, rettv)
17497 typval_T *argvars UNUSED;
17498 typval_T *rettv;
17500 #ifdef FEAT_WINDOWS
17501 win_T *wp;
17502 int winnr = 1;
17503 garray_T ga;
17504 char_u buf[50];
17506 ga_init2(&ga, (int)sizeof(char), 70);
17507 for (wp = firstwin; wp != NULL; wp = wp->w_next)
17509 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
17510 ga_concat(&ga, buf);
17511 # ifdef FEAT_VERTSPLIT
17512 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
17513 ga_concat(&ga, buf);
17514 # endif
17515 ++winnr;
17517 ga_append(&ga, NUL);
17519 rettv->vval.v_string = ga.ga_data;
17520 #else
17521 rettv->vval.v_string = NULL;
17522 #endif
17523 rettv->v_type = VAR_STRING;
17527 * "winrestview()" function
17529 static void
17530 f_winrestview(argvars, rettv)
17531 typval_T *argvars;
17532 typval_T *rettv UNUSED;
17534 dict_T *dict;
17536 if (argvars[0].v_type != VAR_DICT
17537 || (dict = argvars[0].vval.v_dict) == NULL)
17538 EMSG(_(e_invarg));
17539 else
17541 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
17542 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
17543 #ifdef FEAT_VIRTUALEDIT
17544 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
17545 #endif
17546 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
17547 curwin->w_set_curswant = FALSE;
17549 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
17550 #ifdef FEAT_DIFF
17551 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
17552 #endif
17553 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
17554 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
17556 check_cursor();
17557 changed_cline_bef_curs();
17558 invalidate_botline();
17559 redraw_later(VALID);
17561 if (curwin->w_topline == 0)
17562 curwin->w_topline = 1;
17563 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
17564 curwin->w_topline = curbuf->b_ml.ml_line_count;
17565 #ifdef FEAT_DIFF
17566 check_topfill(curwin, TRUE);
17567 #endif
17572 * "winsaveview()" function
17574 static void
17575 f_winsaveview(argvars, rettv)
17576 typval_T *argvars UNUSED;
17577 typval_T *rettv;
17579 dict_T *dict;
17581 dict = dict_alloc();
17582 if (dict == NULL)
17583 return;
17584 rettv->v_type = VAR_DICT;
17585 rettv->vval.v_dict = dict;
17586 ++dict->dv_refcount;
17588 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
17589 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
17590 #ifdef FEAT_VIRTUALEDIT
17591 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
17592 #endif
17593 update_curswant();
17594 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
17596 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
17597 #ifdef FEAT_DIFF
17598 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
17599 #endif
17600 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
17601 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
17605 * "winwidth(nr)" function
17607 static void
17608 f_winwidth(argvars, rettv)
17609 typval_T *argvars;
17610 typval_T *rettv;
17612 win_T *wp;
17614 wp = find_win_by_nr(&argvars[0], NULL);
17615 if (wp == NULL)
17616 rettv->vval.v_number = -1;
17617 else
17618 #ifdef FEAT_VERTSPLIT
17619 rettv->vval.v_number = wp->w_width;
17620 #else
17621 rettv->vval.v_number = Columns;
17622 #endif
17626 * "writefile()" function
17628 static void
17629 f_writefile(argvars, rettv)
17630 typval_T *argvars;
17631 typval_T *rettv;
17633 int binary = FALSE;
17634 char_u *fname;
17635 FILE *fd;
17636 listitem_T *li;
17637 char_u *s;
17638 int ret = 0;
17639 int c;
17641 if (check_restricted() || check_secure())
17642 return;
17644 if (argvars[0].v_type != VAR_LIST)
17646 EMSG2(_(e_listarg), "writefile()");
17647 return;
17649 if (argvars[0].vval.v_list == NULL)
17650 return;
17652 if (argvars[2].v_type != VAR_UNKNOWN
17653 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
17654 binary = TRUE;
17656 /* Always open the file in binary mode, library functions have a mind of
17657 * their own about CR-LF conversion. */
17658 fname = get_tv_string(&argvars[1]);
17659 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
17661 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
17662 ret = -1;
17664 else
17666 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
17667 li = li->li_next)
17669 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
17671 if (*s == '\n')
17672 c = putc(NUL, fd);
17673 else
17674 c = putc(*s, fd);
17675 if (c == EOF)
17677 ret = -1;
17678 break;
17681 if (!binary || li->li_next != NULL)
17682 if (putc('\n', fd) == EOF)
17684 ret = -1;
17685 break;
17687 if (ret < 0)
17689 EMSG(_(e_write));
17690 break;
17693 fclose(fd);
17696 rettv->vval.v_number = ret;
17700 * Translate a String variable into a position.
17701 * Returns NULL when there is an error.
17703 static pos_T *
17704 var2fpos(varp, dollar_lnum, fnum)
17705 typval_T *varp;
17706 int dollar_lnum; /* TRUE when $ is last line */
17707 int *fnum; /* set to fnum for '0, 'A, etc. */
17709 char_u *name;
17710 static pos_T pos;
17711 pos_T *pp;
17713 /* Argument can be [lnum, col, coladd]. */
17714 if (varp->v_type == VAR_LIST)
17716 list_T *l;
17717 int len;
17718 int error = FALSE;
17719 listitem_T *li;
17721 l = varp->vval.v_list;
17722 if (l == NULL)
17723 return NULL;
17725 /* Get the line number */
17726 pos.lnum = list_find_nr(l, 0L, &error);
17727 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
17728 return NULL; /* invalid line number */
17730 /* Get the column number */
17731 pos.col = list_find_nr(l, 1L, &error);
17732 if (error)
17733 return NULL;
17734 len = (long)STRLEN(ml_get(pos.lnum));
17736 /* We accept "$" for the column number: last column. */
17737 li = list_find(l, 1L);
17738 if (li != NULL && li->li_tv.v_type == VAR_STRING
17739 && li->li_tv.vval.v_string != NULL
17740 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
17741 pos.col = len + 1;
17743 /* Accept a position up to the NUL after the line. */
17744 if (pos.col == 0 || (int)pos.col > len + 1)
17745 return NULL; /* invalid column number */
17746 --pos.col;
17748 #ifdef FEAT_VIRTUALEDIT
17749 /* Get the virtual offset. Defaults to zero. */
17750 pos.coladd = list_find_nr(l, 2L, &error);
17751 if (error)
17752 pos.coladd = 0;
17753 #endif
17755 return &pos;
17758 name = get_tv_string_chk(varp);
17759 if (name == NULL)
17760 return NULL;
17761 if (name[0] == '.') /* cursor */
17762 return &curwin->w_cursor;
17763 #ifdef FEAT_VISUAL
17764 if (name[0] == 'v' && name[1] == NUL) /* Visual start */
17766 if (VIsual_active)
17767 return &VIsual;
17768 return &curwin->w_cursor;
17770 #endif
17771 if (name[0] == '\'') /* mark */
17773 pp = getmark_fnum(name[1], FALSE, fnum);
17774 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
17775 return NULL;
17776 return pp;
17779 #ifdef FEAT_VIRTUALEDIT
17780 pos.coladd = 0;
17781 #endif
17783 if (name[0] == 'w' && dollar_lnum)
17785 pos.col = 0;
17786 if (name[1] == '0') /* "w0": first visible line */
17788 update_topline();
17789 pos.lnum = curwin->w_topline;
17790 return &pos;
17792 else if (name[1] == '$') /* "w$": last visible line */
17794 validate_botline();
17795 pos.lnum = curwin->w_botline - 1;
17796 return &pos;
17799 else if (name[0] == '$') /* last column or line */
17801 if (dollar_lnum)
17803 pos.lnum = curbuf->b_ml.ml_line_count;
17804 pos.col = 0;
17806 else
17808 pos.lnum = curwin->w_cursor.lnum;
17809 pos.col = (colnr_T)STRLEN(ml_get_curline());
17811 return &pos;
17813 return NULL;
17817 * Convert list in "arg" into a position and optional file number.
17818 * When "fnump" is NULL there is no file number, only 3 items.
17819 * Note that the column is passed on as-is, the caller may want to decrement
17820 * it to use 1 for the first column.
17821 * Return FAIL when conversion is not possible, doesn't check the position for
17822 * validity.
17824 static int
17825 list2fpos(arg, posp, fnump)
17826 typval_T *arg;
17827 pos_T *posp;
17828 int *fnump;
17830 list_T *l = arg->vval.v_list;
17831 long i = 0;
17832 long n;
17834 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
17835 * when "fnump" isn't NULL and "coladd" is optional. */
17836 if (arg->v_type != VAR_LIST
17837 || l == NULL
17838 || l->lv_len < (fnump == NULL ? 2 : 3)
17839 || l->lv_len > (fnump == NULL ? 3 : 4))
17840 return FAIL;
17842 if (fnump != NULL)
17844 n = list_find_nr(l, i++, NULL); /* fnum */
17845 if (n < 0)
17846 return FAIL;
17847 if (n == 0)
17848 n = curbuf->b_fnum; /* current buffer */
17849 *fnump = n;
17852 n = list_find_nr(l, i++, NULL); /* lnum */
17853 if (n < 0)
17854 return FAIL;
17855 posp->lnum = n;
17857 n = list_find_nr(l, i++, NULL); /* col */
17858 if (n < 0)
17859 return FAIL;
17860 posp->col = n;
17862 #ifdef FEAT_VIRTUALEDIT
17863 n = list_find_nr(l, i, NULL);
17864 if (n < 0)
17865 posp->coladd = 0;
17866 else
17867 posp->coladd = n;
17868 #endif
17870 return OK;
17874 * Get the length of an environment variable name.
17875 * Advance "arg" to the first character after the name.
17876 * Return 0 for error.
17878 static int
17879 get_env_len(arg)
17880 char_u **arg;
17882 char_u *p;
17883 int len;
17885 for (p = *arg; vim_isIDc(*p); ++p)
17887 if (p == *arg) /* no name found */
17888 return 0;
17890 len = (int)(p - *arg);
17891 *arg = p;
17892 return len;
17896 * Get the length of the name of a function or internal variable.
17897 * "arg" is advanced to the first non-white character after the name.
17898 * Return 0 if something is wrong.
17900 static int
17901 get_id_len(arg)
17902 char_u **arg;
17904 char_u *p;
17905 int len;
17907 /* Find the end of the name. */
17908 for (p = *arg; eval_isnamec(*p); ++p)
17910 if (p == *arg) /* no name found */
17911 return 0;
17913 len = (int)(p - *arg);
17914 *arg = skipwhite(p);
17916 return len;
17920 * Get the length of the name of a variable or function.
17921 * Only the name is recognized, does not handle ".key" or "[idx]".
17922 * "arg" is advanced to the first non-white character after the name.
17923 * Return -1 if curly braces expansion failed.
17924 * Return 0 if something else is wrong.
17925 * If the name contains 'magic' {}'s, expand them and return the
17926 * expanded name in an allocated string via 'alias' - caller must free.
17928 static int
17929 get_name_len(arg, alias, evaluate, verbose)
17930 char_u **arg;
17931 char_u **alias;
17932 int evaluate;
17933 int verbose;
17935 int len;
17936 char_u *p;
17937 char_u *expr_start;
17938 char_u *expr_end;
17940 *alias = NULL; /* default to no alias */
17942 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
17943 && (*arg)[2] == (int)KE_SNR)
17945 /* hard coded <SNR>, already translated */
17946 *arg += 3;
17947 return get_id_len(arg) + 3;
17949 len = eval_fname_script(*arg);
17950 if (len > 0)
17952 /* literal "<SID>", "s:" or "<SNR>" */
17953 *arg += len;
17957 * Find the end of the name; check for {} construction.
17959 p = find_name_end(*arg, &expr_start, &expr_end,
17960 len > 0 ? 0 : FNE_CHECK_START);
17961 if (expr_start != NULL)
17963 char_u *temp_string;
17965 if (!evaluate)
17967 len += (int)(p - *arg);
17968 *arg = skipwhite(p);
17969 return len;
17973 * Include any <SID> etc in the expanded string:
17974 * Thus the -len here.
17976 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
17977 if (temp_string == NULL)
17978 return -1;
17979 *alias = temp_string;
17980 *arg = skipwhite(p);
17981 return (int)STRLEN(temp_string);
17984 len += get_id_len(arg);
17985 if (len == 0 && verbose)
17986 EMSG2(_(e_invexpr2), *arg);
17988 return len;
17992 * Find the end of a variable or function name, taking care of magic braces.
17993 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
17994 * start and end of the first magic braces item.
17995 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
17996 * Return a pointer to just after the name. Equal to "arg" if there is no
17997 * valid name.
17999 static char_u *
18000 find_name_end(arg, expr_start, expr_end, flags)
18001 char_u *arg;
18002 char_u **expr_start;
18003 char_u **expr_end;
18004 int flags;
18006 int mb_nest = 0;
18007 int br_nest = 0;
18008 char_u *p;
18010 if (expr_start != NULL)
18012 *expr_start = NULL;
18013 *expr_end = NULL;
18016 /* Quick check for valid starting character. */
18017 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
18018 return arg;
18020 for (p = arg; *p != NUL
18021 && (eval_isnamec(*p)
18022 || *p == '{'
18023 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
18024 || mb_nest != 0
18025 || br_nest != 0); mb_ptr_adv(p))
18027 if (*p == '\'')
18029 /* skip over 'string' to avoid counting [ and ] inside it. */
18030 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
18032 if (*p == NUL)
18033 break;
18035 else if (*p == '"')
18037 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
18038 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
18039 if (*p == '\\' && p[1] != NUL)
18040 ++p;
18041 if (*p == NUL)
18042 break;
18045 if (mb_nest == 0)
18047 if (*p == '[')
18048 ++br_nest;
18049 else if (*p == ']')
18050 --br_nest;
18053 if (br_nest == 0)
18055 if (*p == '{')
18057 mb_nest++;
18058 if (expr_start != NULL && *expr_start == NULL)
18059 *expr_start = p;
18061 else if (*p == '}')
18063 mb_nest--;
18064 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
18065 *expr_end = p;
18070 return p;
18074 * Expands out the 'magic' {}'s in a variable/function name.
18075 * Note that this can call itself recursively, to deal with
18076 * constructs like foo{bar}{baz}{bam}
18077 * The four pointer arguments point to "foo{expre}ss{ion}bar"
18078 * "in_start" ^
18079 * "expr_start" ^
18080 * "expr_end" ^
18081 * "in_end" ^
18083 * Returns a new allocated string, which the caller must free.
18084 * Returns NULL for failure.
18086 static char_u *
18087 make_expanded_name(in_start, expr_start, expr_end, in_end)
18088 char_u *in_start;
18089 char_u *expr_start;
18090 char_u *expr_end;
18091 char_u *in_end;
18093 char_u c1;
18094 char_u *retval = NULL;
18095 char_u *temp_result;
18096 char_u *nextcmd = NULL;
18098 if (expr_end == NULL || in_end == NULL)
18099 return NULL;
18100 *expr_start = NUL;
18101 *expr_end = NUL;
18102 c1 = *in_end;
18103 *in_end = NUL;
18105 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
18106 if (temp_result != NULL && nextcmd == NULL)
18108 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
18109 + (in_end - expr_end) + 1));
18110 if (retval != NULL)
18112 STRCPY(retval, in_start);
18113 STRCAT(retval, temp_result);
18114 STRCAT(retval, expr_end + 1);
18117 vim_free(temp_result);
18119 *in_end = c1; /* put char back for error messages */
18120 *expr_start = '{';
18121 *expr_end = '}';
18123 if (retval != NULL)
18125 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
18126 if (expr_start != NULL)
18128 /* Further expansion! */
18129 temp_result = make_expanded_name(retval, expr_start,
18130 expr_end, temp_result);
18131 vim_free(retval);
18132 retval = temp_result;
18136 return retval;
18140 * Return TRUE if character "c" can be used in a variable or function name.
18141 * Does not include '{' or '}' for magic braces.
18143 static int
18144 eval_isnamec(c)
18145 int c;
18147 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
18151 * Return TRUE if character "c" can be used as the first character in a
18152 * variable or function name (excluding '{' and '}').
18154 static int
18155 eval_isnamec1(c)
18156 int c;
18158 return (ASCII_ISALPHA(c) || c == '_');
18162 * Set number v: variable to "val".
18164 void
18165 set_vim_var_nr(idx, val)
18166 int idx;
18167 long val;
18169 vimvars[idx].vv_nr = val;
18173 * Get number v: variable value.
18175 long
18176 get_vim_var_nr(idx)
18177 int idx;
18179 return vimvars[idx].vv_nr;
18183 * Get string v: variable value. Uses a static buffer, can only be used once.
18185 char_u *
18186 get_vim_var_str(idx)
18187 int idx;
18189 return get_tv_string(&vimvars[idx].vv_tv);
18193 * Get List v: variable value. Caller must take care of reference count when
18194 * needed.
18196 list_T *
18197 get_vim_var_list(idx)
18198 int idx;
18200 return vimvars[idx].vv_list;
18204 * Set v:char to character "c".
18206 void
18207 set_vim_var_char(c)
18208 int c;
18210 #ifdef FEAT_MBYTE
18211 char_u buf[MB_MAXBYTES];
18212 #else
18213 char_u buf[2];
18214 #endif
18216 #ifdef FEAT_MBYTE
18217 if (has_mbyte)
18218 buf[(*mb_char2bytes)(c, buf)] = NUL;
18219 else
18220 #endif
18222 buf[0] = c;
18223 buf[1] = NUL;
18225 set_vim_var_string(VV_CHAR, buf, -1);
18229 * Set v:count to "count" and v:count1 to "count1".
18230 * When "set_prevcount" is TRUE first set v:prevcount from v:count.
18232 void
18233 set_vcount(count, count1, set_prevcount)
18234 long count;
18235 long count1;
18236 int set_prevcount;
18238 if (set_prevcount)
18239 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
18240 vimvars[VV_COUNT].vv_nr = count;
18241 vimvars[VV_COUNT1].vv_nr = count1;
18245 * Set string v: variable to a copy of "val".
18247 void
18248 set_vim_var_string(idx, val, len)
18249 int idx;
18250 char_u *val;
18251 int len; /* length of "val" to use or -1 (whole string) */
18253 /* Need to do this (at least) once, since we can't initialize a union.
18254 * Will always be invoked when "v:progname" is set. */
18255 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
18257 vim_free(vimvars[idx].vv_str);
18258 if (val == NULL)
18259 vimvars[idx].vv_str = NULL;
18260 else if (len == -1)
18261 vimvars[idx].vv_str = vim_strsave(val);
18262 else
18263 vimvars[idx].vv_str = vim_strnsave(val, len);
18267 * Set List v: variable to "val".
18269 void
18270 set_vim_var_list(idx, val)
18271 int idx;
18272 list_T *val;
18274 list_unref(vimvars[idx].vv_list);
18275 vimvars[idx].vv_list = val;
18276 if (val != NULL)
18277 ++val->lv_refcount;
18281 * Set v:register if needed.
18283 void
18284 set_reg_var(c)
18285 int c;
18287 char_u regname;
18289 if (c == 0 || c == ' ')
18290 regname = '"';
18291 else
18292 regname = c;
18293 /* Avoid free/alloc when the value is already right. */
18294 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
18295 set_vim_var_string(VV_REG, &regname, 1);
18299 * Get or set v:exception. If "oldval" == NULL, return the current value.
18300 * Otherwise, restore the value to "oldval" and return NULL.
18301 * Must always be called in pairs to save and restore v:exception! Does not
18302 * take care of memory allocations.
18304 char_u *
18305 v_exception(oldval)
18306 char_u *oldval;
18308 if (oldval == NULL)
18309 return vimvars[VV_EXCEPTION].vv_str;
18311 vimvars[VV_EXCEPTION].vv_str = oldval;
18312 return NULL;
18316 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
18317 * Otherwise, restore the value to "oldval" and return NULL.
18318 * Must always be called in pairs to save and restore v:throwpoint! Does not
18319 * take care of memory allocations.
18321 char_u *
18322 v_throwpoint(oldval)
18323 char_u *oldval;
18325 if (oldval == NULL)
18326 return vimvars[VV_THROWPOINT].vv_str;
18328 vimvars[VV_THROWPOINT].vv_str = oldval;
18329 return NULL;
18332 #if defined(FEAT_AUTOCMD) || defined(PROTO)
18334 * Set v:cmdarg.
18335 * If "eap" != NULL, use "eap" to generate the value and return the old value.
18336 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
18337 * Must always be called in pairs!
18339 char_u *
18340 set_cmdarg(eap, oldarg)
18341 exarg_T *eap;
18342 char_u *oldarg;
18344 char_u *oldval;
18345 char_u *newval;
18346 unsigned len;
18348 oldval = vimvars[VV_CMDARG].vv_str;
18349 if (eap == NULL)
18351 vim_free(oldval);
18352 vimvars[VV_CMDARG].vv_str = oldarg;
18353 return NULL;
18356 if (eap->force_bin == FORCE_BIN)
18357 len = 6;
18358 else if (eap->force_bin == FORCE_NOBIN)
18359 len = 8;
18360 else
18361 len = 0;
18363 if (eap->read_edit)
18364 len += 7;
18366 if (eap->force_ff != 0)
18367 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
18368 # ifdef FEAT_MBYTE
18369 if (eap->force_enc != 0)
18370 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
18371 if (eap->bad_char != 0)
18372 len += 7 + 4; /* " ++bad=" + "keep" or "drop" */
18373 # endif
18375 newval = alloc(len + 1);
18376 if (newval == NULL)
18377 return NULL;
18379 if (eap->force_bin == FORCE_BIN)
18380 sprintf((char *)newval, " ++bin");
18381 else if (eap->force_bin == FORCE_NOBIN)
18382 sprintf((char *)newval, " ++nobin");
18383 else
18384 *newval = NUL;
18386 if (eap->read_edit)
18387 STRCAT(newval, " ++edit");
18389 if (eap->force_ff != 0)
18390 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
18391 eap->cmd + eap->force_ff);
18392 # ifdef FEAT_MBYTE
18393 if (eap->force_enc != 0)
18394 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
18395 eap->cmd + eap->force_enc);
18396 if (eap->bad_char == BAD_KEEP)
18397 STRCPY(newval + STRLEN(newval), " ++bad=keep");
18398 else if (eap->bad_char == BAD_DROP)
18399 STRCPY(newval + STRLEN(newval), " ++bad=drop");
18400 else if (eap->bad_char != 0)
18401 sprintf((char *)newval + STRLEN(newval), " ++bad=%c", eap->bad_char);
18402 # endif
18403 vimvars[VV_CMDARG].vv_str = newval;
18404 return oldval;
18406 #endif
18409 * Get the value of internal variable "name".
18410 * Return OK or FAIL.
18412 static int
18413 get_var_tv(name, len, rettv, verbose)
18414 char_u *name;
18415 int len; /* length of "name" */
18416 typval_T *rettv; /* NULL when only checking existence */
18417 int verbose; /* may give error message */
18419 int ret = OK;
18420 typval_T *tv = NULL;
18421 typval_T atv;
18422 dictitem_T *v;
18423 int cc;
18425 /* truncate the name, so that we can use strcmp() */
18426 cc = name[len];
18427 name[len] = NUL;
18430 * Check for "b:changedtick".
18432 if (STRCMP(name, "b:changedtick") == 0)
18434 atv.v_type = VAR_NUMBER;
18435 atv.vval.v_number = curbuf->b_changedtick;
18436 tv = &atv;
18440 * Check for user-defined variables.
18442 else
18444 v = find_var(name, NULL);
18445 if (v != NULL)
18446 tv = &v->di_tv;
18449 if (tv == NULL)
18451 if (rettv != NULL && verbose)
18452 EMSG2(_(e_undefvar), name);
18453 ret = FAIL;
18455 else if (rettv != NULL)
18456 copy_tv(tv, rettv);
18458 name[len] = cc;
18460 return ret;
18464 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
18465 * Also handle function call with Funcref variable: func(expr)
18466 * Can all be combined: dict.func(expr)[idx]['func'](expr)
18468 static int
18469 handle_subscript(arg, rettv, evaluate, verbose)
18470 char_u **arg;
18471 typval_T *rettv;
18472 int evaluate; /* do more than finding the end */
18473 int verbose; /* give error messages */
18475 int ret = OK;
18476 dict_T *selfdict = NULL;
18477 char_u *s;
18478 int len;
18479 typval_T functv;
18481 while (ret == OK
18482 && (**arg == '['
18483 || (**arg == '.' && rettv->v_type == VAR_DICT)
18484 || (**arg == '(' && rettv->v_type == VAR_FUNC))
18485 && !vim_iswhite(*(*arg - 1)))
18487 if (**arg == '(')
18489 /* need to copy the funcref so that we can clear rettv */
18490 functv = *rettv;
18491 rettv->v_type = VAR_UNKNOWN;
18493 /* Invoke the function. Recursive! */
18494 s = functv.vval.v_string;
18495 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
18496 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
18497 &len, evaluate, selfdict);
18499 /* Clear the funcref afterwards, so that deleting it while
18500 * evaluating the arguments is possible (see test55). */
18501 clear_tv(&functv);
18503 /* Stop the expression evaluation when immediately aborting on
18504 * error, or when an interrupt occurred or an exception was thrown
18505 * but not caught. */
18506 if (aborting())
18508 if (ret == OK)
18509 clear_tv(rettv);
18510 ret = FAIL;
18512 dict_unref(selfdict);
18513 selfdict = NULL;
18515 else /* **arg == '[' || **arg == '.' */
18517 dict_unref(selfdict);
18518 if (rettv->v_type == VAR_DICT)
18520 selfdict = rettv->vval.v_dict;
18521 if (selfdict != NULL)
18522 ++selfdict->dv_refcount;
18524 else
18525 selfdict = NULL;
18526 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
18528 clear_tv(rettv);
18529 ret = FAIL;
18533 dict_unref(selfdict);
18534 return ret;
18538 * Allocate memory for a variable type-value, and make it empty (0 or NULL
18539 * value).
18541 static typval_T *
18542 alloc_tv()
18544 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
18548 * Allocate memory for a variable type-value, and assign a string to it.
18549 * The string "s" must have been allocated, it is consumed.
18550 * Return NULL for out of memory, the variable otherwise.
18552 static typval_T *
18553 alloc_string_tv(s)
18554 char_u *s;
18556 typval_T *rettv;
18558 rettv = alloc_tv();
18559 if (rettv != NULL)
18561 rettv->v_type = VAR_STRING;
18562 rettv->vval.v_string = s;
18564 else
18565 vim_free(s);
18566 return rettv;
18570 * Free the memory for a variable type-value.
18572 void
18573 free_tv(varp)
18574 typval_T *varp;
18576 if (varp != NULL)
18578 switch (varp->v_type)
18580 case VAR_FUNC:
18581 func_unref(varp->vval.v_string);
18582 /*FALLTHROUGH*/
18583 case VAR_STRING:
18584 vim_free(varp->vval.v_string);
18585 break;
18586 case VAR_LIST:
18587 list_unref(varp->vval.v_list);
18588 break;
18589 case VAR_DICT:
18590 dict_unref(varp->vval.v_dict);
18591 break;
18592 case VAR_NUMBER:
18593 #ifdef FEAT_FLOAT
18594 case VAR_FLOAT:
18595 #endif
18596 case VAR_UNKNOWN:
18597 break;
18598 default:
18599 EMSG2(_(e_intern2), "free_tv()");
18600 break;
18602 vim_free(varp);
18607 * Free the memory for a variable value and set the value to NULL or 0.
18609 void
18610 clear_tv(varp)
18611 typval_T *varp;
18613 if (varp != NULL)
18615 switch (varp->v_type)
18617 case VAR_FUNC:
18618 func_unref(varp->vval.v_string);
18619 /*FALLTHROUGH*/
18620 case VAR_STRING:
18621 vim_free(varp->vval.v_string);
18622 varp->vval.v_string = NULL;
18623 break;
18624 case VAR_LIST:
18625 list_unref(varp->vval.v_list);
18626 varp->vval.v_list = NULL;
18627 break;
18628 case VAR_DICT:
18629 dict_unref(varp->vval.v_dict);
18630 varp->vval.v_dict = NULL;
18631 break;
18632 case VAR_NUMBER:
18633 varp->vval.v_number = 0;
18634 break;
18635 #ifdef FEAT_FLOAT
18636 case VAR_FLOAT:
18637 varp->vval.v_float = 0.0;
18638 break;
18639 #endif
18640 case VAR_UNKNOWN:
18641 break;
18642 default:
18643 EMSG2(_(e_intern2), "clear_tv()");
18645 varp->v_lock = 0;
18650 * Set the value of a variable to NULL without freeing items.
18652 static void
18653 init_tv(varp)
18654 typval_T *varp;
18656 if (varp != NULL)
18657 vim_memset(varp, 0, sizeof(typval_T));
18661 * Get the number value of a variable.
18662 * If it is a String variable, uses vim_str2nr().
18663 * For incompatible types, return 0.
18664 * get_tv_number_chk() is similar to get_tv_number(), but informs the
18665 * caller of incompatible types: it sets *denote to TRUE if "denote"
18666 * is not NULL or returns -1 otherwise.
18668 static long
18669 get_tv_number(varp)
18670 typval_T *varp;
18672 int error = FALSE;
18674 return get_tv_number_chk(varp, &error); /* return 0L on error */
18677 long
18678 get_tv_number_chk(varp, denote)
18679 typval_T *varp;
18680 int *denote;
18682 long n = 0L;
18684 switch (varp->v_type)
18686 case VAR_NUMBER:
18687 return (long)(varp->vval.v_number);
18688 #ifdef FEAT_FLOAT
18689 case VAR_FLOAT:
18690 EMSG(_("E805: Using a Float as a Number"));
18691 break;
18692 #endif
18693 case VAR_FUNC:
18694 EMSG(_("E703: Using a Funcref as a Number"));
18695 break;
18696 case VAR_STRING:
18697 if (varp->vval.v_string != NULL)
18698 vim_str2nr(varp->vval.v_string, NULL, NULL,
18699 TRUE, TRUE, &n, NULL);
18700 return n;
18701 case VAR_LIST:
18702 EMSG(_("E745: Using a List as a Number"));
18703 break;
18704 case VAR_DICT:
18705 EMSG(_("E728: Using a Dictionary as a Number"));
18706 break;
18707 default:
18708 EMSG2(_(e_intern2), "get_tv_number()");
18709 break;
18711 if (denote == NULL) /* useful for values that must be unsigned */
18712 n = -1;
18713 else
18714 *denote = TRUE;
18715 return n;
18719 * Get the lnum from the first argument.
18720 * Also accepts ".", "$", etc., but that only works for the current buffer.
18721 * Returns -1 on error.
18723 static linenr_T
18724 get_tv_lnum(argvars)
18725 typval_T *argvars;
18727 typval_T rettv;
18728 linenr_T lnum;
18730 lnum = get_tv_number_chk(&argvars[0], NULL);
18731 if (lnum == 0) /* no valid number, try using line() */
18733 rettv.v_type = VAR_NUMBER;
18734 f_line(argvars, &rettv);
18735 lnum = rettv.vval.v_number;
18736 clear_tv(&rettv);
18738 return lnum;
18742 * Get the lnum from the first argument.
18743 * Also accepts "$", then "buf" is used.
18744 * Returns 0 on error.
18746 static linenr_T
18747 get_tv_lnum_buf(argvars, buf)
18748 typval_T *argvars;
18749 buf_T *buf;
18751 if (argvars[0].v_type == VAR_STRING
18752 && argvars[0].vval.v_string != NULL
18753 && argvars[0].vval.v_string[0] == '$'
18754 && buf != NULL)
18755 return buf->b_ml.ml_line_count;
18756 return get_tv_number_chk(&argvars[0], NULL);
18760 * Get the string value of a variable.
18761 * If it is a Number variable, the number is converted into a string.
18762 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
18763 * get_tv_string_buf() uses a given buffer.
18764 * If the String variable has never been set, return an empty string.
18765 * Never returns NULL;
18766 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
18767 * NULL on error.
18769 static char_u *
18770 get_tv_string(varp)
18771 typval_T *varp;
18773 static char_u mybuf[NUMBUFLEN];
18775 return get_tv_string_buf(varp, mybuf);
18778 static char_u *
18779 get_tv_string_buf(varp, buf)
18780 typval_T *varp;
18781 char_u *buf;
18783 char_u *res = get_tv_string_buf_chk(varp, buf);
18785 return res != NULL ? res : (char_u *)"";
18788 char_u *
18789 get_tv_string_chk(varp)
18790 typval_T *varp;
18792 static char_u mybuf[NUMBUFLEN];
18794 return get_tv_string_buf_chk(varp, mybuf);
18797 static char_u *
18798 get_tv_string_buf_chk(varp, buf)
18799 typval_T *varp;
18800 char_u *buf;
18802 switch (varp->v_type)
18804 case VAR_NUMBER:
18805 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
18806 return buf;
18807 case VAR_FUNC:
18808 EMSG(_("E729: using Funcref as a String"));
18809 break;
18810 case VAR_LIST:
18811 EMSG(_("E730: using List as a String"));
18812 break;
18813 case VAR_DICT:
18814 EMSG(_("E731: using Dictionary as a String"));
18815 break;
18816 #ifdef FEAT_FLOAT
18817 case VAR_FLOAT:
18818 EMSG(_("E806: using Float as a String"));
18819 break;
18820 #endif
18821 case VAR_STRING:
18822 if (varp->vval.v_string != NULL)
18823 return varp->vval.v_string;
18824 return (char_u *)"";
18825 default:
18826 EMSG2(_(e_intern2), "get_tv_string_buf()");
18827 break;
18829 return NULL;
18833 * Find variable "name" in the list of variables.
18834 * Return a pointer to it if found, NULL if not found.
18835 * Careful: "a:0" variables don't have a name.
18836 * When "htp" is not NULL we are writing to the variable, set "htp" to the
18837 * hashtab_T used.
18839 static dictitem_T *
18840 find_var(name, htp)
18841 char_u *name;
18842 hashtab_T **htp;
18844 char_u *varname;
18845 hashtab_T *ht;
18847 ht = find_var_ht(name, &varname);
18848 if (htp != NULL)
18849 *htp = ht;
18850 if (ht == NULL)
18851 return NULL;
18852 return find_var_in_ht(ht, varname, htp != NULL);
18856 * Find variable "varname" in hashtab "ht".
18857 * Returns NULL if not found.
18859 static dictitem_T *
18860 find_var_in_ht(ht, varname, writing)
18861 hashtab_T *ht;
18862 char_u *varname;
18863 int writing;
18865 hashitem_T *hi;
18867 if (*varname == NUL)
18869 /* Must be something like "s:", otherwise "ht" would be NULL. */
18870 switch (varname[-2])
18872 case 's': return &SCRIPT_SV(current_SID)->sv_var;
18873 case 'g': return &globvars_var;
18874 case 'v': return &vimvars_var;
18875 case 'b': return &curbuf->b_bufvar;
18876 case 'w': return &curwin->w_winvar;
18877 #ifdef FEAT_WINDOWS
18878 case 't': return &curtab->tp_winvar;
18879 #endif
18880 case 'l': return current_funccal == NULL
18881 ? NULL : &current_funccal->l_vars_var;
18882 case 'a': return current_funccal == NULL
18883 ? NULL : &current_funccal->l_avars_var;
18885 return NULL;
18888 hi = hash_find(ht, varname);
18889 if (HASHITEM_EMPTY(hi))
18891 /* For global variables we may try auto-loading the script. If it
18892 * worked find the variable again. Don't auto-load a script if it was
18893 * loaded already, otherwise it would be loaded every time when
18894 * checking if a function name is a Funcref variable. */
18895 if (ht == &globvarht && !writing
18896 && script_autoload(varname, FALSE) && !aborting())
18897 hi = hash_find(ht, varname);
18898 if (HASHITEM_EMPTY(hi))
18899 return NULL;
18901 return HI2DI(hi);
18905 * Find the hashtab used for a variable name.
18906 * Set "varname" to the start of name without ':'.
18908 static hashtab_T *
18909 find_var_ht(name, varname)
18910 char_u *name;
18911 char_u **varname;
18913 hashitem_T *hi;
18915 if (name[1] != ':')
18917 /* The name must not start with a colon or #. */
18918 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
18919 return NULL;
18920 *varname = name;
18922 /* "version" is "v:version" in all scopes */
18923 hi = hash_find(&compat_hashtab, name);
18924 if (!HASHITEM_EMPTY(hi))
18925 return &compat_hashtab;
18927 if (current_funccal == NULL)
18928 return &globvarht; /* global variable */
18929 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
18931 *varname = name + 2;
18932 if (*name == 'g') /* global variable */
18933 return &globvarht;
18934 /* There must be no ':' or '#' in the rest of the name, unless g: is used
18936 if (vim_strchr(name + 2, ':') != NULL
18937 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
18938 return NULL;
18939 if (*name == 'b') /* buffer variable */
18940 return &curbuf->b_vars.dv_hashtab;
18941 if (*name == 'w') /* window variable */
18942 return &curwin->w_vars.dv_hashtab;
18943 #ifdef FEAT_WINDOWS
18944 if (*name == 't') /* tab page variable */
18945 return &curtab->tp_vars.dv_hashtab;
18946 #endif
18947 if (*name == 'v') /* v: variable */
18948 return &vimvarht;
18949 if (*name == 'a' && current_funccal != NULL) /* function argument */
18950 return &current_funccal->l_avars.dv_hashtab;
18951 if (*name == 'l' && current_funccal != NULL) /* local function variable */
18952 return &current_funccal->l_vars.dv_hashtab;
18953 if (*name == 's' /* script variable */
18954 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
18955 return &SCRIPT_VARS(current_SID);
18956 return NULL;
18960 * Get the string value of a (global/local) variable.
18961 * Returns NULL when it doesn't exist.
18963 char_u *
18964 get_var_value(name)
18965 char_u *name;
18967 dictitem_T *v;
18969 v = find_var(name, NULL);
18970 if (v == NULL)
18971 return NULL;
18972 return get_tv_string(&v->di_tv);
18976 * Allocate a new hashtab for a sourced script. It will be used while
18977 * sourcing this script and when executing functions defined in the script.
18979 void
18980 new_script_vars(id)
18981 scid_T id;
18983 int i;
18984 hashtab_T *ht;
18985 scriptvar_T *sv;
18987 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
18989 /* Re-allocating ga_data means that an ht_array pointing to
18990 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
18991 * at its init value. Also reset "v_dict", it's always the same. */
18992 for (i = 1; i <= ga_scripts.ga_len; ++i)
18994 ht = &SCRIPT_VARS(i);
18995 if (ht->ht_mask == HT_INIT_SIZE - 1)
18996 ht->ht_array = ht->ht_smallarray;
18997 sv = SCRIPT_SV(i);
18998 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
19001 while (ga_scripts.ga_len < id)
19003 sv = SCRIPT_SV(ga_scripts.ga_len + 1) =
19004 (scriptvar_T *)alloc_clear(sizeof(scriptvar_T));
19005 init_var_dict(&sv->sv_dict, &sv->sv_var);
19006 ++ga_scripts.ga_len;
19012 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
19013 * point to it.
19015 void
19016 init_var_dict(dict, dict_var)
19017 dict_T *dict;
19018 dictitem_T *dict_var;
19020 hash_init(&dict->dv_hashtab);
19021 dict->dv_refcount = DO_NOT_FREE_CNT;
19022 dict->dv_copyID = 0;
19023 dict_var->di_tv.vval.v_dict = dict;
19024 dict_var->di_tv.v_type = VAR_DICT;
19025 dict_var->di_tv.v_lock = VAR_FIXED;
19026 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
19027 dict_var->di_key[0] = NUL;
19031 * Clean up a list of internal variables.
19032 * Frees all allocated variables and the value they contain.
19033 * Clears hashtab "ht", does not free it.
19035 void
19036 vars_clear(ht)
19037 hashtab_T *ht;
19039 vars_clear_ext(ht, TRUE);
19043 * Like vars_clear(), but only free the value if "free_val" is TRUE.
19045 static void
19046 vars_clear_ext(ht, free_val)
19047 hashtab_T *ht;
19048 int free_val;
19050 int todo;
19051 hashitem_T *hi;
19052 dictitem_T *v;
19054 hash_lock(ht);
19055 todo = (int)ht->ht_used;
19056 for (hi = ht->ht_array; todo > 0; ++hi)
19058 if (!HASHITEM_EMPTY(hi))
19060 --todo;
19062 /* Free the variable. Don't remove it from the hashtab,
19063 * ht_array might change then. hash_clear() takes care of it
19064 * later. */
19065 v = HI2DI(hi);
19066 if (free_val)
19067 clear_tv(&v->di_tv);
19068 if ((v->di_flags & DI_FLAGS_FIX) == 0)
19069 vim_free(v);
19072 hash_clear(ht);
19073 ht->ht_used = 0;
19077 * Delete a variable from hashtab "ht" at item "hi".
19078 * Clear the variable value and free the dictitem.
19080 static void
19081 delete_var(ht, hi)
19082 hashtab_T *ht;
19083 hashitem_T *hi;
19085 dictitem_T *di = HI2DI(hi);
19087 hash_remove(ht, hi);
19088 clear_tv(&di->di_tv);
19089 vim_free(di);
19093 * List the value of one internal variable.
19095 static void
19096 list_one_var(v, prefix, first)
19097 dictitem_T *v;
19098 char_u *prefix;
19099 int *first;
19101 char_u *tofree;
19102 char_u *s;
19103 char_u numbuf[NUMBUFLEN];
19105 current_copyID += COPYID_INC;
19106 s = echo_string(&v->di_tv, &tofree, numbuf, current_copyID);
19107 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
19108 s == NULL ? (char_u *)"" : s, first);
19109 vim_free(tofree);
19112 static void
19113 list_one_var_a(prefix, name, type, string, first)
19114 char_u *prefix;
19115 char_u *name;
19116 int type;
19117 char_u *string;
19118 int *first; /* when TRUE clear rest of screen and set to FALSE */
19120 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
19121 msg_start();
19122 msg_puts(prefix);
19123 if (name != NULL) /* "a:" vars don't have a name stored */
19124 msg_puts(name);
19125 msg_putchar(' ');
19126 msg_advance(22);
19127 if (type == VAR_NUMBER)
19128 msg_putchar('#');
19129 else if (type == VAR_FUNC)
19130 msg_putchar('*');
19131 else if (type == VAR_LIST)
19133 msg_putchar('[');
19134 if (*string == '[')
19135 ++string;
19137 else if (type == VAR_DICT)
19139 msg_putchar('{');
19140 if (*string == '{')
19141 ++string;
19143 else
19144 msg_putchar(' ');
19146 msg_outtrans(string);
19148 if (type == VAR_FUNC)
19149 msg_puts((char_u *)"()");
19150 if (*first)
19152 msg_clr_eos();
19153 *first = FALSE;
19158 * Set variable "name" to value in "tv".
19159 * If the variable already exists, the value is updated.
19160 * Otherwise the variable is created.
19162 static void
19163 set_var(name, tv, copy)
19164 char_u *name;
19165 typval_T *tv;
19166 int copy; /* make copy of value in "tv" */
19168 dictitem_T *v;
19169 char_u *varname;
19170 hashtab_T *ht;
19171 char_u *p;
19173 ht = find_var_ht(name, &varname);
19174 if (ht == NULL || *varname == NUL)
19176 EMSG2(_(e_illvar), name);
19177 return;
19179 v = find_var_in_ht(ht, varname, TRUE);
19181 if (tv->v_type == VAR_FUNC)
19183 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
19184 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
19185 ? name[2] : name[0]))
19187 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
19188 return;
19190 /* Don't allow hiding a function. When "v" is not NULL we migth be
19191 * assigning another function to the same var, the type is checked
19192 * below. */
19193 if (v == NULL && function_exists(name))
19195 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
19196 name);
19197 return;
19201 if (v != NULL)
19203 /* existing variable, need to clear the value */
19204 if (var_check_ro(v->di_flags, name)
19205 || tv_check_lock(v->di_tv.v_lock, name))
19206 return;
19207 if (v->di_tv.v_type != tv->v_type
19208 && !((v->di_tv.v_type == VAR_STRING
19209 || v->di_tv.v_type == VAR_NUMBER)
19210 && (tv->v_type == VAR_STRING
19211 || tv->v_type == VAR_NUMBER))
19212 #ifdef FEAT_FLOAT
19213 && !((v->di_tv.v_type == VAR_NUMBER
19214 || v->di_tv.v_type == VAR_FLOAT)
19215 && (tv->v_type == VAR_NUMBER
19216 || tv->v_type == VAR_FLOAT))
19217 #endif
19220 EMSG2(_("E706: Variable type mismatch for: %s"), name);
19221 return;
19225 * Handle setting internal v: variables separately: we don't change
19226 * the type.
19228 if (ht == &vimvarht)
19230 if (v->di_tv.v_type == VAR_STRING)
19232 vim_free(v->di_tv.vval.v_string);
19233 if (copy || tv->v_type != VAR_STRING)
19234 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
19235 else
19237 /* Take over the string to avoid an extra alloc/free. */
19238 v->di_tv.vval.v_string = tv->vval.v_string;
19239 tv->vval.v_string = NULL;
19242 else if (v->di_tv.v_type != VAR_NUMBER)
19243 EMSG2(_(e_intern2), "set_var()");
19244 else
19246 v->di_tv.vval.v_number = get_tv_number(tv);
19247 if (STRCMP(varname, "searchforward") == 0)
19248 set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
19250 return;
19253 clear_tv(&v->di_tv);
19255 else /* add a new variable */
19257 /* Can't add "v:" variable. */
19258 if (ht == &vimvarht)
19260 EMSG2(_(e_illvar), name);
19261 return;
19264 /* Make sure the variable name is valid. */
19265 for (p = varname; *p != NUL; ++p)
19266 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
19267 && *p != AUTOLOAD_CHAR)
19269 EMSG2(_(e_illvar), varname);
19270 return;
19273 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
19274 + STRLEN(varname)));
19275 if (v == NULL)
19276 return;
19277 STRCPY(v->di_key, varname);
19278 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
19280 vim_free(v);
19281 return;
19283 v->di_flags = 0;
19286 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
19287 copy_tv(tv, &v->di_tv);
19288 else
19290 v->di_tv = *tv;
19291 v->di_tv.v_lock = 0;
19292 init_tv(tv);
19297 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
19298 * Also give an error message.
19300 static int
19301 var_check_ro(flags, name)
19302 int flags;
19303 char_u *name;
19305 if (flags & DI_FLAGS_RO)
19307 EMSG2(_(e_readonlyvar), name);
19308 return TRUE;
19310 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
19312 EMSG2(_(e_readonlysbx), name);
19313 return TRUE;
19315 return FALSE;
19319 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
19320 * Also give an error message.
19322 static int
19323 var_check_fixed(flags, name)
19324 int flags;
19325 char_u *name;
19327 if (flags & DI_FLAGS_FIX)
19329 EMSG2(_("E795: Cannot delete variable %s"), name);
19330 return TRUE;
19332 return FALSE;
19336 * Return TRUE if typeval "tv" is set to be locked (immutable).
19337 * Also give an error message, using "name".
19339 static int
19340 tv_check_lock(lock, name)
19341 int lock;
19342 char_u *name;
19344 if (lock & VAR_LOCKED)
19346 EMSG2(_("E741: Value is locked: %s"),
19347 name == NULL ? (char_u *)_("Unknown") : name);
19348 return TRUE;
19350 if (lock & VAR_FIXED)
19352 EMSG2(_("E742: Cannot change value of %s"),
19353 name == NULL ? (char_u *)_("Unknown") : name);
19354 return TRUE;
19356 return FALSE;
19360 * Copy the values from typval_T "from" to typval_T "to".
19361 * When needed allocates string or increases reference count.
19362 * Does not make a copy of a list or dict but copies the reference!
19363 * It is OK for "from" and "to" to point to the same item. This is used to
19364 * make a copy later.
19366 void
19367 copy_tv(from, to)
19368 typval_T *from;
19369 typval_T *to;
19371 to->v_type = from->v_type;
19372 to->v_lock = 0;
19373 switch (from->v_type)
19375 case VAR_NUMBER:
19376 to->vval.v_number = from->vval.v_number;
19377 break;
19378 #ifdef FEAT_FLOAT
19379 case VAR_FLOAT:
19380 to->vval.v_float = from->vval.v_float;
19381 break;
19382 #endif
19383 case VAR_STRING:
19384 case VAR_FUNC:
19385 if (from->vval.v_string == NULL)
19386 to->vval.v_string = NULL;
19387 else
19389 to->vval.v_string = vim_strsave(from->vval.v_string);
19390 if (from->v_type == VAR_FUNC)
19391 func_ref(to->vval.v_string);
19393 break;
19394 case VAR_LIST:
19395 if (from->vval.v_list == NULL)
19396 to->vval.v_list = NULL;
19397 else
19399 to->vval.v_list = from->vval.v_list;
19400 ++to->vval.v_list->lv_refcount;
19402 break;
19403 case VAR_DICT:
19404 if (from->vval.v_dict == NULL)
19405 to->vval.v_dict = NULL;
19406 else
19408 to->vval.v_dict = from->vval.v_dict;
19409 ++to->vval.v_dict->dv_refcount;
19411 break;
19412 default:
19413 EMSG2(_(e_intern2), "copy_tv()");
19414 break;
19419 * Make a copy of an item.
19420 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
19421 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
19422 * reference to an already copied list/dict can be used.
19423 * Returns FAIL or OK.
19425 static int
19426 item_copy(from, to, deep, copyID)
19427 typval_T *from;
19428 typval_T *to;
19429 int deep;
19430 int copyID;
19432 static int recurse = 0;
19433 int ret = OK;
19435 if (recurse >= DICT_MAXNEST)
19437 EMSG(_("E698: variable nested too deep for making a copy"));
19438 return FAIL;
19440 ++recurse;
19442 switch (from->v_type)
19444 case VAR_NUMBER:
19445 #ifdef FEAT_FLOAT
19446 case VAR_FLOAT:
19447 #endif
19448 case VAR_STRING:
19449 case VAR_FUNC:
19450 copy_tv(from, to);
19451 break;
19452 case VAR_LIST:
19453 to->v_type = VAR_LIST;
19454 to->v_lock = 0;
19455 if (from->vval.v_list == NULL)
19456 to->vval.v_list = NULL;
19457 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
19459 /* use the copy made earlier */
19460 to->vval.v_list = from->vval.v_list->lv_copylist;
19461 ++to->vval.v_list->lv_refcount;
19463 else
19464 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
19465 if (to->vval.v_list == NULL)
19466 ret = FAIL;
19467 break;
19468 case VAR_DICT:
19469 to->v_type = VAR_DICT;
19470 to->v_lock = 0;
19471 if (from->vval.v_dict == NULL)
19472 to->vval.v_dict = NULL;
19473 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
19475 /* use the copy made earlier */
19476 to->vval.v_dict = from->vval.v_dict->dv_copydict;
19477 ++to->vval.v_dict->dv_refcount;
19479 else
19480 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
19481 if (to->vval.v_dict == NULL)
19482 ret = FAIL;
19483 break;
19484 default:
19485 EMSG2(_(e_intern2), "item_copy()");
19486 ret = FAIL;
19488 --recurse;
19489 return ret;
19493 * ":echo expr1 ..." print each argument separated with a space, add a
19494 * newline at the end.
19495 * ":echon expr1 ..." print each argument plain.
19497 void
19498 ex_echo(eap)
19499 exarg_T *eap;
19501 char_u *arg = eap->arg;
19502 typval_T rettv;
19503 char_u *tofree;
19504 char_u *p;
19505 int needclr = TRUE;
19506 int atstart = TRUE;
19507 char_u numbuf[NUMBUFLEN];
19509 if (eap->skip)
19510 ++emsg_skip;
19511 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
19513 /* If eval1() causes an error message the text from the command may
19514 * still need to be cleared. E.g., "echo 22,44". */
19515 need_clr_eos = needclr;
19517 p = arg;
19518 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19521 * Report the invalid expression unless the expression evaluation
19522 * has been cancelled due to an aborting error, an interrupt, or an
19523 * exception.
19525 if (!aborting())
19526 EMSG2(_(e_invexpr2), p);
19527 need_clr_eos = FALSE;
19528 break;
19530 need_clr_eos = FALSE;
19532 if (!eap->skip)
19534 if (atstart)
19536 atstart = FALSE;
19537 /* Call msg_start() after eval1(), evaluating the expression
19538 * may cause a message to appear. */
19539 if (eap->cmdidx == CMD_echo)
19540 msg_start();
19542 else if (eap->cmdidx == CMD_echo)
19543 msg_puts_attr((char_u *)" ", echo_attr);
19544 current_copyID += COPYID_INC;
19545 p = echo_string(&rettv, &tofree, numbuf, current_copyID);
19546 if (p != NULL)
19547 for ( ; *p != NUL && !got_int; ++p)
19549 if (*p == '\n' || *p == '\r' || *p == TAB)
19551 if (*p != TAB && needclr)
19553 /* remove any text still there from the command */
19554 msg_clr_eos();
19555 needclr = FALSE;
19557 msg_putchar_attr(*p, echo_attr);
19559 else
19561 #ifdef FEAT_MBYTE
19562 if (has_mbyte)
19564 int i = (*mb_ptr2len)(p);
19566 (void)msg_outtrans_len_attr(p, i, echo_attr);
19567 p += i - 1;
19569 else
19570 #endif
19571 (void)msg_outtrans_len_attr(p, 1, echo_attr);
19574 vim_free(tofree);
19576 clear_tv(&rettv);
19577 arg = skipwhite(arg);
19579 eap->nextcmd = check_nextcmd(arg);
19581 if (eap->skip)
19582 --emsg_skip;
19583 else
19585 /* remove text that may still be there from the command */
19586 if (needclr)
19587 msg_clr_eos();
19588 if (eap->cmdidx == CMD_echo)
19589 msg_end();
19594 * ":echohl {name}".
19596 void
19597 ex_echohl(eap)
19598 exarg_T *eap;
19600 int id;
19602 id = syn_name2id(eap->arg);
19603 if (id == 0)
19604 echo_attr = 0;
19605 else
19606 echo_attr = syn_id2attr(id);
19610 * ":execute expr1 ..." execute the result of an expression.
19611 * ":echomsg expr1 ..." Print a message
19612 * ":echoerr expr1 ..." Print an error
19613 * Each gets spaces around each argument and a newline at the end for
19614 * echo commands
19616 void
19617 ex_execute(eap)
19618 exarg_T *eap;
19620 char_u *arg = eap->arg;
19621 typval_T rettv;
19622 int ret = OK;
19623 char_u *p;
19624 garray_T ga;
19625 int len;
19626 int save_did_emsg;
19628 ga_init2(&ga, 1, 80);
19630 if (eap->skip)
19631 ++emsg_skip;
19632 while (*arg != NUL && *arg != '|' && *arg != '\n')
19634 p = arg;
19635 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19638 * Report the invalid expression unless the expression evaluation
19639 * has been cancelled due to an aborting error, an interrupt, or an
19640 * exception.
19642 if (!aborting())
19643 EMSG2(_(e_invexpr2), p);
19644 ret = FAIL;
19645 break;
19648 if (!eap->skip)
19650 p = get_tv_string(&rettv);
19651 len = (int)STRLEN(p);
19652 if (ga_grow(&ga, len + 2) == FAIL)
19654 clear_tv(&rettv);
19655 ret = FAIL;
19656 break;
19658 if (ga.ga_len)
19659 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
19660 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
19661 ga.ga_len += len;
19664 clear_tv(&rettv);
19665 arg = skipwhite(arg);
19668 if (ret != FAIL && ga.ga_data != NULL)
19670 if (eap->cmdidx == CMD_echomsg)
19672 MSG_ATTR(ga.ga_data, echo_attr);
19673 out_flush();
19675 else if (eap->cmdidx == CMD_echoerr)
19677 /* We don't want to abort following commands, restore did_emsg. */
19678 save_did_emsg = did_emsg;
19679 EMSG((char_u *)ga.ga_data);
19680 if (!force_abort)
19681 did_emsg = save_did_emsg;
19683 else if (eap->cmdidx == CMD_execute)
19684 do_cmdline((char_u *)ga.ga_data,
19685 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
19688 ga_clear(&ga);
19690 if (eap->skip)
19691 --emsg_skip;
19693 eap->nextcmd = check_nextcmd(arg);
19697 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
19698 * "arg" points to the "&" or '+' when called, to "option" when returning.
19699 * Returns NULL when no option name found. Otherwise pointer to the char
19700 * after the option name.
19702 static char_u *
19703 find_option_end(arg, opt_flags)
19704 char_u **arg;
19705 int *opt_flags;
19707 char_u *p = *arg;
19709 ++p;
19710 if (*p == 'g' && p[1] == ':')
19712 *opt_flags = OPT_GLOBAL;
19713 p += 2;
19715 else if (*p == 'l' && p[1] == ':')
19717 *opt_flags = OPT_LOCAL;
19718 p += 2;
19720 else
19721 *opt_flags = 0;
19723 if (!ASCII_ISALPHA(*p))
19724 return NULL;
19725 *arg = p;
19727 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
19728 p += 4; /* termcap option */
19729 else
19730 while (ASCII_ISALPHA(*p))
19731 ++p;
19732 return p;
19736 * ":function"
19738 void
19739 ex_function(eap)
19740 exarg_T *eap;
19742 char_u *theline;
19743 int j;
19744 int c;
19745 int saved_did_emsg;
19746 char_u *name = NULL;
19747 char_u *p;
19748 char_u *arg;
19749 char_u *line_arg = NULL;
19750 garray_T newargs;
19751 garray_T newlines;
19752 int varargs = FALSE;
19753 int mustend = FALSE;
19754 int flags = 0;
19755 ufunc_T *fp;
19756 int indent;
19757 int nesting;
19758 char_u *skip_until = NULL;
19759 dictitem_T *v;
19760 funcdict_T fudi;
19761 static int func_nr = 0; /* number for nameless function */
19762 int paren;
19763 hashtab_T *ht;
19764 int todo;
19765 hashitem_T *hi;
19766 int sourcing_lnum_off;
19769 * ":function" without argument: list functions.
19771 if (ends_excmd(*eap->arg))
19773 if (!eap->skip)
19775 todo = (int)func_hashtab.ht_used;
19776 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19778 if (!HASHITEM_EMPTY(hi))
19780 --todo;
19781 fp = HI2UF(hi);
19782 if (!isdigit(*fp->uf_name))
19783 list_func_head(fp, FALSE);
19787 eap->nextcmd = check_nextcmd(eap->arg);
19788 return;
19792 * ":function /pat": list functions matching pattern.
19794 if (*eap->arg == '/')
19796 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
19797 if (!eap->skip)
19799 regmatch_T regmatch;
19801 c = *p;
19802 *p = NUL;
19803 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
19804 *p = c;
19805 if (regmatch.regprog != NULL)
19807 regmatch.rm_ic = p_ic;
19809 todo = (int)func_hashtab.ht_used;
19810 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19812 if (!HASHITEM_EMPTY(hi))
19814 --todo;
19815 fp = HI2UF(hi);
19816 if (!isdigit(*fp->uf_name)
19817 && vim_regexec(&regmatch, fp->uf_name, 0))
19818 list_func_head(fp, FALSE);
19821 vim_free(regmatch.regprog);
19824 if (*p == '/')
19825 ++p;
19826 eap->nextcmd = check_nextcmd(p);
19827 return;
19831 * Get the function name. There are these situations:
19832 * func normal function name
19833 * "name" == func, "fudi.fd_dict" == NULL
19834 * dict.func new dictionary entry
19835 * "name" == NULL, "fudi.fd_dict" set,
19836 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
19837 * dict.func existing dict entry with a Funcref
19838 * "name" == func, "fudi.fd_dict" set,
19839 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19840 * dict.func existing dict entry that's not a Funcref
19841 * "name" == NULL, "fudi.fd_dict" set,
19842 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19844 p = eap->arg;
19845 name = trans_function_name(&p, eap->skip, 0, &fudi);
19846 paren = (vim_strchr(p, '(') != NULL);
19847 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
19850 * Return on an invalid expression in braces, unless the expression
19851 * evaluation has been cancelled due to an aborting error, an
19852 * interrupt, or an exception.
19854 if (!aborting())
19856 if (!eap->skip && fudi.fd_newkey != NULL)
19857 EMSG2(_(e_dictkey), fudi.fd_newkey);
19858 vim_free(fudi.fd_newkey);
19859 return;
19861 else
19862 eap->skip = TRUE;
19865 /* An error in a function call during evaluation of an expression in magic
19866 * braces should not cause the function not to be defined. */
19867 saved_did_emsg = did_emsg;
19868 did_emsg = FALSE;
19871 * ":function func" with only function name: list function.
19873 if (!paren)
19875 if (!ends_excmd(*skipwhite(p)))
19877 EMSG(_(e_trailing));
19878 goto ret_free;
19880 eap->nextcmd = check_nextcmd(p);
19881 if (eap->nextcmd != NULL)
19882 *p = NUL;
19883 if (!eap->skip && !got_int)
19885 fp = find_func(name);
19886 if (fp != NULL)
19888 list_func_head(fp, TRUE);
19889 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
19891 if (FUNCLINE(fp, j) == NULL)
19892 continue;
19893 msg_putchar('\n');
19894 msg_outnum((long)(j + 1));
19895 if (j < 9)
19896 msg_putchar(' ');
19897 if (j < 99)
19898 msg_putchar(' ');
19899 msg_prt_line(FUNCLINE(fp, j), FALSE);
19900 out_flush(); /* show a line at a time */
19901 ui_breakcheck();
19903 if (!got_int)
19905 msg_putchar('\n');
19906 msg_puts((char_u *)" endfunction");
19909 else
19910 emsg_funcname(N_("E123: Undefined function: %s"), name);
19912 goto ret_free;
19916 * ":function name(arg1, arg2)" Define function.
19918 p = skipwhite(p);
19919 if (*p != '(')
19921 if (!eap->skip)
19923 EMSG2(_("E124: Missing '(': %s"), eap->arg);
19924 goto ret_free;
19926 /* attempt to continue by skipping some text */
19927 if (vim_strchr(p, '(') != NULL)
19928 p = vim_strchr(p, '(');
19930 p = skipwhite(p + 1);
19932 ga_init2(&newargs, (int)sizeof(char_u *), 3);
19933 ga_init2(&newlines, (int)sizeof(char_u *), 3);
19935 if (!eap->skip)
19937 /* Check the name of the function. Unless it's a dictionary function
19938 * (that we are overwriting). */
19939 if (name != NULL)
19940 arg = name;
19941 else
19942 arg = fudi.fd_newkey;
19943 if (arg != NULL && (fudi.fd_di == NULL
19944 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
19946 if (*arg == K_SPECIAL)
19947 j = 3;
19948 else
19949 j = 0;
19950 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
19951 : eval_isnamec(arg[j])))
19952 ++j;
19953 if (arg[j] != NUL)
19954 emsg_funcname((char *)e_invarg2, arg);
19959 * Isolate the arguments: "arg1, arg2, ...)"
19961 while (*p != ')')
19963 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
19965 varargs = TRUE;
19966 p += 3;
19967 mustend = TRUE;
19969 else
19971 arg = p;
19972 while (ASCII_ISALNUM(*p) || *p == '_')
19973 ++p;
19974 if (arg == p || isdigit(*arg)
19975 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
19976 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
19978 if (!eap->skip)
19979 EMSG2(_("E125: Illegal argument: %s"), arg);
19980 break;
19982 if (ga_grow(&newargs, 1) == FAIL)
19983 goto erret;
19984 c = *p;
19985 *p = NUL;
19986 arg = vim_strsave(arg);
19987 if (arg == NULL)
19988 goto erret;
19989 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
19990 *p = c;
19991 newargs.ga_len++;
19992 if (*p == ',')
19993 ++p;
19994 else
19995 mustend = TRUE;
19997 p = skipwhite(p);
19998 if (mustend && *p != ')')
20000 if (!eap->skip)
20001 EMSG2(_(e_invarg2), eap->arg);
20002 break;
20005 ++p; /* skip the ')' */
20007 /* find extra arguments "range", "dict" and "abort" */
20008 for (;;)
20010 p = skipwhite(p);
20011 if (STRNCMP(p, "range", 5) == 0)
20013 flags |= FC_RANGE;
20014 p += 5;
20016 else if (STRNCMP(p, "dict", 4) == 0)
20018 flags |= FC_DICT;
20019 p += 4;
20021 else if (STRNCMP(p, "abort", 5) == 0)
20023 flags |= FC_ABORT;
20024 p += 5;
20026 else
20027 break;
20030 /* When there is a line break use what follows for the function body.
20031 * Makes 'exe "func Test()\n...\nendfunc"' work. */
20032 if (*p == '\n')
20033 line_arg = p + 1;
20034 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
20035 EMSG(_(e_trailing));
20038 * Read the body of the function, until ":endfunction" is found.
20040 if (KeyTyped)
20042 /* Check if the function already exists, don't let the user type the
20043 * whole function before telling him it doesn't work! For a script we
20044 * need to skip the body to be able to find what follows. */
20045 if (!eap->skip && !eap->forceit)
20047 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
20048 EMSG(_(e_funcdict));
20049 else if (name != NULL && find_func(name) != NULL)
20050 emsg_funcname(e_funcexts, name);
20053 if (!eap->skip && did_emsg)
20054 goto erret;
20056 msg_putchar('\n'); /* don't overwrite the function name */
20057 cmdline_row = msg_row;
20060 indent = 2;
20061 nesting = 0;
20062 for (;;)
20064 msg_scroll = TRUE;
20065 need_wait_return = FALSE;
20066 sourcing_lnum_off = sourcing_lnum;
20068 if (line_arg != NULL)
20070 /* Use eap->arg, split up in parts by line breaks. */
20071 theline = line_arg;
20072 p = vim_strchr(theline, '\n');
20073 if (p == NULL)
20074 line_arg += STRLEN(line_arg);
20075 else
20077 *p = NUL;
20078 line_arg = p + 1;
20081 else if (eap->getline == NULL)
20082 theline = getcmdline(':', 0L, indent);
20083 else
20084 theline = eap->getline(':', eap->cookie, indent);
20085 if (KeyTyped)
20086 lines_left = Rows - 1;
20087 if (theline == NULL)
20089 EMSG(_("E126: Missing :endfunction"));
20090 goto erret;
20093 /* Detect line continuation: sourcing_lnum increased more than one. */
20094 if (sourcing_lnum > sourcing_lnum_off + 1)
20095 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
20096 else
20097 sourcing_lnum_off = 0;
20099 if (skip_until != NULL)
20101 /* between ":append" and "." and between ":python <<EOF" and "EOF"
20102 * don't check for ":endfunc". */
20103 if (STRCMP(theline, skip_until) == 0)
20105 vim_free(skip_until);
20106 skip_until = NULL;
20109 else
20111 /* skip ':' and blanks*/
20112 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
20115 /* Check for "endfunction". */
20116 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
20118 if (line_arg == NULL)
20119 vim_free(theline);
20120 break;
20123 /* Increase indent inside "if", "while", "for" and "try", decrease
20124 * at "end". */
20125 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
20126 indent -= 2;
20127 else if (STRNCMP(p, "if", 2) == 0
20128 || STRNCMP(p, "wh", 2) == 0
20129 || STRNCMP(p, "for", 3) == 0
20130 || STRNCMP(p, "try", 3) == 0)
20131 indent += 2;
20133 /* Check for defining a function inside this function. */
20134 if (checkforcmd(&p, "function", 2))
20136 if (*p == '!')
20137 p = skipwhite(p + 1);
20138 p += eval_fname_script(p);
20139 if (ASCII_ISALPHA(*p))
20141 vim_free(trans_function_name(&p, TRUE, 0, NULL));
20142 if (*skipwhite(p) == '(')
20144 ++nesting;
20145 indent += 2;
20150 /* Check for ":append" or ":insert". */
20151 p = skip_range(p, NULL);
20152 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
20153 || (p[0] == 'i'
20154 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
20155 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
20156 skip_until = vim_strsave((char_u *)".");
20158 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
20159 arg = skipwhite(skiptowhite(p));
20160 if (arg[0] == '<' && arg[1] =='<'
20161 && ((p[0] == 'p' && p[1] == 'y'
20162 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
20163 || (p[0] == 'p' && p[1] == 'e'
20164 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
20165 || (p[0] == 't' && p[1] == 'c'
20166 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
20167 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
20168 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
20169 || (p[0] == 'm' && p[1] == 'z'
20170 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
20173 /* ":python <<" continues until a dot, like ":append" */
20174 p = skipwhite(arg + 2);
20175 if (*p == NUL)
20176 skip_until = vim_strsave((char_u *)".");
20177 else
20178 skip_until = vim_strsave(p);
20182 /* Add the line to the function. */
20183 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
20185 if (line_arg == NULL)
20186 vim_free(theline);
20187 goto erret;
20190 /* Copy the line to newly allocated memory. get_one_sourceline()
20191 * allocates 250 bytes per line, this saves 80% on average. The cost
20192 * is an extra alloc/free. */
20193 p = vim_strsave(theline);
20194 if (p != NULL)
20196 if (line_arg == NULL)
20197 vim_free(theline);
20198 theline = p;
20201 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
20203 /* Add NULL lines for continuation lines, so that the line count is
20204 * equal to the index in the growarray. */
20205 while (sourcing_lnum_off-- > 0)
20206 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
20208 /* Check for end of eap->arg. */
20209 if (line_arg != NULL && *line_arg == NUL)
20210 line_arg = NULL;
20213 /* Don't define the function when skipping commands or when an error was
20214 * detected. */
20215 if (eap->skip || did_emsg)
20216 goto erret;
20219 * If there are no errors, add the function
20221 if (fudi.fd_dict == NULL)
20223 v = find_var(name, &ht);
20224 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
20226 emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
20227 name);
20228 goto erret;
20231 fp = find_func(name);
20232 if (fp != NULL)
20234 if (!eap->forceit)
20236 emsg_funcname(e_funcexts, name);
20237 goto erret;
20239 if (fp->uf_calls > 0)
20241 emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"),
20242 name);
20243 goto erret;
20245 /* redefine existing function */
20246 ga_clear_strings(&(fp->uf_args));
20247 ga_clear_strings(&(fp->uf_lines));
20248 vim_free(name);
20249 name = NULL;
20252 else
20254 char numbuf[20];
20256 fp = NULL;
20257 if (fudi.fd_newkey == NULL && !eap->forceit)
20259 EMSG(_(e_funcdict));
20260 goto erret;
20262 if (fudi.fd_di == NULL)
20264 /* Can't add a function to a locked dictionary */
20265 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
20266 goto erret;
20268 /* Can't change an existing function if it is locked */
20269 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
20270 goto erret;
20272 /* Give the function a sequential number. Can only be used with a
20273 * Funcref! */
20274 vim_free(name);
20275 sprintf(numbuf, "%d", ++func_nr);
20276 name = vim_strsave((char_u *)numbuf);
20277 if (name == NULL)
20278 goto erret;
20281 if (fp == NULL)
20283 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
20285 int slen, plen;
20286 char_u *scriptname;
20288 /* Check that the autoload name matches the script name. */
20289 j = FAIL;
20290 if (sourcing_name != NULL)
20292 scriptname = autoload_name(name);
20293 if (scriptname != NULL)
20295 p = vim_strchr(scriptname, '/');
20296 plen = (int)STRLEN(p);
20297 slen = (int)STRLEN(sourcing_name);
20298 if (slen > plen && fnamecmp(p,
20299 sourcing_name + slen - plen) == 0)
20300 j = OK;
20301 vim_free(scriptname);
20304 if (j == FAIL)
20306 EMSG2(_("E746: Function name does not match script file name: %s"), name);
20307 goto erret;
20311 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
20312 if (fp == NULL)
20313 goto erret;
20315 if (fudi.fd_dict != NULL)
20317 if (fudi.fd_di == NULL)
20319 /* add new dict entry */
20320 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
20321 if (fudi.fd_di == NULL)
20323 vim_free(fp);
20324 goto erret;
20326 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
20328 vim_free(fudi.fd_di);
20329 vim_free(fp);
20330 goto erret;
20333 else
20334 /* overwrite existing dict entry */
20335 clear_tv(&fudi.fd_di->di_tv);
20336 fudi.fd_di->di_tv.v_type = VAR_FUNC;
20337 fudi.fd_di->di_tv.v_lock = 0;
20338 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
20339 fp->uf_refcount = 1;
20341 /* behave like "dict" was used */
20342 flags |= FC_DICT;
20345 /* insert the new function in the function list */
20346 STRCPY(fp->uf_name, name);
20347 hash_add(&func_hashtab, UF2HIKEY(fp));
20349 fp->uf_args = newargs;
20350 fp->uf_lines = newlines;
20351 #ifdef FEAT_PROFILE
20352 fp->uf_tml_count = NULL;
20353 fp->uf_tml_total = NULL;
20354 fp->uf_tml_self = NULL;
20355 fp->uf_profiling = FALSE;
20356 if (prof_def_func())
20357 func_do_profile(fp);
20358 #endif
20359 fp->uf_varargs = varargs;
20360 fp->uf_flags = flags;
20361 fp->uf_calls = 0;
20362 fp->uf_script_ID = current_SID;
20363 goto ret_free;
20365 erret:
20366 ga_clear_strings(&newargs);
20367 ga_clear_strings(&newlines);
20368 ret_free:
20369 vim_free(skip_until);
20370 vim_free(fudi.fd_newkey);
20371 vim_free(name);
20372 did_emsg |= saved_did_emsg;
20376 * Get a function name, translating "<SID>" and "<SNR>".
20377 * Also handles a Funcref in a List or Dictionary.
20378 * Returns the function name in allocated memory, or NULL for failure.
20379 * flags:
20380 * TFN_INT: internal function name OK
20381 * TFN_QUIET: be quiet
20382 * Advances "pp" to just after the function name (if no error).
20384 static char_u *
20385 trans_function_name(pp, skip, flags, fdp)
20386 char_u **pp;
20387 int skip; /* only find the end, don't evaluate */
20388 int flags;
20389 funcdict_T *fdp; /* return: info about dictionary used */
20391 char_u *name = NULL;
20392 char_u *start;
20393 char_u *end;
20394 int lead;
20395 char_u sid_buf[20];
20396 int len;
20397 lval_T lv;
20399 if (fdp != NULL)
20400 vim_memset(fdp, 0, sizeof(funcdict_T));
20401 start = *pp;
20403 /* Check for hard coded <SNR>: already translated function ID (from a user
20404 * command). */
20405 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
20406 && (*pp)[2] == (int)KE_SNR)
20408 *pp += 3;
20409 len = get_id_len(pp) + 3;
20410 return vim_strnsave(start, len);
20413 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
20414 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
20415 lead = eval_fname_script(start);
20416 if (lead > 2)
20417 start += lead;
20419 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
20420 lead > 2 ? 0 : FNE_CHECK_START);
20421 if (end == start)
20423 if (!skip)
20424 EMSG(_("E129: Function name required"));
20425 goto theend;
20427 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
20430 * Report an invalid expression in braces, unless the expression
20431 * evaluation has been cancelled due to an aborting error, an
20432 * interrupt, or an exception.
20434 if (!aborting())
20436 if (end != NULL)
20437 EMSG2(_(e_invarg2), start);
20439 else
20440 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
20441 goto theend;
20444 if (lv.ll_tv != NULL)
20446 if (fdp != NULL)
20448 fdp->fd_dict = lv.ll_dict;
20449 fdp->fd_newkey = lv.ll_newkey;
20450 lv.ll_newkey = NULL;
20451 fdp->fd_di = lv.ll_di;
20453 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
20455 name = vim_strsave(lv.ll_tv->vval.v_string);
20456 *pp = end;
20458 else
20460 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
20461 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
20462 EMSG(_(e_funcref));
20463 else
20464 *pp = end;
20465 name = NULL;
20467 goto theend;
20470 if (lv.ll_name == NULL)
20472 /* Error found, but continue after the function name. */
20473 *pp = end;
20474 goto theend;
20477 /* Check if the name is a Funcref. If so, use the value. */
20478 if (lv.ll_exp_name != NULL)
20480 len = (int)STRLEN(lv.ll_exp_name);
20481 name = deref_func_name(lv.ll_exp_name, &len);
20482 if (name == lv.ll_exp_name)
20483 name = NULL;
20485 else
20487 len = (int)(end - *pp);
20488 name = deref_func_name(*pp, &len);
20489 if (name == *pp)
20490 name = NULL;
20492 if (name != NULL)
20494 name = vim_strsave(name);
20495 *pp = end;
20496 goto theend;
20499 if (lv.ll_exp_name != NULL)
20501 len = (int)STRLEN(lv.ll_exp_name);
20502 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
20503 && STRNCMP(lv.ll_name, "s:", 2) == 0)
20505 /* When there was "s:" already or the name expanded to get a
20506 * leading "s:" then remove it. */
20507 lv.ll_name += 2;
20508 len -= 2;
20509 lead = 2;
20512 else
20514 if (lead == 2) /* skip over "s:" */
20515 lv.ll_name += 2;
20516 len = (int)(end - lv.ll_name);
20520 * Copy the function name to allocated memory.
20521 * Accept <SID>name() inside a script, translate into <SNR>123_name().
20522 * Accept <SNR>123_name() outside a script.
20524 if (skip)
20525 lead = 0; /* do nothing */
20526 else if (lead > 0)
20528 lead = 3;
20529 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
20530 || eval_fname_sid(*pp))
20532 /* It's "s:" or "<SID>" */
20533 if (current_SID <= 0)
20535 EMSG(_(e_usingsid));
20536 goto theend;
20538 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
20539 lead += (int)STRLEN(sid_buf);
20542 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
20544 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
20545 goto theend;
20547 name = alloc((unsigned)(len + lead + 1));
20548 if (name != NULL)
20550 if (lead > 0)
20552 name[0] = K_SPECIAL;
20553 name[1] = KS_EXTRA;
20554 name[2] = (int)KE_SNR;
20555 if (lead > 3) /* If it's "<SID>" */
20556 STRCPY(name + 3, sid_buf);
20558 mch_memmove(name + lead, lv.ll_name, (size_t)len);
20559 name[len + lead] = NUL;
20561 *pp = end;
20563 theend:
20564 clear_lval(&lv);
20565 return name;
20569 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
20570 * Return 2 if "p" starts with "s:".
20571 * Return 0 otherwise.
20573 static int
20574 eval_fname_script(p)
20575 char_u *p;
20577 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
20578 || STRNICMP(p + 1, "SNR>", 4) == 0))
20579 return 5;
20580 if (p[0] == 's' && p[1] == ':')
20581 return 2;
20582 return 0;
20586 * Return TRUE if "p" starts with "<SID>" or "s:".
20587 * Only works if eval_fname_script() returned non-zero for "p"!
20589 static int
20590 eval_fname_sid(p)
20591 char_u *p;
20593 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
20597 * List the head of the function: "name(arg1, arg2)".
20599 static void
20600 list_func_head(fp, indent)
20601 ufunc_T *fp;
20602 int indent;
20604 int j;
20606 msg_start();
20607 if (indent)
20608 MSG_PUTS(" ");
20609 MSG_PUTS("function ");
20610 if (fp->uf_name[0] == K_SPECIAL)
20612 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
20613 msg_puts(fp->uf_name + 3);
20615 else
20616 msg_puts(fp->uf_name);
20617 msg_putchar('(');
20618 for (j = 0; j < fp->uf_args.ga_len; ++j)
20620 if (j)
20621 MSG_PUTS(", ");
20622 msg_puts(FUNCARG(fp, j));
20624 if (fp->uf_varargs)
20626 if (j)
20627 MSG_PUTS(", ");
20628 MSG_PUTS("...");
20630 msg_putchar(')');
20631 msg_clr_eos();
20632 if (p_verbose > 0)
20633 last_set_msg(fp->uf_script_ID);
20637 * Find a function by name, return pointer to it in ufuncs.
20638 * Return NULL for unknown function.
20640 static ufunc_T *
20641 find_func(name)
20642 char_u *name;
20644 hashitem_T *hi;
20646 hi = hash_find(&func_hashtab, name);
20647 if (!HASHITEM_EMPTY(hi))
20648 return HI2UF(hi);
20649 return NULL;
20652 #if defined(EXITFREE) || defined(PROTO)
20653 void
20654 free_all_functions()
20656 hashitem_T *hi;
20658 /* Need to start all over every time, because func_free() may change the
20659 * hash table. */
20660 while (func_hashtab.ht_used > 0)
20661 for (hi = func_hashtab.ht_array; ; ++hi)
20662 if (!HASHITEM_EMPTY(hi))
20664 func_free(HI2UF(hi));
20665 break;
20668 #endif
20671 * Return TRUE if a function "name" exists.
20673 static int
20674 function_exists(name)
20675 char_u *name;
20677 char_u *nm = name;
20678 char_u *p;
20679 int n = FALSE;
20681 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
20682 nm = skipwhite(nm);
20684 /* Only accept "funcname", "funcname ", "funcname (..." and
20685 * "funcname(...", not "funcname!...". */
20686 if (p != NULL && (*nm == NUL || *nm == '('))
20688 if (builtin_function(p))
20689 n = (find_internal_func(p) >= 0);
20690 else
20691 n = (find_func(p) != NULL);
20693 vim_free(p);
20694 return n;
20698 * Return TRUE if "name" looks like a builtin function name: starts with a
20699 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
20701 static int
20702 builtin_function(name)
20703 char_u *name;
20705 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
20706 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
20709 #if defined(FEAT_PROFILE) || defined(PROTO)
20711 * Start profiling function "fp".
20713 static void
20714 func_do_profile(fp)
20715 ufunc_T *fp;
20717 fp->uf_tm_count = 0;
20718 profile_zero(&fp->uf_tm_self);
20719 profile_zero(&fp->uf_tm_total);
20720 if (fp->uf_tml_count == NULL)
20721 fp->uf_tml_count = (int *)alloc_clear((unsigned)
20722 (sizeof(int) * fp->uf_lines.ga_len));
20723 if (fp->uf_tml_total == NULL)
20724 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
20725 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20726 if (fp->uf_tml_self == NULL)
20727 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
20728 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20729 fp->uf_tml_idx = -1;
20730 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
20731 || fp->uf_tml_self == NULL)
20732 return; /* out of memory */
20734 fp->uf_profiling = TRUE;
20738 * Dump the profiling results for all functions in file "fd".
20740 void
20741 func_dump_profile(fd)
20742 FILE *fd;
20744 hashitem_T *hi;
20745 int todo;
20746 ufunc_T *fp;
20747 int i;
20748 ufunc_T **sorttab;
20749 int st_len = 0;
20751 todo = (int)func_hashtab.ht_used;
20752 if (todo == 0)
20753 return; /* nothing to dump */
20755 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
20757 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
20759 if (!HASHITEM_EMPTY(hi))
20761 --todo;
20762 fp = HI2UF(hi);
20763 if (fp->uf_profiling)
20765 if (sorttab != NULL)
20766 sorttab[st_len++] = fp;
20768 if (fp->uf_name[0] == K_SPECIAL)
20769 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
20770 else
20771 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
20772 if (fp->uf_tm_count == 1)
20773 fprintf(fd, "Called 1 time\n");
20774 else
20775 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
20776 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
20777 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
20778 fprintf(fd, "\n");
20779 fprintf(fd, "count total (s) self (s)\n");
20781 for (i = 0; i < fp->uf_lines.ga_len; ++i)
20783 if (FUNCLINE(fp, i) == NULL)
20784 continue;
20785 prof_func_line(fd, fp->uf_tml_count[i],
20786 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
20787 fprintf(fd, "%s\n", FUNCLINE(fp, i));
20789 fprintf(fd, "\n");
20794 if (sorttab != NULL && st_len > 0)
20796 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20797 prof_total_cmp);
20798 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
20799 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20800 prof_self_cmp);
20801 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
20804 vim_free(sorttab);
20807 static void
20808 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
20809 FILE *fd;
20810 ufunc_T **sorttab;
20811 int st_len;
20812 char *title;
20813 int prefer_self; /* when equal print only self time */
20815 int i;
20816 ufunc_T *fp;
20818 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
20819 fprintf(fd, "count total (s) self (s) function\n");
20820 for (i = 0; i < 20 && i < st_len; ++i)
20822 fp = sorttab[i];
20823 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
20824 prefer_self);
20825 if (fp->uf_name[0] == K_SPECIAL)
20826 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
20827 else
20828 fprintf(fd, " %s()\n", fp->uf_name);
20830 fprintf(fd, "\n");
20834 * Print the count and times for one function or function line.
20836 static void
20837 prof_func_line(fd, count, total, self, prefer_self)
20838 FILE *fd;
20839 int count;
20840 proftime_T *total;
20841 proftime_T *self;
20842 int prefer_self; /* when equal print only self time */
20844 if (count > 0)
20846 fprintf(fd, "%5d ", count);
20847 if (prefer_self && profile_equal(total, self))
20848 fprintf(fd, " ");
20849 else
20850 fprintf(fd, "%s ", profile_msg(total));
20851 if (!prefer_self && profile_equal(total, self))
20852 fprintf(fd, " ");
20853 else
20854 fprintf(fd, "%s ", profile_msg(self));
20856 else
20857 fprintf(fd, " ");
20861 * Compare function for total time sorting.
20863 static int
20864 #ifdef __BORLANDC__
20865 _RTLENTRYF
20866 #endif
20867 prof_total_cmp(s1, s2)
20868 const void *s1;
20869 const void *s2;
20871 ufunc_T *p1, *p2;
20873 p1 = *(ufunc_T **)s1;
20874 p2 = *(ufunc_T **)s2;
20875 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
20879 * Compare function for self time sorting.
20881 static int
20882 #ifdef __BORLANDC__
20883 _RTLENTRYF
20884 #endif
20885 prof_self_cmp(s1, s2)
20886 const void *s1;
20887 const void *s2;
20889 ufunc_T *p1, *p2;
20891 p1 = *(ufunc_T **)s1;
20892 p2 = *(ufunc_T **)s2;
20893 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
20896 #endif
20899 * If "name" has a package name try autoloading the script for it.
20900 * Return TRUE if a package was loaded.
20902 static int
20903 script_autoload(name, reload)
20904 char_u *name;
20905 int reload; /* load script again when already loaded */
20907 char_u *p;
20908 char_u *scriptname, *tofree;
20909 int ret = FALSE;
20910 int i;
20912 /* If there is no '#' after name[0] there is no package name. */
20913 p = vim_strchr(name, AUTOLOAD_CHAR);
20914 if (p == NULL || p == name)
20915 return FALSE;
20917 tofree = scriptname = autoload_name(name);
20919 /* Find the name in the list of previously loaded package names. Skip
20920 * "autoload/", it's always the same. */
20921 for (i = 0; i < ga_loaded.ga_len; ++i)
20922 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
20923 break;
20924 if (!reload && i < ga_loaded.ga_len)
20925 ret = FALSE; /* was loaded already */
20926 else
20928 /* Remember the name if it wasn't loaded already. */
20929 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
20931 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
20932 tofree = NULL;
20935 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
20936 if (source_runtime(scriptname, FALSE) == OK)
20937 ret = TRUE;
20940 vim_free(tofree);
20941 return ret;
20945 * Return the autoload script name for a function or variable name.
20946 * Returns NULL when out of memory.
20948 static char_u *
20949 autoload_name(name)
20950 char_u *name;
20952 char_u *p;
20953 char_u *scriptname;
20955 /* Get the script file name: replace '#' with '/', append ".vim". */
20956 scriptname = alloc((unsigned)(STRLEN(name) + 14));
20957 if (scriptname == NULL)
20958 return FALSE;
20959 STRCPY(scriptname, "autoload/");
20960 STRCAT(scriptname, name);
20961 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
20962 STRCAT(scriptname, ".vim");
20963 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
20964 *p = '/';
20965 return scriptname;
20968 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
20971 * Function given to ExpandGeneric() to obtain the list of user defined
20972 * function names.
20974 char_u *
20975 get_user_func_name(xp, idx)
20976 expand_T *xp;
20977 int idx;
20979 static long_u done;
20980 static hashitem_T *hi;
20981 ufunc_T *fp;
20983 if (idx == 0)
20985 done = 0;
20986 hi = func_hashtab.ht_array;
20988 if (done < func_hashtab.ht_used)
20990 if (done++ > 0)
20991 ++hi;
20992 while (HASHITEM_EMPTY(hi))
20993 ++hi;
20994 fp = HI2UF(hi);
20996 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
20997 return fp->uf_name; /* prevents overflow */
20999 cat_func_name(IObuff, fp);
21000 if (xp->xp_context != EXPAND_USER_FUNC)
21002 STRCAT(IObuff, "(");
21003 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
21004 STRCAT(IObuff, ")");
21006 return IObuff;
21008 return NULL;
21011 #endif /* FEAT_CMDL_COMPL */
21014 * Copy the function name of "fp" to buffer "buf".
21015 * "buf" must be able to hold the function name plus three bytes.
21016 * Takes care of script-local function names.
21018 static void
21019 cat_func_name(buf, fp)
21020 char_u *buf;
21021 ufunc_T *fp;
21023 if (fp->uf_name[0] == K_SPECIAL)
21025 STRCPY(buf, "<SNR>");
21026 STRCAT(buf, fp->uf_name + 3);
21028 else
21029 STRCPY(buf, fp->uf_name);
21033 * ":delfunction {name}"
21035 void
21036 ex_delfunction(eap)
21037 exarg_T *eap;
21039 ufunc_T *fp = NULL;
21040 char_u *p;
21041 char_u *name;
21042 funcdict_T fudi;
21044 p = eap->arg;
21045 name = trans_function_name(&p, eap->skip, 0, &fudi);
21046 vim_free(fudi.fd_newkey);
21047 if (name == NULL)
21049 if (fudi.fd_dict != NULL && !eap->skip)
21050 EMSG(_(e_funcref));
21051 return;
21053 if (!ends_excmd(*skipwhite(p)))
21055 vim_free(name);
21056 EMSG(_(e_trailing));
21057 return;
21059 eap->nextcmd = check_nextcmd(p);
21060 if (eap->nextcmd != NULL)
21061 *p = NUL;
21063 if (!eap->skip)
21064 fp = find_func(name);
21065 vim_free(name);
21067 if (!eap->skip)
21069 if (fp == NULL)
21071 EMSG2(_(e_nofunc), eap->arg);
21072 return;
21074 if (fp->uf_calls > 0)
21076 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
21077 return;
21080 if (fudi.fd_dict != NULL)
21082 /* Delete the dict item that refers to the function, it will
21083 * invoke func_unref() and possibly delete the function. */
21084 dictitem_remove(fudi.fd_dict, fudi.fd_di);
21086 else
21087 func_free(fp);
21092 * Free a function and remove it from the list of functions.
21094 static void
21095 func_free(fp)
21096 ufunc_T *fp;
21098 hashitem_T *hi;
21100 /* clear this function */
21101 ga_clear_strings(&(fp->uf_args));
21102 ga_clear_strings(&(fp->uf_lines));
21103 #ifdef FEAT_PROFILE
21104 vim_free(fp->uf_tml_count);
21105 vim_free(fp->uf_tml_total);
21106 vim_free(fp->uf_tml_self);
21107 #endif
21109 /* remove the function from the function hashtable */
21110 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
21111 if (HASHITEM_EMPTY(hi))
21112 EMSG2(_(e_intern2), "func_free()");
21113 else
21114 hash_remove(&func_hashtab, hi);
21116 vim_free(fp);
21120 * Unreference a Function: decrement the reference count and free it when it
21121 * becomes zero. Only for numbered functions.
21123 static void
21124 func_unref(name)
21125 char_u *name;
21127 ufunc_T *fp;
21129 if (name != NULL && isdigit(*name))
21131 fp = find_func(name);
21132 if (fp == NULL)
21133 EMSG2(_(e_intern2), "func_unref()");
21134 else if (--fp->uf_refcount <= 0)
21136 /* Only delete it when it's not being used. Otherwise it's done
21137 * when "uf_calls" becomes zero. */
21138 if (fp->uf_calls == 0)
21139 func_free(fp);
21145 * Count a reference to a Function.
21147 static void
21148 func_ref(name)
21149 char_u *name;
21151 ufunc_T *fp;
21153 if (name != NULL && isdigit(*name))
21155 fp = find_func(name);
21156 if (fp == NULL)
21157 EMSG2(_(e_intern2), "func_ref()");
21158 else
21159 ++fp->uf_refcount;
21164 * Call a user function.
21166 static void
21167 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
21168 ufunc_T *fp; /* pointer to function */
21169 int argcount; /* nr of args */
21170 typval_T *argvars; /* arguments */
21171 typval_T *rettv; /* return value */
21172 linenr_T firstline; /* first line of range */
21173 linenr_T lastline; /* last line of range */
21174 dict_T *selfdict; /* Dictionary for "self" */
21176 char_u *save_sourcing_name;
21177 linenr_T save_sourcing_lnum;
21178 scid_T save_current_SID;
21179 funccall_T *fc;
21180 int save_did_emsg;
21181 static int depth = 0;
21182 dictitem_T *v;
21183 int fixvar_idx = 0; /* index in fixvar[] */
21184 int i;
21185 int ai;
21186 char_u numbuf[NUMBUFLEN];
21187 char_u *name;
21188 #ifdef FEAT_PROFILE
21189 proftime_T wait_start;
21190 proftime_T call_start;
21191 #endif
21193 /* If depth of calling is getting too high, don't execute the function */
21194 if (depth >= p_mfd)
21196 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
21197 rettv->v_type = VAR_NUMBER;
21198 rettv->vval.v_number = -1;
21199 return;
21201 ++depth;
21203 line_breakcheck(); /* check for CTRL-C hit */
21205 fc = (funccall_T *)alloc(sizeof(funccall_T));
21206 fc->caller = current_funccal;
21207 current_funccal = fc;
21208 fc->func = fp;
21209 fc->rettv = rettv;
21210 rettv->vval.v_number = 0;
21211 fc->linenr = 0;
21212 fc->returned = FALSE;
21213 fc->level = ex_nesting_level;
21214 /* Check if this function has a breakpoint. */
21215 fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
21216 fc->dbg_tick = debug_tick;
21219 * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables
21220 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
21221 * each argument variable and saves a lot of time.
21224 * Init l: variables.
21226 init_var_dict(&fc->l_vars, &fc->l_vars_var);
21227 if (selfdict != NULL)
21229 /* Set l:self to "selfdict". Use "name" to avoid a warning from
21230 * some compiler that checks the destination size. */
21231 v = &fc->fixvar[fixvar_idx++].var;
21232 name = v->di_key;
21233 STRCPY(name, "self");
21234 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
21235 hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
21236 v->di_tv.v_type = VAR_DICT;
21237 v->di_tv.v_lock = 0;
21238 v->di_tv.vval.v_dict = selfdict;
21239 ++selfdict->dv_refcount;
21243 * Init a: variables.
21244 * Set a:0 to "argcount".
21245 * Set a:000 to a list with room for the "..." arguments.
21247 init_var_dict(&fc->l_avars, &fc->l_avars_var);
21248 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0",
21249 (varnumber_T)(argcount - fp->uf_args.ga_len));
21250 /* Use "name" to avoid a warning from some compiler that checks the
21251 * destination size. */
21252 v = &fc->fixvar[fixvar_idx++].var;
21253 name = v->di_key;
21254 STRCPY(name, "000");
21255 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21256 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21257 v->di_tv.v_type = VAR_LIST;
21258 v->di_tv.v_lock = VAR_FIXED;
21259 v->di_tv.vval.v_list = &fc->l_varlist;
21260 vim_memset(&fc->l_varlist, 0, sizeof(list_T));
21261 fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT;
21262 fc->l_varlist.lv_lock = VAR_FIXED;
21265 * Set a:firstline to "firstline" and a:lastline to "lastline".
21266 * Set a:name to named arguments.
21267 * Set a:N to the "..." arguments.
21269 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline",
21270 (varnumber_T)firstline);
21271 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline",
21272 (varnumber_T)lastline);
21273 for (i = 0; i < argcount; ++i)
21275 ai = i - fp->uf_args.ga_len;
21276 if (ai < 0)
21277 /* named argument a:name */
21278 name = FUNCARG(fp, i);
21279 else
21281 /* "..." argument a:1, a:2, etc. */
21282 sprintf((char *)numbuf, "%d", ai + 1);
21283 name = numbuf;
21285 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
21287 v = &fc->fixvar[fixvar_idx++].var;
21288 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21290 else
21292 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
21293 + STRLEN(name)));
21294 if (v == NULL)
21295 break;
21296 v->di_flags = DI_FLAGS_RO;
21298 STRCPY(v->di_key, name);
21299 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21301 /* Note: the values are copied directly to avoid alloc/free.
21302 * "argvars" must have VAR_FIXED for v_lock. */
21303 v->di_tv = argvars[i];
21304 v->di_tv.v_lock = VAR_FIXED;
21306 if (ai >= 0 && ai < MAX_FUNC_ARGS)
21308 list_append(&fc->l_varlist, &fc->l_listitems[ai]);
21309 fc->l_listitems[ai].li_tv = argvars[i];
21310 fc->l_listitems[ai].li_tv.v_lock = VAR_FIXED;
21314 /* Don't redraw while executing the function. */
21315 ++RedrawingDisabled;
21316 save_sourcing_name = sourcing_name;
21317 save_sourcing_lnum = sourcing_lnum;
21318 sourcing_lnum = 1;
21319 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
21320 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
21321 if (sourcing_name != NULL)
21323 if (save_sourcing_name != NULL
21324 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
21325 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
21326 else
21327 STRCPY(sourcing_name, "function ");
21328 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
21330 if (p_verbose >= 12)
21332 ++no_wait_return;
21333 verbose_enter_scroll();
21335 smsg((char_u *)_("calling %s"), sourcing_name);
21336 if (p_verbose >= 14)
21338 char_u buf[MSG_BUF_LEN];
21339 char_u numbuf2[NUMBUFLEN];
21340 char_u *tofree;
21341 char_u *s;
21343 msg_puts((char_u *)"(");
21344 for (i = 0; i < argcount; ++i)
21346 if (i > 0)
21347 msg_puts((char_u *)", ");
21348 if (argvars[i].v_type == VAR_NUMBER)
21349 msg_outnum((long)argvars[i].vval.v_number);
21350 else
21352 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
21353 if (s != NULL)
21355 trunc_string(s, buf, MSG_BUF_CLEN);
21356 msg_puts(buf);
21357 vim_free(tofree);
21361 msg_puts((char_u *)")");
21363 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21365 verbose_leave_scroll();
21366 --no_wait_return;
21369 #ifdef FEAT_PROFILE
21370 if (do_profiling == PROF_YES)
21372 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
21373 func_do_profile(fp);
21374 if (fp->uf_profiling
21375 || (fc->caller != NULL && fc->caller->func->uf_profiling))
21377 ++fp->uf_tm_count;
21378 profile_start(&call_start);
21379 profile_zero(&fp->uf_tm_children);
21381 script_prof_save(&wait_start);
21383 #endif
21385 save_current_SID = current_SID;
21386 current_SID = fp->uf_script_ID;
21387 save_did_emsg = did_emsg;
21388 did_emsg = FALSE;
21390 /* call do_cmdline() to execute the lines */
21391 do_cmdline(NULL, get_func_line, (void *)fc,
21392 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
21394 --RedrawingDisabled;
21396 /* when the function was aborted because of an error, return -1 */
21397 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
21399 clear_tv(rettv);
21400 rettv->v_type = VAR_NUMBER;
21401 rettv->vval.v_number = -1;
21404 #ifdef FEAT_PROFILE
21405 if (do_profiling == PROF_YES && (fp->uf_profiling
21406 || (fc->caller != NULL && fc->caller->func->uf_profiling)))
21408 profile_end(&call_start);
21409 profile_sub_wait(&wait_start, &call_start);
21410 profile_add(&fp->uf_tm_total, &call_start);
21411 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
21412 if (fc->caller != NULL && fc->caller->func->uf_profiling)
21414 profile_add(&fc->caller->func->uf_tm_children, &call_start);
21415 profile_add(&fc->caller->func->uf_tml_children, &call_start);
21418 #endif
21420 /* when being verbose, mention the return value */
21421 if (p_verbose >= 12)
21423 ++no_wait_return;
21424 verbose_enter_scroll();
21426 if (aborting())
21427 smsg((char_u *)_("%s aborted"), sourcing_name);
21428 else if (fc->rettv->v_type == VAR_NUMBER)
21429 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
21430 (long)fc->rettv->vval.v_number);
21431 else
21433 char_u buf[MSG_BUF_LEN];
21434 char_u numbuf2[NUMBUFLEN];
21435 char_u *tofree;
21436 char_u *s;
21438 /* The value may be very long. Skip the middle part, so that we
21439 * have some idea how it starts and ends. smsg() would always
21440 * truncate it at the end. */
21441 s = tv2string(fc->rettv, &tofree, numbuf2, 0);
21442 if (s != NULL)
21444 trunc_string(s, buf, MSG_BUF_CLEN);
21445 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
21446 vim_free(tofree);
21449 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21451 verbose_leave_scroll();
21452 --no_wait_return;
21455 vim_free(sourcing_name);
21456 sourcing_name = save_sourcing_name;
21457 sourcing_lnum = save_sourcing_lnum;
21458 current_SID = save_current_SID;
21459 #ifdef FEAT_PROFILE
21460 if (do_profiling == PROF_YES)
21461 script_prof_restore(&wait_start);
21462 #endif
21464 if (p_verbose >= 12 && sourcing_name != NULL)
21466 ++no_wait_return;
21467 verbose_enter_scroll();
21469 smsg((char_u *)_("continuing in %s"), sourcing_name);
21470 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21472 verbose_leave_scroll();
21473 --no_wait_return;
21476 did_emsg |= save_did_emsg;
21477 current_funccal = fc->caller;
21478 --depth;
21480 /* If the a:000 list and the l: and a: dicts are not referenced we can
21481 * free the funccall_T and what's in it. */
21482 if (fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
21483 && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
21484 && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT)
21486 free_funccal(fc, FALSE);
21488 else
21490 hashitem_T *hi;
21491 listitem_T *li;
21492 int todo;
21494 /* "fc" is still in use. This can happen when returning "a:000" or
21495 * assigning "l:" to a global variable.
21496 * Link "fc" in the list for garbage collection later. */
21497 fc->caller = previous_funccal;
21498 previous_funccal = fc;
21500 /* Make a copy of the a: variables, since we didn't do that above. */
21501 todo = (int)fc->l_avars.dv_hashtab.ht_used;
21502 for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi)
21504 if (!HASHITEM_EMPTY(hi))
21506 --todo;
21507 v = HI2DI(hi);
21508 copy_tv(&v->di_tv, &v->di_tv);
21512 /* Make a copy of the a:000 items, since we didn't do that above. */
21513 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21514 copy_tv(&li->li_tv, &li->li_tv);
21519 * Return TRUE if items in "fc" do not have "copyID". That means they are not
21520 * referenced from anywhere that is in use.
21522 static int
21523 can_free_funccal(fc, copyID)
21524 funccall_T *fc;
21525 int copyID;
21527 return (fc->l_varlist.lv_copyID != copyID
21528 && fc->l_vars.dv_copyID != copyID
21529 && fc->l_avars.dv_copyID != copyID);
21533 * Free "fc" and what it contains.
21535 static void
21536 free_funccal(fc, free_val)
21537 funccall_T *fc;
21538 int free_val; /* a: vars were allocated */
21540 listitem_T *li;
21542 /* The a: variables typevals may not have been allocated, only free the
21543 * allocated variables. */
21544 vars_clear_ext(&fc->l_avars.dv_hashtab, free_val);
21546 /* free all l: variables */
21547 vars_clear(&fc->l_vars.dv_hashtab);
21549 /* Free the a:000 variables if they were allocated. */
21550 if (free_val)
21551 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21552 clear_tv(&li->li_tv);
21554 vim_free(fc);
21558 * Add a number variable "name" to dict "dp" with value "nr".
21560 static void
21561 add_nr_var(dp, v, name, nr)
21562 dict_T *dp;
21563 dictitem_T *v;
21564 char *name;
21565 varnumber_T nr;
21567 STRCPY(v->di_key, name);
21568 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21569 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
21570 v->di_tv.v_type = VAR_NUMBER;
21571 v->di_tv.v_lock = VAR_FIXED;
21572 v->di_tv.vval.v_number = nr;
21576 * ":return [expr]"
21578 void
21579 ex_return(eap)
21580 exarg_T *eap;
21582 char_u *arg = eap->arg;
21583 typval_T rettv;
21584 int returning = FALSE;
21586 if (current_funccal == NULL)
21588 EMSG(_("E133: :return not inside a function"));
21589 return;
21592 if (eap->skip)
21593 ++emsg_skip;
21595 eap->nextcmd = NULL;
21596 if ((*arg != NUL && *arg != '|' && *arg != '\n')
21597 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
21599 if (!eap->skip)
21600 returning = do_return(eap, FALSE, TRUE, &rettv);
21601 else
21602 clear_tv(&rettv);
21604 /* It's safer to return also on error. */
21605 else if (!eap->skip)
21608 * Return unless the expression evaluation has been cancelled due to an
21609 * aborting error, an interrupt, or an exception.
21611 if (!aborting())
21612 returning = do_return(eap, FALSE, TRUE, NULL);
21615 /* When skipping or the return gets pending, advance to the next command
21616 * in this line (!returning). Otherwise, ignore the rest of the line.
21617 * Following lines will be ignored by get_func_line(). */
21618 if (returning)
21619 eap->nextcmd = NULL;
21620 else if (eap->nextcmd == NULL) /* no argument */
21621 eap->nextcmd = check_nextcmd(arg);
21623 if (eap->skip)
21624 --emsg_skip;
21628 * Return from a function. Possibly makes the return pending. Also called
21629 * for a pending return at the ":endtry" or after returning from an extra
21630 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
21631 * when called due to a ":return" command. "rettv" may point to a typval_T
21632 * with the return rettv. Returns TRUE when the return can be carried out,
21633 * FALSE when the return gets pending.
21636 do_return(eap, reanimate, is_cmd, rettv)
21637 exarg_T *eap;
21638 int reanimate;
21639 int is_cmd;
21640 void *rettv;
21642 int idx;
21643 struct condstack *cstack = eap->cstack;
21645 if (reanimate)
21646 /* Undo the return. */
21647 current_funccal->returned = FALSE;
21650 * Cleanup (and inactivate) conditionals, but stop when a try conditional
21651 * not in its finally clause (which then is to be executed next) is found.
21652 * In this case, make the ":return" pending for execution at the ":endtry".
21653 * Otherwise, return normally.
21655 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
21656 if (idx >= 0)
21658 cstack->cs_pending[idx] = CSTP_RETURN;
21660 if (!is_cmd && !reanimate)
21661 /* A pending return again gets pending. "rettv" points to an
21662 * allocated variable with the rettv of the original ":return"'s
21663 * argument if present or is NULL else. */
21664 cstack->cs_rettv[idx] = rettv;
21665 else
21667 /* When undoing a return in order to make it pending, get the stored
21668 * return rettv. */
21669 if (reanimate)
21670 rettv = current_funccal->rettv;
21672 if (rettv != NULL)
21674 /* Store the value of the pending return. */
21675 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
21676 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
21677 else
21678 EMSG(_(e_outofmem));
21680 else
21681 cstack->cs_rettv[idx] = NULL;
21683 if (reanimate)
21685 /* The pending return value could be overwritten by a ":return"
21686 * without argument in a finally clause; reset the default
21687 * return value. */
21688 current_funccal->rettv->v_type = VAR_NUMBER;
21689 current_funccal->rettv->vval.v_number = 0;
21692 report_make_pending(CSTP_RETURN, rettv);
21694 else
21696 current_funccal->returned = TRUE;
21698 /* If the return is carried out now, store the return value. For
21699 * a return immediately after reanimation, the value is already
21700 * there. */
21701 if (!reanimate && rettv != NULL)
21703 clear_tv(current_funccal->rettv);
21704 *current_funccal->rettv = *(typval_T *)rettv;
21705 if (!is_cmd)
21706 vim_free(rettv);
21710 return idx < 0;
21714 * Free the variable with a pending return value.
21716 void
21717 discard_pending_return(rettv)
21718 void *rettv;
21720 free_tv((typval_T *)rettv);
21724 * Generate a return command for producing the value of "rettv". The result
21725 * is an allocated string. Used by report_pending() for verbose messages.
21727 char_u *
21728 get_return_cmd(rettv)
21729 void *rettv;
21731 char_u *s = NULL;
21732 char_u *tofree = NULL;
21733 char_u numbuf[NUMBUFLEN];
21735 if (rettv != NULL)
21736 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
21737 if (s == NULL)
21738 s = (char_u *)"";
21740 STRCPY(IObuff, ":return ");
21741 STRNCPY(IObuff + 8, s, IOSIZE - 8);
21742 if (STRLEN(s) + 8 >= IOSIZE)
21743 STRCPY(IObuff + IOSIZE - 4, "...");
21744 vim_free(tofree);
21745 return vim_strsave(IObuff);
21749 * Get next function line.
21750 * Called by do_cmdline() to get the next line.
21751 * Returns allocated string, or NULL for end of function.
21753 char_u *
21754 get_func_line(c, cookie, indent)
21755 int c UNUSED;
21756 void *cookie;
21757 int indent UNUSED;
21759 funccall_T *fcp = (funccall_T *)cookie;
21760 ufunc_T *fp = fcp->func;
21761 char_u *retval;
21762 garray_T *gap; /* growarray with function lines */
21764 /* If breakpoints have been added/deleted need to check for it. */
21765 if (fcp->dbg_tick != debug_tick)
21767 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21768 sourcing_lnum);
21769 fcp->dbg_tick = debug_tick;
21771 #ifdef FEAT_PROFILE
21772 if (do_profiling == PROF_YES)
21773 func_line_end(cookie);
21774 #endif
21776 gap = &fp->uf_lines;
21777 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21778 || fcp->returned)
21779 retval = NULL;
21780 else
21782 /* Skip NULL lines (continuation lines). */
21783 while (fcp->linenr < gap->ga_len
21784 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
21785 ++fcp->linenr;
21786 if (fcp->linenr >= gap->ga_len)
21787 retval = NULL;
21788 else
21790 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
21791 sourcing_lnum = fcp->linenr;
21792 #ifdef FEAT_PROFILE
21793 if (do_profiling == PROF_YES)
21794 func_line_start(cookie);
21795 #endif
21799 /* Did we encounter a breakpoint? */
21800 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
21802 dbg_breakpoint(fp->uf_name, sourcing_lnum);
21803 /* Find next breakpoint. */
21804 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21805 sourcing_lnum);
21806 fcp->dbg_tick = debug_tick;
21809 return retval;
21812 #if defined(FEAT_PROFILE) || defined(PROTO)
21814 * Called when starting to read a function line.
21815 * "sourcing_lnum" must be correct!
21816 * When skipping lines it may not actually be executed, but we won't find out
21817 * until later and we need to store the time now.
21819 void
21820 func_line_start(cookie)
21821 void *cookie;
21823 funccall_T *fcp = (funccall_T *)cookie;
21824 ufunc_T *fp = fcp->func;
21826 if (fp->uf_profiling && sourcing_lnum >= 1
21827 && sourcing_lnum <= fp->uf_lines.ga_len)
21829 fp->uf_tml_idx = sourcing_lnum - 1;
21830 /* Skip continuation lines. */
21831 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
21832 --fp->uf_tml_idx;
21833 fp->uf_tml_execed = FALSE;
21834 profile_start(&fp->uf_tml_start);
21835 profile_zero(&fp->uf_tml_children);
21836 profile_get_wait(&fp->uf_tml_wait);
21841 * Called when actually executing a function line.
21843 void
21844 func_line_exec(cookie)
21845 void *cookie;
21847 funccall_T *fcp = (funccall_T *)cookie;
21848 ufunc_T *fp = fcp->func;
21850 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21851 fp->uf_tml_execed = TRUE;
21855 * Called when done with a function line.
21857 void
21858 func_line_end(cookie)
21859 void *cookie;
21861 funccall_T *fcp = (funccall_T *)cookie;
21862 ufunc_T *fp = fcp->func;
21864 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21866 if (fp->uf_tml_execed)
21868 ++fp->uf_tml_count[fp->uf_tml_idx];
21869 profile_end(&fp->uf_tml_start);
21870 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
21871 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
21872 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
21873 &fp->uf_tml_children);
21875 fp->uf_tml_idx = -1;
21878 #endif
21881 * Return TRUE if the currently active function should be ended, because a
21882 * return was encountered or an error occurred. Used inside a ":while".
21885 func_has_ended(cookie)
21886 void *cookie;
21888 funccall_T *fcp = (funccall_T *)cookie;
21890 /* Ignore the "abort" flag if the abortion behavior has been changed due to
21891 * an error inside a try conditional. */
21892 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21893 || fcp->returned);
21897 * return TRUE if cookie indicates a function which "abort"s on errors.
21900 func_has_abort(cookie)
21901 void *cookie;
21903 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
21906 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
21907 typedef enum
21909 VAR_FLAVOUR_DEFAULT, /* doesn't start with uppercase */
21910 VAR_FLAVOUR_SESSION, /* starts with uppercase, some lower */
21911 VAR_FLAVOUR_VIMINFO /* all uppercase */
21912 } var_flavour_T;
21914 static var_flavour_T var_flavour __ARGS((char_u *varname));
21916 static var_flavour_T
21917 var_flavour(varname)
21918 char_u *varname;
21920 char_u *p = varname;
21922 if (ASCII_ISUPPER(*p))
21924 while (*(++p))
21925 if (ASCII_ISLOWER(*p))
21926 return VAR_FLAVOUR_SESSION;
21927 return VAR_FLAVOUR_VIMINFO;
21929 else
21930 return VAR_FLAVOUR_DEFAULT;
21932 #endif
21934 #if defined(FEAT_VIMINFO) || defined(PROTO)
21936 * Restore global vars that start with a capital from the viminfo file
21939 read_viminfo_varlist(virp, writing)
21940 vir_T *virp;
21941 int writing;
21943 char_u *tab;
21944 int type = VAR_NUMBER;
21945 typval_T tv;
21947 if (!writing && (find_viminfo_parameter('!') != NULL))
21949 tab = vim_strchr(virp->vir_line + 1, '\t');
21950 if (tab != NULL)
21952 *tab++ = '\0'; /* isolate the variable name */
21953 if (*tab == 'S') /* string var */
21954 type = VAR_STRING;
21955 #ifdef FEAT_FLOAT
21956 else if (*tab == 'F')
21957 type = VAR_FLOAT;
21958 #endif
21960 tab = vim_strchr(tab, '\t');
21961 if (tab != NULL)
21963 tv.v_type = type;
21964 if (type == VAR_STRING)
21965 tv.vval.v_string = viminfo_readstring(virp,
21966 (int)(tab - virp->vir_line + 1), TRUE);
21967 #ifdef FEAT_FLOAT
21968 else if (type == VAR_FLOAT)
21969 (void)string2float(tab + 1, &tv.vval.v_float);
21970 #endif
21971 else
21972 tv.vval.v_number = atol((char *)tab + 1);
21973 set_var(virp->vir_line + 1, &tv, FALSE);
21974 if (type == VAR_STRING)
21975 vim_free(tv.vval.v_string);
21980 return viminfo_readline(virp);
21984 * Write global vars that start with a capital to the viminfo file
21986 void
21987 write_viminfo_varlist(fp)
21988 FILE *fp;
21990 hashitem_T *hi;
21991 dictitem_T *this_var;
21992 int todo;
21993 char *s;
21994 char_u *p;
21995 char_u *tofree;
21996 char_u numbuf[NUMBUFLEN];
21998 if (find_viminfo_parameter('!') == NULL)
21999 return;
22001 fputs(_("\n# global variables:\n"), fp);
22003 todo = (int)globvarht.ht_used;
22004 for (hi = globvarht.ht_array; todo > 0; ++hi)
22006 if (!HASHITEM_EMPTY(hi))
22008 --todo;
22009 this_var = HI2DI(hi);
22010 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
22012 switch (this_var->di_tv.v_type)
22014 case VAR_STRING: s = "STR"; break;
22015 case VAR_NUMBER: s = "NUM"; break;
22016 #ifdef FEAT_FLOAT
22017 case VAR_FLOAT: s = "FLO"; break;
22018 #endif
22019 default: continue;
22021 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
22022 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
22023 if (p != NULL)
22024 viminfo_writestring(fp, p);
22025 vim_free(tofree);
22030 #endif
22032 #if defined(FEAT_SESSION) || defined(PROTO)
22034 store_session_globals(fd)
22035 FILE *fd;
22037 hashitem_T *hi;
22038 dictitem_T *this_var;
22039 int todo;
22040 char_u *p, *t;
22042 todo = (int)globvarht.ht_used;
22043 for (hi = globvarht.ht_array; todo > 0; ++hi)
22045 if (!HASHITEM_EMPTY(hi))
22047 --todo;
22048 this_var = HI2DI(hi);
22049 if ((this_var->di_tv.v_type == VAR_NUMBER
22050 || this_var->di_tv.v_type == VAR_STRING)
22051 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22053 /* Escape special characters with a backslash. Turn a LF and
22054 * CR into \n and \r. */
22055 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
22056 (char_u *)"\\\"\n\r");
22057 if (p == NULL) /* out of memory */
22058 break;
22059 for (t = p; *t != NUL; ++t)
22060 if (*t == '\n')
22061 *t = 'n';
22062 else if (*t == '\r')
22063 *t = 'r';
22064 if ((fprintf(fd, "let %s = %c%s%c",
22065 this_var->di_key,
22066 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22067 : ' ',
22069 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22070 : ' ') < 0)
22071 || put_eol(fd) == FAIL)
22073 vim_free(p);
22074 return FAIL;
22076 vim_free(p);
22078 #ifdef FEAT_FLOAT
22079 else if (this_var->di_tv.v_type == VAR_FLOAT
22080 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22082 float_T f = this_var->di_tv.vval.v_float;
22083 int sign = ' ';
22085 if (f < 0)
22087 f = -f;
22088 sign = '-';
22090 if ((fprintf(fd, "let %s = %c&%f",
22091 this_var->di_key, sign, f) < 0)
22092 || put_eol(fd) == FAIL)
22093 return FAIL;
22095 #endif
22098 return OK;
22100 #endif
22103 * Display script name where an item was last set.
22104 * Should only be invoked when 'verbose' is non-zero.
22106 void
22107 last_set_msg(scriptID)
22108 scid_T scriptID;
22110 char_u *p;
22112 if (scriptID != 0)
22114 p = home_replace_save(NULL, get_scriptname(scriptID));
22115 if (p != NULL)
22117 verbose_enter();
22118 MSG_PUTS(_("\n\tLast set from "));
22119 MSG_PUTS(p);
22120 vim_free(p);
22121 verbose_leave();
22127 * List v:oldfiles in a nice way.
22129 void
22130 ex_oldfiles(eap)
22131 exarg_T *eap UNUSED;
22133 list_T *l = vimvars[VV_OLDFILES].vv_list;
22134 listitem_T *li;
22135 int nr = 0;
22137 if (l == NULL)
22138 msg((char_u *)_("No old files"));
22139 else
22141 msg_start();
22142 msg_scroll = TRUE;
22143 for (li = l->lv_first; li != NULL && !got_int; li = li->li_next)
22145 msg_outnum((long)++nr);
22146 MSG_PUTS(": ");
22147 msg_outtrans(get_tv_string(&li->li_tv));
22148 msg_putchar('\n');
22149 out_flush(); /* output one line at a time */
22150 ui_breakcheck();
22152 /* Assume "got_int" was set to truncate the listing. */
22153 got_int = FALSE;
22155 #ifdef FEAT_BROWSE_CMD
22156 if (cmdmod.browse)
22158 quit_more = FALSE;
22159 nr = prompt_for_number(FALSE);
22160 msg_starthere();
22161 if (nr > 0)
22163 char_u *p = list_find_str(get_vim_var_list(VV_OLDFILES),
22164 (long)nr);
22166 if (p != NULL)
22168 p = expand_env_save(p);
22169 eap->arg = p;
22170 eap->cmdidx = CMD_edit;
22171 cmdmod.browse = FALSE;
22172 do_exedit(eap, NULL);
22173 vim_free(p);
22177 #endif
22181 #endif /* FEAT_EVAL */
22184 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
22186 #ifdef WIN3264
22188 * Functions for ":8" filename modifier: get 8.3 version of a filename.
22190 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22191 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
22192 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22195 * Get the short path (8.3) for the filename in "fnamep".
22196 * Only works for a valid file name.
22197 * When the path gets longer "fnamep" is changed and the allocated buffer
22198 * is put in "bufp".
22199 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
22200 * Returns OK on success, FAIL on failure.
22202 static int
22203 get_short_pathname(fnamep, bufp, fnamelen)
22204 char_u **fnamep;
22205 char_u **bufp;
22206 int *fnamelen;
22208 int l, len;
22209 char_u *newbuf;
22211 len = *fnamelen;
22212 l = GetShortPathName(*fnamep, *fnamep, len);
22213 if (l > len - 1)
22215 /* If that doesn't work (not enough space), then save the string
22216 * and try again with a new buffer big enough. */
22217 newbuf = vim_strnsave(*fnamep, l);
22218 if (newbuf == NULL)
22219 return FAIL;
22221 vim_free(*bufp);
22222 *fnamep = *bufp = newbuf;
22224 /* Really should always succeed, as the buffer is big enough. */
22225 l = GetShortPathName(*fnamep, *fnamep, l+1);
22228 *fnamelen = l;
22229 return OK;
22233 * Get the short path (8.3) for the filename in "fname". The converted
22234 * path is returned in "bufp".
22236 * Some of the directories specified in "fname" may not exist. This function
22237 * will shorten the existing directories at the beginning of the path and then
22238 * append the remaining non-existing path.
22240 * fname - Pointer to the filename to shorten. On return, contains the
22241 * pointer to the shortened pathname
22242 * bufp - Pointer to an allocated buffer for the filename.
22243 * fnamelen - Length of the filename pointed to by fname
22245 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
22247 static int
22248 shortpath_for_invalid_fname(fname, bufp, fnamelen)
22249 char_u **fname;
22250 char_u **bufp;
22251 int *fnamelen;
22253 char_u *short_fname, *save_fname, *pbuf_unused;
22254 char_u *endp, *save_endp;
22255 char_u ch;
22256 int old_len, len;
22257 int new_len, sfx_len;
22258 int retval = OK;
22260 /* Make a copy */
22261 old_len = *fnamelen;
22262 save_fname = vim_strnsave(*fname, old_len);
22263 pbuf_unused = NULL;
22264 short_fname = NULL;
22266 endp = save_fname + old_len - 1; /* Find the end of the copy */
22267 save_endp = endp;
22270 * Try shortening the supplied path till it succeeds by removing one
22271 * directory at a time from the tail of the path.
22273 len = 0;
22274 for (;;)
22276 /* go back one path-separator */
22277 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
22278 --endp;
22279 if (endp <= save_fname)
22280 break; /* processed the complete path */
22283 * Replace the path separator with a NUL and try to shorten the
22284 * resulting path.
22286 ch = *endp;
22287 *endp = 0;
22288 short_fname = save_fname;
22289 len = (int)STRLEN(short_fname) + 1;
22290 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
22292 retval = FAIL;
22293 goto theend;
22295 *endp = ch; /* preserve the string */
22297 if (len > 0)
22298 break; /* successfully shortened the path */
22300 /* failed to shorten the path. Skip the path separator */
22301 --endp;
22304 if (len > 0)
22307 * Succeeded in shortening the path. Now concatenate the shortened
22308 * path with the remaining path at the tail.
22311 /* Compute the length of the new path. */
22312 sfx_len = (int)(save_endp - endp) + 1;
22313 new_len = len + sfx_len;
22315 *fnamelen = new_len;
22316 vim_free(*bufp);
22317 if (new_len > old_len)
22319 /* There is not enough space in the currently allocated string,
22320 * copy it to a buffer big enough. */
22321 *fname = *bufp = vim_strnsave(short_fname, new_len);
22322 if (*fname == NULL)
22324 retval = FAIL;
22325 goto theend;
22328 else
22330 /* Transfer short_fname to the main buffer (it's big enough),
22331 * unless get_short_pathname() did its work in-place. */
22332 *fname = *bufp = save_fname;
22333 if (short_fname != save_fname)
22334 vim_strncpy(save_fname, short_fname, len);
22335 save_fname = NULL;
22338 /* concat the not-shortened part of the path */
22339 vim_strncpy(*fname + len, endp, sfx_len);
22340 (*fname)[new_len] = NUL;
22343 theend:
22344 vim_free(pbuf_unused);
22345 vim_free(save_fname);
22347 return retval;
22351 * Get a pathname for a partial path.
22352 * Returns OK for success, FAIL for failure.
22354 static int
22355 shortpath_for_partial(fnamep, bufp, fnamelen)
22356 char_u **fnamep;
22357 char_u **bufp;
22358 int *fnamelen;
22360 int sepcount, len, tflen;
22361 char_u *p;
22362 char_u *pbuf, *tfname;
22363 int hasTilde;
22365 /* Count up the path separators from the RHS.. so we know which part
22366 * of the path to return. */
22367 sepcount = 0;
22368 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
22369 if (vim_ispathsep(*p))
22370 ++sepcount;
22372 /* Need full path first (use expand_env() to remove a "~/") */
22373 hasTilde = (**fnamep == '~');
22374 if (hasTilde)
22375 pbuf = tfname = expand_env_save(*fnamep);
22376 else
22377 pbuf = tfname = FullName_save(*fnamep, FALSE);
22379 len = tflen = (int)STRLEN(tfname);
22381 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
22382 return FAIL;
22384 if (len == 0)
22386 /* Don't have a valid filename, so shorten the rest of the
22387 * path if we can. This CAN give us invalid 8.3 filenames, but
22388 * there's not a lot of point in guessing what it might be.
22390 len = tflen;
22391 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
22392 return FAIL;
22395 /* Count the paths backward to find the beginning of the desired string. */
22396 for (p = tfname + len - 1; p >= tfname; --p)
22398 #ifdef FEAT_MBYTE
22399 if (has_mbyte)
22400 p -= mb_head_off(tfname, p);
22401 #endif
22402 if (vim_ispathsep(*p))
22404 if (sepcount == 0 || (hasTilde && sepcount == 1))
22405 break;
22406 else
22407 sepcount --;
22410 if (hasTilde)
22412 --p;
22413 if (p >= tfname)
22414 *p = '~';
22415 else
22416 return FAIL;
22418 else
22419 ++p;
22421 /* Copy in the string - p indexes into tfname - allocated at pbuf */
22422 vim_free(*bufp);
22423 *fnamelen = (int)STRLEN(p);
22424 *bufp = pbuf;
22425 *fnamep = p;
22427 return OK;
22429 #endif /* WIN3264 */
22432 * Adjust a filename, according to a string of modifiers.
22433 * *fnamep must be NUL terminated when called. When returning, the length is
22434 * determined by *fnamelen.
22435 * Returns VALID_ flags or -1 for failure.
22436 * When there is an error, *fnamep is set to NULL.
22439 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
22440 char_u *src; /* string with modifiers */
22441 int *usedlen; /* characters after src that are used */
22442 char_u **fnamep; /* file name so far */
22443 char_u **bufp; /* buffer for allocated file name or NULL */
22444 int *fnamelen; /* length of fnamep */
22446 int valid = 0;
22447 char_u *tail;
22448 char_u *s, *p, *pbuf;
22449 char_u dirname[MAXPATHL];
22450 int c;
22451 int has_fullname = 0;
22452 #ifdef WIN3264
22453 int has_shortname = 0;
22454 #endif
22456 repeat:
22457 /* ":p" - full path/file_name */
22458 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
22460 has_fullname = 1;
22462 valid |= VALID_PATH;
22463 *usedlen += 2;
22465 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
22466 if ((*fnamep)[0] == '~'
22467 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
22468 && ((*fnamep)[1] == '/'
22469 # ifdef BACKSLASH_IN_FILENAME
22470 || (*fnamep)[1] == '\\'
22471 # endif
22472 || (*fnamep)[1] == NUL)
22474 #endif
22477 *fnamep = expand_env_save(*fnamep);
22478 vim_free(*bufp); /* free any allocated file name */
22479 *bufp = *fnamep;
22480 if (*fnamep == NULL)
22481 return -1;
22484 /* When "/." or "/.." is used: force expansion to get rid of it. */
22485 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
22487 if (vim_ispathsep(*p)
22488 && p[1] == '.'
22489 && (p[2] == NUL
22490 || vim_ispathsep(p[2])
22491 || (p[2] == '.'
22492 && (p[3] == NUL || vim_ispathsep(p[3])))))
22493 break;
22496 /* FullName_save() is slow, don't use it when not needed. */
22497 if (*p != NUL || !vim_isAbsName(*fnamep))
22499 *fnamep = FullName_save(*fnamep, *p != NUL);
22500 vim_free(*bufp); /* free any allocated file name */
22501 *bufp = *fnamep;
22502 if (*fnamep == NULL)
22503 return -1;
22506 /* Append a path separator to a directory. */
22507 if (mch_isdir(*fnamep))
22509 /* Make room for one or two extra characters. */
22510 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
22511 vim_free(*bufp); /* free any allocated file name */
22512 *bufp = *fnamep;
22513 if (*fnamep == NULL)
22514 return -1;
22515 add_pathsep(*fnamep);
22519 /* ":." - path relative to the current directory */
22520 /* ":~" - path relative to the home directory */
22521 /* ":8" - shortname path - postponed till after */
22522 while (src[*usedlen] == ':'
22523 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
22525 *usedlen += 2;
22526 if (c == '8')
22528 #ifdef WIN3264
22529 has_shortname = 1; /* Postpone this. */
22530 #endif
22531 continue;
22533 pbuf = NULL;
22534 /* Need full path first (use expand_env() to remove a "~/") */
22535 if (!has_fullname)
22537 if (c == '.' && **fnamep == '~')
22538 p = pbuf = expand_env_save(*fnamep);
22539 else
22540 p = pbuf = FullName_save(*fnamep, FALSE);
22542 else
22543 p = *fnamep;
22545 has_fullname = 0;
22547 if (p != NULL)
22549 if (c == '.')
22551 mch_dirname(dirname, MAXPATHL);
22552 s = shorten_fname(p, dirname);
22553 if (s != NULL)
22555 *fnamep = s;
22556 if (pbuf != NULL)
22558 vim_free(*bufp); /* free any allocated file name */
22559 *bufp = pbuf;
22560 pbuf = NULL;
22564 else
22566 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
22567 /* Only replace it when it starts with '~' */
22568 if (*dirname == '~')
22570 s = vim_strsave(dirname);
22571 if (s != NULL)
22573 *fnamep = s;
22574 vim_free(*bufp);
22575 *bufp = s;
22579 vim_free(pbuf);
22583 tail = gettail(*fnamep);
22584 *fnamelen = (int)STRLEN(*fnamep);
22586 /* ":h" - head, remove "/file_name", can be repeated */
22587 /* Don't remove the first "/" or "c:\" */
22588 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
22590 valid |= VALID_HEAD;
22591 *usedlen += 2;
22592 s = get_past_head(*fnamep);
22593 while (tail > s && after_pathsep(s, tail))
22594 mb_ptr_back(*fnamep, tail);
22595 *fnamelen = (int)(tail - *fnamep);
22596 #ifdef VMS
22597 if (*fnamelen > 0)
22598 *fnamelen += 1; /* the path separator is part of the path */
22599 #endif
22600 if (*fnamelen == 0)
22602 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
22603 p = vim_strsave((char_u *)".");
22604 if (p == NULL)
22605 return -1;
22606 vim_free(*bufp);
22607 *bufp = *fnamep = tail = p;
22608 *fnamelen = 1;
22610 else
22612 while (tail > s && !after_pathsep(s, tail))
22613 mb_ptr_back(*fnamep, tail);
22617 /* ":8" - shortname */
22618 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
22620 *usedlen += 2;
22621 #ifdef WIN3264
22622 has_shortname = 1;
22623 #endif
22626 #ifdef WIN3264
22627 /* Check shortname after we have done 'heads' and before we do 'tails'
22629 if (has_shortname)
22631 pbuf = NULL;
22632 /* Copy the string if it is shortened by :h */
22633 if (*fnamelen < (int)STRLEN(*fnamep))
22635 p = vim_strnsave(*fnamep, *fnamelen);
22636 if (p == 0)
22637 return -1;
22638 vim_free(*bufp);
22639 *bufp = *fnamep = p;
22642 /* Split into two implementations - makes it easier. First is where
22643 * there isn't a full name already, second is where there is.
22645 if (!has_fullname && !vim_isAbsName(*fnamep))
22647 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
22648 return -1;
22650 else
22652 int l;
22654 /* Simple case, already have the full-name
22655 * Nearly always shorter, so try first time. */
22656 l = *fnamelen;
22657 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
22658 return -1;
22660 if (l == 0)
22662 /* Couldn't find the filename.. search the paths.
22664 l = *fnamelen;
22665 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
22666 return -1;
22668 *fnamelen = l;
22671 #endif /* WIN3264 */
22673 /* ":t" - tail, just the basename */
22674 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
22676 *usedlen += 2;
22677 *fnamelen -= (int)(tail - *fnamep);
22678 *fnamep = tail;
22681 /* ":e" - extension, can be repeated */
22682 /* ":r" - root, without extension, can be repeated */
22683 while (src[*usedlen] == ':'
22684 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
22686 /* find a '.' in the tail:
22687 * - for second :e: before the current fname
22688 * - otherwise: The last '.'
22690 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
22691 s = *fnamep - 2;
22692 else
22693 s = *fnamep + *fnamelen - 1;
22694 for ( ; s > tail; --s)
22695 if (s[0] == '.')
22696 break;
22697 if (src[*usedlen + 1] == 'e') /* :e */
22699 if (s > tail)
22701 *fnamelen += (int)(*fnamep - (s + 1));
22702 *fnamep = s + 1;
22703 #ifdef VMS
22704 /* cut version from the extension */
22705 s = *fnamep + *fnamelen - 1;
22706 for ( ; s > *fnamep; --s)
22707 if (s[0] == ';')
22708 break;
22709 if (s > *fnamep)
22710 *fnamelen = s - *fnamep;
22711 #endif
22713 else if (*fnamep <= tail)
22714 *fnamelen = 0;
22716 else /* :r */
22718 if (s > tail) /* remove one extension */
22719 *fnamelen = (int)(s - *fnamep);
22721 *usedlen += 2;
22724 /* ":s?pat?foo?" - substitute */
22725 /* ":gs?pat?foo?" - global substitute */
22726 if (src[*usedlen] == ':'
22727 && (src[*usedlen + 1] == 's'
22728 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
22730 char_u *str;
22731 char_u *pat;
22732 char_u *sub;
22733 int sep;
22734 char_u *flags;
22735 int didit = FALSE;
22737 flags = (char_u *)"";
22738 s = src + *usedlen + 2;
22739 if (src[*usedlen + 1] == 'g')
22741 flags = (char_u *)"g";
22742 ++s;
22745 sep = *s++;
22746 if (sep)
22748 /* find end of pattern */
22749 p = vim_strchr(s, sep);
22750 if (p != NULL)
22752 pat = vim_strnsave(s, (int)(p - s));
22753 if (pat != NULL)
22755 s = p + 1;
22756 /* find end of substitution */
22757 p = vim_strchr(s, sep);
22758 if (p != NULL)
22760 sub = vim_strnsave(s, (int)(p - s));
22761 str = vim_strnsave(*fnamep, *fnamelen);
22762 if (sub != NULL && str != NULL)
22764 *usedlen = (int)(p + 1 - src);
22765 s = do_string_sub(str, pat, sub, flags);
22766 if (s != NULL)
22768 *fnamep = s;
22769 *fnamelen = (int)STRLEN(s);
22770 vim_free(*bufp);
22771 *bufp = s;
22772 didit = TRUE;
22775 vim_free(sub);
22776 vim_free(str);
22778 vim_free(pat);
22781 /* after using ":s", repeat all the modifiers */
22782 if (didit)
22783 goto repeat;
22787 return valid;
22791 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
22792 * "flags" can be "g" to do a global substitute.
22793 * Returns an allocated string, NULL for error.
22795 char_u *
22796 do_string_sub(str, pat, sub, flags)
22797 char_u *str;
22798 char_u *pat;
22799 char_u *sub;
22800 char_u *flags;
22802 int sublen;
22803 regmatch_T regmatch;
22804 int i;
22805 int do_all;
22806 char_u *tail;
22807 garray_T ga;
22808 char_u *ret;
22809 char_u *save_cpo;
22811 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
22812 save_cpo = p_cpo;
22813 p_cpo = empty_option;
22815 ga_init2(&ga, 1, 200);
22817 do_all = (flags[0] == 'g');
22819 regmatch.rm_ic = p_ic;
22820 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
22821 if (regmatch.regprog != NULL)
22823 tail = str;
22824 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
22827 * Get some space for a temporary buffer to do the substitution
22828 * into. It will contain:
22829 * - The text up to where the match is.
22830 * - The substituted text.
22831 * - The text after the match.
22833 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
22834 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
22835 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
22837 ga_clear(&ga);
22838 break;
22841 /* copy the text up to where the match is */
22842 i = (int)(regmatch.startp[0] - tail);
22843 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
22844 /* add the substituted text */
22845 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
22846 + ga.ga_len + i, TRUE, TRUE, FALSE);
22847 ga.ga_len += i + sublen - 1;
22848 /* avoid getting stuck on a match with an empty string */
22849 if (tail == regmatch.endp[0])
22851 if (*tail == NUL)
22852 break;
22853 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
22854 ++ga.ga_len;
22856 else
22858 tail = regmatch.endp[0];
22859 if (*tail == NUL)
22860 break;
22862 if (!do_all)
22863 break;
22866 if (ga.ga_data != NULL)
22867 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
22869 vim_free(regmatch.regprog);
22872 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
22873 ga_clear(&ga);
22874 if (p_cpo == empty_option)
22875 p_cpo = save_cpo;
22876 else
22877 /* Darn, evaluating {sub} expression changed the value. */
22878 free_string_option(save_cpo);
22880 return ret;
22883 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */